It is time. Remove all of ui/views, ui/aura/, ui/compositor, ui/ozone, and a whole bunch of dead code. This is part one of multiple patches. This removes the toplevel directories, and some utility files. Further patches will deep dive to do surgery on the build system, the resource bundles, et cetera. BUG=443439 R=sky@chromium.org Review URL: https://codereview.chromium.org/851853002
diff --git a/base/BUILD.gn b/base/BUILD.gn index 59c55b8..cb914be 100644 --- a/base/BUILD.gn +++ b/base/BUILD.gn
@@ -1406,7 +1406,7 @@ configs += [ "//build/config/linux:glib" ] } - if (!is_linux || use_ozone) { + if (!is_linux) { sources -= [ "message_loop/message_pump_glib_unittest.cc" ] }
diff --git a/base/base.gyp b/base/base.gyp index 5d26fc4..4d5ac00 100644 --- a/base/base.gyp +++ b/base/base.gyp
@@ -757,11 +757,6 @@ 'message_loop/message_pump_glib_unittest.cc', ] }], - ['use_ozone == 1', { - 'sources!': [ - 'message_loop/message_pump_glib_unittest.cc', - ] - }], ['OS == "linux" and use_allocator!="none"', { 'dependencies': [ 'allocator/allocator.gyp:allocator',
diff --git a/base/base.gypi b/base/base.gypi index 349308c..14a632d 100644 --- a/base/base.gypi +++ b/base/base.gypi
@@ -941,11 +941,6 @@ 'strings/string16.cc', ], },], - ['<(use_ozone) == 1', { - 'sources!': [ - 'message_loop/message_pump_glib.cc', - ] - }], ['OS == "linux" and >(nacl_untrusted_build)==0', { 'sources!': [ 'files/file_path_watcher_fsevents.cc',
diff --git a/build/all.gyp b/build/all.gyp index 226eada..aa57010 100644 --- a/build/all.gyp +++ b/build/all.gyp
@@ -29,10 +29,8 @@ '../third_party/libxml/libxml.gyp:*', '../third_party/sqlite/sqlite.gyp:*', '../third_party/zlib/zlib.gyp:*', - '../ui/accessibility/accessibility.gyp:*', '../ui/base/ui_base.gyp:*', '../ui/display/display.gyp:display_unittests', - '../ui/snapshot/snapshot.gyp:*', '../url/url.gyp:*', ], 'conditions': [ @@ -230,17 +228,6 @@ '../third_party/libevent/libevent.gyp:*', ], }], - ['toolkit_views==1', { - 'dependencies': [ - '../ui/views/controls/webview/webview.gyp:*', - '../ui/views/views.gyp:*', - ], - }], - ['use_aura==1', { - 'dependencies': [ - '../ui/aura/aura.gyp:*', - ], - }], ['use_ash==1', { 'dependencies': [ '../ash/ash.gyp:*', @@ -450,20 +437,6 @@ '../printing/printing.gyp:printing_unittests', ], }], - ['use_aura==1', { - 'dependencies': [ - '../ui/app_list/app_list.gyp:app_list_unittests', - '../ui/aura/aura.gyp:aura_unittests', - '../ui/compositor/compositor.gyp:compositor_unittests', - '../ui/keyboard/keyboard.gyp:keyboard_unittests', - '../ui/views/views.gyp:views_unittests', - ], - }], - ['use_aura==1 or toolkit_views==1', { - 'dependencies': [ - '../ui/events/events.gyp:events_unittests', - ], - }], ['use_ash==1', { 'dependencies': [ '../ash/ash.gyp:ash_unittests', @@ -1100,7 +1073,6 @@ '../ui/events/events.gyp:events_unittests', '../ui/gfx/gfx_tests.gyp:gfx_unittests', '../ui/touch_selection/ui_touch_selection.gyp:ui_touch_selection_unittests', - '../ui/views/views.gyp:views_unittests', '../url/url.gyp:url_unittests', ], 'conditions': [ @@ -1197,10 +1169,7 @@ '../third_party/libphonenumber/libphonenumber.gyp:libphonenumber_unittests', '../third_party/WebKit/Source/platform/blink_platform_tests.gyp:blink_heap_unittests', '../third_party/WebKit/Source/platform/blink_platform_tests.gyp:blink_platform_unittests', - '../ui/accessibility/accessibility.gyp:accessibility_unittests', '../ui/app_list/app_list.gyp:app_list_unittests', - '../ui/aura/aura.gyp:aura_unittests', - '../ui/compositor/compositor.gyp:compositor_unittests', '../ui/display/display.gyp:display_unittests', '../ui/events/events.gyp:events_unittests', '../ui/gfx/gfx_tests.gyp:gfx_unittests', @@ -1247,7 +1216,6 @@ '../ui/base/ui_base_tests.gyp:ui_base_unittests', '../ui/gfx/gfx_tests.gyp:gfx_unittests', '../ui/touch_selection/ui_touch_selection.gyp:ui_touch_selection_unittests', - '../ui/views/views.gyp:views_unittests', '../url/url.gyp:url_unittests', ], 'conditions': [ @@ -1287,9 +1255,7 @@ '../remoting/remoting.gyp:remoting_unittests', '../skia/skia_tests.gyp:skia_unittests', '../ui/app_list/app_list.gyp:*', - '../ui/aura/aura.gyp:*', '../ui/base/ui_base_tests.gyp:ui_base_unittests', - '../ui/compositor/compositor.gyp:*', '../ui/display/display.gyp:display_unittests', '../ui/events/events.gyp:*', '../ui/gfx/gfx_tests.gyp:gfx_unittests', @@ -1297,10 +1263,6 @@ '../ui/message_center/message_center.gyp:*', '../ui/snapshot/snapshot.gyp:snapshot_unittests', '../ui/touch_selection/ui_touch_selection.gyp:ui_touch_selection_unittests', - '../ui/views/examples/examples.gyp:views_examples_with_content_exe', - '../ui/views/views.gyp:views', - '../ui/views/views.gyp:views_unittests', - '../ui/wm/wm.gyp:*', 'blink_tests', ], 'conditions': [ @@ -1342,12 +1304,6 @@ '../ui/chromeos/ui_chromeos.gyp:ui_chromeos_unittests', ], }], - ['use_ozone==1', { - 'dependencies': [ - '../ui/ozone/ozone.gyp:*', - '../ui/ozone/demo/ozone_demos.gyp:*', - ], - }], ], }, ], # targets @@ -1402,18 +1358,5 @@ }, # target_name: chromoting_swarm_tests ] }], - ['OS=="mac" and toolkit_views==1', { - 'targets': [ - { - 'target_name': 'macviews_builder', - 'type': 'none', - 'dependencies': [ - '../ui/views/examples/examples.gyp:views_examples_with_content_exe', - '../ui/views/views.gyp:views', - '../ui/views/views.gyp:views_unittests', - ], - }, # target_name: macviews_builder - ], # targets - }], # os=='mac' and toolkit_views==1 ], # conditions }
diff --git a/build/build_config.h b/build/build_config.h index b07660d..57d41fb 100644 --- a/build/build_config.h +++ b/build/build_config.h
@@ -48,7 +48,6 @@ #endif #elif defined(_WIN32) #define OS_WIN 1 -#define TOOLKIT_VIEWS 1 #elif defined(__FreeBSD__) #define OS_FREEBSD 1 #elif defined(__OpenBSD__)
diff --git a/build/common.gypi b/build/common.gypi index d3e39bb..5c8dc2a 100644 --- a/build/common.gypi +++ b/build/common.gypi
@@ -190,13 +190,6 @@ 'use_ash%': 0, }], - # Set default value of toolkit_views based on OS. - ['OS=="win" or chromeos==1 or use_aura==1', { - 'toolkit_views%': 1, - }, { - 'toolkit_views%': 0, - }], - # Embedded builds use aura without ash or views. ['embedded==1', { 'use_aura%': 1, @@ -2589,9 +2582,6 @@ ['component=="shared_library"', { 'defines': ['COMPONENT_BUILD'], }], - ['toolkit_views==1', { - 'defines': ['TOOLKIT_VIEWS=1'], - }], ['ui_compositor_image_transport==1', { 'defines': ['UI_COMPOSITOR_IMAGE_TRANSPORT'], }],
diff --git a/build/config/BUILD.gn b/build/config/BUILD.gn index f32797c..8cbcc7b 100644 --- a/build/config/BUILD.gn +++ b/build/config/BUILD.gn
@@ -78,9 +78,6 @@ # TODO(brettw) should probably be "=1". defines += [ "USE_UDEV" ] } - if (toolkit_views) { - defines += [ "TOOLKIT_VIEWS=1" ] - } if (ui_compositor_image_transport) { # TODO(brettw) should probably be "=1". defines += [ "UI_COMPOSITOR_IMAGE_TRANSPORT" ] @@ -117,9 +114,6 @@ # to rename this but we're hoping to transition away from NSS. defines += [ "USE_NSS=1" ] } - if (use_ozone) { - defines += [ "USE_OZONE=1" ] - } if (use_x11) { defines += [ "USE_X11=1" ] }
diff --git a/build/config/ui.gni b/build/config/ui.gni index dc7a059..7e334fd 100644 --- a/build/config/ui.gni +++ b/build/config/ui.gni
@@ -16,10 +16,6 @@ # desktop-like environment for Aura. Requires use_aura = true use_ash = is_win || is_linux - # Indicates if Ozone is enabled. Ozone is a low-level library layer for Linux - # that does not require X11. - use_ozone = false - # Support ChromeOS touchpad gestures with ozone. use_evdev_gestures = false @@ -50,11 +46,9 @@ use_default_render_theme = use_aura || is_linux # Indicates if the UI toolkit depends on X11. -use_x11 = is_linux && !use_ozone +use_x11 = is_linux -use_ozone_evdev = use_ozone - -use_glib = is_linux && !use_ozone +use_glib = is_linux use_clipboard_aurax11 = is_linux && use_aura && use_x11
diff --git a/build/filename_rules.gypi b/build/filename_rules.gypi index 1bef75f..48a8d10 100644 --- a/build/filename_rules.gypi +++ b/build/filename_rules.gypi
@@ -71,9 +71,6 @@ ['exclude', '(^|/)x/'], ], }], - ['<(toolkit_views)==0 or >(nacl_untrusted_build)==1', { - 'sources/': [ ['exclude', '_views(_browsertest|_unittest)?\\.(h|cc)$'] ] - }], ['<(use_aura)==0 or >(nacl_untrusted_build)==1', { 'sources/': [ ['exclude', '_aura(_browsertest|_unittest)?\\.(h|cc)$'], ['exclude', '(^|/)aura/'], @@ -96,21 +93,6 @@ ['<(use_ash)==0 or OS!="win" or >(nacl_untrusted_build)==1', { 'sources/': [ ['exclude', '_ashwin\\.(h|cc)$'] ] }], - ['<(use_ozone)==0 or >(nacl_untrusted_build)==1', { - 'sources/': [ ['exclude', '_ozone(_browsertest|_unittest)?\\.(h|cc)$'], - ['exclude', '(^|/)ozone/'], - ] - }], - ['<(use_ozone_evdev)==0 or >(nacl_untrusted_build)==1', { - 'sources/': [ ['exclude', '_evdev(_browsertest|_unittest)?\\.(h|cc)$'], - ['exclude', '(^|/)evdev/'], - ] - }], - ['<(ozone_platform_dri)==0 or >(nacl_untrusted_build)==1', { - 'sources/': [ ['exclude', '_dri(_browsertest|_unittest)?\\.(h|cc)$'], - ['exclude', '(^|/)dri/'], - ] - }], ['<(use_pango)==0', { 'sources/': [ ['exclude', '(^|_)pango(_util|_browsertest|_unittest)?\\.(h|cc)$'], ], }],
diff --git a/build/isolate.gypi b/build/isolate.gypi index e6d2f98..e11fc39 100644 --- a/build/isolate.gypi +++ b/build/isolate.gypi
@@ -90,7 +90,6 @@ '--config-variable', 'libpeer_target_type=<(libpeer_target_type)', '--config-variable', 'use_openssl=<(use_openssl)', '--config-variable', 'target_arch=<(target_arch)', - '--config-variable', 'use_ozone=<(use_ozone)', '--config-variable', 'disable_nacl=<(disable_nacl)', ], 'conditions': [
diff --git a/build/secondary/tools/grit/grit_rule.gni b/build/secondary/tools/grit/grit_rule.gni index 7a1cc26..228b6e3 100644 --- a/build/secondary/tools/grit/grit_rule.gni +++ b/build/secondary/tools/grit/grit_rule.gni
@@ -118,13 +118,6 @@ ] } -if (toolkit_views) { - grit_defines += [ - "-D", - "toolkit_views", - ] -} - if (use_aura) { grit_defines += [ "-D", @@ -146,13 +139,6 @@ ] } -if (use_ozone) { - grit_defines += [ - "-D", - "use_ozone", - ] -} - if (enable_image_loader_extension) { grit_defines += [ "-D",
diff --git a/examples/BUILD.gn b/examples/BUILD.gn index c737d98..c5e4f8c 100644 --- a/examples/BUILD.gn +++ b/examples/BUILD.gn
@@ -24,15 +24,12 @@ "//examples/wget", ] - if (use_aura) { - deps += [ - "//examples/aura_demo:aura_demo", - "//examples/browser", - "//examples/nesting_app", - "//examples/window_manager", - "//examples/wm_flow", - ] - } + deps += [ + "//examples/browser", + "//examples/nesting_app", + "//examples/window_manager", + "//examples/wm_flow", + ] if (!is_android) { deps += [ "//examples/pdf_viewer" ]
diff --git a/examples/aura_demo/BUILD.gn b/examples/aura_demo/BUILD.gn deleted file mode 100644 index 5a8d52f..0000000 --- a/examples/aura_demo/BUILD.gn +++ /dev/null
@@ -1,52 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import("//build/config/ui.gni") -import("//mojo/public/mojo_application.gni") - -assert(use_aura) - -mojo_native_application("aura_demo") { - sources = [ - "aura_demo.cc", - ] - - deps = [ - "//base", - "//cc", - "//ui/aura", - "//ui/base", - "//ui/compositor", - "//ui/gfx", - "//ui/gfx/geometry", - "//mojo/application", - "//mojo/common", - "//mojo/converters/geometry", - "//mojo/aura", - "//mojo/public/cpp/system", - "//mojo/services/geometry/public/interfaces", - "//mojo/services/native_viewport/public/interfaces", - "//mojo/services/view_manager/public/cpp", - ] - - datadeps = [ - ":init", - ] -} - -mojo_native_application("init") { - output_name = "aura_demo_init" - - sources = [ - "view_manager_init.cc", - ] - - deps = [ - "//base", - "//mojo/application", - "//mojo/public/interfaces/application", - "//mojo/services/view_manager/public/cpp", - "//mojo/services/view_manager/public/interfaces", - ] -}
diff --git a/examples/aura_demo/aura_demo.cc b/examples/aura_demo/aura_demo.cc deleted file mode 100644 index cfeb8a0..0000000 --- a/examples/aura_demo/aura_demo.cc +++ /dev/null
@@ -1,200 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <stdio.h> -#include <string> - -#include "base/bind.h" -#include "base/macros.h" -#include "mojo/application/application_runner_chromium.h" -#include "mojo/aura/screen_mojo.h" -#include "mojo/aura/window_tree_host_mojo.h" -#include "mojo/public/c/system/main.h" -#include "mojo/public/cpp/application/application_connection.h" -#include "mojo/public/cpp/application/application_delegate.h" -#include "mojo/public/cpp/application/application_impl.h" -#include "mojo/public/cpp/system/core.h" -#include "mojo/services/native_viewport/public/interfaces/native_viewport.mojom.h" -#include "mojo/services/view_manager/public/cpp/view.h" -#include "mojo/services/view_manager/public/cpp/view_manager.h" -#include "mojo/services/view_manager/public/cpp/view_manager_client_factory.h" -#include "mojo/services/view_manager/public/cpp/view_manager_delegate.h" -#include "ui/aura/client/default_capture_client.h" -#include "ui/aura/client/window_tree_client.h" -#include "ui/aura/env.h" -#include "ui/aura/window.h" -#include "ui/aura/window_delegate.h" -#include "ui/base/hit_test.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/codec/png_codec.h" - -namespace examples { - -// Trivial WindowDelegate implementation that draws a colored background. -class DemoWindowDelegate : public aura::WindowDelegate { - public: - explicit DemoWindowDelegate(SkColor color) : color_(color) {} - - // Overridden from WindowDelegate: - virtual gfx::Size GetMinimumSize() const override { - return gfx::Size(); - } - - virtual gfx::Size GetMaximumSize() const override { - return gfx::Size(); - } - - virtual void OnBoundsChanged(const gfx::Rect& old_bounds, - const gfx::Rect& new_bounds) override {} - virtual gfx::NativeCursor GetCursor(const gfx::Point& point) override { - return gfx::kNullCursor; - } - virtual int GetNonClientComponent(const gfx::Point& point) const override { - return HTCAPTION; - } - virtual bool ShouldDescendIntoChildForEventHandling( - aura::Window* child, - const gfx::Point& location) override { - return true; - } - virtual bool CanFocus() override { return true; } - virtual void OnCaptureLost() override {} - virtual void OnPaint(gfx::Canvas* canvas) override { - canvas->DrawColor(color_, SkXfermode::kSrc_Mode); - } - virtual void OnDeviceScaleFactorChanged(float device_scale_factor) override {} - virtual void OnWindowDestroying(aura::Window* window) override {} - virtual void OnWindowDestroyed(aura::Window* window) override {} - virtual void OnWindowTargetVisibilityChanged(bool visible) override {} - virtual bool HasHitTestMask() const override { return false; } - virtual void GetHitTestMask(gfx::Path* mask) const override {} - - private: - const SkColor color_; - - DISALLOW_COPY_AND_ASSIGN(DemoWindowDelegate); -}; - -class DemoWindowTreeClient : public aura::client::WindowTreeClient { - public: - explicit DemoWindowTreeClient(aura::Window* window) : window_(window) { - aura::client::SetWindowTreeClient(window_, this); - } - - virtual ~DemoWindowTreeClient() { - aura::client::SetWindowTreeClient(window_, NULL); - } - - // Overridden from aura::client::WindowTreeClient: - virtual aura::Window* GetDefaultParent(aura::Window* context, - aura::Window* window, - const gfx::Rect& bounds) override { - if (!capture_client_) { - capture_client_.reset( - new aura::client::DefaultCaptureClient(window_->GetRootWindow())); - } - return window_; - } - - private: - aura::Window* window_; - scoped_ptr<aura::client::DefaultCaptureClient> capture_client_; - - DISALLOW_COPY_AND_ASSIGN(DemoWindowTreeClient); -}; - -class AuraDemo : public mojo::ApplicationDelegate, - public mojo::ViewManagerDelegate { - public: - AuraDemo() - : shell_(nullptr), window1_(NULL), window2_(NULL), window21_(NULL) {} - virtual ~AuraDemo() {} - - private: - // Overridden from ViewManagerDelegate: - virtual void OnEmbed( - mojo::View* root, - mojo::ServiceProviderImpl* exported_services, - scoped_ptr<mojo::ServiceProvider> imported_services) override { - // TODO(beng): this function could be called multiple times! - root_ = root; - - window_tree_host_.reset(new mojo::WindowTreeHostMojo(shell_, root)); - window_tree_host_->InitHost(); - - window_tree_client_.reset( - new DemoWindowTreeClient(window_tree_host_->window())); - - delegate1_.reset(new DemoWindowDelegate(SK_ColorBLUE)); - window1_ = new aura::Window(delegate1_.get()); - window1_->Init(aura::WINDOW_LAYER_TEXTURED); - window1_->SetBounds(gfx::Rect(100, 100, 400, 400)); - window1_->Show(); - window_tree_host_->window()->AddChild(window1_); - - delegate2_.reset(new DemoWindowDelegate(SK_ColorRED)); - window2_ = new aura::Window(delegate2_.get()); - window2_->Init(aura::WINDOW_LAYER_TEXTURED); - window2_->SetBounds(gfx::Rect(200, 200, 350, 350)); - window2_->Show(); - window_tree_host_->window()->AddChild(window2_); - - delegate21_.reset(new DemoWindowDelegate(SK_ColorGREEN)); - window21_ = new aura::Window(delegate21_.get()); - window21_->Init(aura::WINDOW_LAYER_TEXTURED); - window21_->SetBounds(gfx::Rect(10, 10, 50, 50)); - window21_->Show(); - window2_->AddChild(window21_); - - window_tree_host_->Show(); - } - virtual void OnViewManagerDisconnected( - mojo::ViewManager* view_manager) override { - base::MessageLoop::current()->Quit(); - } - - virtual void Initialize(mojo::ApplicationImpl* app) override { - shell_ = app->shell(); - view_manager_client_factory_.reset( - new mojo::ViewManagerClientFactory(shell_, this)); - aura::Env::CreateInstance(true); - screen_.reset(mojo::ScreenMojo::Create()); - gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE, screen_.get()); - } - - virtual bool ConfigureIncomingConnection( - mojo::ApplicationConnection* connection) override { - connection->AddService(view_manager_client_factory_.get()); - return true; - } - - mojo::Shell* shell_; - - scoped_ptr<DemoWindowTreeClient> window_tree_client_; - - scoped_ptr<mojo::ScreenMojo> screen_; - - scoped_ptr<DemoWindowDelegate> delegate1_; - scoped_ptr<DemoWindowDelegate> delegate2_; - scoped_ptr<DemoWindowDelegate> delegate21_; - - aura::Window* window1_; - aura::Window* window2_; - aura::Window* window21_; - - mojo::View* root_; - - scoped_ptr<mojo::ViewManagerClientFactory> view_manager_client_factory_; - - scoped_ptr<aura::WindowTreeHost> window_tree_host_; - - DISALLOW_COPY_AND_ASSIGN(AuraDemo); -}; - -} // namespace examples - -MojoResult MojoMain(MojoHandle shell_handle) { - mojo::ApplicationRunnerChromium runner(new examples::AuraDemo); - return runner.Run(shell_handle); -}
diff --git a/examples/aura_demo/view_manager_init.cc b/examples/aura_demo/view_manager_init.cc deleted file mode 100644 index c31b8d5..0000000 --- a/examples/aura_demo/view_manager_init.cc +++ /dev/null
@@ -1,40 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/basictypes.h" -#include "base/bind.h" -#include "mojo/application/application_runner_chromium.h" -#include "mojo/public/c/system/main.h" -#include "mojo/public/cpp/application/application_delegate.h" -#include "mojo/public/cpp/application/application_impl.h" -#include "mojo/public/interfaces/application/service_provider.mojom.h" -#include "mojo/services/view_manager/public/cpp/view_manager.h" -#include "mojo/services/view_manager/public/cpp/view_manager_context.h" - -namespace examples { - -// ViewManagerInit is responsible for establishing the initial connection to -// the view manager. When established it loads |aura_demo|. -class ViewManagerInit : public mojo::ApplicationDelegate { - public: - ViewManagerInit() {} - virtual ~ViewManagerInit() {} - - virtual void Initialize(mojo::ApplicationImpl* app) override { - context_.reset(new mojo::ViewManagerContext(app)); - context_->Embed("mojo:aura_demo"); - } - - private: - scoped_ptr<mojo::ViewManagerContext> context_; - - DISALLOW_COPY_AND_ASSIGN(ViewManagerInit); -}; - -} // namespace examples - -MojoResult MojoMain(MojoHandle shell_handle) { - mojo::ApplicationRunnerChromium runner(new examples::ViewManagerInit); - return runner.Run(shell_handle); -}
diff --git a/examples/browser/BUILD.gn b/examples/browser/BUILD.gn index 9c57470..b763315 100644 --- a/examples/browser/BUILD.gn +++ b/examples/browser/BUILD.gn
@@ -6,8 +6,6 @@ import("//mojo/public/mojo_application.gni") import("//mojo/public/tools/bindings/mojom.gni") -assert(use_aura) - mojo_native_application("browser") { sources = [ "browser.cc", @@ -19,7 +17,6 @@ "//cc", "//examples/window_manager:bindings", "//mojo/application", - "//mojo/aura", "//mojo/common", "//mojo/converters/geometry", "//mojo/converters/input_events", @@ -28,15 +25,12 @@ "//mojo/services/navigation/public/interfaces", "//mojo/services/view_manager/public/cpp", "//mojo/services/view_manager/public/interfaces", - "//mojo/views:views", "//third_party/icu", - "//ui/aura", "//ui/base", - "//ui/compositor", + "//ui/events:events", "//ui/gfx", "//ui/gfx/geometry", "//ui/resources", - "//ui/views", "//url", ] }
diff --git a/examples/window_manager/BUILD.gn b/examples/window_manager/BUILD.gn index 21d8250..1e972f8 100644 --- a/examples/window_manager/BUILD.gn +++ b/examples/window_manager/BUILD.gn
@@ -6,37 +6,35 @@ import("//mojo/public/mojo_application.gni") import("//mojo/public/tools/bindings/mojom.gni") -if (use_aura) { - mojo_native_application("window_manager") { - output_name = "example_window_manager" +mojo_native_application("window_manager") { + output_name = "example_window_manager" - sources = [ - "window_manager.cc", - ] + sources = [ + "window_manager.cc", + ] - deps = [ - ":bindings", - "//base", - "//mojo/application", - "//mojo/converters/geometry", - "//mojo/converters/input_events", - "//mojo/public/c/gles2", - "//mojo/public/cpp/bindings", - "//mojo/public/cpp/utility", - "//mojo/services/geometry/public/interfaces", - "//mojo/services/input_events/public/interfaces", - "//mojo/services/navigation/public/interfaces", - "//mojo/services/view_manager/public/cpp", - "//services/window_manager:lib", - "//ui/base", - "//ui/events:events", - "//ui/gfx", - "//ui/gfx/geometry", - "//ui/gl", - "//ui/resources", - "//url:url", - ] - } + deps = [ + ":bindings", + "//base", + "//mojo/application", + "//mojo/converters/geometry", + "//mojo/converters/input_events", + "//mojo/public/c/gles2", + "//mojo/public/cpp/bindings", + "//mojo/public/cpp/utility", + "//mojo/services/geometry/public/interfaces", + "//mojo/services/input_events/public/interfaces", + "//mojo/services/navigation/public/interfaces", + "//mojo/services/view_manager/public/cpp", + "//services/window_manager:lib", + "//ui/base", + "//ui/events:events", + "//ui/gfx", + "//ui/gfx/geometry", + "//ui/gl", + "//ui/resources", + "//url:url", + ] } mojom("bindings") {
diff --git a/examples/wm_flow/BUILD.gn b/examples/wm_flow/BUILD.gn index 5cf5ebc..9853c58 100644 --- a/examples/wm_flow/BUILD.gn +++ b/examples/wm_flow/BUILD.gn
@@ -6,8 +6,6 @@ import("//mojo/public/mojo_application.gni") import("//mojo/public/tools/bindings/mojom.gni") -assert(use_aura) - group("wm_flow") { deps = [ ":app",
diff --git a/gpu/config/BUILD.gn b/gpu/config/BUILD.gn index df7153d..82d5a1b 100644 --- a/gpu/config/BUILD.gn +++ b/gpu/config/BUILD.gn
@@ -30,7 +30,6 @@ "gpu_info_collector_linux.cc", "gpu_info_collector_linux.h", "gpu_info_collector_mac.mm", - "gpu_info_collector_ozone.cc", "gpu_info_collector_win.cc", "gpu_info_collector_x11.cc", "gpu_info_collector.cc", @@ -76,7 +75,7 @@ if (use_libpci) { defines += [ "USE_LIBPCI=1" ] } - if (is_linux && use_libpci && (use_x11 || use_ozone)) { + if (is_linux && use_libpci && use_x11) { deps += [ "//build/config/linux:libpci" ] } if (is_linux && use_x11) { @@ -88,7 +87,4 @@ } else { sources -= [ "gpu_info_collector_x11.cc" ] } - if (!use_ozone) { - sources -= [ "gpu_info_collector_ozone.cc" ] - } }
diff --git a/gpu/config/gpu_info_collector_ozone.cc b/gpu/config/gpu_info_collector_ozone.cc deleted file mode 100644 index d8fef20..0000000 --- a/gpu/config/gpu_info_collector_ozone.cc +++ /dev/null
@@ -1,15 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/logging.h" -#include "gpu/config/gpu_info_collector_linux.h" - -namespace gpu { - -std::string CollectDriverVersionNVidia() { - NOTIMPLEMENTED(); - return std::string(); -} - -} // namespace gpu
diff --git a/gpu/gpu_config.gypi b/gpu/gpu_config.gypi index 4505503..a012b08 100644 --- a/gpu/gpu_config.gypi +++ b/gpu/gpu_config.gypi
@@ -31,7 +31,6 @@ 'config/gpu_info_collector_linux.cc', 'config/gpu_info_collector_linux.h', 'config/gpu_info_collector_mac.mm', - 'config/gpu_info_collector_ozone.cc', 'config/gpu_info_collector_win.cc', 'config/gpu_info_collector_x11.cc', 'config/gpu_info_collector.cc', @@ -65,7 +64,7 @@ '../third_party/amd/amd_videocard_info_win.cc', ], }], - ['OS=="linux" and use_libpci==1 and (use_x11==1 or use_ozone==1)', { + ['OS=="linux" and use_libpci==1 and use_x11==1', { 'dependencies': [ '../build/linux/system.gyp:libpci', ],
diff --git a/mojo/aura/BUILD.gn b/mojo/aura/BUILD.gn deleted file mode 100644 index add74cd..0000000 --- a/mojo/aura/BUILD.gn +++ /dev/null
@@ -1,43 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -# GYP version: mojo/mojo.gyp:mojo_aura_support -source_set("aura") { - sources = [ - "aura_init.cc", - "aura_init.h", - "screen_mojo.cc", - "screen_mojo.h", - "surface_binding.cc", - "surface_binding.h", - "surface_context_factory.cc", - "surface_context_factory.h", - "window_tree_host_mojo.cc", - "window_tree_host_mojo.h", - ] - - public_deps = [ - "//mojo/services/view_manager/public/cpp", - ] - deps = [ - "//cc", - "//cc/surfaces", - "//skia", - "//ui/aura", - "//ui/compositor", - "//ui/events", - "//ui/events:events_base", - "//ui/gl", - "//mojo/cc", - "//mojo/converters/geometry", - "//mojo/converters/surfaces", - "//mojo/public/c/gles2", - "//mojo/public/cpp/application", - "//mojo/public/interfaces/application:application", - "//mojo/services/gpu/public/interfaces", - "//mojo/services/native_viewport/public/interfaces", - "//mojo/services/surfaces/public/interfaces", - "//mojo/services/view_manager/public/cpp", - ] -}
diff --git a/mojo/aura/DEPS b/mojo/aura/DEPS deleted file mode 100644 index 660a477..0000000 --- a/mojo/aura/DEPS +++ /dev/null
@@ -1,10 +0,0 @@ -include_rules = [ - "+cc", - "-cc/blink", - "+skia", - "+ui/aura", - "+ui/compositor", - "+ui/events", - "+ui/gfx", - "+ui/gl", -]
diff --git a/mojo/aura/aura_init.cc b/mojo/aura/aura_init.cc deleted file mode 100644 index 2f41fd8..0000000 --- a/mojo/aura/aura_init.cc +++ /dev/null
@@ -1,22 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "mojo/aura/aura_init.h" - -#include "mojo/aura/screen_mojo.h" -#include "ui/aura/env.h" - -namespace mojo { - -AuraInit::AuraInit() { - aura::Env::CreateInstance(false); - - screen_.reset(ScreenMojo::Create()); - gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE, screen_.get()); -} - -AuraInit::~AuraInit() { -} - -} // namespace mojo
diff --git a/mojo/aura/aura_init.h b/mojo/aura/aura_init.h deleted file mode 100644 index 3f59449..0000000 --- a/mojo/aura/aura_init.h +++ /dev/null
@@ -1,28 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MOJO_AURA_AURA_INIT_MOJO_H_ -#define MOJO_AURA_AURA_INIT_MOJO_H_ - -#include "base/memory/scoped_ptr.h" - -namespace mojo { - -class ScreenMojo; - -// Sets up necessary state for aura when run with the viewmanager. -class AuraInit { - public: - AuraInit(); - ~AuraInit(); - - private: - scoped_ptr<ScreenMojo> screen_; - - DISALLOW_COPY_AND_ASSIGN(AuraInit); -}; - -} // namespace mojo - -#endif // MOJO_AURA_AURA_INIT_MOJO_H_
diff --git a/mojo/aura/screen_mojo.cc b/mojo/aura/screen_mojo.cc deleted file mode 100644 index 0ac5e39..0000000 --- a/mojo/aura/screen_mojo.cc +++ /dev/null
@@ -1,76 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "mojo/aura/screen_mojo.h" - -#include "ui/gfx/native_widget_types.h" -#include "ui/gfx/rect_conversions.h" - -namespace mojo { - -// static -ScreenMojo* ScreenMojo::Create() { - return new ScreenMojo(gfx::Rect(0, 0, 800, 600)); -} - -ScreenMojo::~ScreenMojo() { -} - -bool ScreenMojo::IsDIPEnabled() { - NOTIMPLEMENTED(); - return true; -} - -gfx::Point ScreenMojo::GetCursorScreenPoint() { - NOTIMPLEMENTED(); - return gfx::Point(); -} - -gfx::NativeWindow ScreenMojo::GetWindowUnderCursor() { - return GetWindowAtScreenPoint(GetCursorScreenPoint()); -} - -gfx::NativeWindow ScreenMojo::GetWindowAtScreenPoint(const gfx::Point& point) { - NOTIMPLEMENTED(); - return NULL; -} - -int ScreenMojo::GetNumDisplays() const { - return 1; -} - -std::vector<gfx::Display> ScreenMojo::GetAllDisplays() const { - return std::vector<gfx::Display>(1, display_); -} - -gfx::Display ScreenMojo::GetDisplayNearestWindow( - gfx::NativeWindow window) const { - return display_; -} - -gfx::Display ScreenMojo::GetDisplayNearestPoint(const gfx::Point& point) const { - return display_; -} - -gfx::Display ScreenMojo::GetDisplayMatching(const gfx::Rect& match_rect) const { - return display_; -} - -gfx::Display ScreenMojo::GetPrimaryDisplay() const { - return display_; -} - -void ScreenMojo::AddObserver(gfx::DisplayObserver* observer) { -} - -void ScreenMojo::RemoveObserver(gfx::DisplayObserver* observer) { -} - -ScreenMojo::ScreenMojo(const gfx::Rect& screen_bounds) { - static int64 synthesized_display_id = 2000; - display_.set_id(synthesized_display_id++); - display_.SetScaleAndBounds(1.0f, screen_bounds); -} - -} // namespace mojo
diff --git a/mojo/aura/screen_mojo.h b/mojo/aura/screen_mojo.h deleted file mode 100644 index 2e5febc..0000000 --- a/mojo/aura/screen_mojo.h +++ /dev/null
@@ -1,50 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MOJO_AURA_SCREEN_MOJO_H_ -#define MOJO_AURA_SCREEN_MOJO_H_ - -#include "base/macros.h" -#include "ui/gfx/display.h" -#include "ui/gfx/screen.h" - -namespace gfx { -class Rect; -class Transform; -} - -namespace mojo { - -// A minimal implementation of gfx::Screen for mojo. -class ScreenMojo : public gfx::Screen { - public: - static ScreenMojo* Create(); - ~ScreenMojo() override; - - protected: - // gfx::Screen overrides: - bool IsDIPEnabled() override; - gfx::Point GetCursorScreenPoint() override; - gfx::NativeWindow GetWindowUnderCursor() override; - gfx::NativeWindow GetWindowAtScreenPoint(const gfx::Point& point) override; - int GetNumDisplays() const override; - std::vector<gfx::Display> GetAllDisplays() const override; - gfx::Display GetDisplayNearestWindow(gfx::NativeView view) const override; - gfx::Display GetDisplayNearestPoint(const gfx::Point& point) const override; - gfx::Display GetDisplayMatching(const gfx::Rect& match_rect) const override; - gfx::Display GetPrimaryDisplay() const override; - void AddObserver(gfx::DisplayObserver* observer) override; - void RemoveObserver(gfx::DisplayObserver* observer) override; - - private: - explicit ScreenMojo(const gfx::Rect& screen_bounds); - - gfx::Display display_; - - DISALLOW_COPY_AND_ASSIGN(ScreenMojo); -}; - -} // namespace mojo - -#endif // MOJO_AURA_SCREEN_MOJO_H_
diff --git a/mojo/aura/surface_binding.cc b/mojo/aura/surface_binding.cc deleted file mode 100644 index e08b623..0000000 --- a/mojo/aura/surface_binding.cc +++ /dev/null
@@ -1,240 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "mojo/aura/surface_binding.h" - -#include <map> - -#include "base/bind.h" -#include "base/lazy_instance.h" -#include "base/threading/thread_local.h" -#include "cc/output/compositor_frame.h" -#include "cc/output/output_surface.h" -#include "cc/output/output_surface_client.h" -#include "cc/output/software_output_device.h" -#include "cc/resources/shared_bitmap_manager.h" -#include "mojo/aura/window_tree_host_mojo.h" -#include "mojo/cc/context_provider_mojo.h" -#include "mojo/converters/geometry/geometry_type_converters.h" -#include "mojo/converters/surfaces/surfaces_type_converters.h" -#include "mojo/public/cpp/application/connect.h" -#include "mojo/public/interfaces/application/shell.mojom.h" -#include "mojo/services/gpu/public/interfaces/gpu.mojom.h" -#include "mojo/services/surfaces/public/interfaces/surfaces.mojom.h" -#include "mojo/services/view_manager/public/cpp/view.h" -#include "mojo/services/view_manager/public/cpp/view_manager.h" - -namespace mojo { -namespace { - -// OutputSurface --------------------------------------------------------------- - -// OutputSurface implementation for a view. Pushes the surface id to View when -// appropriate. -class OutputSurfaceImpl : public cc::OutputSurface { - public: - OutputSurfaceImpl(View* view, - const scoped_refptr<cc::ContextProvider>& context_provider, - Surface* surface, - uint32_t id_namespace, - uint32_t* next_local_id); - ~OutputSurfaceImpl() override; - - // cc::OutputSurface: - void SwapBuffers(cc::CompositorFrame* frame) override; - - private: - View* view_; - Surface* surface_; - uint32_t id_namespace_; - uint32_t* next_local_id_; // Owned by PerViewManagerState. - uint32_t local_id_; - gfx::Size surface_size_; - - DISALLOW_COPY_AND_ASSIGN(OutputSurfaceImpl); -}; - -OutputSurfaceImpl::OutputSurfaceImpl( - View* view, - const scoped_refptr<cc::ContextProvider>& context_provider, - Surface* surface, - uint32_t id_namespace, - uint32_t* next_local_id) - : cc::OutputSurface(context_provider), - view_(view), - surface_(surface), - id_namespace_(id_namespace), - next_local_id_(next_local_id), - local_id_(0u) { - capabilities_.delegated_rendering = true; - capabilities_.max_frames_pending = 1; -} - -OutputSurfaceImpl::~OutputSurfaceImpl() { -} - -void OutputSurfaceImpl::SwapBuffers(cc::CompositorFrame* frame) { - gfx::Size frame_size = - frame->delegated_frame_data->render_pass_list.back()->output_rect.size(); - if (frame_size != surface_size_) { - if (local_id_ != 0u) - surface_->DestroySurface(local_id_); - local_id_ = (*next_local_id_)++; - surface_->CreateSurface(local_id_); - auto qualified_id = mojo::SurfaceId::New(); - qualified_id->local = local_id_; - qualified_id->id_namespace = id_namespace_; - view_->SetSurfaceId(qualified_id.Pass()); - surface_size_ = frame_size; - } - - surface_->SubmitFrame(local_id_, Frame::From(*frame), mojo::Closure()); - - client_->DidSwapBuffers(); - client_->DidSwapBuffersComplete(); -} - -} // namespace - -// PerViewManagerState --------------------------------------------------------- - -// State needed per ViewManager. Provides the real implementation of -// CreateOutputSurface. SurfaceBinding obtains a pointer to the -// PerViewManagerState appropriate for the ViewManager. PerViewManagerState is -// stored in a thread local map. When no more refereces to a PerViewManagerState -// remain the PerViewManagerState is deleted and the underlying map cleaned up. -class SurfaceBinding::PerViewManagerState - : public base::RefCounted<PerViewManagerState>, - public mojo::SurfaceClient { - public: - static PerViewManagerState* Get(Shell* shell, ViewManager* view_manager); - - scoped_ptr<cc::OutputSurface> CreateOutputSurface(View* view); - - private: - typedef std::map<ViewManager*, PerViewManagerState*> ViewManagerToStateMap; - - friend class base::RefCounted<PerViewManagerState>; - - PerViewManagerState(Shell* shell, ViewManager* view_manager); - ~PerViewManagerState(); - - void Init(); - - // SurfaceClient: - void SetIdNamespace(uint32_t id_namespace) override; - void ReturnResources( - mojo::Array<mojo::ReturnedResourcePtr> resources) override; - - static base::LazyInstance< - base::ThreadLocalPointer<ViewManagerToStateMap>>::Leaky view_states; - - Shell* shell_; - ViewManager* view_manager_; - - // Set of state needed to create an OutputSurface. - GpuPtr gpu_; - SurfacePtr surface_; - uint32_t id_namespace_; - uint32_t next_local_id_; - - DISALLOW_COPY_AND_ASSIGN(PerViewManagerState); -}; - -// static -base::LazyInstance<base::ThreadLocalPointer< - SurfaceBinding::PerViewManagerState::ViewManagerToStateMap>>::Leaky - SurfaceBinding::PerViewManagerState::view_states; - -// static -SurfaceBinding::PerViewManagerState* SurfaceBinding::PerViewManagerState::Get( - Shell* shell, - ViewManager* view_manager) { - ViewManagerToStateMap* view_map = view_states.Pointer()->Get(); - if (!view_map) { - view_map = new ViewManagerToStateMap; - view_states.Pointer()->Set(view_map); - } - if (!(*view_map)[view_manager]) { - (*view_map)[view_manager] = new PerViewManagerState(shell, view_manager); - (*view_map)[view_manager]->Init(); - } - return (*view_map)[view_manager]; -} - -scoped_ptr<cc::OutputSurface> -SurfaceBinding::PerViewManagerState::CreateOutputSurface(View* view) { - // TODO(sky): figure out lifetime here. Do I need to worry about the return - // value outliving this? - CommandBufferPtr cb; - gpu_->CreateOffscreenGLES2Context(GetProxy(&cb)); - scoped_refptr<cc::ContextProvider> context_provider( - new ContextProviderMojo(cb.PassMessagePipe())); - return make_scoped_ptr(new OutputSurfaceImpl( - view, context_provider, surface_.get(), id_namespace_, &next_local_id_)); -} - -SurfaceBinding::PerViewManagerState::PerViewManagerState( - Shell* shell, - ViewManager* view_manager) - : shell_(shell), - view_manager_(view_manager), - id_namespace_(0u), - next_local_id_(0u) { -} - -SurfaceBinding::PerViewManagerState::~PerViewManagerState() { - ViewManagerToStateMap* view_map = view_states.Pointer()->Get(); - DCHECK(view_map); - DCHECK_EQ(this, (*view_map)[view_manager_]); - view_map->erase(view_manager_); - if (view_map->empty()) { - delete view_map; - view_states.Pointer()->Set(nullptr); - } -} - -void SurfaceBinding::PerViewManagerState::Init() { - DCHECK(!surface_.get()); - - ServiceProviderPtr surfaces_service_provider; - shell_->ConnectToApplication("mojo:surfaces_service", - GetProxy(&surfaces_service_provider)); - ConnectToService(surfaces_service_provider.get(), &surface_); - surface_.set_client(this); - // Block until we receive our id namespace. - surface_.WaitForIncomingMethodCall(); - DCHECK_NE(0u, id_namespace_); - - ServiceProviderPtr gpu_service_provider; - // TODO(jamesr): Should be mojo:gpu_service - shell_->ConnectToApplication("mojo:native_viewport_service", - GetProxy(&gpu_service_provider)); - ConnectToService(gpu_service_provider.get(), &gpu_); -} - -void SurfaceBinding::PerViewManagerState::SetIdNamespace( - uint32_t id_namespace) { - id_namespace_ = id_namespace; -} - -void SurfaceBinding::PerViewManagerState::ReturnResources( - mojo::Array<mojo::ReturnedResourcePtr> resources) { -} - -// SurfaceBinding -------------------------------------------------------------- - -SurfaceBinding::SurfaceBinding(Shell* shell, View* view) - : view_(view), - state_(PerViewManagerState::Get(shell, view->view_manager())) { -} - -SurfaceBinding::~SurfaceBinding() { -} - -scoped_ptr<cc::OutputSurface> SurfaceBinding::CreateOutputSurface() { - return state_->CreateOutputSurface(view_); -} - -} // namespace mojo
diff --git a/mojo/aura/surface_binding.h b/mojo/aura/surface_binding.h deleted file mode 100644 index 33f6eac..0000000 --- a/mojo/aura/surface_binding.h +++ /dev/null
@@ -1,45 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MOJO_AURA_SURFACE_BINDING_H_ -#define MOJO_AURA_SURFACE_BINDING_H_ - -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" - -namespace cc { -class OutputSurface; -} - -namespace mojo { -class Shell; -class View; - -// SurfaceBinding is responsible for managing the connections necessary to -// bind a View to the surfaces service. -// Internally SurfaceBinding manages one connection (and related structures) per -// ViewManager. That is, all Views from a particular ViewManager share the same -// connection. -class SurfaceBinding { - public: - SurfaceBinding(Shell* shell, View* view); - ~SurfaceBinding(); - - // Creates an OutputSurface that renders to the View supplied to the - // constructor. - scoped_ptr<cc::OutputSurface> CreateOutputSurface(); - - private: - class PerViewManagerState; - - Shell* shell_; - View* view_; - scoped_refptr<PerViewManagerState> state_; - - DISALLOW_COPY_AND_ASSIGN(SurfaceBinding); -}; - -} // namespace mojo - -#endif // MOJO_AURA_SURFACE_BINDING_H_
diff --git a/mojo/aura/surface_context_factory.cc b/mojo/aura/surface_context_factory.cc deleted file mode 100644 index 3e1422f..0000000 --- a/mojo/aura/surface_context_factory.cc +++ /dev/null
@@ -1,69 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "mojo/aura/surface_context_factory.h" - -#include "cc/output/output_surface.h" -#include "cc/resources/shared_bitmap_manager.h" -#include "cc/surfaces/surface_id_allocator.h" -#include "mojo/public/interfaces/application/shell.mojom.h" -#include "mojo/services/view_manager/public/cpp/view.h" -#include "ui/compositor/reflector.h" - -namespace mojo { - -SurfaceContextFactory::SurfaceContextFactory(Shell* shell, View* view) - : surface_binding_(shell, view) { -} - -SurfaceContextFactory::~SurfaceContextFactory() { -} - -void SurfaceContextFactory::CreateOutputSurface( - base::WeakPtr<ui::Compositor> compositor, - bool software_fallback) { - compositor->SetOutputSurface(surface_binding_.CreateOutputSurface()); -} - -scoped_refptr<ui::Reflector> SurfaceContextFactory::CreateReflector( - ui::Compositor* mirroed_compositor, - ui::Layer* mirroring_layer) { - return new ui::Reflector(); -} - -void SurfaceContextFactory::RemoveReflector( - scoped_refptr<ui::Reflector> reflector) { -} - -scoped_refptr<cc::ContextProvider> -SurfaceContextFactory::SharedMainThreadContextProvider() { - return nullptr; -} - -void SurfaceContextFactory::RemoveCompositor(ui::Compositor* compositor) { -} - -bool SurfaceContextFactory::DoesCreateTestContexts() { - return false; -} - -cc::SharedBitmapManager* SurfaceContextFactory::GetSharedBitmapManager() { - return nullptr; -} - -gpu::GpuMemoryBufferManager* -SurfaceContextFactory::GetGpuMemoryBufferManager() { - return nullptr; -} - -base::MessageLoopProxy* SurfaceContextFactory::GetCompositorMessageLoop() { - return nullptr; -} - -scoped_ptr<cc::SurfaceIdAllocator> -SurfaceContextFactory::CreateSurfaceIdAllocator() { - return nullptr; -} - -} // namespace mojo
diff --git a/mojo/aura/surface_context_factory.h b/mojo/aura/surface_context_factory.h deleted file mode 100644 index a69bb90..0000000 --- a/mojo/aura/surface_context_factory.h +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MOJO_AURA_SURFACE_CONTEXT_FACTORY_H_ -#define MOJO_AURA_SURFACE_CONTEXT_FACTORY_H_ - -#include "mojo/aura/surface_binding.h" -#include "ui/compositor/compositor.h" - -namespace mojo { -class Shell; -class View; - -class SurfaceContextFactory : public ui::ContextFactory { - public: - SurfaceContextFactory(Shell* shell, View* view); - ~SurfaceContextFactory() override; - - private: - // ContextFactory: - void CreateOutputSurface(base::WeakPtr<ui::Compositor> compositor, - bool software_fallback) override; - scoped_refptr<ui::Reflector> CreateReflector( - ui::Compositor* mirrored_compositor, - ui::Layer* mirroring_layer) override; - void RemoveReflector(scoped_refptr<ui::Reflector> reflector) override; - scoped_refptr<cc::ContextProvider> SharedMainThreadContextProvider() override; - void RemoveCompositor(ui::Compositor* compositor) override; - bool DoesCreateTestContexts() override; - cc::SharedBitmapManager* GetSharedBitmapManager() override; - gpu::GpuMemoryBufferManager* GetGpuMemoryBufferManager() override; - base::MessageLoopProxy* GetCompositorMessageLoop() override; - scoped_ptr<cc::SurfaceIdAllocator> CreateSurfaceIdAllocator() override; - - SurfaceBinding surface_binding_; - - DISALLOW_COPY_AND_ASSIGN(SurfaceContextFactory); -}; - -} // namespace mojo - -#endif // MOJO_AURA_SURFACE_CONTEXT_FACTORY_H_
diff --git a/mojo/aura/window_tree_host_mojo.cc b/mojo/aura/window_tree_host_mojo.cc deleted file mode 100644 index ddb316f..0000000 --- a/mojo/aura/window_tree_host_mojo.cc +++ /dev/null
@@ -1,122 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "mojo/aura/window_tree_host_mojo.h" - -#include "mojo/aura/surface_context_factory.h" -#include "mojo/converters/geometry/geometry_type_converters.h" -#include "mojo/public/interfaces/application/shell.mojom.h" -#include "mojo/services/view_manager/public/cpp/view_manager.h" -#include "ui/aura/env.h" -#include "ui/aura/window.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/events/event.h" -#include "ui/events/event_constants.h" - -namespace mojo { - -//////////////////////////////////////////////////////////////////////////////// -// WindowTreeHostMojo, public: - -WindowTreeHostMojo::WindowTreeHostMojo(Shell* shell, View* view) - : view_(view), bounds_(view->bounds().To<gfx::Rect>()) { - view_->AddObserver(this); - - context_factory_.reset(new SurfaceContextFactory(shell, view_)); - // WindowTreeHost creates the compositor using the ContextFactory from - // aura::Env. Install |context_factory_| there so that |context_factory_| is - // picked up. - ui::ContextFactory* default_context_factory = - aura::Env::GetInstance()->context_factory(); - aura::Env::GetInstance()->set_context_factory(context_factory_.get()); - CreateCompositor(GetAcceleratedWidget()); - aura::Env::GetInstance()->set_context_factory(default_context_factory); - DCHECK_EQ(context_factory_.get(), compositor()->context_factory()); -} - -WindowTreeHostMojo::~WindowTreeHostMojo() { - view_->RemoveObserver(this); - DestroyCompositor(); - DestroyDispatcher(); -} - -//////////////////////////////////////////////////////////////////////////////// -// WindowTreeHostMojo, aura::WindowTreeHost implementation: - -ui::EventSource* WindowTreeHostMojo::GetEventSource() { - return this; -} - -gfx::AcceleratedWidget WindowTreeHostMojo::GetAcceleratedWidget() { - return gfx::kNullAcceleratedWidget; -} - -void WindowTreeHostMojo::Show() { - window()->Show(); -} - -void WindowTreeHostMojo::Hide() { -} - -gfx::Rect WindowTreeHostMojo::GetBounds() const { - return bounds_; -} - -void WindowTreeHostMojo::SetBounds(const gfx::Rect& bounds) { - window()->SetBounds(gfx::Rect(bounds.size())); -} - -gfx::Point WindowTreeHostMojo::GetLocationOnNativeScreen() const { - return gfx::Point(0, 0); -} - -void WindowTreeHostMojo::SetCapture() { - NOTIMPLEMENTED(); -} - -void WindowTreeHostMojo::ReleaseCapture() { - NOTIMPLEMENTED(); -} - -void WindowTreeHostMojo::PostNativeEvent( - const base::NativeEvent& native_event) { - NOTIMPLEMENTED(); -} - -void WindowTreeHostMojo::SetCursorNative(gfx::NativeCursor cursor) { - NOTIMPLEMENTED(); -} - -void WindowTreeHostMojo::MoveCursorToNative(const gfx::Point& location) { - NOTIMPLEMENTED(); -} - -void WindowTreeHostMojo::OnCursorVisibilityChangedNative(bool show) { - NOTIMPLEMENTED(); -} - -//////////////////////////////////////////////////////////////////////////////// -// WindowTreeHostMojo, ui::EventSource implementation: - -ui::EventProcessor* WindowTreeHostMojo::GetEventProcessor() { - return dispatcher(); -} - -//////////////////////////////////////////////////////////////////////////////// -// WindowTreeHostMojo, ViewObserver implementation: - -void WindowTreeHostMojo::OnViewBoundsChanged( - View* view, - const Rect& old_bounds, - const Rect& new_bounds) { - gfx::Rect old_bounds2 = old_bounds.To<gfx::Rect>(); - gfx::Rect new_bounds2 = new_bounds.To<gfx::Rect>(); - bounds_ = new_bounds2; - if (old_bounds2.origin() != new_bounds2.origin()) - OnHostMoved(bounds_.origin()); - if (old_bounds2.size() != new_bounds2.size()) - OnHostResized(bounds_.size()); -} - -} // namespace mojo
diff --git a/mojo/aura/window_tree_host_mojo.h b/mojo/aura/window_tree_host_mojo.h deleted file mode 100644 index 8cd1255..0000000 --- a/mojo/aura/window_tree_host_mojo.h +++ /dev/null
@@ -1,73 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MOJO_EXAMPLES_AURA_DEMO_WINDOW_TREE_HOST_VIEW_MANAGER_H_ -#define MOJO_EXAMPLES_AURA_DEMO_WINDOW_TREE_HOST_VIEW_MANAGER_H_ - -#include "base/macros.h" -#include "mojo/services/view_manager/public/cpp/view_observer.h" -#include "ui/aura/window_tree_host.h" -#include "ui/events/event_source.h" -#include "ui/gfx/geometry/rect.h" - -class SkBitmap; - -namespace ui { -class Compositor; -} - -namespace mojo { - -class Shell; -class SurfaceContextFactory; - -class WindowTreeHostMojo : public aura::WindowTreeHost, - public ui::EventSource, - public ViewObserver { - public: - WindowTreeHostMojo(Shell* shell, View* view); - ~WindowTreeHostMojo() override; - - const gfx::Rect& bounds() const { return bounds_; } - - ui::EventDispatchDetails SendEventToProcessor(ui::Event* event) { - return ui::EventSource::SendEventToProcessor(event); - } - - private: - // WindowTreeHost: - ui::EventSource* GetEventSource() override; - gfx::AcceleratedWidget GetAcceleratedWidget() override; - void Show() override; - void Hide() override; - gfx::Rect GetBounds() const override; - void SetBounds(const gfx::Rect& bounds) override; - gfx::Point GetLocationOnNativeScreen() const override; - void SetCapture() override; - void ReleaseCapture() override; - void PostNativeEvent(const base::NativeEvent& native_event) override; - void SetCursorNative(gfx::NativeCursor cursor) override; - void MoveCursorToNative(const gfx::Point& location) override; - void OnCursorVisibilityChangedNative(bool show) override; - - // ui::EventSource: - ui::EventProcessor* GetEventProcessor() override; - - // ViewObserver: - void OnViewBoundsChanged(View* view, - const Rect& old_bounds, - const Rect& new_bounds) override; - - View* view_; - - gfx::Rect bounds_; - - scoped_ptr<SurfaceContextFactory> context_factory_; - - DISALLOW_COPY_AND_ASSIGN(WindowTreeHostMojo); -}; - -} // namespace mojo - -#endif // MOJO_EXAMPLES_AURA_DEMO_WINDOW_TREE_HOST_VIEW_MANAGER_H_
diff --git a/mojo/services/view_manager/public/cpp/tests/BUILD.gn b/mojo/services/view_manager/public/cpp/tests/BUILD.gn index fb2ed5a..4ccedc9 100644 --- a/mojo/services/view_manager/public/cpp/tests/BUILD.gn +++ b/mojo/services/view_manager/public/cpp/tests/BUILD.gn
@@ -20,13 +20,9 @@ "//mojo/services/geometry/public/cpp", "//mojo/services/geometry/public/interfaces", "//mojo/services/view_manager/public/cpp", + "//mojo/services/view_manager/public/cpp/lib:run_unittests", "//mojo/services/view_manager/public/interfaces", "//shell:test_support", "//testing/gtest", ] - if (use_aura) { - deps += [ "//mojo/services/view_manager/public/cpp/lib:run_unittests" ] - } else { - deps += [ "//mojo/edk/test:run_all_unittests" ] - } }
diff --git a/mojo/views/BUILD.gn b/mojo/views/BUILD.gn deleted file mode 100644 index b609524..0000000 --- a/mojo/views/BUILD.gn +++ /dev/null
@@ -1,43 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import("//build/config/ui.gni") - -assert(use_aura) - -# GYP version: mojo/mojo.gyp:mojo_views_support -static_library("views") { - sources = [ - "input_method_mojo_linux.cc", - "input_method_mojo_linux.h", - "native_widget_mojo.cc", - "native_widget_mojo.h", - "native_widget_view_manager.cc", - "native_widget_view_manager.h", - "views_init.cc", - "views_init.h", - ] - - public_deps = [ - "//mojo/aura", - "//mojo/converters/geometry", - "//mojo/services/view_manager/public/cpp", - "//skia", - "//ui/base", - "//ui/views", - ] - - deps = [ - "//base", - "//base:i18n", - "//base/third_party/dynamic_annotations", - "//skia", - "//third_party/icu", - "//ui/aura", - "//ui/base", - "//ui/gfx", - "//ui/native_theme:native_theme", - "//ui/wm", - ] -}
diff --git a/mojo/views/DEPS b/mojo/views/DEPS deleted file mode 100644 index 5a3e079..0000000 --- a/mojo/views/DEPS +++ /dev/null
@@ -1,11 +0,0 @@ -include_rules = [ - "+base", - "+skia", - "+ui/aura", - "+ui/base", - "+ui/compositor", - "+ui/events", - "+ui/native_theme", - "+ui/views", - "+ui/wm", -]
diff --git a/mojo/views/input_method_mojo_linux.cc b/mojo/views/input_method_mojo_linux.cc deleted file mode 100644 index e54b644..0000000 --- a/mojo/views/input_method_mojo_linux.cc +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "mojo/views/input_method_mojo_linux.h" - -#include "ui/base/ime/text_input_client.h" -#include "ui/events/event.h" - -namespace mojo { - -InputMethodMojoLinux::InputMethodMojoLinux( - ui::internal::InputMethodDelegate* delegate) - : ui::InputMethodAuraLinux(delegate) { -} - -InputMethodMojoLinux::~InputMethodMojoLinux() {} - -bool InputMethodMojoLinux::DispatchKeyEvent(const ui::KeyEvent& event) { - DCHECK(event.type() == ui::ET_KEY_PRESSED || - event.type() == ui::ET_KEY_RELEASED); - DCHECK(system_toplevel_window_focused()); - - // If no text input client, do nothing. - if (!GetTextInputClient()) - return DispatchKeyEventPostIME(event); - - // Here is where we change the differ from our base class's logic. Instead of - // always dispatching a key down event, and then sending a synthesized - // character event, we instead check to see if this is a character event and - // send out the key if it is. (We fallback to normal dispatch if it isn't.) - if (event.is_char()) { - const uint16 ch = event.GetCharacter(); - if (GetTextInputClient()) - GetTextInputClient()->InsertChar(ch, event.flags()); - - return false; - } - - return DispatchKeyEventPostIME(event); -} - -} // namespace mojo
diff --git a/mojo/views/input_method_mojo_linux.h b/mojo/views/input_method_mojo_linux.h deleted file mode 100644 index f941ab2..0000000 --- a/mojo/views/input_method_mojo_linux.h +++ /dev/null
@@ -1,38 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MOJO_VIEWS_INPUT_METHOD_MOJO_LINUX_H_ -#define MOJO_VIEWS_INPUT_METHOD_MOJO_LINUX_H_ - -#include "ui/base/ime/input_method_auralinux.h" -#include "ui/base/ime/input_method_delegate.h" - -namespace mojo { - -// An input method for linux that does absolutely no translation. -// -// The current InputMethodMinimal makes assumptions that a system will only -// input/output keydown/keyup events; it assumes that things don't work like -// Windows does. When it gets a keydown event, it then tries to insert a -// character at the same time. -// -// However, we're standardizing on Windows' WM_CHAR style events. This tries to -// follow InputMethodWin::DispatchKeyEvent() instead, because PlatformViewX11 -// now synthesizes a character events so that we have one behaviour across our -// platforms. -class InputMethodMojoLinux : public ui::InputMethodAuraLinux { - public: - explicit InputMethodMojoLinux(ui::internal::InputMethodDelegate* delegate); - virtual ~InputMethodMojoLinux(); - - // Overriden from ui::InputMethodAuraLinux: - virtual bool DispatchKeyEvent(const ui::KeyEvent& event) override; - - private: - DISALLOW_COPY_AND_ASSIGN(InputMethodMojoLinux); -}; - -} // namespace mojo - -#endif // MOJO_VIEWS_INPUT_METHOD_MOJO_LINUX_H_
diff --git a/mojo/views/native_widget_mojo.cc b/mojo/views/native_widget_mojo.cc deleted file mode 100644 index 4a297eb..0000000 --- a/mojo/views/native_widget_mojo.cc +++ /dev/null
@@ -1,646 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "mojo/views/native_widget_mojo.h" - -#include "base/bind.h" -#include "base/thread_task_runner_handle.h" -#include "mojo/aura/surface_context_factory.h" -#include "mojo/converters/geometry/geometry_type_converters.h" -#include "mojo/converters/input_events/input_events_type_converters.h" -#include "ui/compositor/compositor.h" -#include "ui/events/event.h" -#include "ui/native_theme/native_theme_aura.h" -#include "ui/views/ime/input_method.h" -#include "ui/views/views_delegate.h" -#include "ui/views/widget/native_widget_delegate.h" -#include "ui/views/widget/widget_delegate.h" - -namespace gfx { -class Canvas; -} - -namespace mojo { - -//////////////////////////////////////////////////////////////////////////////// -// NativeWidgetMojo, public: - -NativeWidgetMojo::NativeWidgetMojo( - views::internal::NativeWidgetDelegate* delegate, - mojo::Shell* shell, - mojo::View* view) - : delegate_(delegate), - ownership_(views::Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET), - view_(view), - destroying_(false), - close_widget_factory_(this) { - context_factory_.reset(new SurfaceContextFactory(shell, view)); - compositor_.reset(new ui::Compositor(gfx::kNullAcceleratedWidget, - context_factory_.get(), - base::ThreadTaskRunnerHandle::Get())); - - gfx::Size size = view->bounds().To<gfx::Rect>().size(); - compositor_->SetScaleAndSize(1.0f, size); -} - -//////////////////////////////////////////////////////////////////////////////// -// NativeWidgetMojo, internal::NativeWidgetPrivate implementation: - -void NativeWidgetMojo::InitNativeWidget( - const views::Widget::InitParams& params) { - ownership_ = params.ownership; - - SetLayer(new ui::Layer(ui::LAYER_TEXTURED)); - layer()->SetVisible(true); - layer()->set_delegate(this); - compositor_->SetRootLayer(layer()); - - // TODO(erg): The aura version sets shadows types on their window here. - if (params.type == views::Widget::InitParams::TYPE_CONTROL) - view_->SetVisible(true); - - delegate_->OnNativeWidgetCreated(false); - - gfx::Rect window_bounds = params.bounds; - // TODO(erg): Handle params.child once we have child widgets, along with - // params.parent. - - // Set properties before adding to the parent so that its layout manager sees - // the correct values. - OnSizeConstraintsChanged(); - - // TODO(erg): Handle parent relations here. - - // Start observing property changes. - view_->AddObserver(this); - - // TODO(erg): Do additional things related to the restore bounds and - // maximization. See NWA. - SetBounds(window_bounds); -} - -views::NonClientFrameView* NativeWidgetMojo::CreateNonClientFrameView() { - return nullptr; -} - -bool NativeWidgetMojo::ShouldUseNativeFrame() const { - // TODO(erg): We can probably remove this method; it's only used in windows - // for Aero frames. - return false; -} - -bool NativeWidgetMojo::ShouldWindowContentsBeTransparent() const { - return false; -} - -void NativeWidgetMojo::FrameTypeChanged() { - // This is called when the Theme has changed; forward the event to the root - // widget. - GetWidget()->ThemeChanged(); - GetWidget()->GetRootView()->SchedulePaint(); -} - -views::Widget* NativeWidgetMojo::GetWidget() { - return delegate_->AsWidget(); -} - -const views::Widget* NativeWidgetMojo::GetWidget() const { - return delegate_->AsWidget(); -} - -gfx::NativeView NativeWidgetMojo::GetNativeView() const { - // TODO(erg): Actually implementing this will require moving off aura - // entirely because of the NativeView typedefs. (Those will need to be - // changed to mojo::View being the native view/window.) - return nullptr; -} - -gfx::NativeWindow NativeWidgetMojo::GetNativeWindow() const { - return nullptr; -} - -views::Widget* NativeWidgetMojo::GetTopLevelWidget() { - NativeWidgetPrivate* native_widget = GetTopLevelNativeWidget(GetNativeView()); - return native_widget ? native_widget->GetWidget() : nullptr; -} - -const ui::Compositor* NativeWidgetMojo::GetCompositor() const { - return compositor_.get(); -} - -ui::Compositor* NativeWidgetMojo::GetCompositor() { - return compositor_.get(); -} - -ui::Layer* NativeWidgetMojo::GetLayer() { - return layer(); -} - -void NativeWidgetMojo::ReorderNativeViews() { - // TODO(erg): Punting on this until we actually have something that uses - // ui::Layer or NativeViewHost. - NOTIMPLEMENTED(); -} - -void NativeWidgetMojo::ViewRemoved(views::View* view) { - NOTIMPLEMENTED(); -} - -void NativeWidgetMojo::SetNativeWindowProperty(const char* name, void* value) { - // TODO(erg): "Native Window" properties do not actually set things on the - // system's native window; in mojo::View parlance, this is actually a local - // property, not a shared one. - NOTIMPLEMENTED(); -} - -void* NativeWidgetMojo::GetNativeWindowProperty(const char* name) const { - NOTIMPLEMENTED(); - return nullptr; -} - -views::TooltipManager* NativeWidgetMojo::GetTooltipManager() const { - NOTIMPLEMENTED(); - return nullptr; -} - -void NativeWidgetMojo::SetCapture() { - NOTIMPLEMENTED(); -} - -void NativeWidgetMojo::ReleaseCapture() { - NOTIMPLEMENTED(); -} - -bool NativeWidgetMojo::HasCapture() const { - NOTIMPLEMENTED(); - return false; -} - -views::InputMethod* NativeWidgetMojo::CreateInputMethod() { - // TODO(erg): Implement this; having a NOTIMPLEMENTED() spews too much. - return nullptr; -} - -views::internal::InputMethodDelegate* -NativeWidgetMojo::GetInputMethodDelegate() { - NOTIMPLEMENTED(); - return nullptr; -} - -ui::InputMethod* NativeWidgetMojo::GetHostInputMethod() { - NOTIMPLEMENTED(); - return nullptr; -} - -void NativeWidgetMojo::CenterWindow(const gfx::Size& size) { - NOTIMPLEMENTED(); -} - -void NativeWidgetMojo::GetWindowPlacement( - gfx::Rect* bounds, - ui::WindowShowState* show_state) const { - // The interface specifies returning restored bounds, not current bounds. - *bounds = GetRestoredBounds(); - // TODO(erg): Redo how we encode |show_state|. -} - -bool NativeWidgetMojo::SetWindowTitle(const base::string16& title) { - NOTIMPLEMENTED(); - return true; -} - -void NativeWidgetMojo::SetWindowIcons(const gfx::ImageSkia& window_icon, - const gfx::ImageSkia& app_icon) { - // TODO(erg): If we add an interface for this, we should change the method - // type to pass a representation of different icon sizes. The current - // signature is a legacy of how Windows passes icons around. -} - -void NativeWidgetMojo::InitModalType(ui::ModalType modal_type) { - NOTIMPLEMENTED(); -} - -gfx::Rect NativeWidgetMojo::GetWindowBoundsInScreen() const { - NOTIMPLEMENTED(); - return gfx::Rect(); -} - -gfx::Rect NativeWidgetMojo::GetClientAreaBoundsInScreen() const { - // View-to-screen coordinate system transformations depend on this returning - // the full window bounds, for example View::ConvertPointToScreen(). - NOTIMPLEMENTED(); - return gfx::Rect(); -} - -gfx::Rect NativeWidgetMojo::GetRestoredBounds() const { - NOTIMPLEMENTED(); - return gfx::Rect(); -} - -void NativeWidgetMojo::SetBounds(const gfx::Rect& bounds) { - if (!view_) - return; - - view_->SetBounds(*mojo::Rect::From(bounds)); - - gfx::Size size = bounds.size(); - compositor_->SetScaleAndSize(1.0f, size); - layer()->SetBounds(gfx::Rect(size)); - delegate_->OnNativeWidgetSizeChanged(size); -} - -void NativeWidgetMojo::SetSize(const gfx::Size& size) { - NOTIMPLEMENTED(); -} - -void NativeWidgetMojo::StackAbove(gfx::NativeView native_view) { - NOTIMPLEMENTED(); -} - -void NativeWidgetMojo::StackAtTop() { - NOTIMPLEMENTED(); -} - -void NativeWidgetMojo::StackBelow(gfx::NativeView native_view) { - NOTIMPLEMENTED(); -} - -void NativeWidgetMojo::SetShape(gfx::NativeRegion region) { - // TODO(erg): This is incomplete here. We also need to set the shape on the - // mojo::View. - NOTIMPLEMENTED(); - if (view_) - layer()->SetAlphaShape(make_scoped_ptr(region)); - else - delete region; -} - -void NativeWidgetMojo::Close() { - // |window_| may already be deleted by parent window. This can happen - // when this widget is child widget or has transient parent - // and ownership is WIDGET_OWNS_NATIVE_WIDGET. - DCHECK(view_ || - ownership_ == views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET); - if (view_) { - Hide(); - // TODO(erg): Undo window modality here. - } - - if (!close_widget_factory_.HasWeakPtrs()) { - base::MessageLoop::current()->PostTask( - FROM_HERE, base::Bind(&NativeWidgetMojo::CloseNow, - close_widget_factory_.GetWeakPtr())); - } -} - -void NativeWidgetMojo::CloseNow() { - view_->Destroy(); -} - -void NativeWidgetMojo::Show() { - ShowWithWindowState(ui::SHOW_STATE_NORMAL); -} - -void NativeWidgetMojo::Hide() { - if (view_) - view_->SetVisible(false); -} - -void NativeWidgetMojo::ShowMaximizedWithBounds( - const gfx::Rect& restored_bounds) { - // TODO(erg): Save the restored bounds. - ShowWithWindowState(ui::SHOW_STATE_MAXIMIZED); -} - -void NativeWidgetMojo::ShowWithWindowState(ui::WindowShowState state) { - if (!view_) - return; - - // TODO(erg): Set |show_state|, if it still makes sense. - view_->SetVisible(true); - if (delegate_->CanActivate()) { - if (state != ui::SHOW_STATE_INACTIVE) - Activate(); - // SetInitialFocus() should be always be called, even for - // SHOW_STATE_INACTIVE. If the window has to stay inactive, the method will - // do the right thing. - SetInitialFocus(state); - } -} - -bool NativeWidgetMojo::IsVisible() const { - return view_ && view_->visible(); -} - -void NativeWidgetMojo::Activate() { - // TODO(erg): Need to plumb activation to the window manager here. - NOTIMPLEMENTED(); -} - -void NativeWidgetMojo::Deactivate() { - // TODO(erg): Need to plumb deactivation to the window manager here. - NOTIMPLEMENTED(); -} - -bool NativeWidgetMojo::IsActive() const { - return true; -} - -void NativeWidgetMojo::SetAlwaysOnTop(bool on_top) { - // TODO(erg): Plumb this to the window manager. - NOTIMPLEMENTED(); -} - -bool NativeWidgetMojo::IsAlwaysOnTop() const { - return false; -} - -void NativeWidgetMojo::SetVisibleOnAllWorkspaces(bool always_visible) { - // Not implemented on chromeos or for child widgets. -} - -void NativeWidgetMojo::Maximize() { - // TODO(erg): Everything about minimization/maximization should really be - // part of the window manager; these methods should be replaced with - // something like "RequestMaximize()". - NOTIMPLEMENTED(); -} - -void NativeWidgetMojo::Minimize() { - NOTIMPLEMENTED(); -} - -bool NativeWidgetMojo::IsMaximized() const { - return false; -} - -bool NativeWidgetMojo::IsMinimized() const { - return false; -} - -void NativeWidgetMojo::Restore() { - NOTIMPLEMENTED(); -} - -void NativeWidgetMojo::SetFullscreen(bool fullscreen) { - NOTIMPLEMENTED(); -} - -bool NativeWidgetMojo::IsFullscreen() const { - return false; -} - -void NativeWidgetMojo::SetOpacity(unsigned char opacity) { - // TODO(erg): Also need this on mojo::View. - if (layer()) - layer()->SetOpacity(opacity / 255.0); -} - -void NativeWidgetMojo::SetUseDragFrame(bool use_drag_frame) { - NOTIMPLEMENTED(); -} - -void NativeWidgetMojo::FlashFrame(bool flash) { - NOTIMPLEMENTED(); -} - -void NativeWidgetMojo::RunShellDrag(views::View* view, - const ui::OSExchangeData& data, - const gfx::Point& location, - int operation, - ui::DragDropTypes::DragEventSource source) { - NOTIMPLEMENTED(); -} - -void NativeWidgetMojo::SchedulePaintInRect(const gfx::Rect& rect) { - layer()->SchedulePaint(rect); -} - -void NativeWidgetMojo::SetCursor(gfx::NativeCursor cursor) { - // TODO(erg): Requires a cursor client. Is so spammy that we don't put down a - // NOTIMPLEMENTED(). -} - -bool NativeWidgetMojo::IsMouseEventsEnabled() const { - // TODO(erg): Requires a cursor client. - NOTIMPLEMENTED(); - return true; -} - -void NativeWidgetMojo::ClearNativeFocus() { - // TODO(erg): Requires an aura::client::FocusClient equivalent. -} - -gfx::Rect NativeWidgetMojo::GetWorkAreaBoundsInScreen() const { - // TODO(erg): Requires a gfx::Screen equivalent. - return gfx::Rect(); -} - -views::Widget::MoveLoopResult NativeWidgetMojo::RunMoveLoop( - const gfx::Vector2d& drag_offset, - views::Widget::MoveLoopSource source, - views::Widget::MoveLoopEscapeBehavior escape_behavior) { - // TODO(erg): This is really complicated. Requires an - // aura::client::WindowMoveClient equivalent. - NOTIMPLEMENTED(); - return views::Widget::MOVE_LOOP_CANCELED; -} - -void NativeWidgetMojo::EndMoveLoop() { - // TODO(erg): Requires an aura::client::WindowMoveClient equivalent. - NOTIMPLEMENTED(); -} - -void NativeWidgetMojo::SetVisibilityChangedAnimationsEnabled(bool value) { - NOTIMPLEMENTED(); -} - -ui::NativeTheme* NativeWidgetMojo::GetNativeTheme() const { - // TODO(erg): NativeThemeAura does not actually use aura. When we remove - // aura, this should be renamed to not be confusing. - return ui::NativeThemeAura::instance(); -} - -void NativeWidgetMojo::OnRootViewLayout() { -} - -bool NativeWidgetMojo::IsTranslucentWindowOpacitySupported() const { - return true; -} - -void NativeWidgetMojo::OnSizeConstraintsChanged() { - // TODO(erg): In the aura version, we set Can{Maximize,Minimize,Resize} - // properties on our backing window from the widget_delegate(). Figure out - // what we do policy wise here. -} - -void NativeWidgetMojo::RepostNativeEvent(gfx::NativeEvent native_event) { - // TODO(erg): Remove this method from the whole views system. The one caller - // is in WebDialogView, which I assume we'll never use in mojo. - NOTREACHED(); -} - -//////////////////////////////////////////////////////////////////////////////// -// NativeWidgetMojo, ui::EventHandler implementation: - -void NativeWidgetMojo::OnKeyEvent(ui::KeyEvent* event) { - // TODO(erg): Key event handling is a pile of hurt. Rebuilding all of this - // means dealing with the IME. For now, punt. - NOTIMPLEMENTED(); -} - -void NativeWidgetMojo::OnMouseEvent(ui::MouseEvent* event) { - DCHECK(view_); - DCHECK(view_->visible()); - if (event->type() == ui::ET_MOUSEWHEEL) { - delegate_->OnMouseEvent(event); - if (event->handled()) - return; - } - - // TODO(erg): In the aura version, we do something with the - // ToopltipManagerAura here. - delegate_->OnMouseEvent(event); -} - -void NativeWidgetMojo::OnScrollEvent(ui::ScrollEvent* event) { - delegate_->OnScrollEvent(event); -} - -void NativeWidgetMojo::OnGestureEvent(ui::GestureEvent* event) { - DCHECK(view_); - DCHECK(view_->visible() || event->IsEndingEvent()); - delegate_->OnGestureEvent(event); -} - -//////////////////////////////////////////////////////////////////////////////// -// NativeWidgetMojo, ViewObserver implementation: - -void NativeWidgetMojo::OnViewDestroying(View* view) { - view->RemoveObserver(this); - delegate_->OnNativeWidgetDestroying(); -} - -void NativeWidgetMojo::OnViewDestroyed(View* view) { - DCHECK_EQ(view, view_); - view_ = nullptr; - delegate_->OnNativeWidgetDestroyed(); - if (ownership_ == views::Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET) - delete this; -} - -void NativeWidgetMojo::OnViewBoundsChanged(View* view, - const Rect& mojo_old_bounds, - const Rect& mojo_new_bounds) { - gfx::Rect old_bounds = mojo_old_bounds.To<gfx::Rect>(); - gfx::Rect new_bounds = mojo_new_bounds.To<gfx::Rect>(); - - gfx::Size size = new_bounds.size(); - compositor_->SetScaleAndSize(1.0f, size); - layer()->SetBounds(gfx::Rect(size)); - - // Assume that if the old bounds was completely empty a move happened. This - // handles the case of a maximize animation acquiring the layer (acquiring a - // layer results in clearing the bounds). - if (old_bounds.origin() != new_bounds.origin() || - (old_bounds == gfx::Rect(0, 0, 0, 0) && !new_bounds.IsEmpty())) { - delegate_->OnNativeWidgetMove(); - } - if (old_bounds.size() != new_bounds.size()) - delegate_->OnNativeWidgetSizeChanged(new_bounds.size()); -} - -void NativeWidgetMojo::OnViewFocusChanged(View* gained_focus, - View* lost_focus) { - if (view_ == gained_focus) { - if (GetWidget()->GetInputMethod()) // Null in tests. - GetWidget()->GetInputMethod()->OnFocus(); - - // TODO(erg): We need to set mojo::View* as the gfx::NativeView. Once that - // is done, we can uncomment the line below. - // - // delegate_->OnNativeFocus(lost_focus); - } else if (view_ == lost_focus) { - // GetInputMethod() recreates the input method if it's previously been - // destroyed. If we get called during destruction, the input method will be - // gone, and creating a new one and telling it that we lost the focus will - // trigger a DCHECK (the new input method doesn't think that we have the - // focus and doesn't expect a blur). OnBlur() shouldn't be called during - // destruction unless WIDGET_OWNS_NATIVE_WIDGET is set (which is just the - // case in tests). - if (!destroying_) { - if (GetWidget()->GetInputMethod()) - GetWidget()->GetInputMethod()->OnBlur(); - } else { - DCHECK_EQ(ownership_, - views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET); - } - - // TODO(erg): We need to set mojo::View* as the gfx::NativeView. Once that - // is done, we can uncomment the line below. - // - // delegate_->OnNativeBlur(gained_focus); - } -} - -void NativeWidgetMojo::OnViewInputEvent(View* view, const EventPtr& event) { - scoped_ptr<ui::Event> ui_event(event.To<scoped_ptr<ui::Event>>()); - if (ui_event) - OnEvent(ui_event.get()); -} - -// TODO(erg): Add an OnViewActivationChanged() method and plumb that from the -// window manager through the view manager to here. - -//////////////////////////////////////////////////////////////////////////////// -// NativeWidgetMojo, LayerDelegate: - -void NativeWidgetMojo::OnPaintLayer(gfx::Canvas* canvas) { - delegate_->OnNativeWidgetPaint(canvas); -} - -void NativeWidgetMojo::OnDelegatedFrameDamage( - const gfx::Rect& damage_rect_in_dip) { - NOTIMPLEMENTED(); -} - -void NativeWidgetMojo::OnDeviceScaleFactorChanged(float device_scale_factor) { - NOTIMPLEMENTED(); -} - -base::Closure NativeWidgetMojo::PrepareForLayerBoundsChange() { - // TODO(erg): This needs a real implementation, but we don't NOTIMPLEMENTED() - // because spam. - return base::Closure(); -} - -//////////////////////////////////////////////////////////////////////////////// -// NativeWidgetMojo, protected: - -NativeWidgetMojo::~NativeWidgetMojo() { - destroying_ = true; - if (ownership_ == views::Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET) - delete delegate_; - else - CloseNow(); -} - -//////////////////////////////////////////////////////////////////////////////// -// NativeWidgetMojo, private: - -void NativeWidgetMojo::SetInitialFocus(ui::WindowShowState show_state) { - NOTIMPLEMENTED(); -} - -namespace internal { - -//////////////////////////////////////////////////////////////////////////////// -// internal::NativeWidgetPrivate, public: - -// TODO(erg): Re-implement the static NativeWidgetPrivate interface here. This -// is already implemented in NativeWidgetAura, and we can't reimplement it here -// until we delete it there. - -} // namespace internal -} // namespace mojo
diff --git a/mojo/views/native_widget_mojo.h b/mojo/views/native_widget_mojo.h deleted file mode 100644 index 221a05c..0000000 --- a/mojo/views/native_widget_mojo.h +++ /dev/null
@@ -1,198 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_WIDGET_NATIVE_WIDGET_MOJO_H_ -#define UI_VIEWS_WIDGET_NATIVE_WIDGET_MOJO_H_ - -#include "base/memory/weak_ptr.h" -#include "mojo/services/view_manager/public/cpp/view_observer.h" -#include "ui/base/cursor/cursor.h" -#include "ui/compositor/layer_delegate.h" -#include "ui/compositor/layer_owner.h" -#include "ui/views/widget/native_widget_private.h" - -namespace views { -class DropHelper; -class InputMethod; -class TooltipManager; -class NonClientFrameView; -class Widget; -namespace internal { -class InputMethodDelegate; -class NativeWidgetDelegate; -} -} - -namespace ui { -class InputMethod; -} - -namespace mojo { -class Shell; -class SurfaceContextFactory; -class View; - -// A NativeWidget which interacts with a mojo::View. -class NativeWidgetMojo - : public views::internal::NativeWidgetPrivate, - public ui::EventHandler, - public ViewObserver, - public ui::LayerOwner, - public ui::LayerDelegate { - public: - NativeWidgetMojo(views::internal::NativeWidgetDelegate* delegate, - mojo::Shell* shell, - mojo::View* view); - - // Overridden from internal::NativeWidgetPrivate: - virtual void InitNativeWidget( - const views::Widget::InitParams& params) override; - virtual views::NonClientFrameView* CreateNonClientFrameView() override; - virtual bool ShouldUseNativeFrame() const override; - virtual bool ShouldWindowContentsBeTransparent() const override; - virtual void FrameTypeChanged() override; - virtual views::Widget* GetWidget() override; - virtual const views::Widget* GetWidget() const override; - virtual gfx::NativeView GetNativeView() const override; - virtual gfx::NativeWindow GetNativeWindow() const override; - virtual views::Widget* GetTopLevelWidget() override; - virtual const ui::Compositor* GetCompositor() const override; - virtual ui::Compositor* GetCompositor() override; - virtual ui::Layer* GetLayer() override; - virtual void ReorderNativeViews() override; - virtual void ViewRemoved(views::View* view) override; - virtual void SetNativeWindowProperty(const char* name, void* value) override; - virtual void* GetNativeWindowProperty(const char* name) const override; - virtual views::TooltipManager* GetTooltipManager() const override; - virtual void SetCapture() override; - virtual void ReleaseCapture() override; - virtual bool HasCapture() const override; - virtual views::InputMethod* CreateInputMethod() override; - virtual views::internal::InputMethodDelegate* GetInputMethodDelegate() - override; - virtual ui::InputMethod* GetHostInputMethod() override; - virtual void CenterWindow(const gfx::Size& size) override; - virtual void GetWindowPlacement( - gfx::Rect* bounds, - ui::WindowShowState* maximized) const override; - virtual bool SetWindowTitle(const base::string16& title) override; - virtual void SetWindowIcons(const gfx::ImageSkia& window_icon, - const gfx::ImageSkia& app_icon) override; - virtual void InitModalType(ui::ModalType modal_type) override; - virtual gfx::Rect GetWindowBoundsInScreen() const override; - virtual gfx::Rect GetClientAreaBoundsInScreen() const override; - virtual gfx::Rect GetRestoredBounds() const override; - virtual void SetBounds(const gfx::Rect& bounds) override; - virtual void SetSize(const gfx::Size& size) override; - virtual void StackAbove(gfx::NativeView native_view) override; - virtual void StackAtTop() override; - virtual void StackBelow(gfx::NativeView native_view) override; - virtual void SetShape(gfx::NativeRegion shape) override; - virtual void Close() override; - virtual void CloseNow() override; - virtual void Show() override; - virtual void Hide() override; - virtual void ShowMaximizedWithBounds( - const gfx::Rect& restored_bounds) override; - virtual void ShowWithWindowState(ui::WindowShowState state) override; - virtual bool IsVisible() const override; - virtual void Activate() override; - virtual void Deactivate() override; - virtual bool IsActive() const override; - virtual void SetAlwaysOnTop(bool always_on_top) override; - virtual bool IsAlwaysOnTop() const override; - virtual void SetVisibleOnAllWorkspaces(bool always_visible) override; - virtual void Maximize() override; - virtual void Minimize() override; - virtual bool IsMaximized() const override; - virtual bool IsMinimized() const override; - virtual void Restore() override; - virtual void SetFullscreen(bool fullscreen) override; - virtual bool IsFullscreen() const override; - virtual void SetOpacity(unsigned char opacity) override; - virtual void SetUseDragFrame(bool use_drag_frame) override; - virtual void FlashFrame(bool flash_frame) override; - virtual void RunShellDrag(views::View* view, - const ui::OSExchangeData& data, - const gfx::Point& location, - int operation, - ui::DragDropTypes::DragEventSource source) override; - virtual void SchedulePaintInRect(const gfx::Rect& rect) override; - virtual void SetCursor(gfx::NativeCursor cursor) override; - virtual bool IsMouseEventsEnabled() const override; - virtual void ClearNativeFocus() override; - virtual gfx::Rect GetWorkAreaBoundsInScreen() const override; - virtual views::Widget::MoveLoopResult RunMoveLoop( - const gfx::Vector2d& drag_offset, - views::Widget::MoveLoopSource source, - views::Widget::MoveLoopEscapeBehavior escape_behavior) override; - virtual void EndMoveLoop() override; - virtual void SetVisibilityChangedAnimationsEnabled(bool value) override; - virtual ui::NativeTheme* GetNativeTheme() const override; - virtual void OnRootViewLayout() override; - virtual bool IsTranslucentWindowOpacitySupported() const override; - virtual void OnSizeConstraintsChanged() override; - virtual void RepostNativeEvent(gfx::NativeEvent native_event) override; - - // Overridden from ui::EventHandler: - void OnKeyEvent(ui::KeyEvent* event) override; - void OnMouseEvent(ui::MouseEvent* event) override; - void OnScrollEvent(ui::ScrollEvent* event) override; - void OnGestureEvent(ui::GestureEvent* event) override; - - // TODO(erg): Plumb activation events from the window manager to here. We - // should receive the equivalent of OnWindowActivated() and OnWindowFocused() - // here. - - // TODO(erg): Handle drag/drop. Maybe an equivalent of - // aura::client::DragDropDelegate? Or a different design? - - // Overridden from ViewObserver: - void OnViewDestroying(View* view) override; - void OnViewDestroyed(View* view) override; - void OnViewBoundsChanged(View* view, - const Rect& old_bounds, - const Rect& new_bounds) override; - void OnViewFocusChanged(View* gained_focus, View* lost_focus) override; - void OnViewInputEvent(View* view, const EventPtr& event) override; - - // Overridden from LayerDelegate: - void OnPaintLayer(gfx::Canvas* canvas) override; - void OnDelegatedFrameDamage(const gfx::Rect& damage_rect_in_dip) override; - void OnDeviceScaleFactorChanged(float device_scale_factor) override; - base::Closure PrepareForLayerBoundsChange() override; - - protected: - virtual ~NativeWidgetMojo(); - - views::internal::NativeWidgetDelegate* delegate() { return delegate_; } - - private: - class ActiveWindowObserver; - - void SetInitialFocus(ui::WindowShowState show_state); - - views::internal::NativeWidgetDelegate* delegate_; - - // See class documentation for Widget in widget.h for a note about ownership. - views::Widget::InitParams::Ownership ownership_; - - mojo::View* view_; - - // Are we in the destructor? - bool destroying_; - - scoped_ptr<SurfaceContextFactory> context_factory_; - scoped_ptr<ui::Compositor> compositor_; - - // The following factory is used for calls to close the NativeWidgetMojo - // instance. - base::WeakPtrFactory<NativeWidgetMojo> close_widget_factory_; - - DISALLOW_COPY_AND_ASSIGN(NativeWidgetMojo); -}; - -} // namespace mojo - -#endif // UI_VIEWS_WIDGET_NATIVE_WIDGET_MOJO_H_
diff --git a/mojo/views/native_widget_view_manager.cc b/mojo/views/native_widget_view_manager.cc deleted file mode 100644 index e463fda..0000000 --- a/mojo/views/native_widget_view_manager.cc +++ /dev/null
@@ -1,164 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "mojo/views/native_widget_view_manager.h" - -#include "mojo/aura/window_tree_host_mojo.h" -#include "mojo/converters/geometry/geometry_type_converters.h" -#include "mojo/converters/input_events/input_events_type_converters.h" -#include "ui/aura/client/aura_constants.h" -#include "ui/aura/client/default_capture_client.h" -#include "ui/aura/window.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/base/ime/input_method.h" -#include "ui/base/ime/input_method_base.h" -#include "ui/base/ime/input_method_delegate.h" -#include "ui/base/ime/input_method_factory.h" -#include "ui/base/ime/text_input_client.h" -#include "ui/wm/core/base_focus_rules.h" -#include "ui/wm/core/capture_controller.h" -#include "ui/wm/core/focus_controller.h" - -#if defined(OS_LINUX) -#include "mojo/views/input_method_mojo_linux.h" -#endif - -namespace mojo { -namespace { - -// TODO: figure out what this should be. -class FocusRulesImpl : public wm::BaseFocusRules { - public: - FocusRulesImpl() {} - virtual ~FocusRulesImpl() {} - - virtual bool SupportsChildActivation(aura::Window* window) const override { - return true; - } - - private: - DISALLOW_COPY_AND_ASSIGN(FocusRulesImpl); -}; - -class MinimalInputEventFilter : public ui::internal::InputMethodDelegate, - public ui::EventHandler { - public: - explicit MinimalInputEventFilter(aura::Window* root) - : root_(root) { - ui::InitializeInputMethodForTesting(); -#if defined(OS_LINUX) - input_method_.reset(new InputMethodMojoLinux(this)); -#else - input_method_ = ui::CreateInputMethod(this, gfx::kNullAcceleratedWidget); -#endif - input_method_->Init(true); - root_->AddPreTargetHandler(this); - root_->SetProperty(aura::client::kRootWindowInputMethodKey, - input_method_.get()); - } - - virtual ~MinimalInputEventFilter() { - root_->RemovePreTargetHandler(this); - root_->SetProperty(aura::client::kRootWindowInputMethodKey, - static_cast<ui::InputMethod*>(NULL)); - } - - private: - // ui::EventHandler: - virtual void OnKeyEvent(ui::KeyEvent* event) override { - // See the comment in InputMethodEventFilter::OnKeyEvent() for details. - if (event->IsTranslated()) { - event->SetTranslated(false); - } else { - if (input_method_->DispatchKeyEvent(*event)) - event->StopPropagation(); - } - } - - // ui::internal::InputMethodDelegate: - virtual bool DispatchKeyEventPostIME(const ui::KeyEvent& event) override { - // See the comment in InputMethodEventFilter::DispatchKeyEventPostIME() for - // details. - ui::KeyEvent aura_event(event); - aura_event.SetTranslated(true); - ui::EventDispatchDetails details = - root_->GetHost()->dispatcher()->OnEventFromSource(&aura_event); - return aura_event.handled() || details.dispatcher_destroyed; - } - - aura::Window* root_; - scoped_ptr<ui::InputMethod> input_method_; - - DISALLOW_COPY_AND_ASSIGN(MinimalInputEventFilter); -}; - -} // namespace - -NativeWidgetViewManager::NativeWidgetViewManager( - views::internal::NativeWidgetDelegate* delegate, - Shell* shell, - View* view) - : NativeWidgetAura(delegate), view_(view) { - view_->AddObserver(this); - window_tree_host_.reset(new WindowTreeHostMojo(shell, view_)); - window_tree_host_->InitHost(); - - ime_filter_.reset( - new MinimalInputEventFilter(window_tree_host_->window())); - - focus_client_.reset(new wm::FocusController(new FocusRulesImpl)); - - aura::client::SetFocusClient(window_tree_host_->window(), - focus_client_.get()); - aura::client::SetActivationClient(window_tree_host_->window(), - focus_client_.get()); - window_tree_host_->window()->AddPreTargetHandler(focus_client_.get()); - - capture_client_.reset( - new aura::client::DefaultCaptureClient(window_tree_host_->window())); -} - -NativeWidgetViewManager::~NativeWidgetViewManager() { - if (view_) - view_->RemoveObserver(this); -} - -void NativeWidgetViewManager::InitNativeWidget( - const views::Widget::InitParams& in_params) { - views::Widget::InitParams params(in_params); - params.parent = window_tree_host_->window(); - NativeWidgetAura::InitNativeWidget(params); -} - -void NativeWidgetViewManager::OnWindowVisibilityChanged(aura::Window* window, - bool visible) { - view_->SetVisible(visible); - // NOTE: We could also update aura::Window's visibility when the View's - // visibilty changes, but this code isn't going to be around for very long so - // I'm not bothering. -} - -void NativeWidgetViewManager::OnViewDestroyed(View* view) { - DCHECK_EQ(view, view_); - view->RemoveObserver(this); - view_ = NULL; - // TODO(sky): WindowTreeHostMojo assumes the View outlives it. - // NativeWidgetViewManager needs to deal, likely by deleting this. -} - -void NativeWidgetViewManager::OnViewBoundsChanged(View* view, - const Rect& old_bounds, - const Rect& new_bounds) { - gfx::Rect view_rect = view->bounds().To<gfx::Rect>(); - GetWidget()->SetBounds(gfx::Rect(view_rect.size())); -} - -void NativeWidgetViewManager::OnViewInputEvent(View* view, - const EventPtr& event) { - scoped_ptr<ui::Event> ui_event(event.To<scoped_ptr<ui::Event> >()); - if (ui_event) - window_tree_host_->SendEventToProcessor(ui_event.get()); -} - -} // namespace mojo
diff --git a/mojo/views/native_widget_view_manager.h b/mojo/views/native_widget_view_manager.h deleted file mode 100644 index bfd43cf..0000000 --- a/mojo/views/native_widget_view_manager.h +++ /dev/null
@@ -1,67 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MOJO_VIEWS_NATIVE_WIDGET_VIEW_MANAGER_H_ -#define MOJO_VIEWS_NATIVE_WIDGET_VIEW_MANAGER_H_ - -#include "mojo/services/view_manager/public/cpp/view_observer.h" -#include "ui/views/widget/native_widget_aura.h" - -namespace aura { -namespace client { -class DefaultCaptureClient; -} -} - -namespace ui { -namespace internal { -class InputMethodDelegate; -} -} - -namespace wm { -class FocusController; -} - -namespace mojo { - -class Shell; -class WindowTreeHostMojo; - -class NativeWidgetViewManager : public views::NativeWidgetAura, - public ViewObserver { - public: - NativeWidgetViewManager(views::internal::NativeWidgetDelegate* delegate, - Shell* shell, - View* view); - ~NativeWidgetViewManager() override; - - private: - // Overridden from internal::NativeWidgetAura: - void InitNativeWidget(const views::Widget::InitParams& in_params) override; - void OnWindowVisibilityChanged(aura::Window* window, bool visible) override; - - // ViewObserver: - void OnViewDestroyed(View* view) override; - void OnViewBoundsChanged(View* view, - const Rect& old_bounds, - const Rect& new_bounds) override; - void OnViewInputEvent(View* view, const EventPtr& event) override; - - scoped_ptr<WindowTreeHostMojo> window_tree_host_; - - scoped_ptr<wm::FocusController> focus_client_; - - scoped_ptr<ui::internal::InputMethodDelegate> ime_filter_; - - View* view_; - - scoped_ptr<aura::client::DefaultCaptureClient> capture_client_; - - DISALLOW_COPY_AND_ASSIGN(NativeWidgetViewManager); -}; - -} // namespace mojo - -#endif // MOJO_VIEWS_NATIVE_WIDGET_VIEW_MANAGER_H_
diff --git a/mojo/views/views_init.cc b/mojo/views/views_init.cc deleted file mode 100644 index fa2ef54..0000000 --- a/mojo/views/views_init.cc +++ /dev/null
@@ -1,54 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "mojo/views/views_init.h" - -#include "base/i18n/icu_util.h" -#include "base/lazy_instance.h" -#include "base/path_service.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/base/ui_base_paths.h" - -namespace mojo { -namespace { - -// Used to ensure we only init once. -class Setup { - public: - Setup() { - base::i18n::InitializeICU(); - - ui::RegisterPathProvider(); - - base::FilePath ui_test_pak_path; - CHECK(PathService::Get(ui::UI_TEST_PAK, &ui_test_pak_path)); - ui::ResourceBundle::InitSharedInstanceWithPakPath(ui_test_pak_path); - - // There is a bunch of static state in gfx::Font, by running this now, - // before any other apps load, we ensure all the state is set up. - gfx::Font(); - } - - ~Setup() { - } - - private: - DISALLOW_COPY_AND_ASSIGN(Setup); -}; - -static base::LazyInstance<Setup>::Leaky setup = LAZY_INSTANCE_INITIALIZER; - -} // namespace - -void InitViews() { - setup.Get(); -} -ViewsInit::ViewsInit() { - InitViews(); -} - -ViewsInit::~ViewsInit() { -} - -} // namespace mojo
diff --git a/mojo/views/views_init.h b/mojo/views/views_init.h deleted file mode 100644 index ad3b95e..0000000 --- a/mojo/views/views_init.h +++ /dev/null
@@ -1,26 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MOJO_VIEWS_VIEWS_INIT_H_ -#define MOJO_VIEWS_VIEWS_INIT_H_ - -#include "mojo/aura/aura_init.h" - -namespace mojo { - -// Sets up necessary state for views when run with the viewmanager. -class ViewsInit { - public: - ViewsInit(); - ~ViewsInit(); - - private: - AuraInit aura_init_; - - DISALLOW_COPY_AND_ASSIGN(ViewsInit); -}; - -} // namespace mojo - -#endif // MOJO_VIEWS_VIEWS_INIT_H_
diff --git a/services/native_viewport/BUILD.gn b/services/native_viewport/BUILD.gn index f7f7308..9622465 100644 --- a/services/native_viewport/BUILD.gn +++ b/services/native_viewport/BUILD.gn
@@ -62,7 +62,6 @@ "platform_viewport_android.h", "platform_viewport_headless.cc", "platform_viewport_headless.h", - "platform_viewport_ozone.cc", "platform_viewport_stub.cc", "platform_viewport_win.cc", "platform_viewport_x11.cc", @@ -74,10 +73,6 @@ sources -= [ "platform_viewport_stub.cc" ] } - if (!use_ozone) { - sources -= [ "platform_viewport_ozone.cc" ] - } - deps = [ "//base", "//cc/surfaces",
diff --git a/services/native_viewport/platform_viewport_ozone.cc b/services/native_viewport/platform_viewport_ozone.cc deleted file mode 100644 index 1ce2fa3..0000000 --- a/services/native_viewport/platform_viewport_ozone.cc +++ /dev/null
@@ -1,97 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "services/native_viewport/platform_viewport.h" - -#include "mojo/converters/geometry/geometry_type_converters.h" -#include "ui/events/event.h" -#include "ui/events/platform/platform_event_dispatcher.h" -#include "ui/events/platform/platform_event_source.h" -#include "ui/ozone/public/cursor_factory_ozone.h" -#include "ui/ozone/public/ozone_platform.h" -#include "ui/ozone/public/surface_factory_ozone.h" -#include "ui/platform_window/platform_window.h" -#include "ui/platform_window/platform_window_delegate.h" - -namespace native_viewport { - -// TODO(spang): Deduplicate with PlatformViewportX11.. but there's a hack -// in there that prevents this. -class PlatformViewportOzone : public PlatformViewport, - public ui::PlatformWindowDelegate { - public: - explicit PlatformViewportOzone(Delegate* delegate) : delegate_(delegate) { - ui::OzonePlatform::InitializeForUI(); - } - - virtual ~PlatformViewportOzone() { - // Destroy the platform-window while |this| is still alive. - platform_window_.reset(); - } - - private: - // Overridden from PlatformViewport: - virtual void Init(const gfx::Rect& bounds) override { - platform_window_ = - ui::OzonePlatform::GetInstance()->CreatePlatformWindow(this, bounds); - } - - virtual void Show() override { platform_window_->Show(); } - - virtual void Hide() override { platform_window_->Hide(); } - - virtual void Close() override { platform_window_->Close(); } - - virtual gfx::Size GetSize() override { - return platform_window_->GetBounds().size(); - } - - virtual void SetBounds(const gfx::Rect& bounds) override { - platform_window_->SetBounds(bounds); - } - - virtual void SetCapture() override { platform_window_->SetCapture(); } - - virtual void ReleaseCapture() override { platform_window_->ReleaseCapture(); } - - // ui::PlatformWindowDelegate: - virtual void OnBoundsChanged(const gfx::Rect& new_bounds) override { - mojo::ViewportMetricsPtr metrics = mojo::ViewportMetrics::New(); - metrics->size = new_bounds.size(); - delegate_->OnMetricsChanged(metrics.Pass()); - } - - virtual void OnDamageRect(const gfx::Rect& damaged_region) override {} - - virtual void DispatchEvent(ui::Event* event) override { - delegate_->OnEvent(event); - } - - virtual void OnCloseRequest() override { platform_window_->Close(); } - - virtual void OnClosed() override { delegate_->OnDestroyed(); } - - virtual void OnWindowStateChanged(ui::PlatformWindowState state) override {} - - virtual void OnLostCapture() override {} - - virtual void OnAcceleratedWidgetAvailable( - gfx::AcceleratedWidget widget) override { - delegate_->OnAcceleratedWidgetAvailable(widget); - } - - virtual void OnActivationChanged(bool active) override {} - - scoped_ptr<ui::PlatformWindow> platform_window_; - Delegate* delegate_; - - DISALLOW_COPY_AND_ASSIGN(PlatformViewportOzone); -}; - -// static -scoped_ptr<PlatformViewport> PlatformViewport::Create(Delegate* delegate) { - return make_scoped_ptr(new PlatformViewportOzone(delegate)); -} - -} // namespace native_viewport
diff --git a/skia/ext/platform_canvas_unittest.cc b/skia/ext/platform_canvas_unittest.cc index 9ab5667..a7dfb69 100644 --- a/skia/ext/platform_canvas_unittest.cc +++ b/skia/ext/platform_canvas_unittest.cc
@@ -207,8 +207,6 @@ EXPECT_TRUE(VerifyBlackRect(*canvas, kLayerX, kLayerY, kLayerW, kLayerH)); } -#if !defined(USE_AURA) // http://crbug.com/154358 - // Test native clipping. TEST(PlatformCanvas, ClipRegion) { // Initialize a white canvas @@ -234,8 +232,6 @@ EXPECT_TRUE(VerifyCanvasColor(*canvas, SK_ColorWHITE)); } -#endif // !defined(USE_AURA) - // Test the layers get filled properly by native rendering. TEST(PlatformCanvas, FillLayer) { // Create the canvas initialized to opaque white. @@ -293,8 +289,6 @@ EXPECT_TRUE(VerifyBlackRect(*canvas, kInnerX, kInnerY, kInnerW, kInnerH)); } -#if !defined(USE_AURA) // http://crbug.com/154358 - // Test that translation + make layer works properly. TEST(PlatformCanvas, TranslateLayer) { // Create the canvas initialized to opaque white. @@ -395,8 +389,6 @@ #endif } -#endif // #if !defined(USE_AURA) - TEST(PlatformBitmapTest, PlatformBitmap) { const int kWidth = 400; const int kHeight = 300;
diff --git a/skia/ext/vector_canvas_unittest.cc b/skia/ext/vector_canvas_unittest.cc index d3ad9a0..d2cbf29 100644 --- a/skia/ext/vector_canvas_unittest.cc +++ b/skia/ext/vector_canvas_unittest.cc
@@ -450,8 +450,6 @@ //////////////////////////////////////////////////////////////////////////////// // Actual tests -#if !defined(USE_AURA) // http://crbug.com/154358 - TEST_F(VectorCanvasTest, BasicDrawing) { EXPECT_EQ(Image(*vcanvas_).PercentageDifferent(Image(*pcanvas_)), 0.) << L"clean"; @@ -965,6 +963,4 @@ } } -#endif // !defined(USE_AURA) - } // namespace skia
diff --git a/sky/engine/testing/platform/BUILD.gn b/sky/engine/testing/platform/BUILD.gn index 3086098..2cc55d6 100644 --- a/sky/engine/testing/platform/BUILD.gn +++ b/sky/engine/testing/platform/BUILD.gn
@@ -16,7 +16,6 @@ "//base", "//net", "//sky/engine", - "//ui/native_theme", "//url", "//skia", ]
diff --git a/sky/viewer/BUILD.gn b/sky/viewer/BUILD.gn index 76406d7..f1f2453 100644 --- a/sky/viewer/BUILD.gn +++ b/sky/viewer/BUILD.gn
@@ -64,7 +64,6 @@ "//sky/services/inspector:bindings", "//sky/services/testing:bindings", "//third_party/icu", - "//ui/native_theme", "//url", ] }
diff --git a/tools/gritsettings/resource_ids b/tools/gritsettings/resource_ids index efd5760..31e33d4 100644 --- a/tools/gritsettings/resource_ids +++ b/tools/gritsettings/resource_ids
@@ -248,7 +248,6 @@ "android_webview/java/strings/android_webview_strings.grd": {}, "chrome/android/java/strings/android_chrome_strings.grd": {}, "content/public/android/java/strings/android_content_strings.grd": {}, - "ui/accessibility/extensions/strings/accessibility_extensions_strings.grd": {}, "ui/android/java/strings/android_ui_strings.grd": {}, # Resource ids starting at 31000 are reserved for projects built on Chromium.
diff --git a/tools/xdisplaycheck/xdisplaycheck.cc b/tools/xdisplaycheck/xdisplaycheck.cc index 6623153..a5a447c 100644 --- a/tools/xdisplaycheck/xdisplaycheck.cc +++ b/tools/xdisplaycheck/xdisplaycheck.cc
@@ -16,10 +16,6 @@ #include <time.h> #include <X11/Xlib.h> -#if defined(USE_AURA) -#include <X11/extensions/XInput2.h> -#endif - void Sleep(int duration_ms) { struct timespec sleep_time, remaining; @@ -77,33 +73,6 @@ fprintf(stderr, "Connected after %d retries\n", tries); -#if defined(USE_AURA) - // Check for XInput2 - int opcode, event, err; - if (!XQueryExtension(scoped_display.display(), "XInputExtension", &opcode, - &event, &err)) { - fprintf(stderr, - "Failed to get XInputExtension on %s.\n", XDisplayName(NULL)); - return -2; - } - - int major = 2, minor = 0; - if (XIQueryVersion(scoped_display.display(), &major, &minor) == BadRequest) { - fprintf(stderr, - "Server does not have XInput2 on %s.\n", XDisplayName(NULL)); - return -3; - } - - // Ask for the list of devices. This can cause some Xvfb to crash. - int count = 0; - XIDeviceInfo* devices = - XIQueryDevice(scoped_display.display(), XIAllDevices, &count); - if (devices) - XIFreeDeviceInfo(devices); - - fprintf(stderr, - "XInput2 verified initially sane on %s.\n", XDisplayName(NULL)); -#endif return 0; }
diff --git a/ui/accessibility/BUILD.gn b/ui/accessibility/BUILD.gn deleted file mode 100644 index 80c4000..0000000 --- a/ui/accessibility/BUILD.gn +++ /dev/null
@@ -1,71 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -component("accessibility") { - sources = [ - "ax_enums.cc", - "ax_enums.h", - "ax_node.cc", - "ax_node.h", - "ax_node_data.cc", - "ax_node_data.h", - "ax_serializable_tree.cc", - "ax_serializable_tree.h", - "ax_text_utils.cc", - "ax_text_utils.h", - "ax_tree.cc", - "ax_tree.h", - "ax_tree_serializer.cc", - "ax_tree_serializer.h", - "ax_tree_source.h", - "ax_tree_update.cc", - "ax_tree_update.h", - "ax_view_state.cc", - "ax_view_state.h", - "platform/ax_platform_node.cc", - "platform/ax_platform_node.h", - "platform/ax_platform_node_base.cc", - "platform/ax_platform_node_base.h", - "platform/ax_platform_node_delegate.h", - "platform/ax_platform_node_mac.h", - "platform/ax_platform_node_mac.mm", - ] - - defines = [ "ACCESSIBILITY_IMPLEMENTATION" ] - - public_deps = [ - "//base", - "//ui/gfx", - "//ui/gfx/geometry", - ] -} - -source_set("test_support") { - sources = [ - "tree_generator.cc", - "tree_generator.h", - ] - - deps = [ - ":accessibility", - ] -} - -test("accessibility_unittests") { - sources = [ - "ax_generated_tree_unittest.cc", - "ax_tree_serializer_unittest.cc", - "ax_tree_unittest.cc", - ] - - deps = [ - ":accessibility", - ":test_support", - "//base", - "//base/test:run_all_unittests", - "//testing/gtest", - "//ui/gfx", - "//ui/gfx/geometry", - ] -}
diff --git a/ui/accessibility/DEPS b/ui/accessibility/DEPS deleted file mode 100644 index b273ae3..0000000 --- a/ui/accessibility/DEPS +++ /dev/null
@@ -1,3 +0,0 @@ -include_rules = [ - "+ui/gfx", -]
diff --git a/ui/accessibility/OWNERS b/ui/accessibility/OWNERS deleted file mode 100644 index 2c197f6..0000000 --- a/ui/accessibility/OWNERS +++ /dev/null
@@ -1,3 +0,0 @@ -dmazzoni@chromium.org -dtseng@chromium.org -aboxhall@chromium.org
diff --git a/ui/accessibility/accessibility.gyp b/ui/accessibility/accessibility.gyp deleted file mode 100644 index 02eec8c..0000000 --- a/ui/accessibility/accessibility.gyp +++ /dev/null
@@ -1,84 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -{ - 'variables': { - 'chromium_code': 1, - }, - - 'targets': [ - { - 'target_name': 'accessibility', - 'type': '<(component)', - 'hard_dependency': 1, - 'dependencies': [ - '../../base/base.gyp:base', - '../gfx/gfx.gyp:gfx', - '../gfx/gfx.gyp:gfx_geometry', - ], - 'defines': [ - 'ACCESSIBILITY_IMPLEMENTATION', - ], - 'sources': [ - # All .cc, .h under accessibility, except unittests - 'ax_enums.cc', - 'ax_enums.h', - 'ax_node.cc', - 'ax_node.h', - 'ax_node_data.cc', - 'ax_node_data.h', - 'ax_serializable_tree.cc', - 'ax_serializable_tree.h', - 'ax_text_utils.cc', - 'ax_text_utils.h', - 'ax_tree.cc', - 'ax_tree.h', - 'ax_tree_serializer.cc', - 'ax_tree_serializer.h', - 'ax_tree_source.h', - 'ax_tree_update.cc', - 'ax_tree_update.h', - 'ax_view_state.cc', - 'ax_view_state.h', - 'platform/ax_platform_node.cc', - 'platform/ax_platform_node.h', - 'platform/ax_platform_node_base.cc', - 'platform/ax_platform_node_base.h', - 'platform/ax_platform_node_delegate.h', - 'platform/ax_platform_node_mac.h', - 'platform/ax_platform_node_mac.mm', - ] - }, - { - 'target_name': 'accessibility_test_support', - 'type': 'static_library', - 'dependencies': [ - '../../base/base.gyp:base', - 'accessibility' - ], - 'sources': [ - 'tree_generator.cc', - 'tree_generator.h' - ] - }, - { - 'target_name': 'accessibility_unittests', - 'type': 'executable', - 'dependencies': [ - '../../base/base.gyp:base', - '../../base/base.gyp:run_all_unittests', - '../../testing/gtest.gyp:gtest', - '../gfx/gfx.gyp:gfx', - '../gfx/gfx.gyp:gfx_geometry', - 'accessibility', - 'accessibility_test_support', - ], - 'sources': [ - 'ax_generated_tree_unittest.cc', - 'ax_tree_serializer_unittest.cc', - 'ax_tree_unittest.cc', - ] - }, - ], -}
diff --git a/ui/accessibility/ax_enums.cc b/ui/accessibility/ax_enums.cc deleted file mode 100644 index 281a102..0000000 --- a/ui/accessibility/ax_enums.cc +++ /dev/null
@@ -1,945 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/accessibility/ax_enums.h" - -#include "base/logging.h" - -namespace ui { - -std::string ToString(AXEvent enum_param) { - switch (enum_param) { - case AX_EVENT_ACTIVEDESCENDANTCHANGED: - return "activedescendantchanged"; - case AX_EVENT_ALERT: - return "alert"; - case AX_EVENT_ARIA_ATTRIBUTE_CHANGED: - return "ariaAttributeChanged"; - case AX_EVENT_AUTOCORRECTION_OCCURED: - return "autocorrectionOccured"; - case AX_EVENT_BLUR: - return "blur"; - case AX_EVENT_CHECKED_STATE_CHANGED: - return "checkedStateChanged"; - case AX_EVENT_CHILDREN_CHANGED: - return "childrenChanged"; - case AX_EVENT_FOCUS: - return "focus"; - case AX_EVENT_HIDE: - return "hide"; - case AX_EVENT_HOVER: - return "hover"; - case AX_EVENT_INVALID_STATUS_CHANGED: - return "invalidStatusChanged"; - case AX_EVENT_LAYOUT_COMPLETE: - return "layoutComplete"; - case AX_EVENT_LIVE_REGION_CHANGED: - return "liveRegionChanged"; - case AX_EVENT_LOAD_COMPLETE: - return "loadComplete"; - case AX_EVENT_LOCATION_CHANGED: - return "locationChanged"; - case AX_EVENT_MENU_END: - return "menuEnd"; - case AX_EVENT_MENU_LIST_ITEM_SELECTED: - return "menuListItemSelected"; - case AX_EVENT_MENU_LIST_VALUE_CHANGED: - return "menuListValueChanged"; - case AX_EVENT_MENU_POPUP_END: - return "menuPopupEnd"; - case AX_EVENT_MENU_POPUP_START: - return "menuPopupStart"; - case AX_EVENT_MENU_START: - return "menuStart"; - case AX_EVENT_ROW_COLLAPSED: - return "rowCollapsed"; - case AX_EVENT_ROW_COUNT_CHANGED: - return "rowCountChanged"; - case AX_EVENT_ROW_EXPANDED: - return "rowExpanded"; - case AX_EVENT_SCROLL_POSITION_CHANGED: - return "scrollPositionChanged"; - case AX_EVENT_SCROLLED_TO_ANCHOR: - return "scrolledToAnchor"; - case AX_EVENT_SELECTED_CHILDREN_CHANGED: - return "selectedChildrenChanged"; - case AX_EVENT_SELECTION: - return "selection"; - case AX_EVENT_SELECTION_ADD: - return "selectionAdd"; - case AX_EVENT_SELECTION_REMOVE: - return "selectionRemove"; - case AX_EVENT_SHOW: - return "show"; - case AX_EVENT_TEXT_CHANGED: - return "textChanged"; - case AX_EVENT_TEXT_SELECTION_CHANGED: - return "textSelectionChanged"; - case AX_EVENT_VALUE_CHANGED: - return "valueChanged"; - case AX_EVENT_NONE: - return ""; - } - NOTREACHED(); - return ""; -} - -AXEvent ParseAXEvent(const std::string& enum_string) { - if (enum_string == "activedescendantchanged") - return AX_EVENT_ACTIVEDESCENDANTCHANGED; - if (enum_string == "alert") return AX_EVENT_ALERT; - if (enum_string == "aria_attribute_changed") - return AX_EVENT_ARIA_ATTRIBUTE_CHANGED; - if (enum_string == "autocorrection_occured") - return AX_EVENT_AUTOCORRECTION_OCCURED; - if (enum_string == "blur") return AX_EVENT_BLUR; - if (enum_string == "checked_state_changed") - return AX_EVENT_CHECKED_STATE_CHANGED; - if (enum_string == "children_changed") return AX_EVENT_CHILDREN_CHANGED; - if (enum_string == "focus") return AX_EVENT_FOCUS; - if (enum_string == "hide") return AX_EVENT_HIDE; - if (enum_string == "hover") return AX_EVENT_HOVER; - if (enum_string == "invalid_status_changed") - return AX_EVENT_INVALID_STATUS_CHANGED; - if (enum_string == "layout_complete") return AX_EVENT_LAYOUT_COMPLETE; - if (enum_string == "live_region_changed") return AX_EVENT_LIVE_REGION_CHANGED; - if (enum_string == "load_complete") return AX_EVENT_LOAD_COMPLETE; - if (enum_string == "location_changed") return AX_EVENT_LOCATION_CHANGED; - if (enum_string == "menu_end") return AX_EVENT_MENU_END; - if (enum_string == "menu_list_item_selected") - return AX_EVENT_MENU_LIST_ITEM_SELECTED; - if (enum_string == "menu_list_value_changed") - return AX_EVENT_MENU_LIST_VALUE_CHANGED; - if (enum_string == "menu_popup_end") return AX_EVENT_MENU_POPUP_END; - if (enum_string == "menu_popup_start") return AX_EVENT_MENU_POPUP_START; - if (enum_string == "menu_start") return AX_EVENT_MENU_START; - if (enum_string == "row_collapsed") return AX_EVENT_ROW_COLLAPSED; - if (enum_string == "row_count_changed") return AX_EVENT_ROW_COUNT_CHANGED; - if (enum_string == "row_expanded") return AX_EVENT_ROW_EXPANDED; - if (enum_string == "scroll_position_changed") - return AX_EVENT_SCROLL_POSITION_CHANGED; - if (enum_string == "scrolled_to_anchor") return AX_EVENT_SCROLLED_TO_ANCHOR; - if (enum_string == "selected_children_changed") - return AX_EVENT_SELECTED_CHILDREN_CHANGED; - if (enum_string == "selection") return AX_EVENT_SELECTION; - if (enum_string == "selection_add") return AX_EVENT_SELECTION_ADD; - if (enum_string == "selection_remove") return AX_EVENT_SELECTION_REMOVE; - if (enum_string == "show") return AX_EVENT_SHOW; - if (enum_string == "text_changed") return AX_EVENT_TEXT_CHANGED; - if (enum_string == "text_selection_changed") - return AX_EVENT_TEXT_SELECTION_CHANGED; - if (enum_string == "value_changed") return AX_EVENT_VALUE_CHANGED; - return AX_EVENT_NONE; -} - -std::string ToString(AXRole enum_param) { - switch (enum_param) { - case AX_ROLE_ALERT_DIALOG: - return "alertDialog"; - case AX_ROLE_ALERT: - return "alert"; - case AX_ROLE_ANNOTATION: - return "annotation"; - case AX_ROLE_APPLICATION: - return "application"; - case AX_ROLE_ARTICLE: - return "article"; - case AX_ROLE_BANNER: - return "banner"; - case AX_ROLE_BROWSER: - return "browser"; - case AX_ROLE_BUSY_INDICATOR: - return "busyIndicator"; - case AX_ROLE_BUTTON: - return "button"; - case AX_ROLE_BUTTON_DROP_DOWN: - return "buttonDropDown"; - case AX_ROLE_CANVAS: - return "canvas"; - case AX_ROLE_CELL: - return "cell"; - case AX_ROLE_CHECK_BOX: - return "checkBox"; - case AX_ROLE_CLIENT: - return "client"; - case AX_ROLE_COLOR_WELL: - return "colorWell"; - case AX_ROLE_COLUMN_HEADER: - return "columnHeader"; - case AX_ROLE_COLUMN: - return "column"; - case AX_ROLE_COMBO_BOX: - return "comboBox"; - case AX_ROLE_COMPLEMENTARY: - return "complementary"; - case AX_ROLE_CONTENT_INFO: - return "contentInfo"; - case AX_ROLE_DATE: - return "date"; - case AX_ROLE_DATE_TIME: - return "dateTime"; - case AX_ROLE_DEFINITION: - return "definition"; - case AX_ROLE_DESCRIPTION_LIST_DETAIL: - return "descriptionListDetail"; - case AX_ROLE_DESCRIPTION_LIST: - return "descriptionList"; - case AX_ROLE_DESCRIPTION_LIST_TERM: - return "descriptionListTerm"; - case AX_ROLE_DESKTOP: - return "desktop"; - case AX_ROLE_DETAILS: - return "details"; - case AX_ROLE_DIALOG: - return "dialog"; - case AX_ROLE_DIRECTORY: - return "directory"; - case AX_ROLE_DISCLOSURE_TRIANGLE: - return "disclosureTriangle"; - case AX_ROLE_DIV: - return "div"; - case AX_ROLE_DOCUMENT: - return "document"; - case AX_ROLE_DRAWER: - return "drawer"; - case AX_ROLE_EDITABLE_TEXT: - return "editableText"; - case AX_ROLE_EMBEDDED_OBJECT: - return "embeddedObject"; - case AX_ROLE_FIGCAPTION: - return "figcaption"; - case AX_ROLE_FIGURE: - return "figure"; - case AX_ROLE_FOOTER: - return "footer"; - case AX_ROLE_FORM: - return "form"; - case AX_ROLE_GRID: - return "grid"; - case AX_ROLE_GROUP: - return "group"; - case AX_ROLE_GROW_AREA: - return "growArea"; - case AX_ROLE_HEADING: - return "heading"; - case AX_ROLE_HELP_TAG: - return "helpTag"; - case AX_ROLE_HORIZONTAL_RULE: - return "horizontalRule"; - case AX_ROLE_IFRAME: - return "iframe"; - case AX_ROLE_IGNORED: - return "ignored"; - case AX_ROLE_IMAGE_MAP_LINK: - return "imageMapLink"; - case AX_ROLE_IMAGE_MAP: - return "imageMap"; - case AX_ROLE_IMAGE: - return "image"; - case AX_ROLE_INCREMENTOR: - return "incrementor"; - case AX_ROLE_INLINE_TEXT_BOX: - return "inlineTextBox"; - case AX_ROLE_LABEL_TEXT: - return "labelText"; - case AX_ROLE_LEGEND: - return "legend"; - case AX_ROLE_LINK: - return "link"; - case AX_ROLE_LIST_BOX_OPTION: - return "listBoxOption"; - case AX_ROLE_LIST_BOX: - return "listBox"; - case AX_ROLE_LIST_ITEM: - return "listItem"; - case AX_ROLE_LIST_MARKER: - return "listMarker"; - case AX_ROLE_LIST: - return "list"; - case AX_ROLE_LOCATION_BAR: - return "locationBar"; - case AX_ROLE_LOG: - return "log"; - case AX_ROLE_MAIN: - return "main"; - case AX_ROLE_MARQUEE: - return "marquee"; - case AX_ROLE_MATH_ELEMENT: - return "mathElement"; - case AX_ROLE_MATH: - return "math"; - case AX_ROLE_MATTE: - return "matte"; - case AX_ROLE_MENU_BAR: - return "menuBar"; - case AX_ROLE_MENU_BUTTON: - return "menuButton"; - case AX_ROLE_MENU_ITEM: - return "menuItem"; - case AX_ROLE_MENU_ITEM_CHECK_BOX: - return "menuItemCheckBox"; - case AX_ROLE_MENU_ITEM_RADIO: - return "menuItemRadio"; - case AX_ROLE_MENU_LIST_OPTION: - return "menuListOption"; - case AX_ROLE_MENU_LIST_POPUP: - return "menuListPopup"; - case AX_ROLE_MENU: - return "menu"; - case AX_ROLE_METER: - return "meter"; - case AX_ROLE_NAVIGATION: - return "navigation"; - case AX_ROLE_NOTE: - return "note"; - case AX_ROLE_OUTLINE: - return "outline"; - case AX_ROLE_PANE: - return "pane"; - case AX_ROLE_PARAGRAPH: - return "paragraph"; - case AX_ROLE_POP_UP_BUTTON: - return "popUpButton"; - case AX_ROLE_PRESENTATIONAL: - return "presentational"; - case AX_ROLE_PROGRESS_INDICATOR: - return "progressIndicator"; - case AX_ROLE_RADIO_BUTTON: - return "radioButton"; - case AX_ROLE_RADIO_GROUP: - return "radioGroup"; - case AX_ROLE_REGION: - return "region"; - case AX_ROLE_ROOT_WEB_AREA: - return "rootWebArea"; - case AX_ROLE_ROW_HEADER: - return "rowHeader"; - case AX_ROLE_ROW: - return "row"; - case AX_ROLE_RULER_MARKER: - return "rulerMarker"; - case AX_ROLE_RULER: - return "ruler"; - case AX_ROLE_SVG_ROOT: - return "svgRoot"; - case AX_ROLE_SCROLL_AREA: - return "scrollArea"; - case AX_ROLE_SCROLL_BAR: - return "scrollBar"; - case AX_ROLE_SEAMLESS_WEB_AREA: - return "seamlessWebArea"; - case AX_ROLE_SEARCH: - return "search"; - case AX_ROLE_SHEET: - return "sheet"; - case AX_ROLE_SLIDER: - return "slider"; - case AX_ROLE_SLIDER_THUMB: - return "sliderThumb"; - case AX_ROLE_SPIN_BUTTON_PART: - return "spinButtonPart"; - case AX_ROLE_SPIN_BUTTON: - return "spinButton"; - case AX_ROLE_SPLIT_GROUP: - return "splitGroup"; - case AX_ROLE_SPLITTER: - return "splitter"; - case AX_ROLE_STATIC_TEXT: - return "staticText"; - case AX_ROLE_STATUS: - return "status"; - case AX_ROLE_SYSTEM_WIDE: - return "systemWide"; - case AX_ROLE_TAB_GROUP: - return "tabGroup"; - case AX_ROLE_TAB_LIST: - return "tabList"; - case AX_ROLE_TAB_PANEL: - return "tabPanel"; - case AX_ROLE_TAB: - return "tab"; - case AX_ROLE_TABLE_HEADER_CONTAINER: - return "tableHeaderContainer"; - case AX_ROLE_TABLE: - return "table"; - case AX_ROLE_TEXT_AREA: - return "textArea"; - case AX_ROLE_TEXT_FIELD: - return "textField"; - case AX_ROLE_TIME: - return "time"; - case AX_ROLE_TIMER: - return "timer"; - case AX_ROLE_TITLE_BAR: - return "titleBar"; - case AX_ROLE_TOGGLE_BUTTON: - return "toggleButton"; - case AX_ROLE_TOOLBAR: - return "toolbar"; - case AX_ROLE_TREE_GRID: - return "treeGrid"; - case AX_ROLE_TREE_ITEM: - return "treeItem"; - case AX_ROLE_TREE: - return "tree"; - case AX_ROLE_UNKNOWN: - return "unknown"; - case AX_ROLE_TOOLTIP: - return "tooltip"; - case AX_ROLE_VALUE_INDICATOR: - return "valueIndicator"; - case AX_ROLE_WEB_AREA: - return "webArea"; - case AX_ROLE_WINDOW: - return "window"; - case AX_ROLE_NONE: - return ""; - } - NOTREACHED(); - return ""; -} - -AXRole ParseAXRole(const std::string& enum_string) { - if (enum_string == "alert_dialog") return AX_ROLE_ALERT_DIALOG; - if (enum_string == "alert") return AX_ROLE_ALERT; - if (enum_string == "annotation") return AX_ROLE_ANNOTATION; - if (enum_string == "application") return AX_ROLE_APPLICATION; - if (enum_string == "article") return AX_ROLE_ARTICLE; - if (enum_string == "banner") return AX_ROLE_BANNER; - if (enum_string == "browser") return AX_ROLE_BROWSER; - if (enum_string == "busy_indicator") return AX_ROLE_BUSY_INDICATOR; - if (enum_string == "button") return AX_ROLE_BUTTON; - if (enum_string == "button_drop_down") return AX_ROLE_BUTTON_DROP_DOWN; - if (enum_string == "canvas") return AX_ROLE_CANVAS; - if (enum_string == "cell") return AX_ROLE_CELL; - if (enum_string == "check_box") return AX_ROLE_CHECK_BOX; - if (enum_string == "client") return AX_ROLE_CLIENT; - if (enum_string == "color_well") return AX_ROLE_COLOR_WELL; - if (enum_string == "column_header") return AX_ROLE_COLUMN_HEADER; - if (enum_string == "column") return AX_ROLE_COLUMN; - if (enum_string == "combo_box") return AX_ROLE_COMBO_BOX; - if (enum_string == "complementary") return AX_ROLE_COMPLEMENTARY; - if (enum_string == "content_info") return AX_ROLE_CONTENT_INFO; - if (enum_string == "date") return AX_ROLE_DATE; - if (enum_string == "date_time") return AX_ROLE_DATE_TIME; - if (enum_string == "definition") return AX_ROLE_DEFINITION; - if (enum_string == "description_list_detail") - return AX_ROLE_DESCRIPTION_LIST_DETAIL; - if (enum_string == "description_list") return AX_ROLE_DESCRIPTION_LIST; - if (enum_string == "description_list_term") - return AX_ROLE_DESCRIPTION_LIST_TERM; - if (enum_string == "desktop") return AX_ROLE_DESKTOP; - if (enum_string == "details") return AX_ROLE_DETAILS; - if (enum_string == "dialog") return AX_ROLE_DIALOG; - if (enum_string == "directory") return AX_ROLE_DIRECTORY; - if (enum_string == "disclosure_triangle") return AX_ROLE_DISCLOSURE_TRIANGLE; - if (enum_string == "div") return AX_ROLE_DIV; - if (enum_string == "document") return AX_ROLE_DOCUMENT; - if (enum_string == "drawer") return AX_ROLE_DRAWER; - if (enum_string == "editable_text") return AX_ROLE_EDITABLE_TEXT; - if (enum_string == "embedded_object") return AX_ROLE_EMBEDDED_OBJECT; - if (enum_string == "figcaption") return AX_ROLE_FIGCAPTION; - if (enum_string == "figure") return AX_ROLE_FIGURE; - if (enum_string == "footer") return AX_ROLE_FOOTER; - if (enum_string == "form") return AX_ROLE_FORM; - if (enum_string == "grid") return AX_ROLE_GRID; - if (enum_string == "group") return AX_ROLE_GROUP; - if (enum_string == "grow_area") return AX_ROLE_GROW_AREA; - if (enum_string == "heading") return AX_ROLE_HEADING; - if (enum_string == "help_tag") return AX_ROLE_HELP_TAG; - if (enum_string == "horizontal_rule") return AX_ROLE_HORIZONTAL_RULE; - if (enum_string == "iframe") return AX_ROLE_IFRAME; - if (enum_string == "ignored") return AX_ROLE_IGNORED; - if (enum_string == "image_map_link") return AX_ROLE_IMAGE_MAP_LINK; - if (enum_string == "image_map") return AX_ROLE_IMAGE_MAP; - if (enum_string == "image") return AX_ROLE_IMAGE; - if (enum_string == "incrementor") return AX_ROLE_INCREMENTOR; - if (enum_string == "inline_text_box") return AX_ROLE_INLINE_TEXT_BOX; - if (enum_string == "label_text") return AX_ROLE_LABEL_TEXT; - if (enum_string == "legend") return AX_ROLE_LEGEND; - if (enum_string == "link") return AX_ROLE_LINK; - if (enum_string == "list_box_option") return AX_ROLE_LIST_BOX_OPTION; - if (enum_string == "list_box") return AX_ROLE_LIST_BOX; - if (enum_string == "list_item") return AX_ROLE_LIST_ITEM; - if (enum_string == "list_marker") return AX_ROLE_LIST_MARKER; - if (enum_string == "list") return AX_ROLE_LIST; - if (enum_string == "location_bar") return AX_ROLE_LOCATION_BAR; - if (enum_string == "log") return AX_ROLE_LOG; - if (enum_string == "main") return AX_ROLE_MAIN; - if (enum_string == "marquee") return AX_ROLE_MARQUEE; - if (enum_string == "math_element") return AX_ROLE_MATH_ELEMENT; - if (enum_string == "math") return AX_ROLE_MATH; - if (enum_string == "matte") return AX_ROLE_MATTE; - if (enum_string == "menu_bar") return AX_ROLE_MENU_BAR; - if (enum_string == "menu_button") return AX_ROLE_MENU_BUTTON; - if (enum_string == "menu_item") return AX_ROLE_MENU_ITEM; - if (enum_string == "menu_item_check_box") return AX_ROLE_MENU_ITEM_CHECK_BOX; - if (enum_string == "menu_item_radio") return AX_ROLE_MENU_ITEM_RADIO; - if (enum_string == "menu_list_option") return AX_ROLE_MENU_LIST_OPTION; - if (enum_string == "menu_list_popup") return AX_ROLE_MENU_LIST_POPUP; - if (enum_string == "menu") return AX_ROLE_MENU; - if (enum_string == "meter") return AX_ROLE_METER; - if (enum_string == "navigation") return AX_ROLE_NAVIGATION; - if (enum_string == "note") return AX_ROLE_NOTE; - if (enum_string == "outline") return AX_ROLE_OUTLINE; - if (enum_string == "pane") return AX_ROLE_PANE; - if (enum_string == "paragraph") return AX_ROLE_PARAGRAPH; - if (enum_string == "pop_up_button") return AX_ROLE_POP_UP_BUTTON; - if (enum_string == "presentational") return AX_ROLE_PRESENTATIONAL; - if (enum_string == "progress_indicator") return AX_ROLE_PROGRESS_INDICATOR; - if (enum_string == "radio_button") return AX_ROLE_RADIO_BUTTON; - if (enum_string == "radio_group") return AX_ROLE_RADIO_GROUP; - if (enum_string == "region") return AX_ROLE_REGION; - if (enum_string == "root_web_area") return AX_ROLE_ROOT_WEB_AREA; - if (enum_string == "row_header") return AX_ROLE_ROW_HEADER; - if (enum_string == "row") return AX_ROLE_ROW; - if (enum_string == "ruler_marker") return AX_ROLE_RULER_MARKER; - if (enum_string == "ruler") return AX_ROLE_RULER; - if (enum_string == "svg_root") return AX_ROLE_SVG_ROOT; - if (enum_string == "scroll_area") return AX_ROLE_SCROLL_AREA; - if (enum_string == "scroll_bar") return AX_ROLE_SCROLL_BAR; - if (enum_string == "seamless_web_area") return AX_ROLE_SEAMLESS_WEB_AREA; - if (enum_string == "search") return AX_ROLE_SEARCH; - if (enum_string == "sheet") return AX_ROLE_SHEET; - if (enum_string == "slider") return AX_ROLE_SLIDER; - if (enum_string == "slider_thumb") return AX_ROLE_SLIDER_THUMB; - if (enum_string == "spin_button_part") return AX_ROLE_SPIN_BUTTON_PART; - if (enum_string == "spin_button") return AX_ROLE_SPIN_BUTTON; - if (enum_string == "split_group") return AX_ROLE_SPLIT_GROUP; - if (enum_string == "splitter") return AX_ROLE_SPLITTER; - if (enum_string == "static_text") return AX_ROLE_STATIC_TEXT; - if (enum_string == "status") return AX_ROLE_STATUS; - if (enum_string == "system_wide") return AX_ROLE_SYSTEM_WIDE; - if (enum_string == "tab_group") return AX_ROLE_TAB_GROUP; - if (enum_string == "tab_list") return AX_ROLE_TAB_LIST; - if (enum_string == "tab_panel") return AX_ROLE_TAB_PANEL; - if (enum_string == "tab") return AX_ROLE_TAB; - if (enum_string == "table_header_container") - return AX_ROLE_TABLE_HEADER_CONTAINER; - if (enum_string == "table") return AX_ROLE_TABLE; - if (enum_string == "text_area") return AX_ROLE_TEXT_AREA; - if (enum_string == "text_field") return AX_ROLE_TEXT_FIELD; - if (enum_string == "time") return AX_ROLE_TIME; - if (enum_string == "timer") return AX_ROLE_TIMER; - if (enum_string == "title_bar") return AX_ROLE_TITLE_BAR; - if (enum_string == "toggle_button") return AX_ROLE_TOGGLE_BUTTON; - if (enum_string == "toolbar") return AX_ROLE_TOOLBAR; - if (enum_string == "tree_grid") return AX_ROLE_TREE_GRID; - if (enum_string == "tree_item") return AX_ROLE_TREE_ITEM; - if (enum_string == "tree") return AX_ROLE_TREE; - if (enum_string == "unknown") return AX_ROLE_UNKNOWN; - if (enum_string == "tooltip") return AX_ROLE_TOOLTIP; - if (enum_string == "value_indicator") return AX_ROLE_VALUE_INDICATOR; - if (enum_string == "web_area") return AX_ROLE_WEB_AREA; - if (enum_string == "window") return AX_ROLE_WINDOW; - return AX_ROLE_NONE; -} - -std::string ToString(AXState enum_param) { - switch (enum_param) { - case AX_STATE_BUSY: - return "busy"; - case AX_STATE_CHECKED: - return "checked"; - case AX_STATE_COLLAPSED: - return "collapsed"; - case AX_STATE_DEFAULT: - return "default"; - case AX_STATE_DISABLED: - return "disabled"; - case AX_STATE_EDITABLE: - return "editable"; - case AX_STATE_ENABLED: - return "enabled"; - case AX_STATE_EXPANDED: - return "expanded"; - case AX_STATE_FOCUSABLE: - return "focusable"; - case AX_STATE_FOCUSED: - return "focused"; - case AX_STATE_HASPOPUP: - return "haspopup"; - case AX_STATE_HOVERED: - return "hovered"; - case AX_STATE_INDETERMINATE: - return "indeterminate"; - case AX_STATE_INVISIBLE: - return "invisible"; - case AX_STATE_LINKED: - return "linked"; - case AX_STATE_MULTISELECTABLE: - return "multiselectable"; - case AX_STATE_OFFSCREEN: - return "offscreen"; - case AX_STATE_PRESSED: - return "pressed"; - case AX_STATE_PROTECTED: - return "protected"; - case AX_STATE_READ_ONLY: - return "readOnly"; - case AX_STATE_REQUIRED: - return "required"; - case AX_STATE_SELECTABLE: - return "selectable"; - case AX_STATE_SELECTED: - return "selected"; - case AX_STATE_VERTICAL: - return "vertical"; - case AX_STATE_VISITED: - return "visited"; - case AX_STATE_NONE: - return ""; - } - NOTREACHED(); - return ""; -} - -AXState ParseAXState(const std::string& enum_string) { - if (enum_string == "busy") return AX_STATE_BUSY; - if (enum_string == "checked") return AX_STATE_CHECKED; - if (enum_string == "collapsed") return AX_STATE_COLLAPSED; - if (enum_string == "default") return AX_STATE_DEFAULT; - if (enum_string == "disabled") return AX_STATE_DISABLED; - if (enum_string == "editable") return AX_STATE_EDITABLE; - if (enum_string == "enabled") return AX_STATE_ENABLED; - if (enum_string == "expanded") return AX_STATE_EXPANDED; - if (enum_string == "focusable") return AX_STATE_FOCUSABLE; - if (enum_string == "focused") return AX_STATE_FOCUSED; - if (enum_string == "haspopup") return AX_STATE_HASPOPUP; - if (enum_string == "hovered") return AX_STATE_HOVERED; - if (enum_string == "indeterminate") return AX_STATE_INDETERMINATE; - if (enum_string == "invisible") return AX_STATE_INVISIBLE; - if (enum_string == "linked") return AX_STATE_LINKED; - if (enum_string == "multiselectable") return AX_STATE_MULTISELECTABLE; - if (enum_string == "offscreen") return AX_STATE_OFFSCREEN; - if (enum_string == "pressed") return AX_STATE_PRESSED; - if (enum_string == "protected") return AX_STATE_PROTECTED; - if (enum_string == "read_only") return AX_STATE_READ_ONLY; - if (enum_string == "required") return AX_STATE_REQUIRED; - if (enum_string == "selectable") return AX_STATE_SELECTABLE; - if (enum_string == "selected") return AX_STATE_SELECTED; - if (enum_string == "vertical") return AX_STATE_VERTICAL; - if (enum_string == "visited") return AX_STATE_VISITED; - return AX_STATE_NONE; -} - -std::string ToString(AXStringAttribute enum_param) { - switch (enum_param) { - case AX_ATTR_DOC_URL: - return "docUrl"; - case AX_ATTR_DOC_TITLE: - return "docTitle"; - case AX_ATTR_DOC_MIMETYPE: - return "docMimetype"; - case AX_ATTR_DOC_DOCTYPE: - return "docDoctype"; - case AX_ATTR_ACCESS_KEY: - return "accessKey"; - case AX_ATTR_ACTION: - return "action"; - case AX_ATTR_CONTAINER_LIVE_RELEVANT: - return "containerLiveRelevant"; - case AX_ATTR_CONTAINER_LIVE_STATUS: - return "containerLiveStatus"; - case AX_ATTR_DESCRIPTION: - return "description"; - case AX_ATTR_DISPLAY: - return "display"; - case AX_ATTR_HELP: - return "help"; - case AX_ATTR_HTML_TAG: - return "htmlTag"; - case AX_ATTR_NAME: - return "name"; - case AX_ATTR_LIVE_RELEVANT: - return "liveRelevant"; - case AX_ATTR_LIVE_STATUS: - return "liveStatus"; - case AX_ATTR_ROLE: - return "role"; - case AX_ATTR_SHORTCUT: - return "shortcut"; - case AX_ATTR_TEXT_INPUT_TYPE: - return "textInputType"; - case AX_ATTR_URL: - return "url"; - case AX_ATTR_VALUE: - return "value"; - case AX_STRING_ATTRIBUTE_NONE: - return ""; - } - NOTREACHED(); - return ""; -} - -AXStringAttribute ParseAXStringAttribute(const std::string& enum_string) { - if (enum_string == "doc_url") return AX_ATTR_DOC_URL; - if (enum_string == "doc_title") return AX_ATTR_DOC_TITLE; - if (enum_string == "doc_mimetype") return AX_ATTR_DOC_MIMETYPE; - if (enum_string == "doc_doctype") return AX_ATTR_DOC_DOCTYPE; - if (enum_string == "access_key") return AX_ATTR_ACCESS_KEY; - if (enum_string == "action") return AX_ATTR_ACTION; - if (enum_string == "container_live_relevant") - return AX_ATTR_CONTAINER_LIVE_RELEVANT; - if (enum_string == "container_live_status") - return AX_ATTR_CONTAINER_LIVE_STATUS; - if (enum_string == "description") return AX_ATTR_DESCRIPTION; - if (enum_string == "display") return AX_ATTR_DISPLAY; - if (enum_string == "help") return AX_ATTR_HELP; - if (enum_string == "html_tag") return AX_ATTR_HTML_TAG; - if (enum_string == "name") return AX_ATTR_NAME; - if (enum_string == "live_relevant") return AX_ATTR_LIVE_RELEVANT; - if (enum_string == "live_status") return AX_ATTR_LIVE_STATUS; - if (enum_string == "role") return AX_ATTR_ROLE; - if (enum_string == "shortcut") return AX_ATTR_SHORTCUT; - if (enum_string == "text_input_type") return AX_ATTR_TEXT_INPUT_TYPE; - if (enum_string == "url") return AX_ATTR_URL; - if (enum_string == "value") return AX_ATTR_VALUE; - return AX_STRING_ATTRIBUTE_NONE; -} - -std::string ToString(AXIntAttribute enum_param) { - switch (enum_param) { - case AX_ATTR_SCROLL_X: - return "scrollX"; - case AX_ATTR_SCROLL_X_MIN: - return "scrollXMin"; - case AX_ATTR_SCROLL_X_MAX: - return "scrollXMax"; - case AX_ATTR_SCROLL_Y: - return "scrollY"; - case AX_ATTR_SCROLL_Y_MIN: - return "scrollYMin"; - case AX_ATTR_SCROLL_Y_MAX: - return "scrollYMax"; - case AX_ATTR_TEXT_SEL_START: - return "textSelStart"; - case AX_ATTR_TEXT_SEL_END: - return "textSelEnd"; - case AX_ATTR_TABLE_ROW_COUNT: - return "tableRowCount"; - case AX_ATTR_TABLE_COLUMN_COUNT: - return "tableColumnCount"; - case AX_ATTR_TABLE_HEADER_ID: - return "tableHeaderId"; - case AX_ATTR_TABLE_ROW_INDEX: - return "tableRowIndex"; - case AX_ATTR_TABLE_ROW_HEADER_ID: - return "tableRowHeaderId"; - case AX_ATTR_TABLE_COLUMN_INDEX: - return "tableColumnIndex"; - case AX_ATTR_TABLE_COLUMN_HEADER_ID: - return "tableColumnHeaderId"; - case AX_ATTR_TABLE_CELL_COLUMN_INDEX: - return "tableCellColumnIndex"; - case AX_ATTR_TABLE_CELL_COLUMN_SPAN: - return "tableCellColumnSpan"; - case AX_ATTR_TABLE_CELL_ROW_INDEX: - return "tableCellRowIndex"; - case AX_ATTR_TABLE_CELL_ROW_SPAN: - return "tableCellRowSpan"; - case AX_ATTR_HIERARCHICAL_LEVEL: - return "hierarchicalLevel"; - case AX_ATTR_TITLE_UI_ELEMENT: - return "titleUiElement"; - case AX_ATTR_ACTIVEDESCENDANT_ID: - return "activedescendantId"; - case AX_ATTR_COLOR_VALUE_RED: - return "colorValueRed"; - case AX_ATTR_COLOR_VALUE_GREEN: - return "colorValueGreen"; - case AX_ATTR_COLOR_VALUE_BLUE: - return "colorValueBlue"; - case AX_ATTR_TEXT_DIRECTION: - return "textDirection"; - case AX_INT_ATTRIBUTE_NONE: - return ""; - } - NOTREACHED(); - return ""; -} - -AXIntAttribute ParseAXIntAttribute(const std::string& enum_string) { - if (enum_string == "scroll_x") return AX_ATTR_SCROLL_X; - if (enum_string == "scroll_x_min") return AX_ATTR_SCROLL_X_MIN; - if (enum_string == "scroll_x_max") return AX_ATTR_SCROLL_X_MAX; - if (enum_string == "scroll_y") return AX_ATTR_SCROLL_Y; - if (enum_string == "scroll_y_min") return AX_ATTR_SCROLL_Y_MIN; - if (enum_string == "scroll_y_max") return AX_ATTR_SCROLL_Y_MAX; - if (enum_string == "text_sel_start") return AX_ATTR_TEXT_SEL_START; - if (enum_string == "text_sel_end") return AX_ATTR_TEXT_SEL_END; - if (enum_string == "table_row_count") return AX_ATTR_TABLE_ROW_COUNT; - if (enum_string == "table_column_count") return AX_ATTR_TABLE_COLUMN_COUNT; - if (enum_string == "table_header_id") return AX_ATTR_TABLE_HEADER_ID; - if (enum_string == "table_row_index") return AX_ATTR_TABLE_ROW_INDEX; - if (enum_string == "table_row_header_id") return AX_ATTR_TABLE_ROW_HEADER_ID; - if (enum_string == "table_column_index") return AX_ATTR_TABLE_COLUMN_INDEX; - if (enum_string == "table_column_header_id") - return AX_ATTR_TABLE_COLUMN_HEADER_ID; - if (enum_string == "table_cell_column_index") - return AX_ATTR_TABLE_CELL_COLUMN_INDEX; - if (enum_string == "table_cell_column_span") - return AX_ATTR_TABLE_CELL_COLUMN_SPAN; - if (enum_string == "table_cell_row_index") - return AX_ATTR_TABLE_CELL_ROW_INDEX; - if (enum_string == "table_cell_row_span") return AX_ATTR_TABLE_CELL_ROW_SPAN; - if (enum_string == "hierarchical_level") return AX_ATTR_HIERARCHICAL_LEVEL; - if (enum_string == "title_ui_element") return AX_ATTR_TITLE_UI_ELEMENT; - if (enum_string == "activedescendant_id") return AX_ATTR_ACTIVEDESCENDANT_ID; - if (enum_string == "color_value_red") return AX_ATTR_COLOR_VALUE_RED; - if (enum_string == "color_value_green") return AX_ATTR_COLOR_VALUE_GREEN; - if (enum_string == "color_value_blue") return AX_ATTR_COLOR_VALUE_BLUE; - if (enum_string == "text_direction") return AX_ATTR_TEXT_DIRECTION; - return AX_INT_ATTRIBUTE_NONE; -} - -std::string ToString(AXFloatAttribute enum_param) { - switch (enum_param) { - case AX_ATTR_DOC_LOADING_PROGRESS: - return "docLoadingProgress"; - case AX_ATTR_VALUE_FOR_RANGE: - return "valueForRange"; - case AX_ATTR_MIN_VALUE_FOR_RANGE: - return "minValueForRange"; - case AX_ATTR_MAX_VALUE_FOR_RANGE: - return "maxValueForRange"; - case AX_FLOAT_ATTRIBUTE_NONE: - return ""; - } - NOTREACHED(); - return ""; -} - -AXFloatAttribute ParseAXFloatAttribute(const std::string& enum_string) { - if (enum_string == "doc_loading_progress") - return AX_ATTR_DOC_LOADING_PROGRESS; - if (enum_string == "value_for_range") return AX_ATTR_VALUE_FOR_RANGE; - if (enum_string == "min_value_for_range") return AX_ATTR_MIN_VALUE_FOR_RANGE; - if (enum_string == "max_value_for_range") return AX_ATTR_MAX_VALUE_FOR_RANGE; - return AX_FLOAT_ATTRIBUTE_NONE; -} - -std::string ToString(AXBoolAttribute enum_param) { - switch (enum_param) { - case AX_ATTR_DOC_LOADED: - return "docLoaded"; - case AX_ATTR_BUTTON_MIXED: - return "buttonMixed"; - case AX_ATTR_CONTAINER_LIVE_ATOMIC: - return "containerLiveAtomic"; - case AX_ATTR_CONTAINER_LIVE_BUSY: - return "containerLiveBusy"; - case AX_ATTR_LIVE_ATOMIC: - return "liveAtomic"; - case AX_ATTR_LIVE_BUSY: - return "liveBusy"; - case AX_ATTR_ARIA_READONLY: - return "ariaReadonly"; - case AX_ATTR_CAN_SET_VALUE: - return "canSetValue"; - case AX_ATTR_UPDATE_LOCATION_ONLY: - return "updateLocationOnly"; - case AX_ATTR_CANVAS_HAS_FALLBACK: - return "canvasHasFallback"; - case AX_ATTR_IS_AX_TREE_HOST: - return "isAxTreeHost"; - case AX_BOOL_ATTRIBUTE_NONE: - return ""; - } - NOTREACHED(); - return ""; -} - -AXBoolAttribute ParseAXBoolAttribute(const std::string& enum_string) { - if (enum_string == "doc_loaded") return AX_ATTR_DOC_LOADED; - if (enum_string == "button_mixed") return AX_ATTR_BUTTON_MIXED; - if (enum_string == "container_live_atomic") - return AX_ATTR_CONTAINER_LIVE_ATOMIC; - if (enum_string == "container_live_busy") return AX_ATTR_CONTAINER_LIVE_BUSY; - if (enum_string == "live_atomic") return AX_ATTR_LIVE_ATOMIC; - if (enum_string == "live_busy") return AX_ATTR_LIVE_BUSY; - if (enum_string == "aria_readonly") return AX_ATTR_ARIA_READONLY; - if (enum_string == "can_set_value") return AX_ATTR_CAN_SET_VALUE; - if (enum_string == "update_location_only") - return AX_ATTR_UPDATE_LOCATION_ONLY; - if (enum_string == "canvas_has_fallback") return AX_ATTR_CANVAS_HAS_FALLBACK; - if (enum_string == "is_ax_tree_host") return AX_ATTR_IS_AX_TREE_HOST; - return AX_BOOL_ATTRIBUTE_NONE; -} - -std::string ToString(AXIntListAttribute enum_param) { - switch (enum_param) { - case AX_ATTR_INDIRECT_CHILD_IDS: - return "indirectChildIds"; - case AX_ATTR_CONTROLS_IDS: - return "controlsIds"; - case AX_ATTR_DESCRIBEDBY_IDS: - return "describedbyIds"; - case AX_ATTR_FLOWTO_IDS: - return "flowtoIds"; - case AX_ATTR_LABELLEDBY_IDS: - return "labelledbyIds"; - case AX_ATTR_OWNS_IDS: - return "ownsIds"; - case AX_ATTR_LINE_BREAKS: - return "lineBreaks"; - case AX_ATTR_CELL_IDS: - return "cellIds"; - case AX_ATTR_UNIQUE_CELL_IDS: - return "uniqueCellIds"; - case AX_ATTR_CHARACTER_OFFSETS: - return "characterOffsets"; - case AX_ATTR_WORD_STARTS: - return "wordStarts"; - case AX_ATTR_WORD_ENDS: - return "wordEnds"; - case AX_INT_LIST_ATTRIBUTE_NONE: - return ""; - } - NOTREACHED(); - return ""; -} - -AXIntListAttribute ParseAXIntListAttribute(const std::string& enum_string) { - if (enum_string == "indirect_child_ids") return AX_ATTR_INDIRECT_CHILD_IDS; - if (enum_string == "controls_ids") return AX_ATTR_CONTROLS_IDS; - if (enum_string == "describedby_ids") return AX_ATTR_DESCRIBEDBY_IDS; - if (enum_string == "flowto_ids") return AX_ATTR_FLOWTO_IDS; - if (enum_string == "labelledby_ids") return AX_ATTR_LABELLEDBY_IDS; - if (enum_string == "owns_ids") return AX_ATTR_OWNS_IDS; - if (enum_string == "line_breaks") return AX_ATTR_LINE_BREAKS; - if (enum_string == "cell_ids") return AX_ATTR_CELL_IDS; - if (enum_string == "unique_cell_ids") return AX_ATTR_UNIQUE_CELL_IDS; - if (enum_string == "character_offsets") return AX_ATTR_CHARACTER_OFFSETS; - if (enum_string == "word_starts") return AX_ATTR_WORD_STARTS; - if (enum_string == "word_ends") return AX_ATTR_WORD_ENDS; - return AX_INT_LIST_ATTRIBUTE_NONE; -} - -std::string ToString(AXTextDirection enum_param) { - switch (enum_param) { - case AX_TEXT_DIRECTION_LR: - return "textDirectionLr"; - case AX_TEXT_DIRECTION_RL: - return "textDirectionRl"; - case AX_TEXT_DIRECTION_TB: - return "textDirectionTb"; - case AX_TEXT_DIRECTION_BT: - return "textDirectionBt"; - case AX_TEXT_DIRECTION_NONE: - return ""; - } - NOTREACHED(); - return ""; -} - -AXTextDirection ParseAXTextDirection(const std::string& enum_string) { - if (enum_string == "text_direction_lr") return AX_TEXT_DIRECTION_LR; - if (enum_string == "text_direction_rl") return AX_TEXT_DIRECTION_RL; - if (enum_string == "text_direction_tb") return AX_TEXT_DIRECTION_TB; - if (enum_string == "text_direction_bt") return AX_TEXT_DIRECTION_BT; - return AX_TEXT_DIRECTION_NONE; -} - -} // namespace ui
diff --git a/ui/accessibility/ax_enums.h b/ui/accessibility/ax_enums.h deleted file mode 100644 index 5aba98b..0000000 --- a/ui/accessibility/ax_enums.h +++ /dev/null
@@ -1,350 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_ACCESSIBILITY_AX_ENUMS_H__ -#define UI_ACCESSIBILITY_AX_ENUMS_H__ - -#include <string> - -namespace ui { - -enum AXEvent { - AX_EVENT_NONE, - AX_EVENT_ACTIVEDESCENDANTCHANGED, - AX_EVENT_ALERT, - AX_EVENT_ARIA_ATTRIBUTE_CHANGED, - AX_EVENT_AUTOCORRECTION_OCCURED, - AX_EVENT_BLUR, - AX_EVENT_CHECKED_STATE_CHANGED, - AX_EVENT_CHILDREN_CHANGED, - AX_EVENT_FOCUS, - AX_EVENT_HIDE, - AX_EVENT_HOVER, - AX_EVENT_INVALID_STATUS_CHANGED, - AX_EVENT_LAYOUT_COMPLETE, - AX_EVENT_LIVE_REGION_CHANGED, - AX_EVENT_LOAD_COMPLETE, - AX_EVENT_LOCATION_CHANGED, - AX_EVENT_MENU_END, - AX_EVENT_MENU_LIST_ITEM_SELECTED, - AX_EVENT_MENU_LIST_VALUE_CHANGED, - AX_EVENT_MENU_POPUP_END, - AX_EVENT_MENU_POPUP_START, - AX_EVENT_MENU_START, - AX_EVENT_ROW_COLLAPSED, - AX_EVENT_ROW_COUNT_CHANGED, - AX_EVENT_ROW_EXPANDED, - AX_EVENT_SCROLL_POSITION_CHANGED, - AX_EVENT_SCROLLED_TO_ANCHOR, - AX_EVENT_SELECTED_CHILDREN_CHANGED, - AX_EVENT_SELECTION, - AX_EVENT_SELECTION_ADD, - AX_EVENT_SELECTION_REMOVE, - AX_EVENT_SHOW, - AX_EVENT_TEXT_CHANGED, - AX_EVENT_TEXT_SELECTION_CHANGED, - AX_EVENT_VALUE_CHANGED, - AX_EVENT_LAST = AX_EVENT_VALUE_CHANGED, -}; - -std::string ToString(AXEvent as_enum); -AXEvent ParseAXEvent(const std::string& as_string); - -enum AXRole { - AX_ROLE_NONE, - AX_ROLE_ALERT_DIALOG, - AX_ROLE_ALERT, - AX_ROLE_ANNOTATION, - AX_ROLE_APPLICATION, - AX_ROLE_ARTICLE, - AX_ROLE_BANNER, - AX_ROLE_BROWSER, - AX_ROLE_BUSY_INDICATOR, - AX_ROLE_BUTTON, - AX_ROLE_BUTTON_DROP_DOWN, - AX_ROLE_CANVAS, - AX_ROLE_CELL, - AX_ROLE_CHECK_BOX, - AX_ROLE_CLIENT, - AX_ROLE_COLOR_WELL, - AX_ROLE_COLUMN_HEADER, - AX_ROLE_COLUMN, - AX_ROLE_COMBO_BOX, - AX_ROLE_COMPLEMENTARY, - AX_ROLE_CONTENT_INFO, - AX_ROLE_DATE, - AX_ROLE_DATE_TIME, - AX_ROLE_DEFINITION, - AX_ROLE_DESCRIPTION_LIST_DETAIL, - AX_ROLE_DESCRIPTION_LIST, - AX_ROLE_DESCRIPTION_LIST_TERM, - AX_ROLE_DESKTOP, - AX_ROLE_DETAILS, - AX_ROLE_DIALOG, - AX_ROLE_DIRECTORY, - AX_ROLE_DISCLOSURE_TRIANGLE, - AX_ROLE_DIV, - AX_ROLE_DOCUMENT, - AX_ROLE_DRAWER, - AX_ROLE_EDITABLE_TEXT, - AX_ROLE_EMBEDDED_OBJECT, - AX_ROLE_FIGCAPTION, - AX_ROLE_FIGURE, - AX_ROLE_FOOTER, - AX_ROLE_FORM, - AX_ROLE_GRID, - AX_ROLE_GROUP, - AX_ROLE_GROW_AREA, - AX_ROLE_HEADING, - AX_ROLE_HELP_TAG, - AX_ROLE_HORIZONTAL_RULE, - AX_ROLE_IFRAME, - AX_ROLE_IGNORED, - AX_ROLE_IMAGE_MAP_LINK, - AX_ROLE_IMAGE_MAP, - AX_ROLE_IMAGE, - AX_ROLE_INCREMENTOR, - AX_ROLE_INLINE_TEXT_BOX, - AX_ROLE_LABEL_TEXT, - AX_ROLE_LEGEND, - AX_ROLE_LINK, - AX_ROLE_LIST_BOX_OPTION, - AX_ROLE_LIST_BOX, - AX_ROLE_LIST_ITEM, - AX_ROLE_LIST_MARKER, - AX_ROLE_LIST, - AX_ROLE_LOCATION_BAR, - AX_ROLE_LOG, - AX_ROLE_MAIN, - AX_ROLE_MARQUEE, - AX_ROLE_MATH_ELEMENT, - AX_ROLE_MATH, - AX_ROLE_MATTE, - AX_ROLE_MENU_BAR, - AX_ROLE_MENU_BUTTON, - AX_ROLE_MENU_ITEM, - AX_ROLE_MENU_ITEM_CHECK_BOX, - AX_ROLE_MENU_ITEM_RADIO, - AX_ROLE_MENU_LIST_OPTION, - AX_ROLE_MENU_LIST_POPUP, - AX_ROLE_MENU, - AX_ROLE_METER, - AX_ROLE_NAVIGATION, - AX_ROLE_NOTE, - AX_ROLE_OUTLINE, - AX_ROLE_PANE, - AX_ROLE_PARAGRAPH, - AX_ROLE_POP_UP_BUTTON, - AX_ROLE_PRESENTATIONAL, - AX_ROLE_PROGRESS_INDICATOR, - AX_ROLE_RADIO_BUTTON, - AX_ROLE_RADIO_GROUP, - AX_ROLE_REGION, - AX_ROLE_ROOT_WEB_AREA, - AX_ROLE_ROW_HEADER, - AX_ROLE_ROW, - AX_ROLE_RULER_MARKER, - AX_ROLE_RULER, - AX_ROLE_SVG_ROOT, - AX_ROLE_SCROLL_AREA, - AX_ROLE_SCROLL_BAR, - AX_ROLE_SEAMLESS_WEB_AREA, - AX_ROLE_SEARCH, - AX_ROLE_SHEET, - AX_ROLE_SLIDER, - AX_ROLE_SLIDER_THUMB, - AX_ROLE_SPIN_BUTTON_PART, - AX_ROLE_SPIN_BUTTON, - AX_ROLE_SPLIT_GROUP, - AX_ROLE_SPLITTER, - AX_ROLE_STATIC_TEXT, - AX_ROLE_STATUS, - AX_ROLE_SYSTEM_WIDE, - AX_ROLE_TAB_GROUP, - AX_ROLE_TAB_LIST, - AX_ROLE_TAB_PANEL, - AX_ROLE_TAB, - AX_ROLE_TABLE_HEADER_CONTAINER, - AX_ROLE_TABLE, - AX_ROLE_TEXT_AREA, - AX_ROLE_TEXT_FIELD, - AX_ROLE_TIME, - AX_ROLE_TIMER, - AX_ROLE_TITLE_BAR, - AX_ROLE_TOGGLE_BUTTON, - AX_ROLE_TOOLBAR, - AX_ROLE_TREE_GRID, - AX_ROLE_TREE_ITEM, - AX_ROLE_TREE, - AX_ROLE_UNKNOWN, - AX_ROLE_TOOLTIP, - AX_ROLE_VALUE_INDICATOR, - AX_ROLE_WEB_AREA, - AX_ROLE_WINDOW, - AX_ROLE_LAST = AX_ROLE_WINDOW, -}; - -std::string ToString(AXRole as_enum); -AXRole ParseAXRole(const std::string& as_string); - -enum AXState { - AX_STATE_NONE, - AX_STATE_BUSY, - AX_STATE_CHECKED, - AX_STATE_COLLAPSED, - AX_STATE_DEFAULT, - AX_STATE_DISABLED, - AX_STATE_EDITABLE, - AX_STATE_ENABLED, - AX_STATE_EXPANDED, - AX_STATE_FOCUSABLE, - AX_STATE_FOCUSED, - AX_STATE_HASPOPUP, - AX_STATE_HOVERED, - AX_STATE_INDETERMINATE, - AX_STATE_INVISIBLE, - AX_STATE_LINKED, - AX_STATE_MULTISELECTABLE, - AX_STATE_OFFSCREEN, - AX_STATE_PRESSED, - AX_STATE_PROTECTED, - AX_STATE_READ_ONLY, - AX_STATE_REQUIRED, - AX_STATE_SELECTABLE, - AX_STATE_SELECTED, - AX_STATE_VERTICAL, - AX_STATE_VISITED, - AX_STATE_LAST = AX_STATE_VISITED, -}; - -std::string ToString(AXState as_enum); -AXState ParseAXState(const std::string& as_string); - -enum AXStringAttribute { - AX_STRING_ATTRIBUTE_NONE, - AX_ATTR_DOC_URL, - AX_ATTR_DOC_TITLE, - AX_ATTR_DOC_MIMETYPE, - AX_ATTR_DOC_DOCTYPE, - AX_ATTR_ACCESS_KEY, - AX_ATTR_ACTION, - AX_ATTR_CONTAINER_LIVE_RELEVANT, - AX_ATTR_CONTAINER_LIVE_STATUS, - AX_ATTR_DESCRIPTION, - AX_ATTR_DISPLAY, - AX_ATTR_HELP, - AX_ATTR_HTML_TAG, - AX_ATTR_NAME, - AX_ATTR_LIVE_RELEVANT, - AX_ATTR_LIVE_STATUS, - AX_ATTR_ROLE, - AX_ATTR_SHORTCUT, - AX_ATTR_TEXT_INPUT_TYPE, - AX_ATTR_URL, - AX_ATTR_VALUE, - AX_STRING_ATTRIBUTE_LAST = AX_ATTR_VALUE, -}; - -std::string ToString(AXStringAttribute as_enum); -AXStringAttribute ParseAXStringAttribute(const std::string& as_string); - -enum AXIntAttribute { - AX_INT_ATTRIBUTE_NONE, - AX_ATTR_SCROLL_X, - AX_ATTR_SCROLL_X_MIN, - AX_ATTR_SCROLL_X_MAX, - AX_ATTR_SCROLL_Y, - AX_ATTR_SCROLL_Y_MIN, - AX_ATTR_SCROLL_Y_MAX, - AX_ATTR_TEXT_SEL_START, - AX_ATTR_TEXT_SEL_END, - AX_ATTR_TABLE_ROW_COUNT, - AX_ATTR_TABLE_COLUMN_COUNT, - AX_ATTR_TABLE_HEADER_ID, - AX_ATTR_TABLE_ROW_INDEX, - AX_ATTR_TABLE_ROW_HEADER_ID, - AX_ATTR_TABLE_COLUMN_INDEX, - AX_ATTR_TABLE_COLUMN_HEADER_ID, - AX_ATTR_TABLE_CELL_COLUMN_INDEX, - AX_ATTR_TABLE_CELL_COLUMN_SPAN, - AX_ATTR_TABLE_CELL_ROW_INDEX, - AX_ATTR_TABLE_CELL_ROW_SPAN, - AX_ATTR_HIERARCHICAL_LEVEL, - AX_ATTR_TITLE_UI_ELEMENT, - AX_ATTR_ACTIVEDESCENDANT_ID, - AX_ATTR_COLOR_VALUE_RED, - AX_ATTR_COLOR_VALUE_GREEN, - AX_ATTR_COLOR_VALUE_BLUE, - AX_ATTR_TEXT_DIRECTION, - AX_INT_ATTRIBUTE_LAST = AX_ATTR_TEXT_DIRECTION, -}; - -std::string ToString(AXIntAttribute as_enum); -AXIntAttribute ParseAXIntAttribute(const std::string& as_string); - -enum AXFloatAttribute { - AX_FLOAT_ATTRIBUTE_NONE, - AX_ATTR_DOC_LOADING_PROGRESS, - AX_ATTR_VALUE_FOR_RANGE, - AX_ATTR_MIN_VALUE_FOR_RANGE, - AX_ATTR_MAX_VALUE_FOR_RANGE, - AX_FLOAT_ATTRIBUTE_LAST = AX_ATTR_MAX_VALUE_FOR_RANGE, -}; - -std::string ToString(AXFloatAttribute as_enum); -AXFloatAttribute ParseAXFloatAttribute(const std::string& as_string); - -enum AXBoolAttribute { - AX_BOOL_ATTRIBUTE_NONE, - AX_ATTR_DOC_LOADED, - AX_ATTR_BUTTON_MIXED, - AX_ATTR_CONTAINER_LIVE_ATOMIC, - AX_ATTR_CONTAINER_LIVE_BUSY, - AX_ATTR_LIVE_ATOMIC, - AX_ATTR_LIVE_BUSY, - AX_ATTR_ARIA_READONLY, - AX_ATTR_CAN_SET_VALUE, - AX_ATTR_UPDATE_LOCATION_ONLY, - AX_ATTR_CANVAS_HAS_FALLBACK, - AX_ATTR_IS_AX_TREE_HOST, - AX_BOOL_ATTRIBUTE_LAST = AX_ATTR_IS_AX_TREE_HOST, -}; - -std::string ToString(AXBoolAttribute as_enum); -AXBoolAttribute ParseAXBoolAttribute(const std::string& as_string); - -enum AXIntListAttribute { - AX_INT_LIST_ATTRIBUTE_NONE, - AX_ATTR_INDIRECT_CHILD_IDS, - AX_ATTR_CONTROLS_IDS, - AX_ATTR_DESCRIBEDBY_IDS, - AX_ATTR_FLOWTO_IDS, - AX_ATTR_LABELLEDBY_IDS, - AX_ATTR_OWNS_IDS, - AX_ATTR_LINE_BREAKS, - AX_ATTR_CELL_IDS, - AX_ATTR_UNIQUE_CELL_IDS, - AX_ATTR_CHARACTER_OFFSETS, - AX_ATTR_WORD_STARTS, - AX_ATTR_WORD_ENDS, - AX_INT_LIST_ATTRIBUTE_LAST = AX_ATTR_WORD_ENDS, -}; - -std::string ToString(AXIntListAttribute as_enum); -AXIntListAttribute ParseAXIntListAttribute(const std::string& as_string); - -enum AXTextDirection { - AX_TEXT_DIRECTION_NONE, - AX_TEXT_DIRECTION_LR, - AX_TEXT_DIRECTION_RL, - AX_TEXT_DIRECTION_TB, - AX_TEXT_DIRECTION_BT, - AX_TEXT_DIRECTION_LAST = AX_TEXT_DIRECTION_BT, -}; - -std::string ToString(AXTextDirection as_enum); -AXTextDirection ParseAXTextDirection(const std::string& as_string); - -} // namespace ui -#endif // UI_ACCESSIBILITY_AX_ENUMS_H__
diff --git a/ui/accessibility/ax_export.h b/ui/accessibility/ax_export.h deleted file mode 100644 index f437365..0000000 --- a/ui/accessibility/ax_export.h +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_ACCESSIBILITY_AX_EXPORT_H_ -#define UI_ACCESSIBILITY_AX_EXPORT_H_ - -// Defines AX_EXPORT so that functionality implemented by the -// ui/accessibility module can be exported to consumers. - -#if defined(COMPONENT_BUILD) -#if defined(WIN32) - -#if defined(ACCESSIBILITY_IMPLEMENTATION) -#define AX_EXPORT __declspec(dllexport) -#else -#define AX_EXPORT __declspec(dllimport) -#endif // defined(ACCESSIBILITY_IMPLEMENTATION) - -#else // defined(WIN32) -#if defined(ACCESSIBILITY_IMPLEMENTATION) -#define AX_EXPORT __attribute__((visibility("default"))) -#else -#define AX_EXPORT -#endif -#endif - -#else // defined(COMPONENT_BUILD) -#define AX_EXPORT -#endif - -#endif // UI_ACCESSIBILITY_AX_EXPORT_H_
diff --git a/ui/accessibility/ax_generated_tree_unittest.cc b/ui/accessibility/ax_generated_tree_unittest.cc deleted file mode 100644 index 3845886..0000000 --- a/ui/accessibility/ax_generated_tree_unittest.cc +++ /dev/null
@@ -1,157 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/memory/scoped_ptr.h" -#include "base/strings/string_number_conversions.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/accessibility/ax_node.h" -#include "ui/accessibility/ax_serializable_tree.h" -#include "ui/accessibility/ax_tree.h" -#include "ui/accessibility/ax_tree_serializer.h" -#include "ui/accessibility/tree_generator.h" - -namespace ui { -namespace { - -// A function to turn a tree into a string, capturing only the node ids -// and their relationship to one another. -// -// The string format is kind of like an S-expression, with each expression -// being either a node id, or a node id followed by a subexpression -// representing its children. -// -// Examples: -// -// (1) is a tree with a single node with id 1. -// (1 (2 3)) is a tree with 1 as the root, and 2 and 3 as its children. -// (1 (2 (3))) has 1 as the root, 2 as its child, and then 3 as the child of 2. -void TreeToStringHelper(const AXNode* node, std::string* out_result) { - *out_result += base::IntToString(node->id()); - if (node->child_count() != 0) { - *out_result += " ("; - for (int i = 0; i < node->child_count(); ++i) { - if (i != 0) - *out_result += " "; - TreeToStringHelper(node->ChildAtIndex(i), out_result); - } - *out_result += ")"; - } -} - -std::string TreeToString(const AXTree& tree) { - std::string result; - TreeToStringHelper(tree.GetRoot(), &result); - return "(" + result + ")"; -} - -} // anonymous namespace - -// Test the TreeGenerator class by building all possible trees with -// 3 nodes and the ids [1...3]. -TEST(AXGeneratedTreeTest, TestTreeGenerator) { - int tree_size = 3; - TreeGenerator generator(tree_size); - const char* EXPECTED_TREES[] = { - "(1 (2 3))", - "(2 (1 3))", - "(3 (1 2))", - "(1 (3 2))", - "(2 (3 1))", - "(3 (2 1))", - "(1 (2 (3)))", - "(2 (1 (3)))", - "(3 (1 (2)))", - "(1 (3 (2)))", - "(2 (3 (1)))", - "(3 (2 (1)))", - }; - - int n = generator.UniqueTreeCount(); - ASSERT_EQ(static_cast<int>(arraysize(EXPECTED_TREES)), n); - - for (int i = 0; i < n; i++) { - AXTree tree; - generator.BuildUniqueTree(i, &tree); - std::string str = TreeToString(tree); - EXPECT_EQ(EXPECTED_TREES[i], str); - } -} - -// Test mutating every possible tree with <n> nodes to every other possible -// tree with <n> nodes, where <n> is 4 in release mode and 3 in debug mode -// (for speed). For each possible combination of trees, we also vary which -// node we serialize first. -// -// For every possible scenario, we check that the AXTreeUpdate is valid, -// that the destination tree can unserialize it and create a valid tree, -// and that after updating all nodes the resulting tree now matches the -// intended tree. -TEST(AXGeneratedTreeTest, SerializeGeneratedTrees) { - // Do a more exhaustive test in release mode. If you're modifying - // the algorithm you may want to try even larger tree sizes if you - // can afford the time. -#ifdef NDEBUG - int tree_size = 4; -#else - LOG(WARNING) << "Debug build, only testing trees with 3 nodes and not 4."; - int tree_size = 3; -#endif - - TreeGenerator generator(tree_size); - int n = generator.UniqueTreeCount(); - - for (int i = 0; i < n; i++) { - // Build the first tree, tree0. - AXSerializableTree tree0; - generator.BuildUniqueTree(i, &tree0); - SCOPED_TRACE("tree0 is " + TreeToString(tree0)); - - for (int j = 0; j < n; j++) { - // Build the second tree, tree1. - AXSerializableTree tree1; - generator.BuildUniqueTree(j, &tree1); - SCOPED_TRACE("tree1 is " + TreeToString(tree0)); - - // Now iterate over which node to update first, |k|. - for (int k = 0; k < tree_size; k++) { - SCOPED_TRACE("i=" + base::IntToString(i) + - " j=" + base::IntToString(j) + - " k=" + base::IntToString(k)); - - // Start by serializing tree0 and unserializing it into a new - // empty tree |dst_tree|. - scoped_ptr<AXTreeSource<const AXNode*> > tree0_source( - tree0.CreateTreeSource()); - AXTreeSerializer<const AXNode*> serializer(tree0_source.get()); - AXTreeUpdate update0; - serializer.SerializeChanges(tree0.GetRoot(), &update0); - - AXTree dst_tree; - ASSERT_TRUE(dst_tree.Unserialize(update0)); - - // At this point, |dst_tree| should now be identical to |tree0|. - EXPECT_EQ(TreeToString(tree0), TreeToString(dst_tree)); - - // Next, pretend that tree0 turned into tree1, and serialize - // a sequence of updates to |dst_tree| to match. - scoped_ptr<AXTreeSource<const AXNode*> > tree1_source( - tree1.CreateTreeSource()); - serializer.ChangeTreeSourceForTesting(tree1_source.get()); - - for (int k_index = 0; k_index < tree_size; ++k_index) { - int id = 1 + (k + k_index) % tree_size; - AXTreeUpdate update; - serializer.SerializeChanges(tree1.GetFromId(id), &update); - ASSERT_TRUE(dst_tree.Unserialize(update)); - } - - // After the sequence of updates, |dst_tree| should now be - // identical to |tree1|. - EXPECT_EQ(TreeToString(tree1), TreeToString(dst_tree)); - } - } - } -} - -} // namespace ui
diff --git a/ui/accessibility/ax_node.cc b/ui/accessibility/ax_node.cc deleted file mode 100644 index 587f737..0000000 --- a/ui/accessibility/ax_node.cc +++ /dev/null
@@ -1,47 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/accessibility/ax_node.h" - -namespace ui { - -AXNode::AXNode(AXNode* parent, int32 id, int32 index_in_parent) - : index_in_parent_(index_in_parent), - parent_(parent) { - data_.id = id; -} - -AXNode::~AXNode() { -} - -void AXNode::SetData(const AXNodeData& src) { - data_ = src; -} - -void AXNode::SetLocation(const gfx::Rect& new_location) { - data_.location = new_location; -} - -void AXNode::SetIndexInParent(int index_in_parent) { - index_in_parent_ = index_in_parent; -} - -void AXNode::SwapChildren(std::vector<AXNode*>& children) { - children.swap(children_); -} - -void AXNode::Destroy() { - delete this; -} - -bool AXNode::IsDescendantOf(AXNode* ancestor) { - if (this == ancestor) - return true; - else if (parent()) - return parent()->IsDescendantOf(ancestor); - - return false; -} - -} // namespace ui
diff --git a/ui/accessibility/ax_node.h b/ui/accessibility/ax_node.h deleted file mode 100644 index 5da7340..0000000 --- a/ui/accessibility/ax_node.h +++ /dev/null
@@ -1,68 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_ACCESSIBILITY_AX_NODE_H_ -#define UI_ACCESSIBILITY_AX_NODE_H_ - -#include "ui/accessibility/ax_node_data.h" - -namespace ui { - -// One node in an AXTree. -class AX_EXPORT AXNode { - public: - // The constructor requires a parent, id, and index in parent, but - // the data is not required. After initialization, only index_in_parent - // is allowed to change, the others are guaranteed to never change. - AXNode(AXNode* parent, int32 id, int32 index_in_parent); - virtual ~AXNode(); - - // Accessors. - int32 id() const { return data_.id; } - AXNode* parent() const { return parent_; } - int child_count() const { return static_cast<int>(children_.size()); } - const AXNodeData& data() const { return data_; } - const std::vector<AXNode*>& children() const { return children_; } - int index_in_parent() const { return index_in_parent_; } - - // Get the child at the given index. - AXNode* ChildAtIndex(int index) const { return children_[index]; } - - // Set the node's accessibility data. This may be done during initial - // initialization or later when the node data changes. - void SetData(const AXNodeData& src); - - // Update this node's location. This is separate from SetData just because - // changing only the location is common and should be more efficient than - // re-copying all of the data. - void SetLocation(const gfx::Rect& new_location); - - // Set the index in parent, for example if siblings were inserted or deleted. - void SetIndexInParent(int index_in_parent); - - // Swap the internal children vector with |children|. This instance - // now owns all of the passed children. - void SwapChildren(std::vector<AXNode*>& children); - - // This is called when the AXTree no longer includes this node in the - // tree. Reference counting is used on some platforms because the - // operating system may hold onto a reference to an AXNode - // object even after we're through with it, so this may decrement the - // reference count and clear out the object's data. - void Destroy(); - - // Return true if this object is equal to or a descendant of |ancestor|. - bool IsDescendantOf(AXNode* ancestor); - - private: - int index_in_parent_; - AXNode* parent_; - std::vector<AXNode*> children_; - AXNodeData data_; -}; - - -} // namespace ui - -#endif // UI_ACCESSIBILITY_AX_NODE_H_
diff --git a/ui/accessibility/ax_node_data.cc b/ui/accessibility/ax_node_data.cc deleted file mode 100644 index a306214..0000000 --- a/ui/accessibility/ax_node_data.cc +++ /dev/null
@@ -1,407 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/accessibility/ax_node_data.h" - -#include <set> - -#include "base/strings/string_number_conversions.h" -#include "base/strings/string_util.h" -#include "base/strings/utf_string_conversions.h" - -using base::DoubleToString; -using base::IntToString; - -namespace ui { - -namespace { - -std::string IntVectorToString(const std::vector<int>& items) { - std::string str; - for (size_t i = 0; i < items.size(); ++i) { - if (i > 0) - str += ","; - str += IntToString(items[i]); - } - return str; -} - -} // Anonymous namespace - -AXNodeData::AXNodeData() - : id(-1), - role(AX_ROLE_UNKNOWN), - state(0xFFFFFFFF) { -} - -AXNodeData::~AXNodeData() { -} - -void AXNodeData::AddStringAttribute( - AXStringAttribute attribute, const std::string& value) { - string_attributes.push_back(std::make_pair(attribute, value)); -} - -void AXNodeData::AddIntAttribute( - AXIntAttribute attribute, int value) { - int_attributes.push_back(std::make_pair(attribute, value)); -} - -void AXNodeData::AddFloatAttribute( - AXFloatAttribute attribute, float value) { - float_attributes.push_back(std::make_pair(attribute, value)); -} - -void AXNodeData::AddBoolAttribute( - AXBoolAttribute attribute, bool value) { - bool_attributes.push_back(std::make_pair(attribute, value)); -} - -void AXNodeData::AddIntListAttribute( - AXIntListAttribute attribute, const std::vector<int32>& value) { - intlist_attributes.push_back(std::make_pair(attribute, value)); -} - -void AXNodeData::SetName(std::string name) { - string_attributes.push_back(std::make_pair(AX_ATTR_NAME, name)); -} - -void AXNodeData::SetValue(std::string value) { - string_attributes.push_back(std::make_pair(AX_ATTR_VALUE, value)); -} - -std::string AXNodeData::ToString() const { - std::string result; - - result += "id=" + IntToString(id); - result += " " + ui::ToString(role); - - if (state & (1 << ui::AX_STATE_BUSY)) - result += " BUSY"; - if (state & (1 << ui::AX_STATE_CHECKED)) - result += " CHECKED"; - if (state & (1 << ui::AX_STATE_COLLAPSED)) - result += " COLLAPSED"; - if (state & (1 << ui::AX_STATE_EXPANDED)) - result += " EXPANDED"; - if (state & (1 << ui::AX_STATE_FOCUSABLE)) - result += " FOCUSABLE"; - if (state & (1 << ui::AX_STATE_FOCUSED)) - result += " FOCUSED"; - if (state & (1 << ui::AX_STATE_HASPOPUP)) - result += " HASPOPUP"; - if (state & (1 << ui::AX_STATE_HOVERED)) - result += " HOVERED"; - if (state & (1 << ui::AX_STATE_INDETERMINATE)) - result += " INDETERMINATE"; - if (state & (1 << ui::AX_STATE_INVISIBLE)) - result += " INVISIBLE"; - if (state & (1 << ui::AX_STATE_LINKED)) - result += " LINKED"; - if (state & (1 << ui::AX_STATE_MULTISELECTABLE)) - result += " MULTISELECTABLE"; - if (state & (1 << ui::AX_STATE_OFFSCREEN)) - result += " OFFSCREEN"; - if (state & (1 << ui::AX_STATE_PRESSED)) - result += " PRESSED"; - if (state & (1 << ui::AX_STATE_PROTECTED)) - result += " PROTECTED"; - if (state & (1 << ui::AX_STATE_READ_ONLY)) - result += " READONLY"; - if (state & (1 << ui::AX_STATE_REQUIRED)) - result += " REQUIRED"; - if (state & (1 << ui::AX_STATE_SELECTABLE)) - result += " SELECTABLE"; - if (state & (1 << ui::AX_STATE_SELECTED)) - result += " SELECTED"; - if (state & (1 << ui::AX_STATE_VERTICAL)) - result += " VERTICAL"; - if (state & (1 << ui::AX_STATE_VISITED)) - result += " VISITED"; - - result += " (" + IntToString(location.x()) + ", " + - IntToString(location.y()) + ")-(" + - IntToString(location.width()) + ", " + - IntToString(location.height()) + ")"; - - for (size_t i = 0; i < int_attributes.size(); ++i) { - std::string value = IntToString(int_attributes[i].second); - switch (int_attributes[i].first) { - case AX_ATTR_SCROLL_X: - result += " scroll_x=" + value; - break; - case AX_ATTR_SCROLL_X_MIN: - result += " scroll_x_min=" + value; - break; - case AX_ATTR_SCROLL_X_MAX: - result += " scroll_x_max=" + value; - break; - case AX_ATTR_SCROLL_Y: - result += " scroll_y=" + value; - break; - case AX_ATTR_SCROLL_Y_MIN: - result += " scroll_y_min=" + value; - break; - case AX_ATTR_SCROLL_Y_MAX: - result += " scroll_y_max=" + value; - break; - case AX_ATTR_HIERARCHICAL_LEVEL: - result += " level=" + value; - break; - case AX_ATTR_TEXT_SEL_START: - result += " sel_start=" + value; - break; - case AX_ATTR_TEXT_SEL_END: - result += " sel_end=" + value; - break; - case AX_ATTR_TABLE_ROW_COUNT: - result += " rows=" + value; - break; - case AX_ATTR_TABLE_COLUMN_COUNT: - result += " cols=" + value; - break; - case AX_ATTR_TABLE_CELL_COLUMN_INDEX: - result += " col=" + value; - break; - case AX_ATTR_TABLE_CELL_ROW_INDEX: - result += " row=" + value; - break; - case AX_ATTR_TABLE_CELL_COLUMN_SPAN: - result += " colspan=" + value; - break; - case AX_ATTR_TABLE_CELL_ROW_SPAN: - result += " rowspan=" + value; - break; - case AX_ATTR_TABLE_COLUMN_HEADER_ID: - result += " column_header_id=" + value; - break; - case AX_ATTR_TABLE_COLUMN_INDEX: - result += " column_index=" + value; - break; - case AX_ATTR_TABLE_HEADER_ID: - result += " header_id=" + value; - break; - case AX_ATTR_TABLE_ROW_HEADER_ID: - result += " row_header_id=" + value; - break; - case AX_ATTR_TABLE_ROW_INDEX: - result += " row_index=" + value; - break; - case AX_ATTR_TITLE_UI_ELEMENT: - result += " title_elem=" + value; - break; - case AX_ATTR_ACTIVEDESCENDANT_ID: - result += " activedescendant=" + value; - break; - case AX_ATTR_COLOR_VALUE_RED: - result += " color_value_red=" + value; - break; - case AX_ATTR_COLOR_VALUE_GREEN: - result += " color_value_green=" + value; - break; - case AX_ATTR_COLOR_VALUE_BLUE: - result += " color_value_blue=" + value; - break; - case AX_ATTR_TEXT_DIRECTION: - switch (int_attributes[i].second) { - case AX_TEXT_DIRECTION_LR: - default: - result += " text_direction=lr"; - break; - case AX_TEXT_DIRECTION_RL: - result += " text_direction=rl"; - break; - case AX_TEXT_DIRECTION_TB: - result += " text_direction=tb"; - break; - case AX_TEXT_DIRECTION_BT: - result += " text_direction=bt"; - break; - } - break; - case AX_INT_ATTRIBUTE_NONE: - break; - } - } - - for (size_t i = 0; i < string_attributes.size(); ++i) { - std::string value = string_attributes[i].second; - switch (string_attributes[i].first) { - case AX_ATTR_DOC_URL: - result += " doc_url=" + value; - break; - case AX_ATTR_DOC_TITLE: - result += " doc_title=" + value; - break; - case AX_ATTR_DOC_MIMETYPE: - result += " doc_mimetype=" + value; - break; - case AX_ATTR_DOC_DOCTYPE: - result += " doc_doctype=" + value; - break; - case AX_ATTR_ACCESS_KEY: - result += " access_key=" + value; - break; - case AX_ATTR_ACTION: - result += " action=" + value; - break; - case AX_ATTR_DESCRIPTION: - result += " description=" + value; - break; - case AX_ATTR_DISPLAY: - result += " display=" + value; - break; - case AX_ATTR_HELP: - result += " help=" + value; - break; - case AX_ATTR_HTML_TAG: - result += " html_tag=" + value; - break; - case AX_ATTR_LIVE_RELEVANT: - result += " relevant=" + value; - break; - case AX_ATTR_LIVE_STATUS: - result += " live=" + value; - break; - case AX_ATTR_CONTAINER_LIVE_RELEVANT: - result += " container_relevant=" + value; - break; - case AX_ATTR_CONTAINER_LIVE_STATUS: - result += " container_live=" + value; - break; - case AX_ATTR_ROLE: - result += " role=" + value; - break; - case AX_ATTR_SHORTCUT: - result += " shortcut=" + value; - break; - case AX_ATTR_TEXT_INPUT_TYPE: - result += " text_input_type=" + value; - break; - case AX_ATTR_URL: - result += " url=" + value; - break; - case AX_ATTR_NAME: - result += " name=" + value; - break; - case AX_ATTR_VALUE: - result += " value=" + value; - break; - case AX_STRING_ATTRIBUTE_NONE: - break; - } - } - - for (size_t i = 0; i < float_attributes.size(); ++i) { - std::string value = DoubleToString(float_attributes[i].second); - switch (float_attributes[i].first) { - case AX_ATTR_DOC_LOADING_PROGRESS: - result += " doc_progress=" + value; - break; - case AX_ATTR_VALUE_FOR_RANGE: - result += " value_for_range=" + value; - break; - case AX_ATTR_MAX_VALUE_FOR_RANGE: - result += " max_value=" + value; - break; - case AX_ATTR_MIN_VALUE_FOR_RANGE: - result += " min_value=" + value; - break; - case AX_FLOAT_ATTRIBUTE_NONE: - break; - } - } - - for (size_t i = 0; i < bool_attributes.size(); ++i) { - std::string value = bool_attributes[i].second ? "true" : "false"; - switch (bool_attributes[i].first) { - case AX_ATTR_DOC_LOADED: - result += " doc_loaded=" + value; - break; - case AX_ATTR_BUTTON_MIXED: - result += " mixed=" + value; - break; - case AX_ATTR_LIVE_ATOMIC: - result += " atomic=" + value; - break; - case AX_ATTR_LIVE_BUSY: - result += " busy=" + value; - break; - case AX_ATTR_CONTAINER_LIVE_ATOMIC: - result += " container_atomic=" + value; - break; - case AX_ATTR_CONTAINER_LIVE_BUSY: - result += " container_busy=" + value; - break; - case AX_ATTR_ARIA_READONLY: - result += " aria_readonly=" + value; - break; - case AX_ATTR_CAN_SET_VALUE: - result += " can_set_value=" + value; - break; - case AX_ATTR_UPDATE_LOCATION_ONLY: - result += " update_location_only=" + value; - break; - case AX_ATTR_CANVAS_HAS_FALLBACK: - result += " has_fallback=" + value; - break; - case AX_ATTR_IS_AX_TREE_HOST: - result += " is_ax_tree_host=" + value; - break; - case AX_BOOL_ATTRIBUTE_NONE: - break; - } - } - - for (size_t i = 0; i < intlist_attributes.size(); ++i) { - const std::vector<int32>& values = intlist_attributes[i].second; - switch (intlist_attributes[i].first) { - case AX_ATTR_INDIRECT_CHILD_IDS: - result += " indirect_child_ids=" + IntVectorToString(values); - break; - case AX_ATTR_CONTROLS_IDS: - result += " controls_ids=" + IntVectorToString(values); - break; - case AX_ATTR_DESCRIBEDBY_IDS: - result += " describedby_ids=" + IntVectorToString(values); - break; - case AX_ATTR_FLOWTO_IDS: - result += " flowto_ids=" + IntVectorToString(values); - break; - case AX_ATTR_LABELLEDBY_IDS: - result += " labelledby_ids=" + IntVectorToString(values); - break; - case AX_ATTR_OWNS_IDS: - result += " owns_ids=" + IntVectorToString(values); - break; - case AX_ATTR_LINE_BREAKS: - result += " line_breaks=" + IntVectorToString(values); - break; - case AX_ATTR_CELL_IDS: - result += " cell_ids=" + IntVectorToString(values); - break; - case AX_ATTR_UNIQUE_CELL_IDS: - result += " unique_cell_ids=" + IntVectorToString(values); - break; - case AX_ATTR_CHARACTER_OFFSETS: - result += " character_offsets=" + IntVectorToString(values); - break; - case AX_ATTR_WORD_STARTS: - result += " word_starts=" + IntVectorToString(values); - break; - case AX_ATTR_WORD_ENDS: - result += " word_ends=" + IntVectorToString(values); - break; - case AX_INT_LIST_ATTRIBUTE_NONE: - break; - } - } - - if (!child_ids.empty()) - result += " child_ids=" + IntVectorToString(child_ids); - - return result; -} - -} // namespace ui
diff --git a/ui/accessibility/ax_node_data.h b/ui/accessibility/ax_node_data.h deleted file mode 100644 index b6a1310..0000000 --- a/ui/accessibility/ax_node_data.h +++ /dev/null
@@ -1,62 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_ACCESSIBILITY_AX_NODE_DATA_H_ -#define UI_ACCESSIBILITY_AX_NODE_DATA_H_ - -#include <map> -#include <string> -#include <vector> - -#include "base/strings/string16.h" -#include "base/strings/string_split.h" -#include "ui/accessibility/ax_enums.h" -#include "ui/accessibility/ax_export.h" -#include "ui/gfx/rect.h" - -namespace ui { - -// A compact representation of the accessibility information for a -// single web object, in a form that can be serialized and sent from -// one process to another. -struct AX_EXPORT AXNodeData { - AXNodeData(); - virtual ~AXNodeData(); - - void AddStringAttribute(AXStringAttribute attribute, - const std::string& value); - void AddIntAttribute(AXIntAttribute attribute, int value); - void AddFloatAttribute(AXFloatAttribute attribute, float value); - void AddBoolAttribute(AXBoolAttribute attribute, bool value); - void AddIntListAttribute(AXIntListAttribute attribute, - const std::vector<int32>& value); - - // Convenience functions, mainly for writing unit tests. - // Equivalent to AddStringAttribute(ATTR_NAME, name). - void SetName(std::string name); - // Equivalent to AddStringAttribute(ATTR_VALUE, value). - void SetValue(std::string value); - - // Return a string representation of this data, for debugging. - std::string ToString() const; - - // This is a simple serializable struct. All member variables should be - // public and copyable. - int32 id; - AXRole role; - uint32 state; - gfx::Rect location; - std::vector<std::pair<AXStringAttribute, std::string> > string_attributes; - std::vector<std::pair<AXIntAttribute, int32> > int_attributes; - std::vector<std::pair<AXFloatAttribute, float> > float_attributes; - std::vector<std::pair<AXBoolAttribute, bool> > bool_attributes; - std::vector<std::pair<AXIntListAttribute, std::vector<int32> > > - intlist_attributes; - base::StringPairs html_attributes; - std::vector<int32> child_ids; -}; - -} // namespace ui - -#endif // UI_ACCESSIBILITY_AX_NODE_DATA_H_
diff --git a/ui/accessibility/ax_serializable_tree.cc b/ui/accessibility/ax_serializable_tree.cc deleted file mode 100644 index 750b3b0..0000000 --- a/ui/accessibility/ax_serializable_tree.cc +++ /dev/null
@@ -1,69 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/accessibility/ax_serializable_tree.h" - -#include "ui/accessibility/ax_node.h" - -namespace ui { - -// This class is an implementation of the AXTreeSource interface with -// AXNode as the node type, that just delegates to an AXTree. The purpose -// of this is so that AXTreeSerializer only needs to work with the -// AXTreeSource abstraction and doesn't need to actually know about -// AXTree directly. Another AXTreeSource is used to abstract the Blink -// accessibility tree. -class AX_EXPORT AXTreeSourceAdapter : public AXTreeSource<const AXNode*> { - public: - AXTreeSourceAdapter(AXTree* tree) : tree_(tree) {} - ~AXTreeSourceAdapter() override {} - - // AXTreeSource implementation. - AXNode* GetRoot() const override { return tree_->GetRoot(); } - - AXNode* GetFromId(int32 id) const override { return tree_->GetFromId(id); } - - int32 GetId(const AXNode* node) const override { return node->id(); } - - void GetChildren(const AXNode* node, - std::vector<const AXNode*>* out_children) const override { - for (int i = 0; i < node->child_count(); ++i) - out_children->push_back(node->ChildAtIndex(i)); - } - - AXNode* GetParent(const AXNode* node) const override { - return node->parent(); - } - - bool IsValid(const AXNode* node) const override { return node != NULL; } - - bool IsEqual(const AXNode* node1, const AXNode* node2) const override { - return node1 == node2; - } - - const AXNode* GetNull() const override { return NULL; } - - void SerializeNode(const AXNode* node, AXNodeData* out_data) const override { - *out_data = node->data(); - } - - private: - AXTree* tree_; -}; - -AXSerializableTree::AXSerializableTree() - : AXTree() {} - -AXSerializableTree::AXSerializableTree(const AXTreeUpdate& initial_state) - : AXTree(initial_state) { -} - -AXSerializableTree::~AXSerializableTree() { -} - -AXTreeSource<const AXNode*>* AXSerializableTree::CreateTreeSource() { - return new AXTreeSourceAdapter(this); -} - -} // namespace ui
diff --git a/ui/accessibility/ax_serializable_tree.h b/ui/accessibility/ax_serializable_tree.h deleted file mode 100644 index dfbdf8e..0000000 --- a/ui/accessibility/ax_serializable_tree.h +++ /dev/null
@@ -1,26 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_ACCESSIBILITY_AX_SERIALIZABLE_TREE_H_ -#define UI_ACCESSIBILITY_AX_SERIALIZABLE_TREE_H_ - -#include "ui/accessibility/ax_tree.h" -#include "ui/accessibility/ax_tree_source.h" - -namespace ui { - -class AX_EXPORT AXSerializableTree : public AXTree { - public: - AXSerializableTree(); - explicit AXSerializableTree(const AXTreeUpdate& initial_state); - ~AXSerializableTree() override; - - // Create a TreeSource adapter for this tree. The client gets ownership - // of the return value and should delete it when done. - virtual AXTreeSource<const AXNode*>* CreateTreeSource(); -}; - -} // namespace ui - -#endif // UI_ACCESSIBILITY_AX_TREE_H_
diff --git a/ui/accessibility/ax_text_utils.cc b/ui/accessibility/ax_text_utils.cc deleted file mode 100644 index 08cd562..0000000 --- a/ui/accessibility/ax_text_utils.cc +++ /dev/null
@@ -1,88 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/accessibility/ax_text_utils.h" - -#include "base/logging.h" -#include "base/strings/string_util.h" - -namespace ui { - -size_t FindAccessibleTextBoundary(const base::string16& text, - const std::vector<int>& line_breaks, - TextBoundaryType boundary, - size_t start_offset, - TextBoundaryDirection direction) { - size_t text_size = text.size(); - DCHECK(start_offset <= text_size); - - if (boundary == CHAR_BOUNDARY) { - if (direction == FORWARDS_DIRECTION && start_offset < text_size) - return start_offset + 1; - else - return start_offset; - } else if (boundary == LINE_BOUNDARY) { - if (direction == FORWARDS_DIRECTION) { - for (size_t j = 0; j < line_breaks.size(); ++j) { - size_t line_break = line_breaks[j] >= 0 ? line_breaks[j] : 0; - if (line_break > start_offset) - return line_break; - } - return text_size; - } else { - for (size_t j = line_breaks.size(); j != 0; --j) { - size_t line_break = line_breaks[j - 1] >= 0 ? line_breaks[j - 1] : 0; - if (line_break <= start_offset) - return line_break; - } - return 0; - } - } - - size_t result = start_offset; - for (;;) { - size_t pos; - if (direction == FORWARDS_DIRECTION) { - if (result >= text_size) - return text_size; - pos = result; - } else { - if (result == 0) - return 0; - pos = result - 1; - } - - switch (boundary) { - case CHAR_BOUNDARY: - case LINE_BOUNDARY: - NOTREACHED(); // These are handled above. - break; - case WORD_BOUNDARY: - if (IsWhitespace(text[pos])) - return result; - break; - case PARAGRAPH_BOUNDARY: - if (text[pos] == '\n') - return result; - break; - case SENTENCE_BOUNDARY: - if ((text[pos] == '.' || text[pos] == '!' || text[pos] == '?') && - (pos == text_size - 1 || IsWhitespace(text[pos + 1]))) { - return result; - } - break; - case ALL_BOUNDARY: - default: - break; - } - - if (direction == FORWARDS_DIRECTION) { - result++; - } else { - result--; - } - } -} - -} // Namespace ui
diff --git a/ui/accessibility/ax_text_utils.h b/ui/accessibility/ax_text_utils.h deleted file mode 100644 index 2dc2d2f..0000000 --- a/ui/accessibility/ax_text_utils.h +++ /dev/null
@@ -1,54 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_ACCESSIBILITY_AX_TEXT_UTILS_H_ -#define UI_ACCESSIBILITY_AX_TEXT_UTILS_H_ - -#include <vector> - -#include "base/basictypes.h" -#include "base/strings/string16.h" -#include "ui/accessibility/ax_export.h" - -namespace ui { - -// Boundaries that can be passed to FindAccessibleTextBoundary, -// representing various visual boundaries in (potentially multi-line) -// text. This is used by assistive technology in order to, for example, -// retrieve the nearest word to the cursor, or retrieve all of the -// text from the current cursor position to the end of the line. -// These should be self-explanatory; "line" here refers to the visual -// line as currently displayed (possibly affected by wrapping). -enum TextBoundaryType { - CHAR_BOUNDARY, - WORD_BOUNDARY, - LINE_BOUNDARY, - SENTENCE_BOUNDARY, - PARAGRAPH_BOUNDARY, - ALL_BOUNDARY -}; - -// A direction when searching for the next boundary. -enum TextBoundaryDirection { - // Search forwards for the next boundary past the starting position. - FORWARDS_DIRECTION, - // Search backwards for the previous boundary before the starting position. - BACKWARDS_DIRECTION -}; - -// Convenience method needed to implement platform-specific text -// accessibility APIs like IAccessible2. Search forwards or backwards -// (depending on |direction|) from the given |start_offset| until the -// given boundary is found, and return the offset of that boundary, -// using the vector of line break character offsets in |line_breaks|. -size_t AX_EXPORT - FindAccessibleTextBoundary(const base::string16& text, - const std::vector<int>& line_breaks, - TextBoundaryType boundary, - size_t start_offset, - TextBoundaryDirection direction); - -} // namespace ui - -#endif // UI_ACCESSIBILITY_AX_TEXT_UTILS_H_
diff --git a/ui/accessibility/ax_tree.cc b/ui/accessibility/ax_tree.cc deleted file mode 100644 index ecfbae8..0000000 --- a/ui/accessibility/ax_tree.cc +++ /dev/null
@@ -1,269 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/accessibility/ax_tree.h" - -#include <set> - -#include "base/logging.h" -#include "base/strings/stringprintf.h" -#include "ui/accessibility/ax_node.h" - -namespace ui { - -namespace { - -std::string TreeToStringHelper(AXNode* node, int indent) { - std::string result = std::string(2 * indent, ' '); - result += node->data().ToString() + "\n"; - for (int i = 0; i < node->child_count(); ++i) - result += TreeToStringHelper(node->ChildAtIndex(i), indent + 1); - return result; -} - -} // anonymous namespace - -// Intermediate state to keep track of during a tree update. -struct AXTreeUpdateState { - // During an update, this keeps track of all nodes that have been - // implicitly referenced as part of this update, but haven't been - // updated yet. It's an error if there are any pending nodes at the - // end of Unserialize. - std::set<AXNode*> pending_nodes; - - // Keeps track of new nodes created during this update. - std::set<AXNode*> new_nodes; -}; - -AXTreeDelegate::AXTreeDelegate() { -} - -AXTreeDelegate::~AXTreeDelegate() { -} - -AXTree::AXTree() - : delegate_(NULL), root_(NULL) { - AXNodeData root; - root.id = -1; - root.role = AX_ROLE_ROOT_WEB_AREA; - - AXTreeUpdate initial_state; - initial_state.nodes.push_back(root); - CHECK(Unserialize(initial_state)) << error(); -} - -AXTree::AXTree(const AXTreeUpdate& initial_state) - : delegate_(NULL), root_(NULL) { - CHECK(Unserialize(initial_state)) << error(); -} - -AXTree::~AXTree() { - if (root_) - DestroyNodeAndSubtree(root_); -} - -void AXTree::SetDelegate(AXTreeDelegate* delegate) { - delegate_ = delegate; -} - -AXNode* AXTree::GetRoot() const { - return root_; -} - -AXNode* AXTree::GetFromId(int32 id) const { - base::hash_map<int32, AXNode*>::const_iterator iter = id_map_.find(id); - return iter != id_map_.end() ? (iter->second) : NULL; -} - -bool AXTree::Unserialize(const AXTreeUpdate& update) { - AXTreeUpdateState update_state; - int32 old_root_id = root_ ? root_->id() : 0; - - if (update.node_id_to_clear != 0) { - AXNode* node = GetFromId(update.node_id_to_clear); - if (!node) { - error_ = base::StringPrintf("Bad node_id_to_clear: %d", - update.node_id_to_clear); - return false; - } - if (node == root_) { - DestroyNodeAndSubtree(root_); - root_ = NULL; - } else { - for (int i = 0; i < node->child_count(); ++i) - DestroyNodeAndSubtree(node->ChildAtIndex(i)); - std::vector<AXNode*> children; - node->SwapChildren(children); - update_state.pending_nodes.insert(node); - } - } - - for (size_t i = 0; i < update.nodes.size(); ++i) { - if (!UpdateNode(update.nodes[i], &update_state)) - return false; - } - - if (!update_state.pending_nodes.empty()) { - error_ = "Nodes left pending by the update:"; - for (std::set<AXNode*>::iterator iter = update_state.pending_nodes.begin(); - iter != update_state.pending_nodes.end(); ++iter) { - error_ += base::StringPrintf(" %d", (*iter)->id()); - } - return false; - } - - if (delegate_) { - for (size_t i = 0; i < update.nodes.size(); ++i) { - AXNode* node = GetFromId(update.nodes[i].id); - if (update_state.new_nodes.find(node) != update_state.new_nodes.end()) { - delegate_->OnNodeCreationFinished(node); - update_state.new_nodes.erase(node); - } else { - delegate_->OnNodeChangeFinished(node); - } - } - if (root_->id() != old_root_id) - delegate_->OnRootChanged(root_); - } - - return true; -} - -std::string AXTree::ToString() const { - return TreeToStringHelper(root_, 0); -} - -AXNode* AXTree::CreateNode( - AXNode* parent, int32 id, int32 index_in_parent) { - AXNode* new_node = new AXNode(parent, id, index_in_parent); - id_map_[new_node->id()] = new_node; - if (delegate_) - delegate_->OnNodeCreated(new_node); - return new_node; -} - -bool AXTree::UpdateNode( - const AXNodeData& src, AXTreeUpdateState* update_state) { - // This method updates one node in the tree based on serialized data - // received in an AXTreeUpdate. See AXTreeUpdate for pre and post - // conditions. - - // Look up the node by id. If it's not found, then either the root - // of the tree is being swapped, or we're out of sync with the source - // and this is a serious error. - AXNode* node = GetFromId(src.id); - AXNode* new_root = NULL; - if (node) { - update_state->pending_nodes.erase(node); - node->SetData(src); - } else { - if (src.role != AX_ROLE_ROOT_WEB_AREA) { - error_ = base::StringPrintf( - "%d is not in the tree and not the new root", src.id); - return false; - } - new_root = CreateNode(NULL, src.id, 0); - node = new_root; - update_state->new_nodes.insert(node); - node->SetData(src); - } - - if (delegate_) - delegate_->OnNodeChanged(node); - - // First, delete nodes that used to be children of this node but aren't - // anymore. - if (!DeleteOldChildren(node, src.child_ids)) { - if (new_root) - DestroyNodeAndSubtree(new_root); - return false; - } - - // Now build a new children vector, reusing nodes when possible, - // and swap it in. - std::vector<AXNode*> new_children; - bool success = CreateNewChildVector( - node, src.child_ids, &new_children, update_state); - node->SwapChildren(new_children); - - // Update the root of the tree if needed. - if (src.role == AX_ROLE_ROOT_WEB_AREA && - (!root_ || root_->id() != src.id)) { - if (root_) - DestroyNodeAndSubtree(root_); - root_ = node; - } - - return success; -} - -void AXTree::DestroyNodeAndSubtree(AXNode* node) { - id_map_.erase(node->id()); - for (int i = 0; i < node->child_count(); ++i) - DestroyNodeAndSubtree(node->ChildAtIndex(i)); - if (delegate_) - delegate_->OnNodeWillBeDeleted(node); - node->Destroy(); -} - -bool AXTree::DeleteOldChildren(AXNode* node, - const std::vector<int32> new_child_ids) { - // Create a set of child ids in |src| for fast lookup, and return false - // if a duplicate is found; - std::set<int32> new_child_id_set; - for (size_t i = 0; i < new_child_ids.size(); ++i) { - if (new_child_id_set.find(new_child_ids[i]) != new_child_id_set.end()) { - error_ = base::StringPrintf("Node %d has duplicate child id %d", - node->id(), new_child_ids[i]); - return false; - } - new_child_id_set.insert(new_child_ids[i]); - } - - // Delete the old children. - const std::vector<AXNode*>& old_children = node->children(); - for (size_t i = 0; i < old_children.size(); ++i) { - int old_id = old_children[i]->id(); - if (new_child_id_set.find(old_id) == new_child_id_set.end()) - DestroyNodeAndSubtree(old_children[i]); - } - - return true; -} - -bool AXTree::CreateNewChildVector(AXNode* node, - const std::vector<int32> new_child_ids, - std::vector<AXNode*>* new_children, - AXTreeUpdateState* update_state) { - bool success = true; - for (size_t i = 0; i < new_child_ids.size(); ++i) { - int32 child_id = new_child_ids[i]; - int32 index_in_parent = static_cast<int32>(i); - AXNode* child = GetFromId(child_id); - if (child) { - if (child->parent() != node) { - // This is a serious error - nodes should never be reparented. - // If this case occurs, continue so this node isn't left in an - // inconsistent state, but return failure at the end. - error_ = base::StringPrintf( - "Node %d reparented from %d to %d", - child->id(), - child->parent() ? child->parent()->id() : 0, - node->id()); - success = false; - continue; - } - child->SetIndexInParent(index_in_parent); - } else { - child = CreateNode(node, child_id, index_in_parent); - update_state->pending_nodes.insert(child); - update_state->new_nodes.insert(child); - } - new_children->push_back(child); - } - - return success; -} - -} // namespace ui
diff --git a/ui/accessibility/ax_tree.h b/ui/accessibility/ax_tree.h deleted file mode 100644 index b4baac4..0000000 --- a/ui/accessibility/ax_tree.h +++ /dev/null
@@ -1,128 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_ACCESSIBILITY_AX_TREE_H_ -#define UI_ACCESSIBILITY_AX_TREE_H_ - -#include <set> - -#include "base/containers/hash_tables.h" -#include "ui/accessibility/ax_export.h" -#include "ui/accessibility/ax_tree_update.h" - -namespace ui { - -class AXNode; -struct AXTreeUpdateState; - -// Used when you want to be notified when changes happen to the tree. -// -// Some of the notifications are called in the middle of an update operation. -// Be careful, as the tree may be in an inconsistent state at this time; -// don't walk the parents and children at this time: -// OnNodeWillBeDeleted -// OnNodeCreated -// OnNodeChanged -// -// Other notifications are called at the end of an atomic update operation. -// From these, it's safe to walk the tree and do any initialization that -// assumes the tree is in a consistent state. -// OnNodeCreationFinished -// OnNodeChangeFinished -// OnRootChanged -class AX_EXPORT AXTreeDelegate { - public: - AXTreeDelegate(); - virtual ~AXTreeDelegate(); - - // Called just before a node is deleted. Its id and data will be valid, - // but its links to parents and children are invalid. This is called - // in the middle of an update, the tree may be in an invalid state! - virtual void OnNodeWillBeDeleted(AXNode* node) = 0; - - // Called immediately after a new node is created. The tree may be in - // the middle of an update, don't walk the parents and children now. - virtual void OnNodeCreated(AXNode* node) = 0; - - // Called when a node changes its data or children. The tree may be in - // the middle of an update, don't walk the parents and children now. - virtual void OnNodeChanged(AXNode* node) = 0; - - // Called for each new node at the end of an update operation, - // when the tree is in a consistent state. - virtual void OnNodeCreationFinished(AXNode* node) = 0; - - // Called for each existing node that changed at the end of an update - // operation, when the tree is in a consistent state. - virtual void OnNodeChangeFinished(AXNode* node) = 0; - - // Called at the end of an update operation when the root node changes. - virtual void OnRootChanged(AXNode* new_root) = 0; -}; - -// AXTree is a live, managed tree of AXNode objects that can receive -// updates from another AXTreeSource via AXTreeUpdates, and it can be -// used as a source for sending updates to another client tree. -// It's designed to be subclassed to implement support for native -// accessibility APIs on a specific platform. -class AX_EXPORT AXTree { - public: - AXTree(); - explicit AXTree(const AXTreeUpdate& initial_state); - virtual ~AXTree(); - - virtual void SetDelegate(AXTreeDelegate* delegate); - - virtual AXNode* GetRoot() const; - virtual AXNode* GetFromId(int32 id) const; - - // Returns true on success. If it returns false, it's a fatal error - // and this tree should be destroyed, and the source of the tree update - // should not be trusted any longer. - virtual bool Unserialize(const AXTreeUpdate& update); - - // Return a multi-line indented string representation, for logging. - std::string ToString() const; - - // A string describing the error from an unsuccessful Unserialize, - // for testing and debugging. - const std::string& error() { return error_; } - - private: - AXNode* CreateNode(AXNode* parent, int32 id, int32 index_in_parent); - - // This is called from within Unserialize(), it returns true on success. - bool UpdateNode(const AXNodeData& src, AXTreeUpdateState* update_state); - - void OnRootChanged(); - - // Call Destroy() on |node|, and delete it from the id map, and then - // call recursively on all nodes in its subtree. - void DestroyNodeAndSubtree(AXNode* node); - - // Iterate over the children of |node| and for each child, destroy the - // child and its subtree if its id is not in |new_child_ids|. Returns - // true on success, false on fatal error. - bool DeleteOldChildren(AXNode* node, - const std::vector<int32> new_child_ids); - - // Iterate over |new_child_ids| and populate |new_children| with - // pointers to child nodes, reusing existing nodes already in the tree - // if they exist, and creating otherwise. Reparenting is disallowed, so - // if the id already exists as the child of another node, that's an - // error. Returns true on success, false on fatal error. - bool CreateNewChildVector(AXNode* node, - const std::vector<int32> new_child_ids, - std::vector<AXNode*>* new_children, - AXTreeUpdateState* update_state); - - AXTreeDelegate* delegate_; - AXNode* root_; - base::hash_map<int32, AXNode*> id_map_; - std::string error_; -}; - -} // namespace ui - -#endif // UI_ACCESSIBILITY_AX_TREE_H_
diff --git a/ui/accessibility/ax_tree_serializer.cc b/ui/accessibility/ax_tree_serializer.cc deleted file mode 100644 index eff444c..0000000 --- a/ui/accessibility/ax_tree_serializer.cc +++ /dev/null
@@ -1,15 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/accessibility/ax_tree_serializer.h" - -namespace ui { - -ClientTreeNode::ClientTreeNode() { -} - -ClientTreeNode::~ClientTreeNode() { -} - -} // namespace ui
diff --git a/ui/accessibility/ax_tree_serializer.h b/ui/accessibility/ax_tree_serializer.h deleted file mode 100644 index f1cbfce..0000000 --- a/ui/accessibility/ax_tree_serializer.h +++ /dev/null
@@ -1,465 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_ACCESSIBILITY_AX_TREE_SERIALIZER_H_ -#define UI_ACCESSIBILITY_AX_TREE_SERIALIZER_H_ - -#include <set> - -#include "base/containers/hash_tables.h" -#include "base/logging.h" -#include "base/stl_util.h" -#include "ui/accessibility/ax_tree_source.h" -#include "ui/accessibility/ax_tree_update.h" - -namespace ui { - -struct ClientTreeNode; - -// AXTreeSerializer is a helper class that serializes incremental -// updates to an AXTreeSource as a AXTreeUpdate struct. -// These structs can be unserialized by a client object such as an -// AXTree. An AXTreeSerializer keeps track of the tree of node ids that its -// client is aware of so that it will never generate an AXTreeUpdate that -// results in an invalid tree. -// -// Every node in the source tree must have an id that's a unique positive -// integer, the same node must not appear twice. -// -// Usage: -// -// You must call SerializeChanges() every time a node in the tree changes, -// and send the generated AXTreeUpdate to the client. -// -// If a node is added, call SerializeChanges on its parent. -// If a node is removed, call SerializeChanges on its parent. -// If a whole new subtree is added, just call SerializeChanges on its root. -// If the root of the tree changes, call SerializeChanges on the new root. -// -// AXTreeSerializer will avoid re-serializing nodes that do not change. -// For example, if node 1 has children 2, 3, 4, 5 and then child 2 is -// removed and a new child 6 is added, the AXTreeSerializer will only -// update nodes 1 and 6 (and any children of node 6 recursively). It will -// assume that nodes 3, 4, and 5 are not modified unless you explicitly -// call SerializeChanges() on them. -// -// As long as the source tree has unique ids for every node and no loops, -// and as long as every update is applied to the client tree, AXTreeSerializer -// will continue to work. If the source tree makes a change but fails to -// call SerializeChanges properly, the trees may get out of sync - but -// because AXTreeSerializer always keeps track of what updates it's sent, -// it will never send an invalid update and the client tree will not break, -// it just may not contain all of the changes. -template<typename AXSourceNode> -class AXTreeSerializer { - public: - explicit AXTreeSerializer(AXTreeSource<AXSourceNode>* tree); - ~AXTreeSerializer(); - - // Throw out the internal state that keeps track of the nodes the client - // knows about. This has the effect that the next update will send the - // entire tree over because it assumes the client knows nothing. - void Reset(); - - // Serialize all changes to |node| and append them to |out_update|. - void SerializeChanges(AXSourceNode node, - AXTreeUpdate* out_update); - - // Delete the client subtree for this node, ensuring that the subtree - // is re-serialized. - void DeleteClientSubtree(AXSourceNode node); - - // Only for unit testing. Normally this class relies on getting a call - // to SerializeChanges() every time the source tree changes. For unit - // testing, it's convenient to create a static AXTree for the initial - // state and then call ChangeTreeSourceForTesting and then SerializeChanges - // to simulate the changes you'd get if a tree changed from the initial - // state to the second tree's state. - void ChangeTreeSourceForTesting(AXTreeSource<AXSourceNode>* new_tree); - - private: - // Return the least common ancestor of a node in the source tree - // and a node in the client tree, or NULL if there is no such node. - // The least common ancestor is the closest ancestor to |node| (which - // may be |node| itself) that's in both the source tree and client tree, - // and for which both the source and client tree agree on their ancestor - // chain up to the root. - // - // Example 1: - // - // Client Tree Source tree | - // 1 1 | - // / \ / \ | - // 2 3 2 4 | - // - // LCA(source node 2, client node 2) is node 2. - // LCA(source node 3, client node 4) is node 1. - // - // Example 2: - // - // Client Tree Source tree | - // 1 1 | - // / \ / \ | - // 2 3 2 3 | - // / \ / / | - // 4 7 8 4 | - // / \ / \ | - // 5 6 5 6 | - // - // LCA(source node 8, client node 7) is node 2. - // LCA(source node 5, client node 5) is node 1. - // It's not node 5, because the two trees disagree on the parent of - // node 4, so the LCA is the first ancestor both trees agree on. - AXSourceNode LeastCommonAncestor(AXSourceNode node, - ClientTreeNode* client_node); - - // Return the least common ancestor of |node| that's in the client tree. - // This just walks up the ancestors of |node| until it finds a node that's - // also in the client tree, and then calls LeastCommonAncestor on the - // source node and client node. - AXSourceNode LeastCommonAncestor(AXSourceNode node); - - // Walk the subtree rooted at |node| and return true if any nodes that - // would be updated are being reparented. If so, update |out_lca| to point - // to the least common ancestor of the previous LCA and the previous - // parent of the node being reparented. - bool AnyDescendantWasReparented(AXSourceNode node, - AXSourceNode* out_lca); - - ClientTreeNode* ClientTreeNodeById(int32 id); - - // Delete the given client tree node and recursively delete all of its - // descendants. - void DeleteClientSubtree(ClientTreeNode* client_node); - - // Helper function, called recursively with each new node to serialize. - void SerializeChangedNodes(AXSourceNode node, - AXTreeUpdate* out_update); - - // The tree source. - AXTreeSource<AXSourceNode>* tree_; - - // Our representation of the client tree. - ClientTreeNode* client_root_; - - // A map from IDs to nodes in the client tree. - base::hash_map<int32, ClientTreeNode*> client_id_map_; -}; - -// In order to keep track of what nodes the client knows about, we keep a -// representation of the client tree - just IDs and parent/child -// relationships. -struct AX_EXPORT ClientTreeNode { - ClientTreeNode(); - virtual ~ClientTreeNode(); - int32 id; - ClientTreeNode* parent; - std::vector<ClientTreeNode*> children; -}; - -template<typename AXSourceNode> -AXTreeSerializer<AXSourceNode>::AXTreeSerializer( - AXTreeSource<AXSourceNode>* tree) - : tree_(tree), - client_root_(NULL) { -} - -template<typename AXSourceNode> -AXTreeSerializer<AXSourceNode>::~AXTreeSerializer() { - Reset(); -} - -template<typename AXSourceNode> -void AXTreeSerializer<AXSourceNode>::Reset() { - if (!client_root_) - return; - - DeleteClientSubtree(client_root_); - client_id_map_.erase(client_root_->id); - delete client_root_; - client_root_ = NULL; -} - -template<typename AXSourceNode> -void AXTreeSerializer<AXSourceNode>::ChangeTreeSourceForTesting( - AXTreeSource<AXSourceNode>* new_tree) { - tree_ = new_tree; -} - -template<typename AXSourceNode> -AXSourceNode AXTreeSerializer<AXSourceNode>::LeastCommonAncestor( - AXSourceNode node, ClientTreeNode* client_node) { - if (!tree_->IsValid(node) || client_node == NULL) - return tree_->GetNull(); - - std::vector<AXSourceNode> ancestors; - while (tree_->IsValid(node)) { - ancestors.push_back(node); - node = tree_->GetParent(node); - } - - std::vector<ClientTreeNode*> client_ancestors; - while (client_node) { - client_ancestors.push_back(client_node); - client_node = client_node->parent; - } - - // Start at the root. Keep going until the source ancestor chain and - // client ancestor chain disagree. The last node before they disagree - // is the LCA. - AXSourceNode lca = tree_->GetNull(); - int source_index = static_cast<int>(ancestors.size() - 1); - int client_index = static_cast<int>(client_ancestors.size() - 1); - while (source_index >= 0 && client_index >= 0) { - if (tree_->GetId(ancestors[source_index]) != - client_ancestors[client_index]->id) { - return lca; - } - lca = ancestors[source_index]; - source_index--; - client_index--; - } - return lca; -} - -template<typename AXSourceNode> -AXSourceNode AXTreeSerializer<AXSourceNode>::LeastCommonAncestor( - AXSourceNode node) { - // Walk up the tree until the source node's id also exists in the - // client tree, then call LeastCommonAncestor on those two nodes. - ClientTreeNode* client_node = ClientTreeNodeById(tree_->GetId(node)); - while (tree_->IsValid(node) && !client_node) { - node = tree_->GetParent(node); - if (tree_->IsValid(node)) - client_node = ClientTreeNodeById(tree_->GetId(node)); - } - return LeastCommonAncestor(node, client_node); -} - -template<typename AXSourceNode> -bool AXTreeSerializer<AXSourceNode>::AnyDescendantWasReparented( - AXSourceNode node, AXSourceNode* out_lca) { - bool result = false; - int id = tree_->GetId(node); - std::vector<AXSourceNode> children; - tree_->GetChildren(node, &children); - for (size_t i = 0; i < children.size(); ++i) { - AXSourceNode& child = children[i]; - int child_id = tree_->GetId(child); - ClientTreeNode* client_child = ClientTreeNodeById(child_id); - if (client_child) { - if (!client_child->parent) { - // If the client child has no parent, it must have been the - // previous root node, so there is no LCA and we can exit early. - *out_lca = tree_->GetNull(); - return true; - } else if (client_child->parent->id != id) { - // If the client child's parent is not this node, update the LCA - // and return true (reparenting was found). - *out_lca = LeastCommonAncestor(*out_lca, client_child); - result = true; - } else { - // This child is already in the client tree, we won't - // recursively serialize it so we don't need to check this - // subtree recursively for reparenting. - continue; - } - } - - // This is a new child or reparented child, check it recursively. - if (AnyDescendantWasReparented(child, out_lca)) - result = true; - } - return result; -} - -template<typename AXSourceNode> -ClientTreeNode* AXTreeSerializer<AXSourceNode>::ClientTreeNodeById(int32 id) { - base::hash_map<int32, ClientTreeNode*>::iterator iter = - client_id_map_.find(id); - if (iter != client_id_map_.end()) - return iter->second; - else - return NULL; -} - -template<typename AXSourceNode> -void AXTreeSerializer<AXSourceNode>::SerializeChanges( - AXSourceNode node, - AXTreeUpdate* out_update) { - // If the node isn't in the client tree, we need to serialize starting - // with the LCA. - AXSourceNode lca = LeastCommonAncestor(node); - - if (client_root_) { - bool need_delete = false; - if (tree_->IsValid(lca)) { - // Check for any reparenting within this subtree - if there is - // any, we need to delete and reserialize the whole subtree - // that contains the old and new parents of the reparented node. - if (AnyDescendantWasReparented(lca, &lca)) - need_delete = true; - } - - if (!tree_->IsValid(lca)) { - // If there's no LCA, just tell the client to destroy the whole - // tree and then we'll serialize everything from the new root. - out_update->node_id_to_clear = client_root_->id; - Reset(); - } else if (need_delete) { - // Otherwise, if we need to reserialize a subtree, first we need - // to delete those nodes in our client tree so that - // SerializeChangedNodes() will be sure to send them again. - out_update->node_id_to_clear = tree_->GetId(lca); - ClientTreeNode* client_lca = ClientTreeNodeById(tree_->GetId(lca)); - CHECK(client_lca); - for (size_t i = 0; i < client_lca->children.size(); ++i) { - client_id_map_.erase(client_lca->children[i]->id); - DeleteClientSubtree(client_lca->children[i]); - delete client_lca->children[i]; - } - client_lca->children.clear(); - } - } - - // Serialize from the LCA, or from the root if there isn't one. - if (!tree_->IsValid(lca)) - lca = tree_->GetRoot(); - SerializeChangedNodes(lca, out_update); -} - -template<typename AXSourceNode> -void AXTreeSerializer<AXSourceNode>::DeleteClientSubtree(AXSourceNode node) { - ClientTreeNode* client_node = ClientTreeNodeById(tree_->GetId(node)); - if (client_node) - DeleteClientSubtree(client_node); -} - -template<typename AXSourceNode> -void AXTreeSerializer<AXSourceNode>::DeleteClientSubtree( - ClientTreeNode* client_node) { - for (size_t i = 0; i < client_node->children.size(); ++i) { - client_id_map_.erase(client_node->children[i]->id); - DeleteClientSubtree(client_node->children[i]); - delete client_node->children[i]; - } - client_node->children.clear(); -} - -template<typename AXSourceNode> -void AXTreeSerializer<AXSourceNode>::SerializeChangedNodes( - AXSourceNode node, - AXTreeUpdate* out_update) { - // This method has three responsibilities: - // 1. Serialize |node| into an AXNodeData, and append it to - // the AXTreeUpdate to be sent to the client. - // 2. Determine if |node| has any new children that the client doesn't - // know about yet, and call SerializeChangedNodes recursively on those. - // 3. Update our internal data structure that keeps track of what nodes - // the client knows about. - - // First, find the ClientTreeNode for this id in our data structure where - // we keep track of what accessibility objects the client already knows - // about. If we don't find it, then this must be the new root of the - // accessibility tree. - int id = tree_->GetId(node); - ClientTreeNode* client_node = ClientTreeNodeById(id); - if (!client_node) { - Reset(); - client_root_ = new ClientTreeNode(); - client_node = client_root_; - client_node->id = id; - client_node->parent = NULL; - client_id_map_[client_node->id] = client_node; - } - - // Iterate over the ids of the children of |node|. - // Create a set of the child ids so we can quickly look - // up which children are new and which ones were there before. - base::hash_set<int32> new_child_ids; - std::vector<AXSourceNode> children; - tree_->GetChildren(node, &children); - for (size_t i = 0; i < children.size(); ++i) { - AXSourceNode& child = children[i]; - int new_child_id = tree_->GetId(child); - new_child_ids.insert(new_child_id); - - // This is a sanity check - there shouldn't be any reparenting - // because we've already handled it above. - ClientTreeNode* client_child = client_id_map_[new_child_id]; - CHECK(!client_child || client_child->parent == client_node); - } - - // Go through the old children and delete subtrees for child - // ids that are no longer present, and create a map from - // id to ClientTreeNode for the rest. It's important to delete - // first in a separate pass so that nodes that are reparented - // don't end up children of two different parents in the middle - // of an update, which can lead to a double-free. - base::hash_map<int32, ClientTreeNode*> client_child_id_map; - std::vector<ClientTreeNode*> old_children; - old_children.swap(client_node->children); - for (size_t i = 0; i < old_children.size(); ++i) { - ClientTreeNode* old_child = old_children[i]; - int old_child_id = old_child->id; - if (new_child_ids.find(old_child_id) == new_child_ids.end()) { - client_id_map_.erase(old_child_id); - DeleteClientSubtree(old_child); - delete old_child; - } else { - client_child_id_map[old_child_id] = old_child; - } - } - - // Serialize this node. This fills in all of the fields in - // AXNodeData except child_ids, which we handle below. - out_update->nodes.push_back(AXNodeData()); - AXNodeData* serialized_node = &out_update->nodes.back(); - tree_->SerializeNode(node, serialized_node); - // TODO(dmazzoni/dtseng): Make the serializer not depend on roles to identify - // the root. - if (serialized_node->id == client_root_->id && - (serialized_node->role != AX_ROLE_ROOT_WEB_AREA && - serialized_node->role != AX_ROLE_DESKTOP)) { - serialized_node->role = AX_ROLE_ROOT_WEB_AREA; - } - serialized_node->child_ids.clear(); - - // Iterate over the children, make note of the ones that are new - // and need to be serialized, and update the ClientTreeNode - // data structure to reflect the new tree. - std::vector<AXSourceNode> children_to_serialize; - client_node->children.reserve(children.size()); - for (size_t i = 0; i < children.size(); ++i) { - AXSourceNode& child = children[i]; - int child_id = tree_->GetId(child); - - // No need to do anything more with children that aren't new; - // the client will reuse its existing object. - if (new_child_ids.find(child_id) == new_child_ids.end()) - continue; - - new_child_ids.erase(child_id); - serialized_node->child_ids.push_back(child_id); - if (client_child_id_map.find(child_id) != client_child_id_map.end()) { - ClientTreeNode* reused_child = client_child_id_map[child_id]; - client_node->children.push_back(reused_child); - } else { - ClientTreeNode* new_child = new ClientTreeNode(); - new_child->id = child_id; - new_child->parent = client_node; - client_node->children.push_back(new_child); - client_id_map_[child_id] = new_child; - children_to_serialize.push_back(child); - } - } - - // Serialize all of the new children, recursively. - for (size_t i = 0; i < children_to_serialize.size(); ++i) - SerializeChangedNodes(children_to_serialize[i], out_update); -} - -} // namespace ui - -#endif // UI_ACCESSIBILITY_AX_TREE_SERIALIZER_H_
diff --git a/ui/accessibility/ax_tree_serializer_unittest.cc b/ui/accessibility/ax_tree_serializer_unittest.cc deleted file mode 100644 index a0c0fb7..0000000 --- a/ui/accessibility/ax_tree_serializer_unittest.cc +++ /dev/null
@@ -1,182 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/memory/scoped_ptr.h" -#include "base/strings/string_number_conversions.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/accessibility/ax_node.h" -#include "ui/accessibility/ax_serializable_tree.h" -#include "ui/accessibility/ax_tree.h" -#include "ui/accessibility/ax_tree_serializer.h" - -namespace ui { - -// The framework for these tests is that each test sets up |treedata0_| -// and |treedata1_| and then calls GetTreeSerializer, which creates a -// serializer for a tree that's initially in state |treedata0_|, but then -// changes to state |treedata1_|. This allows each test to check the -// updates created by AXTreeSerializer or unit-test its private -// member functions. -class AXTreeSerializerTest : public testing::Test { - public: - AXTreeSerializerTest() {} - virtual ~AXTreeSerializerTest() {} - - protected: - void CreateTreeSerializer(); - - AXTreeUpdate treedata0_; - AXTreeUpdate treedata1_; - scoped_ptr<AXSerializableTree> tree0_; - scoped_ptr<AXSerializableTree> tree1_; - scoped_ptr<AXTreeSource<const AXNode*> > tree0_source_; - scoped_ptr<AXTreeSource<const AXNode*> > tree1_source_; - scoped_ptr<AXTreeSerializer<const AXNode*> > serializer_; - - private: - DISALLOW_COPY_AND_ASSIGN(AXTreeSerializerTest); -}; - -void AXTreeSerializerTest::CreateTreeSerializer() { - if (serializer_) - return; - - tree0_.reset(new AXSerializableTree(treedata0_)); - tree1_.reset(new AXSerializableTree(treedata1_)); - - // Serialize tree0 so that AXTreeSerializer thinks that its client - // is totally in sync. - tree0_source_.reset(tree0_->CreateTreeSource()); - serializer_.reset(new AXTreeSerializer<const AXNode*>(tree0_source_.get())); - AXTreeUpdate unused_update; - serializer_->SerializeChanges(tree0_->GetRoot(), &unused_update); - - // Pretend that tree0_ turned into tree1_. The next call to - // AXTreeSerializer will force it to consider these changes to - // the tree and send them as part of the next update. - tree1_source_.reset(tree1_->CreateTreeSource()); - serializer_->ChangeTreeSourceForTesting(tree1_source_.get()); -} - -// In this test, one child is added to the root. Only the root and -// new child should be added. -TEST_F(AXTreeSerializerTest, UpdateContainsOnlyChangedNodes) { - // (1 (2 3)) - treedata0_.nodes.resize(3); - treedata0_.nodes[0].id = 1; - treedata0_.nodes[0].role = AX_ROLE_ROOT_WEB_AREA; - treedata0_.nodes[0].child_ids.push_back(2); - treedata0_.nodes[0].child_ids.push_back(3); - treedata0_.nodes[1].id = 2; - treedata0_.nodes[2].id = 3; - - // (1 (4 2 3)) - treedata1_.nodes.resize(4); - treedata1_.nodes[0].id = 1; - treedata1_.nodes[0].role = AX_ROLE_ROOT_WEB_AREA; - treedata1_.nodes[0].child_ids.push_back(4); - treedata1_.nodes[0].child_ids.push_back(2); - treedata1_.nodes[0].child_ids.push_back(3); - treedata1_.nodes[1].id = 2; - treedata1_.nodes[2].id = 3; - treedata1_.nodes[3].id = 4; - - CreateTreeSerializer(); - AXTreeUpdate update; - serializer_->SerializeChanges(tree1_->GetFromId(1), &update); - - // The update should only touch nodes 1 and 4 - nodes 2 and 3 are unchanged - // and shouldn't be affected. - EXPECT_EQ(0, update.node_id_to_clear); - ASSERT_EQ(static_cast<size_t>(2), update.nodes.size()); - EXPECT_EQ(1, update.nodes[0].id); - EXPECT_EQ(4, update.nodes[1].id); -} - -// When the root changes, the whole tree is updated, even if some of it -// is unaffected. -TEST_F(AXTreeSerializerTest, NewRootUpdatesEntireTree) { - // (1 (2 (3 (4)))) - treedata0_.nodes.resize(4); - treedata0_.nodes[0].id = 1; - treedata0_.nodes[0].role = AX_ROLE_ROOT_WEB_AREA; - treedata0_.nodes[0].child_ids.push_back(2); - treedata0_.nodes[1].id = 2; - treedata0_.nodes[1].child_ids.push_back(3); - treedata0_.nodes[2].id = 3; - treedata0_.nodes[2].child_ids.push_back(4); - treedata0_.nodes[3].id = 4; - - // (5 (2 (3 (4)))) - treedata1_.nodes.resize(4); - treedata1_.nodes[0].id = 5; - treedata1_.nodes[0].role = AX_ROLE_ROOT_WEB_AREA; - treedata1_.nodes[0].child_ids.push_back(2); - treedata1_.nodes[1].id = 2; - treedata1_.nodes[1].child_ids.push_back(3); - treedata1_.nodes[2].id = 3; - treedata1_.nodes[2].child_ids.push_back(4); - treedata1_.nodes[3].id = 4; - - CreateTreeSerializer(); - AXTreeUpdate update; - serializer_->SerializeChanges(tree1_->GetFromId(4), &update); - - // The update should delete the subtree rooted at node id=1, and - // then include all four nodes in the update, even though the - // subtree rooted at id=2 didn't actually change. - EXPECT_EQ(1, update.node_id_to_clear); - ASSERT_EQ(static_cast<size_t>(4), update.nodes.size()); - EXPECT_EQ(5, update.nodes[0].id); - EXPECT_EQ(2, update.nodes[1].id); - EXPECT_EQ(3, update.nodes[2].id); - EXPECT_EQ(4, update.nodes[3].id); -} - -// When a node is reparented, the subtree including both the old parent -// and new parent of the reparented node must be deleted and recreated. -TEST_F(AXTreeSerializerTest, ReparentingUpdatesSubtree) { - // (1 (2 (3 (4) 5))) - treedata0_.nodes.resize(5); - treedata0_.nodes[0].id = 1; - treedata0_.nodes[0].role = AX_ROLE_ROOT_WEB_AREA; - treedata0_.nodes[0].child_ids.push_back(2); - treedata0_.nodes[1].id = 2; - treedata0_.nodes[1].child_ids.push_back(3); - treedata0_.nodes[1].child_ids.push_back(5); - treedata0_.nodes[2].id = 3; - treedata0_.nodes[2].child_ids.push_back(4); - treedata0_.nodes[3].id = 4; - treedata0_.nodes[4].id = 5; - - // Node 5 has been reparented from being a child of node 2, - // to a child of node 4. - // (1 (2 (3 (4 (5))))) - treedata1_.nodes.resize(5); - treedata1_.nodes[0].id = 1; - treedata1_.nodes[0].role = AX_ROLE_ROOT_WEB_AREA; - treedata1_.nodes[0].child_ids.push_back(2); - treedata1_.nodes[1].id = 2; - treedata1_.nodes[1].child_ids.push_back(3); - treedata1_.nodes[2].id = 3; - treedata1_.nodes[2].child_ids.push_back(4); - treedata1_.nodes[3].id = 4; - treedata1_.nodes[3].child_ids.push_back(5); - treedata1_.nodes[4].id = 5; - - CreateTreeSerializer(); - AXTreeUpdate update; - serializer_->SerializeChanges(tree1_->GetFromId(4), &update); - - // The update should delete the subtree rooted at node id=2, and - // then include nodes 2...5. - EXPECT_EQ(2, update.node_id_to_clear); - ASSERT_EQ(static_cast<size_t>(4), update.nodes.size()); - EXPECT_EQ(2, update.nodes[0].id); - EXPECT_EQ(3, update.nodes[1].id); - EXPECT_EQ(4, update.nodes[2].id); - EXPECT_EQ(5, update.nodes[3].id); -} - -} // namespace ui
diff --git a/ui/accessibility/ax_tree_source.h b/ui/accessibility/ax_tree_source.h deleted file mode 100644 index 1f13d8f..0000000 --- a/ui/accessibility/ax_tree_source.h +++ /dev/null
@@ -1,64 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_ACCESSIBILITY_AX_TREE_SOURCE_H_ -#define UI_ACCESSIBILITY_AX_TREE_SOURCE_H_ - -#include <vector> - -#include "ui/accessibility/ax_node_data.h" - -namespace ui { - -// An AXTreeSource is an abstract interface for a serializable -// accessibility tree. The tree may be in some other format or -// may be computed dynamically, but maintains the properties that -// it's a strict tree, it has a unique id for each node, and all -// of the accessibility information about a node can be serialized -// as an AXNodeData. This is the primary interface to use when -// an accessibility tree will be sent over an IPC before being -// consumed. -template<typename AXNodeSource> -class AXTreeSource { - public: - virtual ~AXTreeSource() {} - - // Get the root of the tree. - virtual AXNodeSource GetRoot() const = 0; - - // Get a node by its id. If no node by that id exists in the tree, return a - // null node, i.e. one that will return false if you call IsValid on it. - virtual AXNodeSource GetFromId(int32 id) const = 0; - - // Return the id of a node. All ids must be positive integers. - virtual int32 GetId(AXNodeSource node) const = 0; - - // Append all children of |node| to |out_children|. - virtual void GetChildren(AXNodeSource node, - std::vector<AXNodeSource>* out_children) const = 0; - - // Get the parent of |node|. - virtual AXNodeSource GetParent(AXNodeSource node) const = 0; - - // Returns true if |node| is valid, and false if it's a null pointer or a - // node object representing the null pointer. - virtual bool IsValid(AXNodeSource node) const = 0; - - // Returns true if two nodes are equal. - virtual bool IsEqual(AXNodeSource node1, - AXNodeSource node2) const = 0; - - // Return a AXNodeSource representing null. - virtual AXNodeSource GetNull() const = 0; - - // Serialize one node in the tree. - virtual void SerializeNode(AXNodeSource node, AXNodeData* out_data) const = 0; - - protected: - AXTreeSource() {} -}; - -} // namespace ui - -#endif // UI_ACCESSIBILITY_AX_TREE_SOURCE_H_
diff --git a/ui/accessibility/ax_tree_unittest.cc b/ui/accessibility/ax_tree_unittest.cc deleted file mode 100644 index 6c5d885..0000000 --- a/ui/accessibility/ax_tree_unittest.cc +++ /dev/null
@@ -1,298 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/memory/scoped_ptr.h" -#include "base/strings/string_number_conversions.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/accessibility/ax_node.h" -#include "ui/accessibility/ax_serializable_tree.h" -#include "ui/accessibility/ax_tree.h" -#include "ui/accessibility/ax_tree_serializer.h" - -namespace ui { - -namespace { - -class FakeAXTreeDelegate : public AXTreeDelegate { - public: - void OnNodeWillBeDeleted(AXNode* node) override { - deleted_ids_.push_back(node->id()); - } - - void OnNodeCreated(AXNode* node) override { - created_ids_.push_back(node->id()); - } - - void OnNodeChanged(AXNode* node) override { - changed_ids_.push_back(node->id()); - } - - void OnNodeCreationFinished(AXNode* node) override { - creation_finished_ids_.push_back(node->id()); - } - - void OnNodeChangeFinished(AXNode* node) override { - change_finished_ids_.push_back(node->id()); - } - - void OnRootChanged(AXNode* new_root) override { - new_root_ids_.push_back(new_root->id()); - } - - const std::vector<int32>& deleted_ids() { return deleted_ids_; } - const std::vector<int32>& created_ids() { return created_ids_; } - const std::vector<int32>& creation_finished_ids() { - return creation_finished_ids_; - } - const std::vector<int32>& new_root_ids() { return new_root_ids_; } - - private: - std::vector<int32> deleted_ids_; - std::vector<int32> created_ids_; - std::vector<int32> creation_finished_ids_; - std::vector<int32> changed_ids_; - std::vector<int32> change_finished_ids_; - std::vector<int32> new_root_ids_; -}; - -} // namespace - -TEST(AXTreeTest, SerializeSimpleAXTree) { - AXNodeData root; - root.id = 1; - root.role = AX_ROLE_ROOT_WEB_AREA; - root.state = (1 << AX_STATE_FOCUSABLE) | (1 << AX_STATE_FOCUSED); - root.location = gfx::Rect(0, 0, 800, 600); - root.child_ids.push_back(2); - root.child_ids.push_back(3); - - AXNodeData button; - button.id = 2; - button.role = AX_ROLE_BUTTON; - button.state = 0; - button.location = gfx::Rect(20, 20, 200, 30); - - AXNodeData checkbox; - checkbox.id = 3; - checkbox.role = AX_ROLE_CHECK_BOX; - checkbox.state = 0; - checkbox.location = gfx::Rect(20, 50, 200, 30); - - AXTreeUpdate initial_state; - initial_state.nodes.push_back(root); - initial_state.nodes.push_back(button); - initial_state.nodes.push_back(checkbox); - AXSerializableTree src_tree(initial_state); - - scoped_ptr<AXTreeSource<const AXNode*> > tree_source( - src_tree.CreateTreeSource()); - AXTreeSerializer<const AXNode*> serializer(tree_source.get()); - AXTreeUpdate update; - serializer.SerializeChanges(src_tree.GetRoot(), &update); - - AXTree dst_tree; - ASSERT_TRUE(dst_tree.Unserialize(update)); - - const AXNode* root_node = dst_tree.GetRoot(); - ASSERT_TRUE(root_node != NULL); - EXPECT_EQ(root.id, root_node->id()); - EXPECT_EQ(root.role, root_node->data().role); - - ASSERT_EQ(2, root_node->child_count()); - - const AXNode* button_node = root_node->ChildAtIndex(0); - EXPECT_EQ(button.id, button_node->id()); - EXPECT_EQ(button.role, button_node->data().role); - - const AXNode* checkbox_node = root_node->ChildAtIndex(1); - EXPECT_EQ(checkbox.id, checkbox_node->id()); - EXPECT_EQ(checkbox.role, checkbox_node->data().role); - - EXPECT_EQ( - "id=1 rootWebArea FOCUSABLE FOCUSED (0, 0)-(800, 600) child_ids=2,3\n" - " id=2 button (20, 20)-(200, 30)\n" - " id=3 checkBox (20, 50)-(200, 30)\n", - dst_tree.ToString()); -} - -TEST(AXTreeTest, SerializeAXTreeUpdate) { - AXNodeData list; - list.id = 3; - list.role = AX_ROLE_LIST; - list.state = 0; - list.child_ids.push_back(4); - list.child_ids.push_back(5); - list.child_ids.push_back(6); - - AXNodeData list_item_2; - list_item_2.id = 5; - list_item_2.role = AX_ROLE_LIST_ITEM; - list_item_2.state = 0; - - AXNodeData list_item_3; - list_item_3.id = 6; - list_item_3.role = AX_ROLE_LIST_ITEM; - list_item_3.state = 0; - - AXNodeData button; - button.id = 7; - button.role = AX_ROLE_BUTTON; - button.state = 0; - - AXTreeUpdate update; - update.nodes.push_back(list); - update.nodes.push_back(list_item_2); - update.nodes.push_back(list_item_3); - update.nodes.push_back(button); - - EXPECT_EQ( - "id=3 list (0, 0)-(0, 0) child_ids=4,5,6\n" - " id=5 listItem (0, 0)-(0, 0)\n" - " id=6 listItem (0, 0)-(0, 0)\n" - "id=7 button (0, 0)-(0, 0)\n", - update.ToString()); -} - -TEST(AXTreeTest, DeleteUnknownSubtreeFails) { - AXNodeData root; - root.id = 1; - root.role = AX_ROLE_ROOT_WEB_AREA; - - AXTreeUpdate initial_state; - initial_state.nodes.push_back(root); - AXTree tree(initial_state); - - // This should fail because we're asking it to delete - // a subtree rooted at id=2, which doesn't exist. - AXTreeUpdate update; - update.node_id_to_clear = 2; - update.nodes.resize(1); - update.nodes[0].id = 1; - update.nodes[0].id = AX_ROLE_ROOT_WEB_AREA; - EXPECT_FALSE(tree.Unserialize(update)); - ASSERT_EQ("Bad node_id_to_clear: 2", tree.error()); -} - -TEST(AXTreeTest, LeaveOrphanedDeletedSubtreeFails) { - AXTreeUpdate initial_state; - initial_state.nodes.resize(3); - initial_state.nodes[0].id = 1; - initial_state.nodes[0].role = AX_ROLE_ROOT_WEB_AREA; - initial_state.nodes[0].child_ids.push_back(2); - initial_state.nodes[0].child_ids.push_back(3); - initial_state.nodes[1].id = 2; - initial_state.nodes[2].id = 3; - AXTree tree(initial_state); - - // This should fail because we delete a subtree rooted at id=2 - // but never update it. - AXTreeUpdate update; - update.node_id_to_clear = 2; - update.nodes.resize(1); - update.nodes[0].id = 3; - EXPECT_FALSE(tree.Unserialize(update)); - ASSERT_EQ("Nodes left pending by the update: 2", tree.error()); -} - -TEST(AXTreeTest, LeaveOrphanedNewChildFails) { - AXTreeUpdate initial_state; - initial_state.nodes.resize(1); - initial_state.nodes[0].id = 1; - initial_state.nodes[0].role = AX_ROLE_ROOT_WEB_AREA; - AXTree tree(initial_state); - - // This should fail because we add a new child to the root node - // but never update it. - AXTreeUpdate update; - update.nodes.resize(1); - update.nodes[0].id = 1; - update.nodes[0].role = AX_ROLE_ROOT_WEB_AREA; - update.nodes[0].child_ids.push_back(2); - EXPECT_FALSE(tree.Unserialize(update)); - ASSERT_EQ("Nodes left pending by the update: 2", tree.error()); -} - -TEST(AXTreeTest, DuplicateChildIdFails) { - AXTreeUpdate initial_state; - initial_state.nodes.resize(1); - initial_state.nodes[0].id = 1; - initial_state.nodes[0].role = AX_ROLE_ROOT_WEB_AREA; - AXTree tree(initial_state); - - // This should fail because a child id appears twice. - AXTreeUpdate update; - update.nodes.resize(2); - update.nodes[0].id = 1; - update.nodes[0].role = AX_ROLE_ROOT_WEB_AREA; - update.nodes[0].child_ids.push_back(2); - update.nodes[0].child_ids.push_back(2); - update.nodes[1].id = 2; - EXPECT_FALSE(tree.Unserialize(update)); - ASSERT_EQ("Node 1 has duplicate child id 2", tree.error()); -} - -TEST(AXTreeTest, InvalidReparentingFails) { - AXTreeUpdate initial_state; - initial_state.nodes.resize(3); - initial_state.nodes[0].id = 1; - initial_state.nodes[0].role = AX_ROLE_ROOT_WEB_AREA; - initial_state.nodes[0].child_ids.push_back(2); - initial_state.nodes[1].id = 2; - initial_state.nodes[1].child_ids.push_back(3); - initial_state.nodes[2].id = 3; - - AXTree tree(initial_state); - - // This should fail because node 3 is reparented from node 2 to node 1 - // without deleting node 1's subtree first. - AXTreeUpdate update; - update.nodes.resize(3); - update.nodes[0].id = 1; - update.nodes[0].role = AX_ROLE_ROOT_WEB_AREA; - update.nodes[0].child_ids.push_back(3); - update.nodes[0].child_ids.push_back(2); - update.nodes[1].id = 2; - update.nodes[2].id = 3; - EXPECT_FALSE(tree.Unserialize(update)); - ASSERT_EQ("Node 3 reparented from 2 to 1", tree.error()); -} - -TEST(AXTreeTest, TreeDelegateIsCalled) { - AXTreeUpdate initial_state; - initial_state.nodes.resize(1); - initial_state.nodes[0].id = 1; - initial_state.nodes[0].role = AX_ROLE_ROOT_WEB_AREA; - - AXTree tree(initial_state); - AXTreeUpdate update; - update.node_id_to_clear = 1; - update.nodes.resize(2); - update.nodes[0].id = 2; - update.nodes[0].role = AX_ROLE_ROOT_WEB_AREA; - update.nodes[0].child_ids.push_back(3); - update.nodes[1].id = 3; - - FakeAXTreeDelegate fake_delegate; - tree.SetDelegate(&fake_delegate); - - EXPECT_TRUE(tree.Unserialize(update)); - - ASSERT_EQ(1U, fake_delegate.deleted_ids().size()); - EXPECT_EQ(1, fake_delegate.deleted_ids()[0]); - - ASSERT_EQ(2U, fake_delegate.created_ids().size()); - EXPECT_EQ(2, fake_delegate.created_ids()[0]); - EXPECT_EQ(3, fake_delegate.created_ids()[1]); - - ASSERT_EQ(2U, fake_delegate.creation_finished_ids().size()); - EXPECT_EQ(2, fake_delegate.creation_finished_ids()[0]); - EXPECT_EQ(3, fake_delegate.creation_finished_ids()[1]); - - ASSERT_EQ(1U, fake_delegate.new_root_ids().size()); - EXPECT_EQ(2, fake_delegate.new_root_ids()[0]); - - tree.SetDelegate(NULL); -} - -} // namespace ui
diff --git a/ui/accessibility/ax_tree_update.cc b/ui/accessibility/ax_tree_update.cc deleted file mode 100644 index 8e9d019..0000000 --- a/ui/accessibility/ax_tree_update.cc +++ /dev/null
@@ -1,42 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/accessibility/ax_tree_update.h" - -#include "base/containers/hash_tables.h" -#include "base/strings/string_number_conversions.h" - -namespace ui { - -AXTreeUpdate::AXTreeUpdate() : node_id_to_clear(0) { -} - -AXTreeUpdate::~AXTreeUpdate() { -} - -std::string AXTreeUpdate::ToString() const { - std::string result; - if (node_id_to_clear != 0) { - result += "AXTreeUpdate: clear node " + - base::IntToString(node_id_to_clear) + "\n"; - } - - // The challenge here is that we want to indent the nodes being updated - // so that parent/child relationships are clear, but we don't have access - // to the rest of the tree for context, so we have to try to show the - // relative indentation of child nodes in this update relative to their - // parents. - base::hash_map<int32, int> id_to_indentation; - for (size_t i = 0; i < nodes.size(); ++i) { - int indent = id_to_indentation[nodes[i].id]; - result += std::string(2 * indent, ' '); - result += nodes[i].ToString() + "\n"; - for (size_t j = 0; j < nodes[i].child_ids.size(); ++j) - id_to_indentation[nodes[i].child_ids[j]] = indent + 1; - } - - return result; -} - -} // namespace ui
diff --git a/ui/accessibility/ax_tree_update.h b/ui/accessibility/ax_tree_update.h deleted file mode 100644 index 314a78f..0000000 --- a/ui/accessibility/ax_tree_update.h +++ /dev/null
@@ -1,61 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_ACCESSIBILITY_AX_TREE_UPDATE_H_ -#define UI_ACCESSIBILITY_AX_TREE_UPDATE_H_ - -#include <vector> - -#include "ui/accessibility/ax_node_data.h" - -namespace ui { - -// An AXTreeUpdate is a serialized representation of an atomic change -// to an AXTree. The sender and receiver must be in sync; the update -// is only meant to bring the tree from a specific previous state into -// its next state. Trying to apply it to the wrong tree should immediately -// die with a fatal assertion. -// -// An AXTreeUpdate consists of an optional node id to clear (meaning -// that all of that node's children and their descendants are deleted), -// followed by an ordered vector of AXNodeData structures to be applied -// to the tree in order. -// -// Suppose that the next AXNodeData to be applied is |node|. The following -// invariants must hold: -// 1. Either |node.id| is already in the tree, or else the tree is empty, -// |node| is the new root of the tree, and -// |node.role| == WebAXRoleRootWebArea. -// 2. Every child id in |node.child_ids| must either be already a child -// of this node, or a new id not previously in the tree. It is not -// allowed to "reparent" a child to this node without first removing -// that child from its previous parent. -// 3. When a new id appears in |node.child_ids|, the tree should create a -// new uninitialized placeholder node for it immediately. That -// placeholder must be updated within the same AXTreeUpdate, otherwise -// it's a fatal error. This guarantees the tree is always complete -// before or after an AXTreeUpdate. -struct AX_EXPORT AXTreeUpdate { - AXTreeUpdate(); - ~AXTreeUpdate(); - - // The id of a node to clear, before applying any updates, - // or 0 if no nodes should be cleared. Clearing a node means deleting - // all of its children and their descendants, but leaving that node in - // the tree. It's an error to clear a node but not subsequently update it - // as part of the tree update. - int node_id_to_clear; - - // A vector of nodes to update, according to the rules above. - std::vector<AXNodeData> nodes; - - // Return a multi-line indented string representation, for logging. - std::string ToString() const; - - // TODO(dmazzoni): location changes -}; - -} // namespace ui - -#endif // UI_ACCESSIBILITY_AX_TREE_UPDATE_H_
diff --git a/ui/accessibility/ax_view_state.cc b/ui/accessibility/ax_view_state.cc deleted file mode 100644 index 11044bc..0000000 --- a/ui/accessibility/ax_view_state.cc +++ /dev/null
@@ -1,27 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/accessibility/ax_view_state.h" - -namespace ui { - -AXViewState::AXViewState() - : role(AX_ROLE_CLIENT), - selection_start(-1), - selection_end(-1), - index(-1), - count(-1), - state_(0) { } - -AXViewState::~AXViewState() { } - -void AXViewState::AddStateFlag(ui::AXState state_flag) { - state_ |= (1 << state_flag); -} - -bool AXViewState::HasStateFlag(ui::AXState state_flag) const { - return 0 != (state_ & (1 << state_flag)); -} - -} // namespace ui
diff --git a/ui/accessibility/ax_view_state.h b/ui/accessibility/ax_view_state.h deleted file mode 100644 index 2f1aab0..0000000 --- a/ui/accessibility/ax_view_state.h +++ /dev/null
@@ -1,81 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_ACCESSIBILITY_AX_VIEW_STATE_H_ -#define UI_ACCESSIBILITY_AX_VIEW_STATE_H_ - -#include "base/basictypes.h" -#include "base/callback.h" -#include "base/strings/string16.h" -#include "ui/accessibility/ax_enums.h" -#include "ui/accessibility/ax_export.h" - -namespace ui { - -//////////////////////////////////////////////////////////////////////////////// -// -// AXViewState -// -// A cross-platform struct for storing the core accessibility information -// that should be provided about any UI view to assistive technology (AT). -// -//////////////////////////////////////////////////////////////////////////////// -struct AX_EXPORT AXViewState { - public: - AXViewState(); - ~AXViewState(); - - // Set or check bits in |state_|. - void AddStateFlag(ui::AXState state); - bool HasStateFlag(ui::AXState state) const; - - // The view's state, a bitmask containing fields such as checked - // (for a checkbox) and protected (for a password text box). This "state" - // should not be confused with the class's name. - uint32 state() { return state_; } - - // The view's role, like button or list box. - AXRole role; - - // The view's name / label. - base::string16 name; - - // The view's value, for example the text content. - base::string16 value; - - // The name of the default action if the user clicks on this view. - base::string16 default_action; - - // The keyboard shortcut to activate this view, if any. - base::string16 keyboard_shortcut; - - // The selection start and end. Only applies to views with text content, - // such as a text box or combo box; start and end should be -1 otherwise. - int selection_start; - int selection_end; - - // The selected item's index and the count of the number of items. - // Only applies to views with multiple choices like a listbox; both - // index and count should be -1 otherwise. - int index; - int count; - - // An optional callback that can be used by accessibility clients to - // set the string value of this view. This only applies to roles where - // setting the value makes sense, like a text box. Not often used by - // screen readers, but often used by automation software to script - // things like logging into portals or filling forms. - // - // This callback is only valid for the lifetime of the view, and should - // be a safe no-op if the view is deleted. Typically, accessible views - // should use a WeakPtr when binding the callback. - base::Callback<void(const base::string16&)> set_value_callback; - - private: - uint32 state_; -}; - -} // namespace ui - -#endif // UI_ACCESSIBILITY_AX_VIEW_STATE_H_
diff --git a/ui/accessibility/extensions/README.chromium b/ui/accessibility/extensions/README.chromium deleted file mode 100644 index 4fda434..0000000 --- a/ui/accessibility/extensions/README.chromium +++ /dev/null
@@ -1,3 +0,0 @@ -This directory contains accessibility extensions developed by the -Chrome team, not included with Chrome by default, but available via a -one-click install from the Settings page.
diff --git a/ui/accessibility/extensions/alt/background.js b/ui/accessibility/extensions/alt/background.js deleted file mode 100644 index a37bd83..0000000 --- a/ui/accessibility/extensions/alt/background.js +++ /dev/null
@@ -1,45 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -function injectScripts(opt_tab) { - chrome.tabs.executeScript({ - file: 'lib/axs_testing.js', - allFrames: true - }, function() { - console.log('successfully injected axs_testing.js'); - chrome.tabs.executeScript({ - file: 'hide-images.js', - allFrames: true - }, function() { - console.log('successfully injected script', opt_tab ? opt_tab.url : ''); - chrome.tabs.insertCSS({ - file: 'hide-images.css', - allFrames: true - }, function() { - console.log('successfully injected css', opt_tab ? opt_tab.url : ''); - chrome.tabs.executeScript({ - code: 'toggleEnabled();', - allFrames: true - }, function() { - console.log('created infobar'); - chrome.tabs.executeScript({ - code: 'createInfobar();' - }); - }); - }); - }); - }); -} - -chrome.commands.onCommand.addListener(function(command) { - console.log('command: ', command); - if (command == 'example_keyboard_command') { - injectScripts(); - } -}); - -chrome.browserAction.onClicked.addListener(function(tab) { - injectScripts(tab); -}); -
diff --git a/ui/accessibility/extensions/alt/hide-images.css b/ui/accessibility/extensions/alt/hide-images.css deleted file mode 100644 index a9d30e3..0000000 --- a/ui/accessibility/extensions/alt/hide-images.css +++ /dev/null
@@ -1,146 +0,0 @@ -/* Copyright (c) 2014 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. */ - -body[show-alt] img { - /* add some fake content to hang the ::before element off */ - content: "" !important; - background-image: url('data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7') - - /* display non-floated and remove any background color */ - float: none !important; - background-color: inherit !important; - - /* set height to contain the text content */ - height: 100% !important; -} - -body[show-alt] img:not([alt]):not([aria-hidden=true]):not([role=presentation]):before { - content: url('chrome-extension://__MSG_@@extension_id__/images/speech-missing-alt-16.png') " " attr(_repaired) !important; - box-shadow: inset 0 -4px 0 rgba(230, 124, 115, 1) !important; -} - -body[show-alt] img:not([aria-hidden=true]):not([role=presentation]):not([alt='']):before { - content: url('chrome-extension://__MSG_@@extension_id__/images/speech-16.png') " " attr(alt) !important; - box-shadow: inset 0 -4px 0 rgba(139, 195, 74, 1) !important; - display: table; - clear: both; -} - -@-webkit-keyframes slideDown { - from { - -webkit-transform: translateY(-150%); - } - to { - -webkit-transform: translateY(0px); - } -} - -@-webkit-keyframes slideUp { - from { - -webkit-transform: translateY(0%); - } - to { - -webkit-transform: translateY(-150%); - } -} - -body[show-alt] .show-alt-infobar { - -webkit-animation-name: slideDown; - -webkit-animation-duration: 0.5s; - -webkit-animation-delay: 0.5s; - -webkit-animation-iteration-count: 1; - -webkit-animation-timing-function: ease; - -webkit-animation-direction: forwards; - -webkit-transform: translateY(0%); -} - -body:not([show-alt]) .show-alt-infobar { - -webkit-animation-name: slideUp; - -webkit-animation-duration: 0.5s; - -webkit-animation-delay: 0.5s; - -webkit-animation-iteration-count: 1; - -webkit-animation-timing-function: ease; - -webkit-animation-direction: forwards; - -webkit-transform: translateY(-150%); -} - -.show-alt-infobar { - top: 0; - left: 0; - right: 0; - z-index: 100000001; /* :( */ - position: fixed !important; - background: #fde073 !important; - text-align: center !important; - line-height: 2.0; - overflow: hidden; - box-shadow: 0 0 5px black; - box-shadow: 0 0 5px black; - font-family: Arial, sans-serif !important; - font-size: 12pt !important; - -webkit-animation-fill-mode: backwards; -} - -.show-alt-infobar .content { - display: inline-block !important; -} - -.show-alt-infobar span { - margin: 5px; -} - -.show-alt-infobar button.link-button { - -webkit-appearance: none !important; - font: inherit !important; - background: inherit !important; - border: none !important; - color: #1155CC !important; - cursor: pointer !important; - display: inline !important; - margin: 0 !important; - padding: 0 !important; - text-decoration: none !important; - box-shadow: none !important; - text-transform: none !important; - padding: none !important; -} - -.show-alt-infobar button.link-button:hover, -.show-alt-infobar button.link-button:focus { - color: #1155CC; - text-decoration: underline; - outline: none; -} - -.show-alt-infobar .controls { - float: right !important; - display: inline-block !important; - padding-right: 5px !important; -} - -.show-alt-infobar .close-button-gray:hover, -.show-alt-infobar .close-button-gray:focus { - background-position: -143px -96px !important; - outline: none; -} - -.show-alt-infobar .close-button-gray { - -webkit-appearance: none !important; - font: inherit !important; - background: inherit !important; - border: none !important; - cursor: pointer !important; - margin: 0 !important; - padding: 0 !important; - text-decoration: none !important; - box-shadow: none !important; - text-transform: none !important; - padding: none !important; - width: 13px !important; - height: 13px !important; - background-position: -175px -96px !important; - background-image: url('chrome-extension://__MSG_@@extension_id__/images/statusbarButtonGlyphs.png') !important; - background-size: 320px 144px !important; - display: inline-block !important; -}
diff --git a/ui/accessibility/extensions/alt/hide-images.js b/ui/accessibility/extensions/alt/hide-images.js deleted file mode 100644 index 2e9e374..0000000 --- a/ui/accessibility/extensions/alt/hide-images.js +++ /dev/null
@@ -1,107 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -function toggleEnabled(event) { - if (!document.body) - return; - if (document.body.hasAttribute('show-alt')) - document.body.removeAttribute('show-alt'); - else - document.body.setAttribute('show-alt', ''); -} - -function processImage(image) { - image.style.setProperty('min-height', image.height + 'px'); - image.style.setProperty('min-width', image.width + 'px'); - var style = window.getComputedStyle(image, null); - var contrastRatio = - axs.utils.getContrastRatioForElementWithComputedStyle(style, image); - if (contrastRatio != null && axs.utils.isLowContrast(contrastRatio, style)) { - var bgColor = axs.utils.getBgColor(style, image); - var fgColor = axs.utils.getFgColor(style, image, bgColor); - var suggestedColors = axs.utils.suggestColors( - bgColor, fgColor, contrastRatio, style); - var suggestedColorsAA = suggestedColors['AA']; - image.style.setProperty('color', suggestedColorsAA['fg']); - image.style.setProperty( - 'background-color', suggestedColorsAA['bg'], 'important'); - } - if (!image.hasAttribute('alt')) { - if (image.hasAttribute('_repaired')) - return; - var filename = image.src.split('/').pop(); - image.setAttribute('_repaired', filename); - } -} - -var observer = new MutationObserver(function(mutations) { - mutations.forEach(function(mutation) { - if (!mutation.addedNodes || mutation.addedNodes.length == 0) - return; - for (var i = 0; i < mutation.addedNodes.length; i++) { - var addedNode = mutation.addedNodes[i]; - if (!(addedNode instanceof - addedNode.ownerDocument.defaultView.HTMLImageElement)) { - continue; - } - processImage(addedNode); - } - }); -}); -observer.observe(document, { childList: true, subtree: true }); - -var images = document.querySelectorAll('img'); -for (var i = 0; i < images.length; i++) { - processImage(images[i]); -} - -if (!infobarDismissed) - var infobarDismissed = false; - -function createInfobar() { - if (infobarDismissed) - return; - - if (!document.body) - return; - - if (document.querySelector('.show-alt-infobar')) - return; - - var showAltInfobar = document.createElement('div'); - showAltInfobar.className = 'show-alt-infobar'; - - var showAltInfoControls = document.createElement('div'); - showAltInfoControls.className = 'controls'; - - var showAltInfoCloseButton = document.createElement('button'); - showAltInfoCloseButton.className = 'close-button-gray'; - showAltInfoCloseButton.addEventListener('click', function() { - document.body.removeChild(showAltInfobar); - infobarDismissed = true; - }); - - showAltInfoControls.appendChild(showAltInfoCloseButton); - showAltInfobar.appendChild(showAltInfoControls); - - var showAltInfoContent = document.createElement('div'); - showAltInfoContent.className = 'content'; - // TODO(aboxhall): i18n - var showAltInfoText = document.createElement('span'); - showAltInfoText.textContent = 'Images have been replaced by their alt text.'; - showAltInfoText.setAttribute('role', 'status'); - showAltInfoContent.appendChild(showAltInfoText); - - var undoButton = document.createElement('button'); - undoButton.className = 'link-button'; - undoButton.textContent = 'Undo'; - undoButton.addEventListener('click', toggleEnabled); - - var closeButton = document.createElement('button'); - - showAltInfoContent.appendChild(undoButton); - showAltInfobar.appendChild(showAltInfoContent); - - document.body.insertBefore(showAltInfobar, document.body.firstChild); -}
diff --git a/ui/accessibility/extensions/alt/images/icon-19.png b/ui/accessibility/extensions/alt/images/icon-19.png deleted file mode 100644 index 055dee3..0000000 --- a/ui/accessibility/extensions/alt/images/icon-19.png +++ /dev/null Binary files differ
diff --git a/ui/accessibility/extensions/alt/images/icon-38.png b/ui/accessibility/extensions/alt/images/icon-38.png deleted file mode 100644 index e4fb436..0000000 --- a/ui/accessibility/extensions/alt/images/icon-38.png +++ /dev/null Binary files differ
diff --git a/ui/accessibility/extensions/alt/images/speech-16.png b/ui/accessibility/extensions/alt/images/speech-16.png deleted file mode 100644 index 5de84ab..0000000 --- a/ui/accessibility/extensions/alt/images/speech-16.png +++ /dev/null Binary files differ
diff --git a/ui/accessibility/extensions/alt/images/speech-missing-alt-16.png b/ui/accessibility/extensions/alt/images/speech-missing-alt-16.png deleted file mode 100644 index c80e5ba..0000000 --- a/ui/accessibility/extensions/alt/images/speech-missing-alt-16.png +++ /dev/null Binary files differ
diff --git a/ui/accessibility/extensions/alt/images/statusbarButtonGlyphs.png b/ui/accessibility/extensions/alt/images/statusbarButtonGlyphs.png deleted file mode 100644 index 5472776..0000000 --- a/ui/accessibility/extensions/alt/images/statusbarButtonGlyphs.png +++ /dev/null Binary files differ
diff --git a/ui/accessibility/extensions/alt/manifest.json b/ui/accessibility/extensions/alt/manifest.json deleted file mode 100644 index 2581f43..0000000 --- a/ui/accessibility/extensions/alt/manifest.json +++ /dev/null
@@ -1,33 +0,0 @@ -{ - "name": "Replace images with alt text", - "version": "0.1", - "description": "__MSG_appDesc__", - "background": { - "scripts": [ "background.js" ] - }, - "commands": { - "example_keyboard_command": { - "suggested_key": { - "default": "Ctrl+Shift+I", - "mac": "Ctrl+Shift+I" - }, - "description": "Replace all images with their alt text." - } - }, - "browser_action": { - "default_title": "Replace all images with their alt text.", - "default_icon": { - "19": "images/icon-19.png", - "38": "images/icon-38.png" - } - }, - "permissions": [ - "activeTab" - ], - "manifest_version": 2, - "web_accessible_resources": [ - "images/speech-16.png", - "images/speech-missing-alt-16.png", - "images/statusbarButtonGlyphs.png" - ] -}
diff --git a/ui/accessibility/extensions/caretbrowsing/_locales/en/messages.json b/ui/accessibility/extensions/caretbrowsing/_locales/en/messages.json deleted file mode 100644 index 76ec13a..0000000 --- a/ui/accessibility/extensions/caretbrowsing/_locales/en/messages.json +++ /dev/null
@@ -1,74 +0,0 @@ -{ - "appName": { - "message": "Caret Browsing", - "description": "The title of the application, displayed in the web store." - }, - "appDesc": { - "message": "Browse the text of web pages using arrow keys.", - "description":"The description of the application, displayed in the web store." - }, - "caretBrowsingOptions": { - "message": "Caret Browsing Options", - "description": "The title of the options page." - }, - "subheading1": { - "message": "This extension gives you a movable cursor in the web page, allowing you to select text with the keyboard.", - "description": "Text at the top of the options page explaining the extension." - }, - "subheading2": { - "message": "Try it out now - Caret Browsing is always enabled on this page!", - "description": "More text at the top of the options page, explaining that Caret Browsing (the name of this extension) is enabled on this page and the user can try it." - }, - "keyboardCommands": { - "message": "Keyboard Commands", - "description": "Title of the heading on the page that describes keyboard commands." - }, - "enableDisableNonCros": { - "message": "Press <span class='key'>F7</span> to turn on Caret Browsing. Press it again to turn it off.", - "description": "Instructions for how to enable or disable this feature on any platform other than Chrome OS." - }, - "enableDisableCros": { - "message": "Press <span class='key'>Alt</span> + <img src='increase_brightness.png'> (the Increase Brightness key, or F7) to turn on Caret Browsing. Press it again to turn it off.", - "description": "Instructions for how to enable or disable this feature on a Chromebook, where you have to hold Alt and press the special Increase Brightness key on the top of the keyboard, or F7 if you're using an alternate keyboard." - }, - "moveByWordsNonMac": { - "message": "Hold down <span class='key'>Control</span> to move by words.", - "description": "Text that describes how to move by words using the Control key. This string is used on all platforms other than Mac." - }, - "moveByWordsMac": { - "message": "Hold down <span class='key'>Option</span> to move by words.", - "description": "Text that describes how to move by words using the Option key on a Mac keyboard." - }, - "visualFeedback": { - "message": "Visual Feedback", - "description": "Heading text for the part of the options page that lets the user choose options for how the caret is shown visually." - }, - "whenEnabled": { - "message": "When Caret Browsing is enabled:", - "description": "Subheading in the options page where the user chooses what to show visually when this feature (Caret Browsing) is enabled." - }, - "animation": { - "message": "Highlight the cursor position with an animation.", - "description": "One of several possible options for what to do when the cursor first appears - this option is to show a quick animation." - }, - "flash": { - "message": "Highlight the cursor position with a quick flash.", - "description": "One of several possible options for what to do when the cursor first appears - this option is to flash something quickly." - }, - "noFeedback": { - "message": "No feedback, just show the cursor.", - "description": "One of several possible options for what to do when the cursor first appears - this option is to do nothing." - }, - "jump": { - "message": "When the caret jumps by a large distance:", - "description": "Subheading in the options page where the user chooses what to show visually when the cursor jumps from one part of the page to another part that's far away." - }, - "navHelp": { - "message": "<p>Use arrow keys to move throughout the document. </p><p>Click anywhere to move the cursor to that location. </p> <p> Press <span class='key'>Shift</span> + arrows to select text.</p>", - "description": "A description of how to use the caret browsing feature." - }, - "focusHelp": { - "message": "<p>When you reach a link or control, it is automatically focused. Press <span class='key'>Enter</span> to click a link or button. </p> <p> When a focused control (like a text box or a list box) is capturing arrow keys, press <span class='key'>Esc</span> followed by the left or right arrow to continue Caret Browsing. </p> <p> Alternatively, press <span class='key'>Tab</span> to move to the next focusable control. </p>", - "description": "A description of how to use the caret browsing feature to navigate between focusable controls like text fields." - } -}
diff --git a/ui/accessibility/extensions/caretbrowsing/background.js b/ui/accessibility/extensions/caretbrowsing/background.js deleted file mode 100644 index 18c722a..0000000 --- a/ui/accessibility/extensions/caretbrowsing/background.js +++ /dev/null
@@ -1,108 +0,0 @@ -// Copyright (c) 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -/** - * @fileoverview Script that runs on the background page. - */ - -CONTENT_SCRIPTS = [ - 'accessibility_utils.js', - 'traverse_util.js', - 'caret_browsing.js' -]; - -/** - * The class handling the Caret Browsing background page, which keeps - * track of the current state, handles the browser action button, and - * initializes the content script in all running tabs when the extension - * is first loaded. - * @constructor - */ -var CaretBkgnd = function() {}; - -/** - * Flag indicating whether caret browsing is enabled. Global, applies to - * all tabs simultaneously. - * @type {boolean} - */ -CaretBkgnd.isEnabled; - -/** - * Change the browser action icon and tooltip based on the enabled state. - */ -CaretBkgnd.setIcon = function() { - chrome.browserAction.setIcon( - {'path': CaretBkgnd.isEnabled ? - '../caret_19_on.png' : - '../caret_19.png'}); - chrome.browserAction.setTitle( - {'title': CaretBkgnd.isEnabled ? - 'Turn Off Caret Browsing (F7)' : - 'Turn On Caret Browsing (F7)' }); -}; - -/** - * This is called when the extension is first loaded, so that it can be - * immediately used in all already-open tabs. It's not needed for any - * new tabs that open after that, the content script will be automatically - * injected into any new tab. - */ -CaretBkgnd.injectContentScripts = function() { - chrome.windows.getAll({'populate': true}, function(windows) { - for (var i = 0; i < windows.length; i++) { - var tabs = windows[i].tabs; - for (var j = 0; j < tabs.length; j++) { - for (var k = 0; k < CONTENT_SCRIPTS.length; k++) { - chrome.tabs.executeScript( - tabs[j].id, - {file: CONTENT_SCRIPTS[k], allFrames: true}, - function(result) { - // Ignore. - chrome.runtime.lastError; - }); - } - } - } - }); -}; - -/** - * Toggle caret browsing on or off, and update the browser action icon and - * all open tabs. - */ -CaretBkgnd.toggle = function() { - CaretBkgnd.isEnabled = !CaretBkgnd.isEnabled; - var obj = {}; - obj['enabled'] = CaretBkgnd.isEnabled; - chrome.storage.sync.set(obj); - CaretBkgnd.setIcon(); -}; - -/** - * Initialize the background script. Set the initial value of the flag - * based on the saved preference in localStorage, update the browser action, - * inject into running tabs, and then set up communication with content - * scripts in tabs. Also check for prefs updates (from the options page) - * and send them to content scripts. - */ -CaretBkgnd.init = function() { - chrome.storage.sync.get('enabled', function(result) { - CaretBkgnd.isEnabled = result['enabled']; - CaretBkgnd.setIcon(); - CaretBkgnd.injectContentScripts(); - - chrome.browserAction.onClicked.addListener(function(tab) { - CaretBkgnd.toggle(); - }); - }); - - chrome.storage.onChanged.addListener(function() { - chrome.storage.sync.get('enabled', function(result) { - CaretBkgnd.isEnabled = result['enabled']; - CaretBkgnd.setIcon(); - }); - }); -}; - -CaretBkgnd.init();
diff --git a/ui/accessibility/extensions/caretbrowsing/caret_128.png b/ui/accessibility/extensions/caretbrowsing/caret_128.png deleted file mode 100644 index 29e309b..0000000 --- a/ui/accessibility/extensions/caretbrowsing/caret_128.png +++ /dev/null Binary files differ
diff --git a/ui/accessibility/extensions/caretbrowsing/caret_16.png b/ui/accessibility/extensions/caretbrowsing/caret_16.png deleted file mode 100644 index e6e59f0..0000000 --- a/ui/accessibility/extensions/caretbrowsing/caret_16.png +++ /dev/null Binary files differ
diff --git a/ui/accessibility/extensions/caretbrowsing/caret_19.png b/ui/accessibility/extensions/caretbrowsing/caret_19.png deleted file mode 100644 index e90bb5b..0000000 --- a/ui/accessibility/extensions/caretbrowsing/caret_19.png +++ /dev/null Binary files differ
diff --git a/ui/accessibility/extensions/caretbrowsing/caret_19_on.png b/ui/accessibility/extensions/caretbrowsing/caret_19_on.png deleted file mode 100644 index a2dd689..0000000 --- a/ui/accessibility/extensions/caretbrowsing/caret_19_on.png +++ /dev/null Binary files differ
diff --git a/ui/accessibility/extensions/caretbrowsing/caret_48.png b/ui/accessibility/extensions/caretbrowsing/caret_48.png deleted file mode 100644 index df4f1dd..0000000 --- a/ui/accessibility/extensions/caretbrowsing/caret_48.png +++ /dev/null Binary files differ
diff --git a/ui/accessibility/extensions/caretbrowsing/caretbrowsing.css b/ui/accessibility/extensions/caretbrowsing/caretbrowsing.css deleted file mode 100644 index 563d2e3..0000000 --- a/ui/accessibility/extensions/caretbrowsing/caretbrowsing.css +++ /dev/null
@@ -1,22 +0,0 @@ -/* Copyright (c) 2014 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. */ - -.CaretBrowsing_Caret { - position: absolute; - z-index: 2147483647; - min-height: 10px; - background-color: #000; -} - -.CaretBrowsing_AnimateCaret { - position: absolute; - z-index: 2147483647; - min-height: 10px; -} - -.CaretBrowsing_FlashVert { - position: fixed; - z-index: 2147483647; - background: linear-gradient(left, rgba(128, 128, 255, 0) 0%,rgba(128, 128, 255, 0.3) 45%,rgba(128, 128, 255, 0.8) 50%,rgba(128, 128, 255, 0.3) 65%,rgba(128, 128, 255, 0) 100%); -}
diff --git a/ui/accessibility/extensions/caretbrowsing/caretbrowsing.js b/ui/accessibility/extensions/caretbrowsing/caretbrowsing.js deleted file mode 100644 index 4e1e7bf..0000000 --- a/ui/accessibility/extensions/caretbrowsing/caretbrowsing.js +++ /dev/null
@@ -1,1424 +0,0 @@ -/* Copyright (c) 2014 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. */ - -/** - * @fileoverview Caret browsing content script, runs in each frame. - * - * The behavior is based on Mozilla's spec whenever possible: - * http://www.mozilla.org/access/keyboard/proposal - * - * The one exception is that Esc is used to escape out of a form control, - * rather than their proposed key (which doesn't seem to work in the - * latest Firefox anyway). - * - * Some details about how Chrome selection works, which will help in - * understanding the code: - * - * The Selection object (window.getSelection()) has four components that - * completely describe the state of the caret or selection: - * - * base and anchor: this is the start of the selection, the fixed point. - * extent and focus: this is the end of the selection, the part that - * moves when you hold down shift and press the left or right arrows. - * - * When the selection is a cursor, the base, anchor, extent, and focus are - * all the same. - * - * There's only one time when the base and anchor are not the same, or the - * extent and focus are not the same, and that's when the selection is in - * an ambiguous state - i.e. it's not clear which edge is the focus and which - * is the anchor. As an example, if you double-click to select a word, then - * the behavior is dependent on your next action. If you press Shift+Right, - * the right edge becomes the focus. But if you press Shift+Left, the left - * edge becomes the focus. - * - * When the selection is in an ambiguous state, the base and extent are set - * to the position where the mouse clicked, and the anchor and focus are set - * to the boundaries of the selection. - * - * The only way to set the selection and give it direction is to use - * the non-standard Selection.setBaseAndExtent method. If you try to use - * Selection.addRange(), the anchor will always be on the left and the focus - * will always be on the right, making it impossible to manipulate - * selections that move from right to left. - * - * Finally, Chrome will throw an exception if you try to set an invalid - * selection - a selection where the left and right edges are not the same, - * but it doesn't span any visible characters. A common example is that - * there are often many whitespace characters in the DOM that are not - * visible on the page; trying to select them will fail. Another example is - * any node that's invisible or not displayed. - * - * While there are probably many possible methods to determine what is - * selectable, this code uses the method of determining if there's a valid - * bounding box for the range or not - keep moving the cursor forwards until - * the range from the previous position and candidate next position has a - * valid bounding box. - */ - -/** - * Return whether a node is focusable. This includes nodes whose tabindex - * attribute is set to "-1" explicitly - these nodes are not in the tab - * order, but they should still be focused if the user navigates to them - * using linear or smart DOM navigation. - * - * Note that when the tabIndex property of an Element is -1, that doesn't - * tell us whether the tabIndex attribute is missing or set to "-1" explicitly, - * so we have to check the attribute. - * - * @param {Object} targetNode The node to check if it's focusable. - * @return {boolean} True if the node is focusable. - */ -function isFocusable(targetNode) { - if (!targetNode || typeof(targetNode.tabIndex) != 'number') { - return false; - } - - if (targetNode.tabIndex >= 0) { - return true; - } - - if (targetNode.hasAttribute && - targetNode.hasAttribute('tabindex') && - targetNode.getAttribute('tabindex') == '-1') { - return true; - } - - return false; -} - -/** - * Determines whether or not a node is or is the descendant of another node. - * - * @param {Object} node The node to be checked. - * @param {Object} ancestor The node to see if it's a descendant of. - * @return {boolean} True if the node is ancestor or is a descendant of it. - */ -function isDescendantOfNode(node, ancestor) { - while (node && ancestor) { - if (node.isSameNode(ancestor)) { - return true; - } - node = node.parentNode; - } - return false; -} - - - -/** - * The class handling the Caret Browsing implementation in the page. - * Installs a keydown listener that always responds to the F7 key, - * sets up communication with the background page, and then when caret - * browsing is enabled, response to various key events to move the caret - * or selection within the text content of the document. Uses the native - * Chrome selection wherever possible, but displays its own flashing - * caret using a DIV because there's no native caret available. - * @constructor - */ -var CaretBrowsing = function() {}; - -/** - * Is caret browsing enabled? - * @type {boolean} - */ -CaretBrowsing.isEnabled = false; - -/** - * Keep it enabled even when flipped off (for the options page)? - * @type {boolean} - */ -CaretBrowsing.forceEnabled = false; - -/** - * What to do when the caret appears? - * @type {string} - */ -CaretBrowsing.onEnable; - -/** - * What to do when the caret jumps? - * @type {string} - */ -CaretBrowsing.onJump; - -/** - * Is this window / iframe focused? We won't show the caret if not, - * especially so that carets aren't shown in two iframes of the same - * tab. - * @type {boolean} - */ -CaretBrowsing.isWindowFocused = false; - -/** - * Is the caret actually visible? This is true only if isEnabled and - * isWindowFocused are both true. - * @type {boolean} - */ -CaretBrowsing.isCaretVisible = false; - -/** - * The actual caret element, an absolute-positioned flashing line. - * @type {Element} - */ -CaretBrowsing.caretElement; - -/** - * The x-position of the caret, in absolute pixels. - * @type {number} - */ -CaretBrowsing.caretX = 0; - -/** - * The y-position of the caret, in absolute pixels. - * @type {number} - */ -CaretBrowsing.caretY = 0; - -/** - * The width of the caret in pixels. - * @type {number} - */ -CaretBrowsing.caretWidth = 0; - -/** - * The height of the caret in pixels. - * @type {number} - */ -CaretBrowsing.caretHeight = 0; - -/** - * The foregroundc color. - * @type {string} - */ -CaretBrowsing.caretForeground = '#000'; - -/** - * The backgroundc color. - * @type {string} - */ -CaretBrowsing.caretBackground = '#fff'; - -/** - * Is the selection collapsed, i.e. are the start and end locations - * the same? If so, our blinking caret image is shown; otherwise - * the Chrome selection is shown. - * @type {boolean} - */ -CaretBrowsing.isSelectionCollapsed = false; - -/** - * The id returned by window.setInterval for our blink function, so - * we can cancel it when caret browsing is disabled. - * @type {number?} - */ -CaretBrowsing.blinkFunctionId = null; - -/** - * The desired x-coordinate to match when moving the caret up and down. - * To match the behavior as documented in Mozilla's caret browsing spec - * (http://www.mozilla.org/access/keyboard/proposal), we keep track of the - * initial x position when the user starts moving the caret up and down, - * so that the x position doesn't drift as you move throughout lines, but - * stays as close as possible to the initial position. This is reset when - * moving left or right or clicking. - * @type {number?} - */ -CaretBrowsing.targetX = null; - -/** - * A flag that flips on or off as the caret blinks. - * @type {boolean} - */ -CaretBrowsing.blinkFlag = true; - -/** - * Whether or not we're on a Mac - affects modifier keys. - * @type {boolean} - */ -CaretBrowsing.isMac = (navigator.appVersion.indexOf("Mac") != -1); - -/** - * Check if a node is a control that normally allows the user to interact - * with it using arrow keys. We won't override the arrow keys when such a - * control has focus, the user must press Escape to do caret browsing outside - * that control. - * @param {Node} node A node to check. - * @return {boolean} True if this node is a control that the user can - * interact with using arrow keys. - */ -CaretBrowsing.isControlThatNeedsArrowKeys = function(node) { - if (!node) { - return false; - } - - if (node == document.body || node != document.activeElement) { - return false; - } - - if (node.constructor == HTMLSelectElement) { - return true; - } - - if (node.constructor == HTMLInputElement) { - switch (node.type) { - case 'email': - case 'number': - case 'password': - case 'search': - case 'text': - case 'tel': - case 'url': - case '': - return true; // All of these are text boxes. - case 'datetime': - case 'datetime-local': - case 'date': - case 'month': - case 'radio': - case 'range': - case 'week': - return true; // These are other input elements that use arrows. - } - } - - // Handle focusable ARIA controls. - if (node.getAttribute && isFocusable(node)) { - var role = node.getAttribute('role'); - switch (role) { - case 'combobox': - case 'grid': - case 'gridcell': - case 'listbox': - case 'menu': - case 'menubar': - case 'menuitem': - case 'menuitemcheckbox': - case 'menuitemradio': - case 'option': - case 'radiogroup': - case 'scrollbar': - case 'slider': - case 'spinbutton': - case 'tab': - case 'tablist': - case 'textbox': - case 'tree': - case 'treegrid': - case 'treeitem': - return true; - } - } - - return false; -}; - -/** - * If there's no initial selection, set the cursor just before the - * first text character in the document. - */ -CaretBrowsing.setInitialCursor = function() { - var sel = window.getSelection(); - if (sel.rangeCount > 0) { - return; - } - - var start = new Cursor(document.body, 0, ''); - var end = new Cursor(document.body, 0, ''); - var nodesCrossed = []; - var result = TraverseUtil.getNextChar(start, end, nodesCrossed, true); - if (result == null) { - return; - } - CaretBrowsing.setAndValidateSelection(start, start); -}; - -/** - * Set focus to a node if it's focusable. If it's an input element, - * select the text, otherwise it doesn't appear focused to the user. - * Every other control behaves normally if you just call focus() on it. - * @param {Node} node The node to focus. - * @return {boolean} True if the node was focused. - */ -CaretBrowsing.setFocusToNode = function(node) { - while (node && node != document.body) { - if (isFocusable(node) && node.constructor != HTMLIFrameElement) { - node.focus(); - if (node.constructor == HTMLInputElement && node.select) { - node.select(); - } - return true; - } - node = node.parentNode; - } - - return false; -}; - -/** - * Set focus to the first focusable node in the given list. - * select the text, otherwise it doesn't appear focused to the user. - * Every other control behaves normally if you just call focus() on it. - * @param {Array.<Node>} nodeList An array of nodes to focus. - * @return {boolean} True if the node was focused. - */ -CaretBrowsing.setFocusToFirstFocusable = function(nodeList) { - for (var i = 0; i < nodeList.length; i++) { - if (CaretBrowsing.setFocusToNode(nodeList[i])) { - return true; - } - } - return false; -}; - -/** - * Set the caret element's normal style, i.e. not when animating. - */ -CaretBrowsing.setCaretElementNormalStyle = function() { - var element = CaretBrowsing.caretElement; - element.className = 'CaretBrowsing_Caret'; - element.style.opacity = CaretBrowsing.isSelectionCollapsed ? '1.0' : '0.0'; - element.style.left = CaretBrowsing.caretX + 'px'; - element.style.top = CaretBrowsing.caretY + 'px'; - element.style.width = CaretBrowsing.caretWidth + 'px'; - element.style.height = CaretBrowsing.caretHeight + 'px'; - element.style.color = CaretBrowsing.caretForeground; -}; - -/** - * Animate the caret element into the normal style. - */ -CaretBrowsing.animateCaretElement = function() { - var element = CaretBrowsing.caretElement; - element.style.left = (CaretBrowsing.caretX - 50) + 'px'; - element.style.top = (CaretBrowsing.caretY - 100) + 'px'; - element.style.width = (CaretBrowsing.caretWidth + 100) + 'px'; - element.style.height = (CaretBrowsing.caretHeight + 200) + 'px'; - element.className = 'CaretBrowsing_AnimateCaret'; - - // Start the animation. The setTimeout is so that the old values will get - // applied first, so we can animate to the new values. - window.setTimeout(function() { - if (!CaretBrowsing.caretElement) { - return; - } - CaretBrowsing.setCaretElementNormalStyle(); - element.style['-webkit-transition'] = 'all 0.8s ease-in'; - function listener() { - element.removeEventListener( - 'webkitTransitionEnd', listener, false); - element.style['-webkit-transition'] = 'none'; - } - element.addEventListener( - 'webkitTransitionEnd', listener, false); - }, 0); -}; - -/** - * Quick flash and then show the normal caret style. - */ -CaretBrowsing.flashCaretElement = function() { - var x = CaretBrowsing.caretX - window.pageXOffset; - var y = CaretBrowsing.caretY - window.pageYOffset; - var height = CaretBrowsing.caretHeight; - - var vert = document.createElement('div'); - vert.className = 'CaretBrowsing_FlashVert'; - vert.style.left = (x - 6) + 'px'; - vert.style.top = (y - 100) + 'px'; - vert.style.width = '11px'; - vert.style.height = (200) + 'px'; - document.body.appendChild(vert); - - window.setTimeout(function() { - document.body.removeChild(vert); - if (CaretBrowsing.caretElement) { - CaretBrowsing.setCaretElementNormalStyle(); - } - }, 250); -}; - -/** - * Create the caret element. This assumes that caretX, caretY, - * caretWidth, and caretHeight have all been set. The caret is - * animated in so the user can find it when it first appears. - */ -CaretBrowsing.createCaretElement = function() { - var element = document.createElement('div'); - element.className = 'CaretBrowsing_Caret'; - document.body.appendChild(element); - CaretBrowsing.caretElement = element; - - if (CaretBrowsing.onEnable == 'anim') { - CaretBrowsing.animateCaretElement(); - } else if (CaretBrowsing.onEnable == 'flash') { - CaretBrowsing.flashCaretElement(); - } else { - CaretBrowsing.setCaretElementNormalStyle(); - } -}; - -/** - * Recreate the caret element, triggering any intro animation. - */ -CaretBrowsing.recreateCaretElement = function() { - if (CaretBrowsing.caretElement) { - window.clearInterval(CaretBrowsing.blinkFunctionId); - CaretBrowsing.caretElement.parentElement.removeChild( - CaretBrowsing.caretElement); - CaretBrowsing.caretElement = null; - CaretBrowsing.updateIsCaretVisible(); - } -}; - -/** - * Get the rectangle for a cursor position. This is tricky because - * you can't get the bounding rectangle of an empty range, so this function - * computes the rect by trying a range including one character earlier or - * later than the cursor position. - * @param {Cursor} cursor A single cursor position. - * @return {{left: number, top: number, width: number, height: number}} - * The bounding rectangle of the cursor. - */ -CaretBrowsing.getCursorRect = function(cursor) { - var node = cursor.node; - var index = cursor.index; - var rect = { - left: 0, - top: 0, - width: 1, - height: 0 - }; - if (node.constructor == Text) { - var left = index; - var right = index; - var max = node.data.length; - var newRange = document.createRange(); - while (left > 0 || right < max) { - if (left > 0) { - left--; - newRange.setStart(node, left); - newRange.setEnd(node, index); - var rangeRect = newRange.getBoundingClientRect(); - if (rangeRect && rangeRect.width && rangeRect.height) { - rect.left = rangeRect.right; - rect.top = rangeRect.top; - rect.height = rangeRect.height; - break; - } - } - if (right < max) { - right++; - newRange.setStart(node, index); - newRange.setEnd(node, right); - var rangeRect = newRange.getBoundingClientRect(); - if (rangeRect && rangeRect.width && rangeRect.height) { - rect.left = rangeRect.left; - rect.top = rangeRect.top; - rect.height = rangeRect.height; - break; - } - } - } - } else { - rect.height = node.offsetHeight; - while (node !== null) { - rect.left += node.offsetLeft; - rect.top += node.offsetTop; - node = node.offsetParent; - } - } - rect.left += window.pageXOffset; - rect.top += window.pageYOffset; - return rect; -}; - -/** - * Compute the new location of the caret or selection and update - * the element as needed. - * @param {boolean} scrollToSelection If true, will also scroll the page - * to the caret / selection location. - */ -CaretBrowsing.updateCaretOrSelection = function(scrollToSelection) { - var previousX = CaretBrowsing.caretX; - var previousY = CaretBrowsing.caretY; - - var sel = window.getSelection(); - if (sel.rangeCount == 0) { - if (CaretBrowsing.caretElement) { - CaretBrowsing.isSelectionCollapsed = false; - CaretBrowsing.caretElement.style.opacity = '0.0'; - } - return; - } - - var range = sel.getRangeAt(0); - if (!range) { - if (CaretBrowsing.caretElement) { - CaretBrowsing.isSelectionCollapsed = false; - CaretBrowsing.caretElement.style.opacity = '0.0'; - } - return; - } - - if (CaretBrowsing.isControlThatNeedsArrowKeys(document.activeElement)) { - var node = document.activeElement; - CaretBrowsing.caretWidth = node.offsetWidth; - CaretBrowsing.caretHeight = node.offsetHeight; - CaretBrowsing.caretX = 0; - CaretBrowsing.caretY = 0; - while (node.offsetParent) { - CaretBrowsing.caretX += node.offsetLeft; - CaretBrowsing.caretY += node.offsetTop; - node = node.offsetParent; - } - CaretBrowsing.isSelectionCollapsed = false; - } else if (range.startOffset != range.endOffset || - range.startContainer != range.endContainer) { - var rect = range.getBoundingClientRect(); - if (!rect) { - return; - } - CaretBrowsing.caretX = rect.left + window.pageXOffset; - CaretBrowsing.caretY = rect.top + window.pageYOffset; - CaretBrowsing.caretWidth = rect.width; - CaretBrowsing.caretHeight = rect.height; - CaretBrowsing.isSelectionCollapsed = false; - } else { - var rect = CaretBrowsing.getCursorRect( - new Cursor(range.startContainer, - range.startOffset, - TraverseUtil.getNodeText(range.startContainer))); - CaretBrowsing.caretX = rect.left; - CaretBrowsing.caretY = rect.top; - CaretBrowsing.caretWidth = rect.width; - CaretBrowsing.caretHeight = rect.height; - CaretBrowsing.isSelectionCollapsed = true; - } - - if (!CaretBrowsing.caretElement) { - CaretBrowsing.createCaretElement(); - } else { - var element = CaretBrowsing.caretElement; - if (CaretBrowsing.isSelectionCollapsed) { - element.style.opacity = '1.0'; - element.style.left = CaretBrowsing.caretX + 'px'; - element.style.top = CaretBrowsing.caretY + 'px'; - element.style.width = CaretBrowsing.caretWidth + 'px'; - element.style.height = CaretBrowsing.caretHeight + 'px'; - } else { - element.style.opacity = '0.0'; - } - } - - var elem = range.startContainer; - if (elem.constructor == Text) - elem = elem.parentElement; - var style = window.getComputedStyle(elem); - var bg = axs.utils.getBgColor(style, elem); - var fg = axs.utils.getFgColor(style, elem, bg); - CaretBrowsing.caretBackground = axs.utils.colorToString(bg); - CaretBrowsing.caretForeground = axs.utils.colorToString(fg); - - if (scrollToSelection) { - // Scroll just to the "focus" position of the selection, - // the part the user is manipulating. - var rect = CaretBrowsing.getCursorRect( - new Cursor(sel.focusNode, sel.focusOffset, - TraverseUtil.getNodeText(sel.focusNode))); - - var yscroll = window.pageYOffset; - var pageHeight = window.innerHeight; - var caretY = rect.top; - var caretHeight = Math.min(rect.height, 30); - if (yscroll + pageHeight < caretY + caretHeight) { - window.scroll(0, (caretY + caretHeight - pageHeight + 100)); - } else if (caretY < yscroll) { - window.scroll(0, (caretY - 100)); - } - } - - if (Math.abs(previousX - CaretBrowsing.caretX) > 500 || - Math.abs(previousY - CaretBrowsing.caretY) > 100) { - if (CaretBrowsing.onJump == 'anim') { - CaretBrowsing.animateCaretElement(); - } else if (CaretBrowsing.onJump == 'flash') { - CaretBrowsing.flashCaretElement(); - } - } -}; - -/** - * Return true if the selection directionality is ambiguous, which happens - * if, for example, the user double-clicks in the middle of a word to select - * it. In that case, the selection should extend by the right edge if the - * user presses right, and by the left edge if the user presses left. - * @param {Selection} sel The selection. - * @return {boolean} True if the selection directionality is ambiguous. - */ -CaretBrowsing.isAmbiguous = function(sel) { - return (sel.anchorNode != sel.baseNode || - sel.anchorOffset != sel.baseOffset || - sel.focusNode != sel.extentNode || - sel.focusOffset != sel.extentOffset); -}; - -/** - * Create a Cursor from the anchor position of the selection, the - * part that doesn't normally move. - * @param {Selection} sel The selection. - * @return {Cursor} A cursor pointing to the selection's anchor location. - */ -CaretBrowsing.makeAnchorCursor = function(sel) { - return new Cursor(sel.anchorNode, sel.anchorOffset, - TraverseUtil.getNodeText(sel.anchorNode)); -}; - -/** - * Create a Cursor from the focus position of the selection. - * @param {Selection} sel The selection. - * @return {Cursor} A cursor pointing to the selection's focus location. - */ -CaretBrowsing.makeFocusCursor = function(sel) { - return new Cursor(sel.focusNode, sel.focusOffset, - TraverseUtil.getNodeText(sel.focusNode)); -}; - -/** - * Create a Cursor from the left boundary of the selection - the boundary - * closer to the start of the document. - * @param {Selection} sel The selection. - * @return {Cursor} A cursor pointing to the selection's left boundary. - */ -CaretBrowsing.makeLeftCursor = function(sel) { - var range = sel.rangeCount == 1 ? sel.getRangeAt(0) : null; - if (range && - range.endContainer == sel.anchorNode && - range.endOffset == sel.anchorOffset) { - return CaretBrowsing.makeFocusCursor(sel); - } else { - return CaretBrowsing.makeAnchorCursor(sel); - } -}; - -/** - * Create a Cursor from the right boundary of the selection - the boundary - * closer to the end of the document. - * @param {Selection} sel The selection. - * @return {Cursor} A cursor pointing to the selection's right boundary. - */ -CaretBrowsing.makeRightCursor = function(sel) { - var range = sel.rangeCount == 1 ? sel.getRangeAt(0) : null; - if (range && - range.endContainer == sel.anchorNode && - range.endOffset == sel.anchorOffset) { - return CaretBrowsing.makeAnchorCursor(sel); - } else { - return CaretBrowsing.makeFocusCursor(sel); - } -}; - -/** - * Try to set the window's selection to be between the given start and end - * cursors, and return whether or not it was successful. - * @param {Cursor} start The start position. - * @param {Cursor} end The end position. - * @return {boolean} True if the selection was successfully set. - */ -CaretBrowsing.setAndValidateSelection = function(start, end) { - var sel = window.getSelection(); - sel.setBaseAndExtent(start.node, start.index, end.node, end.index); - - if (sel.rangeCount != 1) { - return false; - } - - return (sel.anchorNode == start.node && - sel.anchorOffset == start.index && - sel.focusNode == end.node && - sel.focusOffset == end.index); -}; - -/** - * Note: the built-in function by the same name is unreliable. - * @param {Selection} sel The selection. - * @return {boolean} True if the start and end positions are the same. - */ -CaretBrowsing.isCollapsed = function(sel) { - return (sel.anchorOffset == sel.focusOffset && - sel.anchorNode == sel.focusNode); -}; - -/** - * Determines if the modifier key is held down that should cause - * the cursor to move by word rather than by character. - * @param {Event} evt A keyboard event. - * @return {boolean} True if the cursor should move by word. - */ -CaretBrowsing.isMoveByWordEvent = function(evt) { - if (CaretBrowsing.isMac) { - return evt.altKey; - } else { - return evt.ctrlKey; - } -}; - -/** - * Moves the cursor forwards to the next valid position. - * @param {Cursor} cursor The current cursor location. - * On exit, the cursor will be at the next position. - * @param {Array.<Node>} nodesCrossed Any HTML nodes crossed between the - * initial and final cursor position will be pushed onto this array. - * @return {?string} The character reached, or null if the bottom of the - * document has been reached. - */ -CaretBrowsing.forwards = function(cursor, nodesCrossed) { - var previousCursor = cursor.clone(); - var result = TraverseUtil.forwardsChar(cursor, nodesCrossed); - - // Work around the fact that TraverseUtil.forwardsChar returns once per - // char in a block of text, rather than once per possible selection - // position in a block of text. - if (result && cursor.node != previousCursor.node && cursor.index > 0) { - cursor.index = 0; - } - - return result; -}; - -/** - * Moves the cursor backwards to the previous valid position. - * @param {Cursor} cursor The current cursor location. - * On exit, the cursor will be at the previous position. - * @param {Array.<Node>} nodesCrossed Any HTML nodes crossed between the - * initial and final cursor position will be pushed onto this array. - * @return {?string} The character reached, or null if the top of the - * document has been reached. - */ -CaretBrowsing.backwards = function(cursor, nodesCrossed) { - var previousCursor = cursor.clone(); - var result = TraverseUtil.backwardsChar(cursor, nodesCrossed); - - // Work around the fact that TraverseUtil.backwardsChar returns once per - // char in a block of text, rather than once per possible selection - // position in a block of text. - if (result && - cursor.node != previousCursor.node && - cursor.index < cursor.text.length) { - cursor.index = cursor.text.length; - } - - return result; -}; - -/** - * Called when the user presses the right arrow. If there's a selection, - * moves the cursor to the end of the selection range. If it's a cursor, - * moves past one character. - * @param {Event} evt The DOM event. - * @return {boolean} True if the default action should be performed. - */ -CaretBrowsing.moveRight = function(evt) { - CaretBrowsing.targetX = null; - - var sel = window.getSelection(); - if (!evt.shiftKey && !CaretBrowsing.isCollapsed(sel)) { - var right = CaretBrowsing.makeRightCursor(sel); - CaretBrowsing.setAndValidateSelection(right, right); - return false; - } - - var start = CaretBrowsing.isAmbiguous(sel) ? - CaretBrowsing.makeLeftCursor(sel) : - CaretBrowsing.makeAnchorCursor(sel); - var end = CaretBrowsing.isAmbiguous(sel) ? - CaretBrowsing.makeRightCursor(sel) : - CaretBrowsing.makeFocusCursor(sel); - var previousEnd = end.clone(); - var nodesCrossed = []; - while (true) { - var result; - if (CaretBrowsing.isMoveByWordEvent(evt)) { - result = TraverseUtil.getNextWord(previousEnd, end, nodesCrossed); - } else { - previousEnd = end.clone(); - result = CaretBrowsing.forwards(end, nodesCrossed); - } - - if (result === null) { - return CaretBrowsing.moveLeft(evt); - } - - if (CaretBrowsing.setAndValidateSelection( - evt.shiftKey ? start : end, end)) { - break; - } - } - - if (!evt.shiftKey) { - nodesCrossed.push(end.node); - CaretBrowsing.setFocusToFirstFocusable(nodesCrossed); - } - - return false; -}; - -/** - * Called when the user presses the left arrow. If there's a selection, - * moves the cursor to the start of the selection range. If it's a cursor, - * moves backwards past one character. - * @param {Event} evt The DOM event. - * @return {boolean} True if the default action should be performed. - */ -CaretBrowsing.moveLeft = function(evt) { - CaretBrowsing.targetX = null; - - var sel = window.getSelection(); - if (!evt.shiftKey && !CaretBrowsing.isCollapsed(sel)) { - var left = CaretBrowsing.makeLeftCursor(sel); - CaretBrowsing.setAndValidateSelection(left, left); - return false; - } - - var start = CaretBrowsing.isAmbiguous(sel) ? - CaretBrowsing.makeLeftCursor(sel) : - CaretBrowsing.makeFocusCursor(sel); - var end = CaretBrowsing.isAmbiguous(sel) ? - CaretBrowsing.makeRightCursor(sel) : - CaretBrowsing.makeAnchorCursor(sel); - var previousStart = start.clone(); - var nodesCrossed = []; - while (true) { - var result; - if (CaretBrowsing.isMoveByWordEvent(evt)) { - result = TraverseUtil.getPreviousWord( - start, previousStart, nodesCrossed); - } else { - previousStart = start.clone(); - result = CaretBrowsing.backwards(start, nodesCrossed); - } - - if (result === null) { - break; - } - - if (CaretBrowsing.setAndValidateSelection( - evt.shiftKey ? end : start, start)) { - break; - } - } - - if (!evt.shiftKey) { - nodesCrossed.push(start.node); - CaretBrowsing.setFocusToFirstFocusable(nodesCrossed); - } - - return false; -}; - - -/** - * Called when the user presses the down arrow. If there's a selection, - * moves the cursor to the end of the selection range. If it's a cursor, - * attempts to move to the equivalent horizontal pixel position in the - * subsequent line of text. If this is impossible, go to the first character - * of the next line. - * @param {Event} evt The DOM event. - * @return {boolean} True if the default action should be performed. - */ -CaretBrowsing.moveDown = function(evt) { - var sel = window.getSelection(); - if (!evt.shiftKey && !CaretBrowsing.isCollapsed(sel)) { - var right = CaretBrowsing.makeRightCursor(sel); - CaretBrowsing.setAndValidateSelection(right, right); - return false; - } - - var start = CaretBrowsing.isAmbiguous(sel) ? - CaretBrowsing.makeLeftCursor(sel) : - CaretBrowsing.makeAnchorCursor(sel); - var end = CaretBrowsing.isAmbiguous(sel) ? - CaretBrowsing.makeRightCursor(sel) : - CaretBrowsing.makeFocusCursor(sel); - var endRect = CaretBrowsing.getCursorRect(end); - if (CaretBrowsing.targetX === null) { - CaretBrowsing.targetX = endRect.left; - } - var previousEnd = end.clone(); - var leftPos = end.clone(); - var rightPos = end.clone(); - var bestPos = null; - var bestY = null; - var bestDelta = null; - var bestHeight = null; - var nodesCrossed = []; - var y = -1; - while (true) { - if (null === CaretBrowsing.forwards(rightPos, nodesCrossed)) { - if (CaretBrowsing.setAndValidateSelection( - evt.shiftKey ? start : leftPos, leftPos)) { - break; - } else { - return CaretBrowsing.moveLeft(evt); - } - break; - } - var range = document.createRange(); - range.setStart(leftPos.node, leftPos.index); - range.setEnd(rightPos.node, rightPos.index); - var rect = range.getBoundingClientRect(); - if (rect && rect.width < rect.height) { - y = rect.top + window.pageYOffset; - - // Return the best match so far if we get half a line past the best. - if (bestY != null && y > bestY + bestHeight / 2) { - if (CaretBrowsing.setAndValidateSelection( - evt.shiftKey ? start : bestPos, bestPos)) { - break; - } else { - bestY = null; - } - } - - // Stop here if we're an entire line the wrong direction - // (for example, we reached the top of the next column). - if (y < endRect.top - endRect.height) { - if (CaretBrowsing.setAndValidateSelection( - evt.shiftKey ? start : leftPos, leftPos)) { - break; - } - } - - // Otherwise look to see if this current position is on the - // next line and better than the previous best match, if any. - if (y >= endRect.top + endRect.height) { - var deltaLeft = Math.abs(CaretBrowsing.targetX - rect.left); - if ((bestDelta == null || deltaLeft < bestDelta) && - (leftPos.node != end.node || leftPos.index != end.index)) { - bestPos = leftPos.clone(); - bestY = y; - bestDelta = deltaLeft; - bestHeight = rect.height; - } - var deltaRight = Math.abs(CaretBrowsing.targetX - rect.right); - if (bestDelta == null || deltaRight < bestDelta) { - bestPos = rightPos.clone(); - bestY = y; - bestDelta = deltaRight; - bestHeight = rect.height; - } - - // Return the best match so far if the deltas are getting worse, - // not better. - if (bestDelta != null && - deltaLeft > bestDelta && - deltaRight > bestDelta) { - if (CaretBrowsing.setAndValidateSelection( - evt.shiftKey ? start : bestPos, bestPos)) { - break; - } else { - bestY = null; - } - } - } - } - leftPos = rightPos.clone(); - } - - if (!evt.shiftKey) { - CaretBrowsing.setFocusToNode(leftPos.node); - } - - return false; -}; - -/** - * Called when the user presses the up arrow. If there's a selection, - * moves the cursor to the start of the selection range. If it's a cursor, - * attempts to move to the equivalent horizontal pixel position in the - * previous line of text. If this is impossible, go to the last character - * of the previous line. - * @param {Event} evt The DOM event. - * @return {boolean} True if the default action should be performed. - */ -CaretBrowsing.moveUp = function(evt) { - var sel = window.getSelection(); - if (!evt.shiftKey && !CaretBrowsing.isCollapsed(sel)) { - var left = CaretBrowsing.makeLeftCursor(sel); - CaretBrowsing.setAndValidateSelection(left, left); - return false; - } - - var start = CaretBrowsing.isAmbiguous(sel) ? - CaretBrowsing.makeLeftCursor(sel) : - CaretBrowsing.makeFocusCursor(sel); - var end = CaretBrowsing.isAmbiguous(sel) ? - CaretBrowsing.makeRightCursor(sel) : - CaretBrowsing.makeAnchorCursor(sel); - var startRect = CaretBrowsing.getCursorRect(start); - if (CaretBrowsing.targetX === null) { - CaretBrowsing.targetX = startRect.left; - } - var previousStart = start.clone(); - var leftPos = start.clone(); - var rightPos = start.clone(); - var bestPos = null; - var bestY = null; - var bestDelta = null; - var bestHeight = null; - var nodesCrossed = []; - var y = 999999; - while (true) { - if (null === CaretBrowsing.backwards(leftPos, nodesCrossed)) { - CaretBrowsing.setAndValidateSelection( - evt.shiftKey ? end : rightPos, rightPos); - break; - } - var range = document.createRange(); - range.setStart(leftPos.node, leftPos.index); - range.setEnd(rightPos.node, rightPos.index); - var rect = range.getBoundingClientRect(); - if (rect && rect.width < rect.height) { - y = rect.top + window.pageYOffset; - - // Return the best match so far if we get half a line past the best. - if (bestY != null && y < bestY - bestHeight / 2) { - if (CaretBrowsing.setAndValidateSelection( - evt.shiftKey ? end : bestPos, bestPos)) { - break; - } else { - bestY = null; - } - } - - // Exit if we're an entire line the wrong direction - // (for example, we reached the bottom of the previous column.) - if (y > startRect.top + startRect.height) { - if (CaretBrowsing.setAndValidateSelection( - evt.shiftKey ? end : rightPos, rightPos)) { - break; - } - } - - // Otherwise look to see if this current position is on the - // next line and better than the previous best match, if any. - if (y <= startRect.top - startRect.height) { - var deltaLeft = Math.abs(CaretBrowsing.targetX - rect.left); - if (bestDelta == null || deltaLeft < bestDelta) { - bestPos = leftPos.clone(); - bestY = y; - bestDelta = deltaLeft; - bestHeight = rect.height; - } - var deltaRight = Math.abs(CaretBrowsing.targetX - rect.right); - if ((bestDelta == null || deltaRight < bestDelta) && - (rightPos.node != start.node || rightPos.index != start.index)) { - bestPos = rightPos.clone(); - bestY = y; - bestDelta = deltaRight; - bestHeight = rect.height; - } - - // Return the best match so far if the deltas are getting worse, - // not better. - if (bestDelta != null && - deltaLeft > bestDelta && - deltaRight > bestDelta) { - if (CaretBrowsing.setAndValidateSelection( - evt.shiftKey ? end : bestPos, bestPos)) { - break; - } else { - bestY = null; - } - } - } - } - rightPos = leftPos.clone(); - } - - if (!evt.shiftKey) { - CaretBrowsing.setFocusToNode(rightPos.node); - } - - return false; -}; - -/** - * Set the document's selection to surround a control, so that the next - * arrow key they press will allow them to explore the content before - * or after a given control. - * @param {Node} control The control to escape from. - */ -CaretBrowsing.escapeFromControl = function(control) { - control.blur(); - - var start = new Cursor(control, 0, ''); - var previousStart = start.clone(); - var end = new Cursor(control, 0, ''); - var previousEnd = end.clone(); - - var nodesCrossed = []; - while (true) { - if (null === CaretBrowsing.backwards(start, nodesCrossed)) { - break; - } - - var r = document.createRange(); - r.setStart(start.node, start.index); - r.setEnd(previousStart.node, previousStart.index); - if (r.getBoundingClientRect()) { - break; - } - previousStart = start.clone(); - } - while (true) { - if (null === CaretBrowsing.forwards(end, nodesCrossed)) { - break; - } - if (isDescendantOfNode(end.node, control)) { - previousEnd = end.clone(); - continue; - } - - var r = document.createRange(); - r.setStart(previousEnd.node, previousEnd.index); - r.setEnd(end.node, end.index); - if (r.getBoundingClientRect()) { - break; - } - } - - if (!isDescendantOfNode(previousStart.node, control)) { - start = previousStart.clone(); - } - - if (!isDescendantOfNode(previousEnd.node, control)) { - end = previousEnd.clone(); - } - - CaretBrowsing.setAndValidateSelection(start, end); - - window.setTimeout(function() { - CaretBrowsing.updateCaretOrSelection(true); - }, 0); -}; - -/** - * Toggle whether caret browsing is enabled or not. - */ -CaretBrowsing.toggle = function() { - if (CaretBrowsing.forceEnabled) { - CaretBrowsing.recreateCaretElement(); - return; - } - - CaretBrowsing.isEnabled = !CaretBrowsing.isEnabled; - var obj = {}; - obj['enabled'] = CaretBrowsing.isEnabled; - chrome.storage.sync.set(obj); - CaretBrowsing.updateIsCaretVisible(); -}; - -/** - * Event handler, called when a key is pressed. - * @param {Event} evt The DOM event. - * @return {boolean} True if the default action should be performed. - */ -CaretBrowsing.onKeyDown = function(evt) { - if (evt.defaultPrevented) { - return; - } - - if (evt.keyCode == 118) { // F7 - CaretBrowsing.toggle(); - } - - if (!CaretBrowsing.isEnabled) { - return true; - } - - if (evt.target && CaretBrowsing.isControlThatNeedsArrowKeys( - /** @type (Node) */(evt.target))) { - if (evt.keyCode == 27) { - CaretBrowsing.escapeFromControl(/** @type {Node} */(evt.target)); - evt.preventDefault(); - evt.stopPropagation(); - return false; - } else { - return true; - } - } - - // If the current selection doesn't have a range, try to escape out of - // the current control. If that fails, return so we don't fail whe - // trying to move the cursor or selection. - var sel = window.getSelection(); - if (sel.rangeCount == 0) { - if (document.activeElement) { - CaretBrowsing.escapeFromControl(document.activeElement); - sel = window.getSelection(); - } - - if (sel.rangeCount == 0) { - return true; - } - } - - if (CaretBrowsing.caretElement) { - CaretBrowsing.caretElement.style.visibility = 'visible'; - CaretBrowsing.blinkFlag = true; - } - - var result = true; - switch (evt.keyCode) { - case 37: - result = CaretBrowsing.moveLeft(evt); - break; - case 38: - result = CaretBrowsing.moveUp(evt); - break; - case 39: - result = CaretBrowsing.moveRight(evt); - break; - case 40: - result = CaretBrowsing.moveDown(evt); - break; - } - - if (result == false) { - evt.preventDefault(); - evt.stopPropagation(); - } - - window.setTimeout(function() { - CaretBrowsing.updateCaretOrSelection(result == false); - }, 0); - - return result; -}; - -/** - * Event handler, called when the mouse is clicked. Chrome already - * sets the selection when the mouse is clicked, all we need to do is - * update our cursor. - * @param {Event} evt The DOM event. - * @return {boolean} True if the default action should be performed. - */ -CaretBrowsing.onClick = function(evt) { - if (!CaretBrowsing.isEnabled) { - return true; - } - window.setTimeout(function() { - CaretBrowsing.targetX = null; - CaretBrowsing.updateCaretOrSelection(false); - }, 0); - return true; -}; - -/** - * Called at a regular interval. Blink the cursor by changing its visibility. - */ -CaretBrowsing.caretBlinkFunction = function() { - if (CaretBrowsing.caretElement) { - if (CaretBrowsing.blinkFlag) { - CaretBrowsing.caretElement.style.backgroundColor = - CaretBrowsing.caretForeground; - CaretBrowsing.blinkFlag = false; - } else { - CaretBrowsing.caretElement.style.backgroundColor = - CaretBrowsing.caretBackground; - CaretBrowsing.blinkFlag = true; - } - } -}; - -/** - * Update whether or not the caret is visible, based on whether caret browsing - * is enabled and whether this window / iframe has focus. - */ -CaretBrowsing.updateIsCaretVisible = function() { - CaretBrowsing.isCaretVisible = - (CaretBrowsing.isEnabled && CaretBrowsing.isWindowFocused); - if (CaretBrowsing.isCaretVisible && !CaretBrowsing.caretElement) { - CaretBrowsing.setInitialCursor(); - CaretBrowsing.updateCaretOrSelection(true); - if (CaretBrowsing.caretElement) { - CaretBrowsing.blinkFunctionId = window.setInterval( - CaretBrowsing.caretBlinkFunction, 500); - } - } else if (!CaretBrowsing.isCaretVisible && - CaretBrowsing.caretElement) { - window.clearInterval(CaretBrowsing.blinkFunctionId); - if (CaretBrowsing.caretElement) { - CaretBrowsing.isSelectionCollapsed = false; - CaretBrowsing.caretElement.parentElement.removeChild( - CaretBrowsing.caretElement); - CaretBrowsing.caretElement = null; - } - } -}; - -/** - * Called when the prefs get updated. - */ -CaretBrowsing.onPrefsUpdated = function() { - chrome.storage.sync.get(null, function(result) { - if (!CaretBrowsing.forceEnabled) { - CaretBrowsing.isEnabled = result['enabled']; - } - CaretBrowsing.onEnable = result['onenable']; - CaretBrowsing.onJump = result['onjump']; - CaretBrowsing.recreateCaretElement(); - }); -}; - -/** - * Called when this window / iframe gains focus. - */ -CaretBrowsing.onWindowFocus = function() { - CaretBrowsing.isWindowFocused = true; - CaretBrowsing.updateIsCaretVisible(); -}; - -/** - * Called when this window / iframe loses focus. - */ -CaretBrowsing.onWindowBlur = function() { - CaretBrowsing.isWindowFocused = false; - CaretBrowsing.updateIsCaretVisible(); -}; - -/** - * Initializes caret browsing by adding event listeners and extension - * message listeners. - */ -CaretBrowsing.init = function() { - CaretBrowsing.isWindowFocused = document.hasFocus(); - - document.addEventListener('keydown', CaretBrowsing.onKeyDown, false); - document.addEventListener('click', CaretBrowsing.onClick, false); - window.addEventListener('focus', CaretBrowsing.onWindowFocus, false); - window.addEventListener('blur', CaretBrowsing.onWindowBlur, false); -}; - -window.setTimeout(function() { - - // Make sure the script only loads once. - if (!window['caretBrowsingLoaded']) { - window['caretBrowsingLoaded'] = true; - CaretBrowsing.init(); - - if (document.body.getAttribute('caretbrowsing') == 'on') { - CaretBrowsing.forceEnabled = true; - CaretBrowsing.isEnabled = true; - CaretBrowsing.updateIsCaretVisible(); - } - - chrome.storage.onChanged.addListener(function() { - CaretBrowsing.onPrefsUpdated(); - }); - CaretBrowsing.onPrefsUpdated(); - } - -}, 0);
diff --git a/ui/accessibility/extensions/caretbrowsing/increase_brightness.png b/ui/accessibility/extensions/caretbrowsing/increase_brightness.png deleted file mode 100644 index 7f427fb..0000000 --- a/ui/accessibility/extensions/caretbrowsing/increase_brightness.png +++ /dev/null Binary files differ
diff --git a/ui/accessibility/extensions/caretbrowsing/manifest.json b/ui/accessibility/extensions/caretbrowsing/manifest.json deleted file mode 100644 index fdabe26..0000000 --- a/ui/accessibility/extensions/caretbrowsing/manifest.json +++ /dev/null
@@ -1,43 +0,0 @@ -{ - "name": "__MSG_appName__", - "version": "0.3", - "description": "__MSG_appDesc__", - "manifest_version": 2, - "permissions": [ - "<all_urls>", - "storage", - "tabs" - ], - "background": { - "scripts": [ - "background.js" - ] - }, - "browser_action": { - "default_icon": "caret_19.png", - "default_title": "__MSG_toggle__" - }, - "content_scripts": [ - { - "matches": [ - "<all_urls>" - ], - "all_frames": true, - "css": [ - "caretbrowsing.css" - ], - "js": [ - "accessibility_utils.js", - "traverse_util.js", - "caretbrowsing.js" - ] - } - ], - "default_locale": "en", - "icons": { - "16": "caret_16.png", - "48": "caret_48.png", - "128": "caret_128.png" - }, - "options_page": "options.html" -}
diff --git a/ui/accessibility/extensions/caretbrowsing/options.html b/ui/accessibility/extensions/caretbrowsing/options.html deleted file mode 100644 index 6a463b8..0000000 --- a/ui/accessibility/extensions/caretbrowsing/options.html +++ /dev/null
@@ -1,218 +0,0 @@ -<html> -<head> - <title>Caret Browsing Options</title> - <style> - body { - font-family: Lucida Grande, sans-serif, arial, helvetica; - width: 920px; - margin-left: auto; - margin-right: auto; - } - .banner { - width: 100%; - float: left; - } - .banner_left { - padding: 8px; - float: left; - } - .banner_right { - padding: 8px; - } - .body_wrapper { - width: 100%; - float: left; - } - .body_left { - border: 0; - padding: 0; - margin: 0; - width: 50%; - float: left; - } - .body_right { - border: 0; - padding: 0; - margin: 0; - width: 46%; - float: left; - } - .body_inner { - padding: 0 32px; - } - body.mac .nonmac { - display: none; - } - body.nonmac .mac { - display: none; - } - body.cros .noncros { - display: none; - } - body.noncros .cros { - display: none; - } - .key { - border: 1px solid #666; - color: #444; - padding: 0.2em 0.8em; - margin: 0 0.3em; - background: #eee; - } - p { - line-height: 1.6em; - } - fieldset { - margin-bottom: 1em; - } - fieldset div { - margin: 0.6em 0; - } - p.cros img { - vertical-align: middle; - } - </style> - <link href="caretbrowsing.css" rel="stylesheet" type="text/css"> - <script src="accessibility_utils.js"></script> - <script src="traverse_util.js"></script> - <script src="caretbrowsing.js"></script> - <script src="options.js"></script> -</head> -<body caretbrowsing="on"> - -<div class="banner"> - <div class="banner_left"> - <img src="caret_128.png" class="logo" alt=""> - </div> - <div class="banner_right"> - <h1 i18n-content="appName">Caret Browsing</h1> - <p i18n-content="subheading1"> - This extension gives you a movable cursor in the web page, - allowing you to select text with the keyboard. - </p> - <p i18n-content="subheading2"> - Try it out now - Caret Browsing is always enabled on this page! - </p> - </div> -</div> - -<div class="body_wrapper"> - <div class="body_left"> - <div class="body_inner"> - <h2 i18n-content="keyboardCommands">Keyboard Commands</h2> - - <p class="noncros" i18n-content="enableDisableNonCros"> - Press <span class="key">F7</span> to turn on Caret Browsing. - Press it again to turn it off. - </p> - <p class="cros" i18n-content="enableDisableCros"> - Press <span class="key">Alt</span> + <img src="increase_brightness.png"> (the Increase Brightness key, or F7) to turn on Caret Browsing. - Press it again to turn it off. - </p> - - <div i18n-content="navHelp"> - <p> - Use arrow keys to move throughout the document. - </p> - - <p> - Click anywhere to move the cursor to that location. - </p> - - <p> - Press <span class="key">Shift</span> + arrows to select text. - </p> - </div> - - <p class="nonmac" i18n-content="moveByWordsNonMac"> - Hold down <span class="key">Control</span> to move by words. - </p> - <p class="mac" i18n-content="moveByWordsMac"> - Hold down <span class="key">Option</span> to move by words. - </p> - - <div i18n-content="focusHelp"> - <p> - When you reach a link or control, it is automatically focused. - Press <span class="key">Enter</span> to click a link or button. - </p> - - <p> - When a focused control (like a text box or a list box) is capturing - arrow keys, press <span class="key">Esc</span> followed by the - left or right arrow to continue Caret Browsing. - </p> - - <p> - Alternatively, press <span class="key">Tab</span> to move to the - next focusable control. - </p> - </div> - </div> - </div> - <div class="body_right"> - <div class="body_inner"> - <h2>Visual Feedback</h2> - - <fieldset> - <legend i18n-content="whenEnabled"> - When Caret Browsing is enabled: - </legend> - - <div> - <input type="radio" id="onenable_anim" name="onenable" value="anim"> - <label for="onenable_anim" i18n-content="animation"> - Highlight the cursor position with an animation. - </label> - </div> - - <div> - <input type="radio" id="onenable_flash" name="onenable" value="flash"> - <label for="onenable_flash" i18n-content="flash"> - Highlight the cursor position with a quick flash. - </label> - </div> - - <div> - <input type="radio" id="onenable_nothing" name="onenable" value="none"> - <label for="onenable_nothing" i18n-content="noFeedback"> - No feedback, just show the cursor. - </label> - </div> - - </fieldset> - - <fieldset> - <legend i18n-content="jump"> - When the caret jumps by a large distance: - </legend> - - <div> - <input type="radio" id="onjump_anim" name="onjump" value="anim"> - <label for="onjump_anim" i18n-content="animation"> - Highlight the cursor position with an animation. - </label> - </div> - - <div> - <input type="radio" id="onjump_flash" name="onjump" value="flash"> - <label for="onjump_flash" i18n-content="flash"> - Highlight the cursor position with a quick flash. - </label> - </div> - - <div> - <input type="radio" id="onjump_nothing" name="onjump" value="none"> - <label for="onjump_nothing" i18n-content="noFeedback"> - No feedback, just move the cursor. - </label> - </div> - - </fieldset> - - </div> - </div> -</div> - -</body> -</html>
diff --git a/ui/accessibility/extensions/caretbrowsing/options.js b/ui/accessibility/extensions/caretbrowsing/options.js deleted file mode 100644 index cd9a601..0000000 --- a/ui/accessibility/extensions/caretbrowsing/options.js +++ /dev/null
@@ -1,63 +0,0 @@ -/* Copyright (c) 2014 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. */ - -function setRadio(name, defaultValue) { - chrome.storage.sync.get(name, function(result) { - var value = result[name]; - if (value === undefined) { - value = defaultValue; - var obj = {}; - obj[name] = value; - chrome.storage.sync.set(obj); - } - var controls = document.querySelectorAll( - 'input[type="radio"][name="' + name + '"]'); - for (var i = 0; i < controls.length; i++) { - var c = controls[i]; - if (c.value == value) { - c.checked = true; - } - c.addEventListener('change', function(evt) { - if (evt.target.checked) { - var obj = {}; - obj[evt.target.name] = evt.target.value; - chrome.storage.sync.set(obj); - } - }, false); - } - }); -} - -function load() { - var isMac = (navigator.appVersion.indexOf("Mac") != -1); - if (isMac) { - document.body.classList.add('mac'); - } else { - document.body.classList.add('nonmac'); - } - - var isCros = (navigator.appVersion.indexOf("CrOS") != -1); - if (isCros) { - document.body.classList.add('cros'); - } else { - document.body.classList.add('noncros'); - } - - setRadio('onenable', 'anim'); - setRadio('onjump', 'flash'); - - var heading = document.querySelector('h1'); - var sel = window.getSelection(); - sel.setBaseAndExtent(heading, 0, heading, 0); - - document.title = chrome.i18n.getMessage('caretBrowsingOptions'); - var i18nElements = document.querySelectorAll('*[i18n-content]'); - for (var i = 0; i < i18nElements.length; i++) { - var elem = i18nElements[i]; - var msg = elem.getAttribute('i18n-content'); - elem.innerHTML = chrome.i18n.getMessage(msg); - } -} - -window.addEventListener('load', load, false);
diff --git a/ui/accessibility/extensions/caretbrowsing/traverse_util.js b/ui/accessibility/extensions/caretbrowsing/traverse_util.js deleted file mode 100644 index 4818fc9..0000000 --- a/ui/accessibility/extensions/caretbrowsing/traverse_util.js +++ /dev/null
@@ -1,869 +0,0 @@ -/* Copyright (c) 2014 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. */ - -/** - * @fileoverview Low-level DOM traversal utility functions to find the - * next (or previous) character, word, sentence, line, or paragraph, - * in a completely stateless manner without actually manipulating the - * selection. - */ - -/** - * A class to represent a cursor location in the document, - * like the start position or end position of a selection range. - * - * Later this may be extended to support "virtual text" for an object, - * like the ALT text for an image. - * - * Note: we cache the text of a particular node at the time we - * traverse into it. Later we should add support for dynamically - * reloading it. - * @param {Node} node The DOM node. - * @param {number} index The index of the character within the node. - * @param {string} text The cached text contents of the node. - * @constructor - */ -Cursor = function(node, index, text) { - this.node = node; - this.index = index; - this.text = text; -}; - -/** - * @return {Cursor} A new cursor pointing to the same location. - */ -Cursor.prototype.clone = function() { - return new Cursor(this.node, this.index, this.text); -}; - -/** - * Modify this cursor to point to the location that another cursor points to. - * @param {Cursor} otherCursor The cursor to copy from. - */ -Cursor.prototype.copyFrom = function(otherCursor) { - this.node = otherCursor.node; - this.index = otherCursor.index; - this.text = otherCursor.text; -}; - -/** - * Utility functions for stateless DOM traversal. - * @constructor - */ -TraverseUtil = function() {}; - -/** - * Gets the text representation of a node. This allows us to substitute - * alt text, names, or titles for html elements that provide them. - * @param {Node} node A DOM node. - * @return {string} A text string representation of the node. - */ -TraverseUtil.getNodeText = function(node) { - if (node.constructor == Text) { - return node.data; - } else { - return ''; - } -}; - -/** - * Return true if a node should be treated as a leaf node, because - * its children are properties of the object that shouldn't be traversed. - * - * TODO(dmazzoni): replace this with a predicate that detects nodes with - * ARIA roles and other objects that have their own description. - * For now we just detect a couple of common cases. - * - * @param {Node} node A DOM node. - * @return {boolean} True if the node should be treated as a leaf node. - */ -TraverseUtil.treatAsLeafNode = function(node) { - return node.childNodes.length == 0 || - node.nodeName == 'SELECT' || - node.nodeName == 'OBJECT'; -}; - -/** - * Return true only if a single character is whitespace. - * From https://developer.mozilla.org/en/Whitespace_in_the_DOM, - * whitespace is defined as one of the characters - * "\t" TAB \u0009 - * "\n" LF \u000A - * "\r" CR \u000D - * " " SPC \u0020. - * - * @param {string} c A string containing a single character. - * @return {boolean} True if the character is whitespace, otherwise false. - */ -TraverseUtil.isWhitespace = function(c) { - return (c == ' ' || c == '\n' || c == '\r' || c == '\t'); -}; - -/** - * Set the selection to the range between the given start and end cursors. - * @param {Cursor} start The desired start of the selection. - * @param {Cursor} end The desired end of the selection. - * @return {Selection} the selection object. - */ -TraverseUtil.setSelection = function(start, end) { - var sel = window.getSelection(); - sel.removeAllRanges(); - var range = document.createRange(); - range.setStart(start.node, start.index); - range.setEnd(end.node, end.index); - sel.addRange(range); - - return sel; -}; - -/** - * Use the computed CSS style to figure out if this DOM node is currently - * visible. - * @param {Node} node A HTML DOM node. - * @return {boolean} Whether or not the html node is visible. - */ -TraverseUtil.isVisible = function(node) { - if (!node.style) - return true; - var style = window.getComputedStyle(/** @type {Element} */(node), null); - return (!!style && style.display != 'none' && style.visibility != 'hidden'); -}; - -/** - * Use the class name to figure out if this DOM node should be traversed. - * @param {Node} node A HTML DOM node. - * @return {boolean} Whether or not the html node should be traversed. - */ -TraverseUtil.isSkipped = function(node) { - if (node.constructor == Text) - node = node.parentElement; - if (node.className == 'CaretBrowsing_Caret' || - node.className == 'CaretBrowsing_AnimateCaret') { - return true; - } - return false; -}; - -/** - * Moves the cursor forwards until it has crossed exactly one character. - * @param {Cursor} cursor The cursor location where the search should start. - * On exit, the cursor will be immediately to the right of the - * character returned. - * @param {Array.<Node>} nodesCrossed Any HTML nodes crossed between the - * initial and final cursor position will be pushed onto this array. - * @return {?string} The character found, or null if the bottom of the - * document has been reached. - */ -TraverseUtil.forwardsChar = function(cursor, nodesCrossed) { - while (true) { - // Move down until we get to a leaf node. - var childNode = null; - if (!TraverseUtil.treatAsLeafNode(cursor.node)) { - for (var i = cursor.index; i < cursor.node.childNodes.length; i++) { - var node = cursor.node.childNodes[i]; - if (TraverseUtil.isSkipped(node)) { - nodesCrossed.push(node); - continue; - } - if (TraverseUtil.isVisible(node)) { - childNode = node; - break; - } - } - } - if (childNode) { - cursor.node = childNode; - cursor.index = 0; - cursor.text = TraverseUtil.getNodeText(cursor.node); - if (cursor.node.constructor != Text) { - nodesCrossed.push(cursor.node); - } - continue; - } - - // Return the next character from this leaf node. - if (cursor.index < cursor.text.length) - return cursor.text[cursor.index++]; - - // Move to the next sibling, going up the tree as necessary. - while (cursor.node != null) { - // Try to move to the next sibling. - var siblingNode = null; - for (var node = cursor.node.nextSibling; - node != null; - node = node.nextSibling) { - if (TraverseUtil.isSkipped(node)) { - nodesCrossed.push(node); - continue; - } - if (TraverseUtil.isVisible(node)) { - siblingNode = node; - break; - } - } - if (siblingNode) { - cursor.node = siblingNode; - cursor.text = TraverseUtil.getNodeText(siblingNode); - cursor.index = 0; - - if (cursor.node.constructor != Text) { - nodesCrossed.push(cursor.node); - } - - break; - } - - // Otherwise, move to the parent. - if (cursor.node.parentNode && - cursor.node.parentNode.constructor != HTMLBodyElement) { - cursor.node = cursor.node.parentNode; - cursor.text = null; - cursor.index = 0; - } else { - return null; - } - } - } -}; - -/** - * Moves the cursor backwards until it has crossed exactly one character. - * @param {Cursor} cursor The cursor location where the search should start. - * On exit, the cursor will be immediately to the left of the - * character returned. - * @param {Array.<Node>} nodesCrossed Any HTML nodes crossed between the - * initial and final cursor position will be pushed onto this array. - * @return {?string} The previous character, or null if the top of the - * document has been reached. - */ -TraverseUtil.backwardsChar = function(cursor, nodesCrossed) { - while (true) { - // Move down until we get to a leaf node. - var childNode = null; - if (!TraverseUtil.treatAsLeafNode(cursor.node)) { - for (var i = cursor.index - 1; i >= 0; i--) { - var node = cursor.node.childNodes[i]; - if (TraverseUtil.isSkipped(node)) { - nodesCrossed.push(node); - continue; - } - if (TraverseUtil.isVisible(node)) { - childNode = node; - break; - } - } - } - if (childNode) { - cursor.node = childNode; - cursor.text = TraverseUtil.getNodeText(cursor.node); - if (cursor.text.length) - cursor.index = cursor.text.length; - else - cursor.index = cursor.node.childNodes.length; - if (cursor.node.constructor != Text) - nodesCrossed.push(cursor.node); - continue; - } - - // Return the previous character from this leaf node. - if (cursor.text.length > 0 && cursor.index > 0) { - return cursor.text[--cursor.index]; - } - - // Move to the previous sibling, going up the tree as necessary. - while (true) { - // Try to move to the previous sibling. - var siblingNode = null; - for (var node = cursor.node.previousSibling; - node != null; - node = node.previousSibling) { - if (TraverseUtil.isSkipped(node)) { - nodesCrossed.push(node); - continue; - } - if (TraverseUtil.isVisible(node)) { - siblingNode = node; - break; - } - } - if (siblingNode) { - cursor.node = siblingNode; - cursor.text = TraverseUtil.getNodeText(siblingNode); - if (cursor.text.length) - cursor.index = cursor.text.length; - else - cursor.index = cursor.node.childNodes.length; - if (cursor.node.constructor != Text) - nodesCrossed.push(cursor.node); - break; - } - - // Otherwise, move to the parent. - if (cursor.node.parentNode && - cursor.node.parentNode.constructor != HTMLBodyElement) { - cursor.node = cursor.node.parentNode; - cursor.text = null; - cursor.index = 0; - } else { - return null; - } - } - } -}; - -/** - * Finds the next character, starting from endCursor. Upon exit, startCursor - * and endCursor will surround the next character. If skipWhitespace is - * true, will skip until a real character is found. Otherwise, it will - * attempt to select all of the whitespace between the initial position - * of endCursor and the next non-whitespace character. - * @param {Cursor} startCursor On exit, points to the position before - * the char. - * @param {Cursor} endCursor The position to start searching for the next - * char. On exit, will point to the position past the char. - * @param {Array.<Node>} nodesCrossed Any HTML nodes crossed between the - * initial and final cursor position will be pushed onto this array. - * @param {boolean} skipWhitespace If true, will keep scanning until a - * non-whitespace character is found. - * @return {?string} The next char, or null if the bottom of the - * document has been reached. - */ -TraverseUtil.getNextChar = function( - startCursor, endCursor, nodesCrossed, skipWhitespace) { - - // Save the starting position and get the first character. - startCursor.copyFrom(endCursor); - var c = TraverseUtil.forwardsChar(endCursor, nodesCrossed); - if (c == null) - return null; - - // Keep track of whether the first character was whitespace. - var initialWhitespace = TraverseUtil.isWhitespace(c); - - // Keep scanning until we find a non-whitespace or non-skipped character. - while ((TraverseUtil.isWhitespace(c)) || - (TraverseUtil.isSkipped(endCursor.node))) { - c = TraverseUtil.forwardsChar(endCursor, nodesCrossed); - if (c == null) - return null; - } - if (skipWhitespace || !initialWhitespace) { - // If skipWhitepace is true, or if the first character we encountered - // was not whitespace, return that non-whitespace character. - startCursor.copyFrom(endCursor); - startCursor.index--; - return c; - } - else { - for (var i = 0; i < nodesCrossed.length; i++) { - if (TraverseUtil.isSkipped(nodesCrossed[i])) { - // We need to make sure that startCursor and endCursor aren't - // surrounding a skippable node. - endCursor.index--; - startCursor.copyFrom(endCursor); - startCursor.index--; - return ' '; - } - } - // Otherwise, return all of the whitespace before that last character. - endCursor.index--; - return ' '; - } -}; - -/** - * Finds the previous character, starting from startCursor. Upon exit, - * startCursor and endCursor will surround the previous character. - * If skipWhitespace is true, will skip until a real character is found. - * Otherwise, it will attempt to select all of the whitespace between - * the initial position of endCursor and the next non-whitespace character. - * @param {Cursor} startCursor The position to start searching for the - * char. On exit, will point to the position before the char. - * @param {Cursor} endCursor The position to start searching for the next - * char. On exit, will point to the position past the char. - * @param {Array.<Node>} nodesCrossed Any HTML nodes crossed between the - * initial and final cursor position will be pushed onto this array. - * @param {boolean} skipWhitespace If true, will keep scanning until a - * non-whitespace character is found. - * @return {?string} The previous char, or null if the top of the - * document has been reached. - */ -TraverseUtil.getPreviousChar = function( - startCursor, endCursor, nodesCrossed, skipWhitespace) { - - // Save the starting position and get the first character. - endCursor.copyFrom(startCursor); - var c = TraverseUtil.backwardsChar(startCursor, nodesCrossed); - if (c == null) - return null; - - // Keep track of whether the first character was whitespace. - var initialWhitespace = TraverseUtil.isWhitespace(c); - - // Keep scanning until we find a non-whitespace or non-skipped character. - while ((TraverseUtil.isWhitespace(c)) || - (TraverseUtil.isSkipped(startCursor.node))) { - c = TraverseUtil.backwardsChar(startCursor, nodesCrossed); - if (c == null) - return null; - } - if (skipWhitespace || !initialWhitespace) { - // If skipWhitepace is true, or if the first character we encountered - // was not whitespace, return that non-whitespace character. - endCursor.copyFrom(startCursor); - endCursor.index++; - return c; - } else { - for (var i = 0; i < nodesCrossed.length; i++) { - if (TraverseUtil.isSkipped(nodesCrossed[i])) { - startCursor.index++; - endCursor.copyFrom(startCursor); - endCursor.index++; - return ' '; - } - } - // Otherwise, return all of the whitespace before that last character. - startCursor.index++; - return ' '; - } -}; - -/** - * Finds the next word, starting from endCursor. Upon exit, startCursor - * and endCursor will surround the next word. A word is defined to be - * a string of 1 or more non-whitespace characters in the same DOM node. - * @param {Cursor} startCursor On exit, will point to the beginning of the - * word returned. - * @param {Cursor} endCursor The position to start searching for the next - * word. On exit, will point to the end of the word returned. - * @param {Array.<Node>} nodesCrossed Any HTML nodes crossed between the - * initial and final cursor position will be pushed onto this array. - * @return {?string} The next word, or null if the bottom of the - * document has been reached. - */ -TraverseUtil.getNextWord = function(startCursor, endCursor, - nodesCrossed) { - - // Find the first non-whitespace or non-skipped character. - var cursor = endCursor.clone(); - var c = TraverseUtil.forwardsChar(cursor, nodesCrossed); - if (c == null) - return null; - while ((TraverseUtil.isWhitespace(c)) || - (TraverseUtil.isSkipped(cursor.node))) { - c = TraverseUtil.forwardsChar(cursor, nodesCrossed); - if (c == null) - return null; - } - - // Set startCursor to the position immediately before the first - // character in our word. It's safe to decrement |index| because - // forwardsChar guarantees that the cursor will be immediately to the - // right of the returned character on exit. - startCursor.copyFrom(cursor); - startCursor.index--; - - // Keep building up our word until we reach a whitespace character or - // would cross a tag. Don't actually return any tags crossed, because this - // word goes up until the tag boundary but not past it. - endCursor.copyFrom(cursor); - var word = c; - var newNodesCrossed = []; - c = TraverseUtil.forwardsChar(cursor, newNodesCrossed); - if (c == null) { - return word; - } - while (!TraverseUtil.isWhitespace(c) && - newNodesCrossed.length == 0) { - word += c; - endCursor.copyFrom(cursor); - c = TraverseUtil.forwardsChar(cursor, newNodesCrossed); - if (c == null) { - return word; - } - } - return word; -}; - -/** - * Finds the previous word, starting from startCursor. Upon exit, startCursor - * and endCursor will surround the previous word. A word is defined to be - * a string of 1 or more non-whitespace characters in the same DOM node. - * @param {Cursor} startCursor The position to start searching for the - * previous word. On exit, will point to the beginning of the - * word returned. - * @param {Cursor} endCursor On exit, will point to the end of the - * word returned. - * @param {Array.<Node>} nodesCrossed Any HTML nodes crossed between the - * initial and final cursor position will be pushed onto this array. - * @return {?string} The previous word, or null if the bottom of the - * document has been reached. - */ -TraverseUtil.getPreviousWord = function(startCursor, endCursor, - nodesCrossed) { - // Find the first non-whitespace or non-skipped character. - var cursor = startCursor.clone(); - var c = TraverseUtil.backwardsChar(cursor, nodesCrossed); - if (c == null) - return null; - while ((TraverseUtil.isWhitespace(c) || - (TraverseUtil.isSkipped(cursor.node)))) { - c = TraverseUtil.backwardsChar(cursor, nodesCrossed); - if (c == null) - return null; - } - - // Set endCursor to the position immediately after the first - // character we've found (the last character of the word, since we're - // searching backwards). - endCursor.copyFrom(cursor); - endCursor.index++; - - // Keep building up our word until we reach a whitespace character or - // would cross a tag. Don't actually return any tags crossed, because this - // word goes up until the tag boundary but not past it. - startCursor.copyFrom(cursor); - var word = c; - var newNodesCrossed = []; - c = TraverseUtil.backwardsChar(cursor, newNodesCrossed); - if (c == null) - return word; - while (!TraverseUtil.isWhitespace(c) && - newNodesCrossed.length == 0) { - word = c + word; - startCursor.copyFrom(cursor); - c = TraverseUtil.backwardsChar(cursor, newNodesCrossed); - if (c == null) - return word; - } - - return word; -}; - -/** - * Finds the next sentence, starting from endCursor. Upon exit, - * startCursor and endCursor will surround the next sentence. - * - * @param {Cursor} startCursor On exit, marks the beginning of the sentence. - * @param {Cursor} endCursor The position to start searching for the next - * sentence. On exit, will point to the end of the returned string. - * @param {Array.<Node>} nodesCrossed Any HTML nodes crossed between the - * initial and final cursor position will be pushed onto this array. - * @param {Object} breakTags Associative array of tags that should break - * the sentence. - * @return {?string} The next sentence, or null if the bottom of the - * document has been reached. - */ -TraverseUtil.getNextSentence = function( - startCursor, endCursor, nodesCrossed, breakTags) { - return TraverseUtil.getNextString( - startCursor, endCursor, nodesCrossed, - function(str, word, nodes) { - if (str.substr(-1) == '.') - return true; - for (var i = 0; i < nodes.length; i++) { - if (TraverseUtil.isSkipped(nodes[i])) { - return true; - } - var style = window.getComputedStyle(nodes[i], null); - if (style && (style.display != 'inline' || - breakTags[nodes[i].tagName])) { - return true; - } - } - return false; - }); -}; - -/** - * Finds the previous sentence, starting from startCursor. Upon exit, - * startCursor and endCursor will surround the previous sentence. - * - * @param {Cursor} startCursor The position to start searching for the next - * sentence. On exit, will point to the start of the returned string. - * @param {Cursor} endCursor On exit, the end of the returned string. - * @param {Array.<Node>} nodesCrossed Any HTML nodes crossed between the - * initial and final cursor position will be pushed onto this array. - * @param {Object} breakTags Associative array of tags that should break - * the sentence. - * @return {?string} The previous sentence, or null if the bottom of the - * document has been reached. - */ -TraverseUtil.getPreviousSentence = function( - startCursor, endCursor, nodesCrossed, breakTags) { - return TraverseUtil.getPreviousString( - startCursor, endCursor, nodesCrossed, - function(str, word, nodes) { - if (word.substr(-1) == '.') - return true; - for (var i = 0; i < nodes.length; i++) { - if (TraverseUtil.isSkipped(nodes[i])) { - return true; - } - var style = window.getComputedStyle(nodes[i], null); - if (style && (style.display != 'inline' || - breakTags[nodes[i].tagName])) { - return true; - } - } - return false; - }); -}; - -/** - * Finds the next line, starting from endCursor. Upon exit, - * startCursor and endCursor will surround the next line. - * - * @param {Cursor} startCursor On exit, marks the beginning of the line. - * @param {Cursor} endCursor The position to start searching for the next - * line. On exit, will point to the end of the returned string. - * @param {Array.<Node>} nodesCrossed Any HTML nodes crossed between the - * initial and final cursor position will be pushed onto this array. - * @param {number} lineLength The maximum number of characters in a line. - * @param {Object} breakTags Associative array of tags that should break - * the line. - * @return {?string} The next line, or null if the bottom of the - * document has been reached. - */ -TraverseUtil.getNextLine = function( - startCursor, endCursor, nodesCrossed, lineLength, breakTags) { - return TraverseUtil.getNextString( - startCursor, endCursor, nodesCrossed, - function(str, word, nodes) { - if (str.length + word.length + 1 > lineLength) - return true; - for (var i = 0; i < nodes.length; i++) { - if (TraverseUtil.isSkipped(nodes[i])) { - return true; - } - var style = window.getComputedStyle(nodes[i], null); - if (style && (style.display != 'inline' || - breakTags[nodes[i].tagName])) { - return true; - } - } - return false; - }); -}; - -/** - * Finds the previous line, starting from startCursor. Upon exit, - * startCursor and endCursor will surround the previous line. - * - * @param {Cursor} startCursor The position to start searching for the next - * line. On exit, will point to the start of the returned string. - * @param {Cursor} endCursor On exit, the end of the returned string. - * @param {Array.<Node>} nodesCrossed Any HTML nodes crossed between the - * initial and final cursor position will be pushed onto this array. - * @param {number} lineLength The maximum number of characters in a line. - * @param {Object} breakTags Associative array of tags that should break - * the sentence. - * @return {?string} The previous line, or null if the bottom of the - * document has been reached. - */ -TraverseUtil.getPreviousLine = function( - startCursor, endCursor, nodesCrossed, lineLength, breakTags) { - return TraverseUtil.getPreviousString( - startCursor, endCursor, nodesCrossed, - function(str, word, nodes) { - if (str.length + word.length + 1 > lineLength) - return true; - for (var i = 0; i < nodes.length; i++) { - if (TraverseUtil.isSkipped(nodes[i])) { - return true; - } - var style = window.getComputedStyle(nodes[i], null); - if (style && (style.display != 'inline' || - breakTags[nodes[i].tagName])) { - return true; - } - } - return false; - }); -}; - -/** - * Finds the next paragraph, starting from endCursor. Upon exit, - * startCursor and endCursor will surround the next paragraph. - * - * @param {Cursor} startCursor On exit, marks the beginning of the paragraph. - * @param {Cursor} endCursor The position to start searching for the next - * paragraph. On exit, will point to the end of the returned string. - * @param {Array.<Node>} nodesCrossed Any HTML nodes crossed between the - * initial and final cursor position will be pushed onto this array. - * @return {?string} The next paragraph, or null if the bottom of the - * document has been reached. - */ -TraverseUtil.getNextParagraph = function(startCursor, endCursor, - nodesCrossed) { - return TraverseUtil.getNextString( - startCursor, endCursor, nodesCrossed, - function(str, word, nodes) { - for (var i = 0; i < nodes.length; i++) { - if (TraverseUtil.isSkipped(nodes[i])) { - return true; - } - var style = window.getComputedStyle(nodes[i], null); - if (style && style.display != 'inline') { - return true; - } - } - return false; - }); -}; - -/** - * Finds the previous paragraph, starting from startCursor. Upon exit, - * startCursor and endCursor will surround the previous paragraph. - * - * @param {Cursor} startCursor The position to start searching for the next - * paragraph. On exit, will point to the start of the returned string. - * @param {Cursor} endCursor On exit, the end of the returned string. - * @param {Array.<Node>} nodesCrossed Any HTML nodes crossed between the - * initial and final cursor position will be pushed onto this array. - * @return {?string} The previous paragraph, or null if the bottom of the - * document has been reached. - */ -TraverseUtil.getPreviousParagraph = function( - startCursor, endCursor, nodesCrossed) { - return TraverseUtil.getPreviousString( - startCursor, endCursor, nodesCrossed, - function(str, word, nodes) { - for (var i = 0; i < nodes.length; i++) { - if (TraverseUtil.isSkipped(nodes[i])) { - return true; - } - var style = window.getComputedStyle(nodes[i], null); - if (style && style.display != 'inline') { - return true; - } - } - return false; - }); -}; - -/** - * Customizable function to return the next string of words in the DOM, based - * on provided functions to decide when to break one string and start - * the next. This can be used to get the next sentence, line, paragraph, - * or potentially other granularities. - * - * Finds the next contiguous string, starting from endCursor. Upon exit, - * startCursor and endCursor will surround the next string. - * - * The breakBefore function takes three parameters, and - * should return true if the string should be broken before the proposed - * next word: - * str The string so far. - * word The next word to be added. - * nodesCrossed The nodes crossed in reaching this next word. - * - * @param {Cursor} startCursor On exit, will point to the beginning of the - * next string. - * @param {Cursor} endCursor The position to start searching for the next - * string. On exit, will point to the end of the returned string. - * @param {Array.<Node>} nodesCrossed Any HTML nodes crossed between the - * initial and final cursor position will be pushed onto this array. - * @param {function(string, string, Array.<string>)} breakBefore - * Function that takes the string so far, next word to be added, and - * nodes crossed, and returns true if the string should be ended before - * adding this word. - * @return {?string} The next string, or null if the bottom of the - * document has been reached. - */ -TraverseUtil.getNextString = function( - startCursor, endCursor, nodesCrossed, breakBefore) { - // Get the first word and set the start cursor to the start of the - // first word. - var wordStartCursor = endCursor.clone(); - var wordEndCursor = endCursor.clone(); - var newNodesCrossed = []; - var str = ''; - var word = TraverseUtil.getNextWord( - wordStartCursor, wordEndCursor, newNodesCrossed); - if (word == null) - return null; - startCursor.copyFrom(wordStartCursor); - - // Always add the first word when the string is empty, and then keep - // adding more words as long as breakBefore returns false - while (!str || !breakBefore(str, word, newNodesCrossed)) { - // Append this word, set the end cursor to the end of this word, and - // update the returned list of nodes crossed to include ones we crossed - // in reaching this word. - if (str) - str += ' '; - str += word; - nodesCrossed = nodesCrossed.concat(newNodesCrossed); - endCursor.copyFrom(wordEndCursor); - - // Get the next word and go back to the top of the loop. - newNodesCrossed = []; - word = TraverseUtil.getNextWord( - wordStartCursor, wordEndCursor, newNodesCrossed); - if (word == null) - return str; - } - - return str; -}; - -/** - * Customizable function to return the previous string of words in the DOM, - * based on provided functions to decide when to break one string and start - * the next. See getNextString, above, for more details. - * - * Finds the previous contiguous string, starting from startCursor. Upon exit, - * startCursor and endCursor will surround the next string. - * - * @param {Cursor} startCursor The position to start searching for the - * previous string. On exit, will point to the beginning of the - * string returned. - * @param {Cursor} endCursor On exit, will point to the end of the - * string returned. - * @param {Array.<Node>} nodesCrossed Any HTML nodes crossed between the - * initial and final cursor position will be pushed onto this array. - * @param {function(string, string, Array.<string>)} breakBefore - * Function that takes the string so far, the word to be added, and - * nodes crossed, and returns true if the string should be ended before - * adding this word. - * @return {?string} The next string, or null if the top of the - * document has been reached. - */ -TraverseUtil.getPreviousString = function( - startCursor, endCursor, nodesCrossed, breakBefore) { - // Get the first word and set the end cursor to the end of the - // first word. - var wordStartCursor = startCursor.clone(); - var wordEndCursor = startCursor.clone(); - var newNodesCrossed = []; - var str = ''; - var word = TraverseUtil.getPreviousWord( - wordStartCursor, wordEndCursor, newNodesCrossed); - if (word == null) - return null; - endCursor.copyFrom(wordEndCursor); - - // Always add the first word when the string is empty, and then keep - // adding more words as long as breakBefore returns false - while (!str || !breakBefore(str, word, newNodesCrossed)) { - // Prepend this word, set the start cursor to the start of this word, and - // update the returned list of nodes crossed to include ones we crossed - // in reaching this word. - if (str) - str = ' ' + str; - str = word + str; - nodesCrossed = nodesCrossed.concat(newNodesCrossed); - startCursor.copyFrom(wordStartCursor); -v - // Get the previous word and go back to the top of the loop. - newNodesCrossed = []; - word = TraverseUtil.getPreviousWord( - wordStartCursor, wordEndCursor, newNodesCrossed); - if (word == null) - return str; - } - - return str; -};
diff --git a/ui/accessibility/extensions/highcontrast/background.js b/ui/accessibility/extensions/highcontrast/background.js deleted file mode 100644 index 24cba94..0000000 --- a/ui/accessibility/extensions/highcontrast/background.js +++ /dev/null
@@ -1,100 +0,0 @@ -// Copyright (c) 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -function injectContentScripts() { - chrome.windows.getAll({'populate': true}, function(windows) { - for (var i = 0; i < windows.length; i++) { - var tabs = windows[i].tabs; - for (var j = 0; j < tabs.length; j++) { - var url = tabs[j].url; - if (url.indexOf('chrome') == 0 || url.indexOf('about') == 0) { - continue; - } - chrome.tabs.insertCSS( - tabs[j].id, - {file: 'highcontrast.css', allFrames: true}); - chrome.tabs.executeScript( - tabs[j].id, - {file: 'highcontrast.js', allFrames: true}); - } - } - }); -} - -function updateTabs() { - var msg = { - 'enabled': getEnabled() - }; - chrome.windows.getAll({'populate': true}, function(windows) { - for (var i = 0; i < windows.length; i++) { - var tabs = windows[i].tabs; - for (var j = 0; j < tabs.length; j++) { - var url = tabs[j].url; - if (isDisallowedUrl(url)) { - continue; - } - var msg = { - 'enabled': getEnabled(), - 'scheme': getSiteScheme(siteFromUrl(url)) - }; - chrome.tabs.sendRequest(tabs[j].id, msg); - } - } - }); -} - -function toggleEnabled() { - setEnabled(!getEnabled()); - updateTabs(); -} - -function toggleSite(url) { - var site = siteFromUrl(url); - var scheme = getSiteScheme(site); - if (scheme > 0) { - scheme = 0; - } else if (getDefaultScheme() > 0) { - scheme = getDefaultScheme(); - } else { - scheme = DEFAULT_SCHEME; - } - setSiteScheme(site, scheme); - updateTabs(); -} - -function init() { - injectContentScripts(); - updateTabs(); - - chrome.extension.onRequest.addListener( - function(request, sender, sendResponse) { - if (request['toggle_global']) { - toggleEnabled(); - } - if (request['toggle_site']) { - toggleSite(sender.tab ? sender.tab.url : 'www.example.com'); - } - if (request['init']) { - var scheme = getDefaultScheme(); - if (sender.tab) { - scheme = getSiteScheme(siteFromUrl(sender.tab.url)); - } - var msg = { - 'enabled': getEnabled(), - 'scheme': scheme - }; - sendResponse(msg); - } - }); - - document.addEventListener('storage', function(evt) { - updateTabs(); - }, false); - - if (navigator.appVersion.indexOf('Mac') != -1) { - chrome.browserAction.setTitle({'title': 'High Contrast (Cmd+Shift+F11)'}); - } -} - -init();
diff --git a/ui/accessibility/extensions/highcontrast/common.js b/ui/accessibility/extensions/highcontrast/common.js deleted file mode 100644 index e466642..0000000 --- a/ui/accessibility/extensions/highcontrast/common.js +++ /dev/null
@@ -1,101 +0,0 @@ -// Copyright (c) 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -var DEFAULT_SCHEME = 3; -var MAX_SCHEME = 5; - -function $(id) { - return document.getElementById(id); -} - -function getEnabled() { - var result = localStorage['enabled']; - if (result === 'true' || result === 'false') { - return (result === 'true'); - } - localStorage['enabled'] = 'true'; - return true; -} - -function setEnabled(enabled) { - localStorage['enabled'] = enabled; -} - -function getKeyAction() { - var keyAction = localStorage['keyaction']; - if (keyAction == 'global' || keyAction == 'site') { - return keyAction; - } - keyAction = 'global'; - localStorage['keyaction'] = keyAction; - return keyAction; -} - -function setKeyAction(keyAction) { - if (keyAction != 'global' && keyAction != 'site') { - keyAction = 'global'; - } - localStorage['keyaction'] = keyAction; -} - -function getDefaultScheme() { - var scheme = localStorage['scheme']; - if (scheme >= 0 && scheme <= MAX_SCHEME) { - return scheme; - } - scheme = DEFAULT_SCHEME; - localStorage['scheme'] = scheme; - return scheme; -} - -function setDefaultScheme(scheme) { - if (!(scheme >= 0 && scheme <= MAX_SCHEME)) { - scheme = DEFAULT_SCHEME; - } - localStorage['scheme'] = scheme; -} - -function getSiteScheme(site) { - var scheme = getDefaultScheme(); - try { - var siteSchemes = JSON.parse(localStorage['siteschemes']); - scheme = siteSchemes[site]; - if (!(scheme >= 0 && scheme <= MAX_SCHEME)) { - scheme = getDefaultScheme(); - } - } catch (e) { - scheme = getDefaultScheme(); - } - return scheme; -} - -function setSiteScheme(site, scheme) { - if (!(scheme >= 0 && scheme <= MAX_SCHEME)) { - scheme = getDefaultScheme(); - } - var siteSchemes = {}; - try { - siteSchemes = JSON.parse(localStorage['siteschemes']); - siteSchemes['www.example.com'] = getDefaultScheme(); - } catch (e) { - siteSchemes = {}; - } - siteSchemes[site] = scheme; - localStorage['siteschemes'] = JSON.stringify(siteSchemes); -} - -function resetSiteSchemes() { - var siteSchemes = {}; - localStorage['siteschemes'] = JSON.stringify(siteSchemes); -} - -function siteFromUrl(url) { - var a = document.createElement('a'); - a.href = url; - return a.hostname; -} - -function isDisallowedUrl(url) { - return url.indexOf('chrome') == 0 || url.indexOf('about') == 0; -}
diff --git a/ui/accessibility/extensions/highcontrast/highcontrast-128.png b/ui/accessibility/extensions/highcontrast/highcontrast-128.png deleted file mode 100644 index e63fa42..0000000 --- a/ui/accessibility/extensions/highcontrast/highcontrast-128.png +++ /dev/null Binary files differ
diff --git a/ui/accessibility/extensions/highcontrast/highcontrast-16.png b/ui/accessibility/extensions/highcontrast/highcontrast-16.png deleted file mode 100644 index 5ca52ef..0000000 --- a/ui/accessibility/extensions/highcontrast/highcontrast-16.png +++ /dev/null Binary files differ
diff --git a/ui/accessibility/extensions/highcontrast/highcontrast-19.png b/ui/accessibility/extensions/highcontrast/highcontrast-19.png deleted file mode 100644 index 9c8f5ab..0000000 --- a/ui/accessibility/extensions/highcontrast/highcontrast-19.png +++ /dev/null Binary files differ
diff --git a/ui/accessibility/extensions/highcontrast/highcontrast-48.png b/ui/accessibility/extensions/highcontrast/highcontrast-48.png deleted file mode 100644 index 67402fb..0000000 --- a/ui/accessibility/extensions/highcontrast/highcontrast-48.png +++ /dev/null Binary files differ
diff --git a/ui/accessibility/extensions/highcontrast/highcontrast.css b/ui/accessibility/extensions/highcontrast/highcontrast.css deleted file mode 100644 index c403063..0000000 --- a/ui/accessibility/extensions/highcontrast/highcontrast.css +++ /dev/null
@@ -1,81 +0,0 @@ -/* Copyright (c) 2014 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. */ - -html[hc="a0"] { - -webkit-filter: url('#hc_extension_off'); -} -html[hcx="0"] img[src*="jpg"], -html[hcx="0"] img[src*="jpeg"], -html[hcx="0"] svg image, -html[hcx="0"] img.rg_i, -html[hcx="0"] embed, -html[hcx="0"] object, -html[hcx="0"] video { - -webkit-filter: url('#hc_extension_off'); -} - -html[hc="a1"] { - -webkit-filter: url('#hc_extension_highcontrast'); -} -html[hcx="1"] img[src*="jpg"], -html[hcx="1"] img[src*="jpeg"], -html[hcx="1"] img.rg_i, -html[hcx="1"] svg image, -html[hcx="1"] embed, -html[hcx="1"] object, -html[hcx="1"] video { - -webkit-filter: url('#hc_extension_highcontrast_back'); -} - -html[hc="a2"] { - -webkit-filter: url('#hc_extension_grayscale'); -} -html[hcx="2"] img[src*="jpg"], -html[hcx="2"] img[src*="jpeg"], -html[hcx="2"] img.rg_i, -html[hcx="2"] svg image, -html[hcx="2"] embed, -html[hcx="2"] object, -html[hcx="2"] video { - -webkit-filter: url('#hc_extension_grayscale_back'); -} - -html[hc="a3"] { - -webkit-filter: url('#hc_extension_invert'); -} -html[hcx="3"] img[src*="jpg"], -html[hcx="3"] img[src*="jpeg"], -html[hcx="3"] img.rg_i, -html[hcx="3"] svg image, -html[hcx="3"] embed, -html[hcx="3"] object, -html[hcx="3"] video { - -webkit-filter: url('#hc_extension_invert_back'); -} - -html[hc="a4"] { - -webkit-filter: url('#hc_extension_invert_grayscale'); -} -html[hcx="4"] img[src*="jpg"], -html[hcx="4"] img[src*="jpeg"], -html[hcx="4"] img.rg_i, -html[hcx="4"] svg image, -html[hcx="4"] embed, -html[hcx="4"] object, -html[hcx="4"] video { - -webkit-filter: url('#hc_extension_invert_back'); -} - -html[hc="a5"] { - -webkit-filter: url('#hc_extension_yellow_on_black'); -} -html[hcx="5"] img[src*="jpg"], -html[hcx="5"] img[src*="jpeg"], -html[hcx="5"] img.rg_i, -html[hcx="5"] svg image, -html[hcx="5"] embed, -html[hcx="5"] object, -html[hcx="5"] video { - -webkit-filter: url('#hc_extension_yellow_on_black_back'); -}
diff --git a/ui/accessibility/extensions/highcontrast/highcontrast.js b/ui/accessibility/extensions/highcontrast/highcontrast.js deleted file mode 100644 index d115d3e..0000000 --- a/ui/accessibility/extensions/highcontrast/highcontrast.js +++ /dev/null
@@ -1,121 +0,0 @@ -// Copyright (c) 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -var mode; -var enabled = false; -var scheme = ''; -var timeoutId = null; - -var filterMap = { - '0': 'url("#hc_extension_off")', - '1': 'url("#hc_extension_highcontrast")', - '2': 'url("#hc_extension_grayscale")', - '3': 'url("#hc_extension_invert")', - '4': 'url("#hc_extension_invert_grayscale")', - '5': 'url("#hc_extension_yellow_on_black")' -}; - -var svgContent = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1"><defs><filter id="hc_extension_off"><feComponentTransfer><feFuncR type="table" tableValues="0 1"/><feFuncG type="table" tableValues="0 1"/><feFuncB type="table" tableValues="0 1"/></feComponentTransfer></filter><filter id="hc_extension_highcontrast"><feComponentTransfer><feFuncR type="gamma" exponent="3.0"/><feFuncG type="gamma" exponent="3.0"/><feFuncB type="gamma" exponent="3.0"/></feComponentTransfer></filter><filter id="hc_extension_highcontrast_back"><feComponentTransfer><feFuncR type="gamma" exponent="0.33"/><feFuncG type="gamma" exponent="0.33"/><feFuncB type="gamma" exponent="0.33"/></feComponentTransfer></filter><filter id="hc_extension_grayscale"><feColorMatrix type="matrix" values="0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"/><feComponentTransfer><feFuncR type="gamma" exponent="3"/><feFuncG type="gamma" exponent="3"/><feFuncB type="gamma" exponent="3"/></feComponentTransfer></filter><filter id="hc_extension_grayscale_back"><feComponentTransfer><feFuncR type="gamma" exponent="0.33"/><feFuncG type="gamma" exponent="0.33"/><feFuncB type="gamma" exponent="0.33"/></feComponentTransfer></filter><filter id="hc_extension_invert"><feComponentTransfer><feFuncR type="gamma" amplitude="-1" exponent="3" offset="1"/><feFuncG type="gamma" amplitude="-1" exponent="3" offset="1"/><feFuncB type="gamma" amplitude="-1" exponent="3" offset="1"/></feComponentTransfer></filter><filter id="hc_extension_invert_back"><feComponentTransfer><feFuncR type="table" tableValues="1 0"/><feFuncG type="table" tableValues="1 0"/><feFuncB type="table" tableValues="1 0"/></feComponentTransfer><feComponentTransfer><feFuncR type="gamma" exponent="1.7"/><feFuncG type="gamma" exponent="1.7"/><feFuncB type="gamma" exponent="1.7"/></feComponentTransfer></filter><filter id="hc_extension_invert_grayscale"><feColorMatrix type="matrix" values="0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"/><feComponentTransfer><feFuncR type="gamma" amplitude="-1" exponent="3" offset="1"/><feFuncG type="gamma" amplitude="-1" exponent="3" offset="1"/><feFuncB type="gamma" amplitude="-1" exponent="3" offset="1"/></feComponentTransfer></filter><filter id="hc_extension_yellow_on_black"><feComponentTransfer><feFuncR type="gamma" amplitude="-1" exponent="3" offset="1"/><feFuncG type="gamma" amplitude="-1" exponent="3" offset="1"/><feFuncB type="gamma" amplitude="-1" exponent="3" offset="1"/></feComponentTransfer><feColorMatrix type="matrix" values="0.3 0.5 0.2 0 0 0.3 0.5 0.2 0 0 0 0 0 0 0 0 0 0 1 0"/></filter><filter id="hc_extension_yellow_on_black_back"><feComponentTransfer><feFuncR type="table" tableValues="1 0"/><feFuncG type="table" tableValues="1 0"/><feFuncB type="table" tableValues="1 0"/></feComponentTransfer><feComponentTransfer><feFuncR type="gamma" exponent="0.33"/><feFuncG type="gamma" exponent="0.33"/><feFuncB type="gamma" exponent="0.33"/></feComponentTransfer></filter></defs></svg>'; - -function addSvgIfMissing() { - var wrap = document.getElementById('hc_extension_svg_filters'); - if (wrap) - return; - wrap = document.createElement('span'); - wrap.id = 'hc_extension_svg_filters'; - wrap.setAttribute('hidden', ''); - wrap.innerHTML = svgContent; - document.body.appendChild(wrap); -} - -function update() { - var html = document.documentElement; - if (enabled) { - if (!document.body) { - window.setTimeout(update, 100); - return; - } - addSvgIfMissing(); - if (html.getAttribute('hc') != mode + scheme) - html.setAttribute('hc', mode + scheme); - if (html.getAttribute('hcx') != scheme) - html.setAttribute('hcx', scheme); - - if (window == window.top) { - window.scrollBy(0, 1); - window.scrollBy(0, -1); - } - - /** - if (mode == 'a') { - html.style.webkitFilter = filterMap[scheme]; - } - else { - html.style.webkitFilter = 'none'; - }**/ - - } else { - html.setAttribute('hc', mode + '0'); - html.setAttribute('hcx', '0'); - window.setTimeout(function() { - html.removeAttribute('hc'); - html.removeAttribute('hcx'); - }, 0); - } -} - -function onExtensionMessage(request) { - if (enabled != request.enabled || scheme != request.scheme) { - enabled = request.enabled; - scheme = request.scheme; - update(); - } -} - -function onEvent(evt) { - if (evt.keyCode == 122 /* F11 */ && - evt.shiftKey) { - chrome.extension.sendRequest({'toggle_global': true}); - evt.stopPropagation(); - evt.preventDefault(); - return false; - } - if (evt.keyCode == 123 /* F12 */ && - evt.shiftKey) { - chrome.extension.sendRequest({'toggle_site': true}); - evt.stopPropagation(); - evt.preventDefault(); - return false; - } - return true; -} - -function init() { - if (window == window.top) { - mode = 'a'; - } else { - mode = 'b'; - } - chrome.extension.onRequest.addListener(onExtensionMessage); - chrome.extension.sendRequest({'init': true}, onExtensionMessage); - document.addEventListener('keydown', onEvent, false); - - // Work around bug that causes filter to be lost when the HTML element's attributes change. - var html = document.documentElement; - var config = { attributes: true, childList: false, characterData: false }; - var observer = new MutationObserver(function(mutations) { - observer.disconnect(); - html.removeAttribute('hc'); - html.removeAttribute('hcx'); - window.setTimeout(function() { - update(); - window.setTimeout(function() { - observer.observe(html, config); - }, 0); - }, 0); - }); - observer.observe(html, config); -} - -init();
diff --git a/ui/accessibility/extensions/highcontrast/manifest.json b/ui/accessibility/extensions/highcontrast/manifest.json deleted file mode 100644 index 4ffbb97..0000000 --- a/ui/accessibility/extensions/highcontrast/manifest.json +++ /dev/null
@@ -1,41 +0,0 @@ -{ - "name": "__MSG_appName__", - "version": "0.6", - "description": "__MSG_appDesc__", - "manifest_version": 2, - "permissions": [ - "<all_urls>", - "tabs" - ], - "background": { - "scripts": [ - "common.js", - "background.js" - ] - }, - "browser_action": { - "default_icon": "highcontrast-19.png", - "default_title": "__MSG_appName__", - "default_popup": "popup.html" - }, - "content_scripts": [ - { - "run_at": "document_start", - "matches": [ - "<all_urls>" - ], - "all_frames": true, - "css": [ - "highcontrast.css" - ], - "js": [ - "highcontrast.js" - ] - } - ], - "icons": { - "16": "highcontrast-16.png", - "48": "highcontrast-48.png", - "128": "highcontrast-128.png" - } -}
diff --git a/ui/accessibility/extensions/highcontrast/popup.html b/ui/accessibility/extensions/highcontrast/popup.html deleted file mode 100644 index e3e58d9..0000000 --- a/ui/accessibility/extensions/highcontrast/popup.html +++ /dev/null
@@ -1,106 +0,0 @@ -<!doctype html> -<html> -<head> -<link rel="stylesheet" type="text/css" href="highcontrast.css"> -<style type="text/css"> -html { - border-radius: 6px; -} -body { - width: 18em; - padding: 0.75em; - border-radius: 6px; -} -* { - font-family: Arial, Helvetica, sans-serif; - font-size: 10pt; -} -#title { - outline: none; -} -.kb { - font-weight: normal; - font-style: italic; - font-size: 10pt; -} -button { - width: 100%; - margin: 0.75em 0 0.25em 0; - padding: 0.5em 1.5em; -} -button#toggle { - font-size: 12pt; -} -body.disabled h3, -body.disabled a, -body.disabled label { - color: #aaa; -} -h2 { - font-size: 12pt; - text-align: center; -} -label { - display: block; -} -fieldset { - border: none; - margin: 0; - margin-bottom: 1em; - padding: 0; -} -legend { - padding-top: 1em; - padding-bottom: 0.5em; -} -input[type="radio"] { - margin-left: 1em; -} -</style> -<script type="text/javascript" src="common.js"></script> -<script type="text/javascript" src="popup.js"></script> -</head> -<body> - -<h2 id="title"></h2> - -<button id="toggle"></button> - -<div id="subcontrols"> - - <fieldset> - <legend id="scheme_title"></legend> - <label> - <input type="radio" name="scheme" value="0"> - <span i18n-content="normal"></span> - </label> - <label> - <input type="radio" name="scheme" value="1"> - <span i18n-content="increased_contrast"><span>Increased Contrast - </label> - <label> - <input type="radio" name="scheme" value="2"> - Grayscale - </label> - <label> - <input type="radio" name="scheme" value="3"> - Inverted Color - </label> - <label> - <input type="radio" name="scheme" value="4"> - Inverted Grayscale - </label> - <label> - <input type="radio" name="scheme" value="5"> - Yellow on Black - </label> - </fieldset> - - <button id="make_default">Set as default scheme</button> - - <button id="forget">Forget site customizations</button> - -</div> - -</body> -</html>
diff --git a/ui/accessibility/extensions/highcontrast/popup.js b/ui/accessibility/extensions/highcontrast/popup.js deleted file mode 100644 index 33fc0df..0000000 --- a/ui/accessibility/extensions/highcontrast/popup.js +++ /dev/null
@@ -1,139 +0,0 @@ -// Copyright (c) 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -var site; -var key1; -var key2; - -function setRadio(name, value) { - var radios = document.querySelectorAll('input[name="' + name + '"]'); - for (var i = 0; i < radios.length; i++) { - radios[i].checked = (radios[i].value == value); - radios[i].disabled = !getEnabled(); - } -} - -function update() { - document.body.className = getEnabled() ? '' : 'disabled'; - - if (getEnabled()) { - $('title').innerText = 'High Contrast is Enabled'; - $('toggle').innerHTML = '<b>Disable</b> ' + - '<span class="kb">(' + key1 + ')</span>'; - $('subcontrols').style.display = 'block'; - } else { - $('title').innerText = 'High Contrast is Disabled'; - $('toggle').innerHTML = '<b>Enable</b> ' + - '<span class="kb">(' + key1 + ')</span>'; - $('subcontrols').style.display = 'none'; - } - - setRadio('keyaction', getKeyAction()); - if (site) { - setRadio('scheme', getSiteScheme(site)); - $('make_default').disabled = (getSiteScheme(site) == getDefaultScheme()); - } else { - setRadio('scheme', getDefaultScheme()); - } - if (getEnabled()) { - document.documentElement.setAttribute( - 'hc', - site ? 'a' + getSiteScheme(site) : 'a' + getDefaultScheme()); - } else { - document.documentElement.setAttribute('hc', 'a0'); - } - chrome.extension.getBackgroundPage().updateTabs(); -} - -function onToggle() { - setEnabled(!getEnabled()); - update(); -} - -function onForget() { - resetSiteSchemes(); - update(); -} - -function onRadioChange(name, value) { - switch (name) { - case 'keyaction': - setKeyAction(value); - break; - case 'apply': - setApply(value); - break; - case 'scheme': - if (site) { - setSiteScheme(site, value); - } else { - setDefaultScheme(value); - } - break; - } - update(); -} - -function onMakeDefault() { - setDefaultScheme(getSiteScheme(site)); - update(); -} - -function addRadioListeners(name) { - var radios = document.querySelectorAll('input[name="' + name + '"]'); - for (var i = 0; i < radios.length; i++) { - radios[i].addEventListener('change', function(evt) { - onRadioChange(evt.target.name, evt.target.value); - }, false); - radios[i].addEventListener('click', function(evt) { - onRadioChange(evt.target.name, evt.target.value); - }, false); - } -} - -function init() { - var i18nElements = document.querySelectorAll('*[i18n-content]'); - for (var i = 0; i < i18nElements.length; i++) { - var elem = i18nElements[i]; - var msg = elem.getAttribute('i18n-content'); - elem.innerHTML = chrome.i18n.getMessage(msg); - } - - addRadioListeners('keyaction'); - addRadioListeners('apply'); - addRadioListeners('scheme'); - $('toggle').addEventListener('click', onToggle, false); - $('make_default').addEventListener('click', onMakeDefault, false); - $('forget').addEventListener('click', onForget, false); - if (navigator.appVersion.indexOf('Mac') != -1) { - key1 = '⌘+Shift+F11'; - key2 = '⌘+Shift+F12'; - } else { - key1 = 'Shift+F11'; - key2 = 'Shift+F12'; - } - - chrome.windows.getLastFocused({'populate': true}, function(window) { - for (var i = 0; i < window.tabs.length; i++) { - var tab = window.tabs[i]; - if (tab.active) { - if (isDisallowedUrl(tab.url)) { - $('scheme_title').innerText = 'Default color scheme:'; - $('make_default').style.display = 'none'; - } else { - site = siteFromUrl(tab.url); - $('scheme_title').innerHTML = 'Color scheme for <b>' + site + - '</b>:<br><span class="kb">(' + key2 + ')</span>'; - $('make_default').style.display = 'block'; - } - update(); - return; - } - } - site = 'unknown site'; - update(); - }); -} - -window.addEventListener('load', init, false);
diff --git a/ui/accessibility/extensions/longdesc/background.js b/ui/accessibility/extensions/longdesc/background.js deleted file mode 100644 index 3c97bc0..0000000 --- a/ui/accessibility/extensions/longdesc/background.js +++ /dev/null
@@ -1,66 +0,0 @@ -/* Copyright (c) 2014 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. */ - -var ariaDescribedAt = ''; -var longDesc = ''; - - /** - * This is called when the extension is first loaded, so that it can be - * immediately used in all already-open tabs. It's not needed for any - * new tabs that open after that, the content script will be automatically - * injected into any new tab. - */ -chrome.windows.getAll({'populate': true}, function(windows) { - for (var i = 0; i < windows.length; i++) { - var tabs = windows[i].tabs; - for (var j = 0; j < tabs.length; j++) { - chrome.tabs.executeScript( - tabs[j].id, - {file: 'lastRightClick.js'}); - } - } -}); - -/** - * Add context menu item when the extension is installed. - */ -chrome.contextMenus.create({ - "title": chrome.i18n.getMessage('openLongDescription'), - "contexts": ["all"], - "id": "moreInfo", - "onclick": contextMenuClicked, - "enabled": false - }); - -/** - * Add listener for messages from content script. - * Enable/disable the context menu item. - */ -chrome.runtime.onMessage.addListener( - function (request, sender, sendResponse) { - if (request.enabled) { - ariaDescribedAt = request.ariaDescribedAt; - longDesc = request.longDesc; - } - chrome.contextMenus.update('moreInfo', { - "enabled": request.enabled - }); - }); - -/** - * Event handler for when a context menu item is clicked. - * aria-describedat is given a higher priority. - * No need to strip the URL of leading/trailing white space - * because Chrome takes care of this. - * - * @param info - * @param tab - */ -function contextMenuClicked(info, tab) { - if (ariaDescribedAt !== '') { - chrome.tabs.create({url: ariaDescribedAt}); - } else if (longDesc !== '') { - chrome.tabs.create({url: longDesc}); - } -}
diff --git a/ui/accessibility/extensions/longdesc/icon.png b/ui/accessibility/extensions/longdesc/icon.png deleted file mode 100644 index 3792d51..0000000 --- a/ui/accessibility/extensions/longdesc/icon.png +++ /dev/null Binary files differ
diff --git a/ui/accessibility/extensions/longdesc/lastRightClick.js b/ui/accessibility/extensions/longdesc/lastRightClick.js deleted file mode 100644 index 42566b9..0000000 --- a/ui/accessibility/extensions/longdesc/lastRightClick.js +++ /dev/null
@@ -1,96 +0,0 @@ -/* Copyright (c) 2014 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. */ - -var borderColor; -var borderStyle; -var borderWidth; - -chrome.storage.onChanged.addListener(function(changes, namespace) { - if (changes.addBorder.newValue) { - addBorders(); - } else { - removeBorders(); - } -}); - -chrome.storage.sync.get("addBorder", function(item) { - if (item.addBorder) { - addBorders(); - } -}); - -document.addEventListener('contextmenu', function(element) { - updateContextMenuItem(element); -}, false); - -document.addEventListener('mouseover', function(element) { - updateContextMenuItem(element); -}, false); - -document.addEventListener('focus', function(element) { - updateContextMenuItem(element); -}); - -/** - * Sends a message to the backgrond script notifying it to - * enable or disable the context menu item. - * - * @param element - */ -function updateContextMenuItem(element) { - var longDesc = ''; - var ariaDescribedAt = ''; - - if (element.target.hasAttribute("longdesc")) { - longDesc = element.target.getAttribute("longdesc"); - } - - if (element.target.hasAttribute("aria-describedat")) { - ariaDescribedAt = element.target.getAttribute("aria-describedat"); - } - - if (longDesc !== '' || ariaDescribedAt !== '') { - chrome.runtime.sendMessage({ - ariaDescribedAt: ariaDescribedAt, - longDesc: longDesc, - enabled: true - }); - } else { - chrome.runtime.sendMessage({ - enabled: false - }); - } -} - -/** - * Modify border to make the HTML element more visible. - */ -function addBorders() { - var elementArray = new Array(document.querySelectorAll('[longdesc]')); - elementArray.concat(new Array(document.querySelectorAll('[aria-describedat]'))); - - for (var i = 0; i < elementArray.length; i++) { - borderColor = elementArray[0][i].style.borderColor; - borderStyle = elementArray[0][i].style.borderStyle; - borderWidth = elementArray[0][i].style.borderWidth; - - elementArray[0][i].style.borderColor = 'blue'; - elementArray[0][i].style.borderStyle = 'groove'; - elementArray[0][i].style.borderWidth = '15px'; - } -} - -/** - * Revert back to the original border styling. - */ -function removeBorders() { - var elementArray = new Array(document.querySelectorAll('[longdesc]')); - elementArray.concat(new Array(document.querySelectorAll('[aria-describedat]'))); - - for (var i = 0; i < elementArray.length; i++) { - elementArray[0][i].style.borderColor = borderColor; - elementArray[0][i].style.borderStyle = borderStyle; - elementArray[0][i].style.borderWidth = borderWidth; - } -}
diff --git a/ui/accessibility/extensions/longdesc/manifest.json b/ui/accessibility/extensions/longdesc/manifest.json deleted file mode 100644 index b374c47..0000000 --- a/ui/accessibility/extensions/longdesc/manifest.json +++ /dev/null
@@ -1,23 +0,0 @@ -{ - "name": "__MSG_appName__", - "version": "0.1", - "description": "__MSG_appDesc__", - "background": { - "scripts": [ "background.js" ] - }, - "content_scripts": [{ - "matches": ["<all_urls>"], - "js": ["lastRightClick.js"] - }], - "icons": { - "16": "icon.png" - }, - "permissions": [ - "tabs", - "contextMenus", - "storage", - "<all_urls>" - ], - "manifest_version": 2, - "options_page": "options.html" -}
diff --git a/ui/accessibility/extensions/longdesc/options.html b/ui/accessibility/extensions/longdesc/options.html deleted file mode 100644 index 8cc2a95..0000000 --- a/ui/accessibility/extensions/longdesc/options.html +++ /dev/null
@@ -1,11 +0,0 @@ -<!doctype html> -<html> -<body> - <h1>Options</h1> - <br> - <label> - <input type="checkbox" id="border">Add border to elements with aria-describedat or longdesc attributes. - </label> - <script src="options.js"></script> -</body> -</html>
diff --git a/ui/accessibility/extensions/longdesc/options.js b/ui/accessibility/extensions/longdesc/options.js deleted file mode 100644 index d90d32b..0000000 --- a/ui/accessibility/extensions/longdesc/options.js +++ /dev/null
@@ -1,30 +0,0 @@ -/* Copyright (c) 2014 The Chromium Authors. All rights reserved. - * Use of this source code is governed by a BSD-style license that can be - * found in the LICENSE file. */ - -// Saves options to chrome.storage -function save_options() { - var border = document.getElementById('border').checked; - chrome.storage.sync.set({ - addBorder: border - }, function() { - // Update status to let user know options were saved. - var status = document.getElementById('status'); - status.textContent = 'Options saved.'; - setTimeout(function() { - status.textContent = ''; - }, 750); - }); -} - -// Restores select box and checkbox state using the preferences -// stored in chrome.storage. -function restore_options() { - // Use default value addBOrder = false. - chrome.storage.sync.get("addBorder", function(item) { - document.getElementById('border').checked = item.addBorder; - }); -} - -document.addEventListener('DOMContentLoaded', restore_options); -document.getElementById('border').addEventListener('click', save_options);
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings.grd b/ui/accessibility/extensions/strings/accessibility_extensions_strings.grd deleted file mode 100644 index da94bea..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings.grd +++ /dev/null
@@ -1,252 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> - -<!-- Strings for all extensions. Each message should be named with the - name of the extension as a prefix, e.g. IDS_ALT_APP_NAME. --> - -<grit base_dir="." current_release="1" enc_check="möl" latest_public_release="0" source_lang_id="en"> - <outputs> - <output filename="_locales/am/messages.json" type="chrome_messages_json" lang="am"/> - <output filename="_locales/ar/messages.json" type="chrome_messages_json" lang="ar"/> - <output filename="_locales/bg/messages.json" type="chrome_messages_json" lang="bg"/> - <output filename="_locales/bn/messages.json" type="chrome_messages_json" lang="bn"/> - <output filename="_locales/ca/messages.json" type="chrome_messages_json" lang="ca"/> - <output filename="_locales/cs/messages.json" type="chrome_messages_json" lang="cs"/> - <output filename="_locales/da/messages.json" type="chrome_messages_json" lang="da"/> - <output filename="_locales/de/messages.json" type="chrome_messages_json" lang="de"/> - <output filename="_locales/el/messages.json" type="chrome_messages_json" lang="el"/> - <output filename="_locales/en_GB/messages.json" type="chrome_messages_json" lang="en-GB"/> - <output filename="_locales/en/messages.json" type="chrome_messages_json" lang="en"/> - <output filename="_locales/es/messages.json" type="chrome_messages_json" lang="es"/> - <output filename="_locales/es_419/messages.json" type="chrome_messages_json" lang="es-419"/> - <output filename="_locales/et/messages.json" type="chrome_messages_json" lang="et"/> - <output filename="_locales/fa/messages.json" type="chrome_messages_json" lang="fa"/> - <output filename="_locales/fi/messages.json" type="chrome_messages_json" lang="fi"/> - <output filename="_locales/fil/messages.json" type="chrome_messages_json" lang="fil"/> - <output filename="_locales/fr/messages.json" type="chrome_messages_json" lang="fr"/> - <output filename="_locales/gu/messages.json" type="chrome_messages_json" lang="gu"/> - <output filename="_locales/he/messages.json" type="chrome_messages_json" lang="he"/> - <output filename="_locales/hi/messages.json" type="chrome_messages_json" lang="hi"/> - <output filename="_locales/hr/messages.json" type="chrome_messages_json" lang="hr"/> - <output filename="_locales/hu/messages.json" type="chrome_messages_json" lang="hu"/> - <output filename="_locales/id/messages.json" type="chrome_messages_json" lang="id"/> - <output filename="_locales/it/messages.json" type="chrome_messages_json" lang="it"/> - <output filename="_locales/ja/messages.json" type="chrome_messages_json" lang="ja"/> - <output filename="_locales/kn/messages.json" type="chrome_messages_json" lang="kn"/> - <output filename="_locales/ko/messages.json" type="chrome_messages_json" lang="ko"/> - <output filename="_locales/lt/messages.json" type="chrome_messages_json" lang="lt"/> - <output filename="_locales/lv/messages.json" type="chrome_messages_json" lang="lv"/> - <output filename="_locales/ml/messages.json" type="chrome_messages_json" lang="ml"/> - <output filename="_locales/mr/messages.json" type="chrome_messages_json" lang="mr"/> - <output filename="_locales/ms/messages.json" type="chrome_messages_json" lang="ms"/> - <output filename="_locales/nl/messages.json" type="chrome_messages_json" lang="nl"/> - <output filename="_locales/nb/messages.json" type="chrome_messages_json" lang="no"/> - <output filename="_locales/pl/messages.json" type="chrome_messages_json" lang="pl"/> - <output filename="_locales/pt_BR/messages.json" type="chrome_messages_json" lang="pt-BR"/> - <output filename="_locales/pt_PT/messages.json" type="chrome_messages_json" lang="pt-PT"/> - <output filename="_locales/ro/messages.json" type="chrome_messages_json" lang="ro"/> - <output filename="_locales/ru/messages.json" type="chrome_messages_json" lang="ru"/> - <output filename="_locales/sk/messages.json" type="chrome_messages_json" lang="sk"/> - <output filename="_locales/sl/messages.json" type="chrome_messages_json" lang="sl"/> - <output filename="_locales/sr/messages.json" type="chrome_messages_json" lang="sr"/> - <output filename="_locales/sv/messages.json" type="chrome_messages_json" lang="sv"/> - <output filename="_locales/sw/messages.json" type="chrome_messages_json" lang="sw"/> - <output filename="_locales/ta/messages.json" type="chrome_messages_json" lang="ta"/> - <output filename="_locales/te/messages.json" type="chrome_messages_json" lang="te"/> - <output filename="_locales/th/messages.json" type="chrome_messages_json" lang="th"/> - <output filename="_locales/tr/messages.json" type="chrome_messages_json" lang="tr"/> - <output filename="_locales/uk/messages.json" type="chrome_messages_json" lang="uk"/> - <output filename="_locales/vi/messages.json" type="chrome_messages_json" lang="vi"/> - <output filename="_locales/zh_CN/messages.json" type="chrome_messages_json" lang="zh-CN"/> - <output filename="_locales/zh_TW/messages.json" type="chrome_messages_json" lang="zh-TW"/> - </outputs> - <translations> - <file path="accessibility_extensions_strings_am.xtb" lang="am" /> - <file path="accessibility_extensions_strings_ar.xtb" lang="ar" /> - <file path="accessibility_extensions_strings_bg.xtb" lang="bg" /> - <file path="accessibility_extensions_strings_bn.xtb" lang="bn" /> - <file path="accessibility_extensions_strings_ca.xtb" lang="ca" /> - <file path="accessibility_extensions_strings_cs.xtb" lang="cs" /> - <file path="accessibility_extensions_strings_da.xtb" lang="da" /> - <file path="accessibility_extensions_strings_de.xtb" lang="de" /> - <file path="accessibility_extensions_strings_el.xtb" lang="el" /> - <file path="accessibility_extensions_strings_en-GB.xtb" lang="en-GB" /> - <file path="accessibility_extensions_strings_es.xtb" lang="es" /> - <file path="accessibility_extensions_strings_es-419.xtb" lang="es-419" /> - <file path="accessibility_extensions_strings_et.xtb" lang="et" /> - <file path="accessibility_extensions_strings_fa.xtb" lang="fa" /> - <file path="accessibility_extensions_strings_fi.xtb" lang="fi" /> - <file path="accessibility_extensions_strings_fil.xtb" lang="fil" /> - <file path="accessibility_extensions_strings_fr.xtb" lang="fr" /> - <file path="accessibility_extensions_strings_gu.xtb" lang="gu" /> - <file path="accessibility_extensions_strings_hi.xtb" lang="hi" /> - <file path="accessibility_extensions_strings_hr.xtb" lang="hr" /> - <file path="accessibility_extensions_strings_hu.xtb" lang="hu" /> - <file path="accessibility_extensions_strings_id.xtb" lang="id" /> - <file path="accessibility_extensions_strings_it.xtb" lang="it" /> - <!-- The translation console uses 'iw' for Hebrew, but we use 'he'. --> - <file path="accessibility_extensions_strings_iw.xtb" lang="he" /> - <file path="accessibility_extensions_strings_ja.xtb" lang="ja" /> - <file path="accessibility_extensions_strings_kn.xtb" lang="kn" /> - <file path="accessibility_extensions_strings_ko.xtb" lang="ko" /> - <file path="accessibility_extensions_strings_lt.xtb" lang="lt" /> - <file path="accessibility_extensions_strings_lv.xtb" lang="lv" /> - <file path="accessibility_extensions_strings_ml.xtb" lang="ml" /> - <file path="accessibility_extensions_strings_mr.xtb" lang="mr" /> - <file path="accessibility_extensions_strings_ms.xtb" lang="ms" /> - <file path="accessibility_extensions_strings_nl.xtb" lang="nl" /> - <file path="accessibility_extensions_strings_no.xtb" lang="no" /> - <file path="accessibility_extensions_strings_pl.xtb" lang="pl" /> - <file path="accessibility_extensions_strings_pt-BR.xtb" lang="pt-BR" /> - <file path="accessibility_extensions_strings_pt-PT.xtb" lang="pt-PT" /> - <file path="accessibility_extensions_strings_ro.xtb" lang="ro" /> - <file path="accessibility_extensions_strings_ru.xtb" lang="ru" /> - <file path="accessibility_extensions_strings_sk.xtb" lang="sk" /> - <file path="accessibility_extensions_strings_sl.xtb" lang="sl" /> - <file path="accessibility_extensions_strings_sr.xtb" lang="sr" /> - <file path="accessibility_extensions_strings_sv.xtb" lang="sv" /> - <file path="accessibility_extensions_strings_sw.xtb" lang="sw" /> - <file path="accessibility_extensions_strings_ta.xtb" lang="ta" /> - <file path="accessibility_extensions_strings_te.xtb" lang="te" /> - <file path="accessibility_extensions_strings_th.xtb" lang="th" /> - <file path="accessibility_extensions_strings_tr.xtb" lang="tr" /> - <file path="accessibility_extensions_strings_uk.xtb" lang="uk" /> - <file path="accessibility_extensions_strings_vi.xtb" lang="vi" /> - <file path="accessibility_extensions_strings_zh-CN.xtb" lang="zh-CN" /> - <file path="accessibility_extensions_strings_zh-TW.xtb" lang="zh-TW" /> - </translations> - <release allow_pseudo="false" seq="1"> - <messages fallback_to_english="true"> - - <!-- Alt extension --> - - <message desc="The title of the application, displayed in the web store. Do not translate the word 'Alt', it refers to the ALT attribute in HTML. Okay to put it in quotes." name="IDS_ALT_APPNAME"> - Image Alt Text Viewer - </message> - <message desc="The description of the application, displayed in the web store." name="IDS_ALT_APPDESC"> - Replace images with their alt text. - </message> - - <!-- Long Descriptions in Context Menu extension --> - - <message desc="The title of the application, displayed in the web store." name="IDS_LONGDESC_APPNAME"> - Long Descriptions in Context Menu - </message> - <message desc="The description of the application, displayed in the web store." name="IDS_LONGDESC_APPDESC"> - Any HTML element with either a "longdesc" or "aria-describedat" attribute will get a thick vibrant border, and if you right-click on it, an option to view the long description is added to the context menu. - </message> - <message desc="Context menu item that opens the long description of an image in a new browser tab." name="IDS_LONGDESC_CONTEXT_MENU_ITEM"> - Open Long Description In New Tab - </message> - - <!-- High Contrast extension --> - - <message desc="The title of the application, displayed in the web store. The term High Contrast refers to contrast between dark and light colors - higher contrast is easier to see." name="IDS_HIGHCONTRAST_APPNAME"> - High Contrast - </message> - <message desc="The description of the application, displayed in the web store." name="IDS_HIGHCONTRAST_APPDESC"> - Change or invert the color scheme to make webpages easier to read. - </message> - - <message desc="Mode where the High Contrast extension does not modify the page, it displays it normally with no color correction." name="IDS_HIGHCONTRAST_MODE_NORMAL"> - Normal - </message> - <message desc="Mode where the High Contrast extension displays your web page with increased contrast (between dark and light color)." name="IDS_HIGHCONTRAST_INCREASED_CONTRAST"> - Increased Contrast - </message> - <message desc="Mode where the High Contrast extension displays your web page in grayscale, with no color." name="IDS_HIGHCONTRAST_GRAYSCALE"> - Grayscale - </message> - <message desc="Mode where the High Contrast extension displays your web page in inverted color - i.e. black becomes white, white becomes black." name="IDS_HIGHCONTRAST_INVERTED_COLOR"> - Inverted Color - </message> - <message desc="Mode where the High Contrast extension displays your web page in inverted grayscale - i.e. black becomes white, white becomes black, and color becomes gray." name="IDS_HIGHCONTRAST_INVERTED_GRAYSCALE"> - Inverted Grayscale - </message> - <message desc="Mode where the High Contrast extension displays your web page in only yellow on black, for maximum readability." name="IDS_HIGHCONTRAST_YELLOW_ON_BLACK"> - Yellow on Black - </message> - <message desc="Title of button that makes the current settings the default." name="IDS_HIGHCONTRAST_SETDEFAULT"> - Set as default scheme - </message> - <message desc="Title of button that tells the extension to forget any preferences for the current site and revert back to the defaults." name="IDS_HIGHCONTRAST_FORGET"> - Forget site customizations - </message> - <message desc="Message indicating the extension is currently enabled." name="IDS_HIGHCONTRAST_ENABLED"> - High Contrast is Enabled - </message> - <message desc="Message indicating the extension is currently disabled." name="IDS_HIGHCONTRAST_DISABLED"> - High Contrast is Disabled - </message> - <message desc="Title of button to enable the extension." name="IDS_HIGHCONTRAST_ENABLE"> - Enable - </message> - <message desc="Title of button to disable the extension." name="IDS_HIGHCONTRAST_DISABLE"> - Disable - </message> - <message desc="Control label that indicates the color scheme selected by the user will be the default." name="IDS_HIGHCONTRAST_DEFAULT"> - Default color scheme: - </message> - <message desc="Control label that indicates the color scheme selected by the user will apply only to the specified web site." name="IDS_HIGHCONTRAST_"> - Color scheme for <ph name="site">$1<ex>facebook.com</ex></ph>: - </message> - - <!-- Caret browsing extension --> - - <message desc="One of several possible options for what to do when the cursor first appears - this option is to show a quick animation." name="IDS_CARET_BROWSING_ANIMATION"> - Highlight the cursor position with an animation. - </message> - <message desc="The description of the application, displayed in the web store." name="IDS_CARET_BROWSING_APPDESC"> - Browse the text of web pages using arrow keys. - </message> - <message desc="The title of the application, displayed in the web store." name="IDS_CARET_BROWSING_APPNAME"> - Caret Browsing - </message> - <message desc="The title of the options page." name="IDS_CARET_BROWSING_CARETBROWSINGOPTIONS"> - Caret Browsing Options - </message> - <message desc="Instructions for how to enable or disable this feature on a Chromebook, where you have to hold Alt and press the special Increase Brightness key on the top of the keyboard, or F7 if you're using an alternate keyboard." name="IDS_CARET_BROWSING_ENABLEDISABLECROS"> - Press <span class='key'>Alt</span> + <img src='increase_brightness.png'> (the Increase Brightness key, or F7) to turn on Caret Browsing. Press it again to turn it off. - </message> - <message desc="Instructions for how to enable or disable this feature on any platform other than Chrome OS." name="IDS_CARET_BROWSING_ENABLEDISABLENONCROS"> - Press <span class='key'>F7</span> to turn on Caret Browsing. Press it again to turn it off. - </message> - <message desc="One of several possible options for what to do when the cursor first appears - this option is to flash something quickly." name="IDS_CARET_BROWSING_FLASH"> - Highlight the cursor position with a quick flash. - </message> - <message desc="A description of how to use the caret browsing feature to navigate between focusable controls like text fields." name="IDS_CARET_BROWSING_FOCUSHELP"> - <p>When you reach a link or control, it is automatically focused. Press <span class='key'>Enter</span> to click a link or button. </p> <p> When a focused control (like a text box or a list box) is capturing arrow keys, press <span class='key'>Esc</span> followed by the left or right arrow to continue Caret Browsing. </p> <p> Alternatively, press <span class='key'>Tab</span> to move to the next focusable control. </p> - </message> - <message desc="Subheading in the options page where the user chooses what to show visually when the cursor jumps from one part of the page to another part that's far away." name="IDS_CARET_BROWSING_JUMP"> - When the caret jumps by a large distance: - </message> - <message desc="Title of the heading on the page that describes keyboard commands." name="IDS_CARET_BROWSING_KEYBOARDCOMMANDS"> - Keyboard Commands - </message> - <message desc="Text that describes how to move by words using the Option key on a Mac keyboard." name="IDS_CARET_BROWSING_MOVEBYWORDSMAC"> - Hold down <span class='key'>Option</span> to move by words. - </message> - <message desc="Text that describes how to move by words using the Control key. This string is used on all platforms other than Mac." name="IDS_CARET_BROWSING_MOVEBYWORDSNONMAC"> - Hold down <span class='key'>Control</span> to move by words. - </message> - <message desc="A description of how to use the caret browsing feature." name="IDS_CARET_BROWSING_NAVHELP"> - <p>Use arrow keys to move throughout the document. </p><p>Click anywhere to move the cursor to that location. </p> <p> Press <span class='key'>Shift</span> + arrows to select text.</p> - </message> - <message desc="One of several possible options for what to do when the cursor first appears - this option is to do nothing." name="IDS_CARET_BROWSING_NOFEEDBACK"> - No feedback, just show the cursor. - </message> - <message desc="Text at the top of the options page explaining the extension." name="IDS_CARET_BROWSING_SUBHEADING1"> - This extension gives you a movable cursor in the web page, allowing you to select text with the keyboard. - </message> - <message desc="More text at the top of the options page, explaining that Caret Browsing (the name of this extension) is enabled on this page and the user can try it." name="IDS_CARET_BROWSING_SUBHEADING2"> - Try it out now - Caret Browsing is always enabled on this page! - </message> - <message desc="Heading text for the part of the options page that lets the user choose options for how the caret is shown visually." name="IDS_CARET_BROWSING_VISUALFEEDBACK"> - Visual Feedback - </message> - <message desc="Subheading in the options page where the user chooses what to show visually when this feature (Caret Browsing) is enabled." name="IDS_CARET_BROWSING_WHENENABLED"> - When Caret Browsing is enabled: - </message> - - </messages> - </release> -</grit>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_am.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_am.xtb deleted file mode 100644 index 6c985cb8..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_am.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="am"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_ar.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_ar.xtb deleted file mode 100644 index e8b5562..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_ar.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="ar"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_bg.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_bg.xtb deleted file mode 100644 index ebab473..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_bg.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="bg"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_bn.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_bn.xtb deleted file mode 100644 index e77d333..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_bn.xtb +++ /dev/null
@@ -1,3 +0,0 @@ -<?xml version="1.0" ?> -<translationbundle lang="bn"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_ca.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_ca.xtb deleted file mode 100644 index 1438d89..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_ca.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="ca"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_cs.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_cs.xtb deleted file mode 100644 index 2d95130..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_cs.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="cs"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_da.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_da.xtb deleted file mode 100644 index 751fa4a..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_da.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="da"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_de.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_de.xtb deleted file mode 100644 index 91de7f5..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_de.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="de"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_el.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_el.xtb deleted file mode 100644 index 6e5e7d8..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_el.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="el"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_en-GB.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_en-GB.xtb deleted file mode 100644 index 0fb2133..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_en-GB.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="en-GB"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_es-419.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_es-419.xtb deleted file mode 100644 index 2fe4770..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_es-419.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="es-419"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_es.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_es.xtb deleted file mode 100644 index 64022ec..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_es.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="es"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_et.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_et.xtb deleted file mode 100644 index 5244dfd..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_et.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="et"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_fa.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_fa.xtb deleted file mode 100644 index 18626f8..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_fa.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="fa"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_fi.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_fi.xtb deleted file mode 100644 index 4691cd5..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_fi.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="fi"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_fil.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_fil.xtb deleted file mode 100644 index 443630e..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_fil.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="fil"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_fr.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_fr.xtb deleted file mode 100644 index 63026a3..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_fr.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="fr"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_gu.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_gu.xtb deleted file mode 100644 index 7d8a4df..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_gu.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="gu"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_hi.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_hi.xtb deleted file mode 100644 index a6ddd5d..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_hi.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="hi"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_hr.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_hr.xtb deleted file mode 100644 index 26f99d0..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_hr.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="hr"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_hu.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_hu.xtb deleted file mode 100644 index 7ef9a5e..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_hu.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="hu"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_id.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_id.xtb deleted file mode 100644 index aa34783..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_id.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="id"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_it.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_it.xtb deleted file mode 100644 index a6ac8d4..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_it.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="it"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_iw.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_iw.xtb deleted file mode 100644 index 86b5533..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_iw.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="iw"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_ja.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_ja.xtb deleted file mode 100644 index 23139e6..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_ja.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="ja"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_kn.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_kn.xtb deleted file mode 100644 index cc3643a..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_kn.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="kn"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_ko.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_ko.xtb deleted file mode 100644 index e0fc370..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_ko.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="ko"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_lt.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_lt.xtb deleted file mode 100644 index 5804ae2..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_lt.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="lt"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_lv.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_lv.xtb deleted file mode 100644 index a0a1c47..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_lv.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="lv"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_ml.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_ml.xtb deleted file mode 100644 index f7db315..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_ml.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="ml"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_mr.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_mr.xtb deleted file mode 100644 index 098d29c..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_mr.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="mr"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_ms.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_ms.xtb deleted file mode 100644 index 1fb470a..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_ms.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="ms"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_nl.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_nl.xtb deleted file mode 100644 index e782410..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_nl.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="nl"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_no.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_no.xtb deleted file mode 100644 index 913638b..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_no.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="no"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_pl.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_pl.xtb deleted file mode 100644 index 4519e3d..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_pl.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="pl"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_pt-BR.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_pt-BR.xtb deleted file mode 100644 index e95eb56..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_pt-BR.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="pt-BR"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_pt-PT.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_pt-PT.xtb deleted file mode 100644 index 1dcf557..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_pt-PT.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="pt-PT"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_ro.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_ro.xtb deleted file mode 100644 index 9e43493..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_ro.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="ro"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_ru.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_ru.xtb deleted file mode 100644 index c4a621b..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_ru.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="ru"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_sk.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_sk.xtb deleted file mode 100644 index 00750d3..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_sk.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="sk"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_sl.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_sl.xtb deleted file mode 100644 index 489b7e4..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_sl.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="sl"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_sr.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_sr.xtb deleted file mode 100644 index 38f6f35..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_sr.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="sr"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_sv.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_sv.xtb deleted file mode 100644 index ddea3dc..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_sv.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="sv"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_sw.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_sw.xtb deleted file mode 100644 index b775088..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_sw.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="sw"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_ta.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_ta.xtb deleted file mode 100644 index ef90687..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_ta.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="ta"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_te.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_te.xtb deleted file mode 100644 index 48c714b..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_te.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="te"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_th.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_th.xtb deleted file mode 100644 index fae3196..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_th.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="th"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_tr.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_tr.xtb deleted file mode 100644 index 9a29951..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_tr.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="tr"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_uk.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_uk.xtb deleted file mode 100644 index f0db52c..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_uk.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="uk"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_vi.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_vi.xtb deleted file mode 100644 index b2957da..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_vi.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="vi"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_zh-CN.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_zh-CN.xtb deleted file mode 100644 index 26e8b40..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_zh-CN.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="zh-CN"> -</translationbundle>
diff --git a/ui/accessibility/extensions/strings/accessibility_extensions_strings_zh-TW.xtb b/ui/accessibility/extensions/strings/accessibility_extensions_strings_zh-TW.xtb deleted file mode 100644 index 935ef48..0000000 --- a/ui/accessibility/extensions/strings/accessibility_extensions_strings_zh-TW.xtb +++ /dev/null
@@ -1,4 +0,0 @@ -<?xml version="1.0" ?> -<!DOCTYPE translationbundle> -<translationbundle lang="zh-TW"> -</translationbundle>
diff --git a/ui/accessibility/platform/ax_platform_node.cc b/ui/accessibility/platform/ax_platform_node.cc deleted file mode 100644 index 37b8ef4..0000000 --- a/ui/accessibility/platform/ax_platform_node.cc +++ /dev/null
@@ -1,25 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/accessibility/platform/ax_platform_node.h" - -#include "ui/accessibility/ax_node_data.h" -#include "ui/accessibility/platform/ax_platform_node_delegate.h" - -namespace ui { - -#if !defined(OS_MACOSX) -// static -AXPlatformNode* AXPlatformNode::Create(AXPlatformNodeDelegate* delegate) { - return NULL; -} -#endif - -AXPlatformNode::AXPlatformNode() { -} - -AXPlatformNode::~AXPlatformNode() { -} - -} // namespace ui
diff --git a/ui/accessibility/platform/ax_platform_node.h b/ui/accessibility/platform/ax_platform_node.h deleted file mode 100644 index 10ecba2..0000000 --- a/ui/accessibility/platform/ax_platform_node.h +++ /dev/null
@@ -1,33 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_H_ -#define UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_H_ - -#include "ui/accessibility/ax_export.h" -#include "ui/gfx/native_widget_types.h" - -namespace ui { - -class AXPlatformNodeDelegate; - -class AX_EXPORT AXPlatformNode { - public: - // Create a platform appropriate instance. - static AXPlatformNode* Create(AXPlatformNodeDelegate* delegate); - - // Call Destroy rather than deleting this, because the subclass may - // use reference counting. - virtual void Destroy() = 0; - - virtual gfx::NativeViewAccessible GetNativeViewAccessible() = 0; - - protected: - AXPlatformNode(); - virtual ~AXPlatformNode(); -}; - -} // namespace ui - -#endif // UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_H_
diff --git a/ui/accessibility/platform/ax_platform_node_base.cc b/ui/accessibility/platform/ax_platform_node_base.cc deleted file mode 100644 index 3479af1..0000000 --- a/ui/accessibility/platform/ax_platform_node_base.cc +++ /dev/null
@@ -1,58 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/accessibility/platform/ax_platform_node_base.h" - -#include "ui/accessibility/ax_node_data.h" -#include "ui/accessibility/platform/ax_platform_node_delegate.h" - -namespace ui { - -AXPlatformNodeBase::AXPlatformNodeBase() { -} - -AXPlatformNodeBase::~AXPlatformNodeBase() { -} - -void AXPlatformNodeBase::Init(AXPlatformNodeDelegate* delegate) { - delegate_ = delegate; -} - -AXRole AXPlatformNodeBase::GetRole() const { - return delegate_ ? delegate_->GetData()->role : AX_ROLE_UNKNOWN; -} - -gfx::Rect AXPlatformNodeBase::GetBoundsInScreen() const { - if (!delegate_) - return gfx::Rect(); - gfx::Rect bounds = delegate_->GetData()->location; - bounds.Offset(delegate_->GetGlobalCoordinateOffset()); - return bounds; -} - -gfx::NativeViewAccessible AXPlatformNodeBase::GetParent() { - return delegate_ ? delegate_->GetParent() : NULL; -} - -int AXPlatformNodeBase::GetChildCount() { - return delegate_ ? delegate_->GetChildCount() : 0; -} - -gfx::NativeViewAccessible AXPlatformNodeBase::ChildAtIndex(int index) { - return delegate_ ? delegate_->ChildAtIndex(index) : NULL; -} - -// AXPlatformNode - -void AXPlatformNodeBase::Destroy() { - delegate_ = NULL; - delete this; -} - -gfx::NativeViewAccessible AXPlatformNodeBase::GetNativeViewAccessible() { - return NULL; -} - - -} // namespace ui
diff --git a/ui/accessibility/platform/ax_platform_node_base.h b/ui/accessibility/platform/ax_platform_node_base.h deleted file mode 100644 index fcc0f5c..0000000 --- a/ui/accessibility/platform/ax_platform_node_base.h +++ /dev/null
@@ -1,44 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_BASE_H_ -#define UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_BASE_H_ - -#include "ui/accessibility/ax_enums.h" -#include "ui/accessibility/platform/ax_platform_node.h" -#include "ui/gfx/geometry/rect.h" -#include "ui/gfx/native_widget_types.h" - -namespace ui { - -class AXPlatformNodeDelegate; - -class AXPlatformNodeBase : public AXPlatformNode { - public: - virtual void Init(AXPlatformNodeDelegate* delegate); - - // These are simple wrappers to our delegate. - AXRole GetRole() const; - gfx::Rect GetBoundsInScreen() const; - gfx::NativeViewAccessible GetParent(); - int GetChildCount(); - gfx::NativeViewAccessible ChildAtIndex(int index); - - // AXPlatformNode - void Destroy() override; - gfx::NativeViewAccessible GetNativeViewAccessible() override; - - protected: - AXPlatformNodeBase(); - ~AXPlatformNodeBase() override; - - AXPlatformNodeDelegate* delegate_; // Weak. Owns this. - - private: - DISALLOW_COPY_AND_ASSIGN(AXPlatformNodeBase); -}; - -} // namespace ui - -#endif // UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_BASE_H_
diff --git a/ui/accessibility/platform/ax_platform_node_delegate.h b/ui/accessibility/platform/ax_platform_node_delegate.h deleted file mode 100644 index 9af5c4d..0000000 --- a/ui/accessibility/platform/ax_platform_node_delegate.h +++ /dev/null
@@ -1,44 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_DELEGATE_H_ -#define UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_DELEGATE_H_ - -#include "ui/accessibility/ax_enums.h" -#include "ui/accessibility/ax_export.h" -#include "ui/gfx/geometry/vector2d.h" -#include "ui/gfx/native_widget_types.h" - -namespace ui { - -struct AXNodeData; -class AXPlatformNode; - -class AX_EXPORT AXPlatformNodeDelegate { - public: - // Get the accessibility data that should be exposed for this node. - virtual AXNodeData* GetData() = 0; - - // Get the parent of the node unless it's the root, then it returns NULL. - virtual gfx::NativeViewAccessible GetParent() = 0; - - // Get the number of children of this node. - virtual int GetChildCount() = 0; - - // Get the child of a node from [0...GetChildCount() - 1] - virtual gfx::NativeViewAccessible ChildAtIndex(int index) = 0; - - // Get the offset to convert local coordinates to screen global coordinates. - virtual gfx::Vector2d GetGlobalCoordinateOffset() = 0; - - // - // Events. - // - virtual void NotifyAccessibilityEvent(ui::AXEvent event_type) = 0; - -}; - -} // namespace ui - -#endif // UI_ACCESSIBILITY_PLATFORM_AX_PLATFORM_NODE_DELEGATE_H_
diff --git a/ui/accessibility/platform/ax_platform_node_mac.h b/ui/accessibility/platform/ax_platform_node_mac.h deleted file mode 100644 index f39a94d..0000000 --- a/ui/accessibility/platform/ax_platform_node_mac.h +++ /dev/null
@@ -1,50 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_ACCESSIBILITY_AX_PLATFORM_NODE_MAC_H_ -#define UI_ACCESSIBILITY_AX_PLATFORM_NODE_MAC_H_ - -#include "base/mac/scoped_nsobject.h" -#include "ui/accessibility/ax_export.h" -#include "ui/accessibility/platform/ax_platform_node_base.h" - -@class AXPlatformNodeCocoa; - -namespace ui { - -class AXPlatformNodeMac : public AXPlatformNodeBase { - public: - AXPlatformNodeMac(); - - // AXPlatformNode. - void Destroy() override; - gfx::NativeViewAccessible GetNativeViewAccessible() override; - - private: - ~AXPlatformNodeMac() override; - - base::scoped_nsobject<AXPlatformNodeCocoa> native_node_; - - DISALLOW_COPY_AND_ASSIGN(AXPlatformNodeMac); -}; - -} // namespace ui - -AX_EXPORT -@interface AXPlatformNodeCocoa : NSObject { - @private - ui::AXPlatformNodeBase* node_; // Weak. Retains us. -} - -+ (NSString*)nativeRoleFromAXRole:(ui::AXRole)role; -+ (NSString*)nativeSubroleFromAXRole:(ui::AXRole)role; - -- (instancetype)initWithNode:(ui::AXPlatformNodeBase*)node; -- (void)detach; - -@property(nonatomic, readonly) NSRect boundsInScreen; - -@end - -#endif // UI_ACCESSIBILITY_AX_PLATFORM_NODE_MAC_H_
diff --git a/ui/accessibility/platform/ax_platform_node_mac.mm b/ui/accessibility/platform/ax_platform_node_mac.mm deleted file mode 100644 index 2b450ea..0000000 --- a/ui/accessibility/platform/ax_platform_node_mac.mm +++ /dev/null
@@ -1,319 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#import "ui/accessibility/platform/ax_platform_node_mac.h" - -#import <Cocoa/Cocoa.h> - -#include "base/strings/sys_string_conversions.h" -#import "ui/accessibility/platform/ax_platform_node_delegate.h" -#import "ui/gfx/mac/coordinate_conversion.h" - -namespace { - -struct MapEntry { - ui::AXRole value; - NSString* nativeValue; -}; - -typedef std::map<ui::AXRole, NSString*> RoleMap; - -RoleMap BuildRoleMap() { - const MapEntry roles[] = { - {ui::AX_ROLE_ALERT, NSAccessibilityGroupRole}, - {ui::AX_ROLE_ALERT_DIALOG, NSAccessibilityGroupRole}, - {ui::AX_ROLE_ANNOTATION, NSAccessibilityUnknownRole}, - {ui::AX_ROLE_APPLICATION, NSAccessibilityGroupRole}, - {ui::AX_ROLE_ARTICLE, NSAccessibilityGroupRole}, - {ui::AX_ROLE_BANNER, NSAccessibilityGroupRole}, - {ui::AX_ROLE_BROWSER, NSAccessibilityBrowserRole}, - {ui::AX_ROLE_BUSY_INDICATOR, NSAccessibilityBusyIndicatorRole}, - {ui::AX_ROLE_BUTTON, NSAccessibilityButtonRole}, - {ui::AX_ROLE_CANVAS, NSAccessibilityImageRole}, - {ui::AX_ROLE_CELL, @"AXCell"}, - {ui::AX_ROLE_CHECK_BOX, NSAccessibilityCheckBoxRole}, - {ui::AX_ROLE_COLOR_WELL, NSAccessibilityColorWellRole}, - {ui::AX_ROLE_COLUMN, NSAccessibilityColumnRole}, - {ui::AX_ROLE_COLUMN_HEADER, @"AXCell"}, - {ui::AX_ROLE_COMBO_BOX, NSAccessibilityComboBoxRole}, - {ui::AX_ROLE_COMPLEMENTARY, NSAccessibilityGroupRole}, - {ui::AX_ROLE_CONTENT_INFO, NSAccessibilityGroupRole}, - {ui::AX_ROLE_DEFINITION, NSAccessibilityGroupRole}, - {ui::AX_ROLE_DESCRIPTION_LIST_DETAIL, NSAccessibilityGroupRole}, - {ui::AX_ROLE_DESCRIPTION_LIST, NSAccessibilityListRole}, - {ui::AX_ROLE_DESCRIPTION_LIST_TERM, NSAccessibilityGroupRole}, - {ui::AX_ROLE_DIALOG, NSAccessibilityGroupRole}, - {ui::AX_ROLE_DETAILS, NSAccessibilityGroupRole}, - {ui::AX_ROLE_DIRECTORY, NSAccessibilityListRole}, - {ui::AX_ROLE_DISCLOSURE_TRIANGLE, NSAccessibilityDisclosureTriangleRole}, - {ui::AX_ROLE_DIV, NSAccessibilityGroupRole}, - {ui::AX_ROLE_DOCUMENT, NSAccessibilityGroupRole}, - {ui::AX_ROLE_DRAWER, NSAccessibilityDrawerRole}, - {ui::AX_ROLE_EDITABLE_TEXT, NSAccessibilityTextFieldRole}, - {ui::AX_ROLE_FIGCAPTION, NSAccessibilityGroupRole}, - {ui::AX_ROLE_FIGURE, NSAccessibilityGroupRole}, - {ui::AX_ROLE_FOOTER, NSAccessibilityGroupRole}, - {ui::AX_ROLE_FORM, NSAccessibilityGroupRole}, - {ui::AX_ROLE_GRID, NSAccessibilityGridRole}, - {ui::AX_ROLE_GROUP, NSAccessibilityGroupRole}, - {ui::AX_ROLE_GROW_AREA, NSAccessibilityGrowAreaRole}, - {ui::AX_ROLE_HEADING, @"AXHeading"}, - {ui::AX_ROLE_HELP_TAG, NSAccessibilityHelpTagRole}, - {ui::AX_ROLE_HORIZONTAL_RULE, NSAccessibilityGroupRole}, - {ui::AX_ROLE_IFRAME, NSAccessibilityGroupRole}, - {ui::AX_ROLE_IGNORED, NSAccessibilityUnknownRole}, - {ui::AX_ROLE_IMAGE, NSAccessibilityImageRole}, - {ui::AX_ROLE_IMAGE_MAP, NSAccessibilityGroupRole}, - {ui::AX_ROLE_IMAGE_MAP_LINK, NSAccessibilityLinkRole}, - {ui::AX_ROLE_INCREMENTOR, NSAccessibilityIncrementorRole}, - {ui::AX_ROLE_LABEL_TEXT, NSAccessibilityGroupRole}, - {ui::AX_ROLE_LINK, NSAccessibilityLinkRole}, - {ui::AX_ROLE_LIST, NSAccessibilityListRole}, - {ui::AX_ROLE_LIST_BOX, NSAccessibilityListRole}, - {ui::AX_ROLE_LIST_BOX_OPTION, NSAccessibilityStaticTextRole}, - {ui::AX_ROLE_LIST_ITEM, NSAccessibilityGroupRole}, - {ui::AX_ROLE_LIST_MARKER, @"AXListMarker"}, - {ui::AX_ROLE_LOG, NSAccessibilityGroupRole}, - {ui::AX_ROLE_MAIN, NSAccessibilityGroupRole}, - {ui::AX_ROLE_MARQUEE, NSAccessibilityGroupRole}, - {ui::AX_ROLE_MATH, NSAccessibilityGroupRole}, - {ui::AX_ROLE_MATTE, NSAccessibilityMatteRole}, - {ui::AX_ROLE_MENU, NSAccessibilityMenuRole}, - {ui::AX_ROLE_MENU_BAR, NSAccessibilityMenuBarRole}, - {ui::AX_ROLE_MENU_BUTTON, NSAccessibilityButtonRole}, - {ui::AX_ROLE_MENU_ITEM, NSAccessibilityMenuItemRole}, - {ui::AX_ROLE_MENU_ITEM_CHECK_BOX, NSAccessibilityMenuItemRole}, - {ui::AX_ROLE_MENU_ITEM_RADIO, NSAccessibilityMenuItemRole}, - {ui::AX_ROLE_MENU_LIST_OPTION, NSAccessibilityMenuItemRole}, - {ui::AX_ROLE_MENU_LIST_POPUP, NSAccessibilityUnknownRole}, - {ui::AX_ROLE_METER, NSAccessibilityProgressIndicatorRole}, - {ui::AX_ROLE_NAVIGATION, NSAccessibilityGroupRole}, - {ui::AX_ROLE_NONE, NSAccessibilityGroupRole}, - {ui::AX_ROLE_NOTE, NSAccessibilityGroupRole}, - {ui::AX_ROLE_OUTLINE, NSAccessibilityOutlineRole}, - {ui::AX_ROLE_PARAGRAPH, NSAccessibilityGroupRole}, - {ui::AX_ROLE_POP_UP_BUTTON, NSAccessibilityPopUpButtonRole}, - {ui::AX_ROLE_PRESENTATIONAL, NSAccessibilityGroupRole}, - {ui::AX_ROLE_PROGRESS_INDICATOR, NSAccessibilityProgressIndicatorRole}, - {ui::AX_ROLE_RADIO_BUTTON, NSAccessibilityRadioButtonRole}, - {ui::AX_ROLE_RADIO_GROUP, NSAccessibilityRadioGroupRole}, - {ui::AX_ROLE_REGION, NSAccessibilityGroupRole}, - {ui::AX_ROLE_ROOT_WEB_AREA, @"AXWebArea"}, - {ui::AX_ROLE_ROW, NSAccessibilityRowRole}, - {ui::AX_ROLE_ROW_HEADER, @"AXCell"}, - {ui::AX_ROLE_RULER, NSAccessibilityRulerRole}, - {ui::AX_ROLE_RULER_MARKER, NSAccessibilityRulerMarkerRole}, - {ui::AX_ROLE_SCROLL_BAR, NSAccessibilityScrollBarRole}, - {ui::AX_ROLE_SEARCH, NSAccessibilityGroupRole}, - {ui::AX_ROLE_SHEET, NSAccessibilitySheetRole}, - {ui::AX_ROLE_SLIDER, NSAccessibilitySliderRole}, - {ui::AX_ROLE_SLIDER_THUMB, NSAccessibilityValueIndicatorRole}, - {ui::AX_ROLE_SPIN_BUTTON, NSAccessibilitySliderRole}, - {ui::AX_ROLE_SPLITTER, NSAccessibilitySplitterRole}, - {ui::AX_ROLE_SPLIT_GROUP, NSAccessibilitySplitGroupRole}, - {ui::AX_ROLE_STATIC_TEXT, NSAccessibilityStaticTextRole}, - {ui::AX_ROLE_STATUS, NSAccessibilityGroupRole}, - {ui::AX_ROLE_SVG_ROOT, NSAccessibilityGroupRole}, - {ui::AX_ROLE_SYSTEM_WIDE, NSAccessibilityUnknownRole}, - {ui::AX_ROLE_TAB, NSAccessibilityRadioButtonRole}, - {ui::AX_ROLE_TABLE, NSAccessibilityTableRole}, - {ui::AX_ROLE_TABLE_HEADER_CONTAINER, NSAccessibilityGroupRole}, - {ui::AX_ROLE_TAB_LIST, NSAccessibilityTabGroupRole}, - {ui::AX_ROLE_TAB_PANEL, NSAccessibilityGroupRole}, - {ui::AX_ROLE_TEXT_AREA, NSAccessibilityTextAreaRole}, - {ui::AX_ROLE_TEXT_FIELD, NSAccessibilityTextFieldRole}, - {ui::AX_ROLE_TIMER, NSAccessibilityGroupRole}, - {ui::AX_ROLE_TOGGLE_BUTTON, NSAccessibilityCheckBoxRole}, - {ui::AX_ROLE_TOOLBAR, NSAccessibilityToolbarRole}, - {ui::AX_ROLE_TOOLTIP, NSAccessibilityGroupRole}, - {ui::AX_ROLE_TREE, NSAccessibilityOutlineRole}, - {ui::AX_ROLE_TREE_GRID, NSAccessibilityTableRole}, - {ui::AX_ROLE_TREE_ITEM, NSAccessibilityRowRole}, - {ui::AX_ROLE_VALUE_INDICATOR, NSAccessibilityValueIndicatorRole}, - {ui::AX_ROLE_WEB_AREA, @"AXWebArea"}, - {ui::AX_ROLE_WINDOW, NSAccessibilityWindowRole}, - - // TODO(dtseng): we don't correctly support the attributes for these - // roles. - // { ui::AX_ROLE_SCROLL_AREA, NSAccessibilityScrollAreaRole }, - }; - - RoleMap role_map; - for (size_t i = 0; i < arraysize(roles); ++i) - role_map[roles[i].value] = roles[i].nativeValue; - return role_map; -} - -RoleMap BuildSubroleMap() { - const MapEntry subroles[] = { - {ui::AX_ROLE_ALERT, @"AXApplicationAlert"}, - {ui::AX_ROLE_ALERT_DIALOG, @"AXApplicationAlertDialog"}, - {ui::AX_ROLE_ARTICLE, @"AXDocumentArticle"}, - {ui::AX_ROLE_DEFINITION, @"AXDefinition"}, - {ui::AX_ROLE_DESCRIPTION_LIST_DETAIL, @"AXDescription"}, - {ui::AX_ROLE_DESCRIPTION_LIST_TERM, @"AXTerm"}, - {ui::AX_ROLE_DIALOG, @"AXApplicationDialog"}, - {ui::AX_ROLE_DOCUMENT, @"AXDocument"}, - {ui::AX_ROLE_FOOTER, @"AXLandmarkContentInfo"}, - {ui::AX_ROLE_APPLICATION, @"AXLandmarkApplication"}, - {ui::AX_ROLE_BANNER, @"AXLandmarkBanner"}, - {ui::AX_ROLE_COMPLEMENTARY, @"AXLandmarkComplementary"}, - {ui::AX_ROLE_CONTENT_INFO, @"AXLandmarkContentInfo"}, - {ui::AX_ROLE_MAIN, @"AXLandmarkMain"}, - {ui::AX_ROLE_NAVIGATION, @"AXLandmarkNavigation"}, - {ui::AX_ROLE_SEARCH, @"AXLandmarkSearch"}, - {ui::AX_ROLE_LOG, @"AXApplicationLog"}, - {ui::AX_ROLE_MARQUEE, @"AXApplicationMarquee"}, - {ui::AX_ROLE_MATH, @"AXDocumentMath"}, - {ui::AX_ROLE_NOTE, @"AXDocumentNote"}, - {ui::AX_ROLE_REGION, @"AXDocumentRegion"}, - {ui::AX_ROLE_STATUS, @"AXApplicationStatus"}, - {ui::AX_ROLE_TAB_PANEL, @"AXTabPanel"}, - {ui::AX_ROLE_TIMER, @"AXApplicationTimer"}, - {ui::AX_ROLE_TOGGLE_BUTTON, @"AXToggleButton"}, - {ui::AX_ROLE_TOOLTIP, @"AXUserInterfaceTooltip"}, - {ui::AX_ROLE_TREE_ITEM, NSAccessibilityOutlineRowSubrole}, - }; - - RoleMap subrole_map; - for (size_t i = 0; i < arraysize(subroles); ++i) - subrole_map[subroles[i].value] = subroles[i].nativeValue; - return subrole_map; -} - -} // namespace - -@implementation AXPlatformNodeCocoa - -// A mapping of AX roles to native roles. -+ (NSString*)nativeRoleFromAXRole:(ui::AXRole)role { - CR_DEFINE_STATIC_LOCAL(RoleMap, role_map, (BuildRoleMap())); - RoleMap::iterator it = role_map.find(role); - return it != role_map.end() ? it->second : NSAccessibilityUnknownRole; -} - -// A mapping of AX roles to native subroles. -+ (NSString*)nativeSubroleFromAXRole:(ui::AXRole)role { - CR_DEFINE_STATIC_LOCAL(RoleMap, subrole_map, (BuildSubroleMap())); - RoleMap::iterator it = subrole_map.find(role); - return it != subrole_map.end() ? it->second : nil; -} - -- (instancetype)initWithNode:(ui::AXPlatformNodeBase*)node { - if ((self = [super init])) { - node_ = node; - } - return self; -} - -- (void)detach { - node_ = nil; -} - -- (NSRect)boundsInScreen { - if (!node_) - return NSZeroRect; - return gfx::ScreenRectToNSRect(node_->GetBoundsInScreen()); -} - -- (NSArray*)AXChildren { - if (!node_) - return nil; - int count = node_->GetChildCount(); - NSMutableArray* children = [NSMutableArray arrayWithCapacity:count]; - for (int i = 0; i < count; ++i) - [children addObject:node_->ChildAtIndex(i)]; - return NSAccessibilityUnignoredChildren(children); -} - -- (id)AXParent { - if (!node_) - return nil; - return NSAccessibilityUnignoredAncestor(node_->GetParent()); -} - -- (NSValue*)AXPosition { - return [NSValue valueWithPoint:self.boundsInScreen.origin]; -} - -- (NSString*)AXRole { - if (!node_) - return nil; - return [[self class] nativeRoleFromAXRole:node_->GetRole()]; -} - -- (NSValue*)AXSize { - return [NSValue valueWithSize:self.boundsInScreen.size]; -} - -// NSAccessibility informal protocol implementation. - -- (BOOL)accessibilityIsIgnored { - return [[self AXRole] isEqualToString:NSAccessibilityUnknownRole]; -} - -- (id)accessibilityHitTest:(NSPoint)point { - for (AXPlatformNodeCocoa* child in [self AXChildren]) { - if (NSPointInRect(point, child.boundsInScreen)) - return [child accessibilityHitTest:point]; - } - return NSAccessibilityUnignoredAncestor(self); -} - -- (NSArray*)accessibilityActionNames { - return nil; -} - -- (NSArray*)accessibilityAttributeNames { - return @[ - NSAccessibilityChildrenAttribute, - NSAccessibilityParentAttribute, - NSAccessibilityPositionAttribute, - NSAccessibilityRoleAttribute, - NSAccessibilitySizeAttribute, - ]; -} - -- (BOOL)accessibilityIsAttributeSettable:(NSString*)attribute { - return NO; -} - -- (id)accessibilityAttributeValue:(NSString*)attribute { - SEL selector = NSSelectorFromString(attribute); - if ([self respondsToSelector:selector]) - return [self performSelector:selector]; - return nil; -} - -@end - -namespace ui { - -// static -AXPlatformNode* AXPlatformNode::Create(AXPlatformNodeDelegate* delegate) { - AXPlatformNodeBase* node = new AXPlatformNodeMac(); - node->Init(delegate); - return node; -} - -AXPlatformNodeMac::AXPlatformNodeMac() { -} - -AXPlatformNodeMac::~AXPlatformNodeMac() { -} - -void AXPlatformNodeMac::Destroy() { - if (native_node_) - [native_node_ detach]; - delegate_ = NULL; - delete this; -} - -gfx::NativeViewAccessible AXPlatformNodeMac::GetNativeViewAccessible() { - if (!native_node_) - native_node_.reset([[AXPlatformNodeCocoa alloc] initWithNode:this]); - return native_node_.get(); -} - -} // namespace ui
diff --git a/ui/accessibility/tree_generator.cc b/ui/accessibility/tree_generator.cc deleted file mode 100644 index 25ae76f..0000000 --- a/ui/accessibility/tree_generator.cc +++ /dev/null
@@ -1,68 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/accessibility/tree_generator.h" - -#include "base/logging.h" -#include "ui/accessibility/ax_serializable_tree.h" -#include "ui/accessibility/ax_tree.h" - -namespace ui { - -TreeGenerator::TreeGenerator(int node_count) - : node_count_(node_count), unique_tree_count_(1) { - // (n-1)! for the possible trees. - for (int i = 2; i < node_count_; i++) - unique_tree_count_ *= i; - // n! for the permutations of ids. - for (int i = 2; i <= node_count_; i++) - unique_tree_count_ *= i; -}; - -int TreeGenerator::UniqueTreeCount() const { - return unique_tree_count_; -}; - -void TreeGenerator::BuildUniqueTree(int tree_index, AXTree* out_tree) const { - std::vector<int> indices; - std::vector<int> permuted; - CHECK(tree_index <= unique_tree_count_); - - // Use the first few bits of |tree_index| to permute the indices. - for (int i = 0; i < node_count_; i++) - indices.push_back(i + 1); - for (int i = 0; i < node_count_; i++) { - int p = (node_count_ - i); - int index = tree_index % p; - tree_index /= p; - permuted.push_back(indices[index]); - indices.erase(indices.begin() + index); - } - - // Build an AXTreeUpdate. The first two nodes of the tree always - // go in the same place. - AXTreeUpdate update; - update.nodes.resize(node_count_); - update.nodes[0].id = permuted[0]; - update.nodes[0].role = AX_ROLE_ROOT_WEB_AREA; - update.nodes[0].state = AX_STATE_NONE; - update.nodes[0].child_ids.push_back(permuted[1]); - update.nodes[1].id = permuted[1]; - update.nodes[1].state = AX_STATE_NONE; - - // The remaining nodes are assigned based on their parent - // selected from the next bits from |tree_index|. - for (int i = 2; i < node_count_; i++) { - update.nodes[i].id = permuted[i]; - update.nodes[i].state = AX_STATE_NONE; - int parent_index = (tree_index % i); - tree_index /= i; - update.nodes[parent_index].child_ids.push_back(permuted[i]); - } - - // Unserialize the tree update into the destination tree. - CHECK(out_tree->Unserialize(update)) << out_tree->error(); -}; - -} // namespace ui
diff --git a/ui/accessibility/tree_generator.h b/ui/accessibility/tree_generator.h deleted file mode 100644 index 3041d92..0000000 --- a/ui/accessibility/tree_generator.h +++ /dev/null
@@ -1,48 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -namespace ui { - -class AXTree; - -// A class to create all possible trees with <n> nodes and the ids [1...n]. -// -// There are two parts to the algorithm: -// -// The tree structure is formed as follows: without loss of generality, -// the first node becomes the root and the second node becomes its -// child. Thereafter, choose every possible parent for every other node. -// -// So for node i in (3...n), there are (i - 1) possible choices for its -// parent, for a total of (n-1)! (n minus 1 factorial) possible trees. -// -// The second part is the assignment of ids to the nodes in the tree. -// There are exactly n! (n factorial) permutations of the sequence 1...n, -// and each of these is assigned to every node in every possible tree. -// -// The total number of trees returned for a given <n>, then, is -// n! * (n-1)! -// -// n = 2: 2 trees -// n = 3: 12 trees -// n = 4: 144 trees -// n = 5: 2880 trees -// -// This grows really fast! Luckily it's very unlikely that there'd be -// bugs that affect trees with >4 nodes that wouldn't affect a smaller tree -// too. -class TreeGenerator { - public: - TreeGenerator(int node_count); - - int UniqueTreeCount() const; - - void BuildUniqueTree(int tree_index, AXTree* out_tree) const; - - private: - int node_count_; - int unique_tree_count_; -}; - -} // namespace ui
diff --git a/ui/aura/BUILD.gn b/ui/aura/BUILD.gn deleted file mode 100644 index 24d44cc..0000000 --- a/ui/aura/BUILD.gn +++ /dev/null
@@ -1,285 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import("//build/config/ui.gni") - -component("aura") { - sources = [ - "client/aura_constants.cc", - "client/aura_constants.h", - "client/capture_client.cc", - "client/capture_client.h", - "client/capture_delegate.h", - "client/cursor_client.cc", - "client/cursor_client.h", - "client/cursor_client_observer.h", - "client/cursor_client_observer.cc", - "client/default_capture_client.cc", - "client/default_capture_client.h", - "client/event_client.cc", - "client/event_client.h", - "client/focus_change_observer.cc", - "client/focus_change_observer.h", - "client/focus_client.cc", - "client/focus_client.h", - "client/screen_position_client.cc", - "client/screen_position_client.h", - "client/visibility_client.cc", - "client/visibility_client.h", - "client/window_stacking_client.cc", - "client/window_stacking_client.h", - "client/window_tree_client.cc", - "client/window_tree_client.h", - "env.cc", - "env.h", - "env_observer.h", - "input_state_lookup.cc", - "input_state_lookup.h", - "input_state_lookup_win.cc", - "input_state_lookup_win.h", - "layout_manager.cc", - "layout_manager.h", - "scoped_window_targeter.cc", - "scoped_window_targeter.h", - "window.cc", - "window.h", - "window_event_dispatcher.cc", - "window_event_dispatcher.h", - "window_delegate.h", - "window_layer_type.h", - "window_observer.cc", - "window_observer.h", - "window_targeter.cc", - "window_targeter.h", - "window_tracker.cc", - "window_tracker.h", - "window_tree_host.cc", - "window_tree_host.h", - "window_tree_host_mac.mm", - "window_tree_host_mac.h", - "window_tree_host_observer.h", - "window_tree_host_win.cc", - "window_tree_host_win.h", - "window_tree_host_x11.cc", - "window_tree_host_x11.h", - "../wm/public/activation_change_observer.h", - "../wm/public/activation_change_observer.cc", - "../wm/public/activation_client.cc", - "../wm/public/activation_client.h", - "../wm/public/activation_delegate.cc", - "../wm/public/activation_delegate.h", - "../wm/public/animation_host.cc", - "../wm/public/animation_host.h", - "../wm/public/dispatcher_client.cc", - "../wm/public/dispatcher_client.h", - "../wm/public/drag_drop_client.cc", - "../wm/public/drag_drop_client.h", - "../wm/public/drag_drop_delegate.cc", - "../wm/public/drag_drop_delegate.h", - "../wm/public/scoped_tooltip_disabler.cc", - "../wm/public/scoped_tooltip_disabler.h", - "../wm/public/tooltip_client.cc", - "../wm/public/tooltip_client.h", - "../wm/public/transient_window_client.cc", - "../wm/public/transient_window_client.h", - "../wm/public/window_move_client.cc", - "../wm/public/window_move_client.h", - "../wm/public/window_types.h", - ] - - defines = [ "AURA_IMPLEMENTATION" ] - - deps = [ - "//base", - "//base:i18n", - "//base/third_party/dynamic_annotations", - "//skia", - "//ui/base", - "//ui/compositor", - "//ui/events", - "//ui/events/platform", - "//ui/gfx", - "//ui/gfx/geometry", - ] - - if (use_x11) { - configs += [ - "//build/config/linux:x11", - "//build/config/linux:xrandr", - ] - deps += [ "//ui/events/platform/x11" ] - } - - if (is_win) { - sources -= [ - "input_state_lookup.cc", - "window_tree_host_x11.cc", - ] - deps += [ "//ui/platform_window/win" ] - } - - if (use_ozone) { - sources += [ - "window_tree_host_ozone.cc", - "window_tree_host_ozone.h", - ] - # TODO(GYP) enable when these targets exist. - #deps += [ - # "//ui/events/ozone", - # "//ui/ozone", - #] - } -} - -if (false) { - source_set("test_support") { - testonly = true - sources = [ - "test/aura_test_base.cc", - "test/aura_test_base.h", - "test/aura_test_helper.cc", - "test/aura_test_helper.h", - "test/aura_test_utils.cc", - "test/aura_test_utils.h", - "test/env_test_helper.h", - "test/event_generator_delegate_aura.cc", - "test/event_generator_delegate_aura.h", - "test/test_cursor_client.cc", - "test/test_cursor_client.h", - "test/test_focus_client.cc", - "test/test_focus_client.h", - "test/test_screen.cc", - "test/test_screen.h", - "test/test_window_tree_client.cc", - "test/test_window_tree_client.h", - "test/test_windows.cc", - "test/test_windows.h", - "test/test_window_delegate.cc", - "test/test_window_delegate.h", - "test/ui_controls_factory_aura.h", - "test/window_event_dispatcher_test_api.cc", - "test/window_event_dispatcher_test_api.h", - "test/window_test_api.cc", - "test/window_test_api.h", - ] - - public_deps = [ - ":aura", - ] - deps = [ - "//skia", - "//testing/gtest", - "//ui/base:test_support", - "//ui/compositor:test_support", - "//ui/events", - "//ui/events:events_base", - "//ui/events:test_support", - "//ui/gfx", - "//ui/gfx/geometry", - "//ui/wm", - ] - - if (is_win) { - cflags = [ "/wd4267" ] # TODO(jschuh): crbug.com/167187 fix size_t to int truncations. - } - - if (use_aura) { - if (is_win) { - sources += [ "test/ui_controls_factory_aurawin.cc" ] - } - - if (use_x11) { - sources += [ "test/ui_controls_factory_aurax11.cc" ] - } - } - } - - executable("demo") { - output_name = "aura_demo" - testonly = true - - sources = [ - "demo/demo_main.cc", - ] - - deps = [ - ":aura", - ":test_support", - "//base", - "//base:i18n", - "//skia", - "//third_party/icu", - "//ui/base", - "//ui/compositor", - "//ui/compositor:test_support", - "//ui/events", - "//ui/gfx", - "//ui/gfx/geometry", - "//ui/gl", - ] - - if (use_x11) { - deps += [ "//ui/gfx/x" ] - } - } - - executable("bench") { - output_name = "aura_bench" - testonly = true - - sources = [ - "bench/bench_main.cc", - ] - - deps = [ - ":test_support", - "//base", - "//base:i18n", - "//cc", - "//gpu/command_buffer/client:gles2_interface", - "//skia", - "//third_party/icu", - "//ui/base", - "//ui/compositor", - "//ui/compositor:test_support", - "//ui/events", - "//ui/gfx", - "//ui/gfx/geometry", - "//ui/gl", - ] - - if (use_x11) { - deps += [ "//ui/gfx/x" ] - } - } - - test("aura_unittests") { - sources = [ - "gestures/gesture_recognizer_unittest.cc", - "test/run_all_unittests.cc", - "window_event_dispatcher_unittest.cc", - "window_targeter_unittest.cc", - "window_unittest.cc", - ] - - deps = [ - ":test_support", - "//base/allocator", - "//base/test:test_support", - "//skia", - "//testing/gtest", - "//ui/base:test_support", - "//ui/compositor:test_support", - "//ui/events:test_support", - "//ui/events:gesture_detection", - "//ui/gfx", - "//ui/gfx/geometry", - "//ui/gl", - ] - - if (is_linux) { - deps += [ "//third_party/mesa" ] - } - } -} # if (false)
diff --git a/ui/aura/DEPS b/ui/aura/DEPS deleted file mode 100644 index 9b9ca33..0000000 --- a/ui/aura/DEPS +++ /dev/null
@@ -1,14 +0,0 @@ -include_rules = [ - "+skia/ext", - "+third_party/skia", - "+ui/base", - "+ui/compositor", - "+ui/events", - "+ui/gfx", - "+ui/metro_viewer", # TODO(beng): investigate moving remote_root_window_host - # to ui/metro_viewer. - "+ui/ozone/public", - "+ui/platform_window", - "+ui/wm/public", -] -
diff --git a/ui/aura/OWNERS b/ui/aura/OWNERS deleted file mode 100644 index 447142e..0000000 --- a/ui/aura/OWNERS +++ /dev/null
@@ -1,6 +0,0 @@ -ben@chromium.org -sky@chromium.org -sadrul@chromium.org - -per-file *x11.cc=erg@chromium.org -per-file *x11.h=erg@chromium.org
diff --git a/ui/aura/aura.gyp b/ui/aura/aura.gyp deleted file mode 100644 index 88ddcce..0000000 --- a/ui/aura/aura.gyp +++ /dev/null
@@ -1,310 +0,0 @@ -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -{ - 'variables': { - 'chromium_code': 1, - }, - 'targets': [ - { - # GN version: //ui/aura - 'target_name': 'aura', - 'type': '<(component)', - 'dependencies': [ - '../../base/base.gyp:base', - '../../base/base.gyp:base_i18n', - '../../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', - '../../skia/skia.gyp:skia', - '../base/ui_base.gyp:ui_base', - '../compositor/compositor.gyp:compositor', - '../events/events.gyp:events', - '../events/events.gyp:events_base', - '../events/platform/events_platform.gyp:events_platform', - '../gfx/gfx.gyp:gfx', - '../gfx/gfx.gyp:gfx_geometry', - ], - 'defines': [ - 'AURA_IMPLEMENTATION', - ], - 'sources': [ - 'client/aura_constants.cc', - 'client/aura_constants.h', - 'client/capture_client.cc', - 'client/capture_client.h', - 'client/capture_delegate.h', - 'client/cursor_client.cc', - 'client/cursor_client.h', - 'client/cursor_client_observer.h', - 'client/cursor_client_observer.cc', - 'client/default_capture_client.cc', - 'client/default_capture_client.h', - 'client/event_client.cc', - 'client/event_client.h', - 'client/focus_change_observer.cc', - 'client/focus_change_observer.h', - 'client/focus_client.cc', - 'client/focus_client.h', - 'client/screen_position_client.cc', - 'client/screen_position_client.h', - 'client/visibility_client.cc', - 'client/visibility_client.h', - 'client/window_stacking_client.cc', - 'client/window_stacking_client.h', - 'client/window_tree_client.cc', - 'client/window_tree_client.h', - 'env.cc', - 'env.h', - 'env_observer.h', - 'input_state_lookup.cc', - 'input_state_lookup.h', - 'input_state_lookup_win.cc', - 'input_state_lookup_win.h', - 'layout_manager.cc', - 'layout_manager.h', - 'remote_window_tree_host_win.cc', - 'remote_window_tree_host_win.h', - 'scoped_window_targeter.cc', - 'scoped_window_targeter.h', - 'window.cc', - 'window.h', - 'window_event_dispatcher.cc', - 'window_event_dispatcher.h', - 'window_delegate.h', - 'window_layer_type.h', - 'window_observer.cc', - 'window_observer.h', - 'window_targeter.cc', - 'window_targeter.h', - 'window_tracker.cc', - 'window_tracker.h', - 'window_tree_host.cc', - 'window_tree_host.h', - 'window_tree_host_mac.mm', - 'window_tree_host_mac.h', - 'window_tree_host_observer.h', - 'window_tree_host_ozone.cc', - 'window_tree_host_ozone.h', - 'window_tree_host_win.cc', - 'window_tree_host_win.h', - 'window_tree_host_x11.cc', - 'window_tree_host_x11.h', - '../wm/public/activation_change_observer.h', - '../wm/public/activation_change_observer.cc', - '../wm/public/activation_client.cc', - '../wm/public/activation_client.h', - '../wm/public/activation_delegate.cc', - '../wm/public/activation_delegate.h', - '../wm/public/animation_host.cc', - '../wm/public/animation_host.h', - '../wm/public/dispatcher_client.cc', - '../wm/public/dispatcher_client.h', - '../wm/public/drag_drop_client.cc', - '../wm/public/drag_drop_client.h', - '../wm/public/drag_drop_delegate.cc', - '../wm/public/drag_drop_delegate.h', - '../wm/public/scoped_tooltip_disabler.cc', - '../wm/public/scoped_tooltip_disabler.h', - '../wm/public/tooltip_client.cc', - '../wm/public/tooltip_client.h', - '../wm/public/transient_window_client.cc', - '../wm/public/transient_window_client.h', - '../wm/public/window_move_client.cc', - '../wm/public/window_move_client.h', - '../wm/public/window_types.h', - ], - 'conditions': [ - ['use_x11==1', { - 'dependencies': [ - '../../build/linux/system.gyp:x11', - '../../build/linux/system.gyp:xrandr', - '../../build/linux/system.gyp:xi', - '../events/platform/x11/x11_events_platform.gyp:x11_events_platform', - ], - }], - ['OS=="win"', { - 'dependencies': [ - '../metro_viewer/metro_viewer.gyp:metro_viewer_messages', - '../platform_window/win/win_window.gyp:win_window', - '../../ipc/ipc.gyp:ipc', - ], - 'sources!': [ - 'input_state_lookup.cc', - ], - }], - ['use_ozone==1', { - 'dependencies': [ - '../events/ozone/events_ozone.gyp:events_ozone', - '../ozone/ozone.gyp:ozone', - '../ozone/ozone.gyp:ozone_base', - ], - }], - ], - }, - { - # GN version: //ui/aura:test_support - 'target_name': 'aura_test_support', - 'type': 'static_library', - 'dependencies': [ - '../../skia/skia.gyp:skia', - '../../testing/gtest.gyp:gtest', - '../base/ui_base.gyp:ui_base', - '../base/ui_base.gyp:ui_base_test_support', - '../compositor/compositor.gyp:compositor_test_support', - '../events/events.gyp:events', - '../events/events.gyp:events_base', - '../events/events.gyp:events_test_support', - '../gfx/gfx.gyp:gfx', - '../gfx/gfx.gyp:gfx_geometry', - 'aura', - ], - 'include_dirs': [ - '..', - ], - 'sources': [ - 'test/aura_test_base.cc', - 'test/aura_test_base.h', - 'test/aura_test_helper.cc', - 'test/aura_test_helper.h', - 'test/aura_test_utils.cc', - 'test/aura_test_utils.h', - 'test/env_test_helper.h', - 'test/event_generator_delegate_aura.cc', - 'test/event_generator_delegate_aura.h', - 'test/test_cursor_client.cc', - 'test/test_cursor_client.h', - 'test/test_focus_client.cc', - 'test/test_focus_client.h', - 'test/test_screen.cc', - 'test/test_screen.h', - 'test/test_window_tree_client.cc', - 'test/test_window_tree_client.h', - 'test/test_windows.cc', - 'test/test_windows.h', - 'test/test_window_delegate.cc', - 'test/test_window_delegate.h', - 'test/ui_controls_factory_aura.h', - 'test/ui_controls_factory_aurawin.cc', - 'test/ui_controls_factory_aurax11.cc', - 'test/ui_controls_factory_ozone.cc', - 'test/window_event_dispatcher_test_api.cc', - 'test/window_event_dispatcher_test_api.h', - 'test/window_test_api.cc', - 'test/window_test_api.h', - ], - # TODO(jschuh): crbug.com/167187 fix size_t to int truncations. - 'msvs_disabled_warnings': [ 4267, ], - }, - { - 'target_name': 'aura_demo', - 'type': 'executable', - 'dependencies': [ - '../../base/base.gyp:base', - '../../base/base.gyp:base_i18n', - '../../skia/skia.gyp:skia', - '../../third_party/icu/icu.gyp:icui18n', - '../../third_party/icu/icu.gyp:icuuc', - '../base/ui_base.gyp:ui_base', - '../compositor/compositor.gyp:compositor', - '../compositor/compositor.gyp:compositor_test_support', - '../events/events.gyp:events', - '../gfx/gfx.gyp:gfx', - '../gfx/gfx.gyp:gfx_geometry', - 'aura', - 'aura_test_support', - ], - 'include_dirs': [ - '..', - ], - 'sources': [ - 'demo/demo_main.cc', - ], - 'conditions': [ - ['use_x11==1', { - 'dependencies': [ - '../gfx/x/gfx_x11.gyp:gfx_x11', - ], - }], - ] - }, - { - 'target_name': 'aura_bench', - 'type': 'executable', - 'dependencies': [ - '../../base/base.gyp:base', - '../../base/base.gyp:base_i18n', - '../../cc/cc.gyp:cc', - '../../gpu/gpu.gyp:gles2_implementation', - '../../skia/skia.gyp:skia', - '../../third_party/icu/icu.gyp:icui18n', - '../../third_party/icu/icu.gyp:icuuc', - '../base/ui_base.gyp:ui_base', - '../compositor/compositor.gyp:compositor', - '../compositor/compositor.gyp:compositor_test_support', - '../events/events.gyp:events', - '../gfx/gfx.gyp:gfx', - '../gfx/gfx.gyp:gfx_geometry', - 'aura', - 'aura_test_support', - ], - 'include_dirs': [ - '..', - ], - 'sources': [ - 'bench/bench_main.cc', - ], - 'conditions': [ - ['use_x11==1', { - 'dependencies': [ - '../gfx/x/gfx_x11.gyp:gfx_x11', - ], - }], - ] - }, - { - 'target_name': 'aura_unittests', - 'type': 'executable', - 'dependencies': [ - '../../base/base.gyp:test_support_base', - '../../skia/skia.gyp:skia', - '../../testing/gtest.gyp:gtest', - '../base/ui_base.gyp:ui_base', - '../base/ui_base.gyp:ui_base_test_support', - '../compositor/compositor.gyp:compositor', - '../compositor/compositor.gyp:compositor_test_support', - '../events/events.gyp:events', - '../events/events.gyp:events_base', - '../events/events.gyp:gesture_detection', - '../gfx/gfx.gyp:gfx', - '../gfx/gfx.gyp:gfx_geometry', - '../gl/gl.gyp:gl', - 'aura_test_support', - 'aura', - ], - 'include_dirs': [ - '..', - ], - 'sources': [ - 'gestures/gesture_recognizer_unittest.cc', - 'window_event_dispatcher_unittest.cc', - 'test/run_all_unittests.cc', - 'window_targeter_unittest.cc', - 'window_unittest.cc', - ], - 'conditions': [ - # osmesa GL implementation is used on linux. - ['OS=="linux"', { - 'dependencies': [ - '<(DEPTH)/third_party/mesa/mesa.gyp:osmesa', - ], - }], - ['OS=="linux" and use_allocator!="none"', { - 'dependencies': [ - # See http://crbug.com/162998#c4 for why this is needed. - '../../base/allocator/allocator.gyp:allocator', - ], - }], - ], - }, - ], -}
diff --git a/ui/aura/aura_export.h b/ui/aura/aura_export.h deleted file mode 100644 index 1093040..0000000 --- a/ui/aura/aura_export.h +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_AURA_EXPORT_H_ -#define UI_AURA_AURA_EXPORT_H_ - -// Defines AURA_EXPORT so that functionality implemented by the aura module -// can be exported to consumers. - -#if defined(COMPONENT_BUILD) -#if defined(WIN32) - -#if defined(AURA_IMPLEMENTATION) -#define AURA_EXPORT __declspec(dllexport) -#else -#define AURA_EXPORT __declspec(dllimport) -#endif // defined(AURA_IMPLEMENTATION) - -#else // defined(WIN32) -#if defined(AURA_IMPLEMENTATION) -#define AURA_EXPORT __attribute__((visibility("default"))) -#else -#define AURA_EXPORT -#endif -#endif - -#else // defined(COMPONENT_BUILD) -#define AURA_EXPORT -#endif - -#endif // UI_AURA_AURA_EXPORT_H_
diff --git a/ui/aura/bench/DEPS b/ui/aura/bench/DEPS deleted file mode 100644 index 315ad72..0000000 --- a/ui/aura/bench/DEPS +++ /dev/null
@@ -1,8 +0,0 @@ -include_rules = [ - "+cc", - "-cc/blink", - "-cc/surfaces", - "+gpu/command_buffer/client/gles2_interface.h", - "+third_party/khronos", - "+ui/gl/gl_surface.h", # To initialize GL bindings. -]
diff --git a/ui/aura/bench/bench_main.cc b/ui/aura/bench/bench_main.cc deleted file mode 100644 index 4704f7b..0000000 --- a/ui/aura/bench/bench_main.cc +++ /dev/null
@@ -1,373 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#if defined(USE_X11) -#include <X11/Xlib.h> -#endif - -#include "base/at_exit.h" -#include "base/bind.h" -#include "base/command_line.h" -#include "base/i18n/icu_util.h" -#include "base/memory/scoped_ptr.h" -#include "base/message_loop/message_loop.h" -#include "base/strings/string_split.h" -#include "base/time/time.h" -#include "cc/output/context_provider.h" -#include "gpu/command_buffer/client/gles2_interface.h" -#include "third_party/khronos/GLES2/gl2.h" -#include "third_party/skia/include/core/SkXfermode.h" -#include "ui/aura/client/default_capture_client.h" -#include "ui/aura/env.h" -#include "ui/aura/test/test_focus_client.h" -#include "ui/aura/test/test_screen.h" -#include "ui/aura/window.h" -#include "ui/aura/window_tree_host.h" -#include "ui/base/hit_test.h" -#include "ui/compositor/compositor.h" -#include "ui/compositor/compositor_observer.h" -#include "ui/compositor/debug_utils.h" -#include "ui/compositor/layer.h" -#include "ui/compositor/test/in_process_context_factory.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/rect.h" -#include "ui/gfx/skia_util.h" -#include "ui/gfx/x/x11_connection.h" -#include "ui/gl/gl_surface.h" - -#ifndef GL_GLEXT_PROTOTYPES -#define GL_GLEXT_PROTOTYPES 1 -#endif -#include "third_party/khronos/GLES2/gl2ext.h" - -using base::TimeTicks; -using ui::Compositor; -using ui::Layer; -using ui::LayerDelegate; - -namespace { - -class ColoredLayer : public Layer, public LayerDelegate { - public: - explicit ColoredLayer(SkColor color) - : Layer(ui::LAYER_TEXTURED), - color_(color), - draw_(true) { - set_delegate(this); - } - - virtual ~ColoredLayer() {} - - // Overridden from LayerDelegate: - virtual void OnPaintLayer(gfx::Canvas* canvas) override { - if (draw_) { - canvas->DrawColor(color_); - } - } - - virtual void OnDelegatedFrameDamage( - const gfx::Rect& damage_rect_in_dip) override {} - - virtual void OnDeviceScaleFactorChanged(float device_scale_factor) override { - } - - virtual base::Closure PrepareForLayerBoundsChange() override { - return base::Closure(); - } - - void set_color(SkColor color) { color_ = color; } - void set_draw(bool draw) { draw_ = draw; } - - private: - SkColor color_; - bool draw_; - - DISALLOW_COPY_AND_ASSIGN(ColoredLayer); -}; - -const int kFrames = 100; - -// Benchmark base class, hooks up drawing callback and displaying FPS. -class BenchCompositorObserver : public ui::CompositorObserver { - public: - explicit BenchCompositorObserver(int max_frames) - : start_time_(), - frames_(0), - max_frames_(max_frames) { - } - - virtual void OnCompositingDidCommit(ui::Compositor* compositor) override {} - - virtual void OnCompositingStarted(Compositor* compositor, - base::TimeTicks start_time) override {} - - virtual void OnCompositingEnded(Compositor* compositor) override { - if (start_time_.is_null()) { - start_time_ = TimeTicks::Now(); - } else { - ++frames_; - if (frames_ % kFrames == 0) { - TimeTicks now = TimeTicks::Now(); - double ms = (now - start_time_).InMillisecondsF() / kFrames; - LOG(INFO) << "FPS: " << 1000.f / ms << " (" << ms << " ms)"; - start_time_ = now; - } - } - if (max_frames_ && frames_ == max_frames_) { - base::MessageLoop::current()->Quit(); - } else { - Draw(); - } - } - - virtual void OnCompositingAborted(Compositor* compositor) override {} - - virtual void OnCompositingLockStateChanged( - Compositor* compositor) override {} - - virtual void Draw() {} - - int frames() const { return frames_; } - - private: - TimeTicks start_time_; - int frames_; - int max_frames_; - - DISALLOW_COPY_AND_ASSIGN(BenchCompositorObserver); -}; - -void ReturnMailbox(scoped_refptr<cc::ContextProvider> context_provider, - GLuint texture, - GLuint sync_point, - bool is_lost) { - gpu::gles2::GLES2Interface* gl = context_provider->ContextGL(); - gl->WaitSyncPointCHROMIUM(sync_point); - gl->DeleteTextures(1, &texture); - gl->ShallowFlushCHROMIUM(); -} - -// A benchmark that adds a texture layer that is updated every frame. -class WebGLBench : public BenchCompositorObserver { - public: - WebGLBench(ui::ContextFactory* context_factory, - Layer* parent, - Compositor* compositor, - int max_frames) - : BenchCompositorObserver(max_frames), - parent_(parent), - webgl_(ui::LAYER_SOLID_COLOR), - compositor_(compositor), - fbo_(0), - do_draw_(true) { - CommandLine* command_line = CommandLine::ForCurrentProcess(); - do_draw_ = !command_line->HasSwitch("disable-draw"); - - std::string webgl_size = command_line->GetSwitchValueASCII("webgl-size"); - int width = 0; - int height = 0; - if (!webgl_size.empty()) { - std::vector<std::string> split_size; - base::SplitString(webgl_size, 'x', &split_size); - if (split_size.size() == 2) { - width = atoi(split_size[0].c_str()); - height = atoi(split_size[1].c_str()); - } - } - if (!width || !height) { - width = 800; - height = 600; - } - gfx::Rect bounds(width, height); - webgl_.SetBounds(bounds); - parent_->Add(&webgl_); - - context_provider_ = context_factory->SharedMainThreadContextProvider(); - gpu::gles2::GLES2Interface* gl = context_provider_->ContextGL(); - GLuint texture = 0; - gl->GenTextures(1, &texture); - gl->BindTexture(GL_TEXTURE_2D, texture); - gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - gl->TexImage2D(GL_TEXTURE_2D, - 0, - GL_RGBA, - width, - height, - 0, - GL_RGBA, - GL_UNSIGNED_BYTE, - NULL); - gpu::Mailbox mailbox; - gl->GenMailboxCHROMIUM(mailbox.name); - gl->ProduceTextureCHROMIUM(GL_TEXTURE_2D, mailbox.name); - - gl->GenFramebuffers(1, &fbo_); - gl->BindFramebuffer(GL_FRAMEBUFFER, fbo_); - gl->FramebufferTexture2D( - GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0); - gl->ClearColor(0.f, 1.f, 0.f, 1.f); - gl->Clear(GL_COLOR_BUFFER_BIT); - gl->Flush(); - - GLuint sync_point = gl->InsertSyncPointCHROMIUM(); - webgl_.SetTextureMailbox( - cc::TextureMailbox(mailbox, GL_TEXTURE_2D, sync_point), - cc::SingleReleaseCallback::Create( - base::Bind(ReturnMailbox, context_provider_, texture)), - bounds.size()); - compositor->AddObserver(this); - } - - virtual ~WebGLBench() { - webgl_.SetShowSolidColorContent(); - gpu::gles2::GLES2Interface* gl = context_provider_->ContextGL(); - gl->DeleteFramebuffers(1, &fbo_); - compositor_->RemoveObserver(this); - } - - virtual void Draw() override { - if (do_draw_) { - gpu::gles2::GLES2Interface* gl = context_provider_->ContextGL(); - gl->ClearColor((frames() % kFrames)*1.0/kFrames, 1.f, 0.f, 1.f); - gl->Clear(GL_COLOR_BUFFER_BIT); - gl->Flush(); - } - webgl_.SchedulePaint(gfx::Rect(webgl_.bounds().size())); - compositor_->ScheduleDraw(); - } - - private: - Layer* parent_; - Layer webgl_; - Compositor* compositor_; - scoped_refptr<cc::ContextProvider> context_provider_; - - // The FBO that is used to render to the texture. - unsigned int fbo_; - - // Whether or not to draw to the texture every frame. - bool do_draw_; - - DISALLOW_COPY_AND_ASSIGN(WebGLBench); -}; - -// A benchmark that paints (in software) all tiles every frame. -class SoftwareScrollBench : public BenchCompositorObserver { - public: - SoftwareScrollBench(ColoredLayer* layer, - Compositor* compositor, - int max_frames) - : BenchCompositorObserver(max_frames), - layer_(layer), - compositor_(compositor) { - compositor->AddObserver(this); - layer_->set_draw( - !CommandLine::ForCurrentProcess()->HasSwitch("disable-draw")); - } - - virtual ~SoftwareScrollBench() { - compositor_->RemoveObserver(this); - } - - virtual void Draw() override { - layer_->set_color( - SkColorSetARGBInline(255*(frames() % kFrames)/kFrames, 255, 0, 255)); - layer_->SchedulePaint(gfx::Rect(layer_->bounds().size())); - } - - private: - ColoredLayer* layer_; - Compositor* compositor_; - - DISALLOW_COPY_AND_ASSIGN(SoftwareScrollBench); -}; - -} // namespace - -int main(int argc, char** argv) { - CommandLine::Init(argc, argv); - - base::AtExitManager exit_manager; - -#if defined(USE_X11) - // This demo uses InProcessContextFactory which uses X on a separate Gpu - // thread. - gfx::InitializeThreadedX11(); -#endif - - gfx::GLSurface::InitializeOneOff(); - - // The ContextFactory must exist before any Compositors are created. - scoped_ptr<ui::InProcessContextFactory> context_factory( - new ui::InProcessContextFactory()); - - base::i18n::InitializeICU(); - - base::MessageLoopForUI message_loop; - aura::Env::CreateInstance(true); - aura::Env::GetInstance()->set_context_factory(context_factory.get()); - scoped_ptr<aura::TestScreen> test_screen( - aura::TestScreen::CreateFullscreen()); - gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE, test_screen.get()); - scoped_ptr<aura::WindowTreeHost> host( - test_screen->CreateHostForPrimaryDisplay()); - aura::client::SetCaptureClient( - host->window(), - new aura::client::DefaultCaptureClient(host->window())); - - scoped_ptr<aura::client::FocusClient> focus_client( - new aura::test::TestFocusClient); - aura::client::SetFocusClient(host->window(), focus_client.get()); - - // add layers - ColoredLayer background(SK_ColorRED); - background.SetBounds(host->window()->bounds()); - host->window()->layer()->Add(&background); - - ColoredLayer window(SK_ColorBLUE); - window.SetBounds(gfx::Rect(background.bounds().size())); - background.Add(&window); - - Layer content_layer(ui::LAYER_NOT_DRAWN); - - CommandLine* command_line = CommandLine::ForCurrentProcess(); - bool force = command_line->HasSwitch("force-render-surface"); - content_layer.SetForceRenderSurface(force); - gfx::Rect bounds(window.bounds().size()); - bounds.Inset(0, 30, 0, 0); - content_layer.SetBounds(bounds); - window.Add(&content_layer); - - ColoredLayer page_background(SK_ColorWHITE); - page_background.SetBounds(gfx::Rect(content_layer.bounds().size())); - content_layer.Add(&page_background); - - int frames = atoi(command_line->GetSwitchValueASCII("frames").c_str()); - scoped_ptr<BenchCompositorObserver> bench; - - if (command_line->HasSwitch("bench-software-scroll")) { - bench.reset(new SoftwareScrollBench(&page_background, - host->compositor(), - frames)); - } else { - bench.reset(new WebGLBench(context_factory.get(), - &page_background, - host->compositor(), - frames)); - } - -#ifndef NDEBUG - ui::PrintLayerHierarchy(host->window()->layer(), gfx::Point(100, 100)); -#endif - - host->Show(); - base::MessageLoopForUI::current()->Run(); - focus_client.reset(); - host.reset(); - - return 0; -}
diff --git a/ui/aura/client/aura_constants.cc b/ui/aura/client/aura_constants.cc deleted file mode 100644 index f903bff..0000000 --- a/ui/aura/client/aura_constants.cc +++ /dev/null
@@ -1,40 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/client/aura_constants.h" - -#include "ui/aura/window_property.h" -#include "ui/gfx/rect.h" - -DECLARE_EXPORTED_WINDOW_PROPERTY_TYPE(AURA_EXPORT, bool) -DECLARE_EXPORTED_WINDOW_PROPERTY_TYPE(AURA_EXPORT, ui::ModalType) -DECLARE_EXPORTED_WINDOW_PROPERTY_TYPE(AURA_EXPORT, gfx::Rect*) -DECLARE_EXPORTED_WINDOW_PROPERTY_TYPE(AURA_EXPORT, ui::InputMethod*) -DECLARE_EXPORTED_WINDOW_PROPERTY_TYPE(AURA_EXPORT, ui::WindowShowState) - -namespace aura { -namespace client { - -// Alphabetical sort. - -DEFINE_WINDOW_PROPERTY_KEY(bool, kAlwaysOnTopKey, false); -DEFINE_WINDOW_PROPERTY_KEY(bool, kAnimationsDisabledKey, false); -DEFINE_WINDOW_PROPERTY_KEY(bool, kCanMaximizeKey, false); -DEFINE_WINDOW_PROPERTY_KEY(bool, kCanMinimizeKey, false); -DEFINE_WINDOW_PROPERTY_KEY(bool, kCanResizeKey, true); -DEFINE_WINDOW_PROPERTY_KEY(bool, kConstrainedWindowKey, false); -DEFINE_WINDOW_PROPERTY_KEY(bool, kDrawAttentionKey, false); -DEFINE_WINDOW_PROPERTY_KEY(Window*, kHostWindowKey, NULL); -DEFINE_WINDOW_PROPERTY_KEY(ui::ModalType, kModalKey, ui::MODAL_TYPE_NONE); -// gfx::Rect object for RestoreBoundsKey property is owned by the window -// and will be freed automatically. -DEFINE_OWNED_WINDOW_PROPERTY_KEY(gfx::Rect, kRestoreBoundsKey, NULL); -DEFINE_WINDOW_PROPERTY_KEY( - ui::WindowShowState, kRestoreShowStateKey, ui::SHOW_STATE_DEFAULT); -DEFINE_WINDOW_PROPERTY_KEY(ui::InputMethod*, kRootWindowInputMethodKey, NULL); -DEFINE_WINDOW_PROPERTY_KEY( - ui::WindowShowState, kShowStateKey, ui::SHOW_STATE_DEFAULT); - -} // namespace client -} // namespace aura
diff --git a/ui/aura/client/aura_constants.h b/ui/aura/client/aura_constants.h deleted file mode 100644 index d346098..0000000 --- a/ui/aura/client/aura_constants.h +++ /dev/null
@@ -1,73 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_CLIENT_AURA_CONSTANTS_H_ -#define UI_AURA_CLIENT_AURA_CONSTANTS_H_ - -#include "ui/aura/aura_export.h" -#include "ui/aura/window.h" -#include "ui/base/ui_base_types.h" - -namespace ui { -class InputMethod; -} - -namespace aura { -namespace client { - -// Alphabetical sort. - -// A property key to store always-on-top flag. -AURA_EXPORT extern const WindowProperty<bool>* const kAlwaysOnTopKey; - -// A property key to store whether animations are disabled for the window. Type -// of value is an int. -AURA_EXPORT extern const WindowProperty<bool>* const kAnimationsDisabledKey; - -// A property key to store the can-maximize flag. -AURA_EXPORT extern const WindowProperty<bool>* const kCanMaximizeKey; - -// A property key to store the can-minimize flag. -AURA_EXPORT extern const WindowProperty<bool>* const kCanMinimizeKey; - -// A property key to store the can-resize flag. -AURA_EXPORT extern const WindowProperty<bool>* const kCanResizeKey; - -// A property key to store if a window is a constrained window or not. -AURA_EXPORT extern const WindowProperty<bool>* const kConstrainedWindowKey; - -// A property key to indicate that a window should show that it deserves -// attention. -AURA_EXPORT extern const aura::WindowProperty<bool>* const kDrawAttentionKey; - -// A property key to store the host window of a window. This lets -// WebContentsViews find the windows that should constrain NPAPI plugins. -AURA_EXPORT extern const WindowProperty<Window*>* const kHostWindowKey; - -// A property key to store the window modality. -AURA_EXPORT extern const WindowProperty<ui::ModalType>* const kModalKey; - -// A property key to store the restore bounds for a window. -AURA_EXPORT extern const WindowProperty<gfx::Rect*>* const kRestoreBoundsKey; - -// A property key to store ui::WindowShowState for restoring a window. -// Used in Ash to remember the show state before the window was minimized. -AURA_EXPORT extern const WindowProperty<ui::WindowShowState>* const - kRestoreShowStateKey; - -// A property key to store an input method object that handles a key event. -AURA_EXPORT extern const WindowProperty<ui::InputMethod*>* const - kRootWindowInputMethodKey; - -// A property key to store ui::WindowShowState for a window. -// See ui/base/ui_base_types.h for its definition. -AURA_EXPORT extern const WindowProperty<ui::WindowShowState>* const - kShowStateKey; - -// Alphabetical sort. - -} // namespace client -} // namespace aura - -#endif // UI_AURA_CLIENT_AURA_CONSTANTS_H_
diff --git a/ui/aura/client/capture_client.cc b/ui/aura/client/capture_client.cc deleted file mode 100644 index 6d78c88..0000000 --- a/ui/aura/client/capture_client.cc +++ /dev/null
@@ -1,36 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/client/capture_client.h" - -#include "ui/aura/window_event_dispatcher.h" -#include "ui/aura/window_property.h" - -DECLARE_WINDOW_PROPERTY_TYPE(aura::client::CaptureClient*) - -namespace aura { -namespace client { - -DEFINE_WINDOW_PROPERTY_KEY( - CaptureClient*, kRootWindowCaptureClientKey, NULL); - -void SetCaptureClient(Window* root_window, CaptureClient* client) { - root_window->SetProperty(kRootWindowCaptureClientKey, client); -} - -CaptureClient* GetCaptureClient(Window* root_window) { - return root_window ? - root_window->GetProperty(kRootWindowCaptureClientKey) : NULL; -} - -Window* GetCaptureWindow(Window* window) { - Window* root_window = window->GetRootWindow(); - if (!root_window) - return NULL; - CaptureClient* capture_client = GetCaptureClient(root_window); - return capture_client ? capture_client->GetCaptureWindow() : NULL; -} - -} // namespace client -} // namespace aura
diff --git a/ui/aura/client/capture_client.h b/ui/aura/client/capture_client.h deleted file mode 100644 index 6d27a29..0000000 --- a/ui/aura/client/capture_client.h +++ /dev/null
@@ -1,50 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_CLIENT_CAPTURE_CLIENT_H_ -#define UI_AURA_CLIENT_CAPTURE_CLIENT_H_ - -#include "ui/aura/aura_export.h" - -namespace aura { -class Window; - -namespace client { - -// An interface implemented by an object that manages input capture. -class AURA_EXPORT CaptureClient { - public: - // Does a capture on the |window|. - virtual void SetCapture(Window* window) = 0; - - // Releases a capture from the |window|. - virtual void ReleaseCapture(Window* window) = 0; - - // Returns the current capture window. This may only return a Window if the - // Window that has capture is a child of the Window the CaptureClient is - // installed on. GetGlobalCaptureWindow() can be used to locate the Window - // that has capture regardless of the Window the CaptureClient is installed - // on. - virtual Window* GetCaptureWindow() = 0; - - // See description of GetCaptureWindow() for details. - virtual Window* GetGlobalCaptureWindow() = 0; - - protected: - virtual ~CaptureClient() {} -}; - -// Sets/Gets the capture client on the root Window. -AURA_EXPORT void SetCaptureClient(Window* root_window, - CaptureClient* client); -AURA_EXPORT CaptureClient* GetCaptureClient(Window* root_window); - -// A utility function to get the current capture window. Returns NULL -// if the window doesn't have a root window, or there is no capture window. -AURA_EXPORT Window* GetCaptureWindow(Window* window); - -} // namespace clients -} // namespace aura - -#endif // UI_AURA_CLIENT_CAPTURE_CLIENT_H_
diff --git a/ui/aura/client/capture_delegate.h b/ui/aura/client/capture_delegate.h deleted file mode 100644 index 7ebcaee..0000000 --- a/ui/aura/client/capture_delegate.h +++ /dev/null
@@ -1,39 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_CLIENT_CAPTURE_DELEGATE_H_ -#define UI_AURA_CLIENT_CAPTURE_DELEGATE_H_ - -#include "ui/aura/aura_export.h" - -namespace aura { -class Window; -namespace client { - -// This interface provides API to change the root Window's capture state without -// exposing them as RootWindow API. -class AURA_EXPORT CaptureDelegate { - public: - // Called when a capture is set on |new_capture| and/or a capture is - // released on |old_capture|. - // NOTE: |old_capture| and |new_capture| are not necessarily contained in the - // window hierarchy of the delegate. - virtual void UpdateCapture(aura::Window* old_capture, - aura::Window* new_capture) = 0; - - // Called when another root gets capture. - virtual void OnOtherRootGotCapture() = 0; - - // Sets/Release a native capture on host windows. - virtual void SetNativeCapture() = 0; - virtual void ReleaseNativeCapture() = 0; - - protected: - virtual ~CaptureDelegate() {} -}; - -} // namespace client -} // namespace aura - -#endif // UI_AURA_CLIENT_CAPTURE_DELEGATE_H_
diff --git a/ui/aura/client/cursor_client.cc b/ui/aura/client/cursor_client.cc deleted file mode 100644 index ca105ed..0000000 --- a/ui/aura/client/cursor_client.cc +++ /dev/null
@@ -1,28 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/client/cursor_client.h" - -#include "ui/aura/window.h" -#include "ui/aura/window_property.h" - -DECLARE_WINDOW_PROPERTY_TYPE(aura::client::CursorClient*) - -namespace aura { -namespace client { - -// A property key to store a client that handles window moves. -DEFINE_LOCAL_WINDOW_PROPERTY_KEY( - CursorClient*, kCursorClientKey, NULL); - -void SetCursorClient(Window* window, CursorClient* client) { - window->SetProperty(kCursorClientKey, client); -} - -CursorClient* GetCursorClient(Window* window) { - return window->GetProperty(kCursorClientKey); -} - -} // namespace client -} // namespace aura
diff --git a/ui/aura/client/cursor_client.h b/ui/aura/client/cursor_client.h deleted file mode 100644 index fc48e03..0000000 --- a/ui/aura/client/cursor_client.h +++ /dev/null
@@ -1,96 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_CLIENT_CURSOR_CLIENT_H_ -#define UI_AURA_CLIENT_CURSOR_CLIENT_H_ - -#include "base/strings/string16.h" -#include "ui/aura/aura_export.h" -#include "ui/base/cursor/cursor.h" -#include "ui/gfx/native_widget_types.h" - -namespace gfx { -class Display; -} - -namespace ui { -class KeyEvent; -} - -namespace aura { -class Window; -namespace client { -class CursorClientObserver; - -// An interface that receives cursor change events. -class AURA_EXPORT CursorClient { - public: - // Notes that |window| has requested the change to |cursor|. - virtual void SetCursor(gfx::NativeCursor cursor) = 0; - - // Returns the current cursor. - virtual gfx::NativeCursor GetCursor() const = 0; - - // Shows the cursor. This does not take effect When mouse events are disabled. - virtual void ShowCursor() = 0; - - // Hides the cursor. Mouse events keep being sent even when the cursor is - // invisible. - virtual void HideCursor() = 0; - - // Sets the type of the mouse cursor icon. - virtual void SetCursorSet(ui::CursorSetType cursor_set) = 0; - - // Gets the type of the mouse cursor icon. - virtual ui::CursorSetType GetCursorSet() const = 0; - - // Gets whether the cursor is visible. - virtual bool IsCursorVisible() const = 0; - - // Makes mouse events start being sent and shows the cursor if it was hidden - // with DisableMouseEvents. - virtual void EnableMouseEvents() = 0; - - // Makes mouse events stop being sent and hides the cursor if it is visible. - virtual void DisableMouseEvents() = 0; - - // Returns true if mouse events are enabled. - virtual bool IsMouseEventsEnabled() const = 0; - - // Sets the display for the cursor. - virtual void SetDisplay(const gfx::Display& display) = 0; - - // Locks the cursor change. The cursor type, cursor visibility, and mouse - // events enable state never change as long as lock is held by anyone. - virtual void LockCursor() = 0; - - // Unlocks the cursor change. If all the locks are released, the cursor type, - // cursor visibility, and mouse events enable state are restored to the ones - // set by the lastest call of SetCursor, ShowCursor/HideCursor, and - // EnableMouseEvents/DisableMouseEvents. - virtual void UnlockCursor() = 0; - - // Returns true if the cursor is locked. - virtual bool IsCursorLocked() const = 0; - - // Used to add or remove a CursorClientObserver. - virtual void AddObserver(CursorClientObserver* observer) = 0; - virtual void RemoveObserver(CursorClientObserver* observer) = 0; - - // Returns true if the mouse cursor should be hidden on |event|. - virtual bool ShouldHideCursorOnKeyEvent(const ui::KeyEvent& event) const = 0; - - protected: - virtual ~CursorClient() {} -}; - -// Sets/Gets the activation client for the specified window. -AURA_EXPORT void SetCursorClient(Window* window, - CursorClient* client); -AURA_EXPORT CursorClient* GetCursorClient(Window* window); - -} // namespace client -} // namespace aura - -#endif // UI_AURA_CLIENT_CURSOR_CLIENT_H_
diff --git a/ui/aura/client/cursor_client_observer.cc b/ui/aura/client/cursor_client_observer.cc deleted file mode 100644 index 6e40e60..0000000 --- a/ui/aura/client/cursor_client_observer.cc +++ /dev/null
@@ -1,7 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// Added to make sure that something is built in aura with this -// include so that the symbol CursorClientObserver is exported. -#include "ui/aura/client/cursor_client_observer.h"
diff --git a/ui/aura/client/cursor_client_observer.h b/ui/aura/client/cursor_client_observer.h deleted file mode 100644 index 1a6d1a8..0000000 --- a/ui/aura/client/cursor_client_observer.h +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_CLIENT_CURSOR_CLIENT_OBSERVER_H_ -#define UI_AURA_CLIENT_CURSOR_CLIENT_OBSERVER_H_ - -#include "ui/aura/aura_export.h" - -namespace aura { -namespace client { - -class AURA_EXPORT CursorClientObserver { - public: - virtual void OnCursorVisibilityChanged(bool is_visible) = 0; - - protected: - virtual ~CursorClientObserver() {} -}; - -} // namespace client -} // namespace aura - -#endif // UI_AURA_CLIENT_CURSOR_CLIENT_OBSERVER_H_
diff --git a/ui/aura/client/default_capture_client.cc b/ui/aura/client/default_capture_client.cc deleted file mode 100644 index 69632d8..0000000 --- a/ui/aura/client/default_capture_client.cc +++ /dev/null
@@ -1,59 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/client/default_capture_client.h" - -#include "ui/aura/window.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/aura/window_tree_host.h" - -namespace aura { -namespace client { - -DefaultCaptureClient::DefaultCaptureClient(Window* root_window) - : root_window_(root_window), - capture_window_(NULL) { - SetCaptureClient(root_window_, this); -} - -DefaultCaptureClient::~DefaultCaptureClient() { - SetCaptureClient(root_window_, NULL); -} - -void DefaultCaptureClient::SetCapture(Window* window) { - if (capture_window_ == window) - return; - if (window) { - ui::GestureRecognizer::Get()->TransferEventsTo( - capture_window_, window); - } - - Window* old_capture_window = capture_window_; - capture_window_ = window; - - CaptureDelegate* capture_delegate = root_window_->GetHost()->dispatcher(); - if (capture_window_) - capture_delegate->SetNativeCapture(); - else - capture_delegate->ReleaseNativeCapture(); - - capture_delegate->UpdateCapture(old_capture_window, capture_window_); -} - -void DefaultCaptureClient::ReleaseCapture(Window* window) { - if (capture_window_ != window) - return; - SetCapture(NULL); -} - -Window* DefaultCaptureClient::GetCaptureWindow() { - return capture_window_; -} - -Window* DefaultCaptureClient::GetGlobalCaptureWindow() { - return capture_window_; -} - -} // namespace client -} // namespace aura
diff --git a/ui/aura/client/default_capture_client.h b/ui/aura/client/default_capture_client.h deleted file mode 100644 index 41194af..0000000 --- a/ui/aura/client/default_capture_client.h +++ /dev/null
@@ -1,37 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_CLIENT_DEFAULT_CAPTURE_CLIENT_H_ -#define UI_AURA_CLIENT_DEFAULT_CAPTURE_CLIENT_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "ui/aura/aura_export.h" -#include "ui/aura/client/capture_client.h" - -namespace aura { -namespace client { - -class AURA_EXPORT DefaultCaptureClient : public client::CaptureClient { - public: - explicit DefaultCaptureClient(Window* root_window); - virtual ~DefaultCaptureClient(); - - private: - // Overridden from client::CaptureClient: - virtual void SetCapture(Window* window) override; - virtual void ReleaseCapture(Window* window) override; - virtual Window* GetCaptureWindow() override; - virtual Window* GetGlobalCaptureWindow() override; - - Window* root_window_; - Window* capture_window_; - - DISALLOW_COPY_AND_ASSIGN(DefaultCaptureClient); -}; - -} // namespace client -} // namespace aura - -#endif // UI_AURA_CLIENT_DEFAULT_CAPTURE_CLIENT_H_
diff --git a/ui/aura/client/event_client.cc b/ui/aura/client/event_client.cc deleted file mode 100644 index d6da07e..0000000 --- a/ui/aura/client/event_client.cc +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/client/event_client.h" - -#include "ui/aura/window_event_dispatcher.h" -#include "ui/aura/window_property.h" - -DECLARE_WINDOW_PROPERTY_TYPE(aura::client::EventClient*) - -namespace aura { -namespace client { - -DEFINE_WINDOW_PROPERTY_KEY(EventClient*, kRootWindowEventClientKey, NULL); - -void SetEventClient(Window* root_window, EventClient* client) { - DCHECK_EQ(root_window->GetRootWindow(), root_window); - root_window->SetProperty(kRootWindowEventClientKey, client); -} - -EventClient* GetEventClient(const Window* root_window) { - if (root_window) - DCHECK_EQ(root_window->GetRootWindow(), root_window); - return root_window ? - root_window->GetProperty(kRootWindowEventClientKey) : NULL; -} - -} // namespace client -} // namespace aura
diff --git a/ui/aura/client/event_client.h b/ui/aura/client/event_client.h deleted file mode 100644 index 3ce88e3..0000000 --- a/ui/aura/client/event_client.h +++ /dev/null
@@ -1,38 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_CLIENT_EVENT_CLIENT_H_ -#define UI_AURA_CLIENT_EVENT_CLIENT_H_ - -#include "ui/aura/aura_export.h" - -namespace ui { -class EventTarget; -} - -namespace aura { -class Window; -namespace client { - -// An interface implemented by an object that alters event processing. -class AURA_EXPORT EventClient { - public: - // Returns true if events can be processed by |window| or any of its children. - virtual bool CanProcessEventsWithinSubtree(const Window* window) const = 0; - - // Returns the top level EventTarget for the current environment. - virtual ui::EventTarget* GetToplevelEventTarget() = 0; - - protected: - virtual ~EventClient() {} -}; - -// Sets/Gets the event client on the root Window. -AURA_EXPORT void SetEventClient(Window* root_window, EventClient* client); -AURA_EXPORT EventClient* GetEventClient(const Window* root_window); - -} // namespace clients -} // namespace aura - -#endif // UI_AURA_CLIENT_EVENT_CLIENT_H_
diff --git a/ui/aura/client/focus_change_observer.cc b/ui/aura/client/focus_change_observer.cc deleted file mode 100644 index 8db471d..0000000 --- a/ui/aura/client/focus_change_observer.cc +++ /dev/null
@@ -1,28 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/client/focus_change_observer.h" - -#include "ui/aura/window.h" -#include "ui/aura/window_property.h" - -DECLARE_WINDOW_PROPERTY_TYPE(aura::client::FocusChangeObserver*) - -namespace aura { -namespace client { - -DEFINE_LOCAL_WINDOW_PROPERTY_KEY( - FocusChangeObserver*, kFocusChangeObserverKey, NULL); - -FocusChangeObserver* GetFocusChangeObserver(Window* window) { - return window ? window->GetProperty(kFocusChangeObserverKey) : NULL; -} - -void SetFocusChangeObserver(Window* window, - FocusChangeObserver* focus_change_observer) { - window->SetProperty(kFocusChangeObserverKey, focus_change_observer); -} - -} // namespace client -} // namespace aura
diff --git a/ui/aura/client/focus_change_observer.h b/ui/aura/client/focus_change_observer.h deleted file mode 100644 index 46db114..0000000 --- a/ui/aura/client/focus_change_observer.h +++ /dev/null
@@ -1,33 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_CLIENT_FOCUS_CHANGE_OBSERVER_H_ -#define UI_AURA_CLIENT_FOCUS_CHANGE_OBSERVER_H_ - -#include "ui/aura/aura_export.h" - -namespace aura { -class Window; -namespace client { - -// TODO(beng): this interface will be OBSOLETE by FocusChangeEvent. -class AURA_EXPORT FocusChangeObserver { - public: - // Called when focus moves from |lost_focus| to |gained_focus|. - virtual void OnWindowFocused(Window* gained_focus, Window* lost_focus) = 0; - - protected: - virtual ~FocusChangeObserver() {} -}; - -AURA_EXPORT FocusChangeObserver* GetFocusChangeObserver(Window* window); -AURA_EXPORT void SetFocusChangeObserver( - Window* window, - FocusChangeObserver* focus_change_observer); - - -} // namespace client -} // namespace aura - -#endif // UI_AURA_CLIENT_FOCUS_CHANGE_OBSERVER_H_
diff --git a/ui/aura/client/focus_client.cc b/ui/aura/client/focus_client.cc deleted file mode 100644 index 1f24a80..0000000 --- a/ui/aura/client/focus_client.cc +++ /dev/null
@@ -1,34 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/client/focus_client.h" - -#include "ui/aura/window_event_dispatcher.h" -#include "ui/aura/window_property.h" - -DECLARE_EXPORTED_WINDOW_PROPERTY_TYPE(AURA_EXPORT, aura::Window*) -DECLARE_WINDOW_PROPERTY_TYPE(aura::client::FocusClient*) - -namespace aura { -namespace client { - -DEFINE_WINDOW_PROPERTY_KEY(FocusClient*, kRootWindowFocusClientKey, NULL); - -void SetFocusClient(Window* root_window, FocusClient* client) { - DCHECK_EQ(root_window->GetRootWindow(), root_window); - root_window->SetProperty(kRootWindowFocusClientKey, client); -} - -FocusClient* GetFocusClient(Window* window) { - return GetFocusClient(static_cast<const Window*>(window)); -} - -FocusClient* GetFocusClient(const Window* window) { - const Window* root_window = window->GetRootWindow(); - return root_window ? - root_window->GetProperty(kRootWindowFocusClientKey) : NULL; -} - -} // namespace client -} // namespace aura
diff --git a/ui/aura/client/focus_client.h b/ui/aura/client/focus_client.h deleted file mode 100644 index cec64ec..0000000 --- a/ui/aura/client/focus_client.h +++ /dev/null
@@ -1,46 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_CLIENT_FOCUS_CLIENT_H_ -#define UI_AURA_CLIENT_FOCUS_CLIENT_H_ - -#include "ui/aura/aura_export.h" - -namespace ui { -class Event; -} - -namespace aura { -class Window; -namespace client { -class FocusChangeObserver; - -// An interface implemented by an object that manages window focus. -class AURA_EXPORT FocusClient { - public: - virtual ~FocusClient() {} - - virtual void AddObserver(FocusChangeObserver* observer) = 0; - virtual void RemoveObserver(FocusChangeObserver* observer) = 0; - - // Focuses |window|. Passing NULL clears focus. - virtual void FocusWindow(Window* window) = 0; - - // Sets focus to |window| if it's within the active window. Not intended as a - // general purpose API, use FocusWindow() instead. - virtual void ResetFocusWithinActiveWindow(Window* window) = 0; - - // Retrieves the focused window, or NULL if there is none. - virtual Window* GetFocusedWindow() = 0; -}; - -// Sets/Gets the focus client on the root Window. -AURA_EXPORT void SetFocusClient(Window* root_window, FocusClient* client); -AURA_EXPORT FocusClient* GetFocusClient(Window* window); -AURA_EXPORT FocusClient* GetFocusClient(const Window* window); - -} // namespace clients -} // namespace aura - -#endif // UI_AURA_CLIENT_FOCUS_CLIENT_H_
diff --git a/ui/aura/client/screen_position_client.cc b/ui/aura/client/screen_position_client.cc deleted file mode 100644 index 6415376..0000000 --- a/ui/aura/client/screen_position_client.cc +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/client/screen_position_client.h" - -#include "ui/aura/window_property.h" - -DECLARE_WINDOW_PROPERTY_TYPE(aura::client::ScreenPositionClient*) - -namespace aura { -namespace client { - -DEFINE_LOCAL_WINDOW_PROPERTY_KEY(ScreenPositionClient*, - kScreenPositionClientKey, - NULL); - -void SetScreenPositionClient(Window* root_window, - ScreenPositionClient* client) { - DCHECK_EQ(root_window->GetRootWindow(), root_window); - root_window->SetProperty(kScreenPositionClientKey, client); -} - -ScreenPositionClient* GetScreenPositionClient(const Window* root_window) { - if (root_window) - DCHECK_EQ(root_window->GetRootWindow(), root_window); - return root_window ? - root_window->GetProperty(kScreenPositionClientKey) : NULL; -} - -} // namespace client -} // namespace aura
diff --git a/ui/aura/client/screen_position_client.h b/ui/aura/client/screen_position_client.h deleted file mode 100644 index 9dceb22..0000000 --- a/ui/aura/client/screen_position_client.h +++ /dev/null
@@ -1,55 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_SCREEN_POSITION_CLIENT_H_ -#define UI_AURA_SCREEN_POSITION_CLIENT_H_ - -#include "ui/aura/aura_export.h" -#include "ui/aura/window.h" - -namespace gfx { -class Display; -class Rect; -} - -namespace aura { -class Window; -namespace client { - -// An interface implemented by an object that changes coordinates within a root -// Window into system coordinates. -class AURA_EXPORT ScreenPositionClient { - public: - virtual ~ScreenPositionClient() {} - - // Converts the |screen_point| from a given |window|'s coordinate space - // into screen coordinate space. - virtual void ConvertPointToScreen(const Window* window, - gfx::Point* point) = 0; - virtual void ConvertPointFromScreen(const Window* window, - gfx::Point* point) = 0; - // Converts the |screen_point| from root window host's coordinate of - // into screen coordinate space. - // A typical example of using this function instead of ConvertPointToScreen is - // when X's native input is captured by a drag operation. - // See the comments for ash::GetRootWindowRelativeToWindow for details. - virtual void ConvertHostPointToScreen(Window* root_window, - gfx::Point* point) = 0; - // Sets the bounds of the window. The implementation is responsible - // for finding out and translating the right coordinates for the |window|. - virtual void SetBounds(Window* window, - const gfx::Rect& bounds, - const gfx::Display& display) = 0; -}; - -// Sets/Gets the activation client on the Window. -AURA_EXPORT void SetScreenPositionClient(Window* root_window, - ScreenPositionClient* client); -AURA_EXPORT ScreenPositionClient* GetScreenPositionClient( - const Window* root_window); - -} // namespace clients -} // namespace aura - -#endif // UI_AURA_SCREEN_POSITION_CLIENT_H_
diff --git a/ui/aura/client/visibility_client.cc b/ui/aura/client/visibility_client.cc deleted file mode 100644 index 853c034..0000000 --- a/ui/aura/client/visibility_client.cc +++ /dev/null
@@ -1,35 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/client/visibility_client.h" - -#include "ui/aura/window_event_dispatcher.h" -#include "ui/aura/window_property.h" - -DECLARE_WINDOW_PROPERTY_TYPE(aura::client::VisibilityClient*) - -namespace aura { -namespace client { - -// A property key to store a client that handles window visibility changes. -DEFINE_LOCAL_WINDOW_PROPERTY_KEY( - VisibilityClient*, kWindowVisibilityClientKey, NULL); - - -void SetVisibilityClient(Window* window, VisibilityClient* client) { - window->SetProperty(kWindowVisibilityClientKey, client); -} - -VisibilityClient* GetVisibilityClient(Window* window) { - VisibilityClient* visibility_client = NULL; - aura::Window* current = window; - do { - visibility_client = current->GetProperty(kWindowVisibilityClientKey); - current = current->parent(); - } while (current && !visibility_client); - return visibility_client; -} - -} // namespace client -} // namespace aura
diff --git a/ui/aura/client/visibility_client.h b/ui/aura/client/visibility_client.h deleted file mode 100644 index b36cddc..0000000 --- a/ui/aura/client/visibility_client.h +++ /dev/null
@@ -1,37 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_CLIENT_VISIBILITY_CLIENT_H_ -#define UI_AURA_CLIENT_VISIBILITY_CLIENT_H_ - -#include "ui/aura/aura_export.h" - -namespace aura { -class Window; -namespace client { - -// An interface implemented by an object that manages the visibility of Windows' -// layers as Window visibility changes. -class AURA_EXPORT VisibilityClient { - public: - // Called when |window|'s visibility is changing to |visible|. The implementor - // can decide whether or not to pass on the visibility to the underlying - // layer. - virtual void UpdateLayerVisibility(Window* window, bool visible) = 0; - - protected: - virtual ~VisibilityClient() {} -}; - -// Sets the VisibilityClient on the Window. -AURA_EXPORT void SetVisibilityClient(Window* window, VisibilityClient* client); - -// Gets the VisibilityClient for the window. This will crawl up |window|'s -// hierarchy until it finds one. -AURA_EXPORT VisibilityClient* GetVisibilityClient(Window* window); - -} // namespace clients -} // namespace aura - -#endif // UI_AURA_CLIENT_VISIBILITY_CLIENT_H_
diff --git a/ui/aura/client/window_stacking_client.cc b/ui/aura/client/window_stacking_client.cc deleted file mode 100644 index 8f90976..0000000 --- a/ui/aura/client/window_stacking_client.cc +++ /dev/null
@@ -1,25 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/client/window_stacking_client.h" - -namespace aura { -namespace client { - -namespace { - -WindowStackingClient* instance = NULL; - -} // namespace - -void SetWindowStackingClient(WindowStackingClient* client) { - instance = client; -} - -WindowStackingClient* GetWindowStackingClient() { - return instance; -} - -} // namespace client -} // namespace aura
diff --git a/ui/aura/client/window_stacking_client.h b/ui/aura/client/window_stacking_client.h deleted file mode 100644 index 8482603..0000000 --- a/ui/aura/client/window_stacking_client.h +++ /dev/null
@@ -1,39 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_CLIENT_WINDOW_STACKING_CLIENT_H_ -#define UI_AURA_CLIENT_WINDOW_STACKING_CLIENT_H_ - -#include "base/basictypes.h" -#include "base/memory/scoped_ptr.h" -#include "ui/aura/aura_export.h" -#include "ui/aura/window.h" - -namespace aura { -namespace client { - -class AURA_EXPORT WindowStackingClient { - public: - // Invoked from the various Window stacking functions. Allows the - // WindowStackingClient to alter the source, target and/or direction to stack. - // Returns true if stacking should continue; false if the stacking should not - // happen. - virtual bool AdjustStacking(Window** child, - Window** target, - Window::StackDirection* direction) = 0; - - protected: - virtual ~WindowStackingClient() {} -}; - -// Sets/gets the WindowStackingClient. This does *not* take ownership of -// |client|. It is assumed the caller will invoke SetWindowStackingClient(NULL) -// before deleting |client|. -AURA_EXPORT void SetWindowStackingClient(WindowStackingClient* client); -AURA_EXPORT WindowStackingClient* GetWindowStackingClient(); - -} // namespace client -} // namespace aura - -#endif // UI_AURA_CLIENT_WINDOW_STACKING_CLIENT_H_
diff --git a/ui/aura/client/window_tree_client.cc b/ui/aura/client/window_tree_client.cc deleted file mode 100644 index 1b263c3..0000000 --- a/ui/aura/client/window_tree_client.cc +++ /dev/null
@@ -1,51 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/client/window_tree_client.h" - -#include "ui/aura/env.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/aura/window_property.h" - -DECLARE_WINDOW_PROPERTY_TYPE(aura::client::WindowTreeClient*) - -namespace aura { -namespace client { - -DEFINE_WINDOW_PROPERTY_KEY( - WindowTreeClient*, kRootWindowWindowTreeClientKey, NULL); - -void SetWindowTreeClient(Window* window, WindowTreeClient* window_tree_client) { - DCHECK(window); - - Window* root_window = window->GetRootWindow(); - DCHECK(root_window); - root_window->SetProperty(kRootWindowWindowTreeClientKey, window_tree_client); -} - -WindowTreeClient* GetWindowTreeClient(Window* window) { - DCHECK(window); - Window* root_window = window->GetRootWindow(); - DCHECK(root_window); - WindowTreeClient* client = - root_window->GetProperty(kRootWindowWindowTreeClientKey); - DCHECK(client); - return client; -} - -void ParentWindowWithContext(Window* window, - Window* context, - const gfx::Rect& screen_bounds) { - DCHECK(context); - - // |context| must be attached to a hierarchy with a WindowTreeClient. - WindowTreeClient* client = GetWindowTreeClient(context); - DCHECK(client); - Window* default_parent = - client->GetDefaultParent(context, window, screen_bounds); - default_parent->AddChild(window); -} - -} // namespace client -} // namespace aura
diff --git a/ui/aura/client/window_tree_client.h b/ui/aura/client/window_tree_client.h deleted file mode 100644 index 59cb132..0000000 --- a/ui/aura/client/window_tree_client.h +++ /dev/null
@@ -1,56 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_CLIENT_WINDOW_TREE_CLIENT_H_ -#define UI_AURA_CLIENT_WINDOW_TREE_CLIENT_H_ - -#include "ui/aura/aura_export.h" - -namespace gfx { -class Rect; -} - -namespace aura { -class Window; -namespace client { - -// Implementations of this object are used to help locate a default parent for -// NULL-parented Windows. -class AURA_EXPORT WindowTreeClient { - public: - virtual ~WindowTreeClient() {} - - // Called by the Window when it looks for a default parent. Returns the - // window that |window| should be added to instead. |context| provides a - // Window (generally a RootWindow) that can be used to determine which - // desktop type the default parent should be chosen from. NOTE: this may - // have side effects. It should only be used when |window| is going to be - // immediately added. - // - // TODO(erg): Remove |context|, and maybe after oshima's patch lands, - // |bounds|. - virtual Window* GetDefaultParent( - Window* context, - Window* window, - const gfx::Rect& bounds) = 0; -}; - -// Set/Get a window tree client for the RootWindow containing |window|. |window| -// must not be NULL. -AURA_EXPORT void SetWindowTreeClient(Window* window, - WindowTreeClient* window_tree_client); -WindowTreeClient* GetWindowTreeClient(Window* window); - -// Adds |window| to an appropriate parent by consulting an implementation of -// WindowTreeClient attached at the root Window containing |context|. The final -// location may be a window hierarchy other than the one supplied via -// |context|, which must not be NULL. |screen_bounds| may be empty. -AURA_EXPORT void ParentWindowWithContext(Window* window, - Window* context, - const gfx::Rect& screen_bounds); - -} // namespace client -} // namespace aura - -#endif // UI_AURA_CLIENT_WINDOW_TREE_CLIENT_H_
diff --git a/ui/aura/demo/DEPS b/ui/aura/demo/DEPS deleted file mode 100644 index 07d8243..0000000 --- a/ui/aura/demo/DEPS +++ /dev/null
@@ -1,3 +0,0 @@ -include_rules = [ - "+ui/gl/gl_surface.h", # To initialize GL bindings. -]
diff --git a/ui/aura/demo/demo_main.cc b/ui/aura/demo/demo_main.cc deleted file mode 100644 index ec5ea52..0000000 --- a/ui/aura/demo/demo_main.cc +++ /dev/null
@@ -1,184 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/at_exit.h" -#include "base/command_line.h" -#include "base/i18n/icu_util.h" -#include "base/memory/scoped_ptr.h" -#include "base/message_loop/message_loop.h" -#include "third_party/skia/include/core/SkXfermode.h" -#include "ui/aura/client/default_capture_client.h" -#include "ui/aura/client/window_tree_client.h" -#include "ui/aura/env.h" -#include "ui/aura/test/test_focus_client.h" -#include "ui/aura/test/test_screen.h" -#include "ui/aura/window.h" -#include "ui/aura/window_delegate.h" -#include "ui/aura/window_tree_host.h" -#include "ui/base/hit_test.h" -#include "ui/compositor/test/in_process_context_factory.h" -#include "ui/events/event.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/rect.h" -#include "ui/gl/gl_surface.h" - -#if defined(USE_X11) -#include "ui/gfx/x/x11_connection.h" -#endif - -#if defined(OS_WIN) -#include "ui/gfx/win/dpi.h" -#endif - -namespace { - -// Trivial WindowDelegate implementation that draws a colored background. -class DemoWindowDelegate : public aura::WindowDelegate { - public: - explicit DemoWindowDelegate(SkColor color) : color_(color) {} - - // Overridden from WindowDelegate: - virtual gfx::Size GetMinimumSize() const override { - return gfx::Size(); - } - - virtual gfx::Size GetMaximumSize() const override { - return gfx::Size(); - } - - virtual void OnBoundsChanged(const gfx::Rect& old_bounds, - const gfx::Rect& new_bounds) override {} - virtual gfx::NativeCursor GetCursor(const gfx::Point& point) override { - return gfx::kNullCursor; - } - virtual int GetNonClientComponent(const gfx::Point& point) const override { - return HTCAPTION; - } - virtual bool ShouldDescendIntoChildForEventHandling( - aura::Window* child, - const gfx::Point& location) override { - return true; - } - virtual bool CanFocus() override { return true; } - virtual void OnCaptureLost() override {} - virtual void OnPaint(gfx::Canvas* canvas) override { - canvas->DrawColor(color_, SkXfermode::kSrc_Mode); - } - virtual void OnDeviceScaleFactorChanged(float device_scale_factor) override {} - virtual void OnWindowDestroying(aura::Window* window) override {} - virtual void OnWindowDestroyed(aura::Window* window) override {} - virtual void OnWindowTargetVisibilityChanged(bool visible) override {} - virtual bool HasHitTestMask() const override { return false; } - virtual void GetHitTestMask(gfx::Path* mask) const override {} - - private: - SkColor color_; - - DISALLOW_COPY_AND_ASSIGN(DemoWindowDelegate); -}; - -class DemoWindowTreeClient : public aura::client::WindowTreeClient { - public: - explicit DemoWindowTreeClient(aura::Window* window) : window_(window) { - aura::client::SetWindowTreeClient(window_, this); - } - - virtual ~DemoWindowTreeClient() { - aura::client::SetWindowTreeClient(window_, NULL); - } - - // Overridden from aura::client::WindowTreeClient: - virtual aura::Window* GetDefaultParent(aura::Window* context, - aura::Window* window, - const gfx::Rect& bounds) override { - if (!capture_client_) { - capture_client_.reset( - new aura::client::DefaultCaptureClient(window_->GetRootWindow())); - } - return window_; - } - - private: - aura::Window* window_; - - scoped_ptr<aura::client::DefaultCaptureClient> capture_client_; - - DISALLOW_COPY_AND_ASSIGN(DemoWindowTreeClient); -}; - -int DemoMain() { -#if defined(USE_X11) - // This demo uses InProcessContextFactory which uses X on a separate Gpu - // thread. - gfx::InitializeThreadedX11(); -#endif - - gfx::GLSurface::InitializeOneOff(); - -#if defined(OS_WIN) - gfx::InitDeviceScaleFactor(1.0f); -#endif - - // The ContextFactory must exist before any Compositors are created. - scoped_ptr<ui::InProcessContextFactory> context_factory( - new ui::InProcessContextFactory()); - - // Create the message-loop here before creating the root window. - base::MessageLoopForUI message_loop; - - aura::Env::CreateInstance(true); - aura::Env::GetInstance()->set_context_factory(context_factory.get()); - scoped_ptr<aura::TestScreen> test_screen( - aura::TestScreen::Create(gfx::Size())); - gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE, test_screen.get()); - scoped_ptr<aura::WindowTreeHost> host( - test_screen->CreateHostForPrimaryDisplay()); - scoped_ptr<DemoWindowTreeClient> window_tree_client( - new DemoWindowTreeClient(host->window())); - aura::test::TestFocusClient focus_client; - aura::client::SetFocusClient(host->window(), &focus_client); - - // Create a hierarchy of test windows. - DemoWindowDelegate window_delegate1(SK_ColorBLUE); - aura::Window window1(&window_delegate1); - window1.set_id(1); - window1.Init(aura::WINDOW_LAYER_TEXTURED); - window1.SetBounds(gfx::Rect(100, 100, 400, 400)); - window1.Show(); - aura::client::ParentWindowWithContext(&window1, host->window(), gfx::Rect()); - - DemoWindowDelegate window_delegate2(SK_ColorRED); - aura::Window window2(&window_delegate2); - window2.set_id(2); - window2.Init(aura::WINDOW_LAYER_TEXTURED); - window2.SetBounds(gfx::Rect(200, 200, 350, 350)); - window2.Show(); - aura::client::ParentWindowWithContext(&window2, host->window(), gfx::Rect()); - - DemoWindowDelegate window_delegate3(SK_ColorGREEN); - aura::Window window3(&window_delegate3); - window3.set_id(3); - window3.Init(aura::WINDOW_LAYER_TEXTURED); - window3.SetBounds(gfx::Rect(10, 10, 50, 50)); - window3.Show(); - window2.AddChild(&window3); - - host->Show(); - base::MessageLoopForUI::current()->Run(); - - return 0; -} - -} // namespace - -int main(int argc, char** argv) { - CommandLine::Init(argc, argv); - - // The exit manager is in charge of calling the dtors of singleton objects. - base::AtExitManager exit_manager; - - base::i18n::InitializeICU(); - - return DemoMain(); -}
diff --git a/ui/aura/env.cc b/ui/aura/env.cc deleted file mode 100644 index 636e347..0000000 --- a/ui/aura/env.cc +++ /dev/null
@@ -1,123 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/env.h" - -#include "base/lazy_instance.h" -#include "base/threading/thread_local.h" -#include "ui/aura/env_observer.h" -#include "ui/aura/input_state_lookup.h" -#include "ui/events/event_target_iterator.h" -#include "ui/events/platform/platform_event_source.h" - -#if defined(USE_OZONE) -#include "ui/ozone/public/ozone_platform.h" -#endif - -namespace aura { - -namespace { - -// Env is thread local so that aura may be used on multiple threads. -base::LazyInstance<base::ThreadLocalPointer<Env> >::Leaky lazy_tls_ptr = - LAZY_INSTANCE_INITIALIZER; - -} // namespace - -//////////////////////////////////////////////////////////////////////////////// -// Env, public: - -// static -void Env::CreateInstance(bool create_event_source) { - if (!lazy_tls_ptr.Pointer()->Get()) - (new Env())->Init(create_event_source); -} - -// static -Env* Env::GetInstance() { - Env* env = lazy_tls_ptr.Pointer()->Get(); - DCHECK(env) << "Env::CreateInstance must be called before getting the " - "instance of Env."; - return env; -} - -// static -void Env::DeleteInstance() { - delete lazy_tls_ptr.Pointer()->Get(); -} - -void Env::AddObserver(EnvObserver* observer) { - observers_.AddObserver(observer); -} - -void Env::RemoveObserver(EnvObserver* observer) { - observers_.RemoveObserver(observer); -} - -bool Env::IsMouseButtonDown() const { - return input_state_lookup_.get() ? input_state_lookup_->IsMouseButtonDown() : - mouse_button_flags_ != 0; -} - -//////////////////////////////////////////////////////////////////////////////// -// Env, private: - -Env::Env() - : mouse_button_flags_(0), - is_touch_down_(false), - input_state_lookup_(InputStateLookup::Create().Pass()), - context_factory_(NULL) { - DCHECK(lazy_tls_ptr.Pointer()->Get() == NULL); - lazy_tls_ptr.Pointer()->Set(this); -} - -Env::~Env() { - FOR_EACH_OBSERVER(EnvObserver, observers_, OnWillDestroyEnv()); - DCHECK_EQ(this, lazy_tls_ptr.Pointer()->Get()); - lazy_tls_ptr.Pointer()->Set(NULL); -} - -void Env::Init(bool create_event_source) { -#if defined(USE_OZONE) - // The ozone platform can provide its own event source. So initialize the - // platform before creating the default event source. - ui::OzonePlatform::InitializeForUI(); -#endif - if (create_event_source && !ui::PlatformEventSource::GetInstance()) - event_source_ = ui::PlatformEventSource::CreateDefault(); -} - -void Env::NotifyWindowInitialized(Window* window) { - FOR_EACH_OBSERVER(EnvObserver, observers_, OnWindowInitialized(window)); -} - -void Env::NotifyHostInitialized(WindowTreeHost* host) { - FOR_EACH_OBSERVER(EnvObserver, observers_, OnHostInitialized(host)); -} - -void Env::NotifyHostActivated(WindowTreeHost* host) { - FOR_EACH_OBSERVER(EnvObserver, observers_, OnHostActivated(host)); -} - -//////////////////////////////////////////////////////////////////////////////// -// Env, ui::EventTarget implementation: - -bool Env::CanAcceptEvent(const ui::Event& event) { - return true; -} - -ui::EventTarget* Env::GetParentTarget() { - return NULL; -} - -scoped_ptr<ui::EventTargetIterator> Env::GetChildIterator() { - return scoped_ptr<ui::EventTargetIterator>(); -} - -ui::EventTargeter* Env::GetEventTargeter() { - NOTREACHED(); - return NULL; -} - -} // namespace aura
diff --git a/ui/aura/env.h b/ui/aura/env.h deleted file mode 100644 index 7c5d200..0000000 --- a/ui/aura/env.h +++ /dev/null
@@ -1,112 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_ENV_H_ -#define UI_AURA_ENV_H_ - -#include "base/memory/scoped_ptr.h" -#include "base/observer_list.h" -#include "base/supports_user_data.h" -#include "ui/aura/aura_export.h" -#include "ui/events/event_handler.h" -#include "ui/events/event_target.h" -#include "ui/gfx/point.h" - -namespace ui { -class ContextFactory; -class PlatformEventSource; -} -namespace aura { - -namespace test { -class EnvTestHelper; -} - -class EnvObserver; -class InputStateLookup; -class Window; -class WindowTreeHost; - -// A singleton object that tracks general state within Aura. -class AURA_EXPORT Env : public ui::EventTarget, public base::SupportsUserData { - public: - // Creates the single Env instance (if it hasn't been created yet). If - // |create_event_source| is true a PlatformEventSource is created. - // TODO(sky): nuke |create_event_source|. Only necessary while mojo's - // nativeviewportservice lives in the same process as the viewmanager. - static void CreateInstance(bool create_event_source); - static Env* GetInstance(); - static void DeleteInstance(); - - void AddObserver(EnvObserver* observer); - void RemoveObserver(EnvObserver* observer); - - int mouse_button_flags() const { return mouse_button_flags_; } - void set_mouse_button_flags(int mouse_button_flags) { - mouse_button_flags_ = mouse_button_flags; - } - // Returns true if a mouse button is down. This may query the native OS, - // otherwise it uses |mouse_button_flags_|. - bool IsMouseButtonDown() const; - - // Gets/sets the last mouse location seen in a mouse event in the screen - // coordinates. - const gfx::Point& last_mouse_location() const { return last_mouse_location_; } - void set_last_mouse_location(const gfx::Point& last_mouse_location) { - last_mouse_location_ = last_mouse_location; - } - - // Whether any touch device is currently down. - bool is_touch_down() const { return is_touch_down_; } - void set_touch_down(bool value) { is_touch_down_ = value; } - - void set_context_factory(ui::ContextFactory* context_factory) { - context_factory_ = context_factory; - } - ui::ContextFactory* context_factory() { return context_factory_; } - - private: - friend class test::EnvTestHelper; - friend class Window; - friend class WindowTreeHost; - - Env(); - virtual ~Env(); - - // See description of CreateInstance() for deatils of |create_event_source|. - void Init(bool create_event_source); - - // Called by the Window when it is initialized. Notifies observers. - void NotifyWindowInitialized(Window* window); - - // Called by the WindowTreeHost when it is initialized. Notifies observers. - void NotifyHostInitialized(WindowTreeHost* host); - - // Invoked by WindowTreeHost when it is activated. Notifies observers. - void NotifyHostActivated(WindowTreeHost* host); - - // Overridden from ui::EventTarget: - virtual bool CanAcceptEvent(const ui::Event& event) override; - virtual ui::EventTarget* GetParentTarget() override; - virtual scoped_ptr<ui::EventTargetIterator> GetChildIterator() override; - virtual ui::EventTargeter* GetEventTargeter() override; - - ObserverList<EnvObserver> observers_; - - int mouse_button_flags_; - // Location of last mouse event, in screen coordinates. - gfx::Point last_mouse_location_; - bool is_touch_down_; - - scoped_ptr<InputStateLookup> input_state_lookup_; - scoped_ptr<ui::PlatformEventSource> event_source_; - - ui::ContextFactory* context_factory_; - - DISALLOW_COPY_AND_ASSIGN(Env); -}; - -} // namespace aura - -#endif // UI_AURA_ENV_H_
diff --git a/ui/aura/env_observer.h b/ui/aura/env_observer.h deleted file mode 100644 index 51a6946..0000000 --- a/ui/aura/env_observer.h +++ /dev/null
@@ -1,35 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_ENV_OBSERVER_H_ -#define UI_AURA_ENV_OBSERVER_H_ - -#include "ui/aura/aura_export.h" - -namespace aura { - -class Window; -class WindowTreeHost; - -class AURA_EXPORT EnvObserver { - public: - // Called when |window| has been initialized. - virtual void OnWindowInitialized(Window* window) = 0; - - // Called when a WindowTreeHost is initialized. - virtual void OnHostInitialized(WindowTreeHost* host) {}; - - // Called when a WindowTreeHost is activated. - virtual void OnHostActivated(WindowTreeHost* host) {} - - // Called right before Env is destroyed. - virtual void OnWillDestroyEnv() {} - - protected: - virtual ~EnvObserver() {} -}; - -} // namespace aura - -#endif // UI_AURA_ENV_OBSERVER_H_
diff --git a/ui/aura/gestures/OWNERS b/ui/aura/gestures/OWNERS deleted file mode 100644 index 92704b0..0000000 --- a/ui/aura/gestures/OWNERS +++ /dev/null
@@ -1,3 +0,0 @@ -rjkroege@chromium.org -sadrul@chromium.org -tdresser@chromium.org
diff --git a/ui/aura/gestures/gesture_recognizer_unittest.cc b/ui/aura/gestures/gesture_recognizer_unittest.cc deleted file mode 100644 index f1b51d8..0000000 --- a/ui/aura/gestures/gesture_recognizer_unittest.cc +++ /dev/null
@@ -1,4315 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/command_line.h" -#include "base/memory/scoped_vector.h" -#include "base/run_loop.h" -#include "base/strings/string_number_conversions.h" -#include "base/timer/timer.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/aura/env.h" -#include "ui/aura/test/aura_test_base.h" -#include "ui/aura/test/test_window_delegate.h" -#include "ui/aura/test/test_windows.h" -#include "ui/aura/window.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/base/hit_test.h" -#include "ui/base/ui_base_switches.h" -#include "ui/events/event.h" -#include "ui/events/event_switches.h" -#include "ui/events/event_utils.h" -#include "ui/events/gestures/gesture_configuration.h" -#include "ui/events/gestures/gesture_recognizer_impl.h" -#include "ui/events/gestures/gesture_types.h" -#include "ui/events/test/event_generator.h" -#include "ui/events/test/events_test_utils.h" -#include "ui/gfx/point.h" -#include "ui/gfx/rect.h" - -#include <queue> - -namespace aura { -namespace test { - -namespace { - -std::string WindowIDAsString(ui::GestureConsumer* consumer) { - return consumer ? - base::IntToString(static_cast<Window*>(consumer)->id()) : "?"; -} - -#define EXPECT_0_EVENTS(events) \ - EXPECT_EQ(0u, events.size()) - -#define EXPECT_1_EVENT(events, e0) \ - EXPECT_EQ(1u, events.size()); \ - EXPECT_EQ(e0, events[0]) - -#define EXPECT_2_EVENTS(events, e0, e1) \ - EXPECT_EQ(2u, events.size()); \ - EXPECT_EQ(e0, events[0]); \ - EXPECT_EQ(e1, events[1]) - -#define EXPECT_3_EVENTS(events, e0, e1, e2) \ - EXPECT_EQ(3u, events.size()); \ - EXPECT_EQ(e0, events[0]); \ - EXPECT_EQ(e1, events[1]); \ - EXPECT_EQ(e2, events[2]) - -#define EXPECT_4_EVENTS(events, e0, e1, e2, e3) \ - EXPECT_EQ(4u, events.size()); \ - EXPECT_EQ(e0, events[0]); \ - EXPECT_EQ(e1, events[1]); \ - EXPECT_EQ(e2, events[2]); \ - EXPECT_EQ(e3, events[3]) - -// A delegate that keeps track of gesture events. -class GestureEventConsumeDelegate : public TestWindowDelegate { - public: - GestureEventConsumeDelegate() - : tap_(false), - tap_down_(false), - tap_cancel_(false), - begin_(false), - end_(false), - scroll_begin_(false), - scroll_update_(false), - scroll_end_(false), - pinch_begin_(false), - pinch_update_(false), - pinch_end_(false), - long_press_(false), - fling_(false), - two_finger_tap_(false), - show_press_(false), - swipe_left_(false), - swipe_right_(false), - swipe_up_(false), - swipe_down_(false), - scroll_x_(0), - scroll_y_(0), - scroll_velocity_x_(0), - scroll_velocity_y_(0), - velocity_x_(0), - velocity_y_(0), - scroll_x_hint_(0), - scroll_y_hint_(0), - tap_count_(0), - flags_(0), - wait_until_event_(ui::ET_UNKNOWN) {} - - virtual ~GestureEventConsumeDelegate() {} - - void Reset() { - events_.clear(); - tap_ = false; - tap_down_ = false; - tap_cancel_ = false; - begin_ = false; - end_ = false; - scroll_begin_ = false; - scroll_update_ = false; - scroll_end_ = false; - pinch_begin_ = false; - pinch_update_ = false; - pinch_end_ = false; - long_press_ = false; - fling_ = false; - two_finger_tap_ = false; - show_press_ = false; - swipe_left_ = false; - swipe_right_ = false; - swipe_up_ = false; - swipe_down_ = false; - - scroll_begin_position_.SetPoint(0, 0); - tap_location_.SetPoint(0, 0); - gesture_end_location_.SetPoint(0, 0); - - scroll_x_ = 0; - scroll_y_ = 0; - scroll_velocity_x_ = 0; - scroll_velocity_y_ = 0; - velocity_x_ = 0; - velocity_y_ = 0; - scroll_x_hint_ = 0; - scroll_y_hint_ = 0; - tap_count_ = 0; - scale_ = 0; - flags_ = 0; - latency_info_.Clear(); - } - - const std::vector<ui::EventType>& events() const { return events_; }; - - bool tap() const { return tap_; } - bool tap_down() const { return tap_down_; } - bool tap_cancel() const { return tap_cancel_; } - bool begin() const { return begin_; } - bool end() const { return end_; } - bool scroll_begin() const { return scroll_begin_; } - bool scroll_update() const { return scroll_update_; } - bool scroll_end() const { return scroll_end_; } - bool pinch_begin() const { return pinch_begin_; } - bool pinch_update() const { return pinch_update_; } - bool pinch_end() const { return pinch_end_; } - bool long_press() const { return long_press_; } - bool long_tap() const { return long_tap_; } - bool fling() const { return fling_; } - bool two_finger_tap() const { return two_finger_tap_; } - bool show_press() const { return show_press_; } - bool swipe_left() const { return swipe_left_; } - bool swipe_right() const { return swipe_right_; } - bool swipe_up() const { return swipe_up_; } - bool swipe_down() const { return swipe_down_; } - - const gfx::Point& scroll_begin_position() const { - return scroll_begin_position_; - } - - const gfx::Point& tap_location() const { - return tap_location_; - } - - const gfx::Point& gesture_end_location() const { - return gesture_end_location_; - } - - float scroll_x() const { return scroll_x_; } - float scroll_y() const { return scroll_y_; } - float scroll_velocity_x() const { return scroll_velocity_x_; } - float scroll_velocity_y() const { return scroll_velocity_y_; } - float velocity_x() const { return velocity_x_; } - float velocity_y() const { return velocity_y_; } - float scroll_x_hint() const { return scroll_x_hint_; } - float scroll_y_hint() const { return scroll_y_hint_; } - float scale() const { return scale_; } - const gfx::Rect& bounding_box() const { return bounding_box_; } - int tap_count() const { return tap_count_; } - int flags() const { return flags_; } - const ui::LatencyInfo& latency_info() const { return latency_info_; } - - void WaitUntilReceivedGesture(ui::EventType type) { - wait_until_event_ = type; - run_loop_.reset(new base::RunLoop()); - run_loop_->Run(); - } - - virtual void OnGestureEvent(ui::GestureEvent* gesture) override { - events_.push_back(gesture->type()); - bounding_box_ = gesture->details().bounding_box(); - flags_ = gesture->flags(); - latency_info_ = *gesture->latency(); - switch (gesture->type()) { - case ui::ET_GESTURE_TAP: - tap_location_ = gesture->location(); - tap_count_ = gesture->details().tap_count(); - tap_ = true; - break; - case ui::ET_GESTURE_TAP_DOWN: - tap_down_ = true; - break; - case ui::ET_GESTURE_TAP_CANCEL: - tap_cancel_ = true; - break; - case ui::ET_GESTURE_BEGIN: - begin_ = true; - break; - case ui::ET_GESTURE_END: - end_ = true; - gesture_end_location_ = gesture->location(); - break; - case ui::ET_GESTURE_SCROLL_BEGIN: - scroll_begin_ = true; - scroll_begin_position_ = gesture->location(); - scroll_x_hint_ = gesture->details().scroll_x_hint(); - scroll_y_hint_ = gesture->details().scroll_y_hint(); - break; - case ui::ET_GESTURE_SCROLL_UPDATE: - scroll_update_ = true; - scroll_x_ += gesture->details().scroll_x(); - scroll_y_ += gesture->details().scroll_y(); - break; - case ui::ET_GESTURE_SCROLL_END: - EXPECT_TRUE(velocity_x_ == 0 && velocity_y_ == 0); - scroll_end_ = true; - break; - case ui::ET_GESTURE_PINCH_BEGIN: - pinch_begin_ = true; - break; - case ui::ET_GESTURE_PINCH_UPDATE: - pinch_update_ = true; - scale_ = gesture->details().scale(); - break; - case ui::ET_GESTURE_PINCH_END: - pinch_end_ = true; - break; - case ui::ET_GESTURE_LONG_PRESS: - long_press_ = true; - break; - case ui::ET_GESTURE_LONG_TAP: - long_tap_ = true; - break; - case ui::ET_SCROLL_FLING_START: - EXPECT_TRUE(gesture->details().velocity_x() != 0 || - gesture->details().velocity_y() != 0); - EXPECT_FALSE(scroll_end_); - fling_ = true; - velocity_x_ = gesture->details().velocity_x(); - velocity_y_ = gesture->details().velocity_y(); - break; - case ui::ET_GESTURE_TWO_FINGER_TAP: - two_finger_tap_ = true; - break; - case ui::ET_GESTURE_SHOW_PRESS: - show_press_ = true; - break; - case ui::ET_GESTURE_SWIPE: - swipe_left_ = gesture->details().swipe_left(); - swipe_right_ = gesture->details().swipe_right(); - swipe_up_ = gesture->details().swipe_up(); - swipe_down_ = gesture->details().swipe_down(); - break; - case ui::ET_SCROLL_FLING_CANCEL: - // Only used in unified gesture detection. - break; - default: - NOTREACHED(); - } - if (wait_until_event_ == gesture->type() && run_loop_) { - run_loop_->Quit(); - wait_until_event_ = ui::ET_UNKNOWN; - } - gesture->StopPropagation(); - } - - private: - scoped_ptr<base::RunLoop> run_loop_; - std::vector<ui::EventType> events_; - - bool tap_; - bool tap_down_; - bool tap_cancel_; - bool begin_; - bool end_; - bool scroll_begin_; - bool scroll_update_; - bool scroll_end_; - bool pinch_begin_; - bool pinch_update_; - bool pinch_end_; - bool long_press_; - bool long_tap_; - bool fling_; - bool two_finger_tap_; - bool show_press_; - bool swipe_left_; - bool swipe_right_; - bool swipe_up_; - bool swipe_down_; - - gfx::Point scroll_begin_position_; - gfx::Point tap_location_; - gfx::Point gesture_end_location_; - - float scroll_x_; - float scroll_y_; - float scroll_velocity_x_; - float scroll_velocity_y_; - float velocity_x_; - float velocity_y_; - float scroll_x_hint_; - float scroll_y_hint_; - float scale_; - gfx::Rect bounding_box_; - int tap_count_; - int flags_; - ui::LatencyInfo latency_info_; - - ui::EventType wait_until_event_; - - DISALLOW_COPY_AND_ASSIGN(GestureEventConsumeDelegate); -}; - -class QueueTouchEventDelegate : public GestureEventConsumeDelegate { - public: - explicit QueueTouchEventDelegate(WindowEventDispatcher* dispatcher) - : window_(NULL), - dispatcher_(dispatcher), - queue_events_(true) { - } - virtual ~QueueTouchEventDelegate() { - while(!queue_.empty()) { - delete queue_.front(); - queue_.pop(); - } - } - - virtual void OnTouchEvent(ui::TouchEvent* event) override { - if (queue_events_) { - queue_.push(new ui::TouchEvent(*event, window_, window_)); - event->StopPropagation(); - } - } - - void ReceivedAck() { - ReceivedAckImpl(false); - } - - void ReceivedAckPreventDefaulted() { - ReceivedAckImpl(true); - } - - void set_window(Window* w) { window_ = w; } - void set_queue_events(bool queue) { queue_events_ = queue; } - - private: - void ReceivedAckImpl(bool prevent_defaulted) { - scoped_ptr<ui::TouchEvent> event(queue_.front()); - dispatcher_->ProcessedTouchEvent(event.get(), window_, - prevent_defaulted ? ui::ER_HANDLED : ui::ER_UNHANDLED); - queue_.pop(); - } - - std::queue<ui::TouchEvent*> queue_; - Window* window_; - WindowEventDispatcher* dispatcher_; - bool queue_events_; - - DISALLOW_COPY_AND_ASSIGN(QueueTouchEventDelegate); -}; - -// A delegate that ignores gesture events but keeps track of [synthetic] mouse -// events. -class GestureEventSynthDelegate : public TestWindowDelegate { - public: - GestureEventSynthDelegate() - : mouse_enter_(false), - mouse_exit_(false), - mouse_press_(false), - mouse_release_(false), - mouse_move_(false), - double_click_(false) { - } - - void Reset() { - mouse_enter_ = false; - mouse_exit_ = false; - mouse_press_ = false; - mouse_release_ = false; - mouse_move_ = false; - double_click_ = false; - } - - bool mouse_enter() const { return mouse_enter_; } - bool mouse_exit() const { return mouse_exit_; } - bool mouse_press() const { return mouse_press_; } - bool mouse_move() const { return mouse_move_; } - bool mouse_release() const { return mouse_release_; } - bool double_click() const { return double_click_; } - - virtual void OnMouseEvent(ui::MouseEvent* event) override { - switch (event->type()) { - case ui::ET_MOUSE_PRESSED: - double_click_ = event->flags() & ui::EF_IS_DOUBLE_CLICK; - mouse_press_ = true; - break; - case ui::ET_MOUSE_RELEASED: - mouse_release_ = true; - break; - case ui::ET_MOUSE_MOVED: - mouse_move_ = true; - break; - case ui::ET_MOUSE_ENTERED: - mouse_enter_ = true; - break; - case ui::ET_MOUSE_EXITED: - mouse_exit_ = true; - break; - default: - NOTREACHED(); - } - event->SetHandled(); - } - - private: - bool mouse_enter_; - bool mouse_exit_; - bool mouse_press_; - bool mouse_release_; - bool mouse_move_; - bool double_click_; - - DISALLOW_COPY_AND_ASSIGN(GestureEventSynthDelegate); -}; - -class ScopedGestureRecognizerSetter { - public: - // Takes ownership of |new_gr|. - explicit ScopedGestureRecognizerSetter(ui::GestureRecognizer* new_gr) - : new_gr_(new_gr) { - original_gr_ = ui::GestureRecognizer::Get(); - ui::SetGestureRecognizerForTesting(new_gr_.get()); - } - - virtual ~ScopedGestureRecognizerSetter() { - ui::SetGestureRecognizerForTesting(original_gr_); - } - - private: - ui::GestureRecognizer* original_gr_; - scoped_ptr<ui::GestureRecognizer> new_gr_; - - DISALLOW_COPY_AND_ASSIGN(ScopedGestureRecognizerSetter); -}; - -class TimedEvents { - private: - int simulated_now_; - - public: - // Use a non-zero start time to pass DCHECKs which ensure events have had a - // time assigned. - TimedEvents() : simulated_now_(1) { - } - - base::TimeDelta Now() { - base::TimeDelta t = base::TimeDelta::FromMilliseconds(simulated_now_); - simulated_now_++; - return t; - } - - base::TimeDelta LeapForward(int time_in_millis) { - simulated_now_ += time_in_millis; - return base::TimeDelta::FromMilliseconds(simulated_now_); - } - - base::TimeDelta InFuture(int time_in_millis) { - return base::TimeDelta::FromMilliseconds(simulated_now_ + time_in_millis); - } - - void SendScrollEvents(ui::EventProcessor* dispatcher, - float x_start, - float y_start, - int dx, - int dy, - int touch_id, - int time_step, - int num_steps, - GestureEventConsumeDelegate* delegate) { - float x = x_start; - float y = y_start; - - for (int i = 0; i < num_steps; i++) { - x += dx; - y += dy; - ui::TouchEvent move(ui::ET_TOUCH_MOVED, gfx::PointF(x, y), - touch_id, - base::TimeDelta::FromMilliseconds(simulated_now_)); - ui::EventDispatchDetails details = dispatcher->OnEventFromSource(&move); - ASSERT_FALSE(details.dispatcher_destroyed); - simulated_now_ += time_step; - } - } - - void SendScrollEvent(ui::EventProcessor* dispatcher, - float x, - float y, - int touch_id, - GestureEventConsumeDelegate* delegate) { - delegate->Reset(); - ui::TouchEvent move(ui::ET_TOUCH_MOVED, gfx::PointF(x, y), - touch_id, - base::TimeDelta::FromMilliseconds(simulated_now_)); - ui::EventDispatchDetails details = dispatcher->OnEventFromSource(&move); - ASSERT_FALSE(details.dispatcher_destroyed); - simulated_now_++; - } -}; - -// An event handler to keep track of events. -class TestEventHandler : public ui::EventHandler { - public: - TestEventHandler() - : touch_released_count_(0), - touch_pressed_count_(0), - touch_moved_count_(0) {} - - virtual ~TestEventHandler() {} - - virtual void OnTouchEvent(ui::TouchEvent* event) override { - switch (event->type()) { - case ui::ET_TOUCH_RELEASED: - touch_released_count_++; - break; - case ui::ET_TOUCH_PRESSED: - touch_pressed_count_++; - break; - case ui::ET_TOUCH_MOVED: - touch_moved_count_++; - break; - case ui::ET_TOUCH_CANCELLED: - cancelled_touch_points_.push_back(event->location()); - break; - default: - break; - } - } - - void Reset() { - touch_released_count_ = 0; - touch_pressed_count_ = 0; - touch_moved_count_ = 0; - cancelled_touch_points_.clear(); - } - - int touch_released_count() const { return touch_released_count_; } - int touch_pressed_count() const { return touch_pressed_count_; } - int touch_moved_count() const { return touch_moved_count_; } - int touch_cancelled_count() const { - return static_cast<int>(cancelled_touch_points_.size()); - } - const std::vector<gfx::PointF>& cancelled_touch_points() const { - return cancelled_touch_points_; - } - - private: - int touch_released_count_; - int touch_pressed_count_; - int touch_moved_count_; - std::vector<gfx::PointF> cancelled_touch_points_; - - DISALLOW_COPY_AND_ASSIGN(TestEventHandler); -}; - -// Removes the target window from its parent when it receives a touch-cancel -// event. -class RemoveOnTouchCancelHandler : public TestEventHandler { - public: - RemoveOnTouchCancelHandler() {} - virtual ~RemoveOnTouchCancelHandler() {} - - private: - // ui::EventHandler: - virtual void OnTouchEvent(ui::TouchEvent* event) override { - TestEventHandler::OnTouchEvent(event); - if (event->type() == ui::ET_TOUCH_CANCELLED) { - Window* target = static_cast<Window*>(event->target()); - // This is tiptoeing around crbug.com/310172. If this event handler isn't - // removed, we enter an infinite loop. - target->RemovePreTargetHandler(this); - target->parent()->RemoveChild(target); - } - } - - DISALLOW_COPY_AND_ASSIGN(RemoveOnTouchCancelHandler); -}; - -void DelayByLongPressTimeout() { - ui::GestureProvider::Config config; - base::RunLoop run_loop; - base::MessageLoop::current()->PostDelayedTask( - FROM_HERE, - run_loop.QuitClosure(), - config.gesture_detector_config.longpress_timeout * 2); - run_loop.Run(); -} - -void DelayByShowPressTimeout() { - ui::GestureProvider::Config config; - base::RunLoop run_loop; - base::MessageLoop::current()->PostDelayedTask( - FROM_HERE, - run_loop.QuitClosure(), - config.gesture_detector_config.showpress_timeout * 2); - run_loop.Run(); -} - -} // namespace - -class GestureRecognizerTest : public AuraTestBase, - public ::testing::WithParamInterface<bool> { - public: - GestureRecognizerTest() {} - - virtual void SetUp() override { - AuraTestBase::SetUp(); - ui::GestureConfiguration::set_show_press_delay_in_ms(2); - ui::GestureConfiguration::set_long_press_time_in_ms(3); - } - - DISALLOW_COPY_AND_ASSIGN(GestureRecognizerTest); -}; - -// Check that appropriate touch events generate tap gesture events. -TEST_F(GestureRecognizerTest, GestureEventTap) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - TimedEvents tes; - const int kWindowWidth = 123; - const int kWindowHeight = 45; - const int kTouchId = 2; - gfx::Rect bounds(100, 200, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - - delegate->Reset(); - ui::TouchEvent press(ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&press); - EXPECT_FALSE(delegate->tap()); - EXPECT_FALSE(delegate->show_press()); - EXPECT_TRUE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_TRUE(delegate->begin()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - EXPECT_FALSE(delegate->long_press()); - - delegate->Reset(); - delegate->WaitUntilReceivedGesture(ui::ET_GESTURE_SHOW_PRESS); - EXPECT_TRUE(delegate->show_press()); - EXPECT_FALSE(delegate->tap_down()); - - // Make sure there is enough delay before the touch is released so that it is - // recognized as a tap. - delegate->Reset(); - ui::TouchEvent release(ui::ET_TOUCH_RELEASED, gfx::Point(101, 201), - kTouchId, tes.LeapForward(50)); - - DispatchEventUsingWindowDispatcher(&release); - EXPECT_TRUE(delegate->tap()); - EXPECT_FALSE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_FALSE(delegate->begin()); - EXPECT_TRUE(delegate->end()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - - EXPECT_EQ(1, delegate->tap_count()); -} - -// Check that appropriate touch events generate tap gesture events -// when information about the touch radii are provided. -TEST_F(GestureRecognizerTest, GestureEventTapRegion) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - TimedEvents tes; - const int kWindowWidth = 800; - const int kWindowHeight = 600; - const int kTouchId = 2; - gfx::Rect bounds(0, 0, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - - // Test with no ET_TOUCH_MOVED events. - { - delegate->Reset(); - ui::TouchEvent press(ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), - kTouchId, tes.Now()); - press.set_radius_x(5); - press.set_radius_y(12); - DispatchEventUsingWindowDispatcher(&press); - EXPECT_FALSE(delegate->tap()); - EXPECT_TRUE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_TRUE(delegate->begin()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - EXPECT_FALSE(delegate->long_press()); - - // Make sure there is enough delay before the touch is released so that it - // is recognized as a tap. - delegate->Reset(); - ui::TouchEvent release(ui::ET_TOUCH_RELEASED, gfx::Point(101, 201), - kTouchId, tes.LeapForward(50)); - release.set_radius_x(5); - release.set_radius_y(12); - - DispatchEventUsingWindowDispatcher(&release); - EXPECT_TRUE(delegate->tap()); - EXPECT_FALSE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_FALSE(delegate->begin()); - EXPECT_TRUE(delegate->end()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - - EXPECT_EQ(1, delegate->tap_count()); - gfx::Point actual_point(delegate->tap_location()); - EXPECT_EQ(24, delegate->bounding_box().width()); - EXPECT_EQ(24, delegate->bounding_box().height()); - EXPECT_EQ(101, actual_point.x()); - EXPECT_EQ(201, actual_point.y()); - } - - // Test with no ET_TOUCH_MOVED events but different touch points and radii. - { - delegate->Reset(); - ui::TouchEvent press(ui::ET_TOUCH_PRESSED, gfx::Point(365, 290), - kTouchId, tes.Now()); - press.set_radius_x(8); - press.set_radius_y(14); - DispatchEventUsingWindowDispatcher(&press); - EXPECT_FALSE(delegate->tap()); - EXPECT_TRUE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_TRUE(delegate->begin()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - EXPECT_FALSE(delegate->long_press()); - - delegate->Reset(); - ui::TouchEvent release(ui::ET_TOUCH_RELEASED, gfx::Point(367, 291), - kTouchId, tes.LeapForward(50)); - release.set_radius_x(20); - release.set_radius_y(13); - - DispatchEventUsingWindowDispatcher(&release); - EXPECT_TRUE(delegate->tap()); - EXPECT_FALSE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_FALSE(delegate->begin()); - EXPECT_TRUE(delegate->end()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - - EXPECT_EQ(1, delegate->tap_count()); - gfx::Point actual_point(delegate->tap_location()); - EXPECT_EQ(40, delegate->bounding_box().width()); - EXPECT_EQ(40, delegate->bounding_box().height()); - EXPECT_EQ(367, actual_point.x()); - EXPECT_EQ(291, actual_point.y()); - } - - // Test with a single ET_TOUCH_MOVED event. - { - delegate->Reset(); - ui::TouchEvent press(ui::ET_TOUCH_PRESSED, gfx::Point(46, 205), - kTouchId, tes.Now()); - press.set_radius_x(6); - press.set_radius_y(10); - DispatchEventUsingWindowDispatcher(&press); - EXPECT_FALSE(delegate->tap()); - EXPECT_TRUE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_TRUE(delegate->begin()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - EXPECT_FALSE(delegate->long_press()); - - delegate->Reset(); - ui::TouchEvent move(ui::ET_TOUCH_MOVED, gfx::Point(49, 204), - kTouchId, tes.LeapForward(50)); - move.set_radius_x(8); - move.set_radius_y(12); - DispatchEventUsingWindowDispatcher(&move); - EXPECT_FALSE(delegate->tap()); - EXPECT_FALSE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_FALSE(delegate->begin()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - EXPECT_FALSE(delegate->long_press()); - - delegate->Reset(); - ui::TouchEvent release(ui::ET_TOUCH_RELEASED, gfx::Point(49, 204), - kTouchId, tes.LeapForward(50)); - release.set_radius_x(4); - release.set_radius_y(8); - - DispatchEventUsingWindowDispatcher(&release); - EXPECT_TRUE(delegate->tap()); - EXPECT_FALSE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_FALSE(delegate->begin()); - EXPECT_TRUE(delegate->end()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - - EXPECT_EQ(1, delegate->tap_count()); - gfx::Point actual_point(delegate->tap_location()); - EXPECT_EQ(16, delegate->bounding_box().width()); - EXPECT_EQ(16, delegate->bounding_box().height()); - EXPECT_EQ(49, actual_point.x()); - EXPECT_EQ(204, actual_point.y()); - } - - // Test with a few ET_TOUCH_MOVED events. - { - delegate->Reset(); - ui::TouchEvent press(ui::ET_TOUCH_PRESSED, gfx::Point(400, 150), - kTouchId, tes.Now()); - press.set_radius_x(7); - press.set_radius_y(10); - DispatchEventUsingWindowDispatcher(&press); - EXPECT_FALSE(delegate->tap()); - EXPECT_TRUE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_TRUE(delegate->begin()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - EXPECT_FALSE(delegate->long_press()); - - delegate->Reset(); - ui::TouchEvent move(ui::ET_TOUCH_MOVED, gfx::Point(397, 151), - kTouchId, tes.LeapForward(50)); - move.set_radius_x(13); - move.set_radius_y(12); - DispatchEventUsingWindowDispatcher(&move); - EXPECT_FALSE(delegate->tap()); - EXPECT_FALSE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_FALSE(delegate->begin()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - EXPECT_FALSE(delegate->long_press()); - - delegate->Reset(); - ui::TouchEvent move1(ui::ET_TOUCH_MOVED, gfx::Point(397, 149), - kTouchId, tes.LeapForward(50)); - move1.set_radius_x(16); - move1.set_radius_y(16); - DispatchEventUsingWindowDispatcher(&move1); - EXPECT_FALSE(delegate->tap()); - EXPECT_FALSE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_FALSE(delegate->begin()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - EXPECT_FALSE(delegate->long_press()); - - delegate->Reset(); - ui::TouchEvent move2(ui::ET_TOUCH_MOVED, gfx::Point(400, 150), - kTouchId, tes.LeapForward(50)); - move2.set_radius_x(14); - move2.set_radius_y(10); - DispatchEventUsingWindowDispatcher(&move2); - EXPECT_FALSE(delegate->tap()); - EXPECT_FALSE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_FALSE(delegate->begin()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - EXPECT_FALSE(delegate->long_press()); - - delegate->Reset(); - ui::TouchEvent release(ui::ET_TOUCH_RELEASED, gfx::Point(401, 149), - kTouchId, tes.LeapForward(50)); - release.set_radius_x(8); - release.set_radius_y(9); - - DispatchEventUsingWindowDispatcher(&release); - EXPECT_TRUE(delegate->tap()); - EXPECT_FALSE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_FALSE(delegate->begin()); - EXPECT_TRUE(delegate->end()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - - EXPECT_EQ(1, delegate->tap_count()); - gfx::Point actual_point(delegate->tap_location()); - EXPECT_EQ(18, delegate->bounding_box().width()); - EXPECT_EQ(18, delegate->bounding_box().height()); - EXPECT_EQ(401, actual_point.x()); - EXPECT_EQ(149, actual_point.y()); - } -} - -// Check that appropriate touch events generate scroll gesture events. -TEST_F(GestureRecognizerTest, GestureEventScroll) { - // We'll start by moving the touch point by (10.5, 10.5). We want 5 dips of - // that distance to be consumed by the slop, so we set the slop radius to - // sqrt(5 * 5 + 5 * 5). - ui::GestureConfiguration::set_max_touch_move_in_pixels_for_click( - sqrt(5.f * 5 + 5 * 5)); - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - TimedEvents tes; - const int kWindowWidth = 123; - const int kWindowHeight = 45; - const int kTouchId = 5; - gfx::Rect bounds(100, 200, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - - delegate->Reset(); - ui::TouchEvent press(ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&press); - EXPECT_2_EVENTS(delegate->events(), - ui::ET_GESTURE_BEGIN, - ui::ET_GESTURE_TAP_DOWN); - - // Move the touch-point enough so that it is considered as a scroll. This - // should generate both SCROLL_BEGIN and SCROLL_UPDATE gestures. - // The first movement is diagonal, to ensure that we have a free scroll, - // and not a rail scroll. - tes.SendScrollEvent(event_processor(), 111.5, 211.5, kTouchId, - delegate.get()); - EXPECT_3_EVENTS(delegate->events(), - ui::ET_GESTURE_TAP_CANCEL, - ui::ET_GESTURE_SCROLL_BEGIN, - ui::ET_GESTURE_SCROLL_UPDATE); - // The slop consumed 5 dips - EXPECT_FLOAT_EQ(5.5, delegate->scroll_x()); - EXPECT_FLOAT_EQ(5.5, delegate->scroll_y()); - EXPECT_EQ(gfx::Point(1, 1).ToString(), - delegate->scroll_begin_position().ToString()); - - // When scrolling with a single finger, the bounding box of the gesture should - // be empty, since it's a single point and the radius for testing is zero. - EXPECT_TRUE(delegate->bounding_box().IsEmpty()); - - // Move some more to generate a few more scroll updates. Make sure that we get - // out of the snap channel for the unified GR. - tes.SendScrollEvent(event_processor(), 20, 120, kTouchId, delegate.get()); - EXPECT_1_EVENT(delegate->events(), ui::ET_GESTURE_SCROLL_UPDATE); - EXPECT_FLOAT_EQ(-91.5, delegate->scroll_x()); - EXPECT_FLOAT_EQ(-91.5, delegate->scroll_y()); - EXPECT_TRUE(delegate->bounding_box().IsEmpty()); - - tes.SendScrollEvent(event_processor(), 50, 124, kTouchId, delegate.get()); - EXPECT_1_EVENT(delegate->events(), ui::ET_GESTURE_SCROLL_UPDATE); - EXPECT_EQ(30, delegate->scroll_x()); - EXPECT_EQ(4, delegate->scroll_y()); - EXPECT_TRUE(delegate->bounding_box().IsEmpty()); - - // Release the touch. This should end the scroll. - delegate->Reset(); - ui::TouchEvent release(ui::ET_TOUCH_RELEASED, gfx::Point(101, 201), - kTouchId, - tes.LeapForward(50)); - DispatchEventUsingWindowDispatcher(&release); - EXPECT_2_EVENTS(delegate->events(), - ui::ET_SCROLL_FLING_START, - ui::ET_GESTURE_END); - EXPECT_TRUE(delegate->bounding_box().IsEmpty()); -} - -// Check that predicted scroll update positions are correct. -TEST_F(GestureRecognizerTest, GestureEventScrollPrediction) { - // We'll start by moving the touch point by (5, 5). We want all of that - // distance to be consumed by the slop, so we set the slop radius to - // sqrt(5 * 5 + 5 * 5). - ui::GestureConfiguration::set_max_touch_move_in_pixels_for_click( - sqrt(5.f * 5 + 5 * 5)); - - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - TimedEvents tes; - const int kWindowWidth = 123; - const int kWindowHeight = 45; - const int kTouchId = 5; - gfx::Rect bounds(95, 195, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - - delegate->Reset(); - // Tracks the total scroll since we want to verify that the correct position - // will be scrolled to throughout the prediction. - gfx::Vector2dF total_scroll; - ui::TouchEvent press(ui::ET_TOUCH_PRESSED, gfx::Point(96, 196), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&press); - EXPECT_2_EVENTS(delegate->events(), - ui::ET_GESTURE_BEGIN, - ui::ET_GESTURE_TAP_DOWN); - delegate->Reset(); - - // Get rid of touch slop. - ui::TouchEvent move(ui::ET_TOUCH_MOVED, gfx::Point(111, 211), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&move); - EXPECT_3_EVENTS(delegate->events(), - ui::ET_GESTURE_TAP_CANCEL, - ui::ET_GESTURE_SCROLL_BEGIN, - ui::ET_GESTURE_SCROLL_UPDATE); - total_scroll.set_x(total_scroll.x() + delegate->scroll_x()); - total_scroll.set_y(total_scroll.y() + delegate->scroll_y()); - - // Move the touch-point enough so that it is considered as a scroll. This - // should generate both SCROLL_BEGIN and SCROLL_UPDATE gestures. - // The first movement is diagonal, to ensure that we have a free scroll, - // and not a rail scroll. - tes.LeapForward(30); - tes.SendScrollEvent(event_processor(), 130, 230, kTouchId, delegate.get()); - EXPECT_1_EVENT(delegate->events(), - ui::ET_GESTURE_SCROLL_UPDATE); - total_scroll.set_x(total_scroll.x() + delegate->scroll_x()); - total_scroll.set_y(total_scroll.y() + delegate->scroll_y()); - - // Move some more to generate a few more scroll updates. - tes.LeapForward(30); - tes.SendScrollEvent(event_processor(), 110, 211, kTouchId, delegate.get()); - EXPECT_1_EVENT(delegate->events(), ui::ET_GESTURE_SCROLL_UPDATE); - total_scroll.set_x(total_scroll.x() + delegate->scroll_x()); - total_scroll.set_y(total_scroll.y() + delegate->scroll_y()); - - tes.LeapForward(30); - tes.SendScrollEvent(event_processor(), 140, 215, kTouchId, delegate.get()); - EXPECT_1_EVENT(delegate->events(), ui::ET_GESTURE_SCROLL_UPDATE); - total_scroll.set_x(total_scroll.x() + delegate->scroll_x()); - total_scroll.set_y(total_scroll.y() + delegate->scroll_y()); - - // Release the touch. This should end the scroll. - delegate->Reset(); - ui::TouchEvent release(ui::ET_TOUCH_RELEASED, gfx::Point(101, 201), - kTouchId, - tes.LeapForward(50)); - DispatchEventUsingWindowDispatcher(&release); -} - -// Check that the bounding box during a scroll event is correct. -TEST_F(GestureRecognizerTest, GestureEventScrollBoundingBox) { - TimedEvents tes; - for (float radius = 1; radius <= 10; ++radius) { - ui::GestureConfiguration::set_default_radius(radius); - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - const int kWindowWidth = 123; - const int kWindowHeight = 45; - const int kTouchId = 5; - gfx::Rect bounds(100, 200, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - - const float kPositionX = 101; - const float kPositionY = 201; - delegate->Reset(); - ui::TouchEvent press(ui::ET_TOUCH_PRESSED, - gfx::PointF(kPositionX, kPositionY), - kTouchId, - tes.Now()); - DispatchEventUsingWindowDispatcher(&press); - EXPECT_EQ(gfx::RectF(kPositionX - radius, - kPositionY - radius, - radius * 2, - radius * 2), - delegate->bounding_box()); - - const int kScrollAmount = 50; - tes.SendScrollEvents(event_processor(), kPositionX, kPositionY, - 1, 1, kTouchId, 1, kScrollAmount, delegate.get()); - EXPECT_EQ(gfx::Point(1, 1).ToString(), - delegate->scroll_begin_position().ToString()); - EXPECT_EQ(gfx::RectF(kPositionX + kScrollAmount - radius, - kPositionY + kScrollAmount - radius, - radius * 2, - radius * 2), - delegate->bounding_box()); - - // Release the touch. This should end the scroll. - delegate->Reset(); - ui::TouchEvent release(ui::ET_TOUCH_RELEASED, - gfx::PointF(kPositionX + kScrollAmount, - kPositionY + kScrollAmount), - kTouchId, press.time_stamp() + - base::TimeDelta::FromMilliseconds(50)); - DispatchEventUsingWindowDispatcher(&release); - EXPECT_EQ(gfx::RectF(kPositionX + kScrollAmount - radius, - kPositionY + kScrollAmount - radius, - radius * 2, - radius * 2), - delegate->bounding_box()); - } - ui::GestureConfiguration::set_default_radius(0); -} - -// Check Scroll End Events report correct velocities -// if the user was on a horizontal rail -TEST_F(GestureRecognizerTest, GestureEventHorizontalRailFling) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - TimedEvents tes; - const int kTouchId = 7; - gfx::Rect bounds(0, 0, 1000, 1000); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - - ui::TouchEvent press(ui::ET_TOUCH_PRESSED, gfx::Point(0, 0), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&press); - - // Get rid of touch slop. - ui::TouchEvent move(ui::ET_TOUCH_MOVED, gfx::Point(10, 0), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&move); - delegate->Reset(); - - - // Move the touch-point horizontally enough that it is considered a - // horizontal scroll. - tes.SendScrollEvent(event_processor(), 30, 1, kTouchId, delegate.get()); - EXPECT_FLOAT_EQ(0, delegate->scroll_y()); - EXPECT_FLOAT_EQ(20, delegate->scroll_x()); - - // Get a high x velocity, while still staying on the rail - const int kScrollAmount = 8; - tes.SendScrollEvents(event_processor(), - 1, - 1, - 100, - 10, - kTouchId, - 1, - kScrollAmount, - delegate.get()); - - delegate->Reset(); - ui::TouchEvent release(ui::ET_TOUCH_RELEASED, gfx::Point(101, 201), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&release); - - EXPECT_TRUE(delegate->fling()); - EXPECT_FALSE(delegate->scroll_end()); - EXPECT_GT(delegate->velocity_x(), 0); - EXPECT_EQ(0, delegate->velocity_y()); -} - -// Check Scroll End Events report correct velocities -// if the user was on a vertical rail -TEST_F(GestureRecognizerTest, GestureEventVerticalRailFling) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - TimedEvents tes; - const int kTouchId = 7; - gfx::Rect bounds(0, 0, 1000, 1000); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - - ui::TouchEvent press(ui::ET_TOUCH_PRESSED, gfx::Point(0, 0), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&press); - - // Get rid of touch slop. - ui::TouchEvent move(ui::ET_TOUCH_MOVED, gfx::Point(0, 10), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&move); - delegate->Reset(); - - // Move the touch-point vertically enough that it is considered a - // vertical scroll. - tes.SendScrollEvent(event_processor(), 1, 30, kTouchId, delegate.get()); - EXPECT_EQ(20, delegate->scroll_y()); - EXPECT_EQ(0, delegate->scroll_x()); - EXPECT_EQ(0, delegate->scroll_velocity_x()); - - // Get a high y velocity, while still staying on the rail - const int kScrollAmount = 8; - tes.SendScrollEvents(event_processor(), - 1, - 6, - 10, - 100, - kTouchId, - 1, - kScrollAmount, - delegate.get()); - EXPECT_EQ(0, delegate->scroll_velocity_x()); - - delegate->Reset(); - ui::TouchEvent release(ui::ET_TOUCH_RELEASED, gfx::Point(101, 206), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&release); - - EXPECT_TRUE(delegate->fling()); - EXPECT_FALSE(delegate->scroll_end()); - EXPECT_EQ(0, delegate->velocity_x()); - EXPECT_GT(delegate->velocity_y(), 0); -} - -// Check Scroll End Events report non-zero velocities if the user is not on a -// rail -TEST_F(GestureRecognizerTest, GestureEventNonRailFling) { - ui::GestureConfiguration::set_max_touch_move_in_pixels_for_click(0); - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - TimedEvents tes; - const int kTouchId = 7; - gfx::Rect bounds(0, 0, 1000, 1000); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - - ui::TouchEvent press(ui::ET_TOUCH_PRESSED, gfx::Point(0, 0), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&press); - - // Move the touch-point such that a non-rail scroll begins, and we're outside - // the snap channel for the unified GR. - tes.SendScrollEvent(event_processor(), 50, 50, kTouchId, delegate.get()); - EXPECT_EQ(50, delegate->scroll_y()); - EXPECT_EQ(50, delegate->scroll_x()); - - const int kScrollAmount = 8; - tes.SendScrollEvents(event_processor(), - 1, - 1, - 10, - 100, - kTouchId, - 1, - kScrollAmount, - delegate.get()); - - delegate->Reset(); - ui::TouchEvent release(ui::ET_TOUCH_RELEASED, gfx::Point(101, 201), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&release); - - EXPECT_TRUE(delegate->fling()); - EXPECT_FALSE(delegate->scroll_end()); - EXPECT_GT(delegate->velocity_x(), 0); - EXPECT_GT(delegate->velocity_y(), 0); -} - -// Check that appropriate touch events generate long press events -TEST_F(GestureRecognizerTest, GestureEventLongPress) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - const int kWindowWidth = 123; - const int kWindowHeight = 45; - const int kTouchId = 2; - gfx::Rect bounds(100, 200, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - - delegate->Reset(); - - ui::TouchEvent press1(ui::ET_TOUCH_PRESSED, - gfx::Point(101, 201), - kTouchId, - ui::EventTimeForNow()); - DispatchEventUsingWindowDispatcher(&press1); - EXPECT_TRUE(delegate->tap_down()); - EXPECT_TRUE(delegate->begin()); - EXPECT_FALSE(delegate->tap_cancel()); - - // We haven't pressed long enough for a long press to occur - EXPECT_FALSE(delegate->long_press()); - - // Wait until the timer runs out - delegate->WaitUntilReceivedGesture(ui::ET_GESTURE_LONG_PRESS); - EXPECT_TRUE(delegate->long_press()); - EXPECT_FALSE(delegate->tap_cancel()); - - delegate->Reset(); - ui::TouchEvent release1(ui::ET_TOUCH_RELEASED, - gfx::Point(101, 201), - kTouchId, - ui::EventTimeForNow()); - DispatchEventUsingWindowDispatcher(&release1); - EXPECT_FALSE(delegate->long_press()); - - // Note the tap cancel isn't dispatched until the release - EXPECT_TRUE(delegate->tap_cancel()); - EXPECT_FALSE(delegate->tap()); -} - -// Check that scrolling prevents a long press. -TEST_F(GestureRecognizerTest, GestureEventLongPressCancelledByScroll) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - TimedEvents tes; - const int kWindowWidth = 123; - const int kWindowHeight = 45; - const int kTouchId = 6; - gfx::Rect bounds(100, 200, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - - delegate->Reset(); - - ui::TouchEvent press1(ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&press1); - EXPECT_TRUE(delegate->tap_down()); - - // We haven't pressed long enough for a long press to occur - EXPECT_FALSE(delegate->long_press()); - EXPECT_FALSE(delegate->tap_cancel()); - - // Scroll around, to cancel the long press - tes.SendScrollEvent(event_processor(), 130, 230, kTouchId, delegate.get()); - - // Wait until a long press event would have fired, if it hadn't been - // cancelled. - DelayByLongPressTimeout(); - - EXPECT_FALSE(delegate->long_press()); - EXPECT_TRUE(delegate->tap_cancel()); - - delegate->Reset(); - ui::TouchEvent release1(ui::ET_TOUCH_RELEASED, gfx::Point(101, 201), - kTouchId, tes.LeapForward(10)); - DispatchEventUsingWindowDispatcher(&release1); - EXPECT_FALSE(delegate->long_press()); - EXPECT_FALSE(delegate->tap_cancel()); -} - -// Check that appropriate touch events generate long tap events -TEST_F(GestureRecognizerTest, GestureEventLongTap) { - ui::GestureConfiguration::set_max_touch_down_duration_for_click_in_ms(3); - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - const int kWindowWidth = 123; - const int kWindowHeight = 45; - const int kTouchId = 2; - gfx::Rect bounds(100, 200, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - - delegate->Reset(); - - ui::TouchEvent press1(ui::ET_TOUCH_PRESSED, - gfx::Point(101, 201), - kTouchId, - ui::EventTimeForNow()); - DispatchEventUsingWindowDispatcher(&press1); - EXPECT_TRUE(delegate->tap_down()); - EXPECT_TRUE(delegate->begin()); - EXPECT_FALSE(delegate->tap_cancel()); - - // We haven't pressed long enough for a long press to occur - EXPECT_FALSE(delegate->long_press()); - - // Wait until the timer runs out - delegate->WaitUntilReceivedGesture(ui::ET_GESTURE_LONG_PRESS); - EXPECT_TRUE(delegate->long_press()); - EXPECT_FALSE(delegate->tap_cancel()); - - delegate->Reset(); - ui::TouchEvent release1(ui::ET_TOUCH_RELEASED, - gfx::Point(101, 201), - kTouchId, - ui::EventTimeForNow()); - DispatchEventUsingWindowDispatcher(&release1); - EXPECT_FALSE(delegate->long_press()); - EXPECT_TRUE(delegate->long_tap()); - - // Note the tap cancel isn't dispatched until the release - EXPECT_TRUE(delegate->tap_cancel()); - EXPECT_FALSE(delegate->tap()); -} - -// Check that second tap cancels a long press -TEST_F(GestureRecognizerTest, GestureEventLongPressCancelledBySecondTap) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - TimedEvents tes; - const int kWindowWidth = 300; - const int kWindowHeight = 400; - const int kTouchId1 = 8; - const int kTouchId2 = 2; - gfx::Rect bounds(5, 5, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - - delegate->Reset(); - ui::TouchEvent press(ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), - kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&press); - EXPECT_TRUE(delegate->tap_down()); - EXPECT_TRUE(delegate->begin()); - - // We haven't pressed long enough for a long press to occur - EXPECT_FALSE(delegate->long_press()); - - // Second tap, to cancel the long press - delegate->Reset(); - ui::TouchEvent press2(ui::ET_TOUCH_PRESSED, gfx::Point(10, 10), - kTouchId2, tes.Now()); - DispatchEventUsingWindowDispatcher(&press2); - EXPECT_FALSE(delegate->tap_down()); // no touch down for second tap. - EXPECT_TRUE(delegate->tap_cancel()); - EXPECT_TRUE(delegate->begin()); - - // Wait until the timer runs out - DelayByLongPressTimeout(); - - // No long press occurred - EXPECT_FALSE(delegate->long_press()); - - delegate->Reset(); - ui::TouchEvent release1(ui::ET_TOUCH_RELEASED, gfx::Point(101, 201), - kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&release1); - EXPECT_FALSE(delegate->long_press()); - EXPECT_TRUE(delegate->two_finger_tap()); - EXPECT_FALSE(delegate->tap_cancel()); -} - -// Check that horizontal scroll gestures cause scrolls on horizontal rails. -// Also tests that horizontal rails can be broken. -TEST_F(GestureRecognizerTest, GestureEventHorizontalRailScroll) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - TimedEvents tes; - const int kTouchId = 7; - gfx::Rect bounds(0, 0, 1000, 1000); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - - ui::TouchEvent press(ui::ET_TOUCH_PRESSED, gfx::Point(0, 0), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&press); - - // Get rid of touch slop. - ui::TouchEvent move(ui::ET_TOUCH_MOVED, gfx::Point(5, 0), - kTouchId, tes.Now()); - - DispatchEventUsingWindowDispatcher(&move); - delegate->Reset(); - - // Move the touch-point horizontally enough that it is considered a - // horizontal scroll. - tes.SendScrollEvent(event_processor(), 25, 0, kTouchId, delegate.get()); - EXPECT_EQ(0, delegate->scroll_y()); - EXPECT_EQ(20, delegate->scroll_x()); - - tes.SendScrollEvent(event_processor(), 30, 6, kTouchId, delegate.get()); - EXPECT_TRUE(delegate->scroll_update()); - EXPECT_EQ(5, delegate->scroll_x()); - // y shouldn't change, as we're on a horizontal rail. - EXPECT_EQ(0, delegate->scroll_y()); - - // Send enough information that a velocity can be calculated for the gesture, - // and we can break the rail - const int kScrollAmount = 8; - tes.SendScrollEvents(event_processor(), - 1, - 1, - 6, - 100, - kTouchId, - 1, - kScrollAmount, - delegate.get()); - - tes.SendScrollEvent(event_processor(), 5, 0, kTouchId, delegate.get()); - tes.SendScrollEvent(event_processor(), 10, 5, kTouchId, delegate.get()); - - // The rail should be broken - EXPECT_TRUE(delegate->scroll_update()); - EXPECT_EQ(5, delegate->scroll_x()); - EXPECT_EQ(5, delegate->scroll_y()); -} - -// Check that vertical scroll gestures cause scrolls on vertical rails. -// Also tests that vertical rails can be broken. -TEST_F(GestureRecognizerTest, GestureEventVerticalRailScroll) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - TimedEvents tes; - const int kTouchId = 7; - gfx::Rect bounds(0, 0, 1000, 1000); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - - ui::TouchEvent press(ui::ET_TOUCH_PRESSED, gfx::Point(0, 0), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&press); - - // Get rid of touch slop. - ui::TouchEvent move(ui::ET_TOUCH_MOVED, gfx::Point(0, 5), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&move); - delegate->Reset(); - - // Move the touch-point vertically enough that it is considered a - // vertical scroll. - tes.SendScrollEvent(event_processor(), 0, 25, kTouchId, delegate.get()); - EXPECT_EQ(0, delegate->scroll_x()); - EXPECT_EQ(20, delegate->scroll_y()); - - tes.SendScrollEvent(event_processor(), 6, 30, kTouchId, delegate.get()); - EXPECT_TRUE(delegate->scroll_update()); - EXPECT_EQ(5, delegate->scroll_y()); - // x shouldn't change, as we're on a vertical rail. - EXPECT_EQ(0, delegate->scroll_x()); - EXPECT_EQ(0, delegate->scroll_velocity_x()); - - // Send enough information that a velocity can be calculated for the gesture, - // and we can break the rail - const int kScrollAmount = 8; - tes.SendScrollEvents(event_processor(), - 1, - 6, - 100, - 1, - kTouchId, - 1, - kScrollAmount, - delegate.get()); - - tes.SendScrollEvent(event_processor(), 0, 5, kTouchId, delegate.get()); - tes.SendScrollEvent(event_processor(), 5, 10, kTouchId, delegate.get()); - - // The rail should be broken - EXPECT_TRUE(delegate->scroll_update()); - EXPECT_EQ(5, delegate->scroll_x()); - EXPECT_EQ(5, delegate->scroll_y()); -} - -TEST_F(GestureRecognizerTest, GestureTapFollowedByScroll) { - // We'll start by moving the touch point by (5, 5). We want all of that - // distance to be consumed by the slop, so we set the slop radius to - // sqrt(5 * 5 + 5 * 5). - ui::GestureConfiguration::set_max_touch_move_in_pixels_for_click( - sqrt(5.f * 5 + 5 * 5)); - - // First, tap. Then, do a scroll using the same touch-id. - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - TimedEvents tes; - const int kWindowWidth = 123; - const int kWindowHeight = 45; - const int kTouchId = 3; - gfx::Rect bounds(100, 200, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - - delegate->Reset(); - ui::TouchEvent press(ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&press); - EXPECT_FALSE(delegate->tap()); - EXPECT_TRUE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - - // Make sure there is enough delay before the touch is released so that it is - // recognized as a tap. - delegate->Reset(); - ui::TouchEvent release(ui::ET_TOUCH_RELEASED, gfx::Point(101, 201), - kTouchId, tes.LeapForward(50)); - DispatchEventUsingWindowDispatcher(&release); - EXPECT_TRUE(delegate->tap()); - EXPECT_FALSE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - - // Now, do a scroll gesture. Delay it sufficiently so that it doesn't trigger - // a double-tap. - delegate->Reset(); - ui::TouchEvent press1(ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), - kTouchId, tes.LeapForward(1000)); - DispatchEventUsingWindowDispatcher(&press1); - EXPECT_FALSE(delegate->tap()); - EXPECT_TRUE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - - // Get rid of touch slop. - ui::TouchEvent move_remove_slop(ui::ET_TOUCH_MOVED, gfx::Point(116, 216), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&move_remove_slop); - EXPECT_TRUE(delegate->tap_cancel()); - EXPECT_TRUE(delegate->scroll_begin()); - EXPECT_TRUE(delegate->scroll_update()); - EXPECT_EQ(15, delegate->scroll_x_hint()); - EXPECT_EQ(15, delegate->scroll_y_hint()); - - delegate->Reset(); - - // Move the touch-point enough so that it is considered as a scroll. This - // should generate both SCROLL_BEGIN and SCROLL_UPDATE gestures. - // The first movement is diagonal, to ensure that we have a free scroll, - // and not a rail scroll. - delegate->Reset(); - ui::TouchEvent move(ui::ET_TOUCH_MOVED, gfx::Point(135, 235), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&move); - EXPECT_FALSE(delegate->tap()); - EXPECT_FALSE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_TRUE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - EXPECT_EQ(19, delegate->scroll_x()); - EXPECT_EQ(19, delegate->scroll_y()); - - // Move some more to generate a few more scroll updates. - delegate->Reset(); - ui::TouchEvent move1(ui::ET_TOUCH_MOVED, gfx::Point(115, 216), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&move1); - EXPECT_FALSE(delegate->tap()); - EXPECT_FALSE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_TRUE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - EXPECT_EQ(-20, delegate->scroll_x()); - EXPECT_EQ(-19, delegate->scroll_y()); - EXPECT_EQ(0, delegate->scroll_x_hint()); - EXPECT_EQ(0, delegate->scroll_y_hint()); - - delegate->Reset(); - ui::TouchEvent move2(ui::ET_TOUCH_MOVED, gfx::Point(145, 220), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&move2); - EXPECT_FALSE(delegate->tap()); - EXPECT_FALSE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_TRUE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - EXPECT_EQ(30, delegate->scroll_x()); - EXPECT_EQ(4, delegate->scroll_y()); - - // Release the touch. This should end the scroll. - delegate->Reset(); - ui::TouchEvent release1(ui::ET_TOUCH_RELEASED, gfx::Point(101, 201), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&release1); - EXPECT_FALSE(delegate->tap()); - EXPECT_FALSE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - EXPECT_TRUE(delegate->fling()); -} - -TEST_F(GestureRecognizerTest, AsynchronousGestureRecognition) { - scoped_ptr<QueueTouchEventDelegate> queued_delegate( - new QueueTouchEventDelegate(host()->dispatcher())); - TimedEvents tes; - const int kWindowWidth = 123; - const int kWindowHeight = 45; - const int kTouchId1 = 6; - const int kTouchId2 = 4; - gfx::Rect bounds(100, 200, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> queue(CreateTestWindowWithDelegate( - queued_delegate.get(), -1234, bounds, root_window())); - - queued_delegate->set_window(queue.get()); - - // Touch down on the window. This should not generate any gesture event. - queued_delegate->Reset(); - ui::TouchEvent press( - ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&press); - EXPECT_FALSE(queued_delegate->tap()); - EXPECT_FALSE(queued_delegate->tap_down()); - EXPECT_FALSE(queued_delegate->tap_cancel()); - EXPECT_FALSE(queued_delegate->begin()); - EXPECT_FALSE(queued_delegate->scroll_begin()); - EXPECT_FALSE(queued_delegate->scroll_update()); - EXPECT_FALSE(queued_delegate->scroll_end()); - - // Introduce some delay before the touch is released so that it is recognized - // as a tap. However, this still should not create any gesture events. - queued_delegate->Reset(); - ui::TouchEvent release( - ui::ET_TOUCH_RELEASED, - gfx::Point(101, 201), - kTouchId1, - press.time_stamp() + base::TimeDelta::FromMilliseconds(50)); - DispatchEventUsingWindowDispatcher(&release); - EXPECT_FALSE(queued_delegate->tap()); - EXPECT_FALSE(queued_delegate->tap_down()); - EXPECT_FALSE(queued_delegate->tap_cancel()); - EXPECT_FALSE(queued_delegate->begin()); - EXPECT_FALSE(queued_delegate->end()); - EXPECT_FALSE(queued_delegate->scroll_begin()); - EXPECT_FALSE(queued_delegate->scroll_update()); - EXPECT_FALSE(queued_delegate->scroll_end()); - - // Create another window, and place a touch-down on it. This should create a - // tap-down gesture. - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -2345, gfx::Rect(0, 0, 50, 50), root_window())); - delegate->Reset(); - ui::TouchEvent press2( - ui::ET_TOUCH_PRESSED, gfx::Point(10, 20), kTouchId2, tes.Now()); - DispatchEventUsingWindowDispatcher(&press2); - EXPECT_FALSE(delegate->tap()); - EXPECT_TRUE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_FALSE(queued_delegate->begin()); - EXPECT_FALSE(queued_delegate->end()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - - ui::TouchEvent release2( - ui::ET_TOUCH_RELEASED, gfx::Point(10, 20), kTouchId2, tes.Now()); - DispatchEventUsingWindowDispatcher(&release2); - - // Process the first queued event. - queued_delegate->Reset(); - queued_delegate->ReceivedAck(); - EXPECT_FALSE(queued_delegate->tap()); - EXPECT_TRUE(queued_delegate->tap_down()); - EXPECT_TRUE(queued_delegate->begin()); - EXPECT_FALSE(queued_delegate->tap_cancel()); - EXPECT_FALSE(queued_delegate->end()); - EXPECT_FALSE(queued_delegate->scroll_begin()); - EXPECT_FALSE(queued_delegate->scroll_update()); - EXPECT_FALSE(queued_delegate->scroll_end()); - - // Now, process the second queued event. - queued_delegate->Reset(); - queued_delegate->ReceivedAck(); - EXPECT_TRUE(queued_delegate->tap()); - EXPECT_FALSE(queued_delegate->tap_down()); - EXPECT_FALSE(queued_delegate->tap_cancel()); - EXPECT_FALSE(queued_delegate->begin()); - EXPECT_TRUE(queued_delegate->end()); - EXPECT_FALSE(queued_delegate->scroll_begin()); - EXPECT_FALSE(queued_delegate->scroll_update()); - EXPECT_FALSE(queued_delegate->scroll_end()); - - // Start all over. Press on the first window, then press again on the second - // window. The second press should still go to the first window. - queued_delegate->Reset(); - ui::TouchEvent press3( - ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&press3); - EXPECT_FALSE(queued_delegate->tap()); - EXPECT_FALSE(queued_delegate->tap_down()); - EXPECT_FALSE(queued_delegate->tap_cancel()); - EXPECT_FALSE(queued_delegate->begin()); - EXPECT_FALSE(queued_delegate->end()); - EXPECT_FALSE(queued_delegate->begin()); - EXPECT_FALSE(queued_delegate->end()); - EXPECT_FALSE(queued_delegate->scroll_begin()); - EXPECT_FALSE(queued_delegate->scroll_update()); - EXPECT_FALSE(queued_delegate->scroll_end()); - - queued_delegate->Reset(); - delegate->Reset(); - ui::TouchEvent press4( - ui::ET_TOUCH_PRESSED, gfx::Point(103, 203), kTouchId2, tes.Now()); - DispatchEventUsingWindowDispatcher(&press4); - EXPECT_FALSE(delegate->tap()); - EXPECT_FALSE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_FALSE(delegate->begin()); - EXPECT_FALSE(delegate->end()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - EXPECT_FALSE(queued_delegate->tap()); - EXPECT_FALSE(queued_delegate->tap_down()); - EXPECT_FALSE(queued_delegate->tap_cancel()); - EXPECT_FALSE(queued_delegate->begin()); - EXPECT_FALSE(queued_delegate->end()); - EXPECT_FALSE(queued_delegate->scroll_begin()); - EXPECT_FALSE(queued_delegate->scroll_update()); - EXPECT_FALSE(queued_delegate->scroll_end()); - - // Move the second touch-point enough so that it is considered a pinch. This - // should generate both SCROLL_BEGIN and PINCH_BEGIN gestures. - queued_delegate->Reset(); - delegate->Reset(); - ui::TouchEvent move( - ui::ET_TOUCH_MOVED, - gfx::PointF( - 203 + ui::GestureConfiguration::max_touch_move_in_pixels_for_click(), - 303), - kTouchId2, - tes.Now()); - DispatchEventUsingWindowDispatcher(&move); - EXPECT_FALSE(delegate->tap()); - EXPECT_FALSE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_FALSE(delegate->begin()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - EXPECT_FALSE(queued_delegate->tap()); - EXPECT_FALSE(queued_delegate->tap_down()); - EXPECT_FALSE(queued_delegate->tap_cancel()); - EXPECT_FALSE(queued_delegate->begin()); - EXPECT_FALSE(queued_delegate->scroll_begin()); - EXPECT_FALSE(queued_delegate->scroll_update()); - EXPECT_FALSE(queued_delegate->scroll_end()); - - queued_delegate->Reset(); - queued_delegate->ReceivedAck(); - EXPECT_FALSE(queued_delegate->tap()); - EXPECT_TRUE(queued_delegate->tap_down()); - EXPECT_TRUE(queued_delegate->begin()); - EXPECT_FALSE(queued_delegate->tap_cancel()); - EXPECT_FALSE(queued_delegate->end()); - EXPECT_FALSE(queued_delegate->scroll_begin()); - EXPECT_FALSE(queued_delegate->scroll_update()); - EXPECT_FALSE(queued_delegate->scroll_end()); - - queued_delegate->Reset(); - queued_delegate->ReceivedAck(); - EXPECT_FALSE(queued_delegate->tap()); - EXPECT_FALSE(queued_delegate->tap_down()); // no touch down for second tap. - EXPECT_TRUE(queued_delegate->tap_cancel()); - EXPECT_TRUE(queued_delegate->begin()); - EXPECT_FALSE(queued_delegate->end()); - EXPECT_FALSE(queued_delegate->scroll_begin()); - EXPECT_FALSE(queued_delegate->scroll_update()); - EXPECT_FALSE(queued_delegate->scroll_end()); - EXPECT_FALSE(queued_delegate->pinch_begin()); - EXPECT_FALSE(queued_delegate->pinch_update()); - EXPECT_FALSE(queued_delegate->pinch_end()); - - queued_delegate->Reset(); - queued_delegate->ReceivedAck(); - EXPECT_FALSE(queued_delegate->tap()); - EXPECT_FALSE(queued_delegate->tap_down()); - EXPECT_FALSE(queued_delegate->tap_cancel()); - EXPECT_FALSE(queued_delegate->begin()); - EXPECT_FALSE(queued_delegate->end()); - EXPECT_TRUE(queued_delegate->scroll_begin()); - - EXPECT_TRUE(queued_delegate->scroll_update()); - EXPECT_FALSE(queued_delegate->scroll_end()); - EXPECT_TRUE(queued_delegate->pinch_begin()); - EXPECT_FALSE(queued_delegate->pinch_update()); - EXPECT_FALSE(queued_delegate->pinch_end()); -} - -// Check that appropriate touch events generate pinch gesture events. -TEST_F(GestureRecognizerTest, GestureEventPinchFromScroll) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - TimedEvents tes; - const int kWindowWidth = 300; - const int kWindowHeight = 400; - const int kTouchId1 = 5; - const int kTouchId2 = 3; - gfx::Rect bounds(5, 5, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - - delegate->Reset(); - ui::TouchEvent press(ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), - kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&press); - EXPECT_2_EVENTS(delegate->events(), - ui::ET_GESTURE_BEGIN, - ui::ET_GESTURE_TAP_DOWN); - - // Move the touch-point enough so that it is considered as a scroll. This - // should generate both SCROLL_BEGIN and SCROLL_UPDATE gestures. - delegate->Reset(); - ui::TouchEvent move(ui::ET_TOUCH_MOVED, gfx::Point(130, 301), - kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&move); - EXPECT_3_EVENTS(delegate->events(), - ui::ET_GESTURE_TAP_CANCEL, - ui::ET_GESTURE_SCROLL_BEGIN, - ui::ET_GESTURE_SCROLL_UPDATE); - - // Press the second finger. It should cause pinch-begin. Note that we will not - // transition to two finger tap here because the touch points are far enough. - delegate->Reset(); - ui::TouchEvent press2(ui::ET_TOUCH_PRESSED, gfx::Point(10, 10), - kTouchId2, tes.Now()); - DispatchEventUsingWindowDispatcher(&press2); - EXPECT_1_EVENT(delegate->events(), ui::ET_GESTURE_BEGIN); - EXPECT_EQ(gfx::Rect(10, 10, 120, 291).ToString(), - delegate->bounding_box().ToString()); - - // Move the first finger. - delegate->Reset(); - ui::TouchEvent move3(ui::ET_TOUCH_MOVED, gfx::Point(95, 201), - kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&move3); - EXPECT_2_EVENTS(delegate->events(), - ui::ET_GESTURE_SCROLL_UPDATE, - ui::ET_GESTURE_PINCH_BEGIN); - EXPECT_EQ(gfx::Rect(10, 10, 85, 191).ToString(), - delegate->bounding_box().ToString()); - - // Now move the second finger. - delegate->Reset(); - ui::TouchEvent move4(ui::ET_TOUCH_MOVED, gfx::Point(55, 15), - kTouchId2, tes.Now()); - DispatchEventUsingWindowDispatcher(&move4); - EXPECT_2_EVENTS(delegate->events(), - ui::ET_GESTURE_SCROLL_UPDATE, - ui::ET_GESTURE_PINCH_UPDATE); - EXPECT_EQ(gfx::Rect(55, 15, 40, 186).ToString(), - delegate->bounding_box().ToString()); - - // Release the first finger. This should end pinch. - delegate->Reset(); - ui::TouchEvent release(ui::ET_TOUCH_RELEASED, gfx::Point(101, 201), - kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&release); - EXPECT_2_EVENTS(delegate->events(), - ui::ET_GESTURE_PINCH_END, - ui::ET_GESTURE_END); - EXPECT_EQ(gfx::Rect(55, 15, 46, 186).ToString(), - delegate->bounding_box().ToString()); - - // Move the second finger. This should still generate a scroll. - delegate->Reset(); - ui::TouchEvent move5(ui::ET_TOUCH_MOVED, gfx::Point(25, 10), - kTouchId2, tes.Now()); - DispatchEventUsingWindowDispatcher(&move5); - EXPECT_1_EVENT(delegate->events(), ui::ET_GESTURE_SCROLL_UPDATE); - EXPECT_TRUE(delegate->bounding_box().IsEmpty()); -} - -TEST_F(GestureRecognizerTest, GestureEventPinchFromScrollFromPinch) { -scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - TimedEvents tes; - const int kWindowWidth = 300; - const int kWindowHeight = 400; - const int kTouchId1 = 5; - const int kTouchId2 = 3; - gfx::Rect bounds(5, 5, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - - ui::TouchEvent press(ui::ET_TOUCH_PRESSED, gfx::Point(101, 301), - kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&press); - delegate->Reset(); - ui::TouchEvent press2(ui::ET_TOUCH_PRESSED, gfx::Point(10, 10), - kTouchId2, tes.Now()); - DispatchEventUsingWindowDispatcher(&press2); - EXPECT_FALSE(delegate->pinch_begin()); - - // Touch move triggers pinch begin. - tes.SendScrollEvent(event_processor(), 130, 230, kTouchId1, delegate.get()); - EXPECT_TRUE(delegate->pinch_begin()); - EXPECT_FALSE(delegate->pinch_update()); - - // Touch move triggers pinch update. - tes.SendScrollEvent(event_processor(), 160, 200, kTouchId1, delegate.get()); - EXPECT_FALSE(delegate->pinch_begin()); - EXPECT_TRUE(delegate->pinch_update()); - - // Pinch has started, now release the second finger - delegate->Reset(); - ui::TouchEvent release(ui::ET_TOUCH_RELEASED, gfx::Point(101, 201), - kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&release); - EXPECT_TRUE(delegate->pinch_end()); - - tes.SendScrollEvent(event_processor(), 130, 230, kTouchId2, delegate.get()); - EXPECT_TRUE(delegate->scroll_update()); - - // Pinch again - delegate->Reset(); - ui::TouchEvent press3(ui::ET_TOUCH_PRESSED, gfx::Point(10, 10), - kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&press3); - // Now the touch points are close. So we will go into two finger tap. - // Move the touch-point enough to break two-finger-tap and enter pinch. - ui::TouchEvent move2(ui::ET_TOUCH_MOVED, gfx::Point(101, 50), - kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&move2); - EXPECT_TRUE(delegate->pinch_begin()); - - tes.SendScrollEvent(event_processor(), 350, 350, kTouchId1, delegate.get()); - EXPECT_TRUE(delegate->pinch_update()); -} - -TEST_F(GestureRecognizerTest, GestureEventPinchFromTap) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - TimedEvents tes; - const int kWindowWidth = 300; - const int kWindowHeight = 400; - const int kTouchId1 = 3; - const int kTouchId2 = 5; - gfx::Rect bounds(5, 5, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - - delegate->Reset(); - ui::TouchEvent press(ui::ET_TOUCH_PRESSED, gfx::Point(101, 301), - kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&press); - EXPECT_2_EVENTS(delegate->events(), - ui::ET_GESTURE_BEGIN, - ui::ET_GESTURE_TAP_DOWN); - EXPECT_TRUE(delegate->bounding_box().IsEmpty()); - - // Press the second finger far enough to break two finger tap. - delegate->Reset(); - ui::TouchEvent press2(ui::ET_TOUCH_PRESSED, gfx::Point(10, 10), - kTouchId2, tes.Now()); - DispatchEventUsingWindowDispatcher(&press2); - EXPECT_2_EVENTS(delegate->events(), - ui::ET_GESTURE_TAP_CANCEL, - ui::ET_GESTURE_BEGIN); - EXPECT_EQ(gfx::Rect(10, 10, 91, 291).ToString(), - delegate->bounding_box().ToString()); - - // Move the first finger. - delegate->Reset(); - ui::TouchEvent move3(ui::ET_TOUCH_MOVED, gfx::Point(65, 201), - kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&move3); - EXPECT_3_EVENTS(delegate->events(), - ui::ET_GESTURE_SCROLL_BEGIN, - ui::ET_GESTURE_SCROLL_UPDATE, - ui::ET_GESTURE_PINCH_BEGIN); - EXPECT_EQ(gfx::Rect(10, 10, 55, 191).ToString(), - delegate->bounding_box().ToString()); - - // Now move the second finger. - delegate->Reset(); - ui::TouchEvent move4(ui::ET_TOUCH_MOVED, gfx::Point(55, 15), - kTouchId2, tes.Now()); - DispatchEventUsingWindowDispatcher(&move4); - EXPECT_2_EVENTS(delegate->events(), - ui::ET_GESTURE_SCROLL_UPDATE, - ui::ET_GESTURE_PINCH_UPDATE); - EXPECT_EQ(gfx::Rect(55, 15, 10, 186).ToString(), - delegate->bounding_box().ToString()); - - // Release the first finger. This should end pinch. - delegate->Reset(); - ui::TouchEvent release(ui::ET_TOUCH_RELEASED, gfx::Point(101, 201), - kTouchId1, tes.LeapForward(10)); - DispatchEventUsingWindowDispatcher(&release); - EXPECT_2_EVENTS(delegate->events(), - ui::ET_GESTURE_PINCH_END, - ui::ET_GESTURE_END); - EXPECT_EQ(gfx::Rect(55, 15, 46, 186).ToString(), - delegate->bounding_box().ToString()); - - // Move the second finger. This should still generate a scroll. - delegate->Reset(); - ui::TouchEvent move5(ui::ET_TOUCH_MOVED, gfx::Point(25, 10), - kTouchId2, tes.Now()); - DispatchEventUsingWindowDispatcher(&move5); - EXPECT_1_EVENT(delegate->events(), ui::ET_GESTURE_SCROLL_UPDATE); - EXPECT_TRUE(delegate->bounding_box().IsEmpty()); -} - -TEST_F(GestureRecognizerTest, GestureEventIgnoresDisconnectedEvents) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - TimedEvents tes; - - ui::TouchEvent release1(ui::ET_TOUCH_RELEASED, gfx::Point(101, 201), - 6, tes.Now()); - DispatchEventUsingWindowDispatcher(&release1); - EXPECT_FALSE(delegate->tap()); - EXPECT_FALSE(delegate->tap_down()); -} - -// Check that a touch is locked to the window of the closest current touch -// within max_separation_for_gesture_touches_in_pixels -TEST_F(GestureRecognizerTest, GestureEventTouchLockSelectsCorrectWindow) { - ui::GestureRecognizer* gesture_recognizer = new ui::GestureRecognizerImpl(); - TimedEvents tes; - ScopedGestureRecognizerSetter gr_setter(gesture_recognizer); - - ui::GestureConsumer* target; - const int kNumWindows = 4; - - scoped_ptr<GestureEventConsumeDelegate*[]> delegates( - new GestureEventConsumeDelegate*[kNumWindows]); - - ui::GestureConfiguration:: - set_max_separation_for_gesture_touches_in_pixels(499); - - scoped_ptr<gfx::Rect[]> window_bounds(new gfx::Rect[kNumWindows]); - window_bounds[0] = gfx::Rect(0, 0, 1, 1); - window_bounds[1] = gfx::Rect(500, 0, 1, 1); - window_bounds[2] = gfx::Rect(0, 500, 1, 1); - window_bounds[3] = gfx::Rect(500, 500, 1, 1); - - scoped_ptr<aura::Window*[]> windows(new aura::Window*[kNumWindows]); - - // Instantiate windows with |window_bounds| and touch each window at - // its origin. - for (int i = 0; i < kNumWindows; ++i) { - delegates[i] = new GestureEventConsumeDelegate(); - windows[i] = CreateTestWindowWithDelegate( - delegates[i], i, window_bounds[i], root_window()); - windows[i]->set_id(i); - ui::TouchEvent press(ui::ET_TOUCH_PRESSED, window_bounds[i].origin(), - i, tes.Now()); - DispatchEventUsingWindowDispatcher(&press); - } - - // Touches should now be associated with the closest touch within - // ui::GestureConfiguration::max_separation_for_gesture_touches_in_pixels - target = gesture_recognizer->GetTargetForLocation(gfx::Point(11, 11), -1); - EXPECT_EQ("0", WindowIDAsString(target)); - target = gesture_recognizer->GetTargetForLocation(gfx::Point(511, 11), -1); - EXPECT_EQ("1", WindowIDAsString(target)); - target = gesture_recognizer->GetTargetForLocation(gfx::Point(11, 511), -1); - EXPECT_EQ("2", WindowIDAsString(target)); - target = gesture_recognizer->GetTargetForLocation(gfx::Point(511, 511), -1); - EXPECT_EQ("3", WindowIDAsString(target)); - - // Add a touch in the middle associated with windows[2] - ui::TouchEvent press(ui::ET_TOUCH_PRESSED, gfx::Point(0, 500), - kNumWindows, tes.Now()); - DispatchEventUsingWindowDispatcher(&press); - ui::TouchEvent move(ui::ET_TOUCH_MOVED, gfx::Point(250, 250), - kNumWindows, tes.Now()); - DispatchEventUsingWindowDispatcher(&move); - - target = gesture_recognizer->GetTargetForLocation(gfx::Point(250, 250), -1); - EXPECT_EQ("2", WindowIDAsString(target)); - - // Make sure that ties are broken by distance to a current touch - // Closer to the point in the bottom right. - target = gesture_recognizer->GetTargetForLocation(gfx::Point(380, 380), -1); - EXPECT_EQ("3", WindowIDAsString(target)); - - // This touch is closer to the point in the middle - target = gesture_recognizer->GetTargetForLocation(gfx::Point(300, 300), -1); - EXPECT_EQ("2", WindowIDAsString(target)); - - // A touch too far from other touches won't be locked to anything - target = gesture_recognizer->GetTargetForLocation(gfx::Point(1000, 1000), -1); - EXPECT_TRUE(target == NULL); - - // Move a touch associated with windows[2] to 1000, 1000 - ui::TouchEvent move2(ui::ET_TOUCH_MOVED, gfx::Point(1000, 1000), - kNumWindows, tes.Now()); - DispatchEventUsingWindowDispatcher(&move2); - - target = gesture_recognizer->GetTargetForLocation(gfx::Point(1000, 1000), -1); - EXPECT_EQ("2", WindowIDAsString(target)); - - for (int i = 0; i < kNumWindows; ++i) { - // Delete windows before deleting delegates. - delete windows[i]; - delete delegates[i]; - } -} - -// Check that a touch's target will not be effected by a touch on a different -// screen. -TEST_F(GestureRecognizerTest, GestureEventTouchLockIgnoresOtherScreens) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - gfx::Rect bounds(0, 0, 10, 10); - scoped_ptr<aura::Window> window( - CreateTestWindowWithDelegate(delegate.get(), 0, bounds, root_window())); - - const int kTouchId1 = 8; - const int kTouchId2 = 2; - TimedEvents tes; - - ui::TouchEvent press1(ui::ET_TOUCH_PRESSED, gfx::Point(5, 5), - kTouchId1, tes.Now()); - ui::EventTestApi test_press1(&press1); - test_press1.set_source_device_id(1); - DispatchEventUsingWindowDispatcher(&press1); - - ui::TouchEvent press2(ui::ET_TOUCH_PRESSED, gfx::Point(20, 20), - kTouchId2, tes.Now()); - ui::EventTestApi test_press2(&press2); - test_press2.set_source_device_id(2); - DispatchEventUsingWindowDispatcher(&press2); - - // The second press should not have been locked to the same target as the - // first, as they occured on different displays. - EXPECT_NE( - ui::GestureRecognizer::Get()->GetTouchLockedTarget(press1), - ui::GestureRecognizer::Get()->GetTouchLockedTarget(press2)); -} - -// Check that touch events outside the root window are still handled -// by the root window's gesture sequence. -TEST_F(GestureRecognizerTest, GestureEventOutsideRootWindowTap) { - TimedEvents tes; - scoped_ptr<aura::Window> window(CreateTestWindowWithBounds( - gfx::Rect(-100, -100, 2000, 2000), root_window())); - - gfx::Point pos1(-10, -10); - ui::TouchEvent press1(ui::ET_TOUCH_PRESSED, pos1, 0, tes.Now()); - DispatchEventUsingWindowDispatcher(&press1); - - gfx::Point pos2(1000, 1000); - ui::TouchEvent press2(ui::ET_TOUCH_PRESSED, pos2, 1, tes.Now()); - DispatchEventUsingWindowDispatcher(&press2); - - // As these presses were outside the root window, they should be - // associated with the root window. - EXPECT_EQ(root_window(), - static_cast<aura::Window*>( - ui::GestureRecognizer::Get()->GetTouchLockedTarget(press1))); - EXPECT_EQ(root_window(), - static_cast<aura::Window*>( - ui::GestureRecognizer::Get()->GetTouchLockedTarget(press2))); -} - -TEST_F(GestureRecognizerTest, NoTapWithPreventDefaultedRelease) { - scoped_ptr<QueueTouchEventDelegate> delegate( - new QueueTouchEventDelegate(host()->dispatcher())); - TimedEvents tes; - const int kTouchId = 2; - gfx::Rect bounds(100, 200, 100, 100); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - delegate->set_window(window.get()); - - delegate->Reset(); - ui::TouchEvent press(ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&press); - ui::TouchEvent release(ui::ET_TOUCH_RELEASED, gfx::Point(101, 201), - kTouchId, tes.LeapForward(50)); - DispatchEventUsingWindowDispatcher(&release); - - delegate->Reset(); - delegate->ReceivedAck(); - EXPECT_TRUE(delegate->tap_down()); - delegate->Reset(); - delegate->ReceivedAckPreventDefaulted(); - EXPECT_FALSE(delegate->tap()); - EXPECT_TRUE(delegate->tap_cancel()); -} - -TEST_F(GestureRecognizerTest, PinchScrollWithPreventDefaultedRelease) { - scoped_ptr<QueueTouchEventDelegate> delegate( - new QueueTouchEventDelegate(host()->dispatcher())); - TimedEvents tes; - const int kTouchId1 = 7; - const int kTouchId2 = 5; - gfx::Rect bounds(10, 20, 100, 100); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - delegate->set_window(window.get()); - - { - delegate->Reset(); - ui::TouchEvent press(ui::ET_TOUCH_PRESSED, gfx::Point(15, 25), kTouchId1, - tes.Now()); - ui::TouchEvent move(ui::ET_TOUCH_MOVED, gfx::Point(20, 95), kTouchId1, - tes.LeapForward(200)); - ui::TouchEvent release(ui::ET_TOUCH_RELEASED, gfx::Point(15, 25), kTouchId1, - tes.LeapForward(50)); - DispatchEventUsingWindowDispatcher(&press); - DispatchEventUsingWindowDispatcher(&move); - DispatchEventUsingWindowDispatcher(&release); - delegate->Reset(); - - // Ack the press event. - delegate->ReceivedAck(); - EXPECT_2_EVENTS( - delegate->events(), ui::ET_GESTURE_BEGIN, ui::ET_GESTURE_TAP_DOWN); - delegate->Reset(); - - // Ack the move event. - delegate->ReceivedAck(); - EXPECT_3_EVENTS(delegate->events(), - ui::ET_GESTURE_TAP_CANCEL, - ui::ET_GESTURE_SCROLL_BEGIN, - ui::ET_GESTURE_SCROLL_UPDATE); - delegate->Reset(); - - // Ack the release event. Although the release event has been processed, it - // should still generate a scroll-end event. - delegate->ReceivedAckPreventDefaulted(); - EXPECT_2_EVENTS( - delegate->events(), ui::ET_GESTURE_SCROLL_END, ui::ET_GESTURE_END); - } - - ui::TouchEvent press(ui::ET_TOUCH_PRESSED, gfx::Point(15, 25), kTouchId1, - tes.Now()); - ui::TouchEvent move(ui::ET_TOUCH_MOVED, gfx::Point(20, 95), kTouchId1, - tes.LeapForward(200)); - ui::TouchEvent release(ui::ET_TOUCH_RELEASED, gfx::Point(15, 25), kTouchId1, - tes.LeapForward(50)); - ui::TouchEvent press2(ui::ET_TOUCH_PRESSED, gfx::Point(55, 25), kTouchId2, - tes.Now()); - ui::TouchEvent move2(ui::ET_TOUCH_MOVED, gfx::Point(145, 85), kTouchId2, - tes.LeapForward(1000)); - ui::TouchEvent release2(ui::ET_TOUCH_RELEASED, gfx::Point(145, 85), kTouchId2, - tes.LeapForward(14)); - - // Do a pinch. - DispatchEventUsingWindowDispatcher(&press); - DispatchEventUsingWindowDispatcher(&move); - DispatchEventUsingWindowDispatcher(&press2); - DispatchEventUsingWindowDispatcher(&move2); - DispatchEventUsingWindowDispatcher(&release); - DispatchEventUsingWindowDispatcher(&release2); - - // Ack the press and move events. - delegate->Reset(); - delegate->ReceivedAck(); - EXPECT_2_EVENTS( - delegate->events(), ui::ET_GESTURE_BEGIN, ui::ET_GESTURE_TAP_DOWN); - - delegate->Reset(); - delegate->ReceivedAck(); - EXPECT_3_EVENTS(delegate->events(), - ui::ET_GESTURE_TAP_CANCEL, - ui::ET_GESTURE_SCROLL_BEGIN, - ui::ET_GESTURE_SCROLL_UPDATE); - - delegate->Reset(); - delegate->ReceivedAck(); - EXPECT_1_EVENT(delegate->events(), ui::ET_GESTURE_BEGIN); - - delegate->Reset(); - delegate->ReceivedAck(); - EXPECT_2_EVENTS(delegate->events(), - ui::ET_GESTURE_SCROLL_UPDATE, - ui::ET_GESTURE_PINCH_BEGIN); - - // Ack the first release. Although the release is processed, it should still - // generate a pinch-end event. - delegate->Reset(); - delegate->ReceivedAckPreventDefaulted(); - EXPECT_2_EVENTS( - delegate->events(), ui::ET_GESTURE_PINCH_END, ui::ET_GESTURE_END); - - delegate->Reset(); - delegate->ReceivedAckPreventDefaulted(); - EXPECT_2_EVENTS( - delegate->events(), ui::ET_GESTURE_SCROLL_END, ui::ET_GESTURE_END); -} - -TEST_F(GestureRecognizerTest, GestureEndLocation) { - GestureEventConsumeDelegate delegate; - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - &delegate, -1234, gfx::Rect(10, 10, 300, 300), root_window())); - ui::test::EventGenerator generator(root_window(), window.get()); - const gfx::Point begin(20, 20); - const gfx::Point end(150, 150); - const gfx::Vector2d window_offset = - window->bounds().origin().OffsetFromOrigin(); - generator.GestureScrollSequence(begin, end, - base::TimeDelta::FromMilliseconds(20), - 10); - EXPECT_EQ((begin - window_offset).ToString(), - delegate.scroll_begin_position().ToString()); - EXPECT_EQ((end - window_offset).ToString(), - delegate.gesture_end_location().ToString()); -} - -TEST_F(GestureRecognizerTest, CaptureSendsGestureEnd) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, gfx::Rect(10, 10, 300, 300), root_window())); - ui::test::EventGenerator generator(root_window()); - - generator.MoveMouseRelativeTo(window.get(), gfx::Point(10, 10)); - generator.PressTouch(); - RunAllPendingInMessageLoop(); - - EXPECT_TRUE(delegate->tap_down()); - - scoped_ptr<aura::Window> capture(CreateTestWindowWithBounds( - gfx::Rect(10, 10, 200, 200), root_window())); - capture->SetCapture(); - RunAllPendingInMessageLoop(); - - EXPECT_TRUE(delegate->end()); - EXPECT_TRUE(delegate->tap_cancel()); -} - -// Check that previous touch actions that are completely finished (either -// released or cancelled), do not receive extra synthetic cancels upon change of -// capture. -TEST_F(GestureRecognizerTest, CaptureDoesNotCancelFinishedTouches) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - scoped_ptr<TestEventHandler> handler(new TestEventHandler); - root_window()->AddPreTargetHandler(handler.get()); - - // Create a window and set it as the capture window. - scoped_ptr<aura::Window> window1(CreateTestWindowWithDelegate(delegate.get(), - -1234, gfx::Rect(10, 10, 300, 300), root_window())); - window1->SetCapture(); - - ui::test::EventGenerator generator(root_window()); - TimedEvents tes; - - // Generate two touch-press events on the window. - scoped_ptr<ui::TouchEvent> touch0(new ui::TouchEvent(ui::ET_TOUCH_PRESSED, - gfx::Point(20, 20), 0, - tes.Now())); - scoped_ptr<ui::TouchEvent> touch1(new ui::TouchEvent(ui::ET_TOUCH_PRESSED, - gfx::Point(30, 30), 1, - tes.Now())); - generator.Dispatch(touch0.get()); - generator.Dispatch(touch1.get()); - RunAllPendingInMessageLoop(); - EXPECT_EQ(2, handler->touch_pressed_count()); - - // Advance time. - tes.LeapForward(1000); - - // End the two touches, one by a touch-release and one by a touch-cancel; to - // cover both cases. - touch0.reset(new ui::TouchEvent(ui::ET_TOUCH_RELEASED, gfx::Point(20, 20), 0, - tes.Now())); - touch1.reset(new ui::TouchEvent(ui::ET_TOUCH_CANCELLED, gfx::Point(30, 30), 1, - tes.Now())); - generator.Dispatch(touch0.get()); - generator.Dispatch(touch1.get()); - RunAllPendingInMessageLoop(); - EXPECT_EQ(1, handler->touch_released_count()); - EXPECT_EQ(1, handler->touch_cancelled_count()); - - // Create a new window and set it as the new capture window. - scoped_ptr<aura::Window> window2(CreateTestWindowWithBounds( - gfx::Rect(100, 100, 300, 300), root_window())); - window2->SetCapture(); - RunAllPendingInMessageLoop(); - // Check that setting capture does not generate any synthetic touch-cancels - // for the two previously finished touch actions. - EXPECT_EQ(1, handler->touch_cancelled_count()); - - root_window()->RemovePreTargetHandler(handler.get()); -} - -// Tests that a press with the same touch id as an existing touch is ignored. -TEST_F(GestureRecognizerTest, PressDoesNotCrash) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - TimedEvents tes; - - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, gfx::Rect(10, 10, 300, 300), root_window())); - - ui::TouchEvent press(ui::ET_TOUCH_PRESSED, gfx::Point(45, 45), 7, tes.Now()); - press.set_radius_x(40); - DispatchEventUsingWindowDispatcher(&press); - EXPECT_TRUE(delegate->tap_down()); - EXPECT_EQ(gfx::Rect(5, 5, 80, 80).ToString(), - delegate->bounding_box().ToString()); - delegate->Reset(); - - ui::TouchEvent press2(ui::ET_TOUCH_PRESSED, gfx::Point(55, 45), 7, tes.Now()); - DispatchEventUsingWindowDispatcher(&press2); - - // This new press should not generate a tap-down. - EXPECT_FALSE(delegate->begin()); - EXPECT_FALSE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_FALSE(delegate->scroll_begin()); -} - -TEST_F(GestureRecognizerTest, TwoFingerTap) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - const int kWindowWidth = 123; - const int kWindowHeight = 45; - const int kTouchId1 = 2; - const int kTouchId2 = 3; - gfx::Rect bounds(100, 200, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - TimedEvents tes; - - delegate->Reset(); - ui::TouchEvent press1(ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), - kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&press1); - EXPECT_2_EVENTS( - delegate->events(), ui::ET_GESTURE_BEGIN, ui::ET_GESTURE_TAP_DOWN); - - delegate->Reset(); - ui::TouchEvent press2(ui::ET_TOUCH_PRESSED, gfx::Point(130, 201), - kTouchId2, tes.Now()); - DispatchEventUsingWindowDispatcher(&press2); - EXPECT_2_EVENTS( - delegate->events(), ui::ET_GESTURE_TAP_CANCEL, ui::ET_GESTURE_BEGIN); - - // Little bit of touch move should not affect our state. - delegate->Reset(); - ui::TouchEvent move1(ui::ET_TOUCH_MOVED, gfx::Point(102, 202), - kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&move1); - ui::TouchEvent move2(ui::ET_TOUCH_MOVED, gfx::Point(131, 202), - kTouchId2, tes.Now()); - DispatchEventUsingWindowDispatcher(&move2); - EXPECT_2_EVENTS(delegate->events(), - ui::ET_GESTURE_SCROLL_BEGIN, - ui::ET_GESTURE_SCROLL_UPDATE); - - // Make sure there is enough delay before the touch is released so that it is - // recognized as a tap. - delegate->Reset(); - ui::TouchEvent release1(ui::ET_TOUCH_RELEASED, gfx::Point(101, 201), - kTouchId1, tes.LeapForward(50)); - - DispatchEventUsingWindowDispatcher(&release1); - EXPECT_2_EVENTS( - delegate->events(), ui::ET_GESTURE_TWO_FINGER_TAP, ui::ET_GESTURE_END); - - // Lift second finger. - // Make sure there is enough delay before the touch is released so that it is - // recognized as a tap. - delegate->Reset(); - ui::TouchEvent release2(ui::ET_TOUCH_RELEASED, gfx::Point(130, 201), - kTouchId2, tes.LeapForward(50)); - - DispatchEventUsingWindowDispatcher(&release2); - EXPECT_2_EVENTS( - delegate->events(), ui::ET_GESTURE_SCROLL_END, ui::ET_GESTURE_END); -} - -TEST_F(GestureRecognizerTest, TwoFingerTapExpired) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - const int kWindowWidth = 123; - const int kWindowHeight = 45; - const int kTouchId1 = 2; - const int kTouchId2 = 3; - gfx::Rect bounds(100, 200, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - TimedEvents tes; - - delegate->Reset(); - ui::TouchEvent press1(ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), - kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&press1); - - delegate->Reset(); - ui::TouchEvent press2(ui::ET_TOUCH_PRESSED, gfx::Point(130, 201), - kTouchId2, tes.Now()); - DispatchEventUsingWindowDispatcher(&press2); - - // Send release event after sufficient delay so that two finger time expires. - delegate->Reset(); - ui::TouchEvent release1(ui::ET_TOUCH_RELEASED, gfx::Point(101, 201), - kTouchId1, tes.LeapForward(1000)); - - DispatchEventUsingWindowDispatcher(&release1); - EXPECT_FALSE(delegate->two_finger_tap()); - - // Lift second finger. - // Make sure there is enough delay before the touch is released so that it is - // recognized as a tap. - delegate->Reset(); - ui::TouchEvent release2(ui::ET_TOUCH_RELEASED, gfx::Point(130, 201), - kTouchId2, tes.LeapForward(50)); - - DispatchEventUsingWindowDispatcher(&release2); - EXPECT_FALSE(delegate->two_finger_tap()); -} - -TEST_F(GestureRecognizerTest, TwoFingerTapChangesToPinch) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - const int kWindowWidth = 123; - const int kWindowHeight = 45; - const int kTouchId1 = 2; - const int kTouchId2 = 3; - TimedEvents tes; - - // Test moving first finger - { - gfx::Rect bounds(100, 200, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - - delegate->Reset(); - ui::TouchEvent press1(ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), - kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&press1); - - delegate->Reset(); - ui::TouchEvent press2(ui::ET_TOUCH_PRESSED, gfx::Point(130, 201), - kTouchId2, tes.Now()); - DispatchEventUsingWindowDispatcher(&press2); - - tes.SendScrollEvent(event_processor(), 230, 330, kTouchId1, delegate.get()); - EXPECT_FALSE(delegate->two_finger_tap()); - EXPECT_TRUE(delegate->pinch_begin()); - - // Make sure there is enough delay before the touch is released so that it - // is recognized as a tap. - delegate->Reset(); - ui::TouchEvent release(ui::ET_TOUCH_RELEASED, gfx::Point(101, 201), - kTouchId2, tes.LeapForward(50)); - - DispatchEventUsingWindowDispatcher(&release); - EXPECT_FALSE(delegate->two_finger_tap()); - EXPECT_TRUE(delegate->pinch_end()); - } - - // Test moving second finger - { - gfx::Rect bounds(100, 200, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - - delegate->Reset(); - ui::TouchEvent press1(ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), - kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&press1); - - delegate->Reset(); - ui::TouchEvent press2(ui::ET_TOUCH_PRESSED, gfx::Point(130, 201), - kTouchId2, tes.Now()); - DispatchEventUsingWindowDispatcher(&press2); - - tes.SendScrollEvent(event_processor(), 301, 230, kTouchId2, delegate.get()); - EXPECT_FALSE(delegate->two_finger_tap()); - EXPECT_TRUE(delegate->pinch_begin()); - - // Make sure there is enough delay before the touch is released so that it - // is recognized as a tap. - delegate->Reset(); - ui::TouchEvent release(ui::ET_TOUCH_RELEASED, gfx::Point(101, 201), - kTouchId1, tes.LeapForward(50)); - - DispatchEventUsingWindowDispatcher(&release); - EXPECT_FALSE(delegate->two_finger_tap()); - EXPECT_TRUE(delegate->pinch_end()); - } -} - -TEST_F(GestureRecognizerTest, NoTwoFingerTapWhenFirstFingerHasScrolled) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - const int kWindowWidth = 123; - const int kWindowHeight = 45; - const int kTouchId1 = 2; - const int kTouchId2 = 3; - TimedEvents tes; - - gfx::Rect bounds(100, 200, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - - delegate->Reset(); - ui::TouchEvent press1(ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), - kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&press1); - tes.SendScrollEvent(event_processor(), 130, 230, kTouchId1, delegate.get()); - - delegate->Reset(); - ui::TouchEvent press2(ui::ET_TOUCH_PRESSED, gfx::Point(130, 201), - kTouchId2, tes.Now()); - DispatchEventUsingWindowDispatcher(&press2); - - EXPECT_FALSE(delegate->pinch_begin()); - - // Make sure there is enough delay before the touch is released so that it - // is recognized as a tap. - delegate->Reset(); - ui::TouchEvent release(ui::ET_TOUCH_RELEASED, gfx::Point(101, 201), - kTouchId2, tes.LeapForward(50)); - - DispatchEventUsingWindowDispatcher(&release); - EXPECT_FALSE(delegate->two_finger_tap()); - EXPECT_FALSE(delegate->pinch_end()); -} - -TEST_F(GestureRecognizerTest, MultiFingerSwipe) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - const int kWindowWidth = 123; - const int kWindowHeight = 45; - - gfx::Rect bounds(5, 10, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - - const int kSteps = 15; - const int kTouchPoints = 4; - gfx::Point points[kTouchPoints] = { - gfx::Point(10, 30), - gfx::Point(30, 20), - gfx::Point(50, 30), - gfx::Point(80, 50) - }; - - ui::test::EventGenerator generator(root_window(), window.get()); - - // The unified gesture recognizer assumes a finger has stopped if it hasn't - // moved for too long. See ui/events/gesture_detection/velocity_tracker.cc's - // kAssumePointerStoppedTimeMs. - for (int count = 2; count <= kTouchPoints; ++count) { - generator.GestureMultiFingerScroll( - count, points, 10, kSteps, 0, -11 * kSteps); - EXPECT_TRUE(delegate->swipe_up()); - delegate->Reset(); - - generator.GestureMultiFingerScroll( - count, points, 10, kSteps, 0, 11 * kSteps); - EXPECT_TRUE(delegate->swipe_down()); - delegate->Reset(); - - generator.GestureMultiFingerScroll( - count, points, 10, kSteps, -11 * kSteps, 0); - EXPECT_TRUE(delegate->swipe_left()); - delegate->Reset(); - - generator.GestureMultiFingerScroll( - count, points, 10, kSteps, 11 * kSteps, 0); - EXPECT_TRUE(delegate->swipe_right()); - delegate->Reset(); - - generator.GestureMultiFingerScroll( - count, points, 10, kSteps, 5 * kSteps, 12 * kSteps); - EXPECT_FALSE(delegate->swipe_down()); - delegate->Reset(); - - generator.GestureMultiFingerScroll( - count, points, 10, kSteps, 4 * kSteps, 12 * kSteps); - EXPECT_TRUE(delegate->swipe_down()); - delegate->Reset(); - - generator.GestureMultiFingerScroll( - count, points, 10, kSteps, 3 * kSteps, 12 * kSteps); - EXPECT_TRUE(delegate->swipe_down()); - delegate->Reset(); - } -} - -TEST_F(GestureRecognizerTest, TwoFingerTapCancelled) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - const int kWindowWidth = 123; - const int kWindowHeight = 45; - const int kTouchId1 = 2; - const int kTouchId2 = 3; - TimedEvents tes; - - // Test canceling first finger. - { - gfx::Rect bounds(100, 200, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - - delegate->Reset(); - ui::TouchEvent press1(ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), - kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&press1); - - delegate->Reset(); - ui::TouchEvent press2(ui::ET_TOUCH_PRESSED, gfx::Point(130, 201), - kTouchId2, tes.Now()); - DispatchEventUsingWindowDispatcher(&press2); - - delegate->Reset(); - ui::TouchEvent cancel(ui::ET_TOUCH_CANCELLED, gfx::Point(130, 201), - kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&cancel); - EXPECT_FALSE(delegate->two_finger_tap()); - - // Make sure there is enough delay before the touch is released so that it - // is recognized as a tap. - delegate->Reset(); - ui::TouchEvent release(ui::ET_TOUCH_RELEASED, gfx::Point(101, 201), - kTouchId2, tes.LeapForward(50)); - - DispatchEventUsingWindowDispatcher(&release); - EXPECT_FALSE(delegate->two_finger_tap()); - } - - // Test canceling second finger - { - gfx::Rect bounds(100, 200, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - - delegate->Reset(); - ui::TouchEvent press1(ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), - kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&press1); - - delegate->Reset(); - ui::TouchEvent press2(ui::ET_TOUCH_PRESSED, gfx::Point(130, 201), - kTouchId2, tes.Now()); - DispatchEventUsingWindowDispatcher(&press2); - - delegate->Reset(); - ui::TouchEvent cancel(ui::ET_TOUCH_CANCELLED, gfx::Point(130, 201), - kTouchId2, tes.Now()); - DispatchEventUsingWindowDispatcher(&cancel); - EXPECT_FALSE(delegate->two_finger_tap()); - - // Make sure there is enough delay before the touch is released so that it - // is recognized as a tap. - delegate->Reset(); - ui::TouchEvent release(ui::ET_TOUCH_RELEASED, gfx::Point(101, 201), - kTouchId1, tes.LeapForward(50)); - - DispatchEventUsingWindowDispatcher(&release); - EXPECT_FALSE(delegate->two_finger_tap()); - } -} - -TEST_F(GestureRecognizerTest, VeryWideTwoFingerTouchDownShouldBeAPinch) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - const int kWindowWidth = 523; - const int kWindowHeight = 45; - const int kTouchId1 = 2; - const int kTouchId2 = 3; - gfx::Rect bounds(100, 200, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - TimedEvents tes; - - delegate->Reset(); - ui::TouchEvent press1(ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), - kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&press1); - EXPECT_FALSE(delegate->tap()); - EXPECT_TRUE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - EXPECT_FALSE(delegate->long_press()); - EXPECT_FALSE(delegate->two_finger_tap()); - - delegate->Reset(); - ui::TouchEvent press2(ui::ET_TOUCH_PRESSED, gfx::Point(430, 201), - kTouchId2, tes.Now()); - DispatchEventUsingWindowDispatcher(&press2); - EXPECT_FALSE(delegate->tap()); - EXPECT_FALSE(delegate->tap_down()); // no touch down for second tap. - EXPECT_TRUE(delegate->tap_cancel()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - EXPECT_FALSE(delegate->long_press()); - EXPECT_FALSE(delegate->two_finger_tap()); - EXPECT_FALSE(delegate->pinch_begin()); - - delegate->Reset(); - ui::TouchEvent move2(ui::ET_TOUCH_MOVED, gfx::Point(530, 301), - kTouchId2, tes.Now()); - DispatchEventUsingWindowDispatcher(&move2); - EXPECT_FALSE(delegate->tap()); - EXPECT_FALSE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - // Pinch & Scroll only when there is enough movement. - EXPECT_TRUE(delegate->scroll_begin()); - EXPECT_TRUE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - EXPECT_FALSE(delegate->long_press()); - EXPECT_FALSE(delegate->two_finger_tap()); - EXPECT_TRUE(delegate->pinch_begin()); -} - -// Verifies if a window is the target of multiple touch-ids and we hide the -// window everything is cleaned up correctly. -TEST_F(GestureRecognizerTest, FlushAllOnHide) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - gfx::Rect bounds(0, 0, 200, 200); - scoped_ptr<aura::Window> window( - CreateTestWindowWithDelegate(delegate.get(), 0, bounds, root_window())); - const int kTouchId1 = 8; - const int kTouchId2 = 2; - TimedEvents tes; - - ui::TouchEvent press1(ui::ET_TOUCH_PRESSED, gfx::Point(10, 10), - kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&press1); - ui::TouchEvent press2(ui::ET_TOUCH_PRESSED, gfx::Point(20, 20), - kTouchId2, tes.Now()); - DispatchEventUsingWindowDispatcher(&press2); - window->Hide(); - EXPECT_EQ(NULL, - ui::GestureRecognizer::Get()->GetTouchLockedTarget(press1)); - EXPECT_EQ(NULL, - ui::GestureRecognizer::Get()->GetTouchLockedTarget(press2)); -} - -TEST_F(GestureRecognizerTest, LongPressTimerStopsOnPreventDefaultedTouchMoves) { - scoped_ptr<QueueTouchEventDelegate> delegate( - new QueueTouchEventDelegate(host()->dispatcher())); - const int kTouchId = 2; - gfx::Rect bounds(100, 200, 100, 100); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - delegate->set_window(window.get()); - TimedEvents tes; - - delegate->Reset(); - ui::TouchEvent press(ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&press); - // Scroll around, to cancel the long press - tes.SendScrollEvent(event_processor(), 130, 230, kTouchId, delegate.get()); - - delegate->Reset(); - delegate->ReceivedAck(); - EXPECT_TRUE(delegate->tap_down()); - - // Wait long enough that long press would have fired if the touchmove hadn't - // prevented it. - DelayByLongPressTimeout(); - - delegate->Reset(); - delegate->ReceivedAckPreventDefaulted(); - EXPECT_FALSE(delegate->long_press()); -} - -// Same as GestureEventConsumeDelegate, but consumes all the touch-move events. -class ConsumesTouchMovesDelegate : public GestureEventConsumeDelegate { - public: - ConsumesTouchMovesDelegate() : consume_touch_move_(true) {} - virtual ~ConsumesTouchMovesDelegate() {} - - void set_consume_touch_move(bool consume) { consume_touch_move_ = consume; } - - private: - virtual void OnTouchEvent(ui::TouchEvent* touch) override { - if (consume_touch_move_ && touch->type() == ui::ET_TOUCH_MOVED) - touch->SetHandled(); - else - GestureEventConsumeDelegate::OnTouchEvent(touch); - } - - bool consume_touch_move_; - - DISALLOW_COPY_AND_ASSIGN(ConsumesTouchMovesDelegate); -}; - -// Same as GestureEventScroll, but tests that the behavior is the same -// even if all the touch-move events are consumed. -TEST_F(GestureRecognizerTest, GestureEventScrollTouchMoveConsumed) { - scoped_ptr<ConsumesTouchMovesDelegate> delegate( - new ConsumesTouchMovesDelegate()); - const int kWindowWidth = 123; - const int kWindowHeight = 45; - const int kTouchId = 5; - gfx::Rect bounds(100, 200, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - TimedEvents tes; - - delegate->Reset(); - ui::TouchEvent press(ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&press); - EXPECT_FALSE(delegate->tap()); - EXPECT_TRUE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_TRUE(delegate->begin()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - - // Move the touch-point enough so that it would normally be considered a - // scroll. But since the touch-moves will be consumed, the scroll should not - // start. - tes.SendScrollEvent(event_processor(), 130, 230, kTouchId, delegate.get()); - EXPECT_FALSE(delegate->tap()); - EXPECT_FALSE(delegate->tap_down()); - EXPECT_TRUE(delegate->tap_cancel()); - EXPECT_FALSE(delegate->begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - - EXPECT_TRUE(delegate->scroll_begin()); - - // Release the touch back at the start point. This should end without causing - // a tap. - delegate->Reset(); - ui::TouchEvent release(ui::ET_TOUCH_RELEASED, gfx::Point(130, 230), - kTouchId, tes.LeapForward(50)); - DispatchEventUsingWindowDispatcher(&release); - EXPECT_FALSE(delegate->tap()); - EXPECT_FALSE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_FALSE(delegate->begin()); - EXPECT_TRUE(delegate->end()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - - EXPECT_TRUE(delegate->scroll_end()); -} - -// Tests the behavior of 2F scroll when some of the touch-move events are -// consumed. -TEST_F(GestureRecognizerTest, GestureEventScrollTwoFingerTouchMoveConsumed) { - scoped_ptr<ConsumesTouchMovesDelegate> delegate( - new ConsumesTouchMovesDelegate()); - const int kWindowWidth = 123; - const int kWindowHeight = 100; - const int kTouchId1 = 2; - const int kTouchId2 = 3; - TimedEvents tes; - - gfx::Rect bounds(100, 200, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - - delegate->Reset(); - ui::TouchEvent press1(ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), - kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&press1); - tes.SendScrollEvent(event_processor(), 131, 231, kTouchId1, delegate.get()); - - EXPECT_2_EVENTS(delegate->events(), - ui::ET_GESTURE_TAP_CANCEL, - ui::ET_GESTURE_SCROLL_BEGIN); - - delegate->Reset(); - // Second finger touches down and moves. - ui::TouchEvent press2(ui::ET_TOUCH_PRESSED, gfx::Point(130, 201), - kTouchId2, tes.LeapForward(50)); - DispatchEventUsingWindowDispatcher(&press2); - tes.SendScrollEvent(event_processor(), 161, 231, kTouchId2, delegate.get()); - EXPECT_0_EVENTS(delegate->events()); - - delegate->Reset(); - // Move first finger again, no PinchUpdate & ScrollUpdate. - tes.SendScrollEvent(event_processor(), 161, 261, kTouchId1, delegate.get()); - EXPECT_0_EVENTS(delegate->events()); - - // Stops consuming touch-move. - delegate->set_consume_touch_move(false); - - delegate->Reset(); - // Making a pinch gesture. - tes.SendScrollEvent(event_processor(), 161, 260, kTouchId1, delegate.get()); - EXPECT_1_EVENT(delegate->events(), ui::ET_GESTURE_SCROLL_UPDATE); - - delegate->Reset(); - tes.SendScrollEvent(event_processor(), 161, 261, kTouchId2, delegate.get()); - EXPECT_1_EVENT(delegate->events(), ui::ET_GESTURE_SCROLL_UPDATE); - - delegate->Reset(); - ui::TouchEvent release1(ui::ET_TOUCH_RELEASED, gfx::Point(101, 201), - kTouchId1, tes.Now()); - ui::TouchEvent release2(ui::ET_TOUCH_RELEASED, gfx::Point(130, 201), - kTouchId2, tes.Now()); - DispatchEventUsingWindowDispatcher(&release1); - DispatchEventUsingWindowDispatcher(&release2); - - EXPECT_3_EVENTS(delegate->events(), - ui::ET_GESTURE_END, - ui::ET_GESTURE_SCROLL_END, - ui::ET_GESTURE_END); -} - -// Like as GestureEventTouchMoveConsumed but tests the different behavior -// depending on whether the events were consumed before or after the scroll -// started. -TEST_F(GestureRecognizerTest, GestureEventScrollTouchMovePartialConsumed) { - scoped_ptr<ConsumesTouchMovesDelegate> delegate( - new ConsumesTouchMovesDelegate()); - const int kWindowWidth = 123; - const int kWindowHeight = 45; - const int kTouchId = 5; - gfx::Rect bounds(100, 200, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - TimedEvents tes; - - delegate->Reset(); - ui::TouchEvent press(ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&press); - EXPECT_FALSE(delegate->tap()); - EXPECT_TRUE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_TRUE(delegate->begin()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - - // Move the touch-point enough so that it would normally be considered a - // scroll. But since the touch-moves will be consumed, the scroll should not - // start. - tes.SendScrollEvent(event_processor(), 130, 230, kTouchId, delegate.get()); - EXPECT_FALSE(delegate->tap()); - EXPECT_FALSE(delegate->tap_down()); - EXPECT_TRUE(delegate->tap_cancel()); - EXPECT_FALSE(delegate->begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - - // Consuming the first touch move event won't prevent all future scrolling. - EXPECT_TRUE(delegate->scroll_begin()); - - // Now, stop consuming touch-move events, and move the touch-point again. - delegate->set_consume_touch_move(false); - tes.SendScrollEvent(event_processor(), 159, 259, kTouchId, delegate.get()); - EXPECT_FALSE(delegate->tap()); - EXPECT_FALSE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_FALSE(delegate->begin()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_end()); - - // Scroll not prevented by consumed first touch move. - EXPECT_TRUE(delegate->scroll_update()); - EXPECT_EQ(29, delegate->scroll_x()); - EXPECT_EQ(29, delegate->scroll_y()); - EXPECT_EQ(gfx::Point(0, 0).ToString(), - delegate->scroll_begin_position().ToString()); - - // Start consuming touch-move events again. - delegate->set_consume_touch_move(true); - - // Move some more to generate a few more scroll updates. - tes.SendScrollEvent(event_processor(), 110, 211, kTouchId, delegate.get()); - EXPECT_FALSE(delegate->tap()); - EXPECT_FALSE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_FALSE(delegate->begin()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - EXPECT_EQ(0, delegate->scroll_x()); - EXPECT_EQ(0, delegate->scroll_y()); - - tes.SendScrollEvent(event_processor(), 140, 215, kTouchId, delegate.get()); - EXPECT_FALSE(delegate->tap()); - EXPECT_FALSE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_FALSE(delegate->begin()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - EXPECT_EQ(0, delegate->scroll_x()); - EXPECT_EQ(0, delegate->scroll_y()); - - // Release the touch. - delegate->Reset(); - ui::TouchEvent release(ui::ET_TOUCH_RELEASED, gfx::Point(101, 201), - kTouchId, tes.LeapForward(50)); - DispatchEventUsingWindowDispatcher(&release); - EXPECT_FALSE(delegate->tap()); - EXPECT_FALSE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_FALSE(delegate->begin()); - EXPECT_TRUE(delegate->end()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->fling()); - - EXPECT_TRUE(delegate->scroll_end()); -} - -// Check that appropriate touch events generate double tap gesture events. -TEST_F(GestureRecognizerTest, GestureEventDoubleTap) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - const int kWindowWidth = 123; - const int kWindowHeight = 45; - const int kTouchId = 2; - gfx::Rect bounds(100, 200, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - TimedEvents tes; - - // First tap (tested in GestureEventTap) - ui::TouchEvent press1(ui::ET_TOUCH_PRESSED, gfx::Point(104, 201), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&press1); - ui::TouchEvent release1(ui::ET_TOUCH_RELEASED, gfx::Point(104, 201), - kTouchId, tes.LeapForward(50)); - DispatchEventUsingWindowDispatcher(&release1); - delegate->Reset(); - - // Second tap - ui::TouchEvent press2(ui::ET_TOUCH_PRESSED, gfx::Point(101, 203), - kTouchId, tes.LeapForward(200)); - DispatchEventUsingWindowDispatcher(&press2); - ui::TouchEvent release2(ui::ET_TOUCH_RELEASED, gfx::Point(102, 206), - kTouchId, tes.LeapForward(50)); - DispatchEventUsingWindowDispatcher(&release2); - - EXPECT_TRUE(delegate->tap()); - EXPECT_TRUE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_TRUE(delegate->begin()); - EXPECT_TRUE(delegate->end()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - - EXPECT_EQ(2, delegate->tap_count()); -} - -// Check that appropriate touch events generate triple tap gesture events. -TEST_F(GestureRecognizerTest, GestureEventTripleTap) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - const int kWindowWidth = 123; - const int kWindowHeight = 45; - const int kTouchId = 2; - gfx::Rect bounds(100, 200, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - TimedEvents tes; - - // First tap (tested in GestureEventTap) - ui::TouchEvent press1(ui::ET_TOUCH_PRESSED, gfx::Point(104, 201), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&press1); - ui::TouchEvent release1(ui::ET_TOUCH_RELEASED, gfx::Point(104, 201), - kTouchId, tes.LeapForward(50)); - DispatchEventUsingWindowDispatcher(&release1); - - EXPECT_EQ(1, delegate->tap_count()); - delegate->Reset(); - - // Second tap (tested in GestureEventDoubleTap) - ui::TouchEvent press2(ui::ET_TOUCH_PRESSED, gfx::Point(101, 203), - kTouchId, tes.LeapForward(200)); - DispatchEventUsingWindowDispatcher(&press2); - ui::TouchEvent release2(ui::ET_TOUCH_RELEASED, gfx::Point(102, 206), - kTouchId, tes.LeapForward(50)); - DispatchEventUsingWindowDispatcher(&release2); - - EXPECT_EQ(2, delegate->tap_count()); - delegate->Reset(); - - // Third tap - ui::TouchEvent press3(ui::ET_TOUCH_PRESSED, gfx::Point(102, 206), - kTouchId, tes.LeapForward(200)); - DispatchEventUsingWindowDispatcher(&press3); - ui::TouchEvent release3(ui::ET_TOUCH_RELEASED, gfx::Point(102, 206), - kTouchId, tes.LeapForward(50)); - DispatchEventUsingWindowDispatcher(&release3); - - // Third, Fourth and Fifth Taps. Taps after the third should have their - // |tap_count| wrap around back to 1. - for (int i = 3; i < 5; ++i) { - ui::TouchEvent press3(ui::ET_TOUCH_PRESSED, - gfx::Point(102, 206), - kTouchId, - tes.LeapForward(200)); - DispatchEventUsingWindowDispatcher(&press3); - ui::TouchEvent release3(ui::ET_TOUCH_RELEASED, - gfx::Point(102, 206), - kTouchId, - tes.LeapForward(50)); - DispatchEventUsingWindowDispatcher(&release3); - - EXPECT_TRUE(delegate->tap()); - EXPECT_TRUE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_TRUE(delegate->begin()); - EXPECT_TRUE(delegate->end()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - EXPECT_EQ(1 + (i % 3), delegate->tap_count()); - } -} - -// Check that we don't get a double tap when the two taps are far apart. -TEST_F(GestureRecognizerTest, TwoTapsFarApart) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - const int kWindowWidth = 123; - const int kWindowHeight = 45; - const int kTouchId = 2; - gfx::Rect bounds(100, 200, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - TimedEvents tes; - - // First tap (tested in GestureEventTap) - ui::TouchEvent press1(ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&press1); - ui::TouchEvent release1(ui::ET_TOUCH_RELEASED, gfx::Point(101, 201), - kTouchId, tes.LeapForward(50)); - DispatchEventUsingWindowDispatcher(&release1); - delegate->Reset(); - - // Second tap, close in time but far in distance - ui::TouchEvent press2(ui::ET_TOUCH_PRESSED, gfx::Point(201, 201), - kTouchId, tes.LeapForward(200)); - DispatchEventUsingWindowDispatcher(&press2); - ui::TouchEvent release2(ui::ET_TOUCH_RELEASED, gfx::Point(201, 201), - kTouchId, tes.LeapForward(50)); - DispatchEventUsingWindowDispatcher(&release2); - - EXPECT_TRUE(delegate->tap()); - EXPECT_TRUE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_TRUE(delegate->begin()); - EXPECT_TRUE(delegate->end()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - - EXPECT_EQ(1, delegate->tap_count()); -} - -// Check that we don't get a double tap when the two taps have a long enough -// delay in between. -TEST_F(GestureRecognizerTest, TwoTapsWithDelayBetween) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - const int kWindowWidth = 123; - const int kWindowHeight = 45; - const int kTouchId = 2; - gfx::Rect bounds(100, 200, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - TimedEvents tes; - - // First tap (tested in GestureEventTap) - ui::TouchEvent press1(ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&press1); - ui::TouchEvent release1(ui::ET_TOUCH_RELEASED, gfx::Point(101, 201), - kTouchId, tes.LeapForward(50)); - DispatchEventUsingWindowDispatcher(&release1); - delegate->Reset(); - - // Second tap, close in distance but after some delay - ui::TouchEvent press2(ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), - kTouchId, tes.LeapForward(2000)); - DispatchEventUsingWindowDispatcher(&press2); - ui::TouchEvent release2(ui::ET_TOUCH_RELEASED, gfx::Point(101, 201), - kTouchId, tes.LeapForward(50)); - DispatchEventUsingWindowDispatcher(&release2); - - EXPECT_TRUE(delegate->tap()); - EXPECT_TRUE(delegate->tap_down()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_TRUE(delegate->begin()); - EXPECT_TRUE(delegate->end()); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - - EXPECT_EQ(1, delegate->tap_count()); -} - -// Checks that if the bounding-box of a gesture changes because of change in -// radius of a touch-point, and not because of change in position, then there -// are not gesture events from that. -TEST_F(GestureRecognizerTest, BoundingBoxRadiusChange) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - const int kWindowWidth = 234; - const int kWindowHeight = 345; - const int kTouchId = 5, kTouchId2 = 7; - gfx::Rect bounds(100, 200, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - TimedEvents tes; - - ui::TouchEvent press1( - ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&press1); - EXPECT_TRUE(delegate->bounding_box().IsEmpty()); - - delegate->Reset(); - - ui::TouchEvent press2( - ui::ET_TOUCH_PRESSED, gfx::Point(201, 201), kTouchId2, - tes.LeapForward(400)); - press2.set_radius_x(5); - DispatchEventUsingWindowDispatcher(&press2); - EXPECT_FALSE(delegate->pinch_begin()); - EXPECT_EQ(gfx::Rect(101, 196, 105, 10).ToString(), - delegate->bounding_box().ToString()); - - delegate->Reset(); - - ui::TouchEvent move1(ui::ET_TOUCH_MOVED, gfx::Point(50, 50), kTouchId, - tes.LeapForward(40)); - DispatchEventUsingWindowDispatcher(&move1); - EXPECT_TRUE(delegate->pinch_begin()); - EXPECT_EQ(gfx::Rect(50, 50, 156, 156).ToString(), - delegate->bounding_box().ToString()); - - delegate->Reset(); - - // The position doesn't move, but the radius changes. - ui::TouchEvent move2( - ui::ET_TOUCH_MOVED, gfx::Point(50, 50), kTouchId, tes.LeapForward(40)); - move2.set_radius_x(50); - move2.set_radius_y(60); - DispatchEventUsingWindowDispatcher(&move2); - EXPECT_FALSE(delegate->tap()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->pinch_update()); - - delegate->Reset(); -} - -// Checks that slow scrolls deliver the correct deltas. -// In particular, fix for http;//crbug.com/150573. -TEST_F(GestureRecognizerTest, NoDriftInScroll) { - ui::GestureConfiguration::set_max_touch_move_in_pixels_for_click(3); - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - const int kWindowWidth = 234; - const int kWindowHeight = 345; - const int kTouchId = 5; - TimedEvents tes; - gfx::Rect bounds(100, 200, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - - ui::TouchEvent press1( - ui::ET_TOUCH_PRESSED, gfx::Point(101, 208), kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&press1); - EXPECT_TRUE(delegate->begin()); - - delegate->Reset(); - - ui::TouchEvent move1(ui::ET_TOUCH_MOVED, gfx::Point(101, 206), kTouchId, - tes.LeapForward(40)); - DispatchEventUsingWindowDispatcher(&move1); - EXPECT_FALSE(delegate->scroll_begin()); - - delegate->Reset(); - - ui::TouchEvent move2(ui::ET_TOUCH_MOVED, gfx::Point(101, 204), kTouchId, - tes.LeapForward(40)); - DispatchEventUsingWindowDispatcher(&move2); - EXPECT_TRUE(delegate->tap_cancel()); - EXPECT_TRUE(delegate->scroll_begin()); - EXPECT_TRUE(delegate->scroll_update()); - // 3 px consumed by touch slop region. - EXPECT_EQ(-1, delegate->scroll_y()); - EXPECT_EQ(-4, delegate->scroll_y_hint()); - - delegate->Reset(); - - ui::TouchEvent move3(ui::ET_TOUCH_MOVED, gfx::Point(101, 204), kTouchId, - tes.LeapForward(40)); - DispatchEventUsingWindowDispatcher(&move3); - EXPECT_FALSE(delegate->scroll_update()); - - delegate->Reset(); - - ui::TouchEvent move4(ui::ET_TOUCH_MOVED, gfx::Point(101, 203), kTouchId, - tes.LeapForward(40)); - DispatchEventUsingWindowDispatcher(&move4); - EXPECT_TRUE(delegate->scroll_update()); - EXPECT_EQ(-1, delegate->scroll_y()); - - delegate->Reset(); -} - -// Ensure that move events which are preventDefaulted will cause a tap -// cancel gesture event to be fired if the move would normally cause a -// scroll. See bug http://crbug.com/146397. -TEST_F(GestureRecognizerTest, GestureEventConsumedTouchMoveCanFireTapCancel) { - scoped_ptr<ConsumesTouchMovesDelegate> delegate( - new ConsumesTouchMovesDelegate()); - const int kTouchId = 5; - gfx::Rect bounds(100, 200, 123, 45); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - TimedEvents tes; - - delegate->Reset(); - ui::TouchEvent press(ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), - kTouchId, tes.Now()); - - delegate->set_consume_touch_move(false); - DispatchEventUsingWindowDispatcher(&press); - delegate->set_consume_touch_move(true); - delegate->Reset(); - // Move the touch-point enough so that it would normally be considered a - // scroll. But since the touch-moves will be consumed, no scrolling should - // occur. - // With the unified gesture detector, we will receive a scroll begin gesture, - // whereas with the aura gesture recognizer we won't. - tes.SendScrollEvent(event_processor(), 130, 230, kTouchId, delegate.get()); - EXPECT_FALSE(delegate->tap()); - EXPECT_FALSE(delegate->tap_down()); - EXPECT_TRUE(delegate->tap_cancel()); - EXPECT_FALSE(delegate->begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); -} - -TEST_F(GestureRecognizerTest, - TransferEventDispatchesTouchCancel) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - TimedEvents tes; - const int kWindowWidth = 800; - const int kWindowHeight = 600; - const int kTouchId1 = 1; - const int kTouchId2 = 2; - gfx::Rect bounds(0, 0, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - scoped_ptr<TestEventHandler> handler(new TestEventHandler()); - window->AddPreTargetHandler(handler.get()); - - // Start a gesture sequence on |window|. Then transfer the events to NULL. - // Make sure |window| receives a touch-cancel event. - delegate->Reset(); - ui::TouchEvent press( - ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&press); - EXPECT_2_EVENTS( - delegate->events(), ui::ET_GESTURE_BEGIN, ui::ET_GESTURE_TAP_DOWN); - delegate->Reset(); - ui::TouchEvent p2( - ui::ET_TOUCH_PRESSED, gfx::Point(50, 50), kTouchId2, tes.Now()); - DispatchEventUsingWindowDispatcher(&p2); - EXPECT_2_EVENTS( - delegate->events(), ui::ET_GESTURE_TAP_CANCEL, ui::ET_GESTURE_BEGIN); - delegate->Reset(); - ui::TouchEvent move( - ui::ET_TOUCH_MOVED, gfx::Point(350, 300), kTouchId2, tes.Now()); - DispatchEventUsingWindowDispatcher(&move); - EXPECT_3_EVENTS(delegate->events(), - ui::ET_GESTURE_SCROLL_BEGIN, - ui::ET_GESTURE_SCROLL_UPDATE, - ui::ET_GESTURE_PINCH_BEGIN); - EXPECT_EQ(2, handler->touch_pressed_count()); - delegate->Reset(); - handler->Reset(); - - ui::GestureRecognizer* gesture_recognizer = ui::GestureRecognizer::Get(); - EXPECT_EQ(window.get(), - gesture_recognizer->GetTouchLockedTarget(press)); - gesture_recognizer->TransferEventsTo(window.get(), NULL); - EXPECT_EQ(NULL, - gesture_recognizer->GetTouchLockedTarget(press)); - EXPECT_4_EVENTS(delegate->events(), - ui::ET_GESTURE_PINCH_END, - ui::ET_GESTURE_SCROLL_END, - ui::ET_GESTURE_END, - ui::ET_GESTURE_END); - const std::vector<gfx::PointF>& points = handler->cancelled_touch_points(); - EXPECT_EQ(2U, points.size()); - EXPECT_EQ(gfx::Point(101, 201), points[0]); - EXPECT_EQ(gfx::Point(350, 300), points[1]); -} - -// Check that appropriate touch events generate show press events -TEST_F(GestureRecognizerTest, GestureEventShowPress) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - TimedEvents tes; - const int kWindowWidth = 123; - const int kWindowHeight = 45; - const int kTouchId = 2; - gfx::Rect bounds(100, 200, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - - delegate->Reset(); - - ui::TouchEvent press1(ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&press1); - EXPECT_TRUE(delegate->tap_down()); - EXPECT_TRUE(delegate->begin()); - EXPECT_FALSE(delegate->tap_cancel()); - - // We haven't pressed long enough for a show press to occur - EXPECT_FALSE(delegate->show_press()); - - // Wait until the timer runs out - delegate->WaitUntilReceivedGesture(ui::ET_GESTURE_SHOW_PRESS); - EXPECT_TRUE(delegate->show_press()); - EXPECT_FALSE(delegate->tap_cancel()); - - delegate->Reset(); - ui::TouchEvent release1(ui::ET_TOUCH_RELEASED, gfx::Point(101, 201), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&release1); - EXPECT_FALSE(delegate->long_press()); - - // Note the tap isn't dispatched until the release - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_TRUE(delegate->tap()); -} - -// Check that scrolling cancels a show press -TEST_F(GestureRecognizerTest, GestureEventShowPressCancelledByScroll) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - TimedEvents tes; - const int kWindowWidth = 123; - const int kWindowHeight = 45; - const int kTouchId = 6; - gfx::Rect bounds(100, 200, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - - delegate->Reset(); - - ui::TouchEvent press1(ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&press1); - EXPECT_TRUE(delegate->tap_down()); - - // We haven't pressed long enough for a show press to occur - EXPECT_FALSE(delegate->show_press()); - EXPECT_FALSE(delegate->tap_cancel()); - - // Scroll around, to cancel the show press - tes.SendScrollEvent(event_processor(), 130, 230, kTouchId, delegate.get()); - // Wait until the timer runs out - DelayByShowPressTimeout(); - EXPECT_FALSE(delegate->show_press()); - EXPECT_TRUE(delegate->tap_cancel()); - - delegate->Reset(); - ui::TouchEvent release1(ui::ET_TOUCH_RELEASED, gfx::Point(101, 201), - kTouchId, tes.LeapForward(10)); - DispatchEventUsingWindowDispatcher(&release1); - EXPECT_FALSE(delegate->show_press()); - EXPECT_FALSE(delegate->tap_cancel()); -} - -// Test that show press events are sent immediately on tap -TEST_F(GestureRecognizerTest, GestureEventShowPressSentOnTap) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - TimedEvents tes; - const int kWindowWidth = 123; - const int kWindowHeight = 45; - const int kTouchId = 6; - gfx::Rect bounds(100, 200, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - - delegate->Reset(); - - ui::TouchEvent press1(ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&press1); - EXPECT_TRUE(delegate->tap_down()); - - // We haven't pressed long enough for a show press to occur - EXPECT_FALSE(delegate->show_press()); - EXPECT_FALSE(delegate->tap_cancel()); - - delegate->Reset(); - ui::TouchEvent release1(ui::ET_TOUCH_RELEASED, gfx::Point(101, 201), - kTouchId, tes.LeapForward(50)); - DispatchEventUsingWindowDispatcher(&release1); - EXPECT_TRUE(delegate->show_press()); - EXPECT_FALSE(delegate->tap_cancel()); - EXPECT_TRUE(delegate->tap()); -} - -// Test that consuming the first move touch event prevents a scroll. -TEST_F(GestureRecognizerTest, GestureEventConsumedTouchMoveScrollTest) { - scoped_ptr<QueueTouchEventDelegate> delegate( - new QueueTouchEventDelegate(host()->dispatcher())); - TimedEvents tes; - const int kTouchId = 7; - gfx::Rect bounds(0, 0, 1000, 1000); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - delegate->set_window(window.get()); - - ui::TouchEvent press(ui::ET_TOUCH_PRESSED, gfx::Point(0, 0), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&press); - delegate->ReceivedAck(); - - // A touch move within the slop region is never consumed in web contents. The - // unified GR won't prevent scroll if a touch move within the slop region is - // consumed, so make sure this touch move exceeds the slop region. - ui::TouchEvent move1(ui::ET_TOUCH_MOVED, gfx::Point(10, 10), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&move1); - delegate->ReceivedAckPreventDefaulted(); - - ui::TouchEvent move2(ui::ET_TOUCH_MOVED, gfx::Point(20, 20), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&move2); - delegate->ReceivedAck(); - - // With the unified gesture detector, consuming the first touch move event - // won't prevent all future scrolling. - EXPECT_TRUE(delegate->scroll_begin()); - EXPECT_TRUE(delegate->scroll_update()); -} - -// Test that consuming the first move touch doesn't prevent a tap. -TEST_F(GestureRecognizerTest, GestureEventConsumedTouchMoveTapTest) { - scoped_ptr<QueueTouchEventDelegate> delegate( - new QueueTouchEventDelegate(host()->dispatcher())); - TimedEvents tes; - const int kTouchId = 7; - gfx::Rect bounds(0, 0, 1000, 1000); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - delegate->set_window(window.get()); - - ui::TouchEvent press(ui::ET_TOUCH_PRESSED, gfx::Point(0, 0), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&press); - delegate->ReceivedAck(); - - ui::TouchEvent move(ui::ET_TOUCH_MOVED, gfx::Point(2, 2), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&move); - delegate->ReceivedAckPreventDefaulted(); - - ui::TouchEvent release(ui::ET_TOUCH_RELEASED, gfx::Point(2, 2), - kTouchId, tes.LeapForward(50)); - DispatchEventUsingWindowDispatcher(&release); - delegate->ReceivedAck(); - - EXPECT_TRUE(delegate->tap()); -} - -// Test that consuming the first move touch doesn't prevent a long press. -TEST_F(GestureRecognizerTest, GestureEventConsumedTouchMoveLongPressTest) { - scoped_ptr<QueueTouchEventDelegate> delegate( - new QueueTouchEventDelegate(host()->dispatcher())); - TimedEvents tes; - const int kWindowWidth = 123; - const int kWindowHeight = 45; - const int kTouchId = 2; - gfx::Rect bounds(100, 200, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - delegate->set_window(window.get()); - - delegate->Reset(); - - ui::TouchEvent press1(ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&press1); - delegate->ReceivedAck(); - - ui::TouchEvent move(ui::ET_TOUCH_MOVED, gfx::Point(103, 203), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&move); - delegate->ReceivedAckPreventDefaulted(); - - // Wait until the timer runs out - delegate->WaitUntilReceivedGesture(ui::ET_GESTURE_LONG_PRESS); - EXPECT_TRUE(delegate->long_press()); -} - -// Tests that the deltas are correct when leaving the slop region very slowly. -TEST_F(GestureRecognizerTest, TestExceedingSlopSlowly) { - ui::GestureConfiguration::set_max_touch_move_in_pixels_for_click(3); - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - const int kWindowWidth = 234; - const int kWindowHeight = 345; - const int kTouchId = 5; - TimedEvents tes; - gfx::Rect bounds(0, 0, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - - ui::TouchEvent press( - ui::ET_TOUCH_PRESSED, gfx::Point(10, 10), kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&press); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - delegate->Reset(); - - ui::TouchEvent move1(ui::ET_TOUCH_MOVED, gfx::Point(11, 10), kTouchId, - tes.LeapForward(40)); - DispatchEventUsingWindowDispatcher(&move1); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_EQ(0, delegate->scroll_x()); - EXPECT_EQ(0, delegate->scroll_x_hint()); - delegate->Reset(); - - ui::TouchEvent move2(ui::ET_TOUCH_MOVED, gfx::Point(12, 10), kTouchId, - tes.LeapForward(40)); - DispatchEventUsingWindowDispatcher(&move2); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_EQ(0, delegate->scroll_x()); - EXPECT_EQ(0, delegate->scroll_x_hint()); - delegate->Reset(); - - - ui::TouchEvent move3(ui::ET_TOUCH_MOVED, gfx::PointF(13.1f, 10.f), kTouchId, - tes.LeapForward(40)); - DispatchEventUsingWindowDispatcher(&move3); - EXPECT_TRUE(delegate->scroll_begin()); - EXPECT_TRUE(delegate->scroll_update()); - EXPECT_NEAR(0.1, delegate->scroll_x(), 0.0001); - EXPECT_FLOAT_EQ(3.1f, delegate->scroll_x_hint()); - delegate->Reset(); - - ui::TouchEvent move4(ui::ET_TOUCH_MOVED, gfx::Point(14, 10), kTouchId, - tes.LeapForward(40)); - DispatchEventUsingWindowDispatcher(&move4); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_TRUE(delegate->scroll_update()); - EXPECT_NEAR(0.9, delegate->scroll_x(), 0.0001); - EXPECT_EQ(0.f, delegate->scroll_x_hint()); - delegate->Reset(); -} - -TEST_F(GestureRecognizerTest, ScrollAlternatelyConsumedTest) { - scoped_ptr<QueueTouchEventDelegate> delegate( - new QueueTouchEventDelegate(host()->dispatcher())); - TimedEvents tes; - const int kWindowWidth = 3000; - const int kWindowHeight = 3000; - const int kTouchId = 2; - gfx::Rect bounds(0, 0, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - delegate->set_window(window.get()); - - delegate->Reset(); - - int x = 0; - int y = 0; - - ui::TouchEvent press1(ui::ET_TOUCH_PRESSED, gfx::Point(x, y), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&press1); - delegate->ReceivedAck(); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - delegate->Reset(); - - x += 100; - y += 100; - ui::TouchEvent move1(ui::ET_TOUCH_MOVED, gfx::Point(x, y), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&move1); - delegate->ReceivedAck(); - EXPECT_TRUE(delegate->scroll_begin()); - EXPECT_TRUE(delegate->scroll_update()); - delegate->Reset(); - - for (int i = 0; i < 3; ++i) { - x += 10; - y += 10; - ui::TouchEvent move2( - ui::ET_TOUCH_MOVED, gfx::Point(x, y), kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&move2); - delegate->ReceivedAck(); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_TRUE(delegate->scroll_update()); - EXPECT_EQ(10, delegate->scroll_x()); - EXPECT_EQ(10, delegate->scroll_y()); - delegate->Reset(); - - x += 20; - y += 20; - ui::TouchEvent move3( - ui::ET_TOUCH_MOVED, gfx::Point(x, y), kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&move3); - delegate->ReceivedAckPreventDefaulted(); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - delegate->Reset(); - } -} - -TEST_F(GestureRecognizerTest, PinchAlternatelyConsumedTest) { - scoped_ptr<QueueTouchEventDelegate> delegate( - new QueueTouchEventDelegate(host()->dispatcher())); - TimedEvents tes; - const int kWindowWidth = 3000; - const int kWindowHeight = 3000; - const int kTouchId1 = 5; - const int kTouchId2 = 7; - gfx::Rect bounds(0, 0, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - delegate->set_window(window.get()); - delegate->Reset(); - - ui::TouchEvent press1(ui::ET_TOUCH_PRESSED, gfx::Point(0, 0), - kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&press1); - delegate->ReceivedAck(); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - delegate->Reset(); - - int x = 0; - int y = 0; - - ui::TouchEvent press2(ui::ET_TOUCH_PRESSED, gfx::Point(x, y), - kTouchId2, tes.Now()); - DispatchEventUsingWindowDispatcher(&press2); - delegate->ReceivedAck(); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->pinch_begin()); - EXPECT_FALSE(delegate->pinch_update()); - - delegate->Reset(); - - x += 100; - y += 100; - ui::TouchEvent move1(ui::ET_TOUCH_MOVED, gfx::Point(x, y), - kTouchId2, tes.Now()); - DispatchEventUsingWindowDispatcher(&move1); - delegate->ReceivedAck(); - EXPECT_TRUE(delegate->scroll_begin()); - EXPECT_TRUE(delegate->scroll_update()); - EXPECT_TRUE(delegate->pinch_begin()); - EXPECT_FALSE(delegate->pinch_update()); - delegate->Reset(); - - const float expected_scales[] = {1.5f, 1.2f, 1.125f}; - - for (int i = 0; i < 3; ++i) { - x += 50; - y += 50; - ui::TouchEvent move2( - ui::ET_TOUCH_MOVED, gfx::Point(x, y), kTouchId2, tes.Now()); - DispatchEventUsingWindowDispatcher(&move2); - delegate->ReceivedAck(); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_TRUE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - EXPECT_FALSE(delegate->pinch_begin()); - EXPECT_TRUE(delegate->pinch_update()); - EXPECT_FALSE(delegate->pinch_end()); - EXPECT_EQ(25, delegate->scroll_x()); - EXPECT_EQ(25, delegate->scroll_y()); - EXPECT_FLOAT_EQ(expected_scales[i], delegate->scale()); - delegate->Reset(); - - x += 100; - y += 100; - ui::TouchEvent move3( - ui::ET_TOUCH_MOVED, gfx::Point(x, y), kTouchId2, tes.Now()); - DispatchEventUsingWindowDispatcher(&move3); - delegate->ReceivedAckPreventDefaulted(); - EXPECT_FALSE(delegate->scroll_begin()); - EXPECT_FALSE(delegate->scroll_update()); - EXPECT_FALSE(delegate->scroll_end()); - EXPECT_FALSE(delegate->pinch_begin()); - EXPECT_FALSE(delegate->pinch_update()); - EXPECT_FALSE(delegate->pinch_end()); - delegate->Reset(); - } -} - -// Test that touch event flags are passed through to the gesture event. -TEST_F(GestureRecognizerTest, GestureEventFlagsPassedFromTouchEvent) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - TimedEvents tes; - const int kWindowWidth = 123; - const int kWindowHeight = 45; - const int kTouchId = 6; - gfx::Rect bounds(100, 200, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - - delegate->Reset(); - - ui::TouchEvent press1(ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&press1); - EXPECT_TRUE(delegate->tap_down()); - - int default_flags = delegate->flags(); - - ui::TouchEvent move1( - ui::ET_TOUCH_MOVED, gfx::Point(397, 149), kTouchId, tes.LeapForward(50)); - move1.set_flags(992); - - DispatchEventUsingWindowDispatcher(&move1); - EXPECT_NE(default_flags, delegate->flags()); -} - -// Test that latency info is passed through to the gesture event. -TEST_F(GestureRecognizerTest, LatencyPassedFromTouchEvent) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - TimedEvents tes; - const int kWindowWidth = 123; - const int kWindowHeight = 45; - const int kTouchId = 6; - - const base::TimeTicks time_original = base::TimeTicks::FromInternalValue(100); - const base::TimeTicks time_ui = base::TimeTicks::FromInternalValue(200); - const base::TimeTicks time_acked = base::TimeTicks::FromInternalValue(300); - - gfx::Rect bounds(100, 200, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - - delegate->Reset(); - - ui::TouchEvent press1(ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), - kTouchId, tes.Now()); - - // Ensure the only components around are the ones we add. - press1.latency()->Clear(); - - press1.latency()->AddLatencyNumberWithTimestamp( - ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT, 0, 0, time_original, 1); - - press1.latency()->AddLatencyNumberWithTimestamp( - ui::INPUT_EVENT_LATENCY_UI_COMPONENT, 0, 0, time_ui, 1); - - press1.latency()->AddLatencyNumberWithTimestamp( - ui::INPUT_EVENT_LATENCY_ACKED_TOUCH_COMPONENT, 0, 0, time_acked, 1); - - DispatchEventUsingWindowDispatcher(&press1); - EXPECT_TRUE(delegate->tap_down()); - - ui::LatencyInfo::LatencyComponent component; - - EXPECT_EQ(3U, delegate->latency_info().latency_components.size()); - ASSERT_TRUE(delegate->latency_info().FindLatency( - ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT, 0, &component)); - EXPECT_EQ(time_original, component.event_time); - - ASSERT_TRUE(delegate->latency_info().FindLatency( - ui::INPUT_EVENT_LATENCY_UI_COMPONENT, 0, &component)); - EXPECT_EQ(time_ui, component.event_time); - - ASSERT_TRUE(delegate->latency_info().FindLatency( - ui::INPUT_EVENT_LATENCY_ACKED_TOUCH_COMPONENT, 0, &component)); - EXPECT_EQ(time_acked, component.event_time); - - delegate->WaitUntilReceivedGesture(ui::ET_GESTURE_SHOW_PRESS); - EXPECT_TRUE(delegate->show_press()); - EXPECT_EQ(0U, delegate->latency_info().latency_components.size()); -} - -// A delegate that deletes a window on long press. -class GestureEventDeleteWindowOnLongPress : public GestureEventConsumeDelegate { - public: - GestureEventDeleteWindowOnLongPress() - : window_(NULL) {} - - void set_window(aura::Window** window) { window_ = window; } - - virtual void OnGestureEvent(ui::GestureEvent* gesture) override { - GestureEventConsumeDelegate::OnGestureEvent(gesture); - if (gesture->type() != ui::ET_GESTURE_LONG_PRESS) - return; - ui::GestureRecognizer::Get()->CleanupStateForConsumer(*window_); - delete *window_; - *window_ = NULL; - } - - private: - aura::Window** window_; - DISALLOW_COPY_AND_ASSIGN(GestureEventDeleteWindowOnLongPress); -}; - -// Check that deleting the window in response to a long press gesture doesn't -// crash. -TEST_F(GestureRecognizerTest, GestureEventLongPressDeletingWindow) { - GestureEventDeleteWindowOnLongPress delegate; - const int kWindowWidth = 123; - const int kWindowHeight = 45; - const int kTouchId = 2; - gfx::Rect bounds(100, 200, kWindowWidth, kWindowHeight); - aura::Window* window(CreateTestWindowWithDelegate( - &delegate, -1234, bounds, root_window())); - delegate.set_window(&window); - - ui::TouchEvent press1(ui::ET_TOUCH_PRESSED, - gfx::Point(101, 201), - kTouchId, - ui::EventTimeForNow()); - DispatchEventUsingWindowDispatcher(&press1); - EXPECT_TRUE(window != NULL); - - // Wait until the timer runs out. - delegate.WaitUntilReceivedGesture(ui::ET_GESTURE_LONG_PRESS); - EXPECT_EQ(NULL, window); -} - -TEST_F(GestureRecognizerTest, GestureEventSmallPinchDisabled) { - CommandLine::ForCurrentProcess()->AppendSwitch( - switches::kCompensateForUnstablePinchZoom); - - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - TimedEvents tes; - const int kWindowWidth = 300; - const int kWindowHeight = 400; - const int kTouchId1 = 3; - const int kTouchId2 = 5; - gfx::Rect bounds(5, 5, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - - ui::TouchEvent press1(ui::ET_TOUCH_PRESSED, gfx::Point(101, 301), - kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&press1); - ui::TouchEvent press2(ui::ET_TOUCH_PRESSED, gfx::Point(10, 10), - kTouchId2, tes.Now()); - DispatchEventUsingWindowDispatcher(&press2); - - // Move the first finger. - delegate->Reset(); - ui::TouchEvent move1(ui::ET_TOUCH_MOVED, gfx::Point(65, 201), - kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&move1); - - EXPECT_3_EVENTS(delegate->events(), - ui::ET_GESTURE_SCROLL_BEGIN, - ui::ET_GESTURE_SCROLL_UPDATE, - ui::ET_GESTURE_PINCH_BEGIN); - - // No pinch update occurs, as kCompensateForUnstablePinchZoom is on, and this - // is a very small pinch. - delegate->Reset(); - ui::TouchEvent move2(ui::ET_TOUCH_MOVED, gfx::Point(65, 202), - kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&move2); - EXPECT_1_EVENT(delegate->events(), ui::ET_GESTURE_SCROLL_UPDATE); -} - -TEST_F(GestureRecognizerTest, GestureEventSmallPinchEnabled) { - scoped_ptr<GestureEventConsumeDelegate> delegate( - new GestureEventConsumeDelegate()); - TimedEvents tes; - const int kWindowWidth = 300; - const int kWindowHeight = 400; - const int kTouchId1 = 3; - const int kTouchId2 = 5; - gfx::Rect bounds(5, 5, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - - ui::TouchEvent press1(ui::ET_TOUCH_PRESSED, gfx::Point(101, 301), - kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&press1); - ui::TouchEvent press2(ui::ET_TOUCH_PRESSED, gfx::Point(10, 10), - kTouchId2, tes.Now()); - DispatchEventUsingWindowDispatcher(&press2); - - // Move the first finger. - delegate->Reset(); - ui::TouchEvent move1(ui::ET_TOUCH_MOVED, gfx::Point(65, 201), - kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&move1); - - EXPECT_3_EVENTS(delegate->events(), - ui::ET_GESTURE_SCROLL_BEGIN, - ui::ET_GESTURE_SCROLL_UPDATE, - ui::ET_GESTURE_PINCH_BEGIN); - - delegate->Reset(); - ui::TouchEvent move2(ui::ET_TOUCH_MOVED, gfx::Point(65, 202), - kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&move2); - EXPECT_2_EVENTS(delegate->events(), - ui::ET_GESTURE_SCROLL_UPDATE, - ui::ET_GESTURE_PINCH_UPDATE); -} - -// Tests that delaying the ack of a touch release doesn't trigger a long press -// gesture. -TEST_F(GestureRecognizerTest, DISABLED_EagerGestureDetection) { - scoped_ptr<QueueTouchEventDelegate> delegate( - new QueueTouchEventDelegate(host()->dispatcher())); - TimedEvents tes; - const int kTouchId = 2; - gfx::Rect bounds(100, 200, 100, 100); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - delegate->set_window(window.get()); - - delegate->Reset(); - ui::TouchEvent press(ui::ET_TOUCH_PRESSED, gfx::Point(101, 201), - kTouchId, tes.Now()); - DispatchEventUsingWindowDispatcher(&press); - ui::TouchEvent release(ui::ET_TOUCH_RELEASED, gfx::Point(101, 201), - kTouchId, tes.LeapForward(50)); - DispatchEventUsingWindowDispatcher(&release); - - delegate->Reset(); - // Ack the touch press. - delegate->ReceivedAck(); - EXPECT_TRUE(delegate->tap_down()); - - delegate->Reset(); - // Wait until the long press event would fire (if we weren't eager). - DelayByLongPressTimeout(); - - // Ack the touch release. - delegate->ReceivedAck(); - EXPECT_TRUE(delegate->tap()); - EXPECT_FALSE(delegate->long_press()); -} - -// This tests crbug.com/405519, in which events which the gesture detector -// ignores cause future events to also be thrown away. -TEST_F(GestureRecognizerTest, IgnoredEventsDontPreventFutureEvents) { - scoped_ptr<QueueTouchEventDelegate> delegate( - new QueueTouchEventDelegate(host()->dispatcher())); - TimedEvents tes; - const int kWindowWidth = 300; - const int kWindowHeight = 400; - const int kTouchId1 = 3; - gfx::Rect bounds(5, 5, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - delegate.get(), -1234, bounds, root_window())); - delegate->set_window(window.get()); - - ui::TouchEvent press1( - ui::ET_TOUCH_PRESSED, gfx::Point(101, 301), kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&press1); - delegate->ReceivedAck(); - - EXPECT_2_EVENTS( - delegate->events(), ui::ET_GESTURE_BEGIN, ui::ET_GESTURE_TAP_DOWN); - - // Move the first finger. - delegate->Reset(); - ui::TouchEvent move1( - ui::ET_TOUCH_MOVED, gfx::Point(65, 201), kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&move1); - delegate->ReceivedAck(); - - EXPECT_3_EVENTS(delegate->events(), - ui::ET_GESTURE_TAP_CANCEL, - ui::ET_GESTURE_SCROLL_BEGIN, - ui::ET_GESTURE_SCROLL_UPDATE); - - delegate->Reset(); - ui::TouchEvent move2( - ui::ET_TOUCH_MOVED, gfx::Point(65, 202), kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&move2); - - // Send a touchmove event at the same location as the previous touchmove - // event. This shouldn't do anything. - ui::TouchEvent move3( - ui::ET_TOUCH_MOVED, gfx::Point(65, 202), kTouchId1, tes.Now()); - DispatchEventUsingWindowDispatcher(&move3); - - delegate->ReceivedAck(); - EXPECT_1_EVENT(delegate->events(), ui::ET_GESTURE_SCROLL_UPDATE); -} - -} // namespace test -} // namespace aura
diff --git a/ui/aura/input_state_lookup.cc b/ui/aura/input_state_lookup.cc deleted file mode 100644 index 86ab3cd..0000000 --- a/ui/aura/input_state_lookup.cc +++ /dev/null
@@ -1,16 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/input_state_lookup.h" - -#include "base/logging.h" - -namespace aura { - -// static -scoped_ptr<InputStateLookup> InputStateLookup::Create() { - return scoped_ptr<InputStateLookup>(); -} - -} // namespace aura
diff --git a/ui/aura/input_state_lookup.h b/ui/aura/input_state_lookup.h deleted file mode 100644 index 4c2b424..0000000 --- a/ui/aura/input_state_lookup.h +++ /dev/null
@@ -1,27 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_INPUT_STATE_LOOKUP_H_ -#define UI_AURA_INPUT_STATE_LOOKUP_H_ - -#include "base/memory/scoped_ptr.h" -#include "ui/aura/aura_export.h" - -namespace aura { - -// InputStateLookup is used to obtain the state of input devices. -class AURA_EXPORT InputStateLookup { - public: - virtual ~InputStateLookup() {} - - // Creates the platform specific InputStateLookup. May return NULL. - static scoped_ptr<InputStateLookup> Create(); - - // Returns true if any mouse button is down. - virtual bool IsMouseButtonDown() const = 0; -}; - -} // namespace aura - -#endif // UI_AURA_INPUT_STATE_LOOKUP_H_
diff --git a/ui/aura/input_state_lookup_win.cc b/ui/aura/input_state_lookup_win.cc deleted file mode 100644 index 7a6bf12..0000000 --- a/ui/aura/input_state_lookup_win.cc +++ /dev/null
@@ -1,31 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/input_state_lookup_win.h" - -#include <windows.h> -#include <winuser.h> - -namespace aura { - -// static -scoped_ptr<InputStateLookup> InputStateLookup::Create() { - return scoped_ptr<InputStateLookup>(new InputStateLookupWin); -} - -InputStateLookupWin::InputStateLookupWin() { -} - -InputStateLookupWin::~InputStateLookupWin() { -} - -bool InputStateLookupWin::IsMouseButtonDown() const { - return (GetKeyState(VK_LBUTTON) & 0x80) || - (GetKeyState(VK_RBUTTON) & 0x80) || - (GetKeyState(VK_MBUTTON) & 0x80) || - (GetKeyState(VK_XBUTTON1) & 0x80) || - (GetKeyState(VK_XBUTTON2) & 0x80); -} - -} // namespace aura
diff --git a/ui/aura/input_state_lookup_win.h b/ui/aura/input_state_lookup_win.h deleted file mode 100644 index 94e4ee6..0000000 --- a/ui/aura/input_state_lookup_win.h +++ /dev/null
@@ -1,29 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_INPUT_STATE_LOOKUP_WIN_H_ -#define UI_AURA_INPUT_STATE_LOOKUP_WIN_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "ui/aura/input_state_lookup.h" - -namespace aura { - -// Windows implementation of InputStateLookup. -class AURA_EXPORT InputStateLookupWin : public InputStateLookup { - public: - InputStateLookupWin(); - virtual ~InputStateLookupWin(); - - // InputStateLookup overrides: - virtual bool IsMouseButtonDown() const override; - - private: - DISALLOW_COPY_AND_ASSIGN(InputStateLookupWin); -}; - -} // namespace aura - -#endif // UI_AURA_INPUT_STATE_LOOKUP_WIN_H_
diff --git a/ui/aura/layout_manager.cc b/ui/aura/layout_manager.cc deleted file mode 100644 index 1621995..0000000 --- a/ui/aura/layout_manager.cc +++ /dev/null
@@ -1,22 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/layout_manager.h" - -#include "ui/aura/window.h" - -namespace aura { - -LayoutManager::LayoutManager() { -} - -LayoutManager::~LayoutManager() { -} - -void LayoutManager::SetChildBoundsDirect(aura::Window* child, - const gfx::Rect& bounds) { - child->SetBoundsInternal(bounds); -} - -} // namespace aura
diff --git a/ui/aura/layout_manager.h b/ui/aura/layout_manager.h deleted file mode 100644 index 2ae4606..0000000 --- a/ui/aura/layout_manager.h +++ /dev/null
@@ -1,58 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_LAYOUT_MANAGER_H_ -#define UI_AURA_LAYOUT_MANAGER_H_ - -#include "base/basictypes.h" -#include "ui/aura/aura_export.h" - -namespace gfx { -class Rect; -} - -namespace aura { -class Window; - -// An interface implemented by an object that places child windows. -class AURA_EXPORT LayoutManager { - public: - LayoutManager(); - virtual ~LayoutManager(); - - // Invoked when the window is resized. - virtual void OnWindowResized() = 0; - - // Invoked when the window |child| has been added. - virtual void OnWindowAddedToLayout(Window* child) = 0; - - // Invoked prior to removing |window|. - virtual void OnWillRemoveWindowFromLayout(Window* child) = 0; - - // Invoked after removing |window|. - virtual void OnWindowRemovedFromLayout(Window* child) = 0; - - // Invoked when the |SetVisible()| is invoked on the window |child|. - // |visible| is the value supplied to |SetVisible()|. If |visible| is true, - // window->IsVisible() may still return false. See description in - // Window::IsVisible() for details. - virtual void OnChildWindowVisibilityChanged(Window* child, bool visible) = 0; - - // Invoked when |Window::SetBounds| is called on |child|. - // Implementation must call |SetChildBoundsDirect| to change the - // |child|'s bounds. LayoutManager may modify |requested_bounds| - // before applying, or ignore the request. - virtual void SetChildBounds(Window* child, - const gfx::Rect& requested_bounds) = 0; - - protected: - // Sets the child's bounds forcibly. LayoutManager is responsible - // for checking the state and make sure the bounds are correctly - // adjusted. - void SetChildBoundsDirect(aura::Window* child, const gfx::Rect& bounds); -}; - -} // namespace aura - -#endif // UI_AURA_LAYOUT_MANAGER_H_
diff --git a/ui/aura/scoped_window_targeter.cc b/ui/aura/scoped_window_targeter.cc deleted file mode 100644 index d71e919..0000000 --- a/ui/aura/scoped_window_targeter.cc +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/scoped_window_targeter.h" - -#include "ui/aura/window.h" - -namespace aura { - -ScopedWindowTargeter::ScopedWindowTargeter( - Window* window, - scoped_ptr<ui::EventTargeter> new_targeter) - : window_(window), - old_targeter_(window->SetEventTargeter(new_targeter.Pass())) { - window_->AddObserver(this); -} - -ScopedWindowTargeter::~ScopedWindowTargeter() { - if (window_) { - window_->RemoveObserver(this); - window_->SetEventTargeter(old_targeter_.Pass()); - } -} - -void ScopedWindowTargeter::OnWindowDestroyed(Window* window) { - CHECK_EQ(window_, window); - window_ = NULL; - old_targeter_.reset(); -} - -} // namespace aura
diff --git a/ui/aura/scoped_window_targeter.h b/ui/aura/scoped_window_targeter.h deleted file mode 100644 index 14c3e89..0000000 --- a/ui/aura/scoped_window_targeter.h +++ /dev/null
@@ -1,46 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_SCOPED_WINDOW_TARGETER_H_ -#define UI_AURA_SCOPED_WINDOW_TARGETER_H_ - -#include "base/macros.h" -#include "base/memory/scoped_ptr.h" -#include "ui/aura/window_observer.h" - -namespace ui { -class EventTargeter; -} - -namespace aura { - -class Window; - -// ScopedWindowTargeter is used to temporarily replace the event-targeter for a -// window. Upon construction, it installs a new targeter on the window, and upon -// destruction, it restores the previous event-targeter on the window. -class AURA_EXPORT ScopedWindowTargeter : public WindowObserver { - public: - ScopedWindowTargeter(Window* window, - scoped_ptr<ui::EventTargeter> new_targeter); - - virtual ~ScopedWindowTargeter(); - - ui::EventTargeter* old_targeter() { - return old_targeter_.get(); - } - - private: - // WindowObserver: - virtual void OnWindowDestroyed(Window* window) override; - - Window* window_; - scoped_ptr<ui::EventTargeter> old_targeter_; - - DISALLOW_COPY_AND_ASSIGN(ScopedWindowTargeter); -}; - -} // namespace aura - -#endif // UI_AURA_SCOPED_WINDOW_TARGETER_H_
diff --git a/ui/aura/test/DEPS b/ui/aura/test/DEPS deleted file mode 100644 index f59fd38..0000000 --- a/ui/aura/test/DEPS +++ /dev/null
@@ -1,3 +0,0 @@ -include_rules = [ - "+ui/gl", -]
diff --git a/ui/aura/test/aura_test_base.cc b/ui/aura/test/aura_test_base.cc deleted file mode 100644 index a6271cc..0000000 --- a/ui/aura/test/aura_test_base.cc +++ /dev/null
@@ -1,107 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/test/aura_test_base.h" - -#include "ui/aura/client/window_tree_client.h" -#include "ui/aura/test/aura_test_helper.h" -#include "ui/aura/test/test_window_delegate.h" -#include "ui/aura/window.h" -#include "ui/base/ime/input_method_initializer.h" -#include "ui/compositor/test/context_factories_for_test.h" -#include "ui/events/event_dispatcher.h" -#include "ui/events/event_processor.h" -#include "ui/events/gestures/gesture_configuration.h" - -namespace aura { -namespace test { - -AuraTestBase::AuraTestBase() - : setup_called_(false), - teardown_called_(false) { -} - -AuraTestBase::~AuraTestBase() { - CHECK(setup_called_) - << "You have overridden SetUp but never called super class's SetUp"; - CHECK(teardown_called_) - << "You have overridden TearDown but never called super class's TearDown"; -} - -void AuraTestBase::SetUp() { - setup_called_ = true; - testing::Test::SetUp(); - ui::InitializeInputMethodForTesting(); - - // Changing the parameters for gesture recognition shouldn't cause - // tests to fail, so we use a separate set of parameters for unit - // testing. - ui::GestureConfiguration::set_long_press_time_in_ms(1000); - ui::GestureConfiguration::set_semi_long_press_time_in_ms(400); - ui::GestureConfiguration::set_show_press_delay_in_ms(5); - ui::GestureConfiguration::set_max_distance_for_two_finger_tap_in_pixels(300); - ui::GestureConfiguration::set_max_time_between_double_click_in_ms(700); - ui::GestureConfiguration:: - set_max_separation_for_gesture_touches_in_pixels(150); - ui::GestureConfiguration::set_max_touch_down_duration_for_click_in_ms(800); - ui::GestureConfiguration::set_max_touch_move_in_pixels_for_click(5); - ui::GestureConfiguration::set_max_distance_between_taps_for_double_tap(20); - ui::GestureConfiguration::set_min_distance_for_pinch_scroll_in_pixels(20); - ui::GestureConfiguration::set_min_pinch_update_distance_in_pixels(5); - ui::GestureConfiguration::set_default_radius(0); - ui::GestureConfiguration::set_fling_velocity_cap(15000); - ui::GestureConfiguration::set_min_swipe_speed(10); - - // The ContextFactory must exist before any Compositors are created. - bool enable_pixel_output = false; - ui::ContextFactory* context_factory = - ui::InitializeContextFactoryForTests(enable_pixel_output); - - helper_.reset(new AuraTestHelper(&message_loop_)); - helper_->SetUp(context_factory); -} - -void AuraTestBase::TearDown() { - teardown_called_ = true; - - // Flush the message loop because we have pending release tasks - // and these tasks if un-executed would upset Valgrind. - RunAllPendingInMessageLoop(); - - helper_->TearDown(); - ui::TerminateContextFactoryForTests(); - ui::ShutdownInputMethodForTesting(); - testing::Test::TearDown(); -} - -Window* AuraTestBase::CreateNormalWindow(int id, Window* parent, - WindowDelegate* delegate) { - Window* window = new Window( - delegate ? delegate : - test::TestWindowDelegate::CreateSelfDestroyingDelegate()); - window->set_id(id); - window->Init(aura::WINDOW_LAYER_TEXTURED); - parent->AddChild(window); - window->SetBounds(gfx::Rect(0, 0, 100, 100)); - window->Show(); - return window; -} - -void AuraTestBase::RunAllPendingInMessageLoop() { - helper_->RunAllPendingInMessageLoop(); -} - -void AuraTestBase::ParentWindow(Window* window) { - client::ParentWindowWithContext(window, root_window(), gfx::Rect()); -} - -bool AuraTestBase::DispatchEventUsingWindowDispatcher(ui::Event* event) { - ui::EventDispatchDetails details = - event_processor()->OnEventFromSource(event); - CHECK(!details.dispatcher_destroyed); - return event->handled(); -} - -} // namespace test -} // namespace aura
diff --git a/ui/aura/test/aura_test_base.h b/ui/aura/test/aura_test_base.h deleted file mode 100644 index 4717243..0000000 --- a/ui/aura/test/aura_test_base.h +++ /dev/null
@@ -1,60 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_TEST_AURA_TEST_BASE_H_ -#define UI_AURA_TEST_AURA_TEST_BASE_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/message_loop/message_loop.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/aura/test/aura_test_helper.h" - -namespace aura { -class Window; -class WindowDelegate; -namespace test { - -// A base class for aura unit tests. -// TODO(beng): Instances of this test will create and own a RootWindow. -class AuraTestBase : public testing::Test { - public: - AuraTestBase(); - virtual ~AuraTestBase(); - - // testing::Test: - virtual void SetUp() override; - virtual void TearDown() override; - - // Creates a normal window parented to |parent|. - aura::Window* CreateNormalWindow(int id, Window* parent, - aura::WindowDelegate* delegate); - - protected: - void RunAllPendingInMessageLoop(); - - void ParentWindow(Window* window); - - // A convenience function for dispatching an event to |dispatcher()|. - // Returns whether |event| was handled. - bool DispatchEventUsingWindowDispatcher(ui::Event* event); - - Window* root_window() { return helper_->root_window(); } - WindowTreeHost* host() { return helper_->host(); } - ui::EventProcessor* event_processor() { return helper_->event_processor(); } - TestScreen* test_screen() { return helper_->test_screen(); } - - private: - bool setup_called_; - bool teardown_called_; - base::MessageLoopForUI message_loop_; - scoped_ptr<AuraTestHelper> helper_; - - DISALLOW_COPY_AND_ASSIGN(AuraTestBase); -}; - -} // namespace test -} // namespace aura - -#endif // UI_AURA_TEST_AURA_TEST_BASE_H_
diff --git a/ui/aura/test/aura_test_helper.cc b/ui/aura/test/aura_test_helper.cc deleted file mode 100644 index 836cf03..0000000 --- a/ui/aura/test/aura_test_helper.cc +++ /dev/null
@@ -1,117 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/test/aura_test_helper.h" - -#include "base/message_loop/message_loop.h" -#include "base/run_loop.h" -#include "ui/aura/client/aura_constants.h" -#include "ui/aura/client/default_capture_client.h" -#include "ui/aura/client/focus_client.h" -#include "ui/aura/env.h" -#include "ui/aura/input_state_lookup.h" -#include "ui/aura/test/env_test_helper.h" -#include "ui/aura/test/event_generator_delegate_aura.h" -#include "ui/aura/test/test_focus_client.h" -#include "ui/aura/test/test_screen.h" -#include "ui/aura/test/test_window_tree_client.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/base/ime/dummy_input_method.h" -#include "ui/base/ime/input_method_initializer.h" -#include "ui/compositor/compositor.h" -#include "ui/compositor/layer_animator.h" -#include "ui/compositor/scoped_animation_duration_scale_mode.h" -#include "ui/gfx/screen.h" - -#if defined(USE_X11) -#include "ui/aura/window_tree_host_x11.h" -#include "ui/base/x/x11_util.h" -#endif - -namespace aura { -namespace test { - -AuraTestHelper::AuraTestHelper(base::MessageLoopForUI* message_loop) - : setup_called_(false), - teardown_called_(false), - owns_host_(false) { - DCHECK(message_loop); - message_loop_ = message_loop; - // Disable animations during tests. - zero_duration_mode_.reset(new ui::ScopedAnimationDurationScaleMode( - ui::ScopedAnimationDurationScaleMode::ZERO_DURATION)); -#if defined(USE_X11) - test::SetUseOverrideRedirectWindowByDefault(true); -#endif - InitializeAuraEventGeneratorDelegate(); -} - -AuraTestHelper::~AuraTestHelper() { - CHECK(setup_called_) - << "AuraTestHelper::SetUp() never called."; - CHECK(teardown_called_) - << "AuraTestHelper::TearDown() never called."; -} - -void AuraTestHelper::SetUp(ui::ContextFactory* context_factory) { - setup_called_ = true; - - Env::CreateInstance(true); - Env::GetInstance()->set_context_factory(context_factory); - // Unit tests generally don't want to query the system, rather use the state - // from RootWindow. - EnvTestHelper(Env::GetInstance()).SetInputStateLookup( - scoped_ptr<InputStateLookup>()); - - ui::InitializeInputMethodForTesting(); - - gfx::Size host_size(800, 600); - test_screen_.reset(TestScreen::Create(host_size)); - gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE, test_screen_.get()); - host_.reset(test_screen_->CreateHostForPrimaryDisplay()); - - focus_client_.reset(new TestFocusClient); - client::SetFocusClient(root_window(), focus_client_.get()); - stacking_client_.reset(new TestWindowTreeClient(root_window())); - capture_client_.reset(new client::DefaultCaptureClient(root_window())); - test_input_method_.reset(new ui::DummyInputMethod); - root_window()->SetProperty( - client::kRootWindowInputMethodKey, - test_input_method_.get()); - - root_window()->Show(); - // Ensure width != height so tests won't confuse them. - host()->SetBounds(gfx::Rect(host_size)); -} - -void AuraTestHelper::TearDown() { - teardown_called_ = true; - test_input_method_.reset(); - stacking_client_.reset(); - capture_client_.reset(); - focus_client_.reset(); - client::SetFocusClient(root_window(), NULL); - host_.reset(); - ui::GestureRecognizer::Reset(); - test_screen_.reset(); - gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE, NULL); - -#if defined(USE_X11) - ui::test::ResetXCursorCache(); -#endif - - ui::ShutdownInputMethodForTesting(); - - Env::DeleteInstance(); -} - -void AuraTestHelper::RunAllPendingInMessageLoop() { - // TODO(jbates) crbug.com/134753 Find quitters of this RunLoop and have them - // use run_loop.QuitClosure(). - base::RunLoop run_loop; - run_loop.RunUntilIdle(); -} - -} // namespace test -} // namespace aura
diff --git a/ui/aura/test/aura_test_helper.h b/ui/aura/test/aura_test_helper.h deleted file mode 100644 index d547b0c..0000000 --- a/ui/aura/test/aura_test_helper.h +++ /dev/null
@@ -1,75 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_TEST_AURA_TEST_HELPER_H_ -#define UI_AURA_TEST_AURA_TEST_HELPER_H_ - -#include "base/basictypes.h" -#include "base/memory/scoped_ptr.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/aura/window_tree_host.h" - -namespace base { -class MessageLoopForUI; -} - -namespace ui { -class ContextFactory; -class InputMethod; -class ScopedAnimationDurationScaleMode; -} - -namespace aura { -class TestScreen; -namespace client { -class DefaultCaptureClient; -class FocusClient; -} -namespace test { -class TestWindowTreeClient; - -// A helper class owned by tests that does common initialization required for -// Aura use. This class creates a root window with clients and other objects -// that are necessary to run test on Aura. -class AuraTestHelper { - public: - explicit AuraTestHelper(base::MessageLoopForUI* message_loop); - ~AuraTestHelper(); - - // Creates and initializes (shows and sizes) the RootWindow for use in tests. - void SetUp(ui::ContextFactory* context_factory); - - // Clean up objects that are created for tests. This also deletes the Env - // object. - void TearDown(); - - // Flushes message loop. - void RunAllPendingInMessageLoop(); - - Window* root_window() { return host_->window(); } - ui::EventProcessor* event_processor() { return host_->event_processor(); } - WindowTreeHost* host() { return host_.get(); } - - TestScreen* test_screen() { return test_screen_.get(); } - - private: - base::MessageLoopForUI* message_loop_; - bool setup_called_; - bool teardown_called_; - bool owns_host_; - scoped_ptr<WindowTreeHost> host_; - scoped_ptr<TestWindowTreeClient> stacking_client_; - scoped_ptr<client::DefaultCaptureClient> capture_client_; - scoped_ptr<ui::InputMethod> test_input_method_; - scoped_ptr<client::FocusClient> focus_client_; - scoped_ptr<TestScreen> test_screen_; - scoped_ptr<ui::ScopedAnimationDurationScaleMode> zero_duration_mode_; - - DISALLOW_COPY_AND_ASSIGN(AuraTestHelper); -}; - -} // namespace test -} // namespace aura - -#endif // UI_AURA_TEST_AURA_TEST_HELPER_H_
diff --git a/ui/aura/test/aura_test_utils.cc b/ui/aura/test/aura_test_utils.cc deleted file mode 100644 index fe4120b..0000000 --- a/ui/aura/test/aura_test_utils.cc +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/test/aura_test_utils.h" - -#include "ui/aura/window_tree_host.h" - -namespace aura { -namespace test { - -class WindowTreeHostTestApi { - public: - explicit WindowTreeHostTestApi(WindowTreeHost* host) : host_(host) {} - - const gfx::Point& last_cursor_request_position_in_host() { - return host_->last_cursor_request_position_in_host_; - } - - private: - WindowTreeHost* host_; - - DISALLOW_COPY_AND_ASSIGN(WindowTreeHostTestApi); -}; - -const gfx::Point& QueryLatestMousePositionRequestInHost(WindowTreeHost* host) { - WindowTreeHostTestApi host_test_api(host); - return host_test_api.last_cursor_request_position_in_host(); -} - -} // namespace test -} // namespace aura
diff --git a/ui/aura/test/aura_test_utils.h b/ui/aura/test/aura_test_utils.h deleted file mode 100644 index ec94b3c..0000000 --- a/ui/aura/test/aura_test_utils.h +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_TEST_AURA_TEST_UTILS_H_ -#define UI_AURA_TEST_AURA_TEST_UTILS_H_ - -#include "base/macros.h" - -namespace gfx { -class Point; -} - -namespace aura { -class WindowTreeHost; - -namespace test { - -const gfx::Point& QueryLatestMousePositionRequestInHost(WindowTreeHost* host); - -} // namespace test -} // namespace aura - -#endif // UI_AURA_TEST_AURA_TEST_UTILS_H_
diff --git a/ui/aura/test/env_test_helper.h b/ui/aura/test/env_test_helper.h deleted file mode 100644 index 0c1ef31..0000000 --- a/ui/aura/test/env_test_helper.h +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_TEST_ENV_TEST_HELPER_H_ -#define UI_AURA_TEST_ENV_TEST_HELPER_H_ - -#include "ui/aura/env.h" -#include "ui/aura/input_state_lookup.h" - -namespace aura { -namespace test { - -class EnvTestHelper { - public: - explicit EnvTestHelper(Env* env) : env_(env) {} - ~EnvTestHelper() {} - - void SetInputStateLookup(scoped_ptr<InputStateLookup> input_state_lookup) { - env_->input_state_lookup_ = input_state_lookup.Pass(); - } - - private: - Env* env_; - - DISALLOW_COPY_AND_ASSIGN(EnvTestHelper); -}; - -} // namespace test -} // namespace aura - -#endif // UI_AURA_TEST_ENV_TEST_HELPER_H_
diff --git a/ui/aura/test/event_generator_delegate_aura.cc b/ui/aura/test/event_generator_delegate_aura.cc deleted file mode 100644 index 576cc8e..0000000 --- a/ui/aura/test/event_generator_delegate_aura.cc +++ /dev/null
@@ -1,128 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/test/event_generator_delegate_aura.h" - -#include "base/memory/singleton.h" -#include "ui/aura/client/screen_position_client.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/aura/window_tree_host.h" - -namespace aura { -namespace test { -namespace { - -class DefaultEventGeneratorDelegate : public EventGeneratorDelegateAura { - public: - static DefaultEventGeneratorDelegate* GetInstance() { - return Singleton<DefaultEventGeneratorDelegate>::get(); - } - - // EventGeneratorDelegate: - virtual void SetContext(ui::test::EventGenerator* owner, - gfx::NativeWindow root_window, - gfx::NativeWindow window) override { - root_window_ = root_window; - } - - // EventGeneratorDelegateAura: - virtual WindowTreeHost* GetHostAt(const gfx::Point& point) const override { - return root_window_->GetHost(); - } - - virtual client::ScreenPositionClient* GetScreenPositionClient( - const aura::Window* window) const override { - return NULL; - } - - private: - friend struct DefaultSingletonTraits<DefaultEventGeneratorDelegate>; - - DefaultEventGeneratorDelegate() : root_window_(NULL) { - DCHECK(!ui::test::EventGenerator::default_delegate); - ui::test::EventGenerator::default_delegate = this; - } - - virtual ~DefaultEventGeneratorDelegate() { - DCHECK_EQ(this, ui::test::EventGenerator::default_delegate); - ui::test::EventGenerator::default_delegate = NULL; - } - - Window* root_window_; - - DISALLOW_COPY_AND_ASSIGN(DefaultEventGeneratorDelegate); -}; - -const Window* WindowFromTarget(const ui::EventTarget* event_target) { - return static_cast<const Window*>(event_target); -} - -} // namespace - -void InitializeAuraEventGeneratorDelegate() { - DefaultEventGeneratorDelegate::GetInstance(); -} - -EventGeneratorDelegateAura::EventGeneratorDelegateAura() { -} - -EventGeneratorDelegateAura::~EventGeneratorDelegateAura() { -} - -ui::EventTarget* EventGeneratorDelegateAura::GetTargetAt( - const gfx::Point& location) { - return GetHostAt(location)->window(); -} - -ui::EventSource* EventGeneratorDelegateAura::GetEventSource( - ui::EventTarget* target) { - return static_cast<Window*>(target)->GetHost()->GetEventSource(); -} - -gfx::Point EventGeneratorDelegateAura::CenterOfTarget( - const ui::EventTarget* target) const { - gfx::Point center = - gfx::Rect(WindowFromTarget(target)->bounds().size()).CenterPoint(); - ConvertPointFromTarget(target, ¢er); - return center; -} - -gfx::Point EventGeneratorDelegateAura::CenterOfWindow( - gfx::NativeWindow window) const { - return CenterOfTarget(window); -} - -void EventGeneratorDelegateAura::ConvertPointFromTarget( - const ui::EventTarget* event_target, - gfx::Point* point) const { - DCHECK(point); - const Window* target = WindowFromTarget(event_target); - aura::client::ScreenPositionClient* client = GetScreenPositionClient(target); - if (client) - client->ConvertPointToScreen(target, point); - else - aura::Window::ConvertPointToTarget(target, target->GetRootWindow(), point); -} - -void EventGeneratorDelegateAura::ConvertPointToTarget( - const ui::EventTarget* event_target, - gfx::Point* point) const { - DCHECK(point); - const Window* target = WindowFromTarget(event_target); - aura::client::ScreenPositionClient* client = GetScreenPositionClient(target); - if (client) - client->ConvertPointFromScreen(target, point); - else - aura::Window::ConvertPointToTarget(target->GetRootWindow(), target, point); -} - -void EventGeneratorDelegateAura::ConvertPointFromHost( - const ui::EventTarget* hosted_target, - gfx::Point* point) const { - const Window* window = WindowFromTarget(hosted_target); - window->GetHost()->ConvertPointFromHost(point); -} - -} // namespace test -} // namespace aura
diff --git a/ui/aura/test/event_generator_delegate_aura.h b/ui/aura/test/event_generator_delegate_aura.h deleted file mode 100644 index b43bf68..0000000 --- a/ui/aura/test/event_generator_delegate_aura.h +++ /dev/null
@@ -1,57 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_TEST_EVENT_GENERATOR_DELEGATE_AURA_H_ -#define UI_AURA_TEST_EVENT_GENERATOR_DELEGATE_AURA_H_ - -#include "ui/events/test/event_generator.h" - -namespace aura { -class Window; -class WindowTreeHost; - -namespace client { -class ScreenPositionClient; -} - -namespace test { - -void InitializeAuraEventGeneratorDelegate(); - -// Implementation of ui::test::EventGeneratorDelegate for Aura. -class EventGeneratorDelegateAura : public ui::test::EventGeneratorDelegate { - public: - EventGeneratorDelegateAura(); - virtual ~EventGeneratorDelegateAura(); - - // Returns the host for given point. - virtual WindowTreeHost* GetHostAt(const gfx::Point& point) const = 0; - - // Returns the screen position client that determines the - // coordinates used in EventGenerator. EventGenerator uses - // root Window's coordinate if this returns NULL. - virtual client::ScreenPositionClient* GetScreenPositionClient( - const aura::Window* window) const = 0; - - // Overridden from ui::test::EventGeneratorDelegate: - virtual ui::EventTarget* GetTargetAt(const gfx::Point& location) override; - virtual ui::EventSource* GetEventSource(ui::EventTarget* target) override; - virtual gfx::Point CenterOfTarget( - const ui::EventTarget* target) const override; - virtual gfx::Point CenterOfWindow(gfx::NativeWindow window) const override; - virtual void ConvertPointFromTarget(const ui::EventTarget* target, - gfx::Point* point) const override; - virtual void ConvertPointToTarget(const ui::EventTarget* target, - gfx::Point* point) const override; - virtual void ConvertPointFromHost(const ui::EventTarget* hosted_target, - gfx::Point* point) const override; - - private: - DISALLOW_COPY_AND_ASSIGN(EventGeneratorDelegateAura); -}; - -} // namespace test -} // namespace aura - -#endif // UI_AURA_TEST_EVENT_GENERATOR_DELEGATE_AURA_H_
diff --git a/ui/aura/test/run_all_unittests.cc b/ui/aura/test/run_all_unittests.cc deleted file mode 100644 index 48ea16e..0000000 --- a/ui/aura/test/run_all_unittests.cc +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/bind.h" -#include "base/test/launcher/unit_test_launcher.h" -#include "base/test/test_suite.h" -#include "ui/gl/gl_surface.h" - -int main(int argc, char** argv) { - base::TestSuite test_suite(argc, argv); - gfx::GLSurface::InitializeOneOffForTests(); - - return base::LaunchUnitTests( - argc, - argv, - base::Bind(&base::TestSuite::Run, base::Unretained(&test_suite))); -}
diff --git a/ui/aura/test/test_cursor_client.cc b/ui/aura/test/test_cursor_client.cc deleted file mode 100644 index ef1eba2..0000000 --- a/ui/aura/test/test_cursor_client.cc +++ /dev/null
@@ -1,102 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/test/test_cursor_client.h" - -#include "ui/aura/client/cursor_client_observer.h" - -namespace aura { -namespace test { - -TestCursorClient::TestCursorClient(aura::Window* root_window) - : visible_(true), - should_hide_cursor_on_key_event_(true), - mouse_events_enabled_(true), - cursor_lock_count_(0), - calls_to_set_cursor_(0), - root_window_(root_window) { - client::SetCursorClient(root_window, this); -} - -TestCursorClient::~TestCursorClient() { - client::SetCursorClient(root_window_, NULL); -} - -void TestCursorClient::SetCursor(gfx::NativeCursor cursor) { - calls_to_set_cursor_++; -} - -gfx::NativeCursor TestCursorClient::GetCursor() const { - return ui::kCursorNull; -} - -void TestCursorClient::ShowCursor() { - visible_ = true; - FOR_EACH_OBSERVER(aura::client::CursorClientObserver, observers_, - OnCursorVisibilityChanged(true)); -} - -void TestCursorClient::HideCursor() { - visible_ = false; - FOR_EACH_OBSERVER(aura::client::CursorClientObserver, observers_, - OnCursorVisibilityChanged(false)); -} - -void TestCursorClient::SetCursorSet(ui::CursorSetType cursor_set) { -} - -ui::CursorSetType TestCursorClient::GetCursorSet() const { - return ui::CURSOR_SET_NORMAL; -} - -bool TestCursorClient::IsCursorVisible() const { - return visible_; -} - -void TestCursorClient::EnableMouseEvents() { - mouse_events_enabled_ = true; -} - -void TestCursorClient::DisableMouseEvents() { - mouse_events_enabled_ = false; -} - -bool TestCursorClient::IsMouseEventsEnabled() const { - return mouse_events_enabled_; -} - -void TestCursorClient::SetDisplay(const gfx::Display& display) { -} - -void TestCursorClient::LockCursor() { - cursor_lock_count_++; -} - -void TestCursorClient::UnlockCursor() { - cursor_lock_count_--; - if (cursor_lock_count_ < 0) - cursor_lock_count_ = 0; -} - -bool TestCursorClient::IsCursorLocked() const { - return cursor_lock_count_ > 0; -} - -void TestCursorClient::AddObserver( - aura::client::CursorClientObserver* observer) { - observers_.AddObserver(observer); -} - -void TestCursorClient::RemoveObserver( - aura::client::CursorClientObserver* observer) { - observers_.RemoveObserver(observer); -} - -bool TestCursorClient::ShouldHideCursorOnKeyEvent( - const ui::KeyEvent& event) const { - return should_hide_cursor_on_key_event_; -} - -} // namespace test -} // namespace aura
diff --git a/ui/aura/test/test_cursor_client.h b/ui/aura/test/test_cursor_client.h deleted file mode 100644 index c3f845e..0000000 --- a/ui/aura/test/test_cursor_client.h +++ /dev/null
@@ -1,71 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_TEST_TEST_CURSOR_CLIENT_H_ -#define UI_AURA_TEST_TEST_CURSOR_CLIENT_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/observer_list.h" -#include "ui/aura/client/cursor_client.h" - -namespace ui { -class KeyEvent; -} - -namespace aura { -namespace test { - -class TestCursorClient : public aura::client::CursorClient { - public: - explicit TestCursorClient(aura::Window* root_window); - virtual ~TestCursorClient(); - - // Used to track the number of times SetCursor() was called. - int calls_to_set_cursor() const { return calls_to_set_cursor_; } - void reset_calls_to_set_cursor() { calls_to_set_cursor_ = 0; } - - // Set whether or not to hide cursor on key events. - void set_should_hide_cursor_on_key_event(bool hide) { - should_hide_cursor_on_key_event_ = hide; - } - - // Overridden from aura::client::CursorClient: - virtual void SetCursor(gfx::NativeCursor cursor) override; - virtual gfx::NativeCursor GetCursor() const override; - virtual void ShowCursor() override; - virtual void HideCursor() override; - virtual void SetCursorSet(ui::CursorSetType cursor_set) override; - virtual ui::CursorSetType GetCursorSet() const override; - virtual bool IsCursorVisible() const override; - virtual void EnableMouseEvents() override; - virtual void DisableMouseEvents() override; - virtual bool IsMouseEventsEnabled() const override; - virtual void SetDisplay(const gfx::Display& display) override; - virtual void LockCursor() override; - virtual void UnlockCursor() override; - virtual bool IsCursorLocked() const override; - virtual void AddObserver( - aura::client::CursorClientObserver* observer) override; - virtual void RemoveObserver( - aura::client::CursorClientObserver* observer) override; - virtual bool ShouldHideCursorOnKeyEvent( - const ui::KeyEvent& event) const override; - - private: - bool visible_; - bool should_hide_cursor_on_key_event_; - bool mouse_events_enabled_; - int cursor_lock_count_; - int calls_to_set_cursor_; - ObserverList<aura::client::CursorClientObserver> observers_; - aura::Window* root_window_; - - DISALLOW_COPY_AND_ASSIGN(TestCursorClient); -}; - -} // namespace test -} // namespace aura - -#endif // UI_AURA_TEST_TEST_CURSOR_CLIENT_H_
diff --git a/ui/aura/test/test_focus_client.cc b/ui/aura/test/test_focus_client.cc deleted file mode 100644 index c7f9f8c..0000000 --- a/ui/aura/test/test_focus_client.cc +++ /dev/null
@@ -1,70 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/test/test_focus_client.h" - -#include "ui/aura/client/focus_change_observer.h" -#include "ui/aura/window.h" - -namespace aura { -namespace test { - -//////////////////////////////////////////////////////////////////////////////// -// TestFocusClient, public: - -TestFocusClient::TestFocusClient() - : focused_window_(NULL), - observer_manager_(this) { -} - -TestFocusClient::~TestFocusClient() { -} - -//////////////////////////////////////////////////////////////////////////////// -// TestFocusClient, client::FocusClient implementation: - -void TestFocusClient::AddObserver(client::FocusChangeObserver* observer) { -} - -void TestFocusClient::RemoveObserver(client::FocusChangeObserver* observer) { -} - -void TestFocusClient::FocusWindow(Window* window) { - if (window && !window->CanFocus()) - return; - if (focused_window_) - observer_manager_.Remove(focused_window_); - aura::Window* old_focused_window = focused_window_; - focused_window_ = window; - if (focused_window_) - observer_manager_.Add(focused_window_); - - client::FocusChangeObserver* observer = - client::GetFocusChangeObserver(old_focused_window); - if (observer) - observer->OnWindowFocused(focused_window_, old_focused_window); - observer = client::GetFocusChangeObserver(focused_window_); - if (observer) - observer->OnWindowFocused(focused_window_, old_focused_window); -} - -void TestFocusClient::ResetFocusWithinActiveWindow(Window* window) { - if (!window->Contains(focused_window_)) - FocusWindow(window); -} - -Window* TestFocusClient::GetFocusedWindow() { - return focused_window_; -} - -//////////////////////////////////////////////////////////////////////////////// -// TestFocusClient, WindowObserver implementation: - -void TestFocusClient::OnWindowDestroying(Window* window) { - DCHECK_EQ(window, focused_window_); - FocusWindow(NULL); -} - -} // namespace test -} // namespace aura
diff --git a/ui/aura/test/test_focus_client.h b/ui/aura/test/test_focus_client.h deleted file mode 100644 index 5f9f718..0000000 --- a/ui/aura/test/test_focus_client.h +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_TEST_TEST_FOCUS_CLIENT_H_ -#define UI_AURA_TEST_TEST_FOCUS_CLIENT_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/scoped_observer.h" -#include "ui/aura/client/focus_client.h" -#include "ui/aura/window_observer.h" - -namespace aura { -namespace test { - -class TestFocusClient : public client::FocusClient, - public WindowObserver { - public: - TestFocusClient(); - virtual ~TestFocusClient(); - - private: - // Overridden from client::FocusClient: - virtual void AddObserver(client::FocusChangeObserver* observer) override; - virtual void RemoveObserver(client::FocusChangeObserver* observer) override; - virtual void FocusWindow(Window* window) override; - virtual void ResetFocusWithinActiveWindow(Window* window) override; - virtual Window* GetFocusedWindow() override; - - // Overridden from WindowObserver: - virtual void OnWindowDestroying(Window* window) override; - - Window* focused_window_; - ScopedObserver<Window, WindowObserver> observer_manager_; - - DISALLOW_COPY_AND_ASSIGN(TestFocusClient); -}; - -} // namespace test -} // namespace aura - -#endif // UI_AURA_TEST_TEST_FOCUS_CLIENT_H_
diff --git a/ui/aura/test/test_screen.cc b/ui/aura/test/test_screen.cc deleted file mode 100644 index 63e44b9..0000000 --- a/ui/aura/test/test_screen.cc +++ /dev/null
@@ -1,179 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/test/test_screen.h" - -#include "base/logging.h" -#include "ui/aura/env.h" -#include "ui/aura/window.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/aura/window_tree_host.h" -#include "ui/gfx/geometry/size_conversions.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/gfx/rect_conversions.h" -#include "ui/gfx/screen.h" - -namespace aura { - -namespace { - -bool IsRotationPortrait(gfx::Display::Rotation rotation) { - return rotation == gfx::Display::ROTATE_90 || - rotation == gfx::Display::ROTATE_270; -} - -} // namespace - -// static -TestScreen* TestScreen::Create(const gfx::Size& size) { - const gfx::Size kDefaultSize(800, 600); - // Use (0,0) because the desktop aura tests are executed in - // native environment where the display's origin is (0,0). - return new TestScreen(gfx::Rect(size.IsEmpty() ? kDefaultSize : size)); -} - -// static -TestScreen* TestScreen::CreateFullscreen() { - return new TestScreen(gfx::Rect(WindowTreeHost::GetNativeScreenSize())); -} - -TestScreen::~TestScreen() { -} - -WindowTreeHost* TestScreen::CreateHostForPrimaryDisplay() { - DCHECK(!host_); - host_ = WindowTreeHost::Create(gfx::Rect(display_.GetSizeInPixel())); - host_->window()->AddObserver(this); - host_->InitHost(); - return host_; -} - -void TestScreen::SetDeviceScaleFactor(float device_scale_factor) { - gfx::Rect bounds_in_pixel(display_.GetSizeInPixel()); - display_.SetScaleAndBounds(device_scale_factor, bounds_in_pixel); - host_->OnHostResized(bounds_in_pixel.size()); -} - -void TestScreen::SetDisplayRotation(gfx::Display::Rotation rotation) { - gfx::Rect bounds_in_pixel(display_.GetSizeInPixel()); - gfx::Rect new_bounds(bounds_in_pixel); - if (IsRotationPortrait(rotation) != IsRotationPortrait(display_.rotation())) { - new_bounds.set_width(bounds_in_pixel.height()); - new_bounds.set_height(bounds_in_pixel.width()); - } - display_.set_rotation(rotation); - display_.SetScaleAndBounds(display_.device_scale_factor(), new_bounds); - host_->SetRootTransform(GetRotationTransform() * GetUIScaleTransform()); -} - -void TestScreen::SetUIScale(float ui_scale) { - ui_scale_ = ui_scale; - gfx::Rect bounds_in_pixel(display_.GetSizeInPixel()); - gfx::Rect new_bounds = gfx::ToNearestRect( - gfx::ScaleRect(bounds_in_pixel, 1.0f / ui_scale)); - display_.SetScaleAndBounds(display_.device_scale_factor(), new_bounds); - host_->SetRootTransform(GetRotationTransform() * GetUIScaleTransform()); -} - -void TestScreen::SetWorkAreaInsets(const gfx::Insets& insets) { - display_.UpdateWorkAreaFromInsets(insets); -} - -gfx::Transform TestScreen::GetRotationTransform() const { - gfx::Transform rotate; - switch (display_.rotation()) { - case gfx::Display::ROTATE_0: - break; - case gfx::Display::ROTATE_90: - rotate.Translate(display_.bounds().height(), 0); - rotate.Rotate(90); - break; - case gfx::Display::ROTATE_270: - rotate.Translate(0, display_.bounds().width()); - rotate.Rotate(270); - break; - case gfx::Display::ROTATE_180: - rotate.Translate(display_.bounds().width(), - display_.bounds().height()); - rotate.Rotate(180); - break; - } - - return rotate; -} - -gfx::Transform TestScreen::GetUIScaleTransform() const { - gfx::Transform ui_scale; - ui_scale.Scale(1.0f / ui_scale_, 1.0f / ui_scale_); - return ui_scale; -} - -bool TestScreen::IsDIPEnabled() { - return true; -} - -void TestScreen::OnWindowBoundsChanged( - Window* window, const gfx::Rect& old_bounds, const gfx::Rect& new_bounds) { - DCHECK_EQ(host_->window(), window); - display_.SetSize(gfx::ToFlooredSize( - gfx::ScaleSize(new_bounds.size(), display_.device_scale_factor()))); -} - -void TestScreen::OnWindowDestroying(Window* window) { - if (host_->window() == window) - host_ = NULL; -} - -gfx::Point TestScreen::GetCursorScreenPoint() { - return Env::GetInstance()->last_mouse_location(); -} - -gfx::NativeWindow TestScreen::GetWindowUnderCursor() { - return GetWindowAtScreenPoint(GetCursorScreenPoint()); -} - -gfx::NativeWindow TestScreen::GetWindowAtScreenPoint(const gfx::Point& point) { - return host_->window()->GetTopWindowContainingPoint(point); -} - -int TestScreen::GetNumDisplays() const { - return 1; -} - -std::vector<gfx::Display> TestScreen::GetAllDisplays() const { - return std::vector<gfx::Display>(1, display_); -} - -gfx::Display TestScreen::GetDisplayNearestWindow( - gfx::NativeWindow window) const { - return display_; -} - -gfx::Display TestScreen::GetDisplayNearestPoint(const gfx::Point& point) const { - return display_; -} - -gfx::Display TestScreen::GetDisplayMatching(const gfx::Rect& match_rect) const { - return display_; -} - -gfx::Display TestScreen::GetPrimaryDisplay() const { - return display_; -} - -void TestScreen::AddObserver(gfx::DisplayObserver* observer) { -} - -void TestScreen::RemoveObserver(gfx::DisplayObserver* observer) { -} - -TestScreen::TestScreen(const gfx::Rect& screen_bounds) - : host_(NULL), - ui_scale_(1.0f) { - static int64 synthesized_display_id = 2000; - display_.set_id(synthesized_display_id++); - display_.SetScaleAndBounds(1.0f, screen_bounds); -} - -} // namespace aura
diff --git a/ui/aura/test/test_screen.h b/ui/aura/test/test_screen.h deleted file mode 100644 index 7b1f98b..0000000 --- a/ui/aura/test/test_screen.h +++ /dev/null
@@ -1,83 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_TEST_TEST_SCREEN_H_ -#define UI_AURA_TEST_TEST_SCREEN_H_ - -#include "base/compiler_specific.h" -#include "ui/aura/window_observer.h" -#include "ui/gfx/display.h" -#include "ui/gfx/screen.h" - -namespace gfx { -class Insets; -class Rect; -class Transform; -} - -namespace aura { -class Window; -class WindowTreeHost; - -// A minimal, testing Aura implementation of gfx::Screen. -class TestScreen : public gfx::Screen, - public WindowObserver { - public: - // Creates a gfx::Screen of the specified size. If no size is specified, then - // creates a 800x600 screen. |size| is in physical pixels. - static TestScreen* Create(const gfx::Size& size); - // Creates a TestScreen that uses fullscreen for the display. - static TestScreen* CreateFullscreen(); - virtual ~TestScreen(); - - WindowTreeHost* CreateHostForPrimaryDisplay(); - - void SetDeviceScaleFactor(float device_scale_fator); - void SetDisplayRotation(gfx::Display::Rotation rotation); - void SetUIScale(float ui_scale); - void SetWorkAreaInsets(const gfx::Insets& insets); - - protected: - gfx::Transform GetRotationTransform() const; - gfx::Transform GetUIScaleTransform() const; - - // WindowObserver overrides: - virtual void OnWindowBoundsChanged(Window* window, - const gfx::Rect& old_bounds, - const gfx::Rect& new_bounds) override; - virtual void OnWindowDestroying(Window* window) override; - - // gfx::Screen overrides: - virtual bool IsDIPEnabled() override; - virtual gfx::Point GetCursorScreenPoint() override; - virtual gfx::NativeWindow GetWindowUnderCursor() override; - virtual gfx::NativeWindow GetWindowAtScreenPoint(const gfx::Point& point) - override; - virtual int GetNumDisplays() const override; - virtual std::vector<gfx::Display> GetAllDisplays() const override; - virtual gfx::Display GetDisplayNearestWindow( - gfx::NativeView view) const override; - virtual gfx::Display GetDisplayNearestPoint( - const gfx::Point& point) const override; - virtual gfx::Display GetDisplayMatching( - const gfx::Rect& match_rect) const override; - virtual gfx::Display GetPrimaryDisplay() const override; - virtual void AddObserver(gfx::DisplayObserver* observer) override; - virtual void RemoveObserver(gfx::DisplayObserver* observer) override; - - private: - explicit TestScreen(const gfx::Rect& screen_bounds); - - aura::WindowTreeHost* host_; - - gfx::Display display_; - - float ui_scale_; - - DISALLOW_COPY_AND_ASSIGN(TestScreen); -}; - -} // namespace aura - -#endif // UI_AURA_TEST_TEST_SCREEN_H_
diff --git a/ui/aura/test/test_window_delegate.cc b/ui/aura/test/test_window_delegate.cc deleted file mode 100644 index 7f0ca1b..0000000 --- a/ui/aura/test/test_window_delegate.cc +++ /dev/null
@@ -1,227 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/test/test_window_delegate.h" - -#include "base/strings/stringprintf.h" -#include "ui/aura/window.h" -#include "ui/base/hit_test.h" -#include "ui/events/event.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/path.h" -#include "ui/gfx/skia_util.h" - -#if defined(USE_AURA) -#include "ui/base/cursor/cursor.h" -#endif - -namespace aura { -namespace test { - -//////////////////////////////////////////////////////////////////////////////// -// TestWindowDelegate - -TestWindowDelegate::TestWindowDelegate() - : window_component_(HTCLIENT), - delete_on_destroyed_(false), - can_focus_(true) { -} - -TestWindowDelegate::~TestWindowDelegate() { -} - -// static -TestWindowDelegate* TestWindowDelegate::CreateSelfDestroyingDelegate() { - TestWindowDelegate* delegate = new TestWindowDelegate; - delegate->delete_on_destroyed_ = true; - return delegate; -} - -gfx::Size TestWindowDelegate::GetMinimumSize() const { - return minimum_size_; -} - -gfx::Size TestWindowDelegate::GetMaximumSize() const { - return maximum_size_; -} - -void TestWindowDelegate::OnBoundsChanged(const gfx::Rect& old_bounds, - const gfx::Rect& new_bounds) { -} - -gfx::NativeCursor TestWindowDelegate::GetCursor(const gfx::Point& point) { - return gfx::kNullCursor; -} - -int TestWindowDelegate::GetNonClientComponent(const gfx::Point& point) const { - return window_component_; -} - -bool TestWindowDelegate::ShouldDescendIntoChildForEventHandling( - Window* child, - const gfx::Point& location) { - return true; -} - -bool TestWindowDelegate::CanFocus() { - return can_focus_; -} - -void TestWindowDelegate::OnCaptureLost() { -} - -void TestWindowDelegate::OnPaint(gfx::Canvas* canvas) { -} - -void TestWindowDelegate::OnDeviceScaleFactorChanged( - float device_scale_factor) { -} - -void TestWindowDelegate::OnWindowDestroying(Window* window) { -} - -void TestWindowDelegate::OnWindowDestroyed(Window* window) { - if (delete_on_destroyed_) - delete this; -} - -void TestWindowDelegate::OnWindowTargetVisibilityChanged(bool visible) { -} - -bool TestWindowDelegate::HasHitTestMask() const { - return false; -} - -void TestWindowDelegate::GetHitTestMask(gfx::Path* mask) const { -} - -//////////////////////////////////////////////////////////////////////////////// -// ColorTestWindowDelegate - -ColorTestWindowDelegate::ColorTestWindowDelegate(SkColor color) - : color_(color), - last_key_code_(ui::VKEY_UNKNOWN) { -} - -ColorTestWindowDelegate::~ColorTestWindowDelegate() { -} - -void ColorTestWindowDelegate::OnKeyEvent(ui::KeyEvent* event) { - last_key_code_ = event->key_code(); - event->SetHandled(); -} - -void ColorTestWindowDelegate::OnWindowDestroyed(Window* window) { - delete this; -} - -void ColorTestWindowDelegate::OnPaint(gfx::Canvas* canvas) { - canvas->DrawColor(color_, SkXfermode::kSrc_Mode); -} - -//////////////////////////////////////////////////////////////////////////////// -// MaskedWindowDelegate - -MaskedWindowDelegate::MaskedWindowDelegate(const gfx::Rect mask_rect) - : mask_rect_(mask_rect) { -} - -bool MaskedWindowDelegate::HasHitTestMask() const { - return true; -} - -void MaskedWindowDelegate::GetHitTestMask(gfx::Path* mask) const { - mask->addRect(RectToSkRect(mask_rect_)); -} - -//////////////////////////////////////////////////////////////////////////////// -// EventCountDelegate - -EventCountDelegate::EventCountDelegate() - : mouse_enter_count_(0), - mouse_move_count_(0), - mouse_leave_count_(0), - mouse_press_count_(0), - mouse_release_count_(0), - key_press_count_(0), - key_release_count_(0), - gesture_count_(0) { -} - -void EventCountDelegate::OnKeyEvent(ui::KeyEvent* event) { - switch (event->type()) { - case ui::ET_KEY_PRESSED: - key_press_count_++; - break; - case ui::ET_KEY_RELEASED: - key_release_count_++; - default: - break; - } -} - -void EventCountDelegate::OnMouseEvent(ui::MouseEvent* event) { - switch (event->type()) { - case ui::ET_MOUSE_MOVED: - mouse_move_count_++; - break; - case ui::ET_MOUSE_ENTERED: - mouse_enter_count_++; - break; - case ui::ET_MOUSE_EXITED: - mouse_leave_count_++; - break; - case ui::ET_MOUSE_PRESSED: - mouse_press_count_++; - break; - case ui::ET_MOUSE_RELEASED: - mouse_release_count_++; - break; - default: - break; - } -} - -void EventCountDelegate::OnGestureEvent(ui::GestureEvent* event) { - gesture_count_++; -} - -std::string EventCountDelegate::GetMouseMotionCountsAndReset() { - std::string result = base::StringPrintf("%d %d %d", - mouse_enter_count_, - mouse_move_count_, - mouse_leave_count_); - mouse_enter_count_ = 0; - mouse_move_count_ = 0; - mouse_leave_count_ = 0; - return result; -} - -std::string EventCountDelegate::GetMouseButtonCountsAndReset() { - std::string result = base::StringPrintf("%d %d", - mouse_press_count_, - mouse_release_count_); - mouse_press_count_ = 0; - mouse_release_count_ = 0; - return result; -} - - -std::string EventCountDelegate::GetKeyCountsAndReset() { - std::string result = base::StringPrintf("%d %d", - key_press_count_, - key_release_count_); - key_press_count_ = 0; - key_release_count_ = 0; - return result; -} - -int EventCountDelegate::GetGestureCountAndReset() { - int gesture_count = gesture_count_; - gesture_count_ = 0; - return gesture_count; -} - -} // namespace test -} // namespace aura
diff --git a/ui/aura/test/test_window_delegate.h b/ui/aura/test/test_window_delegate.h deleted file mode 100644 index 1cb142a..0000000 --- a/ui/aura/test/test_window_delegate.h +++ /dev/null
@@ -1,151 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_TEST_TEST_WINDOW_DELEGATE_H_ -#define UI_AURA_TEST_TEST_WINDOW_DELEGATE_H_ - -#include <string> - -#include "base/compiler_specific.h" -#include "third_party/skia/include/core/SkColor.h" -#include "ui/aura/window_delegate.h" -#include "ui/events/keycodes/keyboard_codes.h" -#include "ui/gfx/rect.h" - -namespace aura { -namespace test { - -// WindowDelegate implementation with all methods stubbed out. -class TestWindowDelegate : public WindowDelegate { - public: - TestWindowDelegate(); - virtual ~TestWindowDelegate(); - - // Returns a TestWindowDelegate that delete itself when - // the associated window is destroyed. - static TestWindowDelegate* CreateSelfDestroyingDelegate(); - - void set_window_component(int window_component) { - window_component_ = window_component; - } - - void set_minimum_size(const gfx::Size& minimum_size) { - minimum_size_ = minimum_size; - } - - void set_maximum_size(const gfx::Size& maximum_size) { - maximum_size_ = maximum_size; - } - - // Sets the return value for CanFocus(). Default is true. - void set_can_focus(bool can_focus) { can_focus_ = can_focus; } - - // Overridden from WindowDelegate: - virtual gfx::Size GetMinimumSize() const override; - virtual gfx::Size GetMaximumSize() const override; - virtual void OnBoundsChanged(const gfx::Rect& old_bounds, - const gfx::Rect& new_bounds) override; - virtual gfx::NativeCursor GetCursor(const gfx::Point& point) override; - virtual int GetNonClientComponent(const gfx::Point& point) const override; - virtual bool ShouldDescendIntoChildForEventHandling( - Window* child, - const gfx::Point& location) override; - virtual bool CanFocus() override; - virtual void OnCaptureLost() override; - virtual void OnPaint(gfx::Canvas* canvas) override; - virtual void OnDeviceScaleFactorChanged(float device_scale_factor) override; - virtual void OnWindowDestroying(Window* window) override; - virtual void OnWindowDestroyed(Window* window) override; - virtual void OnWindowTargetVisibilityChanged(bool visible) override; - virtual bool HasHitTestMask() const override; - virtual void GetHitTestMask(gfx::Path* mask) const override; - - private: - int window_component_; - bool delete_on_destroyed_; - gfx::Size minimum_size_; - gfx::Size maximum_size_; - bool can_focus_; - - DISALLOW_COPY_AND_ASSIGN(TestWindowDelegate); -}; - -// A simple WindowDelegate implementation for these tests. It owns itself -// (deletes itself when the Window it is attached to is destroyed). -class ColorTestWindowDelegate : public TestWindowDelegate { - public: - explicit ColorTestWindowDelegate(SkColor color); - virtual ~ColorTestWindowDelegate(); - - ui::KeyboardCode last_key_code() const { return last_key_code_; } - - // Overridden from TestWindowDelegate: - virtual void OnKeyEvent(ui::KeyEvent* event) override; - virtual void OnWindowDestroyed(Window* window) override; - virtual void OnPaint(gfx::Canvas* canvas) override; - - private: - SkColor color_; - ui::KeyboardCode last_key_code_; - - DISALLOW_COPY_AND_ASSIGN(ColorTestWindowDelegate); -}; - -// A simple WindowDelegate that has a hit-test mask. -class MaskedWindowDelegate : public TestWindowDelegate { - public: - explicit MaskedWindowDelegate(const gfx::Rect mask_rect); - - // Overridden from TestWindowDelegate: - virtual bool HasHitTestMask() const override; - virtual void GetHitTestMask(gfx::Path* mask) const override; - - private: - gfx::Rect mask_rect_; - - DISALLOW_COPY_AND_ASSIGN(MaskedWindowDelegate); -}; - -// Keeps track of mouse/key events. -class EventCountDelegate : public TestWindowDelegate { - public: - EventCountDelegate(); - - // Overridden from TestWindowDelegate: - virtual void OnKeyEvent(ui::KeyEvent* event) override; - virtual void OnMouseEvent(ui::MouseEvent* event) override; - virtual void OnGestureEvent(ui::GestureEvent* event) override; - - // Returns the counts of mouse motion events in the - // form of "<enter> <move> <leave>". - std::string GetMouseMotionCountsAndReset(); - - // Returns the counts of mouse button events in the - // form of "<press> <release>". - std::string GetMouseButtonCountsAndReset(); - - // Returns the counts of key events in the form of - // "<press> <release>". - std::string GetKeyCountsAndReset(); - - // Returns number of gesture events. - int GetGestureCountAndReset(); - - private: - int mouse_enter_count_; - int mouse_move_count_; - int mouse_leave_count_; - int mouse_press_count_; - int mouse_release_count_; - int key_press_count_; - int key_release_count_; - int gesture_count_; - - DISALLOW_COPY_AND_ASSIGN(EventCountDelegate); -}; - -} // namespace test -} // namespace aura - -#endif // UI_AURA_TEST_TEST_WINDOW_DELEGATE_H_
diff --git a/ui/aura/test/test_window_tree_client.cc b/ui/aura/test/test_window_tree_client.cc deleted file mode 100644 index 41faa9d..0000000 --- a/ui/aura/test/test_window_tree_client.cc +++ /dev/null
@@ -1,28 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/test/test_window_tree_client.h" - -#include "ui/aura/window.h" - -namespace aura { -namespace test { - -TestWindowTreeClient::TestWindowTreeClient(Window* root_window) - : root_window_(root_window) { - client::SetWindowTreeClient(root_window_, this); -} - -TestWindowTreeClient::~TestWindowTreeClient() { - client::SetWindowTreeClient(root_window_, NULL); -} - -Window* TestWindowTreeClient::GetDefaultParent(Window* context, - Window* window, - const gfx::Rect& bounds) { - return root_window_; -} - -} // namespace test -} // namespace aura
diff --git a/ui/aura/test/test_window_tree_client.h b/ui/aura/test/test_window_tree_client.h deleted file mode 100644 index 8856a9f..0000000 --- a/ui/aura/test/test_window_tree_client.h +++ /dev/null
@@ -1,34 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_TEST_TEST_WINDOW_TREE_CLIENT_H_ -#define UI_AURA_TEST_TEST_WINDOW_TREE_CLIENT_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "ui/aura/aura_export.h" -#include "ui/aura/client/window_tree_client.h" - -namespace aura { -namespace test { - -class TestWindowTreeClient : public client::WindowTreeClient { - public: - explicit TestWindowTreeClient(Window* root_window); - virtual ~TestWindowTreeClient(); - - // Overridden from client::WindowTreeClient: - virtual Window* GetDefaultParent(Window* context, - Window* window, - const gfx::Rect& bounds) override; - private: - Window* root_window_; - - DISALLOW_COPY_AND_ASSIGN(TestWindowTreeClient); -}; - -} // namespace test -} // namespace aura - -#endif // UI_AURA_TEST_TEST_WINDOW_TREE_CLIENT_H_
diff --git a/ui/aura/test/test_windows.cc b/ui/aura/test/test_windows.cc deleted file mode 100644 index fbb2005..0000000 --- a/ui/aura/test/test_windows.cc +++ /dev/null
@@ -1,89 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/test/test_windows.h" - -#include "base/strings/string_number_conversions.h" -#include "ui/aura/client/aura_constants.h" -#include "ui/aura/window.h" -#include "ui/compositor/layer.h" -#include "ui/gfx/rect.h" - -namespace aura { -namespace test { - -Window* CreateTestWindowWithId(int id, Window* parent) { - return CreateTestWindowWithDelegate(NULL, id, gfx::Rect(), parent); -} - -Window* CreateTestWindowWithBounds(const gfx::Rect& bounds, Window* parent) { - return CreateTestWindowWithDelegate(NULL, 0, bounds, parent); -} - -Window* CreateTestWindow(SkColor color, - int id, - const gfx::Rect& bounds, - Window* parent) { - return CreateTestWindowWithDelegate(new ColorTestWindowDelegate(color), - id, bounds, parent); -} - -Window* CreateTestWindowWithDelegate(WindowDelegate* delegate, - int id, - const gfx::Rect& bounds, - Window* parent) { - return CreateTestWindowWithDelegateAndType( - delegate, ui::wm::WINDOW_TYPE_NORMAL, id, bounds, parent); -} - -Window* CreateTestWindowWithDelegateAndType(WindowDelegate* delegate, - ui::wm::WindowType type, - int id, - const gfx::Rect& bounds, - Window* parent) { - Window* window = new Window(delegate); - window->set_id(id); - window->SetType(type); - window->Init(aura::WINDOW_LAYER_TEXTURED); - window->SetBounds(bounds); - window->Show(); - if (parent) - parent->AddChild(window); - window->SetProperty(aura::client::kCanMaximizeKey, true); - return window; -} - -template <typename T> -bool ObjectIsAbove(T* upper, T* lower) { - DCHECK_EQ(upper->parent(), lower->parent()); - DCHECK_NE(upper, lower); - const std::vector<T*>& children = upper->parent()->children(); - const size_t upper_i = - std::find(children.begin(), children.end(), upper) - children.begin(); - const size_t lower_i = - std::find(children.begin(), children.end(), lower) - children.begin(); - return upper_i > lower_i; -} - -bool WindowIsAbove(Window* upper, Window* lower) { - return ObjectIsAbove<Window>(upper, lower); -} - -bool LayerIsAbove(Window* upper, Window* lower) { - return ObjectIsAbove<ui::Layer>(upper->layer(), lower->layer()); -} - -std::string ChildWindowIDsAsString(aura::Window* parent) { - std::string result; - for (Window::Windows::const_iterator i = parent->children().begin(); - i != parent->children().end(); ++i) { - if (!result.empty()) - result += " "; - result += base::IntToString((*i)->id()); - } - return result; -} - -} // namespace test -} // namespace aura
diff --git a/ui/aura/test/test_windows.h b/ui/aura/test/test_windows.h deleted file mode 100644 index ef6a2f0..0000000 --- a/ui/aura/test/test_windows.h +++ /dev/null
@@ -1,49 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_TEST_TEST_WINDOWS_H_ -#define UI_AURA_TEST_TEST_WINDOWS_H_ - -#include <string> - -#include "base/compiler_specific.h" -#include "third_party/skia/include/core/SkColor.h" -#include "ui/aura/test/aura_test_base.h" -#include "ui/aura/test/test_window_delegate.h" -#include "ui/wm/public/window_types.h" - -namespace aura { -namespace test { - -Window* CreateTestWindowWithId(int id, Window* parent); -Window* CreateTestWindowWithBounds(const gfx::Rect& bounds, Window* parent); -Window* CreateTestWindow(SkColor color, - int id, - const gfx::Rect& bounds, - Window* parent); -Window* CreateTestWindowWithDelegate(WindowDelegate* delegate, - int id, - const gfx::Rect& bounds, - Window* parent); -Window* CreateTestWindowWithDelegateAndType(WindowDelegate* delegate, - ui::wm::WindowType type, - int id, - const gfx::Rect& bounds, - Window* parent); - -// Returns true if |upper| is above |lower| in the window stacking order. -bool WindowIsAbove(Window* upper, Window* lower); - -// Returns true if |upper|'s layer is above |lower|'s layer in the layer -// stacking order. -bool LayerIsAbove(Window* upper, Window* lower); - -// Returns a string containing the id of each of the child windows (bottommost -// first) of |parent|. The format of the string is "id1 id2 id...". -std::string ChildWindowIDsAsString(aura::Window* parent); - -} // namespace test -} // namespace aura - -#endif // UI_AURA_TEST_TEST_WINDOWS_H_
diff --git a/ui/aura/test/ui_controls_factory_aura.h b/ui/aura/test/ui_controls_factory_aura.h deleted file mode 100644 index b675222..0000000 --- a/ui/aura/test/ui_controls_factory_aura.h +++ /dev/null
@@ -1,20 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_TEST_UI_CONTROLS_FACTORY_AURA_H_ -#define UI_AURA_TEST_UI_CONTROLS_FACTORY_AURA_H_ - -#include "ui/base/test/ui_controls_aura.h" - -namespace aura { -class WindowTreeHost; - -namespace test { - -ui_controls::UIControlsAura* CreateUIControlsAura(WindowTreeHost* host); - -} // namespace test -} // namespace aura - -#endif // UI_AURA_TEST_UI_CONTROLS_FACTORY_AURA_H_
diff --git a/ui/aura/test/ui_controls_factory_aurawin.cc b/ui/aura/test/ui_controls_factory_aurawin.cc deleted file mode 100644 index 717aea5..0000000 --- a/ui/aura/test/ui_controls_factory_aurawin.cc +++ /dev/null
@@ -1,92 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/basictypes.h" -#include "base/logging.h" -#include "base/message_loop/message_loop.h" -#include "ui/aura/test/ui_controls_factory_aura.h" -#include "ui/aura/window.h" -#include "ui/aura/window_tree_host.h" -#include "ui/base/test/ui_controls_aura.h" -#include "ui/base/test/ui_controls_internal_win.h" - -namespace aura { -namespace test { - -namespace { - -using ui_controls::DOWN; -using ui_controls::LEFT; -using ui_controls::MIDDLE; -using ui_controls::MouseButton; -using ui_controls::RIGHT; -using ui_controls::UIControlsAura; -using ui_controls::UP; -using namespace ui_controls::internal; - -class UIControlsWin : public UIControlsAura { - public: - UIControlsWin() {} - - // UIControlsAura overrides: - virtual bool SendKeyPress(gfx::NativeWindow native_window, - ui::KeyboardCode key, - bool control, - bool shift, - bool alt, - bool command) { - DCHECK(!command); // No command key on Aura - HWND window = - native_window->GetHost()->GetAcceleratedWidget(); - return SendKeyPressImpl( - window, key, control, shift, alt, base::Closure()); - } - virtual bool SendKeyPressNotifyWhenDone(gfx::NativeWindow native_window, - ui::KeyboardCode key, - bool control, - bool shift, - bool alt, - bool command, - const base::Closure& task) { - DCHECK(!command); // No command key on Aura - HWND window = - native_window->GetHost()->GetAcceleratedWidget(); - return SendKeyPressImpl(window, key, control, shift, alt, task); - } - virtual bool SendMouseMove(long screen_x, long screen_y) { - return SendMouseMoveImpl(screen_x, screen_y, base::Closure()); - } - virtual bool SendMouseMoveNotifyWhenDone(long screen_x, - long screen_y, - const base::Closure& task) { - return SendMouseMoveImpl(screen_x, screen_y, task); - } - virtual bool SendMouseEvents(MouseButton type, int state) { - return SendMouseEventsImpl(type, state, base::Closure()); - } - virtual bool SendMouseEventsNotifyWhenDone(MouseButton type, - int state, - const base::Closure& task) { - return SendMouseEventsImpl(type, state, task); - } - virtual bool SendMouseClick(MouseButton type) { - return SendMouseEvents(type, UP | DOWN); - } - virtual void RunClosureAfterAllPendingUIEvents(const base::Closure& closure) { - // On windows, posting UI events is synchronous so just post the closure. - base::MessageLoopForUI::current()->PostTask(FROM_HERE, closure); - } - - private: - DISALLOW_COPY_AND_ASSIGN(UIControlsWin); -}; - -} // namespace - -UIControlsAura* CreateUIControlsAura(WindowTreeHost* host) { - return new UIControlsWin(); -} - -} // namespace test -} // namespace aura
diff --git a/ui/aura/test/ui_controls_factory_aurax11.cc b/ui/aura/test/ui_controls_factory_aurax11.cc deleted file mode 100644 index 8f6b278..0000000 --- a/ui/aura/test/ui_controls_factory_aurax11.cc +++ /dev/null
@@ -1,234 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <X11/keysym.h> -#include <X11/Xlib.h> - -#include "base/bind.h" -#include "base/logging.h" -#include "ui/aura/client/screen_position_client.h" -#include "ui/aura/env.h" -#include "ui/aura/test/aura_test_utils.h" -#include "ui/aura/test/ui_controls_factory_aura.h" -#include "ui/aura/window.h" -#include "ui/aura/window_tree_host.h" -#include "ui/base/test/ui_controls_aura.h" -#include "ui/base/x/x11_util.h" -#include "ui/compositor/dip_util.h" -#include "ui/events/keycodes/keyboard_code_conversion_x.h" -#include "ui/events/test/platform_event_waiter.h" - -namespace aura { -namespace test { -namespace { - -using ui_controls::DOWN; -using ui_controls::LEFT; -using ui_controls::MIDDLE; -using ui_controls::MouseButton; -using ui_controls::RIGHT; -using ui_controls::UIControlsAura; -using ui_controls::UP; - -// Mask of the buttons currently down. -unsigned button_down_mask = 0; - -// Returns atom that indidates that the XEvent is marker event. -Atom MarkerEventAtom() { - return XInternAtom(gfx::GetXDisplay(), "marker_event", False); -} - -// Returns true when the event is a marker event. -bool Matcher(const base::NativeEvent& event) { - return event->xany.type == ClientMessage && - event->xclient.message_type == MarkerEventAtom(); -} - -class UIControlsX11 : public UIControlsAura { - public: - UIControlsX11(WindowTreeHost* host) : host_(host) { - } - - virtual bool SendKeyPress(gfx::NativeWindow window, - ui::KeyboardCode key, - bool control, - bool shift, - bool alt, - bool command) override { - return SendKeyPressNotifyWhenDone( - window, key, control, shift, alt, command, base::Closure()); - } - virtual bool SendKeyPressNotifyWhenDone( - gfx::NativeWindow window, - ui::KeyboardCode key, - bool control, - bool shift, - bool alt, - bool command, - const base::Closure& closure) override { - XEvent xevent = {0}; - xevent.xkey.type = KeyPress; - if (control) - SetKeycodeAndSendThenMask(&xevent, XK_Control_L, ControlMask); - if (shift) - SetKeycodeAndSendThenMask(&xevent, XK_Shift_L, ShiftMask); - if (alt) - SetKeycodeAndSendThenMask(&xevent, XK_Alt_L, Mod1Mask); - if (command) - SetKeycodeAndSendThenMask(&xevent, XK_Meta_L, Mod4Mask); - xevent.xkey.keycode = - XKeysymToKeycode(gfx::GetXDisplay(), - ui::XKeysymForWindowsKeyCode(key, shift)); - host_->PostNativeEvent(&xevent); - - // Send key release events. - xevent.xkey.type = KeyRelease; - host_->PostNativeEvent(&xevent); - if (alt) - UnmaskAndSetKeycodeThenSend(&xevent, Mod1Mask, XK_Alt_L); - if (shift) - UnmaskAndSetKeycodeThenSend(&xevent, ShiftMask, XK_Shift_L); - if (control) - UnmaskAndSetKeycodeThenSend(&xevent, ControlMask, XK_Control_L); - if (command) - UnmaskAndSetKeycodeThenSend(&xevent, Mod4Mask, XK_Meta_L); - DCHECK(!xevent.xkey.state); - RunClosureAfterAllPendingUIEvents(closure); - return true; - } - - virtual bool SendMouseMove(long screen_x, long screen_y) override { - return SendMouseMoveNotifyWhenDone(screen_x, screen_y, base::Closure()); - } - virtual bool SendMouseMoveNotifyWhenDone( - long screen_x, - long screen_y, - const base::Closure& closure) override { - gfx::Point root_location(screen_x, screen_y); - aura::client::ScreenPositionClient* screen_position_client = - aura::client::GetScreenPositionClient(host_->window()); - if (screen_position_client) { - screen_position_client->ConvertPointFromScreen(host_->window(), - &root_location); - } - gfx::Point root_current_location = - QueryLatestMousePositionRequestInHost(host_); - host_->ConvertPointFromHost(&root_current_location); - - if (root_location != root_current_location && button_down_mask == 0) { - // Move the cursor because EnterNotify/LeaveNotify are generated with the - // current mouse position as a result of XGrabPointer() - host_->window()->MoveCursorTo(root_location); - } else { - XEvent xevent = {0}; - XMotionEvent* xmotion = &xevent.xmotion; - xmotion->type = MotionNotify; - xmotion->x = root_location.x(); - xmotion->y = root_location.y(); - xmotion->state = button_down_mask; - xmotion->same_screen = True; - // WindowTreeHost will take care of other necessary fields. - host_->PostNativeEvent(&xevent); - } - RunClosureAfterAllPendingUIEvents(closure); - return true; - } - virtual bool SendMouseEvents(MouseButton type, int state) override { - return SendMouseEventsNotifyWhenDone(type, state, base::Closure()); - } - virtual bool SendMouseEventsNotifyWhenDone( - MouseButton type, - int state, - const base::Closure& closure) override { - XEvent xevent = {0}; - XButtonEvent* xbutton = &xevent.xbutton; - gfx::Point mouse_loc = aura::Env::GetInstance()->last_mouse_location(); - aura::client::ScreenPositionClient* screen_position_client = - aura::client::GetScreenPositionClient(host_->window()); - if (screen_position_client) { - screen_position_client->ConvertPointFromScreen(host_->window(), - &mouse_loc); - } - xbutton->x = mouse_loc.x(); - xbutton->y = mouse_loc.y(); - xbutton->same_screen = True; - switch (type) { - case LEFT: - xbutton->button = Button1; - xbutton->state = Button1Mask; - break; - case MIDDLE: - xbutton->button = Button2; - xbutton->state = Button2Mask; - break; - case RIGHT: - xbutton->button = Button3; - xbutton->state = Button3Mask; - break; - } - // WindowEventDispatcher will take care of other necessary fields. - if (state & DOWN) { - xevent.xbutton.type = ButtonPress; - host_->PostNativeEvent(&xevent); - button_down_mask |= xbutton->state; - } - if (state & UP) { - xevent.xbutton.type = ButtonRelease; - host_->PostNativeEvent(&xevent); - button_down_mask = (button_down_mask | xbutton->state) ^ xbutton->state; - } - RunClosureAfterAllPendingUIEvents(closure); - return true; - } - virtual bool SendMouseClick(MouseButton type) override { - return SendMouseEvents(type, UP | DOWN); - } - virtual void RunClosureAfterAllPendingUIEvents( - const base::Closure& closure) override { - if (closure.is_null()) - return; - static XEvent* marker_event = NULL; - if (!marker_event) { - marker_event = new XEvent(); - marker_event->xclient.type = ClientMessage; - marker_event->xclient.display = NULL; - marker_event->xclient.window = None; - marker_event->xclient.format = 8; - } - marker_event->xclient.message_type = MarkerEventAtom(); - host_->PostNativeEvent(marker_event); - ui::PlatformEventWaiter::Create(closure, base::Bind(&Matcher)); - } - private: - void SetKeycodeAndSendThenMask(XEvent* xevent, - KeySym keysym, - unsigned int mask) { - xevent->xkey.keycode = - XKeysymToKeycode(gfx::GetXDisplay(), keysym); - host_->PostNativeEvent(xevent); - xevent->xkey.state |= mask; - } - - void UnmaskAndSetKeycodeThenSend(XEvent* xevent, - unsigned int mask, - KeySym keysym) { - xevent->xkey.state ^= mask; - xevent->xkey.keycode = - XKeysymToKeycode(gfx::GetXDisplay(), keysym); - host_->PostNativeEvent(xevent); - } - - WindowTreeHost* host_; - - DISALLOW_COPY_AND_ASSIGN(UIControlsX11); -}; - -} // namespace - -UIControlsAura* CreateUIControlsAura(WindowTreeHost* host) { - return new UIControlsX11(host); -} - -} // namespace test -} // namespace aura
diff --git a/ui/aura/test/ui_controls_factory_ozone.cc b/ui/aura/test/ui_controls_factory_ozone.cc deleted file mode 100644 index 5bd96bb..0000000 --- a/ui/aura/test/ui_controls_factory_ozone.cc +++ /dev/null
@@ -1,230 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/bind.h" -#include "base/logging.h" -#include "ui/aura/client/screen_position_client.h" -#include "ui/aura/env.h" -#include "ui/aura/test/aura_test_utils.h" -#include "ui/aura/test/ui_controls_factory_aura.h" -#include "ui/aura/window_tree_host.h" -#include "ui/base/test/ui_controls_aura.h" - -namespace aura { -namespace test { -namespace { - -class UIControlsOzone : public ui_controls::UIControlsAura { - public: - UIControlsOzone(WindowTreeHost* host) : host_(host) {} - - virtual bool SendKeyPress(gfx::NativeWindow window, - ui::KeyboardCode key, - bool control, - bool shift, - bool alt, - bool command) override { - return SendKeyPressNotifyWhenDone( - window, key, control, shift, alt, command, base::Closure()); - } - virtual bool SendKeyPressNotifyWhenDone( - gfx::NativeWindow window, - ui::KeyboardCode key, - bool control, - bool shift, - bool alt, - bool command, - const base::Closure& closure) override { - int flags = button_down_mask_; - - if (control) { - flags |= ui::EF_CONTROL_DOWN; - PostKeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_CONTROL, flags); - } - - if (shift) { - flags |= ui::EF_SHIFT_DOWN; - PostKeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_SHIFT, flags); - } - - if (alt) { - flags |= ui::EF_ALT_DOWN; - PostKeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_MENU, flags); - } - - if (command) { - flags |= ui::EF_COMMAND_DOWN; - PostKeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_LWIN, flags); - } - - PostKeyEvent(ui::ET_KEY_PRESSED, key, flags); - PostKeyEvent(ui::ET_KEY_RELEASED, key, flags); - - if (alt) { - flags &= ~ui::EF_ALT_DOWN; - PostKeyEvent(ui::ET_KEY_RELEASED, ui::VKEY_MENU, flags); - } - - if (shift) { - flags &= ~ui::EF_SHIFT_DOWN; - PostKeyEvent(ui::ET_KEY_RELEASED, ui::VKEY_SHIFT, flags); - } - - if (control) { - flags &= ~ui::EF_CONTROL_DOWN; - PostKeyEvent(ui::ET_KEY_RELEASED, ui::VKEY_CONTROL, flags); - } - - if (command) { - flags &= ~ui::EF_COMMAND_DOWN; - PostKeyEvent(ui::ET_KEY_RELEASED, ui::VKEY_LWIN, flags); - } - - RunClosureAfterAllPendingUIEvents(closure); - return true; - } - - virtual bool SendMouseMove(long screen_x, long screen_y) override { - return SendMouseMoveNotifyWhenDone(screen_x, screen_y, base::Closure()); - } - virtual bool SendMouseMoveNotifyWhenDone( - long screen_x, - long screen_y, - const base::Closure& closure) override { - gfx::Point root_location(screen_x, screen_y); - aura::client::ScreenPositionClient* screen_position_client = - aura::client::GetScreenPositionClient(host_->window()); - if (screen_position_client) { - screen_position_client->ConvertPointFromScreen(host_->window(), - &root_location); - } - gfx::Point root_current_location = - QueryLatestMousePositionRequestInHost(host_); - host_->ConvertPointFromHost(&root_current_location); - - if (button_down_mask_) - PostMouseEvent(ui::ET_MOUSE_DRAGGED, root_location, 0, 0); - else - PostMouseEvent(ui::ET_MOUSE_MOVED, root_location, 0, 0); - - RunClosureAfterAllPendingUIEvents(closure); - return true; - } - virtual bool SendMouseEvents(ui_controls::MouseButton type, - int state) override { - return SendMouseEventsNotifyWhenDone(type, state, base::Closure()); - } - virtual bool SendMouseEventsNotifyWhenDone( - ui_controls::MouseButton type, - int state, - const base::Closure& closure) override { - gfx::Point loc = aura::Env::GetInstance()->last_mouse_location(); - aura::client::ScreenPositionClient* screen_position_client = - aura::client::GetScreenPositionClient(host_->window()); - if (screen_position_client) { - screen_position_client->ConvertPointFromScreen(host_->window(), &loc); - } - int flag = 0; - - switch (type) { - case ui_controls::LEFT: - flag = ui::EF_LEFT_MOUSE_BUTTON; - break; - case ui_controls::MIDDLE: - flag = ui::EF_MIDDLE_MOUSE_BUTTON; - break; - case ui_controls::RIGHT: - flag = ui::EF_RIGHT_MOUSE_BUTTON; - break; - default: - NOTREACHED(); - break; - } - - if (state & ui_controls::DOWN) { - button_down_mask_ |= flag; - PostMouseEvent(ui::ET_MOUSE_PRESSED, loc, button_down_mask_ | flag, flag); - } - if (state & ui_controls::UP) { - button_down_mask_ &= ~flag; - PostMouseEvent( - ui::ET_MOUSE_RELEASED, loc, button_down_mask_ | flag, flag); - } - - RunClosureAfterAllPendingUIEvents(closure); - return true; - } - virtual bool SendMouseClick(ui_controls::MouseButton type) override { - return SendMouseEvents(type, ui_controls::UP | ui_controls::DOWN); - } - virtual void RunClosureAfterAllPendingUIEvents( - const base::Closure& closure) override { - if (!closure.is_null()) - base::MessageLoop::current()->PostTask(FROM_HERE, closure); - } - - private: - void PostKeyEvent(ui::EventType type, ui::KeyboardCode key_code, int flags) { - base::MessageLoop::current()->PostTask( - FROM_HERE, - base::Bind(&UIControlsOzone::PostKeyEventTask, - base::Unretained(this), - type, - key_code, - flags)); - } - - void PostKeyEventTask(ui::EventType type, - ui::KeyboardCode key_code, - int flags) { - // Do not rewrite injected events. See crbug.com/136465. - flags |= ui::EF_FINAL; - - ui::KeyEvent key_event(type, key_code, flags); - host_->PostNativeEvent(&key_event); - } - - void PostMouseEvent(ui::EventType type, - const gfx::PointF& location, - int flags, - int changed_button_flags) { - base::MessageLoop::current()->PostTask( - FROM_HERE, - base::Bind(&UIControlsOzone::PostMouseEventTask, - base::Unretained(this), - type, - location, - flags, - changed_button_flags)); - } - - void PostMouseEventTask(ui::EventType type, - const gfx::PointF& location, - int flags, - int changed_button_flags) { - ui::MouseEvent mouse_event( - type, location, location, flags, changed_button_flags); - - // This hack is necessary to set the repeat count for clicks. - ui::MouseEvent mouse_event2(&mouse_event); - - host_->PostNativeEvent(&mouse_event2); - } - - WindowTreeHost* host_; - - // Mask of the mouse buttons currently down. - unsigned button_down_mask_ = 0; - - DISALLOW_COPY_AND_ASSIGN(UIControlsOzone); -}; - -} // namespace - -ui_controls::UIControlsAura* CreateUIControlsAura(WindowTreeHost* host) { - return new UIControlsOzone(host); -} - -} // namespace test -} // namespace aura
diff --git a/ui/aura/test/window_event_dispatcher_test_api.cc b/ui/aura/test/window_event_dispatcher_test_api.cc deleted file mode 100644 index b2a4098..0000000 --- a/ui/aura/test/window_event_dispatcher_test_api.cc +++ /dev/null
@@ -1,22 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/test/window_event_dispatcher_test_api.h" - -#include "ui/aura/window_event_dispatcher.h" - -namespace aura { -namespace test { - -WindowEventDispatcherTestApi::WindowEventDispatcherTestApi( - WindowEventDispatcher* dispatcher) : dispatcher_(dispatcher) { -} - -bool WindowEventDispatcherTestApi::HoldingPointerMoves() const { - return dispatcher_->move_hold_count_ > 0; -} - -} // namespace test -} // namespace aura -
diff --git a/ui/aura/test/window_event_dispatcher_test_api.h b/ui/aura/test/window_event_dispatcher_test_api.h deleted file mode 100644 index a38cabf..0000000 --- a/ui/aura/test/window_event_dispatcher_test_api.h +++ /dev/null
@@ -1,31 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_TEST_WINDOW_EVENT_DISPATCHER_TEST_API_H_ -#define UI_AURA_TEST_WINDOW_EVENT_DISPATCHER_TEST_API_H_ - -#include "base/basictypes.h" - -namespace aura { - -class WindowEventDispatcher; - -namespace test { - -class WindowEventDispatcherTestApi { - public: - explicit WindowEventDispatcherTestApi(WindowEventDispatcher* dispatcher); - - bool HoldingPointerMoves() const; - - private: - WindowEventDispatcher* dispatcher_; - - DISALLOW_COPY_AND_ASSIGN(WindowEventDispatcherTestApi); -}; - -} // namespace test -} // namespace aura - -#endif // UI_AURA_TEST_WINDOW_EVENT_DISPATCHER_TEST_API_H_
diff --git a/ui/aura/test/window_test_api.cc b/ui/aura/test/window_test_api.cc deleted file mode 100644 index 0ea3e18..0000000 --- a/ui/aura/test/window_test_api.cc +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/test/window_test_api.h" - -#include "ui/aura/window.h" - -namespace aura { -namespace test { - -WindowTestApi::WindowTestApi(Window* window) : window_(window) { -} - -bool WindowTestApi::OwnsLayer() const { - return window_->OwnsLayer(); -} - -bool WindowTestApi::ContainsMouse() const { - return window_->ContainsMouse(); -} - -} // namespace test -} // namespace aura
diff --git a/ui/aura/test/window_test_api.h b/ui/aura/test/window_test_api.h deleted file mode 100644 index 16a38cc..0000000 --- a/ui/aura/test/window_test_api.h +++ /dev/null
@@ -1,33 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_TEST_WINDOW_TEST_API_H_ -#define UI_AURA_TEST_WINDOW_TEST_API_H_ - -#include "base/basictypes.h" - -namespace aura { - -class Window; - -namespace test { - -class WindowTestApi { - public: - explicit WindowTestApi(Window* window); - - bool OwnsLayer() const; - - bool ContainsMouse() const; - - private: - Window* window_; - - DISALLOW_COPY_AND_ASSIGN(WindowTestApi); -}; - -} // namespace test -} // namespace aura - -#endif // UI_AURA_TEST_WINDOW_TEST_API_H_
diff --git a/ui/aura/window.cc b/ui/aura/window.cc deleted file mode 100644 index 33cf5b0..0000000 --- a/ui/aura/window.cc +++ /dev/null
@@ -1,1470 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/window.h" - -#include <algorithm> - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/callback.h" -#include "base/logging.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/string_util.h" -#include "base/strings/stringprintf.h" -#include "ui/aura/client/capture_client.h" -#include "ui/aura/client/cursor_client.h" -#include "ui/aura/client/event_client.h" -#include "ui/aura/client/focus_client.h" -#include "ui/aura/client/screen_position_client.h" -#include "ui/aura/client/visibility_client.h" -#include "ui/aura/client/window_stacking_client.h" -#include "ui/aura/env.h" -#include "ui/aura/layout_manager.h" -#include "ui/aura/window_delegate.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/aura/window_observer.h" -#include "ui/aura/window_tracker.h" -#include "ui/aura/window_tree_host.h" -#include "ui/compositor/compositor.h" -#include "ui/compositor/layer.h" -#include "ui/events/event_target_iterator.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/path.h" -#include "ui/gfx/scoped_canvas.h" -#include "ui/gfx/screen.h" - -namespace aura { - -namespace { - -ui::LayerType WindowLayerTypeToUILayerType(WindowLayerType window_layer_type) { - switch (window_layer_type) { - case WINDOW_LAYER_NONE: - break; - case WINDOW_LAYER_NOT_DRAWN: - return ui::LAYER_NOT_DRAWN; - case WINDOW_LAYER_TEXTURED: - return ui::LAYER_TEXTURED; - case WINDOW_LAYER_SOLID_COLOR: - return ui::LAYER_SOLID_COLOR; - } - NOTREACHED(); - return ui::LAYER_NOT_DRAWN; -} - -// Used when searching for a Window to stack relative to. -template <class T> -T IteratorForDirectionBegin(aura::Window* window); - -template <> -Window::Windows::const_iterator IteratorForDirectionBegin( - aura::Window* window) { - return window->children().begin(); -} - -template <> -Window::Windows::const_reverse_iterator IteratorForDirectionBegin( - aura::Window* window) { - return window->children().rbegin(); -} - -template <class T> -T IteratorForDirectionEnd(aura::Window* window); - -template <> -Window::Windows::const_iterator IteratorForDirectionEnd(aura::Window* window) { - return window->children().end(); -} - -template <> -Window::Windows::const_reverse_iterator IteratorForDirectionEnd( - aura::Window* window) { - return window->children().rend(); -} - -// Depth first search for the first Window with a layer to stack relative -// to. Starts at target. Does not descend into |ignore|. -template <class T> -ui::Layer* FindStackingTargetLayerDown(aura::Window* target, - aura::Window* ignore) { - if (target == ignore) - return NULL; - - if (target->layer()) - return target->layer(); - - for (T i = IteratorForDirectionBegin<T>(target); - i != IteratorForDirectionEnd<T>(target); ++i) { - ui::Layer* layer = FindStackingTargetLayerDown<T>(*i, ignore); - if (layer) - return layer; - } - return NULL; -} - -// Depth first search through the siblings of |target||. This does not search -// all the siblings, only those before/after |target| (depening upon the -// template type) and ignoring |ignore|. Returns the Layer of the first Window -// encountered with a Layer. -template <class T> -ui::Layer* FindStackingLayerInSiblings(aura::Window* target, - aura::Window* ignore) { - aura::Window* parent = target->parent(); - for (T i = std::find(IteratorForDirectionBegin<T>(parent), - IteratorForDirectionEnd<T>(parent), target); - i != IteratorForDirectionEnd<T>(parent); ++i) { - ui::Layer* layer = FindStackingTargetLayerDown<T>(*i, ignore); - if (layer) - return layer; - } - return NULL; -} - -// Returns the first Window that has a Layer. This does a depth first search -// through the descendants of |target| first, then ascends up doing a depth -// first search through siblings of all ancestors until a Layer is found or an -// ancestor with a layer is found. This is intended to locate a layer to stack -// other layers relative to. -template <class T> -ui::Layer* FindStackingTargetLayer(aura::Window* target, aura::Window* ignore) { - ui::Layer* result = FindStackingTargetLayerDown<T>(target, ignore); - if (result) - return result; - while (target->parent()) { - ui::Layer* result = FindStackingLayerInSiblings<T>(target, ignore); - if (result) - return result; - target = target->parent(); - if (target->layer()) - return NULL; - } - return NULL; -} - -// Does a depth first search for all descendants of |child| that have layers. -// This stops at any descendants that have layers (and adds them to |layers|). -void GetLayersToStack(aura::Window* child, std::vector<ui::Layer*>* layers) { - if (child->layer()) { - layers->push_back(child->layer()); - return; - } - for (size_t i = 0; i < child->children().size(); ++i) - GetLayersToStack(child->children()[i], layers); -} - -} // namespace - -class ScopedCursorHider { - public: - explicit ScopedCursorHider(Window* window) - : window_(window), - hid_cursor_(false) { - if (!window_->IsRootWindow()) - return; - const bool cursor_is_in_bounds = window_->GetBoundsInScreen().Contains( - Env::GetInstance()->last_mouse_location()); - client::CursorClient* cursor_client = client::GetCursorClient(window_); - if (cursor_is_in_bounds && cursor_client && - cursor_client->IsCursorVisible()) { - cursor_client->HideCursor(); - hid_cursor_ = true; - } - } - ~ScopedCursorHider() { - if (!window_->IsRootWindow()) - return; - - // Update the device scale factor of the cursor client only when the last - // mouse location is on this root window. - if (hid_cursor_) { - client::CursorClient* cursor_client = client::GetCursorClient(window_); - if (cursor_client) { - const gfx::Display& display = - gfx::Screen::GetScreenFor(window_)->GetDisplayNearestWindow( - window_); - cursor_client->SetDisplay(display); - cursor_client->ShowCursor(); - } - } - } - - private: - Window* window_; - bool hid_cursor_; - - DISALLOW_COPY_AND_ASSIGN(ScopedCursorHider); -}; - -Window::Window(WindowDelegate* delegate) - : host_(NULL), - type_(ui::wm::WINDOW_TYPE_UNKNOWN), - owned_by_parent_(true), - delegate_(delegate), - parent_(NULL), - visible_(false), - id_(-1), - transparent_(false), - user_data_(NULL), - ignore_events_(false), - // Don't notify newly added observers during notification. This causes - // problems for code that adds an observer as part of an observer - // notification (such as the workspace code). - observers_(ObserverList<WindowObserver>::NOTIFY_EXISTING_ONLY) { - set_target_handler(delegate_); -} - -Window::~Window() { - // |layer()| can be NULL during tests, or if this Window is layerless. - if (layer()) { - if (layer()->owner() == this) - layer()->CompleteAllAnimations(); - layer()->SuppressPaint(); - } - - // Let the delegate know we're in the processing of destroying. - if (delegate_) - delegate_->OnWindowDestroying(this); - FOR_EACH_OBSERVER(WindowObserver, observers_, OnWindowDestroying(this)); - - // TODO(beng): See comment in window_event_dispatcher.h. This shouldn't be - // necessary but unfortunately is right now due to ordering - // peculiarities. WED must be notified _after_ other observers - // are notified of pending teardown but before the hierarchy - // is actually torn down. - WindowTreeHost* host = GetHost(); - if (host) - host->dispatcher()->OnPostNotifiedWindowDestroying(this); - - // The window should have already had its state cleaned up in - // WindowEventDispatcher::OnWindowHidden(), but there have been some crashes - // involving windows being destroyed without being hidden first. See - // crbug.com/342040. This should help us debug the issue. TODO(tdresser): - // remove this once we determine why we have windows that are destroyed - // without being hidden. - bool window_incorrectly_cleaned_up = CleanupGestureState(); - CHECK(!window_incorrectly_cleaned_up); - - // Then destroy the children. - RemoveOrDestroyChildren(); - - // The window needs to be removed from the parent before calling the - // WindowDestroyed callbacks of delegate and the observers. - if (parent_) - parent_->RemoveChild(this); - - if (delegate_) - delegate_->OnWindowDestroyed(this); - ObserverListBase<WindowObserver>::Iterator iter(observers_); - for (WindowObserver* observer = iter.GetNext(); observer; - observer = iter.GetNext()) { - RemoveObserver(observer); - observer->OnWindowDestroyed(this); - } - - // Clear properties. - for (std::map<const void*, Value>::const_iterator iter = prop_map_.begin(); - iter != prop_map_.end(); - ++iter) { - if (iter->second.deallocator) - (*iter->second.deallocator)(iter->second.value); - } - prop_map_.clear(); - - // If we have layer it will either be destroyed by |layer_owner_|'s dtor, or - // by whoever acquired it. We don't have a layer if Init() wasn't invoked or - // we are layerless. - if (layer()) - layer()->set_delegate(NULL); - DestroyLayer(); -} - -void Window::Init(WindowLayerType window_layer_type) { - if (window_layer_type != WINDOW_LAYER_NONE) { - SetLayer(new ui::Layer(WindowLayerTypeToUILayerType(window_layer_type))); - layer()->SetVisible(false); - layer()->set_delegate(this); - UpdateLayerName(); - layer()->SetFillsBoundsOpaquely(!transparent_); - } - - Env::GetInstance()->NotifyWindowInitialized(this); -} - -void Window::SetType(ui::wm::WindowType type) { - // Cannot change type after the window is initialized. - DCHECK(!layer()); - type_ = type; -} - -void Window::SetName(const std::string& name) { - name_ = name; - - if (layer()) - UpdateLayerName(); -} - -void Window::SetTitle(const base::string16& title) { - title_ = title; - FOR_EACH_OBSERVER(WindowObserver, - observers_, - OnWindowTitleChanged(this)); -} - -void Window::SetTransparent(bool transparent) { - transparent_ = transparent; - if (layer()) - layer()->SetFillsBoundsOpaquely(!transparent_); -} - -void Window::SetFillsBoundsCompletely(bool fills_bounds) { - if (layer()) - layer()->SetFillsBoundsCompletely(fills_bounds); -} - -Window* Window::GetRootWindow() { - return const_cast<Window*>( - static_cast<const Window*>(this)->GetRootWindow()); -} - -const Window* Window::GetRootWindow() const { - return IsRootWindow() ? this : parent_ ? parent_->GetRootWindow() : NULL; -} - -WindowTreeHost* Window::GetHost() { - return const_cast<WindowTreeHost*>(const_cast<const Window*>(this)-> - GetHost()); -} - -const WindowTreeHost* Window::GetHost() const { - const Window* root_window = GetRootWindow(); - return root_window ? root_window->host_ : NULL; -} - -void Window::Show() { - if (layer()) { - DCHECK_EQ(visible_, layer()->GetTargetVisibility()); - // It is not allowed that a window is visible but the layers alpha is fully - // transparent since the window would still be considered to be active but - // could not be seen. - DCHECK(!(visible_ && layer()->GetTargetOpacity() == 0.0f)); - } - SetVisible(true); -} - -void Window::Hide() { - // RootWindow::OnVisibilityChanged will call ReleaseCapture. - SetVisible(false); -} - -bool Window::IsVisible() const { - // Layer visibility can be inconsistent with window visibility, for example - // when a Window is hidden, we want this function to return false immediately - // after, even though the client may decide to animate the hide effect (and - // so the layer will be visible for some time after Hide() is called). - for (const Window* window = this; window; window = window->parent()) { - if (!window->visible_) - return false; - if (window->layer()) - return window->layer()->IsDrawn(); - } - return false; -} - -gfx::Rect Window::GetBoundsInRootWindow() const { - // TODO(beng): There may be a better way to handle this, and the existing code - // is likely wrong anyway in a multi-display world, but this will - // do for now. - if (!GetRootWindow()) - return bounds(); - gfx::Point origin = bounds().origin(); - ConvertPointToTarget(parent_, GetRootWindow(), &origin); - return gfx::Rect(origin, bounds().size()); -} - -gfx::Rect Window::GetBoundsInScreen() const { - gfx::Rect bounds(GetBoundsInRootWindow()); - const Window* root = GetRootWindow(); - if (root) { - aura::client::ScreenPositionClient* screen_position_client = - aura::client::GetScreenPositionClient(root); - if (screen_position_client) { - gfx::Point origin = bounds.origin(); - screen_position_client->ConvertPointToScreen(root, &origin); - bounds.set_origin(origin); - } - } - return bounds; -} - -void Window::SetTransform(const gfx::Transform& transform) { - if (!layer()) { - // Transforms aren't supported on layerless windows. - NOTREACHED(); - return; - } - FOR_EACH_OBSERVER(WindowObserver, observers_, - OnWindowTransforming(this)); - layer()->SetTransform(transform); - FOR_EACH_OBSERVER(WindowObserver, observers_, - OnWindowTransformed(this)); - NotifyAncestorWindowTransformed(this); -} - -void Window::SetLayoutManager(LayoutManager* layout_manager) { - if (layout_manager == layout_manager_) - return; - layout_manager_.reset(layout_manager); - if (!layout_manager) - return; - // If we're changing to a new layout manager, ensure it is aware of all the - // existing child windows. - for (Windows::const_iterator it = children_.begin(); - it != children_.end(); - ++it) - layout_manager_->OnWindowAddedToLayout(*it); -} - -scoped_ptr<ui::EventTargeter> -Window::SetEventTargeter(scoped_ptr<ui::EventTargeter> targeter) { - scoped_ptr<ui::EventTargeter> old_targeter = targeter_.Pass(); - targeter_ = targeter.Pass(); - return old_targeter.Pass(); -} - -void Window::SetBounds(const gfx::Rect& new_bounds) { - if (parent_ && parent_->layout_manager()) - parent_->layout_manager()->SetChildBounds(this, new_bounds); - else { - // Ensure we don't go smaller than our minimum bounds. - gfx::Rect final_bounds(new_bounds); - if (delegate_) { - const gfx::Size& min_size = delegate_->GetMinimumSize(); - final_bounds.set_width(std::max(min_size.width(), final_bounds.width())); - final_bounds.set_height(std::max(min_size.height(), - final_bounds.height())); - } - SetBoundsInternal(final_bounds); - } -} - -void Window::SetBoundsInScreen(const gfx::Rect& new_bounds_in_screen, - const gfx::Display& dst_display) { - Window* root = GetRootWindow(); - if (root) { - gfx::Point origin = new_bounds_in_screen.origin(); - aura::client::ScreenPositionClient* screen_position_client = - aura::client::GetScreenPositionClient(root); - screen_position_client->SetBounds(this, new_bounds_in_screen, dst_display); - return; - } - SetBounds(new_bounds_in_screen); -} - -gfx::Rect Window::GetTargetBounds() const { - if (!layer()) - return bounds(); - - if (!parent_ || parent_->layer()) - return layer()->GetTargetBounds(); - - // We have a layer but our parent (who is valid) doesn't. This means the - // coordinates of the layer are relative to the first ancestor with a layer; - // convert to be relative to parent. - gfx::Vector2d offset; - const aura::Window* ancestor_with_layer = - parent_->GetAncestorWithLayer(&offset); - if (!ancestor_with_layer) - return layer()->GetTargetBounds(); - - gfx::Rect layer_target_bounds = layer()->GetTargetBounds(); - layer_target_bounds -= offset; - return layer_target_bounds; -} - -void Window::SchedulePaintInRect(const gfx::Rect& rect) { - if (!layer() && parent_) { - // Notification of paint scheduled happens for the window with a layer. - gfx::Rect parent_rect(bounds().size()); - parent_rect.Intersect(rect); - if (!parent_rect.IsEmpty()) { - parent_rect.Offset(bounds().origin().OffsetFromOrigin()); - parent_->SchedulePaintInRect(parent_rect); - } - } else if (layer()) { - layer()->SchedulePaint(rect); - } -} - -void Window::StackChildAtTop(Window* child) { - if (children_.size() <= 1 || child == children_.back()) - return; // In the front already. - StackChildAbove(child, children_.back()); -} - -void Window::StackChildAbove(Window* child, Window* target) { - StackChildRelativeTo(child, target, STACK_ABOVE); -} - -void Window::StackChildAtBottom(Window* child) { - if (children_.size() <= 1 || child == children_.front()) - return; // At the bottom already. - StackChildBelow(child, children_.front()); -} - -void Window::StackChildBelow(Window* child, Window* target) { - StackChildRelativeTo(child, target, STACK_BELOW); -} - -void Window::AddChild(Window* child) { - WindowObserver::HierarchyChangeParams params; - params.target = child; - params.new_parent = this; - params.old_parent = child->parent(); - params.phase = WindowObserver::HierarchyChangeParams::HIERARCHY_CHANGING; - NotifyWindowHierarchyChange(params); - - Window* old_root = child->GetRootWindow(); - - DCHECK(std::find(children_.begin(), children_.end(), child) == - children_.end()); - if (child->parent()) - child->parent()->RemoveChildImpl(child, this); - - gfx::Vector2d offset; - aura::Window* ancestor_with_layer = GetAncestorWithLayer(&offset); - - child->parent_ = this; - - if (ancestor_with_layer) { - offset += child->bounds().OffsetFromOrigin(); - child->ReparentLayers(ancestor_with_layer->layer(), offset); - } - - children_.push_back(child); - if (layout_manager_) - layout_manager_->OnWindowAddedToLayout(child); - FOR_EACH_OBSERVER(WindowObserver, observers_, OnWindowAdded(child)); - child->OnParentChanged(); - - Window* root_window = GetRootWindow(); - if (root_window && old_root != root_window) { - root_window->GetHost()->dispatcher()->OnWindowAddedToRootWindow(child); - child->NotifyAddedToRootWindow(); - } - - params.phase = WindowObserver::HierarchyChangeParams::HIERARCHY_CHANGED; - NotifyWindowHierarchyChange(params); -} - -void Window::RemoveChild(Window* child) { - WindowObserver::HierarchyChangeParams params; - params.target = child; - params.new_parent = NULL; - params.old_parent = this; - params.phase = WindowObserver::HierarchyChangeParams::HIERARCHY_CHANGING; - NotifyWindowHierarchyChange(params); - - RemoveChildImpl(child, NULL); - - params.phase = WindowObserver::HierarchyChangeParams::HIERARCHY_CHANGED; - NotifyWindowHierarchyChange(params); -} - -bool Window::Contains(const Window* other) const { - for (const Window* parent = other; parent; parent = parent->parent_) { - if (parent == this) - return true; - } - return false; -} - -Window* Window::GetChildById(int id) { - return const_cast<Window*>(const_cast<const Window*>(this)->GetChildById(id)); -} - -const Window* Window::GetChildById(int id) const { - Windows::const_iterator i; - for (i = children_.begin(); i != children_.end(); ++i) { - if ((*i)->id() == id) - return *i; - const Window* result = (*i)->GetChildById(id); - if (result) - return result; - } - return NULL; -} - -// static -void Window::ConvertPointToTarget(const Window* source, - const Window* target, - gfx::Point* point) { - if (!source) - return; - if (source->GetRootWindow() != target->GetRootWindow()) { - client::ScreenPositionClient* source_client = - client::GetScreenPositionClient(source->GetRootWindow()); - // |source_client| can be NULL in tests. - if (source_client) - source_client->ConvertPointToScreen(source, point); - - client::ScreenPositionClient* target_client = - client::GetScreenPositionClient(target->GetRootWindow()); - // |target_client| can be NULL in tests. - if (target_client) - target_client->ConvertPointFromScreen(target, point); - } else if ((source != target) && (!source->layer() || !target->layer())) { - if (!source->layer()) { - gfx::Vector2d offset_to_layer; - source = source->GetAncestorWithLayer(&offset_to_layer); - *point += offset_to_layer; - } - if (!target->layer()) { - gfx::Vector2d offset_to_layer; - target = target->GetAncestorWithLayer(&offset_to_layer); - *point -= offset_to_layer; - } - ui::Layer::ConvertPointToLayer(source->layer(), target->layer(), point); - } else { - ui::Layer::ConvertPointToLayer(source->layer(), target->layer(), point); - } -} - -// static -void Window::ConvertRectToTarget(const Window* source, - const Window* target, - gfx::Rect* rect) { - DCHECK(rect); - gfx::Point origin = rect->origin(); - ConvertPointToTarget(source, target, &origin); - rect->set_origin(origin); -} - -void Window::MoveCursorTo(const gfx::Point& point_in_window) { - Window* root_window = GetRootWindow(); - DCHECK(root_window); - gfx::Point point_in_root(point_in_window); - ConvertPointToTarget(this, root_window, &point_in_root); - root_window->GetHost()->MoveCursorTo(point_in_root); -} - -gfx::NativeCursor Window::GetCursor(const gfx::Point& point) const { - return delegate_ ? delegate_->GetCursor(point) : gfx::kNullCursor; -} - -void Window::AddObserver(WindowObserver* observer) { - observer->OnObservingWindow(this); - observers_.AddObserver(observer); -} - -void Window::RemoveObserver(WindowObserver* observer) { - observer->OnUnobservingWindow(this); - observers_.RemoveObserver(observer); -} - -bool Window::HasObserver(WindowObserver* observer) { - return observers_.HasObserver(observer); -} - -bool Window::ContainsPointInRoot(const gfx::Point& point_in_root) const { - const Window* root_window = GetRootWindow(); - if (!root_window) - return false; - gfx::Point local_point(point_in_root); - ConvertPointToTarget(root_window, this, &local_point); - return gfx::Rect(GetTargetBounds().size()).Contains(local_point); -} - -bool Window::ContainsPoint(const gfx::Point& local_point) const { - return gfx::Rect(bounds().size()).Contains(local_point); -} - -Window* Window::GetEventHandlerForPoint(const gfx::Point& local_point) { - return GetWindowForPoint(local_point, true, true); -} - -Window* Window::GetTopWindowContainingPoint(const gfx::Point& local_point) { - return GetWindowForPoint(local_point, false, false); -} - -Window* Window::GetToplevelWindow() { - Window* topmost_window_with_delegate = NULL; - for (aura::Window* window = this; window != NULL; window = window->parent()) { - if (window->delegate()) - topmost_window_with_delegate = window; - } - return topmost_window_with_delegate; -} - -void Window::Focus() { - client::FocusClient* client = client::GetFocusClient(this); - DCHECK(client); - client->FocusWindow(this); -} - -void Window::Blur() { - client::FocusClient* client = client::GetFocusClient(this); - DCHECK(client); - client->FocusWindow(NULL); -} - -bool Window::HasFocus() const { - client::FocusClient* client = client::GetFocusClient(this); - return client && client->GetFocusedWindow() == this; -} - -bool Window::CanFocus() const { - if (IsRootWindow()) - return IsVisible(); - - // NOTE: as part of focusing the window the ActivationClient may make the - // window visible (by way of making a hidden ancestor visible). For this - // reason we can't check visibility here and assume the client is doing it. - if (!parent_ || (delegate_ && !delegate_->CanFocus())) - return false; - - // The client may forbid certain windows from receiving focus at a given point - // in time. - client::EventClient* client = client::GetEventClient(GetRootWindow()); - if (client && !client->CanProcessEventsWithinSubtree(this)) - return false; - - return parent_->CanFocus(); -} - -bool Window::CanReceiveEvents() const { - if (IsRootWindow()) - return IsVisible(); - - // The client may forbid certain windows from receiving events at a given - // point in time. - client::EventClient* client = client::GetEventClient(GetRootWindow()); - if (client && !client->CanProcessEventsWithinSubtree(this)) - return false; - - return parent_ && IsVisible() && parent_->CanReceiveEvents(); -} - -void Window::SetCapture() { - if (!IsVisible()) - return; - - Window* root_window = GetRootWindow(); - if (!root_window) - return; - client::CaptureClient* capture_client = client::GetCaptureClient(root_window); - if (!capture_client) - return; - client::GetCaptureClient(root_window)->SetCapture(this); -} - -void Window::ReleaseCapture() { - Window* root_window = GetRootWindow(); - if (!root_window) - return; - client::CaptureClient* capture_client = client::GetCaptureClient(root_window); - if (!capture_client) - return; - client::GetCaptureClient(root_window)->ReleaseCapture(this); -} - -bool Window::HasCapture() { - Window* root_window = GetRootWindow(); - if (!root_window) - return false; - client::CaptureClient* capture_client = client::GetCaptureClient(root_window); - return capture_client && capture_client->GetCaptureWindow() == this; -} - -void Window::SuppressPaint() { - if (layer()) - layer()->SuppressPaint(); -} - -// {Set,Get,Clear}Property are implemented in window_property.h. - -void Window::SetNativeWindowProperty(const char* key, void* value) { - SetPropertyInternal( - key, key, NULL, reinterpret_cast<int64>(value), 0); -} - -void* Window::GetNativeWindowProperty(const char* key) const { - return reinterpret_cast<void*>(GetPropertyInternal(key, 0)); -} - -void Window::OnDeviceScaleFactorChanged(float device_scale_factor) { - ScopedCursorHider hider(this); - if (delegate_) - delegate_->OnDeviceScaleFactorChanged(device_scale_factor); -} - -#if !defined(NDEBUG) -std::string Window::GetDebugInfo() const { - return base::StringPrintf( - "%s<%d> bounds(%d, %d, %d, %d) %s %s opacity=%.1f", - name().empty() ? "Unknown" : name().c_str(), id(), - bounds().x(), bounds().y(), bounds().width(), bounds().height(), - visible_ ? "WindowVisible" : "WindowHidden", - layer() ? - (layer()->GetTargetVisibility() ? "LayerVisible" : "LayerHidden") : - "NoLayer", - layer() ? layer()->opacity() : 1.0f); -} - -void Window::PrintWindowHierarchy(int depth) const { - VLOG(0) << base::StringPrintf( - "%*s%s", depth * 2, "", GetDebugInfo().c_str()); - for (Windows::const_iterator it = children_.begin(); - it != children_.end(); ++it) { - Window* child = *it; - child->PrintWindowHierarchy(depth + 1); - } -} -#endif - -void Window::RemoveOrDestroyChildren() { - while (!children_.empty()) { - Window* child = children_[0]; - if (child->owned_by_parent_) { - delete child; - // Deleting the child so remove it from out children_ list. - DCHECK(std::find(children_.begin(), children_.end(), child) == - children_.end()); - } else { - // Even if we can't delete the child, we still need to remove it from the - // parent so that relevant bookkeeping (parent_ back-pointers etc) are - // updated. - RemoveChild(child); - } - } -} - -/////////////////////////////////////////////////////////////////////////////// -// Window, private: - -int64 Window::SetPropertyInternal(const void* key, - const char* name, - PropertyDeallocator deallocator, - int64 value, - int64 default_value) { - int64 old = GetPropertyInternal(key, default_value); - if (value == default_value) { - prop_map_.erase(key); - } else { - Value prop_value; - prop_value.name = name; - prop_value.value = value; - prop_value.deallocator = deallocator; - prop_map_[key] = prop_value; - } - FOR_EACH_OBSERVER(WindowObserver, observers_, - OnWindowPropertyChanged(this, key, old)); - return old; -} - -int64 Window::GetPropertyInternal(const void* key, - int64 default_value) const { - std::map<const void*, Value>::const_iterator iter = prop_map_.find(key); - if (iter == prop_map_.end()) - return default_value; - return iter->second.value; -} - -bool Window::HitTest(const gfx::Point& local_point) { - gfx::Rect local_bounds(bounds().size()); - if (!delegate_ || !delegate_->HasHitTestMask()) - return local_bounds.Contains(local_point); - - gfx::Path mask; - delegate_->GetHitTestMask(&mask); - - SkRegion clip_region; - clip_region.setRect(local_bounds.x(), local_bounds.y(), - local_bounds.width(), local_bounds.height()); - SkRegion mask_region; - return mask_region.setPath(mask, clip_region) && - mask_region.contains(local_point.x(), local_point.y()); -} - -void Window::SetBoundsInternal(const gfx::Rect& new_bounds) { - gfx::Rect actual_new_bounds(new_bounds); - gfx::Rect old_bounds = GetTargetBounds(); - - // Always need to set the layer's bounds -- even if it is to the same thing. - // This may cause important side effects such as stopping animation. - if (!layer()) { - const gfx::Vector2d origin_delta = new_bounds.OffsetFromOrigin() - - bounds_.OffsetFromOrigin(); - bounds_ = new_bounds; - OffsetLayerBounds(origin_delta); - } else { - if (parent_ && !parent_->layer()) { - gfx::Vector2d offset; - const aura::Window* ancestor_with_layer = - parent_->GetAncestorWithLayer(&offset); - if (ancestor_with_layer) - actual_new_bounds.Offset(offset); - } - layer()->SetBounds(actual_new_bounds); - } - - // If we are currently not the layer's delegate, we will not get bounds - // changed notification from the layer (this typically happens after animating - // hidden). We must notify ourselves. - if (!layer() || layer()->delegate() != this) - OnWindowBoundsChanged(old_bounds); -} - -void Window::SetVisible(bool visible) { - if ((layer() && visible == layer()->GetTargetVisibility()) || - (!layer() && visible == visible_)) - return; // No change. - - FOR_EACH_OBSERVER(WindowObserver, observers_, - OnWindowVisibilityChanging(this, visible)); - - client::VisibilityClient* visibility_client = - client::GetVisibilityClient(this); - if (visibility_client) - visibility_client->UpdateLayerVisibility(this, visible); - else if (layer()) - layer()->SetVisible(visible); - visible_ = visible; - SchedulePaint(); - if (parent_ && parent_->layout_manager_) - parent_->layout_manager_->OnChildWindowVisibilityChanged(this, visible); - - if (delegate_) - delegate_->OnWindowTargetVisibilityChanged(visible); - - NotifyWindowVisibilityChanged(this, visible); -} - -void Window::SchedulePaint() { - SchedulePaintInRect(gfx::Rect(0, 0, bounds().width(), bounds().height())); -} - -void Window::Paint(gfx::Canvas* canvas) { - if (delegate_) - delegate_->OnPaint(canvas); - PaintLayerlessChildren(canvas); -} - -void Window::PaintLayerlessChildren(gfx::Canvas* canvas) { - for (size_t i = 0, count = children_.size(); i < count; ++i) { - Window* child = children_[i]; - if (!child->layer() && child->visible_) { - gfx::ScopedCanvas scoped_canvas(canvas); - canvas->ClipRect(child->bounds()); - if (!canvas->IsClipEmpty()) { - canvas->Translate(child->bounds().OffsetFromOrigin()); - child->Paint(canvas); - } - } - } -} - -Window* Window::GetWindowForPoint(const gfx::Point& local_point, - bool return_tightest, - bool for_event_handling) { - if (!IsVisible()) - return NULL; - - if ((for_event_handling && !HitTest(local_point)) || - (!for_event_handling && !ContainsPoint(local_point))) - return NULL; - - // Check if I should claim this event and not pass it to my children because - // the location is inside my hit test override area. For details, see - // set_hit_test_bounds_override_inner(). - if (for_event_handling && !hit_test_bounds_override_inner_.empty()) { - gfx::Rect inset_local_bounds(gfx::Point(), bounds().size()); - inset_local_bounds.Inset(hit_test_bounds_override_inner_); - // We know we're inside the normal local bounds, so if we're outside the - // inset bounds we must be in the special hit test override area. - DCHECK(HitTest(local_point)); - if (!inset_local_bounds.Contains(local_point)) - return delegate_ ? this : NULL; - } - - if (!return_tightest && delegate_) - return this; - - for (Windows::const_reverse_iterator it = children_.rbegin(), - rend = children_.rend(); - it != rend; ++it) { - Window* child = *it; - - if (for_event_handling) { - if (child->ignore_events_) - continue; - // The client may not allow events to be processed by certain subtrees. - client::EventClient* client = client::GetEventClient(GetRootWindow()); - if (client && !client->CanProcessEventsWithinSubtree(child)) - continue; - if (delegate_ && !delegate_->ShouldDescendIntoChildForEventHandling( - child, local_point)) - continue; - } - - gfx::Point point_in_child_coords(local_point); - ConvertPointToTarget(this, child, &point_in_child_coords); - Window* match = child->GetWindowForPoint(point_in_child_coords, - return_tightest, - for_event_handling); - if (match) - return match; - } - - return delegate_ ? this : NULL; -} - -void Window::RemoveChildImpl(Window* child, Window* new_parent) { - if (layout_manager_) - layout_manager_->OnWillRemoveWindowFromLayout(child); - FOR_EACH_OBSERVER(WindowObserver, observers_, OnWillRemoveWindow(child)); - Window* root_window = child->GetRootWindow(); - Window* new_root_window = new_parent ? new_parent->GetRootWindow() : NULL; - if (root_window && root_window != new_root_window) - child->NotifyRemovingFromRootWindow(new_root_window); - - gfx::Vector2d offset; - GetAncestorWithLayer(&offset); - child->UnparentLayers(!layer(), offset); - child->parent_ = NULL; - Windows::iterator i = std::find(children_.begin(), children_.end(), child); - DCHECK(i != children_.end()); - children_.erase(i); - child->OnParentChanged(); - if (layout_manager_) - layout_manager_->OnWindowRemovedFromLayout(child); -} - -void Window::UnparentLayers(bool has_layerless_ancestor, - const gfx::Vector2d& offset) { - if (!layer()) { - const gfx::Vector2d new_offset = offset + bounds().OffsetFromOrigin(); - for (size_t i = 0; i < children_.size(); ++i) { - children_[i]->UnparentLayers(true, new_offset); - } - } else { - // Only remove the layer if we still own it. Someone else may have acquired - // ownership of it via AcquireLayer() and may expect the hierarchy to go - // unchanged as the Window is destroyed. - if (OwnsLayer()) { - if (layer()->parent()) - layer()->parent()->Remove(layer()); - if (has_layerless_ancestor) { - const gfx::Rect real_bounds(bounds_); - gfx::Rect layer_bounds(layer()->bounds()); - layer_bounds.Offset(-offset); - layer()->SetBounds(layer_bounds); - bounds_ = real_bounds; - } - } - } -} - -void Window::ReparentLayers(ui::Layer* parent_layer, - const gfx::Vector2d& offset) { - if (!layer()) { - for (size_t i = 0; i < children_.size(); ++i) { - children_[i]->ReparentLayers( - parent_layer, - offset + children_[i]->bounds().OffsetFromOrigin()); - } - } else { - const gfx::Rect real_bounds(bounds()); - parent_layer->Add(layer()); - gfx::Rect layer_bounds(layer()->bounds().size()); - layer_bounds += offset; - layer()->SetBounds(layer_bounds); - bounds_ = real_bounds; - } -} - -void Window::OffsetLayerBounds(const gfx::Vector2d& offset) { - if (!layer()) { - for (size_t i = 0; i < children_.size(); ++i) - children_[i]->OffsetLayerBounds(offset); - } else { - gfx::Rect layer_bounds(layer()->bounds()); - layer_bounds += offset; - layer()->SetBounds(layer_bounds); - } -} - -void Window::OnParentChanged() { - FOR_EACH_OBSERVER( - WindowObserver, observers_, OnWindowParentChanged(this, parent_)); -} - -void Window::StackChildRelativeTo(Window* child, - Window* target, - StackDirection direction) { - DCHECK_NE(child, target); - DCHECK(child); - DCHECK(target); - DCHECK_EQ(this, child->parent()); - DCHECK_EQ(this, target->parent()); - - client::WindowStackingClient* stacking_client = - client::GetWindowStackingClient(); - if (stacking_client && - !stacking_client->AdjustStacking(&child, &target, &direction)) - return; - - const size_t child_i = - std::find(children_.begin(), children_.end(), child) - children_.begin(); - const size_t target_i = - std::find(children_.begin(), children_.end(), target) - children_.begin(); - - // Don't move the child if it is already in the right place. - if ((direction == STACK_ABOVE && child_i == target_i + 1) || - (direction == STACK_BELOW && child_i + 1 == target_i)) - return; - - const size_t dest_i = - direction == STACK_ABOVE ? - (child_i < target_i ? target_i : target_i + 1) : - (child_i < target_i ? target_i - 1 : target_i); - children_.erase(children_.begin() + child_i); - children_.insert(children_.begin() + dest_i, child); - - StackChildLayerRelativeTo(child, target, direction); - - child->OnStackingChanged(); -} - -void Window::StackChildLayerRelativeTo(Window* child, - Window* target, - StackDirection direction) { - Window* ancestor_with_layer = GetAncestorWithLayer(NULL); - ui::Layer* ancestor_layer = - ancestor_with_layer ? ancestor_with_layer->layer() : NULL; - if (!ancestor_layer) - return; - - if (child->layer() && target->layer()) { - if (direction == STACK_ABOVE) - ancestor_layer->StackAbove(child->layer(), target->layer()); - else - ancestor_layer->StackBelow(child->layer(), target->layer()); - return; - } - typedef std::vector<ui::Layer*> Layers; - Layers layers; - GetLayersToStack(child, &layers); - if (layers.empty()) - return; - - ui::Layer* target_layer; - if (direction == STACK_ABOVE) { - target_layer = - FindStackingTargetLayer<Windows::const_reverse_iterator>(target, child); - } else { - target_layer = - FindStackingTargetLayer<Windows::const_iterator>(target, child); - } - - if (!target_layer) { - if (direction == STACK_ABOVE) { - for (Layers::const_reverse_iterator i = layers.rbegin(), - rend = layers.rend(); i != rend; ++i) { - ancestor_layer->StackAtBottom(*i); - } - } else { - for (Layers::const_iterator i = layers.begin(); i != layers.end(); ++i) - ancestor_layer->StackAtTop(*i); - } - return; - } - - if (direction == STACK_ABOVE) { - for (Layers::const_reverse_iterator i = layers.rbegin(), - rend = layers.rend(); i != rend; ++i) { - ancestor_layer->StackAbove(*i, target_layer); - } - } else { - for (Layers::const_iterator i = layers.begin(); i != layers.end(); ++i) - ancestor_layer->StackBelow(*i, target_layer); - } -} - -void Window::OnStackingChanged() { - FOR_EACH_OBSERVER(WindowObserver, observers_, OnWindowStackingChanged(this)); -} - -void Window::NotifyRemovingFromRootWindow(Window* new_root) { - FOR_EACH_OBSERVER(WindowObserver, observers_, - OnWindowRemovingFromRootWindow(this, new_root)); - for (Window::Windows::const_iterator it = children_.begin(); - it != children_.end(); ++it) { - (*it)->NotifyRemovingFromRootWindow(new_root); - } -} - -void Window::NotifyAddedToRootWindow() { - FOR_EACH_OBSERVER(WindowObserver, observers_, - OnWindowAddedToRootWindow(this)); - for (Window::Windows::const_iterator it = children_.begin(); - it != children_.end(); ++it) { - (*it)->NotifyAddedToRootWindow(); - } -} - -void Window::NotifyWindowHierarchyChange( - const WindowObserver::HierarchyChangeParams& params) { - params.target->NotifyWindowHierarchyChangeDown(params); - switch (params.phase) { - case WindowObserver::HierarchyChangeParams::HIERARCHY_CHANGING: - if (params.old_parent) - params.old_parent->NotifyWindowHierarchyChangeUp(params); - break; - case WindowObserver::HierarchyChangeParams::HIERARCHY_CHANGED: - if (params.new_parent) - params.new_parent->NotifyWindowHierarchyChangeUp(params); - break; - default: - NOTREACHED(); - break; - } -} - -void Window::NotifyWindowHierarchyChangeDown( - const WindowObserver::HierarchyChangeParams& params) { - NotifyWindowHierarchyChangeAtReceiver(params); - for (Window::Windows::const_iterator it = children_.begin(); - it != children_.end(); ++it) { - (*it)->NotifyWindowHierarchyChangeDown(params); - } -} - -void Window::NotifyWindowHierarchyChangeUp( - const WindowObserver::HierarchyChangeParams& params) { - for (Window* window = this; window; window = window->parent()) - window->NotifyWindowHierarchyChangeAtReceiver(params); -} - -void Window::NotifyWindowHierarchyChangeAtReceiver( - const WindowObserver::HierarchyChangeParams& params) { - WindowObserver::HierarchyChangeParams local_params = params; - local_params.receiver = this; - - switch (params.phase) { - case WindowObserver::HierarchyChangeParams::HIERARCHY_CHANGING: - FOR_EACH_OBSERVER(WindowObserver, observers_, - OnWindowHierarchyChanging(local_params)); - break; - case WindowObserver::HierarchyChangeParams::HIERARCHY_CHANGED: - FOR_EACH_OBSERVER(WindowObserver, observers_, - OnWindowHierarchyChanged(local_params)); - break; - default: - NOTREACHED(); - break; - } -} - -void Window::NotifyWindowVisibilityChanged(aura::Window* target, - bool visible) { - if (!NotifyWindowVisibilityChangedDown(target, visible)) { - return; // |this| has been deleted. - } - NotifyWindowVisibilityChangedUp(target, visible); -} - -bool Window::NotifyWindowVisibilityChangedAtReceiver(aura::Window* target, - bool visible) { - // |this| may be deleted during a call to OnWindowVisibilityChanged() on one - // of the observers. We create an local observer for that. In that case we - // exit without further access to any members. - WindowTracker tracker; - tracker.Add(this); - FOR_EACH_OBSERVER(WindowObserver, observers_, - OnWindowVisibilityChanged(target, visible)); - return tracker.Contains(this); -} - -bool Window::NotifyWindowVisibilityChangedDown(aura::Window* target, - bool visible) { - if (!NotifyWindowVisibilityChangedAtReceiver(target, visible)) - return false; // |this| was deleted. - std::set<const Window*> child_already_processed; - bool child_destroyed = false; - do { - child_destroyed = false; - for (Window::Windows::const_iterator it = children_.begin(); - it != children_.end(); ++it) { - if (!child_already_processed.insert(*it).second) - continue; - if (!(*it)->NotifyWindowVisibilityChangedDown(target, visible)) { - // |*it| was deleted, |it| is invalid and |children_| has changed. - // We exit the current for-loop and enter a new one. - child_destroyed = true; - break; - } - } - } while (child_destroyed); - return true; -} - -void Window::NotifyWindowVisibilityChangedUp(aura::Window* target, - bool visible) { - // Start with the parent as we already notified |this| - // in NotifyWindowVisibilityChangedDown. - for (Window* window = parent(); window; window = window->parent()) { - bool ret = window->NotifyWindowVisibilityChangedAtReceiver(target, visible); - DCHECK(ret); - } -} - -void Window::NotifyAncestorWindowTransformed(Window* source) { - FOR_EACH_OBSERVER(WindowObserver, observers_, - OnAncestorWindowTransformed(source, this)); - for (Window::Windows::const_iterator it = children_.begin(); - it != children_.end(); ++it) { - (*it)->NotifyAncestorWindowTransformed(source); - } -} - -void Window::OnWindowBoundsChanged(const gfx::Rect& old_bounds) { - if (layer()) { - bounds_ = layer()->bounds(); - if (parent_ && !parent_->layer()) { - gfx::Vector2d offset; - aura::Window* ancestor_with_layer = - parent_->GetAncestorWithLayer(&offset); - if (ancestor_with_layer) - bounds_.Offset(-offset); - } - } - - if (layout_manager_) - layout_manager_->OnWindowResized(); - if (delegate_) - delegate_->OnBoundsChanged(old_bounds, bounds()); - FOR_EACH_OBSERVER(WindowObserver, - observers_, - OnWindowBoundsChanged(this, old_bounds, bounds())); -} - -bool Window::CleanupGestureState() { - bool state_modified = false; - state_modified |= ui::GestureRecognizer::Get()->CancelActiveTouches(this); - state_modified |= - ui::GestureRecognizer::Get()->CleanupStateForConsumer(this); - for (Window::Windows::iterator iter = children_.begin(); - iter != children_.end(); - ++iter) { - state_modified |= (*iter)->CleanupGestureState(); - } - return state_modified; -} - -void Window::OnPaintLayer(gfx::Canvas* canvas) { - Paint(canvas); -} - -void Window::OnDelegatedFrameDamage(const gfx::Rect& damage_rect_in_dip) { - DCHECK(layer()); - FOR_EACH_OBSERVER(WindowObserver, - observers_, - OnDelegatedFrameDamage(this, damage_rect_in_dip)); -} - -base::Closure Window::PrepareForLayerBoundsChange() { - return base::Bind(&Window::OnWindowBoundsChanged, base::Unretained(this), - bounds()); -} - -bool Window::CanAcceptEvent(const ui::Event& event) { - // The client may forbid certain windows from receiving events at a given - // point in time. - client::EventClient* client = client::GetEventClient(GetRootWindow()); - if (client && !client->CanProcessEventsWithinSubtree(this)) - return false; - - // We need to make sure that a touch cancel event and any gesture events it - // creates can always reach the window. This ensures that we receive a valid - // touch / gesture stream. - if (event.IsEndingEvent()) - return true; - - if (!IsVisible()) - return false; - - // The top-most window can always process an event. - if (!parent_) - return true; - - // For located events (i.e. mouse, touch etc.), an assumption is made that - // windows that don't have a default event-handler cannot process the event - // (see more in GetWindowForPoint()). This assumption is not made for key - // events. - return event.IsKeyEvent() || target_handler(); -} - -ui::EventTarget* Window::GetParentTarget() { - if (IsRootWindow()) { - return client::GetEventClient(this) ? - client::GetEventClient(this)->GetToplevelEventTarget() : - Env::GetInstance(); - } - return parent_; -} - -scoped_ptr<ui::EventTargetIterator> Window::GetChildIterator() { - return scoped_ptr<ui::EventTargetIterator>( - new ui::EventTargetIteratorImpl<Window>(children())); -} - -ui::EventTargeter* Window::GetEventTargeter() { - return targeter_.get(); -} - -void Window::ConvertEventToTarget(ui::EventTarget* target, - ui::LocatedEvent* event) { - event->ConvertLocationToTarget(this, - static_cast<Window*>(target)); -} - -void Window::UpdateLayerName() { -#if !defined(NDEBUG) - DCHECK(layer()); - - std::string layer_name(name_); - if (layer_name.empty()) - layer_name = "Unnamed Window"; - - if (id_ != -1) - layer_name += " " + base::IntToString(id_); - - layer()->set_name(layer_name); -#endif -} - -bool Window::ContainsMouse() { - bool contains_mouse = false; - if (IsVisible()) { - WindowTreeHost* host = GetHost(); - contains_mouse = host && - ContainsPointInRoot(host->dispatcher()->GetLastMouseLocationInRoot()); - } - return contains_mouse; -} - -const Window* Window::GetAncestorWithLayer(gfx::Vector2d* offset) const { - for (const aura::Window* window = this; window; window = window->parent()) { - if (window->layer()) - return window; - if (offset) - *offset += window->bounds().OffsetFromOrigin(); - } - if (offset) - *offset = gfx::Vector2d(); - return NULL; -} - -} // namespace aura
diff --git a/ui/aura/window.h b/ui/aura/window.h deleted file mode 100644 index cb2397c..0000000 --- a/ui/aura/window.h +++ /dev/null
@@ -1,549 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_WINDOW_H_ -#define UI_AURA_WINDOW_H_ - -#include <map> -#include <string> -#include <vector> - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "base/observer_list.h" -#include "base/strings/string16.h" -#include "ui/aura/aura_export.h" -#include "ui/aura/window_layer_type.h" -#include "ui/aura/window_observer.h" -#include "ui/compositor/layer_animator.h" -#include "ui/compositor/layer_delegate.h" -#include "ui/compositor/layer_owner.h" -#include "ui/events/event_constants.h" -#include "ui/events/event_target.h" -#include "ui/events/event_targeter.h" -#include "ui/events/gestures/gesture_types.h" -#include "ui/gfx/insets.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/gfx/rect.h" -#include "ui/wm/public/window_types.h" - -namespace gfx { -class Display; -class Transform; -class Vector2d; -} - -namespace ui { -class EventHandler; -class Layer; -class Texture; -} - -namespace aura { - -class LayoutManager; -class WindowDelegate; -class WindowObserver; -class WindowTreeHost; - -// Defined in window_property.h (which we do not include) -template<typename T> -struct WindowProperty; - -namespace test { -class WindowTestApi; -} - -// Aura window implementation. Interesting events are sent to the -// WindowDelegate. -// TODO(beng): resolve ownership. -class AURA_EXPORT Window : public ui::LayerDelegate, - public ui::LayerOwner, - public ui::EventTarget, - public ui::GestureConsumer { - public: - // Used when stacking windows. - enum StackDirection { - STACK_ABOVE, - STACK_BELOW - }; - - typedef std::vector<Window*> Windows; - - explicit Window(WindowDelegate* delegate); - ~Window() override; - - // Initializes the window. This creates the window's layer. - void Init(WindowLayerType layer_type); - - void set_owned_by_parent(bool owned_by_parent) { - owned_by_parent_ = owned_by_parent; - } - bool owned_by_parent() const { return owned_by_parent_; } - - // A type is used to identify a class of Windows and customize behavior such - // as event handling and parenting. This field should only be consumed by the - // shell -- Aura itself shouldn't contain type-specific logic. - ui::wm::WindowType type() const { return type_; } - void SetType(ui::wm::WindowType type); - - int id() const { return id_; } - void set_id(int id) { id_ = id; } - - const std::string& name() const { return name_; } - void SetName(const std::string& name); - - const base::string16 title() const { return title_; } - void SetTitle(const base::string16& title); - - bool transparent() const { return transparent_; } - void SetTransparent(bool transparent); - - // See description in Layer::SetFillsBoundsCompletely. - void SetFillsBoundsCompletely(bool fills_bounds); - - WindowDelegate* delegate() { return delegate_; } - const WindowDelegate* delegate() const { return delegate_; } - - const gfx::Rect& bounds() const { return bounds_; } - - Window* parent() { return parent_; } - const Window* parent() const { return parent_; } - - // Returns the root Window that contains this Window. The root Window is - // defined as the Window that has a dispatcher. These functions return NULL if - // the Window is contained in a hierarchy that does not have a dispatcher at - // its root. - Window* GetRootWindow(); - const Window* GetRootWindow() const; - - WindowTreeHost* GetHost(); - const WindowTreeHost* GetHost() const; - void set_host(WindowTreeHost* host) { host_ = host; } - bool IsRootWindow() const { return !!host_; } - - // The Window does not own this object. - void set_user_data(void* user_data) { user_data_ = user_data; } - void* user_data() const { return user_data_; } - - // Changes the visibility of the window. - void Show(); - void Hide(); - // Returns true if this window and all its ancestors are visible. - bool IsVisible() const; - // Returns the visibility requested by this window. IsVisible() takes into - // account the visibility of the layer and ancestors, where as this tracks - // whether Show() without a Hide() has been invoked. - bool TargetVisibility() const { return visible_; } - - // Returns the window's bounds in root window's coordinates. - gfx::Rect GetBoundsInRootWindow() const; - - // Returns the window's bounds in screen coordinates. - // How the root window's coordinates is mapped to screen's coordinates - // is platform dependent and defined in the implementation of the - // |aura::client::ScreenPositionClient| interface. - gfx::Rect GetBoundsInScreen() const; - - void SetTransform(const gfx::Transform& transform); - - // Assigns a LayoutManager to size and place child windows. - // The Window takes ownership of the LayoutManager. - void SetLayoutManager(LayoutManager* layout_manager); - LayoutManager* layout_manager() { return layout_manager_.get(); } - - // Sets a new event-targeter for the window, and returns the previous - // event-targeter. - scoped_ptr<ui::EventTargeter> SetEventTargeter( - scoped_ptr<ui::EventTargeter> targeter); - - // Changes the bounds of the window. If present, the window's parent's - // LayoutManager may adjust the bounds. - void SetBounds(const gfx::Rect& new_bounds); - - // Changes the bounds of the window in the screen coordintates. - // If present, the window's parent's LayoutManager may adjust the bounds. - void SetBoundsInScreen(const gfx::Rect& new_bounds_in_screen_coords, - const gfx::Display& dst_display); - - // Returns the target bounds of the window. If the window's layer is - // not animating, it simply returns the current bounds. - gfx::Rect GetTargetBounds() const; - - // Marks the a portion of window as needing to be painted. - void SchedulePaintInRect(const gfx::Rect& rect); - - // Stacks the specified child of this Window at the front of the z-order. - void StackChildAtTop(Window* child); - - // Stacks |child| above |target|. Does nothing if |child| is already above - // |target|. Does not stack on top of windows with NULL layer delegates, - // see WindowTest.StackingMadrigal for details. - void StackChildAbove(Window* child, Window* target); - - // Stacks the specified child of this window at the bottom of the z-order. - void StackChildAtBottom(Window* child); - - // Stacks |child| below |target|. Does nothing if |child| is already below - // |target|. - void StackChildBelow(Window* child, Window* target); - - // Tree operations. - void AddChild(Window* child); - void RemoveChild(Window* child); - - const Windows& children() const { return children_; } - - // Returns true if this Window contains |other| somewhere in its children. - bool Contains(const Window* other) const; - - // Retrieves the first-level child with the specified id, or NULL if no first- - // level child is found matching |id|. - Window* GetChildById(int id); - const Window* GetChildById(int id) const; - - // Converts |point| from |source|'s coordinates to |target|'s. If |source| is - // NULL, the function returns without modifying |point|. |target| cannot be - // NULL. - static void ConvertPointToTarget(const Window* source, - const Window* target, - gfx::Point* point); - static void ConvertRectToTarget(const Window* source, - const Window* target, - gfx::Rect* rect); - - // Moves the cursor to the specified location relative to the window. - void MoveCursorTo(const gfx::Point& point_in_window); - - // Returns the cursor for the specified point, in window coordinates. - gfx::NativeCursor GetCursor(const gfx::Point& point) const; - - // Add/remove observer. - void AddObserver(WindowObserver* observer); - void RemoveObserver(WindowObserver* observer); - bool HasObserver(WindowObserver* observer); - - void set_ignore_events(bool ignore_events) { ignore_events_ = ignore_events; } - bool ignore_events() const { return ignore_events_; } - - // Sets the window to grab hits for an area extending |insets| pixels inside - // its bounds (even if that inner region overlaps a child window). This can be - // used to create an invisible non-client area that overlaps the client area. - void set_hit_test_bounds_override_inner(const gfx::Insets& insets) { - hit_test_bounds_override_inner_ = insets; - } - gfx::Insets hit_test_bounds_override_inner() const { - return hit_test_bounds_override_inner_; - } - - // Returns true if the |point_in_root| in root window's coordinate falls - // within this window's bounds. Returns false if the window is detached - // from root window. - bool ContainsPointInRoot(const gfx::Point& point_in_root) const; - - // Returns true if relative-to-this-Window's-origin |local_point| falls - // within this Window's bounds. - bool ContainsPoint(const gfx::Point& local_point) const; - - // Returns the Window that most closely encloses |local_point| for the - // purposes of event targeting. - Window* GetEventHandlerForPoint(const gfx::Point& local_point); - - // Returns the topmost Window with a delegate containing |local_point|. - Window* GetTopWindowContainingPoint(const gfx::Point& local_point); - - // Returns this window's toplevel window (the highest-up-the-tree anscestor - // that has a delegate set). The toplevel window may be |this|. - Window* GetToplevelWindow(); - - // Claims or relinquishes the claim to focus. - void Focus(); - void Blur(); - - // Returns true if the Window is currently the focused window. - bool HasFocus() const; - - // Returns true if the Window can be focused. - bool CanFocus() const; - - // Returns true if the Window can receive events. - bool CanReceiveEvents() const; - - // Does a capture on the window. This does nothing if the window isn't showing - // (VISIBILITY_SHOWN) or isn't contained in a valid window hierarchy. - void SetCapture(); - - // Releases a capture. - void ReleaseCapture(); - - // Returns true if this window has capture. - bool HasCapture(); - - // Suppresses painting window content by disgarding damaged rect and ignoring - // new paint requests. This is a one way operation and there is no way to - // reenable painting. - void SuppressPaint(); - - // Sets the |value| of the given window |property|. Setting to the default - // value (e.g., NULL) removes the property. The caller is responsible for the - // lifetime of any object set as a property on the Window. - template<typename T> - void SetProperty(const WindowProperty<T>* property, T value); - - // Returns the value of the given window |property|. Returns the - // property-specific default value if the property was not previously set. - template<typename T> - T GetProperty(const WindowProperty<T>* property) const; - - // Sets the |property| to its default value. Useful for avoiding a cast when - // setting to NULL. - template<typename T> - void ClearProperty(const WindowProperty<T>* property); - - // NativeWidget::[GS]etNativeWindowProperty use strings as keys, and this is - // difficult to change while retaining compatibility with other platforms. - // TODO(benrg): Find a better solution. - void SetNativeWindowProperty(const char* key, void* value); - void* GetNativeWindowProperty(const char* key) const; - - // Type of a function to delete a property that this window owns. - typedef void (*PropertyDeallocator)(int64 value); - - // Overridden from ui::LayerDelegate: - void OnDeviceScaleFactorChanged(float device_scale_factor) override; - -#if !defined(NDEBUG) - // These methods are useful when debugging. - std::string GetDebugInfo() const; - void PrintWindowHierarchy(int depth) const; -#endif - - // Returns true if there was state needing to be cleaned up. - bool CleanupGestureState(); - - protected: - // Deletes (or removes if not owned by parent) all child windows. Intended for - // use from the destructor. - void RemoveOrDestroyChildren(); - - private: - friend class test::WindowTestApi; - friend class LayoutManager; - friend class WindowTargeter; - - // Called by the public {Set,Get,Clear}Property functions. - int64 SetPropertyInternal(const void* key, - const char* name, - PropertyDeallocator deallocator, - int64 value, - int64 default_value); - int64 GetPropertyInternal(const void* key, int64 default_value) const; - - // Returns true if the mouse pointer at relative-to-this-Window's-origin - // |local_point| can trigger an event for this Window. - // TODO(beng): A Window can supply a hit-test mask to cause some portions of - // itself to not trigger events, causing the events to fall through to the - // Window behind. - bool HitTest(const gfx::Point& local_point); - - // Changes the bounds of the window without condition. - void SetBoundsInternal(const gfx::Rect& new_bounds); - - // Updates the visible state of the layer, but does not make visible-state - // specific changes. Called from Show()/Hide(). - void SetVisible(bool visible); - - // Schedules a paint for the Window's entire bounds. - void SchedulePaint(); - - // Asks the delegate to paint the window and invokes PaintLayerlessChildren() - // to paint any children with no layers. - void Paint(gfx::Canvas* canvas); - - // Paints any layerless children to |canvas|. - void PaintLayerlessChildren(gfx::Canvas* canvas); - - // Gets a Window (either this one or a subwindow) containing |local_point|. - // If |return_tightest| is true, returns the tightest-containing (i.e. - // furthest down the hierarchy) Window containing the point; otherwise, - // returns the loosest. If |for_event_handling| is true, then hit-test masks - // are honored; otherwise, only bounds checks are performed. - Window* GetWindowForPoint(const gfx::Point& local_point, - bool return_tightest, - bool for_event_handling); - - // Implementation of RemoveChild(). If |child| is being removed as the result - // of an add, |new_parent| is the new parent |child| is going to be parented - // to. - void RemoveChildImpl(Window* child, Window* new_parent); - - // If this Window has a layer the layer's parent is set to NULL, otherwise - // UnparentLayers() is invoked on all the children. |offset| is the offset - // relative to the nearest ancestor with a layer. - void UnparentLayers(bool has_layerless_ancestor, - const gfx::Vector2d& offset); - - // If this Window has a layer it is added to |parent| and the origin set to - // |offset|. Otherwise this recurses through the children invoking - // ReparentLayers(). The net effect is both setting the parent of layers to - // |parent| as well as updating bounds of windows with a layerless ancestor. - void ReparentLayers(ui::Layer* parent, const gfx::Vector2d& offset); - - // Offsets the first encountered Windows with layers by |offset|. This - // recurses through all layerless Windows, stopping at windows with layers. - void OffsetLayerBounds(const gfx::Vector2d& offset); - - // Called when this window's parent has changed. - void OnParentChanged(); - - // The various stacking functions call into this to do the actual stacking. - void StackChildRelativeTo(Window* child, - Window* target, - StackDirection direction); - - // Invoked from StackChildRelativeTo() to stack the layers appropriately - // when stacking |child| relative to |target|. - void StackChildLayerRelativeTo(Window* child, - Window* target, - StackDirection direction); - - // Called when this window's stacking order among its siblings is changed. - void OnStackingChanged(); - - // Notifies observers registered with this Window (and its subtree) when the - // Window has been added or is about to be removed from a RootWindow. - void NotifyRemovingFromRootWindow(Window* new_root); - void NotifyAddedToRootWindow(); - - // Methods implementing hierarchy change notifications. See WindowObserver for - // more details. - void NotifyWindowHierarchyChange( - const WindowObserver::HierarchyChangeParams& params); - // Notifies this window and its child hierarchy. - void NotifyWindowHierarchyChangeDown( - const WindowObserver::HierarchyChangeParams& params); - // Notifies this window and its parent hierarchy. - void NotifyWindowHierarchyChangeUp( - const WindowObserver::HierarchyChangeParams& params); - // Notifies this window's observers. - void NotifyWindowHierarchyChangeAtReceiver( - const WindowObserver::HierarchyChangeParams& params); - - // Methods implementing visibility change notifications. See WindowObserver - // for more details. - void NotifyWindowVisibilityChanged(aura::Window* target, bool visible); - // Notifies this window's observers. Returns false if |this| was deleted - // during the call (by an observer), otherwise true. - bool NotifyWindowVisibilityChangedAtReceiver(aura::Window* target, - bool visible); - // Notifies this window and its child hierarchy. Returns false if - // |this| was deleted during the call (by an observer), otherwise - // true. - bool NotifyWindowVisibilityChangedDown(aura::Window* target, bool visible); - // Notifies this window and its parent hierarchy. - void NotifyWindowVisibilityChangedUp(aura::Window* target, bool visible); - - // Notifies this window and its child hierarchy of a transform applied to - // |source|. - void NotifyAncestorWindowTransformed(Window* source); - - // Invoked when the bounds of the window changes. This may be invoked directly - // by us, or from the closure returned by PrepareForLayerBoundsChange() after - // the bounds of the layer has changed. |old_bounds| is the previous bounds. - void OnWindowBoundsChanged(const gfx::Rect& old_bounds); - - // Overridden from ui::LayerDelegate: - void OnPaintLayer(gfx::Canvas* canvas) override; - void OnDelegatedFrameDamage(const gfx::Rect& damage_rect_in_dip) override; - base::Closure PrepareForLayerBoundsChange() override; - - // Overridden from ui::EventTarget: - bool CanAcceptEvent(const ui::Event& event) override; - EventTarget* GetParentTarget() override; - scoped_ptr<ui::EventTargetIterator> GetChildIterator() override; - ui::EventTargeter* GetEventTargeter() override; - void ConvertEventToTarget(ui::EventTarget* target, - ui::LocatedEvent* event) override; - - // Updates the layer name based on the window's name and id. - void UpdateLayerName(); - - // Returns true if the mouse is currently within our bounds. - bool ContainsMouse(); - - // Returns the first ancestor (starting at |this|) with a layer. |offset| is - // set to the offset from |this| to the first ancestor with a layer. |offset| - // may be NULL. - Window* GetAncestorWithLayer(gfx::Vector2d* offset) { - return const_cast<Window*>( - const_cast<const Window*>(this)->GetAncestorWithLayer(offset)); - } - const Window* GetAncestorWithLayer(gfx::Vector2d* offset) const; - - // Bounds of this window relative to the parent. This is cached as the bounds - // of the Layer and Window are not necessarily the same. In particular bounds - // of the Layer are relative to the first ancestor with a Layer, where as this - // is relative to the parent Window. - gfx::Rect bounds_; - - WindowTreeHost* host_; - - ui::wm::WindowType type_; - - // True if the Window is owned by its parent - i.e. it will be deleted by its - // parent during its parents destruction. True is the default. - bool owned_by_parent_; - - WindowDelegate* delegate_; - - // The Window's parent. - Window* parent_; - - // Child windows. Topmost is last. - Windows children_; - - // The visibility state of the window as set by Show()/Hide(). This may differ - // from the visibility of the underlying layer, which may remain visible after - // the window is hidden (e.g. to animate its disappearance). - bool visible_; - - int id_; - std::string name_; - - base::string16 title_; - - // Whether layer is initialized as non-opaque. - bool transparent_; - - scoped_ptr<LayoutManager> layout_manager_; - scoped_ptr<ui::EventTargeter> targeter_; - - void* user_data_; - - // Makes the window pass all events through to any windows behind it. - bool ignore_events_; - - // See set_hit_test_bounds_override_inner(). - gfx::Insets hit_test_bounds_override_inner_; - - ObserverList<WindowObserver, true> observers_; - - // Value struct to keep the name and deallocator for this property. - // Key cannot be used for this purpose because it can be char* or - // WindowProperty<>. - struct Value { - const char* name; - int64 value; - PropertyDeallocator deallocator; - }; - - std::map<const void*, Value> prop_map_; - - DISALLOW_COPY_AND_ASSIGN(Window); -}; - -} // namespace aura - -#endif // UI_AURA_WINDOW_H_
diff --git a/ui/aura/window_delegate.h b/ui/aura/window_delegate.h deleted file mode 100644 index 90e978a..0000000 --- a/ui/aura/window_delegate.h +++ /dev/null
@@ -1,109 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_WINDOW_DELEGATE_H_ -#define UI_AURA_WINDOW_DELEGATE_H_ - -#include "base/compiler_specific.h" -#include "base/memory/ref_counted.h" -#include "ui/aura/aura_export.h" -#include "ui/events/event_constants.h" -#include "ui/events/event_handler.h" -#include "ui/gfx/native_widget_types.h" - -namespace gfx { -class Canvas; -class Path; -class Point; -class Rect; -class Size; -} - -namespace ui { -class GestureEvent; -class KeyEvent; -class Layer; -class MouseEvent; -class Texture; -class TouchEvent; -} - -namespace aura { - -// Delegate interface for aura::Window. -class AURA_EXPORT WindowDelegate : public ui::EventHandler { - public: - // Returns the window's minimum size, or size 0,0 if there is no limit. - virtual gfx::Size GetMinimumSize() const = 0; - - // Returns the window's maximum size, or size 0,0 if there is no limit. - virtual gfx::Size GetMaximumSize() const = 0; - - // Called when the Window's position and/or size changes. - virtual void OnBoundsChanged(const gfx::Rect& old_bounds, - const gfx::Rect& new_bounds) = 0; - - // Returns the native cursor for the specified point, in window coordinates, - // or NULL for the default cursor. - virtual gfx::NativeCursor GetCursor(const gfx::Point& point) = 0; - - // Returns the non-client component (see hit_test.h) containing |point|, in - // window coordinates. - virtual int GetNonClientComponent(const gfx::Point& point) const = 0; - - // Returns true if event handling should descend into |child|. |location| is - // in terms of the Window. - virtual bool ShouldDescendIntoChildForEventHandling( - Window* child, - const gfx::Point& location) = 0; - - // Returns true of the window can be focused. - virtual bool CanFocus() = 0; - - // Invoked when mouse capture is lost on the window. - virtual void OnCaptureLost() = 0; - - // Asks the delegate to paint window contents into the supplied canvas. - virtual void OnPaint(gfx::Canvas* canvas) = 0; - - // Called when the window's device scale factor has changed. - virtual void OnDeviceScaleFactorChanged(float device_scale_factor) = 0; - - // Called from Window's destructor before OnWindowDestroyed and before the - // children have been destroyed and the window has been removed from its - // parent. - // This method takes the window because the delegate implementation may no - // longer have a route back to the window by the time this method is called. - virtual void OnWindowDestroying(Window* window) = 0; - - // Called when the Window has been destroyed (i.e. from its destructor). This - // is called after OnWindowDestroying and after the children have been - // deleted and the window has been removed from its parent. - // The delegate can use this as an opportunity to delete itself if necessary. - // This method takes the window because the delegate implementation may no - // longer have a route back to the window by the time this method is called. - virtual void OnWindowDestroyed(Window* window) = 0; - - // Called when the TargetVisibility() of a Window changes. |visible| - // corresponds to the target visibility of the window. See - // Window::TargetVisibility() for details. - virtual void OnWindowTargetVisibilityChanged(bool visible) = 0; - - // Called from Window::HitTest to check if the window has a custom hit test - // mask. It works similar to the views counterparts. That is, if the function - // returns true, GetHitTestMask below will be called to get the mask. - // Otherwise, Window will hit-test against its bounds. - virtual bool HasHitTestMask() const = 0; - - // Called from Window::HitTest to retrieve hit test mask when HasHitTestMask - // above returns true. - virtual void GetHitTestMask(gfx::Path* mask) const = 0; - - protected: - virtual ~WindowDelegate() {} -}; - -} // namespace aura - -#endif // UI_AURA_WINDOW_DELEGATE_H_
diff --git a/ui/aura/window_event_dispatcher.cc b/ui/aura/window_event_dispatcher.cc deleted file mode 100644 index 0b1103d..0000000 --- a/ui/aura/window_event_dispatcher.cc +++ /dev/null
@@ -1,906 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/window_event_dispatcher.h" - -#include "base/bind.h" -#include "base/debug/trace_event.h" -#include "base/logging.h" -#include "base/message_loop/message_loop.h" -#include "ui/aura/client/capture_client.h" -#include "ui/aura/client/cursor_client.h" -#include "ui/aura/client/event_client.h" -#include "ui/aura/client/focus_client.h" -#include "ui/aura/client/screen_position_client.h" -#include "ui/aura/env.h" -#include "ui/aura/window.h" -#include "ui/aura/window_delegate.h" -#include "ui/aura/window_targeter.h" -#include "ui/aura/window_tracker.h" -#include "ui/aura/window_tree_host.h" -#include "ui/base/hit_test.h" -#include "ui/compositor/dip_util.h" -#include "ui/events/event.h" -#include "ui/events/gestures/gesture_recognizer.h" -#include "ui/events/gestures/gesture_types.h" - -typedef ui::EventDispatchDetails DispatchDetails; - -namespace aura { - -namespace { - -// Returns true if |target| has a non-client (frame) component at |location|, -// in window coordinates. -bool IsNonClientLocation(Window* target, const gfx::Point& location) { - if (!target->delegate()) - return false; - int hit_test_code = target->delegate()->GetNonClientComponent(location); - return hit_test_code != HTCLIENT && hit_test_code != HTNOWHERE; -} - -Window* ConsumerToWindow(ui::GestureConsumer* consumer) { - return consumer ? static_cast<Window*>(consumer) : NULL; -} - -void SetLastMouseLocation(const Window* root_window, - const gfx::Point& location_in_root) { - client::ScreenPositionClient* client = - client::GetScreenPositionClient(root_window); - if (client) { - gfx::Point location_in_screen = location_in_root; - client->ConvertPointToScreen(root_window, &location_in_screen); - Env::GetInstance()->set_last_mouse_location(location_in_screen); - } else { - Env::GetInstance()->set_last_mouse_location(location_in_root); - } -} - -bool IsEventCandidateForHold(const ui::Event& event) { - if (event.type() == ui::ET_TOUCH_MOVED) - return true; - if (event.type() == ui::ET_MOUSE_DRAGGED) - return true; - if (event.IsMouseEvent() && (event.flags() & ui::EF_IS_SYNTHESIZED)) - return true; - return false; -} - -} // namespace - -//////////////////////////////////////////////////////////////////////////////// -// WindowEventDispatcher, public: - -WindowEventDispatcher::WindowEventDispatcher(WindowTreeHost* host) - : host_(host), - touch_ids_down_(0), - mouse_pressed_handler_(NULL), - mouse_moved_handler_(NULL), - event_dispatch_target_(NULL), - old_dispatch_target_(NULL), - synthesize_mouse_move_(false), - move_hold_count_(0), - dispatching_held_event_(false), - observer_manager_(this), - repost_event_factory_(this), - held_event_factory_(this) { - ui::GestureRecognizer::Get()->AddGestureEventHelper(this); - Env::GetInstance()->AddObserver(this); -} - -WindowEventDispatcher::~WindowEventDispatcher() { - TRACE_EVENT0("shutdown", "WindowEventDispatcher::Destructor"); - Env::GetInstance()->RemoveObserver(this); - ui::GestureRecognizer::Get()->RemoveGestureEventHelper(this); -} - -void WindowEventDispatcher::RepostEvent(const ui::LocatedEvent& event) { - DCHECK(event.type() == ui::ET_MOUSE_PRESSED || - event.type() == ui::ET_GESTURE_TAP_DOWN); - // We allow for only one outstanding repostable event. This is used - // in exiting context menus. A dropped repost request is allowed. - if (event.type() == ui::ET_MOUSE_PRESSED) { - held_repostable_event_.reset( - new ui::MouseEvent( - static_cast<const ui::MouseEvent&>(event), - static_cast<aura::Window*>(event.target()), - window())); - base::MessageLoop::current()->PostNonNestableTask( - FROM_HERE, base::Bind( - base::IgnoreResult(&WindowEventDispatcher::DispatchHeldEvents), - repost_event_factory_.GetWeakPtr())); - } else { - DCHECK(event.type() == ui::ET_GESTURE_TAP_DOWN); - held_repostable_event_.reset(); - // TODO(rbyers): Reposing of gestures is tricky to get - // right, so it's not yet supported. crbug.com/170987. - } -} - -void WindowEventDispatcher::OnMouseEventsEnableStateChanged(bool enabled) { - // Send entered / exited so that visual state can be updated to match - // mouse events state. - PostSynthesizeMouseMove(); - // TODO(mazda): Add code to disable mouse events when |enabled| == false. -} - -void WindowEventDispatcher::DispatchCancelModeEvent() { - ui::CancelModeEvent event; - Window* focused_window = client::GetFocusClient(window())->GetFocusedWindow(); - if (focused_window && !window()->Contains(focused_window)) - focused_window = NULL; - DispatchDetails details = - DispatchEvent(focused_window ? focused_window : window(), &event); - if (details.dispatcher_destroyed) - return; -} - -void WindowEventDispatcher::DispatchGestureEvent(ui::GestureEvent* event) { - DispatchDetails details = DispatchHeldEvents(); - if (details.dispatcher_destroyed) - return; - Window* target = GetGestureTarget(event); - if (target) { - event->ConvertLocationToTarget(window(), target); - DispatchDetails details = DispatchEvent(target, event); - if (details.dispatcher_destroyed) - return; - } -} - -DispatchDetails WindowEventDispatcher::DispatchMouseExitAtPoint( - const gfx::Point& point) { - ui::MouseEvent event(ui::ET_MOUSE_EXITED, point, point, ui::EF_NONE, - ui::EF_NONE); - return DispatchMouseEnterOrExit(event, ui::ET_MOUSE_EXITED); -} - -void WindowEventDispatcher::ProcessedTouchEvent(ui::TouchEvent* event, - Window* window, - ui::EventResult result) { - // TODO(tdresser): Move this to PreDispatchTouchEvent, to enable eager - // gesture detection. See crbug.com/410280. - if (!ui::GestureRecognizer::Get() - ->ProcessTouchEventPreDispatch(*event, window)) { - return; - } - - // Once we've fully migrated to the eager gesture detector, we won't need to - // pass an event here. - scoped_ptr<ui::GestureRecognizer::Gestures> gestures( - ui::GestureRecognizer::Get()->ProcessTouchEventOnAsyncAck( - *event, result, window)); - DispatchDetails details = ProcessGestures(gestures.get()); - if (details.dispatcher_destroyed) - return; -} - -void WindowEventDispatcher::HoldPointerMoves() { - if (!move_hold_count_) - held_event_factory_.InvalidateWeakPtrs(); - ++move_hold_count_; - TRACE_EVENT_ASYNC_BEGIN0("ui", "WindowEventDispatcher::HoldPointerMoves", - this); -} - -void WindowEventDispatcher::ReleasePointerMoves() { - --move_hold_count_; - DCHECK_GE(move_hold_count_, 0); - if (!move_hold_count_ && held_move_event_) { - // We don't want to call DispatchHeldEvents directly, because this might be - // called from a deep stack while another event, in which case dispatching - // another one may not be safe/expected. Instead we post a task, that we - // may cancel if HoldPointerMoves is called again before it executes. - base::MessageLoop::current()->PostNonNestableTask( - FROM_HERE, base::Bind( - base::IgnoreResult(&WindowEventDispatcher::DispatchHeldEvents), - held_event_factory_.GetWeakPtr())); - } - TRACE_EVENT_ASYNC_END0("ui", "WindowEventDispatcher::HoldPointerMoves", this); -} - -gfx::Point WindowEventDispatcher::GetLastMouseLocationInRoot() const { - gfx::Point location = Env::GetInstance()->last_mouse_location(); - client::ScreenPositionClient* client = - client::GetScreenPositionClient(window()); - if (client) - client->ConvertPointFromScreen(window(), &location); - return location; -} - -void WindowEventDispatcher::OnHostLostMouseGrab() { - mouse_pressed_handler_ = NULL; - mouse_moved_handler_ = NULL; -} - -void WindowEventDispatcher::OnCursorMovedToRootLocation( - const gfx::Point& root_location) { - SetLastMouseLocation(window(), root_location); - synthesize_mouse_move_ = false; -} - -void WindowEventDispatcher::OnPostNotifiedWindowDestroying(Window* window) { - OnWindowHidden(window, WINDOW_DESTROYED); -} - -//////////////////////////////////////////////////////////////////////////////// -// WindowEventDispatcher, private: - -Window* WindowEventDispatcher::window() { - return host_->window(); -} - -const Window* WindowEventDispatcher::window() const { - return host_->window(); -} - -void WindowEventDispatcher::TransformEventForDeviceScaleFactor( - ui::LocatedEvent* event) { - event->UpdateForRootTransform(host_->GetInverseRootTransform()); -} - -void WindowEventDispatcher::DispatchMouseExitToHidingWindow(Window* window) { - // The mouse capture is intentionally ignored. Think that a mouse enters - // to a window, the window sets the capture, the mouse exits the window, - // and then it releases the capture. In that case OnMouseExited won't - // be called. So it is natural not to emit OnMouseExited even though - // |window| is the capture window. - gfx::Point last_mouse_location = GetLastMouseLocationInRoot(); - if (window->Contains(mouse_moved_handler_) && - window->ContainsPointInRoot(last_mouse_location)) { - DispatchDetails details = DispatchMouseExitAtPoint(last_mouse_location); - if (details.dispatcher_destroyed) - return; - } -} - -ui::EventDispatchDetails WindowEventDispatcher::DispatchMouseEnterOrExit( - const ui::MouseEvent& event, - ui::EventType type) { - if (event.type() != ui::ET_MOUSE_CAPTURE_CHANGED && - !(event.flags() & ui::EF_IS_SYNTHESIZED)) { - SetLastMouseLocation(window(), event.root_location()); - } - - if (!mouse_moved_handler_ || !mouse_moved_handler_->delegate() || - !window()->Contains(mouse_moved_handler_)) - return DispatchDetails(); - - // |event| may be an event in the process of being dispatched to a target (in - // which case its locations will be in the event's target's coordinate - // system), or a synthetic event created in root-window (in which case, the - // event's target will be NULL, and the event will be in the root-window's - // coordinate system. - aura::Window* target = static_cast<Window*>(event.target()); - if (!target) - target = window(); - ui::MouseEvent translated_event(event, - target, - mouse_moved_handler_, - type, - event.flags() | ui::EF_IS_SYNTHESIZED); - return DispatchEvent(mouse_moved_handler_, &translated_event); -} - -ui::EventDispatchDetails WindowEventDispatcher::ProcessGestures( - ui::GestureRecognizer::Gestures* gestures) { - DispatchDetails details; - if (!gestures || gestures->empty()) - return details; - - Window* target = GetGestureTarget(gestures->get().at(0)); - if (!target) - return details; - - for (size_t i = 0; i < gestures->size(); ++i) { - ui::GestureEvent* event = gestures->get().at(i); - event->ConvertLocationToTarget(window(), target); - details = DispatchEvent(target, event); - if (details.dispatcher_destroyed || details.target_destroyed) - break; - } - return details; -} - -void WindowEventDispatcher::OnWindowHidden(Window* invisible, - WindowHiddenReason reason) { - // If the window the mouse was pressed in becomes invisible, it should no - // longer receive mouse events. - if (invisible->Contains(mouse_pressed_handler_)) - mouse_pressed_handler_ = NULL; - if (invisible->Contains(mouse_moved_handler_)) - mouse_moved_handler_ = NULL; - - // If events are being dispatched from a nested message-loop, and the target - // of the outer loop is hidden or moved to another dispatcher during - // dispatching events in the inner loop, then reset the target for the outer - // loop. - if (invisible->Contains(old_dispatch_target_)) - old_dispatch_target_ = NULL; - - invisible->CleanupGestureState(); - - // Do not clear the capture, and the |event_dispatch_target_| if the - // window is moving across hosts, because the target itself is actually still - // visible and clearing them stops further event processing, which can cause - // unexpected behaviors. See crbug.com/157583 - if (reason != WINDOW_MOVING) { - // We don't ask |invisible| here, because invisible may have been removed - // from the window hierarchy already by the time this function is called - // (OnWindowDestroyed). - client::CaptureClient* capture_client = - client::GetCaptureClient(host_->window()); - Window* capture_window = - capture_client ? capture_client->GetCaptureWindow() : NULL; - - if (invisible->Contains(event_dispatch_target_)) - event_dispatch_target_ = NULL; - - // If the ancestor of the capture window is hidden, release the capture. - // Note that this may delete the window so do not use capture_window - // after this. - if (invisible->Contains(capture_window) && invisible != window()) - capture_window->ReleaseCapture(); - } -} - -Window* WindowEventDispatcher::GetGestureTarget(ui::GestureEvent* event) { - Window* target = NULL; - if (!event->IsEndingEvent()) { - // The window that received the start event (e.g. scroll begin) needs to - // receive the end event (e.g. scroll end). - target = client::GetCaptureWindow(window()); - } - if (!target) { - target = ConsumerToWindow( - ui::GestureRecognizer::Get()->GetTargetForGestureEvent(*event)); - } - - return target; -} - -//////////////////////////////////////////////////////////////////////////////// -// WindowEventDispatcher, aura::client::CaptureDelegate implementation: - -void WindowEventDispatcher::UpdateCapture(Window* old_capture, - Window* new_capture) { - // |mouse_moved_handler_| may have been set to a Window in a different root - // (see below). Clear it here to ensure we don't end up referencing a stale - // Window. - if (mouse_moved_handler_ && !window()->Contains(mouse_moved_handler_)) - mouse_moved_handler_ = NULL; - - if (old_capture && old_capture->GetRootWindow() == window() && - old_capture->delegate()) { - // Send a capture changed event with bogus location data. - ui::MouseEvent event(ui::ET_MOUSE_CAPTURE_CHANGED, gfx::Point(), - gfx::Point(), 0, 0); - - DispatchDetails details = DispatchEvent(old_capture, &event); - if (details.dispatcher_destroyed) - return; - - old_capture->delegate()->OnCaptureLost(); - } - - if (new_capture) { - // Make all subsequent mouse events go to the capture window. We shouldn't - // need to send an event here as OnCaptureLost() should take care of that. - if (mouse_moved_handler_ || Env::GetInstance()->IsMouseButtonDown()) - mouse_moved_handler_ = new_capture; - } else { - // Make sure mouse_moved_handler gets updated. - DispatchDetails details = SynthesizeMouseMoveEvent(); - if (details.dispatcher_destroyed) - return; - } - mouse_pressed_handler_ = NULL; -} - -void WindowEventDispatcher::OnOtherRootGotCapture() { - // Windows provides the TrackMouseEvents API which allows us to rely on the - // OS to send us the mouse exit events (WM_MOUSELEAVE). Additionally on - // desktop Windows, every top level window could potentially have its own - // root window, in which case this function will get called whenever those - // windows grab mouse capture. Sending mouse exit messages in these cases - // causes subtle bugs like (crbug.com/394672). -#if !defined(OS_WIN) - if (mouse_moved_handler_) { - // Dispatch a mouse exit to reset any state associated with hover. This is - // important when going from no window having capture to a window having - // capture because we do not dispatch ET_MOUSE_CAPTURE_CHANGED in this case. - DispatchDetails details = DispatchMouseExitAtPoint( - GetLastMouseLocationInRoot()); - if (details.dispatcher_destroyed) - return; - } -#endif - - mouse_moved_handler_ = NULL; - mouse_pressed_handler_ = NULL; -} - -void WindowEventDispatcher::SetNativeCapture() { - host_->SetCapture(); -} - -void WindowEventDispatcher::ReleaseNativeCapture() { - host_->ReleaseCapture(); -} - -//////////////////////////////////////////////////////////////////////////////// -// WindowEventDispatcher, ui::EventProcessor implementation: -ui::EventTarget* WindowEventDispatcher::GetRootTarget() { - return window(); -} - -void WindowEventDispatcher::OnEventProcessingStarted(ui::Event* event) { - // The held events are already in |window()|'s coordinate system. So it is - // not necessary to apply the transform to convert from the host's - // coordinate system to |window()|'s coordinate system. - if (event->IsLocatedEvent() && !dispatching_held_event_) - TransformEventForDeviceScaleFactor(static_cast<ui::LocatedEvent*>(event)); -} - -//////////////////////////////////////////////////////////////////////////////// -// WindowEventDispatcher, ui::EventDispatcherDelegate implementation: - -bool WindowEventDispatcher::CanDispatchToTarget(ui::EventTarget* target) { - return event_dispatch_target_ == target; -} - -ui::EventDispatchDetails WindowEventDispatcher::PreDispatchEvent( - ui::EventTarget* target, - ui::Event* event) { - Window* target_window = static_cast<Window*>(target); - CHECK(window()->Contains(target_window)); - - if (!dispatching_held_event_) { - bool can_be_held = IsEventCandidateForHold(*event); - if (!move_hold_count_ || !can_be_held) { - if (can_be_held) - held_move_event_.reset(); - DispatchDetails details = DispatchHeldEvents(); - if (details.dispatcher_destroyed || details.target_destroyed) - return details; - } - } - - if (event->IsMouseEvent()) { - PreDispatchMouseEvent(target_window, static_cast<ui::MouseEvent*>(event)); - } else if (event->IsScrollEvent()) { - PreDispatchLocatedEvent(target_window, - static_cast<ui::ScrollEvent*>(event)); - } else if (event->IsTouchEvent()) { - PreDispatchTouchEvent(target_window, static_cast<ui::TouchEvent*>(event)); - } - old_dispatch_target_ = event_dispatch_target_; - event_dispatch_target_ = static_cast<Window*>(target); - return DispatchDetails(); -} - -ui::EventDispatchDetails WindowEventDispatcher::PostDispatchEvent( - ui::EventTarget* target, - const ui::Event& event) { - DispatchDetails details; - if (!target || target != event_dispatch_target_) - details.target_destroyed = true; - event_dispatch_target_ = old_dispatch_target_; - old_dispatch_target_ = NULL; -#ifndef NDEBUG - DCHECK(!event_dispatch_target_ || window()->Contains(event_dispatch_target_)); -#endif - - if (event.IsTouchEvent() && !details.target_destroyed) { - // Do not let 'held' touch events contribute to any gestures unless it is - // being dispatched. - if (dispatching_held_event_ || !held_move_event_ || - !held_move_event_->IsTouchEvent()) { - - // Once we've fully migrated to the eager gesture detector, we won't - // need to pass an event here. - ui::TouchEvent orig_event(static_cast<const ui::TouchEvent&>(event), - static_cast<Window*>(event.target()), - window()); - - if (event.result() & ui::ER_CONSUMED) - orig_event.StopPropagation(); - - // TODO(tdresser): Move this to PreDispatchTouchEvent, to enable eager - // gesture detection. See crbug.com/410280. - if (!ui::GestureRecognizer::Get() - ->ProcessTouchEventPreDispatch(orig_event, - static_cast<Window*>(target))) { - return details; - } - - scoped_ptr<ui::GestureRecognizer::Gestures> gestures; - - gestures.reset( - ui::GestureRecognizer::Get()->ProcessTouchEventPostDispatch( - orig_event, event.result(), static_cast<Window*>(target))); - - return ProcessGestures(gestures.get()); - } - } - - return details; -} - -//////////////////////////////////////////////////////////////////////////////// -// WindowEventDispatcher, ui::GestureEventHelper implementation: - -bool WindowEventDispatcher::CanDispatchToConsumer( - ui::GestureConsumer* consumer) { - Window* consumer_window = ConsumerToWindow(consumer); - return (consumer_window && consumer_window->GetRootWindow() == window()); -} - -void WindowEventDispatcher::DispatchCancelTouchEvent(ui::TouchEvent* event) { - // The touchcancel event's location is based on the last known location of - // the pointer, in dips. OnEventFromSource expects events with co-ordinates - // in raw pixels, so we convert back to raw pixels here. - event->UpdateForRootTransform(host_->GetRootTransform()); - DispatchDetails details = OnEventFromSource(event); - if (details.dispatcher_destroyed) - return; -} - -//////////////////////////////////////////////////////////////////////////////// -// WindowEventDispatcher, WindowObserver implementation: - -void WindowEventDispatcher::OnWindowDestroying(Window* window) { - if (!host_->window()->Contains(window)) - return; - - DispatchMouseExitToHidingWindow(window); - SynthesizeMouseMoveAfterChangeToWindow(window); -} - -void WindowEventDispatcher::OnWindowDestroyed(Window* window) { - // We observe all windows regardless of what root Window (if any) they're - // attached to. - observer_manager_.Remove(window); -} - -void WindowEventDispatcher::OnWindowAddedToRootWindow(Window* attached) { - if (!observer_manager_.IsObserving(attached)) - observer_manager_.Add(attached); - - if (!host_->window()->Contains(attached)) - return; - - SynthesizeMouseMoveAfterChangeToWindow(attached); -} - -void WindowEventDispatcher::OnWindowRemovingFromRootWindow(Window* detached, - Window* new_root) { - if (!host_->window()->Contains(detached)) - return; - - DCHECK(client::GetCaptureWindow(window()) != window()); - - DispatchMouseExitToHidingWindow(detached); - SynthesizeMouseMoveAfterChangeToWindow(detached); - - // Hiding the window releases capture which can implicitly destroy the window - // so the window may no longer be valid after this call. - OnWindowHidden(detached, new_root ? WINDOW_MOVING : WINDOW_HIDDEN); -} - -void WindowEventDispatcher::OnWindowVisibilityChanging(Window* window, - bool visible) { - if (!host_->window()->Contains(window)) - return; - - DispatchMouseExitToHidingWindow(window); -} - -void WindowEventDispatcher::OnWindowVisibilityChanged(Window* window, - bool visible) { - if (!host_->window()->Contains(window)) - return; - - if (window->ContainsPointInRoot(GetLastMouseLocationInRoot())) - PostSynthesizeMouseMove(); - - // Hiding the window releases capture which can implicitly destroy the window - // so the window may no longer be valid after this call. - if (!visible) - OnWindowHidden(window, WINDOW_HIDDEN); -} - -void WindowEventDispatcher::OnWindowBoundsChanged(Window* window, - const gfx::Rect& old_bounds, - const gfx::Rect& new_bounds) { - if (!host_->window()->Contains(window)) - return; - - if (window == host_->window()) { - TRACE_EVENT1("ui", "WindowEventDispatcher::OnWindowBoundsChanged(root)", - "size", new_bounds.size().ToString()); - - DispatchDetails details = DispatchHeldEvents(); - if (details.dispatcher_destroyed) - return; - - synthesize_mouse_move_ = false; - } - - if (window->IsVisible() && !window->ignore_events()) { - gfx::Rect old_bounds_in_root = old_bounds, new_bounds_in_root = new_bounds; - Window::ConvertRectToTarget(window->parent(), host_->window(), - &old_bounds_in_root); - Window::ConvertRectToTarget(window->parent(), host_->window(), - &new_bounds_in_root); - gfx::Point last_mouse_location = GetLastMouseLocationInRoot(); - if (old_bounds_in_root.Contains(last_mouse_location) != - new_bounds_in_root.Contains(last_mouse_location)) { - PostSynthesizeMouseMove(); - } - } -} - -void WindowEventDispatcher::OnWindowTransforming(Window* window) { - if (!host_->window()->Contains(window)) - return; - - SynthesizeMouseMoveAfterChangeToWindow(window); -} - -void WindowEventDispatcher::OnWindowTransformed(Window* window) { - if (!host_->window()->Contains(window)) - return; - - SynthesizeMouseMoveAfterChangeToWindow(window); -} - -/////////////////////////////////////////////////////////////////////////////// -// WindowEventDispatcher, EnvObserver implementation: - -void WindowEventDispatcher::OnWindowInitialized(Window* window) { - observer_manager_.Add(window); -} - -//////////////////////////////////////////////////////////////////////////////// -// WindowEventDispatcher, private: - -ui::EventDispatchDetails WindowEventDispatcher::DispatchHeldEvents() { - if (!held_repostable_event_ && !held_move_event_) - return DispatchDetails(); - - CHECK(!dispatching_held_event_); - dispatching_held_event_ = true; - - DispatchDetails dispatch_details; - if (held_repostable_event_) { - if (held_repostable_event_->type() == ui::ET_MOUSE_PRESSED) { - scoped_ptr<ui::MouseEvent> mouse_event( - static_cast<ui::MouseEvent*>(held_repostable_event_.release())); - dispatch_details = OnEventFromSource(mouse_event.get()); - } else { - // TODO(rbyers): GESTURE_TAP_DOWN not yet supported: crbug.com/170987. - NOTREACHED(); - } - if (dispatch_details.dispatcher_destroyed) - return dispatch_details; - } - - if (held_move_event_) { - // If a mouse move has been synthesized, the target location is suspect, - // so drop the held mouse event. - if (held_move_event_->IsTouchEvent() || - (held_move_event_->IsMouseEvent() && !synthesize_mouse_move_)) { - dispatch_details = OnEventFromSource(held_move_event_.get()); - } - if (!dispatch_details.dispatcher_destroyed) - held_move_event_.reset(); - } - - if (!dispatch_details.dispatcher_destroyed) - dispatching_held_event_ = false; - return dispatch_details; -} - -void WindowEventDispatcher::PostSynthesizeMouseMove() { - if (synthesize_mouse_move_) - return; - synthesize_mouse_move_ = true; - base::MessageLoop::current()->PostNonNestableTask( - FROM_HERE, - base::Bind(base::IgnoreResult( - &WindowEventDispatcher::SynthesizeMouseMoveEvent), - held_event_factory_.GetWeakPtr())); -} - -void WindowEventDispatcher::SynthesizeMouseMoveAfterChangeToWindow( - Window* window) { - if (window->IsVisible() && - window->ContainsPointInRoot(GetLastMouseLocationInRoot())) { - PostSynthesizeMouseMove(); - } -} - -ui::EventDispatchDetails WindowEventDispatcher::SynthesizeMouseMoveEvent() { - DispatchDetails details; - if (!synthesize_mouse_move_) - return details; - synthesize_mouse_move_ = false; - - // If one of the mouse buttons is currently down, then do not synthesize a - // mouse-move event. In such cases, aura could synthesize a DRAGGED event - // instead of a MOVED event, but in multi-display/multi-host scenarios, the - // DRAGGED event can be synthesized in the incorrect host. So avoid - // synthesizing any events at all. - if (Env::GetInstance()->mouse_button_flags()) - return details; - - gfx::Point root_mouse_location = GetLastMouseLocationInRoot(); - if (!window()->bounds().Contains(root_mouse_location)) - return details; - gfx::Point host_mouse_location = root_mouse_location; - host_->ConvertPointToHost(&host_mouse_location); - ui::MouseEvent event(ui::ET_MOUSE_MOVED, - host_mouse_location, - host_mouse_location, - ui::EF_IS_SYNTHESIZED, - 0); - return OnEventFromSource(&event); -} - -void WindowEventDispatcher::PreDispatchLocatedEvent(Window* target, - ui::LocatedEvent* event) { - int flags = event->flags(); - if (IsNonClientLocation(target, event->location())) - flags |= ui::EF_IS_NON_CLIENT; - event->set_flags(flags); - - if (!dispatching_held_event_ && - (event->IsMouseEvent() || event->IsScrollEvent()) && - !(event->flags() & ui::EF_IS_SYNTHESIZED)) { - if (event->type() != ui::ET_MOUSE_CAPTURE_CHANGED) - SetLastMouseLocation(window(), event->root_location()); - synthesize_mouse_move_ = false; - } -} - -void WindowEventDispatcher::PreDispatchMouseEvent(Window* target, - ui::MouseEvent* event) { - client::CursorClient* cursor_client = client::GetCursorClient(window()); - // We allow synthesized mouse exit events through even if mouse events are - // disabled. This ensures that hover state, etc on controls like buttons is - // cleared. - if (cursor_client && - !cursor_client->IsMouseEventsEnabled() && - (event->flags() & ui::EF_IS_SYNTHESIZED) && - (event->type() != ui::ET_MOUSE_EXITED)) { - event->SetHandled(); - return; - } - - if (IsEventCandidateForHold(*event) && !dispatching_held_event_) { - if (move_hold_count_) { - if (!(event->flags() & ui::EF_IS_SYNTHESIZED) && - event->type() != ui::ET_MOUSE_CAPTURE_CHANGED) { - SetLastMouseLocation(window(), event->root_location()); - } - held_move_event_.reset(new ui::MouseEvent(*event, target, window())); - event->SetHandled(); - return; - } else { - // We may have a held event for a period between the time move_hold_count_ - // fell to 0 and the DispatchHeldEvents executes. Since we're going to - // dispatch the new event directly below, we can reset the old one. - held_move_event_.reset(); - } - } - - const int kMouseButtonFlagMask = ui::EF_LEFT_MOUSE_BUTTON | - ui::EF_MIDDLE_MOUSE_BUTTON | - ui::EF_RIGHT_MOUSE_BUTTON; - switch (event->type()) { - case ui::ET_MOUSE_EXITED: - if (!target || target == window()) { - DispatchDetails details = - DispatchMouseEnterOrExit(*event, ui::ET_MOUSE_EXITED); - if (details.dispatcher_destroyed) { - event->SetHandled(); - return; - } - mouse_moved_handler_ = NULL; - } - break; - case ui::ET_MOUSE_MOVED: - // Send an exit to the current |mouse_moved_handler_| and an enter to - // |target|. Take care that both us and |target| aren't destroyed during - // dispatch. - if (target != mouse_moved_handler_) { - aura::Window* old_mouse_moved_handler = mouse_moved_handler_; - WindowTracker live_window; - live_window.Add(target); - DispatchDetails details = - DispatchMouseEnterOrExit(*event, ui::ET_MOUSE_EXITED); - if (details.dispatcher_destroyed) { - event->SetHandled(); - return; - } - // If the |mouse_moved_handler_| changes out from under us, assume a - // nested message loop ran and we don't need to do anything. - if (mouse_moved_handler_ != old_mouse_moved_handler) { - event->SetHandled(); - return; - } - if (!live_window.Contains(target) || details.target_destroyed) { - mouse_moved_handler_ = NULL; - event->SetHandled(); - return; - } - live_window.Remove(target); - - mouse_moved_handler_ = target; - details = DispatchMouseEnterOrExit(*event, ui::ET_MOUSE_ENTERED); - if (details.dispatcher_destroyed || details.target_destroyed) { - event->SetHandled(); - return; - } - } - break; - case ui::ET_MOUSE_PRESSED: - // Don't set the mouse pressed handler for non client mouse down events. - // These are only sent by Windows and are not always followed with non - // client mouse up events which causes subsequent mouse events to be - // sent to the wrong target. - if (!(event->flags() & ui::EF_IS_NON_CLIENT) && !mouse_pressed_handler_) - mouse_pressed_handler_ = target; - Env::GetInstance()->set_mouse_button_flags( - event->flags() & kMouseButtonFlagMask); - break; - case ui::ET_MOUSE_RELEASED: - mouse_pressed_handler_ = NULL; - Env::GetInstance()->set_mouse_button_flags(event->flags() & - kMouseButtonFlagMask & ~event->changed_button_flags()); - break; - default: - break; - } - - PreDispatchLocatedEvent(target, event); -} - -void WindowEventDispatcher::PreDispatchTouchEvent(Window* target, - ui::TouchEvent* event) { - switch (event->type()) { - case ui::ET_TOUCH_PRESSED: - touch_ids_down_ |= (1 << event->touch_id()); - Env::GetInstance()->set_touch_down(touch_ids_down_ != 0); - break; - - // Handle ET_TOUCH_CANCELLED only if it has a native event. - case ui::ET_TOUCH_CANCELLED: - if (!event->HasNativeEvent()) - break; - // fallthrough - case ui::ET_TOUCH_RELEASED: - touch_ids_down_ = (touch_ids_down_ | (1 << event->touch_id())) ^ - (1 << event->touch_id()); - Env::GetInstance()->set_touch_down(touch_ids_down_ != 0); - break; - - case ui::ET_TOUCH_MOVED: - if (move_hold_count_ && !dispatching_held_event_) { - held_move_event_.reset(new ui::TouchEvent(*event, target, window())); - event->SetHandled(); - return; - } - break; - - default: - NOTREACHED(); - break; - } - - PreDispatchLocatedEvent(target, event); -} - -} // namespace aura
diff --git a/ui/aura/window_event_dispatcher.h b/ui/aura/window_event_dispatcher.h deleted file mode 100644 index a93c5d8..0000000 --- a/ui/aura/window_event_dispatcher.h +++ /dev/null
@@ -1,272 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_WINDOW_EVENT_DISPATCHER_H_ -#define UI_AURA_WINDOW_EVENT_DISPATCHER_H_ - -#include <vector> - -#include "base/basictypes.h" -#include "base/gtest_prod_util.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "base/memory/weak_ptr.h" -#include "base/message_loop/message_loop.h" -#include "base/scoped_observer.h" -#include "ui/aura/aura_export.h" -#include "ui/aura/client/capture_delegate.h" -#include "ui/aura/env_observer.h" -#include "ui/aura/window_observer.h" -#include "ui/base/cursor/cursor.h" -#include "ui/events/event_constants.h" -#include "ui/events/event_processor.h" -#include "ui/events/event_targeter.h" -#include "ui/events/gestures/gesture_recognizer.h" -#include "ui/events/gestures/gesture_types.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/gfx/point.h" - -namespace gfx { -class Size; -class Transform; -} - -namespace ui { -class GestureEvent; -class GestureRecognizer; -class KeyEvent; -class MouseEvent; -class ScrollEvent; -class TouchEvent; -} - -namespace aura { -class TestScreen; -class WindowTargeter; -class WindowTreeHost; - -namespace test { -class WindowEventDispatcherTestApi; -} - -// WindowEventDispatcher orchestrates event dispatch within a window tree -// owned by WindowTreeHost. WTH also owns the WED. -// TODO(beng): In progress, remove functionality not directly related to -// event dispatch. -class AURA_EXPORT WindowEventDispatcher : public ui::EventProcessor, - public ui::GestureEventHelper, - public client::CaptureDelegate, - public WindowObserver, - public EnvObserver { - public: - explicit WindowEventDispatcher(WindowTreeHost* host); - virtual ~WindowEventDispatcher(); - - Window* mouse_pressed_handler() { return mouse_pressed_handler_; } - Window* mouse_moved_handler() { return mouse_moved_handler_; } - - // Repost event for re-processing. Used when exiting context menus. - // We only support the ET_MOUSE_PRESSED and ET_GESTURE_TAP_DOWN event - // types (although the latter is currently a no-op). - void RepostEvent(const ui::LocatedEvent& event); - - // Invoked when the mouse events get enabled or disabled. - void OnMouseEventsEnableStateChanged(bool enabled); - - void DispatchCancelModeEvent(); - - // Dispatches a ui::ET_MOUSE_EXITED event at |point|. - // TODO(beng): needed only for WTH::OnCursorVisibilityChanged(). - ui::EventDispatchDetails DispatchMouseExitAtPoint( - const gfx::Point& point) WARN_UNUSED_RESULT; - - // Gesture Recognition ------------------------------------------------------- - - // When a touch event is dispatched to a Window, it may want to process the - // touch event asynchronously. In such cases, the window should consume the - // event during the event dispatch. Once the event is properly processed, the - // window should let the WindowEventDispatcher know about the result of the - // event processing, so that gesture events can be properly created and - // dispatched. |event|'s location should be in the dispatcher's coordinate - // space, in DIPs. - void ProcessedTouchEvent(ui::TouchEvent* event, - Window* window, - ui::EventResult result); - - // These methods are used to defer the processing of mouse/touch events - // related to resize. A client (typically a RenderWidgetHostViewAura) can call - // HoldPointerMoves when an resize is initiated and then ReleasePointerMoves - // once the resize is completed. - // - // More than one hold can be invoked and each hold must be cancelled by a - // release before we resume normal operation. - void HoldPointerMoves(); - void ReleasePointerMoves(); - - // Gets the last location seen in a mouse event in this root window's - // coordinates. This may return a point outside the root window's bounds. - gfx::Point GetLastMouseLocationInRoot() const; - - void OnHostLostMouseGrab(); - void OnCursorMovedToRootLocation(const gfx::Point& root_location); - - // TODO(beng): This is only needed because this cleanup needs to happen after - // all other observers are notified of OnWindowDestroying() but - // before OnWindowDestroyed() is sent (i.e. while the window - // hierarchy is still intact). This didn't seem worth adding a - // generic notification for as only this class needs to implement - // it. I would however like to find a way to do this via an - // observer. - void OnPostNotifiedWindowDestroying(Window* window); - - private: - FRIEND_TEST_ALL_PREFIXES(WindowEventDispatcherTest, - KeepTranslatedEventInRoot); - - friend class test::WindowEventDispatcherTestApi; - friend class Window; - friend class TestScreen; - - // The parameter for OnWindowHidden() to specify why window is hidden. - enum WindowHiddenReason { - WINDOW_DESTROYED, // Window is destroyed. - WINDOW_HIDDEN, // Window is hidden. - WINDOW_MOVING, // Window is temporarily marked as hidden due to move - // across root windows. - }; - - Window* window(); - const Window* window() const; - - // Updates the event with the appropriate transform for the device scale - // factor. The WindowEventDispatcher dispatches events in the physical pixel - // coordinate. But the event processing from WindowEventDispatcher onwards - // happen in device-independent pixel coordinate. So it is necessary to update - // the event received from the host. - void TransformEventForDeviceScaleFactor(ui::LocatedEvent* event); - - // Dispatches OnMouseExited to the |window| which is hiding if necessary. - void DispatchMouseExitToHidingWindow(Window* window); - - // Dispatches the specified event type (intended for enter/exit) to the - // |mouse_moved_handler_|. - ui::EventDispatchDetails DispatchMouseEnterOrExit( - const ui::MouseEvent& event, - ui::EventType type) WARN_UNUSED_RESULT; - ui::EventDispatchDetails ProcessGestures( - ui::GestureRecognizer::Gestures* gestures) WARN_UNUSED_RESULT; - - // Called when a window becomes invisible, either by being removed - // from root window hierarchy, via SetVisible(false) or being destroyed. - // |reason| specifies what triggered the hiding. Note that becoming invisible - // will cause a window to lose capture and some windows may destroy themselves - // on capture (like DragDropTracker). - void OnWindowHidden(Window* invisible, WindowHiddenReason reason); - - // Returns a target window for the given gesture event. - Window* GetGestureTarget(ui::GestureEvent* event); - - // Overridden from aura::client::CaptureDelegate: - virtual void UpdateCapture(Window* old_capture, Window* new_capture) override; - virtual void OnOtherRootGotCapture() override; - virtual void SetNativeCapture() override; - virtual void ReleaseNativeCapture() override; - - // Overridden from ui::EventProcessor: - virtual ui::EventTarget* GetRootTarget() override; - virtual void OnEventProcessingStarted(ui::Event* event) override; - - // Overridden from ui::EventDispatcherDelegate. - virtual bool CanDispatchToTarget(ui::EventTarget* target) override; - virtual ui::EventDispatchDetails PreDispatchEvent(ui::EventTarget* target, - ui::Event* event) override; - virtual ui::EventDispatchDetails PostDispatchEvent( - ui::EventTarget* target, const ui::Event& event) override; - - // Overridden from ui::GestureEventHelper. - virtual bool CanDispatchToConsumer(ui::GestureConsumer* consumer) override; - virtual void DispatchGestureEvent(ui::GestureEvent* event) override; - virtual void DispatchCancelTouchEvent(ui::TouchEvent* event) override; - - // Overridden from WindowObserver: - virtual void OnWindowDestroying(Window* window) override; - virtual void OnWindowDestroyed(Window* window) override; - virtual void OnWindowAddedToRootWindow(Window* window) override; - virtual void OnWindowRemovingFromRootWindow(Window* window, - Window* new_root) override; - virtual void OnWindowVisibilityChanging(Window* window, - bool visible) override; - virtual void OnWindowVisibilityChanged(Window* window, bool visible) override; - virtual void OnWindowBoundsChanged(Window* window, - const gfx::Rect& old_bounds, - const gfx::Rect& new_bounds) override; - virtual void OnWindowTransforming(Window* window) override; - virtual void OnWindowTransformed(Window* window) override; - - // Overridden from EnvObserver: - virtual void OnWindowInitialized(Window* window) override; - - // We hold and aggregate mouse drags and touch moves as a way of throttling - // resizes when HoldMouseMoves() is called. The following methods are used to - // dispatch held and newly incoming mouse and touch events, typically when an - // event other than one of these needs dispatching or a matching - // ReleaseMouseMoves()/ReleaseTouchMoves() is called. NOTE: because these - // methods dispatch events from WindowTreeHost the coordinates are in terms of - // the root. - ui::EventDispatchDetails DispatchHeldEvents() WARN_UNUSED_RESULT; - - // Posts a task to send synthesized mouse move event if there is no a pending - // task. - void PostSynthesizeMouseMove(); - - // Creates and dispatches synthesized mouse move event using the current mouse - // location. - ui::EventDispatchDetails SynthesizeMouseMoveEvent() WARN_UNUSED_RESULT; - - // Calls SynthesizeMouseMove() if |window| is currently visible and contains - // the mouse cursor. - void SynthesizeMouseMoveAfterChangeToWindow(Window* window); - - void PreDispatchLocatedEvent(Window* target, ui::LocatedEvent* event); - void PreDispatchMouseEvent(Window* target, ui::MouseEvent* event); - void PreDispatchTouchEvent(Window* target, ui::TouchEvent* event); - - WindowTreeHost* host_; - - // Touch ids that are currently down. - uint32 touch_ids_down_; - - Window* mouse_pressed_handler_; - Window* mouse_moved_handler_; - Window* event_dispatch_target_; - Window* old_dispatch_target_; - - bool synthesize_mouse_move_; - - // How many move holds are outstanding. We try to defer dispatching - // touch/mouse moves while the count is > 0. - int move_hold_count_; - // The location of |held_move_event_| is in |window_|'s coordinate. - scoped_ptr<ui::LocatedEvent> held_move_event_; - - // Allowing for reposting of events. Used when exiting context menus. - scoped_ptr<ui::LocatedEvent> held_repostable_event_; - - // Set when dispatching a held event. - bool dispatching_held_event_; - - ScopedObserver<aura::Window, aura::WindowObserver> observer_manager_; - - // Used to schedule reposting an event. - base::WeakPtrFactory<WindowEventDispatcher> repost_event_factory_; - - // Used to schedule DispatchHeldEvents() when |move_hold_count_| goes to 0. - base::WeakPtrFactory<WindowEventDispatcher> held_event_factory_; - - DISALLOW_COPY_AND_ASSIGN(WindowEventDispatcher); -}; - -} // namespace aura - -#endif // UI_AURA_WINDOW_EVENT_DISPATCHER_H_
diff --git a/ui/aura/window_event_dispatcher_unittest.cc b/ui/aura/window_event_dispatcher_unittest.cc deleted file mode 100644 index 6822101..0000000 --- a/ui/aura/window_event_dispatcher_unittest.cc +++ /dev/null
@@ -1,2369 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/window_event_dispatcher.h" - -#include <vector> - -#include "base/bind.h" -#include "base/run_loop.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/aura/client/capture_client.h" -#include "ui/aura/client/event_client.h" -#include "ui/aura/client/focus_client.h" -#include "ui/aura/env.h" -#include "ui/aura/test/aura_test_base.h" -#include "ui/aura/test/env_test_helper.h" -#include "ui/aura/test/test_cursor_client.h" -#include "ui/aura/test/test_screen.h" -#include "ui/aura/test/test_window_delegate.h" -#include "ui/aura/test/test_windows.h" -#include "ui/aura/window.h" -#include "ui/aura/window_tracker.h" -#include "ui/base/hit_test.h" -#include "ui/events/event.h" -#include "ui/events/event_handler.h" -#include "ui/events/event_utils.h" -#include "ui/events/gestures/gesture_configuration.h" -#include "ui/events/keycodes/keyboard_codes.h" -#include "ui/events/test/event_generator.h" -#include "ui/events/test/test_event_handler.h" -#include "ui/gfx/point.h" -#include "ui/gfx/rect.h" -#include "ui/gfx/screen.h" -#include "ui/gfx/transform.h" - -namespace aura { -namespace { - -// A delegate that always returns a non-client component for hit tests. -class NonClientDelegate : public test::TestWindowDelegate { - public: - NonClientDelegate() - : non_client_count_(0), - mouse_event_count_(0), - mouse_event_flags_(0x0) { - } - virtual ~NonClientDelegate() {} - - int non_client_count() const { return non_client_count_; } - gfx::Point non_client_location() const { return non_client_location_; } - int mouse_event_count() const { return mouse_event_count_; } - gfx::Point mouse_event_location() const { return mouse_event_location_; } - int mouse_event_flags() const { return mouse_event_flags_; } - - virtual int GetNonClientComponent(const gfx::Point& location) const override { - NonClientDelegate* self = const_cast<NonClientDelegate*>(this); - self->non_client_count_++; - self->non_client_location_ = location; - return HTTOPLEFT; - } - virtual void OnMouseEvent(ui::MouseEvent* event) override { - mouse_event_count_++; - mouse_event_location_ = event->location(); - mouse_event_flags_ = event->flags(); - event->SetHandled(); - } - - private: - int non_client_count_; - gfx::Point non_client_location_; - int mouse_event_count_; - gfx::Point mouse_event_location_; - int mouse_event_flags_; - - DISALLOW_COPY_AND_ASSIGN(NonClientDelegate); -}; - -// A simple event handler that consumes key events. -class ConsumeKeyHandler : public ui::test::TestEventHandler { - public: - ConsumeKeyHandler() {} - virtual ~ConsumeKeyHandler() {} - - // Overridden from ui::EventHandler: - virtual void OnKeyEvent(ui::KeyEvent* event) override { - ui::test::TestEventHandler::OnKeyEvent(event); - event->StopPropagation(); - } - - private: - DISALLOW_COPY_AND_ASSIGN(ConsumeKeyHandler); -}; - -bool IsFocusedWindow(aura::Window* window) { - return client::GetFocusClient(window)->GetFocusedWindow() == window; -} - -} // namespace - -typedef test::AuraTestBase WindowEventDispatcherTest; - -TEST_F(WindowEventDispatcherTest, OnHostMouseEvent) { - // Create two non-overlapping windows so we don't have to worry about which - // is on top. - scoped_ptr<NonClientDelegate> delegate1(new NonClientDelegate()); - scoped_ptr<NonClientDelegate> delegate2(new NonClientDelegate()); - const int kWindowWidth = 123; - const int kWindowHeight = 45; - gfx::Rect bounds1(100, 200, kWindowWidth, kWindowHeight); - gfx::Rect bounds2(300, 400, kWindowWidth, kWindowHeight); - scoped_ptr<aura::Window> window1(CreateTestWindowWithDelegate( - delegate1.get(), -1234, bounds1, root_window())); - scoped_ptr<aura::Window> window2(CreateTestWindowWithDelegate( - delegate2.get(), -5678, bounds2, root_window())); - - // Send a mouse event to window1. - gfx::Point point(101, 201); - ui::MouseEvent event1( - ui::ET_MOUSE_PRESSED, point, point, ui::EF_LEFT_MOUSE_BUTTON, - ui::EF_LEFT_MOUSE_BUTTON); - DispatchEventUsingWindowDispatcher(&event1); - - // Event was tested for non-client area for the target window. - EXPECT_EQ(1, delegate1->non_client_count()); - EXPECT_EQ(0, delegate2->non_client_count()); - // The non-client component test was in local coordinates. - EXPECT_EQ(gfx::Point(1, 1), delegate1->non_client_location()); - // Mouse event was received by target window. - EXPECT_EQ(1, delegate1->mouse_event_count()); - EXPECT_EQ(0, delegate2->mouse_event_count()); - // Event was in local coordinates. - EXPECT_EQ(gfx::Point(1, 1), delegate1->mouse_event_location()); - // Non-client flag was set. - EXPECT_TRUE(delegate1->mouse_event_flags() & ui::EF_IS_NON_CLIENT); -} - -TEST_F(WindowEventDispatcherTest, RepostEvent) { - // Test RepostEvent in RootWindow. It only works for Mouse Press. - EXPECT_FALSE(Env::GetInstance()->IsMouseButtonDown()); - gfx::Point point(10, 10); - ui::MouseEvent event( - ui::ET_MOUSE_PRESSED, point, point, ui::EF_LEFT_MOUSE_BUTTON, - ui::EF_LEFT_MOUSE_BUTTON); - host()->dispatcher()->RepostEvent(event); - RunAllPendingInMessageLoop(); - EXPECT_TRUE(Env::GetInstance()->IsMouseButtonDown()); -} - -// Check that we correctly track the state of the mouse buttons in response to -// button press and release events. -TEST_F(WindowEventDispatcherTest, MouseButtonState) { - EXPECT_FALSE(Env::GetInstance()->IsMouseButtonDown()); - - gfx::Point location; - scoped_ptr<ui::MouseEvent> event; - - // Press the left button. - event.reset(new ui::MouseEvent( - ui::ET_MOUSE_PRESSED, - location, - location, - ui::EF_LEFT_MOUSE_BUTTON, - ui::EF_LEFT_MOUSE_BUTTON)); - DispatchEventUsingWindowDispatcher(event.get()); - EXPECT_TRUE(Env::GetInstance()->IsMouseButtonDown()); - - // Additionally press the right. - event.reset(new ui::MouseEvent( - ui::ET_MOUSE_PRESSED, - location, - location, - ui::EF_LEFT_MOUSE_BUTTON | ui::EF_RIGHT_MOUSE_BUTTON, - ui::EF_RIGHT_MOUSE_BUTTON)); - DispatchEventUsingWindowDispatcher(event.get()); - EXPECT_TRUE(Env::GetInstance()->IsMouseButtonDown()); - - // Release the left button. - event.reset(new ui::MouseEvent( - ui::ET_MOUSE_RELEASED, - location, - location, - ui::EF_RIGHT_MOUSE_BUTTON, - ui::EF_LEFT_MOUSE_BUTTON)); - DispatchEventUsingWindowDispatcher(event.get()); - EXPECT_TRUE(Env::GetInstance()->IsMouseButtonDown()); - - // Release the right button. We should ignore the Shift-is-down flag. - event.reset(new ui::MouseEvent( - ui::ET_MOUSE_RELEASED, - location, - location, - ui::EF_SHIFT_DOWN, - ui::EF_RIGHT_MOUSE_BUTTON)); - DispatchEventUsingWindowDispatcher(event.get()); - EXPECT_FALSE(Env::GetInstance()->IsMouseButtonDown()); - - // Press the middle button. - event.reset(new ui::MouseEvent( - ui::ET_MOUSE_PRESSED, - location, - location, - ui::EF_MIDDLE_MOUSE_BUTTON, - ui::EF_MIDDLE_MOUSE_BUTTON)); - DispatchEventUsingWindowDispatcher(event.get()); - EXPECT_TRUE(Env::GetInstance()->IsMouseButtonDown()); -} - -TEST_F(WindowEventDispatcherTest, TranslatedEvent) { - scoped_ptr<Window> w1(test::CreateTestWindowWithDelegate(NULL, 1, - gfx::Rect(50, 50, 100, 100), root_window())); - - gfx::Point origin(100, 100); - ui::MouseEvent root(ui::ET_MOUSE_PRESSED, origin, origin, 0, 0); - - EXPECT_EQ("100,100", root.location().ToString()); - EXPECT_EQ("100,100", root.root_location().ToString()); - - ui::MouseEvent translated_event( - root, static_cast<Window*>(root_window()), w1.get(), - ui::ET_MOUSE_ENTERED, root.flags()); - EXPECT_EQ("50,50", translated_event.location().ToString()); - EXPECT_EQ("100,100", translated_event.root_location().ToString()); -} - -namespace { - -class TestEventClient : public client::EventClient { - public: - static const int kNonLockWindowId = 100; - static const int kLockWindowId = 200; - - explicit TestEventClient(Window* root_window) - : root_window_(root_window), - lock_(false) { - client::SetEventClient(root_window_, this); - Window* lock_window = - test::CreateTestWindowWithBounds(root_window_->bounds(), root_window_); - lock_window->set_id(kLockWindowId); - Window* non_lock_window = - test::CreateTestWindowWithBounds(root_window_->bounds(), root_window_); - non_lock_window->set_id(kNonLockWindowId); - } - virtual ~TestEventClient() { - client::SetEventClient(root_window_, NULL); - } - - // Starts/stops locking. Locking prevents windows other than those inside - // the lock container from receiving events, getting focus etc. - void Lock() { - lock_ = true; - } - void Unlock() { - lock_ = false; - } - - Window* GetLockWindow() { - return const_cast<Window*>( - static_cast<const TestEventClient*>(this)->GetLockWindow()); - } - const Window* GetLockWindow() const { - return root_window_->GetChildById(kLockWindowId); - } - Window* GetNonLockWindow() { - return root_window_->GetChildById(kNonLockWindowId); - } - - private: - // Overridden from client::EventClient: - virtual bool CanProcessEventsWithinSubtree( - const Window* window) const override { - return lock_ ? - window->Contains(GetLockWindow()) || GetLockWindow()->Contains(window) : - true; - } - - virtual ui::EventTarget* GetToplevelEventTarget() override { - return NULL; - } - - Window* root_window_; - bool lock_; - - DISALLOW_COPY_AND_ASSIGN(TestEventClient); -}; - -} // namespace - -TEST_F(WindowEventDispatcherTest, CanProcessEventsWithinSubtree) { - TestEventClient client(root_window()); - test::TestWindowDelegate d; - - ui::test::TestEventHandler nonlock_ef; - ui::test::TestEventHandler lock_ef; - client.GetNonLockWindow()->AddPreTargetHandler(&nonlock_ef); - client.GetLockWindow()->AddPreTargetHandler(&lock_ef); - - Window* w1 = test::CreateTestWindowWithBounds(gfx::Rect(10, 10, 20, 20), - client.GetNonLockWindow()); - w1->set_id(1); - Window* w2 = test::CreateTestWindowWithBounds(gfx::Rect(30, 30, 20, 20), - client.GetNonLockWindow()); - w2->set_id(2); - scoped_ptr<Window> w3( - test::CreateTestWindowWithDelegate(&d, 3, gfx::Rect(30, 30, 20, 20), - client.GetLockWindow())); - - w1->Focus(); - EXPECT_TRUE(IsFocusedWindow(w1)); - - client.Lock(); - - // Since we're locked, the attempt to focus w2 will be ignored. - w2->Focus(); - EXPECT_TRUE(IsFocusedWindow(w1)); - EXPECT_FALSE(IsFocusedWindow(w2)); - - { - // Attempting to send a key event to w1 (not in the lock container) should - // cause focus to be reset. - ui::test::EventGenerator generator(root_window()); - generator.PressKey(ui::VKEY_SPACE, 0); - EXPECT_EQ(NULL, client::GetFocusClient(w1)->GetFocusedWindow()); - EXPECT_FALSE(IsFocusedWindow(w1)); - } - - { - // Events sent to a window not in the lock container will not be processed. - // i.e. never sent to the non-lock container's event filter. - ui::test::EventGenerator generator(root_window(), w1); - generator.ClickLeftButton(); - EXPECT_EQ(0, nonlock_ef.num_mouse_events()); - - // Events sent to a window in the lock container will be processed. - ui::test::EventGenerator generator3(root_window(), w3.get()); - generator3.PressLeftButton(); - EXPECT_EQ(1, lock_ef.num_mouse_events()); - } - - // Prevent w3 from being deleted by the hierarchy since its delegate is owned - // by this scope. - w3->parent()->RemoveChild(w3.get()); -} - -TEST_F(WindowEventDispatcherTest, DontIgnoreUnknownKeys) { - ConsumeKeyHandler handler; - root_window()->AddPreTargetHandler(&handler); - - ui::KeyEvent unknown_event(ui::ET_KEY_PRESSED, ui::VKEY_UNKNOWN, ui::EF_NONE); - DispatchEventUsingWindowDispatcher(&unknown_event); - EXPECT_TRUE(unknown_event.handled()); - EXPECT_EQ(1, handler.num_key_events()); - - handler.Reset(); - ui::KeyEvent known_event(ui::ET_KEY_PRESSED, ui::VKEY_A, ui::EF_NONE); - DispatchEventUsingWindowDispatcher(&known_event); - EXPECT_TRUE(known_event.handled()); - EXPECT_EQ(1, handler.num_key_events()); - - handler.Reset(); - ui::KeyEvent ime_event(ui::ET_KEY_PRESSED, ui::VKEY_UNKNOWN, - ui::EF_IME_FABRICATED_KEY); - DispatchEventUsingWindowDispatcher(&ime_event); - EXPECT_TRUE(ime_event.handled()); - EXPECT_EQ(1, handler.num_key_events()); - - handler.Reset(); - ui::KeyEvent unknown_key_with_char_event(ui::ET_KEY_PRESSED, ui::VKEY_UNKNOWN, - ui::EF_NONE); - unknown_key_with_char_event.set_character(0x00e4 /* "ä" */); - DispatchEventUsingWindowDispatcher(&unknown_key_with_char_event); - EXPECT_TRUE(unknown_key_with_char_event.handled()); - EXPECT_EQ(1, handler.num_key_events()); -} - -TEST_F(WindowEventDispatcherTest, NoDelegateWindowReceivesKeyEvents) { - scoped_ptr<Window> w1(CreateNormalWindow(1, root_window(), NULL)); - w1->Show(); - w1->Focus(); - - ui::test::TestEventHandler handler; - w1->AddPreTargetHandler(&handler); - ui::KeyEvent key_press(ui::ET_KEY_PRESSED, ui::VKEY_A, ui::EF_NONE); - DispatchEventUsingWindowDispatcher(&key_press); - EXPECT_TRUE(key_press.handled()); - EXPECT_EQ(1, handler.num_key_events()); - - w1->RemovePreTargetHandler(&handler); -} - -// Tests that touch-events that are beyond the bounds of the root-window do get -// propagated to the event filters correctly with the root as the target. -TEST_F(WindowEventDispatcherTest, TouchEventsOutsideBounds) { - ui::test::TestEventHandler handler; - root_window()->AddPreTargetHandler(&handler); - - gfx::Point position = root_window()->bounds().origin(); - position.Offset(-10, -10); - ui::TouchEvent press( - ui::ET_TOUCH_PRESSED, position, 0, ui::EventTimeForNow()); - DispatchEventUsingWindowDispatcher(&press); - EXPECT_EQ(1, handler.num_touch_events()); - - position = root_window()->bounds().origin(); - position.Offset(root_window()->bounds().width() + 10, - root_window()->bounds().height() + 10); - ui::TouchEvent release( - ui::ET_TOUCH_RELEASED, position, 0, ui::EventTimeForNow()); - DispatchEventUsingWindowDispatcher(&release); - EXPECT_EQ(2, handler.num_touch_events()); -} - -// Tests that scroll events are dispatched correctly. -TEST_F(WindowEventDispatcherTest, ScrollEventDispatch) { - base::TimeDelta now = ui::EventTimeForNow(); - ui::test::TestEventHandler handler; - root_window()->AddPreTargetHandler(&handler); - - test::TestWindowDelegate delegate; - scoped_ptr<Window> w1(CreateNormalWindow(1, root_window(), &delegate)); - w1->SetBounds(gfx::Rect(20, 20, 40, 40)); - - // A scroll event on the root-window itself is dispatched. - ui::ScrollEvent scroll1(ui::ET_SCROLL, - gfx::Point(10, 10), - now, - 0, - 0, -10, - 0, -10, - 2); - DispatchEventUsingWindowDispatcher(&scroll1); - EXPECT_EQ(1, handler.num_scroll_events()); - - // Scroll event on a window should be dispatched properly. - ui::ScrollEvent scroll2(ui::ET_SCROLL, - gfx::Point(25, 30), - now, - 0, - -10, 0, - -10, 0, - 2); - DispatchEventUsingWindowDispatcher(&scroll2); - EXPECT_EQ(2, handler.num_scroll_events()); - root_window()->RemovePreTargetHandler(&handler); -} - -namespace { - -// FilterFilter that tracks the types of events it's seen. -class EventFilterRecorder : public ui::EventHandler { - public: - typedef std::vector<ui::EventType> Events; - typedef std::vector<gfx::Point> EventLocations; - typedef std::vector<int> EventFlags; - - EventFilterRecorder() - : wait_until_event_(ui::ET_UNKNOWN) { - } - - const Events& events() const { return events_; } - - const EventLocations& mouse_locations() const { return mouse_locations_; } - gfx::Point mouse_location(int i) const { return mouse_locations_[i]; } - const EventLocations& touch_locations() const { return touch_locations_; } - const EventLocations& gesture_locations() const { return gesture_locations_; } - const EventFlags& mouse_event_flags() const { return mouse_event_flags_; } - - void WaitUntilReceivedEvent(ui::EventType type) { - wait_until_event_ = type; - run_loop_.reset(new base::RunLoop()); - run_loop_->Run(); - } - - Events GetAndResetEvents() { - Events events = events_; - Reset(); - return events; - } - - void Reset() { - events_.clear(); - mouse_locations_.clear(); - touch_locations_.clear(); - gesture_locations_.clear(); - mouse_event_flags_.clear(); - } - - // ui::EventHandler overrides: - virtual void OnEvent(ui::Event* event) override { - ui::EventHandler::OnEvent(event); - events_.push_back(event->type()); - if (wait_until_event_ == event->type() && run_loop_) { - run_loop_->Quit(); - wait_until_event_ = ui::ET_UNKNOWN; - } - } - - virtual void OnMouseEvent(ui::MouseEvent* event) override { - mouse_locations_.push_back(event->location()); - mouse_event_flags_.push_back(event->flags()); - } - - virtual void OnTouchEvent(ui::TouchEvent* event) override { - touch_locations_.push_back(event->location()); - } - - virtual void OnGestureEvent(ui::GestureEvent* event) override { - gesture_locations_.push_back(event->location()); - } - - bool HasReceivedEvent(ui::EventType type) { - return std::find(events_.begin(), events_.end(), type) != events_.end(); - } - - private: - scoped_ptr<base::RunLoop> run_loop_; - ui::EventType wait_until_event_; - - Events events_; - EventLocations mouse_locations_; - EventLocations touch_locations_; - EventLocations gesture_locations_; - EventFlags mouse_event_flags_; - - DISALLOW_COPY_AND_ASSIGN(EventFilterRecorder); -}; - -// Converts an EventType to a string. -std::string EventTypeToString(ui::EventType type) { - switch (type) { - case ui::ET_TOUCH_RELEASED: - return "TOUCH_RELEASED"; - - case ui::ET_TOUCH_CANCELLED: - return "TOUCH_CANCELLED"; - - case ui::ET_TOUCH_PRESSED: - return "TOUCH_PRESSED"; - - case ui::ET_TOUCH_MOVED: - return "TOUCH_MOVED"; - - case ui::ET_MOUSE_PRESSED: - return "MOUSE_PRESSED"; - - case ui::ET_MOUSE_DRAGGED: - return "MOUSE_DRAGGED"; - - case ui::ET_MOUSE_RELEASED: - return "MOUSE_RELEASED"; - - case ui::ET_MOUSE_MOVED: - return "MOUSE_MOVED"; - - case ui::ET_MOUSE_ENTERED: - return "MOUSE_ENTERED"; - - case ui::ET_MOUSE_EXITED: - return "MOUSE_EXITED"; - - case ui::ET_GESTURE_SCROLL_BEGIN: - return "GESTURE_SCROLL_BEGIN"; - - case ui::ET_GESTURE_SCROLL_END: - return "GESTURE_SCROLL_END"; - - case ui::ET_GESTURE_SCROLL_UPDATE: - return "GESTURE_SCROLL_UPDATE"; - - case ui::ET_GESTURE_PINCH_BEGIN: - return "GESTURE_PINCH_BEGIN"; - - case ui::ET_GESTURE_PINCH_END: - return "GESTURE_PINCH_END"; - - case ui::ET_GESTURE_PINCH_UPDATE: - return "GESTURE_PINCH_UPDATE"; - - case ui::ET_GESTURE_TAP: - return "GESTURE_TAP"; - - case ui::ET_GESTURE_TAP_DOWN: - return "GESTURE_TAP_DOWN"; - - case ui::ET_GESTURE_TAP_CANCEL: - return "GESTURE_TAP_CANCEL"; - - case ui::ET_GESTURE_SHOW_PRESS: - return "GESTURE_SHOW_PRESS"; - - case ui::ET_GESTURE_BEGIN: - return "GESTURE_BEGIN"; - - case ui::ET_GESTURE_END: - return "GESTURE_END"; - - default: - // We should explicitly require each event type. - NOTREACHED() << "Received unexpected event: " << type; - break; - } - return ""; -} - -std::string EventTypesToString(const EventFilterRecorder::Events& events) { - std::string result; - for (size_t i = 0; i < events.size(); ++i) { - if (i != 0) - result += " "; - result += EventTypeToString(events[i]); - } - return result; -} - -} // namespace - -#if defined(OS_WIN) && defined(ARCH_CPU_X86) -#define MAYBE(x) DISABLED_##x -#else -#define MAYBE(x) x -#endif - -// Verifies a repost mouse event targets the window with capture (if there is -// one). -// Flaky on 32-bit Windows bots. http://crbug.com/388290 -TEST_F(WindowEventDispatcherTest, MAYBE(RepostTargetsCaptureWindow)) { - // Set capture on |window| generate a mouse event (that is reposted) and not - // over |window| and verify |window| gets it (|window| gets it because it has - // capture). - EXPECT_FALSE(Env::GetInstance()->IsMouseButtonDown()); - EventFilterRecorder recorder; - scoped_ptr<Window> window(CreateNormalWindow(1, root_window(), NULL)); - window->SetBounds(gfx::Rect(20, 20, 40, 30)); - window->AddPreTargetHandler(&recorder); - window->SetCapture(); - const ui::MouseEvent press_event( - ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(), - ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); - host()->dispatcher()->RepostEvent(press_event); - RunAllPendingInMessageLoop(); // Necessitated by RepostEvent(). - // Mouse moves/enters may be generated. We only care about a pressed. - EXPECT_TRUE(EventTypesToString(recorder.events()).find("MOUSE_PRESSED") != - std::string::npos) << EventTypesToString(recorder.events()); -} - -TEST_F(WindowEventDispatcherTest, MouseMovesHeld) { - EventFilterRecorder recorder; - root_window()->AddPreTargetHandler(&recorder); - - test::TestWindowDelegate delegate; - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - &delegate, 1, gfx::Rect(0, 0, 100, 100), root_window())); - - ui::MouseEvent mouse_move_event(ui::ET_MOUSE_MOVED, gfx::Point(0, 0), - gfx::Point(0, 0), 0, 0); - DispatchEventUsingWindowDispatcher(&mouse_move_event); - // Discard MOUSE_ENTER. - recorder.Reset(); - - host()->dispatcher()->HoldPointerMoves(); - - // Check that we don't immediately dispatch the MOUSE_DRAGGED event. - ui::MouseEvent mouse_dragged_event(ui::ET_MOUSE_DRAGGED, gfx::Point(0, 0), - gfx::Point(0, 0), 0, 0); - DispatchEventUsingWindowDispatcher(&mouse_dragged_event); - EXPECT_TRUE(recorder.events().empty()); - - // Check that we do dispatch the held MOUSE_DRAGGED event before another type - // of event. - ui::MouseEvent mouse_pressed_event(ui::ET_MOUSE_PRESSED, gfx::Point(0, 0), - gfx::Point(0, 0), 0, 0); - DispatchEventUsingWindowDispatcher(&mouse_pressed_event); - EXPECT_EQ("MOUSE_DRAGGED MOUSE_PRESSED", - EventTypesToString(recorder.events())); - recorder.Reset(); - - // Check that we coalesce held MOUSE_DRAGGED events. Note that here (and - // elsewhere in this test) we re-define each event prior to dispatch so that - // it has the correct state (phase, handled, target, etc.). - mouse_dragged_event = ui::MouseEvent( - ui::ET_MOUSE_DRAGGED, gfx::Point(0, 0), gfx::Point(0, 0), 0, 0); - ui::MouseEvent mouse_dragged_event2(ui::ET_MOUSE_DRAGGED, gfx::Point(10, 10), - gfx::Point(10, 10), 0, 0); - DispatchEventUsingWindowDispatcher(&mouse_dragged_event); - DispatchEventUsingWindowDispatcher(&mouse_dragged_event2); - EXPECT_TRUE(recorder.events().empty()); - mouse_pressed_event = ui::MouseEvent( - ui::ET_MOUSE_PRESSED, gfx::Point(0, 0), gfx::Point(0, 0), 0, 0); - DispatchEventUsingWindowDispatcher(&mouse_pressed_event); - EXPECT_EQ("MOUSE_DRAGGED MOUSE_PRESSED", - EventTypesToString(recorder.events())); - recorder.Reset(); - - // Check that on ReleasePointerMoves, held events are not dispatched - // immediately, but posted instead. - mouse_dragged_event = ui::MouseEvent( - ui::ET_MOUSE_DRAGGED, gfx::Point(0, 0), gfx::Point(0, 0), 0, 0); - DispatchEventUsingWindowDispatcher(&mouse_dragged_event); - host()->dispatcher()->ReleasePointerMoves(); - EXPECT_TRUE(recorder.events().empty()); - RunAllPendingInMessageLoop(); - EXPECT_EQ("MOUSE_DRAGGED", EventTypesToString(recorder.events())); - recorder.Reset(); - - // However if another message comes in before the dispatch of the posted - // event, check that the posted event is dispatched before this new event. - host()->dispatcher()->HoldPointerMoves(); - mouse_dragged_event = ui::MouseEvent( - ui::ET_MOUSE_DRAGGED, gfx::Point(0, 0), gfx::Point(0, 0), 0, 0); - DispatchEventUsingWindowDispatcher(&mouse_dragged_event); - host()->dispatcher()->ReleasePointerMoves(); - mouse_pressed_event = ui::MouseEvent( - ui::ET_MOUSE_PRESSED, gfx::Point(0, 0), gfx::Point(0, 0), 0, 0); - DispatchEventUsingWindowDispatcher(&mouse_pressed_event); - EXPECT_EQ("MOUSE_DRAGGED MOUSE_PRESSED", - EventTypesToString(recorder.events())); - recorder.Reset(); - RunAllPendingInMessageLoop(); - EXPECT_TRUE(recorder.events().empty()); - - // Check that if the other message is another MOUSE_DRAGGED, we still coalesce - // them. - host()->dispatcher()->HoldPointerMoves(); - mouse_dragged_event = ui::MouseEvent( - ui::ET_MOUSE_DRAGGED, gfx::Point(0, 0), gfx::Point(0, 0), 0, 0); - DispatchEventUsingWindowDispatcher(&mouse_dragged_event); - host()->dispatcher()->ReleasePointerMoves(); - mouse_dragged_event2 = ui::MouseEvent( - ui::ET_MOUSE_DRAGGED, gfx::Point(10, 10), gfx::Point(10, 10), 0, 0); - DispatchEventUsingWindowDispatcher(&mouse_dragged_event2); - EXPECT_EQ("MOUSE_DRAGGED", EventTypesToString(recorder.events())); - recorder.Reset(); - RunAllPendingInMessageLoop(); - EXPECT_TRUE(recorder.events().empty()); - - // Check that synthetic mouse move event has a right location when issued - // while holding pointer moves. - mouse_dragged_event = ui::MouseEvent( - ui::ET_MOUSE_DRAGGED, gfx::Point(0, 0), gfx::Point(0, 0), 0, 0); - mouse_dragged_event2 = ui::MouseEvent( - ui::ET_MOUSE_DRAGGED, gfx::Point(10, 10), gfx::Point(10, 10), 0, 0); - ui::MouseEvent mouse_dragged_event3(ui::ET_MOUSE_DRAGGED, gfx::Point(28, 28), - gfx::Point(28, 28), 0, 0); - host()->dispatcher()->HoldPointerMoves(); - DispatchEventUsingWindowDispatcher(&mouse_dragged_event); - DispatchEventUsingWindowDispatcher(&mouse_dragged_event2); - window->SetBounds(gfx::Rect(15, 15, 80, 80)); - DispatchEventUsingWindowDispatcher(&mouse_dragged_event3); - RunAllPendingInMessageLoop(); - EXPECT_TRUE(recorder.events().empty()); - host()->dispatcher()->ReleasePointerMoves(); - RunAllPendingInMessageLoop(); - EXPECT_EQ("MOUSE_MOVED", EventTypesToString(recorder.events())); - EXPECT_EQ(gfx::Point(13, 13), recorder.mouse_location(0)); - recorder.Reset(); - root_window()->RemovePreTargetHandler(&recorder); -} - -TEST_F(WindowEventDispatcherTest, TouchMovesHeld) { - EventFilterRecorder recorder; - root_window()->AddPreTargetHandler(&recorder); - - test::TestWindowDelegate delegate; - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - &delegate, 1, gfx::Rect(50, 50, 100, 100), root_window())); - - // Starting the touch and throwing out the first few events, since the system - // is going to generate synthetic mouse events that are not relevant to the - // test. - ui::TouchEvent touch_pressed_event( - ui::ET_TOUCH_PRESSED, gfx::Point(10, 10), 0, ui::EventTimeForNow()); - DispatchEventUsingWindowDispatcher(&touch_pressed_event); - recorder.WaitUntilReceivedEvent(ui::ET_GESTURE_SHOW_PRESS); - recorder.Reset(); - - host()->dispatcher()->HoldPointerMoves(); - - // Check that we don't immediately dispatch the TOUCH_MOVED event. - ui::TouchEvent touch_moved_event( - ui::ET_TOUCH_MOVED, gfx::Point(10, 10), 0, ui::EventTimeForNow()); - ui::TouchEvent touch_moved_event2( - ui::ET_TOUCH_MOVED, gfx::Point(11, 10), 0, ui::EventTimeForNow()); - ui::TouchEvent touch_moved_event3( - ui::ET_TOUCH_MOVED, gfx::Point(12, 10), 0, ui::EventTimeForNow()); - - DispatchEventUsingWindowDispatcher(&touch_moved_event); - EXPECT_TRUE(recorder.events().empty()); - - // Check that on ReleasePointerMoves, held events are not dispatched - // immediately, but posted instead. - DispatchEventUsingWindowDispatcher(&touch_moved_event2); - host()->dispatcher()->ReleasePointerMoves(); - EXPECT_TRUE(recorder.events().empty()); - - RunAllPendingInMessageLoop(); - EXPECT_EQ("TOUCH_MOVED", EventTypesToString(recorder.events())); - recorder.Reset(); - - // If another touch event occurs then the held touch should be dispatched - // immediately before it. - ui::TouchEvent touch_released_event( - ui::ET_TOUCH_RELEASED, gfx::Point(10, 10), 0, ui::EventTimeForNow()); - recorder.Reset(); - host()->dispatcher()->HoldPointerMoves(); - DispatchEventUsingWindowDispatcher(&touch_moved_event3); - DispatchEventUsingWindowDispatcher(&touch_released_event); - EXPECT_EQ("TOUCH_MOVED TOUCH_RELEASED GESTURE_TAP GESTURE_END", - EventTypesToString(recorder.events())); - recorder.Reset(); - host()->dispatcher()->ReleasePointerMoves(); - RunAllPendingInMessageLoop(); - EXPECT_TRUE(recorder.events().empty()); -} - -// Verifies that a direct call to ProcessedTouchEvent() with a -// TOUCH_PRESSED event does not cause a crash. -TEST_F(WindowEventDispatcherTest, CallToProcessedTouchEvent) { - test::TestWindowDelegate delegate; - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - &delegate, 1, gfx::Rect(50, 50, 100, 100), root_window())); - - ui::TouchEvent touch( - ui::ET_TOUCH_PRESSED, gfx::Point(10, 10), 1, ui::EventTimeForNow()); - host()->dispatcher()->ProcessedTouchEvent( - &touch, window.get(), ui::ER_UNHANDLED); -} - -// This event handler requests the dispatcher to start holding pointer-move -// events when it receives the first scroll-update gesture. -class HoldPointerOnScrollHandler : public ui::test::TestEventHandler { - public: - HoldPointerOnScrollHandler(WindowEventDispatcher* dispatcher, - EventFilterRecorder* filter) - : dispatcher_(dispatcher), - filter_(filter), - holding_moves_(false) {} - virtual ~HoldPointerOnScrollHandler() {} - - private: - // ui::test::TestEventHandler: - virtual void OnGestureEvent(ui::GestureEvent* gesture) override { - if (!holding_moves_ && gesture->type() == ui::ET_GESTURE_SCROLL_UPDATE) { - holding_moves_ = true; - dispatcher_->HoldPointerMoves(); - filter_->Reset(); - } else if (gesture->type() == ui::ET_GESTURE_SCROLL_END) { - dispatcher_->ReleasePointerMoves(); - holding_moves_ = false; - } - } - - WindowEventDispatcher* dispatcher_; - EventFilterRecorder* filter_; - bool holding_moves_; - - DISALLOW_COPY_AND_ASSIGN(HoldPointerOnScrollHandler); -}; - -// Tests that touch-move events don't contribute to an in-progress scroll -// gesture if touch-move events are being held by the dispatcher. -TEST_F(WindowEventDispatcherTest, TouchMovesHeldOnScroll) { - EventFilterRecorder recorder; - root_window()->AddPreTargetHandler(&recorder); - test::TestWindowDelegate delegate; - HoldPointerOnScrollHandler handler(host()->dispatcher(), &recorder); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - &delegate, 1, gfx::Rect(50, 50, 100, 100), root_window())); - window->AddPreTargetHandler(&handler); - - ui::test::EventGenerator generator(root_window()); - generator.GestureScrollSequence( - gfx::Point(60, 60), gfx::Point(10, 60), - base::TimeDelta::FromMilliseconds(100), 25); - - // |handler| will have reset |filter| and started holding the touch-move - // events when scrolling started. At the end of the scroll (i.e. upon - // touch-release), the held touch-move event will have been dispatched first, - // along with the subsequent events (i.e. touch-release, scroll-end, and - // gesture-end). - const EventFilterRecorder::Events& events = recorder.events(); - EXPECT_EQ( - "TOUCH_MOVED GESTURE_SCROLL_UPDATE TOUCH_RELEASED " - "GESTURE_SCROLL_END GESTURE_END", - EventTypesToString(events)); - ASSERT_EQ(2u, recorder.touch_locations().size()); - EXPECT_EQ(gfx::Point(-40, 10).ToString(), - recorder.touch_locations()[0].ToString()); - EXPECT_EQ(gfx::Point(-40, 10).ToString(), - recorder.touch_locations()[1].ToString()); -} - -// Tests that a 'held' touch-event does contribute to gesture event when it is -// dispatched. -TEST_F(WindowEventDispatcherTest, HeldTouchMoveContributesToGesture) { - EventFilterRecorder recorder; - root_window()->AddPreTargetHandler(&recorder); - - const gfx::Point location(20, 20); - ui::TouchEvent press( - ui::ET_TOUCH_PRESSED, location, 0, ui::EventTimeForNow()); - DispatchEventUsingWindowDispatcher(&press); - EXPECT_TRUE(recorder.HasReceivedEvent(ui::ET_TOUCH_PRESSED)); - recorder.Reset(); - - host()->dispatcher()->HoldPointerMoves(); - - ui::TouchEvent move(ui::ET_TOUCH_MOVED, - location + gfx::Vector2d(100, 100), - 0, - ui::EventTimeForNow()); - DispatchEventUsingWindowDispatcher(&move); - EXPECT_FALSE(recorder.HasReceivedEvent(ui::ET_TOUCH_MOVED)); - EXPECT_FALSE(recorder.HasReceivedEvent(ui::ET_GESTURE_SCROLL_BEGIN)); - recorder.Reset(); - - host()->dispatcher()->ReleasePointerMoves(); - EXPECT_FALSE(recorder.HasReceivedEvent(ui::ET_TOUCH_MOVED)); - RunAllPendingInMessageLoop(); - EXPECT_TRUE(recorder.HasReceivedEvent(ui::ET_TOUCH_MOVED)); - EXPECT_TRUE(recorder.HasReceivedEvent(ui::ET_GESTURE_SCROLL_BEGIN)); - EXPECT_TRUE(recorder.HasReceivedEvent(ui::ET_GESTURE_SCROLL_UPDATE)); - - root_window()->RemovePreTargetHandler(&recorder); -} - -// Tests that synthetic mouse events are ignored when mouse -// events are disabled. -TEST_F(WindowEventDispatcherTest, DispatchSyntheticMouseEvents) { - EventFilterRecorder recorder; - root_window()->AddPreTargetHandler(&recorder); - - test::TestWindowDelegate delegate; - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - &delegate, 1234, gfx::Rect(5, 5, 100, 100), root_window())); - window->Show(); - window->SetCapture(); - - test::TestCursorClient cursor_client(root_window()); - - // Dispatch a non-synthetic mouse event when mouse events are enabled. - ui::MouseEvent mouse1(ui::ET_MOUSE_MOVED, gfx::Point(10, 10), - gfx::Point(10, 10), 0, 0); - DispatchEventUsingWindowDispatcher(&mouse1); - EXPECT_FALSE(recorder.events().empty()); - recorder.Reset(); - - // Dispatch a synthetic mouse event when mouse events are enabled. - ui::MouseEvent mouse2(ui::ET_MOUSE_MOVED, gfx::Point(10, 10), - gfx::Point(10, 10), ui::EF_IS_SYNTHESIZED, 0); - DispatchEventUsingWindowDispatcher(&mouse2); - EXPECT_FALSE(recorder.events().empty()); - recorder.Reset(); - - // Dispatch a synthetic mouse event when mouse events are disabled. - cursor_client.DisableMouseEvents(); - DispatchEventUsingWindowDispatcher(&mouse2); - EXPECT_TRUE(recorder.events().empty()); - root_window()->RemovePreTargetHandler(&recorder); -} - -// Tests that a mouse-move event is not synthesized when a mouse-button is down. -TEST_F(WindowEventDispatcherTest, DoNotSynthesizeWhileButtonDown) { - EventFilterRecorder recorder; - test::TestWindowDelegate delegate; - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - &delegate, 1234, gfx::Rect(5, 5, 100, 100), root_window())); - window->Show(); - - window->AddPreTargetHandler(&recorder); - // Dispatch a non-synthetic mouse event when mouse events are enabled. - ui::MouseEvent mouse1(ui::ET_MOUSE_PRESSED, gfx::Point(10, 10), - gfx::Point(10, 10), ui::EF_LEFT_MOUSE_BUTTON, - ui::EF_LEFT_MOUSE_BUTTON); - DispatchEventUsingWindowDispatcher(&mouse1); - ASSERT_EQ(1u, recorder.events().size()); - EXPECT_EQ(ui::ET_MOUSE_PRESSED, recorder.events()[0]); - window->RemovePreTargetHandler(&recorder); - recorder.Reset(); - - // Move |window| away from underneath the cursor. - root_window()->AddPreTargetHandler(&recorder); - window->SetBounds(gfx::Rect(30, 30, 100, 100)); - EXPECT_TRUE(recorder.events().empty()); - RunAllPendingInMessageLoop(); - EXPECT_TRUE(recorder.events().empty()); - root_window()->RemovePreTargetHandler(&recorder); -} - -#if defined(OS_WIN) && defined(ARCH_CPU_X86) -#define MAYBE(x) DISABLED_##x -#else -#define MAYBE(x) x -#endif - -// Tests synthetic mouse events generated when window bounds changes such that -// the cursor previously outside the window becomes inside, or vice versa. -// Do not synthesize events if the window ignores events or is invisible. -// Flaky on 32-bit Windows bots. http://crbug.com/388272 -TEST_F(WindowEventDispatcherTest, - MAYBE(SynthesizeMouseEventsOnWindowBoundsChanged)) { - test::TestWindowDelegate delegate; - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - &delegate, 1234, gfx::Rect(5, 5, 100, 100), root_window())); - window->Show(); - window->SetCapture(); - - EventFilterRecorder recorder; - window->AddPreTargetHandler(&recorder); - - // Dispatch a non-synthetic mouse event to place cursor inside window bounds. - ui::MouseEvent mouse(ui::ET_MOUSE_MOVED, gfx::Point(10, 10), - gfx::Point(10, 10), 0, 0); - DispatchEventUsingWindowDispatcher(&mouse); - EXPECT_FALSE(recorder.events().empty()); - recorder.Reset(); - - // Update the window bounds so that cursor is now outside the window. - // This should trigger a synthetic MOVED event. - gfx::Rect bounds1(20, 20, 100, 100); - window->SetBounds(bounds1); - RunAllPendingInMessageLoop(); - ASSERT_FALSE(recorder.events().empty()); - ASSERT_FALSE(recorder.mouse_event_flags().empty()); - EXPECT_EQ(ui::ET_MOUSE_MOVED, recorder.events().back()); - EXPECT_EQ(ui::EF_IS_SYNTHESIZED, recorder.mouse_event_flags().back()); - recorder.Reset(); - - // Set window to ignore events. - window->set_ignore_events(true); - - // Update the window bounds so that cursor is back inside the window. - // This should not trigger a synthetic event. - gfx::Rect bounds2(5, 5, 100, 100); - window->SetBounds(bounds2); - RunAllPendingInMessageLoop(); - EXPECT_TRUE(recorder.events().empty()); - recorder.Reset(); - - // Set window to accept events but invisible. - window->set_ignore_events(false); - window->Hide(); - recorder.Reset(); - - // Update the window bounds so that cursor is outside the window. - // This should not trigger a synthetic event. - window->SetBounds(bounds1); - RunAllPendingInMessageLoop(); - EXPECT_TRUE(recorder.events().empty()); -} - -// Tests that a mouse exit is dispatched to the last known cursor location -// when the cursor becomes invisible. -TEST_F(WindowEventDispatcherTest, DispatchMouseExitWhenCursorHidden) { - EventFilterRecorder recorder; - root_window()->AddPreTargetHandler(&recorder); - - test::TestWindowDelegate delegate; - gfx::Point window_origin(7, 18); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - &delegate, 1234, gfx::Rect(window_origin, gfx::Size(100, 100)), - root_window())); - window->Show(); - - // Dispatch a mouse move event into the window. - gfx::Point mouse_location(gfx::Point(15, 25)); - ui::MouseEvent mouse1(ui::ET_MOUSE_MOVED, mouse_location, - mouse_location, 0, 0); - EXPECT_TRUE(recorder.events().empty()); - DispatchEventUsingWindowDispatcher(&mouse1); - EXPECT_FALSE(recorder.events().empty()); - recorder.Reset(); - - // Hide the cursor and verify a mouse exit was dispatched. - host()->OnCursorVisibilityChanged(false); - EXPECT_FALSE(recorder.events().empty()); - EXPECT_EQ("MOUSE_EXITED", EventTypesToString(recorder.events())); - - // Verify the mouse exit was dispatched at the correct location - // (in the correct coordinate space). - int translated_x = mouse_location.x() - window_origin.x(); - int translated_y = mouse_location.y() - window_origin.y(); - gfx::Point translated_point(translated_x, translated_y); - EXPECT_EQ(recorder.mouse_location(0).ToString(), translated_point.ToString()); - root_window()->RemovePreTargetHandler(&recorder); -} - -// Tests that a synthetic mouse exit is dispatched to the last known cursor -// location after mouse events are disabled on the cursor client. -TEST_F(WindowEventDispatcherTest, - DispatchSyntheticMouseExitAfterMouseEventsDisabled) { - EventFilterRecorder recorder; - root_window()->AddPreTargetHandler(&recorder); - - test::TestWindowDelegate delegate; - gfx::Point window_origin(7, 18); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - &delegate, 1234, gfx::Rect(window_origin, gfx::Size(100, 100)), - root_window())); - window->Show(); - - // Dispatch a mouse move event into the window. - gfx::Point mouse_location(gfx::Point(15, 25)); - ui::MouseEvent mouse1(ui::ET_MOUSE_MOVED, mouse_location, - mouse_location, 0, 0); - EXPECT_TRUE(recorder.events().empty()); - DispatchEventUsingWindowDispatcher(&mouse1); - EXPECT_FALSE(recorder.events().empty()); - recorder.Reset(); - - test::TestCursorClient cursor_client(root_window()); - cursor_client.DisableMouseEvents(); - - gfx::Point mouse_exit_location(gfx::Point(150, 150)); - ui::MouseEvent mouse2(ui::ET_MOUSE_EXITED, gfx::Point(150, 150), - gfx::Point(150, 150), ui::EF_IS_SYNTHESIZED, 0); - DispatchEventUsingWindowDispatcher(&mouse2); - - EXPECT_FALSE(recorder.events().empty()); - // We get the mouse exited event twice in our filter. Once during the - // predispatch phase and during the actual dispatch. - EXPECT_EQ("MOUSE_EXITED MOUSE_EXITED", EventTypesToString(recorder.events())); - - // Verify the mouse exit was dispatched at the correct location - // (in the correct coordinate space). - int translated_x = mouse_exit_location.x() - window_origin.x(); - int translated_y = mouse_exit_location.y() - window_origin.y(); - gfx::Point translated_point(translated_x, translated_y); - EXPECT_EQ(recorder.mouse_location(0).ToString(), translated_point.ToString()); - root_window()->RemovePreTargetHandler(&recorder); -} - -class DeletingEventFilter : public ui::EventHandler { - public: - DeletingEventFilter() - : delete_during_pre_handle_(false) {} - virtual ~DeletingEventFilter() {} - - void Reset(bool delete_during_pre_handle) { - delete_during_pre_handle_ = delete_during_pre_handle; - } - - private: - // Overridden from ui::EventHandler: - virtual void OnKeyEvent(ui::KeyEvent* event) override { - if (delete_during_pre_handle_) - delete event->target(); - } - - virtual void OnMouseEvent(ui::MouseEvent* event) override { - if (delete_during_pre_handle_) - delete event->target(); - } - - bool delete_during_pre_handle_; - - DISALLOW_COPY_AND_ASSIGN(DeletingEventFilter); -}; - -class DeletingWindowDelegate : public test::TestWindowDelegate { - public: - DeletingWindowDelegate() - : window_(NULL), - delete_during_handle_(false), - got_event_(false) {} - virtual ~DeletingWindowDelegate() {} - - void Reset(Window* window, bool delete_during_handle) { - window_ = window; - delete_during_handle_ = delete_during_handle; - got_event_ = false; - } - bool got_event() const { return got_event_; } - - private: - // Overridden from WindowDelegate: - virtual void OnKeyEvent(ui::KeyEvent* event) override { - if (delete_during_handle_) - delete window_; - got_event_ = true; - } - - virtual void OnMouseEvent(ui::MouseEvent* event) override { - if (delete_during_handle_) - delete window_; - got_event_ = true; - } - - Window* window_; - bool delete_during_handle_; - bool got_event_; - - DISALLOW_COPY_AND_ASSIGN(DeletingWindowDelegate); -}; - -TEST_F(WindowEventDispatcherTest, DeleteWindowDuringDispatch) { - // Verifies that we can delete a window during each phase of event handling. - // Deleting the window should not cause a crash, only prevent further - // processing from occurring. - scoped_ptr<Window> w1(CreateNormalWindow(1, root_window(), NULL)); - DeletingWindowDelegate d11; - Window* w11 = CreateNormalWindow(11, w1.get(), &d11); - WindowTracker tracker; - DeletingEventFilter w1_filter; - w1->AddPreTargetHandler(&w1_filter); - client::GetFocusClient(w1.get())->FocusWindow(w11); - - ui::test::EventGenerator generator(root_window(), w11); - - // First up, no one deletes anything. - tracker.Add(w11); - d11.Reset(w11, false); - - generator.PressLeftButton(); - EXPECT_TRUE(tracker.Contains(w11)); - EXPECT_TRUE(d11.got_event()); - generator.ReleaseLeftButton(); - - // Delegate deletes w11. This will prevent the post-handle step from applying. - w1_filter.Reset(false); - d11.Reset(w11, true); - generator.PressKey(ui::VKEY_A, 0); - EXPECT_FALSE(tracker.Contains(w11)); - EXPECT_TRUE(d11.got_event()); - - // Pre-handle step deletes w11. This will prevent the delegate and the post- - // handle steps from applying. - w11 = CreateNormalWindow(11, w1.get(), &d11); - w1_filter.Reset(true); - d11.Reset(w11, false); - generator.PressLeftButton(); - EXPECT_FALSE(tracker.Contains(w11)); - EXPECT_FALSE(d11.got_event()); -} - -namespace { - -// A window delegate that detaches the parent of the target's parent window when -// it receives a tap event. -class DetachesParentOnTapDelegate : public test::TestWindowDelegate { - public: - DetachesParentOnTapDelegate() {} - virtual ~DetachesParentOnTapDelegate() {} - - private: - virtual void OnGestureEvent(ui::GestureEvent* event) override { - if (event->type() == ui::ET_GESTURE_TAP_DOWN) { - event->SetHandled(); - return; - } - - if (event->type() == ui::ET_GESTURE_TAP) { - Window* parent = static_cast<Window*>(event->target())->parent(); - parent->parent()->RemoveChild(parent); - event->SetHandled(); - } - } - - DISALLOW_COPY_AND_ASSIGN(DetachesParentOnTapDelegate); -}; - -} // namespace - -// Tests that the gesture recognizer is reset for all child windows when a -// window hides. No expectations, just checks that the test does not crash. -TEST_F(WindowEventDispatcherTest, - GestureRecognizerResetsTargetWhenParentHides) { - scoped_ptr<Window> w1(CreateNormalWindow(1, root_window(), NULL)); - DetachesParentOnTapDelegate delegate; - scoped_ptr<Window> parent(CreateNormalWindow(22, w1.get(), NULL)); - Window* child = CreateNormalWindow(11, parent.get(), &delegate); - ui::test::EventGenerator generator(root_window(), child); - generator.GestureTapAt(gfx::Point(40, 40)); -} - -namespace { - -// A window delegate that processes nested gestures on tap. -class NestedGestureDelegate : public test::TestWindowDelegate { - public: - NestedGestureDelegate(ui::test::EventGenerator* generator, - const gfx::Point tap_location) - : generator_(generator), - tap_location_(tap_location), - gesture_end_count_(0) {} - virtual ~NestedGestureDelegate() {} - - int gesture_end_count() const { return gesture_end_count_; } - - private: - virtual void OnGestureEvent(ui::GestureEvent* event) override { - switch (event->type()) { - case ui::ET_GESTURE_TAP_DOWN: - event->SetHandled(); - break; - case ui::ET_GESTURE_TAP: - if (generator_) - generator_->GestureTapAt(tap_location_); - event->SetHandled(); - break; - case ui::ET_GESTURE_END: - ++gesture_end_count_; - break; - default: - break; - } - } - - ui::test::EventGenerator* generator_; - const gfx::Point tap_location_; - int gesture_end_count_; - DISALLOW_COPY_AND_ASSIGN(NestedGestureDelegate); -}; - -} // namespace - -// Tests that gesture end is delivered after nested gesture processing. -TEST_F(WindowEventDispatcherTest, GestureEndDeliveredAfterNestedGestures) { - NestedGestureDelegate d1(NULL, gfx::Point()); - scoped_ptr<Window> w1(CreateNormalWindow(1, root_window(), &d1)); - w1->SetBounds(gfx::Rect(0, 0, 100, 100)); - - ui::test::EventGenerator nested_generator(root_window(), w1.get()); - NestedGestureDelegate d2(&nested_generator, w1->bounds().CenterPoint()); - scoped_ptr<Window> w2(CreateNormalWindow(1, root_window(), &d2)); - w2->SetBounds(gfx::Rect(100, 0, 100, 100)); - - // Tap on w2 which triggers nested gestures for w1. - ui::test::EventGenerator generator(root_window(), w2.get()); - generator.GestureTapAt(w2->bounds().CenterPoint()); - - // Both windows should get their gesture end events. - EXPECT_EQ(1, d1.gesture_end_count()); - EXPECT_EQ(1, d2.gesture_end_count()); -} - -// Tests whether we can repost the Tap down gesture event. -TEST_F(WindowEventDispatcherTest, RepostTapdownGestureTest) { - EventFilterRecorder recorder; - root_window()->AddPreTargetHandler(&recorder); - - test::TestWindowDelegate delegate; - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - &delegate, 1, gfx::Rect(0, 0, 100, 100), root_window())); - - ui::GestureEventDetails details(ui::ET_GESTURE_TAP_DOWN); - gfx::Point point(10, 10); - ui::GestureEvent event(point.x(), - point.y(), - 0, - ui::EventTimeForNow(), - details); - host()->dispatcher()->RepostEvent(event); - RunAllPendingInMessageLoop(); - // TODO(rbyers): Currently disabled - crbug.com/170987 - EXPECT_FALSE(EventTypesToString(recorder.events()).find("GESTURE_TAP_DOWN") != - std::string::npos); - recorder.Reset(); - root_window()->RemovePreTargetHandler(&recorder); -} - -// This class inherits from the EventFilterRecorder class which provides a -// facility to record events. This class additionally provides a facility to -// repost the ET_GESTURE_TAP_DOWN gesture to the target window and records -// events after that. -class RepostGestureEventRecorder : public EventFilterRecorder { - public: - RepostGestureEventRecorder(aura::Window* repost_source, - aura::Window* repost_target) - : repost_source_(repost_source), - repost_target_(repost_target), - reposted_(false), - done_cleanup_(false) {} - - virtual ~RepostGestureEventRecorder() {} - - virtual void OnTouchEvent(ui::TouchEvent* event) override { - if (reposted_ && event->type() == ui::ET_TOUCH_PRESSED) { - done_cleanup_ = true; - Reset(); - } - EventFilterRecorder::OnTouchEvent(event); - } - - virtual void OnGestureEvent(ui::GestureEvent* event) override { - EXPECT_EQ(done_cleanup_ ? repost_target_ : repost_source_, event->target()); - if (event->type() == ui::ET_GESTURE_TAP_DOWN) { - if (!reposted_) { - EXPECT_NE(repost_target_, event->target()); - reposted_ = true; - repost_target_->GetHost()->dispatcher()->RepostEvent(*event); - // Ensure that the reposted gesture event above goes to the - // repost_target_; - repost_source_->GetRootWindow()->RemoveChild(repost_source_); - return; - } - } - EventFilterRecorder::OnGestureEvent(event); - } - - // Ignore mouse events as they don't fire at all times. This causes - // the GestureRepostEventOrder test to fail randomly. - virtual void OnMouseEvent(ui::MouseEvent* event) override {} - - private: - aura::Window* repost_source_; - aura::Window* repost_target_; - // set to true if we reposted the ET_GESTURE_TAP_DOWN event. - bool reposted_; - // set true if we're done cleaning up after hiding repost_source_; - bool done_cleanup_; - DISALLOW_COPY_AND_ASSIGN(RepostGestureEventRecorder); -}; - -// Tests whether events which are generated after the reposted gesture event -// are received after that. In this case the scroll sequence events should -// be received after the reposted gesture event. -TEST_F(WindowEventDispatcherTest, GestureRepostEventOrder) { - // Expected events at the end for the repost_target window defined below. - const char kExpectedTargetEvents[] = - // TODO)(rbyers): Gesture event reposting is disabled - crbug.com/279039. - // "GESTURE_BEGIN GESTURE_TAP_DOWN " - "TOUCH_PRESSED GESTURE_BEGIN GESTURE_TAP_DOWN TOUCH_MOVED " - "GESTURE_TAP_CANCEL GESTURE_SCROLL_BEGIN GESTURE_SCROLL_UPDATE TOUCH_MOVED " - "GESTURE_SCROLL_UPDATE TOUCH_MOVED GESTURE_SCROLL_UPDATE TOUCH_RELEASED " - "GESTURE_SCROLL_END GESTURE_END"; - // We create two windows. - // The first window (repost_source) is the one to which the initial tap - // gesture is sent. It reposts this event to the second window - // (repost_target). - // We then generate the scroll sequence for repost_target and look for two - // ET_GESTURE_TAP_DOWN events in the event list at the end. - test::TestWindowDelegate delegate; - scoped_ptr<aura::Window> repost_target(CreateTestWindowWithDelegate( - &delegate, 1, gfx::Rect(0, 0, 100, 100), root_window())); - - scoped_ptr<aura::Window> repost_source(CreateTestWindowWithDelegate( - &delegate, 1, gfx::Rect(0, 0, 50, 50), root_window())); - - RepostGestureEventRecorder repost_event_recorder(repost_source.get(), - repost_target.get()); - root_window()->AddPreTargetHandler(&repost_event_recorder); - - // Generate a tap down gesture for the repost_source. This will be reposted - // to repost_target. - ui::test::EventGenerator repost_generator(root_window(), repost_source.get()); - repost_generator.GestureTapAt(gfx::Point(40, 40)); - RunAllPendingInMessageLoop(); - - ui::test::EventGenerator scroll_generator(root_window(), repost_target.get()); - scroll_generator.GestureScrollSequence( - gfx::Point(80, 80), - gfx::Point(100, 100), - base::TimeDelta::FromMilliseconds(100), - 3); - RunAllPendingInMessageLoop(); - - int tap_down_count = 0; - for (size_t i = 0; i < repost_event_recorder.events().size(); ++i) { - if (repost_event_recorder.events()[i] == ui::ET_GESTURE_TAP_DOWN) - ++tap_down_count; - } - - // We expect two tap down events. One from the repost and the other one from - // the scroll sequence posted above. - // TODO(rbyers): Currently disabled - crbug.com/170987 - EXPECT_EQ(1, tap_down_count); - - EXPECT_EQ(kExpectedTargetEvents, - EventTypesToString(repost_event_recorder.events())); - root_window()->RemovePreTargetHandler(&repost_event_recorder); -} - -class OnMouseExitDeletingEventFilter : public EventFilterRecorder { - public: - OnMouseExitDeletingEventFilter() : window_to_delete_(NULL) {} - virtual ~OnMouseExitDeletingEventFilter() {} - - void set_window_to_delete(Window* window_to_delete) { - window_to_delete_ = window_to_delete; - } - - private: - // Overridden from ui::EventHandler: - virtual void OnMouseEvent(ui::MouseEvent* event) override { - EventFilterRecorder::OnMouseEvent(event); - if (window_to_delete_) { - delete window_to_delete_; - window_to_delete_ = NULL; - } - } - - Window* window_to_delete_; - - DISALLOW_COPY_AND_ASSIGN(OnMouseExitDeletingEventFilter); -}; - -// Tests that RootWindow drops mouse-moved event that is supposed to be sent to -// a child, but the child is destroyed because of the synthesized mouse-exit -// event generated on the previous mouse_moved_handler_. -TEST_F(WindowEventDispatcherTest, DeleteWindowDuringMouseMovedDispatch) { - // Create window 1 and set its event filter. Window 1 will take ownership of - // the event filter. - scoped_ptr<Window> w1(CreateNormalWindow(1, root_window(), NULL)); - OnMouseExitDeletingEventFilter w1_filter; - w1->AddPreTargetHandler(&w1_filter); - w1->SetBounds(gfx::Rect(20, 20, 60, 60)); - EXPECT_EQ(NULL, host()->dispatcher()->mouse_moved_handler()); - - ui::test::EventGenerator generator(root_window(), w1.get()); - - // Move mouse over window 1 to set it as the |mouse_moved_handler_| for the - // root window. - generator.MoveMouseTo(51, 51); - EXPECT_EQ(w1.get(), host()->dispatcher()->mouse_moved_handler()); - - // Create window 2 under the mouse cursor and stack it above window 1. - Window* w2 = CreateNormalWindow(2, root_window(), NULL); - w2->SetBounds(gfx::Rect(30, 30, 40, 40)); - root_window()->StackChildAbove(w2, w1.get()); - - // Set window 2 as the window that is to be deleted when a mouse-exited event - // happens on window 1. - w1_filter.set_window_to_delete(w2); - - // Move mosue over window 2. This should generate a mouse-exited event for - // window 1 resulting in deletion of window 2. The original mouse-moved event - // that was targeted to window 2 should be dropped since window 2 is - // destroyed. This test passes if no crash happens. - generator.MoveMouseTo(52, 52); - EXPECT_EQ(NULL, host()->dispatcher()->mouse_moved_handler()); - - // Check events received by window 1. - EXPECT_EQ("MOUSE_ENTERED MOUSE_MOVED MOUSE_EXITED", - EventTypesToString(w1_filter.events())); -} - -namespace { - -// Used to track if OnWindowDestroying() is invoked and if there is a valid -// RootWindow at such time. -class ValidRootDuringDestructionWindowObserver : public aura::WindowObserver { - public: - ValidRootDuringDestructionWindowObserver(bool* got_destroying, - bool* has_valid_root) - : got_destroying_(got_destroying), - has_valid_root_(has_valid_root) { - } - - // WindowObserver: - virtual void OnWindowDestroying(aura::Window* window) override { - *got_destroying_ = true; - *has_valid_root_ = (window->GetRootWindow() != NULL); - } - - private: - bool* got_destroying_; - bool* has_valid_root_; - - DISALLOW_COPY_AND_ASSIGN(ValidRootDuringDestructionWindowObserver); -}; - -} // namespace - -// Verifies GetRootWindow() from ~Window returns a valid root. -TEST_F(WindowEventDispatcherTest, ValidRootDuringDestruction) { - bool got_destroying = false; - bool has_valid_root = false; - ValidRootDuringDestructionWindowObserver observer(&got_destroying, - &has_valid_root); - { - scoped_ptr<WindowTreeHost> host( - WindowTreeHost::Create(gfx::Rect(0, 0, 100, 100))); - host->InitHost(); - // Owned by WindowEventDispatcher. - Window* w1 = CreateNormalWindow(1, host->window(), NULL); - w1->AddObserver(&observer); - } - EXPECT_TRUE(got_destroying); - EXPECT_TRUE(has_valid_root); -} - -namespace { - -// See description above DontResetHeldEvent for details. -class DontResetHeldEventWindowDelegate : public test::TestWindowDelegate { - public: - explicit DontResetHeldEventWindowDelegate(aura::Window* root) - : root_(root), - mouse_event_count_(0) {} - virtual ~DontResetHeldEventWindowDelegate() {} - - int mouse_event_count() const { return mouse_event_count_; } - - // TestWindowDelegate: - virtual void OnMouseEvent(ui::MouseEvent* event) override { - if ((event->flags() & ui::EF_SHIFT_DOWN) != 0 && - mouse_event_count_++ == 0) { - ui::MouseEvent mouse_event(ui::ET_MOUSE_PRESSED, - gfx::Point(10, 10), gfx::Point(10, 10), - ui::EF_SHIFT_DOWN, 0); - root_->GetHost()->dispatcher()->RepostEvent(mouse_event); - } - } - - private: - Window* root_; - int mouse_event_count_; - - DISALLOW_COPY_AND_ASSIGN(DontResetHeldEventWindowDelegate); -}; - -} // namespace - -// Verifies RootWindow doesn't reset |RootWindow::held_repostable_event_| after -// dispatching. This is done by using DontResetHeldEventWindowDelegate, which -// tracks the number of events with ui::EF_SHIFT_DOWN set (all reposted events -// have EF_SHIFT_DOWN). When the first event is seen RepostEvent() is used to -// schedule another reposted event. -TEST_F(WindowEventDispatcherTest, DontResetHeldEvent) { - DontResetHeldEventWindowDelegate delegate(root_window()); - scoped_ptr<Window> w1(CreateNormalWindow(1, root_window(), &delegate)); - w1->SetBounds(gfx::Rect(0, 0, 40, 40)); - ui::MouseEvent pressed(ui::ET_MOUSE_PRESSED, - gfx::Point(10, 10), gfx::Point(10, 10), - ui::EF_SHIFT_DOWN, 0); - root_window()->GetHost()->dispatcher()->RepostEvent(pressed); - ui::MouseEvent pressed2(ui::ET_MOUSE_PRESSED, - gfx::Point(10, 10), gfx::Point(10, 10), 0, 0); - // Dispatch an event to flush event scheduled by way of RepostEvent(). - DispatchEventUsingWindowDispatcher(&pressed2); - // Delegate should have seen reposted event (identified by way of - // EF_SHIFT_DOWN). Dispatch another event to flush the second - // RepostedEvent(). - EXPECT_EQ(1, delegate.mouse_event_count()); - DispatchEventUsingWindowDispatcher(&pressed2); - EXPECT_EQ(2, delegate.mouse_event_count()); -} - -namespace { - -// See description above DeleteHostFromHeldMouseEvent for details. -class DeleteHostFromHeldMouseEventDelegate - : public test::TestWindowDelegate { - public: - explicit DeleteHostFromHeldMouseEventDelegate(WindowTreeHost* host) - : host_(host), - got_mouse_event_(false), - got_destroy_(false) { - } - virtual ~DeleteHostFromHeldMouseEventDelegate() {} - - bool got_mouse_event() const { return got_mouse_event_; } - bool got_destroy() const { return got_destroy_; } - - // TestWindowDelegate: - virtual void OnMouseEvent(ui::MouseEvent* event) override { - if ((event->flags() & ui::EF_SHIFT_DOWN) != 0) { - got_mouse_event_ = true; - delete host_; - } - } - virtual void OnWindowDestroyed(Window* window) override { - got_destroy_ = true; - } - - private: - WindowTreeHost* host_; - bool got_mouse_event_; - bool got_destroy_; - - DISALLOW_COPY_AND_ASSIGN(DeleteHostFromHeldMouseEventDelegate); -}; - -} // namespace - -// Verifies if a WindowTreeHost is deleted from dispatching a held mouse event -// we don't crash. -TEST_F(WindowEventDispatcherTest, DeleteHostFromHeldMouseEvent) { - // Should be deleted by |delegate|. - WindowTreeHost* h2 = WindowTreeHost::Create(gfx::Rect(0, 0, 100, 100)); - h2->InitHost(); - DeleteHostFromHeldMouseEventDelegate delegate(h2); - // Owned by |h2|. - Window* w1 = CreateNormalWindow(1, h2->window(), &delegate); - w1->SetBounds(gfx::Rect(0, 0, 40, 40)); - ui::MouseEvent pressed(ui::ET_MOUSE_PRESSED, - gfx::Point(10, 10), gfx::Point(10, 10), - ui::EF_SHIFT_DOWN, 0); - h2->dispatcher()->RepostEvent(pressed); - // RunAllPendingInMessageLoop() to make sure the |pressed| is run. - RunAllPendingInMessageLoop(); - EXPECT_TRUE(delegate.got_mouse_event()); - EXPECT_TRUE(delegate.got_destroy()); -} - -TEST_F(WindowEventDispatcherTest, WindowHideCancelsActiveTouches) { - EventFilterRecorder recorder; - root_window()->AddPreTargetHandler(&recorder); - - test::TestWindowDelegate delegate; - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - &delegate, 1, gfx::Rect(0, 0, 100, 100), root_window())); - - gfx::Point position1 = root_window()->bounds().origin(); - ui::TouchEvent press( - ui::ET_TOUCH_PRESSED, position1, 0, ui::EventTimeForNow()); - DispatchEventUsingWindowDispatcher(&press); - - EXPECT_EQ("TOUCH_PRESSED GESTURE_BEGIN GESTURE_TAP_DOWN", - EventTypesToString(recorder.GetAndResetEvents())); - - window->Hide(); - - EXPECT_EQ(ui::ET_TOUCH_CANCELLED, recorder.events()[0]); - EXPECT_TRUE(recorder.HasReceivedEvent(ui::ET_GESTURE_TAP_CANCEL)); - EXPECT_TRUE(recorder.HasReceivedEvent(ui::ET_GESTURE_END)); - EXPECT_EQ(3U, recorder.events().size()); - root_window()->RemovePreTargetHandler(&recorder); -} - -TEST_F(WindowEventDispatcherTest, WindowHideCancelsActiveGestures) { - EventFilterRecorder recorder; - root_window()->AddPreTargetHandler(&recorder); - - test::TestWindowDelegate delegate; - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - &delegate, 1, gfx::Rect(0, 0, 100, 100), root_window())); - - gfx::Point position1 = root_window()->bounds().origin(); - gfx::Point position2 = root_window()->bounds().CenterPoint(); - ui::TouchEvent press( - ui::ET_TOUCH_PRESSED, position1, 0, ui::EventTimeForNow()); - DispatchEventUsingWindowDispatcher(&press); - - ui::TouchEvent move( - ui::ET_TOUCH_MOVED, position2, 0, ui::EventTimeForNow()); - DispatchEventUsingWindowDispatcher(&move); - - ui::TouchEvent press2( - ui::ET_TOUCH_PRESSED, position1, 1, ui::EventTimeForNow()); - DispatchEventUsingWindowDispatcher(&press2); - - // TODO(tdresser): once the unified Gesture Recognizer has stuck, remove the - // special casing here. See crbug.com/332418 for details. - std::string expected = - "TOUCH_PRESSED GESTURE_BEGIN GESTURE_TAP_DOWN TOUCH_MOVED " - "GESTURE_TAP_CANCEL GESTURE_SCROLL_BEGIN GESTURE_SCROLL_UPDATE " - "TOUCH_PRESSED GESTURE_BEGIN GESTURE_PINCH_BEGIN"; - - std::string expected_ugr = - "TOUCH_PRESSED GESTURE_BEGIN GESTURE_TAP_DOWN TOUCH_MOVED " - "GESTURE_TAP_CANCEL GESTURE_SCROLL_BEGIN GESTURE_SCROLL_UPDATE " - "TOUCH_PRESSED GESTURE_BEGIN"; - - std::string events_string = EventTypesToString(recorder.GetAndResetEvents()); - EXPECT_TRUE((expected == events_string) || (expected_ugr == events_string)); - - window->Hide(); - - expected = - "TOUCH_CANCELLED GESTURE_PINCH_END GESTURE_END TOUCH_CANCELLED " - "GESTURE_SCROLL_END GESTURE_END"; - expected_ugr = - "TOUCH_CANCELLED GESTURE_SCROLL_END GESTURE_END TOUCH_CANCELLED " - "GESTURE_END"; - - events_string = EventTypesToString(recorder.GetAndResetEvents()); - EXPECT_TRUE((expected == events_string) || (expected_ugr == events_string)); - - root_window()->RemovePreTargetHandler(&recorder); -} - -// Places two windows side by side. Presses down on one window, and starts a -// scroll. Sets capture on the other window and ensures that the "ending" events -// aren't sent to the window which gained capture. -TEST_F(WindowEventDispatcherTest, EndingEventDoesntRetarget) { - EventFilterRecorder recorder1; - EventFilterRecorder recorder2; - scoped_ptr<Window> window1(CreateNormalWindow(1, root_window(), NULL)); - window1->SetBounds(gfx::Rect(0, 0, 40, 40)); - - scoped_ptr<Window> window2(CreateNormalWindow(2, root_window(), NULL)); - window2->SetBounds(gfx::Rect(40, 0, 40, 40)); - - window1->AddPreTargetHandler(&recorder1); - window2->AddPreTargetHandler(&recorder2); - - gfx::Point position = window1->bounds().origin(); - ui::TouchEvent press( - ui::ET_TOUCH_PRESSED, position, 0, ui::EventTimeForNow()); - DispatchEventUsingWindowDispatcher(&press); - - gfx::Point position2 = window1->bounds().CenterPoint(); - ui::TouchEvent move( - ui::ET_TOUCH_MOVED, position2, 0, ui::EventTimeForNow()); - DispatchEventUsingWindowDispatcher(&move); - - window2->SetCapture(); - - EXPECT_EQ("TOUCH_PRESSED GESTURE_BEGIN GESTURE_TAP_DOWN TOUCH_MOVED " - "GESTURE_TAP_CANCEL GESTURE_SCROLL_BEGIN GESTURE_SCROLL_UPDATE " - "TOUCH_CANCELLED GESTURE_SCROLL_END GESTURE_END", - EventTypesToString(recorder1.events())); - - EXPECT_TRUE(recorder2.events().empty()); -} - -namespace { - -// This class creates and manages a window which is destroyed as soon as -// capture is lost. This is the case for the drag and drop capture window. -class CaptureWindowTracker : public test::TestWindowDelegate { - public: - CaptureWindowTracker() {} - virtual ~CaptureWindowTracker() {} - - void CreateCaptureWindow(aura::Window* root_window) { - capture_window_.reset(test::CreateTestWindowWithDelegate( - this, -1234, gfx::Rect(20, 20, 20, 20), root_window)); - capture_window_->SetCapture(); - } - - void reset() { - capture_window_.reset(); - } - - virtual void OnCaptureLost() override { - capture_window_.reset(); - } - - virtual void OnWindowDestroyed(Window* window) override { - TestWindowDelegate::OnWindowDestroyed(window); - capture_window_.reset(); - } - - aura::Window* capture_window() { return capture_window_.get(); } - - private: - scoped_ptr<aura::Window> capture_window_; - - DISALLOW_COPY_AND_ASSIGN(CaptureWindowTracker); -}; - -} - -// Verifies handling loss of capture by the capture window being hidden. -TEST_F(WindowEventDispatcherTest, CaptureWindowHidden) { - CaptureWindowTracker capture_window_tracker; - capture_window_tracker.CreateCaptureWindow(root_window()); - capture_window_tracker.capture_window()->Hide(); - EXPECT_EQ(NULL, capture_window_tracker.capture_window()); -} - -// Verifies handling loss of capture by the capture window being destroyed. -TEST_F(WindowEventDispatcherTest, CaptureWindowDestroyed) { - CaptureWindowTracker capture_window_tracker; - capture_window_tracker.CreateCaptureWindow(root_window()); - capture_window_tracker.reset(); - EXPECT_EQ(NULL, capture_window_tracker.capture_window()); -} - -class ExitMessageLoopOnMousePress : public ui::test::TestEventHandler { - public: - ExitMessageLoopOnMousePress() {} - virtual ~ExitMessageLoopOnMousePress() {} - - protected: - virtual void OnMouseEvent(ui::MouseEvent* event) override { - ui::test::TestEventHandler::OnMouseEvent(event); - if (event->type() == ui::ET_MOUSE_PRESSED) - base::MessageLoopForUI::current()->Quit(); - } - - private: - DISALLOW_COPY_AND_ASSIGN(ExitMessageLoopOnMousePress); -}; - -class WindowEventDispatcherTestWithMessageLoop - : public WindowEventDispatcherTest { - public: - WindowEventDispatcherTestWithMessageLoop() {} - virtual ~WindowEventDispatcherTestWithMessageLoop() {} - - void RunTest() { - // Reset any event the window may have received when bringing up the window - // (e.g. mouse-move events if the mouse cursor is over the window). - handler_.Reset(); - - // Start a nested message-loop, post an event to be dispatched, and then - // terminate the message-loop. When the message-loop unwinds and gets back, - // the reposted event should not have fired. - scoped_ptr<ui::MouseEvent> mouse(new ui::MouseEvent(ui::ET_MOUSE_PRESSED, - gfx::Point(10, 10), - gfx::Point(10, 10), - ui::EF_NONE, - ui::EF_NONE)); - message_loop()->PostTask( - FROM_HERE, - base::Bind(&WindowEventDispatcherTestWithMessageLoop::RepostEventHelper, - host()->dispatcher(), - base::Passed(&mouse))); - message_loop()->PostTask(FROM_HERE, message_loop()->QuitClosure()); - - base::MessageLoop::ScopedNestableTaskAllower allow(message_loop()); - base::RunLoop loop; - loop.Run(); - EXPECT_EQ(0, handler_.num_mouse_events()); - - // Let the current message-loop run. The event-handler will terminate the - // message-loop when it receives the reposted event. - } - - base::MessageLoop* message_loop() { - return base::MessageLoopForUI::current(); - } - - protected: - virtual void SetUp() override { - WindowEventDispatcherTest::SetUp(); - window_.reset(CreateNormalWindow(1, root_window(), NULL)); - window_->AddPreTargetHandler(&handler_); - } - - virtual void TearDown() override { - window_.reset(); - WindowEventDispatcherTest::TearDown(); - } - - private: - // Used to avoid a copying |event| when binding to a closure. - static void RepostEventHelper(WindowEventDispatcher* dispatcher, - scoped_ptr<ui::MouseEvent> event) { - dispatcher->RepostEvent(*event); - } - - scoped_ptr<Window> window_; - ExitMessageLoopOnMousePress handler_; - - DISALLOW_COPY_AND_ASSIGN(WindowEventDispatcherTestWithMessageLoop); -}; - -TEST_F(WindowEventDispatcherTestWithMessageLoop, EventRepostedInNonNestedLoop) { - CHECK(!message_loop()->is_running()); - // Perform the test in a callback, so that it runs after the message-loop - // starts. - message_loop()->PostTask( - FROM_HERE, base::Bind( - &WindowEventDispatcherTestWithMessageLoop::RunTest, - base::Unretained(this))); - message_loop()->Run(); -} - -class WindowEventDispatcherTestInHighDPI : public WindowEventDispatcherTest { - public: - WindowEventDispatcherTestInHighDPI() {} - virtual ~WindowEventDispatcherTestInHighDPI() {} - - protected: - virtual void SetUp() override { - WindowEventDispatcherTest::SetUp(); - test_screen()->SetDeviceScaleFactor(2.f); - } -}; - -TEST_F(WindowEventDispatcherTestInHighDPI, EventLocationTransform) { - test::TestWindowDelegate delegate; - scoped_ptr<aura::Window> child(test::CreateTestWindowWithDelegate(&delegate, - 1234, gfx::Rect(20, 20, 100, 100), root_window())); - child->Show(); - - ui::test::TestEventHandler handler_child; - ui::test::TestEventHandler handler_root; - root_window()->AddPreTargetHandler(&handler_root); - child->AddPreTargetHandler(&handler_child); - - { - ui::MouseEvent move(ui::ET_MOUSE_MOVED, - gfx::Point(30, 30), gfx::Point(30, 30), - ui::EF_NONE, ui::EF_NONE); - DispatchEventUsingWindowDispatcher(&move); - EXPECT_EQ(0, handler_child.num_mouse_events()); - EXPECT_EQ(1, handler_root.num_mouse_events()); - } - - { - ui::MouseEvent move(ui::ET_MOUSE_MOVED, - gfx::Point(50, 50), gfx::Point(50, 50), - ui::EF_NONE, ui::EF_NONE); - DispatchEventUsingWindowDispatcher(&move); - // The child receives an ENTER, and a MOVED event. - EXPECT_EQ(2, handler_child.num_mouse_events()); - // The root receives both the ENTER and the MOVED events dispatched to - // |child|, as well as an EXIT event. - EXPECT_EQ(3, handler_root.num_mouse_events()); - } - - child->RemovePreTargetHandler(&handler_child); - root_window()->RemovePreTargetHandler(&handler_root); -} - -TEST_F(WindowEventDispatcherTestInHighDPI, TouchMovesHeldOnScroll) { - EventFilterRecorder recorder; - root_window()->AddPreTargetHandler(&recorder); - test::TestWindowDelegate delegate; - HoldPointerOnScrollHandler handler(host()->dispatcher(), &recorder); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - &delegate, 1, gfx::Rect(50, 50, 100, 100), root_window())); - window->AddPreTargetHandler(&handler); - - ui::test::EventGenerator generator(root_window()); - generator.GestureScrollSequence( - gfx::Point(120, 120), gfx::Point(20, 120), - base::TimeDelta::FromMilliseconds(100), 25); - - // |handler| will have reset |filter| and started holding the touch-move - // events when scrolling started. At the end of the scroll (i.e. upon - // touch-release), the held touch-move event will have been dispatched first, - // along with the subsequent events (i.e. touch-release, scroll-end, and - // gesture-end). - const EventFilterRecorder::Events& events = recorder.events(); - EXPECT_EQ( - "TOUCH_MOVED GESTURE_SCROLL_UPDATE TOUCH_RELEASED " - "GESTURE_SCROLL_END GESTURE_END", - EventTypesToString(events)); - ASSERT_EQ(2u, recorder.touch_locations().size()); - EXPECT_EQ(gfx::Point(-40, 10).ToString(), - recorder.touch_locations()[0].ToString()); - EXPECT_EQ(gfx::Point(-40, 10).ToString(), - recorder.touch_locations()[1].ToString()); -} - -class SelfDestructDelegate : public test::TestWindowDelegate { - public: - SelfDestructDelegate() {} - virtual ~SelfDestructDelegate() {} - - virtual void OnMouseEvent(ui::MouseEvent* event) override { - window_.reset(); - } - - void set_window(scoped_ptr<aura::Window> window) { - window_ = window.Pass(); - } - bool has_window() const { return !!window_.get(); } - - private: - scoped_ptr<aura::Window> window_; - DISALLOW_COPY_AND_ASSIGN(SelfDestructDelegate); -}; - -TEST_F(WindowEventDispatcherTest, SynthesizedLocatedEvent) { - ui::test::EventGenerator generator(root_window()); - generator.MoveMouseTo(10, 10); - EXPECT_EQ("10,10", - Env::GetInstance()->last_mouse_location().ToString()); - - // Synthesized event should not update the mouse location. - ui::MouseEvent mouseev(ui::ET_MOUSE_MOVED, gfx::Point(), gfx::Point(), - ui::EF_IS_SYNTHESIZED, 0); - generator.Dispatch(&mouseev); - EXPECT_EQ("10,10", - Env::GetInstance()->last_mouse_location().ToString()); - - generator.MoveMouseTo(0, 0); - EXPECT_EQ("0,0", - Env::GetInstance()->last_mouse_location().ToString()); - - // Make sure the location gets updated when a syntheiszed enter - // event destroyed the window. - SelfDestructDelegate delegate; - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - &delegate, 1, gfx::Rect(50, 50, 100, 100), root_window())); - delegate.set_window(window.Pass()); - EXPECT_TRUE(delegate.has_window()); - - generator.MoveMouseTo(100, 100); - EXPECT_FALSE(delegate.has_window()); - EXPECT_EQ("100,100", - Env::GetInstance()->last_mouse_location().ToString()); -} - -class StaticFocusClient : public client::FocusClient { - public: - explicit StaticFocusClient(Window* focused) - : focused_(focused) {} - virtual ~StaticFocusClient() {} - - private: - // client::FocusClient: - virtual void AddObserver(client::FocusChangeObserver* observer) override {} - virtual void RemoveObserver(client::FocusChangeObserver* observer) override {} - virtual void FocusWindow(Window* window) override {} - virtual void ResetFocusWithinActiveWindow(Window* window) override {} - virtual Window* GetFocusedWindow() override { return focused_; } - - Window* focused_; - - DISALLOW_COPY_AND_ASSIGN(StaticFocusClient); -}; - -// Tests that host-cancel-mode event can be dispatched to a dispatcher safely -// when the focused window does not live in the dispatcher's tree. -TEST_F(WindowEventDispatcherTest, HostCancelModeWithFocusedWindowOutside) { - test::TestWindowDelegate delegate; - scoped_ptr<Window> focused(CreateTestWindowWithDelegate(&delegate, 123, - gfx::Rect(20, 30, 100, 50), NULL)); - StaticFocusClient focus_client(focused.get()); - client::SetFocusClient(root_window(), &focus_client); - EXPECT_FALSE(root_window()->Contains(focused.get())); - EXPECT_EQ(focused.get(), - client::GetFocusClient(root_window())->GetFocusedWindow()); - host()->dispatcher()->DispatchCancelModeEvent(); - EXPECT_EQ(focused.get(), - client::GetFocusClient(root_window())->GetFocusedWindow()); -} - -// Dispatches a mouse-move event to |target| when it receives a mouse-move -// event. -class DispatchEventHandler : public ui::EventHandler { - public: - explicit DispatchEventHandler(Window* target) - : target_(target), - dispatched_(false) {} - virtual ~DispatchEventHandler() {} - - bool dispatched() const { return dispatched_; } - private: - // ui::EventHandler: - virtual void OnMouseEvent(ui::MouseEvent* mouse) override { - if (mouse->type() == ui::ET_MOUSE_MOVED) { - ui::MouseEvent move(ui::ET_MOUSE_MOVED, target_->bounds().CenterPoint(), - target_->bounds().CenterPoint(), ui::EF_NONE, ui::EF_NONE); - ui::EventDispatchDetails details = - target_->GetHost()->dispatcher()->OnEventFromSource(&move); - ASSERT_FALSE(details.dispatcher_destroyed); - EXPECT_FALSE(details.target_destroyed); - EXPECT_EQ(target_, move.target()); - dispatched_ = true; - } - ui::EventHandler::OnMouseEvent(mouse); - } - - Window* target_; - bool dispatched_; - - DISALLOW_COPY_AND_ASSIGN(DispatchEventHandler); -}; - -// Moves |window| to |root_window| when it receives a mouse-move event. -class MoveWindowHandler : public ui::EventHandler { - public: - MoveWindowHandler(Window* window, Window* root_window) - : window_to_move_(window), - root_window_to_move_to_(root_window) {} - virtual ~MoveWindowHandler() {} - - private: - // ui::EventHandler: - virtual void OnMouseEvent(ui::MouseEvent* mouse) override { - if (mouse->type() == ui::ET_MOUSE_MOVED) { - root_window_to_move_to_->AddChild(window_to_move_); - } - ui::EventHandler::OnMouseEvent(mouse); - } - - Window* window_to_move_; - Window* root_window_to_move_to_; - - DISALLOW_COPY_AND_ASSIGN(MoveWindowHandler); -}; - -// Tests that nested event dispatch works correctly if the target of the older -// event being dispatched is moved to a different dispatcher in response to an -// event in the inner loop. -TEST_F(WindowEventDispatcherTest, NestedEventDispatchTargetMoved) { - scoped_ptr<WindowTreeHost> second_host( - WindowTreeHost::Create(gfx::Rect(20, 30, 100, 50))); - second_host->InitHost(); - Window* second_root = second_host->window(); - - // Create two windows parented to |root_window()|. - test::TestWindowDelegate delegate; - scoped_ptr<Window> first(CreateTestWindowWithDelegate(&delegate, 123, - gfx::Rect(20, 10, 10, 20), root_window())); - scoped_ptr<Window> second(CreateTestWindowWithDelegate(&delegate, 234, - gfx::Rect(40, 10, 50, 20), root_window())); - - // Setup a handler on |first| so that it dispatches an event to |second| when - // |first| receives an event. - DispatchEventHandler dispatch_event(second.get()); - first->AddPreTargetHandler(&dispatch_event); - - // Setup a handler on |second| so that it moves |first| into |second_root| - // when |second| receives an event. - MoveWindowHandler move_window(first.get(), second_root); - second->AddPreTargetHandler(&move_window); - - // Some sanity checks: |first| is inside |root_window()|'s tree. - EXPECT_EQ(root_window(), first->GetRootWindow()); - // The two root windows are different. - EXPECT_NE(root_window(), second_root); - - // Dispatch an event to |first|. - ui::MouseEvent move(ui::ET_MOUSE_MOVED, first->bounds().CenterPoint(), - first->bounds().CenterPoint(), ui::EF_NONE, ui::EF_NONE); - ui::EventDispatchDetails details = - host()->dispatcher()->OnEventFromSource(&move); - ASSERT_FALSE(details.dispatcher_destroyed); - EXPECT_TRUE(details.target_destroyed); - EXPECT_EQ(first.get(), move.target()); - EXPECT_TRUE(dispatch_event.dispatched()); - EXPECT_EQ(second_root, first->GetRootWindow()); - - first->RemovePreTargetHandler(&dispatch_event); - second->RemovePreTargetHandler(&move_window); -} - -class AlwaysMouseDownInputStateLookup : public InputStateLookup { - public: - AlwaysMouseDownInputStateLookup() {} - virtual ~AlwaysMouseDownInputStateLookup() {} - - private: - // InputStateLookup: - virtual bool IsMouseButtonDown() const override { return true; } - - DISALLOW_COPY_AND_ASSIGN(AlwaysMouseDownInputStateLookup); -}; - -TEST_F(WindowEventDispatcherTest, - CursorVisibilityChangedWhileCaptureWindowInAnotherDispatcher) { - test::EventCountDelegate delegate; - scoped_ptr<Window> window(CreateTestWindowWithDelegate(&delegate, 123, - gfx::Rect(20, 10, 10, 20), root_window())); - window->Show(); - - scoped_ptr<WindowTreeHost> second_host( - WindowTreeHost::Create(gfx::Rect(20, 30, 100, 50))); - second_host->InitHost(); - WindowEventDispatcher* second_dispatcher = second_host->dispatcher(); - - // Install an InputStateLookup on the Env that always claims that a - // mouse-button is down. - test::EnvTestHelper(Env::GetInstance()).SetInputStateLookup( - scoped_ptr<InputStateLookup>(new AlwaysMouseDownInputStateLookup())); - - window->SetCapture(); - - // Because the mouse button is down, setting the capture on |window| will set - // it as the mouse-move handler for |root_window()|. - EXPECT_EQ(window.get(), host()->dispatcher()->mouse_moved_handler()); - - // This does not set |window| as the mouse-move handler for the second - // dispatcher. - EXPECT_EQ(NULL, second_dispatcher->mouse_moved_handler()); - - // However, some capture-client updates the capture in each root-window on a - // capture. Emulate that here. Because of this, the second dispatcher also has - // |window| as the mouse-move handler. - client::CaptureDelegate* second_capture_delegate = second_dispatcher; - second_capture_delegate->UpdateCapture(NULL, window.get()); - EXPECT_EQ(window.get(), second_dispatcher->mouse_moved_handler()); - - // Reset the mouse-event counts for |window|. - delegate.GetMouseMotionCountsAndReset(); - - // Notify both hosts that the cursor is now hidden. This should send a single - // mouse-exit event to |window|. - host()->OnCursorVisibilityChanged(false); - second_host->OnCursorVisibilityChanged(false); - EXPECT_EQ("0 0 1", delegate.GetMouseMotionCountsAndReset()); -} - -TEST_F(WindowEventDispatcherTest, - RedirectedEventToDifferentDispatcherLocation) { - scoped_ptr<WindowTreeHost> second_host( - WindowTreeHost::Create(gfx::Rect(20, 30, 100, 50))); - second_host->InitHost(); - client::SetCaptureClient(second_host->window(), - client::GetCaptureClient(root_window())); - - test::EventCountDelegate delegate; - scoped_ptr<Window> window_first(CreateTestWindowWithDelegate(&delegate, 123, - gfx::Rect(20, 10, 10, 20), root_window())); - window_first->Show(); - - scoped_ptr<Window> window_second(CreateTestWindowWithDelegate(&delegate, 12, - gfx::Rect(10, 10, 20, 30), second_host->window())); - window_second->Show(); - - window_second->SetCapture(); - EXPECT_EQ(window_second.get(), - client::GetCaptureWindow(root_window())); - - // Send an event to the first host. Make sure it goes to |window_second| in - // |second_host| instead (since it has capture). - EventFilterRecorder recorder_first; - window_first->AddPreTargetHandler(&recorder_first); - EventFilterRecorder recorder_second; - window_second->AddPreTargetHandler(&recorder_second); - const gfx::Point event_location(25, 15); - ui::MouseEvent mouse(ui::ET_MOUSE_PRESSED, event_location, - event_location, ui::EF_LEFT_MOUSE_BUTTON, - ui::EF_LEFT_MOUSE_BUTTON); - DispatchEventUsingWindowDispatcher(&mouse); - EXPECT_TRUE(recorder_first.events().empty()); - ASSERT_EQ(1u, recorder_second.events().size()); - EXPECT_EQ(ui::ET_MOUSE_PRESSED, recorder_second.events()[0]); - EXPECT_EQ(event_location.ToString(), - recorder_second.mouse_locations()[0].ToString()); -} - -class AsyncWindowDelegate : public test::TestWindowDelegate { - public: - AsyncWindowDelegate(WindowEventDispatcher* dispatcher) - : dispatcher_(dispatcher) {} - - void set_window(Window* window) { - window_ = window; - } - private: - virtual void OnTouchEvent(ui::TouchEvent* event) override { - // Convert touch event back to root window coordinates. - event->ConvertLocationToTarget(window_, window_->GetRootWindow()); - dispatcher_->ProcessedTouchEvent(event, window_, ui::ER_UNHANDLED); - event->StopPropagation(); - } - - WindowEventDispatcher* dispatcher_; - Window* window_; - - DISALLOW_COPY_AND_ASSIGN(AsyncWindowDelegate); -}; - -// Tests that gesture events dispatched through the asynchronous flow have -// co-ordinates in the right co-ordinate space. -TEST_F(WindowEventDispatcherTest, GestureEventCoordinates) { - const float kX = 67.3f; - const float kY = 97.8f; - - const int kWindowOffset = 50; - EventFilterRecorder recorder; - root_window()->AddPreTargetHandler(&recorder); - AsyncWindowDelegate delegate(host()->dispatcher()); - HoldPointerOnScrollHandler handler(host()->dispatcher(), &recorder); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate( - &delegate, - 1, - gfx::Rect(kWindowOffset, kWindowOffset, 100, 100), - root_window())); - window->AddPreTargetHandler(&handler); - - delegate.set_window(window.get()); - - ui::TouchEvent touch_pressed_event( - ui::ET_TOUCH_PRESSED, gfx::PointF(kX, kY), 0, ui::EventTimeForNow()); - - DispatchEventUsingWindowDispatcher(&touch_pressed_event); - - ASSERT_EQ(1u, recorder.touch_locations().size()); - EXPECT_EQ(gfx::Point(kX - kWindowOffset, kY - kWindowOffset).ToString(), - recorder.touch_locations()[0].ToString()); - - ASSERT_EQ(2u, recorder.gesture_locations().size()); - EXPECT_EQ(gfx::Point(kX - kWindowOffset, kY - kWindowOffset).ToString(), - recorder.gesture_locations()[0].ToString()); -} - -} // namespace aura
diff --git a/ui/aura/window_layer_type.h b/ui/aura/window_layer_type.h deleted file mode 100644 index 97e312a..0000000 --- a/ui/aura/window_layer_type.h +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_WINDOW_LAYER_TYPE_H_ -#define UI_AURA_WINDOW_LAYER_TYPE_H_ - -namespace aura { - -// These constants mirror that of ui::LayerType with the addition of -// WINDOW_LAYER_NONE. See ui::LayerType for description of ones in common. -enum WindowLayerType { - // Note that Windows with WINDOW_LAYER_NONE impose limitations on the - // Window: transforms and animations aren't supported. - WINDOW_LAYER_NONE, - - WINDOW_LAYER_NOT_DRAWN, - WINDOW_LAYER_TEXTURED, - WINDOW_LAYER_SOLID_COLOR, -}; - -} // namespace aura - -#endif // UI_AURA_WINDOW_LAYER_TYPE_H_
diff --git a/ui/aura/window_observer.cc b/ui/aura/window_observer.cc deleted file mode 100644 index 24d51d4..0000000 --- a/ui/aura/window_observer.cc +++ /dev/null
@@ -1,31 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/window_observer.h" - -#include "base/logging.h" -#include "ui/aura/window.h" - -namespace aura { - -WindowObserver::WindowObserver() : observing_(0) { -} - -WindowObserver::~WindowObserver() { - // TODO(flackr): Remove this check and observing_ counter when the cause of - // http://crbug.com/365364 is discovered. - CHECK_EQ(0, observing_); -} - -void WindowObserver::OnObservingWindow(aura::Window* window) { - if (!window->HasObserver(this)) - observing_++; -} - -void WindowObserver::OnUnobservingWindow(aura::Window* window) { - if (window->HasObserver(this)) - observing_--; -} - -} // namespace aura
diff --git a/ui/aura/window_observer.h b/ui/aura/window_observer.h deleted file mode 100644 index f4e7237..0000000 --- a/ui/aura/window_observer.h +++ /dev/null
@@ -1,144 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_WINDOW_OBSERVER_H_ -#define UI_AURA_WINDOW_OBSERVER_H_ - -#include "base/basictypes.h" -#include "base/strings/string16.h" -#include "ui/aura/aura_export.h" - -namespace gfx { -class Rect; -} // namespace gfx - -namespace aura { - -class Window; - -class AURA_EXPORT WindowObserver { - public: - struct HierarchyChangeParams { - enum HierarchyChangePhase { - HIERARCHY_CHANGING, - HIERARCHY_CHANGED - }; - - Window* target; // The window that was added or removed. - Window* new_parent; - Window* old_parent; - HierarchyChangePhase phase; - Window* receiver; // The window receiving the notification. - }; - - WindowObserver(); - - // Called when a window is added or removed. Notifications are sent to the - // following hierarchies in this order: - // 1. |target|. - // 2. |target|'s child hierarchy. - // 3. |target|'s parent hierarchy in its |old_parent| - // (only for Changing notifications). - // 3. |target|'s parent hierarchy in its |new_parent|. - // (only for Changed notifications). - // This sequence is performed via the Changing and Changed notifications below - // before and after the change is committed. - virtual void OnWindowHierarchyChanging(const HierarchyChangeParams& params) {} - virtual void OnWindowHierarchyChanged(const HierarchyChangeParams& params) {} - - // Invoked when |new_window| has been added as a child of this window. - virtual void OnWindowAdded(Window* new_window) {} - - // Invoked prior to removing |window| as a child of this window. - virtual void OnWillRemoveWindow(Window* window) {} - - // Invoked when this window's parent window changes. |parent| may be NULL. - virtual void OnWindowParentChanged(Window* window, Window* parent) {} - - // Invoked when SetProperty(), ClearProperty(), or - // NativeWidgetAura::SetNativeWindowProperty() is called on the window. - // |key| is either a WindowProperty<T>* (SetProperty, ClearProperty) - // or a const char* (SetNativeWindowProperty). Either way, it can simply be - // compared for equality with the property constant. |old| is the old property - // value, which must be cast to the appropriate type before use. - virtual void OnWindowPropertyChanged(Window* window, - const void* key, - intptr_t old) {} - - // Invoked when SetVisible() is invoked on a window. |visible| is the - // value supplied to SetVisible(). If |visible| is true, window->IsVisible() - // may still return false. See description in Window::IsVisible() for details. - virtual void OnWindowVisibilityChanging(Window* window, bool visible) {} - virtual void OnWindowVisibilityChanged(Window* window, bool visible) {} - - // Invoked when SetBounds() is invoked on |window|. |old_bounds| and - // |new_bounds| are in parent coordinates. - virtual void OnWindowBoundsChanged(Window* window, - const gfx::Rect& old_bounds, - const gfx::Rect& new_bounds) {} - - // Invoked when SetTransform() is invoked on |window|. - virtual void OnWindowTransforming(Window* window) {} - virtual void OnWindowTransformed(Window* window) {} - - // Invoked when SetTransform() is invoked on an ancestor of the window being - // observed (including the window itself). - virtual void OnAncestorWindowTransformed(Window* source, Window* window) {} - - // Invoked when |window|'s position among its siblings in the stacking order - // has changed. - virtual void OnWindowStackingChanged(Window* window) {} - - // Invoked when a region of |window| has damage from a new delegated frame. - virtual void OnDelegatedFrameDamage(Window* window, - const gfx::Rect& damage_rect_in_dip) {} - - // Invoked when the Window is being destroyed (i.e. from the start of its - // destructor). This is called before the window is removed from its parent. - virtual void OnWindowDestroying(Window* window) {} - - // Invoked when the Window has been destroyed (i.e. at the end of - // its destructor). This is called after the window is removed from - // its parent. Window automatically removes its WindowObservers - // before calling this method, so the following code is no op. - // - // void MyWindowObserver::OnWindowDestroyed(aura::Window* window) { - // window->RemoveObserver(this); - // } - virtual void OnWindowDestroyed(Window* window) {} - - // Called when a Window has been added to a RootWindow. - virtual void OnWindowAddedToRootWindow(Window* window) {} - - // Called when a Window is about to be removed from a root Window. - // |new_root| contains the new root Window if it is being added to one - // atomically. - virtual void OnWindowRemovingFromRootWindow(Window* window, - Window* new_root) {} - - // Called when the window title has changed. - virtual void OnWindowTitleChanged(Window* window) {} - - protected: - virtual ~WindowObserver(); - - private: - friend class Window; - - // Called when this is added as an observer on |window|. - void OnObservingWindow(Window* window); - - // Called when this is removed from the observers on |window|. - void OnUnobservingWindow(Window* window); - - // Tracks the number of windows being observed to track down - // http://crbug.com/365364. - int observing_; - - DISALLOW_COPY_AND_ASSIGN(WindowObserver); -}; - -} // namespace aura - -#endif // UI_AURA_WINDOW_OBSERVER_H_
diff --git a/ui/aura/window_property.h b/ui/aura/window_property.h deleted file mode 100644 index 0b1574e..0000000 --- a/ui/aura/window_property.h +++ /dev/null
@@ -1,144 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_WINDOW_PROPERTY_H_ -#define UI_AURA_WINDOW_PROPERTY_H_ - -#include "base/basictypes.h" -#include "ui/aura/aura_export.h" -#include "ui/aura/window.h" - -// This header should be included by code that defines WindowProperties. It -// should not be included by code that only gets and sets WindowProperties. -// -// To define a new WindowProperty: -// -// #include "foo/foo_export.h" -// #include "ui/aura/window_property.h" -// -// DECLARE_EXPORTED_WINDOW_PROPERTY_TYPE(FOO_EXPORT, MyType); -// namespace foo { -// // Use this to define an exported property that is premitive, -// // or a pointer you don't want automatically deleted. -// DEFINE_WINDOW_PROPERTY_KEY(MyType, kMyKey, MyDefault); -// -// // Use this to define an exported property whose value is a heap -// // allocated object, and has to be owned and freed by the window. -// DEFINE_OWNED_WINDOW_PROPERTY_KEY(gfx::Rect, kRestoreBoundsKey, NULL); -// -// // Use this to define a non exported property that is primitive, -// // or a pointer you don't want to automatically deleted, and is used -// // only in a specific file. This will define the property in an unnamed -// // namespace which cannot be accessed from another file. -// DEFINE_LOCAL_WINDOW_PROPERTY_KEY(MyType, kMyKey, MyDefault); -// -// } // foo namespace -// -// To define a new type used for WindowProperty. -// -// // outside all namespaces: -// DECLARE_EXPORTED_WINDOW_PROPERTY_TYPE(FOO_EXPORT, MyType) -// -// If a property type is not exported, use DECLARE_WINDOW_PROPERTY_TYPE(MyType) -// which is a shorthand for DECLARE_EXPORTED_WINDOW_PROPERTY_TYPE(, MyType). - -namespace aura { -namespace { - -// No single new-style cast works for every conversion to/from int64, so we -// need this helper class. A third specialization is needed for bool because -// MSVC warning C4800 (forcing value to bool) is not suppressed by an explicit -// cast (!). -template<typename T> -class WindowPropertyCaster { - public: - static int64 ToInt64(T x) { return static_cast<int64>(x); } - static T FromInt64(int64 x) { return static_cast<T>(x); } -}; -template<typename T> -class WindowPropertyCaster<T*> { - public: - static int64 ToInt64(T* x) { return reinterpret_cast<int64>(x); } - static T* FromInt64(int64 x) { return reinterpret_cast<T*>(x); } -}; -template<> -class WindowPropertyCaster<bool> { - public: - static int64 ToInt64(bool x) { return static_cast<int64>(x); } - static bool FromInt64(int64 x) { return x != 0; } -}; - -} // namespace - -template<typename T> -struct WindowProperty { - T default_value; - const char* name; - Window::PropertyDeallocator deallocator; -}; - -template<typename T> -void Window::SetProperty(const WindowProperty<T>* property, T value) { - int64 old = SetPropertyInternal( - property, - property->name, - value == property->default_value ? NULL : property->deallocator, - WindowPropertyCaster<T>::ToInt64(value), - WindowPropertyCaster<T>::ToInt64(property->default_value)); - if (property->deallocator && - old != WindowPropertyCaster<T>::ToInt64(property->default_value)) { - (*property->deallocator)(old); - } -} - -template<typename T> -T Window::GetProperty(const WindowProperty<T>* property) const { - return WindowPropertyCaster<T>::FromInt64(GetPropertyInternal( - property, WindowPropertyCaster<T>::ToInt64(property->default_value))); -} - -template<typename T> -void Window::ClearProperty(const WindowProperty<T>* property) { - SetProperty(property, property->default_value); -} - -} // namespace aura - -// Macros to instantiate the property getter/setter template functions. -#define DECLARE_EXPORTED_WINDOW_PROPERTY_TYPE(EXPORT, T) \ - template EXPORT void aura::Window::SetProperty( \ - const aura::WindowProperty<T >*, T); \ - template EXPORT T aura::Window::GetProperty( \ - const aura::WindowProperty<T >*) const; \ - template EXPORT void aura::Window::ClearProperty( \ - const aura::WindowProperty<T >*); -#define DECLARE_WINDOW_PROPERTY_TYPE(T) \ - DECLARE_EXPORTED_WINDOW_PROPERTY_TYPE(, T) - -#define DEFINE_WINDOW_PROPERTY_KEY(TYPE, NAME, DEFAULT) \ - COMPILE_ASSERT(sizeof(TYPE) <= sizeof(int64), property_type_too_large); \ - namespace { \ - const aura::WindowProperty<TYPE> NAME ## _Value = {DEFAULT, #NAME, NULL}; \ - } \ - const aura::WindowProperty<TYPE>* const NAME = & NAME ## _Value; - -#define DEFINE_LOCAL_WINDOW_PROPERTY_KEY(TYPE, NAME, DEFAULT) \ - COMPILE_ASSERT(sizeof(TYPE) <= sizeof(int64), property_type_too_large); \ - namespace { \ - const aura::WindowProperty<TYPE> NAME ## _Value = {DEFAULT, #NAME, NULL}; \ - const aura::WindowProperty<TYPE>* const NAME = & NAME ## _Value; \ - } - -#define DEFINE_OWNED_WINDOW_PROPERTY_KEY(TYPE, NAME, DEFAULT) \ - namespace { \ - void Deallocator ## NAME (int64 p) { \ - enum { type_must_be_complete = sizeof(TYPE) }; \ - delete aura::WindowPropertyCaster<TYPE*>::FromInt64(p); \ - } \ - const aura::WindowProperty<TYPE*> NAME ## _Value = \ - {DEFAULT,#NAME,&Deallocator ## NAME}; \ - } \ - const aura::WindowProperty<TYPE*>* const NAME = & NAME ## _Value; - -#endif // UI_AURA_WINDOW_PROPERTY_H_
diff --git a/ui/aura/window_targeter.cc b/ui/aura/window_targeter.cc deleted file mode 100644 index 7303e22..0000000 --- a/ui/aura/window_targeter.cc +++ /dev/null
@@ -1,159 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/window_targeter.h" - -#include "ui/aura/client/capture_client.h" -#include "ui/aura/client/event_client.h" -#include "ui/aura/client/focus_client.h" -#include "ui/aura/window.h" -#include "ui/aura/window_delegate.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/aura/window_tree_host.h" -#include "ui/events/event_target.h" - -namespace aura { - -namespace { - -bool IsLocatedEvent(const ui::Event& event) { - return event.IsMouseEvent() || event.IsTouchEvent() || - event.IsScrollEvent() || event.IsGestureEvent(); -} - -} // namespace - -WindowTargeter::WindowTargeter() {} -WindowTargeter::~WindowTargeter() {} - -ui::EventTarget* WindowTargeter::FindTargetForEvent(ui::EventTarget* root, - ui::Event* event) { - Window* window = static_cast<Window*>(root); - Window* target = event->IsKeyEvent() ? - FindTargetForKeyEvent(window, *static_cast<ui::KeyEvent*>(event)) : - static_cast<Window*>(EventTargeter::FindTargetForEvent(root, event)); - if (target && !window->parent() && !window->Contains(target)) { - // |window| is the root window, but |target| is not a descendent of - // |window|. So do not allow dispatching from here. Instead, dispatch the - // event through the WindowEventDispatcher that owns |target|. - aura::Window* new_root = target->GetRootWindow(); - if (IsLocatedEvent(*event)) { - // The event has been transformed to be in |target|'s coordinate system. - // But dispatching the event through the EventProcessor requires the event - // to be in the host's coordinate system. So, convert the event to be in - // the root's coordinate space, and then to the host's coordinate space by - // applying the host's transform. - ui::LocatedEvent* located_event = static_cast<ui::LocatedEvent*>(event); - located_event->ConvertLocationToTarget(target, new_root); - located_event->UpdateForRootTransform( - new_root->GetHost()->GetRootTransform()); - } - ignore_result( - new_root->GetHost()->event_processor()->OnEventFromSource(event)); - - target = NULL; - } - return target; -} - -bool WindowTargeter::SubtreeCanAcceptEvent( - ui::EventTarget* target, - const ui::LocatedEvent& event) const { - aura::Window* window = static_cast<aura::Window*>(target); - if (!window->IsVisible()) - return false; - if (window->ignore_events()) - return false; - client::EventClient* client = client::GetEventClient(window->GetRootWindow()); - if (client && !client->CanProcessEventsWithinSubtree(window)) - return false; - - Window* parent = window->parent(); - if (parent && parent->delegate_ && !parent->delegate_-> - ShouldDescendIntoChildForEventHandling(window, event.location())) { - return false; - } - return true; -} - -bool WindowTargeter::EventLocationInsideBounds( - ui::EventTarget* target, - const ui::LocatedEvent& event) const { - aura::Window* window = static_cast<aura::Window*>(target); - gfx::Point point = event.location(); - if (window->parent()) - aura::Window::ConvertPointToTarget(window->parent(), window, &point); - return gfx::Rect(window->bounds().size()).Contains(point); -} - -ui::EventTarget* WindowTargeter::FindTargetForLocatedEvent( - ui::EventTarget* root, - ui::LocatedEvent* event) { - Window* window = static_cast<Window*>(root); - if (!window->parent()) { - Window* target = FindTargetInRootWindow(window, *event); - if (target) { - window->ConvertEventToTarget(target, event); - return target; - } - } - return EventTargeter::FindTargetForLocatedEvent(root, event); -} - -Window* WindowTargeter::FindTargetForKeyEvent(Window* window, - const ui::KeyEvent& key) { - Window* root_window = window->GetRootWindow(); - client::FocusClient* focus_client = client::GetFocusClient(root_window); - Window* focused_window = focus_client->GetFocusedWindow(); - if (!focused_window) - return window; - - client::EventClient* event_client = client::GetEventClient(root_window); - if (event_client && - !event_client->CanProcessEventsWithinSubtree(focused_window)) { - focus_client->FocusWindow(NULL); - return NULL; - } - return focused_window ? focused_window : window; -} - -Window* WindowTargeter::FindTargetInRootWindow(Window* root_window, - const ui::LocatedEvent& event) { - DCHECK_EQ(root_window, root_window->GetRootWindow()); - - // Mouse events should be dispatched to the window that processed the - // mouse-press events (if any). - if (event.IsScrollEvent() || event.IsMouseEvent()) { - WindowEventDispatcher* dispatcher = root_window->GetHost()->dispatcher(); - if (dispatcher->mouse_pressed_handler()) - return dispatcher->mouse_pressed_handler(); - } - - // All events should be directed towards the capture window (if any). - Window* capture_window = client::GetCaptureWindow(root_window); - if (capture_window) - return capture_window; - - if (event.IsTouchEvent()) { - // Query the gesture-recognizer to find targets for touch events. - const ui::TouchEvent& touch = static_cast<const ui::TouchEvent&>(event); - ui::GestureConsumer* consumer = - ui::GestureRecognizer::Get()->GetTouchLockedTarget(touch); - if (consumer) - return static_cast<Window*>(consumer); - consumer = - ui::GestureRecognizer::Get()->GetTargetForLocation( - event.location(), touch.source_device_id()); - if (consumer) - return static_cast<Window*>(consumer); - - // If the initial touch is outside the root window, target the root. - if (!root_window->bounds().Contains(event.location())) - return root_window; - } - - return NULL; -} - -} // namespace aura
diff --git a/ui/aura/window_targeter.h b/ui/aura/window_targeter.h deleted file mode 100644 index 5054c57..0000000 --- a/ui/aura/window_targeter.h +++ /dev/null
@@ -1,45 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_WINDOW_TARGETER_H_ -#define UI_AURA_WINDOW_TARGETER_H_ - -#include "ui/aura/aura_export.h" -#include "ui/events/event_targeter.h" - -namespace aura { - -class Window; - -class AURA_EXPORT WindowTargeter : public ui::EventTargeter { - public: - WindowTargeter(); - virtual ~WindowTargeter(); - - protected: - // ui::EventTargeter: - virtual ui::EventTarget* FindTargetForEvent(ui::EventTarget* root, - ui::Event* event) override; - virtual ui::EventTarget* FindTargetForLocatedEvent( - ui::EventTarget* root, - ui::LocatedEvent* event) override; - virtual bool SubtreeCanAcceptEvent( - ui::EventTarget* target, - const ui::LocatedEvent& event) const override; - virtual bool EventLocationInsideBounds( - ui::EventTarget* target, - const ui::LocatedEvent& event) const override; - - private: - Window* FindTargetForKeyEvent(Window* root_window, - const ui::KeyEvent& event); - Window* FindTargetInRootWindow(Window* root_window, - const ui::LocatedEvent& event); - - DISALLOW_COPY_AND_ASSIGN(WindowTargeter); -}; - -} // namespace aura - -#endif // UI_AURA_WINDOW_TARGETER_H_
diff --git a/ui/aura/window_targeter_unittest.cc b/ui/aura/window_targeter_unittest.cc deleted file mode 100644 index 847f567..0000000 --- a/ui/aura/window_targeter_unittest.cc +++ /dev/null
@@ -1,180 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/window_targeter.h" - -#include "ui/aura/scoped_window_targeter.h" -#include "ui/aura/test/aura_test_base.h" -#include "ui/aura/test/test_window_delegate.h" -#include "ui/aura/window.h" -#include "ui/events/test/test_event_handler.h" - -namespace aura { - -// Always returns the same window. -class StaticWindowTargeter : public ui::EventTargeter { - public: - explicit StaticWindowTargeter(aura::Window* window) - : window_(window) {} - virtual ~StaticWindowTargeter() {} - - private: - // ui::EventTargeter: - virtual ui::EventTarget* FindTargetForLocatedEvent( - ui::EventTarget* root, - ui::LocatedEvent* event) override { - return window_; - } - - Window* window_; - - DISALLOW_COPY_AND_ASSIGN(StaticWindowTargeter); -}; - -class WindowTargeterTest : public test::AuraTestBase { - public: - WindowTargeterTest() {} - virtual ~WindowTargeterTest() {} - - Window* root_window() { return AuraTestBase::root_window(); } -}; - -gfx::RectF GetEffectiveVisibleBoundsInRootWindow(Window* window) { - gfx::RectF bounds = gfx::Rect(window->bounds().size()); - Window* root = window->GetRootWindow(); - CHECK(window->layer()); - CHECK(root->layer()); - gfx::Transform transform; - if (!window->layer()->GetTargetTransformRelativeTo(root->layer(), &transform)) - return gfx::RectF(); - transform.TransformRect(&bounds); - return bounds; -} - -TEST_F(WindowTargeterTest, Basic) { - test::TestWindowDelegate delegate; - scoped_ptr<Window> window(CreateNormalWindow(1, root_window(), &delegate)); - Window* one = CreateNormalWindow(2, window.get(), &delegate); - Window* two = CreateNormalWindow(3, window.get(), &delegate); - - window->SetBounds(gfx::Rect(0, 0, 100, 100)); - one->SetBounds(gfx::Rect(0, 0, 500, 100)); - two->SetBounds(gfx::Rect(501, 0, 500, 1000)); - - root_window()->Show(); - - ui::test::TestEventHandler handler; - one->AddPreTargetHandler(&handler); - - ui::MouseEvent press(ui::ET_MOUSE_PRESSED, - gfx::Point(20, 20), - gfx::Point(20, 20), - ui::EF_NONE, - ui::EF_NONE); - DispatchEventUsingWindowDispatcher(&press); - EXPECT_EQ(1, handler.num_mouse_events()); - - handler.Reset(); - DispatchEventUsingWindowDispatcher(&press); - EXPECT_EQ(1, handler.num_mouse_events()); - - one->RemovePreTargetHandler(&handler); -} - -TEST_F(WindowTargeterTest, ScopedWindowTargeter) { - test::TestWindowDelegate delegate; - scoped_ptr<Window> window(CreateNormalWindow(1, root_window(), &delegate)); - Window* child = CreateNormalWindow(2, window.get(), &delegate); - - window->SetBounds(gfx::Rect(30, 30, 100, 100)); - child->SetBounds(gfx::Rect(20, 20, 50, 50)); - root_window()->Show(); - - ui::EventTarget* root = root_window(); - ui::EventTargeter* targeter = root->GetEventTargeter(); - - gfx::Point event_location(60, 60); - { - ui::MouseEvent mouse(ui::ET_MOUSE_MOVED, event_location, event_location, - ui::EF_NONE, ui::EF_NONE); - EXPECT_EQ(child, targeter->FindTargetForEvent(root, &mouse)); - } - - // Install a targeter on |window| so that the events never reach the child. - scoped_ptr<ScopedWindowTargeter> scoped_targeter( - new ScopedWindowTargeter(window.get(), scoped_ptr<ui::EventTargeter>( - new StaticWindowTargeter(window.get())))); - { - ui::MouseEvent mouse(ui::ET_MOUSE_MOVED, event_location, event_location, - ui::EF_NONE, ui::EF_NONE); - EXPECT_EQ(window.get(), targeter->FindTargetForEvent(root, &mouse)); - } - scoped_targeter.reset(); - { - ui::MouseEvent mouse(ui::ET_MOUSE_MOVED, event_location, event_location, - ui::EF_NONE, ui::EF_NONE); - EXPECT_EQ(child, targeter->FindTargetForEvent(root, &mouse)); - } -} - -// Test that ScopedWindowTargeter does not crash if the window for which it -// replaces the targeter gets destroyed before it does. -TEST_F(WindowTargeterTest, ScopedWindowTargeterWindowDestroyed) { - test::TestWindowDelegate delegate; - scoped_ptr<Window> window(CreateNormalWindow(1, root_window(), &delegate)); - scoped_ptr<ScopedWindowTargeter> scoped_targeter( - new ScopedWindowTargeter(window.get(), scoped_ptr<ui::EventTargeter>( - new StaticWindowTargeter(window.get())))); - - window.reset(); - scoped_targeter.reset(); - - // We did not crash! -} - -TEST_F(WindowTargeterTest, TargetTransformedWindow) { - root_window()->Show(); - - test::TestWindowDelegate delegate; - scoped_ptr<Window> window(CreateNormalWindow(2, root_window(), &delegate)); - - const gfx::Rect window_bounds(100, 20, 400, 80); - window->SetBounds(window_bounds); - - ui::EventTarget* root_target = root_window(); - ui::EventTargeter* targeter = root_target->GetEventTargeter(); - gfx::Point event_location(490, 50); - { - ui::MouseEvent mouse(ui::ET_MOUSE_MOVED, event_location, event_location, - ui::EF_NONE, ui::EF_NONE); - EXPECT_EQ(window.get(), targeter->FindTargetForEvent(root_target, &mouse)); - } - - // Scale |window| by 50%. This should move it away from underneath - // |event_location|, so an event in that location will not be targeted to it. - gfx::Transform transform; - transform.Scale(0.5, 0.5); - window->SetTransform(transform); - EXPECT_EQ(gfx::RectF(100, 20, 200, 40).ToString(), - GetEffectiveVisibleBoundsInRootWindow(window.get()).ToString()); - { - ui::MouseEvent mouse(ui::ET_MOUSE_MOVED, event_location, event_location, - ui::EF_NONE, ui::EF_NONE); - EXPECT_EQ(root_window(), targeter->FindTargetForEvent(root_target, &mouse)); - } - - transform = gfx::Transform(); - transform.Translate(200, 10); - transform.Scale(0.5, 0.5); - window->SetTransform(transform); - EXPECT_EQ(gfx::RectF(300, 30, 200, 40).ToString(), - GetEffectiveVisibleBoundsInRootWindow(window.get()).ToString()); - { - ui::MouseEvent mouse(ui::ET_MOUSE_MOVED, event_location, event_location, - ui::EF_NONE, ui::EF_NONE); - EXPECT_EQ(window.get(), targeter->FindTargetForEvent(root_target, &mouse)); - } -} - -} // namespace aura
diff --git a/ui/aura/window_tracker.cc b/ui/aura/window_tracker.cc deleted file mode 100644 index 9653e5f..0000000 --- a/ui/aura/window_tracker.cc +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/window_tracker.h" - -#include "ui/aura/window.h" - -namespace aura { - -WindowTracker::WindowTracker() { -} - -WindowTracker::~WindowTracker() { - for (Windows::iterator i = windows_.begin(); i != windows_.end(); ++i) - (*i)->RemoveObserver(this); -} - -void WindowTracker::Add(Window* window) { - if (windows_.count(window)) - return; - - window->AddObserver(this); - windows_.insert(window); -} - -void WindowTracker::Remove(Window* window) { - if (windows_.count(window)) { - windows_.erase(window); - window->RemoveObserver(this); - } -} - -bool WindowTracker::Contains(Window* window) { - return windows_.count(window) > 0; -} - -void WindowTracker::OnWindowDestroying(Window* window) { - DCHECK_GT(windows_.count(window), 0u); - Remove(window); -} - -} // namespace aura
diff --git a/ui/aura/window_tracker.h b/ui/aura/window_tracker.h deleted file mode 100644 index 3a9650e..0000000 --- a/ui/aura/window_tracker.h +++ /dev/null
@@ -1,50 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_WINDOW_TRACKER_H_ -#define UI_AURA_WINDOW_TRACKER_H_ - -#include <set> - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "ui/aura/aura_export.h" -#include "ui/aura/window_observer.h" - -namespace aura { - -// This class keeps track of a set of windows. A Window is removed either -// explicitly by Remove(), or implicitly when the window is destroyed. -class AURA_EXPORT WindowTracker : public WindowObserver { - public: - typedef std::set<Window*> Windows; - - WindowTracker(); - virtual ~WindowTracker(); - - // Returns the set of windows being observed. - const std::set<Window*>& windows() const { return windows_; } - - // Adds |window| to the set of Windows being tracked. - void Add(Window* window); - - // Removes |window| from the set of windows being tracked. - void Remove(Window* window); - - // Returns true if |window| was previously added and has not been removed or - // deleted. - bool Contains(Window* window); - - // WindowObserver overrides: - virtual void OnWindowDestroying(Window* window) override; - - private: - Windows windows_; - - DISALLOW_COPY_AND_ASSIGN(WindowTracker); -}; - -} // namespace aura - -#endif // UI_AURA_WINDOW_TRACKER_H_
diff --git a/ui/aura/window_tree_host.cc b/ui/aura/window_tree_host.cc deleted file mode 100644 index bbe52fc..0000000 --- a/ui/aura/window_tree_host.cc +++ /dev/null
@@ -1,278 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/window_tree_host.h" - -#include "base/debug/trace_event.h" -#include "base/thread_task_runner_handle.h" -#include "ui/aura/client/capture_client.h" -#include "ui/aura/client/cursor_client.h" -#include "ui/aura/env.h" -#include "ui/aura/window.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/aura/window_targeter.h" -#include "ui/aura/window_tree_host_observer.h" -#include "ui/base/view_prop.h" -#include "ui/compositor/dip_util.h" -#include "ui/compositor/layer.h" -#include "ui/gfx/display.h" -#include "ui/gfx/insets.h" -#include "ui/gfx/point.h" -#include "ui/gfx/point3_f.h" -#include "ui/gfx/point_conversions.h" -#include "ui/gfx/screen.h" -#include "ui/gfx/size_conversions.h" - -namespace aura { - -const char kWindowTreeHostForAcceleratedWidget[] = - "__AURA_WINDOW_TREE_HOST_ACCELERATED_WIDGET__"; - -float GetDeviceScaleFactorFromDisplay(Window* window) { - gfx::Display display = gfx::Screen::GetScreenFor(window)-> - GetDisplayNearestWindow(window); - DCHECK(display.is_valid()); - return display.device_scale_factor(); -} - -//////////////////////////////////////////////////////////////////////////////// -// WindowTreeHost, public: - -WindowTreeHost::~WindowTreeHost() { - DCHECK(!compositor_) << "compositor must be destroyed before root window"; -} - -#if defined(OS_ANDROID) -// static -WindowTreeHost* WindowTreeHost::Create(const gfx::Rect& bounds) { - // This is only hit for tests and ash, right now these aren't an issue so - // adding the CHECK. - // TODO(sky): decide if we want a factory. - CHECK(false); - return NULL; -} -#endif - -// static -WindowTreeHost* WindowTreeHost::GetForAcceleratedWidget( - gfx::AcceleratedWidget widget) { - return reinterpret_cast<WindowTreeHost*>( - ui::ViewProp::GetValue(widget, kWindowTreeHostForAcceleratedWidget)); -} - -void WindowTreeHost::InitHost() { - InitCompositor(); - UpdateRootWindowSize(GetBounds().size()); - Env::GetInstance()->NotifyHostInitialized(this); - window()->Show(); -} - -void WindowTreeHost::InitCompositor() { - compositor_->SetScaleAndSize(GetDeviceScaleFactorFromDisplay(window()), - GetBounds().size()); - compositor_->SetRootLayer(window()->layer()); -} - -void WindowTreeHost::AddObserver(WindowTreeHostObserver* observer) { - observers_.AddObserver(observer); -} - -void WindowTreeHost::RemoveObserver(WindowTreeHostObserver* observer) { - observers_.RemoveObserver(observer); -} - -ui::EventProcessor* WindowTreeHost::event_processor() { - return dispatcher(); -} - -gfx::Transform WindowTreeHost::GetRootTransform() const { - float scale = ui::GetDeviceScaleFactor(window()->layer()); - gfx::Transform transform; - transform.Scale(scale, scale); - transform *= window()->layer()->transform(); - return transform; -} - -void WindowTreeHost::SetRootTransform(const gfx::Transform& transform) { - window()->SetTransform(transform); - UpdateRootWindowSize(GetBounds().size()); -} - -gfx::Transform WindowTreeHost::GetInverseRootTransform() const { - gfx::Transform invert; - gfx::Transform transform = GetRootTransform(); - if (!transform.GetInverse(&invert)) - return transform; - return invert; -} - -void WindowTreeHost::UpdateRootWindowSize(const gfx::Size& host_size) { - gfx::Rect bounds(host_size); - gfx::RectF new_bounds(ui::ConvertRectToDIP(window()->layer(), bounds)); - window()->layer()->transform().TransformRect(&new_bounds); - window()->SetBounds(gfx::Rect(gfx::ToFlooredSize(new_bounds.size()))); -} - -void WindowTreeHost::ConvertPointToNativeScreen(gfx::Point* point) const { - ConvertPointToHost(point); - gfx::Point location = GetLocationOnNativeScreen(); - point->Offset(location.x(), location.y()); -} - -void WindowTreeHost::ConvertPointFromNativeScreen(gfx::Point* point) const { - gfx::Point location = GetLocationOnNativeScreen(); - point->Offset(-location.x(), -location.y()); - ConvertPointFromHost(point); -} - -void WindowTreeHost::ConvertPointToHost(gfx::Point* point) const { - gfx::Point3F point_3f(*point); - GetRootTransform().TransformPoint(&point_3f); - *point = gfx::ToFlooredPoint(point_3f.AsPointF()); -} - -void WindowTreeHost::ConvertPointFromHost(gfx::Point* point) const { - gfx::Point3F point_3f(*point); - GetInverseRootTransform().TransformPoint(&point_3f); - *point = gfx::ToFlooredPoint(point_3f.AsPointF()); -} - -void WindowTreeHost::SetCursor(gfx::NativeCursor cursor) { - last_cursor_ = cursor; - // A lot of code seems to depend on NULL cursors actually showing an arrow, - // so just pass everything along to the host. - SetCursorNative(cursor); -} - -void WindowTreeHost::OnCursorVisibilityChanged(bool show) { - // Clear any existing mouse hover effects when the cursor becomes invisible. - // Note we do not need to dispatch a mouse enter when the cursor becomes - // visible because that can only happen in response to a mouse event, which - // will trigger its own mouse enter. - if (!show) { - ui::EventDispatchDetails details = dispatcher()->DispatchMouseExitAtPoint( - dispatcher()->GetLastMouseLocationInRoot()); - if (details.dispatcher_destroyed) - return; - } - - OnCursorVisibilityChangedNative(show); -} - -void WindowTreeHost::MoveCursorTo(const gfx::Point& location_in_dip) { - gfx::Point host_location(location_in_dip); - ConvertPointToHost(&host_location); - MoveCursorToInternal(location_in_dip, host_location); -} - -void WindowTreeHost::MoveCursorToHostLocation(const gfx::Point& host_location) { - gfx::Point root_location(host_location); - ConvertPointFromHost(&root_location); - MoveCursorToInternal(root_location, host_location); -} - -//////////////////////////////////////////////////////////////////////////////// -// WindowTreeHost, protected: - -WindowTreeHost::WindowTreeHost() - : window_(new Window(NULL)), - last_cursor_(ui::kCursorNull) { -} - -void WindowTreeHost::DestroyCompositor() { - compositor_.reset(); -} - -void WindowTreeHost::DestroyDispatcher() { - delete window_; - window_ = NULL; - dispatcher_.reset(); - - // TODO(beng): this comment is no longer quite valid since this function - // isn't called from WED, and WED isn't a subclass of Window. So it seems - // like we could just rely on ~Window now. - // Destroy child windows while we're still valid. This is also done by - // ~Window, but by that time any calls to virtual methods overriden here (such - // as GetRootWindow()) result in Window's implementation. By destroying here - // we ensure GetRootWindow() still returns this. - //window()->RemoveOrDestroyChildren(); -} - -void WindowTreeHost::CreateCompositor( - gfx::AcceleratedWidget accelerated_widget) { - DCHECK(Env::GetInstance()); - ui::ContextFactory* context_factory = Env::GetInstance()->context_factory(); - DCHECK(context_factory); - compositor_.reset( - new ui::Compositor(GetAcceleratedWidget(), - context_factory, - base::ThreadTaskRunnerHandle::Get())); - // TODO(beng): I think this setup should probably all move to a "accelerated - // widget available" function. - if (!dispatcher()) { - window()->Init(WINDOW_LAYER_NOT_DRAWN); - window()->set_host(this); - window()->SetName("RootWindow"); - window()->SetEventTargeter( - scoped_ptr<ui::EventTargeter>(new WindowTargeter())); - prop_.reset(new ui::ViewProp(GetAcceleratedWidget(), - kWindowTreeHostForAcceleratedWidget, - this)); - dispatcher_.reset(new WindowEventDispatcher(this)); - } -} - -void WindowTreeHost::OnHostMoved(const gfx::Point& new_location) { - TRACE_EVENT1("ui", "WindowTreeHost::OnHostMoved", - "origin", new_location.ToString()); - - FOR_EACH_OBSERVER(WindowTreeHostObserver, observers_, - OnHostMoved(this, new_location)); -} - -void WindowTreeHost::OnHostResized(const gfx::Size& new_size) { - // The compositor should have the same size as the native root window host. - // Get the latest scale from display because it might have been changed. - compositor_->SetScaleAndSize(GetDeviceScaleFactorFromDisplay(window()), - new_size); - - gfx::Size layer_size = GetBounds().size(); - // The layer, and the observers should be notified of the - // transformed size of the root window. - UpdateRootWindowSize(layer_size); - FOR_EACH_OBSERVER(WindowTreeHostObserver, observers_, OnHostResized(this)); -} - -void WindowTreeHost::OnHostCloseRequested() { - FOR_EACH_OBSERVER(WindowTreeHostObserver, observers_, - OnHostCloseRequested(this)); -} - -void WindowTreeHost::OnHostActivated() { - Env::GetInstance()->NotifyHostActivated(this); -} - -void WindowTreeHost::OnHostLostWindowCapture() { - Window* capture_window = client::GetCaptureWindow(window()); - if (capture_window && capture_window->GetRootWindow() == window()) - capture_window->ReleaseCapture(); -} - -//////////////////////////////////////////////////////////////////////////////// -// WindowTreeHost, private: - -void WindowTreeHost::MoveCursorToInternal(const gfx::Point& root_location, - const gfx::Point& host_location) { - last_cursor_request_position_in_host_ = host_location; - MoveCursorToNative(host_location); - client::CursorClient* cursor_client = client::GetCursorClient(window()); - if (cursor_client) { - const gfx::Display& display = - gfx::Screen::GetScreenFor(window())->GetDisplayNearestWindow(window()); - cursor_client->SetDisplay(display); - } - dispatcher()->OnCursorMovedToRootLocation(root_location); -} - -} // namespace aura
diff --git a/ui/aura/window_tree_host.h b/ui/aura/window_tree_host.h deleted file mode 100644 index aaf0d3b..0000000 --- a/ui/aura/window_tree_host.h +++ /dev/null
@@ -1,203 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_WINDOW_TREE_HOST_H_ -#define UI_AURA_WINDOW_TREE_HOST_H_ - -#include <vector> - -#include "base/event_types.h" -#include "base/message_loop/message_loop.h" -#include "ui/aura/aura_export.h" -#include "ui/base/cursor/cursor.h" -#include "ui/events/event_source.h" -#include "ui/gfx/native_widget_types.h" - -namespace gfx { -class Insets; -class Point; -class Rect; -class Size; -class Transform; -} - -namespace ui { -class Compositor; -class EventProcessor; -class ViewProp; -} - -namespace aura { -namespace test { -class WindowTreeHostTestApi; -} - -class WindowEventDispatcher; -class WindowTreeHostObserver; - -// WindowTreeHost bridges between a native window and the embedded RootWindow. -// It provides the accelerated widget and maps events from the native os to -// aura. -class AURA_EXPORT WindowTreeHost { - public: - virtual ~WindowTreeHost(); - - // Creates a new WindowTreeHost. The caller owns the returned value. - static WindowTreeHost* Create(const gfx::Rect& bounds); - - // Returns the WindowTreeHost for the specified accelerated widget, or NULL - // if there is none associated. - static WindowTreeHost* GetForAcceleratedWidget(gfx::AcceleratedWidget widget); - - void InitHost(); - - void InitCompositor(); - - void AddObserver(WindowTreeHostObserver* observer); - void RemoveObserver(WindowTreeHostObserver* observer); - - Window* window() { return window_; } - const Window* window() const { return window_; } - - ui::EventProcessor* event_processor(); - - WindowEventDispatcher* dispatcher() { - return const_cast<WindowEventDispatcher*>( - const_cast<const WindowTreeHost*>(this)->dispatcher()); - } - const WindowEventDispatcher* dispatcher() const { return dispatcher_.get(); } - - ui::Compositor* compositor() { return compositor_.get(); } - - // Gets/Sets the root window's transform. - virtual gfx::Transform GetRootTransform() const; - virtual void SetRootTransform(const gfx::Transform& transform); - virtual gfx::Transform GetInverseRootTransform() const; - - // Updates the root window's size using |host_size|, current - // transform and insets. - virtual void UpdateRootWindowSize(const gfx::Size& host_size); - - // Returns the actual size of the screen. - // (gfx::Screen only reports on the virtual desktop exposed by Aura.) - static gfx::Size GetNativeScreenSize(); - - // Converts |point| from the root window's coordinate system to native - // screen's. - void ConvertPointToNativeScreen(gfx::Point* point) const; - - // Converts |point| from native screen coordinate system to the root window's. - void ConvertPointFromNativeScreen(gfx::Point* point) const; - - // Converts |point| from the root window's coordinate system to the - // host window's. - void ConvertPointToHost(gfx::Point* point) const; - - // Converts |point| from the host window's coordinate system to the - // root window's. - void ConvertPointFromHost(gfx::Point* point) const; - - // Cursor. - // Sets the currently-displayed cursor. If the cursor was previously hidden - // via ShowCursor(false), it will remain hidden until ShowCursor(true) is - // called, at which point the cursor that was last set via SetCursor() will be - // used. - void SetCursor(gfx::NativeCursor cursor); - - // Invoked when the cursor's visibility has changed. - void OnCursorVisibilityChanged(bool visible); - - // Moves the cursor to the specified location relative to the root window. - void MoveCursorTo(const gfx::Point& location); - - // Moves the cursor to the |host_location| given in host coordinates. - void MoveCursorToHostLocation(const gfx::Point& host_location); - - gfx::NativeCursor last_cursor() const { return last_cursor_; } - - // Returns the EventSource responsible for dispatching events to the window - // tree. - virtual ui::EventSource* GetEventSource() = 0; - - // Returns the accelerated widget. - virtual gfx::AcceleratedWidget GetAcceleratedWidget() = 0; - - // Shows the WindowTreeHost. - virtual void Show() = 0; - - // Hides the WindowTreeHost. - virtual void Hide() = 0; - - // Gets/Sets the size of the WindowTreeHost. - virtual gfx::Rect GetBounds() const = 0; - virtual void SetBounds(const gfx::Rect& bounds) = 0; - - // Sets the OS capture to the root window. - virtual void SetCapture() = 0; - - // Releases OS capture of the root window. - virtual void ReleaseCapture() = 0; - - // Posts |native_event| to the platform's event queue. - virtual void PostNativeEvent(const base::NativeEvent& native_event) = 0; - - protected: - friend class TestScreen; // TODO(beng): see if we can remove/consolidate. - - WindowTreeHost(); - void DestroyCompositor(); - void DestroyDispatcher(); - - void CreateCompositor(gfx::AcceleratedWidget accelerated_widget); - - // Returns the location of the RootWindow on native screen. - virtual gfx::Point GetLocationOnNativeScreen() const = 0; - - void OnHostMoved(const gfx::Point& new_location); - void OnHostResized(const gfx::Size& new_size); - void OnHostCloseRequested(); - void OnHostActivated(); - void OnHostLostWindowCapture(); - - // Sets the currently displayed cursor. - virtual void SetCursorNative(gfx::NativeCursor cursor) = 0; - - // Moves the cursor to the specified location relative to the root window. - virtual void MoveCursorToNative(const gfx::Point& location) = 0; - - // kCalled when the cursor visibility has changed. - virtual void OnCursorVisibilityChangedNative(bool show) = 0; - - private: - friend class test::WindowTreeHostTestApi; - - // Moves the cursor to the specified location. This method is internally used - // by MoveCursorTo() and MoveCursorToHostLocation(). - void MoveCursorToInternal(const gfx::Point& root_location, - const gfx::Point& host_location); - - // We don't use a scoped_ptr for |window_| since we need this ptr to be valid - // during its deletion. (Window's dtor notifies observers that may attempt to - // reach back up to access this object which will be valid until the end of - // the dtor). - Window* window_; // Owning. - - ObserverList<WindowTreeHostObserver> observers_; - - scoped_ptr<WindowEventDispatcher> dispatcher_; - - scoped_ptr<ui::Compositor> compositor_; - - // Last cursor set. Used for testing. - gfx::NativeCursor last_cursor_; - gfx::Point last_cursor_request_position_in_host_; - - scoped_ptr<ui::ViewProp> prop_; - - DISALLOW_COPY_AND_ASSIGN(WindowTreeHost); -}; - -} // namespace aura - -#endif // UI_AURA_WINDOW_TREE_HOST_H_
diff --git a/ui/aura/window_tree_host_mac.h b/ui/aura/window_tree_host_mac.h deleted file mode 100644 index da502b5..0000000 --- a/ui/aura/window_tree_host_mac.h +++ /dev/null
@@ -1,61 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_WINDOW_TREE_HOST_MAC_H_ -#define UI_AURA_WINDOW_TREE_HOST_MAC_H_ - -#include <vector> - -#include "base/mac/scoped_nsobject.h" -#include "ui/aura/aura_export.h" -#include "ui/aura/window_tree_host.h" -#include "ui/gfx/insets.h" -#include "ui/gfx/rect.h" - -namespace ui { -class MouseEvent; -} - -namespace aura { - -namespace internal { -class TouchEventCalibrate; -} - -class AURA_EXPORT WindowTreeHostMac : public WindowTreeHost { - public: - explicit WindowTreeHostMac(const gfx::Rect& bounds); - virtual ~WindowTreeHostMac(); - - private: - // WindowTreeHost Overrides. - virtual ui::EventSource* GetEventSource() override; - virtual gfx::AcceleratedWidget GetAcceleratedWidget() override; - virtual void Show() override; - virtual void Hide() override; - virtual void ToggleFullScreen() override; - virtual gfx::Rect GetBounds() const override; - virtual void SetBounds(const gfx::Rect& bounds) override; - virtual gfx::Insets GetInsets() const override; - virtual void SetInsets(const gfx::Insets& insets) override; - virtual gfx::Point GetLocationOnNativeScreen() const override; - virtual void SetCapture() override; - virtual void ReleaseCapture() override; - virtual bool ConfineCursorToRootWindow() override; - virtual void UnConfineCursor() override; - virtual void SetCursorNative(gfx::NativeCursor cursor_type) override; - virtual void MoveCursorToNative(const gfx::Point& location) override; - virtual void OnCursorVisibilityChangedNative(bool show) override; - virtual void PostNativeEvent(const base::NativeEvent& event) override; - virtual void OnDeviceScaleFactorChanged(float device_scale_factor) override; - - private: - base::scoped_nsobject<NSWindow> window_; - - DISALLOW_COPY_AND_ASSIGN(WindowTreeHostMac); -}; - -} // namespace aura - -#endif // UI_AURA_WINDOW_TREE_HOST_MAC_H_
diff --git a/ui/aura/window_tree_host_mac.mm b/ui/aura/window_tree_host_mac.mm deleted file mode 100644 index 7fb3f82..0000000 --- a/ui/aura/window_tree_host_mac.mm +++ /dev/null
@@ -1,114 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <Cocoa/Cocoa.h> - -#include "ui/aura/window_tree_host_mac.h" -#include "ui/aura/window_tree_host.h" - -namespace aura { - -WindowTreeHostMac::WindowTreeHostMac(const gfx::Rect& bounds) { - window_.reset( - [[NSWindow alloc] - initWithContentRect:NSRectFromCGRect(bounds.ToCGRect()) - styleMask:NSBorderlessWindowMask - backing:NSBackingStoreBuffered - defer:NO]); - CreateCompositor(GetAcceleratedWidget()); -} - -WindowTreeHostMac::~WindowTreeHostMac() { - DestroyDispatcher(); -} - -EventSource* WindowTreeHostMac::GetEventSource() { - NOTIMPLEMENTED(); - return nil; -} - -gfx::AcceleratedWidget WindowTreeHostMac::GetAcceleratedWidget() { - return [window_ contentView]; -} -void WindowTreeHostMac::Show() { - [window_ makeKeyAndOrderFront:nil]; -} - -void WindowTreeHostMac::Hide() { - [window_ orderOut:nil]; -} - -void WindowTreeHostMac::ToggleFullScreen() { -} - -gfx::Rect WindowTreeHostMac::GetBounds() const { - return gfx::Rect(NSRectToCGRect([window_ frame])); -} - -void WindowTreeHostMac::SetBounds(const gfx::Rect& bounds) { - [window_ setFrame:NSRectFromCGRect(bounds.ToCGRect()) display:YES animate:NO]; -} - -gfx::Insets WindowTreeHostMac::GetInsets() const { - NOTIMPLEMENTED(); - return gfx::Insets(); -} - -void WindowTreeHostMac::SetInsets(const gfx::Insets& insets) { - NOTIMPLEMENTED(); -} - -gfx::Point WindowTreeHostMac::GetLocationOnNativeScreen() const { - NOTIMPLEMENTED(); - return gfx::Point(0, 0); -} - -void WindowTreeHostMac::SetCapture() { - NOTIMPLEMENTED(); -} - -void WindowTreeHostMac::ReleaseCapture() { - NOTIMPLEMENTED(); -} - -bool WindowTreeHostMac::ConfineCursorToRootWindow() { - return false; -} - -void WindowTreeHostMac::UnConfineCursor() { - NOTIMPLEMENTED(); -} - -void WindowTreeHostMac::SetCursorNative(gfx::NativeCursor cursor_type) { - NOTIMPLEMENTED(); -} - -void WindowTreeHostMac::MoveCursorToNative(const gfx::Point& location) { - NOTIMPLEMENTED(); -} - -void WindowTreeHostMac::OnCursorVisibilityChangedNative(bool show) { - NOTIMPLEMENTED(); -} - -void WindowTreeHostMac::PostNativeEvent(const base::NativeEvent& event) { - NOTIMPLEMENTED(); -} - -void WindowTreeHostMac::OnDeviceScaleFactorChanged(float device_scale_factor) { - NOTIMPLEMENTED(); -} - -// static -WindowTreeHost* WindowTreeHost::Create(const gfx::Rect& bounds) { - return new WindowTreeHostMac(bounds); -} - -// static -gfx::Size WindowTreeHost::GetNativeScreenSize() { - NOTIMPLEMENTED(); - return gfx::Size(1024, 768); -} - -} // namespace aura
diff --git a/ui/aura/window_tree_host_observer.h b/ui/aura/window_tree_host_observer.h deleted file mode 100644 index d96e9d3..0000000 --- a/ui/aura/window_tree_host_observer.h +++ /dev/null
@@ -1,36 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_WINDOW_TREE_HOST_OBSERVER_H_ -#define UI_AURA_WINDOW_TREE_HOST_OBSERVER_H_ - -#include "ui/aura/aura_export.h" - -namespace gfx { -class Point; -} - -namespace aura { -class Window; -class WindowTreeHost; - -class AURA_EXPORT WindowTreeHostObserver { - public: - // Called when the host's client size has changed. - virtual void OnHostResized(const WindowTreeHost* host) {} - - // Called when the host is moved on screen. - virtual void OnHostMoved(const WindowTreeHost* host, - const gfx::Point& new_origin) {} - - // Called when the native window system sends the host request to close. - virtual void OnHostCloseRequested(const WindowTreeHost* host) {} - - protected: - virtual ~WindowTreeHostObserver() {} -}; - -} // namespace aura - -#endif // UI_AURA_WINDOW_TREE_HOST_OBSERVER_H_
diff --git a/ui/aura/window_tree_host_ozone.cc b/ui/aura/window_tree_host_ozone.cc deleted file mode 100644 index 6c332d7..0000000 --- a/ui/aura/window_tree_host_ozone.cc +++ /dev/null
@@ -1,129 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/window_tree_host_ozone.h" - -#include "ui/aura/window_event_dispatcher.h" -#include "ui/ozone/public/cursor_factory_ozone.h" -#include "ui/ozone/public/ozone_platform.h" -#include "ui/platform_window/platform_window.h" - -namespace aura { - -WindowTreeHostOzone::WindowTreeHostOzone(const gfx::Rect& bounds) - : widget_(gfx::kNullAcceleratedWidget) { - platform_window_ = - ui::OzonePlatform::GetInstance()->CreatePlatformWindow(this, bounds); -} - -WindowTreeHostOzone::~WindowTreeHostOzone() { - DestroyCompositor(); - DestroyDispatcher(); -} - -void WindowTreeHostOzone::OnBoundsChanged(const gfx::Rect& new_bounds) { - // TOOD(spang): Should we determine which parts changed? - OnHostResized(new_bounds.size()); - OnHostMoved(new_bounds.origin()); -} - -void WindowTreeHostOzone::OnDamageRect(const gfx::Rect& damaged_region) { -} - -void WindowTreeHostOzone::DispatchEvent(ui::Event* event) { - SendEventToProcessor(event); -} - -void WindowTreeHostOzone::OnCloseRequest() { - OnHostCloseRequested(); -} - -void WindowTreeHostOzone::OnClosed() { -} - -void WindowTreeHostOzone::OnWindowStateChanged( - ui::PlatformWindowState new_state) { -} - -void WindowTreeHostOzone::OnLostCapture() { -} - -void WindowTreeHostOzone::OnAcceleratedWidgetAvailable( - gfx::AcceleratedWidget widget) { - widget_ = widget; - CreateCompositor(widget_); -} - -void WindowTreeHostOzone::OnActivationChanged(bool active) { -} - -ui::EventSource* WindowTreeHostOzone::GetEventSource() { - return this; -} - -gfx::AcceleratedWidget WindowTreeHostOzone::GetAcceleratedWidget() { - return widget_; -} - -void WindowTreeHostOzone::Show() { - platform_window_->Show(); -} - -void WindowTreeHostOzone::Hide() { - platform_window_->Hide(); -} - -gfx::Rect WindowTreeHostOzone::GetBounds() const { - return platform_window_->GetBounds(); -} - -void WindowTreeHostOzone::SetBounds(const gfx::Rect& bounds) { - platform_window_->SetBounds(bounds); -} - -gfx::Point WindowTreeHostOzone::GetLocationOnNativeScreen() const { - return platform_window_->GetBounds().origin(); -} - -void WindowTreeHostOzone::SetCapture() { - platform_window_->SetCapture(); -} - -void WindowTreeHostOzone::ReleaseCapture() { - platform_window_->ReleaseCapture(); -} - -void WindowTreeHostOzone::PostNativeEvent( - const base::NativeEvent& native_event) { - SendEventToProcessor(static_cast<ui::Event*>(native_event)); -} - -void WindowTreeHostOzone::SetCursorNative(gfx::NativeCursor cursor) { - platform_window_->SetCursor(cursor.platform()); -} - -void WindowTreeHostOzone::MoveCursorToNative(const gfx::Point& location) { - platform_window_->MoveCursorTo(location); -} - -void WindowTreeHostOzone::OnCursorVisibilityChangedNative(bool show) { - NOTIMPLEMENTED(); -} - -ui::EventProcessor* WindowTreeHostOzone::GetEventProcessor() { - return dispatcher(); -} - -// static -WindowTreeHost* WindowTreeHost::Create(const gfx::Rect& bounds) { - return new WindowTreeHostOzone(bounds); -} - -// static -gfx::Size WindowTreeHost::GetNativeScreenSize() { - NOTIMPLEMENTED(); - return gfx::Size(); -} - -} // namespace aura
diff --git a/ui/aura/window_tree_host_ozone.h b/ui/aura/window_tree_host_ozone.h deleted file mode 100644 index f0e8c98..0000000 --- a/ui/aura/window_tree_host_ozone.h +++ /dev/null
@@ -1,69 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_WINDOW_TREE_HOST_OZONE_H_ -#define UI_AURA_WINDOW_TREE_HOST_OZONE_H_ - -#include "base/memory/scoped_ptr.h" -#include "ui/aura/window_tree_host.h" -#include "ui/events/event_source.h" -#include "ui/gfx/rect.h" -#include "ui/platform_window/platform_window_delegate.h" - -namespace ui { -class PlatformWindow; -} - -namespace aura { - -class AURA_EXPORT WindowTreeHostOzone : public WindowTreeHost, - public ui::EventSource, - public ui::PlatformWindowDelegate { - public: - explicit WindowTreeHostOzone(const gfx::Rect& bounds); - virtual ~WindowTreeHostOzone(); - - private: - // ui::PlatformWindowDelegate: - virtual void OnBoundsChanged(const gfx::Rect&) override; - virtual void OnDamageRect(const gfx::Rect& damaged_region) override; - virtual void DispatchEvent(ui::Event* event) override; - virtual void OnCloseRequest() override; - virtual void OnClosed() override; - virtual void OnWindowStateChanged(ui::PlatformWindowState new_state) override; - virtual void OnLostCapture() override; - virtual void OnAcceleratedWidgetAvailable( - gfx::AcceleratedWidget widget) override; - virtual void OnActivationChanged(bool active) override; - - // WindowTreeHost: - virtual ui::EventSource* GetEventSource() override; - virtual gfx::AcceleratedWidget GetAcceleratedWidget() override; - virtual void Show() override; - virtual void Hide() override; - virtual gfx::Rect GetBounds() const override; - virtual void SetBounds(const gfx::Rect& bounds) override; - virtual gfx::Point GetLocationOnNativeScreen() const override; - virtual void SetCapture() override; - virtual void ReleaseCapture() override; - virtual void PostNativeEvent(const base::NativeEvent& event) override; - virtual void SetCursorNative(gfx::NativeCursor cursor_type) override; - virtual void MoveCursorToNative(const gfx::Point& location) override; - virtual void OnCursorVisibilityChangedNative(bool show) override; - - // ui::EventSource overrides. - virtual ui::EventProcessor* GetEventProcessor() override; - - // Platform-specific part of this WindowTreeHost. - scoped_ptr<ui::PlatformWindow> platform_window_; - - // The identifier used to create a compositing surface. - gfx::AcceleratedWidget widget_; - - DISALLOW_COPY_AND_ASSIGN(WindowTreeHostOzone); -}; - -} // namespace aura - -#endif // UI_AURA_WINDOW_TREE_HOST_OZONE_H_
diff --git a/ui/aura/window_tree_host_win.cc b/ui/aura/window_tree_host_win.cc deleted file mode 100644 index 51bbcc6..0000000 --- a/ui/aura/window_tree_host_win.cc +++ /dev/null
@@ -1,173 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/window_tree_host_win.h" - -#include <windows.h> - -#include <algorithm> - -#include "base/message_loop/message_loop.h" -#include "ui/aura/client/cursor_client.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/base/cursor/cursor_loader_win.h" -#include "ui/base/view_prop.h" -#include "ui/compositor/compositor.h" -#include "ui/events/event.h" -#include "ui/gfx/display.h" -#include "ui/gfx/insets.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/gfx/screen.h" -#include "ui/platform_window/win/win_window.h" - -using std::max; -using std::min; - -namespace aura { -namespace { - -bool use_popup_as_root_window_for_test = false; - -} // namespace - -// static -WindowTreeHost* WindowTreeHost::Create(const gfx::Rect& bounds) { - return new WindowTreeHostWin(bounds); -} - -// static -gfx::Size WindowTreeHost::GetNativeScreenSize() { - return gfx::Size(GetSystemMetrics(SM_CXSCREEN), - GetSystemMetrics(SM_CYSCREEN)); -} - -WindowTreeHostWin::WindowTreeHostWin(const gfx::Rect& bounds) - : has_capture_(false), - widget_(gfx::kNullAcceleratedWidget), - window_(new ui::WinWindow(this, bounds)) { -} - -WindowTreeHostWin::~WindowTreeHostWin() { - DestroyCompositor(); - DestroyDispatcher(); - window_.reset(); -} - -ui::EventSource* WindowTreeHostWin::GetEventSource() { - return this; -} - -gfx::AcceleratedWidget WindowTreeHostWin::GetAcceleratedWidget() { - return widget_; -} - -void WindowTreeHostWin::Show() { - window_->Show(); -} - -void WindowTreeHostWin::Hide() { - window_->Hide(); -} - -gfx::Rect WindowTreeHostWin::GetBounds() const { - return window_->GetBounds(); -} - -void WindowTreeHostWin::SetBounds(const gfx::Rect& bounds) { - window_->SetBounds(bounds); -} - -gfx::Point WindowTreeHostWin::GetLocationOnNativeScreen() const { - return window_->GetBounds().origin(); -} - -void WindowTreeHostWin::SetCapture() { - if (!has_capture_) { - has_capture_ = true; - window_->SetCapture(); - } -} - -void WindowTreeHostWin::ReleaseCapture() { - if (has_capture_) - window_->ReleaseCapture(); -} - -void WindowTreeHostWin::SetCursorNative(gfx::NativeCursor native_cursor) { - // Custom web cursors are handled directly. - if (native_cursor == ui::kCursorCustom) - return; - - ui::CursorLoaderWin cursor_loader; - cursor_loader.SetPlatformCursor(&native_cursor); - ::SetCursor(native_cursor.platform()); -} - -void WindowTreeHostWin::MoveCursorToNative(const gfx::Point& location) { - // Deliberately not implemented. -} - -void WindowTreeHostWin::OnCursorVisibilityChangedNative(bool show) { - NOTIMPLEMENTED(); -} - -void WindowTreeHostWin::PostNativeEvent(const base::NativeEvent& native_event) { - ::PostMessage( - widget_, native_event.message, native_event.wParam, native_event.lParam); -} - -ui::EventProcessor* WindowTreeHostWin::GetEventProcessor() { - return dispatcher(); -} - -void WindowTreeHostWin::OnBoundsChanged(const gfx::Rect& new_bounds) { - gfx::Rect old_bounds = bounds_; - bounds_ = new_bounds; - if (bounds_.origin() != old_bounds.origin()) - OnHostMoved(bounds_.origin()); - if (bounds_.size() != old_bounds.size()) - OnHostResized(bounds_.size()); -} - -void WindowTreeHostWin::OnDamageRect(const gfx::Rect& damage_rect) { - compositor()->ScheduleRedrawRect(damage_rect); -} - -void WindowTreeHostWin::DispatchEvent(ui::Event* event) { - ui::EventDispatchDetails details = SendEventToProcessor(event); - if (details.dispatcher_destroyed) - event->SetHandled(); -} - -void WindowTreeHostWin::OnCloseRequest() { - // TODO: this obviously shouldn't be here. - base::MessageLoopForUI::current()->Quit(); -} - -void WindowTreeHostWin::OnClosed() { -} - -void WindowTreeHostWin::OnWindowStateChanged( - ui::PlatformWindowState new_state) { -} - -void WindowTreeHostWin::OnLostCapture() { - if (has_capture_) { - has_capture_ = false; - OnHostLostWindowCapture(); - } -} - -void WindowTreeHostWin::OnAcceleratedWidgetAvailable( - gfx::AcceleratedWidget widget) { - widget_ = widget; - CreateCompositor(widget); -} - -void WindowTreeHostWin::OnActivationChanged(bool active) { - if (active) - OnHostActivated(); -} - -} // namespace aura
diff --git a/ui/aura/window_tree_host_win.h b/ui/aura/window_tree_host_win.h deleted file mode 100644 index bfbdc07..0000000 --- a/ui/aura/window_tree_host_win.h +++ /dev/null
@@ -1,70 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_WINDOW_TREE_HOST_WIN_H_ -#define UI_AURA_WINDOW_TREE_HOST_WIN_H_ - -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "ui/aura/aura_export.h" -#include "ui/aura/window_tree_host.h" -#include "ui/events/event_source.h" -#include "ui/platform_window/platform_window.h" -#include "ui/platform_window/platform_window_delegate.h" - -namespace aura { - -class AURA_EXPORT WindowTreeHostWin - : public WindowTreeHost, - public ui::EventSource, - public NON_EXPORTED_BASE(ui::PlatformWindowDelegate) { - public: - explicit WindowTreeHostWin(const gfx::Rect& bounds); - virtual ~WindowTreeHostWin(); - - // WindowTreeHost: - virtual ui::EventSource* GetEventSource() override; - virtual gfx::AcceleratedWidget GetAcceleratedWidget() override; - virtual void Show() override; - virtual void Hide() override; - virtual gfx::Rect GetBounds() const override; - virtual void SetBounds(const gfx::Rect& bounds) override; - virtual gfx::Point GetLocationOnNativeScreen() const override; - virtual void SetCapture() override; - virtual void ReleaseCapture() override; - virtual void SetCursorNative(gfx::NativeCursor cursor) override; - virtual void MoveCursorToNative(const gfx::Point& location) override; - virtual void OnCursorVisibilityChangedNative(bool show) override; - virtual void PostNativeEvent(const base::NativeEvent& native_event) override; - - // ui::EventSource: - virtual ui::EventProcessor* GetEventProcessor() override; - - protected: - gfx::AcceleratedWidget hwnd() const { return widget_; } - - private: - // ui::PlatformWindowDelegate: - virtual void OnBoundsChanged(const gfx::Rect& new_bounds) override; - virtual void OnDamageRect(const gfx::Rect& damaged_region) override; - virtual void DispatchEvent(ui::Event* event) override; - virtual void OnCloseRequest() override; - virtual void OnClosed() override; - virtual void OnWindowStateChanged(ui::PlatformWindowState new_state) override; - virtual void OnLostCapture() override; - virtual void OnAcceleratedWidgetAvailable( - gfx::AcceleratedWidget widget) override; - virtual void OnActivationChanged(bool active) override; - - bool has_capture_; - gfx::Rect bounds_; - gfx::AcceleratedWidget widget_; - scoped_ptr<ui::PlatformWindow> window_; - - DISALLOW_COPY_AND_ASSIGN(WindowTreeHostWin); -}; - -} // namespace aura - -#endif // UI_AURA_WINDOW_TREE_HOST_WIN_H_
diff --git a/ui/aura/window_tree_host_x11.cc b/ui/aura/window_tree_host_x11.cc deleted file mode 100644 index 06c3a3f..0000000 --- a/ui/aura/window_tree_host_x11.cc +++ /dev/null
@@ -1,736 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/window_tree_host_x11.h" - -#include <strings.h> -#include <X11/cursorfont.h> -#include <X11/extensions/XInput2.h> -#include <X11/extensions/Xrandr.h> -#include <X11/Xatom.h> -#include <X11/Xcursor/Xcursor.h> -#include <X11/Xlib.h> - -#include <algorithm> -#include <limits> -#include <string> - -#include "base/basictypes.h" -#include "base/command_line.h" -#include "base/debug/trace_event.h" -#include "base/stl_util.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/string_util.h" -#include "base/strings/stringprintf.h" -#include "base/sys_info.h" -#include "ui/aura/client/cursor_client.h" -#include "ui/aura/env.h" -#include "ui/aura/window.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/base/cursor/cursor.h" -#include "ui/base/ui_base_switches.h" -#include "ui/base/view_prop.h" -#include "ui/base/x/x11_util.h" -#include "ui/compositor/compositor.h" -#include "ui/compositor/dip_util.h" -#include "ui/compositor/layer.h" -#include "ui/events/event.h" -#include "ui/events/event_switches.h" -#include "ui/events/event_utils.h" -#include "ui/events/keycodes/keyboard_codes.h" -#include "ui/events/platform/platform_event_observer.h" -#include "ui/events/platform/x11/x11_event_source.h" -#include "ui/events/x/device_data_manager_x11.h" -#include "ui/events/x/device_list_cache_x.h" -#include "ui/events/x/touch_factory_x11.h" -#include "ui/gfx/screen.h" - -using std::max; -using std::min; - -namespace aura { - -namespace { - -const char* kAtomsToCache[] = { - "WM_DELETE_WINDOW", - "_NET_WM_PING", - "_NET_WM_PID", - NULL -}; - -::Window FindEventTarget(const base::NativeEvent& xev) { - ::Window target = xev->xany.window; - if (xev->type == GenericEvent) - target = static_cast<XIDeviceEvent*>(xev->xcookie.data)->event; - return target; -} - -void SelectXInput2EventsForRootWindow(XDisplay* display, ::Window root_window) { - CHECK(ui::IsXInput2Available()); - unsigned char mask[XIMaskLen(XI_LASTEVENT)] = {}; - memset(mask, 0, sizeof(mask)); - - XISetMask(mask, XI_HierarchyChanged); - - XIEventMask evmask; - evmask.deviceid = XIAllDevices; - evmask.mask_len = sizeof(mask); - evmask.mask = mask; - XISelectEvents(display, root_window, &evmask, 1); - -#if defined(OS_CHROMEOS) - if (base::SysInfo::IsRunningOnChromeOS()) { - // It is necessary to listen for touch events on the root window for proper - // touch event calibration on Chrome OS, but this is not currently necessary - // on the desktop. This seems to fail in some cases (e.g. when logging - // in incognito). So select for non-touch events first, and then select for - // touch-events (but keep the other events in the mask, i.e. do not memset - // |mask| back to 0). - // TODO(sad): Figure out why this happens. http://crbug.com/153976 - XISetMask(mask, XI_TouchBegin); - XISetMask(mask, XI_TouchUpdate); - XISetMask(mask, XI_TouchEnd); - XISelectEvents(display, root_window, &evmask, 1); - } -#endif -} - -bool default_override_redirect = false; - -} // namespace - -namespace internal { - -// TODO(miletus) : Move this into DeviceDataManager. -// Accomplishes 2 tasks concerning touch event calibration: -// 1. Being a message-pump observer, -// routes all the touch events to the X root window, -// where they can be calibrated later. -// 2. Has the Calibrate method that does the actual bezel calibration, -// when invoked from X root window's event dispatcher. -class TouchEventCalibrate : public ui::PlatformEventObserver { - public: - TouchEventCalibrate() : left_(0), right_(0), top_(0), bottom_(0) { - if (ui::PlatformEventSource::GetInstance()) - ui::PlatformEventSource::GetInstance()->AddPlatformEventObserver(this); -#if defined(USE_XI2_MT) - std::vector<std::string> parts; - if (Tokenize(CommandLine::ForCurrentProcess()->GetSwitchValueASCII( - switches::kTouchCalibration), - ",", - &parts) >= 4) { - if (!base::StringToInt(parts[0], &left_)) - DLOG(ERROR) << "Incorrect left border calibration value passed."; - if (!base::StringToInt(parts[1], &right_)) - DLOG(ERROR) << "Incorrect right border calibration value passed."; - if (!base::StringToInt(parts[2], &top_)) - DLOG(ERROR) << "Incorrect top border calibration value passed."; - if (!base::StringToInt(parts[3], &bottom_)) - DLOG(ERROR) << "Incorrect bottom border calibration value passed."; - } -#endif // defined(USE_XI2_MT) - } - - virtual ~TouchEventCalibrate() { - if (ui::PlatformEventSource::GetInstance()) - ui::PlatformEventSource::GetInstance()->RemovePlatformEventObserver(this); - } - - // Modify the location of the |event|, - // expanding it from |bounds| to (|bounds| + bezels). - // Required when touchscreen is bigger than screen (i.e. has bezels), - // because we receive events in touchscreen coordinates, - // which need to be expanded when converting to screen coordinates, - // so that location on bezels will be outside of screen area. - void Calibrate(ui::TouchEvent* event, const gfx::Rect& bounds) { -#if defined(USE_XI2_MT) - int x = event->x(); - int y = event->y(); - - if (!left_ && !right_ && !top_ && !bottom_) - return; - - const int resolution_x = bounds.width(); - const int resolution_y = bounds.height(); - // The "grace area" (10% in this case) is to make it easier for the user to - // navigate to the corner. - const double kGraceAreaFraction = 0.1; - if (left_ || right_) { - // Offset the x position to the real - x -= left_; - // Check if we are in the grace area of the left side. - // Note: We might not want to do this when the gesture is locked? - if (x < 0 && x > -left_ * kGraceAreaFraction) - x = 0; - // Check if we are in the grace area of the right side. - // Note: We might not want to do this when the gesture is locked? - if (x > resolution_x - left_ && - x < resolution_x - left_ + right_ * kGraceAreaFraction) - x = resolution_x - left_; - // Scale the screen area back to the full resolution of the screen. - x = (x * resolution_x) / (resolution_x - (right_ + left_)); - } - if (top_ || bottom_) { - // When there is a top bezel we add our border, - y -= top_; - - // Check if we are in the grace area of the top side. - // Note: We might not want to do this when the gesture is locked? - if (y < 0 && y > -top_ * kGraceAreaFraction) - y = 0; - - // Check if we are in the grace area of the bottom side. - // Note: We might not want to do this when the gesture is locked? - if (y > resolution_y - top_ && - y < resolution_y - top_ + bottom_ * kGraceAreaFraction) - y = resolution_y - top_; - // Scale the screen area back to the full resolution of the screen. - y = (y * resolution_y) / (resolution_y - (bottom_ + top_)); - } - - // Set the modified coordinate back to the event. - if (event->root_location() == event->location()) { - // Usually those will be equal, - // if not, I am not sure what the correct value should be. - event->set_root_location(gfx::Point(x, y)); - } - event->set_location(gfx::Point(x, y)); -#endif // defined(USE_XI2_MT) - } - - private: - // ui::PlatformEventObserver: - virtual void WillProcessEvent(const ui::PlatformEvent& event) override { -#if defined(USE_XI2_MT) - if (event->type == GenericEvent && - (event->xgeneric.evtype == XI_TouchBegin || - event->xgeneric.evtype == XI_TouchUpdate || - event->xgeneric.evtype == XI_TouchEnd)) { - XIDeviceEvent* xievent = static_cast<XIDeviceEvent*>(event->xcookie.data); - xievent->event = xievent->root; - xievent->event_x = xievent->root_x; - xievent->event_y = xievent->root_y; - } -#endif // defined(USE_XI2_MT) - } - - virtual void DidProcessEvent(const ui::PlatformEvent& event) override {} - - // The difference in screen's native resolution pixels between - // the border of the touchscreen and the border of the screen, - // aka bezel sizes. - int left_; - int right_; - int top_; - int bottom_; - - DISALLOW_COPY_AND_ASSIGN(TouchEventCalibrate); -}; - -} // namespace internal - -//////////////////////////////////////////////////////////////////////////////// -// WindowTreeHostX11 - -WindowTreeHostX11::WindowTreeHostX11(const gfx::Rect& bounds) - : xdisplay_(gfx::GetXDisplay()), - xwindow_(0), - x_root_window_(DefaultRootWindow(xdisplay_)), - current_cursor_(ui::kCursorNull), - window_mapped_(false), - bounds_(bounds), - touch_calibrate_(new internal::TouchEventCalibrate), - atom_cache_(xdisplay_, kAtomsToCache) { - XSetWindowAttributes swa; - memset(&swa, 0, sizeof(swa)); - swa.background_pixmap = None; - swa.override_redirect = default_override_redirect; - xwindow_ = XCreateWindow( - xdisplay_, x_root_window_, - bounds.x(), bounds.y(), bounds.width(), bounds.height(), - 0, // border width - CopyFromParent, // depth - InputOutput, - CopyFromParent, // visual - CWBackPixmap | CWOverrideRedirect, - &swa); - if (ui::PlatformEventSource::GetInstance()) - ui::PlatformEventSource::GetInstance()->AddPlatformEventDispatcher(this); - - long event_mask = ButtonPressMask | ButtonReleaseMask | FocusChangeMask | - KeyPressMask | KeyReleaseMask | - EnterWindowMask | LeaveWindowMask | - ExposureMask | VisibilityChangeMask | - StructureNotifyMask | PropertyChangeMask | - PointerMotionMask; - XSelectInput(xdisplay_, xwindow_, event_mask); - XFlush(xdisplay_); - - if (ui::IsXInput2Available()) { - ui::TouchFactory::GetInstance()->SetupXI2ForXWindow(xwindow_); - SelectXInput2EventsForRootWindow(xdisplay_, x_root_window_); - } - - // TODO(erg): We currently only request window deletion events. We also - // should listen for activation events and anything else that GTK+ listens - // for, and do something useful. - ::Atom protocols[2]; - protocols[0] = atom_cache_.GetAtom("WM_DELETE_WINDOW"); - protocols[1] = atom_cache_.GetAtom("_NET_WM_PING"); - XSetWMProtocols(xdisplay_, xwindow_, protocols, 2); - - // We need a WM_CLIENT_MACHINE and WM_LOCALE_NAME value so we integrate with - // the desktop environment. - XSetWMProperties(xdisplay_, xwindow_, NULL, NULL, NULL, 0, NULL, NULL, NULL); - - // Likewise, the X server needs to know this window's pid so it knows which - // program to kill if the window hangs. - // XChangeProperty() expects "pid" to be long. - COMPILE_ASSERT(sizeof(long) >= sizeof(pid_t), pid_t_bigger_than_long); - long pid = getpid(); - XChangeProperty(xdisplay_, - xwindow_, - atom_cache_.GetAtom("_NET_WM_PID"), - XA_CARDINAL, - 32, - PropModeReplace, - reinterpret_cast<unsigned char*>(&pid), 1); - - // Allow subclasses to create and cache additional atoms. - atom_cache_.allow_uncached_atoms(); - - XRRSelectInput(xdisplay_, x_root_window_, - RRScreenChangeNotifyMask | RROutputChangeNotifyMask); - CreateCompositor(GetAcceleratedWidget()); -} - -WindowTreeHostX11::~WindowTreeHostX11() { - if (ui::PlatformEventSource::GetInstance()) - ui::PlatformEventSource::GetInstance()->RemovePlatformEventDispatcher(this); - - DestroyCompositor(); - DestroyDispatcher(); - XDestroyWindow(xdisplay_, xwindow_); -} - -bool WindowTreeHostX11::CanDispatchEvent(const ui::PlatformEvent& event) { - ::Window target = FindEventTarget(event); - return target == xwindow_ || target == x_root_window_; -} - -uint32_t WindowTreeHostX11::DispatchEvent(const ui::PlatformEvent& event) { - XEvent* xev = event; - if (FindEventTarget(xev) == x_root_window_) { - if (xev->type == GenericEvent) - DispatchXI2Event(xev); - return ui::POST_DISPATCH_NONE; - } - - if (xev->type == MotionNotify) { - // Discard all but the most recent motion event that targets the same - // window with unchanged state. - XEvent last_event; - while (XPending(xev->xany.display)) { - XEvent next_event; - XPeekEvent(xev->xany.display, &next_event); - if (next_event.type == MotionNotify && - next_event.xmotion.window == xev->xmotion.window && - next_event.xmotion.subwindow == xev->xmotion.subwindow && - next_event.xmotion.state == xev->xmotion.state) { - XNextEvent(xev->xany.display, &last_event); - xev = &last_event; - } else { - break; - } - } - } - - if ((xev->type == EnterNotify || xev->type == LeaveNotify) && - xev->xcrossing.detail == NotifyInferior) { - // Ignore EventNotify and LeaveNotify events from children of |xwindow_|. - // NativeViewGLSurfaceGLX adds a child to |xwindow_|. - // TODO(pkotwicz|tdanderson): Figure out whether the suppression is - // necessary. crbug.com/385716 - return ui::POST_DISPATCH_STOP_PROPAGATION; - } - - if (xev->type == EnterNotify || - xev->type == LeaveNotify || - xev->type == KeyPress || - xev->type == KeyRelease || - xev->type == ButtonPress || - xev->type == ButtonRelease || - xev->type == MotionNotify) { - switch (ui::EventTypeFromNative(xev)) { - case ui::ET_KEY_PRESSED: - case ui::ET_KEY_RELEASED: { - ui::KeyEvent keydown_event(xev); - SendEventToProcessor(&keydown_event); - break; - } - case ui::ET_MOUSE_MOVED: - case ui::ET_MOUSE_DRAGGED: - case ui::ET_MOUSE_ENTERED: - case ui::ET_MOUSE_EXITED: - case ui::ET_MOUSE_PRESSED: - case ui::ET_MOUSE_RELEASED: { - ui::MouseEvent mouse_event(xev); - if (xev->type == EnterNotify) { - aura::Window* root_window = window(); - client::CursorClient* cursor_client = - client::GetCursorClient(root_window); - if (cursor_client) { - const gfx::Display display = gfx::Screen::GetScreenFor( - root_window)->GetDisplayNearestWindow(root_window); - cursor_client->SetDisplay(display); - } - // EnterNotify creates ET_MOUSE_MOVE. Mark as synthesized as this is - // not a real mouse move event. - mouse_event.set_flags(mouse_event.flags() | ui::EF_IS_SYNTHESIZED); - } - - TranslateAndDispatchLocatedEvent(&mouse_event); - break; - } - case ui::ET_MOUSEWHEEL: { - ui::MouseWheelEvent mouseev(xev); - TranslateAndDispatchLocatedEvent(&mouseev); - break; - } - case ui::ET_UNKNOWN: - // No event is created for X11-release events for mouse-wheel buttons. - break; - default: - NOTREACHED(); - } - return ui::POST_DISPATCH_STOP_PROPAGATION; - } - - switch (xev->type) { - case Expose: { - gfx::Rect damage_rect(xev->xexpose.x, xev->xexpose.y, - xev->xexpose.width, xev->xexpose.height); - compositor()->ScheduleRedrawRect(damage_rect); - break; - } - case FocusOut: - if (xev->xfocus.mode != NotifyGrab) - OnHostLostWindowCapture(); - break; - case ConfigureNotify: { - DCHECK_EQ(xwindow_, xev->xconfigure.event); - DCHECK_EQ(xwindow_, xev->xconfigure.window); - // It's possible that the X window may be resized by some other means - // than from within aura (e.g. the X window manager can change the - // size). Make sure the root window size is maintained properly. - gfx::Rect bounds(xev->xconfigure.x, xev->xconfigure.y, - xev->xconfigure.width, xev->xconfigure.height); - bool size_changed = bounds_.size() != bounds.size(); - bool origin_changed = bounds_.origin() != bounds.origin(); - bounds_ = bounds; - OnConfigureNotify(); - if (size_changed) - OnHostResized(bounds.size()); - if (origin_changed) - OnHostMoved(bounds_.origin()); - break; - } - case GenericEvent: - DispatchXI2Event(xev); - break; - case ClientMessage: { - Atom message_type = static_cast<Atom>(xev->xclient.data.l[0]); - if (message_type == atom_cache_.GetAtom("WM_DELETE_WINDOW")) { - // We have received a close message from the window manager. - OnHostCloseRequested(); - } else if (message_type == atom_cache_.GetAtom("_NET_WM_PING")) { - XEvent reply_event = *xev; - reply_event.xclient.window = x_root_window_; - - XSendEvent(xdisplay_, - reply_event.xclient.window, - False, - SubstructureRedirectMask | SubstructureNotifyMask, - &reply_event); - XFlush(xdisplay_); - } - break; - } - case MappingNotify: { - switch (xev->xmapping.request) { - case MappingModifier: - case MappingKeyboard: - XRefreshKeyboardMapping(&xev->xmapping); - break; - case MappingPointer: - ui::DeviceDataManagerX11::GetInstance()->UpdateButtonMap(); - break; - default: - NOTIMPLEMENTED() << " Unknown request: " << xev->xmapping.request; - break; - } - break; - } - } - return ui::POST_DISPATCH_STOP_PROPAGATION; -} - -ui::EventSource* WindowTreeHostX11::GetEventSource() { - return this; -} - -gfx::AcceleratedWidget WindowTreeHostX11::GetAcceleratedWidget() { - return xwindow_; -} - -void WindowTreeHostX11::Show() { - if (!window_mapped_) { - // Before we map the window, set size hints. Otherwise, some window managers - // will ignore toplevel XMoveWindow commands. - XSizeHints size_hints; - size_hints.flags = PPosition | PWinGravity; - size_hints.x = bounds_.x(); - size_hints.y = bounds_.y(); - // Set StaticGravity so that the window position is not affected by the - // frame width when running with window manager. - size_hints.win_gravity = StaticGravity; - XSetWMNormalHints(xdisplay_, xwindow_, &size_hints); - - XMapWindow(xdisplay_, xwindow_); - - // We now block until our window is mapped. Some X11 APIs will crash and - // burn if passed |xwindow_| before the window is mapped, and XMapWindow is - // asynchronous. - if (ui::X11EventSource::GetInstance()) - ui::X11EventSource::GetInstance()->BlockUntilWindowMapped(xwindow_); - window_mapped_ = true; - } -} - -void WindowTreeHostX11::Hide() { - if (window_mapped_) { - XWithdrawWindow(xdisplay_, xwindow_, 0); - window_mapped_ = false; - } -} - -gfx::Rect WindowTreeHostX11::GetBounds() const { - return bounds_; -} - -void WindowTreeHostX11::SetBounds(const gfx::Rect& bounds) { - // Even if the host window's size doesn't change, aura's root window - // size, which is in DIP, changes when the scale changes. - float current_scale = compositor()->device_scale_factor(); - float new_scale = gfx::Screen::GetScreenFor(window())-> - GetDisplayNearestWindow(window()).device_scale_factor(); - bool origin_changed = bounds_.origin() != bounds.origin(); - bool size_changed = bounds_.size() != bounds.size(); - XWindowChanges changes = {0}; - unsigned value_mask = 0; - - if (size_changed) { - changes.width = bounds.width(); - changes.height = bounds.height(); - value_mask = CWHeight | CWWidth; - } - - if (origin_changed) { - changes.x = bounds.x(); - changes.y = bounds.y(); - value_mask |= CWX | CWY; - } - if (value_mask) - XConfigureWindow(xdisplay_, xwindow_, value_mask, &changes); - - // Assume that the resize will go through as requested, which should be the - // case if we're running without a window manager. If there's a window - // manager, it can modify or ignore the request, but (per ICCCM) we'll get a - // (possibly synthetic) ConfigureNotify about the actual size and correct - // |bounds_| later. - bounds_ = bounds; - if (origin_changed) - OnHostMoved(bounds.origin()); - if (size_changed || current_scale != new_scale) { - OnHostResized(bounds.size()); - } else { - window()->SchedulePaintInRect(window()->bounds()); - } -} - -gfx::Point WindowTreeHostX11::GetLocationOnNativeScreen() const { - return bounds_.origin(); -} - -void WindowTreeHostX11::SetCapture() { - // TODO(oshima): Grab x input. -} - -void WindowTreeHostX11::ReleaseCapture() { - // TODO(oshima): Release x input. -} - -void WindowTreeHostX11::PostNativeEvent( - const base::NativeEvent& native_event) { - DCHECK(xwindow_); - DCHECK(xdisplay_); - XEvent xevent = *native_event; - xevent.xany.display = xdisplay_; - xevent.xany.window = xwindow_; - - switch (xevent.type) { - case EnterNotify: - case LeaveNotify: - case MotionNotify: - case KeyPress: - case KeyRelease: - case ButtonPress: - case ButtonRelease: { - // The fields used below are in the same place for all of events - // above. Using xmotion from XEvent's unions to avoid repeating - // the code. - xevent.xmotion.root = x_root_window_; - xevent.xmotion.time = CurrentTime; - - gfx::Point point(xevent.xmotion.x, xevent.xmotion.y); - ConvertPointToNativeScreen(&point); - xevent.xmotion.x_root = point.x(); - xevent.xmotion.y_root = point.y(); - } - default: - break; - } - XSendEvent(xdisplay_, xwindow_, False, 0, &xevent); - XFlush(xdisplay_); -} - -void WindowTreeHostX11::SetCursorNative(gfx::NativeCursor cursor) { - if (cursor == current_cursor_) - return; - current_cursor_ = cursor; - SetCursorInternal(cursor); -} - -void WindowTreeHostX11::MoveCursorToNative(const gfx::Point& location) { - XWarpPointer(xdisplay_, None, x_root_window_, 0, 0, 0, 0, - bounds_.x() + location.x(), - bounds_.y() + location.y()); -} - -void WindowTreeHostX11::OnCursorVisibilityChangedNative(bool show) { -} - -ui::EventProcessor* WindowTreeHostX11::GetEventProcessor() { - return dispatcher(); -} - -void WindowTreeHostX11::DispatchXI2Event(const base::NativeEvent& event) { - ui::TouchFactory* factory = ui::TouchFactory::GetInstance(); - XEvent* xev = event; - XIDeviceEvent* xiev = static_cast<XIDeviceEvent*>(xev->xcookie.data); - if (!factory->ShouldProcessXI2Event(xev)) - return; - - TRACE_EVENT1("input", "WindowTreeHostX11::DispatchXI2Event", - "event_latency_us", - (ui::EventTimeForNow() - ui::EventTimeFromNative(event)). - InMicroseconds()); - - int num_coalesced = 0; - XEvent last_event; - if (xev->xgeneric.evtype == XI_Motion) { - // If this is a motion event, we want to coalesce all pending motion - // events that are at the top of the queue. Note, we don't coalesce - // touch update events here. - num_coalesced = ui::CoalescePendingMotionEvents(xev, &last_event); - if (num_coalesced > 0) - xev = &last_event; - } - ui::EventType type = ui::EventTypeFromNative(xev); - - switch (type) { - case ui::ET_TOUCH_MOVED: - case ui::ET_TOUCH_PRESSED: - case ui::ET_TOUCH_CANCELLED: - case ui::ET_TOUCH_RELEASED: { - ui::TouchEvent touchev(xev); - if (ui::DeviceDataManagerX11::GetInstance()->TouchEventNeedsCalibrate( - xiev->deviceid)) { - touch_calibrate_->Calibrate(&touchev, bounds_); - } - TranslateAndDispatchLocatedEvent(&touchev); - break; - } - case ui::ET_MOUSE_MOVED: - case ui::ET_MOUSE_DRAGGED: - case ui::ET_MOUSE_PRESSED: - case ui::ET_MOUSE_RELEASED: - case ui::ET_MOUSE_ENTERED: - case ui::ET_MOUSE_EXITED: { - ui::MouseEvent mouseev(xev); - TranslateAndDispatchLocatedEvent(&mouseev); - break; - } - case ui::ET_MOUSEWHEEL: { - ui::MouseWheelEvent mouseev(xev); - TranslateAndDispatchLocatedEvent(&mouseev); - break; - } - case ui::ET_SCROLL_FLING_START: - case ui::ET_SCROLL_FLING_CANCEL: - case ui::ET_SCROLL: { - ui::ScrollEvent scrollev(xev); - SendEventToProcessor(&scrollev); - break; - } - case ui::ET_KEY_PRESSED: - case ui::ET_KEY_RELEASED: { - ui::KeyEvent key_event(xev); - SendEventToProcessor(&key_event); - break; - } - case ui::ET_UMA_DATA: - break; - case ui::ET_UNKNOWN: - break; - default: - NOTREACHED(); - } - - // If we coalesced an event we need to free its cookie. - if (num_coalesced > 0) - XFreeEventData(xev->xgeneric.display, &last_event.xcookie); -} - -void WindowTreeHostX11::SetCursorInternal(gfx::NativeCursor cursor) { - XDefineCursor(xdisplay_, xwindow_, cursor.platform()); -} - -void WindowTreeHostX11::OnConfigureNotify() {} - -void WindowTreeHostX11::TranslateAndDispatchLocatedEvent( - ui::LocatedEvent* event) { - SendEventToProcessor(event); -} - -// static -WindowTreeHost* WindowTreeHost::Create(const gfx::Rect& bounds) { - return new WindowTreeHostX11(bounds); -} - -// static -gfx::Size WindowTreeHost::GetNativeScreenSize() { - ::XDisplay* xdisplay = gfx::GetXDisplay(); - return gfx::Size(DisplayWidth(xdisplay, 0), DisplayHeight(xdisplay, 0)); -} - -namespace test { - -void SetUseOverrideRedirectWindowByDefault(bool override_redirect) { - default_override_redirect = override_redirect; -} - -} // namespace test -} // namespace aura
diff --git a/ui/aura/window_tree_host_x11.h b/ui/aura/window_tree_host_x11.h deleted file mode 100644 index 1c05bf0..0000000 --- a/ui/aura/window_tree_host_x11.h +++ /dev/null
@@ -1,117 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_AURA_WINDOW_TREE_HOST_X11_H_ -#define UI_AURA_WINDOW_TREE_HOST_X11_H_ - -#include "base/memory/scoped_ptr.h" -#include "ui/aura/aura_export.h" -#include "ui/aura/window_tree_host.h" -#include "ui/events/event_source.h" -#include "ui/events/platform/platform_event_dispatcher.h" -#include "ui/gfx/insets.h" -#include "ui/gfx/rect.h" -#include "ui/gfx/x/x11_atom_cache.h" - -// X forward decls to avoid including Xlib.h in a header file. -typedef struct _XDisplay XDisplay; -typedef unsigned long XID; -typedef XID Window; - -namespace ui { -class MouseEvent; -} - -namespace aura { - -namespace internal { -class TouchEventCalibrate; -} - -class AURA_EXPORT WindowTreeHostX11 : public WindowTreeHost, - public ui::EventSource, - public ui::PlatformEventDispatcher { - - public: - explicit WindowTreeHostX11(const gfx::Rect& bounds); - virtual ~WindowTreeHostX11(); - - // ui::PlatformEventDispatcher: - virtual bool CanDispatchEvent(const ui::PlatformEvent& event) override; - virtual uint32_t DispatchEvent(const ui::PlatformEvent& event) override; - - // WindowTreeHost: - virtual ui::EventSource* GetEventSource() override; - virtual gfx::AcceleratedWidget GetAcceleratedWidget() override; - virtual void Show() override; - virtual void Hide() override; - virtual gfx::Rect GetBounds() const override; - virtual void SetBounds(const gfx::Rect& bounds) override; - virtual gfx::Point GetLocationOnNativeScreen() const override; - virtual void SetCapture() override; - virtual void ReleaseCapture() override; - virtual void PostNativeEvent(const base::NativeEvent& event) override; - virtual void SetCursorNative(gfx::NativeCursor cursor_type) override; - virtual void MoveCursorToNative(const gfx::Point& location) override; - virtual void OnCursorVisibilityChangedNative(bool show) override; - - // ui::EventSource overrides. - virtual ui::EventProcessor* GetEventProcessor() override; - - protected: - // Called when X Configure Notify event is recevied. - virtual void OnConfigureNotify(); - - // Translates the native mouse location into screen coordinates and - // dispatches the event via WindowEventDispatcher. - virtual void TranslateAndDispatchLocatedEvent(ui::LocatedEvent* event); - - ::Window x_root_window() { return x_root_window_; } - XDisplay* xdisplay() { return xdisplay_; } - const gfx::Rect bounds() const { return bounds_; } - ui::X11AtomCache* atom_cache() { return &atom_cache_; } - - private: - // Dispatches XI2 events. Note that some events targetted for the X root - // window are dispatched to the aura root window (e.g. touch events after - // calibration). - void DispatchXI2Event(const base::NativeEvent& event); - - // Sets the cursor on |xwindow_| to |cursor|. Does not check or update - // |current_cursor_|. - void SetCursorInternal(gfx::NativeCursor cursor); - - // The display and the native X window hosting the root window. - XDisplay* xdisplay_; - ::Window xwindow_; - - // The native root window. - ::Window x_root_window_; - - // Current Aura cursor. - gfx::NativeCursor current_cursor_; - - // Is the window mapped to the screen? - bool window_mapped_; - - // The bounds of |xwindow_|. - gfx::Rect bounds_; - - scoped_ptr<internal::TouchEventCalibrate> touch_calibrate_; - - ui::X11AtomCache atom_cache_; - - DISALLOW_COPY_AND_ASSIGN(WindowTreeHostX11); -}; - -namespace test { - -// Set the default value of the override redirect flag used to -// create a X window for WindowTreeHostX11. -AURA_EXPORT void SetUseOverrideRedirectWindowByDefault(bool override_redirect); - -} // namespace test -} // namespace aura - -#endif // UI_AURA_WINDOW_TREE_HOST_X11_H_
diff --git a/ui/aura/window_unittest.cc b/ui/aura/window_unittest.cc deleted file mode 100644 index 486bc6b..0000000 --- a/ui/aura/window_unittest.cc +++ /dev/null
@@ -1,3499 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/window.h" - -#include <string> -#include <utility> -#include <vector> - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/string_util.h" -#include "base/strings/stringprintf.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/aura/client/capture_client.h" -#include "ui/aura/client/focus_change_observer.h" -#include "ui/aura/client/visibility_client.h" -#include "ui/aura/client/window_tree_client.h" -#include "ui/aura/test/aura_test_base.h" -#include "ui/aura/test/aura_test_utils.h" -#include "ui/aura/test/test_window_delegate.h" -#include "ui/aura/test/test_windows.h" -#include "ui/aura/test/window_test_api.h" -#include "ui/aura/window_delegate.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/aura/window_observer.h" -#include "ui/aura/window_property.h" -#include "ui/aura/window_tree_host.h" -#include "ui/base/hit_test.h" -#include "ui/compositor/layer.h" -#include "ui/compositor/layer_animation_observer.h" -#include "ui/compositor/scoped_animation_duration_scale_mode.h" -#include "ui/compositor/scoped_layer_animation_settings.h" -#include "ui/compositor/test/test_layers.h" -#include "ui/events/event.h" -#include "ui/events/event_utils.h" -#include "ui/events/gestures/gesture_configuration.h" -#include "ui/events/keycodes/keyboard_codes.h" -#include "ui/events/test/event_generator.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/screen.h" -#include "ui/gfx/skia_util.h" -#include "ui/gfx/vector2d.h" - -DECLARE_WINDOW_PROPERTY_TYPE(const char*) -DECLARE_WINDOW_PROPERTY_TYPE(int) - -namespace aura { -namespace test { - -class WindowTest : public AuraTestBase { - public: - WindowTest() : max_separation_(0) { - } - - virtual void SetUp() override { - AuraTestBase::SetUp(); - // TODO: there needs to be an easier way to do this. - max_separation_ = ui::GestureConfiguration:: - max_separation_for_gesture_touches_in_pixels(); - ui::GestureConfiguration:: - set_max_separation_for_gesture_touches_in_pixels(0); - } - - virtual void TearDown() override { - AuraTestBase::TearDown(); - ui::GestureConfiguration:: - set_max_separation_for_gesture_touches_in_pixels(max_separation_); - } - - private: - float max_separation_; - - DISALLOW_COPY_AND_ASSIGN(WindowTest); -}; - -namespace { - -// Used for verifying destruction methods are invoked. -class DestroyTrackingDelegateImpl : public TestWindowDelegate { - public: - DestroyTrackingDelegateImpl() - : destroying_count_(0), - destroyed_count_(0), - in_destroying_(false) {} - - void clear_destroying_count() { destroying_count_ = 0; } - int destroying_count() const { return destroying_count_; } - - void clear_destroyed_count() { destroyed_count_ = 0; } - int destroyed_count() const { return destroyed_count_; } - - bool in_destroying() const { return in_destroying_; } - - virtual void OnWindowDestroying(Window* window) override { - EXPECT_FALSE(in_destroying_); - in_destroying_ = true; - destroying_count_++; - } - - virtual void OnWindowDestroyed(Window* window) override { - EXPECT_TRUE(in_destroying_); - in_destroying_ = false; - destroyed_count_++; - } - - private: - int destroying_count_; - int destroyed_count_; - bool in_destroying_; - - DISALLOW_COPY_AND_ASSIGN(DestroyTrackingDelegateImpl); -}; - -// Used to verify that when OnWindowDestroying is invoked the parent is also -// is in the process of being destroyed. -class ChildWindowDelegateImpl : public DestroyTrackingDelegateImpl { - public: - explicit ChildWindowDelegateImpl( - DestroyTrackingDelegateImpl* parent_delegate) - : parent_delegate_(parent_delegate) { - } - - virtual void OnWindowDestroying(Window* window) override { - EXPECT_TRUE(parent_delegate_->in_destroying()); - DestroyTrackingDelegateImpl::OnWindowDestroying(window); - } - - private: - DestroyTrackingDelegateImpl* parent_delegate_; - - DISALLOW_COPY_AND_ASSIGN(ChildWindowDelegateImpl); -}; - -// Used to verify that a Window is removed from its parent when -// OnWindowDestroyed is called. -class DestroyOrphanDelegate : public TestWindowDelegate { - public: - DestroyOrphanDelegate() : window_(NULL) { - } - - void set_window(Window* window) { window_ = window; } - - virtual void OnWindowDestroyed(Window* window) override { - EXPECT_FALSE(window_->parent()); - } - - private: - Window* window_; - DISALLOW_COPY_AND_ASSIGN(DestroyOrphanDelegate); -}; - -// Used in verifying mouse capture. -class CaptureWindowDelegateImpl : public TestWindowDelegate { - public: - CaptureWindowDelegateImpl() { - ResetCounts(); - } - - void ResetCounts() { - capture_changed_event_count_ = 0; - capture_lost_count_ = 0; - mouse_event_count_ = 0; - touch_event_count_ = 0; - gesture_event_count_ = 0; - } - - int capture_changed_event_count() const { - return capture_changed_event_count_; - } - int capture_lost_count() const { return capture_lost_count_; } - int mouse_event_count() const { return mouse_event_count_; } - int touch_event_count() const { return touch_event_count_; } - int gesture_event_count() const { return gesture_event_count_; } - - virtual void OnMouseEvent(ui::MouseEvent* event) override { - if (event->type() == ui::ET_MOUSE_CAPTURE_CHANGED) - capture_changed_event_count_++; - mouse_event_count_++; - } - virtual void OnTouchEvent(ui::TouchEvent* event) override { - touch_event_count_++; - } - virtual void OnGestureEvent(ui::GestureEvent* event) override { - gesture_event_count_++; - } - virtual void OnCaptureLost() override { - capture_lost_count_++; - } - - private: - int capture_changed_event_count_; - int capture_lost_count_; - int mouse_event_count_; - int touch_event_count_; - int gesture_event_count_; - - DISALLOW_COPY_AND_ASSIGN(CaptureWindowDelegateImpl); -}; - -// Keeps track of the location of the gesture. -class GestureTrackPositionDelegate : public TestWindowDelegate { - public: - GestureTrackPositionDelegate() {} - - virtual void OnGestureEvent(ui::GestureEvent* event) override { - position_ = event->location(); - event->StopPropagation(); - } - - const gfx::Point& position() const { return position_; } - - private: - gfx::Point position_; - - DISALLOW_COPY_AND_ASSIGN(GestureTrackPositionDelegate); -}; - -base::TimeDelta getTime() { - return ui::EventTimeForNow(); -} - -class SelfEventHandlingWindowDelegate : public TestWindowDelegate { - public: - SelfEventHandlingWindowDelegate() {} - - virtual bool ShouldDescendIntoChildForEventHandling( - Window* child, - const gfx::Point& location) override { - return false; - } - - private: - DISALLOW_COPY_AND_ASSIGN(SelfEventHandlingWindowDelegate); -}; - -// The delegate deletes itself when the window is being destroyed. -class DestroyWindowDelegate : public TestWindowDelegate { - public: - DestroyWindowDelegate() {} - - private: - virtual ~DestroyWindowDelegate() {} - - // Overridden from WindowDelegate. - virtual void OnWindowDestroyed(Window* window) override { - delete this; - } - - DISALLOW_COPY_AND_ASSIGN(DestroyWindowDelegate); -}; - -} // namespace - -TEST_F(WindowTest, GetChildById) { - scoped_ptr<Window> w1(CreateTestWindowWithId(1, root_window())); - scoped_ptr<Window> w11(CreateTestWindowWithId(11, w1.get())); - scoped_ptr<Window> w111(CreateTestWindowWithId(111, w11.get())); - scoped_ptr<Window> w12(CreateTestWindowWithId(12, w1.get())); - - EXPECT_EQ(NULL, w1->GetChildById(57)); - EXPECT_EQ(w12.get(), w1->GetChildById(12)); - EXPECT_EQ(w111.get(), w1->GetChildById(111)); -} - -// Make sure that Window::Contains correctly handles children, grandchildren, -// and not containing NULL or parents. -TEST_F(WindowTest, Contains) { - Window parent(NULL); - parent.Init(aura::WINDOW_LAYER_NOT_DRAWN); - Window child1(NULL); - child1.Init(aura::WINDOW_LAYER_NOT_DRAWN); - Window child2(NULL); - child2.Init(aura::WINDOW_LAYER_NOT_DRAWN); - - parent.AddChild(&child1); - child1.AddChild(&child2); - - EXPECT_TRUE(parent.Contains(&parent)); - EXPECT_TRUE(parent.Contains(&child1)); - EXPECT_TRUE(parent.Contains(&child2)); - - EXPECT_FALSE(parent.Contains(NULL)); - EXPECT_FALSE(child1.Contains(&parent)); - EXPECT_FALSE(child2.Contains(&child1)); -} - -TEST_F(WindowTest, ContainsPointInRoot) { - scoped_ptr<Window> w( - CreateTestWindow(SK_ColorWHITE, 1, gfx::Rect(10, 10, 5, 5), - root_window())); - EXPECT_FALSE(w->ContainsPointInRoot(gfx::Point(9, 9))); - EXPECT_TRUE(w->ContainsPointInRoot(gfx::Point(10, 10))); - EXPECT_TRUE(w->ContainsPointInRoot(gfx::Point(14, 14))); - EXPECT_FALSE(w->ContainsPointInRoot(gfx::Point(15, 15))); - EXPECT_FALSE(w->ContainsPointInRoot(gfx::Point(20, 20))); -} - -TEST_F(WindowTest, ContainsPoint) { - scoped_ptr<Window> w( - CreateTestWindow(SK_ColorWHITE, 1, gfx::Rect(10, 10, 5, 5), - root_window())); - EXPECT_TRUE(w->ContainsPoint(gfx::Point(0, 0))); - EXPECT_TRUE(w->ContainsPoint(gfx::Point(4, 4))); - EXPECT_FALSE(w->ContainsPoint(gfx::Point(5, 5))); - EXPECT_FALSE(w->ContainsPoint(gfx::Point(10, 10))); -} - -TEST_F(WindowTest, ConvertPointToWindow) { - // Window::ConvertPointToWindow is mostly identical to - // Layer::ConvertPointToLayer, except NULL values for |source| are permitted, - // in which case the function just returns. - scoped_ptr<Window> w1(CreateTestWindowWithId(1, root_window())); - gfx::Point reference_point(100, 100); - gfx::Point test_point = reference_point; - Window::ConvertPointToTarget(NULL, w1.get(), &test_point); - EXPECT_EQ(reference_point, test_point); -} - -TEST_F(WindowTest, MoveCursorTo) { - scoped_ptr<Window> w1( - CreateTestWindow(SK_ColorWHITE, 1, gfx::Rect(10, 10, 500, 500), - root_window())); - scoped_ptr<Window> w11( - CreateTestWindow(SK_ColorGREEN, 11, gfx::Rect(5, 5, 100, 100), w1.get())); - scoped_ptr<Window> w111( - CreateTestWindow(SK_ColorCYAN, 111, gfx::Rect(5, 5, 75, 75), w11.get())); - scoped_ptr<Window> w1111( - CreateTestWindow(SK_ColorRED, 1111, gfx::Rect(5, 5, 50, 50), w111.get())); - - Window* root = root_window(); - root->MoveCursorTo(gfx::Point(10, 10)); - EXPECT_EQ("10,10", - gfx::Screen::GetScreenFor(root)->GetCursorScreenPoint().ToString()); - w1->MoveCursorTo(gfx::Point(10, 10)); - EXPECT_EQ("20,20", - gfx::Screen::GetScreenFor(root)->GetCursorScreenPoint().ToString()); - w11->MoveCursorTo(gfx::Point(10, 10)); - EXPECT_EQ("25,25", - gfx::Screen::GetScreenFor(root)->GetCursorScreenPoint().ToString()); - w111->MoveCursorTo(gfx::Point(10, 10)); - EXPECT_EQ("30,30", - gfx::Screen::GetScreenFor(root)->GetCursorScreenPoint().ToString()); - w1111->MoveCursorTo(gfx::Point(10, 10)); - EXPECT_EQ("35,35", - gfx::Screen::GetScreenFor(root)->GetCursorScreenPoint().ToString()); -} - -TEST_F(WindowTest, ContainsMouse) { - scoped_ptr<Window> w( - CreateTestWindow(SK_ColorWHITE, 1, gfx::Rect(10, 10, 500, 500), - root_window())); - w->Show(); - WindowTestApi w_test_api(w.get()); - Window* root = root_window(); - root->MoveCursorTo(gfx::Point(10, 10)); - EXPECT_TRUE(w_test_api.ContainsMouse()); - root->MoveCursorTo(gfx::Point(9, 10)); - EXPECT_FALSE(w_test_api.ContainsMouse()); -} - -// Test Window::ConvertPointToWindow() with transform to root_window. -TEST_F(WindowTest, MoveCursorToWithTransformRootWindow) { - gfx::Transform transform; - transform.Translate(100.0, 100.0); - transform.Rotate(90.0); - transform.Scale(2.0, 5.0); - host()->SetRootTransform(transform); - host()->MoveCursorTo(gfx::Point(10, 10)); -#if !defined(OS_WIN) - // TODO(yoshiki): fix this to build on Windows. See crbug.com/133413.OD - EXPECT_EQ("50,120", QueryLatestMousePositionRequestInHost(host()).ToString()); -#endif - EXPECT_EQ("10,10", gfx::Screen::GetScreenFor( - root_window())->GetCursorScreenPoint().ToString()); -} - -// Tests Window::ConvertPointToWindow() with transform to non-root windows. -TEST_F(WindowTest, MoveCursorToWithTransformWindow) { - scoped_ptr<Window> w1( - CreateTestWindow(SK_ColorWHITE, 1, gfx::Rect(10, 10, 500, 500), - root_window())); - - gfx::Transform transform1; - transform1.Scale(2, 2); - w1->SetTransform(transform1); - w1->MoveCursorTo(gfx::Point(10, 10)); - EXPECT_EQ("30,30", - gfx::Screen::GetScreenFor(w1.get())->GetCursorScreenPoint().ToString()); - - gfx::Transform transform2; - transform2.Translate(-10, 20); - w1->SetTransform(transform2); - w1->MoveCursorTo(gfx::Point(10, 10)); - EXPECT_EQ("10,40", - gfx::Screen::GetScreenFor(w1.get())->GetCursorScreenPoint().ToString()); - - gfx::Transform transform3; - transform3.Rotate(90.0); - w1->SetTransform(transform3); - w1->MoveCursorTo(gfx::Point(5, 5)); - EXPECT_EQ("5,15", - gfx::Screen::GetScreenFor(w1.get())->GetCursorScreenPoint().ToString()); - - gfx::Transform transform4; - transform4.Translate(100.0, 100.0); - transform4.Rotate(90.0); - transform4.Scale(2.0, 5.0); - w1->SetTransform(transform4); - w1->MoveCursorTo(gfx::Point(10, 10)); - EXPECT_EQ("60,130", - gfx::Screen::GetScreenFor(w1.get())->GetCursorScreenPoint().ToString()); -} - -// Test Window::ConvertPointToWindow() with complex transforms to both root and -// non-root windows. -// Test Window::ConvertPointToWindow() with transform to root_window. -TEST_F(WindowTest, MoveCursorToWithComplexTransform) { - scoped_ptr<Window> w1( - CreateTestWindow(SK_ColorWHITE, 1, gfx::Rect(10, 10, 500, 500), - root_window())); - scoped_ptr<Window> w11( - CreateTestWindow(SK_ColorGREEN, 11, gfx::Rect(5, 5, 100, 100), w1.get())); - scoped_ptr<Window> w111( - CreateTestWindow(SK_ColorCYAN, 111, gfx::Rect(5, 5, 75, 75), w11.get())); - scoped_ptr<Window> w1111( - CreateTestWindow(SK_ColorRED, 1111, gfx::Rect(5, 5, 50, 50), w111.get())); - - Window* root = root_window(); - - // The root window expects transforms that produce integer rects. - gfx::Transform root_transform; - root_transform.Translate(60.0, 70.0); - root_transform.Rotate(-90.0); - root_transform.Translate(-50.0, -50.0); - root_transform.Scale(2.0, 3.0); - - gfx::Transform transform; - transform.Translate(10.0, 20.0); - transform.Rotate(10.0); - transform.Scale(0.3f, 0.5f); - host()->SetRootTransform(root_transform); - w1->SetTransform(transform); - w11->SetTransform(transform); - w111->SetTransform(transform); - w1111->SetTransform(transform); - - w1111->MoveCursorTo(gfx::Point(10, 10)); - -#if !defined(OS_WIN) - // TODO(yoshiki): fix this to build on Windows. See crbug.com/133413. - EXPECT_EQ("169,80", QueryLatestMousePositionRequestInHost(host()).ToString()); -#endif - EXPECT_EQ("20,53", - gfx::Screen::GetScreenFor(root)->GetCursorScreenPoint().ToString()); -} - -TEST_F(WindowTest, GetEventHandlerForPoint) { - scoped_ptr<Window> w1( - CreateTestWindow(SK_ColorWHITE, 1, gfx::Rect(10, 10, 500, 500), - root_window())); - scoped_ptr<Window> w11( - CreateTestWindow(SK_ColorGREEN, 11, gfx::Rect(5, 5, 100, 100), w1.get())); - scoped_ptr<Window> w111( - CreateTestWindow(SK_ColorCYAN, 111, gfx::Rect(5, 5, 75, 75), w11.get())); - scoped_ptr<Window> w1111( - CreateTestWindow(SK_ColorRED, 1111, gfx::Rect(5, 5, 50, 50), w111.get())); - scoped_ptr<Window> w12( - CreateTestWindow(SK_ColorMAGENTA, 12, gfx::Rect(10, 420, 25, 25), - w1.get())); - scoped_ptr<Window> w121( - CreateTestWindow(SK_ColorYELLOW, 121, gfx::Rect(5, 5, 5, 5), w12.get())); - scoped_ptr<Window> w13( - CreateTestWindow(SK_ColorGRAY, 13, gfx::Rect(5, 470, 50, 50), w1.get())); - - Window* root = root_window(); - w1->parent()->SetBounds(gfx::Rect(500, 500)); - EXPECT_EQ(NULL, root->GetEventHandlerForPoint(gfx::Point(5, 5))); - EXPECT_EQ(w1.get(), root->GetEventHandlerForPoint(gfx::Point(11, 11))); - EXPECT_EQ(w11.get(), root->GetEventHandlerForPoint(gfx::Point(16, 16))); - EXPECT_EQ(w111.get(), root->GetEventHandlerForPoint(gfx::Point(21, 21))); - EXPECT_EQ(w1111.get(), root->GetEventHandlerForPoint(gfx::Point(26, 26))); - EXPECT_EQ(w12.get(), root->GetEventHandlerForPoint(gfx::Point(21, 431))); - EXPECT_EQ(w121.get(), root->GetEventHandlerForPoint(gfx::Point(26, 436))); - EXPECT_EQ(w13.get(), root->GetEventHandlerForPoint(gfx::Point(26, 481))); -} - -TEST_F(WindowTest, GetEventHandlerForPointWithOverride) { - // If our child is flush to our top-left corner he gets events just inside the - // window edges. - scoped_ptr<Window> parent( - CreateTestWindow(SK_ColorWHITE, 1, gfx::Rect(10, 20, 400, 500), - root_window())); - scoped_ptr<Window> child( - CreateTestWindow(SK_ColorRED, 2, gfx::Rect(0, 0, 60, 70), parent.get())); - EXPECT_EQ(child.get(), parent->GetEventHandlerForPoint(gfx::Point(0, 0))); - EXPECT_EQ(child.get(), parent->GetEventHandlerForPoint(gfx::Point(1, 1))); - - // We can override the hit test bounds of the parent to make the parent grab - // events along that edge. - parent->set_hit_test_bounds_override_inner(gfx::Insets(1, 1, 1, 1)); - EXPECT_EQ(parent.get(), parent->GetEventHandlerForPoint(gfx::Point(0, 0))); - EXPECT_EQ(child.get(), parent->GetEventHandlerForPoint(gfx::Point(1, 1))); -} - -TEST_F(WindowTest, GetEventHandlerForPointWithOverrideDescendingOrder) { - scoped_ptr<SelfEventHandlingWindowDelegate> parent_delegate( - new SelfEventHandlingWindowDelegate); - scoped_ptr<Window> parent(CreateTestWindowWithDelegate( - parent_delegate.get(), 1, gfx::Rect(10, 20, 400, 500), root_window())); - scoped_ptr<Window> child( - CreateTestWindow(SK_ColorRED, 2, gfx::Rect(0, 0, 390, 480), - parent.get())); - - // We can override ShouldDescendIntoChildForEventHandling to make the parent - // grab all events. - EXPECT_EQ(parent.get(), parent->GetEventHandlerForPoint(gfx::Point(0, 0))); - EXPECT_EQ(parent.get(), parent->GetEventHandlerForPoint(gfx::Point(50, 50))); -} - -TEST_F(WindowTest, GetTopWindowContainingPoint) { - Window* root = root_window(); - root->SetBounds(gfx::Rect(0, 0, 300, 300)); - - scoped_ptr<Window> w1( - CreateTestWindow(SK_ColorWHITE, 1, gfx::Rect(10, 10, 100, 100), - root_window())); - scoped_ptr<Window> w11( - CreateTestWindow(SK_ColorGREEN, 11, gfx::Rect(0, 0, 120, 120), w1.get())); - - scoped_ptr<Window> w2( - CreateTestWindow(SK_ColorRED, 2, gfx::Rect(5, 5, 55, 55), - root_window())); - - scoped_ptr<Window> w3( - CreateTestWindowWithDelegate( - NULL, 3, gfx::Rect(200, 200, 100, 100), root_window())); - scoped_ptr<Window> w31( - CreateTestWindow(SK_ColorCYAN, 31, gfx::Rect(0, 0, 50, 50), w3.get())); - scoped_ptr<Window> w311( - CreateTestWindow(SK_ColorBLUE, 311, gfx::Rect(0, 0, 10, 10), w31.get())); - - EXPECT_EQ(NULL, root->GetTopWindowContainingPoint(gfx::Point(0, 0))); - EXPECT_EQ(w2.get(), root->GetTopWindowContainingPoint(gfx::Point(5, 5))); - EXPECT_EQ(w2.get(), root->GetTopWindowContainingPoint(gfx::Point(10, 10))); - EXPECT_EQ(w2.get(), root->GetTopWindowContainingPoint(gfx::Point(59, 59))); - EXPECT_EQ(w1.get(), root->GetTopWindowContainingPoint(gfx::Point(60, 60))); - EXPECT_EQ(w1.get(), root->GetTopWindowContainingPoint(gfx::Point(109, 109))); - EXPECT_EQ(NULL, root->GetTopWindowContainingPoint(gfx::Point(110, 110))); - EXPECT_EQ(w31.get(), root->GetTopWindowContainingPoint(gfx::Point(200, 200))); - EXPECT_EQ(w31.get(), root->GetTopWindowContainingPoint(gfx::Point(220, 220))); - EXPECT_EQ(NULL, root->GetTopWindowContainingPoint(gfx::Point(260, 260))); -} - -TEST_F(WindowTest, GetToplevelWindow) { - const gfx::Rect kBounds(0, 0, 10, 10); - TestWindowDelegate delegate; - - scoped_ptr<Window> w1(CreateTestWindowWithId(1, root_window())); - scoped_ptr<Window> w11( - CreateTestWindowWithDelegate(&delegate, 11, kBounds, w1.get())); - scoped_ptr<Window> w111(CreateTestWindowWithId(111, w11.get())); - scoped_ptr<Window> w1111( - CreateTestWindowWithDelegate(&delegate, 1111, kBounds, w111.get())); - - EXPECT_TRUE(root_window()->GetToplevelWindow() == NULL); - EXPECT_TRUE(w1->GetToplevelWindow() == NULL); - EXPECT_EQ(w11.get(), w11->GetToplevelWindow()); - EXPECT_EQ(w11.get(), w111->GetToplevelWindow()); - EXPECT_EQ(w11.get(), w1111->GetToplevelWindow()); -} - -class AddedToRootWindowObserver : public WindowObserver { - public: - AddedToRootWindowObserver() : called_(false) {} - - virtual void OnWindowAddedToRootWindow(Window* window) override { - called_ = true; - } - - bool called() const { return called_; } - - private: - bool called_; - - DISALLOW_COPY_AND_ASSIGN(AddedToRootWindowObserver); -}; - -TEST_F(WindowTest, WindowAddedToRootWindowShouldNotifyChildAndNotParent) { - AddedToRootWindowObserver parent_observer; - AddedToRootWindowObserver child_observer; - scoped_ptr<Window> parent_window(CreateTestWindowWithId(1, root_window())); - scoped_ptr<Window> child_window(new Window(NULL)); - child_window->Init(aura::WINDOW_LAYER_TEXTURED); - child_window->Show(); - - parent_window->AddObserver(&parent_observer); - child_window->AddObserver(&child_observer); - - parent_window->AddChild(child_window.get()); - - EXPECT_FALSE(parent_observer.called()); - EXPECT_TRUE(child_observer.called()); - - parent_window->RemoveObserver(&parent_observer); - child_window->RemoveObserver(&child_observer); -} - -// Various destruction assertions. -TEST_F(WindowTest, DestroyTest) { - DestroyTrackingDelegateImpl parent_delegate; - ChildWindowDelegateImpl child_delegate(&parent_delegate); - { - scoped_ptr<Window> parent( - CreateTestWindowWithDelegate(&parent_delegate, 0, gfx::Rect(), - root_window())); - CreateTestWindowWithDelegate(&child_delegate, 0, gfx::Rect(), parent.get()); - } - // Both the parent and child should have been destroyed. - EXPECT_EQ(1, parent_delegate.destroying_count()); - EXPECT_EQ(1, parent_delegate.destroyed_count()); - EXPECT_EQ(1, child_delegate.destroying_count()); - EXPECT_EQ(1, child_delegate.destroyed_count()); -} - -// Tests that a window is orphaned before OnWindowDestroyed is called. -TEST_F(WindowTest, OrphanedBeforeOnDestroyed) { - TestWindowDelegate parent_delegate; - DestroyOrphanDelegate child_delegate; - { - scoped_ptr<Window> parent( - CreateTestWindowWithDelegate(&parent_delegate, 0, gfx::Rect(), - root_window())); - scoped_ptr<Window> child(CreateTestWindowWithDelegate(&child_delegate, 0, - gfx::Rect(), parent.get())); - child_delegate.set_window(child.get()); - } -} - -// Make sure StackChildAtTop moves both the window and layer to the front. -TEST_F(WindowTest, StackChildAtTop) { - Window parent(NULL); - parent.Init(aura::WINDOW_LAYER_NOT_DRAWN); - Window child1(NULL); - child1.Init(aura::WINDOW_LAYER_NOT_DRAWN); - Window child2(NULL); - child2.Init(aura::WINDOW_LAYER_NOT_DRAWN); - - parent.AddChild(&child1); - parent.AddChild(&child2); - ASSERT_EQ(2u, parent.children().size()); - EXPECT_EQ(&child1, parent.children()[0]); - EXPECT_EQ(&child2, parent.children()[1]); - ASSERT_EQ(2u, parent.layer()->children().size()); - EXPECT_EQ(child1.layer(), parent.layer()->children()[0]); - EXPECT_EQ(child2.layer(), parent.layer()->children()[1]); - - parent.StackChildAtTop(&child1); - ASSERT_EQ(2u, parent.children().size()); - EXPECT_EQ(&child1, parent.children()[1]); - EXPECT_EQ(&child2, parent.children()[0]); - ASSERT_EQ(2u, parent.layer()->children().size()); - EXPECT_EQ(child1.layer(), parent.layer()->children()[1]); - EXPECT_EQ(child2.layer(), parent.layer()->children()[0]); -} - -// Make sure StackChildBelow works. -TEST_F(WindowTest, StackChildBelow) { - Window parent(NULL); - parent.Init(aura::WINDOW_LAYER_NOT_DRAWN); - Window child1(NULL); - child1.Init(aura::WINDOW_LAYER_NOT_DRAWN); - child1.set_id(1); - Window child2(NULL); - child2.Init(aura::WINDOW_LAYER_NOT_DRAWN); - child2.set_id(2); - Window child3(NULL); - child3.Init(aura::WINDOW_LAYER_NOT_DRAWN); - child3.set_id(3); - - parent.AddChild(&child1); - parent.AddChild(&child2); - parent.AddChild(&child3); - EXPECT_EQ("1 2 3", ChildWindowIDsAsString(&parent)); - - parent.StackChildBelow(&child1, &child2); - EXPECT_EQ("1 2 3", ChildWindowIDsAsString(&parent)); - - parent.StackChildBelow(&child2, &child1); - EXPECT_EQ("2 1 3", ChildWindowIDsAsString(&parent)); - - parent.StackChildBelow(&child3, &child2); - EXPECT_EQ("3 2 1", ChildWindowIDsAsString(&parent)); - - parent.StackChildBelow(&child3, &child1); - EXPECT_EQ("2 3 1", ChildWindowIDsAsString(&parent)); -} - -// Various assertions for StackChildAbove. -TEST_F(WindowTest, StackChildAbove) { - Window parent(NULL); - parent.Init(aura::WINDOW_LAYER_NOT_DRAWN); - Window child1(NULL); - child1.Init(aura::WINDOW_LAYER_NOT_DRAWN); - Window child2(NULL); - child2.Init(aura::WINDOW_LAYER_NOT_DRAWN); - Window child3(NULL); - child3.Init(aura::WINDOW_LAYER_NOT_DRAWN); - - parent.AddChild(&child1); - parent.AddChild(&child2); - - // Move 1 in front of 2. - parent.StackChildAbove(&child1, &child2); - ASSERT_EQ(2u, parent.children().size()); - EXPECT_EQ(&child2, parent.children()[0]); - EXPECT_EQ(&child1, parent.children()[1]); - ASSERT_EQ(2u, parent.layer()->children().size()); - EXPECT_EQ(child2.layer(), parent.layer()->children()[0]); - EXPECT_EQ(child1.layer(), parent.layer()->children()[1]); - - // Add 3, resulting in order [2, 1, 3], then move 2 in front of 1, resulting - // in [1, 2, 3]. - parent.AddChild(&child3); - parent.StackChildAbove(&child2, &child1); - ASSERT_EQ(3u, parent.children().size()); - EXPECT_EQ(&child1, parent.children()[0]); - EXPECT_EQ(&child2, parent.children()[1]); - EXPECT_EQ(&child3, parent.children()[2]); - ASSERT_EQ(3u, parent.layer()->children().size()); - EXPECT_EQ(child1.layer(), parent.layer()->children()[0]); - EXPECT_EQ(child2.layer(), parent.layer()->children()[1]); - EXPECT_EQ(child3.layer(), parent.layer()->children()[2]); - - // Move 1 in front of 3, resulting in [2, 3, 1]. - parent.StackChildAbove(&child1, &child3); - ASSERT_EQ(3u, parent.children().size()); - EXPECT_EQ(&child2, parent.children()[0]); - EXPECT_EQ(&child3, parent.children()[1]); - EXPECT_EQ(&child1, parent.children()[2]); - ASSERT_EQ(3u, parent.layer()->children().size()); - EXPECT_EQ(child2.layer(), parent.layer()->children()[0]); - EXPECT_EQ(child3.layer(), parent.layer()->children()[1]); - EXPECT_EQ(child1.layer(), parent.layer()->children()[2]); - - // Moving 1 in front of 2 should lower it, resulting in [2, 1, 3]. - parent.StackChildAbove(&child1, &child2); - ASSERT_EQ(3u, parent.children().size()); - EXPECT_EQ(&child2, parent.children()[0]); - EXPECT_EQ(&child1, parent.children()[1]); - EXPECT_EQ(&child3, parent.children()[2]); - ASSERT_EQ(3u, parent.layer()->children().size()); - EXPECT_EQ(child2.layer(), parent.layer()->children()[0]); - EXPECT_EQ(child1.layer(), parent.layer()->children()[1]); - EXPECT_EQ(child3.layer(), parent.layer()->children()[2]); -} - -// Various capture assertions. -TEST_F(WindowTest, CaptureTests) { - CaptureWindowDelegateImpl delegate; - scoped_ptr<Window> window(CreateTestWindowWithDelegate( - &delegate, 0, gfx::Rect(0, 0, 20, 20), root_window())); - EXPECT_FALSE(window->HasCapture()); - - delegate.ResetCounts(); - - // Do a capture. - window->SetCapture(); - EXPECT_TRUE(window->HasCapture()); - EXPECT_EQ(0, delegate.capture_lost_count()); - EXPECT_EQ(0, delegate.capture_changed_event_count()); - ui::test::EventGenerator generator(root_window(), gfx::Point(50, 50)); - generator.PressLeftButton(); - EXPECT_EQ(1, delegate.mouse_event_count()); - generator.ReleaseLeftButton(); - - EXPECT_EQ(2, delegate.mouse_event_count()); - delegate.ResetCounts(); - - ui::TouchEvent touchev( - ui::ET_TOUCH_PRESSED, gfx::Point(50, 50), 0, getTime()); - DispatchEventUsingWindowDispatcher(&touchev); - EXPECT_EQ(1, delegate.touch_event_count()); - delegate.ResetCounts(); - - window->ReleaseCapture(); - EXPECT_FALSE(window->HasCapture()); - EXPECT_EQ(1, delegate.capture_lost_count()); - EXPECT_EQ(1, delegate.capture_changed_event_count()); - EXPECT_EQ(1, delegate.mouse_event_count()); - EXPECT_EQ(0, delegate.touch_event_count()); - - generator.PressLeftButton(); - EXPECT_EQ(1, delegate.mouse_event_count()); - - ui::TouchEvent touchev2( - ui::ET_TOUCH_PRESSED, gfx::Point(250, 250), 1, getTime()); - DispatchEventUsingWindowDispatcher(&touchev2); - EXPECT_EQ(0, delegate.touch_event_count()); - - // Removing the capture window from parent should reset the capture window - // in the root window. - window->SetCapture(); - EXPECT_EQ(window.get(), aura::client::GetCaptureWindow(root_window())); - window->parent()->RemoveChild(window.get()); - EXPECT_FALSE(window->HasCapture()); - EXPECT_EQ(NULL, aura::client::GetCaptureWindow(root_window())); -} - -TEST_F(WindowTest, TouchCaptureCancelsOtherTouches) { - CaptureWindowDelegateImpl delegate1; - scoped_ptr<Window> w1(CreateTestWindowWithDelegate( - &delegate1, 0, gfx::Rect(0, 0, 50, 50), root_window())); - CaptureWindowDelegateImpl delegate2; - scoped_ptr<Window> w2(CreateTestWindowWithDelegate( - &delegate2, 0, gfx::Rect(50, 50, 50, 50), root_window())); - - // Press on w1. - ui::TouchEvent press1( - ui::ET_TOUCH_PRESSED, gfx::Point(10, 10), 0, getTime()); - DispatchEventUsingWindowDispatcher(&press1); - // We will get both GESTURE_BEGIN and GESTURE_TAP_DOWN. - EXPECT_EQ(2, delegate1.gesture_event_count()); - delegate1.ResetCounts(); - - // Capturing to w2 should cause the touch to be canceled. - w2->SetCapture(); - EXPECT_EQ(1, delegate1.touch_event_count()); - EXPECT_EQ(0, delegate2.touch_event_count()); - delegate1.ResetCounts(); - delegate2.ResetCounts(); - - // Events now go to w2. - ui::TouchEvent move(ui::ET_TOUCH_MOVED, gfx::Point(10, 20), 0, getTime()); - DispatchEventUsingWindowDispatcher(&move); - EXPECT_EQ(0, delegate1.gesture_event_count()); - EXPECT_EQ(0, delegate1.touch_event_count()); - EXPECT_EQ(0, delegate2.gesture_event_count()); - EXPECT_EQ(1, delegate2.touch_event_count()); - - ui::TouchEvent release( - ui::ET_TOUCH_RELEASED, gfx::Point(10, 20), 0, getTime()); - DispatchEventUsingWindowDispatcher(&release); - EXPECT_EQ(0, delegate1.gesture_event_count()); - EXPECT_EQ(0, delegate2.gesture_event_count()); - - // A new press is captured by w2. - ui::TouchEvent press2( - ui::ET_TOUCH_PRESSED, gfx::Point(10, 10), 0, getTime()); - DispatchEventUsingWindowDispatcher(&press2); - EXPECT_EQ(0, delegate1.gesture_event_count()); - // We will get both GESTURE_BEGIN and GESTURE_TAP_DOWN. - EXPECT_EQ(2, delegate2.gesture_event_count()); - delegate1.ResetCounts(); - delegate2.ResetCounts(); - - // And releasing capture changes nothing. - w2->ReleaseCapture(); - EXPECT_EQ(0, delegate1.gesture_event_count()); - EXPECT_EQ(0, delegate1.touch_event_count()); - EXPECT_EQ(0, delegate2.gesture_event_count()); - EXPECT_EQ(0, delegate2.touch_event_count()); -} - -TEST_F(WindowTest, TouchCaptureDoesntCancelCapturedTouches) { - CaptureWindowDelegateImpl delegate; - scoped_ptr<Window> window(CreateTestWindowWithDelegate( - &delegate, 0, gfx::Rect(0, 0, 50, 50), root_window())); - base::TimeDelta time = getTime(); - const int kTimeDelta = 100; - - ui::TouchEvent press( - ui::ET_TOUCH_PRESSED, gfx::Point(10, 10), 0, time); - DispatchEventUsingWindowDispatcher(&press); - - // We will get both GESTURE_BEGIN and GESTURE_TAP_DOWN. - EXPECT_EQ(2, delegate.gesture_event_count()); - EXPECT_EQ(1, delegate.touch_event_count()); - delegate.ResetCounts(); - - window->SetCapture(); - EXPECT_EQ(0, delegate.gesture_event_count()); - EXPECT_EQ(0, delegate.touch_event_count()); - delegate.ResetCounts(); - - // On move We will get TOUCH_MOVED, GESTURE_TAP_CANCEL, - // GESTURE_SCROLL_START and GESTURE_SCROLL_UPDATE. - time += base::TimeDelta::FromMilliseconds(kTimeDelta); - ui::TouchEvent move(ui::ET_TOUCH_MOVED, gfx::Point(10, 20), 0, time); - DispatchEventUsingWindowDispatcher(&move); - EXPECT_EQ(1, delegate.touch_event_count()); - EXPECT_EQ(3, delegate.gesture_event_count()); - delegate.ResetCounts(); - - // Release capture shouldn't change anything. - window->ReleaseCapture(); - EXPECT_EQ(0, delegate.touch_event_count()); - EXPECT_EQ(0, delegate.gesture_event_count()); - delegate.ResetCounts(); - - // On move we still get TOUCH_MOVED and GESTURE_SCROLL_UPDATE. - time += base::TimeDelta::FromMilliseconds(kTimeDelta); - ui::TouchEvent move2(ui::ET_TOUCH_MOVED, gfx::Point(10, 30), 0, time); - DispatchEventUsingWindowDispatcher(&move2); - EXPECT_EQ(1, delegate.touch_event_count()); - EXPECT_EQ(1, delegate.gesture_event_count()); - delegate.ResetCounts(); - - // And on release we get TOUCH_RELEASED, GESTURE_SCROLL_END, GESTURE_END - time += base::TimeDelta::FromMilliseconds(kTimeDelta); - ui::TouchEvent release( - ui::ET_TOUCH_RELEASED, gfx::Point(10, 20), 0, time); - DispatchEventUsingWindowDispatcher(&release); - EXPECT_EQ(1, delegate.touch_event_count()); - EXPECT_EQ(2, delegate.gesture_event_count()); -} - - -// Assertions around SetCapture() and touch/gestures. -TEST_F(WindowTest, TransferCaptureTouchEvents) { - // Touch on |w1|. - CaptureWindowDelegateImpl d1; - scoped_ptr<Window> w1(CreateTestWindowWithDelegate( - &d1, 0, gfx::Rect(0, 0, 20, 20), root_window())); - ui::TouchEvent p1(ui::ET_TOUCH_PRESSED, gfx::Point(10, 10), 0, getTime()); - DispatchEventUsingWindowDispatcher(&p1); - // We will get both GESTURE_BEGIN and GESTURE_TAP_DOWN. - EXPECT_EQ(1, d1.touch_event_count()); - EXPECT_EQ(2, d1.gesture_event_count()); - d1.ResetCounts(); - - // Touch on |w2| with a different id. - CaptureWindowDelegateImpl d2; - scoped_ptr<Window> w2(CreateTestWindowWithDelegate( - &d2, 0, gfx::Rect(40, 0, 40, 20), root_window())); - ui::TouchEvent p2(ui::ET_TOUCH_PRESSED, gfx::Point(41, 10), 1, getTime()); - DispatchEventUsingWindowDispatcher(&p2); - EXPECT_EQ(0, d1.touch_event_count()); - EXPECT_EQ(0, d1.gesture_event_count()); - // We will get both GESTURE_BEGIN and GESTURE_TAP_DOWN for new target window. - EXPECT_EQ(1, d2.touch_event_count()); - EXPECT_EQ(2, d2.gesture_event_count()); - d1.ResetCounts(); - d2.ResetCounts(); - - // Set capture on |w2|, this should send a cancel (TAP_CANCEL, END) to |w1| - // but not |w2|. - w2->SetCapture(); - EXPECT_EQ(1, d1.touch_event_count()); - EXPECT_EQ(2, d1.gesture_event_count()); - EXPECT_EQ(0, d2.touch_event_count()); - EXPECT_EQ(0, d2.gesture_event_count()); - d1.ResetCounts(); - d2.ResetCounts(); - - CaptureWindowDelegateImpl d3; - scoped_ptr<Window> w3(CreateTestWindowWithDelegate( - &d3, 0, gfx::Rect(0, 0, 100, 101), root_window())); - // Set capture on w3. No new events should be received. - // Note this difference in behavior between the first and second capture - // is confusing and error prone. http://crbug.com/236930 - w3->SetCapture(); - EXPECT_EQ(0, d1.touch_event_count()); - EXPECT_EQ(0, d1.gesture_event_count()); - EXPECT_EQ(0, d2.touch_event_count()); - EXPECT_EQ(0, d2.gesture_event_count()); - EXPECT_EQ(0, d3.touch_event_count()); - EXPECT_EQ(0, d3.gesture_event_count()); - - // Move touch id originally associated with |w2|. Since capture was transfered - // from 2 to 3 only |w3| should get the event. - ui::TouchEvent m3(ui::ET_TOUCH_MOVED, gfx::Point(110, 105), 1, getTime()); - DispatchEventUsingWindowDispatcher(&m3); - EXPECT_EQ(0, d1.touch_event_count()); - EXPECT_EQ(0, d1.gesture_event_count()); - EXPECT_EQ(0, d2.touch_event_count()); - EXPECT_EQ(0, d2.gesture_event_count()); - // |w3| gets a TOUCH_MOVE, TAP_CANCEL and two scroll related events. - EXPECT_EQ(1, d3.touch_event_count()); - EXPECT_EQ(3, d3.gesture_event_count()); - d1.ResetCounts(); - d2.ResetCounts(); - d3.ResetCounts(); - - // When we release capture, no touches are canceled. - w3->ReleaseCapture(); - EXPECT_EQ(0, d1.touch_event_count()); - EXPECT_EQ(0, d1.gesture_event_count()); - EXPECT_EQ(0, d2.touch_event_count()); - EXPECT_EQ(0, d2.gesture_event_count()); - EXPECT_EQ(0, d3.touch_event_count()); - EXPECT_EQ(0, d3.gesture_event_count()); - - // And when we move the touch again, |w3| still gets the events. - ui::TouchEvent m4(ui::ET_TOUCH_MOVED, gfx::Point(120, 105), 1, getTime()); - DispatchEventUsingWindowDispatcher(&m4); - EXPECT_EQ(0, d1.touch_event_count()); - EXPECT_EQ(0, d1.gesture_event_count()); - EXPECT_EQ(0, d2.touch_event_count()); - EXPECT_EQ(0, d2.gesture_event_count()); - EXPECT_EQ(1, d3.touch_event_count()); - EXPECT_EQ(1, d3.gesture_event_count()); - d1.ResetCounts(); - d2.ResetCounts(); - d3.ResetCounts(); -} - -// Changes capture while capture is already ongoing. -TEST_F(WindowTest, ChangeCaptureWhileMouseDown) { - CaptureWindowDelegateImpl delegate; - scoped_ptr<Window> window(CreateTestWindowWithDelegate( - &delegate, 0, gfx::Rect(0, 0, 20, 20), root_window())); - CaptureWindowDelegateImpl delegate2; - scoped_ptr<Window> w2(CreateTestWindowWithDelegate( - &delegate2, 0, gfx::Rect(20, 20, 20, 20), root_window())); - - // Execute the scheduled draws so that mouse events are not - // aggregated. - RunAllPendingInMessageLoop(); - - EXPECT_FALSE(window->HasCapture()); - - // Do a capture. - delegate.ResetCounts(); - window->SetCapture(); - EXPECT_TRUE(window->HasCapture()); - EXPECT_EQ(0, delegate.capture_lost_count()); - EXPECT_EQ(0, delegate.capture_changed_event_count()); - ui::test::EventGenerator generator(root_window(), gfx::Point(50, 50)); - generator.PressLeftButton(); - EXPECT_EQ(0, delegate.capture_lost_count()); - EXPECT_EQ(0, delegate.capture_changed_event_count()); - EXPECT_EQ(1, delegate.mouse_event_count()); - - // Set capture to |w2|, should implicitly unset capture for |window|. - delegate.ResetCounts(); - delegate2.ResetCounts(); - w2->SetCapture(); - - generator.MoveMouseTo(gfx::Point(40, 40), 2); - EXPECT_EQ(1, delegate.capture_lost_count()); - EXPECT_EQ(1, delegate.capture_changed_event_count()); - EXPECT_EQ(1, delegate.mouse_event_count()); - EXPECT_EQ(2, delegate2.mouse_event_count()); -} - -// Verifies capture is reset when a window is destroyed. -TEST_F(WindowTest, ReleaseCaptureOnDestroy) { - CaptureWindowDelegateImpl delegate; - scoped_ptr<Window> window(CreateTestWindowWithDelegate( - &delegate, 0, gfx::Rect(0, 0, 20, 20), root_window())); - EXPECT_FALSE(window->HasCapture()); - - // Do a capture. - window->SetCapture(); - EXPECT_TRUE(window->HasCapture()); - - // Destroy the window. - window.reset(); - - // Make sure the root window doesn't reference the window anymore. - EXPECT_EQ(NULL, host()->dispatcher()->mouse_pressed_handler()); - EXPECT_EQ(NULL, aura::client::GetCaptureWindow(root_window())); -} - -TEST_F(WindowTest, GetBoundsInRootWindow) { - scoped_ptr<Window> viewport(CreateTestWindowWithBounds( - gfx::Rect(0, 0, 300, 300), root_window())); - scoped_ptr<Window> child(CreateTestWindowWithBounds( - gfx::Rect(0, 0, 100, 100), viewport.get())); - // Sanity check. - EXPECT_EQ("0,0 100x100", child->GetBoundsInRootWindow().ToString()); - - // The |child| window's screen bounds should move along with the |viewport|. - viewport->SetBounds(gfx::Rect(-100, -100, 300, 300)); - EXPECT_EQ("-100,-100 100x100", child->GetBoundsInRootWindow().ToString()); - - // The |child| window is moved to the 0,0 in screen coordinates. - // |GetBoundsInRootWindow()| should return 0,0. - child->SetBounds(gfx::Rect(100, 100, 100, 100)); - EXPECT_EQ("0,0 100x100", child->GetBoundsInRootWindow().ToString()); -} - -class MouseEnterExitWindowDelegate : public TestWindowDelegate { - public: - MouseEnterExitWindowDelegate() : entered_(false), exited_(false) {} - - virtual void OnMouseEvent(ui::MouseEvent* event) override { - switch (event->type()) { - case ui::ET_MOUSE_ENTERED: - EXPECT_TRUE(event->flags() & ui::EF_IS_SYNTHESIZED); - entered_ = true; - break; - case ui::ET_MOUSE_EXITED: - EXPECT_TRUE(event->flags() & ui::EF_IS_SYNTHESIZED); - exited_ = true; - break; - default: - break; - } - } - - bool entered() const { return entered_; } - bool exited() const { return exited_; } - - // Clear the entered / exited states. - void ResetExpectations() { - entered_ = false; - exited_ = false; - } - - private: - bool entered_; - bool exited_; - - DISALLOW_COPY_AND_ASSIGN(MouseEnterExitWindowDelegate); -}; - - -// Verifies that the WindowDelegate receives MouseExit and MouseEnter events for -// mouse transitions from window to window. -TEST_F(WindowTest, MouseEnterExit) { - MouseEnterExitWindowDelegate d1; - scoped_ptr<Window> w1( - CreateTestWindowWithDelegate(&d1, 1, gfx::Rect(10, 10, 50, 50), - root_window())); - MouseEnterExitWindowDelegate d2; - scoped_ptr<Window> w2( - CreateTestWindowWithDelegate(&d2, 2, gfx::Rect(70, 70, 50, 50), - root_window())); - - ui::test::EventGenerator generator(root_window()); - generator.MoveMouseToCenterOf(w1.get()); - EXPECT_TRUE(d1.entered()); - EXPECT_FALSE(d1.exited()); - EXPECT_FALSE(d2.entered()); - EXPECT_FALSE(d2.exited()); - - generator.MoveMouseToCenterOf(w2.get()); - EXPECT_TRUE(d1.entered()); - EXPECT_TRUE(d1.exited()); - EXPECT_TRUE(d2.entered()); - EXPECT_FALSE(d2.exited()); -} - -// Verifies that the WindowDelegate receives MouseExit from ET_MOUSE_EXITED. -TEST_F(WindowTest, WindowTreeHostExit) { - MouseEnterExitWindowDelegate d1; - scoped_ptr<Window> w1( - CreateTestWindowWithDelegate(&d1, 1, gfx::Rect(10, 10, 50, 50), - root_window())); - - ui::test::EventGenerator generator(root_window()); - generator.MoveMouseToCenterOf(w1.get()); - EXPECT_TRUE(d1.entered()); - EXPECT_FALSE(d1.exited()); - d1.ResetExpectations(); - - ui::MouseEvent exit_event( - ui::ET_MOUSE_EXITED, gfx::Point(), gfx::Point(), 0, 0); - DispatchEventUsingWindowDispatcher(&exit_event); - EXPECT_FALSE(d1.entered()); - EXPECT_TRUE(d1.exited()); -} - -// Verifies that the WindowDelegate receives MouseExit and MouseEnter events for -// mouse transitions from window to window, even if the entered window sets -// and releases capture. -TEST_F(WindowTest, MouseEnterExitWithClick) { - MouseEnterExitWindowDelegate d1; - scoped_ptr<Window> w1( - CreateTestWindowWithDelegate(&d1, 1, gfx::Rect(10, 10, 50, 50), - root_window())); - MouseEnterExitWindowDelegate d2; - scoped_ptr<Window> w2( - CreateTestWindowWithDelegate(&d2, 2, gfx::Rect(70, 70, 50, 50), - root_window())); - - ui::test::EventGenerator generator(root_window()); - generator.MoveMouseToCenterOf(w1.get()); - EXPECT_TRUE(d1.entered()); - EXPECT_FALSE(d1.exited()); - EXPECT_FALSE(d2.entered()); - EXPECT_FALSE(d2.exited()); - - // Emmulate what Views does on a click by grabbing and releasing capture. - generator.PressLeftButton(); - w1->SetCapture(); - w1->ReleaseCapture(); - generator.ReleaseLeftButton(); - - generator.MoveMouseToCenterOf(w2.get()); - EXPECT_TRUE(d1.entered()); - EXPECT_TRUE(d1.exited()); - EXPECT_TRUE(d2.entered()); - EXPECT_FALSE(d2.exited()); -} - -TEST_F(WindowTest, MouseEnterExitWhenDeleteWithCapture) { - MouseEnterExitWindowDelegate delegate; - scoped_ptr<Window> window( - CreateTestWindowWithDelegate(&delegate, 1, gfx::Rect(10, 10, 50, 50), - root_window())); - - ui::test::EventGenerator generator(root_window()); - generator.MoveMouseToCenterOf(window.get()); - EXPECT_TRUE(delegate.entered()); - EXPECT_FALSE(delegate.exited()); - - // Emmulate what Views does on a click by grabbing and releasing capture. - generator.PressLeftButton(); - window->SetCapture(); - - delegate.ResetExpectations(); - generator.MoveMouseTo(0, 0); - EXPECT_FALSE(delegate.entered()); - EXPECT_FALSE(delegate.exited()); - - delegate.ResetExpectations(); - window.reset(); - EXPECT_FALSE(delegate.entered()); - EXPECT_FALSE(delegate.exited()); -} - -// Verifies that enter / exits are sent if windows appear and are deleted -// under the current mouse position.. -TEST_F(WindowTest, MouseEnterExitWithDelete) { - MouseEnterExitWindowDelegate d1; - scoped_ptr<Window> w1( - CreateTestWindowWithDelegate(&d1, 1, gfx::Rect(10, 10, 50, 50), - root_window())); - - ui::test::EventGenerator generator(root_window()); - generator.MoveMouseToCenterOf(w1.get()); - EXPECT_TRUE(d1.entered()); - EXPECT_FALSE(d1.exited()); - d1.ResetExpectations(); - - MouseEnterExitWindowDelegate d2; - { - scoped_ptr<Window> w2( - CreateTestWindowWithDelegate(&d2, 2, gfx::Rect(10, 10, 50, 50), - root_window())); - // Enters / exits can be sent asynchronously. - RunAllPendingInMessageLoop(); - EXPECT_FALSE(d1.entered()); - EXPECT_TRUE(d1.exited()); - EXPECT_TRUE(d2.entered()); - EXPECT_FALSE(d2.exited()); - d1.ResetExpectations(); - d2.ResetExpectations(); - } - // Enters / exits can be sent asynchronously. - RunAllPendingInMessageLoop(); - EXPECT_TRUE(d2.exited()); - EXPECT_TRUE(d1.entered()); -} - -// Verifies that enter / exits are sent if windows appear and are hidden -// under the current mouse position.. -TEST_F(WindowTest, MouseEnterExitWithHide) { - MouseEnterExitWindowDelegate d1; - scoped_ptr<Window> w1( - CreateTestWindowWithDelegate(&d1, 1, gfx::Rect(10, 10, 50, 50), - root_window())); - - ui::test::EventGenerator generator(root_window()); - generator.MoveMouseToCenterOf(w1.get()); - EXPECT_TRUE(d1.entered()); - EXPECT_FALSE(d1.exited()); - - MouseEnterExitWindowDelegate d2; - scoped_ptr<Window> w2( - CreateTestWindowWithDelegate(&d2, 2, gfx::Rect(10, 10, 50, 50), - root_window())); - // Enters / exits can be send asynchronously. - RunAllPendingInMessageLoop(); - EXPECT_TRUE(d1.entered()); - EXPECT_TRUE(d1.exited()); - EXPECT_TRUE(d2.entered()); - EXPECT_FALSE(d2.exited()); - - d1.ResetExpectations(); - w2->Hide(); - // Enters / exits can be send asynchronously. - RunAllPendingInMessageLoop(); - EXPECT_TRUE(d2.exited()); - EXPECT_TRUE(d1.entered()); -} - -TEST_F(WindowTest, MouseEnterExitWithParentHide) { - MouseEnterExitWindowDelegate d1; - scoped_ptr<Window> w1( - CreateTestWindowWithDelegate(&d1, 1, gfx::Rect(10, 10, 50, 50), - root_window())); - MouseEnterExitWindowDelegate d2; - Window* w2 = CreateTestWindowWithDelegate(&d2, 2, gfx::Rect(10, 10, 50, 50), - w1.get()); - ui::test::EventGenerator generator(root_window()); - generator.MoveMouseToCenterOf(w2); - // Enters / exits can be send asynchronously. - RunAllPendingInMessageLoop(); - EXPECT_TRUE(d2.entered()); - EXPECT_FALSE(d2.exited()); - - d2.ResetExpectations(); - w1->Hide(); - RunAllPendingInMessageLoop(); - EXPECT_FALSE(d2.entered()); - EXPECT_TRUE(d2.exited()); - - w1.reset(); -} - -TEST_F(WindowTest, MouseEnterExitWithParentDelete) { - MouseEnterExitWindowDelegate d1; - scoped_ptr<Window> w1( - CreateTestWindowWithDelegate(&d1, 1, gfx::Rect(10, 10, 50, 50), - root_window())); - MouseEnterExitWindowDelegate d2; - Window* w2 = CreateTestWindowWithDelegate(&d2, 2, gfx::Rect(10, 10, 50, 50), - w1.get()); - ui::test::EventGenerator generator(root_window()); - generator.MoveMouseToCenterOf(w2); - - // Enters / exits can be send asynchronously. - RunAllPendingInMessageLoop(); - EXPECT_TRUE(d2.entered()); - EXPECT_FALSE(d2.exited()); - - d2.ResetExpectations(); - w1.reset(); - RunAllPendingInMessageLoop(); - EXPECT_FALSE(d2.entered()); - EXPECT_TRUE(d2.exited()); -} - -// Creates a window with a delegate (w111) that can handle events at a lower -// z-index than a window without a delegate (w12). w12 is sized to fill the -// entire bounds of the container. This test verifies that -// GetEventHandlerForPoint() skips w12 even though its bounds contain the event, -// because it has no children that can handle the event and it has no delegate -// allowing it to handle the event itself. -TEST_F(WindowTest, GetEventHandlerForPoint_NoDelegate) { - TestWindowDelegate d111; - scoped_ptr<Window> w1(CreateTestWindowWithDelegate(NULL, 1, - gfx::Rect(0, 0, 500, 500), root_window())); - scoped_ptr<Window> w11(CreateTestWindowWithDelegate(NULL, 11, - gfx::Rect(0, 0, 500, 500), w1.get())); - scoped_ptr<Window> w111(CreateTestWindowWithDelegate(&d111, 111, - gfx::Rect(50, 50, 450, 450), w11.get())); - scoped_ptr<Window> w12(CreateTestWindowWithDelegate(NULL, 12, - gfx::Rect(0, 0, 500, 500), w1.get())); - - gfx::Point target_point = w111->bounds().CenterPoint(); - EXPECT_EQ(w111.get(), w1->GetEventHandlerForPoint(target_point)); -} - -class VisibilityWindowDelegate : public TestWindowDelegate { - public: - VisibilityWindowDelegate() - : shown_(0), - hidden_(0) { - } - - int shown() const { return shown_; } - int hidden() const { return hidden_; } - void Clear() { - shown_ = 0; - hidden_ = 0; - } - - virtual void OnWindowTargetVisibilityChanged(bool visible) override { - if (visible) - shown_++; - else - hidden_++; - } - - private: - int shown_; - int hidden_; - - DISALLOW_COPY_AND_ASSIGN(VisibilityWindowDelegate); -}; - -// Verifies show/hide propagate correctly to children and the layer. -TEST_F(WindowTest, Visibility) { - VisibilityWindowDelegate d; - VisibilityWindowDelegate d2; - scoped_ptr<Window> w1(CreateTestWindowWithDelegate(&d, 1, gfx::Rect(), - root_window())); - scoped_ptr<Window> w2( - CreateTestWindowWithDelegate(&d2, 2, gfx::Rect(), w1.get())); - scoped_ptr<Window> w3(CreateTestWindowWithId(3, w2.get())); - - // Create shows all the windows. - EXPECT_TRUE(w1->IsVisible()); - EXPECT_TRUE(w2->IsVisible()); - EXPECT_TRUE(w3->IsVisible()); - EXPECT_EQ(1, d.shown()); - - d.Clear(); - w1->Hide(); - EXPECT_FALSE(w1->IsVisible()); - EXPECT_FALSE(w2->IsVisible()); - EXPECT_FALSE(w3->IsVisible()); - EXPECT_EQ(1, d.hidden()); - EXPECT_EQ(0, d.shown()); - - w2->Show(); - EXPECT_FALSE(w1->IsVisible()); - EXPECT_FALSE(w2->IsVisible()); - EXPECT_FALSE(w3->IsVisible()); - - w3->Hide(); - EXPECT_FALSE(w1->IsVisible()); - EXPECT_FALSE(w2->IsVisible()); - EXPECT_FALSE(w3->IsVisible()); - - d.Clear(); - w1->Show(); - EXPECT_TRUE(w1->IsVisible()); - EXPECT_TRUE(w2->IsVisible()); - EXPECT_FALSE(w3->IsVisible()); - EXPECT_EQ(0, d.hidden()); - EXPECT_EQ(1, d.shown()); - - w3->Show(); - EXPECT_TRUE(w1->IsVisible()); - EXPECT_TRUE(w2->IsVisible()); - EXPECT_TRUE(w3->IsVisible()); - - // Verify that if an ancestor isn't visible and we change the visibility of a - // child window that OnChildWindowVisibilityChanged() is still invoked. - w1->Hide(); - d2.Clear(); - w2->Hide(); - EXPECT_EQ(1, d2.hidden()); - EXPECT_EQ(0, d2.shown()); - d2.Clear(); - w2->Show(); - EXPECT_EQ(0, d2.hidden()); - EXPECT_EQ(1, d2.shown()); -} - -TEST_F(WindowTest, IgnoreEventsTest) { - TestWindowDelegate d11; - TestWindowDelegate d12; - TestWindowDelegate d111; - TestWindowDelegate d121; - scoped_ptr<Window> w1(CreateTestWindowWithDelegate(NULL, 1, - gfx::Rect(0, 0, 500, 500), root_window())); - scoped_ptr<Window> w11(CreateTestWindowWithDelegate(&d11, 11, - gfx::Rect(0, 0, 500, 500), w1.get())); - scoped_ptr<Window> w111(CreateTestWindowWithDelegate(&d111, 111, - gfx::Rect(50, 50, 450, 450), w11.get())); - scoped_ptr<Window> w12(CreateTestWindowWithDelegate(&d12, 12, - gfx::Rect(0, 0, 500, 500), w1.get())); - scoped_ptr<Window> w121(CreateTestWindowWithDelegate(&d121, 121, - gfx::Rect(150, 150, 50, 50), w12.get())); - - EXPECT_EQ(w12.get(), w1->GetEventHandlerForPoint(gfx::Point(10, 10))); - w12->set_ignore_events(true); - EXPECT_EQ(w11.get(), w1->GetEventHandlerForPoint(gfx::Point(10, 10))); - w12->set_ignore_events(false); - - EXPECT_EQ(w121.get(), w1->GetEventHandlerForPoint(gfx::Point(160, 160))); - w121->set_ignore_events(true); - EXPECT_EQ(w12.get(), w1->GetEventHandlerForPoint(gfx::Point(160, 160))); - w12->set_ignore_events(true); - EXPECT_EQ(w111.get(), w1->GetEventHandlerForPoint(gfx::Point(160, 160))); - w111->set_ignore_events(true); - EXPECT_EQ(w11.get(), w1->GetEventHandlerForPoint(gfx::Point(160, 160))); -} - -// Tests transformation on the root window. -TEST_F(WindowTest, Transform) { - gfx::Size size = host()->GetBounds().size(); - EXPECT_EQ(gfx::Rect(size), - gfx::Screen::GetScreenFor(root_window())->GetDisplayNearestPoint( - gfx::Point()).bounds()); - - // Rotate it clock-wise 90 degrees. - gfx::Transform transform; - transform.Translate(size.height(), 0); - transform.Rotate(90.0); - host()->SetRootTransform(transform); - - // The size should be the transformed size. - gfx::Size transformed_size(size.height(), size.width()); - EXPECT_EQ(transformed_size.ToString(), - root_window()->bounds().size().ToString()); - EXPECT_EQ( - gfx::Rect(transformed_size).ToString(), - gfx::Screen::GetScreenFor(root_window())->GetDisplayNearestPoint( - gfx::Point()).bounds().ToString()); - - // Host size shouldn't change. - EXPECT_EQ(size.ToString(), host()->GetBounds().size().ToString()); -} - -TEST_F(WindowTest, TransformGesture) { - gfx::Size size = host()->GetBounds().size(); - - scoped_ptr<GestureTrackPositionDelegate> delegate( - new GestureTrackPositionDelegate); - scoped_ptr<Window> window(CreateTestWindowWithDelegate(delegate.get(), -1234, - gfx::Rect(0, 0, 20, 20), root_window())); - - // Rotate the root-window clock-wise 90 degrees. - gfx::Transform transform; - transform.Translate(size.height(), 0.0); - transform.Rotate(90.0); - host()->SetRootTransform(transform); - - ui::TouchEvent press( - ui::ET_TOUCH_PRESSED, gfx::Point(size.height() - 10, 10), 0, getTime()); - DispatchEventUsingWindowDispatcher(&press); - EXPECT_EQ(gfx::Point(10, 10).ToString(), delegate->position().ToString()); -} - -namespace { -DEFINE_WINDOW_PROPERTY_KEY(int, kIntKey, -2); -DEFINE_WINDOW_PROPERTY_KEY(const char*, kStringKey, "squeamish"); -} - -TEST_F(WindowTest, Property) { - scoped_ptr<Window> w(CreateTestWindowWithId(0, root_window())); - - static const char native_prop_key[] = "fnord"; - - // Non-existent properties should return the default values. - EXPECT_EQ(-2, w->GetProperty(kIntKey)); - EXPECT_EQ(std::string("squeamish"), w->GetProperty(kStringKey)); - EXPECT_EQ(NULL, w->GetNativeWindowProperty(native_prop_key)); - - // A set property value should be returned again (even if it's the default - // value). - w->SetProperty(kIntKey, INT_MAX); - EXPECT_EQ(INT_MAX, w->GetProperty(kIntKey)); - w->SetProperty(kIntKey, -2); - EXPECT_EQ(-2, w->GetProperty(kIntKey)); - w->SetProperty(kIntKey, INT_MIN); - EXPECT_EQ(INT_MIN, w->GetProperty(kIntKey)); - - w->SetProperty(kStringKey, static_cast<const char*>(NULL)); - EXPECT_EQ(NULL, w->GetProperty(kStringKey)); - w->SetProperty(kStringKey, "squeamish"); - EXPECT_EQ(std::string("squeamish"), w->GetProperty(kStringKey)); - w->SetProperty(kStringKey, "ossifrage"); - EXPECT_EQ(std::string("ossifrage"), w->GetProperty(kStringKey)); - - w->SetNativeWindowProperty(native_prop_key, &*w); - EXPECT_EQ(&*w, w->GetNativeWindowProperty(native_prop_key)); - w->SetNativeWindowProperty(native_prop_key, NULL); - EXPECT_EQ(NULL, w->GetNativeWindowProperty(native_prop_key)); - - // ClearProperty should restore the default value. - w->ClearProperty(kIntKey); - EXPECT_EQ(-2, w->GetProperty(kIntKey)); - w->ClearProperty(kStringKey); - EXPECT_EQ(std::string("squeamish"), w->GetProperty(kStringKey)); -} - -namespace { - -class TestProperty { - public: - TestProperty() {} - virtual ~TestProperty() { - last_deleted_ = this; - } - static TestProperty* last_deleted() { return last_deleted_; } - - private: - static TestProperty* last_deleted_; - DISALLOW_COPY_AND_ASSIGN(TestProperty); -}; - -TestProperty* TestProperty::last_deleted_ = NULL; - -DEFINE_OWNED_WINDOW_PROPERTY_KEY(TestProperty, kOwnedKey, NULL); - -} // namespace - -TEST_F(WindowTest, OwnedProperty) { - scoped_ptr<Window> w(CreateTestWindowWithId(0, root_window())); - EXPECT_EQ(NULL, w->GetProperty(kOwnedKey)); - TestProperty* p1 = new TestProperty(); - w->SetProperty(kOwnedKey, p1); - EXPECT_EQ(p1, w->GetProperty(kOwnedKey)); - EXPECT_EQ(NULL, TestProperty::last_deleted()); - - TestProperty* p2 = new TestProperty(); - w->SetProperty(kOwnedKey, p2); - EXPECT_EQ(p2, w->GetProperty(kOwnedKey)); - EXPECT_EQ(p1, TestProperty::last_deleted()); - - w->ClearProperty(kOwnedKey); - EXPECT_EQ(NULL, w->GetProperty(kOwnedKey)); - EXPECT_EQ(p2, TestProperty::last_deleted()); - - TestProperty* p3 = new TestProperty(); - w->SetProperty(kOwnedKey, p3); - EXPECT_EQ(p3, w->GetProperty(kOwnedKey)); - EXPECT_EQ(p2, TestProperty::last_deleted()); - w.reset(); - EXPECT_EQ(p3, TestProperty::last_deleted()); -} - -TEST_F(WindowTest, SetBoundsInternalShouldCheckTargetBounds) { - // We cannot short-circuit animations in this test. - ui::ScopedAnimationDurationScaleMode test_duration_mode( - ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION); - - scoped_ptr<Window> w1( - CreateTestWindowWithBounds(gfx::Rect(0, 0, 100, 100), root_window())); - - EXPECT_FALSE(!w1->layer()); - w1->layer()->GetAnimator()->set_disable_timer_for_test(true); - ui::LayerAnimator* animator = w1->layer()->GetAnimator(); - - EXPECT_EQ("0,0 100x100", w1->bounds().ToString()); - EXPECT_EQ("0,0 100x100", w1->layer()->GetTargetBounds().ToString()); - - // Animate to a different position. - { - ui::ScopedLayerAnimationSettings settings(w1->layer()->GetAnimator()); - w1->SetBounds(gfx::Rect(100, 100, 100, 100)); - } - - EXPECT_EQ("0,0 100x100", w1->bounds().ToString()); - EXPECT_EQ("100,100 100x100", w1->layer()->GetTargetBounds().ToString()); - - // Animate back to the first position. The animation hasn't started yet, so - // the current bounds are still (0, 0, 100, 100), but the target bounds are - // (100, 100, 100, 100). If we step the animator ahead, we should find that - // we're at (0, 0, 100, 100). That is, the second animation should be applied. - { - ui::ScopedLayerAnimationSettings settings(w1->layer()->GetAnimator()); - w1->SetBounds(gfx::Rect(0, 0, 100, 100)); - } - - EXPECT_EQ("0,0 100x100", w1->bounds().ToString()); - EXPECT_EQ("0,0 100x100", w1->layer()->GetTargetBounds().ToString()); - - // Confirm that the target bounds are reached. - base::TimeTicks start_time = - w1->layer()->GetAnimator()->last_step_time(); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(1000)); - - EXPECT_EQ("0,0 100x100", w1->bounds().ToString()); -} - - -typedef std::pair<const void*, intptr_t> PropertyChangeInfo; - -class WindowObserverTest : public WindowTest, - public WindowObserver { - public: - struct VisibilityInfo { - bool window_visible; - bool visible_param; - int changed_count; - }; - - WindowObserverTest() - : added_count_(0), - removed_count_(0), - destroyed_count_(0), - old_property_value_(-3) { - } - - virtual ~WindowObserverTest() {} - - const VisibilityInfo* GetVisibilityInfo() const { - return visibility_info_.get(); - } - - void ResetVisibilityInfo() { - visibility_info_.reset(); - } - - // Returns a description of the WindowObserver methods that have been invoked. - std::string WindowObserverCountStateAndClear() { - std::string result( - base::StringPrintf("added=%d removed=%d", - added_count_, removed_count_)); - added_count_ = removed_count_ = 0; - return result; - } - - int DestroyedCountAndClear() { - int result = destroyed_count_; - destroyed_count_ = 0; - return result; - } - - // Return a tuple of the arguments passed in OnPropertyChanged callback. - PropertyChangeInfo PropertyChangeInfoAndClear() { - PropertyChangeInfo result(property_key_, old_property_value_); - property_key_ = NULL; - old_property_value_ = -3; - return result; - } - - std::string TransformNotificationsAndClear() { - std::string result; - for (std::vector<std::pair<int, int> >::iterator it = - transform_notifications_.begin(); - it != transform_notifications_.end(); - ++it) { - base::StringAppendF(&result, "(%d,%d)", it->first, it->second); - } - transform_notifications_.clear(); - return result; - } - - private: - virtual void OnWindowAdded(Window* new_window) override { - added_count_++; - } - - virtual void OnWillRemoveWindow(Window* window) override { - removed_count_++; - } - - virtual void OnWindowVisibilityChanged(Window* window, - bool visible) override { - if (!visibility_info_) { - visibility_info_.reset(new VisibilityInfo); - visibility_info_->changed_count = 0; - } - visibility_info_->window_visible = window->IsVisible(); - visibility_info_->visible_param = visible; - visibility_info_->changed_count++; - } - - virtual void OnWindowDestroyed(Window* window) override { - EXPECT_FALSE(window->parent()); - destroyed_count_++; - } - - virtual void OnWindowPropertyChanged(Window* window, - const void* key, - intptr_t old) override { - property_key_ = key; - old_property_value_ = old; - } - - virtual void OnAncestorWindowTransformed(Window* source, - Window* window) override { - transform_notifications_.push_back( - std::make_pair(source->id(), window->id())); - } - - int added_count_; - int removed_count_; - int destroyed_count_; - scoped_ptr<VisibilityInfo> visibility_info_; - const void* property_key_; - intptr_t old_property_value_; - std::vector<std::pair<int, int> > transform_notifications_; - - DISALLOW_COPY_AND_ASSIGN(WindowObserverTest); -}; - -// Various assertions for WindowObserver. -TEST_F(WindowObserverTest, WindowObserver) { - scoped_ptr<Window> w1(CreateTestWindowWithId(1, root_window())); - w1->AddObserver(this); - - // Create a new window as a child of w1, our observer should be notified. - scoped_ptr<Window> w2(CreateTestWindowWithId(2, w1.get())); - EXPECT_EQ("added=1 removed=0", WindowObserverCountStateAndClear()); - - // Delete w2, which should result in the remove notification. - w2.reset(); - EXPECT_EQ("added=0 removed=1", WindowObserverCountStateAndClear()); - - // Create a window that isn't parented to w1, we shouldn't get any - // notification. - scoped_ptr<Window> w3(CreateTestWindowWithId(3, root_window())); - EXPECT_EQ("added=0 removed=0", WindowObserverCountStateAndClear()); - - // Similarly destroying w3 shouldn't notify us either. - w3.reset(); - EXPECT_EQ("added=0 removed=0", WindowObserverCountStateAndClear()); - w1->RemoveObserver(this); -} - -// Test if OnWindowVisibilityChagned is invoked with expected -// parameters. -TEST_F(WindowObserverTest, WindowVisibility) { - scoped_ptr<Window> w1(CreateTestWindowWithId(1, root_window())); - scoped_ptr<Window> w2(CreateTestWindowWithId(1, w1.get())); - w2->AddObserver(this); - - // Hide should make the window invisible and the passed visible - // parameter is false. - w2->Hide(); - EXPECT_FALSE(!GetVisibilityInfo()); - EXPECT_FALSE(!GetVisibilityInfo()); - if (!GetVisibilityInfo()) - return; - EXPECT_FALSE(GetVisibilityInfo()->window_visible); - EXPECT_FALSE(GetVisibilityInfo()->visible_param); - EXPECT_EQ(1, GetVisibilityInfo()->changed_count); - - // If parent isn't visible, showing window won't make the window visible, but - // passed visible value must be true. - w1->Hide(); - ResetVisibilityInfo(); - EXPECT_TRUE(!GetVisibilityInfo()); - w2->Show(); - EXPECT_FALSE(!GetVisibilityInfo()); - if (!GetVisibilityInfo()) - return; - EXPECT_FALSE(GetVisibilityInfo()->window_visible); - EXPECT_TRUE(GetVisibilityInfo()->visible_param); - EXPECT_EQ(1, GetVisibilityInfo()->changed_count); - - // If parent is visible, showing window will make the window - // visible and the passed visible value is true. - w1->Show(); - w2->Hide(); - ResetVisibilityInfo(); - w2->Show(); - EXPECT_FALSE(!GetVisibilityInfo()); - if (!GetVisibilityInfo()) - return; - EXPECT_TRUE(GetVisibilityInfo()->window_visible); - EXPECT_TRUE(GetVisibilityInfo()->visible_param); - EXPECT_EQ(1, GetVisibilityInfo()->changed_count); - - // Verify that the OnWindowVisibilityChanged only once - // per visibility change. - w2->Hide(); - EXPECT_EQ(2, GetVisibilityInfo()->changed_count); - - w2->Hide(); - EXPECT_EQ(2, GetVisibilityInfo()->changed_count); -} - -// Test if OnWindowDestroyed is invoked as expected. -TEST_F(WindowObserverTest, WindowDestroyed) { - // Delete a window should fire a destroyed notification. - scoped_ptr<Window> w1(CreateTestWindowWithId(1, root_window())); - w1->AddObserver(this); - w1.reset(); - EXPECT_EQ(1, DestroyedCountAndClear()); - - // Observe on child and delete parent window should fire a notification. - scoped_ptr<Window> parent(CreateTestWindowWithId(1, root_window())); - Window* child = CreateTestWindowWithId(1, parent.get()); // owned by parent - child->AddObserver(this); - parent.reset(); - EXPECT_EQ(1, DestroyedCountAndClear()); -} - -TEST_F(WindowObserverTest, PropertyChanged) { - // Setting property should fire a property change notification. - scoped_ptr<Window> w1(CreateTestWindowWithId(1, root_window())); - w1->AddObserver(this); - - static const WindowProperty<int> prop = {-2}; - static const char native_prop_key[] = "fnord"; - - w1->SetProperty(&prop, 1); - EXPECT_EQ(PropertyChangeInfo(&prop, -2), PropertyChangeInfoAndClear()); - w1->SetProperty(&prop, -2); - EXPECT_EQ(PropertyChangeInfo(&prop, 1), PropertyChangeInfoAndClear()); - w1->SetProperty(&prop, 3); - EXPECT_EQ(PropertyChangeInfo(&prop, -2), PropertyChangeInfoAndClear()); - w1->ClearProperty(&prop); - EXPECT_EQ(PropertyChangeInfo(&prop, 3), PropertyChangeInfoAndClear()); - - w1->SetNativeWindowProperty(native_prop_key, &*w1); - EXPECT_EQ(PropertyChangeInfo(native_prop_key, 0), - PropertyChangeInfoAndClear()); - w1->SetNativeWindowProperty(native_prop_key, NULL); - EXPECT_EQ(PropertyChangeInfo(native_prop_key, - reinterpret_cast<intptr_t>(&*w1)), - PropertyChangeInfoAndClear()); - - // Sanity check to see if |PropertyChangeInfoAndClear| really clears. - EXPECT_EQ(PropertyChangeInfo( - reinterpret_cast<const void*>(NULL), -3), PropertyChangeInfoAndClear()); -} - -TEST_F(WindowObserverTest, AncestorTransformed) { - // Create following window hierarchy: - // root_window - // +-- w1 - // +-- w2 - // +-- w3 - // +-- w4 - // Then, apply a transform to |w1| and ensure all its descendants are - // notified. - scoped_ptr<Window> w1(CreateTestWindowWithId(1, root_window())); - w1->AddObserver(this); - scoped_ptr<Window> w2(CreateTestWindowWithId(2, w1.get())); - w2->AddObserver(this); - scoped_ptr<Window> w3(CreateTestWindowWithId(3, w1.get())); - w3->AddObserver(this); - scoped_ptr<Window> w4(CreateTestWindowWithId(4, w3.get())); - w4->AddObserver(this); - - EXPECT_EQ(std::string(), TransformNotificationsAndClear()); - - gfx::Transform transform; - transform.Translate(10, 10); - w1->SetTransform(transform); - - EXPECT_EQ("(1,1)(1,2)(1,3)(1,4)", TransformNotificationsAndClear()); -} - -TEST_F(WindowTest, AcquireLayer) { - scoped_ptr<Window> window1(CreateTestWindowWithId(1, root_window())); - scoped_ptr<Window> window2(CreateTestWindowWithId(2, root_window())); - ui::Layer* parent = window1->parent()->layer(); - EXPECT_EQ(2U, parent->children().size()); - - WindowTestApi window1_test_api(window1.get()); - WindowTestApi window2_test_api(window2.get()); - - EXPECT_TRUE(window1_test_api.OwnsLayer()); - EXPECT_TRUE(window2_test_api.OwnsLayer()); - - // After acquisition, window1 should not own its layer, but it should still - // be available to the window. - scoped_ptr<ui::Layer> window1_layer(window1->AcquireLayer()); - EXPECT_FALSE(window1_test_api.OwnsLayer()); - EXPECT_TRUE(window1_layer.get() == window1->layer()); - - // The acquired layer's owner should be set NULL and re-acquring - // should return NULL. - EXPECT_FALSE(window1_layer->owner()); - scoped_ptr<ui::Layer> window1_layer_reacquired(window1->AcquireLayer()); - EXPECT_FALSE(window1_layer_reacquired.get()); - - // Upon destruction, window1's layer should still be valid, and in the layer - // hierarchy, but window2's should be gone, and no longer in the hierarchy. - window1.reset(); - window2.reset(); - - // This should be set by the window's destructor. - EXPECT_TRUE(window1_layer->delegate() == NULL); - EXPECT_EQ(1U, parent->children().size()); -} - -// Make sure that properties which should persist from the old layer to the new -// layer actually do. -TEST_F(WindowTest, RecreateLayer) { - // Set properties to non default values. - Window w(new ColorTestWindowDelegate(SK_ColorWHITE)); - w.set_id(1); - w.Init(aura::WINDOW_LAYER_SOLID_COLOR); - w.SetBounds(gfx::Rect(0, 0, 100, 100)); - - ui::Layer* layer = w.layer(); - layer->SetVisible(false); - layer->SetMasksToBounds(true); - - ui::Layer child_layer; - layer->Add(&child_layer); - - scoped_ptr<ui::Layer> old_layer(w.RecreateLayer()); - layer = w.layer(); - EXPECT_EQ(ui::LAYER_SOLID_COLOR, layer->type()); - EXPECT_FALSE(layer->visible()); - EXPECT_EQ(1u, layer->children().size()); - EXPECT_TRUE(layer->GetMasksToBounds()); - EXPECT_EQ("0,0 100x100", w.bounds().ToString()); - EXPECT_EQ("0,0 100x100", layer->bounds().ToString()); -} - -// Verify that RecreateLayer() stacks the old layer above the newly creatd -// layer. -TEST_F(WindowTest, RecreateLayerZOrder) { - scoped_ptr<Window> w( - CreateTestWindow(SK_ColorWHITE, 1, gfx::Rect(0, 0, 100, 100), - root_window())); - scoped_ptr<ui::Layer> old_layer(w->RecreateLayer()); - - const std::vector<ui::Layer*>& child_layers = - root_window()->layer()->children(); - ASSERT_EQ(2u, child_layers.size()); - EXPECT_EQ(w->layer(), child_layers[0]); - EXPECT_EQ(old_layer.get(), child_layers[1]); -} - -// Ensure that acquiring a layer then recreating a layer does not crash -// and that RecreateLayer returns null. -TEST_F(WindowTest, AcquireThenRecreateLayer) { - scoped_ptr<Window> w( - CreateTestWindow(SK_ColorWHITE, 1, gfx::Rect(0, 0, 100, 100), - root_window())); - scoped_ptr<ui::Layer> acquired_layer(w->AcquireLayer()); - scoped_ptr<ui::Layer> doubly_acquired_layer(w->RecreateLayer()); - EXPECT_EQ(NULL, doubly_acquired_layer.get()); - - // Destroy window before layer gets destroyed. - w.reset(); -} - -TEST_F(WindowTest, StackWindowAtBottomBelowWindowWhoseLayerHasNoDelegate) { - scoped_ptr<Window> window1(CreateTestWindowWithId(1, root_window())); - window1->layer()->set_name("1"); - scoped_ptr<Window> window2(CreateTestWindowWithId(2, root_window())); - window2->layer()->set_name("2"); - scoped_ptr<Window> window3(CreateTestWindowWithId(3, root_window())); - window3->layer()->set_name("3"); - - EXPECT_EQ("1 2 3", ChildWindowIDsAsString(root_window())); - EXPECT_EQ("1 2 3", - ui::test::ChildLayerNamesAsString(*root_window()->layer())); - window1->layer()->set_delegate(NULL); - root_window()->StackChildAtBottom(window3.get()); - - // Window 3 should have moved to the bottom. - EXPECT_EQ("3 1 2", ChildWindowIDsAsString(root_window())); - EXPECT_EQ("3 1 2", - ui::test::ChildLayerNamesAsString(*root_window()->layer())); -} - -class TestVisibilityClient : public client::VisibilityClient { - public: - explicit TestVisibilityClient(Window* root_window) - : ignore_visibility_changes_(false) { - client::SetVisibilityClient(root_window, this); - } - virtual ~TestVisibilityClient() { - } - - void set_ignore_visibility_changes(bool ignore_visibility_changes) { - ignore_visibility_changes_ = ignore_visibility_changes; - } - - // Overridden from client::VisibilityClient: - virtual void UpdateLayerVisibility(aura::Window* window, - bool visible) override { - if (!ignore_visibility_changes_) - window->layer()->SetVisible(visible); - } - - private: - bool ignore_visibility_changes_; - DISALLOW_COPY_AND_ASSIGN(TestVisibilityClient); -}; - -TEST_F(WindowTest, VisibilityClientIsVisible) { - TestVisibilityClient client(root_window()); - - scoped_ptr<Window> window(CreateTestWindowWithId(1, root_window())); - EXPECT_TRUE(window->IsVisible()); - EXPECT_TRUE(window->layer()->visible()); - - window->Hide(); - EXPECT_FALSE(window->IsVisible()); - EXPECT_FALSE(window->layer()->visible()); - window->Show(); - - client.set_ignore_visibility_changes(true); - window->Hide(); - EXPECT_FALSE(window->IsVisible()); - EXPECT_TRUE(window->layer()->visible()); -} - -// Tests mouse events on window change. -TEST_F(WindowTest, MouseEventsOnWindowChange) { - gfx::Size size = host()->GetBounds().size(); - - ui::test::EventGenerator generator(root_window()); - generator.MoveMouseTo(50, 50); - - EventCountDelegate d1; - scoped_ptr<Window> w1(CreateTestWindowWithDelegate(&d1, 1, - gfx::Rect(0, 0, 100, 100), root_window())); - RunAllPendingInMessageLoop(); - // The format of result is "Enter/Mouse/Leave". - EXPECT_EQ("1 1 0", d1.GetMouseMotionCountsAndReset()); - - // Adding new window. - EventCountDelegate d11; - scoped_ptr<Window> w11(CreateTestWindowWithDelegate( - &d11, 1, gfx::Rect(0, 0, 100, 100), w1.get())); - RunAllPendingInMessageLoop(); - EXPECT_EQ("0 0 1", d1.GetMouseMotionCountsAndReset()); - EXPECT_EQ("1 1 0", d11.GetMouseMotionCountsAndReset()); - - // Move bounds. - w11->SetBounds(gfx::Rect(0, 0, 10, 10)); - RunAllPendingInMessageLoop(); - EXPECT_EQ("1 1 0", d1.GetMouseMotionCountsAndReset()); - EXPECT_EQ("0 0 1", d11.GetMouseMotionCountsAndReset()); - - w11->SetBounds(gfx::Rect(0, 0, 60, 60)); - RunAllPendingInMessageLoop(); - EXPECT_EQ("0 0 1", d1.GetMouseMotionCountsAndReset()); - EXPECT_EQ("1 1 0", d11.GetMouseMotionCountsAndReset()); - - // Detach, then re-attach. - w1->RemoveChild(w11.get()); - RunAllPendingInMessageLoop(); - EXPECT_EQ("1 1 0", d1.GetMouseMotionCountsAndReset()); - // Window is detached, so no event is set. - EXPECT_EQ("0 0 1", d11.GetMouseMotionCountsAndReset()); - - w1->AddChild(w11.get()); - RunAllPendingInMessageLoop(); - EXPECT_EQ("0 0 1", d1.GetMouseMotionCountsAndReset()); - // Window is detached, so no event is set. - EXPECT_EQ("1 1 0", d11.GetMouseMotionCountsAndReset()); - - // Visibility Change - w11->Hide(); - RunAllPendingInMessageLoop(); - EXPECT_EQ("1 1 0", d1.GetMouseMotionCountsAndReset()); - EXPECT_EQ("0 0 1", d11.GetMouseMotionCountsAndReset()); - - w11->Show(); - RunAllPendingInMessageLoop(); - EXPECT_EQ("0 0 1", d1.GetMouseMotionCountsAndReset()); - EXPECT_EQ("1 1 0", d11.GetMouseMotionCountsAndReset()); - - // Transform: move d11 by 100 100. - gfx::Transform transform; - transform.Translate(100, 100); - w11->SetTransform(transform); - RunAllPendingInMessageLoop(); - EXPECT_EQ("1 1 0", d1.GetMouseMotionCountsAndReset()); - EXPECT_EQ("0 0 1", d11.GetMouseMotionCountsAndReset()); - - w11->SetTransform(gfx::Transform()); - RunAllPendingInMessageLoop(); - EXPECT_EQ("0 0 1", d1.GetMouseMotionCountsAndReset()); - EXPECT_EQ("1 1 0", d11.GetMouseMotionCountsAndReset()); - - // Closing a window. - w11.reset(); - RunAllPendingInMessageLoop(); - EXPECT_EQ("1 1 0", d1.GetMouseMotionCountsAndReset()); - - // Make sure we don't synthesize events if the mouse - // is outside of the root window. - generator.MoveMouseTo(-10, -10); - EXPECT_EQ("0 0 1", d1.GetMouseMotionCountsAndReset()); - - // Adding new windows. - w11.reset(CreateTestWindowWithDelegate( - &d11, 1, gfx::Rect(0, 0, 100, 100), w1.get())); - RunAllPendingInMessageLoop(); - EXPECT_EQ("0 0 0", d1.GetMouseMotionCountsAndReset()); - EXPECT_EQ("0 0 1", d11.GetMouseMotionCountsAndReset()); - - // Closing windows - w11.reset(); - RunAllPendingInMessageLoop(); - EXPECT_EQ("0 0 0", d1.GetMouseMotionCountsAndReset()); - EXPECT_EQ("0 0 0", d11.GetMouseMotionCountsAndReset()); -} - -class RootWindowAttachmentObserver : public WindowObserver { - public: - RootWindowAttachmentObserver() : added_count_(0), removed_count_(0) {} - virtual ~RootWindowAttachmentObserver() {} - - int added_count() const { return added_count_; } - int removed_count() const { return removed_count_; } - - void Clear() { - added_count_ = 0; - removed_count_ = 0; - } - - // Overridden from WindowObserver: - virtual void OnWindowAddedToRootWindow(Window* window) override { - ++added_count_; - } - virtual void OnWindowRemovingFromRootWindow(Window* window, - Window* new_root) override { - ++removed_count_; - } - - private: - int added_count_; - int removed_count_; - - DISALLOW_COPY_AND_ASSIGN(RootWindowAttachmentObserver); -}; - -TEST_F(WindowTest, RootWindowAttachment) { - RootWindowAttachmentObserver observer; - - // Test a direct add/remove from the RootWindow. - scoped_ptr<Window> w1(new Window(NULL)); - w1->Init(aura::WINDOW_LAYER_NOT_DRAWN); - w1->AddObserver(&observer); - - ParentWindow(w1.get()); - EXPECT_EQ(1, observer.added_count()); - EXPECT_EQ(0, observer.removed_count()); - - w1.reset(); - EXPECT_EQ(1, observer.added_count()); - EXPECT_EQ(1, observer.removed_count()); - - observer.Clear(); - - // Test an indirect add/remove from the RootWindow. - w1.reset(new Window(NULL)); - w1->Init(aura::WINDOW_LAYER_NOT_DRAWN); - Window* w11 = new Window(NULL); - w11->Init(aura::WINDOW_LAYER_NOT_DRAWN); - w11->AddObserver(&observer); - w1->AddChild(w11); - EXPECT_EQ(0, observer.added_count()); - EXPECT_EQ(0, observer.removed_count()); - - ParentWindow(w1.get()); - EXPECT_EQ(1, observer.added_count()); - EXPECT_EQ(0, observer.removed_count()); - - w1.reset(); // Deletes w11. - w11 = NULL; - EXPECT_EQ(1, observer.added_count()); - EXPECT_EQ(1, observer.removed_count()); - - observer.Clear(); - - // Test an indirect add/remove with nested observers. - w1.reset(new Window(NULL)); - w1->Init(aura::WINDOW_LAYER_NOT_DRAWN); - w11 = new Window(NULL); - w11->Init(aura::WINDOW_LAYER_NOT_DRAWN); - w11->AddObserver(&observer); - w1->AddChild(w11); - Window* w111 = new Window(NULL); - w111->Init(aura::WINDOW_LAYER_NOT_DRAWN); - w111->AddObserver(&observer); - w11->AddChild(w111); - - EXPECT_EQ(0, observer.added_count()); - EXPECT_EQ(0, observer.removed_count()); - - ParentWindow(w1.get()); - EXPECT_EQ(2, observer.added_count()); - EXPECT_EQ(0, observer.removed_count()); - - w1.reset(); // Deletes w11 and w111. - w11 = NULL; - w111 = NULL; - EXPECT_EQ(2, observer.added_count()); - EXPECT_EQ(2, observer.removed_count()); -} - -class BoundsChangedWindowObserver : public WindowObserver { - public: - BoundsChangedWindowObserver() : root_set_(false) {} - - virtual void OnWindowBoundsChanged(Window* window, - const gfx::Rect& old_bounds, - const gfx::Rect& new_bounds) override { - root_set_ = window->GetRootWindow() != NULL; - } - - bool root_set() const { return root_set_; } - - private: - bool root_set_; - - DISALLOW_COPY_AND_ASSIGN(BoundsChangedWindowObserver); -}; - -TEST_F(WindowTest, RootWindowSetWhenReparenting) { - Window parent1(NULL); - parent1.Init(aura::WINDOW_LAYER_NOT_DRAWN); - Window parent2(NULL); - parent2.Init(aura::WINDOW_LAYER_NOT_DRAWN); - ParentWindow(&parent1); - ParentWindow(&parent2); - parent1.SetBounds(gfx::Rect(10, 10, 300, 300)); - parent2.SetBounds(gfx::Rect(20, 20, 300, 300)); - - BoundsChangedWindowObserver observer; - Window child(NULL); - child.Init(aura::WINDOW_LAYER_NOT_DRAWN); - child.SetBounds(gfx::Rect(5, 5, 100, 100)); - parent1.AddChild(&child); - - // We need animations to start in order to observe the bounds changes. - ui::ScopedAnimationDurationScaleMode test_duration_mode( - ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION); - ui::ScopedLayerAnimationSettings settings1(child.layer()->GetAnimator()); - settings1.SetTransitionDuration(base::TimeDelta::FromMilliseconds(100)); - gfx::Rect new_bounds(gfx::Rect(35, 35, 50, 50)); - child.SetBounds(new_bounds); - - child.AddObserver(&observer); - - // Reparenting the |child| will cause it to get moved. During this move - // the window should still have root window set. - parent2.AddChild(&child); - EXPECT_TRUE(observer.root_set()); - - // Animations should stop and the bounds should be as set before the |child| - // got reparented. - EXPECT_EQ(new_bounds.ToString(), child.GetTargetBounds().ToString()); - EXPECT_EQ(new_bounds.ToString(), child.bounds().ToString()); - EXPECT_EQ("55,55 50x50", child.GetBoundsInRootWindow().ToString()); -} - -TEST_F(WindowTest, OwnedByParentFalse) { - // By default, a window is owned by its parent. If this is set to false, the - // window will not be destroyed when its parent is. - - scoped_ptr<Window> w1(new Window(NULL)); - w1->Init(aura::WINDOW_LAYER_NOT_DRAWN); - scoped_ptr<Window> w2(new Window(NULL)); - w2->set_owned_by_parent(false); - w2->Init(aura::WINDOW_LAYER_NOT_DRAWN); - w1->AddChild(w2.get()); - - w1.reset(); - - // We should be able to deref w2 still, but its parent should now be NULL. - EXPECT_EQ(NULL, w2->parent()); -} - -namespace { - -// Used By DeleteWindowFromOnWindowDestroyed. Destroys a Window from -// OnWindowDestroyed(). -class OwningWindowDelegate : public TestWindowDelegate { - public: - OwningWindowDelegate() {} - - void SetOwnedWindow(Window* window) { - owned_window_.reset(window); - } - - virtual void OnWindowDestroyed(Window* window) override { - owned_window_.reset(NULL); - } - - private: - scoped_ptr<Window> owned_window_; - - DISALLOW_COPY_AND_ASSIGN(OwningWindowDelegate); -}; - -} // namespace - -// Creates a window with two child windows. When the first child window is -// destroyed (WindowDelegate::OnWindowDestroyed) it deletes the second child. -// This synthesizes BrowserView and the status bubble. Both are children of the -// same parent and destroying BrowserView triggers it destroying the status -// bubble. -TEST_F(WindowTest, DeleteWindowFromOnWindowDestroyed) { - scoped_ptr<Window> parent(new Window(NULL)); - parent->Init(aura::WINDOW_LAYER_NOT_DRAWN); - OwningWindowDelegate delegate; - Window* c1 = new Window(&delegate); - c1->Init(aura::WINDOW_LAYER_NOT_DRAWN); - parent->AddChild(c1); - Window* c2 = new Window(NULL); - c2->Init(aura::WINDOW_LAYER_NOT_DRAWN); - parent->AddChild(c2); - delegate.SetOwnedWindow(c2); - parent.reset(); -} - -namespace { - -// Used by DelegateNotifiedAsBoundsChange to verify OnBoundsChanged() is -// invoked. -class BoundsChangeDelegate : public TestWindowDelegate { - public: - BoundsChangeDelegate() : bounds_changed_(false) {} - - void clear_bounds_changed() { bounds_changed_ = false; } - bool bounds_changed() const { - return bounds_changed_; - } - - // Window - virtual void OnBoundsChanged(const gfx::Rect& old_bounds, - const gfx::Rect& new_bounds) override { - bounds_changed_ = true; - } - - private: - // Was OnBoundsChanged() invoked? - bool bounds_changed_; - - DISALLOW_COPY_AND_ASSIGN(BoundsChangeDelegate); -}; - -} // namespace - -// Verifies the delegate is notified when the actual bounds of the layer -// change. -TEST_F(WindowTest, DelegateNotifiedAsBoundsChange) { - BoundsChangeDelegate delegate; - - // We cannot short-circuit animations in this test. - ui::ScopedAnimationDurationScaleMode test_duration_mode( - ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION); - - scoped_ptr<Window> window( - CreateTestWindowWithDelegate(&delegate, 1, - gfx::Rect(0, 0, 100, 100), root_window())); - window->layer()->GetAnimator()->set_disable_timer_for_test(true); - - delegate.clear_bounds_changed(); - - // Animate to a different position. - { - ui::ScopedLayerAnimationSettings settings(window->layer()->GetAnimator()); - window->SetBounds(gfx::Rect(100, 100, 100, 100)); - } - - // Bounds shouldn't immediately have changed. - EXPECT_EQ("0,0 100x100", window->bounds().ToString()); - EXPECT_FALSE(delegate.bounds_changed()); - - // Animate to the end, which should notify of the change. - base::TimeTicks start_time = - window->layer()->GetAnimator()->last_step_time(); - ui::LayerAnimator* animator = window->layer()->GetAnimator(); - animator->Step(start_time + base::TimeDelta::FromMilliseconds(1000)); - EXPECT_TRUE(delegate.bounds_changed()); - EXPECT_NE("0,0 100x100", window->bounds().ToString()); -} - -// Verifies the delegate is notified when the actual bounds of the layer -// change even when the window is not the layer's delegate -TEST_F(WindowTest, DelegateNotifiedAsBoundsChangeInHiddenLayer) { - BoundsChangeDelegate delegate; - - // We cannot short-circuit animations in this test. - ui::ScopedAnimationDurationScaleMode test_duration_mode( - ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION); - - scoped_ptr<Window> window( - CreateTestWindowWithDelegate(&delegate, 1, - gfx::Rect(0, 0, 100, 100), root_window())); - window->layer()->GetAnimator()->set_disable_timer_for_test(true); - - delegate.clear_bounds_changed(); - - // Suppress paint on the window since it is hidden (should reset the layer's - // delegate to NULL) - window->SuppressPaint(); - EXPECT_EQ(NULL, window->layer()->delegate()); - - // Animate to a different position. - { - ui::ScopedLayerAnimationSettings settings(window->layer()->GetAnimator()); - window->SetBounds(gfx::Rect(100, 100, 110, 100)); - } - - // Layer delegate is NULL but we should still get bounds changed notification. - EXPECT_EQ("100,100 110x100", window->GetTargetBounds().ToString()); - EXPECT_TRUE(delegate.bounds_changed()); - - delegate.clear_bounds_changed(); - - // Animate to the end: will *not* notify of the change since we are hidden. - base::TimeTicks start_time = - window->layer()->GetAnimator()->last_step_time(); - ui::LayerAnimator* animator = window->layer()->GetAnimator(); - animator->Step(start_time + base::TimeDelta::FromMilliseconds(1000)); - - // No bounds changed notification at the end of animation since layer - // delegate is NULL. - EXPECT_FALSE(delegate.bounds_changed()); - EXPECT_NE("0,0 100x100", window->layer()->bounds().ToString()); -} - -namespace { - -// Used by AddChildNotifications to track notification counts. -class AddChildNotificationsObserver : public WindowObserver { - public: - AddChildNotificationsObserver() : added_count_(0), removed_count_(0) {} - - std::string CountStringAndReset() { - std::string result = base::IntToString(added_count_) + " " + - base::IntToString(removed_count_); - added_count_ = removed_count_ = 0; - return result; - } - - // WindowObserver overrides: - virtual void OnWindowAddedToRootWindow(Window* window) override { - added_count_++; - } - virtual void OnWindowRemovingFromRootWindow(Window* window, - Window* new_root) override { - removed_count_++; - } - - private: - int added_count_; - int removed_count_; - - DISALLOW_COPY_AND_ASSIGN(AddChildNotificationsObserver); -}; - -} // namespace - -// Assertions around when root window notifications are sent. -TEST_F(WindowTest, AddChildNotifications) { - AddChildNotificationsObserver observer; - scoped_ptr<Window> w1(CreateTestWindowWithId(1, root_window())); - scoped_ptr<Window> w2(CreateTestWindowWithId(1, root_window())); - w2->AddObserver(&observer); - w2->Focus(); - EXPECT_TRUE(w2->HasFocus()); - - // Move |w2| to be a child of |w1|. - w1->AddChild(w2.get()); - // Sine we moved in the same root, observer shouldn't be notified. - EXPECT_EQ("0 0", observer.CountStringAndReset()); - // |w2| should still have focus after moving. - EXPECT_TRUE(w2->HasFocus()); -} - -// Tests that a delegate that destroys itself when the window is destroyed does -// not break. -TEST_F(WindowTest, DelegateDestroysSelfOnWindowDestroy) { - scoped_ptr<Window> w1(CreateTestWindowWithDelegate( - new DestroyWindowDelegate(), - 0, - gfx::Rect(10, 20, 30, 40), - root_window())); -} - -class HierarchyObserver : public WindowObserver { - public: - HierarchyObserver(Window* target) : target_(target) { - target_->AddObserver(this); - } - virtual ~HierarchyObserver() { - target_->RemoveObserver(this); - } - - void ValidateState( - int index, - const WindowObserver::HierarchyChangeParams& params) const { - ParamsMatch(params_[index], params); - } - - void Reset() { - params_.clear(); - } - - private: - // Overridden from WindowObserver: - virtual void OnWindowHierarchyChanging( - const HierarchyChangeParams& params) override { - params_.push_back(params); - } - virtual void OnWindowHierarchyChanged( - const HierarchyChangeParams& params) override { - params_.push_back(params); - } - - void ParamsMatch(const WindowObserver::HierarchyChangeParams& p1, - const WindowObserver::HierarchyChangeParams& p2) const { - EXPECT_EQ(p1.phase, p2.phase); - EXPECT_EQ(p1.target, p2.target); - EXPECT_EQ(p1.new_parent, p2.new_parent); - EXPECT_EQ(p1.old_parent, p2.old_parent); - EXPECT_EQ(p1.receiver, p2.receiver); - } - - Window* target_; - std::vector<WindowObserver::HierarchyChangeParams> params_; - - DISALLOW_COPY_AND_ASSIGN(HierarchyObserver); -}; - -// Tests hierarchy change notifications. -TEST_F(WindowTest, OnWindowHierarchyChange) { - { - // Simple add & remove. - HierarchyObserver oroot(root_window()); - - scoped_ptr<Window> w1(CreateTestWindowWithId(1, NULL)); - HierarchyObserver o1(w1.get()); - - // Add. - root_window()->AddChild(w1.get()); - - WindowObserver::HierarchyChangeParams params; - params.phase = WindowObserver::HierarchyChangeParams::HIERARCHY_CHANGING; - params.target = w1.get(); - params.old_parent = NULL; - params.new_parent = root_window(); - params.receiver = w1.get(); - o1.ValidateState(0, params); - - params.phase = WindowObserver::HierarchyChangeParams::HIERARCHY_CHANGED; - params.receiver = w1.get(); - o1.ValidateState(1, params); - - params.receiver = root_window(); - oroot.ValidateState(0, params); - - // Remove. - o1.Reset(); - oroot.Reset(); - - root_window()->RemoveChild(w1.get()); - - params.phase = WindowObserver::HierarchyChangeParams::HIERARCHY_CHANGING; - params.old_parent = root_window(); - params.new_parent = NULL; - params.receiver = w1.get(); - - o1.ValidateState(0, params); - - params.receiver = root_window(); - oroot.ValidateState(0, params); - - params.phase = WindowObserver::HierarchyChangeParams::HIERARCHY_CHANGED; - params.receiver = w1.get(); - o1.ValidateState(1, params); - } - - { - // Add & remove of hierarchy. Tests notification order per documentation in - // WindowObserver. - HierarchyObserver o(root_window()); - scoped_ptr<Window> w1(CreateTestWindowWithId(1, NULL)); - Window* w11 = CreateTestWindowWithId(11, w1.get()); - w1->AddObserver(&o); - w11->AddObserver(&o); - - // Add. - root_window()->AddChild(w1.get()); - - // Dispatched to target first. - int index = 0; - WindowObserver::HierarchyChangeParams params; - params.phase = WindowObserver::HierarchyChangeParams::HIERARCHY_CHANGING; - params.target = w1.get(); - params.old_parent = NULL; - params.new_parent = root_window(); - params.receiver = w1.get(); - o.ValidateState(index++, params); - - // Dispatched to target's children. - params.receiver = w11; - o.ValidateState(index++, params); - - params.phase = WindowObserver::HierarchyChangeParams::HIERARCHY_CHANGED; - - // Now process the "changed" phase. - params.receiver = w1.get(); - o.ValidateState(index++, params); - params.receiver = w11; - o.ValidateState(index++, params); - params.receiver = root_window(); - o.ValidateState(index++, params); - - // Remove. - root_window()->RemoveChild(w1.get()); - params.phase = WindowObserver::HierarchyChangeParams::HIERARCHY_CHANGING; - params.old_parent = root_window(); - params.new_parent = NULL; - params.receiver = w1.get(); - o.ValidateState(index++, params); - params.receiver = w11; - o.ValidateState(index++, params); - params.receiver = root_window(); - o.ValidateState(index++, params); - params.phase = WindowObserver::HierarchyChangeParams::HIERARCHY_CHANGED; - params.receiver = w1.get(); - o.ValidateState(index++, params); - params.receiver = w11; - o.ValidateState(index++, params); - - w1.reset(); - } - - { - // Reparent. Tests notification order per documentation in WindowObserver. - scoped_ptr<Window> w1(CreateTestWindowWithId(1, root_window())); - Window* w11 = CreateTestWindowWithId(11, w1.get()); - Window* w111 = CreateTestWindowWithId(111, w11); - scoped_ptr<Window> w2(CreateTestWindowWithId(2, root_window())); - - HierarchyObserver o(root_window()); - w1->AddObserver(&o); - w11->AddObserver(&o); - w111->AddObserver(&o); - w2->AddObserver(&o); - - w2->AddChild(w11); - - // Dispatched to target first. - int index = 0; - WindowObserver::HierarchyChangeParams params; - params.phase = WindowObserver::HierarchyChangeParams::HIERARCHY_CHANGING; - params.target = w11; - params.old_parent = w1.get(); - params.new_parent = w2.get(); - params.receiver = w11; - o.ValidateState(index++, params); - - // Then to target's children. - params.receiver = w111; - o.ValidateState(index++, params); - - // Then to target's old parent chain. - params.receiver = w1.get(); - o.ValidateState(index++, params); - params.receiver = root_window(); - o.ValidateState(index++, params); - - // "Changed" phase. - params.phase = WindowObserver::HierarchyChangeParams::HIERARCHY_CHANGED; - params.receiver = w11; - o.ValidateState(index++, params); - params.receiver = w111; - o.ValidateState(index++, params); - params.receiver = w2.get(); - o.ValidateState(index++, params); - params.receiver = root_window(); - o.ValidateState(index++, params); - - w1.reset(); - w2.reset(); - } - -} - -// Verifies SchedulePaint() on a layerless window results in damaging the right -// thing. -TEST_F(WindowTest, LayerlessWindowSchedulePaint) { - Window root(NULL); - root.Init(aura::WINDOW_LAYER_NOT_DRAWN); - root.SetBounds(gfx::Rect(0, 0, 100, 100)); - - Window* layerless_window = new Window(NULL); // Owned by |root|. - layerless_window->Init(WINDOW_LAYER_NONE); - layerless_window->SetBounds(gfx::Rect(10, 11, 12, 13)); - root.AddChild(layerless_window); - - root.layer()->SendDamagedRects(); - layerless_window->SchedulePaintInRect(gfx::Rect(1, 2, 100, 4)); - // Note the the region is clipped by the parent hence 100 going to 11. - EXPECT_EQ("11,13 11x4", - gfx::SkIRectToRect(root.layer()->damaged_region().getBounds()). - ToString()); - - Window* layerless_window2 = new Window(NULL); // Owned by |layerless_window|. - layerless_window2->Init(WINDOW_LAYER_NONE); - layerless_window2->SetBounds(gfx::Rect(1, 2, 3, 4)); - layerless_window->AddChild(layerless_window2); - - root.layer()->SendDamagedRects(); - layerless_window2->SchedulePaintInRect(gfx::Rect(1, 2, 100, 4)); - // Note the the region is clipped by the |layerless_window| hence 100 going to - // 2. - EXPECT_EQ("12,15 2x2", - gfx::SkIRectToRect(root.layer()->damaged_region().getBounds()). - ToString()); -} - -// Verifies bounds of layerless windows are correctly updated when adding -// removing. -TEST_F(WindowTest, NestedLayerlessWindowsBoundsOnAddRemove) { - // Creates the following structure (all children owned by root): - // root - // w1ll 1,2 - // w11ll 3,4 - // w111 5,6 - // w12 7,8 - // w121 9,10 - // - // ll: layer less, eg no layer - Window root(NULL); - root.Init(WINDOW_LAYER_NOT_DRAWN); - root.SetBounds(gfx::Rect(0, 0, 100, 100)); - - Window* w1ll = new Window(NULL); - w1ll->Init(WINDOW_LAYER_NONE); - w1ll->SetBounds(gfx::Rect(1, 2, 100, 100)); - - Window* w11ll = new Window(NULL); - w11ll->Init(WINDOW_LAYER_NONE); - w11ll->SetBounds(gfx::Rect(3, 4, 100, 100)); - w1ll->AddChild(w11ll); - - Window* w111 = new Window(NULL); - w111->Init(WINDOW_LAYER_NOT_DRAWN); - w111->SetBounds(gfx::Rect(5, 6, 100, 100)); - w11ll->AddChild(w111); - - Window* w12 = new Window(NULL); - w12->Init(WINDOW_LAYER_NOT_DRAWN); - w12->SetBounds(gfx::Rect(7, 8, 100, 100)); - w1ll->AddChild(w12); - - Window* w121 = new Window(NULL); - w121->Init(WINDOW_LAYER_NOT_DRAWN); - w121->SetBounds(gfx::Rect(9, 10, 100, 100)); - w12->AddChild(w121); - - root.AddChild(w1ll); - - // All layers should be parented to the root. - EXPECT_EQ(root.layer(), w111->layer()->parent()); - EXPECT_EQ(root.layer(), w12->layer()->parent()); - EXPECT_EQ(w12->layer(), w121->layer()->parent()); - - // Ensure bounds are what we expect. - EXPECT_EQ("1,2 100x100", w1ll->bounds().ToString()); - EXPECT_EQ("3,4 100x100", w11ll->bounds().ToString()); - EXPECT_EQ("5,6 100x100", w111->bounds().ToString()); - EXPECT_EQ("7,8 100x100", w12->bounds().ToString()); - EXPECT_EQ("9,10 100x100", w121->bounds().ToString()); - - // Bounds of layers are relative to the nearest ancestor with a layer. - EXPECT_EQ("8,10 100x100", w12->layer()->bounds().ToString()); - EXPECT_EQ("9,12 100x100", w111->layer()->bounds().ToString()); - EXPECT_EQ("9,10 100x100", w121->layer()->bounds().ToString()); - - // Remove and repeat. - root.RemoveChild(w1ll); - - EXPECT_TRUE(w111->layer()->parent() == NULL); - EXPECT_TRUE(w12->layer()->parent() == NULL); - - // Verify bounds haven't changed again. - EXPECT_EQ("1,2 100x100", w1ll->bounds().ToString()); - EXPECT_EQ("3,4 100x100", w11ll->bounds().ToString()); - EXPECT_EQ("5,6 100x100", w111->bounds().ToString()); - EXPECT_EQ("7,8 100x100", w12->bounds().ToString()); - EXPECT_EQ("9,10 100x100", w121->bounds().ToString()); - - // Bounds of layers should now match that of windows. - EXPECT_EQ("7,8 100x100", w12->layer()->bounds().ToString()); - EXPECT_EQ("5,6 100x100", w111->layer()->bounds().ToString()); - EXPECT_EQ("9,10 100x100", w121->layer()->bounds().ToString()); - - delete w1ll; -} - -// Verifies bounds of layerless windows are correctly updated when bounds -// of ancestor changes. -TEST_F(WindowTest, NestedLayerlessWindowsBoundsOnSetBounds) { - // Creates the following structure (all children owned by root): - // root - // w1ll 1,2 - // w11ll 3,4 - // w111 5,6 - // w12 7,8 - // w121 9,10 - // - // ll: layer less, eg no layer - Window root(NULL); - root.Init(WINDOW_LAYER_NOT_DRAWN); - root.SetBounds(gfx::Rect(0, 0, 100, 100)); - - Window* w1ll = new Window(NULL); - w1ll->Init(WINDOW_LAYER_NONE); - w1ll->SetBounds(gfx::Rect(1, 2, 100, 100)); - - Window* w11ll = new Window(NULL); - w11ll->Init(WINDOW_LAYER_NONE); - w11ll->SetBounds(gfx::Rect(3, 4, 100, 100)); - w1ll->AddChild(w11ll); - - Window* w111 = new Window(NULL); - w111->Init(WINDOW_LAYER_NOT_DRAWN); - w111->SetBounds(gfx::Rect(5, 6, 100, 100)); - w11ll->AddChild(w111); - - Window* w12 = new Window(NULL); - w12->Init(WINDOW_LAYER_NOT_DRAWN); - w12->SetBounds(gfx::Rect(7, 8, 100, 100)); - w1ll->AddChild(w12); - - Window* w121 = new Window(NULL); - w121->Init(WINDOW_LAYER_NOT_DRAWN); - w121->SetBounds(gfx::Rect(9, 10, 100, 100)); - w12->AddChild(w121); - - root.AddChild(w1ll); - - w111->SetBounds(gfx::Rect(7, 8, 11, 12)); - EXPECT_EQ("7,8 11x12", w111->bounds().ToString()); - EXPECT_EQ("7,8 11x12", w111->GetTargetBounds().ToString()); - EXPECT_EQ("11,14 11x12", w111->layer()->bounds().ToString()); - - // Set back. - w111->SetBounds(gfx::Rect(5, 6, 100, 100)); - EXPECT_EQ("5,6 100x100", w111->bounds().ToString()); - EXPECT_EQ("5,6 100x100", w111->GetTargetBounds().ToString()); - EXPECT_EQ("9,12 100x100", w111->layer()->bounds().ToString()); - - // Setting the bounds of a layerless window needs to adjust the bounds of - // layered children. - w11ll->SetBounds(gfx::Rect(5, 6, 100, 100)); - EXPECT_EQ("5,6 100x100", w11ll->bounds().ToString()); - EXPECT_EQ("5,6 100x100", w11ll->GetTargetBounds().ToString()); - EXPECT_EQ("5,6 100x100", w111->bounds().ToString()); - EXPECT_EQ("5,6 100x100", w111->GetTargetBounds().ToString()); - EXPECT_EQ("11,14 100x100", w111->layer()->bounds().ToString()); - - root.RemoveChild(w1ll); - - w111->SetBounds(gfx::Rect(7, 8, 11, 12)); - EXPECT_EQ("7,8 11x12", w111->bounds().ToString()); - EXPECT_EQ("7,8 11x12", w111->GetTargetBounds().ToString()); - EXPECT_EQ("7,8 11x12", w111->layer()->bounds().ToString()); - - delete w1ll; -} - -namespace { - -// Tracks the number of times paint is invoked along with what the clip and -// translate was. -class PaintWindowDelegate : public TestWindowDelegate { - public: - PaintWindowDelegate() : paint_count_(0) {} - virtual ~PaintWindowDelegate() {} - - const gfx::Rect& most_recent_paint_clip_bounds() const { - return most_recent_paint_clip_bounds_; - } - - const gfx::Vector2d& most_recent_paint_matrix_offset() const { - return most_recent_paint_matrix_offset_; - } - - void clear_paint_count() { paint_count_ = 0; } - int paint_count() const { return paint_count_; } - - // TestWindowDelegate:: - virtual void OnPaint(gfx::Canvas* canvas) override { - paint_count_++; - canvas->GetClipBounds(&most_recent_paint_clip_bounds_); - const SkMatrix& matrix = canvas->sk_canvas()->getTotalMatrix(); - most_recent_paint_matrix_offset_ = gfx::Vector2d( - SkScalarFloorToInt(matrix.getTranslateX()), - SkScalarFloorToInt(matrix.getTranslateY())); - } - - private: - int paint_count_; - gfx::Rect most_recent_paint_clip_bounds_; - gfx::Vector2d most_recent_paint_matrix_offset_; - - DISALLOW_COPY_AND_ASSIGN(PaintWindowDelegate); -}; - -} // namespace - -// Assertions around layerless children being painted when non-layerless window -// is painted. -TEST_F(WindowTest, PaintLayerless) { - // Creates the following structure (all children owned by root): - // root - // w1ll 1,2 40x50 - // w11ll 3,4 11x12 - // w111 5,6 - // - // ll: layer less, eg no layer - PaintWindowDelegate w1ll_delegate; - PaintWindowDelegate w11ll_delegate; - PaintWindowDelegate w111_delegate; - - Window root(NULL); - root.Init(WINDOW_LAYER_NOT_DRAWN); - root.SetBounds(gfx::Rect(0, 0, 100, 100)); - - Window* w1ll = new Window(&w1ll_delegate); - w1ll->Init(WINDOW_LAYER_NONE); - w1ll->SetBounds(gfx::Rect(1, 2, 40, 50)); - w1ll->Show(); - root.AddChild(w1ll); - - Window* w11ll = new Window(&w11ll_delegate); - w11ll->Init(WINDOW_LAYER_NONE); - w11ll->SetBounds(gfx::Rect(3, 4, 11, 12)); - w11ll->Show(); - w1ll->AddChild(w11ll); - - Window* w111 = new Window(&w111_delegate); - w111->Init(WINDOW_LAYER_NOT_DRAWN); - w111->SetBounds(gfx::Rect(5, 6, 100, 100)); - w111->Show(); - w11ll->AddChild(w111); - - EXPECT_EQ(0, w1ll_delegate.paint_count()); - EXPECT_EQ(0, w11ll_delegate.paint_count()); - EXPECT_EQ(0, w111_delegate.paint_count()); - - // Paint the root, this should trigger painting of the two layerless - // descendants but not the layered descendant. - gfx::Canvas canvas(gfx::Size(200, 200), 1.0f, true); - static_cast<ui::LayerDelegate&>(root).OnPaintLayer(&canvas); - - // NOTE: SkCanvas::getClipBounds() extends the clip 1 pixel to the left and up - // and 2 pixels down and to the right. - EXPECT_EQ(1, w1ll_delegate.paint_count()); - EXPECT_EQ("-1,-1 42x52", - w1ll_delegate.most_recent_paint_clip_bounds().ToString()); - EXPECT_EQ("[1 2]", - w1ll_delegate.most_recent_paint_matrix_offset().ToString()); - EXPECT_EQ(1, w11ll_delegate.paint_count()); - EXPECT_EQ("-1,-1 13x14", - w11ll_delegate.most_recent_paint_clip_bounds().ToString()); - EXPECT_EQ("[4 6]", - w11ll_delegate.most_recent_paint_matrix_offset().ToString()); - EXPECT_EQ(0, w111_delegate.paint_count()); -} - -namespace { - -std::string ConvertPointToTargetString(const Window* source, - const Window* target) { - gfx::Point location; - Window::ConvertPointToTarget(source, target, &location); - return location.ToString(); -} - -} // namespace - -// Assertions around Window::ConvertPointToTarget() with layerless windows. -TEST_F(WindowTest, ConvertPointToTargetLayerless) { - // Creates the following structure (all children owned by root): - // root - // w1ll 1,2 - // w11ll 3,4 - // w111 5,6 - // w12 7,8 - // w121 9,10 - // - // ll: layer less, eg no layer - Window root(NULL); - root.Init(WINDOW_LAYER_NOT_DRAWN); - root.SetBounds(gfx::Rect(0, 0, 100, 100)); - - Window* w1ll = new Window(NULL); - w1ll->Init(WINDOW_LAYER_NONE); - w1ll->SetBounds(gfx::Rect(1, 2, 100, 100)); - - Window* w11ll = new Window(NULL); - w11ll->Init(WINDOW_LAYER_NONE); - w11ll->SetBounds(gfx::Rect(3, 4, 100, 100)); - w1ll->AddChild(w11ll); - - Window* w111 = new Window(NULL); - w111->Init(WINDOW_LAYER_NOT_DRAWN); - w111->SetBounds(gfx::Rect(5, 6, 100, 100)); - w11ll->AddChild(w111); - - Window* w12 = new Window(NULL); - w12->Init(WINDOW_LAYER_NOT_DRAWN); - w12->SetBounds(gfx::Rect(7, 8, 100, 100)); - w1ll->AddChild(w12); - - Window* w121 = new Window(NULL); - w121->Init(WINDOW_LAYER_NOT_DRAWN); - w121->SetBounds(gfx::Rect(9, 10, 100, 100)); - w12->AddChild(w121); - - root.AddChild(w1ll); - - // w111->w11ll - EXPECT_EQ("5,6", ConvertPointToTargetString(w111, w11ll)); - - // w111->w1ll - EXPECT_EQ("8,10", ConvertPointToTargetString(w111, w1ll)); - - // w111->root - EXPECT_EQ("9,12", ConvertPointToTargetString(w111, &root)); - - // w111->w12 - EXPECT_EQ("1,2", ConvertPointToTargetString(w111, w12)); - - // w111->w121 - EXPECT_EQ("-8,-8", ConvertPointToTargetString(w111, w121)); - - // w11ll->w111 - EXPECT_EQ("-5,-6", ConvertPointToTargetString(w11ll, w111)); - - // w11ll->w11ll - EXPECT_EQ("3,4", ConvertPointToTargetString(w11ll, w1ll)); - - // w11ll->root - EXPECT_EQ("4,6", ConvertPointToTargetString(w11ll, &root)); - - // w11ll->w12 - EXPECT_EQ("-4,-4", ConvertPointToTargetString(w11ll, w12)); -} - -#if !defined(NDEBUG) -// Verifies PrintWindowHierarchy() doesn't crash with a layerless window. -TEST_F(WindowTest, PrintWindowHierarchyNotCrashLayerless) { - Window root(NULL); - root.Init(WINDOW_LAYER_NONE); - root.SetBounds(gfx::Rect(0, 0, 100, 100)); - root.PrintWindowHierarchy(0); -} -#endif - -namespace { - -// See AddWindowsFromString() for details. -aura::Window* CreateWindowFromDescription(const std::string& description, - WindowDelegate* delegate) { - WindowLayerType window_type = WINDOW_LAYER_NOT_DRAWN; - std::vector<std::string> tokens; - Tokenize(description, ":", &tokens); - DCHECK(!tokens.empty()); - std::string name(tokens[0]); - tokens.erase(tokens.begin()); - if (!tokens.empty()) { - if (tokens[0] == "ll") { - window_type = WINDOW_LAYER_NONE; - tokens.erase(tokens.begin()); - } - DCHECK(tokens.empty()) << "unknown tokens for creating window " - << description; - } - Window* window = new Window(delegate); - window->Init(window_type); - window->SetName(name); - // Window name is only propagated to layer in debug builds. - if (window->layer()) - window->layer()->set_name(name); - return window; -} - -// Creates and adds a tree of windows to |parent|. |description| consists -// of the following pieces: -// X: Identifies a new window. Consists of a name and optionally ":ll" to -// specify WINDOW_LAYER_NONE, eg "w1:ll". -// []: optionally used to specify the children of the window. Contains any -// number of window identifiers and their corresponding children. -// For example: "[ a [ a1 a2:ll ] b c [ c1 ] ]" creates the tree: -// a -// a1 -// a2 -> WINDOW_LAYER_NONE. -// b -// c -// c1 -// NOTE: you must have a space after every token. -std::string::size_type AddWindowsFromString(aura::Window* parent, - const std::string& description, - std::string::size_type start_pos, - WindowDelegate* delegate) { - DCHECK(parent); - std::string::size_type end_pos = description.find(' ', start_pos); - while (end_pos != std::string::npos) { - const std::string::size_type part_length = end_pos - start_pos; - const std::string window_description = - description.substr(start_pos, part_length); - if (window_description == "[") { - start_pos = AddWindowsFromString(parent->children().back(), - description, - end_pos + 1, - delegate); - end_pos = description.find(' ', start_pos); - if (end_pos == std::string::npos && start_pos != end_pos) - end_pos = description.length(); - } else if (window_description == "]") { - ++end_pos; - break; - } else { - Window* window = - CreateWindowFromDescription(window_description, delegate); - parent->AddChild(window); - start_pos = ++end_pos; - end_pos = description.find(' ', start_pos); - } - } - return end_pos; -} - -// Used by BuildRootWindowTreeDescription(). -std::string BuildWindowTreeDescription(const aura::Window& window) { - std::string result; - result += window.name(); - if (window.children().empty()) - return result; - - result += " [ "; - for (size_t i = 0; i < window.children().size(); ++i) { - if (i != 0) - result += " "; - result += BuildWindowTreeDescription(*(window.children()[i])); - } - result += " ]"; - return result; -} - -// Creates a string from |window|. See AddWindowsFromString() for details of the -// returned string. This does *not* include the layer type in the description, -// on the name. -std::string BuildRootWindowTreeDescription(const aura::Window& window) { - std::string result; - for (size_t i = 0; i < window.children().size(); ++i) { - if (i != 0) - result += " "; - result += BuildWindowTreeDescription(*(window.children()[i])); - } - return result; -} - -// Used by BuildRootWindowTreeDescription(). -std::string BuildLayerTreeDescription(const ui::Layer& layer) { - std::string result; - result += layer.name(); - if (layer.children().empty()) - return result; - - result += " [ "; - for (size_t i = 0; i < layer.children().size(); ++i) { - if (i != 0) - result += " "; - result += BuildLayerTreeDescription(*(layer.children()[i])); - } - result += " ]"; - return result; -} - -// Builds a string for all the children of |layer|. The returned string is in -// the same format as AddWindowsFromString() but only includes the name of the -// layers. -std::string BuildRootLayerTreeDescription(const ui::Layer& layer) { - std::string result; - for (size_t i = 0; i < layer.children().size(); ++i) { - if (i != 0) - result += " "; - result += BuildLayerTreeDescription(*(layer.children()[i])); - } - return result; -} - -// Returns the first window whose name matches |name| in |parent|. -aura::Window* FindWindowByName(aura::Window* parent, - const std::string& name) { - if (parent->name() == name) - return parent; - for (size_t i = 0; i < parent->children().size(); ++i) { - aura::Window* child = FindWindowByName(parent->children()[i], name); - if (child) - return child; - } - return NULL; -} - -} // namespace - -// Direction to stack. -enum StackType { - STACK_ABOVE, - STACK_BELOW, - STACK_AT_BOTTOM, - STACK_AT_TOP, -}; - -// Permutations of StackChildAt with various data. -TEST_F(WindowTest, StackChildAtLayerless) { - struct TestData { - // Describes the window tree to create. See AddWindowsFromString() for - // details. - const std::string initial_description; - - // Identifies the window to move. - const std::string source_window; - - // Window to move |source_window| relative to. Not used for STACK_AT_BOTTOM - // or STACK_AT_TOP. - const std::string target_window; - - StackType stack_type; - - // Expected window and layer results. - const std::string expected_description; - const std::string expected_layer_description; - } data[] = { - // 1 at top. - { - "1:ll [ 11 12 ] 2:ll [ 21 ]", - "1", - "", - STACK_AT_TOP, - "2 [ 21 ] 1 [ 11 12 ]", - "21 11 12", - }, - - // 1 at bottom. - { - "1:ll [ 11 12 ] 2:ll [ 21 ]", - "1", - "", - STACK_AT_BOTTOM, - "1 [ 11 12 ] 2 [ 21 ]", - "11 12 21", - }, - - // 2 at bottom. - { - "1:ll [ 11 12 ] 2:ll [ 21 ]", - "2", - "", - STACK_AT_BOTTOM, - "2 [ 21 ] 1 [ 11 12 ]", - "21 11 12", - }, - - // 3 below 2. - { - "1:ll [ 11 12 ] 2:ll [ 21 ] 3:ll", - "3", - "2", - STACK_BELOW, - "1 [ 11 12 ] 3 2 [ 21 ]", - "11 12 21", - }, - - // 2 below 1. - { - "1:ll [ 11 12 ] 2:ll [ 21 ]", - "2", - "1", - STACK_BELOW, - "2 [ 21 ] 1 [ 11 12 ]", - "21 11 12", - }, - - // 1 above 3. - { - "1:ll [ 11 12 ] 2:ll [ 21 ] 3:ll", - "1", - "3", - STACK_ABOVE, - "2 [ 21 ] 3 1 [ 11 12 ]", - "21 11 12", - }, - - // 1 above 2. - { - "1:ll [ 11 12 ] 2:ll [ 21 ]", - "1", - "2", - STACK_ABOVE, - "2 [ 21 ] 1 [ 11 12 ]", - "21 11 12", - }, - }; - for (size_t i = 0; i < arraysize(data); ++i) { - test::TestWindowDelegate delegate; - Window root(NULL); - root.Init(WINDOW_LAYER_NOT_DRAWN); - root.SetBounds(gfx::Rect(0, 0, 100, 100)); - AddWindowsFromString( - &root, - data[i].initial_description, - static_cast<std::string::size_type>(0), &delegate); - aura::Window* source = FindWindowByName(&root, data[i].source_window); - ASSERT_TRUE(source != NULL) << "unable to find source window " - << data[i].source_window << " at " << i; - aura::Window* target = FindWindowByName(&root, data[i].target_window); - switch (data[i].stack_type) { - case STACK_ABOVE: - ASSERT_TRUE(target != NULL) << "unable to find target window " - << data[i].target_window << " at " << i; - source->parent()->StackChildAbove(source, target); - break; - case STACK_BELOW: - ASSERT_TRUE(target != NULL) << "unable to find target window " - << data[i].target_window << " at " << i; - source->parent()->StackChildBelow(source, target); - break; - case STACK_AT_BOTTOM: - source->parent()->StackChildAtBottom(source); - break; - case STACK_AT_TOP: - source->parent()->StackChildAtTop(source); - break; - } - EXPECT_EQ(data[i].expected_layer_description, - BuildRootLayerTreeDescription(*root.layer())) - << "layer tree doesn't match at " << i; - EXPECT_EQ(data[i].expected_description, - BuildRootWindowTreeDescription(root)) - << "window tree doesn't match at " << i; - } -} - -namespace { - -class TestLayerAnimationObserver : public ui::LayerAnimationObserver { - public: - TestLayerAnimationObserver() - : animation_completed_(false), - animation_aborted_(false) {} - virtual ~TestLayerAnimationObserver() {} - - bool animation_completed() const { return animation_completed_; } - bool animation_aborted() const { return animation_aborted_; } - - void Reset() { - animation_completed_ = false; - animation_aborted_ = false; - } - - private: - // ui::LayerAnimationObserver: - virtual void OnLayerAnimationEnded( - ui::LayerAnimationSequence* sequence) override { - animation_completed_ = true; - } - - virtual void OnLayerAnimationAborted( - ui::LayerAnimationSequence* sequence) override { - animation_aborted_ = true; - } - - virtual void OnLayerAnimationScheduled( - ui::LayerAnimationSequence* sequence) override { - } - - bool animation_completed_; - bool animation_aborted_; - - DISALLOW_COPY_AND_ASSIGN(TestLayerAnimationObserver); -}; - -} - -TEST_F(WindowTest, WindowDestroyCompletesAnimations) { - ui::ScopedAnimationDurationScaleMode test_duration_mode( - ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION); - scoped_refptr<ui::LayerAnimator> animator = - ui::LayerAnimator::CreateImplicitAnimator(); - TestLayerAnimationObserver observer; - animator->AddObserver(&observer); - // Make sure destroying a Window completes the animation. - { - scoped_ptr<Window> window(CreateTestWindowWithId(1, root_window())); - window->layer()->SetAnimator(animator.get()); - - gfx::Transform transform; - transform.Scale(0.5f, 0.5f); - window->SetTransform(transform); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FALSE(observer.animation_completed()); - } - EXPECT_TRUE(animator.get()); - EXPECT_FALSE(animator->is_animating()); - EXPECT_TRUE(observer.animation_completed()); - EXPECT_FALSE(observer.animation_aborted()); - animator->RemoveObserver(&observer); - observer.Reset(); - - animator = ui::LayerAnimator::CreateImplicitAnimator(); - animator->AddObserver(&observer); - ui::Layer layer; - layer.SetAnimator(animator.get()); - { - scoped_ptr<Window> window(CreateTestWindowWithId(1, root_window())); - window->layer()->Add(&layer); - - gfx::Transform transform; - transform.Scale(0.5f, 0.5f); - layer.SetTransform(transform); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FALSE(observer.animation_completed()); - } - - EXPECT_TRUE(animator.get()); - EXPECT_FALSE(animator->is_animating()); - EXPECT_TRUE(observer.animation_completed()); - EXPECT_FALSE(observer.animation_aborted()); - animator->RemoveObserver(&observer); -} - -} // namespace test -} // namespace aura
diff --git a/ui/base/BUILD.gn b/ui/base/BUILD.gn index d826a52..fb7ea89 100644 --- a/ui/base/BUILD.gn +++ b/ui/base/BUILD.gn
@@ -16,13 +16,6 @@ component("base") { output_name = "ui_base" sources = [ - "accelerators/accelerator.cc", - "accelerators/accelerator.h", - "accelerators/accelerator_manager.cc", - "accelerators/accelerator_manager.h", - "accelerators/menu_label_accelerator_util_linux.cc", - "accelerators/menu_label_accelerator_util_linux.h", - "accelerators/platform_accelerator.h", "android/system_ui_resource_manager.h", "android/ui_base_jni_registrar.cc", "android/ui_base_jni_registrar.h", @@ -32,26 +25,6 @@ "android/window_android.h", "android/window_android_compositor.h", "android/window_android_observer.h", - "base_window.cc", - "base_window.h", - "clipboard/clipboard.cc", - "clipboard/clipboard.h", - "clipboard/clipboard_android.cc", - "clipboard/clipboard_android.h", - "clipboard/clipboard_constants.cc", - "clipboard/clipboard_mac.h", - "clipboard/clipboard_mac.mm", - "clipboard/clipboard_types.h", - "clipboard/clipboard_util_win.cc", - "clipboard/clipboard_util_win.h", - "clipboard/clipboard_win.cc", - "clipboard/clipboard_win.h", - "clipboard/custom_data_helper.cc", - "clipboard/custom_data_helper.h", - "clipboard/custom_data_helper_linux.cc", - "clipboard/custom_data_helper_mac.mm", - "clipboard/scoped_clipboard_writer.cc", - "clipboard/scoped_clipboard_writer.h", "cursor/cursor.cc", "cursor/cursor.h", "cursor/cursor_android.cc", @@ -59,34 +32,6 @@ "cursor/cursor_util.cc", "cursor/cursor_util.h", "cursor/cursor_win.cc", - "cursor/cursors_aura.cc", - "cursor/cursors_aura.h", - "cursor/image_cursors.cc", - "cursor/image_cursors.h", - "default_theme_provider.cc", - "default_theme_provider.h", - "default_theme_provider_mac.mm", - "dragdrop/drag_drop_types.h", - "dragdrop/drag_drop_types_win.cc", - "dragdrop/drag_source_win.cc", - "dragdrop/drag_source_win.h", - "dragdrop/drag_utils.cc", - "dragdrop/drag_utils.h", - "dragdrop/drag_utils_aura.cc", - "dragdrop/drag_utils_mac.mm", - "dragdrop/drag_utils_win.cc", - "dragdrop/drop_target_event.cc", - "dragdrop/drop_target_event.h", - "dragdrop/drop_target_win.cc", - "dragdrop/drop_target_win.h", - "dragdrop/file_info.cc", - "dragdrop/file_info.h", - "dragdrop/os_exchange_data.cc", - "dragdrop/os_exchange_data.h", - "dragdrop/os_exchange_data_provider_mac.h", - "dragdrop/os_exchange_data_provider_mac.mm", - "dragdrop/os_exchange_data_provider_win.cc", - "dragdrop/os_exchange_data_provider_win.h", "hit_test.h", "l10n/formatter.cc", "l10n/formatter.h", @@ -109,34 +54,6 @@ "layout.cc", "layout.h", "layout_mac.mm", - "models/button_menu_item_model.cc", - "models/button_menu_item_model.h", - "models/combobox_model.cc", - "models/combobox_model.h", - "models/combobox_model_observer.h", - "models/dialog_model.cc", - "models/dialog_model.h", - "models/list_model.h", - "models/list_model_observer.h", - "models/list_selection_model.cc", - "models/list_selection_model.h", - "models/menu_model.cc", - "models/menu_model.h", - "models/menu_model_delegate.h", - "models/menu_separator_types.h", - "models/simple_combobox_model.cc", - "models/simple_combobox_model.h", - "models/simple_menu_model.cc", - "models/simple_menu_model.h", - "models/table_model.cc", - "models/table_model.h", - "models/table_model_observer.h", - "models/tree_model.cc", - "models/tree_model.h", - "models/tree_node_iterator.h", - "models/tree_node_model.h", - "nine_image_painter_factory.cc", - "nine_image_painter_factory.h", "resource/data_pack.cc", "resource/data_pack.h", "resource/resource_bundle.cc", @@ -152,15 +69,10 @@ "resource/resource_handle.h", "text/bytes_formatting.cc", "text/bytes_formatting.h", - "theme_provider.cc", - "theme_provider.h", "touch/touch_device.h", - "touch/touch_editing_controller.cc", - "touch/touch_editing_controller.h", "touch/touch_enabled.cc", "touch/touch_enabled.h", "ui_base_export.h", - "ui_base_exports.cc", "ui_base_paths.cc", "ui_base_paths.h", "ui_base_switches.cc", @@ -207,8 +119,6 @@ sources += [ "touch/touch_device_win.cc" ] } else if (is_android) { sources += [ "touch/touch_device_android.cc" ] - } else if (use_ozone) { - sources += [ "touch/touch_device_ozone.cc" ] } else if (use_aura && use_x11) { sources += [ "touch/touch_device_aurax11.cc" ] } else { @@ -237,129 +147,12 @@ "//url", ] - if (ui_base_build_ime) { - if (!is_android) { - deps += [ "//ui/events" ] - } - - sources += [ - "ime/candidate_window.cc", - "ime/candidate_window.h", - "ime/chromeos/character_composer.cc", - "ime/chromeos/character_composer.h", - "ime/chromeos/ime_bridge.cc", - "ime/chromeos/ime_bridge.h", - "ime/chromeos/ime_keymap.cc", - "ime/chromeos/ime_keymap.h", - "ime/chromeos/mock_ime_candidate_window_handler.cc", - "ime/chromeos/mock_ime_candidate_window_handler.h", - "ime/chromeos/mock_ime_engine_handler.cc", - "ime/chromeos/mock_ime_engine_handler.h", - "ime/chromeos/mock_ime_input_context_handler.cc", - "ime/chromeos/mock_ime_input_context_handler.h", - "ime/composition_text.cc", - "ime/composition_text.h", - "ime/composition_text_util_pango.cc", - "ime/composition_text_util_pango.h", - "ime/composition_underline.h", - "ime/dummy_input_method_delegate.cc", - "ime/dummy_input_method_delegate.h", - "ime/infolist_entry.cc", - "ime/infolist_entry.h", - "ime/input_method.h", - "ime/input_method_auralinux.cc", - "ime/input_method_auralinux.h", - "ime/input_method_base.cc", - "ime/input_method_base.h", - "ime/input_method_chromeos.cc", - "ime/input_method_chromeos.h", - "ime/input_method_delegate.h", - "ime/input_method_factory.cc", - "ime/input_method_factory.h", - "ime/input_method_initializer.cc", - "ime/input_method_initializer.h", - "ime/input_method_mac.h", - "ime/input_method_mac.mm", - "ime/input_method_minimal.cc", - "ime/input_method_minimal.h", - "ime/input_method_observer.h", - "ime/input_method_win.cc", - "ime/input_method_win.h", - "ime/linux/fake_input_method_context.cc", - "ime/linux/fake_input_method_context.h", - "ime/linux/fake_input_method_context_factory.cc", - "ime/linux/fake_input_method_context_factory.h", - "ime/linux/linux_input_method_context.h", - "ime/linux/linux_input_method_context_factory.cc", - "ime/linux/linux_input_method_context_factory.h", - "ime/mock_input_method.cc", - "ime/mock_input_method.h", - "ime/remote_input_method_delegate_win.h", - "ime/remote_input_method_win.cc", - "ime/remote_input_method_win.h", - "ime/text_input_client.cc", - "ime/text_input_client.h", - "ime/text_input_focus_manager.cc", - "ime/text_input_focus_manager.h", - "ime/text_input_type.h", - "ime/win/imm32_manager.cc", - "ime/win/imm32_manager.h", - "ime/win/tsf_input_scope.cc", - "ime/win/tsf_input_scope.h", - ] - - if (!use_aura || (!is_linux && !use_ozone)) { - sources -= [ - "ime/input_method_auralinux.cc", - "ime/input_method_auralinux.h", - ] - } - - if (!toolkit_views && !use_aura) { - sources -= [ - "ime/input_method_factory.cc", - "ime/input_method_factory.h", - "ime/input_method_minimal.cc", - "ime/input_method_minimal.h", - ] - } - - if (is_chromeos) { - deps += [ "//chromeos" ] - } - - if (use_pango) { - configs += [ "//build/config/linux:pangocairo" ] - } else { - sources -= [ - "ime/composition_text_util_pango.cc", - "ime/composition_text_util_pango.h", - ] - } - } - - if (toolkit_views) { - deps += [ "//ui/events" ] - } - - if (use_x11 && use_aura) { - sources += [ - "x/selection_owner.cc", - "x/selection_owner.h", - "x/selection_requestor.cc", - "x/selection_requestor.h", - "x/selection_utils.cc", - "x/selection_utils.h", - ] - } - if (use_aura) { deps += [ "//ui/events" ] } else { sources -= [ "cursor/cursor.cc", "cursor/cursor.h", - "dragdrop/drag_utils_aura.cc", ] } if (use_x11) { @@ -379,10 +172,6 @@ sources -= [ "resource/resource_bundle_auralinux.cc" ] } - if (use_aura && is_win) { - sources -= [ "dragdrop/drag_utils_aura.cc" ] - } - if (is_linux) { configs += [ "//build/config/linux:fontconfig", @@ -390,22 +179,6 @@ ] } - if ((is_linux && !is_chromeos) || is_chromeos) { - if (!toolkit_views && !use_aura) { - sources -= [ - "dragdrop/drag_utils.cc", - "dragdrop/drag_utils.h", - ] - } - } - - if (is_chromeos || (use_aura && is_linux && !use_x11)) { - sources += [ - "dragdrop/os_exchange_data_provider_aura.cc", - "dragdrop/os_exchange_data_provider_aura.h", - ] - } - libs = [] if (is_win) { sources += [ @@ -432,24 +205,15 @@ "oleacc.lib", ] } else { - if (!use_aura) { - sources -= [ - "view_prop.cc", - "view_prop.h", - ] - } + sources -= [ + "view_prop.cc", + "view_prop.h", + ] } if (is_mac) { deps += [ "//third_party/mozilla" ] - sources -= [ - "cursor/image_cursors.cc", - "cursor/image_cursors.h", - "dragdrop/drag_utils.cc", - "dragdrop/drag_utils.h", - ] - libs += [ "Accelerate.framework", "AudioUnit.framework", @@ -466,56 +230,17 @@ configs += [ "//build/config/linux:x11" ] } - if (use_aura) { - if (use_x11) { - sources += [ - "cursor/cursor_loader_x11.cc", - "cursor/cursor_loader_x11.h", - "cursor/cursor_x11.cc", - ] - if (!is_chromeos) { - # These Aura X11 files aren't used on ChromeOS. - sources += [ - "dragdrop/os_exchange_data_provider_aurax11.cc", - "dragdrop/os_exchange_data_provider_aurax11.h", - ] - } - } - } - if (use_ozone) { + if (use_x11) { sources += [ - "cursor/cursor_loader_ozone.cc", - "cursor/cursor_loader_ozone.h", - "cursor/cursor_ozone.cc", - "cursor/ozone/bitmap_cursor_factory_ozone.cc", - "cursor/ozone/bitmap_cursor_factory_ozone.h", - ] - - deps += [ "//ui/ozone:ozone_base" ] - } - - if (!toolkit_views) { - sources -= [ - "dragdrop/drag_drop_types.h", - "dragdrop/drop_target_event.cc", - "dragdrop/drop_target_event.h", - "dragdrop/os_exchange_data.cc", - "dragdrop/os_exchange_data.h", - "nine_image_painter_factory.cc", - "nine_image_painter_factory.h", + "cursor/cursor_loader_x11.cc", + "cursor/cursor_loader_x11.h", + "cursor/cursor_x11.cc", ] } if (is_android) { sources -= [ - "default_theme_provider.cc", - "dragdrop/drag_utils.cc", - "dragdrop/drag_utils.h", "l10n/l10n_font_util.cc", - "models/button_menu_item_model.cc", - "models/dialog_model.cc", - "theme_provider.cc", - "touch/touch_editing_controller.cc", "ui_base_types.cc", ] @@ -534,55 +259,11 @@ if (is_android && !use_aura) { sources -= [ "cursor/cursor_android.cc" ] } - - # Aura clipboard. - if (use_aura) { - if (use_x11) { - sources += [ "clipboard/clipboard_aurax11.cc" ] - } else if (!is_win) { - # This file is used for all non-X11, non-Windows aura Builds. - sources += [ "clipboard/clipboard_aura.cc" ] - } - } -} - -source_set("test_support") { - testonly = true - sources = [ - "test/ui_controls.h", - "test/ui_controls_aura.cc", - "test/ui_controls_internal_win.cc", - "test/ui_controls_internal_win.h", - "test/ui_controls_mac.mm", - "test/ui_controls_win.cc", - ] - - public_deps = [ - ":base", - ] - deps = [ - "//base", - "//skia", - "//testing/gtest", - "//ui/events:events_base", - "//ui/gfx", - "//ui/gfx/geometry", - ] - - if (ui_base_build_ime) { - sources += [ - "ime/dummy_input_method.cc", - "ime/dummy_input_method.h", - "ime/dummy_text_input_client.cc", - "ime/dummy_text_input_client.h", - ] - } } if (is_android) { generate_jni("ui_base_jni_headers") { sources = [ - "../android/java/src/org/chromium/ui/base/Clipboard.java", "../android/java/src/org/chromium/ui/base/DeviceFormFactor.java", "../android/java/src/org/chromium/ui/base/LocalizationUtils.java", "../android/java/src/org/chromium/ui/base/ResourceBundle.java", @@ -622,42 +303,14 @@ sources += [ "accelerators/accelerator_manager_unittest.cc", "accelerators/menu_label_accelerator_util_linux_unittest.cc", - "clipboard/custom_data_helper_unittest.cc", - "dragdrop/os_exchange_data_provider_aurax11_unittest.cc", "models/list_model_unittest.cc", "models/list_selection_model_unittest.cc", "models/tree_node_model_unittest.cc", "test/data/resource.h", "text/bytes_formatting_unittest.cc", "view_prop_unittest.cc", - "x/selection_requestor_unittest.cc", ] - if (!use_x11) { - if (is_chromeos) { - # These were already removed in the chromeos case. - sources -= [ - "ime/chromeos/character_composer_unittest.cc", - "ime/input_method_chromeos_unittest.cc", - ] - } - } - - if (ui_base_build_ime) { - sources += [ - "ime/candidate_window_unittest.cc", - "ime/chromeos/character_composer_unittest.cc", - "ime/input_method_base_unittest.cc", - "ime/input_method_chromeos_unittest.cc", - "ime/remote_input_method_win_unittest.cc", - "ime/win/imm32_manager_unittest.cc", - "ime/win/tsf_input_scope_unittest.cc", - ] - if (use_x11) { - sources += [ "ime/composition_text_util_pango_unittest.cc" ] - } - } - deps = [ "//base", "//base/allocator", @@ -668,7 +321,6 @@ "//testing/gtest", "//third_party/icu", "//ui/base", - "//ui/base:test_support", "//ui/events:events_base", "//ui/events:test_support", "//ui/gfx:test_support", @@ -680,7 +332,6 @@ if (is_win) { sources += [ - "dragdrop/os_exchange_data_win_unittest.cc", "win/hwnd_subclass_unittest.cc", "win/open_file_name_win_unittest.cc", ] @@ -736,21 +387,8 @@ ] } - if (use_aura || toolkit_views) { - sources += [ "dragdrop/os_exchange_data_unittest.cc" ] - - deps += [ - "//ui/events", - "//ui/events/platform", - ] - } - if (is_chromeos) { sources += [ "../chromeos/touch_exploration_controller_unittest.cc" ] - sources -= [ - "dragdrop/os_exchange_data_provider_aurax11_unittest.cc", - "x/selection_requestor_unittest.cc", - ] deps += [ "//chromeos", "//ui/aura:test_support",
diff --git a/ui/base/accelerators/accelerator.cc b/ui/base/accelerators/accelerator.cc deleted file mode 100644 index b4a8cc6..0000000 --- a/ui/base/accelerators/accelerator.cc +++ /dev/null
@@ -1,265 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/accelerators/accelerator.h" - -#if defined(OS_WIN) -#include <windows.h> -#endif - -#include "base/i18n/rtl.h" -#include "base/logging.h" -#include "base/strings/string_util.h" -#include "base/strings/utf_string_conversions.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/strings/grit/ui_strings.h" - -#if !defined(OS_WIN) && (defined(USE_AURA) || defined(OS_MACOSX)) -#include "ui/events/keycodes/keyboard_code_conversion.h" -#endif - -namespace ui { - -Accelerator::Accelerator() - : key_code_(ui::VKEY_UNKNOWN), - type_(ui::ET_KEY_PRESSED), - modifiers_(0), - is_repeat_(false) { -} - -Accelerator::Accelerator(KeyboardCode keycode, int modifiers) - : key_code_(keycode), - type_(ui::ET_KEY_PRESSED), - modifiers_(modifiers), - is_repeat_(false) { -} - -Accelerator::Accelerator(const Accelerator& accelerator) { - key_code_ = accelerator.key_code_; - type_ = accelerator.type_; - modifiers_ = accelerator.modifiers_; - is_repeat_ = accelerator.is_repeat_; - if (accelerator.platform_accelerator_.get()) - platform_accelerator_ = accelerator.platform_accelerator_->CreateCopy(); -} - -Accelerator::~Accelerator() { -} - -Accelerator& Accelerator::operator=(const Accelerator& accelerator) { - if (this != &accelerator) { - key_code_ = accelerator.key_code_; - type_ = accelerator.type_; - modifiers_ = accelerator.modifiers_; - is_repeat_ = accelerator.is_repeat_; - if (accelerator.platform_accelerator_.get()) - platform_accelerator_ = accelerator.platform_accelerator_->CreateCopy(); - else - platform_accelerator_.reset(); - } - return *this; -} - -bool Accelerator::operator <(const Accelerator& rhs) const { - if (key_code_ != rhs.key_code_) - return key_code_ < rhs.key_code_; - if (type_ != rhs.type_) - return type_ < rhs.type_; - return modifiers_ < rhs.modifiers_; -} - -bool Accelerator::operator ==(const Accelerator& rhs) const { - if ((key_code_ == rhs.key_code_) && (type_ == rhs.type_) && - (modifiers_ == rhs.modifiers_)) - return true; - - bool platform_equal = - platform_accelerator_.get() && rhs.platform_accelerator_.get() && - platform_accelerator_.get() == rhs.platform_accelerator_.get(); - - return platform_equal; -} - -bool Accelerator::operator !=(const Accelerator& rhs) const { - return !(*this == rhs); -} - -bool Accelerator::IsShiftDown() const { - return (modifiers_ & EF_SHIFT_DOWN) != 0; -} - -bool Accelerator::IsCtrlDown() const { - return (modifiers_ & EF_CONTROL_DOWN) != 0; -} - -bool Accelerator::IsAltDown() const { - return (modifiers_ & EF_ALT_DOWN) != 0; -} - -bool Accelerator::IsCmdDown() const { - return (modifiers_ & EF_COMMAND_DOWN) != 0; -} - -bool Accelerator::IsRepeat() const { - return is_repeat_; -} - -base::string16 Accelerator::GetShortcutText() const { - int string_id = 0; - switch (key_code_) { - case ui::VKEY_TAB: - string_id = IDS_APP_TAB_KEY; - break; - case ui::VKEY_RETURN: - string_id = IDS_APP_ENTER_KEY; - break; - case ui::VKEY_ESCAPE: - string_id = IDS_APP_ESC_KEY; - break; - case ui::VKEY_PRIOR: - string_id = IDS_APP_PAGEUP_KEY; - break; - case ui::VKEY_NEXT: - string_id = IDS_APP_PAGEDOWN_KEY; - break; - case ui::VKEY_END: - string_id = IDS_APP_END_KEY; - break; - case ui::VKEY_HOME: - string_id = IDS_APP_HOME_KEY; - break; - case ui::VKEY_INSERT: - string_id = IDS_APP_INSERT_KEY; - break; - case ui::VKEY_DELETE: - string_id = IDS_APP_DELETE_KEY; - break; - case ui::VKEY_LEFT: - string_id = IDS_APP_LEFT_ARROW_KEY; - break; - case ui::VKEY_RIGHT: - string_id = IDS_APP_RIGHT_ARROW_KEY; - break; - case ui::VKEY_UP: - string_id = IDS_APP_UP_ARROW_KEY; - break; - case ui::VKEY_DOWN: - string_id = IDS_APP_DOWN_ARROW_KEY; - break; - case ui::VKEY_BACK: - string_id = IDS_APP_BACKSPACE_KEY; - break; - case ui::VKEY_F1: - string_id = IDS_APP_F1_KEY; - break; - case ui::VKEY_F11: - string_id = IDS_APP_F11_KEY; - break; - case ui::VKEY_OEM_COMMA: - string_id = IDS_APP_COMMA_KEY; - break; - case ui::VKEY_OEM_PERIOD: - string_id = IDS_APP_PERIOD_KEY; - break; - case ui::VKEY_MEDIA_NEXT_TRACK: - string_id = IDS_APP_MEDIA_NEXT_TRACK_KEY; - break; - case ui::VKEY_MEDIA_PLAY_PAUSE: - string_id = IDS_APP_MEDIA_PLAY_PAUSE_KEY; - break; - case ui::VKEY_MEDIA_PREV_TRACK: - string_id = IDS_APP_MEDIA_PREV_TRACK_KEY; - break; - case ui::VKEY_MEDIA_STOP: - string_id = IDS_APP_MEDIA_STOP_KEY; - break; - default: - break; - } - - base::string16 shortcut; - if (!string_id) { -#if defined(OS_WIN) - // Our fallback is to try translate the key code to a regular character - // unless it is one of digits (VK_0 to VK_9). Some keyboard - // layouts have characters other than digits assigned in - // an unshifted mode (e.g. French AZERY layout has 'a with grave - // accent' for '0'). For display in the menu (e.g. Ctrl-0 for the - // default zoom level), we leave VK_[0-9] alone without translation. - wchar_t key; - if (key_code_ >= '0' && key_code_ <= '9') - key = static_cast<wchar_t>(key_code_); - else - key = LOWORD(::MapVirtualKeyW(key_code_, MAPVK_VK_TO_CHAR)); - shortcut += key; -#elif defined(USE_AURA) || defined(OS_MACOSX) - const uint16 c = GetCharacterFromKeyCode(key_code_, false); - if (c != 0) - shortcut += - static_cast<base::string16::value_type>(base::ToUpperASCII(c)); -#endif - } else { - shortcut = l10n_util::GetStringUTF16(string_id); - } - - // Checking whether the character used for the accelerator is alphanumeric. - // If it is not, then we need to adjust the string later on if the locale is - // right-to-left. See below for more information of why such adjustment is - // required. - base::string16 shortcut_rtl; - bool adjust_shortcut_for_rtl = false; - if (base::i18n::IsRTL() && shortcut.length() == 1 && - !IsAsciiAlpha(shortcut[0]) && !IsAsciiDigit(shortcut[0])) { - adjust_shortcut_for_rtl = true; - shortcut_rtl.assign(shortcut); - } - - if (IsShiftDown()) - shortcut = l10n_util::GetStringFUTF16(IDS_APP_SHIFT_MODIFIER, shortcut); - - // Note that we use 'else-if' in order to avoid using Ctrl+Alt as a shortcut. - // See http://blogs.msdn.com/oldnewthing/archive/2004/03/29/101121.aspx for - // more information. - if (IsCtrlDown()) - shortcut = l10n_util::GetStringFUTF16(IDS_APP_CONTROL_MODIFIER, shortcut); - else if (IsAltDown()) - shortcut = l10n_util::GetStringFUTF16(IDS_APP_ALT_MODIFIER, shortcut); - - if (IsCmdDown()) - shortcut = l10n_util::GetStringFUTF16(IDS_APP_COMMAND_MODIFIER, shortcut); - - // For some reason, menus in Windows ignore standard Unicode directionality - // marks (such as LRE, PDF, etc.). On RTL locales, we use RTL menus and - // therefore any text we draw for the menu items is drawn in an RTL context. - // Thus, the text "Ctrl++" (which we currently use for the Zoom In option) - // appears as "++Ctrl" in RTL because the Unicode BiDi algorithm puts - // punctuations on the left when the context is right-to-left. Shortcuts that - // do not end with a punctuation mark (such as "Ctrl+H" do not have this - // problem). - // - // The only way to solve this problem is to adjust the string if the locale - // is RTL so that it is drawn correctly in an RTL context. Instead of - // returning "Ctrl++" in the above example, we return "++Ctrl". This will - // cause the text to appear as "Ctrl++" when Windows draws the string in an - // RTL context because the punctuation no longer appears at the end of the - // string. - // - // TODO(idana) bug# 1232732: this hack can be avoided if instead of using - // views::Menu we use views::MenuItemView because the latter is a View - // subclass and therefore it supports marking text as RTL or LTR using - // standard Unicode directionality marks. - if (adjust_shortcut_for_rtl) { - int key_length = static_cast<int>(shortcut_rtl.length()); - DCHECK_GT(key_length, 0); - shortcut_rtl.append(base::ASCIIToUTF16("+")); - - // Subtracting the size of the shortcut key and 1 for the '+' sign. - shortcut_rtl.append(shortcut, 0, shortcut.length() - key_length - 1); - shortcut.swap(shortcut_rtl); - } - - return shortcut; -} - -} // namespace ui
diff --git a/ui/base/accelerators/accelerator.h b/ui/base/accelerators/accelerator.h deleted file mode 100644 index 430a209..0000000 --- a/ui/base/accelerators/accelerator.h +++ /dev/null
@@ -1,122 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This class describe a keyboard accelerator (or keyboard shortcut). -// Keyboard accelerators are registered with the FocusManager. -// It has a copy constructor and assignment operator so that it can be copied. -// It also defines the < operator so that it can be used as a key in a std::map. -// - -#ifndef UI_BASE_ACCELERATORS_ACCELERATOR_H_ -#define UI_BASE_ACCELERATORS_ACCELERATOR_H_ - -#include "base/memory/scoped_ptr.h" -#include "base/strings/string16.h" -#include "ui/base/accelerators/platform_accelerator.h" -#include "ui/base/ui_base_export.h" -#include "ui/events/event_constants.h" -#include "ui/events/keycodes/keyboard_codes.h" - -namespace ui { - -class PlatformAccelerator; - -// This is a cross-platform class for accelerator keys used in menus. -// |platform_accelerator| should be used to store platform specific data. -class UI_BASE_EXPORT Accelerator { - public: - Accelerator(); - Accelerator(ui::KeyboardCode keycode, int modifiers); - Accelerator(const Accelerator& accelerator); - ~Accelerator(); - - Accelerator& operator=(const Accelerator& accelerator); - - // Define the < operator so that the KeyboardShortcut can be used as a key in - // a std::map. - bool operator <(const Accelerator& rhs) const; - - bool operator ==(const Accelerator& rhs) const; - - bool operator !=(const Accelerator& rhs) const; - - ui::KeyboardCode key_code() const { return key_code_; } - - // Sets the event type if the accelerator should be processed on an event - // other than ui::ET_KEY_PRESSED. - void set_type(ui::EventType type) { type_ = type; } - ui::EventType type() const { return type_; } - - int modifiers() const { return modifiers_; } - - bool IsShiftDown() const; - bool IsCtrlDown() const; - bool IsAltDown() const; - bool IsCmdDown() const; - bool IsRepeat() const; - - // Returns a string with the localized shortcut if any. - base::string16 GetShortcutText() const; - - void set_platform_accelerator(scoped_ptr<PlatformAccelerator> p) { - platform_accelerator_ = p.Pass(); - } - - // This class keeps ownership of the returned object. - const PlatformAccelerator* platform_accelerator() const { - return platform_accelerator_.get(); - } - - void set_is_repeat(bool is_repeat) { is_repeat_ = is_repeat; } - - protected: - // The keycode (VK_...). - KeyboardCode key_code_; - - // The event type (usually ui::ET_KEY_PRESSED). - EventType type_; - - // The state of the Shift/Ctrl/Alt keys. - int modifiers_; - - // True if the accelerator is created for an auto repeated key event. - bool is_repeat_; - - // Stores platform specific data. May be NULL. - scoped_ptr<PlatformAccelerator> platform_accelerator_; -}; - -// An interface that classes that want to register for keyboard accelerators -// should implement. -class UI_BASE_EXPORT AcceleratorTarget { - public: - // Should return true if the accelerator was processed. - virtual bool AcceleratorPressed(const Accelerator& accelerator) = 0; - - // Should return true if the target can handle the accelerator events. The - // AcceleratorPressed method is invoked only for targets for which - // CanHandleAccelerators returns true. - virtual bool CanHandleAccelerators() const = 0; - - protected: - virtual ~AcceleratorTarget() {} -}; - -// Since accelerator code is one of the few things that can't be cross platform -// in the chrome UI, separate out just the GetAcceleratorForCommandId() from -// the menu delegates. -class AcceleratorProvider { - public: - // Gets the accelerator for the specified command id. Returns true if the - // command id has a valid accelerator, false otherwise. - virtual bool GetAcceleratorForCommandId(int command_id, - ui::Accelerator* accelerator) = 0; - - protected: - virtual ~AcceleratorProvider() {} -}; - -} // namespace ui - -#endif // UI_BASE_ACCELERATORS_ACCELERATOR_H_
diff --git a/ui/base/accelerators/accelerator_manager.cc b/ui/base/accelerators/accelerator_manager.cc deleted file mode 100644 index 0dc4bfc..0000000 --- a/ui/base/accelerators/accelerator_manager.cc +++ /dev/null
@@ -1,120 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/accelerators/accelerator_manager.h" - -#include <algorithm> - -#include "base/logging.h" - -namespace ui { - -AcceleratorManager::AcceleratorManager() { -} - -AcceleratorManager::~AcceleratorManager() { -} - -void AcceleratorManager::Register(const Accelerator& accelerator, - HandlerPriority priority, - AcceleratorTarget* target) { - AcceleratorTargetList& targets = accelerators_[accelerator].second; - DCHECK(std::find(targets.begin(), targets.end(), target) == targets.end()) - << "Registering the same target multiple times"; - - // All priority accelerators go to the front of the line. - if (priority) { - DCHECK(!accelerators_[accelerator].first) - << "Only one _priority_ handler can be registered"; - targets.push_front(target); - // Mark that we have a priority accelerator at the front. - accelerators_[accelerator].first = true; - return; - } - - // We are registering a normal priority handler. If no priority accelerator - // handler has been registered before us, just add the new handler to the - // front. Otherwise, register it after the first (only) priority handler. - if (!accelerators_[accelerator].first) - targets.push_front(target); - else - targets.insert(++targets.begin(), target); -} - -void AcceleratorManager::Unregister(const Accelerator& accelerator, - AcceleratorTarget* target) { - AcceleratorMap::iterator map_iter = accelerators_.find(accelerator); - if (map_iter == accelerators_.end()) { - NOTREACHED() << "Unregistering non-existing accelerator"; - return; - } - - AcceleratorTargetList* targets = &map_iter->second.second; - AcceleratorTargetList::iterator target_iter = - std::find(targets->begin(), targets->end(), target); - if (target_iter == targets->end()) { - NOTREACHED() << "Unregistering accelerator for wrong target"; - return; - } - - // Check to see if we have a priority handler and whether we are removing it. - if (accelerators_[accelerator].first && target_iter == targets->begin()) { - // We've are taking the priority accelerator away, flip the priority flag. - accelerators_[accelerator].first = false; - } - - targets->erase(target_iter); -} - -void AcceleratorManager::UnregisterAll(AcceleratorTarget* target) { - for (AcceleratorMap::iterator map_iter = accelerators_.begin(); - map_iter != accelerators_.end(); ++map_iter) { - AcceleratorTargetList* targets = &map_iter->second.second; - targets->remove(target); - } -} - -bool AcceleratorManager::Process(const Accelerator& accelerator) { - bool result = false; - AcceleratorMap::iterator map_iter = accelerators_.find(accelerator); - if (map_iter != accelerators_.end()) { - // We have to copy the target list here, because an AcceleratorPressed - // event handler may modify the list. - AcceleratorTargetList targets(map_iter->second.second); - for (AcceleratorTargetList::iterator iter = targets.begin(); - iter != targets.end(); ++iter) { - if ((*iter)->CanHandleAccelerators() && - (*iter)->AcceleratorPressed(accelerator)) { - result = true; - break; - } - } - } - return result; -} - -AcceleratorTarget* AcceleratorManager::GetCurrentTarget( - const Accelerator& accelerator) const { - AcceleratorMap::const_iterator map_iter = accelerators_.find(accelerator); - if (map_iter == accelerators_.end() || map_iter->second.second.empty()) - return NULL; - return map_iter->second.second.front(); -} - -bool AcceleratorManager::HasPriorityHandler( - const Accelerator& accelerator) const { - AcceleratorMap::const_iterator map_iter = accelerators_.find(accelerator); - if (map_iter == accelerators_.end() || map_iter->second.second.empty()) - return false; - - // Check if we have a priority handler. If not, there's no more work needed. - if (!map_iter->second.first) - return false; - - // If the priority handler says it cannot handle the accelerator, we must not - // count it as one. - return map_iter->second.second.front()->CanHandleAccelerators(); -} - -} // namespace ui
diff --git a/ui/base/accelerators/accelerator_manager.h b/ui/base/accelerators/accelerator_manager.h deleted file mode 100644 index 0e33ad6..0000000 --- a/ui/base/accelerators/accelerator_manager.h +++ /dev/null
@@ -1,87 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_ACCELERATORS_ACCELERATOR_MANAGER_H_ -#define UI_BASE_ACCELERATORS_ACCELERATOR_MANAGER_H_ - -#include <list> -#include <map> -#include <utility> - -#include "base/basictypes.h" -#include "ui/base/accelerators/accelerator.h" -#include "ui/base/ui_base_export.h" -#include "ui/events/event_constants.h" - -namespace ui { - -// The AcceleratorManger is used to handle keyboard accelerators. -class UI_BASE_EXPORT AcceleratorManager { - public: - enum HandlerPriority { - kNormalPriority, - kHighPriority, - }; - - AcceleratorManager(); - ~AcceleratorManager(); - - // 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 Register(const Accelerator& accelerator, - HandlerPriority priority, - AcceleratorTarget* target); - - // Unregister the specified keyboard accelerator for the specified target. - void Unregister(const Accelerator& accelerator, AcceleratorTarget* target); - - // Unregister all keyboard accelerator for the specified target. - void UnregisterAll(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 Process(const Accelerator& accelerator); - - // Returns the AcceleratorTarget that should be activated for the specified - // keyboard accelerator, or NULL if no view is registered for that keyboard - // accelerator. - AcceleratorTarget* GetCurrentTarget(const Accelerator& accelertor) const; - - // Whether the given |accelerator| has a priority handler associated with it. - bool HasPriorityHandler(const Accelerator& accelerator) const; - - private: - // The accelerators and associated targets. - typedef std::list<AcceleratorTarget*> AcceleratorTargetList; - // This construct pairs together a |bool| (denoting whether the list contains - // a priority_handler at the front) with the list of AcceleratorTargets. - typedef std::pair<bool, AcceleratorTargetList> AcceleratorTargets; - typedef std::map<Accelerator, AcceleratorTargets> AcceleratorMap; - AcceleratorMap accelerators_; - - DISALLOW_COPY_AND_ASSIGN(AcceleratorManager); -}; - -} // namespace ui - -#endif // UI_BASE_ACCELERATORS_ACCELERATOR_MANAGER_H_
diff --git a/ui/base/accelerators/accelerator_manager_unittest.cc b/ui/base/accelerators/accelerator_manager_unittest.cc deleted file mode 100644 index ec5a47b..0000000 --- a/ui/base/accelerators/accelerator_manager_unittest.cc +++ /dev/null
@@ -1,183 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/accelerators/accelerator_manager.h" - -#include "base/compiler_specific.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/events/event_constants.h" -#include "ui/events/keycodes/keyboard_codes.h" - -namespace ui { -namespace test { - -namespace { - -class TestTarget : public AcceleratorTarget { - public: - TestTarget() : accelerator_pressed_count_(0) {} - ~TestTarget() override {} - - int accelerator_pressed_count() const { - return accelerator_pressed_count_; - } - - void set_accelerator_pressed_count(int accelerator_pressed_count) { - accelerator_pressed_count_ = accelerator_pressed_count; - } - - // Overridden from AcceleratorTarget: - bool AcceleratorPressed(const Accelerator& accelerator) override; - bool CanHandleAccelerators() const override; - - private: - int accelerator_pressed_count_; - - DISALLOW_COPY_AND_ASSIGN(TestTarget); -}; - -bool TestTarget::AcceleratorPressed(const Accelerator& accelerator) { - ++accelerator_pressed_count_; - return true; -} - -bool TestTarget::CanHandleAccelerators() const { - return true; -} - -Accelerator GetAccelerator(KeyboardCode code, int mask) { - return Accelerator(code, mask); -} - -} // namespace - -class AcceleratorManagerTest : public testing::Test { - public: - AcceleratorManagerTest() {} - virtual ~AcceleratorManagerTest() {} - - AcceleratorManager manager_; -}; - -TEST_F(AcceleratorManagerTest, Register) { - const Accelerator accelerator_a(VKEY_A, EF_NONE); - TestTarget target; - manager_.Register(accelerator_a, AcceleratorManager::kNormalPriority, - &target); - - // The registered accelerator is processed. - EXPECT_TRUE(manager_.Process(accelerator_a)); - EXPECT_EQ(1, target.accelerator_pressed_count()); -} - -TEST_F(AcceleratorManagerTest, RegisterMultipleTarget) { - const Accelerator accelerator_a(VKEY_A, EF_NONE); - TestTarget target1; - manager_.Register(accelerator_a, AcceleratorManager::kNormalPriority, - &target1); - TestTarget target2; - manager_.Register(accelerator_a, AcceleratorManager::kNormalPriority, - &target2); - - // If multiple targets are registered with the same accelerator, the target - // registered later processes the accelerator. - EXPECT_TRUE(manager_.Process(accelerator_a)); - EXPECT_EQ(0, target1.accelerator_pressed_count()); - EXPECT_EQ(1, target2.accelerator_pressed_count()); -} - -TEST_F(AcceleratorManagerTest, Unregister) { - const Accelerator accelerator_a(VKEY_A, EF_NONE); - TestTarget target; - manager_.Register(accelerator_a, AcceleratorManager::kNormalPriority, - &target); - const Accelerator accelerator_b(VKEY_B, EF_NONE); - manager_.Register(accelerator_b, AcceleratorManager::kNormalPriority, - &target); - - // Unregistering a different accelerator does not affect the other - // accelerator. - manager_.Unregister(accelerator_b, &target); - EXPECT_TRUE(manager_.Process(accelerator_a)); - EXPECT_EQ(1, target.accelerator_pressed_count()); - - // The unregistered accelerator is no longer processed. - target.set_accelerator_pressed_count(0); - manager_.Unregister(accelerator_a, &target); - EXPECT_FALSE(manager_.Process(accelerator_a)); - EXPECT_EQ(0, target.accelerator_pressed_count()); -} - -TEST_F(AcceleratorManagerTest, UnregisterAll) { - const Accelerator accelerator_a(VKEY_A, EF_NONE); - TestTarget target1; - manager_.Register(accelerator_a, AcceleratorManager::kNormalPriority, - &target1); - const Accelerator accelerator_b(VKEY_B, EF_NONE); - manager_.Register(accelerator_b, AcceleratorManager::kNormalPriority, - &target1); - const Accelerator accelerator_c(VKEY_C, EF_NONE); - TestTarget target2; - manager_.Register(accelerator_c, AcceleratorManager::kNormalPriority, - &target2); - manager_.UnregisterAll(&target1); - - // All the accelerators registered for |target1| are no longer processed. - EXPECT_FALSE(manager_.Process(accelerator_a)); - EXPECT_FALSE(manager_.Process(accelerator_b)); - EXPECT_EQ(0, target1.accelerator_pressed_count()); - - // UnregisterAll with a different target does not affect the other target. - EXPECT_TRUE(manager_.Process(accelerator_c)); - EXPECT_EQ(1, target2.accelerator_pressed_count()); -} - -TEST_F(AcceleratorManagerTest, Process) { - TestTarget target; - - // Test all 2*2*2 cases (shift/control/alt = on/off). - for (int mask = 0; mask < 2 * 2 * 2; ++mask) { - Accelerator accelerator(GetAccelerator(VKEY_A, mask)); - const base::string16 text = accelerator.GetShortcutText(); - manager_.Register(accelerator, AcceleratorManager::kNormalPriority, - &target); - - // The registered accelerator is processed. - const int last_count = target.accelerator_pressed_count(); - EXPECT_TRUE(manager_.Process(accelerator)) << text; - EXPECT_EQ(last_count + 1, target.accelerator_pressed_count()) << text; - - // The non-registered accelerators are not processed. - accelerator.set_type(ET_UNKNOWN); - EXPECT_FALSE(manager_.Process(accelerator)) << text; // different type - accelerator.set_type(ET_TRANSLATED_KEY_PRESS); - EXPECT_FALSE(manager_.Process(accelerator)) << text; // different type - accelerator.set_type(ET_KEY_RELEASED); - EXPECT_FALSE(manager_.Process(accelerator)) << text; // different type - accelerator.set_type(ET_TRANSLATED_KEY_RELEASE); - EXPECT_FALSE(manager_.Process(accelerator)) << text; // different type - - EXPECT_FALSE(manager_.Process(GetAccelerator(VKEY_UNKNOWN, mask))) - << text; // different vkey - EXPECT_FALSE(manager_.Process(GetAccelerator(VKEY_B, mask))) - << text; // different vkey - EXPECT_FALSE(manager_.Process(GetAccelerator(VKEY_SHIFT, mask))) - << text; // different vkey - - for (int test_mask = 0; test_mask < 2 * 2 * 2; ++test_mask) { - if (test_mask == mask) - continue; - const Accelerator test_accelerator(GetAccelerator(VKEY_A, test_mask)); - const base::string16 test_text = test_accelerator.GetShortcutText(); - EXPECT_FALSE(manager_.Process(test_accelerator)) - << text << ", " << test_text; // different modifiers - } - - EXPECT_EQ(last_count + 1, target.accelerator_pressed_count()) << text; - manager_.UnregisterAll(&target); - } -} - -} // namespace test -} // namespace ui
diff --git a/ui/base/accelerators/menu_label_accelerator_util_linux.cc b/ui/base/accelerators/menu_label_accelerator_util_linux.cc deleted file mode 100644 index 0a00f82..0000000 --- a/ui/base/accelerators/menu_label_accelerator_util_linux.cc +++ /dev/null
@@ -1,62 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/accelerators/menu_label_accelerator_util_linux.h" - -#include "base/strings/string_util.h" - -namespace { - -// Common implementation of ConvertAcceleratorsFromWindowsStyle() and -// RemoveWindowsStyleAccelerators(). -// Replaces all ampersands (as used in our grd files to indicate mnemonics) -// to |target|, except ampersands appearing in pairs which are replaced by -// a single ampersand. Any underscores get replaced with two underscores as -// is needed by GTK. -std::string ConvertAmpersandsTo(const std::string& label, - const std::string& target) { - std::string ret; - ret.reserve(label.length() * 2); - for (size_t i = 0; i < label.length(); ++i) { - if ('_' == label[i]) { - ret.push_back('_'); - ret.push_back('_'); - } else if ('&' == label[i]) { - if (i + 1 < label.length() && '&' == label[i + 1]) { - ret.push_back('&'); - ++i; - } else { - ret.append(target); - } - } else { - ret.push_back(label[i]); - } - } - - return ret; -} - -} // namespace - -namespace ui { - -std::string ConvertAcceleratorsFromWindowsStyle(const std::string& label) { - return ConvertAmpersandsTo(label, "_"); -} - -std::string RemoveWindowsStyleAccelerators(const std::string& label) { - return ConvertAmpersandsTo(label, std::string()); -} - -// Replaces all ampersands in |label| with two ampersands. This effectively -// escapes strings for later processing by ConvertAmpersandsTo(), so that -// ConvertAmpersandsTo(EscapeWindowsStyleAccelerators(x), *) is |x| with -// underscores doubled, making the string that appears to the user just |x|. -std::string EscapeWindowsStyleAccelerators(const std::string& label) { - std::string ret; - base::ReplaceChars(label, "&", "&&", &ret); - return ret; -} - -} // namespace ui
diff --git a/ui/base/accelerators/menu_label_accelerator_util_linux.h b/ui/base/accelerators/menu_label_accelerator_util_linux.h deleted file mode 100644 index bd8d3cf..0000000 --- a/ui/base/accelerators/menu_label_accelerator_util_linux.h +++ /dev/null
@@ -1,31 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_ACCELERATORS_MENU_LABEL_ACCELERATOR_UTIL_LINUX_H_ -#define UI_BASE_ACCELERATORS_MENU_LABEL_ACCELERATOR_UTIL_LINUX_H_ - -#include <string> - -#include "ui/base/ui_base_export.h" - -namespace ui { - -// Change windows accelerator style to GTK style. (GTK uses _ for -// accelerators. Windows uses & with && as an escape for &.) -UI_BASE_EXPORT std::string ConvertAcceleratorsFromWindowsStyle( - const std::string& label); - -// Removes the "&" accelerators from a Windows label. -UI_BASE_EXPORT std::string RemoveWindowsStyleAccelerators( - const std::string& label); - -// Escapes "&" characters by doubling them so that later calling -// ConvertAcceleratorsFromWindowsStyle() will return the original string (except -// with "_" characters doubled, to escape them for GTK). -UI_BASE_EXPORT std::string EscapeWindowsStyleAccelerators( - const std::string& label); - -} // namespace ui - -#endif // UI_BASE_ACCELERATORS_MENU_LABEL_ACCELERATOR_UTIL_LINUX_H_
diff --git a/ui/base/accelerators/menu_label_accelerator_util_linux_unittest.cc b/ui/base/accelerators/menu_label_accelerator_util_linux_unittest.cc deleted file mode 100644 index 0811e2b..0000000 --- a/ui/base/accelerators/menu_label_accelerator_util_linux_unittest.cc +++ /dev/null
@@ -1,75 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/accelerators/menu_label_accelerator_util_linux.h" - -#include "base/basictypes.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace ui { - -TEST(MenuLabelAcceleratorTest, ConvertAcceleratorsFromWindowsStyle) { - static const struct { - const char* input; - const char* output; - } cases[] = { - { "", "" }, - { "nothing", "nothing" }, - { "foo &bar", "foo _bar" }, - { "foo &&bar", "foo &bar" }, - { "foo &&&bar", "foo &_bar" }, - { "&foo &&bar", "_foo &bar" }, - { "&foo &bar", "_foo _bar" }, - }; - for (size_t i = 0; i < arraysize(cases); ++i) { - std::string result = ConvertAcceleratorsFromWindowsStyle(cases[i].input); - EXPECT_EQ(cases[i].output, result); - } -} - -TEST(MenuLabelAcceleratorTest, RemoveWindowsStyleAccelerators) { - static const struct { - const char* input; - const char* output; - } cases[] = { - { "", "" }, - { "nothing", "nothing" }, - { "foo &bar", "foo bar" }, - { "foo &&bar", "foo &bar" }, - { "foo &&&bar", "foo &bar" }, - { "&foo &&bar", "foo &bar" }, - { "&foo &bar", "foo bar" }, - }; - for (size_t i = 0; i < arraysize(cases); ++i) { - std::string result = RemoveWindowsStyleAccelerators(cases[i].input); - EXPECT_EQ(cases[i].output, result); - } -} - -TEST(MenuLabelAcceleratorTest, EscapeWindowsStyleAccelerators) { - static const struct { - const char* input; - const char* output; - } cases[] = { - { "nothing", "nothing" }, - { "foo &bar", "foo &&bar" }, - { "foo &&bar", "foo &&&&bar" }, - { "foo &&&bar", "foo &&&&&&bar" }, - { "&foo bar", "&&foo bar" }, - { "&&foo bar", "&&&&foo bar" }, - { "&&&foo bar", "&&&&&&foo bar" }, - { "&foo &bar", "&&foo &&bar" }, - { "&&foo &&bar", "&&&&foo &&&&bar" }, - { "f&o&o ba&r", "f&&o&&o ba&&r" }, - { "foo_&_bar", "foo_&&_bar" }, - { "&_foo_bar_&", "&&_foo_bar_&&" }, - }; - - for (size_t i = 0; i < arraysize(cases); ++i) { - std::string result = EscapeWindowsStyleAccelerators(cases[i].input); - EXPECT_EQ(cases[i].output, result); - } -} - -} // namespace ui
diff --git a/ui/base/accelerators/platform_accelerator.h b/ui/base/accelerators/platform_accelerator.h deleted file mode 100644 index cca8021..0000000 --- a/ui/base/accelerators/platform_accelerator.h +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_ACCELERATORS_PLATFORM_ACCELERATOR_H_ -#define UI_BASE_ACCELERATORS_PLATFORM_ACCELERATOR_H_ - -#include "base/memory/scoped_ptr.h" -#include "ui/base/ui_base_export.h" - -namespace ui { - -// Abstract base class for platform specific accelerator keys. -class UI_BASE_EXPORT PlatformAccelerator { - public: - virtual ~PlatformAccelerator() {} - - virtual scoped_ptr<PlatformAccelerator> CreateCopy() const = 0; - virtual bool Equals(const PlatformAccelerator& rhs) const = 0; -}; - -} // namespace ui - -#endif // UI_BASE_ACCELERATORS_PLATFORM_ACCELERATOR_H_
diff --git a/ui/base/android/ui_base_jni_registrar.cc b/ui/base/android/ui_base_jni_registrar.cc index cfa7c49..ab67c84 100644 --- a/ui/base/android/ui_base_jni_registrar.cc +++ b/ui/base/android/ui_base_jni_registrar.cc
@@ -8,7 +8,6 @@ #include "base/android/jni_registrar.h" #include "ui/base/android/view_android.h" #include "ui/base/android/window_android.h" -#include "ui/base/clipboard/clipboard_android.h" #include "ui/base/l10n/l10n_util_android.h" #include "ui/base/resource/resource_bundle_android.h" #include "ui/base/touch/touch_device.h" @@ -17,7 +16,6 @@ namespace android { static base::android::RegistrationMethod kUiRegisteredMethods[] = { - { "Clipboard", RegisterClipboardAndroid }, { "LocalizationUtils", l10n_util::RegisterLocalizationUtil }, { "ResourceBundle", RegisterResourceBundleAndroid }, { "TouchDevice", RegisterTouchDeviceAndroid },
diff --git a/ui/base/base_window.cc b/ui/base/base_window.cc deleted file mode 100644 index 231a177..0000000 --- a/ui/base/base_window.cc +++ /dev/null
@@ -1,16 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/base_window.h" - -namespace ui { - -bool BaseWindow::IsRestored(const BaseWindow& window) { - return !window.IsMaximized() && - !window.IsMinimized() && - !window.IsFullscreen(); -} - -} // namespace ui -
diff --git a/ui/base/base_window.h b/ui/base/base_window.h deleted file mode 100644 index 6646169..0000000 --- a/ui/base/base_window.h +++ /dev/null
@@ -1,99 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_BASE_WINDOW_H_ -#define UI_BASE_BASE_WINDOW_H_ - -#include "base/compiler_specific.h" -#include "ui/base/ui_base_types.h" // WindowShowState -#include "ui/gfx/native_widget_types.h" - -namespace gfx { -class Rect; -} - -class SkRegion; - -namespace ui { - -// Provides an interface to perform actions on windows, and query window -// state. -class UI_BASE_EXPORT BaseWindow { - public: - // Returns true if the window is currently the active/focused window. - virtual bool IsActive() const = 0; - - // Returns true if the window is maximized (aka zoomed). - virtual bool IsMaximized() const = 0; - - // Returns true if the window is minimized. - virtual bool IsMinimized() const = 0; - - // Returns true if the window is full screen. - virtual bool IsFullscreen() const = 0; - - // Returns true if the window is fully restored (not Fullscreen, Maximized, - // Minimized). - static bool IsRestored(const BaseWindow& window); - - // Return a platform dependent identifier for this window. - virtual gfx::NativeWindow GetNativeWindow() = 0; - - // Returns the nonmaximized bounds of the window (even if the window is - // currently maximized or minimized) in terms of the screen coordinates. - virtual gfx::Rect GetRestoredBounds() const = 0; - - // Returns the restore state for the window (platform dependent). - virtual ui::WindowShowState GetRestoredState() const = 0; - - // Retrieves the window's current bounds, including its window. - // This will only differ from GetRestoredBounds() for maximized - // and minimized windows. - virtual gfx::Rect GetBounds() const = 0; - - // Shows the window, or activates it if it's already visible. - virtual void Show() = 0; - - // Hides the window. - virtual void Hide() = 0; - - // Show the window, but do not activate it. Does nothing if window - // is already visible. - virtual void ShowInactive() = 0; - - // Closes the window as soon as possible. The close action may be delayed - // if an operation is in progress (e.g. a drag operation). - virtual void Close() = 0; - - // Activates (brings to front) the window. Restores the window from minimized - // state if necessary. - virtual void Activate() = 0; - - // Deactivates the window, making the next window in the Z order the active - // window. - virtual void Deactivate() = 0; - - // Maximizes/minimizes/restores the window. - virtual void Maximize() = 0; - virtual void Minimize() = 0; - virtual void Restore() = 0; - - // Sets the window's size and position to the specified values. - virtual void SetBounds(const gfx::Rect& bounds) = 0; - - // Flashes the taskbar item associated with this window. - // Set |flash| to true to initiate flashing, false to stop flashing. - virtual void FlashFrame(bool flash) = 0; - - // Returns true if a window is set to be always on top. - virtual bool IsAlwaysOnTop() const = 0; - - // If set to true, the window will stay on top of other windows which do not - // have this flag enabled. - virtual void SetAlwaysOnTop(bool always_on_top) = 0; -}; - -} // namespace ui - -#endif // UI_BASE_BASE_WINDOW_H_
diff --git a/ui/base/clipboard/DEPS b/ui/base/clipboard/DEPS deleted file mode 100644 index e963fe5..0000000 --- a/ui/base/clipboard/DEPS +++ /dev/null
@@ -1,4 +0,0 @@ -include_rules = [ - "+jni", - "+third_party/mozilla", -]
diff --git a/ui/base/clipboard/OWNERS b/ui/base/clipboard/OWNERS deleted file mode 100644 index 3b1f792..0000000 --- a/ui/base/clipboard/OWNERS +++ /dev/null
@@ -1,2 +0,0 @@ -dcheng@chromium.org -tony@chromium.org
diff --git a/ui/base/clipboard/clipboard.cc b/ui/base/clipboard/clipboard.cc deleted file mode 100644 index 27f747a..0000000 --- a/ui/base/clipboard/clipboard.cc +++ /dev/null
@@ -1,233 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/clipboard/clipboard.h" - -#include <iterator> -#include <limits> - -#include "base/lazy_instance.h" -#include "base/logging.h" -#include "base/memory/scoped_ptr.h" -#include "base/synchronization/lock.h" -#include "third_party/skia/include/core/SkBitmap.h" -#include "ui/gfx/size.h" - -namespace ui { - -namespace { - -// Valides a shared bitmap on the clipboard. -// Returns true if the clipboard data makes sense and it's safe to access the -// bitmap. -bool ValidateAndMapSharedBitmap(size_t bitmap_bytes, - base::SharedMemory* bitmap_data) { - using base::SharedMemory; - - if (!bitmap_data || !SharedMemory::IsHandleValid(bitmap_data->handle())) - return false; - - if (!bitmap_data->Map(bitmap_bytes)) { - PLOG(ERROR) << "Failed to map bitmap memory"; - return false; - } - return true; -} - -// A list of allowed threads. By default, this is empty and no thread checking -// is done (in the unit test case), but a user (like content) can set which -// threads are allowed to call this method. -typedef std::vector<base::PlatformThreadId> AllowedThreadsVector; -static base::LazyInstance<AllowedThreadsVector> g_allowed_threads = - LAZY_INSTANCE_INITIALIZER; - -// Mapping from threads to clipboard objects. -typedef std::map<base::PlatformThreadId, Clipboard*> ClipboardMap; -static base::LazyInstance<ClipboardMap> g_clipboard_map = - LAZY_INSTANCE_INITIALIZER; - -// Mutex that controls access to |g_clipboard_map|. -static base::LazyInstance<base::Lock>::Leaky - g_clipboard_map_lock = LAZY_INSTANCE_INITIALIZER; - -} // namespace - -// static -void Clipboard::SetAllowedThreads( - const std::vector<base::PlatformThreadId>& allowed_threads) { - base::AutoLock lock(g_clipboard_map_lock.Get()); - - g_allowed_threads.Get().clear(); - std::copy(allowed_threads.begin(), allowed_threads.end(), - std::back_inserter(g_allowed_threads.Get())); -} - -// static -Clipboard* Clipboard::GetForCurrentThread() { - base::AutoLock lock(g_clipboard_map_lock.Get()); - - base::PlatformThreadId id = base::PlatformThread::CurrentId(); - - AllowedThreadsVector* allowed_threads = g_allowed_threads.Pointer(); - if (!allowed_threads->empty()) { - bool found = false; - for (AllowedThreadsVector::const_iterator it = allowed_threads->begin(); - it != allowed_threads->end(); ++it) { - if (*it == id) { - found = true; - break; - } - } - - DCHECK(found); - } - - ClipboardMap* clipboard_map = g_clipboard_map.Pointer(); - ClipboardMap::iterator it = clipboard_map->find(id); - if (it != clipboard_map->end()) - return it->second; - - Clipboard* clipboard = Clipboard::Create(); - clipboard_map->insert(std::make_pair(id, clipboard)); - return clipboard; -} - -void Clipboard::DestroyClipboardForCurrentThread() { - base::AutoLock lock(g_clipboard_map_lock.Get()); - - ClipboardMap* clipboard_map = g_clipboard_map.Pointer(); - base::PlatformThreadId id = base::PlatformThread::CurrentId(); - ClipboardMap::iterator it = clipboard_map->find(id); - if (it != clipboard_map->end()) { - delete it->second; - clipboard_map->erase(it); - } -} - -void Clipboard::DispatchObject(ObjectType type, const ObjectMapParams& params) { - // All types apart from CBF_WEBKIT need at least 1 non-empty param. - if (type != CBF_WEBKIT && (params.empty() || params[0].empty())) - return; - // Some other types need a non-empty 2nd param. - if ((type == CBF_BOOKMARK || type == CBF_SMBITMAP || type == CBF_DATA) && - (params.size() != 2 || params[1].empty())) - return; - switch (type) { - case CBF_TEXT: - WriteText(&(params[0].front()), params[0].size()); - break; - - case CBF_HTML: - if (params.size() == 2) { - if (params[1].empty()) - return; - WriteHTML(&(params[0].front()), params[0].size(), - &(params[1].front()), params[1].size()); - } else if (params.size() == 1) { - WriteHTML(&(params[0].front()), params[0].size(), NULL, 0); - } - break; - - case CBF_RTF: - WriteRTF(&(params[0].front()), params[0].size()); - break; - - case CBF_BOOKMARK: - WriteBookmark(&(params[0].front()), params[0].size(), - &(params[1].front()), params[1].size()); - break; - - case CBF_WEBKIT: - WriteWebSmartPaste(); - break; - - case CBF_SMBITMAP: { - using base::SharedMemory; - using base::SharedMemoryHandle; - - if (params[0].size() != sizeof(SharedMemory*) || - params[1].size() != sizeof(gfx::Size)) { - return; - } - - SkBitmap bitmap; - const gfx::Size* unvalidated_size = - reinterpret_cast<const gfx::Size*>(¶ms[1].front()); - // Let Skia do some sanity checking for us (no negative widths/heights, no - // overflows while calculating bytes per row, etc). - if (!bitmap.setInfo(SkImageInfo::MakeN32Premul( - unvalidated_size->width(), unvalidated_size->height()))) { - return; - } - // Make sure the size is representable as a signed 32-bit int, so - // SkBitmap::getSize() won't be truncated. - if (!sk_64_isS32(bitmap.computeSize64())) - return; - - // It's OK to cast away constness here since we map the handle as - // read-only. - const char* raw_bitmap_data_const = - reinterpret_cast<const char*>(¶ms[0].front()); - char* raw_bitmap_data = const_cast<char*>(raw_bitmap_data_const); - scoped_ptr<SharedMemory> bitmap_data( - *reinterpret_cast<SharedMemory**>(raw_bitmap_data)); - - if (!ValidateAndMapSharedBitmap(bitmap.getSize(), bitmap_data.get())) - return; - bitmap.setPixels(bitmap_data->memory()); - - WriteBitmap(bitmap); - break; - } - - case CBF_DATA: - WriteData( - FormatType::Deserialize( - std::string(&(params[0].front()), params[0].size())), - &(params[1].front()), - params[1].size()); - break; - - default: - NOTREACHED(); - } -} - -// static -bool Clipboard::ReplaceSharedMemHandle(ObjectMap* objects, - base::SharedMemoryHandle bitmap_handle, - base::ProcessHandle process) { - using base::SharedMemory; - bool has_shared_bitmap = false; - - for (ObjectMap::iterator iter = objects->begin(); iter != objects->end(); - ++iter) { - if (iter->first == CBF_SMBITMAP) { - // The code currently only accepts sending a single bitmap over this way. - // Fail if we ever encounter more than one shmem bitmap structure to fill. - if (has_shared_bitmap) - return false; - -#if defined(OS_WIN) - SharedMemory* bitmap = new SharedMemory(bitmap_handle, true, process); -#else - SharedMemory* bitmap = new SharedMemory(bitmap_handle, true); -#endif - - // There must always be two parameters associated with each shmem bitmap. - if (iter->second.size() != 2) - return false; - - // We store the shared memory object pointer so it can be retrieved by the - // UI thread (see DispatchObject()). - iter->second[0].clear(); - for (size_t i = 0; i < sizeof(SharedMemory*); ++i) - iter->second[0].push_back(reinterpret_cast<char*>(&bitmap)[i]); - has_shared_bitmap = true; - } - } - return true; -} - -} // namespace ui
diff --git a/ui/base/clipboard/clipboard.h b/ui/base/clipboard/clipboard.h deleted file mode 100644 index 73c3aa2..0000000 --- a/ui/base/clipboard/clipboard.h +++ /dev/null
@@ -1,335 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_CLIPBOARD_CLIPBOARD_H_ -#define UI_BASE_CLIPBOARD_CLIPBOARD_H_ - -#include <map> -#include <string> -#include <vector> - -#include "base/compiler_specific.h" -#include "base/gtest_prod_util.h" -#include "base/memory/shared_memory.h" -#include "base/process/process.h" -#include "base/strings/string16.h" -#include "base/threading/platform_thread.h" -#include "base/threading/thread_checker.h" -#include "ui/base/clipboard/clipboard_types.h" -#include "ui/base/ui_base_export.h" - -#if defined(OS_WIN) -#include <objidl.h> -#endif - -namespace base { -class FilePath; - -namespace win { -class MessageWindow; -} // namespace win -} // namespace base - -// TODO(dcheng): Temporary until the IPC layer doesn't use WriteObjects(). -namespace content { -class ClipboardMessageFilter; -} - -namespace gfx { -class Size; -} - -class SkBitmap; - -#ifdef __OBJC__ -@class NSString; -#else -class NSString; -#endif - -namespace ui { -class ClipboardTest; -class ScopedClipboardWriter; - -class UI_BASE_EXPORT Clipboard : NON_EXPORTED_BASE(public base::ThreadChecker) { - public: - // MIME type constants. - static const char kMimeTypeText[]; - static const char kMimeTypeURIList[]; - static const char kMimeTypeDownloadURL[]; - static const char kMimeTypeHTML[]; - static const char kMimeTypeRTF[]; - static const char kMimeTypePNG[]; - - // Platform neutral holder for native data representation of a clipboard type. - struct UI_BASE_EXPORT FormatType { - FormatType(); - ~FormatType(); - - // Serializes and deserializes a FormatType for use in IPC messages. - std::string Serialize() const; - static FormatType Deserialize(const std::string& serialization); - -#if defined(USE_AURA) - // FormatType can be used in a set on some platforms. - bool operator<(const FormatType& other) const; -#endif - -#if defined(OS_WIN) - const FORMATETC& ToFormatEtc() const { return data_; } -#elif defined(USE_AURA) || defined(OS_ANDROID) - const std::string& ToString() const { return data_; } -#elif defined(OS_MACOSX) - NSString* ToNSString() const { return data_; } - // Custom copy and assignment constructor to handle NSString. - FormatType(const FormatType& other); - FormatType& operator=(const FormatType& other); -#endif - - bool Equals(const FormatType& other) const; - - private: - friend class Clipboard; - - // Platform-specific glue used internally by the Clipboard class. Each - // plaform should define,at least one of each of the following: - // 1. A constructor that wraps that native clipboard format descriptor. - // 2. An accessor to retrieve the wrapped descriptor. - // 3. A data member to hold the wrapped descriptor. - // - // Note that in some cases, the accessor for the wrapped descriptor may be - // public, as these format types can be used by drag and drop code as well. -#if defined(OS_WIN) - explicit FormatType(UINT native_format); - FormatType(UINT native_format, LONG index); - FORMATETC data_; -#elif defined(USE_AURA) || defined(OS_ANDROID) - explicit FormatType(const std::string& native_format); - std::string data_; -#elif defined(OS_MACOSX) - explicit FormatType(NSString* native_format); - NSString* data_; -#else -#error No FormatType definition. -#endif - - // Copyable and assignable, since this is essentially an opaque value type. - }; - - // TODO(dcheng): Make this private once the IPC layer no longer needs to - // serialize this information. - // ObjectType designates the type of data to be stored in the clipboard. This - // designation is shared across all OSes. The system-specific designation - // is defined by FormatType. A single ObjectType might be represented by - // several system-specific FormatTypes. For example, on Linux the CBF_TEXT - // ObjectType maps to "text/plain", "STRING", and several other formats. On - // windows it maps to CF_UNICODETEXT. - enum ObjectType { - CBF_TEXT, - CBF_HTML, - CBF_RTF, - CBF_BOOKMARK, - CBF_WEBKIT, - CBF_SMBITMAP, // Bitmap from shared memory. - CBF_DATA, // Arbitrary block of bytes. - }; - - // ObjectMap is a map from ObjectType to associated data. - // The data is organized differently for each ObjectType. The following - // table summarizes what kind of data is stored for each key. - // * indicates an optional argument. - // - // Key Arguments Type - // ------------------------------------- - // CBF_TEXT text char array - // CBF_HTML html char array - // url* char array - // CBF_RTF data byte array - // CBF_BOOKMARK html char array - // url char array - // CBF_WEBKIT none empty vector - // CBF_SMBITMAP shared_mem A pointer to an unmapped base::SharedMemory - // object containing the bitmap data. The bitmap - // data should be premultiplied. - // size gfx::Size struct - // CBF_DATA format char array - // data byte array - typedef std::vector<char> ObjectMapParam; - typedef std::vector<ObjectMapParam> ObjectMapParams; - typedef std::map<int /* ObjectType */, ObjectMapParams> ObjectMap; - - static bool IsSupportedClipboardType(int32 type) { - switch (type) { - case CLIPBOARD_TYPE_COPY_PASTE: - return true; -#if !defined(OS_WIN) && !defined(OS_MACOSX) && !defined(OS_CHROMEOS) - case CLIPBOARD_TYPE_SELECTION: - return true; -#endif - } - return false; - } - - static ClipboardType FromInt(int32 type) { - return static_cast<ClipboardType>(type); - } - - // Sets the list of threads that are allowed to access the clipboard. - static void SetAllowedThreads( - const std::vector<base::PlatformThreadId>& allowed_threads); - - // Returns the clipboard object for the current thread. - // - // Most implementations will have at most one clipboard which will live on - // the main UI thread, but Windows has tricky semantics where there have to - // be two clipboards: one that lives on the UI thread and one that lives on - // the IO thread. - static Clipboard* GetForCurrentThread(); - - // Destroys the clipboard for the current thread. Usually, this will clean up - // all clipboards, except on Windows. (Previous code leaks the IO thread - // clipboard, so it shouldn't be a problem.) - static void DestroyClipboardForCurrentThread(); - - // Returns a sequence number which uniquely identifies clipboard state. - // This can be used to version the data on the clipboard and determine - // whether it has changed. - virtual uint64 GetSequenceNumber(ClipboardType type) = 0; - - // Tests whether the clipboard contains a certain format - virtual bool IsFormatAvailable(const FormatType& format, - ClipboardType type) const = 0; - - // Clear the clipboard data. - virtual void Clear(ClipboardType type) = 0; - - virtual void ReadAvailableTypes(ClipboardType type, - std::vector<base::string16>* types, - bool* contains_filenames) const = 0; - - // Reads UNICODE text from the clipboard, if available. - virtual void ReadText(ClipboardType type, base::string16* result) const = 0; - - // Reads ASCII text from the clipboard, if available. - virtual void ReadAsciiText(ClipboardType type, std::string* result) const = 0; - - // Reads HTML from the clipboard, if available. If the HTML fragment requires - // context to parse, |fragment_start| and |fragment_end| are indexes into - // markup indicating the beginning and end of the actual fragment. Otherwise, - // they will contain 0 and markup->size(). - virtual void ReadHTML(ClipboardType type, - base::string16* markup, - std::string* src_url, - uint32* fragment_start, - uint32* fragment_end) const = 0; - - // Reads RTF from the clipboard, if available. Stores the result as a byte - // vector. - virtual void ReadRTF(ClipboardType type, std::string* result) const = 0; - - // Reads an image from the clipboard, if available. - virtual SkBitmap ReadImage(ClipboardType type) const = 0; - - virtual void ReadCustomData(ClipboardType clipboard_type, - const base::string16& type, - base::string16* result) const = 0; - - // Reads a bookmark from the clipboard, if available. - virtual void ReadBookmark(base::string16* title, std::string* url) const = 0; - - // Reads raw data from the clipboard with the given format type. Stores result - // as a byte vector. - virtual void ReadData(const FormatType& format, - std::string* result) const = 0; - - // Gets the FormatType corresponding to an arbitrary format string, - // registering it with the system if needed. Due to Windows/Linux - // limitiations, |format_string| must never be controlled by the user. - static FormatType GetFormatType(const std::string& format_string); - - // Get format identifiers for various types. - static const FormatType& GetUrlFormatType(); - static const FormatType& GetUrlWFormatType(); - static const FormatType& GetMozUrlFormatType(); - static const FormatType& GetPlainTextFormatType(); - static const FormatType& GetPlainTextWFormatType(); - static const FormatType& GetFilenameFormatType(); - static const FormatType& GetFilenameWFormatType(); - static const FormatType& GetWebKitSmartPasteFormatType(); - // Win: MS HTML Format, Other: Generic HTML format - static const FormatType& GetHtmlFormatType(); - static const FormatType& GetRtfFormatType(); - static const FormatType& GetBitmapFormatType(); - // TODO(raymes): Unify web custom data and pepper custom data: - // crbug.com/158399. - static const FormatType& GetWebCustomDataFormatType(); - static const FormatType& GetPepperCustomDataFormatType(); - - // Embeds a pointer to a SharedMemory object pointed to by |bitmap_handle| - // belonging to |process| into a shared bitmap [CBF_SMBITMAP] slot in - // |objects|. The pointer is deleted by DispatchObjects(). - // - // On non-Windows platforms, |process| is ignored. - static bool ReplaceSharedMemHandle(ObjectMap* objects, - base::SharedMemoryHandle bitmap_handle, - base::ProcessHandle process) - WARN_UNUSED_RESULT; -#if defined(OS_WIN) - // Firefox text/html - static const FormatType& GetTextHtmlFormatType(); - static const FormatType& GetCFHDropFormatType(); - static const FormatType& GetFileDescriptorFormatType(); - static const FormatType& GetFileContentZeroFormatType(); - static const FormatType& GetIDListFormatType(); -#endif - - protected: - static Clipboard* Create(); - - Clipboard() {} - virtual ~Clipboard() {} - - // Write a bunch of objects to the system clipboard. Copies are made of the - // contents of |objects|. - virtual void WriteObjects(ClipboardType type, const ObjectMap& objects) = 0; - - void DispatchObject(ObjectType type, const ObjectMapParams& params); - - virtual void WriteText(const char* text_data, size_t text_len) = 0; - - virtual void WriteHTML(const char* markup_data, - size_t markup_len, - const char* url_data, - size_t url_len) = 0; - - virtual void WriteRTF(const char* rtf_data, size_t data_len) = 0; - - virtual void WriteBookmark(const char* title_data, - size_t title_len, - const char* url_data, - size_t url_len) = 0; - - virtual void WriteWebSmartPaste() = 0; - - virtual void WriteBitmap(const SkBitmap& bitmap) = 0; - - virtual void WriteData(const FormatType& format, - const char* data_data, - size_t data_len) = 0; - - private: - FRIEND_TEST_ALL_PREFIXES(ClipboardTest, SharedBitmapTest); - FRIEND_TEST_ALL_PREFIXES(ClipboardTest, EmptyHTMLTest); - friend class ClipboardTest; - // For access to WriteObjects(). - // TODO(dcheng): Remove the temporary exception for content. - friend class content::ClipboardMessageFilter; - friend class ScopedClipboardWriter; - - DISALLOW_COPY_AND_ASSIGN(Clipboard); -}; - -} // namespace ui - -#endif // UI_BASE_CLIPBOARD_CLIPBOARD_H_
diff --git a/ui/base/clipboard/clipboard_android.cc b/ui/base/clipboard/clipboard_android.cc deleted file mode 100644 index 8b25b7c..0000000 --- a/ui/base/clipboard/clipboard_android.cc +++ /dev/null
@@ -1,456 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/clipboard/clipboard_android.h" - -#include "base/android/jni_string.h" -#include "base/lazy_instance.h" -#include "base/stl_util.h" -#include "base/strings/utf_string_conversions.h" -#include "base/synchronization/lock.h" -#include "jni/Clipboard_jni.h" -#include "third_party/skia/include/core/SkBitmap.h" -#include "ui/gfx/size.h" - -// TODO:(andrewhayden) Support additional formats in Android: Bitmap, URI, HTML, -// HTML+text now that Android's clipboard system supports them, then nuke the -// legacy implementation note below. - -// Legacy implementation note: -// The Android clipboard system used to only support text format. So we used the -// Android system when some text was added or retrieved from the system. For -// anything else, we STILL store the value in some process wide static -// variable protected by a lock. So the (non-text) clipboard will only work -// within the same process. - -using base::android::AttachCurrentThread; -using base::android::ClearException; -using base::android::ConvertJavaStringToUTF8; -using base::android::ConvertUTF8ToJavaString; -using base::android::ScopedJavaGlobalRef; -using base::android::ScopedJavaLocalRef; - -namespace ui { - -namespace { -// Various formats we support. -const char kPlainTextFormat[] = "text"; -const char kHTMLFormat[] = "html"; -const char kRTFFormat[] = "rtf"; -const char kBitmapFormat[] = "bitmap"; -const char kWebKitSmartPasteFormat[] = "webkit_smart"; -const char kBookmarkFormat[] = "bookmark"; -const char kMimeTypePepperCustomData[] = "chromium/x-pepper-custom-data"; -const char kMimeTypeWebCustomData[] = "chromium/x-web-custom-data"; - -class ClipboardMap { - public: - ClipboardMap(); - std::string Get(const std::string& format); - bool HasFormat(const std::string& format); - void Set(const std::string& format, const std::string& data); - void Clear(); - - private: - void SyncWithAndroidClipboard(); - std::map<std::string, std::string> map_; - base::Lock lock_; - - // Java class and methods for the Android ClipboardManager. - ScopedJavaGlobalRef<jobject> clipboard_manager_; -}; -base::LazyInstance<ClipboardMap>::Leaky g_map = LAZY_INSTANCE_INITIALIZER; - -ClipboardMap::ClipboardMap() { - JNIEnv* env = AttachCurrentThread(); - DCHECK(env); - - // Get the context. - jobject context = base::android::GetApplicationContext(); - DCHECK(context); - - ScopedJavaLocalRef<jobject> local_ref = - Java_Clipboard_create(env, context); - DCHECK(local_ref.obj()); - clipboard_manager_.Reset(env, local_ref.Release()); -} - -std::string ClipboardMap::Get(const std::string& format) { - base::AutoLock lock(lock_); - SyncWithAndroidClipboard(); - std::map<std::string, std::string>::const_iterator it = map_.find(format); - return it == map_.end() ? std::string() : it->second; -} - -bool ClipboardMap::HasFormat(const std::string& format) { - base::AutoLock lock(lock_); - SyncWithAndroidClipboard(); - return ContainsKey(map_, format); -} - -void ClipboardMap::Set(const std::string& format, const std::string& data) { - JNIEnv* env = AttachCurrentThread(); - base::AutoLock lock(lock_); - SyncWithAndroidClipboard(); - - map_[format] = data; - if (format == kPlainTextFormat) { - ScopedJavaLocalRef<jstring> str = ConvertUTF8ToJavaString(env, data); - DCHECK(str.obj()); - - Java_Clipboard_setText(env, clipboard_manager_.obj(), str.obj()); - } else if (format == kHTMLFormat) { - // Android's API for storing HTML content on the clipboard requires a plain- - // text representation to be available as well. ScopedClipboardWriter has a - // stable order for setting clipboard data, ensuring that plain-text data - // is available first. Do not write to the clipboard when only HTML data is - // available, because otherwise others apps may not be able to paste it. - if (!ContainsKey(map_, kPlainTextFormat)) - return; - - ScopedJavaLocalRef<jstring> html = ConvertUTF8ToJavaString(env, data); - ScopedJavaLocalRef<jstring> text = ConvertUTF8ToJavaString( - env, map_[kPlainTextFormat].c_str()); - - DCHECK(html.obj() && text.obj()); - Java_Clipboard_setHTMLText( - env, clipboard_manager_.obj(), html.obj(), text.obj()); - } -} - -void ClipboardMap::Clear() { - JNIEnv* env = AttachCurrentThread(); - base::AutoLock lock(lock_); - map_.clear(); - Java_Clipboard_setText(env, clipboard_manager_.obj(), NULL); -} - -// If the internal map contains a plain-text entry and it does not match that -// in the Android clipboard, clear the map and insert the Android text into it. -// If there is an HTML entry in the Android clipboard it gets inserted in the -// map. -void ClipboardMap::SyncWithAndroidClipboard() { - lock_.AssertAcquired(); - JNIEnv* env = AttachCurrentThread(); - - // Update the plain text clipboard entry - std::map<std::string, std::string>::const_iterator it = - map_.find(kPlainTextFormat); - ScopedJavaLocalRef<jstring> java_string_text = - Java_Clipboard_getCoercedText(env, clipboard_manager_.obj()); - if (java_string_text.obj()) { - std::string android_string = ConvertJavaStringToUTF8(java_string_text); - if (!android_string.empty() && - (it == map_.end() || it->second != android_string)) { - // There is a different string in the Android clipboard than we have. - // Clear the map on our side. - map_.clear(); - map_[kPlainTextFormat] = android_string; - } - } else { - if (it != map_.end()) { - // We have plain text on this side, but Android doesn't. Nuke ours. - map_.clear(); - } - } - - if (!Java_Clipboard_isHTMLClipboardSupported(env)) { - return; - } - - // Update the html clipboard entry - ScopedJavaLocalRef<jstring> java_string_html = - Java_Clipboard_getHTMLText(env, clipboard_manager_.obj()); - if (java_string_html.obj()) { - std::string android_string = ConvertJavaStringToUTF8(java_string_html); - if (!android_string.empty()) { - map_[kHTMLFormat] = android_string; - return; - } - } - it = map_.find(kHTMLFormat); - if (it != map_.end()) { - map_.erase(kHTMLFormat); - } -} - -} // namespace - -// Clipboard::FormatType implementation. -Clipboard::FormatType::FormatType() { -} - -Clipboard::FormatType::FormatType(const std::string& native_format) - : data_(native_format) { -} - -Clipboard::FormatType::~FormatType() { -} - -std::string Clipboard::FormatType::Serialize() const { - return data_; -} - -// static -Clipboard::FormatType Clipboard::FormatType::Deserialize( - const std::string& serialization) { - return FormatType(serialization); -} - -bool Clipboard::FormatType::Equals(const FormatType& other) const { - return data_ == other.data_; -} - -// Various predefined FormatTypes. -// static -Clipboard::FormatType Clipboard::GetFormatType( - const std::string& format_string) { - return FormatType::Deserialize(format_string); -} - -// static -const Clipboard::FormatType& Clipboard::GetPlainTextFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (kPlainTextFormat)); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetPlainTextWFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (kPlainTextFormat)); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetWebKitSmartPasteFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (kWebKitSmartPasteFormat)); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetHtmlFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (kHTMLFormat)); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetRtfFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (kRTFFormat)); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetBitmapFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (kBitmapFormat)); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetWebCustomDataFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeWebCustomData)); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetPepperCustomDataFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypePepperCustomData)); - return type; -} - -// Clipboard factory method. -// static -Clipboard* Clipboard::Create() { - return new ClipboardAndroid; -} - -// ClipboardAndroid implementation. -ClipboardAndroid::ClipboardAndroid() { - DCHECK(CalledOnValidThread()); -} - -ClipboardAndroid::~ClipboardAndroid() { - DCHECK(CalledOnValidThread()); -} - -uint64 ClipboardAndroid::GetSequenceNumber(ClipboardType /* type */) { - DCHECK(CalledOnValidThread()); - // TODO: implement this. For now this interface will advertise - // that the clipboard never changes. That's fine as long as we - // don't rely on this signal. - return 0; -} - -bool ClipboardAndroid::IsFormatAvailable(const Clipboard::FormatType& format, - ClipboardType type) const { - DCHECK(CalledOnValidThread()); - DCHECK_EQ(type, CLIPBOARD_TYPE_COPY_PASTE); - return g_map.Get().HasFormat(format.ToString()); -} - -void ClipboardAndroid::Clear(ClipboardType type) { - DCHECK(CalledOnValidThread()); - DCHECK_EQ(type, CLIPBOARD_TYPE_COPY_PASTE); - g_map.Get().Clear(); -} - -void ClipboardAndroid::ReadAvailableTypes(ClipboardType type, - std::vector<base::string16>* types, - bool* contains_filenames) const { - DCHECK(CalledOnValidThread()); - DCHECK_EQ(type, CLIPBOARD_TYPE_COPY_PASTE); - - if (!types || !contains_filenames) { - NOTREACHED(); - return; - } - - NOTIMPLEMENTED(); - - types->clear(); - *contains_filenames = false; -} - -void ClipboardAndroid::ReadText(ClipboardType type, - base::string16* result) const { - DCHECK(CalledOnValidThread()); - DCHECK_EQ(type, CLIPBOARD_TYPE_COPY_PASTE); - std::string utf8; - ReadAsciiText(type, &utf8); - *result = base::UTF8ToUTF16(utf8); -} - -void ClipboardAndroid::ReadAsciiText(ClipboardType type, - std::string* result) const { - DCHECK(CalledOnValidThread()); - DCHECK_EQ(type, CLIPBOARD_TYPE_COPY_PASTE); - *result = g_map.Get().Get(kPlainTextFormat); -} - -// Note: |src_url| isn't really used. It is only implemented in Windows -void ClipboardAndroid::ReadHTML(ClipboardType type, - base::string16* markup, - std::string* src_url, - uint32* fragment_start, - uint32* fragment_end) const { - DCHECK(CalledOnValidThread()); - DCHECK_EQ(type, CLIPBOARD_TYPE_COPY_PASTE); - if (src_url) - src_url->clear(); - - std::string input = g_map.Get().Get(kHTMLFormat); - *markup = base::UTF8ToUTF16(input); - - *fragment_start = 0; - *fragment_end = static_cast<uint32>(markup->length()); -} - -void ClipboardAndroid::ReadRTF(ClipboardType type, std::string* result) const { - DCHECK(CalledOnValidThread()); - NOTIMPLEMENTED(); -} - -SkBitmap ClipboardAndroid::ReadImage(ClipboardType type) const { - DCHECK(CalledOnValidThread()); - DCHECK_EQ(type, CLIPBOARD_TYPE_COPY_PASTE); - std::string input = g_map.Get().Get(kBitmapFormat); - - SkBitmap bmp; - if (!input.empty()) { - DCHECK_LE(sizeof(gfx::Size), input.size()); - const gfx::Size* size = reinterpret_cast<const gfx::Size*>(input.data()); - - bmp.allocN32Pixels(size->width(), size->height()); - - DCHECK_EQ(sizeof(gfx::Size) + bmp.getSize(), input.size()); - - memcpy(bmp.getPixels(), input.data() + sizeof(gfx::Size), bmp.getSize()); - } - return bmp; -} - -void ClipboardAndroid::ReadCustomData(ClipboardType clipboard_type, - const base::string16& type, - base::string16* result) const { - DCHECK(CalledOnValidThread()); - NOTIMPLEMENTED(); -} - -void ClipboardAndroid::ReadBookmark(base::string16* title, - std::string* url) const { - DCHECK(CalledOnValidThread()); - NOTIMPLEMENTED(); -} - -void ClipboardAndroid::ReadData(const Clipboard::FormatType& format, - std::string* result) const { - DCHECK(CalledOnValidThread()); - *result = g_map.Get().Get(format.ToString()); -} - -// Main entry point used to write several values in the clipboard. -void ClipboardAndroid::WriteObjects(ClipboardType type, - const ObjectMap& objects) { - DCHECK(CalledOnValidThread()); - DCHECK_EQ(type, CLIPBOARD_TYPE_COPY_PASTE); - g_map.Get().Clear(); - for (ObjectMap::const_iterator iter = objects.begin(); iter != objects.end(); - ++iter) { - DispatchObject(static_cast<ObjectType>(iter->first), iter->second); - } -} - -void ClipboardAndroid::WriteText(const char* text_data, size_t text_len) { - g_map.Get().Set(kPlainTextFormat, std::string(text_data, text_len)); -} - -void ClipboardAndroid::WriteHTML(const char* markup_data, - size_t markup_len, - const char* url_data, - size_t url_len) { - g_map.Get().Set(kHTMLFormat, std::string(markup_data, markup_len)); -} - -void ClipboardAndroid::WriteRTF(const char* rtf_data, size_t data_len) { - NOTIMPLEMENTED(); -} - -// Note: according to other platforms implementations, this really writes the -// URL spec. -void ClipboardAndroid::WriteBookmark(const char* title_data, - size_t title_len, - const char* url_data, - size_t url_len) { - g_map.Get().Set(kBookmarkFormat, std::string(url_data, url_len)); -} - -// Write an extra flavor that signifies WebKit was the last to modify the -// pasteboard. This flavor has no data. -void ClipboardAndroid::WriteWebSmartPaste() { - g_map.Get().Set(kWebKitSmartPasteFormat, std::string()); -} - -// Note: we implement this to pass all unit tests but it is currently unclear -// how some code would consume this. -void ClipboardAndroid::WriteBitmap(const SkBitmap& bitmap) { - gfx::Size size(bitmap.width(), bitmap.height()); - - std::string packed(reinterpret_cast<const char*>(&size), sizeof(size)); - { - SkAutoLockPixels bitmap_lock(bitmap); - packed += std::string(static_cast<const char*>(bitmap.getPixels()), - bitmap.getSize()); - } - g_map.Get().Set(kBitmapFormat, packed); -} - -void ClipboardAndroid::WriteData(const Clipboard::FormatType& format, - const char* data_data, - size_t data_len) { - g_map.Get().Set(format.ToString(), std::string(data_data, data_len)); -} - -bool RegisterClipboardAndroid(JNIEnv* env) { - return RegisterNativesImpl(env); -} - -} // namespace ui
diff --git a/ui/base/clipboard/clipboard_android.h b/ui/base/clipboard/clipboard_android.h deleted file mode 100644 index 65287bf..0000000 --- a/ui/base/clipboard/clipboard_android.h +++ /dev/null
@@ -1,67 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_CLIPBOARD_CLIPBOARD_ANDROID_H_ -#define UI_BASE_CLIPBOARD_CLIPBOARD_ANDROID_H_ - -#include "ui/base/clipboard/clipboard.h" - -#include <jni.h> - -namespace ui { - -bool RegisterClipboardAndroid(JNIEnv* env); - -class ClipboardAndroid : public Clipboard { - private: - friend class Clipboard; - - ClipboardAndroid(); - ~ClipboardAndroid() override; - - // Clipboard overrides: - uint64 GetSequenceNumber(ClipboardType type) override; - bool IsFormatAvailable(const FormatType& format, - ClipboardType type) const override; - void Clear(ClipboardType type) override; - void ReadAvailableTypes(ClipboardType type, - std::vector<base::string16>* types, - bool* contains_filenames) const override; - void ReadText(ClipboardType type, base::string16* result) const override; - void ReadAsciiText(ClipboardType type, std::string* result) const override; - void ReadHTML(ClipboardType type, - base::string16* markup, - std::string* src_url, - uint32* fragment_start, - uint32* fragment_end) const override; - void ReadRTF(ClipboardType type, std::string* result) const override; - SkBitmap ReadImage(ClipboardType type) const override; - void ReadCustomData(ClipboardType clipboard_type, - const base::string16& type, - base::string16* result) const override; - void ReadBookmark(base::string16* title, std::string* url) const override; - void ReadData(const FormatType& format, std::string* result) const override; - void WriteObjects(ClipboardType type, const ObjectMap& objects) override; - void WriteText(const char* text_data, size_t text_len) override; - void WriteHTML(const char* markup_data, - size_t markup_len, - const char* url_data, - size_t url_len) override; - void WriteRTF(const char* rtf_data, size_t data_len) override; - void WriteBookmark(const char* title_data, - size_t title_len, - const char* url_data, - size_t url_len) override; - void WriteWebSmartPaste() override; - void WriteBitmap(const SkBitmap& bitmap) override; - void WriteData(const FormatType& format, - const char* data_data, - size_t data_len) override; - - DISALLOW_COPY_AND_ASSIGN(ClipboardAndroid); -}; - -} // namespace ui - -#endif // UI_BASE_CLIPBOARD_CLIPBOARD_ANDROID_H_
diff --git a/ui/base/clipboard/clipboard_aura.cc b/ui/base/clipboard/clipboard_aura.cc deleted file mode 100644 index 166f3bb..0000000 --- a/ui/base/clipboard/clipboard_aura.cc +++ /dev/null
@@ -1,689 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/clipboard/clipboard_aura.h" - -#include <list> - -#include "base/basictypes.h" -#include "base/files/file_path.h" -#include "base/logging.h" -#include "base/memory/scoped_ptr.h" -#include "base/stl_util.h" -#include "base/strings/utf_string_conversions.h" -#include "third_party/skia/include/core/SkBitmap.h" -#include "ui/base/clipboard/custom_data_helper.h" -#include "ui/gfx/size.h" - -namespace ui { - -namespace { -const char kMimeTypeFilename[] = "chromium/filename"; -const char kMimeTypeBitmap[] = "image/bmp"; -const char kMimeTypePepperCustomData[] = "chromium/x-pepper-custom-data"; -const char kMimeTypeWebkitSmartPaste[] = "chromium/x-webkit-paste"; -const size_t kMaxClipboardSize = 1; - -// Clipboard data format used by AuraClipboard. -enum AuraClipboardFormat { - TEXT = 1 << 0, - HTML = 1 << 1, - RTF = 1 << 2, - BOOKMARK = 1 << 3, - BITMAP = 1 << 4, - CUSTOM = 1 << 5, - WEB = 1 << 6, -}; - -// ClipboardData contains data copied to the Clipboard for a variety of formats. -// It mostly just provides APIs to cleanly access and manipulate this data. -class ClipboardData { - public: - ClipboardData() - : web_smart_paste_(false), - format_(0) {} - - virtual ~ClipboardData() {} - - // Bitmask of AuraClipboardFormat types. - int format() const { return format_; } - - const std::string& text() const { return text_; } - void set_text(const std::string& text) { - text_ = text; - format_ |= TEXT; - } - - const std::string& markup_data() const { return markup_data_; } - void set_markup_data(const std::string& markup_data) { - markup_data_ = markup_data; - format_ |= HTML; - } - - const std::string& rtf_data() const { return rtf_data_; } - void SetRTFData(const std::string& rtf_data) { - rtf_data_ = rtf_data; - format_ |= RTF; - } - - const std::string& url() const { return url_; } - void set_url(const std::string& url) { - url_ = url; - format_ |= HTML; - } - - const std::string& bookmark_title() const { return bookmark_title_; } - void set_bookmark_title(const std::string& bookmark_title) { - bookmark_title_ = bookmark_title; - format_ |= BOOKMARK; - } - - const std::string& bookmark_url() const { return bookmark_url_; } - void set_bookmark_url(const std::string& bookmark_url) { - bookmark_url_ = bookmark_url; - format_ |= BOOKMARK; - } - - const SkBitmap& bitmap() const { return bitmap_; } - void SetBitmapData(const SkBitmap& bitmap) { - bitmap.copyTo(&bitmap_); - format_ |= BITMAP; - } - - const std::string& custom_data_format() const { return custom_data_format_; } - const std::string& custom_data_data() const { return custom_data_data_; } - void SetCustomData(const std::string& data_format, - const std::string& data_data) { - if (data_data.size() == 0) { - custom_data_data_.clear(); - custom_data_format_.clear(); - return; - } - custom_data_data_ = data_data; - custom_data_format_ = data_format; - format_ |= CUSTOM; - } - - bool web_smart_paste() const { return web_smart_paste_; } - void set_web_smart_paste(bool web_smart_paste) { - web_smart_paste_ = web_smart_paste; - format_ |= WEB; - } - - private: - // Plain text in UTF8 format. - std::string text_; - - // HTML markup data in UTF8 format. - std::string markup_data_; - std::string url_; - - // RTF data. - std::string rtf_data_; - - // Bookmark title in UTF8 format. - std::string bookmark_title_; - std::string bookmark_url_; - - // Filenames. - std::vector<std::string> files_; - - // Bitmap images. - SkBitmap bitmap_; - - // Data with custom format. - std::string custom_data_format_; - std::string custom_data_data_; - - // WebKit smart paste data. - bool web_smart_paste_; - - int format_; - - DISALLOW_COPY_AND_ASSIGN(ClipboardData); -}; - -// Platform clipboard implementation for Aura. This handles things like format -// conversion, versioning of clipboard items etc. The goal is to roughly provide -// a substitute to platform clipboards on other platforms such as GtkClipboard -// on gtk or winapi clipboard on win. -class AuraClipboard { - public: - AuraClipboard() : sequence_number_(0) { - } - - ~AuraClipboard() { - Clear(); - } - - void Clear() { - sequence_number_++; - STLDeleteContainerPointers(data_list_.begin(), data_list_.end()); - data_list_.clear(); - } - - uint64_t sequence_number() const { - return sequence_number_; - } - - // Returns the data currently on the top of the clipboard stack, NULL if the - // clipboard stack is empty. - const ClipboardData* GetData() const { - if (data_list_.empty()) - return NULL; - return data_list_.front(); - } - - // Returns true if the data on top of the clipboard stack has format |format| - // or another format that can be converted to |format|. - bool IsFormatAvailable(AuraClipboardFormat format) const { - switch (format) { - case TEXT: - return HasFormat(TEXT) || HasFormat(BOOKMARK); - default: - return HasFormat(format); - } - } - - // Reads text from the data at the top of clipboard stack. - void ReadText(base::string16* result) const { - std::string utf8_result; - ReadAsciiText(&utf8_result); - *result = base::UTF8ToUTF16(utf8_result); - } - - // Reads ascii text from the data at the top of clipboard stack. - void ReadAsciiText(std::string* result) const { - result->clear(); - const ClipboardData* data = GetData(); - if (!data) - return; - if (HasFormat(TEXT)) - *result = data->text(); - else if (HasFormat(HTML)) - *result = data->markup_data(); - else if (HasFormat(BOOKMARK)) - *result = data->bookmark_url(); - } - - // Reads HTML from the data at the top of clipboard stack. - void ReadHTML(base::string16* markup, - std::string* src_url, - uint32* fragment_start, - uint32* fragment_end) const { - markup->clear(); - if (src_url) - src_url->clear(); - *fragment_start = 0; - *fragment_end = 0; - - if (!HasFormat(HTML)) - return; - - const ClipboardData* data = GetData(); - *markup = base::UTF8ToUTF16(data->markup_data()); - *src_url = data->url(); - - *fragment_start = 0; - DCHECK_LE(markup->length(), kuint32max); - *fragment_end = static_cast<uint32>(markup->length()); - } - - // Reads RTF from the data at the top of clipboard stack. - void ReadRTF(std::string* result) const { - result->clear(); - const ClipboardData* data = GetData(); - if (!HasFormat(RTF)) - return; - - *result = data->rtf_data(); - } - - // Reads image from the data at the top of clipboard stack. - SkBitmap ReadImage() const { - SkBitmap img; - if (!HasFormat(BITMAP)) - return img; - - // A shallow copy should be fine here, but just to be safe... - const SkBitmap& clipboard_bitmap = GetData()->bitmap(); - clipboard_bitmap.copyTo(&img); - return img; - } - - // Reads data of type |type| from the data at the top of clipboard stack. - void ReadCustomData(const base::string16& type, - base::string16* result) const { - result->clear(); - const ClipboardData* data = GetData(); - if (!HasFormat(CUSTOM)) - return; - - ui::ReadCustomDataForType(data->custom_data_data().c_str(), - data->custom_data_data().size(), - type, result); - } - - // Reads bookmark from the data at the top of clipboard stack. - void ReadBookmark(base::string16* title, std::string* url) const { - title->clear(); - url->clear(); - if (!HasFormat(BOOKMARK)) - return; - - const ClipboardData* data = GetData(); - *title = base::UTF8ToUTF16(data->bookmark_title()); - *url = data->bookmark_url(); - } - - void ReadData(const std::string& type, std::string* result) const { - result->clear(); - const ClipboardData* data = GetData(); - if (!HasFormat(CUSTOM) || type != data->custom_data_format()) - return; - - *result = data->custom_data_data(); - } - - // Writes |data| to the top of the clipboard stack. - void WriteData(ClipboardData* data) { - DCHECK(data); - AddToListEnsuringSize(data); - } - - private: - // True if the data on top of the clipboard stack has format |format|. - bool HasFormat(AuraClipboardFormat format) const { - const ClipboardData* data = GetData(); - if (!data) - return false; - - return data->format() & format; - } - - void AddToListEnsuringSize(ClipboardData* data) { - DCHECK(data); - sequence_number_++; - data_list_.push_front(data); - - // If the size of list becomes more than the maximum allowed, we delete the - // last element. - if (data_list_.size() > kMaxClipboardSize) { - ClipboardData* last = data_list_.back(); - data_list_.pop_back(); - delete last; - } - } - - // Stack containing various versions of ClipboardData. - std::list<ClipboardData*> data_list_; - - // Sequence number uniquely identifying clipboard state. - uint64_t sequence_number_; - - DISALLOW_COPY_AND_ASSIGN(AuraClipboard); -}; - -AuraClipboard* aura_clipboard = NULL; - -AuraClipboard* GetClipboard() { - if (!aura_clipboard) - aura_clipboard = new AuraClipboard(); - return aura_clipboard; -} - -void DeleteClipboard() { - if (aura_clipboard) - delete aura_clipboard; - aura_clipboard = NULL; -} - -// Helper class to build a ClipboardData object and write it to clipboard. -class ClipboardDataBuilder { - public: - static void CommitToClipboard() { - GetClipboard()->WriteData(GetCurrentData()); - current_data_ = NULL; - } - - static void WriteText(const char* text_data, size_t text_len) { - ClipboardData* data = GetCurrentData(); - data->set_text(std::string(text_data, text_len)); - } - - static void WriteHTML(const char* markup_data, - size_t markup_len, - const char* url_data, - size_t url_len) { - ClipboardData* data = GetCurrentData(); - data->set_markup_data(std::string(markup_data, markup_len)); - data->set_url(std::string(url_data, url_len)); - } - - static void WriteRTF(const char* rtf_data, size_t rtf_len) { - ClipboardData* data = GetCurrentData(); - data->SetRTFData(std::string(rtf_data, rtf_len)); - } - - static void WriteBookmark(const char* title_data, - size_t title_len, - const char* url_data, - size_t url_len) { - ClipboardData* data = GetCurrentData(); - data->set_bookmark_title(std::string(title_data, title_len)); - data->set_bookmark_url(std::string(url_data, url_len)); - } - - static void WriteWebSmartPaste() { - ClipboardData* data = GetCurrentData(); - data->set_web_smart_paste(true); - } - - static void WriteBitmap(const SkBitmap& bitmap) { - ClipboardData* data = GetCurrentData(); - data->SetBitmapData(bitmap); - } - - static void WriteData(const std::string& format, - const char* data_data, - size_t data_len) { - ClipboardData* data = GetCurrentData(); - data->SetCustomData(format, std::string(data_data, data_len)); - } - - private: - static ClipboardData* GetCurrentData() { - if (!current_data_) - current_data_ = new ClipboardData; - return current_data_; - } - - static ClipboardData* current_data_; -}; - -ClipboardData* ClipboardDataBuilder::current_data_ = NULL; - -} // namespace - -// Clipboard::FormatType implementation. -Clipboard::FormatType::FormatType() { -} - -Clipboard::FormatType::FormatType(const std::string& native_format) - : data_(native_format) { -} - -Clipboard::FormatType::~FormatType() { -} - -std::string Clipboard::FormatType::Serialize() const { - return data_; -} - -// static -Clipboard::FormatType Clipboard::FormatType::Deserialize( - const std::string& serialization) { - return FormatType(serialization); -} - -bool Clipboard::FormatType::operator<(const FormatType& other) const { - return data_ < other.data_; -} - -bool Clipboard::FormatType::Equals(const FormatType& other) const { - return data_ == other.data_; -} - -// Various predefined FormatTypes. -// static -Clipboard::FormatType Clipboard::GetFormatType( - const std::string& format_string) { - return FormatType::Deserialize(format_string); -} - -// static -const Clipboard::FormatType& Clipboard::GetUrlFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeURIList)); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetUrlWFormatType() { - return GetUrlFormatType(); -} - -// static -const Clipboard::FormatType& Clipboard::GetPlainTextFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeText)); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetPlainTextWFormatType() { - return GetPlainTextFormatType(); -} - -// static -const Clipboard::FormatType& Clipboard::GetFilenameFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeFilename)); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetFilenameWFormatType() { - return Clipboard::GetFilenameFormatType(); -} - -// static -const Clipboard::FormatType& Clipboard::GetHtmlFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeHTML)); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetRtfFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeRTF)); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetBitmapFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeBitmap)); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetWebKitSmartPasteFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeWebkitSmartPaste)); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetWebCustomDataFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeWebCustomData)); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetPepperCustomDataFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypePepperCustomData)); - return type; -} - -// Clipboard factory method. -Clipboard* Clipboard::Create() { - return new ClipboardAura; -} - -// ClipboardAura implementation. -ClipboardAura::ClipboardAura() { - DCHECK(CalledOnValidThread()); - // Make sure clipboard is created. - GetClipboard(); -} - -ClipboardAura::~ClipboardAura() { - DCHECK(CalledOnValidThread()); - DeleteClipboard(); -} - -uint64 ClipboardAura::GetSequenceNumber(ClipboardType type) { - DCHECK(CalledOnValidThread()); - return GetClipboard()->sequence_number(); -} - -bool ClipboardAura::IsFormatAvailable(const FormatType& format, - ClipboardType type) const { - DCHECK(CalledOnValidThread()); - DCHECK(IsSupportedClipboardType(type)); - AuraClipboard* clipboard = GetClipboard(); - if (GetPlainTextFormatType().Equals(format) || - GetUrlFormatType().Equals(format)) - return clipboard->IsFormatAvailable(TEXT); - else if (GetHtmlFormatType().Equals(format)) - return clipboard->IsFormatAvailable(HTML); - else if (GetRtfFormatType().Equals(format)) - return clipboard->IsFormatAvailable(RTF); - else if (GetBitmapFormatType().Equals(format)) - return clipboard->IsFormatAvailable(BITMAP); - else if (GetWebKitSmartPasteFormatType().Equals(format)) - return clipboard->IsFormatAvailable(WEB); - else { - const ClipboardData* data = clipboard->GetData(); - if (data && data->custom_data_format() == format.ToString()) - return true; - } - return false; -} - -void ClipboardAura::Clear(ClipboardType type) { - DCHECK(CalledOnValidThread()); - DCHECK(IsSupportedClipboardType(type)); - AuraClipboard* clipboard = GetClipboard(); - clipboard->Clear(); -} - -void ClipboardAura::ReadAvailableTypes(ClipboardType type, - std::vector<base::string16>* types, - bool* contains_filenames) const { - DCHECK(CalledOnValidThread()); - if (!types || !contains_filenames) { - NOTREACHED(); - return; - } - - types->clear(); - *contains_filenames = false; - if (IsFormatAvailable(GetPlainTextFormatType(), type)) - types->push_back(base::UTF8ToUTF16(GetPlainTextFormatType().ToString())); - if (IsFormatAvailable(GetHtmlFormatType(), type)) - types->push_back(base::UTF8ToUTF16(GetHtmlFormatType().ToString())); - if (IsFormatAvailable(GetRtfFormatType(), type)) - types->push_back(base::UTF8ToUTF16(GetRtfFormatType().ToString())); - if (IsFormatAvailable(GetBitmapFormatType(), type)) - types->push_back(base::UTF8ToUTF16(kMimeTypePNG)); - - AuraClipboard* clipboard = GetClipboard(); - if (clipboard->IsFormatAvailable(CUSTOM) && clipboard->GetData()) { - ui::ReadCustomDataTypes(clipboard->GetData()->custom_data_data().c_str(), - clipboard->GetData()->custom_data_data().size(), types); - } -} - -void ClipboardAura::ReadText(ClipboardType type, base::string16* result) const { - DCHECK(CalledOnValidThread()); - GetClipboard()->ReadText(result); -} - -void ClipboardAura::ReadAsciiText(ClipboardType type, - std::string* result) const { - DCHECK(CalledOnValidThread()); - GetClipboard()->ReadAsciiText(result); -} - -void ClipboardAura::ReadHTML(ClipboardType type, - base::string16* markup, - std::string* src_url, - uint32* fragment_start, - uint32* fragment_end) const { - DCHECK(CalledOnValidThread()); - GetClipboard()->ReadHTML(markup, src_url, fragment_start, fragment_end); -} - -void ClipboardAura::ReadRTF(ClipboardType type, std::string* result) const { - DCHECK(CalledOnValidThread()); - GetClipboard()->ReadRTF(result); -} - -SkBitmap ClipboardAura::ReadImage(ClipboardType type) const { - DCHECK(CalledOnValidThread()); - return GetClipboard()->ReadImage(); -} - -void ClipboardAura::ReadCustomData(ClipboardType clipboard_type, - const base::string16& type, - base::string16* result) const { - DCHECK(CalledOnValidThread()); - GetClipboard()->ReadCustomData(type, result); -} - -void ClipboardAura::ReadBookmark(base::string16* title, - std::string* url) const { - DCHECK(CalledOnValidThread()); - GetClipboard()->ReadBookmark(title, url); -} - -void ClipboardAura::ReadData(const FormatType& format, - std::string* result) const { - DCHECK(CalledOnValidThread()); - GetClipboard()->ReadData(format.ToString(), result); -} - -void ClipboardAura::WriteObjects(ClipboardType type, const ObjectMap& objects) { - DCHECK(CalledOnValidThread()); - DCHECK(IsSupportedClipboardType(type)); - for (ObjectMap::const_iterator iter = objects.begin(); iter != objects.end(); - ++iter) { - DispatchObject(static_cast<ObjectType>(iter->first), iter->second); - } - ClipboardDataBuilder::CommitToClipboard(); -} - -void ClipboardAura::WriteText(const char* text_data, size_t text_len) { - ClipboardDataBuilder::WriteText(text_data, text_len); -} - -void ClipboardAura::WriteHTML(const char* markup_data, - size_t markup_len, - const char* url_data, - size_t url_len) { - ClipboardDataBuilder::WriteHTML(markup_data, markup_len, url_data, url_len); -} - -void ClipboardAura::WriteRTF(const char* rtf_data, size_t data_len) { - ClipboardDataBuilder::WriteRTF(rtf_data, data_len); -} - -void ClipboardAura::WriteBookmark(const char* title_data, - size_t title_len, - const char* url_data, - size_t url_len) { - ClipboardDataBuilder::WriteBookmark(title_data, title_len, url_data, url_len); -} - -void ClipboardAura::WriteWebSmartPaste() { - ClipboardDataBuilder::WriteWebSmartPaste(); -} - -void ClipboardAura::WriteBitmap(const SkBitmap& bitmap) { - ClipboardDataBuilder::WriteBitmap(bitmap); -} - -void ClipboardAura::WriteData(const FormatType& format, - const char* data_data, - size_t data_len) { - ClipboardDataBuilder::WriteData(format.ToString(), data_data, data_len); -} - -} // namespace ui
diff --git a/ui/base/clipboard/clipboard_aura.h b/ui/base/clipboard/clipboard_aura.h deleted file mode 100644 index bb2fbc6..0000000 --- a/ui/base/clipboard/clipboard_aura.h +++ /dev/null
@@ -1,63 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_CLIPBOARD_CLIPBOARD_AURA_H_ -#define UI_BASE_CLIPBOARD_CLIPBOARD_AURA_H_ - -#include "ui/base/clipboard/clipboard.h" - -namespace ui { - -class ClipboardAura : public Clipboard { - private: - friend class Clipboard; - - ClipboardAura(); - ~ClipboardAura() override; - - // Clipboard overrides: - uint64 GetSequenceNumber(ClipboardType type) override; - bool IsFormatAvailable(const FormatType& format, - ClipboardType type) const override; - void Clear(ClipboardType type) override; - void ReadAvailableTypes(ClipboardType type, - std::vector<base::string16>* types, - bool* contains_filenames) const override; - void ReadText(ClipboardType type, base::string16* result) const override; - void ReadAsciiText(ClipboardType type, std::string* result) const override; - void ReadHTML(ClipboardType type, - base::string16* markup, - std::string* src_url, - uint32* fragment_start, - uint32* fragment_end) const override; - void ReadRTF(ClipboardType type, std::string* result) const override; - SkBitmap ReadImage(ClipboardType type) const override; - void ReadCustomData(ClipboardType clipboard_type, - const base::string16& type, - base::string16* result) const override; - void ReadBookmark(base::string16* title, std::string* url) const override; - void ReadData(const FormatType& format, std::string* result) const override; - void WriteObjects(ClipboardType type, const ObjectMap& objects) override; - void WriteText(const char* text_data, size_t text_len) override; - void WriteHTML(const char* markup_data, - size_t markup_len, - const char* url_data, - size_t url_len) override; - void WriteRTF(const char* rtf_data, size_t data_len) override; - void WriteBookmark(const char* title_data, - size_t title_len, - const char* url_data, - size_t url_len) override; - void WriteWebSmartPaste() override; - void WriteBitmap(const SkBitmap& bitmap) override; - void WriteData(const FormatType& format, - const char* data_data, - size_t data_len) override; - - DISALLOW_COPY_AND_ASSIGN(ClipboardAura); -}; - -} // namespace ui - -#endif // UI_BASE_CLIPBOARD_CLIPBOARD_AURA_H_
diff --git a/ui/base/clipboard/clipboard_aurax11.cc b/ui/base/clipboard/clipboard_aurax11.cc deleted file mode 100644 index b12c696..0000000 --- a/ui/base/clipboard/clipboard_aurax11.cc +++ /dev/null
@@ -1,938 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/clipboard/clipboard_aurax11.h" - -#include <X11/extensions/Xfixes.h> -#include <X11/Xatom.h> -#include <list> -#include <set> - -#include "base/basictypes.h" -#include "base/files/file_path.h" -#include "base/logging.h" -#include "base/memory/ref_counted_memory.h" -#include "base/memory/scoped_ptr.h" -#include "base/memory/singleton.h" -#include "base/metrics/histogram.h" -#include "base/stl_util.h" -#include "base/strings/utf_string_conversions.h" -#include "third_party/skia/include/core/SkBitmap.h" -#include "ui/base/clipboard/custom_data_helper.h" -#include "ui/base/x/selection_owner.h" -#include "ui/base/x/selection_requestor.h" -#include "ui/base/x/selection_utils.h" -#include "ui/base/x/x11_util.h" -#include "ui/events/platform/platform_event_dispatcher.h" -#include "ui/events/platform/platform_event_observer.h" -#include "ui/events/platform/platform_event_source.h" -#include "ui/gfx/codec/png_codec.h" -#include "ui/gfx/size.h" -#include "ui/gfx/x/x11_atom_cache.h" - -namespace ui { - -namespace { - -const char kClipboard[] = "CLIPBOARD"; -const char kClipboardManager[] = "CLIPBOARD_MANAGER"; -const char kMimeTypeFilename[] = "chromium/filename"; -const char kMimeTypePepperCustomData[] = "chromium/x-pepper-custom-data"; -const char kMimeTypeWebkitSmartPaste[] = "chromium/x-webkit-paste"; -const char kSaveTargets[] = "SAVE_TARGETS"; -const char kTargets[] = "TARGETS"; - -const char* kAtomsToCache[] = { - kClipboard, - kClipboardManager, - Clipboard::kMimeTypePNG, - kMimeTypeFilename, - kMimeTypeMozillaURL, - kMimeTypeWebkitSmartPaste, - kSaveTargets, - kString, - kTargets, - kText, - kUtf8String, - NULL -}; - -/////////////////////////////////////////////////////////////////////////////// - -// Uses the XFixes API to provide sequence numbers for GetSequenceNumber(). -class SelectionChangeObserver : public ui::PlatformEventObserver { - public: - static SelectionChangeObserver* GetInstance(); - - uint64 clipboard_sequence_number() const { - return clipboard_sequence_number_; - } - uint64 primary_sequence_number() const { return primary_sequence_number_; } - - private: - friend struct DefaultSingletonTraits<SelectionChangeObserver>; - - SelectionChangeObserver(); - virtual ~SelectionChangeObserver(); - - // ui::PlatformEventObserver: - virtual void WillProcessEvent(const ui::PlatformEvent& event) override; - virtual void DidProcessEvent(const ui::PlatformEvent& event) override {} - - int event_base_; - Atom clipboard_atom_; - uint64 clipboard_sequence_number_; - uint64 primary_sequence_number_; - - DISALLOW_COPY_AND_ASSIGN(SelectionChangeObserver); -}; - -SelectionChangeObserver::SelectionChangeObserver() - : event_base_(-1), - clipboard_atom_(None), - clipboard_sequence_number_(0), - primary_sequence_number_(0) { - int ignored; - if (XFixesQueryExtension(gfx::GetXDisplay(), &event_base_, &ignored)) { - clipboard_atom_ = XInternAtom(gfx::GetXDisplay(), kClipboard, false); - XFixesSelectSelectionInput(gfx::GetXDisplay(), GetX11RootWindow(), - clipboard_atom_, - XFixesSetSelectionOwnerNotifyMask | - XFixesSelectionWindowDestroyNotifyMask | - XFixesSelectionClientCloseNotifyMask); - // This seems to be semi-optional. For some reason, registering for any - // selection notify events seems to subscribe us to events for both the - // primary and the clipboard buffers. Register anyway just to be safe. - XFixesSelectSelectionInput(gfx::GetXDisplay(), GetX11RootWindow(), - XA_PRIMARY, - XFixesSetSelectionOwnerNotifyMask | - XFixesSelectionWindowDestroyNotifyMask | - XFixesSelectionClientCloseNotifyMask); - - ui::PlatformEventSource::GetInstance()->AddPlatformEventObserver(this); - } -} - -SelectionChangeObserver::~SelectionChangeObserver() { - // We are a singleton; we will outlive the event source. -} - -SelectionChangeObserver* SelectionChangeObserver::GetInstance() { - return Singleton<SelectionChangeObserver>::get(); -} - -void SelectionChangeObserver::WillProcessEvent(const ui::PlatformEvent& event) { - if (event->type == event_base_ + XFixesSelectionNotify) { - XFixesSelectionNotifyEvent* ev = - reinterpret_cast<XFixesSelectionNotifyEvent*>(event); - if (ev->selection == clipboard_atom_) { - clipboard_sequence_number_++; - } else if (ev->selection == XA_PRIMARY) { - primary_sequence_number_++; - } else { - DLOG(ERROR) << "Unexpected selection atom: " << ev->selection; - } - } -} - -/////////////////////////////////////////////////////////////////////////////// - -// Represents a list of possible return types. Copy constructable. -class TargetList { - public: - typedef std::vector< ::Atom> AtomVector; - - TargetList(const AtomVector& target_list, X11AtomCache* atom_cache); - - const AtomVector& target_list() { return target_list_; } - - bool ContainsText() const; - bool ContainsFormat(const Clipboard::FormatType& format_type) const; - bool ContainsAtom(::Atom atom) const; - - private: - AtomVector target_list_; - X11AtomCache* atom_cache_; -}; - -TargetList::TargetList(const AtomVector& target_list, - X11AtomCache* atom_cache) - : target_list_(target_list), - atom_cache_(atom_cache) { -} - -bool TargetList::ContainsText() const { - std::vector< ::Atom> atoms = GetTextAtomsFrom(atom_cache_); - for (std::vector< ::Atom>::const_iterator it = atoms.begin(); - it != atoms.end(); ++it) { - if (ContainsAtom(*it)) - return true; - } - - return false; -} - -bool TargetList::ContainsFormat( - const Clipboard::FormatType& format_type) const { - ::Atom atom = atom_cache_->GetAtom(format_type.ToString().c_str()); - return ContainsAtom(atom); -} - -bool TargetList::ContainsAtom(::Atom atom) const { - return find(target_list_.begin(), target_list_.end(), atom) - != target_list_.end(); -} - -} // namespace - -/////////////////////////////////////////////////////////////////////////////// - -// I would love for the FormatType to really be a wrapper around an X11 ::Atom, -// but there are a few problems. Chromeos unit tests spawn a new X11 server for -// each test, so Atom numeric values don't persist across tests. We could still -// maybe deal with that if we didn't have static accessor methods everywhere. - -Clipboard::FormatType::FormatType() { -} - -Clipboard::FormatType::FormatType(const std::string& native_format) - : data_(native_format) { -} - -Clipboard::FormatType::~FormatType() { -} - -std::string Clipboard::FormatType::Serialize() const { - return data_; -} - -// static -Clipboard::FormatType Clipboard::FormatType::Deserialize( - const std::string& serialization) { - return FormatType(serialization); -} - -bool Clipboard::FormatType::operator<(const FormatType& other) const { - return data_ < other.data_; -} - -bool Clipboard::FormatType::Equals(const FormatType& other) const { - return data_ == other.data_; -} - -/////////////////////////////////////////////////////////////////////////////// -// ClipboardAuraX11::AuraX11Details - -// Private implementation of our X11 integration. Keeps X11 headers out of the -// majority of chrome, which break badly. -class ClipboardAuraX11::AuraX11Details : public PlatformEventDispatcher { - public: - AuraX11Details(); - virtual ~AuraX11Details(); - - X11AtomCache* atom_cache() { return &atom_cache_; } - - // Returns the X11 type that we pass to various XSelection functions for the - // given type. - ::Atom LookupSelectionForClipboardType(ClipboardType type) const; - - // Returns the X11 type that we pass to various XSelection functions for - // CLIPBOARD_TYPE_COPY_PASTE. - ::Atom GetCopyPasteSelection() const; - - // Finds the SelectionFormatMap for the incoming selection atom. - const SelectionFormatMap& LookupStorageForAtom(::Atom atom); - - // As we need to collect all the data types before we tell X11 that we own a - // particular selection, we create a temporary clipboard mapping that - // InsertMapping writes to. Then we commit it in TakeOwnershipOfSelection, - // where we save it in one of the clipboard data slots. - void CreateNewClipboardData(); - - // Inserts a mapping into clipboard_data_. - void InsertMapping(const std::string& key, - const scoped_refptr<base::RefCountedMemory>& memory); - - // Moves the temporary |clipboard_data_| to the long term data storage for - // |type|. - void TakeOwnershipOfSelection(ClipboardType type); - - // Returns the first of |types| offered by the current selection holder in - // |data_out|, or returns NULL if none of those types are available. - // - // If the selection holder is us, this call is synchronous and we pull - // the data out of |clipboard_selection_| or |primary_selection_|. If the - // selection holder is some other window, we spin up a nested message loop - // and do the asynchronous dance with whatever application is holding the - // selection. - ui::SelectionData RequestAndWaitForTypes(ClipboardType type, - const std::vector< ::Atom>& types); - - // Retrieves the list of possible data types the current clipboard owner has. - // - // If the selection holder is us, this is synchronous, otherwise this runs a - // blocking message loop. - TargetList WaitAndGetTargetsList(ClipboardType type); - - // Returns a list of all text atoms that we handle. - std::vector< ::Atom> GetTextAtoms() const; - - // Returns a vector with a |format| converted to an X11 atom. - std::vector< ::Atom> GetAtomsForFormat(const Clipboard::FormatType& format); - - // Clears a certain clipboard type, whether we own it or not. - void Clear(ClipboardType type); - - // If we own the CLIPBOARD selection, requests the clipboard manager to take - // ownership of it. - void StoreCopyPasteDataAndWait(); - - private: - // PlatformEventDispatcher: - virtual bool CanDispatchEvent(const PlatformEvent& event) override; - virtual uint32_t DispatchEvent(const PlatformEvent& event) override; - - // Our X11 state. - Display* x_display_; - ::Window x_root_window_; - - // Input-only window used as a selection owner. - ::Window x_window_; - - X11AtomCache atom_cache_; - - // Object which requests and receives selection data. - SelectionRequestor selection_requestor_; - - // Temporary target map that we write to during DispatchObects. - SelectionFormatMap clipboard_data_; - - // Objects which offer selection data to other windows. - SelectionOwner clipboard_owner_; - SelectionOwner primary_owner_; - - DISALLOW_COPY_AND_ASSIGN(AuraX11Details); -}; - -ClipboardAuraX11::AuraX11Details::AuraX11Details() - : x_display_(gfx::GetXDisplay()), - x_root_window_(DefaultRootWindow(x_display_)), - x_window_(XCreateWindow(x_display_, - x_root_window_, - -100, - -100, - 10, - 10, // x, y, width, height - 0, // border width - CopyFromParent, // depth - InputOnly, - CopyFromParent, // visual - 0, - NULL)), - atom_cache_(x_display_, kAtomsToCache), - selection_requestor_(x_display_, x_window_, this), - clipboard_owner_(x_display_, x_window_, atom_cache_.GetAtom(kClipboard)), - primary_owner_(x_display_, x_window_, XA_PRIMARY) { - // We don't know all possible MIME types at compile time. - atom_cache_.allow_uncached_atoms(); - - XStoreName(x_display_, x_window_, "Chromium clipboard"); - XSelectInput(x_display_, x_window_, PropertyChangeMask); - - if (PlatformEventSource::GetInstance()) - PlatformEventSource::GetInstance()->AddPlatformEventDispatcher(this); -} - -ClipboardAuraX11::AuraX11Details::~AuraX11Details() { - if (PlatformEventSource::GetInstance()) - PlatformEventSource::GetInstance()->RemovePlatformEventDispatcher(this); - - XDestroyWindow(x_display_, x_window_); -} - -::Atom ClipboardAuraX11::AuraX11Details::LookupSelectionForClipboardType( - ClipboardType type) const { - if (type == CLIPBOARD_TYPE_COPY_PASTE) - return GetCopyPasteSelection(); - - return XA_PRIMARY; -} - -::Atom ClipboardAuraX11::AuraX11Details::GetCopyPasteSelection() const { - return atom_cache_.GetAtom(kClipboard); -} - -const SelectionFormatMap& -ClipboardAuraX11::AuraX11Details::LookupStorageForAtom(::Atom atom) { - if (atom == XA_PRIMARY) - return primary_owner_.selection_format_map(); - - DCHECK_EQ(GetCopyPasteSelection(), atom); - return clipboard_owner_.selection_format_map(); -} - -void ClipboardAuraX11::AuraX11Details::CreateNewClipboardData() { - clipboard_data_ = SelectionFormatMap(); -} - -void ClipboardAuraX11::AuraX11Details::InsertMapping( - const std::string& key, - const scoped_refptr<base::RefCountedMemory>& memory) { - ::Atom atom_key = atom_cache_.GetAtom(key.c_str()); - clipboard_data_.Insert(atom_key, memory); -} - -void ClipboardAuraX11::AuraX11Details::TakeOwnershipOfSelection( - ClipboardType type) { - if (type == CLIPBOARD_TYPE_COPY_PASTE) - return clipboard_owner_.TakeOwnershipOfSelection(clipboard_data_); - else - return primary_owner_.TakeOwnershipOfSelection(clipboard_data_); -} - -SelectionData ClipboardAuraX11::AuraX11Details::RequestAndWaitForTypes( - ClipboardType type, - const std::vector<::Atom>& types) { - ::Atom selection_name = LookupSelectionForClipboardType(type); - if (XGetSelectionOwner(x_display_, selection_name) == x_window_) { - // We can local fastpath instead of playing the nested message loop game - // with the X server. - const SelectionFormatMap& format_map = LookupStorageForAtom(selection_name); - - for (std::vector< ::Atom>::const_iterator it = types.begin(); - it != types.end(); ++it) { - SelectionFormatMap::const_iterator format_map_it = format_map.find(*it); - if (format_map_it != format_map.end()) - return SelectionData(format_map_it->first, format_map_it->second); - } - } else { - TargetList targets = WaitAndGetTargetsList(type); - - ::Atom selection_name = LookupSelectionForClipboardType(type); - std::vector< ::Atom> intersection; - ui::GetAtomIntersection(types, targets.target_list(), &intersection); - return selection_requestor_.RequestAndWaitForTypes(selection_name, - intersection); - } - - return SelectionData(); -} - -TargetList ClipboardAuraX11::AuraX11Details::WaitAndGetTargetsList( - ClipboardType type) { - ::Atom selection_name = LookupSelectionForClipboardType(type); - std::vector< ::Atom> out; - if (XGetSelectionOwner(x_display_, selection_name) == x_window_) { - // We can local fastpath and return the list of local targets. - const SelectionFormatMap& format_map = LookupStorageForAtom(selection_name); - - for (SelectionFormatMap::const_iterator it = format_map.begin(); - it != format_map.end(); ++it) { - out.push_back(it->first); - } - } else { - scoped_refptr<base::RefCountedMemory> data; - size_t out_data_items = 0; - ::Atom out_type = None; - - if (selection_requestor_.PerformBlockingConvertSelection( - selection_name, - atom_cache_.GetAtom(kTargets), - &data, - &out_data_items, - &out_type)) { - // Some apps return an |out_type| of "TARGETS". (crbug.com/377893) - if (out_type == XA_ATOM || out_type == atom_cache_.GetAtom(kTargets)) { - const ::Atom* atom_array = - reinterpret_cast<const ::Atom*>(data->front()); - for (size_t i = 0; i < out_data_items; ++i) - out.push_back(atom_array[i]); - } - } else { - // There was no target list. Most Java apps doesn't offer a TARGETS list, - // even though they AWT to. They will offer individual text types if you - // ask. If this is the case we attempt to make sense of the contents as - // text. This is pretty unfortunate since it means we have to actually - // copy the data to see if it is available, but at least this path - // shouldn't be hit for conforming programs. - std::vector< ::Atom> types = GetTextAtoms(); - for (std::vector< ::Atom>::const_iterator it = types.begin(); - it != types.end(); ++it) { - ::Atom type = None; - if (selection_requestor_.PerformBlockingConvertSelection(selection_name, - *it, - NULL, - NULL, - &type) && - type == *it) { - out.push_back(*it); - } - } - } - } - - return TargetList(out, &atom_cache_); -} - -std::vector<::Atom> ClipboardAuraX11::AuraX11Details::GetTextAtoms() const { - return GetTextAtomsFrom(&atom_cache_); -} - -std::vector<::Atom> ClipboardAuraX11::AuraX11Details::GetAtomsForFormat( - const Clipboard::FormatType& format) { - std::vector< ::Atom> atoms; - atoms.push_back(atom_cache_.GetAtom(format.ToString().c_str())); - return atoms; -} - -void ClipboardAuraX11::AuraX11Details::Clear(ClipboardType type) { - if (type == CLIPBOARD_TYPE_COPY_PASTE) - clipboard_owner_.ClearSelectionOwner(); - else - primary_owner_.ClearSelectionOwner(); -} - -void ClipboardAuraX11::AuraX11Details::StoreCopyPasteDataAndWait() { - ::Atom selection = GetCopyPasteSelection(); - if (XGetSelectionOwner(x_display_, selection) != x_window_) - return; - - ::Atom clipboard_manager_atom = atom_cache_.GetAtom(kClipboardManager); - if (XGetSelectionOwner(x_display_, clipboard_manager_atom) == None) - return; - - const SelectionFormatMap& format_map = LookupStorageForAtom(selection); - if (format_map.size() == 0) - return; - std::vector<Atom> targets = format_map.GetTypes(); - - base::TimeTicks start = base::TimeTicks::Now(); - selection_requestor_.PerformBlockingConvertSelectionWithParameter( - atom_cache_.GetAtom(kClipboardManager), - atom_cache_.GetAtom(kSaveTargets), - targets); - UMA_HISTOGRAM_TIMES("Clipboard.X11StoreCopyPasteDuration", - base::TimeTicks::Now() - start); -} - -bool ClipboardAuraX11::AuraX11Details::CanDispatchEvent( - const PlatformEvent& event) { - if (event->xany.window == x_window_) - return true; - - if (event->type == PropertyNotify) { - return primary_owner_.CanDispatchPropertyEvent(*event) || - clipboard_owner_.CanDispatchPropertyEvent(*event) || - selection_requestor_.CanDispatchPropertyEvent(*event); - } - return false; -} - -uint32_t ClipboardAuraX11::AuraX11Details::DispatchEvent( - const PlatformEvent& xev) { - switch (xev->type) { - case SelectionRequest: { - if (xev->xselectionrequest.selection == XA_PRIMARY) { - primary_owner_.OnSelectionRequest(*xev); - } else { - // We should not get requests for the CLIPBOARD_MANAGER selection - // because we never take ownership of it. - DCHECK_EQ(GetCopyPasteSelection(), xev->xselectionrequest.selection); - clipboard_owner_.OnSelectionRequest(*xev); - } - break; - } - case SelectionNotify: { - selection_requestor_.OnSelectionNotify(*xev); - break; - } - case SelectionClear: { - if (xev->xselectionclear.selection == XA_PRIMARY) { - primary_owner_.OnSelectionClear(*xev); - } else { - // We should not get requests for the CLIPBOARD_MANAGER selection - // because we never take ownership of it. - DCHECK_EQ(GetCopyPasteSelection(), xev->xselection.selection); - clipboard_owner_.OnSelectionClear(*xev); - } - break; - } - case PropertyNotify: { - if (primary_owner_.CanDispatchPropertyEvent(*xev)) - primary_owner_.OnPropertyEvent(*xev); - if (clipboard_owner_.CanDispatchPropertyEvent(*xev)) - clipboard_owner_.OnPropertyEvent(*xev); - if (selection_requestor_.CanDispatchPropertyEvent(*xev)) - selection_requestor_.OnPropertyEvent(*xev); - break; - } - default: - break; - } - - return POST_DISPATCH_NONE; -} - -/////////////////////////////////////////////////////////////////////////////// -// Various predefined FormatTypes. -// static -Clipboard::FormatType Clipboard::GetFormatType( - const std::string& format_string) { - return FormatType::Deserialize(format_string); -} - -// static -const Clipboard::FormatType& Clipboard::GetUrlFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeURIList)); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetUrlWFormatType() { - return GetUrlFormatType(); -} - -// static -const Clipboard::FormatType& Clipboard::GetPlainTextFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeText)); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetPlainTextWFormatType() { - return GetPlainTextFormatType(); -} - -// static -const Clipboard::FormatType& Clipboard::GetFilenameFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeFilename)); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetFilenameWFormatType() { - return Clipboard::GetFilenameFormatType(); -} - -// static -const Clipboard::FormatType& Clipboard::GetHtmlFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeHTML)); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetRtfFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeRTF)); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetBitmapFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypePNG)); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetWebKitSmartPasteFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeWebkitSmartPaste)); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetWebCustomDataFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypeWebCustomData)); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetPepperCustomDataFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (kMimeTypePepperCustomData)); - return type; -} - -/////////////////////////////////////////////////////////////////////////////// -// Clipboard factory method. -Clipboard* Clipboard::Create() { - return new ClipboardAuraX11; -} - -/////////////////////////////////////////////////////////////////////////////// -// ClipboardAuraX11 - -ClipboardAuraX11::ClipboardAuraX11() : aurax11_details_(new AuraX11Details) { - DCHECK(CalledOnValidThread()); -} - -ClipboardAuraX11::~ClipboardAuraX11() { - DCHECK(CalledOnValidThread()); - - aurax11_details_->StoreCopyPasteDataAndWait(); -} - -uint64 ClipboardAuraX11::GetSequenceNumber(ClipboardType type) { - DCHECK(CalledOnValidThread()); - if (type == CLIPBOARD_TYPE_COPY_PASTE) - return SelectionChangeObserver::GetInstance()->clipboard_sequence_number(); - else - return SelectionChangeObserver::GetInstance()->primary_sequence_number(); -} - -bool ClipboardAuraX11::IsFormatAvailable(const FormatType& format, - ClipboardType type) const { - DCHECK(CalledOnValidThread()); - DCHECK(IsSupportedClipboardType(type)); - - TargetList target_list = aurax11_details_->WaitAndGetTargetsList(type); - if (format.Equals(GetPlainTextFormatType()) || - format.Equals(GetUrlFormatType())) { - return target_list.ContainsText(); - } - return target_list.ContainsFormat(format); -} - -void ClipboardAuraX11::Clear(ClipboardType type) { - DCHECK(CalledOnValidThread()); - DCHECK(IsSupportedClipboardType(type)); - aurax11_details_->Clear(type); -} - -void ClipboardAuraX11::ReadAvailableTypes(ClipboardType type, - std::vector<base::string16>* types, - bool* contains_filenames) const { - DCHECK(CalledOnValidThread()); - if (!types || !contains_filenames) { - NOTREACHED(); - return; - } - - TargetList target_list = aurax11_details_->WaitAndGetTargetsList(type); - - types->clear(); - - if (target_list.ContainsText()) - types->push_back(base::UTF8ToUTF16(kMimeTypeText)); - if (target_list.ContainsFormat(GetHtmlFormatType())) - types->push_back(base::UTF8ToUTF16(kMimeTypeHTML)); - if (target_list.ContainsFormat(GetRtfFormatType())) - types->push_back(base::UTF8ToUTF16(kMimeTypeRTF)); - if (target_list.ContainsFormat(GetBitmapFormatType())) - types->push_back(base::UTF8ToUTF16(kMimeTypePNG)); - *contains_filenames = false; - - SelectionData data(aurax11_details_->RequestAndWaitForTypes( - type, aurax11_details_->GetAtomsForFormat(GetWebCustomDataFormatType()))); - if (data.IsValid()) - ReadCustomDataTypes(data.GetData(), data.GetSize(), types); -} - -void ClipboardAuraX11::ReadText(ClipboardType type, - base::string16* result) const { - DCHECK(CalledOnValidThread()); - - SelectionData data(aurax11_details_->RequestAndWaitForTypes( - type, aurax11_details_->GetTextAtoms())); - if (data.IsValid()) { - std::string text = data.GetText(); - *result = base::UTF8ToUTF16(text); - } -} - -void ClipboardAuraX11::ReadAsciiText(ClipboardType type, - std::string* result) const { - DCHECK(CalledOnValidThread()); - - SelectionData data(aurax11_details_->RequestAndWaitForTypes( - type, aurax11_details_->GetTextAtoms())); - if (data.IsValid()) - result->assign(data.GetText()); -} - -// TODO(estade): handle different charsets. -// TODO(port): set *src_url. -void ClipboardAuraX11::ReadHTML(ClipboardType type, - base::string16* markup, - std::string* src_url, - uint32* fragment_start, - uint32* fragment_end) const { - DCHECK(CalledOnValidThread()); - markup->clear(); - if (src_url) - src_url->clear(); - *fragment_start = 0; - *fragment_end = 0; - - SelectionData data(aurax11_details_->RequestAndWaitForTypes( - type, aurax11_details_->GetAtomsForFormat(GetHtmlFormatType()))); - if (data.IsValid()) { - *markup = data.GetHtml(); - - *fragment_start = 0; - DCHECK(markup->length() <= kuint32max); - *fragment_end = static_cast<uint32>(markup->length()); - } -} - -void ClipboardAuraX11::ReadRTF(ClipboardType type, std::string* result) const { - DCHECK(CalledOnValidThread()); - - SelectionData data(aurax11_details_->RequestAndWaitForTypes( - type, aurax11_details_->GetAtomsForFormat(GetRtfFormatType()))); - if (data.IsValid()) - data.AssignTo(result); -} - -SkBitmap ClipboardAuraX11::ReadImage(ClipboardType type) const { - DCHECK(CalledOnValidThread()); - - SelectionData data(aurax11_details_->RequestAndWaitForTypes( - type, aurax11_details_->GetAtomsForFormat(GetBitmapFormatType()))); - if (data.IsValid()) { - SkBitmap bitmap; - if (gfx::PNGCodec::Decode(data.GetData(), data.GetSize(), &bitmap)) - return SkBitmap(bitmap); - } - - return SkBitmap(); -} - -void ClipboardAuraX11::ReadCustomData(ClipboardType clipboard_type, - const base::string16& type, - base::string16* result) const { - DCHECK(CalledOnValidThread()); - - SelectionData data(aurax11_details_->RequestAndWaitForTypes( - clipboard_type, - aurax11_details_->GetAtomsForFormat(GetWebCustomDataFormatType()))); - if (data.IsValid()) - ReadCustomDataForType(data.GetData(), data.GetSize(), type, result); -} - -void ClipboardAuraX11::ReadBookmark(base::string16* title, - std::string* url) const { - DCHECK(CalledOnValidThread()); - // TODO(erg): This was left NOTIMPLEMENTED() in the gtk port too. - NOTIMPLEMENTED(); -} - -void ClipboardAuraX11::ReadData(const FormatType& format, - std::string* result) const { - DCHECK(CalledOnValidThread()); - - SelectionData data(aurax11_details_->RequestAndWaitForTypes( - CLIPBOARD_TYPE_COPY_PASTE, aurax11_details_->GetAtomsForFormat(format))); - if (data.IsValid()) - data.AssignTo(result); -} - -void ClipboardAuraX11::WriteObjects(ClipboardType type, - const ObjectMap& objects) { - DCHECK(CalledOnValidThread()); - DCHECK(IsSupportedClipboardType(type)); - - aurax11_details_->CreateNewClipboardData(); - for (ObjectMap::const_iterator iter = objects.begin(); iter != objects.end(); - ++iter) { - DispatchObject(static_cast<ObjectType>(iter->first), iter->second); - } - aurax11_details_->TakeOwnershipOfSelection(type); - - if (type == CLIPBOARD_TYPE_COPY_PASTE) { - ObjectMap::const_iterator text_iter = objects.find(CBF_TEXT); - if (text_iter != objects.end()) { - aurax11_details_->CreateNewClipboardData(); - const ObjectMapParams& params_vector = text_iter->second; - if (params_vector.size()) { - const ObjectMapParam& char_vector = params_vector[0]; - if (char_vector.size()) - WriteText(&char_vector.front(), char_vector.size()); - } - aurax11_details_->TakeOwnershipOfSelection(CLIPBOARD_TYPE_SELECTION); - } - } -} - -void ClipboardAuraX11::WriteText(const char* text_data, size_t text_len) { - std::string str(text_data, text_len); - scoped_refptr<base::RefCountedMemory> mem( - base::RefCountedString::TakeString(&str)); - - aurax11_details_->InsertMapping(kMimeTypeText, mem); - aurax11_details_->InsertMapping(kText, mem); - aurax11_details_->InsertMapping(kString, mem); - aurax11_details_->InsertMapping(kUtf8String, mem); -} - -void ClipboardAuraX11::WriteHTML(const char* markup_data, - size_t markup_len, - const char* url_data, - size_t url_len) { - // TODO(estade): We need to expand relative links with |url_data|. - static const char* html_prefix = "<meta http-equiv=\"content-type\" " - "content=\"text/html; charset=utf-8\">"; - std::string data = html_prefix; - data += std::string(markup_data, markup_len); - // Some programs expect NULL-terminated data. See http://crbug.com/42624 - data += '\0'; - - scoped_refptr<base::RefCountedMemory> mem( - base::RefCountedString::TakeString(&data)); - aurax11_details_->InsertMapping(kMimeTypeHTML, mem); -} - -void ClipboardAuraX11::WriteRTF(const char* rtf_data, size_t data_len) { - WriteData(GetRtfFormatType(), rtf_data, data_len); -} - -void ClipboardAuraX11::WriteBookmark(const char* title_data, - size_t title_len, - const char* url_data, - size_t url_len) { - // Write as a mozilla url (UTF16: URL, newline, title). - base::string16 url = base::UTF8ToUTF16(std::string(url_data, url_len) + "\n"); - base::string16 title = base::UTF8ToUTF16(std::string(title_data, title_len)); - - std::vector<unsigned char> data; - ui::AddString16ToVector(url, &data); - ui::AddString16ToVector(title, &data); - scoped_refptr<base::RefCountedMemory> mem( - base::RefCountedBytes::TakeVector(&data)); - - aurax11_details_->InsertMapping(kMimeTypeMozillaURL, mem); -} - -// Write an extra flavor that signifies WebKit was the last to modify the -// pasteboard. This flavor has no data. -void ClipboardAuraX11::WriteWebSmartPaste() { - std::string empty; - aurax11_details_->InsertMapping( - kMimeTypeWebkitSmartPaste, - scoped_refptr<base::RefCountedMemory>( - base::RefCountedString::TakeString(&empty))); -} - -void ClipboardAuraX11::WriteBitmap(const SkBitmap& bitmap) { - // Encode the bitmap as a PNG for transport. - std::vector<unsigned char> output; - if (gfx::PNGCodec::FastEncodeBGRASkBitmap(bitmap, false, &output)) { - aurax11_details_->InsertMapping(kMimeTypePNG, - base::RefCountedBytes::TakeVector( - &output)); - } -} - -void ClipboardAuraX11::WriteData(const FormatType& format, - const char* data_data, - size_t data_len) { - // We assume that certain mapping types are only written by trusted code. - // Therefore we must upkeep their integrity. - if (format.Equals(GetBitmapFormatType())) - return; - - std::vector<unsigned char> bytes(data_data, data_data + data_len); - scoped_refptr<base::RefCountedMemory> mem( - base::RefCountedBytes::TakeVector(&bytes)); - aurax11_details_->InsertMapping(format.ToString(), mem); -} - -} // namespace ui
diff --git a/ui/base/clipboard/clipboard_aurax11.h b/ui/base/clipboard/clipboard_aurax11.h deleted file mode 100644 index fa734c0..0000000 --- a/ui/base/clipboard/clipboard_aurax11.h +++ /dev/null
@@ -1,70 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_CLIPBOARD_CLIPBOARD_AURAX11_H_ -#define UI_BASE_CLIPBOARD_CLIPBOARD_AURAX11_H_ - -#include "ui/base/clipboard/clipboard.h" - -#include "base/memory/scoped_ptr.h" - -namespace ui { - -class ClipboardAuraX11 : public Clipboard { - private: - friend class Clipboard; - - ClipboardAuraX11(); - ~ClipboardAuraX11() override; - - // Clipboard overrides: - uint64 GetSequenceNumber(ClipboardType type) override; - bool IsFormatAvailable(const FormatType& format, - ClipboardType type) const override; - void Clear(ClipboardType type) override; - void ReadAvailableTypes(ClipboardType type, - std::vector<base::string16>* types, - bool* contains_filenames) const override; - void ReadText(ClipboardType type, base::string16* result) const override; - void ReadAsciiText(ClipboardType type, std::string* result) const override; - void ReadHTML(ClipboardType type, - base::string16* markup, - std::string* src_url, - uint32* fragment_start, - uint32* fragment_end) const override; - void ReadRTF(ClipboardType type, std::string* result) const override; - SkBitmap ReadImage(ClipboardType type) const override; - void ReadCustomData(ClipboardType clipboard_type, - const base::string16& type, - base::string16* result) const override; - void ReadBookmark(base::string16* title, std::string* url) const override; - void ReadData(const FormatType& format, std::string* result) const override; - void WriteObjects(ClipboardType type, const ObjectMap& objects) override; - void WriteText(const char* text_data, size_t text_len) override; - void WriteHTML(const char* markup_data, - size_t markup_len, - const char* url_data, - size_t url_len) override; - void WriteRTF(const char* rtf_data, size_t data_len) override; - void WriteBookmark(const char* title_data, - size_t title_len, - const char* url_data, - size_t url_len) override; - void WriteWebSmartPaste() override; - void WriteBitmap(const SkBitmap& bitmap) override; - void WriteData(const FormatType& format, - const char* data_data, - size_t data_len) override; - - // TODO(dcheng): Is this still needed now that each platform clipboard has its - // own class derived from Clipboard? - class AuraX11Details; - scoped_ptr<AuraX11Details> aurax11_details_; - - DISALLOW_COPY_AND_ASSIGN(ClipboardAuraX11); -}; - -} // namespace ui - -#endif // UI_BASE_CLIPBOARD_CLIPBOARD_AURAX11_H_
diff --git a/ui/base/clipboard/clipboard_constants.cc b/ui/base/clipboard/clipboard_constants.cc deleted file mode 100644 index 2d499dc..0000000 --- a/ui/base/clipboard/clipboard_constants.cc +++ /dev/null
@@ -1,16 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/clipboard/clipboard.h" - -namespace ui { - -const char Clipboard::kMimeTypeText[] = "text/plain"; -const char Clipboard::kMimeTypeURIList[] = "text/uri-list"; -const char Clipboard::kMimeTypeDownloadURL[] = "downloadurl"; -const char Clipboard::kMimeTypeHTML[] = "text/html"; -const char Clipboard::kMimeTypeRTF[] = "text/rtf"; -const char Clipboard::kMimeTypePNG[] = "image/png"; - -} // namespace ui
diff --git a/ui/base/clipboard/clipboard_mac.h b/ui/base/clipboard/clipboard_mac.h deleted file mode 100644 index 203c374..0000000 --- a/ui/base/clipboard/clipboard_mac.h +++ /dev/null
@@ -1,63 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_CLIPBOARD_CLIPBOARD_MAC_H_ -#define UI_BASE_CLIPBOARD_CLIPBOARD_MAC_H_ - -#include "ui/base/clipboard/clipboard.h" - -namespace ui { - -class ClipboardMac : public Clipboard { - private: - friend class Clipboard; - - ClipboardMac(); - ~ClipboardMac() override; - - // Clipboard overrides: - uint64 GetSequenceNumber(ClipboardType type) override; - bool IsFormatAvailable(const FormatType& format, - ClipboardType type) const override; - void Clear(ClipboardType type) override; - void ReadAvailableTypes(ClipboardType type, - std::vector<base::string16>* types, - bool* contains_filenames) const override; - void ReadText(ClipboardType type, base::string16* result) const override; - void ReadAsciiText(ClipboardType type, std::string* result) const override; - void ReadHTML(ClipboardType type, - base::string16* markup, - std::string* src_url, - uint32* fragment_start, - uint32* fragment_end) const override; - void ReadRTF(ClipboardType type, std::string* result) const override; - SkBitmap ReadImage(ClipboardType type) const override; - void ReadCustomData(ClipboardType clipboard_type, - const base::string16& type, - base::string16* result) const override; - void ReadBookmark(base::string16* title, std::string* url) const override; - void ReadData(const FormatType& format, std::string* result) const override; - void WriteObjects(ClipboardType type, const ObjectMap& objects) override; - void WriteText(const char* text_data, size_t text_len) override; - void WriteHTML(const char* markup_data, - size_t markup_len, - const char* url_data, - size_t url_len) override; - void WriteRTF(const char* rtf_data, size_t data_len) override; - void WriteBookmark(const char* title_data, - size_t title_len, - const char* url_data, - size_t url_len) override; - void WriteWebSmartPaste() override; - void WriteBitmap(const SkBitmap& bitmap) override; - void WriteData(const FormatType& format, - const char* data_data, - size_t data_len) override; - - DISALLOW_COPY_AND_ASSIGN(ClipboardMac); -}; - -} // namespace ui - -#endif // UI_BASE_CLIPBOARD_CLIPBOARD_MAC_H_
diff --git a/ui/base/clipboard/clipboard_mac.mm b/ui/base/clipboard/clipboard_mac.mm deleted file mode 100644 index 63c1edf..0000000 --- a/ui/base/clipboard/clipboard_mac.mm +++ /dev/null
@@ -1,453 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/clipboard/clipboard_mac.h" - -#import <Cocoa/Cocoa.h> - -#include "base/basictypes.h" -#include "base/files/file_path.h" -#include "base/logging.h" -#include "base/mac/mac_util.h" -#include "base/mac/scoped_cftyperef.h" -#import "base/mac/scoped_nsexception_enabler.h" -#include "base/mac/scoped_nsobject.h" -#include "base/stl_util.h" -#include "base/strings/sys_string_conversions.h" -#include "base/strings/utf_string_conversions.h" -#include "skia/ext/skia_utils_mac.h" -#import "third_party/mozilla/NSPasteboard+Utils.h" -#include "third_party/skia/include/core/SkBitmap.h" -#include "ui/base/clipboard/custom_data_helper.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/scoped_ns_graphics_context_save_gstate_mac.h" -#include "ui/gfx/size.h" - -namespace ui { - -namespace { - -// Would be nice if this were in UTCoreTypes.h, but it isn't -NSString* const kUTTypeURLName = @"public.url-name"; - -// Tells us if WebKit was the last to write to the pasteboard. There's no -// actual data associated with this type. -NSString* const kWebSmartPastePboardType = @"NeXT smart paste pasteboard type"; - -// Pepper custom data format type. -NSString* const kPepperCustomDataPboardType = - @"org.chromium.pepper-custom-data"; - -NSPasteboard* GetPasteboard() { - // The pasteboard should not be nil in a UI session, but this handy DCHECK - // can help track down problems if someone tries using clipboard code outside - // of a UI session. - NSPasteboard* pasteboard = [NSPasteboard generalPasteboard]; - DCHECK(pasteboard); - return pasteboard; -} - -} // namespace - -// Clipboard::FormatType implementation. -Clipboard::FormatType::FormatType() : data_(nil) { -} - -Clipboard::FormatType::FormatType(NSString* native_format) - : data_([native_format retain]) { -} - -Clipboard::FormatType::FormatType(const FormatType& other) - : data_([other.data_ retain]) { -} - -Clipboard::FormatType& Clipboard::FormatType::operator=( - const FormatType& other) { - if (this != &other) { - [data_ release]; - data_ = [other.data_ retain]; - } - return *this; -} - -bool Clipboard::FormatType::Equals(const FormatType& other) const { - return [data_ isEqualToString:other.data_]; -} - -Clipboard::FormatType::~FormatType() { - [data_ release]; -} - -std::string Clipboard::FormatType::Serialize() const { - return base::SysNSStringToUTF8(data_); -} - -// static -Clipboard::FormatType Clipboard::FormatType::Deserialize( - const std::string& serialization) { - return FormatType(base::SysUTF8ToNSString(serialization)); -} - -// Various predefined FormatTypes. -// static -Clipboard::FormatType Clipboard::GetFormatType( - const std::string& format_string) { - return FormatType::Deserialize(format_string); -} - -// static -const Clipboard::FormatType& Clipboard::GetUrlFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (NSURLPboardType)); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetUrlWFormatType() { - return GetUrlFormatType(); -} - -// static -const Clipboard::FormatType& Clipboard::GetPlainTextFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (NSStringPboardType)); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetPlainTextWFormatType() { - return GetPlainTextFormatType(); -} - -// static -const Clipboard::FormatType& Clipboard::GetFilenameFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (NSFilenamesPboardType)); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetFilenameWFormatType() { - return GetFilenameFormatType(); -} - -// static -const Clipboard::FormatType& Clipboard::GetHtmlFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (NSHTMLPboardType)); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetRtfFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (NSRTFPboardType)); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetBitmapFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (NSTIFFPboardType)); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetWebKitSmartPasteFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (kWebSmartPastePboardType)); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetWebCustomDataFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (kWebCustomDataPboardType)); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetPepperCustomDataFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (kPepperCustomDataPboardType)); - return type; -} - -// Clipboard factory method. -// static -Clipboard* Clipboard::Create() { - return new ClipboardMac; -} - -// ClipboardMac implementation. -ClipboardMac::ClipboardMac() { - DCHECK(CalledOnValidThread()); -} - -ClipboardMac::~ClipboardMac() { - DCHECK(CalledOnValidThread()); -} - -uint64 ClipboardMac::GetSequenceNumber(ClipboardType type) { - DCHECK(CalledOnValidThread()); - DCHECK_EQ(type, CLIPBOARD_TYPE_COPY_PASTE); - - NSPasteboard* pb = GetPasteboard(); - return [pb changeCount]; -} - -bool ClipboardMac::IsFormatAvailable(const FormatType& format, - ClipboardType type) const { - DCHECK(CalledOnValidThread()); - DCHECK_EQ(type, CLIPBOARD_TYPE_COPY_PASTE); - - NSPasteboard* pb = GetPasteboard(); - NSArray* types = [pb types]; - - // Safari only places RTF on the pasteboard, never HTML. We can convert RTF - // to HTML, so the presence of either indicates success when looking for HTML. - if ([format.ToNSString() isEqualToString:NSHTMLPboardType]) { - return [types containsObject:NSHTMLPboardType] || - [types containsObject:NSRTFPboardType]; - } - return [types containsObject:format.ToNSString()]; -} - -void ClipboardMac::Clear(ClipboardType type) { - DCHECK(CalledOnValidThread()); - DCHECK_EQ(type, CLIPBOARD_TYPE_COPY_PASTE); - - NSPasteboard* pb = GetPasteboard(); - [pb declareTypes:[NSArray array] owner:nil]; -} - -void ClipboardMac::ReadAvailableTypes(ClipboardType type, - std::vector<base::string16>* types, - bool* contains_filenames) const { - DCHECK(CalledOnValidThread()); - types->clear(); - if (IsFormatAvailable(Clipboard::GetPlainTextFormatType(), type)) - types->push_back(base::UTF8ToUTF16(kMimeTypeText)); - if (IsFormatAvailable(Clipboard::GetHtmlFormatType(), type)) - types->push_back(base::UTF8ToUTF16(kMimeTypeHTML)); - if (IsFormatAvailable(Clipboard::GetRtfFormatType(), type)) - types->push_back(base::UTF8ToUTF16(kMimeTypeRTF)); - if ([NSImage canInitWithPasteboard:GetPasteboard()]) - types->push_back(base::UTF8ToUTF16(kMimeTypePNG)); - *contains_filenames = false; - - NSPasteboard* pb = GetPasteboard(); - if ([[pb types] containsObject:kWebCustomDataPboardType]) { - NSData* data = [pb dataForType:kWebCustomDataPboardType]; - if ([data length]) - ReadCustomDataTypes([data bytes], [data length], types); - } -} - -void ClipboardMac::ReadText(ClipboardType type, base::string16* result) const { - DCHECK(CalledOnValidThread()); - DCHECK_EQ(type, CLIPBOARD_TYPE_COPY_PASTE); - NSPasteboard* pb = GetPasteboard(); - NSString* contents = [pb stringForType:NSStringPboardType]; - - *result = base::SysNSStringToUTF16(contents); -} - -void ClipboardMac::ReadAsciiText(ClipboardType type, - std::string* result) const { - DCHECK(CalledOnValidThread()); - DCHECK_EQ(type, CLIPBOARD_TYPE_COPY_PASTE); - NSPasteboard* pb = GetPasteboard(); - NSString* contents = [pb stringForType:NSStringPboardType]; - - if (!contents) - result->clear(); - else - result->assign([contents UTF8String]); -} - -void ClipboardMac::ReadHTML(ClipboardType type, - base::string16* markup, - std::string* src_url, - uint32* fragment_start, - uint32* fragment_end) const { - DCHECK(CalledOnValidThread()); - DCHECK_EQ(type, CLIPBOARD_TYPE_COPY_PASTE); - - // TODO(avi): src_url? - markup->clear(); - if (src_url) - src_url->clear(); - - NSPasteboard* pb = GetPasteboard(); - NSArray* supportedTypes = [NSArray arrayWithObjects:NSHTMLPboardType, - NSRTFPboardType, - NSStringPboardType, - nil]; - NSString* bestType = [pb availableTypeFromArray:supportedTypes]; - if (bestType) { - NSString* contents = [pb stringForType:bestType]; - if ([bestType isEqualToString:NSRTFPboardType]) - contents = [pb htmlFromRtf]; - *markup = base::SysNSStringToUTF16(contents); - } - - *fragment_start = 0; - DCHECK(markup->length() <= kuint32max); - *fragment_end = static_cast<uint32>(markup->length()); -} - -void ClipboardMac::ReadRTF(ClipboardType type, std::string* result) const { - DCHECK(CalledOnValidThread()); - DCHECK_EQ(type, CLIPBOARD_TYPE_COPY_PASTE); - - return ReadData(GetRtfFormatType(), result); -} - -SkBitmap ClipboardMac::ReadImage(ClipboardType type) const { - DCHECK(CalledOnValidThread()); - DCHECK_EQ(type, CLIPBOARD_TYPE_COPY_PASTE); - - // If the pasteboard's image data is not to its liking, the guts of NSImage - // may throw, and that exception will leak. Prevent a crash in that case; - // a blank image is better. - base::scoped_nsobject<NSImage> image(base::mac::RunBlockIgnoringExceptions(^{ - return [[NSImage alloc] initWithPasteboard:GetPasteboard()]; - })); - SkBitmap bitmap; - if (image.get()) { - bitmap = gfx::NSImageToSkBitmapWithColorSpace( - image.get(), /*is_opaque=*/ false, base::mac::GetSystemColorSpace()); - } - return bitmap; -} - -void ClipboardMac::ReadCustomData(ClipboardType clipboard_type, - const base::string16& type, - base::string16* result) const { - DCHECK(CalledOnValidThread()); - DCHECK_EQ(clipboard_type, CLIPBOARD_TYPE_COPY_PASTE); - - NSPasteboard* pb = GetPasteboard(); - if ([[pb types] containsObject:kWebCustomDataPboardType]) { - NSData* data = [pb dataForType:kWebCustomDataPboardType]; - if ([data length]) - ReadCustomDataForType([data bytes], [data length], type, result); - } -} - -void ClipboardMac::ReadBookmark(base::string16* title, std::string* url) const { - DCHECK(CalledOnValidThread()); - NSPasteboard* pb = GetPasteboard(); - - if (title) { - NSString* contents = [pb stringForType:kUTTypeURLName]; - *title = base::SysNSStringToUTF16(contents); - } - - if (url) { - NSString* url_string = [[NSURL URLFromPasteboard:pb] absoluteString]; - if (!url_string) - url->clear(); - else - url->assign([url_string UTF8String]); - } -} - -void ClipboardMac::ReadData(const FormatType& format, - std::string* result) const { - DCHECK(CalledOnValidThread()); - NSPasteboard* pb = GetPasteboard(); - NSData* data = [pb dataForType:format.ToNSString()]; - if ([data length]) - result->assign(static_cast<const char*>([data bytes]), [data length]); -} - -void ClipboardMac::WriteObjects(ClipboardType type, const ObjectMap& objects) { - DCHECK(CalledOnValidThread()); - DCHECK_EQ(type, CLIPBOARD_TYPE_COPY_PASTE); - - NSPasteboard* pb = GetPasteboard(); - [pb declareTypes:[NSArray array] owner:nil]; - - for (ObjectMap::const_iterator iter = objects.begin(); iter != objects.end(); - ++iter) { - DispatchObject(static_cast<ObjectType>(iter->first), iter->second); - } -} - -void ClipboardMac::WriteText(const char* text_data, size_t text_len) { - std::string text_str(text_data, text_len); - NSString* text = base::SysUTF8ToNSString(text_str); - NSPasteboard* pb = GetPasteboard(); - [pb addTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil]; - [pb setString:text forType:NSStringPboardType]; -} - -void ClipboardMac::WriteHTML(const char* markup_data, - size_t markup_len, - const char* url_data, - size_t url_len) { - // We need to mark it as utf-8. (see crbug.com/11957) - std::string html_fragment_str("<meta charset='utf-8'>"); - html_fragment_str.append(markup_data, markup_len); - NSString* html_fragment = base::SysUTF8ToNSString(html_fragment_str); - - // TODO(avi): url_data? - NSPasteboard* pb = GetPasteboard(); - [pb addTypes:[NSArray arrayWithObject:NSHTMLPboardType] owner:nil]; - [pb setString:html_fragment forType:NSHTMLPboardType]; -} - -void ClipboardMac::WriteRTF(const char* rtf_data, size_t data_len) { - WriteData(GetRtfFormatType(), rtf_data, data_len); -} - -void ClipboardMac::WriteBookmark(const char* title_data, - size_t title_len, - const char* url_data, - size_t url_len) { - std::string title_str(title_data, title_len); - NSString* title = base::SysUTF8ToNSString(title_str); - std::string url_str(url_data, url_len); - NSString* url = base::SysUTF8ToNSString(url_str); - - // TODO(playmobil): In the Windows version of this function, an HTML - // representation of the bookmark is also added to the clipboard, to support - // drag and drop of web shortcuts. I don't think we need to do this on the - // Mac, but we should double check later on. - NSURL* nsurl = [NSURL URLWithString:url]; - - NSPasteboard* pb = GetPasteboard(); - // passing UTIs into the pasteboard methods is valid >= 10.5 - [pb addTypes:[NSArray arrayWithObjects:NSURLPboardType, kUTTypeURLName, nil] - owner:nil]; - [nsurl writeToPasteboard:pb]; - [pb setString:title forType:kUTTypeURLName]; -} - -void ClipboardMac::WriteBitmap(const SkBitmap& bitmap) { - NSImage* image = gfx::SkBitmapToNSImageWithColorSpace( - bitmap, base::mac::GetSystemColorSpace()); - // An API to ask the NSImage to write itself to the clipboard comes in 10.6 :( - // For now, spit out the image as a TIFF. - NSPasteboard* pb = GetPasteboard(); - [pb addTypes:[NSArray arrayWithObject:NSTIFFPboardType] owner:nil]; - NSData* tiff_data = [image TIFFRepresentation]; - LOG_IF(ERROR, tiff_data == NULL) << "Failed to allocate image for clipboard"; - if (tiff_data) { - [pb setData:tiff_data forType:NSTIFFPboardType]; - } -} - -void ClipboardMac::WriteData(const FormatType& format, - const char* data_data, - size_t data_len) { - NSPasteboard* pb = GetPasteboard(); - [pb addTypes:[NSArray arrayWithObject:format.ToNSString()] owner:nil]; - [pb setData:[NSData dataWithBytes:data_data length:data_len] - forType:format.ToNSString()]; -} - -// Write an extra flavor that signifies WebKit was the last to modify the -// pasteboard. This flavor has no data. -void ClipboardMac::WriteWebSmartPaste() { - NSPasteboard* pb = GetPasteboard(); - NSString* format = GetWebKitSmartPasteFormatType().ToNSString(); - [pb addTypes:[NSArray arrayWithObject:format] owner:nil]; - [pb setData:nil forType:format]; -} - -} // namespace ui
diff --git a/ui/base/clipboard/clipboard_types.h b/ui/base/clipboard/clipboard_types.h deleted file mode 100644 index 8929d92..0000000 --- a/ui/base/clipboard/clipboard_types.h +++ /dev/null
@@ -1,22 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_CLIPBOARD_CLIPBOARD_TYPES_H_ -#define UI_BASE_CLIPBOARD_CLIPBOARD_TYPES_H_ - -namespace ui { - -// This type designates which clipboard the action should be applied to. -// Only platforms that use the X Window System support the selection buffer. -// Drag type is only supported on Mac OS X. -enum ClipboardType { - CLIPBOARD_TYPE_COPY_PASTE, - CLIPBOARD_TYPE_SELECTION, - CLIPBOARD_TYPE_DRAG, - CLIPBOARD_TYPE_LAST = CLIPBOARD_TYPE_DRAG -}; - -} // namespace ui - -#endif // UI_BASE_CLIPBOARD_CLIPBOARD_TYPES_H_
diff --git a/ui/base/clipboard/clipboard_unittest.cc b/ui/base/clipboard/clipboard_unittest.cc deleted file mode 100644 index 1e05bda..0000000 --- a/ui/base/clipboard/clipboard_unittest.cc +++ /dev/null
@@ -1,800 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "build/build_config.h" - -#include <string> - -#include "base/basictypes.h" -#include "base/memory/scoped_ptr.h" -#include "base/message_loop/message_loop.h" -#include "base/pickle.h" -#include "base/run_loop.h" -#include "base/strings/string_util.h" -#include "base/strings/utf_string_conversions.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "testing/platform_test.h" -#include "third_party/skia/include/core/SkBitmap.h" -#include "third_party/skia/include/core/SkColor.h" -#include "third_party/skia/include/core/SkScalar.h" -#include "third_party/skia/include/core/SkUnPreMultiply.h" -#include "ui/base/clipboard/clipboard.h" -#include "ui/base/clipboard/scoped_clipboard_writer.h" -#include "ui/gfx/size.h" - -#if defined(OS_WIN) -#include "ui/base/clipboard/clipboard_util_win.h" -#endif - -#if defined(OS_ANDROID) -#include "base/android/jni_android.h" -#include "base/android/jni_string.h" -#endif - -#if defined(USE_AURA) -#include "ui/events/platform/platform_event_source.h" -#endif - -using base::ASCIIToUTF16; -using base::UTF8ToUTF16; -using base::UTF16ToUTF8; - -namespace ui { - -class ClipboardTest : public PlatformTest { - public: -#if defined(USE_AURA) - ClipboardTest() : event_source_(ui::PlatformEventSource::CreateDefault()) {} -#else - ClipboardTest() {} -#endif - - virtual ~ClipboardTest() { - ui::Clipboard::DestroyClipboardForCurrentThread(); - } - - static void WriteObjectsToClipboard(ui::Clipboard* clipboard, - const Clipboard::ObjectMap& objects) { - clipboard->WriteObjects(ui::CLIPBOARD_TYPE_COPY_PASTE, objects); - } - - protected: - Clipboard& clipboard() { return *ui::Clipboard::GetForCurrentThread(); } - - void WriteObjectsToClipboard(const Clipboard::ObjectMap& objects) { - WriteObjectsToClipboard(&clipboard(), objects); - } - - private: - base::MessageLoopForUI message_loop_; -#if defined(USE_AURA) - scoped_ptr<PlatformEventSource> event_source_; -#endif -}; - -namespace { - -bool MarkupMatches(const base::string16& expected_markup, - const base::string16& actual_markup) { - return actual_markup.find(expected_markup) != base::string16::npos; -} - -} // namespace - -TEST_F(ClipboardTest, ClearTest) { - { - ScopedClipboardWriter clipboard_writer(CLIPBOARD_TYPE_COPY_PASTE); - clipboard_writer.WriteText(ASCIIToUTF16("clear me")); - } - - clipboard().Clear(CLIPBOARD_TYPE_COPY_PASTE); - - EXPECT_FALSE(clipboard().IsFormatAvailable( - Clipboard::GetPlainTextWFormatType(), CLIPBOARD_TYPE_COPY_PASTE)); - EXPECT_FALSE(clipboard().IsFormatAvailable( - Clipboard::GetPlainTextFormatType(), CLIPBOARD_TYPE_COPY_PASTE)); -} - -TEST_F(ClipboardTest, TextTest) { - base::string16 text(ASCIIToUTF16("This is a base::string16!#$")), text_result; - std::string ascii_text; - - { - ScopedClipboardWriter clipboard_writer(CLIPBOARD_TYPE_COPY_PASTE); - clipboard_writer.WriteText(text); - } - - EXPECT_TRUE(clipboard().IsFormatAvailable( - Clipboard::GetPlainTextWFormatType(), CLIPBOARD_TYPE_COPY_PASTE)); - EXPECT_TRUE(clipboard().IsFormatAvailable(Clipboard::GetPlainTextFormatType(), - CLIPBOARD_TYPE_COPY_PASTE)); - clipboard().ReadText(CLIPBOARD_TYPE_COPY_PASTE, &text_result); - - EXPECT_EQ(text, text_result); - clipboard().ReadAsciiText(CLIPBOARD_TYPE_COPY_PASTE, &ascii_text); - EXPECT_EQ(UTF16ToUTF8(text), ascii_text); -} - -TEST_F(ClipboardTest, HTMLTest) { - base::string16 markup(ASCIIToUTF16("<string>Hi!</string>")), markup_result; - base::string16 plain(ASCIIToUTF16("Hi!")), plain_result; - std::string url("http://www.example.com/"), url_result; - - { - ScopedClipboardWriter clipboard_writer(CLIPBOARD_TYPE_COPY_PASTE); - clipboard_writer.WriteText(plain); - clipboard_writer.WriteHTML(markup, url); - } - - EXPECT_TRUE(clipboard().IsFormatAvailable(Clipboard::GetHtmlFormatType(), - CLIPBOARD_TYPE_COPY_PASTE)); - uint32 ignored; - clipboard().ReadHTML(CLIPBOARD_TYPE_COPY_PASTE, &markup_result, &url_result, - &ignored, &ignored); - EXPECT_PRED2(MarkupMatches, markup, markup_result); -#if defined(OS_WIN) - // TODO(playmobil): It's not clear that non windows clipboards need to support - // this. - EXPECT_EQ(url, url_result); -#endif // defined(OS_WIN) -} - -TEST_F(ClipboardTest, RTFTest) { - std::string rtf = - "{\\rtf1\\ansi{\\fonttbl\\f0\\fswiss Helvetica;}\\f0\\pard\n" - "This is some {\\b bold} text.\\par\n" - "}"; - - { - ScopedClipboardWriter clipboard_writer(CLIPBOARD_TYPE_COPY_PASTE); - clipboard_writer.WriteRTF(rtf); - } - - EXPECT_TRUE(clipboard().IsFormatAvailable(Clipboard::GetRtfFormatType(), - CLIPBOARD_TYPE_COPY_PASTE)); - std::string result; - clipboard().ReadRTF(CLIPBOARD_TYPE_COPY_PASTE, &result); - EXPECT_EQ(rtf, result); -} - -// TODO(dnicoara) Enable test once Ozone implements clipboard support: -// crbug.com/361707 -#if defined(OS_LINUX) && !defined(OS_CHROMEOS) && !defined(USE_OZONE) -TEST_F(ClipboardTest, MultipleBufferTest) { - base::string16 text(ASCIIToUTF16("Standard")), text_result; - base::string16 markup(ASCIIToUTF16("<string>Selection</string>")); - std::string url("http://www.example.com/"), url_result; - - { - ScopedClipboardWriter clipboard_writer(CLIPBOARD_TYPE_COPY_PASTE); - clipboard_writer.WriteText(text); - } - - { - ScopedClipboardWriter clipboard_writer(CLIPBOARD_TYPE_SELECTION); - clipboard_writer.WriteHTML(markup, url); - } - - EXPECT_TRUE(clipboard().IsFormatAvailable(Clipboard::GetPlainTextFormatType(), - CLIPBOARD_TYPE_COPY_PASTE)); - EXPECT_FALSE(clipboard().IsFormatAvailable( - Clipboard::GetPlainTextFormatType(), - CLIPBOARD_TYPE_SELECTION)); - - EXPECT_FALSE(clipboard().IsFormatAvailable(Clipboard::GetHtmlFormatType(), - CLIPBOARD_TYPE_COPY_PASTE)); - EXPECT_TRUE(clipboard().IsFormatAvailable(Clipboard::GetHtmlFormatType(), - CLIPBOARD_TYPE_SELECTION)); - - clipboard().ReadText(CLIPBOARD_TYPE_COPY_PASTE, &text_result); - EXPECT_EQ(text, text_result); - - uint32 ignored; - base::string16 markup_result; - clipboard().ReadHTML(CLIPBOARD_TYPE_SELECTION, - &markup_result, - &url_result, - &ignored, - &ignored); - EXPECT_PRED2(MarkupMatches, markup, markup_result); -} -#endif - -TEST_F(ClipboardTest, TrickyHTMLTest) { - base::string16 markup(ASCIIToUTF16("<em>Bye!<!--EndFragment --></em>")), - markup_result; - std::string url, url_result; - base::string16 plain(ASCIIToUTF16("Bye!")), plain_result; - - { - ScopedClipboardWriter clipboard_writer(CLIPBOARD_TYPE_COPY_PASTE); - clipboard_writer.WriteText(plain); - clipboard_writer.WriteHTML(markup, url); - } - - EXPECT_TRUE(clipboard().IsFormatAvailable(Clipboard::GetHtmlFormatType(), - CLIPBOARD_TYPE_COPY_PASTE)); - uint32 ignored; - clipboard().ReadHTML(CLIPBOARD_TYPE_COPY_PASTE, &markup_result, &url_result, - &ignored, &ignored); - EXPECT_PRED2(MarkupMatches, markup, markup_result); -#if defined(OS_WIN) - // TODO(playmobil): It's not clear that non windows clipboards need to support - // this. - EXPECT_EQ(url, url_result); -#endif // defined(OS_WIN) -} - -#if defined(OS_WIN) -TEST_F(ClipboardTest, UniodeHTMLTest) { - base::string16 markup(UTF8ToUTF16("<div>A \xc3\xb8 \xe6\xb0\xb4</div>")), - markup_result; - std::string url, url_result; - - { - ScopedClipboardWriter clipboard_writer(CLIPBOARD_TYPE_COPY_PASTE); - clipboard_writer.WriteHTML(markup, url); - } - - EXPECT_TRUE(clipboard().IsFormatAvailable(Clipboard::GetHtmlFormatType(), - CLIPBOARD_TYPE_COPY_PASTE)); - uint32 fragment_start; - uint32 fragment_end; - clipboard().ReadHTML(CLIPBOARD_TYPE_COPY_PASTE, &markup_result, &url_result, - &fragment_start, &fragment_end); - EXPECT_PRED2(MarkupMatches, markup, markup_result); - EXPECT_EQ(url, url_result); - // Make sure that fragment indices were adjusted when converting. - EXPECT_EQ(36, fragment_start); - EXPECT_EQ(52, fragment_end); -} -#endif // defined(OS_WIN) - -// TODO(estade): Port the following test (decide what target we use for urls) -#if !defined(OS_POSIX) || defined(OS_MACOSX) -TEST_F(ClipboardTest, BookmarkTest) { - base::string16 title(ASCIIToUTF16("The Example Company")), title_result; - std::string url("http://www.example.com/"), url_result; - - { - ScopedClipboardWriter clipboard_writer(CLIPBOARD_TYPE_COPY_PASTE); - clipboard_writer.WriteBookmark(title, url); - } - - EXPECT_TRUE(clipboard().IsFormatAvailable(Clipboard::GetUrlWFormatType(), - CLIPBOARD_TYPE_COPY_PASTE)); - clipboard().ReadBookmark(&title_result, &url_result); - EXPECT_EQ(title, title_result); - EXPECT_EQ(url, url_result); -} -#endif // defined(OS_WIN) - -TEST_F(ClipboardTest, MultiFormatTest) { - base::string16 text(ASCIIToUTF16("Hi!")), text_result; - base::string16 markup(ASCIIToUTF16("<strong>Hi!</string>")), markup_result; - std::string url("http://www.example.com/"), url_result; - std::string ascii_text; - - { - ScopedClipboardWriter clipboard_writer(CLIPBOARD_TYPE_COPY_PASTE); - clipboard_writer.WriteHTML(markup, url); - clipboard_writer.WriteText(text); - } - - EXPECT_TRUE(clipboard().IsFormatAvailable(Clipboard::GetHtmlFormatType(), - CLIPBOARD_TYPE_COPY_PASTE)); - EXPECT_TRUE(clipboard().IsFormatAvailable( - Clipboard::GetPlainTextWFormatType(), CLIPBOARD_TYPE_COPY_PASTE)); - EXPECT_TRUE(clipboard().IsFormatAvailable( - Clipboard::GetPlainTextFormatType(), CLIPBOARD_TYPE_COPY_PASTE)); - uint32 ignored; - clipboard().ReadHTML(CLIPBOARD_TYPE_COPY_PASTE, &markup_result, &url_result, - &ignored, &ignored); - EXPECT_PRED2(MarkupMatches, markup, markup_result); -#if defined(OS_WIN) - // TODO(playmobil): It's not clear that non windows clipboards need to support - // this. - EXPECT_EQ(url, url_result); -#endif // defined(OS_WIN) - clipboard().ReadText(CLIPBOARD_TYPE_COPY_PASTE, &text_result); - EXPECT_EQ(text, text_result); - clipboard().ReadAsciiText(CLIPBOARD_TYPE_COPY_PASTE, &ascii_text); - EXPECT_EQ(UTF16ToUTF8(text), ascii_text); -} - -TEST_F(ClipboardTest, URLTest) { - base::string16 url(ASCIIToUTF16("http://www.google.com/")); - - { - ScopedClipboardWriter clipboard_writer(CLIPBOARD_TYPE_COPY_PASTE); - clipboard_writer.WriteURL(url); - } - - EXPECT_TRUE(clipboard().IsFormatAvailable( - Clipboard::GetPlainTextWFormatType(), CLIPBOARD_TYPE_COPY_PASTE)); - EXPECT_TRUE(clipboard().IsFormatAvailable(Clipboard::GetPlainTextFormatType(), - CLIPBOARD_TYPE_COPY_PASTE)); - base::string16 text_result; - clipboard().ReadText(CLIPBOARD_TYPE_COPY_PASTE, &text_result); - - EXPECT_EQ(text_result, url); - - std::string ascii_text; - clipboard().ReadAsciiText(CLIPBOARD_TYPE_COPY_PASTE, &ascii_text); - EXPECT_EQ(UTF16ToUTF8(url), ascii_text); - -#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID) - ascii_text.clear(); - clipboard().ReadAsciiText(CLIPBOARD_TYPE_SELECTION, &ascii_text); - EXPECT_EQ(UTF16ToUTF8(url), ascii_text); -#endif -} - -// TODO(dcheng): The tests for copying to the clipboard also test IPC -// interaction... consider moving them to a different layer so we can -// consolidate the validation logic. -// Note that |bitmap_data| is not premultiplied! -static void TestBitmapWrite(Clipboard* clipboard, - const uint32* bitmap_data, - size_t bitmap_data_size, - const gfx::Size& size) { - // Create shared memory region. - base::SharedMemory shared_buf; - ASSERT_TRUE(shared_buf.CreateAndMapAnonymous(bitmap_data_size)); - memcpy(shared_buf.memory(), bitmap_data, bitmap_data_size); - // CBF_SMBITMAP expects premultiplied bitmap data so do that now. - uint32* pixel_buffer = static_cast<uint32*>(shared_buf.memory()); - for (int j = 0; j < size.height(); ++j) { - for (int i = 0; i < size.width(); ++i) { - uint32& pixel = pixel_buffer[i + j * size.width()]; - pixel = SkPreMultiplyColor(pixel); - } - } - base::SharedMemoryHandle handle_to_share; - base::ProcessHandle current_process = base::kNullProcessHandle; -#if defined(OS_WIN) - current_process = GetCurrentProcess(); -#endif - shared_buf.ShareToProcess(current_process, &handle_to_share); - ASSERT_TRUE(shared_buf.Unmap()); - - // Setup data for clipboard(). - Clipboard::ObjectMapParam placeholder_param; - Clipboard::ObjectMapParam size_param; - const char* size_data = reinterpret_cast<const char*>(&size); - for (size_t i = 0; i < sizeof(size); ++i) - size_param.push_back(size_data[i]); - - Clipboard::ObjectMapParams params; - params.push_back(placeholder_param); - params.push_back(size_param); - - Clipboard::ObjectMap objects; - objects[Clipboard::CBF_SMBITMAP] = params; - ASSERT_TRUE(Clipboard::ReplaceSharedMemHandle( - &objects, handle_to_share, current_process)); - - ClipboardTest::WriteObjectsToClipboard(clipboard, objects); - - EXPECT_TRUE(clipboard->IsFormatAvailable(Clipboard::GetBitmapFormatType(), - CLIPBOARD_TYPE_COPY_PASTE)); - const SkBitmap& image = clipboard->ReadImage(CLIPBOARD_TYPE_COPY_PASTE); - EXPECT_EQ(size, gfx::Size(image.width(), image.height())); - SkAutoLockPixels image_lock(image); - for (int j = 0; j < image.height(); ++j) { - const uint32* row_address = image.getAddr32(0, j); - for (int i = 0; i < image.width(); ++i) { - int offset = i + j * image.width(); - uint32 pixel = SkPreMultiplyColor(bitmap_data[offset]); - EXPECT_EQ(pixel, row_address[i]) - << "i = " << i << ", j = " << j; - } - } -} - -TEST_F(ClipboardTest, SharedBitmapTest) { - const uint32 fake_bitmap_1[] = { - 0x46155189, 0xF6A55C8D, 0x79845674, 0xFA57BD89, - 0x78FD46AE, 0x87C64F5A, 0x36EDC5AF, 0x4378F568, - 0x91E9F63A, 0xC31EA14F, 0x69AB32DF, 0x643A3FD1, - }; - { - SCOPED_TRACE("first bitmap"); - TestBitmapWrite( - &clipboard(), fake_bitmap_1, sizeof(fake_bitmap_1), gfx::Size(4, 3)); - } - - const uint32 fake_bitmap_2[] = { - 0x46155189, 0xF6A55C8D, - 0x79845674, 0xFA57BD89, - 0x78FD46AE, 0x87C64F5A, - 0x36EDC5AF, 0x4378F568, - 0x91E9F63A, 0xC31EA14F, - 0x69AB32DF, 0x643A3FD1, - 0xA6DF041D, 0x83046278, - }; - { - SCOPED_TRACE("second bitmap"); - TestBitmapWrite( - &clipboard(), fake_bitmap_2, sizeof(fake_bitmap_2), gfx::Size(2, 7)); - } -} - -namespace { -// A size class that just happens to have the same layout as gfx::Size! -struct UnsafeSize { - int width; - int height; -}; -COMPILE_ASSERT(sizeof(UnsafeSize) == sizeof(gfx::Size), - UnsafeSize_must_be_same_size_as_gfx_Size); -} // namespace - -TEST_F(ClipboardTest, SharedBitmapWithTwoNegativeSizes) { - Clipboard::ObjectMapParam placeholder_param; - void* crash_me = reinterpret_cast<void*>(57); - placeholder_param.resize(sizeof(crash_me)); - memcpy(&placeholder_param.front(), &crash_me, sizeof(crash_me)); - - Clipboard::ObjectMapParam size_param; - UnsafeSize size = {-100, -100}; - size_param.resize(sizeof(size)); - memcpy(&size_param.front(), &size, sizeof(size)); - - Clipboard::ObjectMapParams params; - params.push_back(placeholder_param); - params.push_back(size_param); - - Clipboard::ObjectMap objects; - objects[Clipboard::CBF_SMBITMAP] = params; - - WriteObjectsToClipboard(objects); - EXPECT_FALSE(clipboard().IsFormatAvailable(Clipboard::GetBitmapFormatType(), - CLIPBOARD_TYPE_COPY_PASTE)); -} - -TEST_F(ClipboardTest, SharedBitmapWithOneNegativeSize) { - Clipboard::ObjectMapParam placeholder_param; - void* crash_me = reinterpret_cast<void*>(57); - placeholder_param.resize(sizeof(crash_me)); - memcpy(&placeholder_param.front(), &crash_me, sizeof(crash_me)); - - Clipboard::ObjectMapParam size_param; - UnsafeSize size = {-100, 100}; - size_param.resize(sizeof(size)); - memcpy(&size_param.front(), &size, sizeof(size)); - - Clipboard::ObjectMapParams params; - params.push_back(placeholder_param); - params.push_back(size_param); - - Clipboard::ObjectMap objects; - objects[Clipboard::CBF_SMBITMAP] = params; - - WriteObjectsToClipboard(objects); - EXPECT_FALSE(clipboard().IsFormatAvailable(Clipboard::GetBitmapFormatType(), - CLIPBOARD_TYPE_COPY_PASTE)); -} - -TEST_F(ClipboardTest, BitmapWithSuperSize) { - Clipboard::ObjectMapParam placeholder_param; - void* crash_me = reinterpret_cast<void*>(57); - placeholder_param.resize(sizeof(crash_me)); - memcpy(&placeholder_param.front(), &crash_me, sizeof(crash_me)); - - Clipboard::ObjectMapParam size_param; - // Width just big enough that bytes per row won't fit in a 32-bit - // representation. - gfx::Size size(0x20000000, 1); - size_param.resize(sizeof(size)); - memcpy(&size_param.front(), &size, sizeof(size)); - - Clipboard::ObjectMapParams params; - params.push_back(placeholder_param); - params.push_back(size_param); - - Clipboard::ObjectMap objects; - objects[Clipboard::CBF_SMBITMAP] = params; - - WriteObjectsToClipboard(objects); - EXPECT_FALSE(clipboard().IsFormatAvailable(Clipboard::GetBitmapFormatType(), - CLIPBOARD_TYPE_COPY_PASTE)); -} - -TEST_F(ClipboardTest, BitmapWithSuperSize2) { - Clipboard::ObjectMapParam placeholder_param; - void* crash_me = reinterpret_cast<void*>(57); - placeholder_param.resize(sizeof(crash_me)); - memcpy(&placeholder_param.front(), &crash_me, sizeof(crash_me)); - - Clipboard::ObjectMapParam size_param; - // Width and height large enough that SkBitmap::getSize() will be truncated. - gfx::Size size(0x0fffffff, 0x0fffffff); - size_param.resize(sizeof(size)); - memcpy(&size_param.front(), &size, sizeof(size)); - - Clipboard::ObjectMapParams params; - params.push_back(placeholder_param); - params.push_back(size_param); - - Clipboard::ObjectMap objects; - objects[Clipboard::CBF_SMBITMAP] = params; - - WriteObjectsToClipboard(objects); - EXPECT_FALSE(clipboard().IsFormatAvailable(Clipboard::GetBitmapFormatType(), - CLIPBOARD_TYPE_COPY_PASTE)); -} - -TEST_F(ClipboardTest, DataTest) { - const ui::Clipboard::FormatType kFormat = - ui::Clipboard::GetFormatType("chromium/x-test-format"); - std::string payload("test string"); - Pickle write_pickle; - write_pickle.WriteString(payload); - - { - ScopedClipboardWriter clipboard_writer(CLIPBOARD_TYPE_COPY_PASTE); - clipboard_writer.WritePickledData(write_pickle, kFormat); - } - - ASSERT_TRUE(clipboard().IsFormatAvailable( - kFormat, CLIPBOARD_TYPE_COPY_PASTE)); - std::string output; - clipboard().ReadData(kFormat, &output); - ASSERT_FALSE(output.empty()); - - Pickle read_pickle(output.data(), output.size()); - PickleIterator iter(read_pickle); - std::string unpickled_string; - ASSERT_TRUE(read_pickle.ReadString(&iter, &unpickled_string)); - EXPECT_EQ(payload, unpickled_string); -} - -TEST_F(ClipboardTest, MultipleDataTest) { - const ui::Clipboard::FormatType kFormat1 = - ui::Clipboard::GetFormatType("chromium/x-test-format1"); - std::string payload1("test string1"); - Pickle write_pickle1; - write_pickle1.WriteString(payload1); - - const ui::Clipboard::FormatType kFormat2 = - ui::Clipboard::GetFormatType("chromium/x-test-format2"); - std::string payload2("test string2"); - Pickle write_pickle2; - write_pickle2.WriteString(payload2); - - { - ScopedClipboardWriter clipboard_writer(CLIPBOARD_TYPE_COPY_PASTE); - clipboard_writer.WritePickledData(write_pickle1, kFormat1); - // overwrite the previous pickle for fun - clipboard_writer.WritePickledData(write_pickle2, kFormat2); - } - - ASSERT_TRUE(clipboard().IsFormatAvailable( - kFormat2, CLIPBOARD_TYPE_COPY_PASTE)); - - // Check string 2. - std::string output2; - clipboard().ReadData(kFormat2, &output2); - ASSERT_FALSE(output2.empty()); - - Pickle read_pickle2(output2.data(), output2.size()); - PickleIterator iter2(read_pickle2); - std::string unpickled_string2; - ASSERT_TRUE(read_pickle2.ReadString(&iter2, &unpickled_string2)); - EXPECT_EQ(payload2, unpickled_string2); - - { - ScopedClipboardWriter clipboard_writer(CLIPBOARD_TYPE_COPY_PASTE); - clipboard_writer.WritePickledData(write_pickle2, kFormat2); - // overwrite the previous pickle for fun - clipboard_writer.WritePickledData(write_pickle1, kFormat1); - } - - ASSERT_TRUE(clipboard().IsFormatAvailable( - kFormat1, CLIPBOARD_TYPE_COPY_PASTE)); - - // Check string 1. - std::string output1; - clipboard().ReadData(kFormat1, &output1); - ASSERT_FALSE(output1.empty()); - - Pickle read_pickle1(output1.data(), output1.size()); - PickleIterator iter1(read_pickle1); - std::string unpickled_string1; - ASSERT_TRUE(read_pickle1.ReadString(&iter1, &unpickled_string1)); - EXPECT_EQ(payload1, unpickled_string1); -} - -#if !defined(OS_MACOSX) && !defined(OS_ANDROID) -TEST_F(ClipboardTest, HyperlinkTest) { - const std::string kTitle("The <Example> Company's \"home page\""); - const std::string kUrl("http://www.example.com?x=3<=3#\"'<>"); - const std::string kExpectedHtml( - "<a href=\"http://www.example.com?x=3&lt=3#"'<>\">" - "The <Example> Company's "home page"</a>"); - - std::string url_result; - base::string16 html_result; - { - ScopedClipboardWriter clipboard_writer(CLIPBOARD_TYPE_COPY_PASTE); - clipboard_writer.WriteHyperlink(ASCIIToUTF16(kTitle), kUrl); - } - - EXPECT_TRUE(clipboard().IsFormatAvailable(Clipboard::GetHtmlFormatType(), - CLIPBOARD_TYPE_COPY_PASTE)); - uint32 ignored; - clipboard().ReadHTML(CLIPBOARD_TYPE_COPY_PASTE, &html_result, &url_result, - &ignored, &ignored); - EXPECT_PRED2(MarkupMatches, ASCIIToUTF16(kExpectedHtml), html_result); -} -#endif - -#if defined(OS_WIN) // Windows only tests. -TEST_F(ClipboardTest, WebSmartPasteTest) { - { - ScopedClipboardWriter clipboard_writer(CLIPBOARD_TYPE_COPY_PASTE); - clipboard_writer.WriteWebSmartPaste(); - } - - EXPECT_TRUE(clipboard().IsFormatAvailable( - Clipboard::GetWebKitSmartPasteFormatType(), CLIPBOARD_TYPE_COPY_PASTE)); -} - -void HtmlTestHelper(const std::string& cf_html, - const std::string& expected_html) { - std::string html; - ClipboardUtil::CFHtmlToHtml(cf_html, &html, NULL); - EXPECT_EQ(html, expected_html); -} - -TEST_F(ClipboardTest, HtmlTest) { - // Test converting from CF_HTML format data with <!--StartFragment--> and - // <!--EndFragment--> comments, like from MS Word. - HtmlTestHelper("Version:1.0\r\n" - "StartHTML:0000000105\r\n" - "EndHTML:0000000199\r\n" - "StartFragment:0000000123\r\n" - "EndFragment:0000000161\r\n" - "\r\n" - "<html>\r\n" - "<body>\r\n" - "<!--StartFragment-->\r\n" - "\r\n" - "<p>Foo</p>\r\n" - "\r\n" - "<!--EndFragment-->\r\n" - "</body>\r\n" - "</html>\r\n\r\n", - "<p>Foo</p>"); - - // Test converting from CF_HTML format data without <!--StartFragment--> and - // <!--EndFragment--> comments, like from OpenOffice Writer. - HtmlTestHelper("Version:1.0\r\n" - "StartHTML:0000000105\r\n" - "EndHTML:0000000151\r\n" - "StartFragment:0000000121\r\n" - "EndFragment:0000000131\r\n" - "<html>\r\n" - "<body>\r\n" - "<p>Foo</p>\r\n" - "</body>\r\n" - "</html>\r\n\r\n", - "<p>Foo</p>"); -} -#endif // defined(OS_WIN) - -// Test writing all formats we have simultaneously. -TEST_F(ClipboardTest, WriteEverything) { - { - ScopedClipboardWriter writer(CLIPBOARD_TYPE_COPY_PASTE); - writer.WriteText(UTF8ToUTF16("foo")); - writer.WriteURL(UTF8ToUTF16("foo")); - writer.WriteHTML(UTF8ToUTF16("foo"), "bar"); - writer.WriteBookmark(UTF8ToUTF16("foo"), "bar"); - writer.WriteHyperlink(ASCIIToUTF16("foo"), "bar"); - writer.WriteWebSmartPaste(); - // Left out: WriteFile, WriteFiles, WriteBitmapFromPixels, WritePickledData. - } - - // Passes if we don't crash. -} - -// TODO(dcheng): Fix this test for Android. It's rather involved, since the -// clipboard change listener is posted to the Java message loop, and spinning -// that loop from C++ to trigger the callback in the test requires a non-trivial -// amount of additional work. -#if !defined(OS_ANDROID) -// Simple test that the sequence number appears to change when the clipboard is -// written to. -// TODO(dcheng): Add a version to test CLIPBOARD_TYPE_SELECTION. -TEST_F(ClipboardTest, GetSequenceNumber) { - const uint64 first_sequence_number = - clipboard().GetSequenceNumber(CLIPBOARD_TYPE_COPY_PASTE); - - { - ScopedClipboardWriter writer(CLIPBOARD_TYPE_COPY_PASTE); - writer.WriteText(UTF8ToUTF16("World")); - } - - // On some platforms, the sequence number is updated by a UI callback so pump - // the message loop to make sure we get the notification. - base::RunLoop().RunUntilIdle(); - - const uint64 second_sequence_number = - clipboard().GetSequenceNumber(CLIPBOARD_TYPE_COPY_PASTE); - - EXPECT_NE(first_sequence_number, second_sequence_number); -} -#endif - -#if defined(OS_ANDROID) - -// Test that if another application writes some text to the pasteboard the -// clipboard properly invalidates other types. -TEST_F(ClipboardTest, InternalClipboardInvalidation) { - // Write a Webkit smart paste tag to our clipboard. - { - ScopedClipboardWriter clipboard_writer(CLIPBOARD_TYPE_COPY_PASTE); - clipboard_writer.WriteWebSmartPaste(); - } - EXPECT_TRUE(clipboard().IsFormatAvailable( - Clipboard::GetWebKitSmartPasteFormatType(), CLIPBOARD_TYPE_COPY_PASTE)); - - // - // Simulate that another application copied something in the Clipboard - // - std::string new_value("Some text copied by some other app"); - using base::android::ConvertUTF8ToJavaString; - using base::android::MethodID; - using base::android::ScopedJavaLocalRef; - - JNIEnv* env = base::android::AttachCurrentThread(); - ASSERT_TRUE(env); - - jobject context = base::android::GetApplicationContext(); - ASSERT_TRUE(context); - - ScopedJavaLocalRef<jclass> context_class = - base::android::GetClass(env, "android/content/Context"); - - jmethodID get_system_service = MethodID::Get<MethodID::TYPE_INSTANCE>( - env, context_class.obj(), "getSystemService", - "(Ljava/lang/String;)Ljava/lang/Object;"); - - // Retrieve the system service. - ScopedJavaLocalRef<jstring> service_name = ConvertUTF8ToJavaString( - env, "clipboard"); - ScopedJavaLocalRef<jobject> clipboard_manager( - env, env->CallObjectMethod( - context, get_system_service, service_name.obj())); - ASSERT_TRUE(clipboard_manager.obj() && !base::android::ClearException(env)); - - ScopedJavaLocalRef<jclass> clipboard_class = - base::android::GetClass(env, "android/text/ClipboardManager"); - jmethodID set_text = MethodID::Get<MethodID::TYPE_INSTANCE>( - env, clipboard_class.obj(), "setText", "(Ljava/lang/CharSequence;)V"); - ScopedJavaLocalRef<jstring> new_value_string = ConvertUTF8ToJavaString( - env, new_value.c_str()); - - // Will need to call toString as CharSequence is not always a String. - env->CallVoidMethod(clipboard_manager.obj(), - set_text, - new_value_string.obj()); - - // The WebKit smart paste tag should now be gone. - EXPECT_FALSE(clipboard().IsFormatAvailable( - Clipboard::GetWebKitSmartPasteFormatType(), CLIPBOARD_TYPE_COPY_PASTE)); - - // Make sure some text is available - EXPECT_TRUE(clipboard().IsFormatAvailable( - Clipboard::GetPlainTextWFormatType(), CLIPBOARD_TYPE_COPY_PASTE)); - - // Make sure the text is what we inserted while simulating the other app - std::string contents; - clipboard().ReadAsciiText(CLIPBOARD_TYPE_COPY_PASTE, &contents); - EXPECT_EQ(contents, new_value); -} -#endif -} // namespace ui
diff --git a/ui/base/clipboard/clipboard_util_win.cc b/ui/base/clipboard/clipboard_util_win.cc deleted file mode 100644 index 687f0ff..0000000 --- a/ui/base/clipboard/clipboard_util_win.cc +++ /dev/null
@@ -1,502 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/clipboard/clipboard_util_win.h" - -#include <shellapi.h> -#include <shlwapi.h> -#include <wininet.h> // For INTERNET_MAX_URL_LENGTH. - -#include "base/basictypes.h" -#include "base/logging.h" -#include "base/strings/string_util.h" -#include "base/strings/stringprintf.h" -#include "base/strings/sys_string_conversions.h" -#include "base/strings/utf_string_conversions.h" -#include "base/win/scoped_hglobal.h" -#include "net/base/filename_util.h" -#include "ui/base/clipboard/clipboard.h" -#include "ui/base/clipboard/custom_data_helper.h" -#include "url/gurl.h" - -namespace ui { - -namespace { - -bool HasData(IDataObject* data_object, const Clipboard::FormatType& format) { - FORMATETC format_etc = format.ToFormatEtc(); - return SUCCEEDED(data_object->QueryGetData(&format_etc)); -} - -bool GetData(IDataObject* data_object, - const Clipboard::FormatType& format, - STGMEDIUM* medium) { - FORMATETC format_etc = format.ToFormatEtc(); - return SUCCEEDED(data_object->GetData(&format_etc, medium)); -} - -bool GetUrlFromHDrop(IDataObject* data_object, - GURL* url, - base::string16* title) { - DCHECK(data_object && url && title); - - bool success = false; - STGMEDIUM medium; - if (!GetData(data_object, Clipboard::GetCFHDropFormatType(), &medium)) - return false; - - { - base::win::ScopedHGlobal<HDROP> hdrop(medium.hGlobal); - - if (!hdrop.get()) - return false; - - wchar_t filename[MAX_PATH]; - if (DragQueryFileW(hdrop.get(), 0, filename, arraysize(filename))) { - wchar_t url_buffer[INTERNET_MAX_URL_LENGTH]; - if (0 == _wcsicmp(PathFindExtensionW(filename), L".url") && - GetPrivateProfileStringW(L"InternetShortcut", - L"url", - 0, - url_buffer, - arraysize(url_buffer), - filename)) { - *url = GURL(url_buffer); - PathRemoveExtension(filename); - title->assign(PathFindFileName(filename)); - success = url->is_valid(); - } - } - } - - ReleaseStgMedium(&medium); - return success; -} - -void SplitUrlAndTitle(const base::string16& str, - GURL* url, - base::string16* title) { - DCHECK(url && title); - size_t newline_pos = str.find('\n'); - if (newline_pos != base::string16::npos) { - *url = GURL(base::string16(str, 0, newline_pos)); - title->assign(str, newline_pos + 1, base::string16::npos); - } else { - *url = GURL(str); - title->assign(str); - } -} - -} // namespace - -bool ClipboardUtil::HasUrl(IDataObject* data_object, bool convert_filenames) { - DCHECK(data_object); - return HasData(data_object, Clipboard::GetMozUrlFormatType()) || - HasData(data_object, Clipboard::GetUrlWFormatType()) || - HasData(data_object, Clipboard::GetUrlFormatType()) || - (convert_filenames && HasFilenames(data_object)); -} - -bool ClipboardUtil::HasFilenames(IDataObject* data_object) { - DCHECK(data_object); - return HasData(data_object, Clipboard::GetCFHDropFormatType()) || - HasData(data_object, Clipboard::GetFilenameWFormatType()) || - HasData(data_object, Clipboard::GetFilenameFormatType()); -} - -bool ClipboardUtil::HasFileContents(IDataObject* data_object) { - DCHECK(data_object); - return HasData(data_object, Clipboard::GetFileContentZeroFormatType()); -} - -bool ClipboardUtil::HasHtml(IDataObject* data_object) { - DCHECK(data_object); - return HasData(data_object, Clipboard::GetHtmlFormatType()) || - HasData(data_object, Clipboard::GetTextHtmlFormatType()); -} - -bool ClipboardUtil::HasPlainText(IDataObject* data_object) { - DCHECK(data_object); - return HasData(data_object, Clipboard::GetPlainTextWFormatType()) || - HasData(data_object, Clipboard::GetPlainTextFormatType()); -} - -bool ClipboardUtil::GetUrl(IDataObject* data_object, - GURL* url, - base::string16* title, - bool convert_filenames) { - DCHECK(data_object && url && title); - if (!HasUrl(data_object, convert_filenames)) - return false; - - // Try to extract a URL from |data_object| in a variety of formats. - STGMEDIUM store; - if (GetUrlFromHDrop(data_object, url, title)) - return true; - - if (GetData(data_object, Clipboard::GetMozUrlFormatType(), &store) || - GetData(data_object, Clipboard::GetUrlWFormatType(), &store)) { - { - // Mozilla URL format or unicode URL - base::win::ScopedHGlobal<wchar_t*> data(store.hGlobal); - SplitUrlAndTitle(data.get(), url, title); - } - ReleaseStgMedium(&store); - return url->is_valid(); - } - - if (GetData(data_object, Clipboard::GetUrlFormatType(), &store)) { - { - // URL using ascii - base::win::ScopedHGlobal<char*> data(store.hGlobal); - SplitUrlAndTitle(base::UTF8ToWide(data.get()), url, title); - } - ReleaseStgMedium(&store); - return url->is_valid(); - } - - if (convert_filenames) { - std::vector<base::string16> filenames; - if (!GetFilenames(data_object, &filenames)) - return false; - DCHECK_GT(filenames.size(), 0U); - *url = net::FilePathToFileURL(base::FilePath(filenames[0])); - return url->is_valid(); - } - - return false; -} - -bool ClipboardUtil::GetFilenames(IDataObject* data_object, - std::vector<base::string16>* filenames) { - DCHECK(data_object && filenames); - if (!HasFilenames(data_object)) - return false; - - STGMEDIUM medium; - if (GetData(data_object, Clipboard::GetCFHDropFormatType(), &medium)) { - { - base::win::ScopedHGlobal<HDROP> hdrop(medium.hGlobal); - if (!hdrop.get()) - return false; - - const int kMaxFilenameLen = 4096; - const unsigned num_files = DragQueryFileW(hdrop.get(), 0xffffffff, 0, 0); - for (unsigned int i = 0; i < num_files; ++i) { - wchar_t filename[kMaxFilenameLen]; - if (!DragQueryFileW(hdrop.get(), i, filename, kMaxFilenameLen)) - continue; - filenames->push_back(filename); - } - } - ReleaseStgMedium(&medium); - return true; - } - - if (GetData(data_object, Clipboard::GetFilenameWFormatType(), &medium)) { - { - // filename using unicode - base::win::ScopedHGlobal<wchar_t*> data(medium.hGlobal); - if (data.get() && data.get()[0]) - filenames->push_back(data.get()); - } - ReleaseStgMedium(&medium); - return true; - } - - if (GetData(data_object, Clipboard::GetFilenameFormatType(), &medium)) { - { - // filename using ascii - base::win::ScopedHGlobal<char*> data(medium.hGlobal); - if (data.get() && data.get()[0]) - filenames->push_back(base::SysNativeMBToWide(data.get())); - } - ReleaseStgMedium(&medium); - return true; - } - - return false; -} - -bool ClipboardUtil::GetPlainText(IDataObject* data_object, - base::string16* plain_text) { - DCHECK(data_object && plain_text); - if (!HasPlainText(data_object)) - return false; - - STGMEDIUM store; - if (GetData(data_object, Clipboard::GetPlainTextWFormatType(), &store)) { - { - // Unicode text - base::win::ScopedHGlobal<wchar_t*> data(store.hGlobal); - plain_text->assign(data.get()); - } - ReleaseStgMedium(&store); - return true; - } - - if (GetData(data_object, Clipboard::GetPlainTextFormatType(), &store)) { - { - // ascii text - base::win::ScopedHGlobal<char*> data(store.hGlobal); - plain_text->assign(base::UTF8ToWide(data.get())); - } - ReleaseStgMedium(&store); - return true; - } - - // If a file is dropped on the window, it does not provide either of the - // plain text formats, so here we try to forcibly get a url. - GURL url; - base::string16 title; - if (GetUrl(data_object, &url, &title, false)) { - *plain_text = base::UTF8ToUTF16(url.spec()); - return true; - } - return false; -} - -bool ClipboardUtil::GetHtml(IDataObject* data_object, - base::string16* html, std::string* base_url) { - DCHECK(data_object && html && base_url); - - STGMEDIUM store; - if (HasData(data_object, Clipboard::GetHtmlFormatType()) && - GetData(data_object, Clipboard::GetHtmlFormatType(), &store)) { - { - // MS CF html - base::win::ScopedHGlobal<char*> data(store.hGlobal); - - std::string html_utf8; - CFHtmlToHtml(std::string(data.get(), data.Size()), &html_utf8, base_url); - html->assign(base::UTF8ToWide(html_utf8)); - } - ReleaseStgMedium(&store); - return true; - } - - if (!HasData(data_object, Clipboard::GetTextHtmlFormatType())) - return false; - - if (!GetData(data_object, Clipboard::GetTextHtmlFormatType(), &store)) - return false; - - { - // text/html - base::win::ScopedHGlobal<wchar_t*> data(store.hGlobal); - html->assign(data.get()); - } - ReleaseStgMedium(&store); - return true; -} - -bool ClipboardUtil::GetFileContents(IDataObject* data_object, - base::string16* filename, std::string* file_contents) { - DCHECK(data_object && filename && file_contents); - if (!HasData(data_object, Clipboard::GetFileContentZeroFormatType()) && - !HasData(data_object, Clipboard::GetFileDescriptorFormatType())) - return false; - - STGMEDIUM content; - // The call to GetData can be very slow depending on what is in - // |data_object|. - if (GetData( - data_object, Clipboard::GetFileContentZeroFormatType(), &content)) { - if (TYMED_HGLOBAL == content.tymed) { - base::win::ScopedHGlobal<char*> data(content.hGlobal); - file_contents->assign(data.get(), data.Size()); - } - ReleaseStgMedium(&content); - } - - STGMEDIUM description; - if (GetData(data_object, - Clipboard::GetFileDescriptorFormatType(), - &description)) { - { - base::win::ScopedHGlobal<FILEGROUPDESCRIPTOR*> fgd(description.hGlobal); - // We expect there to be at least one file in here. - DCHECK_GE(fgd->cItems, 1u); - filename->assign(fgd->fgd[0].cFileName); - } - ReleaseStgMedium(&description); - } - return true; -} - -bool ClipboardUtil::GetWebCustomData( - IDataObject* data_object, - std::map<base::string16, base::string16>* custom_data) { - DCHECK(data_object && custom_data); - - if (!HasData(data_object, Clipboard::GetWebCustomDataFormatType())) - return false; - - STGMEDIUM store; - if (GetData(data_object, Clipboard::GetWebCustomDataFormatType(), &store)) { - { - base::win::ScopedHGlobal<char*> data(store.hGlobal); - ReadCustomDataIntoMap(data.get(), data.Size(), custom_data); - } - ReleaseStgMedium(&store); - return true; - } - return false; -} - - -// HtmlToCFHtml and CFHtmlToHtml are based on similar methods in -// WebCore/platform/win/ClipboardUtilitiesWin.cpp. -/* - * Copyright (C) 2007, 2008 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -// Helper method for converting from text/html to MS CF_HTML. -// Documentation for the CF_HTML format is available at -// http://msdn.microsoft.com/en-us/library/aa767917(VS.85).aspx -std::string ClipboardUtil::HtmlToCFHtml(const std::string& html, - const std::string& base_url) { - if (html.empty()) - return std::string(); - - #define MAX_DIGITS 10 - #define MAKE_NUMBER_FORMAT_1(digits) MAKE_NUMBER_FORMAT_2(digits) - #define MAKE_NUMBER_FORMAT_2(digits) "%0" #digits "u" - #define NUMBER_FORMAT MAKE_NUMBER_FORMAT_1(MAX_DIGITS) - - static const char* header = "Version:0.9\r\n" - "StartHTML:" NUMBER_FORMAT "\r\n" - "EndHTML:" NUMBER_FORMAT "\r\n" - "StartFragment:" NUMBER_FORMAT "\r\n" - "EndFragment:" NUMBER_FORMAT "\r\n"; - static const char* source_url_prefix = "SourceURL:"; - - static const char* start_markup = - "<html>\r\n<body>\r\n<!--StartFragment-->"; - static const char* end_markup = - "<!--EndFragment-->\r\n</body>\r\n</html>"; - - // Calculate offsets - size_t start_html_offset = strlen(header) - strlen(NUMBER_FORMAT) * 4 + - MAX_DIGITS * 4; - if (!base_url.empty()) { - start_html_offset += strlen(source_url_prefix) + - base_url.length() + 2; // Add 2 for \r\n. - } - size_t start_fragment_offset = start_html_offset + strlen(start_markup); - size_t end_fragment_offset = start_fragment_offset + html.length(); - size_t end_html_offset = end_fragment_offset + strlen(end_markup); - - std::string result = base::StringPrintf(header, - start_html_offset, - end_html_offset, - start_fragment_offset, - end_fragment_offset); - if (!base_url.empty()) { - result.append(source_url_prefix); - result.append(base_url); - result.append("\r\n"); - } - result.append(start_markup); - result.append(html); - result.append(end_markup); - - #undef MAX_DIGITS - #undef MAKE_NUMBER_FORMAT_1 - #undef MAKE_NUMBER_FORMAT_2 - #undef NUMBER_FORMAT - - return result; -} - -// Helper method for converting from MS CF_HTML to text/html. -void ClipboardUtil::CFHtmlToHtml(const std::string& cf_html, - std::string* html, - std::string* base_url) { - size_t fragment_start = std::string::npos; - size_t fragment_end = std::string::npos; - - ClipboardUtil::CFHtmlExtractMetadata( - cf_html, base_url, NULL, &fragment_start, &fragment_end); - - if (html && - fragment_start != std::string::npos && - fragment_end != std::string::npos) { - *html = cf_html.substr(fragment_start, fragment_end - fragment_start); - base::TrimWhitespace(*html, base::TRIM_ALL, html); - } -} - -void ClipboardUtil::CFHtmlExtractMetadata(const std::string& cf_html, - std::string* base_url, - size_t* html_start, - size_t* fragment_start, - size_t* fragment_end) { - // Obtain base_url if present. - if (base_url) { - static std::string src_url_str("SourceURL:"); - size_t line_start = cf_html.find(src_url_str); - if (line_start != std::string::npos) { - size_t src_end = cf_html.find("\n", line_start); - size_t src_start = line_start + src_url_str.length(); - if (src_end != std::string::npos && src_start != std::string::npos) { - *base_url = cf_html.substr(src_start, src_end - src_start); - base::TrimWhitespace(*base_url, base::TRIM_ALL, base_url); - } - } - } - - // Find the markup between "<!--StartFragment-->" and "<!--EndFragment-->". - // If the comments cannot be found, like copying from OpenOffice Writer, - // we simply fall back to using StartFragment/EndFragment bytecount values - // to determine the fragment indexes. - std::string cf_html_lower = base::StringToLowerASCII(cf_html); - size_t markup_start = cf_html_lower.find("<html", 0); - if (html_start) { - *html_start = markup_start; - } - size_t tag_start = cf_html.find("<!--StartFragment", markup_start); - if (tag_start == std::string::npos) { - static std::string start_fragment_str("StartFragment:"); - size_t start_fragment_start = cf_html.find(start_fragment_str); - if (start_fragment_start != std::string::npos) { - *fragment_start = static_cast<size_t>(atoi(cf_html.c_str() + - start_fragment_start + start_fragment_str.length())); - } - - static std::string end_fragment_str("EndFragment:"); - size_t end_fragment_start = cf_html.find(end_fragment_str); - if (end_fragment_start != std::string::npos) { - *fragment_end = static_cast<size_t>(atoi(cf_html.c_str() + - end_fragment_start + end_fragment_str.length())); - } - } else { - *fragment_start = cf_html.find('>', tag_start) + 1; - size_t tag_end = cf_html.rfind("<!--EndFragment", std::string::npos); - *fragment_end = cf_html.rfind('<', tag_end); - } -} - -} // namespace ui
diff --git a/ui/base/clipboard/clipboard_util_win.h b/ui/base/clipboard/clipboard_util_win.h deleted file mode 100644 index c2171da..0000000 --- a/ui/base/clipboard/clipboard_util_win.h +++ /dev/null
@@ -1,76 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -// -// Some helper functions for working with the clipboard and IDataObjects. - -#ifndef UI_BASE_CLIPBOARD_CLIPBOARD_UTIL_WIN_H_ -#define UI_BASE_CLIPBOARD_CLIPBOARD_UTIL_WIN_H_ - -#include <shlobj.h> -#include <map> -#include <string> -#include <vector> - -#include "base/strings/string16.h" -#include "ui/base/ui_base_export.h" - -class GURL; - -namespace ui { - -class UI_BASE_EXPORT ClipboardUtil { - public: - ///////////////////////////////////////////////////////////////////////////// - // These methods check to see if |data_object| has the requested type. - // Returns true if it does. - static bool HasUrl(IDataObject* data_object, bool convert_filenames); - static bool HasFilenames(IDataObject* data_object); - static bool HasPlainText(IDataObject* data_object); - static bool HasFileContents(IDataObject* data_object); - static bool HasHtml(IDataObject* data_object); - - ///////////////////////////////////////////////////////////////////////////// - // Helper methods to extract information from an IDataObject. These methods - // return true if the requested data type is found in |data_object|. - - // Only returns true if url->is_valid() is true. - static bool GetUrl(IDataObject* data_object, - GURL* url, - base::string16* title, - bool convert_filenames); - static bool GetFilenames(IDataObject* data_object, - std::vector<base::string16>* filenames); - static bool GetPlainText(IDataObject* data_object, - base::string16* plain_text); - static bool GetHtml(IDataObject* data_object, - base::string16* text_html, - std::string* base_url); - static bool GetFileContents(IDataObject* data_object, - base::string16* filename, - std::string* file_contents); - // This represents custom MIME types a web page might set to transport its - // own types of data for drag and drop. It is sandboxed in its own CLIPFORMAT - // to avoid polluting the ::RegisterClipboardFormat() namespace with random - // strings from web content. - static bool GetWebCustomData( - IDataObject* data_object, - std::map<base::string16, base::string16>* custom_data); - - // Helper method for converting between MS CF_HTML format and plain - // text/html. - static std::string HtmlToCFHtml(const std::string& html, - const std::string& base_url); - static void CFHtmlToHtml(const std::string& cf_html, - std::string* html, - std::string* base_url); - static void CFHtmlExtractMetadata(const std::string& cf_html, - std::string* base_url, - size_t* html_start, - size_t* fragment_start, - size_t* fragment_end); -}; - -} - -#endif // UI_BASE_CLIPBOARD_CLIPBOARD_UTIL_WIN_H_
diff --git a/ui/base/clipboard/clipboard_win.cc b/ui/base/clipboard/clipboard_win.cc deleted file mode 100644 index f37f077..0000000 --- a/ui/base/clipboard/clipboard_win.cc +++ /dev/null
@@ -1,862 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// Many of these functions are based on those found in -// webkit/port/platform/PasteboardWin.cpp - -#include "ui/base/clipboard/clipboard_win.h" - -#include <shellapi.h> -#include <shlobj.h> - -#include "base/basictypes.h" -#include "base/bind.h" -#include "base/files/file_path.h" -#include "base/logging.h" -#include "base/memory/shared_memory.h" -#include "base/message_loop/message_loop.h" -#include "base/numerics/safe_conversions.h" -#include "base/stl_util.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/string_util.h" -#include "base/strings/utf_offset_string_conversions.h" -#include "base/strings/utf_string_conversions.h" -#include "base/win/message_window.h" -#include "base/win/scoped_gdi_object.h" -#include "base/win/scoped_hdc.h" -#include "third_party/skia/include/core/SkBitmap.h" -#include "ui/base/clipboard/clipboard_util_win.h" -#include "ui/base/clipboard/custom_data_helper.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/size.h" - -namespace ui { - -namespace { - -// A scoper to manage acquiring and automatically releasing the clipboard. -class ScopedClipboard { - public: - ScopedClipboard() : opened_(false) { } - - ~ScopedClipboard() { - if (opened_) - Release(); - } - - bool Acquire(HWND owner) { - const int kMaxAttemptsToOpenClipboard = 5; - - if (opened_) { - NOTREACHED(); - return false; - } - - // Attempt to open the clipboard, which will acquire the Windows clipboard - // lock. This may fail if another process currently holds this lock. - // We're willing to try a few times in the hopes of acquiring it. - // - // This turns out to be an issue when using remote desktop because the - // rdpclip.exe process likes to read what we've written to the clipboard and - // send it to the RDP client. If we open and close the clipboard in quick - // succession, we might be trying to open it while rdpclip.exe has it open, - // See Bug 815425. - // - // In fact, we believe we'll only spin this loop over remote desktop. In - // normal situations, the user is initiating clipboard operations and there - // shouldn't be contention. - - for (int attempts = 0; attempts < kMaxAttemptsToOpenClipboard; ++attempts) { - // If we didn't manage to open the clipboard, sleep a bit and be hopeful. - if (attempts != 0) - ::Sleep(5); - - if (::OpenClipboard(owner)) { - opened_ = true; - return true; - } - } - - // We failed to acquire the clipboard. - return false; - } - - void Release() { - if (opened_) { - ::CloseClipboard(); - opened_ = false; - } else { - NOTREACHED(); - } - } - - private: - bool opened_; -}; - -bool ClipboardOwnerWndProc(UINT message, - WPARAM wparam, - LPARAM lparam, - LRESULT* result) { - switch (message) { - case WM_RENDERFORMAT: - // This message comes when SetClipboardData was sent a null data handle - // and now it's come time to put the data on the clipboard. - // We always set data, so there isn't a need to actually do anything here. - break; - case WM_RENDERALLFORMATS: - // This message comes when SetClipboardData was sent a null data handle - // and now this application is about to quit, so it must put data on - // the clipboard before it exits. - // We always set data, so there isn't a need to actually do anything here. - break; - case WM_DRAWCLIPBOARD: - break; - case WM_DESTROY: - break; - case WM_CHANGECBCHAIN: - break; - default: - return false; - } - - *result = 0; - return true; -} - -template <typename charT> -HGLOBAL CreateGlobalData(const std::basic_string<charT>& str) { - HGLOBAL data = - ::GlobalAlloc(GMEM_MOVEABLE, ((str.size() + 1) * sizeof(charT))); - if (data) { - charT* raw_data = static_cast<charT*>(::GlobalLock(data)); - memcpy(raw_data, str.data(), str.size() * sizeof(charT)); - raw_data[str.size()] = '\0'; - ::GlobalUnlock(data); - } - return data; -}; - -bool BitmapHasInvalidPremultipliedColors(const SkBitmap& bitmap) { - for (int x = 0; x < bitmap.width(); ++x) { - for (int y = 0; y < bitmap.height(); ++y) { - uint32_t pixel = *bitmap.getAddr32(x, y); - if (SkColorGetR(pixel) > SkColorGetA(pixel) || - SkColorGetG(pixel) > SkColorGetA(pixel) || - SkColorGetB(pixel) > SkColorGetA(pixel)) - return true; - } - } - return false; -} - -void MakeBitmapOpaque(const SkBitmap& bitmap) { - for (int x = 0; x < bitmap.width(); ++x) { - for (int y = 0; y < bitmap.height(); ++y) { - *bitmap.getAddr32(x, y) = SkColorSetA(*bitmap.getAddr32(x, y), 0xFF); - } - } -} - -void ParseBookmarkClipboardFormat(const base::string16& bookmark, - base::string16* title, - std::string* url) { - const base::string16 kDelim = base::ASCIIToUTF16("\r\n"); - - const size_t title_end = bookmark.find_first_of(kDelim); - if (title) - title->assign(bookmark.substr(0, title_end)); - - if (url) { - const size_t url_start = bookmark.find_first_not_of(kDelim, title_end); - if (url_start != base::string16::npos) { - *url = - base::UTF16ToUTF8(bookmark.substr(url_start, base::string16::npos)); - } - } -} - -void FreeData(unsigned int format, HANDLE data) { - if (format == CF_BITMAP) - ::DeleteObject(static_cast<HBITMAP>(data)); - else - ::GlobalFree(data); -} - -} // namespace - -// Clipboard::FormatType implementation. -Clipboard::FormatType::FormatType() : data_() {} - -Clipboard::FormatType::FormatType(UINT native_format) : data_() { - // There's no good way to actually initialize this in the constructor in - // C++03. - data_.cfFormat = static_cast<CLIPFORMAT>(native_format); - data_.dwAspect = DVASPECT_CONTENT; - data_.lindex = -1; - data_.tymed = TYMED_HGLOBAL; -} - -Clipboard::FormatType::FormatType(UINT native_format, LONG index) : data_() { - // There's no good way to actually initialize this in the constructor in - // C++03. - data_.cfFormat = static_cast<CLIPFORMAT>(native_format); - data_.dwAspect = DVASPECT_CONTENT; - data_.lindex = index; - data_.tymed = TYMED_HGLOBAL; -} - -Clipboard::FormatType::~FormatType() { -} - -std::string Clipboard::FormatType::Serialize() const { - return base::IntToString(data_.cfFormat); -} - -// static -Clipboard::FormatType Clipboard::FormatType::Deserialize( - const std::string& serialization) { - int clipboard_format = -1; - if (!base::StringToInt(serialization, &clipboard_format)) { - NOTREACHED(); - return FormatType(); - } - return FormatType(clipboard_format); -} - -bool Clipboard::FormatType::operator<(const FormatType& other) const { - return data_.cfFormat < other.data_.cfFormat; -} - -bool Clipboard::FormatType::Equals(const FormatType& other) const { - return data_.cfFormat == other.data_.cfFormat; -} - -// Various predefined FormatTypes. -// static -Clipboard::FormatType Clipboard::GetFormatType( - const std::string& format_string) { - return FormatType( - ::RegisterClipboardFormat(base::ASCIIToWide(format_string).c_str())); -} - -// static -const Clipboard::FormatType& Clipboard::GetUrlFormatType() { - CR_DEFINE_STATIC_LOCAL( - FormatType, type, (::RegisterClipboardFormat(CFSTR_INETURLA))); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetUrlWFormatType() { - CR_DEFINE_STATIC_LOCAL( - FormatType, type, (::RegisterClipboardFormat(CFSTR_INETURLW))); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetMozUrlFormatType() { - CR_DEFINE_STATIC_LOCAL( - FormatType, type, (::RegisterClipboardFormat(L"text/x-moz-url"))); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetPlainTextFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (CF_TEXT)); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetPlainTextWFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (CF_UNICODETEXT)); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetFilenameFormatType() { - CR_DEFINE_STATIC_LOCAL( - FormatType, type, (::RegisterClipboardFormat(CFSTR_FILENAMEA))); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetFilenameWFormatType() { - CR_DEFINE_STATIC_LOCAL( - FormatType, type, (::RegisterClipboardFormat(CFSTR_FILENAMEW))); - return type; -} - -// MS HTML Format -// static -const Clipboard::FormatType& Clipboard::GetHtmlFormatType() { - CR_DEFINE_STATIC_LOCAL( - FormatType, type, (::RegisterClipboardFormat(L"HTML Format"))); - return type; -} - -// MS RTF Format -// static -const Clipboard::FormatType& Clipboard::GetRtfFormatType() { - CR_DEFINE_STATIC_LOCAL( - FormatType, type, (::RegisterClipboardFormat(L"Rich Text Format"))); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetBitmapFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (CF_BITMAP)); - return type; -} - -// Firefox text/html -// static -const Clipboard::FormatType& Clipboard::GetTextHtmlFormatType() { - CR_DEFINE_STATIC_LOCAL( - FormatType, type, (::RegisterClipboardFormat(L"text/html"))); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetCFHDropFormatType() { - CR_DEFINE_STATIC_LOCAL(FormatType, type, (CF_HDROP)); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetFileDescriptorFormatType() { - CR_DEFINE_STATIC_LOCAL( - FormatType, type, (::RegisterClipboardFormat(CFSTR_FILEDESCRIPTOR))); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetFileContentZeroFormatType() { - CR_DEFINE_STATIC_LOCAL( - FormatType, type, (::RegisterClipboardFormat(CFSTR_FILECONTENTS), 0)); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetIDListFormatType() { - CR_DEFINE_STATIC_LOCAL( - FormatType, type, (::RegisterClipboardFormat(CFSTR_SHELLIDLIST))); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetWebKitSmartPasteFormatType() { - CR_DEFINE_STATIC_LOCAL( - FormatType, - type, - (::RegisterClipboardFormat(L"WebKit Smart Paste Format"))); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetWebCustomDataFormatType() { - // TODO(dcheng): This name is temporary. See http://crbug.com/106449. - CR_DEFINE_STATIC_LOCAL( - FormatType, - type, - (::RegisterClipboardFormat(L"Chromium Web Custom MIME Data Format"))); - return type; -} - -// static -const Clipboard::FormatType& Clipboard::GetPepperCustomDataFormatType() { - CR_DEFINE_STATIC_LOCAL( - FormatType, - type, - (::RegisterClipboardFormat(L"Chromium Pepper MIME Data Format"))); - return type; -} - -// Clipboard factory method. -// static -Clipboard* Clipboard::Create() { - return new ClipboardWin; -} - -// ClipboardWin implementation. -ClipboardWin::ClipboardWin() { - if (base::MessageLoopForUI::IsCurrent()) - clipboard_owner_.reset(new base::win::MessageWindow()); -} - -ClipboardWin::~ClipboardWin() { -} - -uint64 ClipboardWin::GetSequenceNumber(ClipboardType type) { - DCHECK_EQ(type, CLIPBOARD_TYPE_COPY_PASTE); - return ::GetClipboardSequenceNumber(); -} - -bool ClipboardWin::IsFormatAvailable(const Clipboard::FormatType& format, - ClipboardType type) const { - DCHECK_EQ(type, CLIPBOARD_TYPE_COPY_PASTE); - return ::IsClipboardFormatAvailable(format.ToFormatEtc().cfFormat) != FALSE; -} - -void ClipboardWin::Clear(ClipboardType type) { - DCHECK_EQ(type, CLIPBOARD_TYPE_COPY_PASTE); - ScopedClipboard clipboard; - if (!clipboard.Acquire(GetClipboardWindow())) - return; - - ::EmptyClipboard(); -} - -void ClipboardWin::ReadAvailableTypes(ClipboardType type, - std::vector<base::string16>* types, - bool* contains_filenames) const { - if (!types || !contains_filenames) { - NOTREACHED(); - return; - } - - types->clear(); - if (::IsClipboardFormatAvailable( - GetPlainTextFormatType().ToFormatEtc().cfFormat)) - types->push_back(base::UTF8ToUTF16(kMimeTypeText)); - if (::IsClipboardFormatAvailable(GetHtmlFormatType().ToFormatEtc().cfFormat)) - types->push_back(base::UTF8ToUTF16(kMimeTypeHTML)); - if (::IsClipboardFormatAvailable(GetRtfFormatType().ToFormatEtc().cfFormat)) - types->push_back(base::UTF8ToUTF16(kMimeTypeRTF)); - if (::IsClipboardFormatAvailable(CF_DIB)) - types->push_back(base::UTF8ToUTF16(kMimeTypePNG)); - *contains_filenames = false; - - // Acquire the clipboard. - ScopedClipboard clipboard; - if (!clipboard.Acquire(GetClipboardWindow())) - return; - - HANDLE hdata = - ::GetClipboardData(GetWebCustomDataFormatType().ToFormatEtc().cfFormat); - if (!hdata) - return; - - ReadCustomDataTypes(::GlobalLock(hdata), ::GlobalSize(hdata), types); - ::GlobalUnlock(hdata); -} - -void ClipboardWin::ReadText(ClipboardType type, base::string16* result) const { - DCHECK_EQ(type, CLIPBOARD_TYPE_COPY_PASTE); - if (!result) { - NOTREACHED(); - return; - } - - result->clear(); - - // Acquire the clipboard. - ScopedClipboard clipboard; - if (!clipboard.Acquire(GetClipboardWindow())) - return; - - HANDLE data = ::GetClipboardData(CF_UNICODETEXT); - if (!data) - return; - - result->assign(static_cast<const base::char16*>(::GlobalLock(data))); - ::GlobalUnlock(data); -} - -void ClipboardWin::ReadAsciiText(ClipboardType type, - std::string* result) const { - DCHECK_EQ(type, CLIPBOARD_TYPE_COPY_PASTE); - if (!result) { - NOTREACHED(); - return; - } - - result->clear(); - - // Acquire the clipboard. - ScopedClipboard clipboard; - if (!clipboard.Acquire(GetClipboardWindow())) - return; - - HANDLE data = ::GetClipboardData(CF_TEXT); - if (!data) - return; - - result->assign(static_cast<const char*>(::GlobalLock(data))); - ::GlobalUnlock(data); -} - -void ClipboardWin::ReadHTML(ClipboardType type, - base::string16* markup, - std::string* src_url, - uint32* fragment_start, - uint32* fragment_end) const { - DCHECK_EQ(type, CLIPBOARD_TYPE_COPY_PASTE); - - markup->clear(); - // TODO(dcheng): Remove these checks, I don't think they should be optional. - DCHECK(src_url); - if (src_url) - src_url->clear(); - *fragment_start = 0; - *fragment_end = 0; - - // Acquire the clipboard. - ScopedClipboard clipboard; - if (!clipboard.Acquire(GetClipboardWindow())) - return; - - HANDLE data = ::GetClipboardData(GetHtmlFormatType().ToFormatEtc().cfFormat); - if (!data) - return; - - std::string cf_html(static_cast<const char*>(::GlobalLock(data))); - ::GlobalUnlock(data); - - size_t html_start = std::string::npos; - size_t start_index = std::string::npos; - size_t end_index = std::string::npos; - ClipboardUtil::CFHtmlExtractMetadata(cf_html, src_url, &html_start, - &start_index, &end_index); - - // This might happen if the contents of the clipboard changed and CF_HTML is - // no longer available. - if (start_index == std::string::npos || - end_index == std::string::npos || - html_start == std::string::npos) - return; - - if (start_index < html_start || end_index < start_index) - return; - - std::vector<size_t> offsets; - offsets.push_back(start_index - html_start); - offsets.push_back(end_index - html_start); - markup->assign(base::UTF8ToUTF16AndAdjustOffsets(cf_html.data() + html_start, - &offsets)); - *fragment_start = base::checked_cast<uint32>(offsets[0]); - *fragment_end = base::checked_cast<uint32>(offsets[1]); -} - -void ClipboardWin::ReadRTF(ClipboardType type, std::string* result) const { - DCHECK_EQ(type, CLIPBOARD_TYPE_COPY_PASTE); - - ReadData(GetRtfFormatType(), result); -} - -SkBitmap ClipboardWin::ReadImage(ClipboardType type) const { - DCHECK_EQ(type, CLIPBOARD_TYPE_COPY_PASTE); - - // Acquire the clipboard. - ScopedClipboard clipboard; - if (!clipboard.Acquire(GetClipboardWindow())) - return SkBitmap(); - - // We use a DIB rather than a DDB here since ::GetObject() with the - // HBITMAP returned from ::GetClipboardData(CF_BITMAP) always reports a color - // depth of 32bpp. - BITMAPINFO* bitmap = static_cast<BITMAPINFO*>(::GetClipboardData(CF_DIB)); - if (!bitmap) - return SkBitmap(); - int color_table_length = 0; - switch (bitmap->bmiHeader.biBitCount) { - case 1: - case 4: - case 8: - color_table_length = bitmap->bmiHeader.biClrUsed - ? bitmap->bmiHeader.biClrUsed - : 1 << bitmap->bmiHeader.biBitCount; - break; - case 16: - case 32: - if (bitmap->bmiHeader.biCompression == BI_BITFIELDS) - color_table_length = 3; - break; - case 24: - break; - default: - NOTREACHED(); - } - const void* bitmap_bits = reinterpret_cast<const char*>(bitmap) - + bitmap->bmiHeader.biSize + color_table_length * sizeof(RGBQUAD); - - gfx::Canvas canvas(gfx::Size(bitmap->bmiHeader.biWidth, - bitmap->bmiHeader.biHeight), - 1.0f, - false); - { - skia::ScopedPlatformPaint scoped_platform_paint(canvas.sk_canvas()); - HDC dc = scoped_platform_paint.GetPlatformSurface(); - ::SetDIBitsToDevice(dc, 0, 0, bitmap->bmiHeader.biWidth, - bitmap->bmiHeader.biHeight, 0, 0, 0, - bitmap->bmiHeader.biHeight, bitmap_bits, bitmap, - DIB_RGB_COLORS); - } - // Windows doesn't really handle alpha channels well in many situations. When - // the source image is < 32 bpp, we force the bitmap to be opaque. When the - // source image is 32 bpp, the alpha channel might still contain garbage data. - // Since Windows uses premultiplied alpha, we scan for instances where - // (R, G, B) > A. If there are any invalid premultiplied colors in the image, - // we assume the alpha channel contains garbage and force the bitmap to be - // opaque as well. Note that this heuristic will fail on a transparent bitmap - // containing only black pixels... - const SkBitmap& device_bitmap = - canvas.sk_canvas()->getDevice()->accessBitmap(true); - { - SkAutoLockPixels lock(device_bitmap); - bool has_invalid_alpha_channel = bitmap->bmiHeader.biBitCount < 32 || - BitmapHasInvalidPremultipliedColors(device_bitmap); - if (has_invalid_alpha_channel) { - MakeBitmapOpaque(device_bitmap); - } - } - - return canvas.ExtractImageRep().sk_bitmap(); -} - -void ClipboardWin::ReadCustomData(ClipboardType clipboard_type, - const base::string16& type, - base::string16* result) const { - DCHECK_EQ(clipboard_type, CLIPBOARD_TYPE_COPY_PASTE); - - // Acquire the clipboard. - ScopedClipboard clipboard; - if (!clipboard.Acquire(GetClipboardWindow())) - return; - - HANDLE hdata = - ::GetClipboardData(GetWebCustomDataFormatType().ToFormatEtc().cfFormat); - if (!hdata) - return; - - ReadCustomDataForType(::GlobalLock(hdata), ::GlobalSize(hdata), type, result); - ::GlobalUnlock(hdata); -} - -void ClipboardWin::ReadBookmark(base::string16* title, std::string* url) const { - if (title) - title->clear(); - - if (url) - url->clear(); - - // Acquire the clipboard. - ScopedClipboard clipboard; - if (!clipboard.Acquire(GetClipboardWindow())) - return; - - HANDLE data = ::GetClipboardData(GetUrlWFormatType().ToFormatEtc().cfFormat); - if (!data) - return; - - base::string16 bookmark(static_cast<const base::char16*>(::GlobalLock(data))); - ::GlobalUnlock(data); - - ParseBookmarkClipboardFormat(bookmark, title, url); -} - -void ClipboardWin::ReadData(const FormatType& format, - std::string* result) const { - if (!result) { - NOTREACHED(); - return; - } - - ScopedClipboard clipboard; - if (!clipboard.Acquire(GetClipboardWindow())) - return; - - HANDLE data = ::GetClipboardData(format.ToFormatEtc().cfFormat); - if (!data) - return; - - result->assign(static_cast<const char*>(::GlobalLock(data)), - ::GlobalSize(data)); - ::GlobalUnlock(data); -} - -void ClipboardWin::WriteObjects(ClipboardType type, const ObjectMap& objects) { - DCHECK_EQ(type, CLIPBOARD_TYPE_COPY_PASTE); - - ScopedClipboard clipboard; - if (!clipboard.Acquire(GetClipboardWindow())) - return; - - ::EmptyClipboard(); - - for (ObjectMap::const_iterator iter = objects.begin(); iter != objects.end(); - ++iter) { - DispatchObject(static_cast<ObjectType>(iter->first), iter->second); - } -} - -void ClipboardWin::WriteText(const char* text_data, size_t text_len) { - base::string16 text; - base::UTF8ToUTF16(text_data, text_len, &text); - HGLOBAL glob = CreateGlobalData(text); - - WriteToClipboard(CF_UNICODETEXT, glob); -} - -void ClipboardWin::WriteHTML(const char* markup_data, - size_t markup_len, - const char* url_data, - size_t url_len) { - std::string markup(markup_data, markup_len); - std::string url; - - if (url_len > 0) - url.assign(url_data, url_len); - - std::string html_fragment = ClipboardUtil::HtmlToCFHtml(markup, url); - HGLOBAL glob = CreateGlobalData(html_fragment); - - WriteToClipboard(Clipboard::GetHtmlFormatType().ToFormatEtc().cfFormat, glob); -} - -void ClipboardWin::WriteRTF(const char* rtf_data, size_t data_len) { - WriteData(GetRtfFormatType(), rtf_data, data_len); -} - -void ClipboardWin::WriteBookmark(const char* title_data, - size_t title_len, - const char* url_data, - size_t url_len) { - std::string bookmark(title_data, title_len); - bookmark.append(1, L'\n'); - bookmark.append(url_data, url_len); - - base::string16 wide_bookmark = base::UTF8ToWide(bookmark); - HGLOBAL glob = CreateGlobalData(wide_bookmark); - - WriteToClipboard(GetUrlWFormatType().ToFormatEtc().cfFormat, glob); -} - -void ClipboardWin::WriteWebSmartPaste() { - DCHECK(clipboard_owner_->hwnd() != NULL); - ::SetClipboardData(GetWebKitSmartPasteFormatType().ToFormatEtc().cfFormat, - NULL); -} - -void ClipboardWin::WriteBitmap(const SkBitmap& bitmap) { - HDC dc = ::GetDC(NULL); - - // This doesn't actually cost us a memcpy when the bitmap comes from the - // renderer as we load it into the bitmap using setPixels which just sets a - // pointer. Someone has to memcpy it into GDI, it might as well be us here. - - // TODO(darin): share data in gfx/bitmap_header.cc somehow - BITMAPINFO bm_info = {0}; - bm_info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); - bm_info.bmiHeader.biWidth = bitmap.width(); - bm_info.bmiHeader.biHeight = -bitmap.height(); // sets vertical orientation - bm_info.bmiHeader.biPlanes = 1; - bm_info.bmiHeader.biBitCount = 32; - bm_info.bmiHeader.biCompression = BI_RGB; - - // ::CreateDIBSection allocates memory for us to copy our bitmap into. - // Unfortunately, we can't write the created bitmap to the clipboard, - // (see http://msdn2.microsoft.com/en-us/library/ms532292.aspx) - void* bits; - HBITMAP source_hbitmap = - ::CreateDIBSection(dc, &bm_info, DIB_RGB_COLORS, &bits, NULL, 0); - - if (bits && source_hbitmap) { - { - SkAutoLockPixels bitmap_lock(bitmap); - // Copy the bitmap out of shared memory and into GDI - memcpy(bits, bitmap.getPixels(), bitmap.getSize()); - } - - // Now we have an HBITMAP, we can write it to the clipboard - WriteBitmapFromHandle(source_hbitmap, - gfx::Size(bitmap.width(), bitmap.height())); - } - - ::DeleteObject(source_hbitmap); - ::ReleaseDC(NULL, dc); -} - -void ClipboardWin::WriteData(const FormatType& format, - const char* data_data, - size_t data_len) { - HGLOBAL hdata = ::GlobalAlloc(GMEM_MOVEABLE, data_len); - if (!hdata) - return; - - char* data = static_cast<char*>(::GlobalLock(hdata)); - memcpy(data, data_data, data_len); - ::GlobalUnlock(data); - WriteToClipboard(format.ToFormatEtc().cfFormat, hdata); -} - -void ClipboardWin::WriteBitmapFromHandle(HBITMAP source_hbitmap, - const gfx::Size& size) { - // We would like to just call ::SetClipboardData on the source_hbitmap, - // but that bitmap might not be of a sort we can write to the clipboard. - // For this reason, we create a new bitmap, copy the bits over, and then - // write that to the clipboard. - - HDC dc = ::GetDC(NULL); - HDC compatible_dc = ::CreateCompatibleDC(NULL); - HDC source_dc = ::CreateCompatibleDC(NULL); - - // This is the HBITMAP we will eventually write to the clipboard - HBITMAP hbitmap = ::CreateCompatibleBitmap(dc, size.width(), size.height()); - if (!hbitmap) { - // Failed to create the bitmap - ::DeleteDC(compatible_dc); - ::DeleteDC(source_dc); - ::ReleaseDC(NULL, dc); - return; - } - - HBITMAP old_hbitmap = (HBITMAP)SelectObject(compatible_dc, hbitmap); - HBITMAP old_source = (HBITMAP)SelectObject(source_dc, source_hbitmap); - - // Now we need to blend it into an HBITMAP we can place on the clipboard - BLENDFUNCTION bf = {AC_SRC_OVER, 0, 255, AC_SRC_ALPHA}; - ::GdiAlphaBlend(compatible_dc, - 0, - 0, - size.width(), - size.height(), - source_dc, - 0, - 0, - size.width(), - size.height(), - bf); - - // Clean up all the handles we just opened - ::SelectObject(compatible_dc, old_hbitmap); - ::SelectObject(source_dc, old_source); - ::DeleteObject(old_hbitmap); - ::DeleteObject(old_source); - ::DeleteDC(compatible_dc); - ::DeleteDC(source_dc); - ::ReleaseDC(NULL, dc); - - WriteToClipboard(CF_BITMAP, hbitmap); -} - -void ClipboardWin::WriteToClipboard(unsigned int format, HANDLE handle) { - DCHECK(clipboard_owner_->hwnd() != NULL); - if (handle && !::SetClipboardData(format, handle)) { - DCHECK(ERROR_CLIPBOARD_NOT_OPEN != GetLastError()); - FreeData(format, handle); - } -} - -HWND ClipboardWin::GetClipboardWindow() const { - if (!clipboard_owner_) - return NULL; - - if (clipboard_owner_->hwnd() == NULL) - clipboard_owner_->Create(base::Bind(&ClipboardOwnerWndProc)); - - return clipboard_owner_->hwnd(); -} - -} // namespace ui
diff --git a/ui/base/clipboard/clipboard_win.h b/ui/base/clipboard/clipboard_win.h deleted file mode 100644 index a0769ff..0000000 --- a/ui/base/clipboard/clipboard_win.h +++ /dev/null
@@ -1,77 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_CLIPBOARD_CLIPBOARD_WIN_H_ -#define UI_BASE_CLIPBOARD_CLIPBOARD_WIN_H_ - -#include "ui/base/clipboard/clipboard.h" - -#include "base/memory/scoped_ptr.h" - -namespace ui { - -class ClipboardWin : public Clipboard { - private: - friend class Clipboard; - - ClipboardWin(); - ~ClipboardWin() override; - - // Clipboard overrides: - uint64 GetSequenceNumber(ClipboardType type) override; - bool IsFormatAvailable(const FormatType& format, - ClipboardType type) const override; - void Clear(ClipboardType type) override; - void ReadAvailableTypes(ClipboardType type, - std::vector<base::string16>* types, - bool* contains_filenames) const override; - void ReadText(ClipboardType type, base::string16* result) const override; - void ReadAsciiText(ClipboardType type, std::string* result) const override; - void ReadHTML(ClipboardType type, - base::string16* markup, - std::string* src_url, - uint32* fragment_start, - uint32* fragment_end) const override; - void ReadRTF(ClipboardType type, std::string* result) const override; - SkBitmap ReadImage(ClipboardType type) const override; - void ReadCustomData(ClipboardType clipboard_type, - const base::string16& type, - base::string16* result) const override; - void ReadBookmark(base::string16* title, std::string* url) const override; - void ReadData(const FormatType& format, std::string* result) const override; - void WriteObjects(ClipboardType type, const ObjectMap& objects) override; - void WriteText(const char* text_data, size_t text_len) override; - void WriteHTML(const char* markup_data, - size_t markup_len, - const char* url_data, - size_t url_len) override; - void WriteRTF(const char* rtf_data, size_t data_len) override; - void WriteBookmark(const char* title_data, - size_t title_len, - const char* url_data, - size_t url_len) override; - void WriteWebSmartPaste() override; - void WriteBitmap(const SkBitmap& bitmap) override; - void WriteData(const FormatType& format, - const char* data_data, - size_t data_len) override; - - void WriteBitmapFromHandle(HBITMAP source_hbitmap, const gfx::Size& size); - - // Safely write to system clipboard. Free |handle| on failure. - void WriteToClipboard(unsigned int format, HANDLE handle); - - // Return the window that should be the clipboard owner, creating it - // if neccessary. Marked const for lazily initialization by const methods. - HWND GetClipboardWindow() const; - - // Mark this as mutable so const methods can still do lazy initialization. - mutable scoped_ptr<base::win::MessageWindow> clipboard_owner_; - - DISALLOW_COPY_AND_ASSIGN(ClipboardWin); -}; - -} // namespace ui - -#endif // UI_BASE_CLIPBOARD_CLIPBOARD_WIN_H_
diff --git a/ui/base/clipboard/custom_data_helper.cc b/ui/base/clipboard/custom_data_helper.cc deleted file mode 100644 index a37349e..0000000 --- a/ui/base/clipboard/custom_data_helper.cc +++ /dev/null
@@ -1,129 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -// -// TODO(dcheng): For efficiency reasons, consider passing custom data around -// as a vector instead. It allows us to append a -// std::pair<base::string16, base::string16> and swap the deserialized values. - -#include "ui/base/clipboard/custom_data_helper.h" - -#include <utility> - -#include "base/pickle.h" - -namespace ui { - -namespace { - -class SkippablePickle : public Pickle { - public: - SkippablePickle(const void* data, size_t data_len); - bool SkipString16(PickleIterator* iter); -}; - -SkippablePickle::SkippablePickle(const void* data, size_t data_len) - : Pickle(reinterpret_cast<const char*>(data), data_len) { -} - -bool SkippablePickle::SkipString16(PickleIterator* iter) { - DCHECK(iter); - - int len; - if (!iter->ReadLength(&len)) - return false; - return iter->SkipBytes(len * sizeof(base::char16)); -} - -} // namespace - -void ReadCustomDataTypes(const void* data, - size_t data_length, - std::vector<base::string16>* types) { - SkippablePickle pickle(data, data_length); - PickleIterator iter(pickle); - - size_t size = 0; - if (!iter.ReadSizeT(&size)) - return; - - // Keep track of the original elements in the types vector. On failure, we - // truncate the vector to the original size since we want to ignore corrupt - // custom data pickles. - size_t original_size = types->size(); - - for (size_t i = 0; i < size; ++i) { - types->push_back(base::string16()); - if (!iter.ReadString16(&types->back()) || - !pickle.SkipString16(&iter)) { - types->resize(original_size); - return; - } - } -} - -void ReadCustomDataForType(const void* data, - size_t data_length, - const base::string16& type, - base::string16* result) { - SkippablePickle pickle(data, data_length); - PickleIterator iter(pickle); - - size_t size = 0; - if (!iter.ReadSizeT(&size)) - return; - - for (size_t i = 0; i < size; ++i) { - base::string16 deserialized_type; - if (!iter.ReadString16(&deserialized_type)) - return; - if (deserialized_type == type) { - ignore_result(iter.ReadString16(result)); - return; - } - if (!pickle.SkipString16(&iter)) - return; - } -} - -void ReadCustomDataIntoMap(const void* data, - size_t data_length, - std::map<base::string16, base::string16>* result) { - Pickle pickle(reinterpret_cast<const char*>(data), data_length); - PickleIterator iter(pickle); - - size_t size = 0; - if (!iter.ReadSizeT(&size)) - return; - - for (size_t i = 0; i < size; ++i) { - base::string16 type; - if (!iter.ReadString16(&type)) { - // Data is corrupt, return an empty map. - result->clear(); - return; - } - std::pair<std::map<base::string16, base::string16>::iterator, bool> - insert_result = result->insert(std::make_pair(type, base::string16())); - if (!iter.ReadString16(&insert_result.first->second)) { - // Data is corrupt, return an empty map. - result->clear(); - return; - } - } -} - -void WriteCustomDataToPickle( - const std::map<base::string16, base::string16>& data, - Pickle* pickle) { - pickle->WriteSizeT(data.size()); - for (std::map<base::string16, base::string16>::const_iterator it = - data.begin(); - it != data.end(); - ++it) { - pickle->WriteString16(it->first); - pickle->WriteString16(it->second); - } -} - -} // namespace ui
diff --git a/ui/base/clipboard/custom_data_helper.h b/ui/base/clipboard/custom_data_helper.h deleted file mode 100644 index 8c927aa..0000000 --- a/ui/base/clipboard/custom_data_helper.h +++ /dev/null
@@ -1,55 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -// -// Due to restrictions of most operating systems, we don't directly map each -// type of custom data to a native data transfer type. Instead, we serialize -// each key-value pair into the pickle as a pair of string objects, and then -// write the binary data in the pickle to the native data transfer object. - -#ifndef UI_BASE_CLIPBOARD_CUSTOM_DATA_HELPER_H_ -#define UI_BASE_CLIPBOARD_CUSTOM_DATA_HELPER_H_ - -#include <map> -#include <vector> - -#include "base/strings/string16.h" -#include "ui/base/ui_base_export.h" - -class Pickle; - -#if defined(OS_MACOSX) -#ifdef __OBJC__ -@class NSString; -#else -class NSString; -#endif -#endif // defined(OS_MACOSX) - -namespace ui { - -#if defined(OS_MACOSX) && !defined(USE_AURA) -UI_BASE_EXPORT extern NSString* const kWebCustomDataPboardType; -#elif !defined(OS_WIN) && defined(USE_AURA) -UI_BASE_EXPORT extern const char kMimeTypeWebCustomData[]; -#endif - -UI_BASE_EXPORT void ReadCustomDataTypes(const void* data, - size_t data_length, - std::vector<base::string16>* types); -UI_BASE_EXPORT void ReadCustomDataForType(const void* data, - size_t data_length, - const base::string16& type, - base::string16* result); -UI_BASE_EXPORT void ReadCustomDataIntoMap( - const void* data, - size_t data_length, - std::map<base::string16, base::string16>* result); - -UI_BASE_EXPORT void WriteCustomDataToPickle( - const std::map<base::string16, base::string16>& data, - Pickle* pickle); - -} // namespace ui - -#endif // UI_BASE_CLIPBOARD_CLIPBOARD_H_
diff --git a/ui/base/clipboard/custom_data_helper_linux.cc b/ui/base/clipboard/custom_data_helper_linux.cc deleted file mode 100644 index d8cc89e..0000000 --- a/ui/base/clipboard/custom_data_helper_linux.cc +++ /dev/null
@@ -1,13 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "build/build_config.h" -#include "ui/base/clipboard/custom_data_helper.h" - -namespace ui { - -// TODO(dcheng): This name is temporary. See crbug.com/106449 -const char kMimeTypeWebCustomData[] = "chromium/x-web-custom-data"; - -} // namespace ui
diff --git a/ui/base/clipboard/custom_data_helper_mac.mm b/ui/base/clipboard/custom_data_helper_mac.mm deleted file mode 100644 index ae43621..0000000 --- a/ui/base/clipboard/custom_data_helper_mac.mm +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/clipboard/custom_data_helper.h" - -#import <Foundation/Foundation.h> - -namespace ui { - -// TODO(dcheng): This name is temporary. See crbug.com/106449. -#if defined(USE_AURA) -const char kMimeTypeWebCustomData[] = "chromium/x-web-custom-data"; -#else -NSString* const kWebCustomDataPboardType = @"org.chromium.web-custom-data"; -#endif - -} // namespace ui
diff --git a/ui/base/clipboard/custom_data_helper_unittest.cc b/ui/base/clipboard/custom_data_helper_unittest.cc deleted file mode 100644 index a765852..0000000 --- a/ui/base/clipboard/custom_data_helper_unittest.cc +++ /dev/null
@@ -1,170 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/clipboard/custom_data_helper.h" - -#include <utility> - -#include "base/pickle.h" -#include "base/strings/utf_string_conversions.h" -#include "testing/gtest/include/gtest/gtest.h" - -using base::ASCIIToUTF16; - -namespace ui { - -namespace { - -void PrepareEmptyTestData(Pickle* pickle) { - std::map<base::string16, base::string16> data; - WriteCustomDataToPickle(data, pickle); -} - -void PrepareTestData(Pickle* pickle) { - std::map<base::string16, base::string16> data; - data.insert(std::make_pair(ASCIIToUTF16("abc"), base::string16())); - data.insert(std::make_pair(ASCIIToUTF16("de"), ASCIIToUTF16("1"))); - data.insert(std::make_pair(ASCIIToUTF16("f"), ASCIIToUTF16("23"))); - WriteCustomDataToPickle(data, pickle); -} - -TEST(CustomDataHelperTest, EmptyReadTypes) { - Pickle pickle; - PrepareEmptyTestData(&pickle); - - std::vector<base::string16> types; - ReadCustomDataTypes(pickle.data(), pickle.size(), &types); - EXPECT_EQ(0u, types.size()); -} - -TEST(CustomDataHelperTest, EmptyReadSingleType) { - Pickle pickle; - PrepareEmptyTestData(&pickle); - - base::string16 result; - ReadCustomDataForType(pickle.data(), - pickle.size(), - ASCIIToUTF16("f"), - &result); - EXPECT_EQ(base::string16(), result); -} - -TEST(CustomDataHelperTest, EmptyReadMap) { - Pickle pickle; - PrepareEmptyTestData(&pickle); - - std::map<base::string16, base::string16> result; - ReadCustomDataIntoMap(pickle.data(), pickle.size(), &result); - EXPECT_EQ(0u, result.size()); -} - -TEST(CustomDataHelperTest, ReadTypes) { - Pickle pickle; - PrepareTestData(&pickle); - - std::vector<base::string16> types; - ReadCustomDataTypes(pickle.data(), pickle.size(), &types); - - std::vector<base::string16> expected; - expected.push_back(ASCIIToUTF16("abc")); - expected.push_back(ASCIIToUTF16("de")); - expected.push_back(ASCIIToUTF16("f")); - EXPECT_EQ(expected, types); -} - -TEST(CustomDataHelperTest, ReadSingleType) { - Pickle pickle; - PrepareTestData(&pickle); - - base::string16 result; - ReadCustomDataForType(pickle.data(), - pickle.size(), - ASCIIToUTF16("abc"), - &result); - EXPECT_EQ(base::string16(), result); - - ReadCustomDataForType(pickle.data(), - pickle.size(), - ASCIIToUTF16("de"), - &result); - EXPECT_EQ(ASCIIToUTF16("1"), result); - - ReadCustomDataForType(pickle.data(), - pickle.size(), - ASCIIToUTF16("f"), - &result); - EXPECT_EQ(ASCIIToUTF16("23"), result); -} - -TEST(CustomDataHelperTest, ReadMap) { - Pickle pickle; - PrepareTestData(&pickle); - - std::map<base::string16, base::string16> result; - ReadCustomDataIntoMap(pickle.data(), pickle.size(), &result); - - std::map<base::string16, base::string16> expected; - expected.insert(std::make_pair(ASCIIToUTF16("abc"), base::string16())); - expected.insert(std::make_pair(ASCIIToUTF16("de"), ASCIIToUTF16("1"))); - expected.insert(std::make_pair(ASCIIToUTF16("f"), ASCIIToUTF16("23"))); - EXPECT_EQ(expected, result); -} - -TEST(CustomDataHelperTest, BadReadTypes) { - // ReadCustomDataTypes makes the additional guarantee that the contents of the - // result vector will not change if the input is malformed. - std::vector<base::string16> expected; - expected.push_back(ASCIIToUTF16("abc")); - expected.push_back(ASCIIToUTF16("de")); - expected.push_back(ASCIIToUTF16("f")); - - Pickle malformed; - malformed.WriteSizeT(1000); - malformed.WriteString16(ASCIIToUTF16("hello")); - malformed.WriteString16(ASCIIToUTF16("world")); - std::vector<base::string16> actual(expected); - ReadCustomDataTypes(malformed.data(), malformed.size(), &actual); - EXPECT_EQ(expected, actual); - - Pickle malformed2; - malformed2.WriteSizeT(1); - malformed2.WriteString16(ASCIIToUTF16("hello")); - std::vector<base::string16> actual2(expected); - ReadCustomDataTypes(malformed2.data(), malformed2.size(), &actual2); - EXPECT_EQ(expected, actual2); -} - -TEST(CustomDataHelperTest, BadPickle) { - base::string16 result_data; - std::map<base::string16, base::string16> result_map; - - Pickle malformed; - malformed.WriteSizeT(1000); - malformed.WriteString16(ASCIIToUTF16("hello")); - malformed.WriteString16(ASCIIToUTF16("world")); - - ReadCustomDataForType(malformed.data(), - malformed.size(), - ASCIIToUTF16("f"), - &result_data); - ReadCustomDataIntoMap(malformed.data(), malformed.size(), &result_map); - EXPECT_EQ(0u, result_data.size()); - EXPECT_EQ(0u, result_map.size()); - - Pickle malformed2; - malformed2.WriteSizeT(1); - malformed2.WriteString16(ASCIIToUTF16("hello")); - - ReadCustomDataForType(malformed2.data(), - malformed2.size(), - ASCIIToUTF16("f"), - &result_data); - ReadCustomDataIntoMap(malformed2.data(), malformed2.size(), &result_map); - EXPECT_EQ(0u, result_data.size()); - EXPECT_EQ(0u, result_map.size()); -} - -} // namespace - -} // namespace ui
diff --git a/ui/base/clipboard/scoped_clipboard_writer.cc b/ui/base/clipboard/scoped_clipboard_writer.cc deleted file mode 100644 index 50a7ba3..0000000 --- a/ui/base/clipboard/scoped_clipboard_writer.cc +++ /dev/null
@@ -1,127 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file implements the ScopedClipboardWriter class. Documentation on its -// purpose can be found in our header. Documentation on the format of the -// parameters for each clipboard target can be found in clipboard.h. - -#include "ui/base/clipboard/scoped_clipboard_writer.h" - -#include "base/pickle.h" -#include "base/strings/utf_string_conversions.h" -#include "net/base/escape.h" -#include "ui/gfx/size.h" - -namespace ui { - -ScopedClipboardWriter::ScopedClipboardWriter(ClipboardType type) : type_(type) { -} - -ScopedClipboardWriter::~ScopedClipboardWriter() { - if (!objects_.empty()) - ui::Clipboard::GetForCurrentThread()->WriteObjects(type_, objects_); -} - -void ScopedClipboardWriter::WriteText(const base::string16& text) { - WriteTextOrURL(text, false); -} - -void ScopedClipboardWriter::WriteURL(const base::string16& text) { - WriteTextOrURL(text, true); -} - -void ScopedClipboardWriter::WriteHTML(const base::string16& markup, - const std::string& source_url) { - std::string utf8_markup = base::UTF16ToUTF8(markup); - - Clipboard::ObjectMapParams parameters; - parameters.push_back( - Clipboard::ObjectMapParam(utf8_markup.begin(), - utf8_markup.end())); - if (!source_url.empty()) { - parameters.push_back(Clipboard::ObjectMapParam(source_url.begin(), - source_url.end())); - } - - objects_[Clipboard::CBF_HTML] = parameters; -} - -void ScopedClipboardWriter::WriteRTF(const std::string& rtf_data) { - Clipboard::ObjectMapParams parameters; - parameters.push_back(Clipboard::ObjectMapParam(rtf_data.begin(), - rtf_data.end())); - objects_[Clipboard::CBF_RTF] = parameters; -} - -void ScopedClipboardWriter::WriteBookmark(const base::string16& bookmark_title, - const std::string& url) { - if (bookmark_title.empty() || url.empty()) - return; - - std::string utf8_markup = base::UTF16ToUTF8(bookmark_title); - - Clipboard::ObjectMapParams parameters; - parameters.push_back(Clipboard::ObjectMapParam(utf8_markup.begin(), - utf8_markup.end())); - parameters.push_back(Clipboard::ObjectMapParam(url.begin(), url.end())); - objects_[Clipboard::CBF_BOOKMARK] = parameters; -} - -void ScopedClipboardWriter::WriteHyperlink(const base::string16& anchor_text, - const std::string& url) { - if (anchor_text.empty() || url.empty()) - return; - - // Construct the hyperlink. - std::string html("<a href=\""); - html.append(net::EscapeForHTML(url)); - html.append("\">"); - html.append(net::EscapeForHTML(base::UTF16ToUTF8(anchor_text))); - html.append("</a>"); - WriteHTML(base::UTF8ToUTF16(html), std::string()); -} - -void ScopedClipboardWriter::WriteWebSmartPaste() { - objects_[Clipboard::CBF_WEBKIT] = Clipboard::ObjectMapParams(); -} - -void ScopedClipboardWriter::WritePickledData( - const Pickle& pickle, const Clipboard::FormatType& format) { - std::string format_string = format.Serialize(); - Clipboard::ObjectMapParam format_parameter(format_string.begin(), - format_string.end()); - Clipboard::ObjectMapParam data_parameter; - - data_parameter.resize(pickle.size()); - memcpy(const_cast<char*>(&data_parameter.front()), - pickle.data(), pickle.size()); - - Clipboard::ObjectMapParams parameters; - parameters.push_back(format_parameter); - parameters.push_back(data_parameter); - objects_[Clipboard::CBF_DATA] = parameters; -} - -void ScopedClipboardWriter::Reset() { - url_text_.clear(); - objects_.clear(); -} - -void ScopedClipboardWriter::WriteTextOrURL(const base::string16& text, - bool is_url) { - std::string utf8_text = base::UTF16ToUTF8(text); - - Clipboard::ObjectMapParams parameters; - parameters.push_back(Clipboard::ObjectMapParam(utf8_text.begin(), - utf8_text.end())); - objects_[Clipboard::CBF_TEXT] = parameters; - - if (is_url) { - url_text_ = utf8_text; - } else { - url_text_.clear(); - } -} - -} // namespace ui
diff --git a/ui/base/clipboard/scoped_clipboard_writer.h b/ui/base/clipboard/scoped_clipboard_writer.h deleted file mode 100644 index ab799bd..0000000 --- a/ui/base/clipboard/scoped_clipboard_writer.h +++ /dev/null
@@ -1,88 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file declares the ScopedClipboardWriter class, a wrapper around -// the Clipboard class which simplifies writing data to the system clipboard. -// Upon deletion the class atomically writes all data to the clipboard, -// avoiding any potential race condition with other processes that are also -// writing to the system clipboard. - -#ifndef UI_BASE_CLIPBOARD_SCOPED_CLIPBOARD_WRITER_H_ -#define UI_BASE_CLIPBOARD_SCOPED_CLIPBOARD_WRITER_H_ - -#include <string> - -#include "base/strings/string16.h" -#include "ui/base/clipboard/clipboard.h" -#include "ui/base/ui_base_export.h" - -class Pickle; - -namespace ui { - -// This class is a wrapper for |Clipboard| that handles packing data -// into a Clipboard::ObjectMap. -class UI_BASE_EXPORT ScopedClipboardWriter { - public: - // Create an instance that is a simple wrapper around the clipboard of the - // given type. - explicit ScopedClipboardWriter(ClipboardType type); - - ~ScopedClipboardWriter(); - - // Converts |text| to UTF-8 and adds it to the clipboard. - void WriteText(const base::string16& text); - - // Converts the text of the URL to UTF-8 and adds it to the clipboard, then - // notifies the Clipboard that we just wrote a URL. - void WriteURL(const base::string16& text); - - // Adds HTML to the clipboard. The url parameter is optional, but especially - // useful if the HTML fragment contains relative links. - void WriteHTML(const base::string16& markup, const std::string& source_url); - - // Adds RTF to the clipboard. - void WriteRTF(const std::string& rtf_data); - - // Adds a bookmark to the clipboard. - void WriteBookmark(const base::string16& bookmark_title, - const std::string& url); - - // Adds an html hyperlink (<a href>) to the clipboard. |anchor_text| and - // |url| will be escaped as needed. - void WriteHyperlink(const base::string16& anchor_text, - const std::string& url); - - // Used by WebKit to determine whether WebKit wrote the clipboard last - void WriteWebSmartPaste(); - - // Adds arbitrary pickled data to clipboard. - void WritePickledData(const Pickle& pickle, - const Clipboard::FormatType& format); - - // Removes all objects that would be written to the clipboard. - void Reset(); - - protected: - // Converts |text| to UTF-8 and adds it to the clipboard. If it's a URL, we - // also notify the clipboard of that fact. - void WriteTextOrURL(const base::string16& text, bool is_url); - - // We accumulate the data passed to the various targets in the |objects_| - // vector, and pass it to Clipboard::WriteObjects() during object destruction. - Clipboard::ObjectMap objects_; - const ClipboardType type_; - - // We keep around the UTF-8 text of the URL in order to pass it to - // Clipboard::DidWriteURL(). - std::string url_text_; - - private: - DISALLOW_COPY_AND_ASSIGN(ScopedClipboardWriter); -}; - -} // namespace ui - -#endif // UI_BASE_CLIPBOARD_SCOPED_CLIPBOARD_WRITER_H_ -
diff --git a/ui/base/cursor/cursor_loader_ozone.cc b/ui/base/cursor/cursor_loader_ozone.cc deleted file mode 100644 index 08b831e..0000000 --- a/ui/base/cursor/cursor_loader_ozone.cc +++ /dev/null
@@ -1,75 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/cursor/cursor_loader_ozone.h" - -#include <vector> - -#include "ui/base/cursor/cursor.h" -#include "ui/base/cursor/cursor_util.h" -#include "ui/ozone/public/cursor_factory_ozone.h" - -namespace ui { - -CursorLoaderOzone::CursorLoaderOzone() {} - -CursorLoaderOzone::~CursorLoaderOzone() {} - -void CursorLoaderOzone::LoadImageCursor(int id, - int resource_id, - const gfx::Point& hot) { - SkBitmap bitmap; - gfx::Point hotspot = hot; - - GetImageCursorBitmap(resource_id, scale(), rotation(), &hotspot, &bitmap); - - cursors_[id] = - CursorFactoryOzone::GetInstance()->CreateImageCursor(bitmap, hotspot); -} - -void CursorLoaderOzone::LoadAnimatedCursor(int id, - int resource_id, - const gfx::Point& hot, - int frame_delay_ms) { - std::vector<SkBitmap> bitmaps; - gfx::Point hotspot = hot; - - GetAnimatedCursorBitmaps( - resource_id, scale(), rotation(), &hotspot, &bitmaps); - - cursors_[id] = CursorFactoryOzone::GetInstance()->CreateAnimatedCursor( - bitmaps, hotspot, frame_delay_ms); -} - -void CursorLoaderOzone::UnloadAll() { - for (ImageCursorMap::const_iterator it = cursors_.begin(); - it != cursors_.end(); - ++it) - CursorFactoryOzone::GetInstance()->UnrefImageCursor(it->second); - cursors_.clear(); -} - -void CursorLoaderOzone::SetPlatformCursor(gfx::NativeCursor* cursor) { - int native_type = cursor->native_type(); - PlatformCursor platform; - - if (cursors_.count(native_type)) { - // An image cursor is loaded for this type. - platform = cursors_[native_type]; - } else if (native_type == kCursorCustom) { - // The platform cursor was already set via WebCursor::GetPlatformCursor. - platform = cursor->platform(); - } else { - // Use default cursor of this type. - platform = CursorFactoryOzone::GetInstance()->GetDefaultCursor(native_type); - } - - cursor->SetPlatformCursor(platform); -} - -CursorLoader* CursorLoader::Create() { - return new CursorLoaderOzone(); -} - -} // namespace ui
diff --git a/ui/base/cursor/cursor_loader_ozone.h b/ui/base/cursor/cursor_loader_ozone.h deleted file mode 100644 index 7aef431..0000000 --- a/ui/base/cursor/cursor_loader_ozone.h +++ /dev/null
@@ -1,41 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_CURSOR_CURSOR_LOADER_OZONE_H_ -#define UI_BASE_CURSOR_CURSOR_LOADER_OZONE_H_ - -#include <map> - -#include "ui/base/cursor/cursor.h" -#include "ui/base/cursor/cursor_loader.h" - -namespace ui { - -class UI_BASE_EXPORT CursorLoaderOzone : public CursorLoader { - public: - CursorLoaderOzone(); - virtual ~CursorLoaderOzone(); - - // CursorLoader overrides: - virtual void LoadImageCursor(int id, - int resource_id, - const gfx::Point& hot) override; - virtual void LoadAnimatedCursor(int id, - int resource_id, - const gfx::Point& hot, - int frame_delay_ms) override; - virtual void UnloadAll() override; - virtual void SetPlatformCursor(gfx::NativeCursor* cursor) override; - - private: - // Pointers are owned by ResourceBundle and must not be freed here. - typedef std::map<int, PlatformCursor> ImageCursorMap; - ImageCursorMap cursors_; - - DISALLOW_COPY_AND_ASSIGN(CursorLoaderOzone); -}; - -} // namespace ui - -#endif // UI_BASE_CURSOR_CURSOR_LOADER_OZONE_H_
diff --git a/ui/base/cursor/cursor_ozone.cc b/ui/base/cursor/cursor_ozone.cc deleted file mode 100644 index c4ef8c4..0000000 --- a/ui/base/cursor/cursor_ozone.cc +++ /dev/null
@@ -1,21 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/cursor/cursor.h" - -#include "ui/ozone/public/cursor_factory_ozone.h" - -namespace ui { - -void Cursor::RefCustomCursor() { - if (platform_cursor_) - CursorFactoryOzone::GetInstance()->RefImageCursor(platform_cursor_); -} - -void Cursor::UnrefCustomCursor() { - if (platform_cursor_) - CursorFactoryOzone::GetInstance()->UnrefImageCursor(platform_cursor_); -} - -} // namespace ui
diff --git a/ui/base/cursor/cursors_aura.cc b/ui/base/cursor/cursors_aura.cc deleted file mode 100644 index e244b19..0000000 --- a/ui/base/cursor/cursors_aura.cc +++ /dev/null
@@ -1,245 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/cursor/cursors_aura.h" - -#include "third_party/skia/include/core/SkBitmap.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/gfx/image/image_skia.h" -#include "ui/gfx/point.h" -#include "ui/resources/grit/ui_resources.h" - -namespace ui { -namespace { - -struct HotPoint { - int x; - int y; -}; - -struct CursorData { - int id; - int resource_id; - HotPoint hot_1x; - HotPoint hot_2x; -}; - -struct CursorSet { - const CursorSetType id; - const CursorData* cursors; - const int length; - const CursorData* animated_cursors; - const int animated_length; -}; - -const CursorData kNormalCursors[] = { - {ui::kCursorNull, IDR_AURA_CURSOR_PTR, {4, 4}, {8, 9}}, - {ui::kCursorPointer, IDR_AURA_CURSOR_PTR, {4, 4}, {8, 9}}, - {ui::kCursorNoDrop, IDR_AURA_CURSOR_NO_DROP, {9, 9}, {18, 18}}, - {ui::kCursorNotAllowed, IDR_AURA_CURSOR_NO_DROP, {9, 9}, {18, 18}}, - {ui::kCursorCopy, IDR_AURA_CURSOR_COPY, {9, 9}, {18, 18}}, - {ui::kCursorHand, IDR_AURA_CURSOR_HAND, {9, 4}, {19, 8}}, - {ui::kCursorMove, IDR_AURA_CURSOR_MOVE, {11, 11}, {23, 23}}, - {ui::kCursorNorthEastResize, IDR_AURA_CURSOR_NORTH_EAST_RESIZE, - {12, 11}, {25, 23}}, - {ui::kCursorSouthWestResize, IDR_AURA_CURSOR_SOUTH_WEST_RESIZE, - {12, 11}, {25, 23}}, - {ui::kCursorSouthEastResize, IDR_AURA_CURSOR_SOUTH_EAST_RESIZE, - {11, 11}, {24, 23}}, - {ui::kCursorNorthWestResize, IDR_AURA_CURSOR_NORTH_WEST_RESIZE, - {11, 11}, {24, 23}}, - {ui::kCursorNorthResize, IDR_AURA_CURSOR_NORTH_RESIZE, {11, 12}, {23, 23}}, - {ui::kCursorSouthResize, IDR_AURA_CURSOR_SOUTH_RESIZE, {11, 12}, {23, 23}}, - {ui::kCursorEastResize, IDR_AURA_CURSOR_EAST_RESIZE, {12, 11}, {25, 23}}, - {ui::kCursorWestResize, IDR_AURA_CURSOR_WEST_RESIZE, {12, 11}, {25, 23}}, - {ui::kCursorIBeam, IDR_AURA_CURSOR_IBEAM, {12, 12}, {24, 25}}, - {ui::kCursorAlias, IDR_AURA_CURSOR_ALIAS, {8, 6}, {15, 11}}, - {ui::kCursorCell, IDR_AURA_CURSOR_CELL, {11, 11}, {24, 23}}, - {ui::kCursorContextMenu, IDR_AURA_CURSOR_CONTEXT_MENU, {4, 4}, {8, 9}}, - {ui::kCursorCross, IDR_AURA_CURSOR_CROSSHAIR, {12, 12}, {25, 23}}, - {ui::kCursorHelp, IDR_AURA_CURSOR_HELP, {4, 4}, {8, 9}}, - {ui::kCursorVerticalText, IDR_AURA_CURSOR_XTERM_HORIZ, {12, 11}, {26, 23}}, - {ui::kCursorZoomIn, IDR_AURA_CURSOR_ZOOM_IN, {10, 10}, {20, 20}}, - {ui::kCursorZoomOut, IDR_AURA_CURSOR_ZOOM_OUT, {10, 10}, {20, 20}}, - {ui::kCursorRowResize, IDR_AURA_CURSOR_ROW_RESIZE, {11, 12}, {23, 23}}, - {ui::kCursorColumnResize, IDR_AURA_CURSOR_COL_RESIZE, {12, 11}, {25, 23}}, - {ui::kCursorEastWestResize, IDR_AURA_CURSOR_EAST_WEST_RESIZE, - {12, 11}, {25, 23}}, - {ui::kCursorNorthSouthResize, IDR_AURA_CURSOR_NORTH_SOUTH_RESIZE, - {11, 12}, {23, 23}}, - {ui::kCursorNorthEastSouthWestResize, - IDR_AURA_CURSOR_NORTH_EAST_SOUTH_WEST_RESIZE, {12, 11}, {25, 23}}, - {ui::kCursorNorthWestSouthEastResize, - IDR_AURA_CURSOR_NORTH_WEST_SOUTH_EAST_RESIZE, {11, 11}, {24, 23}}, - {ui::kCursorGrab, IDR_AURA_CURSOR_GRAB, {8, 5}, {16, 10}}, - {ui::kCursorGrabbing, IDR_AURA_CURSOR_GRABBING, {9, 9}, {18, 18}}, -}; - -const CursorData kLargeCursors[] = { - // The 2x hotspots should be double of the 1x, even though the cursors are - // shown as same size as 1x (64x64), because in 2x dpi screen, the 1x large - // cursor assets (64x64) are internally enlarged to the double size (128x128) - // by ResourceBundleImageSource. - {ui::kCursorNull, IDR_AURA_CURSOR_BIG_PTR, {10, 10}, {20, 20}}, - {ui::kCursorPointer, IDR_AURA_CURSOR_BIG_PTR, {10, 10}, {20, 20}}, - {ui::kCursorNoDrop, IDR_AURA_CURSOR_BIG_NO_DROP, {10, 10}, {20, 20}}, - {ui::kCursorNotAllowed, IDR_AURA_CURSOR_BIG_NO_DROP, {10, 10}, {20, 20}}, - {ui::kCursorCopy, IDR_AURA_CURSOR_BIG_COPY, {10, 10}, {20, 20}}, - {ui::kCursorHand, IDR_AURA_CURSOR_BIG_HAND, {25, 7}, {50, 14}}, - {ui::kCursorMove, IDR_AURA_CURSOR_BIG_MOVE, {32, 31}, {64, 62}}, - {ui::kCursorNorthEastResize, IDR_AURA_CURSOR_BIG_NORTH_EAST_RESIZE, - {31, 28}, {62, 56}}, - {ui::kCursorSouthWestResize, IDR_AURA_CURSOR_BIG_SOUTH_WEST_RESIZE, - {31, 28}, {62, 56}}, - {ui::kCursorSouthEastResize, IDR_AURA_CURSOR_BIG_SOUTH_EAST_RESIZE, - {28, 28}, {56, 56}}, - {ui::kCursorNorthWestResize, IDR_AURA_CURSOR_BIG_NORTH_WEST_RESIZE, - {28, 28}, {56, 56}}, - {ui::kCursorNorthResize, IDR_AURA_CURSOR_BIG_NORTH_RESIZE, - {29, 32}, {58, 64}}, - {ui::kCursorSouthResize, IDR_AURA_CURSOR_BIG_SOUTH_RESIZE, - {29, 32}, {58, 64}}, - {ui::kCursorEastResize, IDR_AURA_CURSOR_BIG_EAST_RESIZE, {35, 29}, {70, 58}}, - {ui::kCursorWestResize, IDR_AURA_CURSOR_BIG_WEST_RESIZE, {35, 29}, {70, 58}}, - {ui::kCursorIBeam, IDR_AURA_CURSOR_BIG_IBEAM, {30, 32}, {60, 64}}, - {ui::kCursorAlias, IDR_AURA_CURSOR_BIG_ALIAS, {19, 11}, {38, 22}}, - {ui::kCursorCell, IDR_AURA_CURSOR_BIG_CELL, {30, 30}, {60, 60}}, - {ui::kCursorContextMenu, IDR_AURA_CURSOR_BIG_CONTEXT_MENU, - {11, 11}, {22, 22}}, - {ui::kCursorCross, IDR_AURA_CURSOR_BIG_CROSSHAIR, {31, 30}, {62, 60}}, - {ui::kCursorHelp, IDR_AURA_CURSOR_BIG_HELP, {10, 11}, {20, 22}}, - {ui::kCursorVerticalText, IDR_AURA_CURSOR_BIG_XTERM_HORIZ, - {32, 30}, {64, 60}}, - {ui::kCursorZoomIn, IDR_AURA_CURSOR_BIG_ZOOM_IN, {25, 26}, {50, 52}}, - {ui::kCursorZoomOut, IDR_AURA_CURSOR_BIG_ZOOM_OUT, {26, 26}, {52, 52}}, - {ui::kCursorRowResize, IDR_AURA_CURSOR_BIG_ROW_RESIZE, {29, 32}, {58, 64}}, - {ui::kCursorColumnResize, IDR_AURA_CURSOR_BIG_COL_RESIZE, {35, 29}, {70, 58}}, - {ui::kCursorEastWestResize, IDR_AURA_CURSOR_BIG_EAST_WEST_RESIZE, - {35, 29}, {70, 58}}, - {ui::kCursorNorthSouthResize, IDR_AURA_CURSOR_BIG_NORTH_SOUTH_RESIZE, - {29, 32}, {58, 64}}, - {ui::kCursorNorthEastSouthWestResize, - IDR_AURA_CURSOR_BIG_NORTH_EAST_SOUTH_WEST_RESIZE, {32, 30}, {64, 60}}, - {ui::kCursorNorthWestSouthEastResize, - IDR_AURA_CURSOR_BIG_NORTH_WEST_SOUTH_EAST_RESIZE, {32, 31}, {64, 62}}, - {ui::kCursorGrab, IDR_AURA_CURSOR_BIG_GRAB, {21, 11}, {42, 22}}, - {ui::kCursorGrabbing, IDR_AURA_CURSOR_BIG_GRABBING, {20, 12}, {40, 24}}, -}; - -const CursorData kAnimatedCursors[] = { - {ui::kCursorWait, IDR_THROBBER, {7, 7}, {14, 14}}, - {ui::kCursorProgress, IDR_THROBBER, {7, 7}, {14, 14}}, -}; - -const CursorSet kCursorSets[] = { - { - CURSOR_SET_NORMAL, - kNormalCursors, arraysize(kNormalCursors), - kAnimatedCursors, arraysize(kAnimatedCursors) - }, - { - CURSOR_SET_LARGE, - kLargeCursors, arraysize(kLargeCursors), - // TODO(yoshiki): Replace animated cursors with big assets. crbug.com/247254 - kAnimatedCursors, arraysize(kAnimatedCursors) - }, -}; - -const CursorSet* GetCursorSetByType(CursorSetType cursor_set_id) { - for (size_t i = 0; i < arraysize(kCursorSets); ++i) { - if (kCursorSets[i].id == cursor_set_id) - return &kCursorSets[i]; - } - - return NULL; -} - -bool SearchTable(const CursorData* table, - size_t table_length, - int id, - float scale_factor, - int* resource_id, - gfx::Point* point) { - bool resource_2x_available = - ResourceBundle::GetSharedInstance().GetMaxScaleFactor() == - SCALE_FACTOR_200P; - for (size_t i = 0; i < table_length; ++i) { - if (table[i].id == id) { - *resource_id = table[i].resource_id; - *point = scale_factor == 1.0f || !resource_2x_available ? - gfx::Point(table[i].hot_1x.x, table[i].hot_1x.y) : - gfx::Point(table[i].hot_2x.x, table[i].hot_2x.y); - return true; - } - } - - return false; -} - -} // namespace - -bool GetCursorDataFor(CursorSetType cursor_set_id, - int id, - float scale_factor, - int* resource_id, - gfx::Point* point) { - const CursorSet* cursor_set = GetCursorSetByType(cursor_set_id); - if (cursor_set && - SearchTable(cursor_set->cursors, - cursor_set->length, - id, scale_factor, resource_id, point)) { - return true; - } - - // Falls back to the default cursor set. - cursor_set = GetCursorSetByType(ui::CURSOR_SET_NORMAL); - DCHECK(cursor_set); - return SearchTable(cursor_set->cursors, - cursor_set->length, - id, scale_factor, resource_id, point); -} - -bool GetAnimatedCursorDataFor(CursorSetType cursor_set_id, - int id, - float scale_factor, - int* resource_id, - gfx::Point* point) { - const CursorSet* cursor_set = GetCursorSetByType(cursor_set_id); - if (cursor_set && - SearchTable(cursor_set->animated_cursors, - cursor_set->animated_length, - id, scale_factor, resource_id, point)) { - return true; - } - - // Falls back to the default cursor set. - cursor_set = GetCursorSetByType(ui::CURSOR_SET_NORMAL); - DCHECK(cursor_set); - return SearchTable(cursor_set->animated_cursors, - cursor_set->animated_length, - id, scale_factor, resource_id, point); -} - -bool GetCursorBitmap(const Cursor& cursor, - SkBitmap* bitmap, - gfx::Point* point) { - DCHECK(bitmap && point); - int resource_id; - if (!GetCursorDataFor(ui::CURSOR_SET_NORMAL, - cursor.native_type(), - cursor.device_scale_factor(), - &resource_id, - point)) { - return false; - } - - const SkBitmap* cursor_bitmap = ResourceBundle::GetSharedInstance(). - GetImageSkiaNamed(resource_id)->bitmap(); - if (!cursor_bitmap) - return false; - *bitmap = *cursor_bitmap; - return true; -} - -} // namespace ui
diff --git a/ui/base/cursor/cursors_aura.h b/ui/base/cursor/cursors_aura.h deleted file mode 100644 index e8eae0a..0000000 --- a/ui/base/cursor/cursors_aura.h +++ /dev/null
@@ -1,45 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_CURSOR_CURSORS_AURA_H_ -#define UI_BASE_CURSOR_CURSORS_AURA_H_ - -#include "ui/base/cursor/cursor.h" -#include "ui/base/ui_base_export.h" - -class SkBitmap; - -namespace gfx { -class Point; -} - -namespace ui { - -const int kAnimatedCursorFrameDelayMs = 25; - -// Returns data about |id|, where id is a cursor constant like -// ui::kCursorHelp. The IDR will be placed in |resource_id| and the hotspots -// for the different DPIs will be placed in |hot_1x| and |hot_2x|. Returns -// false if |id| is invalid. -bool UI_BASE_EXPORT GetCursorDataFor(CursorSetType cursor_set_id, - int id, - float scale_factor, - int* resource_id, - gfx::Point* point); - -// Like above, but for animated cursors. -bool UI_BASE_EXPORT GetAnimatedCursorDataFor(CursorSetType cursor_set_id, - int id, - float scale_factor, - int* resource_id, - gfx::Point* point); - -// Returns the cursor bitmap for |cursor|. Returns false if |cursor| is invalid. -// The cursor hot point location is set in |point|. -bool UI_BASE_EXPORT - GetCursorBitmap(const Cursor& cursor, SkBitmap* bitmap, gfx::Point* point); - -} // namespace ui - -#endif // UI_BASE_CURSOR_CURSORS_AURA_H_
diff --git a/ui/base/cursor/image_cursors.cc b/ui/base/cursor/image_cursors.cc deleted file mode 100644 index b4c19fc..0000000 --- a/ui/base/cursor/image_cursors.cc +++ /dev/null
@@ -1,150 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/cursor/image_cursors.h" - -#include <float.h> - -#include "base/logging.h" -#include "base/strings/string16.h" -#include "ui/base/cursor/cursor.h" -#include "ui/base/cursor/cursor_loader.h" -#include "ui/base/cursor/cursors_aura.h" -#include "ui/gfx/display.h" -#include "ui/gfx/point.h" - -namespace ui { - -namespace { - -const int kImageCursorIds[] = { - kCursorNull, - kCursorPointer, - kCursorNoDrop, - kCursorNotAllowed, - kCursorCopy, - kCursorHand, - kCursorMove, - kCursorNorthEastResize, - kCursorSouthWestResize, - kCursorSouthEastResize, - kCursorNorthWestResize, - kCursorNorthResize, - kCursorSouthResize, - kCursorEastResize, - kCursorWestResize, - kCursorIBeam, - kCursorAlias, - kCursorCell, - kCursorContextMenu, - kCursorCross, - kCursorHelp, - kCursorVerticalText, - kCursorZoomIn, - kCursorZoomOut, - kCursorRowResize, - kCursorColumnResize, - kCursorEastWestResize, - kCursorNorthSouthResize, - kCursorNorthEastSouthWestResize, - kCursorNorthWestSouthEastResize, - kCursorGrab, - kCursorGrabbing, -}; - -const int kAnimatedCursorIds[] = { - kCursorWait, - kCursorProgress -}; - -} // namespace - -ImageCursors::ImageCursors() : cursor_set_(CURSOR_SET_NORMAL) { -} - -ImageCursors::~ImageCursors() { -} - -float ImageCursors::GetScale() const { - if (!cursor_loader_) { - NOTREACHED(); - // Returning default on release build as it's not serious enough to crash - // even if this ever happens. - return 1.0f; - } - return cursor_loader_->scale(); -} - -gfx::Display::Rotation ImageCursors::GetRotation() const { - if (!cursor_loader_) { - NOTREACHED(); - // Returning default on release build as it's not serious enough to crash - // even if this ever happens. - return gfx::Display::ROTATE_0; - } - return cursor_loader_->rotation(); -} - -bool ImageCursors::SetDisplay(const gfx::Display& display, - float scale_factor) { - if (!cursor_loader_) { - cursor_loader_.reset(CursorLoader::Create()); - } else if (cursor_loader_->rotation() == display.rotation() && - cursor_loader_->scale() == scale_factor) { - return false; - } - - cursor_loader_->set_rotation(display.rotation()); - cursor_loader_->set_scale(scale_factor); - ReloadCursors(); - return true; -} - -void ImageCursors::ReloadCursors() { - float device_scale_factor = cursor_loader_->scale(); - - cursor_loader_->UnloadAll(); - - for (size_t i = 0; i < arraysize(kImageCursorIds); ++i) { - int resource_id = -1; - gfx::Point hot_point; - bool success = GetCursorDataFor(cursor_set_, - kImageCursorIds[i], - device_scale_factor, - &resource_id, - &hot_point); - DCHECK(success); - cursor_loader_->LoadImageCursor(kImageCursorIds[i], resource_id, hot_point); - } - for (size_t i = 0; i < arraysize(kAnimatedCursorIds); ++i) { - int resource_id = -1; - gfx::Point hot_point; - bool success = GetAnimatedCursorDataFor(cursor_set_, - kAnimatedCursorIds[i], - device_scale_factor, - &resource_id, - &hot_point); - DCHECK(success); - cursor_loader_->LoadAnimatedCursor(kAnimatedCursorIds[i], - resource_id, - hot_point, - kAnimatedCursorFrameDelayMs); - } -} - -void ImageCursors::SetCursorSet(CursorSetType cursor_set) { - if (cursor_set_ == cursor_set) - return; - - cursor_set_ = cursor_set; - - if (cursor_loader_.get()) - ReloadCursors(); -} - -void ImageCursors::SetPlatformCursor(gfx::NativeCursor* cursor) { - cursor_loader_->SetPlatformCursor(cursor); -} - -} // namespace ui
diff --git a/ui/base/cursor/image_cursors.h b/ui/base/cursor/image_cursors.h deleted file mode 100644 index 25676ca..0000000 --- a/ui/base/cursor/image_cursors.h +++ /dev/null
@@ -1,52 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_CURSOR_IMAGE_CURSORS_H_ -#define UI_BASE_CURSOR_IMAGE_CURSORS_H_ - -#include "base/memory/scoped_ptr.h" -#include "base/strings/string16.h" -#include "ui/base/cursor/cursor.h" -#include "ui/base/ui_base_export.h" -#include "ui/gfx/display.h" -#include "ui/gfx/native_widget_types.h" - -namespace ui { - -class CursorLoader; - -// A utility class that provides cursors for NativeCursors for which we have -// image resources. -class UI_BASE_EXPORT ImageCursors { - public: - ImageCursors(); - ~ImageCursors(); - - // Returns the scale and rotation of the currently loaded cursor. - float GetScale() const; - gfx::Display::Rotation GetRotation() const; - - // Sets the display the cursors are loaded for. |scale_factor| determines the - // size of the image to load. Returns true if the cursor image is reloaded. - bool SetDisplay(const gfx::Display& display, float scale_factor); - - // Sets the type of the mouse cursor icon. - void SetCursorSet(CursorSetType cursor_set); - - // Sets the platform cursor based on the native type of |cursor|. - void SetPlatformCursor(gfx::NativeCursor* cursor); - - private: - // Reloads the all loaded cursors in the cursor loader. - void ReloadCursors(); - - scoped_ptr<CursorLoader> cursor_loader_; - CursorSetType cursor_set_; - - DISALLOW_COPY_AND_ASSIGN(ImageCursors); -}; - -} // namespace ui - -#endif // UI_BASE_CURSOR_IMAGE_CURSORS_H_
diff --git a/ui/base/cursor/ozone/OWNERS b/ui/base/cursor/ozone/OWNERS deleted file mode 100644 index 479c4d8..0000000 --- a/ui/base/cursor/ozone/OWNERS +++ /dev/null
@@ -1,2 +0,0 @@ -rjkroege@chromium.org -spang@chromium.org
diff --git a/ui/base/cursor/ozone/bitmap_cursor_factory_ozone.cc b/ui/base/cursor/ozone/bitmap_cursor_factory_ozone.cc deleted file mode 100644 index f96d98f..0000000 --- a/ui/base/cursor/ozone/bitmap_cursor_factory_ozone.cc +++ /dev/null
@@ -1,126 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/cursor/ozone/bitmap_cursor_factory_ozone.h" - -#include "base/logging.h" -#include "third_party/skia/include/core/SkBitmap.h" -#include "ui/base/cursor/cursors_aura.h" - -namespace ui { - -namespace { - -BitmapCursorOzone* ToBitmapCursorOzone(PlatformCursor cursor) { - return static_cast<BitmapCursorOzone*>(cursor); -} - -PlatformCursor ToPlatformCursor(BitmapCursorOzone* cursor) { - return static_cast<PlatformCursor>(cursor); -} - -scoped_refptr<BitmapCursorOzone> CreateDefaultBitmapCursor(int type) { - SkBitmap bitmap; - gfx::Point hotspot; - if (GetCursorBitmap(type, &bitmap, &hotspot)) - return new BitmapCursorOzone(bitmap, hotspot); - return NULL; -} - -} // namespace - -BitmapCursorOzone::BitmapCursorOzone(const SkBitmap& bitmap, - const gfx::Point& hotspot) - : hotspot_(hotspot), frame_delay_ms_(0) { - bitmaps_.push_back(bitmap); -} - -BitmapCursorOzone::BitmapCursorOzone(const std::vector<SkBitmap>& bitmaps, - const gfx::Point& hotspot, - int frame_delay_ms) - : bitmaps_(bitmaps), hotspot_(hotspot), frame_delay_ms_(frame_delay_ms) { - DCHECK_LT(0U, bitmaps.size()); - DCHECK_LE(0, frame_delay_ms); -} - -BitmapCursorOzone::~BitmapCursorOzone() { -} - -const gfx::Point& BitmapCursorOzone::hotspot() { - return hotspot_; -} - -const SkBitmap& BitmapCursorOzone::bitmap() { - return bitmaps_[0]; -} - -const std::vector<SkBitmap>& BitmapCursorOzone::bitmaps() { - return bitmaps_; -} - -int BitmapCursorOzone::frame_delay_ms() { - return frame_delay_ms_; -} - -BitmapCursorFactoryOzone::BitmapCursorFactoryOzone() {} - -BitmapCursorFactoryOzone::~BitmapCursorFactoryOzone() {} - -// static -scoped_refptr<BitmapCursorOzone> BitmapCursorFactoryOzone::GetBitmapCursor( - PlatformCursor platform_cursor) { - return make_scoped_refptr(ToBitmapCursorOzone(platform_cursor)); -} - -PlatformCursor BitmapCursorFactoryOzone::GetDefaultCursor(int type) { - return GetDefaultCursorInternal(type).get(); -} - -PlatformCursor BitmapCursorFactoryOzone::CreateImageCursor( - const SkBitmap& bitmap, - const gfx::Point& hotspot) { - BitmapCursorOzone* cursor = new BitmapCursorOzone(bitmap, hotspot); - cursor->AddRef(); // Balanced by UnrefImageCursor. - return ToPlatformCursor(cursor); -} - -PlatformCursor BitmapCursorFactoryOzone::CreateAnimatedCursor( - const std::vector<SkBitmap>& bitmaps, - const gfx::Point& hotspot, - int frame_delay_ms) { - DCHECK_LT(0U, bitmaps.size()); - BitmapCursorOzone* cursor = - new BitmapCursorOzone(bitmaps, hotspot, frame_delay_ms); - cursor->AddRef(); // Balanced by UnrefImageCursor. - return ToPlatformCursor(cursor); -} - -void BitmapCursorFactoryOzone::RefImageCursor(PlatformCursor cursor) { - ToBitmapCursorOzone(cursor)->AddRef(); -} - -void BitmapCursorFactoryOzone::UnrefImageCursor(PlatformCursor cursor) { - ToBitmapCursorOzone(cursor)->Release(); -} - -scoped_refptr<BitmapCursorOzone> -BitmapCursorFactoryOzone::GetDefaultCursorInternal(int type) { - if (type == kCursorNone) - return NULL; // NULL is used for hidden cursor. - - if (!default_cursors_.count(type)) { - // Create new image cursor from default aura bitmap for this type. We hold a - // ref forever because clients do not do refcounting for default cursors. - scoped_refptr<BitmapCursorOzone> cursor = CreateDefaultBitmapCursor(type); - if (!cursor.get() && type != kCursorPointer) - cursor = GetDefaultCursorInternal(kCursorPointer); - DCHECK(cursor.get()) << "Failed to load default cursor bitmap"; - default_cursors_[type] = cursor; - } - - // Returned owned default cursor for this type. - return default_cursors_[type]; -} - -} // namespace ui
diff --git a/ui/base/cursor/ozone/bitmap_cursor_factory_ozone.h b/ui/base/cursor/ozone/bitmap_cursor_factory_ozone.h deleted file mode 100644 index 037fd08..0000000 --- a/ui/base/cursor/ozone/bitmap_cursor_factory_ozone.h +++ /dev/null
@@ -1,86 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_CURSOR_OZONE_BITMAP_CURSOR_FACTORY_OZONE_H_ -#define UI_BASE_CURSOR_OZONE_BITMAP_CURSOR_FACTORY_OZONE_H_ - -#include <map> - -#include "base/memory/ref_counted.h" -#include "third_party/skia/include/core/SkBitmap.h" -#include "ui/base/cursor/cursor.h" -#include "ui/base/ui_base_export.h" -#include "ui/gfx/geometry/point.h" -#include "ui/ozone/public/cursor_factory_ozone.h" - -namespace ui { - -// A cursor that is an SkBitmap combined with a gfx::Point hotspot. -class UI_BASE_EXPORT BitmapCursorOzone - : public base::RefCounted<BitmapCursorOzone> { - public: - BitmapCursorOzone(const SkBitmap& bitmap, const gfx::Point& hotspot); - BitmapCursorOzone(const std::vector<SkBitmap>& bitmaps, - const gfx::Point& hotspot, - int frame_delay_ms); - - const gfx::Point& hotspot(); - const SkBitmap& bitmap(); - - // For animated cursors. - const std::vector<SkBitmap>& bitmaps(); - int frame_delay_ms(); - - private: - friend class base::RefCounted<BitmapCursorOzone>; - ~BitmapCursorOzone(); - - std::vector<SkBitmap> bitmaps_; - gfx::Point hotspot_; - int frame_delay_ms_; - - DISALLOW_COPY_AND_ASSIGN(BitmapCursorOzone); -}; - -// CursorFactoryOzone implementation for bitmapped cursors. -// -// This is a base class for platforms where PlatformCursor is an SkBitmap -// combined with a gfx::Point for the hotspot. -// -// Subclasses need only implement SetBitmapCursor() as everything else is -// implemented here. -class UI_BASE_EXPORT BitmapCursorFactoryOzone : public CursorFactoryOzone { - public: - BitmapCursorFactoryOzone(); - virtual ~BitmapCursorFactoryOzone(); - - // Convert PlatformCursor to BitmapCursorOzone. - static scoped_refptr<BitmapCursorOzone> GetBitmapCursor( - PlatformCursor platform_cursor); - - // CursorFactoryOzone: - virtual PlatformCursor GetDefaultCursor(int type) override; - virtual PlatformCursor CreateImageCursor(const SkBitmap& bitmap, - const gfx::Point& hotspot) override; - virtual PlatformCursor CreateAnimatedCursor( - const std::vector<SkBitmap>& bitmaps, - const gfx::Point& hotspot, - int frame_delay_ms) override; - virtual void RefImageCursor(PlatformCursor cursor) override; - virtual void UnrefImageCursor(PlatformCursor cursor) override; - - private: - // Get cached BitmapCursorOzone for a default cursor. - scoped_refptr<BitmapCursorOzone> GetDefaultCursorInternal(int type); - - // Default cursors are cached & owned by the factory. - typedef std::map<int, scoped_refptr<BitmapCursorOzone> > DefaultCursorMap; - DefaultCursorMap default_cursors_; - - DISALLOW_COPY_AND_ASSIGN(BitmapCursorFactoryOzone); -}; - -} // namespace ui - -#endif // UI_BASE_CURSOR_OZONE_BITMAP_CURSOR_FACTORY_OZONE_H_
diff --git a/ui/base/default_theme_provider.cc b/ui/base/default_theme_provider.cc deleted file mode 100644 index 210ff18..0000000 --- a/ui/base/default_theme_provider.cc +++ /dev/null
@@ -1,47 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/default_theme_provider.h" - -#include "ui/base/resource/resource_bundle.h" -#include "ui/gfx/image/image_skia.h" - -namespace ui { - -DefaultThemeProvider::DefaultThemeProvider() {} - -DefaultThemeProvider::~DefaultThemeProvider() {} - -bool DefaultThemeProvider::UsingSystemTheme() const { - return true; -} - -gfx::ImageSkia* DefaultThemeProvider::GetImageSkiaNamed(int id) const { - return ResourceBundle::GetSharedInstance().GetImageSkiaNamed(id); -} - -SkColor DefaultThemeProvider::GetColor(int id) const { - // Return debugging-blue. - return 0xff0000ff; -} - -int DefaultThemeProvider::GetDisplayProperty(int id) const { - return -1; -} - -bool DefaultThemeProvider::ShouldUseNativeFrame() const { - return false; -} - -bool DefaultThemeProvider::HasCustomImage(int id) const { - return false; -} - -base::RefCountedMemory* DefaultThemeProvider::GetRawData( - int id, - ui::ScaleFactor scale_factor) const { - return NULL; -} - -} // namespace ui
diff --git a/ui/base/default_theme_provider.h b/ui/base/default_theme_provider.h deleted file mode 100644 index 173442d..0000000 --- a/ui/base/default_theme_provider.h +++ /dev/null
@@ -1,50 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_DEFAULT_THEME_PROVIDER_H_ -#define UI_BASE_DEFAULT_THEME_PROVIDER_H_ - -#include <vector> - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "ui/base/theme_provider.h" -#include "ui/base/ui_base_export.h" - -namespace ui { -class ResourceBundle; -} - -namespace ui { - -class UI_BASE_EXPORT DefaultThemeProvider : public ThemeProvider { - public: - DefaultThemeProvider(); - ~DefaultThemeProvider() override; - - // Overridden from ui::ThemeProvider: - bool UsingSystemTheme() const override; - gfx::ImageSkia* GetImageSkiaNamed(int id) const override; - SkColor GetColor(int id) const override; - int GetDisplayProperty(int id) const override; - bool ShouldUseNativeFrame() const override; - bool HasCustomImage(int id) const override; - base::RefCountedMemory* GetRawData(int id, ui::ScaleFactor scale_factor) - const override; - -#if defined(OS_MACOSX) - NSImage* GetNSImageNamed(int id) const override; - NSColor* GetNSImageColorNamed(int id) const override; - NSColor* GetNSColor(int id) const override; - NSColor* GetNSColorTint(int id) const override; - NSGradient* GetNSGradient(int id) const override; -#endif - - private: - DISALLOW_COPY_AND_ASSIGN(DefaultThemeProvider); -}; - -} // namespace ui - -#endif // UI_BASE_DEFAULT_THEME_PROVIDER_H_
diff --git a/ui/base/default_theme_provider_mac.mm b/ui/base/default_theme_provider_mac.mm deleted file mode 100644 index 6d5e684..0000000 --- a/ui/base/default_theme_provider_mac.mm +++ /dev/null
@@ -1,35 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/default_theme_provider.h" - -#import <Cocoa/Cocoa.h> - -#include "ui/base/resource/resource_bundle.h" - -namespace ui { - -NSImage* DefaultThemeProvider::GetNSImageNamed(int id) const { - return ResourceBundle::GetSharedInstance(). - GetNativeImageNamed(id).ToNSImage(); -} - -NSColor* DefaultThemeProvider::GetNSImageColorNamed(int id) const { - NSImage* image = GetNSImageNamed(id); - return [NSColor colorWithPatternImage:image]; -} - -NSColor* DefaultThemeProvider::GetNSColor(int id) const { - return [NSColor redColor]; -} - -NSColor* DefaultThemeProvider::GetNSColorTint(int id) const { - return [NSColor redColor]; -} - -NSGradient* DefaultThemeProvider::GetNSGradient(int id) const { - return nil; -} - -} // namespace ui
diff --git a/ui/base/dragdrop/DEPS b/ui/base/dragdrop/DEPS deleted file mode 100644 index 0f8f399..0000000 --- a/ui/base/dragdrop/DEPS +++ /dev/null
@@ -1,3 +0,0 @@ -include_rules = [ - "+third_party/mozilla", -]
diff --git a/ui/base/dragdrop/download_file_interface.h b/ui/base/dragdrop/download_file_interface.h deleted file mode 100644 index 327fe79..0000000 --- a/ui/base/dragdrop/download_file_interface.h +++ /dev/null
@@ -1,60 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_DRAGDROP_DOWNLOAD_FILE_INTERFACE_H_ -#define UI_BASE_DRAGDROP_DOWNLOAD_FILE_INTERFACE_H_ - -#include "build/build_config.h" - -#include "base/basictypes.h" -#include "base/memory/ref_counted.h" - -#include "ui/base/ui_base_export.h" - -#if defined(OS_WIN) -#include <objidl.h> -#endif - -namespace base { -class FilePath; -} - -namespace ui { - -// TODO(benjhayden, anybody): Do these need to be RefCountedThreadSafe? - -// Defines the interface to observe the status of file download. -class UI_BASE_EXPORT DownloadFileObserver - : public base::RefCountedThreadSafe<DownloadFileObserver> { - public: - virtual void OnDownloadCompleted(const base::FilePath& file_path) = 0; - virtual void OnDownloadAborted() = 0; - - protected: - friend class base::RefCountedThreadSafe<DownloadFileObserver>; - virtual ~DownloadFileObserver() {} -}; - -// Defines the interface to control how a file is downloaded. -class UI_BASE_EXPORT DownloadFileProvider - : public base::RefCountedThreadSafe<DownloadFileProvider> { - public: - // Starts the download asynchronously and returns immediately. - virtual void Start(DownloadFileObserver* observer) = 0; - - // Returns true if the download succeeded and false otherwise. Waits until the - // download is completed/cancelled/interrupted before returning. - virtual bool Wait() = 0; - - // Cancels the download. - virtual void Stop() = 0; - - protected: - friend class base::RefCountedThreadSafe<DownloadFileProvider>; - virtual ~DownloadFileProvider() {} -}; - -} // namespace ui - -#endif // UI_BASE_DRAGDROP_DOWNLOAD_FILE_INTERFACE_H_
diff --git a/ui/base/dragdrop/drag_drop_types.h b/ui/base/dragdrop/drag_drop_types.h deleted file mode 100644 index c74d4e2..0000000 --- a/ui/base/dragdrop/drag_drop_types.h +++ /dev/null
@@ -1,36 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_DRAGDROP_DRAG_DROP_TYPES_H_ -#define UI_BASE_DRAGDROP_DRAG_DROP_TYPES_H_ - -#include "base/basictypes.h" -#include "ui/base/ui_base_export.h" - -namespace ui { - -class UI_BASE_EXPORT DragDropTypes { - public: - enum DragOperation { - DRAG_NONE = 0, - DRAG_MOVE = 1 << 0, - DRAG_COPY = 1 << 1, - DRAG_LINK = 1 << 2 - }; - - enum DragEventSource { - DRAG_EVENT_SOURCE_MOUSE, - DRAG_EVENT_SOURCE_TOUCH, - DRAG_EVENT_SOURCE_LAST = DRAG_EVENT_SOURCE_TOUCH - }; - -#if defined(OS_WIN) - static uint32 DragOperationToDropEffect(int drag_operation); - static int DropEffectToDragOperation(uint32 effect); -#endif -}; - -} // namespace ui - -#endif // UI_BASE_DRAGDROP_DRAG_DROP_TYPES_H_
diff --git a/ui/base/dragdrop/drag_drop_types_win.cc b/ui/base/dragdrop/drag_drop_types_win.cc deleted file mode 100644 index d6beff5..0000000 --- a/ui/base/dragdrop/drag_drop_types_win.cc +++ /dev/null
@@ -1,34 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/dragdrop/drag_drop_types.h" - -#include <oleidl.h> - -namespace ui { - -int ui::DragDropTypes::DropEffectToDragOperation( - uint32 effect) { - int drag_operation = DRAG_NONE; - if (effect & DROPEFFECT_LINK) - drag_operation |= DRAG_LINK; - if (effect & DROPEFFECT_COPY) - drag_operation |= DRAG_COPY; - if (effect & DROPEFFECT_MOVE) - drag_operation |= DRAG_MOVE; - return drag_operation; -} - -uint32 ui::DragDropTypes::DragOperationToDropEffect(int drag_operation) { - uint32 drop_effect = DROPEFFECT_NONE; - if (drag_operation & DRAG_LINK) - drop_effect |= DROPEFFECT_LINK; - if (drag_operation & DRAG_COPY) - drop_effect |= DROPEFFECT_COPY; - if (drag_operation & DRAG_MOVE) - drop_effect |= DROPEFFECT_MOVE; - return drop_effect; -} - -} // namespace ui
diff --git a/ui/base/dragdrop/drag_source_win.cc b/ui/base/dragdrop/drag_source_win.cc deleted file mode 100644 index 90ce682..0000000 --- a/ui/base/dragdrop/drag_source_win.cc +++ /dev/null
@@ -1,55 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/dragdrop/drag_source_win.h" - -namespace ui { - -DragSourceWin::DragSourceWin() : cancel_drag_(false) { -} - -HRESULT DragSourceWin::QueryContinueDrag(BOOL escape_pressed, DWORD key_state) { - if (cancel_drag_) - return DRAGDROP_S_CANCEL; - - if (escape_pressed) { - OnDragSourceCancel(); - return DRAGDROP_S_CANCEL; - } - - if (!(key_state & MK_LBUTTON)) { - OnDragSourceDrop(); - return DRAGDROP_S_DROP; - } - - OnDragSourceMove(); - return S_OK; -} - -HRESULT DragSourceWin::GiveFeedback(DWORD effect) { - return DRAGDROP_S_USEDEFAULTCURSORS; -} - -HRESULT DragSourceWin::QueryInterface(const IID& iid, void** object) { - *object = NULL; - if (IsEqualIID(iid, IID_IUnknown) || IsEqualIID(iid, IID_IDropSource)) { - *object = this; - } else { - return E_NOINTERFACE; - } - AddRef(); - return S_OK; -} - -ULONG DragSourceWin::AddRef() { - base::RefCountedThreadSafe<DragSourceWin>::AddRef(); - return 0; -} - -ULONG DragSourceWin::Release() { - base::RefCountedThreadSafe<DragSourceWin>::Release(); - return 0; -} - -} // namespace ui
diff --git a/ui/base/dragdrop/drag_source_win.h b/ui/base/dragdrop/drag_source_win.h deleted file mode 100644 index cec2aa1..0000000 --- a/ui/base/dragdrop/drag_source_win.h +++ /dev/null
@@ -1,57 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_DRAGDROP_DRAG_SOURCE_WIN_H_ -#define UI_BASE_DRAGDROP_DRAG_SOURCE_WIN_H_ - -#include <objidl.h> - -#include "base/basictypes.h" -#include "base/memory/ref_counted.h" -#include "ui/base/ui_base_export.h" - -namespace ui { - -// A base IDropSource implementation. Handles notifications sent by an active -// drag-drop operation as the user mouses over other drop targets on their -// system. This object tells Windows whether or not the drag should continue, -// and supplies the appropriate cursors. -class UI_BASE_EXPORT DragSourceWin - : public IDropSource, - public base::RefCountedThreadSafe<DragSourceWin> { - public: - DragSourceWin(); - virtual ~DragSourceWin() {} - - // Stop the drag operation at the next chance we get. This doesn't - // synchronously stop the drag (since Windows is controlling that), - // but lets us tell Windows to cancel the drag the next chance we get. - void CancelDrag() { - cancel_drag_ = true; - } - - // IDropSource implementation: - HRESULT __stdcall QueryContinueDrag(BOOL escape_pressed, DWORD key_state); - HRESULT __stdcall GiveFeedback(DWORD effect); - - // IUnknown implementation: - HRESULT __stdcall QueryInterface(const IID& iid, void** object); - ULONG __stdcall AddRef(); - ULONG __stdcall Release(); - - protected: - virtual void OnDragSourceCancel() {} - virtual void OnDragSourceDrop() {} - virtual void OnDragSourceMove() {} - - private: - // Set to true if we want to cancel the drag operation. - bool cancel_drag_; - - DISALLOW_COPY_AND_ASSIGN(DragSourceWin); -}; - -} // namespace ui - -#endif // UI_BASE_DRAGDROP_DRAG_SOURCE_WIN_H_
diff --git a/ui/base/dragdrop/drag_utils.cc b/ui/base/dragdrop/drag_utils.cc deleted file mode 100644 index 363dad4..0000000 --- a/ui/base/dragdrop/drag_utils.cc +++ /dev/null
@@ -1,105 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/dragdrop/drag_utils.h" - -#include "base/files/file_util.h" -#include "base/logging.h" -#include "base/strings/utf_string_conversions.h" -#include "ui/base/dragdrop/os_exchange_data.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/font_list.h" -#include "ui/gfx/geometry/point.h" -#include "ui/gfx/geometry/rect.h" -#include "ui/gfx/geometry/size.h" -#include "ui/gfx/image/canvas_image_source.h" -#include "url/gurl.h" - -namespace drag_utils { - -namespace { - -// Maximum width of the link drag image in pixels. -static const int kLinkDragImageVPadding = 3; - -// File dragging pixel measurements -static const int kFileDragImageMaxWidth = 200; -static const SkColor kFileDragImageTextColor = SK_ColorBLACK; - -class FileDragImageSource : public gfx::CanvasImageSource { - public: - FileDragImageSource(const base::FilePath& file_name, - const gfx::ImageSkia& icon) - : CanvasImageSource(CalculateSize(icon), false), - file_name_(file_name), - icon_(icon) { - } - - virtual ~FileDragImageSource() { - } - - // Overridden from gfx::CanvasImageSource. - virtual void Draw(gfx::Canvas* canvas) override { - if (!icon_.isNull()) { - // Paint the icon. - canvas->DrawImageInt(icon_, (size().width() - icon_.width()) / 2, 0); - } - - base::string16 name = file_name_.BaseName().LossyDisplayName(); - const int flags = gfx::Canvas::TEXT_ALIGN_CENTER; - const gfx::FontList font_list; -#if defined(OS_WIN) - // Paint the file name. We inset it one pixel to allow room for the halo. - const gfx::Rect rect(1, icon_.height() + kLinkDragImageVPadding + 1, - size().width() - 2, font_list.GetHeight()); - canvas->DrawStringRectWithHalo(name, font_list, kFileDragImageTextColor, - SK_ColorWHITE, rect, flags); -#else - // NO_SUBPIXEL_RENDERING is required when drawing to a non-opaque canvas. - const gfx::Rect rect(0, icon_.height() + kLinkDragImageVPadding, - size().width(), font_list.GetHeight()); - canvas->DrawStringRectWithFlags(name, font_list, kFileDragImageTextColor, - rect, - flags | gfx::Canvas::NO_SUBPIXEL_RENDERING); -#endif - } - - private: - gfx::Size CalculateSize(const gfx::ImageSkia& icon) const { - const int width = kFileDragImageMaxWidth; - // Add +2 here to allow room for the halo. - const int height = gfx::FontList().GetHeight() + icon.height() + - kLinkDragImageVPadding + 2; - return gfx::Size(width, height); - } - - const base::FilePath file_name_; - const gfx::ImageSkia icon_; - - DISALLOW_COPY_AND_ASSIGN(FileDragImageSource); -}; - -} // namespace - -void CreateDragImageForFile(const base::FilePath& file_name, - const gfx::ImageSkia& icon, - ui::OSExchangeData* data_object) { - DCHECK(data_object); - gfx::CanvasImageSource* source = new FileDragImageSource(file_name, icon); - gfx::Size size = source->size(); - // ImageSkia takes ownership of |source|. - gfx::ImageSkia image = gfx::ImageSkia(source, size); - - gfx::Vector2d cursor_offset(size.width() / 2, kLinkDragImageVPadding); - SetDragImageOnDataObject(image, cursor_offset, data_object); -} - -void SetDragImageOnDataObject(const gfx::Canvas& canvas, - const gfx::Vector2d& cursor_offset, - ui::OSExchangeData* data_object) { - gfx::ImageSkia image = gfx::ImageSkia(canvas.ExtractImageRep()); - SetDragImageOnDataObject(image, cursor_offset, data_object); -} - -} // namespace drag_utils
diff --git a/ui/base/dragdrop/drag_utils.h b/ui/base/dragdrop/drag_utils.h deleted file mode 100644 index 48ee94f..0000000 --- a/ui/base/dragdrop/drag_utils.h +++ /dev/null
@@ -1,51 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_DRAGDROP_DRAG_UTILS_H_ -#define UI_BASE_DRAGDROP_DRAG_UTILS_H_ - -#include <string> - -#include "base/files/file_path.h" -#include "ui/base/ui_base_export.h" - -class GURL; - -namespace gfx { -class Canvas; -class ImageSkia; -class Size; -class Vector2d; -} - -namespace ui { -class OSExchangeData; -} -using ui::OSExchangeData; - -namespace drag_utils { - -// Creates a dragging image to be displayed when the user drags a file from -// Chrome (via the download manager, for example). The drag image is set into -// the supplied data_object. |file_name| can be a full path, but the directory -// portion will be truncated in the drag image. |icon| can be empty. -UI_BASE_EXPORT void CreateDragImageForFile(const base::FilePath& file_name, - const gfx::ImageSkia& icon, - ui::OSExchangeData* data_object); - -// Sets the drag image on data_object from the supplied canvas. -// |cursor_offset| gives the location of the hotspot for the drag image. -UI_BASE_EXPORT void SetDragImageOnDataObject(const gfx::Canvas& canvas, - const gfx::Vector2d& cursor_offset, - ui::OSExchangeData* data_object); - -// Sets the drag image on data_object from the supplied ImageSkia. -// |cursor_offset| gives the location of the hotspot for the drag image. -UI_BASE_EXPORT void SetDragImageOnDataObject(const gfx::ImageSkia& image_skia, - const gfx::Vector2d& cursor_offset, - ui::OSExchangeData* data_object); - -} // namespace drag_utils - -#endif // UI_BASE_DRAGDROP_DRAG_UTILS_H_
diff --git a/ui/base/dragdrop/drag_utils_aura.cc b/ui/base/dragdrop/drag_utils_aura.cc deleted file mode 100644 index e202e81..0000000 --- a/ui/base/dragdrop/drag_utils_aura.cc +++ /dev/null
@@ -1,23 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/dragdrop/drag_utils.h" - -#include "base/logging.h" -#include "ui/base/dragdrop/os_exchange_data.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/image/image_skia.h" -#include "ui/gfx/size.h" -#include "ui/gfx/vector2d.h" - -namespace drag_utils { - -void SetDragImageOnDataObject(const gfx::ImageSkia& image, - const gfx::Vector2d& cursor_offset, - ui::OSExchangeData* data_object) { - - data_object->provider().SetDragImage(image, cursor_offset); -} - -} // namespace drag_utils
diff --git a/ui/base/dragdrop/drag_utils_mac.mm b/ui/base/dragdrop/drag_utils_mac.mm deleted file mode 100644 index 22171bd..0000000 --- a/ui/base/dragdrop/drag_utils_mac.mm +++ /dev/null
@@ -1,23 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/dragdrop/drag_utils.h" - -#include "base/logging.h" - -namespace drag_utils { - -void SetDragImageOnDataObject(const gfx::Canvas& canvas, - const gfx::Vector2d& cursor_offset, - ui::OSExchangeData* data_object) { - NOTIMPLEMENTED(); -} - -void SetDragImageOnDataObject(const gfx::ImageSkia& image_skia, - const gfx::Vector2d& cursor_offset, - ui::OSExchangeData* data_object) { - NOTIMPLEMENTED(); -} - -} // namespace drag_utils
diff --git a/ui/base/dragdrop/drag_utils_win.cc b/ui/base/dragdrop/drag_utils_win.cc deleted file mode 100644 index 9fedd42..0000000 --- a/ui/base/dragdrop/drag_utils_win.cc +++ /dev/null
@@ -1,85 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/dragdrop/drag_utils.h" - -#include <objidl.h> -#include <shlobj.h> -#include <shobjidl.h> - -#include "base/win/scoped_comptr.h" -#include "base/win/scoped_hdc.h" -#include "third_party/skia/include/core/SkBitmap.h" -#include "ui/base/dragdrop/os_exchange_data.h" -#include "ui/base/dragdrop/os_exchange_data_provider_win.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/gdi_util.h" -#include "ui/gfx/geometry/size.h" -#include "ui/gfx/image/image_skia.h" -#include "ui/gfx/skbitmap_operations.h" - -namespace drag_utils { - -static void SetDragImageOnDataObject(HBITMAP hbitmap, - const gfx::Size& size_in_pixels, - const gfx::Vector2d& cursor_offset, - IDataObject* data_object) { - base::win::ScopedComPtr<IDragSourceHelper> helper; - HRESULT rv = CoCreateInstance(CLSID_DragDropHelper, 0, CLSCTX_INPROC_SERVER, - IID_IDragSourceHelper, helper.ReceiveVoid()); - if (SUCCEEDED(rv)) { - SHDRAGIMAGE sdi; - sdi.sizeDragImage = size_in_pixels.ToSIZE(); - sdi.crColorKey = 0xFFFFFFFF; - sdi.hbmpDragImage = hbitmap; - sdi.ptOffset = gfx::PointAtOffsetFromOrigin(cursor_offset).ToPOINT(); - helper->InitializeFromBitmap(&sdi, data_object); - } -} - -// Blit the contents of the canvas to a new HBITMAP. It is the caller's -// responsibility to release the |bits| buffer. -static HBITMAP CreateHBITMAPFromSkBitmap(const SkBitmap& sk_bitmap) { - base::win::ScopedGetDC screen_dc(NULL); - BITMAPINFOHEADER header; - gfx::CreateBitmapHeader(sk_bitmap.width(), sk_bitmap.height(), &header); - void* bits; - HBITMAP bitmap = - CreateDIBSection(screen_dc, reinterpret_cast<BITMAPINFO*>(&header), - DIB_RGB_COLORS, &bits, NULL, 0); - if (!bitmap || !bits) - return NULL; - DCHECK_EQ(sk_bitmap.rowBytes(), static_cast<size_t>(sk_bitmap.width() * 4)); - SkAutoLockPixels lock(sk_bitmap); - memcpy( - bits, sk_bitmap.getPixels(), sk_bitmap.height() * sk_bitmap.rowBytes()); - return bitmap; -} - -void SetDragImageOnDataObject(const gfx::ImageSkia& image_skia, - const gfx::Vector2d& cursor_offset, - ui::OSExchangeData* data_object) { - DCHECK(data_object && !image_skia.size().IsEmpty()); - // InitializeFromBitmap() doesn't expect an alpha channel and is confused - // by premultiplied colors, so unpremultiply the bitmap. - // SetDragImageOnDataObject(HBITMAP) takes ownership of the bitmap. - HBITMAP bitmap = CreateHBITMAPFromSkBitmap( - SkBitmapOperations::UnPreMultiply(*image_skia.bitmap())); - if (bitmap) { - // Attach 'bitmap' to the data_object. - SetDragImageOnDataObject( - bitmap, - gfx::Size(image_skia.bitmap()->width(), image_skia.bitmap()->height()), - cursor_offset, - ui::OSExchangeDataProviderWin::GetIDataObject(*data_object)); - } - - // TODO: the above code is used in non-Ash, while below is used in Ash. If we - // could figure this context out then we wouldn't do unnecessary work. However - // as it stands getting this information in ui/base would be a layering - // violation. - data_object->provider().SetDragImage(image_skia, cursor_offset); -} - -} // namespace drag_utils
diff --git a/ui/base/dragdrop/drop_target_event.cc b/ui/base/dragdrop/drop_target_event.cc deleted file mode 100644 index bbbf84a..0000000 --- a/ui/base/dragdrop/drop_target_event.cc +++ /dev/null
@@ -1,28 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/dragdrop/drop_target_event.h" - -#include "ui/events/event_utils.h" - -namespace ui { - -//////////////////////////////////////////////////////////////////////////////// -// DropTargetEvent - -DropTargetEvent::DropTargetEvent(const OSExchangeData& data, - const gfx::Point& location, - const gfx::Point& root_location, - int source_operations) - : LocatedEvent(ET_DROP_TARGET_EVENT, - location, - root_location, - EventTimeForNow(), - 0), - data_(data), - source_operations_(source_operations) { -} - -} // namespace ui -
diff --git a/ui/base/dragdrop/drop_target_event.h b/ui/base/dragdrop/drop_target_event.h deleted file mode 100644 index 18c0630..0000000 --- a/ui/base/dragdrop/drop_target_event.h +++ /dev/null
@@ -1,36 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_DRAGDROP_DROP_TARGET_EVENT_H_ -#define UI_BASE_DRAGDROP_DROP_TARGET_EVENT_H_ - -#include "ui/events/event.h" -#include "ui/base/dragdrop/os_exchange_data.h" - -namespace ui { - -class UI_BASE_EXPORT DropTargetEvent : public LocatedEvent { - public: - DropTargetEvent(const OSExchangeData& data, - const gfx::Point& location, - const gfx::Point& root_location, - int source_operations); - - const OSExchangeData& data() const { return data_; } - int source_operations() const { return source_operations_; } - - private: - // Data associated with the drag/drop session. - const OSExchangeData& data_; - - // Bitmask of supported DragDropTypes::DragOperation by the source. - int source_operations_; - - DISALLOW_COPY_AND_ASSIGN(DropTargetEvent); -}; - -} // namespace ui - -#endif // UI_BASE_DRAGDROP_DROP_TARGET_EVENT_H_ -
diff --git a/ui/base/dragdrop/drop_target_win.cc b/ui/base/dragdrop/drop_target_win.cc deleted file mode 100644 index e3a105e..0000000 --- a/ui/base/dragdrop/drop_target_win.cc +++ /dev/null
@@ -1,149 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/dragdrop/drop_target_win.h" - -#include <shlobj.h> - -#include "base/logging.h" - -namespace ui { - -IDropTargetHelper* DropTargetWin::cached_drop_target_helper_ = NULL; - -DropTargetWin::DropTargetWin(HWND hwnd) - : hwnd_(hwnd), - ref_count_(0) { - DCHECK(hwnd); - HRESULT result = RegisterDragDrop(hwnd, this); - DCHECK(SUCCEEDED(result)); -} - -DropTargetWin::~DropTargetWin() { -} - -// static -IDropTargetHelper* DropTargetWin::DropHelper() { - if (!cached_drop_target_helper_) { - CoCreateInstance(CLSID_DragDropHelper, 0, CLSCTX_INPROC_SERVER, - IID_IDropTargetHelper, - reinterpret_cast<void**>(&cached_drop_target_helper_)); - } - return cached_drop_target_helper_; -} - -/////////////////////////////////////////////////////////////////////////////// -// DropTargetWin, IDropTarget implementation: - -HRESULT DropTargetWin::DragEnter(IDataObject* data_object, - DWORD key_state, - POINTL cursor_position, - DWORD* effect) { - // Tell the helper that we entered so it can update the drag image. - IDropTargetHelper* drop_helper = DropHelper(); - if (drop_helper) { - drop_helper->DragEnter(GetHWND(), data_object, - reinterpret_cast<POINT*>(&cursor_position), *effect); - } - - current_data_object_ = data_object; - POINT screen_pt = { cursor_position.x, cursor_position.y }; - *effect = OnDragEnter(current_data_object_.get(), key_state, screen_pt, - *effect); - return S_OK; -} - -HRESULT DropTargetWin::DragOver(DWORD key_state, - POINTL cursor_position, - DWORD* effect) { - // Tell the helper that we moved over it so it can update the drag image. - IDropTargetHelper* drop_helper = DropHelper(); - if (drop_helper) - drop_helper->DragOver(reinterpret_cast<POINT*>(&cursor_position), *effect); - - POINT screen_pt = { cursor_position.x, cursor_position.y }; - *effect = OnDragOver(current_data_object_.get(), key_state, screen_pt, - *effect); - return S_OK; -} - -HRESULT DropTargetWin::DragLeave() { - // Tell the helper that we moved out of it so it can update the drag image. - IDropTargetHelper* drop_helper = DropHelper(); - if (drop_helper) - drop_helper->DragLeave(); - - OnDragLeave(current_data_object_.get()); - - current_data_object_ = NULL; - return S_OK; -} - -HRESULT DropTargetWin::Drop(IDataObject* data_object, - DWORD key_state, - POINTL cursor_position, - DWORD* effect) { - // Tell the helper that we dropped onto it so it can update the drag image. - IDropTargetHelper* drop_helper = DropHelper(); - if (drop_helper) { - drop_helper->Drop(current_data_object_.get(), - reinterpret_cast<POINT*>(&cursor_position), *effect); - } - - POINT screen_pt = { cursor_position.x, cursor_position.y }; - *effect = OnDrop(current_data_object_.get(), key_state, screen_pt, *effect); - return S_OK; -} - -/////////////////////////////////////////////////////////////////////////////// -// DropTargetWin, IUnknown implementation: - -HRESULT DropTargetWin::QueryInterface(const IID& iid, void** object) { - *object = NULL; - if (IsEqualIID(iid, IID_IUnknown) || IsEqualIID(iid, IID_IDropTarget)) { - *object = this; - } else { - return E_NOINTERFACE; - } - AddRef(); - return S_OK; -} - -ULONG DropTargetWin::AddRef() { - return ++ref_count_; -} - -ULONG DropTargetWin::Release() { - if (--ref_count_ == 0) { - delete this; - return 0U; - } - return ref_count_; -} - -DWORD DropTargetWin::OnDragEnter(IDataObject* data_object, - DWORD key_state, - POINT cursor_position, - DWORD effect) { - return DROPEFFECT_NONE; -} - -DWORD DropTargetWin::OnDragOver(IDataObject* data_object, - DWORD key_state, - POINT cursor_position, - DWORD effect) { - return DROPEFFECT_NONE; -} - -void DropTargetWin::OnDragLeave(IDataObject* data_object) { -} - -DWORD DropTargetWin::OnDrop(IDataObject* data_object, - DWORD key_state, - POINT cursor_position, - DWORD effect) { - return DROPEFFECT_NONE; -} - -} // namespace ui
diff --git a/ui/base/dragdrop/drop_target_win.h b/ui/base/dragdrop/drop_target_win.h deleted file mode 100644 index 4536f1d..0000000 --- a/ui/base/dragdrop/drop_target_win.h +++ /dev/null
@@ -1,114 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_DRAGDROP_DROP_TARGET_WIN_H_ -#define UI_BASE_DRAGDROP_DROP_TARGET_WIN_H_ - -#include <objidl.h> - -#include "base/memory/ref_counted.h" -#include "ui/base/ui_base_export.h" - -// Windows interface. -struct IDropTargetHelper; - -namespace ui { - -// A DropTarget implementation that takes care of the nitty gritty -// of dnd. While this class is concrete, subclasses will most likely -// want to override various OnXXX methods. -// -// Because DropTarget is ref counted you shouldn't delete it directly, -// rather wrap it in a scoped_refptr. Be sure and invoke RevokeDragDrop(m_hWnd) -// before the HWND is deleted too. -// -// This class is meant to be used in a STA and is not multithread-safe. -class UI_BASE_EXPORT DropTargetWin : public IDropTarget { - public: - // Create a new DropTarget associating it with the given HWND. - explicit DropTargetWin(HWND hwnd); - virtual ~DropTargetWin(); - - // IDropTarget implementation: - HRESULT __stdcall DragEnter(IDataObject* data_object, - DWORD key_state, - POINTL cursor_position, - DWORD* effect); - HRESULT __stdcall DragOver(DWORD key_state, - POINTL cursor_position, - DWORD* effect); - HRESULT __stdcall DragLeave(); - HRESULT __stdcall Drop(IDataObject* data_object, - DWORD key_state, - POINTL cursor_position, - DWORD* effect); - - // IUnknown implementation: - HRESULT __stdcall QueryInterface(const IID& iid, void** object); - ULONG __stdcall AddRef(); - ULONG __stdcall Release(); - - protected: - // Returns the hosting HWND. - HWND GetHWND() { return hwnd_; } - - // Invoked when the cursor first moves over the hwnd during a dnd session. - // This should return a bitmask of the supported drop operations: - // DROPEFFECT_NONE, DROPEFFECT_COPY, DROPEFFECT_LINK and/or - // DROPEFFECT_MOVE. - virtual DWORD OnDragEnter(IDataObject* data_object, - DWORD key_state, - POINT cursor_position, - DWORD effect); - - // Invoked when the cursor moves over the window during a dnd session. - // This should return a bitmask of the supported drop operations: - // DROPEFFECT_NONE, DROPEFFECT_COPY, DROPEFFECT_LINK and/or - // DROPEFFECT_MOVE. - virtual DWORD OnDragOver(IDataObject* data_object, - DWORD key_state, - POINT cursor_position, - DWORD effect); - - // Invoked when the cursor moves outside the bounds of the hwnd during a - // dnd session. - virtual void OnDragLeave(IDataObject* data_object); - - // Invoked when the drop ends on the window. This should return the operation - // that was taken. - virtual DWORD OnDrop(IDataObject* data_object, - DWORD key_state, - POINT cursor_position, - DWORD effect); - - private: - // Returns the cached drop helper, creating one if necessary. The returned - // object is not addrefed. May return NULL if the object couldn't be created. - static IDropTargetHelper* DropHelper(); - - // The data object currently being dragged over this drop target. - scoped_refptr<IDataObject> current_data_object_; - - // A helper object that is used to provide drag image support while the mouse - // is dragging over the content area. - // - // DO NOT ACCESS DIRECTLY! Use DropHelper() instead, which will lazily create - // this if it doesn't exist yet. This object can take tens of milliseconds to - // create, and we don't want to block any window opening for this, especially - // since often, DnD will never be used. Instead, we force this penalty to the - // first time it is actually used. - static IDropTargetHelper* cached_drop_target_helper_; - - // The HWND of the source. This HWND is used to determine coordinates for - // mouse events that are sent to the renderer notifying various drag states. - HWND hwnd_; - - LONG ref_count_; - - DISALLOW_COPY_AND_ASSIGN(DropTargetWin); -}; - -} // namespace ui - -#endif // UI_BASE_DRAGDROP_DROP_TARGET_WIN_H_
diff --git a/ui/base/dragdrop/file_info.cc b/ui/base/dragdrop/file_info.cc deleted file mode 100644 index e5b894a..0000000 --- a/ui/base/dragdrop/file_info.cc +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/dragdrop/file_info.h" - -namespace ui { - -FileInfo::FileInfo() {} - -FileInfo::FileInfo(const base::FilePath& path, - const base::FilePath& display_name) - : path(path), display_name(display_name) {} - -FileInfo::~FileInfo() {} - -} // namespace ui
diff --git a/ui/base/dragdrop/file_info.h b/ui/base/dragdrop/file_info.h deleted file mode 100644 index 6e4f456..0000000 --- a/ui/base/dragdrop/file_info.h +++ /dev/null
@@ -1,25 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_DRAGDROP_FILE_INFO_H_ -#define UI_BASE_DRAGDROP_FILE_INFO_H_ - -#include "base/files/file_path.h" -#include "ui/base/ui_base_export.h" - -namespace ui { - -// struct that bundles a file's path with an optional display name. -struct UI_BASE_EXPORT FileInfo { - FileInfo(); - FileInfo(const base::FilePath& path, const base::FilePath& display_name); - ~FileInfo(); - - base::FilePath path; - base::FilePath display_name; // Optional. -}; - -} // namespace ui - -#endif // UI_BASE_DRAGDROP_FILE_INFO_H_
diff --git a/ui/base/dragdrop/os_exchange_data.cc b/ui/base/dragdrop/os_exchange_data.cc deleted file mode 100644 index c236a46..0000000 --- a/ui/base/dragdrop/os_exchange_data.cc +++ /dev/null
@@ -1,151 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/dragdrop/os_exchange_data.h" - -#include "base/pickle.h" -#include "url/gurl.h" - -namespace ui { - -OSExchangeData::DownloadFileInfo::DownloadFileInfo( - const base::FilePath& filename, - DownloadFileProvider* downloader) - : filename(filename), - downloader(downloader) { -} - -OSExchangeData::DownloadFileInfo::~DownloadFileInfo() {} - -OSExchangeData::OSExchangeData() : provider_(CreateProvider()) { -} - -OSExchangeData::OSExchangeData(Provider* provider) : provider_(provider) { -} - -OSExchangeData::~OSExchangeData() { -} - -void OSExchangeData::MarkOriginatedFromRenderer() { - provider_->MarkOriginatedFromRenderer(); -} - -bool OSExchangeData::DidOriginateFromRenderer() const { - return provider_->DidOriginateFromRenderer(); -} - -void OSExchangeData::SetString(const base::string16& data) { - provider_->SetString(data); -} - -void OSExchangeData::SetURL(const GURL& url, const base::string16& title) { - provider_->SetURL(url, title); -} - -void OSExchangeData::SetFilename(const base::FilePath& path) { - provider_->SetFilename(path); -} - -void OSExchangeData::SetFilenames( - const std::vector<FileInfo>& filenames) { - provider_->SetFilenames(filenames); -} - -void OSExchangeData::SetPickledData(const CustomFormat& format, - const Pickle& data) { - provider_->SetPickledData(format, data); -} - -bool OSExchangeData::GetString(base::string16* data) const { - return provider_->GetString(data); -} - -bool OSExchangeData::GetURLAndTitle(FilenameToURLPolicy policy, - GURL* url, - base::string16* title) const { - return provider_->GetURLAndTitle(policy, url, title); -} - -bool OSExchangeData::GetFilename(base::FilePath* path) const { - return provider_->GetFilename(path); -} - -bool OSExchangeData::GetFilenames( - std::vector<FileInfo>* filenames) const { - return provider_->GetFilenames(filenames); -} - -bool OSExchangeData::GetPickledData(const CustomFormat& format, - Pickle* data) const { - return provider_->GetPickledData(format, data); -} - -bool OSExchangeData::HasString() const { - return provider_->HasString(); -} - -bool OSExchangeData::HasURL(FilenameToURLPolicy policy) const { - return provider_->HasURL(policy); -} - -bool OSExchangeData::HasFile() const { - return provider_->HasFile(); -} - -bool OSExchangeData::HasCustomFormat(const CustomFormat& format) const { - return provider_->HasCustomFormat(format); -} - -bool OSExchangeData::HasAnyFormat( - int formats, - const std::set<CustomFormat>& custom_formats) const { - if ((formats & STRING) != 0 && HasString()) - return true; - if ((formats & URL) != 0 && HasURL(CONVERT_FILENAMES)) - return true; -#if defined(OS_WIN) - if ((formats & FILE_CONTENTS) != 0 && provider_->HasFileContents()) - return true; -#endif -#if defined(USE_AURA) - if ((formats & HTML) != 0 && provider_->HasHtml()) - return true; -#endif - if ((formats & FILE_NAME) != 0 && provider_->HasFile()) - return true; - for (std::set<CustomFormat>::const_iterator i = custom_formats.begin(); - i != custom_formats.end(); ++i) { - if (HasCustomFormat(*i)) - return true; - } - return false; -} - -#if defined(OS_WIN) -void OSExchangeData::SetFileContents(const base::FilePath& filename, - const std::string& file_contents) { - provider_->SetFileContents(filename, file_contents); -} - -bool OSExchangeData::GetFileContents(base::FilePath* filename, - std::string* file_contents) const { - return provider_->GetFileContents(filename, file_contents); -} - -void OSExchangeData::SetDownloadFileInfo(const DownloadFileInfo& download) { - provider_->SetDownloadFileInfo(download); -} -#endif - -#if defined(USE_AURA) -void OSExchangeData::SetHtml(const base::string16& html, const GURL& base_url) { - provider_->SetHtml(html, base_url); -} - -bool OSExchangeData::GetHtml(base::string16* html, GURL* base_url) const { - return provider_->GetHtml(html, base_url); -} -#endif - -} // namespace ui
diff --git a/ui/base/dragdrop/os_exchange_data.h b/ui/base/dragdrop/os_exchange_data.h deleted file mode 100644 index 539e894..0000000 --- a/ui/base/dragdrop/os_exchange_data.h +++ /dev/null
@@ -1,240 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_DRAGDROP_OS_EXCHANGE_DATA_H_ -#define UI_BASE_DRAGDROP_OS_EXCHANGE_DATA_H_ - -#include "build/build_config.h" - -#include <set> -#include <string> - -#if defined(OS_WIN) -#include <objidl.h> -#endif - -#include "base/basictypes.h" -#include "base/files/file_path.h" -#include "base/memory/scoped_ptr.h" -#include "ui/base/clipboard/clipboard.h" -#include "ui/base/dragdrop/download_file_interface.h" -#include "ui/base/ui_base_export.h" - -class GURL; -class Pickle; - -namespace gfx { -class ImageSkia; -class Vector2d; -} - -namespace ui { - -struct FileInfo; - -/////////////////////////////////////////////////////////////////////////////// -// -// OSExchangeData -// An object that holds interchange data to be sent out to OS services like -// clipboard, drag and drop, etc. This object exposes an API that clients can -// use to specify raw data and its high level type. This object takes care of -// translating that into something the OS can understand. -// -/////////////////////////////////////////////////////////////////////////////// - -// NOTE: Support for html and file contents is required by TabContentViewWin. -// TabContentsViewGtk uses a different class to handle drag support that does -// not use OSExchangeData. As such, file contents and html support is only -// compiled on windows. -class UI_BASE_EXPORT OSExchangeData { - public: - // CustomFormats are used for non-standard data types. For example, bookmark - // nodes are written using a CustomFormat. - // TODO(dcheng): Remove this completely and just use Clipboard::FormatType. - typedef Clipboard::FormatType CustomFormat; - - // Enumeration of the known formats. - enum Format { - STRING = 1 << 0, - URL = 1 << 1, - FILE_NAME = 1 << 2, - PICKLED_DATA = 1 << 3, -#if defined(OS_WIN) - FILE_CONTENTS = 1 << 4, -#endif -#if defined(USE_AURA) - HTML = 1 << 5, -#endif - }; - - // Controls whether or not filenames should be converted to file: URLs when - // getting a URL. - enum FilenameToURLPolicy { CONVERT_FILENAMES, DO_NOT_CONVERT_FILENAMES, }; - - // Encapsulates the info about a file to be downloaded. - struct UI_BASE_EXPORT DownloadFileInfo { - DownloadFileInfo(const base::FilePath& filename, - DownloadFileProvider* downloader); - ~DownloadFileInfo(); - - base::FilePath filename; - scoped_refptr<DownloadFileProvider> downloader; - }; - - // Provider defines the platform specific part of OSExchangeData that - // interacts with the native system. - class UI_BASE_EXPORT Provider { - public: - Provider() {} - virtual ~Provider() {} - - virtual Provider* Clone() const = 0; - - virtual void MarkOriginatedFromRenderer() = 0; - virtual bool DidOriginateFromRenderer() const = 0; - - virtual void SetString(const base::string16& data) = 0; - virtual void SetURL(const GURL& url, const base::string16& title) = 0; - virtual void SetFilename(const base::FilePath& path) = 0; - virtual void SetFilenames( - const std::vector<FileInfo>& file_names) = 0; - virtual void SetPickledData(const CustomFormat& format, - const Pickle& data) = 0; - - virtual bool GetString(base::string16* data) const = 0; - virtual bool GetURLAndTitle(FilenameToURLPolicy policy, - GURL* url, - base::string16* title) const = 0; - virtual bool GetFilename(base::FilePath* path) const = 0; - virtual bool GetFilenames( - std::vector<FileInfo>* file_names) const = 0; - virtual bool GetPickledData(const CustomFormat& format, - Pickle* data) const = 0; - - virtual bool HasString() const = 0; - virtual bool HasURL(FilenameToURLPolicy policy) const = 0; - virtual bool HasFile() const = 0; - virtual bool HasCustomFormat(const CustomFormat& format) const = 0; - -#if (!defined(OS_CHROMEOS) && defined(USE_X11)) || defined(OS_WIN) - virtual void SetFileContents(const base::FilePath& filename, - const std::string& file_contents) = 0; -#endif -#if defined(OS_WIN) - virtual bool GetFileContents(base::FilePath* filename, - std::string* file_contents) const = 0; - virtual bool HasFileContents() const = 0; - virtual void SetDownloadFileInfo(const DownloadFileInfo& download) = 0; -#endif - -#if defined(USE_AURA) - virtual void SetHtml(const base::string16& html, const GURL& base_url) = 0; - virtual bool GetHtml(base::string16* html, GURL* base_url) const = 0; - virtual bool HasHtml() const = 0; -#endif - -#if defined(USE_AURA) - virtual void SetDragImage(const gfx::ImageSkia& image, - const gfx::Vector2d& cursor_offset) = 0; - virtual const gfx::ImageSkia& GetDragImage() const = 0; - virtual const gfx::Vector2d& GetDragImageOffset() const = 0; -#endif - }; - - // Creates the platform specific Provider. - static Provider* CreateProvider(); - - OSExchangeData(); - // Creates an OSExchangeData with the specified provider. OSExchangeData - // takes ownership of the supplied provider. - explicit OSExchangeData(Provider* provider); - - ~OSExchangeData(); - - // Returns the Provider, which actually stores and manages the data. - const Provider& provider() const { return *provider_; } - Provider& provider() { return *provider_; } - - // Marks drag data as tainted if it originates from the renderer. This is used - // to avoid granting privileges to a renderer when dragging in tainted data, - // since it could allow potential escalation of privileges. - void MarkOriginatedFromRenderer(); - bool DidOriginateFromRenderer() const; - - // These functions add data to the OSExchangeData object of various Chrome - // types. The OSExchangeData object takes care of translating the data into - // a format suitable for exchange with the OS. - // NOTE WELL: Typically, a data object like this will contain only one of the - // following types of data. In cases where more data is held, the - // order in which these functions are called is _important_! - // ---> The order types are added to an OSExchangeData object controls - // the order of enumeration in our IEnumFORMATETC implementation! - // This comes into play when selecting the best (most preferable) - // data type for insertion into a DropTarget. - void SetString(const base::string16& data); - // A URL can have an optional title in some exchange formats. - void SetURL(const GURL& url, const base::string16& title); - // A full path to a file. - void SetFilename(const base::FilePath& path); - // Full path to one or more files. See also SetFilenames() in Provider. - void SetFilenames( - const std::vector<FileInfo>& file_names); - // Adds pickled data of the specified format. - void SetPickledData(const CustomFormat& format, const Pickle& data); - - // These functions retrieve data of the specified type. If data exists, the - // functions return and the result is in the out parameter. If the data does - // not exist, the out parameter is not touched. The out parameter cannot be - // NULL. - bool GetString(base::string16* data) const; - bool GetURLAndTitle(FilenameToURLPolicy policy, - GURL* url, - base::string16* title) const; - // Return the path of a file, if available. - bool GetFilename(base::FilePath* path) const; - bool GetFilenames( - std::vector<FileInfo>* file_names) const; - bool GetPickledData(const CustomFormat& format, Pickle* data) const; - - // Test whether or not data of certain types is present, without actually - // returning anything. - bool HasString() const; - bool HasURL(FilenameToURLPolicy policy) const; - bool HasFile() const; - bool HasCustomFormat(const CustomFormat& format) const; - - // Returns true if this OSExchangeData has data in any of the formats in - // |formats| or any custom format in |custom_formats|. - bool HasAnyFormat(int formats, - const std::set<CustomFormat>& custom_formats) const; - -#if defined(OS_WIN) - // Adds the bytes of a file (CFSTR_FILECONTENTS and CFSTR_FILEDESCRIPTOR on - // Windows). - void SetFileContents(const base::FilePath& filename, - const std::string& file_contents); - bool GetFileContents(base::FilePath* filename, - std::string* file_contents) const; - - // Adds a download file with full path (CF_HDROP). - void SetDownloadFileInfo(const DownloadFileInfo& download); -#endif - -#if defined(USE_AURA) - // Adds a snippet of HTML. |html| is just raw html but this sets both - // text/html and CF_HTML. - void SetHtml(const base::string16& html, const GURL& base_url); - bool GetHtml(base::string16* html, GURL* base_url) const; -#endif - - private: - // Provides the actual data. - scoped_ptr<Provider> provider_; - - DISALLOW_COPY_AND_ASSIGN(OSExchangeData); -}; - -} // namespace ui - -#endif // UI_BASE_DRAGDROP_OS_EXCHANGE_DATA_H_
diff --git a/ui/base/dragdrop/os_exchange_data_provider_aura.cc b/ui/base/dragdrop/os_exchange_data_provider_aura.cc deleted file mode 100644 index 0d4fb90..0000000 --- a/ui/base/dragdrop/os_exchange_data_provider_aura.cc +++ /dev/null
@@ -1,214 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/dragdrop/os_exchange_data_provider_aura.h" - -#include "base/logging.h" -#include "base/strings/utf_string_conversions.h" -#include "net/base/net_util.h" -#include "ui/base/clipboard/clipboard.h" -#include "ui/base/clipboard/scoped_clipboard_writer.h" -#include "ui/base/dragdrop/file_info.h" - -namespace ui { - -OSExchangeDataProviderAura::OSExchangeDataProviderAura() - : formats_(0) { -} - -OSExchangeDataProviderAura::~OSExchangeDataProviderAura() {} - -OSExchangeData::Provider* OSExchangeDataProviderAura::Clone() const { - OSExchangeDataProviderAura* ret = new OSExchangeDataProviderAura(); - ret->formats_ = formats_; - ret->string_ = string_; - ret->url_ = url_; - ret->title_ = title_; - ret->filenames_ = filenames_; - ret->pickle_data_ = pickle_data_; - // We skip copying the drag images. - ret->html_ = html_; - ret->base_url_ = base_url_; - - return ret; -} - -void OSExchangeDataProviderAura::MarkOriginatedFromRenderer() { - // TODO(dcheng): Currently unneeded because ChromeOS Aura correctly separates - // URL and filename metadata, and does not implement the DownloadURL protocol. -} - -bool OSExchangeDataProviderAura::DidOriginateFromRenderer() const { - return false; -} - -void OSExchangeDataProviderAura::SetString(const base::string16& data) { - if (HasString()) - return; - - string_ = data; - formats_ |= OSExchangeData::STRING; -} - -void OSExchangeDataProviderAura::SetURL(const GURL& url, - const base::string16& title) { - url_ = url; - title_ = title; - formats_ |= OSExchangeData::URL; - - SetString(base::UTF8ToUTF16(url.spec())); -} - -void OSExchangeDataProviderAura::SetFilename(const base::FilePath& path) { - filenames_.clear(); - filenames_.push_back(FileInfo(path, base::FilePath())); - formats_ |= OSExchangeData::FILE_NAME; -} - -void OSExchangeDataProviderAura::SetFilenames( - const std::vector<FileInfo>& filenames) { - filenames_ = filenames; - formats_ |= OSExchangeData::FILE_NAME; -} - -void OSExchangeDataProviderAura::SetPickledData( - const OSExchangeData::CustomFormat& format, - const Pickle& data) { - pickle_data_[format] = data; - formats_ |= OSExchangeData::PICKLED_DATA; -} - -bool OSExchangeDataProviderAura::GetString(base::string16* data) const { - if ((formats_ & OSExchangeData::STRING) == 0) - return false; - *data = string_; - return true; -} - -bool OSExchangeDataProviderAura::GetURLAndTitle( - OSExchangeData::FilenameToURLPolicy policy, - GURL* url, - base::string16* title) const { - // TODO(dcheng): implement filename conversion. - if ((formats_ & OSExchangeData::URL) == 0) { - title->clear(); - return GetPlainTextURL(url); - } - - if (!url_.is_valid()) - return false; - - *url = url_; - *title = title_; - return true; -} - -bool OSExchangeDataProviderAura::GetFilename(base::FilePath* path) const { - if ((formats_ & OSExchangeData::FILE_NAME) == 0) - return false; - DCHECK(!filenames_.empty()); - *path = filenames_[0].path; - return true; -} - -bool OSExchangeDataProviderAura::GetFilenames( - std::vector<FileInfo>* filenames) const { - if ((formats_ & OSExchangeData::FILE_NAME) == 0) - return false; - *filenames = filenames_; - return true; -} - -bool OSExchangeDataProviderAura::GetPickledData( - const OSExchangeData::CustomFormat& format, - Pickle* data) const { - PickleData::const_iterator i = pickle_data_.find(format); - if (i == pickle_data_.end()) - return false; - - *data = i->second; - return true; -} - -bool OSExchangeDataProviderAura::HasString() const { - return (formats_ & OSExchangeData::STRING) != 0; -} - -bool OSExchangeDataProviderAura::HasURL( - OSExchangeData::FilenameToURLPolicy policy) const { - // TODO(dcheng): implement filename conversion. - if ((formats_ & OSExchangeData::URL) != 0) { - return true; - } - // No URL, see if we have plain text that can be parsed as a URL. - return GetPlainTextURL(NULL); -} - -bool OSExchangeDataProviderAura::HasFile() const { - return (formats_ & OSExchangeData::FILE_NAME) != 0; -} - -bool OSExchangeDataProviderAura::HasCustomFormat( - const OSExchangeData::CustomFormat& format) const { - return pickle_data_.find(format) != pickle_data_.end(); -} - -void OSExchangeDataProviderAura::SetHtml(const base::string16& html, - const GURL& base_url) { - formats_ |= OSExchangeData::HTML; - html_ = html; - base_url_ = base_url; -} - -bool OSExchangeDataProviderAura::GetHtml(base::string16* html, - GURL* base_url) const { - if ((formats_ & OSExchangeData::HTML) == 0) - return false; - *html = html_; - *base_url = base_url_; - return true; -} - -bool OSExchangeDataProviderAura::HasHtml() const { - return ((formats_ & OSExchangeData::HTML) != 0); -} - -void OSExchangeDataProviderAura::SetDragImage( - const gfx::ImageSkia& image, - const gfx::Vector2d& cursor_offset) { - drag_image_ = image; - drag_image_offset_ = cursor_offset; -} - -const gfx::ImageSkia& OSExchangeDataProviderAura::GetDragImage() const { - return drag_image_; -} - -const gfx::Vector2d& -OSExchangeDataProviderAura::GetDragImageOffset() const { - return drag_image_offset_; -} - -bool OSExchangeDataProviderAura::GetPlainTextURL(GURL* url) const { - if ((formats_ & OSExchangeData::STRING) == 0) - return false; - - GURL test_url(string_); - if (!test_url.is_valid()) - return false; - - if (url) - *url = test_url; - return true; -} - -/////////////////////////////////////////////////////////////////////////////// -// OSExchangeData, public: - -// static -OSExchangeData::Provider* OSExchangeData::CreateProvider() { - return new OSExchangeDataProviderAura(); -} - -} // namespace ui
diff --git a/ui/base/dragdrop/os_exchange_data_provider_aura.h b/ui/base/dragdrop/os_exchange_data_provider_aura.h deleted file mode 100644 index 88218a2..0000000 --- a/ui/base/dragdrop/os_exchange_data_provider_aura.h +++ /dev/null
@@ -1,99 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_DRAGDROP_OS_EXCHANGE_DATA_PROVIDER_AURA_H_ -#define UI_BASE_DRAGDROP_OS_EXCHANGE_DATA_PROVIDER_AURA_H_ - -#include <map> - -#include "base/files/file_path.h" -#include "base/pickle.h" -#include "ui/base/dragdrop/os_exchange_data.h" -#include "ui/gfx/image/image_skia.h" -#include "ui/gfx/vector2d.h" -#include "url/gurl.h" - -namespace ui { - -class Clipboard; - -// OSExchangeData::Provider implementation for aura on linux. -class UI_BASE_EXPORT OSExchangeDataProviderAura - : public OSExchangeData::Provider { - public: - OSExchangeDataProviderAura(); - virtual ~OSExchangeDataProviderAura(); - - // Overridden from OSExchangeData::Provider: - virtual Provider* Clone() const override; - virtual void MarkOriginatedFromRenderer() override; - virtual bool DidOriginateFromRenderer() const override; - virtual void SetString(const base::string16& data) override; - virtual void SetURL(const GURL& url, const base::string16& title) override; - virtual void SetFilename(const base::FilePath& path) override; - virtual void SetFilenames(const std::vector<FileInfo>& filenames) override; - virtual void SetPickledData(const OSExchangeData::CustomFormat& format, - const Pickle& data) override; - virtual bool GetString(base::string16* data) const override; - virtual bool GetURLAndTitle(OSExchangeData::FilenameToURLPolicy policy, - GURL* url, - base::string16* title) const override; - virtual bool GetFilename(base::FilePath* path) const override; - virtual bool GetFilenames(std::vector<FileInfo>* filenames) const override; - virtual bool GetPickledData(const OSExchangeData::CustomFormat& format, - Pickle* data) const override; - virtual bool HasString() const override; - virtual bool HasURL(OSExchangeData::FilenameToURLPolicy policy) const - override; - virtual bool HasFile() const override; - virtual bool HasCustomFormat(const OSExchangeData::CustomFormat& format) const - override; - - virtual void SetHtml(const base::string16& html, - const GURL& base_url) override; - virtual bool GetHtml(base::string16* html, GURL* base_url) const override; - virtual bool HasHtml() const override; - virtual void SetDragImage(const gfx::ImageSkia& image, - const gfx::Vector2d& cursor_offset) override; - virtual const gfx::ImageSkia& GetDragImage() const override; - virtual const gfx::Vector2d& GetDragImageOffset() const override; - - private: - typedef std::map<OSExchangeData::CustomFormat, Pickle> PickleData; - - // Returns true if |formats_| contains a string format and the string can be - // parsed as a URL. - bool GetPlainTextURL(GURL* url) const; - - // Actual formats that have been set. See comment above |known_formats_| - // for details. - int formats_; - - // String contents. - base::string16 string_; - - // URL contents. - GURL url_; - base::string16 title_; - - // File name. - std::vector<FileInfo> filenames_; - - // PICKLED_DATA contents. - PickleData pickle_data_; - - // Drag image and offset data. - gfx::ImageSkia drag_image_; - gfx::Vector2d drag_image_offset_; - - // For HTML format - base::string16 html_; - GURL base_url_; - - DISALLOW_COPY_AND_ASSIGN(OSExchangeDataProviderAura); -}; - -} // namespace ui - -#endif // UI_BASE_DRAGDROP_OS_EXCHANGE_DATA_PROVIDER_AURA_H_
diff --git a/ui/base/dragdrop/os_exchange_data_provider_aurax11.cc b/ui/base/dragdrop/os_exchange_data_provider_aurax11.cc deleted file mode 100644 index 714069f..0000000 --- a/ui/base/dragdrop/os_exchange_data_provider_aurax11.cc +++ /dev/null
@@ -1,553 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/dragdrop/os_exchange_data_provider_aurax11.h" - -#include "base/logging.h" -#include "base/memory/ref_counted_memory.h" -#include "base/strings/string_util.h" -#include "base/strings/utf_string_conversions.h" -#include "net/base/filename_util.h" -#include "ui/base/clipboard/clipboard.h" -#include "ui/base/clipboard/scoped_clipboard_writer.h" -#include "ui/base/dragdrop/file_info.h" -#include "ui/base/x/selection_utils.h" -#include "ui/base/x/x11_util.h" -#include "ui/events/platform/platform_event_source.h" - -// Note: the GetBlah() methods are used immediately by the -// web_contents_view_aura.cc:PrepareDropData(), while the omnibox is a -// little more discriminating and calls HasBlah() before trying to get the -// information. - -namespace ui { - -namespace { - -const char kDndSelection[] = "XdndSelection"; -const char kRendererTaint[] = "chromium/x-renderer-taint"; - -const char kNetscapeURL[] = "_NETSCAPE_URL"; - -const char* kAtomsToCache[] = { - kString, - kText, - kUtf8String, - kDndSelection, - Clipboard::kMimeTypeURIList, - kMimeTypeMozillaURL, - kNetscapeURL, - Clipboard::kMimeTypeText, - kRendererTaint, - NULL -}; - -} // namespace - -OSExchangeDataProviderAuraX11::OSExchangeDataProviderAuraX11( - ::Window x_window, - const SelectionFormatMap& selection) - : x_display_(gfx::GetXDisplay()), - x_root_window_(DefaultRootWindow(x_display_)), - own_window_(false), - x_window_(x_window), - atom_cache_(x_display_, kAtomsToCache), - format_map_(selection), - selection_owner_(x_display_, x_window_, - atom_cache_.GetAtom(kDndSelection)) { - // We don't know all possible MIME types at compile time. - atom_cache_.allow_uncached_atoms(); -} - -OSExchangeDataProviderAuraX11::OSExchangeDataProviderAuraX11() - : x_display_(gfx::GetXDisplay()), - x_root_window_(DefaultRootWindow(x_display_)), - own_window_(true), - x_window_(XCreateWindow( - x_display_, - x_root_window_, - -100, -100, 10, 10, // x, y, width, height - 0, // border width - CopyFromParent, // depth - InputOnly, - CopyFromParent, // visual - 0, - NULL)), - atom_cache_(x_display_, kAtomsToCache), - format_map_(), - selection_owner_(x_display_, x_window_, - atom_cache_.GetAtom(kDndSelection)) { - // We don't know all possible MIME types at compile time. - atom_cache_.allow_uncached_atoms(); - - XStoreName(x_display_, x_window_, "Chromium Drag & Drop Window"); - - PlatformEventSource::GetInstance()->AddPlatformEventDispatcher(this); -} - -OSExchangeDataProviderAuraX11::~OSExchangeDataProviderAuraX11() { - if (own_window_) { - PlatformEventSource::GetInstance()->RemovePlatformEventDispatcher(this); - XDestroyWindow(x_display_, x_window_); - } -} - -void OSExchangeDataProviderAuraX11::TakeOwnershipOfSelection() const { - selection_owner_.TakeOwnershipOfSelection(format_map_); -} - -void OSExchangeDataProviderAuraX11::RetrieveTargets( - std::vector<Atom>* targets) const { - selection_owner_.RetrieveTargets(targets); -} - -SelectionFormatMap OSExchangeDataProviderAuraX11::GetFormatMap() const { - // We return the |selection_owner_|'s format map instead of our own in case - // ours has been modified since TakeOwnershipOfSelection() was called. - return selection_owner_.selection_format_map(); -} - -OSExchangeData::Provider* OSExchangeDataProviderAuraX11::Clone() const { - OSExchangeDataProviderAuraX11* ret = new OSExchangeDataProviderAuraX11(); - ret->format_map_ = format_map_; - return ret; -} - -void OSExchangeDataProviderAuraX11::MarkOriginatedFromRenderer() { - std::string empty; - format_map_.Insert(atom_cache_.GetAtom(kRendererTaint), - scoped_refptr<base::RefCountedMemory>( - base::RefCountedString::TakeString(&empty))); -} - -bool OSExchangeDataProviderAuraX11::DidOriginateFromRenderer() const { - return format_map_.find(atom_cache_.GetAtom(kRendererTaint)) != - format_map_.end(); -} - -void OSExchangeDataProviderAuraX11::SetString(const base::string16& text_data) { - if (HasString()) - return; - - std::string utf8 = base::UTF16ToUTF8(text_data); - scoped_refptr<base::RefCountedMemory> mem( - base::RefCountedString::TakeString(&utf8)); - - format_map_.Insert(atom_cache_.GetAtom(Clipboard::kMimeTypeText), mem); - format_map_.Insert(atom_cache_.GetAtom(kText), mem); - format_map_.Insert(atom_cache_.GetAtom(kString), mem); - format_map_.Insert(atom_cache_.GetAtom(kUtf8String), mem); -} - -void OSExchangeDataProviderAuraX11::SetURL(const GURL& url, - const base::string16& title) { - // TODO(dcheng): The original GTK code tries very hard to avoid writing out an - // empty title. Is this necessary? - if (url.is_valid()) { - // Mozilla's URL format: (UTF16: URL, newline, title) - base::string16 spec = base::UTF8ToUTF16(url.spec()); - - std::vector<unsigned char> data; - ui::AddString16ToVector(spec, &data); - ui::AddString16ToVector(base::ASCIIToUTF16("\n"), &data); - ui::AddString16ToVector(title, &data); - scoped_refptr<base::RefCountedMemory> mem( - base::RefCountedBytes::TakeVector(&data)); - - format_map_.Insert(atom_cache_.GetAtom(kMimeTypeMozillaURL), mem); - - // Set a string fallback as well. - SetString(spec); - - // Return early if this drag already contains file contents (this implies - // that file contents must be populated before URLs). Nautilus (and possibly - // other file managers) prefer _NETSCAPE_URL over the X Direct Save - // protocol, but we want to prioritize XDS in this case. - if (!file_contents_name_.empty()) - return; - - // Set _NETSCAPE_URL for file managers like Nautilus that use it as a hint - // to create a link to the URL. Setting text/uri-list doesn't work because - // Nautilus will fetch and copy the contents of the URL to the drop target - // instead of linking... - // Format is UTF8: URL + "\n" + title. - std::string netscape_url = url.spec(); - netscape_url += "\n"; - netscape_url += base::UTF16ToUTF8(title); - format_map_.Insert(atom_cache_.GetAtom(kNetscapeURL), - scoped_refptr<base::RefCountedMemory>( - base::RefCountedString::TakeString(&netscape_url))); - } -} - -void OSExchangeDataProviderAuraX11::SetFilename(const base::FilePath& path) { - std::vector<FileInfo> data; - data.push_back(FileInfo(path, base::FilePath())); - SetFilenames(data); -} - -void OSExchangeDataProviderAuraX11::SetFilenames( - const std::vector<FileInfo>& filenames) { - std::vector<std::string> paths; - for (std::vector<FileInfo>::const_iterator it = filenames.begin(); - it != filenames.end(); - ++it) { - std::string url_spec = net::FilePathToFileURL(it->path).spec(); - if (!url_spec.empty()) - paths.push_back(url_spec); - } - - std::string joined_data = JoinString(paths, '\n'); - scoped_refptr<base::RefCountedMemory> mem( - base::RefCountedString::TakeString(&joined_data)); - format_map_.Insert(atom_cache_.GetAtom(Clipboard::kMimeTypeURIList), mem); -} - -void OSExchangeDataProviderAuraX11::SetPickledData( - const OSExchangeData::CustomFormat& format, - const Pickle& pickle) { - const unsigned char* data = - reinterpret_cast<const unsigned char*>(pickle.data()); - - std::vector<unsigned char> bytes; - bytes.insert(bytes.end(), data, data + pickle.size()); - scoped_refptr<base::RefCountedMemory> mem( - base::RefCountedBytes::TakeVector(&bytes)); - - format_map_.Insert(atom_cache_.GetAtom(format.ToString().c_str()), mem); -} - -bool OSExchangeDataProviderAuraX11::GetString(base::string16* result) const { - if (HasFile()) { - // Various Linux file managers both pass a list of file:// URIs and set the - // string representation to the URI. We explicitly don't want to return use - // this representation. - return false; - } - - std::vector< ::Atom> text_atoms = ui::GetTextAtomsFrom(&atom_cache_); - std::vector< ::Atom> requested_types; - ui::GetAtomIntersection(text_atoms, GetTargets(), &requested_types); - - ui::SelectionData data(format_map_.GetFirstOf(requested_types)); - if (data.IsValid()) { - std::string text = data.GetText(); - *result = base::UTF8ToUTF16(text); - return true; - } - - return false; -} - -bool OSExchangeDataProviderAuraX11::GetURLAndTitle( - OSExchangeData::FilenameToURLPolicy policy, - GURL* url, - base::string16* title) const { - std::vector< ::Atom> url_atoms = ui::GetURLAtomsFrom(&atom_cache_); - std::vector< ::Atom> requested_types; - ui::GetAtomIntersection(url_atoms, GetTargets(), &requested_types); - - ui::SelectionData data(format_map_.GetFirstOf(requested_types)); - if (data.IsValid()) { - // TODO(erg): Technically, both of these forms can accept multiple URLs, - // but that doesn't match the assumptions of the rest of the system which - // expect single types. - - if (data.GetType() == atom_cache_.GetAtom(kMimeTypeMozillaURL)) { - // Mozilla URLs are (UTF16: URL, newline, title). - base::string16 unparsed; - data.AssignTo(&unparsed); - - std::vector<base::string16> tokens; - size_t num_tokens = Tokenize(unparsed, base::ASCIIToUTF16("\n"), &tokens); - if (num_tokens > 0) { - if (num_tokens > 1) - *title = tokens[1]; - else - *title = base::string16(); - - *url = GURL(tokens[0]); - return true; - } - } else if (data.GetType() == atom_cache_.GetAtom( - Clipboard::kMimeTypeURIList)) { - std::vector<std::string> tokens = ui::ParseURIList(data); - for (std::vector<std::string>::const_iterator it = tokens.begin(); - it != tokens.end(); ++it) { - GURL test_url(*it); - if (!test_url.SchemeIsFile() || - policy == OSExchangeData::CONVERT_FILENAMES) { - *url = test_url; - *title = base::string16(); - return true; - } - } - } - } - - return false; -} - -bool OSExchangeDataProviderAuraX11::GetFilename(base::FilePath* path) const { - std::vector<FileInfo> filenames; - if (GetFilenames(&filenames)) { - *path = filenames.front().path; - return true; - } - - return false; -} - -bool OSExchangeDataProviderAuraX11::GetFilenames( - std::vector<FileInfo>* filenames) const { - std::vector< ::Atom> url_atoms = ui::GetURIListAtomsFrom(&atom_cache_); - std::vector< ::Atom> requested_types; - ui::GetAtomIntersection(url_atoms, GetTargets(), &requested_types); - - filenames->clear(); - ui::SelectionData data(format_map_.GetFirstOf(requested_types)); - if (data.IsValid()) { - std::vector<std::string> tokens = ui::ParseURIList(data); - for (std::vector<std::string>::const_iterator it = tokens.begin(); - it != tokens.end(); ++it) { - GURL url(*it); - base::FilePath file_path; - if (url.SchemeIsFile() && net::FileURLToFilePath(url, &file_path)) { - filenames->push_back(FileInfo(file_path, base::FilePath())); - } - } - } - - return !filenames->empty(); -} - -bool OSExchangeDataProviderAuraX11::GetPickledData( - const OSExchangeData::CustomFormat& format, - Pickle* pickle) const { - std::vector< ::Atom> requested_types; - requested_types.push_back(atom_cache_.GetAtom(format.ToString().c_str())); - - ui::SelectionData data(format_map_.GetFirstOf(requested_types)); - if (data.IsValid()) { - // Note that the pickle object on the right hand side of the assignment - // only refers to the bytes in |data|. The assignment copies the data. - *pickle = Pickle(reinterpret_cast<const char*>(data.GetData()), - static_cast<int>(data.GetSize())); - return true; - } - - return false; -} - -bool OSExchangeDataProviderAuraX11::HasString() const { - std::vector< ::Atom> text_atoms = ui::GetTextAtomsFrom(&atom_cache_); - std::vector< ::Atom> requested_types; - ui::GetAtomIntersection(text_atoms, GetTargets(), &requested_types); - return !requested_types.empty() && !HasFile(); -} - -bool OSExchangeDataProviderAuraX11::HasURL( - OSExchangeData::FilenameToURLPolicy policy) const { - std::vector< ::Atom> url_atoms = ui::GetURLAtomsFrom(&atom_cache_); - std::vector< ::Atom> requested_types; - ui::GetAtomIntersection(url_atoms, GetTargets(), &requested_types); - - if (requested_types.empty()) - return false; - - // The Linux desktop doesn't differentiate between files and URLs like - // Windows does and stuffs all the data into one mime type. - ui::SelectionData data(format_map_.GetFirstOf(requested_types)); - if (data.IsValid()) { - if (data.GetType() == atom_cache_.GetAtom(kMimeTypeMozillaURL)) { - // File managers shouldn't be using this type, so this is a URL. - return true; - } else if (data.GetType() == atom_cache_.GetAtom( - ui::Clipboard::kMimeTypeURIList)) { - std::vector<std::string> tokens = ui::ParseURIList(data); - for (std::vector<std::string>::const_iterator it = tokens.begin(); - it != tokens.end(); ++it) { - if (!GURL(*it).SchemeIsFile() || - policy == OSExchangeData::CONVERT_FILENAMES) - return true; - } - - return false; - } - } - - return false; -} - -bool OSExchangeDataProviderAuraX11::HasFile() const { - std::vector< ::Atom> url_atoms = ui::GetURIListAtomsFrom(&atom_cache_); - std::vector< ::Atom> requested_types; - ui::GetAtomIntersection(url_atoms, GetTargets(), &requested_types); - - if (requested_types.empty()) - return false; - - // To actually answer whether we have a file, we need to look through the - // contents of the kMimeTypeURIList type, and see if any of them are file:// - // URIs. - ui::SelectionData data(format_map_.GetFirstOf(requested_types)); - if (data.IsValid()) { - std::vector<std::string> tokens = ui::ParseURIList(data); - for (std::vector<std::string>::const_iterator it = tokens.begin(); - it != tokens.end(); ++it) { - GURL url(*it); - base::FilePath file_path; - if (url.SchemeIsFile() && net::FileURLToFilePath(url, &file_path)) - return true; - } - } - - return false; -} - -bool OSExchangeDataProviderAuraX11::HasCustomFormat( - const OSExchangeData::CustomFormat& format) const { - std::vector< ::Atom> url_atoms; - url_atoms.push_back(atom_cache_.GetAtom(format.ToString().c_str())); - std::vector< ::Atom> requested_types; - ui::GetAtomIntersection(url_atoms, GetTargets(), &requested_types); - - return !requested_types.empty(); -} - -void OSExchangeDataProviderAuraX11::SetFileContents( - const base::FilePath& filename, - const std::string& file_contents) { - DCHECK(!filename.empty()); - DCHECK(format_map_.end() == - format_map_.find(atom_cache_.GetAtom(kMimeTypeMozillaURL))); - - file_contents_name_ = filename; - - // Direct save handling is a complicated juggling affair between this class, - // SelectionFormat, and DesktopDragDropClientAuraX11. The general idea behind - // the protocol is this: - // - The source window sets its XdndDirectSave0 window property to the - // proposed filename. - // - When a target window receives the drop, it updates the XdndDirectSave0 - // property on the source window to the filename it would like the contents - // to be saved to and then requests the XdndDirectSave0 type from the - // source. - // - The source is supposed to copy the file here and return success (S), - // failure (F), or error (E). - // - In this case, failure means the destination should try to populate the - // file itself by copying the data from application/octet-stream. To make - // things simpler for Chrome, we always 'fail' and let the destination do - // the work. - std::string failure("F"); - format_map_.Insert( - atom_cache_.GetAtom("XdndDirectSave0"), - scoped_refptr<base::RefCountedMemory>( - base::RefCountedString::TakeString(&failure))); - std::string file_contents_copy = file_contents; - format_map_.Insert( - atom_cache_.GetAtom("application/octet-stream"), - scoped_refptr<base::RefCountedMemory>( - base::RefCountedString::TakeString(&file_contents_copy))); -} - -void OSExchangeDataProviderAuraX11::SetHtml(const base::string16& html, - const GURL& base_url) { - std::vector<unsigned char> bytes; - // Manually jam a UTF16 BOM into bytes because otherwise, other programs will - // assume UTF-8. - bytes.push_back(0xFF); - bytes.push_back(0xFE); - ui::AddString16ToVector(html, &bytes); - scoped_refptr<base::RefCountedMemory> mem( - base::RefCountedBytes::TakeVector(&bytes)); - - format_map_.Insert(atom_cache_.GetAtom(Clipboard::kMimeTypeHTML), mem); -} - -bool OSExchangeDataProviderAuraX11::GetHtml(base::string16* html, - GURL* base_url) const { - std::vector< ::Atom> url_atoms; - url_atoms.push_back(atom_cache_.GetAtom(Clipboard::kMimeTypeHTML)); - std::vector< ::Atom> requested_types; - ui::GetAtomIntersection(url_atoms, GetTargets(), &requested_types); - - ui::SelectionData data(format_map_.GetFirstOf(requested_types)); - if (data.IsValid()) { - *html = data.GetHtml(); - *base_url = GURL(); - return true; - } - - return false; -} - -bool OSExchangeDataProviderAuraX11::HasHtml() const { - std::vector< ::Atom> url_atoms; - url_atoms.push_back(atom_cache_.GetAtom(Clipboard::kMimeTypeHTML)); - std::vector< ::Atom> requested_types; - ui::GetAtomIntersection(url_atoms, GetTargets(), &requested_types); - - return !requested_types.empty(); -} - -void OSExchangeDataProviderAuraX11::SetDragImage( - const gfx::ImageSkia& image, - const gfx::Vector2d& cursor_offset) { - drag_image_ = image; - drag_image_offset_ = cursor_offset; -} - -const gfx::ImageSkia& OSExchangeDataProviderAuraX11::GetDragImage() const { - return drag_image_; -} - -const gfx::Vector2d& OSExchangeDataProviderAuraX11::GetDragImageOffset() const { - return drag_image_offset_; -} - -bool OSExchangeDataProviderAuraX11::CanDispatchEvent( - const PlatformEvent& event) { - return event->xany.window == x_window_; -} - -uint32_t OSExchangeDataProviderAuraX11::DispatchEvent( - const PlatformEvent& event) { - XEvent* xev = event; - switch (xev->type) { - case SelectionRequest: - selection_owner_.OnSelectionRequest(*xev); - return ui::POST_DISPATCH_STOP_PROPAGATION; - default: - NOTIMPLEMENTED(); - } - return ui::POST_DISPATCH_NONE; -} - -bool OSExchangeDataProviderAuraX11::GetPlainTextURL(GURL* url) const { - base::string16 text; - if (GetString(&text)) { - GURL test_url(text); - if (test_url.is_valid()) { - *url = test_url; - return true; - } - } - - return false; -} - -std::vector< ::Atom> OSExchangeDataProviderAuraX11::GetTargets() const { - return format_map_.GetTypes(); -} - -/////////////////////////////////////////////////////////////////////////////// -// OSExchangeData, public: - -// static -OSExchangeData::Provider* OSExchangeData::CreateProvider() { - return new OSExchangeDataProviderAuraX11(); -} - -} // namespace ui
diff --git a/ui/base/dragdrop/os_exchange_data_provider_aurax11.h b/ui/base/dragdrop/os_exchange_data_provider_aurax11.h deleted file mode 100644 index 9664b02..0000000 --- a/ui/base/dragdrop/os_exchange_data_provider_aurax11.h +++ /dev/null
@@ -1,151 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_DRAGDROP_OS_EXCHANGE_DATA_PROVIDER_AURAX11_H_ -#define UI_BASE_DRAGDROP_OS_EXCHANGE_DATA_PROVIDER_AURAX11_H_ - -#include <X11/Xlib.h> - -// Get rid of a macro from Xlib.h that conflicts with Aura's RootWindow class. -#undef RootWindow - -#include <map> - -#include "base/files/file_path.h" -#include "base/pickle.h" -#include "ui/base/dragdrop/os_exchange_data.h" -#include "ui/base/x/selection_owner.h" -#include "ui/base/x/selection_requestor.h" -#include "ui/base/x/selection_utils.h" -#include "ui/events/platform/platform_event_dispatcher.h" -#include "ui/gfx/image/image_skia.h" -#include "ui/gfx/vector2d.h" -#include "ui/gfx/x/x11_atom_cache.h" -#include "url/gurl.h" - -namespace ui { - -class Clipboard; -class OSExchangeDataProviderAuraX11Test; - -// OSExchangeData::Provider implementation for aura on linux. -class UI_BASE_EXPORT OSExchangeDataProviderAuraX11 - : public OSExchangeData::Provider, - public ui::PlatformEventDispatcher { - public: - // |x_window| is the window the cursor is over, and |selection| is the set of - // data being offered. - OSExchangeDataProviderAuraX11(::Window x_window, - const SelectionFormatMap& selection); - - // Creates a Provider for sending drag information. This creates its own, - // hidden X11 window to own send data. - OSExchangeDataProviderAuraX11(); - - virtual ~OSExchangeDataProviderAuraX11(); - - // After all the Set* methods have built up the data we're offering, call - // this to take ownership of the XdndSelection clipboard. - void TakeOwnershipOfSelection() const; - - // Retrieves a list of types we're offering. Noop if we haven't taken the - // selection. - void RetrieveTargets(std::vector<Atom>* targets) const; - - // Makes a copy of the format map currently being offered. - SelectionFormatMap GetFormatMap() const; - - const base::FilePath& file_contents_name() const { - return file_contents_name_; - } - - // Overridden from OSExchangeData::Provider: - virtual Provider* Clone() const override; - virtual void MarkOriginatedFromRenderer() override; - virtual bool DidOriginateFromRenderer() const override; - virtual void SetString(const base::string16& data) override; - virtual void SetURL(const GURL& url, const base::string16& title) override; - virtual void SetFilename(const base::FilePath& path) override; - virtual void SetFilenames(const std::vector<FileInfo>& filenames) override; - virtual void SetPickledData(const OSExchangeData::CustomFormat& format, - const Pickle& pickle) override; - virtual bool GetString(base::string16* data) const override; - virtual bool GetURLAndTitle(OSExchangeData::FilenameToURLPolicy policy, - GURL* url, - base::string16* title) const override; - virtual bool GetFilename(base::FilePath* path) const override; - virtual bool GetFilenames(std::vector<FileInfo>* filenames) const override; - virtual bool GetPickledData(const OSExchangeData::CustomFormat& format, - Pickle* pickle) const override; - virtual bool HasString() const override; - virtual bool HasURL(OSExchangeData::FilenameToURLPolicy policy) const - override; - virtual bool HasFile() const override; - virtual bool HasCustomFormat(const OSExchangeData::CustomFormat& format) const - override; - - virtual void SetFileContents(const base::FilePath& filename, - const std::string& file_contents) override; - - virtual void SetHtml(const base::string16& html, - const GURL& base_url) override; - virtual bool GetHtml(base::string16* html, GURL* base_url) const override; - virtual bool HasHtml() const override; - virtual void SetDragImage(const gfx::ImageSkia& image, - const gfx::Vector2d& cursor_offset) override; - virtual const gfx::ImageSkia& GetDragImage() const override; - virtual const gfx::Vector2d& GetDragImageOffset() const override; - - // ui::PlatformEventDispatcher: - virtual bool CanDispatchEvent(const PlatformEvent& event) override; - virtual uint32_t DispatchEvent(const PlatformEvent& event) override; - - private: - friend class OSExchangeDataProviderAuraX11Test; - typedef std::map<OSExchangeData::CustomFormat, Pickle> PickleData; - - // Returns true if |formats_| contains a string format and the string can be - // parsed as a URL. - bool GetPlainTextURL(GURL* url) const; - - // Returns the targets in |format_map_|. - std::vector< ::Atom> GetTargets() const; - - // Drag image and offset data. - gfx::ImageSkia drag_image_; - gfx::Vector2d drag_image_offset_; - - // Our X11 state. - Display* x_display_; - ::Window x_root_window_; - - // In X11, because the IPC parts of drag operations are implemented by - // XSelection, we require an x11 window to receive drag messages on. The - // OSExchangeDataProvider system is modeled on the Windows implementation, - // which does not require a window. We only sometimes have a valid window - // available (in the case of drag receiving). Other times, we need to create - // our own xwindow just to receive events on it. - const bool own_window_; - - ::Window x_window_; - - X11AtomCache atom_cache_; - - // A representation of data. This is either passed to us from the other - // process, or built up through a sequence of Set*() calls. It can be passed - // to |selection_owner_| when we take the selection. - SelectionFormatMap format_map_; - - // Auxilary data for the X Direct Save protocol. - base::FilePath file_contents_name_; - - // Takes a snapshot of |format_map_| and offers it to other windows. - mutable SelectionOwner selection_owner_; - - DISALLOW_COPY_AND_ASSIGN(OSExchangeDataProviderAuraX11); -}; - -} // namespace ui - -#endif // UI_BASE_DRAGDROP_OS_EXCHANGE_DATA_PROVIDER_AURAX11_H_
diff --git a/ui/base/dragdrop/os_exchange_data_provider_aurax11_unittest.cc b/ui/base/dragdrop/os_exchange_data_provider_aurax11_unittest.cc deleted file mode 100644 index 457ba6b..0000000 --- a/ui/base/dragdrop/os_exchange_data_provider_aurax11_unittest.cc +++ /dev/null
@@ -1,128 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/dragdrop/os_exchange_data_provider_aurax11.h" - -// Clean up X11 header polution -#undef None -#undef Bool - -#include "base/message_loop/message_loop.h" -#include "base/strings/string16.h" -#include "base/strings/utf_string_conversions.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/base/dragdrop/file_info.h" -#include "ui/events/platform/x11/x11_event_source.h" -#include "url/gurl.h" - -const char kFileURL[] = "file:///home/user/file.txt"; -const char kFileName[] = "/home/user/file.txt"; -const char kGoogleTitle[] = "Google"; -const char kGoogleURL[] = "http://www.google.com/"; - -namespace ui { - -class OSExchangeDataProviderAuraX11Test : public testing::Test { - public: - OSExchangeDataProviderAuraX11Test() : event_source(gfx::GetXDisplay()) {} - - void AddURLList(const std::string& list_contents) { - std::string contents_copy = list_contents; - scoped_refptr<base::RefCountedMemory> mem( - base::RefCountedString::TakeString(&contents_copy)); - - provider.format_map_.Insert( - provider.atom_cache_.GetAtom(ui::Clipboard::kMimeTypeURIList), - mem); - } - - protected: - base::MessageLoopForUI message_loop; - X11EventSource event_source; - ui::OSExchangeDataProviderAuraX11 provider; -}; - -TEST_F(OSExchangeDataProviderAuraX11Test, MozillaURL) { - // Check that we can get titled entries. - provider.SetURL(GURL(kGoogleURL), base::ASCIIToUTF16(kGoogleTitle)); - { - GURL out_gurl; - base::string16 out_str; - EXPECT_TRUE(provider.GetURLAndTitle( - OSExchangeData::DO_NOT_CONVERT_FILENAMES, &out_gurl, &out_str)); - EXPECT_EQ(base::ASCIIToUTF16(kGoogleTitle), out_str); - EXPECT_EQ(kGoogleURL, out_gurl.spec()); - } - - // Check that we can get non-titled entries. - provider.SetURL(GURL(kGoogleURL), base::string16()); - { - GURL out_gurl; - base::string16 out_str; - EXPECT_TRUE(provider.GetURLAndTitle( - OSExchangeData::DO_NOT_CONVERT_FILENAMES, &out_gurl, &out_str)); - EXPECT_EQ(base::string16(), out_str); - EXPECT_EQ(kGoogleURL, out_gurl.spec()); - } -} - -TEST_F(OSExchangeDataProviderAuraX11Test, FilesArentURLs) { - AddURLList(kFileURL); - - EXPECT_TRUE(provider.HasFile()); - EXPECT_TRUE(provider.HasURL(ui::OSExchangeData::CONVERT_FILENAMES)); - EXPECT_FALSE(provider.HasURL(ui::OSExchangeData::DO_NOT_CONVERT_FILENAMES)); -} - -TEST_F(OSExchangeDataProviderAuraX11Test, HTTPURLsArentFiles) { - AddURLList(kGoogleURL); - - EXPECT_FALSE(provider.HasFile()); - EXPECT_TRUE(provider.HasURL(ui::OSExchangeData::CONVERT_FILENAMES)); - EXPECT_TRUE(provider.HasURL(ui::OSExchangeData::DO_NOT_CONVERT_FILENAMES)); -} - -TEST_F(OSExchangeDataProviderAuraX11Test, URIListWithBoth) { - AddURLList("file:///home/user/file.txt\nhttp://www.google.com"); - - EXPECT_TRUE(provider.HasFile()); - EXPECT_TRUE(provider.HasURL(ui::OSExchangeData::CONVERT_FILENAMES)); - EXPECT_TRUE(provider.HasURL(ui::OSExchangeData::DO_NOT_CONVERT_FILENAMES)); - - // We should only receive the file from GetFilenames(). - std::vector<FileInfo> filenames; - EXPECT_TRUE(provider.GetFilenames(&filenames)); - ASSERT_EQ(1u, filenames.size()); - EXPECT_EQ(kFileName, filenames[0].path.value()); - - // We should only receive the URL here. - GURL out_gurl; - base::string16 out_str; - EXPECT_TRUE(provider.GetURLAndTitle( - OSExchangeData::DO_NOT_CONVERT_FILENAMES, &out_gurl, &out_str)); - EXPECT_EQ(base::string16(), out_str); - EXPECT_EQ(kGoogleURL, out_gurl.spec()); -} - -TEST_F(OSExchangeDataProviderAuraX11Test, OnlyStringURLIsUnfiltered) { - const base::string16 file_url = base::UTF8ToUTF16(kFileURL); - provider.SetString(file_url); - - EXPECT_TRUE(provider.HasString()); - EXPECT_FALSE(provider.HasURL(ui::OSExchangeData::DO_NOT_CONVERT_FILENAMES)); -} - -TEST_F(OSExchangeDataProviderAuraX11Test, StringAndURIListFilterString) { - const base::string16 file_url = base::UTF8ToUTF16(kFileURL); - provider.SetString(file_url); - AddURLList(kFileURL); - - EXPECT_FALSE(provider.HasString()); - base::string16 out_str; - EXPECT_FALSE(provider.GetString(&out_str)); - - EXPECT_TRUE(provider.HasFile()); -} - -} // namespace ui
diff --git a/ui/base/dragdrop/os_exchange_data_provider_mac.h b/ui/base/dragdrop/os_exchange_data_provider_mac.h deleted file mode 100644 index 3488c25..0000000 --- a/ui/base/dragdrop/os_exchange_data_provider_mac.h +++ /dev/null
@@ -1,55 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_DRAGDROP_OS_EXCHANGE_DATA_PROVIDER_MAC_H_ -#define UI_BASE_DRAGDROP_OS_EXCHANGE_DATA_PROVIDER_MAC_H_ - -#import "base/mac/scoped_nsobject.h" -#include "ui/base/dragdrop/os_exchange_data.h" - -@class NSPasteboard; - -namespace ui { - -// OSExchangeData::Provider implementation for Mac. -class UI_BASE_EXPORT OSExchangeDataProviderMac - : public OSExchangeData::Provider { - public: - OSExchangeDataProviderMac(); - explicit OSExchangeDataProviderMac(NSPasteboard* pasteboard); - ~OSExchangeDataProviderMac() override; - - // Overridden from OSExchangeData::Provider: - Provider* Clone() const override; - void MarkOriginatedFromRenderer() override; - bool DidOriginateFromRenderer() const override; - void SetString(const base::string16& data) override; - void SetURL(const GURL& url, const base::string16& title) override; - void SetFilename(const base::FilePath& path) override; - void SetFilenames(const std::vector<FileInfo>& filenames) override; - void SetPickledData(const OSExchangeData::CustomFormat& format, - const Pickle& data) override; - bool GetString(base::string16* data) const override; - bool GetURLAndTitle(OSExchangeData::FilenameToURLPolicy policy, - GURL* url, - base::string16* title) const override; - bool GetFilename(base::FilePath* path) const override; - bool GetFilenames(std::vector<FileInfo>* filenames) const override; - bool GetPickledData(const OSExchangeData::CustomFormat& format, - Pickle* data) const override; - bool HasString() const override; - bool HasURL(OSExchangeData::FilenameToURLPolicy policy) const override; - bool HasFile() const override; - bool HasCustomFormat( - const OSExchangeData::CustomFormat& format) const override; - - private: - base::scoped_nsobject<NSPasteboard> pasteboard_; - - DISALLOW_COPY_AND_ASSIGN(OSExchangeDataProviderMac); -}; - -} // namespace ui - -#endif // UI_BASE_DRAGDROP_OS_EXCHANGE_DATA_PROVIDER_MAC_H_
diff --git a/ui/base/dragdrop/os_exchange_data_provider_mac.mm b/ui/base/dragdrop/os_exchange_data_provider_mac.mm deleted file mode 100644 index 94e4bed..0000000 --- a/ui/base/dragdrop/os_exchange_data_provider_mac.mm +++ /dev/null
@@ -1,168 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/dragdrop/os_exchange_data_provider_mac.h" - -#import <Cocoa/Cocoa.h> - -#include "base/logging.h" -#include "base/pickle.h" -#include "base/strings/sys_string_conversions.h" -#import "third_party/mozilla/NSPasteboard+Utils.h" -#include "url/gurl.h" - -namespace ui { - -OSExchangeDataProviderMac::OSExchangeDataProviderMac() - : pasteboard_([[NSPasteboard pasteboardWithUniqueName] retain]) { -} - -OSExchangeDataProviderMac::OSExchangeDataProviderMac(NSPasteboard* pasteboard) - : pasteboard_([pasteboard retain]) { -} - -OSExchangeDataProviderMac::~OSExchangeDataProviderMac() { -} - -OSExchangeData::Provider* OSExchangeDataProviderMac::Clone() const { - return new OSExchangeDataProviderMac(pasteboard_); -} - -void OSExchangeDataProviderMac::MarkOriginatedFromRenderer() { - NOTIMPLEMENTED(); -} - -bool OSExchangeDataProviderMac::DidOriginateFromRenderer() const { - NOTIMPLEMENTED(); - return false; -} - -void OSExchangeDataProviderMac::SetString(const base::string16& string) { - [pasteboard_ writeObjects:@[ base::SysUTF16ToNSString(string) ]]; -} - -void OSExchangeDataProviderMac::SetURL(const GURL& url, - const base::string16& title) { - NSURL* ns_url = [NSURL URLWithString:base::SysUTF8ToNSString(url.spec())]; - [pasteboard_ writeObjects:@[ ns_url ]]; - - [pasteboard_ setString:base::SysUTF16ToNSString(title) - forType:kCorePasteboardFlavorType_urln]; -} - -void OSExchangeDataProviderMac::SetFilename(const base::FilePath& path) { - [pasteboard_ setPropertyList:@[ base::SysUTF8ToNSString(path.value()) ] - forType:NSFilenamesPboardType]; -} - -void OSExchangeDataProviderMac::SetFilenames( - const std::vector<FileInfo>& filenames) { - NOTIMPLEMENTED(); -} - -void OSExchangeDataProviderMac::SetPickledData( - const OSExchangeData::CustomFormat& format, - const Pickle& data) { - NSData* ns_data = [NSData dataWithBytes:data.data() length:data.size()]; - [pasteboard_ setData:ns_data forType:format.ToNSString()]; -} - -bool OSExchangeDataProviderMac::GetString(base::string16* data) const { - DCHECK(data); - NSArray* items = [pasteboard_ readObjectsForClasses:@[ [NSString class] ] - options:@{ }]; - if ([items count] == 0) - return false; - - *data = base::SysNSStringToUTF16([items objectAtIndex:0]); - return true; -} - -bool OSExchangeDataProviderMac::GetURLAndTitle( - OSExchangeData::FilenameToURLPolicy policy, - GURL* url, - base::string16* title) const { - DCHECK(url); - DCHECK(title); - NSArray* items = [pasteboard_ readObjectsForClasses:@[ [NSURL class] ] - options:@{ }]; - if ([items count] == 0) - return false; - - NSURL* ns_url = [items objectAtIndex:0]; - - if (policy == OSExchangeData::DO_NOT_CONVERT_FILENAMES) { - // If the URL matches a filename, assume that it came from SetFilename(). - // Don't return it if we are not supposed to convert filename to URL. - NSArray* paths = [pasteboard_ propertyListForType:NSFilenamesPboardType]; - NSString* url_path = [[ns_url path] stringByStandardizingPath]; - for (NSString* path in paths) { - if ([[path stringByStandardizingPath] isEqualToString:url_path]) - return false; - } - } - - *url = GURL([[ns_url absoluteString] UTF8String]); - *title = base::SysNSStringToUTF16( - [pasteboard_ stringForType:kCorePasteboardFlavorType_urln]); - return true; -} - -bool OSExchangeDataProviderMac::GetFilename(base::FilePath* path) const { - NSArray* paths = [pasteboard_ propertyListForType:NSFilenamesPboardType]; - if ([paths count] == 0) - return false; - - *path = base::FilePath([[paths objectAtIndex:0] UTF8String]); - return true; -} - -bool OSExchangeDataProviderMac::GetFilenames( - std::vector<FileInfo>* filenames) const { - NOTIMPLEMENTED(); - return false; -} - -bool OSExchangeDataProviderMac::GetPickledData( - const OSExchangeData::CustomFormat& format, - Pickle* data) const { - DCHECK(data); - NSData* ns_data = [pasteboard_ dataForType:format.ToNSString()]; - if (!ns_data) - return false; - - *data = Pickle(static_cast<const char*>([ns_data bytes]), [ns_data length]); - return true; -} - -bool OSExchangeDataProviderMac::HasString() const { - NSArray* classes = @[ [NSString class] ]; - return [pasteboard_ canReadObjectForClasses:classes options:nil]; -} - -bool OSExchangeDataProviderMac::HasURL( - OSExchangeData::FilenameToURLPolicy policy) const { - GURL url; - base::string16 title; - return GetURLAndTitle(policy, &url, &title); -} - -bool OSExchangeDataProviderMac::HasFile() const { - return [[pasteboard_ types] containsObject:NSFilenamesPboardType]; -} - -bool OSExchangeDataProviderMac::HasCustomFormat( - const OSExchangeData::CustomFormat& format) const { - return [[pasteboard_ types] containsObject:format.ToNSString()]; -} - -/////////////////////////////////////////////////////////////////////////////// -// OSExchangeData, public: - -// static -OSExchangeData::Provider* OSExchangeData::CreateProvider() { - return new OSExchangeDataProviderMac; -} - -} // namespace ui
diff --git a/ui/base/dragdrop/os_exchange_data_provider_win.cc b/ui/base/dragdrop/os_exchange_data_provider_win.cc deleted file mode 100644 index 8e5f5ea..0000000 --- a/ui/base/dragdrop/os_exchange_data_provider_win.cc +++ /dev/null
@@ -1,1058 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/dragdrop/os_exchange_data_provider_win.h" - -#include <algorithm> - -#include "base/basictypes.h" -#include "base/files/file_path.h" -#include "base/i18n/file_util_icu.h" -#include "base/logging.h" -#include "base/pickle.h" -#include "base/strings/utf_string_conversions.h" -#include "base/win/scoped_hglobal.h" -#include "net/base/filename_util.h" -#include "ui/base/clipboard/clipboard.h" -#include "ui/base/clipboard/clipboard_util_win.h" -#include "ui/base/dragdrop/file_info.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/strings/grit/ui_strings.h" -#include "url/gurl.h" - -namespace ui { - -static const OSExchangeData::CustomFormat& GetRendererTaintCustomType() { - CR_DEFINE_STATIC_LOCAL( - ui::OSExchangeData::CustomFormat, - format, - (ui::Clipboard::GetFormatType("chromium/x-renderer-taint"))); - return format; -} - -// Creates a new STGMEDIUM object to hold the specified text. The caller -// owns the resulting object. The "Bytes" version does not NULL terminate, the -// string version does. -static STGMEDIUM* GetStorageForBytes(const void* data, size_t bytes); -template <typename T> -static STGMEDIUM* GetStorageForString(const std::basic_string<T>& data); -// Creates the contents of an Internet Shortcut file for the given URL. -static void GetInternetShortcutFileContents(const GURL& url, std::string* data); -// Creates a valid file name given a suggested title and URL. -static void CreateValidFileNameFromTitle(const GURL& url, - const base::string16& title, - base::string16* validated); -// Creates a new STGMEDIUM object to hold a file. -static STGMEDIUM* GetStorageForFileName(const base::FilePath& path); -static STGMEDIUM* GetIDListStorageForFileName(const base::FilePath& path); -// Creates a File Descriptor for the creation of a file to the given URL and -// returns a handle to it. -static STGMEDIUM* GetStorageForFileDescriptor(const base::FilePath& path); - -/////////////////////////////////////////////////////////////////////////////// -// FormatEtcEnumerator - -// -// This object implements an enumeration interface. The existence of an -// implementation of this interface is exposed to clients through -// OSExchangeData's EnumFormatEtc method. Our implementation is nobody's -// business but our own, so it lives in this file. -// -// This Windows API is truly a gem. It wants to be an enumerator but assumes -// some sort of sequential data (why not just use an array?). See comments -// throughout. -// -class FormatEtcEnumerator final : public IEnumFORMATETC { - public: - FormatEtcEnumerator(DataObjectImpl::StoredData::const_iterator begin, - DataObjectImpl::StoredData::const_iterator end); - ~FormatEtcEnumerator(); - - // IEnumFORMATETC implementation: - HRESULT __stdcall Next( - ULONG count, FORMATETC* elements_array, ULONG* elements_fetched); - HRESULT __stdcall Skip(ULONG skip_count); - HRESULT __stdcall Reset(); - HRESULT __stdcall Clone(IEnumFORMATETC** clone); - - // IUnknown implementation: - HRESULT __stdcall QueryInterface(const IID& iid, void** object); - ULONG __stdcall AddRef(); - ULONG __stdcall Release(); - - private: - // This can only be called from |CloneFromOther|, since it initializes the - // contents_ from the other enumerator's contents. - FormatEtcEnumerator() : cursor_(0), ref_count_(0) { - } - - // Clone a new FormatEtc from another instance of this enumeration. - static FormatEtcEnumerator* CloneFromOther(const FormatEtcEnumerator* other); - - private: - // We are _forced_ to use a vector as our internal data model as Windows' - // retarded IEnumFORMATETC API assumes a deterministic ordering of elements - // through methods like Next and Skip. This exposes the underlying data - // structure to the user. Bah. - ScopedVector<FORMATETC> contents_; - - // The cursor of the active enumeration - an index into |contents_|. - size_t cursor_; - - LONG ref_count_; - - DISALLOW_COPY_AND_ASSIGN(FormatEtcEnumerator); -}; - -// Safely makes a copy of all of the relevant bits of a FORMATETC object. -static void CloneFormatEtc(FORMATETC* source, FORMATETC* clone) { - *clone = *source; - if (source->ptd) { - source->ptd = - static_cast<DVTARGETDEVICE*>(CoTaskMemAlloc(sizeof(DVTARGETDEVICE))); - *(clone->ptd) = *(source->ptd); - } -} - -FormatEtcEnumerator::FormatEtcEnumerator( - DataObjectImpl::StoredData::const_iterator start, - DataObjectImpl::StoredData::const_iterator end) - : ref_count_(0), cursor_(0) { - // Copy FORMATETC data from our source into ourselves. - while (start != end) { - FORMATETC* format_etc = new FORMATETC; - CloneFormatEtc(&(*start)->format_etc, format_etc); - contents_.push_back(format_etc); - ++start; - } -} - -FormatEtcEnumerator::~FormatEtcEnumerator() { -} - -STDMETHODIMP FormatEtcEnumerator::Next( - ULONG count, FORMATETC* elements_array, ULONG* elements_fetched) { - // MSDN says |elements_fetched| is allowed to be NULL if count is 1. - if (!elements_fetched) - DCHECK_EQ(count, 1ul); - - // This method copies count elements into |elements_array|. - ULONG index = 0; - while (cursor_ < contents_.size() && index < count) { - CloneFormatEtc(contents_[cursor_], &elements_array[index]); - ++cursor_; - ++index; - } - // The out param is for how many we actually copied. - if (elements_fetched) - *elements_fetched = index; - - // If the two don't agree, then we fail. - return index == count ? S_OK : S_FALSE; -} - -STDMETHODIMP FormatEtcEnumerator::Skip(ULONG skip_count) { - cursor_ += skip_count; - // MSDN implies it's OK to leave the enumerator trashed. - // "Whatever you say, boss" - return cursor_ <= contents_.size() ? S_OK : S_FALSE; -} - -STDMETHODIMP FormatEtcEnumerator::Reset() { - cursor_ = 0; - return S_OK; -} - -STDMETHODIMP FormatEtcEnumerator::Clone(IEnumFORMATETC** clone) { - // Clone the current enumerator in its exact state, including cursor. - FormatEtcEnumerator* e = CloneFromOther(this); - e->AddRef(); - *clone = e; - return S_OK; -} - -STDMETHODIMP FormatEtcEnumerator::QueryInterface(const IID& iid, - void** object) { - *object = NULL; - if (IsEqualIID(iid, IID_IUnknown) || IsEqualIID(iid, IID_IEnumFORMATETC)) { - *object = this; - } else { - return E_NOINTERFACE; - } - AddRef(); - return S_OK; -} - -ULONG FormatEtcEnumerator::AddRef() { - return InterlockedIncrement(&ref_count_); -} - -ULONG FormatEtcEnumerator::Release() { - if (InterlockedDecrement(&ref_count_) == 0) { - ULONG copied_refcnt = ref_count_; - delete this; - return copied_refcnt; - } - return ref_count_; -} - -// static -FormatEtcEnumerator* FormatEtcEnumerator::CloneFromOther( - const FormatEtcEnumerator* other) { - FormatEtcEnumerator* e = new FormatEtcEnumerator; - // Copy FORMATETC data from our source into ourselves. - ScopedVector<FORMATETC>::const_iterator start = other->contents_.begin(); - while (start != other->contents_.end()) { - FORMATETC* format_etc = new FORMATETC; - CloneFormatEtc(*start, format_etc); - e->contents_.push_back(format_etc); - ++start; - } - // Carry over - e->cursor_ = other->cursor_; - return e; -} - -/////////////////////////////////////////////////////////////////////////////// -// OSExchangeDataProviderWin, public: - -// static -bool OSExchangeDataProviderWin::HasPlainTextURL(IDataObject* source) { - base::string16 plain_text; - return (ClipboardUtil::GetPlainText(source, &plain_text) && - !plain_text.empty() && GURL(plain_text).is_valid()); -} - -// static -bool OSExchangeDataProviderWin::GetPlainTextURL(IDataObject* source, - GURL* url) { - base::string16 plain_text; - if (ClipboardUtil::GetPlainText(source, &plain_text) && - !plain_text.empty()) { - GURL gurl(plain_text); - if (gurl.is_valid()) { - *url = gurl; - return true; - } - } - return false; -} - -// static -DataObjectImpl* OSExchangeDataProviderWin::GetDataObjectImpl( - const OSExchangeData& data) { - return static_cast<const OSExchangeDataProviderWin*>(&data.provider())-> - data_.get(); -} - -// static -IDataObject* OSExchangeDataProviderWin::GetIDataObject( - const OSExchangeData& data) { - return static_cast<const OSExchangeDataProviderWin*>(&data.provider())-> - data_object(); -} - -// static -IDataObjectAsyncCapability* OSExchangeDataProviderWin::GetIAsyncOperation( - const OSExchangeData& data) { - return static_cast<const OSExchangeDataProviderWin*>(&data.provider())-> - async_operation(); -} - -OSExchangeDataProviderWin::OSExchangeDataProviderWin(IDataObject* source) - : data_(new DataObjectImpl()), - source_object_(source) { -} - -OSExchangeDataProviderWin::OSExchangeDataProviderWin() - : data_(new DataObjectImpl()), - source_object_(data_.get()) { -} - -OSExchangeDataProviderWin::~OSExchangeDataProviderWin() { -} - -OSExchangeData::Provider* OSExchangeDataProviderWin::Clone() const { - return new OSExchangeDataProviderWin(data_object()); -} - -void OSExchangeDataProviderWin::MarkOriginatedFromRenderer() { - STGMEDIUM* storage = GetStorageForString(std::string()); - data_->contents_.push_back(new DataObjectImpl::StoredDataInfo( - GetRendererTaintCustomType().ToFormatEtc(), storage)); -} - -bool OSExchangeDataProviderWin::DidOriginateFromRenderer() const { - return HasCustomFormat(GetRendererTaintCustomType()); -} - -void OSExchangeDataProviderWin::SetString(const base::string16& data) { - STGMEDIUM* storage = GetStorageForString(data); - data_->contents_.push_back(new DataObjectImpl::StoredDataInfo( - Clipboard::GetPlainTextWFormatType().ToFormatEtc(), storage)); - - // Also add the UTF8-encoded version. - storage = GetStorageForString(base::UTF16ToUTF8(data)); - data_->contents_.push_back(new DataObjectImpl::StoredDataInfo( - Clipboard::GetPlainTextFormatType().ToFormatEtc(), storage)); -} - -void OSExchangeDataProviderWin::SetURL(const GURL& url, - const base::string16& title) { - // NOTE WELL: - // Every time you change the order of the first two CLIPFORMATS that get - // added here, you need to update the EnumerationViaCOM test case in - // the _unittest.cc file to reflect the new arrangement otherwise that test - // will fail! It assumes an insertion order. - - // Add text/x-moz-url for drags from Firefox - base::string16 x_moz_url_str = base::UTF8ToUTF16(url.spec()); - x_moz_url_str += '\n'; - x_moz_url_str += title; - STGMEDIUM* storage = GetStorageForString(x_moz_url_str); - data_->contents_.push_back(new DataObjectImpl::StoredDataInfo( - Clipboard::GetMozUrlFormatType().ToFormatEtc(), storage)); - - // Add a .URL shortcut file for dragging to Explorer. - base::string16 valid_file_name; - CreateValidFileNameFromTitle(url, title, &valid_file_name); - std::string shortcut_url_file_contents; - GetInternetShortcutFileContents(url, &shortcut_url_file_contents); - SetFileContents(base::FilePath(valid_file_name), shortcut_url_file_contents); - - // Add a UniformResourceLocator link for apps like IE and Word. - storage = GetStorageForString(base::UTF8ToUTF16(url.spec())); - data_->contents_.push_back(new DataObjectImpl::StoredDataInfo( - Clipboard::GetUrlWFormatType().ToFormatEtc(), storage)); - storage = GetStorageForString(url.spec()); - data_->contents_.push_back(new DataObjectImpl::StoredDataInfo( - Clipboard::GetUrlFormatType().ToFormatEtc(), storage)); - - // TODO(beng): add CF_HTML. - // http://code.google.com/p/chromium/issues/detail?id=6767 - - // Also add text representations (these should be last since they're the - // least preferable). - SetString(base::UTF8ToUTF16(url.spec())); -} - -void OSExchangeDataProviderWin::SetFilename(const base::FilePath& path) { - STGMEDIUM* storage = GetStorageForFileName(path); - DataObjectImpl::StoredDataInfo* info = new DataObjectImpl::StoredDataInfo( - Clipboard::GetCFHDropFormatType().ToFormatEtc(), storage); - data_->contents_.push_back(info); - - storage = GetIDListStorageForFileName(path); - if (!storage) - return; - info = new DataObjectImpl::StoredDataInfo( - Clipboard::GetIDListFormatType().ToFormatEtc(), storage); - data_->contents_.push_back(info); -} - -void OSExchangeDataProviderWin::SetFilenames( - const std::vector<FileInfo>& filenames) { - for (size_t i = 0; i < filenames.size(); ++i) { - STGMEDIUM* storage = GetStorageForFileName(filenames[i].path); - DataObjectImpl::StoredDataInfo* info = new DataObjectImpl::StoredDataInfo( - Clipboard::GetCFHDropFormatType().ToFormatEtc(), storage); - data_->contents_.push_back(info); - } -} - -void OSExchangeDataProviderWin::SetPickledData( - const OSExchangeData::CustomFormat& format, - const Pickle& data) { - STGMEDIUM* storage = GetStorageForBytes(data.data(), data.size()); - data_->contents_.push_back( - new DataObjectImpl::StoredDataInfo(format.ToFormatEtc(), storage)); -} - -void OSExchangeDataProviderWin::SetFileContents( - const base::FilePath& filename, - const std::string& file_contents) { - // Add CFSTR_FILEDESCRIPTOR - STGMEDIUM* storage = GetStorageForFileDescriptor(filename); - data_->contents_.push_back(new DataObjectImpl::StoredDataInfo( - Clipboard::GetFileDescriptorFormatType().ToFormatEtc(), storage)); - - // Add CFSTR_FILECONTENTS - storage = GetStorageForBytes(file_contents.data(), file_contents.length()); - data_->contents_.push_back(new DataObjectImpl::StoredDataInfo( - Clipboard::GetFileContentZeroFormatType().ToFormatEtc(), storage)); -} - -void OSExchangeDataProviderWin::SetHtml(const base::string16& html, - const GURL& base_url) { - // Add both MS CF_HTML and text/html format. CF_HTML should be in utf-8. - std::string utf8_html = base::UTF16ToUTF8(html); - std::string url = base_url.is_valid() ? base_url.spec() : std::string(); - - std::string cf_html = ClipboardUtil::HtmlToCFHtml(utf8_html, url); - STGMEDIUM* storage = GetStorageForBytes(cf_html.c_str(), cf_html.size()); - data_->contents_.push_back(new DataObjectImpl::StoredDataInfo( - Clipboard::GetHtmlFormatType().ToFormatEtc(), storage)); - - STGMEDIUM* storage_plain = GetStorageForBytes(utf8_html.c_str(), - utf8_html.size()); - data_->contents_.push_back(new DataObjectImpl::StoredDataInfo( - Clipboard::GetTextHtmlFormatType().ToFormatEtc(), storage_plain)); -} - -bool OSExchangeDataProviderWin::GetString(base::string16* data) const { - return ClipboardUtil::GetPlainText(source_object_.get(), data); -} - -bool OSExchangeDataProviderWin::GetURLAndTitle( - OSExchangeData::FilenameToURLPolicy policy, - GURL* url, - base::string16* title) const { - base::string16 url_str; - bool success = ClipboardUtil::GetUrl( - source_object_.get(), - url, - title, - policy == OSExchangeData::CONVERT_FILENAMES ? true : false); - if (success) { - DCHECK(url->is_valid()); - return true; - } else if (GetPlainTextURL(source_object_.get(), url)) { - if (url->is_valid()) - *title = net::GetSuggestedFilename(*url, "", "", "", "", std::string()); - else - title->clear(); - return true; - } - return false; -} - -bool OSExchangeDataProviderWin::GetFilename(base::FilePath* path) const { - std::vector<base::string16> filenames; - bool success = ClipboardUtil::GetFilenames(source_object_.get(), &filenames); - if (success) - *path = base::FilePath(filenames[0]); - return success; -} - -bool OSExchangeDataProviderWin::GetFilenames( - std::vector<FileInfo>* filenames) const { - std::vector<base::string16> filenames_local; - bool success = ClipboardUtil::GetFilenames(source_object_.get(), - &filenames_local); - if (success) { - for (size_t i = 0; i < filenames_local.size(); ++i) - filenames->push_back( - FileInfo(base::FilePath(filenames_local[i]), base::FilePath())); - } - return success; -} - -bool OSExchangeDataProviderWin::GetPickledData( - const OSExchangeData::CustomFormat& format, - Pickle* data) const { - DCHECK(data); - bool success = false; - STGMEDIUM medium; - FORMATETC format_etc = format.ToFormatEtc(); - if (SUCCEEDED(source_object_->GetData(&format_etc, &medium))) { - if (medium.tymed & TYMED_HGLOBAL) { - base::win::ScopedHGlobal<char*> c_data(medium.hGlobal); - DCHECK_GT(c_data.Size(), 0u); - *data = Pickle(c_data.get(), static_cast<int>(c_data.Size())); - success = true; - } - ReleaseStgMedium(&medium); - } - return success; -} - -bool OSExchangeDataProviderWin::GetFileContents( - base::FilePath* filename, - std::string* file_contents) const { - base::string16 filename_str; - if (!ClipboardUtil::GetFileContents(source_object_.get(), &filename_str, - file_contents)) { - return false; - } - *filename = base::FilePath(filename_str); - return true; -} - -bool OSExchangeDataProviderWin::GetHtml(base::string16* html, - GURL* base_url) const { - std::string url; - bool success = ClipboardUtil::GetHtml(source_object_.get(), html, &url); - if (success) - *base_url = GURL(url); - return success; -} - -bool OSExchangeDataProviderWin::HasString() const { - return ClipboardUtil::HasPlainText(source_object_.get()); -} - -bool OSExchangeDataProviderWin::HasURL( - OSExchangeData::FilenameToURLPolicy policy) const { - return (ClipboardUtil::HasUrl( - source_object_.get(), - policy == OSExchangeData::CONVERT_FILENAMES ? true : false) || - HasPlainTextURL(source_object_.get())); -} - -bool OSExchangeDataProviderWin::HasFile() const { - return ClipboardUtil::HasFilenames(source_object_.get()); -} - -bool OSExchangeDataProviderWin::HasFileContents() const { - return ClipboardUtil::HasFileContents(source_object_.get()); -} - -bool OSExchangeDataProviderWin::HasHtml() const { - return ClipboardUtil::HasHtml(source_object_.get()); -} - -bool OSExchangeDataProviderWin::HasCustomFormat( - const OSExchangeData::CustomFormat& format) const { - FORMATETC format_etc = format.ToFormatEtc(); - return (source_object_->QueryGetData(&format_etc) == S_OK); -} - -void OSExchangeDataProviderWin::SetDownloadFileInfo( - const OSExchangeData::DownloadFileInfo& download) { - // If the filename is not provided, set storage to NULL to indicate that - // the delay rendering will be used. - // TODO(dcheng): Is it actually possible for filename to be empty here? I - // think we always synthesize one in WebContentsDragWin. - STGMEDIUM* storage = NULL; - if (!download.filename.empty()) - storage = GetStorageForFileName(download.filename); - - // Add CF_HDROP. - DataObjectImpl::StoredDataInfo* info = new DataObjectImpl::StoredDataInfo( - Clipboard::GetCFHDropFormatType().ToFormatEtc(), storage); - info->downloader = download.downloader; - data_->contents_.push_back(info); -} - -void OSExchangeDataProviderWin::SetDragImage( - const gfx::ImageSkia& image, - const gfx::Vector2d& cursor_offset) { - drag_image_ = image; - drag_image_offset_ = cursor_offset; -} - -const gfx::ImageSkia& OSExchangeDataProviderWin::GetDragImage() const { - return drag_image_; -} - -const gfx::Vector2d& OSExchangeDataProviderWin::GetDragImageOffset() const { - return drag_image_offset_; -} - -/////////////////////////////////////////////////////////////////////////////// -// DataObjectImpl, IDataObject implementation: - -// The following function, DuplicateMedium, is derived from WCDataObject.cpp -// in the WebKit source code. This is the license information for the file: -/* - * Copyright (C) 2007 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -static void DuplicateMedium(CLIPFORMAT source_clipformat, - STGMEDIUM* source, - STGMEDIUM* destination) { - switch (source->tymed) { - case TYMED_HGLOBAL: - destination->hGlobal = - static_cast<HGLOBAL>(OleDuplicateData( - source->hGlobal, source_clipformat, 0)); - break; - case TYMED_MFPICT: - destination->hMetaFilePict = - static_cast<HMETAFILEPICT>(OleDuplicateData( - source->hMetaFilePict, source_clipformat, 0)); - break; - case TYMED_GDI: - destination->hBitmap = - static_cast<HBITMAP>(OleDuplicateData( - source->hBitmap, source_clipformat, 0)); - break; - case TYMED_ENHMF: - destination->hEnhMetaFile = - static_cast<HENHMETAFILE>(OleDuplicateData( - source->hEnhMetaFile, source_clipformat, 0)); - break; - case TYMED_FILE: - destination->lpszFileName = - static_cast<LPOLESTR>(OleDuplicateData( - source->lpszFileName, source_clipformat, 0)); - break; - case TYMED_ISTREAM: - destination->pstm = source->pstm; - destination->pstm->AddRef(); - break; - case TYMED_ISTORAGE: - destination->pstg = source->pstg; - destination->pstg->AddRef(); - break; - } - - destination->tymed = source->tymed; - destination->pUnkForRelease = source->pUnkForRelease; - if (destination->pUnkForRelease) - destination->pUnkForRelease->AddRef(); -} - -DataObjectImpl::DataObjectImpl() - : is_aborting_(false), - in_drag_loop_(false), - in_async_mode_(false), - async_operation_started_(false), - observer_(NULL) { -} - -DataObjectImpl::~DataObjectImpl() { - StopDownloads(); - if (observer_) - observer_->OnDataObjectDisposed(); -} - -void DataObjectImpl::StopDownloads() { - for (StoredData::iterator iter = contents_.begin(); - iter != contents_.end(); ++iter) { - if ((*iter)->downloader.get()) { - (*iter)->downloader->Stop(); - (*iter)->downloader = 0; - } - } -} - -void DataObjectImpl::RemoveData(const FORMATETC& format) { - if (format.ptd) - return; // Don't attempt to compare target devices. - - for (StoredData::iterator i = contents_.begin(); i != contents_.end(); ++i) { - if (!(*i)->format_etc.ptd && - format.cfFormat == (*i)->format_etc.cfFormat && - format.dwAspect == (*i)->format_etc.dwAspect && - format.lindex == (*i)->format_etc.lindex && - format.tymed == (*i)->format_etc.tymed) { - contents_.erase(i); - return; - } - } -} - -void DataObjectImpl::OnDownloadCompleted(const base::FilePath& file_path) { - DataObjectImpl::StoredData::iterator iter = contents_.begin(); - for (; iter != contents_.end(); ++iter) { - if ((*iter)->format_etc.cfFormat == CF_HDROP) { - // Release the old storage. - if ((*iter)->owns_medium) { - ReleaseStgMedium((*iter)->medium); - delete (*iter)->medium; - } - - // Update the storage. - (*iter)->owns_medium = true; - (*iter)->medium = GetStorageForFileName(file_path); - - break; - } - } - DCHECK(iter != contents_.end()); -} - -void DataObjectImpl::OnDownloadAborted() { -} - -HRESULT DataObjectImpl::GetData(FORMATETC* format_etc, STGMEDIUM* medium) { - if (is_aborting_) - return DV_E_FORMATETC; - - StoredData::iterator iter = contents_.begin(); - while (iter != contents_.end()) { - if ((*iter)->format_etc.cfFormat == format_etc->cfFormat && - (*iter)->format_etc.lindex == format_etc->lindex && - ((*iter)->format_etc.tymed & format_etc->tymed)) { - // If medium is NULL, delay-rendering will be used. - if ((*iter)->medium) { - DuplicateMedium((*iter)->format_etc.cfFormat, (*iter)->medium, medium); - } else { - // Fail all GetData() attempts for DownloadURL data if the drag and drop - // operation is still in progress. - if (in_drag_loop_) - return DV_E_FORMATETC; - - bool wait_for_data = false; - - // In async mode, we do not want to start waiting for the data before - // the async operation is started. This is because we want to postpone - // until Shell kicks off a background thread to do the work so that - // we do not block the UI thread. - if (!in_async_mode_ || async_operation_started_) - wait_for_data = true; - - if (!wait_for_data) - return DV_E_FORMATETC; - - // Notify the observer we start waiting for the data. This gives - // an observer a chance to end the drag and drop. - if (observer_) - observer_->OnWaitForData(); - - // Now we can start the download. - if ((*iter)->downloader.get()) { - (*iter)->downloader->Start(this); - if (!(*iter)->downloader->Wait()) { - is_aborting_ = true; - return DV_E_FORMATETC; - } - } - - // The stored data should have been updated with the final version. - // So we just need to call this function again to retrieve it. - return GetData(format_etc, medium); - } - return S_OK; - } - ++iter; - } - - return DV_E_FORMATETC; -} - -HRESULT DataObjectImpl::GetDataHere(FORMATETC* format_etc, - STGMEDIUM* medium) { - return DATA_E_FORMATETC; -} - -HRESULT DataObjectImpl::QueryGetData(FORMATETC* format_etc) { - StoredData::const_iterator iter = contents_.begin(); - while (iter != contents_.end()) { - if ((*iter)->format_etc.cfFormat == format_etc->cfFormat) - return S_OK; - ++iter; - } - return DV_E_FORMATETC; -} - -HRESULT DataObjectImpl::GetCanonicalFormatEtc( - FORMATETC* format_etc, FORMATETC* result) { - format_etc->ptd = NULL; - return E_NOTIMPL; -} - -HRESULT DataObjectImpl::SetData( - FORMATETC* format_etc, STGMEDIUM* medium, BOOL should_release) { - RemoveData(*format_etc); - - STGMEDIUM* local_medium = new STGMEDIUM; - if (should_release) { - *local_medium = *medium; - } else { - DuplicateMedium(format_etc->cfFormat, medium, local_medium); - } - - DataObjectImpl::StoredDataInfo* info = - new DataObjectImpl::StoredDataInfo(*format_etc, local_medium); - info->medium->tymed = format_etc->tymed; - info->owns_medium = !!should_release; - // Make newly added data appear first. - // TODO(dcheng): Make various setters agree whether elements should be - // prioritized from front to back or back to front. - contents_.insert(contents_.begin(), info); - - return S_OK; -} - -HRESULT DataObjectImpl::EnumFormatEtc( - DWORD direction, IEnumFORMATETC** enumerator) { - if (direction == DATADIR_GET) { - FormatEtcEnumerator* e = - new FormatEtcEnumerator(contents_.begin(), contents_.end()); - e->AddRef(); - *enumerator = e; - return S_OK; - } - return E_NOTIMPL; -} - -HRESULT DataObjectImpl::DAdvise( - FORMATETC* format_etc, DWORD advf, IAdviseSink* sink, DWORD* connection) { - return OLE_E_ADVISENOTSUPPORTED; -} - -HRESULT DataObjectImpl::DUnadvise(DWORD connection) { - return OLE_E_ADVISENOTSUPPORTED; -} - -HRESULT DataObjectImpl::EnumDAdvise(IEnumSTATDATA** enumerator) { - return OLE_E_ADVISENOTSUPPORTED; -} - -/////////////////////////////////////////////////////////////////////////////// -// DataObjectImpl, IDataObjectAsyncCapability implementation: - -HRESULT DataObjectImpl::EndOperation( - HRESULT result, IBindCtx* reserved, DWORD effects) { - async_operation_started_ = false; - return S_OK; -} - -HRESULT DataObjectImpl::GetAsyncMode(BOOL* is_op_async) { - *is_op_async = in_async_mode_ ? TRUE : FALSE; - return S_OK; -} - -HRESULT DataObjectImpl::InOperation(BOOL* in_async_op) { - *in_async_op = async_operation_started_ ? TRUE : FALSE; - return S_OK; -} - -HRESULT DataObjectImpl::SetAsyncMode(BOOL do_op_async) { - in_async_mode_ = (do_op_async == TRUE); - return S_OK; -} - -HRESULT DataObjectImpl::StartOperation(IBindCtx* reserved) { - async_operation_started_ = true; - return S_OK; -} - -/////////////////////////////////////////////////////////////////////////////// -// DataObjectImpl, IUnknown implementation: - -HRESULT DataObjectImpl::QueryInterface(const IID& iid, void** object) { - if (!object) - return E_POINTER; - if (IsEqualIID(iid, IID_IDataObject) || IsEqualIID(iid, IID_IUnknown)) { - *object = static_cast<IDataObject*>(this); - } else if (in_async_mode_ && - IsEqualIID(iid, __uuidof(IDataObjectAsyncCapability))) { - *object = static_cast<IDataObjectAsyncCapability*>(this); - } else { - *object = NULL; - return E_NOINTERFACE; - } - AddRef(); - return S_OK; -} - -ULONG DataObjectImpl::AddRef() { - base::RefCountedThreadSafe<DownloadFileObserver>::AddRef(); - return 0; -} - -ULONG DataObjectImpl::Release() { - base::RefCountedThreadSafe<DownloadFileObserver>::Release(); - return 0; -} - -/////////////////////////////////////////////////////////////////////////////// -// DataObjectImpl, private: - -static STGMEDIUM* GetStorageForBytes(const void* data, size_t bytes) { - HANDLE handle = GlobalAlloc(GPTR, static_cast<int>(bytes)); - if (handle) { - base::win::ScopedHGlobal<uint8*> scoped(handle); - memcpy(scoped.get(), data, bytes); - } - - STGMEDIUM* storage = new STGMEDIUM; - storage->hGlobal = handle; - storage->tymed = TYMED_HGLOBAL; - storage->pUnkForRelease = NULL; - return storage; -} - -template <typename T> -static STGMEDIUM* GetStorageForString(const std::basic_string<T>& data) { - return GetStorageForBytes( - data.c_str(), - (data.size() + 1) * sizeof(typename std::basic_string<T>::value_type)); -} - -static void GetInternetShortcutFileContents(const GURL& url, - std::string* data) { - DCHECK(data); - static const std::string kInternetShortcutFileStart = - "[InternetShortcut]\r\nURL="; - static const std::string kInternetShortcutFileEnd = - "\r\n"; - *data = kInternetShortcutFileStart + url.spec() + kInternetShortcutFileEnd; -} - -static void CreateValidFileNameFromTitle(const GURL& url, - const base::string16& title, - base::string16* validated) { - if (title.empty()) { - if (url.is_valid()) { - *validated = net::GetSuggestedFilename(url, "", "", "", "", - std::string()); - } else { - // Nothing else can be done, just use a default. - *validated = - l10n_util::GetStringUTF16(IDS_APP_UNTITLED_SHORTCUT_FILE_NAME); - } - } else { - *validated = title; - base::i18n::ReplaceIllegalCharactersInPath(validated, '-'); - } - static const wchar_t extension[] = L".url"; - static const size_t max_length = MAX_PATH - arraysize(extension); - if (validated->size() > max_length) - validated->erase(max_length); - *validated += extension; -} - -static STGMEDIUM* GetStorageForFileName(const base::FilePath& path) { - const size_t kDropSize = sizeof(DROPFILES); - const size_t kTotalBytes = - kDropSize + (path.value().length() + 2) * sizeof(wchar_t); - HANDLE hdata = GlobalAlloc(GMEM_MOVEABLE, kTotalBytes); - - base::win::ScopedHGlobal<DROPFILES*> locked_mem(hdata); - DROPFILES* drop_files = locked_mem.get(); - drop_files->pFiles = sizeof(DROPFILES); - drop_files->fWide = TRUE; - wchar_t* data = reinterpret_cast<wchar_t*>( - reinterpret_cast<BYTE*>(drop_files) + kDropSize); - const size_t copy_size = (path.value().length() + 1) * sizeof(wchar_t); - memcpy(data, path.value().c_str(), copy_size); - data[path.value().length() + 1] = L'\0'; // Double NULL - - STGMEDIUM* storage = new STGMEDIUM; - storage->tymed = TYMED_HGLOBAL; - storage->hGlobal = hdata; - storage->pUnkForRelease = NULL; - return storage; -} - -static LPITEMIDLIST PIDLNext(LPITEMIDLIST pidl) { - return reinterpret_cast<LPITEMIDLIST>( - reinterpret_cast<BYTE*>(pidl) + pidl->mkid.cb); -} - -static size_t PIDLSize(LPITEMIDLIST pidl) { - size_t s = 0; - while (pidl->mkid.cb > 0) { - s += pidl->mkid.cb; - pidl = PIDLNext(pidl); - } - // We add 2 because an LPITEMIDLIST is terminated by two NULL bytes. - return 2 + s; -} - -static LPITEMIDLIST GetNthPIDL(CIDA* cida, int n) { - return reinterpret_cast<LPITEMIDLIST>( - reinterpret_cast<LPBYTE>(cida) + cida->aoffset[n]); -} - -static LPITEMIDLIST GetPidlFromPath(const base::FilePath& path) { - LPITEMIDLIST pidl = NULL; - LPSHELLFOLDER desktop_folder = NULL; - LPWSTR path_str = const_cast<LPWSTR>(path.value().c_str()); - - if (FAILED(SHGetDesktopFolder(&desktop_folder))) - return NULL; - - HRESULT hr = desktop_folder->ParseDisplayName( - NULL, NULL, path_str, NULL, &pidl, NULL); - - return SUCCEEDED(hr) ? pidl : NULL; -} - -static STGMEDIUM* GetIDListStorageForFileName(const base::FilePath& path) { - LPITEMIDLIST pidl = GetPidlFromPath(path); - if (!pidl) - return NULL; - - // When using CFSTR_SHELLIDLIST the hGlobal field of the STGMEDIUM is a - // pointer to a CIDA*. A CIDA is a variable length struct that contains a PIDL - // count (a UINT), an array of offsets of the following PIDLs (a UINT[]) and - // then a series of PIDLs laid out contiguously in memory. A PIDL is - // represented by an ITEMIDLIST struct, which contains a single SHITEMID. - // Despite only containing a single SHITEMID, ITEMIDLISTs are so-named because - // SHITEMIDs contain their own size and so given one, the next can be found by - // looking at the section of memory after it. The end of a list is indicated - // by two NULL bytes. - // Here we require two PIDLs - the first PIDL is the parent folder and is - // NULL here to indicate that the parent folder is the desktop, and the second - // is the PIDL of |path|. - const size_t kPIDLCountSize = sizeof(UINT); - const size_t kPIDLOffsetsSize = 2 * sizeof(UINT); - const size_t kFirstPIDLOffset = kPIDLCountSize + kPIDLOffsetsSize; - const size_t kFirstPIDLSize = 2; // Empty PIDL - 2 NULL bytes. - const size_t kSecondPIDLSize = PIDLSize(pidl); - const size_t kCIDASize = kFirstPIDLOffset + kFirstPIDLSize + kSecondPIDLSize; - HANDLE hdata = GlobalAlloc(GMEM_MOVEABLE, kCIDASize); - - base::win::ScopedHGlobal<CIDA*> locked_mem(hdata); - CIDA* cida = locked_mem.get(); - cida->cidl = 1; // We have one PIDL (not including the 0th root PIDL). - cida->aoffset[0] = kFirstPIDLOffset; - cida->aoffset[1] = kFirstPIDLOffset + kFirstPIDLSize; - LPITEMIDLIST idl = GetNthPIDL(cida, 0); - idl->mkid.cb = 0; - idl->mkid.abID[0] = 0; - idl = GetNthPIDL(cida, 1); - memcpy(idl, pidl, kSecondPIDLSize); - - STGMEDIUM* storage = new STGMEDIUM; - storage->tymed = TYMED_HGLOBAL; - storage->hGlobal = hdata; - storage->pUnkForRelease = NULL; - return storage; -} - -static STGMEDIUM* GetStorageForFileDescriptor( - const base::FilePath& path) { - base::string16 file_name = path.value(); - DCHECK(!file_name.empty()); - HANDLE hdata = GlobalAlloc(GPTR, sizeof(FILEGROUPDESCRIPTOR)); - base::win::ScopedHGlobal<FILEGROUPDESCRIPTOR*> locked_mem(hdata); - - FILEGROUPDESCRIPTOR* descriptor = locked_mem.get(); - descriptor->cItems = 1; - descriptor->fgd[0].dwFlags = FD_LINKUI; - wcsncpy_s(descriptor->fgd[0].cFileName, MAX_PATH, file_name.c_str(), - std::min(file_name.size(), static_cast<size_t>(MAX_PATH - 1u))); - - STGMEDIUM* storage = new STGMEDIUM; - storage->tymed = TYMED_HGLOBAL; - storage->hGlobal = hdata; - storage->pUnkForRelease = NULL; - return storage; -} - -/////////////////////////////////////////////////////////////////////////////// -// OSExchangeData, public: - -// static -OSExchangeData::Provider* OSExchangeData::CreateProvider() { - return new OSExchangeDataProviderWin(); -} - -} // namespace ui
diff --git a/ui/base/dragdrop/os_exchange_data_provider_win.h b/ui/base/dragdrop/os_exchange_data_provider_win.h deleted file mode 100644 index 8587bd1..0000000 --- a/ui/base/dragdrop/os_exchange_data_provider_win.h +++ /dev/null
@@ -1,202 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_DRAGDROP_OS_EXCHANGE_DATA_PROVIDER_WIN_H_ -#define UI_BASE_DRAGDROP_OS_EXCHANGE_DATA_PROVIDER_WIN_H_ - -#include <objidl.h> -#include <shlobj.h> -#include <string> -#include <vector> - -// Win8 SDK compatibility, see http://goo.gl/fufvl for more information. -// "Note: This interface has been renamed IDataObjectAsyncCapability." -// If we're building on pre-8 we define it to its old name. It's documented as -// being binary compatible. -#ifndef __IDataObjectAsyncCapability_FWD_DEFINED__ -#define IDataObjectAsyncCapability IAsyncOperation -#endif - -#include "base/memory/scoped_vector.h" -#include "base/win/scoped_comptr.h" -#include "ui/base/dragdrop/os_exchange_data.h" -#include "ui/base/ui_base_export.h" -#include "ui/gfx/image/image_skia.h" -#include "ui/gfx/vector2d.h" - -namespace ui { - -class DataObjectImpl : public DownloadFileObserver, - public IDataObject, - public IDataObjectAsyncCapability { - public: - class Observer { - public: - virtual void OnWaitForData() = 0; - virtual void OnDataObjectDisposed() = 0; - protected: - virtual ~Observer() { } - }; - - DataObjectImpl(); - - // Accessors. - void set_observer(Observer* observer) { observer_ = observer; } - void set_in_drag_loop(bool in_drag_loop) { in_drag_loop_ = in_drag_loop; } - - // Number of known formats. - size_t size() const { return contents_.size(); } - - // DownloadFileObserver implementation: - virtual void OnDownloadCompleted(const base::FilePath& file_path); - virtual void OnDownloadAborted(); - - // IDataObject implementation: - HRESULT __stdcall GetData(FORMATETC* format_etc, STGMEDIUM* medium); - HRESULT __stdcall GetDataHere(FORMATETC* format_etc, STGMEDIUM* medium); - HRESULT __stdcall QueryGetData(FORMATETC* format_etc); - HRESULT __stdcall GetCanonicalFormatEtc( - FORMATETC* format_etc, FORMATETC* result); - HRESULT __stdcall SetData( - FORMATETC* format_etc, STGMEDIUM* medium, BOOL should_release); - HRESULT __stdcall EnumFormatEtc( - DWORD direction, IEnumFORMATETC** enumerator); - HRESULT __stdcall DAdvise(FORMATETC* format_etc, DWORD advf, - IAdviseSink* sink, DWORD* connection); - HRESULT __stdcall DUnadvise(DWORD connection); - HRESULT __stdcall EnumDAdvise(IEnumSTATDATA** enumerator); - - // IDataObjectAsyncCapability implementation: - HRESULT __stdcall EndOperation( - HRESULT result, IBindCtx* reserved, DWORD effects); - HRESULT __stdcall GetAsyncMode(BOOL* is_op_async); - HRESULT __stdcall InOperation(BOOL* in_async_op); - HRESULT __stdcall SetAsyncMode(BOOL do_op_async); - HRESULT __stdcall StartOperation(IBindCtx* reserved); - - // IUnknown implementation: - HRESULT __stdcall QueryInterface(const IID& iid, void** object); - ULONG __stdcall AddRef(); - ULONG __stdcall Release(); - - private: - // FormatEtcEnumerator only likes us for our StoredDataMap typedef. - friend class FormatEtcEnumerator; - friend class OSExchangeDataProviderWin; - - virtual ~DataObjectImpl(); - - void StopDownloads(); - - // Removes from contents_ the first data that matches |format|. - void RemoveData(const FORMATETC& format); - - // Our internal representation of stored data & type info. - struct StoredDataInfo { - FORMATETC format_etc; - STGMEDIUM* medium; - bool owns_medium; - scoped_refptr<DownloadFileProvider> downloader; - - StoredDataInfo(const FORMATETC& format_etc, STGMEDIUM* medium) - : format_etc(format_etc), medium(medium), owns_medium(true) {} - - ~StoredDataInfo() { - if (owns_medium) { - ReleaseStgMedium(medium); - delete medium; - } - if (downloader.get()) - downloader->Stop(); - } - }; - - typedef ScopedVector<StoredDataInfo> StoredData; - StoredData contents_; - - base::win::ScopedComPtr<IDataObject> source_object_; - - bool is_aborting_; - bool in_drag_loop_; - bool in_async_mode_; - bool async_operation_started_; - Observer* observer_; -}; - -class UI_BASE_EXPORT OSExchangeDataProviderWin - : public OSExchangeData::Provider { - public: - // Returns true if source has plain text that is a valid url. - static bool HasPlainTextURL(IDataObject* source); - - // Returns true if source has plain text that is a valid URL and sets url to - // that url. - static bool GetPlainTextURL(IDataObject* source, GURL* url); - - static DataObjectImpl* GetDataObjectImpl(const OSExchangeData& data); - static IDataObject* GetIDataObject(const OSExchangeData& data); - static IDataObjectAsyncCapability* GetIAsyncOperation( - const OSExchangeData& data); - - explicit OSExchangeDataProviderWin(IDataObject* source); - OSExchangeDataProviderWin(); - - virtual ~OSExchangeDataProviderWin(); - - IDataObject* data_object() const { return data_.get(); } - IDataObjectAsyncCapability* async_operation() const { return data_.get(); } - - // OSExchangeData::Provider methods. - virtual Provider* Clone() const; - virtual void MarkOriginatedFromRenderer(); - virtual bool DidOriginateFromRenderer() const; - virtual void SetString(const base::string16& data); - virtual void SetURL(const GURL& url, const base::string16& title); - virtual void SetFilename(const base::FilePath& path); - virtual void SetFilenames(const std::vector<FileInfo>& filenames); - virtual void SetPickledData(const OSExchangeData::CustomFormat& format, - const Pickle& data); - virtual void SetFileContents(const base::FilePath& filename, - const std::string& file_contents); - virtual void SetHtml(const base::string16& html, const GURL& base_url); - - virtual bool GetString(base::string16* data) const; - virtual bool GetURLAndTitle(OSExchangeData::FilenameToURLPolicy policy, - GURL* url, - base::string16* title) const; - virtual bool GetFilename(base::FilePath* path) const; - virtual bool GetFilenames(std::vector<FileInfo>* filenames) const; - virtual bool GetPickledData(const OSExchangeData::CustomFormat& format, - Pickle* data) const; - virtual bool GetFileContents(base::FilePath* filename, - std::string* file_contents) const; - virtual bool GetHtml(base::string16* html, GURL* base_url) const; - virtual bool HasString() const; - virtual bool HasURL(OSExchangeData::FilenameToURLPolicy policy) const; - virtual bool HasFile() const; - virtual bool HasFileContents() const; - virtual bool HasHtml() const; - virtual bool HasCustomFormat( - const OSExchangeData::CustomFormat& format) const; - virtual void SetDownloadFileInfo( - const OSExchangeData::DownloadFileInfo& download_info); - virtual void SetDragImage(const gfx::ImageSkia& image, - const gfx::Vector2d& cursor_offset) override; - virtual const gfx::ImageSkia& GetDragImage() const override; - virtual const gfx::Vector2d& GetDragImageOffset() const override; - - private: - scoped_refptr<DataObjectImpl> data_; - base::win::ScopedComPtr<IDataObject> source_object_; - - // Drag image and offset data. Only used for Ash. - gfx::ImageSkia drag_image_; - gfx::Vector2d drag_image_offset_; - - DISALLOW_COPY_AND_ASSIGN(OSExchangeDataProviderWin); -}; - -} // namespace ui - -#endif // UI_BASE_DRAGDROP_OS_EXCHANGE_DATA_PROVIDER_WIN_H_
diff --git a/ui/base/dragdrop/os_exchange_data_unittest.cc b/ui/base/dragdrop/os_exchange_data_unittest.cc deleted file mode 100644 index 417b6a6..0000000 --- a/ui/base/dragdrop/os_exchange_data_unittest.cc +++ /dev/null
@@ -1,186 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/files/file_util.h" -#include "base/message_loop/message_loop.h" -#include "base/pickle.h" -#include "base/strings/utf_string_conversions.h" -#include "net/base/filename_util.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "testing/platform_test.h" -#include "ui/base/dragdrop/os_exchange_data.h" -#include "ui/events/platform/platform_event_source.h" -#include "url/gurl.h" - -namespace ui { - -class OSExchangeDataTest : public PlatformTest { - public: - OSExchangeDataTest() - : event_source_(ui::PlatformEventSource::CreateDefault()) {} - - private: - base::MessageLoopForUI message_loop_; - scoped_ptr<PlatformEventSource> event_source_; -}; - -TEST_F(OSExchangeDataTest, StringDataGetAndSet) { - OSExchangeData data; - base::string16 input = base::ASCIIToUTF16("I can has cheezburger?"); - EXPECT_FALSE(data.HasString()); - data.SetString(input); - EXPECT_TRUE(data.HasString()); - - OSExchangeData data2(data.provider().Clone()); - base::string16 output; - EXPECT_TRUE(data2.HasString()); - EXPECT_TRUE(data2.GetString(&output)); - EXPECT_EQ(input, output); - std::string url_spec = "http://www.goats.com/"; - GURL url(url_spec); - base::string16 title; - EXPECT_FALSE(data2.GetURLAndTitle( - OSExchangeData::DO_NOT_CONVERT_FILENAMES, &url, &title)); - // No URLs in |data|, so url should be untouched. - EXPECT_EQ(url_spec, url.spec()); -} - -TEST_F(OSExchangeDataTest, TestURLExchangeFormats) { - OSExchangeData data; - std::string url_spec = "http://www.google.com/"; - GURL url(url_spec); - base::string16 url_title = base::ASCIIToUTF16("www.google.com"); - EXPECT_FALSE(data.HasURL(OSExchangeData::DO_NOT_CONVERT_FILENAMES)); - data.SetURL(url, url_title); - EXPECT_TRUE(data.HasURL(OSExchangeData::DO_NOT_CONVERT_FILENAMES)); - - OSExchangeData data2(data.provider().Clone()); - - // URL spec and title should match - GURL output_url; - base::string16 output_title; - EXPECT_TRUE(data2.HasURL(OSExchangeData::DO_NOT_CONVERT_FILENAMES)); - EXPECT_TRUE(data2.GetURLAndTitle( - OSExchangeData::DO_NOT_CONVERT_FILENAMES, &output_url, &output_title)); - EXPECT_EQ(url_spec, output_url.spec()); - EXPECT_EQ(url_title, output_title); - base::string16 output_string; - - // URL should be the raw text response - EXPECT_TRUE(data2.GetString(&output_string)); - EXPECT_EQ(url_spec, base::UTF16ToUTF8(output_string)); -} - -// Test that setting the URL does not overwrite a previously set custom string. -TEST_F(OSExchangeDataTest, URLAndString) { - OSExchangeData data; - base::string16 string = base::ASCIIToUTF16("I can has cheezburger?"); - data.SetString(string); - std::string url_spec = "http://www.google.com/"; - GURL url(url_spec); - base::string16 url_title = base::ASCIIToUTF16("www.google.com"); - data.SetURL(url, url_title); - - base::string16 output_string; - EXPECT_TRUE(data.GetString(&output_string)); - EXPECT_EQ(string, output_string); - - GURL output_url; - base::string16 output_title; - EXPECT_TRUE(data.GetURLAndTitle( - OSExchangeData::DO_NOT_CONVERT_FILENAMES, &output_url, &output_title)); - EXPECT_EQ(url_spec, output_url.spec()); - EXPECT_EQ(url_title, output_title); -} - -TEST_F(OSExchangeDataTest, TestFileToURLConversion) { - OSExchangeData data; - EXPECT_FALSE(data.HasURL(OSExchangeData::DO_NOT_CONVERT_FILENAMES)); - EXPECT_FALSE(data.HasURL(OSExchangeData::CONVERT_FILENAMES)); - EXPECT_FALSE(data.HasFile()); - - base::FilePath current_directory; - ASSERT_TRUE(base::GetCurrentDirectory(¤t_directory)); - - data.SetFilename(current_directory); - - { - EXPECT_FALSE(data.HasURL(OSExchangeData::DO_NOT_CONVERT_FILENAMES)); - GURL actual_url; - base::string16 actual_title; - EXPECT_FALSE(data.GetURLAndTitle( - OSExchangeData::DO_NOT_CONVERT_FILENAMES, &actual_url, &actual_title)); - EXPECT_EQ(GURL(), actual_url); - EXPECT_EQ(base::string16(), actual_title); - } - - { -// Filename to URL conversion is not implemented on ChromeOS or on non-X11 Linux -// builds. -#if defined(OS_CHROMEOS) || (defined(OS_LINUX) && !defined(USE_X11)) - const bool expected_success = false; - const GURL expected_url; -#else - const bool expected_success = true; - const GURL expected_url(net::FilePathToFileURL(current_directory)); -#endif - EXPECT_EQ(expected_success, data.HasURL(OSExchangeData::CONVERT_FILENAMES)); - GURL actual_url; - base::string16 actual_title; - EXPECT_EQ( - expected_success, - data.GetURLAndTitle( - OSExchangeData::CONVERT_FILENAMES, &actual_url, &actual_title)); - // Some Mac OS versions return the URL in file://localhost form instead - // of file:///, so we compare the url's path not its absolute string. - EXPECT_EQ(expected_url.path(), actual_url.path()); - EXPECT_EQ(base::string16(), actual_title); - } - EXPECT_TRUE(data.HasFile()); - base::FilePath actual_path; - EXPECT_TRUE(data.GetFilename(&actual_path)); - EXPECT_EQ(current_directory, actual_path); -} - -TEST_F(OSExchangeDataTest, TestPickledData) { - const OSExchangeData::CustomFormat kTestFormat = - ui::Clipboard::GetFormatType("application/vnd.chromium.test"); - - Pickle saved_pickle; - saved_pickle.WriteInt(1); - saved_pickle.WriteInt(2); - OSExchangeData data; - data.SetPickledData(kTestFormat, saved_pickle); - - OSExchangeData copy(data.provider().Clone()); - EXPECT_TRUE(copy.HasCustomFormat(kTestFormat)); - - Pickle restored_pickle; - EXPECT_TRUE(copy.GetPickledData(kTestFormat, &restored_pickle)); - PickleIterator iterator(restored_pickle); - int value; - EXPECT_TRUE(restored_pickle.ReadInt(&iterator, &value)); - EXPECT_EQ(1, value); - EXPECT_TRUE(restored_pickle.ReadInt(&iterator, &value)); - EXPECT_EQ(2, value); -} - -#if defined(USE_AURA) -TEST_F(OSExchangeDataTest, TestHTML) { - OSExchangeData data; - GURL url("http://www.google.com/"); - base::string16 html = base::ASCIIToUTF16( - "<HTML>\n<BODY>\n" - "<b>bold.</b> <i><b>This is bold italic.</b></i>\n" - "</BODY>\n</HTML>"); - data.SetHtml(html, url); - - OSExchangeData copy(data.provider().Clone()); - base::string16 read_html; - EXPECT_TRUE(copy.GetHtml(&read_html, &url)); - EXPECT_EQ(html, read_html); -} -#endif - -} // namespace ui
diff --git a/ui/base/dragdrop/os_exchange_data_win_unittest.cc b/ui/base/dragdrop/os_exchange_data_win_unittest.cc deleted file mode 100644 index 1040ecf..0000000 --- a/ui/base/dragdrop/os_exchange_data_win_unittest.cc +++ /dev/null
@@ -1,357 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "base/strings/utf_string_conversions.h" -#include "base/win/scoped_hglobal.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/base/clipboard/clipboard.h" -#include "ui/base/dragdrop/os_exchange_data.h" -#include "ui/base/dragdrop/os_exchange_data_provider_win.h" -#include "url/gurl.h" - -namespace ui { - -// Test getting using the IDataObject COM API -TEST(OSExchangeDataWinTest, StringDataAccessViaCOM) { - OSExchangeData data; - std::wstring input = L"O hai googlz."; - data.SetString(input); - base::win::ScopedComPtr<IDataObject> com_data( - OSExchangeDataProviderWin::GetIDataObject(data)); - - FORMATETC format_etc = - { CF_UNICODETEXT, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL }; - EXPECT_EQ(S_OK, com_data->QueryGetData(&format_etc)); - - STGMEDIUM medium; - EXPECT_EQ(S_OK, com_data->GetData(&format_etc, &medium)); - std::wstring output = - base::win::ScopedHGlobal<wchar_t*>(medium.hGlobal).get(); - EXPECT_EQ(input, output); - ReleaseStgMedium(&medium); -} - -// Test setting using the IDataObject COM API -TEST(OSExchangeDataWinTest, StringDataWritingViaCOM) { - OSExchangeData data; - std::wstring input = L"http://www.google.com/"; - - base::win::ScopedComPtr<IDataObject> com_data( - OSExchangeDataProviderWin::GetIDataObject(data)); - - // Store data in the object using the COM SetData API. - CLIPFORMAT cfstr_ineturl = RegisterClipboardFormat(CFSTR_INETURL); - FORMATETC format_etc = - { cfstr_ineturl, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL }; - STGMEDIUM medium; - medium.tymed = TYMED_HGLOBAL; - HGLOBAL glob = GlobalAlloc(GPTR, sizeof(wchar_t) * (input.size() + 1)); - size_t stringsz = input.size(); - SIZE_T sz = GlobalSize(glob); - base::win::ScopedHGlobal<wchar_t*> global_lock(glob); - wchar_t* buffer_handle = global_lock.get(); - wcscpy_s(buffer_handle, input.size() + 1, input.c_str()); - medium.hGlobal = glob; - medium.pUnkForRelease = NULL; - EXPECT_EQ(S_OK, com_data->SetData(&format_etc, &medium, TRUE)); - - // Construct a new object with the old object so that we can use our access - // APIs. - OSExchangeData data2(data.provider().Clone()); - EXPECT_TRUE(data2.HasURL(OSExchangeData::CONVERT_FILENAMES)); - GURL url_from_data; - std::wstring title; - EXPECT_TRUE(data2.GetURLAndTitle( - OSExchangeData::CONVERT_FILENAMES, &url_from_data, &title)); - GURL reference_url(input); - EXPECT_EQ(reference_url.spec(), url_from_data.spec()); -} - -// Verifies SetData invoked twice with the same data clobbers existing data. -TEST(OSExchangeDataWinTest, RemoveData) { - OSExchangeData data; - std::wstring input = L"http://www.google.com/"; - std::wstring input2 = L"http://www.google2.com/"; - - base::win::ScopedComPtr<IDataObject> com_data( - OSExchangeDataProviderWin::GetIDataObject(data)); - - // Store data in the object using the COM SetData API. - CLIPFORMAT cfstr_ineturl = RegisterClipboardFormat(CFSTR_INETURL); - FORMATETC format_etc = - { cfstr_ineturl, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL }; - STGMEDIUM medium; - medium.tymed = TYMED_HGLOBAL; - { - HGLOBAL glob = GlobalAlloc(GPTR, sizeof(wchar_t) * (input.size() + 1)); - size_t stringsz = input.size(); - SIZE_T sz = GlobalSize(glob); - base::win::ScopedHGlobal<wchar_t*> global_lock(glob); - wchar_t* buffer_handle = global_lock.get(); - wcscpy_s(buffer_handle, input.size() + 1, input.c_str()); - medium.hGlobal = glob; - medium.pUnkForRelease = NULL; - EXPECT_EQ(S_OK, com_data->SetData(&format_etc, &medium, TRUE)); - } - // This should clobber the existing data. - { - HGLOBAL glob = GlobalAlloc(GPTR, sizeof(wchar_t) * (input2.size() + 1)); - size_t stringsz = input2.size(); - SIZE_T sz = GlobalSize(glob); - base::win::ScopedHGlobal<wchar_t*> global_lock(glob); - wchar_t* buffer_handle = global_lock.get(); - wcscpy_s(buffer_handle, input2.size() + 1, input2.c_str()); - medium.hGlobal = glob; - medium.pUnkForRelease = NULL; - EXPECT_EQ(S_OK, com_data->SetData(&format_etc, &medium, TRUE)); - } - EXPECT_EQ(1u, static_cast<DataObjectImpl*>(com_data.get())->size()); - - // Construct a new object with the old object so that we can use our access - // APIs. - OSExchangeData data2(data.provider().Clone()); - EXPECT_TRUE(data2.HasURL(OSExchangeData::CONVERT_FILENAMES)); - GURL url_from_data; - std::wstring title; - EXPECT_TRUE(data2.GetURLAndTitle( - OSExchangeData::CONVERT_FILENAMES, &url_from_data, &title)); - EXPECT_EQ(GURL(input2).spec(), url_from_data.spec()); -} - -TEST(OSExchangeDataWinTest, URLDataAccessViaCOM) { - OSExchangeData data; - GURL url("http://www.google.com/"); - data.SetURL(url, L""); - base::win::ScopedComPtr<IDataObject> com_data( - OSExchangeDataProviderWin::GetIDataObject(data)); - - CLIPFORMAT cfstr_ineturl = RegisterClipboardFormat(CFSTR_INETURL); - FORMATETC format_etc = - { cfstr_ineturl, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL }; - EXPECT_EQ(S_OK, com_data->QueryGetData(&format_etc)); - - STGMEDIUM medium; - EXPECT_EQ(S_OK, com_data->GetData(&format_etc, &medium)); - std::wstring output = - base::win::ScopedHGlobal<wchar_t*>(medium.hGlobal).get(); - EXPECT_EQ(url.spec(), base::WideToUTF8(output)); - ReleaseStgMedium(&medium); -} - -TEST(OSExchangeDataWinTest, MultipleFormatsViaCOM) { - OSExchangeData data; - std::string url_spec = "http://www.google.com/"; - GURL url(url_spec); - std::wstring text = L"O hai googlz."; - data.SetURL(url, L"Google"); - data.SetString(text); - - base::win::ScopedComPtr<IDataObject> com_data( - OSExchangeDataProviderWin::GetIDataObject(data)); - - CLIPFORMAT cfstr_ineturl = RegisterClipboardFormat(CFSTR_INETURL); - FORMATETC url_format_etc = - { cfstr_ineturl, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL }; - EXPECT_EQ(S_OK, com_data->QueryGetData(&url_format_etc)); - FORMATETC text_format_etc = - { CF_UNICODETEXT, NULL, DVASPECT_CONTENT, -1, TYMED_HGLOBAL }; - EXPECT_EQ(S_OK, com_data->QueryGetData(&text_format_etc)); - - STGMEDIUM medium; - EXPECT_EQ(S_OK, com_data->GetData(&url_format_etc, &medium)); - std::wstring output_url = - base::win::ScopedHGlobal<wchar_t*>(medium.hGlobal).get(); - EXPECT_EQ(url.spec(), base::WideToUTF8(output_url)); - ReleaseStgMedium(&medium); - - // The text is supposed to be the raw text of the URL, _NOT_ the value of - // |text|! This is because the URL is added first and thus takes precedence! - EXPECT_EQ(S_OK, com_data->GetData(&text_format_etc, &medium)); - std::wstring output_text = - base::win::ScopedHGlobal<wchar_t*>(medium.hGlobal).get(); - EXPECT_EQ(url_spec, base::WideToUTF8(output_text)); - ReleaseStgMedium(&medium); -} - -TEST(OSExchangeDataWinTest, EnumerationViaCOM) { - OSExchangeData data; - data.SetURL(GURL("http://www.google.com/"), L""); - data.SetString(L"O hai googlz."); - - CLIPFORMAT cfstr_file_group_descriptor = - RegisterClipboardFormat(CFSTR_FILEDESCRIPTOR); - CLIPFORMAT text_x_moz_url = RegisterClipboardFormat(L"text/x-moz-url"); - - base::win::ScopedComPtr<IDataObject> com_data( - OSExchangeDataProviderWin::GetIDataObject(data)); - base::win::ScopedComPtr<IEnumFORMATETC> enumerator; - EXPECT_EQ(S_OK, com_data.get()->EnumFormatEtc(DATADIR_GET, - enumerator.Receive())); - - // Test that we can get one item. - { - // Explictly don't reset the first time, to verify the creation state is - // OK. - ULONG retrieved = 0; - FORMATETC elements_array[1]; - EXPECT_EQ(S_OK, enumerator->Next(1, - reinterpret_cast<FORMATETC*>(&elements_array), &retrieved)); - EXPECT_EQ(1, retrieved); - EXPECT_EQ(text_x_moz_url, elements_array[0].cfFormat); - } - - // Test that we can get one item with a NULL retrieved value. - { - EXPECT_EQ(S_OK, enumerator->Reset()); - FORMATETC elements_array[1]; - EXPECT_EQ(S_OK, enumerator->Next(1, - reinterpret_cast<FORMATETC*>(&elements_array), NULL)); - EXPECT_EQ(text_x_moz_url, elements_array[0].cfFormat); - } - - // Test that we can get two items. - { - EXPECT_EQ(S_OK, enumerator->Reset()); - ULONG retrieved = 0; - FORMATETC elements_array[2]; - EXPECT_EQ(S_OK, enumerator->Next(2, - reinterpret_cast<FORMATETC*>(&elements_array), &retrieved)); - EXPECT_EQ(2, retrieved); - EXPECT_EQ(text_x_moz_url, elements_array[0].cfFormat); - EXPECT_EQ(cfstr_file_group_descriptor, elements_array[1].cfFormat); - } - - // Test that we can skip the first item. - { - EXPECT_EQ(S_OK, enumerator->Reset()); - EXPECT_EQ(S_OK, enumerator->Skip(1)); - ULONG retrieved = 0; - FORMATETC elements_array[1]; - EXPECT_EQ(S_OK, enumerator->Next(1, - reinterpret_cast<FORMATETC*>(&elements_array), &retrieved)); - EXPECT_EQ(1, retrieved); - EXPECT_EQ(cfstr_file_group_descriptor, elements_array[0].cfFormat); - } - - // Test that we can skip the first item, and create a clone that matches in - // this state, and modify the original without affecting the clone. - { - EXPECT_EQ(S_OK, enumerator->Reset()); - EXPECT_EQ(S_OK, enumerator->Skip(1)); - base::win::ScopedComPtr<IEnumFORMATETC> cloned_enumerator; - EXPECT_EQ(S_OK, enumerator.get()->Clone(cloned_enumerator.Receive())); - EXPECT_EQ(S_OK, enumerator.get()->Reset()); - - { - ULONG retrieved = 0; - FORMATETC elements_array[1]; - EXPECT_EQ(S_OK, cloned_enumerator->Next(1, - reinterpret_cast<FORMATETC*>(&elements_array), &retrieved)); - EXPECT_EQ(1, retrieved); - EXPECT_EQ(cfstr_file_group_descriptor, elements_array[0].cfFormat); - } - - { - ULONG retrieved = 0; - FORMATETC elements_array[1]; - EXPECT_EQ(S_OK, enumerator->Next(1, - reinterpret_cast<FORMATETC*>(&elements_array), &retrieved)); - EXPECT_EQ(1, retrieved); - EXPECT_EQ(text_x_moz_url, elements_array[0].cfFormat); - } - } -} - -TEST(OSExchangeDataWinTest, TestURLExchangeFormatsViaCOM) { - OSExchangeData data; - std::string url_spec = "http://www.google.com/"; - GURL url(url_spec); - std::wstring url_title = L"www.google.com"; - data.SetURL(url, url_title); - - // File contents access via COM - base::win::ScopedComPtr<IDataObject> com_data( - OSExchangeDataProviderWin::GetIDataObject(data)); - { - CLIPFORMAT cfstr_file_contents = - RegisterClipboardFormat(CFSTR_FILECONTENTS); - FORMATETC format_etc = - { cfstr_file_contents, NULL, DVASPECT_CONTENT, 0, TYMED_HGLOBAL }; - EXPECT_EQ(S_OK, com_data->QueryGetData(&format_etc)); - - STGMEDIUM medium; - EXPECT_EQ(S_OK, com_data->GetData(&format_etc, &medium)); - base::win::ScopedHGlobal<char*> glob(medium.hGlobal); - std::string output(glob.get(), glob.Size()); - std::string file_contents = "[InternetShortcut]\r\nURL="; - file_contents += url_spec; - file_contents += "\r\n"; - EXPECT_EQ(file_contents, output); - ReleaseStgMedium(&medium); - } -} - -TEST(OSExchangeDataWinTest, FileContents) { - OSExchangeData data; - std::string file_contents("data\0with\0nulls", 15); - data.SetFileContents(base::FilePath(L"filename.txt"), file_contents); - - OSExchangeData copy(data.provider().Clone()); - base::FilePath filename; - std::string read_contents; - EXPECT_TRUE(copy.GetFileContents(&filename, &read_contents)); - EXPECT_EQ(L"filename.txt", filename.value()); - EXPECT_EQ(file_contents, read_contents); -} - -TEST(OSExchangeDataWinTest, CFHtml) { - OSExchangeData data; - GURL url("http://www.google.com/"); - std::wstring html( - L"<HTML>\n<BODY>\n" - L"<b>bold.</b> <i><b>This is bold italic.</b></i>\n" - L"</BODY>\n</HTML>"); - data.SetHtml(html, url); - - // Check the CF_HTML too. - std::string expected_cf_html( - "Version:0.9\r\nStartHTML:0000000139\r\nEndHTML:0000000288\r\n" - "StartFragment:0000000175\r\nEndFragment:0000000252\r\n" - "SourceURL:http://www.google.com/\r\n<html>\r\n<body>\r\n" - "<!--StartFragment-->"); - expected_cf_html += base::WideToUTF8(html); - expected_cf_html.append("<!--EndFragment-->\r\n</body>\r\n</html>"); - - FORMATETC format = Clipboard::GetHtmlFormatType().ToFormatEtc(); - STGMEDIUM medium; - IDataObject* data_object = OSExchangeDataProviderWin::GetIDataObject(data); - EXPECT_EQ(S_OK, data_object->GetData(&format, &medium)); - base::win::ScopedHGlobal<char*> glob(medium.hGlobal); - std::string output(glob.get(), glob.Size()); - EXPECT_EQ(expected_cf_html, output); - ReleaseStgMedium(&medium); -} - -TEST(OSExchangeDataWinTest, SetURLWithMaxPath) { - OSExchangeData data; - std::wstring long_title(L'a', MAX_PATH + 1); - data.SetURL(GURL("http://google.com"), long_title); -} - -TEST(OSExchangeDataWinTest, ProvideURLForPlainTextURL) { - OSExchangeData data; - data.SetString(L"http://google.com"); - - OSExchangeData data2(data.provider().Clone()); - ASSERT_TRUE(data2.HasURL(OSExchangeData::CONVERT_FILENAMES)); - GURL read_url; - std::wstring title; - EXPECT_TRUE(data2.GetURLAndTitle( - OSExchangeData::CONVERT_FILENAMES, &read_url, &title)); - EXPECT_EQ(GURL("http://google.com"), read_url); -} - -} // namespace ui
diff --git a/ui/base/glib/glib_integers.h b/ui/base/glib/glib_integers.h deleted file mode 100644 index a875ffe..0000000 --- a/ui/base/glib/glib_integers.h +++ /dev/null
@@ -1,27 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_GLIB_GLIB_INTEGERS_H_ -#define UI_BASE_GLIB_GLIB_INTEGERS_H_ - -// GLib/GObject/Gtk all use their own integer typedefs. They are copied here -// for forward declaration reasons so we don't pull in all of glib/gtypes.h -// when we just need a gpointer. -typedef char gchar; -typedef short gshort; -typedef long glong; -typedef int gint; -typedef gint gboolean; -typedef unsigned char guchar; -typedef unsigned short gushort; -typedef unsigned long gulong; -typedef unsigned int guint; - -typedef unsigned short guint16; -typedef unsigned int guint32; - -typedef void* gpointer; -typedef const void *gconstpointer; - -#endif // UI_BASE_GLIB_GLIB_INTEGERS_H_
diff --git a/ui/base/glib/glib_signal.h b/ui/base/glib/glib_signal.h deleted file mode 100644 index 23630f4..0000000 --- a/ui/base/glib/glib_signal.h +++ /dev/null
@@ -1,154 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_GLIB_GLIB_SIGNAL_H_ -#define UI_BASE_GLIB_GLIB_SIGNAL_H_ - -typedef void* gpointer; - -// At the time of writing this, there were two common ways of binding our C++ -// code to the gobject C system. We either defined a whole bunch of "static -// MethodThunk()" which just called nonstatic Method()s on a class (which hurt -// readability of the headers and signal connection code) OR we declared -// "static Method()" and passed in the current object as the gpointer (and hurt -// readability in the implementation by having "context->" before every -// variable). - -// The hopeful result of using these macros is that the code will be more -// readable and regular. There shouldn't be a bunch of static Thunks visible in -// the headers and the implementations shouldn't be filled with "context->" -// de-references. - -#define CHROMEG_CALLBACK_0(CLASS, RETURN, METHOD, SENDER) \ - static RETURN METHOD ## Thunk(SENDER sender, gpointer userdata) { \ - return reinterpret_cast<CLASS*>(userdata)->METHOD(sender); \ - } \ - \ - RETURN METHOD(SENDER); - -#define CHROMEG_CALLBACK_1(CLASS, RETURN, METHOD, SENDER, ARG1) \ - static RETURN METHOD ## Thunk(SENDER sender, ARG1 one, \ - gpointer userdata) { \ - return reinterpret_cast<CLASS*>(userdata)->METHOD(sender, one); \ - } \ - \ - RETURN METHOD(SENDER, ARG1); - -#define CHROMEG_CALLBACK_2(CLASS, RETURN, METHOD, SENDER, ARG1, ARG2) \ - static RETURN METHOD ## Thunk(SENDER sender, ARG1 one, ARG2 two, \ - gpointer userdata) { \ - return reinterpret_cast<CLASS*>(userdata)->METHOD(sender, one, two); \ - } \ - \ - RETURN METHOD(SENDER, ARG1, ARG2); - -#define CHROMEG_CALLBACK_3(CLASS, RETURN, METHOD, SENDER, ARG1, ARG2, ARG3) \ - static RETURN METHOD ## Thunk(SENDER sender, ARG1 one, ARG2 two, \ - ARG3 three, gpointer userdata) { \ - return reinterpret_cast<CLASS*>(userdata)-> \ - METHOD(sender, one, two, three); \ - } \ - \ - RETURN METHOD(SENDER, ARG1, ARG2, ARG3); - -#define CHROMEG_CALLBACK_4(CLASS, RETURN, METHOD, SENDER, ARG1, ARG2, ARG3, \ - ARG4) \ - static RETURN METHOD ## Thunk(SENDER sender, ARG1 one, ARG2 two, \ - ARG3 three, ARG4 four, \ - gpointer userdata) { \ - return reinterpret_cast<CLASS*>(userdata)-> \ - METHOD(sender, one, two, three, four); \ - } \ - \ - RETURN METHOD(SENDER, ARG1, ARG2, ARG3, ARG4); - -#define CHROMEG_CALLBACK_5(CLASS, RETURN, METHOD, SENDER, ARG1, ARG2, ARG3, \ - ARG4, ARG5) \ - static RETURN METHOD ## Thunk(SENDER sender, ARG1 one, ARG2 two, \ - ARG3 three, ARG4 four, ARG5 five, \ - gpointer userdata) { \ - return reinterpret_cast<CLASS*>(userdata)-> \ - METHOD(sender, one, two, three, four, five); \ - } \ - \ - RETURN METHOD(SENDER, ARG1, ARG2, ARG3, ARG4, ARG5); - -#define CHROMEG_CALLBACK_6(CLASS, RETURN, METHOD, SENDER, ARG1, ARG2, ARG3, \ - ARG4, ARG5, ARG6) \ - static RETURN METHOD ## Thunk(SENDER sender, ARG1 one, ARG2 two, \ - ARG3 three, ARG4 four, ARG5 five, \ - ARG6 six, gpointer userdata) { \ - return reinterpret_cast<CLASS*>(userdata)-> \ - METHOD(sender, one, two, three, four, five, six); \ - } \ - \ - RETURN METHOD(SENDER, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6); - -#define CHROMEG_VIRTUAL_CALLBACK_0(CLASS, RETURN, METHOD, SENDER) \ - static RETURN METHOD ## Thunk(SENDER sender, gpointer userdata) { \ - return reinterpret_cast<CLASS*>(userdata)->METHOD(sender); \ - } \ - \ - virtual RETURN METHOD(SENDER); - -#define CHROMEG_VIRTUAL_CALLBACK_1(CLASS, RETURN, METHOD, SENDER, ARG1) \ - static RETURN METHOD ## Thunk(SENDER sender, ARG1 one, \ - gpointer userdata) { \ - return reinterpret_cast<CLASS*>(userdata)->METHOD(sender, one); \ - } \ - \ - virtual RETURN METHOD(SENDER, ARG1); - -#define CHROMEG_VIRTUAL_CALLBACK_2(CLASS, RETURN, METHOD, SENDER, ARG1, ARG2) \ - static RETURN METHOD ## Thunk(SENDER sender, ARG1 one, ARG2 two, \ - gpointer userdata) { \ - return reinterpret_cast<CLASS*>(userdata)->METHOD(sender, one, two); \ - } \ - \ - virtual RETURN METHOD(SENDER, ARG1, ARG2); - -#define CHROMEG_VIRTUAL_CALLBACK_3(CLASS, RETURN, METHOD, SENDER, ARG1, ARG2, \ - ARG3) \ - static RETURN METHOD ## Thunk(SENDER sender, ARG1 one, ARG2 two, \ - ARG3 three, gpointer userdata) { \ - return reinterpret_cast<CLASS*>(userdata)-> \ - METHOD(sender, one, two, three); \ - } \ - \ - virtual RETURN METHOD(SENDER, ARG1, ARG2, ARG3); - -#define CHROMEG_VIRTUAL_CALLBACK_4(CLASS, RETURN, METHOD, SENDER, ARG1, ARG2, \ - ARG3, ARG4) \ - static RETURN METHOD ## Thunk(SENDER sender, ARG1 one, ARG2 two, \ - ARG3 three, ARG4 four, \ - gpointer userdata) { \ - return reinterpret_cast<CLASS*>(userdata)-> \ - METHOD(sender, one, two, three, four); \ - } \ - \ - virtual RETURN METHOD(SENDER, ARG1, ARG2, ARG3, ARG4); - -#define CHROMEG_VIRTUAL_CALLBACK_5(CLASS, RETURN, METHOD, SENDER, ARG1, ARG2, \ - ARG3, ARG4, ARG5) \ - static RETURN METHOD ## Thunk(SENDER sender, ARG1 one, ARG2 two, \ - ARG3 three, ARG4 four, ARG5 five, \ - gpointer userdata) { \ - return reinterpret_cast<CLASS*>(userdata)-> \ - METHOD(sender, one, two, three, four, five); \ - } \ - \ - virtual RETURN METHOD(SENDER, ARG1, ARG2, ARG3, ARG4, ARG5); - -#define CHROMEG_VIRTUAL_CALLBACK_6(CLASS, RETURN, METHOD, SENDER, ARG1, ARG2, \ - ARG3, ARG4, ARG5, ARG6) \ - static RETURN METHOD ## Thunk(SENDER sender, ARG1 one, ARG2 two, \ - ARG3 three, ARG4 four, ARG5 five, \ - ARG6 six, gpointer userdata) { \ - return reinterpret_cast<CLASS*>(userdata)-> \ - METHOD(sender, one, two, three, four, five, six); \ - } \ - \ - virtual RETURN METHOD(SENDER, ARG1, ARG2, ARG3, ARG4, ARG5, ARG6); - -#endif
diff --git a/ui/base/ime/DEPS b/ui/base/ime/DEPS deleted file mode 100644 index d59514e..0000000 --- a/ui/base/ime/DEPS +++ /dev/null
@@ -1,5 +0,0 @@ -include_rules = [ - "+chromeos/ime", - "+third_party/gtk+/gdk/gdkkeysyms.h", - "+third_party/gtk+/gtk/gtkimcontextsimpleseqs.h", -]
diff --git a/ui/base/ime/OWNERS b/ui/base/ime/OWNERS deleted file mode 100644 index bc96702..0000000 --- a/ui/base/ime/OWNERS +++ /dev/null
@@ -1,10 +0,0 @@ -# primary reviewer. -yukishiino@chromium.org - -# backup reviewers. -komatsu@chromium.org -mukai@chromium.org -nona@chromium.org - -# For Windows. -yukawa@chromium.org
diff --git a/ui/base/ime/candidate_window.cc b/ui/base/ime/candidate_window.cc deleted file mode 100644 index 6cb32e2..0000000 --- a/ui/base/ime/candidate_window.cc +++ /dev/null
@@ -1,103 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/candidate_window.h" - -#include <string> -#include "base/logging.h" -#include "base/strings/utf_string_conversions.h" -#include "base/values.h" - -namespace ui { - -namespace { -// The default entry number of a page in CandidateWindow. -const int kDefaultPageSize = 9; -} // namespace - -CandidateWindow::CandidateWindow() - : property_(new CandidateWindowProperty) { -} - -CandidateWindow::~CandidateWindow() { -} - -bool CandidateWindow::IsEqual(const CandidateWindow& cw) const { - if (page_size() != cw.page_size() || - cursor_position() != cw.cursor_position() || - is_cursor_visible() != cw.is_cursor_visible() || - orientation() != cw.orientation() || - show_window_at_composition() != cw.show_window_at_composition() || - is_auxiliary_text_visible() != cw.is_auxiliary_text_visible() || - auxiliary_text() != cw.auxiliary_text() || - candidates_.size() != cw.candidates_.size()) - return false; - - for (size_t i = 0; i < candidates_.size(); ++i) { - const Entry& left = candidates_[i]; - const Entry& right = cw.candidates_[i]; - if (left.value != right.value || - left.label != right.label || - left.annotation != right.annotation || - left.description_title != right.description_title || - left.description_body != right.description_body) - return false; - } - return true; -} - -void CandidateWindow::CopyFrom(const CandidateWindow& cw) { - SetProperty(cw.GetProperty()); - candidates_.clear(); - candidates_ = cw.candidates_; -} - - -void CandidateWindow::GetInfolistEntries( - std::vector<ui::InfolistEntry>* infolist_entries, - bool* has_highlighted) const { - DCHECK(infolist_entries); - DCHECK(has_highlighted); - infolist_entries->clear(); - *has_highlighted = false; - - const size_t cursor_index_in_page = cursor_position() % page_size(); - - for (size_t i = 0; i < candidates().size(); ++i) { - const CandidateWindow::Entry& candidate_entry = candidates()[i]; - if (candidate_entry.description_title.empty() && - candidate_entry.description_body.empty()) - continue; - - InfolistEntry entry(candidate_entry.description_title, - candidate_entry.description_body); - if (i == cursor_index_in_page) { - entry.highlighted = true; - *has_highlighted = true; - } - infolist_entries->push_back(entry); - } -} - -// When the default values are changed, please modify -// InputMethodEngineInterface::CandidateWindowProperty too. -CandidateWindow::CandidateWindowProperty::CandidateWindowProperty() - : page_size(kDefaultPageSize), - cursor_position(0), - is_cursor_visible(true), - is_vertical(false), - show_window_at_composition(false), - is_auxiliary_text_visible(false) { -} - -CandidateWindow::CandidateWindowProperty::~CandidateWindowProperty() { -} - -CandidateWindow::Entry::Entry() { -} - -CandidateWindow::Entry::~Entry() { -} - -} // namespace ui
diff --git a/ui/base/ime/candidate_window.h b/ui/base/ime/candidate_window.h deleted file mode 100644 index 6ae6dd8..0000000 --- a/ui/base/ime/candidate_window.h +++ /dev/null
@@ -1,131 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_CANDIDATE_WINDOW_H_ -#define UI_BASE_IME_CANDIDATE_WINDOW_H_ - -#include <string> -#include <vector> -#include "base/basictypes.h" -#include "base/memory/scoped_ptr.h" -#include "ui/base/ime/infolist_entry.h" -#include "ui/base/ui_base_export.h" - -namespace ui { - -// CandidateWindow represents the structure of candidates generated from IME. -class UI_BASE_EXPORT CandidateWindow { - public: - enum Orientation { - HORIZONTAL = 0, - VERTICAL = 1, - }; - - struct UI_BASE_EXPORT CandidateWindowProperty { - CandidateWindowProperty(); - virtual ~CandidateWindowProperty(); - int page_size; - int cursor_position; - bool is_cursor_visible; - bool is_vertical; - bool show_window_at_composition; - - // Auxiliary text is typically displayed in the footer of the candidate - // window. - std::string auxiliary_text; - bool is_auxiliary_text_visible; - }; - - // Represents a candidate entry. - struct UI_BASE_EXPORT Entry { - Entry(); - virtual ~Entry(); - base::string16 value; - base::string16 label; - base::string16 annotation; - base::string16 description_title; - base::string16 description_body; - }; - - CandidateWindow(); - virtual ~CandidateWindow(); - - // Returns true if the given |candidate_window| is equal to myself. - bool IsEqual(const CandidateWindow& candidate_window) const; - - // Copies |candidate_window| to myself. - void CopyFrom(const CandidateWindow& candidate_window); - - const CandidateWindowProperty& GetProperty() const { - return *property_; - } - void SetProperty(const CandidateWindowProperty& property) { - *property_ = property; - } - - // Gets the infolist entry models. Sets |has_highlighted| to true if |entries| - // contains highlighted entry. - void GetInfolistEntries(std::vector<InfolistEntry>* entries, - bool* has_highlighted) const; - - // Returns the number of candidates in one page. - uint32 page_size() const { return property_->page_size; } - void set_page_size(uint32 page_size) { property_->page_size = page_size; } - - // Returns the cursor index of the currently selected candidate. - uint32 cursor_position() const { return property_->cursor_position; } - void set_cursor_position(uint32 cursor_position) { - property_->cursor_position = cursor_position; - } - - // Returns true if the cursor is visible. - bool is_cursor_visible() const { return property_->is_cursor_visible; } - void set_is_cursor_visible(bool is_cursor_visible) { - property_->is_cursor_visible = is_cursor_visible; - } - - // Returns the orientation of the candidate window. - Orientation orientation() const { - return property_->is_vertical ? VERTICAL : HORIZONTAL; - } - void set_orientation(Orientation orientation) { - property_->is_vertical = (orientation == VERTICAL); - } - - // Returns true if the auxiliary text is visible. - bool is_auxiliary_text_visible() const { - return property_->is_auxiliary_text_visible; - } - void set_is_auxiliary_text_visible(bool is_auxiliary_text_visible) const { - property_->is_auxiliary_text_visible = is_auxiliary_text_visible; - } - - // Accessors of auxiliary_text. - const std::string& auxiliary_text() const { - return property_->auxiliary_text; - } - void set_auxiliary_text(const std::string& auxiliary_text) const { - property_->auxiliary_text = auxiliary_text; - } - - const std::vector<Entry>& candidates() const { return candidates_; } - std::vector<Entry>* mutable_candidates() { return &candidates_; } - - bool show_window_at_composition() const { - return property_->show_window_at_composition; - } - void set_show_window_at_composition(bool show_window_at_composition) { - property_->show_window_at_composition = show_window_at_composition; - } - - private: - scoped_ptr<CandidateWindowProperty> property_; - std::vector<Entry> candidates_; - - DISALLOW_COPY_AND_ASSIGN(CandidateWindow); -}; - -} // namespace ui - -#endif // UI_BASE_IME_CANDIDATE_WINDOW_H_
diff --git a/ui/base/ime/candidate_window_unittest.cc b/ui/base/ime/candidate_window_unittest.cc deleted file mode 100644 index 4defe56..0000000 --- a/ui/base/ime/candidate_window_unittest.cc +++ /dev/null
@@ -1,262 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -// TODO(nona): Add more tests. - -#include "ui/base/ime/candidate_window.h" - -#include <string> - -#include "base/compiler_specific.h" -#include "base/logging.h" -#include "base/memory/scoped_ptr.h" -#include "base/strings/utf_string_conversions.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace ui { - -namespace { - -const size_t kSampleCandidateSize = 3; -const char* kSampleCandidate[] = { - "Sample Candidate 1", - "Sample Candidate 2", - "Sample Candidate 3", -}; -const char* kSampleDescriptionTitle[] = { - "Sample Description Title 1", - "Sample Description Title 2", - "Sample Description Title 3", -}; -const char* kSampleDescriptionBody[] = { - "Sample Description Body 1", - "Sample Description Body 2", - "Sample Description Body 3", -}; - -} - -TEST(CandidateWindow, IsEqualTest) { - CandidateWindow cw1; - CandidateWindow cw2; - - const base::string16 kSampleString1 = base::UTF8ToUTF16("Sample 1"); - const base::string16 kSampleString2 = base::UTF8ToUTF16("Sample 2"); - - EXPECT_TRUE(cw1.IsEqual(cw2)); - EXPECT_TRUE(cw2.IsEqual(cw1)); - - cw1.set_page_size(1); - cw2.set_page_size(2); - EXPECT_FALSE(cw1.IsEqual(cw2)); - EXPECT_FALSE(cw2.IsEqual(cw1)); - cw2.set_page_size(1); - - cw1.set_cursor_position(1); - cw2.set_cursor_position(2); - EXPECT_FALSE(cw1.IsEqual(cw2)); - EXPECT_FALSE(cw2.IsEqual(cw1)); - cw2.set_cursor_position(1); - - cw1.set_is_cursor_visible(true); - cw2.set_is_cursor_visible(false); - EXPECT_FALSE(cw1.IsEqual(cw2)); - EXPECT_FALSE(cw2.IsEqual(cw1)); - cw2.set_is_cursor_visible(true); - - cw1.set_orientation(CandidateWindow::HORIZONTAL); - cw2.set_orientation(CandidateWindow::VERTICAL); - EXPECT_FALSE(cw1.IsEqual(cw2)); - EXPECT_FALSE(cw2.IsEqual(cw1)); - cw2.set_orientation(CandidateWindow::HORIZONTAL); - - cw1.set_show_window_at_composition(true); - cw2.set_show_window_at_composition(false); - EXPECT_FALSE(cw1.IsEqual(cw2)); - EXPECT_FALSE(cw2.IsEqual(cw1)); - cw2.set_show_window_at_composition(true); - - // Check equality for candidates member variable. - CandidateWindow::Entry entry1; - CandidateWindow::Entry entry2; - - cw1.mutable_candidates()->push_back(entry1); - EXPECT_FALSE(cw1.IsEqual(cw2)); - EXPECT_FALSE(cw2.IsEqual(cw1)); - cw2.mutable_candidates()->push_back(entry2); - EXPECT_TRUE(cw1.IsEqual(cw2)); - EXPECT_TRUE(cw2.IsEqual(cw1)); - - entry1.value = kSampleString1; - entry2.value = kSampleString2; - cw1.mutable_candidates()->push_back(entry1); - cw2.mutable_candidates()->push_back(entry2); - EXPECT_FALSE(cw1.IsEqual(cw2)); - EXPECT_FALSE(cw2.IsEqual(cw1)); - cw1.mutable_candidates()->clear(); - cw2.mutable_candidates()->clear(); - - entry1.label = kSampleString1; - entry2.label = kSampleString2; - cw1.mutable_candidates()->push_back(entry1); - cw2.mutable_candidates()->push_back(entry2); - EXPECT_FALSE(cw1.IsEqual(cw2)); - EXPECT_FALSE(cw2.IsEqual(cw1)); - cw1.mutable_candidates()->clear(); - cw2.mutable_candidates()->clear(); - - entry1.annotation = kSampleString1; - entry2.annotation = kSampleString2; - cw1.mutable_candidates()->push_back(entry1); - cw2.mutable_candidates()->push_back(entry2); - EXPECT_FALSE(cw1.IsEqual(cw2)); - EXPECT_FALSE(cw2.IsEqual(cw1)); - cw1.mutable_candidates()->clear(); - cw2.mutable_candidates()->clear(); - - entry1.description_title = kSampleString1; - entry2.description_title = kSampleString2; - cw1.mutable_candidates()->push_back(entry1); - cw2.mutable_candidates()->push_back(entry2); - EXPECT_FALSE(cw1.IsEqual(cw2)); - EXPECT_FALSE(cw2.IsEqual(cw1)); - cw1.mutable_candidates()->clear(); - cw2.mutable_candidates()->clear(); - - entry1.description_body = kSampleString1; - entry2.description_body = kSampleString2; - cw1.mutable_candidates()->push_back(entry1); - cw2.mutable_candidates()->push_back(entry2); - EXPECT_FALSE(cw1.IsEqual(cw2)); - EXPECT_FALSE(cw2.IsEqual(cw1)); - cw1.mutable_candidates()->clear(); - cw2.mutable_candidates()->clear(); -} - -TEST(CandidateWindow, CopyFromTest) { - CandidateWindow cw1; - CandidateWindow cw2; - - const base::string16 kSampleString = base::UTF8ToUTF16("Sample"); - - cw1.set_page_size(1); - cw1.set_cursor_position(2); - cw1.set_is_cursor_visible(false); - cw1.set_orientation(CandidateWindow::HORIZONTAL); - cw1.set_show_window_at_composition(false); - - CandidateWindow::Entry entry; - entry.value = kSampleString; - entry.label = kSampleString; - entry.annotation = kSampleString; - entry.description_title = kSampleString; - entry.description_body = kSampleString; - cw1.mutable_candidates()->push_back(entry); - - cw2.CopyFrom(cw1); - EXPECT_TRUE(cw1.IsEqual(cw2)); -} - -TEST(CandidateWindow, GetInfolistEntries_DenseCase) { - CandidateWindow candidate_window; - candidate_window.set_page_size(10); - for (size_t i = 0; i < kSampleCandidateSize; ++i) { - CandidateWindow::Entry entry; - entry.value = base::UTF8ToUTF16(kSampleCandidate[i]); - entry.description_title = base::UTF8ToUTF16(kSampleDescriptionTitle[i]); - entry.description_body = base::UTF8ToUTF16(kSampleDescriptionBody[i]); - candidate_window.mutable_candidates()->push_back(entry); - } - candidate_window.set_cursor_position(1); - - std::vector<InfolistEntry> infolist_entries; - bool has_highlighted = false; - - candidate_window.GetInfolistEntries(&infolist_entries, &has_highlighted); - - EXPECT_EQ(kSampleCandidateSize, infolist_entries.size()); - EXPECT_TRUE(has_highlighted); - EXPECT_TRUE(infolist_entries[1].highlighted); -} - -TEST(CandidateWindow, GetInfolistEntries_SparseCase) { - CandidateWindow candidate_window; - candidate_window.set_page_size(10); - for (size_t i = 0; i < kSampleCandidateSize; ++i) { - CandidateWindow::Entry entry; - entry.value = base::UTF8ToUTF16(kSampleCandidate[i]); - candidate_window.mutable_candidates()->push_back(entry); - } - - std::vector<CandidateWindow::Entry>* candidates = - candidate_window.mutable_candidates(); - (*candidates)[2].description_title = - base::UTF8ToUTF16(kSampleDescriptionTitle[2]); - (*candidates)[2].description_body = - base::UTF8ToUTF16(kSampleDescriptionBody[2]); - - candidate_window.set_cursor_position(2); - - std::vector<InfolistEntry> infolist_entries; - bool has_highlighted = false; - - candidate_window.GetInfolistEntries(&infolist_entries, &has_highlighted); - - // Infolist entries skips empty descriptions, so expected entry size is 1. - EXPECT_EQ(1UL, infolist_entries.size()); - EXPECT_TRUE(has_highlighted); - EXPECT_TRUE(infolist_entries[0].highlighted); -} - -TEST(CandidateWindow, GetInfolistEntries_SparseNoSelectionCase) { - CandidateWindow candidate_window; - candidate_window.set_page_size(10); - - for (size_t i = 0; i < kSampleCandidateSize; ++i) { - CandidateWindow::Entry entry; - entry.value = base::UTF8ToUTF16(kSampleCandidate[i]); - candidate_window.mutable_candidates()->push_back(entry); - } - - std::vector<CandidateWindow::Entry>* candidates = - candidate_window.mutable_candidates(); - (*candidates)[2].description_title = - base::UTF8ToUTF16(kSampleDescriptionTitle[2]); - (*candidates)[2].description_body = - base::UTF8ToUTF16(kSampleDescriptionBody[2]); - - candidate_window.set_cursor_position(0); - - std::vector<InfolistEntry> infolist_entries; - bool has_highlighted; - - candidate_window.GetInfolistEntries(&infolist_entries, &has_highlighted); - - // Infolist entries skips empty descriptions, so expected entry size is 1 and - // no highlighted entries. - EXPECT_EQ(1UL, infolist_entries.size()); - EXPECT_FALSE(has_highlighted); - EXPECT_FALSE(infolist_entries[0].highlighted); -} - -TEST(CandidateWindow, GetInfolistEntries_NoInfolistCase) { - CandidateWindow candidate_window; - candidate_window.set_page_size(10); - - for (size_t i = 0; i < kSampleCandidateSize; ++i) { - CandidateWindow::Entry entry; - entry.value = base::UTF8ToUTF16(kSampleCandidate[i]); - candidate_window.mutable_candidates()->push_back(entry); - } - candidate_window.set_cursor_position(1); - - std::vector<InfolistEntry> infolist_entries; - bool has_highlighted = false; - - candidate_window.GetInfolistEntries(&infolist_entries, &has_highlighted); - - EXPECT_TRUE(infolist_entries.empty()); - EXPECT_FALSE(has_highlighted); -} - -} // namespace ui
diff --git a/ui/base/ime/chromeos/character_composer.cc b/ui/base/ime/chromeos/character_composer.cc deleted file mode 100644 index fe99fdd..0000000 --- a/ui/base/ime/chromeos/character_composer.cc +++ /dev/null
@@ -1,557 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/chromeos/character_composer.h" - -#include <algorithm> -#include <iterator> - -#include "base/strings/utf_string_conversions.h" -#include "base/third_party/icu/icu_utf.h" -// Note for Gtk removal: gdkkeysyms.h only contains a set of -// '#define GDK_KeyName 0xNNNN' macros and does not #include any Gtk headers. -#include "third_party/gtk+/gdk/gdkkeysyms.h" - -#include "ui/base/glib/glib_integers.h" -#include "ui/events/event.h" -#include "ui/events/keycodes/keyboard_codes.h" - -// Note for Gtk removal: gtkimcontextsimpleseqs.h does not #include any Gtk -// headers and only contains one big guint16 array |gtk_compose_seqs_compact| -// which defines the main compose table. The table has internal linkage. -// The order of header inclusion is out of order because -// gtkimcontextsimpleseqs.h depends on guint16, which is defined in -// "ui/base/glib/glib_integers.h". -#include "third_party/gtk+/gtk/gtkimcontextsimpleseqs.h" - -namespace { - -// A black list for not composing dead keys. Once the key combination is listed -// below, the dead key won't work even when this is listed in -// gtkimcontextsimpleseqs.h. This only supports two keyevent sequenses. -// TODO(nona): Remove this hack. -const struct BlackListedDeadKey { - uint32 first_key; // target first key event. - uint32 second_key; // target second key event. - uint32 output_char; // the character to be inserted if the filter is matched. - bool consume; // true if the original key event will be consumed. -} kBlackListedDeadKeys[] = { - { GDK_KEY_dead_acute, GDK_KEY_m, GDK_KEY_apostrophe, false }, - { GDK_KEY_dead_acute, GDK_KEY_s, GDK_KEY_apostrophe, false }, - { GDK_KEY_dead_acute, GDK_KEY_t, GDK_KEY_apostrophe, false }, - { GDK_KEY_dead_acute, GDK_KEY_v, GDK_KEY_apostrophe, false }, - { GDK_KEY_dead_acute, GDK_KEY_dead_acute, GDK_KEY_apostrophe, true }, -}; - -typedef std::vector<unsigned int> ComposeBufferType; - -// An iterator class to apply std::lower_bound for composition table. -class SequenceIterator - : public std::iterator<std::random_access_iterator_tag, const uint16*> { - public: - SequenceIterator() : ptr_(NULL), stride_(0) {} - SequenceIterator(const uint16* ptr, int stride) - : ptr_(ptr), stride_(stride) {} - - const uint16* ptr() const {return ptr_;} - int stride() const {return stride_;} - - SequenceIterator& operator++() { - ptr_ += stride_; - return *this; - } - SequenceIterator& operator+=(int n) { - ptr_ += stride_*n; - return *this; - } - - const uint16* operator*() const {return ptr_;} - - private: - const uint16* ptr_; - int stride_; -}; - -inline SequenceIterator operator+(const SequenceIterator& l, int r) { - return SequenceIterator(l) += r; -} - -inline int operator-(const SequenceIterator& l, const SequenceIterator& r) { - const int d = l.ptr() - r.ptr(); - DCHECK(l.stride() == r.stride() && l.stride() > 0 && d%l.stride() == 0); - return d/l.stride(); -} - -inline bool operator==(const SequenceIterator& l, const SequenceIterator& r) { - DCHECK(l.stride() == r.stride()); - return l.ptr() == r.ptr(); -} - -inline bool operator!=(const SequenceIterator& l, const SequenceIterator& r) { - return !(l == r); -} - -// A function to compare key value. -inline int CompareSequenceValue(unsigned int l, unsigned int r) { - return (l > r) ? 1 : ((l < r) ? -1 : 0); -} - -// A template to make |CompareFunc| work like operator<. -// |CompareFunc| is required to implement a member function, -// int operator()(const ComposeBufferType& l, const uint16* r) const. -template<typename CompareFunc> -struct ComparatorAdoptor { - bool operator()(const ComposeBufferType& l, const uint16* r) const { - return CompareFunc()(l, r) == -1; - } - bool operator()(const uint16* l, const ComposeBufferType& r) const { - return CompareFunc()(r, l) == 1; - } -}; - -class ComposeChecker { - public: - // This class does not take the ownership of |data|, |data| should be alive - // for the lifetime of the object. - // |data| is a pointer to the head of an array of - // length (|max_sequence_length| + 2)*|n_sequences|. - // Every (|max_sequence_length| + 2) elements of |data| represent an entry. - // First |max_sequence_length| elements of an entry is the sequecne which - // composes the character represented by the last two elements of the entry. - ComposeChecker(const uint16* data, int max_sequence_length, int n_sequences); - bool CheckSequence(const ComposeBufferType& sequence, - uint32* composed_character) const; - - private: - struct CompareSequence { - int operator()(const ComposeBufferType& l, const uint16* r) const; - }; - - // This class does not take the ownership of |data_|, - // the dtor does not delete |data_|. - const uint16* data_; - int max_sequence_length_; - int n_sequences_; - int row_stride_; - - DISALLOW_COPY_AND_ASSIGN(ComposeChecker); -}; - -ComposeChecker::ComposeChecker(const uint16* data, - int max_sequence_length, - int n_sequences) - : data_(data), - max_sequence_length_(max_sequence_length), - n_sequences_(n_sequences), - row_stride_(max_sequence_length + 2) { -} - -bool ComposeChecker::CheckSequence(const ComposeBufferType& sequence, - uint32* composed_character) const { - const int sequence_length = sequence.size(); - if (sequence_length > max_sequence_length_) - return false; - // Find sequence in the table. - const SequenceIterator begin(data_, row_stride_); - const SequenceIterator end = begin + n_sequences_; - const SequenceIterator found = std::lower_bound( - begin, end, sequence, ComparatorAdoptor<CompareSequence>()); - if (found == end || CompareSequence()(sequence, *found) != 0) - return false; - - if (sequence_length == max_sequence_length_ || - (*found)[sequence_length] == 0) { - // |found| is not partially matching. It's fully matching. - if (found + 1 == end || - CompareSequence()(sequence, *(found + 1)) != 0) { - // There is no composition longer than |found| which matches to - // |sequence|. - const uint32 value = ((*found)[max_sequence_length_] << 16) | - (*found)[max_sequence_length_ + 1]; - *composed_character = value; - } - } - return true; -} - -int ComposeChecker::CompareSequence::operator()(const ComposeBufferType& l, - const uint16* r) const { - for(size_t i = 0; i < l.size(); ++i) { - const int compare_result = CompareSequenceValue(l[i], r[i]); - if(compare_result) - return compare_result; - } - return 0; -} - - -class ComposeCheckerWithCompactTable { - public: - // This class does not take the ownership of |data|, |data| should be alive - // for the lifetime of the object. - // First |index_size|*|index_stride| elements of |data| are an index table. - // Every |index_stride| elements of an index table are an index entry. - // If you are checking with a sequence of length N beginning with character C, - // you have to find an index entry whose first element is C, then get the N-th - // element of the index entry as the index. - // The index is pointing the element of |data| where the composition table for - // sequences of length N beginning with C is placed. - - ComposeCheckerWithCompactTable(const uint16* data, - int max_sequence_length, - int index_size, - int index_stride); - bool CheckSequence(const ComposeBufferType& sequence, - uint32* composed_character) const; - - private: - struct CompareSequenceFront { - int operator()(const ComposeBufferType& l, const uint16* r) const; - }; - struct CompareSequenceSkipFront { - int operator()(const ComposeBufferType& l, const uint16* r) const; - }; - - // This class does not take the ownership of |data_|, - // the dtor does not delete |data_|. - const uint16* data_; - int max_sequence_length_; - int index_size_; - int index_stride_; -}; - -ComposeCheckerWithCompactTable::ComposeCheckerWithCompactTable( - const uint16* data, - int max_sequence_length, - int index_size, - int index_stride) - : data_(data), - max_sequence_length_(max_sequence_length), - index_size_(index_size), - index_stride_(index_stride) { -} - -bool ComposeCheckerWithCompactTable::CheckSequence( - const ComposeBufferType& sequence, - uint32* composed_character) const { - const int compose_length = sequence.size(); - if (compose_length > max_sequence_length_) - return false; - // Find corresponding index for the first keypress. - const SequenceIterator index_begin(data_, index_stride_); - const SequenceIterator index_end = index_begin + index_size_; - const SequenceIterator index = - std::lower_bound(index_begin, index_end, sequence, - ComparatorAdoptor<CompareSequenceFront>()); - if (index == index_end || CompareSequenceFront()(sequence, *index) != 0) - return false; - if (compose_length == 1) - return true; - // Check for composition sequences. - for (int length = compose_length - 1; length < max_sequence_length_; - ++length) { - const uint16* table = data_ + (*index)[length]; - const uint16* table_next = data_ + (*index)[length + 1]; - if (table_next > table) { - // There are composition sequences for this |length|. - const int row_stride = length + 1; - const int n_sequences = (table_next - table)/row_stride; - const SequenceIterator table_begin(table, row_stride); - const SequenceIterator table_end = table_begin + n_sequences; - const SequenceIterator found = - std::lower_bound(table_begin, table_end, sequence, - ComparatorAdoptor<CompareSequenceSkipFront>()); - if (found != table_end && - CompareSequenceSkipFront()(sequence, *found) == 0) { - if (length == compose_length - 1) // Exact match. - *composed_character = (*found)[length]; - return true; - } - } - } - return false; -} - -int ComposeCheckerWithCompactTable::CompareSequenceFront::operator()( - const ComposeBufferType& l, const uint16* r) const { - return CompareSequenceValue(l[0], r[0]); -} - -int ComposeCheckerWithCompactTable::CompareSequenceSkipFront::operator()( - const ComposeBufferType& l, const uint16* r) const { - for(size_t i = 1; i < l.size(); ++i) { - const int compare_result = CompareSequenceValue(l[i], r[i - 1]); - if(compare_result) - return compare_result; - } - return 0; -} - - -// Additional table. - -// The difference between this and the default input method is the handling -// of C+acute - this method produces C WITH CEDILLA rather than C WITH ACUTE. -// For languages that use CCedilla and not acute, this is the preferred mapping, -// and is particularly important for pt_BR, where the us-intl keyboard is -// used extensively. - -const uint16 cedilla_compose_seqs[] = { - // LATIN_CAPITAL_LETTER_C_WITH_CEDILLA - GDK_KEY_dead_acute, GDK_KEY_C, 0, 0, 0, 0x00C7, - // LATIN_SMALL_LETTER_C_WITH_CEDILLA - GDK_KEY_dead_acute, GDK_KEY_c, 0, 0, 0, 0x00E7, - // LATIN_CAPITAL_LETTER_C_WITH_CEDILLA - GDK_KEY_Multi_key, GDK_KEY_apostrophe, GDK_KEY_C, 0, 0, 0x00C7, - // LATIN_SMALL_LETTER_C_WITH_CEDILLA - GDK_KEY_Multi_key, GDK_KEY_apostrophe, GDK_KEY_c, 0, 0, 0x00E7, - // LATIN_CAPITAL_LETTER_C_WITH_CEDILLA - GDK_KEY_Multi_key, GDK_KEY_C, GDK_KEY_apostrophe, 0, 0, 0x00C7, - // LATIN_SMALL_LETTER_C_WITH_CEDILLA - GDK_KEY_Multi_key, GDK_KEY_c, GDK_KEY_apostrophe, 0, 0, 0x00E7, -}; - -bool KeypressShouldBeIgnored(unsigned int keyval) { - switch(keyval) { - case GDK_KEY_Shift_L: - case GDK_KEY_Shift_R: - case GDK_KEY_Control_L: - case GDK_KEY_Control_R: - case GDK_KEY_Caps_Lock: - case GDK_KEY_Shift_Lock: - case GDK_KEY_Meta_L: - case GDK_KEY_Meta_R: - case GDK_KEY_Alt_L: - case GDK_KEY_Alt_R: - case GDK_KEY_Super_L: - case GDK_KEY_Super_R: - case GDK_KEY_Hyper_L: - case GDK_KEY_Hyper_R: - case GDK_KEY_Mode_switch: - case GDK_KEY_ISO_Level3_Shift: - return true; - default: - return false; - } -} - -bool CheckCharacterComposeTable(const ComposeBufferType& sequence, - uint32* composed_character) { - // Check cedilla compose table. - const ComposeChecker kCedillaComposeChecker( - cedilla_compose_seqs, 4, arraysize(cedilla_compose_seqs)/(4 + 2)); - if (kCedillaComposeChecker.CheckSequence(sequence, composed_character)) - return true; - - // Check main compose table. - const ComposeCheckerWithCompactTable kMainComposeChecker( - gtk_compose_seqs_compact, 5, 24, 6); - if (kMainComposeChecker.CheckSequence(sequence, composed_character)) - return true; - - return false; -} - -// Converts |character| to UTF16 string. -// Returns false when |character| is not a valid character. -bool UTF32CharacterToUTF16(uint32 character, base::string16* output) { - output->clear(); - // Reject invalid character. (e.g. codepoint greater than 0x10ffff) - if (!CBU_IS_UNICODE_CHAR(character)) - return false; - if (character) { - output->resize(CBU16_LENGTH(character)); - size_t i = 0; - CBU16_APPEND_UNSAFE(&(*output)[0], i, character); - } - return true; -} - -// Returns an hexadecimal digit integer (0 to 15) corresponding to |keyval|. -// -1 is returned when |keyval| cannot be a hexadecimal digit. -int KeyvalToHexDigit(unsigned int keyval) { - if (GDK_KEY_0 <= keyval && keyval <= GDK_KEY_9) - return keyval - GDK_KEY_0; - if (GDK_KEY_a <= keyval && keyval <= GDK_KEY_f) - return keyval - GDK_KEY_a + 10; - if (GDK_KEY_A <= keyval && keyval <= GDK_KEY_F) - return keyval - GDK_KEY_A + 10; - return -1; // |keyval| cannot be a hexadecimal digit. -} - -// Returns an hexadecimal digit integer (0 to 15) corresponding to |keycode|. -// -1 is returned when |keycode| cannot be a hexadecimal digit. -int KeycodeToHexDigit(unsigned int keycode) { - if (ui::VKEY_0 <= keycode && keycode <= ui::VKEY_9) - return keycode - ui::VKEY_0; - if (ui::VKEY_A <= keycode && keycode <= ui::VKEY_F) - return keycode - ui::VKEY_A + 10; - return -1; // |keycode| cannot be a hexadecimal digit. -} - -} // namespace - -namespace ui { - -CharacterComposer::CharacterComposer() : composition_mode_(KEY_SEQUENCE_MODE) {} - -CharacterComposer::~CharacterComposer() {} - -void CharacterComposer::Reset() { - compose_buffer_.clear(); - composed_character_.clear(); - preedit_string_.clear(); - composition_mode_ = KEY_SEQUENCE_MODE; -} - -bool CharacterComposer::FilterKeyPress(const ui::KeyEvent& event) { - uint32 keyval = event.platform_keycode(); - if (!keyval || - (event.type() != ET_KEY_PRESSED && event.type() != ET_KEY_RELEASED)) - return false; - - return FilterKeyPressInternal(keyval, event.key_code(), event.flags()); -} - - -bool CharacterComposer::FilterKeyPressInternal(unsigned int keyval, - unsigned int keycode, - int flags) { - composed_character_.clear(); - preedit_string_.clear(); - - // We don't care about modifier key presses. - if(KeypressShouldBeIgnored(keyval)) - return false; - - // When the user presses Ctrl+Shift+U, maybe switch to HEX_MODE. - // We don't care about other modifiers like Alt. When CapsLock is down, we - // do nothing because what we receive is Ctrl+Shift+u (not U). - if (keyval == GDK_KEY_U && (flags & EF_SHIFT_DOWN) && - (flags & EF_CONTROL_DOWN)) { - if (composition_mode_ == KEY_SEQUENCE_MODE && compose_buffer_.empty()) { - // There is no ongoing composition. Let's switch to HEX_MODE. - composition_mode_ = HEX_MODE; - UpdatePreeditStringHexMode(); - return true; - } - } - - // Filter key press in an appropriate manner. - switch (composition_mode_) { - case KEY_SEQUENCE_MODE: - return FilterKeyPressSequenceMode(keyval, flags); - case HEX_MODE: - return FilterKeyPressHexMode(keyval, keycode, flags); - default: - NOTREACHED(); - return false; - } -} - -bool CharacterComposer::FilterKeyPressSequenceMode(unsigned int keyval, - int flags) { - DCHECK(composition_mode_ == KEY_SEQUENCE_MODE); - compose_buffer_.push_back(keyval); - - if (compose_buffer_.size() == 2U) { - for (size_t i = 0; i < arraysize(kBlackListedDeadKeys); ++i) { - if (compose_buffer_[0] == kBlackListedDeadKeys[i].first_key && - compose_buffer_[1] == kBlackListedDeadKeys[i].second_key ) { - Reset(); - composed_character_.push_back(kBlackListedDeadKeys[i].output_char); - return kBlackListedDeadKeys[i].consume; - } - } - } - - // Check compose table. - uint32 composed_character_utf32 = 0; - if (CheckCharacterComposeTable(compose_buffer_, &composed_character_utf32)) { - // Key press is recognized as a part of composition. - if (composed_character_utf32 != 0) { - // We get a composed character. - compose_buffer_.clear(); - UTF32CharacterToUTF16(composed_character_utf32, &composed_character_); - } - return true; - } - // Key press is not a part of composition. - compose_buffer_.pop_back(); // Remove the keypress added this time. - if (!compose_buffer_.empty()) { - compose_buffer_.clear(); - return true; - } - return false; -} - -bool CharacterComposer::FilterKeyPressHexMode(unsigned int keyval, - unsigned int keycode, - int flags) { - DCHECK(composition_mode_ == HEX_MODE); - const size_t kMaxHexSequenceLength = 8; - int hex_digit = KeyvalToHexDigit(keyval); - if (hex_digit < 0) { - // With 101 keyboard, control + shift + 3 produces '#', but a user may - // have intended to type '3'. So, if a hexadecimal character was not found, - // suppose a user is holding shift key (and possibly control key, too) and - // try a character with modifier keys removed. - hex_digit = KeycodeToHexDigit(keycode); - } - - if (keyval == GDK_KEY_Escape) { - // Cancel composition when ESC is pressed. - Reset(); - } else if (keyval == GDK_KEY_Return || keyval == GDK_KEY_KP_Enter || - keyval == GDK_KEY_ISO_Enter || - keyval == GDK_KEY_space || keyval == GDK_KEY_KP_Space) { - // Commit the composed character when Enter or space is pressed. - CommitHex(); - } else if (keyval == GDK_KEY_BackSpace) { - // Pop back the buffer when Backspace is pressed. - if (!compose_buffer_.empty()) { - compose_buffer_.pop_back(); - } else { - // If there is no character in |compose_buffer_|, cancel composition. - Reset(); - } - } else if (hex_digit >= 0 && - compose_buffer_.size() < kMaxHexSequenceLength) { - // Add the key to the buffer if it is a hex digit. - compose_buffer_.push_back(hex_digit); - } - - UpdatePreeditStringHexMode(); - - return true; -} - -void CharacterComposer::CommitHex() { - DCHECK(composition_mode_ == HEX_MODE); - uint32 composed_character_utf32 = 0; - for (size_t i = 0; i != compose_buffer_.size(); ++i) { - const uint32 digit = compose_buffer_[i]; - DCHECK(0 <= digit && digit < 16); - composed_character_utf32 <<= 4; - composed_character_utf32 |= digit; - } - Reset(); - UTF32CharacterToUTF16(composed_character_utf32, &composed_character_); -} - -void CharacterComposer::UpdatePreeditStringHexMode() { - if (composition_mode_ != HEX_MODE) { - preedit_string_.clear(); - return; - } - std::string preedit_string_ascii("u"); - for (size_t i = 0; i != compose_buffer_.size(); ++i) { - const int digit = compose_buffer_[i]; - DCHECK(0 <= digit && digit < 16); - preedit_string_ascii += digit <= 9 ? ('0' + digit) : ('a' + (digit - 10)); - } - preedit_string_ = base::ASCIIToUTF16(preedit_string_ascii); -} - -} // namespace ui
diff --git a/ui/base/ime/chromeos/character_composer.h b/ui/base/ime/chromeos/character_composer.h deleted file mode 100644 index 5d4267f..0000000 --- a/ui/base/ime/chromeos/character_composer.h +++ /dev/null
@@ -1,103 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_CHROMEOS_CHARACTER_COMPOSER_H_ -#define UI_BASE_IME_CHROMEOS_CHARACTER_COMPOSER_H_ - -#include <vector> - -#include "base/strings/string_util.h" -#include "ui/base/ui_base_export.h" - -namespace ui { -class KeyEvent; - -// A class to recognize compose and dead key sequence. -// Outputs composed character. -class UI_BASE_EXPORT CharacterComposer { - public: - CharacterComposer(); - ~CharacterComposer(); - - void Reset(); - - // Filters keypress. - // Returns true if the keypress is recognized as a part of composition - // sequence. - // Fabricated events which don't have the native event, are not supported. - bool FilterKeyPress(const ui::KeyEvent& event); - - // Returns a string consisting of composed character. - // Empty string is returned when there is no composition result. - const base::string16& composed_character() const { - return composed_character_; - } - - // Returns the preedit string. - const base::string16& preedit_string() const { return preedit_string_; } - - private: - friend class CharacterComposerTest; - - // An enum to describe composition mode. - enum CompositionMode { - // This is the initial state. - // Composite a character with dead-keys and compose-key. - KEY_SEQUENCE_MODE, - // Composite a character with a hexadecimal unicode sequence. - HEX_MODE, - }; - - // Filters keypress using IBus defined value. - // Returns true if the keypress is recognized as a part of composition - // sequence. - // |keyval| must be a GDK_KEY_* constant. - // |keycode| must be a X key code. - // |flags| must be a combination of ui::EF_* flags. - // - // composed_character() returns non empty string when there is a character - // composed after this method returns true. - // preedit_string() returns non empty string when there is a preedit string - // after this method returns true. - // Return values of preedit_string() is empty after this method returns false. - // composed_character() may have some characters which are consumed in this - // composing session. - // - // - // TODO(nona): Actually a X KeySym is passed to |keyval|, so we should use - // XK_* rather than GDK_KEY_*. - bool FilterKeyPressInternal(unsigned int keyval, unsigned int keycode, - int flags); - - // Filters keypress in key sequence mode. - bool FilterKeyPressSequenceMode(unsigned int keyval, int flags); - - // Filters keypress in hexadecimal mode. - bool FilterKeyPressHexMode(unsigned int keyval, unsigned int keycode, - int flags); - - // Commit a character composed from hexadecimal uncode sequence - void CommitHex(); - - // Updates preedit string in hexadecimal mode. - void UpdatePreeditStringHexMode(); - - // Remembers keypresses previously filtered. - std::vector<unsigned int> compose_buffer_; - - // A string representing the composed character. - base::string16 composed_character_; - - // Preedit string. - base::string16 preedit_string_; - - // Composition mode which this instance is in. - CompositionMode composition_mode_; - - DISALLOW_COPY_AND_ASSIGN(CharacterComposer); -}; - -} // namespace ui - -#endif // UI_BASE_IME_CHROMEOS_CHARACTER_COMPOSER_H_
diff --git a/ui/base/ime/chromeos/character_composer_unittest.cc b/ui/base/ime/chromeos/character_composer_unittest.cc deleted file mode 100644 index 208b51f..0000000 --- a/ui/base/ime/chromeos/character_composer_unittest.cc +++ /dev/null
@@ -1,542 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/chromeos/character_composer.h" - -#include "base/strings/utf_string_conversions.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "third_party/gtk+/gdk/gdkkeysyms.h" -#include "ui/base/glib/glib_integers.h" -#include "ui/events/event_constants.h" -#include "ui/events/keycodes/keyboard_codes.h" - -using base::ASCIIToUTF16; - -namespace ui { - -class CharacterComposerTest : public testing::Test { - protected: - bool FilterKeyPress(CharacterComposer* character_composer, - uint key, - uint keycode, - int flags) { - return character_composer->FilterKeyPressInternal(key, keycode, flags); - } - - // Expects key is not filtered and no character is composed. - void ExpectKeyNotFilteredWithKeyCode(CharacterComposer* character_composer, - uint key, - uint keycode, - int flags) { - EXPECT_FALSE(character_composer->FilterKeyPressInternal(key, keycode, - flags)); - EXPECT_TRUE(character_composer->composed_character().empty()); - } - - // Expects key is filtered and no character is composed. - void ExpectKeyFilteredWithKeycode(CharacterComposer* character_composer, - uint key, - uint keycode, - int flags) { - EXPECT_TRUE(character_composer->FilterKeyPressInternal(key, keycode, - flags)); - EXPECT_TRUE(character_composer->composed_character().empty()); - } - - // Expects key is not filtered and no character is composed. - void ExpectKeyNotFiltered(CharacterComposer* character_composer, - uint key, - int flags) { - ExpectKeyNotFilteredWithKeyCode(character_composer, key, 0, flags); - } - - // Expects key is filtered and no character is composed. - void ExpectKeyFiltered(CharacterComposer* character_composer, - uint key, - int flags) { - ExpectKeyFilteredWithKeycode(character_composer, key, 0, flags); - } - - // Expects |expected_character| is composed after sequence [key1, key2]. - void ExpectCharacterComposed(CharacterComposer* character_composer, - uint key1, - uint key2, - int flags, - const base::string16& expected_character) { - ExpectKeyFiltered(character_composer, key1, flags); - EXPECT_TRUE(character_composer->FilterKeyPressInternal(key2, 0, flags)); - EXPECT_EQ(expected_character, character_composer->composed_character()); - } - - // Expects |expected_character| is composed after sequence [key1, key2, key3]. - void ExpectCharacterComposed(CharacterComposer* character_composer, - uint key1, - uint key2, - uint key3, - int flags, - const base::string16& expected_character) { - ExpectKeyFiltered(character_composer, key1, flags); - ExpectCharacterComposed(character_composer, key2, key3, flags, - expected_character); - } - - // Expects |expected_character| is composed after sequence [key1, key2, key3, - // key 4]. - void ExpectCharacterComposed(CharacterComposer* character_composer, - uint key1, - uint key2, - uint key3, - uint key4, - int flags, - const base::string16& expected_character) { - ExpectKeyFiltered(character_composer, key1, flags); - ExpectCharacterComposed(character_composer, key2, key3, key4, flags, - expected_character); - } - - // Expects |expected_character| is composed after sequence [key1, key2, key3, - // key 4, key5]. - void ExpectCharacterComposed(CharacterComposer* character_composer, - uint key1, - uint key2, - uint key3, - uint key4, - uint key5, - int flags, - const base::string16& expected_character) { - ExpectKeyFiltered(character_composer, key1, flags); - ExpectCharacterComposed(character_composer, key2, key3, key4, key5, flags, - expected_character); - } - - // Expects |expected_character| is composed after sequence [key1, key2, key3, - // key 4, key5, key6]. - void ExpectCharacterComposed(CharacterComposer* character_composer, - uint key1, - uint key2, - uint key3, - uint key4, - uint key5, - uint key6, - int flags, - const base::string16& expected_character) { - ExpectKeyFiltered(character_composer, key1, flags); - ExpectCharacterComposed(character_composer, key2, key3, key4, key5, key6, - flags, expected_character); - } - - // Expects |expected_character| is composed after sequence [{key1, keycode1}]. - void ExpectCharacterComposedWithKeyCode( - CharacterComposer* character_composer, - uint key1, uint keycode1, - int flags, - const base::string16& expected_character) { - EXPECT_TRUE(character_composer->FilterKeyPressInternal(key1, keycode1, - flags)); - EXPECT_EQ(expected_character, character_composer->composed_character()); - } -}; - -TEST_F(CharacterComposerTest, InitialState) { - CharacterComposer character_composer; - EXPECT_TRUE(character_composer.composed_character().empty()); -} - -TEST_F(CharacterComposerTest, NormalKeyIsNotFiltered) { - CharacterComposer character_composer; - ExpectKeyNotFiltered(&character_composer, GDK_KEY_B, 0); - ExpectKeyNotFiltered(&character_composer, GDK_KEY_Z, 0); - ExpectKeyNotFiltered(&character_composer, GDK_KEY_c, 0); - ExpectKeyNotFiltered(&character_composer, GDK_KEY_m, 0); - ExpectKeyNotFiltered(&character_composer, GDK_KEY_0, 0); - ExpectKeyNotFiltered(&character_composer, GDK_KEY_1, 0); - ExpectKeyNotFiltered(&character_composer, GDK_KEY_8, 0); -} - -TEST_F(CharacterComposerTest, PartiallyMatchingSequence) { - CharacterComposer character_composer; - - // Composition with sequence ['dead acute', '1'] will fail. - ExpectKeyFiltered(&character_composer, GDK_KEY_dead_acute, 0); - ExpectKeyFiltered(&character_composer, GDK_KEY_1, 0); - - // Composition with sequence ['dead acute', 'dead circumflex', '1'] will fail. - ExpectKeyFiltered(&character_composer, GDK_KEY_dead_acute, 0); - ExpectKeyFiltered(&character_composer, GDK_KEY_dead_circumflex, 0); - ExpectKeyFiltered(&character_composer, GDK_KEY_1, 0); -} - -TEST_F(CharacterComposerTest, FullyMatchingSequences) { - CharacterComposer character_composer; - // LATIN SMALL LETTER A WITH ACUTE - ExpectCharacterComposed(&character_composer, GDK_KEY_dead_acute, GDK_KEY_a, 0, - base::string16(1, 0x00E1)); - // LATIN CAPITAL LETTER A WITH ACUTE - ExpectCharacterComposed(&character_composer, GDK_KEY_dead_acute, GDK_KEY_A, 0, - base::string16(1, 0x00C1)); - // GRAVE ACCENT - ExpectCharacterComposed(&character_composer, GDK_KEY_dead_grave, - GDK_KEY_dead_grave, 0, base::string16(1, 0x0060)); - // LATIN SMALL LETTER A WITH CIRCUMFLEX AND ACUTE - ExpectCharacterComposed(&character_composer, GDK_KEY_dead_acute, - GDK_KEY_dead_circumflex, GDK_KEY_a, 0, - base::string16(1, 0x1EA5)); - // LATIN CAPITAL LETTER U WITH HORN AND GRAVE - ExpectCharacterComposed(&character_composer, GDK_KEY_dead_grave, - GDK_KEY_dead_horn, GDK_KEY_U, 0, - base::string16(1, 0x1EEA)); - // LATIN CAPITAL LETTER C WITH CEDILLA - ExpectCharacterComposed(&character_composer, GDK_KEY_dead_acute, GDK_KEY_C, 0, - base::string16(1, 0x00C7)); - // LATIN SMALL LETTER C WITH CEDILLA - ExpectCharacterComposed(&character_composer, GDK_KEY_dead_acute, GDK_KEY_c, 0, - base::string16(1, 0x00E7)); -} - -TEST_F(CharacterComposerTest, FullyMatchingSequencesAfterMatchingFailure) { - CharacterComposer character_composer; - // Composition with sequence ['dead acute', 'dead circumflex', '1'] will fail. - ExpectKeyFiltered(&character_composer, GDK_KEY_dead_acute, 0); - ExpectKeyFiltered(&character_composer, GDK_KEY_dead_circumflex, 0); - ExpectKeyFiltered(&character_composer, GDK_KEY_1, 0); - // LATIN SMALL LETTER A WITH CIRCUMFLEX AND ACUTE - ExpectCharacterComposed(&character_composer, GDK_KEY_dead_acute, - GDK_KEY_dead_circumflex, GDK_KEY_a, 0, - base::string16(1, 0x1EA5)); -} - -TEST_F(CharacterComposerTest, ComposedCharacterIsClearedAfterReset) { - CharacterComposer character_composer; - ExpectCharacterComposed(&character_composer, GDK_KEY_dead_acute, GDK_KEY_a, 0, - base::string16(1, 0x00E1)); - character_composer.Reset(); - EXPECT_TRUE(character_composer.composed_character().empty()); -} - -TEST_F(CharacterComposerTest, CompositionStateIsClearedAfterReset) { - CharacterComposer character_composer; - // Even though sequence ['dead acute', 'a'] will compose 'a with acute', - // no character is composed here because of reset. - ExpectKeyFiltered(&character_composer, GDK_KEY_dead_acute, 0); - character_composer.Reset(); - ExpectKeyNotFiltered(&character_composer, GDK_KEY_a, 0); -} - -TEST_F(CharacterComposerTest, KeySequenceCompositionPreedit) { - CharacterComposer character_composer; - // LATIN SMALL LETTER A WITH ACUTE - // preedit_string() is always empty in key sequence composition mode. - ExpectKeyFiltered(&character_composer, GDK_KEY_dead_acute, 0); - EXPECT_TRUE(character_composer.preedit_string().empty()); - EXPECT_TRUE(FilterKeyPress(&character_composer, GDK_KEY_a, 0, 0)); - EXPECT_EQ(base::string16(1, 0x00E1), character_composer.composed_character()); - EXPECT_TRUE(character_composer.preedit_string().empty()); -} - -// ComposeCheckerWithCompactTable in character_composer.cc is depending on the -// assumption that the data in gtkimcontextsimpleseqs.h is correctly ordered. -TEST_F(CharacterComposerTest, MainTableIsCorrectlyOrdered) { - // This file is included here intentionally, instead of the top of the file, - // because including this file at the top of the file will define a - // global constant and contaminate the global namespace. -#include "third_party/gtk+/gtk/gtkimcontextsimpleseqs.h" - const int index_size = 26; - const int index_stride = 6; - - // Verify that the index is correctly ordered - for (int i = 1; i < index_size; ++i) { - const int index_key_prev = gtk_compose_seqs_compact[(i - 1)*index_stride]; - const int index_key = gtk_compose_seqs_compact[i*index_stride]; - EXPECT_TRUE(index_key > index_key_prev); - } - - // Verify that the sequenes are correctly ordered - struct { - int operator()(const uint16* l, const uint16* r, int length) const{ - for (int i = 0; i < length; ++i) { - if (l[i] > r[i]) - return 1; - if (l[i] < r[i]) - return -1; - } - return 0; - } - } compare_sequence; - - for (int i = 0; i < index_size; ++i) { - for (int length = 1; length < index_stride - 1; ++length) { - const int index_begin = gtk_compose_seqs_compact[i*index_stride + length]; - const int index_end = - gtk_compose_seqs_compact[i*index_stride + length + 1]; - const int stride = length + 1; - for (int index = index_begin + stride; index < index_end; - index += stride) { - const uint16* sequence = >k_compose_seqs_compact[index]; - const uint16* sequence_prev = sequence - stride; - EXPECT_EQ(1, compare_sequence(sequence, sequence_prev, length)); - } - } - } -} - -TEST_F(CharacterComposerTest, HexadecimalComposition) { - CharacterComposer character_composer; - // HIRAGANA LETTER A (U+3042) - ExpectKeyFiltered(&character_composer, GDK_KEY_U, - EF_SHIFT_DOWN | EF_CONTROL_DOWN); - ExpectCharacterComposed(&character_composer, GDK_KEY_3, GDK_KEY_0, GDK_KEY_4, - GDK_KEY_2, GDK_KEY_space, 0, - base::string16(1, 0x3042)); - // MUSICAL KEYBOARD (U+1F3B9) - const base::char16 kMusicalKeyboard[] = {0xd83c, 0xdfb9}; - ExpectKeyFiltered(&character_composer, GDK_KEY_U, - EF_SHIFT_DOWN | EF_CONTROL_DOWN); - ExpectCharacterComposed(&character_composer, GDK_KEY_1, GDK_KEY_f, GDK_KEY_3, - GDK_KEY_b, GDK_KEY_9, GDK_KEY_Return, 0, - base::string16(kMusicalKeyboard, - kMusicalKeyboard + - arraysize(kMusicalKeyboard))); -} - -TEST_F(CharacterComposerTest, HexadecimalCompositionPreedit) { - CharacterComposer character_composer; - // HIRAGANA LETTER A (U+3042) - ExpectKeyFiltered(&character_composer, GDK_KEY_U, - EF_SHIFT_DOWN | EF_CONTROL_DOWN); - EXPECT_EQ(ASCIIToUTF16("u"), character_composer.preedit_string()); - ExpectKeyFiltered(&character_composer, GDK_KEY_3, 0); - EXPECT_EQ(ASCIIToUTF16("u3"), character_composer.preedit_string()); - ExpectKeyFiltered(&character_composer, GDK_KEY_0, 0); - EXPECT_EQ(ASCIIToUTF16("u30"), character_composer.preedit_string()); - ExpectKeyFiltered(&character_composer, GDK_KEY_4, 0); - EXPECT_EQ(ASCIIToUTF16("u304"), character_composer.preedit_string()); - ExpectKeyFiltered(&character_composer, GDK_KEY_a, 0); - EXPECT_EQ(ASCIIToUTF16("u304a"), character_composer.preedit_string()); - ExpectKeyFiltered(&character_composer, GDK_KEY_BackSpace, 0); - EXPECT_EQ(ASCIIToUTF16("u304"), character_composer.preedit_string()); - ExpectCharacterComposed(&character_composer, GDK_KEY_2, GDK_KEY_Return, 0, - base::string16(1, 0x3042)); - EXPECT_EQ(ASCIIToUTF16(""), character_composer.preedit_string()); - - // Sequence with an ignored character ('x') and Escape. - ExpectKeyFiltered(&character_composer, GDK_KEY_U, - EF_SHIFT_DOWN | EF_CONTROL_DOWN); - EXPECT_EQ(ASCIIToUTF16("u"), character_composer.preedit_string()); - ExpectKeyFiltered(&character_composer, GDK_KEY_3, 0); - EXPECT_EQ(ASCIIToUTF16("u3"), character_composer.preedit_string()); - ExpectKeyFiltered(&character_composer, GDK_KEY_0, 0); - EXPECT_EQ(ASCIIToUTF16("u30"), character_composer.preedit_string()); - ExpectKeyFiltered(&character_composer, GDK_KEY_x, 0); - EXPECT_EQ(ASCIIToUTF16("u30"), character_composer.preedit_string()); - ExpectKeyFiltered(&character_composer, GDK_KEY_4, 0); - EXPECT_EQ(ASCIIToUTF16("u304"), character_composer.preedit_string()); - ExpectKeyFiltered(&character_composer, GDK_KEY_2, 0); - EXPECT_EQ(ASCIIToUTF16("u3042"), character_composer.preedit_string()); - ExpectKeyFiltered(&character_composer, GDK_KEY_Escape, 0); - EXPECT_EQ(ASCIIToUTF16(""), character_composer.preedit_string()); -} - -TEST_F(CharacterComposerTest, HexadecimalCompositionWithNonHexKey) { - CharacterComposer character_composer; - - // Sequence [Ctrl+Shift+U, x, space] does not compose a character. - ExpectKeyFiltered(&character_composer, GDK_KEY_U, - EF_SHIFT_DOWN | EF_CONTROL_DOWN); - ExpectKeyFiltered(&character_composer, GDK_KEY_x, 0); - ExpectKeyFiltered(&character_composer, GDK_KEY_space, 0); - EXPECT_TRUE(character_composer.composed_character().empty()); - - // HIRAGANA LETTER A (U+3042) with a sequence [3, 0, x, 4, 2]. - ExpectKeyFiltered(&character_composer, GDK_KEY_U, - EF_SHIFT_DOWN | EF_CONTROL_DOWN); - ExpectCharacterComposed(&character_composer, GDK_KEY_3, GDK_KEY_0, GDK_KEY_x, - GDK_KEY_4, GDK_KEY_2, GDK_KEY_space, 0, - base::string16(1, 0x3042)); -} - -TEST_F(CharacterComposerTest, HexadecimalCompositionWithAdditionalModifiers) { - CharacterComposer character_composer; - - // Ctrl+Shift+Alt+U - // HIRAGANA LETTER A (U+3042) - ExpectKeyFiltered(&character_composer, GDK_KEY_U, - EF_SHIFT_DOWN | EF_CONTROL_DOWN | EF_ALT_DOWN); - ExpectCharacterComposed(&character_composer, GDK_KEY_3, GDK_KEY_0, GDK_KEY_4, - GDK_KEY_2, GDK_KEY_space, 0, - base::string16(1, 0x3042)); - - // Ctrl+Shift+u (CapsLock enabled) - ExpectKeyNotFiltered(&character_composer, GDK_KEY_u, - EF_SHIFT_DOWN | EF_CONTROL_DOWN | EF_CAPS_LOCK_DOWN); -} - -TEST_F(CharacterComposerTest, CancelHexadecimalComposition) { - CharacterComposer character_composer; - // Cancel composition with ESC. - ExpectKeyFiltered(&character_composer, GDK_KEY_U, - EF_SHIFT_DOWN | EF_CONTROL_DOWN); - ExpectKeyFiltered(&character_composer, GDK_KEY_1, 0); - ExpectKeyFiltered(&character_composer, GDK_KEY_Escape, 0); - - // Now we can start composition again since the last composition was - // cancelled. - // HIRAGANA LETTER A (U+3042) - ExpectKeyFiltered(&character_composer, GDK_KEY_U, - EF_SHIFT_DOWN | EF_CONTROL_DOWN); - ExpectCharacterComposed(&character_composer, GDK_KEY_3, GDK_KEY_0, GDK_KEY_4, - GDK_KEY_2, GDK_KEY_space, 0, - base::string16(1, 0x3042)); -} - -TEST_F(CharacterComposerTest, HexadecimalCompositionWithBackspace) { - CharacterComposer character_composer; - // HIRAGANA LETTER A (U+3042) - ExpectKeyFiltered(&character_composer, GDK_KEY_U, - EF_SHIFT_DOWN | EF_CONTROL_DOWN); - ExpectKeyFiltered(&character_composer, GDK_KEY_3, 0); - ExpectKeyFiltered(&character_composer, GDK_KEY_0, 0); - ExpectKeyFiltered(&character_composer, GDK_KEY_f, 0); - ExpectKeyFiltered(&character_composer, GDK_KEY_BackSpace, 0); - ExpectCharacterComposed(&character_composer, GDK_KEY_4, GDK_KEY_2, - GDK_KEY_space, 0, base::string16(1, 0x3042)); -} - -TEST_F(CharacterComposerTest, CancelHexadecimalCompositionWithBackspace) { - CharacterComposer character_composer; - - // Backspace just after Ctrl+Shift+U. - ExpectKeyFiltered(&character_composer, GDK_KEY_U, - EF_SHIFT_DOWN | EF_CONTROL_DOWN); - ExpectKeyFiltered(&character_composer, GDK_KEY_BackSpace, 0); - ExpectKeyNotFiltered(&character_composer, GDK_KEY_3, 0); - - // Backspace twice after Ctrl+Shift+U and 3. - ExpectKeyFiltered(&character_composer, GDK_KEY_U, - EF_SHIFT_DOWN | EF_CONTROL_DOWN); - ExpectKeyFiltered(&character_composer, GDK_KEY_3, 0); - ExpectKeyFiltered(&character_composer, GDK_KEY_BackSpace, 0); - ExpectKeyFiltered(&character_composer, GDK_KEY_BackSpace, 0); - ExpectKeyNotFiltered(&character_composer, GDK_KEY_3, 0); -} - -TEST_F(CharacterComposerTest, HexadecimalCompositionPreeditWithModifierPressed) -{ - // This test case supposes X Window System uses 101 keyboard layout. - CharacterComposer character_composer; - const int control_shift = EF_CONTROL_DOWN | EF_SHIFT_DOWN; - // HIRAGANA LETTER A (U+3042) - ExpectKeyFilteredWithKeycode(&character_composer, - GDK_KEY_U, ui::VKEY_U, control_shift); - EXPECT_EQ(ASCIIToUTF16("u"), character_composer.preedit_string()); - ExpectKeyFilteredWithKeycode(&character_composer, - GDK_KEY_numbersign, ui::VKEY_3, control_shift); - EXPECT_EQ(ASCIIToUTF16("u3"), character_composer.preedit_string()); - ExpectKeyFilteredWithKeycode(&character_composer, - GDK_KEY_parenright, ui::VKEY_0, control_shift); - EXPECT_EQ(ASCIIToUTF16("u30"), character_composer.preedit_string()); - ExpectKeyFilteredWithKeycode(&character_composer, - GDK_KEY_dollar, ui::VKEY_4, control_shift); - EXPECT_EQ(ASCIIToUTF16("u304"), character_composer.preedit_string()); - ExpectKeyFilteredWithKeycode(&character_composer, - GDK_KEY_A, ui::VKEY_A, control_shift); - EXPECT_EQ(ASCIIToUTF16("u304a"), character_composer.preedit_string()); - ExpectKeyFilteredWithKeycode(&character_composer, - GDK_KEY_BackSpace, ui::VKEY_BACK, control_shift); - EXPECT_EQ(ASCIIToUTF16("u304"), character_composer.preedit_string()); - ExpectKeyFilteredWithKeycode(&character_composer, - GDK_KEY_at, ui::VKEY_2, control_shift); - EXPECT_EQ(ASCIIToUTF16("u3042"), character_composer.preedit_string()); - ExpectCharacterComposedWithKeyCode(&character_composer, - GDK_KEY_Return, ui::VKEY_RETURN, - control_shift, - base::string16(1, 0x3042)); - EXPECT_EQ(ASCIIToUTF16(""), character_composer.preedit_string()); - - // Sequence with an ignored character (control + shift + 'x') and Escape. - ExpectKeyFilteredWithKeycode(&character_composer, - GDK_KEY_U, ui::VKEY_U, control_shift); - EXPECT_EQ(ASCIIToUTF16("u"), character_composer.preedit_string()); - ExpectKeyFilteredWithKeycode(&character_composer, - GDK_KEY_numbersign, ui::VKEY_3, control_shift); - EXPECT_EQ(ASCIIToUTF16("u3"), character_composer.preedit_string()); - ExpectKeyFilteredWithKeycode(&character_composer, - GDK_KEY_parenright, ui::VKEY_0, control_shift); - EXPECT_EQ(ASCIIToUTF16("u30"), character_composer.preedit_string()); - ExpectKeyFilteredWithKeycode(&character_composer, - GDK_KEY_X, ui::VKEY_X, control_shift); - EXPECT_EQ(ASCIIToUTF16("u30"), character_composer.preedit_string()); - ExpectKeyFilteredWithKeycode(&character_composer, - GDK_KEY_dollar, ui::VKEY_4, control_shift); - EXPECT_EQ(ASCIIToUTF16("u304"), character_composer.preedit_string()); - ExpectKeyFilteredWithKeycode(&character_composer, - GDK_KEY_at, ui::VKEY_2, control_shift); - EXPECT_EQ(ASCIIToUTF16("u3042"), character_composer.preedit_string()); - ExpectKeyFilteredWithKeycode(&character_composer, - GDK_KEY_Escape, ui::VKEY_ESCAPE, control_shift); - EXPECT_EQ(ASCIIToUTF16(""), character_composer.preedit_string()); -} - -TEST_F(CharacterComposerTest, InvalidHexadecimalSequence) { - CharacterComposer character_composer; - // U+FFFFFFFF - ExpectKeyFiltered(&character_composer, GDK_KEY_U, - EF_SHIFT_DOWN | EF_CONTROL_DOWN); - for (int i = 0; i < 8; ++i) - ExpectKeyFiltered(&character_composer, GDK_KEY_f, 0); - ExpectKeyFiltered(&character_composer, GDK_KEY_space, 0); - - // U+0000 (Actually, this is a valid unicode character, but we don't - // compose a string with a character '\0') - ExpectKeyFiltered(&character_composer, GDK_KEY_U, - EF_SHIFT_DOWN | EF_CONTROL_DOWN); - for (int i = 0; i < 4; ++i) - ExpectKeyFiltered(&character_composer, GDK_KEY_0, 0); - ExpectKeyFiltered(&character_composer, GDK_KEY_space, 0); - - // U+10FFFF - ExpectKeyFiltered(&character_composer, GDK_KEY_U, - EF_SHIFT_DOWN | EF_CONTROL_DOWN); - ExpectKeyFiltered(&character_composer, GDK_KEY_1, 0); - ExpectKeyFiltered(&character_composer, GDK_KEY_0, 0); - for (int i = 0; i < 4; ++i) - ExpectKeyFiltered(&character_composer, GDK_KEY_f, 0); - ExpectKeyFiltered(&character_composer, GDK_KEY_space, 0); - - // U+110000 - ExpectKeyFiltered(&character_composer, GDK_KEY_U, - EF_SHIFT_DOWN | EF_CONTROL_DOWN); - ExpectKeyFiltered(&character_composer, GDK_KEY_1, 0); - ExpectKeyFiltered(&character_composer, GDK_KEY_1, 0); - for (int i = 0; i < 4; ++i) - ExpectKeyFiltered(&character_composer, GDK_KEY_0, 0); - ExpectKeyFiltered(&character_composer, GDK_KEY_space, 0); -} - -TEST_F(CharacterComposerTest, HexadecimalSequenceAndDeadKey) { - CharacterComposer character_composer; - // LATIN SMALL LETTER A WITH ACUTE - ExpectCharacterComposed(&character_composer, GDK_KEY_dead_acute, GDK_KEY_a, 0, - base::string16(1, 0x00E1)); - // HIRAGANA LETTER A (U+3042) with dead_acute ignored. - ExpectKeyFiltered(&character_composer, GDK_KEY_U, - EF_SHIFT_DOWN | EF_CONTROL_DOWN); - ExpectCharacterComposed(&character_composer, GDK_KEY_3, GDK_KEY_0, - GDK_KEY_dead_acute, GDK_KEY_4, GDK_KEY_2, - GDK_KEY_space, 0, base::string16(1, 0x3042)); - // LATIN CAPITAL LETTER U WITH ACUTE while 'U' is pressed with Ctrl+Shift. - ExpectKeyFiltered(&character_composer, GDK_KEY_dead_acute, 0); - EXPECT_TRUE(FilterKeyPress(&character_composer, GDK_KEY_U, 0, - EF_SHIFT_DOWN | EF_CONTROL_DOWN)); - EXPECT_EQ(base::string16(1, 0x00DA), character_composer.composed_character()); -} - -TEST_F(CharacterComposerTest, BlacklistedKeyeventsTest) { - CharacterComposer character_composer; - EXPECT_TRUE(FilterKeyPress(&character_composer, GDK_KEY_dead_acute, 0, 0)); - EXPECT_FALSE(FilterKeyPress(&character_composer, GDK_KEY_s, 0, 0)); - ASSERT_EQ(1U, character_composer.composed_character().size()); - EXPECT_EQ(GDK_KEY_apostrophe, character_composer.composed_character().at(0)); -} - -} // namespace ui
diff --git a/ui/base/ime/chromeos/ime_bridge.cc b/ui/base/ime/chromeos/ime_bridge.cc deleted file mode 100644 index 98f997e..0000000 --- a/ui/base/ime/chromeos/ime_bridge.cc +++ /dev/null
@@ -1,107 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/chromeos/ime_bridge.h" - -#include <map> -#include "base/logging.h" -#include "base/memory/singleton.h" - -namespace chromeos { - -static IMEBridge* g_ime_bridge = NULL; - -// An implementation of IMEBridge. -class IMEBridgeImpl : public IMEBridge { - public: - IMEBridgeImpl() - : input_context_handler_(NULL), - engine_handler_(NULL), - candidate_window_handler_(NULL), - current_text_input_(ui::TEXT_INPUT_TYPE_NONE) { - } - - virtual ~IMEBridgeImpl() { - } - - // IMEBridge override. - virtual IMEInputContextHandlerInterface* - GetInputContextHandler() const override { - return input_context_handler_; - } - - // IMEBridge override. - virtual void SetInputContextHandler( - IMEInputContextHandlerInterface* handler) override { - input_context_handler_ = handler; - } - - // IMEBridge override. - virtual void SetCurrentEngineHandler( - IMEEngineHandlerInterface* handler) override { - engine_handler_ = handler; - } - - // IMEBridge override. - virtual IMEEngineHandlerInterface* GetCurrentEngineHandler() const override { - return engine_handler_; - } - - // IMEBridge override. - virtual IMECandidateWindowHandlerInterface* GetCandidateWindowHandler() const - override { - return candidate_window_handler_; - } - - // IMEBridge override. - virtual void SetCandidateWindowHandler( - IMECandidateWindowHandlerInterface* handler) override { - candidate_window_handler_ = handler; - } - - // IMEBridge override. - virtual void SetCurrentTextInputType(ui::TextInputType input_type) override { - current_text_input_ = input_type; - } - - // IMEBridge override. - virtual ui::TextInputType GetCurrentTextInputType() const override { - return current_text_input_; - } - - private: - IMEInputContextHandlerInterface* input_context_handler_; - IMEEngineHandlerInterface* engine_handler_; - IMECandidateWindowHandlerInterface* candidate_window_handler_; - ui::TextInputType current_text_input_; - - DISALLOW_COPY_AND_ASSIGN(IMEBridgeImpl); -}; - -/////////////////////////////////////////////////////////////////////////////// -// IMEBridge -IMEBridge::IMEBridge() { -} - -IMEBridge::~IMEBridge() { -} - -// static. -void IMEBridge::Initialize() { - if (!g_ime_bridge) - g_ime_bridge = new IMEBridgeImpl(); -} - -// static. -void IMEBridge::Shutdown() { - delete g_ime_bridge; - g_ime_bridge = NULL; -} - -// static. -IMEBridge* IMEBridge::Get() { - return g_ime_bridge; -} - -} // namespace chromeos
diff --git a/ui/base/ime/chromeos/ime_bridge.h b/ui/base/ime/chromeos/ime_bridge.h deleted file mode 100644 index a4b5fef..0000000 --- a/ui/base/ime/chromeos/ime_bridge.h +++ /dev/null
@@ -1,191 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_CHROMEOS_IME_BRIDGE_H_ -#define UI_BASE_IME_CHROMEOS_IME_BRIDGE_H_ - -#include <string> -#include "base/basictypes.h" -#include "base/callback.h" -#include "base/strings/string16.h" -#include "ui/base/ime/text_input_mode.h" -#include "ui/base/ime/text_input_type.h" -#include "ui/base/ui_base_export.h" - -namespace gfx { -class Rect; -} // namespace gfx - -namespace ui { -class CandidateWindow; -class KeyEvent; -} // namespace ui - -namespace chromeos { - -class CompositionText; - -class UI_BASE_EXPORT IMEInputContextHandlerInterface { - public: - // Called when the engine commit a text. - virtual void CommitText(const std::string& text) = 0; - - // Called when the engine updates composition text. - virtual void UpdateCompositionText(const CompositionText& text, - uint32 cursor_pos, - bool visible) = 0; - - // Called when the engine request deleting surrounding string. - virtual void DeleteSurroundingText(int32 offset, uint32 length) = 0; -}; - - -// A interface to handle the engine handler method call. -class UI_BASE_EXPORT IMEEngineHandlerInterface { - public: - typedef base::Callback<void (bool consumed)> KeyEventDoneCallback; - - // A information about a focused text input field. - // A type of each member is based on the html spec, but InputContext can be - // used to specify about a non html text field like Omnibox. - struct InputContext { - InputContext(ui::TextInputType type_, ui::TextInputMode mode_) : - type(type_), mode(mode_) {} - - // An attribute of the field defined at - // http://www.w3.org/TR/html401/interact/forms.html#input-control-types. - ui::TextInputType type; - // An attribute of the field defined at - // http://www.whatwg.org/specs/web-apps/current-work/multipage/ - // association-of-controls-and-forms.html#input-modalities - // :-the-inputmode-attribute. - ui::TextInputMode mode; - }; - - virtual ~IMEEngineHandlerInterface() {} - - // Called when the Chrome input field get the focus. - virtual void FocusIn(const InputContext& input_context) = 0; - - // Called when the Chrome input field lose the focus. - virtual void FocusOut() = 0; - - // Called when the IME is enabled. - virtual void Enable(const std::string& component_id) = 0; - - // Called when the IME is disabled. - virtual void Disable() = 0; - - // Called when a property is activated or changed. - virtual void PropertyActivate(const std::string& property_name) = 0; - - // Called when the IME is reset. - virtual void Reset() = 0; - - // Called when the key event is received. - // Actual implementation must call |callback| after key event handling. - virtual void ProcessKeyEvent(const ui::KeyEvent& key_event, - const KeyEventDoneCallback& callback) = 0; - - // Called when the candidate in lookup table is clicked. The |index| is 0 - // based candidate index in lookup table. - virtual void CandidateClicked(uint32 index) = 0; - - // Called when a new surrounding text is set. The |text| is surrounding text - // and |cursor_pos| is 0 based index of cursor position in |text|. If there is - // selection range, |anchor_pos| represents opposite index from |cursor_pos|. - // Otherwise |anchor_pos| is equal to |cursor_pos|. - virtual void SetSurroundingText(const std::string& text, uint32 cursor_pos, - uint32 anchor_pos) = 0; - - protected: - IMEEngineHandlerInterface() {} -}; - -// A interface to handle the candidate window related method call. -class UI_BASE_EXPORT IMECandidateWindowHandlerInterface { - public: - virtual ~IMECandidateWindowHandlerInterface() {} - - // Called when the IME updates the lookup table. - virtual void UpdateLookupTable(const ui::CandidateWindow& candidate_window, - bool visible) = 0; - - // Called when the IME updates the preedit text. The |text| is given in - // UTF-16 encoding. - virtual void UpdatePreeditText(const base::string16& text, - uint32 cursor_pos, - bool visible) = 0; - - // Called when the application changes its caret bounds. - virtual void SetCursorBounds(const gfx::Rect& cursor_bounds, - const gfx::Rect& composition_head) = 0; - - // Called when the text field's focus state is changed. - // |is_focused| is true when the text field gains the focus. - virtual void FocusStateChanged(bool is_focused) {} - - protected: - IMECandidateWindowHandlerInterface() {} -}; - - -// IMEBridge provides access of each IME related handler. This class -// is used for IME implementation. -class UI_BASE_EXPORT IMEBridge { - public: - virtual ~IMEBridge(); - - // Allocates the global instance. Must be called before any calls to Get(). - static void Initialize(); - - // Releases the global instance. - static void Shutdown(); - - // Returns IMEBridge global instance. Initialize() must be called first. - static IMEBridge* Get(); - - // Returns current InputContextHandler. This function returns NULL if input - // context is not ready to use. - virtual IMEInputContextHandlerInterface* GetInputContextHandler() const = 0; - - // Updates current InputContextHandler. If there is no active input context, - // pass NULL for |handler|. Caller must release |handler|. - virtual void SetInputContextHandler( - IMEInputContextHandlerInterface* handler) = 0; - - // Updates current EngineHandler. If there is no active engine service, pass - // NULL for |handler|. Caller must release |handler|. - virtual void SetCurrentEngineHandler(IMEEngineHandlerInterface* handler) = 0; - - // Returns current EngineHandler. This function returns NULL if current engine - // is not ready to use. - virtual IMEEngineHandlerInterface* GetCurrentEngineHandler() const = 0; - - // Returns current CandidateWindowHandler. This function returns NULL if - // current candidate window is not ready to use. - virtual IMECandidateWindowHandlerInterface* GetCandidateWindowHandler() - const = 0; - - // Updates current CandidatWindowHandler. If there is no active candidate - // window service, pass NULL for |handler|. Caller must release |handler|. - virtual void SetCandidateWindowHandler( - IMECandidateWindowHandlerInterface* handler) = 0; - - // Updates current text input type. - virtual void SetCurrentTextInputType(ui::TextInputType input_type) = 0; - - // Returns the current text input type. - virtual ui::TextInputType GetCurrentTextInputType() const = 0; - - protected: - IMEBridge(); - - private: - DISALLOW_COPY_AND_ASSIGN(IMEBridge); -}; - -} // namespace chromeos - -#endif // UI_BASE_IME_CHROMEOS_IME_BRIDGE_H_
diff --git a/ui/base/ime/chromeos/ime_keymap.cc b/ui/base/ime/chromeos/ime_keymap.cc deleted file mode 100644 index ec3513a..0000000 --- a/ui/base/ime/chromeos/ime_keymap.cc +++ /dev/null
@@ -1,197 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/chromeos/ime_keymap.h" - -#include <map> - -#include "base/lazy_instance.h" - -namespace ui { - -namespace { - -const struct KeyCodeTable { - KeyboardCode keyboard_code; - const char* dom_code; -} kKeyCodeTable[] = { - {VKEY_BACK, "Backspace"}, - {VKEY_TAB, "Tab"}, - {VKEY_RETURN, "Enter"}, - {VKEY_MENU, "ContextMenu"}, - {VKEY_PAUSE, "Pause"}, - {VKEY_CAPITAL, "CapsLock"}, - {VKEY_KANA, "KanaMode"}, - {VKEY_HANGUL, "HangulMode"}, - {VKEY_HANJA, "Hanja"}, - {VKEY_KANJI, "Kanji"}, - {VKEY_ESCAPE, "Escape"}, - {VKEY_CONVERT, "Convert"}, - {VKEY_NONCONVERT, "NoConvert"}, - {VKEY_SPACE, "Space"}, - {VKEY_END, "End"}, - {VKEY_HOME, "Home"}, - {VKEY_LEFT, "ArrowLeft"}, - {VKEY_UP, "ArrowUp"}, - {VKEY_RIGHT, "ArrowRight"}, - {VKEY_DOWN, "ArrowDown"}, - {VKEY_PRINT, "PrintScreen"}, - {VKEY_INSERT, "Insert"}, - {VKEY_DELETE, "Delete"}, - {VKEY_HELP, "Help"}, - {VKEY_0, "Digit0"}, - {VKEY_1, "Digit1"}, - {VKEY_2, "Digit2"}, - {VKEY_3, "Digit3"}, - {VKEY_4, "Digit4"}, - {VKEY_5, "Digit5"}, - {VKEY_6, "Digit6"}, - {VKEY_7, "Digit7"}, - {VKEY_8, "Digit8"}, - {VKEY_9, "Digit9"}, - {VKEY_A, "KeyA"}, - {VKEY_B, "KeyB"}, - {VKEY_C, "KeyC"}, - {VKEY_D, "KeyD"}, - {VKEY_E, "KeyE"}, - {VKEY_F, "KeyF"}, - {VKEY_G, "KeyG"}, - {VKEY_H, "KeyH"}, - {VKEY_I, "KeyI"}, - {VKEY_J, "KeyJ"}, - {VKEY_K, "KeyK"}, - {VKEY_L, "KeyL"}, - {VKEY_M, "KeyM"}, - {VKEY_N, "KeyN"}, - {VKEY_O, "KeyO"}, - {VKEY_P, "KeyP"}, - {VKEY_Q, "KeyQ"}, - {VKEY_R, "KeyR"}, - {VKEY_S, "KeyS"}, - {VKEY_T, "KeyT"}, - {VKEY_U, "KeyU"}, - {VKEY_V, "KeyV"}, - {VKEY_W, "KeyW"}, - {VKEY_X, "KeyX"}, - {VKEY_Y, "KeyY"}, - {VKEY_Z, "KeyZ"}, - {VKEY_LWIN, "OSLeft"}, - {VKEY_RWIN, "OSRight"}, - {VKEY_NUMPAD0, "Numpad0"}, - {VKEY_NUMPAD1, "Numpad1"}, - {VKEY_NUMPAD2, "Numpad2"}, - {VKEY_NUMPAD3, "Numpad3"}, - {VKEY_NUMPAD4, "Numpad4"}, - {VKEY_NUMPAD5, "Numpad5"}, - {VKEY_NUMPAD6, "Numpad6"}, - {VKEY_NUMPAD7, "Numpad7"}, - {VKEY_NUMPAD8, "Numpad8"}, - {VKEY_NUMPAD9, "Numpad9"}, - {VKEY_MULTIPLY, "NumpadMultiply"}, - {VKEY_ADD, "NumpadAdd"}, - {VKEY_SUBTRACT, "NumpadSubtract"}, - {VKEY_DECIMAL, "NumpadDecimal"}, - {VKEY_DIVIDE, "NumpadDivide"}, - {VKEY_F1, "F1"}, - {VKEY_F2, "F2"}, - {VKEY_F3, "F3"}, - {VKEY_F4, "F4"}, - {VKEY_F5, "F5"}, - {VKEY_F6, "F6"}, - {VKEY_F7, "F7"}, - {VKEY_F8, "F8"}, - {VKEY_F9, "F9"}, - {VKEY_F10, "F10"}, - {VKEY_F11, "F11"}, - {VKEY_F12, "F12"}, - {VKEY_F13, "F13"}, - {VKEY_F14, "F14"}, - {VKEY_F15, "F15"}, - {VKEY_F16, "F16"}, - {VKEY_F17, "F17"}, - {VKEY_F18, "F18"}, - {VKEY_F19, "F19"}, - {VKEY_F20, "F20"}, - {VKEY_F21, "F21"}, - {VKEY_F22, "F22"}, - {VKEY_F23, "F23"}, - {VKEY_F24, "F24"}, - {VKEY_NUMLOCK, "NumLock"}, - {VKEY_SCROLL, "ScrollLock"}, - {VKEY_LSHIFT, "ShiftLeft"}, - {VKEY_RSHIFT, "ShiftRight"}, - {VKEY_LCONTROL, "CtrlLeft"}, - {VKEY_RCONTROL, "CtrlRight"}, - {VKEY_LMENU, "AltLeft"}, - {VKEY_RMENU, "AltRight"}, - {VKEY_BROWSER_BACK, "BrowserBack"}, - {VKEY_BROWSER_FORWARD, "BrowserForward"}, - {VKEY_BROWSER_REFRESH, "BrowserRefresh"}, - {VKEY_BROWSER_STOP, "BrowserStop"}, - {VKEY_BROWSER_SEARCH, "BrowserSearch"}, - {VKEY_BROWSER_HOME, "BrowserHome"}, - {VKEY_VOLUME_MUTE, "VolumeMute"}, - {VKEY_VOLUME_DOWN, "VolumeDown"}, - {VKEY_VOLUME_UP, "VolumeUp"}, - {VKEY_BRIGHTNESS_DOWN, "BrightnessDown"}, - {VKEY_BRIGHTNESS_UP, "BrightnessUp"}, - {VKEY_MEDIA_LAUNCH_APP1, "ChromeOSSwitchWindow"}, - {VKEY_MEDIA_LAUNCH_APP2, "ChromeOSFullscreen"}, - {VKEY_MEDIA_NEXT_TRACK, "MediaTrackNext"}, - {VKEY_MEDIA_PREV_TRACK, "MediaTrackPrevious"}, - {VKEY_MEDIA_STOP, "MediaStop"}, - {VKEY_MEDIA_PLAY_PAUSE, "MediaPlayPause"}, - {VKEY_MEDIA_LAUNCH_MAIL, "LaunchMail"}, - {VKEY_OEM_1, "Semicolon"}, - {VKEY_OEM_PLUS, "Equal"}, - {VKEY_OEM_COMMA, "Comma"}, - {VKEY_OEM_MINUS, "Minus"}, - {VKEY_OEM_PERIOD, "Period"}, - {VKEY_OEM_2, "Slash"}, - {VKEY_OEM_3, "Backquote"}, - {VKEY_OEM_4, "BracketLeft"}, - {VKEY_OEM_5, "Backslash"}, - {VKEY_OEM_6, "BracketRight"}, - {VKEY_OEM_7, "Quote"}}; - -class KeyCodeMap { - public: - KeyCodeMap() { - for (size_t i = 0; i < arraysize(kKeyCodeTable); ++i) { - map_dom_key_[kKeyCodeTable[i].dom_code] = kKeyCodeTable[i].keyboard_code; - map_key_dom_[kKeyCodeTable[i].keyboard_code] = kKeyCodeTable[i].dom_code; - } - } - - KeyboardCode GetKeyboardCode(const std::string& dom_code) const { - std::map<std::string, KeyboardCode>::const_iterator it = - map_dom_key_.find(dom_code); - return (it == map_dom_key_.end()) ? VKEY_UNKNOWN : it->second; - } - - std::string GetDomKeycode(KeyboardCode key_code) const { - std::map<KeyboardCode, std::string>::const_iterator it = - map_key_dom_.find(key_code); - return (it == map_key_dom_.end()) ? "" : it->second; - } - - private: - std::map<std::string, KeyboardCode> map_dom_key_; - std::map<KeyboardCode, std::string> map_key_dom_; -}; - -base::LazyInstance<KeyCodeMap>::Leaky g_keycode_map = - LAZY_INSTANCE_INITIALIZER; - -} // namespace - -KeyboardCode DomKeycodeToKeyboardCode(const std::string& code) { - return g_keycode_map.Get().GetKeyboardCode(code); -} - -std::string KeyboardCodeToDomKeycode(KeyboardCode code) { - return g_keycode_map.Get().GetDomKeycode(code); -} - -} // namespace ui
diff --git a/ui/base/ime/chromeos/ime_keymap.h b/ui/base/ime/chromeos/ime_keymap.h deleted file mode 100644 index a4cdf0d..0000000 --- a/ui/base/ime/chromeos/ime_keymap.h +++ /dev/null
@@ -1,23 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_CHROMEOS_IME_KEYMAP_H_ -#define UI_BASE_IME_CHROMEOS_IME_KEYMAP_H_ - -#include <string> -#include "base/basictypes.h" -#include "ui/base/ui_base_export.h" -#include "ui/events/keycodes/keyboard_codes.h" - -namespace ui { - -// Translates the DOM4 key code string to ui::KeyboardCode. -UI_BASE_EXPORT KeyboardCode DomKeycodeToKeyboardCode(const std::string& code); - -// Translates the ui::KeyboardCode to DOM4 key code string. -UI_BASE_EXPORT std::string KeyboardCodeToDomKeycode(KeyboardCode code); - -} // namespace ui - -#endif // UI_BASE_IME_CHROMEOS_IME_KEYMAP_H_
diff --git a/ui/base/ime/chromeos/mock_ime_candidate_window_handler.cc b/ui/base/ime/chromeos/mock_ime_candidate_window_handler.cc deleted file mode 100644 index 6e61876..0000000 --- a/ui/base/ime/chromeos/mock_ime_candidate_window_handler.cc +++ /dev/null
@@ -1,42 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/chromeos/mock_ime_candidate_window_handler.h" - -namespace chromeos { - -MockIMECandidateWindowHandler::MockIMECandidateWindowHandler() - : set_cursor_bounds_call_count_(0), - update_lookup_table_call_count_(0) { -} - -MockIMECandidateWindowHandler::~MockIMECandidateWindowHandler() { - -} - -void MockIMECandidateWindowHandler::UpdateLookupTable( - const ui::CandidateWindow& table, - bool visible) { - ++update_lookup_table_call_count_; - last_update_lookup_table_arg_.lookup_table.CopyFrom(table); - last_update_lookup_table_arg_.is_visible = visible; -} - -void MockIMECandidateWindowHandler::UpdatePreeditText( - const base::string16& text, - uint32 cursor_pos, - bool visible) {} - -void MockIMECandidateWindowHandler::SetCursorBounds( - const gfx::Rect& cursor_bounds, - const gfx::Rect& composition_head) { - ++set_cursor_bounds_call_count_; -} - -void MockIMECandidateWindowHandler::Reset() { - set_cursor_bounds_call_count_ = 0; - update_lookup_table_call_count_ = 0; -} - -} // namespace chromeos
diff --git a/ui/base/ime/chromeos/mock_ime_candidate_window_handler.h b/ui/base/ime/chromeos/mock_ime_candidate_window_handler.h deleted file mode 100644 index 9bac92c..0000000 --- a/ui/base/ime/chromeos/mock_ime_candidate_window_handler.h +++ /dev/null
@@ -1,61 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_CHROMEOS_MOCK_IME_CANDIDATE_WINDOW_HANDLER_H_ -#define UI_BASE_IME_CHROMEOS_MOCK_IME_CANDIDATE_WINDOW_HANDLER_H_ - -#include "ui/base/ime/candidate_window.h" -#include "ui/base/ime/chromeos/ime_bridge.h" -#include "ui/base/ui_base_export.h" - -namespace chromeos { - -class UI_BASE_EXPORT MockIMECandidateWindowHandler - : public IMECandidateWindowHandlerInterface { - public: - struct UpdateLookupTableArg { - ui::CandidateWindow lookup_table; - bool is_visible; - }; - - struct UpdateAuxiliaryTextArg { - std::string text; - bool is_visible; - }; - - MockIMECandidateWindowHandler(); - virtual ~MockIMECandidateWindowHandler(); - - // IMECandidateWindowHandlerInterface override. - virtual void UpdateLookupTable( - const ui::CandidateWindow& candidate_window, - bool visible) override; - virtual void UpdatePreeditText( - const base::string16& text, uint32 cursor_pos, bool visible) override; - virtual void SetCursorBounds(const gfx::Rect& cursor_bounds, - const gfx::Rect& composition_head) override; - - int set_cursor_bounds_call_count() const { - return set_cursor_bounds_call_count_; - } - - int update_lookup_table_call_count() const { - return update_lookup_table_call_count_; - } - - const UpdateLookupTableArg& last_update_lookup_table_arg() { - return last_update_lookup_table_arg_; - } - // Resets all call count. - void Reset(); - - private: - int set_cursor_bounds_call_count_; - int update_lookup_table_call_count_; - UpdateLookupTableArg last_update_lookup_table_arg_; -}; - -} // namespace chromeos - -#endif // UI_BASE_IME_CHROMEOS_MOCK_IME_CANDIDATE_WINDOW_HANDLER_H_
diff --git a/ui/base/ime/chromeos/mock_ime_engine_handler.cc b/ui/base/ime/chromeos/mock_ime_engine_handler.cc deleted file mode 100644 index ca855a0..0000000 --- a/ui/base/ime/chromeos/mock_ime_engine_handler.cc +++ /dev/null
@@ -1,70 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/chromeos/mock_ime_engine_handler.h" - -namespace chromeos { - -MockIMEEngineHandler::MockIMEEngineHandler() - : focus_in_call_count_(0), - focus_out_call_count_(0), - set_surrounding_text_call_count_(0), - process_key_event_call_count_(0), - reset_call_count_(0), - last_text_input_context_(ui::TEXT_INPUT_TYPE_NONE, - ui::TEXT_INPUT_MODE_DEFAULT), - last_set_surrounding_cursor_pos_(0), - last_set_surrounding_anchor_pos_(0) { -} - -MockIMEEngineHandler::~MockIMEEngineHandler() { -} - -void MockIMEEngineHandler::FocusIn(const InputContext& input_context) { - last_text_input_context_ = input_context; - if (last_text_input_context_.type != ui::TEXT_INPUT_TYPE_NONE) - ++focus_in_call_count_; -} - -void MockIMEEngineHandler::FocusOut() { - if (last_text_input_context_.type != ui::TEXT_INPUT_TYPE_NONE) - ++focus_out_call_count_; - last_text_input_context_.type = ui::TEXT_INPUT_TYPE_NONE; -} - -void MockIMEEngineHandler::Enable(const std::string& component_id) { -} - -void MockIMEEngineHandler::Disable() { -} - -void MockIMEEngineHandler::PropertyActivate(const std::string& property_name) { - last_activated_property_ = property_name; -} - -void MockIMEEngineHandler::Reset() { - ++reset_call_count_; -} - -void MockIMEEngineHandler::ProcessKeyEvent( - const ui::KeyEvent& key_event, - const KeyEventDoneCallback& callback) { - ++process_key_event_call_count_; - last_processed_key_event_.reset(new ui::KeyEvent(key_event)); - last_passed_callback_ = callback; -} - -void MockIMEEngineHandler::CandidateClicked(uint32 index) { -} - -void MockIMEEngineHandler::SetSurroundingText(const std::string& text, - uint32 cursor_pos, - uint32 anchor_pos) { - ++set_surrounding_text_call_count_; - last_set_surrounding_text_ = text; - last_set_surrounding_cursor_pos_ = cursor_pos; - last_set_surrounding_anchor_pos_ = anchor_pos; -} - -} // namespace chromeos
diff --git a/ui/base/ime/chromeos/mock_ime_engine_handler.h b/ui/base/ime/chromeos/mock_ime_engine_handler.h deleted file mode 100644 index 798cde6..0000000 --- a/ui/base/ime/chromeos/mock_ime_engine_handler.h +++ /dev/null
@@ -1,86 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_CHROMEOS_MOCK_IME_ENGINE_HANDLER_H_ -#define UI_BASE_IME_CHROMEOS_MOCK_IME_ENGINE_HANDLER_H_ - -#include "ui/base/ime/chromeos/ime_bridge.h" -#include "ui/base/ui_base_export.h" -#include "ui/events/event.h" - -namespace chromeos { - -class UI_BASE_EXPORT MockIMEEngineHandler : public IMEEngineHandlerInterface { - public: - MockIMEEngineHandler(); - virtual ~MockIMEEngineHandler(); - - virtual void FocusIn(const InputContext& input_context) override; - virtual void FocusOut() override; - virtual void Enable(const std::string& component_id) override; - virtual void Disable() override; - virtual void PropertyActivate(const std::string& property_name) override; - virtual void Reset() override; - virtual void ProcessKeyEvent(const ui::KeyEvent& key_event, - const KeyEventDoneCallback& callback) override; - virtual void CandidateClicked(uint32 index) override; - virtual void SetSurroundingText(const std::string& text, uint32 cursor_pos, - uint32 anchor_pos) override; - - int focus_in_call_count() const { return focus_in_call_count_; } - int focus_out_call_count() const { return focus_out_call_count_; } - int reset_call_count() const { return reset_call_count_; } - int set_surrounding_text_call_count() const { - return set_surrounding_text_call_count_; - } - int process_key_event_call_count() const { - return process_key_event_call_count_; - } - - const InputContext& last_text_input_context() const { - return last_text_input_context_; - } - - std::string last_activated_property() const { - return last_activated_property_; - } - - std::string last_set_surrounding_text() const { - return last_set_surrounding_text_; - } - - uint32 last_set_surrounding_cursor_pos() const { - return last_set_surrounding_cursor_pos_; - } - - uint32 last_set_surrounding_anchor_pos() const { - return last_set_surrounding_anchor_pos_; - } - - const ui::KeyEvent* last_processed_key_event() const { - return last_processed_key_event_.get(); - } - - const KeyEventDoneCallback& last_passed_callback() const { - return last_passed_callback_; - } - - private: - int focus_in_call_count_; - int focus_out_call_count_; - int set_surrounding_text_call_count_; - int process_key_event_call_count_; - int reset_call_count_; - InputContext last_text_input_context_; - std::string last_activated_property_; - std::string last_set_surrounding_text_; - uint32 last_set_surrounding_cursor_pos_; - uint32 last_set_surrounding_anchor_pos_; - scoped_ptr<ui::KeyEvent> last_processed_key_event_; - KeyEventDoneCallback last_passed_callback_; -}; - -} // namespace chromeos - -#endif // UI_BASE_IME_CHROMEOS_MOCK_IME_ENGINE_HANDLER_H_
diff --git a/ui/base/ime/chromeos/mock_ime_input_context_handler.cc b/ui/base/ime/chromeos/mock_ime_input_context_handler.cc deleted file mode 100644 index 14e5bc0..0000000 --- a/ui/base/ime/chromeos/mock_ime_input_context_handler.cc +++ /dev/null
@@ -1,49 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/chromeos/mock_ime_input_context_handler.h" - -#include "chromeos/ime/composition_text.h" - -namespace chromeos { - -MockIMEInputContextHandler::MockIMEInputContextHandler() - : commit_text_call_count_(0), - update_preedit_text_call_count_(0), - delete_surrounding_text_call_count_(0) { -} - -MockIMEInputContextHandler::~MockIMEInputContextHandler() { -} - -void MockIMEInputContextHandler::CommitText(const std::string& text) { - ++commit_text_call_count_; - last_commit_text_ = text; -} - -void MockIMEInputContextHandler::UpdateCompositionText( - const CompositionText& text, - uint32 cursor_pos, - bool visible) { - ++update_preedit_text_call_count_; - last_update_composition_arg_.composition_text.CopyFrom(text); - last_update_composition_arg_.cursor_pos = cursor_pos; - last_update_composition_arg_.is_visible = visible; -} - -void MockIMEInputContextHandler::DeleteSurroundingText(int32 offset, - uint32 length) { - ++delete_surrounding_text_call_count_; - last_delete_surrounding_text_arg_.offset = offset; - last_delete_surrounding_text_arg_.length = length; -} - -void MockIMEInputContextHandler::Reset() { - commit_text_call_count_ = 0; - update_preedit_text_call_count_ = 0; - delete_surrounding_text_call_count_ = 0; - last_commit_text_.clear(); -} - -} // namespace chromeos
diff --git a/ui/base/ime/chromeos/mock_ime_input_context_handler.h b/ui/base/ime/chromeos/mock_ime_input_context_handler.h deleted file mode 100644 index 8e18dec..0000000 --- a/ui/base/ime/chromeos/mock_ime_input_context_handler.h +++ /dev/null
@@ -1,73 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_CHROMEOS_MOCK_IME_INPUT_CONTEXT_HANDLER_H_ -#define UI_BASE_IME_CHROMEOS_MOCK_IME_INPUT_CONTEXT_HANDLER_H_ - -#include "chromeos/ime/composition_text.h" -#include "ui/base/ime/chromeos/ime_bridge.h" -#include "ui/base/ui_base_export.h" - -namespace chromeos { - -class UI_BASE_EXPORT MockIMEInputContextHandler - : public IMEInputContextHandlerInterface { - public: - struct UpdateCompositionTextArg { - CompositionText composition_text; - uint32 cursor_pos; - bool is_visible; - }; - - struct DeleteSurroundingTextArg { - int32 offset; - uint32 length; - }; - - MockIMEInputContextHandler(); - virtual ~MockIMEInputContextHandler(); - - virtual void CommitText(const std::string& text) override; - virtual void UpdateCompositionText(const CompositionText& text, - uint32 cursor_pos, - bool visible) override; - virtual void DeleteSurroundingText(int32 offset, uint32 length) override; - - int commit_text_call_count() const { return commit_text_call_count_; } - - int update_preedit_text_call_count() const { - return update_preedit_text_call_count_; - } - - int delete_surrounding_text_call_count() const { - return delete_surrounding_text_call_count_; - } - - const std::string& last_commit_text() const { - return last_commit_text_; - }; - - const UpdateCompositionTextArg& last_update_composition_arg() const { - return last_update_composition_arg_; - } - - const DeleteSurroundingTextArg& last_delete_surrounding_text_arg() const { - return last_delete_surrounding_text_arg_; - } - - // Resets all call count. - void Reset(); - - private: - int commit_text_call_count_; - int update_preedit_text_call_count_; - int delete_surrounding_text_call_count_; - std::string last_commit_text_; - UpdateCompositionTextArg last_update_composition_arg_; - DeleteSurroundingTextArg last_delete_surrounding_text_arg_; -}; - -} // namespace chromeos - -#endif // UI_BASE_IME_CHROMEOS_MOCK_IME_INPUT_CONTEXT_HANDLER_H_
diff --git a/ui/base/ime/composition_text.cc b/ui/base/ime/composition_text.cc deleted file mode 100644 index f85bc74..0000000 --- a/ui/base/ime/composition_text.cc +++ /dev/null
@@ -1,21 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/composition_text.h" - -namespace ui { - -CompositionText::CompositionText() { -} - -CompositionText::~CompositionText() { -} - -void CompositionText::Clear() { - text.clear(); - underlines.clear(); - selection = gfx::Range(); -} - -} // namespace ui
diff --git a/ui/base/ime/composition_text.h b/ui/base/ime/composition_text.h deleted file mode 100644 index e4974bd..0000000 --- a/ui/base/ime/composition_text.h +++ /dev/null
@@ -1,55 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_COMPOSITION_TEXT_H_ -#define UI_BASE_IME_COMPOSITION_TEXT_H_ - -#include "base/strings/string16.h" -#include "ui/base/ime/composition_underline.h" -#include "ui/base/ui_base_export.h" -#include "ui/gfx/range/range.h" - -namespace ui { - -// A struct represents the status of an ongoing composition text. -struct UI_BASE_EXPORT CompositionText { - CompositionText(); - ~CompositionText(); - - bool operator==(const CompositionText& rhs) const { - if ((this->text != rhs.text) || - (this->selection != rhs.selection) || - (this->underlines.size() != rhs.underlines.size())) - return false; - for (size_t i = 0; i < this->underlines.size(); ++i) { - if (this->underlines[i] != rhs.underlines[i]) - return false; - } - return true; - } - - bool operator!=(const CompositionText& rhs) const { - return !(*this == rhs); - } - - void Clear(); - - // Content of the composition text. - base::string16 text; - - // Underline information of the composition text. - // They must be sorted in ascending order by their start_offset and cannot be - // overlapped with each other. - CompositionUnderlines underlines; - - // Selection range in the composition text. It represents the caret position - // if the range length is zero. Usually it's used for representing the target - // clause (on Windows). Gtk doesn't have such concept, so background color is - // usually used instead. - gfx::Range selection; -}; - -} // namespace ui - -#endif // UI_BASE_IME_COMPOSITION_TEXT_H_
diff --git a/ui/base/ime/composition_text_util_pango.cc b/ui/base/ime/composition_text_util_pango.cc deleted file mode 100644 index 325cdd6..0000000 --- a/ui/base/ime/composition_text_util_pango.cc +++ /dev/null
@@ -1,119 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/composition_text_util_pango.h" - -#include <pango/pango-attributes.h> - -#include "base/basictypes.h" -#include "base/i18n/char_iterator.h" -#include "base/strings/string16.h" -#include "base/strings/utf_string_conversions.h" -#include "ui/base/ime/composition_text.h" - -namespace ui { - -void ExtractCompositionTextFromGtkPreedit(const gchar* utf8_text, - PangoAttrList* attrs, - int cursor_position, - CompositionText* composition) { - composition->Clear(); - composition->text = base::UTF8ToUTF16(utf8_text); - - if (composition->text.empty()) - return; - - // Gtk/Pango uses character index for cursor position and byte index for - // attribute range, but we use char16 offset for them. So we need to do - // conversion here. - std::vector<size_t> char16_offsets; - size_t length = composition->text.length(); - base::i18n::UTF16CharIterator char_iterator(&composition->text); - do { - char16_offsets.push_back(char_iterator.array_pos()); - } while (char_iterator.Advance()); - - // The text length in Unicode characters. - int char_length = static_cast<int>(char16_offsets.size()); - // Make sure we can convert the value of |char_length| as well. - char16_offsets.push_back(length); - - size_t cursor_offset = - char16_offsets[std::max(0, std::min(char_length, cursor_position))]; - - composition->selection = gfx::Range(cursor_offset); - - if (attrs) { - int utf8_length = strlen(utf8_text); - PangoAttrIterator* iter = pango_attr_list_get_iterator(attrs); - - // We only care about underline and background attributes and convert - // background attribute into selection if possible. - do { - gint start, end; - pango_attr_iterator_range(iter, &start, &end); - - start = std::min(start, utf8_length); - end = std::min(end, utf8_length); - if (start >= end) - continue; - - start = g_utf8_pointer_to_offset(utf8_text, utf8_text + start); - end = g_utf8_pointer_to_offset(utf8_text, utf8_text + end); - - // Double check, in case |utf8_text| is not a valid utf-8 string. - start = std::min(start, char_length); - end = std::min(end, char_length); - if (start >= end) - continue; - - PangoAttribute* background_attr = - pango_attr_iterator_get(iter, PANGO_ATTR_BACKGROUND); - PangoAttribute* underline_attr = - pango_attr_iterator_get(iter, PANGO_ATTR_UNDERLINE); - - if (background_attr || underline_attr) { - // Use a black thin underline by default. - CompositionUnderline underline(char16_offsets[start], - char16_offsets[end], - SK_ColorBLACK, - false, - SK_ColorTRANSPARENT); - - // Always use thick underline for a range with background color, which - // is usually the selection range. - if (background_attr) { - underline.thick = true; - // If the cursor is at start or end of this underline, then we treat - // it as the selection range as well, but make sure to set the cursor - // position to the selection end. - if (underline.start_offset == cursor_offset) { - composition->selection.set_start(underline.end_offset); - composition->selection.set_end(cursor_offset); - } else if (underline.end_offset == cursor_offset) { - composition->selection.set_start(underline.start_offset); - composition->selection.set_end(cursor_offset); - } - } - if (underline_attr) { - int type = reinterpret_cast<PangoAttrInt*>(underline_attr)->value; - if (type == PANGO_UNDERLINE_DOUBLE) - underline.thick = true; - else if (type == PANGO_UNDERLINE_ERROR) - underline.color = SK_ColorRED; - } - composition->underlines.push_back(underline); - } - } while (pango_attr_iterator_next(iter)); - pango_attr_iterator_destroy(iter); - } - - // Use a black thin underline by default. - if (composition->underlines.empty()) { - composition->underlines.push_back(CompositionUnderline( - 0, length, SK_ColorBLACK, false, SK_ColorTRANSPARENT)); - } -} - -} // namespace ui
diff --git a/ui/base/ime/composition_text_util_pango.h b/ui/base/ime/composition_text_util_pango.h deleted file mode 100644 index 1116fd9..0000000 --- a/ui/base/ime/composition_text_util_pango.h +++ /dev/null
@@ -1,27 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_COMPOSITION_TEXT_UTIL_PANGO_H_ -#define UI_BASE_IME_COMPOSITION_TEXT_UTIL_PANGO_H_ - -#include "ui/base/glib/glib_integers.h" -#include "ui/base/ui_base_export.h" - -typedef struct _PangoAttrList PangoAttrList; - -namespace ui { - -struct CompositionText; - -// Extracts composition text information (text, underlines, selection range) -// from given Gtk preedit data (utf-8 text, pango attributes, cursor position). -UI_BASE_EXPORT void ExtractCompositionTextFromGtkPreedit( - const gchar* utf8_text, - PangoAttrList* attrs, - int cursor_position, - CompositionText* composition); - -} // namespace ui - -#endif // UI_BASE_IME_COMPOSITION_TEXT_UTIL_PANGO_H_
diff --git a/ui/base/ime/composition_text_util_pango_unittest.cc b/ui/base/ime/composition_text_util_pango_unittest.cc deleted file mode 100644 index a2056cf..0000000 --- a/ui/base/ime/composition_text_util_pango_unittest.cc +++ /dev/null
@@ -1,147 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/composition_text_util_pango.h" - -#include <pango/pango-attributes.h> - -#include <string> -#include <utility> - -#include "base/basictypes.h" -#include "base/logging.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/base/ime/composition_text.h" - -namespace { - -struct AttributeInfo { - int type; - int value; - int start_offset; - int end_offset; -}; - -struct Underline { - unsigned start_offset; - unsigned end_offset; - uint32 color; - bool thick; - uint32 background_color; -}; - -struct TestData { - const char* text; - const AttributeInfo attrs[10]; - const Underline underlines[10]; -}; - -const TestData kTestData[] = { - // Normal case - {"One Two Three", - {{PANGO_ATTR_UNDERLINE, PANGO_UNDERLINE_SINGLE, 0, 3}, - {PANGO_ATTR_UNDERLINE, PANGO_UNDERLINE_DOUBLE, 4, 7}, - {PANGO_ATTR_BACKGROUND, 0, 4, 7}, - {PANGO_ATTR_UNDERLINE, PANGO_UNDERLINE_SINGLE, 8, 13}, - {0, 0, 0, 0}}, - {{0, 3, SK_ColorBLACK, false, SK_ColorTRANSPARENT}, - {4, 7, SK_ColorBLACK, true, SK_ColorTRANSPARENT}, - {8, 13, SK_ColorBLACK, false, SK_ColorTRANSPARENT}, - {0, 0, 0, false, SK_ColorTRANSPARENT}}}, - - // Offset overflow. - {"One Two Three", - {{PANGO_ATTR_UNDERLINE, PANGO_UNDERLINE_SINGLE, 0, 3}, - {PANGO_ATTR_BACKGROUND, 0, 4, 7}, - {PANGO_ATTR_UNDERLINE, PANGO_UNDERLINE_SINGLE, 8, 20}, - {0, 0, 0, 0}}, - {{0, 3, SK_ColorBLACK, false, SK_ColorTRANSPARENT}, - {4, 7, SK_ColorBLACK, true, SK_ColorTRANSPARENT}, - {8, 13, SK_ColorBLACK, false, SK_ColorTRANSPARENT}, - {0, 0, 0, false, SK_ColorTRANSPARENT}}}, - - // Error underline. - {"One Two Three", - {{PANGO_ATTR_UNDERLINE, PANGO_UNDERLINE_SINGLE, 0, 3}, - {PANGO_ATTR_UNDERLINE, PANGO_UNDERLINE_ERROR, 4, 7}, - {PANGO_ATTR_UNDERLINE, PANGO_UNDERLINE_SINGLE, 8, 13}, - {0, 0, 0, 0}}, - {{0, 3, SK_ColorBLACK, false, SK_ColorTRANSPARENT}, - {4, 7, SK_ColorRED, false, SK_ColorTRANSPARENT}, - {8, 13, SK_ColorBLACK, false, SK_ColorTRANSPARENT}, - {0, 0, 0, false, SK_ColorTRANSPARENT}}}, - - // Default underline. - {"One Two Three", - {{0, 0, 0, 0}}, - {{0, 13, SK_ColorBLACK, false, SK_ColorTRANSPARENT}, - {0, 0, 0, false, SK_ColorTRANSPARENT}}}, - - // Unicode, including non-BMP characters: "123你好𠀀𠀁一丁 456" - {"123\xE4\xBD\xA0\xE5\xA5\xBD\xF0\xA0\x80\x80\xF0\xA0\x80\x81\xE4\xB8\x80" - "\xE4\xB8\x81 456", - {{PANGO_ATTR_UNDERLINE, PANGO_UNDERLINE_SINGLE, 0, 3}, - {PANGO_ATTR_UNDERLINE, PANGO_UNDERLINE_SINGLE, 3, 5}, - {PANGO_ATTR_BACKGROUND, 0, 5, 7}, - {PANGO_ATTR_UNDERLINE, PANGO_UNDERLINE_SINGLE, 7, 13}, - {0, 0, 0, 0}}, - {{0, 3, SK_ColorBLACK, false, SK_ColorTRANSPARENT}, - {3, 5, SK_ColorBLACK, false, SK_ColorTRANSPARENT}, - {5, 9, SK_ColorBLACK, true, SK_ColorTRANSPARENT}, - {9, 15, SK_ColorBLACK, false, SK_ColorTRANSPARENT}, - {0, 0, 0, false, SK_ColorTRANSPARENT}}}, -}; - -void CompareUnderline(const Underline& a, - const ui::CompositionUnderline& b) { - EXPECT_EQ(a.start_offset, b.start_offset); - EXPECT_EQ(a.end_offset, b.end_offset); - EXPECT_EQ(a.color, b.color); - EXPECT_EQ(a.thick, b.thick); - EXPECT_EQ(a.background_color, b.background_color); -} - -TEST(CompositionTextUtilPangoTest, ExtractCompositionText) { - for (size_t i = 0; i < arraysize(kTestData); ++i) { - const char* text = kTestData[i].text; - const AttributeInfo* attrs = kTestData[i].attrs; - SCOPED_TRACE(testing::Message() << "Testing:" << i - << " text:" << text); - - PangoAttrList* pango_attrs = pango_attr_list_new(); - for (size_t a = 0; attrs[a].type; ++a) { - PangoAttribute* pango_attr = NULL; - switch (attrs[a].type) { - case PANGO_ATTR_UNDERLINE: - pango_attr = pango_attr_underline_new( - static_cast<PangoUnderline>(attrs[a].value)); - break; - case PANGO_ATTR_BACKGROUND: - pango_attr = pango_attr_background_new(0, 0, 0); - break; - default: - NOTREACHED(); - } - pango_attr->start_index = - g_utf8_offset_to_pointer(text, attrs[a].start_offset) - text; - pango_attr->end_index = - g_utf8_offset_to_pointer(text, attrs[a].end_offset) - text; - pango_attr_list_insert(pango_attrs, pango_attr); - } - - ui::CompositionText result; - ui::ExtractCompositionTextFromGtkPreedit(text, pango_attrs, 0, &result); - - const Underline* underlines = kTestData[i].underlines; - for (size_t u = 0; underlines[u].color && - u < result.underlines.size(); ++u) { - SCOPED_TRACE(testing::Message() << "Underline:" << u); - CompareUnderline(underlines[u], result.underlines[u]); - } - - pango_attr_list_unref(pango_attrs); - } -} - -} // namespace
diff --git a/ui/base/ime/composition_underline.h b/ui/base/ime/composition_underline.h deleted file mode 100644 index a8c44b6..0000000 --- a/ui/base/ime/composition_underline.h +++ /dev/null
@@ -1,62 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_COMPOSITION_UNDERLINE_H_ -#define UI_BASE_IME_COMPOSITION_UNDERLINE_H_ - -#include <vector> - -#include "base/basictypes.h" -#include "third_party/skia/include/core/SkColor.h" - -namespace ui { - -// Intentionally keep sync with blink::WebCompositionUnderline defined in: -// third_party/WebKit/public/web/WebCompositionUnderline.h -struct CompositionUnderline { - CompositionUnderline() - : start_offset(0), - end_offset(0), - color(SK_ColorTRANSPARENT), - thick(false), - background_color(SK_ColorTRANSPARENT) {} - - // TODO(huangs): remove this constructor. - CompositionUnderline(uint32 s, uint32 e, SkColor c, bool t) - : start_offset(s), - end_offset(e), - color(c), - thick(t), - background_color(SK_ColorTRANSPARENT) {} - - CompositionUnderline(uint32 s, uint32 e, SkColor c, bool t, SkColor bc) - : start_offset(s), - end_offset(e), - color(c), - thick(t), - background_color(bc) {} - - bool operator==(const CompositionUnderline& rhs) const { - return (this->start_offset == rhs.start_offset) && - (this->end_offset == rhs.end_offset) && (this->color == rhs.color) && - (this->thick == rhs.thick) && - (this->background_color == rhs.background_color); - } - - bool operator!=(const CompositionUnderline& rhs) const { - return !(*this == rhs); - } - - uint32 start_offset; - uint32 end_offset; - SkColor color; - bool thick; - SkColor background_color; -}; - -typedef std::vector<CompositionUnderline> CompositionUnderlines; - -} // namespace ui - -#endif // UI_BASE_IME_COMPOSITION_UNDERLINE_H_
diff --git a/ui/base/ime/dummy_input_method.cc b/ui/base/ime/dummy_input_method.cc deleted file mode 100644 index a12bbfc..0000000 --- a/ui/base/ime/dummy_input_method.cc +++ /dev/null
@@ -1,91 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/dummy_input_method.h" - -namespace ui { - -DummyInputMethod::DummyInputMethod() { -} - -DummyInputMethod::~DummyInputMethod() { -} - -void DummyInputMethod::SetDelegate(internal::InputMethodDelegate* delegate) { -} - -void DummyInputMethod::Init(bool focused) { -} - -void DummyInputMethod::OnFocus() { -} - -void DummyInputMethod::OnBlur() { -} - -bool DummyInputMethod::OnUntranslatedIMEMessage(const base::NativeEvent& event, - NativeEventResult* result) { - return false; -} - -void DummyInputMethod::SetFocusedTextInputClient(TextInputClient* client) { -} - -void DummyInputMethod::DetachTextInputClient(TextInputClient* client) { -} - -TextInputClient* DummyInputMethod::GetTextInputClient() const { - return NULL; -} - -bool DummyInputMethod::DispatchKeyEvent(const ui::KeyEvent& event) { - return false; -} - -void DummyInputMethod::OnTextInputTypeChanged(const TextInputClient* client) { -} - -void DummyInputMethod::OnCaretBoundsChanged(const TextInputClient* client) { -} - -void DummyInputMethod::CancelComposition(const TextInputClient* client) { -} - -void DummyInputMethod::OnInputLocaleChanged() { -} - -std::string DummyInputMethod::GetInputLocale() { - return std::string(); -} - -bool DummyInputMethod::IsActive() { - return true; -} - -TextInputType DummyInputMethod::GetTextInputType() const { - return TEXT_INPUT_TYPE_NONE; -} - -TextInputMode DummyInputMethod::GetTextInputMode() const { - return TEXT_INPUT_MODE_DEFAULT; -} - -bool DummyInputMethod::CanComposeInline() const { - return true; -} - -bool DummyInputMethod::IsCandidatePopupOpen() const { - return false; -} - -void DummyInputMethod::ShowImeIfNeeded() { -} - -void DummyInputMethod::AddObserver(InputMethodObserver* observer) { -} - -void DummyInputMethod::RemoveObserver(InputMethodObserver* observer) { -} - -} // namespace ui
diff --git a/ui/base/ime/dummy_input_method.h b/ui/base/ime/dummy_input_method.h deleted file mode 100644 index 20a019b..0000000 --- a/ui/base/ime/dummy_input_method.h +++ /dev/null
@@ -1,51 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_DUMMY_INPUT_METHOD_H_ -#define UI_BASE_IME_DUMMY_INPUT_METHOD_H_ - -#include "ui/base/ime/input_method.h" - -namespace ui { - -class InputMethodObserver; - -class DummyInputMethod : public InputMethod { - public: - DummyInputMethod(); - ~DummyInputMethod() override; - - // InputMethod overrides: - void SetDelegate(internal::InputMethodDelegate* delegate) override; - void Init(bool focused) override; - void OnFocus() override; - void OnBlur() override; - bool OnUntranslatedIMEMessage(const base::NativeEvent& event, - NativeEventResult* result) override; - void SetFocusedTextInputClient(TextInputClient* client) override; - void DetachTextInputClient(TextInputClient* client) override; - TextInputClient* GetTextInputClient() const override; - bool DispatchKeyEvent(const ui::KeyEvent& event) override; - void OnTextInputTypeChanged(const TextInputClient* client) override; - void OnCaretBoundsChanged(const TextInputClient* client) override; - void CancelComposition(const TextInputClient* client) override; - void OnInputLocaleChanged() override; - std::string GetInputLocale() override; - bool IsActive() override; - TextInputType GetTextInputType() const override; - TextInputMode GetTextInputMode() const override; - bool CanComposeInline() const override; - bool IsCandidatePopupOpen() const override; - void ShowImeIfNeeded() override; - - void AddObserver(InputMethodObserver* observer) override; - void RemoveObserver(InputMethodObserver* observer) override; - - private: - DISALLOW_COPY_AND_ASSIGN(DummyInputMethod); -}; - -} // namespace ui - -#endif // UI_BASE_IME_DUMMY_INPUT_METHOD_H_
diff --git a/ui/base/ime/dummy_input_method_delegate.cc b/ui/base/ime/dummy_input_method_delegate.cc deleted file mode 100644 index 473884a..0000000 --- a/ui/base/ime/dummy_input_method_delegate.cc +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/dummy_input_method_delegate.h" - -namespace ui { -namespace internal { - -DummyInputMethodDelegate::DummyInputMethodDelegate() {} -DummyInputMethodDelegate::~DummyInputMethodDelegate() {} - -bool DummyInputMethodDelegate::DispatchKeyEventPostIME( - const ui::KeyEvent& key_event) { - return true; -} - -} // namespace internal -} // namespace ui
diff --git a/ui/base/ime/dummy_input_method_delegate.h b/ui/base/ime/dummy_input_method_delegate.h deleted file mode 100644 index db5a5e3..0000000 --- a/ui/base/ime/dummy_input_method_delegate.h +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_DUMMY_INPUT_METHOD_DELEGATE_H_ -#define UI_BASE_IME_DUMMY_INPUT_METHOD_DELEGATE_H_ - -#include "base/compiler_specific.h" -#include "base/macros.h" -#include "ui/base/ime/input_method_delegate.h" - -namespace ui { -namespace internal { - -class UI_BASE_EXPORT DummyInputMethodDelegate : public InputMethodDelegate { - public: - DummyInputMethodDelegate(); - ~DummyInputMethodDelegate() override; - - // Overridden from InputMethodDelegate: - bool DispatchKeyEventPostIME(const ui::KeyEvent& key_event) override; - - private: - DISALLOW_COPY_AND_ASSIGN(DummyInputMethodDelegate); -}; - -} // namespace internal -} // namespace ui - -#endif // UI_BASE_IME_DUMMY_INPUT_METHOD_DELEGATE_H_
diff --git a/ui/base/ime/dummy_text_input_client.cc b/ui/base/ime/dummy_text_input_client.cc deleted file mode 100644 index cea49c6..0000000 --- a/ui/base/ime/dummy_text_input_client.cc +++ /dev/null
@@ -1,121 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/dummy_text_input_client.h" -#include "ui/gfx/rect.h" - -namespace ui { - -DummyTextInputClient::DummyTextInputClient() - : text_input_type_(TEXT_INPUT_TYPE_NONE) {} - -DummyTextInputClient::DummyTextInputClient(TextInputType text_input_type) - : text_input_type_(text_input_type) {} - -DummyTextInputClient::~DummyTextInputClient() { -} - -void DummyTextInputClient::SetCompositionText( - const CompositionText& composition) { -} - -void DummyTextInputClient::ConfirmCompositionText() { -} - -void DummyTextInputClient::ClearCompositionText() { -} - -void DummyTextInputClient::InsertText(const base::string16& text) { -} - -void DummyTextInputClient::InsertChar(base::char16 ch, int flags) { -} - -gfx::NativeWindow DummyTextInputClient::GetAttachedWindow() const { - return NULL; -} - -TextInputType DummyTextInputClient::GetTextInputType() const { - return text_input_type_; -} - -TextInputMode DummyTextInputClient::GetTextInputMode() const { - return TEXT_INPUT_MODE_DEFAULT; -} - -bool DummyTextInputClient::CanComposeInline() const { - return false; -} - -gfx::Rect DummyTextInputClient::GetCaretBounds() const { - return gfx::Rect(); -} - -bool DummyTextInputClient::GetCompositionCharacterBounds( - uint32 index, - gfx::Rect* rect) const { - return false; -} - -bool DummyTextInputClient::HasCompositionText() const { - return false; -} - -bool DummyTextInputClient::GetTextRange(gfx::Range* range) const { - return false; -} - -bool DummyTextInputClient::GetCompositionTextRange(gfx::Range* range) const { - return false; -} - -bool DummyTextInputClient::GetSelectionRange(gfx::Range* range) const { - return false; -} - -bool DummyTextInputClient::SetSelectionRange(const gfx::Range& range) { - return false; -} - -bool DummyTextInputClient::DeleteRange(const gfx::Range& range) { - return false; -} - -bool DummyTextInputClient::GetTextFromRange(const gfx::Range& range, - base::string16* text) const { - return false; -} - -void DummyTextInputClient::OnInputMethodChanged() { -} - -bool DummyTextInputClient::ChangeTextDirectionAndLayoutAlignment( - base::i18n::TextDirection direction) { - return false; -} - -void DummyTextInputClient::ExtendSelectionAndDelete(size_t before, - size_t after) { -} - -void DummyTextInputClient::EnsureCaretInRect(const gfx::Rect& rect) { -} - -void DummyTextInputClient::OnCandidateWindowShown() { -} - -void DummyTextInputClient::OnCandidateWindowUpdated() { -} - -void DummyTextInputClient::OnCandidateWindowHidden() { -} - -bool DummyTextInputClient::IsEditingCommandEnabled(int command_id) { - return false; -} - -void DummyTextInputClient::ExecuteEditingCommand(int command_id) { -} - -} // namespace ui
diff --git a/ui/base/ime/dummy_text_input_client.h b/ui/base/ime/dummy_text_input_client.h deleted file mode 100644 index 898ffa2..0000000 --- a/ui/base/ime/dummy_text_input_client.h +++ /dev/null
@@ -1,58 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_DUMMY_TEXT_INPUT_CLIENT_H_ -#define UI_BASE_IME_DUMMY_TEXT_INPUT_CLIENT_H_ - -#include "ui/base/ime/text_input_client.h" - -namespace ui { - -// Dummy implementation of TextInputClient. All functions do nothing. -class DummyTextInputClient : public TextInputClient { - public: - DummyTextInputClient(); - explicit DummyTextInputClient(TextInputType text_input_type); - ~DummyTextInputClient() override; - - // Overriden from TextInputClient. - void SetCompositionText(const CompositionText& composition) override; - void ConfirmCompositionText() override; - void ClearCompositionText() override; - void InsertText(const base::string16& text) override; - void InsertChar(base::char16 ch, int flags) override; - gfx::NativeWindow GetAttachedWindow() const override; - TextInputType GetTextInputType() const override; - TextInputMode GetTextInputMode() const override; - bool CanComposeInline() const override; - gfx::Rect GetCaretBounds() const override; - bool GetCompositionCharacterBounds(uint32 index, - gfx::Rect* rect) const override; - bool HasCompositionText() const override; - bool GetTextRange(gfx::Range* range) const override; - bool GetCompositionTextRange(gfx::Range* range) const override; - bool GetSelectionRange(gfx::Range* range) const override; - bool SetSelectionRange(const gfx::Range& range) override; - bool DeleteRange(const gfx::Range& range) override; - bool GetTextFromRange(const gfx::Range& range, - base::string16* text) const override; - void OnInputMethodChanged() override; - bool ChangeTextDirectionAndLayoutAlignment( - base::i18n::TextDirection direction) override; - void ExtendSelectionAndDelete(size_t before, size_t after) override; - void EnsureCaretInRect(const gfx::Rect& rect) override; - void OnCandidateWindowShown() override; - void OnCandidateWindowUpdated() override; - void OnCandidateWindowHidden() override; - bool IsEditingCommandEnabled(int command_id) override; - void ExecuteEditingCommand(int command_id) override; - - TextInputType text_input_type_; - - DISALLOW_COPY_AND_ASSIGN(DummyTextInputClient); -}; - -} // namespace ui - -#endif // UI_BASE_IME_DUMMY_TEXT_INPUT_CLIENT_H_
diff --git a/ui/base/ime/infolist_entry.cc b/ui/base/ime/infolist_entry.cc deleted file mode 100644 index 7423f73..0000000 --- a/ui/base/ime/infolist_entry.cc +++ /dev/null
@@ -1,22 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/infolist_entry.h" - -namespace ui { - -InfolistEntry::InfolistEntry(const base::string16& title, - const base::string16& body) - : title(title), body(body), highlighted(false) {} - -bool InfolistEntry::operator==(const InfolistEntry& other) const { - return title == other.title && body == other.body && - highlighted == other.highlighted; -} - -bool InfolistEntry::operator!=(const InfolistEntry& other) const { - return !(*this == other); -} - -} // namespace ui
diff --git a/ui/base/ime/infolist_entry.h b/ui/base/ime/infolist_entry.h deleted file mode 100644 index 3cb7672..0000000 --- a/ui/base/ime/infolist_entry.h +++ /dev/null
@@ -1,26 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_INFOLIST_ENTRY_H_ -#define UI_BASE_IME_INFOLIST_ENTRY_H_ - -#include "base/strings/string16.h" -#include "ui/base/ui_base_export.h" - -namespace ui { - -// The data model of infolist window. -struct UI_BASE_EXPORT InfolistEntry { - base::string16 title; - base::string16 body; - bool highlighted; - - InfolistEntry(const base::string16& title, const base::string16& body); - bool operator==(const InfolistEntry& entry) const; - bool operator!=(const InfolistEntry& entry) const; -}; - -} // namespace ui - -#endif // UI_BASE_IME_INFOLIST_ENTRY_H_
diff --git a/ui/base/ime/input_method.h b/ui/base/ime/input_method.h deleted file mode 100644 index 462e0b0..0000000 --- a/ui/base/ime/input_method.h +++ /dev/null
@@ -1,167 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_INPUT_METHOD_H_ -#define UI_BASE_IME_INPUT_METHOD_H_ - -#include <string> - -#include "base/basictypes.h" -#include "base/event_types.h" -#include "ui/base/ime/text_input_mode.h" -#include "ui/base/ime/text_input_type.h" - -namespace ui { - -namespace internal { -class InputMethodDelegate; -} // namespace internal - -class InputMethodObserver; -class KeyEvent; -class TextInputClient; - -// An interface implemented by an object that encapsulates a native input method -// service provided by the underlying operating system, and acts as a "system -// wide" input method for all Chrome windows. A class that implements this -// interface should behave as follows: -// - Receives a keyboard event directly from a message dispatcher for the -// system through the InputMethod::DispatchKeyEvent API, and forwards it to -// an underlying input method for the OS. -// - The input method should handle the key event either of the following ways: -// 1) Send the original key down event to the focused window, which is e.g. -// a NativeWidgetAura (NWA) or a RenderWidgetHostViewAura (RWHVA), using -// internal::InputMethodDelegate::DispatchKeyEventPostIME API, then send -// a Char event using TextInputClient::InsertChar API to a text input -// client, which is, again, e.g. NWA or RWHVA, and then send the original -// key up event to the same window. -// 2) Send VKEY_PROCESSKEY event to the window using the DispatchKeyEvent API, -// then update IME status (e.g. composition text) using TextInputClient, -// and then send the original key up event to the window. -// - Keeps track of the focused TextInputClient to see which client can call -// APIs, OnTextInputTypeChanged, OnCaretBoundsChanged, and CancelComposition, -// that change the state of the input method. -// In Aura environment, aura::WindowTreeHost creates an instance of -// ui::InputMethod and owns it. -class InputMethod { - public: - -#if defined(OS_WIN) - typedef LRESULT NativeEventResult; -#else - typedef int32 NativeEventResult; -#endif - - virtual ~InputMethod() {} - - // Sets the delegate used by this InputMethod instance. It should only be - // called by an object which manages the whole UI. - virtual void SetDelegate(internal::InputMethodDelegate* delegate) = 0; - - // Initializes the InputMethod object. Pass true if the system toplevel window - // already has keyboard focus. - virtual void Init(bool focused) = 0; - - // Called when the top-level system window gets keyboard focus. - virtual void OnFocus() = 0; - - // Called when the top-level system window loses keyboard focus. - virtual void OnBlur() = 0; - - // Called when the focused window receives native IME messages that are not - // translated into other predefined event callbacks. Currently this method is - // used only for IME functionalities specific to Windows. - // TODO(ime): Break down these messages into platform-neutral methods. - virtual bool OnUntranslatedIMEMessage(const base::NativeEvent& event, - NativeEventResult* result) = 0; - - // Sets the text input client which receives text input events such as - // SetCompositionText(). |client| can be NULL. A gfx::NativeWindow which - // implementes TextInputClient interface, e.g. NWA and RWHVA, should register - // itself by calling the method when it is focused, and unregister itself by - // calling the method with NULL when it is unfocused. - virtual void SetFocusedTextInputClient(TextInputClient* client) = 0; - - // Detaches and forgets the |client| regardless of whether it has the focus or - // not. This method is meant to be called when the |client| is going to be - // destroyed. - virtual void DetachTextInputClient(TextInputClient* client) = 0; - - // Gets the current text input client. Returns NULL when no client is set. - virtual TextInputClient* GetTextInputClient() const = 0; - - // Dispatches a key event to the input method. The key event will be - // dispatched back to the caller via - // ui::InputMethodDelegate::DispatchKeyEventPostIME(), once it's processed by - // the input method. It should only be called by a message dispatcher. - // Returns true if the event was processed. - virtual bool DispatchKeyEvent(const ui::KeyEvent& event) = 0; - - // Called by the focused client whenever its text input type is changed. - // Before calling this method, the focused client must confirm or clear - // existing composition text and call InputMethod::CancelComposition() when - // necessary. Otherwise unexpected behavior may happen. This method has no - // effect if the client is not the focused client. - virtual void OnTextInputTypeChanged(const TextInputClient* client) = 0; - - // Called by the focused client whenever its caret bounds is changed. - // This method has no effect if the client is not the focused client. - virtual void OnCaretBoundsChanged(const TextInputClient* client) = 0; - - // Called by the focused client to ask the input method cancel the ongoing - // composition session. This method has no effect if the client is not the - // focused client. - virtual void CancelComposition(const TextInputClient* client) = 0; - - // Called by the focused client whenever its input locale is changed. - // This method is currently used only on Windows. - // This method does not take a parameter of TextInputClient for historical - // reasons. - // TODO(ime): Consider to take a parameter of TextInputClient. - virtual void OnInputLocaleChanged() = 0; - - // Returns the locale of current keyboard layout or input method, as a BCP-47 - // tag, or an empty string if the input method cannot provide it. - virtual std::string GetInputLocale() = 0; - - // Checks if the input method is active, i.e. if it's ready for processing - // keyboard event and generate composition or text result. - // If the input method is inactive, then it's not necessary to inform it the - // changes of caret bounds and text input type. - // Note: character results may still be generated and sent to the text input - // client by calling TextInputClient::InsertChar(), even if the input method - // is not active. - virtual bool IsActive() = 0; - - // TODO(yoichio): Following 3 methods(GetTextInputType, GetTextInputMode and - // CanComposeInline) calls client's same method and returns its value. It is - // not InputMethod itself's infomation. So rename these to - // GetClientTextInputType and so on. - // Gets the text input type of the focused text input client. Returns - // ui::TEXT_INPUT_TYPE_NONE if there is no focused client. - virtual TextInputType GetTextInputType() const = 0; - - // Gets the text input mode of the focused text input client. Returns - // ui::TEXT_INPUT_TYPE_DEFAULT if there is no focused client. - virtual TextInputMode GetTextInputMode() const = 0; - - // Checks if the focused text input client supports inline composition. - virtual bool CanComposeInline() const = 0; - - // Returns true if we know for sure that a candidate window (or IME suggest, - // etc.) is open. Returns false if no popup window is open or the detection - // of IME popups is not supported. - virtual bool IsCandidatePopupOpen() const = 0; - - // Displays an on screen keyboard if enabled. - virtual void ShowImeIfNeeded() = 0; - - // Management of the observer list. - virtual void AddObserver(InputMethodObserver* observer) = 0; - virtual void RemoveObserver(InputMethodObserver* observer) = 0; -}; - -} // namespace ui - -#endif // UI_BASE_IME_INPUT_METHOD_H_
diff --git a/ui/base/ime/input_method_auralinux.cc b/ui/base/ime/input_method_auralinux.cc deleted file mode 100644 index f5d4bee..0000000 --- a/ui/base/ime/input_method_auralinux.cc +++ /dev/null
@@ -1,182 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/input_method_auralinux.h" - -#include "base/environment.h" -#include "ui/base/ime/linux/linux_input_method_context_factory.h" -#include "ui/base/ime/text_input_client.h" -#include "ui/events/event.h" - -namespace ui { - -InputMethodAuraLinux::InputMethodAuraLinux( - internal::InputMethodDelegate* delegate) - : allowed_to_fire_vkey_process_key_(false), vkey_processkey_flags_(0) { - SetDelegate(delegate); -} - -InputMethodAuraLinux::~InputMethodAuraLinux() {} - -// Overriden from InputMethod. - -void InputMethodAuraLinux::Init(bool focused) { - CHECK(LinuxInputMethodContextFactory::instance()) - << "This failure was likely caused because " - << "ui::InitializeInputMethod(ForTesting) was not called " - << "before instantiating this class."; - input_method_context_ = - LinuxInputMethodContextFactory::instance()->CreateInputMethodContext( - this); - CHECK(input_method_context_.get()); - - InputMethodBase::Init(focused); - - if (focused) { - input_method_context_->OnTextInputTypeChanged( - GetTextInputClient() ? - GetTextInputClient()->GetTextInputType() : - TEXT_INPUT_TYPE_TEXT); - } -} - -bool InputMethodAuraLinux::OnUntranslatedIMEMessage( - const base::NativeEvent& event, - NativeEventResult* result) { - return false; -} - -bool InputMethodAuraLinux::DispatchKeyEvent(const ui::KeyEvent& event) { - DCHECK(event.type() == ET_KEY_PRESSED || event.type() == ET_KEY_RELEASED); - DCHECK(system_toplevel_window_focused()); - - // If no text input client, do nothing. - if (!GetTextInputClient()) - return DispatchKeyEventPostIME(event); - - // Let an IME handle the key event first, and allow to fire a VKEY_PROCESSKEY - // event for keydown events. Note that DOM Level 3 Events Sepc requires that - // only keydown events fire keyCode=229 events and not for keyup events. - if (event.type() == ET_KEY_PRESSED && - (event.flags() & ui::EF_IME_FABRICATED_KEY) == 0) - AllowToFireProcessKey(event); - if (input_method_context_->DispatchKeyEvent(event)) - return true; - StopFiringProcessKey(); - - // Otherwise, insert the character. - const bool handled = DispatchKeyEventPostIME(event); - if (event.type() == ET_KEY_PRESSED && GetTextInputClient()) { - const uint16 ch = event.GetCharacter(); - if (ch) { - GetTextInputClient()->InsertChar(ch, event.flags()); - return true; - } - } - return handled; -} - -void InputMethodAuraLinux::OnTextInputTypeChanged( - const TextInputClient* client) { - if (!IsTextInputClientFocused(client)) - return; - input_method_context_->Reset(); - // TODO(yoichio): Support inputmode HTML attribute. - input_method_context_->OnTextInputTypeChanged(client->GetTextInputType()); -} - -void InputMethodAuraLinux::OnCaretBoundsChanged(const TextInputClient* client) { - if (!IsTextInputClientFocused(client)) - return; - input_method_context_->OnCaretBoundsChanged( - GetTextInputClient()->GetCaretBounds()); -} - -void InputMethodAuraLinux::CancelComposition(const TextInputClient* client) { - if (!IsTextInputClientFocused(client)) - return; - input_method_context_->Reset(); - input_method_context_->OnTextInputTypeChanged(client->GetTextInputType()); -} - -void InputMethodAuraLinux::OnInputLocaleChanged() { -} - -std::string InputMethodAuraLinux::GetInputLocale() { - return ""; -} - -bool InputMethodAuraLinux::IsActive() { - // InputMethodAuraLinux is always ready and up. - return true; -} - -bool InputMethodAuraLinux::IsCandidatePopupOpen() const { - // There seems no way to detect candidate windows or any popups. - return false; -} - -// Overriden from ui::LinuxInputMethodContextDelegate - -void InputMethodAuraLinux::OnCommit(const base::string16& text) { - MaybeFireProcessKey(); - if (!IsTextInputTypeNone()) - GetTextInputClient()->InsertText(text); -} - -void InputMethodAuraLinux::OnPreeditChanged( - const CompositionText& composition_text) { - MaybeFireProcessKey(); - TextInputClient* text_input_client = GetTextInputClient(); - if (text_input_client) - text_input_client->SetCompositionText(composition_text); -} - -void InputMethodAuraLinux::OnPreeditEnd() { - MaybeFireProcessKey(); - TextInputClient* text_input_client = GetTextInputClient(); - if (text_input_client && text_input_client->HasCompositionText()) - text_input_client->ClearCompositionText(); -} - -void InputMethodAuraLinux::OnPreeditStart() { - MaybeFireProcessKey(); -} - -// Overridden from InputMethodBase. - -void InputMethodAuraLinux::OnDidChangeFocusedClient( - TextInputClient* focused_before, - TextInputClient* focused) { - input_method_context_->Reset(); - input_method_context_->OnTextInputTypeChanged( - focused ? focused->GetTextInputType() : TEXT_INPUT_TYPE_NONE); - - InputMethodBase::OnDidChangeFocusedClient(focused_before, focused); -} - -// Helper functions to support VKEY_PROCESSKEY. - -void InputMethodAuraLinux::AllowToFireProcessKey(const ui::KeyEvent& event) { - allowed_to_fire_vkey_process_key_ = true; - vkey_processkey_flags_ = event.flags(); -} - -void InputMethodAuraLinux::MaybeFireProcessKey() { - if (!allowed_to_fire_vkey_process_key_) - return; - - const ui::KeyEvent fabricated_event(ET_KEY_PRESSED, - VKEY_PROCESSKEY, - vkey_processkey_flags_); - DispatchKeyEventPostIME(fabricated_event); - StopFiringProcessKey(); -} - -void InputMethodAuraLinux::StopFiringProcessKey() { - allowed_to_fire_vkey_process_key_ = false; - vkey_processkey_flags_ = 0; -} - -} // namespace ui
diff --git a/ui/base/ime/input_method_auralinux.h b/ui/base/ime/input_method_auralinux.h deleted file mode 100644 index 505abbd..0000000 --- a/ui/base/ime/input_method_auralinux.h +++ /dev/null
@@ -1,84 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_INPUT_METHOD_AURALINUX_H_ -#define UI_BASE_IME_INPUT_METHOD_AURALINUX_H_ - -#include "base/memory/scoped_ptr.h" -#include "ui/base/ime/input_method_base.h" -#include "ui/base/ime/linux/linux_input_method_context.h" - -namespace ui { - -// A ui::InputMethod implementation for Aura on Linux platforms. The -// implementation details are separated to ui::LinuxInputMethodContext -// interface. -class UI_BASE_EXPORT InputMethodAuraLinux - : public InputMethodBase, - public LinuxInputMethodContextDelegate { - public: - explicit InputMethodAuraLinux(internal::InputMethodDelegate* delegate); - virtual ~InputMethodAuraLinux(); - - // Overriden from InputMethod. - virtual void Init(bool focused) override; - virtual bool OnUntranslatedIMEMessage(const base::NativeEvent& event, - NativeEventResult* result) override; - virtual bool DispatchKeyEvent(const ui::KeyEvent& event) override; - virtual void OnTextInputTypeChanged(const TextInputClient* client) override; - virtual void OnCaretBoundsChanged(const TextInputClient* client) override; - virtual void CancelComposition(const TextInputClient* client) override; - virtual void OnInputLocaleChanged() override; - virtual std::string GetInputLocale() override; - virtual bool IsActive() override; - virtual bool IsCandidatePopupOpen() const override; - - // Overriden from ui::LinuxInputMethodContextDelegate - virtual void OnCommit(const base::string16& text) override; - virtual void OnPreeditChanged(const CompositionText& composition_text) - override; - virtual void OnPreeditEnd() override; - virtual void OnPreeditStart() override; - - protected: - // Overridden from InputMethodBase. - virtual void OnDidChangeFocusedClient(TextInputClient* focused_before, - TextInputClient* focused) override; - - private: - // Allows to fire a VKEY_PROCESSKEY key event. - void AllowToFireProcessKey(const ui::KeyEvent& event); - // Fires a VKEY_PROCESSKEY key event if allowed. - void MaybeFireProcessKey(); - // Stops firing VKEY_PROCESSKEY key events. - void StopFiringProcessKey(); - - scoped_ptr<LinuxInputMethodContext> input_method_context_; - - // IBus in async mode eagerly consumes all the key events first regardless of - // whether the underlying IME consumes the key event or not, and makes - // gtk_im_context_filter_keypress() always return true, and later pushes - // the key event back to the GDK event queue when it turns out that the - // underlying IME doesn't consume the key event. - // - // Thus we have to defer a decision whether or not to dispatch a - // VKEY_PROCESSKEY key event. Unlike other InputMethod's subclasses, - // DispatchKeyEvent() in this class does not directly dispatch a - // VKEY_PROCESSKEY event, OnCommit or OnPreedit{Start,Changed,End} dispatch - // a VKEY_PROCESSKEY event instead. - // - // Because of this hack, there could be chances that we accidentally dispatch - // VKEY_PROCESSKEY events and other key events in out of order. - // - // |allowed_to_fire_vkey_process_key_| is used not to dispatch a - // VKEY_PROCESSKEY event twice for a single key event. - bool allowed_to_fire_vkey_process_key_; - int vkey_processkey_flags_; - - DISALLOW_COPY_AND_ASSIGN(InputMethodAuraLinux); -}; - -} // namespace ui - -#endif // UI_BASE_IME_INPUT_METHOD_AURALINUX_H_
diff --git a/ui/base/ime/input_method_base.cc b/ui/base/ime/input_method_base.cc deleted file mode 100644 index ed34767..0000000 --- a/ui/base/ime/input_method_base.cc +++ /dev/null
@@ -1,177 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/input_method_base.h" - -#include "base/bind.h" -#include "base/logging.h" -#include "base/message_loop/message_loop.h" -#include "ui/base/ime/input_method_delegate.h" -#include "ui/base/ime/input_method_observer.h" -#include "ui/base/ime/text_input_client.h" -#include "ui/base/ime/text_input_focus_manager.h" -#include "ui/base/ui_base_switches_util.h" -#include "ui/events/event.h" - -namespace ui { - -InputMethodBase::InputMethodBase() - : delegate_(NULL), - text_input_client_(NULL), - system_toplevel_window_focused_(false) { -} - -InputMethodBase::~InputMethodBase() { - FOR_EACH_OBSERVER(InputMethodObserver, - observer_list_, - OnInputMethodDestroyed(this)); -} - -void InputMethodBase::SetDelegate(internal::InputMethodDelegate* delegate) { - delegate_ = delegate; -} - -void InputMethodBase::Init(bool focused) { - if (focused) - OnFocus(); -} - -void InputMethodBase::OnFocus() { - DCHECK(!system_toplevel_window_focused_); - system_toplevel_window_focused_ = true; -} - -void InputMethodBase::OnBlur() { - DCHECK(system_toplevel_window_focused_); - system_toplevel_window_focused_ = false; -} - -void InputMethodBase::SetFocusedTextInputClient(TextInputClient* client) { - SetFocusedTextInputClientInternal(client); -} - -void InputMethodBase::DetachTextInputClient(TextInputClient* client) { - if (text_input_client_ != client) - return; - SetFocusedTextInputClientInternal(NULL); -} - -TextInputClient* InputMethodBase::GetTextInputClient() const { - if (switches::IsTextInputFocusManagerEnabled()) - return TextInputFocusManager::GetInstance()->GetFocusedTextInputClient(); - - return system_toplevel_window_focused_ ? text_input_client_ : NULL; -} - -void InputMethodBase::OnTextInputTypeChanged(const TextInputClient* client) { - if (!IsTextInputClientFocused(client)) - return; - NotifyTextInputStateChanged(client); -} - -TextInputType InputMethodBase::GetTextInputType() const { - TextInputClient* client = GetTextInputClient(); - return client ? client->GetTextInputType() : TEXT_INPUT_TYPE_NONE; -} - -TextInputMode InputMethodBase::GetTextInputMode() const { - TextInputClient* client = GetTextInputClient(); - return client ? client->GetTextInputMode() : TEXT_INPUT_MODE_DEFAULT; -} - -bool InputMethodBase::CanComposeInline() const { - TextInputClient* client = GetTextInputClient(); - return client ? client->CanComposeInline() : true; -} - -void InputMethodBase::ShowImeIfNeeded() { - FOR_EACH_OBSERVER(InputMethodObserver, observer_list_, OnShowImeIfNeeded()); -} - -void InputMethodBase::AddObserver(InputMethodObserver* observer) { - observer_list_.AddObserver(observer); -} - -void InputMethodBase::RemoveObserver(InputMethodObserver* observer) { - observer_list_.RemoveObserver(observer); -} - -bool InputMethodBase::IsTextInputClientFocused(const TextInputClient* client) { - return client && (client == GetTextInputClient()); -} - -bool InputMethodBase::IsTextInputTypeNone() const { - return GetTextInputType() == TEXT_INPUT_TYPE_NONE; -} - -void InputMethodBase::OnInputMethodChanged() const { - TextInputClient* client = GetTextInputClient(); - if (!IsTextInputTypeNone()) - client->OnInputMethodChanged(); -} - -bool InputMethodBase::DispatchKeyEventPostIME( - const ui::KeyEvent& event) const { - if (!delegate_) - return false; - - return delegate_->DispatchKeyEventPostIME(event); -} - -void InputMethodBase::NotifyTextInputStateChanged( - const TextInputClient* client) { - FOR_EACH_OBSERVER(InputMethodObserver, - observer_list_, - OnTextInputStateChanged(client)); -} - -void InputMethodBase::SetFocusedTextInputClientInternal( - TextInputClient* client) { - if (switches::IsTextInputFocusManagerEnabled()) - return; - - TextInputClient* old = text_input_client_; - if (old == client) - return; - OnWillChangeFocusedClient(old, client); - text_input_client_ = client; // NULL allowed. - OnDidChangeFocusedClient(old, client); - NotifyTextInputStateChanged(text_input_client_); -} - -void InputMethodBase::OnCandidateWindowShown() { - base::MessageLoop::current()->PostTask( - FROM_HERE, - base::Bind(&InputMethodBase::CandidateWindowShownCallback, AsWeakPtr())); -} - -void InputMethodBase::OnCandidateWindowUpdated() { - base::MessageLoop::current()->PostTask( - FROM_HERE, - base::Bind(&InputMethodBase::CandidateWindowUpdatedCallback, - AsWeakPtr())); -} - -void InputMethodBase::OnCandidateWindowHidden() { - base::MessageLoop::current()->PostTask( - FROM_HERE, - base::Bind(&InputMethodBase::CandidateWindowHiddenCallback, AsWeakPtr())); -} - -void InputMethodBase::CandidateWindowShownCallback() { - if (TextInputClient* text_input_client = GetTextInputClient()) - text_input_client->OnCandidateWindowShown(); -} - -void InputMethodBase::CandidateWindowUpdatedCallback() { - if (TextInputClient* text_input_client = GetTextInputClient()) - text_input_client->OnCandidateWindowUpdated(); -} - -void InputMethodBase::CandidateWindowHiddenCallback() { - if (TextInputClient* text_input_client = GetTextInputClient()) - text_input_client->OnCandidateWindowHidden(); -} - -} // namespace ui
diff --git a/ui/base/ime/input_method_base.h b/ui/base/ime/input_method_base.h deleted file mode 100644 index 8c6dd25..0000000 --- a/ui/base/ime/input_method_base.h +++ /dev/null
@@ -1,117 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_INPUT_METHOD_BASE_H_ -#define UI_BASE_IME_INPUT_METHOD_BASE_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/memory/weak_ptr.h" -#include "base/observer_list.h" -#include "ui/base/ime/input_method.h" -#include "ui/base/ui_base_export.h" - -namespace gfx { -class Rect; -} // namespace gfx - -namespace ui { - -class InputMethodObserver; -class KeyEvent; -class TextInputClient; - -// A helper class providing functionalities shared among ui::InputMethod -// implementations. -class UI_BASE_EXPORT InputMethodBase - : NON_EXPORTED_BASE(public InputMethod), - public base::SupportsWeakPtr<InputMethodBase> { - public: - InputMethodBase(); - ~InputMethodBase() override; - - // Overriden from InputMethod. - void SetDelegate(internal::InputMethodDelegate* delegate) override; - void Init(bool focused) override; - // If a derived class overrides OnFocus()/OnBlur(), it should call parent's - // implementation first, to make sure |system_toplevel_window_focused_| flag - // can be updated correctly. - void OnFocus() override; - void OnBlur() override; - void SetFocusedTextInputClient(TextInputClient* client) override; - void DetachTextInputClient(TextInputClient* client) override; - TextInputClient* GetTextInputClient() const override; - - // If a derived class overrides this method, it should call parent's - // implementation. - void OnTextInputTypeChanged(const TextInputClient* client) override; - - TextInputType GetTextInputType() const override; - TextInputMode GetTextInputMode() const override; - bool CanComposeInline() const override; - void ShowImeIfNeeded() override; - - void AddObserver(InputMethodObserver* observer) override; - void RemoveObserver(InputMethodObserver* observer) override; - - protected: - virtual void OnWillChangeFocusedClient(TextInputClient* focused_before, - TextInputClient* focused) {} - virtual void OnDidChangeFocusedClient(TextInputClient* focused_before, - TextInputClient* focused) {} - - // Returns true if |client| is currently focused. - bool IsTextInputClientFocused(const TextInputClient* client); - - // Checks if the focused text input client's text input type is - // TEXT_INPUT_TYPE_NONE. Also returns true if there is no focused text - // input client. - bool IsTextInputTypeNone() const; - - // Convenience method to call the focused text input client's - // OnInputMethodChanged() method. It'll only take effect if the current text - // input type is not TEXT_INPUT_TYPE_NONE. - void OnInputMethodChanged() const; - - // Convenience method to call delegate_->DispatchKeyEventPostIME(). - // Returns true if the event was processed - bool DispatchKeyEventPostIME(const ui::KeyEvent& event) const; - - // Convenience method to notify all observers of TextInputClient changes. - void NotifyTextInputStateChanged(const TextInputClient* client); - - // Interface for for signalling candidate window events. - // See also *Callback functions below. To avoid reentrancy issue that - // TextInputClient manipulates IME state during even handling, these methods - // defer sending actual signals to renderer. - void OnCandidateWindowShown(); - void OnCandidateWindowUpdated(); - void OnCandidateWindowHidden(); - - bool system_toplevel_window_focused() const { - return system_toplevel_window_focused_; - } - - private: - void SetFocusedTextInputClientInternal(TextInputClient* client); - - // Deferred callbacks for signalling TextInputClient about candidate window - // appearance changes. - void CandidateWindowShownCallback(); - void CandidateWindowUpdatedCallback(); - void CandidateWindowHiddenCallback(); - - internal::InputMethodDelegate* delegate_; - TextInputClient* text_input_client_; - - ObserverList<InputMethodObserver> observer_list_; - - bool system_toplevel_window_focused_; - - DISALLOW_COPY_AND_ASSIGN(InputMethodBase); -}; - -} // namespace ui - -#endif // UI_BASE_IME_INPUT_METHOD_BASE_H_
diff --git a/ui/base/ime/input_method_base_unittest.cc b/ui/base/ime/input_method_base_unittest.cc deleted file mode 100644 index 48d0c09..0000000 --- a/ui/base/ime/input_method_base_unittest.cc +++ /dev/null
@@ -1,394 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/input_method_base.h" - -#include "base/gtest_prod_util.h" -#include "base/memory/scoped_ptr.h" -#include "base/message_loop/message_loop.h" -#include "base/run_loop.h" -#include "base/scoped_observer.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/base/ime/dummy_text_input_client.h" -#include "ui/base/ime/input_method_observer.h" -#include "ui/base/ime/text_input_focus_manager.h" -#include "ui/base/ui_base_switches_util.h" -#include "ui/events/event.h" - -namespace ui { -namespace { - -class ClientChangeVerifier { - public: - ClientChangeVerifier() - : previous_client_(NULL), - next_client_(NULL), - call_expected_(false), - on_will_change_focused_client_called_(false), - on_did_change_focused_client_called_(false), - on_text_input_state_changed_(false) { - } - - // Expects that focused text input client will not be changed. - void ExpectClientDoesNotChange() { - previous_client_ = NULL; - next_client_ = NULL; - call_expected_ = false; - on_will_change_focused_client_called_ = false; - on_did_change_focused_client_called_ = false; - on_text_input_state_changed_ = false; - } - - // Expects that focused text input client will be changed from - // |previous_client| to |next_client|. - void ExpectClientChange(TextInputClient* previous_client, - TextInputClient* next_client) { - previous_client_ = previous_client; - next_client_ = next_client; - call_expected_ = true; - on_will_change_focused_client_called_ = false; - on_did_change_focused_client_called_ = false; - on_text_input_state_changed_ = false; - } - - // Verifies the result satisfies the expectation or not. - void Verify() { - if (switches::IsTextInputFocusManagerEnabled()) { - EXPECT_FALSE(on_will_change_focused_client_called_); - EXPECT_FALSE(on_did_change_focused_client_called_); - EXPECT_FALSE(on_text_input_state_changed_); - } else { - EXPECT_EQ(call_expected_, on_will_change_focused_client_called_); - EXPECT_EQ(call_expected_, on_did_change_focused_client_called_); - EXPECT_EQ(call_expected_, on_text_input_state_changed_); - } - } - - void OnWillChangeFocusedClient(TextInputClient* focused_before, - TextInputClient* focused) { - EXPECT_TRUE(call_expected_); - - // Check arguments - EXPECT_EQ(previous_client_, focused_before); - EXPECT_EQ(next_client_, focused); - - // Check call order - EXPECT_FALSE(on_will_change_focused_client_called_); - EXPECT_FALSE(on_did_change_focused_client_called_); - EXPECT_FALSE(on_text_input_state_changed_); - - on_will_change_focused_client_called_ = true; - } - - void OnDidChangeFocusedClient(TextInputClient* focused_before, - TextInputClient* focused) { - EXPECT_TRUE(call_expected_); - - // Check arguments - EXPECT_EQ(previous_client_, focused_before); - EXPECT_EQ(next_client_, focused); - - // Check call order - EXPECT_TRUE(on_will_change_focused_client_called_); - EXPECT_FALSE(on_did_change_focused_client_called_); - EXPECT_FALSE(on_text_input_state_changed_); - - on_did_change_focused_client_called_ = true; - } - - void OnTextInputStateChanged(const TextInputClient* client) { - EXPECT_TRUE(call_expected_); - - // Check arguments - EXPECT_EQ(next_client_, client); - - // Check call order - EXPECT_TRUE(on_will_change_focused_client_called_); - EXPECT_TRUE(on_did_change_focused_client_called_); - EXPECT_FALSE(on_text_input_state_changed_); - - on_text_input_state_changed_ = true; - } - - private: - TextInputClient* previous_client_; - TextInputClient* next_client_; - bool call_expected_; - bool on_will_change_focused_client_called_; - bool on_did_change_focused_client_called_; - bool on_text_input_state_changed_; - - DISALLOW_COPY_AND_ASSIGN(ClientChangeVerifier); -}; - -class InputMethodBaseTest : public testing::Test { - protected: - InputMethodBaseTest() { - } - virtual ~InputMethodBaseTest() { - } - - virtual void SetUp() { - message_loop_.reset(new base::MessageLoopForUI); - } - - virtual void TearDown() { - message_loop_.reset(); - } - - private: - scoped_ptr<base::MessageLoop> message_loop_; - DISALLOW_COPY_AND_ASSIGN(InputMethodBaseTest); -}; - -class MockInputMethodBase : public InputMethodBase { - public: - // Note: this class does not take the ownership of |verifier|. - MockInputMethodBase(ClientChangeVerifier* verifier) : verifier_(verifier) { - } - ~MockInputMethodBase() override {} - - private: - // Overriden from InputMethod. - bool OnUntranslatedIMEMessage( - const base::NativeEvent& event, - InputMethod::NativeEventResult* result) override { - return false; - } - bool DispatchKeyEvent(const ui::KeyEvent&) override { return false; } - void OnCaretBoundsChanged(const TextInputClient* client) override {} - void CancelComposition(const TextInputClient* client) override {} - void OnInputLocaleChanged() override {} - std::string GetInputLocale() override { return ""; } - bool IsActive() override { return false; } - bool IsCandidatePopupOpen() const override { return false; } - // Overriden from InputMethodBase. - void OnWillChangeFocusedClient(TextInputClient* focused_before, - TextInputClient* focused) override { - verifier_->OnWillChangeFocusedClient(focused_before, focused); - } - - void OnDidChangeFocusedClient(TextInputClient* focused_before, - TextInputClient* focused) override { - verifier_->OnDidChangeFocusedClient(focused_before, focused); - } - - ClientChangeVerifier* verifier_; - - FRIEND_TEST_ALL_PREFIXES(InputMethodBaseTest, CandidateWindowEvents); - DISALLOW_COPY_AND_ASSIGN(MockInputMethodBase); -}; - -class MockInputMethodObserver : public InputMethodObserver { - public: - // Note: this class does not take the ownership of |verifier|. - explicit MockInputMethodObserver(ClientChangeVerifier* verifier) - : verifier_(verifier) { - } - ~MockInputMethodObserver() override {} - - private: - void OnTextInputTypeChanged(const TextInputClient* client) override {} - void OnFocus() override {} - void OnBlur() override {} - void OnCaretBoundsChanged(const TextInputClient* client) override {} - void OnTextInputStateChanged(const TextInputClient* client) override { - verifier_->OnTextInputStateChanged(client); - } - void OnShowImeIfNeeded() override {} - void OnInputMethodDestroyed(const InputMethod* client) override {} - - ClientChangeVerifier* verifier_; - DISALLOW_COPY_AND_ASSIGN(MockInputMethodObserver); -}; - -class MockTextInputClient : public DummyTextInputClient { - public: - MockTextInputClient() - : shown_event_count_(0), updated_event_count_(0), hidden_event_count_(0) { - } - ~MockTextInputClient() override {} - - void OnCandidateWindowShown() override { ++shown_event_count_; } - void OnCandidateWindowUpdated() override { ++updated_event_count_; } - void OnCandidateWindowHidden() override { ++hidden_event_count_; } - - int shown_event_count() const { return shown_event_count_; } - int updated_event_count() const { return updated_event_count_; } - int hidden_event_count() const { return hidden_event_count_; } - - private: - int shown_event_count_; - int updated_event_count_; - int hidden_event_count_; -}; - -typedef ScopedObserver<InputMethod, InputMethodObserver> - InputMethodScopedObserver; - -void SetFocusedTextInputClient(InputMethod* input_method, - TextInputClient* text_input_client) { - if (switches::IsTextInputFocusManagerEnabled()) { - TextInputFocusManager::GetInstance()->FocusTextInputClient( - text_input_client); - } else { - input_method->SetFocusedTextInputClient(text_input_client); - } -} - -TEST_F(InputMethodBaseTest, SetFocusedTextInputClient) { - DummyTextInputClient text_input_client_1st; - DummyTextInputClient text_input_client_2nd; - - ClientChangeVerifier verifier; - MockInputMethodBase input_method(&verifier); - MockInputMethodObserver input_method_observer(&verifier); - InputMethodScopedObserver scoped_observer(&input_method_observer); - scoped_observer.Add(&input_method); - - // Assume that the top-level-widget gains focus. - input_method.OnFocus(); - - { - SCOPED_TRACE("Focus from NULL to 1st TextInputClient"); - - ASSERT_EQ(NULL, input_method.GetTextInputClient()); - verifier.ExpectClientChange(NULL, &text_input_client_1st); - SetFocusedTextInputClient(&input_method, &text_input_client_1st); - EXPECT_EQ(&text_input_client_1st, input_method.GetTextInputClient()); - verifier.Verify(); - } - - { - SCOPED_TRACE("Redundant focus events must be ignored"); - verifier.ExpectClientDoesNotChange(); - SetFocusedTextInputClient(&input_method, &text_input_client_1st); - verifier.Verify(); - } - - { - SCOPED_TRACE("Focus from 1st to 2nd TextInputClient"); - - ASSERT_EQ(&text_input_client_1st, input_method.GetTextInputClient()); - verifier.ExpectClientChange(&text_input_client_1st, - &text_input_client_2nd); - SetFocusedTextInputClient(&input_method, &text_input_client_2nd); - EXPECT_EQ(&text_input_client_2nd, input_method.GetTextInputClient()); - verifier.Verify(); - } - - { - SCOPED_TRACE("Focus from 2nd TextInputClient to NULL"); - - ASSERT_EQ(&text_input_client_2nd, input_method.GetTextInputClient()); - verifier.ExpectClientChange(&text_input_client_2nd, NULL); - SetFocusedTextInputClient(&input_method, NULL); - EXPECT_EQ(NULL, input_method.GetTextInputClient()); - verifier.Verify(); - } - - { - SCOPED_TRACE("Redundant focus events must be ignored"); - verifier.ExpectClientDoesNotChange(); - SetFocusedTextInputClient(&input_method, NULL); - verifier.Verify(); - } -} - -TEST_F(InputMethodBaseTest, DetachTextInputClient) { - // DetachTextInputClient is not supported when IsTextInputFocusManagerEnabled. - if (switches::IsTextInputFocusManagerEnabled()) - return; - - DummyTextInputClient text_input_client; - DummyTextInputClient text_input_client_the_other; - - ClientChangeVerifier verifier; - MockInputMethodBase input_method(&verifier); - MockInputMethodObserver input_method_observer(&verifier); - InputMethodScopedObserver scoped_observer(&input_method_observer); - scoped_observer.Add(&input_method); - - // Assume that the top-level-widget gains focus. - input_method.OnFocus(); - - // Initialize for the next test. - { - verifier.ExpectClientChange(NULL, &text_input_client); - input_method.SetFocusedTextInputClient(&text_input_client); - verifier.Verify(); - } - - { - SCOPED_TRACE("DetachTextInputClient must be ignored for other clients"); - ASSERT_EQ(&text_input_client, input_method.GetTextInputClient()); - verifier.ExpectClientDoesNotChange(); - input_method.DetachTextInputClient(&text_input_client_the_other); - EXPECT_EQ(&text_input_client, input_method.GetTextInputClient()); - verifier.Verify(); - } - - { - SCOPED_TRACE("DetachTextInputClient must succeed even after the " - "top-level loses the focus"); - - ASSERT_EQ(&text_input_client, input_method.GetTextInputClient()); - input_method.OnBlur(); - input_method.OnFocus(); - verifier.ExpectClientChange(&text_input_client, NULL); - input_method.DetachTextInputClient(&text_input_client); - EXPECT_EQ(NULL, input_method.GetTextInputClient()); - verifier.Verify(); - } -} - -TEST_F(InputMethodBaseTest, CandidateWindowEvents) { - MockTextInputClient text_input_client; - - { - ClientChangeVerifier verifier; - MockInputMethodBase input_method_base(&verifier); - input_method_base.OnFocus(); - - verifier.ExpectClientChange(NULL, &text_input_client); - SetFocusedTextInputClient(&input_method_base, &text_input_client); - - EXPECT_EQ(0, text_input_client.shown_event_count()); - EXPECT_EQ(0, text_input_client.updated_event_count()); - EXPECT_EQ(0, text_input_client.hidden_event_count()); - - input_method_base.OnCandidateWindowShown(); - base::RunLoop().RunUntilIdle(); - - EXPECT_EQ(1, text_input_client.shown_event_count()); - EXPECT_EQ(0, text_input_client.updated_event_count()); - EXPECT_EQ(0, text_input_client.hidden_event_count()); - - input_method_base.OnCandidateWindowUpdated(); - base::RunLoop().RunUntilIdle(); - - EXPECT_EQ(1, text_input_client.shown_event_count()); - EXPECT_EQ(1, text_input_client.updated_event_count()); - EXPECT_EQ(0, text_input_client.hidden_event_count()); - - input_method_base.OnCandidateWindowHidden(); - base::RunLoop().RunUntilIdle(); - - EXPECT_EQ(1, text_input_client.shown_event_count()); - EXPECT_EQ(1, text_input_client.updated_event_count()); - EXPECT_EQ(1, text_input_client.hidden_event_count()); - - input_method_base.OnCandidateWindowShown(); - } - - // If InputMethod is deleted immediately after an event happens, but before - // its callback is invoked, the callback will be cancelled. - base::RunLoop().RunUntilIdle(); - EXPECT_EQ(1, text_input_client.shown_event_count()); - EXPECT_EQ(1, text_input_client.updated_event_count()); - EXPECT_EQ(1, text_input_client.hidden_event_count()); -} - -} // namespace -} // namespace ui
diff --git a/ui/base/ime/input_method_chromeos.cc b/ui/base/ime/input_method_chromeos.cc deleted file mode 100644 index 6930968..0000000 --- a/ui/base/ime/input_method_chromeos.cc +++ /dev/null
@@ -1,662 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/input_method_chromeos.h" - -#include <algorithm> -#include <cstring> -#include <set> -#include <vector> - -#include "base/basictypes.h" -#include "base/bind.h" -#include "base/i18n/char_iterator.h" -#include "base/logging.h" -#include "base/strings/string_util.h" -#include "base/strings/utf_string_conversions.h" -#include "base/sys_info.h" -#include "base/third_party/icu/icu_utf.h" -#include "chromeos/ime/composition_text.h" -#include "chromeos/ime/ime_keyboard.h" -#include "chromeos/ime/input_method_manager.h" -#include "ui/base/ime/text_input_client.h" -#include "ui/events/event.h" -#include "ui/gfx/rect.h" - -namespace { -chromeos::IMEEngineHandlerInterface* GetEngine() { - return chromeos::IMEBridge::Get()->GetCurrentEngineHandler(); -} -} // namespace - -namespace ui { - -// InputMethodChromeOS implementation ----------------------------------------- -InputMethodChromeOS::InputMethodChromeOS( - internal::InputMethodDelegate* delegate) - : composing_text_(false), - composition_changed_(false), - current_keyevent_id_(0), - weak_ptr_factory_(this) { - SetDelegate(delegate); - chromeos::IMEBridge::Get()->SetInputContextHandler(this); - - UpdateContextFocusState(); -} - -InputMethodChromeOS::~InputMethodChromeOS() { - AbandonAllPendingKeyEvents(); - ConfirmCompositionText(); - // We are dead, so we need to ask the client to stop relying on us. - OnInputMethodChanged(); - - chromeos::IMEBridge::Get()->SetInputContextHandler(NULL); -} - -void InputMethodChromeOS::OnFocus() { - InputMethodBase::OnFocus(); - OnTextInputTypeChanged(GetTextInputClient()); -} - -void InputMethodChromeOS::OnBlur() { - ConfirmCompositionText(); - InputMethodBase::OnBlur(); - OnTextInputTypeChanged(GetTextInputClient()); -} - -bool InputMethodChromeOS::OnUntranslatedIMEMessage( - const base::NativeEvent& event, - NativeEventResult* result) { - return false; -} - -void InputMethodChromeOS::ProcessKeyEventDone(uint32 id, - ui::KeyEvent* event, - bool is_handled) { - if (pending_key_events_.find(id) == pending_key_events_.end()) - return; // Abandoned key event. - - DCHECK(event); - if (event->type() == ET_KEY_PRESSED) { - if (is_handled) { - // IME event has a priority to be handled, so that character composer - // should be reset. - character_composer_.Reset(); - } else { - // If IME does not handle key event, passes keyevent to character composer - // to be able to compose complex characters. - is_handled = ExecuteCharacterComposer(*event); - } - } - - if (event->type() == ET_KEY_PRESSED || event->type() == ET_KEY_RELEASED) - ProcessKeyEventPostIME(*event, is_handled); - - // ProcessKeyEventPostIME may change the |pending_key_events_|. - pending_key_events_.erase(id); -} - -bool InputMethodChromeOS::DispatchKeyEvent(const ui::KeyEvent& event) { - DCHECK(event.type() == ET_KEY_PRESSED || event.type() == ET_KEY_RELEASED); - DCHECK(system_toplevel_window_focused()); - - // For linux_chromeos, the ime keyboard cannot track the caps lock state by - // itself, so need to call SetCapsLockEnabled() method to reflect the caps - // lock state by the key event. - if (!base::SysInfo::IsRunningOnChromeOS()) { - chromeos::input_method::InputMethodManager* manager = - chromeos::input_method::InputMethodManager::Get(); - if (manager) { - chromeos::input_method::ImeKeyboard* keyboard = manager->GetImeKeyboard(); - if (keyboard && event.type() == ui::ET_KEY_PRESSED) { - bool caps = (event.key_code() == ui::VKEY_CAPITAL) - ? !keyboard->CapsLockIsEnabled() - : (event.flags() & EF_CAPS_LOCK_DOWN); - keyboard->SetCapsLockEnabled(caps); - } - } - } - - // If |context_| is not usable, then we can only dispatch the key event as is. - // We only dispatch the key event to input method when the |context_| is an - // normal input field (not a password field). - // Note: We need to send the key event to ibus even if the |context_| is not - // enabled, so that ibus can have a chance to enable the |context_|. - if (!IsInputFieldFocused() || !GetEngine()) { - if (event.type() == ET_KEY_PRESSED) { - if (ExecuteCharacterComposer(event)) { - // Treating as PostIME event if character composer handles key event and - // generates some IME event, - ProcessKeyEventPostIME(event, true); - return true; - } - ProcessUnfilteredKeyPressEvent(event); - } else { - DispatchKeyEventPostIME(event); - } - return true; - } - - pending_key_events_.insert(current_keyevent_id_); - - ui::KeyEvent* copied_event = new ui::KeyEvent(event); - GetEngine()->ProcessKeyEvent( - event, - base::Bind(&InputMethodChromeOS::ProcessKeyEventDone, - weak_ptr_factory_.GetWeakPtr(), - current_keyevent_id_, - // Pass the ownership of |copied_event|. - base::Owned(copied_event))); - - ++current_keyevent_id_; - return true; -} - -void InputMethodChromeOS::OnTextInputTypeChanged( - const TextInputClient* client) { - if (!IsTextInputClientFocused(client)) - return; - - UpdateContextFocusState(); - - chromeos::IMEEngineHandlerInterface* engine = GetEngine(); - if (engine) { - // When focused input client is not changed, a text input type change should - // cause blur/focus events to engine. - // The focus in to or out from password field should also notify engine. - engine->FocusOut(); - chromeos::IMEEngineHandlerInterface::InputContext context( - GetTextInputType(), GetTextInputMode()); - engine->FocusIn(context); - } - - InputMethodBase::OnTextInputTypeChanged(client); -} - -void InputMethodChromeOS::OnCaretBoundsChanged(const TextInputClient* client) { - if (!IsInputFieldFocused() || !IsTextInputClientFocused(client)) - return; - - // The current text input type should not be NONE if |context_| is focused. - DCHECK(!IsTextInputTypeNone()); - const gfx::Rect rect = GetTextInputClient()->GetCaretBounds(); - - gfx::Rect composition_head; - if (!GetTextInputClient()->GetCompositionCharacterBounds(0, - &composition_head)) { - composition_head = rect; - } - - chromeos::IMECandidateWindowHandlerInterface* candidate_window = - chromeos::IMEBridge::Get()->GetCandidateWindowHandler(); - if (!candidate_window) - return; - candidate_window->SetCursorBounds(rect, composition_head); - - gfx::Range text_range; - gfx::Range selection_range; - base::string16 surrounding_text; - if (!GetTextInputClient()->GetTextRange(&text_range) || - !GetTextInputClient()->GetTextFromRange(text_range, &surrounding_text) || - !GetTextInputClient()->GetSelectionRange(&selection_range)) { - previous_surrounding_text_.clear(); - previous_selection_range_ = gfx::Range::InvalidRange(); - return; - } - - if (previous_selection_range_ == selection_range && - previous_surrounding_text_ == surrounding_text) - return; - - previous_selection_range_ = selection_range; - previous_surrounding_text_ = surrounding_text; - - if (!selection_range.IsValid()) { - // TODO(nona): Ideally selection_range should not be invalid. - // TODO(nona): If javascript changes the focus on page loading, even (0,0) - // can not be obtained. Need investigation. - return; - } - - // Here SetSurroundingText accepts relative position of |surrounding_text|, so - // we have to convert |selection_range| from node coordinates to - // |surrounding_text| coordinates. - if (!GetEngine()) - return; - GetEngine()->SetSurroundingText(base::UTF16ToUTF8(surrounding_text), - selection_range.start() - text_range.start(), - selection_range.end() - text_range.start()); -} - -void InputMethodChromeOS::CancelComposition(const TextInputClient* client) { - if (IsInputFieldFocused() && IsTextInputClientFocused(client)) - ResetContext(); -} - -void InputMethodChromeOS::OnInputLocaleChanged() { - // Not supported. -} - -std::string InputMethodChromeOS::GetInputLocale() { - // Not supported. - return ""; -} - -bool InputMethodChromeOS::IsActive() { - return true; -} - -bool InputMethodChromeOS::IsCandidatePopupOpen() const { - // TODO(yukishiino): Implement this method. - return false; -} - -void InputMethodChromeOS::OnWillChangeFocusedClient( - TextInputClient* focused_before, - TextInputClient* focused) { - ConfirmCompositionText(); - - if (GetEngine()) - GetEngine()->FocusOut(); -} - -void InputMethodChromeOS::OnDidChangeFocusedClient( - TextInputClient* focused_before, - TextInputClient* focused) { - // Force to update the input type since client's TextInputStateChanged() - // function might not be called if text input types before the client loses - // focus and after it acquires focus again are the same. - UpdateContextFocusState(); - - if (GetEngine()) { - chromeos::IMEEngineHandlerInterface::InputContext context( - GetTextInputType(), GetTextInputMode()); - GetEngine()->FocusIn(context); - } -} - -void InputMethodChromeOS::ConfirmCompositionText() { - TextInputClient* client = GetTextInputClient(); - if (client && client->HasCompositionText()) - client->ConfirmCompositionText(); - - ResetContext(); -} - -void InputMethodChromeOS::ResetContext() { - if (!IsInputFieldFocused() || !GetTextInputClient()) - return; - - DCHECK(system_toplevel_window_focused()); - - composition_.Clear(); - result_text_.clear(); - composing_text_ = false; - composition_changed_ = false; - - // We need to abandon all pending key events, but as above comment says, there - // is no reliable way to abandon all results generated by these abandoned key - // events. - AbandonAllPendingKeyEvents(); - - // This function runs asynchronously. - // Note: some input method engines may not support reset method, such as - // ibus-anthy. But as we control all input method engines by ourselves, we can - // make sure that all of the engines we are using support it correctly. - if (GetEngine()) - GetEngine()->Reset(); - - character_composer_.Reset(); -} - -void InputMethodChromeOS::UpdateContextFocusState() { - ResetContext(); - OnInputMethodChanged(); - - // Propagate the focus event to the candidate window handler which also - // manages the input method mode indicator. - chromeos::IMECandidateWindowHandlerInterface* candidate_window = - chromeos::IMEBridge::Get()->GetCandidateWindowHandler(); - if (candidate_window) - candidate_window->FocusStateChanged(IsInputFieldFocused()); - - chromeos::IMEBridge::Get()->SetCurrentTextInputType(GetTextInputType()); - - if (!IsTextInputTypeNone()) - OnCaretBoundsChanged(GetTextInputClient()); -} - -void InputMethodChromeOS::ProcessKeyEventPostIME( - const ui::KeyEvent& event, - bool handled) { - TextInputClient* client = GetTextInputClient(); - if (!client) { - // As ibus works asynchronously, there is a chance that the focused client - // loses focus before this method gets called. - DispatchKeyEventPostIME(event); - return; - } - - if (event.type() == ET_KEY_PRESSED && handled) - ProcessFilteredKeyPressEvent(event); - - // In case the focus was changed by the key event. The |context_| should have - // been reset when the focused window changed. - if (client != GetTextInputClient()) - return; - - if (HasInputMethodResult()) - ProcessInputMethodResult(event, handled); - - // In case the focus was changed when sending input method results to the - // focused window. - if (client != GetTextInputClient()) - return; - - if (event.type() == ET_KEY_PRESSED && !handled) - ProcessUnfilteredKeyPressEvent(event); - else if (event.type() == ET_KEY_RELEASED) - DispatchKeyEventPostIME(event); -} - -void InputMethodChromeOS::ProcessFilteredKeyPressEvent( - const ui::KeyEvent& event) { - if (NeedInsertChar()) { - DispatchKeyEventPostIME(event); - } else { - const ui::KeyEvent fabricated_event(ET_KEY_PRESSED, - VKEY_PROCESSKEY, - event.flags()); - DispatchKeyEventPostIME(fabricated_event); - } -} - -void InputMethodChromeOS::ProcessUnfilteredKeyPressEvent( - const ui::KeyEvent& event) { - const TextInputClient* prev_client = GetTextInputClient(); - DispatchKeyEventPostIME(event); - - // We shouldn't dispatch the character anymore if the key event dispatch - // caused focus change. For example, in the following scenario, - // 1. visit a web page which has a <textarea>. - // 2. click Omnibox. - // 3. enable Korean IME, press A, then press Tab to move the focus to the web - // page. - // We should return here not to send the Tab key event to RWHV. - TextInputClient* client = GetTextInputClient(); - if (!client || client != prev_client) - return; - - // If a key event was not filtered by |context_| and |character_composer_|, - // then it means the key event didn't generate any result text. So we need - // to send corresponding character to the focused text input client. - uint16 ch = event.GetCharacter(); - if (ch) - client->InsertChar(ch, event.flags()); -} - -void InputMethodChromeOS::ProcessInputMethodResult(const ui::KeyEvent& event, - bool handled) { - TextInputClient* client = GetTextInputClient(); - DCHECK(client); - - if (result_text_.length()) { - if (handled && NeedInsertChar()) { - for (base::string16::const_iterator i = result_text_.begin(); - i != result_text_.end(); ++i) { - client->InsertChar(*i, event.flags()); - } - } else { - client->InsertText(result_text_); - composing_text_ = false; - } - } - - if (composition_changed_ && !IsTextInputTypeNone()) { - if (composition_.text.length()) { - composing_text_ = true; - client->SetCompositionText(composition_); - } else if (result_text_.empty()) { - client->ClearCompositionText(); - } - } - - // We should not clear composition text here, as it may belong to the next - // composition session. - result_text_.clear(); - composition_changed_ = false; -} - -bool InputMethodChromeOS::NeedInsertChar() const { - return GetTextInputClient() && - (IsTextInputTypeNone() || - (!composing_text_ && result_text_.length() == 1)); -} - -bool InputMethodChromeOS::HasInputMethodResult() const { - return result_text_.length() || composition_changed_; -} - -void InputMethodChromeOS::SendFakeProcessKeyEvent(bool pressed) const { - if (!GetTextInputClient()) - return; - KeyEvent evt(pressed ? ET_KEY_PRESSED : ET_KEY_RELEASED, - pressed ? VKEY_PROCESSKEY : VKEY_UNKNOWN, - EF_IME_FABRICATED_KEY); - DispatchKeyEventPostIME(evt); -} - -void InputMethodChromeOS::AbandonAllPendingKeyEvents() { - pending_key_events_.clear(); -} - -void InputMethodChromeOS::CommitText(const std::string& text) { - if (text.empty()) - return; - - // We need to receive input method result even if the text input type is - // TEXT_INPUT_TYPE_NONE, to make sure we can always send correct - // character for each key event to the focused text input client. - if (!GetTextInputClient()) - return; - - const base::string16 utf16_text = base::UTF8ToUTF16(text); - if (utf16_text.empty()) - return; - - // Append the text to the buffer, because commit signal might be fired - // multiple times when processing a key event. - result_text_.append(utf16_text); - - // If we are not handling key event, do not bother sending text result if the - // focused text input client does not support text input. - if (pending_key_events_.empty() && !IsTextInputTypeNone()) { - SendFakeProcessKeyEvent(true); - GetTextInputClient()->InsertText(utf16_text); - SendFakeProcessKeyEvent(false); - result_text_.clear(); - } -} - -void InputMethodChromeOS::UpdateCompositionText( - const chromeos::CompositionText& text, - uint32 cursor_pos, - bool visible) { - if (IsTextInputTypeNone()) - return; - - if (!CanComposeInline()) { - chromeos::IMECandidateWindowHandlerInterface* candidate_window = - chromeos::IMEBridge::Get()->GetCandidateWindowHandler(); - if (candidate_window) - candidate_window->UpdatePreeditText(text.text(), cursor_pos, visible); - } - - // |visible| argument is very confusing. For example, what's the correct - // behavior when: - // 1. OnUpdatePreeditText() is called with a text and visible == false, then - // 2. OnShowPreeditText() is called afterwards. - // - // If it's only for clearing the current preedit text, then why not just use - // OnHidePreeditText()? - if (!visible) { - HidePreeditText(); - return; - } - - ExtractCompositionText(text, cursor_pos, &composition_); - - composition_changed_ = true; - - // In case OnShowPreeditText() is not called. - if (composition_.text.length()) - composing_text_ = true; - - // If we receive a composition text without pending key event, then we need to - // send it to the focused text input client directly. - if (pending_key_events_.empty()) { - SendFakeProcessKeyEvent(true); - GetTextInputClient()->SetCompositionText(composition_); - SendFakeProcessKeyEvent(false); - composition_changed_ = false; - composition_.Clear(); - } -} - -void InputMethodChromeOS::HidePreeditText() { - if (composition_.text.empty() || IsTextInputTypeNone()) - return; - - // Intentionally leaves |composing_text_| unchanged. - composition_changed_ = true; - composition_.Clear(); - - if (pending_key_events_.empty()) { - TextInputClient* client = GetTextInputClient(); - if (client && client->HasCompositionText()) { - SendFakeProcessKeyEvent(true); - client->ClearCompositionText(); - SendFakeProcessKeyEvent(false); - } - composition_changed_ = false; - } -} - -void InputMethodChromeOS::DeleteSurroundingText(int32 offset, uint32 length) { - if (!composition_.text.empty()) - return; // do nothing if there is ongoing composition. - if (offset < 0 && static_cast<uint32>(-1 * offset) != length) - return; // only preceding text can be deletable. - if (GetTextInputClient()) - GetTextInputClient()->ExtendSelectionAndDelete(length, 0U); -} - -bool InputMethodChromeOS::ExecuteCharacterComposer(const ui::KeyEvent& event) { - if (!character_composer_.FilterKeyPress(event)) - return false; - - // CharacterComposer consumed the key event. Update the composition text. - chromeos::CompositionText preedit; - preedit.set_text(character_composer_.preedit_string()); - UpdateCompositionText(preedit, preedit.text().size(), - !preedit.text().empty()); - std::string commit_text = - base::UTF16ToUTF8(character_composer_.composed_character()); - if (!commit_text.empty()) { - CommitText(commit_text); - } - return true; -} - -void InputMethodChromeOS::ExtractCompositionText( - const chromeos::CompositionText& text, - uint32 cursor_position, - CompositionText* out_composition) const { - out_composition->Clear(); - out_composition->text = text.text(); - - if (out_composition->text.empty()) - return; - - // ibus uses character index for cursor position and attribute range, but we - // use char16 offset for them. So we need to do conversion here. - std::vector<size_t> char16_offsets; - size_t length = out_composition->text.length(); - base::i18n::UTF16CharIterator char_iterator(&out_composition->text); - do { - char16_offsets.push_back(char_iterator.array_pos()); - } while (char_iterator.Advance()); - - // The text length in Unicode characters. - uint32 char_length = static_cast<uint32>(char16_offsets.size()); - // Make sure we can convert the value of |char_length| as well. - char16_offsets.push_back(length); - - size_t cursor_offset = - char16_offsets[std::min(char_length, cursor_position)]; - - out_composition->selection = gfx::Range(cursor_offset); - - const std::vector<chromeos::CompositionText::UnderlineAttribute>& - underline_attributes = text.underline_attributes(); - if (!underline_attributes.empty()) { - for (size_t i = 0; i < underline_attributes.size(); ++i) { - const uint32 start = underline_attributes[i].start_index; - const uint32 end = underline_attributes[i].end_index; - if (start >= end) - continue; - CompositionUnderline underline(char16_offsets[start], - char16_offsets[end], - SK_ColorBLACK, - false /* thick */, - SK_ColorTRANSPARENT); - if (underline_attributes[i].type == - chromeos::CompositionText::COMPOSITION_TEXT_UNDERLINE_DOUBLE) - underline.thick = true; - else if (underline_attributes[i].type == - chromeos::CompositionText::COMPOSITION_TEXT_UNDERLINE_ERROR) - underline.color = SK_ColorRED; - else if (underline_attributes[i].type == - chromeos::CompositionText::COMPOSITION_TEXT_UNDERLINE_NONE) - underline.color = SK_ColorTRANSPARENT; - out_composition->underlines.push_back(underline); - } - } - - DCHECK(text.selection_start() <= text.selection_end()); - if (text.selection_start() < text.selection_end()) { - const uint32 start = text.selection_start(); - const uint32 end = text.selection_end(); - CompositionUnderline underline(char16_offsets[start], - char16_offsets[end], - SK_ColorBLACK, - true /* thick */, - SK_ColorTRANSPARENT); - out_composition->underlines.push_back(underline); - - // If the cursor is at start or end of this underline, then we treat - // it as the selection range as well, but make sure to set the cursor - // position to the selection end. - if (underline.start_offset == cursor_offset) { - out_composition->selection.set_start(underline.end_offset); - out_composition->selection.set_end(cursor_offset); - } else if (underline.end_offset == cursor_offset) { - out_composition->selection.set_start(underline.start_offset); - out_composition->selection.set_end(cursor_offset); - } - } - - // Use a black thin underline by default. - if (out_composition->underlines.empty()) { - out_composition->underlines.push_back(CompositionUnderline( - 0, length, SK_ColorBLACK, false /* thick */, SK_ColorTRANSPARENT)); - } -} - -bool InputMethodChromeOS::IsInputFieldFocused() { - TextInputType type = GetTextInputType(); - return (type != TEXT_INPUT_TYPE_NONE) && (type != TEXT_INPUT_TYPE_PASSWORD); -} - -} // namespace ui
diff --git a/ui/base/ime/input_method_chromeos.h b/ui/base/ime/input_method_chromeos.h deleted file mode 100644 index a09cd3d..0000000 --- a/ui/base/ime/input_method_chromeos.h +++ /dev/null
@@ -1,158 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_INPUT_METHOD_CHROMEOS_H_ -#define UI_BASE_IME_INPUT_METHOD_CHROMEOS_H_ - -#include <set> -#include <string> - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "base/memory/weak_ptr.h" -#include "ui/base/ime/chromeos/character_composer.h" -#include "ui/base/ime/chromeos/ime_bridge.h" -#include "ui/base/ime/composition_text.h" -#include "ui/base/ime/input_method_base.h" - -namespace ui { - -// A ui::InputMethod implementation based on IBus. -class UI_BASE_EXPORT InputMethodChromeOS - : public InputMethodBase, - public chromeos::IMEInputContextHandlerInterface { - public: - explicit InputMethodChromeOS(internal::InputMethodDelegate* delegate); - virtual ~InputMethodChromeOS(); - - // Overridden from InputMethod: - virtual void OnFocus() override; - virtual void OnBlur() override; - virtual bool OnUntranslatedIMEMessage(const base::NativeEvent& event, - NativeEventResult* result) override; - virtual bool DispatchKeyEvent(const ui::KeyEvent& event) override; - virtual void OnTextInputTypeChanged(const TextInputClient* client) override; - virtual void OnCaretBoundsChanged(const TextInputClient* client) override; - virtual void CancelComposition(const TextInputClient* client) override; - virtual void OnInputLocaleChanged() override; - virtual std::string GetInputLocale() override; - virtual bool IsActive() override; - virtual bool IsCandidatePopupOpen() const override; - - protected: - // Converts |text| into CompositionText. - void ExtractCompositionText(const chromeos::CompositionText& text, - uint32 cursor_position, - CompositionText* out_composition) const; - - // Process a key returned from the input method. - virtual void ProcessKeyEventPostIME(const ui::KeyEvent& event, - bool handled); - - // Resets context and abandon all pending results and key events. - void ResetContext(); - - private: - class PendingKeyEvent; - - // Overridden from InputMethodBase: - virtual void OnWillChangeFocusedClient(TextInputClient* focused_before, - TextInputClient* focused) override; - virtual void OnDidChangeFocusedClient(TextInputClient* focused_before, - TextInputClient* focused) override; - - // Asks the client to confirm current composition text. - void ConfirmCompositionText(); - - // Checks the availability of focused text input client and update focus - // state. - void UpdateContextFocusState(); - - // Processes a key event that was already filtered by the input method. - // A VKEY_PROCESSKEY may be dispatched to the focused View. - void ProcessFilteredKeyPressEvent(const ui::KeyEvent& event); - - // Processes a key event that was not filtered by the input method. - void ProcessUnfilteredKeyPressEvent(const ui::KeyEvent& event); - - // Sends input method result caused by the given key event to the focused text - // input client. - void ProcessInputMethodResult(const ui::KeyEvent& event, bool filtered); - - // Checks if the pending input method result needs inserting into the focused - // text input client as a single character. - bool NeedInsertChar() const; - - // Checks if there is pending input method result. - bool HasInputMethodResult() const; - - // Sends a fake key event for IME composing without physical key events. - void SendFakeProcessKeyEvent(bool pressed) const; - - // Abandons all pending key events. It usually happends when we lose keyboard - // focus, the text input type is changed or we are destroyed. - void AbandonAllPendingKeyEvents(); - - // Passes keyevent and executes character composition if necessary. Returns - // true if character composer comsumes key event. - bool ExecuteCharacterComposer(const ui::KeyEvent& event); - - // chromeos::IMEInputContextHandlerInterface overrides: - virtual void CommitText(const std::string& text) override; - virtual void UpdateCompositionText(const chromeos::CompositionText& text, - uint32 cursor_pos, - bool visible) override; - virtual void DeleteSurroundingText(int32 offset, uint32 length) override; - - // Hides the composition text. - void HidePreeditText(); - - // Callback function for IMEEngineHandlerInterface::ProcessKeyEvent. - void ProcessKeyEventDone(uint32 id, ui::KeyEvent* event, bool is_handled); - - // Returns whether an input field is focused. Note that password field is not - // considered as an input field. - bool IsInputFieldFocused(); - - // All pending key events. Note: we do not own these object, we just save - // pointers to these object so that we can abandon them when necessary. - // They will be deleted in ProcessKeyEventDone(). - std::set<uint32> pending_key_events_; - - // Pending composition text generated by the current pending key event. - // It'll be sent to the focused text input client as soon as we receive the - // processing result of the pending key event. - CompositionText composition_; - - // Pending result text generated by the current pending key event. - // It'll be sent to the focused text input client as soon as we receive the - // processing result of the pending key event. - base::string16 result_text_; - - base::string16 previous_surrounding_text_; - gfx::Range previous_selection_range_; - - // Indicates if there is an ongoing composition text. - bool composing_text_; - - // Indicates if the composition text is changed or deleted. - bool composition_changed_; - - // The latest id of key event. - uint32 current_keyevent_id_; - - // An object to compose a character from a sequence of key presses - // including dead key etc. - CharacterComposer character_composer_; - - // Used for making callbacks. - base::WeakPtrFactory<InputMethodChromeOS> weak_ptr_factory_; - - DISALLOW_COPY_AND_ASSIGN(InputMethodChromeOS); -}; - -} // namespace ui - -#endif // UI_BASE_IME_INPUT_METHOD_CHROMEOS_H_
diff --git a/ui/base/ime/input_method_chromeos_unittest.cc b/ui/base/ime/input_method_chromeos_unittest.cc deleted file mode 100644 index 5071872..0000000 --- a/ui/base/ime/input_method_chromeos_unittest.cc +++ /dev/null
@@ -1,1071 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/input_method_chromeos.h" - -#include <X11/Xlib.h> -#undef Bool -#undef FocusIn -#undef FocusOut -#undef None - -#include <cstring> - -#include "base/i18n/char_iterator.h" -#include "base/memory/scoped_ptr.h" -#include "base/strings/utf_string_conversions.h" -#include "chromeos/ime/composition_text.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/base/ime/chromeos/ime_bridge.h" -#include "ui/base/ime/chromeos/mock_ime_candidate_window_handler.h" -#include "ui/base/ime/chromeos/mock_ime_engine_handler.h" -#include "ui/base/ime/input_method_delegate.h" -#include "ui/base/ime/text_input_client.h" -#include "ui/base/ime/text_input_focus_manager.h" -#include "ui/base/ui_base_switches_util.h" -#include "ui/events/event.h" -#include "ui/events/test/events_test_utils_x11.h" -#include "ui/gfx/geometry/rect.h" - -using base::UTF8ToUTF16; -using base::UTF16ToUTF8; - -namespace ui { -namespace { - -const base::string16 kSampleText = base::UTF8ToUTF16( - "\xE3\x81\x82\xE3\x81\x84\xE3\x81\x86\xE3\x81\x88\xE3\x81\x8A"); - -typedef chromeos::IMEEngineHandlerInterface::KeyEventDoneCallback - KeyEventCallback; - -uint32 GetOffsetInUTF16( - const base::string16& utf16_string, uint32 utf8_offset) { - DCHECK_LT(utf8_offset, utf16_string.size()); - base::i18n::UTF16CharIterator char_iterator(&utf16_string); - for (size_t i = 0; i < utf8_offset; ++i) - char_iterator.Advance(); - return char_iterator.array_pos(); -} - -bool IsEqualXKeyEvent(const XEvent& e1, const XEvent& e2) { - if ((e1.type == KeyPress && e2.type == KeyPress) || - (e1.type == KeyRelease && e2.type == KeyRelease)) { - return !std::memcmp(&e1.xkey, &e2.xkey, sizeof(XKeyEvent)); - } - return false; -} - -enum KeyEventHandlerBehavior { - KEYEVENT_CONSUME, - KEYEVENT_NOT_CONSUME, -}; - -} // namespace - - -class TestableInputMethodChromeOS : public InputMethodChromeOS { - public: - explicit TestableInputMethodChromeOS(internal::InputMethodDelegate* delegate) - : InputMethodChromeOS(delegate), - process_key_event_post_ime_call_count_(0) { - } - - struct ProcessKeyEventPostIMEArgs { - ProcessKeyEventPostIMEArgs() : event(NULL), handled(false) {} - const ui::KeyEvent* event; - bool handled; - }; - - // Overridden from InputMethodChromeOS: - virtual void ProcessKeyEventPostIME(const ui::KeyEvent& key_event, - bool handled) override { - process_key_event_post_ime_args_.event = &key_event; - process_key_event_post_ime_args_.handled = handled; - ++process_key_event_post_ime_call_count_; - } - - void ResetCallCount() { - process_key_event_post_ime_call_count_ = 0; - } - - const ProcessKeyEventPostIMEArgs& process_key_event_post_ime_args() const { - return process_key_event_post_ime_args_; - } - - int process_key_event_post_ime_call_count() const { - return process_key_event_post_ime_call_count_; - } - - // Change access rights for testing. - using InputMethodChromeOS::ExtractCompositionText; - using InputMethodChromeOS::ResetContext; - - private: - ProcessKeyEventPostIMEArgs process_key_event_post_ime_args_; - int process_key_event_post_ime_call_count_; -}; - -class SynchronousKeyEventHandler { - public: - SynchronousKeyEventHandler(uint32 expected_keyval, - uint32 expected_keycode, - uint32 expected_state, - KeyEventHandlerBehavior behavior) - : expected_keyval_(expected_keyval), - expected_keycode_(expected_keycode), - expected_state_(expected_state), - behavior_(behavior) {} - - virtual ~SynchronousKeyEventHandler() {} - - void Run(uint32 keyval, - uint32 keycode, - uint32 state, - const KeyEventCallback& callback) { - EXPECT_EQ(expected_keyval_, keyval); - EXPECT_EQ(expected_keycode_, keycode); - EXPECT_EQ(expected_state_, state); - callback.Run(behavior_ == KEYEVENT_CONSUME); - } - - private: - const uint32 expected_keyval_; - const uint32 expected_keycode_; - const uint32 expected_state_; - const KeyEventHandlerBehavior behavior_; - - DISALLOW_COPY_AND_ASSIGN(SynchronousKeyEventHandler); -}; - -class AsynchronousKeyEventHandler { - public: - AsynchronousKeyEventHandler(uint32 expected_keyval, - uint32 expected_keycode, - uint32 expected_state) - : expected_keyval_(expected_keyval), - expected_keycode_(expected_keycode), - expected_state_(expected_state) {} - - virtual ~AsynchronousKeyEventHandler() {} - - void Run(uint32 keyval, - uint32 keycode, - uint32 state, - const KeyEventCallback& callback) { - EXPECT_EQ(expected_keyval_, keyval); - EXPECT_EQ(expected_keycode_, keycode); - EXPECT_EQ(expected_state_, state); - callback_ = callback; - } - - void RunCallback(KeyEventHandlerBehavior behavior) { - callback_.Run(behavior == KEYEVENT_CONSUME); - } - - private: - const uint32 expected_keyval_; - const uint32 expected_keycode_; - const uint32 expected_state_; - KeyEventCallback callback_; - - DISALLOW_COPY_AND_ASSIGN(AsynchronousKeyEventHandler); -}; - -class SetSurroundingTextVerifier { - public: - SetSurroundingTextVerifier(const std::string& expected_surrounding_text, - uint32 expected_cursor_position, - uint32 expected_anchor_position) - : expected_surrounding_text_(expected_surrounding_text), - expected_cursor_position_(expected_cursor_position), - expected_anchor_position_(expected_anchor_position) {} - - void Verify(const std::string& text, - uint32 cursor_pos, - uint32 anchor_pos) { - EXPECT_EQ(expected_surrounding_text_, text); - EXPECT_EQ(expected_cursor_position_, cursor_pos); - EXPECT_EQ(expected_anchor_position_, anchor_pos); - } - - private: - const std::string expected_surrounding_text_; - const uint32 expected_cursor_position_; - const uint32 expected_anchor_position_; - - DISALLOW_COPY_AND_ASSIGN(SetSurroundingTextVerifier); -}; - -class InputMethodChromeOSTest : public internal::InputMethodDelegate, - public testing::Test, - public TextInputClient { - public: - InputMethodChromeOSTest() - : dispatched_key_event_(ui::ET_UNKNOWN, ui::VKEY_UNKNOWN, ui::EF_NONE) { - ResetFlags(); - } - - virtual ~InputMethodChromeOSTest() { - } - - virtual void SetUp() override { - chromeos::IMEBridge::Initialize(); - - mock_ime_engine_handler_.reset( - new chromeos::MockIMEEngineHandler()); - chromeos::IMEBridge::Get()->SetCurrentEngineHandler( - mock_ime_engine_handler_.get()); - - mock_ime_candidate_window_handler_.reset( - new chromeos::MockIMECandidateWindowHandler()); - chromeos::IMEBridge::Get()->SetCandidateWindowHandler( - mock_ime_candidate_window_handler_.get()); - - ime_.reset(new TestableInputMethodChromeOS(this)); - if (switches::IsTextInputFocusManagerEnabled()) - TextInputFocusManager::GetInstance()->FocusTextInputClient(this); - else - ime_->SetFocusedTextInputClient(this); - } - - virtual void TearDown() override { - if (ime_.get()) { - if (switches::IsTextInputFocusManagerEnabled()) - TextInputFocusManager::GetInstance()->BlurTextInputClient(this); - else - ime_->SetFocusedTextInputClient(NULL); - } - ime_.reset(); - chromeos::IMEBridge::Get()->SetCurrentEngineHandler(NULL); - chromeos::IMEBridge::Get()->SetCandidateWindowHandler(NULL); - mock_ime_engine_handler_.reset(); - mock_ime_candidate_window_handler_.reset(); - chromeos::IMEBridge::Shutdown(); - } - - // Overridden from ui::internal::InputMethodDelegate: - virtual bool DispatchKeyEventPostIME(const ui::KeyEvent& event) override { - dispatched_key_event_ = event; - return false; - } - - // Overridden from ui::TextInputClient: - virtual void SetCompositionText( - const CompositionText& composition) override { - composition_text_ = composition; - } - virtual void ConfirmCompositionText() override { - confirmed_text_ = composition_text_; - composition_text_.Clear(); - } - virtual void ClearCompositionText() override { - composition_text_.Clear(); - } - virtual void InsertText(const base::string16& text) override { - inserted_text_ = text; - } - virtual void InsertChar(base::char16 ch, int flags) override { - inserted_char_ = ch; - inserted_char_flags_ = flags; - } - virtual gfx::NativeWindow GetAttachedWindow() const override { - return static_cast<gfx::NativeWindow>(NULL); - } - virtual TextInputType GetTextInputType() const override { - return input_type_; - } - virtual TextInputMode GetTextInputMode() const override { - return input_mode_; - } - virtual bool CanComposeInline() const override { - return can_compose_inline_; - } - virtual gfx::Rect GetCaretBounds() const override { - return caret_bounds_; - } - virtual bool GetCompositionCharacterBounds(uint32 index, - gfx::Rect* rect) const override { - return false; - } - virtual bool HasCompositionText() const override { - CompositionText empty; - return composition_text_ != empty; - } - virtual bool GetTextRange(gfx::Range* range) const override { - *range = text_range_; - return true; - } - virtual bool GetCompositionTextRange(gfx::Range* range) const override { - return false; - } - virtual bool GetSelectionRange(gfx::Range* range) const override { - *range = selection_range_; - return true; - } - - virtual bool SetSelectionRange(const gfx::Range& range) override { - return false; - } - virtual bool DeleteRange(const gfx::Range& range) override { return false; } - virtual bool GetTextFromRange(const gfx::Range& range, - base::string16* text) const override { - *text = surrounding_text_.substr(range.GetMin(), range.length()); - return true; - } - virtual void OnInputMethodChanged() override { - ++on_input_method_changed_call_count_; - } - virtual bool ChangeTextDirectionAndLayoutAlignment( - base::i18n::TextDirection direction) override { return false; } - virtual void ExtendSelectionAndDelete(size_t before, - size_t after) override {} - virtual void EnsureCaretInRect(const gfx::Rect& rect) override {} - virtual void OnCandidateWindowShown() override {} - virtual void OnCandidateWindowUpdated() override {} - virtual void OnCandidateWindowHidden() override {} - virtual bool IsEditingCommandEnabled(int command_id) override { - return false; - } - virtual void ExecuteEditingCommand(int command_id) override {} - - bool HasNativeEvent() const { - return dispatched_key_event_.HasNativeEvent(); - } - - void ResetFlags() { - dispatched_key_event_ = ui::KeyEvent(ui::ET_UNKNOWN, ui::VKEY_UNKNOWN, - ui::EF_NONE); - - composition_text_.Clear(); - confirmed_text_.Clear(); - inserted_text_.clear(); - inserted_char_ = 0; - inserted_char_flags_ = 0; - on_input_method_changed_call_count_ = 0; - - input_type_ = TEXT_INPUT_TYPE_NONE; - input_mode_ = TEXT_INPUT_MODE_DEFAULT; - can_compose_inline_ = true; - caret_bounds_ = gfx::Rect(); - } - - scoped_ptr<TestableInputMethodChromeOS> ime_; - - // Copy of the dispatched key event. - ui::KeyEvent dispatched_key_event_; - - // Variables for remembering the parameters that are passed to - // ui::TextInputClient functions. - CompositionText composition_text_; - CompositionText confirmed_text_; - base::string16 inserted_text_; - base::char16 inserted_char_; - unsigned int on_input_method_changed_call_count_; - int inserted_char_flags_; - - // Variables that will be returned from the ui::TextInputClient functions. - TextInputType input_type_; - TextInputMode input_mode_; - bool can_compose_inline_; - gfx::Rect caret_bounds_; - gfx::Range text_range_; - gfx::Range selection_range_; - base::string16 surrounding_text_; - - scoped_ptr<chromeos::MockIMEEngineHandler> mock_ime_engine_handler_; - scoped_ptr<chromeos::MockIMECandidateWindowHandler> - mock_ime_candidate_window_handler_; - - DISALLOW_COPY_AND_ASSIGN(InputMethodChromeOSTest); -}; - -// Tests public APIs in ui::InputMethod first. - -TEST_F(InputMethodChromeOSTest, GetInputLocale) { - // ui::InputMethodChromeOS does not support the API. - ime_->Init(true); - EXPECT_EQ("", ime_->GetInputLocale()); -} - -TEST_F(InputMethodChromeOSTest, IsActive) { - ime_->Init(true); - // ui::InputMethodChromeOS always returns true. - EXPECT_TRUE(ime_->IsActive()); -} - -TEST_F(InputMethodChromeOSTest, GetInputTextType) { - ime_->Init(true); - EXPECT_EQ(TEXT_INPUT_TYPE_NONE, ime_->GetTextInputType()); - input_type_ = TEXT_INPUT_TYPE_PASSWORD; - ime_->OnTextInputTypeChanged(this); - EXPECT_EQ(TEXT_INPUT_TYPE_PASSWORD, ime_->GetTextInputType()); - input_type_ = TEXT_INPUT_TYPE_TEXT; - ime_->OnTextInputTypeChanged(this); - EXPECT_EQ(TEXT_INPUT_TYPE_TEXT, ime_->GetTextInputType()); -} - -TEST_F(InputMethodChromeOSTest, CanComposeInline) { - ime_->Init(true); - EXPECT_TRUE(ime_->CanComposeInline()); - can_compose_inline_ = false; - ime_->OnTextInputTypeChanged(this); - EXPECT_FALSE(ime_->CanComposeInline()); -} - -TEST_F(InputMethodChromeOSTest, GetTextInputClient) { - ime_->Init(true); - EXPECT_EQ(this, ime_->GetTextInputClient()); - if (switches::IsTextInputFocusManagerEnabled()) - TextInputFocusManager::GetInstance()->BlurTextInputClient(this); - else - ime_->SetFocusedTextInputClient(NULL); - EXPECT_EQ(NULL, ime_->GetTextInputClient()); -} - -TEST_F(InputMethodChromeOSTest, GetInputTextType_WithoutFocusedClient) { - ime_->Init(true); - EXPECT_EQ(TEXT_INPUT_TYPE_NONE, ime_->GetTextInputType()); - if (switches::IsTextInputFocusManagerEnabled()) - TextInputFocusManager::GetInstance()->BlurTextInputClient(this); - else - ime_->SetFocusedTextInputClient(NULL); - input_type_ = TEXT_INPUT_TYPE_PASSWORD; - ime_->OnTextInputTypeChanged(this); - // The OnTextInputTypeChanged() call above should be ignored since |this| is - // not the current focused client. - EXPECT_EQ(TEXT_INPUT_TYPE_NONE, ime_->GetTextInputType()); - - if (switches::IsTextInputFocusManagerEnabled()) - TextInputFocusManager::GetInstance()->FocusTextInputClient(this); - else - ime_->SetFocusedTextInputClient(this); - ime_->OnTextInputTypeChanged(this); - EXPECT_EQ(TEXT_INPUT_TYPE_PASSWORD, ime_->GetTextInputType()); -} - -TEST_F(InputMethodChromeOSTest, GetInputTextType_WithoutFocusedWindow) { - ime_->Init(true); - EXPECT_EQ(TEXT_INPUT_TYPE_NONE, ime_->GetTextInputType()); - if (switches::IsTextInputFocusManagerEnabled()) - TextInputFocusManager::GetInstance()->BlurTextInputClient(this); - else - ime_->OnBlur(); - input_type_ = TEXT_INPUT_TYPE_PASSWORD; - ime_->OnTextInputTypeChanged(this); - // The OnTextInputTypeChanged() call above should be ignored since the top- - // level window which the ime_ is attached to is not currently focused. - EXPECT_EQ(TEXT_INPUT_TYPE_NONE, ime_->GetTextInputType()); - - if (switches::IsTextInputFocusManagerEnabled()) - TextInputFocusManager::GetInstance()->FocusTextInputClient(this); - else - ime_->OnFocus(); - ime_->OnTextInputTypeChanged(this); - EXPECT_EQ(TEXT_INPUT_TYPE_PASSWORD, ime_->GetTextInputType()); -} - -TEST_F(InputMethodChromeOSTest, GetInputTextType_WithoutFocusedWindow2) { - // We no longer support the case that |ime_->Init(false)| because no one - // actually uses it. - if (switches::IsTextInputFocusManagerEnabled()) - return; - - ime_->Init(false); // the top-level is initially unfocused. - EXPECT_EQ(TEXT_INPUT_TYPE_NONE, ime_->GetTextInputType()); - input_type_ = TEXT_INPUT_TYPE_PASSWORD; - ime_->OnTextInputTypeChanged(this); - EXPECT_EQ(TEXT_INPUT_TYPE_NONE, ime_->GetTextInputType()); - - ime_->OnFocus(); - ime_->OnTextInputTypeChanged(this); - EXPECT_EQ(TEXT_INPUT_TYPE_PASSWORD, ime_->GetTextInputType()); -} - -// Confirm that IBusClient::FocusIn is called on "connected" if input_type_ is -// TEXT. -TEST_F(InputMethodChromeOSTest, FocusIn_Text) { - ime_->Init(true); - // A context shouldn't be created since the daemon is not running. - EXPECT_EQ(0U, on_input_method_changed_call_count_); - // Click a text input form. - input_type_ = TEXT_INPUT_TYPE_TEXT; - ime_->OnTextInputTypeChanged(this); - // Since a form has focus, IBusClient::FocusIn() should be called. - EXPECT_EQ(1, mock_ime_engine_handler_->focus_in_call_count()); - EXPECT_EQ( - 1, - mock_ime_candidate_window_handler_->set_cursor_bounds_call_count()); - // ui::TextInputClient::OnInputMethodChanged() should be called when - // ui::InputMethodChromeOS connects/disconnects to/from ibus-daemon and the - // current text input type is not NONE. - EXPECT_EQ(1U, on_input_method_changed_call_count_); -} - -// Confirm that InputMethodEngine::FocusIn is called on "connected" even if -// input_type_ is PASSWORD. -TEST_F(InputMethodChromeOSTest, FocusIn_Password) { - ime_->Init(true); - EXPECT_EQ(0U, on_input_method_changed_call_count_); - input_type_ = TEXT_INPUT_TYPE_PASSWORD; - ime_->OnTextInputTypeChanged(this); - // InputMethodEngine::FocusIn() should be called even for password field. - EXPECT_EQ(1, mock_ime_engine_handler_->focus_in_call_count()); - EXPECT_EQ(1U, on_input_method_changed_call_count_); -} - -// Confirm that IBusClient::FocusOut is called as expected. -TEST_F(InputMethodChromeOSTest, FocusOut_None) { - input_type_ = TEXT_INPUT_TYPE_TEXT; - ime_->Init(true); - EXPECT_EQ(1, mock_ime_engine_handler_->focus_in_call_count()); - EXPECT_EQ(0, mock_ime_engine_handler_->focus_out_call_count()); - input_type_ = TEXT_INPUT_TYPE_NONE; - ime_->OnTextInputTypeChanged(this); - EXPECT_EQ(1, mock_ime_engine_handler_->focus_in_call_count()); - EXPECT_EQ(1, mock_ime_engine_handler_->focus_out_call_count()); -} - -// Confirm that IBusClient::FocusOut is called as expected. -TEST_F(InputMethodChromeOSTest, FocusOut_Password) { - input_type_ = TEXT_INPUT_TYPE_TEXT; - ime_->Init(true); - EXPECT_EQ(1, mock_ime_engine_handler_->focus_in_call_count()); - EXPECT_EQ(0, mock_ime_engine_handler_->focus_out_call_count()); - input_type_ = TEXT_INPUT_TYPE_PASSWORD; - ime_->OnTextInputTypeChanged(this); - EXPECT_EQ(2, mock_ime_engine_handler_->focus_in_call_count()); - EXPECT_EQ(1, mock_ime_engine_handler_->focus_out_call_count()); -} - -// FocusIn/FocusOut scenario test -TEST_F(InputMethodChromeOSTest, Focus_Scenario) { - ime_->Init(true); - // Confirm that both FocusIn and FocusOut are NOT called. - EXPECT_EQ(0, mock_ime_engine_handler_->focus_in_call_count()); - EXPECT_EQ(0, mock_ime_engine_handler_->focus_out_call_count()); - EXPECT_EQ(TEXT_INPUT_TYPE_NONE, - mock_ime_engine_handler_->last_text_input_context().type); - EXPECT_EQ(TEXT_INPUT_MODE_DEFAULT, - mock_ime_engine_handler_->last_text_input_context().mode); - - input_type_ = TEXT_INPUT_TYPE_TEXT; - input_mode_ = TEXT_INPUT_MODE_LATIN; - ime_->OnTextInputTypeChanged(this); - // Confirm that only FocusIn is called, the TextInputType is TEXT and the - // TextInputMode is LATIN.. - EXPECT_EQ(1, mock_ime_engine_handler_->focus_in_call_count()); - EXPECT_EQ(0, mock_ime_engine_handler_->focus_out_call_count()); - EXPECT_EQ(TEXT_INPUT_TYPE_TEXT, - mock_ime_engine_handler_->last_text_input_context().type); - EXPECT_EQ(TEXT_INPUT_MODE_LATIN, - mock_ime_engine_handler_->last_text_input_context().mode); - - input_mode_ = TEXT_INPUT_MODE_KANA; - ime_->OnTextInputTypeChanged(this); - // Confirm that both FocusIn and FocusOut are called for mode change. - EXPECT_EQ(2, mock_ime_engine_handler_->focus_in_call_count()); - EXPECT_EQ(1, mock_ime_engine_handler_->focus_out_call_count()); - EXPECT_EQ(TEXT_INPUT_TYPE_TEXT, - mock_ime_engine_handler_->last_text_input_context().type); - EXPECT_EQ(TEXT_INPUT_MODE_KANA, - mock_ime_engine_handler_->last_text_input_context().mode); - - input_type_ = TEXT_INPUT_TYPE_URL; - ime_->OnTextInputTypeChanged(this); - // Confirm that both FocusIn and FocusOut are called and the TextInputType is - // changed to URL. - EXPECT_EQ(3, mock_ime_engine_handler_->focus_in_call_count()); - EXPECT_EQ(2, mock_ime_engine_handler_->focus_out_call_count()); - EXPECT_EQ(TEXT_INPUT_TYPE_URL, - mock_ime_engine_handler_->last_text_input_context().type); - EXPECT_EQ(TEXT_INPUT_MODE_KANA, - mock_ime_engine_handler_->last_text_input_context().mode); - - // When IsTextInputFocusManagerEnabled, InputMethod::SetFocusedTextInputClient - // is not supported and it's no-op. - if (switches::IsTextInputFocusManagerEnabled()) - return; - // Confirm that FocusOut is called when set focus to NULL client. - ime_->SetFocusedTextInputClient(NULL); - EXPECT_EQ(3, mock_ime_engine_handler_->focus_in_call_count()); - EXPECT_EQ(3, mock_ime_engine_handler_->focus_out_call_count()); - // Confirm that FocusIn is called when set focus to this client. - ime_->SetFocusedTextInputClient(this); - EXPECT_EQ(4, mock_ime_engine_handler_->focus_in_call_count()); - EXPECT_EQ(3, mock_ime_engine_handler_->focus_out_call_count()); -} - -// Test if the new |caret_bounds_| is correctly sent to ibus-daemon. -TEST_F(InputMethodChromeOSTest, OnCaretBoundsChanged) { - input_type_ = TEXT_INPUT_TYPE_TEXT; - ime_->Init(true); - EXPECT_EQ( - 1, - mock_ime_candidate_window_handler_->set_cursor_bounds_call_count()); - caret_bounds_ = gfx::Rect(1, 2, 3, 4); - ime_->OnCaretBoundsChanged(this); - EXPECT_EQ( - 2, - mock_ime_candidate_window_handler_->set_cursor_bounds_call_count()); - caret_bounds_ = gfx::Rect(0, 2, 3, 4); - ime_->OnCaretBoundsChanged(this); - EXPECT_EQ( - 3, - mock_ime_candidate_window_handler_->set_cursor_bounds_call_count()); - caret_bounds_ = gfx::Rect(0, 2, 3, 4); // unchanged - ime_->OnCaretBoundsChanged(this); - // Current InputMethodChromeOS implementation performs the IPC - // regardless of the bounds are changed or not. - EXPECT_EQ( - 4, - mock_ime_candidate_window_handler_->set_cursor_bounds_call_count()); -} - -TEST_F(InputMethodChromeOSTest, ExtractCompositionTextTest_NoAttribute) { - const base::string16 kSampleAsciiText = UTF8ToUTF16("Sample Text"); - const uint32 kCursorPos = 2UL; - - chromeos::CompositionText chromeos_composition_text; - chromeos_composition_text.set_text(kSampleAsciiText); - - CompositionText composition_text; - ime_->ExtractCompositionText( - chromeos_composition_text, kCursorPos, &composition_text); - EXPECT_EQ(kSampleAsciiText, composition_text.text); - // If there is no selection, |selection| represents cursor position. - EXPECT_EQ(kCursorPos, composition_text.selection.start()); - EXPECT_EQ(kCursorPos, composition_text.selection.end()); - // If there is no underline, |underlines| contains one underline and it is - // whole text underline. - ASSERT_EQ(1UL, composition_text.underlines.size()); - EXPECT_EQ(0UL, composition_text.underlines[0].start_offset); - EXPECT_EQ(kSampleAsciiText.size(), composition_text.underlines[0].end_offset); - EXPECT_FALSE(composition_text.underlines[0].thick); -} - -TEST_F(InputMethodChromeOSTest, ExtractCompositionTextTest_SingleUnderline) { - const uint32 kCursorPos = 2UL; - - // Set up chromeos composition text with one underline attribute. - chromeos::CompositionText chromeos_composition_text; - chromeos_composition_text.set_text(kSampleText); - chromeos::CompositionText::UnderlineAttribute underline; - underline.type = chromeos::CompositionText::COMPOSITION_TEXT_UNDERLINE_SINGLE; - underline.start_index = 1UL; - underline.end_index = 4UL; - chromeos_composition_text.mutable_underline_attributes()->push_back( - underline); - - CompositionText composition_text; - ime_->ExtractCompositionText( - chromeos_composition_text, kCursorPos, &composition_text); - EXPECT_EQ(kSampleText, composition_text.text); - // If there is no selection, |selection| represents cursor position. - EXPECT_EQ(kCursorPos, composition_text.selection.start()); - EXPECT_EQ(kCursorPos, composition_text.selection.end()); - ASSERT_EQ(1UL, composition_text.underlines.size()); - EXPECT_EQ(GetOffsetInUTF16(kSampleText, underline.start_index), - composition_text.underlines[0].start_offset); - EXPECT_EQ(GetOffsetInUTF16(kSampleText, underline.end_index), - composition_text.underlines[0].end_offset); - // Single underline represents as black thin line. - EXPECT_EQ(SK_ColorBLACK, composition_text.underlines[0].color); - EXPECT_FALSE(composition_text.underlines[0].thick); - EXPECT_EQ(static_cast<SkColor>(SK_ColorTRANSPARENT), - composition_text.underlines[0].background_color); -} - -TEST_F(InputMethodChromeOSTest, ExtractCompositionTextTest_DoubleUnderline) { - const uint32 kCursorPos = 2UL; - - // Set up chromeos composition text with one underline attribute. - chromeos::CompositionText chromeos_composition_text; - chromeos_composition_text.set_text(kSampleText); - chromeos::CompositionText::UnderlineAttribute underline; - underline.type = chromeos::CompositionText::COMPOSITION_TEXT_UNDERLINE_DOUBLE; - underline.start_index = 1UL; - underline.end_index = 4UL; - chromeos_composition_text.mutable_underline_attributes()->push_back( - underline); - - CompositionText composition_text; - ime_->ExtractCompositionText( - chromeos_composition_text, kCursorPos, &composition_text); - EXPECT_EQ(kSampleText, composition_text.text); - // If there is no selection, |selection| represents cursor position. - EXPECT_EQ(kCursorPos, composition_text.selection.start()); - EXPECT_EQ(kCursorPos, composition_text.selection.end()); - ASSERT_EQ(1UL, composition_text.underlines.size()); - EXPECT_EQ(GetOffsetInUTF16(kSampleText, underline.start_index), - composition_text.underlines[0].start_offset); - EXPECT_EQ(GetOffsetInUTF16(kSampleText, underline.end_index), - composition_text.underlines[0].end_offset); - // Double underline represents as black thick line. - EXPECT_EQ(SK_ColorBLACK, composition_text.underlines[0].color); - EXPECT_TRUE(composition_text.underlines[0].thick); - EXPECT_EQ(static_cast<SkColor>(SK_ColorTRANSPARENT), - composition_text.underlines[0].background_color); -} - -TEST_F(InputMethodChromeOSTest, ExtractCompositionTextTest_ErrorUnderline) { - const uint32 kCursorPos = 2UL; - - // Set up chromeos composition text with one underline attribute. - chromeos::CompositionText chromeos_composition_text; - chromeos_composition_text.set_text(kSampleText); - chromeos::CompositionText::UnderlineAttribute underline; - underline.type = chromeos::CompositionText::COMPOSITION_TEXT_UNDERLINE_ERROR; - underline.start_index = 1UL; - underline.end_index = 4UL; - chromeos_composition_text.mutable_underline_attributes()->push_back( - underline); - - CompositionText composition_text; - ime_->ExtractCompositionText( - chromeos_composition_text, kCursorPos, &composition_text); - EXPECT_EQ(kSampleText, composition_text.text); - EXPECT_EQ(kCursorPos, composition_text.selection.start()); - EXPECT_EQ(kCursorPos, composition_text.selection.end()); - ASSERT_EQ(1UL, composition_text.underlines.size()); - EXPECT_EQ(GetOffsetInUTF16(kSampleText, underline.start_index), - composition_text.underlines[0].start_offset); - EXPECT_EQ(GetOffsetInUTF16(kSampleText, underline.end_index), - composition_text.underlines[0].end_offset); - // Error underline represents as red thin line. - EXPECT_EQ(SK_ColorRED, composition_text.underlines[0].color); - EXPECT_FALSE(composition_text.underlines[0].thick); -} - -TEST_F(InputMethodChromeOSTest, ExtractCompositionTextTest_Selection) { - const uint32 kCursorPos = 2UL; - - // Set up chromeos composition text with one underline attribute. - chromeos::CompositionText chromeos_composition_text; - chromeos_composition_text.set_text(kSampleText); - chromeos_composition_text.set_selection_start(1UL); - chromeos_composition_text.set_selection_end(4UL); - - CompositionText composition_text; - ime_->ExtractCompositionText( - chromeos_composition_text, kCursorPos, &composition_text); - EXPECT_EQ(kSampleText, composition_text.text); - EXPECT_EQ(kCursorPos, composition_text.selection.start()); - EXPECT_EQ(kCursorPos, composition_text.selection.end()); - ASSERT_EQ(1UL, composition_text.underlines.size()); - EXPECT_EQ(GetOffsetInUTF16(kSampleText, - chromeos_composition_text.selection_start()), - composition_text.underlines[0].start_offset); - EXPECT_EQ(GetOffsetInUTF16(kSampleText, - chromeos_composition_text.selection_end()), - composition_text.underlines[0].end_offset); - EXPECT_EQ(SK_ColorBLACK, composition_text.underlines[0].color); - EXPECT_TRUE(composition_text.underlines[0].thick); - EXPECT_EQ(static_cast<SkColor>(SK_ColorTRANSPARENT), - composition_text.underlines[0].background_color); -} - -TEST_F(InputMethodChromeOSTest, - ExtractCompositionTextTest_SelectionStartWithCursor) { - const uint32 kCursorPos = 1UL; - - // Set up chromeos composition text with one underline attribute. - chromeos::CompositionText chromeos_composition_text; - chromeos_composition_text.set_text(kSampleText); - chromeos_composition_text.set_selection_start(kCursorPos); - chromeos_composition_text.set_selection_end(4UL); - - CompositionText composition_text; - ime_->ExtractCompositionText( - chromeos_composition_text, kCursorPos, &composition_text); - EXPECT_EQ(kSampleText, composition_text.text); - // If the cursor position is same as selection bounds, selection start - // position become opposit side of selection from cursor. - EXPECT_EQ(GetOffsetInUTF16(kSampleText, - chromeos_composition_text.selection_end()), - composition_text.selection.start()); - EXPECT_EQ(GetOffsetInUTF16(kSampleText, kCursorPos), - composition_text.selection.end()); - ASSERT_EQ(1UL, composition_text.underlines.size()); - EXPECT_EQ(GetOffsetInUTF16(kSampleText, - chromeos_composition_text.selection_start()), - composition_text.underlines[0].start_offset); - EXPECT_EQ(GetOffsetInUTF16(kSampleText, - chromeos_composition_text.selection_end()), - composition_text.underlines[0].end_offset); - EXPECT_EQ(SK_ColorBLACK, composition_text.underlines[0].color); - EXPECT_TRUE(composition_text.underlines[0].thick); - EXPECT_EQ(static_cast<SkColor>(SK_ColorTRANSPARENT), - composition_text.underlines[0].background_color); -} - -TEST_F(InputMethodChromeOSTest, - ExtractCompositionTextTest_SelectionEndWithCursor) { - const uint32 kCursorPos = 4UL; - - // Set up chromeos composition text with one underline attribute. - chromeos::CompositionText chromeos_composition_text; - chromeos_composition_text.set_text(kSampleText); - chromeos_composition_text.set_selection_start(1UL); - chromeos_composition_text.set_selection_end(kCursorPos); - - CompositionText composition_text; - ime_->ExtractCompositionText( - chromeos_composition_text, kCursorPos, &composition_text); - EXPECT_EQ(kSampleText, composition_text.text); - // If the cursor position is same as selection bounds, selection start - // position become opposit side of selection from cursor. - EXPECT_EQ(GetOffsetInUTF16(kSampleText, - chromeos_composition_text.selection_start()), - composition_text.selection.start()); - EXPECT_EQ(GetOffsetInUTF16(kSampleText, kCursorPos), - composition_text.selection.end()); - ASSERT_EQ(1UL, composition_text.underlines.size()); - EXPECT_EQ(GetOffsetInUTF16(kSampleText, - chromeos_composition_text.selection_start()), - composition_text.underlines[0].start_offset); - EXPECT_EQ(GetOffsetInUTF16(kSampleText, - chromeos_composition_text.selection_end()), - composition_text.underlines[0].end_offset); - EXPECT_EQ(SK_ColorBLACK, composition_text.underlines[0].color); - EXPECT_TRUE(composition_text.underlines[0].thick); - EXPECT_EQ(static_cast<SkColor>(SK_ColorTRANSPARENT), - composition_text.underlines[0].background_color); -} - -TEST_F(InputMethodChromeOSTest, SurroundingText_NoSelectionTest) { - ime_->Init(true); - // Click a text input form. - input_type_ = TEXT_INPUT_TYPE_TEXT; - ime_->OnTextInputTypeChanged(this); - - // Set the TextInputClient behaviors. - surrounding_text_ = UTF8ToUTF16("abcdef"); - text_range_ = gfx::Range(0, 6); - selection_range_ = gfx::Range(3, 3); - - // Set the verifier for SetSurroundingText mock call. - SetSurroundingTextVerifier verifier(UTF16ToUTF8(surrounding_text_), 3, 3); - - - ime_->OnCaretBoundsChanged(this); - - // Check the call count. - EXPECT_EQ(1, - mock_ime_engine_handler_->set_surrounding_text_call_count()); - EXPECT_EQ(UTF16ToUTF8(surrounding_text_), - mock_ime_engine_handler_->last_set_surrounding_text()); - EXPECT_EQ(3U, - mock_ime_engine_handler_->last_set_surrounding_cursor_pos()); - EXPECT_EQ(3U, - mock_ime_engine_handler_->last_set_surrounding_anchor_pos()); -} - -TEST_F(InputMethodChromeOSTest, SurroundingText_SelectionTest) { - ime_->Init(true); - // Click a text input form. - input_type_ = TEXT_INPUT_TYPE_TEXT; - ime_->OnTextInputTypeChanged(this); - - // Set the TextInputClient behaviors. - surrounding_text_ = UTF8ToUTF16("abcdef"); - text_range_ = gfx::Range(0, 6); - selection_range_ = gfx::Range(2, 5); - - // Set the verifier for SetSurroundingText mock call. - SetSurroundingTextVerifier verifier(UTF16ToUTF8(surrounding_text_), 2, 5); - - ime_->OnCaretBoundsChanged(this); - - // Check the call count. - EXPECT_EQ(1, - mock_ime_engine_handler_->set_surrounding_text_call_count()); - EXPECT_EQ(UTF16ToUTF8(surrounding_text_), - mock_ime_engine_handler_->last_set_surrounding_text()); - EXPECT_EQ(2U, - mock_ime_engine_handler_->last_set_surrounding_cursor_pos()); - EXPECT_EQ(5U, - mock_ime_engine_handler_->last_set_surrounding_anchor_pos()); -} - -TEST_F(InputMethodChromeOSTest, SurroundingText_PartialText) { - ime_->Init(true); - // Click a text input form. - input_type_ = TEXT_INPUT_TYPE_TEXT; - ime_->OnTextInputTypeChanged(this); - - // Set the TextInputClient behaviors. - surrounding_text_ = UTF8ToUTF16("abcdefghij"); - text_range_ = gfx::Range(5, 10); - selection_range_ = gfx::Range(7, 9); - - ime_->OnCaretBoundsChanged(this); - - // Check the call count. - EXPECT_EQ(1, - mock_ime_engine_handler_->set_surrounding_text_call_count()); - // Set the verifier for SetSurroundingText mock call. - // Here (2, 4) is selection range in expected surrounding text coordinates. - EXPECT_EQ("fghij", - mock_ime_engine_handler_->last_set_surrounding_text()); - EXPECT_EQ(2U, - mock_ime_engine_handler_->last_set_surrounding_cursor_pos()); - EXPECT_EQ(4U, - mock_ime_engine_handler_->last_set_surrounding_anchor_pos()); -} - -TEST_F(InputMethodChromeOSTest, SurroundingText_BecomeEmptyText) { - ime_->Init(true); - // Click a text input form. - input_type_ = TEXT_INPUT_TYPE_TEXT; - ime_->OnTextInputTypeChanged(this); - - // Set the TextInputClient behaviors. - // If the surrounding text becomes empty, text_range become (0, 0) and - // selection range become invalid. - surrounding_text_ = UTF8ToUTF16(""); - text_range_ = gfx::Range(0, 0); - selection_range_ = gfx::Range::InvalidRange(); - - ime_->OnCaretBoundsChanged(this); - - // Check the call count. - EXPECT_EQ(0, - mock_ime_engine_handler_->set_surrounding_text_call_count()); - - // Should not be called twice with same condition. - ime_->OnCaretBoundsChanged(this); - EXPECT_EQ(0, - mock_ime_engine_handler_->set_surrounding_text_call_count()); -} - -class InputMethodChromeOSKeyEventTest : public InputMethodChromeOSTest { - public: - InputMethodChromeOSKeyEventTest() {} - virtual ~InputMethodChromeOSKeyEventTest() {} - - virtual void SetUp() override { - InputMethodChromeOSTest::SetUp(); - ime_->Init(true); - } - - DISALLOW_COPY_AND_ASSIGN(InputMethodChromeOSKeyEventTest); -}; - -TEST_F(InputMethodChromeOSKeyEventTest, KeyEventDelayResponseTest) { - const int kFlags = ui::EF_SHIFT_DOWN; - ScopedXI2Event xevent; - xevent.InitKeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_A, kFlags); - const ui::KeyEvent event(xevent); - - // Do key event. - input_type_ = TEXT_INPUT_TYPE_TEXT; - ime_->OnTextInputTypeChanged(this); - ime_->DispatchKeyEvent(event); - - // Check before state. - const ui::KeyEvent* key_event = - mock_ime_engine_handler_->last_processed_key_event(); - EXPECT_EQ(1, mock_ime_engine_handler_->process_key_event_call_count()); - EXPECT_EQ(ui::VKEY_A, key_event->key_code()); - EXPECT_EQ("KeyA", key_event->code()); - EXPECT_EQ(kFlags, key_event->flags()); - EXPECT_EQ(0, ime_->process_key_event_post_ime_call_count()); - - // Do callback. - mock_ime_engine_handler_->last_passed_callback().Run(true); - - // Check the results - EXPECT_EQ(1, ime_->process_key_event_post_ime_call_count()); - const ui::KeyEvent* stored_event = - ime_->process_key_event_post_ime_args().event; - EXPECT_TRUE(stored_event->HasNativeEvent()); - EXPECT_TRUE(IsEqualXKeyEvent(*xevent, *(stored_event->native_event()))); - EXPECT_TRUE(ime_->process_key_event_post_ime_args().handled); -} - -TEST_F(InputMethodChromeOSKeyEventTest, MultiKeyEventDelayResponseTest) { - // Preparation - input_type_ = TEXT_INPUT_TYPE_TEXT; - ime_->OnTextInputTypeChanged(this); - - const int kFlags = ui::EF_SHIFT_DOWN; - ScopedXI2Event xevent; - xevent.InitKeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_B, kFlags); - const ui::KeyEvent event(xevent); - - // Do key event. - ime_->DispatchKeyEvent(event); - const ui::KeyEvent* key_event = - mock_ime_engine_handler_->last_processed_key_event(); - EXPECT_EQ(ui::VKEY_B, key_event->key_code()); - EXPECT_EQ("KeyB", key_event->code()); - EXPECT_EQ(kFlags, key_event->flags()); - - KeyEventCallback first_callback = - mock_ime_engine_handler_->last_passed_callback(); - - // Do key event again. - ScopedXI2Event xevent2; - xevent2.InitKeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_C, kFlags); - const ui::KeyEvent event2(xevent2); - - ime_->DispatchKeyEvent(event2); - const ui::KeyEvent* key_event2 = - mock_ime_engine_handler_->last_processed_key_event(); - EXPECT_EQ(ui::VKEY_C, key_event2->key_code()); - EXPECT_EQ("KeyC", key_event2->code()); - EXPECT_EQ(kFlags, key_event2->flags()); - - // Check before state. - EXPECT_EQ(2, - mock_ime_engine_handler_->process_key_event_call_count()); - EXPECT_EQ(0, ime_->process_key_event_post_ime_call_count()); - - // Do callback for first key event. - first_callback.Run(true); - - // Check the results for first key event. - EXPECT_EQ(1, ime_->process_key_event_post_ime_call_count()); - const ui::KeyEvent* stored_event = - ime_->process_key_event_post_ime_args().event; - EXPECT_TRUE(stored_event->HasNativeEvent()); - EXPECT_TRUE(IsEqualXKeyEvent(*xevent, *(stored_event->native_event()))); - EXPECT_TRUE(ime_->process_key_event_post_ime_args().handled); - - // Do callback for second key event. - mock_ime_engine_handler_->last_passed_callback().Run(false); - - // Check the results for second key event. - EXPECT_EQ(2, ime_->process_key_event_post_ime_call_count()); - stored_event = ime_->process_key_event_post_ime_args().event; - EXPECT_TRUE(stored_event->HasNativeEvent()); - EXPECT_TRUE(IsEqualXKeyEvent(*xevent2, *(stored_event->native_event()))); - EXPECT_FALSE(ime_->process_key_event_post_ime_args().handled); -} - -TEST_F(InputMethodChromeOSKeyEventTest, KeyEventDelayResponseResetTest) { - ScopedXI2Event xevent; - xevent.InitKeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_A, ui::EF_SHIFT_DOWN); - const ui::KeyEvent event(xevent); - - // Do key event. - input_type_ = TEXT_INPUT_TYPE_TEXT; - ime_->OnTextInputTypeChanged(this); - ime_->DispatchKeyEvent(event); - - // Check before state. - EXPECT_EQ(1, mock_ime_engine_handler_->process_key_event_call_count()); - EXPECT_EQ(0, ime_->process_key_event_post_ime_call_count()); - - ime_->ResetContext(); - - // Do callback. - mock_ime_engine_handler_->last_passed_callback().Run(true); - - EXPECT_EQ(0, ime_->process_key_event_post_ime_call_count()); -} -// TODO(nona): Introduce ProcessKeyEventPostIME tests(crbug.com/156593). - -} // namespace ui
diff --git a/ui/base/ime/input_method_delegate.h b/ui/base/ime/input_method_delegate.h deleted file mode 100644 index 080a8f6..0000000 --- a/ui/base/ime/input_method_delegate.h +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_INPUT_METHOD_DELEGATE_H_ -#define UI_BASE_IME_INPUT_METHOD_DELEGATE_H_ - -#include "ui/base/ui_base_export.h" - -namespace ui { - -class KeyEvent; - -namespace internal { - -// An interface implemented by the object that handles events sent back from an -// ui::InputMethod implementation. -class UI_BASE_EXPORT InputMethodDelegate { - public: - virtual ~InputMethodDelegate() {} - - // Dispatch a key event already processed by the input method. - // Returns true if the event was processed. - virtual bool DispatchKeyEventPostIME(const ui::KeyEvent& key_event) = 0; -}; - -} // namespace internal -} // namespace ui - -#endif // UI_BASE_IME_INPUT_METHOD_DELEGATE_H_
diff --git a/ui/base/ime/input_method_factory.cc b/ui/base/ime/input_method_factory.cc deleted file mode 100644 index e1ad03d..0000000 --- a/ui/base/ime/input_method_factory.cc +++ /dev/null
@@ -1,69 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/input_method_factory.h" - -#include "ui/base/ime/mock_input_method.h" - -#if defined(OS_CHROMEOS) -#include "ui/base/ime/input_method_chromeos.h" -#elif defined(OS_WIN) -#include "base/win/metro.h" -#include "ui/base/ime/input_method_win.h" -#include "ui/base/ime/remote_input_method_win.h" -#elif defined(OS_MACOSX) -#include "ui/base/ime/input_method_mac.h" -#elif defined(USE_AURA) && defined(OS_LINUX) && !defined(OS_CHROMEOS) -#include "ui/base/ime/input_method_auralinux.h" -#else -#include "ui/base/ime/input_method_minimal.h" -#endif - -namespace { - -bool g_input_method_set_for_testing = false; - -bool g_create_input_method_called = false; - -} // namespace - -namespace ui { - -scoped_ptr<InputMethod> CreateInputMethod( - internal::InputMethodDelegate* delegate, - gfx::AcceleratedWidget widget) { - if (!g_create_input_method_called) - g_create_input_method_called = true; - - if (g_input_method_set_for_testing) - return scoped_ptr<InputMethod>(new MockInputMethod(delegate)); - -#if defined(OS_CHROMEOS) - return scoped_ptr<InputMethod>(new InputMethodChromeOS(delegate)); -#elif defined(OS_WIN) - if (IsRemoteInputMethodWinRequired(widget)) - return CreateRemoteInputMethodWin(delegate); - return scoped_ptr<InputMethod>(new InputMethodWin(delegate, widget)); -#elif defined(OS_MACOSX) - return scoped_ptr<InputMethod>(new InputMethodMac(delegate)); -#elif defined(USE_AURA) && defined(OS_LINUX) && !defined(OS_CHROMEOS) - return scoped_ptr<InputMethod>(new InputMethodAuraLinux(delegate)); -#else - return scoped_ptr<InputMethod>(new InputMethodMinimal(delegate)); -#endif -} - -void SetUpInputMethodFactoryForTesting() { - if (g_input_method_set_for_testing) - return; - - CHECK(!g_create_input_method_called) - << "ui::SetUpInputMethodFactoryForTesting was called after use of " - << "ui::CreateInputMethod. You must call " - << "ui::SetUpInputMethodFactoryForTesting earlier."; - - g_input_method_set_for_testing = true; -} - -} // namespace ui
diff --git a/ui/base/ime/input_method_factory.h b/ui/base/ime/input_method_factory.h deleted file mode 100644 index 3debc82..0000000 --- a/ui/base/ime/input_method_factory.h +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_INPUT_METHOD_FACTORY_H_ -#define UI_BASE_IME_INPUT_METHOD_FACTORY_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "ui/base/ime/input_method_initializer.h" -#include "ui/base/ui_base_export.h" -#include "ui/gfx/native_widget_types.h" - -namespace ui { -namespace internal { -class InputMethodDelegate; -} // namespace internal - -class InputMethod; - -// Creates a new instance of InputMethod and returns it. -UI_BASE_EXPORT scoped_ptr<InputMethod> CreateInputMethod( - internal::InputMethodDelegate* delegate, - gfx::AcceleratedWidget widget); - -// Makes CreateInputMethod return a MockInputMethod. -UI_BASE_EXPORT void SetUpInputMethodFactoryForTesting(); - -} // namespace ui; - -#endif // UI_BASE_IME_INPUT_METHOD_FACTORY_H_
diff --git a/ui/base/ime/input_method_initializer.cc b/ui/base/ime/input_method_initializer.cc deleted file mode 100644 index 2fca46c..0000000 --- a/ui/base/ime/input_method_initializer.cc +++ /dev/null
@@ -1,66 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/input_method_initializer.h" - -#if defined(OS_CHROMEOS) -#include "ui/base/ime/chromeos/ime_bridge.h" -#elif defined(USE_AURA) && defined(OS_LINUX) -#include "base/logging.h" -#include "ui/base/ime/linux/fake_input_method_context_factory.h" -#endif - -namespace { - -#if !defined(OS_CHROMEOS) && defined(USE_AURA) && defined(OS_LINUX) -const ui::LinuxInputMethodContextFactory* g_linux_input_method_context_factory; -#endif - -} // namespace - -namespace ui { - -void InitializeInputMethod() { -#if defined(OS_CHROMEOS) - chromeos::IMEBridge::Initialize(); -#endif -} - -void ShutdownInputMethod() { -#if defined(OS_CHROMEOS) - chromeos::IMEBridge::Shutdown(); -#endif -} - -void InitializeInputMethodForTesting() { -#if defined(OS_CHROMEOS) - chromeos::IMEBridge::Initialize(); -#elif defined(USE_AURA) && defined(OS_LINUX) - if (!g_linux_input_method_context_factory) - g_linux_input_method_context_factory = new FakeInputMethodContextFactory(); - const LinuxInputMethodContextFactory* factory = - LinuxInputMethodContextFactory::instance(); - CHECK(!factory || factory == g_linux_input_method_context_factory) - << "LinuxInputMethodContextFactory was already initialized somewhere " - << "else."; - LinuxInputMethodContextFactory::SetInstance( - g_linux_input_method_context_factory); -#endif -} - -void ShutdownInputMethodForTesting() { -#if defined(OS_CHROMEOS) - chromeos::IMEBridge::Shutdown(); -#elif defined(USE_AURA) && defined(OS_LINUX) - const LinuxInputMethodContextFactory* factory = - LinuxInputMethodContextFactory::instance(); - CHECK(!factory || factory == g_linux_input_method_context_factory) - << "An unknown LinuxInputMethodContextFactory was set."; - LinuxInputMethodContextFactory::SetInstance(NULL); - delete g_linux_input_method_context_factory; - g_linux_input_method_context_factory = NULL; -#endif -} - -} // namespace ui
diff --git a/ui/base/ime/input_method_initializer.h b/ui/base/ime/input_method_initializer.h deleted file mode 100644 index 065e53e..0000000 --- a/ui/base/ime/input_method_initializer.h +++ /dev/null
@@ -1,31 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_INPUT_METHOD_INITIALIZER_H_ -#define UI_BASE_IME_INPUT_METHOD_INITIALIZER_H_ - -#include "base/basictypes.h" -#include "ui/base/ui_base_export.h" - -namespace ui { - -// Initializes thread-local resources for input method. This function should be -// called in the UI thread before input method is used. -UI_BASE_EXPORT void InitializeInputMethod(); - -// Shutdown thread-local resources for input method. This function should be -// called in the UI thread after input method is used. -UI_BASE_EXPORT void ShutdownInputMethod(); - -// Initializes thread-local resources for input method. This function is -// intended to be called from Setup function of unit tests. -UI_BASE_EXPORT void InitializeInputMethodForTesting(); - -// Initializes thread-local resources for input method. This function is -// intended to be called from TearDown function of unit tests. -UI_BASE_EXPORT void ShutdownInputMethodForTesting(); - -} // namespace ui - -#endif // UI_BASE_IME_INPUT_METHOD_INITIALIZER_H_
diff --git a/ui/base/ime/input_method_mac.h b/ui/base/ime/input_method_mac.h deleted file mode 100644 index d910fa1..0000000 --- a/ui/base/ime/input_method_mac.h +++ /dev/null
@@ -1,38 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_INPUT_METHOD_MAC_H_ -#define UI_BASE_IME_INPUT_METHOD_MAC_H_ - -#include "ui/base/ime/input_method_base.h" - -namespace ui { - -// A ui::InputMethod implementation for Mac. -// On the Mac, key events don't pass through InputMethod. -// Instead, NSTextInputClient calls are bridged to the currently focused -// ui::TextInputClient object. -class UI_BASE_EXPORT InputMethodMac : public InputMethodBase { - public: - explicit InputMethodMac(internal::InputMethodDelegate* delegate); - ~InputMethodMac() override; - - // Overriden from InputMethod. - bool OnUntranslatedIMEMessage(const base::NativeEvent& event, - NativeEventResult* result) override; - bool DispatchKeyEvent(const ui::KeyEvent& event) override; - void OnCaretBoundsChanged(const TextInputClient* client) override; - void CancelComposition(const TextInputClient* client) override; - void OnInputLocaleChanged() override; - std::string GetInputLocale() override; - bool IsActive() override; - bool IsCandidatePopupOpen() const override; - - private: - DISALLOW_COPY_AND_ASSIGN(InputMethodMac); -}; - -} // namespace ui - -#endif // UI_BASE_IME_INPUT_METHOD_MAC_H_
diff --git a/ui/base/ime/input_method_mac.mm b/ui/base/ime/input_method_mac.mm deleted file mode 100644 index c4b55c9..0000000 --- a/ui/base/ime/input_method_mac.mm +++ /dev/null
@@ -1,49 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/input_method_mac.h" - -namespace ui { - -InputMethodMac::InputMethodMac(internal::InputMethodDelegate* delegate) { - SetDelegate(delegate); -} - -InputMethodMac::~InputMethodMac() { -} - -bool InputMethodMac::OnUntranslatedIMEMessage(const base::NativeEvent& event, - NativeEventResult* result) { - return false; -} - -bool InputMethodMac::DispatchKeyEvent(const ui::KeyEvent& event) { - // IME processing on the Mac does not go through this path. - NOTREACHED(); - return false; -} - -void InputMethodMac::OnCaretBoundsChanged(const TextInputClient* client) { -} - -void InputMethodMac::CancelComposition(const TextInputClient* client) { -} - -void InputMethodMac::OnInputLocaleChanged() { -} - -std::string InputMethodMac::GetInputLocale() { - return ""; -} - -bool InputMethodMac::IsActive() { - return true; -} - -bool InputMethodMac::IsCandidatePopupOpen() const { - // There seems to be no way to tell if a candidate window is open. - return false; -} - -} // namespace ui
diff --git a/ui/base/ime/input_method_minimal.cc b/ui/base/ime/input_method_minimal.cc deleted file mode 100644 index 9466c40..0000000 --- a/ui/base/ime/input_method_minimal.cc +++ /dev/null
@@ -1,63 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/input_method_minimal.h" - -#include "ui/base/ime/text_input_client.h" -#include "ui/events/event.h" -#include "ui/events/event_constants.h" - -namespace ui { - -InputMethodMinimal::InputMethodMinimal( - internal::InputMethodDelegate* delegate) { - SetDelegate(delegate); -} - -InputMethodMinimal::~InputMethodMinimal() {} - -bool InputMethodMinimal::OnUntranslatedIMEMessage( - const base::NativeEvent& event, - NativeEventResult* result) { - return false; -} - -bool InputMethodMinimal::DispatchKeyEvent(const ui::KeyEvent& event) { - DCHECK(event.type() == ET_KEY_PRESSED || event.type() == ET_KEY_RELEASED); - - // If no text input client, do nothing. - if (!GetTextInputClient()) - return DispatchKeyEventPostIME(event); - - // Insert the character. - const bool handled = DispatchKeyEventPostIME(event); - if (event.type() == ET_KEY_PRESSED && GetTextInputClient()) { - const uint16 ch = event.GetCharacter(); - if (ch) { - GetTextInputClient()->InsertChar(ch, event.flags()); - return true; - } - } - return handled; -} - -void InputMethodMinimal::OnCaretBoundsChanged(const TextInputClient* client) {} - -void InputMethodMinimal::CancelComposition(const TextInputClient* client) {} - -void InputMethodMinimal::OnInputLocaleChanged() {} - -std::string InputMethodMinimal::GetInputLocale() { - return std::string(); -} - -bool InputMethodMinimal::IsActive() { - return true; -} - -bool InputMethodMinimal::IsCandidatePopupOpen() const { - return false; -} - -} // namespace ui
diff --git a/ui/base/ime/input_method_minimal.h b/ui/base/ime/input_method_minimal.h deleted file mode 100644 index 14700f5..0000000 --- a/ui/base/ime/input_method_minimal.h +++ /dev/null
@@ -1,36 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_INPUT_METHOD_MINIMAL_H_ -#define UI_BASE_IME_INPUT_METHOD_MINIMAL_H_ - -#include "ui/base/ime/input_method_base.h" - -namespace ui { - -// A minimal implementation of ui::InputMethod, which supports only the direct -// input without any compositions or conversions. -class UI_BASE_EXPORT InputMethodMinimal : public InputMethodBase { - public: - explicit InputMethodMinimal(internal::InputMethodDelegate* delegate); - virtual ~InputMethodMinimal(); - - // Overriden from InputMethod. - virtual bool OnUntranslatedIMEMessage(const base::NativeEvent& event, - NativeEventResult* result) override; - virtual bool DispatchKeyEvent(const ui::KeyEvent& event) override; - virtual void OnCaretBoundsChanged(const TextInputClient* client) override; - virtual void CancelComposition(const TextInputClient* client) override; - virtual void OnInputLocaleChanged() override; - virtual std::string GetInputLocale() override; - virtual bool IsActive() override; - virtual bool IsCandidatePopupOpen() const override; - - private: - DISALLOW_COPY_AND_ASSIGN(InputMethodMinimal); -}; - -} // namespace ui - -#endif // UI_BASE_IME_INPUT_METHOD_MINIMAL_H_
diff --git a/ui/base/ime/input_method_observer.h b/ui/base/ime/input_method_observer.h deleted file mode 100644 index d3432c9..0000000 --- a/ui/base/ime/input_method_observer.h +++ /dev/null
@@ -1,50 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_INPUT_METHOD_OBSERVER_H_ -#define UI_BASE_IME_INPUT_METHOD_OBSERVER_H_ - -#include "ui/base/ui_base_export.h" - -namespace ui { - -class InputMethod; -class TextInputClient; - -class UI_BASE_EXPORT InputMethodObserver { - public: - virtual ~InputMethodObserver() {} - - // Called whenever the text input type is changed for the focused client. - // Currently only used by the mock input method for testing. - virtual void OnTextInputTypeChanged(const TextInputClient* client) = 0; - - // Called when the top-level system window gets keyboard focus. Currently - // only used by the mock input method for testing. - virtual void OnFocus() = 0; - - // Called when the top-level system window loses keyboard focus. Currently - // only used by the mock input method for testing. - virtual void OnBlur() = 0; - - // Called whenever the caret bounds is changed for the input client. - // Currently only used by the mock input method for testing. - virtual void OnCaretBoundsChanged(const TextInputClient* client) = 0; - - // Called when either: - // - the TextInputClient is changed (e.g. by a change of focus) - // - the TextInputType of the TextInputClient changes - virtual void OnTextInputStateChanged(const TextInputClient* client) = 0; - - // Called when the observed InputMethod is being destroyed. - virtual void OnInputMethodDestroyed(const InputMethod* input_method) = 0; - - // Called when a user gesture should trigger showing the virtual keyboard - // or alternate input view (e.g. handwriting palette). Used in ChromeOS. - virtual void OnShowImeIfNeeded() = 0; -}; - -} // namespace ui - -#endif // UI_BASE_IME_INPUT_METHOD_OBSERVER_H_
diff --git a/ui/base/ime/input_method_win.cc b/ui/base/ime/input_method_win.cc deleted file mode 100644 index f6bc4c0..0000000 --- a/ui/base/ime/input_method_win.cc +++ /dev/null
@@ -1,617 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/input_method_win.h" - -#include "base/basictypes.h" -#include "ui/base/ime/text_input_client.h" -#include "ui/base/ime/win/tsf_input_scope.h" -#include "ui/events/event.h" -#include "ui/events/event_constants.h" -#include "ui/events/event_utils.h" -#include "ui/events/keycodes/keyboard_codes.h" -#include "ui/gfx/win/dpi.h" -#include "ui/gfx/win/hwnd_util.h" - -namespace ui { -namespace { - -// Extra number of chars before and after selection (or composition) range which -// is returned to IME for improving conversion accuracy. -static const size_t kExtraNumberOfChars = 20; - -} // namespace - -InputMethodWin::InputMethodWin(internal::InputMethodDelegate* delegate, - HWND toplevel_window_handle) - : toplevel_window_handle_(toplevel_window_handle), - pending_requested_direction_(base::i18n::UNKNOWN_DIRECTION), - accept_carriage_return_(false), - active_(false), - enabled_(false), - is_candidate_popup_open_(false), - composing_window_handle_(NULL) { - SetDelegate(delegate); - // In non-Aura environment, appropriate callbacks to OnFocus() and OnBlur() - // are not implemented yet. To work around this limitation, here we use - // "always focused" model. - // TODO(ime): Fix the caller of OnFocus() and OnBlur() so that appropriate - // focus event will be passed. - InputMethodBase::OnFocus(); -} - -void InputMethodWin::Init(bool focused) { - // Gets the initial input locale. - OnInputLocaleChanged(); - - InputMethodBase::Init(focused); -} - -void InputMethodWin::OnFocus() { - // Ignore OnFocus event for "always focused" model. See the comment in the - // constructor. - // TODO(ime): Implement OnFocus once the callers are fixed. -} - -void InputMethodWin::OnBlur() { - // Ignore OnBlur event for "always focused" model. See the comment in the - // constructor. - // TODO(ime): Implement OnFocus once the callers are fixed. -} - -bool InputMethodWin::OnUntranslatedIMEMessage( - const base::NativeEvent& event, - InputMethod::NativeEventResult* result) { - LRESULT original_result = 0; - BOOL handled = FALSE; - switch (event.message) { - case WM_IME_SETCONTEXT: - original_result = OnImeSetContext( - event.hwnd, event.message, event.wParam, event.lParam, &handled); - break; - case WM_IME_STARTCOMPOSITION: - original_result = OnImeStartComposition( - event.hwnd, event.message, event.wParam, event.lParam, &handled); - break; - case WM_IME_COMPOSITION: - original_result = OnImeComposition( - event.hwnd, event.message, event.wParam, event.lParam, &handled); - break; - case WM_IME_ENDCOMPOSITION: - original_result = OnImeEndComposition( - event.hwnd, event.message, event.wParam, event.lParam, &handled); - break; - case WM_IME_REQUEST: - original_result = OnImeRequest( - event.message, event.wParam, event.lParam, &handled); - break; - case WM_CHAR: - case WM_SYSCHAR: - original_result = OnChar( - event.hwnd, event.message, event.wParam, event.lParam, &handled); - break; - case WM_IME_NOTIFY: - original_result = OnImeNotify( - event.message, event.wParam, event.lParam, &handled); - break; - default: - NOTREACHED() << "Unknown IME message:" << event.message; - break; - } - if (result) - *result = original_result; - return !!handled; -} - -bool InputMethodWin::DispatchKeyEvent(const ui::KeyEvent& event) { - if (!event.HasNativeEvent()) - return DispatchFabricatedKeyEvent(event); - - const base::NativeEvent& native_key_event = event.native_event(); - if (native_key_event.message == WM_CHAR) { - BOOL handled; - OnChar(native_key_event.hwnd, native_key_event.message, - native_key_event.wParam, native_key_event.lParam, &handled); - return !!handled; // Don't send WM_CHAR for post event processing. - } - // Handles ctrl-shift key to change text direction and layout alignment. - if (ui::IMM32Manager::IsRTLKeyboardLayoutInstalled() && - !IsTextInputTypeNone()) { - // TODO: shouldn't need to generate a KeyEvent here. - const ui::KeyEvent key(native_key_event); - ui::KeyboardCode code = key.key_code(); - if (key.type() == ui::ET_KEY_PRESSED) { - if (code == ui::VKEY_SHIFT) { - base::i18n::TextDirection dir; - if (ui::IMM32Manager::IsCtrlShiftPressed(&dir)) - pending_requested_direction_ = dir; - } else if (code != ui::VKEY_CONTROL) { - pending_requested_direction_ = base::i18n::UNKNOWN_DIRECTION; - } - } else if (key.type() == ui::ET_KEY_RELEASED && - (code == ui::VKEY_SHIFT || code == ui::VKEY_CONTROL) && - pending_requested_direction_ != base::i18n::UNKNOWN_DIRECTION) { - GetTextInputClient()->ChangeTextDirectionAndLayoutAlignment( - pending_requested_direction_); - pending_requested_direction_ = base::i18n::UNKNOWN_DIRECTION; - } - } - - return DispatchKeyEventPostIME(event); -} - -void InputMethodWin::OnTextInputTypeChanged(const TextInputClient* client) { - if (!IsTextInputClientFocused(client) || !IsWindowFocused(client)) - return; - imm32_manager_.CancelIME(GetAttachedWindowHandle(client)); - UpdateIMEState(); -} - -void InputMethodWin::OnCaretBoundsChanged(const TextInputClient* client) { - if (!enabled_ || !IsTextInputClientFocused(client) || - !IsWindowFocused(client)) { - return; - } - // The current text input type should not be NONE if |client| is focused. - DCHECK(!IsTextInputTypeNone()); - // Tentatively assume that the returned value is DIP (Density Independent - // Pixel). See the comment in text_input_client.h and http://crbug.com/360334. - const gfx::Rect dip_screen_bounds(GetTextInputClient()->GetCaretBounds()); - const gfx::Rect screen_bounds = gfx::win::DIPToScreenRect(dip_screen_bounds); - - HWND attached_window = GetAttachedWindowHandle(client); - // TODO(ime): see comment in TextInputClient::GetCaretBounds(), this - // conversion shouldn't be necessary. - RECT r = {}; - GetClientRect(attached_window, &r); - POINT window_point = { screen_bounds.x(), screen_bounds.y() }; - ScreenToClient(attached_window, &window_point); - gfx::Rect caret_rect(gfx::Point(window_point.x, window_point.y), - screen_bounds.size()); - imm32_manager_.UpdateCaretRect(attached_window, caret_rect); -} - -void InputMethodWin::CancelComposition(const TextInputClient* client) { - if (enabled_ && IsTextInputClientFocused(client)) - imm32_manager_.CancelIME(GetAttachedWindowHandle(client)); -} - -void InputMethodWin::OnInputLocaleChanged() { - active_ = imm32_manager_.SetInputLanguage(); - locale_ = imm32_manager_.GetInputLanguageName(); - OnInputMethodChanged(); -} - -std::string InputMethodWin::GetInputLocale() { - return locale_; -} - -bool InputMethodWin::IsActive() { - return active_; -} - -bool InputMethodWin::IsCandidatePopupOpen() const { - return is_candidate_popup_open_; -} - -void InputMethodWin::OnWillChangeFocusedClient(TextInputClient* focused_before, - TextInputClient* focused) { - if (IsWindowFocused(focused_before)) - ConfirmCompositionText(); -} - -void InputMethodWin::OnDidChangeFocusedClient( - TextInputClient* focused_before, - TextInputClient* focused) { - if (IsWindowFocused(focused)) { - // Force to update the input type since client's TextInputStateChanged() - // function might not be called if text input types before the client loses - // focus and after it acquires focus again are the same. - OnTextInputTypeChanged(focused); - - UpdateIMEState(); - - // Force to update caret bounds, in case the client thinks that the caret - // bounds has not changed. - OnCaretBoundsChanged(focused); - } - if (focused_before != focused) - accept_carriage_return_ = false; -} - -LRESULT InputMethodWin::OnChar(HWND window_handle, - UINT message, - WPARAM wparam, - LPARAM lparam, - BOOL* handled) { - *handled = TRUE; - - // We need to send character events to the focused text input client event if - // its text input type is ui::TEXT_INPUT_TYPE_NONE. - if (GetTextInputClient()) { - const base::char16 kCarriageReturn = L'\r'; - const base::char16 ch = static_cast<base::char16>(wparam); - // A mask to determine the previous key state from |lparam|. The value is 1 - // if the key is down before the message is sent, or it is 0 if the key is - // up. - const uint32 kPrevKeyDownBit = 0x40000000; - if (ch == kCarriageReturn && !(lparam & kPrevKeyDownBit)) - accept_carriage_return_ = true; - // Conditionally ignore '\r' events to work around crbug.com/319100. - // TODO(yukawa, IME): Figure out long-term solution. - if (ch != kCarriageReturn || accept_carriage_return_) - GetTextInputClient()->InsertChar(ch, ui::GetModifiersFromKeyState()); - } - - // Explicitly show the system menu at a good location on [Alt]+[Space]. - // Note: Setting |handled| to FALSE for DefWindowProc triggering of the system - // menu causes undesirable titlebar artifacts in the classic theme. - if (message == WM_SYSCHAR && wparam == VK_SPACE) - gfx::ShowSystemMenu(window_handle); - - return 0; -} - -LRESULT InputMethodWin::OnImeSetContext(HWND window_handle, - UINT message, - WPARAM wparam, - LPARAM lparam, - BOOL* handled) { - if (!!wparam) - imm32_manager_.CreateImeWindow(window_handle); - - OnInputMethodChanged(); - return imm32_manager_.SetImeWindowStyle( - window_handle, message, wparam, lparam, handled); -} - -LRESULT InputMethodWin::OnImeStartComposition(HWND window_handle, - UINT message, - WPARAM wparam, - LPARAM lparam, - BOOL* handled) { - // We have to prevent WTL from calling ::DefWindowProc() because the function - // calls ::ImmSetCompositionWindow() and ::ImmSetCandidateWindow() to - // over-write the position of IME windows. - *handled = TRUE; - - // Reset the composition status and create IME windows. - composing_window_handle_ = window_handle; - imm32_manager_.CreateImeWindow(window_handle); - imm32_manager_.ResetComposition(window_handle); - return 0; -} - -LRESULT InputMethodWin::OnImeComposition(HWND window_handle, - UINT message, - WPARAM wparam, - LPARAM lparam, - BOOL* handled) { - // We have to prevent WTL from calling ::DefWindowProc() because we do not - // want for the IMM (Input Method Manager) to send WM_IME_CHAR messages. - *handled = TRUE; - - // At first, update the position of the IME window. - imm32_manager_.UpdateImeWindow(window_handle); - - // Retrieve the result string and its attributes of the ongoing composition - // and send it to a renderer process. - ui::CompositionText composition; - if (imm32_manager_.GetResult(window_handle, lparam, &composition.text)) { - if (!IsTextInputTypeNone()) - GetTextInputClient()->InsertText(composition.text); - imm32_manager_.ResetComposition(window_handle); - // Fall though and try reading the composition string. - // Japanese IMEs send a message containing both GCS_RESULTSTR and - // GCS_COMPSTR, which means an ongoing composition has been finished - // by the start of another composition. - } - // Retrieve the composition string and its attributes of the ongoing - // composition and send it to a renderer process. - if (imm32_manager_.GetComposition(window_handle, lparam, &composition) && - !IsTextInputTypeNone()) - GetTextInputClient()->SetCompositionText(composition); - - return 0; -} - -LRESULT InputMethodWin::OnImeEndComposition(HWND window_handle, - UINT message, - WPARAM wparam, - LPARAM lparam, - BOOL* handled) { - // Let WTL call ::DefWindowProc() and release its resources. - *handled = FALSE; - - composing_window_handle_ = NULL; - - if (!IsTextInputTypeNone() && GetTextInputClient()->HasCompositionText()) - GetTextInputClient()->ClearCompositionText(); - - imm32_manager_.ResetComposition(window_handle); - imm32_manager_.DestroyImeWindow(window_handle); - return 0; -} - -LRESULT InputMethodWin::OnImeNotify(UINT message, - WPARAM wparam, - LPARAM lparam, - BOOL* handled) { - *handled = FALSE; - - bool previous_state = is_candidate_popup_open_; - - // Update |is_candidate_popup_open_|, whether a candidate window is open. - switch (wparam) { - case IMN_OPENCANDIDATE: - is_candidate_popup_open_ = true; - if (!previous_state) - OnCandidateWindowShown(); - break; - case IMN_CLOSECANDIDATE: - is_candidate_popup_open_ = false; - if (previous_state) - OnCandidateWindowHidden(); - break; - case IMN_CHANGECANDIDATE: - // TODO(kochi): The IME API expects this event to notify window size change, - // while this may fire more often without window resize. There is no generic - // way to get bounds of candidate window. - OnCandidateWindowUpdated(); - break; - } - - return 0; -} - -LRESULT InputMethodWin::OnImeRequest(UINT message, - WPARAM wparam, - LPARAM lparam, - BOOL* handled) { - *handled = FALSE; - - // Should not receive WM_IME_REQUEST message, if IME is disabled. - const ui::TextInputType type = GetTextInputType(); - if (type == ui::TEXT_INPUT_TYPE_NONE || - type == ui::TEXT_INPUT_TYPE_PASSWORD) { - return 0; - } - - switch (wparam) { - case IMR_RECONVERTSTRING: - *handled = TRUE; - return OnReconvertString(reinterpret_cast<RECONVERTSTRING*>(lparam)); - case IMR_DOCUMENTFEED: - *handled = TRUE; - return OnDocumentFeed(reinterpret_cast<RECONVERTSTRING*>(lparam)); - case IMR_QUERYCHARPOSITION: - *handled = TRUE; - return OnQueryCharPosition(reinterpret_cast<IMECHARPOSITION*>(lparam)); - default: - return 0; - } -} - -LRESULT InputMethodWin::OnDocumentFeed(RECONVERTSTRING* reconv) { - ui::TextInputClient* client = GetTextInputClient(); - if (!client) - return 0; - - gfx::Range text_range; - if (!client->GetTextRange(&text_range) || text_range.is_empty()) - return 0; - - bool result = false; - gfx::Range target_range; - if (client->HasCompositionText()) - result = client->GetCompositionTextRange(&target_range); - - if (!result || target_range.is_empty()) { - if (!client->GetSelectionRange(&target_range) || - !target_range.IsValid()) { - return 0; - } - } - - if (!text_range.Contains(target_range)) - return 0; - - if (target_range.GetMin() - text_range.start() > kExtraNumberOfChars) - text_range.set_start(target_range.GetMin() - kExtraNumberOfChars); - - if (text_range.end() - target_range.GetMax() > kExtraNumberOfChars) - text_range.set_end(target_range.GetMax() + kExtraNumberOfChars); - - size_t len = text_range.length(); - size_t need_size = sizeof(RECONVERTSTRING) + len * sizeof(WCHAR); - - if (!reconv) - return need_size; - - if (reconv->dwSize < need_size) - return 0; - - base::string16 text; - if (!GetTextInputClient()->GetTextFromRange(text_range, &text)) - return 0; - DCHECK_EQ(text_range.length(), text.length()); - - reconv->dwVersion = 0; - reconv->dwStrLen = len; - reconv->dwStrOffset = sizeof(RECONVERTSTRING); - reconv->dwCompStrLen = - client->HasCompositionText() ? target_range.length() : 0; - reconv->dwCompStrOffset = - (target_range.GetMin() - text_range.start()) * sizeof(WCHAR); - reconv->dwTargetStrLen = target_range.length(); - reconv->dwTargetStrOffset = reconv->dwCompStrOffset; - - memcpy((char*)reconv + sizeof(RECONVERTSTRING), - text.c_str(), len * sizeof(WCHAR)); - - // According to Microsoft API document, IMR_RECONVERTSTRING and - // IMR_DOCUMENTFEED should return reconv, but some applications return - // need_size. - return reinterpret_cast<LRESULT>(reconv); -} - -LRESULT InputMethodWin::OnReconvertString(RECONVERTSTRING* reconv) { - ui::TextInputClient* client = GetTextInputClient(); - if (!client) - return 0; - - // If there is a composition string already, we don't allow reconversion. - if (client->HasCompositionText()) - return 0; - - gfx::Range text_range; - if (!client->GetTextRange(&text_range) || text_range.is_empty()) - return 0; - - gfx::Range selection_range; - if (!client->GetSelectionRange(&selection_range) || - selection_range.is_empty()) { - return 0; - } - - DCHECK(text_range.Contains(selection_range)); - - size_t len = selection_range.length(); - size_t need_size = sizeof(RECONVERTSTRING) + len * sizeof(WCHAR); - - if (!reconv) - return need_size; - - if (reconv->dwSize < need_size) - return 0; - - // TODO(penghuang): Return some extra context to help improve IME's - // reconversion accuracy. - base::string16 text; - if (!GetTextInputClient()->GetTextFromRange(selection_range, &text)) - return 0; - DCHECK_EQ(selection_range.length(), text.length()); - - reconv->dwVersion = 0; - reconv->dwStrLen = len; - reconv->dwStrOffset = sizeof(RECONVERTSTRING); - reconv->dwCompStrLen = len; - reconv->dwCompStrOffset = 0; - reconv->dwTargetStrLen = len; - reconv->dwTargetStrOffset = 0; - - memcpy(reinterpret_cast<char*>(reconv) + sizeof(RECONVERTSTRING), - text.c_str(), len * sizeof(WCHAR)); - - // According to Microsoft API document, IMR_RECONVERTSTRING and - // IMR_DOCUMENTFEED should return reconv, but some applications return - // need_size. - return reinterpret_cast<LRESULT>(reconv); -} - -LRESULT InputMethodWin::OnQueryCharPosition(IMECHARPOSITION* char_positon) { - if (!char_positon) - return 0; - - if (char_positon->dwSize < sizeof(IMECHARPOSITION)) - return 0; - - ui::TextInputClient* client = GetTextInputClient(); - if (!client) - return 0; - - // Tentatively assume that the returned value from |client| is DIP (Density - // Independent Pixel). See the comment in text_input_client.h and - // http://crbug.com/360334. - gfx::Rect dip_rect; - if (client->HasCompositionText()) { - if (!client->GetCompositionCharacterBounds(char_positon->dwCharPos, - &dip_rect)) { - return 0; - } - } else { - // If there is no composition and the first character is queried, returns - // the caret bounds. This behavior is the same to that of RichEdit control. - if (char_positon->dwCharPos != 0) - return 0; - dip_rect = client->GetCaretBounds(); - } - const gfx::Rect rect = gfx::win::DIPToScreenRect(dip_rect); - - char_positon->pt.x = rect.x(); - char_positon->pt.y = rect.y(); - char_positon->cLineHeight = rect.height(); - return 1; // returns non-zero value when succeeded. -} - -HWND InputMethodWin::GetAttachedWindowHandle( - const TextInputClient* text_input_client) const { - // On Aura environment, we can assume that |toplevel_window_handle_| always - // represents the valid top-level window handle because each top-level window - // is responsible for lifecycle management of corresponding InputMethod - // instance. - return toplevel_window_handle_; -} - -bool InputMethodWin::IsWindowFocused(const TextInputClient* client) const { - if (!client) - return false; - HWND attached_window_handle = GetAttachedWindowHandle(client); - // When Aura is enabled, |attached_window_handle| should always be a top-level - // window. So we can safely assume that |attached_window_handle| is ready for - // receiving keyboard input as long as it is an active window. This works well - // even when the |attached_window_handle| becomes active but has not received - // WM_FOCUS yet. - return attached_window_handle && GetActiveWindow() == attached_window_handle; -} - -bool InputMethodWin::DispatchFabricatedKeyEvent(const ui::KeyEvent& event) { - if (event.is_char()) { - if (GetTextInputClient()) { - GetTextInputClient()->InsertChar( - static_cast<base::char16>(event.key_code()), - ui::GetModifiersFromKeyState()); - return true; - } - } - return DispatchKeyEventPostIME(event); -} - -void InputMethodWin::ConfirmCompositionText() { - if (composing_window_handle_) - imm32_manager_.CleanupComposition(composing_window_handle_); - - if (!IsTextInputTypeNone()) { - // Though above line should confirm the client's composition text by sending - // a result text to us, in case the input method and the client are in - // inconsistent states, we check the client's composition state again. - if (GetTextInputClient()->HasCompositionText()) - GetTextInputClient()->ConfirmCompositionText(); - } -} - -void InputMethodWin::UpdateIMEState() { - // Use switch here in case we are going to add more text input types. - // We disable input method in password field. - const HWND window_handle = GetAttachedWindowHandle(GetTextInputClient()); - const TextInputType text_input_type = GetTextInputType(); - const TextInputMode text_input_mode = GetTextInputMode(); - switch (text_input_type) { - case ui::TEXT_INPUT_TYPE_NONE: - case ui::TEXT_INPUT_TYPE_PASSWORD: - imm32_manager_.DisableIME(window_handle); - enabled_ = false; - break; - default: - imm32_manager_.EnableIME(window_handle); - enabled_ = true; - break; - } - - imm32_manager_.SetTextInputMode(window_handle, text_input_mode); - tsf_inputscope::SetInputScopeForTsfUnawareWindow( - window_handle, text_input_type, text_input_mode); -} - -} // namespace ui
diff --git a/ui/base/ime/input_method_win.h b/ui/base/ime/input_method_win.h deleted file mode 100644 index b6d5320..0000000 --- a/ui/base/ime/input_method_win.h +++ /dev/null
@@ -1,149 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_INPUT_METHOD_WIN_H_ -#define UI_BASE_IME_INPUT_METHOD_WIN_H_ - -#include <windows.h> - -#include <string> - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "ui/base/ime/input_method_base.h" -#include "ui/base/ime/win/imm32_manager.h" - -namespace ui { - -// A common InputMethod implementation based on IMM32. -class UI_BASE_EXPORT InputMethodWin : public InputMethodBase { - public: - InputMethodWin(internal::InputMethodDelegate* delegate, - HWND toplevel_window_handle); - - // Overridden from InputMethod: - virtual void Init(bool focused) override; - virtual void OnFocus() override; - virtual void OnBlur() override; - virtual bool OnUntranslatedIMEMessage(const base::NativeEvent& event, - NativeEventResult* result) override; - virtual bool DispatchKeyEvent(const ui::KeyEvent& event) override; - virtual void OnTextInputTypeChanged(const TextInputClient* client) override; - virtual void OnCaretBoundsChanged(const TextInputClient* client) override; - virtual void CancelComposition(const TextInputClient* client) override; - virtual void OnInputLocaleChanged() override; - virtual std::string GetInputLocale() override; - virtual bool IsActive() override; - virtual bool IsCandidatePopupOpen() const override; - - protected: - // Overridden from InputMethodBase: - // If a derived class overrides this method, it should call parent's - // implementation. - virtual void OnWillChangeFocusedClient(TextInputClient* focused_before, - TextInputClient* focused) override; - virtual void OnDidChangeFocusedClient(TextInputClient* focused_before, - TextInputClient* focused) override; - - private: - // For both WM_CHAR and WM_SYSCHAR - LRESULT OnChar(HWND window_handle, - UINT message, - WPARAM wparam, - LPARAM lparam, - BOOL* handled); - - LRESULT OnImeSetContext(HWND window_handle, - UINT message, - WPARAM wparam, - LPARAM lparam, - BOOL* handled); - LRESULT OnImeStartComposition(HWND window_handle, - UINT message, - WPARAM wparam, - LPARAM lparam, - BOOL* handled); - LRESULT OnImeComposition(HWND window_handle, - UINT message, - WPARAM wparam, - LPARAM lparam, - BOOL* handled); - LRESULT OnImeEndComposition(HWND window_handle, - UINT message, - WPARAM wparam, - LPARAM lparam, - BOOL* handled); - LRESULT OnImeNotify(UINT message, - WPARAM wparam, - LPARAM lparam, - BOOL* handled); - - // Some IMEs rely on WM_IME_REQUEST message even when TSF is enabled. So - // OnImeRequest (and its actual implementations as OnDocumentFeed, - // OnReconvertString, and OnQueryCharPosition) are placed in this base class. - LRESULT OnImeRequest(UINT message, - WPARAM wparam, - LPARAM lparam, - BOOL* handled); - LRESULT OnDocumentFeed(RECONVERTSTRING* reconv); - LRESULT OnReconvertString(RECONVERTSTRING* reconv); - LRESULT OnQueryCharPosition(IMECHARPOSITION* char_positon); - - // Returns the window handle to which |text_input_client| is bound. - // On Aura environment, |toplevel_window_handle_| is always returned. - HWND GetAttachedWindowHandle(const TextInputClient* text_input_client) const; - - // Returns true if the Win32 native window bound to |client| is considered - // to be ready for receiving keyboard input. - bool IsWindowFocused(const TextInputClient* client) const; - - bool DispatchFabricatedKeyEvent(const ui::KeyEvent& event); - - // Asks the client to confirm current composition text. - void ConfirmCompositionText(); - - // Enables or disables the IME according to the current text input type. - void UpdateIMEState(); - - // Windows IMM32 wrapper. - // (See "ui/base/ime/win/ime_input.h" for its details.) - ui::IMM32Manager imm32_manager_; - - // The toplevel window handle. - // On non-Aura environment, this value is not used and always NULL. - const HWND toplevel_window_handle_; - - // Name of the current input locale. - std::string locale_; - - // The new text direction and layout alignment requested by the user by - // pressing ctrl-shift. It'll be sent to the text input client when the key - // is released. - base::i18n::TextDirection pending_requested_direction_; - - // Represents if WM_CHAR[wparam=='\r'] should be dispatched to the focused - // text input client or ignored silently. This flag is introduced as a quick - // workaround against crbug.com/319100 - // TODO(yukawa, IME): Figure out long-term solution. - bool accept_carriage_return_; - - // Indicates if the current input locale has an IME. - bool active_; - - // True when an IME should be allowed to process key events. - bool enabled_; - - // True if we know for sure that a candidate window is open. - bool is_candidate_popup_open_; - - // Window handle where composition is on-going. NULL when there is no - // composition. - HWND composing_window_handle_; - - DISALLOW_COPY_AND_ASSIGN(InputMethodWin); -}; - -} // namespace ui - -#endif // UI_BASE_IME_INPUT_METHOD_WIN_H_
diff --git a/ui/base/ime/linux/fake_input_method_context.cc b/ui/base/ime/linux/fake_input_method_context.cc deleted file mode 100644 index fd0d8e2..0000000 --- a/ui/base/ime/linux/fake_input_method_context.cc +++ /dev/null
@@ -1,29 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/linux/fake_input_method_context.h" - -namespace ui { - -FakeInputMethodContext::FakeInputMethodContext() {} - -// Overriden from ui::LinuxInputMethodContext - -bool FakeInputMethodContext::DispatchKeyEvent( - const ui::KeyEvent& /* key_event */) { - return false; -} - -void FakeInputMethodContext::Reset() { -} - -void FakeInputMethodContext::OnTextInputTypeChanged( - ui::TextInputType /* text_input_type */) { -} - -void FakeInputMethodContext::OnCaretBoundsChanged( - const gfx::Rect& /* caret_bounds */) { -} - -} // namespace ui
diff --git a/ui/base/ime/linux/fake_input_method_context.h b/ui/base/ime/linux/fake_input_method_context.h deleted file mode 100644 index d13d2b9..0000000 --- a/ui/base/ime/linux/fake_input_method_context.h +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_LINUX_FAKE_INPUT_METHOD_CONTEXT_H_ -#define UI_BASE_IME_LINUX_FAKE_INPUT_METHOD_CONTEXT_H_ - -#include "ui/base/ime/linux/linux_input_method_context.h" - -namespace ui { - -// A fake implementation of LinuxInputMethodContext, which does nothing. -class FakeInputMethodContext : public LinuxInputMethodContext { - public: - FakeInputMethodContext(); - - // Overriden from ui::LinuxInputMethodContext - virtual bool DispatchKeyEvent(const ui::KeyEvent& key_event) override; - virtual void Reset() override; - virtual void OnTextInputTypeChanged(ui::TextInputType text_input_type) - override; - virtual void OnCaretBoundsChanged(const gfx::Rect& caret_bounds) override; - - private: - DISALLOW_COPY_AND_ASSIGN(FakeInputMethodContext); -}; - -} // namespace ui - -#endif // UI_BASE_IME_LINUX_FAKE_INPUT_METHOD_CONTEXT_H_
diff --git a/ui/base/ime/linux/fake_input_method_context_factory.cc b/ui/base/ime/linux/fake_input_method_context_factory.cc deleted file mode 100644 index ba9edf6..0000000 --- a/ui/base/ime/linux/fake_input_method_context_factory.cc +++ /dev/null
@@ -1,21 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/linux/fake_input_method_context_factory.h" - -#include "ui/base/ime/linux/fake_input_method_context.h" - -namespace ui { - -FakeInputMethodContextFactory::FakeInputMethodContextFactory() {} - -// Overriden from ui::LinuxInputMethodContextFactory - -scoped_ptr<LinuxInputMethodContext> -FakeInputMethodContextFactory::CreateInputMethodContext( - LinuxInputMethodContextDelegate* /* delegate */) const { - return scoped_ptr<LinuxInputMethodContext>(new FakeInputMethodContext()); -} - -} // namespace ui
diff --git a/ui/base/ime/linux/fake_input_method_context_factory.h b/ui/base/ime/linux/fake_input_method_context_factory.h deleted file mode 100644 index d6101fa..0000000 --- a/ui/base/ime/linux/fake_input_method_context_factory.h +++ /dev/null
@@ -1,28 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_LINUX_FAKE_INPUT_METHOD_CONTEXT_FACTORY_H_ -#define UI_BASE_IME_LINUX_FAKE_INPUT_METHOD_CONTEXT_FACTORY_H_ - -#include "ui/base/ime/linux/linux_input_method_context_factory.h" - -namespace ui { - -// An implementation of LinuxInputMethodContextFactory, which creates and -// returns FakeInputMethodContext's. -class FakeInputMethodContextFactory : public LinuxInputMethodContextFactory { - public: - FakeInputMethodContextFactory(); - - // Overriden from ui::LinuxInputMethodContextFactory - virtual scoped_ptr<LinuxInputMethodContext> CreateInputMethodContext( - LinuxInputMethodContextDelegate* delegate) const override; - - private: - DISALLOW_COPY_AND_ASSIGN(FakeInputMethodContextFactory); -}; - -} // namespace ui - -#endif // UI_BASE_IME_LINUX_FAKE_INPUT_METHOD_CONTEXT_FACTORY_H_
diff --git a/ui/base/ime/linux/linux_input_method_context.h b/ui/base/ime/linux/linux_input_method_context.h deleted file mode 100644 index 0bcfd0a..0000000 --- a/ui/base/ime/linux/linux_input_method_context.h +++ /dev/null
@@ -1,65 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_LINUX_LINUX_INPUT_METHOD_CONTEXT_H_ -#define UI_BASE_IME_LINUX_LINUX_INPUT_METHOD_CONTEXT_H_ - -#include "base/strings/string16.h" -#include "ui/base/ime/text_input_type.h" -#include "ui/base/ui_base_export.h" - -namespace gfx { -class Rect; -} - -namespace ui { - -struct CompositionText; -class KeyEvent; - -// An interface of input method context for input method frameworks on -// GNU/Linux and likes. -class UI_BASE_EXPORT LinuxInputMethodContext { - public: - virtual ~LinuxInputMethodContext() {} - - // Dispatches the key event to an underlying IME. Returns true if the key - // event is handled, otherwise false. A client must set the text input type - // before dispatching a key event. - virtual bool DispatchKeyEvent(const ui::KeyEvent& key_event) = 0; - - // Resets the context. A client needs to call OnTextInputTypeChanged() again - // before calling DispatchKeyEvent(). - virtual void Reset() = 0; - - // Notifies the context that the text input type has changed. - virtual void OnTextInputTypeChanged(TextInputType text_input_type) = 0; - - // Notifies the context that the caret bounds have changed. |caret_bounds| is - // relative to screen coordinates. - virtual void OnCaretBoundsChanged(const gfx::Rect& caret_bounds) = 0; -}; - -// An interface of callback functions called from LinuxInputMethodContext. -class UI_BASE_EXPORT LinuxInputMethodContextDelegate { - public: - virtual ~LinuxInputMethodContextDelegate() {} - - // Commits the |text| to the text input client. - virtual void OnCommit(const base::string16& text) = 0; - - // Sets the composition text to the text input client. - virtual void OnPreeditChanged(const CompositionText& composition_text) = 0; - - // Cleans up a composition session and makes sure that the composition text is - // cleared. - virtual void OnPreeditEnd() = 0; - - // Prepares things for a new composition session. - virtual void OnPreeditStart() = 0; -}; - -} // namespace ui - -#endif // UI_BASE_IME_LINUX_LINUX_INPUT_METHOD_CONTEXT_H_
diff --git a/ui/base/ime/linux/linux_input_method_context_factory.cc b/ui/base/ime/linux/linux_input_method_context_factory.cc deleted file mode 100644 index 4ba2750..0000000 --- a/ui/base/ime/linux/linux_input_method_context_factory.cc +++ /dev/null
@@ -1,28 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/linux/linux_input_method_context_factory.h" - -namespace { - -const ui::LinuxInputMethodContextFactory* g_linux_input_method_context_factory = - NULL; - -} // namespace - -namespace ui { - -// static -const LinuxInputMethodContextFactory* -LinuxInputMethodContextFactory::instance() { - return g_linux_input_method_context_factory; -} - -// static -void LinuxInputMethodContextFactory::SetInstance( - const LinuxInputMethodContextFactory* instance) { - g_linux_input_method_context_factory = instance; -} - -} // namespace ui
diff --git a/ui/base/ime/linux/linux_input_method_context_factory.h b/ui/base/ime/linux/linux_input_method_context_factory.h deleted file mode 100644 index af2a3a0..0000000 --- a/ui/base/ime/linux/linux_input_method_context_factory.h +++ /dev/null
@@ -1,38 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_LINUX_LINUX_INPUT_METHOD_CONTEXT_FACTORY_H_ -#define UI_BASE_IME_LINUX_LINUX_INPUT_METHOD_CONTEXT_FACTORY_H_ - -#include "base/memory/scoped_ptr.h" -#include "ui/base/ui_base_export.h" - -namespace ui { - -class LinuxInputMethodContext; -class LinuxInputMethodContextDelegate; - -// An interface that lets different Linux platforms override the -// CreateInputMethodContext function declared here to return native input method -// contexts. -class UI_BASE_EXPORT LinuxInputMethodContextFactory { - public: - // Returns the current active factory or NULL. - static const LinuxInputMethodContextFactory* instance(); - - // Sets the dynamically loaded singleton that creates an input method context. - // This pointer is not owned, and if this method is called a second time, - // the first instance is not deleted. - static void SetInstance(const LinuxInputMethodContextFactory* instance); - - virtual ~LinuxInputMethodContextFactory() {} - - // Returns a native input method context. - virtual scoped_ptr<LinuxInputMethodContext> CreateInputMethodContext( - LinuxInputMethodContextDelegate* delegate) const = 0; -}; - -} // namespace ui - -#endif // UI_BASE_IME_LINUX_LINUX_INPUT_METHOD_CONTEXT_FACTORY_H_
diff --git a/ui/base/ime/mock_input_method.cc b/ui/base/ime/mock_input_method.cc deleted file mode 100644 index 5ffc76f..0000000 --- a/ui/base/ime/mock_input_method.cc +++ /dev/null
@@ -1,125 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/mock_input_method.h" - -#include "ui/base/ime/text_input_focus_manager.h" -#include "ui/base/ui_base_switches_util.h" - -namespace ui { - -MockInputMethod::MockInputMethod(internal::InputMethodDelegate* delegate) - : text_input_client_(NULL) { -} - -MockInputMethod::~MockInputMethod() { -} - -void MockInputMethod::SetDelegate(internal::InputMethodDelegate* delegate) { -} - -void MockInputMethod::SetFocusedTextInputClient(TextInputClient* client) { - if (switches::IsTextInputFocusManagerEnabled()) - return; - - if (text_input_client_ == client) - return; - text_input_client_ = client; - if (client) - OnTextInputTypeChanged(client); -} - -void MockInputMethod::DetachTextInputClient(TextInputClient* client) { - if (text_input_client_ == client) { - text_input_client_ = NULL; - } -} - -TextInputClient* MockInputMethod::GetTextInputClient() const { - if (switches::IsTextInputFocusManagerEnabled()) - return TextInputFocusManager::GetInstance()->GetFocusedTextInputClient(); - - return text_input_client_; -} - -bool MockInputMethod::DispatchKeyEvent(const ui::KeyEvent& event) { - return false; -} - -void MockInputMethod::Init(bool focused) { -} - -void MockInputMethod::OnFocus() { - FOR_EACH_OBSERVER(InputMethodObserver, observer_list_, OnFocus()); -} - -void MockInputMethod::OnBlur() { - FOR_EACH_OBSERVER(InputMethodObserver, observer_list_, OnBlur()); -} - -bool MockInputMethod::OnUntranslatedIMEMessage(const base::NativeEvent& event, - NativeEventResult* result) { - if (result) - *result = NativeEventResult(); - return false; -} - -void MockInputMethod::OnTextInputTypeChanged(const TextInputClient* client) { - FOR_EACH_OBSERVER(InputMethodObserver, - observer_list_, - OnTextInputTypeChanged(client)); - FOR_EACH_OBSERVER(InputMethodObserver, - observer_list_, - OnTextInputStateChanged(client)); -} - -void MockInputMethod::OnCaretBoundsChanged(const TextInputClient* client) { - FOR_EACH_OBSERVER(InputMethodObserver, - observer_list_, - OnCaretBoundsChanged(client)); -} - -void MockInputMethod::CancelComposition(const TextInputClient* client) { -} - -void MockInputMethod::OnInputLocaleChanged() { -} - -std::string MockInputMethod::GetInputLocale() { - return ""; -} - -bool MockInputMethod::IsActive() { - return true; -} - -TextInputType MockInputMethod::GetTextInputType() const { - return TEXT_INPUT_TYPE_NONE; -} - -TextInputMode MockInputMethod::GetTextInputMode() const { - return TEXT_INPUT_MODE_DEFAULT; -} - -bool MockInputMethod::CanComposeInline() const { - return true; -} - -bool MockInputMethod::IsCandidatePopupOpen() const { - return false; -} - -void MockInputMethod::ShowImeIfNeeded() { - FOR_EACH_OBSERVER(InputMethodObserver, observer_list_, OnShowImeIfNeeded()); -} - -void MockInputMethod::AddObserver(InputMethodObserver* observer) { - observer_list_.AddObserver(observer); -} - -void MockInputMethod::RemoveObserver(InputMethodObserver* observer) { - observer_list_.RemoveObserver(observer); -} - -} // namespace ui
diff --git a/ui/base/ime/mock_input_method.h b/ui/base/ime/mock_input_method.h deleted file mode 100644 index 67a2029..0000000 --- a/ui/base/ime/mock_input_method.h +++ /dev/null
@@ -1,65 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_MOCK_INPUT_METHOD_H_ -#define UI_BASE_IME_MOCK_INPUT_METHOD_H_ - -#include <string> - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/observer_list.h" -#include "ui/base/ime/input_method.h" -#include "ui/base/ime/input_method_observer.h" -#include "ui/base/ui_base_export.h" - -namespace ui { - -class KeyEvent; -class TextInputClient; - -// A mock ui::InputMethod implementation for testing. You can get the instance -// of this class as the global input method with calling -// SetUpInputMethodFactoryForTesting() which is declared in -// ui/base/ime/input_method_factory.h -class UI_BASE_EXPORT MockInputMethod : NON_EXPORTED_BASE(public InputMethod) { - public: - explicit MockInputMethod(internal::InputMethodDelegate* delegate); - ~MockInputMethod() override; - - // Overriden from InputMethod. - void SetDelegate(internal::InputMethodDelegate* delegate) override; - void Init(bool focused) override; - void OnFocus() override; - void OnBlur() override; - bool OnUntranslatedIMEMessage(const base::NativeEvent& event, - NativeEventResult* result) override; - void SetFocusedTextInputClient(TextInputClient* client) override; - void DetachTextInputClient(TextInputClient* client) override; - TextInputClient* GetTextInputClient() const override; - bool DispatchKeyEvent(const ui::KeyEvent& event) override; - void OnTextInputTypeChanged(const TextInputClient* client) override; - void OnCaretBoundsChanged(const TextInputClient* client) override; - void CancelComposition(const TextInputClient* client) override; - void OnInputLocaleChanged() override; - std::string GetInputLocale() override; - bool IsActive() override; - TextInputType GetTextInputType() const override; - TextInputMode GetTextInputMode() const override; - bool CanComposeInline() const override; - bool IsCandidatePopupOpen() const override; - void ShowImeIfNeeded() override; - void AddObserver(InputMethodObserver* observer) override; - void RemoveObserver(InputMethodObserver* observer) override; - - private: - TextInputClient* text_input_client_; - ObserverList<InputMethodObserver> observer_list_; - - DISALLOW_COPY_AND_ASSIGN(MockInputMethod); -}; - -} // namespace ui - -#endif // UI_BASE_IME_MOCK_INPUT_METHOD_H_
diff --git a/ui/base/ime/remote_input_method_delegate_win.h b/ui/base/ime/remote_input_method_delegate_win.h deleted file mode 100644 index 993faf8..0000000 --- a/ui/base/ime/remote_input_method_delegate_win.h +++ /dev/null
@@ -1,41 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_REMOTE_INPUT_METHOD_DELEGATE_WIN_H_ -#define UI_BASE_IME_REMOTE_INPUT_METHOD_DELEGATE_WIN_H_ - -#include <vector> - -#include "base/basictypes.h" -#include "ui/base/ui_base_export.h" -#include "ui/gfx/rect.h" - -namespace ui { -namespace internal { - -// An interface implemented by the object to forward events that should be -// handled by the IME which is running in the remote metro_driver process. -class UI_BASE_EXPORT RemoteInputMethodDelegateWin { - public: - virtual ~RemoteInputMethodDelegateWin() {} - - // Notifies that composition should be canceled (if any). - virtual void CancelComposition() = 0; - - // Notifies that properties of the focused TextInputClient is changed. - // Note that an empty |input_scopes| represents that TextInputType is - // TEXT_INPUT_TYPE_NONE. - // Caveats: |input_scopes| is defined as std::vector<int32> rather than - // std::vector<InputScope> because the wire format of IPC message - // MetroViewerHostMsg_ImeTextInputClientUpdated uses std::vector<int32> to - // avoid dependency on <InputScope.h> header. - virtual void OnTextInputClientUpdated( - const std::vector<int32>& input_scopes, - const std::vector<gfx::Rect>& composition_character_bounds) = 0; -}; - -} // namespace internal -} // namespace ui - -#endif // UI_BASE_IME_REMOTE_INPUT_METHOD_DELEGATE_WIN_H_
diff --git a/ui/base/ime/remote_input_method_win.cc b/ui/base/ime/remote_input_method_win.cc deleted file mode 100644 index f74dcde..0000000 --- a/ui/base/ime/remote_input_method_win.cc +++ /dev/null
@@ -1,399 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/remote_input_method_win.h" - -#include "base/command_line.h" -#include "base/observer_list.h" -#include "base/strings/utf_string_conversions.h" -#include "base/win/metro.h" -#include "base/win/scoped_handle.h" -#include "ui/base/ime/input_method.h" -#include "ui/base/ime/input_method_delegate.h" -#include "ui/base/ime/input_method_observer.h" -#include "ui/base/ime/remote_input_method_delegate_win.h" -#include "ui/base/ime/text_input_client.h" -#include "ui/base/ime/win/tsf_input_scope.h" -#include "ui/base/ui_base_switches.h" -#include "ui/events/event.h" -#include "ui/events/event_utils.h" -#include "ui/gfx/rect.h" - -namespace ui { -namespace { - -const LANGID kFallbackLangID = - MAKELANGID(LANG_NEUTRAL, SUBLANG_UI_CUSTOM_DEFAULT); - -InputMethod* g_public_interface_ = NULL; -RemoteInputMethodPrivateWin* g_private_interface_ = NULL; - -void RegisterInstance(InputMethod* public_interface, - RemoteInputMethodPrivateWin* private_interface) { - CHECK(g_public_interface_ == NULL) - << "Only one instance is supported at the same time"; - CHECK(g_private_interface_ == NULL) - << "Only one instance is supported at the same time"; - g_public_interface_ = public_interface; - g_private_interface_ = private_interface; -} - -RemoteInputMethodPrivateWin* GetPrivate(InputMethod* public_interface) { - if (g_public_interface_ != public_interface) - return NULL; - return g_private_interface_; -} - -void UnregisterInstance(InputMethod* public_interface) { - RemoteInputMethodPrivateWin* private_interface = GetPrivate(public_interface); - if (g_public_interface_ == public_interface && - g_private_interface_ == private_interface) { - g_public_interface_ = NULL; - g_private_interface_ = NULL; - } -} - -std::string GetLocaleString(LCID Locale_id, LCTYPE locale_type) { - wchar_t buffer[16] = {}; - - //|chars_written| includes NUL terminator. - const int chars_written = - GetLocaleInfo(Locale_id, locale_type, buffer, arraysize(buffer)); - if (chars_written <= 1 || arraysize(buffer) < chars_written) - return std::string(); - std::string result; - base::WideToUTF8(buffer, chars_written - 1, &result); - return result; -} - -std::vector<int32> GetInputScopesAsInt(TextInputType text_input_type, - TextInputMode text_input_mode) { - std::vector<int32> result; - // An empty vector represents |text_input_type| is TEXT_INPUT_TYPE_NONE. - if (text_input_type == TEXT_INPUT_TYPE_NONE) - return result; - - const std::vector<InputScope>& input_scopes = - tsf_inputscope::GetInputScopes(text_input_type, text_input_mode); - result.reserve(input_scopes.size()); - for (size_t i = 0; i < input_scopes.size(); ++i) - result.push_back(static_cast<int32>(input_scopes[i])); - return result; -} - -std::vector<gfx::Rect> GetCompositionCharacterBounds( - const TextInputClient* client) { - if (!client) - return std::vector<gfx::Rect>(); - - std::vector<gfx::Rect> bounds; - if (client->HasCompositionText()) { - gfx::Range range; - if (client->GetCompositionTextRange(&range)) { - for (uint32 i = 0; i < range.length(); ++i) { - gfx::Rect rect; - if (!client->GetCompositionCharacterBounds(i, &rect)) - break; - bounds.push_back(rect); - } - } - } - - // Use the caret bounds as a fallback if no composition character bounds is - // available. One typical use case is PPAPI Flash, which does not support - // GetCompositionCharacterBounds at all. crbug.com/133472 - if (bounds.empty()) - bounds.push_back(client->GetCaretBounds()); - return bounds; -} - -class RemoteInputMethodWin : public InputMethod, - public RemoteInputMethodPrivateWin { - public: - explicit RemoteInputMethodWin(internal::InputMethodDelegate* delegate) - : delegate_(delegate), - remote_delegate_(NULL), - text_input_client_(NULL), - is_candidate_popup_open_(false), - is_ime_(false), - langid_(kFallbackLangID) { - RegisterInstance(this, this); - } - - virtual ~RemoteInputMethodWin() { - FOR_EACH_OBSERVER(InputMethodObserver, - observer_list_, - OnInputMethodDestroyed(this)); - UnregisterInstance(this); - } - - private: - // Overridden from InputMethod: - virtual void SetDelegate(internal::InputMethodDelegate* delegate) override { - delegate_ = delegate; - } - - virtual void Init(bool focused) override { - } - - virtual void OnFocus() override { - } - - virtual void OnBlur() override { - } - - virtual bool OnUntranslatedIMEMessage(const base::NativeEvent& event, - NativeEventResult* result) override { - return false; - } - - virtual void SetFocusedTextInputClient(TextInputClient* client) override { - std::vector<int32> prev_input_scopes; - std::swap(input_scopes_, prev_input_scopes); - std::vector<gfx::Rect> prev_bounds; - std::swap(composition_character_bounds_, prev_bounds); - if (client) { - input_scopes_ = GetInputScopesAsInt(client->GetTextInputType(), - client->GetTextInputMode()); - composition_character_bounds_ = GetCompositionCharacterBounds(client); - } - - const bool text_input_client_changed = text_input_client_ != client; - text_input_client_ = client; - if (text_input_client_changed) { - FOR_EACH_OBSERVER(InputMethodObserver, - observer_list_, - OnTextInputStateChanged(client)); - } - - if (!remote_delegate_ || (prev_input_scopes == input_scopes_ && - prev_bounds == composition_character_bounds_)) - return; - remote_delegate_->OnTextInputClientUpdated(input_scopes_, - composition_character_bounds_); - } - - virtual void DetachTextInputClient(TextInputClient* client) override { - if (text_input_client_ != client) - return; - SetFocusedTextInputClient(NULL); - } - - virtual TextInputClient* GetTextInputClient() const override { - return text_input_client_; - } - - virtual bool DispatchKeyEvent(const ui::KeyEvent& event) override { - if (event.HasNativeEvent()) { - const base::NativeEvent& native_key_event = event.native_event(); - if (native_key_event.message != WM_CHAR) - return false; - if (!text_input_client_) - return false; - text_input_client_->InsertChar( - static_cast<base::char16>(native_key_event.wParam), - ui::GetModifiersFromKeyState()); - return true; - } - - if (event.is_char()) { - if (text_input_client_) { - text_input_client_->InsertChar( - static_cast<base::char16>(event.key_code()), - ui::GetModifiersFromKeyState()); - } - return true; - } - if (!delegate_) - return false; - return delegate_->DispatchKeyEventPostIME(event); - } - - virtual void OnTextInputTypeChanged(const TextInputClient* client) override { - if (!text_input_client_ || text_input_client_ != client) - return; - std::vector<int32> prev_input_scopes; - std::swap(input_scopes_, prev_input_scopes); - input_scopes_ = GetInputScopesAsInt(client->GetTextInputType(), - client->GetTextInputMode()); - if (input_scopes_ != prev_input_scopes && remote_delegate_) { - remote_delegate_->OnTextInputClientUpdated( - input_scopes_, composition_character_bounds_); - } - } - - virtual void OnCaretBoundsChanged(const TextInputClient* client) override { - if (!text_input_client_ || text_input_client_ != client) - return; - std::vector<gfx::Rect> prev_rects; - std::swap(composition_character_bounds_, prev_rects); - composition_character_bounds_ = GetCompositionCharacterBounds(client); - if (composition_character_bounds_ != prev_rects && remote_delegate_) { - remote_delegate_->OnTextInputClientUpdated( - input_scopes_, composition_character_bounds_); - } - } - - virtual void CancelComposition(const TextInputClient* client) override { - if (CanSendRemoteNotification(client)) - remote_delegate_->CancelComposition(); - } - - virtual void OnInputLocaleChanged() override { - } - - virtual std::string GetInputLocale() override { - const LCID locale_id = MAKELCID(langid_, SORT_DEFAULT); - std::string language = - GetLocaleString(locale_id, LOCALE_SISO639LANGNAME); - if (SUBLANGID(langid_) == SUBLANG_NEUTRAL || language.empty()) - return language; - const std::string& region = - GetLocaleString(locale_id, LOCALE_SISO3166CTRYNAME); - if (region.empty()) - return language; - return language.append(1, '-').append(region); - } - - virtual bool IsActive() override { - return true; // always turned on - } - - virtual TextInputType GetTextInputType() const override { - return text_input_client_ ? text_input_client_->GetTextInputType() - : TEXT_INPUT_TYPE_NONE; - } - - virtual TextInputMode GetTextInputMode() const override { - return text_input_client_ ? text_input_client_->GetTextInputMode() - : TEXT_INPUT_MODE_DEFAULT; - } - - virtual bool CanComposeInline() const override { - return text_input_client_ ? text_input_client_->CanComposeInline() : true; - } - - virtual bool IsCandidatePopupOpen() const override { - return is_candidate_popup_open_; - } - - virtual void ShowImeIfNeeded() override { - } - - virtual void AddObserver(InputMethodObserver* observer) override { - observer_list_.AddObserver(observer); - } - - virtual void RemoveObserver(InputMethodObserver* observer) override { - observer_list_.RemoveObserver(observer); - } - - // Overridden from RemoteInputMethodPrivateWin: - virtual void SetRemoteDelegate( - internal::RemoteInputMethodDelegateWin* delegate) override{ - remote_delegate_ = delegate; - - // Sync initial state. - if (remote_delegate_) { - remote_delegate_->OnTextInputClientUpdated( - input_scopes_, composition_character_bounds_); - } - } - - virtual void OnCandidatePopupChanged(bool visible) override { - is_candidate_popup_open_ = visible; - if (!text_input_client_) - return; - // TODO(kochi): Support 'update' case, in addition to show/hide. - // http://crbug.com/238585 - if (visible) - text_input_client_->OnCandidateWindowShown(); - else - text_input_client_->OnCandidateWindowHidden(); - } - - virtual void OnInputSourceChanged(LANGID langid, bool /*is_ime*/) override { - // Note: Currently |is_ime| is not utilized yet. - const bool changed = (langid_ != langid); - langid_ = langid; - if (changed && GetTextInputClient()) - GetTextInputClient()->OnInputMethodChanged(); - } - - virtual void OnCompositionChanged( - const CompositionText& composition_text) override { - if (!text_input_client_) - return; - text_input_client_->SetCompositionText(composition_text); - } - - virtual void OnTextCommitted(const base::string16& text) override { - if (!text_input_client_) - return; - if (text_input_client_->GetTextInputType() == TEXT_INPUT_TYPE_NONE) { - // According to the comment in text_input_client.h, - // TextInputClient::InsertText should never be called when the - // text input type is TEXT_INPUT_TYPE_NONE. - for (size_t i = 0; i < text.size(); ++i) - text_input_client_->InsertChar(text[i], 0); - return; - } - text_input_client_->InsertText(text); - } - - bool CanSendRemoteNotification( - const TextInputClient* text_input_client) const { - return text_input_client_ && - text_input_client_ == text_input_client && - remote_delegate_; - } - - ObserverList<InputMethodObserver> observer_list_; - - internal::InputMethodDelegate* delegate_; - internal::RemoteInputMethodDelegateWin* remote_delegate_; - - TextInputClient* text_input_client_; - std::vector<int32> input_scopes_; - std::vector<gfx::Rect> composition_character_bounds_; - bool is_candidate_popup_open_; - bool is_ime_; - LANGID langid_; - - DISALLOW_COPY_AND_ASSIGN(RemoteInputMethodWin); -}; - -} // namespace - -bool IsRemoteInputMethodWinRequired(gfx::AcceleratedWidget widget) { - // If the remote input method is already registered then don't do it again. - if (ui::g_public_interface_ && ui::g_private_interface_) - return false; - - DWORD process_id = 0; - if (GetWindowThreadProcessId(widget, &process_id) == 0) - return false; - base::win::ScopedHandle process_handle(::OpenProcess( - PROCESS_QUERY_LIMITED_INFORMATION, FALSE, process_id)); - if (!process_handle.IsValid()) - return false; - return base::win::IsProcessImmersive(process_handle.Get()) || - CommandLine::ForCurrentProcess()->HasSwitch( - switches::kViewerConnect); -} - -RemoteInputMethodPrivateWin::RemoteInputMethodPrivateWin() {} - -scoped_ptr<InputMethod> CreateRemoteInputMethodWin( - internal::InputMethodDelegate* delegate) { - return scoped_ptr<InputMethod>(new RemoteInputMethodWin(delegate)); -} - -// static -RemoteInputMethodPrivateWin* RemoteInputMethodPrivateWin::Get( - InputMethod* input_method) { - return GetPrivate(input_method); -} - -} // namespace ui
diff --git a/ui/base/ime/remote_input_method_win.h b/ui/base/ime/remote_input_method_win.h deleted file mode 100644 index 5258f3d..0000000 --- a/ui/base/ime/remote_input_method_win.h +++ /dev/null
@@ -1,100 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_REMOTE_INPUT_METHOD_WIN_H_ -#define UI_BASE_IME_REMOTE_INPUT_METHOD_WIN_H_ - -#include <Windows.h> - -#include <string> - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "base/strings/string16.h" -#include "ui/base/ui_base_export.h" -#include "ui/gfx/native_widget_types.h" - -namespace ui { -namespace internal { -class InputMethodDelegate; -class RemoteInputMethodDelegateWin; -} // namespace internal - -class InputMethod; -struct CompositionText; - -// RemoteInputMethodWin is a special implementation of ui::InputMethod that -// works as a proxy of an IME handler running in the metro_driver process. -// RemoteInputMethodWin works as follows. -// - Any action to RemoteInputMethodWin should be delegated to the -// metro_driver process via RemoteInputMethodDelegateWin. -// - Data retrieval from RemoteInputMethodPrivateWin is implemented with -// data cache. Whenever the IME state in the metro_driver process is changed, -// RemoteWindowTreeHostWin, which receives IPCs from metro_driver process, -// will call RemoteInputMethodPrivateWin::OnCandidatePopupChanged and/or -// RemoteInputMethodPrivateWin::OnInputSourceChanged accordingly so that -// the state cache should be updated. -// - Some IPC messages that represent actions to TextInputClient should be -// delegated to RemoteInputMethodPrivateWin so that RemoteInputMethodWin can -// work as a real proxy. - -// Returns true if |widget| requires RemoteInputMethodWin. -bool IsRemoteInputMethodWinRequired(gfx::AcceleratedWidget widget); - -// Returns the public interface of RemoteInputMethodWin. -// Caveats: Currently only one instance of RemoteInputMethodWin is able to run -// at the same time. -UI_BASE_EXPORT scoped_ptr<InputMethod> CreateRemoteInputMethodWin( - internal::InputMethodDelegate* delegate); - -// Private interface of RemoteInputMethodWin. -class UI_BASE_EXPORT RemoteInputMethodPrivateWin { - public: - RemoteInputMethodPrivateWin(); - - // Returns the private interface of RemoteInputMethodWin when and only when - // |input_method| is instanciated via CreateRemoteInputMethodWin. Caller does - // not take the ownership of the returned object. - // As you might notice, this is yet another reinplementation of dynamic_cast - // or IUnknown::QueryInterface. - static RemoteInputMethodPrivateWin* Get(InputMethod* input_method); - - // Installs RemoteInputMethodDelegateWin delegate. Set NULL to |delegate| to - // unregister. - virtual void SetRemoteDelegate( - internal::RemoteInputMethodDelegateWin* delegate) = 0; - - // Updates internal cache so that subsequent calls of - // RemoteInputMethodWin::IsCandidatePopupOpen can return the correct value - // based on remote IME activities in the metro_driver process. - virtual void OnCandidatePopupChanged(bool visible) = 0; - - // Updates internal cache so that subsequent calls of - // RemoteInputMethodWin::GetInputLocale can return the correct values based on - // remote IME activities in the metro_driver process. - virtual void OnInputSourceChanged(LANGID langid, bool is_ime) = 0; - - // Handles composition-update events occurred in the metro_driver process. - // Caveats: This method is designed to be used only with - // metro_driver::TextService. In other words, there is no garantee that this - // method works a wrapper to call ui::TextInputClient::SetCompositionText. - virtual void OnCompositionChanged( - const CompositionText& composition_text) = 0; - - // Handles text-commit events occurred in the metro_driver process. - // Caveats: This method is designed to be used only with - // metro_driver::TextService. In other words, there is no garantee that this - // method works a wrapper to call ui::TextInputClient::InsertText. In fact, - // this method may call ui::TextInputClient::InsertChar when the text input - // type of the focused text input client is TEXT_INPUT_TYPE_NONE. - virtual void OnTextCommitted(const base::string16& text) = 0; - - private: - DISALLOW_COPY_AND_ASSIGN(RemoteInputMethodPrivateWin); -}; - -} // namespace ui - -#endif // UI_BASE_IME_REMOTE_INPUT_METHOD_WIN_H_
diff --git a/ui/base/ime/remote_input_method_win_unittest.cc b/ui/base/ime/remote_input_method_win_unittest.cc deleted file mode 100644 index 5cf8aa3..0000000 --- a/ui/base/ime/remote_input_method_win_unittest.cc +++ /dev/null
@@ -1,846 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/remote_input_method_win.h" - -#include <InputScope.h> - -#include <vector> - -#include "base/memory/scoped_ptr.h" -#include "base/scoped_observer.h" -#include "base/strings/string16.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/base/ime/composition_text.h" -#include "ui/base/ime/dummy_text_input_client.h" -#include "ui/base/ime/input_method.h" -#include "ui/base/ime/input_method_delegate.h" -#include "ui/base/ime/input_method_observer.h" -#include "ui/base/ime/remote_input_method_delegate_win.h" -#include "ui/events/event.h" - -namespace ui { -namespace { - -class MockTextInputClient : public DummyTextInputClient { - public: - MockTextInputClient() - : text_input_type_(TEXT_INPUT_TYPE_NONE), - text_input_mode_(TEXT_INPUT_MODE_DEFAULT), - call_count_set_composition_text_(0), - call_count_insert_char_(0), - call_count_insert_text_(0), - emulate_pepper_flash_(false), - is_candidate_window_shown_called_(false), - is_candidate_window_hidden_called_(false) { - } - - size_t call_count_set_composition_text() const { - return call_count_set_composition_text_; - } - const base::string16& inserted_text() const { - return inserted_text_; - } - size_t call_count_insert_char() const { - return call_count_insert_char_; - } - size_t call_count_insert_text() const { - return call_count_insert_text_; - } - bool is_candidate_window_shown_called() const { - return is_candidate_window_shown_called_; - } - bool is_candidate_window_hidden_called() const { - return is_candidate_window_hidden_called_; - } - void Reset() { - text_input_type_ = TEXT_INPUT_TYPE_NONE; - text_input_mode_ = TEXT_INPUT_MODE_DEFAULT; - call_count_set_composition_text_ = 0; - inserted_text_.clear(); - call_count_insert_char_ = 0; - call_count_insert_text_ = 0; - caret_bounds_ = gfx::Rect(); - composition_character_bounds_.clear(); - emulate_pepper_flash_ = false; - is_candidate_window_shown_called_ = false; - is_candidate_window_hidden_called_ = false; - } - void set_text_input_type(ui::TextInputType type) { - text_input_type_ = type; - } - void set_text_input_mode(ui::TextInputMode mode) { - text_input_mode_ = mode; - } - void set_caret_bounds(const gfx::Rect& caret_bounds) { - caret_bounds_ = caret_bounds; - } - void set_composition_character_bounds( - const std::vector<gfx::Rect>& composition_character_bounds) { - composition_character_bounds_ = composition_character_bounds; - } - void set_emulate_pepper_flash(bool enabled) { - emulate_pepper_flash_ = enabled; - } - - private: - // Overriden from DummyTextInputClient. - virtual void SetCompositionText( - const ui::CompositionText& composition) override { - ++call_count_set_composition_text_; - } - virtual void InsertChar(base::char16 ch, int flags) override { - inserted_text_.append(1, ch); - ++call_count_insert_char_; - } - virtual void InsertText(const base::string16& text) override { - inserted_text_.append(text); - ++call_count_insert_text_; - } - virtual ui::TextInputType GetTextInputType() const override { - return text_input_type_; - } - virtual ui::TextInputMode GetTextInputMode() const override { - return text_input_mode_; - } - virtual gfx::Rect GetCaretBounds() const { - return caret_bounds_; - } - virtual bool GetCompositionCharacterBounds(uint32 index, - gfx::Rect* rect) const override { - // Emulate the situation of crbug.com/328237. - if (emulate_pepper_flash_) - return false; - if (!rect || composition_character_bounds_.size() <= index) - return false; - *rect = composition_character_bounds_[index]; - return true; - } - virtual bool HasCompositionText() const override { - return !composition_character_bounds_.empty(); - } - virtual bool GetCompositionTextRange(gfx::Range* range) const override { - if (composition_character_bounds_.empty()) - return false; - *range = gfx::Range(0, composition_character_bounds_.size()); - return true; - } - virtual void OnCandidateWindowShown() override { - is_candidate_window_shown_called_ = true; - } - virtual void OnCandidateWindowHidden() override { - is_candidate_window_hidden_called_ = true; - } - - ui::TextInputType text_input_type_; - ui::TextInputMode text_input_mode_; - gfx::Rect caret_bounds_; - std::vector<gfx::Rect> composition_character_bounds_; - base::string16 inserted_text_; - size_t call_count_set_composition_text_; - size_t call_count_insert_char_; - size_t call_count_insert_text_; - bool emulate_pepper_flash_; - bool is_candidate_window_shown_called_; - bool is_candidate_window_hidden_called_; - DISALLOW_COPY_AND_ASSIGN(MockTextInputClient); -}; - -class MockInputMethodDelegate : public internal::InputMethodDelegate { - public: - MockInputMethodDelegate() {} - - const std::vector<ui::KeyboardCode>& fabricated_key_events() const { - return fabricated_key_events_; - } - void Reset() { - fabricated_key_events_.clear(); - } - - private: - virtual bool DispatchKeyEventPostIME(const ui::KeyEvent& event) override { - EXPECT_FALSE(event.HasNativeEvent()); - fabricated_key_events_.push_back(event.key_code()); - return true; - } - - std::vector<ui::KeyboardCode> fabricated_key_events_; - DISALLOW_COPY_AND_ASSIGN(MockInputMethodDelegate); -}; - -class MockRemoteInputMethodDelegateWin - : public internal::RemoteInputMethodDelegateWin { - public: - MockRemoteInputMethodDelegateWin() - : cancel_composition_called_(false), - text_input_client_updated_called_(false) { - } - - bool cancel_composition_called() const { - return cancel_composition_called_; - } - bool text_input_client_updated_called() const { - return text_input_client_updated_called_; - } - const std::vector<int32>& input_scopes() const { - return input_scopes_; - } - const std::vector<gfx::Rect>& composition_character_bounds() const { - return composition_character_bounds_; - } - void Reset() { - cancel_composition_called_ = false; - text_input_client_updated_called_ = false; - input_scopes_.clear(); - composition_character_bounds_.clear(); - } - - private: - virtual void CancelComposition() override { - cancel_composition_called_ = true; - } - - virtual void OnTextInputClientUpdated( - const std::vector<int32>& input_scopes, - const std::vector<gfx::Rect>& composition_character_bounds) override { - text_input_client_updated_called_ = true; - input_scopes_ = input_scopes; - composition_character_bounds_ = composition_character_bounds; - } - - bool cancel_composition_called_; - bool text_input_client_updated_called_; - std::vector<int32> input_scopes_; - std::vector<gfx::Rect> composition_character_bounds_; - DISALLOW_COPY_AND_ASSIGN(MockRemoteInputMethodDelegateWin); -}; - -class MockInputMethodObserver : public InputMethodObserver { - public: - MockInputMethodObserver() - : on_text_input_state_changed_(0), - on_input_method_destroyed_changed_(0) { - } - virtual ~MockInputMethodObserver() { - } - void Reset() { - on_text_input_state_changed_ = 0; - on_input_method_destroyed_changed_ = 0; - } - size_t on_text_input_state_changed() const { - return on_text_input_state_changed_; - } - size_t on_input_method_destroyed_changed() const { - return on_input_method_destroyed_changed_; - } - - private: - // Overriden from InputMethodObserver. - virtual void OnTextInputTypeChanged(const TextInputClient* client) override { - } - virtual void OnFocus() override { - } - virtual void OnBlur() override { - } - virtual void OnCaretBoundsChanged(const TextInputClient* client) override { - } - virtual void OnTextInputStateChanged(const TextInputClient* client) override { - ++on_text_input_state_changed_; - } - virtual void OnInputMethodDestroyed(const InputMethod* client) override { - ++on_input_method_destroyed_changed_; - } - virtual void OnShowImeIfNeeded() { - } - - size_t on_text_input_state_changed_; - size_t on_input_method_destroyed_changed_; - DISALLOW_COPY_AND_ASSIGN(MockInputMethodObserver); -}; - -typedef ScopedObserver<InputMethod, InputMethodObserver> - InputMethodScopedObserver; - -TEST(RemoteInputMethodWinTest, RemoteInputMethodPrivateWin) { - InputMethod* other_ptr = static_cast<InputMethod*>(NULL) + 1; - - // Use typed NULL to make EXPECT_NE happy until nullptr becomes available. - RemoteInputMethodPrivateWin* kNull = - static_cast<RemoteInputMethodPrivateWin*>(NULL); - EXPECT_EQ(kNull, RemoteInputMethodPrivateWin::Get(other_ptr)); - - MockInputMethodDelegate delegate_; - scoped_ptr<InputMethod> input_method(CreateRemoteInputMethodWin(&delegate_)); - EXPECT_NE(kNull, RemoteInputMethodPrivateWin::Get(input_method.get())); - - InputMethod* dangling_ptr = input_method.get(); - input_method.reset(NULL); - EXPECT_EQ(kNull, RemoteInputMethodPrivateWin::Get(dangling_ptr)); -} - -TEST(RemoteInputMethodWinTest, OnInputSourceChanged) { - MockInputMethodDelegate delegate_; - scoped_ptr<InputMethod> input_method(CreateRemoteInputMethodWin(&delegate_)); - RemoteInputMethodPrivateWin* private_ptr = - RemoteInputMethodPrivateWin::Get(input_method.get()); - ASSERT_TRUE(private_ptr != NULL); - - private_ptr->OnInputSourceChanged( - MAKELANGID(LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN), true); - EXPECT_EQ("ja-JP", input_method->GetInputLocale()); - - private_ptr->OnInputSourceChanged( - MAKELANGID(LANG_ARABIC, SUBLANG_ARABIC_QATAR), true); - EXPECT_EQ("ar-QA", input_method->GetInputLocale()); -} - -TEST(RemoteInputMethodWinTest, OnCandidatePopupChanged) { - MockInputMethodDelegate delegate_; - scoped_ptr<InputMethod> input_method(CreateRemoteInputMethodWin(&delegate_)); - RemoteInputMethodPrivateWin* private_ptr = - RemoteInputMethodPrivateWin::Get(input_method.get()); - ASSERT_TRUE(private_ptr != NULL); - - // Initial value - EXPECT_FALSE(input_method->IsCandidatePopupOpen()); - - // RemoteInputMethodWin::OnCandidatePopupChanged can be called even when the - // focused text input client is NULL. - ASSERT_TRUE(input_method->GetTextInputClient() == NULL); - private_ptr->OnCandidatePopupChanged(false); - private_ptr->OnCandidatePopupChanged(true); - - MockTextInputClient mock_text_input_client; - input_method->SetFocusedTextInputClient(&mock_text_input_client); - - ASSERT_FALSE(mock_text_input_client.is_candidate_window_shown_called()); - ASSERT_FALSE(mock_text_input_client.is_candidate_window_hidden_called()); - mock_text_input_client.Reset(); - - private_ptr->OnCandidatePopupChanged(true); - EXPECT_TRUE(input_method->IsCandidatePopupOpen()); - EXPECT_TRUE(mock_text_input_client.is_candidate_window_shown_called()); - EXPECT_FALSE(mock_text_input_client.is_candidate_window_hidden_called()); - - private_ptr->OnCandidatePopupChanged(false); - EXPECT_FALSE(input_method->IsCandidatePopupOpen()); - EXPECT_TRUE(mock_text_input_client.is_candidate_window_shown_called()); - EXPECT_TRUE(mock_text_input_client.is_candidate_window_hidden_called()); -} - -TEST(RemoteInputMethodWinTest, CancelComposition) { - MockInputMethodDelegate delegate_; - MockTextInputClient mock_text_input_client; - scoped_ptr<InputMethod> input_method(CreateRemoteInputMethodWin(&delegate_)); - - // This must not cause a crash. - input_method->CancelComposition(&mock_text_input_client); - - RemoteInputMethodPrivateWin* private_ptr = - RemoteInputMethodPrivateWin::Get(input_method.get()); - ASSERT_TRUE(private_ptr != NULL); - MockRemoteInputMethodDelegateWin mock_remote_delegate; - private_ptr->SetRemoteDelegate(&mock_remote_delegate); - - input_method->CancelComposition(&mock_text_input_client); - EXPECT_FALSE(mock_remote_delegate.cancel_composition_called()); - - input_method->SetFocusedTextInputClient(&mock_text_input_client); - input_method->CancelComposition(&mock_text_input_client); - EXPECT_TRUE(mock_remote_delegate.cancel_composition_called()); -} - -TEST(RemoteInputMethodWinTest, SetFocusedTextInputClient) { - MockInputMethodDelegate delegate_; - MockTextInputClient mock_text_input_client; - scoped_ptr<InputMethod> input_method(CreateRemoteInputMethodWin(&delegate_)); - - mock_text_input_client.set_caret_bounds(gfx::Rect(10, 0, 10, 20)); - mock_text_input_client.set_text_input_type(ui::TEXT_INPUT_TYPE_URL); - input_method->SetFocusedTextInputClient(&mock_text_input_client); - - RemoteInputMethodPrivateWin* private_ptr = - RemoteInputMethodPrivateWin::Get(input_method.get()); - ASSERT_TRUE(private_ptr != NULL); - MockRemoteInputMethodDelegateWin mock_remote_delegate; - private_ptr->SetRemoteDelegate(&mock_remote_delegate); - - // Initial state must be synced. - EXPECT_TRUE(mock_remote_delegate.text_input_client_updated_called()); - ASSERT_EQ(1, mock_remote_delegate.composition_character_bounds().size()); - EXPECT_EQ(gfx::Rect(10, 0, 10, 20), - mock_remote_delegate.composition_character_bounds()[0]); - ASSERT_EQ(1, mock_remote_delegate.input_scopes().size()); - EXPECT_EQ(IS_URL, mock_remote_delegate.input_scopes()[0]); - - // State must be cleared by SetFocusedTextInputClient(NULL). - mock_remote_delegate.Reset(); - input_method->SetFocusedTextInputClient(NULL); - EXPECT_TRUE(mock_remote_delegate.text_input_client_updated_called()); - EXPECT_TRUE(mock_remote_delegate.composition_character_bounds().empty()); - EXPECT_TRUE(mock_remote_delegate.input_scopes().empty()); -} - -TEST(RemoteInputMethodWinTest, DetachTextInputClient) { - MockInputMethodDelegate delegate_; - MockTextInputClient mock_text_input_client; - scoped_ptr<InputMethod> input_method(CreateRemoteInputMethodWin(&delegate_)); - - mock_text_input_client.set_caret_bounds(gfx::Rect(10, 0, 10, 20)); - mock_text_input_client.set_text_input_type(ui::TEXT_INPUT_TYPE_URL); - input_method->SetFocusedTextInputClient(&mock_text_input_client); - - RemoteInputMethodPrivateWin* private_ptr = - RemoteInputMethodPrivateWin::Get(input_method.get()); - ASSERT_TRUE(private_ptr != NULL); - MockRemoteInputMethodDelegateWin mock_remote_delegate; - private_ptr->SetRemoteDelegate(&mock_remote_delegate); - - // Initial state must be synced. - EXPECT_TRUE(mock_remote_delegate.text_input_client_updated_called()); - ASSERT_EQ(1, mock_remote_delegate.composition_character_bounds().size()); - EXPECT_EQ(gfx::Rect(10, 0, 10, 20), - mock_remote_delegate.composition_character_bounds()[0]); - ASSERT_EQ(1, mock_remote_delegate.input_scopes().size()); - EXPECT_EQ(IS_URL, mock_remote_delegate.input_scopes()[0]); - - // State must be cleared by DetachTextInputClient - mock_remote_delegate.Reset(); - input_method->DetachTextInputClient(&mock_text_input_client); - EXPECT_TRUE(mock_remote_delegate.text_input_client_updated_called()); - EXPECT_TRUE(mock_remote_delegate.composition_character_bounds().empty()); - EXPECT_TRUE(mock_remote_delegate.input_scopes().empty()); -} - -TEST(RemoteInputMethodWinTest, OnCaretBoundsChanged) { - MockInputMethodDelegate delegate_; - MockTextInputClient mock_text_input_client; - scoped_ptr<InputMethod> input_method(CreateRemoteInputMethodWin(&delegate_)); - - // This must not cause a crash. - input_method->OnCaretBoundsChanged(&mock_text_input_client); - - mock_text_input_client.set_caret_bounds(gfx::Rect(10, 0, 10, 20)); - input_method->SetFocusedTextInputClient(&mock_text_input_client); - - RemoteInputMethodPrivateWin* private_ptr = - RemoteInputMethodPrivateWin::Get(input_method.get()); - ASSERT_TRUE(private_ptr != NULL); - MockRemoteInputMethodDelegateWin mock_remote_delegate; - private_ptr->SetRemoteDelegate(&mock_remote_delegate); - - // Initial state must be synced. - EXPECT_TRUE(mock_remote_delegate.text_input_client_updated_called()); - ASSERT_EQ(1, mock_remote_delegate.composition_character_bounds().size()); - EXPECT_EQ(gfx::Rect(10, 0, 10, 20), - mock_remote_delegate.composition_character_bounds()[0]); - - // Redundant OnCaretBoundsChanged must be ignored. - mock_remote_delegate.Reset(); - input_method->OnCaretBoundsChanged(&mock_text_input_client); - EXPECT_FALSE(mock_remote_delegate.text_input_client_updated_called()); - - // Check OnCaretBoundsChanged is handled. (w/o composition) - mock_remote_delegate.Reset(); - mock_text_input_client.Reset(); - mock_text_input_client.set_caret_bounds(gfx::Rect(10, 20, 30, 40)); - input_method->OnCaretBoundsChanged(&mock_text_input_client); - EXPECT_TRUE(mock_remote_delegate.text_input_client_updated_called()); - ASSERT_EQ(1, mock_remote_delegate.composition_character_bounds().size()); - EXPECT_EQ(gfx::Rect(10, 20, 30, 40), - mock_remote_delegate.composition_character_bounds()[0]); - - // Check OnCaretBoundsChanged is handled. (w/ composition) - { - mock_remote_delegate.Reset(); - mock_text_input_client.Reset(); - - std::vector<gfx::Rect> bounds; - bounds.push_back(gfx::Rect(10, 20, 30, 40)); - bounds.push_back(gfx::Rect(40, 30, 20, 10)); - mock_text_input_client.set_composition_character_bounds(bounds); - input_method->OnCaretBoundsChanged(&mock_text_input_client); - EXPECT_TRUE(mock_remote_delegate.text_input_client_updated_called()); - EXPECT_EQ(bounds, mock_remote_delegate.composition_character_bounds()); - } -} - -// Test case against crbug.com/328237. -TEST(RemoteInputMethodWinTest, OnCaretBoundsChangedForPepperFlash) { - MockInputMethodDelegate delegate_; - MockTextInputClient mock_text_input_client; - scoped_ptr<InputMethod> input_method(CreateRemoteInputMethodWin(&delegate_)); - input_method->SetFocusedTextInputClient(&mock_text_input_client); - - RemoteInputMethodPrivateWin* private_ptr = - RemoteInputMethodPrivateWin::Get(input_method.get()); - ASSERT_TRUE(private_ptr != NULL); - MockRemoteInputMethodDelegateWin mock_remote_delegate; - private_ptr->SetRemoteDelegate(&mock_remote_delegate); - - mock_remote_delegate.Reset(); - mock_text_input_client.Reset(); - mock_text_input_client.set_emulate_pepper_flash(true); - - std::vector<gfx::Rect> caret_bounds; - caret_bounds.push_back(gfx::Rect(5, 15, 25, 35)); - mock_text_input_client.set_caret_bounds(caret_bounds[0]); - - std::vector<gfx::Rect> composition_bounds; - composition_bounds.push_back(gfx::Rect(10, 20, 30, 40)); - composition_bounds.push_back(gfx::Rect(40, 30, 20, 10)); - mock_text_input_client.set_composition_character_bounds(composition_bounds); - input_method->OnCaretBoundsChanged(&mock_text_input_client); - EXPECT_TRUE(mock_remote_delegate.text_input_client_updated_called()); - // The caret bounds must be used when - // TextInputClient::GetCompositionCharacterBounds failed. - EXPECT_EQ(caret_bounds, mock_remote_delegate.composition_character_bounds()); -} - -TEST(RemoteInputMethodWinTest, OnTextInputTypeChanged) { - MockInputMethodDelegate delegate_; - MockTextInputClient mock_text_input_client; - scoped_ptr<InputMethod> input_method(CreateRemoteInputMethodWin(&delegate_)); - - // This must not cause a crash. - input_method->OnCaretBoundsChanged(&mock_text_input_client); - - mock_text_input_client.set_text_input_type(ui::TEXT_INPUT_TYPE_URL); - input_method->SetFocusedTextInputClient(&mock_text_input_client); - - RemoteInputMethodPrivateWin* private_ptr = - RemoteInputMethodPrivateWin::Get(input_method.get()); - ASSERT_TRUE(private_ptr != NULL); - MockRemoteInputMethodDelegateWin mock_remote_delegate; - private_ptr->SetRemoteDelegate(&mock_remote_delegate); - - // Initial state must be synced. - EXPECT_TRUE(mock_remote_delegate.text_input_client_updated_called()); - ASSERT_EQ(1, mock_remote_delegate.input_scopes().size()); - EXPECT_EQ(IS_URL, mock_remote_delegate.input_scopes()[0]); - - // Check TEXT_INPUT_TYPE_NONE is handled. - mock_remote_delegate.Reset(); - mock_text_input_client.Reset(); - mock_text_input_client.set_text_input_type(ui::TEXT_INPUT_TYPE_NONE); - mock_text_input_client.set_text_input_mode(ui::TEXT_INPUT_MODE_KATAKANA); - input_method->OnTextInputTypeChanged(&mock_text_input_client); - EXPECT_TRUE(mock_remote_delegate.text_input_client_updated_called()); - EXPECT_TRUE(mock_remote_delegate.input_scopes().empty()); - - // Redundant OnTextInputTypeChanged must be ignored. - mock_remote_delegate.Reset(); - input_method->OnTextInputTypeChanged(&mock_text_input_client); - EXPECT_FALSE(mock_remote_delegate.text_input_client_updated_called()); - - mock_remote_delegate.Reset(); - mock_text_input_client.Reset(); - mock_text_input_client.set_caret_bounds(gfx::Rect(10, 20, 30, 40)); - input_method->OnCaretBoundsChanged(&mock_text_input_client); -} - -TEST(RemoteInputMethodWinTest, DispatchKeyEvent_NativeKeyEvent) { - // Basically RemoteInputMethodWin does not handle native keydown event. - - MockInputMethodDelegate delegate_; - MockTextInputClient mock_text_input_client; - scoped_ptr<InputMethod> input_method(CreateRemoteInputMethodWin(&delegate_)); - - const MSG wm_keydown = { NULL, WM_KEYDOWN, ui::VKEY_A }; - ui::KeyEvent native_keydown(wm_keydown); - - // This must not cause a crash. - EXPECT_FALSE(input_method->DispatchKeyEvent(native_keydown)); - EXPECT_TRUE(mock_text_input_client.inserted_text().empty()); - EXPECT_TRUE(delegate_.fabricated_key_events().empty()); - delegate_.Reset(); - mock_text_input_client.Reset(); - - RemoteInputMethodPrivateWin* private_ptr = - RemoteInputMethodPrivateWin::Get(input_method.get()); - ASSERT_TRUE(private_ptr != NULL); - MockRemoteInputMethodDelegateWin mock_remote_delegate; - private_ptr->SetRemoteDelegate(&mock_remote_delegate); - - // TextInputClient is not focused yet here. - - EXPECT_FALSE(input_method->DispatchKeyEvent(native_keydown)); - EXPECT_TRUE(mock_text_input_client.inserted_text().empty()); - EXPECT_TRUE(delegate_.fabricated_key_events().empty()); - delegate_.Reset(); - mock_text_input_client.Reset(); - - input_method->SetFocusedTextInputClient(&mock_text_input_client); - - // TextInputClient is now focused here. - - EXPECT_FALSE(input_method->DispatchKeyEvent(native_keydown)); - EXPECT_TRUE(mock_text_input_client.inserted_text().empty()); - EXPECT_TRUE(delegate_.fabricated_key_events().empty()); - delegate_.Reset(); - mock_text_input_client.Reset(); -} - -TEST(RemoteInputMethodWinTest, DispatchKeyEvent_NativeCharEvent) { - // RemoteInputMethodWin handles native char event if possible. - - MockInputMethodDelegate delegate_; - MockTextInputClient mock_text_input_client; - scoped_ptr<InputMethod> input_method(CreateRemoteInputMethodWin(&delegate_)); - - const MSG wm_char = { NULL, WM_CHAR, 'A', 0 }; - ui::KeyEvent native_char(wm_char); - - // This must not cause a crash. - EXPECT_FALSE(input_method->DispatchKeyEvent(native_char)); - EXPECT_TRUE(mock_text_input_client.inserted_text().empty()); - EXPECT_TRUE(delegate_.fabricated_key_events().empty()); - delegate_.Reset(); - mock_text_input_client.Reset(); - - RemoteInputMethodPrivateWin* private_ptr = - RemoteInputMethodPrivateWin::Get(input_method.get()); - ASSERT_TRUE(private_ptr != NULL); - MockRemoteInputMethodDelegateWin mock_remote_delegate; - private_ptr->SetRemoteDelegate(&mock_remote_delegate); - - // TextInputClient is not focused yet here. - - EXPECT_FALSE(input_method->DispatchKeyEvent(native_char)); - EXPECT_TRUE(mock_text_input_client.inserted_text().empty()); - EXPECT_TRUE(delegate_.fabricated_key_events().empty()); - delegate_.Reset(); - mock_text_input_client.Reset(); - - input_method->SetFocusedTextInputClient(&mock_text_input_client); - - // TextInputClient is now focused here. - - EXPECT_TRUE(input_method->DispatchKeyEvent(native_char)); - EXPECT_EQ(L"A", mock_text_input_client.inserted_text()); - EXPECT_TRUE(delegate_.fabricated_key_events().empty()); - delegate_.Reset(); - mock_text_input_client.Reset(); -} - -TEST(RemoteInputMethodWinTest, DispatchKeyEvent_FabricatedKeyDown) { - // Fabricated non-char event will be delegated to - // InputMethodDelegate::DispatchFabricatedKeyEventPostIME as long as the - // delegate is installed. - - MockInputMethodDelegate delegate_; - MockTextInputClient mock_text_input_client; - scoped_ptr<InputMethod> input_method(CreateRemoteInputMethodWin(&delegate_)); - - ui::KeyEvent fabricated_keydown(ui::ET_KEY_PRESSED, ui::VKEY_A, ui::EF_NONE); - fabricated_keydown.set_character(L'A'); - - // This must not cause a crash. - EXPECT_TRUE(input_method->DispatchKeyEvent(fabricated_keydown)); - EXPECT_TRUE(mock_text_input_client.inserted_text().empty()); - ASSERT_EQ(1, delegate_.fabricated_key_events().size()); - EXPECT_EQ(L'A', delegate_.fabricated_key_events()[0]); - delegate_.Reset(); - mock_text_input_client.Reset(); - - RemoteInputMethodPrivateWin* private_ptr = - RemoteInputMethodPrivateWin::Get(input_method.get()); - ASSERT_TRUE(private_ptr != NULL); - MockRemoteInputMethodDelegateWin mock_remote_delegate; - private_ptr->SetRemoteDelegate(&mock_remote_delegate); - - // TextInputClient is not focused yet here. - - EXPECT_TRUE(input_method->DispatchKeyEvent(fabricated_keydown)); - EXPECT_TRUE(mock_text_input_client.inserted_text().empty()); - ASSERT_EQ(1, delegate_.fabricated_key_events().size()); - EXPECT_EQ(L'A', delegate_.fabricated_key_events()[0]); - delegate_.Reset(); - mock_text_input_client.Reset(); - - input_method->SetFocusedTextInputClient(&mock_text_input_client); - // TextInputClient is now focused here. - - EXPECT_TRUE(input_method->DispatchKeyEvent(fabricated_keydown)); - EXPECT_TRUE(mock_text_input_client.inserted_text().empty()); - ASSERT_EQ(1, delegate_.fabricated_key_events().size()); - EXPECT_EQ(L'A', delegate_.fabricated_key_events()[0]); - delegate_.Reset(); - mock_text_input_client.Reset(); - - input_method->SetDelegate(NULL); - // RemoteInputMethodDelegateWin is no longer set here. - - EXPECT_FALSE(input_method->DispatchKeyEvent(fabricated_keydown)); - EXPECT_TRUE(mock_text_input_client.inserted_text().empty()); -} - -TEST(RemoteInputMethodWinTest, DispatchKeyEvent_FabricatedChar) { - // Note: RemoteInputMethodWin::DispatchKeyEvent should always return true - // for fabricated character events. - - MockInputMethodDelegate delegate_; - MockTextInputClient mock_text_input_client; - scoped_ptr<InputMethod> input_method(CreateRemoteInputMethodWin(&delegate_)); - - ui::KeyEvent fabricated_char(L'A', ui::VKEY_A, ui::EF_NONE); - - // This must not cause a crash. - EXPECT_TRUE(input_method->DispatchKeyEvent(fabricated_char)); - EXPECT_TRUE(mock_text_input_client.inserted_text().empty()); - EXPECT_TRUE(delegate_.fabricated_key_events().empty()); - delegate_.Reset(); - mock_text_input_client.Reset(); - - RemoteInputMethodPrivateWin* private_ptr = - RemoteInputMethodPrivateWin::Get(input_method.get()); - ASSERT_TRUE(private_ptr != NULL); - MockRemoteInputMethodDelegateWin mock_remote_delegate; - private_ptr->SetRemoteDelegate(&mock_remote_delegate); - - // TextInputClient is not focused yet here. - - EXPECT_TRUE(input_method->DispatchKeyEvent(fabricated_char)); - EXPECT_TRUE(mock_text_input_client.inserted_text().empty()); - EXPECT_TRUE(delegate_.fabricated_key_events().empty()); - delegate_.Reset(); - mock_text_input_client.Reset(); - - input_method->SetFocusedTextInputClient(&mock_text_input_client); - - // TextInputClient is now focused here. - - EXPECT_TRUE(input_method->DispatchKeyEvent(fabricated_char)); - EXPECT_EQ(L"A", mock_text_input_client.inserted_text()); - EXPECT_TRUE(delegate_.fabricated_key_events().empty()); - delegate_.Reset(); - mock_text_input_client.Reset(); -} - -TEST(RemoteInputMethodWinTest, OnCompositionChanged) { - MockInputMethodDelegate delegate_; - MockTextInputClient mock_text_input_client; - scoped_ptr<InputMethod> input_method(CreateRemoteInputMethodWin(&delegate_)); - - RemoteInputMethodPrivateWin* private_ptr = - RemoteInputMethodPrivateWin::Get(input_method.get()); - ASSERT_TRUE(private_ptr != NULL); - MockRemoteInputMethodDelegateWin mock_remote_delegate; - private_ptr->SetRemoteDelegate(&mock_remote_delegate); - - CompositionText composition_text; - - // TextInputClient is not focused yet here. - - private_ptr->OnCompositionChanged(composition_text); - EXPECT_EQ(0, mock_text_input_client.call_count_set_composition_text()); - delegate_.Reset(); - mock_text_input_client.Reset(); - - input_method->SetFocusedTextInputClient(&mock_text_input_client); - - // TextInputClient is now focused here. - - private_ptr->OnCompositionChanged(composition_text); - EXPECT_EQ(1, mock_text_input_client.call_count_set_composition_text()); - delegate_.Reset(); - mock_text_input_client.Reset(); -} - -TEST(RemoteInputMethodWinTest, OnTextCommitted) { - MockInputMethodDelegate delegate_; - MockTextInputClient mock_text_input_client; - scoped_ptr<InputMethod> input_method(CreateRemoteInputMethodWin(&delegate_)); - - RemoteInputMethodPrivateWin* private_ptr = - RemoteInputMethodPrivateWin::Get(input_method.get()); - ASSERT_TRUE(private_ptr != NULL); - MockRemoteInputMethodDelegateWin mock_remote_delegate; - private_ptr->SetRemoteDelegate(&mock_remote_delegate); - - base::string16 committed_text = L"Hello"; - - // TextInputClient is not focused yet here. - - mock_text_input_client.set_text_input_type(TEXT_INPUT_TYPE_TEXT); - private_ptr->OnTextCommitted(committed_text); - EXPECT_EQ(0, mock_text_input_client.call_count_insert_char()); - EXPECT_EQ(0, mock_text_input_client.call_count_insert_text()); - EXPECT_EQ(L"", mock_text_input_client.inserted_text()); - delegate_.Reset(); - mock_text_input_client.Reset(); - - input_method->SetFocusedTextInputClient(&mock_text_input_client); - - // TextInputClient is now focused here. - - mock_text_input_client.set_text_input_type(TEXT_INPUT_TYPE_TEXT); - private_ptr->OnTextCommitted(committed_text); - EXPECT_EQ(0, mock_text_input_client.call_count_insert_char()); - EXPECT_EQ(1, mock_text_input_client.call_count_insert_text()); - EXPECT_EQ(committed_text, mock_text_input_client.inserted_text()); - delegate_.Reset(); - mock_text_input_client.Reset(); - - // When TextInputType is TEXT_INPUT_TYPE_NONE, TextInputClient::InsertText - // should not be used. - mock_text_input_client.set_text_input_type(TEXT_INPUT_TYPE_NONE); - private_ptr->OnTextCommitted(committed_text); - EXPECT_EQ(committed_text.size(), - mock_text_input_client.call_count_insert_char()); - EXPECT_EQ(0, mock_text_input_client.call_count_insert_text()); - EXPECT_EQ(committed_text, mock_text_input_client.inserted_text()); - delegate_.Reset(); - mock_text_input_client.Reset(); -} - -TEST(RemoteInputMethodWinTest, OnTextInputStateChanged_Observer) { - DummyTextInputClient text_input_client; - DummyTextInputClient text_input_client_the_other; - - MockInputMethodObserver input_method_observer; - MockInputMethodDelegate delegate_; - scoped_ptr<InputMethod> input_method(CreateRemoteInputMethodWin(&delegate_)); - InputMethodScopedObserver scoped_observer(&input_method_observer); - scoped_observer.Add(input_method.get()); - - input_method->SetFocusedTextInputClient(&text_input_client); - ASSERT_EQ(&text_input_client, input_method->GetTextInputClient()); - EXPECT_EQ(1u, input_method_observer.on_text_input_state_changed()); - input_method_observer.Reset(); - - input_method->SetFocusedTextInputClient(&text_input_client); - ASSERT_EQ(&text_input_client, input_method->GetTextInputClient()); - EXPECT_EQ(0u, input_method_observer.on_text_input_state_changed()); - input_method_observer.Reset(); - - input_method->SetFocusedTextInputClient(&text_input_client_the_other); - ASSERT_EQ(&text_input_client_the_other, input_method->GetTextInputClient()); - EXPECT_EQ(1u, input_method_observer.on_text_input_state_changed()); - input_method_observer.Reset(); - - input_method->DetachTextInputClient(&text_input_client_the_other); - ASSERT_TRUE(input_method->GetTextInputClient() == NULL); - EXPECT_EQ(1u, input_method_observer.on_text_input_state_changed()); - input_method_observer.Reset(); -} - -TEST(RemoteInputMethodWinTest, OnInputMethodDestroyed_Observer) { - DummyTextInputClient text_input_client; - DummyTextInputClient text_input_client_the_other; - - MockInputMethodObserver input_method_observer; - InputMethodScopedObserver scoped_observer(&input_method_observer); - - MockInputMethodDelegate delegate_; - scoped_ptr<InputMethod> input_method(CreateRemoteInputMethodWin(&delegate_)); - input_method->AddObserver(&input_method_observer); - - EXPECT_EQ(0u, input_method_observer.on_input_method_destroyed_changed()); - input_method.reset(); - EXPECT_EQ(1u, input_method_observer.on_input_method_destroyed_changed()); -} - -} // namespace -} // namespace ui
diff --git a/ui/base/ime/text_input_client.cc b/ui/base/ime/text_input_client.cc deleted file mode 100644 index 2fb370e..0000000 --- a/ui/base/ime/text_input_client.cc +++ /dev/null
@@ -1,12 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/text_input_client.h" - -namespace ui { - -TextInputClient::~TextInputClient() { -} - -} // namespace ui
diff --git a/ui/base/ime/text_input_client.h b/ui/base/ime/text_input_client.h deleted file mode 100644 index ff1242f..0000000 --- a/ui/base/ime/text_input_client.h +++ /dev/null
@@ -1,178 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_TEXT_INPUT_CLIENT_H_ -#define UI_BASE_IME_TEXT_INPUT_CLIENT_H_ - -#include "base/basictypes.h" -#include "base/i18n/rtl.h" -#include "base/strings/string16.h" -#include "ui/base/ime/composition_text.h" -#include "ui/base/ime/text_input_mode.h" -#include "ui/base/ime/text_input_type.h" -#include "ui/base/ui_base_export.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/gfx/range/range.h" - -namespace gfx { -class Rect; -} - -namespace ui { - -// An interface implemented by a View that needs text input support. -class UI_BASE_EXPORT TextInputClient { - public: - virtual ~TextInputClient(); - - // Input method result ------------------------------------------------------- - - // Sets composition text and attributes. If there is composition text already, - // it'll be replaced by the new one. Otherwise, current selection will be - // replaced. If there is no selection, the composition text will be inserted - // at the insertion point. - virtual void SetCompositionText(const ui::CompositionText& composition) = 0; - - // Converts current composition text into final content. - virtual void ConfirmCompositionText() = 0; - - // Removes current composition text. - virtual void ClearCompositionText() = 0; - - // Inserts a given text at the insertion point. Current composition text or - // selection will be removed. This method should never be called when the - // current text input type is TEXT_INPUT_TYPE_NONE. - virtual void InsertText(const base::string16& text) = 0; - - // Inserts a single char at the insertion point. Unlike above InsertText() - // method, this method has an extra |flags| parameter indicating the modifier - // key states when the character is generated. This method should only be - // called when a key press is not handled by the input method but still - // generates a character (eg. by the keyboard driver). In another word, the - // preceding key press event should not be a VKEY_PROCESSKEY. - // This method will be called whenever a char is generated by the keyboard, - // even if the current text input type is TEXT_INPUT_TYPE_NONE. - virtual void InsertChar(base::char16 ch, int flags) = 0; - - // Input context information ------------------------------------------------- - - // Returns native window to which input context is bound. - virtual gfx::NativeWindow GetAttachedWindow() const = 0; - - // Returns current text input type. It could be changed and even becomes - // TEXT_INPUT_TYPE_NONE at runtime. - virtual ui::TextInputType GetTextInputType() const = 0; - - // Returns current text input mode. It could be changed and even becomes - // TEXT_INPUT_MODE_DEFAULT at runtime. - virtual ui::TextInputMode GetTextInputMode() const = 0; - - // Returns if the client supports inline composition currently. - virtual bool CanComposeInline() const = 0; - - // Returns current caret (insertion point) bounds in the universal screen - // coordinates. If there is selection, then the selection bounds will be - // returned. - // Note: On Windows, the returned value is supposed to be DIP (Density - // Independent Pixel). - // TODO(ime): Have a clear spec whether the returned value is DIP or not. - // http://crbug.com/360334 - virtual gfx::Rect GetCaretBounds() const = 0; - - // Retrieves the composition character boundary rectangle in the universal - // screen coordinates. The |index| is zero-based index of character position - // in composition text. - // Returns false if there is no composition text or |index| is out of range. - // The |rect| is not touched in the case of failure. - // Note: On Windows, the returned value is supposed to be DIP - // (Density Independent Pixel). - // TODO(ime): Have a clear spec whether the returned value is DIP or not. - // http://crbug.com/360334 - virtual bool GetCompositionCharacterBounds(uint32 index, - gfx::Rect* rect) const = 0; - - // Returns true if there is composition text. - virtual bool HasCompositionText() const = 0; - - // Document content operations ---------------------------------------------- - - // Retrieves the UTF-16 based character range containing accessibled text in - // the View. It must cover the composition and selection range. - // Returns false if the information cannot be retrieved right now. - virtual bool GetTextRange(gfx::Range* range) const = 0; - - // Retrieves the UTF-16 based character range of current composition text. - // Returns false if the information cannot be retrieved right now. - virtual bool GetCompositionTextRange(gfx::Range* range) const = 0; - - // Retrieves the UTF-16 based character range of current selection. - // Returns false if the information cannot be retrieved right now. - virtual bool GetSelectionRange(gfx::Range* range) const = 0; - - // Selects the given UTF-16 based character range. Current composition text - // will be confirmed before selecting the range. - // Returns false if the operation is not supported. - virtual bool SetSelectionRange(const gfx::Range& range) = 0; - - // Deletes contents in the given UTF-16 based character range. Current - // composition text will be confirmed before deleting the range. - // The input caret will be moved to the place where the range gets deleted. - // ExtendSelectionAndDelete should be used instead as far as you are deleting - // characters around current caret. This function with the range based on - // GetSelectionRange has a race condition due to asynchronous IPCs between - // browser and renderer. - // Returns false if the operation is not supported. - virtual bool DeleteRange(const gfx::Range& range) = 0; - - // Retrieves the text content in a given UTF-16 based character range. - // The result will be stored into |*text|. - // Returns false if the operation is not supported or the specified range - // is out of the text range returned by GetTextRange(). - virtual bool GetTextFromRange(const gfx::Range& range, - base::string16* text) const = 0; - - // Miscellaneous ------------------------------------------------------------ - - // Called whenever current keyboard layout or input method is changed, - // especially the change of input locale and text direction. - virtual void OnInputMethodChanged() = 0; - - // Called whenever the user requests to change the text direction and layout - // alignment of the current text box. It's for supporting ctrl-shift on - // Windows. - // Returns false if the operation is not supported. - virtual bool ChangeTextDirectionAndLayoutAlignment( - base::i18n::TextDirection direction) = 0; - - // Deletes the current selection plus the specified number of characters - // before and after the selection or caret. This function should be used - // instead of calling DeleteRange with GetSelectionRange, because - // GetSelectionRange may not be the latest value due to asynchronous of IPC - // between browser and renderer. - virtual void ExtendSelectionAndDelete(size_t before, size_t after) = 0; - - // Ensure the caret is within |rect|. |rect| is in screen coordinates and - // may extend beyond the bounds of this TextInputClient. - // Note: On Windows, the returned value is supposed to be DIP (Density - // Independent Pixel). - // TODO(ime): Have a clear spec whether the returned value is DIP or not. - // http://crbug.com/360334 - virtual void EnsureCaretInRect(const gfx::Rect& rect) = 0; - - // Called when IME shows a candidate window. - virtual void OnCandidateWindowShown() = 0; - // Called when IME updates any appearance of the current candidate window. - virtual void OnCandidateWindowUpdated() = 0; - // Called when IME hides the candidate window. - virtual void OnCandidateWindowHidden() = 0; - - // Returns true if |command_id| is currently allowed to be executed. - virtual bool IsEditingCommandEnabled(int command_id) = 0; - // Execute the command specified by |command_id|. - virtual void ExecuteEditingCommand(int command_id) = 0; -}; - -} // namespace ui - -#endif // UI_BASE_IME_TEXT_INPUT_CLIENT_H_
diff --git a/ui/base/ime/text_input_focus_manager.cc b/ui/base/ime/text_input_focus_manager.cc deleted file mode 100644 index 25033d8..0000000 --- a/ui/base/ime/text_input_focus_manager.cc +++ /dev/null
@@ -1,45 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/text_input_focus_manager.h" - -#include "base/logging.h" -#include "base/memory/singleton.h" - -namespace ui { - -// TODO(sky): reenable these DCHECKs. We're in the process of enabling usage -// of views from multiple threads and this causes problems. See -// http://crbug.com/388045 for details. - -TextInputFocusManager* TextInputFocusManager::GetInstance() { - TextInputFocusManager* instance = Singleton<TextInputFocusManager>::get(); - // DCHECK(instance->thread_checker_.CalledOnValidThread()); - return instance; -} - -TextInputClient* TextInputFocusManager::GetFocusedTextInputClient() { - // DCHECK(thread_checker_.CalledOnValidThread()); - return focused_text_input_client_; -} - -void TextInputFocusManager::FocusTextInputClient( - TextInputClient* text_input_client) { - // DCHECK(thread_checker_.CalledOnValidThread()); - focused_text_input_client_ = text_input_client; -} - -void TextInputFocusManager::BlurTextInputClient( - TextInputClient* text_input_client) { - // DCHECK(thread_checker_.CalledOnValidThread()); - if (focused_text_input_client_ == text_input_client) - focused_text_input_client_ = NULL; -} - -TextInputFocusManager::TextInputFocusManager() - : focused_text_input_client_(NULL) {} - -TextInputFocusManager::~TextInputFocusManager() {} - -} // namespace ui
diff --git a/ui/base/ime/text_input_focus_manager.h b/ui/base/ime/text_input_focus_manager.h deleted file mode 100644 index 22f47e3..0000000 --- a/ui/base/ime/text_input_focus_manager.h +++ /dev/null
@@ -1,47 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_TEXT_INPUT_FOCUS_MANAGER_H_ -#define UI_BASE_IME_TEXT_INPUT_FOCUS_MANAGER_H_ - -#include "base/macros.h" -#include "base/threading/thread_checker.h" -#include "ui/base/ui_base_export.h" - -template <typename T> struct DefaultSingletonTraits; - -namespace ui { - -class TextInputClient; - -// Manages the focused TextInputClient across windows and their contents. -class UI_BASE_EXPORT TextInputFocusManager { - public: - static TextInputFocusManager* GetInstance(); - - // Returns the currently focused text input client or NULL. - TextInputClient* GetFocusedTextInputClient(); - - // Changes the text input focus to |text_input_client|. - void FocusTextInputClient(TextInputClient* text_input_client); - - // Removes the text input focus from |text_input_client|. If - // |text_input_client| was not focused, does nothing. - void BlurTextInputClient(TextInputClient* text_input_client); - - private: - friend struct DefaultSingletonTraits<TextInputFocusManager>; - - TextInputFocusManager(); - ~TextInputFocusManager(); - - TextInputClient* focused_text_input_client_; - base::ThreadChecker thread_checker_; - - DISALLOW_COPY_AND_ASSIGN(TextInputFocusManager); -}; - -} // namespace ui - -#endif // UI_BASE_IME_TEXT_INPUT_FOCUS_MANAGER_H_
diff --git a/ui/base/ime/text_input_mode.h b/ui/base/ime/text_input_mode.h deleted file mode 100644 index 1344f61..0000000 --- a/ui/base/ime/text_input_mode.h +++ /dev/null
@@ -1,31 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_TEXT_INPUT_MODE_H_ -#define UI_BASE_IME_TEXT_INPUT_MODE_H_ - -namespace ui { - -// This mode corrensponds to inputmode -// http://www.whatwg.org/specs/web-apps/current-work/#attr-fe-inputmode -enum TextInputMode { - TEXT_INPUT_MODE_DEFAULT, - TEXT_INPUT_MODE_VERBATIM, - TEXT_INPUT_MODE_LATIN, - TEXT_INPUT_MODE_LATIN_NAME, - TEXT_INPUT_MODE_LATIN_PROSE, - TEXT_INPUT_MODE_FULL_WIDTH_LATIN, - TEXT_INPUT_MODE_KANA, - TEXT_INPUT_MODE_KATAKANA, - TEXT_INPUT_MODE_NUMERIC, - TEXT_INPUT_MODE_TEL, - TEXT_INPUT_MODE_EMAIL, - TEXT_INPUT_MODE_URL, - - TEXT_INPUT_MODE_MAX = TEXT_INPUT_MODE_URL, -}; - -} // namespace ui - -#endif // UI_BASE_IME_TEXT_INPUT_TYPE_H_
diff --git a/ui/base/ime/text_input_type.h b/ui/base/ime/text_input_type.h deleted file mode 100644 index c97568f..0000000 --- a/ui/base/ime/text_input_type.h +++ /dev/null
@@ -1,49 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_TEXT_INPUT_TYPE_H_ -#define UI_BASE_IME_TEXT_INPUT_TYPE_H_ - -namespace ui { - -// Intentionally keep sync with blink::WebTextInputType defined in: -// third_party/WebKit/public/web/WebTextInputType.h -enum TextInputType { - // Input caret is not in an editable node, no input method shall be used. - TEXT_INPUT_TYPE_NONE, - - // Input caret is in a normal editable node, any input method can be used. - TEXT_INPUT_TYPE_TEXT, - - // Input caret is in a password box, an input method may be used only if - // it's suitable for password input. - TEXT_INPUT_TYPE_PASSWORD, - - TEXT_INPUT_TYPE_SEARCH, - TEXT_INPUT_TYPE_EMAIL, - TEXT_INPUT_TYPE_NUMBER, - TEXT_INPUT_TYPE_TELEPHONE, - TEXT_INPUT_TYPE_URL, - TEXT_INPUT_TYPE_DATE, - TEXT_INPUT_TYPE_DATE_TIME, - TEXT_INPUT_TYPE_DATE_TIME_LOCAL, - TEXT_INPUT_TYPE_MONTH, - TEXT_INPUT_TYPE_TIME, - TEXT_INPUT_TYPE_WEEK, - TEXT_INPUT_TYPE_TEXT_AREA, - - // Input caret is in a contenteditable node (not an INPUT field). - TEXT_INPUT_TYPE_CONTENT_EDITABLE, - - // The focused node is date time field. The date time field does not have - // input caret but it is necessary to distinguish from TEXT_INPUT_TYPE_NONE - // for on-screen keyboard. - TEXT_INPUT_TYPE_DATE_TIME_FIELD, - - TEXT_INPUT_TYPE_MAX = TEXT_INPUT_TYPE_DATE_TIME_FIELD, -}; - -} // namespace ui - -#endif // UI_BASE_IME_TEXT_INPUT_TYPE_H_
diff --git a/ui/base/ime/win/imm32_manager.cc b/ui/base/ime/win/imm32_manager.cc deleted file mode 100644 index 7ad2d87..0000000 --- a/ui/base/ime/win/imm32_manager.cc +++ /dev/null
@@ -1,642 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/win/imm32_manager.h" - -#include <msctf.h> - -#include "base/basictypes.h" -#include "base/memory/scoped_ptr.h" -#include "base/strings/string16.h" -#include "base/strings/string_util.h" -#include "base/strings/utf_string_conversions.h" -#include "base/win/scoped_comptr.h" -#include "third_party/skia/include/core/SkColor.h" -#include "ui/base/ime/composition_text.h" - -// "imm32.lib" is required by IMM32 APIs used in this file. -// NOTE(hbono): To comply with a comment from Darin, I have added -// this #pragma directive instead of adding "imm32.lib" to a project file. -#pragma comment(lib, "imm32.lib") - -// Following code requires wchar_t to be same as char16. It should always be -// true on Windows. -COMPILE_ASSERT(sizeof(wchar_t) == sizeof(base::char16), wchar_t__char16_diff); - -/////////////////////////////////////////////////////////////////////////////// -// IMM32Manager - -namespace { - -// Determines whether or not the given attribute represents a target -// (a.k.a. a selection). -bool IsTargetAttribute(char attribute) { - return (attribute == ATTR_TARGET_CONVERTED || - attribute == ATTR_TARGET_NOTCONVERTED); -} - -// Helper function for IMM32Manager::GetCompositionInfo() method, to get the -// target range that's selected by the user in the current composition string. -void GetCompositionTargetRange(HIMC imm_context, int* target_start, - int* target_end) { - int attribute_size = ::ImmGetCompositionString(imm_context, GCS_COMPATTR, - NULL, 0); - if (attribute_size > 0) { - int start = 0; - int end = 0; - scoped_ptr<char[]> attribute_data(new char[attribute_size]); - if (attribute_data.get()) { - ::ImmGetCompositionString(imm_context, GCS_COMPATTR, - attribute_data.get(), attribute_size); - for (start = 0; start < attribute_size; ++start) { - if (IsTargetAttribute(attribute_data[start])) - break; - } - for (end = start; end < attribute_size; ++end) { - if (!IsTargetAttribute(attribute_data[end])) - break; - } - } - *target_start = start; - *target_end = end; - } -} - -// Helper function for IMM32Manager::GetCompositionInfo() method, to get -// underlines information of the current composition string. -void GetCompositionUnderlines(HIMC imm_context, - int target_start, - int target_end, - ui::CompositionUnderlines* underlines) { - int clause_size = ::ImmGetCompositionString(imm_context, GCS_COMPCLAUSE, - NULL, 0); - int clause_length = clause_size / sizeof(uint32); - if (clause_length) { - scoped_ptr<uint32[]> clause_data(new uint32[clause_length]); - if (clause_data.get()) { - ::ImmGetCompositionString(imm_context, GCS_COMPCLAUSE, - clause_data.get(), clause_size); - for (int i = 0; i < clause_length - 1; ++i) { - ui::CompositionUnderline underline; - underline.start_offset = clause_data[i]; - underline.end_offset = clause_data[i+1]; - underline.color = SK_ColorBLACK; - underline.thick = false; - underline.background_color = SK_ColorTRANSPARENT; - - // Use thick underline for the target clause. - if (underline.start_offset >= static_cast<uint32>(target_start) && - underline.end_offset <= static_cast<uint32>(target_end)) { - underline.thick = true; - } - underlines->push_back(underline); - } - } - } -} - -// Checks if a given primary language ID is a RTL language. -bool IsRTLPrimaryLangID(LANGID lang) { - switch (lang) { - case LANG_ARABIC: - case LANG_HEBREW: - case LANG_PERSIAN: - case LANG_SYRIAC: - case LANG_UIGHUR: - case LANG_URDU: - return true; - default: - return false; - } -} - -} // namespace - -namespace ui { - -IMM32Manager::IMM32Manager() - : ime_status_(false), - input_language_id_(LANG_USER_DEFAULT), - is_composing_(false), - system_caret_(false), - caret_rect_(-1, -1, 0, 0), - use_composition_window_(false) { -} - -IMM32Manager::~IMM32Manager() { -} - -bool IMM32Manager::SetInputLanguage() { - // Retrieve the current keyboard layout from Windows and determine whether - // or not the current input context has IMEs. - // Also save its input language for language-specific operations required - // while composing a text. - HKL keyboard_layout = ::GetKeyboardLayout(0); - input_language_id_ = reinterpret_cast<LANGID>(keyboard_layout); - - // Check TSF Input Processor first. - // If the active profile is TSF INPUTPROCESSOR, this is IME. - base::win::ScopedComPtr<ITfInputProcessorProfileMgr> prof_mgr; - TF_INPUTPROCESSORPROFILE prof; - if (SUCCEEDED(prof_mgr.CreateInstance(CLSID_TF_InputProcessorProfiles)) && - SUCCEEDED(prof_mgr->GetActiveProfile(GUID_TFCAT_TIP_KEYBOARD, &prof)) && - prof.hkl == NULL && - prof.dwProfileType == TF_PROFILETYPE_INPUTPROCESSOR) { - ime_status_ = true; - } else { - // If the curent language is not using TSF, check IMM32 based IMEs. - // As ImmIsIME always returns non-0 value on Vista+, use ImmGetIMEFileName - // instead to check if this HKL has any associated IME file. - ime_status_ = (ImmGetIMEFileName(keyboard_layout, NULL, 0) != 0); - } - - return ime_status_; -} - -void IMM32Manager::CreateImeWindow(HWND window_handle) { - // When a user disables TSF (Text Service Framework) and CUAS (Cicero - // Unaware Application Support), Chinese IMEs somehow ignore function calls - // to ::ImmSetCandidateWindow(), i.e. they do not move their candidate - // window to the position given as its parameters, and use the position - // of the current system caret instead, i.e. it uses ::GetCaretPos() to - // retrieve the position of their IME candidate window. - // Therefore, we create a temporary system caret for Chinese IMEs and use - // it during this input context. - // Since some third-party Japanese IME also uses ::GetCaretPos() to determine - // their window position, we also create a caret for Japanese IMEs. - if (PRIMARYLANGID(input_language_id_) == LANG_CHINESE || - PRIMARYLANGID(input_language_id_) == LANG_JAPANESE) { - if (!system_caret_) { - if (::CreateCaret(window_handle, NULL, 1, 1)) { - system_caret_ = true; - } - } - } - // Restore the positions of the IME windows. - UpdateImeWindow(window_handle); -} - -LRESULT IMM32Manager::SetImeWindowStyle(HWND window_handle, UINT message, - WPARAM wparam, LPARAM lparam, - BOOL* handled) { - // To prevent the IMM (Input Method Manager) from displaying the IME - // composition window, Update the styles of the IME windows and EXPLICITLY - // call ::DefWindowProc() here. - // NOTE(hbono): We can NEVER let WTL call ::DefWindowProc() when we update - // the styles of IME windows because the 'lparam' variable is a local one - // and all its updates disappear in returning from this function, i.e. WTL - // does not call ::DefWindowProc() with our updated 'lparam' value but call - // the function with its original value and over-writes our window styles. - *handled = TRUE; - lparam &= ~ISC_SHOWUICOMPOSITIONWINDOW; - return ::DefWindowProc(window_handle, message, wparam, lparam); -} - -void IMM32Manager::DestroyImeWindow(HWND window_handle) { - // Destroy the system caret if we have created for this IME input context. - if (system_caret_) { - ::DestroyCaret(); - system_caret_ = false; - } -} - -void IMM32Manager::MoveImeWindow(HWND window_handle, HIMC imm_context) { - // Does nothing when the target window has no input focus. This is important - // because the renderer may issue SelectionBoundsChanged event even when it - // has no input focus. (e.g. the page update caused by incremental search.) - // So this event should be ignored when the |window_handle| no longer has the - // input focus. - if (GetFocus() != window_handle) - return; - - int x = caret_rect_.x(); - int y = caret_rect_.y(); - - const int kCaretMargin = 1; - if (!use_composition_window_ && - PRIMARYLANGID(input_language_id_) == LANG_CHINESE) { - // As written in a comment in IMM32Manager::CreateImeWindow(), - // Chinese IMEs ignore function calls to ::ImmSetCandidateWindow() - // when a user disables TSF (Text Service Framework) and CUAS (Cicero - // Unaware Application Support). - // On the other hand, when a user enables TSF and CUAS, Chinese IMEs - // ignore the position of the current system caret and uses the - // parameters given to ::ImmSetCandidateWindow() with its 'dwStyle' - // parameter CFS_CANDIDATEPOS. - // Therefore, we do not only call ::ImmSetCandidateWindow() but also - // set the positions of the temporary system caret if it exists. - CANDIDATEFORM candidate_position = {0, CFS_CANDIDATEPOS, {x, y}, - {0, 0, 0, 0}}; - ::ImmSetCandidateWindow(imm_context, &candidate_position); - } - if (system_caret_) { - switch (PRIMARYLANGID(input_language_id_)) { - case LANG_JAPANESE: - ::SetCaretPos(x, y + caret_rect_.height()); - break; - default: - ::SetCaretPos(x, y); - break; - } - } - if (use_composition_window_) { - // Moves the composition text window. - COMPOSITIONFORM cf = {CFS_POINT, {x, y}}; - ::ImmSetCompositionWindow(imm_context, &cf); - // Don't need to set the position of candidate window. - return; - } - - if (PRIMARYLANGID(input_language_id_) == LANG_KOREAN) { - // Chinese IMEs and Japanese IMEs require the upper-left corner of - // the caret to move the position of their candidate windows. - // On the other hand, Korean IMEs require the lower-left corner of the - // caret to move their candidate windows. - y += kCaretMargin; - } - // Japanese IMEs and Korean IMEs also use the rectangle given to - // ::ImmSetCandidateWindow() with its 'dwStyle' parameter CFS_EXCLUDE - // to move their candidate windows when a user disables TSF and CUAS. - // Therefore, we also set this parameter here. - CANDIDATEFORM exclude_rectangle = {0, CFS_EXCLUDE, {x, y}, - {x, y, x + caret_rect_.width(), y + caret_rect_.height()}}; - ::ImmSetCandidateWindow(imm_context, &exclude_rectangle); -} - -void IMM32Manager::UpdateImeWindow(HWND window_handle) { - // Just move the IME window attached to the given window. - if (caret_rect_.x() >= 0 && caret_rect_.y() >= 0) { - HIMC imm_context = ::ImmGetContext(window_handle); - if (imm_context) { - MoveImeWindow(window_handle, imm_context); - ::ImmReleaseContext(window_handle, imm_context); - } - } -} - -void IMM32Manager::CleanupComposition(HWND window_handle) { - // Notify the IMM attached to the given window to complete the ongoing - // composition, (this case happens when the given window is de-activated - // while composing a text and re-activated), and reset the omposition status. - if (is_composing_) { - HIMC imm_context = ::ImmGetContext(window_handle); - if (imm_context) { - ::ImmNotifyIME(imm_context, NI_COMPOSITIONSTR, CPS_COMPLETE, 0); - ::ImmReleaseContext(window_handle, imm_context); - } - ResetComposition(window_handle); - } -} - -void IMM32Manager::ResetComposition(HWND window_handle) { - // Currently, just reset the composition status. - is_composing_ = false; -} - -void IMM32Manager::CompleteComposition(HWND window_handle, HIMC imm_context) { - // We have to confirm there is an ongoing composition before completing it. - // This is for preventing some IMEs from getting confused while completing an - // ongoing composition even if they do not have any ongoing compositions.) - if (is_composing_) { - ::ImmNotifyIME(imm_context, NI_COMPOSITIONSTR, CPS_COMPLETE, 0); - ResetComposition(window_handle); - } -} - -void IMM32Manager::GetCompositionInfo(HIMC imm_context, LPARAM lparam, - CompositionText* composition) { - // We only care about GCS_COMPATTR, GCS_COMPCLAUSE and GCS_CURSORPOS, and - // convert them into underlines and selection range respectively. - composition->underlines.clear(); - - int length = static_cast<int>(composition->text.length()); - - // Find out the range selected by the user. - int target_start = length; - int target_end = length; - if (lparam & GCS_COMPATTR) - GetCompositionTargetRange(imm_context, &target_start, &target_end); - - // Retrieve the selection range information. If CS_NOMOVECARET is specified, - // that means the cursor should not be moved, then we just place the caret at - // the beginning of the composition string. Otherwise we should honour the - // GCS_CURSORPOS value if it's available. - // TODO(suzhe): due to a bug of webkit, we currently can't use selection range - // with composition string. See: https://bugs.webkit.org/show_bug.cgi?id=40805 - if (!(lparam & CS_NOMOVECARET) && (lparam & GCS_CURSORPOS)) { - // IMM32 does not support non-zero-width selection in a composition. So - // always use the caret position as selection range. - int cursor = ::ImmGetCompositionString(imm_context, GCS_CURSORPOS, NULL, 0); - composition->selection = gfx::Range(cursor); - } else { - composition->selection = gfx::Range(0); - } - - // Retrieve the clause segmentations and convert them to underlines. - if (lparam & GCS_COMPCLAUSE) { - GetCompositionUnderlines(imm_context, target_start, target_end, - &composition->underlines); - } - - // Set default underlines in case there is no clause information. - if (!composition->underlines.size()) { - CompositionUnderline underline; - underline.color = SK_ColorBLACK; - underline.background_color = SK_ColorTRANSPARENT; - if (target_start > 0) { - underline.start_offset = 0U; - underline.end_offset = static_cast<uint32>(target_start); - underline.thick = false; - composition->underlines.push_back(underline); - } - if (target_end > target_start) { - underline.start_offset = static_cast<uint32>(target_start); - underline.end_offset = static_cast<uint32>(target_end); - underline.thick = true; - composition->underlines.push_back(underline); - } - if (target_end < length) { - underline.start_offset = static_cast<uint32>(target_end); - underline.end_offset = static_cast<uint32>(length); - underline.thick = false; - composition->underlines.push_back(underline); - } - } -} - -bool IMM32Manager::GetString(HIMC imm_context, - WPARAM lparam, - int type, - base::string16* result) { - if (!(lparam & type)) - return false; - LONG string_size = ::ImmGetCompositionString(imm_context, type, NULL, 0); - if (string_size <= 0) - return false; - DCHECK_EQ(0u, string_size % sizeof(wchar_t)); - ::ImmGetCompositionString(imm_context, type, - WriteInto(result, (string_size / sizeof(wchar_t)) + 1), string_size); - return true; -} - -bool IMM32Manager::GetResult( - HWND window_handle, LPARAM lparam, base::string16* result) { - bool ret = false; - HIMC imm_context = ::ImmGetContext(window_handle); - if (imm_context) { - ret = GetString(imm_context, lparam, GCS_RESULTSTR, result); - ::ImmReleaseContext(window_handle, imm_context); - } - return ret; -} - -bool IMM32Manager::GetComposition(HWND window_handle, LPARAM lparam, - CompositionText* composition) { - bool ret = false; - HIMC imm_context = ::ImmGetContext(window_handle); - if (imm_context) { - // Copy the composition string to the CompositionText object. - ret = GetString(imm_context, lparam, GCS_COMPSTR, &composition->text); - - if (ret) { - // This is a dirty workaround for facebook. Facebook deletes the - // placeholder character (U+3000) used by Traditional-Chinese IMEs at the - // beginning of composition text. This prevents WebKit from replacing this - // placeholder character with a Traditional-Chinese character, i.e. we - // cannot input any characters in a comment box of facebook with - // Traditional-Chinese IMEs. As a workaround, we replace U+3000 at the - // beginning of composition text with U+FF3F, a placeholder character used - // by Japanese IMEs. - if (input_language_id_ == MAKELANGID(LANG_CHINESE, - SUBLANG_CHINESE_TRADITIONAL) && - composition->text[0] == 0x3000) { - composition->text[0] = 0xFF3F; - } - - // Retrieve the composition underlines and selection range information. - GetCompositionInfo(imm_context, lparam, composition); - - // Mark that there is an ongoing composition. - is_composing_ = true; - } - - ::ImmReleaseContext(window_handle, imm_context); - } - return ret; -} - -void IMM32Manager::DisableIME(HWND window_handle) { - // A renderer process have moved its input focus to a password input - // when there is an ongoing composition, e.g. a user has clicked a - // mouse button and selected a password input while composing a text. - // For this case, we have to complete the ongoing composition and - // clean up the resources attached to this object BEFORE DISABLING THE IME. - CleanupComposition(window_handle); - ::ImmAssociateContextEx(window_handle, NULL, 0); -} - -void IMM32Manager::CancelIME(HWND window_handle) { - if (is_composing_) { - HIMC imm_context = ::ImmGetContext(window_handle); - if (imm_context) { - ::ImmNotifyIME(imm_context, NI_COMPOSITIONSTR, CPS_CANCEL, 0); - ::ImmReleaseContext(window_handle, imm_context); - } - ResetComposition(window_handle); - } -} - -void IMM32Manager::EnableIME(HWND window_handle) { - // Load the default IME context. - // NOTE(hbono) - // IMM ignores this call if the IME context is loaded. Therefore, we do - // not have to check whether or not the IME context is loaded. - ::ImmAssociateContextEx(window_handle, NULL, IACE_DEFAULT); -} - -void IMM32Manager::UpdateCaretRect(HWND window_handle, - const gfx::Rect& caret_rect) { - // Save the caret position, and Update the position of the IME window. - // This update is used for moving an IME window when a renderer process - // resize/moves the input caret. - if (caret_rect_ != caret_rect) { - caret_rect_ = caret_rect; - // Move the IME windows. - HIMC imm_context = ::ImmGetContext(window_handle); - if (imm_context) { - MoveImeWindow(window_handle, imm_context); - ::ImmReleaseContext(window_handle, imm_context); - } - } -} - -void IMM32Manager::SetUseCompositionWindow(bool use_composition_window) { - use_composition_window_ = use_composition_window; -} - -std::string IMM32Manager::GetInputLanguageName() const { - const LCID locale_id = MAKELCID(input_language_id_, SORT_DEFAULT); - // max size for LOCALE_SISO639LANGNAME and LOCALE_SISO3166CTRYNAME is 9. - wchar_t buffer[9]; - - // Get language id. - int length = ::GetLocaleInfo(locale_id, LOCALE_SISO639LANGNAME, &buffer[0], - arraysize(buffer)); - if (length <= 1) - return std::string(); - - std::string language; - base::WideToUTF8(buffer, length - 1, &language); - if (SUBLANGID(input_language_id_) == SUBLANG_NEUTRAL) - return language; - - // Get region id. - length = ::GetLocaleInfo(locale_id, LOCALE_SISO3166CTRYNAME, &buffer[0], - arraysize(buffer)); - if (length <= 1) - return language; - - std::string region; - base::WideToUTF8(buffer, length - 1, ®ion); - return language.append(1, '-').append(region); -} - -void IMM32Manager::SetTextInputMode(HWND window_handle, - TextInputMode input_mode) { - if (input_mode == ui::TEXT_INPUT_MODE_DEFAULT) - return; - - const HIMC imm_context = ::ImmGetContext(window_handle); - if (!imm_context) - return; - - DWORD conversion_mode = 0; - DWORD sentence_mode = 0; - if (::ImmGetConversionStatus(imm_context, &conversion_mode, &sentence_mode) - == FALSE) { - return; - } - - BOOL open = FALSE; - ConvertInputModeToImmFlags(input_mode, conversion_mode, &open, - &conversion_mode), - - ::ImmSetOpenStatus(imm_context, open); - if (open) - ::ImmSetConversionStatus(imm_context, conversion_mode, sentence_mode); - ::ImmReleaseContext(window_handle, imm_context); -} - -// static -bool IMM32Manager::IsRTLKeyboardLayoutInstalled() { - static enum { - RTL_KEYBOARD_LAYOUT_NOT_INITIALIZED, - RTL_KEYBOARD_LAYOUT_INSTALLED, - RTL_KEYBOARD_LAYOUT_NOT_INSTALLED, - RTL_KEYBOARD_LAYOUT_ERROR, - } layout = RTL_KEYBOARD_LAYOUT_NOT_INITIALIZED; - - // Cache the result value. - if (layout != RTL_KEYBOARD_LAYOUT_NOT_INITIALIZED) - return layout == RTL_KEYBOARD_LAYOUT_INSTALLED; - - // Retrieve the number of layouts installed in this system. - int size = GetKeyboardLayoutList(0, NULL); - if (size <= 0) { - layout = RTL_KEYBOARD_LAYOUT_ERROR; - return false; - } - - // Retrieve the keyboard layouts in an array and check if there is an RTL - // layout in it. - scoped_ptr<HKL[]> layouts(new HKL[size]); - ::GetKeyboardLayoutList(size, layouts.get()); - for (int i = 0; i < size; ++i) { - if (IsRTLPrimaryLangID(PRIMARYLANGID(layouts[i]))) { - layout = RTL_KEYBOARD_LAYOUT_INSTALLED; - return true; - } - } - - layout = RTL_KEYBOARD_LAYOUT_NOT_INSTALLED; - return false; -} - -bool IMM32Manager::IsCtrlShiftPressed(base::i18n::TextDirection* direction) { - uint8_t keystate[256]; - if (!::GetKeyboardState(&keystate[0])) - return false; - - // To check if a user is pressing only a control key and a right-shift key - // (or a left-shift key), we use the steps below: - // 1. Check if a user is pressing a control key and a right-shift key (or - // a left-shift key). - // 2. If the condition 1 is true, we should check if there are any other - // keys pressed at the same time. - // To ignore the keys checked in 1, we set their status to 0 before - // checking the key status. - const int kKeyDownMask = 0x80; - if ((keystate[VK_CONTROL] & kKeyDownMask) == 0) - return false; - - if (keystate[VK_RSHIFT] & kKeyDownMask) { - keystate[VK_RSHIFT] = 0; - *direction = base::i18n::RIGHT_TO_LEFT; - } else if (keystate[VK_LSHIFT] & kKeyDownMask) { - keystate[VK_LSHIFT] = 0; - *direction = base::i18n::LEFT_TO_RIGHT; - } else { - return false; - } - - // Scan the key status to find pressed keys. We should abandon changing the - // text direction when there are other pressed keys. - // This code is executed only when a user is pressing a control key and a - // right-shift key (or a left-shift key), i.e. we should ignore the status of - // the keys: VK_SHIFT, VK_CONTROL, VK_RCONTROL, and VK_LCONTROL. - // So, we reset their status to 0 and ignore them. - keystate[VK_SHIFT] = 0; - keystate[VK_CONTROL] = 0; - keystate[VK_RCONTROL] = 0; - keystate[VK_LCONTROL] = 0; - // Oddly, pressing F10 in another application seemingly breaks all subsequent - // calls to GetKeyboardState regarding the state of the F22 key. Perhaps this - // defect is limited to my keyboard driver, but ignoring F22 should be okay. - keystate[VK_F22] = 0; - for (int i = 0; i <= VK_PACKET; ++i) { - if (keystate[i] & kKeyDownMask) - return false; - } - return true; -} - -void IMM32Manager::ConvertInputModeToImmFlags(TextInputMode input_mode, - DWORD initial_conversion_mode, - BOOL* open, - DWORD* new_conversion_mode) { - *open = TRUE; - *new_conversion_mode = initial_conversion_mode; - switch (input_mode) { - case ui::TEXT_INPUT_MODE_FULL_WIDTH_LATIN: - *new_conversion_mode |= IME_CMODE_FULLSHAPE; - *new_conversion_mode &= ~(IME_CMODE_NATIVE - | IME_CMODE_KATAKANA); - break; - case ui::TEXT_INPUT_MODE_KANA: - *new_conversion_mode |= (IME_CMODE_NATIVE - | IME_CMODE_FULLSHAPE); - *new_conversion_mode &= ~IME_CMODE_KATAKANA; - break; - case ui::TEXT_INPUT_MODE_KATAKANA: - *new_conversion_mode |= (IME_CMODE_NATIVE - | IME_CMODE_KATAKANA - | IME_CMODE_FULLSHAPE); - break; - default: - *open = FALSE; - break; - } -} - -} // namespace ui
diff --git a/ui/base/ime/win/imm32_manager.h b/ui/base/ime/win/imm32_manager.h deleted file mode 100644 index 3a969fd..0000000 --- a/ui/base/ime/win/imm32_manager.h +++ /dev/null
@@ -1,330 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_WIN_IMM32_MANAGER_H -#define UI_BASE_IME_WIN_IMM32_MANAGER_H - -#include <windows.h> - -#include <string> -#include <vector> - -#include "base/basictypes.h" -#include "base/i18n/rtl.h" -#include "base/strings/string16.h" -#include "ui/base/ime/text_input_mode.h" -#include "ui/base/ui_base_export.h" -#include "ui/gfx/rect.h" - -namespace ui { - -struct CompositionText; - -// This header file defines a struct and a class used for encapsulating IMM32 -// APIs, controls IMEs attached to a window, and enables the 'on-the-spot' -// input without deep knowledge about the APIs, i.e. knowledge about the -// language-specific and IME-specific behaviors. -// The following items enumerates the simplest steps for an (window) -// application to control its IMEs with the struct and the class defined -// this file. -// 1. Add an instance of the IMM32Manager class to its window class. -// (The IMM32Manager class needs a window handle.) -// 2. Add messages handlers listed in the following subsections, follow the -// instructions written in each subsection, and use the IMM32Manager class. -// 2.1. WM_IME_SETCONTEXT (0x0281) -// Call the functions listed below: -// - IMM32Manager::CreateImeWindow(); -// - IMM32Manager::CleanupComposition(), and; -// - IMM32Manager::SetImeWindowStyle(). -// An application MUST prevent from calling ::DefWindowProc(). -// 2.2. WM_IME_STARTCOMPOSITION (0x010D) -// Call the functions listed below: -// - IMM32Manager::CreateImeWindow(), and; -// - IMM32Manager::ResetComposition(). -// An application MUST prevent from calling ::DefWindowProc(). -// 2.3. WM_IME_COMPOSITION (0x010F) -// Call the functions listed below: -// - IMM32Manager::UpdateImeWindow(); -// - IMM32Manager::GetResult(); -// - IMM32Manager::GetComposition(), and; -// - IMM32Manager::ResetComposition() (optional). -// An application MUST prevent from calling ::DefWindowProc(). -// 2.4. WM_IME_ENDCOMPOSITION (0x010E) -// Call the functions listed below: -// - IMM32Manager::ResetComposition(), and; -// - IMM32Manager::DestroyImeWindow(). -// An application CAN call ::DefWindowProc(). -// 2.5. WM_INPUTLANGCHANGE (0x0051) -// Call the functions listed below: -// - IMM32Manager::SetInputLanguage(). -// An application CAN call ::DefWindowProc(). - -// This class controls the IMM (Input Method Manager) through IMM32 APIs and -// enables it to retrieve the string being controled by the IMM. (I wrote -// a note to describe the reason why I do not use 'IME' but 'IMM' below.) -// NOTE(hbono): -// Fortunately or unfortunately, TSF (Text Service Framework) and -// CUAS (Cicero Unaware Application Support) allows IMM32 APIs for -// retrieving not only the inputs from IMEs (Input Method Editors), used -// only for inputting East-Asian language texts, but also the ones from -// tablets (on Windows XP Tablet PC Edition and Windows Vista), voice -// recognizers (e.g. ViaVoice and Microsoft Office), etc. -// We can disable TSF and CUAS in Windows XP Tablet PC Edition. On the other -// hand, we can NEVER disable either TSF or CUAS in Windows Vista, i.e. -// THIS CLASS IS NOT ONLY USED ON THE INPUT CONTEXTS OF EAST-ASIAN -// LANGUAGES BUT ALSO USED ON THE INPUT CONTEXTS OF ALL LANGUAGES. -class UI_BASE_EXPORT IMM32Manager { - public: - IMM32Manager(); - virtual ~IMM32Manager(); - - // Retrieves whether or not there is an ongoing composition. - bool is_composing() const { return is_composing_; } - - // Retrieves the input language from Windows and update it. - // Return values - // * true - // The given input language has IMEs. - // * false - // The given input language does not have IMEs. - bool SetInputLanguage(); - - // Creates the IME windows, and allocate required resources for them. - // Parameters - // * window_handle [in] (HWND) - // Represents the window handle of the caller. - void CreateImeWindow(HWND window_handle); - - // Updates the style of the IME windows. - // Parameters - // * window_handle [in] (HWND) - // Represents the window handle of the caller. - // * message [in] (UINT) - // * wparam [in] (WPARAM) - // * lparam [in] (LPARAM) - // Represent the windows message of the caller. - // These parameters are used for verifying if this function is called - // in a handler function for WM_IME_SETCONTEXT messages because this - // function uses ::DefWindowProc() to update the style. - // A caller just has to pass the input parameters for the handler - // function without modifications. - // * handled [out] (BOOL*) - // Returns ::DefWindowProc() is really called in this function. - // PLEASE DO NOT CALL ::DefWindowProc() IF THIS VALUE IS TRUE! - // All the window styles set in this function are over-written when - // calling ::DefWindowProc() after returning this function. - // Returns the value returned by DefWindowProc. - LRESULT SetImeWindowStyle(HWND window_handle, UINT message, - WPARAM wparam, LPARAM lparam, BOOL* handled); - - // Destroys the IME windows and all the resources attached to them. - // Parameters - // * window_handle [in] (HWND) - // Represents the window handle of the caller. - void DestroyImeWindow(HWND window_handle); - - // Updates the position of the IME windows. - // Parameters - // * window_handle [in] (HWND) - // Represents the window handle of the caller. - void UpdateImeWindow(HWND window_handle); - - // Cleans up the all resources attached to the given IMM32Manager object, and - // reset its composition status. - // Parameters - // * window_handle [in] (HWND) - // Represents the window handle of the caller. - void CleanupComposition(HWND window_handle); - - // Resets the composition status. - // Cancel the ongoing composition if it exists. - // NOTE(hbono): This method does not release the allocated resources. - // Parameters - // * window_handle [in] (HWND) - // Represents the window handle of the caller. - void ResetComposition(HWND window_handle); - - // Retrieves a composition result of the ongoing composition if it exists. - // Parameters - // * window_handle [in] (HWND) - // Represents the window handle of the caller. - // * lparam [in] (LPARAM) - // Specifies the updated members of the ongoing composition, and must be - // the same parameter of a WM_IME_COMPOSITION message handler. - // This parameter is used for checking if the ongoing composition has - // its result string, - // * result [out] (base::string16) - // Represents the object contains the composition result. - // Return values - // * true - // The ongoing composition has a composition result. - // * false - // The ongoing composition does not have composition results. - // Remarks - // This function is designed for being called from WM_IME_COMPOSITION - // message handlers. - bool GetResult(HWND window_handle, LPARAM lparam, base::string16* result); - - // Retrieves the current composition status of the ongoing composition. - // Parameters - // * window_handle [in] (HWND) - // Represents the window handle of the caller. - // * lparam [in] (LPARAM) - // Specifies the updated members of the ongoing composition, and must be - // the same parameter of a WM_IME_COMPOSITION message handler. - // This parameter is used for checking if the ongoing composition has - // its result string, - // * composition [out] (Composition) - // Represents the struct contains the composition status. - // Return values - // * true - // The status of the ongoing composition is updated. - // * false - // The status of the ongoing composition is not updated. - // Remarks - // This function is designed for being called from WM_IME_COMPOSITION - // message handlers. - bool GetComposition(HWND window_handle, LPARAM lparam, - CompositionText* composition); - - // Enables the IME attached to the given window, i.e. allows user-input - // events to be dispatched to the IME. - // Parameters - // * window_handle [in] (HWND) - // Represents the window handle of the caller. - // * complete [in] (bool) - // Represents whether or not to complete the ongoing composition. - // + true - // After finishing the ongoing composition and close its IME windows, - // start another composition and display its IME windows to the given - // position. - // + false - // Just move the IME windows of the ongoing composition to the given - // position without finishing it. - void EnableIME(HWND window_handle); - - // Disables the IME attached to the given window, i.e. prohibits any - // user-input events from being dispatched to the IME. - // In Chrome, this function is used when: - // * a renreder process sets its input focus to a password input. - // Parameters - // * window_handle [in] (HWND) - // Represents the window handle of the caller. - void DisableIME(HWND window_handle); - - // Cancels an ongoing composition of the IME attached to the given window. - // Parameters - // * window_handle [in] (HWND) - // Represents the window handle of the caller. - void CancelIME(HWND window_handle); - - // Updates the caret position of the given window. - // Parameters - // * window_handle [in] (HWND) - // Represents the window handle of the caller. - // * caret_rect [in] (const gfx::Rect&) - // Represent the rectangle of the input caret. - // This rectangle is used for controlling the positions of IME windows. - void UpdateCaretRect(HWND window_handle, const gfx::Rect& caret_rect); - - // Updates the setting whether we want IME to render composition text. - void SetUseCompositionWindow(bool use_composition_window); - - // Returns the current input language id. - LANGID input_language_id() const { return input_language_id_; } - - // Returns BCP-47 tag name of the current input language. - std::string GetInputLanguageName() const; - - // Sets conversion status corresponding to |input_mode|. - virtual void SetTextInputMode(HWND window_handle, TextInputMode input_mode); - - // Helper functions ---------------------------------------------------------- - - // Checks if there is any RTL keyboard layout installed in the system. - static bool IsRTLKeyboardLayoutInstalled(); - - // Checks if the user pressed both Ctrl and right or left Shift keys to - // requrest to change the text direction and layout alignment explicitly. - // Returns true if only a Ctrl key and a Shift key are down. The desired text - // direction will be stored in |*direction|. - static bool IsCtrlShiftPressed(base::i18n::TextDirection* direction); - - // Gets parameters for ::ImmSetOpenStatus and ::ImmSetConversionStatus from - // |input_mode|. - static void ConvertInputModeToImmFlags(TextInputMode input_mode, - DWORD initial_conversion_mode, - BOOL* open, - DWORD* new_conversion_mode); - - - protected: - // Retrieves the composition information. - void GetCompositionInfo(HIMC imm_context, LPARAM lparam, - CompositionText* composition); - - // Updates the position of the IME windows. - void MoveImeWindow(HWND window_handle, HIMC imm_context); - - // Completes the ongoing composition if it exists. - void CompleteComposition(HWND window_handle, HIMC imm_context); - - // Retrieves a string from the IMM. - bool GetString(HIMC imm_context, - WPARAM lparam, - int type, - base::string16* result); - - private: - // Represents whether or not there is an ongoing composition in a browser - // process, i.e. whether or not a browser process is composing a text. - bool is_composing_; - - // This value represents whether or not the current input context has IMEs. - // The following table shows the list of IME status: - // Value Description - // false The current input language does not have IMEs. - // true The current input language has IMEs. - bool ime_status_; - - // The current input Language ID retrieved from Windows, which consists of: - // * Primary Language ID (bit 0 to bit 9), which shows a natunal language - // (English, Korean, Chinese, Japanese, etc.) and; - // * Sub-Language ID (bit 10 to bit 15), which shows a geometrical region - // the language is spoken (For English, United States, United Kingdom, - // Australia, Canada, etc.) - // The following list enumerates some examples for the Language ID: - // * "en-US" (0x0409) - // MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US); - // * "ko-KR" (0x0412) - // MAKELANGID(LANG_KOREAN, SUBLANG_KOREAN); - // * "zh-TW" (0x0404) - // MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_TRADITIONAL); - // * "zh-CN" (0x0804) - // MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED); - // * "ja-JP" (0x0411) - // MAKELANGID(LANG_JAPANESE, SUBLANG_JAPANESE_JAPAN), etc. - // (See <winnt.h> for other available values.) - // This Language ID is used for processing language-specific operations in - // IME functions. - LANGID input_language_id_; - - // Represents whether or not the current input context has created a system - // caret to set the position of its IME candidate window. - // * true: it creates a system caret. - // * false: it does not create a system caret. - bool system_caret_; - - // The rectangle of the input caret retrieved from a renderer process. - gfx::Rect caret_rect_; - - // Indicates whether or not we want IME to render composition text. - bool use_composition_window_; - - DISALLOW_COPY_AND_ASSIGN(IMM32Manager); -}; - -} // namespace ui - -#endif // UI_BASE_IME_WIN_IMM32_MANAGER_H
diff --git a/ui/base/ime/win/imm32_manager_unittest.cc b/ui/base/ime/win/imm32_manager_unittest.cc deleted file mode 100644 index 0c73b03..0000000 --- a/ui/base/ime/win/imm32_manager_unittest.cc +++ /dev/null
@@ -1,92 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/win/imm32_manager.h" - -#include "testing/gtest/include/gtest/gtest.h" - -namespace ui { -namespace { - -struct InputModeTestCase { - TextInputMode input_mode; - DWORD conversion_mode; - BOOL expected_open; - DWORD expected_conversion_mode; -}; - -// Google Test pretty-printer. -void PrintTo(const InputModeTestCase& data, std::ostream* os) { - *os << " input_mode: " << testing::PrintToString(data.input_mode) - << "; conversion_mode: " << testing::PrintToString(data.conversion_mode); -} - -class IMM32ManagerTest - : public ::testing::TestWithParam<InputModeTestCase> { -}; - -const InputModeTestCase - kInputModeTestCases[] = { - {TEXT_INPUT_MODE_DEFAULT, 0, FALSE, 0}, - {TEXT_INPUT_MODE_DEFAULT, IME_CMODE_NATIVE, FALSE, IME_CMODE_NATIVE}, - {TEXT_INPUT_MODE_VERBATIM, 0, FALSE, 0}, - {TEXT_INPUT_MODE_VERBATIM, IME_CMODE_KATAKANA, FALSE, IME_CMODE_KATAKANA}, - {TEXT_INPUT_MODE_LATIN, 0, FALSE, 0}, - {TEXT_INPUT_MODE_LATIN, IME_CMODE_NATIVE, FALSE, IME_CMODE_NATIVE}, - {TEXT_INPUT_MODE_LATIN_NAME, 0, FALSE, 0}, - {TEXT_INPUT_MODE_LATIN_NAME, IME_CMODE_NATIVE, FALSE, IME_CMODE_NATIVE}, - {TEXT_INPUT_MODE_LATIN_PROSE, 0, FALSE, 0}, - {TEXT_INPUT_MODE_LATIN_PROSE, IME_CMODE_NATIVE, FALSE, IME_CMODE_NATIVE}, - {TEXT_INPUT_MODE_FULL_WIDTH_LATIN, - IME_CMODE_NATIVE | IME_CMODE_KATAKANA | IME_CMODE_FULLSHAPE, - TRUE, - IME_CMODE_FULLSHAPE}, - {TEXT_INPUT_MODE_KANA, - 0, - TRUE, - IME_CMODE_NATIVE | IME_CMODE_FULLSHAPE}, - {TEXT_INPUT_MODE_KANA, - IME_CMODE_ROMAN, - TRUE, - IME_CMODE_NATIVE | IME_CMODE_FULLSHAPE | IME_CMODE_ROMAN}, - {TEXT_INPUT_MODE_KATAKANA, - IME_CMODE_NATIVE | IME_CMODE_FULLSHAPE, - TRUE, - IME_CMODE_NATIVE | IME_CMODE_KATAKANA | IME_CMODE_FULLSHAPE}, - {TEXT_INPUT_MODE_KATAKANA, - IME_CMODE_NATIVE | IME_CMODE_FULLSHAPE | IME_CMODE_ROMAN, - TRUE, - IME_CMODE_NATIVE | IME_CMODE_KATAKANA | IME_CMODE_FULLSHAPE - | IME_CMODE_ROMAN}, - {TEXT_INPUT_MODE_NUMERIC, 0, FALSE, 0}, - {TEXT_INPUT_MODE_NUMERIC, IME_CMODE_FULLSHAPE, FALSE, IME_CMODE_FULLSHAPE}, - {TEXT_INPUT_MODE_TEL, 0, FALSE, 0}, - {TEXT_INPUT_MODE_TEL, IME_CMODE_ROMAN, FALSE, IME_CMODE_ROMAN}, - {TEXT_INPUT_MODE_EMAIL, 0, FALSE, 0}, - {TEXT_INPUT_MODE_EMAIL, IME_CMODE_CHARCODE, FALSE, IME_CMODE_CHARCODE}, - {TEXT_INPUT_MODE_URL, 0, FALSE, 0}, - {TEXT_INPUT_MODE_URL, IME_CMODE_HANJACONVERT, FALSE, IME_CMODE_HANJACONVERT}, -}; - -TEST_P(IMM32ManagerTest, ConvertInputModeToImmFlags) { - const InputModeTestCase& test_case = GetParam(); - - BOOL open; - DWORD conversion_mode; - // Call testee method. - IMM32Manager::ConvertInputModeToImmFlags(test_case.input_mode, - test_case.conversion_mode, - &open, - &conversion_mode); - - EXPECT_EQ(test_case.expected_open, open); - EXPECT_EQ(test_case.expected_conversion_mode, conversion_mode); -} - -INSTANTIATE_TEST_CASE_P(, - IMM32ManagerTest, - ::testing::ValuesIn(kInputModeTestCases)); - -} // namespace -} // namespace ui
diff --git a/ui/base/ime/win/tsf_input_scope.cc b/ui/base/ime/win/tsf_input_scope.cc deleted file mode 100644 index 1c248f1..0000000 --- a/ui/base/ime/win/tsf_input_scope.cc +++ /dev/null
@@ -1,217 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/win/tsf_input_scope.h" - -#include <algorithm> - -#include "base/compiler_specific.h" -#include "base/logging.h" -#include "base/message_loop/message_loop.h" -#include "base/win/windows_version.h" - -namespace ui { -namespace tsf_inputscope { -namespace { - -void AppendNonTrivialInputScope(std::vector<InputScope>* input_scopes, - InputScope input_scope) { - DCHECK(input_scopes); - - if (input_scope == IS_DEFAULT) - return; - - if (std::find(input_scopes->begin(), input_scopes->end(), input_scope) != - input_scopes->end()) - return; - - input_scopes->push_back(input_scope); -} - -class TSFInputScope final : public ITfInputScope { - public: - explicit TSFInputScope(const std::vector<InputScope>& input_scopes) - : input_scopes_(input_scopes), - ref_count_(0) {} - - // ITfInputScope: - STDMETHOD_(ULONG, AddRef)() override { - return InterlockedIncrement(&ref_count_); - } - - STDMETHOD_(ULONG, Release)() override { - const LONG count = InterlockedDecrement(&ref_count_); - if (!count) { - delete this; - return 0; - } - return static_cast<ULONG>(count); - } - - STDMETHOD(QueryInterface)(REFIID iid, void** result) override { - if (!result) - return E_INVALIDARG; - if (iid == IID_IUnknown || iid == IID_ITfInputScope) { - *result = static_cast<ITfInputScope*>(this); - } else { - *result = NULL; - return E_NOINTERFACE; - } - AddRef(); - return S_OK; - } - - STDMETHOD(GetInputScopes)(InputScope** input_scopes, UINT* count) override { - if (!count || !input_scopes) - return E_INVALIDARG; - *input_scopes = static_cast<InputScope*>(CoTaskMemAlloc( - sizeof(InputScope) * input_scopes_.size())); - if (!input_scopes) { - *count = 0; - return E_OUTOFMEMORY; - } - - for (size_t i = 0; i < input_scopes_.size(); ++i) - (*input_scopes)[i] = input_scopes_[i]; - *count = input_scopes_.size(); - return S_OK; - } - - STDMETHOD(GetPhrase)(BSTR** phrases, UINT* count) override { - return E_NOTIMPL; - } - - STDMETHOD(GetRegularExpression)(BSTR* regexp) override { - return E_NOTIMPL; - } - - STDMETHOD(GetSRGS)(BSTR* srgs) override { - return E_NOTIMPL; - } - - STDMETHOD(GetXML)(BSTR* xml) override { - return E_NOTIMPL; - } - - private: - // The corresponding text input types. - std::vector<InputScope> input_scopes_; - - // The refrence count of this instance. - volatile LONG ref_count_; - - DISALLOW_COPY_AND_ASSIGN(TSFInputScope); -}; - -typedef HRESULT (WINAPI *SetInputScopesFunc)(HWND window_handle, - const InputScope* input_scope_list, - UINT num_input_scopes, - WCHAR**, /* unused */ - UINT, /* unused */ - WCHAR*, /* unused */ - WCHAR* /* unused */); - -SetInputScopesFunc g_set_input_scopes = NULL; -bool g_get_proc_done = false; - -SetInputScopesFunc GetSetInputScopes() { - DCHECK(base::MessageLoopForUI::IsCurrent()); - // Thread safety is not required because this function is under UI thread. - if (!g_get_proc_done) { - g_get_proc_done = true; - - // For stability reasons, we do not support Windows XP. - if (base::win::GetVersion() < base::win::VERSION_VISTA) - return NULL; - - HMODULE module = NULL; - if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_PIN, L"msctf.dll", - &module)) { - return NULL; - } - g_set_input_scopes = reinterpret_cast<SetInputScopesFunc>( - GetProcAddress(module, "SetInputScopes")); - } - return g_set_input_scopes; -} - -InputScope ConvertTextInputTypeToInputScope(TextInputType text_input_type) { - // Following mapping is based in IE10 on Windows 8. - switch (text_input_type) { - case TEXT_INPUT_TYPE_PASSWORD: - return IS_PASSWORD; - case TEXT_INPUT_TYPE_SEARCH: - return IS_SEARCH; - case TEXT_INPUT_TYPE_EMAIL: - return IS_EMAIL_SMTPEMAILADDRESS; - case TEXT_INPUT_TYPE_NUMBER: - return IS_NUMBER; - case TEXT_INPUT_TYPE_TELEPHONE: - return IS_TELEPHONE_FULLTELEPHONENUMBER; - case TEXT_INPUT_TYPE_URL: - return IS_URL; - default: - return IS_DEFAULT; - } -} - -InputScope ConvertTextInputModeToInputScope(TextInputMode text_input_mode) { - switch (text_input_mode) { - case TEXT_INPUT_MODE_FULL_WIDTH_LATIN: - return IS_ALPHANUMERIC_FULLWIDTH; - case TEXT_INPUT_MODE_KANA: - return IS_HIRAGANA; - case TEXT_INPUT_MODE_KATAKANA: - return IS_KATAKANA_FULLWIDTH; - case TEXT_INPUT_MODE_NUMERIC: - return IS_NUMBER; - case TEXT_INPUT_MODE_TEL: - return IS_TELEPHONE_FULLTELEPHONENUMBER; - case TEXT_INPUT_MODE_EMAIL: - return IS_EMAIL_SMTPEMAILADDRESS; - case TEXT_INPUT_MODE_URL: - return IS_URL; - default: - return IS_DEFAULT; - } -} - -} // namespace - -std::vector<InputScope> GetInputScopes(TextInputType text_input_type, - TextInputMode text_input_mode) { - std::vector<InputScope> input_scopes; - - AppendNonTrivialInputScope(&input_scopes, - ConvertTextInputTypeToInputScope(text_input_type)); - AppendNonTrivialInputScope(&input_scopes, - ConvertTextInputModeToInputScope(text_input_mode)); - - if (input_scopes.empty()) - input_scopes.push_back(IS_DEFAULT); - - return input_scopes; -} - -ITfInputScope* CreateInputScope(TextInputType text_input_type, - TextInputMode text_input_mode) { - return new TSFInputScope(GetInputScopes(text_input_type, text_input_mode)); -} - -void SetInputScopeForTsfUnawareWindow( - HWND window_handle, - TextInputType text_input_type, - TextInputMode text_input_mode) { - SetInputScopesFunc set_input_scopes = GetSetInputScopes(); - if (!set_input_scopes) - return; - - std::vector<InputScope> input_scopes = GetInputScopes(text_input_type, - text_input_mode); - set_input_scopes(window_handle, &input_scopes[0], input_scopes.size(), NULL, - 0, NULL, NULL); -} - -} // namespace tsf_inputscope -} // namespace ui
diff --git a/ui/base/ime/win/tsf_input_scope.h b/ui/base/ime/win/tsf_input_scope.h deleted file mode 100644 index 536d395..0000000 --- a/ui/base/ime/win/tsf_input_scope.h +++ /dev/null
@@ -1,48 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_IME_WIN_TSF_INPUT_SCOPE_H_ -#define UI_BASE_IME_WIN_TSF_INPUT_SCOPE_H_ - -#include <InputScope.h> -#include <Windows.h> -#include <vector> - -#include "base/basictypes.h" -#include "ui/base/ime/text_input_mode.h" -#include "ui/base/ime/text_input_type.h" -#include "ui/base/ui_base_export.h" - -namespace ui { -namespace tsf_inputscope { - -// Returns InputScope list corresoponding to ui::TextInputType and -// ui::TextInputMode. -// This function is only used from following functions but declared for test. -UI_BASE_EXPORT std::vector<InputScope> GetInputScopes( - TextInputType text_input_type, - TextInputMode text_input_mode); - -// Returns an instance of ITfInputScope, which is the Windows-specific -// category representation corresponding to ui::TextInputType and -// ui::TextInputMode that we are using to specify the expected text type -// in the target field. -// The returned instance has 0 reference count. The caller must maintain its -// reference count. -UI_BASE_EXPORT ITfInputScope* CreateInputScope(TextInputType text_input_type, - TextInputMode text_input_mode); - -// A wrapper of the SetInputScopes API exported by msctf.dll. -// http://msdn.microsoft.com/en-us/library/windows/desktop/ms629026.aspx -// Does nothing on Windows XP in case TSF is disabled. -// NOTE: For TSF-aware window, you should use ITfInputScope instead. -UI_BASE_EXPORT void SetInputScopeForTsfUnawareWindow( - HWND window_handle, - TextInputType text_input_type, - TextInputMode text_input_mode); - -} // namespace tsf_inputscope -} // namespace ui - -#endif // UI_BASE_IME_WIN_TSF_INPUT_SCOPE_H_
diff --git a/ui/base/ime/win/tsf_input_scope_unittest.cc b/ui/base/ime/win/tsf_input_scope_unittest.cc deleted file mode 100644 index de6ede1..0000000 --- a/ui/base/ime/win/tsf_input_scope_unittest.cc +++ /dev/null
@@ -1,121 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/ime/win/tsf_input_scope.h" - -#include <InputScope.h> - -#include "testing/gtest/include/gtest/gtest.h" - -namespace ui { -namespace { - -struct GetInputScopesTestCase { - TextInputType input_type; - TextInputMode input_mode; - size_t expected_size; - InputScope expected_input_scopes[2]; -}; - -// Google Test pretty-printer. -void PrintTo(const GetInputScopesTestCase& data, std::ostream* os) { - *os << " input_type: " << testing::PrintToString(data.input_type) - << "; input_mode: " << testing::PrintToString(data.input_mode); -} - -class TSFInputScopeTest - : public testing::TestWithParam<GetInputScopesTestCase> { -}; - -const GetInputScopesTestCase kGetInputScopesTestCases[] = { - // Test cases of TextInputType. - {TEXT_INPUT_TYPE_NONE, TEXT_INPUT_MODE_DEFAULT, - 1, {IS_DEFAULT}}, - {TEXT_INPUT_TYPE_TEXT, TEXT_INPUT_MODE_DEFAULT, - 1, {IS_DEFAULT}}, - {TEXT_INPUT_TYPE_PASSWORD, TEXT_INPUT_MODE_DEFAULT, - 1, {IS_PASSWORD}}, - {TEXT_INPUT_TYPE_SEARCH, TEXT_INPUT_MODE_DEFAULT, - 1, {IS_SEARCH}}, - {TEXT_INPUT_TYPE_EMAIL, TEXT_INPUT_MODE_DEFAULT, - 1, {IS_EMAIL_SMTPEMAILADDRESS}}, - {TEXT_INPUT_TYPE_NUMBER, TEXT_INPUT_MODE_DEFAULT, - 1, {IS_NUMBER}}, - {TEXT_INPUT_TYPE_TELEPHONE, TEXT_INPUT_MODE_DEFAULT, - 1, {IS_TELEPHONE_FULLTELEPHONENUMBER}}, - {TEXT_INPUT_TYPE_URL, TEXT_INPUT_MODE_DEFAULT, - 1, {IS_URL}}, - {TEXT_INPUT_TYPE_DATE, TEXT_INPUT_MODE_DEFAULT, - 1, {IS_DEFAULT}}, - {TEXT_INPUT_TYPE_DATE_TIME, TEXT_INPUT_MODE_DEFAULT, - 1, {IS_DEFAULT}}, - {TEXT_INPUT_TYPE_DATE_TIME_LOCAL, TEXT_INPUT_MODE_DEFAULT, - 1, {IS_DEFAULT}}, - {TEXT_INPUT_TYPE_MONTH, TEXT_INPUT_MODE_DEFAULT, - 1, {IS_DEFAULT}}, - {TEXT_INPUT_TYPE_TIME, TEXT_INPUT_MODE_DEFAULT, - 1, {IS_DEFAULT}}, - {TEXT_INPUT_TYPE_WEEK, TEXT_INPUT_MODE_DEFAULT, - 1, {IS_DEFAULT}}, - {TEXT_INPUT_TYPE_TEXT_AREA, TEXT_INPUT_MODE_DEFAULT, - 1, {IS_DEFAULT}}, - {TEXT_INPUT_TYPE_CONTENT_EDITABLE, TEXT_INPUT_MODE_DEFAULT, - 1, {IS_DEFAULT}}, - {TEXT_INPUT_TYPE_DATE_TIME_FIELD, TEXT_INPUT_MODE_DEFAULT, - 1, {IS_DEFAULT}}, - // Test cases of TextInputMode. - {TEXT_INPUT_TYPE_NONE, TEXT_INPUT_MODE_DEFAULT, - 1, {IS_DEFAULT}}, - {TEXT_INPUT_TYPE_NONE, TEXT_INPUT_MODE_VERBATIM, - 1, {IS_DEFAULT}}, - {TEXT_INPUT_TYPE_NONE, TEXT_INPUT_MODE_LATIN, - 1, {IS_DEFAULT}}, - {TEXT_INPUT_TYPE_NONE, TEXT_INPUT_MODE_LATIN_NAME, - 1, {IS_DEFAULT}}, - {TEXT_INPUT_TYPE_NONE, TEXT_INPUT_MODE_LATIN_PROSE, - 1, {IS_DEFAULT}}, - {TEXT_INPUT_TYPE_NONE, TEXT_INPUT_MODE_FULL_WIDTH_LATIN, - 1, {IS_ALPHANUMERIC_FULLWIDTH}}, - {TEXT_INPUT_TYPE_NONE, TEXT_INPUT_MODE_KANA, - 1, {IS_HIRAGANA}}, - {TEXT_INPUT_TYPE_NONE, TEXT_INPUT_MODE_KATAKANA, - 1, {IS_KATAKANA_FULLWIDTH}}, - {TEXT_INPUT_TYPE_NONE, TEXT_INPUT_MODE_NUMERIC, - 1, {IS_NUMBER}}, - {TEXT_INPUT_TYPE_NONE, TEXT_INPUT_MODE_TEL, - 1, {IS_TELEPHONE_FULLTELEPHONENUMBER}}, - {TEXT_INPUT_TYPE_NONE, TEXT_INPUT_MODE_EMAIL, - 1, {IS_EMAIL_SMTPEMAILADDRESS}}, - {TEXT_INPUT_TYPE_NONE, TEXT_INPUT_MODE_URL, - 1, {IS_URL}}, - // Mixed test cases. - {TEXT_INPUT_TYPE_SEARCH, TEXT_INPUT_MODE_KANA, - 2, {IS_SEARCH, IS_HIRAGANA}}, - {TEXT_INPUT_TYPE_EMAIL, TEXT_INPUT_MODE_EMAIL, - 1, {IS_EMAIL_SMTPEMAILADDRESS}}, - {TEXT_INPUT_TYPE_NUMBER, TEXT_INPUT_MODE_NUMERIC, - 1, {IS_NUMBER}}, - {TEXT_INPUT_TYPE_TELEPHONE, TEXT_INPUT_MODE_TEL, - 1, {IS_TELEPHONE_FULLTELEPHONENUMBER}}, - {TEXT_INPUT_TYPE_URL, TEXT_INPUT_MODE_URL, - 1, {IS_URL}}, -}; - -TEST_P(TSFInputScopeTest, GetInputScopes) { - const GetInputScopesTestCase& test_case = GetParam(); - - std::vector<InputScope> input_scopes = tsf_inputscope::GetInputScopes( - test_case.input_type, test_case.input_mode); - - EXPECT_EQ(test_case.expected_size, input_scopes.size()); - for (size_t i = 0; i < test_case.expected_size; ++i) - EXPECT_EQ(test_case.expected_input_scopes[i], input_scopes[i]); -} - -INSTANTIATE_TEST_CASE_P(, - TSFInputScopeTest, - ::testing::ValuesIn(kGetInputScopesTestCases)); - -} // namespace -} // namespace ui
diff --git a/ui/base/models/button_menu_item_model.cc b/ui/base/models/button_menu_item_model.cc deleted file mode 100644 index 83bd973..0000000 --- a/ui/base/models/button_menu_item_model.cc +++ /dev/null
@@ -1,135 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/models/button_menu_item_model.h" - -#include "ui/base/l10n/l10n_util.h" - -namespace ui { - -bool ButtonMenuItemModel::Delegate::IsItemForCommandIdDynamic( - int command_id) const { - return false; -} - -base::string16 ButtonMenuItemModel::Delegate::GetLabelForCommandId( - int command_id) const { - return base::string16(); -} - -bool ButtonMenuItemModel::Delegate::IsCommandIdEnabled(int command_id) const { - return true; -} - -bool ButtonMenuItemModel::Delegate::DoesCommandIdDismissMenu( - int command_id) const { - return true; -} - -struct ButtonMenuItemModel::Item { - int command_id; - ButtonType type; - base::string16 label; - int icon_idr; - bool part_of_group; -}; - -ButtonMenuItemModel::ButtonMenuItemModel( - int string_id, - ButtonMenuItemModel::Delegate* delegate) - : item_label_(l10n_util::GetStringUTF16(string_id)), - delegate_(delegate) { -} - -ButtonMenuItemModel::~ButtonMenuItemModel() { -} - -void ButtonMenuItemModel::AddGroupItemWithStringId( - int command_id, int string_id) { - Item item = { command_id, TYPE_BUTTON, l10n_util::GetStringUTF16(string_id), - -1, true }; - items_.push_back(item); -} - -void ButtonMenuItemModel::AddItemWithImage(int command_id, - int icon_idr) { - Item item = { command_id, TYPE_BUTTON, base::string16(), icon_idr, false }; - items_.push_back(item); -} - -void ButtonMenuItemModel::AddButtonLabel(int command_id, int string_id) { - Item item = { command_id, TYPE_BUTTON_LABEL, - l10n_util::GetStringUTF16(string_id), -1, false }; - items_.push_back(item); -} - -void ButtonMenuItemModel::AddSpace() { - Item item = { 0, TYPE_SPACE, base::string16(), -1, false }; - items_.push_back(item); -} - -int ButtonMenuItemModel::GetItemCount() const { - return static_cast<int>(items_.size()); -} - -ButtonMenuItemModel::ButtonType ButtonMenuItemModel::GetTypeAt( - int index) const { - return items_[index].type; -} - -int ButtonMenuItemModel::GetCommandIdAt(int index) const { - return items_[index].command_id; -} - -bool ButtonMenuItemModel::IsItemDynamicAt(int index) const { - if (delegate_) - return delegate_->IsItemForCommandIdDynamic(GetCommandIdAt(index)); - return false; -} - -base::string16 ButtonMenuItemModel::GetLabelAt(int index) const { - if (IsItemDynamicAt(index)) - return delegate_->GetLabelForCommandId(GetCommandIdAt(index)); - return items_[index].label; -} - -bool ButtonMenuItemModel::GetIconAt(int index, int* icon_idr) const { - if (items_[index].icon_idr == -1) - return false; - - *icon_idr = items_[index].icon_idr; - return true; -} - -bool ButtonMenuItemModel::PartOfGroup(int index) const { - return items_[index].part_of_group; -} - -void ButtonMenuItemModel::ActivatedCommand(int command_id) { - if (delegate_) - delegate_->ExecuteCommand(command_id, 0); -} - -bool ButtonMenuItemModel::IsEnabledAt(int index) const { - return IsCommandIdEnabled(items_[index].command_id); -} - -bool ButtonMenuItemModel::DismissesMenuAt(int index) const { - return DoesCommandIdDismissMenu(items_[index].command_id); -} - -bool ButtonMenuItemModel::IsCommandIdEnabled(int command_id) const { - if (delegate_) - return delegate_->IsCommandIdEnabled(command_id); - return true; -} - -bool ButtonMenuItemModel::DoesCommandIdDismissMenu(int command_id) const { - if (delegate_) - return delegate_->DoesCommandIdDismissMenu(command_id); - return true; -} - - -} // namespace ui
diff --git a/ui/base/models/button_menu_item_model.h b/ui/base/models/button_menu_item_model.h deleted file mode 100644 index b0bc95b..0000000 --- a/ui/base/models/button_menu_item_model.h +++ /dev/null
@@ -1,113 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_MODELS_BUTTON_MENU_ITEM_MODEL_H_ -#define UI_BASE_MODELS_BUTTON_MENU_ITEM_MODEL_H_ - -#include <vector> - -#include "base/strings/string16.h" -#include "ui/base/ui_base_export.h" - -namespace ui { - -// A model representing the rows of buttons that should be inserted in a button -// containing menu item. -class UI_BASE_EXPORT ButtonMenuItemModel { - public: - // Types of buttons. - enum ButtonType { - TYPE_SPACE, - TYPE_BUTTON, - TYPE_BUTTON_LABEL - }; - - class UI_BASE_EXPORT Delegate { - public: - // Some command ids have labels that change over time. - virtual bool IsItemForCommandIdDynamic(int command_id) const; - virtual base::string16 GetLabelForCommandId(int command_id) const; - - // Performs the action associated with the specified command id. - virtual void ExecuteCommand(int command_id, int event_flags) = 0; - virtual bool IsCommandIdEnabled(int command_id) const; - virtual bool DoesCommandIdDismissMenu(int command_id) const; - - protected: - virtual ~Delegate() {} - }; - - ButtonMenuItemModel(int string_id, ButtonMenuItemModel::Delegate* delegate); - ~ButtonMenuItemModel(); - - // Adds a button that will emit |command_id|. All buttons created through - // this method will have the same size, based on the largest button. - void AddGroupItemWithStringId(int command_id, int string_id); - - // Adds a button that has an icon instead of a label. - void AddItemWithImage(int command_id, int icon_idr); - - // Adds a non-clickable button with a desensitized label that doesn't do - // anything. Usually combined with IsItemForCommandIdDynamic() to add - // information. - void AddButtonLabel(int command_id, int string_id); - - // Adds a small horizontal space. - void AddSpace(); - - // Returns the number of items for iteration. - int GetItemCount() const; - - // Returns what kind of item is at |index|. - ButtonType GetTypeAt(int index) const; - - // Changes a position into a command ID. - int GetCommandIdAt(int index) const; - - // Whether the label for item |index| changes. - bool IsItemDynamicAt(int index) const; - - // Returns the current label value for the button at |index|. - base::string16 GetLabelAt(int index) const; - - // If the button at |index| should have an icon instead, returns true and - // sets the IDR |icon|. - bool GetIconAt(int index, int* icon) const; - - // If the button at |index| should have its size equalized along with all - // other items that have their PartOfGroup bit set. - bool PartOfGroup(int index) const; - - // Called from implementations. - void ActivatedCommand(int command_id); - - // Returns the enabled state of the button at |index|. - bool IsEnabledAt(int index) const; - - // Returns whether clicking on the button at |index| dismisses the menu. - bool DismissesMenuAt(int index) const; - - // Returns the enabled state of the command specified by |command_id|. - bool IsCommandIdEnabled(int command_id) const; - - // Returns whether clicking on |command_id| dismisses the menu. - bool DoesCommandIdDismissMenu(int command_id) const; - - const base::string16& label() const { return item_label_; } - - private: - // The non-clickable label to the left of the buttons. - base::string16 item_label_; - - struct Item; - std::vector<Item> items_; - - Delegate* delegate_; - - DISALLOW_COPY_AND_ASSIGN(ButtonMenuItemModel); -}; - -} // namespace ui - -#endif // UI_BASE_MODELS_BUTTON_MENU_ITEM_MODEL_H_
diff --git a/ui/base/models/combobox_model.cc b/ui/base/models/combobox_model.cc deleted file mode 100644 index c6913da..0000000 --- a/ui/base/models/combobox_model.cc +++ /dev/null
@@ -1,21 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/models/combobox_model.h" - -namespace ui { - -bool ComboboxModel::IsItemSeparatorAt(int index) { - return false; -} - -int ComboboxModel::GetDefaultIndex() const { - return 0; -} - -bool ComboboxModel::IsItemEnabledAt(int index) const { - return true; -} - -} // namespace ui
diff --git a/ui/base/models/combobox_model.h b/ui/base/models/combobox_model.h deleted file mode 100644 index 3618109..0000000 --- a/ui/base/models/combobox_model.h +++ /dev/null
@@ -1,45 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_MODELS_COMBOBOX_MODEL_H_ -#define UI_BASE_MODELS_COMBOBOX_MODEL_H_ - -#include "base/strings/string16.h" -#include "ui/base/ui_base_export.h" - -namespace ui { - -class ComboboxModelObserver; - -// A data model for a combo box. -class UI_BASE_EXPORT ComboboxModel { - public: - // Returns the number of items in the combo box. - virtual int GetItemCount() const = 0; - - // Returns the string at the specified index. - virtual base::string16 GetItemAt(int index) = 0; - - // Should return true if the item at |index| is a non-selectable separator - // item. - virtual bool IsItemSeparatorAt(int index); - - // The index of the item that is selected by default (before user - // interaction). - virtual int GetDefaultIndex() const; - - // Returns true if the item at |index| is enabled. - virtual bool IsItemEnabledAt(int index) const; - - // Adds/removes an observer. Override if model supports mutation. - virtual void AddObserver(ComboboxModelObserver* observer) {} - virtual void RemoveObserver(ComboboxModelObserver* observer) {} - - protected: - virtual ~ComboboxModel() {} -}; - -} // namespace ui - -#endif // UI_BASE_MODELS_COMBOBOX_MODEL_H_
diff --git a/ui/base/models/combobox_model_observer.h b/ui/base/models/combobox_model_observer.h deleted file mode 100644 index f8e281e..0000000 --- a/ui/base/models/combobox_model_observer.h +++ /dev/null
@@ -1,27 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_MODELS_COMBOBOX_MODEL_OBSERVER_H_ -#define UI_BASE_MODELS_COMBOBOX_MODEL_OBSERVER_H_ - -#include "ui/base/ui_base_export.h" - -namespace ui { - -class ComboboxModel; - -// Observer for the ComboboxModel. -class UI_BASE_EXPORT ComboboxModelObserver { - public: - // Invoked when |model| has changed in some way. The observer should assume - // everything changed. - virtual void OnComboboxModelChanged(ComboboxModel* model) = 0; - - protected: - virtual ~ComboboxModelObserver() {} -}; - -} // namespace ui - -#endif // UI_BASE_MODELS_COMBOBOX_MODEL_OBSERVER_H_
diff --git a/ui/base/models/dialog_model.cc b/ui/base/models/dialog_model.cc deleted file mode 100644 index 310bff0..0000000 --- a/ui/base/models/dialog_model.cc +++ /dev/null
@@ -1,12 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/models/dialog_model.h" - -namespace ui { - -DialogModel::~DialogModel() { -} - -} // namespace ui
diff --git a/ui/base/models/dialog_model.h b/ui/base/models/dialog_model.h deleted file mode 100644 index 853eb28..0000000 --- a/ui/base/models/dialog_model.h +++ /dev/null
@@ -1,52 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_MODELS_DIALOG_MODEL_H_ -#define UI_BASE_MODELS_DIALOG_MODEL_H_ - -#include "base/strings/string16.h" -#include "ui/base/ui_base_export.h" -#include "ui/base/ui_base_types.h" - -namespace ui { - -// A model representing a dialog window. The model provides the content to show -// to the user (i.e. label, title), and the ways the user can interact with it -// (i.e. the buttons). -class UI_BASE_EXPORT DialogModel { - public: - virtual ~DialogModel(); - - // Returns the text of show in the dialog. - virtual base::string16 GetDialogLabel() const = 0; - - // Returns the title of the dialog. - virtual base::string16 GetDialogTitle() const = 0; - - // Returns a mask specifying which of the available DialogButtons are visible - // for the dialog. Note: Dialogs with just an OK button are frowned upon. - virtual int GetDialogButtons() const = 0; - - // Returns the default dialog button. This should not be a mask as only - // one button should ever be the default button. Return - // ui::DIALOG_BUTTON_NONE if there is no default. Default - // behavior is to return ui::DIALOG_BUTTON_OK or - // ui::DIALOG_BUTTON_CANCEL (in that order) if they are - // present, ui::DIALOG_BUTTON_NONE otherwise. - virtual int GetDefaultDialogButton() const = 0; - - // Returns whether the default dialog button should be colored blue as a call - // to action. - virtual bool ShouldDefaultButtonBeBlue() const = 0; - - // Returns the label of the specified dialog button. - virtual base::string16 GetDialogButtonLabel(DialogButton button) const = 0; - - // Returns whether the specified dialog button is enabled. - virtual bool IsDialogButtonEnabled(DialogButton button) const = 0; -}; - -} // namespace ui - -#endif // UI_BASE_MODELS_DIALOG_MODEL_H_
diff --git a/ui/base/models/list_model.h b/ui/base/models/list_model.h deleted file mode 100644 index 6955a8f..0000000 --- a/ui/base/models/list_model.h +++ /dev/null
@@ -1,134 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_MODELS_LIST_MODEL_H_ -#define UI_BASE_MODELS_LIST_MODEL_H_ - -#include "base/basictypes.h" -#include "base/logging.h" -#include "base/memory/scoped_ptr.h" -#include "base/memory/scoped_vector.h" -#include "base/observer_list.h" -#include "ui/base/models/list_model_observer.h" - -namespace ui { - -// A list model that manages a list of ItemType pointers. Items added to the -// model are owned by the model. An item can be taken out of the model by -// RemoveAt. -template <class ItemType> -class ListModel { - public: - ListModel() {} - ~ListModel() {} - - // Adds |item| at the |index| into |items_|. Takes ownership of |item|. - void AddAt(size_t index, ItemType* item) { - DCHECK_LE(index, item_count()); - items_.insert(items_.begin() + index, item); - NotifyItemsAdded(index, 1); - } - - // Convenience function to append an item to the model. - void Add(ItemType* item) { - AddAt(item_count(), item); - } - - // Removes the item at |index| from |items_| without deleting it. - // Returns a scoped pointer containing the removed item. - scoped_ptr<ItemType> RemoveAt(size_t index) { - DCHECK_LT(index, item_count()); - ItemType* item = items_[index]; - items_.weak_erase(items_.begin() + index); - NotifyItemsRemoved(index, 1); - return make_scoped_ptr<ItemType>(item); - } - - // Removes all items from the model. This does NOT delete the items. - void RemoveAll() { - size_t count = item_count(); - items_.weak_clear(); - NotifyItemsRemoved(0, count); - } - - // Removes the item at |index| from |items_| and deletes it. - void DeleteAt(size_t index) { - scoped_ptr<ItemType> item = RemoveAt(index); - // |item| will be deleted on destruction. - } - - // Removes and deletes all items from the model. - void DeleteAll() { - ScopedVector<ItemType> to_be_deleted(items_.Pass()); - NotifyItemsRemoved(0, to_be_deleted.size()); - } - - // Moves the item at |index| to |target_index|. |target_index| is in terms - // of the model *after* the item at |index| is removed. - void Move(size_t index, size_t target_index) { - DCHECK_LT(index, item_count()); - DCHECK_LT(target_index, item_count()); - - if (index == target_index) - return; - - ItemType* item = items_[index]; - items_.weak_erase(items_.begin() + index); - items_.insert(items_.begin() + target_index, item); - NotifyItemMoved(index, target_index); - } - - void AddObserver(ListModelObserver* observer) { - observers_.AddObserver(observer); - } - - void RemoveObserver(ListModelObserver* observer) { - observers_.RemoveObserver(observer); - } - - void NotifyItemsAdded(size_t start, size_t count) { - FOR_EACH_OBSERVER(ListModelObserver, - observers_, - ListItemsAdded(start, count)); - } - - void NotifyItemsRemoved(size_t start, size_t count) { - FOR_EACH_OBSERVER(ListModelObserver, - observers_, - ListItemsRemoved(start, count)); - } - - void NotifyItemMoved(size_t index, size_t target_index) { - FOR_EACH_OBSERVER(ListModelObserver, - observers_, - ListItemMoved(index, target_index)); - } - - void NotifyItemsChanged(size_t start, size_t count) { - FOR_EACH_OBSERVER(ListModelObserver, - observers_, - ListItemsChanged(start, count)); - } - - size_t item_count() const { return items_.size(); } - - const ItemType* GetItemAt(size_t index) const { - DCHECK_LT(index, item_count()); - return items_[index]; - } - ItemType* GetItemAt(size_t index) { - return const_cast<ItemType*>( - const_cast<const ListModel<ItemType>*>(this)->GetItemAt(index)); - } - - private: - ScopedVector<ItemType> items_; - ObserverList<ListModelObserver> observers_; - - DISALLOW_COPY_AND_ASSIGN(ListModel<ItemType>); -}; - -} // namespace ui - -#endif // UI_BASE_MODELS_LIST_MODEL_H_
diff --git a/ui/base/models/list_model_observer.h b/ui/base/models/list_model_observer.h deleted file mode 100644 index cc8be0f..0000000 --- a/ui/base/models/list_model_observer.h +++ /dev/null
@@ -1,36 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_MODELS_LIST_MODEL_OBSERVER_H_ -#define UI_BASE_MODELS_LIST_MODEL_OBSERVER_H_ - -#include <stddef.h> - -#include "ui/base/ui_base_export.h" - -namespace ui { - -class UI_BASE_EXPORT ListModelObserver { - public: - // Invoked after items has been added to the model. - virtual void ListItemsAdded(size_t start, size_t count) = 0; - - // Invoked after items has been removed. |start| is the index before the - // removal. - virtual void ListItemsRemoved(size_t start, size_t count) = 0; - - // Invoked after an item has been moved. See ListModel::Move() for details - // of the arguments. - virtual void ListItemMoved(size_t index, size_t target_index) = 0; - - // Invoked after items has been changed. - virtual void ListItemsChanged(size_t start, size_t count) = 0; - - protected: - virtual ~ListModelObserver() {} -}; - -} // namespace ui - -#endif // UI_BASE_MODELS_LIST_MODEL_OBSERVER_H_
diff --git a/ui/base/models/list_model_unittest.cc b/ui/base/models/list_model_unittest.cc deleted file mode 100644 index 8075a4a..0000000 --- a/ui/base/models/list_model_unittest.cc +++ /dev/null
@@ -1,174 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/models/list_model.h" - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace ui { - -class FooItem { - public: - explicit FooItem(int id) : id_(id) {} - - int id() const { return id_; } - - private: - int id_; - DISALLOW_COPY_AND_ASSIGN(FooItem); -}; - -class ListModelTest : public testing::Test, - public ListModelObserver { - public: - ListModelTest() - : added_count_(0), - removed_count_(0), - moved_count_(0), - changed_count_(0) { - } - - void ExpectCountsEqual(size_t added_count, - size_t removed_count, - size_t moved_count, - size_t changed_count) { - EXPECT_EQ(added_count, added_count_); - EXPECT_EQ(removed_count, removed_count_); - EXPECT_EQ(moved_count, moved_count_); - EXPECT_EQ(changed_count, changed_count_); - } - - void ClearCounts() { - added_count_ = removed_count_ = moved_count_ = changed_count_ = 0; - } - - // ListModelObserver implementation: - void ListItemsAdded(size_t start, size_t count) override { - added_count_ += count; - } - void ListItemsRemoved(size_t start, size_t count) override { - removed_count_ += count; - } - void ListItemMoved(size_t index, size_t target_index) override { - ++moved_count_; - } - void ListItemsChanged(size_t start, size_t count) override { - changed_count_ += count; - } - - private: - size_t added_count_; - size_t removed_count_; - size_t moved_count_; - size_t changed_count_; - - DISALLOW_COPY_AND_ASSIGN(ListModelTest); -}; - -TEST_F(ListModelTest, Add) { - ListModel<FooItem> model; - model.AddObserver(this); - - // Append FooItem(0) - model.Add(new FooItem(0)); - ExpectCountsEqual(1, 0, 0, 0); - - // Append FooItem(1) - model.Add(new FooItem(1)); - ExpectCountsEqual(2, 0, 0, 0); - - // Insert FooItem(2) at position 0 - model.AddAt(0, new FooItem(2)); - ExpectCountsEqual(3, 0, 0, 0); - - // Total 3 items in model. - EXPECT_EQ(3U, model.item_count()); - - // First one should be FooItem(2), followed by FooItem(0) and FooItem(1) - EXPECT_EQ(2, model.GetItemAt(0)->id()); - EXPECT_EQ(0, model.GetItemAt(1)->id()); - EXPECT_EQ(1, model.GetItemAt(2)->id()); -} - -TEST_F(ListModelTest, Remove) { - ListModel<FooItem> model; - model.AddObserver(this); - - model.Add(new FooItem(0)); - model.Add(new FooItem(1)); - model.Add(new FooItem(2)); - - ClearCounts(); - - // Remove item at index 1 from model and release memory. - model.DeleteAt(1); - ExpectCountsEqual(0, 1, 0, 0); - - EXPECT_EQ(2U, model.item_count()); - EXPECT_EQ(0, model.GetItemAt(0)->id()); - EXPECT_EQ(2, model.GetItemAt(1)->id()); - - // Remove all items from model and delete them. - model.DeleteAll(); - ExpectCountsEqual(0, 3, 0, 0); -} - -TEST_F(ListModelTest, RemoveAll) { - ListModel<FooItem> model; - model.AddObserver(this); - - scoped_ptr<FooItem> foo0(new FooItem(0)); - scoped_ptr<FooItem> foo1(new FooItem(1)); - scoped_ptr<FooItem> foo2(new FooItem(2)); - - model.Add(foo0.get()); - model.Add(foo1.get()); - model.Add(foo2.get()); - - ClearCounts(); - - // Remove all items and scoped_ptr above would release memory. - model.RemoveAll(); - ExpectCountsEqual(0, 3, 0, 0); -} - -TEST_F(ListModelTest, Move) { - ListModel<FooItem> model; - model.AddObserver(this); - - model.Add(new FooItem(0)); - model.Add(new FooItem(1)); - model.Add(new FooItem(2)); - - ClearCounts(); - - // Moves item at index 0 to index 2. - model.Move(0, 2); - ExpectCountsEqual(0, 0, 1, 0); - EXPECT_EQ(1, model.GetItemAt(0)->id()); - EXPECT_EQ(2, model.GetItemAt(1)->id()); - EXPECT_EQ(0, model.GetItemAt(2)->id()); -} - -TEST_F(ListModelTest, FakeUpdate) { - ListModel<FooItem> model; - model.AddObserver(this); - - model.Add(new FooItem(0)); - model.Add(new FooItem(1)); - model.Add(new FooItem(2)); - - ClearCounts(); - - model.NotifyItemsChanged(0, 1); - ExpectCountsEqual(0, 0, 0, 1); - - model.NotifyItemsChanged(1, 2); - ExpectCountsEqual(0, 0, 0, 3); -} - -} // namespace ui
diff --git a/ui/base/models/list_selection_model.cc b/ui/base/models/list_selection_model.cc deleted file mode 100644 index 5b9fc86..0000000 --- a/ui/base/models/list_selection_model.cc +++ /dev/null
@@ -1,153 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/models/list_selection_model.h" - -#include <algorithm> -#include <valarray> - -#include "base/logging.h" - -namespace ui { - -// static -const int ListSelectionModel::kUnselectedIndex = -1; - -static void IncrementFromImpl(int index, int* value) { - if (*value >= index) - (*value)++; -} - -static bool DecrementFromImpl(int index, int* value) { - if (*value == index) { - *value = ListSelectionModel::kUnselectedIndex; - return true; - } - if (*value > index) - (*value)--; - return false; -} - -ListSelectionModel::ListSelectionModel() - : active_(kUnselectedIndex), - anchor_(kUnselectedIndex) { -} - -ListSelectionModel::~ListSelectionModel() { -} - -void ListSelectionModel::IncrementFrom(int index) { - // Shift the selection to account for the newly inserted tab. - for (SelectedIndices::iterator i = selected_indices_.begin(); - i != selected_indices_.end(); ++i) { - IncrementFromImpl(index, &(*i)); - } - IncrementFromImpl(index, &anchor_); - IncrementFromImpl(index, &active_); -} - -void ListSelectionModel::DecrementFrom(int index) { - for (SelectedIndices::iterator i = selected_indices_.begin(); - i != selected_indices_.end(); ) { - if (DecrementFromImpl(index, &(*i))) - i = selected_indices_.erase(i); - else - ++i; - } - DecrementFromImpl(index, &anchor_); - DecrementFromImpl(index, &active_); -} - -void ListSelectionModel::SetSelectedIndex(int index) { - anchor_ = active_ = index; - selected_indices_.clear(); - if (index != kUnselectedIndex) - selected_indices_.push_back(index); -} - -bool ListSelectionModel::IsSelected(int index) const { - return std::find(selected_indices_.begin(), selected_indices_.end(), index) != - selected_indices_.end(); -} - -void ListSelectionModel::AddIndexToSelection(int index) { - if (!IsSelected(index)) { - selected_indices_.push_back(index); - std::sort(selected_indices_.begin(), selected_indices_.end()); - } -} - -void ListSelectionModel::RemoveIndexFromSelection(int index) { - SelectedIndices::iterator i = std::find(selected_indices_.begin(), - selected_indices_.end(), index); - if (i != selected_indices_.end()) - selected_indices_.erase(i); -} - -void ListSelectionModel::SetSelectionFromAnchorTo(int index) { - if (anchor_ == kUnselectedIndex) { - SetSelectedIndex(index); - } else { - int delta = std::abs(index - anchor_); - SelectedIndices new_selection(delta + 1, 0); - for (int i = 0, min = std::min(index, anchor_); i <= delta; ++i) - new_selection[i] = i + min; - selected_indices_.swap(new_selection); - active_ = index; - } -} - -void ListSelectionModel::AddSelectionFromAnchorTo(int index) { - if (anchor_ == kUnselectedIndex) { - SetSelectedIndex(index); - } else { - for (int i = std::min(index, anchor_), end = std::max(index, anchor_); - i <= end; ++i) { - if (!IsSelected(i)) - selected_indices_.push_back(i); - } - std::sort(selected_indices_.begin(), selected_indices_.end()); - active_ = index; - } -} - -void ListSelectionModel::Move(int from, int to) { - DCHECK_NE(to, from); - bool was_anchor = from == anchor_; - bool was_active = from == active_; - bool was_selected = IsSelected(from); - if (to < from) { - IncrementFrom(to); - DecrementFrom(from + 1); - } else { - DecrementFrom(from); - IncrementFrom(to); - } - if (was_active) - active_ = to; - if (was_anchor) - anchor_ = to; - if (was_selected) - AddIndexToSelection(to); -} - -void ListSelectionModel::Clear() { - anchor_ = active_ = kUnselectedIndex; - SelectedIndices empty_selection; - selected_indices_.swap(empty_selection); -} - -void ListSelectionModel::Copy(const ListSelectionModel& source) { - selected_indices_ = source.selected_indices_; - active_ = source.active_; - anchor_ = source.anchor_; -} - -bool ListSelectionModel::Equals(const ListSelectionModel& rhs) const { - return active_ == rhs.active() && - anchor_ == rhs.anchor() && - selected_indices() == rhs.selected_indices(); -} - -} // namespace ui
diff --git a/ui/base/models/list_selection_model.h b/ui/base/models/list_selection_model.h deleted file mode 100644 index 234714d..0000000 --- a/ui/base/models/list_selection_model.h +++ /dev/null
@@ -1,116 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_MODELS_LIST_SELECTION_MODEL_H_ -#define UI_BASE_MODELS_LIST_SELECTION_MODEL_H_ - -#include <vector> - -#include "base/basictypes.h" -#include "ui/base/ui_base_export.h" - -namespace ui { - -// Selection model represented as a list of ints. Used by the TabStrip. In -// addition to the set of selected indices ListSelectionModel maintains the -// following: -// active: the index of the currently visible tab in the tab strip. -// anchor: the index of the last tab the user clicked on. Extending the -// selection extends it from this index. -// -// Typically there is only one selected item, in which case the anchor and -// active index correspond to the same thing. -class UI_BASE_EXPORT ListSelectionModel { - public: - typedef std::vector<int> SelectedIndices; - - // Used to identify no selection. - static const int kUnselectedIndex; - - ListSelectionModel(); - ~ListSelectionModel(); - - // See class description for details of the anchor. - void set_anchor(int anchor) { anchor_ = anchor; } - int anchor() const { return anchor_; } - - // See class description for details of active. - void set_active(int active) { active_ = active; } - int active() const { return active_; } - - // True if nothing is selected. - bool empty() const { return selected_indices_.empty(); } - - // Number of selected indices. - size_t size() const { return selected_indices_.size(); } - - // Increments all indices >= |index|. For example, if the selection consists - // of [0, 1, 5] and this is invoked with 1, it results in [0, 2, 6]. This also - // updates the anchor and active indices. - // This is used when a new tab is inserted into the tabstrip. - void IncrementFrom(int index); - - // Shifts all indices > |index| down by 1. If |index| is selected, it is - // removed. For example, if the selection consists of [0, 1, 5] and this is - // invoked with 1, it results in [0, 4]. This is used when a tab is removed - // from the tabstrip. - void DecrementFrom(int index); - - // Sets the anchor, active and selection to |index|. - void SetSelectedIndex(int index); - - // Returns true if |index| is selected. - bool IsSelected(int index) const; - - // Adds |index| to the selection. This does not change the active or anchor - // indices. - void AddIndexToSelection(int index); - - // Removes |index| from the selection. This does not change the active or - // anchor indices. - void RemoveIndexFromSelection(int index); - - // Extends the selection from the anchor to |index|. If the anchor is empty, - // this sets the anchor, selection and active indices to |index|. - void SetSelectionFromAnchorTo(int index); - - // Makes sure the indices from the anchor to |index| are selected. This only - // adds to the selection. - void AddSelectionFromAnchorTo(int index); - - // Invoked when an item moves. |from| is the original index, and |to| the - // target index. - // NOTE: this matches the TabStripModel API. If moving to a greater index, - // |to| should be the index *after* removing |from|. For example, consider - // three tabs 'A B C', to move A to the end of the list, this should be - // invoked with '0, 2'. - void Move(int from, int to); - - // Sets the anchor and active to kUnselectedIndex, and removes all the - // selected indices. - void Clear(); - - // Returns the selected indices. The selection is always ordered in acending - // order. - const SelectedIndices& selected_indices() const { return selected_indices_; } - - // Copies the selection from |source| to this. - void Copy(const ListSelectionModel& source); - - // Compares this selection with |rhs|. - bool Equals(const ListSelectionModel& rhs) const; - - private: - SelectedIndices selected_indices_; - - int active_; - - int anchor_; - - DISALLOW_COPY_AND_ASSIGN(ListSelectionModel); -}; - -} // namespace ui - -#endif // UI_BASE_MODELS_LIST_SELECTION_MODEL_H_
diff --git a/ui/base/models/list_selection_model_unittest.cc b/ui/base/models/list_selection_model_unittest.cc deleted file mode 100644 index 7f7a712..0000000 --- a/ui/base/models/list_selection_model_unittest.cc +++ /dev/null
@@ -1,197 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/models/list_selection_model.h" - -#include <algorithm> -#include <string> - -#include "base/strings/string_number_conversions.h" -#include "testing/gtest/include/gtest/gtest.h" - -namespace ui { - -typedef testing::Test ListSelectionModelTest; - -// Returns the state of the selection model as a string. The format is: -// 'active=X anchor=X selection=X X X...'. -static std::string StateAsString(const ListSelectionModel& model) { - std::string result = "active=" + base::IntToString(model.active()) + - " anchor=" + base::IntToString(model.anchor()) + - " selection="; - const ListSelectionModel::SelectedIndices& selection( - model.selected_indices()); - for (size_t i = 0; i < selection.size(); ++i) { - if (i != 0) - result += " "; - result += base::IntToString(selection[i]); - } - return result; -} - -TEST_F(ListSelectionModelTest, InitialState) { - ListSelectionModel model; - EXPECT_EQ("active=-1 anchor=-1 selection=", StateAsString(model)); - EXPECT_TRUE(model.empty()); -} - -TEST_F(ListSelectionModelTest, SetSelectedIndex) { - ListSelectionModel model; - model.SetSelectedIndex(2); - EXPECT_EQ("active=2 anchor=2 selection=2", StateAsString(model)); - EXPECT_FALSE(model.empty()); -} - -TEST_F(ListSelectionModelTest, SetSelectedIndexToEmpty) { - ListSelectionModel model; - model.SetSelectedIndex(-1); - EXPECT_EQ("active=-1 anchor=-1 selection=", StateAsString(model)); - EXPECT_TRUE(model.empty()); -} - -TEST_F(ListSelectionModelTest, IncrementFrom) { - ListSelectionModel model; - model.SetSelectedIndex(1); - model.IncrementFrom(1); - EXPECT_EQ("active=2 anchor=2 selection=2", StateAsString(model)); - - // Increment from 4. This shouldn't effect the selection as its past the - // end of the selection. - model.IncrementFrom(4); - EXPECT_EQ("active=2 anchor=2 selection=2", StateAsString(model)); -} - -TEST_F(ListSelectionModelTest, DecrementFrom) { - ListSelectionModel model; - model.SetSelectedIndex(2); - model.DecrementFrom(0); - EXPECT_EQ("active=1 anchor=1 selection=1", StateAsString(model)); - - // Shift down from 1. As the selection as the index being removed, this should - // clear the selection. - model.DecrementFrom(1); - EXPECT_EQ("active=-1 anchor=-1 selection=", StateAsString(model)); - - // Reset the selection to 2, and shift down from 4. This shouldn't do - // anything. - model.SetSelectedIndex(2); - model.DecrementFrom(4); - EXPECT_EQ("active=2 anchor=2 selection=2", StateAsString(model)); -} - -TEST_F(ListSelectionModelTest, IsSelected) { - ListSelectionModel model; - model.SetSelectedIndex(2); - EXPECT_FALSE(model.IsSelected(0)); - EXPECT_TRUE(model.IsSelected(2)); -} - -TEST_F(ListSelectionModelTest, AddIndexToSelected) { - ListSelectionModel model; - model.AddIndexToSelection(2); - EXPECT_EQ("active=-1 anchor=-1 selection=2", StateAsString(model)); - - model.AddIndexToSelection(4); - EXPECT_EQ("active=-1 anchor=-1 selection=2 4", StateAsString(model)); -} - -TEST_F(ListSelectionModelTest, RemoveIndexFromSelection) { - ListSelectionModel model; - model.SetSelectedIndex(2); - model.AddIndexToSelection(4); - EXPECT_EQ("active=2 anchor=2 selection=2 4", StateAsString(model)); - - model.RemoveIndexFromSelection(4); - EXPECT_EQ("active=2 anchor=2 selection=2", StateAsString(model)); - - model.RemoveIndexFromSelection(2); - EXPECT_EQ("active=2 anchor=2 selection=", StateAsString(model)); -} - -TEST_F(ListSelectionModelTest, SetSelectionFromAnchorTo) { - ListSelectionModel model; - model.SetSelectedIndex(2); - model.SetSelectionFromAnchorTo(7); - EXPECT_EQ("active=7 anchor=2 selection=2 3 4 5 6 7", StateAsString(model)); - - model.Clear(); - model.SetSelectedIndex(7); - model.SetSelectionFromAnchorTo(2); - EXPECT_EQ("active=2 anchor=7 selection=2 3 4 5 6 7", StateAsString(model)); - - model.Clear(); - model.SetSelectionFromAnchorTo(7); - EXPECT_EQ("active=7 anchor=7 selection=7", StateAsString(model)); -} - -TEST_F(ListSelectionModelTest, Clear) { - ListSelectionModel model; - model.SetSelectedIndex(2); - - model.Clear(); - EXPECT_EQ("active=-1 anchor=-1 selection=", StateAsString(model)); -} - -TEST_F(ListSelectionModelTest, MoveToLeft) { - ListSelectionModel model; - model.SetSelectedIndex(0); - model.AddIndexToSelection(4); - model.AddIndexToSelection(10); - model.set_anchor(4); - model.set_active(4); - model.Move(4, 0); - EXPECT_EQ("active=0 anchor=0 selection=0 1 10", StateAsString(model)); -} - -TEST_F(ListSelectionModelTest, MoveToRight) { - ListSelectionModel model; - model.SetSelectedIndex(0); - model.AddIndexToSelection(4); - model.AddIndexToSelection(10); - model.set_anchor(0); - model.set_active(0); - model.Move(0, 3); - EXPECT_EQ("active=3 anchor=3 selection=3 4 10", StateAsString(model)); -} - -TEST_F(ListSelectionModelTest, Copy) { - ListSelectionModel model; - model.SetSelectedIndex(0); - model.AddIndexToSelection(4); - model.AddIndexToSelection(10); - EXPECT_EQ("active=0 anchor=0 selection=0 4 10", StateAsString(model)); - ListSelectionModel model2; - model2.Copy(model); - EXPECT_EQ("active=0 anchor=0 selection=0 4 10", StateAsString(model2)); -} - -TEST_F(ListSelectionModelTest, AddSelectionFromAnchorTo) { - ListSelectionModel model; - model.SetSelectedIndex(2); - - model.AddSelectionFromAnchorTo(4); - EXPECT_EQ("active=4 anchor=2 selection=2 3 4", StateAsString(model)); - - model.AddSelectionFromAnchorTo(0); - EXPECT_EQ("active=0 anchor=2 selection=0 1 2 3 4", StateAsString(model)); -} - -TEST_F(ListSelectionModelTest, Equals) { - ListSelectionModel model1; - model1.SetSelectedIndex(0); - model1.AddSelectionFromAnchorTo(4); - - ListSelectionModel model2; - model2.SetSelectedIndex(0); - model2.AddSelectionFromAnchorTo(4); - - EXPECT_TRUE(model1.Equals(model2)); - EXPECT_TRUE(model2.Equals(model1)); - - model2.SetSelectedIndex(0); - EXPECT_FALSE(model1.Equals(model2)); - EXPECT_FALSE(model2.Equals(model1)); -} - -} // namespace ui
diff --git a/ui/base/models/menu_model.cc b/ui/base/models/menu_model.cc deleted file mode 100644 index 1b5f6ab..0000000 --- a/ui/base/models/menu_model.cc +++ /dev/null
@@ -1,52 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/models/menu_model.h" - -namespace ui { - -bool MenuModel::IsVisibleAt(int index) const { - return true; -} - -// static -bool MenuModel::GetModelAndIndexForCommandId(int command_id, - MenuModel** model, - int* index) { - const int item_count = (*model)->GetItemCount(); - for (int i = 0; i < item_count; ++i) { - const int candidate_index = i; - if ((*model)->GetTypeAt(candidate_index) == TYPE_SUBMENU) { - MenuModel* submenu_model = (*model)->GetSubmenuModelAt(candidate_index); - if (GetModelAndIndexForCommandId(command_id, &submenu_model, index)) { - *model = submenu_model; - return true; - } - } - if ((*model)->GetCommandIdAt(candidate_index) == command_id) { - *index = candidate_index; - return true; - } - } - return false; -} - -base::string16 MenuModel::GetSublabelAt(int index) const { - return base::string16(); -} - -base::string16 MenuModel::GetMinorTextAt(int index) const { - return base::string16(); -} - -const gfx::FontList* MenuModel::GetLabelFontListAt(int index) const { - return NULL; -} - -// Default implementation ignores the event flags. -void MenuModel::ActivatedAt(int index, int event_flags) { - ActivatedAt(index); -} - -} // namespace ui
diff --git a/ui/base/models/menu_model.h b/ui/base/models/menu_model.h deleted file mode 100644 index d0d3100..0000000 --- a/ui/base/models/menu_model.h +++ /dev/null
@@ -1,140 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_MODELS_MENU_MODEL_H_ -#define UI_BASE_MODELS_MENU_MODEL_H_ - -#include "base/strings/string16.h" -#include "ui/base/models/menu_model_delegate.h" -#include "ui/base/models/menu_separator_types.h" -#include "ui/base/ui_base_export.h" -#include "ui/gfx/image/image_skia.h" -#include "ui/gfx/native_widget_types.h" - -namespace gfx { -class FontList; -class Image; -} - -namespace ui { - -class Accelerator; -class ButtonMenuItemModel; - -// An interface implemented by an object that provides the content of a menu. -class UI_BASE_EXPORT MenuModel { - public: - // The type of item. - enum ItemType { - TYPE_COMMAND, - TYPE_CHECK, - TYPE_RADIO, - TYPE_SEPARATOR, - TYPE_BUTTON_ITEM, - TYPE_SUBMENU - }; - - virtual ~MenuModel() {} - - // Returns true if any of the items within the model have icons. Not all - // platforms support icons in menus natively and so this is a hint for - // triggering a custom rendering mode. - virtual bool HasIcons() const = 0; - - // Returns the number of items in the menu. - virtual int GetItemCount() const = 0; - - // Returns the type of item at the specified index. - virtual ItemType GetTypeAt(int index) const = 0; - - // Returns the separator type at the specified index. - virtual ui::MenuSeparatorType GetSeparatorTypeAt(int index) const = 0; - - // Returns the command id of the item at the specified index. - virtual int GetCommandIdAt(int index) const = 0; - - // Returns the label of the item at the specified index. - virtual base::string16 GetLabelAt(int index) const = 0; - - // Returns the sublabel of the item at the specified index. The sublabel - // is rendered beneath the label and using the font GetLabelFontAt(). - virtual base::string16 GetSublabelAt(int index) const; - - // Returns the minor text of the item at the specified index. The minor text - // is rendered to the right of the label and using the font GetLabelFontAt(). - virtual base::string16 GetMinorTextAt(int index) const; - - // Returns true if the menu item (label/sublabel/icon) at the specified - // index can change over the course of the menu's lifetime. If this function - // returns true, the label, sublabel and icon of the menu item will be - // updated each time the menu is shown. - virtual bool IsItemDynamicAt(int index) const = 0; - - // Returns the font list used for the label at the specified index. - // If NULL, then the default font list should be used. - virtual const gfx::FontList* GetLabelFontListAt(int index) const; - - // Gets the acclerator information for the specified index, returning true if - // there is a shortcut accelerator for the item, false otherwise. - virtual bool GetAcceleratorAt(int index, - ui::Accelerator* accelerator) const = 0; - - // Returns the checked state of the item at the specified index. - virtual bool IsItemCheckedAt(int index) const = 0; - - // Returns the id of the group of radio items that the item at the specified - // index belongs to. - virtual int GetGroupIdAt(int index) const = 0; - - // Gets the icon for the item at the specified index, returning true if there - // is an icon, false otherwise. - virtual bool GetIconAt(int index, gfx::Image* icon) = 0; - - // Returns the model for a menu item with a line of buttons at |index|. - virtual ButtonMenuItemModel* GetButtonMenuItemAt(int index) const = 0; - - // Returns the enabled state of the item at the specified index. - virtual bool IsEnabledAt(int index) const = 0; - - // Returns true if the menu item is visible. - virtual bool IsVisibleAt(int index) const; - - // Returns the model for the submenu at the specified index. - virtual MenuModel* GetSubmenuModelAt(int index) const = 0; - - // Called when the highlighted menu item changes to the item at the specified - // index. - virtual void HighlightChangedTo(int index) = 0; - - // Called when the item at the specified index has been activated. - virtual void ActivatedAt(int index) = 0; - - // Called when the item has been activated with given event flags. - // (for the case where the activation involves a navigation). - // |event_flags| is a bit mask of ui::EventFlags. - virtual void ActivatedAt(int index, int event_flags); - - // Called when the menu is about to be shown. - virtual void MenuWillShow() {} - - // Called when the menu has been closed. - virtual void MenuClosed() {} - - // Set the MenuModelDelegate. Owned by the caller of this function. - virtual void SetMenuModelDelegate(MenuModelDelegate* delegate) = 0; - - // Gets the MenuModelDelegate. - virtual MenuModelDelegate* GetMenuModelDelegate() const = 0; - - // Retrieves the model and index that contains a specific command id. Returns - // true if an item with the specified command id is found. |model| is inout, - // and specifies the model to start searching from. - static bool GetModelAndIndexForCommandId(int command_id, - MenuModel** model, - int* index); -}; - -} // namespace ui - -#endif // UI_BASE_MODELS_MENU_MODEL_H_
diff --git a/ui/base/models/menu_model_delegate.h b/ui/base/models/menu_model_delegate.h deleted file mode 100644 index 53b9579..0000000 --- a/ui/base/models/menu_model_delegate.h +++ /dev/null
@@ -1,25 +0,0 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_MODELS_MENU_MODEL_DELEGATE_H_ -#define UI_BASE_MODELS_MENU_MODEL_DELEGATE_H_ - -namespace ui { - -class MenuModelDelegate { - public: - // Invoked when an icon has been loaded from history. - virtual void OnIconChanged(int index) = 0; - - // Invoked after items in |MenuModel| have been removed and/or added, - // delegate should assume the entire contents of the model has changed. - virtual void OnMenuStructureChanged() {} - - protected: - virtual ~MenuModelDelegate() {} -}; - -} // namespace ui - -#endif // UI_BASE_MODELS_MENU_MODEL_DELEGATE_H_
diff --git a/ui/base/models/menu_separator_types.h b/ui/base/models/menu_separator_types.h deleted file mode 100644 index 32c573d..0000000 --- a/ui/base/models/menu_separator_types.h +++ /dev/null
@@ -1,27 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_MODELS_MENU_SEPARATOR_TYPES_H_ -#define UI_BASE_MODELS_MENU_SEPARATOR_TYPES_H_ - -namespace ui { - -// For a separator we have the following types. -enum MenuSeparatorType { - // Normal - top to bottom: Spacing, line, spacing - NORMAL_SEPARATOR, - - // Upper - top to bottom: Line, spacing - UPPER_SEPARATOR, - - // Lower - top to bottom: Spacing, line - LOWER_SEPARATOR, - - // Spacing - top to bottom: Spacing only. - SPACING_SEPARATOR -}; - -} // namespace ui - -#endif // UI_BASE_MODELS_MENU_SEPARATOR_TYPES_H_
diff --git a/ui/base/models/simple_combobox_model.cc b/ui/base/models/simple_combobox_model.cc deleted file mode 100644 index edf339d..0000000 --- a/ui/base/models/simple_combobox_model.cc +++ /dev/null
@@ -1,33 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/models/simple_combobox_model.h" - -namespace ui { - -SimpleComboboxModel::SimpleComboboxModel( - const std::vector<base::string16>& items) - : items_(items) { -} - -SimpleComboboxModel::~SimpleComboboxModel() { -} - -int SimpleComboboxModel::GetItemCount() const { - return items_.size(); -} - -base::string16 SimpleComboboxModel::GetItemAt(int index) { - return items_[index]; -} - -bool SimpleComboboxModel::IsItemSeparatorAt(int index) { - return items_[index].empty(); -} - -int SimpleComboboxModel::GetDefaultIndex() const { - return 0; -} - -} // namespace ui
diff --git a/ui/base/models/simple_combobox_model.h b/ui/base/models/simple_combobox_model.h deleted file mode 100644 index beaa04a..0000000 --- a/ui/base/models/simple_combobox_model.h +++ /dev/null
@@ -1,35 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_MODELS_SIMPLE_COMBOBOX_MODEL_H_ -#define UI_BASE_MODELS_SIMPLE_COMBOBOX_MODEL_H_ - -#include "ui/base/models/combobox_model.h" - -#include <vector> - -namespace ui { - -// A simple data model for a combobox that takes a string16 vector as the items. -// An empty string will be a separator. -class UI_BASE_EXPORT SimpleComboboxModel : public ComboboxModel { - public: - explicit SimpleComboboxModel(const std::vector<base::string16>& items); - ~SimpleComboboxModel() override; - - // ui::ComboboxModel: - int GetItemCount() const override; - base::string16 GetItemAt(int index) override; - bool IsItemSeparatorAt(int index) override; - int GetDefaultIndex() const override; - - private: - const std::vector<base::string16> items_; - - DISALLOW_COPY_AND_ASSIGN(SimpleComboboxModel); -}; - -} // namespace ui - -#endif // UI_BASE_MODELS_SIMPLE_COMBOBOX_MODEL_H_
diff --git a/ui/base/models/simple_menu_model.cc b/ui/base/models/simple_menu_model.cc deleted file mode 100644 index 336fd41..0000000 --- a/ui/base/models/simple_menu_model.cc +++ /dev/null
@@ -1,461 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/models/simple_menu_model.h" - -#include "base/bind.h" -#include "base/message_loop/message_loop.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/gfx/image/image.h" - -namespace ui { - -const int kSeparatorId = -1; - -struct SimpleMenuModel::Item { - int command_id; - base::string16 label; - base::string16 sublabel; - base::string16 minor_text; - gfx::Image icon; - ItemType type; - int group_id; - MenuModel* submenu; - ButtonMenuItemModel* button_model; - MenuSeparatorType separator_type; -}; - -//////////////////////////////////////////////////////////////////////////////// -// SimpleMenuModel::Delegate, public: - -bool SimpleMenuModel::Delegate::IsCommandIdVisible(int command_id) const { - return true; -} - -bool SimpleMenuModel::Delegate::IsItemForCommandIdDynamic( - int command_id) const { - return false; -} - -base::string16 SimpleMenuModel::Delegate::GetLabelForCommandId( - int command_id) const { - return base::string16(); -} - -base::string16 SimpleMenuModel::Delegate::GetSublabelForCommandId( - int command_id) const { - return base::string16(); -} - -base::string16 SimpleMenuModel::Delegate::GetMinorTextForCommandId( - int command_id) const { - return base::string16(); -} - -bool SimpleMenuModel::Delegate::GetIconForCommandId( - int command_id, gfx::Image* image_skia) const { - return false; -} - -void SimpleMenuModel::Delegate::CommandIdHighlighted(int command_id) { -} - -void SimpleMenuModel::Delegate::ExecuteCommand( - int command_id, int event_flags) { - ExecuteCommand(command_id, event_flags); -} - -void SimpleMenuModel::Delegate::MenuWillShow(SimpleMenuModel* /*source*/) { -} - -void SimpleMenuModel::Delegate::MenuClosed(SimpleMenuModel* /*source*/) { -} - -//////////////////////////////////////////////////////////////////////////////// -// SimpleMenuModel, public: - -SimpleMenuModel::SimpleMenuModel(Delegate* delegate) - : delegate_(delegate), - menu_model_delegate_(NULL), - method_factory_(this) { -} - -SimpleMenuModel::~SimpleMenuModel() { -} - -void SimpleMenuModel::AddItem(int command_id, const base::string16& label) { - Item item = { command_id, label, base::string16(), base::string16(), - gfx::Image(), TYPE_COMMAND, -1, NULL, NULL, NORMAL_SEPARATOR }; - AppendItem(item); -} - -void SimpleMenuModel::AddItemWithStringId(int command_id, int string_id) { - AddItem(command_id, l10n_util::GetStringUTF16(string_id)); -} - -void SimpleMenuModel::AddCheckItem(int command_id, - const base::string16& label) { - Item item = { command_id, label, base::string16(), base::string16(), - gfx::Image(), TYPE_CHECK, -1, NULL, NULL, NORMAL_SEPARATOR }; - AppendItem(item); -} - -void SimpleMenuModel::AddCheckItemWithStringId(int command_id, int string_id) { - AddCheckItem(command_id, l10n_util::GetStringUTF16(string_id)); -} - -void SimpleMenuModel::AddRadioItem(int command_id, - const base::string16& label, - int group_id) { - Item item = { command_id, label, base::string16(), base::string16(), - gfx::Image(), TYPE_RADIO, group_id, NULL, NULL, - NORMAL_SEPARATOR }; - AppendItem(item); -} - -void SimpleMenuModel::AddRadioItemWithStringId(int command_id, int string_id, - int group_id) { - AddRadioItem(command_id, l10n_util::GetStringUTF16(string_id), group_id); -} - -void SimpleMenuModel::AddSeparator(MenuSeparatorType separator_type) { - if (items_.empty()) { - if (separator_type == NORMAL_SEPARATOR) { - return; - } - DCHECK_EQ(SPACING_SEPARATOR, separator_type); - } else if (items_.back().type == TYPE_SEPARATOR) { - DCHECK_EQ(NORMAL_SEPARATOR, separator_type); - DCHECK_EQ(NORMAL_SEPARATOR, items_.back().separator_type); - return; - } -#if !defined(USE_AURA) - if (separator_type == SPACING_SEPARATOR) - NOTIMPLEMENTED(); -#endif - Item item = { kSeparatorId, base::string16(), base::string16(), - base::string16(), gfx::Image(), TYPE_SEPARATOR, -1, NULL, NULL, - separator_type }; - AppendItem(item); -} - -void SimpleMenuModel::RemoveTrailingSeparators() { - while (!items_.empty() && items_.back().type == TYPE_SEPARATOR) - items_.pop_back(); - MenuItemsChanged(); -} - -void SimpleMenuModel::AddButtonItem(int command_id, - ButtonMenuItemModel* model) { - Item item = { command_id, base::string16(), base::string16(), - base::string16(), gfx::Image(), TYPE_BUTTON_ITEM, -1, NULL, - model, NORMAL_SEPARATOR }; - AppendItem(item); -} - -void SimpleMenuModel::AddSubMenu(int command_id, - const base::string16& label, - MenuModel* model) { - Item item = { command_id, label, base::string16(), base::string16(), - gfx::Image(), TYPE_SUBMENU, -1, model, NULL, NORMAL_SEPARATOR }; - AppendItem(item); -} - -void SimpleMenuModel::AddSubMenuWithStringId(int command_id, - int string_id, MenuModel* model) { - AddSubMenu(command_id, l10n_util::GetStringUTF16(string_id), model); -} - -void SimpleMenuModel::InsertItemAt(int index, - int command_id, - const base::string16& label) { - Item item = { command_id, label, base::string16(), base::string16(), - gfx::Image(), TYPE_COMMAND, -1, NULL, NULL, NORMAL_SEPARATOR }; - InsertItemAtIndex(item, index); -} - -void SimpleMenuModel::InsertItemWithStringIdAt( - int index, int command_id, int string_id) { - InsertItemAt(index, command_id, l10n_util::GetStringUTF16(string_id)); -} - -void SimpleMenuModel::InsertSeparatorAt(int index, - MenuSeparatorType separator_type) { -#if !defined(USE_AURA) - if (separator_type != NORMAL_SEPARATOR) { - NOTIMPLEMENTED(); - } -#endif - Item item = { kSeparatorId, base::string16(), base::string16(), - base::string16(), gfx::Image(), TYPE_SEPARATOR, -1, NULL, NULL, - separator_type }; - InsertItemAtIndex(item, index); -} - -void SimpleMenuModel::InsertCheckItemAt(int index, - int command_id, - const base::string16& label) { - Item item = { command_id, label, base::string16(), base::string16(), - gfx::Image(), TYPE_CHECK, -1, NULL, NULL, NORMAL_SEPARATOR }; - InsertItemAtIndex(item, index); -} - -void SimpleMenuModel::InsertCheckItemWithStringIdAt( - int index, int command_id, int string_id) { - InsertCheckItemAt(index, command_id, l10n_util::GetStringUTF16(string_id)); -} - -void SimpleMenuModel::InsertRadioItemAt(int index, - int command_id, - const base::string16& label, - int group_id) { - Item item = { command_id, label, base::string16(), base::string16(), - gfx::Image(), TYPE_RADIO, group_id, NULL, NULL, - NORMAL_SEPARATOR }; - InsertItemAtIndex(item, index); -} - -void SimpleMenuModel::InsertRadioItemWithStringIdAt( - int index, int command_id, int string_id, int group_id) { - InsertRadioItemAt( - index, command_id, l10n_util::GetStringUTF16(string_id), group_id); -} - -void SimpleMenuModel::InsertSubMenuAt(int index, - int command_id, - const base::string16& label, - MenuModel* model) { - Item item = { command_id, label, base::string16(), base::string16(), - gfx::Image(), TYPE_SUBMENU, -1, model, NULL, - NORMAL_SEPARATOR }; - InsertItemAtIndex(item, index); -} - -void SimpleMenuModel::InsertSubMenuWithStringIdAt( - int index, int command_id, int string_id, MenuModel* model) { - InsertSubMenuAt(index, command_id, l10n_util::GetStringUTF16(string_id), - model); -} - -void SimpleMenuModel::RemoveItemAt(int index) { - items_.erase(items_.begin() + ValidateItemIndex(index)); - MenuItemsChanged(); -} - -void SimpleMenuModel::SetIcon(int index, const gfx::Image& icon) { - items_[ValidateItemIndex(index)].icon = icon; - MenuItemsChanged(); -} - -void SimpleMenuModel::SetSublabel(int index, const base::string16& sublabel) { - items_[ValidateItemIndex(index)].sublabel = sublabel; - MenuItemsChanged(); -} - -void SimpleMenuModel::SetMinorText(int index, - const base::string16& minor_text) { - items_[ValidateItemIndex(index)].minor_text = minor_text; -} - -void SimpleMenuModel::Clear() { - items_.clear(); - MenuItemsChanged(); -} - -int SimpleMenuModel::GetIndexOfCommandId(int command_id) { - for (ItemVector::iterator i = items_.begin(); i != items_.end(); ++i) { - if (i->command_id == command_id) - return static_cast<int>(std::distance(items_.begin(), i)); - } - return -1; -} - -//////////////////////////////////////////////////////////////////////////////// -// SimpleMenuModel, MenuModel implementation: - -bool SimpleMenuModel::HasIcons() const { - for (ItemVector::const_iterator i = items_.begin(); i != items_.end(); ++i) { - if (!i->icon.IsEmpty()) - return true; - } - - return false; -} - -int SimpleMenuModel::GetItemCount() const { - return static_cast<int>(items_.size()); -} - -MenuModel::ItemType SimpleMenuModel::GetTypeAt(int index) const { - return items_[ValidateItemIndex(index)].type; -} - -ui::MenuSeparatorType SimpleMenuModel::GetSeparatorTypeAt(int index) const { - return items_[ValidateItemIndex(index)].separator_type; -} - -int SimpleMenuModel::GetCommandIdAt(int index) const { - return items_[ValidateItemIndex(index)].command_id; -} - -base::string16 SimpleMenuModel::GetLabelAt(int index) const { - if (IsItemDynamicAt(index)) - return delegate_->GetLabelForCommandId(GetCommandIdAt(index)); - return items_[ValidateItemIndex(index)].label; -} - -base::string16 SimpleMenuModel::GetSublabelAt(int index) const { - if (IsItemDynamicAt(index)) - return delegate_->GetSublabelForCommandId(GetCommandIdAt(index)); - return items_[ValidateItemIndex(index)].sublabel; -} - -base::string16 SimpleMenuModel::GetMinorTextAt(int index) const { - if (IsItemDynamicAt(index)) - return delegate_->GetMinorTextForCommandId(GetCommandIdAt(index)); - return items_[ValidateItemIndex(index)].minor_text; -} - -bool SimpleMenuModel::IsItemDynamicAt(int index) const { - if (delegate_) - return delegate_->IsItemForCommandIdDynamic(GetCommandIdAt(index)); - return false; -} - -bool SimpleMenuModel::GetAcceleratorAt(int index, - ui::Accelerator* accelerator) const { - if (delegate_) { - return delegate_->GetAcceleratorForCommandId(GetCommandIdAt(index), - accelerator); - } - return false; -} - -bool SimpleMenuModel::IsItemCheckedAt(int index) const { - if (!delegate_) - return false; - MenuModel::ItemType item_type = GetTypeAt(index); - return (item_type == TYPE_CHECK || item_type == TYPE_RADIO) ? - delegate_->IsCommandIdChecked(GetCommandIdAt(index)) : false; -} - -int SimpleMenuModel::GetGroupIdAt(int index) const { - return items_[ValidateItemIndex(index)].group_id; -} - -bool SimpleMenuModel::GetIconAt(int index, gfx::Image* icon) { - if (IsItemDynamicAt(index)) - return delegate_->GetIconForCommandId(GetCommandIdAt(index), icon); - - ValidateItemIndex(index); - if (items_[index].icon.IsEmpty()) - return false; - - *icon = items_[index].icon; - return true; -} - -ButtonMenuItemModel* SimpleMenuModel::GetButtonMenuItemAt(int index) const { - return items_[ValidateItemIndex(index)].button_model; -} - -bool SimpleMenuModel::IsEnabledAt(int index) const { - int command_id = GetCommandIdAt(index); - if (!delegate_ || command_id == kSeparatorId || GetButtonMenuItemAt(index)) - return true; - return delegate_->IsCommandIdEnabled(command_id); -} - -bool SimpleMenuModel::IsVisibleAt(int index) const { - int command_id = GetCommandIdAt(index); - if (!delegate_ || command_id == kSeparatorId || GetButtonMenuItemAt(index)) - return true; - return delegate_->IsCommandIdVisible(command_id); -} - -void SimpleMenuModel::HighlightChangedTo(int index) { - if (delegate_) - delegate_->CommandIdHighlighted(GetCommandIdAt(index)); -} - -void SimpleMenuModel::ActivatedAt(int index) { - if (delegate_) - delegate_->ExecuteCommand(GetCommandIdAt(index), 0); -} - -void SimpleMenuModel::ActivatedAt(int index, int event_flags) { - if (delegate_) - delegate_->ExecuteCommand(GetCommandIdAt(index), event_flags); -} - -MenuModel* SimpleMenuModel::GetSubmenuModelAt(int index) const { - return items_[ValidateItemIndex(index)].submenu; -} - -void SimpleMenuModel::MenuWillShow() { - if (delegate_) - delegate_->MenuWillShow(this); -} - -void SimpleMenuModel::MenuClosed() { - // Due to how menus work on the different platforms, ActivatedAt will be - // called after this. It's more convenient for the delegate to be called - // afterwards though, so post a task. - base::MessageLoop::current()->PostTask( - FROM_HERE, - base::Bind(&SimpleMenuModel::OnMenuClosed, method_factory_.GetWeakPtr())); -} - -void SimpleMenuModel::SetMenuModelDelegate( - ui::MenuModelDelegate* menu_model_delegate) { - menu_model_delegate_ = menu_model_delegate; -} - -MenuModelDelegate* SimpleMenuModel::GetMenuModelDelegate() const { - return menu_model_delegate_; -} - -void SimpleMenuModel::OnMenuClosed() { - if (delegate_) - delegate_->MenuClosed(this); -} - -//////////////////////////////////////////////////////////////////////////////// -// SimpleMenuModel, Protected: - -void SimpleMenuModel::MenuItemsChanged() { -} - -//////////////////////////////////////////////////////////////////////////////// -// SimpleMenuModel, Private: - -int SimpleMenuModel::ValidateItemIndex(int index) const { - CHECK_GE(index, 0); - CHECK_LT(static_cast<size_t>(index), items_.size()); - return index; -} - -void SimpleMenuModel::AppendItem(const Item& item) { - ValidateItem(item); - items_.push_back(item); - MenuItemsChanged(); -} - -void SimpleMenuModel::InsertItemAtIndex(const Item& item, int index) { - ValidateItem(item); - items_.insert(items_.begin() + index, item); - MenuItemsChanged(); -} - -void SimpleMenuModel::ValidateItem(const Item& item) { -#ifndef NDEBUG - if (item.type == TYPE_SEPARATOR) { - DCHECK_EQ(item.command_id, kSeparatorId); - } else { - DCHECK_GE(item.command_id, 0); - } -#endif // NDEBUG -} - -} // namespace ui
diff --git a/ui/base/models/simple_menu_model.h b/ui/base/models/simple_menu_model.h deleted file mode 100644 index 49403aa..0000000 --- a/ui/base/models/simple_menu_model.h +++ /dev/null
@@ -1,206 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_MODELS_SIMPLE_MENU_MODEL_H_ -#define UI_BASE_MODELS_SIMPLE_MENU_MODEL_H_ - -#include <vector> - -#include "base/memory/weak_ptr.h" -#include "base/strings/string16.h" -#include "ui/base/models/menu_model.h" - -namespace gfx { -class Image; -} - -namespace ui { - -class ButtonMenuItemModel; - -// A simple MenuModel implementation with an imperative API for adding menu -// items. This makes it easy to construct fixed menus. Menus populated by -// dynamic data sources may be better off implementing MenuModel directly. -// The breadth of MenuModel is not exposed through this API. -class UI_BASE_EXPORT SimpleMenuModel : public MenuModel { - public: - class UI_BASE_EXPORT Delegate { - public: - virtual ~Delegate() {} - - // Methods for determining the state of specific command ids. - virtual bool IsCommandIdChecked(int command_id) const = 0; - virtual bool IsCommandIdEnabled(int command_id) const = 0; - virtual bool IsCommandIdVisible(int command_id) const; - - // Gets the accelerator for the specified command id. Returns true if the - // command id has a valid accelerator, false otherwise. - virtual bool GetAcceleratorForCommandId( - int command_id, - ui::Accelerator* accelerator) = 0; - - // Some command ids have labels, sublabels, minor text and icons that change - // over time. - virtual bool IsItemForCommandIdDynamic(int command_id) const; - virtual base::string16 GetLabelForCommandId(int command_id) const; - virtual base::string16 GetSublabelForCommandId(int command_id) const; - virtual base::string16 GetMinorTextForCommandId(int command_id) const; - // Gets the icon for the item with the specified id, returning true if there - // is an icon, false otherwise. - virtual bool GetIconForCommandId(int command_id, - gfx::Image* icon) const; - - // Notifies the delegate that the item with the specified command id was - // visually highlighted within the menu. - virtual void CommandIdHighlighted(int command_id); - - // Performs the action associates with the specified command id. - // The passed |event_flags| are the flags from the event which issued this - // command and they can be examined to find modifier keys. - virtual void ExecuteCommand(int command_id, int event_flags) = 0; - - // Notifies the delegate that the menu is about to show. - virtual void MenuWillShow(SimpleMenuModel* source); - - // Notifies the delegate that the menu has closed. - virtual void MenuClosed(SimpleMenuModel* source); - }; - - // The Delegate can be NULL, though if it is items can't be checked or - // disabled. - explicit SimpleMenuModel(Delegate* delegate); - ~SimpleMenuModel() override; - - // Methods for adding items to the model. - void AddItem(int command_id, const base::string16& label); - void AddItemWithStringId(int command_id, int string_id); - void AddCheckItem(int command_id, const base::string16& label); - void AddCheckItemWithStringId(int command_id, int string_id); - void AddRadioItem(int command_id, const base::string16& label, int group_id); - void AddRadioItemWithStringId(int command_id, int string_id, int group_id); - - // Adds a separator of the specified type to the model. - // - Adding a separator after another separator is always invalid if they - // differ in type, but silently ignored if they are both NORMAL. - // - Adding a separator to an empty model is invalid, unless they are NORMAL - // or SPACING. NORMAL separators are silently ignored if the model is empty. - void AddSeparator(MenuSeparatorType separator_type); - - // Removes separators until the model's last entry is not a separator, or the - // model is empty. - void RemoveTrailingSeparators(); - - // These three methods take pointers to various sub-models. These models - // should be owned by the same owner of this SimpleMenuModel. - void AddButtonItem(int command_id, ButtonMenuItemModel* model); - void AddSubMenu(int command_id, - const base::string16& label, - MenuModel* model); - void AddSubMenuWithStringId(int command_id, int string_id, MenuModel* model); - - // Methods for inserting items into the model. - void InsertItemAt(int index, int command_id, const base::string16& label); - void InsertItemWithStringIdAt(int index, int command_id, int string_id); - void InsertSeparatorAt(int index, MenuSeparatorType separator_type); - void InsertCheckItemAt(int index, - int command_id, - const base::string16& label); - void InsertCheckItemWithStringIdAt(int index, int command_id, int string_id); - void InsertRadioItemAt(int index, - int command_id, - const base::string16& label, - int group_id); - void InsertRadioItemWithStringIdAt( - int index, int command_id, int string_id, int group_id); - void InsertSubMenuAt(int index, - int command_id, - const base::string16& label, - MenuModel* model); - void InsertSubMenuWithStringIdAt( - int index, int command_id, int string_id, MenuModel* model); - - // Remove item at specified index from the model. - void RemoveItemAt(int index); - - // Sets the icon for the item at |index|. - void SetIcon(int index, const gfx::Image& icon); - - // Sets the sublabel for the item at |index|. - void SetSublabel(int index, const base::string16& sublabel); - - // Sets the minor text for the item at |index|. - void SetMinorText(int index, const base::string16& minor_text); - - // Clears all items. Note that it does not free MenuModel of submenu. - void Clear(); - - // Returns the index of the item that has the given |command_id|. Returns - // -1 if not found. - int GetIndexOfCommandId(int command_id); - - // Overridden from MenuModel: - bool HasIcons() const override; - int GetItemCount() const override; - ItemType GetTypeAt(int index) const override; - ui::MenuSeparatorType GetSeparatorTypeAt(int index) const override; - int GetCommandIdAt(int index) const override; - base::string16 GetLabelAt(int index) const override; - base::string16 GetSublabelAt(int index) const override; - base::string16 GetMinorTextAt(int index) const override; - bool IsItemDynamicAt(int index) const override; - bool GetAcceleratorAt(int index, ui::Accelerator* accelerator) const override; - bool IsItemCheckedAt(int index) const override; - int GetGroupIdAt(int index) const override; - bool GetIconAt(int index, gfx::Image* icon) override; - ui::ButtonMenuItemModel* GetButtonMenuItemAt(int index) const override; - bool IsEnabledAt(int index) const override; - bool IsVisibleAt(int index) const override; - void HighlightChangedTo(int index) override; - void ActivatedAt(int index) override; - void ActivatedAt(int index, int event_flags) override; - MenuModel* GetSubmenuModelAt(int index) const override; - void MenuWillShow() override; - void MenuClosed() override; - void SetMenuModelDelegate( - ui::MenuModelDelegate* menu_model_delegate) override; - MenuModelDelegate* GetMenuModelDelegate() const override; - - protected: - void set_delegate(Delegate* delegate) { delegate_ = delegate; } - Delegate* delegate() { return delegate_; } - - // One or more of the menu menu items associated with the model has changed. - // Do any handling if necessary. - virtual void MenuItemsChanged(); - - private: - struct Item; - - typedef std::vector<Item> ItemVector; - - // Returns |index|. - int ValidateItemIndex(int index) const; - - // Functions for inserting items into |items_|. - void AppendItem(const Item& item); - void InsertItemAtIndex(const Item& item, int index); - void ValidateItem(const Item& item); - - // Notify the delegate that the menu is closed. - void OnMenuClosed(); - - ItemVector items_; - - Delegate* delegate_; - - MenuModelDelegate* menu_model_delegate_; - - base::WeakPtrFactory<SimpleMenuModel> method_factory_; - - DISALLOW_COPY_AND_ASSIGN(SimpleMenuModel); -}; - -} // namespace ui - -#endif // UI_BASE_MODELS_SIMPLE_MENU_MODEL_H_
diff --git a/ui/base/models/table_model.cc b/ui/base/models/table_model.cc deleted file mode 100644 index 37a866f..0000000 --- a/ui/base/models/table_model.cc +++ /dev/null
@@ -1,102 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/models/table_model.h" - -#include "base/i18n/string_compare.h" -#include "base/logging.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/gfx/image/image_skia.h" - -namespace ui { - -// TableColumn ----------------------------------------------------------------- - -TableColumn::TableColumn() - : id(0), - title(), - alignment(LEFT), - width(-1), - percent(), - min_visible_width(0), - sortable(false) { -} - -TableColumn::TableColumn(int id, Alignment alignment, int width, float percent) - : id(id), - title(l10n_util::GetStringUTF16(id)), - alignment(alignment), - width(width), - percent(percent), - min_visible_width(0), - sortable(false) { -} - -// TableModel ----------------------------------------------------------------- - -// Used for sorting. -static icu::Collator* collator = NULL; - -gfx::ImageSkia TableModel::GetIcon(int row) { - return gfx::ImageSkia(); -} - -base::string16 TableModel::GetTooltip(int row) { - return base::string16(); -} - -bool TableModel::ShouldIndent(int row) { - return false; -} - -bool TableModel::HasGroups() { - return false; -} - -TableModel::Groups TableModel::GetGroups() { - // If you override HasGroups to return true, you must override this as - // well. - NOTREACHED(); - return std::vector<Group>(); -} - -int TableModel::GetGroupID(int row) { - // If you override HasGroups to return true, you must override this as - // well. - NOTREACHED(); - return 0; -} - -int TableModel::CompareValues(int row1, int row2, int column_id) { - DCHECK(row1 >= 0 && row1 < RowCount() && - row2 >= 0 && row2 < RowCount()); - base::string16 value1 = GetText(row1, column_id); - base::string16 value2 = GetText(row2, column_id); - icu::Collator* collator = GetCollator(); - - if (collator) - return base::i18n::CompareString16WithCollator(collator, value1, value2); - - NOTREACHED(); - return 0; -} - -void TableModel::ClearCollator() { - delete collator; - collator = NULL; -} - -icu::Collator* TableModel::GetCollator() { - if (!collator) { - UErrorCode create_status = U_ZERO_ERROR; - collator = icu::Collator::createInstance(create_status); - if (!U_SUCCESS(create_status)) { - collator = NULL; - NOTREACHED(); - } - } - return collator; -} - -} // namespace ui
diff --git a/ui/base/models/table_model.h b/ui/base/models/table_model.h deleted file mode 100644 index 68cf202..0000000 --- a/ui/base/models/table_model.h +++ /dev/null
@@ -1,138 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_MODELS_TABLE_MODEL_H_ -#define UI_BASE_MODELS_TABLE_MODEL_H_ - -#include <vector> - -#include "base/strings/string16.h" -#include "third_party/icu/source/i18n/unicode/coll.h" -#include "ui/base/ui_base_export.h" - -namespace gfx { -class ImageSkia; -} - -namespace ui { - -class TableModelObserver; - -// The model driving the TableView. -class UI_BASE_EXPORT TableModel { - public: - // See HasGroups, get GetGroupID for details as to how this is used. - struct Group { - // The title text for the group. - base::string16 title; - - // Unique id for the group. - int id; - }; - typedef std::vector<Group> Groups; - - // Number of rows in the model. - virtual int RowCount() = 0; - - // Returns the value at a particular location in text. - virtual base::string16 GetText(int row, int column_id) = 0; - - // Returns the small icon (16x16) that should be displayed in the first - // column before the text. This is only used when the TableView was created - // with the ICON_AND_TEXT table type. Returns an isNull() image if there is - // no image. - virtual gfx::ImageSkia GetIcon(int row); - - // Returns the tooltip, if any, to show for a particular row. If there are - // multiple columns in the row, this will only be shown when hovering over - // column zero. - virtual base::string16 GetTooltip(int row); - - // If true, this row should be indented. - virtual bool ShouldIndent(int row); - - // Returns true if the TableView has groups. Groups provide a way to visually - // delineate the rows in a table view. When groups are enabled table view - // shows a visual separator for each group, followed by all the rows in - // the group. - // - // On win2k a visual separator is not rendered for the group headers. - virtual bool HasGroups(); - - // Returns the groups. - // This is only used if HasGroups returns true. - virtual Groups GetGroups(); - - // Returns the group id of the specified row. - // This is only used if HasGroups returns true. - virtual int GetGroupID(int row); - - // Sets the observer for the model. The TableView should NOT take ownership - // of the observer. - virtual void SetObserver(TableModelObserver* observer) = 0; - - // Compares the values in the column with id |column_id| for the two rows. - // Returns a value < 0, == 0 or > 0 as to whether the first value is - // <, == or > the second value. - // - // This implementation does a case insensitive locale specific string - // comparison. - virtual int CompareValues(int row1, int row2, int column_id); - - // Reset the collator. - void ClearCollator(); - - protected: - virtual ~TableModel() {} - - // Returns the collator used by CompareValues. - icu::Collator* GetCollator(); -}; - -// TableColumn specifies the title, alignment and size of a particular column. -struct UI_BASE_EXPORT TableColumn { - enum Alignment { - LEFT, RIGHT, CENTER - }; - - TableColumn(); - TableColumn(int id, Alignment alignment, int width, float percent); - - // A unique identifier for the column. - int id; - - // The title for the column. - base::string16 title; - - // Alignment for the content. - Alignment alignment; - - // The size of a column may be specified in two ways: - // 1. A fixed width. Set the width field to a positive number and the - // column will be given that width, in pixels. - // 2. As a percentage of the available width. If width is -1, and percent is - // > 0, the column is given a width of - // available_width * percent / total_percent. - // 3. If the width == -1 and percent == 0, the column is autosized based on - // the width of the column header text. - // - // Sizing is done in four passes. Fixed width columns are given - // their width, percentages are applied, autosized columns are autosized, - // and finally percentages are applied again taking into account the widths - // of autosized columns. - int width; - float percent; - - // The minimum width required for all items in this column - // (including the header) - // to be visible. - int min_visible_width; - - // Is this column sortable? Default is false - bool sortable; -}; - -} // namespace ui - -#endif // UI_BASE_MODELS_TABLE_MODEL_H_
diff --git a/ui/base/models/table_model_observer.h b/ui/base/models/table_model_observer.h deleted file mode 100644 index 4c9d0eb..0000000 --- a/ui/base/models/table_model_observer.h +++ /dev/null
@@ -1,34 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_MODELS_TABLE_MODEL_OBSERVER_H_ -#define UI_BASE_MODELS_TABLE_MODEL_OBSERVER_H_ - -#include "ui/base/ui_base_export.h" - -namespace ui { - -// Observer for a TableModel. Anytime the model changes, it must notify its -// observer. -class UI_BASE_EXPORT TableModelObserver { - public: - // Invoked when the model has been completely changed. - virtual void OnModelChanged() = 0; - - // Invoked when a range of items has changed. - virtual void OnItemsChanged(int start, int length) = 0; - - // Invoked when new items are added. - virtual void OnItemsAdded(int start, int length) = 0; - - // Invoked when a range of items has been removed. - virtual void OnItemsRemoved(int start, int length) = 0; - - protected: - virtual ~TableModelObserver() {} -}; - -} // namespace ui - -#endif // UI_BASE_MODELS_TABLE_MODEL_OBSERVER_H_
diff --git a/ui/base/models/tree_model.cc b/ui/base/models/tree_model.cc deleted file mode 100644 index b30a13b..0000000 --- a/ui/base/models/tree_model.cc +++ /dev/null
@@ -1,20 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/models/tree_model.h" - -#include "base/logging.h" - -namespace ui { - -void TreeModel::SetTitle(TreeModelNode* node, - const base::string16& title) { - NOTREACHED(); -} - -int TreeModel::GetIconIndex(TreeModelNode* node) { - return -1; -} - -} // namespace ui
diff --git a/ui/base/models/tree_model.h b/ui/base/models/tree_model.h deleted file mode 100644 index d553a40..0000000 --- a/ui/base/models/tree_model.h +++ /dev/null
@@ -1,101 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_MODELS_TREE_MODEL_H_ -#define UI_BASE_MODELS_TREE_MODEL_H_ - -#include <vector> - -#include "base/strings/string16.h" -#include "ui/base/ui_base_export.h" - -namespace gfx { -class ImageSkia; -} - -namespace ui { - -class TreeModel; - -// TreeModelNode -------------------------------------------------------------- - -// Type of class returned from the model. -class TreeModelNode { - public: - // Returns the title for the node. - virtual const base::string16& GetTitle() const = 0; - - protected: - virtual ~TreeModelNode() {} -}; - -// Observer for the TreeModel. Notified of significant events to the model. -class UI_BASE_EXPORT TreeModelObserver { - public: - // Notification that nodes were added to the specified parent. - virtual void TreeNodesAdded(TreeModel* model, - TreeModelNode* parent, - int start, - int count) = 0; - - // Notification that nodes were removed from the specified parent. - virtual void TreeNodesRemoved(TreeModel* model, - TreeModelNode* parent, - int start, - int count) = 0; - - // Notification that the contents of a node has changed. - virtual void TreeNodeChanged(TreeModel* model, TreeModelNode* node) = 0; - - protected: - virtual ~TreeModelObserver() {} -}; - -// TreeModel ------------------------------------------------------------------ - -// The model for TreeView. -class UI_BASE_EXPORT TreeModel { - public: - // Returns the root of the tree. This may or may not be shown in the tree, - // see SetRootShown for details. - virtual TreeModelNode* GetRoot() = 0; - - // Returns the number of children in |parent|. - virtual int GetChildCount(TreeModelNode* parent) = 0; - - // Returns the child node of |parent| at |index|. - virtual TreeModelNode* GetChild(TreeModelNode* parent, int index) = 0; - - // Returns the index of |child| in |parent|. - virtual int GetIndexOf(TreeModelNode* parent, TreeModelNode* child) = 0; - - // Returns the parent of |node|, or NULL if |node| is the root. - virtual TreeModelNode* GetParent(TreeModelNode* node) = 0; - - // Adds an observer of the model. - virtual void AddObserver(TreeModelObserver* observer) = 0; - - // Removes an observer of the model. - virtual void RemoveObserver(TreeModelObserver* observer) = 0; - - // Sets the title of |node|. - // This is only invoked if the node is editable and the user edits a node. - virtual void SetTitle(TreeModelNode* node, const base::string16& title); - - // Returns the set of icons for the nodes in the tree. You only need override - // this if you don't want to use the default folder icons. - virtual void GetIcons(std::vector<gfx::ImageSkia>* icons) {} - - // Returns the index of the icon to use for |node|. Return -1 to use the - // default icon. The index is relative to the list of icons returned from - // GetIcons. - virtual int GetIconIndex(TreeModelNode* node); - - protected: - virtual ~TreeModel() {} -}; - -} // namespace ui - -#endif // UI_BASE_MODELS_TREE_MODEL_H_
diff --git a/ui/base/models/tree_node_iterator.h b/ui/base/models/tree_node_iterator.h deleted file mode 100644 index f8664df..0000000 --- a/ui/base/models/tree_node_iterator.h +++ /dev/null
@@ -1,107 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_MODELS_TREE_NODE_ITERATOR_H_ -#define UI_BASE_MODELS_TREE_NODE_ITERATOR_H_ - -#include <stack> - -#include "base/basictypes.h" -#include "base/callback.h" -#include "base/logging.h" - -namespace ui { - -// Iterator that iterates over the descendants of a node. The iteration does -// not include the node itself, only the descendants. The following illustrates -// typical usage: -// while (iterator.has_next()) { -// Node* node = iterator.Next(); -// // do something with node. -// } -template <class NodeType> -class TreeNodeIterator { - public: - typedef base::Callback<bool(NodeType*)> PruneCallback; - - // This contructor accepts an optional filter function |prune| which could be - // used to prune complete branches of the tree. The filter function will be - // evaluated on each tree node and if it evaluates to true the node and all - // its descendants will be skipped by the iterator. - TreeNodeIterator(NodeType* node, const PruneCallback& prune) - : prune_(prune) { - int index = 0; - - // Move forward through the children list until the first non prunable node. - // This is to satisfy the iterator invariant that the current index in the - // Position at the top of the _positions list must point to a node the - // iterator will be returning. - for (; index < node->child_count(); ++index) - if (prune.is_null() || !prune.Run(node->GetChild(index))) - break; - - if (index < node->child_count()) - positions_.push(Position<NodeType>(node, index)); - } - - explicit TreeNodeIterator(NodeType* node) { - if (!node->empty()) - positions_.push(Position<NodeType>(node, 0)); - } - - // Returns true if there are more descendants. - bool has_next() const { return !positions_.empty(); } - - // Returns the next descendant. - NodeType* Next() { - if (!has_next()) { - NOTREACHED(); - return NULL; - } - - // There must always be a valid node in the current Position index. - NodeType* result = positions_.top().node->GetChild(positions_.top().index); - - // Make sure we don't attempt to visit result again. - positions_.top().index++; - - // Iterate over result's children. - positions_.push(Position<NodeType>(result, 0)); - - // Advance to next valid node by skipping over the pruned nodes and the - // empty Positions. At the end of this loop two cases are possible: - // - the current index of the top() Position points to a valid node - // - the _position list is empty, the iterator has_next() will return false. - while (!positions_.empty()) { - if (positions_.top().index >= positions_.top().node->child_count()) - positions_.pop(); // This Position is all processed, move to the next. - else if (!prune_.is_null() && - prune_.Run(positions_.top().node->GetChild(positions_.top().index))) - positions_.top().index++; // Prune the branch. - else - break; // Now positioned at the next node to be returned. - } - - return result; - } - - private: - template <class PositionNodeType> - struct Position { - Position(PositionNodeType* node, int index) : node(node), index(index) {} - Position() : node(NULL), index(-1) {} - - PositionNodeType* node; - int index; - }; - - std::stack<Position<NodeType> > positions_; - PruneCallback prune_; - - DISALLOW_COPY_AND_ASSIGN(TreeNodeIterator); -}; - -} // namespace ui - -#endif // UI_BASE_MODELS_TREE_NODE_ITERATOR_H_
diff --git a/ui/base/models/tree_node_iterator_unittest.cc b/ui/base/models/tree_node_iterator_unittest.cc deleted file mode 100644 index 4acf89c..0000000 --- a/ui/base/models/tree_node_iterator_unittest.cc +++ /dev/null
@@ -1,87 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/models/tree_node_iterator.h" - -#include "base/bind.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/base/models/tree_node_model.h" - -namespace ui { - -namespace { - -typedef TreeNodeWithValue<int> TestNode; - -bool PruneOdd(TestNode* node) { - return node->value % 2; -} - -bool PruneEven(TestNode* node) { - return !PruneOdd(node); -} - -TEST(TreeNodeIteratorTest, Basic) { - TestNode root; - root.Add(new TestNode(), 0); - root.Add(new TestNode(), 1); - TestNode* f3 = new TestNode(); - root.Add(f3, 2); - TestNode* f4 = new TestNode(); - f3->Add(f4, 0); - f4->Add(new TestNode(), 0); - - TreeNodeIterator<TestNode> iterator(&root); - ASSERT_TRUE(iterator.has_next()); - ASSERT_EQ(root.GetChild(0), iterator.Next()); - - ASSERT_TRUE(iterator.has_next()); - ASSERT_EQ(root.GetChild(1), iterator.Next()); - - ASSERT_TRUE(iterator.has_next()); - ASSERT_EQ(root.GetChild(2), iterator.Next()); - - ASSERT_TRUE(iterator.has_next()); - ASSERT_EQ(f4, iterator.Next()); - - ASSERT_TRUE(iterator.has_next()); - ASSERT_EQ(f4->GetChild(0), iterator.Next()); - - ASSERT_FALSE(iterator.has_next()); -} - -// The tree used for testing: -// * + 1 -// + 2 -// + 3 + 4 + 5 -// + 7 -TEST(TreeNodeIteratorTest, Prune) { - TestNode root; - root.Add(new TestNode(1), 0); - root.Add(new TestNode(2), 1); - TestNode* f3 = new TestNode(3); - root.Add(f3, 2); - TestNode* f4 = new TestNode(4); - f3->Add(f4, 0); - f4->Add(new TestNode(5), 0); - f3->Add(new TestNode(7), 1); - - TreeNodeIterator<TestNode> odd_iterator(&root, base::Bind(&PruneOdd)); - ASSERT_TRUE(odd_iterator.has_next()); - ASSERT_EQ(2, odd_iterator.Next()->value); - ASSERT_FALSE(odd_iterator.has_next()); - - TreeNodeIterator<TestNode> even_iterator(&root, base::Bind(&PruneEven)); - ASSERT_TRUE(even_iterator.has_next()); - ASSERT_EQ(1, even_iterator.Next()->value); - ASSERT_TRUE(even_iterator.has_next()); - ASSERT_EQ(3, even_iterator.Next()->value); - ASSERT_TRUE(even_iterator.has_next()); - ASSERT_EQ(7, even_iterator.Next()->value); - ASSERT_FALSE(even_iterator.has_next()); -} - -} // namespace - -} // namespace ui
diff --git a/ui/base/models/tree_node_model.h b/ui/base/models/tree_node_model.h deleted file mode 100644 index 5df2481..0000000 --- a/ui/base/models/tree_node_model.h +++ /dev/null
@@ -1,305 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_MODELS_TREE_NODE_MODEL_H_ -#define UI_BASE_MODELS_TREE_NODE_MODEL_H_ - -#include <algorithm> -#include <vector> - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/logging.h" -#include "base/memory/scoped_ptr.h" -#include "base/memory/scoped_vector.h" -#include "base/observer_list.h" -#include "base/strings/string16.h" -#include "ui/base/models/tree_model.h" - -namespace ui { - -// TreeNodeModel and TreeNodes provide an implementation of TreeModel around -// TreeNodes. -// -// TreeNodes own their children, so that deleting a node deletes all -// descendants. -// -// TreeNodes do NOT maintain a pointer back to the model. As such, if you -// are using TreeNodes with a TreeNodeModel you will need to notify the observer -// yourself any time you make any change directly to the TreeNodes. For example, -// if you directly invoke set_title on a node it does not notify the observer, -// you will need to do it yourself. This includes the following methods: Add, -// Remove and set_title. TreeNodeModel provides cover methods that mutate the -// TreeNodes and notify the observer. If you are using TreeNodes with a -// TreeNodeModel use the cover methods to save yourself the headache. -// -// The following example creates a TreeNode with two children and then -// creates a TreeNodeModel from it: -// -// TreeNodeWithValue<int>* root = new TreeNodeWithValue<int>(); -// root->Add(new TreeNodeWithValue<int>(ASCIIToUTF16("child 1"), 0)); -// root->Add(new TreeNodeWithValue<int>(ASCIIToUTF16("child 2"), 1)); -// TreeNodeModel<TreeNodeWithValue<int> > model(root); -// -// Two variants of TreeNode are provided here: -// -// . TreeNode itself is intended for subclassing. It has one type parameter -// that corresponds to the type of the node. When subclassing use your class -// name as the type parameter, eg: -// class MyTreeNode : public TreeNode<MyTreeNode> . -// . TreeNodeWithValue is a trivial subclass of TreeNode that has one type -// type parameter: a value type that is associated with the node. -// -// Which you use depends upon the situation. If you want to subclass and add -// methods, then use TreeNode. If you don't need any extra methods and just -// want to associate a value with each node, then use TreeNodeWithValue. -// -// Regardless of which TreeNode you use, if you are using the nodes with a -// TreeView take care to notify the observer when mutating the nodes. - -// TreeNode ------------------------------------------------------------------- - -template <class NodeType> -class TreeNode : public TreeModelNode { - public: - TreeNode() : parent_(NULL) {} - - explicit TreeNode(const base::string16& title) - : title_(title), parent_(NULL) {} - - virtual ~TreeNode() {} - - // Adds |node| as a child of this node, at |index|. - virtual void Add(NodeType* node, int index) { - DCHECK(node); - DCHECK_GE(index, 0); - DCHECK_LE(index, child_count()); - // If |node| has a parent, remove it from its parent. - NodeType* parent = node->parent_; - if (parent) - parent->Remove(node); - node->parent_ = static_cast<NodeType*>(this); - children_.insert(children_.begin() + index, node); - } - - // Removes |node| from this node and returns it. It's up to the caller to - // delete it. - virtual NodeType* Remove(NodeType* node) { - typename std::vector<NodeType*>::iterator i = - std::find(children_.begin(), children_.end(), node); - DCHECK(i != children_.end()); - node->parent_ = NULL; - children_.weak_erase(i); - return node; - } - - // Removes all the children from this node. This does NOT delete the nodes. - void RemoveAll() { - for (size_t i = 0; i < children_.size(); ++i) - children_[i]->parent_ = NULL; - children_.weak_clear(); - } - - // Removes all existing children without deleting the nodes and adds all nodes - // contained in |children| into this node as children. - void SetChildren(const std::vector<NodeType*>& children) { - RemoveAll(); - for (size_t i = 0; i < children.size(); ++i) - Add(children[i], static_cast<int>(i)); - } - - // Returns the parent node, or NULL if this is the root node. - const NodeType* parent() const { return parent_; } - NodeType* parent() { return parent_; } - - // Returns true if this is the root node. - bool is_root() const { return parent_ == NULL; } - - // Returns the number of children. - int child_count() const { return static_cast<int>(children_.size()); } - - // Returns true if this node has no children. - bool empty() const { return children_.empty(); } - - // Returns the number of all nodes in the subtree rooted at this node, - // including this node. - int GetTotalNodeCount() const { - int count = 1; // Start with one to include the node itself. - for (size_t i = 0; i < children_.size(); ++i) - count += children_[i]->GetTotalNodeCount(); - return count; - } - - // Returns the node at |index|. - const NodeType* GetChild(int index) const { - DCHECK_GE(index, 0); - DCHECK_LT(index, child_count()); - return children_[index]; - } - NodeType* GetChild(int index) { - return const_cast<NodeType*>( - static_cast<const NodeType&>(*this).GetChild(index)); - } - - // Returns the index of |node|, or -1 if |node| is not a child of this. - int GetIndexOf(const NodeType* node) const { - DCHECK(node); - typename std::vector<NodeType*>::const_iterator i = - std::find(children_.begin(), children_.end(), node); - return i != children_.end() ? static_cast<int>(i - children_.begin()) : -1; - } - - // Sets the title of the node. - virtual void SetTitle(const base::string16& title) { title_ = title; } - - // TreeModelNode: - virtual const base::string16& GetTitle() const override { return title_; } - - // Returns true if this == ancestor, or one of this nodes parents is - // ancestor. - bool HasAncestor(const NodeType* ancestor) const { - if (ancestor == this) - return true; - if (!ancestor) - return false; - return parent_ ? parent_->HasAncestor(ancestor) : false; - } - - protected: - std::vector<NodeType*>& children() { return children_.get(); } - - private: - // Title displayed in the tree. - base::string16 title_; - - // This node's parent. - NodeType* parent_; - - // This node's children. - ScopedVector<NodeType> children_; - - DISALLOW_COPY_AND_ASSIGN(TreeNode); -}; - -// TreeNodeWithValue ---------------------------------------------------------- - -template <class ValueType> -class TreeNodeWithValue : public TreeNode< TreeNodeWithValue<ValueType> > { - public: - TreeNodeWithValue() {} - - explicit TreeNodeWithValue(const ValueType& value) - : ParentType(base::string16()), value(value) {} - - TreeNodeWithValue(const base::string16& title, const ValueType& value) - : ParentType(title), value(value) {} - - ValueType value; - - private: - typedef TreeNode< TreeNodeWithValue<ValueType> > ParentType; - - DISALLOW_COPY_AND_ASSIGN(TreeNodeWithValue); -}; - -// TreeNodeModel -------------------------------------------------------------- - -// TreeModel implementation intended to be used with TreeNodes. -template <class NodeType> -class TreeNodeModel : public TreeModel { - public: - // Creates a TreeNodeModel with the specified root node. The root is owned - // by the TreeNodeModel. - explicit TreeNodeModel(NodeType* root) : root_(root) {} - virtual ~TreeNodeModel() {} - - NodeType* AsNode(TreeModelNode* model_node) { - return static_cast<NodeType*>(model_node); - } - - void Add(NodeType* parent, NodeType* node, int index) { - DCHECK(parent && node); - parent->Add(node, index); - NotifyObserverTreeNodesAdded(parent, index, 1); - } - - NodeType* Remove(NodeType* parent, NodeType* node) { - DCHECK(parent); - int index = parent->GetIndexOf(node); - NodeType* delete_node = parent->Remove(node); - NotifyObserverTreeNodesRemoved(parent, index, 1); - return delete_node; - } - - void NotifyObserverTreeNodesAdded(NodeType* parent, int start, int count) { - FOR_EACH_OBSERVER(TreeModelObserver, - observer_list_, - TreeNodesAdded(this, parent, start, count)); - } - - void NotifyObserverTreeNodesRemoved(NodeType* parent, int start, int count) { - FOR_EACH_OBSERVER(TreeModelObserver, - observer_list_, - TreeNodesRemoved(this, parent, start, count)); - } - - void NotifyObserverTreeNodeChanged(TreeModelNode* node) { - FOR_EACH_OBSERVER(TreeModelObserver, - observer_list_, - TreeNodeChanged(this, node)); - } - - // TreeModel: - virtual NodeType* GetRoot() override { - return root_.get(); - } - - virtual int GetChildCount(TreeModelNode* parent) override { - DCHECK(parent); - return AsNode(parent)->child_count(); - } - - virtual NodeType* GetChild(TreeModelNode* parent, int index) override { - DCHECK(parent); - return AsNode(parent)->GetChild(index); - } - - virtual int GetIndexOf(TreeModelNode* parent, TreeModelNode* child) override { - DCHECK(parent); - return AsNode(parent)->GetIndexOf(AsNode(child)); - } - - virtual TreeModelNode* GetParent(TreeModelNode* node) override { - DCHECK(node); - return AsNode(node)->parent(); - } - - virtual void AddObserver(TreeModelObserver* observer) override { - observer_list_.AddObserver(observer); - } - - virtual void RemoveObserver(TreeModelObserver* observer) override { - observer_list_.RemoveObserver(observer); - } - - virtual void SetTitle(TreeModelNode* node, - const base::string16& title) override { - DCHECK(node); - AsNode(node)->SetTitle(title); - NotifyObserverTreeNodeChanged(node); - } - - private: - // The observers. - ObserverList<TreeModelObserver> observer_list_; - - // The root. - scoped_ptr<NodeType> root_; - - DISALLOW_COPY_AND_ASSIGN(TreeNodeModel); -}; - -} // namespace ui - -#endif // UI_BASE_MODELS_TREE_NODE_MODEL_H_
diff --git a/ui/base/models/tree_node_model_unittest.cc b/ui/base/models/tree_node_model_unittest.cc deleted file mode 100644 index ba923aa..0000000 --- a/ui/base/models/tree_node_model_unittest.cc +++ /dev/null
@@ -1,323 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/models/tree_node_model.h" - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "base/strings/string16.h" -#include "base/strings/stringprintf.h" -#include "base/strings/utf_string_conversions.h" -#include "testing/gtest/include/gtest/gtest.h" - -using base::ASCIIToUTF16; - -namespace ui { - -class TreeNodeModelTest : public testing::Test, public TreeModelObserver { - public: - TreeNodeModelTest() - : added_count_(0), - removed_count_(0), - changed_count_(0) {} - virtual ~TreeNodeModelTest() {} - - protected: - std::string GetObserverCountStateAndClear() { - std::string result(base::StringPrintf("added=%d removed=%d changed=%d", - added_count_, removed_count_, changed_count_)); - added_count_ = removed_count_ = changed_count_ = 0; - return result; - } - - private: - // Overridden from TreeModelObserver: - void TreeNodesAdded(TreeModel* model, - TreeModelNode* parent, - int start, - int count) override { - added_count_++; - } - void TreeNodesRemoved(TreeModel* model, - TreeModelNode* parent, - int start, - int count) override { - removed_count_++; - } - void TreeNodeChanged(TreeModel* model, TreeModelNode* node) override { - changed_count_++; - } - - int added_count_; - int removed_count_; - int changed_count_; - - DISALLOW_COPY_AND_ASSIGN(TreeNodeModelTest); -}; - -typedef TreeNodeWithValue<int> TestNode; - -// Verifies if the model is properly adding a new node in the tree and -// notifying the observers. -// The tree looks like this: -// root -// +-- child1 -// +-- foo1 -// +-- foo2 -// +-- child2 -TEST_F(TreeNodeModelTest, AddNode) { - TestNode* root = new TestNode; - TreeNodeModel<TestNode > model(root); - model.AddObserver(this); - - TestNode* child1 = new TestNode; - model.Add(root, child1, 0); - - EXPECT_EQ("added=1 removed=0 changed=0", GetObserverCountStateAndClear()); - - for (int i = 0; i < 2; ++i) - child1->Add(new TestNode, i); - - TestNode* child2 = new TestNode; - model.Add(root, child2, 1); - - EXPECT_EQ("added=1 removed=0 changed=0", GetObserverCountStateAndClear()); - - EXPECT_EQ(2, root->child_count()); - EXPECT_EQ(2, child1->child_count()); - EXPECT_EQ(0, child2->child_count()); -} - -// Verifies if the model is properly removing a node from the tree -// and notifying the observers. -TEST_F(TreeNodeModelTest, RemoveNode) { - TestNode* root = new TestNode; - TreeNodeModel<TestNode > model(root); - model.AddObserver(this); - - TestNode* child1 = new TestNode; - root->Add(child1, 0); - - EXPECT_EQ(1, model.GetChildCount(root)); - - // Now remove |child1| from |root| and release the memory. - delete model.Remove(root, child1); - - EXPECT_EQ("added=0 removed=1 changed=0", GetObserverCountStateAndClear()); - - EXPECT_EQ(0, model.GetChildCount(root)); -} - -// Verifies if the nodes added under the root are all deleted when calling -// RemoveAll. Note that is responsability of the caller to free the memory -// of the nodes removed after RemoveAll is called. -// The tree looks like this: -// root -// +-- child1 -// +-- foo -// +-- bar0 -// +-- bar1 -// +-- bar2 -// +-- child2 -// +-- child3 -TEST_F(TreeNodeModelTest, RemoveAllNodes) { - TestNode root; - - TestNode child1; - TestNode child2; - TestNode child3; - - root.Add(&child1, 0); - root.Add(&child2, 1); - root.Add(&child3, 2); - - TestNode* foo = new TestNode; - child1.Add(foo, 0); - - // Add some nodes to |foo|. - for (int i = 0; i < 3; ++i) - foo->Add(new TestNode, i); - - EXPECT_EQ(3, root.child_count()); - EXPECT_EQ(1, child1.child_count()); - EXPECT_EQ(3, foo->child_count()); - - // Now remove the child nodes from root. - root.RemoveAll(); - - EXPECT_EQ(0, root.child_count()); - EXPECT_TRUE(root.empty()); - - EXPECT_EQ(1, child1.child_count()); - EXPECT_EQ(3, foo->child_count()); -} - -// Verifies if GetIndexOf() returns the correct index for the specified node. -// The tree looks like this: -// root -// +-- child1 -// +-- foo1 -// +-- child2 -TEST_F(TreeNodeModelTest, GetIndexOf) { - TestNode root; - - TestNode* child1 = new TestNode; - root.Add(child1, 0); - - TestNode* child2 = new TestNode; - root.Add(child2, 1); - - TestNode* foo1 = new TestNode; - child1->Add(foo1, 0); - - EXPECT_EQ(-1, root.GetIndexOf(&root)); - EXPECT_EQ(0, root.GetIndexOf(child1)); - EXPECT_EQ(1, root.GetIndexOf(child2)); - EXPECT_EQ(-1, root.GetIndexOf(foo1)); - - EXPECT_EQ(-1, child1->GetIndexOf(&root)); - EXPECT_EQ(-1, child1->GetIndexOf(child1)); - EXPECT_EQ(-1, child1->GetIndexOf(child2)); - EXPECT_EQ(0, child1->GetIndexOf(foo1)); - - EXPECT_EQ(-1, child2->GetIndexOf(&root)); - EXPECT_EQ(-1, child2->GetIndexOf(child2)); - EXPECT_EQ(-1, child2->GetIndexOf(child1)); - EXPECT_EQ(-1, child2->GetIndexOf(foo1)); -} - -// Verifies whether a specified node has or not an ancestor. -// The tree looks like this: -// root -// +-- child1 -// +-- foo1 -// +-- child2 -TEST_F(TreeNodeModelTest, HasAncestor) { - TestNode root; - TestNode* child1 = new TestNode; - TestNode* child2 = new TestNode; - - root.Add(child1, 0); - root.Add(child2, 1); - - TestNode* foo1 = new TestNode; - child1->Add(foo1, 0); - - EXPECT_TRUE(root.HasAncestor(&root)); - EXPECT_FALSE(root.HasAncestor(child1)); - EXPECT_FALSE(root.HasAncestor(child2)); - EXPECT_FALSE(root.HasAncestor(foo1)); - - EXPECT_TRUE(child1->HasAncestor(child1)); - EXPECT_TRUE(child1->HasAncestor(&root)); - EXPECT_FALSE(child1->HasAncestor(child2)); - EXPECT_FALSE(child1->HasAncestor(foo1)); - - EXPECT_TRUE(child2->HasAncestor(child2)); - EXPECT_TRUE(child2->HasAncestor(&root)); - EXPECT_FALSE(child2->HasAncestor(child1)); - EXPECT_FALSE(child2->HasAncestor(foo1)); - - EXPECT_TRUE(foo1->HasAncestor(foo1)); - EXPECT_TRUE(foo1->HasAncestor(child1)); - EXPECT_TRUE(foo1->HasAncestor(&root)); - EXPECT_FALSE(foo1->HasAncestor(child2)); -} - -// Verifies if GetTotalNodeCount returns the correct number of nodes from the -// node specifed. The count should include the node itself. -// The tree looks like this: -// root -// +-- child1 -// +-- child2 -// +-- child3 -// +-- foo1 -// +-- foo2 -// +-- foo3 -// +-- foo4 -// +-- bar1 -// -// The TotalNodeCount of root is: 9 -// The TotalNodeCount of child1 is: 3 -// The TotalNodeCount of child2 and foo2 is: 2 -// The TotalNodeCount of bar1 is: 1 -// And so on... -TEST_F(TreeNodeModelTest, GetTotalNodeCount) { - TestNode root; - - TestNode* child1 = new TestNode; - TestNode* child2 = new TestNode; - TestNode* child3 = new TestNode; - - root.Add(child1, 0); - child1->Add(child2, 0); - child2->Add(child3, 0); - - TestNode* foo1 = new TestNode; - TestNode* foo2 = new TestNode; - TestNode* foo3 = new TestNode; - TestNode* foo4 = new TestNode; - - root.Add(foo1, 1); - foo1->Add(foo2, 0); - foo2->Add(foo3, 0); - foo1->Add(foo4, 1); - - TestNode* bar1 = new TestNode; - - root.Add(bar1, 2); - - EXPECT_EQ(9, root.GetTotalNodeCount()); - EXPECT_EQ(3, child1->GetTotalNodeCount()); - EXPECT_EQ(2, child2->GetTotalNodeCount()); - EXPECT_EQ(2, foo2->GetTotalNodeCount()); - EXPECT_EQ(1, bar1->GetTotalNodeCount()); -} - -// Makes sure that we are notified when the node is renamed, -// also makes sure the node is properly renamed. -TEST_F(TreeNodeModelTest, SetTitle) { - TestNode* root = new TestNode(ASCIIToUTF16("root"), 0); - TreeNodeModel<TestNode > model(root); - model.AddObserver(this); - - const base::string16 title(ASCIIToUTF16("root2")); - model.SetTitle(root, title); - EXPECT_EQ("added=0 removed=0 changed=1", GetObserverCountStateAndClear()); - EXPECT_EQ(title, root->GetTitle()); -} - -TEST_F(TreeNodeModelTest, BasicOperations) { - TestNode root; - EXPECT_EQ(0, root.child_count()); - - TestNode* child1 = new TestNode; - root.Add(child1, root.child_count()); - EXPECT_EQ(1, root.child_count()); - EXPECT_EQ(&root, child1->parent()); - - TestNode* child2 = new TestNode; - root.Add(child2, root.child_count()); - EXPECT_EQ(2, root.child_count()); - EXPECT_EQ(child1->parent(), child2->parent()); - - scoped_ptr<TestNode > c2(root.Remove(child2)); - EXPECT_EQ(1, root.child_count()); - EXPECT_EQ(NULL, child2->parent()); - - scoped_ptr<TestNode > c1(root.Remove(child1)); - EXPECT_EQ(0, root.child_count()); -} - -TEST_F(TreeNodeModelTest, IsRoot) { - TestNode root; - EXPECT_TRUE(root.is_root()); - - TestNode* child1 = new TestNode; - root.Add(child1, root.child_count()); - EXPECT_FALSE(child1->is_root()); -} - -} // namespace ui
diff --git a/ui/base/nine_image_painter_factory.cc b/ui/base/nine_image_painter_factory.cc deleted file mode 100644 index b22ba67..0000000 --- a/ui/base/nine_image_painter_factory.cc +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/nine_image_painter_factory.h" - -#include "ui/base/resource/resource_bundle.h" -#include "ui/gfx/nine_image_painter.h" - -namespace ui { - -namespace { - -std::vector<gfx::ImageSkia> ImageIdsToImages(const int image_ids[]) { - ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); - std::vector<gfx::ImageSkia> images(9); - for (size_t i = 0; i < 9; ++i) { - if (image_ids[i] != 0) - images[i] = *rb.GetImageSkiaNamed(image_ids[i]); - } - return images; -} - -} // namespace - -scoped_ptr<gfx::NineImagePainter> CreateNineImagePainter( - const int image_ids[]) { - return scoped_ptr<gfx::NineImagePainter>( - new gfx::NineImagePainter(ImageIdsToImages(image_ids))); -} - -} // namespace ui
diff --git a/ui/base/nine_image_painter_factory.h b/ui/base/nine_image_painter_factory.h deleted file mode 100644 index 8a62283..0000000 --- a/ui/base/nine_image_painter_factory.h +++ /dev/null
@@ -1,40 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_NINE_IMAGE_PAINTER_FACTORY_H_ -#define UI_BASE_NINE_IMAGE_PAINTER_FACTORY_H_ - -#include "base/memory/scoped_ptr.h" -#include "ui/base/ui_base_export.h" - -// A macro to define arrays of IDR constants used with CreateImageGridPainter. -#define IMAGE_GRID(x) { x ## _TOP_LEFT, x ## _TOP, x ## _TOP_RIGHT, \ - x ## _LEFT, x ## _CENTER, x ## _RIGHT, \ - x ## _BOTTOM_LEFT, x ## _BOTTOM, x ## _BOTTOM_RIGHT, } - -// Defines a empty image for used in macro for creating image grid for a ring of -// eight images. -#define EMPTY_IMAGE 0 - -// A macro to define arrays of IDR constants used with CreateImageGridPainter -// where only a ring of eight images is provided and center image is empty. -#define IMAGE_GRID_NO_CENTER(x) { x ## _TOP_LEFT, x ## _TOP, x ## _TOP_RIGHT, \ - x ## _LEFT, EMPTY_IMAGE, x ## _RIGHT, \ - x ## _BOTTOM_LEFT, x ## _BOTTOM, x ## _BOTTOM_RIGHT, } - - -namespace gfx { -class NineImagePainter; -} - -namespace ui { - -// Creates a NineImagePainter from an array of image ids. It's expected the -// array came from the IMAGE_GRID macro. -UI_BASE_EXPORT scoped_ptr<gfx::NineImagePainter> CreateNineImagePainter( - const int image_ids[]); - -} // namespace ui - -#endif // UI_BASE_NINE_IMAGE_PAINTER_FACTORY_H_
diff --git a/ui/base/test/ui_controls.h b/ui/base/test/ui_controls.h deleted file mode 100644 index e54f936..0000000 --- a/ui/base/test/ui_controls.h +++ /dev/null
@@ -1,109 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_TEST_UI_CONTROLS_H_ -#define UI_BASE_TEST_UI_CONTROLS_H_ - -#include "base/callback_forward.h" -#include "build/build_config.h" -#include "ui/events/keycodes/keyboard_codes.h" -#include "ui/gfx/native_widget_types.h" - -namespace ui_controls { - -// A set of utility functions to generate native events in platform -// independent way. Note that since the implementations depend on a window being -// top level, these can only be called from test suites that are not sharded. -// For aura tests, please look into |aura::test:EventGenerator| first. This -// class provides a way to emulate events in synchronous way and it is often -// easier to write tests with this class than using |ui_controls|. -// -// Many of the functions in this class include a variant that takes a Closure. -// The version that takes a Closure waits until the generated event is -// processed. Once the generated event is processed the Closure is Run (and -// deleted). Note that this is a somewhat fragile process in that any event of -// the correct type (key down, mouse click, etc.) will trigger the Closure to be -// run. Hence a usage such as -// -// SendKeyPress(...); -// SendKeyPressNotifyWhenDone(..., task); -// -// might trigger |task| early. -// -// Note: Windows does not currently do anything with the |window| argument for -// these functions, so passing NULL is ok. - -// Send a key press with/without modifier keys. -// -// If you're writing a test chances are you want the variant in ui_test_utils. -// See it for details. - -// Per the above comment, these methods can only be called from non-sharded test -// suites. This method ensures that they're not accidently called by sharded -// tests. -void EnableUIControls(); - -bool SendKeyPress(gfx::NativeWindow window, - ui::KeyboardCode key, - bool control, - bool shift, - bool alt, - bool command); -bool SendKeyPressNotifyWhenDone(gfx::NativeWindow window, - ui::KeyboardCode key, - bool control, - bool shift, - bool alt, - bool command, - const base::Closure& task); - -// Simulate a mouse move. -bool SendMouseMove(long screen_x, long screen_y); -bool SendMouseMoveNotifyWhenDone(long screen_x, - long screen_y, - const base::Closure& task); - -enum MouseButton { - LEFT = 0, - MIDDLE, - RIGHT, -}; - -// Used to indicate the state of the button when generating events. -enum MouseButtonState { - UP = 1, - DOWN = 2 -}; - -// Sends a mouse down and/or up message. The click will be sent to wherever -// the cursor currently is, so be sure to move the cursor before calling this -// (and be sure the cursor has arrived!). -bool SendMouseEvents(MouseButton type, int state); -bool SendMouseEventsNotifyWhenDone(MouseButton type, - int state, - const base::Closure& task); - -// Same as SendMouseEvents with UP | DOWN. -bool SendMouseClick(MouseButton type); - -#if defined(TOOLKIT_VIEWS) -// Runs |closure| after processing all pending ui events. -void RunClosureAfterAllPendingUIEvents(const base::Closure& closure); -#endif - -#if defined(USE_AURA) -class UIControlsAura; -void InstallUIControlsAura(UIControlsAura* instance); -#endif - -#if defined(OS_MACOSX) -// Returns true when tests need to use extra Tab and Shift-Tab key events -// to traverse to the desired item; because the application is configured to -// traverse more elements for accessibility reasons. -bool IsFullKeyboardAccessEnabled(); -#endif - -} // namespace ui_controls - -#endif // UI_BASE_TEST_UI_CONTROLS_H_
diff --git a/ui/base/test/ui_controls_aura.cc b/ui/base/test/ui_controls_aura.cc deleted file mode 100644 index c8367ab..0000000 --- a/ui/base/test/ui_controls_aura.cc +++ /dev/null
@@ -1,95 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/test/ui_controls_aura.h" - -#include "base/logging.h" - -namespace ui_controls { -namespace { -UIControlsAura* instance_ = NULL; -bool g_ui_controls_enabled = false; -} // namespace - -void EnableUIControls() { - g_ui_controls_enabled = true; -} - -// An interface to provide Aura implementation of UI control. -bool SendKeyPress(gfx::NativeWindow window, - ui::KeyboardCode key, - bool control, - bool shift, - bool alt, - bool command) { - CHECK(g_ui_controls_enabled); - return instance_->SendKeyPress( - window, key, control, shift, alt, command); -} - -// static -bool SendKeyPressNotifyWhenDone(gfx::NativeWindow window, - ui::KeyboardCode key, - bool control, - bool shift, - bool alt, - bool command, - const base::Closure& task) { - CHECK(g_ui_controls_enabled); - return instance_->SendKeyPressNotifyWhenDone( - window, key, control, shift, alt, command, task); -} - -// static -bool SendMouseMove(long x, long y) { - CHECK(g_ui_controls_enabled); - return instance_->SendMouseMove(x, y); -} - -// static -bool SendMouseMoveNotifyWhenDone(long x, - long y, - const base::Closure& task) { - CHECK(g_ui_controls_enabled); - return instance_->SendMouseMoveNotifyWhenDone(x, y, task); -} - -// static -bool SendMouseEvents(MouseButton type, int state) { - CHECK(g_ui_controls_enabled); - return instance_->SendMouseEvents(type, state); -} - -// static -bool SendMouseEventsNotifyWhenDone(MouseButton type, - int state, - const base::Closure& task) { - CHECK(g_ui_controls_enabled); - return instance_->SendMouseEventsNotifyWhenDone(type, state, task); -} - -// static -bool SendMouseClick(MouseButton type) { - CHECK(g_ui_controls_enabled); - return instance_->SendMouseClick(type); -} - -// static -void RunClosureAfterAllPendingUIEvents(const base::Closure& closure) { - instance_->RunClosureAfterAllPendingUIEvents(closure); -} - -UIControlsAura::UIControlsAura() { -} - -UIControlsAura::~UIControlsAura() { -} - -// static. declared in ui_controls.h -void InstallUIControlsAura(UIControlsAura* instance) { - delete instance_; - instance_ = instance; -} - -} // namespace ui_controls
diff --git a/ui/base/test/ui_controls_aura.h b/ui/base/test/ui_controls_aura.h deleted file mode 100644 index 2224944..0000000 --- a/ui/base/test/ui_controls_aura.h +++ /dev/null
@@ -1,57 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_TEST_BASE_UI_CONTROLS_AURA_H_ -#define UI_TEST_BASE_UI_CONTROLS_AURA_H_ - -#include "base/callback_forward.h" -#include "ui/base/test/ui_controls.h" -#include "ui/events/keycodes/keyboard_codes.h" -#include "ui/gfx/native_widget_types.h" - -namespace ui_controls { - -// An interface to provide Aura implementation of UI control. -class UIControlsAura { - public: - UIControlsAura(); - virtual ~UIControlsAura(); - - virtual bool SendKeyPress(gfx::NativeWindow window, - ui::KeyboardCode key, - bool control, - bool shift, - bool alt, - bool command) = 0; - virtual bool SendKeyPressNotifyWhenDone(gfx::NativeWindow window, - ui::KeyboardCode key, - bool control, - bool shift, - bool alt, - bool command, - const base::Closure& task) = 0; - - // Simulate a mouse move. (x,y) are absolute screen coordinates. - virtual bool SendMouseMove(long x, long y) = 0; - virtual bool SendMouseMoveNotifyWhenDone(long x, - long y, - const base::Closure& task) = 0; - - // Sends a mouse down and/or up message. The click will be sent to wherever - // the cursor currently is, so be sure to move the cursor before calling this - // (and be sure the cursor has arrived!). - virtual bool SendMouseEvents(MouseButton type, int state) =0; - virtual bool SendMouseEventsNotifyWhenDone(MouseButton type, int state, - const base::Closure& task) = 0; - // Same as SendMouseEvents with BUTTON_UP | BUTTON_DOWN. - virtual bool SendMouseClick(MouseButton type) = 0; - - // Runs |closure| after processing all pending ui events. - virtual void RunClosureAfterAllPendingUIEvents( - const base::Closure& closure) = 0; -}; - -} // namespace ui_controls - -#endif // UI_TEST_BASE_UI_CONTROLS_AURA_H_
diff --git a/ui/base/test/ui_controls_internal_win.cc b/ui/base/test/ui_controls_internal_win.cc deleted file mode 100644 index 059c820..0000000 --- a/ui/base/test/ui_controls_internal_win.cc +++ /dev/null
@@ -1,344 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/test/ui_controls_internal_win.h" - -#include "base/bind.h" -#include "base/callback.h" -#include "base/logging.h" -#include "base/memory/ref_counted.h" -#include "base/message_loop/message_loop.h" -#include "ui/events/keycodes/keyboard_code_conversion_win.h" -#include "ui/events/keycodes/keyboard_codes.h" - -namespace { - -// InputDispatcher ------------------------------------------------------------ - -// InputDispatcher is used to listen for a mouse/keyboard event. When the -// appropriate event is received the task is notified. -class InputDispatcher : public base::RefCounted<InputDispatcher> { - public: - InputDispatcher(const base::Closure& task, WPARAM message_waiting_for); - - // Invoked from the hook. If mouse_message matches message_waiting_for_ - // MatchingMessageFound is invoked. - void DispatchedMessage(WPARAM mouse_message); - - // Invoked when a matching event is found. Uninstalls the hook and schedules - // an event that notifies the task. - void MatchingMessageFound(); - - private: - friend class base::RefCounted<InputDispatcher>; - - ~InputDispatcher(); - - // Notifies the task and release this (which should delete it). - void NotifyTask(); - - // The task we notify. - base::Closure task_; - - // Message we're waiting for. Not used for keyboard events. - const WPARAM message_waiting_for_; - - DISALLOW_COPY_AND_ASSIGN(InputDispatcher); -}; - -// Have we installed the hook? -bool installed_hook_ = false; - -// Return value from SetWindowsHookEx. -HHOOK next_hook_ = NULL; - -// If a hook is installed, this is the dispatcher. -InputDispatcher* current_dispatcher_ = NULL; - -// Callback from hook when a mouse message is received. -LRESULT CALLBACK MouseHook(int n_code, WPARAM w_param, LPARAM l_param) { - HHOOK next_hook = next_hook_; - if (n_code == HC_ACTION) { - DCHECK(current_dispatcher_); - current_dispatcher_->DispatchedMessage(w_param); - } - return CallNextHookEx(next_hook, n_code, w_param, l_param); -} - -// Callback from hook when a key message is received. -LRESULT CALLBACK KeyHook(int n_code, WPARAM w_param, LPARAM l_param) { - HHOOK next_hook = next_hook_; - if (n_code == HC_ACTION) { - DCHECK(current_dispatcher_); - if (l_param & (1 << 30)) { - // Only send on key up. - current_dispatcher_->MatchingMessageFound(); - } - } - return CallNextHookEx(next_hook, n_code, w_param, l_param); -} - -// Installs dispatcher as the current hook. -void InstallHook(InputDispatcher* dispatcher, bool key_hook) { - DCHECK(!installed_hook_); - current_dispatcher_ = dispatcher; - installed_hook_ = true; - if (key_hook) { - next_hook_ = SetWindowsHookEx(WH_KEYBOARD, &KeyHook, NULL, - GetCurrentThreadId()); - } else { - // NOTE: I originally tried WH_CALLWNDPROCRET, but for some reason I - // didn't get a mouse message like I do with MouseHook. - next_hook_ = SetWindowsHookEx(WH_MOUSE, &MouseHook, NULL, - GetCurrentThreadId()); - } - DCHECK(next_hook_); -} - -// Uninstalls the hook set in InstallHook. -void UninstallHook(InputDispatcher* dispatcher) { - if (current_dispatcher_ == dispatcher) { - installed_hook_ = false; - current_dispatcher_ = NULL; - UnhookWindowsHookEx(next_hook_); - } -} - -InputDispatcher::InputDispatcher(const base::Closure& task, - WPARAM message_waiting_for) - : task_(task), message_waiting_for_(message_waiting_for) { - InstallHook(this, message_waiting_for == WM_KEYUP); -} - -InputDispatcher::~InputDispatcher() { - // Make sure the hook isn't installed. - UninstallHook(this); -} - -void InputDispatcher::DispatchedMessage(WPARAM message) { - if (message == message_waiting_for_) - MatchingMessageFound(); -} - -void InputDispatcher::MatchingMessageFound() { - UninstallHook(this); - // At the time we're invoked the event has not actually been processed. - // Use PostTask to make sure the event has been processed before notifying. - base::MessageLoop::current()->PostTask( - FROM_HERE, base::Bind(&InputDispatcher::NotifyTask, this)); -} - -void InputDispatcher::NotifyTask() { - task_.Run(); - Release(); -} - -// Private functions ---------------------------------------------------------- - -// Populate the INPUT structure with the appropriate keyboard event -// parameters required by SendInput -bool FillKeyboardInput(ui::KeyboardCode key, INPUT* input, bool key_up) { - memset(input, 0, sizeof(INPUT)); - input->type = INPUT_KEYBOARD; - input->ki.wVk = ui::WindowsKeyCodeForKeyboardCode(key); - input->ki.dwFlags = key_up ? KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP : - KEYEVENTF_EXTENDEDKEY; - - return true; -} - -// Send a key event (up/down) -bool SendKeyEvent(ui::KeyboardCode key, bool up) { - INPUT input = { 0 }; - - if (!FillKeyboardInput(key, &input, up)) - return false; - - if (!::SendInput(1, &input, sizeof(INPUT))) - return false; - - return true; -} - -} // namespace - -namespace ui_controls { -namespace internal { - -bool SendKeyPressImpl(HWND window, - ui::KeyboardCode key, - bool control, - bool shift, - bool alt, - const base::Closure& task) { - // SendInput only works as we expect it if one of our windows is the - // foreground window already. - HWND target_window = (::GetActiveWindow() && - ::GetWindow(::GetActiveWindow(), GW_OWNER) == window) ? - ::GetActiveWindow() : - window; - if (window && ::GetForegroundWindow() != target_window) - return false; - - scoped_refptr<InputDispatcher> dispatcher( - !task.is_null() ? new InputDispatcher(task, WM_KEYUP) : NULL); - - // If a pop-up menu is open, it won't receive events sent using SendInput. - // Check for a pop-up menu using its window class (#32768) and if one - // exists, send the key event directly there. - HWND popup_menu = ::FindWindow(L"#32768", 0); - if (popup_menu != NULL && popup_menu == ::GetTopWindow(NULL)) { - WPARAM w_param = ui::WindowsKeyCodeForKeyboardCode(key); - LPARAM l_param = 0; - ::SendMessage(popup_menu, WM_KEYDOWN, w_param, l_param); - ::SendMessage(popup_menu, WM_KEYUP, w_param, l_param); - - if (dispatcher.get()) - dispatcher->AddRef(); - return true; - } - - INPUT input[8] = { 0 }; // 8, assuming all the modifiers are activated. - - UINT i = 0; - if (control) { - if (!FillKeyboardInput(ui::VKEY_CONTROL, &input[i], false)) - return false; - i++; - } - - if (shift) { - if (!FillKeyboardInput(ui::VKEY_SHIFT, &input[i], false)) - return false; - i++; - } - - if (alt) { - if (!FillKeyboardInput(ui::VKEY_LMENU, &input[i], false)) - return false; - i++; - } - - if (!FillKeyboardInput(key, &input[i], false)) - return false; - i++; - - if (!FillKeyboardInput(key, &input[i], true)) - return false; - i++; - - if (alt) { - if (!FillKeyboardInput(ui::VKEY_LMENU, &input[i], true)) - return false; - i++; - } - - if (shift) { - if (!FillKeyboardInput(ui::VKEY_SHIFT, &input[i], true)) - return false; - i++; - } - - if (control) { - if (!FillKeyboardInput(ui::VKEY_CONTROL, &input[i], true)) - return false; - i++; - } - - if (::SendInput(i, input, sizeof(INPUT)) != i) - return false; - - if (dispatcher.get()) - dispatcher->AddRef(); - - return true; -} - -bool SendMouseMoveImpl(long screen_x, - long screen_y, - const base::Closure& task) { - // First check if the mouse is already there. - POINT current_pos; - ::GetCursorPos(¤t_pos); - if (screen_x == current_pos.x && screen_y == current_pos.y) { - if (!task.is_null()) - base::MessageLoop::current()->PostTask(FROM_HERE, task); - return true; - } - - INPUT input = { 0 }; - - int screen_width = ::GetSystemMetrics(SM_CXSCREEN) - 1; - int screen_height = ::GetSystemMetrics(SM_CYSCREEN) - 1; - LONG pixel_x = static_cast<LONG>(screen_x * (65535.0f / screen_width)); - LONG pixel_y = static_cast<LONG>(screen_y * (65535.0f / screen_height)); - - input.type = INPUT_MOUSE; - input.mi.dwFlags = MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_MOVE; - input.mi.dx = pixel_x; - input.mi.dy = pixel_y; - - scoped_refptr<InputDispatcher> dispatcher( - !task.is_null() ? new InputDispatcher(task, WM_MOUSEMOVE) : NULL); - - if (!::SendInput(1, &input, sizeof(INPUT))) - return false; - - if (dispatcher.get()) - dispatcher->AddRef(); - - return true; -} - -bool SendMouseEventsImpl(MouseButton type, int state, - const base::Closure& task) { - DWORD down_flags = MOUSEEVENTF_ABSOLUTE; - DWORD up_flags = MOUSEEVENTF_ABSOLUTE; - UINT last_event; - - switch (type) { - case LEFT: - down_flags |= MOUSEEVENTF_LEFTDOWN; - up_flags |= MOUSEEVENTF_LEFTUP; - last_event = (state & UP) ? WM_LBUTTONUP : WM_LBUTTONDOWN; - break; - - case MIDDLE: - down_flags |= MOUSEEVENTF_MIDDLEDOWN; - up_flags |= MOUSEEVENTF_MIDDLEUP; - last_event = (state & UP) ? WM_MBUTTONUP : WM_MBUTTONDOWN; - break; - - case RIGHT: - down_flags |= MOUSEEVENTF_RIGHTDOWN; - up_flags |= MOUSEEVENTF_RIGHTUP; - last_event = (state & UP) ? WM_RBUTTONUP : WM_RBUTTONDOWN; - break; - - default: - NOTREACHED(); - return false; - } - - scoped_refptr<InputDispatcher> dispatcher( - !task.is_null() ? new InputDispatcher(task, last_event) : NULL); - - INPUT input = { 0 }; - input.type = INPUT_MOUSE; - input.mi.dwFlags = down_flags; - if ((state & DOWN) && !::SendInput(1, &input, sizeof(INPUT))) - return false; - - input.mi.dwFlags = up_flags; - if ((state & UP) && !::SendInput(1, &input, sizeof(INPUT))) - return false; - - if (dispatcher.get()) - dispatcher->AddRef(); - - return true; -} - -} // namespace internal -} // namespace ui_controls
diff --git a/ui/base/test/ui_controls_internal_win.h b/ui/base/test/ui_controls_internal_win.h deleted file mode 100644 index 1f7c54f..0000000 --- a/ui/base/test/ui_controls_internal_win.h +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_TEST_UI_CONTROLS_INTERNAL_WIN_H_ -#define UI_BASE_TEST_UI_CONTROLS_INTERNAL_WIN_H_ - -#include "base/callback_forward.h" -#include "ui/base/test/ui_controls.h" - -namespace ui_controls { -namespace internal { - -// A utility functions for windows to send key or mouse events and -// run the task. These functions are internal, but exported so that -// aura implementation can use these utility functions. -bool SendKeyPressImpl(HWND hwnd, - ui::KeyboardCode key, - bool control, - bool shift, - bool alt, - const base::Closure& task); -bool SendMouseMoveImpl(long screen_x, long screen_y, const base::Closure& task); -bool SendMouseEventsImpl(MouseButton type, - int state, - const base::Closure& task); -void RunClosureAfterAllPendingUITasksImpl(const base::Closure& task); - -} // namespace internal -} // namespace ui_controls - -#endif // UI_BASE_TEST_UI_CONTROLS_INTERNAL_WIN_H_
diff --git a/ui/base/test/ui_controls_mac.mm b/ui/base/test/ui_controls_mac.mm deleted file mode 100644 index cf2c239..0000000 --- a/ui/base/test/ui_controls_mac.mm +++ /dev/null
@@ -1,396 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/test/ui_controls.h" - -#import <Cocoa/Cocoa.h> -#include <mach/mach_time.h> -#include <vector> - -#include "base/bind.h" -#include "base/callback.h" -#include "base/message_loop/message_loop.h" -#include "ui/events/keycodes/keyboard_code_conversion_mac.h" - - -// Implementation details: We use [NSApplication sendEvent:] instead -// of [NSApplication postEvent:atStart:] so that the event gets sent -// immediately. This lets us run the post-event task right -// immediately as well. Unfortunately I cannot subclass NSEvent (it's -// probably a class cluster) to allow other easy answers. For -// example, if I could subclass NSEvent, I could run the Task in it's -// dealloc routine (which necessarily happens after the event is -// dispatched). Unlike Linux, Mac does not have message loop -// observer/notification. Unlike windows, I cannot post non-events -// into the event queue. (I can post other kinds of tasks but can't -// guarantee their order with regards to events). - -// But [NSApplication sendEvent:] causes a problem when sending mouse click -// events. Because in order to handle mouse drag, when processing a mouse -// click event, the application may want to retrieve the next event -// synchronously by calling NSApplication's nextEventMatchingMask method. -// In this case, [NSApplication sendEvent:] causes deadlock. -// So we need to use [NSApplication postEvent:atStart:] for mouse click -// events. In order to notify the caller correctly after all events has been -// processed, we setup a task to watch for the event queue time to time and -// notify the caller as soon as there is no event in the queue. -// -// TODO(suzhe): -// 1. Investigate why using [NSApplication postEvent:atStart:] for keyboard -// events causes BrowserKeyEventsTest.CommandKeyEvents to fail. -// See http://crbug.com/49270 -// 2. On OSX 10.6, [NSEvent addLocalMonitorForEventsMatchingMask:handler:] may -// be used, so that we don't need to poll the event queue time to time. - -namespace { - -// Stores the current mouse location on the screen. So that we can use it -// when firing keyboard and mouse click events. -NSPoint g_mouse_location = { 0, 0 }; - -bool g_ui_controls_enabled = false; - -// From -// http://stackoverflow.com/questions/1597383/cgeventtimestamp-to-nsdate -// Which credits Apple sample code for this routine. -uint64_t UpTimeInNanoseconds(void) { - uint64_t time; - uint64_t timeNano; - static mach_timebase_info_data_t sTimebaseInfo; - - time = mach_absolute_time(); - - // Convert to nanoseconds. - - // If this is the first time we've run, get the timebase. - // We can use denom == 0 to indicate that sTimebaseInfo is - // uninitialised because it makes no sense to have a zero - // denominator is a fraction. - if (sTimebaseInfo.denom == 0) { - (void) mach_timebase_info(&sTimebaseInfo); - } - - // This could overflow; for testing needs we probably don't care. - timeNano = time * sTimebaseInfo.numer / sTimebaseInfo.denom; - return timeNano; -} - -NSTimeInterval TimeIntervalSinceSystemStartup() { - return UpTimeInNanoseconds() / 1000000000.0; -} - -// Creates and returns an autoreleased key event. -NSEvent* SynthesizeKeyEvent(NSWindow* window, - bool keyDown, - ui::KeyboardCode keycode, - NSUInteger flags) { - unichar character; - unichar characterIgnoringModifiers; - int macKeycode = ui::MacKeyCodeForWindowsKeyCode( - keycode, flags, &character, &characterIgnoringModifiers); - - if (macKeycode < 0) - return nil; - - NSString* charactersIgnoringModifiers = - [[[NSString alloc] initWithCharacters:&characterIgnoringModifiers - length:1] - autorelease]; - NSString* characters = - [[[NSString alloc] initWithCharacters:&character length:1] autorelease]; - - NSEventType type = (keyDown ? NSKeyDown : NSKeyUp); - - // Modifier keys generate NSFlagsChanged event rather than - // NSKeyDown/NSKeyUp events. - if (keycode == ui::VKEY_CONTROL || keycode == ui::VKEY_SHIFT || - keycode == ui::VKEY_MENU || keycode == ui::VKEY_COMMAND) - type = NSFlagsChanged; - - // For events other than mouse moved, [event locationInWindow] is - // UNDEFINED if the event is not NSMouseMoved. Thus, the (0,0) - // location should be fine. - NSEvent* event = - [NSEvent keyEventWithType:type - location:NSZeroPoint - modifierFlags:flags - timestamp:TimeIntervalSinceSystemStartup() - windowNumber:[window windowNumber] - context:nil - characters:characters - charactersIgnoringModifiers:charactersIgnoringModifiers - isARepeat:NO - keyCode:(unsigned short)macKeycode]; - - return event; -} - -// Creates the proper sequence of autoreleased key events for a key down + up. -void SynthesizeKeyEventsSequence(NSWindow* window, - ui::KeyboardCode keycode, - bool control, - bool shift, - bool alt, - bool command, - std::vector<NSEvent*>* events) { - NSEvent* event = nil; - NSUInteger flags = 0; - if (control) { - flags |= NSControlKeyMask; - event = SynthesizeKeyEvent(window, true, ui::VKEY_CONTROL, flags); - DCHECK(event); - events->push_back(event); - } - if (shift) { - flags |= NSShiftKeyMask; - event = SynthesizeKeyEvent(window, true, ui::VKEY_SHIFT, flags); - DCHECK(event); - events->push_back(event); - } - if (alt) { - flags |= NSAlternateKeyMask; - event = SynthesizeKeyEvent(window, true, ui::VKEY_MENU, flags); - DCHECK(event); - events->push_back(event); - } - if (command) { - flags |= NSCommandKeyMask; - event = SynthesizeKeyEvent(window, true, ui::VKEY_COMMAND, flags); - DCHECK(event); - events->push_back(event); - } - - event = SynthesizeKeyEvent(window, true, keycode, flags); - DCHECK(event); - events->push_back(event); - event = SynthesizeKeyEvent(window, false, keycode, flags); - DCHECK(event); - events->push_back(event); - - if (command) { - flags &= ~NSCommandKeyMask; - event = SynthesizeKeyEvent(window, false, ui::VKEY_COMMAND, flags); - DCHECK(event); - events->push_back(event); - } - if (alt) { - flags &= ~NSAlternateKeyMask; - event = SynthesizeKeyEvent(window, false, ui::VKEY_MENU, flags); - DCHECK(event); - events->push_back(event); - } - if (shift) { - flags &= ~NSShiftKeyMask; - event = SynthesizeKeyEvent(window, false, ui::VKEY_SHIFT, flags); - DCHECK(event); - events->push_back(event); - } - if (control) { - flags &= ~NSControlKeyMask; - event = SynthesizeKeyEvent(window, false, ui::VKEY_CONTROL, flags); - DCHECK(event); - events->push_back(event); - } -} - -// A helper function to watch for the event queue. The specific task will be -// fired when there is no more event in the queue. -void EventQueueWatcher(const base::Closure& task) { - NSEvent* event = [NSApp nextEventMatchingMask:NSAnyEventMask - untilDate:nil - inMode:NSDefaultRunLoopMode - dequeue:NO]; - // If there is still event in the queue, then we need to check again. - if (event) { - base::MessageLoop::current()->PostTask( - FROM_HERE, - base::Bind(&EventQueueWatcher, task)); - } else { - base::MessageLoop::current()->PostTask(FROM_HERE, task); - } -} - -// Returns the NSWindow located at |g_mouse_location|. NULL if there is no -// window there, or if the window located there is not owned by the application. -// On Mac, unless dragging, mouse events are sent to the window under the -// cursor. Note that the OS will ignore transparent windows and windows that -// explicitly ignore mouse events. -NSWindow* WindowAtCurrentMouseLocation() { - NSInteger window_number = [NSWindow windowNumberAtPoint:g_mouse_location - belowWindowWithWindowNumber:0]; - return - [[NSApplication sharedApplication] windowWithWindowNumber:window_number]; -} - -} // namespace - -namespace ui_controls { - -void EnableUIControls() { - g_ui_controls_enabled = true; -} - -bool SendKeyPress(gfx::NativeWindow window, - ui::KeyboardCode key, - bool control, - bool shift, - bool alt, - bool command) { - CHECK(g_ui_controls_enabled); - return SendKeyPressNotifyWhenDone(window, key, - control, shift, alt, command, - base::Closure()); -} - -// Win and Linux implement a SendKeyPress() this as a -// SendKeyPressAndRelease(), so we should as well (despite the name). -bool SendKeyPressNotifyWhenDone(gfx::NativeWindow window, - ui::KeyboardCode key, - bool control, - bool shift, - bool alt, - bool command, - const base::Closure& task) { - CHECK(g_ui_controls_enabled); - DCHECK(base::MessageLoopForUI::IsCurrent()); - - std::vector<NSEvent*> events; - SynthesizeKeyEventsSequence( - window, key, control, shift, alt, command, &events); - - // TODO(suzhe): Using [NSApplication postEvent:atStart:] here causes - // BrowserKeyEventsTest.CommandKeyEvents to fail. See http://crbug.com/49270 - // But using [NSApplication sendEvent:] should be safe for keyboard events, - // because until now, no code wants to retrieve the next event when handling - // a keyboard event. - for (std::vector<NSEvent*>::iterator iter = events.begin(); - iter != events.end(); ++iter) - [[NSApplication sharedApplication] sendEvent:*iter]; - - if (!task.is_null()) { - base::MessageLoop::current()->PostTask( - FROM_HERE, base::Bind(&EventQueueWatcher, task)); - } - - return true; -} - -bool SendMouseMove(long x, long y) { - CHECK(g_ui_controls_enabled); - return SendMouseMoveNotifyWhenDone(x, y, base::Closure()); -} - -// Input position is in screen coordinates. However, NSMouseMoved -// events require them window-relative, so we adjust. We *DO* flip -// the coordinate space, so input events can be the same for all -// platforms. E.g. (0,0) is upper-left. -bool SendMouseMoveNotifyWhenDone(long x, long y, const base::Closure& task) { - CHECK(g_ui_controls_enabled); - CGFloat screenHeight = - [[[NSScreen screens] objectAtIndex:0] frame].size.height; - g_mouse_location = NSMakePoint(x, screenHeight - y); // flip! - - NSWindow* window = WindowAtCurrentMouseLocation(); - - NSPoint pointInWindow = g_mouse_location; - if (window) - pointInWindow = [window convertScreenToBase:pointInWindow]; - NSTimeInterval timestamp = TimeIntervalSinceSystemStartup(); - - NSEvent* event = - [NSEvent mouseEventWithType:NSMouseMoved - location:pointInWindow - modifierFlags:0 - timestamp:timestamp - windowNumber:[window windowNumber] - context:nil - eventNumber:0 - clickCount:0 - pressure:0.0]; - [[NSApplication sharedApplication] postEvent:event atStart:NO]; - - if (!task.is_null()) { - base::MessageLoop::current()->PostTask( - FROM_HERE, base::Bind(&EventQueueWatcher, task)); - } - - return true; -} - -bool SendMouseEvents(MouseButton type, int state) { - CHECK(g_ui_controls_enabled); - return SendMouseEventsNotifyWhenDone(type, state, base::Closure()); -} - -bool SendMouseEventsNotifyWhenDone(MouseButton type, int state, - const base::Closure& task) { - CHECK(g_ui_controls_enabled); - // On windows it appears state can be (UP|DOWN). It is unclear if - // that'll happen here but prepare for it just in case. - if (state == (UP|DOWN)) { - return (SendMouseEventsNotifyWhenDone(type, DOWN, base::Closure()) && - SendMouseEventsNotifyWhenDone(type, UP, task)); - } - NSEventType etype = 0; - if (type == LEFT) { - if (state == UP) { - etype = NSLeftMouseUp; - } else { - etype = NSLeftMouseDown; - } - } else if (type == MIDDLE) { - if (state == UP) { - etype = NSOtherMouseUp; - } else { - etype = NSOtherMouseDown; - } - } else if (type == RIGHT) { - if (state == UP) { - etype = NSRightMouseUp; - } else { - etype = NSRightMouseDown; - } - } else { - return false; - } - NSWindow* window = WindowAtCurrentMouseLocation(); - NSPoint pointInWindow = g_mouse_location; - if (window) - pointInWindow = [window convertScreenToBase:pointInWindow]; - - NSEvent* event = - [NSEvent mouseEventWithType:etype - location:pointInWindow - modifierFlags:0 - timestamp:TimeIntervalSinceSystemStartup() - windowNumber:[window windowNumber] - context:nil - eventNumber:0 - clickCount:1 - pressure:(state == DOWN ? 1.0 : 0.0 )]; - [[NSApplication sharedApplication] postEvent:event atStart:NO]; - - if (!task.is_null()) { - base::MessageLoop::current()->PostTask( - FROM_HERE, base::Bind(&EventQueueWatcher, task)); - } - - return true; -} - -bool SendMouseClick(MouseButton type) { - CHECK(g_ui_controls_enabled); - return SendMouseEventsNotifyWhenDone(type, UP|DOWN, base::Closure()); -} - -void RunClosureAfterAllPendingUIEvents(const base::Closure& closure) { - base::MessageLoop::current()->PostTask( - FROM_HERE, base::Bind(&EventQueueWatcher, closure)); -} - -bool IsFullKeyboardAccessEnabled() { - return [NSApp isFullKeyboardAccessEnabled]; -} - -} // namespace ui_controls
diff --git a/ui/base/test/ui_controls_win.cc b/ui/base/test/ui_controls_win.cc deleted file mode 100644 index fc3f6ea..0000000 --- a/ui/base/test/ui_controls_win.cc +++ /dev/null
@@ -1,74 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/test/ui_controls.h" - -#include "base/callback.h" -#include "base/message_loop/message_loop.h" -#include "ui/base/test/ui_controls_internal_win.h" -#include "ui/gfx/point.h" - -namespace ui_controls { -bool g_ui_controls_enabled = false; - -void EnableUIControls() { - g_ui_controls_enabled = true; -} - -bool SendKeyPress(gfx::NativeWindow window, - ui::KeyboardCode key, - bool control, - bool shift, - bool alt, - bool command) { - CHECK(g_ui_controls_enabled); - DCHECK(!command); // No command key on Windows - return internal::SendKeyPressImpl(window, key, control, shift, alt, - base::Closure()); -} - -bool SendKeyPressNotifyWhenDone(gfx::NativeWindow window, - ui::KeyboardCode key, - bool control, - bool shift, - bool alt, - bool command, - const base::Closure& task) { - CHECK(g_ui_controls_enabled); - DCHECK(!command); // No command key on Windows - return internal::SendKeyPressImpl(window, key, control, shift, alt, task); -} - -bool SendMouseMove(long x, long y) { - CHECK(g_ui_controls_enabled); - return internal::SendMouseMoveImpl(x, y, base::Closure()); -} - -bool SendMouseMoveNotifyWhenDone(long x, long y, const base::Closure& task) { - CHECK(g_ui_controls_enabled); - return internal::SendMouseMoveImpl(x, y, task); -} - -bool SendMouseEvents(MouseButton type, int state) { - CHECK(g_ui_controls_enabled); - return internal::SendMouseEventsImpl(type, state, base::Closure()); -} - -bool SendMouseEventsNotifyWhenDone(MouseButton type, int state, - const base::Closure& task) { - CHECK(g_ui_controls_enabled); - return internal::SendMouseEventsImpl(type, state, task); -} - -bool SendMouseClick(MouseButton type) { - CHECK(g_ui_controls_enabled); - return internal::SendMouseEventsImpl(type, UP | DOWN, base::Closure()); -} - -void RunClosureAfterAllPendingUIEvents(const base::Closure& closure) { - // On windows, posting UI events is synchronous so just post the closure. - base::MessageLoopForUI::current()->PostTask(FROM_HERE, closure); -} - -} // namespace ui_controls
diff --git a/ui/base/theme_provider.cc b/ui/base/theme_provider.cc deleted file mode 100644 index a32c7aa..0000000 --- a/ui/base/theme_provider.cc +++ /dev/null
@@ -1,16 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/theme_provider.h" - -namespace ui { - -// We have the destructor here because GCC puts the vtable in the first file -// that includes a virtual function of the class. Leaving it just in the .h file -// means that GCC will fail to link. - -ThemeProvider::~ThemeProvider() { -} - -} // namespace ui
diff --git a/ui/base/theme_provider.h b/ui/base/theme_provider.h deleted file mode 100644 index eeab83d..0000000 --- a/ui/base/theme_provider.h +++ /dev/null
@@ -1,101 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_THEME_PROVIDER_H_ -#define UI_BASE_THEME_PROVIDER_H_ - -#include "base/basictypes.h" -#include "third_party/skia/include/core/SkColor.h" -#include "ui/base/layout.h" -#include "ui/base/ui_base_export.h" - -#if defined(OS_MACOSX) -#ifdef __OBJC__ -@class NSColor; -@class NSGradient; -@class NSImage; -#else -class NSColor; -class NSGradient; -class NSImage; -#endif // __OBJC__ -#endif // OS_* - -class SkBitmap; - -namespace base { -class RefCountedMemory; -} - -namespace gfx { -class ImageSkia; -} - -namespace ui { - -//////////////////////////////////////////////////////////////////////////////// -// -// ThemeProvider -// -// ThemeProvider is an abstract class that defines the API that should be -// implemented to provide bitmaps and color information for a given theme. -// -//////////////////////////////////////////////////////////////////////////////// - -class UI_BASE_EXPORT ThemeProvider { - public: - virtual ~ThemeProvider(); - - // Whether we're using the system theme (which may or may not be the - // same as the default theme). - virtual bool UsingSystemTheme() const = 0; - - // Get the image specified by |id|. An implementation of ThemeProvider should - // have its own source of ids (e.g. an enum, or external resource bundle). - virtual gfx::ImageSkia* GetImageSkiaNamed(int id) const = 0; - - // Get the color specified by |id|. - virtual SkColor GetColor(int id) const = 0; - - // Get the property (e.g. an alignment expressed in an enum, or a width or - // height) specified by |id|. - virtual int GetDisplayProperty(int id) const = 0; - - // Whether we should use the native system frame (typically Aero glass) or - // a custom frame. - virtual bool ShouldUseNativeFrame() const = 0; - - // Whether or not we have a certain image. Used for when the default theme - // doesn't provide a certain image, but custom themes might (badges, etc). - virtual bool HasCustomImage(int id) const = 0; - - // Reads the image data from the theme file into the specified vector. Only - // valid for un-themed resources and the themed IDR_THEME_NTP_* in most - // implementations of ThemeProvider. Returns NULL on error. - virtual base::RefCountedMemory* GetRawData( - int id, - ui::ScaleFactor scale_factor) const = 0; - -#if defined(OS_MACOSX) - // Gets the NSImage with the specified |id|. - virtual NSImage* GetNSImageNamed(int id) const = 0; - - // Gets the NSImage that GetNSImageNamed (above) would return, but returns it - // as a pattern color. - virtual NSColor* GetNSImageColorNamed(int id) const = 0; - - // Gets the NSColor with the specified |id|. - virtual NSColor* GetNSColor(int id) const = 0; - - // Gets the NSColor for tinting with the specified |id|. - virtual NSColor* GetNSColorTint(int id) const = 0; - - // Gets the NSGradient with the specified |id|. - virtual NSGradient* GetNSGradient(int id) const = 0; -#endif -}; - -} // namespace ui - -#endif // UI_BASE_THEME_PROVIDER_H_
diff --git a/ui/base/touch/touch_device_ozone.cc b/ui/base/touch/touch_device_ozone.cc deleted file mode 100644 index ec5a6b7..0000000 --- a/ui/base/touch/touch_device_ozone.cc +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/touch/touch_device.h" - -namespace ui { - -bool IsTouchDevicePresent() { - // TODO(sadrul@chromium.org): Support evdev hotplugging. - return true; -} - -int MaxTouchPoints() { - // Hard-code this to 11 until we have a real implementation. - return 11; -} - -} // namespace ui
diff --git a/ui/base/touch/touch_editing_controller.cc b/ui/base/touch/touch_editing_controller.cc deleted file mode 100644 index 1b84ed9..0000000 --- a/ui/base/touch/touch_editing_controller.cc +++ /dev/null
@@ -1,26 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/touch/touch_editing_controller.h" - -namespace ui { - -namespace { -TouchSelectionControllerFactory* g_shared_instance = NULL; -} // namespace - -TouchSelectionController* TouchSelectionController::create( - TouchEditable* client_view) { - if (g_shared_instance) - return g_shared_instance->create(client_view); - return NULL; -} - -// static -void TouchSelectionControllerFactory::SetInstance( - TouchSelectionControllerFactory* instance) { - g_shared_instance = instance; -} - -} // namespace ui
diff --git a/ui/base/touch/touch_editing_controller.h b/ui/base/touch/touch_editing_controller.h deleted file mode 100644 index 00d8d49..0000000 --- a/ui/base/touch/touch_editing_controller.h +++ /dev/null
@@ -1,99 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_TOUCH_TOUCH_EDITING_CONTROLLER_H_ -#define UI_BASE_TOUCH_TOUCH_EDITING_CONTROLLER_H_ - -#include "ui/base/models/simple_menu_model.h" -#include "ui/gfx/point.h" -#include "ui/gfx/rect.h" - -namespace ui { - -// An interface implemented by widget that has text that can be selected/edited -// using touch. -class UI_BASE_EXPORT TouchEditable : public ui::SimpleMenuModel::Delegate { - public: - // TODO(mohsen): Consider switching from local coordinates to screen - // coordinates in this interface and see if it will simplify things. - - // Select everything between start and end (points are in view's local - // coordinate system). |start| is the logical start and |end| is the logical - // end of selection. Visually, |start| may lie after |end|. - virtual void SelectRect(const gfx::Point& start, const gfx::Point& end) = 0; - - // Move the caret to |point|. |point| is in local coordinates. - virtual void MoveCaretTo(const gfx::Point& point) = 0; - - // Gets the end points of the current selection. The end points p1 and p2 must - // be the cursor rect for the start and end of selection (in local - // coordinates): - // ____________________________________ - // | textfield with |selected text| | - // ------------------------------------ - // ^p1 ^p2 - // - // p1 should be the logical start and p2 the logical end of selection. Hence, - // visually, p1 could be to the right of p2 in the figure above. - virtual void GetSelectionEndPoints(gfx::Rect* p1, gfx::Rect* p2) = 0; - - // Gets the bounds of the client view in its local coordinates. - virtual gfx::Rect GetBounds() = 0; - - // Gets the NativeView hosting the client. - virtual gfx::NativeView GetNativeView() const = 0; - - // Converts a point to/from screen coordinates from/to client view. - virtual void ConvertPointToScreen(gfx::Point* point) = 0; - virtual void ConvertPointFromScreen(gfx::Point* point) = 0; - - // Returns true if the editable draws its own handles (hence, the - // TouchSelectionController need not draw handles). - virtual bool DrawsHandles() = 0; - - // Tells the editable to open context menu. - virtual void OpenContextMenu(const gfx::Point& anchor) = 0; - - // Tells the editable to end touch editing and destroy touch selection - // controller it owns. - virtual void DestroyTouchSelection() = 0; - - protected: - ~TouchEditable() override {} -}; - -// This defines the callback interface for other code to be notified of changes -// in the state of a TouchEditable. -class UI_BASE_EXPORT TouchSelectionController { - public: - virtual ~TouchSelectionController() {} - - // Creates a TouchSelectionController. Caller owns the returned object. - static TouchSelectionController* create( - TouchEditable* client_view); - - // Notifies the controller that the selection has changed. - virtual void SelectionChanged() = 0; - - // Returns true if the user is currently dragging one of the handles. - virtual bool IsHandleDragInProgress() = 0; - - // Hides visible handles. According to the value of |quick|, handles might - // fade out quickly or slowly. - virtual void HideHandles(bool quick) = 0; -}; - -class UI_BASE_EXPORT TouchSelectionControllerFactory { - public: - static void SetInstance(TouchSelectionControllerFactory* instance); - - virtual TouchSelectionController* create(TouchEditable* client_view) = 0; - - protected: - virtual ~TouchSelectionControllerFactory() {} -}; - -} // namespace views - -#endif // UI_BASE_TOUCH_TOUCH_EDITING_CONTROLLER_H_
diff --git a/ui/base/ui_base.gyp b/ui/base/ui_base.gyp index 4655712..c4f94f0 100644 --- a/ui/base/ui_base.gyp +++ b/ui/base/ui_base.gyp
@@ -56,8 +56,6 @@ 'android/window_android.h', 'android/window_android_compositor.h', 'android/window_android_observer.h', - 'base_window.cc', - 'base_window.h', 'clipboard/clipboard.cc', 'clipboard/clipboard.h', 'clipboard/clipboard_android.cc', @@ -133,26 +131,14 @@ 'cursor/cursor.h', 'cursor/cursor_android.cc', 'cursor/cursor_loader.h', - 'cursor/cursor_loader_ozone.cc', - 'cursor/cursor_loader_ozone.h', 'cursor/cursor_loader_win.cc', 'cursor/cursor_loader_win.h', 'cursor/cursor_loader_x11.cc', 'cursor/cursor_loader_x11.h', - 'cursor/cursor_ozone.cc', 'cursor/cursor_util.cc', 'cursor/cursor_util.h', 'cursor/cursor_win.cc', 'cursor/cursor_x11.cc', - 'cursor/cursors_aura.cc', - 'cursor/cursors_aura.h', - 'cursor/image_cursors.cc', - 'cursor/image_cursors.h', - 'cursor/ozone/bitmap_cursor_factory_ozone.cc', - 'cursor/ozone/bitmap_cursor_factory_ozone.h', - 'default_theme_provider.cc', - 'default_theme_provider.h', - 'default_theme_provider_mac.mm', 'device_form_factor_android.cc', 'device_form_factor_android.h', 'device_form_factor_desktop.cc', @@ -296,8 +282,6 @@ 'models/tree_model.h', 'models/tree_node_iterator.h', 'models/tree_node_model.h', - 'nine_image_painter_factory.cc', - 'nine_image_painter_factory.h', 'page_transition_types.cc', 'page_transition_types.h', 'page_transition_types_list.h', @@ -316,16 +300,11 @@ 'resource/resource_handle.h', 'text/bytes_formatting.cc', 'text/bytes_formatting.h', - 'theme_provider.cc', - 'theme_provider.h', 'touch/touch_device.cc', 'touch/touch_device.h', 'touch/touch_device_android.cc', 'touch/touch_device_aurax11.cc', - 'touch/touch_device_ozone.cc', 'touch/touch_device_win.cc', - 'touch/touch_editing_controller.cc', - 'touch/touch_editing_controller.h', 'touch/touch_enabled.cc', 'touch/touch_enabled.h', 'ui_base_export.h', @@ -443,11 +422,6 @@ 'resource/resource_bundle_auralinux.cc', ], }], - ['use_ozone==1', { - 'dependencies': [ - '../ozone/ozone.gyp:ozone_base', - ], - }], ['use_aura==1 and OS=="win"', { 'sources/': [ ['exclude', 'dragdrop/drag_utils_aura.cc'], @@ -472,8 +446,6 @@ 'sources/': [ ['include', '^dragdrop/os_exchange_data.cc'], ['include', '^dragdrop/os_exchange_data.h'], - ['include', '^nine_image_painter_factory.cc'], - ['include', '^nine_image_painter_factory.h'], ], }], ], @@ -553,8 +525,6 @@ '../../third_party/mozilla/mozilla.gyp:mozilla', ], 'sources!': [ - 'cursor/image_cursors.cc', - 'cursor/image_cursors.h', 'dragdrop/drag_utils.cc', 'dragdrop/drag_utils.h', ], @@ -581,30 +551,10 @@ '../events/platform/x11/x11_events_platform.gyp:x11_events_platform', ], }], - ['toolkit_views==0', { - 'sources!': [ - 'dragdrop/drag_drop_types.h', - 'dragdrop/drop_target_event.cc', - 'dragdrop/drop_target_event.h', - 'dragdrop/os_exchange_data.cc', - 'dragdrop/os_exchange_data.h', - 'nine_image_painter_factory.cc', - 'nine_image_painter_factory.h', - ], - }], ['OS=="android"', { 'sources!': [ - 'cursor/image_cursors.cc', - 'cursor/image_cursors.h', - 'default_theme_provider.cc', - 'dragdrop/drag_utils.cc', - 'dragdrop/drag_utils.h', 'l10n/l10n_font_util.cc', - 'models/button_menu_item_model.cc', - 'models/dialog_model.cc', - 'theme_provider.cc', 'touch/touch_device.cc', - 'touch/touch_editing_controller.cc', 'ui_base_types.cc', ], 'dependencies': [ @@ -672,19 +622,6 @@ 'ime/input_method_imm32.h', ], }], - ['use_aura==0 or (desktop_linux==0 and use_ozone==0)', { - 'sources!': [ - 'ime/input_method_auralinux.cc', - 'ime/input_method_auralinux.h', - 'ime/linux/fake_input_method_context.cc', - 'ime/linux/fake_input_method_context.h', - 'ime/linux/fake_input_method_context_factory.cc', - 'ime/linux/fake_input_method_context_factory.h', - 'ime/linux/linux_input_method_context.h', - 'ime/linux/linux_input_method_context_factory.cc', - 'ime/linux/linux_input_method_context_factory.h', - ], - }], ['use_x11==0', { 'sources!': [ 'ime/composition_text_util_pango.cc',
diff --git a/ui/base/ui_base_exports.cc b/ui/base/ui_base_exports.cc deleted file mode 100644 index 8b60d49..0000000 --- a/ui/base/ui_base_exports.cc +++ /dev/null
@@ -1,13 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// This file is for including headers that are not included in any other .cc -// files contained with the ui module. We need to include these here so that -// linker will know to include the symbols, defined by these headers, in the -// resulting dynamic library (ui.dll). - -#include "ui/base/accelerators/accelerator.h" -#include "ui/base/models/combobox_model_observer.h" -#include "ui/base/models/list_model_observer.h" -#include "ui/base/models/table_model_observer.h"
diff --git a/ui/base/ui_base_switches_util.cc b/ui/base/ui_base_switches_util.cc index cc4bf74..3d4c2a2 100644 --- a/ui/base/ui_base_switches_util.cc +++ b/ui/base/ui_base_switches_util.cc
@@ -27,13 +27,8 @@ } bool IsTouchEditingEnabled() { -#if defined(USE_AURA) - return !CommandLine::ForCurrentProcess()->HasSwitch( - switches::kDisableTouchEditing); -#else return CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableTouchEditing); -#endif } bool IsTouchFeedbackEnabled() {
diff --git a/ui/base/view_prop.h b/ui/base/view_prop.h index 3ce14ba..f042962 100644 --- a/ui/base/view_prop.h +++ b/ui/base/view_prop.h
@@ -10,8 +10,8 @@ #include "ui/base/ui_base_export.h" #include "ui/gfx/native_widget_types.h" -#if !defined(OS_WIN) && !defined(USE_AURA) -#error view_prop.h is only for windows and aura builds. +#if !defined(OS_WIN) +#error view_prop.h is only for windows builds. #endif namespace ui {
diff --git a/ui/base/x/selection_owner.cc b/ui/base/x/selection_owner.cc deleted file mode 100644 index b2b44c9..0000000 --- a/ui/base/x/selection_owner.cc +++ /dev/null
@@ -1,384 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/x/selection_owner.h" - -#include <algorithm> -#include <X11/Xlib.h> -#include <X11/Xatom.h> - -#include "base/logging.h" -#include "ui/base/x/selection_utils.h" -#include "ui/base/x/x11_foreign_window_manager.h" -#include "ui/base/x/x11_util.h" - -namespace ui { - -namespace { - -const char kAtomPair[] = "ATOM_PAIR"; -const char kIncr[] = "INCR"; -const char kMultiple[] = "MULTIPLE"; -const char kSaveTargets[] = "SAVE_TARGETS"; -const char kTargets[] = "TARGETS"; - -const char* kAtomsToCache[] = { - kAtomPair, - kIncr, - kMultiple, - kSaveTargets, - kTargets, - NULL -}; - -// The period of |incremental_transfer_abort_timer_|. Arbitrary but must be <= -// than kIncrementalTransferTimeoutMs. -const int kTimerPeriodMs = 1000; - -// The amount of time to wait for the selection requestor to process the data -// sent by the selection owner before aborting an incremental data transfer. -const int kIncrementalTransferTimeoutMs = 10000; - -COMPILE_ASSERT(kTimerPeriodMs <= kIncrementalTransferTimeoutMs, - timer_period_must_be_less_or_equal_to_transfer_timeout); - -// Returns a conservative max size of the data we can pass into -// XChangeProperty(). Copied from GTK. -size_t GetMaxRequestSize(XDisplay* display) { - long extended_max_size = XExtendedMaxRequestSize(display); - long max_size = - (extended_max_size ? extended_max_size : XMaxRequestSize(display)) - 100; - return std::min(static_cast<long>(0x40000), - std::max(static_cast<long>(0), max_size)); -} - -// Gets the value of an atom pair array property. On success, true is returned -// and the value is stored in |value|. -bool GetAtomPairArrayProperty(XID window, - XAtom property, - std::vector<std::pair<XAtom,XAtom> >* value) { - XAtom type = None; - int format = 0; // size in bits of each item in 'property' - unsigned long num_items = 0; - unsigned char* properties = NULL; - unsigned long remaining_bytes = 0; - - int result = XGetWindowProperty(gfx::GetXDisplay(), - window, - property, - 0, // offset into property data to - // read - (~0L), // entire array - False, // deleted - AnyPropertyType, - &type, - &format, - &num_items, - &remaining_bytes, - &properties); - - if (result != Success) - return false; - - // GTK does not require |type| to be kAtomPair. - if (format != 32 || num_items % 2 != 0) { - XFree(properties); - return false; - } - - XAtom* atom_properties = reinterpret_cast<XAtom*>(properties); - value->clear(); - for (size_t i = 0; i < num_items; i+=2) - value->push_back(std::make_pair(atom_properties[i], atom_properties[i+1])); - XFree(properties); - return true; -} - -} // namespace - -SelectionOwner::SelectionOwner(XDisplay* x_display, - XID x_window, - XAtom selection_name) - : x_display_(x_display), - x_window_(x_window), - selection_name_(selection_name), - max_request_size_(GetMaxRequestSize(x_display)), - atom_cache_(x_display_, kAtomsToCache) { -} - -SelectionOwner::~SelectionOwner() { - // If we are the selection owner, we need to release the selection so we - // don't receive further events. However, we don't call ClearSelectionOwner() - // because we don't want to do this indiscriminately. - if (XGetSelectionOwner(x_display_, selection_name_) == x_window_) - XSetSelectionOwner(x_display_, selection_name_, None, CurrentTime); -} - -void SelectionOwner::RetrieveTargets(std::vector<XAtom>* targets) { - for (SelectionFormatMap::const_iterator it = format_map_.begin(); - it != format_map_.end(); ++it) { - targets->push_back(it->first); - } -} - -void SelectionOwner::TakeOwnershipOfSelection( - const SelectionFormatMap& data) { - XSetSelectionOwner(x_display_, selection_name_, x_window_, CurrentTime); - - if (XGetSelectionOwner(x_display_, selection_name_) == x_window_) { - // The X server agrees that we are the selection owner. Commit our data. - format_map_ = data; - } -} - -void SelectionOwner::ClearSelectionOwner() { - XSetSelectionOwner(x_display_, selection_name_, None, CurrentTime); - format_map_ = SelectionFormatMap(); -} - -void SelectionOwner::OnSelectionRequest(const XEvent& event) { - XID requestor = event.xselectionrequest.requestor; - XAtom requested_target = event.xselectionrequest.target; - XAtom requested_property = event.xselectionrequest.property; - - // Incrementally build our selection. By default this is a refusal, and we'll - // override the parts indicating success in the different cases. - XEvent reply; - reply.xselection.type = SelectionNotify; - reply.xselection.requestor = requestor; - reply.xselection.selection = event.xselectionrequest.selection; - reply.xselection.target = requested_target; - reply.xselection.property = None; // Indicates failure - reply.xselection.time = event.xselectionrequest.time; - - if (requested_target == atom_cache_.GetAtom(kMultiple)) { - // The contents of |requested_property| should be a list of - // <target,property> pairs. - std::vector<std::pair<XAtom,XAtom> > conversions; - if (GetAtomPairArrayProperty(requestor, - requested_property, - &conversions)) { - std::vector<XAtom> conversion_results; - for (size_t i = 0; i < conversions.size(); ++i) { - bool conversion_successful = ProcessTarget(conversions[i].first, - requestor, - conversions[i].second); - conversion_results.push_back(conversions[i].first); - conversion_results.push_back( - conversion_successful ? conversions[i].second : None); - } - - // Set the property to indicate which conversions succeeded. This matches - // what GTK does. - XChangeProperty( - x_display_, - requestor, - requested_property, - atom_cache_.GetAtom(kAtomPair), - 32, - PropModeReplace, - reinterpret_cast<const unsigned char*>(&conversion_results.front()), - conversion_results.size()); - - reply.xselection.property = requested_property; - } - } else { - if (ProcessTarget(requested_target, requestor, requested_property)) - reply.xselection.property = requested_property; - } - - // Send off the reply. - XSendEvent(x_display_, requestor, False, 0, &reply); -} - -void SelectionOwner::OnSelectionClear(const XEvent& event) { - DLOG(ERROR) << "SelectionClear"; - - // TODO(erg): If we receive a SelectionClear event while we're handling data, - // we need to delay clearing. -} - -bool SelectionOwner::CanDispatchPropertyEvent(const XEvent& event) { - return event.xproperty.state == PropertyDelete && - FindIncrementalTransferForEvent(event) != incremental_transfers_.end(); -} - -void SelectionOwner::OnPropertyEvent(const XEvent& event) { - std::vector<IncrementalTransfer>::iterator it = - FindIncrementalTransferForEvent(event); - if (it == incremental_transfers_.end()) - return; - - ProcessIncrementalTransfer(&(*it)); - if (!it->data.get()) - CompleteIncrementalTransfer(it); -} - -bool SelectionOwner::ProcessTarget(XAtom target, - XID requestor, - XAtom property) { - XAtom multiple_atom = atom_cache_.GetAtom(kMultiple); - XAtom save_targets_atom = atom_cache_.GetAtom(kSaveTargets); - XAtom targets_atom = atom_cache_.GetAtom(kTargets); - - if (target == multiple_atom || target == save_targets_atom) - return false; - - if (target == targets_atom) { - // We have been asked for TARGETS. Send an atom array back with the data - // types we support. - std::vector<XAtom> targets; - targets.push_back(targets_atom); - targets.push_back(save_targets_atom); - targets.push_back(multiple_atom); - RetrieveTargets(&targets); - - XChangeProperty(x_display_, requestor, property, XA_ATOM, 32, - PropModeReplace, - reinterpret_cast<unsigned char*>(&targets.front()), - targets.size()); - return true; - } else { - // Try to find the data type in map. - SelectionFormatMap::const_iterator it = format_map_.find(target); - if (it != format_map_.end()) { - if (it->second->size() > max_request_size_) { - // We must send the data back in several chunks due to a limitation in - // the size of X requests. Notify the selection requestor that the data - // will be sent incrementally by returning data of type "INCR". - int length = it->second->size(); - XChangeProperty(x_display_, - requestor, - property, - atom_cache_.GetAtom(kIncr), - 32, - PropModeReplace, - reinterpret_cast<unsigned char*>(&length), - 1); - - // Wait for the selection requestor to indicate that it has processed - // the selection result before sending the first chunk of data. The - // selection requestor indicates this by deleting |property|. - base::TimeTicks timeout = - base::TimeTicks::Now() + - base::TimeDelta::FromMilliseconds(kIncrementalTransferTimeoutMs); - int foreign_window_manager_id = - ui::XForeignWindowManager::GetInstance()->RequestEvents( - requestor, PropertyChangeMask); - incremental_transfers_.push_back( - IncrementalTransfer(requestor, - target, - property, - it->second, - 0, - timeout, - foreign_window_manager_id)); - - // Start a timer to abort the data transfer in case that the selection - // requestor does not support the INCR property or gets destroyed during - // the data transfer. - if (!incremental_transfer_abort_timer_.IsRunning()) { - incremental_transfer_abort_timer_.Start( - FROM_HERE, - base::TimeDelta::FromMilliseconds(kTimerPeriodMs), - this, - &SelectionOwner::AbortStaleIncrementalTransfers); - } - } else { - XChangeProperty( - x_display_, - requestor, - property, - target, - 8, - PropModeReplace, - const_cast<unsigned char*>(it->second->front()), - it->second->size()); - } - return true; - } - // I would put error logging here, but GTK ignores TARGETS and spams us - // looking for its own internal types. - } - return false; -} - -void SelectionOwner::ProcessIncrementalTransfer(IncrementalTransfer* transfer) { - size_t remaining = transfer->data->size() - transfer->offset; - size_t chunk_length = std::min(remaining, max_request_size_); - XChangeProperty( - x_display_, - transfer->window, - transfer->property, - transfer->target, - 8, - PropModeReplace, - const_cast<unsigned char*>(transfer->data->front() + transfer->offset), - chunk_length); - transfer->offset += chunk_length; - transfer->timeout = base::TimeTicks::Now() + - base::TimeDelta::FromMilliseconds(kIncrementalTransferTimeoutMs); - - // When offset == data->size(), we still need to transfer a zero-sized chunk - // to notify the selection requestor that the transfer is complete. Clear - // transfer->data once the zero-sized chunk is sent to indicate that state - // related to this data transfer can be cleared. - if (chunk_length == 0) - transfer->data = NULL; -} - -void SelectionOwner::AbortStaleIncrementalTransfers() { - base::TimeTicks now = base::TimeTicks::Now(); - for (int i = static_cast<int>(incremental_transfers_.size()) - 1; - i >= 0; --i) { - if (incremental_transfers_[i].timeout <= now) - CompleteIncrementalTransfer(incremental_transfers_.begin() + i); - } -} - -void SelectionOwner::CompleteIncrementalTransfer( - std::vector<IncrementalTransfer>::iterator it) { - ui::XForeignWindowManager::GetInstance()->CancelRequest( - it->foreign_window_manager_id); - incremental_transfers_.erase(it); - - if (incremental_transfers_.empty()) - incremental_transfer_abort_timer_.Stop(); -} - -std::vector<SelectionOwner::IncrementalTransfer>::iterator - SelectionOwner::FindIncrementalTransferForEvent(const XEvent& event) { - for (std::vector<IncrementalTransfer>::iterator it = - incremental_transfers_.begin(); - it != incremental_transfers_.end(); - ++it) { - if (it->window == event.xproperty.window && - it->property == event.xproperty.atom) { - return it; - } - } - return incremental_transfers_.end(); -} - -SelectionOwner::IncrementalTransfer::IncrementalTransfer( - XID window, - XAtom target, - XAtom property, - const scoped_refptr<base::RefCountedMemory>& data, - int offset, - base::TimeTicks timeout, - int foreign_window_manager_id) - : window(window), - target(target), - property(property), - data(data), - offset(offset), - timeout(timeout), - foreign_window_manager_id(foreign_window_manager_id) { -} - -SelectionOwner::IncrementalTransfer::~IncrementalTransfer() { -} - -} // namespace ui
diff --git a/ui/base/x/selection_owner.h b/ui/base/x/selection_owner.h deleted file mode 100644 index 6e3ac7f..0000000 --- a/ui/base/x/selection_owner.h +++ /dev/null
@@ -1,137 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_X_SELECTION_OWNER_H_ -#define UI_BASE_X_SELECTION_OWNER_H_ - -#include <vector> - -#include "base/basictypes.h" -#include "base/callback.h" -#include "base/memory/ref_counted_memory.h" -#include "base/time/time.h" -#include "base/timer/timer.h" -#include "ui/base/ui_base_export.h" -#include "ui/base/x/selection_utils.h" -#include "ui/gfx/x/x11_atom_cache.h" -#include "ui/gfx/x/x11_types.h" - -namespace ui { - -// Owns a specific X11 selection on an X window. -// -// The selection owner object keeps track of which xwindow is the current -// owner, and when its |xwindow_|, offers different data types to other -// processes. -class UI_BASE_EXPORT SelectionOwner { - public: - SelectionOwner(XDisplay* xdisplay, - XID xwindow, - XAtom selection_name); - ~SelectionOwner(); - - // Returns the current selection data. Useful for fast paths. - const SelectionFormatMap& selection_format_map() { return format_map_; } - - // Appends a list of types we're offering to |targets|. - void RetrieveTargets(std::vector<XAtom>* targets); - - // Attempts to take ownership of the selection. If we're successful, present - // |data| to other windows. - void TakeOwnershipOfSelection(const SelectionFormatMap& data); - - // Clears our internal format map and clears the selection owner, whether we - // own the selection or not. - void ClearSelectionOwner(); - - // It is our owner's responsibility to plumb X11 events on |xwindow_| to us. - void OnSelectionRequest(const XEvent& event); - void OnSelectionClear(const XEvent& event); - - // Returns true if SelectionOwner can process the XPropertyEvent event, - // |event|. - bool CanDispatchPropertyEvent(const XEvent& event); - - void OnPropertyEvent(const XEvent& event); - - private: - // Holds state related to an incremental data transfer. - struct IncrementalTransfer { - IncrementalTransfer(XID window, - XAtom target, - XAtom property, - const scoped_refptr<base::RefCountedMemory>& data, - int offset, - base::TimeTicks timeout, - int foreign_window_manager_id); - ~IncrementalTransfer(); - - // Parameters from the XSelectionRequest. The data is transferred over - // |property| on |window|. - XID window; - XAtom target; - XAtom property; - - // The data to be transferred. - scoped_refptr<base::RefCountedMemory> data; - - // The offset from the beginning of |data| of the first byte to be - // transferred in the next chunk. - size_t offset; - - // Time when the transfer should be aborted because the selection requestor - // is taking too long to notify us that we can send the next chunk. - base::TimeTicks timeout; - - // Used to unselect PropertyChangeMask on |window| when we are done with - // the data transfer. - int foreign_window_manager_id; - }; - - // Attempts to convert the selection to |target|. If the conversion is - // successful, true is returned and the result is stored in the |property| - // of |requestor|. - bool ProcessTarget(XAtom target, XID requestor, XAtom property); - - // Sends the next chunk of data for given the incremental data transfer. - void ProcessIncrementalTransfer(IncrementalTransfer* transfer); - - // Aborts any incremental data transfers which have timed out. - void AbortStaleIncrementalTransfers(); - - // Called when the transfer at |it| has completed to do cleanup. - void CompleteIncrementalTransfer( - std::vector<IncrementalTransfer>::iterator it); - - // Returns the incremental data transfer, if any, which was waiting for - // |event|. - std::vector<IncrementalTransfer>::iterator FindIncrementalTransferForEvent( - const XEvent& event); - - // Our X11 state. - XDisplay* x_display_; - XID x_window_; - - // The X11 selection that this instance communicates on. - XAtom selection_name_; - - // The maximum size of data we can put in XChangeProperty(). - size_t max_request_size_; - - // The data we are currently serving. - SelectionFormatMap format_map_; - - std::vector<IncrementalTransfer> incremental_transfers_; - - // Used to abort stale incremental data transfers. - base::RepeatingTimer<SelectionOwner> incremental_transfer_abort_timer_; - - X11AtomCache atom_cache_; - - DISALLOW_COPY_AND_ASSIGN(SelectionOwner); -}; - -} // namespace ui - -#endif // UI_BASE_X_SELECTION_OWNER_H_
diff --git a/ui/base/x/selection_requestor.cc b/ui/base/x/selection_requestor.cc deleted file mode 100644 index 5cab04f..0000000 --- a/ui/base/x/selection_requestor.cc +++ /dev/null
@@ -1,321 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/x/selection_requestor.h" - -#include <algorithm> -#include <X11/Xlib.h> - -#include "base/run_loop.h" -#include "ui/base/x/selection_utils.h" -#include "ui/base/x/x11_util.h" -#include "ui/events/platform/platform_event_dispatcher.h" -#include "ui/events/platform/platform_event_source.h" -#include "ui/gfx/x/x11_types.h" - -namespace ui { - -namespace { - -const char kChromeSelection[] = "CHROME_SELECTION"; -const char kIncr[] = "INCR"; - -const char* kAtomsToCache[] = { - kChromeSelection, - kIncr, - NULL -}; - -// The period of |abort_timer_|. Arbitrary but must be <= than -// kRequestTimeoutMs. -const int kTimerPeriodMs = 100; - -// The amount of time to wait for a request to complete before aborting it. -const int kRequestTimeoutMs = 10000; - -COMPILE_ASSERT(kTimerPeriodMs <= kRequestTimeoutMs, - timer_period_must_be_less_or_equal_to_request_timeout); - -// Combines |data| into a single RefCountedMemory object. -scoped_refptr<base::RefCountedMemory> CombineRefCountedMemory( - const std::vector<scoped_refptr<base::RefCountedMemory> >& data) { - if (data.size() == 1u) - return data[0]; - - size_t length = 0; - for (size_t i = 0; i < data.size(); ++i) - length += data[i]->size(); - std::vector<unsigned char> combined_data; - combined_data.reserve(length); - - for (size_t i = 0; i < data.size(); ++i) { - combined_data.insert(combined_data.end(), - data[i]->front(), - data[i]->front() + data[i]->size()); - } - return scoped_refptr<base::RefCountedMemory>( - base::RefCountedBytes::TakeVector(&combined_data)); -} - -} // namespace - -SelectionRequestor::SelectionRequestor(XDisplay* x_display, - XID x_window, - PlatformEventDispatcher* dispatcher) - : x_display_(x_display), - x_window_(x_window), - x_property_(None), - dispatcher_(dispatcher), - current_request_index_(0u), - atom_cache_(x_display_, kAtomsToCache) { - x_property_ = atom_cache_.GetAtom(kChromeSelection); -} - -SelectionRequestor::~SelectionRequestor() {} - -bool SelectionRequestor::PerformBlockingConvertSelection( - XAtom selection, - XAtom target, - scoped_refptr<base::RefCountedMemory>* out_data, - size_t* out_data_items, - XAtom* out_type) { - base::TimeTicks timeout = - base::TimeTicks::Now() + - base::TimeDelta::FromMilliseconds(kRequestTimeoutMs); - Request request(selection, target, timeout); - requests_.push_back(&request); - if (current_request_index_ == (requests_.size() - 1)) - ConvertSelectionForCurrentRequest(); - BlockTillSelectionNotifyForRequest(&request); - - std::vector<Request*>::iterator request_it = std::find( - requests_.begin(), requests_.end(), &request); - CHECK(request_it != requests_.end()); - if (static_cast<int>(current_request_index_) > - request_it - requests_.begin()) { - --current_request_index_; - } - requests_.erase(request_it); - - if (requests_.empty()) - abort_timer_.Stop(); - - if (request.success) { - if (out_data) - *out_data = CombineRefCountedMemory(request.out_data); - if (out_data_items) - *out_data_items = request.out_data_items; - if (out_type) - *out_type = request.out_type; - } - return request.success; -} - -void SelectionRequestor::PerformBlockingConvertSelectionWithParameter( - XAtom selection, - XAtom target, - const std::vector<XAtom>& parameter) { - SetAtomArrayProperty(x_window_, kChromeSelection, "ATOM", parameter); - PerformBlockingConvertSelection(selection, target, NULL, NULL, NULL); -} - -SelectionData SelectionRequestor::RequestAndWaitForTypes( - XAtom selection, - const std::vector<XAtom>& types) { - for (std::vector<XAtom>::const_iterator it = types.begin(); - it != types.end(); ++it) { - scoped_refptr<base::RefCountedMemory> data; - XAtom type = None; - if (PerformBlockingConvertSelection(selection, - *it, - &data, - NULL, - &type) && - type == *it) { - return SelectionData(type, data); - } - } - - return SelectionData(); -} - -void SelectionRequestor::OnSelectionNotify(const XEvent& event) { - Request* request = GetCurrentRequest(); - XAtom event_property = event.xselection.property; - if (!request || - request->completed || - request->selection != event.xselection.selection || - request->target != event.xselection.target) { - // ICCCM requires us to delete the property passed into SelectionNotify. - if (event_property != None) - XDeleteProperty(x_display_, x_window_, event_property); - return; - } - - bool success = false; - if (event_property == x_property_) { - scoped_refptr<base::RefCountedMemory> out_data; - success = ui::GetRawBytesOfProperty(x_window_, - x_property_, - &out_data, - &request->out_data_items, - &request->out_type); - if (success) { - request->out_data.clear(); - request->out_data.push_back(out_data); - } - } - if (event_property != None) - XDeleteProperty(x_display_, x_window_, event_property); - - if (request->out_type == atom_cache_.GetAtom(kIncr)) { - request->data_sent_incrementally = true; - request->out_data.clear(); - request->out_data_items = 0u; - request->out_type = None; - request->timeout = base::TimeTicks::Now() + - base::TimeDelta::FromMilliseconds(kRequestTimeoutMs); - } else { - CompleteRequest(current_request_index_, success); - } -} - -bool SelectionRequestor::CanDispatchPropertyEvent(const XEvent& event) { - return event.xproperty.window == x_window_ && - event.xproperty.atom == x_property_ && - event.xproperty.state == PropertyNewValue; -} - -void SelectionRequestor::OnPropertyEvent(const XEvent& event) { - Request* request = GetCurrentRequest(); - if (!request || !request->data_sent_incrementally) - return; - - scoped_refptr<base::RefCountedMemory> out_data; - size_t out_data_items = 0u; - Atom out_type = None; - bool success = ui::GetRawBytesOfProperty(x_window_, - x_property_, - &out_data, - &out_data_items, - &out_type); - if (!success) { - CompleteRequest(current_request_index_, false); - return; - } - - if (request->out_type != None && request->out_type != out_type) { - CompleteRequest(current_request_index_, false); - return; - } - - request->out_data.push_back(out_data); - request->out_data_items += out_data_items; - request->out_type = out_type; - - // Delete the property to tell the selection owner to send the next chunk. - XDeleteProperty(x_display_, x_window_, x_property_); - - request->timeout = base::TimeTicks::Now() + - base::TimeDelta::FromMilliseconds(kRequestTimeoutMs); - - if (out_data->size() == 0u) - CompleteRequest(current_request_index_, true); -} - -void SelectionRequestor::AbortStaleRequests() { - base::TimeTicks now = base::TimeTicks::Now(); - for (size_t i = current_request_index_; i < requests_.size(); ++i) { - if (requests_[i]->timeout <= now) - CompleteRequest(i, false); - } -} - -void SelectionRequestor::CompleteRequest(size_t index, bool success) { - if (index >= requests_.size()) - return; - - Request* request = requests_[index]; - if (request->completed) - return; - request->success = success; - request->completed = true; - - if (index == current_request_index_) { - while (GetCurrentRequest() && GetCurrentRequest()->completed) - ++current_request_index_; - ConvertSelectionForCurrentRequest(); - } - - if (!request->quit_closure.is_null()) - request->quit_closure.Run(); -} - -void SelectionRequestor::ConvertSelectionForCurrentRequest() { - Request* request = GetCurrentRequest(); - if (request) { - XConvertSelection(x_display_, - request->selection, - request->target, - x_property_, - x_window_, - CurrentTime); - } -} - -void SelectionRequestor::BlockTillSelectionNotifyForRequest(Request* request) { - if (PlatformEventSource::GetInstance()) { - if (!abort_timer_.IsRunning()) { - abort_timer_.Start(FROM_HERE, - base::TimeDelta::FromMilliseconds(kTimerPeriodMs), - this, - &SelectionRequestor::AbortStaleRequests); - } - - base::MessageLoop::ScopedNestableTaskAllower allow_nested( - base::MessageLoopForUI::current()); - base::RunLoop run_loop; - request->quit_closure = run_loop.QuitClosure(); - run_loop.Run(); - - // We cannot put logic to process the next request here because the RunLoop - // might be nested. For instance, request 'B' may start a RunLoop while the - // RunLoop for request 'A' is running. It is not possible to end the RunLoop - // for request 'A' without first ending the RunLoop for request 'B'. - } else { - // This occurs if PerformBlockingConvertSelection() is called during - // shutdown and the PlatformEventSource has already been destroyed. - while (!request->completed && - request->timeout > base::TimeTicks::Now()) { - if (XPending(x_display_)) { - XEvent event; - XNextEvent(x_display_, &event); - dispatcher_->DispatchEvent(&event); - } - } - } -} - -SelectionRequestor::Request* SelectionRequestor::GetCurrentRequest() { - return current_request_index_ == requests_.size() ? - NULL : requests_[current_request_index_]; -} - -SelectionRequestor::Request::Request(XAtom selection, - XAtom target, - base::TimeTicks timeout) - : selection(selection), - target(target), - data_sent_incrementally(false), - out_data_items(0u), - out_type(None), - success(false), - timeout(timeout), - completed(false) { -} - -SelectionRequestor::Request::~Request() { -} - -} // namespace ui
diff --git a/ui/base/x/selection_requestor.h b/ui/base/x/selection_requestor.h deleted file mode 100644 index 5455ff7..0000000 --- a/ui/base/x/selection_requestor.h +++ /dev/null
@@ -1,158 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_X_SELECTION_REQUESTOR_H_ -#define UI_BASE_X_SELECTION_REQUESTOR_H_ - -#include <vector> - -#include "base/basictypes.h" -#include "base/callback.h" -#include "base/event_types.h" -#include "base/memory/ref_counted_memory.h" -#include "base/time/time.h" -#include "base/timer/timer.h" -#include "ui/base/ui_base_export.h" -#include "ui/gfx/x/x11_atom_cache.h" -#include "ui/gfx/x/x11_types.h" - -namespace ui { -class PlatformEventDispatcher; -class SelectionData; - -// Requests and later receives data from the X11 server through the selection -// system. -// -// X11 uses a system called "selections" to implement clipboards and drag and -// drop. This class interprets messages from the stateful selection request -// API. SelectionRequestor should only deal with the X11 details; it does not -// implement per-component fast-paths. -class UI_BASE_EXPORT SelectionRequestor { - public: - SelectionRequestor(XDisplay* xdisplay, - XID xwindow, - PlatformEventDispatcher* dispatcher); - ~SelectionRequestor(); - - // Does the work of requesting |target| from |selection|, spinning up the - // nested message loop, and reading the resulting data back. The result is - // stored in |out_data|. - // |out_data_items| is the length of |out_data| in |out_type| items. - bool PerformBlockingConvertSelection( - XAtom selection, - XAtom target, - scoped_refptr<base::RefCountedMemory>* out_data, - size_t* out_data_items, - XAtom* out_type); - - // Requests |target| from |selection|, passing |parameter| as a parameter to - // XConvertSelection(). - void PerformBlockingConvertSelectionWithParameter( - XAtom selection, - XAtom target, - const std::vector<XAtom>& parameter); - - // Returns the first of |types| offered by the current owner of |selection|. - // Returns an empty SelectionData object if none of |types| are available. - SelectionData RequestAndWaitForTypes(XAtom selection, - const std::vector<XAtom>& types); - - // It is our owner's responsibility to plumb X11 SelectionNotify events on - // |xwindow_| to us. - void OnSelectionNotify(const XEvent& event); - - // Returns true if SelectionOwner can process the XChangeProperty event, - // |event|. - bool CanDispatchPropertyEvent(const XEvent& event); - - void OnPropertyEvent(const XEvent& event); - - private: - friend class SelectionRequestorTest; - - // A request that has been issued. - struct Request { - Request(XAtom selection, XAtom target, base::TimeTicks timeout); - ~Request(); - - // The target and selection requested in the XConvertSelection() request. - // Used for error detection. - XAtom selection; - XAtom target; - - // Whether the result of the XConvertSelection() request is being sent - // incrementally. - bool data_sent_incrementally; - - // The result data for the XConvertSelection() request. - std::vector<scoped_refptr<base::RefCountedMemory> > out_data; - size_t out_data_items; - XAtom out_type; - - // Whether the XConvertSelection() request was successful. - bool success; - - // The time when the request should be aborted. - base::TimeTicks timeout; - - // Called to terminate the nested message loop. - base::Closure quit_closure; - - // True if the request is complete. - bool completed; - }; - - // Aborts requests which have timed out. - void AbortStaleRequests(); - - // Mark |request| as completed. If the current request is completed, converts - // the selection for the next request. - void CompleteRequest(size_t index, bool success); - - // Converts the selection for the request at |current_request_index_|. - void ConvertSelectionForCurrentRequest(); - - // Blocks till SelectionNotify is received for the target specified in - // |request|. - void BlockTillSelectionNotifyForRequest(Request* request); - - // Returns the request at |current_request_index_| or NULL if there isn't any. - Request* GetCurrentRequest(); - - // Our X11 state. - XDisplay* x_display_; - XID x_window_; - - // The property on |x_window_| set by the selection owner with the value of - // the selection. - XAtom x_property_; - - // Dispatcher which handles SelectionNotify and SelectionRequest for - // |selection_name_|. PerformBlockingConvertSelection() calls the - // dispatcher directly if PerformBlockingConvertSelection() is called after - // the PlatformEventSource is destroyed. - // Not owned. - PlatformEventDispatcher* dispatcher_; - - // In progress requests. Requests are added to the list at the start of - // PerformBlockingConvertSelection() and are removed and destroyed right - // before the method terminates. - std::vector<Request*> requests_; - - // The index of the currently active request in |requests_|. The active - // request is the request for which XConvertSelection() has been - // called and for which we are waiting for a SelectionNotify response. - size_t current_request_index_; - - // Used to abort requests if the selection owner takes too long to respond. - base::RepeatingTimer<SelectionRequestor> abort_timer_; - - X11AtomCache atom_cache_; - - DISALLOW_COPY_AND_ASSIGN(SelectionRequestor); -}; - -} // namespace ui - -#endif // UI_BASE_X_SELECTION_REQUESTOR_H_
diff --git a/ui/base/x/selection_requestor_unittest.cc b/ui/base/x/selection_requestor_unittest.cc deleted file mode 100644 index f2c7b03..0000000 --- a/ui/base/x/selection_requestor_unittest.cc +++ /dev/null
@@ -1,165 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/x/selection_requestor.h" - -#include "base/memory/ref_counted_memory.h" -#include "base/memory/scoped_ptr.h" -#include "base/message_loop/message_loop.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/base/x/selection_utils.h" -#include "ui/base/x/x11_util.h" -#include "ui/events/platform/platform_event_source.h" -#include "ui/gfx/x/x11_atom_cache.h" -#include "ui/gfx/x/x11_types.h" - -#include <X11/Xlib.h> - -namespace ui { - -namespace { - -const char* kAtomsToCache[] = { - "STRING", - NULL -}; - -} // namespace - -class SelectionRequestorTest : public testing::Test { - public: - SelectionRequestorTest() - : x_display_(gfx::GetXDisplay()), - x_window_(None), - atom_cache_(gfx::GetXDisplay(), kAtomsToCache) { - atom_cache_.allow_uncached_atoms(); - } - - virtual ~SelectionRequestorTest() { - } - - // Responds to the SelectionRequestor's XConvertSelection() request by - // - Setting the property passed into the XConvertSelection() request to - // |value|. - // - Sending a SelectionNotify event. - void SendSelectionNotify(XAtom selection, - XAtom target, - const std::string& value) { - ui::SetStringProperty(x_window_, - requestor_->x_property_, - atom_cache_.GetAtom("STRING"), - value); - - XEvent xev; - xev.type = SelectionNotify; - xev.xselection.serial = 0u; - xev.xselection.display = x_display_; - xev.xselection.requestor = x_window_; - xev.xselection.selection = selection; - xev.xselection.target = target; - xev.xselection.property = requestor_->x_property_; - xev.xselection.time = CurrentTime; - xev.xselection.type = SelectionNotify; - requestor_->OnSelectionNotify(xev); - } - - protected: - virtual void SetUp() override { - // Make X11 synchronous for our display connection. - XSynchronize(x_display_, True); - - // Create a window for the selection requestor to use. - x_window_ = XCreateWindow(x_display_, - DefaultRootWindow(x_display_), - 0, 0, 10, 10, // x, y, width, height - 0, // border width - CopyFromParent, // depth - InputOnly, - CopyFromParent, // visual - 0, - NULL); - - event_source_ = ui::PlatformEventSource::CreateDefault(); - CHECK(ui::PlatformEventSource::GetInstance()); - requestor_.reset(new SelectionRequestor(x_display_, x_window_, NULL)); - } - - virtual void TearDown() override { - requestor_.reset(); - event_source_.reset(); - XDestroyWindow(x_display_, x_window_); - XSynchronize(x_display_, False); - } - - Display* x_display_; - - // |requestor_|'s window. - XID x_window_; - - scoped_ptr<ui::PlatformEventSource> event_source_; - scoped_ptr<SelectionRequestor> requestor_; - - base::MessageLoopForUI message_loop_; - X11AtomCache atom_cache_; - - private: - DISALLOW_COPY_AND_ASSIGN(SelectionRequestorTest); -}; - -namespace { - -// Converts |selection| to |target| and checks the returned values. -void PerformBlockingConvertSelection(SelectionRequestor* requestor, - X11AtomCache* atom_cache, - XAtom selection, - XAtom target, - const std::string& expected_data) { - scoped_refptr<base::RefCountedMemory> out_data; - size_t out_data_items = 0u; - XAtom out_type = None; - EXPECT_TRUE(requestor->PerformBlockingConvertSelection( - selection, target, &out_data, &out_data_items, &out_type)); - EXPECT_EQ(expected_data, ui::RefCountedMemoryToString(out_data)); - EXPECT_EQ(expected_data.size(), out_data_items); - EXPECT_EQ(atom_cache->GetAtom("STRING"), out_type); -} - -} // namespace - -// Test that SelectionRequestor correctly handles receiving a request while it -// is processing another request. -TEST_F(SelectionRequestorTest, NestedRequests) { - // Assume that |selection| will have no owner. If there is an owner, the owner - // will set the property passed into the XConvertSelection() request which is - // undesirable. - XAtom selection = atom_cache_.GetAtom("FAKE_SELECTION"); - - XAtom target1 = atom_cache_.GetAtom("TARGET1"); - XAtom target2 = atom_cache_.GetAtom("TARGET2"); - - base::MessageLoopForUI* loop = base::MessageLoopForUI::current(); - loop->PostTask(FROM_HERE, - base::Bind(&PerformBlockingConvertSelection, - base::Unretained(requestor_.get()), - base::Unretained(&atom_cache_), - selection, - target2, - "Data2")); - loop->PostTask(FROM_HERE, - base::Bind(&SelectionRequestorTest::SendSelectionNotify, - base::Unretained(this), - selection, - target1, - "Data1")); - loop->PostTask(FROM_HERE, - base::Bind(&SelectionRequestorTest::SendSelectionNotify, - base::Unretained(this), - selection, - target2, - "Data2")); - PerformBlockingConvertSelection( - requestor_.get(), &atom_cache_, selection, target1, "Data1"); -} - -} // namespace ui
diff --git a/ui/base/x/selection_utils.cc b/ui/base/x/selection_utils.cc deleted file mode 100644 index d5ce1c0..0000000 --- a/ui/base/x/selection_utils.cc +++ /dev/null
@@ -1,255 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/x/selection_utils.h" - -#include <set> - -#include "base/i18n/icu_string_conversions.h" -#include "base/logging.h" -#include "base/strings/string_util.h" -#include "base/strings/utf_string_conversions.h" -#include "ui/base/clipboard/clipboard.h" -#include "ui/base/x/x11_util.h" -#include "ui/gfx/x/x11_atom_cache.h" - -namespace ui { - -const char kMimeTypeMozillaURL[] = "text/x-moz-url"; -const char kString[] = "STRING"; -const char kText[] = "TEXT"; -const char kTextPlain[] = "text/plain"; -const char kTextPlainUtf8[] = "text/plain;charset=utf-8"; -const char kUtf8String[] = "UTF8_STRING"; - -const char* kSelectionDataAtoms[] = { - Clipboard::kMimeTypeHTML, - kString, - kText, - kTextPlain, - kTextPlainUtf8, - kUtf8String, - NULL -}; - -std::vector< ::Atom> GetTextAtomsFrom(const X11AtomCache* atom_cache) { - std::vector< ::Atom> atoms; - atoms.push_back(atom_cache->GetAtom(kUtf8String)); - atoms.push_back(atom_cache->GetAtom(kString)); - atoms.push_back(atom_cache->GetAtom(kText)); - atoms.push_back(atom_cache->GetAtom(kTextPlain)); - atoms.push_back(atom_cache->GetAtom(kTextPlainUtf8)); - return atoms; -} - -std::vector< ::Atom> GetURLAtomsFrom(const X11AtomCache* atom_cache) { - std::vector< ::Atom> atoms; - atoms.push_back(atom_cache->GetAtom(Clipboard::kMimeTypeURIList)); - atoms.push_back(atom_cache->GetAtom(kMimeTypeMozillaURL)); - return atoms; -} - -std::vector< ::Atom> GetURIListAtomsFrom(const X11AtomCache* atom_cache) { - std::vector< ::Atom> atoms; - atoms.push_back(atom_cache->GetAtom(Clipboard::kMimeTypeURIList)); - return atoms; -} - -void GetAtomIntersection(const std::vector< ::Atom>& desired, - const std::vector< ::Atom>& offered, - std::vector< ::Atom>* output) { - for (std::vector< ::Atom>::const_iterator it = desired.begin(); - it != desired.end(); ++it) { - std::vector< ::Atom>::const_iterator jt = - std::find(offered.begin(), offered.end(), *it); - if (jt != offered.end()) - output->push_back(*it); - } -} - -void AddString16ToVector(const base::string16& str, - std::vector<unsigned char>* bytes) { - const unsigned char* front = - reinterpret_cast<const unsigned char*>(str.data()); - bytes->insert(bytes->end(), front, front + (str.size() * 2)); -} - -std::vector<std::string> ParseURIList(const SelectionData& data) { - // uri-lists are newline separated file lists in URL encoding. - std::string unparsed; - data.AssignTo(&unparsed); - - std::vector<std::string> tokens; - Tokenize(unparsed, "\n", &tokens); - return tokens; -} - -std::string RefCountedMemoryToString( - const scoped_refptr<base::RefCountedMemory>& memory) { - if (!memory.get()) { - NOTREACHED(); - return std::string(); - } - - size_t size = memory->size(); - if (!size) - return std::string(); - - const unsigned char* front = memory->front(); - return std::string(reinterpret_cast<const char*>(front), size); -} - -base::string16 RefCountedMemoryToString16( - const scoped_refptr<base::RefCountedMemory>& memory) { - if (!memory.get()) { - NOTREACHED(); - return base::string16(); - } - - size_t size = memory->size(); - if (!size) - return base::string16(); - - const unsigned char* front = memory->front(); - return base::string16(reinterpret_cast<const base::char16*>(front), size / 2); -} - -/////////////////////////////////////////////////////////////////////////////// - -SelectionFormatMap::SelectionFormatMap() {} - -SelectionFormatMap::~SelectionFormatMap() {} - -void SelectionFormatMap::Insert( - ::Atom atom, - const scoped_refptr<base::RefCountedMemory>& item) { - data_.erase(atom); - data_.insert(std::make_pair(atom, item)); -} - -ui::SelectionData SelectionFormatMap::GetFirstOf( - const std::vector< ::Atom>& requested_types) const { - for (std::vector< ::Atom>::const_iterator it = requested_types.begin(); - it != requested_types.end(); ++it) { - const_iterator data_it = data_.find(*it); - if (data_it != data_.end()) { - return SelectionData(data_it->first, data_it->second); - } - } - - return SelectionData(); -} - -std::vector< ::Atom> SelectionFormatMap::GetTypes() const { - std::vector< ::Atom> atoms; - for (const_iterator it = data_.begin(); it != data_.end(); ++it) - atoms.push_back(it->first); - - return atoms; -} - -/////////////////////////////////////////////////////////////////////////////// - -SelectionData::SelectionData() - : type_(None), - atom_cache_(gfx::GetXDisplay(), kSelectionDataAtoms) { -} - -SelectionData::SelectionData( - ::Atom type, - const scoped_refptr<base::RefCountedMemory>& memory) - : type_(type), - memory_(memory), - atom_cache_(gfx::GetXDisplay(), kSelectionDataAtoms) { -} - -SelectionData::SelectionData(const SelectionData& rhs) - : type_(rhs.type_), - memory_(rhs.memory_), - atom_cache_(gfx::GetXDisplay(), kSelectionDataAtoms) { -} - -SelectionData::~SelectionData() {} - -SelectionData& SelectionData::operator=(const SelectionData& rhs) { - type_ = rhs.type_; - memory_ = rhs.memory_; - // TODO(erg): In some future where we have to support multiple X Displays, - // the following will also need to deal with the display. - return *this; -} - -bool SelectionData::IsValid() const { - return type_ != None; -} - -::Atom SelectionData::GetType() const { - return type_; -} - -const unsigned char* SelectionData::GetData() const { - return memory_.get() ? memory_->front() : NULL; -} - -size_t SelectionData::GetSize() const { - return memory_.get() ? memory_->size() : 0; -} - -std::string SelectionData::GetText() const { - if (type_ == atom_cache_.GetAtom(kUtf8String) || - type_ == atom_cache_.GetAtom(kText) || - type_ == atom_cache_.GetAtom(kTextPlainUtf8)) { - return RefCountedMemoryToString(memory_); - } else if (type_ == atom_cache_.GetAtom(kString) || - type_ == atom_cache_.GetAtom(kTextPlain)) { - std::string result; - base::ConvertToUtf8AndNormalize(RefCountedMemoryToString(memory_), - base::kCodepageLatin1, - &result); - return result; - } else { - // BTW, I looked at COMPOUND_TEXT, and there's no way we're going to - // support that. Yuck. - NOTREACHED(); - return std::string(); - } -} - -base::string16 SelectionData::GetHtml() const { - base::string16 markup; - - if (type_ == atom_cache_.GetAtom(Clipboard::kMimeTypeHTML)) { - const unsigned char* data = GetData(); - size_t size = GetSize(); - - // If the data starts with 0xFEFF, i.e., Byte Order Mark, assume it is - // UTF-16, otherwise assume UTF-8. - if (size >= 2 && - reinterpret_cast<const uint16_t*>(data)[0] == 0xFEFF) { - markup.assign(reinterpret_cast<const uint16_t*>(data) + 1, - (size / 2) - 1); - } else { - base::UTF8ToUTF16(reinterpret_cast<const char*>(data), size, &markup); - } - - // If there is a terminating NULL, drop it. - if (!markup.empty() && markup.at(markup.length() - 1) == '\0') - markup.resize(markup.length() - 1); - - return markup; - } else { - NOTREACHED(); - return markup; - } -} - -void SelectionData::AssignTo(std::string* result) const { - *result = RefCountedMemoryToString(memory_); -} - -void SelectionData::AssignTo(base::string16* result) const { - *result = RefCountedMemoryToString16(memory_); -} - -} // namespace ui
diff --git a/ui/base/x/selection_utils.h b/ui/base/x/selection_utils.h deleted file mode 100644 index 9eca5be..0000000 --- a/ui/base/x/selection_utils.h +++ /dev/null
@@ -1,131 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_BASE_X_SELECTION_UTILS_H_ -#define UI_BASE_X_SELECTION_UTILS_H_ - -#include <X11/Xlib.h> - -// Get rid of a macro from Xlib.h that conflicts with Aura's RootWindow class. -#undef RootWindow - -#include <map> - -#include "base/basictypes.h" -#include "base/memory/ref_counted_memory.h" -#include "ui/base/clipboard/clipboard.h" -#include "ui/base/ui_base_export.h" -#include "ui/gfx/x/x11_atom_cache.h" - -namespace ui { -class SelectionData; -class X11AtomCache; - -extern const char kMimeTypeMozillaURL[]; -extern const char kString[]; -extern const char kText[]; -extern const char kUtf8String[]; - -// Returns a list of all text atoms that we handle. -UI_BASE_EXPORT std::vector< ::Atom> GetTextAtomsFrom( - const X11AtomCache* atom_cache); - -UI_BASE_EXPORT std::vector< ::Atom> GetURLAtomsFrom( - const X11AtomCache* atom_cache); - -UI_BASE_EXPORT std::vector< ::Atom> GetURIListAtomsFrom( - const X11AtomCache* atom_cache); - -// Places the intersection of |desired| and |offered| into |output|. -UI_BASE_EXPORT void GetAtomIntersection(const std::vector< ::Atom>& desired, - const std::vector< ::Atom>& offered, - std::vector< ::Atom>* output); - -// Takes the raw bytes of the base::string16 and copies them into |bytes|. -UI_BASE_EXPORT void AddString16ToVector(const base::string16& str, - std::vector<unsigned char>* bytes); - -// Tokenizes and parses the Selection Data as if it is a URI List. -UI_BASE_EXPORT std::vector<std::string> ParseURIList(const SelectionData& data); - -UI_BASE_EXPORT std::string RefCountedMemoryToString( - const scoped_refptr<base::RefCountedMemory>& memory); - -UI_BASE_EXPORT base::string16 RefCountedMemoryToString16( - const scoped_refptr<base::RefCountedMemory>& memory); - -/////////////////////////////////////////////////////////////////////////////// - -// Represents the selection in different data formats. Binary data passed in is -// assumed to be allocated with new char[], and is owned by SelectionFormatMap. -class UI_BASE_EXPORT SelectionFormatMap { - public: - // Our internal data store, which we only expose through iterators. - typedef std::map< ::Atom, scoped_refptr<base::RefCountedMemory> > InternalMap; - typedef InternalMap::const_iterator const_iterator; - - SelectionFormatMap(); - ~SelectionFormatMap(); - // Copy and assignment deliberately open. - - // Adds the selection in the format |atom|. Ownership of |data| is passed to - // us. - void Insert(::Atom atom, const scoped_refptr<base::RefCountedMemory>& item); - - // Returns the first of the requested_types or NULL if missing. - ui::SelectionData GetFirstOf( - const std::vector< ::Atom>& requested_types) const; - - // Returns all the selected types. - std::vector< ::Atom> GetTypes() const; - - // Pass through to STL map. Only allow non-mutation access. - const_iterator begin() const { return data_.begin(); } - const_iterator end() const { return data_.end(); } - const_iterator find(::Atom atom) const { return data_.find(atom); } - size_t size() const { return data_.size(); } - - private: - InternalMap data_; -}; - -/////////////////////////////////////////////////////////////////////////////// - -// A holder for data with optional X11 deletion semantics. -class UI_BASE_EXPORT SelectionData { - public: - // |atom_cache| is still owned by caller. - SelectionData(); - SelectionData(::Atom type, - const scoped_refptr<base::RefCountedMemory>& memory); - SelectionData(const SelectionData& rhs); - ~SelectionData(); - SelectionData& operator=(const SelectionData& rhs); - - bool IsValid() const; - ::Atom GetType() const; - const unsigned char* GetData() const; - size_t GetSize() const; - - // If |type_| is a string type, convert the data to UTF8 and return it. - std::string GetText() const; - - // If |type_| is the HTML type, returns the data as a string16. This detects - // guesses the character encoding of the source. - base::string16 GetHtml() const; - - // Assigns the raw data to the string. - void AssignTo(std::string* result) const; - void AssignTo(base::string16* result) const; - - private: - ::Atom type_; - scoped_refptr<base::RefCountedMemory> memory_; - - X11AtomCache atom_cache_; -}; - -} // namespace ui - -#endif // UI_BASE_X_SELECTION_UTILS_H_
diff --git a/ui/compositor/BUILD.gn b/ui/compositor/BUILD.gn deleted file mode 100644 index 04a7add..0000000 --- a/ui/compositor/BUILD.gn +++ /dev/null
@@ -1,169 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import("//build/config/ui.gni") - -component("compositor") { - sources = [ - "closure_animation_observer.cc", - "closure_animation_observer.h", - "compositor.cc", - "compositor.h", - "compositor_animation_observer.h", - "compositor_export.h", - "compositor_observer.cc", - "compositor_observer.h", - "compositor_vsync_manager.cc", - "compositor_vsync_manager.h", - "compositor_switches.cc", - "compositor_switches.h", - "debug_utils.cc", - "debug_utils.h", - "dip_util.cc", - "dip_util.h", - "float_animation_curve_adapter.cc", - "float_animation_curve_adapter.h", - "layer.cc", - "layer.h", - "layer_animation_delegate.h", - "layer_animation_element.cc", - "layer_animation_element.h", - "layer_animation_observer.cc", - "layer_animation_observer.h", - "layer_animation_sequence.cc", - "layer_animation_sequence.h", - "layer_animator.cc", - "layer_animator.h", - "layer_animator_collection.cc", - "layer_animator_collection.h", - "layer_delegate.h", - "layer_owner.cc", - "layer_owner.h", - "layer_tree_owner.cc", - "layer_tree_owner.h", - "layer_type.h", - "reflector.h", - "scoped_animation_duration_scale_mode.cc", - "scoped_animation_duration_scale_mode.h", - "scoped_layer_animation_settings.cc", - "scoped_layer_animation_settings.h", - "transform_animation_curve_adapter.cc", - "transform_animation_curve_adapter.h", - ] - - defines = [ "COMPOSITOR_IMPLEMENTATION" ] - - deps = [ - "//base", - "//base/third_party/dynamic_annotations", - "//cc", - "//cc/surfaces", - "//gpu/command_buffer/common", - "//skia", - "//ui/gfx", - "//ui/gfx/geometry", - "//ui/gl", - ] - - if (is_win && use_aura) { - # TODO(sky): before we make this real need to remove - # IDR_BITMAP_BRUSH_IMAGE. - deps += [ - "//ui/resources", - "//third_party/angle:libEGL", - "//third_party/angle:libGLESv2", - ] - } -} - -if (false) { - source_set("test_support") { - testonly = true - sources = [ - "test/context_factories_for_test.cc", - "test/context_factories_for_test.h", - "test/draw_waiter_for_test.cc", - "test/draw_waiter_for_test.h", - "test/in_process_context_factory.cc", - "test/in_process_context_factory.h", - "test/layer_animator_test_controller.cc", - "test/layer_animator_test_controller.h", - "test/test_compositor_host.h", - "test/test_compositor_host_mac.mm", - "test/test_compositor_host_win.cc", - "test/test_layer_animation_delegate.cc", - "test/test_layer_animation_delegate.h", - "test/test_layer_animation_observer.cc", - "test/test_layer_animation_observer.h", - "test/test_layers.cc", - "test/test_layers.h", - "test/test_suite.cc", - "test/test_suite.h", - "test/test_utils.cc", - "test/test_utils.h", - ] - - public_deps = [ - ":compositor", - ] - deps = [ - "//base/test:test_support", - "//cc", - "//cc/surfaces", - "//cc:test_support", - "//skia", - "//testing/gtest", - "//third_party/WebKit/public:blink_minimal", - "//ui/base", - "//ui/gfx", - "//ui/gfx/geometry", - "//ui/gl", - "//webkit/common/gpu", - ] - - if (use_x11) { - configs += [ "//build/config/linux:x11" ] - deps += [ "//ui/gfx/x" ] - } - - if (use_ozone) { - sources += [ "test/test_compositor_host_ozone.cc" ] - } else if (use_x11) { - sources += [ "test/test_compositor_host_x11.cc" ] - } - } -} # if (false) -# TODO(GYP) enable this when all dependencies are complete and it links. -#test("compositor_unittests") { -# sources = [ -# "layer_animation_element_unittest.cc", -# "layer_animation_sequence_unittest.cc", -# "layer_animator_unittest.cc", -# "layer_owner_unittest.cc", -# "layer_unittest.cc", -# "run_all_unittests.cc", -# "transform_animation_curve_adapter_unittest.cc", -# ] -# -# deps = [ -# ":compositor", -# ":test_support", -# "//base", -# "//base/allocator", -# "//base/test:test_support", -# "//cc", -# "//cc:test_support", -# "//skia", -# "//testing/gtest", -# "//ui/base", -# "//ui/gfx", -# "//ui/gfx/geometry", -# "//ui/gl", -# "//ui/resources", -# ] -# -# if (is_linux) { -# deps += [ "//third_party/mesa:osmesa" ] -# } -#}
diff --git a/ui/compositor/DEPS b/ui/compositor/DEPS deleted file mode 100644 index e234d55..0000000 --- a/ui/compositor/DEPS +++ /dev/null
@@ -1,8 +0,0 @@ -include_rules = [ - "+cc", - "-cc/blink", - "+gpu/command_buffer/client/gles2_interface.h", - "+third_party/skia", - "+ui/gfx", - "+ui/gl", -]
diff --git a/ui/compositor/OWNERS b/ui/compositor/OWNERS deleted file mode 100644 index d221622..0000000 --- a/ui/compositor/OWNERS +++ /dev/null
@@ -1,6 +0,0 @@ -danakj@chromium.org -piman@chromium.org -vollick@chromium.org - -# Animation -per-file *animat*=ajuma@chromium.org
diff --git a/ui/compositor/PRESUBMIT.py b/ui/compositor/PRESUBMIT.py deleted file mode 100644 index 405f8ce..0000000 --- a/ui/compositor/PRESUBMIT.py +++ /dev/null
@@ -1,16 +0,0 @@ -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Chromium presubmit script for src/ui/compositor/. - -See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts -for more details on the presubmit API built into gcl. -""" - -def GetPreferredTryMasters(project, change): - return { - 'tryserver.chromium.linux': { - 'linux_chromium_chromeos_rel_swarming': set(['defaulttests']), - } - }
diff --git a/ui/compositor/closure_animation_observer.cc b/ui/compositor/closure_animation_observer.cc deleted file mode 100644 index 2ac7f91..0000000 --- a/ui/compositor/closure_animation_observer.cc +++ /dev/null
@@ -1,22 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/compositor/closure_animation_observer.h" - -namespace ui { - -ClosureAnimationObserver::ClosureAnimationObserver(const base::Closure& closure) - : closure_(closure) { - DCHECK(!closure_.is_null()); -} - -ClosureAnimationObserver::~ClosureAnimationObserver() { -} - -void ClosureAnimationObserver::OnImplicitAnimationsCompleted() { - closure_.Run(); - delete this; -} - -} // namespace ui
diff --git a/ui/compositor/closure_animation_observer.h b/ui/compositor/closure_animation_observer.h deleted file mode 100644 index 1fd1cdf..0000000 --- a/ui/compositor/closure_animation_observer.h +++ /dev/null
@@ -1,35 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_CLOSURE_ANIMATION_OBSERVER_H_ -#define UI_COMPOSITOR_CLOSURE_ANIMATION_OBSERVER_H_ - -#include "base/callback.h" -#include "base/macros.h" -#include "ui/compositor/compositor_export.h" -#include "ui/compositor/layer_animation_observer.h" - -namespace ui { - -// Runs a callback at the end of the animation. This observe also destroys -// itself afterwards. -class COMPOSITOR_EXPORT ClosureAnimationObserver - : public ImplicitAnimationObserver { - public: - explicit ClosureAnimationObserver(const base::Closure& closure); - - private: - ~ClosureAnimationObserver() override; - - // ImplicitAnimationObserver: - void OnImplicitAnimationsCompleted() override; - - const base::Closure closure_; - - DISALLOW_COPY_AND_ASSIGN(ClosureAnimationObserver); -}; - -} // namespace ui - -#endif // UI_COMPOSITOR_CLOSURE_ANIMATION_OBSERVER_H_
diff --git a/ui/compositor/compositor.cc b/ui/compositor/compositor.cc deleted file mode 100644 index 317f0a3..0000000 --- a/ui/compositor/compositor.cc +++ /dev/null
@@ -1,501 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/compositor/compositor.h" - -#include <algorithm> -#include <deque> - -#include "base/bind.h" -#include "base/command_line.h" -#include "base/debug/trace_event.h" -#include "base/message_loop/message_loop.h" -#include "base/metrics/histogram.h" -#include "base/strings/string_util.h" -#include "base/sys_info.h" -#include "cc/base/latency_info_swap_promise.h" -#include "cc/base/switches.h" -#include "cc/input/input_handler.h" -#include "cc/layers/layer.h" -#include "cc/scheduler/begin_frame_source.h" -#include "cc/output/begin_frame_args.h" -#include "cc/output/context_provider.h" -#include "cc/surfaces/surface_id_allocator.h" -#include "cc/trees/layer_tree_host.h" -#include "third_party/skia/include/core/SkBitmap.h" -#include "ui/compositor/compositor_observer.h" -#include "ui/compositor/compositor_switches.h" -#include "ui/compositor/compositor_vsync_manager.h" -#include "ui/compositor/dip_util.h" -#include "ui/compositor/layer.h" -#include "ui/compositor/layer_animator_collection.h" -#include "ui/gfx/frame_time.h" -#include "ui/gl/gl_context.h" -#include "ui/gl/gl_switches.h" - -namespace { - -const double kDefaultRefreshRate = 60.0; -const double kTestRefreshRate = 200.0; - -const int kCompositorLockTimeoutMs = 67; - -} // namespace - -namespace ui { - -CompositorLock::CompositorLock(Compositor* compositor) - : compositor_(compositor) { - compositor_->task_runner_->PostDelayedTask( - FROM_HERE, - base::Bind(&CompositorLock::CancelLock, AsWeakPtr()), - base::TimeDelta::FromMilliseconds(kCompositorLockTimeoutMs)); -} - -CompositorLock::~CompositorLock() { - CancelLock(); -} - -void CompositorLock::CancelLock() { - if (!compositor_) - return; - compositor_->UnlockCompositor(); - compositor_ = NULL; -} - -} // namespace ui - -namespace {} // namespace - -namespace ui { - -class SatisfySwapPromise : public cc::SwapPromise { - public: - explicit SatisfySwapPromise(uint32_t id) : id_(id) {} - - private: - void DidSwap(cc::CompositorFrameMetadata* metadata) override { - metadata->satisfies_sequences.push_back(id_); - } - - void DidNotSwap(DidNotSwapReason reason) override { - // TODO(jbauman): Send to the SurfaceManager immediately. - DCHECK(false); - } - int64 TraceId() const override { return 0; } - uint32_t id_; -}; - -Compositor::Compositor(gfx::AcceleratedWidget widget, - ui::ContextFactory* context_factory, - scoped_refptr<base::SingleThreadTaskRunner> task_runner) - : context_factory_(context_factory), - root_layer_(NULL), - widget_(widget), - surface_id_allocator_(context_factory->CreateSurfaceIdAllocator()), - surface_sequence_number_(0), - compositor_thread_loop_(context_factory->GetCompositorMessageLoop()), - task_runner_(task_runner), - vsync_manager_(new CompositorVSyncManager()), - device_scale_factor_(0.0f), - last_started_frame_(0), - last_ended_frame_(0), - disable_schedule_composite_(false), - compositor_lock_(NULL), - defer_draw_scheduling_(false), - waiting_on_compositing_end_(false), - draw_on_compositing_end_(false), - swap_state_(SWAP_NONE), - layer_animator_collection_(this), - weak_ptr_factory_(this) { - root_web_layer_ = cc::Layer::Create(); - - base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); - - cc::LayerTreeSettings settings; - settings.renderer_settings.refresh_rate = - context_factory_->DoesCreateTestContexts() - ? kTestRefreshRate - : kDefaultRefreshRate; - settings.main_frame_before_activation_enabled = false; - settings.throttle_frame_production = - !command_line->HasSwitch(switches::kDisableGpuVsync); -#if !defined(OS_MACOSX) - settings.renderer_settings.partial_swap_enabled = - !command_line->HasSwitch(cc::switches::kUIDisablePartialSwap); -#endif -#if defined(OS_CHROMEOS) - settings.per_tile_painting_enabled = true; -#endif -#if defined(OS_WIN) - settings.disable_hi_res_timer_tasks_on_battery = true; -#endif - - // These flags should be mirrored by renderer versions in content/renderer/. - settings.initial_debug_state.show_debug_borders = - command_line->HasSwitch(cc::switches::kUIShowCompositedLayerBorders); - settings.initial_debug_state.show_fps_counter = - command_line->HasSwitch(cc::switches::kUIShowFPSCounter); - settings.initial_debug_state.show_layer_animation_bounds_rects = - command_line->HasSwitch(cc::switches::kUIShowLayerAnimationBounds); - settings.initial_debug_state.show_paint_rects = - command_line->HasSwitch(switches::kUIShowPaintRects); - settings.initial_debug_state.show_property_changed_rects = - command_line->HasSwitch(cc::switches::kUIShowPropertyChangedRects); - settings.initial_debug_state.show_surface_damage_rects = - command_line->HasSwitch(cc::switches::kUIShowSurfaceDamageRects); - settings.initial_debug_state.show_screen_space_rects = - command_line->HasSwitch(cc::switches::kUIShowScreenSpaceRects); - settings.initial_debug_state.show_replica_screen_space_rects = - command_line->HasSwitch(cc::switches::kUIShowReplicaScreenSpaceRects); - settings.initial_debug_state.show_occluding_rects = - command_line->HasSwitch(cc::switches::kUIShowOccludingRects); - settings.initial_debug_state.show_non_occluding_rects = - command_line->HasSwitch(cc::switches::kUIShowNonOccludingRects); - - settings.initial_debug_state.SetRecordRenderingStats( - command_line->HasSwitch(cc::switches::kEnableGpuBenchmarking)); - - settings.impl_side_painting = IsUIImplSidePaintingEnabled(); - settings.use_zero_copy = IsUIZeroCopyEnabled(); - settings.single_thread_proxy_scheduler = false; - - base::TimeTicks before_create = base::TimeTicks::Now(); - if (compositor_thread_loop_.get()) { - host_ = cc::LayerTreeHost::CreateThreaded( - this, - context_factory_->GetSharedBitmapManager(), - context_factory_->GetGpuMemoryBufferManager(), - settings, - task_runner_, - compositor_thread_loop_, - nullptr); - } else { - host_ = cc::LayerTreeHost::CreateSingleThreaded( - this, - this, - context_factory_->GetSharedBitmapManager(), - context_factory_->GetGpuMemoryBufferManager(), - settings, - task_runner_, - nullptr); - } - UMA_HISTOGRAM_TIMES("GPU.CreateBrowserCompositor", - base::TimeTicks::Now() - before_create); - host_->SetRootLayer(root_web_layer_); - host_->SetLayerTreeHostClientReady(); -} - -Compositor::~Compositor() { - TRACE_EVENT0("shutdown", "Compositor::destructor"); - - CancelCompositorLock(); - DCHECK(!compositor_lock_); - - if (root_layer_) - root_layer_->SetCompositor(NULL); - - // Stop all outstanding draws before telling the ContextFactory to tear - // down any contexts that the |host_| may rely upon. - host_.reset(); - - context_factory_->RemoveCompositor(this); -} - -void Compositor::SetOutputSurface(scoped_ptr<cc::OutputSurface> surface) { - host_->SetOutputSurface(surface.Pass()); -} - -void Compositor::ScheduleDraw() { - if (compositor_thread_loop_.get()) { - host_->SetNeedsCommit(); - } else if (!defer_draw_scheduling_) { - defer_draw_scheduling_ = true; - task_runner_->PostTask( - FROM_HERE, - base::Bind(&Compositor::Draw, weak_ptr_factory_.GetWeakPtr())); - } -} - -void Compositor::DidInitializeOutputSurface() { -} - -void Compositor::DidFailToInitializeOutputSurface() { - NOTREACHED() << "We don't support fallback"; -} - -void Compositor::SetRootLayer(Layer* root_layer) { - if (root_layer_ == root_layer) - return; - if (root_layer_) - root_layer_->SetCompositor(NULL); - root_layer_ = root_layer; - if (root_layer_ && !root_layer_->GetCompositor()) - root_layer_->SetCompositor(this); - root_web_layer_->RemoveAllChildren(); - if (root_layer_) - root_web_layer_->AddChild(root_layer_->cc_layer()); -} - -void Compositor::SetHostHasTransparentBackground( - bool host_has_transparent_background) { - host_->set_has_transparent_background(host_has_transparent_background); -} - -void Compositor::Draw() { - DCHECK(!compositor_thread_loop_.get()); - - defer_draw_scheduling_ = false; - if (waiting_on_compositing_end_) { - draw_on_compositing_end_ = true; - return; - } - if (!root_layer_) - return; - - TRACE_EVENT_ASYNC_BEGIN0("ui", "Compositor::Draw", last_started_frame_ + 1); - - DCHECK_NE(swap_state_, SWAP_POSTED); - swap_state_ = SWAP_NONE; - - waiting_on_compositing_end_ = true; - last_started_frame_++; - if (!IsLocked()) { - // TODO(nduca): Temporary while compositor calls - // compositeImmediately() directly. - cc::BeginFrameArgs args = cc::BeginFrameArgs::Create( - BEGINFRAME_FROM_HERE, gfx::FrameTime::Now(), base::TimeTicks(), - cc::BeginFrameArgs::DefaultInterval(), cc::BeginFrameArgs::SYNCHRONOUS); - BeginMainFrame(args); - host_->Composite(args.frame_time); - } - if (swap_state_ == SWAP_NONE) - NotifyEnd(); -} - -void Compositor::ScheduleFullRedraw() { - host_->SetNeedsRedraw(); -} - -void Compositor::ScheduleRedrawRect(const gfx::Rect& damage_rect) { - host_->SetNeedsRedrawRect(damage_rect); -} - -void Compositor::FinishAllRendering() { - host_->FinishAllRendering(); -} - -void Compositor::SetLatencyInfo(const ui::LatencyInfo& latency_info) { - scoped_ptr<cc::SwapPromise> swap_promise( - new cc::LatencyInfoSwapPromise(latency_info)); - host_->QueueSwapPromise(swap_promise.Pass()); -} - -void Compositor::SetScaleAndSize(float scale, const gfx::Size& size_in_pixel) { - DCHECK_GT(scale, 0); - if (!size_in_pixel.IsEmpty()) { - size_ = size_in_pixel; - host_->SetViewportSize(size_in_pixel); - root_web_layer_->SetBounds(size_in_pixel); - } - if (device_scale_factor_ != scale) { - device_scale_factor_ = scale; - host_->SetDeviceScaleFactor(scale); - if (root_layer_) - root_layer_->OnDeviceScaleFactorChanged(scale); - } -} - -void Compositor::SetBackgroundColor(SkColor color) { - host_->set_background_color(color); - ScheduleDraw(); -} - -void Compositor::SetVisible(bool visible) { - host_->SetVisible(visible); -} - -scoped_refptr<CompositorVSyncManager> Compositor::vsync_manager() const { - return vsync_manager_; -} - -void Compositor::AddObserver(CompositorObserver* observer) { -#if defined(OS_MACOSX) - // Debugging instrumentation for crbug.com/401630. - // TODO(ccameron): remove this. - CHECK(observer); - if (!observer_list_.HasObserver(observer)) - observer->observing_count_ += 1; -#endif - - observer_list_.AddObserver(observer); -} - -void Compositor::RemoveObserver(CompositorObserver* observer) { -#if defined(OS_MACOSX) - // Debugging instrumentation for crbug.com/401630. - // TODO(ccameron): remove this. - if (observer_list_.HasObserver(observer)) - observer->observing_count_ -= 1; -#endif - - observer_list_.RemoveObserver(observer); -} - -bool Compositor::HasObserver(CompositorObserver* observer) { - return observer_list_.HasObserver(observer); -} - -void Compositor::AddAnimationObserver(CompositorAnimationObserver* observer) { - animation_observer_list_.AddObserver(observer); - host_->SetNeedsAnimate(); -} - -void Compositor::RemoveAnimationObserver( - CompositorAnimationObserver* observer) { - animation_observer_list_.RemoveObserver(observer); -} - -bool Compositor::HasAnimationObserver(CompositorAnimationObserver* observer) { - return animation_observer_list_.HasObserver(observer); -} - -void Compositor::BeginMainFrame(const cc::BeginFrameArgs& args) { - FOR_EACH_OBSERVER(CompositorAnimationObserver, - animation_observer_list_, - OnAnimationStep(args.frame_time)); - if (animation_observer_list_.might_have_observers()) - host_->SetNeedsAnimate(); -} - -void Compositor::Layout() { - // We're sending damage that will be addressed during this composite - // cycle, so we don't need to schedule another composite to address it. - disable_schedule_composite_ = true; - if (root_layer_) - root_layer_->SendDamagedRects(); - disable_schedule_composite_ = false; -} - -void Compositor::RequestNewOutputSurface() { - bool fallback = false; - context_factory_->CreateOutputSurface(weak_ptr_factory_.GetWeakPtr(), - fallback); -} - -void Compositor::DidCommit() { - DCHECK(!IsLocked()); - FOR_EACH_OBSERVER(CompositorObserver, - observer_list_, - OnCompositingDidCommit(this)); -} - -void Compositor::DidCommitAndDrawFrame() { - base::TimeTicks start_time = gfx::FrameTime::Now(); - FOR_EACH_OBSERVER(CompositorObserver, - observer_list_, - OnCompositingStarted(this, start_time)); -} - -void Compositor::DidCompleteSwapBuffers() { - if (compositor_thread_loop_.get()) { - NotifyEnd(); - } else { - DCHECK_EQ(swap_state_, SWAP_POSTED); - NotifyEnd(); - swap_state_ = SWAP_COMPLETED; - } -} - -void Compositor::ScheduleComposite() { - if (!disable_schedule_composite_) - ScheduleDraw(); -} - -void Compositor::ScheduleAnimation() { - ScheduleComposite(); -} - -void Compositor::DidPostSwapBuffers() { - DCHECK(!compositor_thread_loop_.get()); - DCHECK_EQ(swap_state_, SWAP_NONE); - swap_state_ = SWAP_POSTED; -} - -void Compositor::DidAbortSwapBuffers() { - if (!compositor_thread_loop_.get()) { - if (swap_state_ == SWAP_POSTED) { - NotifyEnd(); - swap_state_ = SWAP_COMPLETED; - } - } - - FOR_EACH_OBSERVER(CompositorObserver, - observer_list_, - OnCompositingAborted(this)); -} - -const cc::LayerTreeDebugState& Compositor::GetLayerTreeDebugState() const { - return host_->debug_state(); -} - -void Compositor::SetLayerTreeDebugState( - const cc::LayerTreeDebugState& debug_state) { - host_->SetDebugState(debug_state); -} - -cc::SurfaceSequence Compositor::InsertSurfaceSequenceForNextFrame() { - cc::SurfaceSequence sequence; - sequence.id_namespace = surface_id_allocator_->id_namespace(); - sequence.sequence = ++surface_sequence_number_; - scoped_ptr<cc::SwapPromise> promise( - new SatisfySwapPromise(surface_sequence_number_)); - host_->QueueSwapPromise(promise.Pass()); - return sequence; -} - -scoped_refptr<CompositorLock> Compositor::GetCompositorLock() { - if (!compositor_lock_) { - compositor_lock_ = new CompositorLock(this); - if (compositor_thread_loop_.get()) - host_->SetDeferCommits(true); - FOR_EACH_OBSERVER(CompositorObserver, - observer_list_, - OnCompositingLockStateChanged(this)); - } - return compositor_lock_; -} - -void Compositor::UnlockCompositor() { - DCHECK(compositor_lock_); - compositor_lock_ = NULL; - if (compositor_thread_loop_.get()) - host_->SetDeferCommits(false); - FOR_EACH_OBSERVER(CompositorObserver, - observer_list_, - OnCompositingLockStateChanged(this)); -} - -void Compositor::CancelCompositorLock() { - if (compositor_lock_) - compositor_lock_->CancelLock(); -} - -void Compositor::NotifyEnd() { - last_ended_frame_++; - TRACE_EVENT_ASYNC_END0("ui", "Compositor::Draw", last_ended_frame_); - waiting_on_compositing_end_ = false; - if (draw_on_compositing_end_) { - draw_on_compositing_end_ = false; - - // Call ScheduleDraw() instead of Draw() in order to allow other - // CompositorObservers to be notified before starting another - // draw cycle. - ScheduleDraw(); - } - FOR_EACH_OBSERVER( - CompositorObserver, observer_list_, OnCompositingEnded(this)); -} - -} // namespace ui
diff --git a/ui/compositor/compositor.gyp b/ui/compositor/compositor.gyp deleted file mode 100644 index 76cb687..0000000 --- a/ui/compositor/compositor.gyp +++ /dev/null
@@ -1,183 +0,0 @@ -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -{ - 'variables': { - 'chromium_code': 1, - }, - 'targets': [ - { - 'target_name': 'compositor', - 'type': '<(component)', - 'dependencies': [ - '<(DEPTH)/base/base.gyp:base', - '<(DEPTH)/base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', - '<(DEPTH)/cc/cc.gyp:cc', - '<(DEPTH)/cc/cc.gyp:cc_surfaces', - '<(DEPTH)/gpu/gpu.gyp:command_buffer_common', - '<(DEPTH)/skia/skia.gyp:skia', - '<(DEPTH)/ui/gfx/gfx.gyp:gfx', - '<(DEPTH)/ui/gfx/gfx.gyp:gfx_geometry', - '<(DEPTH)/ui/gl/gl.gyp:gl', - ], - 'defines': [ - 'COMPOSITOR_IMPLEMENTATION', - ], - 'sources': [ - 'closure_animation_observer.cc', - 'closure_animation_observer.h', - 'compositor.cc', - 'compositor.h', - 'compositor_animation_observer.h', - 'compositor_export.h', - 'compositor_observer.cc', - 'compositor_observer.h', - 'compositor_vsync_manager.cc', - 'compositor_vsync_manager.h', - 'compositor_switches.cc', - 'compositor_switches.h', - 'debug_utils.cc', - 'debug_utils.h', - 'dip_util.cc', - 'dip_util.h', - 'float_animation_curve_adapter.cc', - 'float_animation_curve_adapter.h', - 'layer.cc', - 'layer.h', - 'layer_animation_delegate.h', - 'layer_animation_element.cc', - 'layer_animation_element.h', - 'layer_animation_observer.cc', - 'layer_animation_observer.h', - 'layer_animation_sequence.cc', - 'layer_animation_sequence.h', - 'layer_animator.cc', - 'layer_animator.h', - 'layer_animator_collection.cc', - 'layer_animator_collection.h', - 'layer_delegate.h', - 'layer_owner.cc', - 'layer_owner.h', - 'layer_tree_owner.cc', - 'layer_tree_owner.h', - 'layer_type.h', - 'reflector.h', - 'scoped_animation_duration_scale_mode.cc', - 'scoped_animation_duration_scale_mode.h', - 'scoped_layer_animation_settings.cc', - 'scoped_layer_animation_settings.h', - 'transform_animation_curve_adapter.cc', - 'transform_animation_curve_adapter.h', - ], - 'conditions': [ - ['OS == "win" and use_aura == 1', { - # TODO(sky): before we make this real need to remove - # IDR_BITMAP_BRUSH_IMAGE. - 'dependencies': [ - '<(DEPTH)/ui/resources/ui_resources.gyp:ui_resources', - '<(angle_path)/src/angle.gyp:libEGL', - '<(angle_path)/src/angle.gyp:libGLESv2', - ], - }], - ], - }, - { - 'target_name': 'compositor_test_support', - 'type': 'static_library', - 'dependencies': [ - '<(DEPTH)/base/base.gyp:base', - '<(DEPTH)/cc/cc.gyp:cc', - '<(DEPTH)/cc/cc.gyp:cc_surfaces', - '<(DEPTH)/cc/cc_tests.gyp:cc_test_support', - '<(DEPTH)/skia/skia.gyp:skia', - '<(DEPTH)/testing/gtest.gyp:gtest', - '<(DEPTH)/third_party/WebKit/public/blink.gyp:blink_minimal', - '<(DEPTH)/ui/base/ui_base.gyp:ui_base', - '<(DEPTH)/ui/gfx/gfx.gyp:gfx', - '<(DEPTH)/ui/gfx/gfx.gyp:gfx_geometry', - '<(DEPTH)/ui/gl/gl.gyp:gl', - '<(DEPTH)/webkit/common/gpu/webkit_gpu.gyp:webkit_gpu', - 'compositor', - ], - 'sources': [ - 'test/context_factories_for_test.cc', - 'test/context_factories_for_test.h', - 'test/draw_waiter_for_test.cc', - 'test/draw_waiter_for_test.h', - 'test/in_process_context_factory.cc', - 'test/in_process_context_factory.h', - 'test/layer_animator_test_controller.cc', - 'test/layer_animator_test_controller.h', - 'test/test_compositor_host.h', - 'test/test_compositor_host_mac.mm', - 'test/test_compositor_host_ozone.cc', - 'test/test_compositor_host_win.cc', - 'test/test_compositor_host_x11.cc', - 'test/test_layer_animation_delegate.cc', - 'test/test_layer_animation_delegate.h', - 'test/test_layer_animation_observer.cc', - 'test/test_layer_animation_observer.h', - 'test/test_layers.cc', - 'test/test_layers.h', - 'test/test_suite.cc', - 'test/test_suite.h', - 'test/test_utils.cc', - 'test/test_utils.h', - ], - 'conditions': [ - ['use_x11==1', { - 'dependencies': [ - '<(DEPTH)/build/linux/system.gyp:x11', - '<(DEPTH)/ui/gfx/x/gfx_x11.gyp:gfx_x11', - ] - }] - ] - }, - { - 'target_name': 'compositor_unittests', - 'type': 'executable', - 'dependencies': [ - '<(DEPTH)/base/base.gyp:base', - '<(DEPTH)/base/base.gyp:test_support_base', - '<(DEPTH)/cc/cc.gyp:cc', - '<(DEPTH)/cc/cc_tests.gyp:cc_test_support', - '<(DEPTH)/skia/skia.gyp:skia', - '<(DEPTH)/testing/gtest.gyp:gtest', - '<(DEPTH)/ui/base/ui_base.gyp:ui_base', - '<(DEPTH)/ui/gfx/gfx.gyp:gfx', - '<(DEPTH)/ui/gfx/gfx.gyp:gfx_geometry', - '<(DEPTH)/ui/gl/gl.gyp:gl', - '<(DEPTH)/ui/resources/ui_resources.gyp:ui_resources', - 'compositor', - 'compositor_test_support', - ], - 'sources': [ - 'layer_animation_element_unittest.cc', - 'layer_animation_sequence_unittest.cc', - 'layer_animator_unittest.cc', - 'layer_owner_unittest.cc', - 'layer_unittest.cc', - 'run_all_unittests.cc', - 'transform_animation_curve_adapter_unittest.cc', - ], - 'conditions': [ - # osmesa GL implementation is used on linux. - ['OS=="linux"', { - 'dependencies': [ - '<(DEPTH)/third_party/mesa/mesa.gyp:osmesa', - ], - }], - ['os_posix == 1 and OS != "mac"', { - 'conditions': [ - ['use_allocator!="none"', { - 'dependencies': [ - '<(DEPTH)/base/allocator/allocator.gyp:allocator', - ], - }], - ], - }], - ], - }, - ], -}
diff --git a/ui/compositor/compositor.h b/ui/compositor/compositor.h deleted file mode 100644 index a1707a3..0000000 --- a/ui/compositor/compositor.h +++ /dev/null
@@ -1,351 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_COMPOSITOR_H_ -#define UI_COMPOSITOR_COMPOSITOR_H_ - -#include <string> - -#include "base/containers/hash_tables.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "base/observer_list.h" -#include "base/single_thread_task_runner.h" -#include "base/time/time.h" -#include "cc/surfaces/surface_sequence.h" -#include "cc/trees/layer_tree_host_client.h" -#include "cc/trees/layer_tree_host_single_thread_client.h" -#include "third_party/skia/include/core/SkColor.h" -#include "ui/compositor/compositor_animation_observer.h" -#include "ui/compositor/compositor_export.h" -#include "ui/compositor/compositor_observer.h" -#include "ui/compositor/layer_animator_collection.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/gfx/size.h" -#include "ui/gfx/vector2d.h" - -class SkBitmap; - -namespace base { -class MessageLoopProxy; -class RunLoop; -} - -namespace cc { -class ContextProvider; -class Layer; -class LayerTreeDebugState; -class LayerTreeHost; -class SharedBitmapManager; -class SurfaceIdAllocator; -} - -namespace gfx { -class Rect; -class Size; -} - -namespace gpu { -class GpuMemoryBufferManager; -struct Mailbox; -} - -namespace ui { - -class Compositor; -class CompositorVSyncManager; -class Layer; -class Reflector; -class Texture; -struct LatencyInfo; - -// This class abstracts the creation of the 3D context for the compositor. It is -// a global object. -class COMPOSITOR_EXPORT ContextFactory { - public: - virtual ~ContextFactory() {} - - // Creates an output surface for the given compositor. The factory may keep - // per-compositor data (e.g. a shared context), that needs to be cleaned up - // by calling RemoveCompositor when the compositor gets destroyed. - virtual void CreateOutputSurface(base::WeakPtr<Compositor> compositor, - bool software_fallback) = 0; - - // Creates a reflector that copies the content of the |mirrored_compositor| - // onto |mirroring_layer|. - virtual scoped_refptr<Reflector> CreateReflector( - Compositor* mirrored_compositor, - Layer* mirroring_layer) = 0; - // Removes the reflector, which stops the mirroring. - virtual void RemoveReflector(scoped_refptr<Reflector> reflector) = 0; - - // Return a reference to a shared offscreen context provider usable from the - // main thread. - virtual scoped_refptr<cc::ContextProvider> - SharedMainThreadContextProvider() = 0; - - // Destroys per-compositor data. - virtual void RemoveCompositor(Compositor* compositor) = 0; - - // When true, the factory uses test contexts that do not do real GL - // operations. - virtual bool DoesCreateTestContexts() = 0; - - // Gets the shared bitmap manager for software mode. - virtual cc::SharedBitmapManager* GetSharedBitmapManager() = 0; - - // Gets the GPU memory buffer manager. - virtual gpu::GpuMemoryBufferManager* GetGpuMemoryBufferManager() = 0; - - // Gets the compositor message loop, or NULL if not using threaded - // compositing. - virtual base::MessageLoopProxy* GetCompositorMessageLoop() = 0; - - // Creates a Surface ID allocator with a new namespace. - virtual scoped_ptr<cc::SurfaceIdAllocator> CreateSurfaceIdAllocator() = 0; -}; - -// This class represents a lock on the compositor, that can be used to prevent -// commits to the compositor tree while we're waiting for an asynchronous -// event. The typical use case is when waiting for a renderer to produce a frame -// at the right size. The caller keeps a reference on this object, and drops the -// reference once it desires to release the lock. -// Note however that the lock is cancelled after a short timeout to ensure -// responsiveness of the UI, so the compositor tree should be kept in a -// "reasonable" state while the lock is held. -// Don't instantiate this class directly, use Compositor::GetCompositorLock. -class COMPOSITOR_EXPORT CompositorLock - : public base::RefCounted<CompositorLock>, - public base::SupportsWeakPtr<CompositorLock> { - private: - friend class base::RefCounted<CompositorLock>; - friend class Compositor; - - explicit CompositorLock(Compositor* compositor); - ~CompositorLock(); - - void CancelLock(); - - Compositor* compositor_; - DISALLOW_COPY_AND_ASSIGN(CompositorLock); -}; - -// Compositor object to take care of GPU painting. -// A Browser compositor object is responsible for generating the final -// displayable form of pixels comprising a single widget's contents. It draws an -// appropriately transformed texture for each transformed view in the widget's -// view hierarchy. -class COMPOSITOR_EXPORT Compositor - : NON_EXPORTED_BASE(public cc::LayerTreeHostClient), - NON_EXPORTED_BASE(public cc::LayerTreeHostSingleThreadClient) { - public: - Compositor(gfx::AcceleratedWidget widget, - ui::ContextFactory* context_factory, - scoped_refptr<base::SingleThreadTaskRunner> task_runner); - ~Compositor() override; - - ui::ContextFactory* context_factory() { return context_factory_; } - - void SetOutputSurface(scoped_ptr<cc::OutputSurface> surface); - - // Schedules a redraw of the layer tree associated with this compositor. - void ScheduleDraw(); - - // Sets the root of the layer tree drawn by this Compositor. The root layer - // must have no parent. The compositor's root layer is reset if the root layer - // is destroyed. NULL can be passed to reset the root layer, in which case the - // compositor will stop drawing anything. - // The Compositor does not own the root layer. - const Layer* root_layer() const { return root_layer_; } - Layer* root_layer() { return root_layer_; } - void SetRootLayer(Layer* root_layer); - - // Called when we need the compositor to preserve the alpha channel in the - // output for situations when we want to render transparently atop something - // else, e.g. Aero glass. - void SetHostHasTransparentBackground(bool host_has_transparent_background); - - // The scale factor of the device that this compositor is - // compositing layers on. - float device_scale_factor() const { return device_scale_factor_; } - - // Draws the scene created by the layer tree and any visual effects. - void Draw(); - - // Where possible, draws are scissored to a damage region calculated from - // changes to layer properties. This bypasses that and indicates that - // the whole frame needs to be drawn. - void ScheduleFullRedraw(); - - // Schedule redraw and append damage_rect to the damage region calculated - // from changes to layer properties. - void ScheduleRedrawRect(const gfx::Rect& damage_rect); - - // Finishes all outstanding rendering on the GPU. - void FinishAllRendering(); - - void SetLatencyInfo(const LatencyInfo& latency_info); - - // Sets the compositor's device scale factor and size. - void SetScaleAndSize(float scale, const gfx::Size& size_in_pixel); - - // Returns the size of the widget that is being drawn to in pixel coordinates. - const gfx::Size& size() const { return size_; } - - // Sets the background color used for areas that aren't covered by - // the |root_layer|. - void SetBackgroundColor(SkColor color); - - // Set the visibility of the underlying compositor. - void SetVisible(bool visible); - - // Returns the widget for this compositor. - gfx::AcceleratedWidget widget() const { return widget_; } - - // Returns the vsync manager for this compositor. - scoped_refptr<CompositorVSyncManager> vsync_manager() const; - - // Returns the main thread task runner this compositor uses. Users of the - // compositor generally shouldn't use this. - scoped_refptr<base::SingleThreadTaskRunner> task_runner() const { - return task_runner_; - } - - // Compositor does not own observers. It is the responsibility of the - // observer to remove itself when it is done observing. - void AddObserver(CompositorObserver* observer); - void RemoveObserver(CompositorObserver* observer); - bool HasObserver(CompositorObserver* observer); - - void AddAnimationObserver(CompositorAnimationObserver* observer); - void RemoveAnimationObserver(CompositorAnimationObserver* observer); - bool HasAnimationObserver(CompositorAnimationObserver* observer); - - // Creates a compositor lock. Returns NULL if it is not possible to lock at - // this time (i.e. we're waiting to complete a previous unlock). - scoped_refptr<CompositorLock> GetCompositorLock(); - - // Internal functions, called back by command-buffer contexts on swap buffer - // events. - - // Signals swap has been posted. - void OnSwapBuffersPosted(); - - // Signals swap has completed. - void OnSwapBuffersComplete(); - - // Signals swap has aborted (e.g. lost context). - void OnSwapBuffersAborted(); - - // LayerTreeHostClient implementation. - void WillBeginMainFrame(int frame_id) override {} - void DidBeginMainFrame() override {} - void BeginMainFrame(const cc::BeginFrameArgs& args) override; - void Layout() override; - void ApplyViewportDeltas(const gfx::Vector2d& inner_delta, - const gfx::Vector2d& outer_delta, - const gfx::Vector2dF& elastic_overscroll_delta, - float page_scale, - float top_controls_delta) override {} - void ApplyViewportDeltas(const gfx::Vector2d& scroll_delta, - float page_scale, - float top_controls_delta) override {} - void RequestNewOutputSurface() override; - void DidInitializeOutputSurface() override; - void DidFailToInitializeOutputSurface() override; - void WillCommit() override {} - void DidCommit() override; - void DidCommitAndDrawFrame() override; - void DidCompleteSwapBuffers() override; - - // cc::LayerTreeHostSingleThreadClient implementation. - void ScheduleComposite() override; - void ScheduleAnimation() override; - void DidPostSwapBuffers() override; - void DidAbortSwapBuffers() override; - - int last_started_frame() { return last_started_frame_; } - int last_ended_frame() { return last_ended_frame_; } - - bool IsLocked() { return compositor_lock_ != NULL; } - - const cc::LayerTreeDebugState& GetLayerTreeDebugState() const; - void SetLayerTreeDebugState(const cc::LayerTreeDebugState& debug_state); - - LayerAnimatorCollection* layer_animator_collection() { - return &layer_animator_collection_; - } - - // Inserts a SurfaceSequence that will be satisfied on the next frame this - // compositor commits and swaps. - cc::SurfaceSequence InsertSurfaceSequenceForNextFrame(); - - cc::SurfaceIdAllocator* surface_id_allocator() { - return surface_id_allocator_.get(); - } - - private: - friend class base::RefCounted<Compositor>; - friend class CompositorLock; - - // Called by CompositorLock. - void UnlockCompositor(); - - // Called to release any pending CompositorLock - void CancelCompositorLock(); - - // Notifies the compositor that compositing is complete. - void NotifyEnd(); - - gfx::Size size_; - - ui::ContextFactory* context_factory_; - - // The root of the Layer tree drawn by this compositor. - Layer* root_layer_; - - ObserverList<CompositorObserver> observer_list_; - ObserverList<CompositorAnimationObserver> animation_observer_list_; - - gfx::AcceleratedWidget widget_; - scoped_ptr<cc::SurfaceIdAllocator> surface_id_allocator_; - uint32_t surface_sequence_number_; - scoped_refptr<cc::Layer> root_web_layer_; - scoped_ptr<cc::LayerTreeHost> host_; - scoped_refptr<base::MessageLoopProxy> compositor_thread_loop_; - scoped_refptr<base::SingleThreadTaskRunner> task_runner_; - - // The manager of vsync parameters for this compositor. - scoped_refptr<CompositorVSyncManager> vsync_manager_; - - // The device scale factor of the monitor that this compositor is compositing - // layers on. - float device_scale_factor_; - - int last_started_frame_; - int last_ended_frame_; - - bool disable_schedule_composite_; - - CompositorLock* compositor_lock_; - - // Prevent more than one draw from being scheduled. - bool defer_draw_scheduling_; - - // Used to prevent Draw()s while a composite is in progress. - bool waiting_on_compositing_end_; - bool draw_on_compositing_end_; - enum SwapState { SWAP_NONE, SWAP_POSTED, SWAP_COMPLETED }; - SwapState swap_state_; - - LayerAnimatorCollection layer_animator_collection_; - - base::WeakPtrFactory<Compositor> weak_ptr_factory_; - - DISALLOW_COPY_AND_ASSIGN(Compositor); -}; - -} // namespace ui - -#endif // UI_COMPOSITOR_COMPOSITOR_H_
diff --git a/ui/compositor/compositor_animation_observer.h b/ui/compositor/compositor_animation_observer.h deleted file mode 100644 index facfe5a..0000000 --- a/ui/compositor/compositor_animation_observer.h +++ /dev/null
@@ -1,22 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_COMPOSITOR_ANIMATION_OBSERVER_H_ -#define UI_COMPOSITOR_COMPOSITOR_ANIMATION_OBSERVER_H_ - -#include "base/time/time.h" -#include "ui/compositor/compositor_export.h" - -namespace ui { - -class COMPOSITOR_EXPORT CompositorAnimationObserver { - public: - virtual ~CompositorAnimationObserver() {} - - virtual void OnAnimationStep(base::TimeTicks timestamp) = 0; -}; - -} // namespace ui - -#endif // UI_COMPOSITOR_COMPOSITOR_ANIMATION_OBSERVER_H_
diff --git a/ui/compositor/compositor_constants.h b/ui/compositor/compositor_constants.h deleted file mode 100644 index ef007b0..0000000 --- a/ui/compositor/compositor_constants.h +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_COMPOSITOR_CONSTANTS_H_ -#define UI_COMPOSITOR_COMPOSITOR_CONSTANTS_H_ - -// This flag is used to work around a rendering bug in Windows where the -// software surface becomes inconsistent with the hardware surface. This -// happens in particular circumstances (Classic mode, Chrome using hardware -// rendering, and the window on a secondary monitor) and when moving the mouse -// over the window, Windows restores the GDI software surface underneath the -// mouse, rather than the hardware surface we've painted. As a result, for -// small or infrequently painting windows, we force back to the software -// compositor to avoid this bug. See http://crbug.com/333380. -const wchar_t kForceSoftwareCompositor[] = L"Chrome.ForceSoftwareCompositor"; - -#endif // UI_COMPOSITOR_COMPOSITOR_CONSTANTS_H_
diff --git a/ui/compositor/compositor_export.h b/ui/compositor/compositor_export.h deleted file mode 100644 index e219043..0000000 --- a/ui/compositor/compositor_export.h +++ /dev/null
@@ -1,29 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_COMPOSITOR_EXPORT_H_ -#define UI_COMPOSITOR_COMPOSITOR_EXPORT_H_ - -#if defined(COMPONENT_BUILD) -#if defined(WIN32) - -#if defined(COMPOSITOR_IMPLEMENTATION) -#define COMPOSITOR_EXPORT __declspec(dllexport) -#else -#define COMPOSITOR_EXPORT __declspec(dllimport) -#endif // defined(COMPOSITOR_IMPLEMENTATION) - -#else // defined(WIN32) -#if defined(COMPOSITOR_IMPLEMENTATION) -#define COMPOSITOR_EXPORT __attribute__((visibility("default"))) -#else -#define COMPOSITOR_EXPORT -#endif -#endif - -#else // defined(COMPONENT_BUILD) -#define COMPOSITOR_EXPORT -#endif - -#endif // UI_COMPOSITOR_COMPOSITOR_EXPORT_H_
diff --git a/ui/compositor/compositor_observer.cc b/ui/compositor/compositor_observer.cc deleted file mode 100644 index 209cd52..0000000 --- a/ui/compositor/compositor_observer.cc +++ /dev/null
@@ -1,28 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/compositor/compositor_observer.h" - -#include "base/logging.h" - -namespace ui { - -#if defined(OS_MACOSX) -// Debugging instrumentation for crbug.com/401630. -// TODO(ccameron): remove this. -CompositorObserver::CompositorObserver() : observing_count_(0) {} -#else -CompositorObserver::CompositorObserver() {} -#endif - -CompositorObserver::~CompositorObserver() { -#if defined(OS_MACOSX) - // Debugging instrumentation for crbug.com/401630. - // TODO(ccameron): remove this. - CHECK_EQ(observing_count_, 0); -#endif -} - -} -
diff --git a/ui/compositor/compositor_observer.h b/ui/compositor/compositor_observer.h deleted file mode 100644 index 76b6c5b..0000000 --- a/ui/compositor/compositor_observer.h +++ /dev/null
@@ -1,56 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_COMPOSITOR_OBSERVER_H_ -#define UI_COMPOSITOR_COMPOSITOR_OBSERVER_H_ - -#include "base/time/time.h" -#include "ui/compositor/compositor_export.h" - -namespace ui { - -class Compositor; - -// A compositor observer is notified when compositing completes. -class COMPOSITOR_EXPORT CompositorObserver { - public: - CompositorObserver(); - - // A commit proxies information from the main thread to the compositor - // thread. It typically happens when some state changes that will require a - // composite. In the multi-threaded case, many commits may happen between - // two successive composites. In the single-threaded, a single commit - // between two composites (just before the composite as part of the - // composite cycle). If the compositor is locked, it will not send this - // this signal. - virtual void OnCompositingDidCommit(Compositor* compositor) = 0; - - // Called when compositing started: it has taken all the layer changes into - // account and has issued the graphics commands. - virtual void OnCompositingStarted(Compositor* compositor, - base::TimeTicks start_time) = 0; - - // Called when compositing completes: the present to screen has completed. - virtual void OnCompositingEnded(Compositor* compositor) = 0; - - // Called when compositing is aborted (e.g. lost graphics context). - virtual void OnCompositingAborted(Compositor* compositor) = 0; - - // Called when the compositor lock state changes. - virtual void OnCompositingLockStateChanged(Compositor* compositor) = 0; - - protected: -#if defined(OS_MACOSX) - // Debugging instrumentation for crbug.com/401630. - // TODO(ccameron): remove this. - friend class Compositor; - int32 observing_count_; -#endif - - virtual ~CompositorObserver(); -}; - -} // namespace ui - -#endif // UI_COMPOSITOR_COMPOSITOR_OBSERVER_H_
diff --git a/ui/compositor/compositor_switches.cc b/ui/compositor/compositor_switches.cc deleted file mode 100644 index 7103318..0000000 --- a/ui/compositor/compositor_switches.cc +++ /dev/null
@@ -1,44 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/compositor/compositor_switches.h" - -#include "base/command_line.h" - -using base::CommandLine; - -namespace switches { - -// Enable compositing individual elements via hardware overlays when -// permitted by device. -const char kEnableHardwareOverlays[] = "enable-hardware-overlays"; - -// Forces tests to produce pixel output when they normally wouldn't. -const char kEnablePixelOutputInTests[] = "enable-pixel-output-in-tests"; - -const char kUIDisableThreadedCompositing[] = "ui-disable-threaded-compositing"; - -const char kUIEnableImplSidePainting[] = "ui-enable-impl-side-painting"; - -const char kUIEnableZeroCopy[] = "ui-enable-zero-copy"; - -const char kUIShowPaintRects[] = "ui-show-paint-rects"; - -} // namespace switches - -namespace ui { - -bool IsUIImplSidePaintingEnabled() { - const CommandLine& command_line = *CommandLine::ForCurrentProcess(); - - return command_line.HasSwitch(switches::kUIEnableImplSidePainting); -} - -bool IsUIZeroCopyEnabled() { - const CommandLine& command_line = *CommandLine::ForCurrentProcess(); - - return command_line.HasSwitch(switches::kUIEnableZeroCopy); -} - -} // namespace ui
diff --git a/ui/compositor/compositor_switches.h b/ui/compositor/compositor_switches.h deleted file mode 100644 index d487bdd..0000000 --- a/ui/compositor/compositor_switches.h +++ /dev/null
@@ -1,28 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_COMPOSITOR_SWITCHES_H_ -#define UI_COMPOSITOR_COMPOSITOR_SWITCHES_H_ - -#include "ui/compositor/compositor_export.h" - -namespace switches { - -COMPOSITOR_EXPORT extern const char kEnableHardwareOverlays[]; -COMPOSITOR_EXPORT extern const char kEnablePixelOutputInTests[]; -COMPOSITOR_EXPORT extern const char kUIDisableThreadedCompositing[]; -COMPOSITOR_EXPORT extern const char kUIEnableImplSidePainting[]; -COMPOSITOR_EXPORT extern const char kUIEnableZeroCopy[]; -COMPOSITOR_EXPORT extern const char kUIShowPaintRects[]; - -} // namespace switches - -namespace ui { - -COMPOSITOR_EXPORT bool IsUIImplSidePaintingEnabled(); -COMPOSITOR_EXPORT bool IsUIZeroCopyEnabled(); - -} // namespace ui - -#endif // UI_COMPOSITOR_COMPOSITOR_SWITCHES_H_
diff --git a/ui/compositor/compositor_vsync_manager.cc b/ui/compositor/compositor_vsync_manager.cc deleted file mode 100644 index 1a10d4a..0000000 --- a/ui/compositor/compositor_vsync_manager.cc +++ /dev/null
@@ -1,63 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/compositor/compositor_vsync_manager.h" - -namespace ui { - -CompositorVSyncManager::CompositorVSyncManager() - : observer_list_(new ObserverListThreadSafe<Observer>()), - authoritative_vsync_interval_(base::TimeDelta::FromSeconds(0)) {} - -CompositorVSyncManager::~CompositorVSyncManager() {} - -void CompositorVSyncManager::SetAuthoritativeVSyncInterval( - base::TimeDelta interval) { - base::TimeTicks timebase; - { - base::AutoLock lock(vsync_parameters_lock_); - timebase = last_timebase_; - authoritative_vsync_interval_ = interval; - last_interval_ = interval; - } - NotifyObservers(timebase, interval); -} - -void CompositorVSyncManager::UpdateVSyncParameters(base::TimeTicks timebase, - base::TimeDelta interval) { - { - base::AutoLock lock(vsync_parameters_lock_); - if (authoritative_vsync_interval_ != base::TimeDelta::FromSeconds(0)) - interval = authoritative_vsync_interval_; - last_timebase_ = timebase; - last_interval_ = interval; - } - NotifyObservers(timebase, interval); -} - -void CompositorVSyncManager::AddObserver(Observer* observer) { - base::TimeTicks timebase; - base::TimeDelta interval; - { - base::AutoLock lock(vsync_parameters_lock_); - timebase = last_timebase_; - interval = last_interval_; - } - observer_list_->AddObserver(observer); - observer->OnUpdateVSyncParameters(timebase, interval); -} - -void CompositorVSyncManager::RemoveObserver(Observer* observer) { - observer_list_->RemoveObserver(observer); -} - -void CompositorVSyncManager::NotifyObservers(base::TimeTicks timebase, - base::TimeDelta interval) { - observer_list_->Notify( - &CompositorVSyncManager::Observer::OnUpdateVSyncParameters, - timebase, - interval); -} - -} // namespace ui
diff --git a/ui/compositor/compositor_vsync_manager.h b/ui/compositor/compositor_vsync_manager.h deleted file mode 100644 index abfbad6..0000000 --- a/ui/compositor/compositor_vsync_manager.h +++ /dev/null
@@ -1,71 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_COMPOSITOR_VSYNC_MANAGER_H_ -#define UI_COMPOSITOR_COMPOSITOR_VSYNC_MANAGER_H_ - -#include "base/memory/ref_counted.h" -#include "base/observer_list_threadsafe.h" -#include "base/synchronization/lock.h" -#include "base/time/time.h" -#include "ui/compositor/compositor_export.h" - -namespace ui { - -// This class manages vsync parameters for a compositor. It merges updates of -// the parameters from different sources and sends the merged updates to -// observers which register to it. This class is explicitly synchronized and is -// safe to use and update from any thread. Observers of the manager will be -// notified on the thread they have registered from, and should be removed from -// the same thread. -class COMPOSITOR_EXPORT CompositorVSyncManager - : public base::RefCountedThreadSafe<CompositorVSyncManager> { - public: - class Observer { - public: - virtual void OnUpdateVSyncParameters(base::TimeTicks timebase, - base::TimeDelta interval) = 0; - }; - - CompositorVSyncManager(); - - // The "authoritative" vsync interval, if provided, will override |interval| - // as reported by UpdateVSyncParameters() whenever it is called. This is - // typically the value reported by a more reliable source, e.g. the platform - // display configuration. In the particular case of ChromeOS -- this is the - // value queried through XRandR, which is more reliable than the value - // queried through the 3D context. - void SetAuthoritativeVSyncInterval(base::TimeDelta interval); - - // The vsync parameters consist of |timebase|, which is the platform timestamp - // of the last vsync, and |interval|, which is the interval between vsyncs. - // |interval| may be overriden by SetAuthoritativeVSyncInterval() above. - void UpdateVSyncParameters(base::TimeTicks timebase, - base::TimeDelta interval); - - void AddObserver(Observer* observer); - void RemoveObserver(Observer* observer); - - private: - friend class base::RefCountedThreadSafe<CompositorVSyncManager>; - - ~CompositorVSyncManager(); - - void NotifyObservers(base::TimeTicks timebase, base::TimeDelta interval); - - // List of observers. - scoped_refptr<ObserverListThreadSafe<Observer> > observer_list_; - - // Protects the cached vsync parameters below. - base::Lock vsync_parameters_lock_; - base::TimeTicks last_timebase_; - base::TimeDelta last_interval_; - base::TimeDelta authoritative_vsync_interval_; - - DISALLOW_COPY_AND_ASSIGN(CompositorVSyncManager); -}; - -} // namespace ui - -#endif // UI_COMPOSITOR_COMPOSITOR_VSYNC_MANAGER_H_
diff --git a/ui/compositor/debug_utils.cc b/ui/compositor/debug_utils.cc deleted file mode 100644 index cae3abc..0000000 --- a/ui/compositor/debug_utils.cc +++ /dev/null
@@ -1,121 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#define _USE_MATH_DEFINES // For VC++ to get M_PI. This has to be first. - -#include "ui/compositor/debug_utils.h" - -#include <cmath> -#include <iomanip> -#include <ostream> -#include <string> - -#include "base/logging.h" -#include "base/strings/utf_string_conversions.h" -#include "ui/compositor/layer.h" -#include "ui/gfx/interpolated_transform.h" -#include "ui/gfx/point.h" -#include "ui/gfx/point_conversions.h" -#include "ui/gfx/transform.h" - -using base::UTF8ToWide; - -namespace ui { - -namespace { - -void PrintLayerHierarchyImp(const Layer* layer, - int indent, - gfx::Point mouse_location, - std::wostringstream* out) { - std::string indent_str(indent, ' '); - - layer->transform().TransformPointReverse(&mouse_location); - bool mouse_inside_layer_bounds = layer->bounds().Contains(mouse_location); - mouse_location.Offset(-layer->bounds().x(), -layer->bounds().y()); - - *out << UTF8ToWide(indent_str); - if (mouse_inside_layer_bounds) - *out << L'*'; - else - *out << L' '; - - *out << UTF8ToWide(layer->name()) << L' ' << layer; - - switch (layer->type()) { - case ui::LAYER_NOT_DRAWN: - *out << L" not_drawn"; - break; - case ui::LAYER_TEXTURED: - *out << L" textured"; - if (layer->fills_bounds_opaquely()) - *out << L" opaque"; - break; - case ui::LAYER_SOLID_COLOR: - *out << L" solid"; - break; - case ui::LAYER_NINE_PATCH: - *out << L" nine_patch"; - break; - } - - if (!layer->visible()) - *out << L" !visible"; - - std::string property_indent_str(indent+3, ' '); - *out << L'\n' << UTF8ToWide(property_indent_str); - *out << L"bounds: " << layer->bounds().x() << L',' << layer->bounds().y(); - *out << L' ' << layer->bounds().width() << L'x' << layer->bounds().height(); - if (!layer->subpixel_position_offset().IsZero()) - *out << " " << UTF8ToWide(layer->subpixel_position_offset().ToString()); - - const ui::Layer* mask = const_cast<ui::Layer*>(layer)->layer_mask_layer(); - - if (mask) { - *out << L'\n' << UTF8ToWide(property_indent_str); - *out << L"mask layer: " << std::setprecision(2) - << UTF8ToWide(mask->bounds().ToString()) - << UTF8ToWide(mask->subpixel_position_offset().ToString()); - } - - if (layer->opacity() != 1.0f) { - *out << L'\n' << UTF8ToWide(property_indent_str); - *out << L"opacity: " << std::setprecision(2) << layer->opacity(); - } - - gfx::DecomposedTransform decomp; - if (!layer->transform().IsIdentity() && - gfx::DecomposeTransform(&decomp, layer->transform())) { - *out << L'\n' << UTF8ToWide(property_indent_str); - *out << L"translation: " << std::fixed << decomp.translate[0]; - *out << L", " << decomp.translate[1]; - - *out << L'\n' << UTF8ToWide(property_indent_str); - *out << L"rotation: "; - *out << std::acos(decomp.quaternion[3]) * 360.0 / M_PI; - - *out << L'\n' << UTF8ToWide(property_indent_str); - *out << L"scale: " << decomp.scale[0]; - *out << L", " << decomp.scale[1]; - } - - *out << L'\n'; - - for (size_t i = 0, count = layer->children().size(); i < count; ++i) { - PrintLayerHierarchyImp( - layer->children()[i], indent + 3, mouse_location, out); - } -} - -} // namespace - -void PrintLayerHierarchy(const Layer* layer, gfx::Point mouse_location) { - std::wostringstream out; - out << L"Layer hierarchy:\n"; - PrintLayerHierarchyImp(layer, 0, mouse_location, &out); - // Error so logs can be collected from end-users. - LOG(ERROR) << out.str(); -} - -} // namespace ui
diff --git a/ui/compositor/debug_utils.h b/ui/compositor/debug_utils.h deleted file mode 100644 index 966b3ae..0000000 --- a/ui/compositor/debug_utils.h +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_DEBUG_UTILS_H_ -#define UI_COMPOSITOR_DEBUG_UTILS_H_ - -#include "ui/compositor/compositor_export.h" - -namespace gfx { -class Point; -} - -namespace ui { - -class Layer; - -// Log the layer hierarchy. Mark layers which contain |mouse_location| with '*'. -COMPOSITOR_EXPORT void PrintLayerHierarchy(const Layer* layer, - gfx::Point mouse_location); - -} // namespace ui - -#endif // UI_COMPOSITOR_DEBUG_UTILS_H_
diff --git a/ui/compositor/dip_util.cc b/ui/compositor/dip_util.cc deleted file mode 100644 index 69a33a7..0000000 --- a/ui/compositor/dip_util.cc +++ /dev/null
@@ -1,127 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/compositor/dip_util.h" - -#include "base/command_line.h" -#include "cc/layers/layer.h" -#include "ui/compositor/compositor.h" -#include "ui/compositor/compositor_switches.h" -#include "ui/compositor/layer.h" -#include "ui/gfx/display.h" -#include "ui/gfx/geometry/safe_integer_conversions.h" -#include "ui/gfx/point.h" -#include "ui/gfx/point_conversions.h" -#include "ui/gfx/rect.h" -#include "ui/gfx/rect_conversions.h" -#include "ui/gfx/size.h" -#include "ui/gfx/size_conversions.h" - -#if DCHECK_IS_ON() -#include "ui/compositor/layer_animator.h" -#endif - -namespace ui { - -float GetDeviceScaleFactor(const Layer* layer) { - return layer->device_scale_factor(); -} - -gfx::Point ConvertPointToDIP(const Layer* layer, - const gfx::Point& point_in_pixel) { - return gfx::ToFlooredPoint( - gfx::ScalePoint(point_in_pixel, 1.0f / GetDeviceScaleFactor(layer))); -} - -gfx::PointF ConvertPointToDIP(const Layer* layer, - const gfx::PointF& point_in_pixel) { - return gfx::ScalePoint(point_in_pixel, 1.0f / GetDeviceScaleFactor(layer)); -} - -gfx::Size ConvertSizeToDIP(const Layer* layer, - const gfx::Size& size_in_pixel) { - return gfx::ToFlooredSize( - gfx::ScaleSize(size_in_pixel, 1.0f / GetDeviceScaleFactor(layer))); -} - -gfx::Rect ConvertRectToDIP(const Layer* layer, - const gfx::Rect& rect_in_pixel) { - float scale = 1.0f / GetDeviceScaleFactor(layer); - return gfx::ToFlooredRectDeprecated(gfx::ScaleRect(rect_in_pixel, scale)); -} - -gfx::Point ConvertPointToPixel(const Layer* layer, - const gfx::Point& point_in_dip) { - return gfx::ToFlooredPoint( - gfx::ScalePoint(point_in_dip, GetDeviceScaleFactor(layer))); -} - -gfx::Size ConvertSizeToPixel(const Layer* layer, - const gfx::Size& size_in_dip) { - return gfx::ToFlooredSize( - gfx::ScaleSize(size_in_dip, GetDeviceScaleFactor(layer))); -} - -gfx::Rect ConvertRectToPixel(const Layer* layer, - const gfx::Rect& rect_in_dip) { - float scale = GetDeviceScaleFactor(layer); - // Use ToEnclosingRect() to ensure we paint all the possible pixels - // touched. ToEnclosingRect() floors the origin, and ceils the max - // coordinate. To do otherwise (such as flooring the size) potentially - // results in rounding down and not drawing all the pixels that are - // touched. - return gfx::ToEnclosingRect( - gfx::RectF(gfx::ScalePoint(rect_in_dip.origin(), scale), - gfx::ScaleSize(rect_in_dip.size(), scale))); -} - -#if DCHECK_IS_ON() -namespace { - -void CheckSnapped(float snapped_position) { - const float kEplison = 0.0001f; - float diff = std::abs(snapped_position - gfx::ToRoundedInt(snapped_position)); - DCHECK_LT(diff, kEplison); -} - -} // namespace -#endif - -void SnapLayerToPhysicalPixelBoundary(ui::Layer* snapped_layer, - ui::Layer* layer_to_snap) { - DCHECK_NE(snapped_layer, layer_to_snap); - DCHECK(snapped_layer); - DCHECK(snapped_layer->Contains(layer_to_snap)); - - gfx::Point view_offset_dips = layer_to_snap->GetTargetBounds().origin(); - ui::Layer::ConvertPointToLayer( - layer_to_snap->parent(), snapped_layer, &view_offset_dips); - gfx::PointF view_offset = view_offset_dips; - - float scale_factor = GetDeviceScaleFactor(layer_to_snap); - view_offset.Scale(scale_factor); - gfx::PointF view_offset_snapped(gfx::ToRoundedInt(view_offset.x()), - gfx::ToRoundedInt(view_offset.y())); - - gfx::Vector2dF fudge = view_offset_snapped - view_offset; - fudge.Scale(1.0 / scale_factor); - layer_to_snap->SetSubpixelPositionOffset(fudge); -#if DCHECK_IS_ON() - gfx::Point layer_offset; - gfx::PointF origin; - Layer::ConvertPointToLayer( - layer_to_snap->parent(), snapped_layer, &layer_offset); - if (layer_to_snap->GetAnimator()->is_animating()) { - origin = layer_to_snap->GetTargetBounds().origin() + - layer_to_snap->subpixel_position_offset(); - } else { - cc::Layer* cc_layer = layer_to_snap->cc_layer(); - origin = cc_layer->position(); - } - CheckSnapped((layer_offset.x() + origin.x()) * scale_factor); - CheckSnapped((layer_offset.y() + origin.y()) * scale_factor); -#endif -} - -} // namespace ui
diff --git a/ui/compositor/dip_util.h b/ui/compositor/dip_util.h deleted file mode 100644 index cac3681..0000000 --- a/ui/compositor/dip_util.h +++ /dev/null
@@ -1,56 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_DIP_UTIL_H_ -#define UI_COMPOSITOR_DIP_UTIL_H_ - -#include "ui/compositor/compositor_export.h" -#include "base/basictypes.h" -#include "ui/gfx/point_f.h" - -namespace gfx { -class Point; -class Size; -class Rect; -} // namespace gfx - -namespace ui { -class Layer; - -COMPOSITOR_EXPORT float GetDeviceScaleFactor(const Layer* layer); - -// Utility functions that convert point/size/rect between -// DIP and pixel coordinates system. -COMPOSITOR_EXPORT gfx::Point ConvertPointToDIP( - const Layer* layer, - const gfx::Point& point_in_pixel); -COMPOSITOR_EXPORT gfx::PointF ConvertPointToDIP( - const Layer* layer, - const gfx::PointF& point_in_pixel); -COMPOSITOR_EXPORT gfx::Size ConvertSizeToDIP( - const Layer* layer, - const gfx::Size& size_in_pixel); -COMPOSITOR_EXPORT gfx::Rect ConvertRectToDIP( - const Layer* layer, - const gfx::Rect& rect_in_pixel); -COMPOSITOR_EXPORT gfx::Point ConvertPointToPixel( - const Layer* layer, - const gfx::Point& point_in_dip); -COMPOSITOR_EXPORT gfx::Size ConvertSizeToPixel( - const Layer* layer, - const gfx::Size& size_in_dip); -COMPOSITOR_EXPORT gfx::Rect ConvertRectToPixel( - const Layer* layer, - const gfx::Rect& rect_in_dip); - -// Snaps the |layer_to_snap| to the physical pixel boundary. -// |snapped_layer| is a reference layer that should also be -// snapped at the pysical pixel boundary. -COMPOSITOR_EXPORT void SnapLayerToPhysicalPixelBoundary( - ui::Layer* snapped_layer, - ui::Layer* layer_to_snap); - -} // namespace ui - -#endif // UI_COMPOSITOR_DIP_UTIL_H_
diff --git a/ui/compositor/float_animation_curve_adapter.cc b/ui/compositor/float_animation_curve_adapter.cc deleted file mode 100644 index d40d701..0000000 --- a/ui/compositor/float_animation_curve_adapter.cc +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/compositor/float_animation_curve_adapter.h" - -#include "cc/base/time_util.h" - -namespace ui { - -FloatAnimationCurveAdapter::FloatAnimationCurveAdapter( - gfx::Tween::Type tween_type, - float initial_value, - float target_value, - base::TimeDelta duration) - : tween_type_(tween_type), - initial_value_(initial_value), - target_value_(target_value), - duration_(duration) { -} - -base::TimeDelta FloatAnimationCurveAdapter::Duration() const { - return duration_; -} - -scoped_ptr<cc::AnimationCurve> FloatAnimationCurveAdapter::Clone() const { - return make_scoped_ptr(new FloatAnimationCurveAdapter( - tween_type_, initial_value_, target_value_, duration_)); -} - -float FloatAnimationCurveAdapter::GetValue(base::TimeDelta t) const { - if (t >= duration_) - return target_value_; - if (t <= base::TimeDelta()) - return initial_value_; - double progress = cc::TimeUtil::Divide(t, duration_); - return gfx::Tween::FloatValueBetween( - gfx::Tween::CalculateValue(tween_type_, progress), - initial_value_, - target_value_); -} - -} // namespace ui
diff --git a/ui/compositor/float_animation_curve_adapter.h b/ui/compositor/float_animation_curve_adapter.h deleted file mode 100644 index dc665d4..0000000 --- a/ui/compositor/float_animation_curve_adapter.h +++ /dev/null
@@ -1,37 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_FLOAT_ANIMATION_CURVE_ADAPTER_H_ -#define UI_COMPOSITOR_FLOAT_ANIMATION_CURVE_ADAPTER_H_ - -#include "base/time/time.h" -#include "cc/animation/animation_curve.h" -#include "ui/gfx/animation/tween.h" - -namespace ui { - -class FloatAnimationCurveAdapter : public cc::FloatAnimationCurve { - public: - FloatAnimationCurveAdapter(gfx::Tween::Type tween_type, - float initial_value, - float target_value, - base::TimeDelta duration); - - ~FloatAnimationCurveAdapter() override {} - - // FloatAnimationCurve implementation. - base::TimeDelta Duration() const override; - scoped_ptr<cc::AnimationCurve> Clone() const override; - float GetValue(base::TimeDelta t) const override; - - private: - gfx::Tween::Type tween_type_; - float initial_value_; - float target_value_; - base::TimeDelta duration_; -}; - -} // namespace ui - -#endif // UI_COMPOSITOR_FLOAT_ANIMATION_CURVE_ADAPTER_H_
diff --git a/ui/compositor/layer.cc b/ui/compositor/layer.cc deleted file mode 100644 index 2d7b5b3..0000000 --- a/ui/compositor/layer.cc +++ /dev/null
@@ -1,1063 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/compositor/layer.h" - -#include <algorithm> - -#include "base/command_line.h" -#include "base/debug/trace_event.h" -#include "base/json/json_writer.h" -#include "base/lazy_instance.h" -#include "base/logging.h" -#include "base/memory/scoped_ptr.h" -#include "cc/base/scoped_ptr_algorithm.h" -#include "cc/layers/content_layer.h" -#include "cc/layers/delegated_renderer_layer.h" -#include "cc/layers/nine_patch_layer.h" -#include "cc/layers/picture_layer.h" -#include "cc/layers/solid_color_layer.h" -#include "cc/layers/surface_layer.h" -#include "cc/layers/texture_layer.h" -#include "cc/output/copy_output_request.h" -#include "cc/output/delegated_frame_data.h" -#include "cc/output/filter_operation.h" -#include "cc/output/filter_operations.h" -#include "cc/resources/transferable_resource.h" -#include "ui/compositor/compositor_switches.h" -#include "ui/compositor/dip_util.h" -#include "ui/compositor/layer_animator.h" -#include "ui/gfx/animation/animation.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/display.h" -#include "ui/gfx/interpolated_transform.h" -#include "ui/gfx/point3_f.h" -#include "ui/gfx/point_conversions.h" -#include "ui/gfx/size_conversions.h" - -namespace { - -const ui::Layer* GetRoot(const ui::Layer* layer) { - while (layer->parent()) - layer = layer->parent(); - return layer; -} - -struct UIImplSidePaintingStatus { - UIImplSidePaintingStatus() - : enabled(ui::IsUIImplSidePaintingEnabled()) { - } - bool enabled; -}; -base::LazyInstance<UIImplSidePaintingStatus> g_ui_impl_side_painting_status = - LAZY_INSTANCE_INITIALIZER; - -} // namespace - -namespace ui { - -Layer::Layer() - : type_(LAYER_TEXTURED), - compositor_(NULL), - parent_(NULL), - visible_(true), - force_render_surface_(false), - fills_bounds_opaquely_(true), - fills_bounds_completely_(false), - background_blur_radius_(0), - layer_saturation_(0.0f), - layer_brightness_(0.0f), - layer_grayscale_(0.0f), - layer_inverted_(false), - layer_mask_(NULL), - layer_mask_back_link_(NULL), - zoom_(1), - zoom_inset_(0), - delegate_(NULL), - owner_(NULL), - cc_layer_(NULL), - device_scale_factor_(1.0f) { - CreateCcLayer(); -} - -Layer::Layer(LayerType type) - : type_(type), - compositor_(NULL), - parent_(NULL), - visible_(true), - force_render_surface_(false), - fills_bounds_opaquely_(true), - fills_bounds_completely_(false), - background_blur_radius_(0), - layer_saturation_(0.0f), - layer_brightness_(0.0f), - layer_grayscale_(0.0f), - layer_inverted_(false), - layer_mask_(NULL), - layer_mask_back_link_(NULL), - zoom_(1), - zoom_inset_(0), - delegate_(NULL), - owner_(NULL), - cc_layer_(NULL), - device_scale_factor_(1.0f) { - CreateCcLayer(); -} - -Layer::~Layer() { - // Destroying the animator may cause observers to use the layer (and - // indirectly the WebLayer). Destroy the animator first so that the WebLayer - // is still around. - if (animator_.get()) - animator_->SetDelegate(NULL); - animator_ = NULL; - if (compositor_) - compositor_->SetRootLayer(NULL); - if (parent_) - parent_->Remove(this); - if (layer_mask_) - SetMaskLayer(NULL); - if (layer_mask_back_link_) - layer_mask_back_link_->SetMaskLayer(NULL); - for (size_t i = 0; i < children_.size(); ++i) - children_[i]->parent_ = NULL; - cc_layer_->RemoveLayerAnimationEventObserver(this); - cc_layer_->RemoveFromParent(); -} - -// static -bool Layer::UsingPictureLayer() { - return g_ui_impl_side_painting_status.Get().enabled; -} - -Compositor* Layer::GetCompositor() { - return GetRoot(this)->compositor_; -} - -float Layer::opacity() const { - return cc_layer_->opacity(); -} - -void Layer::SetCompositor(Compositor* compositor) { - // This function must only be called to set the compositor on the root layer, - // or to reset it. - DCHECK(!compositor || !compositor_); - DCHECK(!compositor || compositor->root_layer() == this); - DCHECK(!parent_); - if (compositor_) { - RemoveAnimatorsInTreeFromCollection( - compositor_->layer_animator_collection()); - } - compositor_ = compositor; - if (compositor) { - OnDeviceScaleFactorChanged(compositor->device_scale_factor()); - SendPendingThreadedAnimations(); - AddAnimatorsInTreeToCollection(compositor_->layer_animator_collection()); - } -} - -void Layer::Add(Layer* child) { - DCHECK(!child->compositor_); - if (child->parent_) - child->parent_->Remove(child); - child->parent_ = this; - children_.push_back(child); - cc_layer_->AddChild(child->cc_layer_); - child->OnDeviceScaleFactorChanged(device_scale_factor_); - if (GetCompositor()) - child->SendPendingThreadedAnimations(); - LayerAnimatorCollection* collection = GetLayerAnimatorCollection(); - if (collection) - child->AddAnimatorsInTreeToCollection(collection); -} - -void Layer::Remove(Layer* child) { - // Current bounds are used to calculate offsets when layers are reparented. - // Stop (and complete) an ongoing animation to update the bounds immediately. - LayerAnimator* child_animator = child->animator_.get(); - if (child_animator) - child_animator->StopAnimatingProperty(ui::LayerAnimationElement::BOUNDS); - LayerAnimatorCollection* collection = GetLayerAnimatorCollection(); - if (collection) - child->RemoveAnimatorsInTreeFromCollection(collection); - - std::vector<Layer*>::iterator i = - std::find(children_.begin(), children_.end(), child); - DCHECK(i != children_.end()); - children_.erase(i); - child->parent_ = NULL; - child->cc_layer_->RemoveFromParent(); -} - -void Layer::StackAtTop(Layer* child) { - if (children_.size() <= 1 || child == children_.back()) - return; // Already in front. - StackAbove(child, children_.back()); -} - -void Layer::StackAbove(Layer* child, Layer* other) { - StackRelativeTo(child, other, true); -} - -void Layer::StackAtBottom(Layer* child) { - if (children_.size() <= 1 || child == children_.front()) - return; // Already on bottom. - StackBelow(child, children_.front()); -} - -void Layer::StackBelow(Layer* child, Layer* other) { - StackRelativeTo(child, other, false); -} - -bool Layer::Contains(const Layer* other) const { - for (const Layer* parent = other; parent; parent = parent->parent()) { - if (parent == this) - return true; - } - return false; -} - -void Layer::SetAnimator(LayerAnimator* animator) { - if (animator) - animator->SetDelegate(this); - animator_ = animator; -} - -LayerAnimator* Layer::GetAnimator() { - if (!animator_.get()) - SetAnimator(LayerAnimator::CreateDefaultAnimator()); - return animator_.get(); -} - -void Layer::SetTransform(const gfx::Transform& transform) { - GetAnimator()->SetTransform(transform); -} - -gfx::Transform Layer::GetTargetTransform() const { - if (animator_.get() && animator_->IsAnimatingProperty( - LayerAnimationElement::TRANSFORM)) { - return animator_->GetTargetTransform(); - } - return transform(); -} - -void Layer::SetBounds(const gfx::Rect& bounds) { - GetAnimator()->SetBounds(bounds); -} - -void Layer::SetSubpixelPositionOffset(const gfx::Vector2dF offset) { - subpixel_position_offset_ = offset; - RecomputePosition(); -} - -gfx::Rect Layer::GetTargetBounds() const { - if (animator_.get() && animator_->IsAnimatingProperty( - LayerAnimationElement::BOUNDS)) { - return animator_->GetTargetBounds(); - } - return bounds_; -} - -void Layer::SetMasksToBounds(bool masks_to_bounds) { - cc_layer_->SetMasksToBounds(masks_to_bounds); -} - -bool Layer::GetMasksToBounds() const { - return cc_layer_->masks_to_bounds(); -} - -void Layer::SetOpacity(float opacity) { - GetAnimator()->SetOpacity(opacity); -} - -float Layer::GetCombinedOpacity() const { - float opacity = this->opacity(); - Layer* current = this->parent_; - while (current) { - opacity *= current->opacity(); - current = current->parent_; - } - return opacity; -} - -void Layer::SetBackgroundBlur(int blur_radius) { - background_blur_radius_ = blur_radius; - - SetLayerBackgroundFilters(); -} - -void Layer::SetLayerSaturation(float saturation) { - layer_saturation_ = saturation; - SetLayerFilters(); -} - -void Layer::SetLayerBrightness(float brightness) { - GetAnimator()->SetBrightness(brightness); -} - -float Layer::GetTargetBrightness() const { - if (animator_.get() && animator_->IsAnimatingProperty( - LayerAnimationElement::BRIGHTNESS)) { - return animator_->GetTargetBrightness(); - } - return layer_brightness(); -} - -void Layer::SetLayerGrayscale(float grayscale) { - GetAnimator()->SetGrayscale(grayscale); -} - -float Layer::GetTargetGrayscale() const { - if (animator_.get() && animator_->IsAnimatingProperty( - LayerAnimationElement::GRAYSCALE)) { - return animator_->GetTargetGrayscale(); - } - return layer_grayscale(); -} - -void Layer::SetLayerInverted(bool inverted) { - layer_inverted_ = inverted; - SetLayerFilters(); -} - -void Layer::SetMaskLayer(Layer* layer_mask) { - // The provided mask should not have a layer mask itself. - DCHECK(!layer_mask || - (!layer_mask->layer_mask_layer() && - layer_mask->children().empty() && - !layer_mask->layer_mask_back_link_)); - DCHECK(!layer_mask_back_link_); - if (layer_mask_ == layer_mask) - return; - // We need to de-reference the currently linked object so that no problem - // arises if the mask layer gets deleted before this object. - if (layer_mask_) - layer_mask_->layer_mask_back_link_ = NULL; - layer_mask_ = layer_mask; - cc_layer_->SetMaskLayer( - layer_mask ? layer_mask->cc_layer() : NULL); - // We need to reference the linked object so that it can properly break the - // link to us when it gets deleted. - if (layer_mask) { - layer_mask->layer_mask_back_link_ = this; - layer_mask->OnDeviceScaleFactorChanged(device_scale_factor_); - } -} - -void Layer::SetBackgroundZoom(float zoom, int inset) { - zoom_ = zoom; - zoom_inset_ = inset; - - SetLayerBackgroundFilters(); -} - -void Layer::SetAlphaShape(scoped_ptr<SkRegion> region) { - alpha_shape_ = region.Pass(); - - SetLayerFilters(); -} - -void Layer::SetLayerFilters() { - cc::FilterOperations filters; - if (layer_saturation_) { - filters.Append(cc::FilterOperation::CreateSaturateFilter( - layer_saturation_)); - } - if (layer_grayscale_) { - filters.Append(cc::FilterOperation::CreateGrayscaleFilter( - layer_grayscale_)); - } - if (layer_inverted_) - filters.Append(cc::FilterOperation::CreateInvertFilter(1.0)); - // Brightness goes last, because the resulting colors neeed clamping, which - // cause further color matrix filters to be applied separately. In this order, - // they all can be combined in a single pass. - if (layer_brightness_) { - filters.Append(cc::FilterOperation::CreateSaturatingBrightnessFilter( - layer_brightness_)); - } - if (alpha_shape_) { - filters.Append(cc::FilterOperation::CreateAlphaThresholdFilter( - *alpha_shape_, 0.f, 0.f)); - } - - cc_layer_->SetFilters(filters); -} - -void Layer::SetLayerBackgroundFilters() { - cc::FilterOperations filters; - if (zoom_ != 1) - filters.Append(cc::FilterOperation::CreateZoomFilter(zoom_, zoom_inset_)); - - if (background_blur_radius_) { - filters.Append(cc::FilterOperation::CreateBlurFilter( - background_blur_radius_)); - } - - cc_layer_->SetBackgroundFilters(filters); -} - -float Layer::GetTargetOpacity() const { - if (animator_.get() && animator_->IsAnimatingProperty( - LayerAnimationElement::OPACITY)) - return animator_->GetTargetOpacity(); - return opacity(); -} - -void Layer::SetVisible(bool visible) { - GetAnimator()->SetVisibility(visible); -} - -bool Layer::GetTargetVisibility() const { - if (animator_.get() && animator_->IsAnimatingProperty( - LayerAnimationElement::VISIBILITY)) - return animator_->GetTargetVisibility(); - return visible_; -} - -bool Layer::IsDrawn() const { - const Layer* layer = this; - while (layer && layer->visible_) - layer = layer->parent_; - return layer == NULL; -} - -bool Layer::ShouldDraw() const { - return type_ != LAYER_NOT_DRAWN && GetCombinedOpacity() > 0.0f; -} - -// static -void Layer::ConvertPointToLayer(const Layer* source, - const Layer* target, - gfx::Point* point) { - if (source == target) - return; - - const Layer* root_layer = GetRoot(source); - CHECK_EQ(root_layer, GetRoot(target)); - - if (source != root_layer) - source->ConvertPointForAncestor(root_layer, point); - if (target != root_layer) - target->ConvertPointFromAncestor(root_layer, point); -} - -bool Layer::GetTargetTransformRelativeTo(const Layer* ancestor, - gfx::Transform* transform) const { - const Layer* p = this; - for (; p && p != ancestor; p = p->parent()) { - gfx::Transform translation; - translation.Translate(static_cast<float>(p->bounds().x()), - static_cast<float>(p->bounds().y())); - // Use target transform so that result will be correct once animation is - // finished. - if (!p->GetTargetTransform().IsIdentity()) - transform->ConcatTransform(p->GetTargetTransform()); - transform->ConcatTransform(translation); - } - return p == ancestor; -} - -void Layer::SetFillsBoundsOpaquely(bool fills_bounds_opaquely) { - if (fills_bounds_opaquely_ == fills_bounds_opaquely) - return; - - fills_bounds_opaquely_ = fills_bounds_opaquely; - - cc_layer_->SetContentsOpaque(fills_bounds_opaquely); -} - -void Layer::SetFillsBoundsCompletely(bool fills_bounds_completely) { - fills_bounds_completely_ = fills_bounds_completely; -} - -void Layer::SwitchToLayer(scoped_refptr<cc::Layer> new_layer) { - // Finish animations being handled by cc_layer_. - if (animator_.get()) { - animator_->StopAnimatingProperty(LayerAnimationElement::TRANSFORM); - animator_->StopAnimatingProperty(LayerAnimationElement::OPACITY); - } - - if (texture_layer_.get()) - texture_layer_->ClearClient(); - // TODO(piman): delegated_renderer_layer_ cleanup. - - cc_layer_->RemoveAllChildren(); - if (cc_layer_->parent()) { - cc_layer_->parent()->ReplaceChild(cc_layer_, new_layer); - } - cc_layer_->SetLayerClient(NULL); - cc_layer_->RemoveLayerAnimationEventObserver(this); - new_layer->SetOpacity(cc_layer_->opacity()); - new_layer->SetTransform(cc_layer_->transform()); - new_layer->SetPosition(cc_layer_->position()); - new_layer->SetBackgroundColor(cc_layer_->background_color()); - - cc_layer_ = new_layer.get(); - content_layer_ = NULL; - solid_color_layer_ = NULL; - texture_layer_ = NULL; - delegated_renderer_layer_ = NULL; - surface_layer_ = NULL; - - cc_layer_->AddLayerAnimationEventObserver(this); - for (size_t i = 0; i < children_.size(); ++i) { - DCHECK(children_[i]->cc_layer_); - cc_layer_->AddChild(children_[i]->cc_layer_); - } - cc_layer_->SetLayerClient(this); - cc_layer_->SetTransformOrigin(gfx::Point3F()); - cc_layer_->SetContentsOpaque(fills_bounds_opaquely_); - cc_layer_->SetForceRenderSurface(force_render_surface_); - cc_layer_->SetIsDrawable(type_ != LAYER_NOT_DRAWN); - cc_layer_->SetHideLayerAndSubtree(!visible_); - - SetLayerFilters(); - SetLayerBackgroundFilters(); -} - -void Layer::SwitchCCLayerForTest() { - scoped_refptr<cc::Layer> new_layer; - if (Layer::UsingPictureLayer()) - new_layer = cc::PictureLayer::Create(this); - else - new_layer = cc::ContentLayer::Create(this); - SwitchToLayer(new_layer); - content_layer_ = new_layer; -} - -void Layer::SetTextureMailbox( - const cc::TextureMailbox& mailbox, - scoped_ptr<cc::SingleReleaseCallback> release_callback, - gfx::Size texture_size_in_dip) { - DCHECK(type_ == LAYER_TEXTURED || type_ == LAYER_SOLID_COLOR); - DCHECK(mailbox.IsValid()); - DCHECK(release_callback); - if (!texture_layer_.get()) { - scoped_refptr<cc::TextureLayer> new_layer = - cc::TextureLayer::CreateForMailbox(this); - new_layer->SetFlipped(true); - SwitchToLayer(new_layer); - texture_layer_ = new_layer; - } - if (mailbox_release_callback_) - mailbox_release_callback_->Run(0, false); - mailbox_release_callback_ = release_callback.Pass(); - mailbox_ = mailbox; - SetTextureSize(texture_size_in_dip); -} - -void Layer::SetTextureSize(gfx::Size texture_size_in_dip) { - DCHECK(texture_layer_.get()); - if (frame_size_in_dip_ == texture_size_in_dip) - return; - frame_size_in_dip_ = texture_size_in_dip; - RecomputeDrawsContentAndUVRect(); - texture_layer_->SetNeedsDisplay(); -} - -void Layer::SetShowDelegatedContent(cc::DelegatedFrameProvider* frame_provider, - gfx::Size frame_size_in_dip) { - DCHECK(type_ == LAYER_TEXTURED || type_ == LAYER_SOLID_COLOR); - - scoped_refptr<cc::DelegatedRendererLayer> new_layer = - cc::DelegatedRendererLayer::Create(frame_provider); - SwitchToLayer(new_layer); - delegated_renderer_layer_ = new_layer; - - frame_size_in_dip_ = frame_size_in_dip; - RecomputeDrawsContentAndUVRect(); -} - -void Layer::SetShowSurface( - cc::SurfaceId id, - const cc::SurfaceLayer::SatisfyCallback& satisfy_callback, - const cc::SurfaceLayer::RequireCallback& require_callback, - gfx::Size frame_size_in_dip) { - DCHECK(type_ == LAYER_TEXTURED || type_ == LAYER_SOLID_COLOR); - - scoped_refptr<cc::SurfaceLayer> new_layer = - cc::SurfaceLayer::Create(satisfy_callback, require_callback); - new_layer->SetSurfaceId(id, 1.f, frame_size_in_dip); - SwitchToLayer(new_layer); - surface_layer_ = new_layer; - - frame_size_in_dip_ = frame_size_in_dip; - RecomputeDrawsContentAndUVRect(); -} - -void Layer::SetShowSolidColorContent() { - DCHECK_EQ(type_, LAYER_SOLID_COLOR); - - if (solid_color_layer_.get()) - return; - - scoped_refptr<cc::SolidColorLayer> new_layer = cc::SolidColorLayer::Create(); - SwitchToLayer(new_layer); - solid_color_layer_ = new_layer; - - mailbox_ = cc::TextureMailbox(); - if (mailbox_release_callback_) { - mailbox_release_callback_->Run(0, false); - mailbox_release_callback_.reset(); - } - RecomputeDrawsContentAndUVRect(); -} - -void Layer::UpdateNinePatchLayerBitmap(const SkBitmap& bitmap) { - DCHECK(type_ == LAYER_NINE_PATCH && nine_patch_layer_.get()); - SkBitmap bitmap_copy; - if (bitmap.isImmutable()) { - bitmap_copy = bitmap; - } else { - // UIResourceBitmap requires an immutable copy of the input |bitmap|. - bitmap.copyTo(&bitmap_copy); - bitmap_copy.setImmutable(); - } - nine_patch_layer_->SetBitmap(bitmap_copy); -} - -void Layer::UpdateNinePatchLayerAperture(const gfx::Rect& aperture) { - DCHECK(type_ == LAYER_NINE_PATCH && nine_patch_layer_.get()); - nine_patch_layer_->SetAperture(aperture); -} - -void Layer::UpdateNinePatchLayerBorder(const gfx::Rect& border) { - DCHECK(type_ == LAYER_NINE_PATCH && nine_patch_layer_.get()); - nine_patch_layer_->SetBorder(border); -} - -void Layer::SetColor(SkColor color) { GetAnimator()->SetColor(color); } - -bool Layer::SchedulePaint(const gfx::Rect& invalid_rect) { - if ((type_ == LAYER_SOLID_COLOR && !texture_layer_.get()) || - type_ == LAYER_NINE_PATCH || (!delegate_ && !mailbox_.IsValid())) - return false; - - damaged_region_.op(invalid_rect.x(), - invalid_rect.y(), - invalid_rect.right(), - invalid_rect.bottom(), - SkRegion::kUnion_Op); - ScheduleDraw(); - return true; -} - -void Layer::ScheduleDraw() { - Compositor* compositor = GetCompositor(); - if (compositor) - compositor->ScheduleDraw(); -} - -void Layer::SendDamagedRects() { - if ((delegate_ || mailbox_.IsValid()) && !damaged_region_.isEmpty()) { - for (SkRegion::Iterator iter(damaged_region_); !iter.done(); iter.next()) { - const SkIRect& sk_damaged = iter.rect(); - gfx::Rect damaged( - sk_damaged.x(), - sk_damaged.y(), - sk_damaged.width(), - sk_damaged.height()); - cc_layer_->SetNeedsDisplayRect(damaged); - } - damaged_region_.setEmpty(); - } - for (size_t i = 0; i < children_.size(); ++i) - children_[i]->SendDamagedRects(); -} - -void Layer::CompleteAllAnimations() { - typedef std::vector<scoped_refptr<LayerAnimator> > LayerAnimatorVector; - LayerAnimatorVector animators; - CollectAnimators(&animators); - for (LayerAnimatorVector::const_iterator it = animators.begin(); - it != animators.end(); - ++it) { - (*it)->StopAnimating(); - } -} - -void Layer::SuppressPaint() { - if (!delegate_) - return; - delegate_ = NULL; - for (size_t i = 0; i < children_.size(); ++i) - children_[i]->SuppressPaint(); -} - -void Layer::OnDeviceScaleFactorChanged(float device_scale_factor) { - if (device_scale_factor_ == device_scale_factor) - return; - if (animator_.get()) - animator_->StopAnimatingProperty(LayerAnimationElement::TRANSFORM); - device_scale_factor_ = device_scale_factor; - RecomputeDrawsContentAndUVRect(); - RecomputePosition(); - SchedulePaint(gfx::Rect(bounds_.size())); - if (delegate_) - delegate_->OnDeviceScaleFactorChanged(device_scale_factor); - for (size_t i = 0; i < children_.size(); ++i) - children_[i]->OnDeviceScaleFactorChanged(device_scale_factor); - if (layer_mask_) - layer_mask_->OnDeviceScaleFactorChanged(device_scale_factor); -} - -void Layer::OnDelegatedFrameDamage(const gfx::Rect& damage_rect_in_dip) { - DCHECK(delegated_renderer_layer_.get() || surface_layer_.get()); - if (!delegate_) - return; - delegate_->OnDelegatedFrameDamage(damage_rect_in_dip); -} - -void Layer::RequestCopyOfOutput(scoped_ptr<cc::CopyOutputRequest> request) { - cc_layer_->RequestCopyOfOutput(request.Pass()); -} - -void Layer::PaintContents(SkCanvas* sk_canvas, - const gfx::Rect& clip, - ContentLayerClient::GraphicsContextStatus gc_status) { - TRACE_EVENT0("ui", "Layer::PaintContents"); - scoped_ptr<gfx::Canvas> canvas(gfx::Canvas::CreateCanvasWithoutScaling( - sk_canvas, device_scale_factor_)); - if (delegate_) - delegate_->OnPaintLayer(canvas.get()); -} - -scoped_refptr<cc::DisplayItemList> Layer::PaintContentsToDisplayList( - const gfx::Rect& clip, - ContentLayerClient::GraphicsContextStatus gc_status) { - NOTIMPLEMENTED(); - return cc::DisplayItemList::Create(); -} - -bool Layer::FillsBoundsCompletely() const { return fills_bounds_completely_; } - -bool Layer::PrepareTextureMailbox( - cc::TextureMailbox* mailbox, - scoped_ptr<cc::SingleReleaseCallback>* release_callback, - bool use_shared_memory) { - if (!mailbox_release_callback_) - return false; - *mailbox = mailbox_; - *release_callback = mailbox_release_callback_.Pass(); - return true; -} - -void Layer::SetForceRenderSurface(bool force) { - if (force_render_surface_ == force) - return; - - force_render_surface_ = force; - cc_layer_->SetForceRenderSurface(force_render_surface_); -} - -class LayerDebugInfo : public base::debug::ConvertableToTraceFormat { - public: - explicit LayerDebugInfo(std::string name) : name_(name) { } - void AppendAsTraceFormat(std::string* out) const override { - base::DictionaryValue dictionary; - dictionary.SetString("layer_name", name_); - base::JSONWriter::Write(&dictionary, out); - } - - private: - ~LayerDebugInfo() override {} - std::string name_; -}; - -scoped_refptr<base::debug::ConvertableToTraceFormat> Layer::TakeDebugInfo() { - return new LayerDebugInfo(name_); -} - -void Layer::OnAnimationStarted(const cc::AnimationEvent& event) { - if (animator_.get()) - animator_->OnThreadedAnimationStarted(event); -} - -void Layer::CollectAnimators( - std::vector<scoped_refptr<LayerAnimator> >* animators) { - if (IsAnimating()) - animators->push_back(animator_); - std::for_each(children_.begin(), children_.end(), - std::bind2nd(std::mem_fun(&Layer::CollectAnimators), - animators)); -} - -void Layer::StackRelativeTo(Layer* child, Layer* other, bool above) { - DCHECK_NE(child, other); - DCHECK_EQ(this, child->parent()); - DCHECK_EQ(this, other->parent()); - - const size_t child_i = - std::find(children_.begin(), children_.end(), child) - children_.begin(); - const size_t other_i = - std::find(children_.begin(), children_.end(), other) - children_.begin(); - if ((above && child_i == other_i + 1) || (!above && child_i + 1 == other_i)) - return; - - const size_t dest_i = - above ? - (child_i < other_i ? other_i : other_i + 1) : - (child_i < other_i ? other_i - 1 : other_i); - children_.erase(children_.begin() + child_i); - children_.insert(children_.begin() + dest_i, child); - - child->cc_layer_->RemoveFromParent(); - cc_layer_->InsertChild(child->cc_layer_, dest_i); -} - -bool Layer::ConvertPointForAncestor(const Layer* ancestor, - gfx::Point* point) const { - gfx::Transform transform; - bool result = GetTargetTransformRelativeTo(ancestor, &transform); - gfx::Point3F p(*point); - transform.TransformPoint(&p); - *point = gfx::ToFlooredPoint(p.AsPointF()); - return result; -} - -bool Layer::ConvertPointFromAncestor(const Layer* ancestor, - gfx::Point* point) const { - gfx::Transform transform; - bool result = GetTargetTransformRelativeTo(ancestor, &transform); - gfx::Point3F p(*point); - transform.TransformPointReverse(&p); - *point = gfx::ToFlooredPoint(p.AsPointF()); - return result; -} - -void Layer::SetBoundsFromAnimation(const gfx::Rect& bounds) { - if (bounds == bounds_) - return; - - base::Closure closure; - if (delegate_) - closure = delegate_->PrepareForLayerBoundsChange(); - bool was_move = bounds_.size() == bounds.size(); - bounds_ = bounds; - - RecomputeDrawsContentAndUVRect(); - RecomputePosition(); - - if (!closure.is_null()) - closure.Run(); - - if (was_move) { - // Don't schedule a draw if we're invisible. We'll schedule one - // automatically when we get visible. - if (IsDrawn()) - ScheduleDraw(); - } else { - // Always schedule a paint, even if we're invisible. - SchedulePaint(gfx::Rect(bounds.size())); - } -} - -void Layer::SetTransformFromAnimation(const gfx::Transform& transform) { - cc_layer_->SetTransform(transform); -} - -void Layer::SetOpacityFromAnimation(float opacity) { - cc_layer_->SetOpacity(opacity); - ScheduleDraw(); -} - -void Layer::SetVisibilityFromAnimation(bool visible) { - if (visible_ == visible) - return; - - visible_ = visible; - cc_layer_->SetHideLayerAndSubtree(!visible_); -} - -void Layer::SetBrightnessFromAnimation(float brightness) { - layer_brightness_ = brightness; - SetLayerFilters(); -} - -void Layer::SetGrayscaleFromAnimation(float grayscale) { - layer_grayscale_ = grayscale; - SetLayerFilters(); -} - -void Layer::SetColorFromAnimation(SkColor color) { - DCHECK_EQ(type_, LAYER_SOLID_COLOR); - cc_layer_->SetBackgroundColor(color); - SetFillsBoundsOpaquely(SkColorGetA(color) == 0xFF); -} - -void Layer::ScheduleDrawForAnimation() { - ScheduleDraw(); -} - -const gfx::Rect& Layer::GetBoundsForAnimation() const { - return bounds(); -} - -gfx::Transform Layer::GetTransformForAnimation() const { - return transform(); -} - -float Layer::GetOpacityForAnimation() const { - return opacity(); -} - -bool Layer::GetVisibilityForAnimation() const { - return visible(); -} - -float Layer::GetBrightnessForAnimation() const { - return layer_brightness(); -} - -float Layer::GetGrayscaleForAnimation() const { - return layer_grayscale(); -} - -SkColor Layer::GetColorForAnimation() const { - // WebColor is equivalent to SkColor, per WebColor.h. - // The NULL check is here since this is invoked regardless of whether we have - // been configured as LAYER_SOLID_COLOR. - return solid_color_layer_.get() ? - solid_color_layer_->background_color() : SK_ColorBLACK; -} - -float Layer::GetDeviceScaleFactor() const { - return device_scale_factor_; -} - -void Layer::AddThreadedAnimation(scoped_ptr<cc::Animation> animation) { - DCHECK(cc_layer_); - // Until this layer has a compositor (and hence cc_layer_ has a - // LayerTreeHost), addAnimation will fail. - if (GetCompositor()) - cc_layer_->AddAnimation(animation.Pass()); - else - pending_threaded_animations_.push_back(animation.Pass()); -} - -namespace{ - -struct HasAnimationId { - HasAnimationId(int id): id_(id) { - } - - bool operator()(cc::Animation* animation) const { - return animation->id() == id_; - } - - private: - int id_; -}; - -} - -void Layer::RemoveThreadedAnimation(int animation_id) { - DCHECK(cc_layer_); - if (pending_threaded_animations_.size() == 0) { - cc_layer_->RemoveAnimation(animation_id); - return; - } - - pending_threaded_animations_.erase( - cc::remove_if(&pending_threaded_animations_, - pending_threaded_animations_.begin(), - pending_threaded_animations_.end(), - HasAnimationId(animation_id)), - pending_threaded_animations_.end()); -} - -LayerAnimatorCollection* Layer::GetLayerAnimatorCollection() { - Compositor* compositor = GetCompositor(); - return compositor ? compositor->layer_animator_collection() : NULL; -} - -void Layer::SendPendingThreadedAnimations() { - for (cc::ScopedPtrVector<cc::Animation>::iterator it = - pending_threaded_animations_.begin(); - it != pending_threaded_animations_.end(); - ++it) - cc_layer_->AddAnimation(pending_threaded_animations_.take(it)); - - pending_threaded_animations_.clear(); - - for (size_t i = 0; i < children_.size(); ++i) - children_[i]->SendPendingThreadedAnimations(); -} - -void Layer::CreateCcLayer() { - if (type_ == LAYER_SOLID_COLOR) { - solid_color_layer_ = cc::SolidColorLayer::Create(); - cc_layer_ = solid_color_layer_.get(); - } else if (type_ == LAYER_NINE_PATCH) { - nine_patch_layer_ = cc::NinePatchLayer::Create(); - cc_layer_ = nine_patch_layer_.get(); - } else { - if (Layer::UsingPictureLayer()) - content_layer_ = cc::PictureLayer::Create(this); - else - content_layer_ = cc::ContentLayer::Create(this); - cc_layer_ = content_layer_.get(); - } - cc_layer_->SetTransformOrigin(gfx::Point3F()); - cc_layer_->SetContentsOpaque(true); - cc_layer_->SetIsDrawable(type_ != LAYER_NOT_DRAWN); - cc_layer_->AddLayerAnimationEventObserver(this); - cc_layer_->SetLayerClient(this); - RecomputePosition(); -} - -gfx::Transform Layer::transform() const { - return cc_layer_->transform(); -} - -void Layer::RecomputeDrawsContentAndUVRect() { - DCHECK(cc_layer_); - gfx::Size size(bounds_.size()); - if (texture_layer_.get()) { - size.SetToMin(frame_size_in_dip_); - gfx::PointF uv_top_left(0.f, 0.f); - gfx::PointF uv_bottom_right( - static_cast<float>(size.width()) / frame_size_in_dip_.width(), - static_cast<float>(size.height()) / frame_size_in_dip_.height()); - texture_layer_->SetUV(uv_top_left, uv_bottom_right); - } else if (delegated_renderer_layer_.get() || surface_layer_.get()) { - size.SetToMin(frame_size_in_dip_); - } - cc_layer_->SetBounds(size); -} - -void Layer::RecomputePosition() { - cc_layer_->SetPosition(bounds_.origin() + subpixel_position_offset_); -} - -void Layer::AddAnimatorsInTreeToCollection( - LayerAnimatorCollection* collection) { - DCHECK(collection); - if (IsAnimating()) - animator_->AddToCollection(collection); - std::for_each( - children_.begin(), - children_.end(), - std::bind2nd(std::mem_fun(&Layer::AddAnimatorsInTreeToCollection), - collection)); -} - -void Layer::RemoveAnimatorsInTreeFromCollection( - LayerAnimatorCollection* collection) { - DCHECK(collection); - if (IsAnimating()) - animator_->RemoveFromCollection(collection); - std::for_each( - children_.begin(), - children_.end(), - std::bind2nd(std::mem_fun(&Layer::RemoveAnimatorsInTreeFromCollection), - collection)); -} - -bool Layer::IsAnimating() const { - return animator_.get() && animator_->is_animating(); -} - -} // namespace ui
diff --git a/ui/compositor/layer.h b/ui/compositor/layer.h deleted file mode 100644 index 0aa9e0b..0000000 --- a/ui/compositor/layer.h +++ /dev/null
@@ -1,522 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_LAYER_H_ -#define UI_COMPOSITOR_LAYER_H_ - -#include <string> -#include <vector> - -#include "base/compiler_specific.h" -#include "base/memory/ref_counted.h" -#include "base/memory/scoped_ptr.h" -#include "base/message_loop/message_loop.h" -#include "cc/animation/animation_events.h" -#include "cc/animation/layer_animation_event_observer.h" -#include "cc/base/scoped_ptr_vector.h" -#include "cc/layers/content_layer_client.h" -#include "cc/layers/layer_client.h" -#include "cc/layers/surface_layer.h" -#include "cc/layers/texture_layer_client.h" -#include "cc/resources/texture_mailbox.h" -#include "cc/surfaces/surface_id.h" -#include "third_party/skia/include/core/SkColor.h" -#include "third_party/skia/include/core/SkRegion.h" -#include "ui/compositor/compositor.h" -#include "ui/compositor/layer_animation_delegate.h" -#include "ui/compositor/layer_delegate.h" -#include "ui/compositor/layer_type.h" -#include "ui/gfx/rect.h" -#include "ui/gfx/transform.h" - -class SkCanvas; - -namespace cc { -class ContentLayer; -class CopyOutputRequest; -class DelegatedFrameProvider; -class DelegatedRendererLayer; -class Layer; -class NinePatchLayer; -class ResourceUpdateQueue; -class SolidColorLayer; -class SurfaceLayer; -class TextureLayer; -struct ReturnedResource; -typedef std::vector<ReturnedResource> ReturnedResourceArray; -} - -namespace ui { - -class Compositor; -class LayerAnimator; -class LayerOwner; - -// Layer manages a texture, transform and a set of child Layers. Any View that -// has enabled layers ends up creating a Layer to manage the texture. -// A Layer can also be created without a texture, in which case it renders -// nothing and is simply used as a node in a hierarchy of layers. -// Coordinate system used in layers is DIP (Density Independent Pixel) -// coordinates unless explicitly mentioned as pixel coordinates. -// -// NOTE: Unlike Views, each Layer does *not* own its child Layers. If you -// delete a Layer and it has children, the parent of each child Layer is set to -// NULL, but the children are not deleted. -class COMPOSITOR_EXPORT Layer - : public LayerAnimationDelegate, - NON_EXPORTED_BASE(public cc::ContentLayerClient), - NON_EXPORTED_BASE(public cc::TextureLayerClient), - NON_EXPORTED_BASE(public cc::LayerClient), - NON_EXPORTED_BASE(public cc::LayerAnimationEventObserver) { - public: - Layer(); - explicit Layer(LayerType type); - ~Layer() override; - - static bool UsingPictureLayer(); - - // Retrieves the Layer's compositor. The Layer will walk up its parent chain - // to locate it. Returns NULL if the Layer is not attached to a compositor. - Compositor* GetCompositor(); - - // Called by the compositor when the Layer is set as its root Layer. This can - // only ever be called on the root layer. - void SetCompositor(Compositor* compositor); - - LayerDelegate* delegate() { return delegate_; } - void set_delegate(LayerDelegate* delegate) { delegate_ = delegate; } - - LayerOwner* owner() { return owner_; } - - // Adds a new Layer to this Layer. - void Add(Layer* child); - - // Removes a Layer from this Layer. - void Remove(Layer* child); - - // Stacks |child| above all other children. - void StackAtTop(Layer* child); - - // Stacks |child| directly above |other|. Both must be children of this - // layer. Note that if |child| is initially stacked even higher, calling this - // method will result in |child| being lowered in the stacking order. - void StackAbove(Layer* child, Layer* other); - - // Stacks |child| below all other children. - void StackAtBottom(Layer* child); - - // Stacks |child| directly below |other|. Both must be children of this - // layer. - void StackBelow(Layer* child, Layer* other); - - // Returns the child Layers. - const std::vector<Layer*>& children() const { return children_; } - - // The parent. - const Layer* parent() const { return parent_; } - Layer* parent() { return parent_; } - - LayerType type() const { return type_; } - - // Returns true if this Layer contains |other| somewhere in its children. - bool Contains(const Layer* other) const; - - // The layer's animator is responsible for causing automatic animations when - // properties are set. It also manages a queue of pending animations and - // handles blending of animations. The layer takes ownership of the animator. - void SetAnimator(LayerAnimator* animator); - - // Returns the layer's animator. Creates a default animator of one has not - // been set. Will not return NULL. - LayerAnimator* GetAnimator(); - - // The transform, relative to the parent. - void SetTransform(const gfx::Transform& transform); - gfx::Transform transform() const; - - // Return the target transform if animator is running, or the current - // transform otherwise. - gfx::Transform GetTargetTransform() const; - - // The bounds, relative to the parent. - void SetBounds(const gfx::Rect& bounds); - const gfx::Rect& bounds() const { return bounds_; } - - // The offset from our parent (stored in bounds.origin()) is an integer but we - // may need to be at a fractional pixel offset to align properly on screen. - void SetSubpixelPositionOffset(const gfx::Vector2dF offset); - const gfx::Vector2dF& subpixel_position_offset() const { - return subpixel_position_offset_; - } - - // Return the target bounds if animator is running, or the current bounds - // otherwise. - gfx::Rect GetTargetBounds() const; - - // Sets/gets whether or not drawing of child layers should be clipped to the - // bounds of this layer. - void SetMasksToBounds(bool masks_to_bounds); - bool GetMasksToBounds() const; - - // The opacity of the layer. The opacity is applied to each pixel of the - // texture (resulting alpha = opacity * alpha). - float opacity() const; - void SetOpacity(float opacity); - - // Returns the actual opacity, which the opacity of this layer multipled by - // the combined opacity of the parent. - float GetCombinedOpacity() const; - - // Blur pixels by this amount in anything below the layer and visible through - // the layer. - int background_blur() const { return background_blur_radius_; } - void SetBackgroundBlur(int blur_radius); - - // Saturate all pixels of this layer by this amount. - // This effect will get "combined" with the inverted, - // brightness and grayscale setting. - float layer_saturation() const { return layer_saturation_; } - void SetLayerSaturation(float saturation); - - // Change the brightness of all pixels from this layer by this amount. - // This effect will get "combined" with the inverted, saturate - // and grayscale setting. - float layer_brightness() const { return layer_brightness_; } - void SetLayerBrightness(float brightness); - - // Return the target brightness if animator is running, or the current - // brightness otherwise. - float GetTargetBrightness() const; - - // Change the grayscale of all pixels from this layer by this amount. - // This effect will get "combined" with the inverted, saturate - // and brightness setting. - float layer_grayscale() const { return layer_grayscale_; } - void SetLayerGrayscale(float grayscale); - - // Return the target grayscale if animator is running, or the current - // grayscale otherwise. - float GetTargetGrayscale() const; - - // Zoom the background by a factor of |zoom|. The effect is blended along the - // edge across |inset| pixels. - void SetBackgroundZoom(float zoom, int inset); - - // Set the shape of this layer. - SkRegion* alpha_shape() const { return alpha_shape_.get(); } - void SetAlphaShape(scoped_ptr<SkRegion> region); - - // Invert the layer. - bool layer_inverted() const { return layer_inverted_; } - void SetLayerInverted(bool inverted); - - // Return the target opacity if animator is running, or the current opacity - // otherwise. - float GetTargetOpacity() const; - - // Set a layer mask for a layer. - // Note the provided layer mask can neither have a layer mask itself nor can - // it have any children. The ownership of |layer_mask| will not be - // transferred with this call. - // Furthermore: A mask layer can only be set to one layer. - void SetMaskLayer(Layer* layer_mask); - Layer* layer_mask_layer() { return layer_mask_; } - - // Sets the visibility of the Layer. A Layer may be visible but not - // drawn. This happens if any ancestor of a Layer is not visible. - void SetVisible(bool visible); - bool visible() const { return visible_; } - - // Returns the target visibility if the animator is running. Otherwise, it - // returns the current visibility. - bool GetTargetVisibility() const; - - // Returns true if this Layer is drawn. A Layer is drawn only if all ancestors - // are visible. - bool IsDrawn() const; - - // Returns true if this layer can have a texture (has_texture_ is true) - // and is not completely obscured by a child. - bool ShouldDraw() const; - - // Converts a point from the coordinates of |source| to the coordinates of - // |target|. Necessarily, |source| and |target| must inhabit the same Layer - // tree. - static void ConvertPointToLayer(const Layer* source, - const Layer* target, - gfx::Point* point); - - // Converts a transform to be relative to the given |ancestor|. Returns - // whether success (that is, whether the given ancestor was really an - // ancestor of this layer). - bool GetTargetTransformRelativeTo(const Layer* ancestor, - gfx::Transform* transform) const; - - // See description in View for details - void SetFillsBoundsOpaquely(bool fills_bounds_opaquely); - bool fills_bounds_opaquely() const { return fills_bounds_opaquely_; } - - // Set to true if this layer always paints completely within its bounds. If so - // we can omit an unnecessary clear, even if the layer is transparent. - void SetFillsBoundsCompletely(bool fills_bounds_completely); - - const std::string& name() const { return name_; } - void set_name(const std::string& name) { name_ = name; } - - // Set new TextureMailbox for this layer. Note that |mailbox| may hold a - // shared memory resource or an actual mailbox for a texture. - void SetTextureMailbox(const cc::TextureMailbox& mailbox, - scoped_ptr<cc::SingleReleaseCallback> release_callback, - gfx::Size texture_size_in_dip); - void SetTextureSize(gfx::Size texture_size_in_dip); - - // Begins showing delegated frames from the |frame_provider|. - void SetShowDelegatedContent(cc::DelegatedFrameProvider* frame_provider, - gfx::Size frame_size_in_dip); - - // Begins showing content from a surface with a particular id. - void SetShowSurface(cc::SurfaceId id, - const cc::SurfaceLayer::SatisfyCallback& satisfy_callback, - const cc::SurfaceLayer::RequireCallback& require_callback, - gfx::Size frame_size_in_dip); - - bool has_external_content() { - return texture_layer_.get() || delegated_renderer_layer_.get() || - surface_layer_.get(); - } - - // Show a solid color instead of delegated or surface contents. - void SetShowSolidColorContent(); - - // Sets the layer's fill color. May only be called for LAYER_SOLID_COLOR. - void SetColor(SkColor color); - - // Updates the nine patch layer's bitmap, aperture and border. May only be - // called for LAYER_NINE_PATCH. - void UpdateNinePatchLayerBitmap(const SkBitmap& bitmap); - void UpdateNinePatchLayerAperture(const gfx::Rect& aperture); - void UpdateNinePatchLayerBorder(const gfx::Rect& border); - - // Adds |invalid_rect| to the Layer's pending invalid rect and calls - // ScheduleDraw(). Returns false if the paint request is ignored. - bool SchedulePaint(const gfx::Rect& invalid_rect); - - // Schedules a redraw of the layer tree at the compositor. - // Note that this _does not_ invalidate any region of this layer; use - // SchedulePaint() for that. - void ScheduleDraw(); - - // Uses damaged rectangles recorded in |damaged_region_| to invalidate the - // |cc_layer_|. - void SendDamagedRects(); - - const SkRegion& damaged_region() const { return damaged_region_; } - - void CompleteAllAnimations(); - - // Suppresses painting the content by disconnecting |delegate_|. - void SuppressPaint(); - - // Notifies the layer that the device scale factor has changed. - void OnDeviceScaleFactorChanged(float device_scale_factor); - - // Notifies the layer that one of its children has received a new - // delegated frame. - void OnDelegatedFrameDamage(const gfx::Rect& damage_rect_in_dip); - - // Requets a copy of the layer's output as a texture or bitmap. - void RequestCopyOfOutput(scoped_ptr<cc::CopyOutputRequest> request); - - // ContentLayerClient - void PaintContents( - SkCanvas* canvas, - const gfx::Rect& clip, - ContentLayerClient::GraphicsContextStatus gc_status) override; - scoped_refptr<cc::DisplayItemList> PaintContentsToDisplayList( - const gfx::Rect& clip, - GraphicsContextStatus gc_status) override; - bool FillsBoundsCompletely() const override; - - cc::Layer* cc_layer() { return cc_layer_; } - - // TextureLayerClient - bool PrepareTextureMailbox( - cc::TextureMailbox* mailbox, - scoped_ptr<cc::SingleReleaseCallback>* release_callback, - bool use_shared_memory) override; - - float device_scale_factor() const { return device_scale_factor_; } - - // Forces a render surface to be used on this layer. This has no positive - // impact, and is only used for benchmarking/testing purpose. - void SetForceRenderSurface(bool force); - bool force_render_surface() const { return force_render_surface_; } - - // LayerClient - scoped_refptr<base::debug::ConvertableToTraceFormat> TakeDebugInfo() override; - - // LayerAnimationEventObserver - void OnAnimationStarted(const cc::AnimationEvent& event) override; - - // Whether this layer has animations waiting to get sent to its cc::Layer. - bool HasPendingThreadedAnimations() { - return pending_threaded_animations_.size() != 0; - } - - // Triggers a call to SwitchToLayer. - void SwitchCCLayerForTest(); - - private: - friend class LayerOwner; - - void CollectAnimators(std::vector<scoped_refptr<LayerAnimator> >* animators); - - // Stacks |child| above or below |other|. Helper method for StackAbove() and - // StackBelow(). - void StackRelativeTo(Layer* child, Layer* other, bool above); - - bool ConvertPointForAncestor(const Layer* ancestor, gfx::Point* point) const; - bool ConvertPointFromAncestor(const Layer* ancestor, gfx::Point* point) const; - - // Implementation of LayerAnimatorDelegate - void SetBoundsFromAnimation(const gfx::Rect& bounds) override; - void SetTransformFromAnimation(const gfx::Transform& transform) override; - void SetOpacityFromAnimation(float opacity) override; - void SetVisibilityFromAnimation(bool visibility) override; - void SetBrightnessFromAnimation(float brightness) override; - void SetGrayscaleFromAnimation(float grayscale) override; - void SetColorFromAnimation(SkColor color) override; - void ScheduleDrawForAnimation() override; - const gfx::Rect& GetBoundsForAnimation() const override; - gfx::Transform GetTransformForAnimation() const override; - float GetOpacityForAnimation() const override; - bool GetVisibilityForAnimation() const override; - float GetBrightnessForAnimation() const override; - float GetGrayscaleForAnimation() const override; - SkColor GetColorForAnimation() const override; - float GetDeviceScaleFactor() const override; - void AddThreadedAnimation(scoped_ptr<cc::Animation> animation) override; - void RemoveThreadedAnimation(int animation_id) override; - LayerAnimatorCollection* GetLayerAnimatorCollection() override; - - // Creates a corresponding composited layer for |type_|. - void CreateCcLayer(); - - // Recomputes and sets to |cc_layer_|. - void RecomputeDrawsContentAndUVRect(); - void RecomputePosition(); - - // Set all filters which got applied to the layer. - void SetLayerFilters(); - - // Set all filters which got applied to the layer background. - void SetLayerBackgroundFilters(); - - // Cleanup |cc_layer_| and replaces it with |new_layer|. - void SwitchToLayer(scoped_refptr<cc::Layer> new_layer); - - // We cannot send animations to our cc_layer_ until we have been added to a - // layer tree. Instead, we hold on to these animations in - // pending_threaded_animations_, and expect SendPendingThreadedAnimations to - // be called once we have been added to a tree. - void SendPendingThreadedAnimations(); - - void AddAnimatorsInTreeToCollection(LayerAnimatorCollection* collection); - void RemoveAnimatorsInTreeFromCollection(LayerAnimatorCollection* collection); - - // Returns whether the layer has an animating LayerAnimator. - bool IsAnimating() const; - - const LayerType type_; - - Compositor* compositor_; - - Layer* parent_; - - // This layer's children, in bottom-to-top stacking order. - std::vector<Layer*> children_; - - gfx::Rect bounds_; - gfx::Vector2dF subpixel_position_offset_; - - // Visibility of this layer. See SetVisible/IsDrawn for more details. - bool visible_; - - bool force_render_surface_; - - bool fills_bounds_opaquely_; - bool fills_bounds_completely_; - - // Union of damaged rects, in pixel coordinates, to be used when - // compositor is ready to paint the content. - SkRegion damaged_region_; - - int background_blur_radius_; - - // Several variables which will change the visible representation of - // the layer. - float layer_saturation_; - float layer_brightness_; - float layer_grayscale_; - bool layer_inverted_; - - // The associated mask layer with this layer. - Layer* layer_mask_; - // The back link from the mask layer to it's associated masked layer. - // We keep this reference for the case that if the mask layer gets deleted - // while attached to the main layer before the main layer is deleted. - Layer* layer_mask_back_link_; - - // The zoom factor to scale the layer by. Zooming is disabled when this is - // set to 1. - float zoom_; - - // Width of the border in pixels, where the scaling is blended. - int zoom_inset_; - - // Shape of the window. - scoped_ptr<SkRegion> alpha_shape_; - - std::string name_; - - LayerDelegate* delegate_; - - LayerOwner* owner_; - - scoped_refptr<LayerAnimator> animator_; - - // Animations that are passed to AddThreadedAnimation before this layer is - // added to a tree. - cc::ScopedPtrVector<cc::Animation> pending_threaded_animations_; - - // Ownership of the layer is held through one of the strongly typed layer - // pointers, depending on which sort of layer this is. - scoped_refptr<cc::Layer> content_layer_; - scoped_refptr<cc::NinePatchLayer> nine_patch_layer_; - scoped_refptr<cc::TextureLayer> texture_layer_; - scoped_refptr<cc::SolidColorLayer> solid_color_layer_; - scoped_refptr<cc::DelegatedRendererLayer> delegated_renderer_layer_; - scoped_refptr<cc::SurfaceLayer> surface_layer_; - cc::Layer* cc_layer_; - - // A cached copy of |Compositor::device_scale_factor()|. - float device_scale_factor_; - - // The mailbox used by texture_layer_. - cc::TextureMailbox mailbox_; - - // The callback to release the mailbox. This is only set after - // SetTextureMailbox is called, before we give it to the TextureLayer. - scoped_ptr<cc::SingleReleaseCallback> mailbox_release_callback_; - - // The size of the frame or texture in DIP, set when SetShowDelegatedContent - // or SetTextureMailbox was called. - gfx::Size frame_size_in_dip_; - - DISALLOW_COPY_AND_ASSIGN(Layer); -}; - -} // namespace ui - -#endif // UI_COMPOSITOR_LAYER_H_
diff --git a/ui/compositor/layer_animation_delegate.h b/ui/compositor/layer_animation_delegate.h deleted file mode 100644 index 2f38d54..0000000 --- a/ui/compositor/layer_animation_delegate.h +++ /dev/null
@@ -1,48 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_LAYER_ANIMATION_DELEGATE_H_ -#define UI_COMPOSITOR_LAYER_ANIMATION_DELEGATE_H_ - -#include "base/memory/scoped_ptr.h" -#include "cc/animation/animation.h" -#include "third_party/skia/include/core/SkColor.h" -#include "ui/compositor/compositor_export.h" -#include "ui/gfx/rect.h" -#include "ui/gfx/transform.h" - -namespace ui { - -class LayerAnimatorCollection; - -// Layer animations interact with the layers using this interface. -class COMPOSITOR_EXPORT LayerAnimationDelegate { - public: - virtual void SetBoundsFromAnimation(const gfx::Rect& bounds) = 0; - virtual void SetTransformFromAnimation(const gfx::Transform& transform) = 0; - virtual void SetOpacityFromAnimation(float opacity) = 0; - virtual void SetVisibilityFromAnimation(bool visibility) = 0; - virtual void SetBrightnessFromAnimation(float brightness) = 0; - virtual void SetGrayscaleFromAnimation(float grayscale) = 0; - virtual void SetColorFromAnimation(SkColor color) = 0; - virtual void ScheduleDrawForAnimation() = 0; - virtual const gfx::Rect& GetBoundsForAnimation() const = 0; - virtual gfx::Transform GetTransformForAnimation() const = 0; - virtual float GetOpacityForAnimation() const = 0; - virtual bool GetVisibilityForAnimation() const = 0; - virtual float GetBrightnessForAnimation() const = 0; - virtual float GetGrayscaleForAnimation() const = 0; - virtual SkColor GetColorForAnimation() const = 0; - virtual float GetDeviceScaleFactor() const = 0; - virtual void AddThreadedAnimation(scoped_ptr<cc::Animation> animation) = 0; - virtual void RemoveThreadedAnimation(int animation_id) = 0; - virtual LayerAnimatorCollection* GetLayerAnimatorCollection() = 0; - - protected: - virtual ~LayerAnimationDelegate() {} -}; - -} // namespace ui - -#endif // UI_COMPOSITOR_LAYER_ANIMATION_DELEGATE_H_
diff --git a/ui/compositor/layer_animation_element.cc b/ui/compositor/layer_animation_element.cc deleted file mode 100644 index 3e667df..0000000 --- a/ui/compositor/layer_animation_element.cc +++ /dev/null
@@ -1,848 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/compositor/layer_animation_element.h" - -#include "base/compiler_specific.h" -#include "cc/animation/animation.h" -#include "cc/animation/animation_id_provider.h" -#include "ui/compositor/float_animation_curve_adapter.h" -#include "ui/compositor/layer.h" -#include "ui/compositor/layer_animation_delegate.h" -#include "ui/compositor/layer_animator.h" -#include "ui/compositor/scoped_animation_duration_scale_mode.h" -#include "ui/compositor/transform_animation_curve_adapter.h" -#include "ui/gfx/animation/tween.h" -#include "ui/gfx/interpolated_transform.h" - -namespace ui { - -namespace { - -// The factor by which duration is scaled up or down when using -// ScopedAnimationDurationScaleMode. -const int kSlowDurationScaleMultiplier = 4; -const int kFastDurationScaleDivisor = 4; -const int kNonZeroDurationScaleDivisor = 20; - -// Pause ----------------------------------------------------------------------- -class Pause : public LayerAnimationElement { - public: - Pause(AnimatableProperties properties, base::TimeDelta duration) - : LayerAnimationElement(properties, duration) { - } - ~Pause() override {} - - private: - void OnStart(LayerAnimationDelegate* delegate) override {} - bool OnProgress(double t, LayerAnimationDelegate* delegate) override { - return false; - } - void OnGetTarget(TargetValue* target) const override {} - void OnAbort(LayerAnimationDelegate* delegate) override {} - - DISALLOW_COPY_AND_ASSIGN(Pause); -}; - -// TransformTransition --------------------------------------------------------- - -class TransformTransition : public LayerAnimationElement { - public: - TransformTransition(const gfx::Transform& target, base::TimeDelta duration) - : LayerAnimationElement(TRANSFORM, duration), - target_(target) { - } - ~TransformTransition() override {} - - protected: - void OnStart(LayerAnimationDelegate* delegate) override { - start_ = delegate->GetTransformForAnimation(); - } - - bool OnProgress(double t, LayerAnimationDelegate* delegate) override { - delegate->SetTransformFromAnimation( - gfx::Tween::TransformValueBetween(t, start_, target_)); - return true; - } - - void OnGetTarget(TargetValue* target) const override { - target->transform = target_; - } - - void OnAbort(LayerAnimationDelegate* delegate) override {} - - private: - gfx::Transform start_; - const gfx::Transform target_; - - DISALLOW_COPY_AND_ASSIGN(TransformTransition); -}; - -// InterpolatedTransformTransition --------------------------------------------- - -class InterpolatedTransformTransition : public LayerAnimationElement { - public: - InterpolatedTransformTransition(InterpolatedTransform* interpolated_transform, - base::TimeDelta duration) - : LayerAnimationElement(TRANSFORM, duration), - interpolated_transform_(interpolated_transform) { - } - ~InterpolatedTransformTransition() override {} - - protected: - void OnStart(LayerAnimationDelegate* delegate) override {} - - bool OnProgress(double t, LayerAnimationDelegate* delegate) override { - delegate->SetTransformFromAnimation( - interpolated_transform_->Interpolate(static_cast<float>(t))); - return true; - } - - void OnGetTarget(TargetValue* target) const override { - target->transform = interpolated_transform_->Interpolate(1.0f); - } - - void OnAbort(LayerAnimationDelegate* delegate) override {} - - private: - scoped_ptr<InterpolatedTransform> interpolated_transform_; - - DISALLOW_COPY_AND_ASSIGN(InterpolatedTransformTransition); -}; - -// BoundsTransition ------------------------------------------------------------ - -class BoundsTransition : public LayerAnimationElement { - public: - BoundsTransition(const gfx::Rect& target, base::TimeDelta duration) - : LayerAnimationElement(BOUNDS, duration), - target_(target) { - } - ~BoundsTransition() override {} - - protected: - void OnStart(LayerAnimationDelegate* delegate) override { - start_ = delegate->GetBoundsForAnimation(); - } - - bool OnProgress(double t, LayerAnimationDelegate* delegate) override { - delegate->SetBoundsFromAnimation( - gfx::Tween::RectValueBetween(t, start_, target_)); - return true; - } - - void OnGetTarget(TargetValue* target) const override { - target->bounds = target_; - } - - void OnAbort(LayerAnimationDelegate* delegate) override {} - - private: - gfx::Rect start_; - const gfx::Rect target_; - - DISALLOW_COPY_AND_ASSIGN(BoundsTransition); -}; - -// OpacityTransition ----------------------------------------------------------- - -class OpacityTransition : public LayerAnimationElement { - public: - OpacityTransition(float target, base::TimeDelta duration) - : LayerAnimationElement(OPACITY, duration), - start_(0.0f), - target_(target) { - } - ~OpacityTransition() override {} - - protected: - void OnStart(LayerAnimationDelegate* delegate) override { - start_ = delegate->GetOpacityForAnimation(); - } - - bool OnProgress(double t, LayerAnimationDelegate* delegate) override { - delegate->SetOpacityFromAnimation( - gfx::Tween::FloatValueBetween(t, start_, target_)); - return true; - } - - void OnGetTarget(TargetValue* target) const override { - target->opacity = target_; - } - - void OnAbort(LayerAnimationDelegate* delegate) override {} - - private: - float start_; - const float target_; - - DISALLOW_COPY_AND_ASSIGN(OpacityTransition); -}; - -// VisibilityTransition -------------------------------------------------------- - -class VisibilityTransition : public LayerAnimationElement { - public: - VisibilityTransition(bool target, base::TimeDelta duration) - : LayerAnimationElement(VISIBILITY, duration), - start_(false), - target_(target) { - } - ~VisibilityTransition() override {} - - protected: - void OnStart(LayerAnimationDelegate* delegate) override { - start_ = delegate->GetVisibilityForAnimation(); - } - - bool OnProgress(double t, LayerAnimationDelegate* delegate) override { - delegate->SetVisibilityFromAnimation(t == 1.0 ? target_ : start_); - return t == 1.0; - } - - void OnGetTarget(TargetValue* target) const override { - target->visibility = target_; - } - - void OnAbort(LayerAnimationDelegate* delegate) override {} - - private: - bool start_; - const bool target_; - - DISALLOW_COPY_AND_ASSIGN(VisibilityTransition); -}; - -// BrightnessTransition -------------------------------------------------------- - -class BrightnessTransition : public LayerAnimationElement { - public: - BrightnessTransition(float target, base::TimeDelta duration) - : LayerAnimationElement(BRIGHTNESS, duration), - start_(0.0f), - target_(target) { - } - ~BrightnessTransition() override {} - - protected: - void OnStart(LayerAnimationDelegate* delegate) override { - start_ = delegate->GetBrightnessForAnimation(); - } - - bool OnProgress(double t, LayerAnimationDelegate* delegate) override { - delegate->SetBrightnessFromAnimation( - gfx::Tween::FloatValueBetween(t, start_, target_)); - return true; - } - - void OnGetTarget(TargetValue* target) const override { - target->brightness = target_; - } - - void OnAbort(LayerAnimationDelegate* delegate) override {} - - private: - float start_; - const float target_; - - DISALLOW_COPY_AND_ASSIGN(BrightnessTransition); -}; - -// GrayscaleTransition --------------------------------------------------------- - -class GrayscaleTransition : public LayerAnimationElement { - public: - GrayscaleTransition(float target, base::TimeDelta duration) - : LayerAnimationElement(GRAYSCALE, duration), - start_(0.0f), - target_(target) { - } - ~GrayscaleTransition() override {} - - protected: - void OnStart(LayerAnimationDelegate* delegate) override { - start_ = delegate->GetGrayscaleForAnimation(); - } - - bool OnProgress(double t, LayerAnimationDelegate* delegate) override { - delegate->SetGrayscaleFromAnimation( - gfx::Tween::FloatValueBetween(t, start_, target_)); - return true; - } - - void OnGetTarget(TargetValue* target) const override { - target->grayscale = target_; - } - - void OnAbort(LayerAnimationDelegate* delegate) override {} - - private: - float start_; - const float target_; - - DISALLOW_COPY_AND_ASSIGN(GrayscaleTransition); -}; - -// ColorTransition ------------------------------------------------------------- - -class ColorTransition : public LayerAnimationElement { - public: - ColorTransition(SkColor target, base::TimeDelta duration) - : LayerAnimationElement(COLOR, duration), - start_(SK_ColorBLACK), - target_(target) { - } - ~ColorTransition() override {} - - protected: - void OnStart(LayerAnimationDelegate* delegate) override { - start_ = delegate->GetColorForAnimation(); - } - - bool OnProgress(double t, LayerAnimationDelegate* delegate) override { - delegate->SetColorFromAnimation( - gfx::Tween::ColorValueBetween(t, start_, target_)); - return true; - } - - void OnGetTarget(TargetValue* target) const override { - target->color = target_; - } - - void OnAbort(LayerAnimationDelegate* delegate) override {} - - private: - SkColor start_; - const SkColor target_; - - DISALLOW_COPY_AND_ASSIGN(ColorTransition); -}; - -// ThreadedLayerAnimationElement ----------------------------------------------- - -class ThreadedLayerAnimationElement : public LayerAnimationElement { - public: - ThreadedLayerAnimationElement(AnimatableProperties properties, - base::TimeDelta duration) - : LayerAnimationElement(properties, duration) { - } - ~ThreadedLayerAnimationElement() override {} - - bool IsThreaded() const override { return (duration() != base::TimeDelta()); } - - protected: - explicit ThreadedLayerAnimationElement(const LayerAnimationElement& element) - : LayerAnimationElement(element) { - } - - bool OnProgress(double t, LayerAnimationDelegate* delegate) override { - if (t < 1.0) - return false; - - if (Started()) { - delegate->RemoveThreadedAnimation(animation_id()); - } - - OnEnd(delegate); - return true; - } - - void OnAbort(LayerAnimationDelegate* delegate) override { - if (delegate && Started()) { - delegate->RemoveThreadedAnimation(animation_id()); - } - } - - void RequestEffectiveStart(LayerAnimationDelegate* delegate) override { - DCHECK(animation_group_id()); - if (duration() == base::TimeDelta()) { - set_effective_start_time(requested_start_time()); - return; - } - set_effective_start_time(base::TimeTicks()); - scoped_ptr<cc::Animation> animation = CreateCCAnimation(); - animation->set_needs_synchronized_start_time(true); - delegate->AddThreadedAnimation(animation.Pass()); - } - - virtual void OnEnd(LayerAnimationDelegate* delegate) = 0; - - virtual scoped_ptr<cc::Animation> CreateCCAnimation() = 0; - - private: - DISALLOW_COPY_AND_ASSIGN(ThreadedLayerAnimationElement); -}; - -// ThreadedOpacityTransition --------------------------------------------------- - -class ThreadedOpacityTransition : public ThreadedLayerAnimationElement { - public: - ThreadedOpacityTransition(float target, base::TimeDelta duration) - : ThreadedLayerAnimationElement(OPACITY, duration), - start_(0.0f), - target_(target) { - } - ~ThreadedOpacityTransition() override {} - - protected: - void OnStart(LayerAnimationDelegate* delegate) override { - start_ = delegate->GetOpacityForAnimation(); - } - - void OnAbort(LayerAnimationDelegate* delegate) override { - if (delegate && Started()) { - ThreadedLayerAnimationElement::OnAbort(delegate); - delegate->SetOpacityFromAnimation(gfx::Tween::FloatValueBetween( - gfx::Tween::CalculateValue(tween_type(), last_progressed_fraction()), - start_, - target_)); - } - } - - void OnEnd(LayerAnimationDelegate* delegate) override { - delegate->SetOpacityFromAnimation(target_); - } - - scoped_ptr<cc::Animation> CreateCCAnimation() override { - scoped_ptr<cc::AnimationCurve> animation_curve( - new FloatAnimationCurveAdapter(tween_type(), - start_, - target_, - duration())); - scoped_ptr<cc::Animation> animation( - cc::Animation::Create(animation_curve.Pass(), - animation_id(), - animation_group_id(), - cc::Animation::Opacity)); - return animation.Pass(); - } - - void OnGetTarget(TargetValue* target) const override { - target->opacity = target_; - } - - private: - float start_; - const float target_; - - DISALLOW_COPY_AND_ASSIGN(ThreadedOpacityTransition); -}; - -// ThreadedTransformTransition ------------------------------------------------- - -class ThreadedTransformTransition : public ThreadedLayerAnimationElement { - public: - ThreadedTransformTransition(const gfx::Transform& target, - base::TimeDelta duration) - : ThreadedLayerAnimationElement(TRANSFORM, duration), - target_(target) { - } - ~ThreadedTransformTransition() override {} - - protected: - void OnStart(LayerAnimationDelegate* delegate) override { - start_ = delegate->GetTransformForAnimation(); - } - - void OnAbort(LayerAnimationDelegate* delegate) override { - if (delegate && Started()) { - ThreadedLayerAnimationElement::OnAbort(delegate); - delegate->SetTransformFromAnimation(gfx::Tween::TransformValueBetween( - gfx::Tween::CalculateValue(tween_type(), last_progressed_fraction()), - start_, - target_)); - } - } - - void OnEnd(LayerAnimationDelegate* delegate) override { - delegate->SetTransformFromAnimation(target_); - } - - scoped_ptr<cc::Animation> CreateCCAnimation() override { - scoped_ptr<cc::AnimationCurve> animation_curve( - new TransformAnimationCurveAdapter(tween_type(), - start_, - target_, - duration())); - scoped_ptr<cc::Animation> animation( - cc::Animation::Create(animation_curve.Pass(), - animation_id(), - animation_group_id(), - cc::Animation::Transform)); - return animation.Pass(); - } - - void OnGetTarget(TargetValue* target) const override { - target->transform = target_; - } - - private: - gfx::Transform start_; - const gfx::Transform target_; - - DISALLOW_COPY_AND_ASSIGN(ThreadedTransformTransition); -}; - -// InverseTransformTransision -------------------------------------------------- - -class InverseTransformTransition : public ThreadedLayerAnimationElement { - public: - InverseTransformTransition(const gfx::Transform& base_transform, - const LayerAnimationElement* uninverted_transition) - : ThreadedLayerAnimationElement(*uninverted_transition), - base_transform_(base_transform), - uninverted_transition_( - CheckAndCast<const ThreadedTransformTransition*>( - uninverted_transition)) { - } - ~InverseTransformTransition() override {} - - static InverseTransformTransition* Clone(const LayerAnimationElement* other) { - const InverseTransformTransition* other_inverse = - CheckAndCast<const InverseTransformTransition*>(other); - return new InverseTransformTransition( - other_inverse->base_transform_, other_inverse->uninverted_transition_); - } - - protected: - void OnStart(LayerAnimationDelegate* delegate) override { - gfx::Transform start(delegate->GetTransformForAnimation()); - effective_start_ = base_transform_ * start; - - TargetValue target; - uninverted_transition_->GetTargetValue(&target); - base_target_ = target.transform; - - set_tween_type(uninverted_transition_->tween_type()); - - TransformAnimationCurveAdapter base_curve(tween_type(), - base_transform_, - base_target_, - duration()); - - animation_curve_.reset(new InverseTransformCurveAdapter( - base_curve, start, duration())); - computed_target_transform_ = ComputeWithBaseTransform(effective_start_, - base_target_); - } - - void OnAbort(LayerAnimationDelegate* delegate) override { - if (delegate && Started()) { - ThreadedLayerAnimationElement::OnAbort(delegate); - delegate->SetTransformFromAnimation(ComputeCurrentTransform()); - } - } - - void OnEnd(LayerAnimationDelegate* delegate) override { - delegate->SetTransformFromAnimation(computed_target_transform_); - } - - scoped_ptr<cc::Animation> CreateCCAnimation() override { - scoped_ptr<cc::Animation> animation( - cc::Animation::Create(animation_curve_->Clone(), - animation_id(), - animation_group_id(), - cc::Animation::Transform)); - return animation.Pass(); - } - - void OnGetTarget(TargetValue* target) const override { - target->transform = computed_target_transform_; - } - - private: - gfx::Transform ComputeCurrentTransform() const { - gfx::Transform base_current = gfx::Tween::TransformValueBetween( - gfx::Tween::CalculateValue(tween_type(), last_progressed_fraction()), - base_transform_, - base_target_); - return ComputeWithBaseTransform(effective_start_, base_current); - } - - gfx::Transform ComputeWithBaseTransform(gfx::Transform start, - gfx::Transform target) const { - gfx::Transform to_return(gfx::Transform::kSkipInitialization); - bool success = target.GetInverse(&to_return); - DCHECK(success) << "Target transform must be invertible."; - - to_return.PreconcatTransform(start); - return to_return; - } - - template <typename T> - static T CheckAndCast(const LayerAnimationElement* element) { - AnimatableProperties properties = element->properties(); - DCHECK(properties & TRANSFORM); - return static_cast<T>(element); - } - - gfx::Transform effective_start_; - gfx::Transform computed_target_transform_; - - const gfx::Transform base_transform_; - gfx::Transform base_target_; - - scoped_ptr<cc::AnimationCurve> animation_curve_; - - const ThreadedTransformTransition* const uninverted_transition_; - - DISALLOW_COPY_AND_ASSIGN(InverseTransformTransition); -}; - -} // namespace - -// LayerAnimationElement::TargetValue ------------------------------------------ - -LayerAnimationElement::TargetValue::TargetValue() - : opacity(0.0f), - visibility(false), - brightness(0.0f), - grayscale(0.0f), - color(SK_ColorBLACK) { -} - -LayerAnimationElement::TargetValue::TargetValue( - const LayerAnimationDelegate* delegate) - : bounds(delegate ? delegate->GetBoundsForAnimation() : gfx::Rect()), - transform(delegate ? - delegate->GetTransformForAnimation() : gfx::Transform()), - opacity(delegate ? delegate->GetOpacityForAnimation() : 0.0f), - visibility(delegate ? delegate->GetVisibilityForAnimation() : false), - brightness(delegate ? delegate->GetBrightnessForAnimation() : 0.0f), - grayscale(delegate ? delegate->GetGrayscaleForAnimation() : 0.0f), - color(delegate ? delegate->GetColorForAnimation() : 0.0f) { -} - -// LayerAnimationElement ------------------------------------------------------- - -LayerAnimationElement::LayerAnimationElement( - AnimatableProperties properties, base::TimeDelta duration) - : first_frame_(true), - properties_(properties), - duration_(GetEffectiveDuration(duration)), - tween_type_(gfx::Tween::LINEAR), - animation_id_(cc::AnimationIdProvider::NextAnimationId()), - animation_group_id_(0), - last_progressed_fraction_(0.0), - weak_ptr_factory_(this) { -} - -LayerAnimationElement::LayerAnimationElement( - const LayerAnimationElement &element) - : first_frame_(element.first_frame_), - properties_(element.properties_), - duration_(element.duration_), - tween_type_(element.tween_type_), - animation_id_(cc::AnimationIdProvider::NextAnimationId()), - animation_group_id_(element.animation_group_id_), - last_progressed_fraction_(element.last_progressed_fraction_), - weak_ptr_factory_(this) { -} - -LayerAnimationElement::~LayerAnimationElement() { -} - -void LayerAnimationElement::Start(LayerAnimationDelegate* delegate, - int animation_group_id) { - DCHECK(requested_start_time_ != base::TimeTicks()); - DCHECK(first_frame_); - animation_group_id_ = animation_group_id; - last_progressed_fraction_ = 0.0; - OnStart(delegate); - RequestEffectiveStart(delegate); - first_frame_ = false; -} - -bool LayerAnimationElement::Progress(base::TimeTicks now, - LayerAnimationDelegate* delegate) { - DCHECK(requested_start_time_ != base::TimeTicks()); - DCHECK(!first_frame_); - - bool need_draw; - double t = 1.0; - - if ((effective_start_time_ == base::TimeTicks()) || - (now < effective_start_time_)) { - // This hasn't actually started yet. - need_draw = false; - last_progressed_fraction_ = 0.0; - return need_draw; - } - - base::TimeDelta elapsed = now - effective_start_time_; - if ((duration_ > base::TimeDelta()) && (elapsed < duration_)) - t = elapsed.InMillisecondsF() / duration_.InMillisecondsF(); - base::WeakPtr<LayerAnimationElement> alive(weak_ptr_factory_.GetWeakPtr()); - need_draw = OnProgress(gfx::Tween::CalculateValue(tween_type_, t), delegate); - if (!alive) - return need_draw; - first_frame_ = t == 1.0; - last_progressed_fraction_ = t; - return need_draw; -} - -bool LayerAnimationElement::IsFinished(base::TimeTicks time, - base::TimeDelta* total_duration) { - // If an effective start has been requested but the effective start time - // hasn't yet been set, the animation is not finished, regardless of the - // value of |time|. - if (!first_frame_ && (effective_start_time_ == base::TimeTicks())) - return false; - - base::TimeDelta queueing_delay; - if (!first_frame_) - queueing_delay = effective_start_time_ - requested_start_time_; - - base::TimeDelta elapsed = time - requested_start_time_; - if (elapsed >= duration_ + queueing_delay) { - *total_duration = duration_ + queueing_delay; - return true; - } - return false; -} - -bool LayerAnimationElement::ProgressToEnd(LayerAnimationDelegate* delegate) { - if (first_frame_) - OnStart(delegate); - base::WeakPtr<LayerAnimationElement> alive(weak_ptr_factory_.GetWeakPtr()); - bool need_draw = OnProgress(1.0, delegate); - if (!alive) - return need_draw; - last_progressed_fraction_ = 1.0; - first_frame_ = true; - return need_draw; -} - -void LayerAnimationElement::GetTargetValue(TargetValue* target) const { - OnGetTarget(target); -} - -bool LayerAnimationElement::IsThreaded() const { - return false; -} - -void LayerAnimationElement::Abort(LayerAnimationDelegate* delegate) { - OnAbort(delegate); - first_frame_ = true; -} - -void LayerAnimationElement::RequestEffectiveStart( - LayerAnimationDelegate* delegate) { - DCHECK(requested_start_time_ != base::TimeTicks()); - effective_start_time_ = requested_start_time_; -} - -// static -LayerAnimationElement::AnimatableProperty -LayerAnimationElement::ToAnimatableProperty( - cc::Animation::TargetProperty property) { - switch (property) { - case cc::Animation::Transform: - return TRANSFORM; - case cc::Animation::Opacity: - return OPACITY; - default: - NOTREACHED(); - return AnimatableProperty(); - } -} - -// static -base::TimeDelta LayerAnimationElement::GetEffectiveDuration( - const base::TimeDelta& duration) { - switch (ScopedAnimationDurationScaleMode::duration_scale_mode()) { - case ScopedAnimationDurationScaleMode::NORMAL_DURATION: - return duration; - case ScopedAnimationDurationScaleMode::FAST_DURATION: - return duration / kFastDurationScaleDivisor; - case ScopedAnimationDurationScaleMode::SLOW_DURATION: - return duration * kSlowDurationScaleMultiplier; - case ScopedAnimationDurationScaleMode::NON_ZERO_DURATION: - return duration / kNonZeroDurationScaleDivisor; - case ScopedAnimationDurationScaleMode::ZERO_DURATION: - return base::TimeDelta(); - default: - NOTREACHED(); - return base::TimeDelta(); - } -} - -// static -LayerAnimationElement* LayerAnimationElement::CreateTransformElement( - const gfx::Transform& transform, - base::TimeDelta duration) { - return new ThreadedTransformTransition(transform, duration); -} - -// static -LayerAnimationElement* LayerAnimationElement::CreateInverseTransformElement( - const gfx::Transform& base_transform, - const LayerAnimationElement* uninverted_transition) { - return new InverseTransformTransition(base_transform, uninverted_transition); -} - -// static -LayerAnimationElement* LayerAnimationElement::CloneInverseTransformElement( - const LayerAnimationElement* other) { - return InverseTransformTransition::Clone(other); -} - -// static -LayerAnimationElement* -LayerAnimationElement::CreateInterpolatedTransformElement( - InterpolatedTransform* interpolated_transform, - base::TimeDelta duration) { - return new InterpolatedTransformTransition(interpolated_transform, duration); -} - -// static -LayerAnimationElement* LayerAnimationElement::CreateBoundsElement( - const gfx::Rect& bounds, - base::TimeDelta duration) { - return new BoundsTransition(bounds, duration); -} - -// static -LayerAnimationElement* LayerAnimationElement::CreateOpacityElement( - float opacity, - base::TimeDelta duration) { - return new ThreadedOpacityTransition(opacity, duration); -} - -// static -LayerAnimationElement* LayerAnimationElement::CreateVisibilityElement( - bool visibility, - base::TimeDelta duration) { - return new VisibilityTransition(visibility, duration); -} - -// static -LayerAnimationElement* LayerAnimationElement::CreateBrightnessElement( - float brightness, - base::TimeDelta duration) { - return new BrightnessTransition(brightness, duration); -} - -// static -LayerAnimationElement* LayerAnimationElement::CreateGrayscaleElement( - float grayscale, - base::TimeDelta duration) { - return new GrayscaleTransition(grayscale, duration); -} - -// static -LayerAnimationElement* LayerAnimationElement::CreatePauseElement( - AnimatableProperties properties, - base::TimeDelta duration) { - return new Pause(properties, duration); -} - -// static -LayerAnimationElement* LayerAnimationElement::CreateColorElement( - SkColor color, - base::TimeDelta duration) { - return new ColorTransition(color, duration); -} - -} // namespace ui
diff --git a/ui/compositor/layer_animation_element.h b/ui/compositor/layer_animation_element.h deleted file mode 100644 index 0b880a4..0000000 --- a/ui/compositor/layer_animation_element.h +++ /dev/null
@@ -1,247 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_LAYER_ANIMATION_ELEMENT_H_ -#define UI_COMPOSITOR_LAYER_ANIMATION_ELEMENT_H_ - -#include <set> - -#include "base/memory/weak_ptr.h" -#include "base/time/time.h" -#include "cc/animation/animation.h" -#include "cc/animation/animation_events.h" -#include "third_party/skia/include/core/SkColor.h" -#include "ui/compositor/compositor_export.h" -#include "ui/gfx/animation/tween.h" -#include "ui/gfx/rect.h" -#include "ui/gfx/transform.h" - -namespace ui { - -class InterpolatedTransform; -class LayerAnimationDelegate; - -// LayerAnimationElements represent one segment of an animation between two -// keyframes. They know how to update a LayerAnimationDelegate given a value -// between 0 and 1 (0 for initial, and 1 for final). -class COMPOSITOR_EXPORT LayerAnimationElement { - public: - enum AnimatableProperty { - UNKNOWN = 0, - TRANSFORM = (1 << 0), - BOUNDS = (1 << 1), - OPACITY = (1 << 2), - VISIBILITY = (1 << 3), - BRIGHTNESS = (1 << 4), - GRAYSCALE = (1 << 5), - COLOR = (1 << 6), - - // Used when iterating over properties. - FIRST_PROPERTY = TRANSFORM, - SENTINEL = (1 << 7) - }; - - static AnimatableProperty ToAnimatableProperty( - cc::Animation::TargetProperty property); - - struct COMPOSITOR_EXPORT TargetValue { - TargetValue(); - // Initializes the target value to match the delegate. NULL may be supplied. - explicit TargetValue(const LayerAnimationDelegate* delegate); - - gfx::Rect bounds; - gfx::Transform transform; - float opacity; - bool visibility; - float brightness; - float grayscale; - SkColor color; - }; - - typedef uint32 AnimatableProperties; - - LayerAnimationElement(AnimatableProperties properties, - base::TimeDelta duration); - - virtual ~LayerAnimationElement(); - - // Creates an element that transitions to the given transform. The caller owns - // the return value. - static LayerAnimationElement* CreateTransformElement( - const gfx::Transform& transform, - base::TimeDelta duration); - - // Creates an element that counters a transition to the given transform. - // This element maintains the invariant uninverted_transition->at(t) * - // this->at(t) == base_transform * this->at(t_start) for any t. The caller - // owns the return value. - static LayerAnimationElement* CreateInverseTransformElement( - const gfx::Transform& base_transform, - const LayerAnimationElement* uninverted_transition); - - - // Duplicates elements as created by CreateInverseTransformElement. - static LayerAnimationElement* CloneInverseTransformElement( - const LayerAnimationElement* other); - - // Creates an element that transitions to another in a way determined by an - // interpolated transform. The element accepts ownership of the interpolated - // transform. NB: at every step, the interpolated transform clobbers the - // existing transform. That is, it does not interpolate between the existing - // transform and the last value the interpolated transform will assume. It is - // therefore important that the value of the interpolated at time 0 matches - // the current transform. - static LayerAnimationElement* CreateInterpolatedTransformElement( - InterpolatedTransform* interpolated_transform, - base::TimeDelta duration); - - // Creates an element that transitions to the given bounds. The caller owns - // the return value. - static LayerAnimationElement* CreateBoundsElement( - const gfx::Rect& bounds, - base::TimeDelta duration); - - // Creates an element that transitions to the given opacity. The caller owns - // the return value. - static LayerAnimationElement* CreateOpacityElement( - float opacity, - base::TimeDelta duration); - - // Creates an element that sets visibily following a delay. The caller owns - // the return value. - static LayerAnimationElement* CreateVisibilityElement( - bool visibility, - base::TimeDelta duration); - - // Creates an element that transitions to the given brightness. - // The caller owns the return value. - static LayerAnimationElement* CreateBrightnessElement( - float brightness, - base::TimeDelta duration); - - // Creates an element that transitions to the given grayscale value. - // The caller owns the return value. - static LayerAnimationElement* CreateGrayscaleElement( - float grayscale, - base::TimeDelta duration); - - // Creates an element that pauses the given properties. The caller owns the - // return value. - static LayerAnimationElement* CreatePauseElement( - AnimatableProperties properties, - base::TimeDelta duration); - - // Creates an element that transitions to the given color. The caller owns the - // return value. - static LayerAnimationElement* CreateColorElement( - SkColor color, - base::TimeDelta duration); - - // Sets the start time for the animation. This must be called before the first - // call to {Start, IsFinished}. Once the animation is finished, this must - // be called again in order to restart the animation. - void set_requested_start_time(base::TimeTicks start_time) { - requested_start_time_ = start_time; - } - base::TimeTicks requested_start_time() const { return requested_start_time_; } - - // Sets the actual start time for the animation, taking into account any - // queueing delays. - void set_effective_start_time(base::TimeTicks start_time) { - effective_start_time_ = start_time; - } - base::TimeTicks effective_start_time() const { return effective_start_time_; } - - // This must be called before the first call to Progress. If starting the - // animation involves dispatching to another thread, then this will proceed - // with that dispatch, ultimately resulting in the animation getting an - // effective start time (the time the animation starts on the other thread). - void Start(LayerAnimationDelegate* delegate, int animation_group_id); - - // Returns true if the animation has started but hasn't finished. - bool Started() { return !first_frame_; } - - // Updates the delegate to the appropriate value for |now|. Returns true - // if a redraw is required. - bool Progress(base::TimeTicks now, LayerAnimationDelegate* delegate); - - // If calling Progress now, with the given time, will finish the animation, - // returns true and sets |end_duration| to the actual duration for this - // animation, incuding any queueing delays. - bool IsFinished(base::TimeTicks time, base::TimeDelta* total_duration); - - // Updates the delegate to the end of the animation. Returns true if a - // redraw is required. - bool ProgressToEnd(LayerAnimationDelegate* delegate); - - // Called if the animation is not allowed to complete. This may be called - // before OnStarted or Progress. - void Abort(LayerAnimationDelegate* delegate); - - // Assigns the target value to |target|. - void GetTargetValue(TargetValue* target) const; - - // The properties that the element modifies. - AnimatableProperties properties() const { return properties_; } - - // Whether this element animates on the compositor thread. - virtual bool IsThreaded() const; - - gfx::Tween::Type tween_type() const { return tween_type_; } - void set_tween_type(gfx::Tween::Type tween_type) { tween_type_ = tween_type; } - - // Each LayerAnimationElement has a unique animation_id. Elements belonging - // to sequences that are supposed to start together have the same - // animation_group_id. - int animation_id() const { return animation_id_; } - int animation_group_id() const { return animation_group_id_; } - void set_animation_group_id(int id) { animation_group_id_ = id; } - - base::TimeDelta duration() const { return duration_; } - - // The fraction of the animation that has been completed after the last - // call made to {Progress, ProgressToEnd}. - double last_progressed_fraction() const { return last_progressed_fraction_; } - - protected: - // Called once each time the animation element is run before any call to - // OnProgress. - virtual void OnStart(LayerAnimationDelegate* delegate) = 0; - virtual bool OnProgress(double t, LayerAnimationDelegate* delegate) = 0; - virtual void OnGetTarget(TargetValue* target) const = 0; - virtual void OnAbort(LayerAnimationDelegate* delegate) = 0; - - // Actually start the animation, dispatching to another thread if needed. - virtual void RequestEffectiveStart(LayerAnimationDelegate* delegate); - - LayerAnimationElement(const LayerAnimationElement& element); - - private: - // For debugging purposes, we sometimes alter the duration we actually use. - // For example, during tests we often set duration = 0, and it is sometimes - // useful to slow animations down to see them more clearly. - base::TimeDelta GetEffectiveDuration(const base::TimeDelta& delta); - - bool first_frame_; - const AnimatableProperties properties_; - base::TimeTicks requested_start_time_; - - // When the animation actually started, taking into account queueing delays. - base::TimeTicks effective_start_time_; - const base::TimeDelta duration_; - gfx::Tween::Type tween_type_; - - const int animation_id_; - int animation_group_id_; - - double last_progressed_fraction_; - - base::WeakPtrFactory<LayerAnimationElement> weak_ptr_factory_; - - DISALLOW_ASSIGN(LayerAnimationElement); -}; - -} // namespace ui - -#endif // UI_COMPOSITOR_LAYER_ANIMATION_ELEMENT_H_
diff --git a/ui/compositor/layer_animation_element_unittest.cc b/ui/compositor/layer_animation_element_unittest.cc deleted file mode 100644 index 45de8d3..0000000 --- a/ui/compositor/layer_animation_element_unittest.cc +++ /dev/null
@@ -1,436 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/compositor/layer_animation_element.h" - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "base/time/time.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/compositor/layer_animation_delegate.h" -#include "ui/compositor/scoped_animation_duration_scale_mode.h" -#include "ui/compositor/test/test_layer_animation_delegate.h" -#include "ui/compositor/test/test_utils.h" -#include "ui/gfx/rect.h" -#include "ui/gfx/transform.h" - -namespace ui { - -namespace { - -// Check that the transformation element progresses the delegate as expected and -// that the element can be reused after it completes. -TEST(LayerAnimationElementTest, TransformElement) { - TestLayerAnimationDelegate delegate; - gfx::Transform start_transform, target_transform; - start_transform.Rotate(-30.0); - target_transform.Rotate(30.0); - base::TimeTicks start_time; - base::TimeTicks effective_start_time; - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - - scoped_ptr<LayerAnimationElement> element( - LayerAnimationElement::CreateTransformElement(target_transform, delta)); - element->set_animation_group_id(1); - - for (int i = 0; i < 2; ++i) { - start_time = effective_start_time + delta; - element->set_requested_start_time(start_time); - delegate.SetTransformFromAnimation(start_transform); - element->Start(&delegate, 1); - element->Progress(start_time, &delegate); - CheckApproximatelyEqual(start_transform, - delegate.GetTransformForAnimation()); - effective_start_time = start_time + delta; - element->set_effective_start_time(effective_start_time); - element->Progress(effective_start_time, &delegate); - EXPECT_FLOAT_EQ(0.0, element->last_progressed_fraction()); - element->Progress(effective_start_time + delta/2, &delegate); - EXPECT_FLOAT_EQ(0.5, element->last_progressed_fraction()); - - base::TimeDelta element_duration; - EXPECT_TRUE(element->IsFinished(effective_start_time + delta, - &element_duration)); - EXPECT_EQ(2 * delta, element_duration); - - element->Progress(effective_start_time + delta, &delegate); - EXPECT_FLOAT_EQ(1.0, element->last_progressed_fraction()); - CheckApproximatelyEqual(target_transform, - delegate.GetTransformForAnimation()); - } - - LayerAnimationElement::TargetValue target_value(&delegate); - element->GetTargetValue(&target_value); - CheckApproximatelyEqual(target_transform, target_value.transform); -} - -// Ensures that duration is copied correctly. -TEST(LayerAnimationElementTest, InverseElementDurationNoScale) { - gfx::Transform transform; - base::TimeDelta delta; - - scoped_ptr<LayerAnimationElement> base_element( - LayerAnimationElement::CreateTransformElement(transform, delta)); - - scoped_ptr<LayerAnimationElement> inverse_element( - LayerAnimationElement::CreateInverseTransformElement(transform, - base_element.get())); - EXPECT_EQ(base_element->duration(), inverse_element->duration()); -} - -// Ensures that duration is copied correctly and not double scaled. -TEST(LayerAnimationElementTest, InverseElementDurationScaled) { - gfx::Transform transform; - base::TimeDelta delta; - - ScopedAnimationDurationScaleMode faster_duration( - ScopedAnimationDurationScaleMode::FAST_DURATION); - scoped_ptr<LayerAnimationElement> base_element( - LayerAnimationElement::CreateTransformElement(transform, delta)); - - scoped_ptr<LayerAnimationElement> inverse_element( - LayerAnimationElement::CreateInverseTransformElement(transform, - base_element.get())); - EXPECT_EQ(base_element->duration(), inverse_element->duration()); -} - -// Ensures that the GetTargetTransform() method works as intended. -TEST(LayerAnimationElementTest, InverseElementTargetCalculation) { - base::TimeTicks start_time; - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - start_time += delta; - - gfx::Transform identity, transform; - - transform.Scale3d(2.0, 2.0, 2.0); - - scoped_ptr<LayerAnimationElement> base_element( - LayerAnimationElement::CreateTransformElement(transform, delta)); - scoped_ptr<LayerAnimationElement> inverse_element( - LayerAnimationElement::CreateInverseTransformElement(identity, - base_element.get())); - - base_element->set_requested_start_time(start_time); - inverse_element->set_requested_start_time(start_time); - - TestLayerAnimationDelegate delegate; - delegate.SetTransformFromAnimation(transform); - - base_element->Start(&delegate, 1); - inverse_element->Start(&delegate, 1); - LayerAnimationElement::TargetValue target; - inverse_element->GetTargetValue(&target); - - EXPECT_TRUE(target.transform.IsIdentity()) - << "Target should be identity such that the initial 2x scale from the start" - << " carries over at end when parent is doubled."; -} - -// Check that the bounds element progresses the delegate as expected and -// that the element can be reused after it completes. -TEST(LayerAnimationElementTest, BoundsElement) { - TestLayerAnimationDelegate delegate; - gfx::Rect start, target, middle; - start = target = middle = gfx::Rect(0, 0, 50, 50); - start.set_x(-90); - target.set_x(90); - base::TimeTicks start_time; - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - - scoped_ptr<LayerAnimationElement> element( - LayerAnimationElement::CreateBoundsElement(target, delta)); - - for (int i = 0; i < 2; ++i) { - start_time += delta; - element->set_requested_start_time(start_time); - delegate.SetBoundsFromAnimation(start); - element->Start(&delegate, 1); - element->Progress(start_time, &delegate); - CheckApproximatelyEqual(start, delegate.GetBoundsForAnimation()); - element->Progress(start_time + delta/2, &delegate); - CheckApproximatelyEqual(middle, delegate.GetBoundsForAnimation()); - - base::TimeDelta element_duration; - EXPECT_TRUE(element->IsFinished(start_time + delta, &element_duration)); - EXPECT_EQ(delta, element_duration); - - element->Progress(start_time + delta, &delegate); - CheckApproximatelyEqual(target, delegate.GetBoundsForAnimation()); - } - - LayerAnimationElement::TargetValue target_value(&delegate); - element->GetTargetValue(&target_value); - CheckApproximatelyEqual(target, target_value.bounds); -} - -// Check that the opacity element progresses the delegate as expected and -// that the element can be reused after it completes. -TEST(LayerAnimationElementTest, OpacityElement) { - TestLayerAnimationDelegate delegate; - float start = 0.0; - float middle = 0.5; - float target = 1.0; - base::TimeTicks start_time; - base::TimeTicks effective_start_time; - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - scoped_ptr<LayerAnimationElement> element( - LayerAnimationElement::CreateOpacityElement(target, delta)); - - for (int i = 0; i < 2; ++i) { - start_time = effective_start_time + delta; - element->set_requested_start_time(start_time); - delegate.SetOpacityFromAnimation(start); - element->Start(&delegate, 1); - element->Progress(start_time, &delegate); - EXPECT_FLOAT_EQ(start, element->last_progressed_fraction()); - effective_start_time = start_time + delta; - element->set_effective_start_time(effective_start_time); - element->Progress(effective_start_time, &delegate); - EXPECT_FLOAT_EQ(start, element->last_progressed_fraction()); - element->Progress(effective_start_time + delta/2, &delegate); - EXPECT_FLOAT_EQ(middle, element->last_progressed_fraction()); - - base::TimeDelta element_duration; - EXPECT_TRUE(element->IsFinished(effective_start_time + delta, - &element_duration)); - EXPECT_EQ(2 * delta, element_duration); - - element->Progress(effective_start_time + delta, &delegate); - EXPECT_FLOAT_EQ(target, element->last_progressed_fraction()); - EXPECT_FLOAT_EQ(target, delegate.GetOpacityForAnimation()); - } - - LayerAnimationElement::TargetValue target_value(&delegate); - element->GetTargetValue(&target_value); - EXPECT_FLOAT_EQ(target, target_value.opacity); -} - -// Check that the visibility element progresses the delegate as expected and -// that the element can be reused after it completes. -TEST(LayerAnimationElementTest, VisibilityElement) { - TestLayerAnimationDelegate delegate; - bool start = true; - bool target = false; - base::TimeTicks start_time; - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - scoped_ptr<LayerAnimationElement> element( - LayerAnimationElement::CreateVisibilityElement(target, delta)); - - for (int i = 0; i < 2; ++i) { - start_time += delta; - element->set_requested_start_time(start_time); - delegate.SetVisibilityFromAnimation(start); - element->Start(&delegate, 1); - element->Progress(start_time, &delegate); - EXPECT_TRUE(delegate.GetVisibilityForAnimation()); - element->Progress(start_time + delta/2, &delegate); - EXPECT_TRUE(delegate.GetVisibilityForAnimation()); - - base::TimeDelta element_duration; - EXPECT_TRUE(element->IsFinished(start_time + delta, &element_duration)); - EXPECT_EQ(delta, element_duration); - - element->Progress(start_time + delta, &delegate); - EXPECT_FALSE(delegate.GetVisibilityForAnimation()); - } - - LayerAnimationElement::TargetValue target_value(&delegate); - element->GetTargetValue(&target_value); - EXPECT_FALSE(target_value.visibility); -} - -// Check that the Brightness element progresses the delegate as expected and -// that the element can be reused after it completes. -TEST(LayerAnimationElementTest, BrightnessElement) { - TestLayerAnimationDelegate delegate; - float start = 0.0; - float middle = 0.5; - float target = 1.0; - base::TimeTicks start_time; - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - scoped_ptr<LayerAnimationElement> element( - LayerAnimationElement::CreateBrightnessElement(target, delta)); - - for (int i = 0; i < 2; ++i) { - start_time += delta; - element->set_requested_start_time(start_time); - delegate.SetBrightnessFromAnimation(start); - element->Start(&delegate, 1); - element->Progress(start_time, &delegate); - EXPECT_FLOAT_EQ(start, delegate.GetBrightnessForAnimation()); - element->Progress(start_time + delta/2, &delegate); - EXPECT_FLOAT_EQ(middle, delegate.GetBrightnessForAnimation()); - - base::TimeDelta element_duration; - EXPECT_TRUE(element->IsFinished(start_time + delta, &element_duration)); - EXPECT_EQ(delta, element_duration); - - element->Progress(start_time + delta, &delegate); - EXPECT_FLOAT_EQ(target, delegate.GetBrightnessForAnimation()); - } - - LayerAnimationElement::TargetValue target_value(&delegate); - element->GetTargetValue(&target_value); - EXPECT_FLOAT_EQ(target, target_value.brightness); -} - -// Check that the Grayscale element progresses the delegate as expected and -// that the element can be reused after it completes. -TEST(LayerAnimationElementTest, GrayscaleElement) { - TestLayerAnimationDelegate delegate; - float start = 0.0; - float middle = 0.5; - float target = 1.0; - base::TimeTicks start_time; - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - scoped_ptr<LayerAnimationElement> element( - LayerAnimationElement::CreateGrayscaleElement(target, delta)); - - for (int i = 0; i < 2; ++i) { - start_time += delta; - element->set_requested_start_time(start_time); - delegate.SetGrayscaleFromAnimation(start); - element->Start(&delegate, 1); - element->Progress(start_time, &delegate); - EXPECT_FLOAT_EQ(start, delegate.GetGrayscaleForAnimation()); - element->Progress(start_time + delta/2, &delegate); - EXPECT_FLOAT_EQ(middle, delegate.GetGrayscaleForAnimation()); - - base::TimeDelta element_duration; - EXPECT_TRUE(element->IsFinished(start_time + delta, &element_duration)); - EXPECT_EQ(delta, element_duration); - - element->Progress(start_time + delta, &delegate); - EXPECT_FLOAT_EQ(target, delegate.GetGrayscaleForAnimation()); - } - - LayerAnimationElement::TargetValue target_value(&delegate); - element->GetTargetValue(&target_value); - EXPECT_FLOAT_EQ(target, target_value.grayscale); -} - -// Check that the pause element progresses the delegate as expected and -// that the element can be reused after it completes. -TEST(LayerAnimationElementTest, PauseElement) { - LayerAnimationElement::AnimatableProperties properties = - LayerAnimationElement::TRANSFORM | LayerAnimationElement::BOUNDS | - LayerAnimationElement::OPACITY | LayerAnimationElement::BRIGHTNESS | - LayerAnimationElement::GRAYSCALE; - - base::TimeTicks start_time; - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - - scoped_ptr<LayerAnimationElement> element( - LayerAnimationElement::CreatePauseElement(properties, delta)); - - TestLayerAnimationDelegate delegate; - TestLayerAnimationDelegate copy = delegate; - - start_time += delta; - element->set_requested_start_time(start_time); - element->Start(&delegate, 1); - - // Pause should last for |delta|. - base::TimeDelta element_duration; - EXPECT_TRUE(element->IsFinished(start_time + delta, &element_duration)); - EXPECT_EQ(delta, element_duration); - - element->Progress(start_time + delta, &delegate); - - // Nothing should have changed. - CheckApproximatelyEqual(delegate.GetBoundsForAnimation(), - copy.GetBoundsForAnimation()); - CheckApproximatelyEqual(delegate.GetTransformForAnimation(), - copy.GetTransformForAnimation()); - EXPECT_FLOAT_EQ(delegate.GetOpacityForAnimation(), - copy.GetOpacityForAnimation()); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), - copy.GetBrightnessForAnimation()); - EXPECT_FLOAT_EQ(delegate.GetGrayscaleForAnimation(), - copy.GetGrayscaleForAnimation()); -} - -// Check that a threaded opacity element updates the delegate as expected when -// aborted. -TEST(LayerAnimationElementTest, AbortOpacityElement) { - TestLayerAnimationDelegate delegate; - float start = 0.0; - float target = 1.0; - base::TimeTicks start_time; - base::TimeTicks effective_start_time; - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - scoped_ptr<LayerAnimationElement> element( - LayerAnimationElement::CreateOpacityElement(target, delta)); - - // Choose a non-linear Tween type. - gfx::Tween::Type tween_type = gfx::Tween::EASE_IN; - element->set_tween_type(tween_type); - - delegate.SetOpacityFromAnimation(start); - - // Aborting the element before it has started should not update the delegate. - element->Abort(&delegate); - EXPECT_FLOAT_EQ(start, delegate.GetOpacityForAnimation()); - - start_time += delta; - element->set_requested_start_time(start_time); - element->Start(&delegate, 1); - element->Progress(start_time, &delegate); - effective_start_time = start_time + delta; - element->set_effective_start_time(effective_start_time); - element->Progress(effective_start_time, &delegate); - element->Progress(effective_start_time + delta/2, &delegate); - - // Since the element has started, it should update the delegate when - // aborted. - element->Abort(&delegate); - EXPECT_FLOAT_EQ(gfx::Tween::CalculateValue(tween_type, 0.5), - delegate.GetOpacityForAnimation()); -} - -// Check that a threaded transform element updates the delegate as expected when -// aborted. -TEST(LayerAnimationElementTest, AbortTransformElement) { - TestLayerAnimationDelegate delegate; - gfx::Transform start_transform, target_transform; - start_transform.Rotate(-30.0); - target_transform.Rotate(30.0); - base::TimeTicks start_time; - base::TimeTicks effective_start_time; - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - scoped_ptr<LayerAnimationElement> element( - LayerAnimationElement::CreateTransformElement(target_transform, delta)); - - // Choose a non-linear Tween type. - gfx::Tween::Type tween_type = gfx::Tween::EASE_IN; - element->set_tween_type(tween_type); - - delegate.SetTransformFromAnimation(start_transform); - - // Aborting the element before it has started should not update the delegate. - element->Abort(&delegate); - CheckApproximatelyEqual(start_transform, delegate.GetTransformForAnimation()); - - start_time += delta; - element->set_requested_start_time(start_time); - element->Start(&delegate, 1); - element->Progress(start_time, &delegate); - effective_start_time = start_time + delta; - element->set_effective_start_time(effective_start_time); - element->Progress(effective_start_time, &delegate); - element->Progress(effective_start_time + delta/2, &delegate); - - // Since the element has started, it should update the delegate when - // aborted. - element->Abort(&delegate); - target_transform.Blend(start_transform, - gfx::Tween::CalculateValue(tween_type, 0.5)); - CheckApproximatelyEqual(target_transform, - delegate.GetTransformForAnimation()); -} - -} // namespace - -} // namespace ui
diff --git a/ui/compositor/layer_animation_observer.cc b/ui/compositor/layer_animation_observer.cc deleted file mode 100644 index 658a835..0000000 --- a/ui/compositor/layer_animation_observer.cc +++ /dev/null
@@ -1,165 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/compositor/layer_animation_observer.h" - -#include "ui/compositor/layer_animation_sequence.h" - -namespace ui { - -//////////////////////////////////////////////////////////////////////////////// -// LayerAnimationObserver - -LayerAnimationObserver::LayerAnimationObserver() { -} - -LayerAnimationObserver::~LayerAnimationObserver() { - StopObserving(); -} - -bool LayerAnimationObserver::RequiresNotificationWhenAnimatorDestroyed() const { - return false; -} - -void LayerAnimationObserver::OnAttachedToSequence( - LayerAnimationSequence* sequence) { -} - -void LayerAnimationObserver::OnDetachedFromSequence( - LayerAnimationSequence* sequence) { -} - -void LayerAnimationObserver::StopObserving() { - while (!attached_sequences_.empty()) { - LayerAnimationSequence* sequence = *attached_sequences_.begin(); - sequence->RemoveObserver(this); - } -} - -void LayerAnimationObserver::AttachedToSequence( - LayerAnimationSequence* sequence) { - DCHECK(attached_sequences_.find(sequence) == attached_sequences_.end()); - attached_sequences_.insert(sequence); - OnAttachedToSequence(sequence); -} - -void LayerAnimationObserver::DetachedFromSequence( - LayerAnimationSequence* sequence, bool send_notification) { - if (attached_sequences_.find(sequence) != attached_sequences_.end()) - attached_sequences_.erase(sequence); - if (send_notification) - OnDetachedFromSequence(sequence); -} - -//////////////////////////////////////////////////////////////////////////////// -// ImplicitAnimationObserver - -ImplicitAnimationObserver::ImplicitAnimationObserver() - : active_(false), - destroyed_(NULL), - first_sequence_scheduled_(false) { -} - -ImplicitAnimationObserver::~ImplicitAnimationObserver() { - if (destroyed_) - *destroyed_ = true; -} - -void ImplicitAnimationObserver::SetActive(bool active) { - active_ = active; - CheckCompleted(); -} - -void ImplicitAnimationObserver::StopObservingImplicitAnimations() { - SetActive(false); - StopObserving(); -} - -bool ImplicitAnimationObserver::WasAnimationAbortedForProperty( - LayerAnimationElement::AnimatableProperty property) const { - return AnimationStatusForProperty(property) == ANIMATION_STATUS_ABORTED; -} - -bool ImplicitAnimationObserver::WasAnimationCompletedForProperty( - LayerAnimationElement::AnimatableProperty property) const { - return AnimationStatusForProperty(property) == ANIMATION_STATUS_COMPLETED; -} - -void ImplicitAnimationObserver::OnLayerAnimationEnded( - LayerAnimationSequence* sequence) { - UpdatePropertyAnimationStatus(sequence, ANIMATION_STATUS_COMPLETED); - bool destroyed = false; - destroyed_ = &destroyed; - sequence->RemoveObserver(this); - if (destroyed) - return; - destroyed_ = NULL; - DCHECK(attached_sequences().find(sequence) == attached_sequences().end()); - CheckCompleted(); -} - -void ImplicitAnimationObserver::OnLayerAnimationAborted( - LayerAnimationSequence* sequence) { - UpdatePropertyAnimationStatus(sequence, ANIMATION_STATUS_ABORTED); - bool destroyed = false; - destroyed_ = &destroyed; - sequence->RemoveObserver(this); - if (destroyed) - return; - destroyed_ = NULL; - DCHECK(attached_sequences().find(sequence) == attached_sequences().end()); - CheckCompleted(); -} - -void ImplicitAnimationObserver::OnLayerAnimationScheduled( - LayerAnimationSequence* sequence) { - if (!first_sequence_scheduled_) { - first_sequence_scheduled_ = true; - OnImplicitAnimationsScheduled(); - } -} - -void ImplicitAnimationObserver::OnAttachedToSequence( - LayerAnimationSequence* sequence) { -} - -void ImplicitAnimationObserver::OnDetachedFromSequence( - LayerAnimationSequence* sequence) { - DCHECK(attached_sequences().find(sequence) == attached_sequences().end()); - CheckCompleted(); -} - -void ImplicitAnimationObserver::CheckCompleted() { - if (active_ && attached_sequences().empty()) { - active_ = false; - OnImplicitAnimationsCompleted(); - } -} - -void ImplicitAnimationObserver::UpdatePropertyAnimationStatus( - LayerAnimationSequence* sequence, - AnimationStatus status) { - LayerAnimationElement::AnimatableProperties properties = - sequence->properties(); - for (unsigned i = LayerAnimationElement::FIRST_PROPERTY; - i != LayerAnimationElement::SENTINEL; - i = i << 1) { - if (i & properties) { - LayerAnimationElement::AnimatableProperty property = - static_cast<LayerAnimationElement::AnimatableProperty>(i); - property_animation_status_[property] = status; - } - } -} - -ImplicitAnimationObserver::AnimationStatus -ImplicitAnimationObserver::AnimationStatusForProperty( - LayerAnimationElement::AnimatableProperty property) const { - PropertyAnimationStatusMap::const_iterator iter = - property_animation_status_.find(property); - return iter == property_animation_status_.end() ? ANIMATION_STATUS_UNKNOWN : - iter->second; -} - -} // namespace ui
diff --git a/ui/compositor/layer_animation_observer.h b/ui/compositor/layer_animation_observer.h deleted file mode 100644 index 35253d3..0000000 --- a/ui/compositor/layer_animation_observer.h +++ /dev/null
@@ -1,152 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_LAYER_ANIMATION_OBSERVER_H_ -#define UI_COMPOSITOR_LAYER_ANIMATION_OBSERVER_H_ - -#include <map> -#include <set> - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "ui/compositor/compositor_export.h" -#include "ui/compositor/layer_animation_element.h" - -namespace ui { - -class LayerAnimationSequence; -class ScopedLayerAnimationSettings; -class ImplicitAnimationObserver; - -// LayerAnimationObservers are notified when animations complete. -class COMPOSITOR_EXPORT LayerAnimationObserver { - public: - // Called when the |sequence| ends. Not called if |sequence| is aborted. - virtual void OnLayerAnimationEnded( - LayerAnimationSequence* sequence) = 0; - - // Called if |sequence| is aborted for any reason. Should never do anything - // that may cause another animation to be started. - virtual void OnLayerAnimationAborted( - LayerAnimationSequence* sequence) = 0; - - // Called when the animation is scheduled. - virtual void OnLayerAnimationScheduled( - LayerAnimationSequence* sequence) = 0; - - protected: - typedef std::set<LayerAnimationSequence*> AttachedSequences; - - LayerAnimationObserver(); - virtual ~LayerAnimationObserver(); - - // If the animator is destroyed during an animation, the animations are - // aborted. The resulting NotifyAborted notifications will NOT be sent to - // this observer if this function returns false. NOTE: IF YOU override THIS - // FUNCTION TO RETURN TRUE, YOU MUST REMEMBER TO REMOVE YOURSELF AS AN - // OBSERVER WHEN YOU ARE DESTROYED. - virtual bool RequiresNotificationWhenAnimatorDestroyed() const; - - // Called when |this| is added to |sequence|'s observer list. - virtual void OnAttachedToSequence(LayerAnimationSequence* sequence); - - // Called when |this| is removed to |sequence|'s observer list. - virtual void OnDetachedFromSequence(LayerAnimationSequence* sequence); - - // Detaches this observer from all sequences it is currently observing. - void StopObserving(); - - const AttachedSequences& attached_sequences() const { - return attached_sequences_; - } - - private: - friend class LayerAnimationSequence; - - // Called when |this| is added to |sequence|'s observer list. - void AttachedToSequence(LayerAnimationSequence* sequence); - - // Called when |this| is removed to |sequence|'s observer list. - // This will only result in notifications if |send_notification| is true. - void DetachedFromSequence(LayerAnimationSequence* sequence, - bool send_notification); - - AttachedSequences attached_sequences_; -}; - -// An implicit animation observer is intended to be used in conjunction with a -// ScopedLayerAnimationSettings object in order to receive a notification when -// all implicit animations complete. -class COMPOSITOR_EXPORT ImplicitAnimationObserver - : public LayerAnimationObserver { - public: - ImplicitAnimationObserver(); - ~ImplicitAnimationObserver() override; - - // Called when the first animation sequence has started. - virtual void OnImplicitAnimationsScheduled() {} - - virtual void OnImplicitAnimationsCompleted() = 0; - - protected: - // Deactivates the observer and clears the collection of animations it is - // waiting for. - void StopObservingImplicitAnimations(); - - // Returns whether animation for |property| was aborted. - // Note that if the property wasn't animated, then it couldn't have been - // aborted, so this will return false for that property. - bool WasAnimationAbortedForProperty( - LayerAnimationElement::AnimatableProperty property) const; - - // Returns whether animation for |property| was completed successfully. - // Note that if the property wasn't animated, then it couldn't have been - // completed, so this will return false for that property. - bool WasAnimationCompletedForProperty( - LayerAnimationElement::AnimatableProperty property) const; - - private: - enum AnimationStatus { - ANIMATION_STATUS_UNKNOWN, - ANIMATION_STATUS_COMPLETED, - ANIMATION_STATUS_ABORTED, - }; - - friend class ScopedLayerAnimationSettings; - - // LayerAnimationObserver implementation - void OnLayerAnimationEnded(LayerAnimationSequence* sequence) override; - void OnLayerAnimationAborted(LayerAnimationSequence* sequence) override; - void OnLayerAnimationScheduled(LayerAnimationSequence* sequence) override; - void OnAttachedToSequence(LayerAnimationSequence* sequence) override; - void OnDetachedFromSequence(LayerAnimationSequence* sequence) override; - - // OnImplicitAnimationsCompleted is not fired unless the observer is active. - bool active() const { return active_; } - void SetActive(bool active); - - void CheckCompleted(); - - void UpdatePropertyAnimationStatus(LayerAnimationSequence* sequence, - AnimationStatus status); - AnimationStatus AnimationStatusForProperty( - LayerAnimationElement::AnimatableProperty property) const; - - bool active_; - - // Set to true in the destructor (if non-NULL). Used to detect deletion while - // calling out. - bool* destroyed_; - - typedef std::map<LayerAnimationElement::AnimatableProperty, - AnimationStatus> PropertyAnimationStatusMap; - PropertyAnimationStatusMap property_animation_status_; - - // True if OnLayerAnimationScheduled() has been called at least once. - bool first_sequence_scheduled_; -}; - -} // namespace ui - -#endif // UI_COMPOSITOR_LAYER_ANIMATION_OBSERVER_H_
diff --git a/ui/compositor/layer_animation_sequence.cc b/ui/compositor/layer_animation_sequence.cc deleted file mode 100644 index 31d09c9..0000000 --- a/ui/compositor/layer_animation_sequence.cc +++ /dev/null
@@ -1,281 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/compositor/layer_animation_sequence.h" - -#include <algorithm> -#include <iterator> - -#include "base/debug/trace_event.h" -#include "cc/animation/animation_id_provider.h" -#include "ui/compositor/layer_animation_delegate.h" -#include "ui/compositor/layer_animation_element.h" -#include "ui/compositor/layer_animation_observer.h" - -namespace ui { - -LayerAnimationSequence::LayerAnimationSequence() - : properties_(LayerAnimationElement::UNKNOWN), - is_cyclic_(false), - last_element_(0), - waiting_for_group_start_(false), - animation_group_id_(0), - last_progressed_fraction_(0.0), - weak_ptr_factory_(this) { -} - -LayerAnimationSequence::LayerAnimationSequence(LayerAnimationElement* element) - : properties_(LayerAnimationElement::UNKNOWN), - is_cyclic_(false), - last_element_(0), - waiting_for_group_start_(false), - animation_group_id_(0), - last_progressed_fraction_(0.0), - weak_ptr_factory_(this) { - AddElement(element); -} - -LayerAnimationSequence::~LayerAnimationSequence() { - FOR_EACH_OBSERVER(LayerAnimationObserver, - observers_, - DetachedFromSequence(this, true)); -} - -void LayerAnimationSequence::Start(LayerAnimationDelegate* delegate) { - DCHECK(start_time_ != base::TimeTicks()); - last_progressed_fraction_ = 0.0; - if (elements_.empty()) - return; - - elements_[0]->set_requested_start_time(start_time_); - elements_[0]->Start(delegate, animation_group_id_); -} - -void LayerAnimationSequence::Progress(base::TimeTicks now, - LayerAnimationDelegate* delegate) { - DCHECK(start_time_ != base::TimeTicks()); - bool redraw_required = false; - - if (elements_.empty()) - return; - - if (last_element_ == 0) - last_start_ = start_time_; - - size_t current_index = last_element_ % elements_.size(); - base::TimeDelta element_duration; - while (is_cyclic_ || last_element_ < elements_.size()) { - elements_[current_index]->set_requested_start_time(last_start_); - if (!elements_[current_index]->IsFinished(now, &element_duration)) - break; - - // Let the element we're passing finish. - if (elements_[current_index]->ProgressToEnd(delegate)) - redraw_required = true; - last_start_ += element_duration; - ++last_element_; - last_progressed_fraction_ = - elements_[current_index]->last_progressed_fraction(); - current_index = last_element_ % elements_.size(); - } - - if (is_cyclic_ || last_element_ < elements_.size()) { - if (!elements_[current_index]->Started()) { - animation_group_id_ = cc::AnimationIdProvider::NextGroupId(); - elements_[current_index]->Start(delegate, animation_group_id_); - } - base::WeakPtr<LayerAnimationSequence> alive(weak_ptr_factory_.GetWeakPtr()); - if (elements_[current_index]->Progress(now, delegate)) - redraw_required = true; - if (!alive) - return; - last_progressed_fraction_ = - elements_[current_index]->last_progressed_fraction(); - } - - // Since the delegate may be deleted due to the notifications below, it is - // important that we schedule a draw before sending them. - if (redraw_required) - delegate->ScheduleDrawForAnimation(); - - if (!is_cyclic_ && last_element_ == elements_.size()) { - last_element_ = 0; - waiting_for_group_start_ = false; - animation_group_id_ = 0; - NotifyEnded(); - } -} - -bool LayerAnimationSequence::IsFinished(base::TimeTicks time) { - if (is_cyclic_ || waiting_for_group_start_) - return false; - - if (elements_.empty()) - return true; - - if (last_element_ == 0) - last_start_ = start_time_; - - base::TimeTicks current_start = last_start_; - size_t current_index = last_element_; - base::TimeDelta element_duration; - while (current_index < elements_.size()) { - elements_[current_index]->set_requested_start_time(current_start); - if (!elements_[current_index]->IsFinished(time, &element_duration)) - break; - - current_start += element_duration; - ++current_index; - } - - return (current_index == elements_.size()); -} - -void LayerAnimationSequence::ProgressToEnd(LayerAnimationDelegate* delegate) { - bool redraw_required = false; - - if (elements_.empty()) - return; - - size_t current_index = last_element_ % elements_.size(); - while (current_index < elements_.size()) { - if (elements_[current_index]->ProgressToEnd(delegate)) - redraw_required = true; - last_progressed_fraction_ = - elements_[current_index]->last_progressed_fraction(); - ++current_index; - ++last_element_; - } - - if (redraw_required) - delegate->ScheduleDrawForAnimation(); - - if (!is_cyclic_) { - last_element_ = 0; - waiting_for_group_start_ = false; - animation_group_id_ = 0; - NotifyEnded(); - } -} - -void LayerAnimationSequence::GetTargetValue( - LayerAnimationElement::TargetValue* target) const { - if (is_cyclic_) - return; - - for (size_t i = last_element_; i < elements_.size(); ++i) - elements_[i]->GetTargetValue(target); -} - -void LayerAnimationSequence::Abort(LayerAnimationDelegate* delegate) { - size_t current_index = last_element_ % elements_.size(); - while (current_index < elements_.size()) { - elements_[current_index]->Abort(delegate); - ++current_index; - } - last_element_ = 0; - waiting_for_group_start_ = false; - NotifyAborted(); -} - -void LayerAnimationSequence::AddElement(LayerAnimationElement* element) { - properties_ |= element->properties(); - elements_.push_back(make_linked_ptr(element)); -} - -bool LayerAnimationSequence::HasConflictingProperty( - LayerAnimationElement::AnimatableProperties other) const { - return (properties_ & other) != LayerAnimationElement::UNKNOWN; -} - -bool LayerAnimationSequence::IsFirstElementThreaded() const { - if (!elements_.empty()) - return elements_[0]->IsThreaded(); - - return false; -} - -void LayerAnimationSequence::AddObserver(LayerAnimationObserver* observer) { - if (!observers_.HasObserver(observer)) { - observers_.AddObserver(observer); - observer->AttachedToSequence(this); - } -} - -void LayerAnimationSequence::RemoveObserver(LayerAnimationObserver* observer) { - observers_.RemoveObserver(observer); - observer->DetachedFromSequence(this, true); -} - -void LayerAnimationSequence::OnThreadedAnimationStarted( - const cc::AnimationEvent& event) { - if (elements_.empty() || event.group_id != animation_group_id_) - return; - - size_t current_index = last_element_ % elements_.size(); - LayerAnimationElement::AnimatableProperties element_properties = - elements_[current_index]->properties(); - LayerAnimationElement::AnimatableProperty event_property = - LayerAnimationElement::ToAnimatableProperty(event.target_property); - DCHECK(element_properties & event_property); - elements_[current_index]->set_effective_start_time(event.monotonic_time); -} - -void LayerAnimationSequence::OnScheduled() { - NotifyScheduled(); -} - -void LayerAnimationSequence::OnAnimatorDestroyed() { - if (observers_.might_have_observers()) { - ObserverListBase<LayerAnimationObserver>::Iterator it(observers_); - LayerAnimationObserver* obs; - while ((obs = it.GetNext()) != NULL) { - if (!obs->RequiresNotificationWhenAnimatorDestroyed()) { - // Remove the observer, but do not allow notifications to be sent. - observers_.RemoveObserver(obs); - obs->DetachedFromSequence(this, false); - } - } - } -} - -size_t LayerAnimationSequence::size() const { - return elements_.size(); -} - -LayerAnimationElement* LayerAnimationSequence::FirstElement() const { - if (elements_.empty()) { - return NULL; - } - - return elements_[0].get(); -} - -void LayerAnimationSequence::NotifyScheduled() { - FOR_EACH_OBSERVER(LayerAnimationObserver, - observers_, - OnLayerAnimationScheduled(this)); -} - -void LayerAnimationSequence::NotifyEnded() { - FOR_EACH_OBSERVER(LayerAnimationObserver, - observers_, - OnLayerAnimationEnded(this)); -} - -void LayerAnimationSequence::NotifyAborted() { - FOR_EACH_OBSERVER(LayerAnimationObserver, - observers_, - OnLayerAnimationAborted(this)); -} - -LayerAnimationElement* LayerAnimationSequence::CurrentElement() const { - if (elements_.empty()) - return NULL; - - size_t current_index = last_element_ % elements_.size(); - return elements_[current_index].get(); -} - -} // namespace ui
diff --git a/ui/compositor/layer_animation_sequence.h b/ui/compositor/layer_animation_sequence.h deleted file mode 100644 index 19635ad..0000000 --- a/ui/compositor/layer_animation_sequence.h +++ /dev/null
@@ -1,192 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_LAYER_ANIMATION_SEQUENCE_H_ -#define UI_COMPOSITOR_LAYER_ANIMATION_SEQUENCE_H_ - -#include <vector> - -#include "base/gtest_prod_util.h" -#include "base/memory/linked_ptr.h" -#include "base/memory/weak_ptr.h" -#include "base/observer_list.h" -#include "base/time/time.h" -#include "ui/compositor/compositor_export.h" -#include "ui/compositor/layer_animation_element.h" - -namespace ui { - -class LayerAnimationDelegate; -class LayerAnimationObserver; - -// Contains a collection of layer animation elements to be played one after -// another. Although it has a similar interface to LayerAnimationElement, it is -// not a LayerAnimationElement (i.e., it is not permitted to have a sequence in -// a sequence). Sequences own their elements, and sequences are themselves owned -// by a LayerAnimator. -// -// TODO(vollick) Create a 'blended' sequence for transitioning between -// sequences. -// TODO(vollick) Eventually, the LayerAnimator will switch to a model where new -// work is scheduled rather than calling methods directly. This should make it -// impossible for temporary pointers to running animations to go stale. When -// this happens, there will be no need for LayerAnimationSequences to support -// weak pointers. -class COMPOSITOR_EXPORT LayerAnimationSequence - : public base::SupportsWeakPtr<LayerAnimationSequence> { - public: - LayerAnimationSequence(); - // Takes ownership of the given element and adds it to the sequence. - explicit LayerAnimationSequence(LayerAnimationElement* element); - virtual ~LayerAnimationSequence(); - - // Sets the start time for the animation. This must be called before the - // first call to {Start, IsFinished}. Once the animation is finished, this - // must be called again in order to restart the animation. - void set_start_time(base::TimeTicks start_time) { start_time_ = start_time; } - base::TimeTicks start_time() const { return start_time_; } - - // Sets a flag indicating that this sequence will start together with other - // sequences, and at least one of the sequences in this group has a threaded - // first element. - void set_waiting_for_group_start(bool waiting) { - waiting_for_group_start_ = waiting; - } - bool waiting_for_group_start() { return waiting_for_group_start_; } - - // This must be called before the first call to Progress. If starting the - // animation involves dispatching to another thread, then this will proceed - // with that dispatch, ultimately resulting in the animation getting an - // effective start time (the time the animation starts on the other thread). - void Start(LayerAnimationDelegate* delegate); - - // Updates the delegate to the appropriate value for |now|. Requests a - // redraw if it is required. - void Progress(base::TimeTicks now, LayerAnimationDelegate* delegate); - - // Returns true if calling Progress now, with the given time, will finish - // the animation. - bool IsFinished(base::TimeTicks time); - - // Updates the delegate to the end of the animation; if this sequence is - // cyclic, updates the delegate to the end of one cycle of the sequence. - void ProgressToEnd(LayerAnimationDelegate* delegate); - - // Sets the target value to the value that would have been set had - // the sequence completed. Does nothing if the sequence is cyclic. - void GetTargetValue(LayerAnimationElement::TargetValue* target) const; - - // Aborts the given animation. - void Abort(LayerAnimationDelegate* delegate); - - // All properties modified by the sequence. - LayerAnimationElement::AnimatableProperties properties() const { - return properties_; - } - - // Adds an element to the sequence. The sequences takes ownership of this - // element. - void AddElement(LayerAnimationElement* element); - - // Sequences can be looped indefinitely. - void set_is_cyclic(bool is_cyclic) { is_cyclic_ = is_cyclic; } - bool is_cyclic() const { return is_cyclic_; } - - // Returns true if this sequence has at least one element conflicting with a - // property in |other|. - bool HasConflictingProperty( - LayerAnimationElement::AnimatableProperties other) const; - - // Returns true if the first element animates on the compositor thread. - bool IsFirstElementThreaded() const; - - // Used to identify groups of sequences that are supposed to start together. - // Once started, used to identify the sequence that owns a particular - // threaded animation. - int animation_group_id() const { return animation_group_id_; } - void set_animation_group_id(int id) { animation_group_id_ = id; } - - // These functions are used for adding or removing observers from the observer - // list. The observers are notified when animations end. - void AddObserver(LayerAnimationObserver* observer); - void RemoveObserver(LayerAnimationObserver* observer); - - // Called when a threaded animation is actually started. - void OnThreadedAnimationStarted(const cc::AnimationEvent& event); - - // Called when the animator schedules this sequence. - void OnScheduled(); - - // Called when the animator is destroyed. - void OnAnimatorDestroyed(); - - // The last_progressed_fraction of the element most recently progressed by - // by this sequence. Returns 0.0 if no elements have been progressed. - double last_progressed_fraction() const { return last_progressed_fraction_; } - - size_t size() const; - - LayerAnimationElement* FirstElement() const; - - private: - friend class LayerAnimatorTestController; - - typedef std::vector<linked_ptr<LayerAnimationElement> > Elements; - - FRIEND_TEST_ALL_PREFIXES(LayerAnimatorTest, - ObserverReleasedBeforeAnimationSequenceEnds); - - // Notifies the observers that this sequence has been scheduled. - void NotifyScheduled(); - - // Notifies the observers that this sequence has ended. - void NotifyEnded(); - - // Notifies the observers that this sequence has been aborted. - void NotifyAborted(); - - // The currently animating element. - LayerAnimationElement* CurrentElement() const; - - // The union of all the properties modified by all elements in the sequence. - LayerAnimationElement::AnimatableProperties properties_; - - // The elements in the sequence. - Elements elements_; - - // True if the sequence should be looped forever. - bool is_cyclic_; - - // These are used when animating to efficiently find the next element. - size_t last_element_; - base::TimeTicks last_start_; - - // The start time of the current run of the sequence. - base::TimeTicks start_time_; - - // True if this sequence will start together with other sequences, and at - // least one of the sequences in this group has a threaded first element. - bool waiting_for_group_start_; - - // Identifies groups of sequences that are supposed to start together. - // Also used to identify the owner of a particular threaded animation; any - // in-progress threaded animation owned by this sequence will have this - // group id. - int animation_group_id_; - - // These parties are notified when layer animations end. - ObserverList<LayerAnimationObserver> observers_; - - // Tracks the last_progressed_fraction() of the most recently progressed - // element. - double last_progressed_fraction_; - - base::WeakPtrFactory<LayerAnimationSequence> weak_ptr_factory_; - - DISALLOW_COPY_AND_ASSIGN(LayerAnimationSequence); -}; - -} // namespace ui - -#endif // UI_COMPOSITOR_LAYER_ANIMATION_SEQUENCE_H_
diff --git a/ui/compositor/layer_animation_sequence_unittest.cc b/ui/compositor/layer_animation_sequence_unittest.cc deleted file mode 100644 index 6577974..0000000 --- a/ui/compositor/layer_animation_sequence_unittest.cc +++ /dev/null
@@ -1,282 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/compositor/layer_animation_sequence.h" - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "base/time/time.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/compositor/layer_animation_delegate.h" -#include "ui/compositor/layer_animation_element.h" -#include "ui/compositor/test/test_layer_animation_delegate.h" -#include "ui/compositor/test/test_layer_animation_observer.h" -#include "ui/compositor/test/test_utils.h" -#include "ui/gfx/rect.h" -#include "ui/gfx/transform.h" - -namespace ui { - -namespace { - -// Check that the sequence behaves sanely when it contains no elements. -TEST(LayerAnimationSequenceTest, NoElement) { - LayerAnimationSequence sequence; - base::TimeTicks start_time; - start_time += base::TimeDelta::FromSeconds(1); - sequence.set_start_time(start_time); - EXPECT_TRUE(sequence.IsFinished(start_time)); - EXPECT_EQ(static_cast<LayerAnimationElement::AnimatableProperties>( - LayerAnimationElement::UNKNOWN), - sequence.properties()); - EXPECT_FALSE(sequence.HasConflictingProperty(LayerAnimationElement::UNKNOWN)); -} - -// Check that the sequences progresses the delegate as expected when it contains -// a single non-threaded element. -TEST(LayerAnimationSequenceTest, SingleElement) { - LayerAnimationSequence sequence; - TestLayerAnimationDelegate delegate; - float start = 0.0f; - float middle = 0.5f; - float target = 1.0f; - base::TimeTicks start_time; - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - sequence.AddElement( - LayerAnimationElement::CreateBrightnessElement(target, delta)); - - for (int i = 0; i < 2; ++i) { - start_time += delta; - sequence.set_start_time(start_time); - delegate.SetBrightnessFromAnimation(start); - sequence.Start(&delegate); - sequence.Progress(start_time, &delegate); - EXPECT_FLOAT_EQ(start, delegate.GetBrightnessForAnimation()); - sequence.Progress(start_time + base::TimeDelta::FromMilliseconds(500), - &delegate); - EXPECT_FLOAT_EQ(middle, delegate.GetBrightnessForAnimation()); - EXPECT_TRUE(sequence.IsFinished(start_time + delta)); - sequence.Progress(start_time + base::TimeDelta::FromMilliseconds(1000), - &delegate); - EXPECT_FLOAT_EQ(target, delegate.GetBrightnessForAnimation()); - } - - EXPECT_EQ(static_cast<LayerAnimationElement::AnimatableProperties>( - LayerAnimationElement::BRIGHTNESS), - sequence.properties()); -} - -// Check that the sequences progresses the delegate as expected when it contains -// a single threaded element. -TEST(LayerAnimationSequenceTest, SingleThreadedElement) { - LayerAnimationSequence sequence; - TestLayerAnimationDelegate delegate; - float start = 0.0f; - float middle = 0.5f; - float target = 1.0f; - base::TimeTicks start_time; - base::TimeTicks effective_start; - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - sequence.AddElement( - LayerAnimationElement::CreateOpacityElement(target, delta)); - - for (int i = 0; i < 2; ++i) { - int starting_group_id = 1; - sequence.set_animation_group_id(starting_group_id); - start_time = effective_start + delta; - sequence.set_start_time(start_time); - delegate.SetOpacityFromAnimation(start); - sequence.Start(&delegate); - sequence.Progress(start_time, &delegate); - EXPECT_FLOAT_EQ(start, sequence.last_progressed_fraction()); - effective_start = start_time + delta; - sequence.OnThreadedAnimationStarted( - cc::AnimationEvent(cc::AnimationEvent::Started, - 0, - sequence.animation_group_id(), - cc::Animation::Opacity, - effective_start)); - sequence.Progress(effective_start + delta/2, &delegate); - EXPECT_FLOAT_EQ(middle, sequence.last_progressed_fraction()); - EXPECT_TRUE(sequence.IsFinished(effective_start + delta)); - sequence.Progress(effective_start + delta, &delegate); - EXPECT_FLOAT_EQ(target, sequence.last_progressed_fraction()); - EXPECT_FLOAT_EQ(target, delegate.GetOpacityForAnimation()); - } - - EXPECT_EQ(static_cast<LayerAnimationElement::AnimatableProperties>( - LayerAnimationElement::OPACITY), - sequence.properties()); -} - -// Check that the sequences progresses the delegate as expected when it contains -// multiple elements. Note, see the layer animator tests for cyclic sequences. -TEST(LayerAnimationSequenceTest, MultipleElement) { - LayerAnimationSequence sequence; - TestLayerAnimationDelegate delegate; - float start_opacity = 0.0f; - float target_opacity = 1.0f; - base::TimeTicks start_time; - base::TimeTicks opacity_effective_start; - base::TimeTicks transform_effective_start; - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - sequence.AddElement( - LayerAnimationElement::CreateOpacityElement(target_opacity, delta)); - - // Pause bounds for a second. - sequence.AddElement(LayerAnimationElement::CreatePauseElement( - LayerAnimationElement::BOUNDS, delta)); - - gfx::Transform start_transform, target_transform, middle_transform; - start_transform.Rotate(-30.0); - target_transform.Rotate(30.0); - - sequence.AddElement( - LayerAnimationElement::CreateTransformElement(target_transform, delta)); - - for (int i = 0; i < 2; ++i) { - int starting_group_id = 1; - sequence.set_animation_group_id(starting_group_id); - start_time = opacity_effective_start + 4 * delta; - sequence.set_start_time(start_time); - delegate.SetOpacityFromAnimation(start_opacity); - delegate.SetTransformFromAnimation(start_transform); - - sequence.Start(&delegate); - sequence.Progress(start_time, &delegate); - EXPECT_FLOAT_EQ(0.0, sequence.last_progressed_fraction()); - opacity_effective_start = start_time + delta; - EXPECT_EQ(starting_group_id, sequence.animation_group_id()); - sequence.OnThreadedAnimationStarted( - cc::AnimationEvent(cc::AnimationEvent::Started, - 0, - sequence.animation_group_id(), - cc::Animation::Opacity, - opacity_effective_start)); - sequence.Progress(opacity_effective_start + delta/2, &delegate); - EXPECT_FLOAT_EQ(0.5, sequence.last_progressed_fraction()); - sequence.Progress(opacity_effective_start + delta, &delegate); - EXPECT_FLOAT_EQ(target_opacity, delegate.GetOpacityForAnimation()); - - // Now at the start of the pause. - EXPECT_FLOAT_EQ(0.0, sequence.last_progressed_fraction()); - TestLayerAnimationDelegate copy = delegate; - - // In the middle of the pause -- nothing should have changed. - sequence.Progress(opacity_effective_start + delta + delta/2, - &delegate); - CheckApproximatelyEqual(delegate.GetBoundsForAnimation(), - copy.GetBoundsForAnimation()); - CheckApproximatelyEqual(delegate.GetTransformForAnimation(), - copy.GetTransformForAnimation()); - EXPECT_FLOAT_EQ(delegate.GetOpacityForAnimation(), - copy.GetOpacityForAnimation()); - - sequence.Progress(opacity_effective_start + 2 * delta, &delegate); - CheckApproximatelyEqual(start_transform, - delegate.GetTransformForAnimation()); - EXPECT_FLOAT_EQ(0.0, sequence.last_progressed_fraction()); - transform_effective_start = opacity_effective_start + 3 * delta; - EXPECT_NE(starting_group_id, sequence.animation_group_id()); - sequence.OnThreadedAnimationStarted( - cc::AnimationEvent(cc::AnimationEvent::Started, - 0, - sequence.animation_group_id(), - cc::Animation::Transform, - transform_effective_start)); - sequence.Progress(transform_effective_start + delta/2, &delegate); - EXPECT_FLOAT_EQ(0.5, sequence.last_progressed_fraction()); - EXPECT_TRUE(sequence.IsFinished(transform_effective_start + delta)); - sequence.Progress(transform_effective_start + delta, &delegate); - CheckApproximatelyEqual(target_transform, - delegate.GetTransformForAnimation()); - } - - EXPECT_EQ( - static_cast<LayerAnimationElement::AnimatableProperties>( - LayerAnimationElement::OPACITY | LayerAnimationElement::TRANSFORM | - LayerAnimationElement::BOUNDS), - sequence.properties()); -} - -// Check that a sequence can still be aborted if it has cycled many times. -TEST(LayerAnimationSequenceTest, AbortingCyclicSequence) { - LayerAnimationSequence sequence; - TestLayerAnimationDelegate delegate; - float start_brightness = 0.0f; - float target_brightness = 1.0f; - base::TimeTicks start_time; - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - sequence.AddElement( - LayerAnimationElement::CreateBrightnessElement(target_brightness, delta)); - - sequence.AddElement( - LayerAnimationElement::CreateBrightnessElement(start_brightness, delta)); - - sequence.set_is_cyclic(true); - - delegate.SetBrightnessFromAnimation(start_brightness); - - start_time += delta; - sequence.set_start_time(start_time); - sequence.Start(&delegate); - sequence.Progress(start_time + base::TimeDelta::FromMilliseconds(101000), - &delegate); - EXPECT_FLOAT_EQ(target_brightness, delegate.GetBrightnessForAnimation()); - sequence.Abort(&delegate); - - // Should be able to reuse the sequence after aborting. - delegate.SetBrightnessFromAnimation(start_brightness); - start_time += base::TimeDelta::FromMilliseconds(101000); - sequence.set_start_time(start_time); - sequence.Progress(start_time + base::TimeDelta::FromMilliseconds(100000), - &delegate); - EXPECT_FLOAT_EQ(start_brightness, delegate.GetBrightnessForAnimation()); -} - -// Check that a sequence can be 'fast-forwarded' to the end and the target set. -// Also check that this has no effect if the sequence is cyclic. -TEST(LayerAnimationSequenceTest, SetTarget) { - LayerAnimationSequence sequence; - TestLayerAnimationDelegate delegate; - float start_opacity = 0.0f; - float target_opacity = 1.0f; - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - sequence.AddElement( - LayerAnimationElement::CreateOpacityElement(target_opacity, delta)); - - LayerAnimationElement::TargetValue target_value(&delegate); - target_value.opacity = start_opacity; - sequence.GetTargetValue(&target_value); - EXPECT_FLOAT_EQ(target_opacity, target_value.opacity); - - sequence.set_is_cyclic(true); - target_value.opacity = start_opacity; - sequence.GetTargetValue(&target_value); - EXPECT_FLOAT_EQ(start_opacity, target_value.opacity); -} - -TEST(LayerAnimationSequenceTest, AddObserver) { - base::TimeTicks start_time; - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - LayerAnimationSequence sequence; - sequence.AddElement( - LayerAnimationElement::CreateBrightnessElement(1.0f, delta)); - for (int i = 0; i < 2; ++i) { - start_time += delta; - sequence.set_start_time(start_time); - TestLayerAnimationObserver observer; - TestLayerAnimationDelegate delegate; - sequence.AddObserver(&observer); - EXPECT_TRUE(!observer.last_ended_sequence()); - sequence.Progress(start_time + delta, &delegate); - EXPECT_EQ(observer.last_ended_sequence(), &sequence); - sequence.RemoveObserver(&observer); - } -} - -} // namespace - -} // namespace ui
diff --git a/ui/compositor/layer_animator.cc b/ui/compositor/layer_animator.cc deleted file mode 100644 index 39585a7..0000000 --- a/ui/compositor/layer_animator.cc +++ /dev/null
@@ -1,862 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/compositor/layer_animator.h" - -#include "base/debug/trace_event.h" -#include "base/logging.h" -#include "base/memory/scoped_ptr.h" -#include "cc/animation/animation_id_provider.h" -#include "cc/output/begin_frame_args.h" -#include "ui/compositor/compositor.h" -#include "ui/compositor/layer.h" -#include "ui/compositor/layer_animation_delegate.h" -#include "ui/compositor/layer_animation_observer.h" -#include "ui/compositor/layer_animation_sequence.h" -#include "ui/compositor/layer_animator_collection.h" -#include "ui/gfx/frame_time.h" - -#define SAFE_INVOKE_VOID(function, running_anim, ...) \ - if (running_anim.is_sequence_alive()) \ - function(running_anim.sequence(), ##__VA_ARGS__) -#define SAFE_INVOKE_BOOL(function, running_anim) \ - ((running_anim.is_sequence_alive()) \ - ? function(running_anim.sequence()) \ - : false) -#define SAFE_INVOKE_PTR(function, running_anim) \ - ((running_anim.is_sequence_alive()) \ - ? function(running_anim.sequence()) \ - : NULL) - -namespace ui { - -namespace { - -const int kDefaultTransitionDurationMs = 120; - -} // namespace - -// LayerAnimator public -------------------------------------------------------- - -LayerAnimator::LayerAnimator(base::TimeDelta transition_duration) - : delegate_(NULL), - preemption_strategy_(IMMEDIATELY_SET_NEW_TARGET), - is_transition_duration_locked_(false), - transition_duration_(transition_duration), - tween_type_(gfx::Tween::LINEAR), - is_started_(false), - disable_timer_for_test_(false), - adding_animations_(false) { -} - -LayerAnimator::~LayerAnimator() { - for (size_t i = 0; i < running_animations_.size(); ++i) { - if (running_animations_[i].is_sequence_alive()) - running_animations_[i].sequence()->OnAnimatorDestroyed(); - } - ClearAnimationsInternal(); - delegate_ = NULL; -} - -// static -LayerAnimator* LayerAnimator::CreateDefaultAnimator() { - return new LayerAnimator(base::TimeDelta::FromMilliseconds(0)); -} - -// static -LayerAnimator* LayerAnimator::CreateImplicitAnimator() { - return new LayerAnimator( - base::TimeDelta::FromMilliseconds(kDefaultTransitionDurationMs)); -} - -// This macro provides the implementation for the setter and getter (well, -// the getter of the target value) for an animated property. For example, -// it is used for the implementations of SetTransform and GetTargetTransform. -// It is worth noting that SetFoo avoids invoking the usual animation machinery -// if the transition duration is zero -- in this case we just set the property -// on the layer animation delegate immediately. -#define ANIMATED_PROPERTY(type, property, name, member_type, member) \ -void LayerAnimator::Set##name(type value) { \ - base::TimeDelta duration = GetTransitionDuration(); \ - if (duration == base::TimeDelta() && delegate() && \ - (preemption_strategy_ != ENQUEUE_NEW_ANIMATION)) { \ - StopAnimatingProperty(LayerAnimationElement::property); \ - delegate()->Set##name##FromAnimation(value); \ - return; \ - } \ - scoped_ptr<LayerAnimationElement> element( \ - LayerAnimationElement::Create##name##Element(value, duration)); \ - element->set_tween_type(tween_type_); \ - StartAnimation(new LayerAnimationSequence(element.release())); \ -} \ - \ -member_type LayerAnimator::GetTarget##name() const { \ - LayerAnimationElement::TargetValue target(delegate()); \ - GetTargetValue(&target); \ - return target.member; \ -} - -ANIMATED_PROPERTY( - const gfx::Transform&, TRANSFORM, Transform, gfx::Transform, transform); -ANIMATED_PROPERTY(const gfx::Rect&, BOUNDS, Bounds, gfx::Rect, bounds); -ANIMATED_PROPERTY(float, OPACITY, Opacity, float, opacity); -ANIMATED_PROPERTY(bool, VISIBILITY, Visibility, bool, visibility); -ANIMATED_PROPERTY(float, BRIGHTNESS, Brightness, float, brightness); -ANIMATED_PROPERTY(float, GRAYSCALE, Grayscale, float, grayscale); -ANIMATED_PROPERTY(SkColor, COLOR, Color, SkColor, color); - -base::TimeDelta LayerAnimator::GetTransitionDuration() const { - return transition_duration_; -} - -void LayerAnimator::SetDelegate(LayerAnimationDelegate* delegate) { - if (delegate_ && is_started_) { - LayerAnimatorCollection* collection = GetLayerAnimatorCollection(); - if (collection) - collection->StopAnimator(this); - } - delegate_ = delegate; - if (delegate_ && is_started_) { - LayerAnimatorCollection* collection = GetLayerAnimatorCollection(); - if (collection) - collection->StartAnimator(this); - } -} - -void LayerAnimator::StartAnimation(LayerAnimationSequence* animation) { - scoped_refptr<LayerAnimator> retain(this); - OnScheduled(animation); - if (!StartSequenceImmediately(animation)) { - // Attempt to preempt a running animation. - switch (preemption_strategy_) { - case IMMEDIATELY_SET_NEW_TARGET: - ImmediatelySetNewTarget(animation); - break; - case IMMEDIATELY_ANIMATE_TO_NEW_TARGET: - ImmediatelyAnimateToNewTarget(animation); - break; - case ENQUEUE_NEW_ANIMATION: - EnqueueNewAnimation(animation); - break; - case REPLACE_QUEUED_ANIMATIONS: - ReplaceQueuedAnimations(animation); - break; - case BLEND_WITH_CURRENT_ANIMATION: { - // TODO(vollick) Add support for blended sequences and use them here. - NOTIMPLEMENTED(); - break; - } - } - } - FinishAnyAnimationWithZeroDuration(); - UpdateAnimationState(); -} - -void LayerAnimator::ScheduleAnimation(LayerAnimationSequence* animation) { - scoped_refptr<LayerAnimator> retain(this); - OnScheduled(animation); - if (is_animating()) { - animation_queue_.push_back(make_linked_ptr(animation)); - ProcessQueue(); - } else { - StartSequenceImmediately(animation); - } - UpdateAnimationState(); -} - -void LayerAnimator::StartTogether( - const std::vector<LayerAnimationSequence*>& animations) { - scoped_refptr<LayerAnimator> retain(this); - if (preemption_strategy_ == IMMEDIATELY_SET_NEW_TARGET) { - std::vector<LayerAnimationSequence*>::const_iterator iter; - for (iter = animations.begin(); iter != animations.end(); ++iter) { - StartAnimation(*iter); - } - return; - } - - adding_animations_ = true; - if (!is_animating()) { - LayerAnimatorCollection* collection = GetLayerAnimatorCollection(); - if (collection && collection->HasActiveAnimators()) - last_step_time_ = collection->last_tick_time(); - else - last_step_time_ = gfx::FrameTime::Now(); - } - - // Collect all the affected properties. - LayerAnimationElement::AnimatableProperties animated_properties = - LayerAnimationElement::UNKNOWN; - - std::vector<LayerAnimationSequence*>::const_iterator iter; - for (iter = animations.begin(); iter != animations.end(); ++iter) - animated_properties |= (*iter)->properties(); - - // Starting a zero duration pause that affects all the animated properties - // will prevent any of the sequences from animating until there are no - // running animations that affect any of these properties, as well as - // handle preemption strategy. - StartAnimation(new LayerAnimationSequence( - LayerAnimationElement::CreatePauseElement(animated_properties, - base::TimeDelta()))); - - bool wait_for_group_start = false; - for (iter = animations.begin(); iter != animations.end(); ++iter) - wait_for_group_start |= (*iter)->IsFirstElementThreaded(); - - int group_id = cc::AnimationIdProvider::NextGroupId(); - - // These animations (provided they don't animate any common properties) will - // now animate together if trivially scheduled. - for (iter = animations.begin(); iter != animations.end(); ++iter) { - (*iter)->set_animation_group_id(group_id); - (*iter)->set_waiting_for_group_start(wait_for_group_start); - ScheduleAnimation(*iter); - } - - adding_animations_ = false; - UpdateAnimationState(); -} - - -void LayerAnimator::ScheduleTogether( - const std::vector<LayerAnimationSequence*>& animations) { - scoped_refptr<LayerAnimator> retain(this); - - // Collect all the affected properties. - LayerAnimationElement::AnimatableProperties animated_properties = - LayerAnimationElement::UNKNOWN; - - std::vector<LayerAnimationSequence*>::const_iterator iter; - for (iter = animations.begin(); iter != animations.end(); ++iter) - animated_properties |= (*iter)->properties(); - - // Scheduling a zero duration pause that affects all the animated properties - // will prevent any of the sequences from animating until there are no - // running animations that affect any of these properties. - ScheduleAnimation(new LayerAnimationSequence( - LayerAnimationElement::CreatePauseElement(animated_properties, - base::TimeDelta()))); - - bool wait_for_group_start = false; - for (iter = animations.begin(); iter != animations.end(); ++iter) - wait_for_group_start |= (*iter)->IsFirstElementThreaded(); - - int group_id = cc::AnimationIdProvider::NextGroupId(); - - // These animations (provided they don't animate any common properties) will - // now animate together if trivially scheduled. - for (iter = animations.begin(); iter != animations.end(); ++iter) { - (*iter)->set_animation_group_id(group_id); - (*iter)->set_waiting_for_group_start(wait_for_group_start); - ScheduleAnimation(*iter); - } - - UpdateAnimationState(); -} - -void LayerAnimator::SchedulePauseForProperties( - base::TimeDelta duration, - LayerAnimationElement::AnimatableProperties properties_to_pause) { - ScheduleAnimation(new ui::LayerAnimationSequence( - ui::LayerAnimationElement::CreatePauseElement( - properties_to_pause, duration))); -} - -bool LayerAnimator::IsAnimatingProperty( - LayerAnimationElement::AnimatableProperty property) const { - for (AnimationQueue::const_iterator queue_iter = animation_queue_.begin(); - queue_iter != animation_queue_.end(); ++queue_iter) { - if ((*queue_iter)->properties() & property) - return true; - } - return false; -} - -void LayerAnimator::StopAnimatingProperty( - LayerAnimationElement::AnimatableProperty property) { - scoped_refptr<LayerAnimator> retain(this); - while (true) { - // GetRunningAnimation purges deleted animations before searching, so we are - // guaranteed to find a live animation if any is returned at all. - RunningAnimation* running = GetRunningAnimation(property); - if (!running) - break; - // As was mentioned above, this sequence must be alive. - DCHECK(running->is_sequence_alive()); - FinishAnimation(running->sequence(), false); - } -} - -void LayerAnimator::AddObserver(LayerAnimationObserver* observer) { - if (!observers_.HasObserver(observer)) - observers_.AddObserver(observer); -} - -void LayerAnimator::RemoveObserver(LayerAnimationObserver* observer) { - observers_.RemoveObserver(observer); - // Remove the observer from all sequences as well. - for (AnimationQueue::iterator queue_iter = animation_queue_.begin(); - queue_iter != animation_queue_.end(); ++queue_iter) { - (*queue_iter)->RemoveObserver(observer); - } -} - -void LayerAnimator::OnThreadedAnimationStarted( - const cc::AnimationEvent& event) { - LayerAnimationElement::AnimatableProperty property = - LayerAnimationElement::ToAnimatableProperty(event.target_property); - - RunningAnimation* running = GetRunningAnimation(property); - if (!running) - return; - DCHECK(running->is_sequence_alive()); - - if (running->sequence()->animation_group_id() != event.group_id) - return; - - running->sequence()->OnThreadedAnimationStarted(event); - if (!running->sequence()->waiting_for_group_start()) - return; - - base::TimeTicks start_time = event.monotonic_time; - - running->sequence()->set_waiting_for_group_start(false); - - // The call to GetRunningAnimation made above already purged deleted - // animations, so we are guaranteed that all the animations we iterate - // over now are alive. - for (RunningAnimations::iterator iter = running_animations_.begin(); - iter != running_animations_.end(); ++iter) { - // Ensure that each sequence is only Started once, regardless of the - // number of sequences in the group that have threaded first elements. - if (((*iter).sequence()->animation_group_id() == event.group_id) && - !(*iter).sequence()->IsFirstElementThreaded() && - (*iter).sequence()->waiting_for_group_start()) { - (*iter).sequence()->set_start_time(start_time); - (*iter).sequence()->set_waiting_for_group_start(false); - (*iter).sequence()->Start(delegate()); - } - } -} - -void LayerAnimator::AddToCollection(LayerAnimatorCollection* collection) { - if (is_animating() && !is_started_) { - collection->StartAnimator(this); - is_started_ = true; - } -} - -void LayerAnimator::RemoveFromCollection(LayerAnimatorCollection* collection) { - if (is_animating() && is_started_) { - collection->StopAnimator(this); - is_started_ = false; - } -} - -// LayerAnimator protected ----------------------------------------------------- - -void LayerAnimator::ProgressAnimation(LayerAnimationSequence* sequence, - base::TimeTicks now) { - if (!delegate() || sequence->waiting_for_group_start()) - return; - - sequence->Progress(now, delegate()); -} - -void LayerAnimator::ProgressAnimationToEnd(LayerAnimationSequence* sequence) { - if (!delegate()) - return; - - sequence->ProgressToEnd(delegate()); -} - -bool LayerAnimator::HasAnimation(LayerAnimationSequence* sequence) const { - for (AnimationQueue::const_iterator queue_iter = animation_queue_.begin(); - queue_iter != animation_queue_.end(); ++queue_iter) { - if ((*queue_iter).get() == sequence) - return true; - } - return false; -} - -// LayerAnimator private ------------------------------------------------------- - -void LayerAnimator::Step(base::TimeTicks now) { - TRACE_EVENT0("ui", "LayerAnimator::Step"); - scoped_refptr<LayerAnimator> retain(this); - - last_step_time_ = now; - - PurgeDeletedAnimations(); - - // We need to make a copy of the running animations because progressing them - // and finishing them may indirectly affect the collection of running - // animations. - RunningAnimations running_animations_copy = running_animations_; - for (size_t i = 0; i < running_animations_copy.size(); ++i) { - if (!SAFE_INVOKE_BOOL(HasAnimation, running_animations_copy[i])) - continue; - - if (running_animations_copy[i].sequence()->IsFinished(now)) { - SAFE_INVOKE_VOID(FinishAnimation, running_animations_copy[i], false); - } else { - SAFE_INVOKE_VOID(ProgressAnimation, running_animations_copy[i], now); - } - } -} - -void LayerAnimator::StopAnimatingInternal(bool abort) { - scoped_refptr<LayerAnimator> retain(this); - while (is_animating()) { - // We're going to attempt to finish the first running animation. Let's - // ensure that it's valid. - PurgeDeletedAnimations(); - - // If we've purged all running animations, attempt to start one up. - if (running_animations_.empty()) - ProcessQueue(); - - DCHECK(!running_animations_.empty()); - - // Still no luck, let's just bail and clear all animations. - if (running_animations_.empty()) { - ClearAnimationsInternal(); - break; - } - - SAFE_INVOKE_VOID(FinishAnimation, running_animations_[0], abort); - } -} - -void LayerAnimator::UpdateAnimationState() { - if (disable_timer_for_test_) - return; - - const bool should_start = is_animating(); - LayerAnimatorCollection* collection = GetLayerAnimatorCollection(); - if (collection) { - if (should_start && !is_started_) - collection->StartAnimator(this); - else if (!should_start && is_started_) - collection->StopAnimator(this); - is_started_ = should_start; - } else { - is_started_ = false; - } -} - -LayerAnimationSequence* LayerAnimator::RemoveAnimation( - LayerAnimationSequence* sequence) { - linked_ptr<LayerAnimationSequence> to_return; - - bool is_running = false; - - // First remove from running animations - for (RunningAnimations::iterator iter = running_animations_.begin(); - iter != running_animations_.end(); ++iter) { - if ((*iter).sequence() == sequence) { - running_animations_.erase(iter); - is_running = true; - break; - } - } - - // Then remove from the queue - for (AnimationQueue::iterator queue_iter = animation_queue_.begin(); - queue_iter != animation_queue_.end(); ++queue_iter) { - if ((*queue_iter) == sequence) { - to_return = *queue_iter; - animation_queue_.erase(queue_iter); - break; - } - } - - if (!to_return.get() || - !to_return->waiting_for_group_start() || - !to_return->IsFirstElementThreaded()) - return to_return.release(); - - // The removed sequence may have been responsible for making other sequences - // wait for a group start. If no other sequences in the group have a - // threaded first element, the group no longer needs the additional wait. - bool is_wait_still_needed = false; - int group_id = to_return->animation_group_id(); - for (AnimationQueue::iterator queue_iter = animation_queue_.begin(); - queue_iter != animation_queue_.end(); ++queue_iter) { - if (((*queue_iter)->animation_group_id() == group_id) && - (*queue_iter)->IsFirstElementThreaded()) { - is_wait_still_needed = true; - break; - } - } - - if (is_wait_still_needed) - return to_return.release(); - - for (AnimationQueue::iterator queue_iter = animation_queue_.begin(); - queue_iter != animation_queue_.end(); ++queue_iter) { - if ((*queue_iter)->animation_group_id() == group_id && - (*queue_iter)->waiting_for_group_start()) { - (*queue_iter)->set_waiting_for_group_start(false); - if (is_running) { - (*queue_iter)->set_start_time(last_step_time_); - (*queue_iter)->Start(delegate()); - } - } - } - return to_return.release(); -} - -void LayerAnimator::FinishAnimation( - LayerAnimationSequence* sequence, bool abort) { - scoped_refptr<LayerAnimator> retain(this); - scoped_ptr<LayerAnimationSequence> removed(RemoveAnimation(sequence)); - if (abort) - sequence->Abort(delegate()); - else - ProgressAnimationToEnd(sequence); - ProcessQueue(); - UpdateAnimationState(); -} - -void LayerAnimator::FinishAnyAnimationWithZeroDuration() { - scoped_refptr<LayerAnimator> retain(this); - // Special case: if we've started a 0 duration animation, just finish it now - // and get rid of it. We need to make a copy because Progress may indirectly - // cause new animations to start running. - RunningAnimations running_animations_copy = running_animations_; - for (size_t i = 0; i < running_animations_copy.size(); ++i) { - if (!SAFE_INVOKE_BOOL(HasAnimation, running_animations_copy[i])) - continue; - - if (running_animations_copy[i].sequence()->IsFinished( - running_animations_copy[i].sequence()->start_time())) { - SAFE_INVOKE_VOID(ProgressAnimationToEnd, running_animations_copy[i]); - scoped_ptr<LayerAnimationSequence> removed( - SAFE_INVOKE_PTR(RemoveAnimation, running_animations_copy[i])); - } - } - ProcessQueue(); - UpdateAnimationState(); -} - -void LayerAnimator::ClearAnimations() { - scoped_refptr<LayerAnimator> retain(this); - ClearAnimationsInternal(); -} - -LayerAnimator::RunningAnimation* LayerAnimator::GetRunningAnimation( - LayerAnimationElement::AnimatableProperty property) { - PurgeDeletedAnimations(); - for (RunningAnimations::iterator iter = running_animations_.begin(); - iter != running_animations_.end(); ++iter) { - if ((*iter).sequence()->properties() & property) - return &(*iter); - } - return NULL; -} - -void LayerAnimator::AddToQueueIfNotPresent(LayerAnimationSequence* animation) { - // If we don't have the animation in the queue yet, add it. - bool found_sequence = false; - for (AnimationQueue::iterator queue_iter = animation_queue_.begin(); - queue_iter != animation_queue_.end(); ++queue_iter) { - if ((*queue_iter) == animation) { - found_sequence = true; - break; - } - } - - if (!found_sequence) - animation_queue_.push_front(make_linked_ptr(animation)); -} - -void LayerAnimator::RemoveAllAnimationsWithACommonProperty( - LayerAnimationSequence* sequence, bool abort) { - // For all the running animations, if they animate the same property, - // progress them to the end and remove them. Note, Aborting or Progressing - // animations may affect the collection of running animations, so we need to - // operate on a copy. - RunningAnimations running_animations_copy = running_animations_; - for (size_t i = 0; i < running_animations_copy.size(); ++i) { - if (!SAFE_INVOKE_BOOL(HasAnimation, running_animations_copy[i])) - continue; - - if (running_animations_copy[i].sequence()->HasConflictingProperty( - sequence->properties())) { - scoped_ptr<LayerAnimationSequence> removed( - SAFE_INVOKE_PTR(RemoveAnimation, running_animations_copy[i])); - if (abort) - running_animations_copy[i].sequence()->Abort(delegate()); - else - SAFE_INVOKE_VOID(ProgressAnimationToEnd, running_animations_copy[i]); - } - } - - // Same for the queued animations that haven't been started. Again, we'll - // need to operate on a copy. - std::vector<base::WeakPtr<LayerAnimationSequence> > sequences; - for (AnimationQueue::iterator queue_iter = animation_queue_.begin(); - queue_iter != animation_queue_.end(); ++queue_iter) - sequences.push_back((*queue_iter)->AsWeakPtr()); - - for (size_t i = 0; i < sequences.size(); ++i) { - if (!sequences[i].get() || !HasAnimation(sequences[i].get())) - continue; - - if (sequences[i]->HasConflictingProperty(sequence->properties())) { - scoped_ptr<LayerAnimationSequence> removed( - RemoveAnimation(sequences[i].get())); - if (abort) - sequences[i]->Abort(delegate()); - else - ProgressAnimationToEnd(sequences[i].get()); - } - } -} - -void LayerAnimator::ImmediatelySetNewTarget(LayerAnimationSequence* sequence) { - // Need to detect if our sequence gets destroyed. - base::WeakPtr<LayerAnimationSequence> weak_sequence_ptr = - sequence->AsWeakPtr(); - - const bool abort = false; - RemoveAllAnimationsWithACommonProperty(sequence, abort); - if (!weak_sequence_ptr.get()) - return; - - LayerAnimationSequence* removed = RemoveAnimation(sequence); - DCHECK(removed == NULL || removed == sequence); - if (!weak_sequence_ptr.get()) - return; - - ProgressAnimationToEnd(sequence); - if (!weak_sequence_ptr.get()) - return; - - delete sequence; -} - -void LayerAnimator::ImmediatelyAnimateToNewTarget( - LayerAnimationSequence* sequence) { - // Need to detect if our sequence gets destroyed. - base::WeakPtr<LayerAnimationSequence> weak_sequence_ptr = - sequence->AsWeakPtr(); - - const bool abort = true; - RemoveAllAnimationsWithACommonProperty(sequence, abort); - if (!weak_sequence_ptr.get()) - return; - - AddToQueueIfNotPresent(sequence); - if (!weak_sequence_ptr.get()) - return; - - StartSequenceImmediately(sequence); -} - -void LayerAnimator::EnqueueNewAnimation(LayerAnimationSequence* sequence) { - // It is assumed that if there was no conflicting animation, we would - // not have been called. No need to check for a collision; just - // add to the queue. - animation_queue_.push_back(make_linked_ptr(sequence)); - ProcessQueue(); -} - -void LayerAnimator::ReplaceQueuedAnimations(LayerAnimationSequence* sequence) { - // Need to detect if our sequence gets destroyed. - base::WeakPtr<LayerAnimationSequence> weak_sequence_ptr = - sequence->AsWeakPtr(); - - // Remove all animations that aren't running. Note: at each iteration i is - // incremented or an element is removed from the queue, so - // animation_queue_.size() - i is always decreasing and we are always making - // progress towards the loop terminating. - for (size_t i = 0; i < animation_queue_.size();) { - if (!weak_sequence_ptr.get()) - break; - - PurgeDeletedAnimations(); - - bool is_running = false; - for (RunningAnimations::const_iterator iter = running_animations_.begin(); - iter != running_animations_.end(); ++iter) { - if ((*iter).sequence() == animation_queue_[i].get()) { - is_running = true; - break; - } - } - - if (!is_running) - delete RemoveAnimation(animation_queue_[i].get()); - else - ++i; - } - animation_queue_.push_back(make_linked_ptr(sequence)); - ProcessQueue(); -} - -void LayerAnimator::ProcessQueue() { - bool started_sequence = false; - do { - started_sequence = false; - // Build a list of all currently animated properties. - LayerAnimationElement::AnimatableProperties animated = - LayerAnimationElement::UNKNOWN; - for (RunningAnimations::const_iterator iter = running_animations_.begin(); - iter != running_animations_.end(); ++iter) { - if (!(*iter).is_sequence_alive()) - continue; - - animated |= (*iter).sequence()->properties(); - } - - // Try to find an animation that doesn't conflict with an animated - // property or a property that will be animated before it. Note: starting - // the animation may indirectly cause more animations to be started, so we - // need to operate on a copy. - std::vector<base::WeakPtr<LayerAnimationSequence> > sequences; - for (AnimationQueue::iterator queue_iter = animation_queue_.begin(); - queue_iter != animation_queue_.end(); ++queue_iter) - sequences.push_back((*queue_iter)->AsWeakPtr()); - - for (size_t i = 0; i < sequences.size(); ++i) { - if (!sequences[i].get() || !HasAnimation(sequences[i].get())) - continue; - - if (!sequences[i]->HasConflictingProperty(animated)) { - StartSequenceImmediately(sequences[i].get()); - started_sequence = true; - break; - } - - // Animation couldn't be started. Add its properties to the collection so - // that we don't start a conflicting animation. For example, if our queue - // has the elements { {T,B}, {B} } (that is, an element that animates both - // the transform and the bounds followed by an element that animates the - // bounds), and we're currently animating the transform, we can't start - // the first element because it animates the transform, too. We cannot - // start the second element, either, because the first element animates - // bounds too, and needs to go first. - animated |= sequences[i]->properties(); - } - - // If we started a sequence, try again. We may be able to start several. - } while (started_sequence); -} - -bool LayerAnimator::StartSequenceImmediately(LayerAnimationSequence* sequence) { - PurgeDeletedAnimations(); - - // Ensure that no one is animating one of the sequence's properties already. - for (RunningAnimations::const_iterator iter = running_animations_.begin(); - iter != running_animations_.end(); ++iter) { - if ((*iter).sequence()->HasConflictingProperty(sequence->properties())) - return false; - } - - // All clear, actually start the sequence. Note: base::TimeTicks::Now has - // a resolution that can be as bad as 15ms. If this causes glitches in the - // animations, this can be switched to HighResNow() (animation uses Now() - // internally). - // All LayerAnimators share the same LayerAnimatorCollection. Use the - // last_tick_time() from there to ensure animations started during the same - // event complete at the same time. - base::TimeTicks start_time; - LayerAnimatorCollection* collection = GetLayerAnimatorCollection(); - if (is_animating() || adding_animations_) - start_time = last_step_time_; - else if (collection && collection->HasActiveAnimators()) - start_time = collection->last_tick_time(); - else - start_time = gfx::FrameTime::Now(); - - if (!sequence->animation_group_id()) - sequence->set_animation_group_id(cc::AnimationIdProvider::NextGroupId()); - if (!sequence->waiting_for_group_start() || - sequence->IsFirstElementThreaded()) { - sequence->set_start_time(start_time); - sequence->Start(delegate()); - } - running_animations_.push_back( - RunningAnimation(sequence->AsWeakPtr())); - - // Need to keep a reference to the animation. - AddToQueueIfNotPresent(sequence); - - // Ensure that animations get stepped at their start time. - Step(start_time); - - return true; -} - -void LayerAnimator::GetTargetValue( - LayerAnimationElement::TargetValue* target) const { - for (AnimationQueue::const_iterator iter = animation_queue_.begin(); - iter != animation_queue_.end(); ++iter) { - (*iter)->GetTargetValue(target); - } -} - -void LayerAnimator::OnScheduled(LayerAnimationSequence* sequence) { - if (observers_.might_have_observers()) { - ObserverListBase<LayerAnimationObserver>::Iterator it(observers_); - LayerAnimationObserver* obs; - while ((obs = it.GetNext()) != NULL) { - sequence->AddObserver(obs); - } - } - sequence->OnScheduled(); -} - -void LayerAnimator::SetTransitionDuration(base::TimeDelta duration) { - if (is_transition_duration_locked_) - return; - transition_duration_ = duration; -} - -void LayerAnimator::ClearAnimationsInternal() { - PurgeDeletedAnimations(); - - // Abort should never affect the set of running animations, but just in case - // clients are badly behaved, we will use a copy of the running animations. - RunningAnimations running_animations_copy = running_animations_; - for (size_t i = 0; i < running_animations_copy.size(); ++i) { - if (!SAFE_INVOKE_BOOL(HasAnimation, running_animations_copy[i])) - continue; - - scoped_ptr<LayerAnimationSequence> removed( - RemoveAnimation(running_animations_copy[i].sequence())); - if (removed.get()) - removed->Abort(delegate()); - } - // This *should* have cleared the list of running animations. - DCHECK(running_animations_.empty()); - running_animations_.clear(); - animation_queue_.clear(); - UpdateAnimationState(); -} - -void LayerAnimator::PurgeDeletedAnimations() { - for (size_t i = 0; i < running_animations_.size();) { - if (!running_animations_[i].is_sequence_alive()) - running_animations_.erase(running_animations_.begin() + i); - else - i++; - } -} - -LayerAnimatorCollection* LayerAnimator::GetLayerAnimatorCollection() { - return delegate_ ? delegate_->GetLayerAnimatorCollection() : NULL; -} - -LayerAnimator::RunningAnimation::RunningAnimation( - const base::WeakPtr<LayerAnimationSequence>& sequence) - : sequence_(sequence) { -} - -LayerAnimator::RunningAnimation::~RunningAnimation() { } - -} // namespace ui
diff --git a/ui/compositor/layer_animator.h b/ui/compositor/layer_animator.h deleted file mode 100644 index 69744f8..0000000 --- a/ui/compositor/layer_animator.h +++ /dev/null
@@ -1,359 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_LAYER_ANIMATOR_H_ -#define UI_COMPOSITOR_LAYER_ANIMATOR_H_ - -#include <deque> -#include <vector> - -#include "base/compiler_specific.h" -#include "base/gtest_prod_util.h" -#include "base/memory/linked_ptr.h" -#include "base/memory/ref_counted.h" -#include "base/observer_list.h" -#include "base/time/time.h" -#include "ui/compositor/compositor_export.h" -#include "ui/compositor/layer_animation_element.h" -#include "ui/gfx/animation/tween.h" - -namespace gfx { -class Animation; -class Rect; -class Transform; -} - -namespace ui { -class Layer; -class LayerAnimationSequence; -class LayerAnimationDelegate; -class LayerAnimationObserver; -class LayerAnimatorCollection; -class ScopedLayerAnimationSettings; - -// When a property of layer needs to be changed it is set by way of -// LayerAnimator. This enables LayerAnimator to animate property changes. -// NB: during many tests, set_disable_animations_for_test is used and causes -// all animations to complete immediately. The layer animation is ref counted -// so that if its owning layer is deleted (and the owning layer is only other -// class that should ever hold a ref ptr to a LayerAnimator), the animator can -// ensure that it is not disposed of until it finishes executing. It does this -// by holding a reference to itself for the duration of methods for which it -// must guarantee that |this| is valid. -class COMPOSITOR_EXPORT LayerAnimator : public base::RefCounted<LayerAnimator> { - public: - enum PreemptionStrategy { - IMMEDIATELY_SET_NEW_TARGET, - IMMEDIATELY_ANIMATE_TO_NEW_TARGET, - ENQUEUE_NEW_ANIMATION, - REPLACE_QUEUED_ANIMATIONS, - BLEND_WITH_CURRENT_ANIMATION - }; - - explicit LayerAnimator(base::TimeDelta transition_duration); - - // No implicit animations when properties are set. - static LayerAnimator* CreateDefaultAnimator(); - - // Implicitly animates when properties are set. - static LayerAnimator* CreateImplicitAnimator(); - - // Sets the transform on the delegate. May cause an implicit animation. - virtual void SetTransform(const gfx::Transform& transform); - gfx::Transform GetTargetTransform() const; - - // Sets the bounds on the delegate. May cause an implicit animation. - virtual void SetBounds(const gfx::Rect& bounds); - gfx::Rect GetTargetBounds() const; - - // Sets the opacity on the delegate. May cause an implicit animation. - virtual void SetOpacity(float opacity); - float GetTargetOpacity() const; - - // Sets the visibility of the delegate. May cause an implicit animation. - virtual void SetVisibility(bool visibility); - bool GetTargetVisibility() const; - - // Sets the brightness on the delegate. May cause an implicit animation. - virtual void SetBrightness(float brightness); - float GetTargetBrightness() const; - - // Sets the grayscale on the delegate. May cause an implicit animation. - virtual void SetGrayscale(float grayscale); - float GetTargetGrayscale() const; - - // Sets the color on the delegate. May cause an implicit animation. - virtual void SetColor(SkColor color); - SkColor GetTargetColor() const; - - // Returns the default length of animations, including adjustment for slow - // animation mode if set. - base::TimeDelta GetTransitionDuration() const; - - // Sets the layer animation delegate the animator is associated with. The - // animator does not own the delegate. The layer animator expects a non-NULL - // delegate for most of its operations, so do not call any methods without - // a valid delegate installed. - void SetDelegate(LayerAnimationDelegate* delegate); - - // Sets the animation preemption strategy. This determines the behaviour if - // a property is set during an animation. The default is - // IMMEDIATELY_SET_NEW_TARGET (see ImmediatelySetNewTarget below). - void set_preemption_strategy(PreemptionStrategy strategy) { - preemption_strategy_ = strategy; - } - - PreemptionStrategy preemption_strategy() const { - return preemption_strategy_; - } - - // Start an animation sequence. If an animation for the same property is in - // progress, it needs to be interrupted with the new animation. The animator - // takes ownership of this animation sequence. - void StartAnimation(LayerAnimationSequence* animation); - - // Schedule an animation to be run when possible. The animator takes ownership - // of this animation sequence. - void ScheduleAnimation(LayerAnimationSequence* animation); - - // Starts the animations to be run together, ensuring that the first elements - // in these sequences have the same effective start time even when some of - // them start on the compositor thread (but there is no such guarantee for - // the effective start time of subsequent elements). Obviously will not work - // if they animate any common properties. The animator takes ownership of the - // animation sequences. Takes PreemptionStrategy into account. - void StartTogether(const std::vector<LayerAnimationSequence*>& animations); - - // Schedules the animations to be run together, ensuring that the first - // elements in these sequences have the same effective start time even when - // some of them start on the compositor thread (but there is no such guarantee - // for the effective start time of subsequent elements). Obviously will not - // work if they animate any common properties. The animator takes ownership - // of the animation sequences. - void ScheduleTogether(const std::vector<LayerAnimationSequence*>& animations); - - // Schedules a pause for length |duration| of all the specified properties. - // End the list with -1. - void SchedulePauseForProperties( - base::TimeDelta duration, - LayerAnimationElement::AnimatableProperties properties_to_pause); - - // Returns true if there is an animation in the queue (animations remain in - // the queue until they complete, so this includes running animations). - bool is_animating() const { return !animation_queue_.empty(); } - - // Returns true if there is an animation in the queue that animates the given - // property (animations remain in the queue until they complete, so this - // includes running animations). - bool IsAnimatingProperty( - LayerAnimationElement::AnimatableProperty property) const; - - // Stops animating the given property. No effect if there is no running - // animation for the given property. Skips to the final state of the - // animation. - void StopAnimatingProperty( - LayerAnimationElement::AnimatableProperty property); - - // Stops all animation and clears any queued animations. This call progresses - // animations to their end points and notifies all observers. - void StopAnimating() { StopAnimatingInternal(false); } - - // This is similar to StopAnimating, but aborts rather than finishes the - // animations and notifies all observers. - void AbortAllAnimations() { StopAnimatingInternal(true); } - - // These functions are used for adding or removing observers from the observer - // list. The observers are notified when animations end. - void AddObserver(LayerAnimationObserver* observer); - void RemoveObserver(LayerAnimationObserver* observer); - - // Called when a threaded animation is actually started. - void OnThreadedAnimationStarted(const cc::AnimationEvent& event); - - // This determines how implicit animations will be tweened. This has no - // effect on animations that are explicitly started or scheduled. The default - // is Tween::LINEAR. - void set_tween_type(gfx::Tween::Type tween_type) { tween_type_ = tween_type; } - gfx::Tween::Type tween_type() const { return tween_type_; } - - // For testing purposes only. - void set_disable_timer_for_test(bool disable_timer) { - disable_timer_for_test_ = disable_timer; - } - - void set_last_step_time(base::TimeTicks time) { - last_step_time_ = time; - } - base::TimeTicks last_step_time() const { return last_step_time_; } - - void Step(base::TimeTicks time_now); - - void AddToCollection(LayerAnimatorCollection* collection); - void RemoveFromCollection(LayerAnimatorCollection* collection); - - protected: - virtual ~LayerAnimator(); - - LayerAnimationDelegate* delegate() { return delegate_; } - const LayerAnimationDelegate* delegate() const { return delegate_; } - - // Virtual for testing. - virtual void ProgressAnimation(LayerAnimationSequence* sequence, - base::TimeTicks now); - - void ProgressAnimationToEnd(LayerAnimationSequence* sequence); - - // Returns true if the sequence is owned by this animator. - bool HasAnimation(LayerAnimationSequence* sequence) const; - - private: - friend class base::RefCounted<LayerAnimator>; - friend class ScopedLayerAnimationSettings; - friend class LayerAnimatorTestController; - FRIEND_TEST_ALL_PREFIXES(LayerAnimatorTest, AnimatorStartedCorrectly); - FRIEND_TEST_ALL_PREFIXES(LayerAnimatorTest, - AnimatorRemovedFromCollectionWhenLayerIsDestroyed); - - class RunningAnimation { - public: - RunningAnimation(const base::WeakPtr<LayerAnimationSequence>& sequence); - ~RunningAnimation(); - - bool is_sequence_alive() const { return !!sequence_.get(); } - LayerAnimationSequence* sequence() const { return sequence_.get(); } - - private: - base::WeakPtr<LayerAnimationSequence> sequence_; - - // Copy and assign are allowed. - }; - - typedef std::vector<RunningAnimation> RunningAnimations; - typedef std::deque<linked_ptr<LayerAnimationSequence> > AnimationQueue; - - // Finishes all animations by either advancing them to their final state or by - // aborting them. - void StopAnimatingInternal(bool abort); - - // Starts or stops stepping depending on whether thare are running animations. - void UpdateAnimationState(); - - // Removes the sequences from both the running animations and the queue. - // Returns a pointer to the removed animation, if any. NOTE: the caller is - // responsible for deleting the returned pointer. - LayerAnimationSequence* RemoveAnimation( - LayerAnimationSequence* sequence) WARN_UNUSED_RESULT; - - // Progresses to the end of the sequence before removing it. - void FinishAnimation(LayerAnimationSequence* sequence, bool abort); - - // Finishes any running animation with zero duration. - void FinishAnyAnimationWithZeroDuration(); - - // Clears the running animations and the queue. No sequences are progressed. - void ClearAnimations(); - - // Returns the running animation animating the given property, if any. - RunningAnimation* GetRunningAnimation( - LayerAnimationElement::AnimatableProperty property); - - // Checks if the sequence has already been added to the queue and adds it - // to the front if note. - void AddToQueueIfNotPresent(LayerAnimationSequence* sequence); - - // Any running or queued animation that affects a property in common with - // |sequence| is either finished or aborted depending on |abort|. - void RemoveAllAnimationsWithACommonProperty(LayerAnimationSequence* sequence, - bool abort); - - // Preempts a running animation by progressing both the running animation and - // the given sequence to the end. - void ImmediatelySetNewTarget(LayerAnimationSequence* sequence); - - // Preempts by aborting the running animation, and starts the given animation. - void ImmediatelyAnimateToNewTarget(LayerAnimationSequence* sequence); - - // Preempts by adding the new animation to the queue. - void EnqueueNewAnimation(LayerAnimationSequence* sequence); - - // Preempts by wiping out any unstarted animation in the queue and then - // enqueuing this animation. - void ReplaceQueuedAnimations(LayerAnimationSequence* sequence); - - // If there's an animation in the queue that doesn't animate the same property - // as a running animation, or an animation schedule to run before it, start it - // up. Repeat until there are no such animations. - void ProcessQueue(); - - // Attempts to add the sequence to the list of running animations. Returns - // false if there is an animation running that already animates one of the - // properties affected by |sequence|. - bool StartSequenceImmediately(LayerAnimationSequence* sequence); - - // Sets the value of target as if all the running and queued animations were - // allowed to finish. - void GetTargetValue(LayerAnimationElement::TargetValue* target) const; - - // Called whenever an animation is added to the animation queue. Either by - // starting the animation or adding to the queue. - void OnScheduled(LayerAnimationSequence* sequence); - - // Sets |transition_duration_| unless |is_transition_duration_locked_| is set. - void SetTransitionDuration(base::TimeDelta duration); - - // Clears the animation queues and notifies any running animations that they - // have been aborted. - void ClearAnimationsInternal(); - - // Cleans up any running animations that may have been deleted. - void PurgeDeletedAnimations(); - - LayerAnimatorCollection* GetLayerAnimatorCollection(); - - // This is the queue of animations to run. - AnimationQueue animation_queue_; - - // The target of all layer animations. - LayerAnimationDelegate* delegate_; - - // The currently running animations. - RunningAnimations running_animations_; - - // Determines how animations are replaced. - PreemptionStrategy preemption_strategy_; - - // Whether the length of animations is locked. While it is locked - // SetTransitionDuration does not set |transition_duration_|. - bool is_transition_duration_locked_; - - // The default length of animations. - base::TimeDelta transition_duration_; - - // The default tween type for implicit transitions - gfx::Tween::Type tween_type_; - - // Used for coordinating the starting of animations. - base::TimeTicks last_step_time_; - - // True if we are being stepped by our container. - bool is_started_; - - // This prevents the animator from automatically stepping through animations - // and allows for manual stepping. - bool disable_timer_for_test_; - - // Prevents timer adjustments in case when we start multiple animations - // with preemption strategies that discard previous animations. - bool adding_animations_; - - // Observers are notified when layer animations end, are scheduled or are - // aborted. - ObserverList<LayerAnimationObserver> observers_; - - DISALLOW_COPY_AND_ASSIGN(LayerAnimator); -}; - -} // namespace ui - -#endif // UI_COMPOSITOR_LAYER_ANIMATOR_H_
diff --git a/ui/compositor/layer_animator_collection.cc b/ui/compositor/layer_animator_collection.cc deleted file mode 100644 index babdcb6..0000000 --- a/ui/compositor/layer_animator_collection.cc +++ /dev/null
@@ -1,61 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/compositor/layer_animator_collection.h" - -#include <set> - -#include "base/time/time.h" -#include "ui/compositor/compositor.h" -#include "ui/compositor/layer_animator.h" -#include "ui/gfx/frame_time.h" - -namespace ui { - -LayerAnimatorCollection::LayerAnimatorCollection(Compositor* compositor) - : compositor_(compositor), last_tick_time_(gfx::FrameTime::Now()) { -} - -LayerAnimatorCollection::~LayerAnimatorCollection() { - if (compositor_ && compositor_->HasAnimationObserver(this)) - compositor_->RemoveAnimationObserver(this); -} - -void LayerAnimatorCollection::StartAnimator( - scoped_refptr<LayerAnimator> animator) { - DCHECK_EQ(0U, animators_.count(animator)); - if (!animators_.size()) - last_tick_time_ = gfx::FrameTime::Now(); - animators_.insert(animator); - if (animators_.size() == 1U && compositor_) - compositor_->AddAnimationObserver(this); -} - -void LayerAnimatorCollection::StopAnimator( - scoped_refptr<LayerAnimator> animator) { - DCHECK_GT(animators_.count(animator), 0U); - animators_.erase(animator); - if (animators_.empty() && compositor_) - compositor_->RemoveAnimationObserver(this); -} - -bool LayerAnimatorCollection::HasActiveAnimators() const { - return !animators_.empty(); -} - -void LayerAnimatorCollection::OnAnimationStep(base::TimeTicks now) { - last_tick_time_ = now; - std::set<scoped_refptr<LayerAnimator> > list = animators_; - for (std::set<scoped_refptr<LayerAnimator> >::iterator iter = list.begin(); - iter != list.end(); - ++iter) { - // Make sure the animator is still valid. - if (animators_.count(*iter) > 0) - (*iter)->Step(now); - } - if (!HasActiveAnimators() && compositor_) - compositor_->RemoveAnimationObserver(this); -} - -} // namespace ui
diff --git a/ui/compositor/layer_animator_collection.h b/ui/compositor/layer_animator_collection.h deleted file mode 100644 index 1e6ebeb..0000000 --- a/ui/compositor/layer_animator_collection.h +++ /dev/null
@@ -1,49 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_LAYER_ANIMATOR_COLLECTION_H_ -#define UI_COMPOSITOR_LAYER_ANIMATOR_COLLECTION_H_ - -#include <set> - -#include "base/callback.h" -#include "base/memory/ref_counted.h" -#include "base/time/time.h" -#include "ui/compositor/compositor_animation_observer.h" -#include "ui/compositor/compositor_export.h" - -namespace ui { - -class Compositor; -class LayerAnimator; - -// A collection of LayerAnimators that should be updated at each animation step -// in the compositor. -class COMPOSITOR_EXPORT LayerAnimatorCollection - : public CompositorAnimationObserver { - public: - explicit LayerAnimatorCollection(Compositor* compositor); - ~LayerAnimatorCollection() override; - - void StartAnimator(scoped_refptr<LayerAnimator> animator); - void StopAnimator(scoped_refptr<LayerAnimator> animator); - - bool HasActiveAnimators() const; - - base::TimeTicks last_tick_time() const { return last_tick_time_; } - - // CompositorAnimationObserver: - void OnAnimationStep(base::TimeTicks timestamp) override; - - private: - Compositor* compositor_; - base::TimeTicks last_tick_time_; - std::set<scoped_refptr<LayerAnimator> > animators_; - - DISALLOW_COPY_AND_ASSIGN(LayerAnimatorCollection); -}; - -} // namespace ui - -#endif // UI_COMPOSITOR_LAYER_ANIMATOR_COLLECTION_H_
diff --git a/ui/compositor/layer_animator_unittest.cc b/ui/compositor/layer_animator_unittest.cc deleted file mode 100644 index ad4ff61..0000000 --- a/ui/compositor/layer_animator_unittest.cc +++ /dev/null
@@ -1,2623 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/compositor/layer_animator.h" - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "base/strings/stringprintf.h" -#include "base/time/time.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/compositor/layer.h" -#include "ui/compositor/layer_animation_delegate.h" -#include "ui/compositor/layer_animation_element.h" -#include "ui/compositor/layer_animation_sequence.h" -#include "ui/compositor/layer_animator_collection.h" -#include "ui/compositor/scoped_animation_duration_scale_mode.h" -#include "ui/compositor/scoped_layer_animation_settings.h" -#include "ui/compositor/test/context_factories_for_test.h" -#include "ui/compositor/test/layer_animator_test_controller.h" -#include "ui/compositor/test/test_compositor_host.h" -#include "ui/compositor/test/test_layer_animation_delegate.h" -#include "ui/compositor/test/test_layer_animation_observer.h" -#include "ui/compositor/test/test_utils.h" -#include "ui/gfx/frame_time.h" -#include "ui/gfx/rect.h" -#include "ui/gfx/transform.h" - -namespace ui { - -namespace { - -// Converts |color| to a string. Each component of the color is separated by a -// space and the order if A R G B. -std::string ColorToString(SkColor color) { - return base::StringPrintf("%d %d %d %d", SkColorGetA(color), - SkColorGetR(color), SkColorGetG(color), - SkColorGetB(color)); -} - -// Creates vector with two LayerAnimationSequences, based on |first| and -// |second| layer animation elements. -std::vector<LayerAnimationSequence*> CreateMultiSequence( - LayerAnimationElement* first, - LayerAnimationElement* second) { - LayerAnimationSequence* first_sequence = new LayerAnimationSequence(); - first_sequence->AddElement(first); - LayerAnimationSequence* second_sequence = new LayerAnimationSequence(); - second_sequence->AddElement(second); - - std::vector<ui::LayerAnimationSequence*> animations; - animations.push_back(first_sequence); - animations.push_back(second_sequence); - return animations; -} - -class TestImplicitAnimationObserver : public ImplicitAnimationObserver { - public: - explicit TestImplicitAnimationObserver(bool notify_when_animator_destructed) - : animations_completed_(false), - notify_when_animator_destructed_(notify_when_animator_destructed) { - } - - bool animations_completed() const { return animations_completed_; } - void set_animations_completed(bool completed) { - animations_completed_ = completed; - } - - bool WasAnimationAbortedForProperty( - LayerAnimationElement::AnimatableProperty property) const { - return ImplicitAnimationObserver::WasAnimationAbortedForProperty(property); - } - - bool WasAnimationCompletedForProperty( - LayerAnimationElement::AnimatableProperty property) const { - return ImplicitAnimationObserver::WasAnimationCompletedForProperty( - property); - } - - private: - // ImplicitAnimationObserver implementation - virtual void OnImplicitAnimationsCompleted() override { - animations_completed_ = true; - } - - virtual bool RequiresNotificationWhenAnimatorDestroyed() const override { - return notify_when_animator_destructed_; - } - - bool animations_completed_; - bool notify_when_animator_destructed_; - - DISALLOW_COPY_AND_ASSIGN(TestImplicitAnimationObserver); -}; - -// When notified that an animation has ended, stops all other animations. -class DeletingLayerAnimationObserver : public LayerAnimationObserver { - public: - DeletingLayerAnimationObserver(LayerAnimator* animator) - : animator_(animator) { - } - - virtual void OnLayerAnimationEnded( - LayerAnimationSequence* sequence) override { - animator_->StopAnimating(); - } - - virtual void OnLayerAnimationAborted( - LayerAnimationSequence* sequence) override { - animator_->StopAnimating(); - } - - virtual void OnLayerAnimationScheduled( - LayerAnimationSequence* sequence) override { - } - - private: - LayerAnimator* animator_; - - DISALLOW_COPY_AND_ASSIGN(DeletingLayerAnimationObserver); -}; - -class LayerAnimatorDestructionObserver { - public: - LayerAnimatorDestructionObserver() : animator_deleted_(false) {} - virtual ~LayerAnimatorDestructionObserver() {} - - void NotifyAnimatorDeleted() { - animator_deleted_ = true; - } - - bool IsAnimatorDeleted() { - return animator_deleted_; - } - - private: - bool animator_deleted_; - - DISALLOW_COPY_AND_ASSIGN(LayerAnimatorDestructionObserver); -}; - -class TestLayerAnimator : public LayerAnimator { - public: - TestLayerAnimator() : LayerAnimator(base::TimeDelta::FromSeconds(0)), - destruction_observer_(NULL) {} - - void SetDestructionObserver( - LayerAnimatorDestructionObserver* observer) { - destruction_observer_ = observer; - } - - protected: - virtual ~TestLayerAnimator() { - if (destruction_observer_) { - destruction_observer_->NotifyAnimatorDeleted(); - } - } - - virtual void ProgressAnimation(LayerAnimationSequence* sequence, - base::TimeTicks now) override { - EXPECT_TRUE(HasAnimation(sequence)); - LayerAnimator::ProgressAnimation(sequence, now); - } - - private: - LayerAnimatorDestructionObserver* destruction_observer_; - - DISALLOW_COPY_AND_ASSIGN(TestLayerAnimator); -}; - -// The test layer animation sequence updates a live instances count when it is -// created and destroyed. -class TestLayerAnimationSequence : public LayerAnimationSequence { - public: - TestLayerAnimationSequence(LayerAnimationElement* element, - int* num_live_instances) - : LayerAnimationSequence(element), - num_live_instances_(num_live_instances) { - (*num_live_instances_)++; - } - - virtual ~TestLayerAnimationSequence() { - (*num_live_instances_)--; - } - - private: - int* num_live_instances_; - - DISALLOW_COPY_AND_ASSIGN(TestLayerAnimationSequence); -}; - -} // namespace - -// Checks that setting a property on an implicit animator causes an animation to -// happen. -TEST(LayerAnimatorTest, ImplicitAnimation) { - scoped_refptr<LayerAnimator> animator( - LayerAnimator::CreateImplicitAnimator()); - animator->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - base::TimeTicks now = gfx::FrameTime::Now(); - animator->SetBrightness(0.5); - EXPECT_TRUE(animator->is_animating()); - animator->Step(now + base::TimeDelta::FromSeconds(1)); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), 0.5); -} - -// Checks that if the animator is a default animator, that implicit animations -// are not started. -TEST(LayerAnimatorTest, NoImplicitAnimation) { - scoped_refptr<LayerAnimator> animator(LayerAnimator::CreateDefaultAnimator()); - animator->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - animator->SetBrightness(0.5); - EXPECT_FALSE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), 0.5); -} - -// Checks that StopAnimatingProperty stops animation for that property, and also -// skips the stopped animation to the end. -TEST(LayerAnimatorTest, StopAnimatingProperty) { - scoped_refptr<LayerAnimator> animator( - LayerAnimator::CreateImplicitAnimator()); - animator->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - double target_opacity(0.5); - gfx::Rect target_bounds(0, 0, 50, 50); - animator->SetOpacity(target_opacity); - animator->SetBounds(target_bounds); - animator->StopAnimatingProperty(LayerAnimationElement::OPACITY); - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetOpacityForAnimation(), 0.5); - animator->StopAnimatingProperty(LayerAnimationElement::BOUNDS); - EXPECT_FALSE(animator->is_animating()); - CheckApproximatelyEqual(delegate.GetBoundsForAnimation(), target_bounds); -} - -// Checks that multiple running animation for separate properties can be stopped -// simultaneously and that all animations are advanced to their target values. -TEST(LayerAnimatorTest, StopAnimating) { - scoped_refptr<LayerAnimator> animator( - LayerAnimator::CreateImplicitAnimator()); - animator->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - double target_opacity(0.5); - gfx::Rect target_bounds(0, 0, 50, 50); - animator->SetOpacity(target_opacity); - animator->SetBounds(target_bounds); - EXPECT_TRUE(animator->is_animating()); - animator->StopAnimating(); - EXPECT_FALSE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetOpacityForAnimation(), 0.5); - CheckApproximatelyEqual(delegate.GetBoundsForAnimation(), target_bounds); -} - -// Checks that multiple running animation for separate properties can be stopped -// simultaneously and that all animations are advanced to their target values. -TEST(LayerAnimatorTest, AbortAllAnimations) { - scoped_refptr<LayerAnimator> animator( - LayerAnimator::CreateImplicitAnimator()); - animator->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - double initial_opacity(1.0); - gfx::Rect initial_bounds(0, 0, 10, 10); - delegate.SetOpacityFromAnimation(initial_opacity); - delegate.SetBoundsFromAnimation(initial_bounds); - animator->SetDelegate(&delegate); - double target_opacity(0.5); - gfx::Rect target_bounds(0, 0, 50, 50); - animator->SetOpacity(target_opacity); - animator->SetBounds(target_bounds); - EXPECT_TRUE(animator->is_animating()); - animator->AbortAllAnimations(); - EXPECT_FALSE(animator->is_animating()); - EXPECT_FLOAT_EQ(initial_opacity, delegate.GetOpacityForAnimation()); - CheckApproximatelyEqual(initial_bounds, delegate.GetBoundsForAnimation()); -} - -// Schedule a non-threaded animation that can run immediately. This is the -// trivial case and should result in the animation being started immediately. -TEST(LayerAnimatorTest, ScheduleAnimationThatCanRunImmediately) { - scoped_refptr<LayerAnimator> animator(LayerAnimator::CreateDefaultAnimator()); - animator->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - - double start_brightness(0.0); - double middle_brightness(0.5); - double target_brightness(1.0); - - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - - delegate.SetBrightnessFromAnimation(start_brightness); - - animator->ScheduleAnimation( - new LayerAnimationSequence( - LayerAnimationElement::CreateBrightnessElement(target_brightness, - delta))); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), start_brightness); - - base::TimeTicks start_time = animator->last_step_time(); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(500)); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), middle_brightness); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(1000)); - - EXPECT_FALSE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), target_brightness); -} - -// Schedule a threaded animation that can run immediately. -TEST(LayerAnimatorTest, ScheduleThreadedAnimationThatCanRunImmediately) { - double epsilon = 0.00001; - LayerAnimatorTestController test_controller( - LayerAnimator::CreateDefaultAnimator()); - LayerAnimator* animator = test_controller.animator(); - test_controller.animator()->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - test_controller.animator()->SetDelegate(&delegate); - - double start_opacity(0.0); - double target_opacity(1.0); - - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - - delegate.SetOpacityFromAnimation(start_opacity); - - test_controller.animator()->ScheduleAnimation( - new LayerAnimationSequence( - LayerAnimationElement::CreateOpacityElement(target_opacity, delta))); - - EXPECT_TRUE(test_controller.animator()->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetOpacityForAnimation(), start_opacity); - - base::TimeTicks start_time = test_controller.animator()->last_step_time(); - base::TimeTicks effective_start = start_time + delta; - - test_controller.animator()->OnThreadedAnimationStarted(cc::AnimationEvent( - cc::AnimationEvent::Started, - 0, - test_controller.GetRunningSequence(LayerAnimationElement::OPACITY) - ->animation_group_id(), - cc::Animation::Opacity, - effective_start)); - - animator->Step(effective_start + delta / 2); - - EXPECT_TRUE(test_controller.animator()->is_animating()); - EXPECT_NEAR( - 0.5, - test_controller.GetRunningSequence(LayerAnimationElement::OPACITY)-> - last_progressed_fraction(), - epsilon); - - animator->Step(effective_start + delta); - - EXPECT_FALSE(test_controller.animator()->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetOpacityForAnimation(), target_opacity); -} - -// Schedule two non-threaded animations on separate properties. Both animations -// should start immediately and should progress in lock step. -TEST(LayerAnimatorTest, ScheduleTwoAnimationsThatCanRunImmediately) { - scoped_refptr<LayerAnimator> animator(LayerAnimator::CreateDefaultAnimator()); - animator->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - - double start_brightness(0.0); - double middle_brightness(0.5); - double target_brightness(1.0); - - gfx::Rect start_bounds, target_bounds, middle_bounds; - start_bounds = target_bounds = middle_bounds = gfx::Rect(0, 0, 50, 50); - start_bounds.set_x(-90); - target_bounds.set_x(90); - - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - - delegate.SetBrightnessFromAnimation(start_brightness); - delegate.SetBoundsFromAnimation(start_bounds); - - animator->ScheduleAnimation( - new LayerAnimationSequence( - LayerAnimationElement::CreateBrightnessElement(target_brightness, - delta))); - - animator->ScheduleAnimation( - new LayerAnimationSequence( - LayerAnimationElement::CreateBoundsElement(target_bounds, delta))); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), start_brightness); - CheckApproximatelyEqual(delegate.GetBoundsForAnimation(), start_bounds); - - base::TimeTicks start_time = animator->last_step_time(); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(500)); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), middle_brightness); - CheckApproximatelyEqual(delegate.GetBoundsForAnimation(), middle_bounds); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(1000)); - - EXPECT_FALSE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), target_brightness); - CheckApproximatelyEqual(delegate.GetBoundsForAnimation(), target_bounds); -} - -// Schedule a threaded and a non-threaded animation on separate properties. Both -// animations should progress in lock step. -TEST(LayerAnimatorTest, ScheduleThreadedAndNonThreadedAnimations) { - double epsilon = 0.00001; - LayerAnimatorTestController test_controller( - LayerAnimator::CreateDefaultAnimator()); - LayerAnimator* animator = test_controller.animator(); - test_controller.animator()->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - test_controller.animator()->SetDelegate(&delegate); - - double start_opacity(0.0); - double target_opacity(1.0); - - gfx::Rect start_bounds, target_bounds, middle_bounds; - start_bounds = target_bounds = middle_bounds = gfx::Rect(0, 0, 50, 50); - start_bounds.set_x(-90); - target_bounds.set_x(90); - - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - - delegate.SetOpacityFromAnimation(start_opacity); - delegate.SetBoundsFromAnimation(start_bounds); - - std::vector<LayerAnimationSequence*> animations; - animations.push_back( - new LayerAnimationSequence( - LayerAnimationElement::CreateOpacityElement(target_opacity, delta))); - - animations.push_back( - new LayerAnimationSequence( - LayerAnimationElement::CreateBoundsElement(target_bounds, delta))); - - test_controller.animator()->ScheduleTogether(animations); - - EXPECT_TRUE(test_controller.animator()->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetOpacityForAnimation(), start_opacity); - CheckApproximatelyEqual(delegate.GetBoundsForAnimation(), start_bounds); - - base::TimeTicks start_time = test_controller.animator()->last_step_time(); - base::TimeTicks effective_start = start_time + delta; - - test_controller.animator()->OnThreadedAnimationStarted(cc::AnimationEvent( - cc::AnimationEvent::Started, - 0, - test_controller.GetRunningSequence(LayerAnimationElement::OPACITY) - ->animation_group_id(), - cc::Animation::Opacity, - effective_start)); - - animator->Step(effective_start + delta / 2); - - EXPECT_TRUE(test_controller.animator()->is_animating()); - EXPECT_NEAR( - 0.5, - test_controller.GetRunningSequence(LayerAnimationElement::OPACITY)-> - last_progressed_fraction(), - epsilon); - CheckApproximatelyEqual(delegate.GetBoundsForAnimation(), middle_bounds); - - animator->Step(effective_start + delta); - - EXPECT_FALSE(test_controller.animator()->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetOpacityForAnimation(), target_opacity); - CheckApproximatelyEqual(delegate.GetBoundsForAnimation(), target_bounds); -} - -// Schedule two animations on the same property. In this case, the two -// animations should run one after another. -TEST(LayerAnimatorTest, ScheduleTwoAnimationsOnSameProperty) { - scoped_refptr<LayerAnimator> animator(LayerAnimator::CreateDefaultAnimator()); - animator->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - - double start_brightness(0.0); - double middle_brightness(0.5); - double target_brightness(1.0); - - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - - delegate.SetBrightnessFromAnimation(start_brightness); - - animator->ScheduleAnimation( - new LayerAnimationSequence( - LayerAnimationElement::CreateBrightnessElement(target_brightness, - delta))); - - animator->ScheduleAnimation( - new LayerAnimationSequence( - LayerAnimationElement::CreateBrightnessElement(start_brightness, - delta))); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), start_brightness); - - base::TimeTicks start_time = animator->last_step_time(); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(500)); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), middle_brightness); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(1000)); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), target_brightness); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(1500)); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), middle_brightness); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(2000)); - - EXPECT_FALSE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), start_brightness); -} - -// Schedule [{g}, {g,b}, {b}] and ensure that {b} doesn't run right away. That -// is, ensure that all animations targetting a particular property are run in -// order. -TEST(LayerAnimatorTest, ScheduleBlockedAnimation) { - scoped_refptr<LayerAnimator> animator(LayerAnimator::CreateDefaultAnimator()); - animator->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - - double start_grayscale(0.0); - double middle_grayscale(0.5); - double target_grayscale(1.0); - - gfx::Rect start_bounds, target_bounds, middle_bounds; - start_bounds = target_bounds = middle_bounds = gfx::Rect(0, 0, 50, 50); - start_bounds.set_x(-90); - target_bounds.set_x(90); - - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - - delegate.SetGrayscaleFromAnimation(start_grayscale); - delegate.SetBoundsFromAnimation(start_bounds); - - animator->ScheduleAnimation( - new LayerAnimationSequence( - LayerAnimationElement::CreateGrayscaleElement(target_grayscale, - delta))); - - scoped_ptr<LayerAnimationSequence> bounds_and_grayscale( - new LayerAnimationSequence( - LayerAnimationElement::CreateGrayscaleElement(start_grayscale, - delta))); - - bounds_and_grayscale->AddElement( - LayerAnimationElement::CreateBoundsElement(target_bounds, delta)); - - animator->ScheduleAnimation(bounds_and_grayscale.release()); - - animator->ScheduleAnimation( - new LayerAnimationSequence( - LayerAnimationElement::CreateBoundsElement(start_bounds, delta))); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetGrayscaleForAnimation(), start_grayscale); - CheckApproximatelyEqual(delegate.GetBoundsForAnimation(), start_bounds); - - base::TimeTicks start_time = animator->last_step_time(); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(500)); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetGrayscaleForAnimation(), middle_grayscale); - CheckApproximatelyEqual(delegate.GetBoundsForAnimation(), start_bounds); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(1000)); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetGrayscaleForAnimation(), target_grayscale); - CheckApproximatelyEqual(delegate.GetBoundsForAnimation(), start_bounds); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(2000)); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetGrayscaleForAnimation(), start_grayscale); - CheckApproximatelyEqual(delegate.GetBoundsForAnimation(), start_bounds); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(3000)); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetGrayscaleForAnimation(), start_grayscale); - CheckApproximatelyEqual(delegate.GetBoundsForAnimation(), target_bounds); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(4000)); - - EXPECT_FALSE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetGrayscaleForAnimation(), start_grayscale); - CheckApproximatelyEqual(delegate.GetBoundsForAnimation(), start_bounds); -} - -// Schedule {g} and then schedule {g} and {b} together. In this case, since -// ScheduleTogether is being used, the bounds animation should not start until -// the second grayscale animation starts. -TEST(LayerAnimatorTest, ScheduleTogether) { - scoped_refptr<LayerAnimator> animator(LayerAnimator::CreateDefaultAnimator()); - animator->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - - double start_grayscale(0.0); - double target_grayscale(1.0); - - gfx::Rect start_bounds, target_bounds, middle_bounds; - start_bounds = target_bounds = gfx::Rect(0, 0, 50, 50); - start_bounds.set_x(-90); - target_bounds.set_x(90); - - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - - delegate.SetGrayscaleFromAnimation(start_grayscale); - delegate.SetBoundsFromAnimation(start_bounds); - - animator->ScheduleAnimation( - new LayerAnimationSequence( - LayerAnimationElement::CreateGrayscaleElement(target_grayscale, - delta))); - - std::vector<LayerAnimationSequence*> sequences; - sequences.push_back(new LayerAnimationSequence( - LayerAnimationElement::CreateGrayscaleElement(start_grayscale, delta))); - sequences.push_back(new LayerAnimationSequence( - LayerAnimationElement::CreateBoundsElement(target_bounds, delta))); - - animator->ScheduleTogether(sequences); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetGrayscaleForAnimation(), start_grayscale); - CheckApproximatelyEqual(delegate.GetBoundsForAnimation(), start_bounds); - - base::TimeTicks start_time = animator->last_step_time(); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(1000)); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetGrayscaleForAnimation(), target_grayscale); - CheckApproximatelyEqual(delegate.GetBoundsForAnimation(), start_bounds); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(2000)); - - EXPECT_FALSE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetGrayscaleForAnimation(), start_grayscale); - CheckApproximatelyEqual(delegate.GetBoundsForAnimation(), target_bounds); -} - -// Start non-threaded animation (that can run immediately). This is the trivial -// case (see the trival case for ScheduleAnimation). -TEST(LayerAnimatorTest, StartAnimationThatCanRunImmediately) { - scoped_refptr<LayerAnimator> animator(LayerAnimator::CreateDefaultAnimator()); - animator->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - - double start_brightness(0.0); - double middle_brightness(0.5); - double target_brightness(1.0); - - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - - delegate.SetBrightnessFromAnimation(start_brightness); - - animator->StartAnimation( - new LayerAnimationSequence( - LayerAnimationElement::CreateBrightnessElement(target_brightness, - delta))); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), start_brightness); - - base::TimeTicks start_time = animator->last_step_time(); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(500)); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), middle_brightness); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(1000)); - - EXPECT_FALSE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), target_brightness); -} - -// Start threaded animation (that can run immediately). -TEST(LayerAnimatorTest, StartThreadedAnimationThatCanRunImmediately) { - double epsilon = 0.00001; - LayerAnimatorTestController test_controller( - LayerAnimator::CreateDefaultAnimator()); - LayerAnimator* animator = test_controller.animator(); - test_controller.animator()->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - test_controller.animator()->SetDelegate(&delegate); - - double start_opacity(0.0); - double target_opacity(1.0); - - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - - delegate.SetOpacityFromAnimation(start_opacity); - - test_controller.animator()->StartAnimation( - new LayerAnimationSequence( - LayerAnimationElement::CreateOpacityElement(target_opacity, delta))); - - EXPECT_TRUE(test_controller.animator()->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetOpacityForAnimation(), start_opacity); - - base::TimeTicks start_time = test_controller.animator()->last_step_time(); - base::TimeTicks effective_start = start_time + delta; - - test_controller.animator()->OnThreadedAnimationStarted(cc::AnimationEvent( - cc::AnimationEvent::Started, - 0, - test_controller.GetRunningSequence(LayerAnimationElement::OPACITY) - ->animation_group_id(), - cc::Animation::Opacity, - effective_start)); - - animator->Step(effective_start + delta / 2); - - EXPECT_TRUE(test_controller.animator()->is_animating()); - EXPECT_NEAR( - 0.5, - test_controller.GetRunningSequence(LayerAnimationElement::OPACITY)-> - last_progressed_fraction(), - epsilon); - - animator->Step(effective_start + delta); - EXPECT_FALSE(test_controller.animator()->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetOpacityForAnimation(), target_opacity); -} - -// Preempt by immediately setting new target. -TEST(LayerAnimatorTest, PreemptBySettingNewTarget) { - scoped_refptr<LayerAnimator> animator(LayerAnimator::CreateDefaultAnimator()); - animator->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - - double start_opacity(0.0); - double target_opacity(1.0); - - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - - delegate.SetOpacityFromAnimation(start_opacity); - - animator->set_preemption_strategy(LayerAnimator::IMMEDIATELY_SET_NEW_TARGET); - - animator->StartAnimation( - new LayerAnimationSequence( - LayerAnimationElement::CreateOpacityElement(target_opacity, delta))); - - animator->StartAnimation( - new LayerAnimationSequence( - LayerAnimationElement::CreateOpacityElement(start_opacity, delta))); - - EXPECT_FALSE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetOpacityForAnimation(), start_opacity); -} - -// Preempt by animating to new target, with a non-threaded animation. -TEST(LayerAnimatorTest, PreemptByImmediatelyAnimatingToNewTarget) { - scoped_refptr<LayerAnimator> animator(LayerAnimator::CreateDefaultAnimator()); - animator->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - - double start_brightness(0.0); - double middle_brightness(0.5); - double target_brightness(1.0); - - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - - delegate.SetBrightnessFromAnimation(start_brightness); - - animator->set_preemption_strategy( - LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET); - - animator->StartAnimation( - new LayerAnimationSequence( - LayerAnimationElement::CreateBrightnessElement(target_brightness, - delta))); - - base::TimeTicks start_time = animator->last_step_time(); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(500)); - - animator->StartAnimation( - new LayerAnimationSequence( - LayerAnimationElement::CreateBrightnessElement(start_brightness, - delta))); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), middle_brightness); - - animator->StartAnimation( - new LayerAnimationSequence( - LayerAnimationElement::CreateBrightnessElement(start_brightness, - delta))); - - EXPECT_TRUE(animator->is_animating()); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(1000)); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), - 0.5 * (start_brightness + middle_brightness)); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(1500)); - - EXPECT_FALSE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), start_brightness); -} - -// Preempt by animating to new target, with a threaded animation. -TEST(LayerAnimatorTest, PreemptThreadedByImmediatelyAnimatingToNewTarget) { - double epsilon = 0.00001; - LayerAnimatorTestController test_controller( - LayerAnimator::CreateDefaultAnimator()); - LayerAnimator* animator = test_controller.animator(); - test_controller.animator()->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - test_controller.animator()->SetDelegate(&delegate); - - double start_opacity(0.0); - double middle_opacity(0.5); - double target_opacity(1.0); - - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - - delegate.SetOpacityFromAnimation(start_opacity); - - test_controller.animator()->set_preemption_strategy( - LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET); - - test_controller.animator()->StartAnimation( - new LayerAnimationSequence( - LayerAnimationElement::CreateOpacityElement(target_opacity, delta))); - - base::TimeTicks start_time = test_controller.animator()->last_step_time(); - base::TimeTicks effective_start = start_time + delta; - - test_controller.animator()->OnThreadedAnimationStarted(cc::AnimationEvent( - cc::AnimationEvent::Started, - 0, - test_controller.GetRunningSequence(LayerAnimationElement::OPACITY) - ->animation_group_id(), - cc::Animation::Opacity, - effective_start)); - - animator->Step(effective_start + delta / 2); - - test_controller.animator()->StartAnimation( - new LayerAnimationSequence( - LayerAnimationElement::CreateOpacityElement(start_opacity, delta))); - - EXPECT_TRUE(test_controller.animator()->is_animating()); - EXPECT_NEAR(delegate.GetOpacityForAnimation(), middle_opacity, epsilon); - - test_controller.animator()->StartAnimation( - new LayerAnimationSequence( - LayerAnimationElement::CreateOpacityElement(start_opacity, delta))); - - EXPECT_TRUE(test_controller.animator()->is_animating()); - - base::TimeTicks second_effective_start = effective_start + delta; - - test_controller.animator()->OnThreadedAnimationStarted(cc::AnimationEvent( - cc::AnimationEvent::Started, - 0, - test_controller.GetRunningSequence(LayerAnimationElement::OPACITY) - ->animation_group_id(), - cc::Animation::Opacity, - second_effective_start)); - - animator->Step(second_effective_start + delta / 2); - - EXPECT_TRUE(test_controller.animator()->is_animating()); - EXPECT_NEAR( - 0.5, - test_controller.GetRunningSequence(LayerAnimationElement::OPACITY)-> - last_progressed_fraction(), - epsilon); - - animator->Step(second_effective_start + delta); - - EXPECT_FALSE(test_controller.animator()->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetOpacityForAnimation(), start_opacity); -} - -// Preempt by enqueuing the new animation. -TEST(LayerAnimatorTest, PreemptEnqueueNewAnimation) { - scoped_refptr<LayerAnimator> animator(LayerAnimator::CreateDefaultAnimator()); - animator->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - - double start_brightness(0.0); - double middle_brightness(0.5); - double target_brightness(1.0); - - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - - delegate.SetBrightnessFromAnimation(start_brightness); - - animator->set_preemption_strategy(LayerAnimator::ENQUEUE_NEW_ANIMATION); - - animator->StartAnimation( - new LayerAnimationSequence( - LayerAnimationElement::CreateBrightnessElement(target_brightness, - delta))); - - base::TimeTicks start_time = animator->last_step_time(); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(500)); - - animator->StartAnimation( - new LayerAnimationSequence( - LayerAnimationElement::CreateBrightnessElement(start_brightness, - delta))); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), middle_brightness); - - EXPECT_TRUE(animator->is_animating()); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(1000)); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), target_brightness); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(1500)); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), middle_brightness); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(2000)); - - EXPECT_FALSE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), start_brightness); -} - -// Start an animation when there are sequences waiting in the queue. In this -// case, all pending and running animations should be finished, and the new -// animation started. -TEST(LayerAnimatorTest, PreemptyByReplacingQueuedAnimations) { - scoped_refptr<LayerAnimator> animator(LayerAnimator::CreateDefaultAnimator()); - animator->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - - double start_brightness(0.0); - double middle_brightness(0.5); - double target_brightness(1.0); - - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - - delegate.SetBrightnessFromAnimation(start_brightness); - - animator->set_preemption_strategy(LayerAnimator::REPLACE_QUEUED_ANIMATIONS); - - animator->StartAnimation( - new LayerAnimationSequence( - LayerAnimationElement::CreateBrightnessElement(target_brightness, - delta))); - - base::TimeTicks start_time = animator->last_step_time(); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(500)); - - animator->StartAnimation( - new LayerAnimationSequence( - LayerAnimationElement::CreateBrightnessElement(middle_brightness, - delta))); - - // Queue should now have two animations. Starting a third should replace the - // second. - animator->StartAnimation( - new LayerAnimationSequence( - LayerAnimationElement::CreateBrightnessElement(start_brightness, - delta))); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), middle_brightness); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(1000)); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), target_brightness); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(1500)); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), middle_brightness); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(2000)); - - EXPECT_FALSE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), start_brightness); -} - -TEST(LayerAnimatorTest, StartTogetherSetsLastStepTime) { - scoped_refptr<LayerAnimator> animator(LayerAnimator::CreateDefaultAnimator()); - animator->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - - double start_grayscale(0.0); - double target_grayscale(1.0); - double start_brightness(0.1); - double target_brightness(0.9); - - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - - delegate.SetGrayscaleFromAnimation(start_grayscale); - delegate.SetBrightnessFromAnimation(start_brightness); - - animator->set_preemption_strategy( - LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET); - - animator->set_last_step_time(base::TimeTicks()); - - animator->StartTogether( - CreateMultiSequence( - LayerAnimationElement::CreateGrayscaleElement(target_grayscale, - delta), - LayerAnimationElement::CreateBrightnessElement(target_brightness, - delta) - )); - - // If last step time was not set correctly, the resulting delta should be - // miniscule (fractions of a millisecond). If set correctly, then the delta - // should be enormous. Arbitrarily choosing 1 minute as the threshold, - // though a much smaller value would probably have sufficed. - delta = gfx::FrameTime::Now() - animator->last_step_time(); - EXPECT_GT(60.0, delta.InSecondsF()); -} - -//------------------------------------------------------- -// Preempt by immediately setting new target. -TEST(LayerAnimatorTest, MultiPreemptBySettingNewTarget) { - scoped_refptr<LayerAnimator> animator(LayerAnimator::CreateDefaultAnimator()); - animator->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - - double start_opacity(0.0); - double target_opacity(1.0); - double start_brightness(0.1); - double target_brightness(0.9); - - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - - delegate.SetOpacityFromAnimation(start_opacity); - delegate.SetBrightnessFromAnimation(start_brightness); - - animator->set_preemption_strategy(LayerAnimator::IMMEDIATELY_SET_NEW_TARGET); - - animator->StartTogether( - CreateMultiSequence( - LayerAnimationElement::CreateOpacityElement(target_opacity, delta), - LayerAnimationElement::CreateBrightnessElement(target_brightness, - delta) - )); - - animator->StartTogether( - CreateMultiSequence( - LayerAnimationElement::CreateOpacityElement(start_opacity, delta), - LayerAnimationElement::CreateBrightnessElement(start_brightness, - delta) - )); - - EXPECT_FALSE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetOpacityForAnimation(), start_opacity); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), start_brightness); -} - -// Preempt by animating to new target. -TEST(LayerAnimatorTest, MultiPreemptByImmediatelyAnimatingToNewTarget) { - scoped_refptr<LayerAnimator> animator(LayerAnimator::CreateDefaultAnimator()); - animator->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - - double start_grayscale(0.0); - double middle_grayscale(0.5); - double target_grayscale(1.0); - - double start_brightness(0.1); - double middle_brightness(0.2); - double target_brightness(0.3); - - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - - delegate.SetGrayscaleFromAnimation(start_grayscale); - delegate.SetBrightnessFromAnimation(start_brightness); - - animator->set_preemption_strategy( - LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET); - - animator->StartTogether( - CreateMultiSequence( - LayerAnimationElement::CreateGrayscaleElement(target_grayscale, - delta), - LayerAnimationElement::CreateBrightnessElement(target_brightness, - delta) - )); - - base::TimeTicks start_time = animator->last_step_time(); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(500)); - - animator->StartTogether( - CreateMultiSequence( - LayerAnimationElement::CreateGrayscaleElement(start_grayscale, delta), - LayerAnimationElement::CreateBrightnessElement(start_brightness, - delta))); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetGrayscaleForAnimation(), middle_grayscale); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), middle_brightness); - - animator->StartTogether( - CreateMultiSequence( - LayerAnimationElement::CreateGrayscaleElement(start_grayscale, delta), - LayerAnimationElement::CreateBrightnessElement(start_brightness, - delta))); - - EXPECT_TRUE(animator->is_animating()); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(1000)); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetGrayscaleForAnimation(), - 0.5 * (start_grayscale + middle_grayscale)); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), - 0.5 * (start_brightness + middle_brightness)); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(1500)); - - EXPECT_FALSE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetGrayscaleForAnimation(), start_grayscale); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), start_brightness); -} - -// Preempt a threaded animation by animating to new target. -TEST(LayerAnimatorTest, MultiPreemptThreadedByImmediatelyAnimatingToNewTarget) { - double epsilon = 0.00001; - LayerAnimatorTestController test_controller( - LayerAnimator::CreateDefaultAnimator()); - LayerAnimator* animator = test_controller.animator(); - test_controller.animator()->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - test_controller.animator()->SetDelegate(&delegate); - - double start_opacity(0.0); - double middle_opacity(0.5); - double target_opacity(1.0); - - double start_brightness(0.1); - double middle_brightness(0.2); - double target_brightness(0.3); - - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - - delegate.SetOpacityFromAnimation(start_opacity); - delegate.SetBrightnessFromAnimation(start_brightness); - - test_controller.animator()->set_preemption_strategy( - LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET); - - test_controller.animator()->StartTogether( - CreateMultiSequence( - LayerAnimationElement::CreateOpacityElement(target_opacity, delta), - LayerAnimationElement::CreateBrightnessElement(target_brightness, - delta) - )); - - base::TimeTicks start_time = test_controller.animator()->last_step_time(); - base::TimeTicks effective_start = start_time + delta; - - test_controller.animator()->OnThreadedAnimationStarted(cc::AnimationEvent( - cc::AnimationEvent::Started, - 0, - test_controller.GetRunningSequence(LayerAnimationElement::OPACITY) - ->animation_group_id(), - cc::Animation::Opacity, - effective_start)); - - animator->Step(effective_start + delta / 2); - - test_controller.animator()->StartTogether( - CreateMultiSequence( - LayerAnimationElement::CreateOpacityElement(start_opacity, delta), - LayerAnimationElement::CreateBrightnessElement(start_brightness, - delta))); - - EXPECT_TRUE(test_controller.animator()->is_animating()); - EXPECT_NEAR(delegate.GetOpacityForAnimation(), middle_opacity, epsilon); - EXPECT_NEAR(delegate.GetBrightnessForAnimation(), middle_brightness, epsilon); - - test_controller.animator()->StartTogether( - CreateMultiSequence( - LayerAnimationElement::CreateOpacityElement(start_opacity, delta), - LayerAnimationElement::CreateBrightnessElement(start_brightness, - delta))); - - EXPECT_TRUE(test_controller.animator()->is_animating()); - - base::TimeTicks second_effective_start = effective_start + delta; - - test_controller.animator()->OnThreadedAnimationStarted(cc::AnimationEvent( - cc::AnimationEvent::Started, - 0, - test_controller.GetRunningSequence(LayerAnimationElement::OPACITY) - ->animation_group_id(), - cc::Animation::Opacity, - second_effective_start)); - - animator->Step(second_effective_start + delta / 2); - - EXPECT_TRUE(test_controller.animator()->is_animating()); - EXPECT_NEAR( - 0.5, - test_controller.GetRunningSequence(LayerAnimationElement::OPACITY)-> - last_progressed_fraction(), - epsilon); - EXPECT_NEAR(delegate.GetBrightnessForAnimation(), - 0.5 * (start_brightness + middle_brightness), - epsilon); - - animator->Step(second_effective_start + delta); - - EXPECT_FALSE(test_controller.animator()->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetOpacityForAnimation(), start_opacity); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), start_brightness); -} - -// Preempt by enqueuing the new animation. -TEST(LayerAnimatorTest, MultiPreemptEnqueueNewAnimation) { - scoped_refptr<LayerAnimator> animator(LayerAnimator::CreateDefaultAnimator()); - animator->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - - double start_grayscale(0.0); - double middle_grayscale(0.5); - double target_grayscale(1.0); - - double start_brightness(0.1); - double middle_brightness(0.2); - double target_brightness(0.3); - - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - - delegate.SetGrayscaleFromAnimation(start_grayscale); - delegate.SetBrightnessFromAnimation(start_brightness); - - animator->set_preemption_strategy(LayerAnimator::ENQUEUE_NEW_ANIMATION); - - animator->StartTogether( - CreateMultiSequence( - LayerAnimationElement::CreateGrayscaleElement(target_grayscale, - delta), - LayerAnimationElement::CreateBrightnessElement(target_brightness, - delta))); - - base::TimeTicks start_time = animator->last_step_time(); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(500)); - - animator->StartTogether( - CreateMultiSequence( - LayerAnimationElement::CreateGrayscaleElement(start_grayscale, delta), - LayerAnimationElement::CreateBrightnessElement(start_brightness, - delta))); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetGrayscaleForAnimation(), middle_grayscale); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), middle_brightness); - - EXPECT_TRUE(animator->is_animating()); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(1000)); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetGrayscaleForAnimation(), target_grayscale); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), target_brightness); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(1500)); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetGrayscaleForAnimation(), middle_grayscale); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), middle_brightness); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(2000)); - - EXPECT_FALSE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetGrayscaleForAnimation(), start_grayscale); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), start_brightness); -} - -// Start an animation when there are sequences waiting in the queue. In this -// case, all pending and running animations should be finished, and the new -// animation started. -TEST(LayerAnimatorTest, MultiPreemptByReplacingQueuedAnimations) { - scoped_refptr<LayerAnimator> animator(LayerAnimator::CreateDefaultAnimator()); - animator->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - - double start_grayscale(0.0); - double middle_grayscale(0.5); - double target_grayscale(1.0); - - double start_brightness(0.1); - double middle_brightness(0.2); - double target_brightness(0.3); - - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - - delegate.SetGrayscaleFromAnimation(start_grayscale); - delegate.SetBrightnessFromAnimation(start_brightness); - - animator->set_preemption_strategy(LayerAnimator::REPLACE_QUEUED_ANIMATIONS); - - animator->StartTogether( - CreateMultiSequence( - LayerAnimationElement::CreateGrayscaleElement(target_grayscale, - delta), - LayerAnimationElement::CreateBrightnessElement(target_brightness, - delta))); - - base::TimeTicks start_time = animator->last_step_time(); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(500)); - - animator->StartTogether( - CreateMultiSequence( - LayerAnimationElement::CreateGrayscaleElement(middle_grayscale, - delta), - LayerAnimationElement::CreateBrightnessElement(middle_brightness, - delta))); - - // Queue should now have two animations. Starting a third should replace the - // second. - animator->StartTogether( - CreateMultiSequence( - LayerAnimationElement::CreateGrayscaleElement(start_grayscale, delta), - LayerAnimationElement::CreateBrightnessElement(start_brightness, - delta))); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetGrayscaleForAnimation(), middle_grayscale); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), middle_brightness); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(1000)); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetGrayscaleForAnimation(), target_grayscale); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), target_brightness); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(1500)); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetGrayscaleForAnimation(), middle_grayscale); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), middle_brightness); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(2000)); - - EXPECT_FALSE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetGrayscaleForAnimation(), start_grayscale); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), start_brightness); -} -//------------------------------------------------------- -// Test that non-threaded cyclic sequences continue to animate. -TEST(LayerAnimatorTest, CyclicSequences) { - scoped_refptr<LayerAnimator> animator(LayerAnimator::CreateDefaultAnimator()); - animator->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - - double start_brightness(0.0); - double target_brightness(1.0); - - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - - delegate.SetBrightnessFromAnimation(start_brightness); - - scoped_ptr<LayerAnimationSequence> sequence( - new LayerAnimationSequence( - LayerAnimationElement::CreateBrightnessElement(target_brightness, - delta))); - - sequence->AddElement( - LayerAnimationElement::CreateBrightnessElement(start_brightness, delta)); - - sequence->set_is_cyclic(true); - - animator->StartAnimation(sequence.release()); - - base::TimeTicks start_time = animator->last_step_time(); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(1000)); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), target_brightness); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(2000)); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), start_brightness); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(3000)); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), target_brightness); - - // Skip ahead by a lot. - animator->Step(start_time + base::TimeDelta::FromMilliseconds(1000000000)); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), start_brightness); - - // Skip ahead by a lot. - animator->Step(start_time + base::TimeDelta::FromMilliseconds(1000001000)); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetBrightnessForAnimation(), target_brightness); - - animator->StopAnimatingProperty(LayerAnimationElement::BRIGHTNESS); - - EXPECT_FALSE(animator->is_animating()); -} - -// Test that threaded cyclic sequences continue to animate. -TEST(LayerAnimatorTest, ThreadedCyclicSequences) { - LayerAnimatorTestController test_controller( - LayerAnimator::CreateDefaultAnimator()); - LayerAnimator* animator = test_controller.animator(); - test_controller.animator()->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - test_controller.animator()->SetDelegate(&delegate); - - double start_opacity(0.0); - double target_opacity(1.0); - - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - - delegate.SetOpacityFromAnimation(start_opacity); - - scoped_ptr<LayerAnimationSequence> sequence( - new LayerAnimationSequence( - LayerAnimationElement::CreateOpacityElement(target_opacity, delta))); - - sequence->AddElement( - LayerAnimationElement::CreateOpacityElement(start_opacity, delta)); - - sequence->set_is_cyclic(true); - - test_controller.animator()->StartAnimation(sequence.release()); - - base::TimeTicks start_time = test_controller.animator()->last_step_time(); - base::TimeTicks effective_start = start_time + delta; - - test_controller.animator()->OnThreadedAnimationStarted(cc::AnimationEvent( - cc::AnimationEvent::Started, - 0, - test_controller.GetRunningSequence(LayerAnimationElement::OPACITY) - ->animation_group_id(), - cc::Animation::Opacity, - effective_start)); - - animator->Step(effective_start + delta); - EXPECT_TRUE(test_controller.animator()->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetOpacityForAnimation(), target_opacity); - - base::TimeTicks second_effective_start = effective_start + 2 * delta; - test_controller.animator()->OnThreadedAnimationStarted(cc::AnimationEvent( - cc::AnimationEvent::Started, - 0, - test_controller.GetRunningSequence(LayerAnimationElement::OPACITY) - ->animation_group_id(), - cc::Animation::Opacity, - second_effective_start)); - - animator->Step(second_effective_start + delta); - - EXPECT_TRUE(test_controller.animator()->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetOpacityForAnimation(), start_opacity); - - base::TimeTicks third_effective_start = second_effective_start + 2 * delta; - test_controller.animator()->OnThreadedAnimationStarted(cc::AnimationEvent( - cc::AnimationEvent::Started, - 0, - test_controller.GetRunningSequence(LayerAnimationElement::OPACITY) - ->animation_group_id(), - cc::Animation::Opacity, - third_effective_start)); - - animator->Step(third_effective_start + delta); - EXPECT_TRUE(test_controller.animator()->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetOpacityForAnimation(), target_opacity); - - base::TimeTicks fourth_effective_start = third_effective_start + 2 * delta; - test_controller.animator()->OnThreadedAnimationStarted(cc::AnimationEvent( - cc::AnimationEvent::Started, - 0, - test_controller.GetRunningSequence(LayerAnimationElement::OPACITY) - ->animation_group_id(), - cc::Animation::Opacity, - fourth_effective_start)); - - // Skip ahead by a lot. - animator->Step(fourth_effective_start + 1000 * delta); - - EXPECT_TRUE(test_controller.animator()->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetOpacityForAnimation(), target_opacity); - - base::TimeTicks fifth_effective_start = fourth_effective_start + 1001 * delta; - test_controller.animator()->OnThreadedAnimationStarted(cc::AnimationEvent( - cc::AnimationEvent::Started, - 0, - test_controller.GetRunningSequence(LayerAnimationElement::OPACITY) - ->animation_group_id(), - cc::Animation::Opacity, - fifth_effective_start)); - - // Skip ahead by a lot. - animator->Step(fifth_effective_start + 999 * delta); - - EXPECT_TRUE(test_controller.animator()->is_animating()); - EXPECT_FLOAT_EQ(delegate.GetOpacityForAnimation(), start_opacity); - - test_controller.animator()->StopAnimatingProperty( - LayerAnimationElement::OPACITY); - - EXPECT_FALSE(test_controller.animator()->is_animating()); -} - -TEST(LayerAnimatorTest, AddObserverExplicit) { - scoped_refptr<LayerAnimator> animator(LayerAnimator::CreateDefaultAnimator()); - animator->set_disable_timer_for_test(true); - TestLayerAnimationObserver observer; - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - animator->AddObserver(&observer); - observer.set_requires_notification_when_animator_destroyed(true); - - EXPECT_TRUE(!observer.last_ended_sequence()); - - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - - delegate.SetBrightnessFromAnimation(0.0f); - - LayerAnimationSequence* sequence = new LayerAnimationSequence( - LayerAnimationElement::CreateBrightnessElement(1.0f, delta)); - - animator->StartAnimation(sequence); - - EXPECT_EQ(observer.last_scheduled_sequence(), sequence); - - base::TimeTicks start_time = animator->last_step_time(); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(1000)); - - EXPECT_EQ(observer.last_ended_sequence(), sequence); - - // |sequence| has been destroyed. Recreate it to test abort. - sequence = new LayerAnimationSequence( - LayerAnimationElement::CreateBrightnessElement(1.0f, delta)); - - animator->StartAnimation(sequence); - - animator = NULL; - - EXPECT_EQ(observer.last_aborted_sequence(), sequence); -} - -// Tests that an observer added to a scoped settings object is still notified -// when the object goes out of scope. -TEST(LayerAnimatorTest, ImplicitAnimationObservers) { - scoped_refptr<LayerAnimator> animator(LayerAnimator::CreateDefaultAnimator()); - animator->set_disable_timer_for_test(true); - TestImplicitAnimationObserver observer(false); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - - EXPECT_FALSE(observer.animations_completed()); - animator->SetBrightness(1.0f); - - { - ScopedLayerAnimationSettings settings(animator.get()); - settings.AddObserver(&observer); - animator->SetBrightness(0.0f); - } - - EXPECT_FALSE(observer.animations_completed()); - base::TimeTicks start_time = animator->last_step_time(); - animator->Step(start_time + base::TimeDelta::FromMilliseconds(1000)); - EXPECT_TRUE(observer.animations_completed()); - EXPECT_TRUE(observer.WasAnimationCompletedForProperty( - LayerAnimationElement::BRIGHTNESS)); - EXPECT_FLOAT_EQ(0.0f, delegate.GetBrightnessForAnimation()); -} - -// Tests that an observer added to a scoped settings object is still notified -// when the object goes out of scope due to the animation being interrupted. -TEST(LayerAnimatorTest, InterruptedImplicitAnimationObservers) { - scoped_refptr<LayerAnimator> animator(LayerAnimator::CreateDefaultAnimator()); - animator->set_disable_timer_for_test(true); - TestImplicitAnimationObserver observer(false); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - - EXPECT_FALSE(observer.animations_completed()); - animator->SetBrightness(1.0f); - - { - ScopedLayerAnimationSettings settings(animator.get()); - settings.AddObserver(&observer); - animator->SetBrightness(0.0f); - } - - EXPECT_FALSE(observer.animations_completed()); - // This should interrupt the implicit animation causing the observer to be - // notified immediately. - animator->SetBrightness(1.0f); - EXPECT_TRUE(observer.animations_completed()); - EXPECT_TRUE(observer.WasAnimationCompletedForProperty( - LayerAnimationElement::BRIGHTNESS)); - EXPECT_FLOAT_EQ(1.0f, delegate.GetBrightnessForAnimation()); -} - -// Tests that LayerAnimator is not deleted after the animation completes as long -// as there is a live ScopedLayerAnimationSettings object wrapped around it. -TEST(LayerAnimatorTest, AnimatorKeptAliveBySettings) { - // Note we are using a raw pointer unlike in other tests. - TestLayerAnimator* animator = new TestLayerAnimator(); - LayerAnimatorDestructionObserver destruction_observer; - animator->SetDestructionObserver(&destruction_observer); - animator->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - { - // ScopedLayerAnimationSettings should keep the Animator alive as long as - // it is alive, even beyond the end of the animation. - ScopedLayerAnimationSettings settings(animator); - base::TimeTicks now = gfx::FrameTime::Now(); - animator->SetBrightness(0.5); - animator->Step(now + base::TimeDelta::FromSeconds(1)); - EXPECT_FALSE(destruction_observer.IsAnimatorDeleted()); - } - // ScopedLayerAnimationSettings was destroyed, so Animator should be deleted. - EXPECT_TRUE(destruction_observer.IsAnimatorDeleted()); -} - -// Tests that an observer added to a scoped settings object is not notified -// when the animator is destroyed unless explicitly requested. -TEST(LayerAnimatorTest, ImplicitObserversAtAnimatorDestruction) { - scoped_refptr<LayerAnimator> animator(LayerAnimator::CreateDefaultAnimator()); - animator->set_disable_timer_for_test(true); - TestImplicitAnimationObserver observer_notify(true); - TestImplicitAnimationObserver observer_do_not_notify(false); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - - EXPECT_FALSE(observer_notify.animations_completed()); - EXPECT_FALSE(observer_do_not_notify.animations_completed()); - - animator->SetBrightness(1.0f); - - { - ScopedLayerAnimationSettings settings(animator.get()); - settings.AddObserver(&observer_notify); - settings.AddObserver(&observer_do_not_notify); - animator->SetBrightness(0.0f); - } - - EXPECT_FALSE(observer_notify.animations_completed()); - EXPECT_FALSE(observer_do_not_notify.animations_completed()); - animator = NULL; - EXPECT_TRUE(observer_notify.animations_completed()); - EXPECT_TRUE(observer_notify.WasAnimationAbortedForProperty( - LayerAnimationElement::BRIGHTNESS)); - EXPECT_FALSE(observer_do_not_notify.animations_completed()); -} - -TEST(LayerAnimatorTest, AbortedAnimationStatusInImplicitObservers) { - scoped_refptr<LayerAnimator> animator(LayerAnimator::CreateDefaultAnimator()); - animator->set_disable_timer_for_test(true); - TestImplicitAnimationObserver observer(false); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - - EXPECT_FALSE(observer.animations_completed()); - animator->SetBrightness(1.0f); - - { - ScopedLayerAnimationSettings settings(animator.get()); - settings.AddObserver(&observer); - animator->SetBrightness(0.0f); - } - EXPECT_FALSE(observer.animations_completed()); - - animator->AbortAllAnimations(); - EXPECT_TRUE(observer.animations_completed()); - EXPECT_TRUE(observer.WasAnimationAbortedForProperty( - LayerAnimationElement::BRIGHTNESS)); - EXPECT_FALSE(observer.WasAnimationAbortedForProperty( - LayerAnimationElement::OPACITY)); - - observer.set_animations_completed(false); - { - ScopedLayerAnimationSettings settings(animator.get()); - settings.AddObserver(&observer); - animator->SetOpacity(0.0f); - } - EXPECT_FALSE(observer.animations_completed()); - - animator->AbortAllAnimations(); - EXPECT_TRUE(observer.animations_completed()); - EXPECT_TRUE(observer.WasAnimationAbortedForProperty( - LayerAnimationElement::BRIGHTNESS)); - EXPECT_TRUE(observer.WasAnimationAbortedForProperty( - LayerAnimationElement::OPACITY)); -} - -TEST(LayerAnimatorTest, RemoveObserverShouldRemoveFromSequences) { - scoped_refptr<LayerAnimator> animator(LayerAnimator::CreateDefaultAnimator()); - animator->set_disable_timer_for_test(true); - TestLayerAnimationObserver observer; - TestLayerAnimationObserver removed_observer; - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - - LayerAnimationSequence* sequence = new LayerAnimationSequence( - LayerAnimationElement::CreateBrightnessElement(1.0f, delta)); - - sequence->AddObserver(&observer); - sequence->AddObserver(&removed_observer); - - animator->StartAnimation(sequence); - - EXPECT_EQ(observer.last_scheduled_sequence(), sequence); - EXPECT_TRUE(!observer.last_ended_sequence()); - EXPECT_EQ(removed_observer.last_scheduled_sequence(), sequence); - EXPECT_TRUE(!removed_observer.last_ended_sequence()); - - // This should stop the observer from observing sequence. - animator->RemoveObserver(&removed_observer); - - base::TimeTicks start_time = animator->last_step_time(); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(1000)); - - EXPECT_EQ(observer.last_ended_sequence(), sequence); - EXPECT_TRUE(!removed_observer.last_ended_sequence()); -} - -TEST(LayerAnimatorTest, ObserverReleasedBeforeAnimationSequenceEnds) { - TestLayerAnimationDelegate delegate; - scoped_refptr<LayerAnimator> animator(LayerAnimator::CreateDefaultAnimator()); - animator->set_disable_timer_for_test(true); - - scoped_ptr<TestLayerAnimationObserver> observer( - new TestLayerAnimationObserver); - animator->SetDelegate(&delegate); - animator->AddObserver(observer.get()); - - delegate.SetOpacityFromAnimation(0.0f); - - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - LayerAnimationSequence* sequence = new LayerAnimationSequence( - LayerAnimationElement::CreateOpacityElement(1.0f, delta)); - - animator->StartAnimation(sequence); - - // |observer| should be attached to |sequence|. - EXPECT_TRUE(sequence->observers_.might_have_observers()); - - // Now, release |observer| - observer.reset(); - - // And |sequence| should no longer be attached to |observer|. - EXPECT_FALSE(sequence->observers_.might_have_observers()); -} - -TEST(LayerAnimatorTest, ObserverAttachedAfterAnimationStarted) { - scoped_refptr<LayerAnimator> animator(LayerAnimator::CreateDefaultAnimator()); - animator->set_disable_timer_for_test(true); - - TestImplicitAnimationObserver observer(false); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - - delegate.SetBrightnessFromAnimation(0.0f); - - { - ScopedLayerAnimationSettings setter(animator.get()); - - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - LayerAnimationSequence* sequence = new LayerAnimationSequence( - LayerAnimationElement::CreateBrightnessElement(1.0f, delta)); - - animator->StartAnimation(sequence); - base::TimeTicks start_time = animator->last_step_time(); - animator->Step(start_time + base::TimeDelta::FromMilliseconds(500)); - - setter.AddObserver(&observer); - - // Start observing an in-flight animation. - sequence->AddObserver(&observer); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(1000)); - } - - EXPECT_TRUE(observer.animations_completed()); - EXPECT_TRUE(observer.WasAnimationCompletedForProperty( - LayerAnimationElement::BRIGHTNESS)); -} - -TEST(LayerAnimatorTest, ObserverDetachedBeforeAnimationFinished) { - scoped_refptr<LayerAnimator> animator(LayerAnimator::CreateDefaultAnimator()); - animator->set_disable_timer_for_test(true); - - TestImplicitAnimationObserver observer(false); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - - delegate.SetBrightnessFromAnimation(0.0f); - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - LayerAnimationSequence* sequence = new LayerAnimationSequence( - LayerAnimationElement::CreateBrightnessElement(1.0f, delta)); - - { - ScopedLayerAnimationSettings setter(animator.get()); - setter.AddObserver(&observer); - - animator->StartAnimation(sequence); - base::TimeTicks start_time = animator->last_step_time(); - animator->Step(start_time + base::TimeDelta::FromMilliseconds(500)); - } - - EXPECT_FALSE(observer.animations_completed()); - - // Stop observing an in-flight animation. - sequence->RemoveObserver(&observer); - - EXPECT_TRUE(observer.animations_completed()); - - // The animation didn't complete, and neither was it aborted. - EXPECT_FALSE(observer.WasAnimationCompletedForProperty( - LayerAnimationElement::BRIGHTNESS)); - EXPECT_FALSE(observer.WasAnimationAbortedForProperty( - LayerAnimationElement::BRIGHTNESS)); -} - -// This checks that if an animation is deleted due to a callback, that the -// animator does not try to use the deleted animation. For example, if we have -// two running animations, and the first finishes and the resulting callback -// causes the second to be deleted, we should not attempt to animate the second -// animation. -TEST(LayerAnimatorTest, ObserverDeletesAnimationsOnEnd) { - ScopedAnimationDurationScaleMode normal_duration_mode( - ScopedAnimationDurationScaleMode::NORMAL_DURATION); - scoped_refptr<LayerAnimator> animator(new TestLayerAnimator()); - animator->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - - double start_brightness(0.0); - double target_brightness(1.0); - - gfx::Rect start_bounds(0, 0, 50, 50); - gfx::Rect target_bounds(5, 5, 5, 5); - - delegate.SetBrightnessFromAnimation(start_brightness); - delegate.SetBoundsFromAnimation(start_bounds); - - base::TimeDelta brightness_delta = base::TimeDelta::FromSeconds(1); - base::TimeDelta halfway_delta = base::TimeDelta::FromSeconds(2); - base::TimeDelta bounds_delta = base::TimeDelta::FromSeconds(3); - - scoped_ptr<DeletingLayerAnimationObserver> observer( - new DeletingLayerAnimationObserver(animator.get())); - - animator->AddObserver(observer.get()); - - animator->StartAnimation( - new LayerAnimationSequence( - LayerAnimationElement::CreateBrightnessElement( - target_brightness, brightness_delta))); - - animator->StartAnimation(new LayerAnimationSequence( - LayerAnimationElement::CreateBoundsElement( - target_bounds, bounds_delta))); - ASSERT_TRUE(animator->IsAnimatingProperty(LayerAnimationElement::BOUNDS)); - - base::TimeTicks start_time = animator->last_step_time(); - animator->Step(start_time + halfway_delta); - - // Completing the brightness animation should have stopped the bounds - // animation. - ASSERT_FALSE(animator->IsAnimatingProperty(LayerAnimationElement::BOUNDS)); - - animator->RemoveObserver(observer.get()); -} - -// Ensure that stopping animation in a bounds change does not crash and that -// animation gets stopped correctly. -// This scenario is possible when animation is restarted from inside a -// callback triggered by the animation progress. -TEST(LayerAnimatorTest, CallbackDeletesAnimationInProgress) { - - class TestLayerAnimationDeletingDelegate : public TestLayerAnimationDelegate { - public: - TestLayerAnimationDeletingDelegate(LayerAnimator* animator, int max_width) - : animator_(animator), - max_width_(max_width) { - } - - virtual void SetBoundsFromAnimation(const gfx::Rect& bounds) override { - TestLayerAnimationDelegate::SetBoundsFromAnimation(bounds); - if (bounds.width() > max_width_) - animator_->StopAnimating(); - } - private: - LayerAnimator* animator_; - int max_width_; - // Allow copy and assign. - }; - - ScopedAnimationDurationScaleMode normal_duration_mode( - ScopedAnimationDurationScaleMode::NORMAL_DURATION); - scoped_refptr<LayerAnimator> animator(new TestLayerAnimator()); - animator->set_disable_timer_for_test(true); - TestLayerAnimationDeletingDelegate delegate(animator.get(), 30); - animator->SetDelegate(&delegate); - - gfx::Rect start_bounds(0, 0, 0, 0); - gfx::Rect target_bounds(5, 5, 50, 50); - - delegate.SetBoundsFromAnimation(start_bounds); - - base::TimeDelta bounds_delta1 = base::TimeDelta::FromMilliseconds(333); - base::TimeDelta bounds_delta2 = base::TimeDelta::FromMilliseconds(666); - base::TimeDelta bounds_delta = base::TimeDelta::FromMilliseconds(1000); - base::TimeDelta final_delta = base::TimeDelta::FromMilliseconds(1500); - - animator->StartAnimation(new LayerAnimationSequence( - LayerAnimationElement::CreateBoundsElement( - target_bounds, bounds_delta))); - ASSERT_TRUE(animator->IsAnimatingProperty(LayerAnimationElement::BOUNDS)); - - base::TimeTicks start_time = animator->last_step_time(); - ASSERT_NO_FATAL_FAILURE(animator->Step(start_time + bounds_delta1)); - ASSERT_TRUE(animator->IsAnimatingProperty(LayerAnimationElement::BOUNDS)); - - // The next step should change the animated bounds past the threshold and - // cause the animaton to stop. - ASSERT_NO_FATAL_FAILURE(animator->Step(start_time + bounds_delta2)); - ASSERT_FALSE(animator->IsAnimatingProperty(LayerAnimationElement::BOUNDS)); - ASSERT_NO_FATAL_FAILURE(animator->Step(start_time + final_delta)); - - // Completing the animation should have stopped the bounds - // animation. - ASSERT_FALSE(animator->IsAnimatingProperty(LayerAnimationElement::BOUNDS)); -} - -// Similar to the ObserverDeletesAnimationsOnEnd test above except that it -// tests the behavior when the OnLayerAnimationAborted() callback causes -// all of the animator's other animations to be deleted. -TEST(LayerAnimatorTest, ObserverDeletesAnimationsOnAbort) { - ScopedAnimationDurationScaleMode test_duration_mode( - ScopedAnimationDurationScaleMode::NON_ZERO_DURATION); - scoped_refptr<LayerAnimator> animator(new TestLayerAnimator()); - animator->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - - double start_brightness(0.0); - double target_brightness(1.0); - gfx::Rect start_bounds(0, 0, 50, 50); - gfx::Rect target_bounds(5, 5, 5, 5); - base::TimeDelta brightness_delta = base::TimeDelta::FromSeconds(1); - base::TimeDelta bounds_delta = base::TimeDelta::FromSeconds(2); - - delegate.SetBrightnessFromAnimation(start_brightness); - delegate.SetBoundsFromAnimation(start_bounds); - - scoped_ptr<DeletingLayerAnimationObserver> observer( - new DeletingLayerAnimationObserver(animator.get())); - animator->AddObserver(observer.get()); - - animator->StartAnimation( - new LayerAnimationSequence( - LayerAnimationElement::CreateBrightnessElement( - target_brightness, brightness_delta))); - animator->StartAnimation(new LayerAnimationSequence( - LayerAnimationElement::CreateBoundsElement( - target_bounds, bounds_delta))); - ASSERT_TRUE(animator->IsAnimatingProperty(LayerAnimationElement::BOUNDS)); - - animator->set_preemption_strategy( - LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET); - animator->StartAnimation( - new LayerAnimationSequence( - LayerAnimationElement::CreateBrightnessElement( - target_brightness, brightness_delta))); - - // Starting the second brightness animation should have aborted the initial - // brightness animation. |observer| should have stopped the bounds animation - // as a result. - ASSERT_FALSE(animator->IsAnimatingProperty(LayerAnimationElement::BOUNDS)); - - animator->RemoveObserver(observer.get()); -} - -// Check that setting a property during an animation with a default animator -// cancels the original animation. -TEST(LayerAnimatorTest, SettingPropertyDuringAnAnimation) { - scoped_refptr<LayerAnimator> animator(LayerAnimator::CreateDefaultAnimator()); - animator->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - - double start_opacity(0.0); - double target_opacity(1.0); - - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - - delegate.SetOpacityFromAnimation(start_opacity); - - scoped_ptr<LayerAnimationSequence> sequence( - new LayerAnimationSequence( - LayerAnimationElement::CreateOpacityElement(target_opacity, delta))); - - animator->StartAnimation(sequence.release()); - - animator->SetOpacity(0.5); - - EXPECT_FALSE(animator->is_animating()); - EXPECT_EQ(0.5, animator->GetTargetOpacity()); -} - -// Tests that the preemption mode IMMEDIATELY_SET_NEW_TARGET, doesn't cause the -// second sequence to be leaked. -TEST(LayerAnimatorTest, ImmediatelySettingNewTargetDoesNotLeak) { - scoped_refptr<LayerAnimator> animator(LayerAnimator::CreateDefaultAnimator()); - animator->set_preemption_strategy(LayerAnimator::IMMEDIATELY_SET_NEW_TARGET); - animator->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - - gfx::Rect start_bounds(0, 0, 50, 50); - gfx::Rect middle_bounds(10, 10, 100, 100); - gfx::Rect target_bounds(5, 5, 5, 5); - - delegate.SetBoundsFromAnimation(start_bounds); - - { - // start an implicit bounds animation. - ScopedLayerAnimationSettings settings(animator.get()); - animator->SetBounds(middle_bounds); - } - - EXPECT_TRUE(animator->IsAnimatingProperty(LayerAnimationElement::BOUNDS)); - - int num_live_instances = 0; - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - scoped_ptr<TestLayerAnimationSequence> sequence( - new TestLayerAnimationSequence( - LayerAnimationElement::CreateBoundsElement(target_bounds, delta), - &num_live_instances)); - - EXPECT_EQ(1, num_live_instances); - - // This should interrupt the running sequence causing us to immediately set - // the target value. The sequence should alse be destructed. - animator->StartAnimation(sequence.release()); - - EXPECT_FALSE(animator->IsAnimatingProperty(LayerAnimationElement::BOUNDS)); - EXPECT_EQ(0, num_live_instances); - CheckApproximatelyEqual(delegate.GetBoundsForAnimation(), target_bounds); -} - -// Verifies GetTargetOpacity() works when multiple sequences are scheduled. -TEST(LayerAnimatorTest, GetTargetOpacity) { - TestLayerAnimationDelegate delegate; - scoped_refptr<LayerAnimator> animator(LayerAnimator::CreateDefaultAnimator()); - animator->set_preemption_strategy(LayerAnimator::ENQUEUE_NEW_ANIMATION); - animator->set_disable_timer_for_test(true); - animator->SetDelegate(&delegate); - - delegate.SetOpacityFromAnimation(0.0); - - { - ScopedLayerAnimationSettings settings(animator.get()); - animator->SetOpacity(0.5); - EXPECT_EQ(0.5, animator->GetTargetOpacity()); - - // Because the strategy is ENQUEUE_NEW_ANIMATION the target should now be 1. - animator->SetOpacity(1.0); - EXPECT_EQ(1.0, animator->GetTargetOpacity()); - } -} - -// Verifies GetTargetBrightness() works when multiple sequences are scheduled. -TEST(LayerAnimatorTest, GetTargetBrightness) { - scoped_refptr<LayerAnimator> animator(LayerAnimator::CreateDefaultAnimator()); - animator->set_preemption_strategy(LayerAnimator::ENQUEUE_NEW_ANIMATION); - animator->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - - delegate.SetBrightnessFromAnimation(0.0); - - { - ScopedLayerAnimationSettings settings(animator.get()); - animator->SetBrightness(0.5); - EXPECT_EQ(0.5, animator->GetTargetBrightness()); - - // Because the strategy is ENQUEUE_NEW_ANIMATION the target should now be 1. - animator->SetBrightness(1.0); - EXPECT_EQ(1.0, animator->GetTargetBrightness()); - } -} - -// Verifies GetTargetGrayscale() works when multiple sequences are scheduled. -TEST(LayerAnimatorTest, GetTargetGrayscale) { - scoped_refptr<LayerAnimator> animator(LayerAnimator::CreateDefaultAnimator()); - animator->set_preemption_strategy(LayerAnimator::ENQUEUE_NEW_ANIMATION); - animator->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - - delegate.SetGrayscaleFromAnimation(0.0); - - { - ScopedLayerAnimationSettings settings(animator.get()); - animator->SetGrayscale(0.5); - EXPECT_EQ(0.5, animator->GetTargetGrayscale()); - - // Because the strategy is ENQUEUE_NEW_ANIMATION the target should now be 1. - animator->SetGrayscale(1.0); - EXPECT_EQ(1.0, animator->GetTargetGrayscale()); - } -} - -// Verifies color property is modified appropriately. -TEST(LayerAnimatorTest, Color) { - scoped_refptr<LayerAnimator> animator(LayerAnimator::CreateDefaultAnimator()); - animator->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - - SkColor start_color = SkColorSetARGB( 64, 20, 40, 60); - SkColor middle_color = SkColorSetARGB(128, 35, 70, 120); - SkColor target_color = SkColorSetARGB(192, 40, 80, 140); - - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - - delegate.SetColorFromAnimation(start_color); - - animator->ScheduleAnimation( - new LayerAnimationSequence( - LayerAnimationElement::CreateColorElement(target_color, delta))); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_EQ(ColorToString(start_color), - ColorToString(delegate.GetColorForAnimation())); - - base::TimeTicks start_time = animator->last_step_time(); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(500)); - - EXPECT_TRUE(animator->is_animating()); - EXPECT_EQ(ColorToString(middle_color), - ColorToString(delegate.GetColorForAnimation())); - - animator->Step(start_time + base::TimeDelta::FromMilliseconds(1000)); - - EXPECT_FALSE(animator->is_animating()); - EXPECT_EQ(ColorToString(target_color), - ColorToString(delegate.GetColorForAnimation())); -} - -// Verifies SchedulePauseForProperties(). -TEST(LayerAnimatorTest, SchedulePauseForProperties) { - scoped_refptr<LayerAnimator> animator(LayerAnimator::CreateDefaultAnimator()); - animator->set_preemption_strategy(LayerAnimator::ENQUEUE_NEW_ANIMATION); - animator->SchedulePauseForProperties( - base::TimeDelta::FromMilliseconds(100), - LayerAnimationElement::TRANSFORM | LayerAnimationElement::BOUNDS); - EXPECT_TRUE(animator->IsAnimatingProperty(LayerAnimationElement::TRANSFORM)); - EXPECT_TRUE(animator->IsAnimatingProperty(LayerAnimationElement::BOUNDS)); - EXPECT_FALSE(animator->IsAnimatingProperty(LayerAnimationElement::OPACITY)); -} - - -class AnimatorOwner { -public: - AnimatorOwner() - : animator_(LayerAnimator::CreateDefaultAnimator()) { - } - - LayerAnimator* animator() { return animator_.get(); } - -private: - scoped_refptr<LayerAnimator> animator_; - - DISALLOW_COPY_AND_ASSIGN(AnimatorOwner); -}; - -class DeletingObserver : public LayerAnimationObserver { -public: - DeletingObserver(bool* was_deleted) - : animator_owner_(new AnimatorOwner), - delete_on_animation_ended_(false), - delete_on_animation_aborted_(false), - delete_on_animation_scheduled_(false), - was_deleted_(was_deleted) { - animator()->AddObserver(this); - } - - virtual ~DeletingObserver() { - animator()->RemoveObserver(this); - *was_deleted_ = true; - } - - LayerAnimator* animator() { return animator_owner_->animator(); } - - bool delete_on_animation_ended() const { - return delete_on_animation_ended_; - } - void set_delete_on_animation_ended(bool enabled) { - delete_on_animation_ended_ = enabled; - } - - bool delete_on_animation_aborted() const { - return delete_on_animation_aborted_; - } - void set_delete_on_animation_aborted(bool enabled) { - delete_on_animation_aborted_ = enabled; - } - - bool delete_on_animation_scheduled() const { - return delete_on_animation_scheduled_; - } - void set_delete_on_animation_scheduled(bool enabled) { - delete_on_animation_scheduled_ = enabled; - } - - // LayerAnimationObserver implementation. - virtual void OnLayerAnimationEnded( - LayerAnimationSequence* sequence) override { - if (delete_on_animation_ended_) - delete this; - } - - virtual void OnLayerAnimationAborted( - LayerAnimationSequence* sequence) override { - if (delete_on_animation_aborted_) - delete this; - } - - virtual void OnLayerAnimationScheduled( - LayerAnimationSequence* sequence) override { - if (delete_on_animation_scheduled_) - delete this; - } - -private: - scoped_ptr<AnimatorOwner> animator_owner_; - bool delete_on_animation_ended_; - bool delete_on_animation_aborted_; - bool delete_on_animation_scheduled_; - bool* was_deleted_; - - DISALLOW_COPY_AND_ASSIGN(DeletingObserver); -}; - -TEST(LayerAnimatorTest, ObserverDeletesAnimatorAfterFinishingAnimation) { - bool observer_was_deleted = false; - DeletingObserver* observer = new DeletingObserver(&observer_was_deleted); - observer->set_delete_on_animation_ended(true); - observer->set_delete_on_animation_aborted(true); - LayerAnimator* animator = observer->animator(); - animator->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - - delegate.SetBrightnessFromAnimation(0.0f); - - gfx::Rect start_bounds(0, 0, 50, 50); - gfx::Rect target_bounds(10, 10, 100, 100); - - delegate.SetBoundsFromAnimation(start_bounds); - - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - LayerAnimationSequence* brightness_sequence = new LayerAnimationSequence( - LayerAnimationElement::CreateBrightnessElement(1.0f, delta)); - animator->StartAnimation(brightness_sequence); - - delta = base::TimeDelta::FromSeconds(2); - LayerAnimationSequence* bounds_sequence = new LayerAnimationSequence( - LayerAnimationElement::CreateBoundsElement(target_bounds, delta)); - animator->StartAnimation(bounds_sequence); - - base::TimeTicks start_time = animator->last_step_time(); - animator->Step(start_time + base::TimeDelta::FromMilliseconds(1500)); - - EXPECT_TRUE(observer_was_deleted); -} - -TEST(LayerAnimatorTest, ObserverDeletesAnimatorAfterStoppingAnimating) { - bool observer_was_deleted = false; - DeletingObserver* observer = new DeletingObserver(&observer_was_deleted); - observer->set_delete_on_animation_ended(true); - observer->set_delete_on_animation_aborted(true); - LayerAnimator* animator = observer->animator(); - animator->set_disable_timer_for_test(true); - TestLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - - delegate.SetOpacityFromAnimation(0.0f); - - gfx::Rect start_bounds(0, 0, 50, 50); - gfx::Rect target_bounds(10, 10, 100, 100); - - delegate.SetBoundsFromAnimation(start_bounds); - - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - LayerAnimationSequence* opacity_sequence = new LayerAnimationSequence( - LayerAnimationElement::CreateOpacityElement(1.0f, delta)); - animator->StartAnimation(opacity_sequence); - - delta = base::TimeDelta::FromSeconds(2); - LayerAnimationSequence* bounds_sequence = new LayerAnimationSequence( - LayerAnimationElement::CreateBoundsElement(target_bounds, delta)); - animator->StartAnimation(bounds_sequence); - - animator->StopAnimating(); - - EXPECT_TRUE(observer_was_deleted); -} - -TEST(LayerAnimatorTest, ObserverDeletesAnimatorAfterScheduling) { - bool observer_was_deleted = false; - TestLayerAnimationDelegate delegate; - DeletingObserver* observer = new DeletingObserver(&observer_was_deleted); - observer->set_delete_on_animation_scheduled(true); - LayerAnimator* animator = observer->animator(); - animator->set_disable_timer_for_test(true); - animator->SetDelegate(&delegate); - - delegate.SetOpacityFromAnimation(0.0f); - - gfx::Rect start_bounds(0, 0, 50, 50); - gfx::Rect target_bounds(10, 10, 100, 100); - - delegate.SetBoundsFromAnimation(start_bounds); - - std::vector<LayerAnimationSequence*> to_start; - - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - to_start.push_back(new LayerAnimationSequence( - LayerAnimationElement::CreateOpacityElement(1.0f, delta))); - - delta = base::TimeDelta::FromSeconds(2); - to_start.push_back(new LayerAnimationSequence( - LayerAnimationElement::CreateBoundsElement(target_bounds, delta))); - - animator->ScheduleTogether(to_start); - - EXPECT_TRUE(observer_was_deleted); -} - -TEST(LayerAnimatorTest, ObserverDeletesAnimatorAfterAborted) { - bool observer_was_deleted = false; - DeletingObserver* observer = new DeletingObserver(&observer_was_deleted); - TestLayerAnimationDelegate delegate; - observer->set_delete_on_animation_aborted(true); - LayerAnimator* animator = observer->animator(); - animator->set_preemption_strategy( - LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET); - animator->set_disable_timer_for_test(true); - animator->SetDelegate(&delegate); - - delegate.SetOpacityFromAnimation(0.0f); - - gfx::Rect start_bounds(0, 0, 50, 50); - gfx::Rect target_bounds(10, 10, 100, 100); - - delegate.SetBoundsFromAnimation(start_bounds); - - std::vector<LayerAnimationSequence*> to_start; - - base::TimeDelta delta = base::TimeDelta::FromSeconds(1); - to_start.push_back(new LayerAnimationSequence( - LayerAnimationElement::CreateOpacityElement(1.0f, delta))); - - delta = base::TimeDelta::FromSeconds(2); - to_start.push_back(new LayerAnimationSequence( - LayerAnimationElement::CreateBoundsElement(target_bounds, delta))); - - animator->ScheduleTogether(to_start); - - EXPECT_FALSE(observer_was_deleted); - - animator->StartAnimation(new LayerAnimationSequence( - LayerAnimationElement::CreateOpacityElement(1.0f, delta))); - - EXPECT_TRUE(observer_was_deleted); -} - - -TEST(LayerAnimatorTest, TestSetterRespectEnqueueStrategy) { - TestLayerAnimationDelegate delegate; - scoped_refptr<LayerAnimator> animator(LayerAnimator::CreateDefaultAnimator()); - animator->set_disable_timer_for_test(true); - - animator->SetDelegate(&delegate); - - float start_opacity = 0.0f; - float target_opacity = 1.0f; - float magic_opacity = 0.123f; - - delegate.SetOpacityFromAnimation(start_opacity); - - ScopedLayerAnimationSettings settings(animator.get()); - settings.SetPreemptionStrategy( - LayerAnimator::IMMEDIATELY_ANIMATE_TO_NEW_TARGET); - settings.SetTransitionDuration(base::TimeDelta::FromSeconds(1)); - animator->SetOpacity(target_opacity); - - EXPECT_EQ(start_opacity, delegate.GetOpacityForAnimation()); - - settings.SetPreemptionStrategy( - LayerAnimator::ENQUEUE_NEW_ANIMATION); - settings.SetTransitionDuration(base::TimeDelta()); - animator->SetOpacity(magic_opacity); - - EXPECT_EQ(start_opacity, delegate.GetOpacityForAnimation()); -} - -TEST(LayerAnimatorTest, TestScopedCounterAnimation) { - Layer parent, child; - parent.Add(&child); - - gfx::Transform parent_begin, parent_end; - - parent_end.Scale3d(2.0, 0.5, 1.0); - - // Parent animates from identity to the end value. The counter animation will - // start at the end value and animate back to identity. - gfx::Transform child_begin(parent_end); - - child.SetTransform(child_begin); - parent.SetTransform(parent_begin); - - EXPECT_FALSE(child.GetAnimator()->is_animating()); - - ScopedLayerAnimationSettings settings(parent.GetAnimator()); - settings.SetInverselyAnimatedBaseLayer(&parent); - settings.AddInverselyAnimatedLayer(&child); - - parent.SetTransform(parent_end); - - EXPECT_TRUE(child.GetAnimator()->is_animating()); - EXPECT_TRUE(child.GetTargetTransform().IsIdentity()) - << child.GetTargetTransform().ToString(); - -} - -class CollectionLayerAnimationDelegate : public TestLayerAnimationDelegate { - public: - CollectionLayerAnimationDelegate() : collection(NULL) {} - virtual ~CollectionLayerAnimationDelegate() {} - - // LayerAnimationDelegate: - virtual LayerAnimatorCollection* GetLayerAnimatorCollection() override { - return &collection; - } - - private: - LayerAnimatorCollection collection; -}; - -TEST(LayerAnimatorTest, LayerAnimatorCollectionTickTime) { - Layer layer; - LayerAnimator* animator = layer.GetAnimator(); - CollectionLayerAnimationDelegate delegate; - animator->SetDelegate(&delegate); - - LayerAnimatorCollection* collection = delegate.GetLayerAnimatorCollection(); - base::TimeTicks null; - collection->OnAnimationStep(null); - EXPECT_TRUE(collection->last_tick_time().is_null()); - - // Adding an animator to the collection should update the last tick time. - collection->StartAnimator(layer.GetAnimator()); - EXPECT_TRUE(collection->HasActiveAnimators()); - EXPECT_FALSE(collection->last_tick_time().is_null()); - - collection->StopAnimator(layer.GetAnimator()); - EXPECT_FALSE(collection->HasActiveAnimators()); -} - -TEST(LayerAnimatorTest, AnimatorStartedCorrectly) { - Layer layer; - LayerAnimatorTestController test_controller(layer.GetAnimator()); - LayerAnimator* animator = test_controller.animator(); - ASSERT_FALSE(animator->is_started_); - - TestLayerAnimationDelegate test_delegate; - animator->SetDelegate(&test_delegate); - double target_opacity = 1.0; - base::TimeDelta time_delta = base::TimeDelta::FromSeconds(1); - animator->ScheduleAnimation(new LayerAnimationSequence( - LayerAnimationElement::CreateOpacityElement(target_opacity, time_delta))); - EXPECT_FALSE(animator->is_started_); - - CollectionLayerAnimationDelegate collection_delegate; - animator->SetDelegate(&collection_delegate); - animator->UpdateAnimationState(); - EXPECT_TRUE(animator->is_started_); - animator->SetDelegate(NULL); -} - -TEST(LayerAnimatorTest, AnimatorRemovedFromCollectionWhenLayerIsDestroyed) { - scoped_ptr<Layer> layer(new Layer(LAYER_TEXTURED)); - LayerAnimatorTestController test_controller(layer->GetAnimator()); - scoped_refptr<LayerAnimator> animator = test_controller.animator(); - CollectionLayerAnimationDelegate collection_delegate; - animator->SetDelegate(&collection_delegate); - - double target_opacity = 1.0; - base::TimeDelta time_delta = base::TimeDelta::FromSeconds(1); - animator->ScheduleAnimation(new LayerAnimationSequence( - LayerAnimationElement::CreateOpacityElement(target_opacity, time_delta))); - - EXPECT_TRUE( - collection_delegate.GetLayerAnimatorCollection()->HasActiveAnimators()); - - layer.reset(); - EXPECT_EQ(NULL, animator->delegate()); - EXPECT_FALSE( - collection_delegate.GetLayerAnimatorCollection()->HasActiveAnimators()); -} - -TEST(LayerAnimatorTest, LayerMovedBetweenCompositorsDuringAnimation) { - bool enable_pixel_output = false; - ui::ContextFactory* context_factory = - InitializeContextFactoryForTests(enable_pixel_output); - const gfx::Rect bounds(10, 10, 100, 100); - scoped_ptr<TestCompositorHost> host_1( - TestCompositorHost::Create(bounds, context_factory)); - scoped_ptr<TestCompositorHost> host_2( - TestCompositorHost::Create(bounds, context_factory)); - host_1->Show(); - host_2->Show(); - - Compositor* compositor_1 = host_1->GetCompositor(); - Layer root_1; - compositor_1->SetRootLayer(&root_1); - - Compositor* compositor_2 = host_2->GetCompositor(); - Layer root_2; - compositor_2->SetRootLayer(&root_2); - - // Verify that neither compositor has active animators. - EXPECT_FALSE(compositor_1->layer_animator_collection()->HasActiveAnimators()); - EXPECT_FALSE(compositor_2->layer_animator_collection()->HasActiveAnimators()); - - Layer layer; - root_1.Add(&layer); - LayerAnimator* animator = layer.GetAnimator(); - double target_opacity = 1.0; - base::TimeDelta time_delta = base::TimeDelta::FromSeconds(1); - animator->ScheduleAnimation(new LayerAnimationSequence( - LayerAnimationElement::CreateOpacityElement(target_opacity, time_delta))); - EXPECT_TRUE(compositor_1->layer_animator_collection()->HasActiveAnimators()); - EXPECT_FALSE(compositor_2->layer_animator_collection()->HasActiveAnimators()); - - root_2.Add(&layer); - EXPECT_FALSE(compositor_1->layer_animator_collection()->HasActiveAnimators()); - EXPECT_TRUE(compositor_2->layer_animator_collection()->HasActiveAnimators()); - host_2.reset(); - host_1.reset(); - TerminateContextFactoryForTests(); -} - -} // namespace ui
diff --git a/ui/compositor/layer_delegate.h b/ui/compositor/layer_delegate.h deleted file mode 100644 index 9312e02..0000000 --- a/ui/compositor/layer_delegate.h +++ /dev/null
@@ -1,42 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_LAYER_DELEGATE_H_ -#define UI_COMPOSITOR_LAYER_DELEGATE_H_ - -#include "base/callback_forward.h" -#include "ui/compositor/compositor_export.h" - -namespace gfx { -class Canvas; -class Rect; -} - -namespace ui { - -// A delegate interface implemented by an object that renders to a Layer. -class COMPOSITOR_EXPORT LayerDelegate { - public: - // Paint content for the layer to the specified canvas. It has already been - // clipped to the Layer's invalid rect. - virtual void OnPaintLayer(gfx::Canvas* canvas) = 0; - - // A notification that this layer has had a delegated frame swap and - // will be repainted. - virtual void OnDelegatedFrameDamage(const gfx::Rect& damage_rect_in_dip) = 0; - - // Called when the layer's device scale factor has changed. - virtual void OnDeviceScaleFactorChanged(float device_scale_factor) = 0; - - // Invoked prior to the bounds changing. The returned closured is run after - // the bounds change. - virtual base::Closure PrepareForLayerBoundsChange() = 0; - - protected: - virtual ~LayerDelegate() {} -}; - -} // namespace ui - -#endif // UI_COMPOSITOR_LAYER_DELEGATE_H_
diff --git a/ui/compositor/layer_owner.cc b/ui/compositor/layer_owner.cc deleted file mode 100644 index cd614b3..0000000 --- a/ui/compositor/layer_owner.cc +++ /dev/null
@@ -1,88 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/compositor/layer_owner.h" - -#include "ui/compositor/layer_owner_delegate.h" - -namespace ui { - -LayerOwner::LayerOwner() : layer_(NULL), layer_owner_delegate_(NULL) { -} - -LayerOwner::~LayerOwner() { -} - -void LayerOwner::SetLayer(Layer* layer) { - DCHECK(!OwnsLayer()); - layer_owner_.reset(layer); - layer_ = layer; - layer_->owner_ = this; -} - -scoped_ptr<Layer> LayerOwner::AcquireLayer() { - if (layer_owner_) - layer_owner_->owner_ = NULL; - return layer_owner_.Pass(); -} - -scoped_ptr<Layer> LayerOwner::RecreateLayer() { - scoped_ptr<ui::Layer> old_layer(AcquireLayer()); - if (!old_layer) - return old_layer.Pass(); - - LayerDelegate* old_delegate = old_layer->delegate(); - old_layer->set_delegate(NULL); - - const gfx::Rect layer_bounds(old_layer->bounds()); - Layer* new_layer = new ui::Layer(old_layer->type()); - SetLayer(new_layer); - new_layer->SetVisible(old_layer->GetTargetVisibility()); - new_layer->SetOpacity(old_layer->GetTargetOpacity()); - new_layer->SetBounds(layer_bounds); - new_layer->SetMasksToBounds(old_layer->GetMasksToBounds()); - new_layer->set_name(old_layer->name()); - new_layer->SetFillsBoundsOpaquely(old_layer->fills_bounds_opaquely()); - new_layer->SetFillsBoundsCompletely(old_layer->FillsBoundsCompletely()); - new_layer->SetSubpixelPositionOffset(old_layer->subpixel_position_offset()); - SkRegion* alpha_shape = old_layer->alpha_shape(); - if (alpha_shape) - new_layer->SetAlphaShape(make_scoped_ptr(new SkRegion(*alpha_shape))); - - // Install new layer as a sibling of the old layer, stacked below it. - if (old_layer->parent()) { - old_layer->parent()->Add(new_layer); - old_layer->parent()->StackBelow(new_layer, old_layer.get()); - } - - // Migrate all the child layers over to the new layer. Copy the list because - // the items are removed during iteration. - std::vector<ui::Layer*> children_copy = old_layer->children(); - for (std::vector<ui::Layer*>::const_iterator it = children_copy.begin(); - it != children_copy.end(); - ++it) { - ui::Layer* child = *it; - new_layer->Add(child); - } - - // Install the delegate last so that the delegate isn't notified as we copy - // state to the new layer. - new_layer->set_delegate(old_delegate); - - if (layer_owner_delegate_) - layer_owner_delegate_->OnLayerRecreated(old_layer.get(), new_layer); - - return old_layer.Pass(); -} - -void LayerOwner::DestroyLayer() { - layer_ = NULL; - layer_owner_.reset(); -} - -bool LayerOwner::OwnsLayer() const { - return !!layer_owner_; -} - -} // namespace ui
diff --git a/ui/compositor/layer_owner.h b/ui/compositor/layer_owner.h deleted file mode 100644 index 27002e5..0000000 --- a/ui/compositor/layer_owner.h +++ /dev/null
@@ -1,66 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_LAYER_OWNER_H_ -#define UI_COMPOSITOR_LAYER_OWNER_H_ - -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "ui/compositor/compositor_export.h" -#include "ui/compositor/layer.h" - -namespace ui { -class LayerOwnerDelegate; - -class COMPOSITOR_EXPORT LayerOwner { - public: - LayerOwner(); - virtual ~LayerOwner(); - - void SetLayer(Layer* layer); - - // Releases the owning reference to its layer, and returns it. - // This is used when you need to animate the presentation of the owner just - // prior to destroying it. The Owner can be destroyed soon after calling this - // function, and the caller is then responsible for disposing of the layer - // once any animation completes. Note that layer() will remain valid until the - // end of ~LayerOwner(). - scoped_ptr<Layer> AcquireLayer(); - - // Asks the owner to recreate the layer, returning the old Layer. NULL is - // returned if there is no existing layer, or recreate is not supported. - // - // This does not recurse. Existing children of the layer are moved to the new - // layer. - scoped_ptr<Layer> RecreateLayer(); - - ui::Layer* layer() { return layer_; } - const ui::Layer* layer() const { return layer_; } - - void set_layer_owner_delegate(LayerOwnerDelegate* delegate) { - layer_owner_delegate_ = delegate; - } - - protected: - void DestroyLayer(); - - bool OwnsLayer() const; - - private: - // The LayerOwner owns its layer unless ownership is relinquished via a call - // to AcquireLayer(). After that moment |layer_| will still be valid but - // |layer_owner_| will be NULL. The reason for releasing ownership is that - // the client may wish to animate the layer beyond the lifetime of the owner, - // e.g. fading it out when it is destroyed. - scoped_ptr<Layer> layer_owner_; - Layer* layer_; - - LayerOwnerDelegate* layer_owner_delegate_; - - DISALLOW_COPY_AND_ASSIGN(LayerOwner); -}; - -} // namespace ui - -#endif // UI_COMPOSITOR_LAYER_OWNER_H_
diff --git a/ui/compositor/layer_owner_delegate.h b/ui/compositor/layer_owner_delegate.h deleted file mode 100644 index 68ba92e..0000000 --- a/ui/compositor/layer_owner_delegate.h +++ /dev/null
@@ -1,27 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_LAYER_OWNER_DELEGATE_H_ -#define UI_COMPOSITOR_LAYER_OWNER_DELEGATE_H_ - -#include "ui/compositor/compositor_export.h" - -namespace ui { -class Layer; - -// Called from RecreateLayer() after the new layer was created. old_layer is -// the layer that will be returned to the caller of RecreateLayer, new_layer -// will be the layer now used. Used when the layer has external content -// (SetTextureMailbox / SetDelegatedFrame was called). -class COMPOSITOR_EXPORT LayerOwnerDelegate { - public: - virtual void OnLayerRecreated(Layer* old_layer, Layer* new_layer) = 0; - - protected: - virtual ~LayerOwnerDelegate() {} -}; - -} // namespace ui - -#endif // UI_COMPOSITOR_LAYER_OWNER_DELEGATE_H_
diff --git a/ui/compositor/layer_owner_unittest.cc b/ui/compositor/layer_owner_unittest.cc deleted file mode 100644 index 6390eca..0000000 --- a/ui/compositor/layer_owner_unittest.cc +++ /dev/null
@@ -1,33 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/compositor/layer_owner.h" - -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/compositor/layer.h" -#include "ui/compositor/layer_animator.h" -#include "ui/compositor/scoped_layer_animation_settings.h" - -namespace ui { - -TEST(LayerOwnerTest, RecreateLayerHonorsTargetVisibilityAndOpacity) { - LayerOwner owner; - Layer* layer = new Layer; - layer->SetVisible(true); - layer->SetOpacity(1.0f); - - owner.SetLayer(layer); - - ScopedLayerAnimationSettings settings(layer->GetAnimator()); - layer->SetVisible(false); - layer->SetOpacity(0.0f); - EXPECT_TRUE(layer->visible()); - EXPECT_EQ(1.0f, layer->opacity()); - - scoped_ptr<Layer> old_layer(owner.RecreateLayer()); - EXPECT_FALSE(owner.layer()->visible()); - EXPECT_EQ(0.0f, owner.layer()->opacity()); -} - -} // namespace ui
diff --git a/ui/compositor/layer_tree_owner.cc b/ui/compositor/layer_tree_owner.cc deleted file mode 100644 index ebb0a7f..0000000 --- a/ui/compositor/layer_tree_owner.cc +++ /dev/null
@@ -1,34 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/compositor/layer_tree_owner.h" - -#include "ui/compositor/layer.h" - -namespace ui { - -namespace { - -// Deletes |layer| and all its descendants. -void DeepDeleteLayers(Layer* layer) { - std::vector<Layer*> children = layer->children(); - for (std::vector<Layer*>::const_iterator it = children.begin(); - it != children.end(); - ++it) { - Layer* child = *it; - DeepDeleteLayers(child); - } - delete layer; -} - -} // namespace - -LayerTreeOwner::LayerTreeOwner(Layer* root) : root_(root) {} - -LayerTreeOwner::~LayerTreeOwner() { - if (root_) - DeepDeleteLayers(root_); -} - -} // namespace ui
diff --git a/ui/compositor/layer_tree_owner.h b/ui/compositor/layer_tree_owner.h deleted file mode 100644 index 0b2c478..0000000 --- a/ui/compositor/layer_tree_owner.h +++ /dev/null
@@ -1,39 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_LAYER_TREE_OWNER_H_ -#define UI_COMPOSITOR_LAYER_TREE_OWNER_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "ui/compositor/compositor_export.h" - -namespace ui { - -class Layer; - -// Scoping object that owns a Layer and all its descendants. -class COMPOSITOR_EXPORT LayerTreeOwner { - public: - explicit LayerTreeOwner(Layer* root); - ~LayerTreeOwner(); - - Layer* release() WARN_UNUSED_RESULT { - Layer* root = root_; - root_ = NULL; - return root; - } - - Layer* root() { return root_; } - const Layer* root() const { return root_; } - - private: - Layer* root_; - - DISALLOW_COPY_AND_ASSIGN(LayerTreeOwner); -}; - -} // namespace - -#endif // UI_COMPOSITOR_LAYER_TREE_OWNER_H_
diff --git a/ui/compositor/layer_type.h b/ui/compositor/layer_type.h deleted file mode 100644 index 9831916..0000000 --- a/ui/compositor/layer_type.h +++ /dev/null
@@ -1,27 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_LAYER_TYPE_H_ -#define UI_COMPOSITOR_LAYER_TYPE_H_ - -namespace ui { - -enum LayerType { - // A layer that has no onscreen representation (note that its children will - // still be drawn, though). - LAYER_NOT_DRAWN = 0, - - // A layer that has a texture. - LAYER_TEXTURED = 1, - - // A layer that's drawn as a single color. - LAYER_SOLID_COLOR = 2, - - // A layer based on the NinePatchLayer class. - LAYER_NINE_PATCH = 3, -}; - -} // namespace ui - -#endif // UI_COMPOSITOR_LAYER_TYPE_H_
diff --git a/ui/compositor/layer_unittest.cc b/ui/compositor/layer_unittest.cc deleted file mode 100644 index 6ebe72b..0000000 --- a/ui/compositor/layer_unittest.cc +++ /dev/null
@@ -1,1754 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/basictypes.h" -#include "base/bind.h" -#include "base/compiler_specific.h" -#include "base/debug/trace_event.h" -#include "base/files/file_path.h" -#include "base/files/file_util.h" -#include "base/json/json_reader.h" -#include "base/memory/scoped_ptr.h" -#include "base/message_loop/message_loop.h" -#include "base/path_service.h" -#include "base/strings/string_util.h" -#include "base/strings/stringprintf.h" -#include "cc/layers/delegated_frame_provider.h" -#include "cc/layers/delegated_frame_resource_collection.h" -#include "cc/layers/layer.h" -#include "cc/output/copy_output_request.h" -#include "cc/output/copy_output_result.h" -#include "cc/output/delegated_frame_data.h" -#include "cc/test/pixel_test_utils.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/compositor/compositor_observer.h" -#include "ui/compositor/dip_util.h" -#include "ui/compositor/layer.h" -#include "ui/compositor/layer_animation_sequence.h" -#include "ui/compositor/layer_animator.h" -#include "ui/compositor/test/context_factories_for_test.h" -#include "ui/compositor/test/draw_waiter_for_test.h" -#include "ui/compositor/test/test_compositor_host.h" -#include "ui/compositor/test/test_layers.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/codec/png_codec.h" -#include "ui/gfx/gfx_paths.h" -#include "ui/gfx/skia_util.h" - -using cc::MatchesPNGFile; - -namespace ui { - -namespace { - -// There are three test classes in here that configure the Compositor and -// Layer's slightly differently: -// - LayerWithNullDelegateTest uses NullLayerDelegate as the LayerDelegate. This -// is typically the base class you want to use. -// - LayerWithDelegateTest uses LayerDelegate on the delegates. -// - LayerWithRealCompositorTest when a real compositor is required for testing. -// - Slow because they bring up a window and run the real compositor. This -// is typically not what you want. - -class ColoredLayer : public Layer, public LayerDelegate { - public: - explicit ColoredLayer(SkColor color) - : Layer(LAYER_TEXTURED), - color_(color) { - set_delegate(this); - } - - virtual ~ColoredLayer() { } - - // Overridden from LayerDelegate: - virtual void OnPaintLayer(gfx::Canvas* canvas) override { - canvas->DrawColor(color_); - } - - virtual void OnDelegatedFrameDamage( - const gfx::Rect& damage_rect_in_dip) override {} - - virtual void OnDeviceScaleFactorChanged(float device_scale_factor) override { - } - - virtual base::Closure PrepareForLayerBoundsChange() override { - return base::Closure(); - } - - private: - SkColor color_; -}; - -class LayerWithRealCompositorTest : public testing::Test { - public: - LayerWithRealCompositorTest() { - if (PathService::Get(gfx::DIR_TEST_DATA, &test_data_directory_)) { - test_data_directory_ = test_data_directory_.AppendASCII("compositor"); - } else { - LOG(ERROR) << "Could not open test data directory."; - } - } - virtual ~LayerWithRealCompositorTest() {} - - // Overridden from testing::Test: - virtual void SetUp() override { - bool enable_pixel_output = true; - ui::ContextFactory* context_factory = - InitializeContextFactoryForTests(enable_pixel_output); - - const gfx::Rect host_bounds(10, 10, 500, 500); - compositor_host_.reset( - TestCompositorHost::Create(host_bounds, context_factory)); - compositor_host_->Show(); - } - - virtual void TearDown() override { - compositor_host_.reset(); - TerminateContextFactoryForTests(); - } - - Compositor* GetCompositor() { return compositor_host_->GetCompositor(); } - - Layer* CreateLayer(LayerType type) { - return new Layer(type); - } - - Layer* CreateColorLayer(SkColor color, const gfx::Rect& bounds) { - Layer* layer = new ColoredLayer(color); - layer->SetBounds(bounds); - return layer; - } - - Layer* CreateNoTextureLayer(const gfx::Rect& bounds) { - Layer* layer = CreateLayer(LAYER_NOT_DRAWN); - layer->SetBounds(bounds); - return layer; - } - - void DrawTree(Layer* root) { - GetCompositor()->SetRootLayer(root); - GetCompositor()->ScheduleDraw(); - WaitForDraw(); - } - - void ReadPixels(SkBitmap* bitmap) { - ReadPixels(bitmap, gfx::Rect(GetCompositor()->size())); - } - - void ReadPixels(SkBitmap* bitmap, gfx::Rect source_rect) { - scoped_refptr<ReadbackHolder> holder(new ReadbackHolder); - scoped_ptr<cc::CopyOutputRequest> request = - cc::CopyOutputRequest::CreateBitmapRequest( - base::Bind(&ReadbackHolder::OutputRequestCallback, holder)); - request->set_area(source_rect); - - GetCompositor()->root_layer()->RequestCopyOfOutput(request.Pass()); - - // Wait for copy response. This needs to wait as the compositor could - // be in the middle of a draw right now, and the commit with the - // copy output request may not be done on the first draw. - for (int i = 0; i < 2; i++) { - GetCompositor()->ScheduleDraw(); - WaitForDraw(); - } - - // Waits for the callback to finish run and return result. - holder->WaitForReadback(); - - *bitmap = holder->result(); - } - - void WaitForDraw() { ui::DrawWaiterForTest::Wait(GetCompositor()); } - - void WaitForCommit() { - ui::DrawWaiterForTest::WaitForCommit(GetCompositor()); - } - - // Invalidates the entire contents of the layer. - void SchedulePaintForLayer(Layer* layer) { - layer->SchedulePaint( - gfx::Rect(0, 0, layer->bounds().width(), layer->bounds().height())); - } - - const base::FilePath& test_data_directory() const { - return test_data_directory_; - } - - private: - class ReadbackHolder : public base::RefCountedThreadSafe<ReadbackHolder> { - public: - ReadbackHolder() : run_loop_(new base::RunLoop) {} - - void OutputRequestCallback(scoped_ptr<cc::CopyOutputResult> result) { - result_ = result->TakeBitmap(); - run_loop_->Quit(); - } - - void WaitForReadback() { run_loop_->Run(); } - - const SkBitmap& result() const { return *result_; } - - private: - friend class base::RefCountedThreadSafe<ReadbackHolder>; - - virtual ~ReadbackHolder() {} - - scoped_ptr<SkBitmap> result_; - scoped_ptr<base::RunLoop> run_loop_; - }; - - scoped_ptr<TestCompositorHost> compositor_host_; - - // The root directory for test files. - base::FilePath test_data_directory_; - - DISALLOW_COPY_AND_ASSIGN(LayerWithRealCompositorTest); -}; - -// LayerDelegate that paints colors to the layer. -class TestLayerDelegate : public LayerDelegate { - public: - explicit TestLayerDelegate() { reset(); } - virtual ~TestLayerDelegate() {} - - void AddColor(SkColor color) { - colors_.push_back(color); - } - - const gfx::Size& paint_size() const { return paint_size_; } - int color_index() const { return color_index_; } - - std::string ToScaleString() const { - return base::StringPrintf("%.1f %.1f", scale_x_, scale_y_); - } - - float device_scale_factor() const { - return device_scale_factor_; - } - - // Overridden from LayerDelegate: - virtual void OnPaintLayer(gfx::Canvas* canvas) override { - SkISize size = canvas->sk_canvas()->getBaseLayerSize(); - paint_size_ = gfx::Size(size.width(), size.height()); - canvas->DrawColor(colors_[color_index_]); - color_index_ = (color_index_ + 1) % static_cast<int>(colors_.size()); - const SkMatrix& matrix = canvas->sk_canvas()->getTotalMatrix(); - scale_x_ = matrix.getScaleX(); - scale_y_ = matrix.getScaleY(); - } - - virtual void OnDelegatedFrameDamage( - const gfx::Rect& damage_rect_in_dip) override {} - - virtual void OnDeviceScaleFactorChanged(float device_scale_factor) override { - device_scale_factor_ = device_scale_factor; - } - - virtual base::Closure PrepareForLayerBoundsChange() override { - return base::Closure(); - } - - void reset() { - color_index_ = 0; - paint_size_.SetSize(0, 0); - scale_x_ = scale_y_ = 0.0f; - device_scale_factor_ = 0.0f; - } - - private: - std::vector<SkColor> colors_; - int color_index_; - gfx::Size paint_size_; - float scale_x_; - float scale_y_; - float device_scale_factor_; - - DISALLOW_COPY_AND_ASSIGN(TestLayerDelegate); -}; - -// LayerDelegate that verifies that a layer was asked to update its canvas. -class DrawTreeLayerDelegate : public LayerDelegate { - public: - DrawTreeLayerDelegate() : painted_(false) {} - virtual ~DrawTreeLayerDelegate() {} - - void Reset() { - painted_ = false; - } - - bool painted() const { return painted_; } - - private: - // Overridden from LayerDelegate: - virtual void OnPaintLayer(gfx::Canvas* canvas) override { - painted_ = true; - canvas->DrawColor(SK_ColorWHITE); - } - virtual void OnDelegatedFrameDamage( - const gfx::Rect& damage_rect_in_dip) override {} - virtual void OnDeviceScaleFactorChanged(float device_scale_factor) override { - } - virtual base::Closure PrepareForLayerBoundsChange() override { - return base::Closure(); - } - - bool painted_; - - DISALLOW_COPY_AND_ASSIGN(DrawTreeLayerDelegate); -}; - -// The simplest possible layer delegate. Does nothing. -class NullLayerDelegate : public LayerDelegate { - public: - NullLayerDelegate() {} - virtual ~NullLayerDelegate() {} - - private: - // Overridden from LayerDelegate: - virtual void OnPaintLayer(gfx::Canvas* canvas) override {} - virtual void OnDelegatedFrameDamage( - const gfx::Rect& damage_rect_in_dip) override {} - virtual void OnDeviceScaleFactorChanged(float device_scale_factor) override {} - virtual base::Closure PrepareForLayerBoundsChange() override { - return base::Closure(); - } - - DISALLOW_COPY_AND_ASSIGN(NullLayerDelegate); -}; - -// Remembers if it has been notified. -class TestCompositorObserver : public CompositorObserver { - public: - TestCompositorObserver() - : committed_(false), started_(false), ended_(false), aborted_(false) {} - - bool committed() const { return committed_; } - bool notified() const { return started_ && ended_; } - bool aborted() const { return aborted_; } - - void Reset() { - committed_ = false; - started_ = false; - ended_ = false; - aborted_ = false; - } - - private: - virtual void OnCompositingDidCommit(Compositor* compositor) override { - committed_ = true; - } - - virtual void OnCompositingStarted(Compositor* compositor, - base::TimeTicks start_time) override { - started_ = true; - } - - virtual void OnCompositingEnded(Compositor* compositor) override { - ended_ = true; - } - - virtual void OnCompositingAborted(Compositor* compositor) override { - aborted_ = true; - } - - virtual void OnCompositingLockStateChanged(Compositor* compositor) override { - } - - bool committed_; - bool started_; - bool ended_; - bool aborted_; - - DISALLOW_COPY_AND_ASSIGN(TestCompositorObserver); -}; - -} // namespace - -TEST_F(LayerWithRealCompositorTest, Draw) { - scoped_ptr<Layer> layer(CreateColorLayer(SK_ColorRED, - gfx::Rect(20, 20, 50, 50))); - DrawTree(layer.get()); -} - -// Create this hierarchy: -// L1 - red -// +-- L2 - blue -// | +-- L3 - yellow -// +-- L4 - magenta -// -TEST_F(LayerWithRealCompositorTest, Hierarchy) { - scoped_ptr<Layer> l1(CreateColorLayer(SK_ColorRED, - gfx::Rect(20, 20, 400, 400))); - scoped_ptr<Layer> l2(CreateColorLayer(SK_ColorBLUE, - gfx::Rect(10, 10, 350, 350))); - scoped_ptr<Layer> l3(CreateColorLayer(SK_ColorYELLOW, - gfx::Rect(5, 5, 25, 25))); - scoped_ptr<Layer> l4(CreateColorLayer(SK_ColorMAGENTA, - gfx::Rect(300, 300, 100, 100))); - - l1->Add(l2.get()); - l1->Add(l4.get()); - l2->Add(l3.get()); - - DrawTree(l1.get()); -} - -class LayerWithDelegateTest : public testing::Test { - public: - LayerWithDelegateTest() {} - virtual ~LayerWithDelegateTest() {} - - // Overridden from testing::Test: - virtual void SetUp() override { - bool enable_pixel_output = false; - ui::ContextFactory* context_factory = - InitializeContextFactoryForTests(enable_pixel_output); - - const gfx::Rect host_bounds(1000, 1000); - compositor_host_.reset(TestCompositorHost::Create(host_bounds, - context_factory)); - compositor_host_->Show(); - } - - virtual void TearDown() override { - compositor_host_.reset(); - TerminateContextFactoryForTests(); - } - - Compositor* compositor() { return compositor_host_->GetCompositor(); } - - virtual Layer* CreateLayer(LayerType type) { - return new Layer(type); - } - - Layer* CreateColorLayer(SkColor color, const gfx::Rect& bounds) { - Layer* layer = new ColoredLayer(color); - layer->SetBounds(bounds); - return layer; - } - - virtual Layer* CreateNoTextureLayer(const gfx::Rect& bounds) { - Layer* layer = CreateLayer(LAYER_NOT_DRAWN); - layer->SetBounds(bounds); - return layer; - } - - void DrawTree(Layer* root) { - compositor()->SetRootLayer(root); - Draw(); - } - - // Invalidates the entire contents of the layer. - void SchedulePaintForLayer(Layer* layer) { - layer->SchedulePaint( - gfx::Rect(0, 0, layer->bounds().width(), layer->bounds().height())); - } - - // Invokes DrawTree on the compositor. - void Draw() { - compositor()->ScheduleDraw(); - WaitForDraw(); - } - - void WaitForDraw() { DrawWaiterForTest::Wait(compositor()); } - - void WaitForCommit() { - DrawWaiterForTest::WaitForCommit(compositor()); - } - - private: - scoped_ptr<TestCompositorHost> compositor_host_; - - DISALLOW_COPY_AND_ASSIGN(LayerWithDelegateTest); -}; - -// L1 -// +-- L2 -TEST_F(LayerWithDelegateTest, ConvertPointToLayer_Simple) { - scoped_ptr<Layer> l1(CreateColorLayer(SK_ColorRED, - gfx::Rect(20, 20, 400, 400))); - scoped_ptr<Layer> l2(CreateColorLayer(SK_ColorBLUE, - gfx::Rect(10, 10, 350, 350))); - l1->Add(l2.get()); - DrawTree(l1.get()); - - gfx::Point point1_in_l2_coords(5, 5); - Layer::ConvertPointToLayer(l2.get(), l1.get(), &point1_in_l2_coords); - gfx::Point point1_in_l1_coords(15, 15); - EXPECT_EQ(point1_in_l1_coords, point1_in_l2_coords); - - gfx::Point point2_in_l1_coords(5, 5); - Layer::ConvertPointToLayer(l1.get(), l2.get(), &point2_in_l1_coords); - gfx::Point point2_in_l2_coords(-5, -5); - EXPECT_EQ(point2_in_l2_coords, point2_in_l1_coords); -} - -// L1 -// +-- L2 -// +-- L3 -TEST_F(LayerWithDelegateTest, ConvertPointToLayer_Medium) { - scoped_ptr<Layer> l1(CreateColorLayer(SK_ColorRED, - gfx::Rect(20, 20, 400, 400))); - scoped_ptr<Layer> l2(CreateColorLayer(SK_ColorBLUE, - gfx::Rect(10, 10, 350, 350))); - scoped_ptr<Layer> l3(CreateColorLayer(SK_ColorYELLOW, - gfx::Rect(10, 10, 100, 100))); - l1->Add(l2.get()); - l2->Add(l3.get()); - DrawTree(l1.get()); - - gfx::Point point1_in_l3_coords(5, 5); - Layer::ConvertPointToLayer(l3.get(), l1.get(), &point1_in_l3_coords); - gfx::Point point1_in_l1_coords(25, 25); - EXPECT_EQ(point1_in_l1_coords, point1_in_l3_coords); - - gfx::Point point2_in_l1_coords(5, 5); - Layer::ConvertPointToLayer(l1.get(), l3.get(), &point2_in_l1_coords); - gfx::Point point2_in_l3_coords(-15, -15); - EXPECT_EQ(point2_in_l3_coords, point2_in_l1_coords); -} - -TEST_F(LayerWithRealCompositorTest, Delegate) { - scoped_ptr<Layer> l1(CreateColorLayer(SK_ColorBLACK, - gfx::Rect(20, 20, 400, 400))); - GetCompositor()->SetRootLayer(l1.get()); - WaitForDraw(); - - TestLayerDelegate delegate; - l1->set_delegate(&delegate); - delegate.AddColor(SK_ColorWHITE); - delegate.AddColor(SK_ColorYELLOW); - delegate.AddColor(SK_ColorGREEN); - - l1->SchedulePaint(gfx::Rect(0, 0, 400, 400)); - WaitForDraw(); - - EXPECT_EQ(delegate.color_index(), 1); - EXPECT_EQ(delegate.paint_size(), l1->bounds().size()); - - l1->SchedulePaint(gfx::Rect(10, 10, 200, 200)); - WaitForDraw(); - EXPECT_EQ(delegate.color_index(), 2); - EXPECT_EQ(delegate.paint_size(), gfx::Size(200, 200)); - - l1->SchedulePaint(gfx::Rect(5, 5, 50, 50)); - WaitForDraw(); - EXPECT_EQ(delegate.color_index(), 0); - EXPECT_EQ(delegate.paint_size(), gfx::Size(50, 50)); -} - -TEST_F(LayerWithRealCompositorTest, DrawTree) { - scoped_ptr<Layer> l1(CreateColorLayer(SK_ColorRED, - gfx::Rect(20, 20, 400, 400))); - scoped_ptr<Layer> l2(CreateColorLayer(SK_ColorBLUE, - gfx::Rect(10, 10, 350, 350))); - scoped_ptr<Layer> l3(CreateColorLayer(SK_ColorYELLOW, - gfx::Rect(10, 10, 100, 100))); - l1->Add(l2.get()); - l2->Add(l3.get()); - - GetCompositor()->SetRootLayer(l1.get()); - WaitForDraw(); - - DrawTreeLayerDelegate d1; - l1->set_delegate(&d1); - DrawTreeLayerDelegate d2; - l2->set_delegate(&d2); - DrawTreeLayerDelegate d3; - l3->set_delegate(&d3); - - l2->SchedulePaint(gfx::Rect(5, 5, 5, 5)); - WaitForDraw(); - EXPECT_FALSE(d1.painted()); - EXPECT_TRUE(d2.painted()); - EXPECT_FALSE(d3.painted()); -} - -// Tests no-texture Layers. -// Create this hierarchy: -// L1 - red -// +-- L2 - NO TEXTURE -// | +-- L3 - yellow -// +-- L4 - magenta -// -TEST_F(LayerWithRealCompositorTest, HierarchyNoTexture) { - scoped_ptr<Layer> l1(CreateColorLayer(SK_ColorRED, - gfx::Rect(20, 20, 400, 400))); - scoped_ptr<Layer> l2(CreateNoTextureLayer(gfx::Rect(10, 10, 350, 350))); - scoped_ptr<Layer> l3(CreateColorLayer(SK_ColorYELLOW, - gfx::Rect(5, 5, 25, 25))); - scoped_ptr<Layer> l4(CreateColorLayer(SK_ColorMAGENTA, - gfx::Rect(300, 300, 100, 100))); - - l1->Add(l2.get()); - l1->Add(l4.get()); - l2->Add(l3.get()); - - GetCompositor()->SetRootLayer(l1.get()); - WaitForDraw(); - - DrawTreeLayerDelegate d2; - l2->set_delegate(&d2); - DrawTreeLayerDelegate d3; - l3->set_delegate(&d3); - - l2->SchedulePaint(gfx::Rect(5, 5, 5, 5)); - l3->SchedulePaint(gfx::Rect(5, 5, 5, 5)); - WaitForDraw(); - - // |d2| should not have received a paint notification since it has no texture. - EXPECT_FALSE(d2.painted()); - // |d3| should have received a paint notification. - EXPECT_TRUE(d3.painted()); -} - -class LayerWithNullDelegateTest : public LayerWithDelegateTest { - public: - LayerWithNullDelegateTest() {} - virtual ~LayerWithNullDelegateTest() {} - - virtual void SetUp() override { - LayerWithDelegateTest::SetUp(); - default_layer_delegate_.reset(new NullLayerDelegate()); - } - - virtual Layer* CreateLayer(LayerType type) override { - Layer* layer = new Layer(type); - layer->set_delegate(default_layer_delegate_.get()); - return layer; - } - - Layer* CreateTextureRootLayer(const gfx::Rect& bounds) { - Layer* layer = CreateTextureLayer(bounds); - compositor()->SetRootLayer(layer); - return layer; - } - - Layer* CreateTextureLayer(const gfx::Rect& bounds) { - Layer* layer = CreateLayer(LAYER_TEXTURED); - layer->SetBounds(bounds); - return layer; - } - - virtual Layer* CreateNoTextureLayer(const gfx::Rect& bounds) override { - Layer* layer = CreateLayer(LAYER_NOT_DRAWN); - layer->SetBounds(bounds); - return layer; - } - - private: - scoped_ptr<NullLayerDelegate> default_layer_delegate_; - - DISALLOW_COPY_AND_ASSIGN(LayerWithNullDelegateTest); -}; - -TEST_F(LayerWithNullDelegateTest, EscapedDebugNames) { - scoped_ptr<Layer> layer(CreateLayer(LAYER_NOT_DRAWN)); - std::string name = "\"\'\\/\b\f\n\r\t\n"; - layer->set_name(name); - scoped_refptr<base::debug::ConvertableToTraceFormat> debug_info = - layer->TakeDebugInfo(); - EXPECT_TRUE(!!debug_info.get()); - std::string json; - debug_info->AppendAsTraceFormat(&json); - base::JSONReader json_reader; - scoped_ptr<base::Value> debug_info_value(json_reader.ReadToValue(json)); - EXPECT_TRUE(!!debug_info_value); - EXPECT_TRUE(debug_info_value->IsType(base::Value::TYPE_DICTIONARY)); - base::DictionaryValue* dictionary = 0; - EXPECT_TRUE(debug_info_value->GetAsDictionary(&dictionary)); - std::string roundtrip; - EXPECT_TRUE(dictionary->GetString("layer_name", &roundtrip)); - EXPECT_EQ(name, roundtrip); -} - -void ReturnMailbox(bool* run, uint32 sync_point, bool is_lost) { - *run = true; -} - -TEST_F(LayerWithNullDelegateTest, SwitchLayerPreservesCCLayerState) { - scoped_ptr<Layer> l1(CreateLayer(LAYER_SOLID_COLOR)); - l1->SetFillsBoundsOpaquely(true); - l1->SetForceRenderSurface(true); - l1->SetVisible(false); - - EXPECT_EQ(gfx::Point3F(), l1->cc_layer()->transform_origin()); - EXPECT_TRUE(l1->cc_layer()->DrawsContent()); - EXPECT_TRUE(l1->cc_layer()->contents_opaque()); - EXPECT_TRUE(l1->cc_layer()->force_render_surface()); - EXPECT_TRUE(l1->cc_layer()->hide_layer_and_subtree()); - - cc::Layer* before_layer = l1->cc_layer(); - - bool callback1_run = false; - cc::TextureMailbox mailbox(gpu::Mailbox::Generate(), 0, 0); - l1->SetTextureMailbox(mailbox, - cc::SingleReleaseCallback::Create( - base::Bind(ReturnMailbox, &callback1_run)), - gfx::Size(1, 1)); - - EXPECT_NE(before_layer, l1->cc_layer()); - - EXPECT_EQ(gfx::Point3F(), l1->cc_layer()->transform_origin()); - EXPECT_TRUE(l1->cc_layer()->DrawsContent()); - EXPECT_TRUE(l1->cc_layer()->contents_opaque()); - EXPECT_TRUE(l1->cc_layer()->force_render_surface()); - EXPECT_TRUE(l1->cc_layer()->hide_layer_and_subtree()); - EXPECT_FALSE(callback1_run); - - bool callback2_run = false; - mailbox = cc::TextureMailbox(gpu::Mailbox::Generate(), 0, 0); - l1->SetTextureMailbox(mailbox, - cc::SingleReleaseCallback::Create( - base::Bind(ReturnMailbox, &callback2_run)), - gfx::Size(1, 1)); - EXPECT_TRUE(callback1_run); - EXPECT_FALSE(callback2_run); - - l1->SetShowSolidColorContent(); - EXPECT_EQ(gfx::Point3F(), l1->cc_layer()->transform_origin()); - EXPECT_TRUE(l1->cc_layer()->DrawsContent()); - EXPECT_TRUE(l1->cc_layer()->contents_opaque()); - EXPECT_TRUE(l1->cc_layer()->force_render_surface()); - EXPECT_TRUE(l1->cc_layer()->hide_layer_and_subtree()); - EXPECT_TRUE(callback2_run); -} - -// Various visibile/drawn assertions. -TEST_F(LayerWithNullDelegateTest, Visibility) { - scoped_ptr<Layer> l1(new Layer(LAYER_TEXTURED)); - scoped_ptr<Layer> l2(new Layer(LAYER_TEXTURED)); - scoped_ptr<Layer> l3(new Layer(LAYER_TEXTURED)); - l1->Add(l2.get()); - l2->Add(l3.get()); - - NullLayerDelegate delegate; - l1->set_delegate(&delegate); - l2->set_delegate(&delegate); - l3->set_delegate(&delegate); - - // Layers should initially be drawn. - EXPECT_TRUE(l1->IsDrawn()); - EXPECT_TRUE(l2->IsDrawn()); - EXPECT_TRUE(l3->IsDrawn()); - EXPECT_FALSE(l1->cc_layer()->hide_layer_and_subtree()); - EXPECT_FALSE(l2->cc_layer()->hide_layer_and_subtree()); - EXPECT_FALSE(l3->cc_layer()->hide_layer_and_subtree()); - - compositor()->SetRootLayer(l1.get()); - - Draw(); - - l1->SetVisible(false); - EXPECT_FALSE(l1->IsDrawn()); - EXPECT_FALSE(l2->IsDrawn()); - EXPECT_FALSE(l3->IsDrawn()); - EXPECT_TRUE(l1->cc_layer()->hide_layer_and_subtree()); - EXPECT_FALSE(l2->cc_layer()->hide_layer_and_subtree()); - EXPECT_FALSE(l3->cc_layer()->hide_layer_and_subtree()); - - l3->SetVisible(false); - EXPECT_FALSE(l1->IsDrawn()); - EXPECT_FALSE(l2->IsDrawn()); - EXPECT_FALSE(l3->IsDrawn()); - EXPECT_TRUE(l1->cc_layer()->hide_layer_and_subtree()); - EXPECT_FALSE(l2->cc_layer()->hide_layer_and_subtree()); - EXPECT_TRUE(l3->cc_layer()->hide_layer_and_subtree()); - - l1->SetVisible(true); - EXPECT_TRUE(l1->IsDrawn()); - EXPECT_TRUE(l2->IsDrawn()); - EXPECT_FALSE(l3->IsDrawn()); - EXPECT_FALSE(l1->cc_layer()->hide_layer_and_subtree()); - EXPECT_FALSE(l2->cc_layer()->hide_layer_and_subtree()); - EXPECT_TRUE(l3->cc_layer()->hide_layer_and_subtree()); -} - -// Checks that stacking-related methods behave as advertised. -TEST_F(LayerWithNullDelegateTest, Stacking) { - scoped_ptr<Layer> root(new Layer(LAYER_NOT_DRAWN)); - scoped_ptr<Layer> l1(new Layer(LAYER_TEXTURED)); - scoped_ptr<Layer> l2(new Layer(LAYER_TEXTURED)); - scoped_ptr<Layer> l3(new Layer(LAYER_TEXTURED)); - l1->set_name("1"); - l2->set_name("2"); - l3->set_name("3"); - root->Add(l3.get()); - root->Add(l2.get()); - root->Add(l1.get()); - - // Layers' children are stored in bottom-to-top order. - EXPECT_EQ("3 2 1", test::ChildLayerNamesAsString(*root.get())); - - root->StackAtTop(l3.get()); - EXPECT_EQ("2 1 3", test::ChildLayerNamesAsString(*root.get())); - - root->StackAtTop(l1.get()); - EXPECT_EQ("2 3 1", test::ChildLayerNamesAsString(*root.get())); - - root->StackAtTop(l1.get()); - EXPECT_EQ("2 3 1", test::ChildLayerNamesAsString(*root.get())); - - root->StackAbove(l2.get(), l3.get()); - EXPECT_EQ("3 2 1", test::ChildLayerNamesAsString(*root.get())); - - root->StackAbove(l1.get(), l3.get()); - EXPECT_EQ("3 1 2", test::ChildLayerNamesAsString(*root.get())); - - root->StackAbove(l2.get(), l1.get()); - EXPECT_EQ("3 1 2", test::ChildLayerNamesAsString(*root.get())); - - root->StackAtBottom(l2.get()); - EXPECT_EQ("2 3 1", test::ChildLayerNamesAsString(*root.get())); - - root->StackAtBottom(l3.get()); - EXPECT_EQ("3 2 1", test::ChildLayerNamesAsString(*root.get())); - - root->StackAtBottom(l3.get()); - EXPECT_EQ("3 2 1", test::ChildLayerNamesAsString(*root.get())); - - root->StackBelow(l2.get(), l3.get()); - EXPECT_EQ("2 3 1", test::ChildLayerNamesAsString(*root.get())); - - root->StackBelow(l1.get(), l3.get()); - EXPECT_EQ("2 1 3", test::ChildLayerNamesAsString(*root.get())); - - root->StackBelow(l3.get(), l2.get()); - EXPECT_EQ("3 2 1", test::ChildLayerNamesAsString(*root.get())); - - root->StackBelow(l3.get(), l2.get()); - EXPECT_EQ("3 2 1", test::ChildLayerNamesAsString(*root.get())); - - root->StackBelow(l3.get(), l1.get()); - EXPECT_EQ("2 3 1", test::ChildLayerNamesAsString(*root.get())); -} - -// Verifies SetBounds triggers the appropriate painting/drawing. -TEST_F(LayerWithNullDelegateTest, SetBoundsSchedulesPaint) { - scoped_ptr<Layer> l1(CreateTextureLayer(gfx::Rect(0, 0, 200, 200))); - compositor()->SetRootLayer(l1.get()); - - Draw(); - - l1->SetBounds(gfx::Rect(5, 5, 200, 200)); - - // The CompositorDelegate (us) should have been told to draw for a move. - WaitForDraw(); - - l1->SetBounds(gfx::Rect(5, 5, 100, 100)); - - // The CompositorDelegate (us) should have been told to draw for a resize. - WaitForDraw(); -} - -void ExpectRgba(int x, int y, SkColor expected_color, SkColor actual_color) { - EXPECT_EQ(expected_color, actual_color) - << "Pixel error at x=" << x << " y=" << y << "; " - << "actual RGBA=(" - << SkColorGetR(actual_color) << "," - << SkColorGetG(actual_color) << "," - << SkColorGetB(actual_color) << "," - << SkColorGetA(actual_color) << "); " - << "expected RGBA=(" - << SkColorGetR(expected_color) << "," - << SkColorGetG(expected_color) << "," - << SkColorGetB(expected_color) << "," - << SkColorGetA(expected_color) << ")"; -} - -// Checks that pixels are actually drawn to the screen with a read back. -TEST_F(LayerWithRealCompositorTest, DrawPixels) { - gfx::Size viewport_size = GetCompositor()->size(); - - // The window should be some non-trivial size but may not be exactly - // 500x500 on all platforms/bots. - EXPECT_GE(viewport_size.width(), 200); - EXPECT_GE(viewport_size.height(), 200); - - int blue_height = 10; - - scoped_ptr<Layer> layer( - CreateColorLayer(SK_ColorRED, gfx::Rect(viewport_size))); - scoped_ptr<Layer> layer2( - CreateColorLayer(SK_ColorBLUE, - gfx::Rect(0, 0, viewport_size.width(), blue_height))); - - layer->Add(layer2.get()); - - DrawTree(layer.get()); - - SkBitmap bitmap; - ReadPixels(&bitmap, gfx::Rect(viewport_size)); - ASSERT_FALSE(bitmap.empty()); - - SkAutoLockPixels lock(bitmap); - for (int x = 0; x < viewport_size.width(); x++) { - for (int y = 0; y < viewport_size.height(); y++) { - SkColor actual_color = bitmap.getColor(x, y); - SkColor expected_color = y < blue_height ? SK_ColorBLUE : SK_ColorRED; - ExpectRgba(x, y, expected_color, actual_color); - } - } -} - -// Checks that drawing a layer with transparent pixels is blended correctly -// with the lower layer. -TEST_F(LayerWithRealCompositorTest, DrawAlphaBlendedPixels) { - gfx::Size viewport_size = GetCompositor()->size(); - - int test_size = 200; - EXPECT_GE(viewport_size.width(), test_size); - EXPECT_GE(viewport_size.height(), test_size); - - // Blue with a wee bit of transparency. - SkColor blue_with_alpha = SkColorSetARGBInline(40, 10, 20, 200); - SkColor blend_color = SkColorSetARGBInline(255, 216, 3, 32); - - scoped_ptr<Layer> background_layer( - CreateColorLayer(SK_ColorRED, gfx::Rect(viewport_size))); - scoped_ptr<Layer> foreground_layer( - CreateColorLayer(blue_with_alpha, gfx::Rect(viewport_size))); - - // This must be set to false for layers with alpha to be blended correctly. - foreground_layer->SetFillsBoundsOpaquely(false); - - background_layer->Add(foreground_layer.get()); - DrawTree(background_layer.get()); - - SkBitmap bitmap; - ReadPixels(&bitmap, gfx::Rect(viewport_size)); - ASSERT_FALSE(bitmap.empty()); - - SkAutoLockPixels lock(bitmap); - for (int x = 0; x < test_size; x++) { - for (int y = 0; y < test_size; y++) { - SkColor actual_color = bitmap.getColor(x, y); - ExpectRgba(x, y, blend_color, actual_color); - } - } -} - -// Checks that using the AlphaShape filter applied to a layer with -// transparency, alpha-blends properly with the layer below. -TEST_F(LayerWithRealCompositorTest, DrawAlphaThresholdFilterPixels) { - gfx::Size viewport_size = GetCompositor()->size(); - - int test_size = 200; - EXPECT_GE(viewport_size.width(), test_size); - EXPECT_GE(viewport_size.height(), test_size); - - int blue_height = 10; - SkColor blue_with_alpha = SkColorSetARGBInline(40, 0, 0, 255); - SkColor blend_color = SkColorSetARGBInline(255, 215, 0, 40); - - scoped_ptr<Layer> background_layer( - CreateColorLayer(SK_ColorRED, gfx::Rect(viewport_size))); - scoped_ptr<Layer> foreground_layer( - CreateColorLayer(blue_with_alpha, gfx::Rect(viewport_size))); - - // Add a shape to restrict the visible part of the layer. - SkRegion shape; - shape.setRect(0, 0, viewport_size.width(), blue_height); - foreground_layer->SetAlphaShape(make_scoped_ptr(new SkRegion(shape))); - - foreground_layer->SetFillsBoundsOpaquely(false); - - background_layer->Add(foreground_layer.get()); - DrawTree(background_layer.get()); - - SkBitmap bitmap; - ReadPixels(&bitmap, gfx::Rect(viewport_size)); - ASSERT_FALSE(bitmap.empty()); - - SkAutoLockPixels lock(bitmap); - for (int x = 0; x < test_size; x++) { - for (int y = 0; y < test_size; y++) { - SkColor actual_color = bitmap.getColor(x, y); - ExpectRgba(x, y, actual_color, - y < blue_height ? blend_color : SK_ColorRED); - } - } -} - -// Checks the logic around Compositor::SetRootLayer and Layer::SetCompositor. -TEST_F(LayerWithRealCompositorTest, SetRootLayer) { - Compositor* compositor = GetCompositor(); - scoped_ptr<Layer> l1(CreateColorLayer(SK_ColorRED, - gfx::Rect(20, 20, 400, 400))); - scoped_ptr<Layer> l2(CreateColorLayer(SK_ColorBLUE, - gfx::Rect(10, 10, 350, 350))); - - EXPECT_EQ(NULL, l1->GetCompositor()); - EXPECT_EQ(NULL, l2->GetCompositor()); - - compositor->SetRootLayer(l1.get()); - EXPECT_EQ(compositor, l1->GetCompositor()); - - l1->Add(l2.get()); - EXPECT_EQ(compositor, l2->GetCompositor()); - - l1->Remove(l2.get()); - EXPECT_EQ(NULL, l2->GetCompositor()); - - l1->Add(l2.get()); - EXPECT_EQ(compositor, l2->GetCompositor()); - - compositor->SetRootLayer(NULL); - EXPECT_EQ(NULL, l1->GetCompositor()); - EXPECT_EQ(NULL, l2->GetCompositor()); -} - -// Checks that compositor observers are notified when: -// - DrawTree is called, -// - After ScheduleDraw is called, or -// - Whenever SetBounds, SetOpacity or SetTransform are called. -// TODO(vollick): could be reorganized into compositor_unittest.cc -TEST_F(LayerWithRealCompositorTest, CompositorObservers) { - scoped_ptr<Layer> l1(CreateColorLayer(SK_ColorRED, - gfx::Rect(20, 20, 400, 400))); - scoped_ptr<Layer> l2(CreateColorLayer(SK_ColorBLUE, - gfx::Rect(10, 10, 350, 350))); - l1->Add(l2.get()); - TestCompositorObserver observer; - GetCompositor()->AddObserver(&observer); - - // Explicitly called DrawTree should cause the observers to be notified. - // NOTE: this call to DrawTree sets l1 to be the compositor's root layer. - DrawTree(l1.get()); - EXPECT_TRUE(observer.notified()); - - // ScheduleDraw without any visible change should cause a commit. - observer.Reset(); - l1->ScheduleDraw(); - WaitForCommit(); - EXPECT_TRUE(observer.committed()); - - // Moving, but not resizing, a layer should alert the observers. - observer.Reset(); - l2->SetBounds(gfx::Rect(0, 0, 350, 350)); - WaitForDraw(); - EXPECT_TRUE(observer.notified()); - - // So should resizing a layer. - observer.Reset(); - l2->SetBounds(gfx::Rect(0, 0, 400, 400)); - WaitForDraw(); - EXPECT_TRUE(observer.notified()); - - // Opacity changes should alert the observers. - observer.Reset(); - l2->SetOpacity(0.5f); - WaitForDraw(); - EXPECT_TRUE(observer.notified()); - - // So should setting the opacity back. - observer.Reset(); - l2->SetOpacity(1.0f); - WaitForDraw(); - EXPECT_TRUE(observer.notified()); - - // Setting the transform of a layer should alert the observers. - observer.Reset(); - gfx::Transform transform; - transform.Translate(200.0, 200.0); - transform.Rotate(90.0); - transform.Translate(-200.0, -200.0); - l2->SetTransform(transform); - WaitForDraw(); - EXPECT_TRUE(observer.notified()); - - // A change resulting in an aborted swap buffer should alert the observer - // and also signal an abort. - observer.Reset(); - l2->SetOpacity(0.1f); - GetCompositor()->DidAbortSwapBuffers(); - WaitForDraw(); - EXPECT_TRUE(observer.notified()); - EXPECT_TRUE(observer.aborted()); - - GetCompositor()->RemoveObserver(&observer); - - // Opacity changes should no longer alert the removed observer. - observer.Reset(); - l2->SetOpacity(0.5f); - WaitForDraw(); - - EXPECT_FALSE(observer.notified()); -} - -// Checks that modifying the hierarchy correctly affects final composite. -TEST_F(LayerWithRealCompositorTest, ModifyHierarchy) { - GetCompositor()->SetScaleAndSize(1.0f, gfx::Size(50, 50)); - - // l0 - // +-l11 - // | +-l21 - // +-l12 - scoped_ptr<Layer> l0(CreateColorLayer(SK_ColorRED, - gfx::Rect(0, 0, 50, 50))); - scoped_ptr<Layer> l11(CreateColorLayer(SK_ColorGREEN, - gfx::Rect(0, 0, 25, 25))); - scoped_ptr<Layer> l21(CreateColorLayer(SK_ColorMAGENTA, - gfx::Rect(0, 0, 15, 15))); - scoped_ptr<Layer> l12(CreateColorLayer(SK_ColorBLUE, - gfx::Rect(10, 10, 25, 25))); - - base::FilePath ref_img1 = - test_data_directory().AppendASCII("ModifyHierarchy1.png"); - base::FilePath ref_img2 = - test_data_directory().AppendASCII("ModifyHierarchy2.png"); - SkBitmap bitmap; - - l0->Add(l11.get()); - l11->Add(l21.get()); - l0->Add(l12.get()); - DrawTree(l0.get()); - ReadPixels(&bitmap); - ASSERT_FALSE(bitmap.empty()); - // WritePNGFile(bitmap, ref_img1); - EXPECT_TRUE(MatchesPNGFile(bitmap, ref_img1, cc::ExactPixelComparator(true))); - - l0->StackAtTop(l11.get()); - DrawTree(l0.get()); - ReadPixels(&bitmap); - ASSERT_FALSE(bitmap.empty()); - // WritePNGFile(bitmap, ref_img2); - EXPECT_TRUE(MatchesPNGFile(bitmap, ref_img2, cc::ExactPixelComparator(true))); - - // should restore to original configuration - l0->StackAbove(l12.get(), l11.get()); - DrawTree(l0.get()); - ReadPixels(&bitmap); - ASSERT_FALSE(bitmap.empty()); - EXPECT_TRUE(MatchesPNGFile(bitmap, ref_img1, cc::ExactPixelComparator(true))); - - // l11 back to front - l0->StackAtTop(l11.get()); - DrawTree(l0.get()); - ReadPixels(&bitmap); - ASSERT_FALSE(bitmap.empty()); - EXPECT_TRUE(MatchesPNGFile(bitmap, ref_img2, cc::ExactPixelComparator(true))); - - // should restore to original configuration - l0->StackAbove(l12.get(), l11.get()); - DrawTree(l0.get()); - ReadPixels(&bitmap); - ASSERT_FALSE(bitmap.empty()); - EXPECT_TRUE(MatchesPNGFile(bitmap, ref_img1, cc::ExactPixelComparator(true))); - - // l11 back to front - l0->StackAbove(l11.get(), l12.get()); - DrawTree(l0.get()); - ReadPixels(&bitmap); - ASSERT_FALSE(bitmap.empty()); - EXPECT_TRUE(MatchesPNGFile(bitmap, ref_img2, cc::ExactPixelComparator(true))); -} - -// Opacity is rendered correctly. -// Checks that modifying the hierarchy correctly affects final composite. -TEST_F(LayerWithRealCompositorTest, Opacity) { - GetCompositor()->SetScaleAndSize(1.0f, gfx::Size(50, 50)); - - // l0 - // +-l11 - scoped_ptr<Layer> l0(CreateColorLayer(SK_ColorRED, - gfx::Rect(0, 0, 50, 50))); - scoped_ptr<Layer> l11(CreateColorLayer(SK_ColorGREEN, - gfx::Rect(0, 0, 25, 25))); - - base::FilePath ref_img = test_data_directory().AppendASCII("Opacity.png"); - - l11->SetOpacity(0.75); - l0->Add(l11.get()); - DrawTree(l0.get()); - SkBitmap bitmap; - ReadPixels(&bitmap); - ASSERT_FALSE(bitmap.empty()); - // WritePNGFile(bitmap, ref_img); - EXPECT_TRUE(MatchesPNGFile(bitmap, ref_img, cc::ExactPixelComparator(true))); -} - -namespace { - -class SchedulePaintLayerDelegate : public LayerDelegate { - public: - SchedulePaintLayerDelegate() : paint_count_(0), layer_(NULL) {} - - virtual ~SchedulePaintLayerDelegate() {} - - void set_layer(Layer* layer) { - layer_ = layer; - layer_->set_delegate(this); - } - - void SetSchedulePaintRect(const gfx::Rect& rect) { - schedule_paint_rect_ = rect; - } - - int GetPaintCountAndClear() { - int value = paint_count_; - paint_count_ = 0; - return value; - } - - const gfx::RectF& last_clip_rect() const { return last_clip_rect_; } - - private: - // Overridden from LayerDelegate: - virtual void OnPaintLayer(gfx::Canvas* canvas) override { - paint_count_++; - if (!schedule_paint_rect_.IsEmpty()) { - layer_->SchedulePaint(schedule_paint_rect_); - schedule_paint_rect_ = gfx::Rect(); - } - SkRect sk_clip_rect; - if (canvas->sk_canvas()->getClipBounds(&sk_clip_rect)) - last_clip_rect_ = gfx::SkRectToRectF(sk_clip_rect); - } - - virtual void OnDelegatedFrameDamage( - const gfx::Rect& damage_rect_in_dip) override {} - - virtual void OnDeviceScaleFactorChanged(float device_scale_factor) override { - } - - virtual base::Closure PrepareForLayerBoundsChange() override { - return base::Closure(); - } - - int paint_count_; - Layer* layer_; - gfx::Rect schedule_paint_rect_; - gfx::RectF last_clip_rect_; - - DISALLOW_COPY_AND_ASSIGN(SchedulePaintLayerDelegate); -}; - -} // namespace - -// Verifies that if SchedulePaint is invoked during painting the layer is still -// marked dirty. -TEST_F(LayerWithDelegateTest, SchedulePaintFromOnPaintLayer) { - scoped_ptr<Layer> root(CreateColorLayer(SK_ColorRED, - gfx::Rect(0, 0, 500, 500))); - SchedulePaintLayerDelegate child_delegate; - scoped_ptr<Layer> child(CreateColorLayer(SK_ColorBLUE, - gfx::Rect(0, 0, 200, 200))); - child_delegate.set_layer(child.get()); - - root->Add(child.get()); - - SchedulePaintForLayer(root.get()); - DrawTree(root.get()); - child->SchedulePaint(gfx::Rect(0, 0, 20, 20)); - EXPECT_EQ(1, child_delegate.GetPaintCountAndClear()); - - // Set a rect so that when OnPaintLayer() is invoked SchedulePaint is invoked - // again. - child_delegate.SetSchedulePaintRect(gfx::Rect(10, 10, 30, 30)); - WaitForCommit(); - EXPECT_EQ(1, child_delegate.GetPaintCountAndClear()); - - // Because SchedulePaint() was invoked from OnPaintLayer() |child| should - // still need to be painted. - WaitForCommit(); - EXPECT_EQ(1, child_delegate.GetPaintCountAndClear()); - EXPECT_TRUE(child_delegate.last_clip_rect().Contains( - gfx::Rect(10, 10, 30, 30))); -} - -TEST_F(LayerWithRealCompositorTest, ScaleUpDown) { - scoped_ptr<Layer> root(CreateColorLayer(SK_ColorWHITE, - gfx::Rect(10, 20, 200, 220))); - TestLayerDelegate root_delegate; - root_delegate.AddColor(SK_ColorWHITE); - root->set_delegate(&root_delegate); - - scoped_ptr<Layer> l1(CreateColorLayer(SK_ColorWHITE, - gfx::Rect(10, 20, 140, 180))); - TestLayerDelegate l1_delegate; - l1_delegate.AddColor(SK_ColorWHITE); - l1->set_delegate(&l1_delegate); - - GetCompositor()->SetScaleAndSize(1.0f, gfx::Size(500, 500)); - GetCompositor()->SetRootLayer(root.get()); - root->Add(l1.get()); - WaitForDraw(); - - EXPECT_EQ("10,20 200x220", root->bounds().ToString()); - EXPECT_EQ("10,20 140x180", l1->bounds().ToString()); - gfx::Size cc_bounds_size = root->cc_layer()->bounds(); - EXPECT_EQ("200x220", cc_bounds_size.ToString()); - cc_bounds_size = l1->cc_layer()->bounds(); - EXPECT_EQ("140x180", cc_bounds_size.ToString()); - // No scale change, so no scale notification. - EXPECT_EQ(0.0f, root_delegate.device_scale_factor()); - EXPECT_EQ(0.0f, l1_delegate.device_scale_factor()); - - EXPECT_EQ("200x220", root_delegate.paint_size().ToString()); - EXPECT_EQ("140x180", l1_delegate.paint_size().ToString()); - - // Scale up to 2.0. Changing scale doesn't change the bounds in DIP. - GetCompositor()->SetScaleAndSize(2.0f, gfx::Size(500, 500)); - EXPECT_EQ("10,20 200x220", root->bounds().ToString()); - EXPECT_EQ("10,20 140x180", l1->bounds().ToString()); - // CC layer should still match the UI layer bounds. - cc_bounds_size = root->cc_layer()->bounds(); - EXPECT_EQ("200x220", cc_bounds_size.ToString()); - cc_bounds_size = l1->cc_layer()->bounds(); - EXPECT_EQ("140x180", cc_bounds_size.ToString()); - // New scale factor must have been notified. - EXPECT_EQ(2.0f, root_delegate.device_scale_factor()); - EXPECT_EQ(2.0f, l1_delegate.device_scale_factor()); - - // Canvas size must have been scaled down up. - WaitForDraw(); - EXPECT_EQ("400x440", root_delegate.paint_size().ToString()); - EXPECT_EQ("2.0 2.0", root_delegate.ToScaleString()); - EXPECT_EQ("280x360", l1_delegate.paint_size().ToString()); - EXPECT_EQ("2.0 2.0", l1_delegate.ToScaleString()); - - // Scale down back to 1.0f. - GetCompositor()->SetScaleAndSize(1.0f, gfx::Size(500, 500)); - EXPECT_EQ("10,20 200x220", root->bounds().ToString()); - EXPECT_EQ("10,20 140x180", l1->bounds().ToString()); - // CC layer should still match the UI layer bounds. - cc_bounds_size = root->cc_layer()->bounds(); - EXPECT_EQ("200x220", cc_bounds_size.ToString()); - cc_bounds_size = l1->cc_layer()->bounds(); - EXPECT_EQ("140x180", cc_bounds_size.ToString()); - // New scale factor must have been notified. - EXPECT_EQ(1.0f, root_delegate.device_scale_factor()); - EXPECT_EQ(1.0f, l1_delegate.device_scale_factor()); - - // Canvas size must have been scaled down too. - WaitForDraw(); - EXPECT_EQ("200x220", root_delegate.paint_size().ToString()); - EXPECT_EQ("1.0 1.0", root_delegate.ToScaleString()); - EXPECT_EQ("140x180", l1_delegate.paint_size().ToString()); - EXPECT_EQ("1.0 1.0", l1_delegate.ToScaleString()); - - root_delegate.reset(); - l1_delegate.reset(); - // Just changing the size shouldn't notify the scale change nor - // trigger repaint. - GetCompositor()->SetScaleAndSize(1.0f, gfx::Size(1000, 1000)); - // No scale change, so no scale notification. - EXPECT_EQ(0.0f, root_delegate.device_scale_factor()); - EXPECT_EQ(0.0f, l1_delegate.device_scale_factor()); - WaitForDraw(); - EXPECT_EQ("0x0", root_delegate.paint_size().ToString()); - EXPECT_EQ("0.0 0.0", root_delegate.ToScaleString()); - EXPECT_EQ("0x0", l1_delegate.paint_size().ToString()); - EXPECT_EQ("0.0 0.0", l1_delegate.ToScaleString()); -} - -TEST_F(LayerWithRealCompositorTest, ScaleReparent) { - scoped_ptr<Layer> root(CreateColorLayer(SK_ColorWHITE, - gfx::Rect(10, 20, 200, 220))); - scoped_ptr<Layer> l1(CreateColorLayer(SK_ColorWHITE, - gfx::Rect(10, 20, 140, 180))); - TestLayerDelegate l1_delegate; - l1_delegate.AddColor(SK_ColorWHITE); - l1->set_delegate(&l1_delegate); - - GetCompositor()->SetScaleAndSize(1.0f, gfx::Size(500, 500)); - GetCompositor()->SetRootLayer(root.get()); - WaitForDraw(); - - root->Add(l1.get()); - EXPECT_EQ("10,20 140x180", l1->bounds().ToString()); - gfx::Size cc_bounds_size = l1->cc_layer()->bounds(); - EXPECT_EQ("140x180", cc_bounds_size.ToString()); - EXPECT_EQ(0.0f, l1_delegate.device_scale_factor()); - - WaitForDraw(); - EXPECT_EQ("140x180", l1_delegate.paint_size().ToString()); - EXPECT_EQ("1.0 1.0", l1_delegate.ToScaleString()); - - // Remove l1 from root and change the scale. - root->Remove(l1.get()); - EXPECT_EQ(NULL, l1->parent()); - EXPECT_EQ(NULL, l1->GetCompositor()); - GetCompositor()->SetScaleAndSize(2.0f, gfx::Size(500, 500)); - // Sanity check on root and l1. - EXPECT_EQ("10,20 200x220", root->bounds().ToString()); - cc_bounds_size = l1->cc_layer()->bounds(); - EXPECT_EQ("140x180", cc_bounds_size.ToString()); - - root->Add(l1.get()); - EXPECT_EQ("10,20 140x180", l1->bounds().ToString()); - cc_bounds_size = l1->cc_layer()->bounds(); - EXPECT_EQ("140x180", cc_bounds_size.ToString()); - EXPECT_EQ(2.0f, l1_delegate.device_scale_factor()); - WaitForDraw(); - EXPECT_EQ("280x360", l1_delegate.paint_size().ToString()); - EXPECT_EQ("2.0 2.0", l1_delegate.ToScaleString()); -} - -// Verifies that when changing bounds on a layer that is invisible, and then -// made visible, the right thing happens: -// - if just a move, then no painting should happen. -// - if a resize, the layer should be repainted. -TEST_F(LayerWithDelegateTest, SetBoundsWhenInvisible) { - scoped_ptr<Layer> root(CreateNoTextureLayer(gfx::Rect(0, 0, 1000, 1000))); - - scoped_ptr<Layer> child(CreateLayer(LAYER_TEXTURED)); - child->SetBounds(gfx::Rect(0, 0, 500, 500)); - DrawTreeLayerDelegate delegate; - child->set_delegate(&delegate); - root->Add(child.get()); - - // Paint once for initial damage. - child->SetVisible(true); - DrawTree(root.get()); - - // Reset into invisible state. - child->SetVisible(false); - DrawTree(root.get()); - delegate.Reset(); - - // Move layer. - child->SetBounds(gfx::Rect(200, 200, 500, 500)); - child->SetVisible(true); - DrawTree(root.get()); - EXPECT_FALSE(delegate.painted()); - - // Reset into invisible state. - child->SetVisible(false); - DrawTree(root.get()); - delegate.Reset(); - - // Resize layer. - child->SetBounds(gfx::Rect(200, 200, 400, 400)); - child->SetVisible(true); - DrawTree(root.get()); - EXPECT_TRUE(delegate.painted()); -} - -static scoped_ptr<cc::DelegatedFrameData> MakeFrameData(gfx::Size size) { - scoped_ptr<cc::DelegatedFrameData> frame_data(new cc::DelegatedFrameData); - scoped_ptr<cc::RenderPass> render_pass(cc::RenderPass::Create()); - render_pass->SetNew( - cc::RenderPassId(1, 1), gfx::Rect(size), gfx::Rect(), gfx::Transform()); - frame_data->render_pass_list.push_back(render_pass.Pass()); - return frame_data.Pass(); -} - -TEST_F(LayerWithDelegateTest, DelegatedLayer) { - scoped_ptr<Layer> root(CreateNoTextureLayer(gfx::Rect(0, 0, 1000, 1000))); - - scoped_ptr<Layer> child(CreateLayer(LAYER_TEXTURED)); - - child->SetBounds(gfx::Rect(0, 0, 10, 10)); - child->SetVisible(true); - root->Add(child.get()); - DrawTree(root.get()); - - scoped_refptr<cc::DelegatedFrameResourceCollection> resource_collection = - new cc::DelegatedFrameResourceCollection; - scoped_refptr<cc::DelegatedFrameProvider> frame_provider; - - // Content matches layer size. - frame_provider = new cc::DelegatedFrameProvider( - resource_collection.get(), MakeFrameData(gfx::Size(10, 10))); - child->SetShowDelegatedContent(frame_provider.get(), gfx::Size(10, 10)); - EXPECT_EQ(child->cc_layer()->bounds().ToString(), - gfx::Size(10, 10).ToString()); - - // Content larger than layer. - child->SetBounds(gfx::Rect(0, 0, 5, 5)); - EXPECT_EQ(child->cc_layer()->bounds().ToString(), - gfx::Size(5, 5).ToString()); - - // Content smaller than layer. - child->SetBounds(gfx::Rect(0, 0, 10, 10)); - frame_provider = new cc::DelegatedFrameProvider( - resource_collection.get(), MakeFrameData(gfx::Size(5, 5))); - child->SetShowDelegatedContent(frame_provider.get(), gfx::Size(5, 5)); - EXPECT_EQ(child->cc_layer()->bounds().ToString(), gfx::Size(5, 5).ToString()); - - // Hi-DPI content on low-DPI layer. - frame_provider = new cc::DelegatedFrameProvider( - resource_collection.get(), MakeFrameData(gfx::Size(20, 20))); - child->SetShowDelegatedContent(frame_provider.get(), gfx::Size(10, 10)); - EXPECT_EQ(child->cc_layer()->bounds().ToString(), - gfx::Size(10, 10).ToString()); - - // Hi-DPI content on hi-DPI layer. - compositor()->SetScaleAndSize(2.f, gfx::Size(1000, 1000)); - EXPECT_EQ(child->cc_layer()->bounds().ToString(), - gfx::Size(10, 10).ToString()); - - // Low-DPI content on hi-DPI layer. - frame_provider = new cc::DelegatedFrameProvider( - resource_collection.get(), MakeFrameData(gfx::Size(10, 10))); - child->SetShowDelegatedContent(frame_provider.get(), gfx::Size(10, 10)); - EXPECT_EQ(child->cc_layer()->bounds().ToString(), - gfx::Size(10, 10).ToString()); -} - -TEST_F(LayerWithDelegateTest, ExternalContent) { - scoped_ptr<Layer> root(CreateNoTextureLayer(gfx::Rect(0, 0, 1000, 1000))); - scoped_ptr<Layer> child(CreateLayer(LAYER_SOLID_COLOR)); - - child->SetBounds(gfx::Rect(0, 0, 10, 10)); - child->SetVisible(true); - root->Add(child.get()); - - // The layer is already showing solid color content, so the cc layer won't - // change. - scoped_refptr<cc::Layer> before = child->cc_layer(); - child->SetShowSolidColorContent(); - EXPECT_TRUE(child->cc_layer()); - EXPECT_EQ(before.get(), child->cc_layer()); - - scoped_refptr<cc::DelegatedFrameResourceCollection> resource_collection = - new cc::DelegatedFrameResourceCollection; - scoped_refptr<cc::DelegatedFrameProvider> frame_provider = - new cc::DelegatedFrameProvider(resource_collection.get(), - MakeFrameData(gfx::Size(10, 10))); - - // Showing delegated content changes the underlying cc layer. - before = child->cc_layer(); - child->SetShowDelegatedContent(frame_provider.get(), gfx::Size(10, 10)); - EXPECT_TRUE(child->cc_layer()); - EXPECT_NE(before.get(), child->cc_layer()); - - // Changing to painted content should change the underlying cc layer. - before = child->cc_layer(); - child->SetShowSolidColorContent(); - EXPECT_TRUE(child->cc_layer()); - EXPECT_NE(before.get(), child->cc_layer()); -} - -// Verifies that layer filters still attached after changing implementation -// layer. -TEST_F(LayerWithDelegateTest, LayerFiltersSurvival) { - scoped_ptr<Layer> layer(CreateLayer(LAYER_TEXTURED)); - layer->SetBounds(gfx::Rect(0, 0, 10, 10)); - EXPECT_TRUE(layer->cc_layer()); - EXPECT_EQ(0u, layer->cc_layer()->filters().size()); - - layer->SetLayerGrayscale(0.5f); - EXPECT_EQ(layer->layer_grayscale(), 0.5f); - EXPECT_EQ(1u, layer->cc_layer()->filters().size()); - - scoped_refptr<cc::DelegatedFrameResourceCollection> resource_collection = - new cc::DelegatedFrameResourceCollection; - scoped_refptr<cc::DelegatedFrameProvider> frame_provider = - new cc::DelegatedFrameProvider(resource_collection.get(), - MakeFrameData(gfx::Size(10, 10))); - - // Showing delegated content changes the underlying cc layer. - scoped_refptr<cc::Layer> before = layer->cc_layer(); - layer->SetShowDelegatedContent(frame_provider.get(), gfx::Size(10, 10)); - EXPECT_EQ(layer->layer_grayscale(), 0.5f); - EXPECT_TRUE(layer->cc_layer()); - EXPECT_NE(before.get(), layer->cc_layer()); - EXPECT_EQ(1u, layer->cc_layer()->filters().size()); -} - -// Tests Layer::AddThreadedAnimation and Layer::RemoveThreadedAnimation. -TEST_F(LayerWithRealCompositorTest, AddRemoveThreadedAnimations) { - scoped_ptr<Layer> root(CreateLayer(LAYER_TEXTURED)); - scoped_ptr<Layer> l1(CreateLayer(LAYER_TEXTURED)); - scoped_ptr<Layer> l2(CreateLayer(LAYER_TEXTURED)); - - l1->SetAnimator(LayerAnimator::CreateImplicitAnimator()); - l2->SetAnimator(LayerAnimator::CreateImplicitAnimator()); - - EXPECT_FALSE(l1->HasPendingThreadedAnimations()); - - // Trigger a threaded animation. - l1->SetOpacity(0.5f); - - EXPECT_TRUE(l1->HasPendingThreadedAnimations()); - - // Ensure we can remove a pending threaded animation. - l1->GetAnimator()->StopAnimating(); - - EXPECT_FALSE(l1->HasPendingThreadedAnimations()); - - // Trigger another threaded animation. - l1->SetOpacity(0.2f); - - EXPECT_TRUE(l1->HasPendingThreadedAnimations()); - - root->Add(l1.get()); - GetCompositor()->SetRootLayer(root.get()); - - // Now that l1 is part of a tree, it should have dispatched the pending - // animation. - EXPECT_FALSE(l1->HasPendingThreadedAnimations()); - - // Ensure that l1 no longer holds on to animations. - l1->SetOpacity(0.1f); - EXPECT_FALSE(l1->HasPendingThreadedAnimations()); - - // Ensure that adding a layer to an existing tree causes its pending - // animations to get dispatched. - l2->SetOpacity(0.5f); - EXPECT_TRUE(l2->HasPendingThreadedAnimations()); - - l1->Add(l2.get()); - EXPECT_FALSE(l2->HasPendingThreadedAnimations()); -} - -// Tests that in-progress threaded animations complete when a Layer's -// cc::Layer changes. -TEST_F(LayerWithRealCompositorTest, SwitchCCLayerAnimations) { - scoped_ptr<Layer> root(CreateLayer(LAYER_TEXTURED)); - scoped_ptr<Layer> l1(CreateLayer(LAYER_TEXTURED)); - GetCompositor()->SetRootLayer(root.get()); - root->Add(l1.get()); - - l1->SetAnimator(LayerAnimator::CreateImplicitAnimator()); - - EXPECT_FLOAT_EQ(l1->opacity(), 1.0f); - - // Trigger a threaded animation. - l1->SetOpacity(0.5f); - - // Change l1's cc::Layer. - l1->SwitchCCLayerForTest(); - - // Ensure that the opacity animation completed. - EXPECT_FLOAT_EQ(l1->opacity(), 0.5f); -} - -// Tests that the animators in the layer tree is added to the -// animator-collection when the root-layer is set to the compositor. -TEST_F(LayerWithDelegateTest, RootLayerAnimatorsInCompositor) { - scoped_ptr<Layer> root(CreateLayer(LAYER_SOLID_COLOR)); - scoped_ptr<Layer> child(CreateColorLayer(SK_ColorRED, gfx::Rect(10, 10))); - child->SetAnimator(LayerAnimator::CreateImplicitAnimator()); - child->SetOpacity(0.5f); - root->Add(child.get()); - - EXPECT_FALSE(compositor()->layer_animator_collection()->HasActiveAnimators()); - compositor()->SetRootLayer(root.get()); - EXPECT_TRUE(compositor()->layer_animator_collection()->HasActiveAnimators()); -} - -// Tests that adding/removing a layer adds/removes the animator from its entire -// subtree from the compositor's animator-collection. -TEST_F(LayerWithDelegateTest, AddRemoveLayerUpdatesAnimatorsFromSubtree) { - scoped_ptr<Layer> root(CreateLayer(LAYER_TEXTURED)); - scoped_ptr<Layer> child(CreateLayer(LAYER_TEXTURED)); - scoped_ptr<Layer> grandchild(CreateColorLayer(SK_ColorRED, - gfx::Rect(10, 10))); - root->Add(child.get()); - child->Add(grandchild.get()); - compositor()->SetRootLayer(root.get()); - - grandchild->SetAnimator(LayerAnimator::CreateImplicitAnimator()); - grandchild->SetOpacity(0.5f); - EXPECT_TRUE(compositor()->layer_animator_collection()->HasActiveAnimators()); - - root->Remove(child.get()); - EXPECT_FALSE(compositor()->layer_animator_collection()->HasActiveAnimators()); - - root->Add(child.get()); - EXPECT_TRUE(compositor()->layer_animator_collection()->HasActiveAnimators()); -} - -TEST_F(LayerWithDelegateTest, DestroyingLayerRemovesTheAnimatorFromCollection) { - scoped_ptr<Layer> root(CreateLayer(LAYER_TEXTURED)); - scoped_ptr<Layer> child(CreateLayer(LAYER_TEXTURED)); - root->Add(child.get()); - compositor()->SetRootLayer(root.get()); - - child->SetAnimator(LayerAnimator::CreateImplicitAnimator()); - child->SetOpacity(0.5f); - EXPECT_TRUE(compositor()->layer_animator_collection()->HasActiveAnimators()); - - child.reset(); - EXPECT_FALSE(compositor()->layer_animator_collection()->HasActiveAnimators()); -} - -namespace { - -std::string Vector2dFTo100thPercisionString(const gfx::Vector2dF& vector) { - return base::StringPrintf("%.2f %0.2f", vector.x(), vector.y()); -} - -} // namespace - -TEST_F(LayerWithRealCompositorTest, SnapLayerToPixels) { - scoped_ptr<Layer> root(CreateLayer(LAYER_TEXTURED)); - scoped_ptr<Layer> c1(CreateLayer(LAYER_TEXTURED)); - scoped_ptr<Layer> c11(CreateLayer(LAYER_TEXTURED)); - - GetCompositor()->SetScaleAndSize(1.25f, gfx::Size(100, 100)); - GetCompositor()->SetRootLayer(root.get()); - root->Add(c1.get()); - c1->Add(c11.get()); - - root->SetBounds(gfx::Rect(0, 0, 100, 100)); - c1->SetBounds(gfx::Rect(1, 1, 10, 10)); - c11->SetBounds(gfx::Rect(1, 1, 10, 10)); - SnapLayerToPhysicalPixelBoundary(root.get(), c11.get()); - // 0.5 at 1.25 scale : (1 - 0.25 + 0.25) / 1.25 = 0.4 - EXPECT_EQ("0.40 0.40", - Vector2dFTo100thPercisionString(c11->subpixel_position_offset())); - - GetCompositor()->SetScaleAndSize(1.5f, gfx::Size(100, 100)); - SnapLayerToPhysicalPixelBoundary(root.get(), c11.get()); - // c11 must already be aligned at 1.5 scale. - EXPECT_EQ("0.00 0.00", - Vector2dFTo100thPercisionString(c11->subpixel_position_offset())); - - c11->SetBounds(gfx::Rect(2, 2, 10, 10)); - SnapLayerToPhysicalPixelBoundary(root.get(), c11.get()); - // c11 is now off the pixel. - // 0.5 / 1.5 = 0.333... - EXPECT_EQ("0.33 0.33", - Vector2dFTo100thPercisionString(c11->subpixel_position_offset())); -} - -class FrameDamageCheckingDelegate : public TestLayerDelegate { - public: - FrameDamageCheckingDelegate() : delegated_frame_damage_called_(false) {} - - virtual void OnDelegatedFrameDamage( - const gfx::Rect& damage_rect_in_dip) override { - delegated_frame_damage_called_ = true; - delegated_frame_damage_rect_ = damage_rect_in_dip; - } - - const gfx::Rect& delegated_frame_damage_rect() const { - return delegated_frame_damage_rect_; - } - bool delegated_frame_damage_called() const { - return delegated_frame_damage_called_; - } - - private: - gfx::Rect delegated_frame_damage_rect_; - bool delegated_frame_damage_called_; - - DISALLOW_COPY_AND_ASSIGN(FrameDamageCheckingDelegate); -}; - -TEST(LayerDelegateTest, DelegatedFrameDamage) { - scoped_ptr<Layer> layer(new Layer(LAYER_TEXTURED)); - gfx::Rect damage_rect(2, 1, 5, 3); - - FrameDamageCheckingDelegate delegate; - layer->set_delegate(&delegate); - scoped_refptr<cc::DelegatedFrameResourceCollection> resource_collection = - new cc::DelegatedFrameResourceCollection; - scoped_refptr<cc::DelegatedFrameProvider> frame_provider( - new cc::DelegatedFrameProvider(resource_collection.get(), - MakeFrameData(gfx::Size(10, 10)))); - layer->SetShowDelegatedContent(frame_provider.get(), gfx::Size(10, 10)); - - EXPECT_FALSE(delegate.delegated_frame_damage_called()); - layer->OnDelegatedFrameDamage(damage_rect); - EXPECT_TRUE(delegate.delegated_frame_damage_called()); - EXPECT_EQ(damage_rect, delegate.delegated_frame_damage_rect()); -} - -} // namespace ui
diff --git a/ui/compositor/reflector.h b/ui/compositor/reflector.h deleted file mode 100644 index 4145695..0000000 --- a/ui/compositor/reflector.h +++ /dev/null
@@ -1,27 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_REFLECTOR_H_ -#define UI_COMPOSITOR_REFLECTOR_H_ - -#include "base/memory/ref_counted.h" - -namespace ui { - -class Reflector : public base::RefCountedThreadSafe<Reflector> { - public: - Reflector() {} - - virtual void OnMirroringCompositorResized() {} - - protected: - friend class base::RefCountedThreadSafe<Reflector>; - virtual ~Reflector() {} - - DISALLOW_COPY_AND_ASSIGN(Reflector); -}; - -} // namespace ui - -#endif // UI_COMPOSITOR_REFLECTOR_H_
diff --git a/ui/compositor/run_all_unittests.cc b/ui/compositor/run_all_unittests.cc deleted file mode 100644 index df9bb68..0000000 --- a/ui/compositor/run_all_unittests.cc +++ /dev/null
@@ -1,15 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/bind.h" -#include "base/test/launcher/unit_test_launcher.h" -#include "ui/compositor/test/test_suite.h" - -int main(int argc, char** argv) { - ui::test::CompositorTestSuite test_suite(argc, argv); - - return base::LaunchUnitTests( - argc, argv, base::Bind(&ui::test::CompositorTestSuite::Run, - base::Unretained(&test_suite))); -}
diff --git a/ui/compositor/scoped_animation_duration_scale_mode.cc b/ui/compositor/scoped_animation_duration_scale_mode.cc deleted file mode 100644 index 5d146f1..0000000 --- a/ui/compositor/scoped_animation_duration_scale_mode.cc +++ /dev/null
@@ -1,14 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/compositor/scoped_animation_duration_scale_mode.h" - -namespace ui { - -// static -ScopedAnimationDurationScaleMode::DurationScaleMode - ScopedAnimationDurationScaleMode::duration_scale_mode_ = - ScopedAnimationDurationScaleMode::NORMAL_DURATION; - -} // namespace ui
diff --git a/ui/compositor/scoped_animation_duration_scale_mode.h b/ui/compositor/scoped_animation_duration_scale_mode.h deleted file mode 100644 index 9444651..0000000 --- a/ui/compositor/scoped_animation_duration_scale_mode.h +++ /dev/null
@@ -1,51 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_SCOPED_ANIMATION_DURATION_SCALE_MODE_H_ -#define UI_COMPOSITOR_SCOPED_ANIMATION_DURATION_SCALE_MODE_H_ - -#include "base/basictypes.h" -#include "ui/compositor/compositor_export.h" - -namespace ui { - -// Speed up or slow down animations for testing or debugging. -class COMPOSITOR_EXPORT ScopedAnimationDurationScaleMode { - public: - enum DurationScaleMode { - NORMAL_DURATION, - FAST_DURATION, - SLOW_DURATION, - // A very short but guaranteed non-zero duration for individual tests that - // need to assert things about animations after creating them. - NON_ZERO_DURATION, - // Animations complete immediately after being created. Used by most tests. - ZERO_DURATION - }; - - explicit ScopedAnimationDurationScaleMode( - DurationScaleMode scoped_duration_scale_mode) - : old_duration_scale_mode_(duration_scale_mode_) { - duration_scale_mode_ = scoped_duration_scale_mode; - } - - ~ScopedAnimationDurationScaleMode() { - duration_scale_mode_ = old_duration_scale_mode_; - } - - static DurationScaleMode duration_scale_mode() { - return duration_scale_mode_; - } - - private: - DurationScaleMode old_duration_scale_mode_; - - static DurationScaleMode duration_scale_mode_; - - DISALLOW_COPY_AND_ASSIGN(ScopedAnimationDurationScaleMode); -}; - -} // namespace ui - -#endif // UI_COMPOSITOR_SCOPED_ANIMATION_DURATION_SCALE_MODE_H
diff --git a/ui/compositor/scoped_layer_animation_settings.cc b/ui/compositor/scoped_layer_animation_settings.cc deleted file mode 100644 index 7a593ca..0000000 --- a/ui/compositor/scoped_layer_animation_settings.cc +++ /dev/null
@@ -1,162 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/compositor/scoped_layer_animation_settings.h" - -#include "ui/compositor/layer.h" -#include "ui/compositor/layer_animation_observer.h" -#include "ui/compositor/layer_animation_sequence.h" -#include "ui/compositor/layer_animator.h" - -namespace { - -const int kDefaultTransitionDurationMs = 200; - -} // namespace - -namespace ui { - -// InvertingObserver ----------------------------------------------------------- -class InvertingObserver : public ImplicitAnimationObserver { - public: - InvertingObserver() - : base_layer_(NULL) { - } - - ~InvertingObserver() override {} - - void SetLayer(Layer* base_layer) { base_layer_ = base_layer; } - - Layer* layer() { return base_layer_; } - - void AddInverselyAnimatedLayer(Layer* inverse_layer) { - inverse_layers_.push_back(inverse_layer); - } - - void OnImplicitAnimationsCompleted() override {} - - void OnLayerAnimationScheduled(LayerAnimationSequence* sequence) override { - DCHECK(base_layer_ != NULL) - << "Must set base layer with ScopedLayerAnimationSettings::" - << "SetInverslyAnimatedBaseLayer"; - gfx::Transform base_transform = base_layer_->transform(); - scoped_ptr<LayerAnimationElement> inverse = GetInverseElement(sequence, - base_transform); - - for (std::vector<Layer*>::const_iterator i = - inverse_layers_.begin(); i != inverse_layers_.end(); ++i) { - (*i)->GetAnimator()->StartAnimation(new LayerAnimationSequence( - LayerAnimationElement::CloneInverseTransformElement( - inverse.get()))); - } - } - private: - scoped_ptr<LayerAnimationElement> GetInverseElement( - LayerAnimationSequence* sequence, - gfx::Transform base) const { - const size_t expected_size = 1; - DCHECK_EQ(expected_size, sequence->size()) << - "Inverse supported only for single element sequences."; - - LayerAnimationElement* element = sequence->FirstElement(); - DCHECK_EQ(static_cast<LayerAnimationElement::AnimatableProperties>( - LayerAnimationElement::TRANSFORM), - element->properties()) - << "Only transform animations are currently invertible."; - - scoped_ptr<LayerAnimationElement> to_return( - LayerAnimationElement::CreateInverseTransformElement(base, element)); - return to_return.Pass(); - } - - Layer* base_layer_; - // child layers - std::vector<Layer*> inverse_layers_; -}; - - -// ScopedLayerAnimationSettings ------------------------------------------------ -ScopedLayerAnimationSettings::ScopedLayerAnimationSettings( - scoped_refptr<LayerAnimator> animator) - : animator_(animator), - old_is_transition_duration_locked_( - animator->is_transition_duration_locked_), - old_transition_duration_(animator->GetTransitionDuration()), - old_tween_type_(animator->tween_type()), - old_preemption_strategy_(animator->preemption_strategy()), - inverse_observer_(new InvertingObserver()) { - SetTransitionDuration( - base::TimeDelta::FromMilliseconds(kDefaultTransitionDurationMs)); -} - -ScopedLayerAnimationSettings::~ScopedLayerAnimationSettings() { - animator_->is_transition_duration_locked_ = - old_is_transition_duration_locked_; - animator_->SetTransitionDuration(old_transition_duration_); - animator_->set_tween_type(old_tween_type_); - animator_->set_preemption_strategy(old_preemption_strategy_); - - for (std::set<ImplicitAnimationObserver*>::const_iterator i = - observers_.begin(); i != observers_.end(); ++i) { - animator_->observers_.RemoveObserver(*i); - (*i)->SetActive(true); - } - - if (inverse_observer_->layer()) { - animator_->observers_.RemoveObserver(inverse_observer_.get()); - } -} - -void ScopedLayerAnimationSettings::AddObserver( - ImplicitAnimationObserver* observer) { - observers_.insert(observer); - animator_->AddObserver(observer); -} - -void ScopedLayerAnimationSettings::SetTransitionDuration( - base::TimeDelta duration) { - animator_->SetTransitionDuration(duration); -} - -void ScopedLayerAnimationSettings::LockTransitionDuration() { - animator_->is_transition_duration_locked_ = true; -} - -base::TimeDelta ScopedLayerAnimationSettings::GetTransitionDuration() const { - return animator_->GetTransitionDuration(); -} - -void ScopedLayerAnimationSettings::SetTweenType(gfx::Tween::Type tween_type) { - animator_->set_tween_type(tween_type); -} - -gfx::Tween::Type ScopedLayerAnimationSettings::GetTweenType() const { - return animator_->tween_type(); -} - -void ScopedLayerAnimationSettings::SetPreemptionStrategy( - LayerAnimator::PreemptionStrategy strategy) { - animator_->set_preemption_strategy(strategy); -} - -LayerAnimator::PreemptionStrategy -ScopedLayerAnimationSettings::GetPreemptionStrategy() const { - return animator_->preemption_strategy(); -} - -void ScopedLayerAnimationSettings::SetInverselyAnimatedBaseLayer(Layer* base) { - if (inverse_observer_->layer() && !base) { - animator_->RemoveObserver(inverse_observer_.get()); - } else if (base && !(inverse_observer_->layer())) { - animator_->AddObserver(inverse_observer_.get()); - } - inverse_observer_->SetLayer(base); -} - -void ScopedLayerAnimationSettings::AddInverselyAnimatedLayer( - Layer* inverse_layer) { - inverse_observer_->AddInverselyAnimatedLayer(inverse_layer); -} - -} // namespace ui
diff --git a/ui/compositor/scoped_layer_animation_settings.h b/ui/compositor/scoped_layer_animation_settings.h deleted file mode 100644 index e201024..0000000 --- a/ui/compositor/scoped_layer_animation_settings.h +++ /dev/null
@@ -1,71 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_SCOPED_LAYER_ANIMATION_SETTINGS_H_ -#define UI_COMPOSITOR_SCOPED_LAYER_ANIMATION_SETTINGS_H_ - -#include <set> - -#include "base/memory/scoped_vector.h" -#include "base/time/time.h" - -#include "ui/compositor/compositor_export.h" -#include "ui/compositor/layer_animator.h" -#include "ui/gfx/animation/tween.h" - -namespace ui { - -class ImplicitAnimationObserver; -class LayerAnimationObserver; -class InvertingObserver; - -// Scoped settings allow you to temporarily change the animator's settings and -// these changes are reverted when the object is destroyed. NOTE: when the -// settings object is created, it applies the default transition duration -// (200ms). -class COMPOSITOR_EXPORT ScopedLayerAnimationSettings { - public: - explicit ScopedLayerAnimationSettings(scoped_refptr<LayerAnimator> animator); - virtual ~ScopedLayerAnimationSettings(); - - void AddObserver(ImplicitAnimationObserver* observer); - - void SetTransitionDuration(base::TimeDelta duration); - base::TimeDelta GetTransitionDuration() const; - - // Locks transition duration in |animator_|. When transition duration - // is locked any subsequent changes to it are ignored until the - // ScopedLayerAnimationSettings object that has locked the duration goes out - // of scope. - void LockTransitionDuration(); - - void SetTweenType(gfx::Tween::Type tween_type); - gfx::Tween::Type GetTweenType() const; - - void SetPreemptionStrategy(LayerAnimator::PreemptionStrategy strategy); - LayerAnimator::PreemptionStrategy GetPreemptionStrategy() const; - - // Sets the base layer whose animation will be countered. - void SetInverselyAnimatedBaseLayer(Layer* base); - - // Adds the layer to be counter-animated when a transform animation is - // scheduled on the animator_. Must call SetInverselyAnimatedBaseLayer with - // the layer associated with animator_ before animating. - void AddInverselyAnimatedLayer(Layer* inverse_layer); - - private: - scoped_refptr<LayerAnimator> animator_; - bool old_is_transition_duration_locked_; - base::TimeDelta old_transition_duration_; - gfx::Tween::Type old_tween_type_; - LayerAnimator::PreemptionStrategy old_preemption_strategy_; - std::set<ImplicitAnimationObserver*> observers_; - scoped_ptr<InvertingObserver> inverse_observer_; - - DISALLOW_COPY_AND_ASSIGN(ScopedLayerAnimationSettings); -}; - -} // namespace ui - -#endif // UI_COMPOSITOR_SCOPED_LAYER_ANIMATION_SETTINGS_H_
diff --git a/ui/compositor/test/DEPS b/ui/compositor/test/DEPS deleted file mode 100644 index cc6a491..0000000 --- a/ui/compositor/test/DEPS +++ /dev/null
@@ -1,3 +0,0 @@ -include_rules = [ - "+webkit/common/gpu", -]
diff --git a/ui/compositor/test/context_factories_for_test.cc b/ui/compositor/test/context_factories_for_test.cc deleted file mode 100644 index f3eeeb3..0000000 --- a/ui/compositor/test/context_factories_for_test.cc +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/compositor/test/context_factories_for_test.h" - -#include "base/command_line.h" -#include "base/sys_info.h" -#include "ui/compositor/compositor.h" -#include "ui/compositor/compositor_switches.h" -#include "ui/compositor/test/in_process_context_factory.h" -#include "ui/gl/gl_implementation.h" - -namespace { - -static ui::ContextFactory* g_implicit_factory = NULL; -static gfx::DisableNullDrawGLBindings* g_disable_null_draw = NULL; - -} // namespace - -namespace ui { - -// static -ui::ContextFactory* InitializeContextFactoryForTests(bool enable_pixel_output) { - DCHECK(!g_implicit_factory) << - "ContextFactory for tests already initialized."; - CommandLine* command_line = CommandLine::ForCurrentProcess(); - if (command_line->HasSwitch(switches::kEnablePixelOutputInTests)) - enable_pixel_output = true; - if (enable_pixel_output) - g_disable_null_draw = new gfx::DisableNullDrawGLBindings; - g_implicit_factory = new InProcessContextFactory(); - return g_implicit_factory; -} - -void TerminateContextFactoryForTests() { - delete g_implicit_factory; - g_implicit_factory = NULL; - delete g_disable_null_draw; - g_disable_null_draw = NULL; -} - -} // namespace ui
diff --git a/ui/compositor/test/context_factories_for_test.h b/ui/compositor/test/context_factories_for_test.h deleted file mode 100644 index e54d206..0000000 --- a/ui/compositor/test/context_factories_for_test.h +++ /dev/null
@@ -1,20 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -namespace ui { - -class ContextFactory; - -// Set up the compositor ContextFactory for a test environment. Unit tests -// that do not have a full content environment need to call this before -// initializing the Compositor. -// Some tests expect pixel output, and they should pass true for -// |enable_pixel_output|. Most unit tests should pass false. Once this has been -// called, the caller must call TerminateContextFactoryForTests() to clean up. -// TODO(sky): this should return a scoped_ptr and then nuke -// TerminateContextFactoryForTests(). -ui::ContextFactory* InitializeContextFactoryForTests(bool enable_pixel_output); -void TerminateContextFactoryForTests(); - -} // namespace ui
diff --git a/ui/compositor/test/draw_waiter_for_test.cc b/ui/compositor/test/draw_waiter_for_test.cc deleted file mode 100644 index 7687d66..0000000 --- a/ui/compositor/test/draw_waiter_for_test.cc +++ /dev/null
@@ -1,56 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/compositor/test/draw_waiter_for_test.h" - -#include "ui/compositor/compositor.h" - -namespace ui { - -// static -void DrawWaiterForTest::Wait(Compositor* compositor) { - DrawWaiterForTest waiter; - waiter.wait_for_commit_ = false; - waiter.WaitImpl(compositor); -} - -// static -void DrawWaiterForTest::WaitForCommit(Compositor* compositor) { - DrawWaiterForTest waiter; - waiter.wait_for_commit_ = true; - waiter.WaitImpl(compositor); -} - -DrawWaiterForTest::DrawWaiterForTest() { -} - -DrawWaiterForTest::~DrawWaiterForTest() {} - -void DrawWaiterForTest::WaitImpl(Compositor* compositor) { - compositor->AddObserver(this); - wait_run_loop_.reset(new base::RunLoop()); - wait_run_loop_->Run(); - compositor->RemoveObserver(this); -} - -void DrawWaiterForTest::OnCompositingDidCommit(Compositor* compositor) { - if (wait_for_commit_) - wait_run_loop_->Quit(); -} - -void DrawWaiterForTest::OnCompositingStarted(Compositor* compositor, - base::TimeTicks start_time) { -} - -void DrawWaiterForTest::OnCompositingEnded(Compositor* compositor) { - if (!wait_for_commit_) - wait_run_loop_->Quit(); -} - -void DrawWaiterForTest::OnCompositingAborted(Compositor* compositor) { -} - -void DrawWaiterForTest::OnCompositingLockStateChanged(Compositor* compositor) {} - -} // namespace ui
diff --git a/ui/compositor/test/draw_waiter_for_test.h b/ui/compositor/test/draw_waiter_for_test.h deleted file mode 100644 index 55ca2ff..0000000 --- a/ui/compositor/test/draw_waiter_for_test.h +++ /dev/null
@@ -1,51 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_TEST_DRAW_WAITER_H_ -#define UI_COMPOSITOR_TEST_DRAW_WAITER_H_ - -#include "base/run_loop.h" -#include "ui/compositor/compositor_observer.h" - -class Compositor; - -namespace ui { - -// This is only to be used for test. It allows execution of other tasks on -// the current message loop before the current task finishs (there is a -// potential for re-entrancy). -class DrawWaiterForTest : public CompositorObserver { - public: - // Waits for a draw to be issued by the compositor. If the test times out - // here, there may be a logic error in the compositor code causing it - // not to draw. - static void Wait(Compositor* compositor); - - // Waits for a commit instead of a draw. - static void WaitForCommit(Compositor* compositor); - - private: - DrawWaiterForTest(); - ~DrawWaiterForTest() override; - - void WaitImpl(Compositor* compositor); - - // CompositorObserver implementation. - void OnCompositingDidCommit(Compositor* compositor) override; - void OnCompositingStarted(Compositor* compositor, - base::TimeTicks start_time) override; - void OnCompositingEnded(Compositor* compositor) override; - void OnCompositingAborted(Compositor* compositor) override; - void OnCompositingLockStateChanged(Compositor* compositor) override; - - scoped_ptr<base::RunLoop> wait_run_loop_; - - bool wait_for_commit_; - - DISALLOW_COPY_AND_ASSIGN(DrawWaiterForTest); -}; - -} // namespace ui - -#endif // UI_COMPOSITOR_TEST_DRAW_WAITER_H_
diff --git a/ui/compositor/test/in_process_context_factory.cc b/ui/compositor/test/in_process_context_factory.cc deleted file mode 100644 index 3bf0d3e..0000000 --- a/ui/compositor/test/in_process_context_factory.cc +++ /dev/null
@@ -1,117 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/compositor/test/in_process_context_factory.h" - -#include "base/command_line.h" -#include "base/threading/thread.h" -#include "cc/surfaces/surface_id_allocator.h" -#include "cc/test/pixel_test_output_surface.h" -#include "cc/test/test_shared_bitmap_manager.h" -#include "ui/compositor/compositor_switches.h" -#include "ui/compositor/reflector.h" -#include "ui/gl/gl_implementation.h" -#include "ui/gl/gl_surface.h" -#include "webkit/common/gpu/context_provider_in_process.h" -#include "webkit/common/gpu/grcontext_for_webgraphicscontext3d.h" -#include "webkit/common/gpu/webgraphicscontext3d_in_process_command_buffer_impl.h" - -namespace ui { - -InProcessContextFactory::InProcessContextFactory() - : next_surface_id_namespace_(1u) { - DCHECK_NE(gfx::GetGLImplementation(), gfx::kGLImplementationNone) - << "If running tests, ensure that main() is calling " - << "gfx::GLSurface::InitializeOneOffForTests()"; - -#if defined(OS_CHROMEOS) - bool use_thread = !CommandLine::ForCurrentProcess()->HasSwitch( - switches::kUIDisableThreadedCompositing); -#else - bool use_thread = false; -#endif - if (use_thread) { - compositor_thread_.reset(new base::Thread("Browser Compositor")); - compositor_thread_->Start(); - } -} - -InProcessContextFactory::~InProcessContextFactory() {} - -scoped_ptr<cc::OutputSurface> InProcessContextFactory::CreateOutputSurface( - Compositor* compositor, - bool software_fallback) { - DCHECK(!software_fallback); - blink::WebGraphicsContext3D::Attributes attrs; - attrs.depth = false; - attrs.stencil = false; - attrs.antialias = false; - attrs.shareResources = true; - bool lose_context_when_out_of_memory = true; - - using webkit::gpu::WebGraphicsContext3DInProcessCommandBufferImpl; - scoped_ptr<WebGraphicsContext3DInProcessCommandBufferImpl> context3d( - WebGraphicsContext3DInProcessCommandBufferImpl::CreateViewContext( - attrs, lose_context_when_out_of_memory, compositor->widget())); - CHECK(context3d); - - using webkit::gpu::ContextProviderInProcess; - scoped_refptr<ContextProviderInProcess> context_provider = - ContextProviderInProcess::Create(context3d.Pass(), "UICompositor"); - - return make_scoped_ptr(new cc::PixelTestOutputSurface(context_provider)); -} - -scoped_refptr<Reflector> InProcessContextFactory::CreateReflector( - Compositor* mirroed_compositor, - Layer* mirroring_layer) { - return new Reflector(); -} - -void InProcessContextFactory::RemoveReflector( - scoped_refptr<Reflector> reflector) {} - -scoped_refptr<cc::ContextProvider> -InProcessContextFactory::SharedMainThreadContextProvider() { - if (shared_main_thread_contexts_.get() && - !shared_main_thread_contexts_->DestroyedOnMainThread()) - return shared_main_thread_contexts_; - - bool lose_context_when_out_of_memory = false; - shared_main_thread_contexts_ = - webkit::gpu::ContextProviderInProcess::CreateOffscreen( - lose_context_when_out_of_memory); - if (shared_main_thread_contexts_.get() && - !shared_main_thread_contexts_->BindToCurrentThread()) - shared_main_thread_contexts_ = NULL; - - return shared_main_thread_contexts_; -} - -void InProcessContextFactory::RemoveCompositor(Compositor* compositor) {} - -bool InProcessContextFactory::DoesCreateTestContexts() { return false; } - -cc::SharedBitmapManager* InProcessContextFactory::GetSharedBitmapManager() { - return &shared_bitmap_manager_; -} - -cc::GpuMemoryBufferManager* -InProcessContextFactory::GetGpuMemoryBufferManager() { - return &gpu_memory_buffer_manager_; -} - -base::MessageLoopProxy* InProcessContextFactory::GetCompositorMessageLoop() { - if (!compositor_thread_) - return NULL; - return compositor_thread_->message_loop_proxy().get(); -} - -scoped_ptr<cc::SurfaceIdAllocator> -InProcessContextFactory::CreateSurfaceIdAllocator() { - return make_scoped_ptr( - new cc::SurfaceIdAllocator(next_surface_id_namespace_++)); -} - -} // namespace ui
diff --git a/ui/compositor/test/in_process_context_factory.h b/ui/compositor/test/in_process_context_factory.h deleted file mode 100644 index 4e5b3e8..0000000 --- a/ui/compositor/test/in_process_context_factory.h +++ /dev/null
@@ -1,59 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_TEST_IN_PROCESS_CONTEXT_FACTORY_H_ -#define UI_COMPOSITOR_TEST_IN_PROCESS_CONTEXT_FACTORY_H_ - -#include "cc/test/test_gpu_memory_buffer_manager.h" -#include "cc/test/test_shared_bitmap_manager.h" -#include "ui/compositor/compositor.h" - -namespace base { -class Thread; -} - -namespace webkit { -namespace gpu { -class ContextProviderInProcess; -} -} - -namespace ui { - -class InProcessContextFactory : public ContextFactory { - public: - InProcessContextFactory(); - ~InProcessContextFactory() override; - - // ContextFactory implementation - scoped_ptr<cc::OutputSurface> CreateOutputSurface( - Compositor* compositor, - bool software_fallback) override; - - scoped_refptr<Reflector> CreateReflector(Compositor* mirrored_compositor, - Layer* mirroring_layer) override; - void RemoveReflector(scoped_refptr<Reflector> reflector) override; - - scoped_refptr<cc::ContextProvider> SharedMainThreadContextProvider() override; - void RemoveCompositor(Compositor* compositor) override; - bool DoesCreateTestContexts() override; - cc::SharedBitmapManager* GetSharedBitmapManager() override; - cc::GpuMemoryBufferManager* GetGpuMemoryBufferManager() override; - base::MessageLoopProxy* GetCompositorMessageLoop() override; - scoped_ptr<cc::SurfaceIdAllocator> CreateSurfaceIdAllocator() override; - - private: - scoped_ptr<base::Thread> compositor_thread_; - scoped_refptr<webkit::gpu::ContextProviderInProcess> - shared_main_thread_contexts_; - cc::TestSharedBitmapManager shared_bitmap_manager_; - cc::TestGpuMemoryBufferManager gpu_memory_buffer_manager_; - uint32_t next_surface_id_namespace_; - - DISALLOW_COPY_AND_ASSIGN(InProcessContextFactory); -}; - -} // namespace ui - -#endif // UI_COMPOSITOR_TEST_IN_PROCESS_CONTEXT_FACTORY_H_
diff --git a/ui/compositor/test/layer_animator_test_controller.cc b/ui/compositor/test/layer_animator_test_controller.cc deleted file mode 100644 index 9047f6c..0000000 --- a/ui/compositor/test/layer_animator_test_controller.cc +++ /dev/null
@@ -1,60 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "cc/animation/animation.h" -#include "ui/compositor/layer_animation_sequence.h" -#include "ui/compositor/test/layer_animator_test_controller.h" -#include "ui/gfx/frame_time.h" -#include "ui/gfx/rect.h" - -namespace ui { - -LayerAnimatorTestController::LayerAnimatorTestController( - scoped_refptr<LayerAnimator> animator) - : animator_(animator) { -} - -LayerAnimatorTestController::~LayerAnimatorTestController() { -} - -LayerAnimationSequence* LayerAnimatorTestController::GetRunningSequence( - LayerAnimationElement::AnimatableProperty property) { - LayerAnimator::RunningAnimation* running_animation = - animator_->GetRunningAnimation(property); - if (running_animation) - return running_animation->sequence(); - else - return NULL; -} - -void LayerAnimatorTestController::StartThreadedAnimationsIfNeeded() { - std::vector<cc::Animation::TargetProperty> threaded_properties; - threaded_properties.push_back(cc::Animation::Opacity); - threaded_properties.push_back(cc::Animation::Transform); - - for (size_t i = 0; i < threaded_properties.size(); i++) { - LayerAnimationElement::AnimatableProperty animatable_property = - LayerAnimationElement::ToAnimatableProperty(threaded_properties[i]); - LayerAnimationSequence* sequence = GetRunningSequence(animatable_property); - if (!sequence) - continue; - - LayerAnimationElement* element = sequence->CurrentElement(); - if (!(element->properties() & animatable_property)) - continue; - - if (!element->Started() || - element->effective_start_time() != base::TimeTicks()) - continue; - - animator_->OnThreadedAnimationStarted( - cc::AnimationEvent(cc::AnimationEvent::Started, - 0, - element->animation_group_id(), - threaded_properties[i], - gfx::FrameTime::Now())); - } -} - -} // namespace ui
diff --git a/ui/compositor/test/layer_animator_test_controller.h b/ui/compositor/test/layer_animator_test_controller.h deleted file mode 100644 index 0f8d1e8..0000000 --- a/ui/compositor/test/layer_animator_test_controller.h +++ /dev/null
@@ -1,34 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_TEST_LAYER_ANIMATOR_TEST_CONTROLLER_H_ -#define UI_COMPOSITOR_TEST_LAYER_ANIMATOR_TEST_CONTROLLER_H_ - -#include "ui/compositor/layer_animator.h" - -namespace ui { - -// Allows tests to access sequences owned by the animator. -class LayerAnimatorTestController { - public: - LayerAnimatorTestController(scoped_refptr<LayerAnimator> animator); - - ~LayerAnimatorTestController(); - - LayerAnimator* animator() { return animator_.get(); } - - // Returns the running sequence animating the given property, if any. - LayerAnimationSequence* GetRunningSequence( - LayerAnimationElement::AnimatableProperty property); - - // Starts threaded animations that are waiting for an effective start time. - void StartThreadedAnimationsIfNeeded(); - - private: - scoped_refptr<LayerAnimator> animator_; -}; - -} // namespace ui - -#endif // UI_COMPOSITOR_TEST_LAYER_ANIMATOR_TEST_CONTROLLER_H_
diff --git a/ui/compositor/test/test_compositor_host.h b/ui/compositor/test/test_compositor_host.h deleted file mode 100644 index dfdd87d..0000000 --- a/ui/compositor/test/test_compositor_host.h +++ /dev/null
@@ -1,33 +0,0 @@ -// Copyright 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_TEST_TEST_COMPOSITOR_HOST_H_ -#define UI_COMPOSITOR_TEST_TEST_COMPOSITOR_HOST_H_ - -namespace gfx { -class Rect; -} - -namespace ui { - -class Compositor; -class ContextFactory; - -class TestCompositorHost { - public: - virtual ~TestCompositorHost() {} - - // Creates a new TestCompositorHost. The caller owns the returned value. - static TestCompositorHost* Create(const gfx::Rect& bounds, - ui::ContextFactory* context_factory); - - // Shows the TestCompositorHost. - virtual void Show() = 0; - - virtual Compositor* GetCompositor() = 0; -}; - -} // namespace ui - -#endif // UI_COMPOSITOR_TEST_TEST_COMPOSITOR_HOST_H_
diff --git a/ui/compositor/test/test_compositor_host_mac.mm b/ui/compositor/test/test_compositor_host_mac.mm deleted file mode 100644 index b262a21..0000000 --- a/ui/compositor/test/test_compositor_host_mac.mm +++ /dev/null
@@ -1,153 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/compositor/test/test_compositor_host.h" - -#import <AppKit/NSApplication.h> -#import <AppKit/NSOpenGL.h> -#import <AppKit/NSView.h> -#import <AppKit/NSWindow.h> -#import <Foundation/NSAutoreleasePool.h> - -#include "base/compiler_specific.h" -#include "base/mac/scoped_nsobject.h" -#include "base/memory/scoped_ptr.h" -#include "base/thread_task_runner_handle.h" -#include "ui/compositor/compositor.h" -#include "ui/gfx/rect.h" - -// AcceleratedTestView provides an NSView class that delegates drawing to a -// ui::Compositor delegate, setting up the NSOpenGLContext as required. -@interface AcceleratedTestView : NSView { - ui::Compositor* compositor_; -} -// Designated initializer. --(id)init; --(void)setCompositor:(ui::Compositor*)compositor; -@end - -@implementation AcceleratedTestView --(id)init { - // The frame will be resized when reparented into the window's view hierarchy. - self = [super initWithFrame:NSZeroRect]; - return self; -} - --(void)setCompositor:(ui::Compositor*)compositor { - compositor_ = compositor; -} - -- (void)drawRect:(NSRect)rect { - DCHECK(compositor_) << "Drawing with no compositor set."; - compositor_->Draw(); -} -@end - -namespace ui { - -// Tests that use Objective-C memory semantics need to have a top-level -// NSAutoreleasePool set up and initialized prior to execution and drained upon -// exit. The tests will leak otherwise. -class FoundationHost { - protected: - FoundationHost() { - pool_ = [[NSAutoreleasePool alloc] init]; - } - virtual ~FoundationHost() { - [pool_ drain]; - } - - private: - NSAutoreleasePool* pool_; - DISALLOW_COPY_AND_ASSIGN(FoundationHost); -}; - -// Tests that use the AppKit framework need to have the NSApplication -// initialized prior to doing anything with display objects such as windows, -// views, or controls. -class AppKitHost : public FoundationHost { - protected: - AppKitHost() { - [NSApplication sharedApplication]; - } - ~AppKitHost() override {} - private: - DISALLOW_COPY_AND_ASSIGN(AppKitHost); -}; - -// TestCompositorHostMac provides a window surface and a coordinated compositor -// for use in the compositor unit tests. -class TestCompositorHostMac : public TestCompositorHost, - public AppKitHost { - public: - TestCompositorHostMac(const gfx::Rect& bounds, - ui::ContextFactory* context_factory); - ~TestCompositorHostMac() override; - - private: - // TestCompositorHost: - void Show() override; - ui::Compositor* GetCompositor() override; - - gfx::Rect bounds_; - - ui::ContextFactory* context_factory_; - - scoped_ptr<ui::Compositor> compositor_; - - // Owned. Released when window is closed. - NSWindow* window_; - - DISALLOW_COPY_AND_ASSIGN(TestCompositorHostMac); -}; - -TestCompositorHostMac::TestCompositorHostMac( - const gfx::Rect& bounds, - ui::ContextFactory* context_factory) - : bounds_(bounds), context_factory_(context_factory), window_(nil) { -} - -TestCompositorHostMac::~TestCompositorHostMac() { - // Release reference to |compositor_|. Important because the |compositor_| - // holds |this| as its delegate, so that reference must be removed here. - [[window_ contentView] setCompositor:NULL]; - [window_ setContentView:nil]; - - [window_ orderOut:nil]; - [window_ close]; -} - -void TestCompositorHostMac::Show() { - DCHECK(!window_); - window_ = [[NSWindow alloc] - initWithContentRect:NSMakeRect(bounds_.x(), - bounds_.y(), - bounds_.width(), - bounds_.height()) - styleMask:NSBorderlessWindowMask - backing:NSBackingStoreBuffered - defer:NO]; - base::scoped_nsobject<AcceleratedTestView> view( - [[AcceleratedTestView alloc] init]); - compositor_.reset(new ui::Compositor(view, - context_factory_, - base::ThreadTaskRunnerHandle::Get())); - compositor_->SetScaleAndSize(1.0f, bounds_.size()); - [view setCompositor:compositor_.get()]; - [window_ setContentView:view]; - [window_ orderFront:nil]; -} - -ui::Compositor* TestCompositorHostMac::GetCompositor() { - return compositor_.get(); -} - -// static -TestCompositorHost* TestCompositorHost::Create( - const gfx::Rect& bounds, - ui::ContextFactory* context_factory) { - return new TestCompositorHostMac(bounds, context_factory); -} - -} // namespace ui
diff --git a/ui/compositor/test/test_compositor_host_ozone.cc b/ui/compositor/test/test_compositor_host_ozone.cc deleted file mode 100644 index 4871564..0000000 --- a/ui/compositor/test/test_compositor_host_ozone.cc +++ /dev/null
@@ -1,79 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/compositor/test/test_compositor_host.h" - -#include "base/basictypes.h" -#include "base/bind.h" -#include "base/compiler_specific.h" -#include "base/logging.h" -#include "base/memory/scoped_ptr.h" -#include "base/memory/weak_ptr.h" -#include "base/thread_task_runner_handle.h" -#include "ui/compositor/compositor.h" -#include "ui/gfx/rect.h" - -namespace ui { - -class TestCompositorHostOzone : public TestCompositorHost { - public: - TestCompositorHostOzone(const gfx::Rect& bounds, - ui::ContextFactory* context_factory); - virtual ~TestCompositorHostOzone(); - - private: - // Overridden from TestCompositorHost: - virtual void Show() override; - virtual ui::Compositor* GetCompositor() override; - - void Draw(); - - gfx::Rect bounds_; - - ui::ContextFactory* context_factory_; - - scoped_ptr<ui::Compositor> compositor_; - - DISALLOW_COPY_AND_ASSIGN(TestCompositorHostOzone); -}; - -TestCompositorHostOzone::TestCompositorHostOzone( - const gfx::Rect& bounds, - ui::ContextFactory* context_factory) - : bounds_(bounds), - context_factory_(context_factory) {} - -TestCompositorHostOzone::~TestCompositorHostOzone() {} - -void TestCompositorHostOzone::Show() { - // Ozone should rightly have a backing native framebuffer - // An in-memory array draw into by OSMesa is a reasonble - // fascimile of a dumb framebuffer at present. - // GLSurface will allocate the array so long as it is provided - // with a non-0 widget. - // TODO(rjkroege): Use a "real" ozone widget when it is - // available: http://crbug.com/255128 - compositor_.reset(new ui::Compositor(1, - context_factory_, - base::ThreadTaskRunnerHandle::Get())); - compositor_->SetScaleAndSize(1.0f, bounds_.size()); -} - -ui::Compositor* TestCompositorHostOzone::GetCompositor() { - return compositor_.get(); -} - -void TestCompositorHostOzone::Draw() { - if (compositor_.get()) - compositor_->Draw(); -} - -// static -TestCompositorHost* TestCompositorHost::Create( - const gfx::Rect& bounds, - ui::ContextFactory* context_factory) { - return new TestCompositorHostOzone(bounds, context_factory); -} - -} // namespace ui
diff --git a/ui/compositor/test/test_compositor_host_win.cc b/ui/compositor/test/test_compositor_host_win.cc deleted file mode 100644 index 99a5a85..0000000 --- a/ui/compositor/test/test_compositor_host_win.cc +++ /dev/null
@@ -1,66 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/compositor/test/test_compositor_host.h" - -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "base/thread_task_runner_handle.h" -#include "ui/compositor/compositor.h" -#include "ui/gfx/win/window_impl.h" - -namespace ui { - -class TestCompositorHostWin : public TestCompositorHost, - public gfx::WindowImpl { - public: - TestCompositorHostWin(const gfx::Rect& bounds, - ui::ContextFactory* context_factory) { - Init(NULL, bounds); - compositor_.reset(new ui::Compositor(hwnd(), - context_factory, - base::ThreadTaskRunnerHandle::Get())); - compositor_->SetScaleAndSize(1.0f, GetSize()); - } - - virtual ~TestCompositorHostWin() { - DestroyWindow(hwnd()); - } - - // Overridden from TestCompositorHost: - virtual void Show() override { - ShowWindow(hwnd(), SW_SHOWNORMAL); - } - virtual ui::Compositor* GetCompositor() override { - return compositor_.get(); - } - - private: - CR_BEGIN_MSG_MAP_EX(TestCompositorHostWin) - CR_MSG_WM_PAINT(OnPaint) - CR_END_MSG_MAP() - - void OnPaint(HDC dc) { - compositor_->Draw(); - ValidateRect(hwnd(), NULL); - } - - gfx::Size GetSize() { - RECT r; - GetClientRect(hwnd(), &r); - return gfx::Rect(r).size(); - } - - scoped_ptr<ui::Compositor> compositor_; - - DISALLOW_COPY_AND_ASSIGN(TestCompositorHostWin); -}; - -TestCompositorHost* TestCompositorHost::Create( - const gfx::Rect& bounds, - ui::ContextFactory* context_factory) { - return new TestCompositorHostWin(bounds, context_factory); -} - -} // namespace ui
diff --git a/ui/compositor/test/test_compositor_host_x11.cc b/ui/compositor/test/test_compositor_host_x11.cc deleted file mode 100644 index d881d15..0000000 --- a/ui/compositor/test/test_compositor_host_x11.cc +++ /dev/null
@@ -1,100 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/compositor/test/test_compositor_host.h" - -#include <X11/Xlib.h> - -#include "base/basictypes.h" -#include "base/bind.h" -#include "base/compiler_specific.h" -#include "base/logging.h" -#include "base/memory/scoped_ptr.h" -#include "base/memory/weak_ptr.h" -#include "base/thread_task_runner_handle.h" -#include "ui/compositor/compositor.h" -#include "ui/gfx/rect.h" -#include "ui/gfx/x/x11_types.h" - -namespace ui { - -class TestCompositorHostX11 : public TestCompositorHost { - public: - TestCompositorHostX11(const gfx::Rect& bounds, - ui::ContextFactory* context_factory); - virtual ~TestCompositorHostX11(); - - private: - // Overridden from TestCompositorHost: - virtual void Show() override; - virtual ui::Compositor* GetCompositor() override; - - void Draw(); - - gfx::Rect bounds_; - - ui::ContextFactory* context_factory_; - - scoped_ptr<ui::Compositor> compositor_; - - XID window_; - - DISALLOW_COPY_AND_ASSIGN(TestCompositorHostX11); -}; - -TestCompositorHostX11::TestCompositorHostX11( - const gfx::Rect& bounds, - ui::ContextFactory* context_factory) - : bounds_(bounds), - context_factory_(context_factory) { -} - -TestCompositorHostX11::~TestCompositorHostX11() { -} - -void TestCompositorHostX11::Show() { - XDisplay* display = gfx::GetXDisplay(); - XSetWindowAttributes swa; - swa.event_mask = StructureNotifyMask | ExposureMask; - swa.override_redirect = True; - window_ = XCreateWindow( - display, - RootWindow(display, DefaultScreen(display)), // parent - bounds_.x(), bounds_.y(), bounds_.width(), bounds_.height(), - 0, // border width - CopyFromParent, // depth - InputOutput, - CopyFromParent, // visual - CWEventMask | CWOverrideRedirect, &swa); - XMapWindow(display, window_); - - while (1) { - XEvent event; - XNextEvent(display, &event); - if (event.type == MapNotify && event.xmap.window == window_) - break; - } - compositor_.reset(new ui::Compositor(window_, - context_factory_, - base::ThreadTaskRunnerHandle::Get())); - compositor_->SetScaleAndSize(1.0f, bounds_.size()); -} - -ui::Compositor* TestCompositorHostX11::GetCompositor() { - return compositor_.get(); -} - -void TestCompositorHostX11::Draw() { - if (compositor_.get()) - compositor_->Draw(); -} - -// static -TestCompositorHost* TestCompositorHost::Create( - const gfx::Rect& bounds, - ui::ContextFactory* context_factory) { - return new TestCompositorHostX11(bounds, context_factory); -} - -} // namespace ui
diff --git a/ui/compositor/test/test_layer_animation_delegate.cc b/ui/compositor/test/test_layer_animation_delegate.cc deleted file mode 100644 index e6053d6..0000000 --- a/ui/compositor/test/test_layer_animation_delegate.cc +++ /dev/null
@@ -1,106 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/compositor/test/test_layer_animation_delegate.h" - -namespace ui { - -TestLayerAnimationDelegate::TestLayerAnimationDelegate() - : opacity_(1.0f), - visibility_(true), - brightness_(0.0f), - grayscale_(0.0f), - color_(SK_ColorBLACK) { -} - -TestLayerAnimationDelegate::TestLayerAnimationDelegate( - const LayerAnimationDelegate& other) - : bounds_(other.GetBoundsForAnimation()), - transform_(other.GetTransformForAnimation()), - opacity_(other.GetOpacityForAnimation()), - visibility_(other.GetVisibilityForAnimation()), - color_(SK_ColorBLACK) { -} - -TestLayerAnimationDelegate::~TestLayerAnimationDelegate() { -} - -void TestLayerAnimationDelegate::SetBoundsFromAnimation( - const gfx::Rect& bounds) { - bounds_ = bounds; -} - -void TestLayerAnimationDelegate::SetTransformFromAnimation( - const gfx::Transform& transform) { - transform_ = transform; -} - -void TestLayerAnimationDelegate::SetOpacityFromAnimation(float opacity) { - opacity_ = opacity; -} - -void TestLayerAnimationDelegate::SetVisibilityFromAnimation(bool visibility) { - visibility_ = visibility; -} - -void TestLayerAnimationDelegate::SetBrightnessFromAnimation(float brightness) { - brightness_ = brightness; -} - -void TestLayerAnimationDelegate::SetGrayscaleFromAnimation(float grayscale) { - grayscale_ = grayscale; -} - -void TestLayerAnimationDelegate::SetColorFromAnimation(SkColor color) { - color_ = color; -} - -void TestLayerAnimationDelegate::ScheduleDrawForAnimation() { -} - -const gfx::Rect& TestLayerAnimationDelegate::GetBoundsForAnimation() const { - return bounds_; -} - -gfx::Transform TestLayerAnimationDelegate::GetTransformForAnimation() const { - return transform_; -} - -float TestLayerAnimationDelegate::GetOpacityForAnimation() const { - return opacity_; -} - -bool TestLayerAnimationDelegate::GetVisibilityForAnimation() const { - return visibility_; -} - -float TestLayerAnimationDelegate::GetBrightnessForAnimation() const { - return brightness_; -} - -float TestLayerAnimationDelegate::GetGrayscaleForAnimation() const { - return grayscale_; -} - -SkColor TestLayerAnimationDelegate::GetColorForAnimation() const { - return color_; -} - -float TestLayerAnimationDelegate::GetDeviceScaleFactor() const { - return 1.0f; -} - -void TestLayerAnimationDelegate::AddThreadedAnimation( - scoped_ptr<cc::Animation> animation) { -} - -void TestLayerAnimationDelegate::RemoveThreadedAnimation(int animation_id) { -} - -LayerAnimatorCollection* -TestLayerAnimationDelegate::GetLayerAnimatorCollection() { - return NULL; -} - -} // namespace ui
diff --git a/ui/compositor/test/test_layer_animation_delegate.h b/ui/compositor/test/test_layer_animation_delegate.h deleted file mode 100644 index 4b1f817..0000000 --- a/ui/compositor/test/test_layer_animation_delegate.h +++ /dev/null
@@ -1,56 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_TEST_TEST_LAYER_ANIMATION_DELEGATE_H_ -#define UI_COMPOSITOR_TEST_TEST_LAYER_ANIMATION_DELEGATE_H_ - -#include "base/compiler_specific.h" -#include "ui/compositor/layer_animation_delegate.h" -#include "ui/gfx/rect.h" -#include "ui/gfx/transform.h" - -namespace ui { - -class TestLayerAnimationDelegate : public LayerAnimationDelegate { - public: - TestLayerAnimationDelegate(); - explicit TestLayerAnimationDelegate(const LayerAnimationDelegate& other); - ~TestLayerAnimationDelegate() override; - - // Implementation of LayerAnimationDelegate - void SetBoundsFromAnimation(const gfx::Rect& bounds) override; - void SetTransformFromAnimation(const gfx::Transform& transform) override; - void SetOpacityFromAnimation(float opacity) override; - void SetVisibilityFromAnimation(bool visibility) override; - void SetBrightnessFromAnimation(float brightness) override; - void SetGrayscaleFromAnimation(float grayscale) override; - void SetColorFromAnimation(SkColor color) override; - void ScheduleDrawForAnimation() override; - const gfx::Rect& GetBoundsForAnimation() const override; - gfx::Transform GetTransformForAnimation() const override; - float GetOpacityForAnimation() const override; - bool GetVisibilityForAnimation() const override; - float GetBrightnessForAnimation() const override; - float GetGrayscaleForAnimation() const override; - SkColor GetColorForAnimation() const override; - float GetDeviceScaleFactor() const override; - void AddThreadedAnimation(scoped_ptr<cc::Animation> animation) override; - void RemoveThreadedAnimation(int animation_id) override; - LayerAnimatorCollection* GetLayerAnimatorCollection() override; - - private: - gfx::Rect bounds_; - gfx::Transform transform_; - float opacity_; - bool visibility_; - float brightness_; - float grayscale_; - SkColor color_; - - // Allow copy and assign. -}; - -} // namespace ui - -#endif // UI_COMPOSITOR_TEST_TEST_LAYER_ANIMATION_DELEGATE_H_
diff --git a/ui/compositor/test/test_layer_animation_observer.cc b/ui/compositor/test/test_layer_animation_observer.cc deleted file mode 100644 index abc74ae..0000000 --- a/ui/compositor/test/test_layer_animation_observer.cc +++ /dev/null
@@ -1,41 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/compositor/test/test_layer_animation_observer.h" - -#include <cstddef> - -namespace ui { - -TestLayerAnimationObserver::TestLayerAnimationObserver() - : last_ended_sequence_(NULL), - last_scheduled_sequence_(NULL), - last_aborted_sequence_(NULL), - requires_notification_when_animator_destroyed_(false) { -} - -TestLayerAnimationObserver::~TestLayerAnimationObserver() { -} - -void TestLayerAnimationObserver::OnLayerAnimationEnded( - LayerAnimationSequence* sequence) { - last_ended_sequence_ = sequence; -} - -void TestLayerAnimationObserver::OnLayerAnimationAborted( - LayerAnimationSequence* sequence) { - last_aborted_sequence_ = sequence; -} - -void TestLayerAnimationObserver::OnLayerAnimationScheduled( - LayerAnimationSequence* sequence) { - last_scheduled_sequence_ = sequence; -} - -bool -TestLayerAnimationObserver::RequiresNotificationWhenAnimatorDestroyed() const { - return requires_notification_when_animator_destroyed_; -} - -} // namespace ui
diff --git a/ui/compositor/test/test_layer_animation_observer.h b/ui/compositor/test/test_layer_animation_observer.h deleted file mode 100644 index 0f0a18e..0000000 --- a/ui/compositor/test/test_layer_animation_observer.h +++ /dev/null
@@ -1,57 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_TEST_TEST_LAYER_ANIMATION_OBSERVER_H_ -#define UI_COMPOSITOR_TEST_TEST_LAYER_ANIMATION_OBSERVER_H_ - -#include "base/compiler_specific.h" -#include "ui/compositor/layer_animation_observer.h" - -namespace ui { - -class LayerAnimationSequence; - -// Listens to animation ended notifications. Remembers the last sequence that -// it was notified about. -class TestLayerAnimationObserver : public LayerAnimationObserver { - public: - TestLayerAnimationObserver(); - ~TestLayerAnimationObserver() override; - - void OnLayerAnimationEnded(LayerAnimationSequence* sequence) override; - - void OnLayerAnimationAborted(LayerAnimationSequence* sequence) override; - - void OnLayerAnimationScheduled(LayerAnimationSequence* sequence) override; - - bool RequiresNotificationWhenAnimatorDestroyed() const override; - - const LayerAnimationSequence* last_ended_sequence() const { - return last_ended_sequence_; - } - - const LayerAnimationSequence* last_scheduled_sequence() const { - return last_scheduled_sequence_; - } - - const LayerAnimationSequence* last_aborted_sequence() const { - return last_aborted_sequence_; - } - - void set_requires_notification_when_animator_destroyed(bool value) { - requires_notification_when_animator_destroyed_ = value; - } - - private: - const LayerAnimationSequence* last_ended_sequence_; - const LayerAnimationSequence* last_scheduled_sequence_; - const LayerAnimationSequence* last_aborted_sequence_; - bool requires_notification_when_animator_destroyed_; - - // Copy and assign are allowed. -}; - -} // namespace ui - -#endif // UI_COMPOSITOR_TEST_TEST_LAYER_ANIMATION_OBSERVER_H_
diff --git a/ui/compositor/test/test_layers.cc b/ui/compositor/test/test_layers.cc deleted file mode 100644 index 2e71eac..0000000 --- a/ui/compositor/test/test_layers.cc +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/compositor/test/test_layers.h" - -#include "ui/compositor/layer.h" - -namespace ui { -namespace test { - -std::string ChildLayerNamesAsString(const ui::Layer& parent) { - std::string names; - for (std::vector<Layer*>::const_iterator it = parent.children().begin(); - it != parent.children().end(); ++it) { - if (!names.empty()) - names += " "; - names += (*it)->name(); - } - return names; -} - -} // namespace test -} // namespace ui
diff --git a/ui/compositor/test/test_layers.h b/ui/compositor/test/test_layers.h deleted file mode 100644 index 2307808..0000000 --- a/ui/compositor/test/test_layers.h +++ /dev/null
@@ -1,22 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_TEST_TEST_LAYERS_H_ -#define UI_COMPOSITOR_TEST_TEST_LAYERS_H_ - -#include <string> - -namespace ui { -class Layer; - -namespace test { - -// Returns a string containing the name of each of the child layers (bottommost -// first) of |parent|. The format of the string is "name1 name2 ..." -std::string ChildLayerNamesAsString(const ui::Layer& parent); - -} // namespace test -} // namespace ui - -#endif // UI_COMPOSITOR_TEST_TEST_LAYERS_H_
diff --git a/ui/compositor/test/test_suite.cc b/ui/compositor/test/test_suite.cc deleted file mode 100644 index d98f52d..0000000 --- a/ui/compositor/test/test_suite.cc +++ /dev/null
@@ -1,46 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/compositor/test/test_suite.h" - -#include "base/command_line.h" -#include "base/message_loop/message_loop.h" -#include "ui/compositor/compositor.h" -#include "ui/compositor/compositor_switches.h" -#include "ui/gfx/gfx_paths.h" -#include "ui/gl/gl_surface.h" - -#if defined(OS_WIN) -#include "ui/gfx/win/dpi.h" -#endif - -namespace ui { -namespace test { - -CompositorTestSuite::CompositorTestSuite(int argc, char** argv) - : TestSuite(argc, argv) {} - -CompositorTestSuite::~CompositorTestSuite() {} - -void CompositorTestSuite::Initialize() { - base::TestSuite::Initialize(); - gfx::GLSurface::InitializeOneOffForTests(); - - gfx::RegisterPathProvider(); - -#if defined(OS_WIN) - gfx::InitDeviceScaleFactor(1.0f); -#endif - - message_loop_.reset(new base::MessageLoopForUI); -} - -void CompositorTestSuite::Shutdown() { - message_loop_.reset(); - - base::TestSuite::Shutdown(); -} - -} // namespace test -} // namespace ui
diff --git a/ui/compositor/test/test_suite.h b/ui/compositor/test/test_suite.h deleted file mode 100644 index 5cbefe7..0000000 --- a/ui/compositor/test/test_suite.h +++ /dev/null
@@ -1,39 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_TEST_TEST_SUITE_H_ -#define UI_COMPOSITOR_TEST_TEST_SUITE_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "base/test/test_suite.h" - -namespace base { -class MessageLoop; -} - -namespace ui { -namespace test { - -class CompositorTestSuite : public base::TestSuite { - public: - CompositorTestSuite(int argc, char** argv); - ~CompositorTestSuite() override; - - protected: - // Overridden from base::TestSuite: - void Initialize() override; - void Shutdown() override; - - private: - scoped_ptr<base::MessageLoop> message_loop_; - - DISALLOW_COPY_AND_ASSIGN(CompositorTestSuite); -}; - -} // namespace test -} // namespace ui - -#endif // UI_COMPOSITOR_TEST_TEST_SUITE_H_
diff --git a/ui/compositor/test/test_utils.cc b/ui/compositor/test/test_utils.cc deleted file mode 100644 index 145e025..0000000 --- a/ui/compositor/test/test_utils.cc +++ /dev/null
@@ -1,39 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/compositor/test/test_utils.h" - -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/gfx/rect.h" -#include "ui/gfx/transform.h" - -namespace ui { - -//TODO(avallee): Make this into a predicate and add some matrix pretty printing. -void CheckApproximatelyEqual(const gfx::Transform& lhs, - const gfx::Transform& rhs) { - unsigned int errors = 0; - for (int i = 0; i < 4; ++i) { - for (int j = 0; j < 4; ++j) { - EXPECT_FLOAT_EQ(lhs.matrix().get(i, j), rhs.matrix().get(i, j)) - << "(i, j) = (" << i << ", " << j << "), error count: " << ++errors; - } - } - - if (errors) { - ADD_FAILURE() << "Expected matrix:\n" - << lhs.ToString() << "\n" - << "Actual matrix:\n" - << rhs.ToString(); - } -} - -void CheckApproximatelyEqual(const gfx::Rect& lhs, const gfx::Rect& rhs) { - EXPECT_FLOAT_EQ(lhs.x(), rhs.x()); - EXPECT_FLOAT_EQ(lhs.y(), rhs.y()); - EXPECT_FLOAT_EQ(lhs.width(), rhs.width()); - EXPECT_FLOAT_EQ(lhs.height(), rhs.height()); -} - -} // namespace ui
diff --git a/ui/compositor/test/test_utils.h b/ui/compositor/test/test_utils.h deleted file mode 100644 index 9f2163b..0000000 --- a/ui/compositor/test/test_utils.h +++ /dev/null
@@ -1,21 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_TEST_TEST_UTILS_H_ -#define UI_COMPOSITOR_TEST_TEST_UTILS_H_ - -namespace gfx { -class Rect; -class Transform; -} - -namespace ui { - -void CheckApproximatelyEqual(const gfx::Transform& lhs, - const gfx::Transform& rhs); -void CheckApproximatelyEqual(const gfx::Rect& lhs, const gfx::Rect& rhs); - -} // namespace ui - -#endif // UI_COMPOSITOR_TEST_TEST_UTILS_H_
diff --git a/ui/compositor/transform_animation_curve_adapter.cc b/ui/compositor/transform_animation_curve_adapter.cc deleted file mode 100644 index 0f697e0..0000000 --- a/ui/compositor/transform_animation_curve_adapter.cc +++ /dev/null
@@ -1,151 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/compositor/transform_animation_curve_adapter.h" - -#include "cc/base/time_util.h" - -namespace ui { - -TransformAnimationCurveAdapter::TransformAnimationCurveAdapter( - gfx::Tween::Type tween_type, - gfx::Transform initial_value, - gfx::Transform target_value, - base::TimeDelta duration) - : tween_type_(tween_type), - initial_value_(initial_value), - target_value_(target_value), - duration_(duration) { - gfx::DecomposeTransform(&decomposed_initial_value_, initial_value_); - gfx::DecomposeTransform(&decomposed_target_value_, target_value_); -} - -TransformAnimationCurveAdapter::~TransformAnimationCurveAdapter() { -} - -base::TimeDelta TransformAnimationCurveAdapter::Duration() const { - return duration_; -} - -scoped_ptr<cc::AnimationCurve> TransformAnimationCurveAdapter::Clone() const { - return make_scoped_ptr(new TransformAnimationCurveAdapter( - tween_type_, initial_value_, target_value_, duration_)); -} - -gfx::Transform TransformAnimationCurveAdapter::GetValue( - base::TimeDelta t) const { - if (t >= duration_) - return target_value_; - if (t <= base::TimeDelta()) - return initial_value_; - double progress = cc::TimeUtil::Divide(t, duration_); - - gfx::DecomposedTransform to_return; - gfx::BlendDecomposedTransforms(&to_return, - decomposed_target_value_, - decomposed_initial_value_, - gfx::Tween::CalculateValue(tween_type_, - progress)); - return gfx::ComposeTransform(to_return); -} - -bool TransformAnimationCurveAdapter::AnimatedBoundsForBox( - const gfx::BoxF& box, - gfx::BoxF* bounds) const { - // TODO(ajuma): Once cc::TransformOperation::BlendedBoundsForBox supports - // computing bounds for TransformOperationMatrix, use that to compute - // the bounds we need here. - return false; -} - -bool TransformAnimationCurveAdapter::AffectsScale() const { - return !initial_value_.IsIdentityOrTranslation() || - !target_value_.IsIdentityOrTranslation(); -} - -bool TransformAnimationCurveAdapter::IsTranslation() const { - return initial_value_.IsIdentityOrTranslation() && - target_value_.IsIdentityOrTranslation(); -} - -bool TransformAnimationCurveAdapter::PreservesAxisAlignment() const { - return (initial_value_.IsIdentity() || - initial_value_.IsScaleOrTranslation()) && - (target_value_.IsIdentity() || target_value_.IsScaleOrTranslation()); -} - -bool TransformAnimationCurveAdapter::MaximumTargetScale( - bool forward_direction, - float* max_scale) const { - return false; -} - -InverseTransformCurveAdapter::InverseTransformCurveAdapter( - TransformAnimationCurveAdapter base_curve, - gfx::Transform initial_value, - base::TimeDelta duration) - : base_curve_(base_curve), - initial_value_(initial_value), - duration_(duration) { - effective_initial_value_ = - base_curve_.GetValue(base::TimeDelta()) * initial_value_; -} - -InverseTransformCurveAdapter::~InverseTransformCurveAdapter() { -} - -base::TimeDelta InverseTransformCurveAdapter::Duration() const { - return duration_; -} - -scoped_ptr<cc::AnimationCurve> InverseTransformCurveAdapter::Clone() const { - return make_scoped_ptr( - new InverseTransformCurveAdapter(base_curve_, initial_value_, duration_)); -} - -gfx::Transform InverseTransformCurveAdapter::GetValue(base::TimeDelta t) const { - if (t <= base::TimeDelta()) - return initial_value_; - - gfx::Transform base_transform = base_curve_.GetValue(t); - // Invert base - gfx::Transform to_return(gfx::Transform::kSkipInitialization); - bool is_invertible = base_transform.GetInverse(&to_return); - DCHECK(is_invertible); - - to_return.PreconcatTransform(effective_initial_value_); - return to_return; -} - -bool InverseTransformCurveAdapter::AnimatedBoundsForBox( - const gfx::BoxF& box, - gfx::BoxF* bounds) const { - // TODO(ajuma): Once cc::TransformOperation::BlendedBoundsForBox supports - // computing bounds for TransformOperationMatrix, use that to compute - // the bounds we need here. - return false; -} - -bool InverseTransformCurveAdapter::AffectsScale() const { - return !initial_value_.IsIdentityOrTranslation() || - base_curve_.AffectsScale(); -} - -bool InverseTransformCurveAdapter::IsTranslation() const { - return initial_value_.IsIdentityOrTranslation() && - base_curve_.IsTranslation(); -} - -bool InverseTransformCurveAdapter::PreservesAxisAlignment() const { - return (initial_value_.IsIdentity() || - initial_value_.IsScaleOrTranslation()) && - (base_curve_.PreservesAxisAlignment()); -} - -bool InverseTransformCurveAdapter::MaximumTargetScale(bool forward_direction, - float* max_scale) const { - return false; -} - -} // namespace ui
diff --git a/ui/compositor/transform_animation_curve_adapter.h b/ui/compositor/transform_animation_curve_adapter.h deleted file mode 100644 index ba88c59..0000000 --- a/ui/compositor/transform_animation_curve_adapter.h +++ /dev/null
@@ -1,82 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_COMPOSITOR_TRANSFORM_ANIMATION_CURVE_ADAPTER_H_ -#define UI_COMPOSITOR_TRANSFORM_ANIMATION_CURVE_ADAPTER_H_ - -#include "base/time/time.h" -#include "cc/animation/animation_curve.h" -#include "ui/compositor/compositor_export.h" -#include "ui/gfx/animation/tween.h" -#include "ui/gfx/transform.h" -#include "ui/gfx/transform_util.h" - -namespace ui { - -class COMPOSITOR_EXPORT TransformAnimationCurveAdapter - : public cc::TransformAnimationCurve { - public: - TransformAnimationCurveAdapter(gfx::Tween::Type tween_type, - gfx::Transform intial_value, - gfx::Transform target_value, - base::TimeDelta duration); - - ~TransformAnimationCurveAdapter() override; - - // TransformAnimationCurve implementation. - base::TimeDelta Duration() const override; - scoped_ptr<AnimationCurve> Clone() const override; - gfx::Transform GetValue(base::TimeDelta t) const override; - bool AnimatedBoundsForBox(const gfx::BoxF& box, - gfx::BoxF* bounds) const override; - bool AffectsScale() const override; - bool IsTranslation() const override; - bool PreservesAxisAlignment() const override; - bool MaximumTargetScale(bool forward_direction, - float* max_scale) const override; - - private: - gfx::Tween::Type tween_type_; - gfx::Transform initial_value_; - gfx::Transform target_value_; - gfx::DecomposedTransform decomposed_initial_value_; - gfx::DecomposedTransform decomposed_target_value_; - base::TimeDelta duration_; - - DISALLOW_ASSIGN(TransformAnimationCurveAdapter); -}; - -class COMPOSITOR_EXPORT InverseTransformCurveAdapter - : public cc::TransformAnimationCurve { - public: - InverseTransformCurveAdapter(TransformAnimationCurveAdapter base_curve, - gfx::Transform initial_value, - base::TimeDelta duration); - - ~InverseTransformCurveAdapter() override; - - base::TimeDelta Duration() const override; - scoped_ptr<AnimationCurve> Clone() const override; - gfx::Transform GetValue(base::TimeDelta t) const override; - bool AnimatedBoundsForBox(const gfx::BoxF& box, - gfx::BoxF* bounds) const override; - bool AffectsScale() const override; - bool IsTranslation() const override; - bool PreservesAxisAlignment() const override; - bool MaximumTargetScale(bool forward_direction, - float* max_scale) const override; - - private: - TransformAnimationCurveAdapter base_curve_; - gfx::Transform initial_value_; - gfx::Transform effective_initial_value_; - base::TimeDelta duration_; - - DISALLOW_ASSIGN(InverseTransformCurveAdapter); -}; - -} // namespace ui - -#endif // UI_COMPOSITOR_TRANSFORM_ANIMATION_CURVE_ADAPTER_H_ -
diff --git a/ui/compositor/transform_animation_curve_adapter_unittest.cc b/ui/compositor/transform_animation_curve_adapter_unittest.cc deleted file mode 100644 index b68e862..0000000 --- a/ui/compositor/transform_animation_curve_adapter_unittest.cc +++ /dev/null
@@ -1,59 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/compositor/transform_animation_curve_adapter.h" - -#include <sstream> - -#include "base/time/time.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/compositor/test/test_utils.h" - -namespace ui { - -namespace { - -// Check that the inverse transform curve gives the gives a transform that when -// applied on top of the parent transform gives the original transform -TEST(InverseTransformCurveAdapterTest, InversesTransform) { - gfx::Transform parent_start, parent_target; - parent_start.Scale(0.5, 3.0); - parent_start.Translate(-20.0, 30.0); - parent_target.Translate(0, 100); - - gfx::Transform child_transform; - child_transform.Rotate(-30.0); - - base::TimeDelta duration = base::TimeDelta::FromSeconds(1); - - const gfx::Transform effective_child_transform = - parent_start * child_transform; - - TransformAnimationCurveAdapter parent_curve(gfx::Tween::LINEAR, - parent_start, - parent_target, - duration); - - InverseTransformCurveAdapter child_curve(parent_curve, - child_transform, - duration); - static const int kSteps = 1000; - double step = 1.0 / kSteps; - for (int i = 0; i <= kSteps ; ++i) { - std::ostringstream message; - message << "Step " << i << " of " << kSteps; - SCOPED_TRACE(message.str()); - gfx::Transform progress_parent_transform = - parent_curve.GetValue(i*step); - gfx::Transform progress_child_transform = - child_curve.GetValue(i*step); - CheckApproximatelyEqual(effective_child_transform, - progress_parent_transform * - progress_child_transform); - } -} - -} // namespace - -} // namespace ui
diff --git a/ui/display/BUILD.gn b/ui/display/BUILD.gn index d8d8c7c..722841a 100644 --- a/ui/display/BUILD.gn +++ b/ui/display/BUILD.gn
@@ -8,7 +8,6 @@ sources = [ "chromeos/display_configurator.cc", "chromeos/display_configurator.h", - "chromeos/ozone/display_configurator_ozone.cc", "chromeos/x11/display_configurator_x11.cc", "chromeos/x11/display_mode_x11.cc", "chromeos/x11/display_mode_x11.h", @@ -42,31 +41,11 @@ "//build/config/linux:xrandr", ] deps += [ "//ui/events/platform" ] - if (is_chromeos) { - sources -= [ "chromeos/ozone/display_configurator_ozone.cc" ] - } } if (is_chromeos) { deps += [ "//ui/display/types" ] } - - if (use_ozone) { - deps += [ "//ui/ozone" ] - sources -= [ - "chromeos/x11/display_configurator_x11.cc", - "chromeos/x11/display_mode_x11.cc", - "chromeos/x11/display_mode_x11.h", - "chromeos/x11/display_snapshot_x11.cc", - "chromeos/x11/display_snapshot_x11.h", - "chromeos/x11/display_util_x11.cc", - "chromeos/x11/display_util_x11.h", - "chromeos/x11/native_display_delegate_x11.cc", - "chromeos/x11/native_display_delegate_x11.h", - "chromeos/x11/native_display_event_dispatcher_x11.cc", - "chromeos/x11/native_display_event_dispatcher_x11.h", - ] - } } component("test_util") {
diff --git a/ui/display/chromeos/ozone/DEPS b/ui/display/chromeos/ozone/DEPS deleted file mode 100644 index de08167..0000000 --- a/ui/display/chromeos/ozone/DEPS +++ /dev/null
@@ -1,3 +0,0 @@ -include_rules = [ - "+ui/ozone/public", -]
diff --git a/ui/display/chromeos/ozone/display_configurator_ozone.cc b/ui/display/chromeos/ozone/display_configurator_ozone.cc deleted file mode 100644 index 858d21f..0000000 --- a/ui/display/chromeos/ozone/display_configurator_ozone.cc +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/display/chromeos/display_configurator.h" - -#include "ui/display/types/native_display_delegate.h" -#include "ui/ozone/public/ozone_platform.h" - -namespace ui { - -scoped_ptr<NativeDisplayDelegate> -DisplayConfigurator::CreatePlatformNativeDisplayDelegate() { - return ui::OzonePlatform::GetInstance()->CreateNativeDisplayDelegate(); -} - -} // namespace ui
diff --git a/ui/display/display.gyp b/ui/display/display.gyp index ef1d6af..1631166 100644 --- a/ui/display/display.gyp +++ b/ui/display/display.gyp
@@ -47,7 +47,6 @@ # Note: file list duplicated in GN build. 'chromeos/display_configurator.cc', 'chromeos/display_configurator.h', - 'chromeos/ozone/display_configurator_ozone.cc', 'chromeos/x11/display_configurator_x11.cc', 'chromeos/x11/display_mode_x11.cc', 'chromeos/x11/display_mode_x11.h', @@ -78,11 +77,6 @@ 'display_types', ], }], - ['use_ozone == 1', { - 'dependencies': [ - '../../ui/ozone/ozone.gyp:ozone', - ], - }], ], }, {
diff --git a/ui/events/BUILD.gn b/ui/events/BUILD.gn index 00e648a..33740d5 100644 --- a/ui/events/BUILD.gn +++ b/ui/events/BUILD.gn
@@ -146,20 +146,7 @@ deps += [ "//ui/gfx/x" ] } - if (!is_chromeos && is_linux) { - sources += [ - "linux/text_edit_command_auralinux.cc", - "linux/text_edit_command_auralinux.h", - "linux/text_edit_key_bindings_delegate_auralinux.cc", - "linux/text_edit_key_bindings_delegate_auralinux.h", - ] - } - - if (use_ozone) { - sources += [ "ozone/events_ozone.cc" ] - } - - if (is_win || is_mac || use_x11 || use_ozone) { + if (is_win || is_mac || use_x11) { sources -= [ "events_stub.cc" ] } } @@ -305,13 +292,6 @@ sources -= [ "x/events_x_unittest.cc" ] } - if (use_ozone) { - sources += [ - "ozone/evdev/key_event_converter_evdev_unittest.cc", - "ozone/evdev/touch_event_converter_evdev_unittest.cc", - ] - } - if (use_aura) { sources += [ "gestures/gesture_provider_impl_unittest.cc" ] }
diff --git a/ui/events/linux/text_edit_command_auralinux.cc b/ui/events/linux/text_edit_command_auralinux.cc deleted file mode 100644 index 4429225..0000000 --- a/ui/events/linux/text_edit_command_auralinux.cc +++ /dev/null
@@ -1,124 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/events/linux/text_edit_command_auralinux.h" - -#include "base/logging.h" - -namespace ui { - -std::string TextEditCommandAuraLinux::GetCommandString() const { - std::string base_name; - switch (command_id_) { - case COPY: - base_name = "Copy"; - break; - case CUT: - base_name = "Cut"; - break; - case DELETE_BACKWARD: - base_name = "DeleteBackward"; - break; - case DELETE_FORWARD: - base_name = "DeleteForward"; - break; - case DELETE_TO_BEGINING_OF_LINE: - base_name = "DeleteToBeginningOfLine"; - break; - case DELETE_TO_BEGINING_OF_PARAGRAPH: - base_name = "DeleteToBeginningOfParagraph"; - break; - case DELETE_TO_END_OF_LINE: - base_name = "DeleteToEndOfLine"; - break; - case DELETE_TO_END_OF_PARAGRAPH: - base_name = "DeleteToEndOfParagraph"; - break; - case DELETE_WORD_BACKWARD: - base_name = "DeleteWordBackward"; - break; - case DELETE_WORD_FORWARD: - base_name = "DeleteWordForward"; - break; - case INSERT_TEXT: - base_name = "InsertText"; - break; - case MOVE_BACKWARD: - base_name = "MoveBackward"; - break; - case MOVE_DOWN: - base_name = "MoveDown"; - break; - case MOVE_FORWARD: - base_name = "MoveForward"; - break; - case MOVE_LEFT: - base_name = "MoveLeft"; - break; - case MOVE_PAGE_DOWN: - base_name = "MovePageDown"; - break; - case MOVE_PAGE_UP: - base_name = "MovePageUp"; - break; - case MOVE_RIGHT: - base_name = "MoveRight"; - break; - case MOVE_TO_BEGINING_OF_DOCUMENT: - base_name = "MoveToBeginningOfDocument"; - break; - case MOVE_TO_BEGINING_OF_LINE: - base_name = "MoveToBeginningOfLine"; - break; - case MOVE_TO_BEGINING_OF_PARAGRAPH: - base_name = "MoveToBeginningOfParagraph"; - break; - case MOVE_TO_END_OF_DOCUMENT: - base_name = "MoveToEndOfDocument"; - break; - case MOVE_TO_END_OF_LINE: - base_name = "MoveToEndOfLine"; - break; - case MOVE_TO_END_OF_PARAGRAPH: - base_name = "MoveToEndOfParagraph"; - break; - case MOVE_UP: - base_name = "MoveUp"; - break; - case MOVE_WORD_BACKWARD: - base_name = "MoveWordBackward"; - break; - case MOVE_WORD_FORWARD: - base_name = "MoveWordForward"; - break; - case MOVE_WORD_LEFT: - base_name = "MoveWordLeft"; - break; - case MOVE_WORD_RIGHT: - base_name = "MoveWordRight"; - break; - case PASTE: - base_name = "Paste"; - break; - case SELECT_ALL: - base_name = "SelectAll"; - break; - case SET_MARK: - base_name = "SetMark"; - break; - case UNSELECT: - base_name = "Unselect"; - break; - case INVALID_COMMAND: - NOTREACHED(); - return std::string(); - } - - if (extend_selection()) - base_name += "AndModifySelection"; - - return base_name; -} - -} // namespace ui
diff --git a/ui/events/linux/text_edit_command_auralinux.h b/ui/events/linux/text_edit_command_auralinux.h deleted file mode 100644 index 82d3af2..0000000 --- a/ui/events/linux/text_edit_command_auralinux.h +++ /dev/null
@@ -1,82 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_EVENTS_X_TEXT_EDIT_COMMAND_X11_H_ -#define UI_EVENTS_X_TEXT_EDIT_COMMAND_X11_H_ - -#include <string> - -#include "ui/events/events_export.h" - -namespace ui { - -// Represents a command that performs a specific operation on text. -// Copy and assignment are explicitly allowed; these objects live in vectors. -class EVENTS_EXPORT TextEditCommandAuraLinux { - public: - enum CommandId { - COPY, - CUT, - DELETE_BACKWARD, - DELETE_FORWARD, - DELETE_TO_BEGINING_OF_LINE, - DELETE_TO_BEGINING_OF_PARAGRAPH, - DELETE_TO_END_OF_LINE, - DELETE_TO_END_OF_PARAGRAPH, - DELETE_WORD_BACKWARD, - DELETE_WORD_FORWARD, - INSERT_TEXT, - MOVE_BACKWARD, - MOVE_DOWN, - MOVE_FORWARD, - MOVE_LEFT, - MOVE_PAGE_DOWN, - MOVE_PAGE_UP, - MOVE_RIGHT, - MOVE_TO_BEGINING_OF_DOCUMENT, - MOVE_TO_BEGINING_OF_LINE, - MOVE_TO_BEGINING_OF_PARAGRAPH, - MOVE_TO_END_OF_DOCUMENT, - MOVE_TO_END_OF_LINE, - MOVE_TO_END_OF_PARAGRAPH, - MOVE_UP, - MOVE_WORD_BACKWARD, - MOVE_WORD_FORWARD, - MOVE_WORD_LEFT, - MOVE_WORD_RIGHT, - PASTE, - SELECT_ALL, - SET_MARK, - UNSELECT, - INVALID_COMMAND - }; - - TextEditCommandAuraLinux(CommandId command_id, - const std::string& argument, - bool extend_selection) - : command_id_(command_id), - argument_(argument), - extend_selection_(extend_selection) {} - - CommandId command_id() const { return command_id_; } - const std::string& argument() const { return argument_; } - bool extend_selection() const { return extend_selection_; } - - // We communicate these commands back to blink with a string representation. - // This will combine the base command name with "AndModifySelection" if we - // have |extend_selection_| set. - std::string GetCommandString() const; - - private: - CommandId command_id_; - - std::string argument_; - - // In addition to executing the command, modify the selection. - bool extend_selection_; -}; - -} // namespace ui - -#endif // UI_EVENTS_X_TEXT_EDIT_COMMAND_X11_H_
diff --git a/ui/events/linux/text_edit_key_bindings_delegate_auralinux.cc b/ui/events/linux/text_edit_key_bindings_delegate_auralinux.cc deleted file mode 100644 index e6a941b..0000000 --- a/ui/events/linux/text_edit_key_bindings_delegate_auralinux.cc +++ /dev/null
@@ -1,23 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/events/linux/text_edit_key_bindings_delegate_auralinux.h" - -namespace ui { - -namespace { -// Optional delegate. Unowned pointer. -TextEditKeyBindingsDelegateAuraLinux* text_edit_keybinding_delegate_ = 0; -} - -void SetTextEditKeyBindingsDelegate( - TextEditKeyBindingsDelegateAuraLinux* delegate) { - text_edit_keybinding_delegate_ = delegate; -} - -TextEditKeyBindingsDelegateAuraLinux* GetTextEditKeyBindingsDelegate() { - return text_edit_keybinding_delegate_; -} - -} // namespace ui
diff --git a/ui/events/linux/text_edit_key_bindings_delegate_auralinux.h b/ui/events/linux/text_edit_key_bindings_delegate_auralinux.h deleted file mode 100644 index d291626..0000000 --- a/ui/events/linux/text_edit_key_bindings_delegate_auralinux.h +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_EVENTS_X_TEXT_EDIT_KEY_BINDINGS_DELEGATE_X11_H_ -#define UI_EVENTS_X_TEXT_EDIT_KEY_BINDINGS_DELEGATE_X11_H_ - -#include <vector> - -#include "ui/events/events_export.h" - -namespace ui { -class Event; -class TextEditCommandAuraLinux; - -// An interface which can interpret various text editing commands out of key -// events. -// -// On desktop Linux, we've traditionally supported the user's custom -// keybindings. We need to support this in both content/ and in views/. -class EVENTS_EXPORT TextEditKeyBindingsDelegateAuraLinux { - public: - // Matches a key event against the users' platform specific key bindings, - // false will be returned if the key event doesn't correspond to a predefined - // key binding. Edit commands matched with |event| will be stored in - // |edit_commands|, if |edit_commands| is non-NULL. - virtual bool MatchEvent(const ui::Event& event, - std::vector<TextEditCommandAuraLinux>* commands) = 0; - - protected: - virtual ~TextEditKeyBindingsDelegateAuraLinux() {} -}; - -// Sets/Gets the global TextEditKeyBindingsDelegateAuraLinux. No ownership -// changes. Can be NULL. -EVENTS_EXPORT void SetTextEditKeyBindingsDelegate( - TextEditKeyBindingsDelegateAuraLinux* delegate); -EVENTS_EXPORT TextEditKeyBindingsDelegateAuraLinux* - GetTextEditKeyBindingsDelegate(); - -} // namespace ui - -#endif // UI_EVENTS_X_TEXT_EDIT_KEY_BINDINGS_DELEGATE_X11_H_
diff --git a/ui/events/ozone/BUILD.gn b/ui/events/ozone/BUILD.gn deleted file mode 100644 index 572b7d5..0000000 --- a/ui/events/ozone/BUILD.gn +++ /dev/null
@@ -1,89 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import("//build/config/features.gni") -import("//build/config/ui.gni") - -component("events_ozone") { - sources = [ - "device/device_event.cc", - "device/device_event.h", - "device/device_event_observer.h", - "device/device_manager.cc", - "device/device_manager.h", - "device/device_manager_manual.cc", - "device/device_manager_manual.h", - "device/udev/device_manager_udev.cc", - "device/udev/device_manager_udev.h", - "events_ozone_export.h", - ] - - deps = [ - "//base", - ] - - defines = [ "EVENTS_OZONE_IMPLEMENTATION" ] - - if (!use_udev) { - sources -= [ - "device/udev/device_manager_udev.cc", - "device/udev/device_manager_udev.h", - ] - } - - if (use_ozone_evdev && use_udev) { - deps += [ "//device/udev_linux" ] - } -} - -component("events_ozone_evdev") { - sources = [ - "evdev/event_converter_evdev.cc", - "evdev/event_converter_evdev.h", - "evdev/event_device_info.cc", - "evdev/event_device_info.h", - "evdev/event_factory_evdev.cc", - "evdev/event_factory_evdev.h", - "evdev/event_modifiers_evdev.cc", - "evdev/event_modifiers_evdev.h", - "evdev/events_ozone_evdev_export.h", - "evdev/key_event_converter_evdev.cc", - "evdev/key_event_converter_evdev.h", - "evdev/touch_event_converter_evdev.cc", - "evdev/touch_event_converter_evdev.h", - ] - - defines = [ "EVENTS_OZONE_EVDEV_IMPLEMENTATION" ] - - deps = [ - ":events_ozone", - "//base", - "//ui/events/platform", - "//ui/gfx", - ] - - if (use_ozone_evdev) { - defines += [ "USE_OZONE_EVDEV=1" ] - } - - if (use_ozone_evdev && use_evdev_gestures) { - sources += [ - "evdev/libgestures_glue/event_reader_libevdev_cros.cc", - "evdev/libgestures_glue/event_reader_libevdev_cros.h", - "evdev/libgestures_glue/gesture_interpreter_libevdev_cros.cc", - "evdev/libgestures_glue/gesture_interpreter_libevdev_cros.h", - "evdev/libgestures_glue/gesture_logging.cc", - "evdev/libgestures_glue/gesture_logging.h", - "evdev/libgestures_glue/gesture_timer_provider.cc", - "evdev/libgestures_glue/gesture_timer_provider.h", - ] - - defines += [ "USE_EVDEV_GESTURES" ] - - configs += [ - "//build/config/linux:libevdev-cros", - "//build/config/linux:libgestures", - ] - } -}
diff --git a/ui/events/ozone/DEPS b/ui/events/ozone/DEPS deleted file mode 100644 index 3f27114..0000000 --- a/ui/events/ozone/DEPS +++ /dev/null
@@ -1,4 +0,0 @@ -include_rules = [ - "+device/udev_linux", - "+ui/ozone/public", -]
diff --git a/ui/events/ozone/OWNERS b/ui/events/ozone/OWNERS deleted file mode 100644 index 479c4d8..0000000 --- a/ui/events/ozone/OWNERS +++ /dev/null
@@ -1,2 +0,0 @@ -rjkroege@chromium.org -spang@chromium.org
diff --git a/ui/events/ozone/device/device_event.cc b/ui/events/ozone/device/device_event.cc deleted file mode 100644 index e20079a..0000000 --- a/ui/events/ozone/device/device_event.cc +++ /dev/null
@@ -1,16 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/events/ozone/device/device_event.h" - -namespace ui { - -DeviceEvent::DeviceEvent(DeviceType type, - ActionType action, - const base::FilePath& path) - : device_type_(type), - action_type_(action), - path_(path) {} - -} // namespace ui
diff --git a/ui/events/ozone/device/device_event.h b/ui/events/ozone/device/device_event.h deleted file mode 100644 index a24394c..0000000 --- a/ui/events/ozone/device/device_event.h +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_EVENTS_OZONE_DEVICE_EVENT_H_ -#define UI_EVENTS_OZONE_DEVICE_EVENT_H_ - -#include "base/files/file_path.h" -#include "base/macros.h" -#include "ui/events/ozone/events_ozone_export.h" - -namespace ui { - -class EVENTS_OZONE_EXPORT DeviceEvent { - public: - enum DeviceType { - INPUT, - DISPLAY, - }; - - enum ActionType { - ADD, - REMOVE, - CHANGE, - }; - - DeviceEvent(DeviceType type, ActionType action, const base::FilePath& path); - - DeviceType device_type() const { return device_type_; } - ActionType action_type() const { return action_type_; } - base::FilePath path() const { return path_; } - - private: - DeviceType device_type_; - ActionType action_type_; - base::FilePath path_; - - DISALLOW_COPY_AND_ASSIGN(DeviceEvent); -}; - -} // namespace ui - -#endif // UI_EVENTS_OZONE_DEVICE_EVENT_H_
diff --git a/ui/events/ozone/device/device_event_observer.h b/ui/events/ozone/device/device_event_observer.h deleted file mode 100644 index 7ad2f49..0000000 --- a/ui/events/ozone/device/device_event_observer.h +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_EVENTS_OZONE_DEVICE_EVENT_OBSERVER_H_ -#define UI_EVENTS_OZONE_DEVICE_EVENT_OBSERVER_H_ - -#include "ui/events/ozone/events_ozone_export.h" - -namespace ui { - -class DeviceEvent; - -class EVENTS_OZONE_EXPORT DeviceEventObserver { - public: - virtual ~DeviceEventObserver() {} - - virtual void OnDeviceEvent(const DeviceEvent& event) = 0; -}; - -} // namespace ui - -#endif // UI_EVENTS_OZONE_DEVICE_EVENT_OBSERVER_H_ -
diff --git a/ui/events/ozone/device/device_manager.cc b/ui/events/ozone/device/device_manager.cc deleted file mode 100644 index bbd5d80..0000000 --- a/ui/events/ozone/device/device_manager.cc +++ /dev/null
@@ -1,23 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/events/ozone/device/device_manager.h" - -#if defined(USE_UDEV) -#include "ui/events/ozone/device/udev/device_manager_udev.h" -#else -#include "ui/events/ozone/device/device_manager_manual.h" -#endif - -namespace ui { - -scoped_ptr<DeviceManager> CreateDeviceManager() { -#if defined(USE_UDEV) - return scoped_ptr<DeviceManager>(new DeviceManagerUdev()); -#else - return scoped_ptr<DeviceManager>(new DeviceManagerManual()); -#endif -} - -} // namespace ui
diff --git a/ui/events/ozone/device/device_manager.h b/ui/events/ozone/device/device_manager.h deleted file mode 100644 index 0551e7e..0000000 --- a/ui/events/ozone/device/device_manager.h +++ /dev/null
@@ -1,36 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_EVENTS_OZONE_DEVICE_DEVICE_MANAGER_H_ -#define UI_EVENTS_OZONE_DEVICE_DEVICE_MANAGER_H_ - -#include "base/memory/scoped_ptr.h" -#include "ui/events/ozone/events_ozone_export.h" - -namespace ui { - -class DeviceEventObserver; - -class EVENTS_OZONE_EXPORT DeviceManager { - public: - virtual ~DeviceManager() {} - - // Scans the currently available devices and notifies |observer| for each - // device found. If also registering for notifications through AddObserver(), - // the scan should happen after the registration otherwise the observer may - // miss events. - virtual void ScanDevices(DeviceEventObserver* observer) = 0; - - // Registers |observer| for device event notifications. - virtual void AddObserver(DeviceEventObserver* observer) = 0; - - // Removes |observer| from the list of observers notified. - virtual void RemoveObserver(DeviceEventObserver* observer) = 0; -}; - -EVENTS_OZONE_EXPORT scoped_ptr<DeviceManager> CreateDeviceManager(); - -} // namespace ui - -#endif // UI_EVENTS_OZONE_DEVICE_DEVICE_MANAGER_H_
diff --git a/ui/events/ozone/device/device_manager_manual.cc b/ui/events/ozone/device/device_manager_manual.cc deleted file mode 100644 index c86ffcc..0000000 --- a/ui/events/ozone/device/device_manager_manual.cc +++ /dev/null
@@ -1,33 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/events/ozone/device/device_manager_manual.h" - -#include "base/files/file_enumerator.h" -#include "ui/events/ozone/device/device_event.h" -#include "ui/events/ozone/device/device_event_observer.h" - -namespace ui { - -DeviceManagerManual::DeviceManagerManual() {} - -DeviceManagerManual::~DeviceManagerManual() {} - -void DeviceManagerManual::ScanDevices(DeviceEventObserver* observer) { - base::FileEnumerator file_enum(base::FilePath("/dev/input"), - false, - base::FileEnumerator::FILES, - "event*[0-9]"); - for (base::FilePath path = file_enum.Next(); !path.empty(); - path = file_enum.Next()) { - DeviceEvent event(DeviceEvent::INPUT, DeviceEvent::ADD, path); - observer->OnDeviceEvent(event); - } -} - -void DeviceManagerManual::AddObserver(DeviceEventObserver* observer) {} - -void DeviceManagerManual::RemoveObserver(DeviceEventObserver* observer) {} - -} // namespace ui
diff --git a/ui/events/ozone/device/device_manager_manual.h b/ui/events/ozone/device/device_manager_manual.h deleted file mode 100644 index 9104774..0000000 --- a/ui/events/ozone/device/device_manager_manual.h +++ /dev/null
@@ -1,29 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_EVENTS_OZONE_DEVICE_DEVICE_MANAGER_MANUAL_H_ -#define UI_EVENTS_OZONE_DEVICE_DEVICE_MANAGER_MANUAL_H_ - -#include "base/macros.h" -#include "ui/events/ozone/device/device_manager.h" - -namespace ui { - -class DeviceManagerManual : public DeviceManager { - public: - DeviceManagerManual(); - virtual ~DeviceManagerManual(); - - private: - // DeviceManager overrides: - virtual void ScanDevices(DeviceEventObserver* observer) override; - virtual void AddObserver(DeviceEventObserver* observer) override; - virtual void RemoveObserver(DeviceEventObserver* observer) override; - - DISALLOW_COPY_AND_ASSIGN(DeviceManagerManual); -}; - -} // namespace ui - -#endif // UI_EVENTS_OZONE_DEVICE_DEVICE_MANAGER_MANUAL_H_
diff --git a/ui/events/ozone/device/udev/device_manager_udev.cc b/ui/events/ozone/device/udev/device_manager_udev.cc deleted file mode 100644 index 7f86bee..0000000 --- a/ui/events/ozone/device/udev/device_manager_udev.cc +++ /dev/null
@@ -1,186 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/events/ozone/device/udev/device_manager_udev.h" - -#include <libudev.h> - -#include "base/debug/trace_event.h" -#include "base/strings/stringprintf.h" -#include "ui/events/ozone/device/device_event.h" -#include "ui/events/ozone/device/device_event_observer.h" - -namespace ui { - -namespace { - -const char* kSubsystems[] = { - "input", - "drm", -}; - -// Severity levels from syslog.h. We can't include it directly as it -// conflicts with base/logging.h -enum { - SYS_LOG_EMERG = 0, - SYS_LOG_ALERT = 1, - SYS_LOG_CRIT = 2, - SYS_LOG_ERR = 3, - SYS_LOG_WARNING = 4, - SYS_LOG_NOTICE = 5, - SYS_LOG_INFO = 6, - SYS_LOG_DEBUG = 7, -}; - -// Log handler for messages generated from libudev. -void UdevLog(struct udev* udev, - int priority, - const char* file, - int line, - const char* fn, - const char* format, - va_list args) { - if (priority <= SYS_LOG_ERR) - LOG(ERROR) << "libudev: " << fn << ": " << base::StringPrintV(format, args); - else if (priority <= SYS_LOG_INFO) - VLOG(1) << "libudev: " << fn << ": " << base::StringPrintV(format, args); - else // SYS_LOG_DEBUG - VLOG(2) << "libudev: " << fn << ": " << base::StringPrintV(format, args); -} - -// Create libudev context. -device::ScopedUdevPtr UdevCreate() { - struct udev* udev = udev_new(); - if (udev) { - udev_set_log_fn(udev, UdevLog); - udev_set_log_priority(udev, SYS_LOG_DEBUG); - } - return device::ScopedUdevPtr(udev); -} - -// Start monitoring input device changes. -device::ScopedUdevMonitorPtr UdevCreateMonitor(struct udev* udev) { - struct udev_monitor* monitor = udev_monitor_new_from_netlink(udev, "udev"); - if (monitor) { - for (size_t i = 0; i < arraysize(kSubsystems); ++i) - udev_monitor_filter_add_match_subsystem_devtype( - monitor, kSubsystems[i], NULL); - - if (udev_monitor_enable_receiving(monitor)) - LOG(ERROR) << "Failed to start receiving events from udev"; - } else { - LOG(ERROR) << "Failed to create udev monitor"; - } - - return device::ScopedUdevMonitorPtr(monitor); -} - -} // namespace - -DeviceManagerUdev::DeviceManagerUdev() : udev_(UdevCreate()) { -} - -DeviceManagerUdev::~DeviceManagerUdev() { -} - -void DeviceManagerUdev::CreateMonitor() { - if (monitor_) - return; - monitor_ = UdevCreateMonitor(udev_.get()); - if (monitor_) { - int fd = udev_monitor_get_fd(monitor_.get()); - CHECK_GT(fd, 0); - base::MessageLoopForUI::current()->WatchFileDescriptor( - fd, true, base::MessagePumpLibevent::WATCH_READ, &controller_, this); - } -} - -void DeviceManagerUdev::ScanDevices(DeviceEventObserver* observer) { - CreateMonitor(); - - device::ScopedUdevEnumeratePtr enumerate(udev_enumerate_new(udev_.get())); - if (!enumerate) - return; - - for (size_t i = 0; i < arraysize(kSubsystems); ++i) - udev_enumerate_add_match_subsystem(enumerate.get(), kSubsystems[i]); - udev_enumerate_scan_devices(enumerate.get()); - - struct udev_list_entry* devices = - udev_enumerate_get_list_entry(enumerate.get()); - struct udev_list_entry* entry; - - udev_list_entry_foreach(entry, devices) { - device::ScopedUdevDevicePtr device(udev_device_new_from_syspath( - udev_.get(), udev_list_entry_get_name(entry))); - if (!device) - continue; - - scoped_ptr<DeviceEvent> event = ProcessMessage(device.get()); - if (event) - observer->OnDeviceEvent(*event.get()); - } -} - -void DeviceManagerUdev::AddObserver(DeviceEventObserver* observer) { - observers_.AddObserver(observer); -} - -void DeviceManagerUdev::RemoveObserver(DeviceEventObserver* observer) { - observers_.RemoveObserver(observer); -} - -void DeviceManagerUdev::OnFileCanReadWithoutBlocking(int fd) { - // The netlink socket should never become disconnected. There's no need - // to handle broken connections here. - TRACE_EVENT1("ozone", "UdevDeviceChange", "socket", fd); - - device::ScopedUdevDevicePtr device( - udev_monitor_receive_device(monitor_.get())); - if (!device) - return; - - scoped_ptr<DeviceEvent> event = ProcessMessage(device.get()); - if (event) - FOR_EACH_OBSERVER( - DeviceEventObserver, observers_, OnDeviceEvent(*event.get())); -} - -void DeviceManagerUdev::OnFileCanWriteWithoutBlocking(int fd) { - NOTREACHED(); -} - -scoped_ptr<DeviceEvent> DeviceManagerUdev::ProcessMessage(udev_device* device) { - const char* path = udev_device_get_devnode(device); - const char* action = udev_device_get_action(device); - const char* hotplug = udev_device_get_property_value(device, "HOTPLUG"); - const char* subsystem = udev_device_get_property_value(device, "SUBSYSTEM"); - - if (!path || !subsystem) - return scoped_ptr<DeviceEvent>(); - - DeviceEvent::DeviceType device_type; - if (!strcmp(subsystem, "input") && - StartsWithASCII(path, "/dev/input/event", true)) - device_type = DeviceEvent::INPUT; - else if (!strcmp(subsystem, "drm") && hotplug && !strcmp(hotplug, "1")) - device_type = DeviceEvent::DISPLAY; - else - return scoped_ptr<DeviceEvent>(); - - DeviceEvent::ActionType action_type; - if (!action || !strcmp(action, "add")) - action_type = DeviceEvent::ADD; - else if (!strcmp(action, "remove")) - action_type = DeviceEvent::REMOVE; - else if (!strcmp(action, "change")) - action_type = DeviceEvent::CHANGE; - else - return scoped_ptr<DeviceEvent>(); - - return scoped_ptr<DeviceEvent>( - new DeviceEvent(device_type, action_type, base::FilePath(path))); -} - -} // namespace ui
diff --git a/ui/events/ozone/device/udev/device_manager_udev.h b/ui/events/ozone/device/udev/device_manager_udev.h deleted file mode 100644 index 13c76b9..0000000 --- a/ui/events/ozone/device/udev/device_manager_udev.h +++ /dev/null
@@ -1,51 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_EVENTS_OZONE_DEVICE_UDEV_DEVICE_MANAGER_UDEV_H_ -#define UI_EVENTS_OZONE_DEVICE_UDEV_DEVICE_MANAGER_UDEV_H_ - -#include "base/message_loop/message_pump_libevent.h" -#include "base/observer_list.h" -#include "device/udev_linux/udev.h" -#include "ui/events/ozone/device/device_manager.h" - -namespace ui { - -class DeviceEvent; -class DeviceEventObserver; - -class DeviceManagerUdev - : public DeviceManager, base::MessagePumpLibevent::Watcher { - public: - DeviceManagerUdev(); - virtual ~DeviceManagerUdev(); - - private: - scoped_ptr<DeviceEvent> ProcessMessage(udev_device* device); - - // Creates a device-monitor to look for device add/remove/change events. - void CreateMonitor(); - - // DeviceManager overrides: - virtual void ScanDevices(DeviceEventObserver* observer) override; - virtual void AddObserver(DeviceEventObserver* observer) override; - virtual void RemoveObserver(DeviceEventObserver* observer) override; - - // base::MessagePumpLibevent::Watcher overrides: - virtual void OnFileCanReadWithoutBlocking(int fd) override; - virtual void OnFileCanWriteWithoutBlocking(int fd) override; - - device::ScopedUdevPtr udev_; - device::ScopedUdevMonitorPtr monitor_; - - base::MessagePumpLibevent::FileDescriptorWatcher controller_; - - ObserverList<DeviceEventObserver> observers_; - - DISALLOW_COPY_AND_ASSIGN(DeviceManagerUdev); -}; - -} // namespace ui - -#endif // UI_EVENTS_OZONE_DEVICE_UDEV_DEVICE_MANAGER_UDEV_H_
diff --git a/ui/events/ozone/evdev/cursor_delegate_evdev.h b/ui/events/ozone/evdev/cursor_delegate_evdev.h deleted file mode 100644 index 63947b3..0000000 --- a/ui/events/ozone/evdev/cursor_delegate_evdev.h +++ /dev/null
@@ -1,34 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_EVENTS_OZONE_EVDEV_CURSOR_DELEGATE_EVDEV_H_ -#define UI_EVENTS_OZONE_EVDEV_CURSOR_DELEGATE_EVDEV_H_ - -#include "ui/events/ozone/evdev/events_ozone_evdev_export.h" -#include "ui/gfx/geometry/point_f.h" -#include "ui/gfx/native_widget_types.h" - -namespace gfx { -class Vector2dF; -} - -namespace ui { - -class EVENTS_OZONE_EVDEV_EXPORT CursorDelegateEvdev { - public: - // Move the cursor. - virtual void MoveCursor(const gfx::Vector2dF& delta) = 0; - virtual void MoveCursorTo(gfx::AcceleratedWidget widget, - const gfx::PointF& location) = 0; - - // Location in window. - virtual gfx::PointF location() = 0; - - // Cursor visibility. - virtual bool IsCursorVisible() = 0; -}; - -} // namespace ui - -#endif // UI_EVENTS_OZONE_EVDEV_CURSOR_DELEGATE_EVDEV_H_
diff --git a/ui/events/ozone/evdev/event_converter_evdev.cc b/ui/events/ozone/evdev/event_converter_evdev.cc deleted file mode 100644 index 518c7f2..0000000 --- a/ui/events/ozone/evdev/event_converter_evdev.cc +++ /dev/null
@@ -1,45 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/events/ozone/evdev/event_converter_evdev.h" - -#include "base/files/file_path.h" -#include "base/logging.h" -#include "base/message_loop/message_loop.h" - -namespace ui { - -EventConverterEvdev::EventConverterEvdev(int fd, - const base::FilePath& path, - int id) - : fd_(fd), path_(path), id_(id) { -} - -EventConverterEvdev::~EventConverterEvdev() { - Stop(); -} - -void EventConverterEvdev::Start() { - base::MessageLoopForUI::current()->WatchFileDescriptor( - fd_, true, base::MessagePumpLibevent::WATCH_READ, &controller_, this); -} - -void EventConverterEvdev::Stop() { - controller_.StopWatchingFileDescriptor(); -} - -void EventConverterEvdev::OnFileCanWriteWithoutBlocking(int fd) { - NOTREACHED(); -} - -bool EventConverterEvdev::HasTouchscreen() const { - return false; -} - -gfx::Size EventConverterEvdev::GetTouchscreenSize() const { - NOTREACHED(); - return gfx::Size(); -} - -} // namespace ui
diff --git a/ui/events/ozone/evdev/event_converter_evdev.h b/ui/events/ozone/evdev/event_converter_evdev.h deleted file mode 100644 index fc12037..0000000 --- a/ui/events/ozone/evdev/event_converter_evdev.h +++ /dev/null
@@ -1,62 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_EVENTS_OZONE_EVDEV_EVENT_CONVERTER_EVDEV_H_ -#define UI_EVENTS_OZONE_EVDEV_EVENT_CONVERTER_EVDEV_H_ - -#include "base/callback.h" -#include "base/files/file_path.h" -#include "base/message_loop/message_loop.h" -#include "ui/events/ozone/evdev/event_dispatch_callback.h" -#include "ui/events/ozone/evdev/events_ozone_evdev_export.h" -#include "ui/gfx/geometry/size.h" - -namespace ui { - -class EVENTS_OZONE_EVDEV_EXPORT EventConverterEvdev - : public base::MessagePumpLibevent::Watcher { - public: - EventConverterEvdev(int fd, const base::FilePath& path, int id); - virtual ~EventConverterEvdev(); - - int id() const { return id_; } - - const base::FilePath& path() { return path_; } - - // Start reading events. - void Start(); - - // Stop reading events. - void Stop(); - - // Returns true of the converter is used for a touchscreen device. - virtual bool HasTouchscreen() const; - - // Returns the size of the touchscreen device if the converter is used for a - // touchscreen device. - virtual gfx::Size GetTouchscreenSize() const; - - protected: - // base::MessagePumpLibevent::Watcher: - virtual void OnFileCanWriteWithoutBlocking(int fd) override; - - // File descriptor to read. - int fd_; - - // Path to input device. - base::FilePath path_; - - // Uniquely identifies an event converter. - int id_; - - // Controller for watching the input fd. - base::MessagePumpLibevent::FileDescriptorWatcher controller_; - - private: - DISALLOW_COPY_AND_ASSIGN(EventConverterEvdev); -}; - -} // namespace ui - -#endif // UI_EVENTS_OZONE_EVDEV_EVENT_CONVERTER_EVDEV_H_
diff --git a/ui/events/ozone/evdev/event_device_info.cc b/ui/events/ozone/evdev/event_device_info.cc deleted file mode 100644 index 6d75ea9..0000000 --- a/ui/events/ozone/evdev/event_device_info.cc +++ /dev/null
@@ -1,185 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/events/ozone/evdev/event_device_info.h" - -#include <linux/input.h> - -#include "base/logging.h" -#include "base/threading/thread_restrictions.h" - -namespace ui { - -namespace { - -bool GetEventBits(int fd, unsigned int type, void* buf, unsigned int size) { - if (ioctl(fd, EVIOCGBIT(type, size), buf) < 0) { - DLOG(ERROR) << "failed EVIOCGBIT(" << type << ", " << size << ") on fd " - << fd; - return false; - } - - return true; -} - -bool GetPropBits(int fd, void* buf, unsigned int size) { - if (ioctl(fd, EVIOCGPROP(size), buf) < 0) { - DLOG(ERROR) << "failed EVIOCGPROP(" << size << ") on fd " << fd; - return false; - } - - return true; -} - -bool GetAbsInfo(int fd, int code, struct input_absinfo* absinfo) { - if (ioctl(fd, EVIOCGABS(code), absinfo)) { - DLOG(ERROR) << "failed EVIOCGABS(" << code << ") on fd " << fd; - return false; - } - return true; -} - -} // namespace - -EventDeviceInfo::EventDeviceInfo() { - memset(ev_bits_, 0, sizeof(ev_bits_)); - memset(key_bits_, 0, sizeof(key_bits_)); - memset(rel_bits_, 0, sizeof(rel_bits_)); - memset(abs_bits_, 0, sizeof(abs_bits_)); - memset(msc_bits_, 0, sizeof(msc_bits_)); - memset(sw_bits_, 0, sizeof(sw_bits_)); - memset(led_bits_, 0, sizeof(led_bits_)); - memset(prop_bits_, 0, sizeof(prop_bits_)); - memset(abs_info_, 0, sizeof(abs_info_)); -} - -EventDeviceInfo::~EventDeviceInfo() {} - -bool EventDeviceInfo::Initialize(int fd) { - if (!GetEventBits(fd, 0, ev_bits_, sizeof(ev_bits_))) - return false; - - if (!GetEventBits(fd, EV_KEY, key_bits_, sizeof(key_bits_))) - return false; - - if (!GetEventBits(fd, EV_REL, rel_bits_, sizeof(rel_bits_))) - return false; - - if (!GetEventBits(fd, EV_ABS, abs_bits_, sizeof(abs_bits_))) - return false; - - if (!GetEventBits(fd, EV_MSC, msc_bits_, sizeof(msc_bits_))) - return false; - - if (!GetEventBits(fd, EV_SW, sw_bits_, sizeof(sw_bits_))) - return false; - - if (!GetEventBits(fd, EV_LED, led_bits_, sizeof(led_bits_))) - return false; - - if (!GetPropBits(fd, prop_bits_, sizeof(prop_bits_))) - return false; - - for (unsigned int i = 0; i < ABS_CNT; ++i) - if (HasAbsEvent(i)) - if (!GetAbsInfo(fd, i, &abs_info_[i])) - return false; - - return true; -} - -bool EventDeviceInfo::HasEventType(unsigned int type) const { - if (type > EV_MAX) - return false; - return EvdevBitIsSet(ev_bits_, type); -} - -bool EventDeviceInfo::HasKeyEvent(unsigned int code) const { - if (code > KEY_MAX) - return false; - return EvdevBitIsSet(key_bits_, code); -} - -bool EventDeviceInfo::HasRelEvent(unsigned int code) const { - if (code > REL_MAX) - return false; - return EvdevBitIsSet(rel_bits_, code); -} - -bool EventDeviceInfo::HasAbsEvent(unsigned int code) const { - if (code > ABS_MAX) - return false; - return EvdevBitIsSet(abs_bits_, code); -} - -bool EventDeviceInfo::HasMscEvent(unsigned int code) const { - if (code > MSC_MAX) - return false; - return EvdevBitIsSet(msc_bits_, code); -} - -bool EventDeviceInfo::HasSwEvent(unsigned int code) const { - if (code > SW_MAX) - return false; - return EvdevBitIsSet(sw_bits_, code); -} - -bool EventDeviceInfo::HasLedEvent(unsigned int code) const { - if (code > LED_MAX) - return false; - return EvdevBitIsSet(led_bits_, code); -} - -bool EventDeviceInfo::HasProp(unsigned int code) const { - if (code > INPUT_PROP_MAX) - return false; - return EvdevBitIsSet(prop_bits_, code); -} - -int32 EventDeviceInfo::GetAbsMinimum(unsigned int code) const { - return abs_info_[code].minimum; -} - -int32 EventDeviceInfo::GetAbsMaximum(unsigned int code) const { - return abs_info_[code].maximum; -} - -bool EventDeviceInfo::HasAbsXY() const { - if (HasAbsEvent(ABS_X) && HasAbsEvent(ABS_Y)) - return true; - - if (HasAbsEvent(ABS_MT_POSITION_X) && HasAbsEvent(ABS_MT_POSITION_Y)) - return true; - - return false; -} - -bool EventDeviceInfo::HasRelXY() const { - return HasRelEvent(REL_X) && HasRelEvent(REL_Y); -} - -bool EventDeviceInfo::IsMappedToScreen() const { - // Device position is mapped directly to the screen. - if (HasProp(INPUT_PROP_DIRECT)) - return true; - - // Device position moves the cursor. - if (HasProp(INPUT_PROP_POINTER)) - return false; - - // Tablets are mapped to the screen. - if (HasKeyEvent(BTN_TOOL_PEN) || HasKeyEvent(BTN_STYLUS) || - HasKeyEvent(BTN_STYLUS2)) - return true; - - // Touchpads are not mapped to the screen. - if (HasKeyEvent(BTN_LEFT) || HasKeyEvent(BTN_MIDDLE) || - HasKeyEvent(BTN_RIGHT) || HasKeyEvent(BTN_TOOL_FINGER)) - return false; - - // Touchscreens are mapped to the screen. - return true; -} - -} // namespace ui
diff --git a/ui/events/ozone/evdev/event_device_info.h b/ui/events/ozone/evdev/event_device_info.h deleted file mode 100644 index 3217114..0000000 --- a/ui/events/ozone/evdev/event_device_info.h +++ /dev/null
@@ -1,72 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_EVENTS_OZONE_EVDEV_EVENT_DEVICE_INFO_H_ -#define UI_EVENTS_OZONE_EVDEV_EVENT_DEVICE_INFO_H_ - -#include <limits.h> -#include <linux/input.h> - -#include "base/basictypes.h" -#include "ui/events/ozone/evdev/event_device_util.h" -#include "ui/events/ozone/evdev/events_ozone_evdev_export.h" - -namespace ui { - -// Device information for Linux input devices -// -// This stores and queries information about input devices; in -// particular it knows which events the device can generate. -class EVENTS_OZONE_EVDEV_EXPORT EventDeviceInfo { - public: - EventDeviceInfo(); - ~EventDeviceInfo(); - - // Initialize device information from an open device. - bool Initialize(int fd); - - // Check events this device can generate. - bool HasEventType(unsigned int type) const; - bool HasKeyEvent(unsigned int code) const; - bool HasRelEvent(unsigned int code) const; - bool HasAbsEvent(unsigned int code) const; - bool HasMscEvent(unsigned int code) const; - bool HasSwEvent(unsigned int code) const; - bool HasLedEvent(unsigned int code) const; - - // Properties of absolute axes. - int32 GetAbsMinimum(unsigned int code) const; - int32 GetAbsMaximum(unsigned int code) const; - - // Check input device properties. - bool HasProp(unsigned int code) const; - - // Has absolute X & Y axes. - bool HasAbsXY() const; - - // Has relativeX & Y axes. - bool HasRelXY() const; - - // Determine whether absolute device X/Y coordinates are mapped onto the - // screen. This is the case for touchscreens and tablets but not touchpads. - bool IsMappedToScreen() const; - - private: - unsigned long ev_bits_[EVDEV_BITS_TO_LONGS(EV_CNT)]; - unsigned long key_bits_[EVDEV_BITS_TO_LONGS(KEY_CNT)]; - unsigned long rel_bits_[EVDEV_BITS_TO_LONGS(REL_CNT)]; - unsigned long abs_bits_[EVDEV_BITS_TO_LONGS(ABS_CNT)]; - unsigned long msc_bits_[EVDEV_BITS_TO_LONGS(MSC_CNT)]; - unsigned long sw_bits_[EVDEV_BITS_TO_LONGS(SW_CNT)]; - unsigned long led_bits_[EVDEV_BITS_TO_LONGS(LED_CNT)]; - unsigned long prop_bits_[EVDEV_BITS_TO_LONGS(INPUT_PROP_CNT)]; - - struct input_absinfo abs_info_[ABS_CNT]; - - DISALLOW_COPY_AND_ASSIGN(EventDeviceInfo); -}; - -} // namspace ui - -#endif // UI_EVENTS_OZONE_EVDEV_EVENT_DEVICE_INFO_H_
diff --git a/ui/events/ozone/evdev/event_device_util.h b/ui/events/ozone/evdev/event_device_util.h deleted file mode 100644 index 2b65b3b..0000000 --- a/ui/events/ozone/evdev/event_device_util.h +++ /dev/null
@@ -1,21 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_EVENTS_OZONE_EVDEV_EVENT_DEVICE_UTIL_H_ -#define UI_EVENTS_OZONE_EVDEV_EVENT_DEVICE_UTIL_H_ - -#include <limits.h> - -namespace ui { - -#define EVDEV_LONG_BITS (CHAR_BIT * sizeof(long)) -#define EVDEV_BITS_TO_LONGS(x) (((x) + EVDEV_LONG_BITS - 1) / EVDEV_LONG_BITS) - -static inline bool EvdevBitIsSet(const unsigned long* data, int bit) { - return data[bit / EVDEV_LONG_BITS] & (1UL << (bit % EVDEV_LONG_BITS)); -} - -} // namespace ui - -#endif // UI_EVENTS_OZONE_EVDEV_EVENT_DEVICE_UTIL_H_
diff --git a/ui/events/ozone/evdev/event_dispatch_callback.h b/ui/events/ozone/evdev/event_dispatch_callback.h deleted file mode 100644 index ae07817..0000000 --- a/ui/events/ozone/evdev/event_dispatch_callback.h +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_EVENTS_OZONE_EVDEV_EVENT_DISPATCH_CALLBACK_H_ -#define UI_EVENTS_OZONE_EVDEV_EVENT_DISPATCH_CALLBACK_H_ - -#include "base/callback.h" - -namespace ui { - -class Event; - -typedef base::Callback<void(scoped_ptr<Event>)> EventDispatchCallback; - -} // namspace ui - -#endif // UI_EVENTS_OZONE_EVDEV_EVENT_DISPATCH_CALLBACK_H_
diff --git a/ui/events/ozone/evdev/event_factory_evdev.cc b/ui/events/ozone/evdev/event_factory_evdev.cc deleted file mode 100644 index 170d3a6..0000000 --- a/ui/events/ozone/evdev/event_factory_evdev.cc +++ /dev/null
@@ -1,311 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/events/ozone/evdev/event_factory_evdev.h" - -#include <fcntl.h> -#include <linux/input.h> - -#include "base/debug/trace_event.h" -#include "base/stl_util.h" -#include "base/task_runner.h" -#include "base/thread_task_runner_handle.h" -#include "base/threading/worker_pool.h" -#include "ui/events/device_data_manager.h" -#include "ui/events/ozone/device/device_event.h" -#include "ui/events/ozone/device/device_manager.h" -#include "ui/events/ozone/evdev/cursor_delegate_evdev.h" -#include "ui/events/ozone/evdev/event_device_info.h" -#include "ui/events/ozone/evdev/key_event_converter_evdev.h" -#include "ui/events/ozone/evdev/touch_event_converter_evdev.h" - -#if defined(USE_EVDEV_GESTURES) -#include "ui/events/ozone/evdev/libgestures_glue/event_reader_libevdev_cros.h" -#include "ui/events/ozone/evdev/libgestures_glue/gesture_interpreter_libevdev_cros.h" -#include "ui/events/ozone/evdev/libgestures_glue/gesture_property_provider.h" -#endif - -#ifndef EVIOCSCLOCKID -#define EVIOCSCLOCKID _IOW('E', 0xa0, int) -#endif - -namespace ui { - -namespace { - -typedef base::Callback<void(scoped_ptr<EventConverterEvdev>)> - OpenInputDeviceReplyCallback; - -struct OpenInputDeviceParams { - // Unique identifier for the new device. - int id; - - // Device path to open. - base::FilePath path; - - // Callback for dispatching events. Call on UI thread only. - EventDispatchCallback dispatch_callback; - - // State shared between devices. Must not be dereferenced on worker thread. - EventModifiersEvdev* modifiers; - KeyboardEvdev* keyboard; - CursorDelegateEvdev* cursor; -#if defined(USE_EVDEV_GESTURES) - GesturePropertyProvider* gesture_property_provider; -#endif -}; - -#if defined(USE_EVDEV_GESTURES) -bool UseGesturesLibraryForDevice(const EventDeviceInfo& devinfo) { - if (devinfo.HasAbsXY() && !devinfo.IsMappedToScreen()) - return true; // touchpad - - if (devinfo.HasRelXY()) - return true; // mouse - - return false; -} -#endif - -scoped_ptr<EventConverterEvdev> CreateConverter( - const OpenInputDeviceParams& params, - int fd, - const EventDeviceInfo& devinfo) { -#if defined(USE_EVDEV_GESTURES) - // Touchpad or mouse: use gestures library. - // EventReaderLibevdevCros -> GestureInterpreterLibevdevCros -> DispatchEvent - if (UseGesturesLibraryForDevice(devinfo)) { - scoped_ptr<GestureInterpreterLibevdevCros> gesture_interp = make_scoped_ptr( - new GestureInterpreterLibevdevCros(params.id, - params.modifiers, - params.cursor, - params.keyboard, - params.gesture_property_provider, - params.dispatch_callback)); - return make_scoped_ptr(new EventReaderLibevdevCros( - fd, params.path, params.id, gesture_interp.Pass())); - } -#endif - - // Touchscreen: use TouchEventConverterEvdev. - scoped_ptr<EventConverterEvdev> converter; - if (devinfo.HasAbsXY()) - return make_scoped_ptr<EventConverterEvdev>(new TouchEventConverterEvdev( - fd, params.path, params.id, devinfo, params.dispatch_callback)); - - // Everything else: use KeyEventConverterEvdev. - return make_scoped_ptr<EventConverterEvdev>( - new KeyEventConverterEvdev(fd, params.path, params.id, params.keyboard)); -} - -// Open an input device. Opening may put the calling thread to sleep, and -// therefore should be run on a thread where latency is not critical. We -// run it on a thread from the worker pool. -// -// This takes a TaskRunner and runs the reply on that thread, so that we -// can hop threads if necessary (back to the UI thread). -void OpenInputDevice(scoped_ptr<OpenInputDeviceParams> params, - scoped_refptr<base::TaskRunner> reply_runner, - const OpenInputDeviceReplyCallback& reply_callback) { - const base::FilePath& path = params->path; - - TRACE_EVENT1("ozone", "OpenInputDevice", "path", path.value()); - - int fd = open(path.value().c_str(), O_RDONLY | O_NONBLOCK); - if (fd < 0) { - PLOG(ERROR) << "Cannot open '" << path.value(); - return; - } - - // Use monotonic timestamps for events. The touch code in particular - // expects event timestamps to correlate to the monotonic clock - // (base::TimeTicks). - unsigned int clk = CLOCK_MONOTONIC; - if (ioctl(fd, EVIOCSCLOCKID, &clk)) - PLOG(ERROR) << "failed to set CLOCK_MONOTONIC"; - - EventDeviceInfo devinfo; - if (!devinfo.Initialize(fd)) { - LOG(ERROR) << "failed to get device information for " << path.value(); - close(fd); - return; - } - - scoped_ptr<EventConverterEvdev> converter = - CreateConverter(*params, fd, devinfo); - - // Reply with the constructed converter. - reply_runner->PostTask(FROM_HERE, - base::Bind(reply_callback, base::Passed(&converter))); -} - -// Close an input device. Closing may put the calling thread to sleep, and -// therefore should be run on a thread where latency is not critical. We -// run it on the FILE thread. -void CloseInputDevice(const base::FilePath& path, - scoped_ptr<EventConverterEvdev> converter) { - TRACE_EVENT1("ozone", "CloseInputDevice", "path", path.value()); - converter.reset(); -} - -} // namespace - -EventFactoryEvdev::EventFactoryEvdev(CursorDelegateEvdev* cursor, - DeviceManager* device_manager) - : last_device_id_(0), - device_manager_(device_manager), - dispatch_callback_( - base::Bind(&EventFactoryEvdev::PostUiEvent, base::Unretained(this))), - keyboard_(&modifiers_, dispatch_callback_), - cursor_(cursor), -#if defined(USE_EVDEV_GESTURES) - gesture_property_provider_(new GesturePropertyProvider), -#endif - weak_ptr_factory_(this) { - DCHECK(device_manager_); -} - -EventFactoryEvdev::~EventFactoryEvdev() { STLDeleteValues(&converters_); } - -void EventFactoryEvdev::PostUiEvent(scoped_ptr<Event> event) { - base::ThreadTaskRunnerHandle::Get()->PostTask( - FROM_HERE, - base::Bind(&EventFactoryEvdev::DispatchUiEventTask, - weak_ptr_factory_.GetWeakPtr(), - base::Passed(&event))); -} - -void EventFactoryEvdev::DispatchUiEventTask(scoped_ptr<Event> event) { - DispatchEvent(event.get()); -} - -void EventFactoryEvdev::AttachInputDevice( - scoped_ptr<EventConverterEvdev> converter) { - const base::FilePath& path = converter->path(); - - TRACE_EVENT1("ozone", "AttachInputDevice", "path", path.value()); - DCHECK(ui_task_runner_->RunsTasksOnCurrentThread()); - - // If we have an existing device, detach it. We don't want two - // devices with the same name open at the same time. - if (converters_[path]) - DetachInputDevice(path); - - // Add initialized device to map. - converters_[path] = converter.release(); - converters_[path]->Start(); - - NotifyHotplugEventObserver(*converters_[path]); -} - -void EventFactoryEvdev::OnDeviceEvent(const DeviceEvent& event) { - if (event.device_type() != DeviceEvent::INPUT) - return; - - switch (event.action_type()) { - case DeviceEvent::ADD: - case DeviceEvent::CHANGE: { - TRACE_EVENT1("ozone", "OnDeviceAdded", "path", event.path().value()); - - scoped_ptr<OpenInputDeviceParams> params(new OpenInputDeviceParams); - params->id = NextDeviceId(); - params->path = event.path(); - params->dispatch_callback = dispatch_callback_; - params->modifiers = &modifiers_; - params->keyboard = &keyboard_; - params->cursor = cursor_; -#if defined(USE_EVDEV_GESTURES) - params->gesture_property_provider = gesture_property_provider_.get(); -#endif - - OpenInputDeviceReplyCallback reply_callback = - base::Bind(&EventFactoryEvdev::AttachInputDevice, - weak_ptr_factory_.GetWeakPtr()); - - // Dispatch task to open from the worker pool, since open may block. - base::WorkerPool::PostTask(FROM_HERE, - base::Bind(&OpenInputDevice, - base::Passed(¶ms), - ui_task_runner_, - reply_callback), - true /* task_is_slow */); - } - break; - case DeviceEvent::REMOVE: { - TRACE_EVENT1("ozone", "OnDeviceRemoved", "path", event.path().value()); - DetachInputDevice(event.path()); - } - break; - } -} - -void EventFactoryEvdev::OnDispatcherListChanged() { - if (!ui_task_runner_.get()) { - ui_task_runner_ = base::ThreadTaskRunnerHandle::Get(); - // Scan & monitor devices. - device_manager_->AddObserver(this); - device_manager_->ScanDevices(this); - } -} - -void EventFactoryEvdev::DetachInputDevice(const base::FilePath& path) { - TRACE_EVENT1("ozone", "DetachInputDevice", "path", path.value()); - DCHECK(ui_task_runner_->RunsTasksOnCurrentThread()); - - // Remove device from map. - scoped_ptr<EventConverterEvdev> converter(converters_[path]); - converters_.erase(path); - - if (converter) { - // Cancel libevent notifications from this converter. This part must be - // on UI since the polling happens on UI. - converter->Stop(); - - NotifyHotplugEventObserver(*converter); - - // Dispatch task to close from the worker pool, since close may block. - base::WorkerPool::PostTask( - FROM_HERE, - base::Bind(&CloseInputDevice, path, base::Passed(&converter)), - true); - } -} - -void EventFactoryEvdev::WarpCursorTo(gfx::AcceleratedWidget widget, - const gfx::PointF& location) { - if (cursor_) { - cursor_->MoveCursorTo(widget, location); - PostUiEvent(make_scoped_ptr(new MouseEvent(ET_MOUSE_MOVED, - cursor_->location(), - cursor_->location(), - modifiers_.GetModifierFlags(), - /* changed_button_flags */ 0))); - } -} - -void EventFactoryEvdev::NotifyHotplugEventObserver( - const EventConverterEvdev& converter) { - // For now the only information propagated is related to touchscreens. Ignore - // events for everything but touchscreens. - if (!converter.HasTouchscreen()) - return; - - DeviceHotplugEventObserver* observer = DeviceDataManager::GetInstance(); - std::vector<TouchscreenDevice> touchscreens; - for (auto it = converters_.begin(); it != converters_.end(); ++it) { - if (it->second->HasTouchscreen()) { - touchscreens.push_back(TouchscreenDevice(it->second->id(), - it->second->GetTouchscreenSize(), - false /* is_internal */)); - } - } - - observer->OnTouchscreenDevicesUpdated(touchscreens); -} - -int EventFactoryEvdev::NextDeviceId() { - return ++last_device_id_; -} - -} // namespace ui
diff --git a/ui/events/ozone/evdev/event_factory_evdev.h b/ui/events/ozone/evdev/event_factory_evdev.h deleted file mode 100644 index 74585fc..0000000 --- a/ui/events/ozone/evdev/event_factory_evdev.h +++ /dev/null
@@ -1,107 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_EVENTS_OZONE_EVDEV_EVENT_FACTORY_EVDEV_H_ -#define UI_EVENTS_OZONE_EVDEV_EVENT_FACTORY_EVDEV_H_ - -#include "base/callback.h" -#include "base/compiler_specific.h" -#include "base/files/file_path.h" -#include "base/memory/ref_counted.h" -#include "base/task_runner.h" -#include "ui/events/ozone/device/device_event_observer.h" -#include "ui/events/ozone/evdev/event_converter_evdev.h" -#include "ui/events/ozone/evdev/event_modifiers_evdev.h" -#include "ui/events/ozone/evdev/events_ozone_evdev_export.h" -#include "ui/events/ozone/evdev/keyboard_evdev.h" -#include "ui/events/platform/platform_event_source.h" -#include "ui/gfx/native_widget_types.h" - -namespace gfx { -class PointF; -} // namespace gfx - -namespace ui { - -class CursorDelegateEvdev; -class DeviceManager; - -#if defined(USE_EVDEV_GESTURES) -class GesturePropertyProvider; -#endif - -// Ozone events implementation for the Linux input subsystem ("evdev"). -class EVENTS_OZONE_EVDEV_EXPORT EventFactoryEvdev : public DeviceEventObserver, - public PlatformEventSource { - public: - EventFactoryEvdev(CursorDelegateEvdev* cursor, - DeviceManager* device_manager); - virtual ~EventFactoryEvdev(); - - void WarpCursorTo(gfx::AcceleratedWidget widget, - const gfx::PointF& location); - - private: - // Post a task to dispatch an event. - void PostUiEvent(scoped_ptr<Event> event); - - // Dispatch event via PlatformEventSource. - void DispatchUiEventTask(scoped_ptr<Event> event); - - // Open device at path & starting processing events (on UI thread). - void AttachInputDevice(scoped_ptr<EventConverterEvdev> converter); - - // Close device at path (on UI thread). - void DetachInputDevice(const base::FilePath& file_path); - - void NotifyHotplugEventObserver(const EventConverterEvdev& converter); - - int NextDeviceId(); - - // DeviceEventObserver overrides: - // - // Callback for device add (on UI thread). - virtual void OnDeviceEvent(const DeviceEvent& event) override; - - // PlatformEventSource: - virtual void OnDispatcherListChanged() override; - - // Owned per-device event converters (by path). - std::map<base::FilePath, EventConverterEvdev*> converters_; - - // Used to uniquely identify input devices. - int last_device_id_; - - // Interface for scanning & monitoring input devices. - DeviceManager* device_manager_; // Not owned. - - // Task runner for event dispatch. - scoped_refptr<base::TaskRunner> ui_task_runner_; - - // Dispatch callback for events. - EventDispatchCallback dispatch_callback_; - - // Modifier key state (shift, ctrl, etc). - EventModifiersEvdev modifiers_; - - // Keyboard state. - KeyboardEvdev keyboard_; - - // Cursor movement. - CursorDelegateEvdev* cursor_; - -#if defined(USE_EVDEV_GESTURES) - // Gesture library property provider (used by touchpads/mice). - scoped_ptr<GesturePropertyProvider> gesture_property_provider_; -#endif - - // Support weak pointers for attach & detach callbacks. - base::WeakPtrFactory<EventFactoryEvdev> weak_ptr_factory_; - - DISALLOW_COPY_AND_ASSIGN(EventFactoryEvdev); -}; - -} // namespace ui - -#endif // UI_EVENTS_OZONE_EVDEV_EVENT_FACTORY_EVDEV_H_
diff --git a/ui/events/ozone/evdev/event_modifiers_evdev.cc b/ui/events/ozone/evdev/event_modifiers_evdev.cc deleted file mode 100644 index cee7c1c..0000000 --- a/ui/events/ozone/evdev/event_modifiers_evdev.cc +++ /dev/null
@@ -1,79 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/events/ozone/evdev/event_modifiers_evdev.h" - -#include <linux/input.h> - -#include "ui/events/event.h" - -namespace ui { - -namespace { - -static const int kEventFlagFromModifiers[] = { - EF_NONE, // EVDEV_MODIFIER_NONE, - EF_CAPS_LOCK_DOWN, // EVDEV_MODIFIER_CAPS_LOCK - EF_SHIFT_DOWN, // EVDEV_MODIFIER_SHIFT - EF_CONTROL_DOWN, // EVDEV_MODIFIER_CONTROL - EF_ALT_DOWN, // EVDEV_MODIFIER_ALT - EF_LEFT_MOUSE_BUTTON, // EVDEV_MODIFIER_LEFT_MOUSE_BUTTON - EF_MIDDLE_MOUSE_BUTTON, // EVDEV_MODIFIER_MIDDLE_MOUSE_BUTTON - EF_RIGHT_MOUSE_BUTTON, // EVDEV_MODIFIER_RIGHT_MOUSE_BUTTON - EF_COMMAND_DOWN, // EVDEV_MODIFIER_COMMAND - EF_ALTGR_DOWN, // EVDEV_MODIFIER_ALTGR -}; - -} // namespace - -EventModifiersEvdev::EventModifiersEvdev() - : modifier_flags_locked_(0), modifier_flags_(0) { - memset(modifiers_down_, 0, sizeof(modifiers_down_)); -} -EventModifiersEvdev::~EventModifiersEvdev() {} - -void EventModifiersEvdev::UpdateModifier(unsigned int modifier, bool down) { - DCHECK_LT(modifier, EVDEV_NUM_MODIFIERS); - - if (down) { - modifiers_down_[modifier]++; - } else { - // Ignore spurious modifier "up" events. This might happen if the - // button is down during startup. - if (modifiers_down_[modifier]) - modifiers_down_[modifier]--; - } - - UpdateFlags(modifier); -} - -void EventModifiersEvdev::UpdateModifierLock(unsigned int modifier, bool down) { - DCHECK_LT(modifier, EVDEV_NUM_MODIFIERS); - - if (down) - modifier_flags_locked_ ^= kEventFlagFromModifiers[modifier]; - - // TODO(spang): Synchronize with the CapsLock LED. - - UpdateFlags(modifier); -} - -void EventModifiersEvdev::UpdateFlags(unsigned int modifier) { - int mask = kEventFlagFromModifiers[modifier]; - bool down = modifiers_down_[modifier]; - bool locked = (modifier_flags_locked_ & mask); - if (down != locked) - modifier_flags_ |= mask; - else - modifier_flags_ &= ~mask; -} - -int EventModifiersEvdev::GetModifierFlags() { return modifier_flags_; } - -// static -int EventModifiersEvdev::GetEventFlagFromModifier(unsigned int modifier) { - return kEventFlagFromModifiers[modifier]; -} - -} // namespace ui
diff --git a/ui/events/ozone/evdev/event_modifiers_evdev.h b/ui/events/ozone/evdev/event_modifiers_evdev.h deleted file mode 100644 index d10bb8c..0000000 --- a/ui/events/ozone/evdev/event_modifiers_evdev.h +++ /dev/null
@@ -1,77 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_EVENTS_OZONE_EVDEV_EVENT_MODIFIERS_EVDEV_H_ -#define UI_EVENTS_OZONE_EVDEV_EVENT_MODIFIERS_EVDEV_H_ - -#include "base/basictypes.h" -#include "ui/events/ozone/evdev/events_ozone_evdev_export.h" - -namespace ui { - -enum { - EVDEV_MODIFIER_NONE, - EVDEV_MODIFIER_CAPS_LOCK, - EVDEV_MODIFIER_SHIFT, - EVDEV_MODIFIER_CONTROL, - EVDEV_MODIFIER_ALT, - EVDEV_MODIFIER_LEFT_MOUSE_BUTTON, - EVDEV_MODIFIER_MIDDLE_MOUSE_BUTTON, - EVDEV_MODIFIER_RIGHT_MOUSE_BUTTON, - EVDEV_MODIFIER_COMMAND, - EVDEV_MODIFIER_ALTGR, - EVDEV_NUM_MODIFIERS -}; - -// Modifier key state for Evdev. -// -// Chrome relies on the underlying OS to interpret modifier keys such as Shift, -// Ctrl, and Alt. The Linux input subsystem does not assign any special meaning -// to these keys, so this work must happen at a higher layer (normally X11 or -// the console driver). When using evdev directly, we must do it ourselves. -// -// The modifier state is shared between all input devices connected to the -// system. This is to support actions such as Shift-Clicking that use multiple -// devices. -// -// Normally a modifier is set if any of the keys or buttons assigned to it are -// currently pressed. However some keys toggle a persistent "lock" for the -// modifier instead, such as CapsLock. If a modifier is "locked" then its state -// is inverted until it is unlocked. -class EVENTS_OZONE_EVDEV_EXPORT EventModifiersEvdev { - public: - EventModifiersEvdev(); - ~EventModifiersEvdev(); - - // Record key press or release for regular modifier key (shift, alt, etc). - void UpdateModifier(unsigned int modifier, bool down); - - // Record key press or release for locking modifier key (caps lock). - void UpdateModifierLock(unsigned int modifier, bool down); - - // Return current flags to use for incoming events. - int GetModifierFlags(); - - // Return the mask for the specified modifier. - static int GetEventFlagFromModifier(unsigned int modifier); - - private: - // Count of keys pressed for each modifier. - int modifiers_down_[EVDEV_NUM_MODIFIERS]; - - // Mask of modifier flags currently "locked". - int modifier_flags_locked_; - - // Mask of modifier flags currently active (nonzero keys pressed xor locked). - int modifier_flags_; - - // Update modifier_flags_ from modifiers_down_ and modifier_flags_locked_. - void UpdateFlags(unsigned int modifier); - - DISALLOW_COPY_AND_ASSIGN(EventModifiersEvdev); -}; - -} // namspace ui - -#endif // UI_EVENTS_OZONE_EVDEV_EVENT_MODIFIERS_EVDEV_H_
diff --git a/ui/events/ozone/evdev/events_ozone_evdev_export.h b/ui/events/ozone/evdev/events_ozone_evdev_export.h deleted file mode 100644 index 4a4cbac..0000000 --- a/ui/events/ozone/evdev/events_ozone_evdev_export.h +++ /dev/null
@@ -1,29 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_EVENTS_OZONE_EVDEV_EVENTS_OZONE_EVDEV_EXPORT_H_ -#define UI_EVENTS_OZONE_EVDEV_EVENTS_OZONE_EVDEV_EXPORT_H_ - -#if defined(COMPONENT_BUILD) -#if defined(WIN32) - -#if defined(EVENTS_OZONE_EVDEV_IMPLEMENTATION) -#define EVENTS_OZONE_EVDEV_EXPORT __declspec(dllexport) -#else -#define EVENTS_OZONE_EVDEV_EXPORT __declspec(dllimport) -#endif // defined(EVENTS_OZONE_EVDEV_IMPLEMENTATION) - -#else // defined(WIN32) -#if defined(EVENTS_OZONE_EVDEV_IMPLEMENTATION) -#define EVENTS_OZONE_EVDEV_EXPORT __attribute__((visibility("default"))) -#else -#define EVENTS_OZONE_EVDEV_EXPORT -#endif -#endif - -#else // defined(COMPONENT_BUILD) -#define EVENTS_OZONE_EVDEV_EXPORT -#endif - -#endif // UI_EVENTS_OZONE_EVDEV_EVENTS_OZONE_EVDEV_EXPORT_H_
diff --git a/ui/events/ozone/evdev/key_event_converter_evdev.cc b/ui/events/ozone/evdev/key_event_converter_evdev.cc deleted file mode 100644 index 1f07eb2..0000000 --- a/ui/events/ozone/evdev/key_event_converter_evdev.cc +++ /dev/null
@@ -1,62 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/events/ozone/evdev/key_event_converter_evdev.h" - -#include <errno.h> -#include <linux/input.h> - -#include "base/message_loop/message_loop.h" -#include "ui/events/event.h" -#include "ui/events/keycodes/dom4/keycode_converter.h" -#include "ui/events/keycodes/keyboard_codes.h" -#include "ui/events/ozone/evdev/event_modifiers_evdev.h" - -namespace ui { - -namespace { - -} // namespace - -KeyEventConverterEvdev::KeyEventConverterEvdev(int fd, - base::FilePath path, - int id, - KeyboardEvdev* keyboard) - : EventConverterEvdev(fd, path, id), keyboard_(keyboard) { -} - -KeyEventConverterEvdev::~KeyEventConverterEvdev() { - Stop(); - close(fd_); -} - -void KeyEventConverterEvdev::OnFileCanReadWithoutBlocking(int fd) { - input_event inputs[4]; - ssize_t read_size = read(fd, inputs, sizeof(inputs)); - if (read_size < 0) { - if (errno == EINTR || errno == EAGAIN) - return; - if (errno != ENODEV) - PLOG(ERROR) << "error reading device " << path_.value(); - Stop(); - return; - } - - DCHECK_EQ(read_size % sizeof(*inputs), 0u); - ProcessEvents(inputs, read_size / sizeof(*inputs)); -} - -void KeyEventConverterEvdev::ProcessEvents(const input_event* inputs, - int count) { - for (int i = 0; i < count; ++i) { - const input_event& input = inputs[i]; - if (input.type == EV_KEY) { - keyboard_->OnKeyChange(input.code, input.value != 0); - } else if (input.type == EV_SYN) { - // TODO(sadrul): Handle this case appropriately. - } - } -} - -} // namespace ui
diff --git a/ui/events/ozone/evdev/key_event_converter_evdev.h b/ui/events/ozone/evdev/key_event_converter_evdev.h deleted file mode 100644 index f1044fa..0000000 --- a/ui/events/ozone/evdev/key_event_converter_evdev.h +++ /dev/null
@@ -1,47 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_EVENTS_OZONE_EVDEV_KEY_EVENT_CONVERTER_EVDEV_H_ -#define UI_EVENTS_OZONE_EVDEV_KEY_EVENT_CONVERTER_EVDEV_H_ - -#include "base/files/file_path.h" -#include "base/message_loop/message_pump_libevent.h" -#include "ui/events/event.h" -#include "ui/events/ozone/evdev/event_converter_evdev.h" -#include "ui/events/ozone/evdev/event_modifiers_evdev.h" -#include "ui/events/ozone/evdev/events_ozone_evdev_export.h" -#include "ui/events/ozone/evdev/keyboard_evdev.h" - -struct input_event; - -namespace ui { - -class EVENTS_OZONE_EVDEV_EXPORT KeyEventConverterEvdev - : public EventConverterEvdev { - public: - KeyEventConverterEvdev(int fd, - base::FilePath path, - int id, - KeyboardEvdev* keyboard); - virtual ~KeyEventConverterEvdev(); - - // EventConverterEvdev: - virtual void OnFileCanReadWithoutBlocking(int fd) override; - - void ProcessEvents(const struct input_event* inputs, int count); - - private: - // Controller for watching the input fd. - base::MessagePumpLibevent::FileDescriptorWatcher controller_; - - // Shared keyboard state. - KeyboardEvdev* keyboard_; - - DISALLOW_COPY_AND_ASSIGN(KeyEventConverterEvdev); -}; - -} // namspace ui - -#endif // UI_EVENTS_OZONE_EVDEV_KEY_EVENT_CONVERTER_EVDEV_H_ -
diff --git a/ui/events/ozone/evdev/key_event_converter_evdev_unittest.cc b/ui/events/ozone/evdev/key_event_converter_evdev_unittest.cc deleted file mode 100644 index f78925c..0000000 --- a/ui/events/ozone/evdev/key_event_converter_evdev_unittest.cc +++ /dev/null
@@ -1,356 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <linux/input.h> - -#include "base/bind.h" -#include "base/memory/scoped_ptr.h" -#include "base/memory/scoped_vector.h" -#include "base/message_loop/message_loop.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/events/event.h" -#include "ui/events/keycodes/keyboard_codes.h" -#include "ui/events/ozone/evdev/key_event_converter_evdev.h" -#include "ui/events/ozone/evdev/keyboard_evdev.h" - -namespace ui { - -const char kTestDevicePath[] = "/dev/input/test-device"; - -class MockKeyEventConverterEvdev : public KeyEventConverterEvdev { - public: - MockKeyEventConverterEvdev(int fd, KeyboardEvdev* keyboard) - : KeyEventConverterEvdev(fd, - base::FilePath(kTestDevicePath), - 1, - keyboard) { - Start(); - } - virtual ~MockKeyEventConverterEvdev() {}; - - private: - DISALLOW_COPY_AND_ASSIGN(MockKeyEventConverterEvdev); -}; - -} // namespace ui - -// Test fixture. -class KeyEventConverterEvdevTest : public testing::Test { - public: - KeyEventConverterEvdevTest() {} - - // Overridden from testing::Test: - virtual void SetUp() override { - - // Set up pipe to satisfy message pump (unused). - int evdev_io[2]; - if (pipe(evdev_io)) - PLOG(FATAL) << "failed pipe"; - events_in_ = evdev_io[0]; - events_out_ = evdev_io[1]; - - modifiers_.reset(new ui::EventModifiersEvdev()); - keyboard_.reset(new ui::KeyboardEvdev( - modifiers_.get(), - base::Bind(&KeyEventConverterEvdevTest::DispatchEventForTest, - base::Unretained(this)))); - device_.reset( - new ui::MockKeyEventConverterEvdev(events_in_, keyboard_.get())); - } - virtual void TearDown() override { - device_.reset(); - keyboard_.reset(); - modifiers_.reset(); - close(events_in_); - close(events_out_); - } - - ui::MockKeyEventConverterEvdev* device() { return device_.get(); } - ui::EventModifiersEvdev* modifiers() { return modifiers_.get(); } - - unsigned size() { return dispatched_events_.size(); } - ui::KeyEvent* dispatched_event(unsigned index) { - DCHECK_GT(dispatched_events_.size(), index); - ui::Event* ev = dispatched_events_[index]; - DCHECK(ev->IsKeyEvent()); - return static_cast<ui::KeyEvent*>(ev); - } - - private: - void DispatchEventForTest(scoped_ptr<ui::Event> event) { - dispatched_events_.push_back(event.release()); - } - - base::MessageLoopForUI ui_loop_; - - scoped_ptr<ui::EventModifiersEvdev> modifiers_; - scoped_ptr<ui::KeyboardEvdev> keyboard_; - scoped_ptr<ui::MockKeyEventConverterEvdev> device_; - - ScopedVector<ui::Event> dispatched_events_; - - int events_out_; - int events_in_; - - DISALLOW_COPY_AND_ASSIGN(KeyEventConverterEvdevTest); -}; - -TEST_F(KeyEventConverterEvdevTest, KeyPress) { - ui::MockKeyEventConverterEvdev* dev = device(); - - struct input_event mock_kernel_queue[] = { - {{0, 0}, EV_MSC, MSC_SCAN, 0x7002a}, - {{0, 0}, EV_KEY, KEY_BACKSPACE, 1}, - {{0, 0}, EV_SYN, SYN_REPORT, 0}, - - {{0, 0}, EV_MSC, MSC_SCAN, 0x7002a}, - {{0, 0}, EV_KEY, KEY_BACKSPACE, 0}, - {{0, 0}, EV_SYN, SYN_REPORT, 0}, - }; - - dev->ProcessEvents(mock_kernel_queue, arraysize(mock_kernel_queue)); - EXPECT_EQ(2u, size()); - - ui::KeyEvent* event; - - event = dispatched_event(0); - EXPECT_EQ(ui::ET_KEY_PRESSED, event->type()); - EXPECT_EQ(ui::VKEY_BACK, event->key_code()); - EXPECT_EQ(0, event->flags()); - - event = dispatched_event(1); - EXPECT_EQ(ui::ET_KEY_RELEASED, event->type()); - EXPECT_EQ(ui::VKEY_BACK, event->key_code()); - EXPECT_EQ(0, event->flags()); -} - -TEST_F(KeyEventConverterEvdevTest, KeyRepeat) { - ui::MockKeyEventConverterEvdev* dev = device(); - - struct input_event mock_kernel_queue[] = { - {{0, 0}, EV_MSC, MSC_SCAN, 0x7002a}, - {{0, 0}, EV_KEY, KEY_BACKSPACE, 1}, - {{0, 0}, EV_SYN, SYN_REPORT, 0}, - - {{0, 0}, EV_MSC, MSC_SCAN, 0x7002a}, - {{0, 0}, EV_KEY, KEY_BACKSPACE, 2}, - {{0, 0}, EV_SYN, SYN_REPORT, 0}, - - {{0, 0}, EV_MSC, MSC_SCAN, 0x7002a}, - {{0, 0}, EV_KEY, KEY_BACKSPACE, 2}, - {{0, 0}, EV_SYN, SYN_REPORT, 0}, - - {{0, 0}, EV_MSC, MSC_SCAN, 0x7002a}, - {{0, 0}, EV_KEY, KEY_BACKSPACE, 0}, - {{0, 0}, EV_SYN, SYN_REPORT, 0}, - }; - - dev->ProcessEvents(mock_kernel_queue, arraysize(mock_kernel_queue)); - EXPECT_EQ(4u, size()); - - ui::KeyEvent* event; - - event = dispatched_event(0); - EXPECT_EQ(ui::ET_KEY_PRESSED, event->type()); - EXPECT_EQ(ui::VKEY_BACK, event->key_code()); - EXPECT_EQ(0, event->flags()); - - event = dispatched_event(1); - EXPECT_EQ(ui::ET_KEY_PRESSED, event->type()); - EXPECT_EQ(ui::VKEY_BACK, event->key_code()); - EXPECT_EQ(0, event->flags()); - - event = dispatched_event(2); - EXPECT_EQ(ui::ET_KEY_PRESSED, event->type()); - EXPECT_EQ(ui::VKEY_BACK, event->key_code()); - EXPECT_EQ(0, event->flags()); - - event = dispatched_event(3); - EXPECT_EQ(ui::ET_KEY_RELEASED, event->type()); - EXPECT_EQ(ui::VKEY_BACK, event->key_code()); - EXPECT_EQ(0, event->flags()); -} - -TEST_F(KeyEventConverterEvdevTest, NoEvents) { - ui::MockKeyEventConverterEvdev* dev = device(); - dev->ProcessEvents(NULL, 0); - EXPECT_EQ(0u, size()); -} - -TEST_F(KeyEventConverterEvdevTest, KeyWithModifier) { - ui::MockKeyEventConverterEvdev* dev = device(); - - struct input_event mock_kernel_queue[] = { - {{0, 0}, EV_MSC, MSC_SCAN, 0x700e1}, - {{0, 0}, EV_KEY, KEY_LEFTSHIFT, 1}, - {{0, 0}, EV_SYN, SYN_REPORT, 0}, - - {{0, 0}, EV_MSC, MSC_SCAN, 0x70004}, - {{0, 0}, EV_KEY, KEY_A, 1}, - {{0, 0}, EV_SYN, SYN_REPORT, 0}, - - {{0, 0}, EV_MSC, MSC_SCAN, 0x70004}, - {{0, 0}, EV_KEY, KEY_A, 0}, - {{0, 0}, EV_SYN, SYN_REPORT, 0}, - - {{0, 0}, EV_MSC, MSC_SCAN, 0x700e1}, - {{0, 0}, EV_KEY, KEY_LEFTSHIFT, 0}, - {{0, 0}, EV_SYN, SYN_REPORT, 0}, - }; - - dev->ProcessEvents(mock_kernel_queue, arraysize(mock_kernel_queue)); - EXPECT_EQ(4u, size()); - - ui::KeyEvent* event; - - event = dispatched_event(0); - EXPECT_EQ(ui::ET_KEY_PRESSED, event->type()); - EXPECT_EQ(ui::VKEY_SHIFT, event->key_code()); - EXPECT_EQ(ui::EF_SHIFT_DOWN, event->flags()); - - event = dispatched_event(1); - EXPECT_EQ(ui::ET_KEY_PRESSED, event->type()); - EXPECT_EQ(ui::VKEY_A, event->key_code()); - EXPECT_EQ(ui::EF_SHIFT_DOWN, event->flags()); - - event = dispatched_event(2); - EXPECT_EQ(ui::ET_KEY_RELEASED, event->type()); - EXPECT_EQ(ui::VKEY_A, event->key_code()); - EXPECT_EQ(ui::EF_SHIFT_DOWN, event->flags()); - - event = dispatched_event(3); - EXPECT_EQ(ui::ET_KEY_RELEASED, event->type()); - EXPECT_EQ(ui::VKEY_SHIFT, event->key_code()); - EXPECT_EQ(0, event->flags()); -} - -TEST_F(KeyEventConverterEvdevTest, KeyWithDuplicateModifier) { - ui::MockKeyEventConverterEvdev* dev = device(); - - struct input_event mock_kernel_queue[] = { - {{0, 0}, EV_MSC, MSC_SCAN, 0x700e1}, - {{0, 0}, EV_KEY, KEY_LEFTCTRL, 1}, - {{0, 0}, EV_SYN, SYN_REPORT, 0}, - - {{0, 0}, EV_MSC, MSC_SCAN, 0x700e5}, - {{0, 0}, EV_KEY, KEY_RIGHTCTRL, 1}, - {{0, 0}, EV_SYN, SYN_REPORT, 0}, - - {{0, 0}, EV_MSC, MSC_SCAN, 0x7001d}, - {{0, 0}, EV_KEY, KEY_Z, 1}, - {{0, 0}, EV_SYN, SYN_REPORT, 0}, - - {{0, 0}, EV_MSC, MSC_SCAN, 0x7001d}, - {{0, 0}, EV_KEY, KEY_Z, 0}, - {{0, 0}, EV_SYN, SYN_REPORT, 0}, - - {{0, 0}, EV_MSC, MSC_SCAN, 0x700e1}, - {{0, 0}, EV_KEY, KEY_LEFTCTRL, 0}, - {{0, 0}, EV_SYN, SYN_REPORT, 0}, - - {{0, 0}, EV_MSC, MSC_SCAN, 0x700e5}, - {{0, 0}, EV_KEY, KEY_RIGHTCTRL, 0}, - {{0, 0}, EV_SYN, SYN_REPORT, 0}, - }; - - dev->ProcessEvents(mock_kernel_queue, arraysize(mock_kernel_queue)); - EXPECT_EQ(6u, size()); - - ui::KeyEvent* event; - - event = dispatched_event(0); - EXPECT_EQ(ui::ET_KEY_PRESSED, event->type()); - EXPECT_EQ(ui::VKEY_CONTROL, event->key_code()); - EXPECT_EQ(ui::EF_CONTROL_DOWN, event->flags()); - - event = dispatched_event(1); - EXPECT_EQ(ui::ET_KEY_PRESSED, event->type()); - EXPECT_EQ(ui::VKEY_CONTROL, event->key_code()); - EXPECT_EQ(ui::EF_CONTROL_DOWN, event->flags()); - - event = dispatched_event(2); - EXPECT_EQ(ui::ET_KEY_PRESSED, event->type()); - EXPECT_EQ(ui::VKEY_Z, event->key_code()); - EXPECT_EQ(ui::EF_CONTROL_DOWN, event->flags()); - - event = dispatched_event(3); - EXPECT_EQ(ui::ET_KEY_RELEASED, event->type()); - EXPECT_EQ(ui::VKEY_Z, event->key_code()); - EXPECT_EQ(ui::EF_CONTROL_DOWN, event->flags()); - - event = dispatched_event(4); - EXPECT_EQ(ui::ET_KEY_RELEASED, event->type()); - EXPECT_EQ(ui::VKEY_CONTROL, event->key_code()); - EXPECT_EQ(ui::EF_CONTROL_DOWN, event->flags()); - - event = dispatched_event(5); - EXPECT_EQ(ui::ET_KEY_RELEASED, event->type()); - EXPECT_EQ(ui::VKEY_CONTROL, event->key_code()); - EXPECT_EQ(0, event->flags()); -} - -TEST_F(KeyEventConverterEvdevTest, KeyWithLock) { - ui::MockKeyEventConverterEvdev* dev = device(); - - struct input_event mock_kernel_queue[] = { - {{0, 0}, EV_MSC, MSC_SCAN, 0x70039}, - {{0, 0}, EV_KEY, KEY_CAPSLOCK, 1}, - {{0, 0}, EV_SYN, SYN_REPORT, 0}, - - {{0, 0}, EV_MSC, MSC_SCAN, 0x70039}, - {{0, 0}, EV_KEY, KEY_CAPSLOCK, 0}, - {{0, 0}, EV_SYN, SYN_REPORT, 0}, - - {{0, 0}, EV_MSC, MSC_SCAN, 0x70014}, - {{0, 0}, EV_KEY, KEY_Q, 1}, - {{0, 0}, EV_SYN, SYN_REPORT, 0}, - - {{0, 0}, EV_MSC, MSC_SCAN, 0x70014}, - {{0, 0}, EV_KEY, KEY_Q, 0}, - {{0, 0}, EV_SYN, SYN_REPORT, 0}, - - {{0, 0}, EV_MSC, MSC_SCAN, 0x70039}, - {{0, 0}, EV_KEY, KEY_CAPSLOCK, 1}, - {{0, 0}, EV_SYN, SYN_REPORT, 0}, - - {{0, 0}, EV_MSC, MSC_SCAN, 0x70039}, - {{0, 0}, EV_KEY, KEY_CAPSLOCK, 0}, - {{0, 0}, EV_SYN, SYN_REPORT, 0}, - }; - - dev->ProcessEvents(mock_kernel_queue, arraysize(mock_kernel_queue)); - EXPECT_EQ(6u, size()); - - ui::KeyEvent* event; - - event = dispatched_event(0); - EXPECT_EQ(ui::ET_KEY_PRESSED, event->type()); - EXPECT_EQ(ui::VKEY_CAPITAL, event->key_code()); - EXPECT_EQ(ui::EF_CAPS_LOCK_DOWN, event->flags()); - - event = dispatched_event(1); - EXPECT_EQ(ui::ET_KEY_RELEASED, event->type()); - EXPECT_EQ(ui::VKEY_CAPITAL, event->key_code()); - EXPECT_EQ(ui::EF_CAPS_LOCK_DOWN, event->flags()); - - event = dispatched_event(2); - EXPECT_EQ(ui::ET_KEY_PRESSED, event->type()); - EXPECT_EQ(ui::VKEY_Q, event->key_code()); - EXPECT_EQ(ui::EF_CAPS_LOCK_DOWN, event->flags()); - - event = dispatched_event(3); - EXPECT_EQ(ui::ET_KEY_RELEASED, event->type()); - EXPECT_EQ(ui::VKEY_Q, event->key_code()); - EXPECT_EQ(ui::EF_CAPS_LOCK_DOWN, event->flags()); - - event = dispatched_event(4); - EXPECT_EQ(ui::ET_KEY_PRESSED, event->type()); - EXPECT_EQ(ui::VKEY_CAPITAL, event->key_code()); - EXPECT_EQ(0, event->flags()); - - event = dispatched_event(5); - EXPECT_EQ(ui::ET_KEY_RELEASED, event->type()); - EXPECT_EQ(ui::VKEY_CAPITAL, event->key_code()); - EXPECT_EQ(0, event->flags()); -}
diff --git a/ui/events/ozone/evdev/keyboard_evdev.cc b/ui/events/ozone/evdev/keyboard_evdev.cc deleted file mode 100644 index 468f0fd..0000000 --- a/ui/events/ozone/evdev/keyboard_evdev.cc +++ /dev/null
@@ -1,238 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/events/ozone/evdev/keyboard_evdev.h" - -#include "ui/events/event.h" -#include "ui/events/keycodes/dom4/keycode_converter.h" -#include "ui/events/ozone/evdev/event_modifiers_evdev.h" - -namespace ui { - -namespace { - -const int kXkbKeycodeOffset = 8; - -ui::KeyboardCode KeyboardCodeFromEvdevKey(unsigned int code) { - static const ui::KeyboardCode kLinuxBaseKeyMap[] = { - ui::VKEY_UNKNOWN, // KEY_RESERVED - ui::VKEY_ESCAPE, // KEY_ESC - ui::VKEY_1, // KEY_1 - ui::VKEY_2, // KEY_2 - ui::VKEY_3, // KEY_3 - ui::VKEY_4, // KEY_4 - ui::VKEY_5, // KEY_5 - ui::VKEY_6, // KEY_6 - ui::VKEY_7, // KEY_7 - ui::VKEY_8, // KEY_8 - ui::VKEY_9, // KEY_9 - ui::VKEY_0, // KEY_0 - ui::VKEY_OEM_MINUS, // KEY_MINUS - ui::VKEY_OEM_PLUS, // KEY_EQUAL - ui::VKEY_BACK, // KEY_BACKSPACE - ui::VKEY_TAB, // KEY_TAB - ui::VKEY_Q, // KEY_Q - ui::VKEY_W, // KEY_W - ui::VKEY_E, // KEY_E - ui::VKEY_R, // KEY_R - ui::VKEY_T, // KEY_T - ui::VKEY_Y, // KEY_Y - ui::VKEY_U, // KEY_U - ui::VKEY_I, // KEY_I - ui::VKEY_O, // KEY_O - ui::VKEY_P, // KEY_P - ui::VKEY_OEM_4, // KEY_LEFTBRACE - ui::VKEY_OEM_6, // KEY_RIGHTBRACE - ui::VKEY_RETURN, // KEY_ENTER - ui::VKEY_CONTROL, // KEY_LEFTCTRL - ui::VKEY_A, // KEY_A - ui::VKEY_S, // KEY_S - ui::VKEY_D, // KEY_D - ui::VKEY_F, // KEY_F - ui::VKEY_G, // KEY_G - ui::VKEY_H, // KEY_H - ui::VKEY_J, // KEY_J - ui::VKEY_K, // KEY_K - ui::VKEY_L, // KEY_L - ui::VKEY_OEM_1, // KEY_SEMICOLON - ui::VKEY_OEM_7, // KEY_APOSTROPHE - ui::VKEY_OEM_3, // KEY_GRAVE - ui::VKEY_SHIFT, // KEY_LEFTSHIFT - ui::VKEY_OEM_5, // KEY_BACKSLASH - ui::VKEY_Z, // KEY_Z - ui::VKEY_X, // KEY_X - ui::VKEY_C, // KEY_C - ui::VKEY_V, // KEY_V - ui::VKEY_B, // KEY_B - ui::VKEY_N, // KEY_N - ui::VKEY_M, // KEY_M - ui::VKEY_OEM_COMMA, // KEY_COMMA - ui::VKEY_OEM_PERIOD, // KEY_DOT - ui::VKEY_OEM_2, // KEY_SLASH - ui::VKEY_SHIFT, // KEY_RIGHTSHIFT - ui::VKEY_MULTIPLY, // KEY_KPASTERISK - ui::VKEY_MENU, // KEY_LEFTALT - ui::VKEY_SPACE, // KEY_SPACE - ui::VKEY_CAPITAL, // KEY_CAPSLOCK - ui::VKEY_F1, // KEY_F1 - ui::VKEY_F2, // KEY_F2 - ui::VKEY_F3, // KEY_F3 - ui::VKEY_F4, // KEY_F4 - ui::VKEY_F5, // KEY_F5 - ui::VKEY_F6, // KEY_F6 - ui::VKEY_F7, // KEY_F7 - ui::VKEY_F8, // KEY_F8 - ui::VKEY_F9, // KEY_F9 - ui::VKEY_F10, // KEY_F10 - ui::VKEY_NUMLOCK, // KEY_NUMLOCK - ui::VKEY_SCROLL, // KEY_SCROLLLOCK - ui::VKEY_NUMPAD7, // KEY_KP7 - ui::VKEY_NUMPAD8, // KEY_KP8 - ui::VKEY_NUMPAD9, // KEY_KP9 - ui::VKEY_SUBTRACT, // KEY_KPMINUS - ui::VKEY_NUMPAD4, // KEY_KP4 - ui::VKEY_NUMPAD5, // KEY_KP5 - ui::VKEY_NUMPAD6, // KEY_KP6 - ui::VKEY_ADD, // KEY_KPPLUS - ui::VKEY_NUMPAD1, // KEY_KP1 - ui::VKEY_NUMPAD2, // KEY_KP2 - ui::VKEY_NUMPAD3, // KEY_KP3 - ui::VKEY_NUMPAD0, // KEY_KP0 - ui::VKEY_DECIMAL, // KEY_KPDOT - ui::VKEY_UNKNOWN, // (unassigned) - ui::VKEY_DBE_DBCSCHAR, // KEY_ZENKAKUHANKAKU - ui::VKEY_OEM_102, // KEY_102ND - ui::VKEY_F11, // KEY_F11 - ui::VKEY_F12, // KEY_F12 - ui::VKEY_UNKNOWN, // KEY_RO - ui::VKEY_UNKNOWN, // KEY_KATAKANA - ui::VKEY_UNKNOWN, // KEY_HIRAGANA - ui::VKEY_CONVERT, // KEY_HENKAN - ui::VKEY_UNKNOWN, // KEY_KATAKANAHIRAGANA - ui::VKEY_NONCONVERT, // KEY_MUHENKAN - ui::VKEY_UNKNOWN, // KEY_KPJPCOMMA - ui::VKEY_RETURN, // KEY_KPENTER - ui::VKEY_CONTROL, // KEY_RIGHTCTRL - ui::VKEY_DIVIDE, // KEY_KPSLASH - ui::VKEY_PRINT, // KEY_SYSRQ - ui::VKEY_MENU, // KEY_RIGHTALT - ui::VKEY_RETURN, // KEY_LINEFEED - ui::VKEY_HOME, // KEY_HOME - ui::VKEY_UP, // KEY_UP - ui::VKEY_PRIOR, // KEY_PAGEUP - ui::VKEY_LEFT, // KEY_LEFT - ui::VKEY_RIGHT, // KEY_RIGHT - ui::VKEY_END, // KEY_END - ui::VKEY_DOWN, // KEY_DOWN - ui::VKEY_NEXT, // KEY_PAGEDOWN - ui::VKEY_INSERT, // KEY_INSERT - ui::VKEY_DELETE, // KEY_DELETE - ui::VKEY_UNKNOWN, // KEY_MACRO - ui::VKEY_VOLUME_MUTE, // KEY_MUTE - ui::VKEY_VOLUME_DOWN, // KEY_VOLUMEDOWN - ui::VKEY_VOLUME_UP, // KEY_VOLUMEUP - ui::VKEY_POWER, // KEY_POWER - ui::VKEY_OEM_PLUS, // KEY_KPEQUAL - ui::VKEY_UNKNOWN, // KEY_KPPLUSMINUS - ui::VKEY_PAUSE, // KEY_PAUSE - ui::VKEY_MEDIA_LAUNCH_APP1, // KEY_SCALE - ui::VKEY_DECIMAL, // KEY_KPCOMMA - ui::VKEY_HANGUL, // KEY_HANGEUL - ui::VKEY_HANJA, // KEY_HANJA - ui::VKEY_UNKNOWN, // KEY_YEN - ui::VKEY_LWIN, // KEY_LEFTMETA - ui::VKEY_RWIN, // KEY_RIGHTMETA - ui::VKEY_APPS, // KEY_COMPOSE - }; - - if (code < arraysize(kLinuxBaseKeyMap)) - return kLinuxBaseKeyMap[code]; - - LOG(ERROR) << "Unknown key code: " << code; - return ui::VKEY_UNKNOWN; -} - -int ModifierFromEvdevKey(unsigned int code) { - switch (code) { - case KEY_CAPSLOCK: - return EVDEV_MODIFIER_CAPS_LOCK; - case KEY_LEFTSHIFT: - case KEY_RIGHTSHIFT: - return EVDEV_MODIFIER_SHIFT; - case KEY_LEFTCTRL: - case KEY_RIGHTCTRL: - return EVDEV_MODIFIER_CONTROL; - case KEY_LEFTALT: - case KEY_RIGHTALT: - return EVDEV_MODIFIER_ALT; - case BTN_LEFT: - return EVDEV_MODIFIER_LEFT_MOUSE_BUTTON; - case BTN_MIDDLE: - return EVDEV_MODIFIER_MIDDLE_MOUSE_BUTTON; - case BTN_RIGHT: - return EVDEV_MODIFIER_RIGHT_MOUSE_BUTTON; - case KEY_LEFTMETA: - case KEY_RIGHTMETA: - return EVDEV_MODIFIER_COMMAND; - default: - return EVDEV_MODIFIER_NONE; - } -} - -bool IsModifierLockKeyFromEvdevKey(unsigned int code) { - return code == KEY_CAPSLOCK; -} - -} // namespace - -KeyboardEvdev::KeyboardEvdev(EventModifiersEvdev* modifiers, - const EventDispatchCallback& callback) - : callback_(callback), modifiers_(modifiers) { -} - -KeyboardEvdev::~KeyboardEvdev() { -} - -void KeyboardEvdev::OnKeyChange(unsigned int key, bool down) { - if (key > KEY_MAX) - return; - - if (down != key_state_.test(key)) { - // State transition: !(down) -> (down) - if (down) - key_state_.set(key); - else - key_state_.reset(key); - - UpdateModifier(key, down); - } - - DispatchKey(key, down); -} - -void KeyboardEvdev::UpdateModifier(unsigned int key, bool down) { - int modifier = ModifierFromEvdevKey(key); - int locking = IsModifierLockKeyFromEvdevKey(key); - - if (modifier == EVDEV_MODIFIER_NONE) - return; - - if (locking) - modifiers_->UpdateModifierLock(modifier, down); - else - modifiers_->UpdateModifier(modifier, down); -} - -void KeyboardEvdev::DispatchKey(unsigned int key, bool down) { - ui::KeyboardCode code = KeyboardCodeFromEvdevKey(key); - int flags = modifiers_->GetModifierFlags(); - - callback_.Run(make_scoped_ptr(new KeyEvent( - down ? ET_KEY_PRESSED : ET_KEY_RELEASED, - code, - KeycodeConverter::NativeKeycodeToCode(key + kXkbKeycodeOffset), - flags))); -} - -} // namespace ui
diff --git a/ui/events/ozone/evdev/keyboard_evdev.h b/ui/events/ozone/evdev/keyboard_evdev.h deleted file mode 100644 index 913d006..0000000 --- a/ui/events/ozone/evdev/keyboard_evdev.h +++ /dev/null
@@ -1,60 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_EVENTS_OZONE_EVDEV_KEYBOARD_EVDEV_H_ -#define UI_EVENTS_OZONE_EVDEV_KEYBOARD_EVDEV_H_ - -#include <bitset> -#include <linux/input.h> - -#include "ui/events/ozone/evdev/event_device_util.h" -#include "ui/events/ozone/evdev/event_dispatch_callback.h" -#include "ui/events/ozone/evdev/events_ozone_evdev_export.h" - -namespace ui { - -class EventModifiersEvdev; - -// Keyboard for evdev. -// -// This object is responsible for combining all attached keyboards into -// one logical keyboard, applying modifiers & implementing key repeat. -// -// It also currently also applies the layout (hardcoded as US). -// -// TODO(spang): Implement key repeat & turn off kernel repeat. -class EVENTS_OZONE_EVDEV_EXPORT KeyboardEvdev { - public: - KeyboardEvdev(EventModifiersEvdev* modifiers, - const EventDispatchCallback& callback); - ~KeyboardEvdev(); - - // Handlers for raw key presses & releases. - void OnKeyChange(unsigned int code, bool down); - - private: - void UpdateModifier(unsigned int key, bool down); - void DispatchKey(unsigned int key, bool down); - - // Aggregated key state. There is only one bit of state per key; we do not - // attempt to count presses of the same key on multiple keyboards. - // - // A key is down iff the most recent event pertaining to that key was a key - // down event rather than a key up event. Therefore, a particular key position - // can be considered released even if it is being depresssed on one or more - // keyboards. - std::bitset<KEY_CNT> key_state_; - - // Callback for dispatching events. - EventDispatchCallback callback_; - - // Shared modifier state. - EventModifiersEvdev* modifiers_; - - DISALLOW_COPY_AND_ASSIGN(KeyboardEvdev); -}; - -} // namespace ui - -#endif // UI_EVENTS_OZONE_EVDEV_KEYBOARD_EVDEV_H_
diff --git a/ui/events/ozone/evdev/libgestures_glue/event_reader_libevdev_cros.cc b/ui/events/ozone/evdev/libgestures_glue/event_reader_libevdev_cros.cc deleted file mode 100644 index f7859cf..0000000 --- a/ui/events/ozone/evdev/libgestures_glue/event_reader_libevdev_cros.cc +++ /dev/null
@@ -1,91 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/events/ozone/evdev/libgestures_glue/event_reader_libevdev_cros.h" - -#include <errno.h> -#include <libevdev/libevdev.h> -#include <linux/input.h> - -#include "base/message_loop/message_loop.h" -#include "base/strings/string_util.h" -#include "base/strings/stringprintf.h" - -namespace ui { - -namespace { - -std::string FormatLog(const char* fmt, va_list args) { - std::string msg = base::StringPrintV(fmt, args); - if (!msg.empty() && msg[msg.size() - 1] == '\n') - msg.erase(msg.end() - 1, msg.end()); - return msg; -} - -} // namespace - -EventReaderLibevdevCros::EventReaderLibevdevCros(int fd, - const base::FilePath& path, - int id, - scoped_ptr<Delegate> delegate) - : EventConverterEvdev(fd, path, id), delegate_(delegate.Pass()) { - memset(&evdev_, 0, sizeof(evdev_)); - evdev_.log = OnLogMessage; - evdev_.log_udata = this; - evdev_.syn_report = OnSynReport; - evdev_.syn_report_udata = this; - evdev_.fd = fd; - - memset(&evstate_, 0, sizeof(evstate_)); - evdev_.evstate = &evstate_; - Event_Init(&evdev_); - - Event_Open(&evdev_); - - delegate_->OnLibEvdevCrosOpen(&evdev_, &evstate_); -} - -EventReaderLibevdevCros::~EventReaderLibevdevCros() { - Stop(); - EvdevClose(&evdev_); -} - -EventReaderLibevdevCros::Delegate::~Delegate() {} - -void EventReaderLibevdevCros::OnFileCanReadWithoutBlocking(int fd) { - if (EvdevRead(&evdev_)) { - if (errno == EINTR || errno == EAGAIN) - return; - if (errno != ENODEV) - PLOG(ERROR) << "error reading device " << path_.value(); - Stop(); - return; - } -} - -// static -void EventReaderLibevdevCros::OnSynReport(void* data, - EventStateRec* evstate, - struct timeval* tv) { - EventReaderLibevdevCros* reader = static_cast<EventReaderLibevdevCros*>(data); - reader->delegate_->OnLibEvdevCrosEvent(&reader->evdev_, evstate, *tv); -} - -// static -void EventReaderLibevdevCros::OnLogMessage(void* data, - int level, - const char* fmt, - ...) { - va_list args; - va_start(args, fmt); - if (level >= LOGLEVEL_ERROR) - LOG(ERROR) << "libevdev: " << FormatLog(fmt, args); - else if (level >= LOGLEVEL_WARNING) - LOG(WARNING) << "libevdev: " << FormatLog(fmt, args); - else - VLOG(3) << "libevdev: " << FormatLog(fmt, args); - va_end(args); -} - -} // namespace ui
diff --git a/ui/events/ozone/evdev/libgestures_glue/event_reader_libevdev_cros.h b/ui/events/ozone/evdev/libgestures_glue/event_reader_libevdev_cros.h deleted file mode 100644 index c056496..0000000 --- a/ui/events/ozone/evdev/libgestures_glue/event_reader_libevdev_cros.h +++ /dev/null
@@ -1,70 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_EVENTS_OZONE_EVDEV_LIBGESTURES_GLUE_EVENT_READER_LIBEVDEV_CROS_H_ -#define UI_EVENTS_OZONE_EVDEV_LIBGESTURES_GLUE_EVENT_READER_LIBEVDEV_CROS_H_ - -#include <libevdev/libevdev.h> - -#include "base/files/file_path.h" -#include "base/message_loop/message_loop.h" -#include "ui/events/ozone/evdev/event_converter_evdev.h" - -namespace ui { - -// Basic wrapper for libevdev-cros. -// -// This drives libevdev-cros from a file descriptor and calls delegate -// with the updated event state from libevdev-cros. -// -// The library doesn't support all devices currently. In particular there -// is no support for keyboard events. -class EventReaderLibevdevCros : public EventConverterEvdev { - public: - class Delegate { - public: - virtual ~Delegate(); - - // Notifier for open. This is called with the initial event state. - virtual void OnLibEvdevCrosOpen(Evdev* evdev, EventStateRec* evstate) = 0; - - // Notifier for event. This is called with the updated event state. - virtual void OnLibEvdevCrosEvent(Evdev* evdev, - EventStateRec* state, - const timeval& time) = 0; - }; - - EventReaderLibevdevCros(int fd, - const base::FilePath& path, - int id, - scoped_ptr<Delegate> delegate); - ~EventReaderLibevdevCros(); - - // EventConverterEvdev: - virtual void OnFileCanReadWithoutBlocking(int fd) override; - - private: - static void OnSynReport(void* data, - EventStateRec* evstate, - struct timeval* tv); - static void OnLogMessage(void*, int level, const char*, ...); - - // Libevdev state. - Evdev evdev_; - - // Event state. - EventStateRec evstate_; - - // Path to input device. - base::FilePath path_; - - // Delegate for event processing. - scoped_ptr<Delegate> delegate_; - - DISALLOW_COPY_AND_ASSIGN(EventReaderLibevdevCros); -}; - -} // namspace ui - -#endif // UI_EVENTS_OZONE_EVDEV_LIBGESTURES_GLUE_EVENT_READER_LIBEVDEV_CROS_H_
diff --git a/ui/events/ozone/evdev/libgestures_glue/gesture_interpreter_libevdev_cros.cc b/ui/events/ozone/evdev/libgestures_glue/gesture_interpreter_libevdev_cros.cc deleted file mode 100644 index 9bc7c8e..0000000 --- a/ui/events/ozone/evdev/libgestures_glue/gesture_interpreter_libevdev_cros.cc +++ /dev/null
@@ -1,452 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/events/ozone/evdev/libgestures_glue/gesture_interpreter_libevdev_cros.h" - -#include <gestures/gestures.h> -#include <libevdev/libevdev.h> - -#include "base/strings/stringprintf.h" -#include "base/timer/timer.h" -#include "ui/events/event.h" -#include "ui/events/ozone/evdev/cursor_delegate_evdev.h" -#include "ui/events/ozone/evdev/event_device_util.h" -#include "ui/events/ozone/evdev/event_modifiers_evdev.h" -#include "ui/events/ozone/evdev/keyboard_evdev.h" -#include "ui/events/ozone/evdev/libgestures_glue/gesture_property_provider.h" -#include "ui/events/ozone/evdev/libgestures_glue/gesture_timer_provider.h" -#include "ui/gfx/geometry/point_f.h" - -namespace ui { - -namespace { - -// Convert libevdev device class to libgestures device class. -GestureInterpreterDeviceClass GestureDeviceClass(Evdev* evdev) { - switch (evdev->info.evdev_class) { - case EvdevClassMouse: - return GESTURES_DEVCLASS_MOUSE; - case EvdevClassMultitouchMouse: - return GESTURES_DEVCLASS_MULTITOUCH_MOUSE; - case EvdevClassTouchpad: - return GESTURES_DEVCLASS_TOUCHPAD; - case EvdevClassTouchscreen: - return GESTURES_DEVCLASS_TOUCHSCREEN; - default: - return GESTURES_DEVCLASS_UNKNOWN; - } -} - -// Convert libevdev state to libgestures hardware properties. -HardwareProperties GestureHardwareProperties( - Evdev* evdev, - const GestureDeviceProperties* props) { - HardwareProperties hwprops; - hwprops.left = props->area_left; - hwprops.top = props->area_top; - hwprops.right = props->area_right; - hwprops.bottom = props->area_bottom; - hwprops.res_x = props->res_x; - hwprops.res_y = props->res_y; - hwprops.screen_x_dpi = 133; - hwprops.screen_y_dpi = 133; - hwprops.orientation_minimum = props->orientation_minimum; - hwprops.orientation_maximum = props->orientation_maximum; - hwprops.max_finger_cnt = Event_Get_Slot_Count(evdev); - hwprops.max_touch_cnt = Event_Get_Touch_Count_Max(evdev); - hwprops.supports_t5r2 = Event_Get_T5R2(evdev); - hwprops.support_semi_mt = Event_Get_Semi_MT(evdev); - /* buttonpad means a physical button under the touch surface */ - hwprops.is_button_pad = Event_Get_Button_Pad(evdev); - return hwprops; -} - -// Callback from libgestures when a gesture is ready. -void OnGestureReadyHelper(void* client_data, const Gesture* gesture) { - GestureInterpreterLibevdevCros* interpreter = - static_cast<GestureInterpreterLibevdevCros*>(client_data); - interpreter->OnGestureReady(gesture); -} - -// Convert gestures timestamp (stime_t) to ui::Event timestamp. -base::TimeDelta StimeToTimedelta(stime_t timestamp) { - return base::TimeDelta::FromMicroseconds(timestamp * - base::Time::kMicrosecondsPerSecond); -} - -// Number of fingers for scroll gestures. -const int kGestureScrollFingerCount = 2; - -// Number of fingers for swipe gestures. -const int kGestureSwipeFingerCount = 3; - -} // namespace - -GestureInterpreterLibevdevCros::GestureInterpreterLibevdevCros( - int id, - EventModifiersEvdev* modifiers, - CursorDelegateEvdev* cursor, - KeyboardEvdev* keyboard, - GesturePropertyProvider* property_provider, - const EventDispatchCallback& callback) - : id_(id), - modifiers_(modifiers), - cursor_(cursor), - keyboard_(keyboard), - property_provider_(property_provider), - dispatch_callback_(callback), - interpreter_(NULL), - evdev_(NULL), - device_properties_(new GestureDeviceProperties) { - memset(&prev_key_state_, 0, sizeof(prev_key_state_)); -} - -GestureInterpreterLibevdevCros::~GestureInterpreterLibevdevCros() { - // Note that this destructor got called after the evdev device node has been - // closed. Therefore, all clean-up codes here shouldn't depend on the device - // information (except for the pointer address itself). - - // Clean-up if the gesture interpreter has been successfully created. - if (interpreter_) { - // Unset callbacks. - GestureInterpreterSetCallback(interpreter_, NULL, NULL); - GestureInterpreterSetPropProvider(interpreter_, NULL, NULL); - GestureInterpreterSetTimerProvider(interpreter_, NULL, NULL); - DeleteGestureInterpreter(interpreter_); - interpreter_ = NULL; - } - - // Unregister device from the gesture property provider. - GesturesPropFunctionsWrapper::UnregisterDevice(this); -} - -void GestureInterpreterLibevdevCros::OnLibEvdevCrosOpen( - Evdev* evdev, - EventStateRec* evstate) { - DCHECK(evdev->info.is_monotonic) << "libevdev must use monotonic timestamps"; - VLOG(9) << "HACK DO NOT REMOVE OR LINK WILL FAIL" << (void*)gestures_log; - - // Set device pointer and initialize properties. - evdev_ = evdev; - GesturesPropFunctionsWrapper::InitializeDeviceProperties( - this, device_properties_.get()); - HardwareProperties hwprops = - GestureHardwareProperties(evdev, device_properties_.get()); - GestureInterpreterDeviceClass devclass = GestureDeviceClass(evdev); - - // Create & initialize GestureInterpreter. - DCHECK(!interpreter_); - interpreter_ = NewGestureInterpreter(); - GestureInterpreterSetPropProvider( - interpreter_, - const_cast<GesturesPropProvider*>(&kGesturePropProvider), - this); - GestureInterpreterInitialize(interpreter_, devclass); - GestureInterpreterSetHardwareProperties(interpreter_, &hwprops); - GestureInterpreterSetTimerProvider( - interpreter_, - const_cast<GesturesTimerProvider*>(&kGestureTimerProvider), - this); - GestureInterpreterSetCallback(interpreter_, OnGestureReadyHelper, this); -} - -void GestureInterpreterLibevdevCros::OnLibEvdevCrosEvent(Evdev* evdev, - EventStateRec* evstate, - const timeval& time) { - // If the device has keys no it, dispatch any presses/release. - DispatchChangedKeys(evdev, time); - - HardwareState hwstate; - memset(&hwstate, 0, sizeof(hwstate)); - hwstate.timestamp = StimeFromTimeval(&time); - - // Mouse. - hwstate.rel_x = evstate->rel_x; - hwstate.rel_y = evstate->rel_y; - hwstate.rel_wheel = evstate->rel_wheel; - hwstate.rel_hwheel = evstate->rel_hwheel; - - // Touch. - FingerState fingers[Event_Get_Slot_Count(evdev)]; - memset(&fingers, 0, sizeof(fingers)); - int current_finger = 0; - for (int i = 0; i < evstate->slot_count; i++) { - MtSlotPtr slot = &evstate->slots[i]; - if (slot->tracking_id == -1) - continue; - fingers[current_finger].touch_major = slot->touch_major; - fingers[current_finger].touch_minor = slot->touch_minor; - fingers[current_finger].width_major = slot->width_major; - fingers[current_finger].width_minor = slot->width_minor; - fingers[current_finger].pressure = slot->pressure; - fingers[current_finger].orientation = slot->orientation; - fingers[current_finger].position_x = slot->position_x; - fingers[current_finger].position_y = slot->position_y; - fingers[current_finger].tracking_id = slot->tracking_id; - current_finger++; - } - hwstate.touch_cnt = Event_Get_Touch_Count(evdev); - hwstate.finger_cnt = current_finger; - hwstate.fingers = fingers; - - // Buttons. - if (Event_Get_Button_Left(evdev)) - hwstate.buttons_down |= GESTURES_BUTTON_LEFT; - if (Event_Get_Button_Middle(evdev)) - hwstate.buttons_down |= GESTURES_BUTTON_MIDDLE; - if (Event_Get_Button_Right(evdev)) - hwstate.buttons_down |= GESTURES_BUTTON_RIGHT; - - GestureInterpreterPushHardwareState(interpreter_, &hwstate); -} - -void GestureInterpreterLibevdevCros::OnGestureReady(const Gesture* gesture) { - switch (gesture->type) { - case kGestureTypeMove: - OnGestureMove(gesture, &gesture->details.move); - break; - case kGestureTypeScroll: - OnGestureScroll(gesture, &gesture->details.scroll); - break; - case kGestureTypeButtonsChange: - OnGestureButtonsChange(gesture, &gesture->details.buttons); - break; - case kGestureTypeContactInitiated: - OnGestureContactInitiated(gesture); - break; - case kGestureTypeFling: - OnGestureFling(gesture, &gesture->details.fling); - break; - case kGestureTypeSwipe: - OnGestureSwipe(gesture, &gesture->details.swipe); - break; - case kGestureTypeSwipeLift: - OnGestureSwipeLift(gesture, &gesture->details.swipe_lift); - break; - case kGestureTypePinch: - OnGesturePinch(gesture, &gesture->details.pinch); - break; - case kGestureTypeMetrics: - OnGestureMetrics(gesture, &gesture->details.metrics); - break; - default: - LOG(WARNING) << base::StringPrintf("Unrecognized gesture type (%u)", - gesture->type); - break; - } -} - -void GestureInterpreterLibevdevCros::OnGestureMove(const Gesture* gesture, - const GestureMove* move) { - DVLOG(3) << base::StringPrintf("Gesture Move: (%f, %f) [%f, %f]", - move->dx, - move->dy, - move->ordinal_dx, - move->ordinal_dy); - if (!cursor_) - return; // No cursor! - - cursor_->MoveCursor(gfx::Vector2dF(move->dx, move->dy)); - // TODO(spang): Use move->ordinal_dx, move->ordinal_dy - // TODO(spang): Use move->start_time, move->end_time - Dispatch(make_scoped_ptr(new MouseEvent(ET_MOUSE_MOVED, - cursor_->location(), - cursor_->location(), - modifiers_->GetModifierFlags(), - /* changed_button_flags */ 0))); -} - -void GestureInterpreterLibevdevCros::OnGestureScroll( - const Gesture* gesture, - const GestureScroll* scroll) { - DVLOG(3) << base::StringPrintf("Gesture Scroll: (%f, %f) [%f, %f]", - scroll->dx, - scroll->dy, - scroll->ordinal_dx, - scroll->ordinal_dy); - if (!cursor_) - return; // No cursor! - - // TODO(spang): Support SetNaturalScroll - // TODO(spang): Use scroll->start_time - Dispatch(make_scoped_ptr(new ScrollEvent(ET_SCROLL, - cursor_->location(), - StimeToTimedelta(gesture->end_time), - modifiers_->GetModifierFlags(), - scroll->dx, - scroll->dy, - scroll->ordinal_dx, - scroll->ordinal_dy, - kGestureScrollFingerCount))); -} - -void GestureInterpreterLibevdevCros::OnGestureButtonsChange( - const Gesture* gesture, - const GestureButtonsChange* buttons) { - DVLOG(3) << base::StringPrintf("Gesture Button Change: down=0x%02x up=0x%02x", - buttons->down, - buttons->up); - - if (!cursor_) - return; // No cursor! - - // HACK for disabling TTC (actually, all clicks) on hidden cursor. - // This is normally plumbed via properties and can be removed soon. - // TODO(spang): Remove this. - if (buttons->down == GESTURES_BUTTON_LEFT && - buttons->up == GESTURES_BUTTON_LEFT && - !cursor_->IsCursorVisible()) - return; - - // TODO(spang): Use buttons->start_time, buttons->end_time - if (buttons->down & GESTURES_BUTTON_LEFT) - DispatchMouseButton(EVDEV_MODIFIER_LEFT_MOUSE_BUTTON, true); - if (buttons->down & GESTURES_BUTTON_MIDDLE) - DispatchMouseButton(EVDEV_MODIFIER_MIDDLE_MOUSE_BUTTON, true); - if (buttons->down & GESTURES_BUTTON_RIGHT) - DispatchMouseButton(EVDEV_MODIFIER_RIGHT_MOUSE_BUTTON, true); - if (buttons->up & GESTURES_BUTTON_LEFT) - DispatchMouseButton(EVDEV_MODIFIER_LEFT_MOUSE_BUTTON, false); - if (buttons->up & GESTURES_BUTTON_MIDDLE) - DispatchMouseButton(EVDEV_MODIFIER_MIDDLE_MOUSE_BUTTON, false); - if (buttons->up & GESTURES_BUTTON_RIGHT) - DispatchMouseButton(EVDEV_MODIFIER_RIGHT_MOUSE_BUTTON, false); -} - -void GestureInterpreterLibevdevCros::OnGestureContactInitiated( - const Gesture* gesture) { - // TODO(spang): handle contact initiated. -} - -void GestureInterpreterLibevdevCros::OnGestureFling(const Gesture* gesture, - const GestureFling* fling) { - DVLOG(3) << base::StringPrintf( - "Gesture Fling: (%f, %f) [%f, %f] fling_state=%d", - fling->vx, - fling->vy, - fling->ordinal_vx, - fling->ordinal_vy, - fling->fling_state); - - if (!cursor_) - return; // No cursor! - - EventType type = - (fling->fling_state == GESTURES_FLING_START ? ET_SCROLL_FLING_START - : ET_SCROLL_FLING_CANCEL); - - // Fling is like 2-finger scrolling but with velocity instead of displacement. - Dispatch(make_scoped_ptr(new ScrollEvent(type, - cursor_->location(), - StimeToTimedelta(gesture->end_time), - modifiers_->GetModifierFlags(), - fling->vx, - fling->vy, - fling->ordinal_vx, - fling->ordinal_vy, - kGestureScrollFingerCount))); -} - -void GestureInterpreterLibevdevCros::OnGestureSwipe(const Gesture* gesture, - const GestureSwipe* swipe) { - DVLOG(3) << base::StringPrintf("Gesture Swipe: (%f, %f) [%f, %f]", - swipe->dx, - swipe->dy, - swipe->ordinal_dx, - swipe->ordinal_dy); - - if (!cursor_) - return; // No cursor! - - // Swipe is 3-finger scrolling. - Dispatch(make_scoped_ptr(new ScrollEvent(ET_SCROLL, - cursor_->location(), - StimeToTimedelta(gesture->end_time), - modifiers_->GetModifierFlags(), - swipe->dx, - swipe->dy, - swipe->ordinal_dx, - swipe->ordinal_dy, - kGestureSwipeFingerCount))); -} - -void GestureInterpreterLibevdevCros::OnGestureSwipeLift( - const Gesture* gesture, - const GestureSwipeLift* swipelift) { - DVLOG(3) << base::StringPrintf("Gesture Swipe Lift"); - - if (!cursor_) - return; // No cursor! - - // Turn a swipe lift into a fling start. - // TODO(spang): Figure out why and put it in this comment. - - Dispatch(make_scoped_ptr(new ScrollEvent(ET_SCROLL_FLING_START, - cursor_->location(), - StimeToTimedelta(gesture->end_time), - modifiers_->GetModifierFlags(), - /* x_offset */ 0, - /* y_offset */ 0, - /* x_offset_ordinal */ 0, - /* y_offset_ordinal */ 0, - kGestureScrollFingerCount))); -} - -void GestureInterpreterLibevdevCros::OnGesturePinch(const Gesture* gesture, - const GesturePinch* pinch) { - DVLOG(3) << base::StringPrintf( - "Gesture Pinch: dz=%f [%f]", pinch->dz, pinch->ordinal_dz); - - if (!cursor_) - return; // No cursor! - - NOTIMPLEMENTED(); -} - -void GestureInterpreterLibevdevCros::OnGestureMetrics( - const Gesture* gesture, - const GestureMetrics* metrics) { - DVLOG(3) << base::StringPrintf("Gesture Metrics: [%f, %f] type=%d", - metrics->data[0], - metrics->data[1], - metrics->type); - NOTIMPLEMENTED(); -} - -void GestureInterpreterLibevdevCros::Dispatch(scoped_ptr<Event> event) { - dispatch_callback_.Run(event.Pass()); -} - -void GestureInterpreterLibevdevCros::DispatchMouseButton(unsigned int modifier, - bool down) { - const gfx::PointF& loc = cursor_->location(); - int flag = modifiers_->GetEventFlagFromModifier(modifier); - EventType type = (down ? ET_MOUSE_PRESSED : ET_MOUSE_RELEASED); - modifiers_->UpdateModifier(modifier, down); - Dispatch(make_scoped_ptr(new MouseEvent( - type, loc, loc, modifiers_->GetModifierFlags() | flag, flag))); -} - -void GestureInterpreterLibevdevCros::DispatchChangedKeys(Evdev* evdev, - const timeval& time) { - unsigned long key_state_diff[EVDEV_BITS_TO_LONGS(KEY_CNT)]; - - // Find changed keys. - for (unsigned long i = 0; i < arraysize(key_state_diff); ++i) - key_state_diff[i] = evdev->key_state_bitmask[i] ^ prev_key_state_[i]; - - // Dispatch events for changed keys. - for (unsigned long i = 0; i < KEY_CNT; ++i) { - if (EvdevBitIsSet(key_state_diff, i)) { - bool value = EvdevBitIsSet(evdev->key_state_bitmask, i); - keyboard_->OnKeyChange(i, value); - } - } - - // Update internal key state. - for (unsigned long i = 0; i < EVDEV_BITS_TO_LONGS(KEY_CNT); ++i) - prev_key_state_[i] = evdev->key_state_bitmask[i]; -} - -} // namespace ui
diff --git a/ui/events/ozone/evdev/libgestures_glue/gesture_interpreter_libevdev_cros.h b/ui/events/ozone/evdev/libgestures_glue/gesture_interpreter_libevdev_cros.h deleted file mode 100644 index 9d89d0a..0000000 --- a/ui/events/ozone/evdev/libgestures_glue/gesture_interpreter_libevdev_cros.h +++ /dev/null
@@ -1,119 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_EVENTS_OZONE_EVDEV_LIBGESTURES_GLUE_GESTURE_INTERPRETER_LIBEVDEV_CROS_H_ -#define UI_EVENTS_OZONE_EVDEV_LIBGESTURES_GLUE_GESTURE_INTERPRETER_LIBEVDEV_CROS_H_ - -#include <gestures/gestures.h> -#include <libevdev/libevdev.h> - -#include "base/callback.h" -#include "base/memory/scoped_ptr.h" -#include "ui/events/ozone/evdev/cursor_delegate_evdev.h" -#include "ui/events/ozone/evdev/event_device_util.h" -#include "ui/events/ozone/evdev/event_dispatch_callback.h" -#include "ui/events/ozone/evdev/events_ozone_evdev_export.h" -#include "ui/events/ozone/evdev/libgestures_glue/event_reader_libevdev_cros.h" - -namespace ui { - -class EventDeviceInfo; -class EventModifiersEvdev; -class CursorDelegateEvdev; -class KeyboardEvdev; -class GestureDeviceProperties; -class GesturePropertyProvider; - -// Convert libevdev-cros events to ui::Events using libgestures. -// -// This builds a GestureInterpreter for an input device (touchpad or -// mouse). -// -// Raw input events must be preprocessed into a form suitable for -// libgestures. The kernel protocol only emits changes to the device state, -// so changes must be accumulated until a sync event. The full device state -// at sync is then processed by libgestures. -// -// Once we have the state at sync, we convert it to a HardwareState object -// and forward it to libgestures. If any gestures are produced, they are -// converted to ui::Events and dispatched. -class EVENTS_OZONE_EVDEV_EXPORT GestureInterpreterLibevdevCros - : public EventReaderLibevdevCros::Delegate { - public: - GestureInterpreterLibevdevCros(int id, - EventModifiersEvdev* modifiers, - CursorDelegateEvdev* cursor, - KeyboardEvdev* keyboard, - GesturePropertyProvider* property_provider, - const EventDispatchCallback& callback); - virtual ~GestureInterpreterLibevdevCros(); - - // Overriden from ui::EventReaderLibevdevCros::Delegate - virtual void OnLibEvdevCrosOpen(Evdev* evdev, - EventStateRec* evstate) override; - virtual void OnLibEvdevCrosEvent(Evdev* evdev, - EventStateRec* evstate, - const timeval& time) override; - - // Handler for gesture events generated from libgestures. - void OnGestureReady(const Gesture* gesture); - - // Accessors. - int id() { return id_; } - GesturePropertyProvider* property_provider() { return property_provider_; } - Evdev* evdev() { return evdev_; } - - private: - void OnGestureMove(const Gesture* gesture, const GestureMove* move); - void OnGestureScroll(const Gesture* gesture, const GestureScroll* move); - void OnGestureButtonsChange(const Gesture* gesture, - const GestureButtonsChange* move); - void OnGestureContactInitiated(const Gesture* gesture); - void OnGestureFling(const Gesture* gesture, const GestureFling* fling); - void OnGestureSwipe(const Gesture* gesture, const GestureSwipe* swipe); - void OnGestureSwipeLift(const Gesture* gesture, - const GestureSwipeLift* swipelift); - void OnGesturePinch(const Gesture* gesture, const GesturePinch* pinch); - void OnGestureMetrics(const Gesture* gesture, const GestureMetrics* metrics); - - void Dispatch(scoped_ptr<Event> event); - void DispatchMouseButton(unsigned int modifier, bool down); - void DispatchChangedKeys(Evdev* evdev, const timeval& time); - - // The unique device id. - int id_; - - // Shared modifier state. - EventModifiersEvdev* modifiers_; - - // Shared cursor state. - CursorDelegateEvdev* cursor_; - - // Shared keyboard state. - KeyboardEvdev* keyboard_; - - // Shared gesture property provider. - GesturePropertyProvider* property_provider_; - - // Callback for dispatching events. - EventDispatchCallback dispatch_callback_; - - // Gestures interpretation state. - gestures::GestureInterpreter* interpreter_; - - // Last key state from libevdev. - unsigned long prev_key_state_[EVDEV_BITS_TO_LONGS(KEY_CNT)]; - - // Device pointer. - Evdev* evdev_; - - // Gesture lib device properties. - scoped_ptr<GestureDeviceProperties> device_properties_; - - DISALLOW_COPY_AND_ASSIGN(GestureInterpreterLibevdevCros); -}; - -} // namspace ui - -#endif // UI_EVENTS_OZONE_EVDEV_LIBGESTURES_GLUE_GESTURE_INTERPRETER_LIBEVDEV_CROS_H_
diff --git a/ui/events/ozone/evdev/libgestures_glue/gesture_logging.cc b/ui/events/ozone/evdev/libgestures_glue/gesture_logging.cc deleted file mode 100644 index 009fc93..0000000 --- a/ui/events/ozone/evdev/libgestures_glue/gesture_logging.cc +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/events/ozone/evdev/libgestures_glue/gesture_logging.h" - -#include <gestures/gestures.h> -#include <stdarg.h> - -#include "base/logging.h" -#include "base/strings/stringprintf.h" - -namespace { - -std::string FormatLog(const char* fmt, va_list args) { - std::string msg = base::StringPrintV(fmt, args); - if (!msg.empty() && msg[msg.size() - 1] == '\n') - msg.erase(msg.end() - 1, msg.end()); - return msg; -} - -} // namespace - -void gestures_log(int verb, const char* fmt, ...) { - va_list args; - va_start(args, fmt); - if (verb <= GESTURES_LOG_ERROR) - LOG(ERROR) << "gestures: " << FormatLog(fmt, args); - else if (verb <= GESTURES_LOG_INFO) - VLOG(3) << "gestures: " << FormatLog(fmt, args); - va_end(args); -}
diff --git a/ui/events/ozone/evdev/libgestures_glue/gesture_logging.h b/ui/events/ozone/evdev/libgestures_glue/gesture_logging.h deleted file mode 100644 index a5f5435..0000000 --- a/ui/events/ozone/evdev/libgestures_glue/gesture_logging.h +++ /dev/null
@@ -1,15 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_EVENTS_OZONE_EVDEV_LIBGESTURES_GLUE_GESTURE_LOGGING_H_ -#define UI_EVENTS_OZONE_EVDEV_LIBGESTURES_GLUE_GESTURE_LOGGING_H_ - -// libgestures.so binds to this function for logging. -// TODO(spang): Fix libgestures to not require this. -extern "C" - __attribute__((visibility("default"))) void gestures_log(int verb, - const char* fmt, - ...); - -#endif // UI_EVENTS_OZONE_EVDEV_LIBGESTURES_GLUE_GESTURE_LOGGING_H_
diff --git a/ui/events/ozone/evdev/libgestures_glue/gesture_property_provider.cc b/ui/events/ozone/evdev/libgestures_glue/gesture_property_provider.cc deleted file mode 100644 index 1c2a1aa..0000000 --- a/ui/events/ozone/evdev/libgestures_glue/gesture_property_provider.cc +++ /dev/null
@@ -1,1525 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/events/ozone/evdev/libgestures_glue/gesture_property_provider.h" - -#include <gestures/gestures.h> -#include <libevdev/libevdev.h> - -#include <fnmatch.h> -#include <stdint.h> -#include <string.h> -#include <algorithm> -#include <iostream> -#include <vector> - -#include "base/basictypes.h" -#include "base/containers/hash_tables.h" -#include "base/files/file_enumerator.h" -#include "base/files/file_util.h" -#include "base/logging.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/string_split.h" -#include "base/strings/string_tokenizer.h" -#include "base/strings/string_util.h" -#include "base/strings/stringize_macros.h" -#include "base/strings/stringprintf.h" -#include "ui/events/ozone/evdev/libgestures_glue/gesture_interpreter_libevdev_cros.h" - -// Severity level for general info logging purpose. -#define GPROP_LOG DVLOG -#define INFO_SEVERITY 1 - -/* Implementation of GesturesProp declared in gestures.h - * - * libgestures requires that this be in the top level namespace. - * */ -class GesturesProp { - public: - typedef ui::GesturePropertyProvider::PropertyType PropertyType; - - GesturesProp(const std::string& name, - const PropertyType type, - const size_t count) - : name_(name), - type_(type), - count_(count), - get_(NULL), - set_(NULL), - handler_data_(NULL) {} - virtual ~GesturesProp() {} - - // Variant-ish interfaces for accessing the property value. Each type of - // property should override the corresponding interfaces for it. - virtual std::vector<int> GetIntValue() const { - NOTREACHED(); - return std::vector<int>(); - } - virtual bool SetIntValue(const std::vector<int>& value) { - NOTREACHED(); - return false; - } - virtual std::vector<int16_t> GetShortValue() const { - NOTREACHED(); - return std::vector<int16_t>(); - } - virtual bool SetShortValue(const std::vector<int16_t>& value) { - NOTREACHED(); - return false; - } - virtual std::vector<bool> GetBoolValue() const { - NOTREACHED(); - return std::vector<bool>(); - } - virtual bool SetBoolValue(const std::vector<bool>& value) { - NOTREACHED(); - return false; - } - virtual std::string GetStringValue() const { - NOTREACHED(); - return std::string(); - } - virtual bool SetStringValue(const std::string& value) { - NOTREACHED(); - return false; - } - virtual std::vector<double> GetDoubleValue() const { - NOTREACHED(); - return std::vector<double>(); - } - virtual bool SetDoubleValue(const std::vector<double>& value) { - NOTREACHED(); - return false; - } - - // Set property access handlers. - void SetHandlers(GesturesPropGetHandler get, - GesturesPropSetHandler set, - void* data) { - get_ = get; - set_ = set; - handler_data_ = data; - } - - // Accessors. - const std::string& name() const { return name_; } - PropertyType type() const { return type_; } - size_t count() const { return count_; } - virtual bool IsReadOnly() const = 0; - - protected: - void OnGet() const { - // We don't have the X server now so there is currently nothing to do when - // the get handler returns true. - // TODO(sheckylin): Re-visit this if we use handlers that modifies the - // property. - if (get_) - get_(handler_data_); - } - - void OnSet() const { - // Call the property set handler if available. - if (set_) - set_(handler_data_); - } - - private: - // For logging purpose. - friend std::ostream& operator<<(std::ostream& os, - const GesturesProp& property); - - // Interfaces for getting internal pointers and stuff. - virtual const char** GetStringWritebackPtr() const { - NOTREACHED(); - return NULL; - } - virtual bool IsAllocated() const { - NOTREACHED(); - return false; - } - - // Property name, type and number of elements. - std::string name_; - PropertyType type_; - size_t count_; - - // Handler function pointers and the data to be passed to them when the - // property is accessed. - GesturesPropGetHandler get_; - GesturesPropSetHandler set_; - void* handler_data_; - - DISALLOW_COPY_AND_ASSIGN(GesturesProp); -}; - -template <typename T> -class TypedGesturesProp : public GesturesProp { - public: - TypedGesturesProp(const std::string& name, - const PropertyType type, - const size_t count, - T* value) - : GesturesProp(name, type, count), - value_(value), - is_read_only_(false), - is_allocated_(false) { - Init(); - } - virtual ~TypedGesturesProp() override { - if (is_allocated_) - delete[] value_; - } - - // Accessors. - virtual bool IsReadOnly() const override { return is_read_only_; } - - protected: - // Functions for setting/getting numerical properties. - // - // These two functions calls the set/get handler and should only be used in - // Get*Value/Set*Value functions. - template <typename U> - std::vector<U> GetNumericalPropertyValue() const { - // Nothing should be modified so it is OK to call the get handler first. - OnGet(); - return this->template GetNumericalValue<U>(); - } - - template <typename U> - bool SetNumericalPropertyValue(const std::vector<U>& value) { - // Set the value only if not read-only and the vector size matches. - // - // As per the legacy guideline, all read-only properties (created with NULL) - // can't be modified. If we want to change this in the future, re-think - // about the different cases here (e.g., should we allow setting an array - // value of different size?). - if (is_read_only_ || value.size() != count()) - return false; - bool ret = this->template SetNumericalValue(value); - OnSet(); - return ret; - } - - // Initialize a numerical property's value. Note that a (numerical) default - // property's value is always stored in double. - void InitializeNumericalProperty(const T* init, - const GesturesProp* default_property) { - if (IsDefaultPropertyUsable(default_property)) { - GPROP_LOG(INFO_SEVERITY) << "Default property found. Using its value ..."; - this->template SetNumericalValue(default_property->GetDoubleValue()); - } else { - // To work with the interface exposed by the gesture lib, we have no - // choice but to trust that the init array has sufficient size. - std::vector<T> temp(init, init + count()); - this->template SetNumericalValue(temp); - } - } - - // Data pointer. - T* value_; - - // If the flag is on, it means the GesturesProp is created by passing a NULL - // data pointer to the creator functions. We define the property as a - // read-only one and that no value change will be allowed for it. Note that - // the flag is different from is_allocated in that StringProperty will always - // allocate no matter it is created with NULL or not. - bool is_read_only_; - - private: - // Initialize the object. - void Init() { - // If no external data pointer is passed, we have to create our own. - if (!value_) { - value_ = new T[GesturesProp::count()]; - is_read_only_ = true; - is_allocated_ = true; - } - } - - // Low-level functions for setting/getting numerical properties. - template <typename U> - std::vector<U> GetNumericalValue() const { - // We do type-casting because the numerical types may not totally match. - // For example, we store bool as GesturesPropBool to be compatible with the - // gesture library. Also, all parsed xorg-conf property values are stored - // as double because we can't identify their original type lexically. - // TODO(sheckylin): Handle value out-of-range (e.g., double to int). - std::vector<U> result(count()); - for (size_t i = 0; i < count(); ++i) - result[i] = static_cast<U>(value_[i]); - return result; - } - - template <typename U> - bool SetNumericalValue(const std::vector<U>& value) { - for (size_t i = 0; i < count(); ++i) - value_[i] = static_cast<T>(value[i]); - return true; - } - - // Check if a default property usable for (numerical) initialization. - bool IsDefaultPropertyUsable(const GesturesProp* default_property) const { - // We currently assumed that we won't specify any array property in the - // configuration files. The code needs to be updated if the assumption - // becomes invalid in the future. - return (count() == 1 && default_property && - default_property->type() != PropertyType::PT_STRING); - } - - // Accessors. - virtual bool IsAllocated() const override { return is_allocated_; } - - // If the flag is on, it means the memory that the data pointer points to is - // allocated here. We will need to free the memory by ourselves when the - // GesturesProp is destroyed. - bool is_allocated_; -}; - -class GesturesIntProp : public TypedGesturesProp<int> { - public: - GesturesIntProp(const std::string& name, - const size_t count, - int* value, - const int* init, - const GesturesProp* default_property) - : TypedGesturesProp<int>(name, PropertyType::PT_INT, count, value) { - InitializeNumericalProperty(init, default_property); - } - virtual std::vector<int> GetIntValue() const override { - return this->template GetNumericalPropertyValue<int>(); - } - virtual bool SetIntValue(const std::vector<int>& value) override { - return this->template SetNumericalPropertyValue(value); - } -}; - -class GesturesShortProp : public TypedGesturesProp<short> { - public: - GesturesShortProp(const std::string& name, - const size_t count, - short* value, - const short* init, - const GesturesProp* default_property) - : TypedGesturesProp<short>(name, PropertyType::PT_SHORT, count, value) { - InitializeNumericalProperty(init, default_property); - } - virtual std::vector<int16_t> GetShortValue() const override { - return this->template GetNumericalPropertyValue<int16_t>(); - } - virtual bool SetShortValue(const std::vector<int16_t>& value) override { - return this->template SetNumericalPropertyValue(value); - } -}; - -class GesturesBoolProp : public TypedGesturesProp<GesturesPropBool> { - public: - GesturesBoolProp(const std::string& name, - const size_t count, - GesturesPropBool* value, - const GesturesPropBool* init, - const GesturesProp* default_property) - : TypedGesturesProp<GesturesPropBool>(name, - PropertyType::PT_BOOL, - count, - value) { - InitializeNumericalProperty(init, default_property); - } - virtual std::vector<bool> GetBoolValue() const override { - return this->template GetNumericalPropertyValue<bool>(); - } - virtual bool SetBoolValue(const std::vector<bool>& value) override { - return this->template SetNumericalPropertyValue(value); - } -}; - -class GesturesDoubleProp : public TypedGesturesProp<double> { - public: - GesturesDoubleProp(const std::string& name, - const size_t count, - double* value, - const double* init, - const GesturesProp* default_property) - : TypedGesturesProp<double>(name, PropertyType::PT_REAL, count, value) { - InitializeNumericalProperty(init, default_property); - } - virtual std::vector<double> GetDoubleValue() const override { - return this->template GetNumericalPropertyValue<double>(); - } - virtual bool SetDoubleValue(const std::vector<double>& value) override { - return this->template SetNumericalPropertyValue(value); - } -}; - -class GesturesStringProp : public TypedGesturesProp<std::string> { - public: - // StringProperty's memory is always allocated on this side instead of - // externally in the gesture lib as the original one will be destroyed right - // after the constructor call (check the design of StringProperty). To do - // this, we call the TypedGesturesProp constructor with NULL pointer so that - // it always allocates. - GesturesStringProp(const std::string& name, - const char** value, - const char* init, - const GesturesProp* default_property) - : TypedGesturesProp<std::string>(name, PropertyType::PT_STRING, 1, NULL), - write_back_(NULL) { - InitializeStringProperty(value, init, default_property); - } - virtual std::string GetStringValue() const override { - OnGet(); - return *value_; - } - virtual bool SetStringValue(const std::string& value) override { - if (is_read_only_) - return false; - *value_ = value; - - // Write back the pointer in case it may change (e.g., string - // re-allocation). - if (write_back_) - *(write_back_) = value_->c_str(); - OnSet(); - return true; - } - - private: - // Initialize the object. - void InitializeStringProperty(const char** value, - const char* init, - const GesturesProp* default_property) { - // Initialize the property value similar to the numerical types. - if (IsDefaultPropertyUsable(default_property)) { - GPROP_LOG(INFO_SEVERITY) << "Default property found. Using its value ..."; - *value_ = default_property->GetStringValue(); - } else { - *value_ = init; - } - - // If the provided pointer is not NULL, replace its content - // (val_ of StringProperty) with the address of our allocated string. - // Note that we don't have to do this for the other data types as they will - // use the original data pointer if possible and it is unnecessary to do so - // if the pointer is NULL. - if (value) { - *value = value_->c_str(); - write_back_ = value; - // Set the read-only flag back to false. - is_read_only_ = false; - } - } - - // Re-write the function with different criteria as we want string properties - // now. - bool IsDefaultPropertyUsable(const GesturesProp* default_property) const { - return (default_property && - default_property->type() == PropertyType::PT_STRING); - } - - virtual const char** GetStringWritebackPtr() const override { - return write_back_; - } - - // In some cases, we don't directly use the data pointer provided by the - // creators due to its limitation and instead use our own types (e.g., in - // the case of string). We thus need to store the write back pointer so that - // we can update the value in the gesture lib if the property value gets - // changed. - const char** write_back_; -}; - -// Anonymous namespace for utility functions and internal constants. -namespace { - -// The path that we will look for conf files. -const char kConfigurationFilePath[] = "/etc/gesture"; - -// We support only match types that have already been used. One should change -// this if we start using new types in the future. Note that most unsupported -// match types are either useless in CrOS or inapplicable to the non-X -// environment. -const char* kSupportedMatchTypes[] = {"MatchProduct", - "MatchDevicePath", - "MatchUSBID", - "MatchIsPointer", - "MatchIsTouchpad", - "MatchIsTouchscreen"}; -const char* kUnsupportedMatchTypes[] = {"MatchVendor", - "MatchOS", - "MatchPnPID", - "MatchDriver", - "MatchTag", - "MatchLayout", - "MatchIsKeyboard", - "MatchIsJoystick", - "MatchIsTablet"}; - -// Special keywords for boolean values. -const char* kTrue[] = {"on", "true", "yes"}; -const char* kFalse[] = {"off", "false", "no"}; - -// Check if a device falls into one device type category. -bool IsDeviceOfType(const ui::GesturePropertyProvider::DevicePtr device, - const ui::GesturePropertyProvider::DeviceType type) { - EvdevClass evdev_class = device->info.evdev_class; - switch (type) { - case ui::GesturePropertyProvider::DT_MOUSE: - return (evdev_class == EvdevClassMouse || - evdev_class == EvdevClassMultitouchMouse); - break; - case ui::GesturePropertyProvider::DT_TOUCHPAD: - // Note that the behavior here is different from the inputcontrol script - // which actually returns touchscreen devices as well. - return (evdev_class == EvdevClassTouchpad); - break; - case ui::GesturePropertyProvider::DT_TOUCHSCREEN: - return (evdev_class == EvdevClassTouchscreen); - break; - case ui::GesturePropertyProvider::DT_MULTITOUCH: - return (evdev_class == EvdevClassTouchpad || - evdev_class == EvdevClassTouchscreen || - evdev_class == EvdevClassMultitouchMouse); - break; - case ui::GesturePropertyProvider::DT_MULTITOUCH_MOUSE: - return (evdev_class == EvdevClassMultitouchMouse); - break; - case ui::GesturePropertyProvider::DT_ALL: - return true; - break; - default: - NOTREACHED(); - break; - } - return false; -} - -// Trick to get the device path from a file descriptor. -std::string GetDeviceNodePath( - const ui::GesturePropertyProvider::DevicePtr device) { - std::string proc_symlink = "/proc/self/fd/" + base::IntToString(device->fd); - base::FilePath path; - if (!base::ReadSymbolicLink(base::FilePath(proc_symlink), &path)) - return std::string(); - return path.value(); -} - -// Check if a match criteria is currently implemented. Note that we didn't -// implemented all of them as some are inapplicable in the non-X world. -bool IsMatchTypeSupported(const std::string& match_type) { - for (size_t i = 0; i < arraysize(kSupportedMatchTypes); ++i) - if (match_type == kSupportedMatchTypes[i]) - return true; - for (size_t i = 0; i < arraysize(kUnsupportedMatchTypes); ++i) { - if (match_type == kUnsupportedMatchTypes[i]) { - LOG(ERROR) << "Unsupported gestures input class match type: " - << match_type; - return false; - } - } - return false; -} - -// Check if a match criteria is a device type one. -bool IsMatchDeviceType(const std::string& match_type) { - return StartsWithASCII(match_type, "MatchIs", true); -} - -// Parse a boolean value keyword (e.g., on/off, true/false). -int ParseBooleanKeyword(const std::string& value) { - for (size_t i = 0; i < arraysize(kTrue); ++i) - if (LowerCaseEqualsASCII(value, kTrue[i])) - return 1; - for (size_t i = 0; i < arraysize(kFalse); ++i) - if (LowerCaseEqualsASCII(value, kFalse[i])) - return -1; - return 0; -} - -// Log the value of an array property. -template <typename T> -void LogArrayProperty(std::ostream& os, const std::vector<T>& value) { - os << "("; - for (size_t i = 0; i < value.size(); ++i) { - if (i > 0) - os << ", "; - os << value[i]; - } - os << ")"; -} - -// Property type logging function. -std::ostream& operator<<(std::ostream& out, - const ui::GesturePropertyProvider::PropertyType type) { - std::string s; -#define TYPE_CASE(TYPE) \ - case (ui::GesturePropertyProvider::TYPE): \ - s = #TYPE; \ - break; - switch (type) { - TYPE_CASE(PT_INT); - TYPE_CASE(PT_SHORT); - TYPE_CASE(PT_BOOL); - TYPE_CASE(PT_STRING); - TYPE_CASE(PT_REAL); - default: - NOTREACHED(); - break; - } -#undef TYPE_CASE - return out << s; -} - -} // namespace - -// GesturesProp logging function. -std::ostream& operator<<(std::ostream& os, const GesturesProp& prop) { - const GesturesProp* property = ∝ - - // Output the property content. - os << "\"" << property->name() << "\", " << property->type() << ", " - << property->count() << ", (" << property->IsAllocated() << ", " - << property->IsReadOnly() << "), "; - - // Only the string property has the write back pointer. - if (property->type() == ui::GesturePropertyProvider::PT_STRING) - os << property->GetStringWritebackPtr(); - else - os << "NULL"; - - // Output the property values. - os << ", "; - switch (property->type()) { - case ui::GesturePropertyProvider::PT_INT: - LogArrayProperty(os, property->GetIntValue()); - break; - case ui::GesturePropertyProvider::PT_SHORT: - LogArrayProperty(os, property->GetShortValue()); - break; - case ui::GesturePropertyProvider::PT_BOOL: - LogArrayProperty(os, property->GetBoolValue()); - break; - case ui::GesturePropertyProvider::PT_STRING: - os << "\"" << property->GetStringValue() << "\""; - break; - case ui::GesturePropertyProvider::PT_REAL: - LogArrayProperty(os, property->GetDoubleValue()); - break; - default: - LOG(ERROR) << "Unknown gesture property type: " << property->type(); - NOTREACHED(); - break; - } - return os; -} - -namespace ui { -namespace internal { - -// Mapping table from a property name to its corresponding GesturesProp -// object pointer. -typedef base::hash_map<std::string, GesturesProp*> PropertiesMap; -typedef base::ScopedPtrHashMap<std::string, GesturesProp> ScopedPropertiesMap; - -// Struct holding properties of a device. -// -// Note that we can't define it in GesturePropertyProvider as a nested class -// because ScopedPtrHashMap will require us to expose the GestureProp's -// destructor so that it can instantiate the object. This is something we -// don't want to do. -struct GestureDevicePropertyData { - GestureDevicePropertyData() {} - - // Properties owned and being used by the device. - ScopedPropertiesMap properties; - - // Unowned default properties (owned by the configuration file). Their values - // will be applied when a property of the same name is created. These are - // usually only a small portion of all properties in use. - PropertiesMap default_properties; -}; - -// Base class for device match criterias in conf files. -// Check the xorg-conf spec for more detailed information. -class MatchCriteria { - public: - typedef ui::GesturePropertyProvider::DevicePtr DevicePtr; - explicit MatchCriteria(const std::string& arg); - virtual ~MatchCriteria() {} - virtual bool Match(const DevicePtr device) = 0; - - protected: - std::vector<std::string> args_; -}; - -// Match a device based on its evdev name string. -class MatchProduct : public MatchCriteria { - public: - explicit MatchProduct(const std::string& arg); - virtual ~MatchProduct() {} - virtual bool Match(const DevicePtr device); -}; - -// Math a device based on its device node path. -class MatchDevicePath : public MatchCriteria { - public: - explicit MatchDevicePath(const std::string& arg); - virtual ~MatchDevicePath() {} - virtual bool Match(const DevicePtr device); -}; - -// Math a USB device based on its USB vid and pid. -// Mostly used for external mice and touchpads. -class MatchUSBID : public MatchCriteria { - public: - explicit MatchUSBID(const std::string& arg); - virtual ~MatchUSBID() {} - virtual bool Match(const DevicePtr device); - - private: - bool IsValidPattern(const std::string& pattern); - std::vector<std::string> vid_patterns_; - std::vector<std::string> pid_patterns_; -}; - -// Generic base class for device type math criteria. -class MatchDeviceType : public MatchCriteria { - public: - explicit MatchDeviceType(const std::string& arg); - virtual ~MatchDeviceType() {} - virtual bool Match(const DevicePtr device) = 0; - - protected: - bool value_; - bool is_valid_; -}; - -// Check if a device is a pointer device. -class MatchIsPointer : public MatchDeviceType { - public: - explicit MatchIsPointer(const std::string& arg); - virtual ~MatchIsPointer() {} - virtual bool Match(const DevicePtr device); -}; - -// Check if a device is a touchpad. -class MatchIsTouchpad : public MatchDeviceType { - public: - explicit MatchIsTouchpad(const std::string& arg); - virtual ~MatchIsTouchpad() {} - virtual bool Match(const DevicePtr device); -}; - -// Check if a device is a touchscreen. -class MatchIsTouchscreen : public MatchDeviceType { - public: - explicit MatchIsTouchscreen(const std::string& arg); - virtual ~MatchIsTouchscreen() {} - virtual bool Match(const DevicePtr device); -}; - -// Struct for sections in xorg conf files. -struct ConfigurationSection { - typedef ui::GesturePropertyProvider::DevicePtr DevicePtr; - ConfigurationSection() {} - bool Match(const DevicePtr device); - std::string identifier; - ScopedVector<MatchCriteria> criterias; - ScopedVector<GesturesProp> properties; -}; - -MatchCriteria::MatchCriteria(const std::string& arg) { - // TODO(sheckylin): Should we trim all tokens here? - Tokenize(arg, "|", &args_); - if (args_.empty()) { - LOG(ERROR) << "Empty match pattern found, will evaluate to the default " - "value (true): \"" << arg << "\""; - } -} - -MatchProduct::MatchProduct(const std::string& arg) : MatchCriteria(arg) { -} - -bool MatchProduct::Match(const DevicePtr device) { - if (args_.empty()) - return true; - std::string name(device->info.name); - for (size_t i = 0; i < args_.size(); ++i) - if (name.find(args_[i]) != std::string::npos) - return true; - return false; -} - -MatchDevicePath::MatchDevicePath(const std::string& arg) : MatchCriteria(arg) { -} - -bool MatchDevicePath::Match(const DevicePtr device) { - if (args_.empty()) - return true; - - // Check if the device path matches any pattern. - std::string path = GetDeviceNodePath(device); - if (path.empty()) - return false; - for (size_t i = 0; i < args_.size(); ++i) - if (fnmatch(args_[i].c_str(), path.c_str(), FNM_NOESCAPE) == 0) - return true; - return false; -} - -MatchUSBID::MatchUSBID(const std::string& arg) : MatchCriteria(arg) { - // Check each pattern and split valid ones into vids and pids. - for (size_t i = 0; i < args_.size(); ++i) { - if (!IsValidPattern(args_[i])) { - LOG(ERROR) << "Invalid USB ID: " << args_[i]; - continue; - } - std::vector<std::string> tokens; - base::SplitString(args_[i], ':', &tokens); - vid_patterns_.push_back(base::StringToLowerASCII(tokens[0])); - pid_patterns_.push_back(base::StringToLowerASCII(tokens[1])); - } - if (vid_patterns_.empty()) { - LOG(ERROR) << "No valid USB ID pattern found, will be ignored: \"" << arg - << "\""; - } -} - -bool MatchUSBID::Match(const DevicePtr device) { - if (vid_patterns_.empty()) - return true; - std::string vid = base::StringPrintf("%04x", device->info.id.vendor); - std::string pid = base::StringPrintf("%04x", device->info.id.product); - for (size_t i = 0; i < vid_patterns_.size(); ++i) { - if (fnmatch(vid_patterns_[i].c_str(), vid.c_str(), FNM_NOESCAPE) == 0 && - fnmatch(pid_patterns_[i].c_str(), pid.c_str(), FNM_NOESCAPE) == 0) { - return true; - } - } - return false; -} - -bool MatchUSBID::IsValidPattern(const std::string& pattern) { - // Each USB id should be in the lsusb format, i.e., xxxx:xxxx. We choose to do - // a lazy check here: if the pattern contains wrong characters not in the hex - // number range, it won't be matched anyway. - int number_of_colons = 0; - size_t pos_of_colon = 0; - for (size_t i = 0; i < pattern.size(); ++i) - if (pattern[i] == ':') - ++number_of_colons, pos_of_colon = i; - return (number_of_colons == 1) && (pos_of_colon != 0) && - (pos_of_colon != pattern.size() - 1); -} - -MatchDeviceType::MatchDeviceType(const std::string& arg) - : MatchCriteria(arg), value_(true), is_valid_(false) { - // Default value of a match criteria is true. - if (args_.empty()) - args_.push_back("on"); - - // We care only about the first argument. - int value = ParseBooleanKeyword(args_[0]); - if (value) { - is_valid_ = true; - value_ = value > 0; - } - if (!is_valid_) { - LOG(ERROR) - << "No valid device class boolean keyword found, will be ignored: \"" - << arg << "\""; - } -} - -MatchIsPointer::MatchIsPointer(const std::string& arg) : MatchDeviceType(arg) { -} - -bool MatchIsPointer::Match(const DevicePtr device) { - if (!is_valid_) - return true; - return (value_ == (device->info.evdev_class == EvdevClassMouse || - device->info.evdev_class == EvdevClassMultitouchMouse)); -} - -MatchIsTouchpad::MatchIsTouchpad(const std::string& arg) - : MatchDeviceType(arg) { -} - -bool MatchIsTouchpad::Match(const DevicePtr device) { - if (!is_valid_) - return true; - return (value_ == (device->info.evdev_class == EvdevClassTouchpad)); -} - -MatchIsTouchscreen::MatchIsTouchscreen(const std::string& arg) - : MatchDeviceType(arg) { -} - -bool MatchIsTouchscreen::Match(const DevicePtr device) { - if (!is_valid_) - return true; - return (value_ == (device->info.evdev_class == EvdevClassTouchscreen)); -} - -bool ConfigurationSection::Match(DevicePtr device) { - for (size_t i = 0; i < criterias.size(); ++i) - if (!criterias[i]->Match(device)) - return false; - return true; -} - -} // namespace internal - -GesturePropertyProvider::GesturePropertyProvider() { - LoadDeviceConfigurations(); -} - -GesturePropertyProvider::~GesturePropertyProvider() { -} - -void GesturePropertyProvider::GetDeviceIdsByType( - const DeviceType type, - std::vector<DeviceId>* device_ids) { - device_ids->clear(); - DeviceMap::const_iterator it = device_map_.begin(); - for (; it != device_map_.end(); ++it) - if (IsDeviceOfType(it->second, type)) - device_ids->push_back(it->first); -} - -GesturesProp* GesturePropertyProvider::GetProperty(const DeviceId device_id, - const std::string& name) { - return FindProperty(device_id, name); -} - -void GesturePropertyProvider::RegisterDevice(const DeviceId id, - const DevicePtr device) { - DeviceMap::const_iterator it = device_map_.find(id); - if (it != device_map_.end()) - return; - - // Setup data-structures. - device_map_[id] = device; - device_data_map_.set(id, - scoped_ptr<internal::GestureDevicePropertyData>( - new internal::GestureDevicePropertyData)); - - // Gather default property values for the device from the parsed conf files. - SetupDefaultProperties(id, device); - return; -} - -void GesturePropertyProvider::UnregisterDevice(const DeviceId id) { - DeviceMap::const_iterator it = device_map_.find(id); - if (it == device_map_.end()) - return; - device_data_map_.erase(id); - device_map_.erase(it); -} - -void GesturePropertyProvider::AddProperty(const DeviceId device_id, - const std::string& name, - GesturesProp* property) { - // The look-up should never fail because ideally a property can only be - // created with GesturesPropCreate* functions from the gesture lib side. - // Therefore, we simply return on failure. - internal::GestureDevicePropertyData* device_data = - device_data_map_.get(device_id); - if (device_data) - device_data->properties.set(name, scoped_ptr<GesturesProp>(property)); -} - -void GesturePropertyProvider::DeleteProperty(const DeviceId device_id, - const std::string& name) { - internal::GestureDevicePropertyData* device_data = - device_data_map_.get(device_id); - if (device_data) - device_data->properties.erase(name); -} - -GesturesProp* GesturePropertyProvider::FindProperty(const DeviceId device_id, - const std::string& name) { - internal::GestureDevicePropertyData* device_data = - device_data_map_.get(device_id); - if (!device_data) - return NULL; - return device_data->properties.get(name); -} - -GesturesProp* GesturePropertyProvider::GetDefaultProperty( - const DeviceId device_id, - const std::string& name) { - internal::GestureDevicePropertyData* device_data = - device_data_map_.get(device_id); - if (!device_data) - return NULL; - internal::PropertiesMap::const_iterator ib = - device_data->default_properties.find(name); - if (ib == device_data->default_properties.end()) - return NULL; - return ib->second; -} - -void GesturePropertyProvider::LoadDeviceConfigurations() { - // Enumerate conf files and sort them lexicographically. - std::set<base::FilePath> files; - base::FileEnumerator file_enum(base::FilePath(kConfigurationFilePath), - false, - base::FileEnumerator::FILES, - "*.conf"); - for (base::FilePath path = file_enum.Next(); !path.empty(); - path = file_enum.Next()) { - files.insert(path); - } - GPROP_LOG(INFO_SEVERITY) << files.size() << " conf files were found"; - - // Parse conf files one-by-one. - for (std::set<base::FilePath>::iterator file_iter = files.begin(); - file_iter != files.end(); - ++file_iter) { - GPROP_LOG(INFO_SEVERITY) << "Parsing conf file: " << (*file_iter).value(); - std::string content; - if (!base::ReadFileToString(*file_iter, &content)) { - LOG(ERROR) << "Can't loading gestures conf file: " - << (*file_iter).value(); - continue; - } - ParseXorgConfFile(content); - } -} - -void GesturePropertyProvider::ParseXorgConfFile(const std::string& content) { - // To simplify the parsing work, we made some assumption about the conf file - // format which doesn't exist in the original xorg-conf spec. Most important - // ones are: - // 1. All keywords and names are now case-sensitive. Also, underscores are not - // ignored. - // 2. Each entry takes up one and exactly one line in the file. - // 3. No negation of the option value even if the option name is prefixed with - // "No" as it may cause problems for option names that does start with "No" - // (e.g., "Non-linearity"). - - // Break the content into sections, lines and then pieces. - // Sections are delimited by the "EndSection" keyword. - // Lines are delimited by "\n". - // Pieces are delimited by all white-spaces. - std::vector<std::string> sections; - base::SplitStringUsingSubstr(content, "EndSection", §ions); - for (size_t i = 0; i < sections.size(); ++i) { - // Create a new configuration section. - configurations_.push_back(new internal::ConfigurationSection()); - internal::ConfigurationSection* config = configurations_.back(); - - // Break the section into lines. - base::StringTokenizer lines(sections[i], "\n"); - bool is_input_class_section = true; - bool has_checked_section_type = false; - while (is_input_class_section && lines.GetNext()) { - // Parse the line w.r.t. the xorg-conf format. - std::string line(lines.token()); - - // Skip empty lines. - if (line.empty()) - continue; - - // Treat all whitespaces as delimiters. - base::StringTokenizer pieces(line, base::kWhitespaceASCII); - pieces.set_quote_chars("\""); - bool is_parsing = false; - bool has_error = false; - bool next_is_section_type = false; - bool next_is_option_name = false; - bool next_is_option_value = false; - bool next_is_match_criteria = false; - bool next_is_identifier = false; - std::string match_type, option_name; - while (pieces.GetNext()) { - std::string piece(pieces.token()); - - // Skip empty pieces. - if (piece.empty()) - continue; - - // See if we are currently parsing an entry or are still looking for - // one. - if (is_parsing) { - // Stop parsing the current line if the format is wrong. - if (piece.size() <= 2 || piece[0] != '\"' || - piece[piece.size() - 1] != '\"') { - LOG(ERROR) << "Error parsing line: " << lines.token(); - has_error = true; - if (next_is_section_type) - is_input_class_section = false; - break; - } - - // Parse the arguments. Note that we don't break even if a whitespace - // string is passed. It will just be handled in various ways based on - // the entry type. - std::string arg; - base::TrimWhitespaceASCII( - piece.substr(1, piece.size() - 2), base::TRIM_ALL, &arg); - if (next_is_section_type) { - // We only care about InputClass sections. - if (arg != "InputClass") { - has_error = true; - is_input_class_section = false; - } else { - GPROP_LOG(INFO_SEVERITY) << "New InputClass section found"; - has_checked_section_type = true; - } - break; - } else if (next_is_identifier) { - GPROP_LOG(INFO_SEVERITY) << "Identifier: " << arg; - config->identifier = arg; - next_is_identifier = false; - break; - } else if (next_is_option_name) { - // TODO(sheckylin): Support option "Ignore". - option_name = arg; - next_is_option_value = true; - next_is_option_name = false; - } else if (next_is_option_value) { - GesturesProp* property = CreateDefaultProperty(option_name, arg); - if (property) - config->properties.push_back(property); - next_is_option_value = false; - break; - } else if (next_is_match_criteria) { - // Skip all match types that are not supported. - if (IsMatchTypeSupported(match_type)) { - internal::MatchCriteria* criteria = - CreateMatchCriteria(match_type, arg); - if (criteria) - config->criterias.push_back(criteria); - } - next_is_match_criteria = false; - break; - } - } else { - // If the section type hasn't been decided yet, look for it. - // Otherwise, look for valid entries according to the spec. - if (has_checked_section_type) { - if (piece == "Driver") { - // TODO(sheckylin): Support "Driver" so that we can force a device - // not to use the gesture lib. - NOTIMPLEMENTED(); - break; - } else if (piece == "Identifier") { - is_parsing = true; - next_is_identifier = true; - continue; - } else if (piece == "Option") { - is_parsing = true; - next_is_option_name = true; - continue; - } else if (piece.size() > 5 && piece.compare(0, 5, "Match") == 0) { - match_type = piece; - is_parsing = true; - next_is_match_criteria = true; - continue; - } - } else if (piece == "Section") { - is_parsing = true; - next_is_section_type = true; - continue; - } - - // If none of the above is found, check if the current piece starts a - // comment. - if (piece.empty() || piece[0] != '#') { - LOG(ERROR) << "Error parsing line: " << lines.token(); - has_error = true; - } - break; - } - } - - // The value of a boolean option is skipped (default is true). - if (!has_error && (next_is_option_value || next_is_match_criteria)) { - if (next_is_option_value) { - GesturesProp* property = CreateDefaultProperty(option_name, "on"); - if (property) - config->properties.push_back(property); - } else if (IsMatchTypeSupported(match_type) && - IsMatchDeviceType(match_type)) { - internal::MatchCriteria* criteria = - CreateMatchCriteria(match_type, "on"); - if (criteria) - config->criterias.push_back(criteria); - } - } - } - - // Remove useless config sections. - if (!is_input_class_section || - (config->criterias.empty() && config->properties.empty())) { - configurations_.pop_back(); - } - } -} - -internal::MatchCriteria* GesturePropertyProvider::CreateMatchCriteria( - const std::string& match_type, - const std::string& arg) { - GPROP_LOG(INFO_SEVERITY) << "Creating match criteria: (" << match_type << ", " - << arg << ")"; - if (match_type == "MatchProduct") - return new internal::MatchProduct(arg); - if (match_type == "MatchDevicePath") - return new internal::MatchDevicePath(arg); - if (match_type == "MatchUSBID") - return new internal::MatchUSBID(arg); - if (match_type == "MatchIsPointer") - return new internal::MatchIsPointer(arg); - if (match_type == "MatchIsTouchpad") - return new internal::MatchIsTouchpad(arg); - if (match_type == "MatchIsTouchscreen") - return new internal::MatchIsTouchscreen(arg); - NOTREACHED(); - return NULL; -} - -GesturesProp* GesturePropertyProvider::CreateDefaultProperty( - const std::string& name, - const std::string& value) { - // Our parsing rule: - // 1. No hex or oct number is accepted. - // 2. All numbers will be stored as double. - // 3. Array elements can be separated by both white-spaces or commas. - // 4. A token is treated as numeric either if it is one of the special - // keywords for boolean values (on, true, yes, off, false, no) or if - // base::StringToDouble succeeds. - // 5. The property is treated as numeric if and only if all of its elements - // (if any) are numerics. Otherwise, it will be treated as a string. - // 6. A string property will be trimmed before storing its value. - GPROP_LOG(INFO_SEVERITY) << "Creating default property: (" << name << ", " - << value << ")"; - - // Parse elements one-by-one. - std::string delimiters(base::kWhitespaceASCII); - delimiters.append(","); - base::StringTokenizer tokens(value, delimiters); - bool is_all_numeric = true; - std::vector<double> numbers; - while (tokens.GetNext()) { - // Skip empty tokens. - std::string token(tokens.token()); - if (token.empty()) - continue; - - // Check if it is a boolean keyword. - int bool_result = ParseBooleanKeyword(token); - if (bool_result) { - numbers.push_back(bool_result > 0); - continue; - } - - // Check if it is a number. - double real_result; - bool success = base::StringToDouble(token, &real_result); - if (!success) { - is_all_numeric = false; - break; - } - numbers.push_back(real_result); - } - - // Create the GesturesProp. Array properties need to contain at least one - // number and may contain numbers only. - GesturesProp* property = NULL; - if (is_all_numeric && numbers.size()) { - property = new GesturesDoubleProp( - name, numbers.size(), NULL, numbers.data(), NULL); - } else { - property = new GesturesStringProp(name, NULL, value.c_str(), NULL); - } - - GPROP_LOG(INFO_SEVERITY) << "Prop: " << *property; - // The function will always succeed for now but it may change later if we - // specify some name or args as invalid. - return property; -} - -void GesturePropertyProvider::SetupDefaultProperties(const DeviceId device_id, - const DevicePtr device) { - GPROP_LOG(INFO_SEVERITY) << "Setting up default properties for (" << device - << ", " << device_id << ", " << device->info.name - << ")"; - - // Go through all parsed sections. - internal::PropertiesMap& property_map = - device_data_map_.get(device_id)->default_properties; - for (size_t i = 0; i < configurations_.size(); ++i) { - if (configurations_[i]->Match(device)) { - GPROP_LOG(INFO_SEVERITY) << "Conf section \"" - << configurations_[i]->identifier - << "\" is matched"; - for (size_t j = 0; j < configurations_[i]->properties.size(); j++) { - GesturesProp* property = configurations_[i]->properties[j]; - // We can't use insert here because a property may be set for several - // times along the way. - property_map[property->name()] = property; - } - } - } -} - -GesturesProp* GesturesPropFunctionsWrapper::CreateInt(void* device_data, - const char* name, - int* value, - size_t count, - const int* init) { - return CreateProperty<int, GesturesIntProp>( - device_data, name, value, count, init); -} - -GesturesProp* GesturesPropFunctionsWrapper::CreateShort(void* device_data, - const char* name, - short* value, - size_t count, - const short* init) { - return CreateProperty<short, GesturesShortProp>( - device_data, name, value, count, init); -} - -GesturesProp* GesturesPropFunctionsWrapper::CreateBool( - void* device_data, - const char* name, - GesturesPropBool* value, - size_t count, - const GesturesPropBool* init) { - return CreateProperty<GesturesPropBool, GesturesBoolProp>( - device_data, name, value, count, init); -} - -GesturesProp* GesturesPropFunctionsWrapper::CreateReal(void* device_data, - const char* name, - double* value, - size_t count, - const double* init) { - return CreateProperty<double, GesturesDoubleProp>( - device_data, name, value, count, init); -} - -GesturesProp* GesturesPropFunctionsWrapper::CreateString(void* device_data, - const char* name, - const char** value, - const char* init) { - GesturesProp* default_property = NULL; - if (!PreCreateProperty(device_data, name, &default_property)) - return NULL; - GesturesProp* property = - new GesturesStringProp(name, value, init, default_property); - - PostCreateProperty(device_data, name, property); - return property; -} - -void GesturesPropFunctionsWrapper::RegisterHandlers( - void* device_data, - GesturesProp* property, - void* handler_data, - GesturesPropGetHandler get, - GesturesPropSetHandler set) { - // Sanity checks - if (!device_data || !property) - return; - - property->SetHandlers(get, set, handler_data); -} - -void GesturesPropFunctionsWrapper::Free(void* device_data, - GesturesProp* property) { - if (!property) - return; - GesturePropertyProvider* provider = GetPropertyProvider(device_data); - - // No need to manually delete the prop pointer as it is implicitly handled - // with scoped ptr. - GPROP_LOG(3) << "Freeing Property: \"" << property->name() << "\""; - provider->DeleteProperty(GetDeviceId(device_data), property->name()); -} - -bool GesturesPropFunctionsWrapper::InitializeDeviceProperties( - void* device_data, - GestureDeviceProperties* properties) { - if (!device_data) - return false; - GesturePropertyProvider::DevicePtr device = GetDevicePointer(device_data); - - /* Create Device Properties */ - - // Read Only properties. - CreateString( - device_data, "Device Node", NULL, GetDeviceNodePath(device).c_str()); - short vid = static_cast<short>(device->info.id.vendor); - CreateShort(device_data, "Device Vendor ID", NULL, 1, &vid); - short pid = static_cast<short>(device->info.id.product); - CreateShort(device_data, "Device Product ID", NULL, 1, &pid); - - // Useable trackpad area. If not configured in .conf file, - // use x/y valuator min/max as reported by kernel driver. - CreateIntSingle(device_data, - "Active Area Left", - &properties->area_left, - Event_Get_Left(device)); - CreateIntSingle(device_data, - "Active Area Right", - &properties->area_right, - Event_Get_Right(device)); - CreateIntSingle(device_data, - "Active Area Top", - &properties->area_top, - Event_Get_Top(device)); - CreateIntSingle(device_data, - "Active Area Bottom", - &properties->area_bottom, - Event_Get_Bottom(device)); - - // Trackpad resolution (pixels/mm). If not configured in .conf file, - // use x/y resolution as reported by kernel driver. - CreateIntSingle(device_data, - "Vertical Resolution", - &properties->res_y, - Event_Get_Res_Y(device)); - CreateIntSingle(device_data, - "Horizontal Resolution", - &properties->res_x, - Event_Get_Res_X(device)); - - // Trackpad orientation minimum/maximum. If not configured in .conf file, - // use min/max as reported by kernel driver. - CreateIntSingle(device_data, - "Orientation Minimum", - &properties->orientation_minimum, - Event_Get_Orientation_Minimum(device)); - CreateIntSingle(device_data, - "Orientation Maximum", - &properties->orientation_maximum, - Event_Get_Orientation_Maximum(device)); - - // Log dump property. Will call Event_Dump_Debug_Log when its value is being - // set. - GesturesProp* dump_debug_log_prop = CreateBoolSingle( - device_data, "Dump Debug Log", &properties->dump_debug_log, false); - RegisterHandlers( - device_data, dump_debug_log_prop, device, NULL, Event_Dump_Debug_Log); - - // Whether to do the gesture recognition or just passing the multi-touch data - // to upper layers. - CreateBoolSingle(device_data, - "Raw Touch Passthrough", - &properties->raw_passthrough, - false); - return true; -} - -void GesturesPropFunctionsWrapper::UnregisterDevice(void* device_data) { - GesturePropertyProvider* provider = GetPropertyProvider(device_data); - provider->UnregisterDevice(GetDeviceId(device_data)); -} - -template <typename T, class PROPTYPE> -GesturesProp* GesturesPropFunctionsWrapper::CreateProperty(void* device_data, - const char* name, - T* value, - size_t count, - const T* init) { - // Create the property. Use the default property value if possible. - GesturesProp* default_property = NULL; - if (!PreCreateProperty(device_data, name, &default_property)) - return NULL; - GesturesProp* property = - new PROPTYPE(name, count, value, init, default_property); - - // Start tracking the property in the provider. - PostCreateProperty(device_data, name, property); - return property; -} - -bool GesturesPropFunctionsWrapper::PreCreateProperty( - void* device_data, - const char* name, - GesturesProp** default_property) { - GesturePropertyProvider* provider = GetPropertyProvider(device_data); - GesturePropertyProvider::DeviceId device_id = GetDeviceId(device_data); - - // Register the device in the property provider if not yet. - provider->RegisterDevice(device_id, GetDevicePointer(device_data)); - - // First, see if the GesturesProp already exists. - GPROP_LOG(3) << "Creating Property: \"" << name << "\""; - GesturesProp* property = provider->FindProperty(device_id, name); - - // If so, delete it as we can't reuse the data structure (newly-created - // property may have different data type and count, which are fixed upon - // creation via the template mechanism). - if (property) { - LOG(WARNING) << "Gesture property \"" << name - << "\" re-created. This shouldn't happen at the normal usage."; - Free(device_data, property); - } - - // Return the found default property from conf files (could be NULL). - *default_property = provider->GetDefaultProperty(device_id, name); - return true; -} - -void GesturesPropFunctionsWrapper::PostCreateProperty(void* device_data, - const char* name, - GesturesProp* property) { - // Add the property to the gesture property provider. The gesture property - // provider will own it from now on. - GesturePropertyProvider* provider = GetPropertyProvider(device_data); - provider->AddProperty(GetDeviceId(device_data), name, property); - - // Log the creation. - GPROP_LOG(INFO_SEVERITY) << "Created active prop: " << *property; -} - -GesturesProp* GesturesPropFunctionsWrapper::CreateIntSingle(void* device_data, - const char* name, - int* value, - int init) { - return CreateInt(device_data, name, value, 1, &init); -} - -GesturesProp* GesturesPropFunctionsWrapper::CreateBoolSingle( - void* device_data, - const char* name, - GesturesPropBool* value, - GesturesPropBool init) { - return CreateBool(device_data, name, value, 1, &init); -} - -GesturePropertyProvider* GesturesPropFunctionsWrapper::GetPropertyProvider( - void* device_data) { - return static_cast<GestureInterpreterLibevdevCros*>(device_data) - ->property_provider(); -} - -GesturePropertyProvider::DevicePtr -GesturesPropFunctionsWrapper::GetDevicePointer(void* device_data) { - return static_cast<GestureInterpreterLibevdevCros*>(device_data)->evdev(); -} - -GesturePropertyProvider::DeviceId GesturesPropFunctionsWrapper::GetDeviceId( - void* device_data) { - return static_cast<GestureInterpreterLibevdevCros*>(device_data)->id(); -} - -/* Global GesturesPropProvider - * - * Used by PropRegistry in GestureInterpreter to forward property value - * creations from there. - * */ -const GesturesPropProvider kGesturePropProvider = { - GesturesPropFunctionsWrapper::CreateInt, - GesturesPropFunctionsWrapper::CreateShort, - GesturesPropFunctionsWrapper::CreateBool, - GesturesPropFunctionsWrapper::CreateString, - GesturesPropFunctionsWrapper::CreateReal, - GesturesPropFunctionsWrapper::RegisterHandlers, - GesturesPropFunctionsWrapper::Free}; - -} // namespace ui
diff --git a/ui/events/ozone/evdev/libgestures_glue/gesture_property_provider.h b/ui/events/ozone/evdev/libgestures_glue/gesture_property_provider.h deleted file mode 100644 index dd7afb2..0000000 --- a/ui/events/ozone/evdev/libgestures_glue/gesture_property_provider.h +++ /dev/null
@@ -1,263 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_EVENTS_OZONE_EVDEV_LIBGESTURES_GLUE_GESTURE_PROPERTY_PROVIDER_H_ -#define UI_EVENTS_OZONE_EVDEV_LIBGESTURES_GLUE_GESTURE_PROPERTY_PROVIDER_H_ - -#include <gestures/gestures.h> -#include <libevdev/libevdev.h> - -#include <map> -#include <string> - -#include "base/containers/scoped_ptr_hash_map.h" -#include "base/memory/scoped_vector.h" -#include "ui/events/ozone/evdev/events_ozone_evdev_export.h" - -namespace ui { - -class GesturesPropFunctionsWrapper; -class GestureInterpreterLibevdevCros; - -// Not for public consumption, so we wrap it in namespace internal. -namespace internal { -struct GestureDevicePropertyData; -class MatchCriteria; -struct ConfigurationSection; -} - -// A struct holding device properties that are useful when interacting with -// the gestures lib. -struct GestureDeviceProperties { - int area_left; - int area_right; - int area_top; - int area_bottom; - int res_y; - int res_x; - int orientation_minimum; - int orientation_maximum; - GesturesPropBool raw_passthrough; - GesturesPropBool dump_debug_log; -}; - -// Provide the interface to access the CrOS gesture library properties. -// It maintains the property data for all input devices that runs with -// the gesture library. -// -// The class also parses the configuration files on the system to -// initialize the specified property values. The configuration files are -// currently in the xorg-conf format so that they can be shared with non-Ozone -// builds. -class EVENTS_OZONE_EVDEV_EXPORT GesturePropertyProvider { - public: - // Device types. - enum DeviceType { - DT_MOUSE, - DT_TOUCHPAD, - DT_TOUCHSCREEN, - DT_MULTITOUCH, - DT_MULTITOUCH_MOUSE, - DT_ALL, - }; - - // Property types. - enum PropertyType { - PT_INT, - PT_SHORT, - PT_BOOL, - PT_STRING, - PT_REAL, - }; - - // Pointer that leads to the device info. - typedef Evdev* DevicePtr; - - // The device ids are only maintained by EventFactoryEvdev to identify the - // input devices and are not to be confused with the Evdev input node id, for - // example. - typedef int DeviceId; - - GesturePropertyProvider(); - ~GesturePropertyProvider(); - - // Get a list of device ids that matches a device type. - void GetDeviceIdsByType(const DeviceType type, - std::vector<DeviceId>* device_ids); - - // Get the GesturesProp object. Returns NULL if not found. - // - // The user may use the object returned to set/get the property value in the - // gesture library's memory. Note that the values in preferences are not - // synced with the ones here in realtime - they are only applied from the - // preference side in a single way once appropriate (e.g., when the user - // clicked "OK"). - GesturesProp* GetProperty(const DeviceId device_id, const std::string& name); - - private: - friend class GesturesPropFunctionsWrapper; - - // Mapping table from a device id to its device pointer. - typedef std::map<DeviceId, DevicePtr> DeviceMap; - - // Mapping table from a device id to its property data. - // GestureDevicePropertyData contains both properties in use and default - // properties whose values will be applied upon the device attachment. - typedef base::ScopedPtrHashMap<DeviceId, internal::GestureDevicePropertyData> - ScopedDeviceDataMap; - - // Register a device. Setup data-structures and the device's default - // properties. - void RegisterDevice(const DeviceId id, const DevicePtr device); - - // Unregister a device. Remove all of its properties being tracked. - void UnregisterDevice(const DeviceId id); - - // Called by functions in GesturesPropFunctionsWrapper to manipulate - // properties. Note these functions do not new/delete the GesturesProp - // pointers. It is caller's responsibility to manage them. - void AddProperty(const DeviceId device_id, - const std::string& name, - GesturesProp* property); - void DeleteProperty(const DeviceId device_id, const std::string& name); - - // Check if a property exists for a device. Return if it is found. - GesturesProp* FindProperty(const DeviceId device_id, const std::string& name); - - // Get the default value of a property based on the configuration files. - GesturesProp* GetDefaultProperty(const DeviceId device_id, - const std::string& name); - - // The device configuration files are parsed and stored in the memory upon - // Chrome starts. The default property values are then applied to each device - // when it is attached/detected. - void LoadDeviceConfigurations(); - - // Parse a xorg-conf file. We ignore all sections other than InputClass. - // Check the xorg-conf spec for more infomation about its format. - void ParseXorgConfFile(const std::string& content); - - // Create a match criteria. - internal::MatchCriteria* CreateMatchCriteria(const std::string& match_type, - const std::string& arg); - - // Create a property that comes from the conf files. - GesturesProp* CreateDefaultProperty(const std::string& name, - const std::string& value); - - // Setup default property values for a newly found device. - void SetupDefaultProperties(const DeviceId device_id, const DevicePtr device); - - // Map from device ids to device pointers. - DeviceMap device_map_; - - // GestureDevicePropertyData indexed by their respective device ids. Owns the - // objects. - ScopedDeviceDataMap device_data_map_; - - // A vector of parsed sections in configuration files. Owns MatchCriterias, - // GesturesProps and ConfigurationSections in it. - ScopedVector<internal::ConfigurationSection> configurations_; - - DISALLOW_COPY_AND_ASSIGN(GesturePropertyProvider); -}; - -// Wrapper of GesturesProp related functions. We group them together so that we -// can friend them all at once. -class GesturesPropFunctionsWrapper { - public: - // Property provider interface implementation. - // - // These functions will create a GesturesProp object that can link back to the - // memory that holds the real value, which is often declared in the gesture - // lib. - static GesturesProp* CreateInt(void* device_data, - const char* name, - int* value, - size_t count, - const int* init); - static GesturesProp* CreateShort(void* device_data, - const char* name, - short* value, - size_t count, - const short* init); - static GesturesProp* CreateBool(void* device_data, - const char* name, - GesturesPropBool* value, - size_t count, - const GesturesPropBool* init); - - // String GestureProps needs special care due to the use of const char* in the - // gesture lib. Its argument list is also different from numeric properties'. - static GesturesProp* CreateString(void* device_data, - const char* name, - const char** value, - const char* init); - - static GesturesProp* CreateReal(void* device_data, - const char* name, - double* value, - size_t count, - const double* init); - - // Set the handlers to call when a property is accessed. - static void RegisterHandlers(void* device_data, - GesturesProp* property, - void* handler_data, - GesturesPropGetHandler get, - GesturesPropSetHandler set); - - // Free a property. - static void Free(void* device_data, GesturesProp* property); - - // Initialize hardware-related device properties which will be used in the - // gesture lib. - static bool InitializeDeviceProperties(void* device_data, - GestureDeviceProperties* properties); - - // Unregister device from the gesture property provider. - static void UnregisterDevice(void* device_data); - - private: - // Property helper functions. - // Core template function for creating GestureProps. Used by numerical types. - template <typename T, class PROPTYPE> - static GesturesProp* CreateProperty(void* device_data, - const char* name, - T* value, - size_t count, - const T* init); - - // Do things that should happen BEFORE we create the property. - static bool PreCreateProperty(void* device_data, - const char* name, - GesturesProp** default_property); - - // Do things that should happen AFTER we create the property. - static void PostCreateProperty(void* device_data, - const char* name, - GesturesProp* property); - - // Some other utility functions used in InitializeDeviceProperties. - static GesturesProp* CreateIntSingle(void* device_data, - const char* name, - int* value, - int init); - static GesturesProp* CreateBoolSingle(void* device_data, - const char* name, - GesturesPropBool* value, - GesturesPropBool init); - - // Routines to extract information from the GestureInterpreterLibevdevCros - // pointer. - static GesturePropertyProvider* GetPropertyProvider(void* device_data); - static GesturePropertyProvider::DevicePtr GetDevicePointer(void* device_data); - static GesturePropertyProvider::DeviceId GetDeviceId(void* device_data); -}; - -extern const GesturesPropProvider kGesturePropProvider; - -} // namspace ui - -#endif // UI_EVENTS_OZONE_EVDEV_LIBGESTURES_GLUE_GESTURE_PROPERTY_PROVIDER_H_
diff --git a/ui/events/ozone/evdev/libgestures_glue/gesture_timer_provider.cc b/ui/events/ozone/evdev/libgestures_glue/gesture_timer_provider.cc deleted file mode 100644 index 6aad161..0000000 --- a/ui/events/ozone/evdev/libgestures_glue/gesture_timer_provider.cc +++ /dev/null
@@ -1,72 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/events/ozone/evdev/libgestures_glue/gesture_timer_provider.h" - -#include <gestures/gestures.h> - -#include "base/timer/timer.h" - -// libgestures requires that this be in the top level namespace. -class GesturesTimer { - public: - GesturesTimer() : callback_(NULL), callback_data_(NULL) {} - ~GesturesTimer() {} - - void Set(stime_t delay, GesturesTimerCallback callback, void* callback_data) { - callback_ = callback; - callback_data_ = callback_data; - timer_.Start(FROM_HERE, - base::TimeDelta::FromMicroseconds( - delay * base::Time::kMicrosecondsPerSecond), - this, - &GesturesTimer::OnTimerExpired); - } - - void Cancel() { timer_.Stop(); } - - private: - void OnTimerExpired() { - struct timespec ts; - DCHECK(!clock_gettime(CLOCK_MONOTONIC, &ts)); - stime_t next_delay = callback_(StimeFromTimespec(&ts), callback_data_); - if (next_delay >= 0) { - timer_.Start(FROM_HERE, - base::TimeDelta::FromMicroseconds( - next_delay * base::Time::kMicrosecondsPerSecond), - this, - &GesturesTimer::OnTimerExpired); - } - } - - GesturesTimerCallback callback_; - void* callback_data_; - base::OneShotTimer<GesturesTimer> timer_; -}; - -namespace ui { - -namespace { - -GesturesTimer* GesturesTimerCreate(void* data) { return new GesturesTimer; } - -void GesturesTimerSet(void* data, - GesturesTimer* timer, - stime_t delay, - GesturesTimerCallback callback, - void* callback_data) { - timer->Set(delay, callback, callback_data); -} - -void GesturesTimerCancel(void* data, GesturesTimer* timer) { timer->Cancel(); } - -void GesturesTimerFree(void* data, GesturesTimer* timer) { delete timer; } - -} // namespace - -const GesturesTimerProvider kGestureTimerProvider = { - GesturesTimerCreate, GesturesTimerSet, GesturesTimerCancel, - GesturesTimerFree}; - -} // namespace ui
diff --git a/ui/events/ozone/evdev/libgestures_glue/gesture_timer_provider.h b/ui/events/ozone/evdev/libgestures_glue/gesture_timer_provider.h deleted file mode 100644 index edc20ba..0000000 --- a/ui/events/ozone/evdev/libgestures_glue/gesture_timer_provider.h +++ /dev/null
@@ -1,16 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_EVENTS_OZONE_EVDEV_LIBGESTURES_GLUE_GESTURE_TIMER_PROVIDER_H_ -#define UI_EVENTS_OZONE_EVDEV_LIBGESTURES_GLUE_GESTURE_TIMER_PROVIDER_H_ - -#include <gestures/gestures.h> - -namespace ui { - -extern const GesturesTimerProvider kGestureTimerProvider; - -} // namspace ui - -#endif // UI_EVENTS_OZONE_EVDEV_LIBGESTURES_GLUE_GESTURE_TIMER_PROVIDER_H_
diff --git a/ui/events/ozone/evdev/touch_event_converter_evdev.cc b/ui/events/ozone/evdev/touch_event_converter_evdev.cc deleted file mode 100644 index c3fc7e2..0000000 --- a/ui/events/ozone/evdev/touch_event_converter_evdev.cc +++ /dev/null
@@ -1,302 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/events/ozone/evdev/touch_event_converter_evdev.h" - -#include <errno.h> -#include <fcntl.h> -#include <linux/input.h> -#include <poll.h> -#include <stdio.h> -#include <unistd.h> - -#include <cmath> -#include <limits> - -#include "base/bind.h" -#include "base/callback.h" -#include "base/command_line.h" -#include "base/logging.h" -#include "base/memory/scoped_vector.h" -#include "base/message_loop/message_loop.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/string_util.h" -#include "base/strings/stringprintf.h" -#include "ui/events/event.h" -#include "ui/events/event_constants.h" -#include "ui/events/event_switches.h" -#include "ui/gfx/screen.h" - -namespace { - -struct TouchCalibration { - int bezel_left; - int bezel_right; - int bezel_top; - int bezel_bottom; -}; - -void GetTouchCalibration(TouchCalibration* cal) { - std::vector<std::string> parts; - if (Tokenize(CommandLine::ForCurrentProcess()->GetSwitchValueASCII( - switches::kTouchCalibration), - ",", - &parts) >= 4) { - if (!base::StringToInt(parts[0], &cal->bezel_left)) - DLOG(ERROR) << "Incorrect left border calibration value passed."; - if (!base::StringToInt(parts[1], &cal->bezel_right)) - DLOG(ERROR) << "Incorrect right border calibration value passed."; - if (!base::StringToInt(parts[2], &cal->bezel_top)) - DLOG(ERROR) << "Incorrect top border calibration value passed."; - if (!base::StringToInt(parts[3], &cal->bezel_bottom)) - DLOG(ERROR) << "Incorrect bottom border calibration value passed."; - } -} - -float TuxelsToPixels(float val, - float min_tuxels, - float num_tuxels, - float min_pixels, - float num_pixels) { - // Map [min_tuxels, min_tuxels + num_tuxels) to - // [min_pixels, min_pixels + num_pixels). - return min_pixels + (val - min_tuxels) * num_pixels / num_tuxels; -} - -float TuxelToPixelSize(float val, float num_tuxels, float num_pixels) { - return val * num_pixels / num_tuxels; -} - -} // namespace - -namespace ui { - -TouchEventConverterEvdev::TouchEventConverterEvdev( - int fd, - base::FilePath path, - int id, - const EventDeviceInfo& info, - const EventDispatchCallback& callback) - : EventConverterEvdev(fd, path, id), - callback_(callback), - syn_dropped_(false), - is_type_a_(false), - current_slot_(0) { - Init(info); -} - -TouchEventConverterEvdev::~TouchEventConverterEvdev() { - Stop(); - close(fd_); -} - -void TouchEventConverterEvdev::Init(const EventDeviceInfo& info) { - gfx::Screen* screen = gfx::Screen::GetScreenByType(gfx::SCREEN_TYPE_NATIVE); - if (!screen) - return; // No scaling. - gfx::Display display = screen->GetPrimaryDisplay(); - gfx::Size size = display.GetSizeInPixel(); - - pressure_min_ = info.GetAbsMinimum(ABS_MT_PRESSURE); - pressure_max_ = info.GetAbsMaximum(ABS_MT_PRESSURE); - x_min_tuxels_ = info.GetAbsMinimum(ABS_MT_POSITION_X); - x_num_tuxels_ = info.GetAbsMaximum(ABS_MT_POSITION_X) - x_min_tuxels_ + 1; - y_min_tuxels_ = info.GetAbsMinimum(ABS_MT_POSITION_Y); - y_num_tuxels_ = info.GetAbsMaximum(ABS_MT_POSITION_Y) - y_min_tuxels_ + 1; - native_size_ = gfx::Size(x_num_tuxels_, y_num_tuxels_); - - // Map coordinates onto screen. - x_min_pixels_ = 0; - y_min_pixels_ = 0; - x_num_pixels_ = size.width(); - y_num_pixels_ = size.height(); - - VLOG(1) << "mapping touch coordinates to screen coordinates: " - << base::StringPrintf("%dx%d", size.width(), size.height()); - - // Apply --touch-calibration. - TouchCalibration cal = {}; - GetTouchCalibration(&cal); - x_min_tuxels_ += cal.bezel_left; - x_num_tuxels_ -= cal.bezel_left + cal.bezel_right; - y_min_tuxels_ += cal.bezel_top; - y_num_tuxels_ -= cal.bezel_top + cal.bezel_bottom; - - VLOG(1) << "applying touch calibration: " - << base::StringPrintf("[%d, %d, %d, %d]", - cal.bezel_left, - cal.bezel_right, - cal.bezel_top, - cal.bezel_bottom); -} - -bool TouchEventConverterEvdev::Reinitialize() { - EventDeviceInfo info; - if (info.Initialize(fd_)) { - Init(info); - return true; - } - return false; -} - -bool TouchEventConverterEvdev::HasTouchscreen() const { - return true; -} - -gfx::Size TouchEventConverterEvdev::GetTouchscreenSize() const { - return native_size_; -} - -void TouchEventConverterEvdev::OnFileCanReadWithoutBlocking(int fd) { - input_event inputs[MAX_FINGERS * 6 + 1]; - ssize_t read_size = read(fd, inputs, sizeof(inputs)); - if (read_size < 0) { - if (errno == EINTR || errno == EAGAIN) - return; - if (errno != ENODEV) - PLOG(ERROR) << "error reading device " << path_.value(); - Stop(); - return; - } - - for (unsigned i = 0; i < read_size / sizeof(*inputs); i++) { - ProcessInputEvent(inputs[i]); - } -} - -void TouchEventConverterEvdev::ProcessInputEvent(const input_event& input) { - if (input.type == EV_SYN) { - ProcessSyn(input); - } else if(syn_dropped_) { - // Do nothing. This branch indicates we have lost sync with the driver. - } else if (input.type == EV_ABS) { - if (current_slot_ >= MAX_FINGERS) { - LOG(ERROR) << "too many touch events: " << current_slot_; - return; - } - ProcessAbs(input); - } else if (input.type == EV_KEY) { - switch (input.code) { - case BTN_TOUCH: - break; - default: - NOTIMPLEMENTED() << "invalid code for EV_KEY: " << input.code; - } - } else { - NOTIMPLEMENTED() << "invalid type: " << input.type; - } -} - -void TouchEventConverterEvdev::ProcessAbs(const input_event& input) { - switch (input.code) { - case ABS_MT_TOUCH_MAJOR: - altered_slots_.set(current_slot_); - // TODO(spang): If we have all of major, minor, and orientation, - // we can scale the ellipse correctly. However on the Pixel we get - // neither minor nor orientation, so this is all we can do. - events_[current_slot_].radius_x_ = - TuxelToPixelSize(input.value, x_num_tuxels_, x_num_pixels_) / 2.0f; - break; - case ABS_MT_TOUCH_MINOR: - altered_slots_.set(current_slot_); - events_[current_slot_].radius_y_ = - TuxelToPixelSize(input.value, y_num_tuxels_, y_num_pixels_) / 2.0f; - break; - case ABS_MT_POSITION_X: - altered_slots_.set(current_slot_); - events_[current_slot_].x_ = TuxelsToPixels(input.value, - x_min_tuxels_, - x_num_tuxels_, - x_min_pixels_, - x_num_pixels_); - break; - case ABS_MT_POSITION_Y: - altered_slots_.set(current_slot_); - events_[current_slot_].y_ = TuxelsToPixels(input.value, - y_min_tuxels_, - y_num_tuxels_, - y_min_pixels_, - y_num_pixels_); - break; - case ABS_MT_TRACKING_ID: - altered_slots_.set(current_slot_); - if (input.value < 0) { - events_[current_slot_].type_ = ET_TOUCH_RELEASED; - } else { - events_[current_slot_].finger_ = input.value; - events_[current_slot_].type_ = ET_TOUCH_PRESSED; - } - break; - case ABS_MT_PRESSURE: - altered_slots_.set(current_slot_); - events_[current_slot_].pressure_ = input.value - pressure_min_; - events_[current_slot_].pressure_ /= pressure_max_ - pressure_min_; - break; - case ABS_MT_SLOT: - current_slot_ = input.value; - altered_slots_.set(current_slot_); - break; - default: - DVLOG(5) << "unhandled code for EV_ABS: " << input.code; - } -} - -void TouchEventConverterEvdev::ProcessSyn(const input_event& input) { - switch (input.code) { - case SYN_REPORT: - if (syn_dropped_) { - // Have to re-initialize. - if (Reinitialize()) { - syn_dropped_ = false; - altered_slots_.reset(); - } else { - LOG(ERROR) << "failed to re-initialize device info"; - } - } else { - ReportEvents(base::TimeDelta::FromMicroseconds( - input.time.tv_sec * 1000000 + input.time.tv_usec)); - } - if (is_type_a_) - current_slot_ = 0; - break; - case SYN_MT_REPORT: - // For type A devices, we just get a stream of all current contacts, - // in some arbitrary order. - events_[current_slot_++].type_ = ET_TOUCH_PRESSED; - is_type_a_ = true; - break; - case SYN_DROPPED: - // Some buffer has overrun. We ignore all events up to and - // including the next SYN_REPORT. - syn_dropped_ = true; - break; - default: - NOTIMPLEMENTED() << "invalid code for EV_SYN: " << input.code; - } -} - -void TouchEventConverterEvdev::ReportEvents(base::TimeDelta delta) { - for (int i = 0; i < MAX_FINGERS; i++) { - if (altered_slots_[i]) { - // TODO(rikroege): Support elliptical finger regions. - callback_.Run(make_scoped_ptr( - new TouchEvent(events_[i].type_, - gfx::PointF(events_[i].x_, events_[i].y_), - /* flags */ 0, - /* touch_id */ i, - delta, - /* radius_x */ events_[i].radius_x_, - /* radius_y */ events_[i].radius_y_, - /* angle */ 0., - events_[i].pressure_))); - - // Subsequent events for this finger will be touch-move until it - // is released. - events_[i].type_ = ET_TOUCH_MOVED; - } - } - altered_slots_.reset(); -} - -} // namespace ui
diff --git a/ui/events/ozone/evdev/touch_event_converter_evdev.h b/ui/events/ozone/evdev/touch_event_converter_evdev.h deleted file mode 100644 index 83aa13a..0000000 --- a/ui/events/ozone/evdev/touch_event_converter_evdev.h +++ /dev/null
@@ -1,115 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_EVENTS_OZONE_EVDEV_TOUCH_EVENT_CONVERTER_EVDEV_H_ -#define UI_EVENTS_OZONE_EVDEV_TOUCH_EVENT_CONVERTER_EVDEV_H_ - -#include <bitset> - -#include "base/compiler_specific.h" -#include "base/files/file_path.h" -#include "base/message_loop/message_pump_libevent.h" -#include "ui/events/event_constants.h" -#include "ui/events/ozone/evdev/event_converter_evdev.h" -#include "ui/events/ozone/evdev/event_device_info.h" -#include "ui/events/ozone/evdev/events_ozone_evdev_export.h" - -namespace ui { - -class TouchEvent; - -class EVENTS_OZONE_EVDEV_EXPORT TouchEventConverterEvdev - : public EventConverterEvdev { - public: - enum { - MAX_FINGERS = 11 - }; - TouchEventConverterEvdev(int fd, - base::FilePath path, - int id, - const EventDeviceInfo& info, - const EventDispatchCallback& dispatch); - virtual ~TouchEventConverterEvdev(); - - // EventConverterEvdev: - virtual bool HasTouchscreen() const override; - virtual gfx::Size GetTouchscreenSize() const override; - - private: - friend class MockTouchEventConverterEvdev; - - // Unsafe part of initialization. - void Init(const EventDeviceInfo& info); - - // Overidden from base::MessagePumpLibevent::Watcher. - virtual void OnFileCanReadWithoutBlocking(int fd) override; - - virtual bool Reinitialize(); - - void ProcessInputEvent(const input_event& input); - void ProcessAbs(const input_event& input); - void ProcessSyn(const input_event& input); - - void ReportEvents(base::TimeDelta delta); - - // Callback for dispatching events. - EventDispatchCallback callback_; - - // Set if we have seen a SYN_DROPPED and not yet re-synced with the device. - bool syn_dropped_; - - // Set if this is a type A device (uses SYN_MT_REPORT). - bool is_type_a_; - - // Pressure values. - int pressure_min_; - int pressure_max_; // Used to normalize pressure values. - - // Input range for x-axis. - float x_min_tuxels_; - float x_num_tuxels_; - - // Input range for y-axis. - float y_min_tuxels_; - float y_num_tuxels_; - - // Output range for x-axis. - float x_min_pixels_; - float x_num_pixels_; - - // Output range for y-axis. - float y_min_pixels_; - float y_num_pixels_; - - // Size of the touchscreen as reported by the driver. - gfx::Size native_size_; - - // Touch point currently being updated from the /dev/input/event* stream. - int current_slot_; - - // Bit field tracking which in-progress touch points have been modified - // without a syn event. - std::bitset<MAX_FINGERS> altered_slots_; - - struct InProgressEvents { - float x_; - float y_; - int id_; // Device reported "unique" touch point id; -1 means not active - int finger_; // "Finger" id starting from 0; -1 means not active - - EventType type_; - float radius_x_; - float radius_y_; - float pressure_; - }; - - // In-progress touch points. - InProgressEvents events_[MAX_FINGERS]; - - DISALLOW_COPY_AND_ASSIGN(TouchEventConverterEvdev); -}; - -} // namespace ui - -#endif // UI_EVENTS_OZONE_EVDEV_TOUCH_EVENT_CONVERTER_EVDEV_H_
diff --git a/ui/events/ozone/evdev/touch_event_converter_evdev_unittest.cc b/ui/events/ozone/evdev/touch_event_converter_evdev_unittest.cc deleted file mode 100644 index 6a8494b..0000000 --- a/ui/events/ozone/evdev/touch_event_converter_evdev_unittest.cc +++ /dev/null
@@ -1,533 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <errno.h> -#include <fcntl.h> -#include <linux/input.h> -#include <unistd.h> - -#include <vector> - -#include "base/bind.h" -#include "base/memory/scoped_ptr.h" -#include "base/memory/scoped_vector.h" -#include "base/posix/eintr_wrapper.h" -#include "base/run_loop.h" -#include "base/time/time.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/events/event.h" -#include "ui/events/ozone/evdev/touch_event_converter_evdev.h" -#include "ui/events/platform/platform_event_dispatcher.h" -#include "ui/events/platform/platform_event_source.h" - -namespace { - -static int SetNonBlocking(int fd) { - int flags = fcntl(fd, F_GETFL, 0); - if (flags == -1) - flags = 0; - return fcntl(fd, F_SETFL, flags | O_NONBLOCK); -} - -const char kTestDevicePath[] = "/dev/input/test-device"; - -} // namespace - -namespace ui { - -class MockTouchEventConverterEvdev : public TouchEventConverterEvdev { - public: - MockTouchEventConverterEvdev(int fd, base::FilePath path); - virtual ~MockTouchEventConverterEvdev() {}; - - void ConfigureReadMock(struct input_event* queue, - long read_this_many, - long queue_index); - - unsigned size() { return dispatched_events_.size(); } - TouchEvent* event(unsigned index) { - DCHECK_GT(dispatched_events_.size(), index); - Event* ev = dispatched_events_[index]; - DCHECK(ev->IsTouchEvent()); - return static_cast<TouchEvent*>(ev); - } - - // Actually dispatch the event reader code. - void ReadNow() { - OnFileCanReadWithoutBlocking(read_pipe_); - base::RunLoop().RunUntilIdle(); - } - - void DispatchCallback(scoped_ptr<Event> event) { - dispatched_events_.push_back(event.release()); - } - - virtual bool Reinitialize() override { return true; } - - private: - int read_pipe_; - int write_pipe_; - - ScopedVector<Event> dispatched_events_; - - DISALLOW_COPY_AND_ASSIGN(MockTouchEventConverterEvdev); -}; - -MockTouchEventConverterEvdev::MockTouchEventConverterEvdev(int fd, - base::FilePath path) - : TouchEventConverterEvdev( - fd, - path, - 1, - EventDeviceInfo(), - base::Bind(&MockTouchEventConverterEvdev::DispatchCallback, - base::Unretained(this))) { - pressure_min_ = 30; - pressure_max_ = 60; - - // TODO(rjkroege): Check test axes. - x_min_pixels_ = x_min_tuxels_ = 0; - x_num_pixels_ = x_num_tuxels_ = std::numeric_limits<int>::max(); - y_min_pixels_ = y_min_tuxels_ = 0; - y_num_pixels_ = y_num_tuxels_ = std::numeric_limits<int>::max(); - - int fds[2]; - - if (pipe(fds)) - PLOG(FATAL) << "failed pipe"; - - DCHECK(SetNonBlocking(fds[0]) == 0) - << "SetNonBlocking for pipe fd[0] failed, errno: " << errno; - DCHECK(SetNonBlocking(fds[1]) == 0) - << "SetNonBlocking for pipe fd[0] failed, errno: " << errno; - read_pipe_ = fds[0]; - write_pipe_ = fds[1]; -} - -void MockTouchEventConverterEvdev::ConfigureReadMock(struct input_event* queue, - long read_this_many, - long queue_index) { - int nwrite = HANDLE_EINTR(write(write_pipe_, - queue + queue_index, - sizeof(struct input_event) * read_this_many)); - DCHECK(nwrite == - static_cast<int>(sizeof(struct input_event) * read_this_many)) - << "write() failed, errno: " << errno; -} - -} // namespace ui - -// Test fixture. -class TouchEventConverterEvdevTest : public testing::Test { - public: - TouchEventConverterEvdevTest() {} - - // Overridden from testing::Test: - virtual void SetUp() override { - // Set up pipe to satisfy message pump (unused). - int evdev_io[2]; - if (pipe(evdev_io)) - PLOG(FATAL) << "failed pipe"; - events_in_ = evdev_io[0]; - events_out_ = evdev_io[1]; - - loop_ = new base::MessageLoopForUI; - device_ = new ui::MockTouchEventConverterEvdev( - events_in_, base::FilePath(kTestDevicePath)); - } - - virtual void TearDown() override { - delete device_; - delete loop_; - } - - ui::MockTouchEventConverterEvdev* device() { return device_; } - - private: - base::MessageLoop* loop_; - ui::MockTouchEventConverterEvdev* device_; - - int events_out_; - int events_in_; - - DISALLOW_COPY_AND_ASSIGN(TouchEventConverterEvdevTest); -}; - -// TODO(rjkroege): Test for valid handling of time stamps. -TEST_F(TouchEventConverterEvdevTest, TouchDown) { - ui::MockTouchEventConverterEvdev* dev = device(); - - struct input_event mock_kernel_queue[] = { - {{0, 0}, EV_ABS, ABS_MT_TRACKING_ID, 684}, - {{0, 0}, EV_ABS, ABS_MT_TOUCH_MAJOR, 3}, - {{0, 0}, EV_ABS, ABS_MT_PRESSURE, 45}, - {{0, 0}, EV_ABS, ABS_MT_POSITION_X, 42}, - {{0, 0}, EV_ABS, ABS_MT_POSITION_Y, 51}, {{0, 0}, EV_SYN, SYN_REPORT, 0} - }; - - dev->ConfigureReadMock(mock_kernel_queue, 1, 0); - dev->ReadNow(); - EXPECT_EQ(0u, dev->size()); - - dev->ConfigureReadMock(mock_kernel_queue, 2, 1); - dev->ReadNow(); - EXPECT_EQ(0u, dev->size()); - - dev->ConfigureReadMock(mock_kernel_queue, 3, 3); - dev->ReadNow(); - EXPECT_EQ(1u, dev->size()); - - ui::TouchEvent* event = dev->event(0); - EXPECT_FALSE(event == NULL); - - EXPECT_EQ(ui::ET_TOUCH_PRESSED, event->type()); - EXPECT_EQ(base::TimeDelta::FromMicroseconds(0), event->time_stamp()); - EXPECT_EQ(42, event->x()); - EXPECT_EQ(51, event->y()); - EXPECT_EQ(0, event->touch_id()); - EXPECT_FLOAT_EQ(1.5f, event->radius_x()); - EXPECT_FLOAT_EQ(.5f, event->force()); - EXPECT_FLOAT_EQ(0.f, event->rotation_angle()); -} - -TEST_F(TouchEventConverterEvdevTest, NoEvents) { - ui::MockTouchEventConverterEvdev* dev = device(); - dev->ConfigureReadMock(NULL, 0, 0); - EXPECT_EQ(0u, dev->size()); -} - -TEST_F(TouchEventConverterEvdevTest, TouchMove) { - ui::MockTouchEventConverterEvdev* dev = device(); - - struct input_event mock_kernel_queue_press[] = { - {{0, 0}, EV_ABS, ABS_MT_TRACKING_ID, 684}, - {{0, 0}, EV_ABS, ABS_MT_TOUCH_MAJOR, 3}, - {{0, 0}, EV_ABS, ABS_MT_PRESSURE, 45}, - {{0, 0}, EV_ABS, ABS_MT_POSITION_X, 42}, - {{0, 0}, EV_ABS, ABS_MT_POSITION_Y, 51}, {{0, 0}, EV_SYN, SYN_REPORT, 0} - }; - - struct input_event mock_kernel_queue_move1[] = { - {{0, 0}, EV_ABS, ABS_MT_PRESSURE, 50}, - {{0, 0}, EV_ABS, ABS_MT_POSITION_X, 42}, - {{0, 0}, EV_ABS, ABS_MT_POSITION_Y, 43}, {{0, 0}, EV_SYN, SYN_REPORT, 0} - }; - - struct input_event mock_kernel_queue_move2[] = { - {{0, 0}, EV_ABS, ABS_MT_POSITION_Y, 42}, {{0, 0}, EV_SYN, SYN_REPORT, 0} - }; - - // Setup and discard a press. - dev->ConfigureReadMock(mock_kernel_queue_press, 6, 0); - dev->ReadNow(); - EXPECT_EQ(1u, dev->size()); - - dev->ConfigureReadMock(mock_kernel_queue_move1, 4, 0); - dev->ReadNow(); - EXPECT_EQ(2u, dev->size()); - ui::TouchEvent* event = dev->event(1); - EXPECT_FALSE(event == NULL); - - EXPECT_EQ(ui::ET_TOUCH_MOVED, event->type()); - EXPECT_EQ(base::TimeDelta::FromMicroseconds(0), event->time_stamp()); - EXPECT_EQ(42, event->x()); - EXPECT_EQ(43, event->y()); - EXPECT_EQ(0, event->touch_id()); - EXPECT_FLOAT_EQ(2.f / 3.f, event->force()); - EXPECT_FLOAT_EQ(0.f, event->rotation_angle()); - - dev->ConfigureReadMock(mock_kernel_queue_move2, 2, 0); - dev->ReadNow(); - EXPECT_EQ(3u, dev->size()); - event = dev->event(2); - EXPECT_FALSE(event == NULL); - - EXPECT_EQ(ui::ET_TOUCH_MOVED, event->type()); - EXPECT_EQ(base::TimeDelta::FromMicroseconds(0), event->time_stamp()); - EXPECT_EQ(42, event->x()); - EXPECT_EQ(42, event->y()); - EXPECT_EQ(0, event->touch_id()); - EXPECT_FLOAT_EQ(2.f / 3.f, event->force()); - EXPECT_FLOAT_EQ(0.f, event->rotation_angle()); -} - -TEST_F(TouchEventConverterEvdevTest, TouchRelease) { - ui::MockTouchEventConverterEvdev* dev = device(); - - struct input_event mock_kernel_queue_press[] = { - {{0, 0}, EV_ABS, ABS_MT_TRACKING_ID, 684}, - {{0, 0}, EV_ABS, ABS_MT_TOUCH_MAJOR, 3}, - {{0, 0}, EV_ABS, ABS_MT_PRESSURE, 45}, - {{0, 0}, EV_ABS, ABS_MT_POSITION_X, 42}, - {{0, 0}, EV_ABS, ABS_MT_POSITION_Y, 51}, {{0, 0}, EV_SYN, SYN_REPORT, 0} - }; - - struct input_event mock_kernel_queue_release[] = { - {{0, 0}, EV_ABS, ABS_MT_TRACKING_ID, -1}, {{0, 0}, EV_SYN, SYN_REPORT, 0} - }; - - // Setup and discard a press. - dev->ConfigureReadMock(mock_kernel_queue_press, 6, 0); - dev->ReadNow(); - EXPECT_EQ(1u, dev->size()); - ui::TouchEvent* event = dev->event(0); - EXPECT_FALSE(event == NULL); - - dev->ConfigureReadMock(mock_kernel_queue_release, 2, 0); - dev->ReadNow(); - EXPECT_EQ(2u, dev->size()); - event = dev->event(1); - EXPECT_FALSE(event == NULL); - - EXPECT_EQ(ui::ET_TOUCH_RELEASED, event->type()); - EXPECT_EQ(base::TimeDelta::FromMicroseconds(0), event->time_stamp()); - EXPECT_EQ(42, event->x()); - EXPECT_EQ(51, event->y()); - EXPECT_EQ(0, event->touch_id()); - EXPECT_FLOAT_EQ(.5f, event->force()); - EXPECT_FLOAT_EQ(0.f, event->rotation_angle()); -} - -TEST_F(TouchEventConverterEvdevTest, TwoFingerGesture) { - ui::MockTouchEventConverterEvdev* dev = device(); - - ui::TouchEvent* ev0; - ui::TouchEvent* ev1; - - struct input_event mock_kernel_queue_press0[] = { - {{0, 0}, EV_ABS, ABS_MT_TRACKING_ID, 684}, - {{0, 0}, EV_ABS, ABS_MT_TOUCH_MAJOR, 3}, - {{0, 0}, EV_ABS, ABS_MT_PRESSURE, 45}, - {{0, 0}, EV_ABS, ABS_MT_POSITION_X, 42}, - {{0, 0}, EV_ABS, ABS_MT_POSITION_Y, 51}, {{0, 0}, EV_SYN, SYN_REPORT, 0} - }; - // Setup and discard a press. - dev->ConfigureReadMock(mock_kernel_queue_press0, 6, 0); - dev->ReadNow(); - EXPECT_EQ(1u, dev->size()); - - struct input_event mock_kernel_queue_move0[] = { - {{0, 0}, EV_ABS, ABS_MT_POSITION_X, 40}, {{0, 0}, EV_SYN, SYN_REPORT, 0} - }; - // Setup and discard a move. - dev->ConfigureReadMock(mock_kernel_queue_move0, 2, 0); - dev->ReadNow(); - EXPECT_EQ(2u, dev->size()); - - struct input_event mock_kernel_queue_move0press1[] = { - {{0, 0}, EV_ABS, ABS_MT_POSITION_X, 40}, {{0, 0}, EV_SYN, SYN_REPORT, 0}, - {{0, 0}, EV_ABS, ABS_MT_SLOT, 1}, {{0, 0}, EV_ABS, ABS_MT_TRACKING_ID, 686}, - {{0, 0}, EV_ABS, ABS_MT_TOUCH_MAJOR, 3}, - {{0, 0}, EV_ABS, ABS_MT_PRESSURE, 45}, - {{0, 0}, EV_ABS, ABS_MT_POSITION_X, 101}, - {{0, 0}, EV_ABS, ABS_MT_POSITION_Y, 102}, {{0, 0}, EV_SYN, SYN_REPORT, 0} - }; - // Move on 0, press on 1. - dev->ConfigureReadMock(mock_kernel_queue_move0press1, 9, 0); - dev->ReadNow(); - EXPECT_EQ(4u, dev->size()); - ev0 = dev->event(2); - ev1 = dev->event(3); - - // Move - EXPECT_EQ(ui::ET_TOUCH_MOVED, ev0->type()); - EXPECT_EQ(base::TimeDelta::FromMicroseconds(0), ev0->time_stamp()); - EXPECT_EQ(40, ev0->x()); - EXPECT_EQ(51, ev0->y()); - EXPECT_EQ(0, ev0->touch_id()); - EXPECT_FLOAT_EQ(.5f, ev0->force()); - EXPECT_FLOAT_EQ(0.f, ev0->rotation_angle()); - - // Press - EXPECT_EQ(ui::ET_TOUCH_PRESSED, ev1->type()); - EXPECT_EQ(base::TimeDelta::FromMicroseconds(0), ev1->time_stamp()); - EXPECT_EQ(101, ev1->x()); - EXPECT_EQ(102, ev1->y()); - EXPECT_EQ(1, ev1->touch_id()); - EXPECT_FLOAT_EQ(.5f, ev1->force()); - EXPECT_FLOAT_EQ(0.f, ev1->rotation_angle()); - - // Stationary 0, Moves 1. - struct input_event mock_kernel_queue_stationary0_move1[] = { - {{0, 0}, EV_ABS, ABS_MT_POSITION_X, 40}, {{0, 0}, EV_SYN, SYN_REPORT, 0} - }; - dev->ConfigureReadMock(mock_kernel_queue_stationary0_move1, 2, 0); - dev->ReadNow(); - EXPECT_EQ(5u, dev->size()); - ev1 = dev->event(4); - - EXPECT_EQ(ui::ET_TOUCH_MOVED, ev1->type()); - EXPECT_EQ(base::TimeDelta::FromMicroseconds(0), ev1->time_stamp()); - EXPECT_EQ(40, ev1->x()); - EXPECT_EQ(102, ev1->y()); - EXPECT_EQ(1, ev1->touch_id()); - - EXPECT_FLOAT_EQ(.5f, ev1->force()); - EXPECT_FLOAT_EQ(0.f, ev1->rotation_angle()); - - // Move 0, stationary 1. - struct input_event mock_kernel_queue_move0_stationary1[] = { - {{0, 0}, EV_ABS, ABS_MT_SLOT, 0}, {{0, 0}, EV_ABS, ABS_MT_POSITION_X, 39}, - {{0, 0}, EV_SYN, SYN_REPORT, 0} - }; - dev->ConfigureReadMock(mock_kernel_queue_move0_stationary1, 3, 0); - dev->ReadNow(); - EXPECT_EQ(6u, dev->size()); - ev0 = dev->event(5); - - EXPECT_EQ(ui::ET_TOUCH_MOVED, ev0->type()); - EXPECT_EQ(base::TimeDelta::FromMicroseconds(0), ev0->time_stamp()); - EXPECT_EQ(39, ev0->x()); - EXPECT_EQ(51, ev0->y()); - EXPECT_EQ(0, ev0->touch_id()); - EXPECT_FLOAT_EQ(.5f, ev0->force()); - EXPECT_FLOAT_EQ(0.f, ev0->rotation_angle()); - - // Release 0, move 1. - struct input_event mock_kernel_queue_release0_move1[] = { - {{0, 0}, EV_ABS, ABS_MT_TRACKING_ID, -1}, {{0, 0}, EV_ABS, ABS_MT_SLOT, 1}, - {{0, 0}, EV_ABS, ABS_MT_POSITION_X, 38}, {{0, 0}, EV_SYN, SYN_REPORT, 0} - }; - dev->ConfigureReadMock(mock_kernel_queue_release0_move1, 4, 0); - dev->ReadNow(); - EXPECT_EQ(8u, dev->size()); - ev0 = dev->event(6); - ev1 = dev->event(7); - - EXPECT_EQ(ui::ET_TOUCH_RELEASED, ev0->type()); - EXPECT_EQ(base::TimeDelta::FromMicroseconds(0), ev0->time_stamp()); - EXPECT_EQ(39, ev0->x()); - EXPECT_EQ(51, ev0->y()); - EXPECT_EQ(0, ev0->touch_id()); - EXPECT_FLOAT_EQ(.5f, ev0->force()); - EXPECT_FLOAT_EQ(0.f, ev0->rotation_angle()); - - EXPECT_EQ(ui::ET_TOUCH_MOVED, ev1->type()); - EXPECT_EQ(base::TimeDelta::FromMicroseconds(0), ev1->time_stamp()); - EXPECT_EQ(38, ev1->x()); - EXPECT_EQ(102, ev1->y()); - EXPECT_EQ(1, ev1->touch_id()); - EXPECT_FLOAT_EQ(.5f, ev1->force()); - EXPECT_FLOAT_EQ(0.f, ev1->rotation_angle()); - - // Release 1. - struct input_event mock_kernel_queue_release1[] = { - {{0, 0}, EV_ABS, ABS_MT_TRACKING_ID, -1}, {{0, 0}, EV_SYN, SYN_REPORT, 0}, - }; - dev->ConfigureReadMock(mock_kernel_queue_release1, 2, 0); - dev->ReadNow(); - EXPECT_EQ(9u, dev->size()); - ev1 = dev->event(8); - - EXPECT_EQ(ui::ET_TOUCH_RELEASED, ev1->type()); - EXPECT_EQ(base::TimeDelta::FromMicroseconds(0), ev1->time_stamp()); - EXPECT_EQ(38, ev1->x()); - EXPECT_EQ(102, ev1->y()); - EXPECT_EQ(1, ev1->touch_id()); - EXPECT_FLOAT_EQ(.5f, ev1->force()); - EXPECT_FLOAT_EQ(0.f, ev1->rotation_angle()); -} - -TEST_F(TouchEventConverterEvdevTest, TypeA) { - ui::MockTouchEventConverterEvdev* dev = device(); - - struct input_event mock_kernel_queue_press0[] = { - {{0, 0}, EV_ABS, ABS_MT_TOUCH_MAJOR, 3}, - {{0, 0}, EV_ABS, ABS_MT_PRESSURE, 45}, - {{0, 0}, EV_ABS, ABS_MT_POSITION_X, 42}, - {{0, 0}, EV_ABS, ABS_MT_POSITION_Y, 51}, - {{0, 0}, EV_SYN, SYN_MT_REPORT, 0}, - {{0, 0}, EV_ABS, ABS_MT_PRESSURE, 45}, - {{0, 0}, EV_ABS, ABS_MT_POSITION_X, 61}, - {{0, 0}, EV_ABS, ABS_MT_POSITION_Y, 71}, - {{0, 0}, EV_SYN, SYN_MT_REPORT, 0}, - {{0, 0}, EV_SYN, SYN_REPORT, 0} - }; - - // Check that two events are generated. - dev->ConfigureReadMock(mock_kernel_queue_press0, 10, 0); - dev->ReadNow(); - EXPECT_EQ(2u, dev->size()); -} - -TEST_F(TouchEventConverterEvdevTest, Unsync) { - ui::MockTouchEventConverterEvdev* dev = device(); - - struct input_event mock_kernel_queue_press0[] = { - {{0, 0}, EV_ABS, ABS_MT_TRACKING_ID, 684}, - {{0, 0}, EV_ABS, ABS_MT_TOUCH_MAJOR, 3}, - {{0, 0}, EV_ABS, ABS_MT_PRESSURE, 45}, - {{0, 0}, EV_ABS, ABS_MT_POSITION_X, 42}, - {{0, 0}, EV_ABS, ABS_MT_POSITION_Y, 51}, {{0, 0}, EV_SYN, SYN_REPORT, 0} - }; - - dev->ConfigureReadMock(mock_kernel_queue_press0, 6, 0); - dev->ReadNow(); - EXPECT_EQ(1u, dev->size()); - - // Prepare a move with a drop. - struct input_event mock_kernel_queue_move0[] = { - {{0, 0}, EV_SYN, SYN_DROPPED, 0}, - {{0, 0}, EV_ABS, ABS_MT_POSITION_X, 40}, {{0, 0}, EV_SYN, SYN_REPORT, 0} - }; - - // Verify that we didn't receive it/ - dev->ConfigureReadMock(mock_kernel_queue_move0, 3, 0); - dev->ReadNow(); - EXPECT_EQ(1u, dev->size()); - - struct input_event mock_kernel_queue_move1[] = { - {{0, 0}, EV_ABS, ABS_MT_POSITION_X, 40}, {{0, 0}, EV_SYN, SYN_REPORT, 0} - }; - - // Verify that it re-syncs after a SYN_REPORT. - dev->ConfigureReadMock(mock_kernel_queue_move1, 2, 0); - dev->ReadNow(); - EXPECT_EQ(2u, dev->size()); -} - -// crbug.com/407386 -TEST_F(TouchEventConverterEvdevTest, - DontChangeMultitouchPositionFromLegacyAxes) { - ui::MockTouchEventConverterEvdev* dev = device(); - - struct input_event mock_kernel_queue[] = { - {{0, 0}, EV_ABS, ABS_MT_SLOT, 0}, - {{0, 0}, EV_ABS, ABS_MT_TRACKING_ID, 100}, - {{0, 0}, EV_ABS, ABS_MT_POSITION_X, 999}, - {{0, 0}, EV_ABS, ABS_MT_POSITION_Y, 888}, - {{0, 0}, EV_ABS, ABS_MT_PRESSURE, 55}, - {{0, 0}, EV_ABS, ABS_MT_SLOT, 1}, - {{0, 0}, EV_ABS, ABS_MT_TRACKING_ID, 200}, - {{0, 0}, EV_ABS, ABS_MT_PRESSURE, 44}, - {{0, 0}, EV_ABS, ABS_MT_POSITION_X, 777}, - {{0, 0}, EV_ABS, ABS_MT_POSITION_Y, 666}, - {{0, 0}, EV_ABS, ABS_X, 999}, - {{0, 0}, EV_ABS, ABS_Y, 888}, - {{0, 0}, EV_ABS, ABS_PRESSURE, 55}, - {{0, 0}, EV_SYN, SYN_REPORT, 0}, - }; - - // Check that two events are generated. - dev->ConfigureReadMock(mock_kernel_queue, arraysize(mock_kernel_queue), 0); - dev->ReadNow(); - - const unsigned int kExpectedEventCount = 2; - EXPECT_EQ(kExpectedEventCount, dev->size()); - if (kExpectedEventCount != dev->size()) - return; - - ui::TouchEvent* ev0 = dev->event(0); - ui::TouchEvent* ev1 = dev->event(1); - - EXPECT_EQ(0, ev0->touch_id()); - EXPECT_EQ(999, ev0->x()); - EXPECT_EQ(888, ev0->y()); - EXPECT_FLOAT_EQ(0.8333333f, ev0->force()); - - EXPECT_EQ(1, ev1->touch_id()); - EXPECT_EQ(777, ev1->x()); - EXPECT_EQ(666, ev1->y()); - EXPECT_FLOAT_EQ(0.4666666f, ev1->force()); -}
diff --git a/ui/events/ozone/events_ozone.cc b/ui/events/ozone/events_ozone.cc deleted file mode 100644 index d2e1e33..0000000 --- a/ui/events/ozone/events_ozone.cc +++ /dev/null
@@ -1,201 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/events/ozone/events_ozone.h" - -#include "ui/events/event.h" -#include "ui/events/event_constants.h" -#include "ui/events/event_utils.h" - -namespace ui { - -void UpdateDeviceList() { NOTIMPLEMENTED(); } - -base::TimeDelta EventTimeFromNative(const base::NativeEvent& native_event) { - const ui::Event* event = static_cast<const ui::Event*>(native_event); - return event->time_stamp(); -} - -int EventFlagsFromNative(const base::NativeEvent& native_event) { - const ui::Event* event = static_cast<const ui::Event*>(native_event); - return event->flags(); -} - -EventType EventTypeFromNative(const base::NativeEvent& native_event) { - const ui::Event* event = static_cast<const ui::Event*>(native_event); - return event->type(); -} - -gfx::Point EventSystemLocationFromNative( - const base::NativeEvent& native_event) { - const ui::LocatedEvent* e = - static_cast<const ui::LocatedEvent*>(native_event); - DCHECK(e->IsMouseEvent() || e->IsTouchEvent() || e->IsGestureEvent() || - e->IsScrollEvent()); - return e->location(); -} - -gfx::Point EventLocationFromNative(const base::NativeEvent& native_event) { - return EventSystemLocationFromNative(native_event); -} - -int GetChangedMouseButtonFlagsFromNative( - const base::NativeEvent& native_event) { - const ui::MouseEvent* event = - static_cast<const ui::MouseEvent*>(native_event); - DCHECK(event->IsMouseEvent() || event->IsScrollEvent()); - return event->changed_button_flags(); -} - -KeyboardCode KeyboardCodeFromNative(const base::NativeEvent& native_event) { - const ui::KeyEvent* event = static_cast<const ui::KeyEvent*>(native_event); - DCHECK(event->IsKeyEvent()); - return event->key_code(); -} - -const char* CodeFromNative(const base::NativeEvent& native_event) { - const ui::KeyEvent* event = static_cast<const ui::KeyEvent*>(native_event); - DCHECK(event->IsKeyEvent()); - return event->code().c_str(); -} - -uint32 PlatformKeycodeFromNative(const base::NativeEvent& native_event) { - const ui::KeyEvent* event = static_cast<const ui::KeyEvent*>(native_event); - DCHECK(event->IsKeyEvent()); - return event->platform_keycode(); -} - -bool IsCharFromNative(const base::NativeEvent& native_event) { - const ui::KeyEvent* event = static_cast<const ui::KeyEvent*>(native_event); - DCHECK(event->IsKeyEvent()); - return event->is_char(); -} - -gfx::Vector2d GetMouseWheelOffset(const base::NativeEvent& native_event) { - const ui::MouseWheelEvent* event = - static_cast<const ui::MouseWheelEvent*>(native_event); - DCHECK(event->type() == ET_MOUSEWHEEL); - return event->offset(); -} - -base::NativeEvent CopyNativeEvent(const base::NativeEvent& event) { - return NULL; -} - -void ReleaseCopiedNativeEvent(const base::NativeEvent& event) { -} - -void IncrementTouchIdRefCount(const base::NativeEvent& event) { -} - -void ClearTouchIdIfReleased(const base::NativeEvent& xev) { -} - -int GetTouchId(const base::NativeEvent& native_event) { - const ui::TouchEvent* event = - static_cast<const ui::TouchEvent*>(native_event); - DCHECK(event->IsTouchEvent()); - return event->touch_id(); -} - -float GetTouchRadiusX(const base::NativeEvent& native_event) { - const ui::TouchEvent* event = - static_cast<const ui::TouchEvent*>(native_event); - DCHECK(event->IsTouchEvent()); - return event->radius_x(); -} - -float GetTouchRadiusY(const base::NativeEvent& native_event) { - const ui::TouchEvent* event = - static_cast<const ui::TouchEvent*>(native_event); - DCHECK(event->IsTouchEvent()); - return event->radius_y(); -} - -float GetTouchAngle(const base::NativeEvent& native_event) { - const ui::TouchEvent* event = - static_cast<const ui::TouchEvent*>(native_event); - DCHECK(event->IsTouchEvent()); - return event->rotation_angle(); -} - -float GetTouchForce(const base::NativeEvent& native_event) { - const ui::TouchEvent* event = - static_cast<const ui::TouchEvent*>(native_event); - DCHECK(event->IsTouchEvent()); - return event->force(); -} - -bool GetScrollOffsets(const base::NativeEvent& native_event, - float* x_offset, - float* y_offset, - float* x_offset_ordinal, - float* y_offset_ordinal, - int* finger_count) { - const ui::ScrollEvent* event = - static_cast<const ui::ScrollEvent*>(native_event); - DCHECK(event->IsScrollEvent()); - if (x_offset) - *x_offset = event->x_offset(); - if (y_offset) - *y_offset = event->y_offset(); - if (x_offset_ordinal) - *x_offset_ordinal = event->x_offset_ordinal(); - if (y_offset_ordinal) - *y_offset_ordinal = event->y_offset_ordinal(); - if (finger_count) - *finger_count = event->finger_count(); - - return true; -} - -bool GetFlingData(const base::NativeEvent& native_event, - float* vx, - float* vy, - float* vx_ordinal, - float* vy_ordinal, - bool* is_cancel) { - const ui::ScrollEvent* event = - static_cast<const ui::ScrollEvent*>(native_event); - DCHECK(event->IsScrollEvent()); - if (vx) - *vx = event->x_offset(); - if (vy) - *vy = event->y_offset(); - if (vx_ordinal) - *vx_ordinal = event->x_offset_ordinal(); - if (vy_ordinal) - *vy_ordinal = event->y_offset_ordinal(); - if (is_cancel) - *is_cancel = event->type() == ET_SCROLL_FLING_CANCEL; - - return true; -} - -int GetModifiersFromKeyState() { - NOTIMPLEMENTED(); - return 0; -} - -void DispatchEventFromNativeUiEvent(const base::NativeEvent& native_event, - base::Callback<void(ui::Event*)> callback) { - const ui::Event* native_ui_event = static_cast<ui::Event*>(native_event); - if (native_ui_event->IsKeyEvent()) { - ui::KeyEvent key_event(native_event); - callback.Run(&key_event); - } else if (native_ui_event->IsMouseEvent()) { - ui::MouseEvent mouse_event(native_event); - callback.Run(&mouse_event); - } else if (native_ui_event->IsTouchEvent()) { - ui::TouchEvent touch_event(native_event); - callback.Run(&touch_event); - } else if (native_ui_event->IsScrollEvent()) { - ui::ScrollEvent scroll_event(native_event); - callback.Run(&scroll_event); - } else { - NOTREACHED(); - } -} - -} // namespace ui
diff --git a/ui/events/ozone/events_ozone.gyp b/ui/events/ozone/events_ozone.gyp deleted file mode 100644 index c74263a..0000000 --- a/ui/events/ozone/events_ozone.gyp +++ /dev/null
@@ -1,102 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -{ - 'variables': { - 'chromium_code': 1, - }, - 'targets': [{ - 'target_name': 'events_ozone', - 'type': '<(component)', - 'dependencies': [ - '../../../base/base.gyp:base', - ], - 'defines': [ - 'EVENTS_OZONE_IMPLEMENTATION', - ], - 'sources': [ - 'device/device_event.cc', - 'device/device_event.h', - 'device/device_event_observer.h', - 'device/device_manager.cc', - 'device/device_manager.h', - 'device/device_manager_manual.cc', - 'device/device_manager_manual.h', - 'device/udev/device_manager_udev.cc', - 'device/udev/device_manager_udev.h', - 'events_ozone_export.h', - ], - 'conditions': [ - ['use_udev==0', { - 'sources/': [ - ['exclude', '_udev\\.(h|cc)$'], - ], - }], - ['use_ozone_evdev==1 and use_udev==1', { - 'dependencies': [ - '<(DEPTH)/device/udev_linux/udev.gyp:udev_linux', - ], - }], - ], - }, { - 'target_name': 'events_ozone_evdev', - 'type': '<(component)', - 'dependencies': [ - '../../../base/base.gyp:base', - '../../gfx/gfx.gyp:gfx', - '../../ozone/ozone.gyp:ozone_base', - '../events.gyp:dom4_keycode_converter', - '../platform/events_platform.gyp:events_platform', - 'events_ozone', - ], - 'defines': [ - 'EVENTS_OZONE_EVDEV_IMPLEMENTATION', - ], - 'sources': [ - 'evdev/libgestures_glue/event_reader_libevdev_cros.cc', - 'evdev/libgestures_glue/event_reader_libevdev_cros.h', - 'evdev/libgestures_glue/gesture_interpreter_libevdev_cros.cc', - 'evdev/libgestures_glue/gesture_interpreter_libevdev_cros.h', - 'evdev/libgestures_glue/gesture_logging.cc', - 'evdev/libgestures_glue/gesture_logging.h', - 'evdev/libgestures_glue/gesture_property_provider.cc', - 'evdev/libgestures_glue/gesture_property_provider.h', - 'evdev/libgestures_glue/gesture_timer_provider.cc', - 'evdev/libgestures_glue/gesture_timer_provider.h', - 'evdev/event_converter_evdev.cc', - 'evdev/event_converter_evdev.h', - 'evdev/event_device_info.cc', - 'evdev/event_device_info.h', - 'evdev/event_factory_evdev.cc', - 'evdev/event_factory_evdev.h', - 'evdev/event_modifiers_evdev.cc', - 'evdev/event_modifiers_evdev.h', - 'evdev/events_ozone_evdev_export.h', - 'evdev/key_event_converter_evdev.cc', - 'evdev/key_event_converter_evdev.h', - 'evdev/keyboard_evdev.cc', - 'evdev/keyboard_evdev.h', - 'evdev/touch_event_converter_evdev.cc', - 'evdev/touch_event_converter_evdev.h', - ], - 'conditions': [ - ['use_ozone_evdev==1 and use_evdev_gestures==1', { - 'dependencies': [ - '<(DEPTH)/build/linux/system.gyp:libgestures', - '<(DEPTH)/build/linux/system.gyp:libevdev-cros', - ], - 'defines': [ - 'USE_EVDEV_GESTURES', - ], - }, { - 'sources/': [ - ['exclude', '^evdev/libgestures_glue/'], - ], - }], - ['use_ozone_evdev==1', { - 'defines': ['USE_OZONE_EVDEV=1'], - }], - ], - }] -}
diff --git a/ui/events/ozone/events_ozone.h b/ui/events/ozone/events_ozone.h deleted file mode 100644 index ad603cd..0000000 --- a/ui/events/ozone/events_ozone.h +++ /dev/null
@@ -1,39 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_EVENTS_OZONE_EVENTS_OZONE_H_ -#define UI_EVENTS_OZONE_EVENTS_OZONE_H_ - -#include "base/callback.h" -#include "base/event_types.h" -#include "ui/events/events_export.h" - -namespace ui { - -class Event; - -// Wrap a "native" ui::Event in another ui::Event & dispatch it. -// -// This is really unfortunate, but exists for two reasons: -// -// 1. Some of the ui::Event constructors depend on global state that -// is only used when building from a "native" event. For example: -// last_click_event_ is used when constructing MouseEvent from -// NativeEvent to determine click count. -// -// 2. Events contain a reference to a "native event", which some code -// depends on. The ui::Event might get mutated during dispatch, but -// the native event won't. Some code depends on the fact that the -// "native" version of the event is unmodified. -// -// We are trying to fix both of these issues, but in the meantime we -// define NativeEvent == ui::Event. -// -EVENTS_EXPORT void DispatchEventFromNativeUiEvent( - const base::NativeEvent& native_event, - base::Callback<void(ui::Event*)> callback); - -} // namespace ui - -#endif // UI_EVENTS_OZONE_EVENTS_OZONE_H_
diff --git a/ui/events/ozone/events_ozone_export.h b/ui/events/ozone/events_ozone_export.h deleted file mode 100644 index bda8814..0000000 --- a/ui/events/ozone/events_ozone_export.h +++ /dev/null
@@ -1,29 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_EVENTS_OZONE_EVENTS_OZONE_EXPORT_H_ -#define UI_EVENTS_OZONE_EVENTS_OZONE_EXPORT_H_ - -#if defined(COMPONENT_BUILD) -#if defined(WIN32) - -#if defined(EVENTS_OZONE_IMPLEMENTATION) -#define EVENTS_OZONE_EXPORT __declspec(dllexport) -#else -#define EVENTS_OZONE_EXPORT __declspec(dllimport) -#endif // defined(EVENTS_OZONE_IMPLEMENTATION) - -#else // defined(WIN32) -#if defined(EVENTS_OZONE_IMPLEMENTATION) -#define EVENTS_OZONE_EXPORT __attribute__((visibility("default"))) -#else -#define EVENTS_OZONE_EXPORT -#endif -#endif - -#else // defined(COMPONENT_BUILD) -#define EVENTS_OZONE_EXPORT -#endif - -#endif // UI_EVENTS_OZONE_EVENTS_OZONE_EXPORT_H_
diff --git a/ui/events/x/device_list_cache_x.cc b/ui/events/x/device_list_cache_x.cc index df930d1..c6d7360 100644 --- a/ui/events/x/device_list_cache_x.cc +++ b/ui/events/x/device_list_cache_x.cc
@@ -13,11 +13,7 @@ namespace { bool IsXI2Available() { -#if defined(USE_AURA) - return ui::DeviceDataManagerX11::GetInstance()->IsXInput2Available(); -#else return false; -#endif } }
diff --git a/ui/gfx/BUILD.gn b/ui/gfx/BUILD.gn index c178dcc..83b675d 100644 --- a/ui/gfx/BUILD.gn +++ b/ui/gfx/BUILD.gn
@@ -128,8 +128,6 @@ "mac/coordinate_conversion.mm", "mac/scoped_ns_disable_screen_updates.h", "native_widget_types.h", - "nine_image_painter.cc", - "nine_image_painter.h", "path.cc", "path.h", "path_aura.cc", @@ -244,8 +242,6 @@ sources += [ "render_text_mac.cc" ] } else if (use_pango) { sources += [ "render_text_pango.cc" ] - } else if (use_ozone) { - sources += [ "render_text_ozone.cc" ] } } @@ -315,15 +311,8 @@ configs += [ "//build/config/linux:fontconfig" ] } - # Ozone stuff. - if (use_ozone) { - sources += [ "platform_font_ozone.cc" ] - } - if (!use_aura) { sources -= [ - "nine_image_painter.cc", - "nine_image_painter.h", "path_aura.cc", "screen_aura.cc", ] @@ -344,9 +333,6 @@ ] configs += [ "//build/config/linux:pangocairo" ] } - if (use_pango && use_ozone) { - sources -= [ "platform_font_ozone.cc" ] - } } # Looking for gfx_geometry? It's //ui/gfx/geometry:geometry @@ -479,16 +465,6 @@ ] } - if (use_ozone && !use_pango) { - sources -= [ - "canvas_unittest.cc", - "font_list_unittest.cc", - "font_unittest.cc", - "render_text_unittest.cc", - "text_elider_unittest.cc", - ] - } - if (is_android) { sources -= [ # Do not run display_change_notifier_unittest.cc on Android because it
diff --git a/ui/gfx/display.cc b/ui/gfx/display.cc index 914a09e..3208efb 100644 --- a/ui/gfx/display.cc +++ b/ui/gfx/display.cc
@@ -56,9 +56,6 @@ device_scale_factor_(GetForcedDeviceScaleFactor()), rotation_(ROTATE_0), touch_support_(TOUCH_SUPPORT_UNKNOWN) { -#if defined(USE_AURA) - SetScaleAndBounds(device_scale_factor_, bounds); -#endif } Display::~Display() {
diff --git a/ui/gfx/gfx.gyp b/ui/gfx/gfx.gyp index b912b45..ed37001 100644 --- a/ui/gfx/gfx.gyp +++ b/ui/gfx/gfx.gyp
@@ -203,8 +203,6 @@ 'mac/coordinate_conversion.mm', 'mac/scoped_ns_disable_screen_updates.h', 'native_widget_types.h', - 'nine_image_painter.cc', - 'nine_image_painter.h', 'overlay_transform.h', 'pango_util.cc', 'pango_util.h', @@ -221,7 +219,6 @@ 'platform_font_ios.mm', 'platform_font_mac.h', 'platform_font_mac.mm', - 'platform_font_ozone.cc', 'platform_font_pango.cc', 'platform_font_pango.h', 'platform_font_win.cc', @@ -236,7 +233,6 @@ 'render_text_harfbuzz.h', 'render_text_mac.cc', 'render_text_mac.h', - 'render_text_ozone.cc', 'render_text_pango.cc', 'render_text_pango.h', 'render_text_win.cc', @@ -353,12 +349,6 @@ ], }, }], - ['use_aura==0 and toolkit_views==0', { - 'sources!': [ - 'nine_image_painter.cc', - 'nine_image_painter.h', - ], - }], ['OS=="android" and use_aura==0', { 'sources!': [ 'path.cc', @@ -393,10 +383,6 @@ 'dependencies': [ '<(DEPTH)/build/linux/system.gyp:pangocairo', ], - 'sources!': [ - 'platform_font_ozone.cc', - 'render_text_ozone.cc', - ], }], ['desktop_linux==1 or chromeos==1', { 'dependencies': [
diff --git a/ui/gfx/gfx_tests.gyp b/ui/gfx/gfx_tests.gyp index 4f535bf..d83e86b 100644 --- a/ui/gfx/gfx_tests.gyp +++ b/ui/gfx/gfx_tests.gyp
@@ -111,15 +111,6 @@ }], ], }], - ['use_ozone==1 and use_pango==0', { - 'sources!': [ - 'canvas_unittest.cc', - 'font_list_unittest.cc', - 'font_unittest.cc', - 'render_text_unittest.cc', - 'text_elider_unittest.cc', - ], - }], ['OS == "android"', { 'dependencies': [ '../../testing/android/native_test.gyp:native_test_native_code',
diff --git a/ui/gfx/nine_image_painter.cc b/ui/gfx/nine_image_painter.cc deleted file mode 100644 index 500c536..0000000 --- a/ui/gfx/nine_image_painter.cc +++ /dev/null
@@ -1,167 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/gfx/nine_image_painter.h" - -#include <limits> - -#include "third_party/skia/include/core/SkPaint.h" -#include "third_party/skia/include/core/SkRect.h" -#include "third_party/skia/include/core/SkScalar.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/geometry/rect_conversions.h" -#include "ui/gfx/geometry/safe_integer_conversions.h" -#include "ui/gfx/image/image_skia_operations.h" -#include "ui/gfx/insets.h" -#include "ui/gfx/rect.h" -#include "ui/gfx/scoped_canvas.h" -#include "ui/gfx/skia_util.h" - -namespace gfx { - -namespace { - -// The following functions width and height of the image in pixels for the -// scale factor in the Canvas. -int ImageWidthInPixels(const ImageSkia& i, Canvas* c) { - return i.GetRepresentation(c->image_scale()).pixel_width(); -} - -int ImageHeightInPixels(const ImageSkia& i, Canvas* c) { - return i.GetRepresentation(c->image_scale()).pixel_height(); -} - -// Stretches the given image over the specified canvas area. -void Fill(Canvas* c, - const ImageSkia& i, - int x, - int y, - int w, - int h, - const SkPaint& paint) { - c->DrawImageIntInPixel(i, 0, 0, ImageWidthInPixels(i, c), - ImageHeightInPixels(i, c), x, y, w, h, false, paint); -} - -} // namespace - -NineImagePainter::NineImagePainter(const std::vector<ImageSkia>& images) { - DCHECK_EQ(arraysize(images_), images.size()); - for (size_t i = 0; i < arraysize(images_); ++i) - images_[i] = images[i]; -} - -NineImagePainter::NineImagePainter(const ImageSkia& image, - const Insets& insets) { - DCHECK_GE(image.width(), insets.width()); - DCHECK_GE(image.height(), insets.height()); - - // Extract subsets of the original image to match the |images_| format. - const int x[] = - { 0, insets.left(), image.width() - insets.right(), image.width() }; - const int y[] = - { 0, insets.top(), image.height() - insets.bottom(), image.height() }; - - for (size_t j = 0; j < 3; ++j) { - for (size_t i = 0; i < 3; ++i) { - images_[i + j * 3] = ImageSkiaOperations::ExtractSubset(image, - Rect(x[i], y[j], x[i + 1] - x[i], y[j + 1] - y[j])); - } - } -} - -NineImagePainter::~NineImagePainter() { -} - -bool NineImagePainter::IsEmpty() const { - return images_[0].isNull(); -} - -Size NineImagePainter::GetMinimumSize() const { - return IsEmpty() ? Size() : Size( - images_[0].width() + images_[1].width() + images_[2].width(), - images_[0].height() + images_[3].height() + images_[6].height()); -} - -void NineImagePainter::Paint(Canvas* canvas, const Rect& bounds) { - // When no alpha value is specified, use default value of 100% opacity. - Paint(canvas, bounds, std::numeric_limits<uint8>::max()); -} - -void NineImagePainter::Paint(Canvas* canvas, - const Rect& bounds, - const uint8 alpha) { - if (IsEmpty()) - return; - - ScopedCanvas scoped_canvas(canvas); - canvas->Translate(bounds.OffsetFromOrigin()); - - // Get the current transform from the canvas and apply it to the logical - // bounds passed in. This will give us the pixel bounds which can be used - // to draw the images at the correct locations. - // We should not scale the bounds by the canvas->image_scale() as that can be - // different from the real scale in the canvas transform. - SkRect bounds_in_pixels_f; - if (!canvas->sk_canvas()->getTotalMatrix().mapRect( - &bounds_in_pixels_f, RectToSkRect(gfx::Rect(bounds.size())))) - return; // Invalid transform. - - SkIRect bounds_in_pixels; - bounds_in_pixels_f.dround(&bounds_in_pixels); - - SkMatrix matrix = canvas->sk_canvas()->getTotalMatrix(); - matrix.setTranslateX(SkIntToScalar(bounds_in_pixels.x())); - matrix.setTranslateY(SkIntToScalar(bounds_in_pixels.y())); - canvas->sk_canvas()->setMatrix(matrix); - - const int width_in_pixels = bounds_in_pixels.width(); - const int height_in_pixels = bounds_in_pixels.height(); - - // In case the corners and edges don't all have the same width/height, we draw - // the center first, and extend it out in all directions to the edges of the - // images with the smallest widths/heights. This way there will be no - // unpainted areas, though some corners or edges might overlap the center. - int i0w = ImageWidthInPixels(images_[0], canvas); - int i2w = ImageWidthInPixels(images_[2], canvas); - int i3w = ImageWidthInPixels(images_[3], canvas); - int i5w = ImageWidthInPixels(images_[5], canvas); - int i6w = ImageWidthInPixels(images_[6], canvas); - int i8w = ImageWidthInPixels(images_[8], canvas); - - int i4x = std::min(std::min(i0w, i3w), i6w); - int i4w = width_in_pixels - i4x - std::min(std::min(i2w, i5w), i8w); - - int i0h = ImageHeightInPixels(images_[0], canvas); - int i1h = ImageHeightInPixels(images_[1], canvas); - int i2h = ImageHeightInPixels(images_[2], canvas); - int i6h = ImageHeightInPixels(images_[6], canvas); - int i7h = ImageHeightInPixels(images_[7], canvas); - int i8h = ImageHeightInPixels(images_[8], canvas); - - int i4y = std::min(std::min(i0h, i1h), i2h); - int i4h = height_in_pixels - i4y - std::min(std::min(i6h, i7h), i8h); - - SkPaint paint; - paint.setAlpha(alpha); - - if (!images_[4].isNull()) - Fill(canvas, images_[4], i4x, i4y, i4w, i4h, paint); - canvas->DrawImageIntInPixel(images_[0], 0, 0, i0w, i0h, - 0, 0, i0w, i0h, false, paint); - Fill(canvas, images_[1], i0w, 0, width_in_pixels - i0w - i2w, i1h, paint); - canvas->DrawImageIntInPixel(images_[2], 0, 0, i2w, i2h, width_in_pixels - i2w, - 0, i2w, i2h, false, paint); - Fill(canvas, images_[3], 0, i0h, i3w, height_in_pixels - i0h - i6h, paint); - Fill(canvas, images_[5], width_in_pixels - i5w, i2h, i5w, - height_in_pixels - i2h - i8h, paint); - canvas->DrawImageIntInPixel(images_[6], 0, 0, i6w, i6h, 0, - height_in_pixels - i6h, i6w, i6h, false, paint); - Fill(canvas, images_[7], i6w, height_in_pixels - i7h, - width_in_pixels - i6w - i8w, i7h, paint); - canvas->DrawImageIntInPixel(images_[8], 0, 0, i8w, i8h, width_in_pixels - i8w, - height_in_pixels - i8h, i8w, i8h, false, paint); -} - -} // namespace gfx
diff --git a/ui/gfx/platform_font_ozone.cc b/ui/gfx/platform_font_ozone.cc deleted file mode 100644 index aef042a..0000000 --- a/ui/gfx/platform_font_ozone.cc +++ /dev/null
@@ -1,25 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/gfx/platform_font.h" - -namespace gfx { - -// static -PlatformFont* PlatformFont::CreateDefault() { - return NULL; -} - -// static -PlatformFont* PlatformFont::CreateFromNativeFont(NativeFont native_font) { - return NULL; -} - -// static -PlatformFont* PlatformFont::CreateFromNameAndSize(const std::string& font_name, - int font_size) { - return NULL; -} - -} // namespace gfx
diff --git a/ui/gfx/render_text_ozone.cc b/ui/gfx/render_text_ozone.cc deleted file mode 100644 index fb5ef99..0000000 --- a/ui/gfx/render_text_ozone.cc +++ /dev/null
@@ -1,13 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/gfx/render_text.h" - -namespace gfx { - -RenderText* RenderText::CreateNativeInstance() { - return NULL; -} - -} // namespace gfx
diff --git a/ui/gl/BUILD.gn b/ui/gl/BUILD.gn index a7ed9e4..ea1ea98 100644 --- a/ui/gl/BUILD.gn +++ b/ui/gl/BUILD.gn
@@ -234,19 +234,6 @@ deps += [ ":gl_jni_headers" ] } - if (use_ozone) { - sources += [ - "gl_context_ozone.cc", - "gl_egl_api_implementation.cc", - "gl_egl_api_implementation.h", - "gl_implementation_ozone.cc", - "gl_surface_ozone.cc", - ] - deps += [ - "//ui/ozone", - "//ui/ozone:ozone_base", - ] - } if (is_android && !is_android_webview_build) { deps += [ "//ui/android:ui_java" ]
diff --git a/ui/gl/gl.gyp b/ui/gl/gl.gyp index 87ccc81..f11f40c 100644 --- a/ui/gl/gl.gyp +++ b/ui/gl/gl.gyp
@@ -56,7 +56,6 @@ 'gl_context.h', 'gl_context_android.cc', 'gl_context_mac.mm', - 'gl_context_ozone.cc', 'gl_context_osmesa.cc', 'gl_context_osmesa.h', 'gl_context_stub.cc', @@ -86,7 +85,6 @@ 'gl_implementation.cc', 'gl_implementation.h', 'gl_implementation_android.cc', - 'gl_implementation_ozone.cc', 'gl_implementation_mac.cc', 'gl_implementation_win.cc', 'gl_implementation_x11.cc', @@ -106,7 +104,6 @@ 'gl_surface_x11.cc', 'gl_surface_osmesa.cc', 'gl_surface_osmesa.h', - 'gl_surface_ozone.cc', 'gl_switches.cc', 'gl_switches.h', 'gl_version_info.cc', @@ -303,12 +300,6 @@ ['OS!="android"', { 'sources/': [ ['exclude', '^android/'] ], }], - ['use_ozone==1', { - 'dependencies': [ - '../ozone/ozone.gyp:ozone', - '../ozone/ozone.gyp:ozone_base', - ], - }], ['OS=="android" and android_webview_build==0', { 'dependencies': [ '../android/ui_android.gyp:ui_java',
diff --git a/ui/gl/gl_context_ozone.cc b/ui/gl/gl_context_ozone.cc deleted file mode 100644 index 776e114..0000000 --- a/ui/gl/gl_context_ozone.cc +++ /dev/null
@@ -1,47 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/gl/gl_context.h" - -#include "base/logging.h" -#include "base/memory/ref_counted.h" -#include "base/sys_info.h" -#include "ui/gl/gl_bindings.h" -#include "ui/gl/gl_context_egl.h" -#include "ui/gl/gl_context_osmesa.h" -#include "ui/gl/gl_context_stub.h" -#include "ui/gl/gl_implementation.h" -#include "ui/gl/gl_surface.h" - -namespace gfx { - -// static -scoped_refptr<GLContext> GLContext::CreateGLContext( - GLShareGroup* share_group, - GLSurface* compatible_surface, - GpuPreference gpu_preference) { - - switch (GetGLImplementation()) { - case kGLImplementationMockGL: - return scoped_refptr<GLContext>(new GLContextStub()); - case kGLImplementationOSMesaGL: { - scoped_refptr<GLContext> context(new GLContextOSMesa(share_group)); - if (!context->Initialize(compatible_surface, gpu_preference)) - return NULL; - return context; - } - case kGLImplementationEGLGLES2: { - scoped_refptr<GLContext> context(new GLContextEGL(share_group)); - if (!context->Initialize(compatible_surface, gpu_preference)) - return NULL; - return context; - } - default: - NOTREACHED(); - return NULL; - } -} - -} // namespace gfx -
diff --git a/ui/gl/gl_implementation_ozone.cc b/ui/gl/gl_implementation_ozone.cc deleted file mode 100644 index 43b3b04..0000000 --- a/ui/gl/gl_implementation_ozone.cc +++ /dev/null
@@ -1,121 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/bind.h" -#include "ui/gl/gl_bindings.h" -#include "ui/gl/gl_context_stub_with_extensions.h" -#include "ui/gl/gl_egl_api_implementation.h" -#include "ui/gl/gl_gl_api_implementation.h" -#include "ui/gl/gl_implementation.h" -#include "ui/gl/gl_implementation_osmesa.h" -#include "ui/gl/gl_osmesa_api_implementation.h" -#include "ui/ozone/public/ozone_platform.h" -#include "ui/ozone/public/surface_factory_ozone.h" - -namespace gfx { - -namespace { - -void GL_BINDING_CALL MarshalClearDepthToClearDepthf(GLclampd depth) { - glClearDepthf(static_cast<GLclampf>(depth)); -} - -void GL_BINDING_CALL MarshalDepthRangeToDepthRangef(GLclampd z_near, - GLclampd z_far) { - glDepthRangef(static_cast<GLclampf>(z_near), static_cast<GLclampf>(z_far)); -} - -} // namespace - -void GetAllowedGLImplementations(std::vector<GLImplementation>* impls) { - impls->push_back(kGLImplementationEGLGLES2); - impls->push_back(kGLImplementationOSMesaGL); -} - -bool InitializeStaticGLBindings(GLImplementation implementation) { - // Prevent reinitialization with a different implementation. Once the gpu - // unit tests have initialized with kGLImplementationMock, we don't want to - // later switch to another GL implementation. - DCHECK_EQ(kGLImplementationNone, GetGLImplementation()); - ui::OzonePlatform::InitializeForGPU(); - - switch (implementation) { - case kGLImplementationOSMesaGL: - return InitializeStaticGLBindingsOSMesaGL(); - case kGLImplementationEGLGLES2: - if (!ui::SurfaceFactoryOzone::GetInstance()->LoadEGLGLES2Bindings( - base::Bind(&AddGLNativeLibrary), - base::Bind(&SetGLGetProcAddressProc))) - return false; - SetGLImplementation(kGLImplementationEGLGLES2); - InitializeStaticGLBindingsGL(); - InitializeStaticGLBindingsEGL(); - - // These two functions take single precision float rather than double - // precision float parameters in GLES. - ::gfx::g_driver_gl.fn.glClearDepthFn = MarshalClearDepthToClearDepthf; - ::gfx::g_driver_gl.fn.glDepthRangeFn = MarshalDepthRangeToDepthRangef; - break; - case kGLImplementationMockGL: { - SetGLImplementation(kGLImplementationMockGL); - InitializeStaticGLBindingsGL(); - break; - } - default: - NOTIMPLEMENTED() - << "Unsupported GL type for Ozone surface implementation"; - return false; - } - - return true; -} - -bool InitializeDynamicGLBindings(GLImplementation implementation, - GLContext* context) { - switch (implementation) { - case kGLImplementationOSMesaGL: - InitializeDynamicGLBindingsGL(context); - InitializeDynamicGLBindingsOSMESA(context); - break; - case kGLImplementationEGLGLES2: - InitializeDynamicGLBindingsGL(context); - InitializeDynamicGLBindingsEGL(context); - break; - case kGLImplementationMockGL: - if (!context) { - scoped_refptr<GLContextStubWithExtensions> mock_context( - new GLContextStubWithExtensions()); - mock_context->SetGLVersionString("3.0"); - InitializeDynamicGLBindingsGL(mock_context.get()); - } else - InitializeDynamicGLBindingsGL(context); - break; - default: - return false; - } - - return true; -} - -void InitializeDebugGLBindings() { -} - -void ClearGLBindings() { - ClearGLBindingsEGL(); - ClearGLBindingsGL(); - SetGLImplementation(kGLImplementationNone); - UnloadGLNativeLibraries(); -} - -bool GetGLWindowSystemBindingInfo(GLWindowSystemBindingInfo* info) { - switch (GetGLImplementation()) { - case kGLImplementationEGLGLES2: - return GetGLWindowSystemBindingInfoEGL(info); - default: - return false; - } - return false; -} - -} // namespace gfx
diff --git a/ui/gl/gl_surface_egl.cc b/ui/gl/gl_surface_egl.cc index 1b670e1..5e849ac 100644 --- a/ui/gl/gl_surface_egl.cc +++ b/ui/gl/gl_surface_egl.cc
@@ -29,10 +29,6 @@ } #endif -#if defined (USE_OZONE) -#include "ui/ozone/public/surface_factory_ozone.h" -#endif - #if !defined(EGL_FIXED_SIZE_ANGLE) #define EGL_FIXED_SIZE_ANGLE 0x3201 #endif
diff --git a/ui/gl/gl_surface_ozone.cc b/ui/gl/gl_surface_ozone.cc deleted file mode 100644 index eecd064..0000000 --- a/ui/gl/gl_surface_ozone.cc +++ /dev/null
@@ -1,266 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/gl/gl_surface.h" - -#include "base/logging.h" -#include "base/memory/ref_counted.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/gl/gl_context.h" -#include "ui/gl/gl_image.h" -#include "ui/gl/gl_implementation.h" -#include "ui/gl/gl_surface_egl.h" -#include "ui/gl/gl_surface_osmesa.h" -#include "ui/gl/gl_surface_stub.h" -#include "ui/gl/scoped_make_current.h" -#include "ui/ozone/public/surface_factory_ozone.h" -#include "ui/ozone/public/surface_ozone_egl.h" - -namespace gfx { - -namespace { - -// A thin wrapper around GLSurfaceEGL that owns the EGLNativeWindow -class GL_EXPORT GLSurfaceOzoneEGL : public NativeViewGLSurfaceEGL { - public: - GLSurfaceOzoneEGL(scoped_ptr<ui::SurfaceOzoneEGL> ozone_surface, - AcceleratedWidget widget) - : NativeViewGLSurfaceEGL(ozone_surface->GetNativeWindow()), - ozone_surface_(ozone_surface.Pass()), - widget_(widget) {} - - bool Initialize() override { - return Initialize(ozone_surface_->CreateVSyncProvider()); - } - bool Resize(const gfx::Size& size) override { - if (!ozone_surface_->ResizeNativeWindow(size)) { - if (!ReinitializeNativeSurface() || - !ozone_surface_->ResizeNativeWindow(size)) - return false; - } - - return NativeViewGLSurfaceEGL::Resize(size); - } - bool SwapBuffers() override { - if (!NativeViewGLSurfaceEGL::SwapBuffers()) - return false; - - return ozone_surface_->OnSwapBuffers(); - } - bool ScheduleOverlayPlane(int z_order, - OverlayTransform transform, - GLImage* image, - const Rect& bounds_rect, - const RectF& crop_rect) override { - return image->ScheduleOverlayPlane( - widget_, z_order, transform, bounds_rect, crop_rect); - } - - private: - using NativeViewGLSurfaceEGL::Initialize; - - ~GLSurfaceOzoneEGL() override { - Destroy(); // EGL surface must be destroyed before SurfaceOzone - } - - bool ReinitializeNativeSurface() { - scoped_ptr<ui::ScopedMakeCurrent> scoped_make_current; - GLContext* current_context = GLContext::GetCurrent(); - bool was_current = - current_context && current_context->IsCurrent(this); - if (was_current) { - scoped_make_current.reset( - new ui::ScopedMakeCurrent(current_context, this)); - } - - Destroy(); - ozone_surface_ = - ui::SurfaceFactoryOzone::GetInstance()->CreateEGLSurfaceForWidget( - widget_).Pass(); - if (!ozone_surface_) { - LOG(ERROR) << "Failed to create native surface."; - return false; - } - - window_ = ozone_surface_->GetNativeWindow(); - if (!Initialize()) { - LOG(ERROR) << "Failed to initialize."; - return false; - } - - return true; - } - - // The native surface. Deleting this is allowed to free the EGLNativeWindow. - scoped_ptr<ui::SurfaceOzoneEGL> ozone_surface_; - AcceleratedWidget widget_; - - DISALLOW_COPY_AND_ASSIGN(GLSurfaceOzoneEGL); -}; - -class GL_EXPORT GLSurfaceOzoneSurfaceless : public SurfacelessEGL { - public: - GLSurfaceOzoneSurfaceless(scoped_ptr<ui::SurfaceOzoneEGL> ozone_surface, - AcceleratedWidget widget) - : SurfacelessEGL(gfx::Size()), - ozone_surface_(ozone_surface.Pass()), - widget_(widget) {} - - bool Initialize() override { - if (!SurfacelessEGL::Initialize()) - return false; - vsync_provider_ = ozone_surface_->CreateVSyncProvider(); - if (!vsync_provider_) - return false; - return true; - } - bool Resize(const gfx::Size& size) override { - if (!ozone_surface_->ResizeNativeWindow(size)) - return false; - - return SurfacelessEGL::Resize(size); - } - bool SwapBuffers() override { - // TODO: this should be replaced by a fence when supported by the driver. - glFlush(); - return ozone_surface_->OnSwapBuffers(); - } - bool ScheduleOverlayPlane(int z_order, - OverlayTransform transform, - GLImage* image, - const Rect& bounds_rect, - const RectF& crop_rect) override { - return image->ScheduleOverlayPlane( - widget_, z_order, transform, bounds_rect, crop_rect); - } - bool IsOffscreen() override { return false; } - VSyncProvider* GetVSyncProvider() override { return vsync_provider_.get(); } - bool SupportsPostSubBuffer() override { return true; } - bool PostSubBuffer(int x, int y, int width, int height) override { - // The actual sub buffer handling is handled at higher layers. - SwapBuffers(); - return true; - } - bool SwapBuffersAsync(const SwapCompletionCallback& callback) override { - // TODO: this should be replaced by a fence when supported by the driver. - glFlush(); - return ozone_surface_->OnSwapBuffersAsync(callback); - } - bool PostSubBufferAsync(int x, - int y, - int width, - int height, - const SwapCompletionCallback& callback) override { - return SwapBuffersAsync(callback); - } - - private: - ~GLSurfaceOzoneSurfaceless() override { - Destroy(); // EGL surface must be destroyed before SurfaceOzone - } - - // The native surface. Deleting this is allowed to free the EGLNativeWindow. - scoped_ptr<ui::SurfaceOzoneEGL> ozone_surface_; - AcceleratedWidget widget_; - scoped_ptr<VSyncProvider> vsync_provider_; - - DISALLOW_COPY_AND_ASSIGN(GLSurfaceOzoneSurfaceless); -}; - -} // namespace - -// static -bool GLSurface::InitializeOneOffInternal() { - switch (GetGLImplementation()) { - case kGLImplementationEGLGLES2: - if (!GLSurfaceEGL::InitializeOneOff()) { - LOG(ERROR) << "GLSurfaceEGL::InitializeOneOff failed."; - return false; - } - - return true; - case kGLImplementationOSMesaGL: - case kGLImplementationMockGL: - return true; - default: - return false; - } -} - -// static -scoped_refptr<GLSurface> GLSurface::CreateViewGLSurface( - gfx::AcceleratedWidget window) { - if (GetGLImplementation() == kGLImplementationOSMesaGL) { - scoped_refptr<GLSurface> surface(new GLSurfaceOSMesaHeadless()); - if (!surface->Initialize()) - return NULL; - return surface; - } - DCHECK(GetGLImplementation() == kGLImplementationEGLGLES2); - if (window != kNullAcceleratedWidget) { - scoped_refptr<GLSurface> surface; - if (GLSurfaceEGL::IsEGLSurfacelessContextSupported() && - ui::SurfaceFactoryOzone::GetInstance() - ->CanShowPrimaryPlaneAsOverlay()) { - scoped_ptr<ui::SurfaceOzoneEGL> surface_ozone = - ui::SurfaceFactoryOzone::GetInstance() - ->CreateSurfacelessEGLSurfaceForWidget(window); - if (!surface_ozone) - return NULL; - surface = new GLSurfaceOzoneSurfaceless(surface_ozone.Pass(), window); - } else { - scoped_ptr<ui::SurfaceOzoneEGL> surface_ozone = - ui::SurfaceFactoryOzone::GetInstance()->CreateEGLSurfaceForWidget( - window); - if (!surface_ozone) - return NULL; - - surface = new GLSurfaceOzoneEGL(surface_ozone.Pass(), window); - } - if (!surface->Initialize()) - return NULL; - return surface; - } else { - scoped_refptr<GLSurface> surface = new GLSurfaceStub(); - if (surface->Initialize()) - return surface; - } - return NULL; -} - -// static -scoped_refptr<GLSurface> GLSurface::CreateOffscreenGLSurface( - const gfx::Size& size) { - switch (GetGLImplementation()) { - case kGLImplementationOSMesaGL: { - scoped_refptr<GLSurface> surface( - new GLSurfaceOSMesa(OSMesaSurfaceFormatBGRA, size)); - if (!surface->Initialize()) - return NULL; - - return surface; - } - case kGLImplementationEGLGLES2: { - scoped_refptr<GLSurface> surface; - if (GLSurfaceEGL::IsEGLSurfacelessContextSupported() && - (size.width() == 0 && size.height() == 0)) { - surface = new SurfacelessEGL(size); - } else - surface = new PbufferGLSurfaceEGL(size); - - if (!surface->Initialize()) - return NULL; - return surface; - } - default: - NOTREACHED(); - return NULL; - } -} - -EGLNativeDisplayType GetPlatformDefaultEGLNativeDisplay() { - return ui::SurfaceFactoryOzone::GetInstance()->GetNativeDisplay(); -} - -} // namespace gfx
diff --git a/ui/native_theme/BUILD.gn b/ui/native_theme/BUILD.gn deleted file mode 100644 index 66b74f6..0000000 --- a/ui/native_theme/BUILD.gn +++ /dev/null
@@ -1,50 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import("//build/config/ui.gni") - -component("native_theme") { - sources = [ - "common_theme.cc", - "common_theme.h", - "fallback_theme.cc", - "fallback_theme.h", - "native_theme.cc", - "native_theme.h", - "native_theme_base.cc", - "native_theme_base.h", - "native_theme_observer.cc", - "native_theme_observer.h", - "native_theme_switches.cc", - "native_theme_switches.h", - ] - - if (use_aura) { - sources += [ - "native_theme_aura.cc", - "native_theme_aura.h", - ] - } - - if (is_win) { - sources += [ - "native_theme_aurawin.cc", - "native_theme_aurawin.h", - "native_theme_win.cc", - "native_theme_win.h", - ] - } - - defines = [ "NATIVE_THEME_IMPLEMENTATION" ] - - deps = [ - "//base", - "//base/third_party/dynamic_annotations", - "//skia", - "//ui/base", - "//ui/gfx", - "//ui/gfx/geometry", - "//ui/resources", - ] -}
diff --git a/ui/native_theme/DEPS b/ui/native_theme/DEPS deleted file mode 100644 index 79d347c..0000000 --- a/ui/native_theme/DEPS +++ /dev/null
@@ -1,7 +0,0 @@ -include_rules = [ - "+skia/ext", - "+third_party/skia", - "+ui/base", - "+ui/gfx", - "+ui/resources/grit/ui_resources.h", -]
diff --git a/ui/native_theme/common_theme.cc b/ui/native_theme/common_theme.cc deleted file mode 100644 index f57fe4a..0000000 --- a/ui/native_theme/common_theme.cc +++ /dev/null
@@ -1,217 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/native_theme/common_theme.h" - -#include "base/logging.h" -#include "third_party/skia/include/core/SkCanvas.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/color_utils.h" -#include "ui/gfx/image/image_skia.h" -#include "ui/gfx/rect.h" -#include "ui/gfx/skia_util.h" -#include "ui/gfx/sys_color_change_listener.h" -#include "ui/resources/grit/ui_resources.h" - -namespace { - -// Theme colors returned by GetSystemColor(). - -// MenuItem: -const SkColor kMenuBackgroundColor = SK_ColorWHITE; -const SkColor kMenuHighlightBackgroundColor = SkColorSetRGB(0x42, 0x81, 0xF4); -const SkColor kMenuInvertedSchemeHighlightBackgroundColor = - SkColorSetRGB(48, 48, 48); -const SkColor kMenuBorderColor = SkColorSetRGB(0xBA, 0xBA, 0xBA); -const SkColor kEnabledMenuButtonBorderColor = SkColorSetARGB(36, 0, 0, 0); -const SkColor kFocusedMenuButtonBorderColor = SkColorSetARGB(72, 0, 0, 0); -const SkColor kHoverMenuButtonBorderColor = SkColorSetARGB(72, 0, 0, 0); -const SkColor kMenuSeparatorColor = SkColorSetRGB(0xE9, 0xE9, 0xE9); -const SkColor kEnabledMenuItemForegroundColor = SK_ColorBLACK; -const SkColor kDisabledMenuItemForegroundColor = SkColorSetRGB(161, 161, 146); -const SkColor kHoverMenuItemBackgroundColor = - SkColorSetARGB(204, 255, 255, 255); -// Button: -const SkColor kButtonHoverBackgroundColor = SkColorSetRGB(0xEA, 0xEA, 0xEA); -const SkColor kBlueButtonEnabledColor = SK_ColorWHITE; -const SkColor kBlueButtonDisabledColor = SK_ColorWHITE; -const SkColor kBlueButtonPressedColor = SK_ColorWHITE; -const SkColor kBlueButtonHoverColor = SK_ColorWHITE; -const SkColor kBlueButtonShadowColor = SkColorSetRGB(0x53, 0x8C, 0xEA); - -} // namespace - -namespace ui { - -bool CommonThemeGetSystemColor(NativeTheme::ColorId color_id, SkColor* color) { - switch (color_id) { - // MenuItem - case NativeTheme::kColorId_MenuBorderColor: - *color = kMenuBorderColor; - break; - case NativeTheme::kColorId_EnabledMenuButtonBorderColor: - *color = kEnabledMenuButtonBorderColor; - break; - case NativeTheme::kColorId_FocusedMenuButtonBorderColor: - *color = kFocusedMenuButtonBorderColor; - break; - case NativeTheme::kColorId_HoverMenuButtonBorderColor: - *color = kHoverMenuButtonBorderColor; - break; - case NativeTheme::kColorId_MenuSeparatorColor: - *color = kMenuSeparatorColor; - break; - case NativeTheme::kColorId_MenuBackgroundColor: - *color = kMenuBackgroundColor; - break; - case NativeTheme::kColorId_FocusedMenuItemBackgroundColor: - *color = kMenuHighlightBackgroundColor; - break; - case NativeTheme::kColorId_HoverMenuItemBackgroundColor: - *color = kHoverMenuItemBackgroundColor; - break; - case NativeTheme::kColorId_EnabledMenuItemForegroundColor: - *color = kEnabledMenuItemForegroundColor; - break; - case NativeTheme::kColorId_DisabledMenuItemForegroundColor: - *color = kDisabledMenuItemForegroundColor; - break; - case NativeTheme::kColorId_DisabledEmphasizedMenuItemForegroundColor: - *color = SK_ColorBLACK; - break; - case NativeTheme::kColorId_SelectedMenuItemForegroundColor: - *color = SK_ColorWHITE; - break; - case NativeTheme::kColorId_ButtonDisabledColor: - *color = kDisabledMenuItemForegroundColor; - break; - // Button - case NativeTheme::kColorId_ButtonHoverBackgroundColor: - *color = kButtonHoverBackgroundColor; - break; - case NativeTheme::kColorId_BlueButtonEnabledColor: - *color = kBlueButtonEnabledColor; - break; - case NativeTheme::kColorId_BlueButtonDisabledColor: - *color = kBlueButtonDisabledColor; - break; - case NativeTheme::kColorId_BlueButtonPressedColor: - *color = kBlueButtonPressedColor; - break; - case NativeTheme::kColorId_BlueButtonHoverColor: - *color = kBlueButtonHoverColor; - break; - case NativeTheme::kColorId_BlueButtonShadowColor: - *color = kBlueButtonShadowColor; - break; - default: - return false; - } - - if (gfx::IsInvertedColorScheme()) { - switch (color_id) { - case NativeTheme::kColorId_FocusedMenuItemBackgroundColor: - *color = kMenuInvertedSchemeHighlightBackgroundColor; - break; - default: - *color = color_utils::InvertColor(*color); - } - } - return true; -} - -gfx::Size CommonThemeGetPartSize(NativeTheme::Part part, - NativeTheme::State state, - const NativeTheme::ExtraParams& extra) { - gfx::Size size; - switch (part) { - case NativeTheme::kComboboxArrow: - return ui::ResourceBundle::GetSharedInstance().GetImageNamed( - IDR_MENU_DROPARROW).Size(); - - case NativeTheme::kMenuCheck: { - const gfx::ImageSkia* check = - ui::ResourceBundle::GetSharedInstance().GetImageNamed( - IDR_MENU_CHECK_CHECKED).ToImageSkia(); - size.SetSize(check->width(), check->height()); - break; - } - default: - break; - } - - return size; -} - -void CommonThemePaintComboboxArrow(SkCanvas* canvas, const gfx::Rect& rect) { - gfx::ImageSkia* arrow = ui::ResourceBundle::GetSharedInstance(). - GetImageSkiaNamed(IDR_MENU_DROPARROW); - CommonThemeCreateCanvas(canvas)->DrawImageInt(*arrow, rect.x(), rect.y()); -} - -void CommonThemePaintMenuSeparator( - SkCanvas* canvas, - const gfx::Rect& rect, - const NativeTheme::MenuSeparatorExtraParams& extra) { - SkColor color; - CommonThemeGetSystemColor(NativeTheme::kColorId_MenuSeparatorColor, &color); - SkPaint paint; - paint.setColor(kMenuSeparatorColor); - int position_y = rect.y() + rect.height() / 2; - canvas->drawLine(rect.x(), position_y, rect.right(), position_y, paint); -} - -void CommonThemePaintMenuGutter(SkCanvas* canvas, const gfx::Rect& rect) { - SkColor color; - CommonThemeGetSystemColor(NativeTheme::kColorId_MenuSeparatorColor, &color); - SkPaint paint; - paint.setColor(kMenuSeparatorColor); - int position_x = rect.x() + rect.width() / 2; - canvas->drawLine(position_x, rect.y(), position_x, rect.bottom(), paint); -} - -void CommonThemePaintMenuBackground(SkCanvas* canvas, const gfx::Rect& rect) { - SkColor color; - CommonThemeGetSystemColor(NativeTheme::kColorId_MenuBackgroundColor, &color); - SkPaint paint; - paint.setColor(color); - canvas->drawRect(gfx::RectToSkRect(rect), paint); -} - -void CommonThemePaintMenuItemBackground(SkCanvas* canvas, - NativeTheme::State state, - const gfx::Rect& rect) { - SkColor color; - SkPaint paint; - switch (state) { - case NativeTheme::kNormal: - case NativeTheme::kDisabled: - CommonThemeGetSystemColor(NativeTheme::kColorId_MenuBackgroundColor, - &color); - paint.setColor(color); - break; - case NativeTheme::kHovered: - CommonThemeGetSystemColor( - NativeTheme::kColorId_FocusedMenuItemBackgroundColor, &color); - paint.setColor(color); - break; - default: - NOTREACHED() << "Invalid state " << state; - break; - } - canvas->drawRect(gfx::RectToSkRect(rect), paint); -} - -// static -scoped_ptr<gfx::Canvas> CommonThemeCreateCanvas(SkCanvas* sk_canvas) { - // TODO(pkotwicz): Do something better and don't infer device - // scale factor from canvas scale. - SkMatrix m = sk_canvas->getTotalMatrix(); - float device_scale = static_cast<float>(SkScalarAbs(m.getScaleX())); - return scoped_ptr<gfx::Canvas>( - gfx::Canvas::CreateCanvasWithoutScaling(sk_canvas, device_scale)); -} - -} // namespace ui
diff --git a/ui/native_theme/common_theme.h b/ui/native_theme/common_theme.h deleted file mode 100644 index a8db60f..0000000 --- a/ui/native_theme/common_theme.h +++ /dev/null
@@ -1,57 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_NATIVE_THEME_COMMON_THEME_H_ -#define UI_NATIVE_THEME_COMMON_THEME_H_ - -#include "base/memory/scoped_ptr.h" -#include "ui/native_theme/native_theme.h" - -class SkCanvas; - -namespace gfx { -class Canvas; -} - -namespace ui { - -// Drawing code that is common for all platforms. - -// Returns true and |color| if |color_id| is found, or false otherwise. -bool NATIVE_THEME_EXPORT CommonThemeGetSystemColor( - NativeTheme::ColorId color_id, - SkColor* color); - -gfx::Size NATIVE_THEME_EXPORT CommonThemeGetPartSize( - NativeTheme::Part part, - NativeTheme::State state, - const NativeTheme::ExtraParams& extra); - -void NATIVE_THEME_EXPORT CommonThemePaintComboboxArrow( - SkCanvas* canvas, - const gfx::Rect& rect); - -void NATIVE_THEME_EXPORT CommonThemePaintMenuSeparator( - SkCanvas* canvas, - const gfx::Rect& rect, - const NativeTheme::MenuSeparatorExtraParams& extra); - -void NATIVE_THEME_EXPORT CommonThemePaintMenuGutter(SkCanvas* canvas, - const gfx::Rect& rect); - -void NATIVE_THEME_EXPORT CommonThemePaintMenuBackground(SkCanvas* canvas, - const gfx::Rect& rect); - -void NATIVE_THEME_EXPORT CommonThemePaintMenuItemBackground( - SkCanvas* canvas, - NativeTheme::State state, - const gfx::Rect& rect); - -// Creates a gfx::Canvas wrapping an SkCanvas. -scoped_ptr<gfx::Canvas> NATIVE_THEME_EXPORT CommonThemeCreateCanvas( - SkCanvas* sk_canvas); - -} // namespace ui - -#endif // UI_NATIVE_THEME_COMMON_THEME_H_
diff --git a/ui/native_theme/fallback_theme.cc b/ui/native_theme/fallback_theme.cc deleted file mode 100644 index 127243f..0000000 --- a/ui/native_theme/fallback_theme.cc +++ /dev/null
@@ -1,217 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/native_theme/fallback_theme.h" - -#include "base/basictypes.h" -#include "base/logging.h" -#include "ui/gfx/color_utils.h" -#include "ui/native_theme/common_theme.h" - -namespace ui { - -FallbackTheme::FallbackTheme() { -} - -FallbackTheme::~FallbackTheme() { -} - -SkColor FallbackTheme::GetSystemColor(ColorId color_id) const { - // This implementation returns hardcoded colors. - - static const SkColor kInvalidColorIdColor = SkColorSetRGB(255, 0, 128); - // Windows: - static const SkColor kWindowBackgroundColor = SK_ColorWHITE; - // Dialogs: - static const SkColor kDialogBackgroundColor = SkColorSetRGB(251, 251, 251); - // FocusableBorder: - static const SkColor kFocusedBorderColor = SkColorSetRGB(0x4D, 0x90, 0xFE); - static const SkColor kUnfocusedBorderColor = SkColorSetRGB(0xD9, 0xD9, 0xD9); - // Button: - static const SkColor kButtonBackgroundColor = SkColorSetRGB(0xDE, 0xDE, 0xDE); - static const SkColor kButtonEnabledColor = SkColorSetRGB(0x22, 0x22, 0x22); - static const SkColor kButtonHighlightColor = SkColorSetRGB(0, 0, 0); - static const SkColor kButtonHoverColor = kButtonEnabledColor; - // Label: - static const SkColor kLabelEnabledColor = kButtonEnabledColor; - static const SkColor kLabelBackgroundColor = SK_ColorWHITE; - // Textfield: - static const SkColor kTextfieldDefaultColor = SK_ColorBLACK; - static const SkColor kTextfieldDefaultBackground = SK_ColorWHITE; - static const SkColor kTextfieldReadOnlyColor = SK_ColorDKGRAY; - static const SkColor kTextfieldReadOnlyBackground = SK_ColorWHITE; - static const SkColor kTextfieldSelectionBackgroundFocused = - SkColorSetARGB(0x54, 0x60, 0xA8, 0xEB); - static const SkColor kTextfieldSelectionColor = - color_utils::AlphaBlend(SK_ColorBLACK, - kTextfieldSelectionBackgroundFocused, 0xdd); - // Tooltip - static const SkColor kTooltipBackground = 0xFFFFFFCC; - static const SkColor kTooltipTextColor = kLabelEnabledColor; - // Tree - static const SkColor kTreeBackground = SK_ColorWHITE; - static const SkColor kTreeTextColor = SK_ColorBLACK; - static const SkColor kTreeSelectedTextColor = SK_ColorBLACK; - static const SkColor kTreeSelectionBackgroundColor = - SkColorSetRGB(0xEE, 0xEE, 0xEE); - static const SkColor kTreeArrowColor = SkColorSetRGB(0x7A, 0x7A, 0x7A); - // Table - static const SkColor kTableBackground = SK_ColorWHITE; - static const SkColor kTableTextColor = SK_ColorBLACK; - static const SkColor kTableSelectedTextColor = SK_ColorBLACK; - static const SkColor kTableSelectionBackgroundColor = - SkColorSetRGB(0xEE, 0xEE, 0xEE); - static const SkColor kTableGroupingIndicatorColor = - SkColorSetRGB(0xCC, 0xCC, 0xCC); - // Results Tables - static const SkColor kResultsTableHoveredBackground = - color_utils::AlphaBlend(kTextfieldSelectionBackgroundFocused, - kTextfieldDefaultBackground, 0x40); - static const SkColor kResultsTableNormalText = color_utils::AlphaBlend( - SK_ColorBLACK, kTextfieldDefaultBackground, 0xDD); - static const SkColor kResultsTableHoveredText = color_utils::AlphaBlend( - SK_ColorBLACK, kResultsTableHoveredBackground, 0xDD); - static const SkColor kResultsTableSelectedText = color_utils::AlphaBlend( - SK_ColorBLACK, kTextfieldSelectionBackgroundFocused, 0xDD); - static const SkColor kResultsTableNormalDimmedText = color_utils::AlphaBlend( - SK_ColorBLACK, kTextfieldDefaultBackground, 0xBB); - static const SkColor kResultsTableHoveredDimmedText = color_utils::AlphaBlend( - SK_ColorBLACK, kResultsTableHoveredBackground, 0xBB); - static const SkColor kResultsTableSelectedDimmedText = - color_utils::AlphaBlend( - SK_ColorBLACK, kTextfieldSelectionBackgroundFocused, 0xBB); - static const SkColor kResultsTableSelectedOrHoveredUrl = - SkColorSetARGB(0xff, 0x00, 0x66, 0x22); - static const SkColor kResultsTableNormalDivider = color_utils::AlphaBlend( - kResultsTableNormalText, kTextfieldDefaultBackground, 0x34); - static const SkColor kResultsTableHoveredDivider = color_utils::AlphaBlend( - kResultsTableHoveredText, kResultsTableHoveredBackground, 0x34); - static const SkColor kResultsTabSelectedDivider = color_utils::AlphaBlend( - kResultsTableSelectedText, kTextfieldSelectionBackgroundFocused, 0x34); - - SkColor color; - if (CommonThemeGetSystemColor(color_id, &color)) - return color; - - switch (color_id) { - // Windows - case kColorId_WindowBackground: - return kWindowBackgroundColor; - - // Dialogs - case kColorId_DialogBackground: - return kDialogBackgroundColor; - - // FocusableBorder - case kColorId_FocusedBorderColor: - return kFocusedBorderColor; - case kColorId_UnfocusedBorderColor: - return kUnfocusedBorderColor; - - // Button - case kColorId_ButtonBackgroundColor: - return kButtonBackgroundColor; - case kColorId_ButtonEnabledColor: - return kButtonEnabledColor; - case kColorId_ButtonHighlightColor: - return kButtonHighlightColor; - case kColorId_ButtonHoverColor: - return kButtonHoverColor; - - // Label - case kColorId_LabelEnabledColor: - return kLabelEnabledColor; - case kColorId_LabelDisabledColor: - return GetSystemColor(kColorId_ButtonDisabledColor); - case kColorId_LabelBackgroundColor: - return kLabelBackgroundColor; - - // Textfield - case kColorId_TextfieldDefaultColor: - return kTextfieldDefaultColor; - case kColorId_TextfieldDefaultBackground: - return kTextfieldDefaultBackground; - case kColorId_TextfieldReadOnlyColor: - return kTextfieldReadOnlyColor; - case kColorId_TextfieldReadOnlyBackground: - return kTextfieldReadOnlyBackground; - case kColorId_TextfieldSelectionColor: - return kTextfieldSelectionColor; - case kColorId_TextfieldSelectionBackgroundFocused: - return kTextfieldSelectionBackgroundFocused; - - // Tooltip - case kColorId_TooltipBackground: - return kTooltipBackground; - case kColorId_TooltipText: - return kTooltipTextColor; - - // Tree - case kColorId_TreeBackground: - return kTreeBackground; - case kColorId_TreeText: - return kTreeTextColor; - case kColorId_TreeSelectedText: - case kColorId_TreeSelectedTextUnfocused: - return kTreeSelectedTextColor; - case kColorId_TreeSelectionBackgroundFocused: - case kColorId_TreeSelectionBackgroundUnfocused: - return kTreeSelectionBackgroundColor; - case kColorId_TreeArrow: - return kTreeArrowColor; - - // Table - case kColorId_TableBackground: - return kTableBackground; - case kColorId_TableText: - return kTableTextColor; - case kColorId_TableSelectedText: - case kColorId_TableSelectedTextUnfocused: - return kTableSelectedTextColor; - case kColorId_TableSelectionBackgroundFocused: - case kColorId_TableSelectionBackgroundUnfocused: - return kTableSelectionBackgroundColor; - case kColorId_TableGroupingIndicatorColor: - return kTableGroupingIndicatorColor; - - // Results Tables - case kColorId_ResultsTableNormalBackground: - return kTextfieldDefaultBackground; - case kColorId_ResultsTableHoveredBackground: - return kResultsTableHoveredBackground; - case kColorId_ResultsTableSelectedBackground: - return kTextfieldSelectionBackgroundFocused; - case kColorId_ResultsTableNormalText: - return kResultsTableNormalText; - case kColorId_ResultsTableHoveredText: - return kResultsTableHoveredText; - case kColorId_ResultsTableSelectedText: - return kResultsTableSelectedText; - case kColorId_ResultsTableNormalDimmedText: - return kResultsTableNormalDimmedText; - case kColorId_ResultsTableHoveredDimmedText: - return kResultsTableHoveredDimmedText; - case kColorId_ResultsTableSelectedDimmedText: - return kResultsTableSelectedDimmedText; - case kColorId_ResultsTableNormalUrl: - return kTextfieldSelectionColor; - case kColorId_ResultsTableHoveredUrl: - case kColorId_ResultsTableSelectedUrl: - return kResultsTableSelectedOrHoveredUrl; - case kColorId_ResultsTableNormalDivider: - return kResultsTableNormalDivider; - case kColorId_ResultsTableHoveredDivider: - return kResultsTableHoveredDivider; - case kColorId_ResultsTableSelectedDivider: - return kResultsTabSelectedDivider; - - default: - NOTREACHED(); - break; - } - - return kInvalidColorIdColor; -} - -} // namespace ui
diff --git a/ui/native_theme/fallback_theme.h b/ui/native_theme/fallback_theme.h deleted file mode 100644 index ca2cb48..0000000 --- a/ui/native_theme/fallback_theme.h +++ /dev/null
@@ -1,29 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_NATIVE_THEME_FALLBACK_THEME_H_ -#define UI_NATIVE_THEME_FALLBACK_THEME_H_ - -#include "ui/native_theme/native_theme_base.h" - -namespace ui { - -// This theme can draw UI controls on every platform. This is only used when -// zooming a web page and the native theme doesn't support scaling. -class NATIVE_THEME_EXPORT FallbackTheme : public NativeThemeBase { - public: - FallbackTheme(); - ~FallbackTheme() override; - - protected: - // Overridden from NativeThemeBase: - SkColor GetSystemColor(ColorId color_id) const override; - - private: - DISALLOW_COPY_AND_ASSIGN(FallbackTheme); -}; - -} // namespace ui - -#endif // UI_NATIVE_THEME_FALLBACK_THEME_H_
diff --git a/ui/native_theme/native_theme.cc b/ui/native_theme/native_theme.cc deleted file mode 100644 index 94a1eef..0000000 --- a/ui/native_theme/native_theme.cc +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/native_theme/native_theme.h" - -#include "ui/native_theme/native_theme_observer.h" - -namespace ui { - -void NativeTheme::SetScrollbarColors(unsigned inactive_color, - unsigned active_color, - unsigned track_color) { - thumb_inactive_color_ = inactive_color; - thumb_active_color_ = active_color; - track_color_ = track_color; -} - -// NativeTheme::instance() is implemented in the platform specific source files, -// such as native_theme_win.cc or native_theme_linux.cc - -void NativeTheme::AddObserver(NativeThemeObserver* observer) { - native_theme_observers_.AddObserver(observer); -} - -void NativeTheme::RemoveObserver(NativeThemeObserver* observer) { - native_theme_observers_.RemoveObserver(observer); -} - -void NativeTheme::NotifyObservers() { - FOR_EACH_OBSERVER(NativeThemeObserver, native_theme_observers_, - OnNativeThemeUpdated(this)); -} - -NativeTheme::NativeTheme() - : thumb_inactive_color_(0xeaeaea), - thumb_active_color_(0xf4f4f4), - track_color_(0xd3d3d3) { -} - -NativeTheme::~NativeTheme() {} - -} // namespace ui
diff --git a/ui/native_theme/native_theme.gyp b/ui/native_theme/native_theme.gyp deleted file mode 100644 index 7791468..0000000 --- a/ui/native_theme/native_theme.gyp +++ /dev/null
@@ -1,66 +0,0 @@ -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -{ - 'variables': { - 'chromium_code': 1, - }, - 'targets': [ - { - 'target_name': 'native_theme', - 'type': '<(component)', - 'dependencies': [ - '../../base/base.gyp:base', - '../../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', - '../../skia/skia.gyp:skia', - '../base/ui_base.gyp:ui_base', - '../gfx/gfx.gyp:gfx', - '../gfx/gfx.gyp:gfx_geometry', - '../resources/ui_resources.gyp:ui_resources', - ], - 'defines': [ - 'NATIVE_THEME_IMPLEMENTATION', - ], - 'sources': [ - 'common_theme.cc', - 'common_theme.h', - 'fallback_theme.cc', - 'fallback_theme.h', - 'native_theme.cc', - 'native_theme.h', - 'native_theme_android.cc', - 'native_theme_android.h', - 'native_theme_aura.cc', - 'native_theme_aura.h', - 'native_theme_aurawin.cc', - 'native_theme_aurawin.h', - 'native_theme_base.cc', - 'native_theme_base.h', - 'native_theme_mac.h', - 'native_theme_mac.mm', - 'native_theme_observer.cc', - 'native_theme_observer.h', - 'native_theme_switches.cc', - 'native_theme_switches.h', - 'native_theme_win.cc', - 'native_theme_win.h', - ], - }, - { - 'target_name': 'native_theme_unittests', - 'type': '<(gtest_target_type)', - 'dependencies': [ - '../../base/base.gyp:base', - '../../base/base.gyp:test_support_base', - '../../skia/skia.gyp:skia', - '../../testing/gtest.gyp:gtest', - 'native_theme', - ], - 'sources': [ - '../../base/test/run_all_unittests.cc', - 'native_theme_mac_unittest.cc', - ], - }, - ], -}
diff --git a/ui/native_theme/native_theme.h b/ui/native_theme/native_theme.h deleted file mode 100644 index af6febf..0000000 --- a/ui/native_theme/native_theme.h +++ /dev/null
@@ -1,361 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_NATIVE_THEME_NATIVE_THEME_H_ -#define UI_NATIVE_THEME_NATIVE_THEME_H_ - -#include "base/observer_list.h" -#include "third_party/skia/include/core/SkColor.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/native_theme/native_theme_export.h" - -class SkCanvas; - -namespace gfx { -class Rect; -class Size; -} - -namespace ui { - -class NativeThemeObserver; - -// This class supports drawing UI controls (like buttons, text fields, lists, -// comboboxes, etc) that look like the native UI controls of the underlying -// platform, such as Windows or Linux. It also supplies default colors for -// dialog box backgrounds, etc., which are obtained from the system theme where -// possible. -// -// The supported control types are listed in the Part enum. These parts can be -// in any state given by the State enum, where the actual definition of the -// state is part-specific. The supported colors are listed in the ColorId enum. -// -// Some parts require more information than simply the state in order to be -// drawn correctly, and this information is given to the Paint() method via the -// ExtraParams union. Each part that requires more information has its own -// field in the union. -// -// NativeTheme also supports getting the default size of a given part with -// the GetPartSize() method. -class NATIVE_THEME_EXPORT NativeTheme { - public: - // The part to be painted / sized. - enum Part { - kComboboxArrow, - kCheckbox, - kInnerSpinButton, - kMenuList, - kMenuCheck, - kMenuCheckBackground, - kMenuPopupArrow, - kMenuPopupBackground, - kMenuPopupGutter, - kMenuPopupSeparator, - kMenuItemBackground, - kProgressBar, - kPushButton, - kRadio, - - // The order of the arrow enums is important, do not change without also - // changing the code in platform implementations. - kScrollbarDownArrow, - kScrollbarLeftArrow, - kScrollbarRightArrow, - kScrollbarUpArrow, - - kScrollbarHorizontalThumb, - kScrollbarVerticalThumb, - kScrollbarHorizontalTrack, - kScrollbarVerticalTrack, - kScrollbarHorizontalGripper, - kScrollbarVerticalGripper, - // The corner is drawn when there is both a horizontal and vertical - // scrollbar. - kScrollbarCorner, - kSliderTrack, - kSliderThumb, - kTabPanelBackground, - kTextField, - kTrackbarThumb, - kTrackbarTrack, - kWindowResizeGripper, - kMaxPart, - }; - - // The state of the part. - enum State { - // IDs defined as specific values for use in arrays. - kDisabled = 0, - kHovered = 1, - kNormal = 2, - kPressed = 3, - kNumStates = kPressed + 1, - }; - - // Each structure below holds extra information needed when painting a given - // part. - - struct ButtonExtraParams { - bool checked; - bool indeterminate; // Whether the button state is indeterminate. - bool is_default; // Whether the button is default button. - bool is_focused; - bool has_border; - int classic_state; // Used on Windows when uxtheme is not available. - SkColor background_color; - }; - - struct InnerSpinButtonExtraParams { - bool spin_up; - bool read_only; - int classic_state; // Used on Windows when uxtheme is not available. - }; - - struct MenuArrowExtraParams { - bool pointing_right; - // Used for the disabled state to indicate if the item is both disabled and - // selected. - bool is_selected; - }; - - struct MenuCheckExtraParams { - bool is_radio; - // Used for the disabled state to indicate if the item is both disabled and - // selected. - bool is_selected; - }; - - struct MenuItemExtraParams { - bool is_selected; - }; - - struct MenuListExtraParams { - bool has_border; - bool has_border_radius; - int arrow_x; - int arrow_y; - SkColor background_color; - int classic_state; // Used on Windows when uxtheme is not available. - }; - - struct MenuSeparatorExtraParams { - bool has_gutter; - }; - - struct MenuBackgroundExtraParams { - int corner_radius; - }; - - struct ProgressBarExtraParams { - double animated_seconds; - bool determinate; - int value_rect_x; - int value_rect_y; - int value_rect_width; - int value_rect_height; - }; - - struct ScrollbarArrowExtraParams { - bool is_hovering; - }; - - struct ScrollbarTrackExtraParams { - bool is_upper; - int track_x; - int track_y; - int track_width; - int track_height; - int classic_state; // Used on Windows when uxtheme is not available. - }; - - struct ScrollbarThumbExtraParams { - bool is_hovering; - }; - - struct SliderExtraParams { - bool vertical; - bool in_drag; - }; - - struct TextFieldExtraParams { - bool is_text_area; - bool is_listbox; - SkColor background_color; - bool is_read_only; - bool is_focused; - bool fill_content_area; - bool draw_edges; - int classic_state; // Used on Windows when uxtheme is not available. - }; - - struct TrackbarExtraParams { - bool vertical; - int classic_state; // Used on Windows when uxtheme is not available. - }; - - union ExtraParams { - ButtonExtraParams button; - InnerSpinButtonExtraParams inner_spin; - MenuArrowExtraParams menu_arrow; - MenuCheckExtraParams menu_check; - MenuItemExtraParams menu_item; - MenuListExtraParams menu_list; - MenuSeparatorExtraParams menu_separator; - MenuBackgroundExtraParams menu_background; - ProgressBarExtraParams progress_bar; - ScrollbarArrowExtraParams scrollbar_arrow; - ScrollbarTrackExtraParams scrollbar_track; - ScrollbarThumbExtraParams scrollbar_thumb; - SliderExtraParams slider; - TextFieldExtraParams text_field; - TrackbarExtraParams trackbar; - }; - - // Return the size of the part. - virtual gfx::Size GetPartSize(Part part, - State state, - const ExtraParams& extra) const = 0; - - // Paint the part to the canvas. - virtual void Paint(SkCanvas* canvas, - Part part, - State state, - const gfx::Rect& rect, - const ExtraParams& extra) const = 0; - - // Paint part during state transition, used for overlay scrollbar state - // transition animation. - virtual void PaintStateTransition(SkCanvas* canvas, - Part part, - State startState, - State endState, - double progress, - const gfx::Rect& rect) const { } - - // Supports theme specific colors. - void SetScrollbarColors(unsigned inactive_color, - unsigned active_color, - unsigned track_color); - - // Colors for GetSystemColor(). - enum ColorId { - // Windows - kColorId_WindowBackground, - // Dialogs - kColorId_DialogBackground, - // FocusableBorder - kColorId_FocusedBorderColor, - kColorId_UnfocusedBorderColor, - // Button - kColorId_ButtonBackgroundColor, - kColorId_ButtonEnabledColor, - kColorId_ButtonDisabledColor, - kColorId_ButtonHighlightColor, - kColorId_ButtonHoverColor, - kColorId_ButtonHoverBackgroundColor, - kColorId_BlueButtonEnabledColor, - kColorId_BlueButtonDisabledColor, - kColorId_BlueButtonPressedColor, - kColorId_BlueButtonHoverColor, - kColorId_BlueButtonShadowColor, - // MenuItem - kColorId_EnabledMenuItemForegroundColor, - kColorId_DisabledMenuItemForegroundColor, - kColorId_DisabledEmphasizedMenuItemForegroundColor, - kColorId_SelectedMenuItemForegroundColor, - kColorId_FocusedMenuItemBackgroundColor, - kColorId_HoverMenuItemBackgroundColor, - kColorId_MenuSeparatorColor, - kColorId_MenuBackgroundColor, - kColorId_MenuBorderColor, - // MenuButton - buttons in wrench menu - kColorId_EnabledMenuButtonBorderColor, - kColorId_FocusedMenuButtonBorderColor, - kColorId_HoverMenuButtonBorderColor, - // Label - kColorId_LabelEnabledColor, - kColorId_LabelDisabledColor, - kColorId_LabelBackgroundColor, - // Textfield - kColorId_TextfieldDefaultColor, - kColorId_TextfieldDefaultBackground, - kColorId_TextfieldReadOnlyColor, - kColorId_TextfieldReadOnlyBackground, - kColorId_TextfieldSelectionColor, - kColorId_TextfieldSelectionBackgroundFocused, - // Tooltip - kColorId_TooltipBackground, - kColorId_TooltipText, - // Tree - kColorId_TreeBackground, - kColorId_TreeText, - kColorId_TreeSelectedText, - kColorId_TreeSelectedTextUnfocused, - kColorId_TreeSelectionBackgroundFocused, - kColorId_TreeSelectionBackgroundUnfocused, - kColorId_TreeArrow, - // Table - kColorId_TableBackground, - kColorId_TableText, - kColorId_TableSelectedText, - kColorId_TableSelectedTextUnfocused, - kColorId_TableSelectionBackgroundFocused, - kColorId_TableSelectionBackgroundUnfocused, - kColorId_TableGroupingIndicatorColor, - // Results Tables, such as the chrome omnibox. - kColorId_ResultsTableNormalBackground, - kColorId_ResultsTableHoveredBackground, - kColorId_ResultsTableSelectedBackground, - kColorId_ResultsTableNormalText, - kColorId_ResultsTableHoveredText, - kColorId_ResultsTableSelectedText, - kColorId_ResultsTableNormalDimmedText, - kColorId_ResultsTableHoveredDimmedText, - kColorId_ResultsTableSelectedDimmedText, - kColorId_ResultsTableNormalUrl, - kColorId_ResultsTableHoveredUrl, - kColorId_ResultsTableSelectedUrl, - kColorId_ResultsTableNormalDivider, - kColorId_ResultsTableHoveredDivider, - kColorId_ResultsTableSelectedDivider, - // TODO(benrg): move other hardcoded colors here. - - kColorId_NumColors, - }; - - // Return a color from the system theme. - virtual SkColor GetSystemColor(ColorId color_id) const = 0; - - // Returns a shared instance of the native theme. - // The returned object should not be deleted by the caller. This function - // is not thread safe and should only be called from the UI thread. - // Each port of NativeTheme should provide its own implementation of this - // function, returning the port's subclass. - static NativeTheme* instance(); - - // Add or remove observers to be notified when the native theme changes. - void AddObserver(NativeThemeObserver* observer); - void RemoveObserver(NativeThemeObserver* observer); - - // Notify observers of native theme changes. - void NotifyObservers(); - - protected: - NativeTheme(); - virtual ~NativeTheme(); - - unsigned int thumb_inactive_color_; - unsigned int thumb_active_color_; - unsigned int track_color_; - - private: - // Observers to notify when the native theme changes. - ObserverList<NativeThemeObserver> native_theme_observers_; - - DISALLOW_COPY_AND_ASSIGN(NativeTheme); -}; - -} // namespace ui - -#endif // UI_NATIVE_THEME_NATIVE_THEME_H_
diff --git a/ui/native_theme/native_theme_aura.cc b/ui/native_theme/native_theme_aura.cc deleted file mode 100644 index 362ff99..0000000 --- a/ui/native_theme/native_theme_aura.cc +++ /dev/null
@@ -1,329 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/native_theme/native_theme_aura.h" - -#include <limits> - -#include "base/logging.h" -#include "ui/base/layout.h" -#include "ui/base/nine_image_painter_factory.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/image/image_skia.h" -#include "ui/gfx/nine_image_painter.h" -#include "ui/gfx/path.h" -#include "ui/gfx/rect.h" -#include "ui/gfx/size.h" -#include "ui/gfx/skbitmap_operations.h" -#include "ui/gfx/skia_util.h" -#include "ui/native_theme/common_theme.h" -#include "ui/native_theme/native_theme_switches.h" -#include "ui/resources/grit/ui_resources.h" - -using gfx::NineImagePainter; - -#define EMPTY_IMAGE_GRID { 0, 0, 0, 0, 0, 0, 0, 0, 0 } - -namespace ui { - -namespace { - -const int kScrollbarThumbImages[NativeTheme::kNumStates][9] = { - EMPTY_IMAGE_GRID, - IMAGE_GRID(IDR_SCROLLBAR_THUMB_BASE_HOVER), - IMAGE_GRID(IDR_SCROLLBAR_THUMB_BASE_NORMAL), - IMAGE_GRID(IDR_SCROLLBAR_THUMB_BASE_PRESSED) -}; - -const int kScrollbarArrowButtonImages[NativeTheme::kNumStates][9] = { - EMPTY_IMAGE_GRID, - IMAGE_GRID(IDR_SCROLLBAR_ARROW_BUTTON_BASE_HOVER), - IMAGE_GRID(IDR_SCROLLBAR_ARROW_BUTTON_BASE_NORMAL), - IMAGE_GRID(IDR_SCROLLBAR_ARROW_BUTTON_BASE_PRESSED) -}; - -const uint8 kScrollbarOverlayThumbFillAlphas[NativeTheme::kNumStates] = { - 0, // Does not matter, will not paint for disabled state. - 178, // Hover state, opacity 70%, alpha would be 0.7 * 255. - 140, // Normal state, opacity 55%, alpha would be 0.55 * 255. - 178 // Pressed state, opacity 70%, alpha would be 0.7 * 255. -}; - -const uint8 kScrollbarOverlayThumbStrokeAlphas[NativeTheme::kNumStates] = { - 0, // Does not matter, will not paint for disabled state. - 51, // Hover state, opacity 20%, alpha would be 0.2 * 255. - 38, // Normal state, opacity 15%, alpha would be 0.15 * 255. - 51 // Pressed state, opacity 20%, alpha would be 0.2 * 255. -}; - -const int kScrollbarOverlayThumbStrokeImages[9] = - IMAGE_GRID_NO_CENTER(IDR_SCROLLBAR_OVERLAY_THUMB_STROKE); - -const int kScrollbarOverlayThumbFillImages[9] = - IMAGE_GRID(IDR_SCROLLBAR_OVERLAY_THUMB_FILL); - -const int kScrollbarTrackImages[9] = IMAGE_GRID(IDR_SCROLLBAR_BASE); - -} // namespace - -#if !defined(OS_WIN) -// static -NativeTheme* NativeTheme::instance() { - return NativeThemeAura::instance(); -} - -// static -NativeThemeAura* NativeThemeAura::instance() { - CR_DEFINE_STATIC_LOCAL(NativeThemeAura, s_native_theme, ()); - return &s_native_theme; -} -#endif - -NativeThemeAura::NativeThemeAura() { - // We don't draw scrollbar buttons. -#if defined(OS_CHROMEOS) - set_scrollbar_button_length(0); -#endif - - // Images and alphas declarations assume the following order. - COMPILE_ASSERT(kDisabled == 0, states_unexpectedly_changed); - COMPILE_ASSERT(kHovered == 1, states_unexpectedly_changed); - COMPILE_ASSERT(kNormal == 2, states_unexpectedly_changed); - COMPILE_ASSERT(kPressed == 3, states_unexpectedly_changed); -} - -NativeThemeAura::~NativeThemeAura() { -} - -void NativeThemeAura::PaintMenuPopupBackground( - SkCanvas* canvas, - const gfx::Size& size, - const MenuBackgroundExtraParams& menu_background) const { - SkColor color = GetSystemColor(NativeTheme::kColorId_MenuBackgroundColor); - if (menu_background.corner_radius > 0) { - SkPaint paint; - paint.setStyle(SkPaint::kFill_Style); - paint.setFlags(SkPaint::kAntiAlias_Flag); - paint.setColor(color); - - gfx::Path path; - SkRect rect = SkRect::MakeWH(SkIntToScalar(size.width()), - SkIntToScalar(size.height())); - SkScalar radius = SkIntToScalar(menu_background.corner_radius); - SkScalar radii[8] = {radius, radius, radius, radius, - radius, radius, radius, radius}; - path.addRoundRect(rect, radii); - - canvas->drawPath(path, paint); - } else { - canvas->drawColor(color, SkXfermode::kSrc_Mode); - } -} - -void NativeThemeAura::PaintMenuItemBackground( - SkCanvas* canvas, - State state, - const gfx::Rect& rect, - const MenuListExtraParams& menu_list) const { - CommonThemePaintMenuItemBackground(canvas, state, rect); -} - -void NativeThemeAura::PaintArrowButton( - SkCanvas* gc, - const gfx::Rect& rect, - Part direction, - State state) const { - if (direction == kInnerSpinButton) { - FallbackTheme::PaintArrowButton(gc, rect, direction, state); - return; - } - PaintPainter(GetOrCreatePainter( - kScrollbarArrowButtonImages, state, - scrollbar_arrow_button_painters_), - gc, rect); - - // Aura-win uses slightly different arrow colors. - SkColor arrow_color = GetArrowColor(state); - switch (state) { - case kHovered: - case kNormal: - arrow_color = SkColorSetRGB(0x50, 0x50, 0x50); - break; - case kPressed: - arrow_color = SK_ColorWHITE; - default: - break; - } - PaintArrow(gc, rect, direction, arrow_color); -} - -void NativeThemeAura::PaintScrollbarTrack( - SkCanvas* sk_canvas, - Part part, - State state, - const ScrollbarTrackExtraParams& extra_params, - const gfx::Rect& rect) const { - // Overlay Scrollbar should never paint a scrollbar track. - DCHECK(!IsOverlayScrollbarEnabled()); - if (!scrollbar_track_painter_) - scrollbar_track_painter_ = CreateNineImagePainter(kScrollbarTrackImages); - PaintPainter(scrollbar_track_painter_.get(), sk_canvas, rect); -} - -void NativeThemeAura::PaintScrollbarThumb(SkCanvas* sk_canvas, - Part part, - State state, - const gfx::Rect& rect) const { - gfx::Rect thumb_rect(rect); - if (IsOverlayScrollbarEnabled()) { - // Overlay scrollbar has no track, just paint thumb directly. - // Do not paint if state is disabled. - if (state == kDisabled) - return; - - if (!scrollbar_overlay_thumb_painter_) { - scrollbar_overlay_thumb_painter_ = - CreateDualPainter(kScrollbarOverlayThumbFillImages, - kScrollbarOverlayThumbFillAlphas, - kScrollbarOverlayThumbStrokeImages, - kScrollbarOverlayThumbStrokeAlphas); - } - - PaintDualPainter( - scrollbar_overlay_thumb_painter_.get(), sk_canvas, thumb_rect, state); - return; - } - // If there are no scrollbuttons then provide some padding so that thumb - // doesn't touch the top of the track. - const int extra_padding = (scrollbar_button_length() == 0) ? 2 : 0; - if (part == NativeTheme::kScrollbarVerticalThumb) - thumb_rect.Inset(2, extra_padding, 2, extra_padding); - else - thumb_rect.Inset(extra_padding, 2, extra_padding, 2); - PaintPainter(GetOrCreatePainter( - kScrollbarThumbImages, state, scrollbar_thumb_painters_), - sk_canvas, - thumb_rect); -} - -void NativeThemeAura::PaintScrollbarThumbStateTransition( - SkCanvas* canvas, - State startState, - State endState, - double progress, - const gfx::Rect& rect) const { - // Only Overlay scrollbars should have state transition animation. - DCHECK(IsOverlayScrollbarEnabled()); - if (!scrollbar_overlay_thumb_painter_) { - scrollbar_overlay_thumb_painter_ = - CreateDualPainter(kScrollbarOverlayThumbFillImages, - kScrollbarOverlayThumbFillAlphas, - kScrollbarOverlayThumbStrokeImages, - kScrollbarOverlayThumbStrokeAlphas); - } - - PaintDualPainterTransition(scrollbar_overlay_thumb_painter_.get(), - canvas, - rect, - startState, - endState, - progress); -} - -void NativeThemeAura::PaintScrollbarCorner(SkCanvas* canvas, - State state, - const gfx::Rect& rect) const { - // Overlay Scrollbar should never paint a scrollbar corner. - DCHECK(!IsOverlayScrollbarEnabled()); - SkPaint paint; - paint.setColor(SkColorSetRGB(0xF1, 0xF1, 0xF1)); - paint.setStyle(SkPaint::kFill_Style); - paint.setXfermodeMode(SkXfermode::kSrc_Mode); - canvas->drawIRect(RectToSkIRect(rect), paint); -} - -NineImagePainter* NativeThemeAura::GetOrCreatePainter( - const int images[kNumStates][9], - State state, - scoped_ptr<NineImagePainter> painters[kNumStates]) const { - if (painters[state]) - return painters[state].get(); - if (images[state][0] == 0) { - // Must always provide normal state images. - DCHECK_NE(kNormal, state); - return GetOrCreatePainter(images, kNormal, painters); - } - painters[state] = CreateNineImagePainter(images[state]); - return painters[state].get(); -} - -void NativeThemeAura::PaintPainter(NineImagePainter* painter, - SkCanvas* sk_canvas, - const gfx::Rect& rect) const { - DCHECK(painter); - scoped_ptr<gfx::Canvas> canvas(CommonThemeCreateCanvas(sk_canvas)); - painter->Paint(canvas.get(), rect); -} - -scoped_ptr<NativeThemeAura::DualPainter> NativeThemeAura::CreateDualPainter( - const int fill_image_ids[9], - const uint8 fill_alphas[kNumStates], - const int stroke_image_ids[9], - const uint8 stroke_alphas[kNumStates]) const { - scoped_ptr<NativeThemeAura::DualPainter> dual_painter( - new NativeThemeAura::DualPainter(CreateNineImagePainter(fill_image_ids), - fill_alphas, - CreateNineImagePainter(stroke_image_ids), - stroke_alphas)); - return dual_painter.Pass(); -} - -void NativeThemeAura::PaintDualPainter( - NativeThemeAura::DualPainter* dual_painter, - SkCanvas* sk_canvas, - const gfx::Rect& rect, - State state) const { - DCHECK(dual_painter); - scoped_ptr<gfx::Canvas> canvas(CommonThemeCreateCanvas(sk_canvas)); - dual_painter->fill_painter->Paint( - canvas.get(), rect, dual_painter->fill_alphas[state]); - dual_painter->stroke_painter->Paint( - canvas.get(), rect, dual_painter->stroke_alphas[state]); -} - -void NativeThemeAura::PaintDualPainterTransition( - NativeThemeAura::DualPainter* dual_painter, - SkCanvas* sk_canvas, - const gfx::Rect& rect, - State startState, - State endState, - double progress) const { - DCHECK(dual_painter); - scoped_ptr<gfx::Canvas> canvas(CommonThemeCreateCanvas(sk_canvas)); - uint8 fill_alpha = dual_painter->fill_alphas[startState] + - (dual_painter->fill_alphas[endState] - - dual_painter->fill_alphas[startState]) * - progress; - uint8 stroke_alpha = dual_painter->stroke_alphas[startState] + - (dual_painter->stroke_alphas[endState] - - dual_painter->stroke_alphas[startState]) * - progress; - - dual_painter->fill_painter->Paint(canvas.get(), rect, fill_alpha); - dual_painter->stroke_painter->Paint(canvas.get(), rect, stroke_alpha); -} - -NativeThemeAura::DualPainter::DualPainter( - scoped_ptr<NineImagePainter> fill_painter, - const uint8 fill_alphas[kNumStates], - scoped_ptr<NineImagePainter> stroke_painter, - const uint8 stroke_alphas[kNumStates]) - : fill_painter(fill_painter.Pass()), - fill_alphas(fill_alphas), - stroke_painter(stroke_painter.Pass()), - stroke_alphas(stroke_alphas) {} - -NativeThemeAura::DualPainter::~DualPainter() {} - -} // namespace ui
diff --git a/ui/native_theme/native_theme_aura.h b/ui/native_theme/native_theme_aura.h deleted file mode 100644 index 2bcfbed..0000000 --- a/ui/native_theme/native_theme_aura.h +++ /dev/null
@@ -1,129 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_NATIVE_THEME_NATIVE_THEME_AURA_H_ -#define UI_NATIVE_THEME_NATIVE_THEME_AURA_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "ui/native_theme/fallback_theme.h" - -namespace gfx { -class NineImagePainter; -} - -namespace ui { - -// Aura implementation of native theme support. -class NATIVE_THEME_EXPORT NativeThemeAura : public FallbackTheme { - public: - static NativeThemeAura* instance(); - - protected: - NativeThemeAura(); - virtual ~NativeThemeAura(); - - // Overridden from NativeThemeBase: - virtual void PaintMenuPopupBackground( - SkCanvas* canvas, - const gfx::Size& size, - const MenuBackgroundExtraParams& menu_background) const override; - virtual void PaintMenuItemBackground( - SkCanvas* canvas, - State state, - const gfx::Rect& rect, - const MenuListExtraParams& menu_list) const override; - virtual void PaintArrowButton(SkCanvas* gc, - const gfx::Rect& rect, - Part direction, - State state) const override; - virtual void PaintScrollbarTrack( - SkCanvas* sk_canvas, - Part part, - State state, - const ScrollbarTrackExtraParams& extra_params, - const gfx::Rect& rect) const override; - virtual void PaintScrollbarThumb(SkCanvas* sk_canvas, - Part part, - State state, - const gfx::Rect& rect) const override; - virtual void PaintScrollbarCorner(SkCanvas* canvas, - State state, - const gfx::Rect& rect) const override; - - virtual void PaintScrollbarThumbStateTransition(SkCanvas* canvas, - State startState, - State endState, - double progress, - const gfx::Rect& rect) const - override; - - // Returns the NineImagePainter used to paint the specified state, creating if - // necessary. If no image is provided for the specified state the normal state - // images are used. - gfx::NineImagePainter* GetOrCreatePainter( - const int image_ids[kNumStates][9], - State state, - scoped_ptr<gfx::NineImagePainter> painters[kNumStates]) const; - - // Paints |painter| into the canvas using |rect|. - void PaintPainter(gfx::NineImagePainter* painter, - SkCanvas* sk_canvas, - const gfx::Rect& rect) const; - - mutable scoped_ptr<gfx::NineImagePainter> scrollbar_track_painter_; - - mutable scoped_ptr<gfx::NineImagePainter> - scrollbar_thumb_painters_[kNumStates]; - - mutable scoped_ptr<gfx::NineImagePainter> - scrollbar_arrow_button_painters_[kNumStates]; - - private: - struct DualPainter { - // For overlay scrollbar thumbs, fill and stroke are controlled separately, - // and each state is achieved by painting with different opacity. This - // struct bundles information of painter generated using assets and alpha - // value associated with each state, so that a DualPainter for overlay - // scrollbar thumb would only need state as input to paint correctly. - DualPainter(scoped_ptr<gfx::NineImagePainter> fill_painter, - const uint8 fill_alphas[kNumStates], - scoped_ptr<gfx::NineImagePainter> stroke_painter, - const uint8 stroke_alphas[kNumStates]); - ~DualPainter(); - - scoped_ptr<gfx::NineImagePainter> fill_painter; - const uint8* const fill_alphas; - scoped_ptr<gfx::NineImagePainter> stroke_painter; - const uint8* const stroke_alphas; - }; - - // Returns DualPainter from specific fill and stroke, creating if necessary. - scoped_ptr<DualPainter> CreateDualPainter( - const int fill_image_ids[9], - const uint8 fill_alphas[kNumStates], - const int stroke_image_ids[9], - const uint8 stroke_alphas[kNumStates]) const; - - // Paints |dualPainter| into the canvas using |rect| and specific alpha. - void PaintDualPainter(DualPainter* dual_painter, - SkCanvas* sk_canvas, - const gfx::Rect& rect, - State state) const; - - void PaintDualPainterTransition(DualPainter* dual_painter, - SkCanvas* sk_canvas, - const gfx::Rect& rect, - State startState, - State endState, - double progress) const; - - mutable scoped_ptr<DualPainter> scrollbar_overlay_thumb_painter_; - - DISALLOW_COPY_AND_ASSIGN(NativeThemeAura); -}; - -} // namespace ui - -#endif // UI_NATIVE_THEME_NATIVE_THEME_AURA_H_
diff --git a/ui/native_theme/native_theme_aurawin.cc b/ui/native_theme/native_theme_aurawin.cc deleted file mode 100644 index 3cc01e5..0000000 --- a/ui/native_theme/native_theme_aurawin.cc +++ /dev/null
@@ -1,86 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/native_theme/native_theme_aurawin.h" - -#include "third_party/skia/include/core/SkCanvas.h" -#include "ui/native_theme/common_theme.h" -#include "ui/native_theme/native_theme_win.h" - -namespace ui { - -namespace { - -bool IsScrollbarPart(NativeTheme::Part part) { - switch (part) { - case NativeTheme::kScrollbarDownArrow: - case NativeTheme::kScrollbarLeftArrow: - case NativeTheme::kScrollbarRightArrow: - case NativeTheme::kScrollbarUpArrow: - case NativeTheme::kScrollbarHorizontalThumb: - case NativeTheme::kScrollbarVerticalThumb: - case NativeTheme::kScrollbarHorizontalTrack: - case NativeTheme::kScrollbarVerticalTrack: - case NativeTheme::kScrollbarHorizontalGripper: - case NativeTheme::kScrollbarVerticalGripper: - case NativeTheme::kScrollbarCorner: - return true; - } - return false; -} - -} // namespace - -// static -NativeTheme* NativeTheme::instance() { - return NativeThemeAuraWin::instance(); -} - -// static -NativeThemeAura* NativeThemeAura::instance() { - return NativeThemeAuraWin::instance(); -} - -// static -NativeThemeAuraWin* NativeThemeAuraWin::instance() { - CR_DEFINE_STATIC_LOCAL(NativeThemeAuraWin, s_native_theme, ()); - return &s_native_theme; -} - -NativeThemeAuraWin::NativeThemeAuraWin() { -} - -NativeThemeAuraWin::~NativeThemeAuraWin() { -} - -void NativeThemeAuraWin::Paint(SkCanvas* canvas, - Part part, - State state, - const gfx::Rect& rect, - const ExtraParams& extra) const { - if (IsScrollbarPart(part) && - NativeThemeWin::instance()->IsUsingHighContrastTheme()) { - NativeThemeWin::instance()->Paint(canvas, part, state, rect, extra); - return; - } - - NativeThemeAura::Paint(canvas, part, state, rect, extra); -} - -gfx::Size NativeThemeAuraWin::GetPartSize(Part part, - State state, - const ExtraParams& extra) const { - gfx::Size part_size = CommonThemeGetPartSize(part, state, extra); - if (!part_size.IsEmpty()) - return part_size; - - // We want aura on windows to use the same size for scrollbars as we would in - // the native theme. - if (IsScrollbarPart(part)) - return NativeThemeWin::instance()->GetPartSize(part, state, extra); - - return NativeThemeAura::GetPartSize(part, state, extra); -} - -} // namespace ui
diff --git a/ui/native_theme/native_theme_aurawin.h b/ui/native_theme/native_theme_aurawin.h deleted file mode 100644 index 7c7e57d..0000000 --- a/ui/native_theme/native_theme_aurawin.h +++ /dev/null
@@ -1,37 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_NATIVE_THEME_NATIVE_THEME_AURAWIN_H_ -#define UI_NATIVE_THEME_NATIVE_THEME_AURAWIN_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "ui/native_theme/native_theme_aura.h" - -namespace ui { - -// Aura implementation of native theme support. -class NATIVE_THEME_EXPORT NativeThemeAuraWin : public NativeThemeAura { - public: - static NativeThemeAuraWin* instance(); - - private: - NativeThemeAuraWin(); - virtual ~NativeThemeAuraWin(); - - // Overridden from NativeThemeBase: - virtual gfx::Size GetPartSize(Part part, - State state, - const ExtraParams& extra) const override; - virtual void Paint(SkCanvas* canvas, - Part part, - State state, - const gfx::Rect& rect, - const ExtraParams& extra) const override; - DISALLOW_COPY_AND_ASSIGN(NativeThemeAuraWin); -}; - -} // namespace ui - -#endif // UI_NATIVE_THEME_NATIVE_THEME_AURAWIN_H_
diff --git a/ui/native_theme/native_theme_base.cc b/ui/native_theme/native_theme_base.cc deleted file mode 100644 index c2195a3..0000000 --- a/ui/native_theme/native_theme_base.cc +++ /dev/null
@@ -1,1090 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/native_theme/native_theme_base.h" - -#include <limits> - -#include "base/command_line.h" -#include "base/logging.h" -#include "base/memory/scoped_ptr.h" -#include "third_party/skia/include/effects/SkGradientShader.h" -#include "ui/base/layout.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/base/ui_base_switches.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/color_utils.h" -#include "ui/gfx/image/image_skia.h" -#include "ui/gfx/rect.h" -#include "ui/gfx/size.h" -#include "ui/gfx/skia_util.h" -#include "ui/native_theme/common_theme.h" -#include "ui/resources/grit/ui_resources.h" - -namespace { - -// These are the default dimensions of radio buttons and checkboxes. -const int kCheckboxAndRadioWidth = 13; -const int kCheckboxAndRadioHeight = 13; - -// These sizes match the sizes in Chromium Win. -const int kSliderThumbWidth = 11; -const int kSliderThumbHeight = 21; - -const SkColor kSliderTrackBackgroundColor = - SkColorSetRGB(0xe3, 0xdd, 0xd8); -const SkColor kSliderThumbLightGrey = SkColorSetRGB(0xf4, 0xf2, 0xef); -const SkColor kSliderThumbDarkGrey = SkColorSetRGB(0xea, 0xe5, 0xe0); -const SkColor kSliderThumbBorderDarkGrey = - SkColorSetRGB(0x9d, 0x96, 0x8e); - -const SkColor kTextBorderColor = SkColorSetRGB(0xa9, 0xa9, 0xa9); - -const SkColor kMenuPopupBackgroundColor = SkColorSetRGB(210, 225, 246); - -const unsigned int kDefaultScrollbarWidth = 15; -const unsigned int kDefaultScrollbarButtonLength = 14; - -const SkColor kCheckboxTinyColor = SK_ColorGRAY; -const SkColor kCheckboxShadowColor = SkColorSetARGB(0x15, 0, 0, 0); -const SkColor kCheckboxShadowHoveredColor = SkColorSetARGB(0x1F, 0, 0, 0); -const SkColor kCheckboxShadowDisabledColor = SkColorSetARGB(0, 0, 0, 0); -const SkColor kCheckboxGradientColors[] = { - SkColorSetRGB(0xed, 0xed, 0xed), - SkColorSetRGB(0xde, 0xde, 0xde) }; -const SkColor kCheckboxGradientPressedColors[] = { - SkColorSetRGB(0xe7, 0xe7, 0xe7), - SkColorSetRGB(0xd7, 0xd7, 0xd7) }; -const SkColor kCheckboxGradientHoveredColors[] = { - SkColorSetRGB(0xf0, 0xf0, 0xf0), - SkColorSetRGB(0xe0, 0xe0, 0xe0) }; -const SkColor kCheckboxGradientDisabledColors[] = { - SkColorSetARGB(0x80, 0xed, 0xed, 0xed), - SkColorSetARGB(0x80, 0xde, 0xde, 0xde) }; -const SkColor kCheckboxBorderColor = SkColorSetARGB(0x40, 0, 0, 0); -const SkColor kCheckboxBorderHoveredColor = SkColorSetARGB(0x4D, 0, 0, 0); -const SkColor kCheckboxBorderDisabledColor = SkColorSetARGB(0x20, 0, 0, 0); -const SkColor kCheckboxStrokeColor = SkColorSetARGB(0xB3, 0, 0, 0); -const SkColor kCheckboxStrokeDisabledColor = SkColorSetARGB(0x59, 0, 0, 0); -const SkColor kRadioDotColor = SkColorSetRGB(0x66, 0x66, 0x66); -const SkColor kRadioDotDisabledColor = SkColorSetARGB(0x80, 0x66, 0x66, 0x66); - -// Get lightness adjusted color. -SkColor BrightenColor(const color_utils::HSL& hsl, SkAlpha alpha, - double lightness_amount) { - color_utils::HSL adjusted = hsl; - adjusted.l += lightness_amount; - if (adjusted.l > 1.0) - adjusted.l = 1.0; - if (adjusted.l < 0.0) - adjusted.l = 0.0; - - return color_utils::HSLToSkColor(adjusted, alpha); -} - -} // namespace - -namespace ui { - -gfx::Size NativeThemeBase::GetPartSize(Part part, - State state, - const ExtraParams& extra) const { - gfx::Size size = CommonThemeGetPartSize(part, state, extra); - if (!size.IsEmpty()) - return size; - - switch (part) { - // Please keep these in the order of NativeTheme::Part. - case kCheckbox: - return gfx::Size(kCheckboxAndRadioWidth, kCheckboxAndRadioHeight); - case kInnerSpinButton: - return gfx::Size(scrollbar_width_, 0); - case kMenuList: - return gfx::Size(); // No default size. - case kMenuCheck: - case kMenuCheckBackground: - case kMenuPopupArrow: - NOTIMPLEMENTED(); - break; - case kMenuPopupBackground: - return gfx::Size(); // No default size. - case kMenuPopupGutter: - case kMenuPopupSeparator: - NOTIMPLEMENTED(); - break; - case kMenuItemBackground: - case kProgressBar: - case kPushButton: - return gfx::Size(); // No default size. - case kRadio: - return gfx::Size(kCheckboxAndRadioWidth, kCheckboxAndRadioHeight); - case kScrollbarDownArrow: - case kScrollbarUpArrow: - return gfx::Size(scrollbar_width_, scrollbar_button_length_); - case kScrollbarLeftArrow: - case kScrollbarRightArrow: - return gfx::Size(scrollbar_button_length_, scrollbar_width_); - case kScrollbarHorizontalThumb: - // This matches Firefox on Linux. - return gfx::Size(2 * scrollbar_width_, scrollbar_width_); - case kScrollbarVerticalThumb: - // This matches Firefox on Linux. - return gfx::Size(scrollbar_width_, 2 * scrollbar_width_); - case kScrollbarHorizontalTrack: - return gfx::Size(0, scrollbar_width_); - case kScrollbarVerticalTrack: - return gfx::Size(scrollbar_width_, 0); - case kScrollbarHorizontalGripper: - case kScrollbarVerticalGripper: - NOTIMPLEMENTED(); - break; - case kSliderTrack: - return gfx::Size(); // No default size. - case kSliderThumb: - // These sizes match the sizes in Chromium Win. - return gfx::Size(kSliderThumbWidth, kSliderThumbHeight); - case kTabPanelBackground: - NOTIMPLEMENTED(); - break; - case kTextField: - return gfx::Size(); // No default size. - case kTrackbarThumb: - case kTrackbarTrack: - case kWindowResizeGripper: - NOTIMPLEMENTED(); - break; - default: - NOTREACHED() << "Unknown theme part: " << part; - break; - } - return gfx::Size(); -} - -void NativeThemeBase::PaintStateTransition(SkCanvas* canvas, - Part part, - State startState, - State endState, - double progress, - const gfx::Rect& rect) const { - if (rect.IsEmpty()) - return; - - // Currently state transition is animation only working for overlay scrollbars - // on Aura platforms. - switch (part) { - case kScrollbarHorizontalThumb: - case kScrollbarVerticalThumb: - PaintScrollbarThumbStateTransition( - canvas, startState, endState, progress, rect); - break; - default: - NOTREACHED() << "Does not support state transition for this part:" - << part; - break; - } - return; -} - -void NativeThemeBase::Paint(SkCanvas* canvas, - Part part, - State state, - const gfx::Rect& rect, - const ExtraParams& extra) const { - if (rect.IsEmpty()) - return; - - switch (part) { - // Please keep these in the order of NativeTheme::Part. - case kComboboxArrow: - CommonThemePaintComboboxArrow(canvas, rect); - break; - case kCheckbox: - PaintCheckbox(canvas, state, rect, extra.button); - break; - case kInnerSpinButton: - PaintInnerSpinButton(canvas, state, rect, extra.inner_spin); - break; - case kMenuList: - PaintMenuList(canvas, state, rect, extra.menu_list); - break; - case kMenuCheck: - case kMenuCheckBackground: - case kMenuPopupArrow: - NOTIMPLEMENTED(); - break; - case kMenuPopupBackground: - PaintMenuPopupBackground(canvas, rect.size(), extra.menu_background); - break; - case kMenuPopupGutter: - case kMenuPopupSeparator: - NOTIMPLEMENTED(); - break; - case kMenuItemBackground: - PaintMenuItemBackground(canvas, state, rect, extra.menu_list); - break; - case kProgressBar: - PaintProgressBar(canvas, state, rect, extra.progress_bar); - break; - case kPushButton: - PaintButton(canvas, state, rect, extra.button); - break; - case kRadio: - PaintRadio(canvas, state, rect, extra.button); - break; - case kScrollbarDownArrow: - case kScrollbarUpArrow: - case kScrollbarLeftArrow: - case kScrollbarRightArrow: - if (scrollbar_button_length_ > 0) - PaintArrowButton(canvas, rect, part, state); - break; - case kScrollbarHorizontalThumb: - case kScrollbarVerticalThumb: - PaintScrollbarThumb(canvas, part, state, rect); - break; - case kScrollbarHorizontalTrack: - case kScrollbarVerticalTrack: - PaintScrollbarTrack(canvas, part, state, extra.scrollbar_track, rect); - break; - case kScrollbarHorizontalGripper: - case kScrollbarVerticalGripper: - // Invoked by views scrollbar code, don't care about for non-win - // implementations, so no NOTIMPLEMENTED. - break; - case kScrollbarCorner: - PaintScrollbarCorner(canvas, state, rect); - break; - case kSliderTrack: - PaintSliderTrack(canvas, state, rect, extra.slider); - break; - case kSliderThumb: - PaintSliderThumb(canvas, state, rect, extra.slider); - break; - case kTabPanelBackground: - NOTIMPLEMENTED(); - break; - case kTextField: - PaintTextField(canvas, state, rect, extra.text_field); - break; - case kTrackbarThumb: - case kTrackbarTrack: - case kWindowResizeGripper: - NOTIMPLEMENTED(); - break; - default: - NOTREACHED() << "Unknown theme part: " << part; - break; - } -} - -NativeThemeBase::NativeThemeBase() - : scrollbar_width_(kDefaultScrollbarWidth), - scrollbar_button_length_(kDefaultScrollbarButtonLength) { -} - -NativeThemeBase::~NativeThemeBase() { -} - -void NativeThemeBase::PaintArrowButton( - SkCanvas* canvas, - const gfx::Rect& rect, Part direction, State state) const { - SkPaint paint; - - // Calculate button color. - SkScalar trackHSV[3]; - SkColorToHSV(track_color_, trackHSV); - SkColor buttonColor = SaturateAndBrighten(trackHSV, 0, 0.2f); - SkColor backgroundColor = buttonColor; - if (state == kPressed) { - SkScalar buttonHSV[3]; - SkColorToHSV(buttonColor, buttonHSV); - buttonColor = SaturateAndBrighten(buttonHSV, 0, -0.1f); - } else if (state == kHovered) { - SkScalar buttonHSV[3]; - SkColorToHSV(buttonColor, buttonHSV); - buttonColor = SaturateAndBrighten(buttonHSV, 0, 0.05f); - } - - SkIRect skrect; - skrect.set(rect.x(), rect.y(), rect.x() + rect.width(), rect.y() - + rect.height()); - // Paint the background (the area visible behind the rounded corners). - paint.setColor(backgroundColor); - canvas->drawIRect(skrect, paint); - - // Paint the button's outline and fill the middle - SkPath outline; - switch (direction) { - case kScrollbarUpArrow: - outline.moveTo(rect.x() + 0.5, rect.y() + rect.height() + 0.5); - outline.rLineTo(0, -(rect.height() - 2)); - outline.rLineTo(2, -2); - outline.rLineTo(rect.width() - 5, 0); - outline.rLineTo(2, 2); - outline.rLineTo(0, rect.height() - 2); - break; - case kScrollbarDownArrow: - outline.moveTo(rect.x() + 0.5, rect.y() - 0.5); - outline.rLineTo(0, rect.height() - 2); - outline.rLineTo(2, 2); - outline.rLineTo(rect.width() - 5, 0); - outline.rLineTo(2, -2); - outline.rLineTo(0, -(rect.height() - 2)); - break; - case kScrollbarRightArrow: - outline.moveTo(rect.x() - 0.5, rect.y() + 0.5); - outline.rLineTo(rect.width() - 2, 0); - outline.rLineTo(2, 2); - outline.rLineTo(0, rect.height() - 5); - outline.rLineTo(-2, 2); - outline.rLineTo(-(rect.width() - 2), 0); - break; - case kScrollbarLeftArrow: - outline.moveTo(rect.x() + rect.width() + 0.5, rect.y() + 0.5); - outline.rLineTo(-(rect.width() - 2), 0); - outline.rLineTo(-2, 2); - outline.rLineTo(0, rect.height() - 5); - outline.rLineTo(2, 2); - outline.rLineTo(rect.width() - 2, 0); - break; - default: - break; - } - outline.close(); - - paint.setStyle(SkPaint::kFill_Style); - paint.setColor(buttonColor); - canvas->drawPath(outline, paint); - - paint.setAntiAlias(true); - paint.setStyle(SkPaint::kStroke_Style); - SkScalar thumbHSV[3]; - SkColorToHSV(thumb_inactive_color_, thumbHSV); - paint.setColor(OutlineColor(trackHSV, thumbHSV)); - canvas->drawPath(outline, paint); - - PaintArrow(canvas, rect, direction, GetArrowColor(state)); -} - -void NativeThemeBase::PaintArrow(SkCanvas* gc, - const gfx::Rect& rect, - Part direction, - SkColor color) const { - int width_middle, length_middle; - if (direction == kScrollbarUpArrow || direction == kScrollbarDownArrow) { - width_middle = rect.width() / 2 + 1; - length_middle = rect.height() / 2 + 1; - } else { - length_middle = rect.width() / 2 + 1; - width_middle = rect.height() / 2 + 1; - } - - SkPaint paint; - paint.setColor(color); - paint.setAntiAlias(false); - paint.setStyle(SkPaint::kFill_Style); - - SkPath path; - // The constants in this block of code are hand-tailored to produce good - // looking arrows without anti-aliasing. - switch (direction) { - case kScrollbarUpArrow: - path.moveTo(rect.x() + width_middle - 4, rect.y() + length_middle + 2); - path.rLineTo(7, 0); - path.rLineTo(-4, -4); - break; - case kScrollbarDownArrow: - path.moveTo(rect.x() + width_middle - 4, rect.y() + length_middle - 3); - path.rLineTo(7, 0); - path.rLineTo(-4, 4); - break; - case kScrollbarRightArrow: - path.moveTo(rect.x() + length_middle - 3, rect.y() + width_middle - 4); - path.rLineTo(0, 7); - path.rLineTo(4, -4); - break; - case kScrollbarLeftArrow: - path.moveTo(rect.x() + length_middle + 1, rect.y() + width_middle - 5); - path.rLineTo(0, 9); - path.rLineTo(-4, -4); - break; - default: - break; - } - path.close(); - - gc->drawPath(path, paint); -} - -void NativeThemeBase::PaintScrollbarTrack(SkCanvas* canvas, - Part part, - State state, - const ScrollbarTrackExtraParams& extra_params, - const gfx::Rect& rect) const { - SkPaint paint; - SkIRect skrect; - - skrect.set(rect.x(), rect.y(), rect.right(), rect.bottom()); - SkScalar track_hsv[3]; - SkColorToHSV(track_color_, track_hsv); - paint.setColor(SaturateAndBrighten(track_hsv, 0, 0)); - canvas->drawIRect(skrect, paint); - - SkScalar thumb_hsv[3]; - SkColorToHSV(thumb_inactive_color_, thumb_hsv); - - paint.setColor(OutlineColor(track_hsv, thumb_hsv)); - DrawBox(canvas, rect, paint); -} - -void NativeThemeBase::PaintScrollbarThumb(SkCanvas* canvas, - Part part, - State state, - const gfx::Rect& rect) const { - const bool hovered = state == kHovered; - const int midx = rect.x() + rect.width() / 2; - const int midy = rect.y() + rect.height() / 2; - const bool vertical = part == kScrollbarVerticalThumb; - - SkScalar thumb[3]; - SkColorToHSV(hovered ? thumb_active_color_ : thumb_inactive_color_, thumb); - - SkPaint paint; - paint.setColor(SaturateAndBrighten(thumb, 0, 0.02f)); - - SkIRect skrect; - if (vertical) - skrect.set(rect.x(), rect.y(), midx + 1, rect.y() + rect.height()); - else - skrect.set(rect.x(), rect.y(), rect.x() + rect.width(), midy + 1); - - canvas->drawIRect(skrect, paint); - - paint.setColor(SaturateAndBrighten(thumb, 0, -0.02f)); - - if (vertical) { - skrect.set( - midx + 1, rect.y(), rect.x() + rect.width(), rect.y() + rect.height()); - } else { - skrect.set( - rect.x(), midy + 1, rect.x() + rect.width(), rect.y() + rect.height()); - } - - canvas->drawIRect(skrect, paint); - - SkScalar track[3]; - SkColorToHSV(track_color_, track); - paint.setColor(OutlineColor(track, thumb)); - DrawBox(canvas, rect, paint); - - if (rect.height() > 10 && rect.width() > 10) { - const int grippy_half_width = 2; - const int inter_grippy_offset = 3; - if (vertical) { - DrawHorizLine(canvas, - midx - grippy_half_width, - midx + grippy_half_width, - midy - inter_grippy_offset, - paint); - DrawHorizLine(canvas, - midx - grippy_half_width, - midx + grippy_half_width, - midy, - paint); - DrawHorizLine(canvas, - midx - grippy_half_width, - midx + grippy_half_width, - midy + inter_grippy_offset, - paint); - } else { - DrawVertLine(canvas, - midx - inter_grippy_offset, - midy - grippy_half_width, - midy + grippy_half_width, - paint); - DrawVertLine(canvas, - midx, - midy - grippy_half_width, - midy + grippy_half_width, - paint); - DrawVertLine(canvas, - midx + inter_grippy_offset, - midy - grippy_half_width, - midy + grippy_half_width, - paint); - } - } -} - -void NativeThemeBase::PaintScrollbarCorner(SkCanvas* canvas, - State state, - const gfx::Rect& rect) const { -} - -void NativeThemeBase::PaintCheckbox(SkCanvas* canvas, - State state, - const gfx::Rect& rect, - const ButtonExtraParams& button) const { - SkRect skrect = PaintCheckboxRadioCommon(canvas, state, rect, - SkIntToScalar(2)); - if (!skrect.isEmpty()) { - // Draw the checkmark / dash. - SkPaint paint; - paint.setAntiAlias(true); - paint.setStyle(SkPaint::kStroke_Style); - if (state == kDisabled) - paint.setColor(kCheckboxStrokeDisabledColor); - else - paint.setColor(kCheckboxStrokeColor); - if (button.indeterminate) { - SkPath dash; - dash.moveTo(skrect.x() + skrect.width() * 0.16, - (skrect.y() + skrect.bottom()) / 2); - dash.rLineTo(skrect.width() * 0.68, 0); - paint.setStrokeWidth(SkFloatToScalar(skrect.height() * 0.2)); - canvas->drawPath(dash, paint); - } else if (button.checked) { - SkPath check; - check.moveTo(skrect.x() + skrect.width() * 0.2, - skrect.y() + skrect.height() * 0.5); - check.rLineTo(skrect.width() * 0.2, skrect.height() * 0.2); - paint.setStrokeWidth(SkFloatToScalar(skrect.height() * 0.23)); - check.lineTo(skrect.right() - skrect.width() * 0.2, - skrect.y() + skrect.height() * 0.2); - canvas->drawPath(check, paint); - } - } -} - -// Draws the common elements of checkboxes and radio buttons. -// Returns the rectangle within which any additional decorations should be -// drawn, or empty if none. -SkRect NativeThemeBase::PaintCheckboxRadioCommon( - SkCanvas* canvas, - State state, - const gfx::Rect& rect, - const SkScalar borderRadius) const { - - SkRect skrect = gfx::RectToSkRect(rect); - - // Use the largest square that fits inside the provided rectangle. - // No other browser seems to support non-square widget, so accidentally - // having non-square sizes is common (eg. amazon and webkit dev tools). - if (skrect.width() != skrect.height()) { - SkScalar size = SkMinScalar(skrect.width(), skrect.height()); - skrect.inset((skrect.width() - size) / 2, (skrect.height() - size) / 2); - } - - // If the rectangle is too small then paint only a rectangle. We don't want - // to have to worry about '- 1' and '+ 1' calculations below having overflow - // or underflow. - if (skrect.width() <= 2) { - SkPaint paint; - paint.setColor(kCheckboxTinyColor); - paint.setStyle(SkPaint::kFill_Style); - canvas->drawRect(skrect, paint); - // Too small to draw anything more. - return SkRect::MakeEmpty(); - } - - // Make room for the drop shadow. - skrect.iset(skrect.x(), skrect.y(), skrect.right() - 1, skrect.bottom() - 1); - - // Draw the drop shadow below the widget. - if (state != kPressed) { - SkPaint paint; - paint.setAntiAlias(true); - SkRect shadowRect = skrect; - shadowRect.offset(0, 1); - if (state == kDisabled) - paint.setColor(kCheckboxShadowDisabledColor); - else if (state == kHovered) - paint.setColor(kCheckboxShadowHoveredColor); - else - paint.setColor(kCheckboxShadowColor); - paint.setStyle(SkPaint::kFill_Style); - canvas->drawRoundRect(shadowRect, borderRadius, borderRadius, paint); - } - - // Draw the gradient-filled rectangle - SkPoint gradient_bounds[3]; - gradient_bounds[0].set(skrect.x(), skrect.y()); - gradient_bounds[1].set(skrect.x(), skrect.y() + skrect.height() * 0.38); - gradient_bounds[2].set(skrect.x(), skrect.bottom()); - const SkColor* startEndColors; - if (state == kPressed) - startEndColors = kCheckboxGradientPressedColors; - else if (state == kHovered) - startEndColors = kCheckboxGradientHoveredColors; - else if (state == kDisabled) - startEndColors = kCheckboxGradientDisabledColors; - else /* kNormal */ - startEndColors = kCheckboxGradientColors; - SkColor colors[3] = {startEndColors[0], startEndColors[0], startEndColors[1]}; - skia::RefPtr<SkShader> shader = skia::AdoptRef( - SkGradientShader::CreateLinear( - gradient_bounds, colors, NULL, 3, SkShader::kClamp_TileMode)); - SkPaint paint; - paint.setAntiAlias(true); - paint.setShader(shader.get()); - paint.setStyle(SkPaint::kFill_Style); - canvas->drawRoundRect(skrect, borderRadius, borderRadius, paint); - paint.setShader(NULL); - - // Draw the border. - if (state == kHovered) - paint.setColor(kCheckboxBorderHoveredColor); - else if (state == kDisabled) - paint.setColor(kCheckboxBorderDisabledColor); - else - paint.setColor(kCheckboxBorderColor); - paint.setStyle(SkPaint::kStroke_Style); - paint.setStrokeWidth(SkIntToScalar(1)); - skrect.inset(SkFloatToScalar(.5f), SkFloatToScalar(.5f)); - canvas->drawRoundRect(skrect, borderRadius, borderRadius, paint); - - // Return the rectangle excluding the drop shadow for drawing any additional - // decorations. - return skrect; -} - -void NativeThemeBase::PaintRadio(SkCanvas* canvas, - State state, - const gfx::Rect& rect, - const ButtonExtraParams& button) const { - - // Most of a radio button is the same as a checkbox, except the the rounded - // square is a circle (i.e. border radius >= 100%). - const SkScalar radius = SkFloatToScalar( - static_cast<float>(std::max(rect.width(), rect.height())) / 2); - SkRect skrect = PaintCheckboxRadioCommon(canvas, state, rect, radius); - if (!skrect.isEmpty() && button.checked) { - // Draw the dot. - SkPaint paint; - paint.setAntiAlias(true); - paint.setStyle(SkPaint::kFill_Style); - if (state == kDisabled) - paint.setColor(kRadioDotDisabledColor); - else - paint.setColor(kRadioDotColor); - skrect.inset(skrect.width() * 0.25, skrect.height() * 0.25); - // Use drawRoundedRect instead of drawOval to be completely consistent - // with the border in PaintCheckboxRadioNewCommon. - canvas->drawRoundRect(skrect, radius, radius, paint); - } -} - -void NativeThemeBase::PaintButton(SkCanvas* canvas, - State state, - const gfx::Rect& rect, - const ButtonExtraParams& button) const { - SkPaint paint; - const int kRight = rect.right(); - const int kBottom = rect.bottom(); - SkRect skrect = SkRect::MakeLTRB(rect.x(), rect.y(), kRight, kBottom); - SkColor base_color = button.background_color; - - color_utils::HSL base_hsl; - color_utils::SkColorToHSL(base_color, &base_hsl); - - // Our standard gradient is from 0xdd to 0xf8. This is the amount of - // increased luminance between those values. - SkColor light_color(BrightenColor(base_hsl, SkColorGetA(base_color), 0.105)); - - // If the button is too small, fallback to drawing a single, solid color - if (rect.width() < 5 || rect.height() < 5) { - paint.setColor(base_color); - canvas->drawRect(skrect, paint); - return; - } - - paint.setColor(SK_ColorBLACK); - const int kLightEnd = state == kPressed ? 1 : 0; - const int kDarkEnd = !kLightEnd; - SkPoint gradient_bounds[2]; - gradient_bounds[kLightEnd].iset(rect.x(), rect.y()); - gradient_bounds[kDarkEnd].iset(rect.x(), kBottom - 1); - SkColor colors[2]; - colors[0] = light_color; - colors[1] = base_color; - - skia::RefPtr<SkShader> shader = skia::AdoptRef( - SkGradientShader::CreateLinear( - gradient_bounds, colors, NULL, 2, SkShader::kClamp_TileMode)); - paint.setStyle(SkPaint::kFill_Style); - paint.setAntiAlias(true); - paint.setShader(shader.get()); - - canvas->drawRoundRect(skrect, SkIntToScalar(1), SkIntToScalar(1), paint); - paint.setShader(NULL); - - if (button.has_border) { - int border_alpha = state == kHovered ? 0x80 : 0x55; - if (button.is_focused) { - border_alpha = 0xff; - paint.setColor(GetSystemColor(kColorId_FocusedBorderColor)); - } - paint.setStyle(SkPaint::kStroke_Style); - paint.setStrokeWidth(SkIntToScalar(1)); - paint.setAlpha(border_alpha); - skrect.inset(SkFloatToScalar(.5f), SkFloatToScalar(.5f)); - canvas->drawRoundRect(skrect, SkIntToScalar(1), SkIntToScalar(1), paint); - } -} - -void NativeThemeBase::PaintTextField(SkCanvas* canvas, - State state, - const gfx::Rect& rect, - const TextFieldExtraParams& text) const { - SkRect bounds; - bounds.set(rect.x(), rect.y(), rect.right() - 1, rect.bottom() - 1); - - SkPaint fill_paint; - fill_paint.setStyle(SkPaint::kFill_Style); - fill_paint.setColor(text.background_color); - canvas->drawRect(bounds, fill_paint); - - // Text INPUT, listbox SELECT, and TEXTAREA have consistent borders. - // border: 1px solid #a9a9a9 - SkPaint stroke_paint; - stroke_paint.setStyle(SkPaint::kStroke_Style); - stroke_paint.setColor(kTextBorderColor); - canvas->drawRect(bounds, stroke_paint); -} - -void NativeThemeBase::PaintMenuList( - SkCanvas* canvas, - State state, - const gfx::Rect& rect, - const MenuListExtraParams& menu_list) const { - // If a border radius is specified, we let the WebCore paint the background - // and the border of the control. - if (!menu_list.has_border_radius) { - ButtonExtraParams button = { 0 }; - button.background_color = menu_list.background_color; - button.has_border = menu_list.has_border; - PaintButton(canvas, state, rect, button); - } - - SkPaint paint; - paint.setColor(SK_ColorBLACK); - paint.setAntiAlias(true); - paint.setStyle(SkPaint::kFill_Style); - - SkPath path; - path.moveTo(menu_list.arrow_x, menu_list.arrow_y - 3); - path.rLineTo(6, 0); - path.rLineTo(-3, 6); - path.close(); - canvas->drawPath(path, paint); -} - -void NativeThemeBase::PaintMenuPopupBackground( - SkCanvas* canvas, - const gfx::Size& size, - const MenuBackgroundExtraParams& menu_background) const { - canvas->drawColor(kMenuPopupBackgroundColor, SkXfermode::kSrc_Mode); -} - -void NativeThemeBase::PaintMenuItemBackground( - SkCanvas* canvas, - State state, - const gfx::Rect& rect, - const MenuListExtraParams& menu_list) const { - // By default don't draw anything over the normal background. -} - -void NativeThemeBase::PaintSliderTrack(SkCanvas* canvas, - State state, - const gfx::Rect& rect, - const SliderExtraParams& slider) const { - const int kMidX = rect.x() + rect.width() / 2; - const int kMidY = rect.y() + rect.height() / 2; - - SkPaint paint; - paint.setColor(kSliderTrackBackgroundColor); - - SkRect skrect; - if (slider.vertical) { - skrect.set(std::max(rect.x(), kMidX - 2), - rect.y(), - std::min(rect.right(), kMidX + 2), - rect.bottom()); - } else { - skrect.set(rect.x(), - std::max(rect.y(), kMidY - 2), - rect.right(), - std::min(rect.bottom(), kMidY + 2)); - } - canvas->drawRect(skrect, paint); -} - -void NativeThemeBase::PaintSliderThumb(SkCanvas* canvas, - State state, - const gfx::Rect& rect, - const SliderExtraParams& slider) const { - const bool hovered = (state == kHovered) || slider.in_drag; - const int kMidX = rect.x() + rect.width() / 2; - const int kMidY = rect.y() + rect.height() / 2; - - SkPaint paint; - paint.setColor(hovered ? SK_ColorWHITE : kSliderThumbLightGrey); - - SkIRect skrect; - if (slider.vertical) - skrect.set(rect.x(), rect.y(), kMidX + 1, rect.bottom()); - else - skrect.set(rect.x(), rect.y(), rect.right(), kMidY + 1); - - canvas->drawIRect(skrect, paint); - - paint.setColor(hovered ? kSliderThumbLightGrey : kSliderThumbDarkGrey); - - if (slider.vertical) - skrect.set(kMidX + 1, rect.y(), rect.right(), rect.bottom()); - else - skrect.set(rect.x(), kMidY + 1, rect.right(), rect.bottom()); - - canvas->drawIRect(skrect, paint); - - paint.setColor(kSliderThumbBorderDarkGrey); - DrawBox(canvas, rect, paint); - - if (rect.height() > 10 && rect.width() > 10) { - DrawHorizLine(canvas, kMidX - 2, kMidX + 2, kMidY, paint); - DrawHorizLine(canvas, kMidX - 2, kMidX + 2, kMidY - 3, paint); - DrawHorizLine(canvas, kMidX - 2, kMidX + 2, kMidY + 3, paint); - } -} - -void NativeThemeBase::PaintInnerSpinButton(SkCanvas* canvas, - State state, - const gfx::Rect& rect, - const InnerSpinButtonExtraParams& spin_button) const { - if (spin_button.read_only) - state = kDisabled; - - State north_state = state; - State south_state = state; - if (spin_button.spin_up) - south_state = south_state != kDisabled ? kNormal : kDisabled; - else - north_state = north_state != kDisabled ? kNormal : kDisabled; - - gfx::Rect half = rect; - half.set_height(rect.height() / 2); - PaintArrowButton(canvas, half, kScrollbarUpArrow, north_state); - - half.set_y(rect.y() + rect.height() / 2); - PaintArrowButton(canvas, half, kScrollbarDownArrow, south_state); -} - -void NativeThemeBase::PaintProgressBar(SkCanvas* canvas, - State state, - const gfx::Rect& rect, - const ProgressBarExtraParams& progress_bar) const { - ResourceBundle& rb = ResourceBundle::GetSharedInstance(); - gfx::ImageSkia* bar_image = rb.GetImageSkiaNamed(IDR_PROGRESS_BAR); - gfx::ImageSkia* left_border_image = rb.GetImageSkiaNamed( - IDR_PROGRESS_BORDER_LEFT); - gfx::ImageSkia* right_border_image = rb.GetImageSkiaNamed( - IDR_PROGRESS_BORDER_RIGHT); - - DCHECK(bar_image->width() > 0); - DCHECK(rect.width() > 0); - - float tile_scale_y = static_cast<float>(rect.height()) / bar_image->height(); - - int dest_left_border_width = left_border_image->width(); - int dest_right_border_width = right_border_image->width(); - - // Since an implicit float -> int conversion will truncate, we want to make - // sure that if a border is desired, it gets at least one pixel. - if (dest_left_border_width > 0) { - dest_left_border_width = dest_left_border_width * tile_scale_y; - dest_left_border_width = std::max(dest_left_border_width, 1); - } - if (dest_right_border_width > 0) { - dest_right_border_width = dest_right_border_width * tile_scale_y; - dest_right_border_width = std::max(dest_right_border_width, 1); - } - - // Since the width of the progress bar may not be evenly divisible by the - // tile size, in order to make it look right we may need to draw some of the - // with a width of 1 pixel smaller than the rest of the tiles. - int new_tile_width = static_cast<int>(bar_image->width() * tile_scale_y); - new_tile_width = std::max(new_tile_width, 1); - - float tile_scale_x = static_cast<float>(new_tile_width) / bar_image->width(); - if (rect.width() % new_tile_width == 0) { - DrawTiledImage(canvas, *bar_image, 0, 0, tile_scale_x, tile_scale_y, - rect.x(), rect.y(), - rect.width(), rect.height()); - } else { - int num_tiles = 1 + rect.width() / new_tile_width; - int overshoot = num_tiles * new_tile_width - rect.width(); - // Since |overshoot| represents the number of tiles that were too big, draw - // |overshoot| tiles with their width reduced by 1. - int num_big_tiles = num_tiles - overshoot; - int num_small_tiles = overshoot; - int small_width = new_tile_width - 1; - float small_scale_x = static_cast<float>(small_width) / bar_image->width(); - float big_scale_x = tile_scale_x; - - gfx::Rect big_rect = rect; - gfx::Rect small_rect = rect; - big_rect.Inset(0, 0, num_small_tiles*small_width, 0); - small_rect.Inset(num_big_tiles*new_tile_width, 0, 0, 0); - - DrawTiledImage(canvas, *bar_image, 0, 0, big_scale_x, tile_scale_y, - big_rect.x(), big_rect.y(), big_rect.width(), big_rect.height()); - DrawTiledImage(canvas, *bar_image, 0, 0, small_scale_x, tile_scale_y, - small_rect.x(), small_rect.y(), small_rect.width(), small_rect.height()); - } - if (progress_bar.value_rect_width) { - gfx::ImageSkia* value_image = rb.GetImageSkiaNamed(IDR_PROGRESS_VALUE); - - new_tile_width = static_cast<int>(value_image->width() * tile_scale_y); - tile_scale_x = static_cast<float>(new_tile_width) / - value_image->width(); - - DrawTiledImage(canvas, *value_image, 0, 0, tile_scale_x, tile_scale_y, - progress_bar.value_rect_x, - progress_bar.value_rect_y, - progress_bar.value_rect_width, - progress_bar.value_rect_height); - } - - DrawImageInt(canvas, *left_border_image, 0, 0, left_border_image->width(), - left_border_image->height(), rect.x(), rect.y(), dest_left_border_width, - rect.height()); - - int dest_x = rect.right() - dest_right_border_width; - DrawImageInt(canvas, *right_border_image, 0, 0, right_border_image->width(), - right_border_image->height(), dest_x, rect.y(), - dest_right_border_width, rect.height()); -} - -bool NativeThemeBase::IntersectsClipRectInt(SkCanvas* canvas, - int x, int y, int w, int h) const { - SkRect clip; - return canvas->getClipBounds(&clip) && - clip.intersect(SkIntToScalar(x), SkIntToScalar(y), SkIntToScalar(x + w), - SkIntToScalar(y + h)); -} - -void NativeThemeBase::DrawImageInt( - SkCanvas* sk_canvas, const gfx::ImageSkia& image, - int src_x, int src_y, int src_w, int src_h, - int dest_x, int dest_y, int dest_w, int dest_h) const { - scoped_ptr<gfx::Canvas> canvas(CommonThemeCreateCanvas(sk_canvas)); - canvas->DrawImageInt(image, src_x, src_y, src_w, src_h, - dest_x, dest_y, dest_w, dest_h, true); -} - -void NativeThemeBase::DrawTiledImage(SkCanvas* sk_canvas, - const gfx::ImageSkia& image, - int src_x, int src_y, float tile_scale_x, float tile_scale_y, - int dest_x, int dest_y, int w, int h) const { - scoped_ptr<gfx::Canvas> canvas(CommonThemeCreateCanvas(sk_canvas)); - canvas->TileImageInt(image, src_x, src_y, tile_scale_x, - tile_scale_y, dest_x, dest_y, w, h); -} - -SkColor NativeThemeBase::SaturateAndBrighten(SkScalar* hsv, - SkScalar saturate_amount, - SkScalar brighten_amount) const { - SkScalar color[3]; - color[0] = hsv[0]; - color[1] = Clamp(hsv[1] + saturate_amount, 0.0, 1.0); - color[2] = Clamp(hsv[2] + brighten_amount, 0.0, 1.0); - return SkHSVToColor(color); -} - -SkColor NativeThemeBase::GetArrowColor(State state) const { - if (state != kDisabled) - return SK_ColorBLACK; - - SkScalar track_hsv[3]; - SkColorToHSV(track_color_, track_hsv); - SkScalar thumb_hsv[3]; - SkColorToHSV(thumb_inactive_color_, thumb_hsv); - return OutlineColor(track_hsv, thumb_hsv); -} - -void NativeThemeBase::DrawVertLine(SkCanvas* canvas, - int x, - int y1, - int y2, - const SkPaint& paint) const { - SkIRect skrect; - skrect.set(x, y1, x + 1, y2 + 1); - canvas->drawIRect(skrect, paint); -} - -void NativeThemeBase::DrawHorizLine(SkCanvas* canvas, - int x1, - int x2, - int y, - const SkPaint& paint) const { - SkIRect skrect; - skrect.set(x1, y, x2 + 1, y + 1); - canvas->drawIRect(skrect, paint); -} - -void NativeThemeBase::DrawBox(SkCanvas* canvas, - const gfx::Rect& rect, - const SkPaint& paint) const { - const int right = rect.x() + rect.width() - 1; - const int bottom = rect.y() + rect.height() - 1; - DrawHorizLine(canvas, rect.x(), right, rect.y(), paint); - DrawVertLine(canvas, right, rect.y(), bottom, paint); - DrawHorizLine(canvas, rect.x(), right, bottom, paint); - DrawVertLine(canvas, rect.x(), rect.y(), bottom, paint); -} - -SkScalar NativeThemeBase::Clamp(SkScalar value, - SkScalar min, - SkScalar max) const { - return std::min(std::max(value, min), max); -} - -SkColor NativeThemeBase::OutlineColor(SkScalar* hsv1, SkScalar* hsv2) const { - // GTK Theme engines have way too much control over the layout of - // the scrollbar. We might be able to more closely approximate its - // look-and-feel, if we sent whole images instead of just colors - // from the browser to the renderer. But even then, some themes - // would just break. - // - // So, instead, we don't even try to 100% replicate the look of - // the native scrollbar. We render our own version, but we make - // sure to pick colors that blend in nicely with the system GTK - // theme. In most cases, we can just sample a couple of pixels - // from the system scrollbar and use those colors to draw our - // scrollbar. - // - // This works fine for the track color and the overall thumb - // color. But it fails spectacularly for the outline color used - // around the thumb piece. Not all themes have a clearly defined - // outline. For some of them it is partially transparent, and for - // others the thickness is very unpredictable. - // - // So, instead of trying to approximate the system theme, we - // instead try to compute a reasonable looking choice based on the - // known color of the track and the thumb piece. This is difficult - // when trying to deal both with high- and low-contrast themes, - // and both with positive and inverted themes. - // - // The following code has been tested to look OK with all of the - // default GTK themes. - SkScalar min_diff = Clamp((hsv1[1] + hsv2[1]) * 1.2f, 0.28f, 0.5f); - SkScalar diff = Clamp(fabs(hsv1[2] - hsv2[2]) / 2, min_diff, 0.5f); - - if (hsv1[2] + hsv2[2] > 1.0) - diff = -diff; - - return SaturateAndBrighten(hsv2, -0.2f, diff); -} - -} // namespace ui
diff --git a/ui/native_theme/native_theme_base.h b/ui/native_theme/native_theme_base.h deleted file mode 100644 index 8ceed5a..0000000 --- a/ui/native_theme/native_theme_base.h +++ /dev/null
@@ -1,212 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_NATIVE_THEME_NATIVE_THEME_BASE_H_ -#define UI_NATIVE_THEME_NATIVE_THEME_BASE_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "skia/ext/platform_canvas.h" -#include "ui/native_theme/native_theme.h" - -namespace gfx { -class Canvas; -class ImageSkia; -class Rect; -class Size; -} - -namespace ui { - -// Theme support for non-Windows toolkits. -class NATIVE_THEME_EXPORT NativeThemeBase : public NativeTheme { - public: - // NativeTheme implementation: - gfx::Size GetPartSize(Part part, - State state, - const ExtraParams& extra) const override; - void Paint(SkCanvas* canvas, - Part part, - State state, - const gfx::Rect& rect, - const ExtraParams& extra) const override; - - void PaintStateTransition(SkCanvas* canvas, - Part part, - State startState, - State endState, - double progress, - const gfx::Rect& rect) const override; - - protected: - NativeThemeBase(); - ~NativeThemeBase() override; - - // Draw the arrow. Used by scrollbar and inner spin button. - virtual void PaintArrowButton( - SkCanvas* gc, - const gfx::Rect& rect, - Part direction, - State state) const; - // Paint the scrollbar track. Done before the thumb so that it can contain - // alpha. - virtual void PaintScrollbarTrack( - SkCanvas* canvas, - Part part, - State state, - const ScrollbarTrackExtraParams& extra_params, - const gfx::Rect& rect) const; - // Draw the scrollbar thumb over the track. - virtual void PaintScrollbarThumb( - SkCanvas* canvas, - Part part, - State state, - const gfx::Rect& rect) const; - - virtual void PaintScrollbarCorner(SkCanvas* canvas, - State state, - const gfx::Rect& rect) const; - - virtual void PaintCheckbox( - SkCanvas* canvas, - State state, - const gfx::Rect& rect, - const ButtonExtraParams& button) const; - - virtual void PaintRadio( - SkCanvas* canvas, - State state, - const gfx::Rect& rect, - const ButtonExtraParams& button) const; - - virtual void PaintButton( - SkCanvas* canvas, - State state, - const gfx::Rect& rect, - const ButtonExtraParams& button) const; - - virtual void PaintTextField( - SkCanvas* canvas, - State state, - const gfx::Rect& rect, - const TextFieldExtraParams& text) const; - - virtual void PaintMenuList( - SkCanvas* canvas, - State state, - const gfx::Rect& rect, - const MenuListExtraParams& menu_list) const; - - virtual void PaintMenuPopupBackground( - SkCanvas* canvas, - const gfx::Size& size, - const MenuBackgroundExtraParams& menu_background) const; - - virtual void PaintMenuItemBackground( - SkCanvas* canvas, - State state, - const gfx::Rect& rect, - const MenuListExtraParams& menu_list) const; - - virtual void PaintSliderTrack( - SkCanvas* canvas, - State state, - const gfx::Rect& rect, - const SliderExtraParams& slider) const; - - virtual void PaintSliderThumb( - SkCanvas* canvas, - State state, - const gfx::Rect& rect, - const SliderExtraParams& slider) const; - - virtual void PaintInnerSpinButton( - SkCanvas* canvas, - State state, - const gfx::Rect& rect, - const InnerSpinButtonExtraParams& spin_button) const; - - virtual void PaintProgressBar( - SkCanvas* canvas, - State state, - const gfx::Rect& rect, - const ProgressBarExtraParams& progress_bar) const; - - virtual void PaintScrollbarThumbStateTransition( - SkCanvas* canvas, - State startState, - State endState, - double progress, - const gfx::Rect& rect) const {} - - void set_scrollbar_button_length(unsigned int length) { - scrollbar_button_length_ = length; - } - int scrollbar_button_length() const { return scrollbar_button_length_; } - - bool IntersectsClipRectInt(SkCanvas* canvas, - int x, int y, int w, int h) const; - - void DrawImageInt(SkCanvas* canvas, const gfx::ImageSkia& image, - int src_x, int src_y, int src_w, int src_h, - int dest_x, int dest_y, int dest_w, int dest_h) const; - - void DrawTiledImage(SkCanvas* canvas, - const gfx::ImageSkia& image, - int src_x, int src_y, - float tile_scale_x, float tile_scale_y, - int dest_x, int dest_y, int w, int h) const; - - SkColor SaturateAndBrighten(SkScalar* hsv, - SkScalar saturate_amount, - SkScalar brighten_amount) const; - - // Paints the arrow used on the scrollbar and spinner. - void PaintArrow(SkCanvas* canvas, - const gfx::Rect& rect, - Part direction, - SkColor color) const; - - // Returns the color used to draw the arrow. - SkColor GetArrowColor(State state) const; - - private: - void DrawVertLine(SkCanvas* canvas, - int x, - int y1, - int y2, - const SkPaint& paint) const; - void DrawHorizLine(SkCanvas* canvas, - int x1, - int x2, - int y, - const SkPaint& paint) const; - void DrawBox(SkCanvas* canvas, - const gfx::Rect& rect, - const SkPaint& paint) const; - SkScalar Clamp(SkScalar value, - SkScalar min, - SkScalar max) const; - SkColor OutlineColor(SkScalar* hsv1, SkScalar* hsv2) const; - - // Paint the common parts of the checkboxes and radio buttons. - // borderRadius specifies how rounded the corners should be. - SkRect PaintCheckboxRadioCommon( - SkCanvas* canvas, - State state, - const gfx::Rect& rect, - const SkScalar borderRadius) const; - - unsigned int scrollbar_width_; - - // The length of the arrow buttons, 0 means no buttons are drawn. - unsigned int scrollbar_button_length_; - - DISALLOW_COPY_AND_ASSIGN(NativeThemeBase); -}; - -} // namespace ui - -#endif // UI_NATIVE_THEME_NATIVE_THEME_BASE_H_
diff --git a/ui/native_theme/native_theme_export.h b/ui/native_theme/native_theme_export.h deleted file mode 100644 index 85641e5..0000000 --- a/ui/native_theme/native_theme_export.h +++ /dev/null
@@ -1,36 +0,0 @@ -// Copyright 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_NATIVE_THEME_NATIVE_THEME_EXPORT_H_ -#define UI_NATIVE_THEME_NATIVE_THEME_EXPORT_H_ - -// Defines NATIVE_THEME_EXPORT so that functionality implemented by the -// native_theme library can be exported to consumers. - -#if defined(COMPONENT_BUILD) -#if defined(WIN32) - -#if defined(NATIVE_THEME_IMPLEMENTATION) -#define NATIVE_THEME_EXPORT __declspec(dllexport) -#else -#define NATIVE_THEME_EXPORT __declspec(dllimport) -#endif // defined(NATIVE_THEME_IMPLEMENTATION) - -#else // !defined(WIN32) - -#if defined(NATIVE_THEME_IMPLEMENTATION) -#define NATIVE_THEME_EXPORT __attribute__((visibility("default"))) -#else -#define NATIVE_THEME_EXPORT -#endif - -#endif // defined(WIN32) - -#else // !defined(COMPONENT_BUILD) - -#define NATIVE_THEME_EXPORT - -#endif // defined(COMPONENT_BUILD) - -#endif // UI_NATIVE_THEME_NATIVE_THEME_EXPORT_H_
diff --git a/ui/native_theme/native_theme_observer.cc b/ui/native_theme/native_theme_observer.cc deleted file mode 100644 index f516a76..0000000 --- a/ui/native_theme/native_theme_observer.cc +++ /dev/null
@@ -1,11 +0,0 @@ -// Copyright (c) 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/native_theme/native_theme_observer.h" - -namespace ui { - -NativeThemeObserver::~NativeThemeObserver() {} - -} // namespace ui
diff --git a/ui/native_theme/native_theme_observer.h b/ui/native_theme/native_theme_observer.h deleted file mode 100644 index d38d663..0000000 --- a/ui/native_theme/native_theme_observer.h +++ /dev/null
@@ -1,27 +0,0 @@ -// Copyright (c) 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_NATIVE_THEME_NATIVE_THEME_OBSERVER_H_ -#define UI_NATIVE_THEME_NATIVE_THEME_OBSERVER_H_ - -#include "ui/native_theme/native_theme_export.h" - -namespace ui { - -class NativeTheme; - -// Observers which are notified when the native theme changes. -class NATIVE_THEME_EXPORT NativeThemeObserver { - public: - // Called when the native theme changes. The observed theme is passed so that - // observers may handle changes to their associated native theme instances. - virtual void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) = 0; - - protected: - virtual ~NativeThemeObserver(); -}; - -} // namespace ui - -#endif // UI_NATIVE_THEME_NATIVE_THEME_OBSERVER_H_
diff --git a/ui/native_theme/native_theme_switches.cc b/ui/native_theme/native_theme_switches.cc deleted file mode 100644 index 873af51..0000000 --- a/ui/native_theme/native_theme_switches.cc +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/command_line.h" -#include "ui/native_theme/native_theme_switches.h" - -namespace switches { - -// Enables overlay scrollbars on Aura or Linux. Does nothing on Mac. -const char kEnableOverlayScrollbar[] = "enable-overlay-scrollbar"; - -// Disables overlay scrollbars on Aura or Linux. Does nothing on Mac. -const char kDisableOverlayScrollbar[] = "disable-overlay-scrollbar"; - -} // namespace switches - -namespace ui { - -bool IsOverlayScrollbarEnabled() { - const base::CommandLine& command_line = - *base::CommandLine::ForCurrentProcess(); - - if (command_line.HasSwitch(switches::kDisableOverlayScrollbar)) - return false; - else if (command_line.HasSwitch(switches::kEnableOverlayScrollbar)) - return true; - - return false; -} - -} // namespace ui
diff --git a/ui/native_theme/native_theme_switches.h b/ui/native_theme/native_theme_switches.h deleted file mode 100644 index 026ee70..0000000 --- a/ui/native_theme/native_theme_switches.h +++ /dev/null
@@ -1,25 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// Defines all the command-line switches used by native theme - -#ifndef UI_NATIVE_THEME_NATIVE_THEME_SWITCHES_H_ -#define UI_NATIVE_THEME_NATIVE_THEME_SWITCHES_H_ - -#include "ui/native_theme/native_theme_export.h" - -namespace switches { - -NATIVE_THEME_EXPORT extern const char kDisableOverlayScrollbar[]; -NATIVE_THEME_EXPORT extern const char kEnableOverlayScrollbar[]; - -} // namespace switches - -namespace ui { - -NATIVE_THEME_EXPORT bool IsOverlayScrollbarEnabled(); - -} // namespace ui - -#endif // UI_NATIVE_THEME_NATIVE_THEME_SWITCHES_H_
diff --git a/ui/native_theme/native_theme_win.cc b/ui/native_theme/native_theme_win.cc deleted file mode 100644 index d79bdf0..0000000 --- a/ui/native_theme/native_theme_win.cc +++ /dev/null
@@ -1,2068 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/native_theme/native_theme_win.h" - -#include <windows.h> -#include <uxtheme.h> -#include <vsstyle.h> -#include <vssym32.h> - -#include "base/basictypes.h" -#include "base/logging.h" -#include "base/memory/scoped_ptr.h" -#include "base/win/scoped_gdi_object.h" -#include "base/win/scoped_hdc.h" -#include "base/win/scoped_select_object.h" -#include "base/win/windows_version.h" -#include "skia/ext/bitmap_platform_device.h" -#include "skia/ext/platform_canvas.h" -#include "skia/ext/skia_utils_win.h" -#include "third_party/skia/include/core/SkCanvas.h" -#include "third_party/skia/include/core/SkColorPriv.h" -#include "third_party/skia/include/core/SkShader.h" -#include "ui/gfx/color_utils.h" -#include "ui/gfx/gdi_util.h" -#include "ui/gfx/rect.h" -#include "ui/gfx/rect_conversions.h" -#include "ui/gfx/win/dpi.h" -#include "ui/native_theme/common_theme.h" - -// This was removed from Winvers.h but is still used. -#if !defined(COLOR_MENUHIGHLIGHT) -#define COLOR_MENUHIGHLIGHT 29 -#endif - -namespace { - -// TODO: Obtain the correct colors using GetSysColor. -// Theme colors returned by GetSystemColor(). -const SkColor kInvalidColorIdColor = SkColorSetRGB(255, 0, 128); -// Dialogs: -const SkColor kDialogBackgroundColor = SkColorSetRGB(251, 251, 251); -// FocusableBorder: -const SkColor kFocusedBorderColor = SkColorSetRGB(0x4d, 0x90, 0xfe); -const SkColor kUnfocusedBorderColor = SkColorSetRGB(0xd9, 0xd9, 0xd9); -// Button: -const SkColor kButtonBackgroundColor = SkColorSetRGB(0xde, 0xde, 0xde); -const SkColor kButtonHighlightColor = SkColorSetARGB(200, 255, 255, 255); -const SkColor kButtonHoverColor = SkColorSetRGB(6, 45, 117); -const SkColor kButtonHoverBackgroundColor = SkColorSetRGB(0xEA, 0xEA, 0xEA); -// MenuItem: -const SkColor kEnabledMenuItemForegroundColor = SkColorSetRGB(6, 45, 117); -const SkColor kDisabledMenuItemForegroundColor = SkColorSetRGB(161, 161, 146); -const SkColor kFocusedMenuItemBackgroundColor = SkColorSetRGB(246, 249, 253); -const SkColor kMenuSeparatorColor = SkColorSetARGB(50, 0, 0, 0); -// Table: -const SkColor kTreeSelectionBackgroundUnfocused = SkColorSetRGB(240, 240, 240); - -// Windows system color IDs cached and updated by the native theme. -const int kSystemColors[] = { - COLOR_3DFACE, - COLOR_BTNTEXT, - COLOR_GRAYTEXT, - COLOR_HIGHLIGHT, - COLOR_HIGHLIGHTTEXT, - COLOR_SCROLLBAR, - COLOR_WINDOW, - COLOR_WINDOWTEXT, - COLOR_BTNFACE, - COLOR_MENUHIGHLIGHT, -}; - -void SetCheckerboardShader(SkPaint* paint, const RECT& align_rect) { - // Create a 2x2 checkerboard pattern using the 3D face and highlight colors. - const SkColor face = color_utils::GetSysSkColor(COLOR_3DFACE); - const SkColor highlight = color_utils::GetSysSkColor(COLOR_3DHILIGHT); - SkColor buffer[] = { face, highlight, highlight, face }; - // Confusing bit: we first create a temporary bitmap with our desired pattern, - // then copy it to another bitmap. The temporary bitmap doesn't take - // ownership of the pixel data, and so will point to garbage when this - // function returns. The copy will copy the pixel data into a place owned by - // the bitmap, which is in turn owned by the shader, etc., so it will live - // until we're done using it. - SkImageInfo info = SkImageInfo::MakeN32Premul(2, 2); - SkBitmap temp_bitmap; - temp_bitmap.installPixels(info, buffer, info.minRowBytes()); - SkBitmap bitmap; - temp_bitmap.copyTo(&bitmap); - - // Align the pattern with the upper corner of |align_rect|. - SkMatrix local_matrix; - local_matrix.setTranslate(SkIntToScalar(align_rect.left), - SkIntToScalar(align_rect.top)); - skia::RefPtr<SkShader> shader = - skia::AdoptRef(SkShader::CreateBitmapShader(bitmap, - SkShader::kRepeat_TileMode, - SkShader::kRepeat_TileMode, - &local_matrix)); - paint->setShader(shader.get()); -} - -// <-a-> -// [ ***** ] -// ____ | | -// <-a-> <------b-----> -// a: object_width -// b: frame_width -// *: animating object -// -// - the animation goes from "[" to "]" repeatedly. -// - the animation offset is at first "|" -// -int ComputeAnimationProgress(int frame_width, - int object_width, - int pixels_per_second, - double animated_seconds) { - int animation_width = frame_width + object_width; - double interval = static_cast<double>(animation_width) / pixels_per_second; - double ratio = fmod(animated_seconds, interval) / interval; - return static_cast<int>(animation_width * ratio) - object_width; -} - -RECT InsetRect(const RECT* rect, int size) { - gfx::Rect result(*rect); - result.Inset(size, size); - return result.ToRECT(); -} - -} // namespace - -namespace ui { - -bool NativeThemeWin::IsThemingActive() const { - return is_theme_active_ && is_theme_active_(); -} - -bool NativeThemeWin::IsUsingHighContrastTheme() const { - if (is_using_high_contrast_valid_) - return is_using_high_contrast_; - HIGHCONTRAST result; - result.cbSize = sizeof(HIGHCONTRAST); - is_using_high_contrast_ = - SystemParametersInfo(SPI_GETHIGHCONTRAST, result.cbSize, &result, 0) && - (result.dwFlags & HCF_HIGHCONTRASTON) == HCF_HIGHCONTRASTON; - is_using_high_contrast_valid_ = true; - return is_using_high_contrast_; -} - -HRESULT NativeThemeWin::GetThemeColor(ThemeName theme, - int part_id, - int state_id, - int prop_id, - SkColor* color) const { - HANDLE handle = GetThemeHandle(theme); - if (!handle || !get_theme_color_) - return E_NOTIMPL; - COLORREF color_ref; - if (get_theme_color_(handle, part_id, state_id, prop_id, &color_ref) != S_OK) - return E_NOTIMPL; - *color = skia::COLORREFToSkColor(color_ref); - return S_OK; -} - -SkColor NativeThemeWin::GetThemeColorWithDefault(ThemeName theme, - int part_id, - int state_id, - int prop_id, - int default_sys_color) const { - SkColor color; - return (GetThemeColor(theme, part_id, state_id, prop_id, &color) == S_OK) ? - color : color_utils::GetSysSkColor(default_sys_color); -} - -gfx::Size NativeThemeWin::GetThemeBorderSize(ThemeName theme) const { - // For simplicity use the wildcard state==0, part==0, since it works - // for the cases we currently depend on. - int border; - return (GetThemeInt(theme, 0, 0, TMT_BORDERSIZE, &border) == S_OK) ? - gfx::Size(border, border) : - gfx::Size(GetSystemMetrics(SM_CXEDGE), GetSystemMetrics(SM_CYEDGE)); -} - -void NativeThemeWin::DisableTheming() const { - if (set_theme_properties_) - set_theme_properties_(0); -} - -void NativeThemeWin::CloseHandles() const { - if (!close_theme_) - return; - - for (int i = 0; i < LAST; ++i) { - if (theme_handles_[i]) { - close_theme_(theme_handles_[i]); - theme_handles_[i] = NULL; - } - } -} - -bool NativeThemeWin::IsClassicTheme(ThemeName name) const { - return !theme_dll_ || !GetThemeHandle(name); -} - -// static -NativeThemeWin* NativeThemeWin::instance() { - CR_DEFINE_STATIC_LOCAL(NativeThemeWin, s_native_theme, ()); - return &s_native_theme; -} - -gfx::Size NativeThemeWin::GetPartSize(Part part, - State state, - const ExtraParams& extra) const { - gfx::Size part_size = CommonThemeGetPartSize(part, state, extra); - if (!part_size.IsEmpty()) - return part_size; - - // The GetThemePartSize call below returns the default size without - // accounting for user customization (crbug/218291). - switch (part) { - case kScrollbarDownArrow: - case kScrollbarLeftArrow: - case kScrollbarRightArrow: - case kScrollbarUpArrow: - case kScrollbarHorizontalThumb: - case kScrollbarVerticalThumb: - case kScrollbarHorizontalTrack: - case kScrollbarVerticalTrack: { - int size = gfx::win::GetSystemMetricsInDIP(SM_CXVSCROLL); - if (size == 0) - size = 17; - return gfx::Size(size, size); - } - default: - break; - } - - int part_id = GetWindowsPart(part, state, extra); - int state_id = GetWindowsState(part, state, extra); - - base::win::ScopedGetDC screen_dc(NULL); - SIZE size; - if (SUCCEEDED(GetThemePartSize(GetThemeName(part), screen_dc, part_id, - state_id, NULL, TS_TRUE, &size))) - return gfx::Size(size.cx, size.cy); - - // TODO(rogerta): For now, we need to support radio buttons and checkboxes - // when theming is not enabled. Support for other parts can be added - // if/when needed. - return (part == kCheckbox || part == kRadio) ? - gfx::Size(13, 13) : gfx::Size(); -} - -void NativeThemeWin::Paint(SkCanvas* canvas, - Part part, - State state, - const gfx::Rect& rect, - const ExtraParams& extra) const { - if (rect.IsEmpty()) - return; - - switch (part) { - case kComboboxArrow: - CommonThemePaintComboboxArrow(canvas, rect); - return; - case kMenuPopupGutter: - CommonThemePaintMenuGutter(canvas, rect); - return; - case kMenuPopupSeparator: - CommonThemePaintMenuSeparator(canvas, rect, extra.menu_separator); - return; - case kMenuPopupBackground: - CommonThemePaintMenuBackground(canvas, rect); - return; - case kMenuItemBackground: - CommonThemePaintMenuItemBackground(canvas, state, rect); - return; - default: - break; - } - - bool needs_paint_indirect = false; - if (!skia::SupportsPlatformPaint(canvas)) { - // This block will only get hit with --enable-accelerated-drawing flag. - needs_paint_indirect = true; - } else { - // Scrollbar components on Windows Classic theme (on all Windows versions) - // have particularly problematic alpha values, so always draw them - // indirectly. In addition, scrollbar thumbs and grippers for the Windows XP - // theme (available only on Windows XP) also need their alpha values - // fixed. - switch (part) { - case kScrollbarDownArrow: - case kScrollbarUpArrow: - case kScrollbarLeftArrow: - case kScrollbarRightArrow: - needs_paint_indirect = !GetThemeHandle(SCROLLBAR); - break; - case kScrollbarHorizontalThumb: - case kScrollbarVerticalThumb: - case kScrollbarHorizontalGripper: - case kScrollbarVerticalGripper: - needs_paint_indirect = !GetThemeHandle(SCROLLBAR) || - base::win::GetVersion() == base::win::VERSION_XP; - break; - default: - break; - } - } - - if (needs_paint_indirect) - PaintIndirect(canvas, part, state, rect, extra); - else - PaintDirect(canvas, part, state, rect, extra); -} - -NativeThemeWin::NativeThemeWin() - : theme_dll_(LoadLibrary(L"uxtheme.dll")), - draw_theme_(NULL), - draw_theme_ex_(NULL), - get_theme_color_(NULL), - get_theme_content_rect_(NULL), - get_theme_part_size_(NULL), - open_theme_(NULL), - close_theme_(NULL), - set_theme_properties_(NULL), - is_theme_active_(NULL), - get_theme_int_(NULL), - color_change_listener_(this), - is_using_high_contrast_(false), - is_using_high_contrast_valid_(false) { - if (theme_dll_) { - draw_theme_ = reinterpret_cast<DrawThemeBackgroundPtr>( - GetProcAddress(theme_dll_, "DrawThemeBackground")); - draw_theme_ex_ = reinterpret_cast<DrawThemeBackgroundExPtr>( - GetProcAddress(theme_dll_, "DrawThemeBackgroundEx")); - get_theme_color_ = reinterpret_cast<GetThemeColorPtr>( - GetProcAddress(theme_dll_, "GetThemeColor")); - get_theme_content_rect_ = reinterpret_cast<GetThemeContentRectPtr>( - GetProcAddress(theme_dll_, "GetThemeBackgroundContentRect")); - get_theme_part_size_ = reinterpret_cast<GetThemePartSizePtr>( - GetProcAddress(theme_dll_, "GetThemePartSize")); - open_theme_ = reinterpret_cast<OpenThemeDataPtr>( - GetProcAddress(theme_dll_, "OpenThemeData")); - close_theme_ = reinterpret_cast<CloseThemeDataPtr>( - GetProcAddress(theme_dll_, "CloseThemeData")); - set_theme_properties_ = reinterpret_cast<SetThemeAppPropertiesPtr>( - GetProcAddress(theme_dll_, "SetThemeAppProperties")); - is_theme_active_ = reinterpret_cast<IsThemeActivePtr>( - GetProcAddress(theme_dll_, "IsThemeActive")); - get_theme_int_ = reinterpret_cast<GetThemeIntPtr>( - GetProcAddress(theme_dll_, "GetThemeInt")); - } - memset(theme_handles_, 0, sizeof(theme_handles_)); - - // Initialize the cached system colors. - UpdateSystemColors(); -} - -NativeThemeWin::~NativeThemeWin() { - if (theme_dll_) { - // todo (cpu): fix this soon. Making a call to CloseHandles() here breaks - // certain tests and the reliability bots. - // CloseHandles(); - FreeLibrary(theme_dll_); - } -} - -void NativeThemeWin::OnSysColorChange() { - UpdateSystemColors(); - is_using_high_contrast_valid_ = false; - NotifyObservers(); -} - -void NativeThemeWin::UpdateSystemColors() { - for (int i = 0; i < arraysize(kSystemColors); ++i) { - system_colors_[kSystemColors[i]] = - color_utils::GetSysSkColor(kSystemColors[i]); - } -} - -void NativeThemeWin::PaintDirect(SkCanvas* canvas, - Part part, - State state, - const gfx::Rect& rect, - const ExtraParams& extra) const { - skia::ScopedPlatformPaint scoped_platform_paint(canvas); - HDC hdc = scoped_platform_paint.GetPlatformSurface(); - - switch (part) { - case kCheckbox: - PaintCheckbox(hdc, part, state, rect, extra.button); - return; - case kInnerSpinButton: - PaintSpinButton(hdc, part, state, rect, extra.inner_spin); - return; - case kMenuList: - PaintMenuList(hdc, state, rect, extra.menu_list); - return; - case kMenuCheck: - PaintMenuCheck(hdc, state, rect, extra.menu_check); - return; - case kMenuCheckBackground: - PaintMenuCheckBackground(hdc, state, rect); - return; - case kMenuPopupArrow: - PaintMenuArrow(hdc, state, rect, extra.menu_arrow); - return; - case kMenuPopupBackground: - PaintMenuBackground(hdc, rect); - return; - case kMenuPopupGutter: - PaintMenuGutter(hdc, rect); - return; - case kMenuPopupSeparator: - PaintMenuSeparator(hdc, rect); - return; - case kMenuItemBackground: - PaintMenuItemBackground(hdc, state, rect, extra.menu_item); - return; - case kProgressBar: - PaintProgressBar(hdc, rect, extra.progress_bar); - return; - case kPushButton: - PaintPushButton(hdc, part, state, rect, extra.button); - return; - case kRadio: - PaintRadioButton(hdc, part, state, rect, extra.button); - return; - case kScrollbarDownArrow: - case kScrollbarUpArrow: - case kScrollbarLeftArrow: - case kScrollbarRightArrow: - PaintScrollbarArrow(hdc, part, state, rect, extra.scrollbar_arrow); - return; - case kScrollbarHorizontalThumb: - case kScrollbarVerticalThumb: - case kScrollbarHorizontalGripper: - case kScrollbarVerticalGripper: - PaintScrollbarThumb(hdc, part, state, rect, extra.scrollbar_thumb); - return; - case kScrollbarHorizontalTrack: - case kScrollbarVerticalTrack: - PaintScrollbarTrack(canvas, hdc, part, state, rect, - extra.scrollbar_track); - return; - case kScrollbarCorner: - canvas->drawColor(SK_ColorWHITE, SkXfermode::kSrc_Mode); - return; - case kTabPanelBackground: - PaintTabPanelBackground(hdc, rect); - return; - case kTextField: - PaintTextField(hdc, part, state, rect, extra.text_field); - return; - case kTrackbarThumb: - case kTrackbarTrack: - PaintTrackbar(canvas, hdc, part, state, rect, extra.trackbar); - return; - case kWindowResizeGripper: - PaintWindowResizeGripper(hdc, rect); - return; - case kComboboxArrow: - case kSliderTrack: - case kSliderThumb: - case kMaxPart: - NOTREACHED(); - } -} - -SkColor NativeThemeWin::GetSystemColor(ColorId color_id) const { - SkColor color; - if (CommonThemeGetSystemColor(color_id, &color)) - return color; - - switch (color_id) { - // Windows - case kColorId_WindowBackground: - return system_colors_[COLOR_WINDOW]; - - // Dialogs - case kColorId_DialogBackground: - return gfx::IsInvertedColorScheme() ? - color_utils::InvertColor(kDialogBackgroundColor) : - kDialogBackgroundColor; - - // FocusableBorder - case kColorId_FocusedBorderColor: - return kFocusedBorderColor; - case kColorId_UnfocusedBorderColor: - return kUnfocusedBorderColor; - - // Button - case kColorId_ButtonBackgroundColor: - return kButtonBackgroundColor; - case kColorId_ButtonEnabledColor: - return system_colors_[COLOR_BTNTEXT]; - case kColorId_ButtonDisabledColor: - return system_colors_[COLOR_GRAYTEXT]; - case kColorId_ButtonHighlightColor: - return kButtonHighlightColor; - case kColorId_ButtonHoverColor: - return kButtonHoverColor; - case kColorId_ButtonHoverBackgroundColor: - return kButtonHoverBackgroundColor; - case kColorId_BlueButtonEnabledColor: - case kColorId_BlueButtonDisabledColor: - case kColorId_BlueButtonPressedColor: - case kColorId_BlueButtonHoverColor: - NOTREACHED(); - return kInvalidColorIdColor; - - // MenuItem - case kColorId_EnabledMenuItemForegroundColor: - return kEnabledMenuItemForegroundColor; - case kColorId_DisabledMenuItemForegroundColor: - return kDisabledMenuItemForegroundColor; - case kColorId_DisabledEmphasizedMenuItemForegroundColor: - return SK_ColorBLACK; - case kColorId_FocusedMenuItemBackgroundColor: - return kFocusedMenuItemBackgroundColor; - case kColorId_MenuSeparatorColor: - return kMenuSeparatorColor; - case kColorId_SelectedMenuItemForegroundColor: - case kColorId_HoverMenuItemBackgroundColor: - case kColorId_MenuBackgroundColor: - case kColorId_MenuBorderColor: - NOTREACHED(); - return kInvalidColorIdColor; - - // MenuButton - case kColorId_EnabledMenuButtonBorderColor: - case kColorId_FocusedMenuButtonBorderColor: - case kColorId_HoverMenuButtonBorderColor: - NOTREACHED(); - return kInvalidColorIdColor; - - // Label - case kColorId_LabelEnabledColor: - return system_colors_[COLOR_BTNTEXT]; - case kColorId_LabelDisabledColor: - return system_colors_[COLOR_GRAYTEXT]; - case kColorId_LabelBackgroundColor: - return system_colors_[COLOR_WINDOW]; - - // Textfield - case kColorId_TextfieldDefaultColor: - return system_colors_[COLOR_WINDOWTEXT]; - case kColorId_TextfieldDefaultBackground: - return system_colors_[COLOR_WINDOW]; - case kColorId_TextfieldReadOnlyColor: - return system_colors_[COLOR_GRAYTEXT]; - case kColorId_TextfieldReadOnlyBackground: - return system_colors_[COLOR_3DFACE]; - case kColorId_TextfieldSelectionColor: - return system_colors_[COLOR_HIGHLIGHTTEXT]; - case kColorId_TextfieldSelectionBackgroundFocused: - return system_colors_[COLOR_HIGHLIGHT]; - - // Tooltip - case kColorId_TooltipBackground: - case kColorId_TooltipText: - NOTREACHED(); - return kInvalidColorIdColor; - - // Tree - // NOTE: these aren't right for all themes, but as close as I could get. - case kColorId_TreeBackground: - return system_colors_[COLOR_WINDOW]; - case kColorId_TreeText: - return system_colors_[COLOR_WINDOWTEXT]; - case kColorId_TreeSelectedText: - return system_colors_[COLOR_HIGHLIGHTTEXT]; - case kColorId_TreeSelectedTextUnfocused: - return system_colors_[COLOR_BTNTEXT]; - case kColorId_TreeSelectionBackgroundFocused: - return system_colors_[COLOR_HIGHLIGHT]; - case kColorId_TreeSelectionBackgroundUnfocused: - return system_colors_[IsUsingHighContrastTheme() ? - COLOR_MENUHIGHLIGHT : COLOR_BTNFACE]; - case kColorId_TreeArrow: - return system_colors_[COLOR_WINDOWTEXT]; - - // Table - case kColorId_TableBackground: - return system_colors_[COLOR_WINDOW]; - case kColorId_TableText: - return system_colors_[COLOR_WINDOWTEXT]; - case kColorId_TableSelectedText: - return system_colors_[COLOR_HIGHLIGHTTEXT]; - case kColorId_TableSelectedTextUnfocused: - return system_colors_[COLOR_BTNTEXT]; - case kColorId_TableSelectionBackgroundFocused: - return system_colors_[COLOR_HIGHLIGHT]; - case kColorId_TableSelectionBackgroundUnfocused: - return system_colors_[IsUsingHighContrastTheme() ? - COLOR_MENUHIGHLIGHT : COLOR_BTNFACE]; - case kColorId_TableGroupingIndicatorColor: - return system_colors_[COLOR_GRAYTEXT]; - - // Results Tables - case kColorId_ResultsTableNormalBackground: - return system_colors_[COLOR_WINDOW]; - case kColorId_ResultsTableHoveredBackground: - return color_utils::AlphaBlend(system_colors_[COLOR_HIGHLIGHT], - system_colors_[COLOR_WINDOW], 0x40); - case kColorId_ResultsTableSelectedBackground: - return system_colors_[COLOR_HIGHLIGHT]; - case kColorId_ResultsTableNormalText: - case kColorId_ResultsTableHoveredText: - return system_colors_[COLOR_WINDOWTEXT]; - case kColorId_ResultsTableSelectedText: - return system_colors_[COLOR_HIGHLIGHTTEXT]; - case kColorId_ResultsTableNormalDimmedText: - return color_utils::AlphaBlend(system_colors_[COLOR_WINDOWTEXT], - system_colors_[COLOR_WINDOW], 0x80); - case kColorId_ResultsTableHoveredDimmedText: - return color_utils::AlphaBlend( - system_colors_[COLOR_WINDOWTEXT], - GetSystemColor(kColorId_ResultsTableHoveredBackground), 0x80); - case kColorId_ResultsTableSelectedDimmedText: - return color_utils::AlphaBlend(system_colors_[COLOR_HIGHLIGHTTEXT], - system_colors_[COLOR_HIGHLIGHT], 0x80); - case kColorId_ResultsTableNormalUrl: - return color_utils::GetReadableColor(SkColorSetRGB(0, 128, 0), - system_colors_[COLOR_WINDOW]); - case kColorId_ResultsTableHoveredUrl: - return color_utils::GetReadableColor( - SkColorSetRGB(0, 128, 0), - GetSystemColor(kColorId_ResultsTableHoveredBackground)); - case kColorId_ResultsTableSelectedUrl: - return color_utils::GetReadableColor(SkColorSetRGB(0, 128, 0), - system_colors_[COLOR_HIGHLIGHT]); - case kColorId_ResultsTableNormalDivider: - return color_utils::AlphaBlend(system_colors_[COLOR_WINDOWTEXT], - system_colors_[COLOR_WINDOW], 0x34); - case kColorId_ResultsTableHoveredDivider: - return color_utils::AlphaBlend( - system_colors_[COLOR_WINDOWTEXT], - GetSystemColor(kColorId_ResultsTableHoveredBackground), 0x34); - case kColorId_ResultsTableSelectedDivider: - return color_utils::AlphaBlend(system_colors_[COLOR_HIGHLIGHTTEXT], - system_colors_[COLOR_HIGHLIGHT], 0x34); - } - NOTREACHED(); - return kInvalidColorIdColor; -} - -void NativeThemeWin::PaintIndirect(SkCanvas* canvas, - Part part, - State state, - const gfx::Rect& rect, - const ExtraParams& extra) const { - // TODO(asvitkine): This path is pretty inefficient - for each paint operation - // it creates a new offscreen bitmap Skia canvas. This can - // be sped up by doing it only once per part/state and - // keeping a cache of the resulting bitmaps. - - // Create an offscreen canvas that is backed by an HDC. - skia::RefPtr<skia::BitmapPlatformDevice> device = skia::AdoptRef( - skia::BitmapPlatformDevice::Create( - rect.width(), rect.height(), false, NULL)); - DCHECK(device); - SkCanvas offscreen_canvas(device.get()); - DCHECK(skia::SupportsPlatformPaint(&offscreen_canvas)); - - // Some of the Windows theme drawing operations do not write correct alpha - // values for fully-opaque pixels; instead the pixels get alpha 0. This is - // especially a problem on Windows XP or when using the Classic theme. - // - // To work-around this, mark all pixels with a placeholder value, to detect - // which pixels get touched by the paint operation. After paint, set any - // pixels that have alpha 0 to opaque and placeholders to fully-transparent. - const SkColor placeholder = SkColorSetARGB(1, 0, 0, 0); - offscreen_canvas.clear(placeholder); - - // Offset destination rects to have origin (0,0). - gfx::Rect adjusted_rect(rect.size()); - ExtraParams adjusted_extra(extra); - switch (part) { - case kProgressBar: - adjusted_extra.progress_bar.value_rect_x = 0; - adjusted_extra.progress_bar.value_rect_y = 0; - break; - case kScrollbarHorizontalTrack: - case kScrollbarVerticalTrack: - adjusted_extra.scrollbar_track.track_x = 0; - adjusted_extra.scrollbar_track.track_y = 0; - break; - default: - break; - } - // Draw the theme controls using existing HDC-drawing code. - PaintDirect(&offscreen_canvas, part, state, adjusted_rect, adjusted_extra); - - // Copy the pixels to a bitmap that has ref-counted pixel storage, which is - // necessary to have when drawing to a SkPicture. - const SkBitmap& hdc_bitmap = - offscreen_canvas.getDevice()->accessBitmap(false); - SkBitmap bitmap; - hdc_bitmap.copyTo(&bitmap, kN32_SkColorType); - - // Post-process the pixels to fix up the alpha values (see big comment above). - const SkPMColor placeholder_value = SkPreMultiplyColor(placeholder); - const int pixel_count = rect.width() * rect.height(); - SkPMColor* pixels = bitmap.getAddr32(0, 0); - for (int i = 0; i < pixel_count; i++) { - if (pixels[i] == placeholder_value) { - // Pixel wasn't touched - make it fully transparent. - pixels[i] = SkPackARGB32(0, 0, 0, 0); - } else if (SkGetPackedA32(pixels[i]) == 0) { - // Pixel was touched but has incorrect alpha of 0, make it fully opaque. - pixels[i] = SkPackARGB32(0xFF, - SkGetPackedR32(pixels[i]), - SkGetPackedG32(pixels[i]), - SkGetPackedB32(pixels[i])); - } - } - - // Draw the offscreen bitmap to the destination canvas. - canvas->drawBitmap(bitmap, rect.x(), rect.y()); -} - -HRESULT NativeThemeWin::GetThemePartSize(ThemeName theme_name, - HDC hdc, - int part_id, - int state_id, - RECT* rect, - int ts, - SIZE* size) const { - HANDLE handle = GetThemeHandle(theme_name); - return (handle && get_theme_part_size_) ? - get_theme_part_size_(handle, hdc, part_id, state_id, rect, ts, size) : - E_NOTIMPL; -} - -HRESULT NativeThemeWin::PaintButton(HDC hdc, - State state, - const ButtonExtraParams& extra, - int part_id, - int state_id, - RECT* rect) const { - HANDLE handle = GetThemeHandle(BUTTON); - if (handle && draw_theme_) - return draw_theme_(handle, hdc, part_id, state_id, rect, NULL); - - // Adjust classic_state based on part, state, and extras. - int classic_state = extra.classic_state; - switch (part_id) { - case BP_CHECKBOX: - classic_state |= DFCS_BUTTONCHECK; - break; - case BP_RADIOBUTTON: - classic_state |= DFCS_BUTTONRADIO; - break; - case BP_PUSHBUTTON: - classic_state |= DFCS_BUTTONPUSH; - break; - default: - NOTREACHED(); - break; - } - - switch (state) { - case kDisabled: - classic_state |= DFCS_INACTIVE; - break; - case kHovered: - case kNormal: - break; - case kPressed: - classic_state |= DFCS_PUSHED; - break; - case kNumStates: - NOTREACHED(); - break; - } - - if (extra.checked) - classic_state |= DFCS_CHECKED; - - // Draw it manually. - // All pressed states have both low bits set, and no other states do. - const bool focused = ((state_id & ETS_FOCUSED) == ETS_FOCUSED); - const bool pressed = ((state_id & PBS_PRESSED) == PBS_PRESSED); - if ((BP_PUSHBUTTON == part_id) && (pressed || focused)) { - // BP_PUSHBUTTON has a focus rect drawn around the outer edge, and the - // button itself is shrunk by 1 pixel. - HBRUSH brush = GetSysColorBrush(COLOR_3DDKSHADOW); - if (brush) { - FrameRect(hdc, rect, brush); - InflateRect(rect, -1, -1); - } - } - DrawFrameControl(hdc, rect, DFC_BUTTON, classic_state); - - // Draw the focus rectangle (the dotted line box) only on buttons. For radio - // and checkboxes, we let webkit draw the focus rectangle (orange glow). - if ((BP_PUSHBUTTON == part_id) && focused) { - // The focus rect is inside the button. The exact number of pixels depends - // on whether we're in classic mode or using uxtheme. - if (handle && get_theme_content_rect_) { - get_theme_content_rect_(handle, hdc, part_id, state_id, rect, rect); - } else { - InflateRect(rect, -GetSystemMetrics(SM_CXEDGE), - -GetSystemMetrics(SM_CYEDGE)); - } - DrawFocusRect(hdc, rect); - } - - // Classic theme doesn't support indeterminate checkboxes. We draw - // a recangle inside a checkbox like IE10 does. - if (part_id == BP_CHECKBOX && extra.indeterminate) { - RECT inner_rect = *rect; - // "4 / 13" is same as IE10 in classic theme. - int padding = (inner_rect.right - inner_rect.left) * 4 / 13; - InflateRect(&inner_rect, -padding, -padding); - int color_index = state == kDisabled ? COLOR_GRAYTEXT : COLOR_WINDOWTEXT; - FillRect(hdc, &inner_rect, GetSysColorBrush(color_index)); - } - - return S_OK; -} - -HRESULT NativeThemeWin::PaintMenuSeparator( - HDC hdc, - const gfx::Rect& rect) const { - RECT rect_win = rect.ToRECT(); - - HANDLE handle = GetThemeHandle(MENU); - if (handle && draw_theme_) { - // Delta is needed for non-classic to move separator up slightly. - --rect_win.top; - --rect_win.bottom; - return draw_theme_(handle, hdc, MENU_POPUPSEPARATOR, MPI_NORMAL, &rect_win, - NULL); - } - - DrawEdge(hdc, &rect_win, EDGE_ETCHED, BF_TOP); - return S_OK; -} - -HRESULT NativeThemeWin::PaintMenuGutter(HDC hdc, - const gfx::Rect& rect) const { - RECT rect_win = rect.ToRECT(); - HANDLE handle = GetThemeHandle(MENU); - return (handle && draw_theme_) ? - draw_theme_(handle, hdc, MENU_POPUPGUTTER, MPI_NORMAL, &rect_win, NULL) : - E_NOTIMPL; -} - -HRESULT NativeThemeWin::PaintMenuArrow( - HDC hdc, - State state, - const gfx::Rect& rect, - const MenuArrowExtraParams& extra) const { - int state_id = MSM_NORMAL; - if (state == kDisabled) - state_id = MSM_DISABLED; - - HANDLE handle = GetThemeHandle(MENU); - RECT rect_win = rect.ToRECT(); - if (handle && draw_theme_) { - if (extra.pointing_right) { - return draw_theme_(handle, hdc, MENU_POPUPSUBMENU, state_id, &rect_win, - NULL); - } - // There is no way to tell the uxtheme API to draw a left pointing arrow; it - // doesn't have a flag equivalent to DFCS_MENUARROWRIGHT. But they are - // needed for RTL locales on Vista. So use a memory DC and mirror the - // region with GDI's StretchBlt. - gfx::Rect r(rect); - base::win::ScopedCreateDC mem_dc(CreateCompatibleDC(hdc)); - base::win::ScopedBitmap mem_bitmap(CreateCompatibleBitmap(hdc, r.width(), - r.height())); - base::win::ScopedSelectObject select_bitmap(mem_dc.Get(), mem_bitmap); - // Copy and horizontally mirror the background from hdc into mem_dc. Use - // a negative-width source rect, starting at the rightmost pixel. - StretchBlt(mem_dc.Get(), 0, 0, r.width(), r.height(), - hdc, r.right()-1, r.y(), -r.width(), r.height(), SRCCOPY); - // Draw the arrow. - RECT theme_rect = {0, 0, r.width(), r.height()}; - HRESULT result = draw_theme_(handle, mem_dc.Get(), MENU_POPUPSUBMENU, - state_id, &theme_rect, NULL); - // Copy and mirror the result back into mem_dc. - StretchBlt(hdc, r.x(), r.y(), r.width(), r.height(), - mem_dc.Get(), r.width()-1, 0, -r.width(), r.height(), SRCCOPY); - return result; - } - - // For some reason, Windows uses the name DFCS_MENUARROWRIGHT to indicate a - // left pointing arrow. This makes the following statement counterintuitive. - UINT pfc_state = extra.pointing_right ? DFCS_MENUARROW : DFCS_MENUARROWRIGHT; - return PaintFrameControl(hdc, rect, DFC_MENU, pfc_state, extra.is_selected, - state); -} - -HRESULT NativeThemeWin::PaintMenuBackground(HDC hdc, - const gfx::Rect& rect) const { - HANDLE handle = GetThemeHandle(MENU); - RECT rect_win = rect.ToRECT(); - if (handle && draw_theme_) { - HRESULT result = draw_theme_(handle, hdc, MENU_POPUPBACKGROUND, 0, - &rect_win, NULL); - FrameRect(hdc, &rect_win, GetSysColorBrush(COLOR_3DSHADOW)); - return result; - } - - FillRect(hdc, &rect_win, GetSysColorBrush(COLOR_MENU)); - DrawEdge(hdc, &rect_win, EDGE_RAISED, BF_RECT); - return S_OK; -} - -HRESULT NativeThemeWin::PaintMenuCheck( - HDC hdc, - State state, - const gfx::Rect& rect, - const MenuCheckExtraParams& extra) const { - HANDLE handle = GetThemeHandle(MENU); - if (handle && draw_theme_) { - const int state_id = extra.is_radio ? - ((state == kDisabled) ? MC_BULLETDISABLED : MC_BULLETNORMAL) : - ((state == kDisabled) ? MC_CHECKMARKDISABLED : MC_CHECKMARKNORMAL); - RECT rect_win = rect.ToRECT(); - return draw_theme_(handle, hdc, MENU_POPUPCHECK, state_id, &rect_win, NULL); - } - - return PaintFrameControl(hdc, rect, DFC_MENU, - extra.is_radio ? DFCS_MENUBULLET : DFCS_MENUCHECK, - extra.is_selected, state); -} - -HRESULT NativeThemeWin::PaintMenuCheckBackground(HDC hdc, - State state, - const gfx::Rect& rect) const { - HANDLE handle = GetThemeHandle(MENU); - if (!handle || !draw_theme_) - return S_OK; // Nothing to do for background. - - int state_id = state == kDisabled ? MCB_DISABLED : MCB_NORMAL; - RECT rect_win = rect.ToRECT(); - return draw_theme_(handle, hdc, MENU_POPUPCHECKBACKGROUND, state_id, - &rect_win, NULL); -} - -HRESULT NativeThemeWin::PaintMenuItemBackground( - HDC hdc, - State state, - const gfx::Rect& rect, - const MenuItemExtraParams& extra) const { - HANDLE handle = GetThemeHandle(MENU); - RECT rect_win = rect.ToRECT(); - int state_id = MPI_NORMAL; - switch (state) { - case kDisabled: - state_id = extra.is_selected ? MPI_DISABLEDHOT : MPI_DISABLED; - break; - case kHovered: - state_id = MPI_HOT; - break; - case kNormal: - break; - case kPressed: - case kNumStates: - NOTREACHED(); - break; - } - - if (handle && draw_theme_) - return draw_theme_(handle, hdc, MENU_POPUPITEM, state_id, &rect_win, NULL); - - if (extra.is_selected) - FillRect(hdc, &rect_win, GetSysColorBrush(COLOR_HIGHLIGHT)); - return S_OK; -} - -HRESULT NativeThemeWin::PaintPushButton(HDC hdc, - Part part, - State state, - const gfx::Rect& rect, - const ButtonExtraParams& extra) const { - int state_id = extra.is_default ? PBS_DEFAULTED : PBS_NORMAL; - switch (state) { - case kDisabled: - state_id = PBS_DISABLED; - break; - case kHovered: - state_id = PBS_HOT; - break; - case kNormal: - break; - case kPressed: - state_id = PBS_PRESSED; - break; - case kNumStates: - NOTREACHED(); - break; - } - - RECT rect_win = rect.ToRECT(); - return PaintButton(hdc, state, extra, BP_PUSHBUTTON, state_id, &rect_win); -} - -HRESULT NativeThemeWin::PaintRadioButton(HDC hdc, - Part part, - State state, - const gfx::Rect& rect, - const ButtonExtraParams& extra) const { - int state_id = extra.checked ? RBS_CHECKEDNORMAL : RBS_UNCHECKEDNORMAL; - switch (state) { - case kDisabled: - state_id = extra.checked ? RBS_CHECKEDDISABLED : RBS_UNCHECKEDDISABLED; - break; - case kHovered: - state_id = extra.checked ? RBS_CHECKEDHOT : RBS_UNCHECKEDHOT; - break; - case kNormal: - break; - case kPressed: - state_id = extra.checked ? RBS_CHECKEDPRESSED : RBS_UNCHECKEDPRESSED; - break; - case kNumStates: - NOTREACHED(); - break; - } - - RECT rect_win = rect.ToRECT(); - return PaintButton(hdc, state, extra, BP_RADIOBUTTON, state_id, &rect_win); -} - -HRESULT NativeThemeWin::PaintCheckbox(HDC hdc, - Part part, - State state, - const gfx::Rect& rect, - const ButtonExtraParams& extra) const { - int state_id = extra.checked ? - CBS_CHECKEDNORMAL : - (extra.indeterminate ? CBS_MIXEDNORMAL : CBS_UNCHECKEDNORMAL); - switch (state) { - case kDisabled: - state_id = extra.checked ? - CBS_CHECKEDDISABLED : - (extra.indeterminate ? CBS_MIXEDDISABLED : CBS_UNCHECKEDDISABLED); - break; - case kHovered: - state_id = extra.checked ? - CBS_CHECKEDHOT : - (extra.indeterminate ? CBS_MIXEDHOT : CBS_UNCHECKEDHOT); - break; - case kNormal: - break; - case kPressed: - state_id = extra.checked ? - CBS_CHECKEDPRESSED : - (extra.indeterminate ? CBS_MIXEDPRESSED : CBS_UNCHECKEDPRESSED); - break; - case kNumStates: - NOTREACHED(); - break; - } - - RECT rect_win = rect.ToRECT(); - return PaintButton(hdc, state, extra, BP_CHECKBOX, state_id, &rect_win); -} - -HRESULT NativeThemeWin::PaintMenuList(HDC hdc, - State state, - const gfx::Rect& rect, - const MenuListExtraParams& extra) const { - HANDLE handle = GetThemeHandle(MENULIST); - RECT rect_win = rect.ToRECT(); - int state_id = CBXS_NORMAL; - switch (state) { - case kDisabled: - state_id = CBXS_DISABLED; - break; - case kHovered: - state_id = CBXS_HOT; - break; - case kNormal: - break; - case kPressed: - state_id = CBXS_PRESSED; - break; - case kNumStates: - NOTREACHED(); - break; - } - - if (handle && draw_theme_) - return draw_theme_(handle, hdc, CP_DROPDOWNBUTTON, state_id, &rect_win, - NULL); - - // Draw it manually. - DrawFrameControl(hdc, &rect_win, DFC_SCROLL, - DFCS_SCROLLCOMBOBOX | extra.classic_state); - return S_OK; -} - -HRESULT NativeThemeWin::PaintScrollbarArrow( - HDC hdc, - Part part, - State state, - const gfx::Rect& rect, - const ScrollbarArrowExtraParams& extra) const { - static const int state_id_matrix[4][kNumStates] = { - ABS_DOWNDISABLED, ABS_DOWNHOT, ABS_DOWNNORMAL, ABS_DOWNPRESSED, - ABS_LEFTDISABLED, ABS_LEFTHOT, ABS_LEFTNORMAL, ABS_LEFTPRESSED, - ABS_RIGHTDISABLED, ABS_RIGHTHOT, ABS_RIGHTNORMAL, ABS_RIGHTPRESSED, - ABS_UPDISABLED, ABS_UPHOT, ABS_UPNORMAL, ABS_UPPRESSED - }; - HANDLE handle = GetThemeHandle(SCROLLBAR); - RECT rect_win = rect.ToRECT(); - if (handle && draw_theme_) { - int index = part - kScrollbarDownArrow; - DCHECK_GE(index, 0); - DCHECK_LT(static_cast<size_t>(index), arraysize(state_id_matrix)); - int state_id = state_id_matrix[index][state]; - - // Hovering means that the cursor is over the scroolbar, but not over the - // specific arrow itself. We don't want to show it "hot" mode, but only - // in "hover" mode. - if (state == kHovered && extra.is_hovering) { - switch (part) { - case kScrollbarDownArrow: - state_id = ABS_DOWNHOVER; - break; - case kScrollbarLeftArrow: - state_id = ABS_LEFTHOVER; - break; - case kScrollbarRightArrow: - state_id = ABS_RIGHTHOVER; - break; - case kScrollbarUpArrow: - state_id = ABS_UPHOVER; - break; - default: - NOTREACHED(); - break; - } - } - return PaintScaledTheme(handle, hdc, SBP_ARROWBTN, state_id, rect); - } - - int classic_state = DFCS_SCROLLDOWN; - switch (part) { - case kScrollbarDownArrow: - break; - case kScrollbarLeftArrow: - classic_state = DFCS_SCROLLLEFT; - break; - case kScrollbarRightArrow: - classic_state = DFCS_SCROLLRIGHT; - break; - case kScrollbarUpArrow: - classic_state = DFCS_SCROLLUP; - break; - default: - NOTREACHED(); - break; - } - switch (state) { - case kDisabled: - classic_state |= DFCS_INACTIVE; - break; - case kHovered: - classic_state |= DFCS_HOT; - break; - case kNormal: - break; - case kPressed: - classic_state |= DFCS_PUSHED; - break; - case kNumStates: - NOTREACHED(); - break; - } - DrawFrameControl(hdc, &rect_win, DFC_SCROLL, classic_state); - return S_OK; -} - -HRESULT NativeThemeWin::PaintScrollbarThumb( - HDC hdc, - Part part, - State state, - const gfx::Rect& rect, - const ScrollbarThumbExtraParams& extra) const { - HANDLE handle = GetThemeHandle(SCROLLBAR); - RECT rect_win = rect.ToRECT(); - - int part_id = SBP_THUMBBTNVERT; - switch (part) { - case kScrollbarHorizontalThumb: - part_id = SBP_THUMBBTNHORZ; - break; - case kScrollbarVerticalThumb: - break; - case kScrollbarHorizontalGripper: - part_id = SBP_GRIPPERHORZ; - break; - case kScrollbarVerticalGripper: - part_id = SBP_GRIPPERVERT; - break; - default: - NOTREACHED(); - break; - } - - int state_id = SCRBS_NORMAL; - switch (state) { - case kDisabled: - state_id = SCRBS_DISABLED; - break; - case kHovered: - state_id = extra.is_hovering ? SCRBS_HOVER : SCRBS_HOT; - break; - case kNormal: - break; - case kPressed: - state_id = SCRBS_PRESSED; - break; - case kNumStates: - NOTREACHED(); - break; - } - - if (handle && draw_theme_) - return PaintScaledTheme(handle, hdc, part_id, state_id, rect); - - // Draw it manually. - if ((part_id == SBP_THUMBBTNHORZ) || (part_id == SBP_THUMBBTNVERT)) - DrawEdge(hdc, &rect_win, EDGE_RAISED, BF_RECT | BF_MIDDLE); - // Classic mode doesn't have a gripper. - return S_OK; -} - -HRESULT NativeThemeWin::PaintScrollbarTrack( - SkCanvas* canvas, - HDC hdc, - Part part, - State state, - const gfx::Rect& rect, - const ScrollbarTrackExtraParams& extra) const { - HANDLE handle = GetThemeHandle(SCROLLBAR); - RECT rect_win = rect.ToRECT(); - - const int part_id = extra.is_upper ? - ((part == kScrollbarHorizontalTrack) ? - SBP_UPPERTRACKHORZ : SBP_UPPERTRACKVERT) : - ((part == kScrollbarHorizontalTrack) ? - SBP_LOWERTRACKHORZ : SBP_LOWERTRACKVERT); - - int state_id = SCRBS_NORMAL; - switch (state) { - case kDisabled: - state_id = SCRBS_DISABLED; - break; - case kHovered: - state_id = SCRBS_HOVER; - break; - case kNormal: - break; - case kPressed: - state_id = SCRBS_PRESSED; - break; - case kNumStates: - NOTREACHED(); - break; - } - - if (handle && draw_theme_) - return draw_theme_(handle, hdc, part_id, state_id, &rect_win, NULL); - - // Draw it manually. - if ((system_colors_[COLOR_SCROLLBAR] != system_colors_[COLOR_3DFACE]) && - (system_colors_[COLOR_SCROLLBAR] != system_colors_[COLOR_WINDOW])) { - FillRect(hdc, &rect_win, reinterpret_cast<HBRUSH>(COLOR_SCROLLBAR + 1)); - } else { - SkPaint paint; - RECT align_rect = gfx::Rect(extra.track_x, extra.track_y, extra.track_width, - extra.track_height).ToRECT(); - SetCheckerboardShader(&paint, align_rect); - canvas->drawIRect(skia::RECTToSkIRect(rect_win), paint); - } - if (extra.classic_state & DFCS_PUSHED) - InvertRect(hdc, &rect_win); - return S_OK; -} - -HRESULT NativeThemeWin::PaintSpinButton( - HDC hdc, - Part part, - State state, - const gfx::Rect& rect, - const InnerSpinButtonExtraParams& extra) const { - HANDLE handle = GetThemeHandle(SPIN); - RECT rect_win = rect.ToRECT(); - int part_id = extra.spin_up ? SPNP_UP : SPNP_DOWN; - int state_id = extra.spin_up ? UPS_NORMAL : DNS_NORMAL; - switch (state) { - case kDisabled: - state_id = extra.spin_up ? UPS_DISABLED : DNS_DISABLED; - break; - case kHovered: - state_id = extra.spin_up ? UPS_HOT : DNS_HOT; - break; - case kNormal: - break; - case kPressed: - state_id = extra.spin_up ? UPS_PRESSED : DNS_PRESSED; - break; - case kNumStates: - NOTREACHED(); - break; - } - - if (handle && draw_theme_) - return draw_theme_(handle, hdc, part_id, state_id, &rect_win, NULL); - DrawFrameControl(hdc, &rect_win, DFC_SCROLL, extra.classic_state); - return S_OK; -} - -HRESULT NativeThemeWin::PaintTrackbar( - SkCanvas* canvas, - HDC hdc, - Part part, - State state, - const gfx::Rect& rect, - const TrackbarExtraParams& extra) const { - const int part_id = extra.vertical ? - ((part == kTrackbarTrack) ? TKP_TRACKVERT : TKP_THUMBVERT) : - ((part == kTrackbarTrack) ? TKP_TRACK : TKP_THUMBBOTTOM); - - int state_id = TUS_NORMAL; - switch (state) { - case kDisabled: - state_id = TUS_DISABLED; - break; - case kHovered: - state_id = TUS_HOT; - break; - case kNormal: - break; - case kPressed: - state_id = TUS_PRESSED; - break; - case kNumStates: - NOTREACHED(); - break; - } - - // Make the channel be 4 px thick in the center of the supplied rect. (4 px - // matches what XP does in various menus; GetThemePartSize() doesn't seem to - // return good values here.) - RECT rect_win = rect.ToRECT(); - RECT channel_rect = rect.ToRECT(); - const int channel_thickness = 4; - if (part_id == TKP_TRACK) { - channel_rect.top += - ((channel_rect.bottom - channel_rect.top - channel_thickness) / 2); - channel_rect.bottom = channel_rect.top + channel_thickness; - } else if (part_id == TKP_TRACKVERT) { - channel_rect.left += - ((channel_rect.right - channel_rect.left - channel_thickness) / 2); - channel_rect.right = channel_rect.left + channel_thickness; - } // else this isn't actually a channel, so |channel_rect| == |rect|. - - HANDLE handle = GetThemeHandle(TRACKBAR); - if (handle && draw_theme_) - return draw_theme_(handle, hdc, part_id, state_id, &channel_rect, NULL); - - // Classic mode, draw it manually. - if ((part_id == TKP_TRACK) || (part_id == TKP_TRACKVERT)) { - DrawEdge(hdc, &channel_rect, EDGE_SUNKEN, BF_RECT); - } else if (part_id == TKP_THUMBVERT) { - DrawEdge(hdc, &rect_win, EDGE_RAISED, BF_RECT | BF_SOFT | BF_MIDDLE); - } else { - // Split rect into top and bottom pieces. - RECT top_section = rect.ToRECT(); - RECT bottom_section = rect.ToRECT(); - top_section.bottom -= ((bottom_section.right - bottom_section.left) / 2); - bottom_section.top = top_section.bottom; - DrawEdge(hdc, &top_section, EDGE_RAISED, - BF_LEFT | BF_TOP | BF_RIGHT | BF_SOFT | BF_MIDDLE | BF_ADJUST); - - // Split triangular piece into two diagonals. - RECT& left_half = bottom_section; - RECT right_half = bottom_section; - right_half.left += ((bottom_section.right - bottom_section.left) / 2); - left_half.right = right_half.left; - DrawEdge(hdc, &left_half, EDGE_RAISED, - BF_DIAGONAL_ENDTOPLEFT | BF_SOFT | BF_MIDDLE | BF_ADJUST); - DrawEdge(hdc, &right_half, EDGE_RAISED, - BF_DIAGONAL_ENDBOTTOMLEFT | BF_SOFT | BF_MIDDLE | BF_ADJUST); - - // If the button is pressed, draw hatching. - if (extra.classic_state & DFCS_PUSHED) { - SkPaint paint; - SetCheckerboardShader(&paint, rect_win); - - // Fill all three pieces with the pattern. - canvas->drawIRect(skia::RECTToSkIRect(top_section), paint); - - SkScalar left_triangle_top = SkIntToScalar(left_half.top); - SkScalar left_triangle_right = SkIntToScalar(left_half.right); - SkPath left_triangle; - left_triangle.moveTo(SkIntToScalar(left_half.left), left_triangle_top); - left_triangle.lineTo(left_triangle_right, left_triangle_top); - left_triangle.lineTo(left_triangle_right, - SkIntToScalar(left_half.bottom)); - left_triangle.close(); - canvas->drawPath(left_triangle, paint); - - SkScalar right_triangle_left = SkIntToScalar(right_half.left); - SkScalar right_triangle_top = SkIntToScalar(right_half.top); - SkPath right_triangle; - right_triangle.moveTo(right_triangle_left, right_triangle_top); - right_triangle.lineTo(SkIntToScalar(right_half.right), - right_triangle_top); - right_triangle.lineTo(right_triangle_left, - SkIntToScalar(right_half.bottom)); - right_triangle.close(); - canvas->drawPath(right_triangle, paint); - } - } - return S_OK; -} - -HRESULT NativeThemeWin::PaintProgressBar( - HDC hdc, - const gfx::Rect& rect, - const ProgressBarExtraParams& extra) const { - // There is no documentation about the animation speed, frame-rate, nor - // size of moving overlay of the indeterminate progress bar. - // So we just observed real-world programs and guessed following parameters. - const int kDeterminateOverlayPixelsPerSecond = 300; - const int kDeterminateOverlayWidth = 120; - const int kIndeterminateOverlayPixelsPerSecond = 175; - const int kVistaIndeterminateOverlayWidth = 120; - const int kXPIndeterminateOverlayWidth = 55; - // The thickness of the bar frame inside |value_rect| - const int kXPBarPadding = 3; - - RECT bar_rect = rect.ToRECT(); - RECT value_rect = gfx::Rect(extra.value_rect_x, - extra.value_rect_y, - extra.value_rect_width, - extra.value_rect_height).ToRECT(); - - HANDLE handle = GetThemeHandle(PROGRESS); - if (!handle || !draw_theme_ || !draw_theme_ex_) { - FillRect(hdc, &bar_rect, GetSysColorBrush(COLOR_BTNFACE)); - FillRect(hdc, &value_rect, GetSysColorBrush(COLOR_BTNSHADOW)); - DrawEdge(hdc, &bar_rect, EDGE_SUNKEN, BF_RECT | BF_ADJUST); - return S_OK; - } - - draw_theme_(handle, hdc, PP_BAR, 0, &bar_rect, NULL); - - bool pre_vista = base::win::GetVersion() < base::win::VERSION_VISTA; - int bar_width = bar_rect.right - bar_rect.left; - if (!extra.determinate) { - // The glossy overlay for the indeterminate progress bar has a small pause - // after each animation. We emulate this by adding an invisible margin the - // animation has to traverse. - int width_with_margin = bar_width + kIndeterminateOverlayPixelsPerSecond; - int overlay_width = pre_vista ? - kXPIndeterminateOverlayWidth : kVistaIndeterminateOverlayWidth; - RECT overlay_rect = bar_rect; - overlay_rect.left += ComputeAnimationProgress( - width_with_margin, overlay_width, kIndeterminateOverlayPixelsPerSecond, - extra.animated_seconds); - overlay_rect.right = overlay_rect.left + overlay_width; - if (pre_vista) { - RECT shrunk_rect = InsetRect(&overlay_rect, kXPBarPadding); - RECT shrunk_bar_rect = InsetRect(&bar_rect, kXPBarPadding); - draw_theme_(handle, hdc, PP_CHUNK, 0, &shrunk_rect, &shrunk_bar_rect); - } else { - draw_theme_(handle, hdc, PP_MOVEOVERLAY, 0, &overlay_rect, &bar_rect); - } - return S_OK; - } - - // We care about the direction here because PP_CHUNK painting is asymmetric. - // TODO(morrita): This RTL guess can be wrong. We should pass in the - // direction from WebKit. - const DTBGOPTS value_draw_options = { - sizeof(DTBGOPTS), - (bar_rect.right == value_rect.right && bar_rect.left != value_rect.left) ? - DTBG_MIRRORDC : 0, - bar_rect - }; - if (pre_vista) { - // On XP, the progress bar is chunk-style and has no glossy effect. We need - // to shrink the destination rect to fit the part inside the bar with an - // appropriate margin. - RECT shrunk_value_rect = InsetRect(&value_rect, kXPBarPadding); - draw_theme_ex_(handle, hdc, PP_CHUNK, 0, &shrunk_value_rect, - &value_draw_options); - } else { - // On Vista or later, the progress bar part has a single-block value part - // and a glossy effect. The value part has exactly same height as the bar - // part, so we don't need to shrink the rect. - draw_theme_ex_(handle, hdc, PP_FILL, 0, &value_rect, &value_draw_options); - - RECT overlay_rect = value_rect; - overlay_rect.left += ComputeAnimationProgress( - bar_width, kDeterminateOverlayWidth, kDeterminateOverlayPixelsPerSecond, - extra.animated_seconds); - overlay_rect.right = overlay_rect.left + kDeterminateOverlayWidth; - draw_theme_(handle, hdc, PP_MOVEOVERLAY, 0, &overlay_rect, &value_rect); - } - return S_OK; -} - -HRESULT NativeThemeWin::PaintWindowResizeGripper(HDC hdc, - const gfx::Rect& rect) const { - HANDLE handle = GetThemeHandle(STATUS); - RECT rect_win = rect.ToRECT(); - if (handle && draw_theme_) { - // Paint the status bar gripper. There doesn't seem to be a standard - // gripper in Windows for the space between scrollbars. This is pretty - // close, but it's supposed to be painted over a status bar. - return draw_theme_(handle, hdc, SP_GRIPPER, 0, &rect_win, NULL); - } - - // Draw a windows classic scrollbar gripper. - DrawFrameControl(hdc, &rect_win, DFC_SCROLL, DFCS_SCROLLSIZEGRIP); - return S_OK; -} - -HRESULT NativeThemeWin::PaintTabPanelBackground(HDC hdc, - const gfx::Rect& rect) const { - HANDLE handle = GetThemeHandle(TAB); - RECT rect_win = rect.ToRECT(); - if (handle && draw_theme_) - return draw_theme_(handle, hdc, TABP_BODY, 0, &rect_win, NULL); - - // Classic just renders a flat color background. - FillRect(hdc, &rect_win, reinterpret_cast<HBRUSH>(COLOR_3DFACE + 1)); - return S_OK; -} - -HRESULT NativeThemeWin::PaintTextField( - HDC hdc, - Part part, - State state, - const gfx::Rect& rect, - const TextFieldExtraParams& extra) const { - int state_id = ETS_NORMAL; - switch (state) { - case kDisabled: - state_id = ETS_DISABLED; - break; - case kHovered: - state_id = ETS_HOT; - break; - case kNormal: - if (extra.is_read_only) - state_id = ETS_READONLY; - else if (extra.is_focused) - state_id = ETS_FOCUSED; - break; - case kPressed: - state_id = ETS_SELECTED; - break; - case kNumStates: - NOTREACHED(); - break; - } - - RECT rect_win = rect.ToRECT(); - return PaintTextField(hdc, EP_EDITTEXT, state_id, extra.classic_state, - &rect_win, - skia::SkColorToCOLORREF(extra.background_color), - extra.fill_content_area, extra.draw_edges); -} - -HRESULT NativeThemeWin::PaintTextField(HDC hdc, - int part_id, - int state_id, - int classic_state, - RECT* rect, - COLORREF color, - bool fill_content_area, - bool draw_edges) const { - // TODO(ojan): http://b/1210017 Figure out how to give the ability to - // exclude individual edges from being drawn. - - HANDLE handle = GetThemeHandle(TEXTFIELD); - // TODO(mpcomplete): can we detect if the color is specified by the user, - // and if not, just use the system color? - // CreateSolidBrush() accepts a RGB value but alpha must be 0. - base::win::ScopedGDIObject<HBRUSH> bg_brush(CreateSolidBrush(color)); - // DrawThemeBackgroundEx was introduced in XP SP2, so that it's possible - // draw_theme_ex_ is NULL and draw_theme_ is non-null. - if (!handle || (!draw_theme_ex_ && (!draw_theme_ || !draw_edges))) { - // Draw it manually. - if (draw_edges) - DrawEdge(hdc, rect, EDGE_SUNKEN, BF_RECT | BF_ADJUST); - - if (fill_content_area) { - FillRect(hdc, rect, (classic_state & DFCS_INACTIVE) ? - reinterpret_cast<HBRUSH>(COLOR_BTNFACE + 1) : bg_brush); - } - return S_OK; - } - - static const DTBGOPTS omit_border_options = { - sizeof(DTBGOPTS), - DTBG_OMITBORDER, - { 0, 0, 0, 0 } - }; - HRESULT hr = draw_theme_ex_ ? - draw_theme_ex_(handle, hdc, part_id, state_id, rect, - draw_edges ? NULL : &omit_border_options) : - draw_theme_(handle, hdc, part_id, state_id, rect, NULL); - - // TODO(maruel): Need to be fixed if get_theme_content_rect_ is NULL. - if (fill_content_area && get_theme_content_rect_) { - RECT content_rect; - hr = get_theme_content_rect_(handle, hdc, part_id, state_id, rect, - &content_rect); - FillRect(hdc, &content_rect, bg_brush); - } - return hr; -} - -HRESULT NativeThemeWin::PaintScaledTheme(HANDLE theme, - HDC hdc, - int part_id, - int state_id, - const gfx::Rect& rect) const { - // Correct the scaling and positioning of sub-components such as scrollbar - // arrows and thumb grippers in the event that the world transform applies - // scaling (e.g. in high-DPI mode). - XFORM save_transform; - if (GetWorldTransform(hdc, &save_transform)) { - float scale = save_transform.eM11; - if (scale != 1 && save_transform.eM12 == 0) { - ModifyWorldTransform(hdc, NULL, MWT_IDENTITY); - gfx::Rect scaled_rect(gfx::ToEnclosedRect(gfx::ScaleRect(rect, scale))); - scaled_rect.Offset(save_transform.eDx, save_transform.eDy); - RECT bounds = scaled_rect.ToRECT(); - HRESULT result = draw_theme_(theme, hdc, part_id, state_id, &bounds, - NULL); - SetWorldTransform(hdc, &save_transform); - return result; - } - } - RECT bounds = rect.ToRECT(); - return draw_theme_(theme, hdc, part_id, state_id, &bounds, NULL); -} - -// static -NativeThemeWin::ThemeName NativeThemeWin::GetThemeName(Part part) { - switch (part) { - case kCheckbox: - case kPushButton: - case kRadio: - return BUTTON; - case kInnerSpinButton: - return SPIN; - case kMenuList: - case kMenuCheck: - case kMenuPopupArrow: - case kMenuPopupGutter: - case kMenuPopupSeparator: - return MENU; - case kProgressBar: - return PROGRESS; - case kScrollbarDownArrow: - case kScrollbarLeftArrow: - case kScrollbarRightArrow: - case kScrollbarUpArrow: - case kScrollbarHorizontalThumb: - case kScrollbarVerticalThumb: - case kScrollbarHorizontalTrack: - case kScrollbarVerticalTrack: - return SCROLLBAR; - case kSliderTrack: - case kSliderThumb: - return TRACKBAR; - case kTextField: - return TEXTFIELD; - case kWindowResizeGripper: - return STATUS; - case kComboboxArrow: - case kMenuCheckBackground: - case kMenuPopupBackground: - case kMenuItemBackground: - case kScrollbarHorizontalGripper: - case kScrollbarVerticalGripper: - case kScrollbarCorner: - case kTabPanelBackground: - case kTrackbarThumb: - case kTrackbarTrack: - case kMaxPart: - NOTREACHED(); - } - return LAST; -} - -// static -int NativeThemeWin::GetWindowsPart(Part part, - State state, - const ExtraParams& extra) { - switch (part) { - case kCheckbox: - return BP_CHECKBOX; - case kMenuCheck: - return MENU_POPUPCHECK; - case kMenuPopupArrow: - return MENU_POPUPSUBMENU; - case kMenuPopupGutter: - return MENU_POPUPGUTTER; - case kMenuPopupSeparator: - return MENU_POPUPSEPARATOR; - case kPushButton: - return BP_PUSHBUTTON; - case kRadio: - return BP_RADIOBUTTON; - case kScrollbarDownArrow: - case kScrollbarLeftArrow: - case kScrollbarRightArrow: - case kScrollbarUpArrow: - return SBP_ARROWBTN; - case kScrollbarHorizontalThumb: - return SBP_THUMBBTNHORZ; - case kScrollbarVerticalThumb: - return SBP_THUMBBTNVERT; - case kWindowResizeGripper: - return SP_GRIPPER; - case kComboboxArrow: - case kInnerSpinButton: - case kMenuList: - case kMenuCheckBackground: - case kMenuPopupBackground: - case kMenuItemBackground: - case kProgressBar: - case kScrollbarHorizontalTrack: - case kScrollbarVerticalTrack: - case kScrollbarHorizontalGripper: - case kScrollbarVerticalGripper: - case kScrollbarCorner: - case kSliderTrack: - case kSliderThumb: - case kTabPanelBackground: - case kTextField: - case kTrackbarThumb: - case kTrackbarTrack: - case kMaxPart: - NOTREACHED(); - } - return 0; -} - -int NativeThemeWin::GetWindowsState(Part part, - State state, - const ExtraParams& extra) { - switch (part) { - case kCheckbox: - switch (state) { - case kDisabled: - return CBS_UNCHECKEDDISABLED; - case kHovered: - return CBS_UNCHECKEDHOT; - case kNormal: - return CBS_UNCHECKEDNORMAL; - case kPressed: - return CBS_UNCHECKEDPRESSED; - case kNumStates: - NOTREACHED(); - return 0; - } - case kMenuCheck: - switch (state) { - case kDisabled: - return extra.menu_check.is_radio ? - MC_BULLETDISABLED : MC_CHECKMARKDISABLED; - case kHovered: - case kNormal: - case kPressed: - return extra.menu_check.is_radio ? - MC_BULLETNORMAL : MC_CHECKMARKNORMAL; - case kNumStates: - NOTREACHED(); - return 0; - } - case kMenuPopupArrow: - case kMenuPopupGutter: - case kMenuPopupSeparator: - switch (state) { - case kDisabled: - return MBI_DISABLED; - case kHovered: - return MBI_HOT; - case kNormal: - return MBI_NORMAL; - case kPressed: - return MBI_PUSHED; - case kNumStates: - NOTREACHED(); - return 0; - } - case kPushButton: - switch (state) { - case kDisabled: - return PBS_DISABLED; - case kHovered: - return PBS_HOT; - case kNormal: - return PBS_NORMAL; - case kPressed: - return PBS_PRESSED; - case kNumStates: - NOTREACHED(); - return 0; - } - case kRadio: - switch (state) { - case kDisabled: - return RBS_UNCHECKEDDISABLED; - case kHovered: - return RBS_UNCHECKEDHOT; - case kNormal: - return RBS_UNCHECKEDNORMAL; - case kPressed: - return RBS_UNCHECKEDPRESSED; - case kNumStates: - NOTREACHED(); - return 0; - } - case kScrollbarDownArrow: - switch (state) { - case kDisabled: - return ABS_DOWNDISABLED; - case kHovered: - // Mimic ScrollbarThemeChromiumWin.cpp in WebKit. - return base::win::GetVersion() < base::win::VERSION_VISTA ? - ABS_DOWNHOT : ABS_DOWNHOVER; - case kNormal: - return ABS_DOWNNORMAL; - case kPressed: - return ABS_DOWNPRESSED; - case kNumStates: - NOTREACHED(); - return 0; - } - case kScrollbarLeftArrow: - switch (state) { - case kDisabled: - return ABS_LEFTDISABLED; - case kHovered: - // Mimic ScrollbarThemeChromiumWin.cpp in WebKit. - return base::win::GetVersion() < base::win::VERSION_VISTA ? - ABS_LEFTHOT : ABS_LEFTHOVER; - case kNormal: - return ABS_LEFTNORMAL; - case kPressed: - return ABS_LEFTPRESSED; - case kNumStates: - NOTREACHED(); - return 0; - } - case kScrollbarRightArrow: - switch (state) { - case kDisabled: - return ABS_RIGHTDISABLED; - case kHovered: - // Mimic ScrollbarThemeChromiumWin.cpp in WebKit. - return base::win::GetVersion() < base::win::VERSION_VISTA ? - ABS_RIGHTHOT : ABS_RIGHTHOVER; - case kNormal: - return ABS_RIGHTNORMAL; - case kPressed: - return ABS_RIGHTPRESSED; - case kNumStates: - NOTREACHED(); - return 0; - } - break; - case kScrollbarUpArrow: - switch (state) { - case kDisabled: - return ABS_UPDISABLED; - case kHovered: - // Mimic ScrollbarThemeChromiumWin.cpp in WebKit. - return base::win::GetVersion() < base::win::VERSION_VISTA ? - ABS_UPHOT : ABS_UPHOVER; - case kNormal: - return ABS_UPNORMAL; - case kPressed: - return ABS_UPPRESSED; - case kNumStates: - NOTREACHED(); - return 0; - } - break; - case kScrollbarHorizontalThumb: - case kScrollbarVerticalThumb: - switch (state) { - case kDisabled: - return SCRBS_DISABLED; - case kHovered: - // Mimic WebKit's behaviour in ScrollbarThemeChromiumWin.cpp. - return base::win::GetVersion() < base::win::VERSION_VISTA ? - SCRBS_HOT : SCRBS_HOVER; - case kNormal: - return SCRBS_NORMAL; - case kPressed: - return SCRBS_PRESSED; - case kNumStates: - NOTREACHED(); - return 0; - } - case kWindowResizeGripper: - switch (state) { - case kDisabled: - case kHovered: - case kNormal: - case kPressed: - return 1; // gripper has no windows state - case kNumStates: - NOTREACHED(); - return 0; - } - case kComboboxArrow: - case kInnerSpinButton: - case kMenuList: - case kMenuCheckBackground: - case kMenuPopupBackground: - case kMenuItemBackground: - case kProgressBar: - case kScrollbarHorizontalTrack: - case kScrollbarVerticalTrack: - case kScrollbarHorizontalGripper: - case kScrollbarVerticalGripper: - case kScrollbarCorner: - case kSliderTrack: - case kSliderThumb: - case kTabPanelBackground: - case kTextField: - case kTrackbarThumb: - case kTrackbarTrack: - case kMaxPart: - NOTREACHED(); - } - return 0; -} - -HRESULT NativeThemeWin::GetThemeInt(ThemeName theme, - int part_id, - int state_id, - int prop_id, - int *value) const { - HANDLE handle = GetThemeHandle(theme); - return (handle && get_theme_int_) ? - get_theme_int_(handle, part_id, state_id, prop_id, value) : E_NOTIMPL; -} - -HRESULT NativeThemeWin::PaintFrameControl(HDC hdc, - const gfx::Rect& rect, - UINT type, - UINT state, - bool is_selected, - State control_state) const { - const int width = rect.width(); - const int height = rect.height(); - - // DrawFrameControl for menu arrow/check wants a monochrome bitmap. - base::win::ScopedBitmap mask_bitmap(CreateBitmap(width, height, 1, 1, NULL)); - - if (mask_bitmap == NULL) - return E_OUTOFMEMORY; - - base::win::ScopedCreateDC bitmap_dc(CreateCompatibleDC(NULL)); - base::win::ScopedSelectObject select_bitmap(bitmap_dc.Get(), mask_bitmap); - RECT local_rect = { 0, 0, width, height }; - DrawFrameControl(bitmap_dc.Get(), &local_rect, type, state); - - // We're going to use BitBlt with a b&w mask. This results in using the dest - // dc's text color for the black bits in the mask, and the dest dc's - // background color for the white bits in the mask. DrawFrameControl draws the - // check in black, and the background in white. - int bg_color_key = COLOR_MENU; - int text_color_key = COLOR_MENUTEXT; - switch (control_state) { - case kDisabled: - bg_color_key = is_selected ? COLOR_HIGHLIGHT : COLOR_MENU; - text_color_key = COLOR_GRAYTEXT; - break; - case kHovered: - bg_color_key = COLOR_HIGHLIGHT; - text_color_key = COLOR_HIGHLIGHTTEXT; - break; - case kNormal: - break; - case kPressed: - case kNumStates: - NOTREACHED(); - break; - } - COLORREF old_bg_color = SetBkColor(hdc, GetSysColor(bg_color_key)); - COLORREF old_text_color = SetTextColor(hdc, GetSysColor(text_color_key)); - BitBlt(hdc, rect.x(), rect.y(), width, height, bitmap_dc.Get(), 0, 0, - SRCCOPY); - SetBkColor(hdc, old_bg_color); - SetTextColor(hdc, old_text_color); - - return S_OK; -} - -HANDLE NativeThemeWin::GetThemeHandle(ThemeName theme_name) const { - if (!open_theme_ || theme_name < 0 || theme_name >= LAST) - return 0; - - if (theme_handles_[theme_name]) - return theme_handles_[theme_name]; - - // Not found, try to load it. - HANDLE handle = 0; - switch (theme_name) { - case BUTTON: - handle = open_theme_(NULL, L"Button"); - break; - case LIST: - handle = open_theme_(NULL, L"Listview"); - break; - case MENU: - handle = open_theme_(NULL, L"Menu"); - break; - case MENULIST: - handle = open_theme_(NULL, L"Combobox"); - break; - case SCROLLBAR: - handle = open_theme_(NULL, L"Scrollbar"); - break; - case STATUS: - handle = open_theme_(NULL, L"Status"); - break; - case TAB: - handle = open_theme_(NULL, L"Tab"); - break; - case TEXTFIELD: - handle = open_theme_(NULL, L"Edit"); - break; - case TRACKBAR: - handle = open_theme_(NULL, L"Trackbar"); - break; - case WINDOW: - handle = open_theme_(NULL, L"Window"); - break; - case PROGRESS: - handle = open_theme_(NULL, L"Progress"); - break; - case SPIN: - handle = open_theme_(NULL, L"Spin"); - break; - case LAST: - NOTREACHED(); - break; - } - theme_handles_[theme_name] = handle; - return handle; -} - -} // namespace ui
diff --git a/ui/native_theme/native_theme_win.h b/ui/native_theme/native_theme_win.h deleted file mode 100644 index 78f4740..0000000 --- a/ui/native_theme/native_theme_win.h +++ /dev/null
@@ -1,372 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_NATIVE_THEME_NATIVE_THEME_WIN_H_ -#define UI_NATIVE_THEME_NATIVE_THEME_WIN_H_ - -// A wrapper class for working with custom XP/Vista themes provided in -// uxtheme.dll. This is a singleton class that can be grabbed using -// NativeThemeWin::instance(). -// For more information on visual style parts and states, see: -// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/commctls/userex/topics/partsandstates.asp - -#include <map> - -#include <windows.h> -#include <uxtheme.h> - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "third_party/skia/include/core/SkColor.h" -#include "ui/gfx/size.h" -#include "ui/gfx/sys_color_change_listener.h" -#include "ui/native_theme/native_theme.h" - -class SkCanvas; - -namespace ui { - -// Windows implementation of native theme class. -// -// At the moment, this class in in transition from an older API that consists -// of several PaintXXX methods to an API, inherited from the NativeTheme base -// class, that consists of a single Paint() method with a argument to indicate -// what kind of part to paint. -class NATIVE_THEME_EXPORT NativeThemeWin : public NativeTheme, - public gfx::SysColorChangeListener { - public: - enum ThemeName { - BUTTON, - LIST, - MENU, - MENULIST, - SCROLLBAR, - STATUS, - TAB, - TEXTFIELD, - TRACKBAR, - WINDOW, - PROGRESS, - SPIN, - LAST - }; - - bool IsThemingActive() const; - - // Returns true if a high contrast theme is being used. - bool IsUsingHighContrastTheme() const; - - HRESULT GetThemeColor(ThemeName theme, - int part_id, - int state_id, - int prop_id, - SkColor* color) const; - - // Get the theme color if theming is enabled. If theming is unsupported - // for this part, use Win32's GetSysColor to find the color specified - // by default_sys_color. - SkColor GetThemeColorWithDefault(ThemeName theme, - int part_id, - int state_id, - int prop_id, - int default_sys_color) const; - - // Get the thickness of the border associated with the specified theme, - // defaulting to GetSystemMetrics edge size if themes are disabled. - // In Classic Windows, borders are typically 2px; on XP+, they are 1px. - gfx::Size GetThemeBorderSize(ThemeName theme) const; - - // Disables all theming for top-level windows in the entire process, from - // when this method is called until the process exits. All the other - // methods in this class will continue to work, but their output will ignore - // the user's theme. This is meant for use when running tests that require - // consistent visual results. - void DisableTheming() const; - - // Closes cached theme handles so we can unload the DLL or update our UI - // for a theme change. - void CloseHandles() const; - - // Returns true if classic theme is in use. - bool IsClassicTheme(ThemeName name) const; - - // Gets our singleton instance. - static NativeThemeWin* instance(); - - HRESULT PaintTextField(HDC hdc, - int part_id, - int state_id, - int classic_state, - RECT* rect, - COLORREF color, - bool fill_content_area, - bool draw_edges) const; - - // NativeTheme implementation: - virtual gfx::Size GetPartSize(Part part, - State state, - const ExtraParams& extra) const override; - virtual void Paint(SkCanvas* canvas, - Part part, - State state, - const gfx::Rect& rect, - const ExtraParams& extra) const override; - virtual SkColor GetSystemColor(ColorId color_id) const override; - - private: - NativeThemeWin(); - ~NativeThemeWin(); - - // gfx::SysColorChangeListener implementation: - virtual void OnSysColorChange() override; - - // Update the locally cached set of system colors. - void UpdateSystemColors(); - - // Paint directly to canvas' HDC. - void PaintDirect(SkCanvas* canvas, - Part part, - State state, - const gfx::Rect& rect, - const ExtraParams& extra) const; - - // Create a temporary HDC, paint to that, clean up the alpha values in the - // temporary HDC, and then blit the result to canvas. This is to work around - // the fact that Windows XP and some classic themes give bogus alpha values. - void PaintIndirect(SkCanvas* canvas, - Part part, - State state, - const gfx::Rect& rect, - const ExtraParams& extra) const; - - HRESULT GetThemePartSize(ThemeName themeName, - HDC hdc, - int part_id, - int state_id, - RECT* rect, - int ts, - SIZE* size) const; - - HRESULT PaintButton(HDC hdc, - State state, - const ButtonExtraParams& extra, - int part_id, - int state_id, - RECT* rect) const; - - HRESULT PaintMenuSeparator(HDC hdc, - const gfx::Rect& rect) const; - - HRESULT PaintMenuGutter(HDC hdc, const gfx::Rect& rect) const; - - // |arrow_direction| determines whether the arrow is pointing to the left or - // to the right. In RTL locales, sub-menus open from right to left and - // therefore the menu arrow should point to the left and not to the right. - HRESULT PaintMenuArrow(HDC hdc, - State state, - const gfx::Rect& rect, - const MenuArrowExtraParams& extra) const; - - HRESULT PaintMenuBackground(HDC hdc, const gfx::Rect& rect) const; - - HRESULT PaintMenuCheck(HDC hdc, - State state, - const gfx::Rect& rect, - const MenuCheckExtraParams& extra) const; - - HRESULT PaintMenuCheckBackground(HDC hdc, - State state, - const gfx::Rect& rect) const; - - HRESULT PaintMenuItemBackground(HDC hdc, - State state, - const gfx::Rect& rect, - const MenuItemExtraParams& extra) const; - - HRESULT PaintPushButton(HDC hdc, - Part part, - State state, - const gfx::Rect& rect, - const ButtonExtraParams& extra) const; - - HRESULT PaintRadioButton(HDC hdc, - Part part, - State state, - const gfx::Rect& rect, - const ButtonExtraParams& extra) const; - - HRESULT PaintCheckbox(HDC hdc, - Part part, - State state, - const gfx::Rect& rect, - const ButtonExtraParams& extra) const; - - HRESULT PaintMenuList(HDC hdc, - State state, - const gfx::Rect& rect, - const MenuListExtraParams& extra) const; - - // Paints a scrollbar arrow. |classic_state| should have the appropriate - // classic part number ORed in already. - HRESULT PaintScrollbarArrow(HDC hdc, - Part part, - State state, - const gfx::Rect& rect, - const ScrollbarArrowExtraParams& extra) const; - - HRESULT PaintScrollbarThumb(HDC hdc, - Part part, - State state, - const gfx::Rect& rect, - const ScrollbarThumbExtraParams& extra) const; - - // This method is deprecated and will be removed in the near future. - // Paints a scrollbar track section. |align_rect| is only used in classic - // mode, and makes sure the checkerboard pattern in |target_rect| is aligned - // with one presumed to be in |align_rect|. - HRESULT PaintScrollbarTrack(SkCanvas* canvas, - HDC hdc, - Part part, - State state, - const gfx::Rect& rect, - const ScrollbarTrackExtraParams& extra) const; - - HRESULT PaintSpinButton(HDC hdc, - Part part, - State state, - const gfx::Rect& rect, - const InnerSpinButtonExtraParams& extra) const; - - HRESULT PaintTrackbar(SkCanvas* canvas, - HDC hdc, - Part part, - State state, - const gfx::Rect& rect, - const TrackbarExtraParams& extra) const; - - HRESULT PaintProgressBar(HDC hdc, - const gfx::Rect& rect, - const ProgressBarExtraParams& extra) const; - - HRESULT PaintWindowResizeGripper(HDC hdc, const gfx::Rect& rect) const; - - HRESULT PaintTabPanelBackground(HDC hdc, const gfx::Rect& rect) const; - - HRESULT PaintTextField(HDC hdc, - Part part, - State state, - const gfx::Rect& rect, - const TextFieldExtraParams& extra) const; - - // Paints a theme part, with support for scene scaling in high-DPI mode. - // |theme| is the theme handle. |hdc| is the handle for the device context. - // |part_id| is the identifier for the part (e.g. thumb gripper). |state_id| - // is the identifier for the rendering state of the part (e.g. hover). |rect| - // is the bounds for rendering, expressed in logical coordinates. - HRESULT PaintScaledTheme(HANDLE theme, - HDC hdc, - int part_id, - int state_id, - const gfx::Rect& rect) const; - - // Get the windows theme name/part/state. These three helper functions are - // used only by GetPartSize(), as each of the corresponding PaintXXX() - // methods do further validation of the part and state that is required for - // getting the size. - static ThemeName GetThemeName(Part part); - static int GetWindowsPart(Part part, State state, const ExtraParams& extra); - static int GetWindowsState(Part part, State state, const ExtraParams& extra); - - HRESULT GetThemeInt(ThemeName theme, - int part_id, - int state_id, - int prop_id, - int *result) const; - - HRESULT PaintFrameControl(HDC hdc, - const gfx::Rect& rect, - UINT type, - UINT state, - bool is_selected, - State control_state) const; - - // Returns a handle to the theme data. - HANDLE GetThemeHandle(ThemeName theme_name) const; - - typedef HRESULT (WINAPI* DrawThemeBackgroundPtr)(HANDLE theme, - HDC hdc, - int part_id, - int state_id, - const RECT* rect, - const RECT* clip_rect); - typedef HRESULT (WINAPI* DrawThemeBackgroundExPtr)(HANDLE theme, - HDC hdc, - int part_id, - int state_id, - const RECT* rect, - const DTBGOPTS* opts); - typedef HRESULT (WINAPI* GetThemeColorPtr)(HANDLE hTheme, - int part_id, - int state_id, - int prop_id, - COLORREF* color); - typedef HRESULT (WINAPI* GetThemeContentRectPtr)(HANDLE hTheme, - HDC hdc, - int part_id, - int state_id, - const RECT* rect, - RECT* content_rect); - typedef HRESULT (WINAPI* GetThemePartSizePtr)(HANDLE hTheme, - HDC hdc, - int part_id, - int state_id, - RECT* rect, - int ts, - SIZE* size); - typedef HANDLE (WINAPI* OpenThemeDataPtr)(HWND window, - LPCWSTR class_list); - typedef HRESULT (WINAPI* CloseThemeDataPtr)(HANDLE theme); - - typedef void (WINAPI* SetThemeAppPropertiesPtr) (DWORD flags); - typedef BOOL (WINAPI* IsThemeActivePtr)(); - typedef HRESULT (WINAPI* GetThemeIntPtr)(HANDLE hTheme, - int part_id, - int state_id, - int prop_id, - int *value); - - // Function pointers into uxtheme.dll. - DrawThemeBackgroundPtr draw_theme_; - DrawThemeBackgroundExPtr draw_theme_ex_; - GetThemeColorPtr get_theme_color_; - GetThemeContentRectPtr get_theme_content_rect_; - GetThemePartSizePtr get_theme_part_size_; - OpenThemeDataPtr open_theme_; - CloseThemeDataPtr close_theme_; - SetThemeAppPropertiesPtr set_theme_properties_; - IsThemeActivePtr is_theme_active_; - GetThemeIntPtr get_theme_int_; - - // Handle to uxtheme.dll. - HMODULE theme_dll_; - - // A cache of open theme handles. - mutable HANDLE theme_handles_[LAST]; - - // The system color change listener and the updated cache of system colors. - gfx::ScopedSysColorChangeListener color_change_listener_; - mutable std::map<int, SkColor> system_colors_; - - // Is a high contrast theme active? - mutable bool is_using_high_contrast_; - - // Is |is_using_high_contrast_| valid? - mutable bool is_using_high_contrast_valid_; - - DISALLOW_COPY_AND_ASSIGN(NativeThemeWin); -}; - -} // namespace ui - -#endif // UI_NATIVE_THEME_NATIVE_THEME_WIN_H_
diff --git a/ui/ozone/BUILD.gn b/ui/ozone/BUILD.gn deleted file mode 100644 index e95ffc0..0000000 --- a/ui/ozone/BUILD.gn +++ /dev/null
@@ -1,172 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import("//ui/ozone/ozone.gni") - -# The list of platforms that will be built. -ozone_platforms = [] - -# Extra dependencies to pull into ui/ozone for built platforms. -ozone_platform_deps = [] - -# Extra dependencies to pull into ozone_unittests for built platforms. -ozone_platform_test_deps = [] - -if (ozone_platform_egltest) { - ozone_platforms += [ "egltest" ] - ozone_platform_deps += [ "platform/egltest" ] -} - -if (ozone_platform_test) { - ozone_platforms += [ "test" ] - ozone_platform_deps += [ "platform/test" ] -} - -if (ozone_platform_caca) { - ozone_platforms += [ "caca" ] - ozone_platform_deps += [ "platform/caca" ] -} - -if (ozone_platform_dri) { - ozone_platforms += [ "dri" ] - ozone_platform_deps += [ "platform/dri" ] - ozone_platform_test_deps += [ "platform/dri:dri_unittests" ] -} - -if (ozone_platform_gbm) { - ozone_platforms += [ "gbm" ] - ozone_platform_deps += [ "platform/dri:gbm" ] -} - -platform_list_cc_file = "$target_gen_dir/platform_list.cc" -platform_list_h_file = "$target_gen_dir/platform_list.h" -platform_list_txt_file = "$target_gen_dir/platform_list.txt" -constructor_list_cc_file = "$target_gen_dir/constructor_list.cc" - -# GYP version: ui/ozone/ozone.gyp:ozone_base -component("ozone_base") { - sources = [ - "public/cursor_factory_ozone.cc", - "public/cursor_factory_ozone.h", - "public/gpu_platform_support.cc", - "public/gpu_platform_support.h", - "public/gpu_platform_support_host.cc", - "public/gpu_platform_support_host.h", - "public/overlay_candidates_ozone.cc", - "public/overlay_candidates_ozone.h", - "public/surface_factory_ozone.cc", - "public/surface_factory_ozone.h", - "public/surface_ozone_canvas.h", - "public/surface_ozone_egl.h", - ] - - defines = [ "OZONE_BASE_IMPLEMENTATION" ] - - deps = [ - "//base", - "//skia", - "//ui/gfx/geometry", - ] -} - -component("ozone") { - sources = [ - platform_list_cc_file, - platform_list_h_file, - constructor_list_cc_file, - "common/display_mode_proxy.cc", - "common/display_mode_proxy.h", - "common/display_snapshot_proxy.cc", - "common/display_snapshot_proxy.h", - "common/display_util.cc", - "common/display_util.h", - "common/gpu/ozone_gpu_message_generator.cc", - "common/gpu/ozone_gpu_message_generator.h", - "common/gpu/ozone_gpu_message_params.cc", - "common/gpu/ozone_gpu_message_params.h", - "common/gpu/ozone_gpu_messages.h", - "common/native_display_delegate_ozone.cc", - "common/native_display_delegate_ozone.h", - "public/ozone_platform.cc", - "public/ozone_platform.h", - "public/ozone_switches.cc", - "public/ozone_switches.h", - "public/ui_thread_gpu.cc", - "public/ui_thread_gpu.h", - "platform_selection.cc", - "platform_selection.h", - ] - - defines = [ "OZONE_IMPLEMENTATION" ] - - deps = - [ - ":generate_constructor_list", - ":generate_ozone_platform_list", - ":ozone_base", - "//base", - "//ipc", - "//skia", - "//ui/display/types", - "//ui/events", - "//ui/events/ozone:events_ozone", - "//ui/gfx", - "//ui/gfx/geometry", - "//ui/gfx/ipc", - - # TODO(GYP) the GYP version has a way to add additional dependencies via - # build flags. - ] + ozone_platform_deps -} - -# GYP version: ui/ozone/ozone.gyp:generate_ozone_platform_list -action("generate_ozone_platform_list") { - script = "generate_ozone_platform_list.py" - outputs = [ - platform_list_cc_file, - platform_list_h_file, - platform_list_txt_file, - ] - - args = - [ - "--output_cc=" + rebase_path(platform_list_cc_file, root_build_dir), - "--output_h=" + rebase_path(platform_list_h_file, root_build_dir), - "--output_txt=" + rebase_path(platform_list_txt_file, root_build_dir), - "--default=$ozone_platform", - ] + ozone_platforms -} - -# GYP version: ui/ozone/ozone.gyp:generate_constructor_list -action("generate_constructor_list") { - script = "generate_constructor_list.py" - - source_prereqs = [ platform_list_txt_file ] - outputs = [ - constructor_list_cc_file, - ] - - args = [ - "--platform_list=" + rebase_path(platform_list_txt_file, root_build_dir), - "--output_cc=" + rebase_path(constructor_list_cc_file, root_build_dir), - "--namespace=ui", - "--typename=OzonePlatform", - "--include=\"ui/ozone/public/ozone_platform.h\"", - ] - - deps = [ - ":generate_ozone_platform_list", - ] -} - -test("ozone_unittests") { - sources = [ - "run_all_unittests.cc", - ] - - deps = [ - "//base/test:test_support", - "//testing/gtest", - ] + ozone_platform_test_deps -}
diff --git a/ui/ozone/DEPS b/ui/ozone/DEPS deleted file mode 100644 index a019258..0000000 --- a/ui/ozone/DEPS +++ /dev/null
@@ -1,10 +0,0 @@ -include_rules = [ - "+skia/ext", - "+third_party/khronos", - "+third_party/skia", - "+ui/display/types", - "+ui/events", - "+ui/gfx", - "+ui/base/cursor", - "+ui/platform_window", -]
diff --git a/ui/ozone/OWNERS b/ui/ozone/OWNERS deleted file mode 100644 index 479c4d8..0000000 --- a/ui/ozone/OWNERS +++ /dev/null
@@ -1,2 +0,0 @@ -rjkroege@chromium.org -spang@chromium.org
diff --git a/ui/ozone/common/README b/ui/ozone/common/README deleted file mode 100644 index 1ab9e67..0000000 --- a/ui/ozone/common/README +++ /dev/null
@@ -1,2 +0,0 @@ -This directory contains code that is used by multiple platforms, but is not part -of the public platform API. This code should not be used outside of ui/ozone.
diff --git a/ui/ozone/common/display_mode_proxy.cc b/ui/ozone/common/display_mode_proxy.cc deleted file mode 100644 index 6890b33..0000000 --- a/ui/ozone/common/display_mode_proxy.cc +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/common/display_mode_proxy.h" - -#include "ui/ozone/common/gpu/ozone_gpu_message_params.h" - -namespace ui { - -DisplayModeProxy::DisplayModeProxy(const DisplayMode_Params& params) - : DisplayMode(params.size, params.is_interlaced, params.refresh_rate) { -} - -DisplayModeProxy::~DisplayModeProxy() { -} - -} // namespace ui
diff --git a/ui/ozone/common/display_mode_proxy.h b/ui/ozone/common/display_mode_proxy.h deleted file mode 100644 index 0d16204..0000000 --- a/ui/ozone/common/display_mode_proxy.h +++ /dev/null
@@ -1,25 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_COMMON_DISPLAY_MODE_PROXY_H_ -#define UI_OZONE_COMMON_DISPLAY_MODE_PROXY_H_ - -#include "ui/display/types/display_mode.h" - -namespace ui { - -struct DisplayMode_Params; - -class DisplayModeProxy : public DisplayMode { - public: - DisplayModeProxy(const DisplayMode_Params& params); - virtual ~DisplayModeProxy(); - - private: - DISALLOW_COPY_AND_ASSIGN(DisplayModeProxy); -}; - -} // namespace ui - -#endif // UI_OZONE_COMMON_DISPLAY_MODE_PROXY_H_
diff --git a/ui/ozone/common/display_snapshot_proxy.cc b/ui/ozone/common/display_snapshot_proxy.cc deleted file mode 100644 index 0e9db0b..0000000 --- a/ui/ozone/common/display_snapshot_proxy.cc +++ /dev/null
@@ -1,54 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/common/display_snapshot_proxy.h" - -#include "ui/ozone/common/display_mode_proxy.h" -#include "ui/ozone/common/gpu/ozone_gpu_message_params.h" - -namespace ui { - -namespace { - -bool SameModes(const DisplayMode_Params& lhs, const DisplayMode_Params& rhs) { - return lhs.size == rhs.size && lhs.is_interlaced == rhs.is_interlaced && - lhs.refresh_rate == rhs.refresh_rate; -} - -} // namespace - -DisplaySnapshotProxy::DisplaySnapshotProxy(const DisplaySnapshot_Params& params) - : DisplaySnapshot(params.display_id, - params.has_proper_display_id, - params.origin, - params.physical_size, - params.type, - params.is_aspect_preserving_scaling, - params.has_overscan, - params.display_name, - std::vector<const DisplayMode*>(), - NULL, - NULL), - string_representation_(params.string_representation) { - for (size_t i = 0; i < params.modes.size(); ++i) { - modes_.push_back(new DisplayModeProxy(params.modes[i])); - - if (params.has_current_mode && - SameModes(params.modes[i], params.current_mode)) - current_mode_ = modes_.back(); - - if (params.has_native_mode && - SameModes(params.modes[i], params.native_mode)) - native_mode_ = modes_.back(); - } -} - -DisplaySnapshotProxy::~DisplaySnapshotProxy() { -} - -std::string DisplaySnapshotProxy::ToString() const { - return string_representation_; -} - -} // namespace ui
diff --git a/ui/ozone/common/display_snapshot_proxy.h b/ui/ozone/common/display_snapshot_proxy.h deleted file mode 100644 index 175af51..0000000 --- a/ui/ozone/common/display_snapshot_proxy.h +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_COMMON_DISPLAY_SNAPSHOT_PROXY_H_ -#define UI_OZONE_COMMON_DISPLAY_SNAPSHOT_PROXY_H_ - -#include "ui/display/types/display_snapshot.h" - -namespace ui { - -struct DisplaySnapshot_Params; - -class DisplaySnapshotProxy : public DisplaySnapshot { - public: - DisplaySnapshotProxy(const DisplaySnapshot_Params& params); - virtual ~DisplaySnapshotProxy(); - - // DisplaySnapshot override: - virtual std::string ToString() const override; - - private: - std::string string_representation_; - - DISALLOW_COPY_AND_ASSIGN(DisplaySnapshotProxy); -}; - -} // namespace ui - -#endif // UI_OZONE_COMMON_DISPLAY_SNAPSHOT_PROXY_H_
diff --git a/ui/ozone/common/display_util.cc b/ui/ozone/common/display_util.cc deleted file mode 100644 index 784656e..0000000 --- a/ui/ozone/common/display_util.cc +++ /dev/null
@@ -1,48 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/common/display_util.h" - -#include "ui/display/types/display_mode.h" -#include "ui/display/types/display_snapshot.h" - -namespace ui { - -DisplayMode_Params GetDisplayModeParams(const DisplayMode& mode) { - DisplayMode_Params params; - params.size = mode.size(); - params.is_interlaced = mode.is_interlaced(); - params.refresh_rate = mode.refresh_rate(); - - return params; -} - -DisplaySnapshot_Params GetDisplaySnapshotParams( - const DisplaySnapshot& display) { - DisplaySnapshot_Params params; - params.display_id = display.display_id(); - params.has_proper_display_id = display.has_proper_display_id(); - params.origin = display.origin(); - params.physical_size = display.physical_size(); - params.type = display.type(); - params.is_aspect_preserving_scaling = display.is_aspect_preserving_scaling(); - params.has_overscan = display.has_overscan(); - params.display_name = display.display_name(); - for (size_t i = 0; i < display.modes().size(); ++i) - params.modes.push_back(GetDisplayModeParams(*display.modes()[i])); - - params.has_current_mode = display.current_mode() != NULL; - if (params.has_current_mode) - params.current_mode = GetDisplayModeParams(*display.current_mode()); - - params.has_native_mode = display.native_mode() != NULL; - if (params.has_native_mode) - params.native_mode = GetDisplayModeParams(*display.native_mode()); - - params.string_representation = display.ToString(); - - return params; -} - -} // namespace ui
diff --git a/ui/ozone/common/display_util.h b/ui/ozone/common/display_util.h deleted file mode 100644 index 7c4f92a..0000000 --- a/ui/ozone/common/display_util.h +++ /dev/null
@@ -1,20 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_COMMON_DISPLAY_UTIL_H_ -#define UI_OZONE_COMMON_DISPLAY_UTIL_H_ - -#include "ui/ozone/common/gpu/ozone_gpu_message_params.h" - -namespace ui { - -class DisplayMode; -class DisplaySnapshot; - -DisplayMode_Params GetDisplayModeParams(const DisplayMode& mode); -DisplaySnapshot_Params GetDisplaySnapshotParams(const DisplaySnapshot& display); - -} // namespace ui - -#endif // UI_OZONE_COMMON_DISPLAY_UTIL_H_
diff --git a/ui/ozone/common/gpu/OWNERS b/ui/ozone/common/gpu/OWNERS deleted file mode 100644 index 8757192..0000000 --- a/ui/ozone/common/gpu/OWNERS +++ /dev/null
@@ -1,10 +0,0 @@ -# Changes to IPC messages require a security review to avoid introducing -# new sandbox escapes. -per-file *_message*.h=set noparent -per-file *_message*.h=dcheng@chromium.org -per-file *_message*.h=inferno@chromium.org -per-file *_message*.h=jln@chromium.org -per-file *_message*.h=jschuh@chromium.org -per-file *_message*.h=kenrb@chromium.org -per-file *_message*.h=nasko@chromium.org -per-file *_message*.h=tsepez@chromium.org
diff --git a/ui/ozone/common/gpu/ozone_gpu_message_generator.cc b/ui/ozone/common/gpu/ozone_gpu_message_generator.cc deleted file mode 100644 index d3032ed..0000000 --- a/ui/ozone/common/gpu/ozone_gpu_message_generator.cc +++ /dev/null
@@ -1,33 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// Get basic type definitions. -#define IPC_MESSAGE_IMPL -#include "ui/ozone/common/gpu/ozone_gpu_message_generator.h" - -// Generate constructors. -#include "ipc/struct_constructor_macros.h" -#include "ui/ozone/common/gpu/ozone_gpu_message_generator.h" - -// Generate destructors. -#include "ipc/struct_destructor_macros.h" -#include "ui/ozone/common/gpu/ozone_gpu_message_generator.h" - -// Generate param traits write methods. -#include "ipc/param_traits_write_macros.h" -namespace IPC { -#include "ui/ozone/common/gpu/ozone_gpu_message_generator.h" -} // namespace IPC - -// Generate param traits read methods. -#include "ipc/param_traits_read_macros.h" -namespace IPC { -#include "ui/ozone/common/gpu/ozone_gpu_message_generator.h" -} // namespace IPC - -// Generate param traits log methods. -#include "ipc/param_traits_log_macros.h" -namespace IPC { -#include "ui/ozone/common/gpu/ozone_gpu_message_generator.h" -} // namespace IPC
diff --git a/ui/ozone/common/gpu/ozone_gpu_message_generator.h b/ui/ozone/common/gpu/ozone_gpu_message_generator.h deleted file mode 100644 index 3b35c0e..0000000 --- a/ui/ozone/common/gpu/ozone_gpu_message_generator.h +++ /dev/null
@@ -1,7 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// Multiply-included file, hence no include guard. - -#include "ui/ozone/common/gpu/ozone_gpu_messages.h"
diff --git a/ui/ozone/common/gpu/ozone_gpu_message_params.cc b/ui/ozone/common/gpu/ozone_gpu_message_params.cc deleted file mode 100644 index 7b69136..0000000 --- a/ui/ozone/common/gpu/ozone_gpu_message_params.cc +++ /dev/null
@@ -1,31 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/common/gpu/ozone_gpu_message_params.h" - -namespace ui { - -DisplayMode_Params::DisplayMode_Params() - : size(), is_interlaced(false), refresh_rate(0.0f) {} - -DisplayMode_Params::~DisplayMode_Params() {} - -DisplaySnapshot_Params::DisplaySnapshot_Params() - : display_id(0), - has_proper_display_id(false), - origin(), - physical_size(), - type(ui::DISPLAY_CONNECTION_TYPE_NONE), - is_aspect_preserving_scaling(false), - has_overscan(false), - display_name(), - modes(), - has_current_mode(false), - current_mode(), - has_native_mode(false), - native_mode() {} - -DisplaySnapshot_Params::~DisplaySnapshot_Params() {} - -} // namespace ui
diff --git a/ui/ozone/common/gpu/ozone_gpu_message_params.h b/ui/ozone/common/gpu/ozone_gpu_message_params.h deleted file mode 100644 index fcce42f..0000000 --- a/ui/ozone/common/gpu/ozone_gpu_message_params.h +++ /dev/null
@@ -1,49 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_COMMON_GPU_OZONE_GPU_MESSAGE_PARAMS_H_ -#define UI_OZONE_COMMON_GPU_OZONE_GPU_MESSAGE_PARAMS_H_ - -#include <string> -#include <vector> - -#include "ui/display/types/display_constants.h" -#include "ui/gfx/geometry/point.h" -#include "ui/gfx/geometry/size.h" - -namespace ui { - -struct DisplayMode_Params { - DisplayMode_Params(); - ~DisplayMode_Params(); - - gfx::Size size; - bool is_interlaced; - float refresh_rate; -}; - -struct DisplaySnapshot_Params { - DisplaySnapshot_Params(); - ~DisplaySnapshot_Params(); - - int64_t display_id; - bool has_proper_display_id; - gfx::Point origin; - gfx::Size physical_size; - DisplayConnectionType type; - bool is_aspect_preserving_scaling; - bool has_overscan; - std::string display_name; - std::vector<DisplayMode_Params> modes; - bool has_current_mode; - DisplayMode_Params current_mode; - bool has_native_mode; - DisplayMode_Params native_mode; - std::string string_representation; -}; - -} // namespace ui - -#endif // UI_OZONE_COMMON_GPU_OZONE_GPU_MESSAGE_PARAMS_H_ -
diff --git a/ui/ozone/common/gpu/ozone_gpu_messages.h b/ui/ozone/common/gpu/ozone_gpu_messages.h deleted file mode 100644 index 86cd286..0000000 --- a/ui/ozone/common/gpu/ozone_gpu_messages.h +++ /dev/null
@@ -1,103 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// Multiply-included message file, hence no include guard here, but see below -// for a much smaller-than-usual include guard section. - -#include <vector> - -#include "ipc/ipc_message_macros.h" -#include "third_party/skia/include/core/SkBitmap.h" -#include "ui/gfx/geometry/point.h" -#include "ui/gfx/geometry/rect.h" -#include "ui/gfx/ipc/gfx_param_traits.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/ozone/common/gpu/ozone_gpu_message_params.h" -#include "ui/ozone/ozone_export.h" - -#undef IPC_MESSAGE_EXPORT -#define IPC_MESSAGE_EXPORT OZONE_EXPORT - -#define IPC_MESSAGE_START OzoneGpuMsgStart - -IPC_ENUM_TRAITS_MAX_VALUE(ui::DisplayConnectionType, - ui::DISPLAY_CONNECTION_TYPE_LAST) - -IPC_STRUCT_TRAITS_BEGIN(ui::DisplayMode_Params) - IPC_STRUCT_TRAITS_MEMBER(size) - IPC_STRUCT_TRAITS_MEMBER(is_interlaced) - IPC_STRUCT_TRAITS_MEMBER(refresh_rate) -IPC_STRUCT_TRAITS_END() - -IPC_STRUCT_TRAITS_BEGIN(ui::DisplaySnapshot_Params) - IPC_STRUCT_TRAITS_MEMBER(display_id) - IPC_STRUCT_TRAITS_MEMBER(has_proper_display_id) - IPC_STRUCT_TRAITS_MEMBER(origin) - IPC_STRUCT_TRAITS_MEMBER(physical_size) - IPC_STRUCT_TRAITS_MEMBER(type) - IPC_STRUCT_TRAITS_MEMBER(is_aspect_preserving_scaling) - IPC_STRUCT_TRAITS_MEMBER(has_overscan) - IPC_STRUCT_TRAITS_MEMBER(display_name) - IPC_STRUCT_TRAITS_MEMBER(modes) - IPC_STRUCT_TRAITS_MEMBER(has_current_mode) - IPC_STRUCT_TRAITS_MEMBER(current_mode) - IPC_STRUCT_TRAITS_MEMBER(has_native_mode) - IPC_STRUCT_TRAITS_MEMBER(native_mode) - IPC_STRUCT_TRAITS_MEMBER(string_representation) -IPC_STRUCT_TRAITS_END() - -//------------------------------------------------------------------------------ -// GPU Messages -// These are messages from the browser to the GPU process. - -// Update the HW cursor bitmap & move to specified location. -IPC_MESSAGE_CONTROL4(OzoneGpuMsg_CursorSet, - gfx::AcceleratedWidget, - std::vector<SkBitmap>, - gfx::Point /* location */, - int /* frame_delay_ms */) - -// Move the HW cursor to the specified location. -IPC_MESSAGE_CONTROL2(OzoneGpuMsg_CursorMove, - gfx::AcceleratedWidget, gfx::Point) - -// Explicit creation of a WindowDelegate. We explicitly create the window -// delegate such that any state change in the window is not lost while the -// surface is created on the GPU side. -IPC_MESSAGE_CONTROL1(OzoneGpuMsg_CreateWindowDelegate, - gfx::AcceleratedWidget /* widget */) - -IPC_MESSAGE_CONTROL1(OzoneGpuMsg_DestroyWindowDelegate, - gfx::AcceleratedWidget /* widget */) - -// Updates the location and size of the widget on the screen. -IPC_MESSAGE_CONTROL2(OzoneGpuMsg_WindowBoundsChanged, - gfx::AcceleratedWidget /* widget */, - gfx::Rect /* bounds */) - -// Force the DPMS state of the display to on. -IPC_MESSAGE_CONTROL0(OzoneGpuMsg_ForceDPMSOn) - -// Trigger a display reconfiguration. OzoneHostMsg_UpdateNativeDisplays will be -// sent as a response. -// The |displays| parameter will hold a list of last known displays. -IPC_MESSAGE_CONTROL1(OzoneGpuMsg_RefreshNativeDisplays, - std::vector<ui::DisplaySnapshot_Params> /* displays */) - -// Configure a display with the specified mode at the specified location. -IPC_MESSAGE_CONTROL3(OzoneGpuMsg_ConfigureNativeDisplay, - int64_t, // display ID - ui::DisplayMode_Params, // display mode - gfx::Point) // origin for the display - -IPC_MESSAGE_CONTROL1(OzoneGpuMsg_DisableNativeDisplay, - int64_t) // display ID - -//------------------------------------------------------------------------------ -// Browser Messages -// These messages are from the GPU to the browser process. - -// Updates the list of active displays. -IPC_MESSAGE_CONTROL1(OzoneHostMsg_UpdateNativeDisplays, - std::vector<ui::DisplaySnapshot_Params>)
diff --git a/ui/ozone/common/native_display_delegate_ozone.cc b/ui/ozone/common/native_display_delegate_ozone.cc deleted file mode 100644 index 23fae85..0000000 --- a/ui/ozone/common/native_display_delegate_ozone.cc +++ /dev/null
@@ -1,97 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/common/native_display_delegate_ozone.h" - -#include "base/logging.h" - -namespace ui { - -NativeDisplayDelegateOzone::NativeDisplayDelegateOzone() { -} - -NativeDisplayDelegateOzone::~NativeDisplayDelegateOzone() { -} - -void NativeDisplayDelegateOzone::Initialize() { - NOTIMPLEMENTED(); -} - -void NativeDisplayDelegateOzone::GrabServer() { - NOTIMPLEMENTED(); -} - -void NativeDisplayDelegateOzone::UngrabServer() { - NOTIMPLEMENTED(); -} - -void NativeDisplayDelegateOzone::SyncWithServer() { - NOTIMPLEMENTED(); -} - -void NativeDisplayDelegateOzone::SetBackgroundColor(uint32_t color_argb) { - NOTIMPLEMENTED(); -} - -void NativeDisplayDelegateOzone::ForceDPMSOn() { - NOTIMPLEMENTED(); -} - -std::vector<ui::DisplaySnapshot*> NativeDisplayDelegateOzone::GetDisplays() { - NOTIMPLEMENTED(); - return std::vector<ui::DisplaySnapshot*>(); -} - -void NativeDisplayDelegateOzone::AddMode(const ui::DisplaySnapshot& output, - const ui::DisplayMode* mode) { - NOTIMPLEMENTED(); -} - -bool NativeDisplayDelegateOzone::Configure(const ui::DisplaySnapshot& output, - const ui::DisplayMode* mode, - const gfx::Point& origin) { - NOTIMPLEMENTED(); - return false; -} - -void NativeDisplayDelegateOzone::CreateFrameBuffer(const gfx::Size& size) { - NOTIMPLEMENTED(); -} - -bool NativeDisplayDelegateOzone::GetHDCPState(const ui::DisplaySnapshot& output, - ui::HDCPState* state) { - NOTIMPLEMENTED(); - return false; -} - -bool NativeDisplayDelegateOzone::SetHDCPState(const ui::DisplaySnapshot& output, - ui::HDCPState state) { - NOTIMPLEMENTED(); - return false; -} - -std::vector<ui::ColorCalibrationProfile> -NativeDisplayDelegateOzone::GetAvailableColorCalibrationProfiles( - const ui::DisplaySnapshot& output) { - NOTIMPLEMENTED(); - return std::vector<ui::ColorCalibrationProfile>(); -} - -bool NativeDisplayDelegateOzone::SetColorCalibrationProfile( - const ui::DisplaySnapshot& output, - ui::ColorCalibrationProfile new_profile) { - NOTIMPLEMENTED(); - return false; -} - -void NativeDisplayDelegateOzone::AddObserver(NativeDisplayObserver* observer) { - NOTIMPLEMENTED(); -} - -void NativeDisplayDelegateOzone::RemoveObserver( - NativeDisplayObserver* observer) { - NOTIMPLEMENTED(); -} - -} // namespace ui
diff --git a/ui/ozone/common/native_display_delegate_ozone.h b/ui/ozone/common/native_display_delegate_ozone.h deleted file mode 100644 index e600ce5..0000000 --- a/ui/ozone/common/native_display_delegate_ozone.h +++ /dev/null
@@ -1,51 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_COMMON_NATIVE_DISPLAY_DELEGATE_OZONE_H_ -#define UI_OZONE_COMMON_NATIVE_DISPLAY_DELEGATE_OZONE_H_ - -#include "base/macros.h" -#include "ui/display/types/native_display_delegate.h" - -namespace ui { - -class NativeDisplayDelegateOzone : public NativeDisplayDelegate { - public: - NativeDisplayDelegateOzone(); - virtual ~NativeDisplayDelegateOzone(); - - // NativeDisplayDelegate overrides: - virtual void Initialize() override; - virtual void GrabServer() override; - virtual void UngrabServer() override; - virtual void SyncWithServer() override; - virtual void SetBackgroundColor(uint32_t color_argb) override; - virtual void ForceDPMSOn() override; - virtual std::vector<ui::DisplaySnapshot*> GetDisplays() override; - virtual void AddMode(const ui::DisplaySnapshot& output, - const ui::DisplayMode* mode) override; - virtual bool Configure(const ui::DisplaySnapshot& output, - const ui::DisplayMode* mode, - const gfx::Point& origin) override; - virtual void CreateFrameBuffer(const gfx::Size& size) override; - virtual bool GetHDCPState(const ui::DisplaySnapshot& output, - ui::HDCPState* state) override; - virtual bool SetHDCPState(const ui::DisplaySnapshot& output, - ui::HDCPState state) override; - virtual std::vector<ui::ColorCalibrationProfile> - GetAvailableColorCalibrationProfiles( - const ui::DisplaySnapshot& output) override; - virtual bool SetColorCalibrationProfile( - const ui::DisplaySnapshot& output, - ui::ColorCalibrationProfile new_profile) override; - virtual void AddObserver(NativeDisplayObserver* observer) override; - virtual void RemoveObserver(NativeDisplayObserver* observer) override; - - private: - DISALLOW_COPY_AND_ASSIGN(NativeDisplayDelegateOzone); -}; - -} // namespace ui - -#endif // UI_OZONE_COMMON_NATIVE_DISPLAY_DELEGATE_OZONE_H_
diff --git a/ui/ozone/demo/BUILD.gn b/ui/ozone/demo/BUILD.gn deleted file mode 100644 index c58431b..0000000 --- a/ui/ozone/demo/BUILD.gn +++ /dev/null
@@ -1,23 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -group("demo") { - deps = [ - ":ozone_demo", - ] -} - -executable("ozone_demo") { - sources = [ - "ozone_demo.cc", - ] - - deps = [ - "//base", - "//skia", - "//ui/gfx/geometry", - "//ui/gl", - "//ui/ozone", - ] -}
diff --git a/ui/ozone/demo/DEPS b/ui/ozone/demo/DEPS deleted file mode 100644 index f59fd38..0000000 --- a/ui/ozone/demo/DEPS +++ /dev/null
@@ -1,3 +0,0 @@ -include_rules = [ - "+ui/gl", -]
diff --git a/ui/ozone/demo/ozone_demo.cc b/ui/ozone/demo/ozone_demo.cc deleted file mode 100644 index 717b451..0000000 --- a/ui/ozone/demo/ozone_demo.cc +++ /dev/null
@@ -1,222 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/at_exit.h" -#include "base/command_line.h" -#include "base/message_loop/message_loop.h" -#include "base/run_loop.h" -#include "base/timer/timer.h" -#include "third_party/skia/include/core/SkCanvas.h" -#include "third_party/skia/include/core/SkColor.h" -#include "ui/gfx/geometry/size.h" -#include "ui/gl/gl_bindings.h" -#include "ui/gl/gl_context.h" -#include "ui/gl/gl_surface.h" -#include "ui/ozone/public/ozone_platform.h" -#include "ui/ozone/public/surface_factory_ozone.h" -#include "ui/ozone/public/surface_ozone_canvas.h" -#include "ui/ozone/public/ui_thread_gpu.h" -#include "ui/platform_window/platform_window.h" -#include "ui/platform_window/platform_window_delegate.h" - -const int kTestWindowWidth = 800; -const int kTestWindowHeight = 600; - -const int kFrameDelayMilliseconds = 16; - -const int kAnimationSteps = 240; - -const char kDisableGpu[] = "disable-gpu"; - -class DemoWindow : public ui::PlatformWindowDelegate { - public: - DemoWindow() : widget_(gfx::kNullAcceleratedWidget), iteration_(0) { - platform_window_ = ui::OzonePlatform::GetInstance()->CreatePlatformWindow( - this, gfx::Rect(kTestWindowWidth, kTestWindowHeight)); - } - virtual ~DemoWindow() {} - - gfx::AcceleratedWidget GetAcceleratedWidget() { - // TODO(spang): We should start rendering asynchronously. - DCHECK_NE(widget_, gfx::kNullAcceleratedWidget) - << "Widget not available synchronously"; - return widget_; - } - - gfx::Size GetSize() { return platform_window_->GetBounds().size(); } - - void Start() { - if (!CommandLine::ForCurrentProcess()->HasSwitch(kDisableGpu) && - gfx::GLSurface::InitializeOneOff() && StartInProcessGpu() && - InitializeGLSurface()) { - StartAnimationGL(); - } else if (InitializeSoftwareSurface()) { - StartAnimationSoftware(); - } else { - LOG(ERROR) << "Failed to create drawing surface"; - Quit(); - } - } - - void Quit() { - StopAnimation(); - base::MessageLoop::current()->PostTask( - FROM_HERE, base::Bind(&base::DeletePointer<DemoWindow>, this)); - } - - // PlatformWindowDelegate: - virtual void OnBoundsChanged(const gfx::Rect& new_bounds) override {} - virtual void OnDamageRect(const gfx::Rect& damaged_region) override {} - virtual void DispatchEvent(ui::Event* event) override {} - virtual void OnCloseRequest() override { - Quit(); - } - virtual void OnClosed() override {} - virtual void OnWindowStateChanged( - ui::PlatformWindowState new_state) override {} - virtual void OnLostCapture() override {} - virtual void OnAcceleratedWidgetAvailable( - gfx::AcceleratedWidget widget) override { - DCHECK_NE(widget, gfx::kNullAcceleratedWidget); - widget_ = widget; - } - virtual void OnActivationChanged(bool active) override {} - - private: - bool InitializeGLSurface() { - surface_ = gfx::GLSurface::CreateViewGLSurface(GetAcceleratedWidget()); - if (!surface_.get()) { - LOG(ERROR) << "Failed to create GL surface"; - return false; - } - - context_ = gfx::GLContext::CreateGLContext( - NULL, surface_.get(), gfx::PreferIntegratedGpu); - if (!context_.get()) { - LOG(ERROR) << "Failed to create GL context"; - surface_ = NULL; - return false; - } - - surface_->Resize(GetSize()); - - if (!context_->MakeCurrent(surface_.get())) { - LOG(ERROR) << "Failed to make GL context current"; - surface_ = NULL; - context_ = NULL; - return false; - } - - return true; - } - - bool InitializeSoftwareSurface() { - software_surface_ = - ui::SurfaceFactoryOzone::GetInstance()->CreateCanvasForWidget( - GetAcceleratedWidget()); - if (!software_surface_) { - LOG(ERROR) << "Failed to create software surface"; - return false; - } - - software_surface_->ResizeCanvas(GetSize()); - return true; - } - - void StartAnimationGL() { - timer_.Start(FROM_HERE, - base::TimeDelta::FromMicroseconds(kFrameDelayMilliseconds), - this, - &DemoWindow::RenderFrameGL); - } - - void StartAnimationSoftware() { - timer_.Start(FROM_HERE, - base::TimeDelta::FromMicroseconds(kFrameDelayMilliseconds), - this, - &DemoWindow::RenderFrameSoftware); - } - - void StopAnimation() { timer_.Stop(); } - - float NextFraction() { - float fraction = (sinf(iteration_ * 2 * M_PI / kAnimationSteps) + 1) / 2; - - iteration_++; - iteration_ %= kAnimationSteps; - - return fraction; - } - - void RenderFrameGL() { - float fraction = NextFraction(); - gfx::Size window_size = GetSize(); - - glViewport(0, 0, window_size.width(), window_size.height()); - glClearColor(1 - fraction, fraction, 0.0, 1.0); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - - if (!surface_->SwapBuffers()) - LOG(FATAL) << "Failed to swap buffers"; - } - - void RenderFrameSoftware() { - float fraction = NextFraction(); - gfx::Size window_size = GetSize(); - - skia::RefPtr<SkCanvas> canvas = software_surface_->GetCanvas(); - - SkColor color = - SkColorSetARGB(0xff, 0, 0xff * fraction, 0xff * (1 - fraction)); - - canvas->clear(color); - - software_surface_->PresentCanvas(gfx::Rect(window_size)); - } - - bool StartInProcessGpu() { return ui_thread_gpu_.Initialize(); } - - // Timer for animation. - base::RepeatingTimer<DemoWindow> timer_; - - // Bits for GL rendering. - scoped_refptr<gfx::GLSurface> surface_; - scoped_refptr<gfx::GLContext> context_; - - // Bits for software rendeirng. - scoped_ptr<ui::SurfaceOzoneCanvas> software_surface_; - - // Window-related state. - scoped_ptr<ui::PlatformWindow> platform_window_; - gfx::AcceleratedWidget widget_; - - // Helper for applications that do GL on main thread. - ui::UiThreadGpu ui_thread_gpu_; - - // Animation state. - int iteration_; - - DISALLOW_COPY_AND_ASSIGN(DemoWindow); -}; - -int main(int argc, char** argv) { - CommandLine::Init(argc, argv); - base::AtExitManager exit_manager; - - // Build UI thread message loop. This is used by platform - // implementations for event polling & running background tasks. - base::MessageLoopForUI message_loop; - - ui::OzonePlatform::InitializeForUI(); - - DemoWindow* window = new DemoWindow; - window->Start(); - - // Run the message loop until there's nothing left to do. - // TODO(spang): Should we use QuitClosure instead? - base::RunLoop run_loop; - run_loop.RunUntilIdle(); - - return 0; -}
diff --git a/ui/ozone/demo/ozone_demos.gyp b/ui/ozone/demo/ozone_demos.gyp deleted file mode 100644 index edd3e32..0000000 --- a/ui/ozone/demo/ozone_demos.gyp +++ /dev/null
@@ -1,26 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -{ - 'variables': { - 'chromium_code': 1, - }, - 'targets': [ - { - 'target_name': 'ozone_demo', - 'type': 'executable', - 'dependencies': [ - '../../../base/base.gyp:base', - '../../../skia/skia.gyp:skia', - '../../../ui/gfx/gfx.gyp:gfx_geometry', - '../../../ui/gl/gl.gyp:gl', - '../../../ui/ozone/ozone.gyp:ozone', - '../../../ui/ozone/ozone.gyp:ozone_base', - ], - 'sources': [ - 'ozone_demo.cc', - ], - }, - ], -}
diff --git a/ui/ozone/generate_constructor_list.py b/ui/ozone/generate_constructor_list.py deleted file mode 100755 index 42a07e2..0000000 --- a/ui/ozone/generate_constructor_list.py +++ /dev/null
@@ -1,169 +0,0 @@ -#!/usr/bin/env python -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Code generator for PlatformObject<> constructor list. - -This script takes as arguments a list of platform names as a text file and -a list of types and generates a C++ source file containing a list of -the constructors for that object in platform order. - -Example Output: ./ui/ozone/generate_constructor_list.py \ - --platform test \ - --platform dri \ - --export OZONE_EXPORT \ - --namespace ui \ - --typename OzonePlatform \ - --include '"ui/ozone/ozone_platform.h"' - - // DO NOT MODIFY. GENERATED BY generate_constructor_list.py - - #include "ui/ozone/platform_object_internal.h" - - #include "ui/ozone/ozone_platform.h" - - namespace ui { - - OzonePlatform* CreateOzonePlatformTest(); - OzonePlatform* CreateOzonePlatformDri(); - - } // namespace ui - - namespace ui { - - typedef ui::OzonePlatform* (*OzonePlatformConstructor)(); - - template <> const OzonePlatformConstructor - PlatformConstructorList<ui::OzonePlatform>::kConstructors[] = { - &ui::CreateOzonePlatformTest, - &ui::CreateOzonePlatformDri, - }; - - template class OZONE_EXPORT PlatformObject<ui::OzonePlatform>; - - } // namespace ui -""" - -import optparse -import os -import collections -import re -import sys -import string - - -def GetTypedefName(typename): - """Determine typedef name of constructor for typename. - - This is just typename + "Constructor". - """ - - return typename + 'Constructor' - - -def GetConstructorName(typename, platform): - """Determine name of static constructor function from platform name. - - This is just "Create" + typename + platform. - """ - - return 'Create' + typename + string.capitalize(platform) - - -def GenerateConstructorList(out, namespace, export, typenames, platforms, - includes): - """Generate static array containing a list of constructors.""" - - out.write('// DO NOT MODIFY. GENERATED BY generate_constructor_list.py\n') - out.write('\n') - - out.write('#include "ui/ozone/platform_object_internal.h"\n') - out.write('\n') - - for include in includes: - out.write('#include %(include)s\n' % {'include': include}) - out.write('\n') - - out.write('namespace %(namespace)s {\n' % {'namespace': namespace}) - out.write('\n') - - # Declarations of constructor functions. - for typename in typenames: - for platform in platforms: - constructor = GetConstructorName(typename, platform) - out.write('%(typename)s* %(constructor)s();\n' - % {'typename': typename, - 'constructor': constructor}) - out.write('\n') - - out.write('} // namespace %(namespace)s\n' % {'namespace': namespace}) - out.write('\n') - - out.write('namespace ui {\n') - out.write('\n') - - # Handy typedefs for constructor types. - for typename in typenames: - out.write('typedef %(typename)s* (*%(typedef)s)();\n' - % {'typename': namespace + '::' + typename, - 'typedef': GetTypedefName(typename)}) - out.write('\n') - - # The actual constructor lists. - for typename in typenames: - out.write('template <> const %(typedef)s\n' - % {'typedef': GetTypedefName(typename)}) - out.write('PlatformConstructorList<%(typename)s>::kConstructors[] = {\n' - % {'typename': namespace + '::' + typename}) - for platform in platforms: - constructor = GetConstructorName(typename, platform) - out.write(' &%(namespace)s::%(constructor)s,\n' - % {'namespace': namespace, 'constructor': constructor}) - out.write('};\n') - out.write('\n') - - # Exported template instantiation. - for typename in typenames: - out.write('template class %(export)s PlatformObject<%(typename)s>;\n' - % {'export': export, 'typename': namespace + '::' + typename}) - out.write('\n') - - out.write('} // namespace ui\n') - out.write('\n') - - -def main(argv): - parser = optparse.OptionParser() - parser.add_option('--namespace', default='ozone') - parser.add_option('--export', default='OZONE_EXPORT') - parser.add_option('--platform_list') - parser.add_option('--output_cc') - parser.add_option('--include', action='append', default=[]) - parser.add_option('--platform', action='append', default=[]) - parser.add_option('--typename', action='append', default=[]) - options, _ = parser.parse_args(argv) - - platforms = list(options.platform) - typenames = list(options.typename) - includes = list(options.include) - - if options.platform_list: - platforms = open(options.platform_list, 'r').read().strip().split('\n') - - # Write to standard output or file specified by --output_cc. - out_cc = sys.stdout - if options.output_cc: - out_cc = open(options.output_cc, 'wb') - - GenerateConstructorList(out_cc, options.namespace, options.export, - typenames, platforms, includes) - - if options.output_cc: - out_cc.close() - - return 0 - - -if __name__ == '__main__': - sys.exit(main(sys.argv[1:]))
diff --git a/ui/ozone/generate_ozone_platform_list.py b/ui/ozone/generate_ozone_platform_list.py deleted file mode 100755 index d47c398..0000000 --- a/ui/ozone/generate_ozone_platform_list.py +++ /dev/null
@@ -1,177 +0,0 @@ -#!/usr/bin/env python -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Code generator for Ozone platform list. - -This script takes as arguments a list of platform names and generates a C++ -source file containing a list of those platforms. - -Each platform gets an integer identifier that is used to find objects for that -platform (particularly constructors for platform-specific objects). - -Example Output: ./generate_ozone_platform_list.py --default wayland dri wayland - - // platform_list.txt - - wayland - dri - - // platform_list.h - - #ifndef UI_OZONE_PLATFORM_LIST_H_ - #define UI_OZONE_PLATFORM_LIST_H_ - - namespace ui { - - const int kPlatformWayland = 0; - const int kPlatformDri = 1; - - extern const char *kPlatformNames[kPlatformCount]; - - } // namespace ui - - // platform_list.cc - - #include "ui/ozone/platform_list.h" - - namespace ui { - - const char *kPlatformNames[] = { - "wayland", // kPlatformWayland - "dri", // kPlatformDri - }; - - } // namespace ui - - #endif // UI_OZONE_PLATFORM_LIST_H_ - -""" - -import optparse -import os -import collections -import re -import sys -import string - - -def GetConstantName(name): - """Determine name of static constructor function from platform name. - - We just capitalize the platform name and prepend "CreateOzonePlatform". - """ - - return 'kPlatform' + string.capitalize(name) - - -def GeneratePlatformListText(out, platforms): - """Generate text file with list of platform names, in platform id order.""" - - for platform in platforms: - out.write(platform) - out.write('\n') - - out.write('\n') - - -def GeneratePlatformListHeader(out, platforms): - """Generate ids of ozone platforms & declaration of static names array.""" - - out.write('// DO NOT MODIFY. GENERATED BY generate_ozone_platform_list.py\n') - out.write('\n') - - out.write('#ifndef UI_OZONE_PLATFORM_LIST_H_\n') - out.write('#define UI_OZONE_PLATFORM_LIST_H_\n') - out.write('\n') - - out.write('namespace ui {\n') - out.write('\n') - - # Prototypes for platform initializers. - for plat_id, plat_name in enumerate(platforms): - out.write('const int %s = %d;\n' % (GetConstantName(plat_name), plat_id)) - out.write('\n') - - # Platform count. - out.write('const int kPlatformCount = %d;\n' % len(platforms)) - out.write('\n') - - # Declaration for names list. - out.write('extern const char* kPlatformNames[kPlatformCount];\n') - out.write('\n') - - out.write('} // namespace ui\n') - out.write('\n') - - out.write('#endif // UI_OZONE_PLATFORM_LIST_H_\n') - out.write('\n') - - -def GeneratePlatformListSource(out, platforms): - """Generate static array containing a list of ozone platforms.""" - - out.write('// DO NOT MODIFY. GENERATED BY generate_ozone_platform_list.py\n') - out.write('\n') - - out.write('#include "ui/ozone/platform_list.h"\n') - out.write('\n') - - out.write('namespace ui {\n') - out.write('\n') - - # Definition of names list. - out.write('const char* kPlatformNames[] = {\n') - - # Prototypes for platform initializers. - for plat_name in platforms: - out.write(' "%s", // %s\n' % (plat_name, GetConstantName(plat_name))) - out.write('};\n') - out.write('\n') - - out.write('} // namespace ui\n') - out.write('\n') - - -def main(argv): - parser = optparse.OptionParser() - parser.add_option('--output_cc') - parser.add_option('--output_h') - parser.add_option('--output_txt') - parser.add_option('--default') - options, platforms = parser.parse_args(argv) - - # Reorder the platforms when --default is specified. - # The default platform must appear first in the platform list. - if options.default and options.default in platforms: - platforms.remove(options.default) - platforms.insert(0, options.default) - - # Write to standard output or file specified by --output_{cc,h}. - out_cc = sys.stdout - out_h = sys.stdout - out_txt = sys.stdout - if options.output_cc: - out_cc = open(options.output_cc, 'wb') - if options.output_h: - out_h = open(options.output_h, 'wb') - if options.output_txt: - out_txt = open(options.output_txt, 'wb') - - GeneratePlatformListText(out_txt, platforms) - GeneratePlatformListHeader(out_h, platforms) - GeneratePlatformListSource(out_cc, platforms) - - if options.output_cc: - out_cc.close() - if options.output_h: - out_h.close() - if options.output_txt: - out_txt.close() - - return 0 - - -if __name__ == '__main__': - sys.exit(main(sys.argv[1:]))
diff --git a/ui/ozone/gpu/DEPS b/ui/ozone/gpu/DEPS deleted file mode 100644 index f59fd38..0000000 --- a/ui/ozone/gpu/DEPS +++ /dev/null
@@ -1,3 +0,0 @@ -include_rules = [ - "+ui/gl", -]
diff --git a/ui/ozone/gpu/README b/ui/ozone/gpu/README deleted file mode 100644 index 7f96a44..0000000 --- a/ui/ozone/gpu/README +++ /dev/null
@@ -1 +0,0 @@ -This component contains support code for content/common/gpu.
diff --git a/ui/ozone/gpu/gpu_memory_buffer_factory_ozone_native_buffer.cc b/ui/ozone/gpu/gpu_memory_buffer_factory_ozone_native_buffer.cc deleted file mode 100644 index ce1f9ca..0000000 --- a/ui/ozone/gpu/gpu_memory_buffer_factory_ozone_native_buffer.cc +++ /dev/null
@@ -1,159 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/gpu/gpu_memory_buffer_factory_ozone_native_buffer.h" - -#include "base/logging.h" -#include "ui/gl/gl_image_egl.h" -#include "ui/gl/gl_image_linux_dma_buffer.h" -#include "ui/ozone/public/native_pixmap.h" -#include "ui/ozone/public/surface_factory_ozone.h" -#include "ui/ozone/public/surface_ozone_egl.h" - -namespace ui { -namespace { -class GLImageOzoneNativePixmap : public gfx::GLImageEGL { - public: - explicit GLImageOzoneNativePixmap(const gfx::Size& size) : GLImageEGL(size) {} - - bool Initialize(NativePixmap* pixmap) { - EGLint attrs[] = {EGL_IMAGE_PRESERVED_KHR, EGL_TRUE, EGL_NONE}; - if (!Initialize(EGL_NATIVE_PIXMAP_KHR, pixmap->GetEGLClientBuffer(), attrs)) - return false; - pixmap_ = pixmap; - return true; - } - - virtual bool ScheduleOverlayPlane(gfx::AcceleratedWidget widget, - int z_order, - gfx::OverlayTransform transform, - const gfx::Rect& bounds_rect, - const gfx::RectF& crop_rect) override { - return SurfaceFactoryOzone::GetInstance()->ScheduleOverlayPlane( - widget, z_order, transform, pixmap_, bounds_rect, crop_rect); - } - - protected: - virtual ~GLImageOzoneNativePixmap() {} - - private: - using gfx::GLImageEGL::Initialize; - scoped_refptr<NativePixmap> pixmap_; -}; - -class GLImageOzoneNativePixmapDmaBuf : public gfx::GLImageLinuxDMABuffer { - public: - explicit GLImageOzoneNativePixmapDmaBuf(const gfx::Size& size, - unsigned internalformat) - : GLImageLinuxDMABuffer(size, internalformat) {} - - bool Initialize(NativePixmap* pixmap, - gfx::GpuMemoryBuffer::Format format) { - base::FileDescriptor handle(pixmap->GetDmaBufFd(), false); - if (!GLImageLinuxDMABuffer::Initialize( - handle, format, pixmap->GetDmaBufPitch())) - return false; - pixmap_ = pixmap; - return true; - } - - virtual bool ScheduleOverlayPlane(gfx::AcceleratedWidget widget, - int z_order, - gfx::OverlayTransform transform, - const gfx::Rect& bounds_rect, - const gfx::RectF& crop_rect) override { - return SurfaceFactoryOzone::GetInstance()->ScheduleOverlayPlane( - widget, z_order, transform, pixmap_, bounds_rect, crop_rect); - } - - protected: - virtual ~GLImageOzoneNativePixmapDmaBuf() {} - - private: - scoped_refptr<NativePixmap> pixmap_; -}; - -SurfaceFactoryOzone::BufferFormat GetOzoneFormatFor( - gfx::GpuMemoryBuffer::Format format) { - switch (format) { - case gfx::GpuMemoryBuffer::RGBA_8888: - return SurfaceFactoryOzone::RGBA_8888; - case gfx::GpuMemoryBuffer::RGBX_8888: - return SurfaceFactoryOzone::RGBX_8888; - case gfx::GpuMemoryBuffer::BGRA_8888: - NOTREACHED(); - return SurfaceFactoryOzone::RGBA_8888; - } - - NOTREACHED(); - return SurfaceFactoryOzone::RGBA_8888; -} - -std::pair<uint32_t, uint32_t> GetIndex(const gfx::GpuMemoryBufferId& id) { - return std::pair<uint32_t, uint32_t>(id.primary_id, id.secondary_id); -} -} // namespace - -GpuMemoryBufferFactoryOzoneNativeBuffer:: - GpuMemoryBufferFactoryOzoneNativeBuffer() { -} - -GpuMemoryBufferFactoryOzoneNativeBuffer:: - ~GpuMemoryBufferFactoryOzoneNativeBuffer() { -} - -bool GpuMemoryBufferFactoryOzoneNativeBuffer::CreateGpuMemoryBuffer( - const gfx::GpuMemoryBufferId& id, - const gfx::Size& size, - gfx::GpuMemoryBuffer::Format format, - gfx::GpuMemoryBuffer::Usage usage) { - scoped_refptr<NativePixmap> pixmap = - SurfaceFactoryOzone::GetInstance()->CreateNativePixmap( - size, GetOzoneFormatFor(format)); - if (!pixmap.get()) { - LOG(ERROR) << "Failed to create pixmap " << size.width() << "x" - << size.height() << " format " << format << ", usage " << usage; - return false; - } - native_pixmap_map_[GetIndex(id)] = pixmap; - return true; -} - -void GpuMemoryBufferFactoryOzoneNativeBuffer::DestroyGpuMemoryBuffer( - const gfx::GpuMemoryBufferId& id) { - native_pixmap_map_.erase(GetIndex(id)); -} - -scoped_refptr<gfx::GLImage> -GpuMemoryBufferFactoryOzoneNativeBuffer::CreateImageForGpuMemoryBuffer( - const gfx::GpuMemoryBufferId& id, - const gfx::Size& size, - gfx::GpuMemoryBuffer::Format format, - unsigned internalformat) { - BufferToPixmapMap::iterator it = native_pixmap_map_.find(GetIndex(id)); - if (it == native_pixmap_map_.end()) { - return scoped_refptr<gfx::GLImage>(); - } - NativePixmap* pixmap = it->second.get(); - if (pixmap->GetEGLClientBuffer()) { - DCHECK_EQ(-1, pixmap->GetDmaBufFd()); - scoped_refptr<GLImageOzoneNativePixmap> image = - new GLImageOzoneNativePixmap(size); - if (!image->Initialize(pixmap)) { - return scoped_refptr<gfx::GLImage>(); - } - return image; - } - if (pixmap->GetDmaBufFd() > 0) { - scoped_refptr<GLImageOzoneNativePixmapDmaBuf> image = - new GLImageOzoneNativePixmapDmaBuf(size, internalformat); - if (!image->Initialize(pixmap, format)) { - return scoped_refptr<gfx::GLImage>(); - } - return image; - } - return scoped_refptr<gfx::GLImage>(); -} - -} // namespace ui
diff --git a/ui/ozone/gpu/gpu_memory_buffer_factory_ozone_native_buffer.h b/ui/ozone/gpu/gpu_memory_buffer_factory_ozone_native_buffer.h deleted file mode 100644 index c65ce04..0000000 --- a/ui/ozone/gpu/gpu_memory_buffer_factory_ozone_native_buffer.h +++ /dev/null
@@ -1,52 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_GPU_GPU_MEMORY_BUFFER_FACTORY_OZONE_NATIVE_BUFFER_H_ -#define UI_OZONE_GPU_GPU_MEMORY_BUFFER_FACTORY_OZONE_NATIVE_BUFFER_H_ - -#include <map> - -#include "base/memory/ref_counted.h" -#include "ui/gfx/geometry/size.h" -#include "ui/gfx/gpu_memory_buffer.h" -#include "ui/ozone/gpu/ozone_gpu_export.h" - -namespace gfx { -class GLImage; -} - -namespace ui { -class NativePixmap; - -class OZONE_GPU_EXPORT GpuMemoryBufferFactoryOzoneNativeBuffer { - typedef std::map<std::pair<uint32_t, uint32_t>, scoped_refptr<NativePixmap> > - BufferToPixmapMap; - - public: - GpuMemoryBufferFactoryOzoneNativeBuffer(); - virtual ~GpuMemoryBufferFactoryOzoneNativeBuffer(); - - // Creates a GPU memory buffer identified by |id|. - bool CreateGpuMemoryBuffer(const gfx::GpuMemoryBufferId& id, - const gfx::Size& size, - gfx::GpuMemoryBuffer::Format format, - gfx::GpuMemoryBuffer::Usage usage); - - // Destroys GPU memory buffer identified by |id|. - void DestroyGpuMemoryBuffer(const gfx::GpuMemoryBufferId& id); - - // Creates a GLImage instance for GPU memory buffer identified by |id|. - scoped_refptr<gfx::GLImage> CreateImageForGpuMemoryBuffer( - const gfx::GpuMemoryBufferId& id, - const gfx::Size& size, - gfx::GpuMemoryBuffer::Format format, - unsigned internalformat); - - private: - BufferToPixmapMap native_pixmap_map_; -}; - -} // namespace ui - -#endif // UI_OZONE_GPU_GPU_MEMORY_BUFFER_FACTORY_OZONE_NATIVE_BUFFER_H_
diff --git a/ui/ozone/gpu/ozone_gpu.gyp b/ui/ozone/gpu/ozone_gpu.gyp deleted file mode 100644 index 72bf156..0000000 --- a/ui/ozone/gpu/ozone_gpu.gyp +++ /dev/null
@@ -1,28 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -{ - 'variables': { - 'chromium_code': 1, - }, - 'targets': [ - { - 'target_name': 'ozone_gpu', - 'type': '<(component)', - 'dependencies': [ - '../../../base/base.gyp:base', - '../../gfx/gfx.gyp:gfx', - '../../gfx/gfx.gyp:gfx_geometry', - '../../gl/gl.gyp:gl', - ], - 'defines': [ - 'OZONE_GPU_IMPLEMENTATION', - ], - 'sources': [ - 'gpu_memory_buffer_factory_ozone_native_buffer.cc', - 'gpu_memory_buffer_factory_ozone_native_buffer.h', - ], - }, - ], -}
diff --git a/ui/ozone/gpu/ozone_gpu_export.h b/ui/ozone/gpu/ozone_gpu_export.h deleted file mode 100644 index cc4a7bc..0000000 --- a/ui/ozone/gpu/ozone_gpu_export.h +++ /dev/null
@@ -1,29 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_GPU_OZONE_GPU_EXPORT_H_ -#define UI_OZONE_GPU_OZONE_GPU_EXPORT_H_ - -#if defined(COMPONENT_BUILD) -#if defined(WIN32) - -#if defined(OZONE_GPU_IMPLEMENTATION) -#define OZONE_GPU_EXPORT __declspec(dllexport) -#else -#define OZONE_GPU_EXPORT __declspec(dllimport) -#endif // defined(OZONE_GPU_IMPLEMENTATION) - -#else // defined(WIN32) -#if defined(OZONE_GPU_IMPLEMENTATION) -#define OZONE_GPU_EXPORT __attribute__((visibility("default"))) -#else -#define OZONE_GPU_EXPORT -#endif -#endif - -#else // defined(COMPONENT_BUILD) -#define OZONE_GPU_EXPORT -#endif - -#endif // UI_OZONE_GPU_OZONE_GPU_EXPORT_H_
diff --git a/ui/ozone/ozone.gni b/ui/ozone/ozone.gni deleted file mode 100644 index 867813c..0000000 --- a/ui/ozone/ozone.gni +++ /dev/null
@@ -1,31 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -declare_args() { - # Select platforms automatically. Turn this off for manual control. - ozone_auto_platforms = true -} - -declare_args() { - # The platform that will be active by default. - ozone_platform = "" - - # Enable individual platforms. - ozone_platform_caca = false - ozone_platform_dri = false - ozone_platform_egltest = false - ozone_platform_gbm = false - ozone_platform_test = false - - if (ozone_auto_platforms) { - # Use test as the default platform. - ozone_platform = "test" - - # Build all platforms whose deps are in install-build-deps.sh. - # Only these platforms will be compile tested by buildbots. - ozone_platform_dri = true - ozone_platform_test = true - ozone_platform_egltest = true - } -}
diff --git a/ui/ozone/ozone.gyp b/ui/ozone/ozone.gyp deleted file mode 100644 index f965c61..0000000 --- a/ui/ozone/ozone.gyp +++ /dev/null
@@ -1,211 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -{ - 'variables': { - 'chromium_code': 1, - # Normally, the external_ozone_platform* variables below can be - # overridden by supplement.gypi which must exist exactly one level - # below the top-level src directory. They can now also be set in - # $GYP_DEFINES - 'external_ozone_platforms%': [], - 'external_ozone_platform_files%': [], - 'external_ozone_platform_deps%': [], - 'external_ozone_platform_unittest_deps%': [], - 'internal_ozone_platforms': [], - 'internal_ozone_platform_deps': [], - 'internal_ozone_platform_unittest_deps': [], - }, - 'targets': [ - { - # GN version: //ui/ozone:ozone_base - 'target_name': 'ozone_base', - 'type': '<(component)', - 'dependencies': [ - '<(DEPTH)/base/base.gyp:base', - '<(DEPTH)/skia/skia.gyp:skia', - '<(DEPTH)/ui/gfx/gfx.gyp:gfx_geometry', - ], - 'defines': [ - 'OZONE_BASE_IMPLEMENTATION', - ], - 'sources': [ - 'public/cursor_factory_ozone.cc', - 'public/cursor_factory_ozone.h', - 'public/gpu_platform_support.cc', - 'public/gpu_platform_support.h', - 'public/gpu_platform_support_host.cc', - 'public/gpu_platform_support_host.h', - 'public/native_pixmap.h', - 'public/overlay_candidates_ozone.cc', - 'public/overlay_candidates_ozone.h', - 'public/surface_factory_ozone.cc', - 'public/surface_factory_ozone.h', - 'public/surface_ozone_canvas.h', - 'public/surface_ozone_egl.h', - ], - }, - { - # GN version: //ui/ozone - 'target_name': 'ozone', - 'type': '<(component)', - 'dependencies': [ - '<(DEPTH)/base/base.gyp:base', - '<(DEPTH)/ipc/ipc.gyp:ipc', - '<(DEPTH)/skia/skia.gyp:skia', - '<(DEPTH)/ui/display/display.gyp:display_types', - '<(DEPTH)/ui/events/events.gyp:events', - '<(DEPTH)/ui/events/ozone/events_ozone.gyp:events_ozone', - '<(DEPTH)/ui/gfx/gfx.gyp:gfx', - '<(DEPTH)/ui/gfx/gfx.gyp:gfx_geometry', - '<(DEPTH)/ui/gfx/ipc/gfx_ipc.gyp:gfx_ipc', - '<@(external_ozone_platform_deps)', - '<@(internal_ozone_platform_deps)', - 'ozone_base', - ], - 'defines': [ - 'OZONE_IMPLEMENTATION', - ], - 'variables': { - 'platform_list_cc_file': '<(INTERMEDIATE_DIR)/ui/ozone/platform_list.cc', - 'platform_list_h_file': '<(SHARED_INTERMEDIATE_DIR)/ui/ozone/platform_list.h', - 'platform_list_txt_file': '<(SHARED_INTERMEDIATE_DIR)/ui/ozone/platform_list.txt', - 'constructor_list_cc_file': '<(INTERMEDIATE_DIR)/ui/ozone/constructor_list.cc', - 'ozone_platforms': [ - '<@(external_ozone_platforms)', - '<@(internal_ozone_platforms)', - ], - }, - 'include_dirs': [ - '<(SHARED_INTERMEDIATE_DIR)', - ], - 'sources': [ - '<(platform_list_cc_file)', - '<(platform_list_h_file)', - '<(constructor_list_cc_file)', - - 'common/display_mode_proxy.cc', - 'common/display_mode_proxy.h', - 'common/display_snapshot_proxy.cc', - 'common/display_snapshot_proxy.h', - 'common/display_util.cc', - 'common/display_util.h', - 'common/gpu/ozone_gpu_message_generator.cc', - 'common/gpu/ozone_gpu_message_generator.h', - 'common/gpu/ozone_gpu_message_params.cc', - 'common/gpu/ozone_gpu_message_params.h', - 'common/gpu/ozone_gpu_messages.h', - 'common/native_display_delegate_ozone.cc', - 'common/native_display_delegate_ozone.h', - 'public/ozone_platform.cc', - 'public/ozone_platform.h', - 'public/ozone_switches.cc', - 'public/ozone_switches.h', - 'public/ui_thread_gpu.cc', - 'public/ui_thread_gpu.h', - 'platform_selection.cc', - 'platform_selection.h', - '<@(external_ozone_platform_files)', - ], - 'actions': [ - { - # GN version: //ui/ozone:generate_ozone_platform_list - 'action_name': 'generate_ozone_platform_list', - 'variables': { - 'generator_path': 'generate_ozone_platform_list.py', - }, - 'inputs': [ - '<(generator_path)', - ], - 'outputs': [ - '<(platform_list_cc_file)', - '<(platform_list_h_file)', - '<(platform_list_txt_file)', - ], - 'action': [ - 'python', - '<(generator_path)', - '--output_cc=<(platform_list_cc_file)', - '--output_h=<(platform_list_h_file)', - '--output_txt=<(platform_list_txt_file)', - '--default=<(ozone_platform)', - '<@(ozone_platforms)', - ], - }, - { - # GN version: //ui/ozone:generate_constructor_list - 'action_name': 'generate_constructor_list', - 'variables': { - 'generator_path': 'generate_constructor_list.py', - }, - 'inputs': [ - '<(generator_path)', - '<(platform_list_txt_file)', - ], - 'outputs': [ - '<(constructor_list_cc_file)', - ], - 'action': [ - 'python', - '<(generator_path)', - '--platform_list=<(platform_list_txt_file)', - '--output_cc=<(constructor_list_cc_file)', - '--namespace=ui', - '--typename=OzonePlatform', - '--include="ui/ozone/public/ozone_platform.h"' - ], - }, - ], - 'conditions': [ - ['use_udev == 0', { - 'sources/': [ - ['exclude', '_udev\\.(h|cc)$'], - ], - }], - ], - }, - { - 'target_name': 'ozone_unittests', - 'type': '<(gtest_target_type)', - 'sources': [ - 'run_all_unittests.cc', - ], - 'dependencies': [ - 'ozone_base', - '../../base/base.gyp:base', - '../../base/base.gyp:test_support_base', - '../../testing/gtest.gyp:gtest', - '<@(external_ozone_platform_unittest_deps)', - '<@(internal_ozone_platform_unittest_deps)', - ], - }, - ], - 'conditions': [ - ['<(ozone_platform_caca) == 1', { - 'includes': [ - 'platform/caca/caca.gypi', - ], - }], - ['<(ozone_platform_dri) == 1 or <(ozone_platform_gbm) == 1', { - 'includes': [ - 'platform/dri/dri.gypi', - ], - }], - ['<(ozone_platform_egltest) == 1', { - 'includes': [ - 'platform/egltest/egltest.gypi', - ], - }], - ['<(ozone_platform_gbm) == 1', { - 'includes': [ - 'platform/dri/gbm.gypi', - ], - }], - ['<(ozone_platform_test) == 1', { - 'includes': [ - 'platform/test/test.gypi', - ], - }], - ], -}
diff --git a/ui/ozone/ozone_base_export.h b/ui/ozone/ozone_base_export.h deleted file mode 100644 index d3df39b..0000000 --- a/ui/ozone/ozone_base_export.h +++ /dev/null
@@ -1,29 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_OZONE_BASE_EXPORT_H_ -#define UI_OZONE_OZONE_BASE_EXPORT_H_ - -#if defined(COMPONENT_BUILD) -#if defined(WIN32) - -#if defined(OZONE_BASE_IMPLEMENTATION) -#define OZONE_BASE_EXPORT __declspec(dllexport) -#else -#define OZONE_BASE_EXPORT __declspec(dllimport) -#endif // defined(OZONE_BASE_IMPLEMENTATION) - -#else // defined(WIN32) -#if defined(OZONE_BASE_IMPLEMENTATION) -#define OZONE_BASE_EXPORT __attribute__((visibility("default"))) -#else -#define OZONE_BASE_EXPORT -#endif -#endif - -#else // defined(COMPONENT_BUILD) -#define OZONE_BASE_EXPORT -#endif - -#endif // UI_OZONE_OZONE_BASE_EXPORT_H_
diff --git a/ui/ozone/ozone_export.h b/ui/ozone/ozone_export.h deleted file mode 100644 index cc587a5..0000000 --- a/ui/ozone/ozone_export.h +++ /dev/null
@@ -1,29 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_OZONE_EXPORT_H_ -#define UI_OZONE_OZONE_EXPORT_H_ - -#if defined(COMPONENT_BUILD) -#if defined(WIN32) - -#if defined(OZONE_IMPLEMENTATION) -#define OZONE_EXPORT __declspec(dllexport) -#else -#define OZONE_EXPORT __declspec(dllimport) -#endif // defined(OZONE_IMPLEMENTATION) - -#else // defined(WIN32) -#if defined(OZONE_IMPLEMENTATION) -#define OZONE_EXPORT __attribute__((visibility("default"))) -#else -#define OZONE_EXPORT -#endif -#endif - -#else // defined(COMPONENT_BUILD) -#define OZONE_EXPORT -#endif - -#endif // UI_OZONE_OZONE_EXPORT_H_
diff --git a/ui/ozone/platform/README b/ui/ozone/platform/README deleted file mode 100644 index cc91d3b..0000000 --- a/ui/ozone/platform/README +++ /dev/null
@@ -1,2 +0,0 @@ -This directory contains implementations of platforms. Each platform implements -the interfaces from ui/ozone/public for the rest of chromium.
diff --git a/ui/ozone/platform/caca/BUILD.gn b/ui/ozone/platform/caca/BUILD.gn deleted file mode 100644 index a3aacf1..0000000 --- a/ui/ozone/platform/caca/BUILD.gn +++ /dev/null
@@ -1,32 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import("//build/config/linux/pkg_config.gni") - -source_set("caca") { - sources = [ - "caca_event_source.cc", - "caca_event_source.h", - "caca_window.cc", - "caca_window.h", - "caca_window_manager.cc", - "caca_window_manager.h", - "ozone_platform_caca.cc", - "ozone_platform_caca.h", - "scoped_caca_types.cc", - "scoped_caca_types.h", - ] - - deps = [ - "//base", - "//skia", - "//ui/gfx/geometry", - ] - - configs += [ ":libcaca" ] -} - -pkg_config("libcaca") { - packages = [ "caca" ] -}
diff --git a/ui/ozone/platform/caca/OWNERS b/ui/ozone/platform/caca/OWNERS deleted file mode 100644 index 0d77c0e..0000000 --- a/ui/ozone/platform/caca/OWNERS +++ /dev/null
@@ -1 +0,0 @@ -dnicoara@chromium.org
diff --git a/ui/ozone/platform/caca/caca.gypi b/ui/ozone/platform/caca/caca.gypi deleted file mode 100644 index 34a5e69..0000000 --- a/ui/ozone/platform/caca/caca.gypi +++ /dev/null
@@ -1,47 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -{ - 'variables': { - 'internal_ozone_platform_deps': [ - 'ozone_platform_caca', - ], - 'internal_ozone_platforms': [ - 'caca' - ], - }, - 'targets': [ - { - 'target_name': 'ozone_platform_caca', - 'type': 'static_library', - 'defines': [ - 'OZONE_IMPLEMENTATION', - ], - 'dependencies': [ - '../../base/base.gyp:base', - '../../skia/skia.gyp:skia', - '../events/events.gyp:events', - '../gfx/gfx.gyp:gfx', - '../gfx/gfx.gyp:gfx_geometry', - ], - 'link_settings': { - 'libraries': [ - '-lcaca', - ], - }, - 'sources': [ - 'caca_event_source.cc', - 'caca_event_source.h', - 'caca_window.cc', - 'caca_window.h', - 'caca_window_manager.cc', - 'caca_window_manager.h', - 'ozone_platform_caca.cc', - 'ozone_platform_caca.h', - 'scoped_caca_types.cc', - 'scoped_caca_types.h', - ], - }, - ], -}
diff --git a/ui/ozone/platform/caca/caca_event_source.cc b/ui/ozone/platform/caca/caca_event_source.cc deleted file mode 100644 index a8da8b4..0000000 --- a/ui/ozone/platform/caca/caca_event_source.cc +++ /dev/null
@@ -1,229 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/caca/caca_event_source.h" - -#include <caca.h> - -#include "base/bind.h" -#include "base/message_loop/message_loop.h" -#include "ui/events/event.h" -#include "ui/events/keycodes/keyboard_codes.h" -#include "ui/ozone/platform/caca/caca_window.h" - -namespace ui { - -namespace { - -ui::KeyboardCode GetKeyboardCode(const caca_event_t& event) { - // List of special mappings the Caca provides. - static const ui::KeyboardCode kCacaKeyMap[] = { - ui::VKEY_UNKNOWN, - ui::VKEY_A, - ui::VKEY_B, - ui::VKEY_C, - ui::VKEY_D, - ui::VKEY_E, - ui::VKEY_F, - ui::VKEY_G, - ui::VKEY_BACK, - ui::VKEY_TAB, - ui::VKEY_J, - ui::VKEY_K, - ui::VKEY_L, - ui::VKEY_RETURN, - ui::VKEY_N, - ui::VKEY_O, - ui::VKEY_P, - ui::VKEY_Q, - ui::VKEY_R, - ui::VKEY_PAUSE, - ui::VKEY_T, - ui::VKEY_U, - ui::VKEY_V, - ui::VKEY_W, - ui::VKEY_X, - ui::VKEY_Y, - ui::VKEY_Z, - ui::VKEY_ESCAPE, - ui::VKEY_DELETE, - ui::VKEY_UP, - ui::VKEY_DOWN, - ui::VKEY_LEFT, - ui::VKEY_RIGHT, - ui::VKEY_INSERT, - ui::VKEY_HOME, - ui::VKEY_END, - ui::VKEY_PRIOR, - ui::VKEY_NEXT, - ui::VKEY_F1, - ui::VKEY_F2, - ui::VKEY_F3, - ui::VKEY_F4, - ui::VKEY_F5, - ui::VKEY_F6, - ui::VKEY_F7, - ui::VKEY_F8, - ui::VKEY_F9, - ui::VKEY_F10, - ui::VKEY_F11, - ui::VKEY_F12, - }; - - int key_code = caca_get_event_key_ch(&event); - if (key_code >= 'a' && key_code <= 'z') - return static_cast<ui::KeyboardCode>(key_code - ('a' - 'A')); - if (key_code >= '0' && key_code <= 'Z') - return static_cast<ui::KeyboardCode>(key_code); - if (static_cast<unsigned int>(key_code) < arraysize(kCacaKeyMap)) - return kCacaKeyMap[key_code]; - - return ui::VKEY_UNKNOWN; -} - -int ModifierFromKey(const caca_event_t& event) { - int key_code = caca_get_event_key_ch(&event); - if (key_code >= 'A' && key_code <= 'Z') - return ui::EF_SHIFT_DOWN; - if ((key_code >= CACA_KEY_CTRL_A && key_code <= CACA_KEY_CTRL_G) || - (key_code >= CACA_KEY_CTRL_J && key_code <= CACA_KEY_CTRL_L) || - (key_code >= CACA_KEY_CTRL_N && key_code <= CACA_KEY_CTRL_R) || - (key_code >= CACA_KEY_CTRL_T && key_code <= CACA_KEY_CTRL_Z)) - return ui::EF_CONTROL_DOWN; - - return ui::EF_NONE; -} - -int ModifierFromButton(const caca_event_t& event) { - switch (caca_get_event_mouse_button(&event)) { - case 1: - return ui::EF_LEFT_MOUSE_BUTTON; - case 2: - return ui::EF_RIGHT_MOUSE_BUTTON; - case 3: - return ui::EF_MIDDLE_MOUSE_BUTTON; - } - return 0; -} - -// Translate coordinates to bitmap coordinates. -gfx::PointF TranslateLocation(const gfx::PointF& location, CacaWindow* window) { - gfx::Size physical_size = window->physical_size(); - gfx::Size bitmap_size = window->bitmap_size(); - return gfx::PointF( - location.x() * bitmap_size.width() / physical_size.width(), - location.y() * bitmap_size.height() / physical_size.height()); -} - -ui::EventType GetEventTypeFromNative(const caca_event_t& event) { - switch (caca_get_event_type(&event)) { - case CACA_EVENT_KEY_PRESS: - return ui::ET_KEY_PRESSED; - case CACA_EVENT_KEY_RELEASE: - return ui::ET_KEY_RELEASED; - case CACA_EVENT_MOUSE_PRESS: - return ui::ET_MOUSE_PRESSED; - case CACA_EVENT_MOUSE_RELEASE: - return ui::ET_MOUSE_RELEASED; - case CACA_EVENT_MOUSE_MOTION: - return ui::ET_MOUSE_MOVED; - default: - return ui::ET_UNKNOWN; - } -} - -} // namespace - -CacaEventSource::CacaEventSource() : modifier_flags_(0) { -} - -CacaEventSource::~CacaEventSource() { -} - -void CacaEventSource::TryProcessingEvent(CacaWindow* window) { - if (!window->display()) - return; - - caca_event_t event; - int event_mask = CACA_EVENT_KEY_PRESS | CACA_EVENT_KEY_RELEASE | - CACA_EVENT_MOUSE_PRESS | CACA_EVENT_MOUSE_RELEASE | - CACA_EVENT_MOUSE_MOTION | CACA_EVENT_RESIZE | - CACA_EVENT_QUIT; - - if (!caca_get_event(window->display(), event_mask, &event, 0)) - return; - - switch (caca_get_event_type(&event)) { - case CACA_EVENT_KEY_PRESS: - case CACA_EVENT_KEY_RELEASE: - case CACA_EVENT_MOUSE_PRESS: - case CACA_EVENT_MOUSE_RELEASE: - case CACA_EVENT_MOUSE_MOTION: - OnInputEvent(&event, window); - break; - case CACA_EVENT_RESIZE: - window->OnCacaResize(); - break; - case CACA_EVENT_QUIT: - window->OnCacaQuit(); - break; - default: - NOTIMPLEMENTED(); - } -} - -void CacaEventSource::OnInputEvent(caca_event_t* event, CacaWindow* window) { - ui::EventType type = GetEventTypeFromNative(*event); - bool pressed = type == ui::ET_KEY_PRESSED || type == ui::ET_MOUSE_PRESSED; - - switch (type) { - case ui::ET_KEY_PRESSED: - case ui::ET_KEY_RELEASED: { - if (pressed) - modifier_flags_ |= ModifierFromKey(*event); - else - modifier_flags_ &= ~ModifierFromKey(*event); - - ui::KeyEvent key_event( - type, GetKeyboardCode(*event), modifier_flags_); - window->OnCacaEvent(&key_event); - break; - } - case ui::ET_MOUSE_MOVED: - last_cursor_location_.SetPoint(caca_get_event_mouse_x(event), - caca_get_event_mouse_y(event)); - // Update cursor location. - caca_gotoxy(caca_get_canvas(window->display()), - last_cursor_location_.x(), - last_cursor_location_.y()); - - // fallthrough - case ui::ET_MOUSE_PRESSED: - case ui::ET_MOUSE_RELEASED: { - int flags = 0; - int changed_flags = 0; - if (type != ui::ET_MOUSE_MOVED) { - if (pressed) { - changed_flags = ModifierFromButton(*event); - modifier_flags_ |= changed_flags; - } else { - modifier_flags_ &= ~changed_flags; - } - // On release the button pressed is removed from |modifier_flags_|, - // but sending the event needs it set. - flags = modifier_flags_ | changed_flags; - } - gfx::PointF location = TranslateLocation(last_cursor_location_, window); - ui::MouseEvent mouse_event( - type, location, location, flags, changed_flags); - window->OnCacaEvent(&mouse_event); - break; - } - default: - NOTIMPLEMENTED(); - break; - } -} - -} // namespace ui
diff --git a/ui/ozone/platform/caca/caca_event_source.h b/ui/ozone/platform/caca/caca_event_source.h deleted file mode 100644 index daa7fc9..0000000 --- a/ui/ozone/platform/caca/caca_event_source.h +++ /dev/null
@@ -1,44 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_CACA_CACA_EVENT_SOURCE_H_ -#define UI_OZONE_PLATFORM_CACA_CACA_EVENT_SOURCE_H_ - -#include <caca.h> - -#include "base/memory/ref_counted.h" -#include "base/time/time.h" -#include "ui/events/platform/platform_event_source.h" -#include "ui/events/platform/scoped_event_dispatcher.h" -#include "ui/gfx/geometry/point_f.h" - -namespace ui { - -class CacaWindow; - -class CacaEventSource : public PlatformEventSource { - public: - CacaEventSource(); - virtual ~CacaEventSource(); - - // Poll for an event on a particular window. Input events will be - // dispatched on the given dispatcher. - void TryProcessingEvent(CacaWindow* window); - - // Process an input event on a particular window. - void OnInputEvent(caca_event_t* event, CacaWindow* window); - - private: - // Keep track of last cursor position to dispatch correct mouse push/release - // events. - gfx::PointF last_cursor_location_; - - int modifier_flags_; - - DISALLOW_COPY_AND_ASSIGN(CacaEventSource); -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_CACA_CACA_EVENT_SOURCE_H_
diff --git a/ui/ozone/platform/caca/caca_window.cc b/ui/ozone/platform/caca/caca_window.cc deleted file mode 100644 index ff2f571..0000000 --- a/ui/ozone/platform/caca/caca_window.cc +++ /dev/null
@@ -1,146 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/caca/caca_window.h" - -#include "base/bind.h" -#include "base/debug/trace_event.h" -#include "base/logging.h" -#include "base/message_loop/message_loop.h" -#include "ui/events/ozone/events_ozone.h" -#include "ui/events/platform/platform_event_source.h" -#include "ui/ozone/platform/caca/caca_event_source.h" -#include "ui/ozone/platform/caca/caca_window_manager.h" -#include "ui/platform_window/platform_window_delegate.h" - -namespace ui { - -namespace { - -// Size of initial cnavas (in characters). -const int kDefaultCanvasWidth = 160; -const int kDefaultCanvasHeight = 48; - -} // namespace - -// TODO(dnicoara) As an optimization, |bitmap_size_| should be scaled based on -// |physical_size_| and font size. -CacaWindow::CacaWindow(PlatformWindowDelegate* delegate, - CacaWindowManager* manager, - CacaEventSource* event_source, - const gfx::Rect& bounds) - : delegate_(delegate), - manager_(manager), - event_source_(event_source), - weak_ptr_factory_(this) { - widget_ = manager_->AddWindow(this); - ui::PlatformEventSource::GetInstance()->AddPlatformEventDispatcher(this); - delegate_->OnAcceleratedWidgetAvailable(widget_); -} - -CacaWindow::~CacaWindow() { - ui::PlatformEventSource::GetInstance()->RemovePlatformEventDispatcher(this); - manager_->RemoveWindow(widget_, this); -} - -bool CacaWindow::Initialize() { - if (display_) - return true; - - canvas_.reset(caca_create_canvas(kDefaultCanvasWidth, kDefaultCanvasHeight)); - if (!canvas_) { - PLOG(ERROR) << "failed to create libcaca canvas"; - return false; - } - - display_.reset(caca_create_display(canvas_.get())); - if (!display_) { - PLOG(ERROR) << "failed to initialize libcaca display"; - return false; - } - - caca_set_cursor(display_.get(), 1); - caca_set_display_title(display_.get(), "Ozone Content Shell"); - - UpdateDisplaySize(); - - TryProcessingEvent(); - - return true; -} - -void CacaWindow::TryProcessingEvent() { - event_source_->TryProcessingEvent(this); - - // Caca uses a poll based event retrieval. Since we don't want to block we'd - // either need to spin up a new thread or just poll. For simplicity just poll - // for messages. - base::MessageLoop::current()->PostDelayedTask( - FROM_HERE, - base::Bind(&CacaWindow::TryProcessingEvent, - weak_ptr_factory_.GetWeakPtr()), - base::TimeDelta::FromMilliseconds(10)); -} - -void CacaWindow::UpdateDisplaySize() { - physical_size_.SetSize(caca_get_canvas_width(canvas_.get()), - caca_get_canvas_height(canvas_.get())); - - bitmap_size_.SetSize(caca_get_display_width(display_.get()), - caca_get_display_height(display_.get())); -} - -void CacaWindow::OnCacaResize() { - UpdateDisplaySize(); - - delegate_->OnBoundsChanged(gfx::Rect(bitmap_size_)); -} - -void CacaWindow::OnCacaQuit() { - delegate_->OnCloseRequest(); -} - - -void CacaWindow::OnCacaEvent(ui::Event* event) { - DispatchEventFromNativeUiEvent( - event, - base::Bind(&PlatformWindowDelegate::DispatchEvent, - base::Unretained(delegate_))); -} - -gfx::Rect CacaWindow::GetBounds() { return gfx::Rect(bitmap_size_); } - -void CacaWindow::SetBounds(const gfx::Rect& bounds) {} - -void CacaWindow::Show() {} - -void CacaWindow::Hide() {} - -void CacaWindow::Close() {} - -void CacaWindow::SetCapture() {} - -void CacaWindow::ReleaseCapture() {} - -void CacaWindow::ToggleFullscreen() {} - -void CacaWindow::Maximize() {} - -void CacaWindow::Minimize() {} - -void CacaWindow::Restore() {} - -void CacaWindow::SetCursor(PlatformCursor cursor) {} - -void CacaWindow::MoveCursorTo(const gfx::Point& location) {} - -bool CacaWindow::CanDispatchEvent(const PlatformEvent& event) { return true; } - -uint32_t CacaWindow::DispatchEvent(const PlatformEvent& ne) { - // We don't dispatch events via PlatformEventSource. - NOTREACHED(); - return ui::POST_DISPATCH_STOP_PROPAGATION; -} - -} // namespace ui
diff --git a/ui/ozone/platform/caca/caca_window.h b/ui/ozone/platform/caca/caca_window.h deleted file mode 100644 index 5310a93..0000000 --- a/ui/ozone/platform/caca/caca_window.h +++ /dev/null
@@ -1,97 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_CACA_CACA_WINDOW_H_ -#define UI_OZONE_PLATFORM_CACA_CACA_WINDOW_H_ - -#include <caca.h> - -#include "base/debug/stack_trace.h" -#include "base/macros.h" -#include "base/memory/weak_ptr.h" -#include "ui/events/platform/platform_event_dispatcher.h" -#include "ui/gfx/geometry/size.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/ozone/platform/caca/scoped_caca_types.h" -#include "ui/platform_window/platform_window.h" - -namespace ui { - -class CacaEventSource; -class CacaWindowManager; -class PlatformWindowDelegate; - -// Basic initialization of Libcaca. This needs to be shared between SFO and EFO -// since both need the |display_| to draw and process events respectively. -// Note, |canvas_| needs to be here since it is needed for creating a -// |display_|. -class CacaWindow : public PlatformWindow, public PlatformEventDispatcher { - public: - CacaWindow(PlatformWindowDelegate* delegate, - CacaWindowManager* manager, - CacaEventSource* event_source, - const gfx::Rect& bounds); - virtual ~CacaWindow(); - - bool Initialize(); - - // Handlers for events received from libcaca. - void OnCacaQuit(); - void OnCacaResize(); - void OnCacaEvent(ui::Event* event); - - // This is the Caca canvas size. - gfx::Size physical_size() const { return physical_size_; } - gfx::Size bitmap_size() const { return bitmap_size_; } - caca_display_t* display() const { return display_.get(); } - - // PlatformWindow: - virtual gfx::Rect GetBounds() override; - virtual void SetBounds(const gfx::Rect& bounds) override; - virtual void Show() override; - virtual void Hide() override; - virtual void Close() override; - virtual void SetCapture() override; - virtual void ReleaseCapture() override; - virtual void ToggleFullscreen() override; - virtual void Maximize() override; - virtual void Minimize() override; - virtual void Restore() override; - virtual void SetCursor(PlatformCursor cursor) override; - virtual void MoveCursorTo(const gfx::Point& location) override; - - // PlatformEventDispatcher: - virtual bool CanDispatchEvent(const PlatformEvent& event) override; - virtual uint32_t DispatchEvent(const PlatformEvent& event) override; - - private: - // Event polling. - void TryProcessingEvent(); - - // Sync sizes with libcaca. - void UpdateDisplaySize(); - - PlatformWindowDelegate* delegate_; - CacaWindowManager* manager_; - CacaEventSource* event_source_; - gfx::AcceleratedWidget widget_; - - ScopedCacaCanvas canvas_; - ScopedCacaDisplay display_; - - // Size of the console in characters. This can be changed by setting - // CACA_GEOMETRY environment variable. - gfx::Size physical_size_; - - // Size of the backing buffer we draw into. Size in pixels. - gfx::Size bitmap_size_; - - base::WeakPtrFactory<CacaWindow> weak_ptr_factory_; - - DISALLOW_COPY_AND_ASSIGN(CacaWindow); -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_CACA_CACA_WINDOW_H_
diff --git a/ui/ozone/platform/caca/caca_window_manager.cc b/ui/ozone/platform/caca/caca_window_manager.cc deleted file mode 100644 index 0c3a43e..0000000 --- a/ui/ozone/platform/caca/caca_window_manager.cc +++ /dev/null
@@ -1,141 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/caca/caca_window_manager.h" - -#include "base/debug/trace_event.h" -#include "third_party/skia/include/core/SkBitmap.h" -#include "third_party/skia/include/core/SkCanvas.h" -#include "third_party/skia/include/core/SkSurface.h" -#include "ui/gfx/skia_util.h" -#include "ui/gfx/vsync_provider.h" -#include "ui/ozone/platform/caca/caca_window.h" -#include "ui/ozone/platform/caca/scoped_caca_types.h" -#include "ui/ozone/public/surface_ozone_canvas.h" - -namespace ui { - -namespace { - -class CacaSurface : public ui::SurfaceOzoneCanvas { - public: - CacaSurface(CacaWindow* window); - virtual ~CacaSurface(); - - bool Initialize(); - - // ui::SurfaceOzoneCanvas overrides: - virtual skia::RefPtr<SkCanvas> GetCanvas() override; - virtual void ResizeCanvas(const gfx::Size& viewport_size) override; - virtual void PresentCanvas(const gfx::Rect& damage) override; - virtual scoped_ptr<gfx::VSyncProvider> CreateVSyncProvider() override; - - private: - CacaWindow* window_; // Not owned. - - ScopedCacaDither dither_; - - skia::RefPtr<SkSurface> surface_; - - DISALLOW_COPY_AND_ASSIGN(CacaSurface); -}; - -CacaSurface::CacaSurface(CacaWindow* window) : window_(window) { -} - -CacaSurface::~CacaSurface() { -} - -bool CacaSurface::Initialize() { - ResizeCanvas(window_->bitmap_size()); - return true; -} - -skia::RefPtr<SkCanvas> CacaSurface::GetCanvas() { - return skia::SharePtr<SkCanvas>(surface_->getCanvas()); -} - -void CacaSurface::ResizeCanvas(const gfx::Size& viewport_size) { - TRACE_EVENT0("ozone", "CacaSurface::ResizeCanvas"); - - VLOG(2) << "creating libcaca surface with from window " << (void*)window_; - - SkImageInfo info = SkImageInfo::Make(window_->bitmap_size().width(), - window_->bitmap_size().height(), - kN32_SkColorType, - kPremul_SkAlphaType); - - surface_ = skia::AdoptRef(SkSurface::NewRaster(info)); - if (!surface_) - LOG(ERROR) << "Failed to create SkSurface"; - - dither_.reset(caca_create_dither(info.bytesPerPixel() * 8, - info.width(), - info.height(), - info.minRowBytes(), - 0x00ff0000, - 0x0000ff00, - 0x000000ff, - 0xff000000)); - if (!dither_) - LOG(ERROR) << "failed to create dither"; -} - -void CacaSurface::PresentCanvas(const gfx::Rect& damage) { - TRACE_EVENT0("ozone", "CacaSurface::PresentCanvas"); - - SkImageInfo info; - size_t row_bytes; - const void* pixels = surface_->peekPixels(&info, &row_bytes); - - caca_canvas_t* canvas = caca_get_canvas(window_->display()); - caca_dither_bitmap(canvas, - 0, - 0, - caca_get_canvas_width(canvas), - caca_get_canvas_height(canvas), - dither_.get(), - static_cast<const uint8_t*>(pixels)); - caca_refresh_display(window_->display()); -} - -scoped_ptr<gfx::VSyncProvider> CacaSurface::CreateVSyncProvider() { - return scoped_ptr<gfx::VSyncProvider>(); -} - -} // namespace - -CacaWindowManager::CacaWindowManager() { -} - -int32_t CacaWindowManager::AddWindow(CacaWindow* window) { - return windows_.Add(window); -} - -void CacaWindowManager::RemoveWindow(int window_id, CacaWindow* window) { - DCHECK_EQ(window, windows_.Lookup(window_id)); - windows_.Remove(window_id); -} - -CacaWindowManager::~CacaWindowManager() { -} - -bool CacaWindowManager::LoadEGLGLES2Bindings( - AddGLLibraryCallback add_gl_library, - SetGLGetProcAddressProcCallback set_gl_get_proc_address) { - return false; -} - -scoped_ptr<ui::SurfaceOzoneCanvas> CacaWindowManager::CreateCanvasForWidget( - gfx::AcceleratedWidget widget) { - CacaWindow* window = windows_.Lookup(widget); - DCHECK(window); - - scoped_ptr<CacaSurface> canvas(new CacaSurface(window)); - bool initialized = canvas->Initialize(); - DCHECK(initialized); - return canvas.Pass(); -} - -} // namespace ui
diff --git a/ui/ozone/platform/caca/caca_window_manager.h b/ui/ozone/platform/caca/caca_window_manager.h deleted file mode 100644 index de1d5ae..0000000 --- a/ui/ozone/platform/caca/caca_window_manager.h +++ /dev/null
@@ -1,46 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_CACA_CACA_WINDOW_MANAGER_H_ -#define UI_OZONE_PLATFORM_CACA_CACA_WINDOW_MANAGER_H_ - -#include "base/id_map.h" -#include "base/memory/scoped_ptr.h" -#include "ui/ozone/public/surface_factory_ozone.h" - -namespace gfx { -class Rect; -} - -namespace ui { - -class CacaWindow; - -class CacaWindowManager : public SurfaceFactoryOzone { - public: - CacaWindowManager(); - virtual ~CacaWindowManager(); - - // Register a new libcaca window/instance. Returns the window id. - int32_t AddWindow(CacaWindow* window); - - // Remove a libcaca window/instance. - void RemoveWindow(int32_t window_id, CacaWindow* window); - - // ui::SurfaceFactoryOzone overrides: - virtual bool LoadEGLGLES2Bindings( - AddGLLibraryCallback add_gl_library, - SetGLGetProcAddressProcCallback set_gl_get_proc_address) override; - virtual scoped_ptr<SurfaceOzoneCanvas> CreateCanvasForWidget( - gfx::AcceleratedWidget widget) override; - - private: - IDMap<CacaWindow> windows_; - - DISALLOW_COPY_AND_ASSIGN(CacaWindowManager); -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_CACA_CACA_WINDOW_MANAGER_H_
diff --git a/ui/ozone/platform/caca/ozone_platform_caca.cc b/ui/ozone/platform/caca/ozone_platform_caca.cc deleted file mode 100644 index c3b3233..0000000 --- a/ui/ozone/platform/caca/ozone_platform_caca.cc +++ /dev/null
@@ -1,70 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/caca/ozone_platform_caca.h" - -#include "ui/ozone/common/native_display_delegate_ozone.h" -#include "ui/ozone/platform/caca/caca_event_source.h" -#include "ui/ozone/platform/caca/caca_window.h" -#include "ui/ozone/platform/caca/caca_window_manager.h" -#include "ui/ozone/public/cursor_factory_ozone.h" -#include "ui/ozone/public/ozone_platform.h" - -namespace ui { - -namespace { - -class OzonePlatformCaca : public OzonePlatform { - public: - OzonePlatformCaca() {} - virtual ~OzonePlatformCaca() {} - - // OzonePlatform: - virtual ui::SurfaceFactoryOzone* GetSurfaceFactoryOzone() override { - return window_manager_.get(); - } - virtual CursorFactoryOzone* GetCursorFactoryOzone() override { - return cursor_factory_ozone_.get(); - } - virtual GpuPlatformSupport* GetGpuPlatformSupport() override { - return NULL; // no GPU support - } - virtual GpuPlatformSupportHost* GetGpuPlatformSupportHost() override { - return NULL; // no GPU support - } - virtual scoped_ptr<PlatformWindow> CreatePlatformWindow( - PlatformWindowDelegate* delegate, - const gfx::Rect& bounds) override { - scoped_ptr<CacaWindow> caca_window(new CacaWindow( - delegate, window_manager_.get(), event_source_.get(), bounds)); - if (!caca_window->Initialize()) - return nullptr; - return caca_window.Pass(); - } - virtual scoped_ptr<NativeDisplayDelegate> CreateNativeDisplayDelegate() - override { - return scoped_ptr<NativeDisplayDelegate>(new NativeDisplayDelegateOzone()); - } - - virtual void InitializeUI() override { - window_manager_.reset(new CacaWindowManager); - event_source_.reset(new CacaEventSource()); - cursor_factory_ozone_.reset(new CursorFactoryOzone()); - } - - virtual void InitializeGPU() override {} - - private: - scoped_ptr<CacaWindowManager> window_manager_; - scoped_ptr<CacaEventSource> event_source_; - scoped_ptr<CursorFactoryOzone> cursor_factory_ozone_; - - DISALLOW_COPY_AND_ASSIGN(OzonePlatformCaca); -}; - -} // namespace - -OzonePlatform* CreateOzonePlatformCaca() { return new OzonePlatformCaca; } - -} // namespace ui
diff --git a/ui/ozone/platform/caca/ozone_platform_caca.h b/ui/ozone/platform/caca/ozone_platform_caca.h deleted file mode 100644 index bf1f735..0000000 --- a/ui/ozone/platform/caca/ozone_platform_caca.h +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_CACA_OZONE_PLATFORM_CACA_H_ -#define UI_OZONE_PLATFORM_CACA_OZONE_PLATFORM_CACA_H_ - -namespace ui { - -class OzonePlatform; - -// Constructor hook for use in ozone_platform_list.cc -OzonePlatform* CreateOzonePlatformCaca(); - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_CACA_OZONE_PLATFORM_CACA_H_
diff --git a/ui/ozone/platform/caca/scoped_caca_types.cc b/ui/ozone/platform/caca/scoped_caca_types.cc deleted file mode 100644 index 093b7c9..0000000 --- a/ui/ozone/platform/caca/scoped_caca_types.cc +++ /dev/null
@@ -1,23 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/caca/scoped_caca_types.h" - -#include <caca.h> - -namespace ui { - -void CacaCanvasDeleter::operator()(caca_canvas_t* canvas) const { - caca_free_canvas(canvas); -} - -void CacaDisplayDeleter::operator()(caca_display_t* display) const { - caca_free_display(display); -} - -void CacaDitherDeleter::operator()(caca_dither_t* dither) const { - caca_free_dither(dither); -} - -} // namespace ui
diff --git a/ui/ozone/platform/caca/scoped_caca_types.h b/ui/ozone/platform/caca/scoped_caca_types.h deleted file mode 100644 index d789476..0000000 --- a/ui/ozone/platform/caca/scoped_caca_types.h +++ /dev/null
@@ -1,34 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_CACA_SCOPED_CACA_TYPES_H_ -#define UI_OZONE_PLATFORM_CACA_SCOPED_CACA_TYPES_H_ - -#include "base/memory/scoped_ptr.h" - -typedef struct caca_canvas caca_canvas_t; -typedef struct caca_dither caca_dither_t; -typedef struct caca_display caca_display_t; - -namespace ui { - -struct CacaCanvasDeleter { - void operator()(caca_canvas_t* canvas) const; -}; - -struct CacaDisplayDeleter { - void operator()(caca_display_t* display) const; -}; - -struct CacaDitherDeleter { - void operator()(caca_dither_t* dither) const; -}; - -typedef scoped_ptr<caca_canvas_t, CacaCanvasDeleter> ScopedCacaCanvas; -typedef scoped_ptr<caca_display_t, CacaDisplayDeleter> ScopedCacaDisplay; -typedef scoped_ptr<caca_dither_t, CacaDitherDeleter> ScopedCacaDither; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_CACA_SCOPED_CACA_TYPES_H_
diff --git a/ui/ozone/platform/dri/BUILD.gn b/ui/ozone/platform/dri/BUILD.gn deleted file mode 100644 index b59ac71..0000000 --- a/ui/ozone/platform/dri/BUILD.gn +++ /dev/null
@@ -1,146 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import("//build/config/linux/pkg_config.gni") -import("//ui/ozone/ozone.gni") - -pkg_config("libdrm") { - packages = [ "libdrm" ] -} - -source_set("dri_common") { - sources = [ - "channel_observer.h", - "crtc_controller.cc", - "crtc_controller.h", - "display_mode_dri.cc", - "display_mode_dri.h", - "display_snapshot_dri.cc", - "display_snapshot_dri.h", - "dri_console_buffer.cc", - "dri_console_buffer.h", - "dri_cursor.cc", - "dri_cursor.h", - "dri_buffer.cc", - "dri_buffer.h", - "dri_gpu_platform_support.cc", - "dri_gpu_platform_support_.h", - "dri_gpu_platform_support_host.cc", - "dri_gpu_platform_support_host.h", - "dri_surface.cc", - "dri_surface.h", - "dri_surface_factory.cc", - "dri_surface_factory.h", - "dri_util.cc", - "dri_util.h", - "dri_vsync_provider.cc", - "dri_vsync_provider.h", - "dri_window.cc", - "dri_window.h", - "dri_window_delegate.h", - "dri_window_delegate_impl.cc", - "dri_window_delegate_impl.h", - "dri_window_delegate_manager.cc", - "dri_window_delegate_manager.h", - "dri_window_manager.cc", - "dri_window_manager.h", - "dri_wrapper.cc", - "dri_wrapper.h", - "hardware_display_controller.cc", - "hardware_display_controller.h", - "native_display_delegate_dri.cc", - "native_display_delegate_dri.h", - "overlay_plane.cc", - "overlay_plane.h", - "scoped_drm_types.cc", - "scoped_drm_types.h", - "screen_manager.cc", - "screen_manager.h", - "scanout_buffer.h", - "virtual_terminal_manager.cc", - "virtual_terminal_manager.h", - ] - - deps = [ - "//base", - "//skia", - "//ipc", - "//ui/base", - "//ui/display/types", - "//ui/events", - "//ui/events/ozone:events_ozone_evdev", - "//ui/gfx", - "//ui/gfx/geometry", - ] - - public_configs = [ ":libdrm" ] -} - -if (ozone_platform_dri) { - source_set("dri") { - sources = [ - "ozone_platform_dri.cc", - "ozone_platform_dri.h", - ] - - deps = [ - ":dri_common", - "//base", - "//skia", - "//ui/events/ozone:events_ozone_evdev", - ] - } - - source_set("dri_unittests") { - testonly = true - sources = [ - "dri_surface_factory_unittest.cc", - "dri_surface_unittest.cc", - "hardware_display_controller_unittest.cc", - "screen_manager_unittest.cc", - "test/mock_dri_wrapper.cc", - "test/mock_dri_wrapper.h", - ] - - deps = [ - ":dri_common", - "//skia", - "//testing/gtest", - ] - } -} - -if (ozone_platform_gbm) { - pkg_config("libgbm") { - packages = [ "gbm" ] - } - - source_set("gbm") { - sources = [ - "gbm_buffer.cc", - "gbm_buffer.h", - "gbm_buffer_base.cc", - "gbm_buffer_base.h", - "gbm_surface.cc", - "gbm_surface.h", - "gbm_surfaceless.cc", - "gbm_surfaceless.h", - "gbm_surface_factory.cc", - "gbm_surface_factory.h", - "native_display_delegate_proxy.cc", - "native_display_delegate_proxy.h", - "ozone_platform_gbm.cc", - "ozone_platform_gbm.h", - ] - - deps = [ - ":dri_common", - "//base", - "//skia", - "//ui/events/ozone:events_ozone_evdev", - ] - - public_configs = [ ":libgbm" ] - } -}
diff --git a/ui/ozone/platform/dri/DEPS b/ui/ozone/platform/dri/DEPS deleted file mode 100644 index 0ab1471..0000000 --- a/ui/ozone/platform/dri/DEPS +++ /dev/null
@@ -1,3 +0,0 @@ -include_rules = [ - "+ui/display/util", -]
diff --git a/ui/ozone/platform/dri/OWNERS b/ui/ozone/platform/dri/OWNERS deleted file mode 100644 index 0d77c0e..0000000 --- a/ui/ozone/platform/dri/OWNERS +++ /dev/null
@@ -1 +0,0 @@ -dnicoara@chromium.org
diff --git a/ui/ozone/platform/dri/channel_observer.h b/ui/ozone/platform/dri/channel_observer.h deleted file mode 100644 index 356a79e..0000000 --- a/ui/ozone/platform/dri/channel_observer.h +++ /dev/null
@@ -1,21 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_CHANNEL_OBSERVER_H_ -#define UI_OZONE_PLATFORM_DRI_CHANNEL_OBSERVER_H_ - -namespace ui { - -// Observes the channel state. -class ChannelObserver { - public: - virtual ~ChannelObserver() {} - - virtual void OnChannelEstablished() = 0; - virtual void OnChannelDestroyed() = 0; -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_CHANNEL_OBSERVER_H_
diff --git a/ui/ozone/platform/dri/crtc_controller.cc b/ui/ozone/platform/dri/crtc_controller.cc deleted file mode 100644 index f605e5f..0000000 --- a/ui/ozone/platform/dri/crtc_controller.cc +++ /dev/null
@@ -1,139 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/dri/crtc_controller.h" - -#include "base/logging.h" -#include "base/time/time.h" -#include "ui/ozone/platform/dri/dri_wrapper.h" -#include "ui/ozone/platform/dri/scanout_buffer.h" - -namespace ui { - -CrtcController::CrtcController(DriWrapper* drm, - uint32_t crtc, - uint32_t connector) - : drm_(drm), - crtc_(crtc), - connector_(connector), - saved_crtc_(drm->GetCrtc(crtc)), - is_disabled_(true), - page_flip_pending_(false), - time_of_last_flip_(0) { -} - -CrtcController::~CrtcController() { - if (!is_disabled_) { - drm_->SetCrtc(saved_crtc_.get(), std::vector<uint32_t>(1, connector_)); - UnsetCursor(); - } -} - -bool CrtcController::Modeset(const OverlayPlane& plane, drmModeModeInfo mode) { - if (!drm_->SetCrtc(crtc_, - plane.buffer->GetFramebufferId(), - std::vector<uint32_t>(1, connector_), - &mode)) { - LOG(ERROR) << "Failed to modeset: error='" << strerror(errno) - << "' crtc=" << crtc_ << " connector=" << connector_ - << " framebuffer_id=" << plane.buffer->GetFramebufferId() - << " mode=" << mode.hdisplay << "x" << mode.vdisplay << "@" - << mode.vrefresh; - return false; - } - - current_planes_ = std::vector<OverlayPlane>(1, plane); - mode_ = mode; - pending_planes_.clear(); - is_disabled_ = false; - page_flip_pending_ = false; - - return true; -} - -bool CrtcController::Disable() { - if (is_disabled_) - return true; - - is_disabled_ = true; - page_flip_pending_ = false; - return drm_->DisableCrtc(crtc_); -} - -bool CrtcController::SchedulePageFlip(const OverlayPlaneList& overlays) { - DCHECK(!page_flip_pending_); - DCHECK(!is_disabled_); - const OverlayPlane& primary = OverlayPlane::GetPrimaryPlane(overlays); - DCHECK(primary.buffer.get()); - - if (primary.buffer->GetSize() != gfx::Size(mode_.hdisplay, mode_.vdisplay)) { - LOG(WARNING) << "Trying to pageflip a buffer with the wrong size. Expected " - << mode_.hdisplay << "x" << mode_.vdisplay << " got " - << primary.buffer->GetSize().ToString() << " for" - << " crtc=" << crtc_ << " connector=" << connector_; - return true; - } - - if (!drm_->PageFlip(crtc_, primary.buffer->GetFramebufferId(), this)) { - LOG(ERROR) << "Cannot page flip: error='" << strerror(errno) << "'" - << " crtc=" << crtc_ - << " framebuffer=" << primary.buffer->GetFramebufferId() - << " size=" << primary.buffer->GetSize().ToString(); - return false; - } - - page_flip_pending_ = true; - pending_planes_ = overlays; - - for (size_t i = 0; i < overlays.size(); i++) { - const OverlayPlane& plane = overlays[i]; - if (!plane.overlay_plane) - continue; - - const gfx::Size& size = plane.buffer->GetSize(); - gfx::RectF crop_rect = plane.crop_rect; - crop_rect.Scale(size.width(), size.height()); - if (!drm_->PageFlipOverlay(crtc_, - plane.buffer->GetFramebufferId(), - plane.display_bounds, - crop_rect, - plane.overlay_plane)) { - LOG(ERROR) << "Cannot display on overlay: " << strerror(errno); - return false; - } - } - - return true; -} - -void CrtcController::OnPageFlipEvent(unsigned int frame, - unsigned int seconds, - unsigned int useconds) { - page_flip_pending_ = false; - time_of_last_flip_ = - static_cast<uint64_t>(seconds) * base::Time::kMicrosecondsPerSecond + - useconds; - - current_planes_.clear(); - current_planes_.swap(pending_planes_); -} - -bool CrtcController::SetCursor(const scoped_refptr<ScanoutBuffer>& buffer) { - DCHECK(!is_disabled_); - cursor_buffer_ = buffer; - return drm_->SetCursor(crtc_, buffer->GetHandle(), buffer->GetSize()); -} - -bool CrtcController::UnsetCursor() { - bool state = drm_->SetCursor(crtc_, 0, gfx::Size()); - cursor_buffer_ = NULL; - return state; -} - -bool CrtcController::MoveCursor(const gfx::Point& location) { - DCHECK(!is_disabled_); - return drm_->MoveCursor(crtc_, location); -} - -} // namespace ui
diff --git a/ui/ozone/platform/dri/crtc_controller.h b/ui/ozone/platform/dri/crtc_controller.h deleted file mode 100644 index eefe926..0000000 --- a/ui/ozone/platform/dri/crtc_controller.h +++ /dev/null
@@ -1,96 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_CRTC_CONTROLLER_H_ -#define UI_OZONE_PLATFORM_DRI_CRTC_CONTROLLER_H_ - -#include <stddef.h> -#include <stdint.h> -#include <xf86drmMode.h> - -#include "ui/ozone/platform/dri/overlay_plane.h" -#include "ui/ozone/platform/dri/scoped_drm_types.h" - -namespace ui { - -class DriWrapper; - -// Wrapper around a CRTC. -// -// One CRTC can be paired up with one or more connectors. The simplest -// configuration represents one CRTC driving one monitor, while pairing up a -// CRTC with multiple connectors results in hardware mirroring. -class CrtcController { - public: - CrtcController(DriWrapper* drm, uint32_t crtc, uint32_t connector); - ~CrtcController(); - - uint32_t crtc() const { return crtc_; } - uint32_t connector() const { return connector_; } - DriWrapper* drm() const { return drm_; } - bool is_disabled() const { return is_disabled_; } - bool page_flip_pending() const { return page_flip_pending_; } - uint64_t time_of_last_flip() const { return time_of_last_flip_; } - - // Perform the initial modesetting operation using |plane| as the buffer for - // the primary plane. The CRTC configuration is specified by |mode|. - bool Modeset(const OverlayPlane& plane, drmModeModeInfo mode); - - // Disables the controller. - bool Disable(); - - // Schedule a page flip event and present the overlays in |planes|. - bool SchedulePageFlip(const OverlayPlaneList& planes); - - // Called when the page flip event occurred. The event is provided by the - // kernel when a VBlank event finished. This allows the controller to - // update internal state and propagate the update to the surface. - // The tuple (seconds, useconds) represents the event timestamp. |seconds| - // represents the number of seconds while |useconds| represents the - // microseconds (< 1 second) in the timestamp. - void OnPageFlipEvent(unsigned int frame, - unsigned int seconds, - unsigned int useconds); - - bool SetCursor(const scoped_refptr<ScanoutBuffer>& buffer); - bool UnsetCursor(); - bool MoveCursor(const gfx::Point& location); - - private: - DriWrapper* drm_; // Not owned. - - // Buffers need to be declared first so that they are destroyed last. Needed - // since the controllers may reference the buffers. - OverlayPlaneList current_planes_; - OverlayPlaneList pending_planes_; - scoped_refptr<ScanoutBuffer> cursor_buffer_; - - uint32_t crtc_; - - // TODO(dnicoara) Add support for hardware mirroring (multiple connectors). - uint32_t connector_; - - drmModeModeInfo mode_; - - // Store the state of the CRTC before we took over. Used to restore the CRTC - // once we no longer need it. - ScopedDrmCrtcPtr saved_crtc_; - - // Keeps track of the CRTC state. If a surface has been bound, then the value - // is set to false. Otherwise it is true. - bool is_disabled_; - - // True if a successful SchedulePageFlip occurred. Reset to false by a modeset - // operation or when the OnPageFlipEvent callback is triggered. - bool page_flip_pending_; - - // The time of the last page flip event as reported by the kernel callback. - uint64_t time_of_last_flip_; - - DISALLOW_COPY_AND_ASSIGN(CrtcController); -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_CRTC_CONTROLLER_H_
diff --git a/ui/ozone/platform/dri/display_mode_dri.cc b/ui/ozone/platform/dri/display_mode_dri.cc deleted file mode 100644 index 6dd660c..0000000 --- a/ui/ozone/platform/dri/display_mode_dri.cc +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/dri/display_mode_dri.h" - -namespace ui { - -DisplayModeDri::DisplayModeDri(const drmModeModeInfo& mode) - : DisplayMode(gfx::Size(mode.hdisplay, mode.vdisplay), - mode.flags & DRM_MODE_FLAG_INTERLACE, - mode.vrefresh), - mode_info_(mode) { -} - -DisplayModeDri::~DisplayModeDri() { -} - -} // namespace ui
diff --git a/ui/ozone/platform/dri/display_mode_dri.h b/ui/ozone/platform/dri/display_mode_dri.h deleted file mode 100644 index c23c339..0000000 --- a/ui/ozone/platform/dri/display_mode_dri.h +++ /dev/null
@@ -1,33 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_DISPLAY_MODE_DRI_H_ -#define UI_OZONE_PLATFORM_DRI_DISPLAY_MODE_DRI_H_ - -#include <stdint.h> -#include <stdlib.h> -#include <xf86drmMode.h> - -#include "ui/display/types/display_mode.h" - -namespace ui { - -class DisplayModeDri : public DisplayMode { - public: - DisplayModeDri(const drmModeModeInfo& mode); - virtual ~DisplayModeDri(); - - // Native details about this mode. Only used internally in the DRI - // implementation. - drmModeModeInfo mode_info() const { return mode_info_; } - - private: - drmModeModeInfo mode_info_; - - DISALLOW_COPY_AND_ASSIGN(DisplayModeDri); -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_DISPLAY_MODE_DRI_H_
diff --git a/ui/ozone/platform/dri/display_snapshot_dri.cc b/ui/ozone/platform/dri/display_snapshot_dri.cc deleted file mode 100644 index 0d0c559..0000000 --- a/ui/ozone/platform/dri/display_snapshot_dri.cc +++ /dev/null
@@ -1,132 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/dri/display_snapshot_dri.h" - -#include <stdint.h> -#include <stdlib.h> -#include <xf86drmMode.h> - -#include "base/format_macros.h" -#include "base/logging.h" -#include "base/strings/stringprintf.h" -#include "ui/display/util/edid_parser.h" -#include "ui/ozone/platform/dri/display_mode_dri.h" -#include "ui/ozone/platform/dri/dri_util.h" -#include "ui/ozone/platform/dri/dri_wrapper.h" - -namespace ui { - -namespace { - -DisplayConnectionType GetDisplayType(drmModeConnector* connector) { - switch (connector->connector_type) { - case DRM_MODE_CONNECTOR_VGA: - return DISPLAY_CONNECTION_TYPE_VGA; - case DRM_MODE_CONNECTOR_DVII: - case DRM_MODE_CONNECTOR_DVID: - case DRM_MODE_CONNECTOR_DVIA: - return DISPLAY_CONNECTION_TYPE_DVI; - case DRM_MODE_CONNECTOR_LVDS: - case DRM_MODE_CONNECTOR_eDP: - return DISPLAY_CONNECTION_TYPE_INTERNAL; - case DRM_MODE_CONNECTOR_DisplayPort: - return DISPLAY_CONNECTION_TYPE_DISPLAYPORT; - case DRM_MODE_CONNECTOR_HDMIA: - case DRM_MODE_CONNECTOR_HDMIB: - return DISPLAY_CONNECTION_TYPE_HDMI; - default: - return DISPLAY_CONNECTION_TYPE_UNKNOWN; - } -} - -bool IsAspectPreserving(DriWrapper* drm, drmModeConnector* connector) { - ScopedDrmPropertyPtr property(drm->GetProperty(connector, "scaling mode")); - if (!property) - return false; - - for (int props_i = 0; props_i < connector->count_props; ++props_i) { - if (connector->props[props_i] != property->prop_id) - continue; - - for (int enums_i = 0; enums_i < property->count_enums; ++enums_i) { - if (property->enums[enums_i].value == connector->prop_values[props_i] && - strcmp(property->enums[enums_i].name, "Full aspect") == 0) - return true; - } - } - - return false; -} - -} // namespace - -DisplaySnapshotDri::DisplaySnapshotDri(DriWrapper* drm, - drmModeConnector* connector, - drmModeCrtc* crtc, - uint32_t index) - : DisplaySnapshot(index, - false, - gfx::Point(crtc->x, crtc->y), - gfx::Size(connector->mmWidth, connector->mmHeight), - GetDisplayType(connector), - IsAspectPreserving(drm, connector), - false, - std::string(), - std::vector<const DisplayMode*>(), - NULL, - NULL), - connector_(connector->connector_id), - crtc_(crtc->crtc_id), - dpms_property_(drm->GetProperty(connector, "DPMS")) { - if (!dpms_property_) - VLOG(1) << "Failed to find the DPMS property for connector " - << connector->connector_id; - - ScopedDrmPropertyBlobPtr edid_blob(drm->GetPropertyBlob(connector, "EDID")); - - if (edid_blob) { - std::vector<uint8_t> edid( - static_cast<uint8_t*>(edid_blob->data), - static_cast<uint8_t*>(edid_blob->data) + edid_blob->length); - - has_proper_display_id_ = GetDisplayIdFromEDID(edid, index, &display_id_); - ParseOutputDeviceData(edid, NULL, &display_name_); - ParseOutputOverscanFlag(edid, &overscan_flag_); - } else { - VLOG(1) << "Failed to get EDID blob for connector " - << connector->connector_id; - } - - for (int i = 0; i < connector->count_modes; ++i) { - drmModeModeInfo& mode = connector->modes[i]; - modes_.push_back(new DisplayModeDri(mode)); - - if (crtc->mode_valid && SameMode(crtc->mode, mode)) - current_mode_ = modes_.back(); - - if (mode.type & DRM_MODE_TYPE_PREFERRED) - native_mode_ = modes_.back(); - } - - // If no preferred mode is found then use the first one. Using the first one - // since it should be the best mode. - if (!native_mode_ && !modes_.empty()) - native_mode_ = modes_.front(); -} - -DisplaySnapshotDri::~DisplaySnapshotDri() { -} - -std::string DisplaySnapshotDri::ToString() const { - return base::StringPrintf( - "[type=%d, connector=%" PRIu32 ", crtc=%" PRIu32 ", mode=%s, dim=%s]", - type_, - connector_, - crtc_, - current_mode_ ? current_mode_->ToString().c_str() : "NULL", - physical_size_.ToString().c_str()); -} - -} // namespace ui
diff --git a/ui/ozone/platform/dri/display_snapshot_dri.h b/ui/ozone/platform/dri/display_snapshot_dri.h deleted file mode 100644 index 5c13188..0000000 --- a/ui/ozone/platform/dri/display_snapshot_dri.h +++ /dev/null
@@ -1,44 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_DISPLAY_SNAPSHOT_DRI_H_ -#define UI_OZONE_PLATFORM_DRI_DISPLAY_SNAPSHOT_DRI_H_ - -#include "ui/display/types/display_snapshot.h" -#include "ui/ozone/platform/dri/scoped_drm_types.h" - -namespace ui { - -class DriWrapper; - -class DisplaySnapshotDri : public DisplaySnapshot { - public: - DisplaySnapshotDri(DriWrapper* drm, - drmModeConnector* connector, - drmModeCrtc* crtc, - uint32_t index); - virtual ~DisplaySnapshotDri(); - - // Native properties of a display used by the DRI implementation in - // configuring this display. - uint32_t connector() const { return connector_; } - uint32_t crtc() const { return crtc_; } - drmModePropertyRes* dpms_property() const { return dpms_property_.get(); } - - // DisplaySnapshot overrides: - virtual std::string ToString() const override; - - private: - uint32_t connector_; - uint32_t crtc_; - ScopedDrmPropertyPtr dpms_property_; - std::string name_; - bool overscan_flag_; - - DISALLOW_COPY_AND_ASSIGN(DisplaySnapshotDri); -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_DISPLAY_SNAPSHOT_DRI_H_
diff --git a/ui/ozone/platform/dri/dri.gypi b/ui/ozone/platform/dri/dri.gypi deleted file mode 100644 index 9f7f2bd..0000000 --- a/ui/ozone/platform/dri/dri.gypi +++ /dev/null
@@ -1,127 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -{ - 'variables': { - 'internal_ozone_platform_deps': [ - 'ozone_platform_dri', - ], - 'internal_ozone_platform_unittest_deps': [ - 'ozone_platform_dri_unittests', - ], - 'internal_ozone_platforms': [ - 'dri', - ], - 'use_drm_atomic_flip%': 0, - }, - 'targets': [ - { - 'target_name': 'ozone_platform_dri', - 'type': 'static_library', - 'dependencies': [ - '../../base/base.gyp:base', - '../../build/linux/system.gyp:libdrm', - '../../skia/skia.gyp:skia', - '../base/ui_base.gyp:ui_base', - '../display/display.gyp:display_types', - '../display/display.gyp:display_util', - '../events/events.gyp:events', - '../events/ozone/events_ozone.gyp:events_ozone_evdev', - '../gfx/gfx.gyp:gfx', - '../gfx/gfx.gyp:gfx_geometry', - ], - 'defines': [ - 'OZONE_IMPLEMENTATION', - ], - 'sources': [ - 'channel_observer.h', - 'crtc_controller.cc', - 'crtc_controller.h', - 'display_mode_dri.cc', - 'display_mode_dri.h', - 'display_snapshot_dri.cc', - 'display_snapshot_dri.h', - 'dri_console_buffer.cc', - 'dri_console_buffer.h', - 'dri_buffer.cc', - 'dri_buffer.h', - 'dri_cursor.cc', - 'dri_cursor.h', - 'dri_gpu_platform_support.cc', - 'dri_gpu_platform_support.h', - 'dri_gpu_platform_support_host.cc', - 'dri_gpu_platform_support_host.h', - 'dri_surface.cc', - 'dri_surface.h', - 'dri_surface_factory.cc', - 'dri_surface_factory.h', - 'dri_util.cc', - 'dri_util.h', - 'dri_vsync_provider.cc', - 'dri_vsync_provider.h', - 'dri_window.cc', - 'dri_window.h', - 'dri_window_delegate.h', - 'dri_window_delegate_impl.cc', - 'dri_window_delegate_impl.h', - 'dri_window_delegate_manager.cc', - 'dri_window_delegate_manager.h', - 'dri_window_manager.cc', - 'dri_window_manager.h', - 'dri_wrapper.cc', - 'dri_wrapper.h', - 'hardware_display_controller.cc', - 'hardware_display_controller.h', - 'native_display_delegate_dri.cc', - 'native_display_delegate_dri.h', - 'overlay_plane.cc', - 'overlay_plane.h', - 'ozone_platform_dri.cc', - 'ozone_platform_dri.h', - 'scoped_drm_types.cc', - 'scoped_drm_types.h', - 'screen_manager.cc', - 'screen_manager.h', - 'scanout_buffer.h', - 'virtual_terminal_manager.cc', - 'virtual_terminal_manager.h', - ], - 'conditions': [ - ['use_drm_atomic_flip==1', { - 'sources': [ - 'hardware_display_plane.cc', - 'hardware_display_plane.h', - 'hardware_display_plane_manager.cc', - 'hardware_display_plane_manager.h', - ], - }], - ], - }, - { - 'target_name': 'ozone_platform_dri_unittests', - 'type': 'none', - 'dependencies': [ - '../../build/linux/system.gyp:libdrm', - '../../skia/skia.gyp:skia', - '../gfx/gfx.gyp:gfx_geometry', - 'ozone_platform_dri', - ], - 'export_dependent_settings': [ - '../../build/linux/system.gyp:libdrm', - '../../skia/skia.gyp:skia', - '../gfx/gfx.gyp:gfx_geometry', - ], - 'direct_dependent_settings': { - 'sources': [ - 'dri_surface_factory_unittest.cc', - 'dri_surface_unittest.cc', - 'hardware_display_controller_unittest.cc', - 'screen_manager_unittest.cc', - 'test/mock_dri_wrapper.cc', - 'test/mock_dri_wrapper.h', - ], - }, - }, - ], -}
diff --git a/ui/ozone/platform/dri/dri_buffer.cc b/ui/ozone/platform/dri/dri_buffer.cc deleted file mode 100644 index 4a35395..0000000 --- a/ui/ozone/platform/dri/dri_buffer.cc +++ /dev/null
@@ -1,111 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/dri/dri_buffer.h" - -#include "base/logging.h" -#include "ui/ozone/platform/dri/dri_wrapper.h" - -namespace ui { - -namespace { - -// Modesetting cannot happen from a buffer with transparencies. Return the size -// of a pixel without alpha. -uint8_t GetColorDepth(SkColorType type) { - switch (type) { - case kUnknown_SkColorType: - case kAlpha_8_SkColorType: - return 0; - case kIndex_8_SkColorType: - return 8; - case kRGB_565_SkColorType: - return 16; - case kARGB_4444_SkColorType: - return 12; - case kN32_SkColorType: - return 24; - default: - NOTREACHED(); - return 0; - } -} - -} // namespace - -DriBuffer::DriBuffer(DriWrapper* dri) - : dri_(dri), handle_(0), framebuffer_(0) {} - -DriBuffer::~DriBuffer() { - if (!surface_) - return; - - if (framebuffer_) - dri_->RemoveFramebuffer(framebuffer_); - - SkImageInfo info; - void* pixels = const_cast<void*>(surface_->peekPixels(&info, NULL)); - if (!pixels) - return; - - dri_->DestroyDumbBuffer(info, handle_, stride_, pixels); -} - -bool DriBuffer::Initialize(const SkImageInfo& info) { - void* pixels = NULL; - if (!dri_->CreateDumbBuffer(info, &handle_, &stride_, &pixels)) { - VLOG(2) << "Cannot create drm dumb buffer"; - return false; - } - - if (!dri_->AddFramebuffer(info.width(), - info.height(), - GetColorDepth(info.colorType()), - info.bytesPerPixel() << 3, - stride_, - handle_, - &framebuffer_)) { - VLOG(2) << "Failed to register framebuffer: " << strerror(errno); - return false; - } - - surface_ = skia::AdoptRef(SkSurface::NewRasterDirect(info, pixels, stride_)); - if (!surface_) { - VLOG(2) << "Cannot install Skia pixels for drm buffer"; - return false; - } - - return true; -} - -SkCanvas* DriBuffer::GetCanvas() const { - return surface_->getCanvas(); -} - -uint32_t DriBuffer::GetFramebufferId() const { - return framebuffer_; -} - -uint32_t DriBuffer::GetHandle() const { - return handle_; -} - -gfx::Size DriBuffer::GetSize() const { - return gfx::Size(surface_->width(), surface_->height()); -} - -DriBufferGenerator::DriBufferGenerator(DriWrapper* dri) : dri_(dri) {} - -DriBufferGenerator::~DriBufferGenerator() {} - -scoped_refptr<ScanoutBuffer> DriBufferGenerator::Create(const gfx::Size& size) { - scoped_refptr<DriBuffer> buffer(new DriBuffer(dri_)); - SkImageInfo info = SkImageInfo::MakeN32Premul(size.width(), size.height()); - if (!buffer->Initialize(info)) - return NULL; - - return buffer; -} - -} // namespace ui
diff --git a/ui/ozone/platform/dri/dri_buffer.h b/ui/ozone/platform/dri/dri_buffer.h deleted file mode 100644 index 773860f..0000000 --- a/ui/ozone/platform/dri/dri_buffer.h +++ /dev/null
@@ -1,72 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_DRI_BUFFER_H_ -#define UI_OZONE_PLATFORM_DRI_DRI_BUFFER_H_ - -#include "base/macros.h" -#include "skia/ext/refptr.h" -#include "third_party/skia/include/core/SkSurface.h" -#include "ui/ozone/platform/dri/scanout_buffer.h" - -namespace ui { - -class DriWrapper; - -// Wrapper for a DRM allocated buffer. Keeps track of the native properties of -// the buffer and wraps the pixel memory into a SkSurface which can be used to -// draw into using Skia. -class DriBuffer : public ScanoutBuffer { - public: - DriBuffer(DriWrapper* dri); - - // Allocates the backing pixels and wraps them in |surface_|. |info| is used - // to describe the buffer characteristics (size, color format). - bool Initialize(const SkImageInfo& info); - - SkCanvas* GetCanvas() const; - - // ScanoutBuffer: - virtual uint32_t GetFramebufferId() const override; - virtual uint32_t GetHandle() const override; - virtual gfx::Size GetSize() const override; - - protected: - virtual ~DriBuffer(); - - DriWrapper* dri_; // Not owned. - - // Wrapper around the native pixel memory. - skia::RefPtr<SkSurface> surface_; - - // Length of a row of pixels. - uint32_t stride_; - - // Buffer handle used by the DRM allocator. - uint32_t handle_; - - // Buffer ID used by the DRM modesettings API. This is set when the buffer is - // registered with the CRTC. - uint32_t framebuffer_; - - DISALLOW_COPY_AND_ASSIGN(DriBuffer); -}; - -class DriBufferGenerator : public ScanoutBufferGenerator { - public: - DriBufferGenerator(DriWrapper* dri); - virtual ~DriBufferGenerator(); - - // ScanoutBufferGenerator: - virtual scoped_refptr<ScanoutBuffer> Create(const gfx::Size& size) override; - - private: - DriWrapper* dri_; // Not owned. - - DISALLOW_COPY_AND_ASSIGN(DriBufferGenerator); -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_DRI_BUFFER_H_
diff --git a/ui/ozone/platform/dri/dri_console_buffer.cc b/ui/ozone/platform/dri/dri_console_buffer.cc deleted file mode 100644 index 6c1f7a9..0000000 --- a/ui/ozone/platform/dri/dri_console_buffer.cc +++ /dev/null
@@ -1,56 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/dri/dri_console_buffer.h" - -#include <sys/mman.h> -#include <xf86drmMode.h> - -#include "third_party/skia/include/core/SkCanvas.h" -#include "ui/ozone/platform/dri/dri_util.h" -#include "ui/ozone/platform/dri/dri_wrapper.h" -#include "ui/ozone/platform/dri/scoped_drm_types.h" - -namespace ui { - -DriConsoleBuffer::DriConsoleBuffer(DriWrapper* dri, uint32_t framebuffer) - : dri_(dri), - handle_(0), - framebuffer_(framebuffer), - mmap_base_(NULL), - mmap_size_(0) { -} - -DriConsoleBuffer::~DriConsoleBuffer() { - if (mmap_base_) - if (munmap(mmap_base_, mmap_size_)) - PLOG(ERROR) << "munmap"; -} - -bool DriConsoleBuffer::Initialize() { - ScopedDrmFramebufferPtr fb(dri_->GetFramebuffer(framebuffer_)); - - if (!fb) - return false; - - handle_ = fb->handle; - stride_ = fb->pitch; - SkImageInfo info = SkImageInfo::MakeN32Premul(fb->width, fb->height); - - mmap_size_ = info.getSafeSize(stride_); - - if (!MapDumbBuffer(dri_->get_fd(), fb->handle, mmap_size_, &mmap_base_)) { - mmap_base_ = NULL; - return false; - } - - surface_ = - skia::AdoptRef(SkSurface::NewRasterDirect(info, mmap_base_, stride_)); - if (!surface_) - return false; - - return true; -} - -} // namespace ui
diff --git a/ui/ozone/platform/dri/dri_console_buffer.h b/ui/ozone/platform/dri/dri_console_buffer.h deleted file mode 100644 index 51cb4ad..0000000 --- a/ui/ozone/platform/dri/dri_console_buffer.h +++ /dev/null
@@ -1,58 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_DRI_CONSOLE_BUFFER_H_ -#define UI_OZONE_PLATFORM_DRI_DRI_CONSOLE_BUFFER_H_ - -#include "base/macros.h" -#include "skia/ext/refptr.h" -#include "third_party/skia/include/core/SkSurface.h" - -class SkCanvas; - -namespace ui { - -class DriWrapper; - -// Wrapper for the console buffer. This is the buffer that is allocated by -// default by the system and is used when no application is controlling the -// CRTC. Keeps track of the native properties of the buffer and wraps the pixel -// memory into a SkSurface which can be used to draw into using Skia. -class DriConsoleBuffer { - public: - DriConsoleBuffer(DriWrapper* dri, uint32_t framebuffer); - ~DriConsoleBuffer(); - - SkCanvas* canvas() { return surface_->getCanvas(); } - - // Memory map the backing pixels and wrap them in |surface_|. - bool Initialize(); - - protected: - DriWrapper* dri_; // Not owned. - - // Wrapper around the native pixel memory. - skia::RefPtr<SkSurface> surface_; - - // Length of a row of pixels. - uint32_t stride_; - - // Buffer handle used by the DRM allocator. - uint32_t handle_; - - // Buffer ID used by the DRM modesettings API. - uint32_t framebuffer_; - - // Memory map base address. - void* mmap_base_; - - // Memory map size. - size_t mmap_size_; - - DISALLOW_COPY_AND_ASSIGN(DriConsoleBuffer); -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_DRI_CONSOLE_BUFFER_H_
diff --git a/ui/ozone/platform/dri/dri_cursor.cc b/ui/ozone/platform/dri/dri_cursor.cc deleted file mode 100644 index 308541b..0000000 --- a/ui/ozone/platform/dri/dri_cursor.cc +++ /dev/null
@@ -1,99 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/dri/dri_cursor.h" - -#include "ui/base/cursor/ozone/bitmap_cursor_factory_ozone.h" -#include "ui/gfx/geometry/point.h" -#include "ui/gfx/geometry/point_conversions.h" -#include "ui/gfx/geometry/point_f.h" -#include "ui/ozone/platform/dri/dri_surface_factory.h" -#include "ui/ozone/platform/dri/dri_window.h" -#include "ui/ozone/platform/dri/dri_window_manager.h" -#include "ui/ozone/platform/dri/hardware_cursor_delegate.h" - -namespace ui { - -DriCursor::DriCursor(HardwareCursorDelegate* hardware, - DriWindowManager* window_manager) - : hardware_(hardware), - window_manager_(window_manager), - cursor_window_(gfx::kNullAcceleratedWidget) { -} - -DriCursor::~DriCursor() { -} - -void DriCursor::SetCursor(gfx::AcceleratedWidget widget, - PlatformCursor platform_cursor) { - DCHECK_NE(widget, gfx::kNullAcceleratedWidget); - scoped_refptr<BitmapCursorOzone> cursor = - BitmapCursorFactoryOzone::GetBitmapCursor(platform_cursor); - if (cursor_ == cursor || cursor_window_ != widget) - return; - - cursor_ = cursor; - ShowCursor(); -} - -void DriCursor::ShowCursor() { - DCHECK_NE(cursor_window_, gfx::kNullAcceleratedWidget); - if (cursor_.get()) - hardware_->SetHardwareCursor(cursor_window_, - cursor_->bitmaps(), - bitmap_location(), - cursor_->frame_delay_ms()); - else - HideCursor(); -} - -void DriCursor::HideCursor() { - DCHECK_NE(cursor_window_, gfx::kNullAcceleratedWidget); - hardware_->SetHardwareCursor( - cursor_window_, std::vector<SkBitmap>(), gfx::Point(), 0); -} - -void DriCursor::MoveCursorTo(gfx::AcceleratedWidget widget, - const gfx::PointF& location) { - if (widget != cursor_window_ && cursor_window_ != gfx::kNullAcceleratedWidget) - HideCursor(); - - cursor_window_ = widget; - cursor_location_ = location; - - if (cursor_window_ == gfx::kNullAcceleratedWidget) - return; - - DriWindow* window = window_manager_->GetWindow(cursor_window_); - const gfx::Size& size = window->GetBounds().size(); - cursor_location_.SetToMax(gfx::PointF(0, 0)); - // Right and bottom edges are exclusive. - cursor_location_.SetToMin(gfx::PointF(size.width() - 1, size.height() - 1)); - - if (cursor_.get()) - hardware_->MoveHardwareCursor(cursor_window_, bitmap_location()); -} - -void DriCursor::MoveCursor(const gfx::Vector2dF& delta) { - MoveCursorTo(cursor_window_, cursor_location_ + delta); -} - -gfx::AcceleratedWidget DriCursor::GetCursorWindow() { - return cursor_window_; -} - -bool DriCursor::IsCursorVisible() { - return cursor_.get(); -} - -gfx::PointF DriCursor::location() { - return cursor_location_; -} - -gfx::Point DriCursor::bitmap_location() { - return gfx::ToFlooredPoint(cursor_location_) - - cursor_->hotspot().OffsetFromOrigin(); -} - -} // namespace ui
diff --git a/ui/ozone/platform/dri/dri_cursor.h b/ui/ozone/platform/dri/dri_cursor.h deleted file mode 100644 index f13abef..0000000 --- a/ui/ozone/platform/dri/dri_cursor.h +++ /dev/null
@@ -1,64 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_DRI_CURSOR_H_ -#define UI_OZONE_PLATFORM_DRI_DRI_CURSOR_H_ - -#include "base/memory/ref_counted.h" -#include "ui/base/cursor/cursor.h" -#include "ui/events/ozone/evdev/cursor_delegate_evdev.h" -#include "ui/gfx/native_widget_types.h" - -namespace gfx { -class PointF; -class Vector2dF; -} - -namespace ui { - -class BitmapCursorOzone; -class BitmapCursorFactoryOzone; -class DriWindowManager; -class HardwareCursorDelegate; - -class DriCursor : public CursorDelegateEvdev { - public: - explicit DriCursor(HardwareCursorDelegate* hardware, - DriWindowManager* window_manager); - virtual ~DriCursor(); - - void SetCursor(gfx::AcceleratedWidget widget, PlatformCursor platform_cursor); - void ShowCursor(); - void HideCursor(); - gfx::AcceleratedWidget GetCursorWindow(); - - // CursorDelegateEvdev: - virtual void MoveCursorTo(gfx::AcceleratedWidget widget, - const gfx::PointF& location) override; - virtual void MoveCursor(const gfx::Vector2dF& delta) override; - virtual bool IsCursorVisible() override; - virtual gfx::PointF location() override; - - private: - // The location of the bitmap (the cursor location is the hotspot location). - gfx::Point bitmap_location(); - - // The DRI implementation for setting the hardware cursor. - HardwareCursorDelegate* hardware_; - - DriWindowManager* window_manager_; // Not owned. - - // The current cursor bitmap. - scoped_refptr<BitmapCursorOzone> cursor_; - - // The window under the cursor. - gfx::AcceleratedWidget cursor_window_; - - // The location of the cursor within the window. - gfx::PointF cursor_location_; -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_DRI_CURSOR_H_
diff --git a/ui/ozone/platform/dri/dri_gpu_platform_support.cc b/ui/ozone/platform/dri/dri_gpu_platform_support.cc deleted file mode 100644 index 4a19469..0000000 --- a/ui/ozone/platform/dri/dri_gpu_platform_support.cc +++ /dev/null
@@ -1,207 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/dri/dri_gpu_platform_support.h" - -#include "ipc/ipc_message_macros.h" -#include "ui/display/types/display_mode.h" -#include "ui/display/types/display_snapshot.h" -#include "ui/ozone/common/display_util.h" -#include "ui/ozone/common/gpu/ozone_gpu_message_params.h" -#include "ui/ozone/common/gpu/ozone_gpu_messages.h" -#include "ui/ozone/platform/dri/dri_surface_factory.h" -#include "ui/ozone/platform/dri/dri_window_delegate_impl.h" -#include "ui/ozone/platform/dri/dri_window_delegate_manager.h" -#include "ui/ozone/platform/dri/native_display_delegate_dri.h" - -namespace ui { - -namespace { - -class FindDisplayById { - public: - FindDisplayById(int64_t display_id) : display_id_(display_id) {} - - bool operator()(const DisplaySnapshot_Params& display) const { - return display.display_id == display_id_; - } - - private: - int64_t display_id_; -}; - -} // namespace - -DriGpuPlatformSupport::DriGpuPlatformSupport( - DriSurfaceFactory* dri, - DriWindowDelegateManager* window_manager, - ScreenManager* screen_manager, - scoped_ptr<NativeDisplayDelegateDri> ndd) - : sender_(NULL), - dri_(dri), - window_manager_(window_manager), - screen_manager_(screen_manager), - ndd_(ndd.Pass()) { -} - -DriGpuPlatformSupport::~DriGpuPlatformSupport() { -} - -void DriGpuPlatformSupport::AddHandler(scoped_ptr<GpuPlatformSupport> handler) { - handlers_.push_back(handler.release()); -} - -void DriGpuPlatformSupport::OnChannelEstablished(IPC::Sender* sender) { - sender_ = sender; - - for (size_t i = 0; i < handlers_.size(); ++i) - handlers_[i]->OnChannelEstablished(sender); -} - -bool DriGpuPlatformSupport::OnMessageReceived(const IPC::Message& message) { - bool handled = true; - - IPC_BEGIN_MESSAGE_MAP(DriGpuPlatformSupport, message) - IPC_MESSAGE_HANDLER(OzoneGpuMsg_CreateWindowDelegate, OnCreateWindowDelegate) - IPC_MESSAGE_HANDLER(OzoneGpuMsg_DestroyWindowDelegate, - OnDestroyWindowDelegate) - IPC_MESSAGE_HANDLER(OzoneGpuMsg_WindowBoundsChanged, OnWindowBoundsChanged) - - IPC_MESSAGE_HANDLER(OzoneGpuMsg_CursorSet, OnCursorSet) - IPC_MESSAGE_HANDLER(OzoneGpuMsg_CursorMove, OnCursorMove) - - IPC_MESSAGE_HANDLER(OzoneGpuMsg_ForceDPMSOn, OnForceDPMSOn) - IPC_MESSAGE_HANDLER(OzoneGpuMsg_RefreshNativeDisplays, - OnRefreshNativeDisplays) - IPC_MESSAGE_HANDLER(OzoneGpuMsg_ConfigureNativeDisplay, - OnConfigureNativeDisplay) - IPC_MESSAGE_HANDLER(OzoneGpuMsg_DisableNativeDisplay, OnDisableNativeDisplay) - IPC_MESSAGE_UNHANDLED(handled = false); - IPC_END_MESSAGE_MAP() - - if (!handled) - for (size_t i = 0; i < handlers_.size(); ++i) - if (handlers_[i]->OnMessageReceived(message)) - return true; - - return false; -} - -void DriGpuPlatformSupport::OnCreateWindowDelegate( - gfx::AcceleratedWidget widget) { - // Due to how the GPU process starts up this IPC call may happen after the IPC - // to create a surface. Since a surface wants to know the window associated - // with it, we create it ahead of time. So when this call happens we do not - // create a delegate if it already exists. - if (!window_manager_->HasWindowDelegate(widget)) { - scoped_ptr<DriWindowDelegate> delegate( - new DriWindowDelegateImpl(widget, screen_manager_)); - delegate->Initialize(); - window_manager_->AddWindowDelegate(widget, delegate.Pass()); - } -} - -void DriGpuPlatformSupport::OnDestroyWindowDelegate( - gfx::AcceleratedWidget widget) { - scoped_ptr<DriWindowDelegate> delegate = - window_manager_->RemoveWindowDelegate(widget); - delegate->Shutdown(); -} - -void DriGpuPlatformSupport::OnWindowBoundsChanged(gfx::AcceleratedWidget widget, - const gfx::Rect& bounds) { - window_manager_->GetWindowDelegate(widget)->OnBoundsChanged(bounds); -} - -void DriGpuPlatformSupport::OnCursorSet(gfx::AcceleratedWidget widget, - const std::vector<SkBitmap>& bitmaps, - const gfx::Point& location, - int frame_delay_ms) { - dri_->SetHardwareCursor(widget, bitmaps, location, frame_delay_ms); -} - -void DriGpuPlatformSupport::OnCursorMove(gfx::AcceleratedWidget widget, - const gfx::Point& location) { - dri_->MoveHardwareCursor(widget, location); -} - -void DriGpuPlatformSupport::OnForceDPMSOn() { - ndd_->ForceDPMSOn(); -} - -void DriGpuPlatformSupport::OnRefreshNativeDisplays( - const std::vector<DisplaySnapshot_Params>& cached_displays) { - std::vector<DisplaySnapshot_Params> displays; - std::vector<DisplaySnapshot*> native_displays = ndd_->GetDisplays(); - - // If any of the cached displays are in the list of new displays then apply - // their configuration immediately. - for (size_t i = 0; i < native_displays.size(); ++i) { - std::vector<DisplaySnapshot_Params>::const_iterator it = - std::find_if(cached_displays.begin(), - cached_displays.end(), - FindDisplayById(native_displays[i]->display_id())); - - if (it == cached_displays.end()) - continue; - - if (it->has_current_mode) - OnConfigureNativeDisplay(it->display_id, it->current_mode, it->origin); - else - OnDisableNativeDisplay(it->display_id); - } - - for (size_t i = 0; i < native_displays.size(); ++i) - displays.push_back(GetDisplaySnapshotParams(*native_displays[i])); - - sender_->Send(new OzoneHostMsg_UpdateNativeDisplays(displays)); -} - -void DriGpuPlatformSupport::OnConfigureNativeDisplay( - int64_t id, - const DisplayMode_Params& mode_param, - const gfx::Point& origin) { - DisplaySnapshot* display = ndd_->FindDisplaySnapshot(id); - if (!display) { - LOG(ERROR) << "There is no display with ID " << id; - return; - } - - const DisplayMode* mode = NULL; - for (size_t i = 0; i < display->modes().size(); ++i) { - if (mode_param.size == display->modes()[i]->size() && - mode_param.is_interlaced == display->modes()[i]->is_interlaced() && - mode_param.refresh_rate == display->modes()[i]->refresh_rate()) { - mode = display->modes()[i]; - break; - } - } - - // If the display doesn't have the mode natively, then lookup the mode from - // other displays and try using it on the current display (some displays - // support panel fitting and they can use different modes even if the mode - // isn't explicitly declared). - if (!mode) - mode = ndd_->FindDisplayMode( - mode_param.size, mode_param.is_interlaced, mode_param.refresh_rate); - - if (!mode) { - LOG(ERROR) << "Failed to find mode: size=" << mode_param.size.ToString() - << " is_interlaced=" << mode_param.is_interlaced - << " refresh_rate=" << mode_param.refresh_rate; - return; - } - - ndd_->Configure(*display, mode, origin); -} - -void DriGpuPlatformSupport::OnDisableNativeDisplay(int64_t id) { - DisplaySnapshot* display = ndd_->FindDisplaySnapshot(id); - if (display) - ndd_->Configure(*display, NULL, gfx::Point()); - else - LOG(ERROR) << "There is no display with ID " << id; -} - -} // namespace ui
diff --git a/ui/ozone/platform/dri/dri_gpu_platform_support.h b/ui/ozone/platform/dri/dri_gpu_platform_support.h deleted file mode 100644 index 259edb7..0000000 --- a/ui/ozone/platform/dri/dri_gpu_platform_support.h +++ /dev/null
@@ -1,79 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_DRI_GPU_PLATFORM_SUPPORT_H_ -#define UI_OZONE_PLATFORM_DRI_DRI_GPU_PLATFORM_SUPPORT_H_ - -#include "base/containers/scoped_ptr_hash_map.h" -#include "base/memory/scoped_ptr.h" -#include "base/memory/scoped_vector.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/ozone/public/gpu_platform_support.h" - -class SkBitmap; - -namespace gfx { -class Point; -class Rect; -} - -namespace ui { - -class DriSurfaceFactory; -class DriWindowDelegate; -class DriWindowDelegateManager; -class NativeDisplayDelegateDri; -class ScreenManager; - -struct DisplayMode_Params; -struct DisplaySnapshot_Params; - -class DriGpuPlatformSupport : public GpuPlatformSupport { - public: - DriGpuPlatformSupport(DriSurfaceFactory* dri, - DriWindowDelegateManager* window_manager, - ScreenManager* screen_manager, - scoped_ptr<NativeDisplayDelegateDri> ndd); - virtual ~DriGpuPlatformSupport(); - - void AddHandler(scoped_ptr<GpuPlatformSupport> handler); - - // GpuPlatformSupport: - virtual void OnChannelEstablished(IPC::Sender* sender) override; - - // IPC::Listener: - virtual bool OnMessageReceived(const IPC::Message& message) override; - - private: - void OnCreateWindowDelegate(gfx::AcceleratedWidget widget); - void OnDestroyWindowDelegate(gfx::AcceleratedWidget widget); - void OnWindowBoundsChanged(gfx::AcceleratedWidget widget, - const gfx::Rect& bounds); - void OnCursorSet(gfx::AcceleratedWidget widget, - const std::vector<SkBitmap>& bitmaps, - const gfx::Point& location, - int frame_delay_ms); - void OnCursorMove(gfx::AcceleratedWidget widget, const gfx::Point& location); - - // Display related IPC handlers. - void OnForceDPMSOn(); - void OnRefreshNativeDisplays( - const std::vector<DisplaySnapshot_Params>& cached_displays); - void OnConfigureNativeDisplay(int64_t id, - const DisplayMode_Params& mode, - const gfx::Point& origin); - void OnDisableNativeDisplay(int64_t id); - - IPC::Sender* sender_; // Not owned. - DriSurfaceFactory* dri_; // Not owned. - DriWindowDelegateManager* window_manager_; // Not owned. - ScreenManager* screen_manager_; // Not owned. - - scoped_ptr<NativeDisplayDelegateDri> ndd_; - ScopedVector<GpuPlatformSupport> handlers_; -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_DRI_GPU_PLATFORM_SUPPORT_H_
diff --git a/ui/ozone/platform/dri/dri_gpu_platform_support_host.cc b/ui/ozone/platform/dri/dri_gpu_platform_support_host.cc deleted file mode 100644 index 287f53d..0000000 --- a/ui/ozone/platform/dri/dri_gpu_platform_support_host.cc +++ /dev/null
@@ -1,118 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/dri/dri_gpu_platform_support_host.h" - -#include "base/debug/trace_event.h" -#include "ui/ozone/common/gpu/ozone_gpu_message_params.h" -#include "ui/ozone/common/gpu/ozone_gpu_messages.h" -#include "ui/ozone/platform/dri/channel_observer.h" - -namespace ui { - -DriGpuPlatformSupportHost::DriGpuPlatformSupportHost() - : host_id_(-1), sender_(NULL) { -} - -DriGpuPlatformSupportHost::~DriGpuPlatformSupportHost() { -} - -bool DriGpuPlatformSupportHost::IsConnected() const { - return sender_ != NULL; -} - -void DriGpuPlatformSupportHost::RegisterHandler( - GpuPlatformSupportHost* handler) { - handlers_.push_back(handler); -} - -void DriGpuPlatformSupportHost::UnregisterHandler( - GpuPlatformSupportHost* handler) { - std::vector<GpuPlatformSupportHost*>::iterator it = - std::find(handlers_.begin(), handlers_.end(), handler); - if (it != handlers_.end()) - handlers_.erase(it); -} - -void DriGpuPlatformSupportHost::AddChannelObserver(ChannelObserver* observer) { - channel_observers_.AddObserver(observer); - - if (sender_) - observer->OnChannelEstablished(); -} - -void DriGpuPlatformSupportHost::RemoveChannelObserver( - ChannelObserver* observer) { - channel_observers_.RemoveObserver(observer); -} - -void DriGpuPlatformSupportHost::OnChannelEstablished(int host_id, - IPC::Sender* sender) { - TRACE_EVENT1("dri", - "DriGpuPlatformSupportHost::OnChannelEstablished", - "host_id", - host_id); - host_id_ = host_id; - sender_ = sender; - - while (!queued_messages_.empty()) { - Send(queued_messages_.front()); - queued_messages_.pop(); - } - - for (size_t i = 0; i < handlers_.size(); ++i) - handlers_[i]->OnChannelEstablished(host_id, sender); - - FOR_EACH_OBSERVER( - ChannelObserver, channel_observers_, OnChannelEstablished()); -} - -void DriGpuPlatformSupportHost::OnChannelDestroyed(int host_id) { - TRACE_EVENT1("dri", - "DriGpuPlatformSupportHost::OnChannelDestroyed", - "host_id", - host_id); - if (host_id_ == host_id) { - host_id_ = -1; - sender_ = NULL; - - FOR_EACH_OBSERVER( - ChannelObserver, channel_observers_, OnChannelDestroyed()); - } - - for (size_t i = 0; i < handlers_.size(); ++i) - handlers_[i]->OnChannelDestroyed(host_id); -} - -bool DriGpuPlatformSupportHost::OnMessageReceived(const IPC::Message& message) { - for (size_t i = 0; i < handlers_.size(); ++i) - if (handlers_[i]->OnMessageReceived(message)) - return true; - - return false; -} - -bool DriGpuPlatformSupportHost::Send(IPC::Message* message) { - if (sender_) - return sender_->Send(message); - - queued_messages_.push(message); - return true; -} - -void DriGpuPlatformSupportHost::SetHardwareCursor( - gfx::AcceleratedWidget widget, - const std::vector<SkBitmap>& bitmaps, - const gfx::Point& location, - int frame_delay_ms) { - Send(new OzoneGpuMsg_CursorSet(widget, bitmaps, location, frame_delay_ms)); -} - -void DriGpuPlatformSupportHost::MoveHardwareCursor( - gfx::AcceleratedWidget widget, - const gfx::Point& location) { - Send(new OzoneGpuMsg_CursorMove(widget, location)); -} - -} // namespace ui
diff --git a/ui/ozone/platform/dri/dri_gpu_platform_support_host.h b/ui/ozone/platform/dri/dri_gpu_platform_support_host.h deleted file mode 100644 index 61d35f0..0000000 --- a/ui/ozone/platform/dri/dri_gpu_platform_support_host.h +++ /dev/null
@@ -1,72 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_DRI_GPU_PLATFORM_SUPPORT_HOST_H_ -#define UI_OZONE_PLATFORM_DRI_DRI_GPU_PLATFORM_SUPPORT_HOST_H_ - -#include <queue> -#include <vector> - -#include "base/observer_list.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/ozone/platform/dri/hardware_cursor_delegate.h" -#include "ui/ozone/public/gpu_platform_support_host.h" - -class SkBitmap; - -namespace gfx { -class Point; -} - -namespace ui { - -class ChannelObserver; - -class DriGpuPlatformSupportHost : public GpuPlatformSupportHost, - public HardwareCursorDelegate, - public IPC::Sender { - public: - DriGpuPlatformSupportHost(); - virtual ~DriGpuPlatformSupportHost(); - - bool IsConnected() const; - - void RegisterHandler(GpuPlatformSupportHost* handler); - void UnregisterHandler(GpuPlatformSupportHost* handler); - - void AddChannelObserver(ChannelObserver* observer); - void RemoveChannelObserver(ChannelObserver* observer); - - // GpuPlatformSupportHost: - virtual void OnChannelEstablished(int host_id, IPC::Sender* sender) override; - virtual void OnChannelDestroyed(int host_id) override; - - // IPC::Listener: - virtual bool OnMessageReceived(const IPC::Message& message) override; - - // IPC::Sender: - virtual bool Send(IPC::Message* message) override; - - // HardwareCursorDelegate: - virtual void SetHardwareCursor(gfx::AcceleratedWidget widget, - const std::vector<SkBitmap>& bitmaps, - const gfx::Point& location, - int frame_delay_ms) override; - virtual void MoveHardwareCursor(gfx::AcceleratedWidget widget, - const gfx::Point& location) override; - - private: - int host_id_; - IPC::Sender* sender_; - std::vector<GpuPlatformSupportHost*> handlers_; - // If messages are sent before the channel is created, store the messages and - // delay sending them until the channel is created. These messages are stored - // in |queued_messaged_|. - std::queue<IPC::Message*> queued_messages_; - ObserverList<ChannelObserver> channel_observers_; -}; - -} // namespace ui - -#endif // UI_OZONE_GPU_DRI_GPU_PLATFORM_SUPPORT_HOST_H_
diff --git a/ui/ozone/platform/dri/dri_surface.cc b/ui/ozone/platform/dri/dri_surface.cc deleted file mode 100644 index 34f2ce2..0000000 --- a/ui/ozone/platform/dri/dri_surface.cc +++ /dev/null
@@ -1,101 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/dri/dri_surface.h" - -#include "base/logging.h" -#include "base/message_loop/message_loop.h" -#include "third_party/skia/include/core/SkCanvas.h" -#include "third_party/skia/include/core/SkSurface.h" -#include "ui/gfx/geometry/rect.h" -#include "ui/gfx/skia_util.h" -#include "ui/ozone/platform/dri/dri_buffer.h" -#include "ui/ozone/platform/dri/dri_vsync_provider.h" -#include "ui/ozone/platform/dri/dri_window_delegate_impl.h" -#include "ui/ozone/platform/dri/dri_wrapper.h" -#include "ui/ozone/platform/dri/hardware_display_controller.h" - -namespace ui { - -namespace { - -scoped_refptr<DriBuffer> AllocateBuffer(DriWrapper* dri, - const gfx::Size& size) { - scoped_refptr<DriBuffer> buffer(new DriBuffer(dri)); - SkImageInfo info = SkImageInfo::MakeN32Premul(size.width(), size.height()); - - bool initialized = buffer->Initialize(info); - DCHECK(initialized) << "Failed to create drm buffer."; - - return buffer; -} - -} // namespace - -DriSurface::DriSurface(DriWindowDelegate* window_delegate, DriWrapper* dri) - : window_delegate_(window_delegate), - dri_(dri), - buffers_(), - front_buffer_(0) { -} - -DriSurface::~DriSurface() { -} - -skia::RefPtr<SkCanvas> DriSurface::GetCanvas() { - return skia::SharePtr(surface_->getCanvas()); -} - -void DriSurface::ResizeCanvas(const gfx::Size& viewport_size) { - SkImageInfo info = SkImageInfo::MakeN32( - viewport_size.width(), viewport_size.height(), kOpaque_SkAlphaType); - surface_ = skia::AdoptRef(SkSurface::NewRaster(info)); - - HardwareDisplayController* controller = window_delegate_->GetController(); - if (!controller) - return; - - // For the display buffers use the mode size since a |viewport_size| smaller - // than the display size will not scanout. - for (size_t i = 0; i < arraysize(buffers_); ++i) - buffers_[i] = AllocateBuffer(dri_, controller->GetModeSize()); -} - -void DriSurface::PresentCanvas(const gfx::Rect& damage) { - DCHECK(base::MessageLoopForUI::IsCurrent()); - DCHECK(buffers_[front_buffer_ ^ 1].get()); - - HardwareDisplayController* controller = window_delegate_->GetController(); - if (!controller) - return; - - controller->QueueOverlayPlane(OverlayPlane(buffers_[front_buffer_ ^ 1])); - - UpdateNativeSurface(damage); - controller->SchedulePageFlip(); - controller->WaitForPageFlipEvent(); - - // Update our front buffer pointer. - front_buffer_ ^= 1; -} - -scoped_ptr<gfx::VSyncProvider> DriSurface::CreateVSyncProvider() { - return scoped_ptr<gfx::VSyncProvider>(new DriVSyncProvider(window_delegate_)); -} - -void DriSurface::UpdateNativeSurface(const gfx::Rect& damage) { - SkCanvas* canvas = buffers_[front_buffer_ ^ 1]->GetCanvas(); - - // The DriSurface is double buffered, so the current back buffer is - // missing the previous update. Expand damage region. - SkRect real_damage = RectToSkRect(UnionRects(damage, last_damage_)); - - // Copy damage region. - skia::RefPtr<SkImage> image = skia::AdoptRef(surface_->newImageSnapshot()); - canvas->drawImageRect(image.get(), &real_damage, real_damage, NULL); - - last_damage_ = damage; -} - -} // namespace ui
diff --git a/ui/ozone/platform/dri/dri_surface.h b/ui/ozone/platform/dri/dri_surface.h deleted file mode 100644 index d3b7807..0000000 --- a/ui/ozone/platform/dri/dri_surface.h +++ /dev/null
@@ -1,58 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_DRI_SURFACE_H_ -#define UI_OZONE_PLATFORM_DRI_DRI_SURFACE_H_ - -#include "base/memory/ref_counted.h" -#include "ui/gfx/geometry/rect.h" -#include "ui/gfx/geometry/size.h" -#include "ui/gfx/skia_util.h" -#include "ui/ozone/public/surface_ozone_canvas.h" - -class SkCanvas; -class SkSurface; - -namespace ui { - -class DriBuffer; -class DriWindowDelegate; -class DriWrapper; -class HardwareDisplayController; - -class DriSurface : public SurfaceOzoneCanvas { - public: - DriSurface(DriWindowDelegate* window_delegate, DriWrapper* dri); - virtual ~DriSurface(); - - // SurfaceOzoneCanvas: - virtual skia::RefPtr<SkCanvas> GetCanvas() override; - virtual void ResizeCanvas(const gfx::Size& viewport_size) override; - virtual void PresentCanvas(const gfx::Rect& damage) override; - virtual scoped_ptr<gfx::VSyncProvider> CreateVSyncProvider() override; - - private: - void UpdateNativeSurface(const gfx::Rect& damage); - - DriWindowDelegate* window_delegate_; - - // Stores the connection to the graphics card. Pointer not owned by this - // class. - DriWrapper* dri_; - - // The actual buffers used for painting. - scoped_refptr<DriBuffer> buffers_[2]; - - // Keeps track of which bitmap is |buffers_| is the frontbuffer. - int front_buffer_; - - skia::RefPtr<SkSurface> surface_; - gfx::Rect last_damage_; - - DISALLOW_COPY_AND_ASSIGN(DriSurface); -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_DRI_SURFACE_H_
diff --git a/ui/ozone/platform/dri/dri_surface_factory.cc b/ui/ozone/platform/dri/dri_surface_factory.cc deleted file mode 100644 index fb8ce75..0000000 --- a/ui/ozone/platform/dri/dri_surface_factory.cc +++ /dev/null
@@ -1,184 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/dri/dri_surface_factory.h" - -#include <errno.h> - -#include "base/debug/trace_event.h" -#include "third_party/skia/include/core/SkBitmap.h" -#include "third_party/skia/include/core/SkDevice.h" -#include "third_party/skia/include/core/SkSurface.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/ozone/platform/dri/dri_buffer.h" -#include "ui/ozone/platform/dri/dri_surface.h" -#include "ui/ozone/platform/dri/dri_util.h" -#include "ui/ozone/platform/dri/dri_window_delegate_impl.h" -#include "ui/ozone/platform/dri/dri_window_delegate_manager.h" -#include "ui/ozone/platform/dri/dri_wrapper.h" -#include "ui/ozone/platform/dri/hardware_display_controller.h" -#include "ui/ozone/platform/dri/screen_manager.h" -#include "ui/ozone/public/surface_ozone_canvas.h" - -namespace ui { - -namespace { - -// TODO(dnicoara) Read the cursor plane size from the hardware. -const gfx::Size kCursorSize(64, 64); - -void UpdateCursorImage(DriBuffer* cursor, const SkBitmap& image) { - SkRect damage; - image.getBounds(&damage); - - // Clear to transparent in case |image| is smaller than the canvas. - SkCanvas* canvas = cursor->GetCanvas(); - canvas->clear(SK_ColorTRANSPARENT); - - SkRect clip; - clip.set( - 0, 0, canvas->getDeviceSize().width(), canvas->getDeviceSize().height()); - canvas->clipRect(clip, SkRegion::kReplace_Op); - canvas->drawBitmapRectToRect(image, &damage, damage); -} - -} // namespace - -// static -const gfx::AcceleratedWidget DriSurfaceFactory::kDefaultWidgetHandle = 1; - -DriSurfaceFactory::DriSurfaceFactory(DriWrapper* drm, - ScreenManager* screen_manager, - DriWindowDelegateManager* window_manager) - : drm_(drm), - screen_manager_(screen_manager), - window_manager_(window_manager), - state_(UNINITIALIZED), - cursor_frontbuffer_(0), - cursor_widget_(0), - cursor_frame_(0), - cursor_frame_delay_ms_(0) { -} - -DriSurfaceFactory::~DriSurfaceFactory() { - if (state_ == INITIALIZED) - ShutdownHardware(); -} - -DriSurfaceFactory::HardwareState DriSurfaceFactory::InitializeHardware() { - if (state_ != UNINITIALIZED) - return state_; - - if (drm_->get_fd() < 0) { - LOG(ERROR) << "Failed to create DRI connection"; - state_ = FAILED; - return state_; - } - - SkImageInfo info = SkImageInfo::MakeN32Premul(kCursorSize.width(), - kCursorSize.height()); - for (size_t i = 0; i < arraysize(cursor_buffers_); ++i) { - cursor_buffers_[i] = new DriBuffer(drm_); - if (!cursor_buffers_[i]->Initialize(info)) { - LOG(ERROR) << "Failed to initialize cursor buffer"; - state_ = FAILED; - return state_; - } - } - - state_ = INITIALIZED; - return state_; -} - -void DriSurfaceFactory::ShutdownHardware() { - DCHECK(state_ == INITIALIZED); - state_ = UNINITIALIZED; -} - -scoped_ptr<ui::SurfaceOzoneCanvas> DriSurfaceFactory::CreateCanvasForWidget( - gfx::AcceleratedWidget widget) { - DCHECK(state_ == INITIALIZED); - - return scoped_ptr<ui::SurfaceOzoneCanvas>( - new DriSurface(window_manager_->GetWindowDelegate(widget), drm_)); -} - -bool DriSurfaceFactory::LoadEGLGLES2Bindings( - AddGLLibraryCallback add_gl_library, - SetGLGetProcAddressProcCallback set_gl_get_proc_address) { - return false; -} - -void DriSurfaceFactory::SetHardwareCursor(gfx::AcceleratedWidget widget, - const std::vector<SkBitmap>& bitmaps, - const gfx::Point& location, - int frame_delay_ms) { - cursor_widget_ = widget; - cursor_bitmaps_ = bitmaps; - cursor_location_ = location; - cursor_frame_ = 0; - cursor_frame_delay_ms_ = frame_delay_ms; - cursor_timer_.Stop(); - - if (cursor_frame_delay_ms_) - cursor_timer_.Start( - FROM_HERE, - base::TimeDelta::FromMilliseconds(cursor_frame_delay_ms_), - this, - &DriSurfaceFactory::OnCursorAnimationTimeout); - - if (state_ != INITIALIZED) - return; - - ResetCursor(); -} - -void DriSurfaceFactory::MoveHardwareCursor(gfx::AcceleratedWidget widget, - const gfx::Point& location) { - cursor_location_ = location; - - if (state_ != INITIALIZED) - return; - - HardwareDisplayController* controller = - window_manager_->GetWindowDelegate(widget)->GetController(); - if (controller) - controller->MoveCursor(location); -} - -//////////////////////////////////////////////////////////////////////////////// -// DriSurfaceFactory private - -void DriSurfaceFactory::ResetCursor() { - if (!cursor_widget_) - return; - - HardwareDisplayController* controller = - window_manager_->GetWindowDelegate(cursor_widget_)->GetController(); - if (cursor_bitmaps_.size()) { - // Draw new cursor into backbuffer. - UpdateCursorImage(cursor_buffers_[cursor_frontbuffer_ ^ 1].get(), - cursor_bitmaps_[cursor_frame_]); - - // Reset location & buffer. - if (controller) { - controller->MoveCursor(cursor_location_); - controller->SetCursor(cursor_buffers_[cursor_frontbuffer_ ^ 1]); - cursor_frontbuffer_ ^= 1; - } - } else { - // No cursor set. - if (controller) - controller->UnsetCursor(); - } -} - -void DriSurfaceFactory::OnCursorAnimationTimeout() { - cursor_frame_++; - cursor_frame_ %= cursor_bitmaps_.size(); - - ResetCursor(); -} - -} // namespace ui
diff --git a/ui/ozone/platform/dri/dri_surface_factory.h b/ui/ozone/platform/dri/dri_surface_factory.h deleted file mode 100644 index d05ad5f..0000000 --- a/ui/ozone/platform/dri/dri_surface_factory.h +++ /dev/null
@@ -1,93 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_DRI_SURFACE_FACTORY_H_ -#define UI_OZONE_PLATFORM_DRI_DRI_SURFACE_FACTORY_H_ - -#include <map> -#include <vector> - -#include "base/memory/scoped_ptr.h" -#include "base/timer/timer.h" -#include "third_party/skia/include/core/SkBitmap.h" -#include "ui/ozone/platform/dri/hardware_cursor_delegate.h" -#include "ui/ozone/public/surface_factory_ozone.h" - -namespace ui { - -class DriBuffer; -class DriWindowDelegateManager; -class DriWrapper; -class ScreenManager; -class SurfaceOzoneCanvas; - -// SurfaceFactoryOzone implementation on top of DRM/KMS using dumb buffers. -// This implementation is used in conjunction with the software rendering -// path. -class DriSurfaceFactory : public SurfaceFactoryOzone, - public HardwareCursorDelegate { - public: - static const gfx::AcceleratedWidget kDefaultWidgetHandle; - - DriSurfaceFactory(DriWrapper* drm, - ScreenManager* screen_manager, - DriWindowDelegateManager* window_manager); - virtual ~DriSurfaceFactory(); - - // Describes the state of the hardware after initialization. - enum HardwareState { - UNINITIALIZED, - INITIALIZED, - FAILED, - }; - - // Open the display device. - HardwareState InitializeHardware(); - - // Close the display device. - void ShutdownHardware(); - - // SurfaceFactoryOzone: - virtual scoped_ptr<SurfaceOzoneCanvas> CreateCanvasForWidget( - gfx::AcceleratedWidget widget) override; - virtual bool LoadEGLGLES2Bindings( - AddGLLibraryCallback add_gl_library, - SetGLGetProcAddressProcCallback set_gl_get_proc_address) override; - - // HardwareCursorDelegate: - virtual void SetHardwareCursor(gfx::AcceleratedWidget widget, - const std::vector<SkBitmap>& bitmaps, - const gfx::Point& location, - int frame_delay_ms) override; - virtual void MoveHardwareCursor(gfx::AcceleratedWidget window, - const gfx::Point& location) override; - - protected: - // Draw the last set cursor & update the cursor plane. - void ResetCursor(); - - // Draw next frame in an animated cursor. - void OnCursorAnimationTimeout(); - - DriWrapper* drm_; // Not owned. - ScreenManager* screen_manager_; // Not owned. - DriWindowDelegateManager* window_manager_; // Not owned. - HardwareState state_; - - scoped_refptr<DriBuffer> cursor_buffers_[2]; - int cursor_frontbuffer_; - - gfx::AcceleratedWidget cursor_widget_; - std::vector<SkBitmap> cursor_bitmaps_; - gfx::Point cursor_location_; - int cursor_frame_; - int cursor_frame_delay_ms_; - base::RepeatingTimer<DriSurfaceFactory> cursor_timer_; - - DISALLOW_COPY_AND_ASSIGN(DriSurfaceFactory); -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_DRI_SURFACE_FACTORY_H_
diff --git a/ui/ozone/platform/dri/dri_surface_factory_unittest.cc b/ui/ozone/platform/dri/dri_surface_factory_unittest.cc deleted file mode 100644 index 6a124c6..0000000 --- a/ui/ozone/platform/dri/dri_surface_factory_unittest.cc +++ /dev/null
@@ -1,155 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <vector> - -#include "base/memory/scoped_ptr.h" -#include "base/message_loop/message_loop.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "third_party/skia/include/core/SkCanvas.h" -#include "third_party/skia/include/core/SkColor.h" -#include "third_party/skia/include/core/SkImageInfo.h" -#include "ui/ozone/platform/dri/dri_buffer.h" -#include "ui/ozone/platform/dri/dri_surface.h" -#include "ui/ozone/platform/dri/dri_surface_factory.h" -#include "ui/ozone/platform/dri/dri_window_delegate_impl.h" -#include "ui/ozone/platform/dri/dri_window_delegate_manager.h" -#include "ui/ozone/platform/dri/hardware_display_controller.h" -#include "ui/ozone/platform/dri/screen_manager.h" -#include "ui/ozone/platform/dri/test/mock_dri_wrapper.h" -#include "ui/ozone/public/surface_factory_ozone.h" -#include "ui/ozone/public/surface_ozone_canvas.h" - -namespace { - -// Mode of size 6x4. -const drmModeModeInfo kDefaultMode = - {0, 6, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, {'\0'}}; - -const uint32_t kDefaultCrtc = 1; -const uint32_t kDefaultConnector = 2; - -class MockScreenManager : public ui::ScreenManager { - public: - MockScreenManager(ui::DriWrapper* dri, - ui::ScanoutBufferGenerator* buffer_generator) - : ScreenManager(dri, buffer_generator), - dri_(dri) {} - virtual ~MockScreenManager() {} - - // Normally we'd use DRM to figure out the controller configuration. But we - // can't use DRM in unit tests, so we just create a fake configuration. - virtual void ForceInitializationOfPrimaryDisplay() override { - ConfigureDisplayController( - kDefaultCrtc, kDefaultConnector, gfx::Point(), kDefaultMode); - } - - private: - ui::DriWrapper* dri_; // Not owned. - - DISALLOW_COPY_AND_ASSIGN(MockScreenManager); -}; - -} // namespace - -class DriSurfaceFactoryTest : public testing::Test { - public: - DriSurfaceFactoryTest() {} - - virtual void SetUp() override; - virtual void TearDown() override; - protected: - scoped_ptr<base::MessageLoop> message_loop_; - scoped_ptr<ui::MockDriWrapper> dri_; - scoped_ptr<ui::DriBufferGenerator> buffer_generator_; - scoped_ptr<MockScreenManager> screen_manager_; - scoped_ptr<ui::DriSurfaceFactory> factory_; - scoped_ptr<ui::DriWindowDelegateManager> window_delegate_manager_; - - private: - DISALLOW_COPY_AND_ASSIGN(DriSurfaceFactoryTest); -}; - -void DriSurfaceFactoryTest::SetUp() { - message_loop_.reset(new base::MessageLoopForUI); - dri_.reset(new ui::MockDriWrapper(3)); - buffer_generator_.reset(new ui::DriBufferGenerator(dri_.get())); - screen_manager_.reset(new MockScreenManager(dri_.get(), - buffer_generator_.get())); - window_delegate_manager_.reset(new ui::DriWindowDelegateManager()); - factory_.reset(new ui::DriSurfaceFactory( - dri_.get(), screen_manager_.get(), window_delegate_manager_.get())); - - scoped_ptr<ui::DriWindowDelegate> window_delegate( - new ui::DriWindowDelegateImpl(ui::DriSurfaceFactory::kDefaultWidgetHandle, - screen_manager_.get())); - window_delegate->Initialize(); - window_delegate_manager_->AddWindowDelegate( - ui::DriSurfaceFactory::kDefaultWidgetHandle, window_delegate.Pass()); -} - -void DriSurfaceFactoryTest::TearDown() { - scoped_ptr<ui::DriWindowDelegate> delegate = - window_delegate_manager_->RemoveWindowDelegate( - ui::DriSurfaceFactory::kDefaultWidgetHandle); - delegate->Shutdown(); - factory_.reset(); - message_loop_.reset(); -} - -TEST_F(DriSurfaceFactoryTest, FailInitialization) { - dri_->fail_init(); - EXPECT_EQ(ui::DriSurfaceFactory::FAILED, factory_->InitializeHardware()); -} - -TEST_F(DriSurfaceFactoryTest, SuccessfulInitialization) { - EXPECT_EQ(ui::DriSurfaceFactory::INITIALIZED, - factory_->InitializeHardware()); -} - -TEST_F(DriSurfaceFactoryTest, SuccessfulWidgetRealization) { - EXPECT_EQ(ui::DriSurfaceFactory::INITIALIZED, - factory_->InitializeHardware()); - - EXPECT_TRUE(factory_->CreateCanvasForWidget( - ui::DriSurfaceFactory::kDefaultWidgetHandle)); -} - -TEST_F(DriSurfaceFactoryTest, SetCursorImage) { - EXPECT_EQ(ui::DriSurfaceFactory::INITIALIZED, - factory_->InitializeHardware()); - - scoped_ptr<ui::SurfaceOzoneCanvas> surf = factory_->CreateCanvasForWidget( - ui::DriSurfaceFactory::kDefaultWidgetHandle); - EXPECT_TRUE(surf); - - SkBitmap image; - SkImageInfo info = SkImageInfo::Make( - 6, 4, kN32_SkColorType, kPremul_SkAlphaType); - image.allocPixels(info); - image.eraseColor(SK_ColorWHITE); - - std::vector<SkBitmap> cursor_bitmaps; - cursor_bitmaps.push_back(image); - factory_->SetHardwareCursor(ui::DriSurfaceFactory::kDefaultWidgetHandle, - cursor_bitmaps, - gfx::Point(4, 2), - 0); - - SkBitmap cursor; - // Buffers 0 and 1 are the cursor buffers. - cursor.setInfo(dri_->buffers()[1]->getCanvas()->imageInfo()); - EXPECT_TRUE(dri_->buffers()[1]->getCanvas()->readPixels(&cursor, 0, 0)); - - // Check that the frontbuffer is displaying the right image as set above. - for (int i = 0; i < cursor.height(); ++i) { - for (int j = 0; j < cursor.width(); ++j) { - if (j < info.width() && i < info.height()) - EXPECT_EQ(SK_ColorWHITE, cursor.getColor(j, i)); - else - EXPECT_EQ(static_cast<SkColor>(SK_ColorTRANSPARENT), - cursor.getColor(j, i)); - } - } -}
diff --git a/ui/ozone/platform/dri/dri_surface_unittest.cc b/ui/ozone/platform/dri/dri_surface_unittest.cc deleted file mode 100644 index 108e600..0000000 --- a/ui/ozone/platform/dri/dri_surface_unittest.cc +++ /dev/null
@@ -1,126 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/message_loop/message_loop.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "third_party/skia/include/core/SkCanvas.h" -#include "third_party/skia/include/core/SkColor.h" -#include "third_party/skia/include/core/SkDevice.h" -#include "ui/ozone/platform/dri/crtc_controller.h" -#include "ui/ozone/platform/dri/dri_buffer.h" -#include "ui/ozone/platform/dri/dri_surface.h" -#include "ui/ozone/platform/dri/dri_window_delegate.h" -#include "ui/ozone/platform/dri/hardware_display_controller.h" -#include "ui/ozone/platform/dri/test/mock_dri_wrapper.h" - -namespace { - -// Create a basic mode for a 6x4 screen. -const drmModeModeInfo kDefaultMode = - {0, 6, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, {'\0'}}; - -const uint32_t kDefaultCrtc = 1; -const uint32_t kDefaultConnector = 2; - -class MockDriWindowDelegate : public ui::DriWindowDelegate { - public: - MockDriWindowDelegate(ui::DriWrapper* drm) { - controller_.reset(new ui::HardwareDisplayController(make_scoped_ptr( - new ui::CrtcController(drm, kDefaultCrtc, kDefaultConnector)))); - scoped_refptr<ui::DriBuffer> buffer(new ui::DriBuffer(drm)); - SkImageInfo info = SkImageInfo::MakeN32Premul(kDefaultMode.hdisplay, - kDefaultMode.vdisplay); - EXPECT_TRUE(buffer->Initialize(info)); - EXPECT_TRUE(controller_->Modeset(ui::OverlayPlane(buffer), kDefaultMode)); - } - virtual ~MockDriWindowDelegate() {} - - // DriWindowDelegate: - virtual void Initialize() override {} - virtual void Shutdown() override {} - virtual gfx::AcceleratedWidget GetAcceleratedWidget() override { return 1; } - virtual ui::HardwareDisplayController* GetController() override { - return controller_.get(); - } - virtual void OnBoundsChanged(const gfx::Rect& bounds) override {} - - private: - scoped_ptr<ui::HardwareDisplayController> controller_; - - DISALLOW_COPY_AND_ASSIGN(MockDriWindowDelegate); -}; - -} // namespace - -class DriSurfaceTest : public testing::Test { - public: - DriSurfaceTest() {} - - virtual void SetUp() override; - virtual void TearDown() override; - - protected: - scoped_ptr<base::MessageLoop> message_loop_; - scoped_ptr<ui::MockDriWrapper> drm_; - scoped_ptr<MockDriWindowDelegate> window_delegate_; - scoped_ptr<ui::DriSurface> surface_; - - private: - DISALLOW_COPY_AND_ASSIGN(DriSurfaceTest); -}; - -void DriSurfaceTest::SetUp() { - message_loop_.reset(new base::MessageLoopForUI); - drm_.reset(new ui::MockDriWrapper(3)); - window_delegate_.reset(new MockDriWindowDelegate(drm_.get())); - surface_.reset(new ui::DriSurface(window_delegate_.get(), drm_.get())); - surface_->ResizeCanvas(gfx::Size(kDefaultMode.hdisplay, - kDefaultMode.vdisplay)); -} - -void DriSurfaceTest::TearDown() { - surface_.reset(); - window_delegate_.reset(); - drm_.reset(); - message_loop_.reset(); -} - -TEST_F(DriSurfaceTest, CheckFBIDOnSwap) { - surface_->PresentCanvas(gfx::Rect()); - // Framebuffer ID 1 is allocated in SetUp for the buffer used to modeset. - EXPECT_EQ(3u, drm_->current_framebuffer()); - surface_->PresentCanvas(gfx::Rect()); - EXPECT_EQ(2u, drm_->current_framebuffer()); -} - -TEST_F(DriSurfaceTest, CheckSurfaceContents) { - SkPaint paint; - paint.setColor(SK_ColorWHITE); - SkRect rect = SkRect::MakeWH(kDefaultMode.hdisplay / 2, - kDefaultMode.vdisplay / 2); - surface_->GetCanvas()->drawRect(rect, paint); - surface_->PresentCanvas( - gfx::Rect(0, 0, kDefaultMode.hdisplay / 2, kDefaultMode.vdisplay / 2)); - - SkBitmap image; - // Buffer 0 is the buffer used in SetUp for modesetting and buffer 1 is the - // frontbuffer. - // Buffer 2 is the backbuffer we just painted in, so we want to make sure its - // contents are correct. - image.setInfo(drm_->buffers()[2]->getCanvas()->imageInfo()); - EXPECT_TRUE(drm_->buffers()[2]->getCanvas()->readPixels(&image, 0, 0)); - - EXPECT_EQ(kDefaultMode.hdisplay, image.width()); - EXPECT_EQ(kDefaultMode.vdisplay, image.height()); - - // Make sure the updates are correctly propagated to the native surface. - for (int i = 0; i < image.height(); ++i) { - for (int j = 0; j < image.width(); ++j) { - if (j < kDefaultMode.hdisplay / 2 && i < kDefaultMode.vdisplay / 2) - EXPECT_EQ(SK_ColorWHITE, image.getColor(j, i)); - else - EXPECT_EQ(SK_ColorBLACK, image.getColor(j, i)); - } - } -}
diff --git a/ui/ozone/platform/dri/dri_util.cc b/ui/ozone/platform/dri/dri_util.cc deleted file mode 100644 index 5305f6d..0000000 --- a/ui/ozone/platform/dri/dri_util.cc +++ /dev/null
@@ -1,138 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/dri/dri_util.h" - -#include <errno.h> -#include <stdint.h> -#include <stdlib.h> -#include <sys/mman.h> -#include <xf86drm.h> -#include <xf86drmMode.h> - -namespace ui { - -namespace { - -bool IsCrtcInUse(uint32_t crtc, - const ScopedVector<HardwareDisplayControllerInfo>& displays) { - for (size_t i = 0; i < displays.size(); ++i) { - if (crtc == displays[i]->crtc()->crtc_id) - return true; - } - - return false; -} - -uint32_t GetCrtc(int fd, - drmModeConnector* connector, - drmModeRes* resources, - const ScopedVector<HardwareDisplayControllerInfo>& displays) { - // If the connector already has an encoder try to re-use. - if (connector->encoder_id) { - ScopedDrmEncoderPtr encoder(drmModeGetEncoder(fd, connector->encoder_id)); - if (encoder && encoder->crtc_id && !IsCrtcInUse(encoder->crtc_id, displays)) - return encoder->crtc_id; - } - - // Try to find an encoder for the connector. - for (int i = 0; i < connector->count_encoders; ++i) { - ScopedDrmEncoderPtr encoder(drmModeGetEncoder(fd, connector->encoders[i])); - if (!encoder) - continue; - - for (int j = 0; j < resources->count_crtcs; ++j) { - // Check if the encoder is compatible with this CRTC - if (!(encoder->possible_crtcs & (1 << j)) || - IsCrtcInUse(resources->crtcs[j], displays)) - continue; - - return resources->crtcs[j]; - } - } - - return 0; -} - -} // namespace - -HardwareDisplayControllerInfo::HardwareDisplayControllerInfo( - ScopedDrmConnectorPtr connector, - ScopedDrmCrtcPtr crtc) - : connector_(connector.Pass()), - crtc_(crtc.Pass()) {} - -HardwareDisplayControllerInfo::~HardwareDisplayControllerInfo() {} - -ScopedVector<HardwareDisplayControllerInfo> -GetAvailableDisplayControllerInfos(int fd) { - ScopedDrmResourcesPtr resources(drmModeGetResources(fd)); - DCHECK(resources) << "Failed to get DRM resources"; - ScopedVector<HardwareDisplayControllerInfo> displays; - - for (int i = 0; i < resources->count_connectors; ++i) { - ScopedDrmConnectorPtr connector(drmModeGetConnector( - fd, resources->connectors[i])); - - if (!connector || connector->connection != DRM_MODE_CONNECTED || - connector->count_modes == 0) - continue; - - uint32_t crtc_id = GetCrtc(fd, connector.get(), resources.get(), displays); - if (!crtc_id) - continue; - - ScopedDrmCrtcPtr crtc(drmModeGetCrtc(fd, crtc_id)); - displays.push_back(new HardwareDisplayControllerInfo(connector.Pass(), - crtc.Pass())); - } - - return displays.Pass(); -} - -bool SameMode(const drmModeModeInfo& lhs, const drmModeModeInfo& rhs) { - return lhs.clock == rhs.clock && - lhs.hdisplay == rhs.hdisplay && - lhs.vdisplay == rhs.vdisplay && - lhs.vrefresh == rhs.vrefresh && - lhs.hsync_start == rhs.hsync_start && - lhs.hsync_end == rhs.hsync_end && - lhs.htotal == rhs.htotal && - lhs.hskew == rhs.hskew && - lhs.vsync_start == rhs.vsync_start && - lhs.vsync_end == rhs.vsync_end && - lhs.vtotal == rhs.vtotal && - lhs.vscan == rhs.vscan && - lhs.flags == rhs.flags && - strcmp(lhs.name, rhs.name) == 0; -} - -bool MapDumbBuffer(int fd, - uint32_t handle, - uint32_t size, - void** pixels) { - struct drm_mode_map_dumb map_request; - memset(&map_request, 0, sizeof(map_request)); - map_request.handle = handle; - if (drmIoctl(fd, DRM_IOCTL_MODE_MAP_DUMB, &map_request)) { - VLOG(2) << "Cannot prepare dumb buffer for mapping (" << errno << ") " - << strerror(errno); - return false; - } - - *pixels = mmap(0, - size, - PROT_READ | PROT_WRITE, - MAP_SHARED, - fd, - map_request.offset); - if (*pixels == MAP_FAILED) { - VLOG(2) << "Cannot mmap dumb buffer (" << errno << ") " << strerror(errno); - return false; - } - - return true; -} - -} // namespace ui
diff --git a/ui/ozone/platform/dri/dri_util.h b/ui/ozone/platform/dri/dri_util.h deleted file mode 100644 index 94f2b45..0000000 --- a/ui/ozone/platform/dri/dri_util.h +++ /dev/null
@@ -1,49 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_DRI_UTIL_H_ -#define UI_OZONE_PLATFORM_DRI_DRI_UTIL_H_ - -#include "base/macros.h" -#include "base/memory/scoped_vector.h" -#include "ui/ozone/platform/dri/scoped_drm_types.h" - -typedef struct _drmModeModeInfo drmModeModeInfo; - -namespace ui { - -// Representation of the information required to initialize and configure a -// native display. -class HardwareDisplayControllerInfo { - public: - HardwareDisplayControllerInfo(ScopedDrmConnectorPtr connector, - ScopedDrmCrtcPtr crtc); - ~HardwareDisplayControllerInfo(); - - drmModeConnector* connector() const { return connector_.get(); } - drmModeCrtc* crtc() const { return crtc_.get(); } - - private: - ScopedDrmConnectorPtr connector_; - ScopedDrmCrtcPtr crtc_; - - DISALLOW_COPY_AND_ASSIGN(HardwareDisplayControllerInfo); -}; - -// Looks-up and parses the native display configurations returning all available -// displays. -ScopedVector<HardwareDisplayControllerInfo> -GetAvailableDisplayControllerInfos(int fd); - -bool SameMode(const drmModeModeInfo& lhs, const drmModeModeInfo& rhs); - -// Memory maps a DRM buffer. -bool MapDumbBuffer(int fd, - uint32_t handle, - uint32_t size, - void** pixels); - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_DRI_UTIL_H_
diff --git a/ui/ozone/platform/dri/dri_vsync_provider.cc b/ui/ozone/platform/dri/dri_vsync_provider.cc deleted file mode 100644 index bf88c5d..0000000 --- a/ui/ozone/platform/dri/dri_vsync_provider.cc +++ /dev/null
@@ -1,39 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/dri/dri_vsync_provider.h" - -#include "base/time/time.h" -#include "ui/ozone/platform/dri/dri_window_delegate.h" -#include "ui/ozone/platform/dri/hardware_display_controller.h" - -namespace ui { - -DriVSyncProvider::DriVSyncProvider(DriWindowDelegate* window_delegate) - : window_delegate_(window_delegate) { -} - -DriVSyncProvider::~DriVSyncProvider() {} - -void DriVSyncProvider::GetVSyncParameters(const UpdateVSyncCallback& callback) { - HardwareDisplayController* controller = window_delegate_->GetController(); - if (!controller) - return; - - // The value is invalid, so we can't update the parameters. - if (controller->GetTimeOfLastFlip() == 0 || - controller->get_mode().vrefresh == 0) - return; - - // Stores the time of the last refresh. - base::TimeTicks timebase = - base::TimeTicks::FromInternalValue(controller->GetTimeOfLastFlip()); - // Stores the refresh rate. - base::TimeDelta interval = - base::TimeDelta::FromSeconds(1) / controller->get_mode().vrefresh; - - callback.Run(timebase, interval); -} - -} // namespace ui
diff --git a/ui/ozone/platform/dri/dri_vsync_provider.h b/ui/ozone/platform/dri/dri_vsync_provider.h deleted file mode 100644 index 05668f2..0000000 --- a/ui/ozone/platform/dri/dri_vsync_provider.h +++ /dev/null
@@ -1,29 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_IMPL_DRI_VSYNC_PROVIDER_H_ -#define UI_OZONE_PLATFORM_IMPL_DRI_VSYNC_PROVIDER_H_ - -#include "ui/gfx/vsync_provider.h" - -namespace ui { - -class DriWindowDelegate; - -class DriVSyncProvider : public gfx::VSyncProvider { - public: - DriVSyncProvider(DriWindowDelegate* window_delegate); - virtual ~DriVSyncProvider(); - - virtual void GetVSyncParameters(const UpdateVSyncCallback& callback) override; - - private: - DriWindowDelegate* window_delegate_; // Not owned. - - DISALLOW_COPY_AND_ASSIGN(DriVSyncProvider); -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_IMPL_DRI_VSYNC_PROVIDER_H_
diff --git a/ui/ozone/platform/dri/dri_window.cc b/ui/ozone/platform/dri/dri_window.cc deleted file mode 100644 index cce1dd6..0000000 --- a/ui/ozone/platform/dri/dri_window.cc +++ /dev/null
@@ -1,122 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/dri/dri_window.h" - -#include "base/bind.h" -#include "ui/events/event.h" -#include "ui/events/ozone/evdev/event_factory_evdev.h" -#include "ui/events/ozone/events_ozone.h" -#include "ui/events/platform/platform_event_source.h" -#include "ui/ozone/common/gpu/ozone_gpu_messages.h" -#include "ui/ozone/platform/dri/dri_cursor.h" -#include "ui/ozone/platform/dri/dri_gpu_platform_support_host.h" -#include "ui/ozone/platform/dri/dri_window_manager.h" -#include "ui/platform_window/platform_window_delegate.h" - -namespace ui { - -DriWindow::DriWindow(PlatformWindowDelegate* delegate, - const gfx::Rect& bounds, - DriGpuPlatformSupportHost* sender, - EventFactoryEvdev* event_factory, - DriWindowManager* window_manager) - : delegate_(delegate), - sender_(sender), - event_factory_(event_factory), - window_manager_(window_manager), - bounds_(bounds), - widget_(window_manager->NextAcceleratedWidget()) { - window_manager_->AddWindow(widget_, this); -} - -DriWindow::~DriWindow() { - PlatformEventSource::GetInstance()->RemovePlatformEventDispatcher(this); - window_manager_->RemoveWindow(widget_); - - sender_->RemoveChannelObserver(this); - if (!sender_->IsConnected()) - return; - - sender_->Send(new OzoneGpuMsg_DestroyWindowDelegate(widget_)); -} - -void DriWindow::Initialize() { - sender_->AddChannelObserver(this); - delegate_->OnAcceleratedWidgetAvailable(widget_); - PlatformEventSource::GetInstance()->AddPlatformEventDispatcher(this); -} - -void DriWindow::Show() {} - -void DriWindow::Hide() {} - -void DriWindow::Close() {} - -void DriWindow::SetBounds(const gfx::Rect& bounds) { - bounds_ = bounds; - delegate_->OnBoundsChanged(bounds); - - if (!sender_->IsConnected()) - return; - - if (window_manager_->cursor()->GetCursorWindow() == widget_) - window_manager_->cursor()->HideCursor(); - - sender_->Send(new OzoneGpuMsg_WindowBoundsChanged(widget_, bounds)); - - if (window_manager_->cursor()->GetCursorWindow() == widget_) - window_manager_->cursor()->ShowCursor(); -} - -gfx::Rect DriWindow::GetBounds() { - return bounds_; -} - -void DriWindow::SetCapture() {} - -void DriWindow::ReleaseCapture() {} - -void DriWindow::ToggleFullscreen() {} - -void DriWindow::Maximize() {} - -void DriWindow::Minimize() {} - -void DriWindow::Restore() {} - -void DriWindow::SetCursor(PlatformCursor cursor) { - window_manager_->cursor()->SetCursor(widget_, cursor); -} - -void DriWindow::MoveCursorTo(const gfx::Point& location) { - event_factory_->WarpCursorTo(widget_, location); -} - -bool DriWindow::CanDispatchEvent(const PlatformEvent& ne) { - DCHECK(ne); - Event* event = static_cast<Event*>(ne); - if (event->IsMouseEvent() || event->IsScrollEvent()) - return window_manager_->cursor()->GetCursorWindow() == widget_; - - return true; -} - -uint32_t DriWindow::DispatchEvent(const PlatformEvent& native_event) { - DispatchEventFromNativeUiEvent( - native_event, - base::Bind(&PlatformWindowDelegate::DispatchEvent, - base::Unretained(delegate_))); - return POST_DISPATCH_STOP_PROPAGATION; -} - -void DriWindow::OnChannelEstablished() { - sender_->Send(new OzoneGpuMsg_CreateWindowDelegate(widget_)); - sender_->Send(new OzoneGpuMsg_WindowBoundsChanged(widget_, bounds_)); -} - -void DriWindow::OnChannelDestroyed() { -} - -} // namespace ui
diff --git a/ui/ozone/platform/dri/dri_window.h b/ui/ozone/platform/dri/dri_window.h deleted file mode 100644 index 9197ce0..0000000 --- a/ui/ozone/platform/dri/dri_window.h +++ /dev/null
@@ -1,72 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_DRI_WINDOW_H_ -#define UI_OZONE_PLATFORM_DRI_DRI_WINDOW_H_ - -#include "base/memory/scoped_ptr.h" -#include "ui/events/platform/platform_event_dispatcher.h" -#include "ui/gfx/geometry/rect.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/ozone/platform/dri/channel_observer.h" -#include "ui/platform_window/platform_window.h" - -namespace ui { - -class DriWindowDelegate; -class DriWindowManager; -class EventFactoryEvdev; -class DriGpuPlatformSupportHost; - -class DriWindow : public PlatformWindow, - public PlatformEventDispatcher, - public ChannelObserver { - public: - DriWindow(PlatformWindowDelegate* delegate, - const gfx::Rect& bounds, - DriGpuPlatformSupportHost* sender, - EventFactoryEvdev* event_factory, - DriWindowManager* window_manager); - virtual ~DriWindow(); - - void Initialize(); - - // PlatformWindow: - virtual void Show() override; - virtual void Hide() override; - virtual void Close() override; - virtual void SetBounds(const gfx::Rect& bounds) override; - virtual gfx::Rect GetBounds() override; - virtual void SetCapture() override; - virtual void ReleaseCapture() override; - virtual void ToggleFullscreen() override; - virtual void Maximize() override; - virtual void Minimize() override; - virtual void Restore() override; - virtual void SetCursor(PlatformCursor cursor) override; - virtual void MoveCursorTo(const gfx::Point& location) override; - - // PlatformEventDispatcher: - virtual bool CanDispatchEvent(const PlatformEvent& event) override; - virtual uint32_t DispatchEvent(const PlatformEvent& event) override; - - // ChannelObserver: - virtual void OnChannelEstablished() override; - virtual void OnChannelDestroyed() override; - - private: - PlatformWindowDelegate* delegate_; // Not owned. - DriGpuPlatformSupportHost* sender_; // Not owned. - EventFactoryEvdev* event_factory_; // Not owned. - DriWindowManager* window_manager_; // Not owned. - - gfx::Rect bounds_; - gfx::AcceleratedWidget widget_; - - DISALLOW_COPY_AND_ASSIGN(DriWindow); -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_DRI_WINDOW_H_
diff --git a/ui/ozone/platform/dri/dri_window_delegate.h b/ui/ozone/platform/dri/dri_window_delegate.h deleted file mode 100644 index 2787e2c..0000000 --- a/ui/ozone/platform/dri/dri_window_delegate.h +++ /dev/null
@@ -1,52 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_DRI_WINDOW_DELEGATE_H_ -#define UI_OZONE_PLATFORM_DRI_DRI_WINDOW_DELEGATE_H_ - -#include "ui/gfx/native_widget_types.h" - -namespace gfx { -class Rect; -} // namespace gfx - -namespace ui { - -class HardwareDisplayController; - -// Interface for the display-server half of a DriWindow. -// -// The main implementation of this lives in the process that owns the display -// connection (usually the GPU process) and associates a platform window -// (DriWindow) with a display. A window is associated with the display whose -// bounds contains the window bounds. If there's no suitable display, the window -// is disconnected and its contents will not be visible. -// -// In software mode, this is owned directly on DriWindow because the display -// controller object is in the same process. -// -// In accelerated mode, there's a proxy implementation and calls are forwarded -// to the real object in the GPU process via IPC. -class DriWindowDelegate { - public: - virtual ~DriWindowDelegate() {} - - virtual void Initialize() = 0; - - virtual void Shutdown() = 0; - - // Returns the accelerated widget associated with the delegate. - virtual gfx::AcceleratedWidget GetAcceleratedWidget() = 0; - - // Returns the current controller the window is displaying on. Callers should - // not cache the result as the controller may change as the window is moved. - virtual HardwareDisplayController* GetController() = 0; - - // Called when the window is resized/moved. - virtual void OnBoundsChanged(const gfx::Rect& bounds) = 0; -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_DRI_WINDOW_DELEGATE_H_
diff --git a/ui/ozone/platform/dri/dri_window_delegate_impl.cc b/ui/ozone/platform/dri/dri_window_delegate_impl.cc deleted file mode 100644 index a95a8fc..0000000 --- a/ui/ozone/platform/dri/dri_window_delegate_impl.cc +++ /dev/null
@@ -1,46 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/dri/dri_window_delegate_impl.h" - -#include "base/debug/trace_event.h" -#include "ui/ozone/platform/dri/screen_manager.h" - -namespace ui { - -DriWindowDelegateImpl::DriWindowDelegateImpl(gfx::AcceleratedWidget widget, - ScreenManager* screen_manager) - : widget_(widget), screen_manager_(screen_manager) { -} - -DriWindowDelegateImpl::~DriWindowDelegateImpl() { -} - -void DriWindowDelegateImpl::Initialize() { - TRACE_EVENT1("dri", "DriWindowDelegateImpl::Initialize", "widget", widget_); -} - -void DriWindowDelegateImpl::Shutdown() { - TRACE_EVENT1("dri", "DriWindowDelegateImpl::Shutdown", "widget", widget_); -} - -gfx::AcceleratedWidget DriWindowDelegateImpl::GetAcceleratedWidget() { - return widget_; -} - -HardwareDisplayController* DriWindowDelegateImpl::GetController() { - return controller_.get(); -} - -void DriWindowDelegateImpl::OnBoundsChanged(const gfx::Rect& bounds) { - TRACE_EVENT2("dri", - "DriWindowDelegateImpl::OnBoundsChanged", - "widget", - widget_, - "bounds", - bounds.ToString()); - controller_ = screen_manager_->GetDisplayController(bounds); -} - -} // namespace ui
diff --git a/ui/ozone/platform/dri/dri_window_delegate_impl.h b/ui/ozone/platform/dri/dri_window_delegate_impl.h deleted file mode 100644 index 0345beb..0000000 --- a/ui/ozone/platform/dri/dri_window_delegate_impl.h +++ /dev/null
@@ -1,46 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_DRI_WINDOW_DELEGATE_IMPL_H_ -#define UI_OZONE_PLATFORM_DRI_DRI_WINDOW_DELEGATE_IMPL_H_ - -#include "base/memory/weak_ptr.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/ozone/platform/dri/dri_window_delegate.h" - -namespace gfx { -class Rect; -} // namespace gfx - -namespace ui { - -class HardwareDisplayController; -class ScreenManager; - -class DriWindowDelegateImpl : public DriWindowDelegate { - public: - DriWindowDelegateImpl(gfx::AcceleratedWidget widget, - ScreenManager* screen_manager); - virtual ~DriWindowDelegateImpl(); - - // DriWindowDelegate: - virtual void Initialize() override; - virtual void Shutdown() override; - virtual gfx::AcceleratedWidget GetAcceleratedWidget() override; - virtual HardwareDisplayController* GetController() override; - virtual void OnBoundsChanged(const gfx::Rect& bounds) override; - - private: - gfx::AcceleratedWidget widget_; - - ScreenManager* screen_manager_; // Not owned. - - base::WeakPtr<HardwareDisplayController> controller_; - - DISALLOW_COPY_AND_ASSIGN(DriWindowDelegateImpl); -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_DRI_WINDOW_DELEGATE_IMPL_H_
diff --git a/ui/ozone/platform/dri/dri_window_delegate_manager.cc b/ui/ozone/platform/dri/dri_window_delegate_manager.cc deleted file mode 100644 index ffbc4ba..0000000 --- a/ui/ozone/platform/dri/dri_window_delegate_manager.cc +++ /dev/null
@@ -1,49 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/dri/dri_window_delegate_manager.h" - -#include "ui/ozone/platform/dri/dri_window_delegate.h" - -namespace ui { - -DriWindowDelegateManager::DriWindowDelegateManager() { -} - -DriWindowDelegateManager::~DriWindowDelegateManager() { - DCHECK(delegate_map_.empty()); -} - -void DriWindowDelegateManager::AddWindowDelegate( - gfx::AcceleratedWidget widget, - scoped_ptr<DriWindowDelegate> delegate) { - std::pair<WidgetToDelegateMap::iterator, bool> result = - delegate_map_.add(widget, delegate.Pass()); - DCHECK(result.second) << "Delegate already added."; -} - -scoped_ptr<DriWindowDelegate> DriWindowDelegateManager::RemoveWindowDelegate( - gfx::AcceleratedWidget widget) { - scoped_ptr<DriWindowDelegate> delegate = delegate_map_.take_and_erase(widget); - DCHECK(delegate) << "Attempting to remove non-existing delegate for " - << widget; - return delegate.Pass(); -} - -DriWindowDelegate* DriWindowDelegateManager::GetWindowDelegate( - gfx::AcceleratedWidget widget) { - WidgetToDelegateMap::iterator it = delegate_map_.find(widget); - if (it != delegate_map_.end()) - return it->second; - - NOTREACHED() << "Attempting to get non-existing delegate for " << widget; - return NULL; -} - -bool DriWindowDelegateManager::HasWindowDelegate( - gfx::AcceleratedWidget widget) { - return delegate_map_.find(widget) != delegate_map_.end(); -} - -} // namespace ui
diff --git a/ui/ozone/platform/dri/dri_window_delegate_manager.h b/ui/ozone/platform/dri/dri_window_delegate_manager.h deleted file mode 100644 index 5f2a572..0000000 --- a/ui/ozone/platform/dri/dri_window_delegate_manager.h +++ /dev/null
@@ -1,48 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_DRI_WINDOW_DELEGATE_MANAGER_H_ -#define UI_OZONE_PLATFORM_DRI_DRI_WINDOW_DELEGATE_MANAGER_H_ - -#include "base/containers/scoped_ptr_hash_map.h" -#include "ui/gfx/native_widget_types.h" - -namespace ui { - -class DriWindowDelegate; - -class DriWindowDelegateManager { - public: - DriWindowDelegateManager(); - ~DriWindowDelegateManager(); - - // Adds a delegate for |widget|. Note: |widget| should not be associated with - // a delegate when calling this function. - void AddWindowDelegate(gfx::AcceleratedWidget widget, - scoped_ptr<DriWindowDelegate> surface); - - // Removes the delegate for |widget|. Note: |widget| must have a delegate - // associated with it when calling this function. - scoped_ptr<DriWindowDelegate> RemoveWindowDelegate( - gfx::AcceleratedWidget widget); - - // Returns the delegate associated with |widget|. Note: This function should - // be called only if a valid delegate has been associated with |widget|. - DriWindowDelegate* GetWindowDelegate(gfx::AcceleratedWidget widget); - - // Check if |widget| has a valid delegate associated with it. - bool HasWindowDelegate(gfx::AcceleratedWidget widget); - - private: - typedef base::ScopedPtrHashMap<gfx::AcceleratedWidget, DriWindowDelegate> - WidgetToDelegateMap; - - WidgetToDelegateMap delegate_map_; - - DISALLOW_COPY_AND_ASSIGN(DriWindowDelegateManager); -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_DRI_WINDOW_DELEGATE_MANAGER_H_
diff --git a/ui/ozone/platform/dri/dri_window_manager.cc b/ui/ozone/platform/dri/dri_window_manager.cc deleted file mode 100644 index 289d930..0000000 --- a/ui/ozone/platform/dri/dri_window_manager.cc +++ /dev/null
@@ -1,77 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/dri/dri_window_manager.h" - -#include "base/logging.h" -#include "ui/ozone/platform/dri/dri_cursor.h" -#include "ui/ozone/platform/dri/dri_window.h" - -namespace ui { - -namespace { - -gfx::PointF GetDefaultCursorLocation(DriWindow* window) { - return gfx::PointF(window->GetBounds().width() / 2, - window->GetBounds().height() / 2); -} - -} // namespace - -DriWindowManager::DriWindowManager(HardwareCursorDelegate* cursor_delegate) - : last_allocated_widget_(0), cursor_(new DriCursor(cursor_delegate, this)) { -} - -DriWindowManager::~DriWindowManager() { -} - -gfx::AcceleratedWidget DriWindowManager::NextAcceleratedWidget() { - // We're not using 0 since other code assumes that a 0 AcceleratedWidget is an - // invalid widget. - return ++last_allocated_widget_; -} - -void DriWindowManager::AddWindow(gfx::AcceleratedWidget widget, - DriWindow* window) { - std::pair<WidgetToWindowMap::iterator, bool> result = window_map_.insert( - std::pair<gfx::AcceleratedWidget, DriWindow*>(widget, window)); - DCHECK(result.second) << "Window for " << widget << " already added."; - - if (cursor_->GetCursorWindow() == gfx::kNullAcceleratedWidget) - ResetCursorLocation(); -} - -void DriWindowManager::RemoveWindow(gfx::AcceleratedWidget widget) { - WidgetToWindowMap::iterator it = window_map_.find(widget); - if (it != window_map_.end()) - window_map_.erase(it); - else - NOTREACHED() << "Attempting to remove non-existing window " << widget; - - if (cursor_->GetCursorWindow() == widget) - ResetCursorLocation(); -} - -DriWindow* DriWindowManager::GetWindow(gfx::AcceleratedWidget widget) { - WidgetToWindowMap::iterator it = window_map_.find(widget); - if (it != window_map_.end()) - return it->second; - - NOTREACHED() << "Attempting to get non-existing window " << widget; - return NULL; -} - -void DriWindowManager::ResetCursorLocation() { - gfx::AcceleratedWidget cursor_widget = gfx::kNullAcceleratedWidget; - gfx::PointF location; - if (!window_map_.empty()) { - WidgetToWindowMap::iterator it = window_map_.begin(); - cursor_widget = it->first; - location = GetDefaultCursorLocation(it->second); - } - - cursor_->MoveCursorTo(cursor_widget, location); -} - -} // namespace ui
diff --git a/ui/ozone/platform/dri/dri_window_manager.h b/ui/ozone/platform/dri/dri_window_manager.h deleted file mode 100644 index 5a03957..0000000 --- a/ui/ozone/platform/dri/dri_window_manager.h +++ /dev/null
@@ -1,58 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_DRI_WINDOW_MANAGER_H_ -#define UI_OZONE_PLATFORM_DRI_DRI_WINDOW_MANAGER_H_ - -#include <map> - -#include "base/memory/scoped_ptr.h" -#include "ui/gfx/native_widget_types.h" - -namespace ui { - -class DriCursor; -class DriWindow; -class HardwareCursorDelegate; - -// Responsible for keeping the mapping between the allocated widgets and -// windows. -class DriWindowManager { - public: - explicit DriWindowManager(HardwareCursorDelegate* cursor_delegate); - ~DriWindowManager(); - - gfx::AcceleratedWidget NextAcceleratedWidget(); - - // Adds a window for |widget|. Note: |widget| should not be associated when - // calling this function. - void AddWindow(gfx::AcceleratedWidget widget, DriWindow* window); - - // Removes the window association for |widget|. Note: |widget| must be - // associated with a window when calling this function. - void RemoveWindow(gfx::AcceleratedWidget widget); - - // Returns the window associated with |widget|. Note: This function should - // only be called if a valid window has been associated. - DriWindow* GetWindow(gfx::AcceleratedWidget widget); - - DriCursor* cursor() const { return cursor_.get(); } - - private: - // Reset the cursor location based on the list of active windows. - void ResetCursorLocation(); - - typedef std::map<gfx::AcceleratedWidget, DriWindow*> WidgetToWindowMap; - - gfx::AcceleratedWidget last_allocated_widget_; - WidgetToWindowMap window_map_; - - scoped_ptr<DriCursor> cursor_; - - DISALLOW_COPY_AND_ASSIGN(DriWindowManager); -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_DRI_WINDOW_MANAGER_H_
diff --git a/ui/ozone/platform/dri/dri_wrapper.cc b/ui/ozone/platform/dri/dri_wrapper.cc deleted file mode 100644 index 7e80c3a..0000000 --- a/ui/ozone/platform/dri/dri_wrapper.cc +++ /dev/null
@@ -1,304 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/dri/dri_wrapper.h" - -#include <fcntl.h> -#include <sys/mman.h> -#include <unistd.h> -#include <xf86drm.h> -#include <xf86drmMode.h> - -#include "base/debug/trace_event.h" -#include "base/logging.h" -#include "base/stl_util.h" -#include "third_party/skia/include/core/SkImageInfo.h" -#include "ui/ozone/platform/dri/dri_util.h" - -namespace ui { - -namespace { - -uint32_t ToFixedPoint(double v) { - // This returns a number in a 16-bit.16-bit fixed point. - return v * 65536.0; -} - -bool DrmCreateDumbBuffer(int fd, - const SkImageInfo& info, - uint32_t* handle, - uint32_t* stride) { - struct drm_mode_create_dumb request; - memset(&request, 0, sizeof(request)); - request.width = info.width(); - request.height = info.height(); - request.bpp = info.bytesPerPixel() << 3; - request.flags = 0; - - if (drmIoctl(fd, DRM_IOCTL_MODE_CREATE_DUMB, &request) < 0) { - VLOG(2) << "Cannot create dumb buffer (" << errno << ") " - << strerror(errno); - return false; - } - - // The driver may choose to align the last row as well. We don't care about - // the last alignment bits since they aren't used for display purposes, so - // just check that the expected size is <= to what the driver allocated. - DCHECK_LE(info.getSafeSize(request.pitch), request.size); - - *handle = request.handle; - *stride = request.pitch; - return true; -} - -void DrmDestroyDumbBuffer(int fd, uint32_t handle) { - struct drm_mode_destroy_dumb destroy_request; - memset(&destroy_request, 0, sizeof(destroy_request)); - destroy_request.handle = handle; - drmIoctl(fd, DRM_IOCTL_MODE_DESTROY_DUMB, &destroy_request); -} - -} // namespace - -DriWrapper::DriWrapper(const char* device_path) - : fd_(-1), device_path_(device_path) { -} - -DriWrapper::~DriWrapper() { - if (fd_ >= 0) - close(fd_); -} - -void DriWrapper::Initialize() { - fd_ = open(device_path_, O_RDWR | O_CLOEXEC); - if (fd_ < 0) - PLOG(FATAL) << "open: " << device_path_; -} - -ScopedDrmCrtcPtr DriWrapper::GetCrtc(uint32_t crtc_id) { - DCHECK(fd_ >= 0); - return ScopedDrmCrtcPtr(drmModeGetCrtc(fd_, crtc_id)); -} - -bool DriWrapper::SetCrtc(uint32_t crtc_id, - uint32_t framebuffer, - std::vector<uint32_t> connectors, - drmModeModeInfo* mode) { - DCHECK(fd_ >= 0); - DCHECK(!connectors.empty()); - DCHECK(mode); - - TRACE_EVENT2("dri", - "DriWrapper::SetCrtc", - "crtc", - crtc_id, - "size", - gfx::Size(mode->hdisplay, mode->vdisplay).ToString()); - return !drmModeSetCrtc(fd_, - crtc_id, - framebuffer, - 0, - 0, - vector_as_array(&connectors), - connectors.size(), mode); -} - -bool DriWrapper::SetCrtc(drmModeCrtc* crtc, std::vector<uint32_t> connectors) { - DCHECK(fd_ >= 0); - // If there's no buffer then the CRTC was disabled. - if (!crtc->buffer_id) - return DisableCrtc(crtc->crtc_id); - - DCHECK(!connectors.empty()); - - TRACE_EVENT1("dri", "DriWrapper::RestoreCrtc", - "crtc", crtc->crtc_id); - return !drmModeSetCrtc(fd_, - crtc->crtc_id, - crtc->buffer_id, - crtc->x, - crtc->y, - vector_as_array(&connectors), - connectors.size(), - &crtc->mode); -} - -bool DriWrapper::DisableCrtc(uint32_t crtc_id) { - DCHECK(fd_ >= 0); - TRACE_EVENT1("dri", "DriWrapper::DisableCrtc", - "crtc", crtc_id); - return !drmModeSetCrtc(fd_, crtc_id, 0, 0, 0, NULL, 0, NULL); -} - -ScopedDrmConnectorPtr DriWrapper::GetConnector(uint32_t connector_id) { - DCHECK(fd_ >= 0); - TRACE_EVENT1("dri", "DriWrapper::GetConnector", "connector", connector_id); - return ScopedDrmConnectorPtr(drmModeGetConnector(fd_, connector_id)); -} - -bool DriWrapper::AddFramebuffer(uint32_t width, - uint32_t height, - uint8_t depth, - uint8_t bpp, - uint32_t stride, - uint32_t handle, - uint32_t* framebuffer) { - DCHECK(fd_ >= 0); - TRACE_EVENT1("dri", "DriWrapper::AddFramebuffer", - "handle", handle); - return !drmModeAddFB(fd_, - width, - height, - depth, - bpp, - stride, - handle, - framebuffer); -} - -bool DriWrapper::RemoveFramebuffer(uint32_t framebuffer) { - DCHECK(fd_ >= 0); - TRACE_EVENT1("dri", "DriWrapper::RemoveFramebuffer", - "framebuffer", framebuffer); - return !drmModeRmFB(fd_, framebuffer); -} - -bool DriWrapper::PageFlip(uint32_t crtc_id, - uint32_t framebuffer, - void* data) { - DCHECK(fd_ >= 0); - TRACE_EVENT2("dri", "DriWrapper::PageFlip", - "crtc", crtc_id, - "framebuffer", framebuffer); - return !drmModePageFlip(fd_, - crtc_id, - framebuffer, - DRM_MODE_PAGE_FLIP_EVENT, - data); -} - -bool DriWrapper::PageFlipOverlay(uint32_t crtc_id, - uint32_t framebuffer, - const gfx::Rect& location, - const gfx::RectF& source, - int overlay_plane) { - DCHECK(fd_ >= 0); - TRACE_EVENT2("dri", "DriWrapper::PageFlipOverlay", - "crtc", crtc_id, - "framebuffer", framebuffer); - return !drmModeSetPlane(fd_, - overlay_plane, - crtc_id, - framebuffer, - 0, - location.x(), - location.y(), - location.width(), - location.height(), - ToFixedPoint(source.x()), - ToFixedPoint(source.y()), - ToFixedPoint(source.width()), - ToFixedPoint(source.height())); -} - -ScopedDrmFramebufferPtr DriWrapper::GetFramebuffer(uint32_t framebuffer) { - DCHECK(fd_ >= 0); - TRACE_EVENT1("dri", "DriWrapper::GetFramebuffer", - "framebuffer", framebuffer); - return ScopedDrmFramebufferPtr(drmModeGetFB(fd_, framebuffer)); -} - -ScopedDrmPropertyPtr DriWrapper::GetProperty(drmModeConnector* connector, - const char* name) { - TRACE_EVENT2("dri", "DriWrapper::GetProperty", - "connector", connector->connector_id, - "name", name); - for (int i = 0; i < connector->count_props; ++i) { - ScopedDrmPropertyPtr property(drmModeGetProperty(fd_, connector->props[i])); - if (!property) - continue; - - if (strcmp(property->name, name) == 0) - return property.Pass(); - } - - return ScopedDrmPropertyPtr(); -} - -bool DriWrapper::SetProperty(uint32_t connector_id, - uint32_t property_id, - uint64_t value) { - DCHECK(fd_ >= 0); - return !drmModeConnectorSetProperty(fd_, connector_id, property_id, value); -} - -ScopedDrmPropertyBlobPtr DriWrapper::GetPropertyBlob( - drmModeConnector* connector, const char* name) { - DCHECK(fd_ >= 0); - TRACE_EVENT2("dri", "DriWrapper::GetPropertyBlob", - "connector", connector->connector_id, - "name", name); - for (int i = 0; i < connector->count_props; ++i) { - ScopedDrmPropertyPtr property(drmModeGetProperty(fd_, connector->props[i])); - if (!property) - continue; - - if (strcmp(property->name, name) == 0 && - property->flags & DRM_MODE_PROP_BLOB) - return ScopedDrmPropertyBlobPtr( - drmModeGetPropertyBlob(fd_, connector->prop_values[i])); - } - - return ScopedDrmPropertyBlobPtr(); -} - -bool DriWrapper::SetCursor(uint32_t crtc_id, - uint32_t handle, - const gfx::Size& size) { - DCHECK(fd_ >= 0); - TRACE_EVENT1("dri", "DriWrapper::SetCursor", "handle", handle); - return !drmModeSetCursor(fd_, crtc_id, handle, size.width(), size.height()); -} - -bool DriWrapper::MoveCursor(uint32_t crtc_id, const gfx::Point& point) { - DCHECK(fd_ >= 0); - return !drmModeMoveCursor(fd_, crtc_id, point.x(), point.y()); -} - -void DriWrapper::HandleEvent(drmEventContext& event) { - DCHECK(fd_ >= 0); - TRACE_EVENT0("dri", "DriWrapper::HandleEvent"); - drmHandleEvent(fd_, &event); -} - -bool DriWrapper::CreateDumbBuffer(const SkImageInfo& info, - uint32_t* handle, - uint32_t* stride, - void** pixels) { - DCHECK(fd_ >= 0); - - TRACE_EVENT0("dri", "DriWrapper::CreateDumbBuffer"); - if (!DrmCreateDumbBuffer(fd_, info, handle, stride)) - return false; - - if (!MapDumbBuffer(fd_, *handle, info.getSafeSize(*stride), pixels)) { - DrmDestroyDumbBuffer(fd_, *handle); - return false; - } - - return true; -} - -void DriWrapper::DestroyDumbBuffer(const SkImageInfo& info, - uint32_t handle, - uint32_t stride, - void* pixels) { - DCHECK(fd_ >= 0); - TRACE_EVENT1("dri", "DriWrapper::DestroyDumbBuffer", "handle", handle); - munmap(pixels, info.getSafeSize(stride)); - DrmDestroyDumbBuffer(fd_, handle); -} - - -} // namespace ui
diff --git a/ui/ozone/platform/dri/dri_wrapper.h b/ui/ozone/platform/dri/dri_wrapper.h deleted file mode 100644 index a555814..0000000 --- a/ui/ozone/platform/dri/dri_wrapper.h +++ /dev/null
@@ -1,149 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_DRI_WRAPPER_H_ -#define UI_OZONE_PLATFORM_DRI_DRI_WRAPPER_H_ - -#include <stdint.h> - -#include <vector> - -#include "base/macros.h" -#include "ui/gfx/overlay_transform.h" -#include "ui/gfx/rect.h" -#include "ui/gfx/rect_f.h" -#include "ui/ozone/platform/dri/scoped_drm_types.h" - -typedef struct _drmEventContext drmEventContext; -typedef struct _drmModeModeInfo drmModeModeInfo; - -struct SkImageInfo; - -namespace ui { - -// Wraps DRM calls into a nice interface. Used to provide different -// implementations of the DRM calls. For the actual implementation the DRM API -// would be called. In unit tests this interface would be stubbed. -class DriWrapper { - public: - DriWrapper(const char* device_path); - virtual ~DriWrapper(); - - // Open device. - virtual void Initialize(); - - // Get the CRTC state. This is generally used to save state before using the - // CRTC. When the user finishes using the CRTC, the user should restore the - // CRTC to it's initial state. Use |SetCrtc| to restore the state. - virtual ScopedDrmCrtcPtr GetCrtc(uint32_t crtc_id); - - // Used to configure CRTC with ID |crtc_id| to use the connector in - // |connectors|. The CRTC will be configured with mode |mode| and will display - // the framebuffer with ID |framebuffer|. Before being able to display the - // framebuffer, it should be registered with the CRTC using |AddFramebuffer|. - virtual bool SetCrtc(uint32_t crtc_id, - uint32_t framebuffer, - std::vector<uint32_t> connectors, - drmModeModeInfo* mode); - - // Used to set a specific configuration to the CRTC. Normally this function - // would be called with a CRTC saved state (from |GetCrtc|) to restore it to - // its original configuration. - virtual bool SetCrtc(drmModeCrtc* crtc, std::vector<uint32_t> connectors); - - virtual bool DisableCrtc(uint32_t crtc_id); - - // Returns the connector properties for |connector_id|. - virtual ScopedDrmConnectorPtr GetConnector(uint32_t connector_id); - - // Register a buffer with the CRTC. On successful registration, the CRTC will - // assign a framebuffer ID to |framebuffer|. - virtual bool AddFramebuffer(uint32_t width, - uint32_t height, - uint8_t depth, - uint8_t bpp, - uint32_t stride, - uint32_t handle, - uint32_t* framebuffer); - - // Deregister the given |framebuffer|. - virtual bool RemoveFramebuffer(uint32_t framebuffer); - - // Get the DRM details associated with |framebuffer|. - virtual ScopedDrmFramebufferPtr GetFramebuffer(uint32_t framebuffer); - - // Schedules a pageflip for CRTC |crtc_id|. This function will return - // immediately. Upon completion of the pageflip event, the CRTC will be - // displaying the buffer with ID |framebuffer| and will have a DRM event - // queued on |fd_|. |data| is a generic pointer to some information the user - // will receive when processing the pageflip event. - virtual bool PageFlip(uint32_t crtc_id, uint32_t framebuffer, void* data); - - // Schedule an overlay to be show during the page flip for CRTC |crtc_id|. - // |source| location from |framebuffer| will be shown on overlay - // |overlay_plane|, in the bounds specified by |location| on the screen. - virtual bool PageFlipOverlay(uint32_t crtc_id, - uint32_t framebuffer, - const gfx::Rect& location, - const gfx::RectF& source, - int overlay_plane); - - // Returns the property with name |name| associated with |connector|. Returns - // NULL if property not found. If the returned value is valid, it must be - // released using FreeProperty(). - virtual ScopedDrmPropertyPtr GetProperty(drmModeConnector* connector, - const char* name); - - // Sets the value of property with ID |property_id| to |value|. The property - // is applied to the connector with ID |connector_id|. - virtual bool SetProperty(uint32_t connector_id, - uint32_t property_id, - uint64_t value); - - // Return a binary blob associated with |connector|. The binary blob is - // associated with the property with name |name|. Return NULL if the property - // could not be found or if the property does not have a binary blob. If valid - // the returned object must be freed using FreePropertyBlob(). - virtual ScopedDrmPropertyBlobPtr GetPropertyBlob(drmModeConnector* connector, - const char* name); - - // Set the cursor to be displayed in CRTC |crtc_id|. (width, height) is the - // cursor size pointed by |handle|. - virtual bool SetCursor(uint32_t crtc_id, - uint32_t handle, - const gfx::Size& size); - - - // Move the cursor on CRTC |crtc_id| to (x, y); - virtual bool MoveCursor(uint32_t crtc_id, const gfx::Point& point); - - virtual void HandleEvent(drmEventContext& event); - - virtual bool CreateDumbBuffer(const SkImageInfo& info, - uint32_t* handle, - uint32_t* stride, - void** pixels); - - virtual void DestroyDumbBuffer(const SkImageInfo& info, - uint32_t handle, - uint32_t stride, - void* pixels); - - int get_fd() const { return fd_; } - - protected: - // The file descriptor associated with this wrapper. All DRM operations will - // be performed using this FD. - int fd_; - - private: - // Path to DRM device. - const char* device_path_; - - DISALLOW_COPY_AND_ASSIGN(DriWrapper); -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_DRI_WRAPPER_H_
diff --git a/ui/ozone/platform/dri/gbm.gypi b/ui/ozone/platform/dri/gbm.gypi deleted file mode 100644 index 088ecce..0000000 --- a/ui/ozone/platform/dri/gbm.gypi +++ /dev/null
@@ -1,50 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -{ - 'variables': { - 'internal_ozone_platform_deps': [ - 'ozone_platform_gbm', - ], - 'internal_ozone_platforms': [ - 'gbm', - ], - }, - 'targets': [ - { - 'target_name': 'ozone_platform_gbm', - 'type': 'static_library', - 'dependencies': [ - '../../base/base.gyp:base', - '../../build/linux/system.gyp:libdrm', - '../../build/linux/system.gyp:gbm', - '../../skia/skia.gyp:skia', - '../../third_party/khronos/khronos.gyp:khronos_headers', - '../base/ui_base.gyp:ui_base', - '../events/events.gyp:events', - '../events/ozone/events_ozone.gyp:events_ozone', - '../gfx/gfx.gyp:gfx', - ], - 'defines': [ - 'OZONE_IMPLEMENTATION', - ], - 'sources': [ - 'gbm_buffer.cc', - 'gbm_buffer.h', - 'gbm_buffer_base.cc', - 'gbm_buffer_base.h', - 'gbm_surface.cc', - 'gbm_surface.h', - 'gbm_surfaceless.cc', - 'gbm_surfaceless.h', - 'gbm_surface_factory.cc', - 'gbm_surface_factory.h', - 'native_display_delegate_proxy.cc', - 'native_display_delegate_proxy.h', - 'ozone_platform_gbm.cc', - 'ozone_platform_gbm.h', - ], - }, - ], -}
diff --git a/ui/ozone/platform/dri/gbm_buffer.cc b/ui/ozone/platform/dri/gbm_buffer.cc deleted file mode 100644 index 030dc3b..0000000 --- a/ui/ozone/platform/dri/gbm_buffer.cc +++ /dev/null
@@ -1,81 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/dri/gbm_buffer.h" - -#include <gbm.h> - -#include "base/logging.h" - -namespace ui { - -namespace { - -int GetGbmFormatFromBufferFormat(SurfaceFactoryOzone::BufferFormat fmt) { - switch (fmt) { - case SurfaceFactoryOzone::RGBA_8888: - return GBM_BO_FORMAT_ARGB8888; - case SurfaceFactoryOzone::RGBX_8888: - return GBM_BO_FORMAT_XRGB8888; - default: - NOTREACHED(); - return 0; - } -} - -} // namespace - -GbmBuffer::GbmBuffer(DriWrapper* dri, gbm_bo* bo, bool scanout) - : GbmBufferBase(dri, bo, scanout) { -} - -GbmBuffer::~GbmBuffer() { - if (bo()) - gbm_bo_destroy(bo()); -} - -// static -scoped_refptr<GbmBuffer> GbmBuffer::CreateBuffer( - DriWrapper* dri, - gbm_device* device, - SurfaceFactoryOzone::BufferFormat format, - const gfx::Size& size, - bool scanout) { - unsigned flags = GBM_BO_USE_RENDERING; - if (scanout) - flags |= GBM_BO_USE_SCANOUT; - gbm_bo* bo = gbm_bo_create(device, - size.width(), - size.height(), - GetGbmFormatFromBufferFormat(format), - flags); - if (!bo) - return NULL; - - scoped_refptr<GbmBuffer> buffer(new GbmBuffer(dri, bo, scanout)); - if (scanout && !buffer->GetFramebufferId()) - return NULL; - - return buffer; -} - -GbmPixmap::GbmPixmap(scoped_refptr<GbmBuffer> buffer) : buffer_(buffer) { -} - -GbmPixmap::~GbmPixmap() { -} - -void* GbmPixmap::GetEGLClientBuffer() { - return buffer_->bo(); -} - -int GbmPixmap::GetDmaBufFd() { - return -1; -} - -int GbmPixmap::GetDmaBufPitch() { - return -1; -} - -} // namespace ui
diff --git a/ui/ozone/platform/dri/gbm_buffer.h b/ui/ozone/platform/dri/gbm_buffer.h deleted file mode 100644 index 3fad2c5..0000000 --- a/ui/ozone/platform/dri/gbm_buffer.h +++ /dev/null
@@ -1,59 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_GBM_BUFFER_H_ -#define UI_OZONE_PLATFORM_DRI_GBM_BUFFER_H_ - -#include "base/macros.h" -#include "base/memory/scoped_ptr.h" -#include "ui/gfx/geometry/size.h" -#include "ui/ozone/platform/dri/gbm_buffer_base.h" -#include "ui/ozone/public/native_pixmap.h" -#include "ui/ozone/public/surface_factory_ozone.h" - -struct gbm_bo; -struct gbm_device; - -namespace ui { - -class DriWrapper; - -class GbmBuffer : public GbmBufferBase { - public: - static scoped_refptr<GbmBuffer> CreateBuffer( - DriWrapper* dri, - gbm_device* device, - SurfaceFactoryOzone::BufferFormat format, - const gfx::Size& size, - bool scanout); - - private: - GbmBuffer(DriWrapper* dri, gbm_bo* bo, bool scanout); - virtual ~GbmBuffer(); - - DISALLOW_COPY_AND_ASSIGN(GbmBuffer); -}; - -class GbmPixmap : public NativePixmap { - public: - GbmPixmap(scoped_refptr<GbmBuffer> buffer); - - // NativePixmap: - virtual void* GetEGLClientBuffer() override; - virtual int GetDmaBufFd() override; - virtual int GetDmaBufPitch() override; - - scoped_refptr<GbmBuffer> buffer() { return buffer_; } - - private: - virtual ~GbmPixmap(); - - scoped_refptr<GbmBuffer> buffer_; - - DISALLOW_COPY_AND_ASSIGN(GbmPixmap); -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_GBM_BUFFER_H_
diff --git a/ui/ozone/platform/dri/gbm_buffer_base.cc b/ui/ozone/platform/dri/gbm_buffer_base.cc deleted file mode 100644 index f5c057a..0000000 --- a/ui/ozone/platform/dri/gbm_buffer_base.cc +++ /dev/null
@@ -1,53 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/dri/gbm_buffer_base.h" - -#include <gbm.h> - -#include "base/logging.h" -#include "ui/ozone/platform/dri/dri_wrapper.h" - -namespace ui { - -namespace { - -// Pixel configuration for the current buffer format. -// TODO(dnicoara) These will need to change once we query the hardware for -// supported configurations. -const uint8_t kColorDepth = 24; -const uint8_t kPixelDepth = 32; - -} // namespace - -GbmBufferBase::GbmBufferBase(DriWrapper* dri, gbm_bo* bo, bool scanout) - : dri_(dri), bo_(bo), framebuffer_(0) { - if (scanout && !dri_->AddFramebuffer(gbm_bo_get_width(bo), - gbm_bo_get_height(bo), - kColorDepth, - kPixelDepth, - gbm_bo_get_stride(bo), - gbm_bo_get_handle(bo).u32, - &framebuffer_)) - LOG(ERROR) << "Failed to register buffer"; -} - -GbmBufferBase::~GbmBufferBase() { - if (framebuffer_) - dri_->RemoveFramebuffer(framebuffer_); -} - -uint32_t GbmBufferBase::GetFramebufferId() const { - return framebuffer_; -} - -uint32_t GbmBufferBase::GetHandle() const { - return gbm_bo_get_handle(bo_).u32; -} - -gfx::Size GbmBufferBase::GetSize() const { - return gfx::Size(gbm_bo_get_width(bo_), gbm_bo_get_height(bo_)); -} - -} // namespace ui
diff --git a/ui/ozone/platform/dri/gbm_buffer_base.h b/ui/ozone/platform/dri/gbm_buffer_base.h deleted file mode 100644 index 58ce159..0000000 --- a/ui/ozone/platform/dri/gbm_buffer_base.h +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_GBM_BUFFER_BASE_H_ -#define UI_OZONE_PLATFORM_DRI_GBM_BUFFER_BASE_H_ - -#include "ui/ozone/platform/dri/scanout_buffer.h" - -struct gbm_bo; - -namespace ui { - -class DriWrapper; - -// Wrapper for a GBM buffer. The base class provides common functionality -// required to prepare the buffer for scanout. It does not provide any ownership -// of the buffer. Implementations of this base class should deal with buffer -// ownership. -class GbmBufferBase : public ScanoutBuffer { - public: - gbm_bo* bo() const { return bo_; } - - // ScanoutBuffer: - virtual uint32_t GetFramebufferId() const override; - virtual uint32_t GetHandle() const override; - virtual gfx::Size GetSize() const override; - - protected: - GbmBufferBase(DriWrapper* dri, gbm_bo* bo, bool scanout); - virtual ~GbmBufferBase(); - - private: - DriWrapper* dri_; - gbm_bo* bo_; - uint32_t framebuffer_; - - DISALLOW_COPY_AND_ASSIGN(GbmBufferBase); -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_GBM_BUFFER_BASE_H_
diff --git a/ui/ozone/platform/dri/gbm_surface.cc b/ui/ozone/platform/dri/gbm_surface.cc deleted file mode 100644 index 18d00e6..0000000 --- a/ui/ozone/platform/dri/gbm_surface.cc +++ /dev/null
@@ -1,161 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/dri/gbm_surface.h" - -#include <gbm.h> - -#include "base/logging.h" -#include "ui/ozone/platform/dri/dri_buffer.h" -#include "ui/ozone/platform/dri/dri_window_delegate.h" -#include "ui/ozone/platform/dri/dri_wrapper.h" -#include "ui/ozone/platform/dri/gbm_buffer_base.h" -#include "ui/ozone/platform/dri/hardware_display_controller.h" -#include "ui/ozone/platform/dri/scanout_buffer.h" - -namespace ui { - -namespace { - -class GbmSurfaceBuffer : public GbmBufferBase { - public: - static scoped_refptr<GbmSurfaceBuffer> CreateBuffer(DriWrapper* dri, - gbm_bo* buffer); - static scoped_refptr<GbmSurfaceBuffer> GetBuffer(gbm_bo* buffer); - - private: - GbmSurfaceBuffer(DriWrapper* dri, gbm_bo* bo); - virtual ~GbmSurfaceBuffer(); - - static void Destroy(gbm_bo* buffer, void* data); - - // This buffer is special and is released by GBM at any point in time (as - // long as it isn't being used). Since GBM should be the only one to - // release this buffer, keep a self-reference in order to keep this alive. - // When GBM calls Destroy(..) the self-reference will dissapear and this will - // be destroyed. - scoped_refptr<GbmSurfaceBuffer> self_; - - DISALLOW_COPY_AND_ASSIGN(GbmSurfaceBuffer); -}; - -GbmSurfaceBuffer::GbmSurfaceBuffer(DriWrapper* dri, gbm_bo* bo) - : GbmBufferBase(dri, bo, true) { - if (GetFramebufferId()) { - self_ = this; - gbm_bo_set_user_data(bo, this, GbmSurfaceBuffer::Destroy); - } -} - -GbmSurfaceBuffer::~GbmSurfaceBuffer() {} - -// static -scoped_refptr<GbmSurfaceBuffer> GbmSurfaceBuffer::CreateBuffer( - DriWrapper* dri, gbm_bo* buffer) { - scoped_refptr<GbmSurfaceBuffer> scoped_buffer(new GbmSurfaceBuffer(dri, - buffer)); - if (!scoped_buffer->GetFramebufferId()) - return NULL; - - return scoped_buffer; -} - -// static -scoped_refptr<GbmSurfaceBuffer> GbmSurfaceBuffer::GetBuffer(gbm_bo* buffer) { - return scoped_refptr<GbmSurfaceBuffer>( - static_cast<GbmSurfaceBuffer*>(gbm_bo_get_user_data(buffer))); -} - -// static -void GbmSurfaceBuffer::Destroy(gbm_bo* buffer, void* data) { - GbmSurfaceBuffer* scoped_buffer = static_cast<GbmSurfaceBuffer*>(data); - scoped_buffer->self_ = NULL; -} - -} // namespace - -GbmSurface::GbmSurface(DriWindowDelegate* window_delegate, - gbm_device* device, - DriWrapper* dri) - : GbmSurfaceless(window_delegate), - gbm_device_(device), - dri_(dri), - native_surface_(NULL), - current_buffer_(NULL) { -} - -GbmSurface::~GbmSurface() { - if (current_buffer_) - gbm_surface_release_buffer(native_surface_, current_buffer_); - - if (native_surface_) - gbm_surface_destroy(native_surface_); -} - -bool GbmSurface::Initialize() { - // If we're initializing the surface without a controller (possible on startup - // where the surface creation can happen before the native window delegate - // IPCs arrive), initialize the size to a valid value such that surface - // creation doesn't fail. - gfx::Size size(1, 1); - if (window_delegate_->GetController()) { - size = window_delegate_->GetController()->GetModeSize(); - } - // TODO(dnicoara) Check underlying system support for pixel format. - native_surface_ = - gbm_surface_create(gbm_device_, - size.width(), - size.height(), - GBM_BO_FORMAT_XRGB8888, - GBM_BO_USE_SCANOUT | GBM_BO_USE_RENDERING); - - if (!native_surface_) - return false; - - size_ = size; - return true; -} - -intptr_t GbmSurface::GetNativeWindow() { - DCHECK(native_surface_); - return reinterpret_cast<intptr_t>(native_surface_); -} - -bool GbmSurface::ResizeNativeWindow(const gfx::Size& viewport_size) { - if (size_ == viewport_size) - return true; - - return false; -} - -bool GbmSurface::OnSwapBuffers() { - DCHECK(native_surface_); - - gbm_bo* pending_buffer = gbm_surface_lock_front_buffer(native_surface_); - scoped_refptr<GbmSurfaceBuffer> primary = - GbmSurfaceBuffer::GetBuffer(pending_buffer); - if (!primary.get()) { - primary = GbmSurfaceBuffer::CreateBuffer(dri_, pending_buffer); - if (!primary.get()) { - LOG(ERROR) << "Failed to associate the buffer with the controller"; - return false; - } - } - - // The primary buffer is a special case. - if (window_delegate_->GetController()) - window_delegate_->GetController()->QueueOverlayPlane(OverlayPlane(primary)); - - if (!GbmSurfaceless::OnSwapBuffers()) - return false; - - // If there was a frontbuffer, it is no longer active. Release it back to GBM. - if (current_buffer_) - gbm_surface_release_buffer(native_surface_, current_buffer_); - - current_buffer_ = pending_buffer; - return true; -} - -} // namespace ui
diff --git a/ui/ozone/platform/dri/gbm_surface.h b/ui/ozone/platform/dri/gbm_surface.h deleted file mode 100644 index ed54b31..0000000 --- a/ui/ozone/platform/dri/gbm_surface.h +++ /dev/null
@@ -1,59 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_GBM_SURFACE_H_ -#define UI_OZONE_PLATFORM_DRI_GBM_SURFACE_H_ - -#include "base/macros.h" -#include "ui/gfx/geometry/size.h" -#include "ui/ozone/platform/dri/gbm_surfaceless.h" -#include "ui/ozone/public/surface_ozone_egl.h" - -struct gbm_bo; -struct gbm_device; -struct gbm_surface; - -namespace ui { - -class DriBuffer; -class DriWrapper; -class DriWindowDelegate; - -// Extends the GBM surfaceless functionality and adds an implicit surface for -// the primary plane. Arbitrary buffers can still be allocated and displayed as -// overlay planes, however the primary plane is associated with the native -// surface and is updated via an EGLSurface. -class GbmSurface : public GbmSurfaceless { - public: - GbmSurface(DriWindowDelegate* window_delegate, - gbm_device* device, - DriWrapper* dri); - virtual ~GbmSurface(); - - bool Initialize(); - - // GbmSurfaceless: - virtual intptr_t GetNativeWindow() override; - virtual bool ResizeNativeWindow(const gfx::Size& viewport_size) override; - virtual bool OnSwapBuffers() override; - - private: - gbm_device* gbm_device_; - - DriWrapper* dri_; - - // The native GBM surface. In EGL this represents the EGLNativeWindowType. - gbm_surface* native_surface_; - - // Buffer currently used for scanout. - gbm_bo* current_buffer_; - - gfx::Size size_; - - DISALLOW_COPY_AND_ASSIGN(GbmSurface); -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_GBM_SURFACE_H_
diff --git a/ui/ozone/platform/dri/gbm_surface_factory.cc b/ui/ozone/platform/dri/gbm_surface_factory.cc deleted file mode 100644 index e04ae8e..0000000 --- a/ui/ozone/platform/dri/gbm_surface_factory.cc +++ /dev/null
@@ -1,231 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/dri/gbm_surface_factory.h" - -#include <gbm.h> - -#include "base/command_line.h" -#include "base/files/file_path.h" -#include "third_party/khronos/EGL/egl.h" -#include "ui/ozone/platform/dri/dri_window_delegate_impl.h" -#include "ui/ozone/platform/dri/dri_window_delegate_manager.h" -#include "ui/ozone/platform/dri/gbm_buffer.h" -#include "ui/ozone/platform/dri/gbm_surface.h" -#include "ui/ozone/platform/dri/gbm_surfaceless.h" -#include "ui/ozone/platform/dri/screen_manager.h" -#include "ui/ozone/public/native_pixmap.h" -#include "ui/ozone/public/overlay_candidates_ozone.h" -#include "ui/ozone/public/ozone_switches.h" -#include "ui/ozone/public/surface_ozone_egl.h" - -namespace ui { -namespace { - -class SingleOverlay : public OverlayCandidatesOzone { - public: - SingleOverlay() {} - virtual ~SingleOverlay() {} - - virtual void CheckOverlaySupport( - OverlaySurfaceCandidateList* candidates) override { - if (candidates->size() == 2) { - OverlayCandidatesOzone::OverlaySurfaceCandidate* first = - &(*candidates)[0]; - OverlayCandidatesOzone::OverlaySurfaceCandidate* second = - &(*candidates)[1]; - OverlayCandidatesOzone::OverlaySurfaceCandidate* overlay; - if (first->plane_z_order == 0) { - overlay = second; - } else if (second->plane_z_order == 0) { - overlay = first; - } else { - NOTREACHED(); - return; - } - if (overlay->plane_z_order > 0 && - IsTransformSupported(overlay->transform)) { - overlay->overlay_handled = true; - } - } - } - - private: - bool IsTransformSupported(gfx::OverlayTransform transform) { - switch (transform) { - case gfx::OVERLAY_TRANSFORM_NONE: - return true; - default: - return false; - } - } - - DISALLOW_COPY_AND_ASSIGN(SingleOverlay); -}; - -} // namespace - -GbmSurfaceFactory::GbmSurfaceFactory(bool allow_surfaceless) - : DriSurfaceFactory(NULL, NULL, NULL), - device_(NULL), - allow_surfaceless_(allow_surfaceless) { -} - -GbmSurfaceFactory::~GbmSurfaceFactory() {} - -void GbmSurfaceFactory::InitializeGpu( - DriWrapper* dri, - gbm_device* device, - ScreenManager* screen_manager, - DriWindowDelegateManager* window_manager) { - drm_ = dri; - device_ = device; - screen_manager_ = screen_manager; - window_manager_ = window_manager; -} - -intptr_t GbmSurfaceFactory::GetNativeDisplay() { - DCHECK(state_ == INITIALIZED); - return reinterpret_cast<intptr_t>(device_); -} - -const int32* GbmSurfaceFactory::GetEGLSurfaceProperties( - const int32* desired_list) { - static const int32 kConfigAttribs[] = { - EGL_BUFFER_SIZE, 32, - EGL_ALPHA_SIZE, 8, - EGL_BLUE_SIZE, 8, - EGL_GREEN_SIZE, 8, - EGL_RED_SIZE, 8, - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, - EGL_SURFACE_TYPE, EGL_WINDOW_BIT, - EGL_NONE - }; - - return kConfigAttribs; -} - -bool GbmSurfaceFactory::LoadEGLGLES2Bindings( - AddGLLibraryCallback add_gl_library, - SetGLGetProcAddressProcCallback set_gl_get_proc_address) { - base::NativeLibraryLoadError error; - base::NativeLibrary gles_library = base::LoadNativeLibrary( - base::FilePath("libGLESv2.so.2"), - &error); - if (!gles_library) { - LOG(WARNING) << "Failed to load GLES library: " << error.ToString(); - return false; - } - - base::NativeLibrary egl_library = base::LoadNativeLibrary( - base::FilePath("libEGL.so.1"), - &error); - if (!egl_library) { - LOG(WARNING) << "Failed to load EGL library: " << error.ToString(); - base::UnloadNativeLibrary(gles_library); - return false; - } - - GLGetProcAddressProc get_proc_address = - reinterpret_cast<GLGetProcAddressProc>( - base::GetFunctionPointerFromNativeLibrary( - egl_library, "eglGetProcAddress")); - if (!get_proc_address) { - LOG(ERROR) << "eglGetProcAddress not found."; - base::UnloadNativeLibrary(egl_library); - base::UnloadNativeLibrary(gles_library); - return false; - } - - set_gl_get_proc_address.Run(get_proc_address); - add_gl_library.Run(egl_library); - add_gl_library.Run(gles_library); - - return true; -} - -scoped_ptr<SurfaceOzoneEGL> GbmSurfaceFactory::CreateEGLSurfaceForWidget( - gfx::AcceleratedWidget widget) { - DCHECK(state_ == INITIALIZED); - - DriWindowDelegate* delegate = GetOrCreateWindowDelegate(widget); - - scoped_ptr<GbmSurface> surface(new GbmSurface(delegate, device_, drm_)); - if (!surface->Initialize()) - return nullptr; - - return surface.Pass(); -} - -scoped_ptr<SurfaceOzoneEGL> -GbmSurfaceFactory::CreateSurfacelessEGLSurfaceForWidget( - gfx::AcceleratedWidget widget) { - if (!allow_surfaceless_) - return scoped_ptr<SurfaceOzoneEGL>(); - - DriWindowDelegate* delegate = GetOrCreateWindowDelegate(widget); - return scoped_ptr<SurfaceOzoneEGL>(new GbmSurfaceless(delegate)); -} - -scoped_refptr<ui::NativePixmap> GbmSurfaceFactory::CreateNativePixmap( - gfx::Size size, - BufferFormat format) { - scoped_refptr<GbmBuffer> buffer = GbmBuffer::CreateBuffer( - drm_, device_, format, size, true); - if (!buffer.get()) - return NULL; - - return scoped_refptr<GbmPixmap>(new GbmPixmap(buffer)); -} - -OverlayCandidatesOzone* GbmSurfaceFactory::GetOverlayCandidates( - gfx::AcceleratedWidget w) { - if (CommandLine::ForCurrentProcess()->HasSwitch( - switches::kOzoneTestSingleOverlaySupport)) - return new SingleOverlay(); - return NULL; -} - -bool GbmSurfaceFactory::ScheduleOverlayPlane( - gfx::AcceleratedWidget widget, - int plane_z_order, - gfx::OverlayTransform plane_transform, - scoped_refptr<NativePixmap> buffer, - const gfx::Rect& display_bounds, - const gfx::RectF& crop_rect) { - scoped_refptr<GbmPixmap> pixmap = static_cast<GbmPixmap*>(buffer.get()); - if (!pixmap.get()) { - LOG(ERROR) << "ScheduleOverlayPlane passed NULL buffer."; - return false; - } - HardwareDisplayController* hdc = - window_manager_->GetWindowDelegate(widget)->GetController(); - if (!hdc) - return true; - - hdc->QueueOverlayPlane(OverlayPlane(pixmap->buffer(), - plane_z_order, - plane_transform, - display_bounds, - crop_rect)); - return true; -} - -bool GbmSurfaceFactory::CanShowPrimaryPlaneAsOverlay() { - return allow_surfaceless_; -} - -DriWindowDelegate* GbmSurfaceFactory::GetOrCreateWindowDelegate( - gfx::AcceleratedWidget widget) { - if (!window_manager_->HasWindowDelegate(widget)) { - scoped_ptr<DriWindowDelegate> delegate( - new DriWindowDelegateImpl(widget, screen_manager_)); - delegate->Initialize(); - window_manager_->AddWindowDelegate(widget, delegate.Pass()); - } - - return window_manager_->GetWindowDelegate(widget); -} - -} // namespace ui
diff --git a/ui/ozone/platform/dri/gbm_surface_factory.h b/ui/ozone/platform/dri/gbm_surface_factory.h deleted file mode 100644 index 786f77d..0000000 --- a/ui/ozone/platform/dri/gbm_surface_factory.h +++ /dev/null
@@ -1,62 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_GBM_SURFACE_FACTORY_H_ -#define UI_OZONE_PLATFORM_DRI_GBM_SURFACE_FACTORY_H_ - -#include "ui/ozone/platform/dri/dri_surface_factory.h" - -struct gbm_device; - -namespace ui { - -class DriWindowDelegate; -class DriWindowDelegateManager; - -class GbmSurfaceFactory : public DriSurfaceFactory { - public: - GbmSurfaceFactory(bool allow_surfaceless); - virtual ~GbmSurfaceFactory(); - - void InitializeGpu(DriWrapper* dri, - gbm_device* device, - ScreenManager* screen_manager, - DriWindowDelegateManager* window_manager); - - // DriSurfaceFactory: - virtual intptr_t GetNativeDisplay() override; - virtual const int32_t* GetEGLSurfaceProperties( - const int32_t* desired_list) override; - virtual bool LoadEGLGLES2Bindings( - AddGLLibraryCallback add_gl_library, - SetGLGetProcAddressProcCallback set_gl_get_proc_address) override; - virtual scoped_ptr<ui::SurfaceOzoneEGL> CreateEGLSurfaceForWidget( - gfx::AcceleratedWidget w) override; - virtual scoped_ptr<SurfaceOzoneEGL> CreateSurfacelessEGLSurfaceForWidget( - gfx::AcceleratedWidget widget) override; - virtual scoped_refptr<ui::NativePixmap> CreateNativePixmap( - gfx::Size size, - BufferFormat format) override; - virtual OverlayCandidatesOzone* GetOverlayCandidates( - gfx::AcceleratedWidget w) override; - virtual bool ScheduleOverlayPlane(gfx::AcceleratedWidget widget, - int plane_z_order, - gfx::OverlayTransform plane_transform, - scoped_refptr<NativePixmap> buffer, - const gfx::Rect& display_bounds, - const gfx::RectF& crop_rect) override; - virtual bool CanShowPrimaryPlaneAsOverlay() override; - - private: - DriWindowDelegate* GetOrCreateWindowDelegate(gfx::AcceleratedWidget widget); - - gbm_device* device_; // Not owned. - bool allow_surfaceless_; - - DISALLOW_COPY_AND_ASSIGN(GbmSurfaceFactory); -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_GBM_SURFACE_FACTORY_H_
diff --git a/ui/ozone/platform/dri/gbm_surfaceless.cc b/ui/ozone/platform/dri/gbm_surfaceless.cc deleted file mode 100644 index b374844..0000000 --- a/ui/ozone/platform/dri/gbm_surfaceless.cc +++ /dev/null
@@ -1,45 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/dri/gbm_surfaceless.h" - -#include "ui/ozone/platform/dri/dri_vsync_provider.h" -#include "ui/ozone/platform/dri/dri_window_delegate.h" -#include "ui/ozone/platform/dri/gbm_buffer.h" -#include "ui/ozone/platform/dri/hardware_display_controller.h" - -namespace ui { - -GbmSurfaceless::GbmSurfaceless(DriWindowDelegate* window_delegate) - : window_delegate_(window_delegate) { -} - -GbmSurfaceless::~GbmSurfaceless() {} - -intptr_t GbmSurfaceless::GetNativeWindow() { - NOTREACHED(); - return 0; -} - -bool GbmSurfaceless::ResizeNativeWindow(const gfx::Size& viewport_size) { - NOTIMPLEMENTED(); - return false; -} - -bool GbmSurfaceless::OnSwapBuffers() { - HardwareDisplayController* controller = window_delegate_->GetController(); - if (!controller) - return true; - - bool success = controller->SchedulePageFlip(); - controller->WaitForPageFlipEvent(); - - return success; -} - -scoped_ptr<gfx::VSyncProvider> GbmSurfaceless::CreateVSyncProvider() { - return scoped_ptr<gfx::VSyncProvider>(new DriVSyncProvider(window_delegate_)); -} - -} // namespace ui
diff --git a/ui/ozone/platform/dri/gbm_surfaceless.h b/ui/ozone/platform/dri/gbm_surfaceless.h deleted file mode 100644 index d30b7a4..0000000 --- a/ui/ozone/platform/dri/gbm_surfaceless.h +++ /dev/null
@@ -1,41 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_GBM_SURFACELESS_H_ -#define UI_OZONE_PLATFORM_DRI_GBM_SURFACELESS_H_ - -#include "ui/ozone/public/surface_ozone_egl.h" - -namespace gfx { -class Size; -} // namespace gfx - -namespace ui { - -class DriWindowDelegate; - -// In surfaceless mode drawing and displaying happens directly through -// NativePixmap buffers. CC would call into SurfaceFactoryOzone to allocate the -// buffers and then call ScheduleOverlayPlane(..) to schedule the buffer for -// presentation. -class GbmSurfaceless : public SurfaceOzoneEGL { - public: - GbmSurfaceless(DriWindowDelegate* window_delegate); - virtual ~GbmSurfaceless(); - - // SurfaceOzoneEGL: - virtual intptr_t GetNativeWindow() override; - virtual bool ResizeNativeWindow(const gfx::Size& viewport_size) override; - virtual bool OnSwapBuffers() override; - virtual scoped_ptr<gfx::VSyncProvider> CreateVSyncProvider() override; - - protected: - DriWindowDelegate* window_delegate_; - - DISALLOW_COPY_AND_ASSIGN(GbmSurfaceless); -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_GBM_SURFACELESS_H_
diff --git a/ui/ozone/platform/dri/hardware_cursor_delegate.h b/ui/ozone/platform/dri/hardware_cursor_delegate.h deleted file mode 100644 index ed2a348..0000000 --- a/ui/ozone/platform/dri/hardware_cursor_delegate.h +++ /dev/null
@@ -1,39 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_HARDWARE_CURSOR_DELEGATE_H_ -#define UI_OZONE_PLATFORM_DRI_HARDWARE_CURSOR_DELEGATE_H_ - -#include <vector> - -#include "ui/gfx/native_widget_types.h" - -class SkBitmap; - -namespace gfx { -class Point; -} - -namespace ui { - -class HardwareCursorDelegate { - public: - // Update the HW cursor bitmap & move to specified location. If - // the bitmap is empty, the cursor is hidden. - virtual void SetHardwareCursor(gfx::AcceleratedWidget widget, - const std::vector<SkBitmap>& bitmaps, - const gfx::Point& location, - int frame_delay_ms) = 0; - - // Move the HW cursor to the specified location. - virtual void MoveHardwareCursor(gfx::AcceleratedWidget widget, - const gfx::Point& location) = 0; - - protected: - virtual ~HardwareCursorDelegate() {} -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_HARDWARE_CURSOR_DELEGATE_H_
diff --git a/ui/ozone/platform/dri/hardware_display_controller.cc b/ui/ozone/platform/dri/hardware_display_controller.cc deleted file mode 100644 index ee4e4a9..0000000 --- a/ui/ozone/platform/dri/hardware_display_controller.cc +++ /dev/null
@@ -1,219 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/dri/hardware_display_controller.h" - -#include <drm.h> -#include <errno.h> -#include <string.h> -#include <xf86drm.h> - -#include "base/basictypes.h" -#include "base/debug/trace_event.h" -#include "base/logging.h" -#include "third_party/skia/include/core/SkCanvas.h" -#include "ui/gfx/geometry/point.h" -#include "ui/gfx/geometry/size.h" -#include "ui/ozone/platform/dri/crtc_controller.h" -#include "ui/ozone/platform/dri/dri_buffer.h" -#include "ui/ozone/platform/dri/dri_wrapper.h" -#include "ui/ozone/public/native_pixmap.h" - -namespace ui { - -namespace { - -// DRM callback on page flip events. This callback is triggered after the -// page flip has happened and the backbuffer is now the new frontbuffer -// The old frontbuffer is no longer used by the hardware and can be used for -// future draw operations. -// -// |device| will contain a reference to the |ScanoutSurface| object which -// the event belongs to. -// -// TODO(dnicoara) When we have a FD handler for the DRM calls in the message -// loop, we can move this function in the handler. -void HandlePageFlipEvent(int fd, - unsigned int frame, - unsigned int seconds, - unsigned int useconds, - void* controller) { - static_cast<CrtcController*>(controller) - ->OnPageFlipEvent(frame, seconds, useconds); -} - -} // namespace - -HardwareDisplayController::HardwareDisplayController( - scoped_ptr<CrtcController> controller) - : is_disabled_(true) { - crtc_controllers_.push_back(controller.release()); -} - -HardwareDisplayController::~HardwareDisplayController() { - // Reset the cursor. - UnsetCursor(); -} - -bool HardwareDisplayController::Modeset(const OverlayPlane& primary, - drmModeModeInfo mode) { - TRACE_EVENT0("dri", "HDC::Modeset"); - DCHECK(primary.buffer.get()); - bool status = true; - for (size_t i = 0; i < crtc_controllers_.size(); ++i) - status &= crtc_controllers_[i]->Modeset(primary, mode); - - current_planes_ = std::vector<OverlayPlane>(1, primary); - pending_planes_.clear(); - is_disabled_ = false; - mode_ = mode; - return status; -} - -bool HardwareDisplayController::Enable() { - TRACE_EVENT0("dri", "HDC::Enable"); - DCHECK(!current_planes_.empty()); - OverlayPlane primary = OverlayPlane::GetPrimaryPlane(current_planes_); - DCHECK(primary.buffer.get()); - bool status = true; - for (size_t i = 0; i < crtc_controllers_.size(); ++i) - status &= crtc_controllers_[i]->Modeset(primary, mode_); - - return status; -} - -void HardwareDisplayController::Disable() { - TRACE_EVENT0("dri", "HDC::Disable"); - for (size_t i = 0; i < crtc_controllers_.size(); ++i) - crtc_controllers_[i]->Disable(); - - is_disabled_ = true; -} - -void HardwareDisplayController::QueueOverlayPlane(const OverlayPlane& plane) { - pending_planes_.push_back(plane); -} - -bool HardwareDisplayController::SchedulePageFlip() { - DCHECK(!pending_planes_.empty()); - - if (is_disabled_) - return true; - - bool status = true; - for (size_t i = 0; i < crtc_controllers_.size(); ++i) - status &= crtc_controllers_[i]->SchedulePageFlip(pending_planes_); - - return status; -} - -void HardwareDisplayController::WaitForPageFlipEvent() { - TRACE_EVENT0("dri", "HDC::WaitForPageFlipEvent"); - - drmEventContext drm_event; - drm_event.version = DRM_EVENT_CONTEXT_VERSION; - drm_event.page_flip_handler = HandlePageFlipEvent; - drm_event.vblank_handler = NULL; - - bool has_pending_page_flips = false; - // Wait for the page-flips to complete. - for (size_t i = 0; i < crtc_controllers_.size(); ++i) { - // In mirror mode the page flip callbacks can happen in different order than - // scheduled, so we need to make sure that the event for the current CRTC is - // processed before moving to the next CRTC. - while (crtc_controllers_[i]->page_flip_pending()) { - has_pending_page_flips = true; - crtc_controllers_[i]->drm()->HandleEvent(drm_event); - } - } - - // In case there are no pending pageflips do not replace the current planes - // since they are still being used. - if (has_pending_page_flips) - current_planes_.swap(pending_planes_); - - pending_planes_.clear(); -} - -bool HardwareDisplayController::SetCursor( - const scoped_refptr<ScanoutBuffer>& buffer) { - bool status = true; - - if (is_disabled_) - return true; - - for (size_t i = 0; i < crtc_controllers_.size(); ++i) - status &= crtc_controllers_[i]->SetCursor(buffer); - - return status; -} - -bool HardwareDisplayController::UnsetCursor() { - bool status = true; - for (size_t i = 0; i < crtc_controllers_.size(); ++i) - status &= crtc_controllers_[i]->UnsetCursor(); - - return status; -} - -bool HardwareDisplayController::MoveCursor(const gfx::Point& location) { - if (is_disabled_) - return true; - - bool status = true; - for (size_t i = 0; i < crtc_controllers_.size(); ++i) - status &= crtc_controllers_[i]->MoveCursor(location); - - return status; -} - -void HardwareDisplayController::AddCrtc(scoped_ptr<CrtcController> controller) { - crtc_controllers_.push_back(controller.release()); -} - -scoped_ptr<CrtcController> HardwareDisplayController::RemoveCrtc( - uint32_t crtc) { - for (ScopedVector<CrtcController>::iterator it = crtc_controllers_.begin(); - it != crtc_controllers_.end(); - ++it) { - if ((*it)->crtc() == crtc) { - scoped_ptr<CrtcController> controller(*it); - crtc_controllers_.weak_erase(it); - return controller.Pass(); - } - } - - return scoped_ptr<CrtcController>(); -} - -bool HardwareDisplayController::HasCrtc(uint32_t crtc) const { - for (size_t i = 0; i < crtc_controllers_.size(); ++i) - if (crtc_controllers_[i]->crtc() == crtc) - return true; - - return false; -} - -bool HardwareDisplayController::IsMirrored() const { - return crtc_controllers_.size() > 1; -} - -bool HardwareDisplayController::IsDisabled() const { - return is_disabled_; -} - -gfx::Size HardwareDisplayController::GetModeSize() const { - return gfx::Size(mode_.hdisplay, mode_.vdisplay); -} - -uint64_t HardwareDisplayController::GetTimeOfLastFlip() const { - uint64_t time = 0; - for (size_t i = 0; i < crtc_controllers_.size(); ++i) - if (time < crtc_controllers_[i]->time_of_last_flip()) - time = crtc_controllers_[i]->time_of_last_flip(); - - return time; -} - -} // namespace ui
diff --git a/ui/ozone/platform/dri/hardware_display_controller.h b/ui/ozone/platform/dri/hardware_display_controller.h deleted file mode 100644 index 3a948f6..0000000 --- a/ui/ozone/platform/dri/hardware_display_controller.h +++ /dev/null
@@ -1,169 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_HARDWARE_DISPLAY_CONTROLLER_H_ -#define UI_OZONE_PLATFORM_DRI_HARDWARE_DISPLAY_CONTROLLER_H_ - -#include <stddef.h> -#include <stdint.h> -#include <xf86drmMode.h> -#include <vector> - -#include "base/basictypes.h" -#include "base/memory/scoped_ptr.h" -#include "base/memory/scoped_vector.h" -#include "base/memory/weak_ptr.h" -#include "ui/ozone/platform/dri/overlay_plane.h" - -namespace gfx { -class Point; -} - -namespace ui { - -class CrtcController; -class ScanoutBuffer; - -// The HDCOz will handle modesettings and scannout operations for hardware -// devices. -// -// In the DRM world there are 3 components that need to be paired up to be able -// to display an image to the monitor: CRTC (cathode ray tube controller), -// encoder and connector. The CRTC determines which framebuffer to read, when -// to scanout and where to scanout. Encoders converts the stream from the CRTC -// to the appropriate format for the connector. The connector is the physical -// connection that monitors connect to. -// -// There is no 1:1:1 pairing for these components. It is possible for an encoder -// to be compatible to multiple CRTCs and each connector can be used with -// multiple encoders. In addition, it is possible to use one CRTC with multiple -// connectors such that we can display the same image on multiple monitors. -// -// For example, the following configuration shows 2 different screens being -// initialized separately. -// ------------- ------------- -// | Connector | | Connector | -// | HDMI | | VGA | -// ------------- ------------- -// ^ ^ -// | | -// ------------- ------------- -// | Encoder1 | | Encoder2 | -// ------------- ------------- -// ^ ^ -// | | -// ------------- ------------- -// | CRTC1 | | CRTC2 | -// ------------- ------------- -// -// In the following configuration 2 different screens are associated with the -// same CRTC, so on scanout the same framebuffer will be displayed on both -// monitors. -// ------------- ------------- -// | Connector | | Connector | -// | HDMI | | VGA | -// ------------- ------------- -// ^ ^ -// | | -// ------------- ------------- -// | Encoder1 | | Encoder2 | -// ------------- ------------- -// ^ ^ -// | | -// ---------------------- -// | CRTC1 | -// ---------------------- -// -// Note that it is possible to have more connectors than CRTCs which means that -// only a subset of connectors can be active independently, showing different -// framebuffers. Though, in this case, it would be possible to have all -// connectors active if some use the same CRTC to mirror the display. -class HardwareDisplayController - : public base::SupportsWeakPtr<HardwareDisplayController> { - public: - explicit HardwareDisplayController(scoped_ptr<CrtcController> controller); - ~HardwareDisplayController(); - - // Performs the initial CRTC configuration. If successful, it will display the - // framebuffer for |primary| with |mode|. - bool Modeset(const OverlayPlane& primary, - drmModeModeInfo mode); - - // Reconfigures the CRTC with the current surface and mode. - bool Enable(); - - // Disables the CRTC. - void Disable(); - - void QueueOverlayPlane(const OverlayPlane& plane); - - // Schedules the |overlays|' framebuffers to be displayed on the next vsync - // event. The event will be posted on the graphics card file descriptor |fd_| - // and it can be read and processed by |drmHandleEvent|. That function can - // define the callback for the page flip event. A generic data argument will - // be presented to the callback. We use that argument to pass in the HDCO - // object the event belongs to. - // - // Between this call and the callback, the framebuffers used in this call - // should not be modified in any way as it would cause screen tearing if the - // hardware performed the flip. Note that the frontbuffer should also not - // be modified as it could still be displayed. - // - // Note that this function does not block. Also, this function should not be - // called again before the page flip occurrs. - // - // Returns true if the page flip was successfully registered, false otherwise. - bool SchedulePageFlip(); - - // TODO(dnicoara) This should be on the MessageLoop when Ozone can have - // BeginFrame can be triggered explicitly by Ozone. - void WaitForPageFlipEvent(); - - // Set the hardware cursor to show the contents of |surface|. - bool SetCursor(const scoped_refptr<ScanoutBuffer>& buffer); - - bool UnsetCursor(); - - // Moves the hardware cursor to |location|. - bool MoveCursor(const gfx::Point& location); - - void AddCrtc(scoped_ptr<CrtcController> controller); - scoped_ptr<CrtcController> RemoveCrtc(uint32_t crtc); - bool HasCrtc(uint32_t crtc) const; - bool IsMirrored() const; - bool IsDisabled() const; - gfx::Size GetModeSize() const; - - gfx::Point origin() const { return origin_; } - void set_origin(const gfx::Point& origin) { origin_ = origin; } - - const drmModeModeInfo& get_mode() const { return mode_; }; - - uint64_t GetTimeOfLastFlip() const; - - private: - // Buffers need to be declared first so that they are destroyed last. Needed - // since the controllers may reference the buffers. - OverlayPlaneList current_planes_; - OverlayPlaneList pending_planes_; - scoped_refptr<ScanoutBuffer> cursor_buffer_; - - // Stores the CRTC configuration. This is used to identify monitors and - // configure them. - ScopedVector<CrtcController> crtc_controllers_; - - // Location of the controller on the screen. - gfx::Point origin_; - - // The mode used by the last modesetting operation. - drmModeModeInfo mode_; - - bool is_disabled_; - - DISALLOW_COPY_AND_ASSIGN(HardwareDisplayController); -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_HARDWARE_DISPLAY_CONTROLLER_H_
diff --git a/ui/ozone/platform/dri/hardware_display_controller_unittest.cc b/ui/ozone/platform/dri/hardware_display_controller_unittest.cc deleted file mode 100644 index ded4cfe..0000000 --- a/ui/ozone/platform/dri/hardware_display_controller_unittest.cc +++ /dev/null
@@ -1,219 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "testing/gtest/include/gtest/gtest.h" -#include "third_party/skia/include/core/SkCanvas.h" -#include "ui/ozone/platform/dri/crtc_controller.h" -#include "ui/ozone/platform/dri/dri_buffer.h" -#include "ui/ozone/platform/dri/dri_wrapper.h" -#include "ui/ozone/platform/dri/hardware_display_controller.h" -#include "ui/ozone/platform/dri/test/mock_dri_wrapper.h" -#include "ui/ozone/public/native_pixmap.h" - -namespace { - -// Create a basic mode for a 6x4 screen. -const drmModeModeInfo kDefaultMode = - {0, 6, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, {'\0'}}; - -const uint32_t kPrimaryCrtc = 1; -const uint32_t kPrimaryConnector = 2; -const uint32_t kSecondaryCrtc = 3; -const uint32_t kSecondaryConnector = 4; - -const gfx::Size kDefaultModeSize(kDefaultMode.hdisplay, kDefaultMode.vdisplay); -const gfx::SizeF kDefaultModeSizeF(1.0, 1.0); - -class MockScanoutBuffer : public ui::ScanoutBuffer { - public: - MockScanoutBuffer(const gfx::Size& size) : size_(size) {} - - // ScanoutBuffer: - virtual uint32_t GetFramebufferId() const override {return 0; } - virtual uint32_t GetHandle() const override { return 0; } - virtual gfx::Size GetSize() const override { return size_; } - - private: - virtual ~MockScanoutBuffer() {} - - gfx::Size size_; - - DISALLOW_COPY_AND_ASSIGN(MockScanoutBuffer); -}; - -} // namespace - -class HardwareDisplayControllerTest : public testing::Test { - public: - HardwareDisplayControllerTest() {} - virtual ~HardwareDisplayControllerTest() {} - - virtual void SetUp() override; - virtual void TearDown() override; - protected: - scoped_ptr<ui::HardwareDisplayController> controller_; - scoped_ptr<ui::MockDriWrapper> drm_; - - private: - DISALLOW_COPY_AND_ASSIGN(HardwareDisplayControllerTest); -}; - -void HardwareDisplayControllerTest::SetUp() { - drm_.reset(new ui::MockDriWrapper(3)); - controller_.reset(new ui::HardwareDisplayController( - scoped_ptr<ui::CrtcController>(new ui::CrtcController( - drm_.get(), kPrimaryCrtc, kPrimaryConnector)))); -} - -void HardwareDisplayControllerTest::TearDown() { - controller_.reset(); - drm_.reset(); -} - -TEST_F(HardwareDisplayControllerTest, CheckModesettingResult) { - ui::OverlayPlane plane(scoped_refptr<ui::ScanoutBuffer>( - new MockScanoutBuffer(kDefaultModeSize))); - - EXPECT_TRUE(controller_->Modeset(plane, kDefaultMode)); - EXPECT_FALSE(plane.buffer->HasOneRef()); -} - -TEST_F(HardwareDisplayControllerTest, CheckStateAfterPageFlip) { - ui::OverlayPlane plane1(scoped_refptr<ui::ScanoutBuffer>( - new MockScanoutBuffer(kDefaultModeSize))); - - EXPECT_TRUE(controller_->Modeset(plane1, kDefaultMode)); - - ui::OverlayPlane plane2(scoped_refptr<ui::ScanoutBuffer>( - new MockScanoutBuffer(kDefaultModeSize))); - controller_->QueueOverlayPlane(plane2); - EXPECT_TRUE(controller_->SchedulePageFlip()); - controller_->WaitForPageFlipEvent(); - EXPECT_TRUE(plane1.buffer->HasOneRef()); - EXPECT_FALSE(plane2.buffer->HasOneRef()); - - EXPECT_EQ(1, drm_->get_page_flip_call_count()); - EXPECT_EQ(0, drm_->get_overlay_flip_call_count()); -} - -TEST_F(HardwareDisplayControllerTest, CheckStateIfModesetFails) { - drm_->set_set_crtc_expectation(false); - - ui::OverlayPlane plane(scoped_refptr<ui::ScanoutBuffer>(new MockScanoutBuffer( - kDefaultModeSize))); - - EXPECT_FALSE(controller_->Modeset(plane, kDefaultMode)); -} - -TEST_F(HardwareDisplayControllerTest, CheckStateIfPageFlipFails) { - drm_->set_page_flip_expectation(false); - - ui::OverlayPlane plane1(scoped_refptr<ui::ScanoutBuffer>( - new MockScanoutBuffer(kDefaultModeSize))); - - EXPECT_TRUE(controller_->Modeset(plane1, kDefaultMode)); - - ui::OverlayPlane plane2(scoped_refptr<ui::ScanoutBuffer>( - new MockScanoutBuffer(kDefaultModeSize))); - controller_->QueueOverlayPlane(plane2); - EXPECT_FALSE(controller_->SchedulePageFlip()); - EXPECT_FALSE(plane1.buffer->HasOneRef()); - EXPECT_FALSE(plane2.buffer->HasOneRef()); - - controller_->WaitForPageFlipEvent(); - EXPECT_FALSE(plane1.buffer->HasOneRef()); - EXPECT_TRUE(plane2.buffer->HasOneRef()); -} - -TEST_F(HardwareDisplayControllerTest, VerifyNoDRMCallsWhenDisabled) { - ui::OverlayPlane plane1(scoped_refptr<ui::ScanoutBuffer>( - new MockScanoutBuffer(kDefaultModeSize))); - - EXPECT_TRUE(controller_->Modeset(plane1, kDefaultMode)); - controller_->Disable(); - ui::OverlayPlane plane2(scoped_refptr<ui::ScanoutBuffer>( - new MockScanoutBuffer(kDefaultModeSize))); - controller_->QueueOverlayPlane(plane2); - EXPECT_TRUE(controller_->SchedulePageFlip()); - controller_->WaitForPageFlipEvent(); - EXPECT_EQ(0, drm_->get_page_flip_call_count()); - - EXPECT_TRUE(controller_->Modeset(plane1, kDefaultMode)); - controller_->QueueOverlayPlane(plane2); - EXPECT_TRUE(controller_->SchedulePageFlip()); - controller_->WaitForPageFlipEvent(); - EXPECT_EQ(1, drm_->get_page_flip_call_count()); -} - -TEST_F(HardwareDisplayControllerTest, CheckOverlayPresent) { - ui::OverlayPlane plane1(scoped_refptr<ui::ScanoutBuffer>( - new MockScanoutBuffer(kDefaultModeSize))); - ui::OverlayPlane plane2( - scoped_refptr<ui::ScanoutBuffer>(new MockScanoutBuffer(kDefaultModeSize)), - 1, - gfx::OVERLAY_TRANSFORM_NONE, - gfx::Rect(kDefaultModeSize), - gfx::RectF(kDefaultModeSizeF)); - plane2.overlay_plane = 1; // Force association with a plane. - - EXPECT_TRUE(controller_->Modeset(plane1, kDefaultMode)); - - controller_->QueueOverlayPlane(plane1); - controller_->QueueOverlayPlane(plane2); - - EXPECT_TRUE(controller_->SchedulePageFlip()); - controller_->WaitForPageFlipEvent(); - EXPECT_EQ(1, drm_->get_page_flip_call_count()); - EXPECT_EQ(1, drm_->get_overlay_flip_call_count()); -} - -TEST_F(HardwareDisplayControllerTest, PageflipMirroredControllers) { - controller_->AddCrtc(scoped_ptr<ui::CrtcController>( - new ui::CrtcController(drm_.get(), kSecondaryCrtc, kSecondaryConnector))); - - ui::OverlayPlane plane1(scoped_refptr<ui::ScanoutBuffer>( - new MockScanoutBuffer(kDefaultModeSize))); - EXPECT_TRUE(controller_->Modeset(plane1, kDefaultMode)); - EXPECT_EQ(2, drm_->get_set_crtc_call_count()); - - ui::OverlayPlane plane2(scoped_refptr<ui::ScanoutBuffer>( - new MockScanoutBuffer(kDefaultModeSize))); - controller_->QueueOverlayPlane(plane2); - EXPECT_TRUE(controller_->SchedulePageFlip()); - EXPECT_EQ(2, drm_->get_page_flip_call_count()); - - controller_->WaitForPageFlipEvent(); - EXPECT_EQ(2, drm_->get_handle_events_count()); -} - -TEST_F(HardwareDisplayControllerTest, - PageflipMirroredControllersWithInvertedCrtcOrder) { - scoped_ptr<ui::CrtcController> crtc1( - new ui::CrtcController(drm_.get(), kPrimaryCrtc, kPrimaryConnector)); - scoped_ptr<ui::CrtcController> crtc2( - new ui::CrtcController(drm_.get(), kSecondaryCrtc, kSecondaryConnector)); - - // Make sure that if the order is reversed everything is still fine. - std::queue<ui::CrtcController*> crtc_queue; - crtc_queue.push(crtc2.get()); - crtc_queue.push(crtc1.get()); - - controller_.reset(new ui::HardwareDisplayController(crtc1.Pass())); - controller_->AddCrtc(crtc2.Pass()); - - ui::OverlayPlane plane1(scoped_refptr<ui::ScanoutBuffer>( - new MockScanoutBuffer(kDefaultModeSize))); - EXPECT_TRUE(controller_->Modeset(plane1, kDefaultMode)); - EXPECT_EQ(2, drm_->get_set_crtc_call_count()); - - ui::OverlayPlane plane2(scoped_refptr<ui::ScanoutBuffer>( - new MockScanoutBuffer(kDefaultModeSize))); - controller_->QueueOverlayPlane(plane2); - EXPECT_TRUE(controller_->SchedulePageFlip()); - EXPECT_EQ(2, drm_->get_page_flip_call_count()); - - drm_->set_controllers(crtc_queue); - controller_->WaitForPageFlipEvent(); - EXPECT_EQ(2, drm_->get_handle_events_count()); -}
diff --git a/ui/ozone/platform/dri/hardware_display_plane.cc b/ui/ozone/platform/dri/hardware_display_plane.cc deleted file mode 100644 index 61743dc..0000000 --- a/ui/ozone/platform/dri/hardware_display_plane.cc +++ /dev/null
@@ -1,130 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/dri/hardware_display_plane.h" - -#include <drm.h> -#include <errno.h> -#include <xf86drm.h> - -#include "base/logging.h" -#include "ui/gfx/geometry/rect.h" -#include "ui/ozone/platform/dri/dri_wrapper.h" - -namespace ui { - -namespace { -const char* kCrtcPropName = "CRTC_ID"; -const char* kFbPropName = "FB_ID"; -const char* kCrtcXPropName = "CRTC_X"; -const char* kCrtcYPropName = "CRTC_Y"; -const char* kCrtcWPropName = "CRTC_W"; -const char* kCrtcHPropName = "CRTC_H"; -const char* kSrcXPropName = "SRC_X"; -const char* kSrcYPropName = "SRC_Y"; -const char* kSrcWPropName = "SRC_W"; -const char* kSrcHPropName = "SRC_H"; -} - -HardwareDisplayPlane::Property::Property() : id_(0) { -} - -bool HardwareDisplayPlane::Property::Initialize( - DriWrapper* drm, - const char* name, - const ScopedDrmObjectPropertyPtr& plane_props) { - for (uint32_t i = 0; i < plane_props->count_props; i++) { - ScopedDrmPropertyPtr property( - drmModeGetProperty(drm->get_fd(), plane_props->props[i])); - if (!strcmp(property->name, name)) { - id_ = property->prop_id; - break; - } - } - if (!id_) { - LOG(ERROR) << "Could not find property " << name; - return false; - } - return true; -} - -HardwareDisplayPlane::HardwareDisplayPlane( - DriWrapper* drm, - drmModePropertySetPtr atomic_property_set, - ScopedDrmPlanePtr plane) - : drm_(drm), - property_set_(atomic_property_set), - plane_(plane.Pass()), - plane_id_(plane_->plane_id) { -} - -HardwareDisplayPlane::~HardwareDisplayPlane() { -} - -bool HardwareDisplayPlane::CanUseForCrtc(uint32_t crtc_id) { - return plane_->possible_crtcs & (1 << crtc_id); -} - -bool HardwareDisplayPlane::SetPlaneData(uint32_t crtc_id, - uint32_t framebuffer, - const gfx::Rect& crtc_rect, - const gfx::Rect& src_rect) { - int plane_set_error = - drmModePropertySetAdd( - property_set_, plane_id_, crtc_prop_.id_, crtc_id) || - drmModePropertySetAdd( - property_set_, plane_id_, fb_prop_.id_, framebuffer) || - drmModePropertySetAdd( - property_set_, plane_id_, crtc_x_prop_.id_, crtc_rect.x()) || - drmModePropertySetAdd( - property_set_, plane_id_, crtc_y_prop_.id_, crtc_rect.y()) || - drmModePropertySetAdd( - property_set_, plane_id_, crtc_w_prop_.id_, crtc_rect.width()) || - drmModePropertySetAdd( - property_set_, plane_id_, crtc_h_prop_.id_, crtc_rect.height()) || - drmModePropertySetAdd( - property_set_, plane_id_, src_x_prop_.id_, src_rect.x()) || - drmModePropertySetAdd( - property_set_, plane_id_, src_y_prop_.id_, src_rect.x()) || - drmModePropertySetAdd( - property_set_, plane_id_, src_w_prop_.id_, src_rect.width()) || - drmModePropertySetAdd( - property_set_, plane_id_, src_h_prop_.id_, src_rect.height()); - - if (plane_set_error) { - LOG(ERROR) << "Failed to set plane data"; - return false; - } - return true; -} - -bool HardwareDisplayPlane::Initialize() { - ScopedDrmObjectPropertyPtr plane_props(drmModeObjectGetProperties( - drm_->get_fd(), plane_id_, DRM_MODE_OBJECT_PLANE)); - - if (!plane_props) { - LOG(ERROR) << "Unable to get plane properties."; - return false; - } - - bool props_init = - crtc_prop_.Initialize(drm_, kCrtcPropName, plane_props) && - fb_prop_.Initialize(drm_, kFbPropName, plane_props) && - crtc_x_prop_.Initialize(drm_, kCrtcXPropName, plane_props) && - crtc_y_prop_.Initialize(drm_, kCrtcYPropName, plane_props) && - crtc_w_prop_.Initialize(drm_, kCrtcWPropName, plane_props) && - crtc_h_prop_.Initialize(drm_, kCrtcHPropName, plane_props) && - src_x_prop_.Initialize(drm_, kSrcXPropName, plane_props) && - src_y_prop_.Initialize(drm_, kSrcYPropName, plane_props) && - src_w_prop_.Initialize(drm_, kSrcWPropName, plane_props) && - src_h_prop_.Initialize(drm_, kSrcHPropName, plane_props); - - if (!props_init) { - LOG(ERROR) << "Unable to get plane properties."; - return false; - } - return true; -} - -} // namespace ui
diff --git a/ui/ozone/platform/dri/hardware_display_plane.h b/ui/ozone/platform/dri/hardware_display_plane.h deleted file mode 100644 index dd79f76..0000000 --- a/ui/ozone/platform/dri/hardware_display_plane.h +++ /dev/null
@@ -1,77 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_HARDWARE_DISPLAY_PLANE_H_ -#define UI_OZONE_PLATFORM_DRI_HARDWARE_DISPLAY_PLANE_H_ - -#include <stddef.h> -#include <stdint.h> -#include <xf86drmMode.h> - -#include "base/basictypes.h" -#include "ui/ozone/platform/dri/scoped_drm_types.h" - -namespace gfx { -class Rect; -} - -namespace ui { - -class DriWrapper; - -class HardwareDisplayPlane { - public: - HardwareDisplayPlane(DriWrapper* drm, - drmModePropertySetPtr atomic_property_set, - ScopedDrmPlanePtr plane); - - ~HardwareDisplayPlane(); - - bool Initialize(); - - bool CanUseForCrtc(uint32_t crtc_id); - bool SetPlaneData(uint32_t crtc_id, - uint32_t framebuffer, - const gfx::Rect& crtc_rect, - const gfx::Rect& src_rect); - - bool in_use() const { return in_use_; } - void set_in_use(bool in_use) { in_use_ = in_use; } - - private: - struct Property { - Property(); - bool Initialize(DriWrapper* drm, - const char* name, - const ScopedDrmObjectPropertyPtr& plane_properties); - uint32_t id_; - }; - // Object containing the connection to the graphics device and wraps the API - // calls to control it. - DriWrapper* drm_; - - // Not owned. - drmModePropertySetPtr property_set_; - - ScopedDrmPlanePtr plane_; - uint32_t plane_id_; - bool in_use_; - - Property crtc_prop_; - Property fb_prop_; - Property crtc_x_prop_; - Property crtc_y_prop_; - Property crtc_w_prop_; - Property crtc_h_prop_; - Property src_x_prop_; - Property src_y_prop_; - Property src_w_prop_; - Property src_h_prop_; - - DISALLOW_COPY_AND_ASSIGN(HardwareDisplayPlane); -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_HARDWARE_DISPLAY_PLANE_H_
diff --git a/ui/ozone/platform/dri/hardware_display_plane_manager.cc b/ui/ozone/platform/dri/hardware_display_plane_manager.cc deleted file mode 100644 index 0e9bc99..0000000 --- a/ui/ozone/platform/dri/hardware_display_plane_manager.cc +++ /dev/null
@@ -1,57 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/dri/hardware_display_plane_manager.h" - -#include <drm.h> -#include <errno.h> -#include <xf86drm.h> - -#include "base/logging.h" -#include "ui/gfx/geometry/rect.h" -#include "ui/ozone/platform/dri/dri_wrapper.h" - -namespace ui { - -HardwareDisplayPlaneManager::HardwareDisplayPlaneManager(DriWrapper* drm) - : drm_(drm), property_set_(NULL) { -} - -HardwareDisplayPlaneManager::~HardwareDisplayPlaneManager() { - if (property_set_) - drmModePropertySetFree(property_set_); -} - -bool HardwareDisplayPlaneManager::Initialize() { - ScopedDrmPlaneResPtr plane_resources( - drmModeGetPlaneResources(drm_->get_fd())); - if (!plane_resources) { - LOG(ERROR) << "Failed to get plane resources."; - return false; - } - - property_set_ = drmModePropertySetAlloc(); - if (!property_set_) { - LOG(ERROR) << "Failed to allocate property set."; - return false; - } - - uint32_t num_planes = plane_resources->count_planes; - for (uint32_t i = 0; i < num_planes; ++i) { - ScopedDrmPlanePtr drm_plane( - drmModeGetPlane(drm_->get_fd(), plane_resources->planes[i])); - if (!drm_plane) { - LOG(ERROR) << "Failed to get plane " << i << "."; - return false; - } - scoped_ptr<HardwareDisplayPlane> plane( - new HardwareDisplayPlane(drm_, property_set_, drm_plane.Pass())); - if (plane->Initialize()) - planes_.push_back(plane.release()); - } - - return true; -} - -} // namespace ui
diff --git a/ui/ozone/platform/dri/hardware_display_plane_manager.h b/ui/ozone/platform/dri/hardware_display_plane_manager.h deleted file mode 100644 index b6862e3..0000000 --- a/ui/ozone/platform/dri/hardware_display_plane_manager.h +++ /dev/null
@@ -1,49 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_HARDWARE_DISPLAY_PLANE_MANAGER_H_ -#define UI_OZONE_PLATFORM_DRI_HARDWARE_DISPLAY_PLANE_MANAGER_H_ - -#include <stddef.h> -#include <stdint.h> -#include <xf86drmMode.h> -#include <vector> - -#include "base/basictypes.h" -#include "base/memory/scoped_vector.h" -#include "ui/ozone/platform/dri/hardware_display_plane.h" -#include "ui/ozone/platform/dri/scoped_drm_types.h" - -namespace gfx { -class Rect; -} // namespace gfx - -namespace ui { - -class DriWrapper; - -class HardwareDisplayPlaneManager { - public: - HardwareDisplayPlaneManager(DriWrapper* drm); - - ~HardwareDisplayPlaneManager(); - - bool Initialize(); - - const ScopedVector<HardwareDisplayPlane>& get_planes() { return planes_; } - - private: - // Object containing the connection to the graphics device and wraps the API - // calls to control it. - DriWrapper* drm_; - - drmModePropertySetPtr property_set_; - ScopedVector<HardwareDisplayPlane> planes_; - - DISALLOW_COPY_AND_ASSIGN(HardwareDisplayPlaneManager); -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_HARDWARE_DISPLAY_PLANE_MANAGER_H_
diff --git a/ui/ozone/platform/dri/native_display_delegate_dri.cc b/ui/ozone/platform/dri/native_display_delegate_dri.cc deleted file mode 100644 index 6f679b6..0000000 --- a/ui/ozone/platform/dri/native_display_delegate_dri.cc +++ /dev/null
@@ -1,336 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/dri/native_display_delegate_dri.h" - -#include "base/bind.h" -#include "third_party/skia/include/core/SkCanvas.h" -#include "ui/display/types/native_display_observer.h" -#include "ui/events/ozone/device/device_event.h" -#include "ui/events/ozone/device/device_manager.h" -#include "ui/ozone/platform/dri/display_mode_dri.h" -#include "ui/ozone/platform/dri/display_snapshot_dri.h" -#include "ui/ozone/platform/dri/dri_console_buffer.h" -#include "ui/ozone/platform/dri/dri_util.h" -#include "ui/ozone/platform/dri/dri_wrapper.h" -#include "ui/ozone/platform/dri/screen_manager.h" - -namespace ui { - -namespace { - -const size_t kMaxDisplayCount = 2; - -const char kContentProtection[] = "Content Protection"; - -struct ContentProtectionMapping { - const char* name; - HDCPState state; -}; - -const ContentProtectionMapping kContentProtectionStates[] = { - {"Undesired", HDCP_STATE_UNDESIRED}, - {"Desired", HDCP_STATE_DESIRED}, - {"Enabled", HDCP_STATE_ENABLED}}; - -uint32_t GetContentProtectionValue(drmModePropertyRes* property, - HDCPState state) { - std::string name; - for (size_t i = 0; i < arraysize(kContentProtectionStates); ++i) { - if (kContentProtectionStates[i].state == state) { - name = kContentProtectionStates[i].name; - break; - } - } - - for (int i = 0; i < property->count_enums; ++i) - if (name == property->enums[i].name) - return i; - - NOTREACHED(); - return 0; -} - -class DisplaySnapshotComparator { - public: - DisplaySnapshotComparator(const DisplaySnapshotDri* snapshot) - : snapshot_(snapshot) {} - - bool operator()(const DisplaySnapshotDri* other) const { - if (snapshot_->connector() == other->connector() && - snapshot_->crtc() == other->crtc()) - return true; - - return false; - } - - private: - const DisplaySnapshotDri* snapshot_; -}; - -} // namespace - -NativeDisplayDelegateDri::NativeDisplayDelegateDri( - DriWrapper* dri, - ScreenManager* screen_manager, - DeviceManager* device_manager) - : dri_(dri), - screen_manager_(screen_manager), - device_manager_(device_manager) { - // TODO(dnicoara): Remove when async display configuration is supported. - screen_manager_->ForceInitializationOfPrimaryDisplay(); -} - -NativeDisplayDelegateDri::~NativeDisplayDelegateDri() { - if (device_manager_) - device_manager_->RemoveObserver(this); -} - -DisplaySnapshot* NativeDisplayDelegateDri::FindDisplaySnapshot(int64_t id) { - for (size_t i = 0; i < cached_displays_.size(); ++i) - if (cached_displays_[i]->display_id() == id) - return cached_displays_[i]; - - return NULL; -} - -const DisplayMode* NativeDisplayDelegateDri::FindDisplayMode( - const gfx::Size& size, - bool is_interlaced, - float refresh_rate) { - for (size_t i = 0; i < cached_modes_.size(); ++i) - if (cached_modes_[i]->size() == size && - cached_modes_[i]->is_interlaced() == is_interlaced && - cached_modes_[i]->refresh_rate() == refresh_rate) - return cached_modes_[i]; - - return NULL; -} - -void NativeDisplayDelegateDri::Initialize() { - if (device_manager_) - device_manager_->AddObserver(this); - - ScopedVector<HardwareDisplayControllerInfo> displays = - GetAvailableDisplayControllerInfos(dri_->get_fd()); - - // By default all displays show the same console buffer. - console_buffer_.reset( - new DriConsoleBuffer(dri_, displays[0]->crtc()->buffer_id)); - if (!console_buffer_->Initialize()) { - VLOG(1) << "Failed to initialize console buffer"; - console_buffer_.reset(); - } else { - // Clear the console buffer such that restarting Chrome will show a - // predetermined background. - // - // Black was chosen since Chrome's first buffer paints start with a black - // background. - console_buffer_->canvas()->clear(SK_ColorBLACK); - } -} - -void NativeDisplayDelegateDri::GrabServer() { -} - -void NativeDisplayDelegateDri::UngrabServer() { -} - -void NativeDisplayDelegateDri::SyncWithServer() { -} - -void NativeDisplayDelegateDri::SetBackgroundColor(uint32_t color_argb) { - if (console_buffer_) - console_buffer_->canvas()->clear(color_argb); -} - -void NativeDisplayDelegateDri::ForceDPMSOn() { - for (size_t i = 0; i < cached_displays_.size(); ++i) { - DisplaySnapshotDri* dri_output = cached_displays_[i]; - if (dri_output->dpms_property()) - dri_->SetProperty(dri_output->connector(), - dri_output->dpms_property()->prop_id, - DRM_MODE_DPMS_ON); - } -} - -std::vector<DisplaySnapshot*> NativeDisplayDelegateDri::GetDisplays() { - ScopedVector<DisplaySnapshotDri> old_displays(cached_displays_.Pass()); - cached_modes_.clear(); - - ScopedVector<HardwareDisplayControllerInfo> displays = - GetAvailableDisplayControllerInfos(dri_->get_fd()); - for (size_t i = 0; - i < displays.size() && cached_displays_.size() < kMaxDisplayCount; - ++i) { - DisplaySnapshotDri* display = new DisplaySnapshotDri( - dri_, displays[i]->connector(), displays[i]->crtc(), i); - cached_displays_.push_back(display); - cached_modes_.insert( - cached_modes_.end(), display->modes().begin(), display->modes().end()); - } - - NotifyScreenManager(cached_displays_.get(), old_displays.get()); - - std::vector<DisplaySnapshot*> generic_displays(cached_displays_.begin(), - cached_displays_.end()); - return generic_displays; -} - -void NativeDisplayDelegateDri::AddMode(const DisplaySnapshot& output, - const DisplayMode* mode) { -} - -bool NativeDisplayDelegateDri::Configure(const DisplaySnapshot& output, - const DisplayMode* mode, - const gfx::Point& origin) { - const DisplaySnapshotDri& dri_output = - static_cast<const DisplaySnapshotDri&>(output); - - VLOG(1) << "DRM configuring: crtc=" << dri_output.crtc() - << " connector=" << dri_output.connector() - << " origin=" << origin.ToString() - << " size=" << (mode ? mode->size().ToString() : "0x0"); - - if (mode) { - if (!screen_manager_->ConfigureDisplayController( - dri_output.crtc(), - dri_output.connector(), - origin, - static_cast<const DisplayModeDri*>(mode)->mode_info())) { - VLOG(1) << "Failed to configure: crtc=" << dri_output.crtc() - << " connector=" << dri_output.connector(); - return false; - } - } else { - if (!screen_manager_->DisableDisplayController(dri_output.crtc())) { - VLOG(1) << "Failed to disable crtc=" << dri_output.crtc(); - return false; - } - } - - return true; -} - -void NativeDisplayDelegateDri::CreateFrameBuffer(const gfx::Size& size) { -} - -bool NativeDisplayDelegateDri::GetHDCPState(const DisplaySnapshot& output, - HDCPState* state) { - const DisplaySnapshotDri& dri_output = - static_cast<const DisplaySnapshotDri&>(output); - - ScopedDrmConnectorPtr connector(dri_->GetConnector(dri_output.connector())); - if (!connector) { - LOG(ERROR) << "Failed to get connector " << dri_output.connector(); - return false; - } - - ScopedDrmPropertyPtr hdcp_property( - dri_->GetProperty(connector.get(), kContentProtection)); - if (!hdcp_property) { - LOG(ERROR) << "'" << kContentProtection << "' property doesn't exist."; - return false; - } - - DCHECK_LT(static_cast<int>(hdcp_property->prop_id), connector->count_props); - int hdcp_state_idx = connector->prop_values[hdcp_property->prop_id]; - DCHECK_LT(hdcp_state_idx, hdcp_property->count_enums); - - std::string name(hdcp_property->enums[hdcp_state_idx].name); - for (size_t i = 0; i < arraysize(kContentProtectionStates); ++i) { - if (name == kContentProtectionStates[i].name) { - *state = kContentProtectionStates[i].state; - VLOG(3) << "HDCP state: " << *state << " (" << name << ")"; - return true; - } - } - - LOG(ERROR) << "Unknown content protection value '" << name << "'"; - return false; -} - -bool NativeDisplayDelegateDri::SetHDCPState(const DisplaySnapshot& output, - HDCPState state) { - const DisplaySnapshotDri& dri_output = - static_cast<const DisplaySnapshotDri&>(output); - - ScopedDrmConnectorPtr connector(dri_->GetConnector(dri_output.connector())); - if (!connector) { - LOG(ERROR) << "Failed to get connector " << dri_output.connector(); - return false; - } - - ScopedDrmPropertyPtr hdcp_property( - dri_->GetProperty(connector.get(), kContentProtection)); - if (!hdcp_property) { - LOG(ERROR) << "'" << kContentProtection << "' property doesn't exist."; - return false; - } - - return dri_->SetProperty( - dri_output.connector(), - hdcp_property->prop_id, - GetContentProtectionValue(hdcp_property.get(), state)); -} - -std::vector<ui::ColorCalibrationProfile> -NativeDisplayDelegateDri::GetAvailableColorCalibrationProfiles( - const ui::DisplaySnapshot& output) { - NOTIMPLEMENTED(); - return std::vector<ui::ColorCalibrationProfile>(); -} - -bool NativeDisplayDelegateDri::SetColorCalibrationProfile( - const ui::DisplaySnapshot& output, - ui::ColorCalibrationProfile new_profile) { - NOTIMPLEMENTED(); - return false; -} - -void NativeDisplayDelegateDri::AddObserver(NativeDisplayObserver* observer) { - observers_.AddObserver(observer); -} - -void NativeDisplayDelegateDri::RemoveObserver(NativeDisplayObserver* observer) { - observers_.RemoveObserver(observer); -} - -void NativeDisplayDelegateDri::OnDeviceEvent(const DeviceEvent& event) { - if (event.device_type() != DeviceEvent::DISPLAY) - return; - - if (event.action_type() == DeviceEvent::CHANGE) { - VLOG(1) << "Got display changed event"; - FOR_EACH_OBSERVER( - NativeDisplayObserver, observers_, OnConfigurationChanged()); - } -} - -void NativeDisplayDelegateDri::NotifyScreenManager( - const std::vector<DisplaySnapshotDri*>& new_displays, - const std::vector<DisplaySnapshotDri*>& old_displays) const { - for (size_t i = 0; i < old_displays.size(); ++i) { - const std::vector<DisplaySnapshotDri*>::const_iterator it = - std::find_if(new_displays.begin(), - new_displays.end(), - DisplaySnapshotComparator(old_displays[i])); - - if (it == new_displays.end()) - screen_manager_->RemoveDisplayController(old_displays[i]->crtc()); - } - - for (size_t i = 0; i < new_displays.size(); ++i) { - const std::vector<DisplaySnapshotDri*>::const_iterator it = - std::find_if(old_displays.begin(), - old_displays.end(), - DisplaySnapshotComparator(new_displays[i])); - - if (it == old_displays.end()) - screen_manager_->AddDisplayController( - dri_, new_displays[i]->crtc(), new_displays[i]->connector()); - } -} - -} // namespace ui
diff --git a/ui/ozone/platform/dri/native_display_delegate_dri.h b/ui/ozone/platform/dri/native_display_delegate_dri.h deleted file mode 100644 index fc20054..0000000 --- a/ui/ozone/platform/dri/native_display_delegate_dri.h +++ /dev/null
@@ -1,87 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_NATIVE_DISPLAY_DELEGATE_DRI_H_ -#define UI_OZONE_PLATFORM_DRI_NATIVE_DISPLAY_DELEGATE_DRI_H_ - -#include "base/memory/scoped_ptr.h" -#include "base/memory/scoped_vector.h" -#include "base/observer_list.h" -#include "ui/display/types/native_display_delegate.h" -#include "ui/events/ozone/device/device_event_observer.h" - -namespace ui { - -class DeviceManager; -class DisplaySnapshotDri; -class DriConsoleBuffer; -class DriWrapper; -class ScreenManager; - -class NativeDisplayDelegateDri : public NativeDisplayDelegate, - DeviceEventObserver { - public: - NativeDisplayDelegateDri(DriWrapper* dri, - ScreenManager* screen_manager, - DeviceManager* device_manager); - virtual ~NativeDisplayDelegateDri(); - - DisplaySnapshot* FindDisplaySnapshot(int64_t id); - const DisplayMode* FindDisplayMode(const gfx::Size& size, - bool is_interlaced, - float refresh_rate); - - // NativeDisplayDelegate overrides: - virtual void Initialize() override; - virtual void GrabServer() override; - virtual void UngrabServer() override; - virtual void SyncWithServer() override; - virtual void SetBackgroundColor(uint32_t color_argb) override; - virtual void ForceDPMSOn() override; - virtual std::vector<DisplaySnapshot*> GetDisplays() override; - virtual void AddMode(const DisplaySnapshot& output, - const DisplayMode* mode) override; - virtual bool Configure(const DisplaySnapshot& output, - const DisplayMode* mode, - const gfx::Point& origin) override; - virtual void CreateFrameBuffer(const gfx::Size& size) override; - virtual bool GetHDCPState(const DisplaySnapshot& output, - HDCPState* state) override; - virtual bool SetHDCPState(const DisplaySnapshot& output, - HDCPState state) override; - virtual std::vector<ui::ColorCalibrationProfile> - GetAvailableColorCalibrationProfiles( - const ui::DisplaySnapshot& output) override; - virtual bool SetColorCalibrationProfile( - const ui::DisplaySnapshot& output, - ui::ColorCalibrationProfile new_profile) override; - virtual void AddObserver(NativeDisplayObserver* observer) override; - virtual void RemoveObserver(NativeDisplayObserver* observer) override; - - // DeviceEventObserver overrides: - virtual void OnDeviceEvent(const DeviceEvent& event) override; - - private: - // Notify ScreenManager of all the displays that were present before the - // update but are gone after the update. - void NotifyScreenManager( - const std::vector<DisplaySnapshotDri*>& new_displays, - const std::vector<DisplaySnapshotDri*>& old_displays) const; - - DriWrapper* dri_; // Not owned. - ScreenManager* screen_manager_; // Not owned. - DeviceManager* device_manager_; // Not owned. - scoped_ptr<DriConsoleBuffer> console_buffer_; - // Modes can be shared between different displays, so we need to keep track - // of them independently for cleanup. - ScopedVector<const DisplayMode> cached_modes_; - ScopedVector<DisplaySnapshotDri> cached_displays_; - ObserverList<NativeDisplayObserver> observers_; - - DISALLOW_COPY_AND_ASSIGN(NativeDisplayDelegateDri); -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_NATIVE_DISPLAY_DELEGATE_DRI_H_
diff --git a/ui/ozone/platform/dri/native_display_delegate_proxy.cc b/ui/ozone/platform/dri/native_display_delegate_proxy.cc deleted file mode 100644 index 95600d2..0000000 --- a/ui/ozone/platform/dri/native_display_delegate_proxy.cc +++ /dev/null
@@ -1,162 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/dri/native_display_delegate_proxy.h" - -#include "base/logging.h" -#include "ui/display/types/display_snapshot.h" -#include "ui/display/types/native_display_observer.h" -#include "ui/events/ozone/device/device_event.h" -#include "ui/events/ozone/device/device_manager.h" -#include "ui/ozone/common/display_snapshot_proxy.h" -#include "ui/ozone/common/display_util.h" -#include "ui/ozone/common/gpu/ozone_gpu_messages.h" -#include "ui/ozone/platform/dri/dri_gpu_platform_support_host.h" - -namespace ui { - -NativeDisplayDelegateProxy::NativeDisplayDelegateProxy( - DriGpuPlatformSupportHost* proxy, - DeviceManager* device_manager) - : proxy_(proxy), device_manager_(device_manager) { - proxy_->RegisterHandler(this); -} - -NativeDisplayDelegateProxy::~NativeDisplayDelegateProxy() { - if (device_manager_) - device_manager_->RemoveObserver(this); - - proxy_->UnregisterHandler(this); -} - -void NativeDisplayDelegateProxy::Initialize() { - if (device_manager_) - device_manager_->AddObserver(this); -} - -void NativeDisplayDelegateProxy::GrabServer() { -} - -void NativeDisplayDelegateProxy::UngrabServer() { -} - -void NativeDisplayDelegateProxy::SyncWithServer() { -} - -void NativeDisplayDelegateProxy::SetBackgroundColor(uint32_t color_argb) { - NOTIMPLEMENTED(); -} - -void NativeDisplayDelegateProxy::ForceDPMSOn() { - proxy_->Send(new OzoneGpuMsg_ForceDPMSOn()); -} - -std::vector<DisplaySnapshot*> NativeDisplayDelegateProxy::GetDisplays() { - return displays_.get(); -} - -void NativeDisplayDelegateProxy::AddMode(const DisplaySnapshot& output, - const DisplayMode* mode) { -} - -bool NativeDisplayDelegateProxy::Configure(const DisplaySnapshot& output, - const DisplayMode* mode, - const gfx::Point& origin) { - // TODO(dnicoara) Should handle an asynchronous response. - if (mode) - proxy_->Send(new OzoneGpuMsg_ConfigureNativeDisplay( - output.display_id(), GetDisplayModeParams(*mode), origin)); - else - proxy_->Send(new OzoneGpuMsg_DisableNativeDisplay(output.display_id())); - - return true; -} - -void NativeDisplayDelegateProxy::CreateFrameBuffer(const gfx::Size& size) { -} - -bool NativeDisplayDelegateProxy::GetHDCPState(const DisplaySnapshot& output, - HDCPState* state) { - NOTIMPLEMENTED(); - return false; -} - -bool NativeDisplayDelegateProxy::SetHDCPState(const DisplaySnapshot& output, - HDCPState state) { - NOTIMPLEMENTED(); - return false; -} - -std::vector<ColorCalibrationProfile> -NativeDisplayDelegateProxy::GetAvailableColorCalibrationProfiles( - const DisplaySnapshot& output) { - NOTIMPLEMENTED(); - return std::vector<ColorCalibrationProfile>(); -} - -bool NativeDisplayDelegateProxy::SetColorCalibrationProfile( - const DisplaySnapshot& output, - ColorCalibrationProfile new_profile) { - NOTIMPLEMENTED(); - return false; -} - -void NativeDisplayDelegateProxy::AddObserver(NativeDisplayObserver* observer) { - observers_.AddObserver(observer); -} - -void NativeDisplayDelegateProxy::RemoveObserver( - NativeDisplayObserver* observer) { - observers_.RemoveObserver(observer); -} - -void NativeDisplayDelegateProxy::OnDeviceEvent(const DeviceEvent& event) { - if (event.device_type() != DeviceEvent::DISPLAY) - return; - - if (event.action_type() == DeviceEvent::CHANGE) { - VLOG(1) << "Got display changed event"; - proxy_->Send(new OzoneGpuMsg_RefreshNativeDisplays( - std::vector<DisplaySnapshot_Params>())); - } -} - -void NativeDisplayDelegateProxy::OnChannelEstablished(int host_id, - IPC::Sender* sender) { - std::vector<DisplaySnapshot_Params> display_params; - for (size_t i = 0; i < displays_.size(); ++i) - display_params.push_back(GetDisplaySnapshotParams(*displays_[i])); - - // Force an initial configure such that the browser process can get the actual - // state. Pass in the current display state since the GPU process may have - // crashed and we want to re-synchronize the state between processes. - proxy_->Send(new OzoneGpuMsg_RefreshNativeDisplays(display_params)); -} - -void NativeDisplayDelegateProxy::OnChannelDestroyed(int host_id) { -} - -bool NativeDisplayDelegateProxy::OnMessageReceived( - const IPC::Message& message) { - bool handled = true; - - IPC_BEGIN_MESSAGE_MAP(NativeDisplayDelegateProxy, message) - IPC_MESSAGE_HANDLER(OzoneHostMsg_UpdateNativeDisplays, OnUpdateNativeDisplays) - IPC_MESSAGE_UNHANDLED(handled = false) - IPC_END_MESSAGE_MAP() - - return handled; -} - -void NativeDisplayDelegateProxy::OnUpdateNativeDisplays( - const std::vector<DisplaySnapshot_Params>& displays) { - displays_.clear(); - for (size_t i = 0; i < displays.size(); ++i) - displays_.push_back(new DisplaySnapshotProxy(displays[i])); - - FOR_EACH_OBSERVER( - NativeDisplayObserver, observers_, OnConfigurationChanged()); -} - -} // namespace ui
diff --git a/ui/ozone/platform/dri/native_display_delegate_proxy.h b/ui/ozone/platform/dri/native_display_delegate_proxy.h deleted file mode 100644 index 2dcf0e1..0000000 --- a/ui/ozone/platform/dri/native_display_delegate_proxy.h +++ /dev/null
@@ -1,81 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_NATIVE_DISPLAY_DELEGATE_PROXY_H_ -#define UI_OZONE_PLATFORM_DRI_NATIVE_DISPLAY_DELEGATE_PROXY_H_ - -#include "base/macros.h" -#include "base/memory/scoped_vector.h" -#include "base/observer_list.h" -#include "ui/display/types/native_display_delegate.h" -#include "ui/events/ozone/device/device_event_observer.h" -#include "ui/ozone/public/gpu_platform_support_host.h" - -namespace ui { - -class DeviceManager; -class DriGpuPlatformSupportHost; - -struct DisplaySnapshot_Params; - -class NativeDisplayDelegateProxy : public NativeDisplayDelegate, - public DeviceEventObserver, - public GpuPlatformSupportHost { - public: - NativeDisplayDelegateProxy(DriGpuPlatformSupportHost* proxy, - DeviceManager* device_manager); - virtual ~NativeDisplayDelegateProxy(); - - // NativeDisplayDelegate overrides: - virtual void Initialize() override; - virtual void GrabServer() override; - virtual void UngrabServer() override; - virtual void SyncWithServer() override; - virtual void SetBackgroundColor(uint32_t color_argb) override; - virtual void ForceDPMSOn() override; - virtual std::vector<DisplaySnapshot*> GetDisplays() override; - virtual void AddMode(const DisplaySnapshot& output, - const DisplayMode* mode) override; - virtual bool Configure(const DisplaySnapshot& output, - const DisplayMode* mode, - const gfx::Point& origin) override; - virtual void CreateFrameBuffer(const gfx::Size& size) override; - virtual bool GetHDCPState(const DisplaySnapshot& output, - HDCPState* state) override; - virtual bool SetHDCPState(const DisplaySnapshot& output, - HDCPState state) override; - virtual std::vector<ColorCalibrationProfile> - GetAvailableColorCalibrationProfiles( - const DisplaySnapshot& output) override; - virtual bool SetColorCalibrationProfile( - const DisplaySnapshot& output, - ColorCalibrationProfile new_profile) override; - virtual void AddObserver(NativeDisplayObserver* observer) override; - virtual void RemoveObserver(NativeDisplayObserver* observer) override; - - // DeviceEventObserver overrides: - virtual void OnDeviceEvent(const DeviceEvent& event) override; - - // GpuPlatformSupportHost: - virtual void OnChannelEstablished(int host_id, IPC::Sender* sender) override; - virtual void OnChannelDestroyed(int host_id) override; - - // IPC::Listener overrides: - virtual bool OnMessageReceived(const IPC::Message& message) override; - - private: - void OnUpdateNativeDisplays( - const std::vector<DisplaySnapshot_Params>& displays); - - DriGpuPlatformSupportHost* proxy_; // Not owned. - DeviceManager* device_manager_; // Not owned. - ScopedVector<DisplaySnapshot> displays_; - ObserverList<NativeDisplayObserver> observers_; - - DISALLOW_COPY_AND_ASSIGN(NativeDisplayDelegateProxy); -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_NATIVE_DISPLAY_DELEGATE_PROXY_H_
diff --git a/ui/ozone/platform/dri/overlay_plane.cc b/ui/ozone/platform/dri/overlay_plane.cc deleted file mode 100644 index 5f48fdd..0000000 --- a/ui/ozone/platform/dri/overlay_plane.cc +++ /dev/null
@@ -1,48 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/dri/overlay_plane.h" - -#include "base/logging.h" -#include "ui/ozone/platform/dri/scanout_buffer.h" - -namespace ui { - -OverlayPlane::OverlayPlane(scoped_refptr<ScanoutBuffer> buffer) - : buffer(buffer), - z_order(0), - display_bounds(gfx::Point(), buffer->GetSize()), - crop_rect(0, 0, 1, 1), - overlay_plane(0) { -} - -OverlayPlane::OverlayPlane(scoped_refptr<ScanoutBuffer> buffer, - int z_order, - gfx::OverlayTransform plane_transform, - const gfx::Rect& display_bounds, - const gfx::RectF& crop_rect) - : buffer(buffer), - z_order(z_order), - plane_transform(plane_transform), - display_bounds(display_bounds), - crop_rect(crop_rect), - overlay_plane(0) { -} - -OverlayPlane::~OverlayPlane() { -} - -// static -const OverlayPlane& OverlayPlane::GetPrimaryPlane( - const OverlayPlaneList& overlays) { - for (size_t i = 0; i < overlays.size(); ++i) { - if (overlays[i].z_order == 0) - return overlays[i]; - } - - NOTREACHED(); - return overlays[0]; -} - -} // namespace ui
diff --git a/ui/ozone/platform/dri/overlay_plane.h b/ui/ozone/platform/dri/overlay_plane.h deleted file mode 100644 index e1aeee0..0000000 --- a/ui/ozone/platform/dri/overlay_plane.h +++ /dev/null
@@ -1,46 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_OVERLAY_PLANE_H_ -#define UI_OZONE_PLATFORM_DRI_OVERLAY_PLANE_H_ - -#include <vector> - -#include "base/memory/ref_counted.h" -#include "ui/gfx/geometry/rect.h" -#include "ui/gfx/overlay_transform.h" - -namespace ui { - -class ScanoutBuffer; - -struct OverlayPlane; -typedef std::vector<OverlayPlane> OverlayPlaneList; - -struct OverlayPlane { - // Simpler constructor for the primary plane. - explicit OverlayPlane(scoped_refptr<ScanoutBuffer> buffer); - - OverlayPlane(scoped_refptr<ScanoutBuffer> buffer, - int z_order, - gfx::OverlayTransform plane_transform, - const gfx::Rect& display_bounds, - const gfx::RectF& crop_rect); - - ~OverlayPlane(); - - // Returns the primary plane in |overlays|. - static const OverlayPlane& GetPrimaryPlane(const OverlayPlaneList& overlays); - - scoped_refptr<ScanoutBuffer> buffer; - int z_order; - gfx::OverlayTransform plane_transform; - gfx::Rect display_bounds; - gfx::RectF crop_rect; - int overlay_plane; -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_OVERLAY_PLANE_H_
diff --git a/ui/ozone/platform/dri/ozone_platform_dri.cc b/ui/ozone/platform/dri/ozone_platform_dri.cc deleted file mode 100644 index 63750e2..0000000 --- a/ui/ozone/platform/dri/ozone_platform_dri.cc +++ /dev/null
@@ -1,133 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/dri/ozone_platform_dri.h" - -#include "base/at_exit.h" -#include "ui/base/cursor/ozone/bitmap_cursor_factory_ozone.h" -#include "ui/events/ozone/device/device_manager.h" -#include "ui/events/ozone/evdev/cursor_delegate_evdev.h" -#include "ui/events/ozone/evdev/event_factory_evdev.h" -#include "ui/ozone/platform/dri/dri_buffer.h" -#include "ui/ozone/platform/dri/dri_cursor.h" -#include "ui/ozone/platform/dri/dri_gpu_platform_support.h" -#include "ui/ozone/platform/dri/dri_gpu_platform_support_host.h" -#include "ui/ozone/platform/dri/dri_surface_factory.h" -#include "ui/ozone/platform/dri/dri_window.h" -#include "ui/ozone/platform/dri/dri_window_delegate_impl.h" -#include "ui/ozone/platform/dri/dri_window_delegate_manager.h" -#include "ui/ozone/platform/dri/dri_window_manager.h" -#include "ui/ozone/platform/dri/dri_wrapper.h" -#include "ui/ozone/platform/dri/native_display_delegate_dri.h" -#include "ui/ozone/platform/dri/screen_manager.h" -#include "ui/ozone/platform/dri/virtual_terminal_manager.h" -#include "ui/ozone/public/ozone_platform.h" -#include "ui/ozone/public/ui_thread_gpu.h" - -namespace ui { - -namespace { - -const char kDefaultGraphicsCardPath[] = "/dev/dri/card0"; - -// OzonePlatform for Linux DRI (Direct Rendering Infrastructure) -// -// This platform is Linux without any display server (no X, wayland, or -// anything). This means chrome alone owns the display and input devices. -class OzonePlatformDri : public OzonePlatform { - public: - OzonePlatformDri() - : vt_manager_(new VirtualTerminalManager()), - dri_(new DriWrapper(kDefaultGraphicsCardPath)), - buffer_generator_(new DriBufferGenerator(dri_.get())), - screen_manager_(new ScreenManager(dri_.get(), - buffer_generator_.get())), - device_manager_(CreateDeviceManager()) { - base::AtExitManager::RegisterTask( - base::Bind(&base::DeletePointer<OzonePlatformDri>, this)); - } - virtual ~OzonePlatformDri() {} - - // OzonePlatform: - virtual ui::SurfaceFactoryOzone* GetSurfaceFactoryOzone() override { - return surface_factory_ozone_.get(); - } - virtual CursorFactoryOzone* GetCursorFactoryOzone() override { - return cursor_factory_ozone_.get(); - } - virtual GpuPlatformSupport* GetGpuPlatformSupport() override { - return gpu_platform_support_.get(); - } - virtual GpuPlatformSupportHost* GetGpuPlatformSupportHost() override { - return gpu_platform_support_host_.get(); - } - virtual scoped_ptr<PlatformWindow> CreatePlatformWindow( - PlatformWindowDelegate* delegate, - const gfx::Rect& bounds) override { - scoped_ptr<DriWindow> platform_window( - new DriWindow(delegate, - bounds, - gpu_platform_support_host_.get(), - event_factory_ozone_.get(), - window_manager_.get())); - platform_window->Initialize(); - return platform_window.Pass(); - } - virtual scoped_ptr<NativeDisplayDelegate> CreateNativeDisplayDelegate() - override { - return scoped_ptr<NativeDisplayDelegate>(new NativeDisplayDelegateDri( - dri_.get(), screen_manager_.get(), device_manager_.get())); - } - virtual void InitializeUI() override { - dri_->Initialize(); - surface_factory_ozone_.reset(new DriSurfaceFactory( - dri_.get(), screen_manager_.get(), &window_delegate_manager_)); - gpu_platform_support_.reset( - new DriGpuPlatformSupport(surface_factory_ozone_.get(), - &window_delegate_manager_, - screen_manager_.get(), - scoped_ptr<NativeDisplayDelegateDri>())); - gpu_platform_support_host_.reset(new DriGpuPlatformSupportHost()); - cursor_factory_ozone_.reset(new BitmapCursorFactoryOzone); - window_manager_.reset(new DriWindowManager(surface_factory_ozone_.get())); - event_factory_ozone_.reset(new EventFactoryEvdev(window_manager_->cursor(), - device_manager_.get())); - if (surface_factory_ozone_->InitializeHardware() != - DriSurfaceFactory::INITIALIZED) - LOG(FATAL) << "Failed to initialize display hardware."; - - if (!ui_thread_gpu_.Initialize()) - LOG(FATAL) << "Failed to initialize dummy channel."; - } - - virtual void InitializeGPU() override {} - - private: - scoped_ptr<VirtualTerminalManager> vt_manager_; - scoped_ptr<DriWrapper> dri_; - scoped_ptr<DriBufferGenerator> buffer_generator_; - scoped_ptr<ScreenManager> screen_manager_; - scoped_ptr<DeviceManager> device_manager_; - - scoped_ptr<DriSurfaceFactory> surface_factory_ozone_; - scoped_ptr<BitmapCursorFactoryOzone> cursor_factory_ozone_; - scoped_ptr<EventFactoryEvdev> event_factory_ozone_; - - scoped_ptr<DriWindowManager> window_manager_; - - scoped_ptr<DriGpuPlatformSupport> gpu_platform_support_; - scoped_ptr<DriGpuPlatformSupportHost> gpu_platform_support_host_; - - DriWindowDelegateManager window_delegate_manager_; - - UiThreadGpu ui_thread_gpu_; - - DISALLOW_COPY_AND_ASSIGN(OzonePlatformDri); -}; - -} // namespace - -OzonePlatform* CreateOzonePlatformDri() { return new OzonePlatformDri; } - -} // namespace ui
diff --git a/ui/ozone/platform/dri/ozone_platform_dri.h b/ui/ozone/platform/dri/ozone_platform_dri.h deleted file mode 100644 index a63a054..0000000 --- a/ui/ozone/platform/dri/ozone_platform_dri.h +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_OZONE_PLATFORM_DRI_H_ -#define UI_OZONE_PLATFORM_DRI_OZONE_PLATFORM_DRI_H_ - -namespace ui { - -class OzonePlatform; - -// Constructor hook for use in ozone_platform_list.cc -OzonePlatform* CreateOzonePlatformDri(); - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_OZONE_PLATFORM_DRI_H_
diff --git a/ui/ozone/platform/dri/ozone_platform_gbm.cc b/ui/ozone/platform/dri/ozone_platform_gbm.cc deleted file mode 100644 index 344422b..0000000 --- a/ui/ozone/platform/dri/ozone_platform_gbm.cc +++ /dev/null
@@ -1,182 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/dri/ozone_platform_gbm.h" - -#include <dlfcn.h> -#include <gbm.h> -#include <stdlib.h> - -#include "base/at_exit.h" -#include "base/command_line.h" -#include "ui/base/cursor/ozone/bitmap_cursor_factory_ozone.h" -#include "ui/events/ozone/device/device_manager.h" -#include "ui/events/ozone/evdev/event_factory_evdev.h" -#include "ui/ozone/platform/dri/dri_cursor.h" -#include "ui/ozone/platform/dri/dri_gpu_platform_support.h" -#include "ui/ozone/platform/dri/dri_gpu_platform_support_host.h" -#include "ui/ozone/platform/dri/dri_window.h" -#include "ui/ozone/platform/dri/dri_window_delegate_manager.h" -#include "ui/ozone/platform/dri/dri_window_manager.h" -#include "ui/ozone/platform/dri/dri_wrapper.h" -#include "ui/ozone/platform/dri/gbm_buffer.h" -#include "ui/ozone/platform/dri/gbm_surface.h" -#include "ui/ozone/platform/dri/gbm_surface_factory.h" -#include "ui/ozone/platform/dri/native_display_delegate_dri.h" -#include "ui/ozone/platform/dri/native_display_delegate_proxy.h" -#include "ui/ozone/platform/dri/scanout_buffer.h" -#include "ui/ozone/platform/dri/screen_manager.h" -#include "ui/ozone/platform/dri/virtual_terminal_manager.h" -#include "ui/ozone/public/cursor_factory_ozone.h" -#include "ui/ozone/public/gpu_platform_support.h" -#include "ui/ozone/public/gpu_platform_support_host.h" -#include "ui/ozone/public/ozone_platform.h" -#include "ui/ozone/public/ozone_switches.h" - -namespace ui { - -namespace { - -const char kDefaultGraphicsCardPath[] = "/dev/dri/card0"; - -class GbmBufferGenerator : public ScanoutBufferGenerator { - public: - GbmBufferGenerator(DriWrapper* dri) - : dri_(dri), - glapi_lib_(dlopen("libglapi.so.0", RTLD_LAZY | RTLD_GLOBAL)), - device_(gbm_create_device(dri_->get_fd())) { - if (!device_) - LOG(FATAL) << "Unable to initialize gbm for " << kDefaultGraphicsCardPath; - } - virtual ~GbmBufferGenerator() { - gbm_device_destroy(device_); - if (glapi_lib_) - dlclose(glapi_lib_); - } - - gbm_device* device() const { return device_; } - - virtual scoped_refptr<ScanoutBuffer> Create(const gfx::Size& size) override { - return GbmBuffer::CreateBuffer( - dri_, device_, SurfaceFactoryOzone::RGBA_8888, size, true); - } - - protected: - DriWrapper* dri_; // Not owned. - - // HACK: gbm drivers have broken linkage - void *glapi_lib_; - - gbm_device* device_; - - DISALLOW_COPY_AND_ASSIGN(GbmBufferGenerator); -}; - -class OzonePlatformGbm : public OzonePlatform { - public: - OzonePlatformGbm(bool use_surfaceless) : use_surfaceless_(use_surfaceless) { - base::AtExitManager::RegisterTask( - base::Bind(&base::DeletePointer<OzonePlatformGbm>, this)); - } - virtual ~OzonePlatformGbm() {} - - // OzonePlatform: - virtual ui::SurfaceFactoryOzone* GetSurfaceFactoryOzone() override { - return surface_factory_ozone_.get(); - } - virtual CursorFactoryOzone* GetCursorFactoryOzone() override { - return cursor_factory_ozone_.get(); - } - virtual GpuPlatformSupport* GetGpuPlatformSupport() override { - return gpu_platform_support_.get(); - } - virtual GpuPlatformSupportHost* GetGpuPlatformSupportHost() override { - return gpu_platform_support_host_.get(); - } - virtual scoped_ptr<PlatformWindow> CreatePlatformWindow( - PlatformWindowDelegate* delegate, - const gfx::Rect& bounds) override { - scoped_ptr<DriWindow> platform_window( - new DriWindow(delegate, - bounds, - gpu_platform_support_host_.get(), - event_factory_ozone_.get(), - window_manager_.get())); - platform_window->Initialize(); - return platform_window.Pass(); - } - virtual scoped_ptr<NativeDisplayDelegate> CreateNativeDisplayDelegate() - override { - return scoped_ptr<NativeDisplayDelegate>(new NativeDisplayDelegateProxy( - gpu_platform_support_host_.get(), device_manager_.get())); - } - virtual void InitializeUI() override { - vt_manager_.reset(new VirtualTerminalManager()); - // Needed since the browser process creates the accelerated widgets and that - // happens through SFO. - surface_factory_ozone_.reset(new GbmSurfaceFactory(use_surfaceless_)); - device_manager_ = CreateDeviceManager(); - gpu_platform_support_host_.reset(new DriGpuPlatformSupportHost()); - cursor_factory_ozone_.reset(new BitmapCursorFactoryOzone); - window_manager_.reset( - new DriWindowManager(gpu_platform_support_host_.get())); - event_factory_ozone_.reset(new EventFactoryEvdev(window_manager_->cursor(), - device_manager_.get())); - } - - virtual void InitializeGPU() override { - dri_.reset(new DriWrapper(kDefaultGraphicsCardPath)); - dri_->Initialize(); - buffer_generator_.reset(new GbmBufferGenerator(dri_.get())); - screen_manager_.reset(new ScreenManager(dri_.get(), - buffer_generator_.get())); - window_delegate_manager_.reset(new DriWindowDelegateManager()); - if (!surface_factory_ozone_) - surface_factory_ozone_.reset(new GbmSurfaceFactory(use_surfaceless_)); - - surface_factory_ozone_->InitializeGpu(dri_.get(), - buffer_generator_->device(), - screen_manager_.get(), - window_delegate_manager_.get()); - gpu_platform_support_.reset(new DriGpuPlatformSupport( - surface_factory_ozone_.get(), - window_delegate_manager_.get(), - screen_manager_.get(), - scoped_ptr<NativeDisplayDelegateDri>(new NativeDisplayDelegateDri( - dri_.get(), screen_manager_.get(), NULL)))); - if (surface_factory_ozone_->InitializeHardware() != - DriSurfaceFactory::INITIALIZED) - LOG(FATAL) << "failed to initialize display hardware"; - } - - private: - bool use_surfaceless_; - scoped_ptr<VirtualTerminalManager> vt_manager_; - scoped_ptr<DriWrapper> dri_; - scoped_ptr<GbmBufferGenerator> buffer_generator_; - scoped_ptr<ScreenManager> screen_manager_; - scoped_ptr<DeviceManager> device_manager_; - - scoped_ptr<GbmSurfaceFactory> surface_factory_ozone_; - scoped_ptr<BitmapCursorFactoryOzone> cursor_factory_ozone_; - scoped_ptr<EventFactoryEvdev> event_factory_ozone_; - - scoped_ptr<DriGpuPlatformSupport> gpu_platform_support_; - scoped_ptr<DriGpuPlatformSupportHost> gpu_platform_support_host_; - - scoped_ptr<DriWindowDelegateManager> window_delegate_manager_; - // Browser side object only. - scoped_ptr<DriWindowManager> window_manager_; - - DISALLOW_COPY_AND_ASSIGN(OzonePlatformGbm); -}; - -} // namespace - -OzonePlatform* CreateOzonePlatformGbm() { - CommandLine* cmd = CommandLine::ForCurrentProcess(); - return new OzonePlatformGbm(cmd->HasSwitch(switches::kOzoneUseSurfaceless)); -} - -} // namespace ui
diff --git a/ui/ozone/platform/dri/ozone_platform_gbm.h b/ui/ozone/platform/dri/ozone_platform_gbm.h deleted file mode 100644 index 47f5ca7..0000000 --- a/ui/ozone/platform/dri/ozone_platform_gbm.h +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_OZONE_PLATFORM_GBM_H_ -#define UI_OZONE_PLATFORM_DRI_OZONE_PLATFORM_GBM_H_ - -namespace ui { - -class OzonePlatform; - -// Constructor hook for use in ozone_platform_list.cc -OzonePlatform* CreateOzonePlatformGbm(); - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_OZONE_PLATFORM_GBM_H_
diff --git a/ui/ozone/platform/dri/scanout_buffer.h b/ui/ozone/platform/dri/scanout_buffer.h deleted file mode 100644 index 4475c8d..0000000 --- a/ui/ozone/platform/dri/scanout_buffer.h +++ /dev/null
@@ -1,42 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_SCANOUT_BUFFER_H_ -#define UI_OZONE_PLATFORM_DRI_SCANOUT_BUFFER_H_ - -#include <stdint.h> - -#include "base/memory/ref_counted.h" -#include "ui/gfx/geometry/size.h" - -namespace ui { - -// Abstraction for a DRM buffer that can be scanned-out of. -class ScanoutBuffer : public base::RefCounted<ScanoutBuffer> { - public: - // ID allocated by the KMS API when the buffer is registered (via the handle). - virtual uint32_t GetFramebufferId() const = 0; - - // Handle for the buffer. This is received when allocating the buffer. - virtual uint32_t GetHandle() const = 0; - - // Size of the buffer. - virtual gfx::Size GetSize() const = 0; - - protected: - virtual ~ScanoutBuffer() {} - - friend class base::RefCounted<ScanoutBuffer>; -}; - -class ScanoutBufferGenerator { - public: - virtual ~ScanoutBufferGenerator() {} - - virtual scoped_refptr<ScanoutBuffer> Create(const gfx::Size& size) = 0; -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_SCANOUT_BUFFER_H_
diff --git a/ui/ozone/platform/dri/scoped_drm_types.cc b/ui/ozone/platform/dri/scoped_drm_types.cc deleted file mode 100644 index 0f1c6b3..0000000 --- a/ui/ozone/platform/dri/scoped_drm_types.cc +++ /dev/null
@@ -1,53 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/dri/scoped_drm_types.h" - -#include <xf86drmMode.h> - -namespace ui { - -void DrmResourcesDeleter::operator()(drmModeRes* resources) const { - drmModeFreeResources(resources); -} - -void DrmConnectorDeleter::operator()(drmModeConnector* connector) const { - drmModeFreeConnector(connector); -} - -void DrmCrtcDeleter::operator()(drmModeCrtc* crtc) const { - drmModeFreeCrtc(crtc); -} - -void DrmEncoderDeleter::operator()(drmModeEncoder* encoder) const { - drmModeFreeEncoder(encoder); -} - -void DrmObjectPropertiesDeleter::operator()( - drmModeObjectProperties* properties) const { - drmModeFreeObjectProperties(properties); -} - -void DrmPlaneDeleter::operator()(drmModePlane* plane) const { - drmModeFreePlane(plane); -} - -void DrmPlaneResDeleter::operator()(drmModePlaneRes* plane) const { - drmModeFreePlaneResources(plane); -} - -void DrmPropertyDeleter::operator()(drmModePropertyRes* property) const { - drmModeFreeProperty(property); -} - -void DrmPropertyBlobDeleter::operator()( - drmModePropertyBlobRes* property) const { - drmModeFreePropertyBlob(property); -} - -void DrmFramebufferDeleter::operator()(drmModeFB* framebuffer) const { - drmModeFreeFB(framebuffer); -} - -} // namespace ui
diff --git a/ui/ozone/platform/dri/scoped_drm_types.h b/ui/ozone/platform/dri/scoped_drm_types.h deleted file mode 100644 index e651232..0000000 --- a/ui/ozone/platform/dri/scoped_drm_types.h +++ /dev/null
@@ -1,69 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_SCOPED_DRM_TYPES_H_ -#define UI_OZONE_PLATFORM_DRI_SCOPED_DRM_TYPES_H_ - -#include "base/memory/scoped_ptr.h" - -typedef struct _drmModeConnector drmModeConnector; -typedef struct _drmModeCrtc drmModeCrtc; -typedef struct _drmModeEncoder drmModeEncoder; -typedef struct _drmModeFB drmModeFB; -typedef struct _drmModeObjectProperties drmModeObjectProperties; -typedef struct _drmModePlane drmModePlane; -typedef struct _drmModePlaneRes drmModePlaneRes; -typedef struct _drmModeProperty drmModePropertyRes; -typedef struct _drmModePropertyBlob drmModePropertyBlobRes; -typedef struct _drmModeRes drmModeRes; - -namespace ui { - -struct DrmResourcesDeleter { - void operator()(drmModeRes* resources) const; -}; -struct DrmConnectorDeleter { - void operator()(drmModeConnector* connector) const; -}; -struct DrmCrtcDeleter { - void operator()(drmModeCrtc* crtc) const; -}; -struct DrmEncoderDeleter { - void operator()(drmModeEncoder* encoder) const; -}; -struct DrmObjectPropertiesDeleter { - void operator()(drmModeObjectProperties* properties) const; -}; -struct DrmPlaneDeleter { - void operator()(drmModePlane* plane) const; -}; -struct DrmPlaneResDeleter { - void operator()(drmModePlaneRes* plane_res) const; -}; -struct DrmPropertyDeleter { - void operator()(drmModePropertyRes* property) const; -}; -struct DrmPropertyBlobDeleter { - void operator()(drmModePropertyBlobRes* property) const; -}; -struct DrmFramebufferDeleter { - void operator()(drmModeFB* framebuffer) const; -}; - -typedef scoped_ptr<drmModeRes, DrmResourcesDeleter> ScopedDrmResourcesPtr; -typedef scoped_ptr<drmModeConnector, DrmConnectorDeleter> ScopedDrmConnectorPtr; -typedef scoped_ptr<drmModeCrtc, DrmCrtcDeleter> ScopedDrmCrtcPtr; -typedef scoped_ptr<drmModeEncoder, DrmEncoderDeleter> ScopedDrmEncoderPtr; -typedef scoped_ptr<drmModeObjectProperties, DrmObjectPropertiesDeleter> - ScopedDrmObjectPropertyPtr; -typedef scoped_ptr<drmModePlane, DrmPlaneDeleter> ScopedDrmPlanePtr; -typedef scoped_ptr<drmModePlaneRes, DrmPlaneResDeleter> ScopedDrmPlaneResPtr; -typedef scoped_ptr<drmModePropertyRes, DrmPropertyDeleter> ScopedDrmPropertyPtr; -typedef scoped_ptr<drmModePropertyBlobRes, DrmPropertyBlobDeleter> -ScopedDrmPropertyBlobPtr; -typedef scoped_ptr<drmModeFB, DrmFramebufferDeleter> ScopedDrmFramebufferPtr; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_SCOPED_DRM_TYPES_H_
diff --git a/ui/ozone/platform/dri/screen_manager.cc b/ui/ozone/platform/dri/screen_manager.cc deleted file mode 100644 index 10f38c3..0000000 --- a/ui/ozone/platform/dri/screen_manager.cc +++ /dev/null
@@ -1,218 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/dri/screen_manager.h" - -#include <xf86drmMode.h> - -#include "ui/gfx/geometry/point.h" -#include "ui/gfx/geometry/rect.h" -#include "ui/gfx/geometry/size.h" -#include "ui/ozone/platform/dri/crtc_controller.h" -#include "ui/ozone/platform/dri/dri_util.h" -#include "ui/ozone/platform/dri/dri_wrapper.h" -#include "ui/ozone/platform/dri/hardware_display_controller.h" -#include "ui/ozone/platform/dri/scanout_buffer.h" - -namespace ui { - -ScreenManager::ScreenManager(DriWrapper* dri, - ScanoutBufferGenerator* buffer_generator) - : dri_(dri), buffer_generator_(buffer_generator) { -} - -ScreenManager::~ScreenManager() { -} - -void ScreenManager::AddDisplayController(DriWrapper* dri, - uint32_t crtc, - uint32_t connector) { - HardwareDisplayControllers::iterator it = FindDisplayController(crtc); - // TODO(dnicoara): Turn this into a DCHECK when async display configuration is - // properly supported. (When there can't be a race between forcing initial - // display configuration in ScreenManager and NativeDisplayDelegate creating - // the display controllers.) - if (it != controllers_.end()) { - LOG(WARNING) << "Display controller (crtc=" << crtc << ") already present."; - return; - } - - controllers_.push_back(new HardwareDisplayController( - scoped_ptr<CrtcController>(new CrtcController(dri, crtc, connector)))); -} - -void ScreenManager::RemoveDisplayController(uint32_t crtc) { - HardwareDisplayControllers::iterator it = FindDisplayController(crtc); - if (it != controllers_.end()) { - bool is_mirrored = (*it)->IsMirrored(); - (*it)->RemoveCrtc(crtc); - if (!is_mirrored) - controllers_.erase(it); - } -} - -bool ScreenManager::ConfigureDisplayController(uint32_t crtc, - uint32_t connector, - const gfx::Point& origin, - const drmModeModeInfo& mode) { - gfx::Rect modeset_bounds( - origin.x(), origin.y(), mode.hdisplay, mode.vdisplay); - HardwareDisplayControllers::iterator it = FindDisplayController(crtc); - DCHECK(controllers_.end() != it) << "Display controller (crtc=" << crtc - << ") doesn't exist."; - - HardwareDisplayController* controller = *it; - controller = *it; - // If nothing changed just enable the controller. Note, we perform an exact - // comparison on the mode since the refresh rate may have changed. - if (SameMode(mode, controller->get_mode()) && - origin == controller->origin() && !controller->IsDisabled()) - return controller->Enable(); - - // Either the mode or the location of the display changed, so exit mirror - // mode and configure the display independently. If the caller still wants - // mirror mode, subsequent calls configuring the other controllers will - // restore mirror mode. - if (controller->IsMirrored()) { - controller = new HardwareDisplayController(controller->RemoveCrtc(crtc)); - controllers_.push_back(controller); - it = controllers_.end() - 1; - } - - HardwareDisplayControllers::iterator mirror = - FindActiveDisplayControllerByLocation(modeset_bounds); - // Handle mirror mode. - if (mirror != controllers_.end() && it != mirror) - return HandleMirrorMode(it, mirror, crtc, connector); - - return ModesetDisplayController(controller, origin, mode); -} - -bool ScreenManager::DisableDisplayController(uint32_t crtc) { - HardwareDisplayControllers::iterator it = FindDisplayController(crtc); - if (it != controllers_.end()) { - if ((*it)->IsMirrored()) { - HardwareDisplayController* controller = - new HardwareDisplayController((*it)->RemoveCrtc(crtc)); - controllers_.push_back(controller); - } - - (*it)->Disable(); - return true; - } - - LOG(ERROR) << "Failed to find display controller crtc=" << crtc; - return false; -} - -base::WeakPtr<HardwareDisplayController> ScreenManager::GetDisplayController( - const gfx::Rect& bounds) { - // TODO(dnicoara): Remove hack once TestScreen uses a simple Ozone display - // configuration reader and ScreenManager is called from there to create the - // one display needed by the content_shell target. - if (controllers_.empty()) - ForceInitializationOfPrimaryDisplay(); - - HardwareDisplayControllers::iterator it = - FindActiveDisplayControllerByLocation(bounds); - if (it != controllers_.end()) - return (*it)->AsWeakPtr(); - - return base::WeakPtr<HardwareDisplayController>(); -} - -ScreenManager::HardwareDisplayControllers::iterator -ScreenManager::FindDisplayController(uint32_t crtc) { - for (HardwareDisplayControllers::iterator it = controllers_.begin(); - it != controllers_.end(); - ++it) { - if ((*it)->HasCrtc(crtc)) - return it; - } - - return controllers_.end(); -} - -ScreenManager::HardwareDisplayControllers::iterator -ScreenManager::FindActiveDisplayControllerByLocation(const gfx::Rect& bounds) { - for (HardwareDisplayControllers::iterator it = controllers_.begin(); - it != controllers_.end(); - ++it) { - gfx::Rect controller_bounds((*it)->origin(), (*it)->GetModeSize()); - // We don't perform a strict check since content_shell will have windows - // smaller than the display size. - if (controller_bounds.Contains(bounds) && !(*it)->IsDisabled()) - return it; - } - - return controllers_.end(); -} - -void ScreenManager::ForceInitializationOfPrimaryDisplay() { - LOG(WARNING) << "Forcing initialization of primary display."; - ScopedVector<HardwareDisplayControllerInfo> displays = - GetAvailableDisplayControllerInfos(dri_->get_fd()); - - DCHECK_NE(0u, displays.size()); - - ScopedDrmPropertyPtr dpms( - dri_->GetProperty(displays[0]->connector(), "DPMS")); - if (dpms) - dri_->SetProperty(displays[0]->connector()->connector_id, - dpms->prop_id, - DRM_MODE_DPMS_ON); - - AddDisplayController(dri_, - displays[0]->crtc()->crtc_id, - displays[0]->connector()->connector_id); - ConfigureDisplayController(displays[0]->crtc()->crtc_id, - displays[0]->connector()->connector_id, - gfx::Point(), - displays[0]->connector()->modes[0]); -} - -bool ScreenManager::ModesetDisplayController( - HardwareDisplayController* controller, - const gfx::Point& origin, - const drmModeModeInfo& mode) { - controller->set_origin(origin); - // Create a surface suitable for the current controller. - scoped_refptr<ScanoutBuffer> buffer = - buffer_generator_->Create(gfx::Size(mode.hdisplay, mode.vdisplay)); - - if (!buffer.get()) { - LOG(ERROR) << "Failed to create scanout buffer"; - return false; - } - - if (!controller->Modeset(OverlayPlane(buffer), mode)) { - LOG(ERROR) << "Failed to modeset controller"; - return false; - } - - return true; -} - -bool ScreenManager::HandleMirrorMode( - HardwareDisplayControllers::iterator original, - HardwareDisplayControllers::iterator mirror, - uint32_t crtc, - uint32_t connector) { - (*mirror)->AddCrtc((*original)->RemoveCrtc(crtc)); - if ((*mirror)->Enable()) { - controllers_.erase(original); - return true; - } - - LOG(ERROR) << "Failed to switch to mirror mode"; - - // When things go wrong revert back to the previous configuration since - // it is expected that the configuration would not have changed if - // things fail. - (*original)->AddCrtc((*mirror)->RemoveCrtc(crtc)); - (*original)->Enable(); - return false; -} - -} // namespace ui
diff --git a/ui/ozone/platform/dri/screen_manager.h b/ui/ozone/platform/dri/screen_manager.h deleted file mode 100644 index 6b95516..0000000 --- a/ui/ozone/platform/dri/screen_manager.h +++ /dev/null
@@ -1,100 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_SCREEN_MANAGER_H_ -#define UI_OZONE_PLATFORM_DRI_SCREEN_MANAGER_H_ - -#include "base/macros.h" -#include "base/memory/scoped_vector.h" -#include "base/memory/weak_ptr.h" -#include "ui/ozone/platform/dri/hardware_display_controller.h" - -typedef struct _drmModeModeInfo drmModeModeInfo; - -namespace gfx { -class Point; -class Rect; -class Size; -} // namespace gfx - -namespace ui { - -class DriWrapper; -class ScanoutBufferGenerator; - -// Responsible for keeping track of active displays and configuring them. -class ScreenManager { - public: - ScreenManager(DriWrapper* dri, ScanoutBufferGenerator* surface_generator); - virtual ~ScreenManager(); - - // Register a display controller. This must be called before trying to - // configure it. - void AddDisplayController(DriWrapper* dri, uint32_t crtc, uint32_t connector); - - // Remove a display controller from the list of active controllers. The - // controller is removed since it was disconnected. - void RemoveDisplayController(uint32_t crtc); - - // Configure a display controller. The display controller is identified by - // (|crtc|, |connector|) and the controller is modeset using |mode|. - bool ConfigureDisplayController(uint32_t crtc, - uint32_t connector, - const gfx::Point& origin, - const drmModeModeInfo& mode); - - // Disable the display controller identified by |crtc|. Note, the controller - // may still be connected, so this does not remove the controller. - bool DisableDisplayController(uint32_t crtc); - - // Returns a reference to the display controller configured to display within - // |bounds|. - // This returns a weak reference since the display controller may be destroyed - // at any point in time, but the changes are propagated to the compositor much - // later (Compositor owns SurfaceOzone*, which is responsible for updating the - // display surface). - base::WeakPtr<HardwareDisplayController> GetDisplayController( - const gfx::Rect& bounds); - - // On non CrOS builds there is no display configurator to look-up available - // displays and initialize the HDCs. In such cases this is called internally - // to initialize a display. - virtual void ForceInitializationOfPrimaryDisplay(); - - private: - typedef ScopedVector<HardwareDisplayController> HardwareDisplayControllers; - - // Returns an iterator into |controllers_| for the controller identified by - // (|crtc|, |connector|). - HardwareDisplayControllers::iterator FindDisplayController(uint32_t crtc); - - // Returns an iterator into |controllers_| for the controller located at - // |origin|. - HardwareDisplayControllers::iterator FindActiveDisplayControllerByLocation( - const gfx::Rect& bounds); - - // Perform modesetting in |controller| using |origin| and |mode|. - bool ModesetDisplayController(HardwareDisplayController* controller, - const gfx::Point& origin, - const drmModeModeInfo& mode); - - // Tries to set the controller identified by (|crtc|, |connector|) to mirror - // those in |mirror|. |original| is an iterator to the HDC where the - // controller is currently present. - bool HandleMirrorMode(HardwareDisplayControllers::iterator original, - HardwareDisplayControllers::iterator mirror, - uint32_t crtc, - uint32_t connector); - - DriWrapper* dri_; // Not owned. - ScanoutBufferGenerator* buffer_generator_; // Not owned. - // List of display controllers (active and disabled). - HardwareDisplayControllers controllers_; - - DISALLOW_COPY_AND_ASSIGN(ScreenManager); -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_SCREEN_MANAGER_H_
diff --git a/ui/ozone/platform/dri/screen_manager_unittest.cc b/ui/ozone/platform/dri/screen_manager_unittest.cc deleted file mode 100644 index 1ee0006..0000000 --- a/ui/ozone/platform/dri/screen_manager_unittest.cc +++ /dev/null
@@ -1,253 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/ozone/platform/dri/dri_buffer.h" -#include "ui/ozone/platform/dri/hardware_display_controller.h" -#include "ui/ozone/platform/dri/screen_manager.h" -#include "ui/ozone/platform/dri/test/mock_dri_wrapper.h" - -namespace { - -// Create a basic mode for a 6x4 screen. -const drmModeModeInfo kDefaultMode = - {0, 6, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, {'\0'}}; - -const uint32_t kPrimaryCrtc = 1; -const uint32_t kPrimaryConnector = 2; -const uint32_t kSecondaryCrtc = 3; -const uint32_t kSecondaryConnector = 4; - -class MockScreenManager : public ui::ScreenManager { - public: - MockScreenManager(ui::DriWrapper* dri, - ui::ScanoutBufferGenerator* buffer_generator) - : ScreenManager(dri, buffer_generator), dri_(dri) {} - - virtual void ForceInitializationOfPrimaryDisplay() override {} - - private: - ui::DriWrapper* dri_; - - DISALLOW_COPY_AND_ASSIGN(MockScreenManager); -}; - -} // namespace - -class ScreenManagerTest : public testing::Test { - public: - ScreenManagerTest() {} - virtual ~ScreenManagerTest() {} - - gfx::Rect GetPrimaryBounds() const { - return gfx::Rect(0, 0, kDefaultMode.hdisplay, kDefaultMode.vdisplay); - } - - // Secondary is in extended mode, right-of primary. - gfx::Rect GetSecondaryBounds() const { - return gfx::Rect( - kDefaultMode.hdisplay, 0, kDefaultMode.hdisplay, kDefaultMode.vdisplay); - } - - virtual void SetUp() override { - dri_.reset(new ui::MockDriWrapper(3)); - buffer_generator_.reset(new ui::DriBufferGenerator(dri_.get())); - screen_manager_.reset(new MockScreenManager( - dri_.get(), buffer_generator_.get())); - } - virtual void TearDown() override { - screen_manager_.reset(); - dri_.reset(); - } - - protected: - scoped_ptr<ui::MockDriWrapper> dri_; - scoped_ptr<ui::DriBufferGenerator> buffer_generator_; - scoped_ptr<MockScreenManager> screen_manager_; - - private: - DISALLOW_COPY_AND_ASSIGN(ScreenManagerTest); -}; - -TEST_F(ScreenManagerTest, CheckWithNoControllers) { - EXPECT_FALSE(screen_manager_->GetDisplayController(GetPrimaryBounds())); -} - -TEST_F(ScreenManagerTest, CheckWithValidController) { - screen_manager_->AddDisplayController( - dri_.get(), kPrimaryCrtc, kPrimaryConnector); - screen_manager_->ConfigureDisplayController(kPrimaryCrtc, - kPrimaryConnector, - GetPrimaryBounds().origin(), - kDefaultMode); - base::WeakPtr<ui::HardwareDisplayController> controller = - screen_manager_->GetDisplayController(GetPrimaryBounds()); - - EXPECT_TRUE(controller); - EXPECT_TRUE(controller->HasCrtc(kPrimaryCrtc)); -} - -TEST_F(ScreenManagerTest, CheckWithInvalidBounds) { - screen_manager_->AddDisplayController( - dri_.get(), kPrimaryCrtc, kPrimaryConnector); - screen_manager_->ConfigureDisplayController(kPrimaryCrtc, - kPrimaryConnector, - GetPrimaryBounds().origin(), - kDefaultMode); - - EXPECT_TRUE(screen_manager_->GetDisplayController(GetPrimaryBounds())); - EXPECT_FALSE(screen_manager_->GetDisplayController(GetSecondaryBounds())); -} - -TEST_F(ScreenManagerTest, CheckForSecondValidController) { - screen_manager_->AddDisplayController( - dri_.get(), kPrimaryCrtc, kPrimaryConnector); - screen_manager_->ConfigureDisplayController(kPrimaryCrtc, - kPrimaryConnector, - GetPrimaryBounds().origin(), - kDefaultMode); - screen_manager_->AddDisplayController( - dri_.get(), kSecondaryCrtc, kSecondaryConnector); - screen_manager_->ConfigureDisplayController(kSecondaryCrtc, - kSecondaryConnector, - GetSecondaryBounds().origin(), - kDefaultMode); - - EXPECT_TRUE(screen_manager_->GetDisplayController(GetPrimaryBounds())); - EXPECT_TRUE(screen_manager_->GetDisplayController(GetSecondaryBounds())); -} - -TEST_F(ScreenManagerTest, CheckControllerAfterItIsRemoved) { - screen_manager_->AddDisplayController( - dri_.get(), kPrimaryCrtc, kPrimaryConnector); - screen_manager_->ConfigureDisplayController(kPrimaryCrtc, - kPrimaryConnector, - GetPrimaryBounds().origin(), - kDefaultMode); - base::WeakPtr<ui::HardwareDisplayController> controller = - screen_manager_->GetDisplayController(GetPrimaryBounds()); - - EXPECT_TRUE(controller); - screen_manager_->RemoveDisplayController(kPrimaryCrtc); - EXPECT_FALSE(controller); -} - -TEST_F(ScreenManagerTest, CheckDuplicateConfiguration) { - screen_manager_->AddDisplayController( - dri_.get(), kPrimaryCrtc, kPrimaryConnector); - screen_manager_->ConfigureDisplayController(kPrimaryCrtc, - kPrimaryConnector, - GetPrimaryBounds().origin(), - kDefaultMode); - screen_manager_->ConfigureDisplayController(kPrimaryCrtc, - kPrimaryConnector, - GetPrimaryBounds().origin(), - kDefaultMode); - - EXPECT_TRUE(screen_manager_->GetDisplayController(GetPrimaryBounds())); - EXPECT_FALSE(screen_manager_->GetDisplayController(GetSecondaryBounds())); -} - -TEST_F(ScreenManagerTest, CheckChangingMode) { - screen_manager_->AddDisplayController( - dri_.get(), kPrimaryCrtc, kPrimaryConnector); - screen_manager_->ConfigureDisplayController(kPrimaryCrtc, - kPrimaryConnector, - GetPrimaryBounds().origin(), - kDefaultMode); - drmModeModeInfo new_mode = kDefaultMode; - new_mode.vdisplay = 10; - screen_manager_->ConfigureDisplayController( - kPrimaryCrtc, kPrimaryConnector, GetPrimaryBounds().origin(), new_mode); - - gfx::Rect new_bounds(0, 0, new_mode.hdisplay, new_mode.vdisplay); - EXPECT_TRUE(screen_manager_->GetDisplayController(new_bounds)); - EXPECT_FALSE(screen_manager_->GetDisplayController(GetSecondaryBounds())); - drmModeModeInfo mode = - screen_manager_->GetDisplayController(new_bounds)->get_mode(); - EXPECT_EQ(new_mode.vdisplay, mode.vdisplay); - EXPECT_EQ(new_mode.hdisplay, mode.hdisplay); -} - -TEST_F(ScreenManagerTest, CheckForControllersInMirroredMode) { - screen_manager_->AddDisplayController( - dri_.get(), kPrimaryCrtc, kPrimaryConnector); - screen_manager_->ConfigureDisplayController(kPrimaryCrtc, - kPrimaryConnector, - GetPrimaryBounds().origin(), - kDefaultMode); - screen_manager_->AddDisplayController( - dri_.get(), kSecondaryCrtc, kSecondaryConnector); - screen_manager_->ConfigureDisplayController(kSecondaryCrtc, - kSecondaryConnector, - GetPrimaryBounds().origin(), - kDefaultMode); - - EXPECT_TRUE(screen_manager_->GetDisplayController(GetPrimaryBounds())); - EXPECT_FALSE(screen_manager_->GetDisplayController(GetSecondaryBounds())); -} - -TEST_F(ScreenManagerTest, CheckMirrorModeTransitions) { - screen_manager_->AddDisplayController( - dri_.get(), kPrimaryCrtc, kPrimaryConnector); - screen_manager_->ConfigureDisplayController(kPrimaryCrtc, - kPrimaryConnector, - GetPrimaryBounds().origin(), - kDefaultMode); - screen_manager_->AddDisplayController( - dri_.get(), kSecondaryCrtc, kSecondaryConnector); - screen_manager_->ConfigureDisplayController(kSecondaryCrtc, - kSecondaryConnector, - GetSecondaryBounds().origin(), - kDefaultMode); - - EXPECT_TRUE(screen_manager_->GetDisplayController(GetPrimaryBounds())); - EXPECT_TRUE(screen_manager_->GetDisplayController(GetSecondaryBounds())); - - screen_manager_->ConfigureDisplayController(kPrimaryCrtc, - kPrimaryConnector, - GetPrimaryBounds().origin(), - kDefaultMode); - screen_manager_->ConfigureDisplayController(kSecondaryCrtc, - kSecondaryConnector, - GetPrimaryBounds().origin(), - kDefaultMode); - EXPECT_TRUE(screen_manager_->GetDisplayController(GetPrimaryBounds())); - EXPECT_FALSE(screen_manager_->GetDisplayController(GetSecondaryBounds())); - - screen_manager_->ConfigureDisplayController(kPrimaryCrtc, - kPrimaryConnector, - GetSecondaryBounds().origin(), - kDefaultMode); - screen_manager_->ConfigureDisplayController(kSecondaryCrtc, - kSecondaryConnector, - GetPrimaryBounds().origin(), - kDefaultMode); - EXPECT_TRUE(screen_manager_->GetDisplayController(GetPrimaryBounds())); - EXPECT_TRUE(screen_manager_->GetDisplayController(GetSecondaryBounds())); -} - -TEST_F(ScreenManagerTest, MonitorGoneInMirrorMode) { - screen_manager_->AddDisplayController( - dri_.get(), kPrimaryCrtc, kPrimaryConnector); - screen_manager_->ConfigureDisplayController(kPrimaryCrtc, - kPrimaryConnector, - GetPrimaryBounds().origin(), - kDefaultMode); - screen_manager_->AddDisplayController( - dri_.get(), kSecondaryCrtc, kSecondaryConnector); - screen_manager_->ConfigureDisplayController(kSecondaryCrtc, - kSecondaryConnector, - GetPrimaryBounds().origin(), - kDefaultMode); - - screen_manager_->RemoveDisplayController(kSecondaryCrtc); - EXPECT_TRUE( - screen_manager_->ConfigureDisplayController(kPrimaryCrtc, - kPrimaryConnector, - GetPrimaryBounds().origin(), - kDefaultMode)); - EXPECT_TRUE(screen_manager_->GetDisplayController(GetPrimaryBounds())); - EXPECT_FALSE(screen_manager_->GetDisplayController(GetSecondaryBounds())); -}
diff --git a/ui/ozone/platform/dri/test/mock_dri_wrapper.cc b/ui/ozone/platform/dri/test/mock_dri_wrapper.cc deleted file mode 100644 index fefddf7..0000000 --- a/ui/ozone/platform/dri/test/mock_dri_wrapper.cc +++ /dev/null
@@ -1,163 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/dri/test/mock_dri_wrapper.h" - -#include <xf86drm.h> -#include <xf86drmMode.h> - -#include "base/logging.h" -#include "third_party/skia/include/core/SkCanvas.h" -#include "ui/ozone/platform/dri/crtc_controller.h" - -namespace ui { - -namespace { - -template<class Object> Object* DrmAllocator() { - return static_cast<Object*>(drmMalloc(sizeof(Object))); -} - -} // namespace - -MockDriWrapper::MockDriWrapper(int fd) - : DriWrapper(""), - get_crtc_call_count_(0), - set_crtc_call_count_(0), - restore_crtc_call_count_(0), - add_framebuffer_call_count_(0), - remove_framebuffer_call_count_(0), - page_flip_call_count_(0), - overlay_flip_call_count_(0), - handle_events_count_(0), - set_crtc_expectation_(true), - add_framebuffer_expectation_(true), - page_flip_expectation_(true), - create_dumb_buffer_expectation_(true), - current_framebuffer_(0) { - fd_ = fd; -} - -MockDriWrapper::~MockDriWrapper() { - fd_ = -1; -} - -ScopedDrmCrtcPtr MockDriWrapper::GetCrtc(uint32_t crtc_id) { - get_crtc_call_count_++; - return ScopedDrmCrtcPtr(DrmAllocator<drmModeCrtc>()); -} - -bool MockDriWrapper::SetCrtc(uint32_t crtc_id, - uint32_t framebuffer, - std::vector<uint32_t> connectors, - drmModeModeInfo* mode) { - current_framebuffer_ = framebuffer; - set_crtc_call_count_++; - return set_crtc_expectation_; -} - -bool MockDriWrapper::SetCrtc(drmModeCrtc* crtc, - std::vector<uint32_t> connectors) { - restore_crtc_call_count_++; - return true; -} - -ScopedDrmConnectorPtr MockDriWrapper::GetConnector(uint32_t connector_id) { - return ScopedDrmConnectorPtr(DrmAllocator<drmModeConnector>()); -} - -bool MockDriWrapper::AddFramebuffer(uint32_t width, - uint32_t height, - uint8_t depth, - uint8_t bpp, - uint32_t stride, - uint32_t handle, - uint32_t* framebuffer) { - add_framebuffer_call_count_++; - *framebuffer = add_framebuffer_call_count_; - return add_framebuffer_expectation_; -} - -bool MockDriWrapper::RemoveFramebuffer(uint32_t framebuffer) { - remove_framebuffer_call_count_++; - return true; -} - -bool MockDriWrapper::PageFlip(uint32_t crtc_id, - uint32_t framebuffer, - void* data) { - page_flip_call_count_++; - current_framebuffer_ = framebuffer; - controllers_.push(static_cast<ui::CrtcController*>(data)); - return page_flip_expectation_; -} - -bool MockDriWrapper::PageFlipOverlay(uint32_t crtc_id, - uint32_t framebuffer, - const gfx::Rect& location, - const gfx::RectF& source, - int overlay_plane) { - overlay_flip_call_count_++; - return true; -} - -ScopedDrmPropertyPtr MockDriWrapper::GetProperty(drmModeConnector* connector, - const char* name) { - return ScopedDrmPropertyPtr(DrmAllocator<drmModePropertyRes>()); -} - -bool MockDriWrapper::SetProperty(uint32_t connector_id, - uint32_t property_id, - uint64_t value) { - return true; -} - -ScopedDrmPropertyBlobPtr MockDriWrapper::GetPropertyBlob( - drmModeConnector* connector, - const char* name) { - return ScopedDrmPropertyBlobPtr(DrmAllocator<drmModePropertyBlobRes>()); -} - -bool MockDriWrapper::SetCursor(uint32_t crtc_id, - uint32_t handle, - const gfx::Size& size) { - return true; -} - -bool MockDriWrapper::MoveCursor(uint32_t crtc_id, const gfx::Point& point) { - return true; -} - -void MockDriWrapper::HandleEvent(drmEventContext& event) { - CHECK(!controllers_.empty()); - controllers_.front()->OnPageFlipEvent(0, 0, 0); - controllers_.pop(); - handle_events_count_++; -} - -bool MockDriWrapper::CreateDumbBuffer(const SkImageInfo& info, - uint32_t* handle, - uint32_t* stride, - void** pixels) { - if (!create_dumb_buffer_expectation_) - return false; - - *handle = 0; - *stride = info.minRowBytes(); - *pixels = new char[info.getSafeSize(*stride)]; - buffers_.push_back( - skia::AdoptRef(SkSurface::NewRasterDirect(info, *pixels, *stride))); - buffers_.back()->getCanvas()->clear(SK_ColorBLACK); - - return true; -} - -void MockDriWrapper::DestroyDumbBuffer(const SkImageInfo& info, - uint32_t handle, - uint32_t stride, - void* pixels) { - delete[] static_cast<char*>(pixels); -} - -} // namespace ui
diff --git a/ui/ozone/platform/dri/test/mock_dri_wrapper.h b/ui/ozone/platform/dri/test/mock_dri_wrapper.h deleted file mode 100644 index a9b68b7..0000000 --- a/ui/ozone/platform/dri/test/mock_dri_wrapper.h +++ /dev/null
@@ -1,130 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_TEST_MOCK_DRI_WRAPPER_H_ -#define UI_OZONE_PLATFORM_DRI_TEST_MOCK_DRI_WRAPPER_H_ - -#include <queue> -#include <vector> - -#include "skia/ext/refptr.h" -#include "third_party/skia/include/core/SkSurface.h" -#include "ui/ozone/platform/dri/dri_wrapper.h" - -namespace ui { - -class CrtcController; - -// The real DriWrapper makes actual DRM calls which we can't use in unit tests. -class MockDriWrapper : public ui::DriWrapper { - public: - MockDriWrapper(int fd); - virtual ~MockDriWrapper(); - - int get_get_crtc_call_count() const { return get_crtc_call_count_; } - int get_set_crtc_call_count() const { return set_crtc_call_count_; } - int get_restore_crtc_call_count() const { return restore_crtc_call_count_; } - int get_add_framebuffer_call_count() const { - return add_framebuffer_call_count_; - } - int get_remove_framebuffer_call_count() const { - return remove_framebuffer_call_count_; - } - int get_page_flip_call_count() const { return page_flip_call_count_; } - int get_overlay_flip_call_count() const { return overlay_flip_call_count_; } - int get_handle_events_count() const { return handle_events_count_; } - void fail_init() { fd_ = -1; } - void set_set_crtc_expectation(bool state) { set_crtc_expectation_ = state; } - void set_page_flip_expectation(bool state) { page_flip_expectation_ = state; } - void set_add_framebuffer_expectation(bool state) { - add_framebuffer_expectation_ = state; - } - void set_create_dumb_buffer_expectation(bool state) { - create_dumb_buffer_expectation_ = state; - } - - uint32_t current_framebuffer() const { return current_framebuffer_; } - - const std::vector<skia::RefPtr<SkSurface> > buffers() const { - return buffers_; - } - - // Overwrite the list of controllers used when serving the PageFlip requests. - void set_controllers(const std::queue<CrtcController*>& controllers) { - controllers_ = controllers; - } - - // DriWrapper: - virtual ScopedDrmCrtcPtr GetCrtc(uint32_t crtc_id) override; - virtual bool SetCrtc(uint32_t crtc_id, - uint32_t framebuffer, - std::vector<uint32_t> connectors, - drmModeModeInfo* mode) override; - virtual bool SetCrtc(drmModeCrtc* crtc, - std::vector<uint32_t> connectors) override; - virtual ScopedDrmConnectorPtr GetConnector(uint32_t connector_id) override; - virtual bool AddFramebuffer(uint32_t width, - uint32_t height, - uint8_t depth, - uint8_t bpp, - uint32_t stride, - uint32_t handle, - uint32_t* framebuffer) override; - virtual bool RemoveFramebuffer(uint32_t framebuffer) override; - virtual bool PageFlip(uint32_t crtc_id, - uint32_t framebuffer, - void* data) override; - virtual bool PageFlipOverlay(uint32_t crtc_id, - uint32_t framebuffer, - const gfx::Rect& location, - const gfx::RectF& source, - int overlay_plane) override; - virtual ScopedDrmPropertyPtr GetProperty(drmModeConnector* connector, - const char* name) override; - virtual bool SetProperty(uint32_t connector_id, - uint32_t property_id, - uint64_t value) override; - virtual ScopedDrmPropertyBlobPtr GetPropertyBlob(drmModeConnector* connector, - const char* name) override; - virtual bool SetCursor(uint32_t crtc_id, - uint32_t handle, - const gfx::Size& size) override; - virtual bool MoveCursor(uint32_t crtc_id, const gfx::Point& point) override; - virtual void HandleEvent(drmEventContext& event) override; - virtual bool CreateDumbBuffer(const SkImageInfo& info, - uint32_t* handle, - uint32_t* stride, - void** pixels) override; - virtual void DestroyDumbBuffer(const SkImageInfo& info, - uint32_t handle, - uint32_t stride, - void* pixels) override; - - private: - int get_crtc_call_count_; - int set_crtc_call_count_; - int restore_crtc_call_count_; - int add_framebuffer_call_count_; - int remove_framebuffer_call_count_; - int page_flip_call_count_; - int overlay_flip_call_count_; - int handle_events_count_; - - bool set_crtc_expectation_; - bool add_framebuffer_expectation_; - bool page_flip_expectation_; - bool create_dumb_buffer_expectation_; - - uint32_t current_framebuffer_; - - std::vector<skia::RefPtr<SkSurface> > buffers_; - - std::queue<CrtcController*> controllers_; - - DISALLOW_COPY_AND_ASSIGN(MockDriWrapper); -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_TEST_MOCK_DRI_WRAPPER_H_
diff --git a/ui/ozone/platform/dri/virtual_terminal_manager.cc b/ui/ozone/platform/dri/virtual_terminal_manager.cc deleted file mode 100644 index efd8350..0000000 --- a/ui/ozone/platform/dri/virtual_terminal_manager.cc +++ /dev/null
@@ -1,75 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/dri/virtual_terminal_manager.h" - -#include <errno.h> -#include <fcntl.h> -#include <linux/kd.h> -#include <linux/vt.h> -#include <sys/ioctl.h> -#include <unistd.h> - -#include "base/logging.h" - -namespace ui { - -namespace { - -const char kTTYDevice[] = "/dev/tty1"; - -const int kVT = 1; - -} // namespace - -VirtualTerminalManager::VirtualTerminalManager() { - // Use the current console. - fd_ = open(kTTYDevice, O_RDWR | O_CLOEXEC, 0); - if (fd_ < 0) - LOG(ERROR) << "Failed to open '" << kTTYDevice << "' " << strerror(errno); - - if (ioctl(fd_, VT_ACTIVATE, kVT) || ioctl(fd_, VT_WAITACTIVE, kVT)) - LOG(ERROR) << "Failed to switch to VT: " << kVT - << " error: " << strerror(errno);; - - if (ioctl(fd_, KDGETMODE, &vt_mode_)) - LOG(ERROR) << "Failed to get VT mode: " << strerror(errno); - - if (ioctl(fd_, KDSETMODE, KD_GRAPHICS)) - LOG(ERROR) << "Failed to set graphics mode: " << strerror(errno); - - if (tcgetattr(fd_, &terminal_attributes_)) - LOG(ERROR) << "Failed to get terminal attributes"; - - // Stop the TTY from processing keys and echo-ing them to the terminal. - struct termios raw_attributes = terminal_attributes_; - cfmakeraw(&raw_attributes); - raw_attributes.c_oflag |= OPOST; - if (tcsetattr(fd_, TCSANOW, &raw_attributes)) - LOG(ERROR) << "Failed to set raw attributes"; - - if (ioctl(fd_, KDGKBMODE, &previous_keyboard_mode_)) - LOG(ERROR) << "Failed to get keyboard mode"; - - if (ioctl(fd_, KDSKBMODE, K_OFF) && ioctl(fd_, KDSKBMODE, K_RAW)) - LOG(ERROR) << "Failed to set keyboard mode"; -} - -VirtualTerminalManager::~VirtualTerminalManager() { - if (fd_ < 0) - return; - - if (ioctl(fd_, KDSETMODE, &vt_mode_)) - LOG(ERROR) << "Failed to restore VT mode"; - - if (ioctl(fd_, KDSKBMODE, previous_keyboard_mode_)) - LOG(ERROR) << "Failed to restore keyboard mode"; - - if (tcsetattr(fd_, TCSANOW, &terminal_attributes_)) - LOG(ERROR) << "Failed to restore terminal attributes"; - - close(fd_); -} - -} // namespace ui
diff --git a/ui/ozone/platform/dri/virtual_terminal_manager.h b/ui/ozone/platform/dri/virtual_terminal_manager.h deleted file mode 100644 index 11af0b0..0000000 --- a/ui/ozone/platform/dri/virtual_terminal_manager.h +++ /dev/null
@@ -1,31 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_DRI_VIRTUAL_TERMINAL_MANAGER_H_ -#define UI_OZONE_PLATFORM_DRI_VIRTUAL_TERMINAL_MANAGER_H_ - -#include <termios.h> - -#include "base/basictypes.h" - -namespace ui { - -class VirtualTerminalManager { - public: - VirtualTerminalManager(); - ~VirtualTerminalManager(); - - private: - - int fd_; - int vt_mode_; - int previous_keyboard_mode_; - struct termios terminal_attributes_; - - DISALLOW_COPY_AND_ASSIGN(VirtualTerminalManager); -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_DRI_VIRTUAL_TERMINAL_MANAGER_H_
diff --git a/ui/ozone/platform/egltest/BUILD.gn b/ui/ozone/platform/egltest/BUILD.gn deleted file mode 100644 index b9c4fcf..0000000 --- a/ui/ozone/platform/egltest/BUILD.gn +++ /dev/null
@@ -1,39 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import("//tools/generate_library_loader/generate_library_loader.gni") - -source_set("egltest") { - sources = [ - "ozone_platform_egltest.cc", - "ozone_platform_egltest.h", - ] - - deps = [ - ":eglplatform_shim", - "//base", - "//ui/events/ozone:events_ozone_evdev", - "//ui/gfx", - ] -} - -generate_library_loader("eglplatform_shim") { - name = "LibeglplatformShimLoader" - output_h = "libeglplatform_shim.h" - output_cc = "libeglplatform_shim_loader.cc" - header = "\"ui/ozone/platform/egltest/eglplatform_shim.h\"" - - functions = [ - "ShimQueryString", - "ShimInitialize", - "ShimTerminate", - "ShimCreateWindow", - "ShimQueryWindow", - "ShimDestroyWindow", - "ShimGetNativeDisplay", - "ShimGetNativeWindow", - "ShimReleaseNativeWindow", - ] -} -# TODO(spang): eglplatform_shim_x11 once support lands: http://crbug.com/380327
diff --git a/ui/ozone/platform/egltest/eglplatform_shim.h b/ui/ozone/platform/egltest/eglplatform_shim.h deleted file mode 100644 index ce7cce9..0000000 --- a/ui/ozone/platform/egltest/eglplatform_shim.h +++ /dev/null
@@ -1,58 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef __eglplatform_shim_h_ -#define __eglplatform_shim_h_ - -#include <stdbool.h> -#include <stdint.h> - -#ifdef __cplusplus -extern "C" { -#endif - -#define SHIM_EXPORT __attribute__((visibility("default"))) - -// Simple integral native window identifier. -// NB: Unlike EGLNativeWindowType, this will be shipped between processes. -typedef int ShimNativeWindowId; -#define SHIM_NO_WINDOW_ID ((ShimNativeWindowId)0) - -// Opaque versions of EGL types (as used by ozone). -typedef intptr_t ShimEGLNativeDisplayType; -typedef intptr_t ShimEGLNativeWindowType; - -// QueryString targets -#define SHIM_EGL_LIBRARY 0x1001 -#define SHIM_GLES_LIBRARY 0x1002 - -// CreateWindow / QueryWindow attributes -#define SHIM_WINDOW_WIDTH 0x0001 -#define SHIM_WINDOW_HEIGHT 0x0002 - -// Query global implementation information. -SHIM_EXPORT const char* ShimQueryString(int name); - -// Init/terminate library. -SHIM_EXPORT bool ShimInitialize(void); -SHIM_EXPORT bool ShimTerminate(void); - -// Create window handle & query window properties (called from browser process). -SHIM_EXPORT ShimNativeWindowId ShimCreateWindow(void); -SHIM_EXPORT bool ShimQueryWindow(ShimNativeWindowId window_id, - int attribute, - int* value); -SHIM_EXPORT bool ShimDestroyWindow(ShimNativeWindowId window_id); - -// Manage actual EGL platform objects (called from GPU process). -SHIM_EXPORT ShimEGLNativeDisplayType ShimGetNativeDisplay(void); -SHIM_EXPORT ShimEGLNativeWindowType - ShimGetNativeWindow(ShimNativeWindowId native_window_id); -SHIM_EXPORT bool ShimReleaseNativeWindow(ShimEGLNativeWindowType native_window); - -#ifdef __cplusplus -} -#endif - -#endif /* __eglplatform_shim_h */
diff --git a/ui/ozone/platform/egltest/eglplatform_shim_xeleven.cc b/ui/ozone/platform/egltest/eglplatform_shim_xeleven.cc deleted file mode 100644 index c7e0080..0000000 --- a/ui/ozone/platform/egltest/eglplatform_shim_xeleven.cc +++ /dev/null
@@ -1,106 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/egltest/eglplatform_shim.h" - -#include <string.h> -#include <X11/Xlib.h> -#include <X11/Xatom.h> -#include <X11/Xutil.h> - -#ifdef __cplusplus -extern "C" { -#endif - -Display* g_display; - -const int kDefaultX = 0; -const int kDefaultY = 0; -const int kDefaultWidth = 1280; -const int kDefaultHeight = 720; -const int kDefaultBorderWidth = 0; - -const char* ShimQueryString(int name) { - switch (name) { - case SHIM_EGL_LIBRARY: - return "libEGL.so.1"; - case SHIM_GLES_LIBRARY: - return "libGLESv2.so.2"; - default: - return NULL; - } -} - -bool ShimInitialize(void) { - g_display = XOpenDisplay(NULL); - return g_display != NULL; -} - -bool ShimTerminate(void) { - XCloseDisplay(g_display); - return true; -} - -ShimNativeWindowId ShimCreateWindow(void) { - XSetWindowAttributes swa; - memset(&swa, 0, sizeof(swa)); - swa.event_mask = 0; - - Window window = XCreateWindow(g_display, - DefaultRootWindow(g_display), - kDefaultX, - kDefaultY, - kDefaultWidth, - kDefaultHeight, - kDefaultBorderWidth, - CopyFromParent, - InputOutput, - CopyFromParent, - CWEventMask, - &swa); - - XMapWindow(g_display, window); - XStoreName(g_display, window, "EGL test"); - XFlush(g_display); - - return window; -} - -bool ShimQueryWindow(ShimNativeWindowId window_id, int attribute, int* value) { - XWindowAttributes window_attributes; - switch (attribute) { - case SHIM_WINDOW_WIDTH: - XGetWindowAttributes(g_display, window_id, &window_attributes); - *value = window_attributes.width; - return true; - case SHIM_WINDOW_HEIGHT: - XGetWindowAttributes(g_display, window_id, &window_attributes); - *value = window_attributes.height; - return true; - default: - return false; - } -} - -bool ShimDestroyWindow(ShimNativeWindowId window_id) { - XDestroyWindow(g_display, window_id); - return true; -} - -ShimEGLNativeDisplayType ShimGetNativeDisplay(void) { - return reinterpret_cast<ShimEGLNativeDisplayType>(g_display); -} - -ShimEGLNativeWindowType ShimGetNativeWindow( - ShimNativeWindowId native_window_id) { - return native_window_id; -} - -bool ShimReleaseNativeWindow(ShimEGLNativeWindowType native_window) { - return true; -} - -#ifdef __cplusplus -} -#endif
diff --git a/ui/ozone/platform/egltest/egltest.gypi b/ui/ozone/platform/egltest/egltest.gypi deleted file mode 100644 index 8191af5..0000000 --- a/ui/ozone/platform/egltest/egltest.gypi +++ /dev/null
@@ -1,108 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -{ - 'variables': { - 'internal_ozone_platform_deps': [ - 'ozone_platform_egltest', - ], - 'internal_ozone_platforms': [ - 'egltest' - ], - }, - 'targets': [ - { - 'target_name': 'ozone_platform_egltest', - 'type': 'static_library', - 'defines': [ - 'OZONE_IMPLEMENTATION', - ], - 'dependencies': [ - '../../base/base.gyp:base', - '../../third_party/khronos/khronos.gyp:khronos_headers', - '../events/events.gyp:events', - '../events/ozone/events_ozone.gyp:events_ozone_evdev', - '../gfx/gfx.gyp:gfx', - 'eglplatform_shim', - ], - 'sources': [ - 'ozone_platform_egltest.cc', - 'ozone_platform_egltest.h', - ], - }, - { - 'target_name': 'eglplatform_shim', - 'type': 'static_library', - 'dependencies': [ - '../../third_party/khronos/khronos.gyp:khronos_headers', - ], - 'direct_dependent_settings': { - 'include_dirs': [ - '<(SHARED_INTERMEDIATE_DIR)', - ], - }, - 'include_dirs': [ - '../../../..', - ], - 'hard_dependency': 1, - 'actions': [ - { - 'variables': { - 'output_h': '<(SHARED_INTERMEDIATE_DIR)/library_loaders/libeglplatform_shim.h', - 'output_cc': '<(INTERMEDIATE_DIR)/libeglplatform_shim_loader.cc', - 'generator': '../../tools/generate_library_loader/generate_library_loader.py', - }, - 'action_name': 'generate_libeglplatform_shim_loader', - 'inputs': [ - '<(generator)', - ], - 'outputs': [ - '<(output_h)', - '<(output_cc)', - ], - 'action': ['python', - '<(generator)', - '--name', 'LibeglplatformShimLoader', - '--output-h', '<(output_h)', - '--output-cc', '<(output_cc)', - '--header', '"ui/ozone/platform/egltest/eglplatform_shim.h"', - 'ShimQueryString', - 'ShimInitialize', - 'ShimTerminate', - 'ShimCreateWindow', - 'ShimQueryWindow', - 'ShimDestroyWindow', - 'ShimGetNativeDisplay', - 'ShimGetNativeWindow', - 'ShimReleaseNativeWindow', - ], - 'message': 'Generating libeglplatform_shim library loader', - 'process_outputs_as_sources': 1, - }, - ], - }, - ], - 'conditions': [ - ['ozone_platform_ozonex == 1', { - 'targets': [ - { - 'target_name': 'eglplatform_shim_x11', - 'type': 'loadable_module', - 'product_name': 'eglplatform_shim', - 'product_extension': 'so.1', - 'include_dirs': [ - '../../../..', - ], - 'dependencies': [ - '../../build/linux/system.gyp:x11', - ], - 'sources': [ - 'eglplatform_shim.h', - 'eglplatform_shim_xeleven.cc', - ], - }, - ], - }], - ], -}
diff --git a/ui/ozone/platform/egltest/ozone_platform_egltest.cc b/ui/ozone/platform/egltest/ozone_platform_egltest.cc deleted file mode 100644 index c192c9f..0000000 --- a/ui/ozone/platform/egltest/ozone_platform_egltest.cc +++ /dev/null
@@ -1,386 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/egltest/ozone_platform_egltest.h" - -#include "base/bind.h" -#include "base/command_line.h" -#include "base/environment.h" -#include "base/files/file_path.h" -#include "base/path_service.h" -#include "library_loaders/libeglplatform_shim.h" -#include "third_party/khronos/EGL/egl.h" -#include "ui/events/ozone/device/device_manager.h" -#include "ui/events/ozone/evdev/event_factory_evdev.h" -#include "ui/events/ozone/events_ozone.h" -#include "ui/events/platform/platform_event_dispatcher.h" -#include "ui/gfx/vsync_provider.h" -#include "ui/ozone/common/native_display_delegate_ozone.h" -#include "ui/ozone/public/cursor_factory_ozone.h" -#include "ui/ozone/public/gpu_platform_support.h" -#include "ui/ozone/public/gpu_platform_support_host.h" -#include "ui/ozone/public/ozone_platform.h" -#include "ui/ozone/public/ozone_switches.h" -#include "ui/ozone/public/surface_factory_ozone.h" -#include "ui/ozone/public/surface_ozone_egl.h" -#include "ui/platform_window/platform_window.h" -#include "ui/platform_window/platform_window_delegate.h" - -namespace ui { - -namespace { - -const char kEglplatformShim[] = "EGLPLATFORM_SHIM"; -const char kEglplatformShimDefault[] = "libeglplatform_shim.so.1"; -const char kDefaultEglSoname[] = "libEGL.so.1"; -const char kDefaultGlesSoname[] = "libGLESv2.so.2"; - -// Get the library soname to load. -std::string GetShimLibraryName() { - std::string library; - scoped_ptr<base::Environment> env(base::Environment::Create()); - if (env->GetVar(kEglplatformShim, &library)) - return library; - return kEglplatformShimDefault; -} - -class EgltestWindow : public PlatformWindow, public PlatformEventDispatcher { - public: - EgltestWindow(PlatformWindowDelegate* delegate, - LibeglplatformShimLoader* eglplatform_shim, - EventFactoryEvdev* event_factory, - const gfx::Rect& bounds); - virtual ~EgltestWindow(); - - // PlatformWindow: - virtual gfx::Rect GetBounds() override; - virtual void SetBounds(const gfx::Rect& bounds) override; - virtual void Show() override; - virtual void Hide() override; - virtual void Close() override; - virtual void SetCapture() override; - virtual void ReleaseCapture() override; - virtual void ToggleFullscreen() override; - virtual void Maximize() override; - virtual void Minimize() override; - virtual void Restore() override; - virtual void SetCursor(PlatformCursor cursor) override; - virtual void MoveCursorTo(const gfx::Point& location) override; - - // PlatformEventDispatcher: - virtual bool CanDispatchEvent(const PlatformEvent& event) override; - virtual uint32_t DispatchEvent(const PlatformEvent& event) override; - - private: - PlatformWindowDelegate* delegate_; - LibeglplatformShimLoader* eglplatform_shim_; - EventFactoryEvdev* event_factory_; - gfx::Rect bounds_; - ShimNativeWindowId window_id_; - - DISALLOW_COPY_AND_ASSIGN(EgltestWindow); -}; - -EgltestWindow::EgltestWindow(PlatformWindowDelegate* delegate, - LibeglplatformShimLoader* eglplatform_shim, - EventFactoryEvdev* event_factory, - const gfx::Rect& bounds) - : delegate_(delegate), - eglplatform_shim_(eglplatform_shim), - event_factory_(event_factory), - bounds_(bounds), - window_id_(SHIM_NO_WINDOW_ID) { - window_id_ = eglplatform_shim_->ShimCreateWindow(); - delegate_->OnAcceleratedWidgetAvailable(window_id_); - ui::PlatformEventSource::GetInstance()->AddPlatformEventDispatcher(this); -} - -EgltestWindow::~EgltestWindow() { - ui::PlatformEventSource::GetInstance()->RemovePlatformEventDispatcher(this); - if (window_id_ != SHIM_NO_WINDOW_ID) - eglplatform_shim_->ShimDestroyWindow(window_id_); -} - -gfx::Rect EgltestWindow::GetBounds() { - return bounds_; -} - -void EgltestWindow::SetBounds(const gfx::Rect& bounds) { - bounds_ = bounds; - delegate_->OnBoundsChanged(bounds); -} - -void EgltestWindow::Show() { -} - -void EgltestWindow::Hide() { -} - -void EgltestWindow::Close() { -} - -void EgltestWindow::SetCapture() { -} - -void EgltestWindow::ReleaseCapture() { -} - -void EgltestWindow::ToggleFullscreen() { -} - -void EgltestWindow::Maximize() { -} - -void EgltestWindow::Minimize() { -} - -void EgltestWindow::Restore() { -} - -void EgltestWindow::SetCursor(PlatformCursor cursor) { -} - -void EgltestWindow::MoveCursorTo(const gfx::Point& location) { - event_factory_->WarpCursorTo(window_id_, location); -} - -bool EgltestWindow::CanDispatchEvent(const ui::PlatformEvent& ne) { - return true; -} - -uint32_t EgltestWindow::DispatchEvent(const ui::PlatformEvent& native_event) { - DispatchEventFromNativeUiEvent( - native_event, - base::Bind(&PlatformWindowDelegate::DispatchEvent, - base::Unretained(delegate_))); - - return ui::POST_DISPATCH_STOP_PROPAGATION; -} - -// EGL surface wrapper for libeglplatform_shim. -// -// This just manages the native window lifetime using -// ShimGetNativeWindow & ShimReleaseNativeWindow. -class SurfaceOzoneEgltest : public SurfaceOzoneEGL { - public: - SurfaceOzoneEgltest(ShimNativeWindowId window_id, - LibeglplatformShimLoader* eglplatform_shim) - : eglplatform_shim_(eglplatform_shim) { - native_window_ = eglplatform_shim_->ShimGetNativeWindow(window_id); - } - virtual ~SurfaceOzoneEgltest() { - bool ret = eglplatform_shim_->ShimReleaseNativeWindow(native_window_); - DCHECK(ret); - } - - virtual intptr_t GetNativeWindow() override { return native_window_; } - - virtual bool OnSwapBuffers() override { return true; } - - virtual bool ResizeNativeWindow(const gfx::Size& viewport_size) override { - return true; - } - - virtual scoped_ptr<gfx::VSyncProvider> CreateVSyncProvider() override { - return scoped_ptr<gfx::VSyncProvider>(); - } - - private: - LibeglplatformShimLoader* eglplatform_shim_; - intptr_t native_window_; -}; - -// EGL surface factory for libeglplatform_shim. -// -// This finds the right EGL/GLES2 libraries for loading, and creates -// a single native window via ShimCreateWindow for drawing -// into. -class SurfaceFactoryEgltest : public ui::SurfaceFactoryOzone { - public: - SurfaceFactoryEgltest(LibeglplatformShimLoader* eglplatform_shim) - : eglplatform_shim_(eglplatform_shim) {} - virtual ~SurfaceFactoryEgltest() {} - - // SurfaceFactoryOzone: - virtual intptr_t GetNativeDisplay() override; - virtual scoped_ptr<SurfaceOzoneEGL> CreateEGLSurfaceForWidget( - gfx::AcceleratedWidget widget) override; - virtual const int32* GetEGLSurfaceProperties( - const int32* desired_list) override; - virtual bool LoadEGLGLES2Bindings( - AddGLLibraryCallback add_gl_library, - SetGLGetProcAddressProcCallback set_gl_get_proc_address) override; - - private: - LibeglplatformShimLoader* eglplatform_shim_; -}; - -intptr_t SurfaceFactoryEgltest::GetNativeDisplay() { - return eglplatform_shim_->ShimGetNativeDisplay(); -} - -scoped_ptr<SurfaceOzoneEGL> SurfaceFactoryEgltest::CreateEGLSurfaceForWidget( - gfx::AcceleratedWidget widget) { - return make_scoped_ptr<SurfaceOzoneEGL>( - new SurfaceOzoneEgltest(widget, eglplatform_shim_)); -} - -bool SurfaceFactoryEgltest::LoadEGLGLES2Bindings( - AddGLLibraryCallback add_gl_library, - SetGLGetProcAddressProcCallback set_gl_get_proc_address) { - const char* egl_soname = eglplatform_shim_->ShimQueryString(SHIM_EGL_LIBRARY); - const char* gles_soname = - eglplatform_shim_->ShimQueryString(SHIM_GLES_LIBRARY); - if (!egl_soname) - egl_soname = kDefaultEglSoname; - if (!gles_soname) - gles_soname = kDefaultGlesSoname; - - base::NativeLibraryLoadError error; - base::NativeLibrary egl_library = - base::LoadNativeLibrary(base::FilePath(egl_soname), &error); - if (!egl_library) { - LOG(WARNING) << "Failed to load EGL library: " << error.ToString(); - return false; - } - - base::NativeLibrary gles_library = - base::LoadNativeLibrary(base::FilePath(gles_soname), &error); - if (!gles_library) { - LOG(WARNING) << "Failed to load GLES library: " << error.ToString(); - base::UnloadNativeLibrary(egl_library); - return false; - } - - GLGetProcAddressProc get_proc_address = - reinterpret_cast<GLGetProcAddressProc>( - base::GetFunctionPointerFromNativeLibrary(egl_library, - "eglGetProcAddress")); - if (!get_proc_address) { - LOG(ERROR) << "eglGetProcAddress not found."; - base::UnloadNativeLibrary(egl_library); - base::UnloadNativeLibrary(gles_library); - return false; - } - - set_gl_get_proc_address.Run(get_proc_address); - add_gl_library.Run(egl_library); - add_gl_library.Run(gles_library); - return true; -} - -const int32* SurfaceFactoryEgltest::GetEGLSurfaceProperties( - const int32* desired_list) { - static const int32 broken_props[] = { - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, - EGL_SURFACE_TYPE, EGL_WINDOW_BIT | EGL_PBUFFER_BIT, - EGL_NONE, - }; - return broken_props; -} - -// Test platform for EGL. -// -// This is a tiny EGL-based platform. Creation of the native window is -// handled by a separate library called eglplatform_shim.so.1 because -// this itself is platform specific and we want to test out multiple -// hardware platforms. -class OzonePlatformEgltest : public OzonePlatform { - public: - OzonePlatformEgltest() : shim_initialized_(false) {} - virtual ~OzonePlatformEgltest() { - if (shim_initialized_) - eglplatform_shim_.ShimTerminate(); - } - - void LoadShim() { - std::string library = GetShimLibraryName(); - - if (eglplatform_shim_.Load(library)) - return; - - base::FilePath module_path; - if (!PathService::Get(base::DIR_MODULE, &module_path)) - LOG(ERROR) << "failed to get DIR_MODULE from PathService"; - base::FilePath library_path = module_path.Append(library); - - if (eglplatform_shim_.Load(library_path.value())) - return; - - LOG(FATAL) << "failed to load " << library; - } - - void Initialize() { - LoadShim(); - shim_initialized_ = eglplatform_shim_.ShimInitialize(); - } - - // OzonePlatform: - virtual ui::SurfaceFactoryOzone* GetSurfaceFactoryOzone() override { - return surface_factory_ozone_.get(); - } - virtual CursorFactoryOzone* GetCursorFactoryOzone() override { - return cursor_factory_ozone_.get(); - } - virtual GpuPlatformSupport* GetGpuPlatformSupport() override { - return gpu_platform_support_.get(); - } - virtual GpuPlatformSupportHost* GetGpuPlatformSupportHost() override { - return gpu_platform_support_host_.get(); - } - virtual scoped_ptr<PlatformWindow> CreatePlatformWindow( - PlatformWindowDelegate* delegate, - const gfx::Rect& bounds) override { - return make_scoped_ptr<PlatformWindow>( - new EgltestWindow(delegate, - &eglplatform_shim_, - event_factory_ozone_.get(), - bounds)); - } - virtual scoped_ptr<NativeDisplayDelegate> CreateNativeDisplayDelegate() - override { - return scoped_ptr<NativeDisplayDelegate>(new NativeDisplayDelegateOzone()); - } - - virtual void InitializeUI() override { - device_manager_ = CreateDeviceManager(); - if (!surface_factory_ozone_) - surface_factory_ozone_.reset( - new SurfaceFactoryEgltest(&eglplatform_shim_)); - event_factory_ozone_.reset( - new EventFactoryEvdev(NULL, device_manager_.get())); - cursor_factory_ozone_.reset(new CursorFactoryOzone()); - gpu_platform_support_host_.reset(CreateStubGpuPlatformSupportHost()); - } - - virtual void InitializeGPU() override { - if (!surface_factory_ozone_) - surface_factory_ozone_.reset( - new SurfaceFactoryEgltest(&eglplatform_shim_)); - gpu_platform_support_.reset(CreateStubGpuPlatformSupport()); - } - - private: - LibeglplatformShimLoader eglplatform_shim_; - scoped_ptr<DeviceManager> device_manager_; - scoped_ptr<SurfaceFactoryEgltest> surface_factory_ozone_; - scoped_ptr<EventFactoryEvdev> event_factory_ozone_; - scoped_ptr<CursorFactoryOzone> cursor_factory_ozone_; - scoped_ptr<GpuPlatformSupport> gpu_platform_support_; - scoped_ptr<GpuPlatformSupportHost> gpu_platform_support_host_; - - bool shim_initialized_; - - DISALLOW_COPY_AND_ASSIGN(OzonePlatformEgltest); -}; - -} // namespace - -OzonePlatform* CreateOzonePlatformEgltest() { - OzonePlatformEgltest* platform = new OzonePlatformEgltest; - platform->Initialize(); - return platform; -} - -} // namespace ui
diff --git a/ui/ozone/platform/egltest/ozone_platform_egltest.h b/ui/ozone/platform/egltest/ozone_platform_egltest.h deleted file mode 100644 index fb49be5..0000000 --- a/ui/ozone/platform/egltest/ozone_platform_egltest.h +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_TEST_OZONE_PLATFORM_EGLTEST_H_ -#define UI_OZONE_PLATFORM_TEST_OZONE_PLATFORM_EGLTEST_H_ - -namespace ui { - -class OzonePlatform; - -// Constructor hook for use in ozone_platform_list.cc -OzonePlatform* CreateOzonePlatformEgltest(); - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_TEST_OZONE_PLATFORM_EGLTEST_H_
diff --git a/ui/ozone/platform/test/BUILD.gn b/ui/ozone/platform/test/BUILD.gn deleted file mode 100644 index d1ff717..0000000 --- a/ui/ozone/platform/test/BUILD.gn +++ /dev/null
@@ -1,21 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -source_set("test") { - sources = [ - "ozone_platform_test.cc", - "ozone_platform_test.h", - "test_window.cc", - "test_window.h", - "test_window_manager.cc", - "test_window_manager.h", - ] - - deps = [ - "//base", - "//skia", - "//ui/base", - "//ui/gfx/geometry", - ] -}
diff --git a/ui/ozone/platform/test/DEPS b/ui/ozone/platform/test/DEPS deleted file mode 100644 index 41cd997..0000000 --- a/ui/ozone/platform/test/DEPS +++ /dev/null
@@ -1,3 +0,0 @@ -include_rules = [ - "+third_party/skia/include", -]
diff --git a/ui/ozone/platform/test/ozone_platform_test.cc b/ui/ozone/platform/test/ozone_platform_test.cc deleted file mode 100644 index d657129..0000000 --- a/ui/ozone/platform/test/ozone_platform_test.cc +++ /dev/null
@@ -1,92 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/test/ozone_platform_test.h" - -#include "base/command_line.h" -#include "base/files/file_path.h" -#include "ui/base/cursor/ozone/bitmap_cursor_factory_ozone.h" -#include "ui/events/platform/platform_event_source.h" -#include "ui/ozone/common/native_display_delegate_ozone.h" -#include "ui/ozone/platform/test/test_window.h" -#include "ui/ozone/platform/test/test_window_manager.h" -#include "ui/ozone/public/cursor_factory_ozone.h" -#include "ui/ozone/public/gpu_platform_support.h" -#include "ui/ozone/public/gpu_platform_support_host.h" -#include "ui/ozone/public/ozone_platform.h" -#include "ui/ozone/public/ozone_switches.h" - -namespace ui { - -namespace { - -// OzonePlatform for testing -// -// This platform dumps images to a file for testing purposes. -class OzonePlatformTest : public OzonePlatform { - public: - OzonePlatformTest(const base::FilePath& dump_file) : file_path_(dump_file) {} - virtual ~OzonePlatformTest() {} - - // OzonePlatform: - virtual ui::SurfaceFactoryOzone* GetSurfaceFactoryOzone() override { - return window_manager_.get(); - } - virtual CursorFactoryOzone* GetCursorFactoryOzone() override { - return cursor_factory_ozone_.get(); - } - virtual GpuPlatformSupport* GetGpuPlatformSupport() override { - return gpu_platform_support_.get(); - } - virtual GpuPlatformSupportHost* GetGpuPlatformSupportHost() override { - return gpu_platform_support_host_.get(); - } - virtual scoped_ptr<PlatformWindow> CreatePlatformWindow( - PlatformWindowDelegate* delegate, - const gfx::Rect& bounds) override { - return make_scoped_ptr<PlatformWindow>( - new TestWindow(delegate, window_manager_.get(), bounds)); - } - virtual scoped_ptr<NativeDisplayDelegate> CreateNativeDisplayDelegate() - override { - return scoped_ptr<NativeDisplayDelegate>(new NativeDisplayDelegateOzone()); - } - - virtual void InitializeUI() override { - window_manager_.reset(new TestWindowManager(file_path_)); - window_manager_->Initialize(); - // This unbreaks tests that create their own. - if (!PlatformEventSource::GetInstance()) - platform_event_source_ = PlatformEventSource::CreateDefault(); - - cursor_factory_ozone_.reset(new BitmapCursorFactoryOzone); - gpu_platform_support_host_.reset(CreateStubGpuPlatformSupportHost()); - } - - virtual void InitializeGPU() override { - gpu_platform_support_.reset(CreateStubGpuPlatformSupport()); - } - - private: - scoped_ptr<TestWindowManager> window_manager_; - scoped_ptr<PlatformEventSource> platform_event_source_; - scoped_ptr<CursorFactoryOzone> cursor_factory_ozone_; - scoped_ptr<GpuPlatformSupport> gpu_platform_support_; - scoped_ptr<GpuPlatformSupportHost> gpu_platform_support_host_; - base::FilePath file_path_; - - DISALLOW_COPY_AND_ASSIGN(OzonePlatformTest); -}; - -} // namespace - -OzonePlatform* CreateOzonePlatformTest() { - CommandLine* cmd = CommandLine::ForCurrentProcess(); - base::FilePath location; - if (cmd->HasSwitch(switches::kOzoneDumpFile)) - location = cmd->GetSwitchValuePath(switches::kOzoneDumpFile); - return new OzonePlatformTest(location); -} - -} // namespace ui
diff --git a/ui/ozone/platform/test/ozone_platform_test.h b/ui/ozone/platform/test/ozone_platform_test.h deleted file mode 100644 index fb25fd6..0000000 --- a/ui/ozone/platform/test/ozone_platform_test.h +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_TEST_OZONE_PLATFORM_TEST_H_ -#define UI_OZONE_PLATFORM_TEST_OZONE_PLATFORM_TEST_H_ - -namespace ui { - -class OzonePlatform; - -// Constructor hook for use in ozone_platform_list.cc -OzonePlatform* CreateOzonePlatformTest(); - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_TEST_OZONE_PLATFORM_TEST_H_
diff --git a/ui/ozone/platform/test/test.gypi b/ui/ozone/platform/test/test.gypi deleted file mode 100644 index d1a35c8..0000000 --- a/ui/ozone/platform/test/test.gypi +++ /dev/null
@@ -1,36 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -{ - 'variables': { - 'internal_ozone_platform_deps': [ - 'ozone_platform_test', - ], - 'internal_ozone_platforms': [ - 'test' - ], - }, - 'targets': [ - { - 'target_name': 'ozone_platform_test', - 'type': 'static_library', - 'defines': [ - 'OZONE_IMPLEMENTATION', - ], - 'dependencies': [ - '../../base/base.gyp:base', - '../events/events.gyp:events', - '../gfx/gfx.gyp:gfx', - ], - 'sources': [ - 'ozone_platform_test.cc', - 'ozone_platform_test.h', - 'test_window.cc', - 'test_window.h', - 'test_window_manager.cc', - 'test_window_manager.h', - ], - }, - ], -}
diff --git a/ui/ozone/platform/test/test_window.cc b/ui/ozone/platform/test/test_window.cc deleted file mode 100644 index 2cfa26c..0000000 --- a/ui/ozone/platform/test/test_window.cc +++ /dev/null
@@ -1,80 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/test/test_window.h" - -#include <string> - -#include "base/files/file_path.h" -#include "base/strings/string_number_conversions.h" -#include "ui/events/platform/platform_event_source.h" -#include "ui/ozone/platform/test/test_window_manager.h" -#include "ui/platform_window/platform_window_delegate.h" - -namespace ui { - -TestWindow::TestWindow(PlatformWindowDelegate* delegate, - TestWindowManager* manager, - const gfx::Rect& bounds) - : delegate_(delegate), manager_(manager), bounds_(bounds) { - widget_ = manager_->AddWindow(this); - delegate_->OnAcceleratedWidgetAvailable(widget_); -} - -TestWindow::~TestWindow() { - manager_->RemoveWindow(widget_, this); -} - -base::FilePath TestWindow::path() { - base::FilePath base_path = manager_->base_path(); - if (base_path.empty() || base_path == base::FilePath("/dev/null")) - return base_path; - - // Disambiguate multiple window output files with the window id. - return base_path.Append(base::IntToString(widget_)); -} - -gfx::Rect TestWindow::GetBounds() { - return bounds_; -} - -void TestWindow::SetBounds(const gfx::Rect& bounds) { - bounds_ = bounds; - delegate_->OnBoundsChanged(bounds); -} - -void TestWindow::Show() { -} - -void TestWindow::Hide() { -} - -void TestWindow::Close() { -} - -void TestWindow::SetCapture() { -} - -void TestWindow::ReleaseCapture() { -} - -void TestWindow::ToggleFullscreen() { -} - -void TestWindow::Maximize() { -} - -void TestWindow::Minimize() { -} - -void TestWindow::Restore() { -} - -void TestWindow::SetCursor(PlatformCursor cursor) { -} - -void TestWindow::MoveCursorTo(const gfx::Point& location) { -} - -} // namespace ui
diff --git a/ui/ozone/platform/test/test_window.h b/ui/ozone/platform/test/test_window.h deleted file mode 100644 index 37e4ec4..0000000 --- a/ui/ozone/platform/test/test_window.h +++ /dev/null
@@ -1,54 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_TEST_TEST_WINDOW_H_ -#define UI_OZONE_PLATFORM_TEST_TEST_WINDOW_H_ - -#include "base/files/file_path.h" -#include "ui/gfx/geometry/rect.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/platform_window/platform_window.h" - -namespace ui { - -class PlatformWindowDelegate; -class TestWindowManager; - -class TestWindow : public PlatformWindow { - public: - TestWindow(PlatformWindowDelegate* delegate, - TestWindowManager* manager, - const gfx::Rect& bounds); - virtual ~TestWindow(); - - // Path for image file for this window. - base::FilePath path(); - - // PlatformWindow: - virtual gfx::Rect GetBounds() override; - virtual void SetBounds(const gfx::Rect& bounds) override; - virtual void Show() override; - virtual void Hide() override; - virtual void Close() override; - virtual void SetCapture() override; - virtual void ReleaseCapture() override; - virtual void ToggleFullscreen() override; - virtual void Maximize() override; - virtual void Minimize() override; - virtual void Restore() override; - virtual void SetCursor(PlatformCursor cursor) override; - virtual void MoveCursorTo(const gfx::Point& location) override; - - private: - PlatformWindowDelegate* delegate_; - TestWindowManager* manager_; - gfx::Rect bounds_; - gfx::AcceleratedWidget widget_; - - DISALLOW_COPY_AND_ASSIGN(TestWindow); -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_TEST_TEST_WINDOW_H_
diff --git a/ui/ozone/platform/test/test_window_manager.cc b/ui/ozone/platform/test/test_window_manager.cc deleted file mode 100644 index 7ffbad8..0000000 --- a/ui/ozone/platform/test/test_window_manager.cc +++ /dev/null
@@ -1,112 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform/test/test_window_manager.h" - -#include "base/bind.h" -#include "base/files/file_util.h" -#include "base/location.h" -#include "base/stl_util.h" -#include "base/threading/worker_pool.h" -#include "third_party/skia/include/core/SkCanvas.h" -#include "third_party/skia/include/core/SkSurface.h" -#include "ui/gfx/codec/png_codec.h" -#include "ui/gfx/skia_util.h" -#include "ui/gfx/vsync_provider.h" -#include "ui/ozone/public/surface_ozone_canvas.h" - -namespace ui { - -namespace { - -void WriteDataToFile(const base::FilePath& location, const SkBitmap& bitmap) { - DCHECK(!location.empty()); - std::vector<unsigned char> png_data; - gfx::PNGCodec::FastEncodeBGRASkBitmap(bitmap, true, &png_data); - base::WriteFile(location, - reinterpret_cast<const char*>(vector_as_array(&png_data)), - png_data.size()); -} - -class FileSurface : public SurfaceOzoneCanvas { - public: - FileSurface(const base::FilePath& location) : location_(location) {} - virtual ~FileSurface() {} - - // SurfaceOzoneCanvas overrides: - virtual void ResizeCanvas(const gfx::Size& viewport_size) override { - surface_ = skia::AdoptRef(SkSurface::NewRaster(SkImageInfo::MakeN32Premul( - viewport_size.width(), viewport_size.height()))); - } - virtual skia::RefPtr<SkCanvas> GetCanvas() override { - return skia::SharePtr(surface_->getCanvas()); - } - virtual void PresentCanvas(const gfx::Rect& damage) override { - if (location_.empty()) - return; - SkBitmap bitmap; - bitmap.setInfo(surface_->getCanvas()->imageInfo()); - - // TODO(dnicoara) Use SkImage instead to potentially avoid a copy. - // See crbug.com/361605 for details. - if (surface_->getCanvas()->readPixels(&bitmap, 0, 0)) { - base::WorkerPool::PostTask( - FROM_HERE, base::Bind(&WriteDataToFile, location_, bitmap), true); - } - } - virtual scoped_ptr<gfx::VSyncProvider> CreateVSyncProvider() override { - return scoped_ptr<gfx::VSyncProvider>(); - } - - private: - base::FilePath location_; - skia::RefPtr<SkSurface> surface_; -}; - -} // namespace - -TestWindowManager::TestWindowManager(const base::FilePath& dump_location) - : location_(dump_location) { -} - -TestWindowManager::~TestWindowManager() { -} - -void TestWindowManager::Initialize() { - if (location_.empty()) - return; - if (!DirectoryExists(location_) && !base::CreateDirectory(location_) && - location_ != base::FilePath("/dev/null")) - PLOG(FATAL) << "unable to create output directory"; - if (!base::PathIsWritable(location_)) - PLOG(FATAL) << "unable to write to output location"; -} - -int32_t TestWindowManager::AddWindow(TestWindow* window) { - return windows_.Add(window); -} - -void TestWindowManager::RemoveWindow(int32_t window_id, TestWindow* window) { - DCHECK_EQ(window, windows_.Lookup(window_id)); - windows_.Remove(window_id); -} - -base::FilePath TestWindowManager::base_path() const { - return location_; -} - -scoped_ptr<SurfaceOzoneCanvas> TestWindowManager::CreateCanvasForWidget( - gfx::AcceleratedWidget widget) { - TestWindow* window = windows_.Lookup(widget); - DCHECK(window); - return make_scoped_ptr<SurfaceOzoneCanvas>(new FileSurface(window->path())); -} - -bool TestWindowManager::LoadEGLGLES2Bindings( - AddGLLibraryCallback add_gl_library, - SetGLGetProcAddressProcCallback set_gl_get_proc_address) { - return false; -} - -} // namespace ui
diff --git a/ui/ozone/platform/test/test_window_manager.h b/ui/ozone/platform/test/test_window_manager.h deleted file mode 100644 index 0241e8b..0000000 --- a/ui/ozone/platform/test/test_window_manager.h +++ /dev/null
@@ -1,51 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_TEST_FILE_SURFACE_FACTORY_H_ -#define UI_OZONE_PLATFORM_TEST_FILE_SURFACE_FACTORY_H_ - -#include "base/files/file_path.h" -#include "base/id_map.h" -#include "base/memory/scoped_ptr.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/ozone/platform/test/test_window.h" -#include "ui/ozone/public/surface_factory_ozone.h" - -namespace ui { - -class TestWindowManager : public SurfaceFactoryOzone { - public: - explicit TestWindowManager(const base::FilePath& dump_location); - virtual ~TestWindowManager(); - - // Initialize (mainly check that we have a place to write output to). - void Initialize(); - - // Register a new window. Returns the window id. - int32_t AddWindow(TestWindow* window); - - // Remove a window. - void RemoveWindow(int32_t window_id, TestWindow* window); - - // User-supplied path for images. - base::FilePath base_path() const; - - // SurfaceFactoryOzone: - virtual scoped_ptr<SurfaceOzoneCanvas> CreateCanvasForWidget( - gfx::AcceleratedWidget w) override; - virtual bool LoadEGLGLES2Bindings( - AddGLLibraryCallback add_gl_library, - SetGLGetProcAddressProcCallback set_gl_get_proc_address) override; - - private: - base::FilePath location_; - - IDMap<TestWindow> windows_; - - DISALLOW_COPY_AND_ASSIGN(TestWindowManager); -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_TEST_FILE_SURFACE_FACTORY_H_
diff --git a/ui/ozone/platform_constructor_list.h b/ui/ozone/platform_constructor_list.h deleted file mode 100644 index 4f2fa98..0000000 --- a/ui/ozone/platform_constructor_list.h +++ /dev/null
@@ -1,21 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_CONSTRUCTOR_LIST_H_ -#define UI_OZONE_PLATFORM_CONSTRUCTOR_LIST_H_ - -#include "base/memory/scoped_ptr.h" -#include "ui/ozone/platform_list.h" - -namespace ui { - -template <class T> -struct PlatformConstructorList { - typedef T* (*Constructor)(); - static const Constructor kConstructors[kPlatformCount]; -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_CONSTRUCTOR_LIST_H_
diff --git a/ui/ozone/platform_object.h b/ui/ozone/platform_object.h deleted file mode 100644 index 2518c7c..0000000 --- a/ui/ozone/platform_object.h +++ /dev/null
@@ -1,34 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_OBJECT_H_ -#define UI_OZONE_PLATFORM_OBJECT_H_ - -#include "base/memory/scoped_ptr.h" - -namespace ui { - -// Create an instance of platform specific object. -// -// This calls a static constructor function based on the --ozone-platform flag. -// -// For the platform called "foo", PlatformObject<PlatformWidget> will ultimately -// call the function with signature -// -// PlatformWidget* CreatePlatformWidgetFoo(); -// -// A definition of this function for each compiled platform must be provided, or -// link errors will result. -// -// To find the right constructor function, this uses static data defined in the -// source file generated by the generate_constructor_list.py. -template <class T> -class PlatformObject { - public: - static scoped_ptr<T> Create(); -}; - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_OBJECT_H_
diff --git a/ui/ozone/platform_object_internal.h b/ui/ozone/platform_object_internal.h deleted file mode 100644 index 68a42b3..0000000 --- a/ui/ozone/platform_object_internal.h +++ /dev/null
@@ -1,31 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_OBJECT_INTERNAL_H_ -#define UI_OZONE_PLATFORM_OBJECT_INTERNAL_H_ - -#include "ui/ozone/ozone_export.h" -#include "ui/ozone/platform_constructor_list.h" -#include "ui/ozone/platform_object.h" -#include "ui/ozone/platform_selection.h" - -namespace ui { - -template <class T> -scoped_ptr<T> PlatformObject<T>::Create() { - typedef typename PlatformConstructorList<T>::Constructor Constructor; - - // Determine selected platform (from --ozone-platform flag, or default). - int platform = GetOzonePlatformId(); - - // Look up the constructor in the constructor list. - Constructor constructor = PlatformConstructorList<T>::kConstructors[platform]; - - // Call the constructor. - return make_scoped_ptr(constructor()); -} - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_OBJECT_INTERNAL_H_
diff --git a/ui/ozone/platform_selection.cc b/ui/ozone/platform_selection.cc deleted file mode 100644 index 823e2bd..0000000 --- a/ui/ozone/platform_selection.cc +++ /dev/null
@@ -1,52 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/platform_selection.h" - -#include "base/command_line.h" -#include "base/logging.h" -#include "ui/ozone/platform_list.h" -#include "ui/ozone/public/ozone_switches.h" - -namespace ui { - -namespace { - -// Returns the name of the platform to use (value of --ozone-platform flag). -std::string GetPlatformName() { - // The first platform is the default. - if (!CommandLine::ForCurrentProcess()->HasSwitch(switches::kOzonePlatform) && - kPlatformCount > 0) - return kPlatformNames[0]; - return CommandLine::ForCurrentProcess()->GetSwitchValueASCII( - switches::kOzonePlatform); -} - -int g_selected_platform = -1; - -} // namespace - -int GetOzonePlatformId() { - if (g_selected_platform >= 0) - return g_selected_platform; - - std::string platform_name = GetPlatformName(); - - // Search for a matching platform in the list. - for (int platform_id = 0; platform_id < kPlatformCount; ++platform_id) { - if (platform_name == kPlatformNames[platform_id]) { - g_selected_platform = platform_id; - return g_selected_platform; - } - } - - LOG(FATAL) << "Invalid ozone platform: " << platform_name; - return -1; // not reached -} - -const char* GetOzonePlatformName() { - return kPlatformNames[GetOzonePlatformId()]; -} - -} // namespace ui
diff --git a/ui/ozone/platform_selection.h b/ui/ozone/platform_selection.h deleted file mode 100644 index 5a1229f..0000000 --- a/ui/ozone/platform_selection.h +++ /dev/null
@@ -1,21 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PLATFORM_SELECTION_H_ -#define UI_OZONE_PLATFORM_SELECTION_H_ - -#include "ui/ozone/ozone_export.h" -#include "ui/ozone/platform_list.h" - -namespace ui { - -// Get active platform id (by parsing --ozone-platform flag). -OZONE_EXPORT int GetOzonePlatformId(); - -// Get active platform name. -OZONE_EXPORT const char* GetOzonePlatformName(); - -} // namespace ui - -#endif // UI_OZONE_PLATFORM_SELECTION_H_
diff --git a/ui/ozone/public/README b/ui/ozone/public/README deleted file mode 100644 index 27e1b3b..0000000 --- a/ui/ozone/public/README +++ /dev/null
@@ -1,2 +0,0 @@ -This directory contains the platform API exposed to higher level components such -as content. These interfaces can be used outside of ui/ozone.
diff --git a/ui/ozone/public/cursor_factory_ozone.cc b/ui/ozone/public/cursor_factory_ozone.cc deleted file mode 100644 index c7f388d..0000000 --- a/ui/ozone/public/cursor_factory_ozone.cc +++ /dev/null
@@ -1,57 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/public/cursor_factory_ozone.h" - -#include "base/logging.h" - -namespace ui { - -// static -CursorFactoryOzone* CursorFactoryOzone::impl_ = NULL; - -CursorFactoryOzone::CursorFactoryOzone() { - DCHECK(!impl_) << "There should only be a single CursorFactoryOzone."; - impl_ = this; -} - -CursorFactoryOzone::~CursorFactoryOzone() { - DCHECK_EQ(impl_, this); - impl_ = NULL; -} - -CursorFactoryOzone* CursorFactoryOzone::GetInstance() { - DCHECK(impl_) << "No CursorFactoryOzone implementation set."; - return impl_; -} - -PlatformCursor CursorFactoryOzone::GetDefaultCursor(int type) { - NOTIMPLEMENTED(); - return NULL; -} - -PlatformCursor CursorFactoryOzone::CreateImageCursor( - const SkBitmap& bitmap, - const gfx::Point& hotspot) { - NOTIMPLEMENTED(); - return NULL; -} - -PlatformCursor CursorFactoryOzone::CreateAnimatedCursor( - const std::vector<SkBitmap>& bitmaps, - const gfx::Point& hotspot, - int frame_delay_ms) { - NOTIMPLEMENTED(); - return NULL; -} - -void CursorFactoryOzone::RefImageCursor(PlatformCursor cursor) { - NOTIMPLEMENTED(); -} - -void CursorFactoryOzone::UnrefImageCursor(PlatformCursor cursor) { - NOTIMPLEMENTED(); -} - -} // namespace ui
diff --git a/ui/ozone/public/cursor_factory_ozone.h b/ui/ozone/public/cursor_factory_ozone.h deleted file mode 100644 index 4950a31..0000000 --- a/ui/ozone/public/cursor_factory_ozone.h +++ /dev/null
@@ -1,61 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PUBLIC_CURSOR_FACTORY_OZONE_H_ -#define UI_OZONE_PUBLIC_CURSOR_FACTORY_OZONE_H_ - -#include <vector> - -#include "ui/gfx/native_widget_types.h" -#include "ui/ozone/ozone_base_export.h" - -namespace gfx { -class Point; -} - -namespace ui { - -typedef void* PlatformCursor; - -class OZONE_BASE_EXPORT CursorFactoryOzone { - public: - CursorFactoryOzone(); - virtual ~CursorFactoryOzone(); - - // Returns the singleton instance. - static CursorFactoryOzone* GetInstance(); - - // Return the default cursor of the specified type. The types are listed in - // ui/base/cursor/cursor.h. Default cursors are managed by the implementation - // and must live indefinitely; there's no way to know when to free them. - virtual PlatformCursor GetDefaultCursor(int type); - - // Return a image cursor from the specified image & hotspot. Image cursors - // are referenced counted and have an initial refcount of 1. Therefore, each - // CreateImageCursor call must be matched with a call to UnrefImageCursor. - virtual PlatformCursor CreateImageCursor(const SkBitmap& bitmap, - const gfx::Point& hotspot); - - // Return a animated cursor from the specified image & hotspot. Animated - // cursors are referenced counted and have an initial refcount of 1. - // Therefore, each CreateAnimatedCursor call must be matched with a call to - // UnrefImageCursor. - virtual PlatformCursor CreateAnimatedCursor( - const std::vector<SkBitmap>& bitmaps, - const gfx::Point& hotspot, - int frame_delay_ms); - - // Increment platform image cursor refcount. - virtual void RefImageCursor(PlatformCursor cursor); - - // Decrement platform image cursor refcount. - virtual void UnrefImageCursor(PlatformCursor cursor); - - private: - static CursorFactoryOzone* impl_; // not owned -}; - -} // namespace ui - -#endif // UI_OZONE_PUBLIC_CURSOR_FACTORY_OZONE_H_
diff --git a/ui/ozone/public/gpu_platform_support.cc b/ui/ozone/public/gpu_platform_support.cc deleted file mode 100644 index f9f1589..0000000 --- a/ui/ozone/public/gpu_platform_support.cc +++ /dev/null
@@ -1,34 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/public/gpu_platform_support.h" - -#include "base/logging.h" -#include "ui/ozone/ozone_export.h" - -namespace ui { - -namespace { - -// No-op implementation of GpuPlatformSupport. -class StubGpuPlatformSupport : public GpuPlatformSupport { - public: - // GpuPlatformSupport: - virtual void OnChannelEstablished(IPC::Sender* sender) override {} - virtual bool OnMessageReceived(const IPC::Message&) override { return false; } -}; - -} // namespace - -GpuPlatformSupport::GpuPlatformSupport() { -} - -GpuPlatformSupport::~GpuPlatformSupport() { -} - -GpuPlatformSupport* CreateStubGpuPlatformSupport() { - return new StubGpuPlatformSupport; -} - -} // namespace ui
diff --git a/ui/ozone/public/gpu_platform_support.h b/ui/ozone/public/gpu_platform_support.h deleted file mode 100644 index 6aba7fa..0000000 --- a/ui/ozone/public/gpu_platform_support.h +++ /dev/null
@@ -1,31 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PUBLIC_GPU_PLATFORM_SUPPORT_H_ -#define UI_OZONE_PUBLIC_GPU_PLATFORM_SUPPORT_H_ - -#include "ipc/ipc_listener.h" -#include "ipc/ipc_sender.h" -#include "ui/ozone/ozone_base_export.h" - -namespace ui { - -// Platform-specific object to support a GPU process. -// -// See GpuPlatformSupportHost for more context. -class OZONE_BASE_EXPORT GpuPlatformSupport : public IPC::Listener { - public: - GpuPlatformSupport(); - virtual ~GpuPlatformSupport(); - - // Called when the GPU process is spun up & channel established. - virtual void OnChannelEstablished(IPC::Sender* sender) = 0; -}; - -// Create a stub implementation. -OZONE_BASE_EXPORT GpuPlatformSupport* CreateStubGpuPlatformSupport(); - -} // namespace ui - -#endif // UI_OZONE_PUBLIC_GPU_PLATFORM_SUPPORT_H_
diff --git a/ui/ozone/public/gpu_platform_support_host.cc b/ui/ozone/public/gpu_platform_support_host.cc deleted file mode 100644 index a611f50..0000000 --- a/ui/ozone/public/gpu_platform_support_host.cc +++ /dev/null
@@ -1,37 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/public/gpu_platform_support_host.h" - -#include "base/debug/trace_event.h" -#include "base/logging.h" -#include "ui/ozone/ozone_export.h" - -namespace ui { - -namespace { - -// No-op implementations of GpuPlatformSupportHost. -class StubGpuPlatformSupportHost : public GpuPlatformSupportHost { - public: - // GpuPlatformSupportHost: - virtual void OnChannelEstablished(int host_id, IPC::Sender* sender) override { - } - virtual void OnChannelDestroyed(int host_id) override {} - virtual bool OnMessageReceived(const IPC::Message&) override { return false; } -}; - -} // namespace - -GpuPlatformSupportHost::GpuPlatformSupportHost() { -} - -GpuPlatformSupportHost::~GpuPlatformSupportHost() { -} - -GpuPlatformSupportHost* CreateStubGpuPlatformSupportHost() { - return new StubGpuPlatformSupportHost; -} - -} // namespace ui
diff --git a/ui/ozone/public/gpu_platform_support_host.h b/ui/ozone/public/gpu_platform_support_host.h deleted file mode 100644 index 700b75b..0000000 --- a/ui/ozone/public/gpu_platform_support_host.h +++ /dev/null
@@ -1,40 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PUBLIC_GPU_PLATFORM_SUPPORT_HOST_H_ -#define UI_OZONE_PUBLIC_GPU_PLATFORM_SUPPORT_HOST_H_ - -#include "ipc/ipc_listener.h" -#include "ipc/ipc_sender.h" -#include "ui/ozone/ozone_base_export.h" - -namespace ui { - -// Platform-specific object to support a GPU process host. -// -// ChromeOS on bare hardware will do display configuration and cursor -// movement from the GPU process. This provides a conduit for the -// messages needed to make this work. -// -// Under X11, we don't need any GPU messages for display configuration. -// That's why there's no real functionality here: it's purely mechanism -// to support additional messages needed by specific platforms. -class OZONE_BASE_EXPORT GpuPlatformSupportHost : public IPC::Listener { - public: - GpuPlatformSupportHost(); - virtual ~GpuPlatformSupportHost(); - - // Called when the GPU process is spun up & channel established. - virtual void OnChannelEstablished(int host_id, IPC::Sender* sender) = 0; - - // Called when the GPU process is destroyed. - virtual void OnChannelDestroyed(int host_id) = 0; -}; - -// create a stub implementation. -OZONE_BASE_EXPORT GpuPlatformSupportHost* CreateStubGpuPlatformSupportHost(); - -} // namespace ui - -#endif // UI_OZONE_PUBLIC_GPU_PLATFORM_SUPPORT_HOST_H_
diff --git a/ui/ozone/public/native_pixmap.h b/ui/ozone/public/native_pixmap.h deleted file mode 100644 index 8342ca2..0000000 --- a/ui/ozone/public/native_pixmap.h +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PUBLIC_NATIVE_PIXMAP_H_ -#define UI_OZONE_PUBLIC_NATIVE_PIXMAP_H_ - -#include "base/memory/ref_counted.h" - -namespace ui { - -// This represents a buffer that can be directly imported via GL for -// rendering, or exported via dma-buf fds. -class NativePixmap : public base::RefCounted<NativePixmap> { - public: - NativePixmap() {} - - virtual void* /* EGLClientBuffer */ GetEGLClientBuffer() = 0; - virtual int GetDmaBufFd() = 0; - virtual int GetDmaBufPitch() = 0; - - protected: - virtual ~NativePixmap() {} - - friend class base::RefCounted<NativePixmap>; - - DISALLOW_COPY_AND_ASSIGN(NativePixmap); -}; - -} // namespace ui - -#endif // UI_OZONE_PUBLIC_NATIVE_PIXMAP_H_
diff --git a/ui/ozone/public/overlay_candidates_ozone.cc b/ui/ozone/public/overlay_candidates_ozone.cc deleted file mode 100644 index 006f4b2..0000000 --- a/ui/ozone/public/overlay_candidates_ozone.cc +++ /dev/null
@@ -1,28 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/public/overlay_candidates_ozone.h" - -#include <stdlib.h> - -namespace ui { - -OverlayCandidatesOzone::OverlaySurfaceCandidate::OverlaySurfaceCandidate() - : transform(gfx::OVERLAY_TRANSFORM_NONE), - format(SurfaceFactoryOzone::UNKNOWN), - overlay_handled(false) { -} - -OverlayCandidatesOzone::OverlaySurfaceCandidate::~OverlaySurfaceCandidate() { -} - -void OverlayCandidatesOzone::CheckOverlaySupport( - OverlaySurfaceCandidateList* surfaces) { - NOTREACHED(); -} - -OverlayCandidatesOzone::~OverlayCandidatesOzone() { -} - -} // namespace ui
diff --git a/ui/ozone/public/overlay_candidates_ozone.h b/ui/ozone/public/overlay_candidates_ozone.h deleted file mode 100644 index e33de56..0000000 --- a/ui/ozone/public/overlay_candidates_ozone.h +++ /dev/null
@@ -1,56 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PUBLIC_OVERLAY_CANDIDATES_OZONE_H_ -#define UI_OZONE_PUBLIC_OVERLAY_CANDIDATES_OZONE_H_ - -#include <vector> - -#include "base/basictypes.h" -#include "ui/gfx/rect_f.h" -#include "ui/ozone/ozone_base_export.h" -#include "ui/ozone/public/surface_factory_ozone.h" - -namespace ui { - -// This class can be used to answer questions about possible overlay -// configurations for a particular output device. We get an instance of this -// class from SurfaceFactoryOzone given an AcceleratedWidget. -class OZONE_BASE_EXPORT OverlayCandidatesOzone { - public: - struct OverlaySurfaceCandidate { - OverlaySurfaceCandidate(); - ~OverlaySurfaceCandidate(); - - // Transformation to apply to layer during composition. - gfx::OverlayTransform transform; - // Format of the buffer to composite. - SurfaceFactoryOzone::BufferFormat format; - // Rect on the display to position the overlay to. - gfx::Rect display_rect; - // Crop within the buffer to be placed inside |display_rect|. - gfx::RectF crop_rect; - // Stacking order of the overlay plane relative to the main surface, - // which is 0. Signed to allow for "underlays". - int plane_z_order; - - // To be modified by the implementer if this candidate can go into - // an overlay. - bool overlay_handled; - }; - - typedef std::vector<OverlaySurfaceCandidate> OverlaySurfaceCandidateList; - - // A list of possible overlay candidates is presented to this function. - // The expected result is that those candidates that can be in a separate - // plane are marked with |overlay_handled| set to true, otherwise they are - // to be tranditionally composited. - virtual void CheckOverlaySupport(OverlaySurfaceCandidateList* surfaces); - - virtual ~OverlayCandidatesOzone(); -}; - -} // namespace ui - -#endif // UI_OZONE_PUBLIC_OVERLAY_CANDIDATES_OZONE_H_
diff --git a/ui/ozone/public/ozone_platform.cc b/ui/ozone/public/ozone_platform.cc deleted file mode 100644 index 5af0099..0000000 --- a/ui/ozone/public/ozone_platform.cc +++ /dev/null
@@ -1,81 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/command_line.h" -#include "base/debug/trace_event.h" -#include "base/logging.h" -#include "ui/events/device_data_manager.h" -#include "ui/ozone/platform_object.h" -#include "ui/ozone/platform_selection.h" -#include "ui/ozone/public/ozone_platform.h" -#include "ui/ozone/public/ozone_switches.h" - -namespace ui { - -namespace { - -bool g_platform_initialized_ui = false; -bool g_platform_initialized_gpu = false; - -} - -OzonePlatform::OzonePlatform() { - DCHECK(!instance_) << "There should only be a single OzonePlatform."; - instance_ = this; - g_platform_initialized_ui = false; - g_platform_initialized_gpu = false; -} - -OzonePlatform::~OzonePlatform() { - DCHECK_EQ(instance_, this); - instance_ = NULL; -} - -// static -void OzonePlatform::InitializeForUI() { - CreateInstance(); - if (g_platform_initialized_ui) - return; - g_platform_initialized_ui = true; - instance_->InitializeUI(); - // This is deliberately created after initializing so that the platform can - // create its own version of DDM. - DeviceDataManager::CreateInstance(); -} - -// static -void OzonePlatform::InitializeForGPU() { - CreateInstance(); - if (g_platform_initialized_gpu) - return; - g_platform_initialized_gpu = true; - instance_->InitializeGPU(); -} - -// static -OzonePlatform* OzonePlatform::GetInstance() { - DCHECK(instance_) << "OzonePlatform is not initialized"; - return instance_; -} - -// static -void OzonePlatform::CreateInstance() { - if (!instance_) { - TRACE_EVENT1("ozone", - "OzonePlatform::Initialize", - "platform", - GetOzonePlatformName()); - scoped_ptr<OzonePlatform> platform = - PlatformObject<OzonePlatform>::Create(); - - // TODO(spang): Currently need to leak this object. - OzonePlatform* pl = platform.release(); - DCHECK_EQ(instance_, pl); - } -} - -// static -OzonePlatform* OzonePlatform::instance_; - -} // namespace ui
diff --git a/ui/ozone/public/ozone_platform.h b/ui/ozone/public/ozone_platform.h deleted file mode 100644 index c01800c..0000000 --- a/ui/ozone/public/ozone_platform.h +++ /dev/null
@@ -1,79 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PUBLIC_OZONE_PLATFORM_H_ -#define UI_OZONE_PUBLIC_OZONE_PLATFORM_H_ - -#include "base/memory/scoped_ptr.h" -#include "ui/ozone/ozone_export.h" - -namespace gfx { -class Rect; -} - -namespace ui { - -class CursorFactoryOzone; -class NativeDisplayDelegate; -class SurfaceFactoryOzone; -class GpuPlatformSupport; -class GpuPlatformSupportHost; -class PlatformWindow; -class PlatformWindowDelegate; - -// Base class for Ozone platform implementations. -// -// Ozone platforms must override this class and implement the virtual -// GetFooFactoryOzone() methods to provide implementations of the -// various ozone interfaces. -// -// The OzonePlatform subclass can own any state needed by the -// implementation that is shared between the various ozone interfaces, -// such as a connection to the windowing system. -// -// A platform is free to use different implementations of each -// interface depending on the context. You can, for example, create -// different objects depending on the underlying hardware, command -// line flags, or whatever is appropriate for the platform. -class OZONE_EXPORT OzonePlatform { - public: - OzonePlatform(); - virtual ~OzonePlatform(); - - // Initializes the subsystems/resources necessary for the UI process (e.g. - // events, surface, etc.) - static void InitializeForUI(); - - // Initializes the subsystems/resources necessary for the GPU process. - static void InitializeForGPU(); - - static OzonePlatform* GetInstance(); - - // Factory getters to override in subclasses. The returned objects will be - // injected into the appropriate layer at startup. Subclasses should not - // inject these objects themselves. Ownership is retained by OzonePlatform. - virtual ui::SurfaceFactoryOzone* GetSurfaceFactoryOzone() = 0; - virtual ui::CursorFactoryOzone* GetCursorFactoryOzone() = 0; - virtual ui::GpuPlatformSupport* GetGpuPlatformSupport() = 0; - virtual ui::GpuPlatformSupportHost* GetGpuPlatformSupportHost() = 0; - virtual scoped_ptr<PlatformWindow> CreatePlatformWindow( - PlatformWindowDelegate* delegate, - const gfx::Rect& bounds) = 0; - virtual scoped_ptr<ui::NativeDisplayDelegate> - CreateNativeDisplayDelegate() = 0; - - private: - virtual void InitializeUI() = 0; - virtual void InitializeGPU() = 0; - - static void CreateInstance(); - - static OzonePlatform* instance_; - - DISALLOW_COPY_AND_ASSIGN(OzonePlatform); -}; - -} // namespace ui - -#endif // UI_OZONE_PUBLIC_OZONE_PLATFORM_H_
diff --git a/ui/ozone/public/ozone_switches.cc b/ui/ozone/public/ozone_switches.cc deleted file mode 100644 index 32d5327..0000000 --- a/ui/ozone/public/ozone_switches.cc +++ /dev/null
@@ -1,23 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/public/ozone_switches.h" - -namespace switches { - -// Specify ozone platform implementation to use. -const char kOzonePlatform[] = "ozone-platform"; - -// Specify location for image dumps. -const char kOzoneDumpFile[] = "ozone-dump-file"; - -// Specify if the accelerated path should use surfaceless rendering. In this -// mode there is no EGL surface. -const char kOzoneUseSurfaceless[] = "ozone-use-surfaceless"; - -// Enable support for a single overlay plane. -const char kOzoneTestSingleOverlaySupport[] = - "ozone-test-single-overlay-support"; - -} // namespace switches
diff --git a/ui/ozone/public/ozone_switches.h b/ui/ozone/public/ozone_switches.h deleted file mode 100644 index e25c674..0000000 --- a/ui/ozone/public/ozone_switches.h +++ /dev/null
@@ -1,23 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PUBLIC_OZONE_SWITCHES_H_ -#define UI_OZONE_PUBLIC_OZONE_SWITCHES_H_ - -#include "base/compiler_specific.h" -#include "ui/ozone/ozone_export.h" - -namespace switches { - -OZONE_EXPORT extern const char kOzonePlatform[]; - -OZONE_EXPORT extern const char kOzoneDumpFile[]; - -OZONE_EXPORT extern const char kOzoneUseSurfaceless[]; - -OZONE_EXPORT extern const char kOzoneTestSingleOverlaySupport[]; - -} // namespace switches - -#endif // UI_OZONE_PUBLIC_OZONE_SWITCHES_H_
diff --git a/ui/ozone/public/surface_factory_ozone.cc b/ui/ozone/public/surface_factory_ozone.cc deleted file mode 100644 index 46cee88..0000000 --- a/ui/ozone/public/surface_factory_ozone.cc +++ /dev/null
@@ -1,86 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/public/surface_factory_ozone.h" - -#include <stdlib.h> - -#include "base/command_line.h" -#include "ui/ozone/public/native_pixmap.h" -#include "ui/ozone/public/surface_ozone_canvas.h" -#include "ui/ozone/public/surface_ozone_egl.h" - -namespace ui { - -// static -SurfaceFactoryOzone* SurfaceFactoryOzone::impl_ = NULL; - -SurfaceFactoryOzone::SurfaceFactoryOzone() { - DCHECK(!impl_) << "There should only be a single SurfaceFactoryOzone."; - impl_ = this; -} - -SurfaceFactoryOzone::~SurfaceFactoryOzone() { - DCHECK_EQ(impl_, this); - impl_ = NULL; -} - -SurfaceFactoryOzone* SurfaceFactoryOzone::GetInstance() { - DCHECK(impl_) << "No SurfaceFactoryOzone implementation set."; - return impl_; -} - -intptr_t SurfaceFactoryOzone::GetNativeDisplay() { - return 0; -} - -scoped_ptr<SurfaceOzoneEGL> SurfaceFactoryOzone::CreateEGLSurfaceForWidget( - gfx::AcceleratedWidget widget) { - NOTIMPLEMENTED(); - return scoped_ptr<SurfaceOzoneEGL>(); -} - -scoped_ptr<SurfaceOzoneEGL> -SurfaceFactoryOzone::CreateSurfacelessEGLSurfaceForWidget( - gfx::AcceleratedWidget widget) { - NOTIMPLEMENTED(); - return scoped_ptr<SurfaceOzoneEGL>(); -} - -scoped_ptr<SurfaceOzoneCanvas> SurfaceFactoryOzone::CreateCanvasForWidget( - gfx::AcceleratedWidget widget) { - NOTIMPLEMENTED(); - return scoped_ptr<SurfaceOzoneCanvas>(); -} - -const int32* SurfaceFactoryOzone::GetEGLSurfaceProperties( - const int32* desired_attributes) { - return desired_attributes; -} - -ui::OverlayCandidatesOzone* SurfaceFactoryOzone::GetOverlayCandidates( - gfx::AcceleratedWidget w) { - return NULL; -} - -scoped_refptr<ui::NativePixmap> SurfaceFactoryOzone::CreateNativePixmap( - gfx::Size size, - BufferFormat format) { - return NULL; -} - -bool SurfaceFactoryOzone::ScheduleOverlayPlane( - gfx::AcceleratedWidget widget, - int plane_z_order, - gfx::OverlayTransform plane_transform, - scoped_refptr<NativePixmap> buffer, - const gfx::Rect& display_bounds, - const gfx::RectF& crop_rect) { - return false; -} - -bool SurfaceFactoryOzone::CanShowPrimaryPlaneAsOverlay() { - return false; -} -} // namespace ui
diff --git a/ui/ozone/public/surface_factory_ozone.h b/ui/ozone/public/surface_factory_ozone.h deleted file mode 100644 index 62df13e..0000000 --- a/ui/ozone/public/surface_factory_ozone.h +++ /dev/null
@@ -1,158 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PUBLIC_SURFACE_FACTORY_OZONE_H_ -#define UI_OZONE_PUBLIC_SURFACE_FACTORY_OZONE_H_ - -#include "base/callback.h" -#include "base/memory/scoped_ptr.h" -#include "base/native_library.h" -#include "ui/gfx/geometry/point.h" -#include "ui/gfx/geometry/rect.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/gfx/overlay_transform.h" -#include "ui/gfx/rect.h" -#include "ui/ozone/ozone_base_export.h" - -class SkBitmap; -class SkCanvas; - -namespace ui { - -class NativePixmap; -class OverlayCandidatesOzone; -class SurfaceOzoneCanvas; -class SurfaceOzoneEGL; - -// The Ozone interface allows external implementations to hook into Chromium to -// provide a system specific implementation. The Ozone interface supports two -// drawing modes: 1) accelerated drawing through EGL and 2) software drawing -// through Skia. -// -// If you want to paint on a window with ozone, you need to create a -// SurfaceOzoneEGL or SurfaceOzoneCanvas for that window. The platform can -// support software, EGL, or both for painting on the window. -// The following functionality is specific to the drawing mode and may not have -// any meaningful implementation in the other mode. An implementation must -// provide functionality for at least one mode. -// -// 1) Accelerated Drawing (EGL path): -// -// The following functions are specific to EGL: -// - GetNativeDisplay -// - LoadEGLGLES2Bindings -// - GetEGLSurfaceProperties (optional if the properties match the default -// Chromium ones). -// - CreateEGLSurfaceForWidget -// -// 2) Software Drawing (Skia): -// -// The following function is specific to the software path: -// - CreateCanvasForWidget -// -// The accelerated path can optionally provide support for the software drawing -// path. -// -// The remaining functions are not covered since they are needed in both drawing -// modes (See comments bellow for descriptions). -class OZONE_BASE_EXPORT SurfaceFactoryOzone { - public: - // Describes overlay buffer format. - // TODO: this is a placeholder for now and will be populated with more - // formats once we know what sorts of content, video, etc. we can support. - enum BufferFormat { - UNKNOWN, - RGBA_8888, - RGBX_8888, - RGB_888, - }; - - typedef void* (*GLGetProcAddressProc)(const char* name); - typedef base::Callback<void(base::NativeLibrary)> AddGLLibraryCallback; - typedef base::Callback<void(GLGetProcAddressProc)> - SetGLGetProcAddressProcCallback; - - SurfaceFactoryOzone(); - virtual ~SurfaceFactoryOzone(); - - // Returns the singleton instance. - static SurfaceFactoryOzone* GetInstance(); - - // Returns native platform display handle. This is used to obtain the EGL - // display connection for the native display. - virtual intptr_t GetNativeDisplay(); - - // Create SurfaceOzoneEGL for the specified gfx::AcceleratedWidget. - // - // Note: When used from content, this is called in the GPU process. The - // platform must support creation of SurfaceOzoneEGL from the GPU process - // using only the handle contained in gfx::AcceleratedWidget. - virtual scoped_ptr<SurfaceOzoneEGL> CreateEGLSurfaceForWidget( - gfx::AcceleratedWidget widget); - - // Create an EGL surface that isn't backed by any buffers, and is used - // for overlay-only displays. This will return NULL if this mode is - // not supported. - virtual scoped_ptr<SurfaceOzoneEGL> CreateSurfacelessEGLSurfaceForWidget( - gfx::AcceleratedWidget widget); - - // Create SurfaceOzoneCanvas for the specified gfx::AcceleratedWidget. - // - // Note: The platform must support creation of SurfaceOzoneCanvas from the - // Browser Process using only the handle contained in gfx::AcceleratedWidget. - virtual scoped_ptr<SurfaceOzoneCanvas> CreateCanvasForWidget( - gfx::AcceleratedWidget widget); - - // Sets up GL bindings for the native surface. Takes two callback parameters - // that allow Ozone to register the GL bindings. - virtual bool LoadEGLGLES2Bindings( - AddGLLibraryCallback add_gl_library, - SetGLGetProcAddressProcCallback set_gl_get_proc_address) = 0; - - // Returns an array of EGL properties, which can be used in any EGL function - // used to select a display configuration. Note that all properties should be - // immediately followed by the corresponding desired value and array should be - // terminated with EGL_NONE. Ownership of the array is not transferred to - // caller. desired_list contains list of desired EGL properties and values. - virtual const int32* GetEGLSurfaceProperties(const int32* desired_list); - - // Get the hal struct to check for overlay support. - virtual OverlayCandidatesOzone* GetOverlayCandidates( - gfx::AcceleratedWidget w); - - // Cleate a single native buffer to be used for overlay planes. - virtual scoped_refptr<NativePixmap> CreateNativePixmap( - gfx::Size size, - BufferFormat format); - - // Sets the overlay plane to switch to at the next page flip. - // |w| specifies the screen to display this overlay plane on. - // |plane_z_order| specifies the stacking order of the plane relative to the - // main framebuffer located at index 0. - // |plane_transform| specifies how the buffer is to be transformed during. - // composition. - // |buffer| to be presented by the overlay. - // |display_bounds| specify where it is supposed to be on the screen. - // |crop_rect| specifies the region within the buffer to be placed - // inside |display_bounds|. This is specified in texture coordinates, in the - // range of [0,1]. - virtual bool ScheduleOverlayPlane(gfx::AcceleratedWidget widget, - int plane_z_order, - gfx::OverlayTransform plane_transform, - scoped_refptr<NativePixmap> buffer, - const gfx::Rect& display_bounds, - const gfx::RectF& crop_rect); - - // Returns true if overlays can be shown at z-index 0, replacing the main - // surface. Combined with surfaceless extensions, it allows for an - // overlay-only mode. - virtual bool CanShowPrimaryPlaneAsOverlay(); - - private: - static SurfaceFactoryOzone* impl_; // not owned -}; - -} // namespace ui - -#endif // UI_OZONE_PUBLIC_SURFACE_FACTORY_OZONE_H_
diff --git a/ui/ozone/public/surface_ozone_canvas.h b/ui/ozone/public/surface_ozone_canvas.h deleted file mode 100644 index d02338b..0000000 --- a/ui/ozone/public/surface_ozone_canvas.h +++ /dev/null
@@ -1,56 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PUBLIC_SURFACE_OZONE_CANVAS_H_ -#define UI_OZONE_PUBLIC_SURFACE_OZONE_CANVAS_H_ - -#include "base/basictypes.h" -#include "base/memory/scoped_ptr.h" -#include "skia/ext/refptr.h" -#include "ui/ozone/ozone_base_export.h" - -class SkCanvas; - -namespace gfx { -class Size; -class VSyncProvider; -} - -namespace ui { - -// The platform-specific part of an software output. The class is intended -// for use when no EGL/GLES2 acceleration is possible. -// This class owns any bits that the ozone implementation needs freed when -// the software output is destroyed. -class OZONE_BASE_EXPORT SurfaceOzoneCanvas { - public: - virtual ~SurfaceOzoneCanvas() {} - - // Returns an SkCanvas for drawing on the window. - virtual skia::RefPtr<SkCanvas> GetCanvas() = 0; - - // Attempts to resize the canvas to match the viewport size. After - // resizing, the compositor must call GetCanvas() to get the next - // canvas - this invalidates any previous canvas from GetCanvas(). - virtual void ResizeCanvas(const gfx::Size& viewport_size) = 0; - - // Present the current canvas. After presenting, the compositor must - // call GetCanvas() to get the next canvas - this invalidates any - // previous canvas from GetCanvas(). - // - // The implementation may assume that any pixels outside the damage - // rectangle are unchanged since the previous call to PresentCanvas(). - virtual void PresentCanvas(const gfx::Rect& damage) = 0; - - // Returns a gfx::VsyncProvider for this surface. Note that this may be - // called after we have entered the sandbox so if there are operations (e.g. - // opening a file descriptor providing vsync events) that must be done - // outside of the sandbox, they must have been completed in - // InitializeHardware. Returns an empty scoped_ptr on error. - virtual scoped_ptr<gfx::VSyncProvider> CreateVSyncProvider() = 0; -}; - -} // namespace ui - -#endif // UI_OZONE_PUBLIC_SURFACE_OZONE_CANVAS_H_
diff --git a/ui/ozone/public/surface_ozone_egl.h b/ui/ozone/public/surface_ozone_egl.h deleted file mode 100644 index 4f38f06..0000000 --- a/ui/ozone/public/surface_ozone_egl.h +++ /dev/null
@@ -1,51 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PUBLIC_SURFACE_OZONE_EGL_H_ -#define UI_OZONE_PUBLIC_SURFACE_OZONE_EGL_H_ - -#include "base/basictypes.h" -#include "base/memory/scoped_ptr.h" -#include "ui/gfx/overlay_transform.h" -#include "ui/ozone/ozone_base_export.h" - -namespace gfx { -class Size; -class VSyncProvider; -} - -namespace ui { -class NativePixmap; - -// The platform-specific part of an EGL surface. -// -// This class owns any bits that the ozone implementation needs freed when -// the EGL surface is destroyed. -class OZONE_BASE_EXPORT SurfaceOzoneEGL { - public: - virtual ~SurfaceOzoneEGL() {} - - // Returns the EGL native window for rendering onto this surface. - // This can be used to to create a GLSurface. - virtual intptr_t /* EGLNativeWindowType */ GetNativeWindow() = 0; - - // Attempts to resize the EGL native window to match the viewport - // size. - virtual bool ResizeNativeWindow(const gfx::Size& viewport_size) = 0; - - // Called after we swap buffers. This is usually a no-op but can - // be used to present the new front buffer if the platform requires this. - virtual bool OnSwapBuffers() = 0; - - // Returns a gfx::VsyncProvider for this surface. Note that this may be - // called after we have entered the sandbox so if there are operations (e.g. - // opening a file descriptor providing vsync events) that must be done - // outside of the sandbox, they must have been completed in - // InitializeHardware. Returns an empty scoped_ptr on error. - virtual scoped_ptr<gfx::VSyncProvider> CreateVSyncProvider() = 0; -}; - -} // namespace ui - -#endif // UI_OZONE_PUBLIC_SURFACE_OZONE_EGL_H_
diff --git a/ui/ozone/public/ui_thread_gpu.cc b/ui/ozone/public/ui_thread_gpu.cc deleted file mode 100644 index 9601759..0000000 --- a/ui/ozone/public/ui_thread_gpu.cc +++ /dev/null
@@ -1,55 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/ozone/public/ui_thread_gpu.h" - -#include "ipc/ipc_listener.h" -#include "ipc/ipc_message.h" -#include "ipc/ipc_sender.h" -#include "ui/ozone/public/gpu_platform_support.h" -#include "ui/ozone/public/gpu_platform_support_host.h" -#include "ui/ozone/public/ozone_platform.h" - -namespace ui { - -class UiThreadGpuForwardingSender : public IPC::Sender { - public: - explicit UiThreadGpuForwardingSender(IPC::Listener* listener) - : listener_(listener) {} - virtual ~UiThreadGpuForwardingSender() {} - - // IPC::Sender: - virtual bool Send(IPC::Message* msg) override { - listener_->OnMessageReceived(*msg); - delete msg; - return true; - } - - private: - IPC::Listener* listener_; -}; - -UiThreadGpu::UiThreadGpu() { -} - -UiThreadGpu::~UiThreadGpu() { -} - -bool UiThreadGpu::Initialize() { - OzonePlatform* platform = ui::OzonePlatform::GetInstance(); - - ui_sender_.reset( - new UiThreadGpuForwardingSender(platform->GetGpuPlatformSupportHost())); - gpu_sender_.reset( - new UiThreadGpuForwardingSender(platform->GetGpuPlatformSupport())); - - const int kHostId = 1; - platform->GetGpuPlatformSupportHost()->OnChannelEstablished( - kHostId, gpu_sender_.get()); - platform->GetGpuPlatformSupport()->OnChannelEstablished(ui_sender_.get()); - - return true; -} - -} // namespace ui
diff --git a/ui/ozone/public/ui_thread_gpu.h b/ui/ozone/public/ui_thread_gpu.h deleted file mode 100644 index 8e2358a..0000000 --- a/ui/ozone/public/ui_thread_gpu.h +++ /dev/null
@@ -1,40 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_OZONE_PUBLIC_UI_THREAD_GPU_H_ -#define UI_OZONE_PUBLIC_UI_THREAD_GPU_H_ - -#include "base/memory/scoped_ptr.h" -#include "ui/ozone/ozone_export.h" - -namespace IPC { -class Sender; -} - -namespace ui { - -class UiThreadGpuForwardingSender; - -// Helper class for applications that do GL on the UI thead. -// -// This sets up message forwarding between the "gpu" and "ui" threads, -// for applications in which they are both the same thread. -class OZONE_EXPORT UiThreadGpu { - public: - UiThreadGpu(); - virtual ~UiThreadGpu(); - - // Start processing gpu messages. - bool Initialize(); - - private: - scoped_ptr<UiThreadGpuForwardingSender> ui_sender_; - scoped_ptr<UiThreadGpuForwardingSender> gpu_sender_; - - DISALLOW_COPY_AND_ASSIGN(UiThreadGpu); -}; - -} // namespace ui - -#endif // UI_OZONE_PUBLIC_UI_THREAD_GPU_H_
diff --git a/ui/ozone/run_all_unittests.cc b/ui/ozone/run_all_unittests.cc deleted file mode 100644 index 6192740..0000000 --- a/ui/ozone/run_all_unittests.cc +++ /dev/null
@@ -1,45 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/bind.h" -#include "base/test/launcher/unit_test_launcher.h" -#include "base/test/test_suite.h" -#include "build/build_config.h" - -namespace { - -class OzoneTestSuite : public base::TestSuite { - public: - OzoneTestSuite(int argc, char** argv); - - protected: - // base::TestSuite: - virtual void Initialize() override; - virtual void Shutdown() override; - - private: - DISALLOW_COPY_AND_ASSIGN(OzoneTestSuite); -}; - -OzoneTestSuite::OzoneTestSuite(int argc, char** argv) - : base::TestSuite(argc, argv) {} - -void OzoneTestSuite::Initialize() { - base::TestSuite::Initialize(); -} - -void OzoneTestSuite::Shutdown() { - base::TestSuite::Shutdown(); -} - -} // namespace - -int main(int argc, char** argv) { - OzoneTestSuite test_suite(argc, argv); - - return base::LaunchUnitTests(argc, - argv, - base::Bind(&OzoneTestSuite::Run, - base::Unretained(&test_suite))); -}
diff --git a/ui/views/BUILD.gn b/ui/views/BUILD.gn deleted file mode 100644 index 3919349..0000000 --- a/ui/views/BUILD.gn +++ /dev/null
@@ -1,190 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import("//build/config/features.gni") -import("//build/config/ui.gni") - -gypi_values = exec_script("//build/gypi_to_gn.py", - [ rebase_path("views.gyp") ], - "scope", - [ "views.gyp" ]) - -component("views") { - sources = gypi_values.views_sources - - defines = [ "VIEWS_IMPLEMENTATION" ] - - deps = [ - "//base:i18n", - "//base/third_party/dynamic_annotations", - "//skia", - "//third_party/icu", - "//ui/accessibility", - "//ui/aura", - "//ui/native_theme", - "//ui/resources", - "//ui/strings", - "//ui/wm", - "//url", - ] - - public_deps = [ - "//base", - "//ui/base", - "//ui/compositor", - "//ui/events", - "//ui/events:events_base", - "//ui/events/platform", - "//ui/gfx", - "//ui/gfx/geometry", - ] - - if (use_x11 && !is_chromeos) { - deps += [ "//ui/display/util" ] - } - - if (is_win) { - sources += gypi_values.views_win_sources - cflags = [ "/wd4267" ] # TODO(jschuh): crbug.com/167187 fix size_t to int truncations. - libs = [ - "imm32.lib", - "oleacc.lib", - ] - ldflags = [ "/DELAYLOAD:user32.dll" ] - deps += [ - "//third_party/iaccessible2", - "//third_party/wtl", - ] - } - - if (use_ozone) { - deps += [ "//ui/ozone" ] - } - if (use_x11) { - configs += [ - "//build/config/linux:x11", - "//build/config/linux:xrandr", - ] - deps += [ - "//ui/events/platform/x11", - "//ui/gfx/x", - ] - } - - if (use_aura) { - sources += gypi_values.views_aura_sources - } -} - -if (false) { - static_library("test_support") { - testonly = true - sources = gypi_values.views_test_support_sources - - public_deps = [ - ":views", - ] - deps = [ - "//base", - "//skia", - "//testing/gtest", - "//ui/aura", - "//ui/base", - "//ui/compositor", - "//ui/compositor:test_support", - "//ui/events", - "//ui/events:events_base", - "//ui/events:test_support", - "//ui/events/platform", - "//ui/gfx", - "//ui/gfx/geometry", - "//ui/wm", - ] - - if (use_aura) { - sources += gypi_values.views_test_support_aura_sources - deps += [ "//ui/aura:test_support" ] - } - if (use_x11) { - deps += [ "//ui/gfx/x" ] - } - } - - test("views_unittests") { - sources = gypi_values.views_unittests_sources - - deps = [ - ":test_support", - "//base", - "//base:i18n", - "//base/allocator", - "//base/test:test_support", - "//skia", - "//testing/gtest", - "//third_party/icu", - "//ui/accessibility", - "//ui/aura", - "//ui/base", - "//ui/base:test_support", - "//ui/compositor:test_support", - "//ui/events:test_support", - "//ui/events:events_base", - "//ui/events/platform", - "//ui/gfx", - "//ui/gfx/geometry", - "//ui/gl", - "//ui/resources", - "//ui/strings", - "//ui/wm", - "//url", - ] - - if (is_chromeos) { - sources -= [ "ime/input_method_bridge_unittest.cc" ] - } - - if (is_win) { - deps += [ - "//third_party/iaccessible2", - "//third_party/wtl", - ] - libs = [ - "imm32.lib", - "oleacc.lib", - "comctl32.lib", - ] - - # TOOD(GYP) - #'msvs_settings': { - # 'VCManifestTool': { - # 'AdditionalManifestFiles': [ - # '$(ProjectDir)\\test\\views_unittest.manifest', - # ], - # }, - #}, - } - - if (use_x11) { - configs += [ - "//build/config/linux:x11", - "//build/config/linux:xext", - ] - deps += [ - "//ui/events/platform/x11", - "//ui/gfx/x", - ] - } - - if (use_aura) { - sources += gypi_values.views_unittests_aura_sources - deps += [ "//ui/aura:test_support" ] - } - if (use_x11) { - deps += [ - "//ui/events/platform/x11", - "//ui/gfx/x", - ] - } - } -} # if (false)
diff --git a/ui/views/DEPS b/ui/views/DEPS deleted file mode 100644 index 6f7d8ab..0000000 --- a/ui/views/DEPS +++ /dev/null
@@ -1,27 +0,0 @@ -include_rules = [ - "+skia/ext", - "+third_party/iaccessible2", - "+third_party/skia", - "+ui/accessibility", - "+ui/aura", - "+ui/base", - "+ui/compositor", - "+ui/display", - "+ui/events", - "+ui/gfx", - "+ui/gl/gl_surface.h", # To initialize GL for tests. - "+ui/native_theme", - "+ui/ozone/public", - "+ui/resources/grit/ui_resources.h", - "+ui/strings/grit/ui_strings.h", - "+ui/wm/core", - "+ui/wm/public", - - "-testing/gmock", -] - -specific_include_rules = { - "examples_browser_main_parts\.cc": [ - "+ui/wm/test" - ], -}
diff --git a/ui/views/OWNERS b/ui/views/OWNERS deleted file mode 100644 index bcc5cf9..0000000 --- a/ui/views/OWNERS +++ /dev/null
@@ -1,3 +0,0 @@ -ben@chromium.org -sadrul@chromium.org -sky@chromium.org
diff --git a/ui/views/accessibility/DEPS b/ui/views/accessibility/DEPS deleted file mode 100644 index 32ae451..0000000 --- a/ui/views/accessibility/DEPS +++ /dev/null
@@ -1,3 +0,0 @@ -include_rules = [ - "+third_party/iaccessible2", -]
diff --git a/ui/views/accessibility/OWNERS b/ui/views/accessibility/OWNERS deleted file mode 100644 index 11e8fd8..0000000 --- a/ui/views/accessibility/OWNERS +++ /dev/null
@@ -1,2 +0,0 @@ -dmazzoni@chromium.org -dtseng@chromium.org
diff --git a/ui/views/accessibility/ax_aura_obj_cache.cc b/ui/views/accessibility/ax_aura_obj_cache.cc deleted file mode 100644 index ae2df20..0000000 --- a/ui/views/accessibility/ax_aura_obj_cache.cc +++ /dev/null
@@ -1,130 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/accessibility/ax_aura_obj_cache.h" - -#include "base/memory/singleton.h" -#include "base/stl_util.h" -#include "ui/aura/window.h" -#include "ui/views/accessibility/ax_aura_obj_wrapper.h" -#include "ui/views/accessibility/ax_view_obj_wrapper.h" -#include "ui/views/accessibility/ax_widget_obj_wrapper.h" -#include "ui/views/accessibility/ax_window_obj_wrapper.h" -#include "ui/views/view.h" -#include "ui/views/widget/widget.h" - -namespace views { - -// static -AXAuraObjCache* AXAuraObjCache::GetInstance() { - return Singleton<AXAuraObjCache>::get(); -} - -AXAuraObjWrapper* AXAuraObjCache::GetOrCreate(View* view) { - return CreateInternal<AXViewObjWrapper>(view, view_to_id_map_); -} - -AXAuraObjWrapper* AXAuraObjCache::GetOrCreate(Widget* widget) { - return CreateInternal<AXWidgetObjWrapper>(widget, widget_to_id_map_); -} - -AXAuraObjWrapper* AXAuraObjCache::GetOrCreate(aura::Window* window) { - return CreateInternal<AXWindowObjWrapper>(window, window_to_id_map_); -} - -int32 AXAuraObjCache::GetID(View* view) { - return GetIDInternal(view, view_to_id_map_); -} - -int32 AXAuraObjCache::GetID(Widget* widget) { - return GetIDInternal(widget, widget_to_id_map_); -} - -int32 AXAuraObjCache::GetID(aura::Window* window) { - return GetIDInternal(window, window_to_id_map_); -} - -void AXAuraObjCache::Remove(View* view) { - RemoveInternal(view, view_to_id_map_); -} - -void AXAuraObjCache::Remove(Widget* widget) { - RemoveInternal(widget, widget_to_id_map_); -} - -void AXAuraObjCache::Remove(aura::Window* window) { - RemoveInternal(window, window_to_id_map_); -} - -AXAuraObjWrapper* AXAuraObjCache::Get(int32 id) { - std::map<int32, AXAuraObjWrapper*>::iterator it = cache_.find(id); - - if (it == cache_.end()) - return NULL; - - return it->second; -} - -void AXAuraObjCache::Remove(int32 id) { - AXAuraObjWrapper* obj = Get(id); - - if (id == -1 || !obj) - return; - - cache_.erase(id); - delete obj; -} - -AXAuraObjCache::AXAuraObjCache() : current_id_(1) { -} - -AXAuraObjCache::~AXAuraObjCache() { - STLDeleteContainerPairSecondPointers(cache_.begin(), cache_.end()); - cache_.clear(); -} - -template <typename AuraViewWrapper, typename AuraView> -AXAuraObjWrapper* AXAuraObjCache::CreateInternal( - AuraView* aura_view, std::map<AuraView*, int32>& aura_view_to_id_map) { - if (!aura_view) - return NULL; - - typename std::map<AuraView*, int32>::iterator it = - aura_view_to_id_map.find(aura_view); - - if (it != aura_view_to_id_map.end()) - return Get(it->second); - - AXAuraObjWrapper* wrapper = new AuraViewWrapper(aura_view); - aura_view_to_id_map[aura_view] = current_id_; - cache_[current_id_] = wrapper; - current_id_++; - return wrapper; -} - -template<typename AuraView> int32 AXAuraObjCache::GetIDInternal( - AuraView* aura_view, std::map<AuraView*, int32>& aura_view_to_id_map) { - if (!aura_view) - return -1; - - typename std::map<AuraView*, int32>::iterator it = - aura_view_to_id_map.find(aura_view); - - if (it != aura_view_to_id_map.end()) - return it->second; - - return -1; -} - -template<typename AuraView> -void AXAuraObjCache::RemoveInternal( - AuraView* aura_view, std::map<AuraView*, int32>& aura_view_to_id_map) { - int32 id = GetID(aura_view); - if (id == -1) - return; - aura_view_to_id_map.erase(aura_view); - Remove(id); -} - -} // namespace views
diff --git a/ui/views/accessibility/ax_aura_obj_cache.h b/ui/views/accessibility/ax_aura_obj_cache.h deleted file mode 100644 index 6e5d9e8..0000000 --- a/ui/views/accessibility/ax_aura_obj_cache.h +++ /dev/null
@@ -1,83 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_ACCESSIBILITY_AX_AURA_OBJ_CACHE_H_ -#define UI_VIEWS_ACCESSIBILITY_AX_AURA_OBJ_CACHE_H_ - -#include <map> - -#include "base/basictypes.h" -#include "ui/views/views_export.h" - -template <typename T> struct DefaultSingletonTraits; - -namespace aura { -class Window; -} // namespace aura - -namespace views { -class AXAuraObjWrapper; -class View; -class Widget; - -// A cache responsible for assigning id's to a set of interesting Aura views. -class VIEWS_EXPORT AXAuraObjCache { - public: - // Get the single instance of this class. - static AXAuraObjCache* GetInstance(); - - // Get or create an entry in the cache based on an Aura view. - AXAuraObjWrapper* GetOrCreate(View* view); - AXAuraObjWrapper* GetOrCreate(Widget* widget); - AXAuraObjWrapper* GetOrCreate(aura::Window* window); - - // Gets an id given an Aura view. - int32 GetID(View* view); - int32 GetID(Widget* widget); - int32 GetID(aura::Window* window); - - // Gets the next unique id for this cache. Useful for non-Aura view backed - // views. - int32 GetNextID() { return current_id_++; } - - // Removes an entry from this cache based on an Aura view. - void Remove(View* view); - void Remove(Widget* widget); - void Remove(aura::Window* window); - - // Lookup a cached entry based on an id. - AXAuraObjWrapper* Get(int32 id); - - // Remove a cached entry based on an id. - void Remove(int32 id); - - private: - friend struct DefaultSingletonTraits<AXAuraObjCache>; - - AXAuraObjCache(); - virtual ~AXAuraObjCache(); - - template <typename AuraViewWrapper, typename AuraView> - AXAuraObjWrapper* CreateInternal( - AuraView* aura_view, std::map<AuraView*, int32>& aura_view_to_id_map); - - template<typename AuraView> int32 GetIDInternal( - AuraView* aura_view, std::map<AuraView*, int32>& aura_view_to_id_map); - - template<typename AuraView> void RemoveInternal( - AuraView* aura_view, std::map<AuraView*, int32>& aura_view_to_id_map); - - std::map<views::View*, int32> view_to_id_map_; - std::map<views::Widget*, int32> widget_to_id_map_; - std::map<aura::Window*, int32> window_to_id_map_; - - std::map<int32, AXAuraObjWrapper*> cache_; - int32 current_id_; - - DISALLOW_COPY_AND_ASSIGN(AXAuraObjCache); -}; - -} // namespace views - -#endif // UI_VIEWS_ACCESSIBILITY_AX_AURA_OBJ_CACHE_H_
diff --git a/ui/views/accessibility/ax_aura_obj_wrapper.h b/ui/views/accessibility/ax_aura_obj_wrapper.h deleted file mode 100644 index 00f9c59..0000000 --- a/ui/views/accessibility/ax_aura_obj_wrapper.h +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_ACCESSIBILITY_AX_AURA_OBJ_WRAPPER_H_ -#define UI_VIEWS_ACCESSIBILITY_AX_AURA_OBJ_WRAPPER_H_ - -#include <vector> - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/macros.h" -#include "ui/views/views_export.h" - -namespace ui { -struct AXNodeData; -} // namespace ui - -namespace views { - -// An interface abstraction for Aura views that exposes the view-tree formed -// by the implementing view types. -class VIEWS_EXPORT AXAuraObjWrapper { - public: - virtual ~AXAuraObjWrapper() {} - - // Traversal and serialization. - virtual AXAuraObjWrapper* GetParent() = 0; - virtual void GetChildren( - std::vector<AXAuraObjWrapper*>* out_children) = 0; - virtual void Serialize(ui::AXNodeData* out_node_data) = 0; - virtual int32 GetID() = 0; - - // Actions. - virtual void DoDefault() {} - virtual void Focus() {} - virtual void MakeVisible() {} - virtual void SetSelection(int32 start, int32 end) {} -}; - -} // namespace views - -#endif // UI_VIEWS_ACCESSIBILITY_AX_AURA_OBJ_WRAPPER_H_
diff --git a/ui/views/accessibility/ax_view_obj_wrapper.cc b/ui/views/accessibility/ax_view_obj_wrapper.cc deleted file mode 100644 index b5c6077..0000000 --- a/ui/views/accessibility/ax_view_obj_wrapper.cc +++ /dev/null
@@ -1,91 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/accessibility/ax_view_obj_wrapper.h" - -#include "base/strings/utf_string_conversions.h" -#include "ui/accessibility/ax_node_data.h" -#include "ui/accessibility/ax_view_state.h" -#include "ui/views/accessibility/ax_aura_obj_cache.h" -#include "ui/views/view.h" -#include "ui/views/widget/widget.h" - -namespace views { - -AXViewObjWrapper::AXViewObjWrapper(View* view) : view_(view) { - DCHECK(view->GetWidget()); - if (view->GetWidget()) - AXAuraObjCache::GetInstance()->GetOrCreate(view->GetWidget()); -} - -AXViewObjWrapper::~AXViewObjWrapper() {} - -AXAuraObjWrapper* AXViewObjWrapper::GetParent() { - AXAuraObjCache* cache = AXAuraObjCache::GetInstance(); - if (view_->parent()) - return cache->GetOrCreate(view_->parent()); - - return cache->GetOrCreate(view_->GetWidget()); -} - -void AXViewObjWrapper::GetChildren( - std::vector<AXAuraObjWrapper*>* out_children) { - // TODO(dtseng): Need to handle |Widget| child of |View|. - for (int i = 0; i < view_->child_count(); ++i) { - AXAuraObjWrapper* child = - AXAuraObjCache::GetInstance()->GetOrCreate(view_->child_at(i)); - out_children->push_back(child); - } -} - -void AXViewObjWrapper::Serialize(ui::AXNodeData* out_node_data) { - ui::AXViewState view_data; - view_->GetAccessibleState(&view_data); - out_node_data->id = GetID(); - out_node_data->role = view_data.role; - - out_node_data->state = view_data.state(); - if (view_->HasFocus()) - out_node_data->state |= 1 << ui::AX_STATE_FOCUSED; - if (view_->IsFocusable()) - out_node_data->state |= 1 << ui::AX_STATE_FOCUSABLE; - - out_node_data->location = view_->GetBoundsInScreen(); - - out_node_data->AddStringAttribute( - ui::AX_ATTR_NAME, base::UTF16ToUTF8(view_data.name)); - out_node_data->AddStringAttribute( - ui::AX_ATTR_VALUE, base::UTF16ToUTF8(view_data.value)); - - out_node_data->AddIntAttribute(ui::AX_ATTR_TEXT_SEL_START, - view_data.selection_start); - out_node_data->AddIntAttribute(ui::AX_ATTR_TEXT_SEL_END, - view_data.selection_end); -} - -int32 AXViewObjWrapper::GetID() { - return AXAuraObjCache::GetInstance()->GetID(view_); -} - -void AXViewObjWrapper::DoDefault() { - gfx::Rect rect = view_->GetBoundsInScreen(); - gfx::Point center = rect.CenterPoint(); - view_->OnMousePressed(ui::MouseEvent(ui::ET_MOUSE_PRESSED, center, center, - ui::EF_LEFT_MOUSE_BUTTON, - ui::EF_LEFT_MOUSE_BUTTON)); -} - -void AXViewObjWrapper::Focus() { - view_->RequestFocus(); -} - -void AXViewObjWrapper::MakeVisible() { - // TODO(dtseng): Implement. -} - -void AXViewObjWrapper::SetSelection(int32 start, int32 end) { - // TODO(dtseng): Implement. -} - -} // namespace views
diff --git a/ui/views/accessibility/ax_view_obj_wrapper.h b/ui/views/accessibility/ax_view_obj_wrapper.h deleted file mode 100644 index 7a768b7..0000000 --- a/ui/views/accessibility/ax_view_obj_wrapper.h +++ /dev/null
@@ -1,38 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_ACCESSIBILITY_AX_VIEW_OBJ_WRAPPER_H_ -#define UI_VIEWS_ACCESSIBILITY_AX_VIEW_OBJ_WRAPPER_H_ - -#include "ui/views/accessibility/ax_aura_obj_wrapper.h" - -namespace views { -class View; - -// Describes a |View| for use with other AX classes. -class AXViewObjWrapper : public AXAuraObjWrapper { - public: - explicit AXViewObjWrapper(View* view); - virtual ~AXViewObjWrapper(); - - // AXAuraObjWrapper overrides. - virtual AXAuraObjWrapper* GetParent() override; - virtual void GetChildren( - std::vector<AXAuraObjWrapper*>* out_children) override; - virtual void Serialize(ui::AXNodeData* out_node_data) override; - virtual int32 GetID() override; - virtual void DoDefault() override; - virtual void Focus() override; - virtual void MakeVisible() override; - virtual void SetSelection(int32 start, int32 end) override; - - private: - View* view_; - - DISALLOW_COPY_AND_ASSIGN(AXViewObjWrapper); -}; - -} // namespace views - -#endif // UI_VIEWS_ACCESSIBILITY_AX_VIEW_OBJ_WRAPPER_H_
diff --git a/ui/views/accessibility/ax_widget_obj_wrapper.cc b/ui/views/accessibility/ax_widget_obj_wrapper.cc deleted file mode 100644 index 36a3143..0000000 --- a/ui/views/accessibility/ax_widget_obj_wrapper.cc +++ /dev/null
@@ -1,55 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/accessibility/ax_widget_obj_wrapper.h" - -#include "ui/accessibility/ax_node_data.h" -#include "ui/views/accessibility/ax_aura_obj_cache.h" -#include "ui/views/accessibility/ax_aura_obj_wrapper.h" -#include "ui/views/widget/widget.h" - -namespace views { - -AXWidgetObjWrapper::AXWidgetObjWrapper(Widget* widget) : widget_(widget) { - widget->AddObserver(this); - widget->AddRemovalsObserver(this); -} - -AXWidgetObjWrapper::~AXWidgetObjWrapper() { - widget_->RemoveObserver(this); - widget_->RemoveRemovalsObserver(this); - widget_ = NULL; -} - -AXAuraObjWrapper* AXWidgetObjWrapper::GetParent() { - return AXAuraObjCache::GetInstance()->GetOrCreate(widget_->GetNativeView()); -} - -void AXWidgetObjWrapper::GetChildren( - std::vector<AXAuraObjWrapper*>* out_children) { - out_children->push_back( - AXAuraObjCache::GetInstance()->GetOrCreate(widget_->GetRootView())); -} - -void AXWidgetObjWrapper::Serialize(ui::AXNodeData* out_node_data) { - out_node_data->id = GetID(); - out_node_data->role = ui::AX_ROLE_CLIENT; - out_node_data->location = widget_->GetWindowBoundsInScreen(); - // TODO(dtseng): Set better states. - out_node_data->state = 0; -} - -int32 AXWidgetObjWrapper::GetID() { - return AXAuraObjCache::GetInstance()->GetID(widget_); -} - -void AXWidgetObjWrapper::OnWidgetDestroying(Widget* widget) { - AXAuraObjCache::GetInstance()->Remove(widget); -} - -void AXWidgetObjWrapper::OnWillRemoveView(Widget* widget, View* view) { - AXAuraObjCache::GetInstance()->Remove(view); -} - -} // namespace views
diff --git a/ui/views/accessibility/ax_widget_obj_wrapper.h b/ui/views/accessibility/ax_widget_obj_wrapper.h deleted file mode 100644 index 52c03ca..0000000 --- a/ui/views/accessibility/ax_widget_obj_wrapper.h +++ /dev/null
@@ -1,44 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_ACCESSIBILITY_AX_WIDGET_OBJ_WRAPPER_H_ -#define UI_VIEWS_ACCESSIBILITY_AX_WIDGET_OBJ_WRAPPER_H_ - -#include "ui/views/accessibility/ax_aura_obj_wrapper.h" -#include "ui/views/widget/widget_observer.h" -#include "ui/views/widget/widget_removals_observer.h" - -namespace views { -class Widget; - -// Describes a |Widget| for use with other AX classes. -class AXWidgetObjWrapper : public AXAuraObjWrapper, - public WidgetObserver, - public WidgetRemovalsObserver { - public: - explicit AXWidgetObjWrapper(Widget* widget); - virtual ~AXWidgetObjWrapper(); - - // AXAuraObjWrapper overrides. - virtual AXAuraObjWrapper* GetParent() override; - virtual void GetChildren( - std::vector<AXAuraObjWrapper*>* out_children) override; - virtual void Serialize(ui::AXNodeData* out_node_data) override; - virtual int32 GetID() override; - - // WidgetObserver overrides. - virtual void OnWidgetDestroying(Widget* widget) override; - - // WidgetRemovalsObserver overrides. - virtual void OnWillRemoveView(Widget* widget, View* view) override; - - private: - Widget* widget_; - - DISALLOW_COPY_AND_ASSIGN(AXWidgetObjWrapper); -}; - -} // namespace views - -#endif // UI_VIEWS_ACCESSIBILITY_AX_WIDGET_OBJ_WRAPPER_H_
diff --git a/ui/views/accessibility/ax_window_obj_wrapper.cc b/ui/views/accessibility/ax_window_obj_wrapper.cc deleted file mode 100644 index b358de5..0000000 --- a/ui/views/accessibility/ax_window_obj_wrapper.cc +++ /dev/null
@@ -1,64 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/accessibility/ax_window_obj_wrapper.h" - -#include "base/strings/utf_string_conversions.h" -#include "ui/accessibility/ax_node_data.h" -#include "ui/aura/window.h" -#include "ui/views/accessibility/ax_aura_obj_cache.h" -#include "ui/views/widget/widget.h" - -namespace views { - -AXWindowObjWrapper::AXWindowObjWrapper( - aura::Window* window) : window_(window) { - window->AddObserver(this); -} - -AXWindowObjWrapper::~AXWindowObjWrapper() { - window_->RemoveObserver(this); - window_ = NULL; -} - -AXAuraObjWrapper* AXWindowObjWrapper::GetParent() { - if (!window_->parent()) - return NULL; - - return AXAuraObjCache::GetInstance()->GetOrCreate(window_->parent()); -} - -void AXWindowObjWrapper::GetChildren( - std::vector<AXAuraObjWrapper*>* out_children) { - aura::Window::Windows children = window_->children(); - for (size_t i = 0; i < children.size(); ++i) { - out_children->push_back( - AXAuraObjCache::GetInstance()->GetOrCreate(children[i])); - } - - // Also consider any associated widgets as children. - Widget* widget = Widget::GetWidgetForNativeView(window_); - if (widget) - out_children->push_back(AXAuraObjCache::GetInstance()->GetOrCreate(widget)); -} - -void AXWindowObjWrapper::Serialize(ui::AXNodeData* out_node_data) { - out_node_data->id = GetID(); - out_node_data->role = ui::AX_ROLE_WINDOW; - // TODO(dtseng): Set better states. - out_node_data->state = 0; - out_node_data->location = window_->bounds(); - out_node_data->AddStringAttribute( - ui::AX_ATTR_NAME, base::UTF16ToUTF8(window_->title())); -} - -int32 AXWindowObjWrapper::GetID() { - return AXAuraObjCache::GetInstance()->GetID(window_); -} - -void AXWindowObjWrapper::OnWindowDestroying(aura::Window* window) { - AXAuraObjCache::GetInstance()->Remove(window); -} - -} // namespace views
diff --git a/ui/views/accessibility/ax_window_obj_wrapper.h b/ui/views/accessibility/ax_window_obj_wrapper.h deleted file mode 100644 index 14bf2a8..0000000 --- a/ui/views/accessibility/ax_window_obj_wrapper.h +++ /dev/null
@@ -1,42 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_ACCESSIBILITY_AX_WINDOW_OBJ_WRAPPER_H_ -#define UI_VIEWS_ACCESSIBILITY_AX_WINDOW_OBJ_WRAPPER_H_ - -#include "ui/aura/window_observer.h" -#include "ui/views/accessibility/ax_aura_obj_wrapper.h" - -namespace aura { -class Window; -} // namespace aura - -namespace views { - -// Describes a |Window| for use with other AX classes. -class AXWindowObjWrapper : public AXAuraObjWrapper, - public aura::WindowObserver { - public: - explicit AXWindowObjWrapper(aura::Window* window); - virtual ~AXWindowObjWrapper(); - - // AXAuraObjWrapper overrides. - virtual AXAuraObjWrapper* GetParent() override; - virtual void GetChildren( - std::vector<AXAuraObjWrapper*>* out_children) override; - virtual void Serialize(ui::AXNodeData* out_node_data) override; - virtual int32 GetID() override; - - // WindowObserver overrides. - virtual void OnWindowDestroying(aura::Window* window) override; - - private: - aura::Window* window_; - - DISALLOW_COPY_AND_ASSIGN(AXWindowObjWrapper); -}; - -} // namespace views - -#endif // UI_VIEWS_ACCESSIBILITY_AX_WINDOW_OBJ_WRAPPER_H_
diff --git a/ui/views/accessibility/native_view_accessibility.cc b/ui/views/accessibility/native_view_accessibility.cc deleted file mode 100644 index 6ca7676..0000000 --- a/ui/views/accessibility/native_view_accessibility.cc +++ /dev/null
@@ -1,89 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/accessibility/native_view_accessibility.h" - -#include "ui/accessibility/ax_view_state.h" -#include "ui/views/view.h" -#include "ui/views/widget/widget.h" - -namespace views { - -#if !defined(OS_WIN) -// static -NativeViewAccessibility* NativeViewAccessibility::Create(View* view) { - DCHECK(view); - NativeViewAccessibility* instance = new NativeViewAccessibility(); - instance->set_view(view); - return instance; -} -#endif - -NativeViewAccessibility::NativeViewAccessibility() - : view_(NULL), ax_node_(ui::AXPlatformNode::Create(this)) { -} - -NativeViewAccessibility::~NativeViewAccessibility() { - if (ax_node_) - ax_node_->Destroy(); -} - -gfx::NativeViewAccessible NativeViewAccessibility::GetNativeObject() { - return ax_node_ ? ax_node_->GetNativeViewAccessible() : NULL; -} - -void NativeViewAccessibility::Destroy() { - delete this; -} - -#if !defined(OS_WIN) -// static -void NativeViewAccessibility::RegisterWebView(View* web_view) { -} - -// static -void NativeViewAccessibility::UnregisterWebView(View* web_view) { -} -#endif - -// ui::AXPlatformNodeDelegate - -ui::AXNodeData* NativeViewAccessibility::GetData() { - ui::AXViewState state; - view_->GetAccessibleState(&state); - data_.role = state.role; - data_.location = view_->GetBoundsInScreen(); - return &data_; -} - -int NativeViewAccessibility::GetChildCount() { - return view_->child_count(); -} - -gfx::NativeViewAccessible NativeViewAccessibility::ChildAtIndex(int index) { - if (index < 0 || index >= view_->child_count()) - return NULL; - return view_->child_at(index)->GetNativeViewAccessible(); -} - -gfx::NativeViewAccessible NativeViewAccessibility::GetParent() { - if (view_->parent()) - return view_->parent()->GetNativeViewAccessible(); - -#if defined(OS_MACOSX) - if (view_->GetWidget()) - return view_->GetWidget()->GetNativeView(); -#endif - - return NULL; -} - -gfx::Vector2d NativeViewAccessibility::GetGlobalCoordinateOffset() { - return gfx::Vector2d(0, 0); // location is already in screen coordinates. -} - -void NativeViewAccessibility::NotifyAccessibilityEvent(ui::AXEvent event_type) { -} - -} // namespace views
diff --git a/ui/views/accessibility/native_view_accessibility.h b/ui/views/accessibility/native_view_accessibility.h deleted file mode 100644 index 9a94d3a..0000000 --- a/ui/views/accessibility/native_view_accessibility.h +++ /dev/null
@@ -1,63 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_ACCESSIBILITY_NATIVE_VIEW_ACCESSIBILITY_H_ -#define UI_VIEWS_ACCESSIBILITY_NATIVE_VIEW_ACCESSIBILITY_H_ - -#include "ui/accessibility/ax_node_data.h" -#include "ui/accessibility/platform/ax_platform_node.h" -#include "ui/accessibility/platform/ax_platform_node_delegate.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/views/views_export.h" - -namespace views { - -class View; - -class VIEWS_EXPORT NativeViewAccessibility : public ui::AXPlatformNodeDelegate { - public: - static NativeViewAccessibility* Create(View* view); - - virtual gfx::NativeViewAccessible GetNativeObject(); - - // Call Destroy rather than deleting this, because the subclass may - // use reference counting. - virtual void Destroy(); - - // WebViews need to be registered because they implement their own - // tree of accessibility objects, and we need to check them when - // mapping a child id to a NativeViewAccessible. - static void RegisterWebView(View* web_view); - static void UnregisterWebView(View* web_view); - - // ui::AXPlatformNodeDelegate - ui::AXNodeData* GetData() override; - int GetChildCount() override; - gfx::NativeViewAccessible ChildAtIndex(int index) override; - gfx::NativeViewAccessible GetParent() override; - gfx::Vector2d GetGlobalCoordinateOffset() override; - void NotifyAccessibilityEvent(ui::AXEvent event_type) override; - - protected: - NativeViewAccessibility(); - virtual ~NativeViewAccessibility(); - - void set_view(views::View* view) { view_ = view; } - const View* view() const { return view_; } - - View* view_; // Weak. Owns this. - - private: - // We own this, but it is reference-counted on some platforms so we can't use - // a scoped_ptr. It is dereferenced in the destructor. - ui::AXPlatformNode* ax_node_; - - ui::AXNodeData data_; - - DISALLOW_COPY_AND_ASSIGN(NativeViewAccessibility); -}; - -} // namespace views - -#endif // UI_VIEWS_ACCESSIBILITY_NATIVE_VIEW_ACCESSIBILITY_H_
diff --git a/ui/views/accessibility/native_view_accessibility_unittest.cc b/ui/views/accessibility/native_view_accessibility_unittest.cc deleted file mode 100644 index c376bbf..0000000 --- a/ui/views/accessibility/native_view_accessibility_unittest.cc +++ /dev/null
@@ -1,77 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/strings/utf_string_conversions.h" -#include "ui/accessibility/ax_view_state.h" -#include "ui/views/accessibility/native_view_accessibility.h" -#include "ui/views/controls/button/button.h" -#include "ui/views/controls/label.h" -#include "ui/views/test/views_test_base.h" - -namespace views { -namespace test { - -class NativeViewAccessibilityTest; - -namespace { - -class TestButton : public Button { - public: - TestButton() : Button(NULL) {} -}; - -} // namespace - -class NativeViewAccessibilityTest : public ViewsTestBase { - public: - NativeViewAccessibilityTest() {} - virtual ~NativeViewAccessibilityTest() {} - - virtual void SetUp() override { - ViewsTestBase::SetUp(); - button_.reset(new TestButton()); - button_->SetSize(gfx::Size(20, 20)); - button_accessibility_ = NativeViewAccessibility::Create(button_.get()); - - label_.reset(new Label); - button_->AddChildView(label_.get()); - label_accessibility_ = NativeViewAccessibility::Create(label_.get()); - } - - virtual void TearDown() override { - button_accessibility_->Destroy(); - button_accessibility_ = NULL; - label_accessibility_->Destroy(); - label_accessibility_ = NULL; - ViewsTestBase::TearDown(); - } - - protected: - scoped_ptr<TestButton> button_; - NativeViewAccessibility* button_accessibility_; - scoped_ptr<Label> label_; - NativeViewAccessibility* label_accessibility_; -}; - -TEST_F(NativeViewAccessibilityTest, RoleShouldMatch) { - EXPECT_EQ(ui::AX_ROLE_BUTTON, button_accessibility_->GetData()->role); - EXPECT_EQ(ui::AX_ROLE_STATIC_TEXT, label_accessibility_->GetData()->role); -} - -TEST_F(NativeViewAccessibilityTest, BoundsShouldMatch) { - gfx::Rect bounds = button_accessibility_->GetData()->location; - bounds.Offset(button_accessibility_->GetGlobalCoordinateOffset()); - EXPECT_EQ(button_->GetBoundsInScreen(), bounds); -} - -TEST_F(NativeViewAccessibilityTest, LabelIsChildOfButton) { - EXPECT_EQ(1, button_accessibility_->GetChildCount()); - EXPECT_EQ(label_->GetNativeViewAccessible(), - button_accessibility_->ChildAtIndex(0)); - EXPECT_EQ(button_->GetNativeViewAccessible(), - label_accessibility_->GetParent()); -} - -} // namespace test -} // namespace views
diff --git a/ui/views/accessibility/native_view_accessibility_win.cc b/ui/views/accessibility/native_view_accessibility_win.cc deleted file mode 100644 index 023e311..0000000 --- a/ui/views/accessibility/native_view_accessibility_win.cc +++ /dev/null
@@ -1,1540 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/accessibility/native_view_accessibility_win.h" - -#include <oleacc.h> -#include <UIAutomationClient.h> - -#include <set> -#include <vector> - -#include "base/memory/singleton.h" -#include "base/strings/utf_string_conversions.h" -#include "base/win/scoped_comptr.h" -#include "base/win/windows_version.h" -#include "third_party/iaccessible2/ia2_api_all.h" -#include "ui/accessibility/ax_enums.h" -#include "ui/accessibility/ax_text_utils.h" -#include "ui/accessibility/ax_view_state.h" -#include "ui/base/win/accessibility_ids_win.h" -#include "ui/base/win/accessibility_misc_utils.h" -#include "ui/base/win/atl_module.h" -#include "ui/views/controls/button/custom_button.h" -#include "ui/views/focus/focus_manager.h" -#include "ui/views/focus/view_storage.h" -#include "ui/views/widget/widget.h" -#include "ui/views/win/hwnd_util.h" - -namespace views { -namespace { - -class AccessibleWebViewRegistry { - public: - static AccessibleWebViewRegistry* GetInstance(); - - void RegisterWebView(View* web_view); - - void UnregisterWebView(View* web_view); - - // Given the view that received the request for the accessible - // id in |top_view|, and the child id requested, return the native - // accessible object with that child id from one of the WebViews in - // |top_view|'s view hierarchy, if any. - IAccessible* GetAccessibleFromWebView(View* top_view, long child_id); - - // The system uses IAccessible APIs for many purposes, but only - // assistive technology like screen readers uses IAccessible2. - // Call this method to note that the IAccessible2 interface was queried and - // that WebViews should be proactively notified that this interface will be - // used. If this is enabled for the first time, this will explicitly call - // QueryService with an argument of IAccessible2 on all WebViews, otherwise - // it will just do it from now on. - void EnableIAccessible2Support(); - - private: - friend struct DefaultSingletonTraits<AccessibleWebViewRegistry>; - AccessibleWebViewRegistry(); - ~AccessibleWebViewRegistry() {} - - IAccessible* AccessibleObjectFromChildId(View* web_view, long child_id); - - void QueryIAccessible2Interface(View* web_view); - - // Set of all web views. We check whether each one is contained in a - // top view dynamically rather than keeping track of a map. - std::set<View*> web_views_; - - // The most recent top view used in a call to GetAccessibleFromWebView. - View* last_top_view_; - - // The most recent web view where an accessible object was found, - // corresponding to |last_top_view_|. - View* last_web_view_; - - // If IAccessible2 support is enabled, we query the IAccessible2 interface - // of WebViews proactively when they're registered, so that they are - // aware that they need to support this interface. - bool iaccessible2_support_enabled_; - - DISALLOW_COPY_AND_ASSIGN(AccessibleWebViewRegistry); -}; - -AccessibleWebViewRegistry::AccessibleWebViewRegistry() - : last_top_view_(NULL), - last_web_view_(NULL), - iaccessible2_support_enabled_(false) { -} - -AccessibleWebViewRegistry* AccessibleWebViewRegistry::GetInstance() { - return Singleton<AccessibleWebViewRegistry>::get(); -} - -void AccessibleWebViewRegistry::RegisterWebView(View* web_view) { - DCHECK(web_views_.find(web_view) == web_views_.end()); - web_views_.insert(web_view); - - if (iaccessible2_support_enabled_) - QueryIAccessible2Interface(web_view); -} - -void AccessibleWebViewRegistry::UnregisterWebView(View* web_view) { - DCHECK(web_views_.find(web_view) != web_views_.end()); - web_views_.erase(web_view); - if (last_web_view_ == web_view) { - last_top_view_ = NULL; - last_web_view_ = NULL; - } -} - -IAccessible* AccessibleWebViewRegistry::GetAccessibleFromWebView( - View* top_view, long child_id) { - // This function gets called frequently, so try to avoid searching all - // of the web views if the notification is on the same web view that - // sent the last one. - if (last_top_view_ == top_view) { - IAccessible* accessible = - AccessibleObjectFromChildId(last_web_view_, child_id); - if (accessible) - return accessible; - } - - // Search all web views. For each one, first ensure it's a descendant - // of this view where the event was posted - and if so, see if it owns - // an accessible object with that child id. If so, save the view to speed - // up the next notification. - for (std::set<View*>::iterator iter = web_views_.begin(); - iter != web_views_.end(); ++iter) { - View* web_view = *iter; - if (top_view == web_view || !top_view->Contains(web_view)) - continue; - IAccessible* accessible = AccessibleObjectFromChildId(web_view, child_id); - if (accessible) { - last_top_view_ = top_view; - last_web_view_ = web_view; - return accessible; - } - } - - return NULL; -} - -void AccessibleWebViewRegistry::EnableIAccessible2Support() { - if (iaccessible2_support_enabled_) - return; - iaccessible2_support_enabled_ = true; - for (std::set<View*>::iterator iter = web_views_.begin(); - iter != web_views_.end(); ++iter) { - QueryIAccessible2Interface(*iter); - } -} - -IAccessible* AccessibleWebViewRegistry::AccessibleObjectFromChildId( - View* web_view, - long child_id) { - IAccessible* web_view_accessible = web_view->GetNativeViewAccessible(); - if (web_view_accessible == NULL) - return NULL; - - VARIANT var_child; - var_child.vt = VT_I4; - var_child.lVal = child_id; - IAccessible* result = NULL; - if (S_OK == web_view_accessible->get_accChild( - var_child, reinterpret_cast<IDispatch**>(&result))) { - return result; - } - - return NULL; -} - -void AccessibleWebViewRegistry::QueryIAccessible2Interface(View* web_view) { - IAccessible* web_view_accessible = web_view->GetNativeViewAccessible(); - if (!web_view_accessible) - return; - - base::win::ScopedComPtr<IServiceProvider> service_provider; - if (S_OK != web_view_accessible->QueryInterface(service_provider.Receive())) - return; - base::win::ScopedComPtr<IAccessible2> iaccessible2; - service_provider->QueryService( - IID_IAccessible, IID_IAccessible2, - reinterpret_cast<void**>(iaccessible2.Receive())); -} - -} // anonymous namespace - -// static -long NativeViewAccessibilityWin::next_unique_id_ = 1; -int NativeViewAccessibilityWin::view_storage_ids_[kMaxViewStorageIds] = {0}; -int NativeViewAccessibilityWin::next_view_storage_id_index_ = 0; -std::vector<int> NativeViewAccessibilityWin::alert_target_view_storage_ids_; - -// static -NativeViewAccessibility* NativeViewAccessibility::Create(View* view) { - // Make sure ATL is initialized in this module. - ui::win::CreateATLModuleIfNeeded(); - - CComObject<NativeViewAccessibilityWin>* instance = NULL; - HRESULT hr = CComObject<NativeViewAccessibilityWin>::CreateInstance( - &instance); - DCHECK(SUCCEEDED(hr)); - instance->set_view(view); - instance->AddRef(); - return instance; -} - -NativeViewAccessibilityWin::NativeViewAccessibilityWin() - : unique_id_(next_unique_id_++) { -} - -NativeViewAccessibilityWin::~NativeViewAccessibilityWin() { - RemoveAlertTarget(); -} - -void NativeViewAccessibilityWin::NotifyAccessibilityEvent( - ui::AXEvent event_type) { - if (!view_) - return; - - ViewStorage* view_storage = ViewStorage::GetInstance(); - HWND hwnd = HWNDForView(view_); - int view_storage_id = view_storage_ids_[next_view_storage_id_index_]; - if (view_storage_id == 0) { - view_storage_id = view_storage->CreateStorageID(); - view_storage_ids_[next_view_storage_id_index_] = view_storage_id; - } else { - view_storage->RemoveView(view_storage_id); - } - view_storage->StoreView(view_storage_id, view_); - - // Positive child ids are used for enumerating direct children, - // negative child ids can be used as unique ids to refer to a specific - // descendants. Make index into view_storage_ids_ into a negative child id. - int child_id = - base::win::kFirstViewsAccessibilityId - next_view_storage_id_index_; - ::NotifyWinEvent(MSAAEvent(event_type), hwnd, OBJID_CLIENT, child_id); - next_view_storage_id_index_ = - (next_view_storage_id_index_ + 1) % kMaxViewStorageIds; - - // Keep track of views that are a target of an alert event. - if (event_type == ui::AX_EVENT_ALERT) - AddAlertTarget(); -} - -gfx::NativeViewAccessible NativeViewAccessibilityWin::GetNativeObject() { - return this; -} - -void NativeViewAccessibilityWin::Destroy() { - view_ = NULL; - Release(); -} - -STDMETHODIMP NativeViewAccessibilityWin::accHitTest( - LONG x_left, LONG y_top, VARIANT* child) { - if (!child) - return E_INVALIDARG; - - if (!view_ || !view_->GetWidget()) - return E_FAIL; - - // If this is a root view, our widget might have child widgets. - // Search child widgets first, since they're on top in the z-order. - if (view_->GetWidget()->GetRootView() == view_) { - std::vector<Widget*> child_widgets; - PopulateChildWidgetVector(&child_widgets); - for (size_t i = 0; i < child_widgets.size(); ++i) { - Widget* child_widget = child_widgets[i]; - IAccessible* child_accessible = - child_widget->GetRootView()->GetNativeViewAccessible(); - HRESULT result = child_accessible->accHitTest(x_left, y_top, child); - if (result == S_OK) - return result; - } - } - - gfx::Point point(x_left, y_top); - View::ConvertPointFromScreen(view_, &point); - - // If the point is not inside this view, return false. - if (!view_->HitTestPoint(point)) { - child->vt = VT_EMPTY; - return S_FALSE; - } - - // Check if the point is within any of the immediate children of this - // view. - View* hit_child_view = NULL; - for (int i = view_->child_count() - 1; i >= 0; --i) { - View* child_view = view_->child_at(i); - if (!child_view->visible()) - continue; - - gfx::Point point_in_child_coords(point); - view_->ConvertPointToTarget(view_, child_view, &point_in_child_coords); - if (child_view->HitTestPoint(point_in_child_coords)) { - hit_child_view = child_view; - break; - } - } - - // If the point was within one of this view's immediate children, - // call accHitTest recursively on that child's native view accessible - - // which may be a recursive call to this function or it may be overridden, - // for example in the case of a WebView. - if (hit_child_view) { - HRESULT result = hit_child_view->GetNativeViewAccessible()->accHitTest( - x_left, y_top, child); - - // If the recursive call returned CHILDID_SELF, we have to convert that - // into a VT_DISPATCH for the return value to this call. - if (S_OK == result && child->vt == VT_I4 && child->lVal == CHILDID_SELF) { - child->vt = VT_DISPATCH; - child->pdispVal = hit_child_view->GetNativeViewAccessible(); - // Always increment ref when returning a reference to a COM object. - child->pdispVal->AddRef(); - } - return result; - } - - // This object is the best match, so return CHILDID_SELF. It's tempting to - // simplify the logic and use VT_DISPATCH everywhere, but the Windows - // call AccessibleObjectFromPoint will keep calling accHitTest until some - // object returns CHILDID_SELF. - child->vt = VT_I4; - child->lVal = CHILDID_SELF; - return S_OK; -} - -HRESULT NativeViewAccessibilityWin::accDoDefaultAction(VARIANT var_id) { - if (!IsValidId(var_id)) - return E_INVALIDARG; - - // The object does not support the method. This value is returned for - // controls that do not perform actions, such as edit fields. - return DISP_E_MEMBERNOTFOUND; -} - -STDMETHODIMP NativeViewAccessibilityWin::accLocation( - LONG* x_left, LONG* y_top, LONG* width, LONG* height, VARIANT var_id) { - if (!IsValidId(var_id) || !x_left || !y_top || !width || !height) - return E_INVALIDARG; - - if (!view_) - return E_FAIL; - - if (!view_->bounds().IsEmpty()) { - *width = view_->width(); - *height = view_->height(); - gfx::Point topleft(view_->bounds().origin()); - View::ConvertPointToScreen( - view_->parent() ? view_->parent() : view_, &topleft); - *x_left = topleft.x(); - *y_top = topleft.y(); - } else { - return E_FAIL; - } - return S_OK; -} - -STDMETHODIMP NativeViewAccessibilityWin::accNavigate( - LONG nav_dir, VARIANT start, VARIANT* end) { - if (start.vt != VT_I4 || !end) - return E_INVALIDARG; - - if (!view_) - return E_FAIL; - - switch (nav_dir) { - case NAVDIR_FIRSTCHILD: - case NAVDIR_LASTCHILD: { - if (start.lVal != CHILDID_SELF) { - // Start of navigation must be on the View itself. - return E_INVALIDARG; - } else if (!view_->has_children()) { - // No children found. - return S_FALSE; - } - - // Set child_id based on first or last child. - int child_id = 0; - if (nav_dir == NAVDIR_LASTCHILD) - child_id = view_->child_count() - 1; - - View* child = view_->child_at(child_id); - end->vt = VT_DISPATCH; - end->pdispVal = child->GetNativeViewAccessible(); - end->pdispVal->AddRef(); - return S_OK; - } - case NAVDIR_LEFT: - case NAVDIR_UP: - case NAVDIR_PREVIOUS: - case NAVDIR_RIGHT: - case NAVDIR_DOWN: - case NAVDIR_NEXT: { - // Retrieve parent to access view index and perform bounds checking. - View* parent = view_->parent(); - if (!parent) { - return E_FAIL; - } - - if (start.lVal == CHILDID_SELF) { - int view_index = parent->GetIndexOf(view_); - // Check navigation bounds, adjusting for View child indexing (MSAA - // child indexing starts with 1, whereas View indexing starts with 0). - if (!IsValidNav(nav_dir, view_index, -1, - parent->child_count() - 1)) { - // Navigation attempted to go out-of-bounds. - end->vt = VT_EMPTY; - return S_FALSE; - } else { - if (IsNavDirNext(nav_dir)) { - view_index += 1; - } else { - view_index -=1; - } - } - - View* child = parent->child_at(view_index); - end->pdispVal = child->GetNativeViewAccessible(); - end->vt = VT_DISPATCH; - end->pdispVal->AddRef(); - return S_OK; - } else { - // Check navigation bounds, adjusting for MSAA child indexing (MSAA - // child indexing starts with 1, whereas View indexing starts with 0). - if (!IsValidNav(nav_dir, start.lVal, 0, parent->child_count() + 1)) { - // Navigation attempted to go out-of-bounds. - end->vt = VT_EMPTY; - return S_FALSE; - } else { - if (IsNavDirNext(nav_dir)) { - start.lVal += 1; - } else { - start.lVal -= 1; - } - } - - HRESULT result = this->get_accChild(start, &end->pdispVal); - if (result == S_FALSE) { - // Child is a leaf. - end->vt = VT_I4; - end->lVal = start.lVal; - } else if (result == E_INVALIDARG) { - return E_INVALIDARG; - } else { - // Child is not a leaf. - end->vt = VT_DISPATCH; - } - } - break; - } - default: - return E_INVALIDARG; - } - // Navigation performed correctly. Global return for this function, if no - // error triggered an escape earlier. - return S_OK; -} - -STDMETHODIMP NativeViewAccessibilityWin::get_accChild(VARIANT var_child, - IDispatch** disp_child) { - if (var_child.vt != VT_I4 || !disp_child) - return E_INVALIDARG; - - if (!view_ || !view_->GetWidget()) - return E_FAIL; - - LONG child_id = V_I4(&var_child); - - if (child_id == CHILDID_SELF) { - // Remain with the same dispatch. - return S_OK; - } - - // If this is a root view, our widget might have child widgets. Include - std::vector<Widget*> child_widgets; - if (view_->GetWidget()->GetRootView() == view_) - PopulateChildWidgetVector(&child_widgets); - int child_widget_count = static_cast<int>(child_widgets.size()); - - View* child_view = NULL; - if (child_id > 0) { - // Positive child ids are a 1-based child index, used by clients - // that want to enumerate all immediate children. - int child_id_as_index = child_id - 1; - if (child_id_as_index < view_->child_count()) { - child_view = view_->child_at(child_id_as_index); - } else if (child_id_as_index < view_->child_count() + child_widget_count) { - Widget* child_widget = - child_widgets[child_id_as_index - view_->child_count()]; - child_view = child_widget->GetRootView(); - } - } else { - // Negative child ids can be used to map to any descendant. - // Check child widget first. - for (int i = 0; i < child_widget_count; i++) { - Widget* child_widget = child_widgets[i]; - IAccessible* child_accessible = - child_widget->GetRootView()->GetNativeViewAccessible(); - HRESULT result = child_accessible->get_accChild(var_child, disp_child); - if (result == S_OK) - return result; - } - - // We map child ids to a view storage id that can refer to a - // specific view (if that view still exists). - int view_storage_id_index = - base::win::kFirstViewsAccessibilityId - child_id; - if (view_storage_id_index >= 0 && - view_storage_id_index < kMaxViewStorageIds) { - int view_storage_id = view_storage_ids_[view_storage_id_index]; - ViewStorage* view_storage = ViewStorage::GetInstance(); - child_view = view_storage->RetrieveView(view_storage_id); - } else { - *disp_child = AccessibleWebViewRegistry::GetInstance()-> - GetAccessibleFromWebView(view_, child_id); - if (*disp_child) - return S_OK; - } - } - - if (!child_view) { - // No child found. - *disp_child = NULL; - return E_FAIL; - } - - *disp_child = child_view->GetNativeViewAccessible(); - if (*disp_child) { - (*disp_child)->AddRef(); - return S_OK; - } - - return E_FAIL; -} - -STDMETHODIMP NativeViewAccessibilityWin::get_accChildCount(LONG* child_count) { - if (!child_count) - return E_INVALIDARG; - - if (!view_ || !view_->GetWidget()) - return E_FAIL; - - *child_count = view_->child_count(); - - // If this is a root view, our widget might have child widgets. Include - // them, too. - if (view_->GetWidget()->GetRootView() == view_) { - std::vector<Widget*> child_widgets; - PopulateChildWidgetVector(&child_widgets); - *child_count += child_widgets.size(); - } - - return S_OK; -} - -STDMETHODIMP NativeViewAccessibilityWin::get_accDefaultAction( - VARIANT var_id, BSTR* def_action) { - if (!IsValidId(var_id) || !def_action) - return E_INVALIDARG; - - if (!view_) - return E_FAIL; - - ui::AXViewState state; - view_->GetAccessibleState(&state); - base::string16 temp_action = state.default_action; - - if (!temp_action.empty()) { - *def_action = SysAllocString(temp_action.c_str()); - } else { - return S_FALSE; - } - - return S_OK; -} - -STDMETHODIMP NativeViewAccessibilityWin::get_accDescription( - VARIANT var_id, BSTR* desc) { - if (!IsValidId(var_id) || !desc) - return E_INVALIDARG; - - if (!view_) - return E_FAIL; - - base::string16 temp_desc; - - view_->GetTooltipText(gfx::Point(), &temp_desc); - if (!temp_desc.empty()) { - *desc = SysAllocString(temp_desc.c_str()); - } else { - return S_FALSE; - } - - return S_OK; -} - -STDMETHODIMP NativeViewAccessibilityWin::get_accFocus(VARIANT* focus_child) { - if (!focus_child) - return E_INVALIDARG; - - if (!view_) - return E_FAIL; - - FocusManager* focus_manager = view_->GetFocusManager(); - View* focus = focus_manager ? focus_manager->GetFocusedView() : NULL; - if (focus == view_) { - // This view has focus. - focus_child->vt = VT_I4; - focus_child->lVal = CHILDID_SELF; - } else if (focus && view_->Contains(focus)) { - // Return the child object that has the keyboard focus. - focus_child->vt = VT_DISPATCH; - focus_child->pdispVal = focus->GetNativeViewAccessible(); - focus_child->pdispVal->AddRef(); - return S_OK; - } else { - // Neither this object nor any of its children has the keyboard focus. - focus_child->vt = VT_EMPTY; - } - return S_OK; -} - -STDMETHODIMP NativeViewAccessibilityWin::get_accKeyboardShortcut( - VARIANT var_id, BSTR* acc_key) { - if (!IsValidId(var_id) || !acc_key) - return E_INVALIDARG; - - if (!view_) - return E_FAIL; - - ui::AXViewState state; - view_->GetAccessibleState(&state); - base::string16 temp_key = state.keyboard_shortcut; - - if (!temp_key.empty()) { - *acc_key = SysAllocString(temp_key.c_str()); - } else { - return S_FALSE; - } - - return S_OK; -} - -STDMETHODIMP NativeViewAccessibilityWin::get_accName( - VARIANT var_id, BSTR* name) { - if (!IsValidId(var_id) || !name) - return E_INVALIDARG; - - if (!view_) - return E_FAIL; - - // Retrieve the current view's name. - ui::AXViewState state; - view_->GetAccessibleState(&state); - base::string16 temp_name = state.name; - if (!temp_name.empty()) { - // Return name retrieved. - *name = SysAllocString(temp_name.c_str()); - } else { - // If view has no name, return S_FALSE. - return S_FALSE; - } - - return S_OK; -} - -STDMETHODIMP NativeViewAccessibilityWin::get_accParent( - IDispatch** disp_parent) { - if (!disp_parent) - return E_INVALIDARG; - - if (!view_) - return E_FAIL; - - *disp_parent = NULL; - View* parent_view = view_->parent(); - - if (!parent_view) { - HWND hwnd = HWNDForView(view_); - if (!hwnd) - return S_FALSE; - - return ::AccessibleObjectFromWindow( - hwnd, OBJID_WINDOW, IID_IAccessible, - reinterpret_cast<void**>(disp_parent)); - } - - *disp_parent = parent_view->GetNativeViewAccessible(); - (*disp_parent)->AddRef(); - return S_OK; -} - -STDMETHODIMP NativeViewAccessibilityWin::get_accRole( - VARIANT var_id, VARIANT* role) { - if (!IsValidId(var_id) || !role) - return E_INVALIDARG; - - if (!view_) - return E_FAIL; - - ui::AXViewState state; - view_->GetAccessibleState(&state); - role->vt = VT_I4; - role->lVal = MSAARole(state.role); - return S_OK; -} - -STDMETHODIMP NativeViewAccessibilityWin::get_accState( - VARIANT var_id, VARIANT* state) { - // This returns MSAA states. See also the IAccessible2 interface - // get_states(). - - if (!IsValidId(var_id) || !state) - return E_INVALIDARG; - - if (!view_) - return E_FAIL; - - state->vt = VT_I4; - - // Retrieve all currently applicable states of the parent. - SetState(state, view_); - - // Make sure that state is not empty, and has the proper type. - if (state->vt == VT_EMPTY) - return E_FAIL; - - return S_OK; -} - -STDMETHODIMP NativeViewAccessibilityWin::get_accValue(VARIANT var_id, - BSTR* value) { - if (!IsValidId(var_id) || !value) - return E_INVALIDARG; - - if (!view_) - return E_FAIL; - - // Retrieve the current view's value. - ui::AXViewState state; - view_->GetAccessibleState(&state); - base::string16 temp_value = state.value; - - if (!temp_value.empty()) { - // Return value retrieved. - *value = SysAllocString(temp_value.c_str()); - } else { - // If view has no value, fall back into the default implementation. - *value = NULL; - return E_NOTIMPL; - } - - return S_OK; -} - -STDMETHODIMP NativeViewAccessibilityWin::put_accValue(VARIANT var_id, - BSTR new_value) { - if (!IsValidId(var_id) || !new_value) - return E_INVALIDARG; - - if (!view_) - return E_FAIL; - - // Return an error if the view can't set the value. - ui::AXViewState state; - view_->GetAccessibleState(&state); - if (state.set_value_callback.is_null()) - return E_FAIL; - - state.set_value_callback.Run(new_value); - return S_OK; -} - -// IAccessible functions not supported. - -STDMETHODIMP NativeViewAccessibilityWin::get_accSelection(VARIANT* selected) { - if (selected) - selected->vt = VT_EMPTY; - return E_NOTIMPL; -} - -STDMETHODIMP NativeViewAccessibilityWin::accSelect( - LONG flagsSelect, VARIANT var_id) { - return E_NOTIMPL; -} - -STDMETHODIMP NativeViewAccessibilityWin::get_accHelp( - VARIANT var_id, BSTR* help) { - base::string16 temp = base::UTF8ToUTF16(view_->GetClassName()); - *help = SysAllocString(temp.c_str()); - return S_OK; -} - -STDMETHODIMP NativeViewAccessibilityWin::get_accHelpTopic( - BSTR* help_file, VARIANT var_id, LONG* topic_id) { - if (help_file) { - *help_file = NULL; - } - if (topic_id) { - *topic_id = static_cast<LONG>(-1); - } - return E_NOTIMPL; -} - -STDMETHODIMP NativeViewAccessibilityWin::put_accName( - VARIANT var_id, BSTR put_name) { - // Deprecated. - return E_NOTIMPL; -} - -// -// IAccessible2 -// - -STDMETHODIMP NativeViewAccessibilityWin::role(LONG* role) { - if (!view_) - return E_FAIL; - - if (!role) - return E_INVALIDARG; - - ui::AXViewState state; - view_->GetAccessibleState(&state); - *role = MSAARole(state.role); - return S_OK; -} - -STDMETHODIMP NativeViewAccessibilityWin::get_states(AccessibleStates* states) { - // This returns IAccessible2 states, which supplement MSAA states. - // See also the MSAA interface get_accState. - - if (!view_) - return E_FAIL; - - if (!states) - return E_INVALIDARG; - - ui::AXViewState state; - view_->GetAccessibleState(&state); - - // There are only a couple of states we need to support - // in IAccessible2. If any more are added, we may want to - // add a helper function like MSAAState. - *states = IA2_STATE_OPAQUE; - if (state.HasStateFlag(ui::AX_STATE_EDITABLE)) - *states |= IA2_STATE_EDITABLE; - - return S_OK; -} - -STDMETHODIMP NativeViewAccessibilityWin::get_uniqueID(LONG* unique_id) { - if (!view_) - return E_FAIL; - - if (!unique_id) - return E_INVALIDARG; - - *unique_id = unique_id_; - return S_OK; -} - -STDMETHODIMP NativeViewAccessibilityWin::get_windowHandle(HWND* window_handle) { - if (!view_) - return E_FAIL; - - if (!window_handle) - return E_INVALIDARG; - - *window_handle = HWNDForView(view_); - return *window_handle ? S_OK : S_FALSE; -} - -STDMETHODIMP NativeViewAccessibilityWin::get_relationTargetsOfType( - BSTR type_bstr, - long max_targets, - IUnknown ***targets, - long *n_targets) { - if (!view_) - return E_FAIL; - - if (!targets || !n_targets) - return E_INVALIDARG; - - *n_targets = 0; - *targets = NULL; - - // Only respond to requests for relations of type "alerts" on the - // root view. - base::string16 type(type_bstr); - if (type != L"alerts" || view_->parent()) - return S_FALSE; - - // Collect all of the alert views that are still valid. - std::vector<View*> alert_views; - ViewStorage* view_storage = ViewStorage::GetInstance(); - for (size_t i = 0; i < alert_target_view_storage_ids_.size(); ++i) { - int view_storage_id = alert_target_view_storage_ids_[i]; - View* view = view_storage->RetrieveView(view_storage_id); - if (!view || !view_->Contains(view)) - continue; - alert_views.push_back(view); - } - - long count = alert_views.size(); - if (count == 0) - return S_FALSE; - - // Don't return more targets than max_targets - but note that the caller - // is allowed to specify max_targets=0 to mean no limit. - if (max_targets > 0 && count > max_targets) - count = max_targets; - - // Return the number of targets. - *n_targets = count; - - // Allocate COM memory for the result array and populate it. - *targets = static_cast<IUnknown**>( - CoTaskMemAlloc(count * sizeof(IUnknown*))); - for (long i = 0; i < count; ++i) { - (*targets)[i] = alert_views[i]->GetNativeViewAccessible(); - (*targets)[i]->AddRef(); - } - return S_OK; -} - -STDMETHODIMP NativeViewAccessibilityWin::get_attributes(BSTR* attributes) { - if (!view_) - return E_FAIL; - - if (!attributes) - return E_INVALIDARG; - - base::string16 attributes_str; - - // Text fields need to report the attribute "text-model:a1" to instruct - // screen readers to use IAccessible2 APIs to handle text editing in this - // object (as opposed to treating it like a native Windows text box). - // The text-model:a1 attribute is documented here: - // http://www.linuxfoundation.org/collaborate/workgroups/accessibility/ia2/ia2_implementation_guide - ui::AXViewState state; - view_->GetAccessibleState(&state); - if (state.role == ui::AX_ROLE_TEXT_FIELD) { - attributes_str = L"text-model:a1;"; - } - - *attributes = SysAllocString(attributes_str.c_str()); - DCHECK(*attributes); - return S_OK; -} - -// -// IAccessibleText -// - -STDMETHODIMP NativeViewAccessibilityWin::get_nCharacters(LONG* n_characters) { - if (!view_) - return E_FAIL; - - if (!n_characters) - return E_INVALIDARG; - - base::string16 text = TextForIAccessibleText(); - *n_characters = static_cast<LONG>(text.size()); - return S_OK; -} - -STDMETHODIMP NativeViewAccessibilityWin::get_caretOffset(LONG* offset) { - if (!view_) - return E_FAIL; - - if (!offset) - return E_INVALIDARG; - - ui::AXViewState state; - view_->GetAccessibleState(&state); - *offset = static_cast<LONG>(state.selection_end); - return S_OK; -} - -STDMETHODIMP NativeViewAccessibilityWin::get_nSelections(LONG* n_selections) { - if (!view_) - return E_FAIL; - - if (!n_selections) - return E_INVALIDARG; - - ui::AXViewState state; - view_->GetAccessibleState(&state); - if (state.selection_start != state.selection_end) - *n_selections = 1; - else - *n_selections = 0; - return S_OK; -} - -STDMETHODIMP NativeViewAccessibilityWin::get_selection(LONG selection_index, - LONG* start_offset, - LONG* end_offset) { - if (!view_) - return E_FAIL; - - if (!start_offset || !end_offset || selection_index != 0) - return E_INVALIDARG; - - ui::AXViewState state; - view_->GetAccessibleState(&state); - *start_offset = static_cast<LONG>(state.selection_start); - *end_offset = static_cast<LONG>(state.selection_end); - return S_OK; -} - -STDMETHODIMP NativeViewAccessibilityWin::get_text(LONG start_offset, - LONG end_offset, - BSTR* text) { - if (!view_) - return E_FAIL; - - ui::AXViewState state; - view_->GetAccessibleState(&state); - base::string16 text_str = TextForIAccessibleText(); - LONG len = static_cast<LONG>(text_str.size()); - - if (start_offset == IA2_TEXT_OFFSET_LENGTH) { - start_offset = len; - } else if (start_offset == IA2_TEXT_OFFSET_CARET) { - start_offset = static_cast<LONG>(state.selection_end); - } - if (end_offset == IA2_TEXT_OFFSET_LENGTH) { - end_offset = static_cast<LONG>(text_str.size()); - } else if (end_offset == IA2_TEXT_OFFSET_CARET) { - end_offset = static_cast<LONG>(state.selection_end); - } - - // The spec allows the arguments to be reversed. - if (start_offset > end_offset) { - LONG tmp = start_offset; - start_offset = end_offset; - end_offset = tmp; - } - - // The spec does not allow the start or end offsets to be out or range; - // we must return an error if so. - if (start_offset < 0) - return E_INVALIDARG; - if (end_offset > len) - return E_INVALIDARG; - - base::string16 substr = - text_str.substr(start_offset, end_offset - start_offset); - if (substr.empty()) - return S_FALSE; - - *text = SysAllocString(substr.c_str()); - DCHECK(*text); - return S_OK; -} - -STDMETHODIMP NativeViewAccessibilityWin::get_textAtOffset( - LONG offset, - enum IA2TextBoundaryType boundary_type, - LONG* start_offset, LONG* end_offset, - BSTR* text) { - if (!start_offset || !end_offset || !text) - return E_INVALIDARG; - - // The IAccessible2 spec says we don't have to implement the "sentence" - // boundary type, we can just let the screenreader handle it. - if (boundary_type == IA2_TEXT_BOUNDARY_SENTENCE) { - *start_offset = 0; - *end_offset = 0; - *text = NULL; - return S_FALSE; - } - - const base::string16& text_str = TextForIAccessibleText(); - - *start_offset = FindBoundary( - text_str, boundary_type, offset, ui::BACKWARDS_DIRECTION); - *end_offset = FindBoundary( - text_str, boundary_type, offset, ui::FORWARDS_DIRECTION); - return get_text(*start_offset, *end_offset, text); -} - -STDMETHODIMP NativeViewAccessibilityWin::get_textBeforeOffset( - LONG offset, - enum IA2TextBoundaryType boundary_type, - LONG* start_offset, LONG* end_offset, - BSTR* text) { - if (!start_offset || !end_offset || !text) - return E_INVALIDARG; - - // The IAccessible2 spec says we don't have to implement the "sentence" - // boundary type, we can just let the screenreader handle it. - if (boundary_type == IA2_TEXT_BOUNDARY_SENTENCE) { - *start_offset = 0; - *end_offset = 0; - *text = NULL; - return S_FALSE; - } - - const base::string16& text_str = TextForIAccessibleText(); - - *start_offset = FindBoundary( - text_str, boundary_type, offset, ui::BACKWARDS_DIRECTION); - *end_offset = offset; - return get_text(*start_offset, *end_offset, text); -} - -STDMETHODIMP NativeViewAccessibilityWin::get_textAfterOffset( - LONG offset, - enum IA2TextBoundaryType boundary_type, - LONG* start_offset, LONG* end_offset, - BSTR* text) { - if (!start_offset || !end_offset || !text) - return E_INVALIDARG; - - // The IAccessible2 spec says we don't have to implement the "sentence" - // boundary type, we can just let the screenreader handle it. - if (boundary_type == IA2_TEXT_BOUNDARY_SENTENCE) { - *start_offset = 0; - *end_offset = 0; - *text = NULL; - return S_FALSE; - } - - const base::string16& text_str = TextForIAccessibleText(); - - *start_offset = offset; - *end_offset = FindBoundary( - text_str, boundary_type, offset, ui::FORWARDS_DIRECTION); - return get_text(*start_offset, *end_offset, text); -} - -STDMETHODIMP NativeViewAccessibilityWin::get_offsetAtPoint( - LONG x, LONG y, enum IA2CoordinateType coord_type, LONG* offset) { - if (!view_) - return E_FAIL; - - if (!offset) - return E_INVALIDARG; - - // We don't support this method, but we have to return something - // rather than E_NOTIMPL or screen readers will complain. - *offset = 0; - return S_OK; -} - -// -// IServiceProvider methods. -// - -STDMETHODIMP NativeViewAccessibilityWin::QueryService( - REFGUID guidService, REFIID riid, void** object) { - if (!view_) - return E_FAIL; - - if (riid == IID_IAccessible2 || riid == IID_IAccessible2_2) - AccessibleWebViewRegistry::GetInstance()->EnableIAccessible2Support(); - - if (guidService == IID_IAccessible || - guidService == IID_IAccessible2 || - guidService == IID_IAccessible2_2 || - guidService == IID_IAccessibleText) { - return QueryInterface(riid, object); - } - - // We only support the IAccessibleEx interface on Windows 8 and above. This - // is needed for the On screen Keyboard to show up in metro mode, when the - // user taps an editable region in the window. - // All methods in the IAccessibleEx interface are unimplemented. - if (riid == IID_IAccessibleEx && - base::win::GetVersion() >= base::win::VERSION_WIN8) { - return QueryInterface(riid, object); - } - - *object = NULL; - return E_FAIL; -} - -STDMETHODIMP NativeViewAccessibilityWin::GetPatternProvider( - PATTERNID id, IUnknown** provider) { - DVLOG(1) << "In Function: " - << __FUNCTION__ - << " for pattern id: " - << id; - if (id == UIA_ValuePatternId || id == UIA_TextPatternId) { - ui::AXViewState state; - view_->GetAccessibleState(&state); - long role = MSAARole(state.role); - - if (role == ROLE_SYSTEM_TEXT) { - DVLOG(1) << "Returning UIA text provider"; - base::win::UIATextProvider::CreateTextProvider( - state.value, true, provider); - return S_OK; - } - } - return E_NOTIMPL; -} - -STDMETHODIMP NativeViewAccessibilityWin::GetPropertyValue(PROPERTYID id, - VARIANT* ret) { - DVLOG(1) << "In Function: " - << __FUNCTION__ - << " for property id: " - << id; - if (id == UIA_ControlTypePropertyId) { - ui::AXViewState state; - view_->GetAccessibleState(&state); - long role = MSAARole(state.role); - if (role == ROLE_SYSTEM_TEXT) { - V_VT(ret) = VT_I4; - ret->lVal = UIA_EditControlTypeId; - DVLOG(1) << "Returning Edit control type"; - } else { - DVLOG(1) << "Returning empty control type"; - V_VT(ret) = VT_EMPTY; - } - } else { - V_VT(ret) = VT_EMPTY; - } - return S_OK; -} - -// -// Static methods. -// - -void NativeViewAccessibility::RegisterWebView(View* web_view) { - AccessibleWebViewRegistry::GetInstance()->RegisterWebView(web_view); -} - -void NativeViewAccessibility::UnregisterWebView(View* web_view) { - AccessibleWebViewRegistry::GetInstance()->UnregisterWebView(web_view); -} - -int32 NativeViewAccessibilityWin::MSAAEvent(ui::AXEvent event) { - switch (event) { - case ui::AX_EVENT_ALERT: - return EVENT_SYSTEM_ALERT; - case ui::AX_EVENT_FOCUS: - return EVENT_OBJECT_FOCUS; - case ui::AX_EVENT_MENU_START: - return EVENT_SYSTEM_MENUSTART; - case ui::AX_EVENT_MENU_END: - return EVENT_SYSTEM_MENUEND; - case ui::AX_EVENT_MENU_POPUP_START: - return EVENT_SYSTEM_MENUPOPUPSTART; - case ui::AX_EVENT_MENU_POPUP_END: - return EVENT_SYSTEM_MENUPOPUPEND; - case ui::AX_EVENT_SELECTION: - return EVENT_OBJECT_SELECTION; - case ui::AX_EVENT_SELECTION_ADD: - return EVENT_OBJECT_SELECTIONADD; - case ui::AX_EVENT_SELECTION_REMOVE: - return EVENT_OBJECT_SELECTIONREMOVE; - case ui::AX_EVENT_TEXT_CHANGED: - return EVENT_OBJECT_NAMECHANGE; - case ui::AX_EVENT_TEXT_SELECTION_CHANGED: - return IA2_EVENT_TEXT_CARET_MOVED; - case ui::AX_EVENT_VALUE_CHANGED: - return EVENT_OBJECT_VALUECHANGE; - default: - // Not supported or invalid event. - NOTREACHED(); - return -1; - } -} - -int32 NativeViewAccessibilityWin::MSAARole(ui::AXRole role) { - switch (role) { - case ui::AX_ROLE_ALERT: - return ROLE_SYSTEM_ALERT; - case ui::AX_ROLE_APPLICATION: - return ROLE_SYSTEM_APPLICATION; - case ui::AX_ROLE_BUTTON_DROP_DOWN: - return ROLE_SYSTEM_BUTTONDROPDOWN; - case ui::AX_ROLE_POP_UP_BUTTON: - return ROLE_SYSTEM_BUTTONMENU; - case ui::AX_ROLE_CHECK_BOX: - return ROLE_SYSTEM_CHECKBUTTON; - case ui::AX_ROLE_COMBO_BOX: - return ROLE_SYSTEM_COMBOBOX; - case ui::AX_ROLE_DIALOG: - return ROLE_SYSTEM_DIALOG; - case ui::AX_ROLE_GROUP: - return ROLE_SYSTEM_GROUPING; - case ui::AX_ROLE_IMAGE: - return ROLE_SYSTEM_GRAPHIC; - case ui::AX_ROLE_LINK: - return ROLE_SYSTEM_LINK; - case ui::AX_ROLE_LOCATION_BAR: - return ROLE_SYSTEM_GROUPING; - case ui::AX_ROLE_MENU_BAR: - return ROLE_SYSTEM_MENUBAR; - case ui::AX_ROLE_MENU_ITEM: - return ROLE_SYSTEM_MENUITEM; - case ui::AX_ROLE_MENU_LIST_POPUP: - return ROLE_SYSTEM_MENUPOPUP; - case ui::AX_ROLE_TREE: - return ROLE_SYSTEM_OUTLINE; - case ui::AX_ROLE_TREE_ITEM: - return ROLE_SYSTEM_OUTLINEITEM; - case ui::AX_ROLE_TAB: - return ROLE_SYSTEM_PAGETAB; - case ui::AX_ROLE_TAB_LIST: - return ROLE_SYSTEM_PAGETABLIST; - case ui::AX_ROLE_PANE: - return ROLE_SYSTEM_PANE; - case ui::AX_ROLE_PROGRESS_INDICATOR: - return ROLE_SYSTEM_PROGRESSBAR; - case ui::AX_ROLE_BUTTON: - return ROLE_SYSTEM_PUSHBUTTON; - case ui::AX_ROLE_RADIO_BUTTON: - return ROLE_SYSTEM_RADIOBUTTON; - case ui::AX_ROLE_SCROLL_BAR: - return ROLE_SYSTEM_SCROLLBAR; - case ui::AX_ROLE_SPLITTER: - return ROLE_SYSTEM_SEPARATOR; - case ui::AX_ROLE_SLIDER: - return ROLE_SYSTEM_SLIDER; - case ui::AX_ROLE_STATIC_TEXT: - return ROLE_SYSTEM_STATICTEXT; - case ui::AX_ROLE_TEXT_FIELD: - return ROLE_SYSTEM_TEXT; - case ui::AX_ROLE_TITLE_BAR: - return ROLE_SYSTEM_TITLEBAR; - case ui::AX_ROLE_TOOLBAR: - return ROLE_SYSTEM_TOOLBAR; - case ui::AX_ROLE_WINDOW: - return ROLE_SYSTEM_WINDOW; - case ui::AX_ROLE_CLIENT: - default: - // This is the default role for MSAA. - return ROLE_SYSTEM_CLIENT; - } -} - -int32 NativeViewAccessibilityWin::MSAAState(const ui::AXViewState& state) { - // This maps MSAA states for get_accState(). See also the IAccessible2 - // interface get_states(). - - int32 msaa_state = 0; - if (state.HasStateFlag(ui::AX_STATE_CHECKED)) - msaa_state |= STATE_SYSTEM_CHECKED; - if (state.HasStateFlag(ui::AX_STATE_COLLAPSED)) - msaa_state |= STATE_SYSTEM_COLLAPSED; - if (state.HasStateFlag(ui::AX_STATE_DEFAULT)) - msaa_state |= STATE_SYSTEM_DEFAULT; - if (state.HasStateFlag(ui::AX_STATE_EXPANDED)) - msaa_state |= STATE_SYSTEM_EXPANDED; - if (state.HasStateFlag(ui::AX_STATE_HASPOPUP)) - msaa_state |= STATE_SYSTEM_HASPOPUP; - if (state.HasStateFlag(ui::AX_STATE_HOVERED)) - msaa_state |= STATE_SYSTEM_HOTTRACKED; - if (state.HasStateFlag(ui::AX_STATE_INVISIBLE)) - msaa_state |= STATE_SYSTEM_INVISIBLE; - if (state.HasStateFlag(ui::AX_STATE_LINKED)) - msaa_state |= STATE_SYSTEM_LINKED; - if (state.HasStateFlag(ui::AX_STATE_OFFSCREEN)) - msaa_state |= STATE_SYSTEM_OFFSCREEN; - if (state.HasStateFlag(ui::AX_STATE_PRESSED)) - msaa_state |= STATE_SYSTEM_PRESSED; - if (state.HasStateFlag(ui::AX_STATE_PROTECTED)) - msaa_state |= STATE_SYSTEM_PROTECTED; - if (state.HasStateFlag(ui::AX_STATE_READ_ONLY)) - msaa_state |= STATE_SYSTEM_READONLY; - if (state.HasStateFlag(ui::AX_STATE_SELECTABLE)) - msaa_state |= STATE_SYSTEM_SELECTABLE; - if (state.HasStateFlag(ui::AX_STATE_SELECTED)) - msaa_state |= STATE_SYSTEM_SELECTED; - if (state.HasStateFlag(ui::AX_STATE_FOCUSED)) - msaa_state |= STATE_SYSTEM_FOCUSED; - if (state.HasStateFlag(ui::AX_STATE_DISABLED)) - msaa_state |= STATE_SYSTEM_UNAVAILABLE; - return msaa_state; -} - -// -// Private methods. -// - -bool NativeViewAccessibilityWin::IsNavDirNext(int nav_dir) const { - return (nav_dir == NAVDIR_RIGHT || - nav_dir == NAVDIR_DOWN || - nav_dir == NAVDIR_NEXT); -} - -bool NativeViewAccessibilityWin::IsValidNav( - int nav_dir, int start_id, int lower_bound, int upper_bound) const { - if (IsNavDirNext(nav_dir)) { - if ((start_id + 1) > upper_bound) { - return false; - } - } else { - if ((start_id - 1) <= lower_bound) { - return false; - } - } - return true; -} - -bool NativeViewAccessibilityWin::IsValidId(const VARIANT& child) const { - // View accessibility returns an IAccessible for each view so we only support - // the CHILDID_SELF id. - return (VT_I4 == child.vt) && (CHILDID_SELF == child.lVal); -} - -void NativeViewAccessibilityWin::SetState( - VARIANT* msaa_state, View* view) { - // Ensure the output param is initialized to zero. - msaa_state->lVal = 0; - - // Default state; all views can have accessibility focus. - msaa_state->lVal |= STATE_SYSTEM_FOCUSABLE; - - if (!view) - return; - - if (!view->enabled()) - msaa_state->lVal |= STATE_SYSTEM_UNAVAILABLE; - if (!view->visible()) - msaa_state->lVal |= STATE_SYSTEM_INVISIBLE; - if (!strcmp(view->GetClassName(), CustomButton::kViewClassName)) { - CustomButton* button = static_cast<CustomButton*>(view); - if (button->IsHotTracked()) - msaa_state->lVal |= STATE_SYSTEM_HOTTRACKED; - } - if (view->HasFocus()) - msaa_state->lVal |= STATE_SYSTEM_FOCUSED; - - // Add on any view-specific states. - ui::AXViewState view_state; - view->GetAccessibleState(&view_state); - msaa_state->lVal |= MSAAState(view_state); -} - -base::string16 NativeViewAccessibilityWin::TextForIAccessibleText() { - ui::AXViewState state; - view_->GetAccessibleState(&state); - if (state.role == ui::AX_ROLE_TEXT_FIELD) - return state.value; - else - return state.name; -} - -void NativeViewAccessibilityWin::HandleSpecialTextOffset( - const base::string16& text, LONG* offset) { - if (*offset == IA2_TEXT_OFFSET_LENGTH) { - *offset = static_cast<LONG>(text.size()); - } else if (*offset == IA2_TEXT_OFFSET_CARET) { - get_caretOffset(offset); - } -} - -ui::TextBoundaryType NativeViewAccessibilityWin::IA2TextBoundaryToTextBoundary( - IA2TextBoundaryType ia2_boundary) { - switch(ia2_boundary) { - case IA2_TEXT_BOUNDARY_CHAR: return ui::CHAR_BOUNDARY; - case IA2_TEXT_BOUNDARY_WORD: return ui::WORD_BOUNDARY; - case IA2_TEXT_BOUNDARY_LINE: return ui::LINE_BOUNDARY; - case IA2_TEXT_BOUNDARY_SENTENCE: return ui::SENTENCE_BOUNDARY; - case IA2_TEXT_BOUNDARY_PARAGRAPH: return ui::PARAGRAPH_BOUNDARY; - case IA2_TEXT_BOUNDARY_ALL: return ui::ALL_BOUNDARY; - default: - NOTREACHED(); - return ui::CHAR_BOUNDARY; - } -} - -LONG NativeViewAccessibilityWin::FindBoundary( - const base::string16& text, - IA2TextBoundaryType ia2_boundary, - LONG start_offset, - ui::TextBoundaryDirection direction) { - HandleSpecialTextOffset(text, &start_offset); - ui::TextBoundaryType boundary = IA2TextBoundaryToTextBoundary(ia2_boundary); - std::vector<int32> line_breaks; - return ui::FindAccessibleTextBoundary( - text, line_breaks, boundary, start_offset, direction); -} - -void NativeViewAccessibilityWin::PopulateChildWidgetVector( - std::vector<Widget*>* result_child_widgets) { - const Widget* widget = view()->GetWidget(); - if (!widget) - return; - - std::set<Widget*> child_widgets; - Widget::GetAllChildWidgets(widget->GetNativeView(), &child_widgets); - Widget::GetAllOwnedWidgets(widget->GetNativeView(), &child_widgets); - for (std::set<Widget*>::const_iterator iter = child_widgets.begin(); - iter != child_widgets.end(); ++iter) { - Widget* child_widget = *iter; - if (child_widget == widget) - continue; - - if (!child_widget->IsVisible()) - continue; - - if (widget->GetNativeWindowProperty(kWidgetNativeViewHostKey)) - continue; - - result_child_widgets->push_back(child_widget); - } -} - -void NativeViewAccessibilityWin::AddAlertTarget() { - ViewStorage* view_storage = ViewStorage::GetInstance(); - for (size_t i = 0; i < alert_target_view_storage_ids_.size(); ++i) { - int view_storage_id = alert_target_view_storage_ids_[i]; - View* view = view_storage->RetrieveView(view_storage_id); - if (view == view_) - return; - } - int view_storage_id = view_storage->CreateStorageID(); - view_storage->StoreView(view_storage_id, view_); - alert_target_view_storage_ids_.push_back(view_storage_id); -} - -void NativeViewAccessibilityWin::RemoveAlertTarget() { - ViewStorage* view_storage = ViewStorage::GetInstance(); - size_t i = 0; - while (i < alert_target_view_storage_ids_.size()) { - int view_storage_id = alert_target_view_storage_ids_[i]; - View* view = view_storage->RetrieveView(view_storage_id); - if (view == NULL || view == view_) { - alert_target_view_storage_ids_.erase( - alert_target_view_storage_ids_.begin() + i); - } else { - ++i; - } - } -} - -} // namespace views
diff --git a/ui/views/accessibility/native_view_accessibility_win.h b/ui/views/accessibility/native_view_accessibility_win.h deleted file mode 100644 index f985d84..0000000 --- a/ui/views/accessibility/native_view_accessibility_win.h +++ /dev/null
@@ -1,443 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_ACCESSIBILITY_NATIVE_VIEW_ACCESSIBILITY_WIN_H_ -#define UI_VIEWS_ACCESSIBILITY_NATIVE_VIEW_ACCESSIBILITY_WIN_H_ - -#include <atlbase.h> -#include <atlcom.h> -#include <oleacc.h> - -#include <UIAutomationCore.h> - -#include <set> -#include <vector> - -#include "third_party/iaccessible2/ia2_api_all.h" -#include "ui/accessibility/ax_view_state.h" -#include "ui/views/accessibility/native_view_accessibility.h" -#include "ui/views/controls/native/native_view_host.h" -#include "ui/views/view.h" - -namespace ui { -enum TextBoundaryDirection; -enum TextBoundaryType; -} - -namespace views { - -//////////////////////////////////////////////////////////////////////////////// -// -// NativeViewAccessibilityWin -// -// Class implementing the MSAA IAccessible COM interface for a generic View, -// providing accessibility to be used by screen readers and other assistive -// technology (AT). -// -//////////////////////////////////////////////////////////////////////////////// -class __declspec(uuid("26f5641a-246d-457b-a96d-07f3fae6acf2")) -NativeViewAccessibilityWin - : public CComObjectRootEx<CComMultiThreadModel>, - public IDispatchImpl<IAccessible2_2, &IID_IAccessible2_2, - &LIBID_IAccessible2Lib>, - public IAccessibleText, - public IServiceProvider, - public IAccessibleEx, - public IRawElementProviderSimple, - public NativeViewAccessibility { - public: - BEGIN_COM_MAP(NativeViewAccessibilityWin) - COM_INTERFACE_ENTRY2(IDispatch, IAccessible2_2) - COM_INTERFACE_ENTRY(IAccessible) - COM_INTERFACE_ENTRY(IAccessible2) - COM_INTERFACE_ENTRY(IAccessible2_2) - COM_INTERFACE_ENTRY(IAccessibleEx) - COM_INTERFACE_ENTRY(IAccessibleText) - COM_INTERFACE_ENTRY(IRawElementProviderSimple) - COM_INTERFACE_ENTRY(IServiceProvider) - END_COM_MAP() - - virtual ~NativeViewAccessibilityWin(); - - // NativeViewAccessibility. - virtual void NotifyAccessibilityEvent( - ui::AXEvent event_type) override; - virtual gfx::NativeViewAccessible GetNativeObject() override; - virtual void Destroy() override; - - // Supported IAccessible methods. - - // Retrieves the child element or child object at a given point on the screen. - virtual STDMETHODIMP accHitTest(LONG x_left, LONG y_top, VARIANT* child); - - // Performs the object's default action. - STDMETHODIMP accDoDefaultAction(VARIANT var_id); - - // Retrieves the specified object's current screen location. - STDMETHODIMP accLocation(LONG* x_left, - LONG* y_top, - LONG* width, - LONG* height, - VARIANT var_id); - - // Traverses to another UI element and retrieves the object. - STDMETHODIMP accNavigate(LONG nav_dir, VARIANT start, VARIANT* end); - - // Retrieves an IDispatch interface pointer for the specified child. - virtual STDMETHODIMP get_accChild(VARIANT var_child, IDispatch** disp_child); - - // Retrieves the number of accessible children. - virtual STDMETHODIMP get_accChildCount(LONG* child_count); - - // Retrieves a string that describes the object's default action. - STDMETHODIMP get_accDefaultAction(VARIANT var_id, BSTR* default_action); - - // Retrieves the tooltip description. - STDMETHODIMP get_accDescription(VARIANT var_id, BSTR* desc); - - // Retrieves the object that has the keyboard focus. - STDMETHODIMP get_accFocus(VARIANT* focus_child); - - // Retrieves the specified object's shortcut. - STDMETHODIMP get_accKeyboardShortcut(VARIANT var_id, BSTR* access_key); - - // Retrieves the name of the specified object. - STDMETHODIMP get_accName(VARIANT var_id, BSTR* name); - - // Retrieves the IDispatch interface of the object's parent. - STDMETHODIMP get_accParent(IDispatch** disp_parent); - - // Retrieves information describing the role of the specified object. - STDMETHODIMP get_accRole(VARIANT var_id, VARIANT* role); - - // Retrieves the current state of the specified object. - STDMETHODIMP get_accState(VARIANT var_id, VARIANT* state); - - // Retrieve or set the string value associated with the specified object. - // Setting the value is not typically used by screen readers, but it's - // used frequently by automation software. - STDMETHODIMP get_accValue(VARIANT var_id, BSTR* value); - STDMETHODIMP put_accValue(VARIANT var_id, BSTR new_value); - - // Selections not applicable to views. - STDMETHODIMP get_accSelection(VARIANT* selected); - STDMETHODIMP accSelect(LONG flags_sel, VARIANT var_id); - - // Help functions not supported. - STDMETHODIMP get_accHelp(VARIANT var_id, BSTR* help); - STDMETHODIMP get_accHelpTopic(BSTR* help_file, - VARIANT var_id, - LONG* topic_id); - - // Deprecated functions, not implemented here. - STDMETHODIMP put_accName(VARIANT var_id, BSTR put_name); - - // - // IAccessible2 - // - - STDMETHODIMP role(LONG* role); - - STDMETHODIMP get_states(AccessibleStates* states); - - STDMETHODIMP get_uniqueID(LONG* unique_id); - - STDMETHODIMP get_windowHandle(HWND* window_handle); - - STDMETHODIMP get_relationTargetsOfType(BSTR type, - long max_targets, - IUnknown ***targets, - long *n_targets); - - STDMETHODIMP get_attributes(BSTR* attributes); - - // - // IAccessible2 methods not implemented. - // - - STDMETHODIMP get_attribute(BSTR name, VARIANT* attribute) { - return E_NOTIMPL; - } - STDMETHODIMP get_indexInParent(LONG* index_in_parent) { - return E_NOTIMPL; - } - STDMETHODIMP get_extendedRole(BSTR* extended_role) { - return E_NOTIMPL; - } - STDMETHODIMP get_nRelations(LONG* n_relations) { - return E_NOTIMPL; - } - STDMETHODIMP get_relation(LONG relation_index, - IAccessibleRelation** relation) { - return E_NOTIMPL; - } - STDMETHODIMP get_relations(LONG max_relations, - IAccessibleRelation** relations, - LONG* n_relations) { - return E_NOTIMPL; - } - STDMETHODIMP scrollTo(enum IA2ScrollType scroll_type) { - return E_NOTIMPL; - } - STDMETHODIMP scrollToPoint( - enum IA2CoordinateType coordinate_type, - LONG x, - LONG y) { - return E_NOTIMPL; - } - STDMETHODIMP get_groupPosition(LONG* group_level, - LONG* similar_items_in_group, - LONG* position_in_group) { - return E_NOTIMPL; - } - STDMETHODIMP get_localizedExtendedRole( - BSTR* localized_extended_role) { - return E_NOTIMPL; - } - STDMETHODIMP get_nExtendedStates(LONG* n_extended_states) { - return E_NOTIMPL; - } - STDMETHODIMP get_extendedStates(LONG max_extended_states, - BSTR** extended_states, - LONG* n_extended_states) { - return E_NOTIMPL; - } - STDMETHODIMP get_localizedExtendedStates( - LONG max_localized_extended_states, - BSTR** localized_extended_states, - LONG* n_localized_extended_states) { - return E_NOTIMPL; - } - STDMETHODIMP get_locale(IA2Locale* locale) { - return E_NOTIMPL; - } - STDMETHODIMP get_accessibleWithCaret(IUnknown** accessible, - long* caret_offset) { - return E_NOTIMPL; - } - - // - // IAccessibleText methods. - // - - STDMETHODIMP get_nCharacters(LONG* n_characters); - - STDMETHODIMP get_caretOffset(LONG* offset); - - STDMETHODIMP get_nSelections(LONG* n_selections); - - STDMETHODIMP get_selection(LONG selection_index, - LONG* start_offset, - LONG* end_offset); - - STDMETHODIMP get_text(LONG start_offset, LONG end_offset, BSTR* text); - - STDMETHODIMP get_textAtOffset(LONG offset, - enum IA2TextBoundaryType boundary_type, - LONG* start_offset, LONG* end_offset, - BSTR* text); - - STDMETHODIMP get_textBeforeOffset(LONG offset, - enum IA2TextBoundaryType boundary_type, - LONG* start_offset, LONG* end_offset, - BSTR* text); - - STDMETHODIMP get_textAfterOffset(LONG offset, - enum IA2TextBoundaryType boundary_type, - LONG* start_offset, LONG* end_offset, - BSTR* text); - - STDMETHODIMP get_offsetAtPoint(LONG x, LONG y, - enum IA2CoordinateType coord_type, - LONG* offset); - - // - // IAccessibleText methods not implemented. - // - - STDMETHODIMP get_newText(IA2TextSegment* new_text) { - return E_NOTIMPL; - } - STDMETHODIMP get_oldText(IA2TextSegment* old_text) { - return E_NOTIMPL; - } - STDMETHODIMP addSelection(LONG start_offset, LONG end_offset) { - return E_NOTIMPL; - } - STDMETHODIMP get_attributes(LONG offset, - LONG* start_offset, - LONG* end_offset, - BSTR* text_attributes) { - return E_NOTIMPL; - } - STDMETHODIMP get_characterExtents(LONG offset, - enum IA2CoordinateType coord_type, - LONG* x, LONG* y, - LONG* width, LONG* height) { - return E_NOTIMPL; - } - STDMETHODIMP removeSelection(LONG selection_index) { - return E_NOTIMPL; - } - STDMETHODIMP setCaretOffset(LONG offset) { - return E_NOTIMPL; - } - STDMETHODIMP setSelection(LONG selection_index, - LONG start_offset, - LONG end_offset) { - return E_NOTIMPL; - } - STDMETHODIMP scrollSubstringTo(LONG start_index, - LONG end_index, - enum IA2ScrollType scroll_type) { - return E_NOTIMPL; - } - STDMETHODIMP scrollSubstringToPoint(LONG start_index, - LONG end_index, - enum IA2CoordinateType coordinate_type, - LONG x, LONG y) { - return E_NOTIMPL; - } - - // - // IServiceProvider methods. - // - - STDMETHODIMP QueryService(REFGUID guidService, REFIID riid, void** object); - - // - // IAccessibleEx methods not implemented. - // - STDMETHODIMP GetObjectForChild(long child_id, IAccessibleEx** ret) { - return E_NOTIMPL; - } - - STDMETHODIMP GetIAccessiblePair(IAccessible** acc, long* child_id) { - return E_NOTIMPL; - } - - STDMETHODIMP GetRuntimeId(SAFEARRAY** runtime_id) { - return E_NOTIMPL; - } - - STDMETHODIMP ConvertReturnedElement(IRawElementProviderSimple* element, - IAccessibleEx** acc) { - return E_NOTIMPL; - } - - // - // IRawElementProviderSimple methods. - // - // The GetPatternProvider/GetPropertyValue methods need to be implemented for - // the on-screen keyboard to show up in Windows 8 metro. - STDMETHODIMP GetPatternProvider(PATTERNID id, IUnknown** provider); - STDMETHODIMP GetPropertyValue(PROPERTYID id, VARIANT* ret); - - // - // IRawElementProviderSimple methods not implemented. - // - STDMETHODIMP get_ProviderOptions(enum ProviderOptions* ret) { - return E_NOTIMPL; - } - - STDMETHODIMP get_HostRawElementProvider( - IRawElementProviderSimple** provider) { - return E_NOTIMPL; - } - - // Static methods - - // Returns a conversion from the event (as defined in ax_enums.h) - // to an MSAA event. - static int32 MSAAEvent(ui::AXEvent event); - - // Returns a conversion from the Role (as defined in ax_enums.h) - // to an MSAA role. - static int32 MSAARole(ui::AXRole role); - - // Returns a conversion from the State (as defined in ax_enums.h) - // to MSAA states set. - static int32 MSAAState(const ui::AXViewState& state); - - protected: - NativeViewAccessibilityWin(); - - private: - // Determines navigation direction for accNavigate, based on left, up and - // previous being mapped all to previous and right, down, next being mapped - // to next. Returns true if navigation direction is next, false otherwise. - bool IsNavDirNext(int nav_dir) const; - - // Determines if the navigation target is within the allowed bounds. Returns - // true if it is, false otherwise. - bool IsValidNav(int nav_dir, - int start_id, - int lower_bound, - int upper_bound) const; - - // Determines if the child id variant is valid. - bool IsValidId(const VARIANT& child) const; - - // Helper function which sets applicable states of view. - void SetState(VARIANT* msaa_state, View* view); - - // Return the text to use for IAccessibleText. - base::string16 TextForIAccessibleText(); - - // If offset is a member of IA2TextSpecialOffsets this function updates the - // value of offset and returns, otherwise offset remains unchanged. - void HandleSpecialTextOffset(const base::string16& text, LONG* offset); - - // Convert from a IA2TextBoundaryType to a ui::TextBoundaryType. - ui::TextBoundaryType IA2TextBoundaryToTextBoundary(IA2TextBoundaryType type); - - // Search forwards (direction == 1) or backwards (direction == -1) - // from the given offset until the given boundary is found, and - // return the offset of that boundary. - LONG FindBoundary(const base::string16& text, - IA2TextBoundaryType ia2_boundary, - LONG start_offset, - ui::TextBoundaryDirection direction); - - // Populates the given vector with all widgets that are either a child - // or are owned by this view's widget, and who are not contained in a - // NativeViewHost. - void PopulateChildWidgetVector(std::vector<Widget*>* child_widgets); - - // Adds this view to alert_target_view_storage_ids_. - void AddAlertTarget(); - - // Removes this view from alert_target_view_storage_ids_. - void RemoveAlertTarget(); - - // Give CComObject access to the class constructor. - template <class Base> friend class CComObject; - - // A unique id for each object, needed for IAccessible2. - long unique_id_; - - // Next unique id to assign. - static long next_unique_id_; - - // Circular queue size. - static const int kMaxViewStorageIds = 20; - - // Circular queue of view storage ids corresponding to child ids - // used to post notifications using NotifyWinEvent. - static int view_storage_ids_[kMaxViewStorageIds]; - - // Next index into |view_storage_ids_| to use. - static int next_view_storage_id_index_; - - // A vector of view storage ids of views that have been the target of - // an alert event, in order to provide an api to quickly identify all - // open alerts. - static std::vector<int> alert_target_view_storage_ids_; - - DISALLOW_COPY_AND_ASSIGN(NativeViewAccessibilityWin); -}; - -} // namespace views - -#endif // UI_VIEWS_ACCESSIBILITY_NATIVE_VIEW_ACCESSIBILITY_WIN_H_
diff --git a/ui/views/accessibility/native_view_accessibility_win_unittest.cc b/ui/views/accessibility/native_view_accessibility_win_unittest.cc deleted file mode 100644 index 3edab8e..0000000 --- a/ui/views/accessibility/native_view_accessibility_win_unittest.cc +++ /dev/null
@@ -1,204 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <oleacc.h> - -#include "base/win/scoped_bstr.h" -#include "base/win/scoped_comptr.h" -#include "base/win/scoped_variant.h" -#include "third_party/iaccessible2/ia2_api_all.h" -#include "ui/views/accessibility/native_view_accessibility.h" -#include "ui/views/controls/textfield/textfield.h" -#include "ui/views/test/views_test_base.h" - -using base::win::ScopedBstr; -using base::win::ScopedComPtr; -using base::win::ScopedVariant; - -namespace views { -namespace test { - -class NativeViewAcccessibilityWinTest : public ViewsTestBase { - public: - NativeViewAcccessibilityWinTest() {} - virtual ~NativeViewAcccessibilityWinTest() {} - - protected: - void GetIAccessible2InterfaceForView(View* view, IAccessible2_2** result) { - ScopedComPtr<IAccessible> view_accessible( - view->GetNativeViewAccessible()); - ScopedComPtr<IServiceProvider> service_provider; - ASSERT_EQ(S_OK, view_accessible.QueryInterface(service_provider.Receive())); - ASSERT_EQ(S_OK, - service_provider->QueryService(IID_IAccessible2_2, result)); - } -}; - -TEST_F(NativeViewAcccessibilityWinTest, TextfieldAccessibility) { - Widget widget; - Widget::InitParams init_params = - CreateParams(Widget::InitParams::TYPE_POPUP); - init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(init_params); - - View* content = new View; - widget.SetContentsView(content); - - Textfield* textfield = new Textfield; - textfield->SetAccessibleName(L"Name"); - textfield->SetText(L"Value"); - content->AddChildView(textfield); - - ScopedComPtr<IAccessible> content_accessible( - content->GetNativeViewAccessible()); - LONG child_count = 0; - ASSERT_EQ(S_OK, content_accessible->get_accChildCount(&child_count)); - ASSERT_EQ(1L, child_count); - - ScopedComPtr<IDispatch> textfield_dispatch; - ScopedComPtr<IAccessible> textfield_accessible; - ScopedVariant child_index(1); - ASSERT_EQ(S_OK, content_accessible->get_accChild( - child_index, textfield_dispatch.Receive())); - ASSERT_EQ(S_OK, textfield_dispatch.QueryInterface( - textfield_accessible.Receive())); - - ScopedBstr name; - ScopedVariant childid_self(CHILDID_SELF); - ASSERT_EQ(S_OK, textfield_accessible->get_accName( - childid_self, name.Receive())); - ASSERT_STREQ(L"Name", name); - - ScopedBstr value; - ASSERT_EQ(S_OK, textfield_accessible->get_accValue( - childid_self, value.Receive())); - ASSERT_STREQ(L"Value", value); - - ScopedBstr new_value(L"New value"); - ASSERT_EQ(S_OK, textfield_accessible->put_accValue(childid_self, new_value)); - - ASSERT_STREQ(L"New value", textfield->text().c_str()); -} - -TEST_F(NativeViewAcccessibilityWinTest, UnattachedWebView) { - // This is a regression test. Calling get_accChild on the native accessible - // object for a WebView with no attached WebContents was causing an - // infinite loop and crash. This test simulates that with an ordinary - // View that registers itself as a web view with NativeViewAcccessibility. - - Widget widget; - Widget::InitParams init_params = - CreateParams(Widget::InitParams::TYPE_POPUP); - init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(init_params); - - View* content = new View; - widget.SetContentsView(content); - - View* web_view = new View; - content->AddChildView(web_view); - NativeViewAccessibility::RegisterWebView(web_view); - - ScopedComPtr<IAccessible> web_view_accessible( - web_view->GetNativeViewAccessible()); - ScopedComPtr<IDispatch> result_dispatch; - ScopedVariant child_index(-999); - ASSERT_EQ(E_FAIL, web_view_accessible->get_accChild( - child_index, result_dispatch.Receive())); - - NativeViewAccessibility::UnregisterWebView(web_view); -} - -TEST_F(NativeViewAcccessibilityWinTest, AuraOwnedWidgets) { - Widget widget; - Widget::InitParams init_params = - CreateParams(Widget::InitParams::TYPE_WINDOW); - init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(init_params); - - ScopedComPtr<IAccessible> root_view_accessible( - widget.GetRootView()->GetNativeViewAccessible()); - - LONG child_count = 0; - ASSERT_EQ(S_OK, root_view_accessible->get_accChildCount(&child_count)); - ASSERT_EQ(1L, child_count); - - Widget owned_widget; - Widget::InitParams owned_init_params = - CreateParams(Widget::InitParams::TYPE_POPUP); - owned_init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - owned_init_params.parent = widget.GetNativeView(); - owned_widget.Init(owned_init_params); - owned_widget.Show(); - - ASSERT_EQ(S_OK, root_view_accessible->get_accChildCount(&child_count)); - ASSERT_EQ(2L, child_count); -} - -TEST_F(NativeViewAcccessibilityWinTest, RetrieveAllAlerts) { - Widget widget; - Widget::InitParams init_params = - CreateParams(Widget::InitParams::TYPE_POPUP); - init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(init_params); - - View* content = new View; - widget.SetContentsView(content); - - View* infobar = new View; - content->AddChildView(infobar); - - View* infobar2 = new View; - content->AddChildView(infobar2); - - View* root_view = content->parent(); - ASSERT_EQ(NULL, root_view->parent()); - - ScopedComPtr<IAccessible2_2> root_view_accessible; - GetIAccessible2InterfaceForView(root_view, root_view_accessible.Receive()); - - ScopedComPtr<IAccessible2_2> infobar_accessible; - GetIAccessible2InterfaceForView(infobar, infobar_accessible.Receive()); - - ScopedComPtr<IAccessible2_2> infobar2_accessible; - GetIAccessible2InterfaceForView(infobar2, infobar2_accessible.Receive()); - - // Initially, there are no alerts - ScopedBstr alerts_bstr(L"alerts"); - IUnknown** targets; - long n_targets; - ASSERT_EQ(S_FALSE, root_view_accessible->get_relationTargetsOfType( - alerts_bstr, 0, &targets, &n_targets)); - ASSERT_EQ(0, n_targets); - - // Fire alert events on the infobars. - infobar->NotifyAccessibilityEvent(ui::AX_EVENT_ALERT, true); - infobar2->NotifyAccessibilityEvent(ui::AX_EVENT_ALERT, true); - - // Now calling get_relationTargetsOfType should retrieve the alerts. - ASSERT_EQ(S_OK, root_view_accessible->get_relationTargetsOfType( - alerts_bstr, 0, &targets, &n_targets)); - ASSERT_EQ(2, n_targets); - ASSERT_TRUE(infobar_accessible.IsSameObject(targets[0])); - ASSERT_TRUE(infobar2_accessible.IsSameObject(targets[1])); - CoTaskMemFree(targets); - - // If we set max_targets to 1, we should only get the first one. - ASSERT_EQ(S_OK, root_view_accessible->get_relationTargetsOfType( - alerts_bstr, 1, &targets, &n_targets)); - ASSERT_EQ(1, n_targets); - ASSERT_TRUE(infobar_accessible.IsSameObject(targets[0])); - CoTaskMemFree(targets); - - // If we delete the first view, we should only get the second one now. - delete infobar; - ASSERT_EQ(S_OK, root_view_accessible->get_relationTargetsOfType( - alerts_bstr, 0, &targets, &n_targets)); - ASSERT_EQ(1, n_targets); - ASSERT_TRUE(infobar2_accessible.IsSameObject(targets[0])); - CoTaskMemFree(targets); -} - -} // namespace test -} // namespace views
diff --git a/ui/views/accessible_pane_view.cc b/ui/views/accessible_pane_view.cc deleted file mode 100644 index c89dc46..0000000 --- a/ui/views/accessible_pane_view.cc +++ /dev/null
@@ -1,262 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/accessible_pane_view.h" - -#include "base/message_loop/message_loop.h" -#include "ui/accessibility/ax_view_state.h" -#include "ui/views/focus/focus_search.h" -#include "ui/views/focus/view_storage.h" -#include "ui/views/widget/widget.h" - -namespace views { - -// Create tiny subclass of FocusSearch that overrides GetParent and Contains, -// delegating these to methods in AccessiblePaneView. This is needed so that -// subclasses of AccessiblePaneView can customize the focus search logic and -// include views that aren't part of the AccessiblePaneView's view -// hierarchy in the focus order. -class AccessiblePaneViewFocusSearch : public FocusSearch { - public: - explicit AccessiblePaneViewFocusSearch(AccessiblePaneView* pane_view) - : FocusSearch(pane_view, true, true), - accessible_pane_view_(pane_view) {} - - protected: - virtual View* GetParent(View* v) override { - return accessible_pane_view_->ContainsForFocusSearch(root(), v) ? - accessible_pane_view_->GetParentForFocusSearch(v) : NULL; - } - - // 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) override { - return accessible_pane_view_->ContainsForFocusSearch(root, v); - } - - private: - AccessiblePaneView* accessible_pane_view_; - DISALLOW_COPY_AND_ASSIGN(AccessiblePaneViewFocusSearch); -}; - -AccessiblePaneView::AccessiblePaneView() - : pane_has_focus_(false), - allow_deactivate_on_esc_(false), - focus_manager_(NULL), - home_key_(ui::VKEY_HOME, ui::EF_NONE), - end_key_(ui::VKEY_END, ui::EF_NONE), - escape_key_(ui::VKEY_ESCAPE, ui::EF_NONE), - left_key_(ui::VKEY_LEFT, ui::EF_NONE), - right_key_(ui::VKEY_RIGHT, ui::EF_NONE), - method_factory_(this) { - focus_search_.reset(new AccessiblePaneViewFocusSearch(this)); - last_focused_view_storage_id_ = ViewStorage::GetInstance()->CreateStorageID(); -} - -AccessiblePaneView::~AccessiblePaneView() { - if (pane_has_focus_) { - focus_manager_->RemoveFocusChangeListener(this); - } -} - -bool AccessiblePaneView::SetPaneFocus(views::View* initial_focus) { - if (!visible()) - return false; - - if (!focus_manager_) - focus_manager_ = GetFocusManager(); - - View* focused_view = focus_manager_->GetFocusedView(); - if (focused_view && !ContainsForFocusSearch(this, focused_view)) { - ViewStorage* view_storage = ViewStorage::GetInstance(); - view_storage->RemoveView(last_focused_view_storage_id_); - view_storage->StoreView(last_focused_view_storage_id_, focused_view); - } - - // Use the provided initial focus if it's visible and enabled, otherwise - // use the first focusable child. - if (!initial_focus || - !ContainsForFocusSearch(this, initial_focus) || - !initial_focus->visible() || - !initial_focus->enabled()) { - initial_focus = GetFirstFocusableChild(); - } - - // Return false if there are no focusable children. - if (!initial_focus) - return false; - - focus_manager_->SetFocusedView(initial_focus); - - // If we already have pane focus, we're done. - if (pane_has_focus_) - return true; - - // Otherwise, set accelerators and start listening for focus change events. - pane_has_focus_ = true; - ui::AcceleratorManager::HandlerPriority normal = - ui::AcceleratorManager::kNormalPriority; - focus_manager_->RegisterAccelerator(home_key_, normal, this); - focus_manager_->RegisterAccelerator(end_key_, normal, this); - focus_manager_->RegisterAccelerator(escape_key_, normal, this); - focus_manager_->RegisterAccelerator(left_key_, normal, this); - focus_manager_->RegisterAccelerator(right_key_, normal, this); - focus_manager_->AddFocusChangeListener(this); - - return true; -} - -bool AccessiblePaneView::SetPaneFocusAndFocusDefault() { - return SetPaneFocus(GetDefaultFocusableChild()); -} - -views::View* AccessiblePaneView::GetDefaultFocusableChild() { - return NULL; -} - -View* AccessiblePaneView::GetParentForFocusSearch(View* v) { - return v->parent(); -} - -bool AccessiblePaneView::ContainsForFocusSearch(View* root, const View* v) { - return root->Contains(v); -} - -void AccessiblePaneView::RemovePaneFocus() { - focus_manager_->RemoveFocusChangeListener(this); - pane_has_focus_ = false; - - focus_manager_->UnregisterAccelerator(home_key_, this); - focus_manager_->UnregisterAccelerator(end_key_, this); - focus_manager_->UnregisterAccelerator(escape_key_, this); - focus_manager_->UnregisterAccelerator(left_key_, this); - focus_manager_->UnregisterAccelerator(right_key_, this); -} - -views::View* AccessiblePaneView::GetFirstFocusableChild() { - FocusTraversable* dummy_focus_traversable; - views::View* dummy_focus_traversable_view; - return focus_search_->FindNextFocusableView( - NULL, false, views::FocusSearch::DOWN, false, - &dummy_focus_traversable, &dummy_focus_traversable_view); -} - -views::View* AccessiblePaneView::GetLastFocusableChild() { - FocusTraversable* dummy_focus_traversable; - views::View* dummy_focus_traversable_view; - return focus_search_->FindNextFocusableView( - this, true, views::FocusSearch::DOWN, false, - &dummy_focus_traversable, &dummy_focus_traversable_view); -} - -//////////////////////////////////////////////////////////////////////////////// -// View overrides: - -views::FocusTraversable* AccessiblePaneView::GetPaneFocusTraversable() { - if (pane_has_focus_) - return this; - else - return NULL; -} - -bool AccessiblePaneView::AcceleratorPressed( - const ui::Accelerator& accelerator) { - - views::View* focused_view = focus_manager_->GetFocusedView(); - if (!ContainsForFocusSearch(this, focused_view)) - return false; - - switch (accelerator.key_code()) { - case ui::VKEY_ESCAPE: { - RemovePaneFocus(); - View* last_focused_view = ViewStorage::GetInstance()->RetrieveView( - last_focused_view_storage_id_); - if (last_focused_view) { - focus_manager_->SetFocusedViewWithReason( - last_focused_view, FocusManager::kReasonFocusRestore); - } else if (allow_deactivate_on_esc_) { - focused_view->GetWidget()->Deactivate(); - } - return true; - } - case ui::VKEY_LEFT: - focus_manager_->AdvanceFocus(true); - return true; - case ui::VKEY_RIGHT: - focus_manager_->AdvanceFocus(false); - return true; - case ui::VKEY_HOME: - focus_manager_->SetFocusedViewWithReason( - GetFirstFocusableChild(), views::FocusManager::kReasonFocusTraversal); - return true; - case ui::VKEY_END: - focus_manager_->SetFocusedViewWithReason( - GetLastFocusableChild(), views::FocusManager::kReasonFocusTraversal); - return true; - default: - return false; - } -} - -void AccessiblePaneView::SetVisible(bool flag) { - if (visible() && !flag && pane_has_focus_) { - RemovePaneFocus(); - focus_manager_->RestoreFocusedView(); - } - View::SetVisible(flag); -} - -void AccessiblePaneView::GetAccessibleState(ui::AXViewState* state) { - state->role = ui::AX_ROLE_PANE; -} - -void AccessiblePaneView::RequestFocus() { - SetPaneFocusAndFocusDefault(); -} - -//////////////////////////////////////////////////////////////////////////////// -// FocusChangeListener overrides: - -void AccessiblePaneView::OnWillChangeFocus(views::View* focused_before, - views::View* focused_now) { - // Act when focus has changed. -} - -void AccessiblePaneView::OnDidChangeFocus(views::View* focused_before, - views::View* focused_now) { - if (!focused_now) - return; - - views::FocusManager::FocusChangeReason reason = - focus_manager_->focus_change_reason(); - - if (!ContainsForFocusSearch(this, focused_now) || - reason == views::FocusManager::kReasonDirectFocusChange) { - // We should remove pane focus (i.e. make most of the controls - // not focusable again) because the focus has left the pane, - // or because the focus changed within the pane due to the user - // directly focusing to a specific view (e.g., clicking on it). - RemovePaneFocus(); - } -} - -//////////////////////////////////////////////////////////////////////////////// -// FocusTraversable overrides: - -views::FocusSearch* AccessiblePaneView::GetFocusSearch() { - DCHECK(pane_has_focus_); - return focus_search_.get(); -} - -views::FocusTraversable* AccessiblePaneView::GetFocusTraversableParent() { - DCHECK(pane_has_focus_); - return NULL; -} - -views::View* AccessiblePaneView::GetFocusTraversableParentView() { - DCHECK(pane_has_focus_); - return NULL; -} - -} // namespace views
diff --git a/ui/views/accessible_pane_view.h b/ui/views/accessible_pane_view.h deleted file mode 100644 index 345e928..0000000 --- a/ui/views/accessible_pane_view.h +++ /dev/null
@@ -1,132 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_ACCESSIBLE_PANE_VIEW_H_ -#define UI_VIEWS_ACCESSIBLE_PANE_VIEW_H_ - -#include "base/containers/hash_tables.h" -#include "base/memory/scoped_ptr.h" -#include "base/memory/weak_ptr.h" -#include "ui/base/accelerators/accelerator.h" -#include "ui/views/focus/focus_manager.h" -#include "ui/views/view.h" - -namespace views { -class FocusSearch; - -// This class provides keyboard access to any view that extends it, typically -// a toolbar. The user sets focus to a control in this view by pressing -// F6 to traverse all panes, or by pressing a shortcut that jumps directly -// to this pane. -class VIEWS_EXPORT AccessiblePaneView : public View, - public FocusChangeListener, - public FocusTraversable { - public: - AccessiblePaneView(); - virtual ~AccessiblePaneView(); - - // Set focus to the pane with complete keyboard access. - // Focus will be restored to the last focused view if the user escapes. - // If |initial_focus| is not NULL, that control will get - // the initial focus, if it's enabled and focusable. Returns true if - // the pane was able to receive focus. - virtual bool SetPaneFocus(View* initial_focus); - - // Set focus to the pane with complete keyboard access, with the - // focus initially set to the default child. Focus will be restored - // to the last focused view if the user escapes. - // Returns true if the pane was able to receive focus. - virtual bool SetPaneFocusAndFocusDefault(); - - // Overridden from View: - virtual FocusTraversable* GetPaneFocusTraversable() override; - virtual bool AcceleratorPressed(const ui::Accelerator& accelerator) - override; - virtual void SetVisible(bool flag) override; - virtual void GetAccessibleState(ui::AXViewState* state) override; - virtual void RequestFocus() override; - - // Overridden from FocusChangeListener: - virtual void OnWillChangeFocus(View* focused_before, - View* focused_now) override; - virtual void OnDidChangeFocus(View* focused_before, - View* focused_now) override; - - // Overridden from FocusTraversable: - virtual FocusSearch* GetFocusSearch() override; - virtual FocusTraversable* GetFocusTraversableParent() override; - virtual View* GetFocusTraversableParentView() override; - - // For testing only. - const ui::Accelerator& home_key() const { return home_key_; } - const ui::Accelerator& end_key() const { return end_key_; } - const ui::Accelerator& escape_key() const { return escape_key_; } - const ui::Accelerator& left_key() const { return left_key_; } - const ui::Accelerator& right_key() const { return right_key_; } - - protected: - // A subclass can override this to provide a default focusable child - // other than the first focusable child. - virtual View* GetDefaultFocusableChild(); - - // Returns the parent of |v|. Subclasses can override this if - // they need custom focus search behavior. - virtual View* GetParentForFocusSearch(View* v); - - // Returns true if |v| is contained within the hierarchy rooted at |root| - // for the purpose of focus searching. Subclasses can override this if - // they need custom focus search behavior. - virtual bool ContainsForFocusSearch(View* root, const View* v); - - // Remove pane focus. - virtual void RemovePaneFocus(); - - View* GetFirstFocusableChild(); - View* GetLastFocusableChild(); - - FocusManager* focus_manager() const { return focus_manager_; } - - // When finishing navigation by pressing ESC, it is allowed to surrender the - // focus to another window if if |allow| is set and no previous view can be - // found. - void set_allow_deactivate_on_esc(bool allow) { - allow_deactivate_on_esc_ = allow; - } - - private: - bool pane_has_focus_; - - // If true, the panel should be de-activated upon escape when no active view - // is known where to return to. - bool allow_deactivate_on_esc_; - - // Save the focus manager rather than calling GetFocusManager(), - // so that we can remove focus listeners in the destructor. - FocusManager* focus_manager_; - - // Our custom focus search implementation that traps focus in this - // pane and traverses all views that are focusable for accessibility, - // not just those that are normally focusable. - scoped_ptr<FocusSearch> focus_search_; - - // Registered accelerators - ui::Accelerator home_key_; - ui::Accelerator end_key_; - ui::Accelerator escape_key_; - ui::Accelerator left_key_; - ui::Accelerator right_key_; - - // View storage id for the last focused view that's not within this pane. - int last_focused_view_storage_id_; - - friend class AccessiblePaneViewFocusSearch; - - base::WeakPtrFactory<AccessiblePaneView> method_factory_; - - DISALLOW_COPY_AND_ASSIGN(AccessiblePaneView); -}; - -} // namespace views - -#endif // UI_VIEWS_ACCESSIBLE_PANE_VIEW_H_
diff --git a/ui/views/accessible_pane_view_unittest.cc b/ui/views/accessible_pane_view_unittest.cc deleted file mode 100644 index 126fc91..0000000 --- a/ui/views/accessible_pane_view_unittest.cc +++ /dev/null
@@ -1,224 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/accessible_pane_view.h" - -#include "ui/base/accelerators/accelerator.h" -#include "ui/views/controls/button/label_button.h" -#include "ui/views/layout/fill_layout.h" -#include "ui/views/test/views_test_base.h" -#include "ui/views/widget/widget.h" - -namespace views { - -// TODO(alicet): bring pane rotation into views and add tests. -// See browser_view.cc for details. - -typedef ViewsTestBase AccessiblePaneViewTest; - -class TestBarView : public AccessiblePaneView, - public ButtonListener { - public: - TestBarView(); - virtual ~TestBarView(); - - virtual void ButtonPressed(Button* sender, - const ui::Event& event) override; - LabelButton* child_button() const { return child_button_.get(); } - LabelButton* second_child_button() const { - return second_child_button_.get(); - } - LabelButton* third_child_button() const { return third_child_button_.get(); } - LabelButton* not_child_button() const { return not_child_button_.get(); } - - virtual View* GetDefaultFocusableChild() override; - - private: - void Init(); - - scoped_ptr<LabelButton> child_button_; - scoped_ptr<LabelButton> second_child_button_; - scoped_ptr<LabelButton> third_child_button_; - scoped_ptr<LabelButton> not_child_button_; - - DISALLOW_COPY_AND_ASSIGN(TestBarView); -}; - -TestBarView::TestBarView() { - Init(); - set_allow_deactivate_on_esc(true); -} - -TestBarView::~TestBarView() {} - -void TestBarView::ButtonPressed(Button* sender, const ui::Event& event) { -} - -void TestBarView::Init() { - SetLayoutManager(new FillLayout()); - base::string16 label; - child_button_.reset(new LabelButton(this, label)); - AddChildView(child_button_.get()); - second_child_button_.reset(new LabelButton(this, label)); - AddChildView(second_child_button_.get()); - third_child_button_.reset(new LabelButton(this, label)); - AddChildView(third_child_button_.get()); - not_child_button_.reset(new LabelButton(this, label)); -} - -View* TestBarView::GetDefaultFocusableChild() { - return child_button_.get(); -} - -TEST_F(AccessiblePaneViewTest, SimpleSetPaneFocus) { - TestBarView* test_view = new TestBarView(); - scoped_ptr<Widget> widget(new Widget()); - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.bounds = gfx::Rect(50, 50, 650, 650); - widget->Init(params); - View* root = widget->GetRootView(); - root->AddChildView(test_view); - widget->Show(); - widget->Activate(); - - // Set pane focus succeeds, focus on child. - EXPECT_TRUE(test_view->SetPaneFocusAndFocusDefault()); - EXPECT_EQ(test_view, test_view->GetPaneFocusTraversable()); - EXPECT_EQ(test_view->child_button(), - test_view->GetWidget()->GetFocusManager()->GetFocusedView()); - - // Set focus on non child view, focus failed, stays on pane. - EXPECT_TRUE(test_view->SetPaneFocus(test_view->not_child_button())); - EXPECT_FALSE(test_view->not_child_button() == - test_view->GetWidget()->GetFocusManager()->GetFocusedView()); - EXPECT_EQ(test_view->child_button(), - test_view->GetWidget()->GetFocusManager()->GetFocusedView()); - widget->CloseNow(); - widget.reset(); -} - -// This test will not work properly in Windows because it uses ::GetNextWindow -// on deactivate which is rather unpredictable where the focus will land. -TEST_F(AccessiblePaneViewTest, SetPaneFocusAndRestore) { - View* test_view_main = new View(); - scoped_ptr<Widget> widget_main(new Widget()); - Widget::InitParams params_main = CreateParams(Widget::InitParams::TYPE_POPUP); - params_main.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params_main.bounds = gfx::Rect(0, 0, 20, 20); - widget_main->Init(params_main); - View* root_main = widget_main->GetRootView(); - root_main->AddChildView(test_view_main); - widget_main->Activate(); - test_view_main->GetFocusManager()->SetFocusedView(test_view_main); - EXPECT_TRUE(widget_main->IsActive()); - EXPECT_TRUE(test_view_main->HasFocus()); - - TestBarView* test_view_bar = new TestBarView(); - scoped_ptr<Widget> widget_bar(new Widget()); - Widget::InitParams params_bar = CreateParams(Widget::InitParams::TYPE_POPUP); - params_bar.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params_bar.bounds = gfx::Rect(50, 50, 650, 650); - widget_bar->Init(params_bar); - View* root_bar = widget_bar->GetRootView(); - root_bar->AddChildView(test_view_bar); - widget_bar->Show(); - widget_bar->Activate(); - - // Set pane focus succeeds, focus on child. - EXPECT_TRUE(test_view_bar->SetPaneFocusAndFocusDefault()); - EXPECT_FALSE(test_view_main->HasFocus()); - EXPECT_FALSE(widget_main->IsActive()); - EXPECT_EQ(test_view_bar, test_view_bar->GetPaneFocusTraversable()); - EXPECT_EQ(test_view_bar->child_button(), - test_view_bar->GetWidget()->GetFocusManager()->GetFocusedView()); - - test_view_bar->AcceleratorPressed(test_view_bar->escape_key()); - EXPECT_TRUE(widget_main->IsActive()); - EXPECT_FALSE(widget_bar->IsActive()); - - widget_bar->CloseNow(); - widget_bar.reset(); - - widget_main->CloseNow(); - widget_main.reset(); -} - -TEST_F(AccessiblePaneViewTest, TwoSetPaneFocus) { - TestBarView* test_view = new TestBarView(); - TestBarView* test_view_2 = new TestBarView(); - scoped_ptr<Widget> widget(new Widget()); - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.bounds = gfx::Rect(50, 50, 650, 650); - widget->Init(params); - View* root = widget->GetRootView(); - root->AddChildView(test_view); - root->AddChildView(test_view_2); - widget->Show(); - widget->Activate(); - - // Set pane focus succeeds, focus on child. - EXPECT_TRUE(test_view->SetPaneFocusAndFocusDefault()); - EXPECT_EQ(test_view, test_view->GetPaneFocusTraversable()); - EXPECT_EQ(test_view->child_button(), - test_view->GetWidget()->GetFocusManager()->GetFocusedView()); - - // Set focus on another test_view, focus move to that pane. - EXPECT_TRUE(test_view_2->SetPaneFocus(test_view_2->second_child_button())); - EXPECT_FALSE(test_view->child_button() == - test_view->GetWidget()->GetFocusManager()->GetFocusedView()); - EXPECT_EQ(test_view_2->second_child_button(), - test_view->GetWidget()->GetFocusManager()->GetFocusedView()); - widget->CloseNow(); - widget.reset(); -} - -TEST_F(AccessiblePaneViewTest, PaneFocusTraversal) { - TestBarView* test_view = new TestBarView(); - TestBarView* original_test_view = new TestBarView(); - scoped_ptr<Widget> widget(new Widget()); - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.bounds = gfx::Rect(50, 50, 650, 650); - widget->Init(params); - View* root = widget->GetRootView(); - root->AddChildView(original_test_view); - root->AddChildView(test_view); - widget->Show(); - widget->Activate(); - - // Set pane focus on first view. - EXPECT_TRUE(original_test_view->SetPaneFocus( - original_test_view->third_child_button())); - - // Test travesal in second view. - // Set pane focus on second child. - EXPECT_TRUE(test_view->SetPaneFocus(test_view->second_child_button())); - // home - test_view->AcceleratorPressed(test_view->home_key()); - EXPECT_EQ(test_view->child_button(), - test_view->GetWidget()->GetFocusManager()->GetFocusedView()); - // end - test_view->AcceleratorPressed(test_view->end_key()); - EXPECT_EQ(test_view->third_child_button(), - test_view->GetWidget()->GetFocusManager()->GetFocusedView()); - // left - test_view->AcceleratorPressed(test_view->left_key()); - EXPECT_EQ(test_view->second_child_button(), - test_view->GetWidget()->GetFocusManager()->GetFocusedView()); - // right, right - test_view->AcceleratorPressed(test_view->right_key()); - test_view->AcceleratorPressed(test_view->right_key()); - EXPECT_EQ(test_view->child_button(), - test_view->GetWidget()->GetFocusManager()->GetFocusedView()); - - // ESC - test_view->AcceleratorPressed(test_view->escape_key()); - EXPECT_EQ(original_test_view->third_child_button(), - test_view->GetWidget()->GetFocusManager()->GetFocusedView()); - widget->CloseNow(); - widget.reset(); -} -} // namespace views
diff --git a/ui/views/animation/bounds_animator.cc b/ui/views/animation/bounds_animator.cc deleted file mode 100644 index ba94127..0000000 --- a/ui/views/animation/bounds_animator.cc +++ /dev/null
@@ -1,282 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/animation/bounds_animator.h" - -#include "base/memory/scoped_ptr.h" -#include "ui/gfx/animation/animation_container.h" -#include "ui/gfx/animation/slide_animation.h" -#include "ui/views/animation/bounds_animator_observer.h" -#include "ui/views/view.h" - -// Duration in milliseconds for animations. -static const int kDefaultAnimationDuration = 200; - -using gfx::Animation; -using gfx::AnimationContainer; -using gfx::SlideAnimation; -using gfx::Tween; - -namespace views { - -BoundsAnimator::BoundsAnimator(View* parent) - : parent_(parent), - container_(new AnimationContainer()), - animation_duration_ms_(kDefaultAnimationDuration), - tween_type_(Tween::EASE_OUT) { - container_->set_observer(this); -} - -BoundsAnimator::~BoundsAnimator() { - // Reset the delegate so that we don't attempt to notify our observer from - // the destructor. - container_->set_observer(NULL); - - // Delete all the animations, but don't remove any child views. We assume the - // view owns us and is going to be deleted anyway. - for (ViewToDataMap::iterator i = data_.begin(); i != data_.end(); ++i) - CleanupData(false, &(i->second), i->first); -} - -void BoundsAnimator::AnimateViewTo(View* view, const gfx::Rect& target) { - DCHECK(view); - DCHECK_EQ(view->parent(), parent_); - - Data existing_data; - - if (IsAnimating(view)) { - // Don't immediatly delete the animation, that might trigger a callback from - // the animationcontainer. - existing_data = data_[view]; - - RemoveFromMaps(view); - } - - // NOTE: we don't check if the view is already at the target location. Doing - // so leads to odd cases where no animations may be present after invoking - // AnimateViewTo. AnimationProgressed does nothing when the bounds of the - // view don't change. - - Data& data = data_[view]; - data.start_bounds = view->bounds(); - data.target_bounds = target; - data.animation = CreateAnimation(); - - animation_to_view_[data.animation] = view; - - data.animation->Show(); - - CleanupData(true, &existing_data, NULL); -} - -void BoundsAnimator::SetTargetBounds(View* view, const gfx::Rect& target) { - if (!IsAnimating(view)) { - AnimateViewTo(view, target); - return; - } - - data_[view].target_bounds = target; -} - -gfx::Rect BoundsAnimator::GetTargetBounds(View* view) { - if (!IsAnimating(view)) - return view->bounds(); - return data_[view].target_bounds; -} - -void BoundsAnimator::SetAnimationForView(View* view, - SlideAnimation* animation) { - DCHECK(animation); - - scoped_ptr<SlideAnimation> animation_wrapper(animation); - - if (!IsAnimating(view)) - return; - - // We delay deleting the animation until the end so that we don't prematurely - // send out notification that we're done. - scoped_ptr<Animation> old_animation(ResetAnimationForView(view)); - - data_[view].animation = animation_wrapper.release(); - animation_to_view_[animation] = view; - - animation->set_delegate(this); - animation->SetContainer(container_.get()); - animation->Show(); -} - -const SlideAnimation* BoundsAnimator::GetAnimationForView(View* view) { - return !IsAnimating(view) ? NULL : data_[view].animation; -} - -void BoundsAnimator::SetAnimationDelegate( - View* view, - scoped_ptr<AnimationDelegate> delegate) { - DCHECK(IsAnimating(view)); - - data_[view].delegate = delegate.release(); -} - -void BoundsAnimator::StopAnimatingView(View* view) { - if (!IsAnimating(view)) - return; - - data_[view].animation->Stop(); -} - -bool BoundsAnimator::IsAnimating(View* view) const { - return data_.find(view) != data_.end(); -} - -bool BoundsAnimator::IsAnimating() const { - return !data_.empty(); -} - -void BoundsAnimator::Cancel() { - if (data_.empty()) - return; - - while (!data_.empty()) - data_.begin()->second.animation->Stop(); - - // Invoke AnimationContainerProgressed to force a repaint and notify delegate. - AnimationContainerProgressed(container_.get()); -} - -void BoundsAnimator::SetAnimationDuration(int duration_ms) { - animation_duration_ms_ = duration_ms; -} - -void BoundsAnimator::AddObserver(BoundsAnimatorObserver* observer) { - observers_.AddObserver(observer); -} - -void BoundsAnimator::RemoveObserver(BoundsAnimatorObserver* observer) { - observers_.RemoveObserver(observer); -} - -SlideAnimation* BoundsAnimator::CreateAnimation() { - SlideAnimation* animation = new SlideAnimation(this); - animation->SetContainer(container_.get()); - animation->SetSlideDuration(animation_duration_ms_); - animation->SetTweenType(tween_type_); - return animation; -} - -void BoundsAnimator::RemoveFromMaps(View* view) { - DCHECK(data_.count(view) > 0); - DCHECK(animation_to_view_.count(data_[view].animation) > 0); - - animation_to_view_.erase(data_[view].animation); - data_.erase(view); -} - -void BoundsAnimator::CleanupData(bool send_cancel, Data* data, View* view) { - if (send_cancel && data->delegate) - data->delegate->AnimationCanceled(data->animation); - - delete data->delegate; - data->delegate = NULL; - - if (data->animation) { - data->animation->set_delegate(NULL); - delete data->animation; - data->animation = NULL; - } -} - -Animation* BoundsAnimator::ResetAnimationForView(View* view) { - if (!IsAnimating(view)) - return NULL; - - Animation* old_animation = data_[view].animation; - animation_to_view_.erase(old_animation); - data_[view].animation = NULL; - // Reset the delegate so that we don't attempt any processing when the - // animation calls us back. - old_animation->set_delegate(NULL); - return old_animation; -} - -void BoundsAnimator::AnimationEndedOrCanceled(const Animation* animation, - AnimationEndType type) { - DCHECK(animation_to_view_.find(animation) != animation_to_view_.end()); - - View* view = animation_to_view_[animation]; - DCHECK(view); - - // Make a copy of the data as Remove empties out the maps. - Data data = data_[view]; - - RemoveFromMaps(view); - - if (data.delegate) { - if (type == ANIMATION_ENDED) { - data.delegate->AnimationEnded(animation); - } else { - DCHECK_EQ(ANIMATION_CANCELED, type); - data.delegate->AnimationCanceled(animation); - } - } - - CleanupData(false, &data, view); -} - -void BoundsAnimator::AnimationProgressed(const Animation* animation) { - DCHECK(animation_to_view_.find(animation) != animation_to_view_.end()); - - View* view = animation_to_view_[animation]; - DCHECK(view); - const Data& data = data_[view]; - gfx::Rect new_bounds = - animation->CurrentValueBetween(data.start_bounds, data.target_bounds); - if (new_bounds != view->bounds()) { - gfx::Rect total_bounds = gfx::UnionRects(new_bounds, view->bounds()); - - // Build up the region to repaint in repaint_bounds_. We'll do the repaint - // when all animations complete (in AnimationContainerProgressed). - repaint_bounds_.Union(total_bounds); - - view->SetBoundsRect(new_bounds); - } - - if (data.delegate) - data.delegate->AnimationProgressed(animation); -} - -void BoundsAnimator::AnimationEnded(const Animation* animation) { - AnimationEndedOrCanceled(animation, ANIMATION_ENDED); -} - -void BoundsAnimator::AnimationCanceled(const Animation* animation) { - AnimationEndedOrCanceled(animation, ANIMATION_CANCELED); -} - -void BoundsAnimator::AnimationContainerProgressed( - AnimationContainer* container) { - if (!repaint_bounds_.IsEmpty()) { - // Adjust for rtl. - repaint_bounds_.set_x(parent_->GetMirroredXWithWidthInView( - repaint_bounds_.x(), repaint_bounds_.width())); - parent_->SchedulePaintInRect(repaint_bounds_); - repaint_bounds_.SetRect(0, 0, 0, 0); - } - - FOR_EACH_OBSERVER(BoundsAnimatorObserver, - observers_, - OnBoundsAnimatorProgressed(this)); - - if (!IsAnimating()) { - // Notify here rather than from AnimationXXX to avoid deleting the animation - // while the animation is calling us. - FOR_EACH_OBSERVER(BoundsAnimatorObserver, - observers_, - OnBoundsAnimatorDone(this)); - } -} - -void BoundsAnimator::AnimationContainerEmpty(AnimationContainer* container) { -} - -} // namespace views
diff --git a/ui/views/animation/bounds_animator.h b/ui/views/animation/bounds_animator.h deleted file mode 100644 index 0abc37a..0000000 --- a/ui/views/animation/bounds_animator.h +++ /dev/null
@@ -1,186 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_ANIMATION_BOUNDS_ANIMATOR_H_ -#define UI_VIEWS_ANIMATION_BOUNDS_ANIMATOR_H_ - -#include <map> - -#include "base/compiler_specific.h" -#include "base/memory/ref_counted.h" -#include "base/observer_list.h" -#include "ui/gfx/animation/animation_container_observer.h" -#include "ui/gfx/animation/animation_delegate.h" -#include "ui/gfx/animation/tween.h" -#include "ui/gfx/rect.h" -#include "ui/views/views_export.h" - -namespace gfx { -class SlideAnimation; -} - -namespace views { - -class BoundsAnimatorObserver; -class View; - -// Bounds animator is responsible for animating the bounds of a view from the -// the views current location and size to a target position and size. To use -// BoundsAnimator invoke AnimateViewTo for the set of views you want to -// animate. -// -// BoundsAnimator internally creates an animation for each view. If you need -// a specific animation invoke SetAnimationForView after invoking AnimateViewTo. -// You can attach an AnimationDelegate to the individual animation for a view -// by way of SetAnimationDelegate. Additionally you can attach an observer to -// the BoundsAnimator that is notified when all animations are complete. -class VIEWS_EXPORT BoundsAnimator : public gfx::AnimationDelegate, - public gfx::AnimationContainerObserver { - public: - explicit BoundsAnimator(View* view); - virtual ~BoundsAnimator(); - - // Starts animating |view| from its current bounds to |target|. If there is - // already an animation running for the view it's stopped and a new one - // started. If an AnimationDelegate has been set for |view| it is removed - // (after being notified that the animation was canceled). - void AnimateViewTo(View* view, const gfx::Rect& target); - - // Similar to |AnimateViewTo|, but does not reset the animation, only the - // target bounds. If |view| is not being animated this is the same as - // invoking |AnimateViewTo|. - void SetTargetBounds(View* view, const gfx::Rect& target); - - // Returns the target bounds for the specified view. If |view| is not - // animating its current bounds is returned. - gfx::Rect GetTargetBounds(View* view); - - // Sets the animation for the specified view. BoundsAnimator takes ownership - // of the specified animation. - void SetAnimationForView(View* view, gfx::SlideAnimation* animation); - - // Returns the animation for the specified view. BoundsAnimator owns the - // returned Animation. - const gfx::SlideAnimation* GetAnimationForView(View* view); - - // Stops animating the specified view. - void StopAnimatingView(View* view); - - // Sets the delegate for the animation for the specified view. - void SetAnimationDelegate(View* view, - scoped_ptr<gfx::AnimationDelegate> delegate); - - // Returns true if BoundsAnimator is animating the bounds of |view|. - bool IsAnimating(View* view) const; - - // Returns true if BoundsAnimator is animating any view. - bool IsAnimating() const; - - // Cancels all animations, leaving the views at their current location and - // size. Any views marked for deletion are deleted. - void Cancel(); - - // Overrides default animation duration. |duration_ms| is the new duration in - // milliseconds. - void SetAnimationDuration(int duration_ms); - - // Gets the currently used animation duration. - int GetAnimationDuration() const { return animation_duration_ms_; } - - // Sets the tween type for new animations. Default is EASE_OUT. - void set_tween_type(gfx::Tween::Type type) { tween_type_ = type; } - - void AddObserver(BoundsAnimatorObserver* observer); - void RemoveObserver(BoundsAnimatorObserver* observer); - - protected: - // Creates the animation to use for animating views. - virtual gfx::SlideAnimation* CreateAnimation(); - - private: - // Tracks data about the view being animated. - struct Data { - Data() : animation(NULL), delegate(NULL) {} - - // The initial bounds. - gfx::Rect start_bounds; - - // Target bounds. - gfx::Rect target_bounds; - - // The animation. We own this. - gfx::SlideAnimation* animation; - - // Delegate for the animation, may be null. We own this. - gfx::AnimationDelegate* delegate; - }; - - // Used by AnimationEndedOrCanceled. - enum AnimationEndType { - ANIMATION_ENDED, - ANIMATION_CANCELED - }; - - typedef std::map<View*, Data> ViewToDataMap; - - typedef std::map<const gfx::Animation*, View*> AnimationToViewMap; - - // Removes references to |view| and its animation. This does NOT delete the - // animation or delegate. - void RemoveFromMaps(View* view); - - // Does the necessary cleanup for |data|. If |send_cancel| is true and a - // delegate has been installed on |data| AnimationCanceled is invoked on it. - void CleanupData(bool send_cancel, Data* data, View* view); - - // Used when changing the animation for a view. This resets the maps for - // the animation used by view and returns the current animation. Ownership - // of the returned animation passes to the caller. - gfx::Animation* ResetAnimationForView(View* view); - - // Invoked from AnimationEnded and AnimationCanceled. - void AnimationEndedOrCanceled(const gfx::Animation* animation, - AnimationEndType type); - - // gfx::AnimationDelegate overrides. - virtual void AnimationProgressed(const gfx::Animation* animation) override; - virtual void AnimationEnded(const gfx::Animation* animation) override; - virtual void AnimationCanceled(const gfx::Animation* animation) override; - - // gfx::AnimationContainerObserver overrides. - virtual void AnimationContainerProgressed( - gfx::AnimationContainer* container) override; - virtual void AnimationContainerEmpty( - gfx::AnimationContainer* container) override; - - // Parent of all views being animated. - View* parent_; - - ObserverList<BoundsAnimatorObserver> observers_; - - // All animations we create up with the same container. - scoped_refptr<gfx::AnimationContainer> container_; - - // Maps from view being animated to info about the view. - ViewToDataMap data_; - - // Maps from animation to view. - AnimationToViewMap animation_to_view_; - - // As the animations we create update (AnimationProgressed is invoked) this - // is updated. When all the animations have completed for a given tick of - // the timer (AnimationContainerProgressed is invoked) the parent_ is asked - // to repaint these bounds. - gfx::Rect repaint_bounds_; - - int animation_duration_ms_; - - gfx::Tween::Type tween_type_; - - DISALLOW_COPY_AND_ASSIGN(BoundsAnimator); -}; - -} // namespace views - -#endif // UI_VIEWS_ANIMATION_BOUNDS_ANIMATOR_H_
diff --git a/ui/views/animation/bounds_animator_observer.h b/ui/views/animation/bounds_animator_observer.h deleted file mode 100644 index 37a5243..0000000 --- a/ui/views/animation/bounds_animator_observer.h +++ /dev/null
@@ -1,28 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_ANIMATION_BOUNDS_ANIMATOR_OBSERVER_H_ -#define UI_VIEWS_ANIMATION_BOUNDS_ANIMATOR_OBSERVER_H_ - -#include "ui/views/views_export.h" - -namespace views { - -class BoundsAnimator; - -class VIEWS_EXPORT BoundsAnimatorObserver { - public: - // Invoked when animations have progressed. - virtual void OnBoundsAnimatorProgressed(BoundsAnimator* animator) = 0; - - // Invoked when all animations are complete. - virtual void OnBoundsAnimatorDone(BoundsAnimator* animator) = 0; - - protected: - virtual ~BoundsAnimatorObserver() {} -}; - -} // namespace views - -#endif // UI_VIEWS_ANIMATION_BOUNDS_ANIMATOR_OBSERVER_H_
diff --git a/ui/views/animation/bounds_animator_unittest.cc b/ui/views/animation/bounds_animator_unittest.cc deleted file mode 100644 index b8f62a2..0000000 --- a/ui/views/animation/bounds_animator_unittest.cc +++ /dev/null
@@ -1,184 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/animation/bounds_animator.h" - -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/gfx/animation/slide_animation.h" -#include "ui/gfx/animation/test_animation_delegate.h" -#include "ui/views/view.h" - -using gfx::Animation; -using gfx::SlideAnimation; -using gfx::TestAnimationDelegate; - -namespace views { -namespace { - -class TestBoundsAnimator : public BoundsAnimator { - public: - explicit TestBoundsAnimator(View* view) : BoundsAnimator(view) { - } - - protected: - virtual SlideAnimation* CreateAnimation() override { - SlideAnimation* animation = BoundsAnimator::CreateAnimation(); - animation->SetSlideDuration(10); - return animation; - } - - private: - DISALLOW_COPY_AND_ASSIGN(TestBoundsAnimator); -}; - -class OwnedDelegate : public gfx::AnimationDelegate { - public: - OwnedDelegate() {} - - virtual ~OwnedDelegate() { - deleted_ = true; - } - - static bool GetAndClearDeleted() { - bool value = deleted_; - deleted_ = false; - return value; - } - - static bool GetAndClearCanceled() { - bool value = canceled_; - canceled_ = false; - return value; - } - - // Overridden from gfx::AnimationDelegate: - virtual void AnimationCanceled(const Animation* animation) override { - canceled_ = true; - } - - private: - static bool deleted_; - static bool canceled_; - - DISALLOW_COPY_AND_ASSIGN(OwnedDelegate); -}; - -// static -bool OwnedDelegate::deleted_ = false; -bool OwnedDelegate::canceled_ = false; - -class TestView : public View { - public: - TestView() {} - - virtual void SchedulePaintInRect(const gfx::Rect& r) override { - if (dirty_rect_.IsEmpty()) - dirty_rect_ = r; - else - dirty_rect_.Union(r); - } - - const gfx::Rect& dirty_rect() const { return dirty_rect_; } - - private: - gfx::Rect dirty_rect_; - - DISALLOW_COPY_AND_ASSIGN(TestView); -}; - -} // namespace - -class BoundsAnimatorTest : public testing::Test { - public: - BoundsAnimatorTest() : child_(new TestView()), animator_(&parent_) { - parent_.AddChildView(child_); - } - - TestView* parent() { return &parent_; } - TestView* child() { return child_; } - TestBoundsAnimator* animator() { return &animator_; } - - private: - base::MessageLoopForUI message_loop_; - TestView parent_; - TestView* child_; // Owned by |parent_|. - TestBoundsAnimator animator_; - - DISALLOW_COPY_AND_ASSIGN(BoundsAnimatorTest); -}; - -// Checks animate view to. -TEST_F(BoundsAnimatorTest, AnimateViewTo) { - gfx::Rect initial_bounds(0, 0, 10, 10); - child()->SetBoundsRect(initial_bounds); - gfx::Rect target_bounds(10, 10, 20, 20); - animator()->AnimateViewTo(child(), target_bounds); - animator()->SetAnimationDelegate( - child(), scoped_ptr<gfx::AnimationDelegate>(new TestAnimationDelegate())); - - // The animator should be animating now. - EXPECT_TRUE(animator()->IsAnimating()); - - // Run the message loop; the delegate exits the loop when the animation is - // done. - base::MessageLoop::current()->Run(); - - // Make sure the bounds match of the view that was animated match. - EXPECT_EQ(target_bounds, child()->bounds()); - - // The parent should have been told to repaint as the animation progressed. - // The resulting rect is the union of the original and target bounds. - EXPECT_EQ(gfx::UnionRects(target_bounds, initial_bounds), - parent()->dirty_rect()); -} - -// Make sure an AnimationDelegate is deleted when canceled. -TEST_F(BoundsAnimatorTest, DeleteDelegateOnCancel) { - animator()->AnimateViewTo(child(), gfx::Rect(0, 0, 10, 10)); - animator()->SetAnimationDelegate( - child(), scoped_ptr<gfx::AnimationDelegate>(new OwnedDelegate())); - - animator()->Cancel(); - - // The animator should no longer be animating. - EXPECT_FALSE(animator()->IsAnimating()); - - // The cancel should both cancel the delegate and delete it. - EXPECT_TRUE(OwnedDelegate::GetAndClearCanceled()); - EXPECT_TRUE(OwnedDelegate::GetAndClearDeleted()); -} - -// Make sure an AnimationDelegate is deleted when another animation is -// scheduled. -TEST_F(BoundsAnimatorTest, DeleteDelegateOnNewAnimate) { - animator()->AnimateViewTo(child(), gfx::Rect(0, 0, 10, 10)); - animator()->SetAnimationDelegate( - child(), scoped_ptr<gfx::AnimationDelegate>(new OwnedDelegate())); - - animator()->AnimateViewTo(child(), gfx::Rect(0, 0, 10, 10)); - - // Starting a new animation should both cancel the delegate and delete it. - EXPECT_TRUE(OwnedDelegate::GetAndClearDeleted()); - EXPECT_TRUE(OwnedDelegate::GetAndClearCanceled()); -} - -// Makes sure StopAnimating works. -TEST_F(BoundsAnimatorTest, StopAnimating) { - scoped_ptr<OwnedDelegate> delegate(new OwnedDelegate()); - - animator()->AnimateViewTo(child(), gfx::Rect(0, 0, 10, 10)); - animator()->SetAnimationDelegate( - child(), scoped_ptr<gfx::AnimationDelegate>(new OwnedDelegate())); - - animator()->StopAnimatingView(child()); - - // Shouldn't be animating now. - EXPECT_FALSE(animator()->IsAnimating()); - - // Stopping should both cancel the delegate and delete it. - EXPECT_TRUE(OwnedDelegate::GetAndClearDeleted()); - EXPECT_TRUE(OwnedDelegate::GetAndClearCanceled()); -} - -} // namespace views
diff --git a/ui/views/animation/scroll_animator.cc b/ui/views/animation/scroll_animator.cc deleted file mode 100644 index 7d68999..0000000 --- a/ui/views/animation/scroll_animator.cc +++ /dev/null
@@ -1,82 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/animation/scroll_animator.h" - -#include <algorithm> -#include <cmath> - -#include "base/logging.h" -#include "ui/gfx/animation/slide_animation.h" - -namespace { -const float kDefaultAcceleration = -1500.0f; // in pixels per second^2 - -// Assumes that d0 == 0.0f -float GetPosition(float v0, float a, float t) { - float max_t = -v0 / a; - if (t > max_t) - t = max_t; - return t * (v0 + 0.5f * a * t); -} - -float GetDelta(float v0, float a, float t1, float t2) { - return GetPosition(v0, a, t2) - GetPosition(v0, a, t1); -} - -} // namespace - -namespace views { - -ScrollAnimator::ScrollAnimator(ScrollDelegate* delegate) - : delegate_(delegate), - velocity_x_(0.0f), - velocity_y_(0.0f), - last_t_(0.0f), - duration_(0.0f), - acceleration_(kDefaultAcceleration) { - DCHECK(delegate); -} - -ScrollAnimator::~ScrollAnimator() { - Stop(); -} - -void ScrollAnimator::Start(float velocity_x, float velocity_y) { - if (acceleration_ >= 0.0f) - acceleration_ = kDefaultAcceleration; - float v = std::max(fabs(velocity_x), fabs(velocity_y)); - last_t_ = 0.0f; - velocity_x_ = velocity_x; - velocity_y_ = velocity_y; - duration_ = -v / acceleration_; // in seconds - animation_.reset(new gfx::SlideAnimation(this)); - animation_->SetSlideDuration(static_cast<int>(duration_ * 1000)); - animation_->Show(); -} - -void ScrollAnimator::Stop() { - velocity_x_ = velocity_y_ = last_t_ = duration_ = 0.0f; - animation_.reset(); -} - -void ScrollAnimator::AnimationEnded(const gfx::Animation* animation) { - Stop(); -} - -void ScrollAnimator::AnimationProgressed(const gfx::Animation* animation) { - float t = static_cast<float>(animation->GetCurrentValue()) * duration_; - float a_x = velocity_x_ > 0 ? acceleration_ : -acceleration_; - float a_y = velocity_y_ > 0 ? acceleration_ : -acceleration_; - float dx = GetDelta(velocity_x_, a_x, last_t_, t); - float dy = GetDelta(velocity_y_, a_y, last_t_, t); - last_t_ = t; - delegate_->OnScroll(dx, dy); -} - -void ScrollAnimator::AnimationCanceled(const gfx::Animation* animation) { - Stop(); -} - -} // namespace views
diff --git a/ui/views/animation/scroll_animator.h b/ui/views/animation/scroll_animator.h deleted file mode 100644 index b941cdb..0000000 --- a/ui/views/animation/scroll_animator.h +++ /dev/null
@@ -1,63 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_ANIMATION_SCROLL_ANIMATOR_H_ -#define UI_VIEWS_ANIMATION_SCROLL_ANIMATOR_H_ - -#include "base/basictypes.h" -#include "base/memory/scoped_ptr.h" -#include "ui/gfx/animation/animation_delegate.h" -#include "ui/views/views_export.h" - -namespace gfx { -class SlideAnimation; -} - -namespace views { - -class VIEWS_EXPORT ScrollDelegate { - public: - // Returns true if the content was actually scrolled, false otherwise. - virtual bool OnScroll(float dx, float dy) = 0; - - protected: - ~ScrollDelegate() {} -}; - -class VIEWS_EXPORT ScrollAnimator : public gfx::AnimationDelegate { - public: - // The ScrollAnimator does not own the delegate. Uses default acceleration. - explicit ScrollAnimator(ScrollDelegate* delegate); - virtual ~ScrollAnimator(); - - // Use this if you would prefer different acceleration than the default. - void set_acceleration(float acceleration) { acceleration_ = acceleration; } - - void Start(float velocity_x, float velocity_y); - void Stop(); - - bool is_scrolling() const { return !!animation_.get(); } - - private: - // Implementation of gfx::AnimationDelegate. - virtual void AnimationEnded(const gfx::Animation* animation) override; - virtual void AnimationProgressed(const gfx::Animation* animation) override; - virtual void AnimationCanceled(const gfx::Animation* animation) override; - - ScrollDelegate* delegate_; - - float velocity_x_; - float velocity_y_; - float last_t_; - float duration_; - float acceleration_; - - scoped_ptr<gfx::SlideAnimation> animation_; - - DISALLOW_COPY_AND_ASSIGN(ScrollAnimator); -}; - -} // namespace views - -#endif // UI_VIEWS_ANIMATION_SCROLL_ANIMATOR_H_
diff --git a/ui/views/background.cc b/ui/views/background.cc deleted file mode 100644 index d2d64bb..0000000 --- a/ui/views/background.cc +++ /dev/null
@@ -1,130 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/background.h" - -#include "base/logging.h" -#include "skia/ext/skia_utils_win.h" -#include "third_party/skia/include/core/SkPaint.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/color_utils.h" -#include "ui/views/painter.h" -#include "ui/views/view.h" - -namespace views { - -// SolidBackground is a trivial Background implementation that fills the -// background in a solid color. -class SolidBackground : public Background { - public: - explicit SolidBackground(SkColor color) { - SetNativeControlColor(color); - } - - virtual void Paint(gfx::Canvas* canvas, View* view) const override { - // Fill the background. Note that we don't constrain to the bounds as - // canvas is already clipped for us. - canvas->DrawColor(get_color()); - } - - private: - DISALLOW_COPY_AND_ASSIGN(SolidBackground); -}; - -class BackgroundPainter : public Background { - public: - BackgroundPainter(bool owns_painter, Painter* painter) - : owns_painter_(owns_painter), painter_(painter) { - DCHECK(painter); - } - - virtual ~BackgroundPainter() { - if (owns_painter_) - delete painter_; - } - - - virtual void Paint(gfx::Canvas* canvas, View* view) const override { - Painter::PaintPainterAt(canvas, painter_, view->GetLocalBounds()); - } - - private: - bool owns_painter_; - Painter* painter_; - - DISALLOW_COPY_AND_ASSIGN(BackgroundPainter); -}; - -Background::Background() - : color_(SK_ColorWHITE) -#if defined(OS_WIN) - , native_control_brush_(NULL) -#endif -{ -} - -Background::~Background() { -#if defined(OS_WIN) - DeleteObject(native_control_brush_); -#endif -} - -void Background::SetNativeControlColor(SkColor color) { - color_ = color; -#if defined(OS_WIN) - DeleteObject(native_control_brush_); - native_control_brush_ = NULL; -#endif -} - -#if defined(OS_WIN) -HBRUSH Background::GetNativeControlBrush() const { - if (!native_control_brush_) - native_control_brush_ = CreateSolidBrush(skia::SkColorToCOLORREF(color_)); - return native_control_brush_; -} -#endif - -//static -Background* Background::CreateSolidBackground(SkColor color) { - return new SolidBackground(color); -} - -//static -Background* Background::CreateStandardPanelBackground() { - // TODO(beng): Should be in NativeTheme. - return CreateSolidBackground(SK_ColorWHITE); -} - -//static -Background* Background::CreateVerticalGradientBackground(SkColor color1, - SkColor color2) { - Background* background = CreateBackgroundPainter( - true, Painter::CreateVerticalGradient(color1, color2)); - background->SetNativeControlColor( - color_utils::AlphaBlend(color1, color2, 128)); - - return background; -} - -//static -Background* Background::CreateVerticalMultiColorGradientBackground( - SkColor* colors, - SkScalar* pos, - size_t count) { - Background* background = CreateBackgroundPainter( - true, Painter::CreateVerticalMultiColorGradient(colors, pos, count)); - background->SetNativeControlColor( - color_utils::AlphaBlend(colors[0], colors[count-1], 128)); - - return background; -} - -//static -Background* Background::CreateBackgroundPainter(bool owns_painter, - Painter* painter) { - return new BackgroundPainter(owns_painter, painter); -} - -} // namespace views
diff --git a/ui/views/background.h b/ui/views/background.h deleted file mode 100644 index 8ecca6e..0000000 --- a/ui/views/background.h +++ /dev/null
@@ -1,111 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_BACKGROUND_H_ -#define UI_VIEWS_BACKGROUND_H_ - -#include "build/build_config.h" - -#if defined(OS_WIN) -#include <windows.h> -#endif // defined(OS_WIN) - -#include "base/basictypes.h" -#include "third_party/skia/include/core/SkColor.h" -#include "ui/views/views_export.h" - -namespace gfx { -class Canvas; -} - -namespace views { - -class Painter; -class View; - -///////////////////////////////////////////////////////////////////////////// -// -// Background class -// -// A background implements a way for views to paint a background. The -// background can be either solid or based on a gradient. Of course, -// Background can be subclassed to implement various effects. -// -// Any View can have a background. See View::SetBackground() and -// View::OnPaintBackground() -// -///////////////////////////////////////////////////////////////////////////// -class VIEWS_EXPORT Background { - public: - Background(); - virtual ~Background(); - - // Creates a background that fills the canvas in the specified color. - static Background* CreateSolidBackground(SkColor color); - - // Creates a background that fills the canvas in the specified color. - static Background* CreateSolidBackground(int r, int g, int b) { - return CreateSolidBackground(SkColorSetRGB(r, g, b)); - } - - // Creates a background that fills the canvas in the specified color. - static Background* CreateSolidBackground(int r, int g, int b, int a) { - return CreateSolidBackground(SkColorSetARGB(a, r, g, b)); - } - - // Creates a background that contains a vertical gradient that varies - // from |color1| to |color2| - static Background* CreateVerticalGradientBackground(SkColor color1, - SkColor color2); - - // Creates a background that contains a vertical gradient. The gradient can - // have multiple |colors|. The |pos| array contains the relative positions of - // each corresponding color. |colors| and |pos| must be the same size. The - // first element in |pos| must be 0.0 and the last element must be 1.0. - // |count| contains the number of elements in |colors| and |pos|. - static Background* CreateVerticalMultiColorGradientBackground(SkColor* colors, - SkScalar* pos, - size_t count); - - // Creates Chrome's standard panel background - static Background* CreateStandardPanelBackground(); - - // Creates a Background from the specified Painter. If owns_painter is - // true, the Painter is deleted when the Border is deleted. - static Background* CreateBackgroundPainter(bool owns_painter, - Painter* painter); - - // Render the background for the provided view - virtual void Paint(gfx::Canvas* canvas, View* view) const = 0; - - // Set a solid, opaque color to be used when drawing backgrounds of native - // controls. Unfortunately alpha=0 is not an option. - void SetNativeControlColor(SkColor color); - - // Returns the "background color". This is equivalent to the color set in - // SetNativeControlColor(). For solid backgrounds, this is the color; for - // gradient backgrounds, it's the midpoint of the gradient; for painter - // backgrounds, this is not useful (returns a default color). - SkColor get_color() const { return color_; } - -#if defined(OS_WIN) - // TODO(port): Make GetNativeControlBrush portable (currently uses HBRUSH). - - // Get the brush that was specified by SetNativeControlColor - HBRUSH GetNativeControlBrush() const; -#endif // defined(OS_WIN) - - private: - SkColor color_; -#if defined(OS_WIN) - // TODO(port): Create portable replacement for HBRUSH. - mutable HBRUSH native_control_brush_; -#endif // defined(OS_WIN) - - DISALLOW_COPY_AND_ASSIGN(Background); -}; - -} // namespace views - -#endif // UI_VIEWS_BACKGROUND_H_
diff --git a/ui/views/border.cc b/ui/views/border.cc deleted file mode 100644 index dac2daa..0000000 --- a/ui/views/border.cc +++ /dev/null
@@ -1,169 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/border.h" - -#include "base/logging.h" -#include "base/memory/scoped_ptr.h" -#include "ui/gfx/canvas.h" -#include "ui/views/painter.h" -#include "ui/views/view.h" - -namespace views { - -namespace { - -// A simple border with different thicknesses on each side and single color. -class SidedSolidBorder : public Border { - public: - SidedSolidBorder(int top, int left, int bottom, int right, SkColor color); - - // Overridden from Border: - virtual void Paint(const View& view, gfx::Canvas* canvas) override; - virtual gfx::Insets GetInsets() const override; - virtual gfx::Size GetMinimumSize() const override; - - private: - const SkColor color_; - const gfx::Insets insets_; - - DISALLOW_COPY_AND_ASSIGN(SidedSolidBorder); -}; - -SidedSolidBorder::SidedSolidBorder(int top, - int left, - int bottom, - int right, - SkColor color) - : color_(color), - insets_(top, left, bottom, right) { -} - -void SidedSolidBorder::Paint(const View& view, gfx::Canvas* canvas) { - // Top border. - canvas->FillRect(gfx::Rect(0, 0, view.width(), insets_.top()), color_); - // Left border. - canvas->FillRect(gfx::Rect(0, 0, insets_.left(), view.height()), color_); - // Bottom border. - canvas->FillRect(gfx::Rect(0, view.height() - insets_.bottom(), view.width(), - insets_.bottom()), color_); - // Right border. - canvas->FillRect(gfx::Rect(view.width() - insets_.right(), 0, insets_.right(), - view.height()), color_); -} - -gfx::Insets SidedSolidBorder::GetInsets() const { - return insets_; -} - -gfx::Size SidedSolidBorder::GetMinimumSize() const { - return gfx::Size(insets_.width(), insets_.height()); -} - -// A variation of SidedSolidBorder, where each side has the same thickness. -class SolidBorder : public SidedSolidBorder { - public: - SolidBorder(int thickness, SkColor color) - : SidedSolidBorder(thickness, thickness, thickness, thickness, color) { - } - - private: - DISALLOW_COPY_AND_ASSIGN(SolidBorder); -}; - -class EmptyBorder : public Border { - public: - EmptyBorder(int top, int left, int bottom, int right) - : insets_(top, left, bottom, right) {} - - // Overridden from Border: - virtual void Paint(const View& view, gfx::Canvas* canvas) override {} - - virtual gfx::Insets GetInsets() const override { - return insets_; - } - - virtual gfx::Size GetMinimumSize() const override { - return gfx::Size(); - } - - private: - const gfx::Insets insets_; - - DISALLOW_COPY_AND_ASSIGN(EmptyBorder); -}; - -class BorderPainter : public Border { - public: - explicit BorderPainter(Painter* painter, const gfx::Insets& insets) - : painter_(painter), - insets_(insets) { - DCHECK(painter); - } - - virtual ~BorderPainter() {} - - // Overridden from Border: - virtual void Paint(const View& view, gfx::Canvas* canvas) override { - Painter::PaintPainterAt(canvas, painter_.get(), view.GetLocalBounds()); - } - - virtual gfx::Insets GetInsets() const override { - return insets_; - } - - virtual gfx::Size GetMinimumSize() const override { - return painter_->GetMinimumSize(); - } - - private: - scoped_ptr<Painter> painter_; - const gfx::Insets insets_; - - DISALLOW_COPY_AND_ASSIGN(BorderPainter); -}; - -} // namespace - -Border::Border() { -} - -Border::~Border() { -} - -// static -scoped_ptr<Border> Border::NullBorder() { - return scoped_ptr<Border>(); -} - -// static -scoped_ptr<Border> Border::CreateSolidBorder(int thickness, SkColor color) { - return scoped_ptr<Border>(new SolidBorder(thickness, color)); -} - -// static -scoped_ptr<Border> Border::CreateEmptyBorder(int top, - int left, - int bottom, - int right) { - return scoped_ptr<Border>(new EmptyBorder(top, left, bottom, right)); -} - -// static -scoped_ptr<Border> Border::CreateSolidSidedBorder(int top, - int left, - int bottom, - int right, - SkColor color) { - return scoped_ptr<Border>( - new SidedSolidBorder(top, left, bottom, right, color)); -} - -// static -scoped_ptr<Border> Border::CreateBorderPainter(Painter* painter, - const gfx::Insets& insets) { - return scoped_ptr<Border>(new BorderPainter(painter, insets)); -} - -} // namespace views
diff --git a/ui/views/border.h b/ui/views/border.h deleted file mode 100644 index d2657c6..0000000 --- a/ui/views/border.h +++ /dev/null
@@ -1,93 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_BORDER_H_ -#define UI_VIEWS_BORDER_H_ - -#include "base/basictypes.h" -#include "base/memory/scoped_ptr.h" -#include "third_party/skia/include/core/SkColor.h" -#include "ui/gfx/insets.h" -#include "ui/views/views_export.h" - -namespace gfx{ -class Canvas; -class Size; -} - -namespace views { - -class Painter; -class View; - -//////////////////////////////////////////////////////////////////////////////// -// -// Border class. -// -// The border class is used to display a border around a view. -// To set a border on a view, just call SetBorder on the view, for example: -// view->SetBorder(Border::CreateSolidBorder(1, SkColorSetRGB(25, 25, 112)); -// Once set on a view, the border is owned by the view. -// -// IMPORTANT NOTE: not all views support borders at this point. In order to -// support the border, views should make sure to use bounds excluding the -// border (by calling View::GetLocalBoundsExcludingBorder) when doing layout and -// painting. -// -//////////////////////////////////////////////////////////////////////////////// - -class VIEWS_EXPORT Border { - public: - Border(); - virtual ~Border(); - - // Convenience for creating a scoped_ptr with no Border. - static scoped_ptr<Border> NullBorder(); - - // Creates a border that is a simple line of the specified thickness and - // color. - static scoped_ptr<Border> CreateSolidBorder(int thickness, SkColor color); - - // Creates a border for reserving space. The returned border does not - // paint anything. - static scoped_ptr<Border> CreateEmptyBorder(int top, - int left, - int bottom, - int right); - - // Creates a border of the specified color, and specified thickness on each - // side. - static scoped_ptr<Border> CreateSolidSidedBorder(int top, - int left, - int bottom, - int right, - SkColor color); - - // Creates a Border from the specified Painter. The border owns the painter, - // thus the painter is deleted when the Border is deleted. - // |insets| define size of an area allocated for a Border. - static scoped_ptr<Border> CreateBorderPainter(Painter* painter, - const gfx::Insets& insets); - - // Renders the border for the specified view. - virtual void Paint(const View& view, gfx::Canvas* canvas) = 0; - - // Returns the border insets. - virtual gfx::Insets GetInsets() const = 0; - - // Returns the minimum size this border requires. Note that this may not be - // the same as the insets. For example, a Border may paint images to draw - // some graphical border around a view, and this would return the minimum size - // such that these images would not be clipped or overlapping -- but the - // insets may be larger or smaller, depending on how the view wanted its - // content laid out relative to these images. - virtual gfx::Size GetMinimumSize() const = 0; - - private: - DISALLOW_COPY_AND_ASSIGN(Border); -}; - -} // namespace views - -#endif // UI_VIEWS_BORDER_H_
diff --git a/ui/views/bubble/OWNERS b/ui/views/bubble/OWNERS deleted file mode 100644 index 807123d..0000000 --- a/ui/views/bubble/OWNERS +++ /dev/null
@@ -1,2 +0,0 @@ -msw@chromium.org -per-file tray_bubble_view.*=stevenjb@chromium.org
diff --git a/ui/views/bubble/bubble_border.cc b/ui/views/bubble/bubble_border.cc deleted file mode 100644 index 0fd0e3c..0000000 --- a/ui/views/bubble/bubble_border.cc +++ /dev/null
@@ -1,357 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/bubble/bubble_border.h" - -#include <algorithm> - -#include "base/logging.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/rect.h" -#include "ui/gfx/skia_util.h" -#include "ui/resources/grit/ui_resources.h" -#include "ui/views/painter.h" -#include "ui/views/view.h" - -namespace views { - -namespace internal { - -BorderImages::BorderImages(const int border_image_ids[], - const int arrow_image_ids[], - int border_interior_thickness, - int arrow_interior_thickness, - int corner_radius) - : border_painter(Painter::CreateImageGridPainter(border_image_ids)), - border_thickness(0), - border_interior_thickness(border_interior_thickness), - arrow_thickness(0), - arrow_interior_thickness(arrow_interior_thickness), - corner_radius(corner_radius) { - ResourceBundle& rb = ResourceBundle::GetSharedInstance(); - border_thickness = rb.GetImageSkiaNamed(border_image_ids[0])->width(); - if (arrow_image_ids[0] != 0) { - left_arrow = *rb.GetImageSkiaNamed(arrow_image_ids[0]); - top_arrow = *rb.GetImageSkiaNamed(arrow_image_ids[1]); - right_arrow = *rb.GetImageSkiaNamed(arrow_image_ids[2]); - bottom_arrow = *rb.GetImageSkiaNamed(arrow_image_ids[3]); - arrow_thickness = top_arrow.height(); - } -} - -BorderImages::~BorderImages() {} - -} // namespace internal - -namespace { - -// Bubble border and arrow image resource ids. They don't use the IMAGE_GRID -// macro because there is no center image. -const int kNoShadowImages[] = { - IDR_BUBBLE_TL, IDR_BUBBLE_T, IDR_BUBBLE_TR, - IDR_BUBBLE_L, 0, IDR_BUBBLE_R, - IDR_BUBBLE_BL, IDR_BUBBLE_B, IDR_BUBBLE_BR }; -const int kNoShadowArrows[] = { - IDR_BUBBLE_L_ARROW, IDR_BUBBLE_T_ARROW, - IDR_BUBBLE_R_ARROW, IDR_BUBBLE_B_ARROW, }; - -const int kBigShadowImages[] = { - IDR_WINDOW_BUBBLE_SHADOW_BIG_TOP_LEFT, - IDR_WINDOW_BUBBLE_SHADOW_BIG_TOP, - IDR_WINDOW_BUBBLE_SHADOW_BIG_TOP_RIGHT, - IDR_WINDOW_BUBBLE_SHADOW_BIG_LEFT, - 0, - IDR_WINDOW_BUBBLE_SHADOW_BIG_RIGHT, - IDR_WINDOW_BUBBLE_SHADOW_BIG_BOTTOM_LEFT, - IDR_WINDOW_BUBBLE_SHADOW_BIG_BOTTOM, - IDR_WINDOW_BUBBLE_SHADOW_BIG_BOTTOM_RIGHT }; -const int kBigShadowArrows[] = { - IDR_WINDOW_BUBBLE_SHADOW_SPIKE_BIG_LEFT, - IDR_WINDOW_BUBBLE_SHADOW_SPIKE_BIG_TOP, - IDR_WINDOW_BUBBLE_SHADOW_SPIKE_BIG_RIGHT, - IDR_WINDOW_BUBBLE_SHADOW_SPIKE_BIG_BOTTOM }; - -const int kSmallShadowImages[] = { - IDR_WINDOW_BUBBLE_SHADOW_SMALL_TOP_LEFT, - IDR_WINDOW_BUBBLE_SHADOW_SMALL_TOP, - IDR_WINDOW_BUBBLE_SHADOW_SMALL_TOP_RIGHT, - IDR_WINDOW_BUBBLE_SHADOW_SMALL_LEFT, - 0, - IDR_WINDOW_BUBBLE_SHADOW_SMALL_RIGHT, - IDR_WINDOW_BUBBLE_SHADOW_SMALL_BOTTOM_LEFT, - IDR_WINDOW_BUBBLE_SHADOW_SMALL_BOTTOM, - IDR_WINDOW_BUBBLE_SHADOW_SMALL_BOTTOM_RIGHT }; -const int kSmallShadowArrows[] = { - IDR_WINDOW_BUBBLE_SHADOW_SPIKE_SMALL_LEFT, - IDR_WINDOW_BUBBLE_SHADOW_SPIKE_SMALL_TOP, - IDR_WINDOW_BUBBLE_SHADOW_SPIKE_SMALL_RIGHT, - IDR_WINDOW_BUBBLE_SHADOW_SPIKE_SMALL_BOTTOM }; - -using internal::BorderImages; - -// Returns the cached BorderImages for the given |shadow| type. -BorderImages* GetBorderImages(BubbleBorder::Shadow shadow) { - // Keep a cache of bubble border image-set painters, arrows, and metrics. - static BorderImages* kBorderImages[BubbleBorder::SHADOW_COUNT] = { NULL }; - - CHECK_LT(shadow, BubbleBorder::SHADOW_COUNT); - struct BorderImages*& set = kBorderImages[shadow]; - if (set) - return set; - - switch (shadow) { - case BubbleBorder::NO_SHADOW: - case BubbleBorder::NO_SHADOW_OPAQUE_BORDER: - set = new BorderImages(kNoShadowImages, kNoShadowArrows, 6, 7, 4); - break; - case BubbleBorder::BIG_SHADOW: - set = new BorderImages(kBigShadowImages, kBigShadowArrows, 23, 9, 2); - break; - case BubbleBorder::SMALL_SHADOW: - set = new BorderImages(kSmallShadowImages, kSmallShadowArrows, 5, 6, 2); - break; - case BubbleBorder::SHADOW_COUNT: - NOTREACHED(); - break; - } - - return set; -} - -} // namespace - -const int BubbleBorder::kStroke = 1; - -BubbleBorder::BubbleBorder(Arrow arrow, Shadow shadow, SkColor color) - : arrow_(arrow), - arrow_offset_(0), - arrow_paint_type_(PAINT_NORMAL), - alignment_(ALIGN_ARROW_TO_MID_ANCHOR), - shadow_(shadow), - background_color_(color), - use_theme_background_color_(false) { - DCHECK(shadow < SHADOW_COUNT); - images_ = GetBorderImages(shadow); -} - -BubbleBorder::~BubbleBorder() {} - -gfx::Rect BubbleBorder::GetBounds(const gfx::Rect& anchor_rect, - const gfx::Size& contents_size) const { - int x = anchor_rect.x(); - int y = anchor_rect.y(); - int w = anchor_rect.width(); - int h = anchor_rect.height(); - const gfx::Size size(GetSizeForContentsSize(contents_size)); - const int arrow_offset = GetArrowOffset(size); - const int arrow_size = - images_->arrow_interior_thickness + kStroke - images_->arrow_thickness; - const bool mid_anchor = alignment_ == ALIGN_ARROW_TO_MID_ANCHOR; - - // Calculate the bubble coordinates based on the border and arrow settings. - if (is_arrow_on_horizontal(arrow_)) { - if (is_arrow_on_left(arrow_)) { - x += mid_anchor ? w / 2 - arrow_offset : kStroke - GetBorderThickness(); - } else if (is_arrow_at_center(arrow_)) { - x += w / 2 - arrow_offset; - } else { - x += mid_anchor ? w / 2 + arrow_offset - size.width() : - w - size.width() + GetBorderThickness() - kStroke; - } - y += is_arrow_on_top(arrow_) ? h + arrow_size : -arrow_size - size.height(); - } else if (has_arrow(arrow_)) { - x += is_arrow_on_left(arrow_) ? w + arrow_size : -arrow_size - size.width(); - if (is_arrow_on_top(arrow_)) { - y += mid_anchor ? h / 2 - arrow_offset : kStroke - GetBorderThickness(); - } else if (is_arrow_at_center(arrow_)) { - y += h / 2 - arrow_offset; - } else { - y += mid_anchor ? h / 2 + arrow_offset - size.height() : - h - size.height() + GetBorderThickness() - kStroke; - } - } else { - x += (w - size.width()) / 2; - y += (arrow_ == NONE) ? h : (h - size.height()) / 2; - } - - return gfx::Rect(x, y, size.width(), size.height()); -} - -int BubbleBorder::GetBorderThickness() const { - return images_->border_thickness - images_->border_interior_thickness; -} - -int BubbleBorder::GetBorderCornerRadius() const { - return images_->corner_radius; -} - -int BubbleBorder::GetArrowOffset(const gfx::Size& border_size) const { - const int edge_length = is_arrow_on_horizontal(arrow_) ? - border_size.width() : border_size.height(); - if (is_arrow_at_center(arrow_) && arrow_offset_ == 0) - return edge_length / 2; - - // Calculate the minimum offset to not overlap arrow and corner images. - const int min = images_->border_thickness + (images_->top_arrow.width() / 2); - // Ensure the returned value will not cause image overlap, if possible. - return std::max(min, std::min(arrow_offset_, edge_length - min)); -} - -void BubbleBorder::Paint(const views::View& view, gfx::Canvas* canvas) { - gfx::Rect bounds(view.GetContentsBounds()); - bounds.Inset(-GetBorderThickness(), -GetBorderThickness()); - const gfx::Rect arrow_bounds = GetArrowRect(view.GetLocalBounds()); - if (arrow_bounds.IsEmpty()) { - Painter::PaintPainterAt(canvas, images_->border_painter.get(), bounds); - return; - } - - // Clip the arrow bounds out to avoid painting the overlapping edge area. - canvas->Save(); - SkRect arrow_rect(gfx::RectToSkRect(arrow_bounds)); - canvas->sk_canvas()->clipRect(arrow_rect, SkRegion::kDifference_Op); - Painter::PaintPainterAt(canvas, images_->border_painter.get(), bounds); - canvas->Restore(); - - DrawArrow(canvas, arrow_bounds); -} - -gfx::Insets BubbleBorder::GetInsets() const { - // The insets contain the stroke and shadow pixels outside the bubble fill. - const int inset = GetBorderThickness(); - if ((arrow_paint_type_ == PAINT_NONE) || !has_arrow(arrow_)) - return gfx::Insets(inset, inset, inset, inset); - - int first_inset = inset; - int second_inset = std::max(inset, images_->arrow_thickness); - if (is_arrow_on_horizontal(arrow_) ? - is_arrow_on_top(arrow_) : is_arrow_on_left(arrow_)) - std::swap(first_inset, second_inset); - return is_arrow_on_horizontal(arrow_) ? - gfx::Insets(first_inset, inset, second_inset, inset) : - gfx::Insets(inset, first_inset, inset, second_inset); -} - -gfx::Size BubbleBorder::GetMinimumSize() const { - return GetSizeForContentsSize(gfx::Size()); -} - -gfx::Size BubbleBorder::GetSizeForContentsSize( - const gfx::Size& contents_size) const { - // Enlarge the contents size by the thickness of the border images. - gfx::Size size(contents_size); - const gfx::Insets insets = GetInsets(); - size.Enlarge(insets.width(), insets.height()); - - // Ensure the bubble is large enough to not overlap border and arrow images. - const int min = 2 * images_->border_thickness; - const int min_with_arrow_width = min + images_->top_arrow.width(); - const int min_with_arrow_thickness = images_->border_thickness + - std::max(images_->arrow_thickness + images_->border_interior_thickness, - images_->border_thickness); - // Only take arrow image sizes into account when the bubble tip is shown. - if (arrow_paint_type_ == PAINT_NONE || !has_arrow(arrow_)) - size.SetToMax(gfx::Size(min, min)); - else if (is_arrow_on_horizontal(arrow_)) - size.SetToMax(gfx::Size(min_with_arrow_width, min_with_arrow_thickness)); - else - size.SetToMax(gfx::Size(min_with_arrow_thickness, min_with_arrow_width)); - return size; -} - -gfx::ImageSkia* BubbleBorder::GetArrowImage() const { - if (!has_arrow(arrow_)) - return NULL; - if (is_arrow_on_horizontal(arrow_)) { - return is_arrow_on_top(arrow_) ? - &images_->top_arrow : &images_->bottom_arrow; - } - return is_arrow_on_left(arrow_) ? - &images_->left_arrow : &images_->right_arrow; -} - -gfx::Rect BubbleBorder::GetArrowRect(const gfx::Rect& bounds) const { - if (!has_arrow(arrow_) || arrow_paint_type_ != PAINT_NORMAL) - return gfx::Rect(); - - gfx::Point origin; - int offset = GetArrowOffset(bounds.size()); - const int half_length = images_->top_arrow.width() / 2; - const gfx::Insets insets = GetInsets(); - - if (is_arrow_on_horizontal(arrow_)) { - origin.set_x(is_arrow_on_left(arrow_) || is_arrow_at_center(arrow_) ? - offset : bounds.width() - offset); - origin.Offset(-half_length, 0); - if (is_arrow_on_top(arrow_)) - origin.set_y(insets.top() - images_->arrow_thickness); - else - origin.set_y(bounds.height() - insets.bottom()); - } else { - origin.set_y(is_arrow_on_top(arrow_) || is_arrow_at_center(arrow_) ? - offset : bounds.height() - offset); - origin.Offset(0, -half_length); - if (is_arrow_on_left(arrow_)) - origin.set_x(insets.left() - images_->arrow_thickness); - else - origin.set_x(bounds.width() - insets.right()); - } - return gfx::Rect(origin, GetArrowImage()->size()); -} - -void BubbleBorder::DrawArrow(gfx::Canvas* canvas, - const gfx::Rect& arrow_bounds) const { - canvas->DrawImageInt(*GetArrowImage(), arrow_bounds.x(), arrow_bounds.y()); - const bool horizontal = is_arrow_on_horizontal(arrow_); - const int thickness = images_->arrow_interior_thickness; - float tip_x = horizontal ? arrow_bounds.CenterPoint().x() : - is_arrow_on_left(arrow_) ? arrow_bounds.right() - thickness : - arrow_bounds.x() + thickness; - float tip_y = !horizontal ? arrow_bounds.CenterPoint().y() + 0.5f : - is_arrow_on_top(arrow_) ? arrow_bounds.bottom() - thickness : - arrow_bounds.y() + thickness; - const bool positive_offset = horizontal ? - is_arrow_on_top(arrow_) : is_arrow_on_left(arrow_); - const int offset_to_next_vertex = positive_offset ? - images_->arrow_interior_thickness : -images_->arrow_interior_thickness; - - SkPath path; - path.incReserve(4); - path.moveTo(SkDoubleToScalar(tip_x), SkDoubleToScalar(tip_y)); - path.lineTo(SkDoubleToScalar(tip_x + offset_to_next_vertex), - SkDoubleToScalar(tip_y + offset_to_next_vertex)); - const int multiplier = horizontal ? 1 : -1; - path.lineTo(SkDoubleToScalar(tip_x - multiplier * offset_to_next_vertex), - SkDoubleToScalar(tip_y + multiplier * offset_to_next_vertex)); - path.close(); - - SkPaint paint; - paint.setStyle(SkPaint::kFill_Style); - paint.setColor(background_color_); - - canvas->DrawPath(path, paint); -} - -internal::BorderImages* BubbleBorder::GetImagesForTest() const { - return images_; -} - -void BubbleBackground::Paint(gfx::Canvas* canvas, views::View* view) const { - if (border_->shadow() == BubbleBorder::NO_SHADOW_OPAQUE_BORDER) - canvas->DrawColor(border_->background_color()); - - // Fill the contents with a round-rect region to match the border images. - SkPaint paint; - paint.setAntiAlias(true); - paint.setStyle(SkPaint::kFill_Style); - paint.setColor(border_->background_color()); - SkPath path; - gfx::Rect bounds(view->GetLocalBounds()); - bounds.Inset(border_->GetInsets()); - - canvas->DrawRoundRect(bounds, border_->GetBorderCornerRadius(), paint); -} - -} // namespace views
diff --git a/ui/views/bubble/bubble_border.h b/ui/views/bubble/bubble_border.h deleted file mode 100644 index 8fc149b..0000000 --- a/ui/views/bubble/bubble_border.h +++ /dev/null
@@ -1,246 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_BUBBLE_BUBBLE_BORDER_H_ -#define UI_VIEWS_BUBBLE_BUBBLE_BORDER_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "ui/gfx/image/image_skia.h" -#include "ui/views/background.h" -#include "ui/views/border.h" - -namespace gfx { -class Rect; -} - -namespace views { -class Painter; - -namespace internal { - -// A helper that combines each border image-set painter with arrows and metrics. -struct BorderImages { - BorderImages(const int border_image_ids[], - const int arrow_image_ids[], - int border_interior_thickness, - int arrow_interior_thickness, - int corner_radius); - virtual ~BorderImages(); - - scoped_ptr<Painter> border_painter; - gfx::ImageSkia left_arrow; - gfx::ImageSkia top_arrow; - gfx::ImageSkia right_arrow; - gfx::ImageSkia bottom_arrow; - - // The thickness of border and arrow images and their interior areas. - // Thickness is the width of left/right and the height of top/bottom images. - // The interior is measured without including stroke or shadow pixels. - int border_thickness; - int border_interior_thickness; - int arrow_thickness; - int arrow_interior_thickness; - // The corner radius of the bubble's rounded-rect interior area. - int corner_radius; -}; - -} // namespace internal - -// Renders a border, with optional arrow, and a custom dropshadow. -// This can be used to produce floating "bubble" objects with rounded corners. -class VIEWS_EXPORT BubbleBorder : public Border { - public: - // Possible locations for the (optional) arrow. - // 0 bit specifies left or right. - // 1 bit specifies top or bottom. - // 2 bit specifies horizontal or vertical. - // 3 bit specifies whether the arrow at the center of its residing edge. - enum ArrowMask { - RIGHT = 0x01, - BOTTOM = 0x02, - VERTICAL = 0x04, - CENTER = 0x08, - }; - - enum Arrow { - TOP_LEFT = 0, - TOP_RIGHT = RIGHT, - BOTTOM_LEFT = BOTTOM, - BOTTOM_RIGHT = BOTTOM | RIGHT, - LEFT_TOP = VERTICAL, - RIGHT_TOP = VERTICAL | RIGHT, - LEFT_BOTTOM = VERTICAL | BOTTOM, - RIGHT_BOTTOM = VERTICAL | BOTTOM | RIGHT, - TOP_CENTER = CENTER, - BOTTOM_CENTER = CENTER | BOTTOM, - LEFT_CENTER = CENTER | VERTICAL, - RIGHT_CENTER = CENTER | VERTICAL | RIGHT, - NONE = 16, // No arrow. Positioned under the supplied rect. - FLOAT = 17, // No arrow. Centered over the supplied rect. - }; - - enum Shadow { - NO_SHADOW = 0, - NO_SHADOW_OPAQUE_BORDER, - BIG_SHADOW, - SMALL_SHADOW, - SHADOW_COUNT, - }; - - // The position of the bubble in relation to the anchor. - enum BubbleAlignment { - // The tip of the arrow points to the middle of the anchor. - ALIGN_ARROW_TO_MID_ANCHOR, - // The edge nearest to the arrow is lined up with the edge of the anchor. - ALIGN_EDGE_TO_ANCHOR_EDGE, - }; - - // The way the arrow should be painted. - enum ArrowPaintType { - // Fully render the arrow. - PAINT_NORMAL, - // Leave space for the arrow, but do not paint it. - PAINT_TRANSPARENT, - // Neither paint nor leave space for the arrow. - PAINT_NONE, - }; - - BubbleBorder(Arrow arrow, Shadow shadow, SkColor color); - virtual ~BubbleBorder(); - - // Returns the radius of the corner of the border. - // TODO(xiyuan): Get rid of this since it's part of BorderImages now? - static int GetCornerRadius() { - // We can't safely calculate a border radius by comparing the sizes of the - // side and corner images, because either may have been extended in various - // directions in order to do more subtle dropshadow fading or other effects. - // So we hardcode the most accurate value. - return 4; - } - - static bool has_arrow(Arrow a) { return a < NONE; } - - static bool is_arrow_on_left(Arrow a) { - return has_arrow(a) && (a == LEFT_CENTER || !(a & (RIGHT | CENTER))); - } - - static bool is_arrow_on_top(Arrow a) { - return has_arrow(a) && (a == TOP_CENTER || !(a & (BOTTOM | CENTER))); - } - - static bool is_arrow_on_horizontal(Arrow a) { - return a >= NONE ? false : !(a & VERTICAL); - } - - static bool is_arrow_at_center(Arrow a) { - return has_arrow(a) && !!(a & CENTER); - } - - static Arrow horizontal_mirror(Arrow a) { - return (a == TOP_CENTER || a == BOTTOM_CENTER || a >= NONE) ? - a : static_cast<Arrow>(a ^ RIGHT); - } - - static Arrow vertical_mirror(Arrow a) { - return (a == LEFT_CENTER || a == RIGHT_CENTER || a >= NONE) ? - a : static_cast<Arrow>(a ^ BOTTOM); - } - - // Get or set the arrow type. - void set_arrow(Arrow arrow) { arrow_ = arrow; } - Arrow arrow() const { return arrow_; } - - // Get or set the bubble alignment. - void set_alignment(BubbleAlignment alignment) { alignment_ = alignment; } - BubbleAlignment alignment() const { return alignment_; } - - // Get the shadow type. - Shadow shadow() const { return shadow_; } - - // Get or set the background color for the bubble and arrow body. - void set_background_color(SkColor color) { background_color_ = color; } - SkColor background_color() const { return background_color_; } - - // If true, the background color should be determined by the host's - // NativeTheme. - void set_use_theme_background_color(bool use_theme_background_color) { - use_theme_background_color_ = use_theme_background_color; - } - bool use_theme_background_color() { return use_theme_background_color_; } - - // Sets a desired pixel distance between the arrow tip and the outside edge of - // the neighboring border image. For example: |----offset----| - // '(' represents shadow around the '{' edge: ((({ ^ }))) - // The arrow will still anchor to the same location but the bubble will shift - // location to place the arrow |offset| pixels from the perpendicular edge. - void set_arrow_offset(int offset) { arrow_offset_ = offset; } - - // Sets the way the arrow is actually painted. Default is PAINT_NORMAL. - void set_paint_arrow(ArrowPaintType value) { arrow_paint_type_ = value; } - - // Get the desired widget bounds (in screen coordinates) given the anchor rect - // and bubble content size; calculated from shadow and arrow image dimensions. - virtual gfx::Rect GetBounds(const gfx::Rect& anchor_rect, - const gfx::Size& contents_size) const; - - // Get the border exterior thickness, including stroke and shadow, in pixels. - int GetBorderThickness() const; - - // Returns the corner radius of the current image set. - int GetBorderCornerRadius() const; - - // Gets the arrow offset to use. - int GetArrowOffset(const gfx::Size& border_size) const; - - // Overridden from Border: - virtual void Paint(const View& view, gfx::Canvas* canvas) override; - virtual gfx::Insets GetInsets() const override; - virtual gfx::Size GetMinimumSize() const override; - - private: - FRIEND_TEST_ALL_PREFIXES(BubbleBorderTest, GetSizeForContentsSizeTest); - FRIEND_TEST_ALL_PREFIXES(BubbleBorderTest, GetBoundsOriginTest); - - // The border and arrow stroke size used in image assets, in pixels. - static const int kStroke; - - gfx::Size GetSizeForContentsSize(const gfx::Size& contents_size) const; - gfx::ImageSkia* GetArrowImage() const; - gfx::Rect GetArrowRect(const gfx::Rect& bounds) const; - void DrawArrow(gfx::Canvas* canvas, const gfx::Rect& arrow_bounds) const; - - internal::BorderImages* GetImagesForTest() const; - - Arrow arrow_; - int arrow_offset_; - ArrowPaintType arrow_paint_type_; - BubbleAlignment alignment_; - Shadow shadow_; - internal::BorderImages* images_; - SkColor background_color_; - bool use_theme_background_color_; - - DISALLOW_COPY_AND_ASSIGN(BubbleBorder); -}; - -// A Background that clips itself to the specified BubbleBorder and uses -// the background color of the BubbleBorder. -class VIEWS_EXPORT BubbleBackground : public Background { - public: - explicit BubbleBackground(BubbleBorder* border) : border_(border) {} - - // Overridden from Background: - virtual void Paint(gfx::Canvas* canvas, View* view) const override; - - private: - BubbleBorder* border_; - - DISALLOW_COPY_AND_ASSIGN(BubbleBackground); -}; - -} // namespace views - -#endif // UI_VIEWS_BUBBLE_BUBBLE_BORDER_H_
diff --git a/ui/views/bubble/bubble_border_unittest.cc b/ui/views/bubble/bubble_border_unittest.cc deleted file mode 100644 index 404902c..0000000 --- a/ui/views/bubble/bubble_border_unittest.cc +++ /dev/null
@@ -1,415 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/bubble/bubble_border.h" - -#include "base/memory/scoped_ptr.h" -#include "base/strings/stringprintf.h" -#include "ui/views/test/views_test_base.h" - -namespace views { - -typedef views::ViewsTestBase BubbleBorderTest; - -TEST_F(BubbleBorderTest, GetMirroredArrow) { - // Horizontal mirroring. - EXPECT_EQ(BubbleBorder::TOP_RIGHT, - BubbleBorder::horizontal_mirror(BubbleBorder::TOP_LEFT)); - EXPECT_EQ(BubbleBorder::TOP_LEFT, - BubbleBorder::horizontal_mirror(BubbleBorder::TOP_RIGHT)); - - EXPECT_EQ(BubbleBorder::BOTTOM_RIGHT, - BubbleBorder::horizontal_mirror(BubbleBorder::BOTTOM_LEFT)); - EXPECT_EQ(BubbleBorder::BOTTOM_LEFT, - BubbleBorder::horizontal_mirror(BubbleBorder::BOTTOM_RIGHT)); - - EXPECT_EQ(BubbleBorder::RIGHT_TOP, - BubbleBorder::horizontal_mirror(BubbleBorder::LEFT_TOP)); - EXPECT_EQ(BubbleBorder::LEFT_TOP, - BubbleBorder::horizontal_mirror(BubbleBorder::RIGHT_TOP)); - - EXPECT_EQ(BubbleBorder::RIGHT_BOTTOM, - BubbleBorder::horizontal_mirror(BubbleBorder::LEFT_BOTTOM)); - EXPECT_EQ(BubbleBorder::LEFT_BOTTOM, - BubbleBorder::horizontal_mirror(BubbleBorder::RIGHT_BOTTOM)); - - EXPECT_EQ(BubbleBorder::TOP_CENTER, - BubbleBorder::horizontal_mirror(BubbleBorder::TOP_CENTER)); - EXPECT_EQ(BubbleBorder::BOTTOM_CENTER, - BubbleBorder::horizontal_mirror(BubbleBorder::BOTTOM_CENTER)); - - EXPECT_EQ(BubbleBorder::RIGHT_CENTER, - BubbleBorder::horizontal_mirror(BubbleBorder::LEFT_CENTER)); - EXPECT_EQ(BubbleBorder::LEFT_CENTER, - BubbleBorder::horizontal_mirror(BubbleBorder::RIGHT_CENTER)); - - EXPECT_EQ(BubbleBorder::NONE, - BubbleBorder::horizontal_mirror(BubbleBorder::NONE)); - EXPECT_EQ(BubbleBorder::FLOAT, - BubbleBorder::horizontal_mirror(BubbleBorder::FLOAT)); - - // Vertical mirroring. - EXPECT_EQ(BubbleBorder::BOTTOM_LEFT, - BubbleBorder::vertical_mirror(BubbleBorder::TOP_LEFT)); - EXPECT_EQ(BubbleBorder::BOTTOM_RIGHT, - BubbleBorder::vertical_mirror(BubbleBorder::TOP_RIGHT)); - - EXPECT_EQ(BubbleBorder::TOP_LEFT, - BubbleBorder::vertical_mirror(BubbleBorder::BOTTOM_LEFT)); - EXPECT_EQ(BubbleBorder::TOP_RIGHT, - BubbleBorder::vertical_mirror(BubbleBorder::BOTTOM_RIGHT)); - - EXPECT_EQ(BubbleBorder::LEFT_BOTTOM, - BubbleBorder::vertical_mirror(BubbleBorder::LEFT_TOP)); - EXPECT_EQ(BubbleBorder::RIGHT_BOTTOM, - BubbleBorder::vertical_mirror(BubbleBorder::RIGHT_TOP)); - - EXPECT_EQ(BubbleBorder::LEFT_TOP, - BubbleBorder::vertical_mirror(BubbleBorder::LEFT_BOTTOM)); - EXPECT_EQ(BubbleBorder::RIGHT_TOP, - BubbleBorder::vertical_mirror(BubbleBorder::RIGHT_BOTTOM)); - - EXPECT_EQ(BubbleBorder::BOTTOM_CENTER, - BubbleBorder::vertical_mirror(BubbleBorder::TOP_CENTER)); - EXPECT_EQ(BubbleBorder::TOP_CENTER, - BubbleBorder::vertical_mirror(BubbleBorder::BOTTOM_CENTER)); - - EXPECT_EQ(BubbleBorder::LEFT_CENTER, - BubbleBorder::vertical_mirror(BubbleBorder::LEFT_CENTER)); - EXPECT_EQ(BubbleBorder::RIGHT_CENTER, - BubbleBorder::vertical_mirror(BubbleBorder::RIGHT_CENTER)); - - EXPECT_EQ(BubbleBorder::NONE, - BubbleBorder::vertical_mirror(BubbleBorder::NONE)); - EXPECT_EQ(BubbleBorder::FLOAT, - BubbleBorder::vertical_mirror(BubbleBorder::FLOAT)); -} - -TEST_F(BubbleBorderTest, HasArrow) { - EXPECT_TRUE(BubbleBorder::has_arrow(BubbleBorder::TOP_LEFT)); - EXPECT_TRUE(BubbleBorder::has_arrow(BubbleBorder::TOP_RIGHT)); - - EXPECT_TRUE(BubbleBorder::has_arrow(BubbleBorder::BOTTOM_LEFT)); - EXPECT_TRUE(BubbleBorder::has_arrow(BubbleBorder::BOTTOM_RIGHT)); - - EXPECT_TRUE(BubbleBorder::has_arrow(BubbleBorder::LEFT_TOP)); - EXPECT_TRUE(BubbleBorder::has_arrow(BubbleBorder::RIGHT_TOP)); - - EXPECT_TRUE(BubbleBorder::has_arrow(BubbleBorder::LEFT_BOTTOM)); - EXPECT_TRUE(BubbleBorder::has_arrow(BubbleBorder::RIGHT_BOTTOM)); - - EXPECT_TRUE(BubbleBorder::has_arrow(BubbleBorder::TOP_CENTER)); - EXPECT_TRUE(BubbleBorder::has_arrow(BubbleBorder::BOTTOM_CENTER)); - - EXPECT_TRUE(BubbleBorder::has_arrow(BubbleBorder::LEFT_CENTER)); - EXPECT_TRUE(BubbleBorder::has_arrow(BubbleBorder::RIGHT_CENTER)); - - EXPECT_FALSE(BubbleBorder::has_arrow(BubbleBorder::NONE)); - EXPECT_FALSE(BubbleBorder::has_arrow(BubbleBorder::FLOAT)); -} - -TEST_F(BubbleBorderTest, IsArrowOnLeft) { - EXPECT_TRUE(BubbleBorder::is_arrow_on_left(BubbleBorder::TOP_LEFT)); - EXPECT_FALSE(BubbleBorder::is_arrow_on_left(BubbleBorder::TOP_RIGHT)); - - EXPECT_TRUE(BubbleBorder::is_arrow_on_left(BubbleBorder::BOTTOM_LEFT)); - EXPECT_FALSE(BubbleBorder::is_arrow_on_left(BubbleBorder::BOTTOM_RIGHT)); - - EXPECT_TRUE(BubbleBorder::is_arrow_on_left(BubbleBorder::LEFT_TOP)); - EXPECT_FALSE(BubbleBorder::is_arrow_on_left(BubbleBorder::RIGHT_TOP)); - - EXPECT_TRUE(BubbleBorder::is_arrow_on_left(BubbleBorder::LEFT_BOTTOM)); - EXPECT_FALSE(BubbleBorder::is_arrow_on_left(BubbleBorder::RIGHT_BOTTOM)); - - EXPECT_FALSE(BubbleBorder::is_arrow_on_left(BubbleBorder::TOP_CENTER)); - EXPECT_FALSE(BubbleBorder::is_arrow_on_left(BubbleBorder::BOTTOM_CENTER)); - - EXPECT_TRUE(BubbleBorder::is_arrow_on_left(BubbleBorder::LEFT_CENTER)); - EXPECT_FALSE(BubbleBorder::is_arrow_on_left(BubbleBorder::RIGHT_CENTER)); - - EXPECT_FALSE(BubbleBorder::is_arrow_on_left(BubbleBorder::NONE)); - EXPECT_FALSE(BubbleBorder::is_arrow_on_left(BubbleBorder::FLOAT)); -} - -TEST_F(BubbleBorderTest, IsArrowOnTop) { - EXPECT_TRUE(BubbleBorder::is_arrow_on_top(BubbleBorder::TOP_LEFT)); - EXPECT_TRUE(BubbleBorder::is_arrow_on_top(BubbleBorder::TOP_RIGHT)); - - EXPECT_FALSE(BubbleBorder::is_arrow_on_top(BubbleBorder::BOTTOM_LEFT)); - EXPECT_FALSE(BubbleBorder::is_arrow_on_top(BubbleBorder::BOTTOM_RIGHT)); - - EXPECT_TRUE(BubbleBorder::is_arrow_on_top(BubbleBorder::LEFT_TOP)); - EXPECT_TRUE(BubbleBorder::is_arrow_on_top(BubbleBorder::RIGHT_TOP)); - - EXPECT_FALSE(BubbleBorder::is_arrow_on_top(BubbleBorder::LEFT_BOTTOM)); - EXPECT_FALSE(BubbleBorder::is_arrow_on_top(BubbleBorder::RIGHT_BOTTOM)); - - EXPECT_TRUE(BubbleBorder::is_arrow_on_top(BubbleBorder::TOP_CENTER)); - EXPECT_FALSE(BubbleBorder::is_arrow_on_top(BubbleBorder::BOTTOM_CENTER)); - - EXPECT_FALSE(BubbleBorder::is_arrow_on_top(BubbleBorder::LEFT_CENTER)); - EXPECT_FALSE(BubbleBorder::is_arrow_on_top(BubbleBorder::RIGHT_CENTER)); - - EXPECT_FALSE(BubbleBorder::is_arrow_on_top(BubbleBorder::NONE)); - EXPECT_FALSE(BubbleBorder::is_arrow_on_top(BubbleBorder::FLOAT)); -} - -TEST_F(BubbleBorderTest, IsArrowOnHorizontal) { - EXPECT_TRUE(BubbleBorder::is_arrow_on_horizontal(BubbleBorder::TOP_LEFT)); - EXPECT_TRUE(BubbleBorder::is_arrow_on_horizontal(BubbleBorder::TOP_RIGHT)); - - EXPECT_TRUE(BubbleBorder::is_arrow_on_horizontal(BubbleBorder::BOTTOM_LEFT)); - EXPECT_TRUE(BubbleBorder::is_arrow_on_horizontal(BubbleBorder::BOTTOM_RIGHT)); - - EXPECT_FALSE(BubbleBorder::is_arrow_on_horizontal(BubbleBorder::LEFT_TOP)); - EXPECT_FALSE(BubbleBorder::is_arrow_on_horizontal(BubbleBorder::RIGHT_TOP)); - - EXPECT_FALSE(BubbleBorder::is_arrow_on_horizontal(BubbleBorder::LEFT_BOTTOM)); - EXPECT_FALSE( - BubbleBorder::is_arrow_on_horizontal(BubbleBorder::RIGHT_BOTTOM)); - - EXPECT_TRUE(BubbleBorder::is_arrow_on_horizontal(BubbleBorder::TOP_CENTER)); - EXPECT_TRUE( - BubbleBorder::is_arrow_on_horizontal(BubbleBorder::BOTTOM_CENTER)); - - EXPECT_FALSE(BubbleBorder::is_arrow_on_horizontal(BubbleBorder::LEFT_CENTER)); - EXPECT_FALSE( - BubbleBorder::is_arrow_on_horizontal(BubbleBorder::RIGHT_CENTER)); - - EXPECT_FALSE(BubbleBorder::is_arrow_on_horizontal(BubbleBorder::NONE)); - EXPECT_FALSE(BubbleBorder::is_arrow_on_horizontal(BubbleBorder::FLOAT)); -} - -TEST_F(BubbleBorderTest, IsArrowAtCenter) { - EXPECT_FALSE(BubbleBorder::is_arrow_at_center(BubbleBorder::TOP_LEFT)); - EXPECT_FALSE(BubbleBorder::is_arrow_at_center(BubbleBorder::TOP_RIGHT)); - - EXPECT_FALSE(BubbleBorder::is_arrow_at_center(BubbleBorder::BOTTOM_LEFT)); - EXPECT_FALSE(BubbleBorder::is_arrow_at_center(BubbleBorder::BOTTOM_RIGHT)); - - EXPECT_FALSE(BubbleBorder::is_arrow_at_center(BubbleBorder::LEFT_TOP)); - EXPECT_FALSE(BubbleBorder::is_arrow_at_center(BubbleBorder::RIGHT_TOP)); - - EXPECT_FALSE(BubbleBorder::is_arrow_at_center(BubbleBorder::LEFT_BOTTOM)); - EXPECT_FALSE(BubbleBorder::is_arrow_at_center(BubbleBorder::RIGHT_BOTTOM)); - - EXPECT_TRUE(BubbleBorder::is_arrow_at_center(BubbleBorder::TOP_CENTER)); - EXPECT_TRUE(BubbleBorder::is_arrow_at_center(BubbleBorder::BOTTOM_CENTER)); - - EXPECT_TRUE(BubbleBorder::is_arrow_at_center(BubbleBorder::LEFT_CENTER)); - EXPECT_TRUE(BubbleBorder::is_arrow_at_center(BubbleBorder::RIGHT_CENTER)); - - EXPECT_FALSE(BubbleBorder::is_arrow_at_center(BubbleBorder::NONE)); - EXPECT_FALSE(BubbleBorder::is_arrow_at_center(BubbleBorder::FLOAT)); -} - -TEST_F(BubbleBorderTest, GetSizeForContentsSizeTest) { - views::BubbleBorder border(BubbleBorder::NONE, - BubbleBorder::NO_SHADOW, - SK_ColorWHITE); - - const views::internal::BorderImages* kImages = border.GetImagesForTest(); - - // kSmallSize is smaller than the minimum allowable size and does not - // contribute to the resulting size. - const gfx::Size kSmallSize = gfx::Size(1, 2); - // kMediumSize is larger than the minimum allowable size and contributes to - // the resulting size. - const gfx::Size kMediumSize = gfx::Size(50, 60); - - const gfx::Size kSmallHorizArrow( - 2 * kImages->border_thickness + kImages->top_arrow.width(), - kImages->border_thickness + kImages->arrow_thickness + - kImages->border_interior_thickness); - - const gfx::Size kSmallVertArrow(kSmallHorizArrow.height(), - kSmallHorizArrow.width()); - - const gfx::Size kSmallNoArrow(2 * kImages->border_thickness, - 2 * kImages->border_thickness); - - const gfx::Size kMediumHorizArrow( - kMediumSize.width() + 2 * border.GetBorderThickness(), - kMediumSize.height() + border.GetBorderThickness() + - kImages->arrow_thickness); - - const gfx::Size kMediumVertArrow( - kMediumSize.width() + border.GetBorderThickness() + - kImages->arrow_thickness, - kMediumSize.height() + 2 * border.GetBorderThickness()); - - const gfx::Size kMediumNoArrow( - kMediumSize.width() + 2 * border.GetBorderThickness(), - kMediumSize.height() + 2 * border.GetBorderThickness()); - - struct TestCase { - BubbleBorder::Arrow arrow; - gfx::Size content; - gfx::Size expected_with_arrow; - gfx::Size expected_without_arrow; - }; - - TestCase cases[] = { - // Content size: kSmallSize - { BubbleBorder::TOP_LEFT, kSmallSize, kSmallHorizArrow, kSmallNoArrow }, - { BubbleBorder::TOP_CENTER, kSmallSize, kSmallHorizArrow, kSmallNoArrow }, - { BubbleBorder::TOP_RIGHT, kSmallSize, kSmallHorizArrow, kSmallNoArrow }, - { BubbleBorder::BOTTOM_LEFT, kSmallSize, kSmallHorizArrow, kSmallNoArrow }, - { BubbleBorder::BOTTOM_CENTER, kSmallSize, kSmallHorizArrow, - kSmallNoArrow }, - { BubbleBorder::BOTTOM_RIGHT, kSmallSize, kSmallHorizArrow, kSmallNoArrow }, - { BubbleBorder::LEFT_TOP, kSmallSize, kSmallVertArrow, kSmallNoArrow }, - { BubbleBorder::LEFT_CENTER, kSmallSize, kSmallVertArrow, kSmallNoArrow }, - { BubbleBorder::LEFT_BOTTOM, kSmallSize, kSmallVertArrow, kSmallNoArrow }, - { BubbleBorder::RIGHT_TOP, kSmallSize, kSmallVertArrow, kSmallNoArrow }, - { BubbleBorder::RIGHT_CENTER, kSmallSize, kSmallVertArrow, kSmallNoArrow }, - { BubbleBorder::RIGHT_BOTTOM, kSmallSize, kSmallVertArrow, kSmallNoArrow }, - { BubbleBorder::NONE, kSmallSize, kSmallNoArrow, kSmallNoArrow }, - { BubbleBorder::FLOAT, kSmallSize, kSmallNoArrow, kSmallNoArrow }, - - // Content size: kMediumSize - { BubbleBorder::TOP_LEFT, kMediumSize, kMediumHorizArrow, kMediumNoArrow }, - { BubbleBorder::TOP_CENTER, kMediumSize, kMediumHorizArrow, - kMediumNoArrow }, - { BubbleBorder::TOP_RIGHT, kMediumSize, kMediumHorizArrow, kMediumNoArrow }, - { BubbleBorder::BOTTOM_LEFT, kMediumSize, kMediumHorizArrow, - kMediumNoArrow }, - { BubbleBorder::BOTTOM_CENTER, kMediumSize, kMediumHorizArrow, - kMediumNoArrow }, - { BubbleBorder::BOTTOM_RIGHT, kMediumSize, kMediumHorizArrow, - kMediumNoArrow }, - { BubbleBorder::LEFT_TOP, kMediumSize, kMediumVertArrow, kMediumNoArrow }, - { BubbleBorder::LEFT_CENTER, kMediumSize, kMediumVertArrow, - kMediumNoArrow }, - { BubbleBorder::LEFT_BOTTOM, kMediumSize, kMediumVertArrow, - kMediumNoArrow }, - { BubbleBorder::RIGHT_TOP, kMediumSize, kMediumVertArrow, kMediumNoArrow }, - { BubbleBorder::RIGHT_CENTER, kMediumSize, kMediumVertArrow, - kMediumNoArrow }, - { BubbleBorder::RIGHT_BOTTOM, kMediumSize, kMediumVertArrow, - kMediumNoArrow }, - { BubbleBorder::NONE, kMediumSize, kMediumNoArrow, kMediumNoArrow }, - { BubbleBorder::FLOAT, kMediumSize, kMediumNoArrow, kMediumNoArrow } - }; - - for (size_t i = 0; i < arraysize(cases); ++i) { - SCOPED_TRACE(base::StringPrintf("i=%d arrow=%d", - static_cast<int>(i), cases[i].arrow)); - - border.set_arrow(cases[i].arrow); - - border.set_paint_arrow(BubbleBorder::PAINT_NORMAL); - EXPECT_EQ(cases[i].expected_with_arrow, - border.GetSizeForContentsSize(cases[i].content)); - - border.set_paint_arrow(BubbleBorder::PAINT_TRANSPARENT); - EXPECT_EQ(cases[i].expected_with_arrow, - border.GetSizeForContentsSize(cases[i].content)); - - border.set_paint_arrow(BubbleBorder::PAINT_NONE); - EXPECT_EQ(cases[i].expected_without_arrow, - border.GetSizeForContentsSize(cases[i].content)); - } -} - -TEST_F(BubbleBorderTest, GetBoundsOriginTest) { - views::BubbleBorder border(BubbleBorder::TOP_LEFT, - BubbleBorder::NO_SHADOW, - SK_ColorWHITE); - - const gfx::Rect kAnchor(100, 100, 20, 30); - const gfx::Size kContentSize(50, 60); - - const views::internal::BorderImages* kImages = border.GetImagesForTest(); - - border.set_arrow(BubbleBorder::TOP_LEFT); - const gfx::Size kTotalSizeWithHorizArrow = - border.GetSizeForContentsSize(kContentSize); - - border.set_arrow(BubbleBorder::RIGHT_BOTTOM); - const gfx::Size kTotalSizeWithVertArrow = - border.GetSizeForContentsSize(kContentSize); - - border.set_arrow(BubbleBorder::NONE); - const gfx::Size kTotalSizeWithNoArrow = - border.GetSizeForContentsSize(kContentSize); - - const int kBorderThickness = border.GetBorderThickness(); - - const int kArrowOffsetForHorizCenter = kTotalSizeWithHorizArrow.width() / 2; - const int kArrowOffsetForVertCenter = kTotalSizeWithVertArrow.height() / 2; - const int kArrowOffsetForNotCenter = - kImages->border_thickness + (kImages->top_arrow.width() / 2); - - const int kArrowSize = - kImages->arrow_interior_thickness + BubbleBorder::kStroke - - kImages->arrow_thickness; - - const int kTopHorizArrowY = kAnchor.y() + kAnchor.height() + kArrowSize; - const int kBottomHorizArrowY = - kAnchor.y() - kArrowSize - kTotalSizeWithHorizArrow.height(); - - const int kLeftVertArrowX = kAnchor.x() + kAnchor.width() + kArrowSize; - const int kRightVertArrowX = - kAnchor.x() - kArrowSize - kTotalSizeWithVertArrow.width(); - - struct TestCase { - BubbleBorder::Arrow arrow; - BubbleBorder::BubbleAlignment alignment; - int expected_x; - int expected_y; - }; - - TestCase cases[] = { - // Horizontal arrow tests. - { BubbleBorder::TOP_LEFT, BubbleBorder::ALIGN_ARROW_TO_MID_ANCHOR, - kAnchor.CenterPoint().x() - kArrowOffsetForNotCenter, kTopHorizArrowY }, - { BubbleBorder::TOP_LEFT, BubbleBorder::ALIGN_EDGE_TO_ANCHOR_EDGE, - kAnchor.x() + BubbleBorder::kStroke - kBorderThickness, kTopHorizArrowY }, - { BubbleBorder::TOP_CENTER, BubbleBorder::ALIGN_ARROW_TO_MID_ANCHOR, - kAnchor.CenterPoint().x() - kArrowOffsetForHorizCenter, kTopHorizArrowY }, - { BubbleBorder::BOTTOM_RIGHT, BubbleBorder::ALIGN_ARROW_TO_MID_ANCHOR, - kAnchor.CenterPoint().x() + kArrowOffsetForNotCenter - - kTotalSizeWithHorizArrow.width(), kBottomHorizArrowY }, - { BubbleBorder::BOTTOM_RIGHT, BubbleBorder::ALIGN_EDGE_TO_ANCHOR_EDGE, - kAnchor.x() + kAnchor.width() - kTotalSizeWithHorizArrow.width() + - kBorderThickness - BubbleBorder::kStroke, kBottomHorizArrowY }, - - // Vertical arrow tests. - { BubbleBorder::LEFT_TOP, BubbleBorder::ALIGN_ARROW_TO_MID_ANCHOR, - kLeftVertArrowX, kAnchor.CenterPoint().y() - kArrowOffsetForNotCenter }, - { BubbleBorder::LEFT_TOP, BubbleBorder::ALIGN_EDGE_TO_ANCHOR_EDGE, - kLeftVertArrowX, kAnchor.y() + BubbleBorder::kStroke - kBorderThickness }, - { BubbleBorder::LEFT_CENTER, BubbleBorder::ALIGN_ARROW_TO_MID_ANCHOR, - kLeftVertArrowX, kAnchor.CenterPoint().y() - kArrowOffsetForVertCenter }, - { BubbleBorder::RIGHT_BOTTOM, BubbleBorder::ALIGN_ARROW_TO_MID_ANCHOR, - kRightVertArrowX, kAnchor.CenterPoint().y() + kArrowOffsetForNotCenter - - kTotalSizeWithVertArrow.height() }, - { BubbleBorder::RIGHT_BOTTOM, BubbleBorder::ALIGN_EDGE_TO_ANCHOR_EDGE, - kRightVertArrowX, kAnchor.y() + kAnchor.height() - - kTotalSizeWithVertArrow.height() + kBorderThickness - - BubbleBorder::kStroke }, - - // No arrow tests. - { BubbleBorder::NONE, BubbleBorder::ALIGN_ARROW_TO_MID_ANCHOR, - kAnchor.x() + (kAnchor.width() - kTotalSizeWithNoArrow.width()) / 2, - kAnchor.y() + kAnchor.height() }, - { BubbleBorder::FLOAT, BubbleBorder::ALIGN_ARROW_TO_MID_ANCHOR, - kAnchor.x() + (kAnchor.width() - kTotalSizeWithNoArrow.width()) / 2, - kAnchor.y() + (kAnchor.height() - kTotalSizeWithNoArrow.height()) / 2 }, - }; - - for (size_t i = 0; i < arraysize(cases); ++i) { - SCOPED_TRACE(base::StringPrintf("i=%d arrow=%d alignment=%d", - static_cast<int>(i), cases[i].arrow, cases[i].alignment)); - border.set_arrow(cases[i].arrow); - border.set_alignment(cases[i].alignment); - - gfx::Point origin = border.GetBounds(kAnchor, kContentSize).origin(); - EXPECT_EQ(cases[i].expected_x, origin.x()); - EXPECT_EQ(cases[i].expected_y, origin.y()); - } -} - -} // namespace views
diff --git a/ui/views/bubble/bubble_delegate.cc b/ui/views/bubble/bubble_delegate.cc deleted file mode 100644 index e7fad31..0000000 --- a/ui/views/bubble/bubble_delegate.cc +++ /dev/null
@@ -1,303 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/bubble/bubble_delegate.h" - -#include "ui/accessibility/ax_view_state.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/gfx/color_utils.h" -#include "ui/gfx/rect.h" -#include "ui/native_theme/native_theme.h" -#include "ui/views/bubble/bubble_frame_view.h" -#include "ui/views/focus/view_storage.h" -#include "ui/views/widget/widget.h" -#include "ui/views/widget/widget_observer.h" - -#if defined(OS_WIN) -#include "ui/base/win/shell.h" -#endif - -// The defaut margin between the content and the inside border, in pixels. -static const int kDefaultMargin = 6; - -namespace views { - -namespace { - -// Create a widget to host the bubble. -Widget* CreateBubbleWidget(BubbleDelegateView* bubble) { - Widget* bubble_widget = new Widget(); - Widget::InitParams bubble_params(Widget::InitParams::TYPE_BUBBLE); - bubble_params.delegate = bubble; - bubble_params.opacity = Widget::InitParams::TRANSLUCENT_WINDOW; - bubble_params.accept_events = bubble->accept_events(); - if (bubble->parent_window()) - bubble_params.parent = bubble->parent_window(); - else if (bubble->anchor_widget()) - bubble_params.parent = bubble->anchor_widget()->GetNativeView(); - bubble_params.activatable = bubble->CanActivate() ? - Widget::InitParams::ACTIVATABLE_YES : Widget::InitParams::ACTIVATABLE_NO; - bubble->OnBeforeBubbleWidgetInit(&bubble_params, bubble_widget); - bubble_widget->Init(bubble_params); - return bubble_widget; -} - -} // namespace - -BubbleDelegateView::BubbleDelegateView() - : close_on_esc_(true), - close_on_deactivate_(true), - anchor_view_storage_id_(ViewStorage::GetInstance()->CreateStorageID()), - anchor_widget_(NULL), - arrow_(BubbleBorder::TOP_LEFT), - shadow_(BubbleBorder::SMALL_SHADOW), - color_explicitly_set_(false), - margins_(kDefaultMargin, kDefaultMargin, kDefaultMargin, kDefaultMargin), - accept_events_(true), - border_accepts_events_(true), - adjust_if_offscreen_(true), - parent_window_(NULL) { - AddAccelerator(ui::Accelerator(ui::VKEY_ESCAPE, ui::EF_NONE)); - UpdateColorsFromTheme(GetNativeTheme()); -} - -BubbleDelegateView::BubbleDelegateView( - View* anchor_view, - BubbleBorder::Arrow arrow) - : close_on_esc_(true), - close_on_deactivate_(true), - anchor_view_storage_id_(ViewStorage::GetInstance()->CreateStorageID()), - anchor_widget_(NULL), - arrow_(arrow), - shadow_(BubbleBorder::SMALL_SHADOW), - color_explicitly_set_(false), - margins_(kDefaultMargin, kDefaultMargin, kDefaultMargin, kDefaultMargin), - accept_events_(true), - border_accepts_events_(true), - adjust_if_offscreen_(true), - parent_window_(NULL) { - SetAnchorView(anchor_view); - AddAccelerator(ui::Accelerator(ui::VKEY_ESCAPE, ui::EF_NONE)); - UpdateColorsFromTheme(GetNativeTheme()); -} - -BubbleDelegateView::~BubbleDelegateView() { - if (GetWidget()) - GetWidget()->RemoveObserver(this); - SetLayoutManager(NULL); - SetAnchorView(NULL); -} - -// static -Widget* BubbleDelegateView::CreateBubble(BubbleDelegateView* bubble_delegate) { - bubble_delegate->Init(); - // Get the latest anchor widget from the anchor view at bubble creation time. - bubble_delegate->SetAnchorView(bubble_delegate->GetAnchorView()); - Widget* bubble_widget = CreateBubbleWidget(bubble_delegate); - -#if defined(OS_WIN) - // If glass is enabled, the bubble is allowed to extend outside the bounds of - // the parent frame and let DWM handle compositing. If not, then we don't - // want to allow the bubble to extend the frame because it will be clipped. - bubble_delegate->set_adjust_if_offscreen(ui::win::IsAeroGlassEnabled()); -#elif defined(OS_LINUX) && !defined(OS_CHROMEOS) - // Linux clips bubble windows that extend outside their parent window bounds. - bubble_delegate->set_adjust_if_offscreen(false); -#endif - - bubble_delegate->SizeToContents(); - bubble_widget->AddObserver(bubble_delegate); - return bubble_widget; -} - -BubbleDelegateView* BubbleDelegateView::AsBubbleDelegate() { - return this; -} - -bool BubbleDelegateView::ShouldShowCloseButton() const { - return false; -} - -View* BubbleDelegateView::GetContentsView() { - return this; -} - -NonClientFrameView* BubbleDelegateView::CreateNonClientFrameView( - Widget* widget) { - BubbleFrameView* frame = new BubbleFrameView(margins()); - // Note: In CreateBubble, the call to SizeToContents() will cause - // the relayout that this call requires. - frame->SetTitleFontList(GetTitleFontList()); - BubbleBorder::Arrow adjusted_arrow = arrow(); - if (base::i18n::IsRTL()) - adjusted_arrow = BubbleBorder::horizontal_mirror(adjusted_arrow); - frame->SetBubbleBorder(scoped_ptr<BubbleBorder>( - new BubbleBorder(adjusted_arrow, shadow(), color()))); - return frame; -} - -void BubbleDelegateView::GetAccessibleState(ui::AXViewState* state) { - state->role = ui::AX_ROLE_DIALOG; -} - -void BubbleDelegateView::OnWidgetDestroying(Widget* widget) { - if (anchor_widget() == widget) - SetAnchorView(NULL); -} - -void BubbleDelegateView::OnWidgetVisibilityChanging(Widget* widget, - bool visible) { -#if defined(OS_WIN) - // On Windows we need to handle this before the bubble is visible or hidden. - // Please see the comment on the OnWidgetVisibilityChanging function. On - // other platforms it is fine to handle it after the bubble is shown/hidden. - HandleVisibilityChanged(widget, visible); -#endif -} - -void BubbleDelegateView::OnWidgetVisibilityChanged(Widget* widget, - bool visible) { -#if !defined(OS_WIN) - HandleVisibilityChanged(widget, visible); -#endif -} - -void BubbleDelegateView::OnWidgetActivationChanged(Widget* widget, - bool active) { - if (close_on_deactivate() && widget == GetWidget() && !active) - GetWidget()->Close(); -} - -void BubbleDelegateView::OnWidgetBoundsChanged(Widget* widget, - const gfx::Rect& new_bounds) { - if (anchor_widget() == widget) - SizeToContents(); -} - -View* BubbleDelegateView::GetAnchorView() const { - return ViewStorage::GetInstance()->RetrieveView(anchor_view_storage_id_); -} - -gfx::Rect BubbleDelegateView::GetAnchorRect() const { - if (!GetAnchorView()) - return anchor_rect_; - - anchor_rect_ = GetAnchorView()->GetBoundsInScreen(); - anchor_rect_.Inset(anchor_view_insets_); - return anchor_rect_; -} - -void BubbleDelegateView::OnBeforeBubbleWidgetInit(Widget::InitParams* params, - Widget* widget) const { -} - -void BubbleDelegateView::SetAlignment(BubbleBorder::BubbleAlignment alignment) { - GetBubbleFrameView()->bubble_border()->set_alignment(alignment); - SizeToContents(); -} - -void BubbleDelegateView::SetArrowPaintType( - BubbleBorder::ArrowPaintType paint_type) { - GetBubbleFrameView()->bubble_border()->set_paint_arrow(paint_type); - SizeToContents(); -} - -void BubbleDelegateView::OnAnchorBoundsChanged() { - SizeToContents(); -} - -bool BubbleDelegateView::AcceleratorPressed( - const ui::Accelerator& accelerator) { - if (!close_on_esc() || accelerator.key_code() != ui::VKEY_ESCAPE) - return false; - GetWidget()->Close(); - return true; -} - -void BubbleDelegateView::OnNativeThemeChanged(const ui::NativeTheme* theme) { - UpdateColorsFromTheme(theme); -} - -void BubbleDelegateView::Init() {} - -void BubbleDelegateView::SetAnchorView(View* anchor_view) { - // When the anchor view gets set the associated anchor widget might - // change as well. - if (!anchor_view || anchor_widget() != anchor_view->GetWidget()) { - if (anchor_widget()) { - anchor_widget_->RemoveObserver(this); - anchor_widget_ = NULL; - } - if (anchor_view) { - anchor_widget_ = anchor_view->GetWidget(); - if (anchor_widget_) - anchor_widget_->AddObserver(this); - } - } - - // Remove the old storage item and set the new (if there is one). - ViewStorage* view_storage = ViewStorage::GetInstance(); - if (view_storage->RetrieveView(anchor_view_storage_id_)) - view_storage->RemoveView(anchor_view_storage_id_); - if (anchor_view) - view_storage->StoreView(anchor_view_storage_id_, anchor_view); - - // Do not update anchoring for NULL views; this could indicate that our - // NativeWindow is being destroyed, so it would be dangerous for us to update - // our anchor bounds at that point. (It's safe to skip this, since if we were - // to update the bounds when |anchor_view| is NULL, the bubble won't move.) - if (anchor_view && GetWidget()) - OnAnchorBoundsChanged(); -} - -void BubbleDelegateView::SetAnchorRect(const gfx::Rect& rect) { - anchor_rect_ = rect; - if (GetWidget()) - OnAnchorBoundsChanged(); -} - -void BubbleDelegateView::SizeToContents() { - GetWidget()->SetBounds(GetBubbleBounds()); -} - -BubbleFrameView* BubbleDelegateView::GetBubbleFrameView() const { - const NonClientView* view = - GetWidget() ? GetWidget()->non_client_view() : NULL; - return view ? static_cast<BubbleFrameView*>(view->frame_view()) : NULL; -} - -gfx::Rect BubbleDelegateView::GetBubbleBounds() { - // The argument rect has its origin at the bubble's arrow anchor point; - // its size is the preferred size of the bubble's client view (this view). - bool anchor_minimized = anchor_widget() && anchor_widget()->IsMinimized(); - return GetBubbleFrameView()->GetUpdatedWindowBounds(GetAnchorRect(), - GetPreferredSize(), adjust_if_offscreen_ && !anchor_minimized); -} - -const gfx::FontList& BubbleDelegateView::GetTitleFontList() const { - ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); - return rb.GetFontList(ui::ResourceBundle::MediumFont); -} - - -void BubbleDelegateView::UpdateColorsFromTheme(const ui::NativeTheme* theme) { - if (!color_explicitly_set_) - color_ = theme->GetSystemColor(ui::NativeTheme::kColorId_DialogBackground); - set_background(Background::CreateSolidBackground(color())); - BubbleFrameView* frame_view = GetBubbleFrameView(); - if (frame_view) - frame_view->bubble_border()->set_background_color(color()); -} - -void BubbleDelegateView::HandleVisibilityChanged(Widget* widget, bool visible) { - if (widget == GetWidget() && anchor_widget() && - anchor_widget()->GetTopLevelWidget()) { - if (visible) - anchor_widget()->GetTopLevelWidget()->DisableInactiveRendering(); - else - anchor_widget()->GetTopLevelWidget()->EnableInactiveRendering(); - } -} - -} // namespace views
diff --git a/ui/views/bubble/bubble_delegate.h b/ui/views/bubble/bubble_delegate.h deleted file mode 100644 index 5f21313..0000000 --- a/ui/views/bubble/bubble_delegate.h +++ /dev/null
@@ -1,198 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_BUBBLE_BUBBLE_DELEGATE_H_ -#define UI_VIEWS_BUBBLE_BUBBLE_DELEGATE_H_ - -#include "base/gtest_prod_util.h" -#include "ui/views/bubble/bubble_border.h" -#include "ui/views/widget/widget.h" -#include "ui/views/widget/widget_delegate.h" -#include "ui/views/widget/widget_observer.h" - -namespace gfx { -class FontList; -class Rect; -} - -namespace views { - -class BubbleFrameView; - -// BubbleDelegateView creates frame and client views for bubble Widgets. -// BubbleDelegateView itself is the client's contents view. -class VIEWS_EXPORT BubbleDelegateView : public WidgetDelegateView, - public WidgetObserver { - public: - BubbleDelegateView(); - BubbleDelegateView(View* anchor_view, BubbleBorder::Arrow arrow); - virtual ~BubbleDelegateView(); - - // Create and initialize the bubble Widget(s) with proper bounds. - static Widget* CreateBubble(BubbleDelegateView* bubble_delegate); - - // WidgetDelegateView overrides: - virtual BubbleDelegateView* AsBubbleDelegate() override; - virtual bool ShouldShowCloseButton() const override; - virtual View* GetContentsView() override; - virtual NonClientFrameView* CreateNonClientFrameView(Widget* widget) override; - virtual void GetAccessibleState(ui::AXViewState* state) override; - - // WidgetObserver overrides: - virtual void OnWidgetDestroying(Widget* widget) override; - virtual void OnWidgetVisibilityChanging(Widget* widget, bool visible) - override; - virtual void OnWidgetVisibilityChanged(Widget* widget, bool visible) - override; - virtual void OnWidgetActivationChanged(Widget* widget, bool active) override; - virtual void OnWidgetBoundsChanged(Widget* widget, - const gfx::Rect& new_bounds) override; - - bool close_on_esc() const { return close_on_esc_; } - void set_close_on_esc(bool close_on_esc) { close_on_esc_ = close_on_esc; } - - bool close_on_deactivate() const { return close_on_deactivate_; } - void set_close_on_deactivate(bool close) { close_on_deactivate_ = close; } - - View* GetAnchorView() const; - Widget* anchor_widget() const { return anchor_widget_; } - - // The anchor rect is used in the absence of an assigned anchor view. - const gfx::Rect& anchor_rect() const { return anchor_rect_; } - - BubbleBorder::Arrow arrow() const { return arrow_; } - void set_arrow(BubbleBorder::Arrow arrow) { arrow_ = arrow; } - - BubbleBorder::Shadow shadow() const { return shadow_; } - void set_shadow(BubbleBorder::Shadow shadow) { shadow_ = shadow; } - - SkColor color() const { return color_; } - void set_color(SkColor color) { - color_ = color; - color_explicitly_set_ = true; - } - - const gfx::Insets& margins() const { return margins_; } - void set_margins(const gfx::Insets& margins) { margins_ = margins; } - - const gfx::Insets& anchor_view_insets() const { return anchor_view_insets_; } - void set_anchor_view_insets(const gfx::Insets& i) { anchor_view_insets_ = i; } - - gfx::NativeView parent_window() const { return parent_window_; } - void set_parent_window(gfx::NativeView window) { parent_window_ = window; } - - bool accept_events() const { return accept_events_; } - void set_accept_events(bool accept_events) { accept_events_ = accept_events; } - - bool border_accepts_events() const { return border_accepts_events_; } - void set_border_accepts_events(bool event) { border_accepts_events_ = event; } - - bool adjust_if_offscreen() const { return adjust_if_offscreen_; } - void set_adjust_if_offscreen(bool adjust) { adjust_if_offscreen_ = adjust; } - - // Get the arrow's anchor rect in screen space. - virtual gfx::Rect GetAnchorRect() const; - - // Allows delegates to provide custom parameters before widget initialization. - virtual void OnBeforeBubbleWidgetInit(Widget::InitParams* params, - Widget* widget) const; - - // Sets the bubble alignment relative to the anchor. This may only be called - // after calling CreateBubble. - void SetAlignment(BubbleBorder::BubbleAlignment alignment); - - // Sets the bubble arrow paint type. - void SetArrowPaintType(BubbleBorder::ArrowPaintType paint_type); - - // Call this method when the anchor bounds have changed to reposition the - // bubble. The bubble is automatically repositioned when the anchor view - // bounds change as a result of the widget's bounds changing. - void OnAnchorBoundsChanged(); - - protected: - // Get bubble bounds from the anchor rect and client view's preferred size. - virtual gfx::Rect GetBubbleBounds(); - - // Return a FontList to use for the title of the bubble. - // (The default is MediumFont). - virtual const gfx::FontList& GetTitleFontList() const; - - // View overrides: - virtual bool AcceleratorPressed(const ui::Accelerator& accelerator) override; - virtual void OnNativeThemeChanged(const ui::NativeTheme* theme) override; - - // Perform view initialization on the contents for bubble sizing. - virtual void Init(); - - // Sets the anchor view or rect and repositions the bubble. Note that if a - // valid view gets passed, the anchor rect will get ignored. If the view gets - // deleted, but no new view gets set, the last known anchor postion will get - // returned. - void SetAnchorView(View* anchor_view); - void SetAnchorRect(const gfx::Rect& rect); - - // Resize and potentially move the bubble to fit the content's preferred size. - void SizeToContents(); - - BubbleFrameView* GetBubbleFrameView() const; - - private: - friend class BubbleBorderDelegate; - friend class BubbleWindowTargeter; - - FRIEND_TEST_ALL_PREFIXES(BubbleDelegateTest, CreateDelegate); - FRIEND_TEST_ALL_PREFIXES(BubbleDelegateTest, NonClientHitTest); - - // Update the bubble color from |theme|, unless it was explicitly set. - void UpdateColorsFromTheme(const ui::NativeTheme* theme); - - // Handles widget visibility changes. - void HandleVisibilityChanged(Widget* widget, bool visible); - - // Flags controlling bubble closure on the escape key and deactivation. - bool close_on_esc_; - bool close_on_deactivate_; - - // The view and widget to which this bubble is anchored. Since an anchor view - // can be deleted without notice, we store it in the ViewStorage and retrieve - // it from there. It will make sure that the view is still valid. - const int anchor_view_storage_id_; - Widget* anchor_widget_; - - // The anchor rect used in the absence of an anchor view. - mutable gfx::Rect anchor_rect_; - - // The arrow's location on the bubble. - BubbleBorder::Arrow arrow_; - - // Bubble border shadow to use. - BubbleBorder::Shadow shadow_; - - // The background color of the bubble; and flag for when it's explicitly set. - SkColor color_; - bool color_explicitly_set_; - - // The margins between the content and the inside of the border. - gfx::Insets margins_; - - // Insets applied to the |anchor_view_| bounds. - gfx::Insets anchor_view_insets_; - - // Specifies whether the bubble (or its border) handles mouse events, etc. - bool accept_events_; - bool border_accepts_events_; - - // If true (defaults to true), the arrow may be mirrored and moved to fit the - // bubble on screen better. It would be a no-op if the bubble has no arrow. - bool adjust_if_offscreen_; - - // Parent native window of the bubble. - gfx::NativeView parent_window_; - - DISALLOW_COPY_AND_ASSIGN(BubbleDelegateView); -}; - -} // namespace views - -#endif // UI_VIEWS_BUBBLE_BUBBLE_DELEGATE_H_
diff --git a/ui/views/bubble/bubble_delegate_unittest.cc b/ui/views/bubble/bubble_delegate_unittest.cc deleted file mode 100644 index c793f54..0000000 --- a/ui/views/bubble/bubble_delegate_unittest.cc +++ /dev/null
@@ -1,265 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/base/hit_test.h" -#include "ui/views/bubble/bubble_delegate.h" -#include "ui/views/bubble/bubble_frame_view.h" -#include "ui/views/test/test_widget_observer.h" -#include "ui/views/test/views_test_base.h" -#include "ui/views/widget/widget.h" -#include "ui/views/widget/widget_observer.h" - -namespace views { - -namespace { - -class TestBubbleDelegateView : public BubbleDelegateView { - public: - TestBubbleDelegateView(View* anchor_view) - : BubbleDelegateView(anchor_view, BubbleBorder::TOP_LEFT), - view_(new View()) { - view_->SetFocusable(true); - AddChildView(view_); - } - virtual ~TestBubbleDelegateView() {} - - void SetAnchorRectForTest(gfx::Rect rect) { - SetAnchorRect(rect); - } - - void SetAnchorViewForTest(View* view) { - SetAnchorView(view); - } - - // BubbleDelegateView overrides: - virtual View* GetInitiallyFocusedView() override { return view_; } - virtual gfx::Size GetPreferredSize() const override { - return gfx::Size(200, 200); - } - - private: - View* view_; - - DISALLOW_COPY_AND_ASSIGN(TestBubbleDelegateView); -}; - -class BubbleDelegateTest : public ViewsTestBase { - public: - BubbleDelegateTest() {} - virtual ~BubbleDelegateTest() {} - - // Creates a test widget that owns its native widget. - Widget* CreateTestWidget() { - Widget* widget = new Widget(); - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); - params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget->Init(params); - return widget; - } - - private: - DISALLOW_COPY_AND_ASSIGN(BubbleDelegateTest); -}; - -} // namespace - -TEST_F(BubbleDelegateTest, CreateDelegate) { - scoped_ptr<Widget> anchor_widget(CreateTestWidget()); - BubbleDelegateView* bubble_delegate = new BubbleDelegateView( - anchor_widget->GetContentsView(), BubbleBorder::NONE); - bubble_delegate->set_color(SK_ColorGREEN); - Widget* bubble_widget = BubbleDelegateView::CreateBubble(bubble_delegate); - EXPECT_EQ(bubble_delegate, bubble_widget->widget_delegate()); - EXPECT_EQ(bubble_widget, bubble_delegate->GetWidget()); - test::TestWidgetObserver bubble_observer(bubble_widget); - bubble_widget->Show(); - - BubbleBorder* border = bubble_delegate->GetBubbleFrameView()->bubble_border(); - EXPECT_EQ(bubble_delegate->arrow(), border->arrow()); - EXPECT_EQ(bubble_delegate->color(), border->background_color()); - - EXPECT_FALSE(bubble_observer.widget_closed()); - bubble_widget->CloseNow(); - EXPECT_TRUE(bubble_observer.widget_closed()); -} - -TEST_F(BubbleDelegateTest, CloseAnchorWidget) { - scoped_ptr<Widget> anchor_widget(CreateTestWidget()); - BubbleDelegateView* bubble_delegate = new BubbleDelegateView( - anchor_widget->GetContentsView(), BubbleBorder::NONE); - // Preventing close on deactivate should not prevent closing with the anchor. - bubble_delegate->set_close_on_deactivate(false); - Widget* bubble_widget = BubbleDelegateView::CreateBubble(bubble_delegate); - EXPECT_EQ(bubble_delegate, bubble_widget->widget_delegate()); - EXPECT_EQ(bubble_widget, bubble_delegate->GetWidget()); - EXPECT_EQ(anchor_widget, bubble_delegate->anchor_widget()); - test::TestWidgetObserver bubble_observer(bubble_widget); - EXPECT_FALSE(bubble_observer.widget_closed()); - - bubble_widget->Show(); - EXPECT_EQ(anchor_widget, bubble_delegate->anchor_widget()); - EXPECT_FALSE(bubble_observer.widget_closed()); - - // TODO(msw): Remove activation hack to prevent bookkeeping errors in: - // aura::test::TestActivationClient::OnWindowDestroyed(). - scoped_ptr<Widget> smoke_and_mirrors_widget(CreateTestWidget()); - EXPECT_FALSE(bubble_observer.widget_closed()); - - // Ensure that closing the anchor widget also closes the bubble itself. - anchor_widget->CloseNow(); - EXPECT_TRUE(bubble_observer.widget_closed()); -} - -// This test checks that the bubble delegate is capable to handle an early -// destruction of the used anchor view. (Animations and delayed closure of the -// bubble will call upon the anchor view to get its location). -TEST_F(BubbleDelegateTest, CloseAnchorViewTest) { - // Create an anchor widget and add a view to be used as an anchor view. - scoped_ptr<Widget> anchor_widget(CreateTestWidget()); - scoped_ptr<View> anchor_view(new View()); - anchor_widget->GetContentsView()->AddChildView(anchor_view.get()); - TestBubbleDelegateView* bubble_delegate = new TestBubbleDelegateView( - anchor_view.get()); - // Prevent flakes by avoiding closing on activation changes. - bubble_delegate->set_close_on_deactivate(false); - Widget* bubble_widget = BubbleDelegateView::CreateBubble(bubble_delegate); - - // Check that the anchor view is correct and set up an anchor view rect. - // Make sure that this rect will get ignored (as long as the anchor view is - // attached). - EXPECT_EQ(anchor_view, bubble_delegate->GetAnchorView()); - const gfx::Rect set_anchor_rect = gfx::Rect(10, 10, 100, 100); - bubble_delegate->SetAnchorRectForTest(set_anchor_rect); - const gfx::Rect view_rect = bubble_delegate->GetAnchorRect(); - EXPECT_NE(view_rect.ToString(), set_anchor_rect.ToString()); - - // Create the bubble. - bubble_widget->Show(); - EXPECT_EQ(anchor_widget, bubble_delegate->anchor_widget()); - - // Remove now the anchor view and make sure that the original found rect - // is still kept, so that the bubble does not jump when the view gets deleted. - anchor_widget->GetContentsView()->RemoveChildView(anchor_view.get()); - anchor_view.reset(); - EXPECT_EQ(NULL, bubble_delegate->GetAnchorView()); - EXPECT_EQ(view_rect.ToString(), bubble_delegate->GetAnchorRect().ToString()); -} - -// Testing that a move of the anchor view will lead to new bubble locations. -TEST_F(BubbleDelegateTest, TestAnchorRectMovesWithViewTest) { - // Create an anchor widget and add a view to be used as anchor view. - scoped_ptr<Widget> anchor_widget(CreateTestWidget()); - TestBubbleDelegateView* bubble_delegate = new TestBubbleDelegateView( - anchor_widget->GetContentsView()); - BubbleDelegateView::CreateBubble(bubble_delegate); - - anchor_widget->GetContentsView()->SetBounds(10, 10, 100, 100); - const gfx::Rect view_rect = bubble_delegate->GetAnchorRect(); - - anchor_widget->GetContentsView()->SetBounds(20, 10, 100, 100); - const gfx::Rect view_rect_2 = bubble_delegate->GetAnchorRect(); - EXPECT_NE(view_rect.ToString(), view_rect_2.ToString()); -} - -TEST_F(BubbleDelegateTest, ResetAnchorWidget) { - scoped_ptr<Widget> anchor_widget(CreateTestWidget()); - BubbleDelegateView* bubble_delegate = new BubbleDelegateView( - anchor_widget->GetContentsView(), BubbleBorder::NONE); - - // Make sure the bubble widget is parented to a widget other than the anchor - // widget so that closing the anchor widget does not close the bubble widget. - scoped_ptr<Widget> parent_widget(CreateTestWidget()); - bubble_delegate->set_parent_window(parent_widget->GetNativeView()); - // Preventing close on deactivate should not prevent closing with the parent. - bubble_delegate->set_close_on_deactivate(false); - Widget* bubble_widget = BubbleDelegateView::CreateBubble(bubble_delegate); - EXPECT_EQ(bubble_delegate, bubble_widget->widget_delegate()); - EXPECT_EQ(bubble_widget, bubble_delegate->GetWidget()); - EXPECT_EQ(anchor_widget, bubble_delegate->anchor_widget()); - test::TestWidgetObserver bubble_observer(bubble_widget); - EXPECT_FALSE(bubble_observer.widget_closed()); - - // Showing and hiding the bubble widget should have no effect on its anchor. - bubble_widget->Show(); - EXPECT_EQ(anchor_widget, bubble_delegate->anchor_widget()); - bubble_widget->Hide(); - EXPECT_EQ(anchor_widget, bubble_delegate->anchor_widget()); - - // Ensure that closing the anchor widget clears the bubble's reference to that - // anchor widget, but the bubble itself does not close. - anchor_widget->CloseNow(); - EXPECT_NE(anchor_widget, bubble_delegate->anchor_widget()); - EXPECT_FALSE(bubble_observer.widget_closed()); - - // TODO(msw): Remove activation hack to prevent bookkeeping errors in: - // aura::test::TestActivationClient::OnWindowDestroyed(). - scoped_ptr<Widget> smoke_and_mirrors_widget(CreateTestWidget()); - EXPECT_FALSE(bubble_observer.widget_closed()); - - // Ensure that closing the parent widget also closes the bubble itself. - parent_widget->CloseNow(); - EXPECT_TRUE(bubble_observer.widget_closed()); -} - -TEST_F(BubbleDelegateTest, InitiallyFocusedView) { - scoped_ptr<Widget> anchor_widget(CreateTestWidget()); - BubbleDelegateView* bubble_delegate = new BubbleDelegateView( - anchor_widget->GetContentsView(), BubbleBorder::NONE); - Widget* bubble_widget = BubbleDelegateView::CreateBubble(bubble_delegate); - EXPECT_EQ(bubble_delegate->GetInitiallyFocusedView(), - bubble_widget->GetFocusManager()->GetFocusedView()); - bubble_widget->CloseNow(); -} - -TEST_F(BubbleDelegateTest, NonClientHitTest) { - scoped_ptr<Widget> anchor_widget(CreateTestWidget()); - TestBubbleDelegateView* bubble_delegate = - new TestBubbleDelegateView(anchor_widget->GetContentsView()); - BubbleDelegateView::CreateBubble(bubble_delegate); - BubbleFrameView* frame = bubble_delegate->GetBubbleFrameView(); - const int border = frame->bubble_border()->GetBorderThickness(); - - struct { - const int point; - const int hit; - } cases[] = { - { border, HTNOWHERE }, - { border + 50, HTCLIENT }, - { 1000, HTNOWHERE }, - }; - - for (size_t i = 0; i < arraysize(cases); ++i) { - gfx::Point point(cases[i].point, cases[i].point); - EXPECT_EQ(cases[i].hit, frame->NonClientHitTest(point)) - << " with border: " << border << ", at point " << cases[i].point; - } -} - -TEST_F(BubbleDelegateTest, VisibleWhenAnchorWidgetBoundsChanged) { - scoped_ptr<Widget> anchor_widget(CreateTestWidget()); - BubbleDelegateView* bubble_delegate = new BubbleDelegateView( - anchor_widget->GetContentsView(), BubbleBorder::NONE); - Widget* bubble_widget = BubbleDelegateView::CreateBubble(bubble_delegate); - test::TestWidgetObserver bubble_observer(bubble_widget); - EXPECT_FALSE(bubble_observer.widget_closed()); - - bubble_widget->Show(); - EXPECT_TRUE(bubble_widget->IsVisible()); - anchor_widget->SetBounds(gfx::Rect(10, 10, 100, 100)); - EXPECT_TRUE(bubble_widget->IsVisible()); -} - -// Test that setting WidgetDelegate::set_can_activate() to false makes the -// widget created via BubbleDelegateView::CreateBubble() not activatable. -TEST_F(BubbleDelegateTest, NotActivatable) { - scoped_ptr<Widget> anchor_widget(CreateTestWidget()); - BubbleDelegateView* bubble_delegate = new BubbleDelegateView( - anchor_widget->GetContentsView(), BubbleBorder::NONE); - bubble_delegate->set_can_activate(false); - Widget* bubble_widget = BubbleDelegateView::CreateBubble(bubble_delegate); - bubble_widget->Show(); - EXPECT_FALSE(bubble_widget->CanActivate()); -} - -} // namespace views
diff --git a/ui/views/bubble/bubble_frame_view.cc b/ui/views/bubble/bubble_frame_view.cc deleted file mode 100644 index e3eb3c8..0000000 --- a/ui/views/bubble/bubble_frame_view.cc +++ /dev/null
@@ -1,387 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/bubble/bubble_frame_view.h" - -#include <algorithm> - -#include "ui/base/hit_test.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/gfx/path.h" -#include "ui/gfx/screen.h" -#include "ui/gfx/skia_util.h" -#include "ui/native_theme/native_theme.h" -#include "ui/resources/grit/ui_resources.h" -#include "ui/views/bubble/bubble_border.h" -#include "ui/views/controls/button/label_button.h" -#include "ui/views/widget/widget.h" -#include "ui/views/widget/widget_delegate.h" -#include "ui/views/window/client_view.h" - -namespace { - -// Insets for the title bar views in pixels. -const int kTitleTopInset = 12; -const int kTitleLeftInset = 19; -const int kTitleBottomInset = 12; -const int kTitleRightInset = 7; - -// Get the |vertical| or horizontal amount that |available_bounds| overflows -// |window_bounds|. -int GetOffScreenLength(const gfx::Rect& available_bounds, - const gfx::Rect& window_bounds, - bool vertical) { - if (available_bounds.IsEmpty() || available_bounds.Contains(window_bounds)) - return 0; - - // window_bounds - // +---------------------------------+ - // | top | - // | +------------------+ | - // | left | available_bounds | right | - // | +------------------+ | - // | bottom | - // +---------------------------------+ - if (vertical) - return std::max(0, available_bounds.y() - window_bounds.y()) + - std::max(0, window_bounds.bottom() - available_bounds.bottom()); - return std::max(0, available_bounds.x() - window_bounds.x()) + - std::max(0, window_bounds.right() - available_bounds.right()); -} - -} // namespace - -namespace views { - -// static -const char BubbleFrameView::kViewClassName[] = "BubbleFrameView"; - -BubbleFrameView::BubbleFrameView(const gfx::Insets& content_margins) - : bubble_border_(NULL), - content_margins_(content_margins), - title_(NULL), - close_(NULL), - titlebar_extra_view_(NULL) { - ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); - title_ = new Label(base::string16(), - rb.GetFontList(ui::ResourceBundle::MediumFont)); - title_->SetHorizontalAlignment(gfx::ALIGN_LEFT); - AddChildView(title_); - - close_ = CreateCloseButton(this); - close_->SetVisible(false); - AddChildView(close_); -} - -BubbleFrameView::~BubbleFrameView() {} - -// static -gfx::Insets BubbleFrameView::GetTitleInsets() { - return gfx::Insets( - kTitleTopInset, kTitleLeftInset, kTitleBottomInset, kTitleRightInset); -} - -// static -LabelButton* BubbleFrameView::CreateCloseButton(ButtonListener* listener) { - ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); - LabelButton* close = new LabelButton(listener, base::string16()); - close->SetImage(CustomButton::STATE_NORMAL, - *rb.GetImageNamed(IDR_CLOSE_DIALOG).ToImageSkia()); - close->SetImage(CustomButton::STATE_HOVERED, - *rb.GetImageNamed(IDR_CLOSE_DIALOG_H).ToImageSkia()); - close->SetImage(CustomButton::STATE_PRESSED, - *rb.GetImageNamed(IDR_CLOSE_DIALOG_P).ToImageSkia()); - close->SetBorder(scoped_ptr<Border>()); - close->SetSize(close->GetPreferredSize()); - return close; -} - -gfx::Rect BubbleFrameView::GetBoundsForClientView() const { - gfx::Rect client_bounds = GetLocalBounds(); - client_bounds.Inset(GetInsets()); - client_bounds.Inset(bubble_border_->GetInsets()); - return client_bounds; -} - -gfx::Rect BubbleFrameView::GetWindowBoundsForClientBounds( - const gfx::Rect& client_bounds) const { - return const_cast<BubbleFrameView*>(this)->GetUpdatedWindowBounds( - gfx::Rect(), client_bounds.size(), false); -} - -int BubbleFrameView::NonClientHitTest(const gfx::Point& point) { - if (!bounds().Contains(point)) - return HTNOWHERE; - if (close_->visible() && close_->GetMirroredBounds().Contains(point)) - return HTCLOSE; - - // Allow dialogs to show the system menu and be dragged. - if (GetWidget()->widget_delegate()->AsDialogDelegate()) { - gfx::Rect sys_rect(0, 0, title_->x(), title_->y()); - sys_rect.set_origin(gfx::Point(GetMirroredXForRect(sys_rect), 0)); - if (sys_rect.Contains(point)) - return HTSYSMENU; - if (point.y() < title_->bounds().bottom()) - return HTCAPTION; - } - - return GetWidget()->client_view()->NonClientHitTest(point); -} - -void BubbleFrameView::GetWindowMask(const gfx::Size& size, - gfx::Path* window_mask) { - // NOTE: this only provides implementations for the types used by dialogs. - if ((bubble_border_->arrow() != BubbleBorder::NONE && - bubble_border_->arrow() != BubbleBorder::FLOAT) || - (bubble_border_->shadow() != BubbleBorder::SMALL_SHADOW && - bubble_border_->shadow() != BubbleBorder::NO_SHADOW_OPAQUE_BORDER)) - return; - - // Use a window mask roughly matching the border in the image assets. - static const int kBorderStrokeSize = 1; - static const SkScalar kCornerRadius = SkIntToScalar(6); - const gfx::Insets border_insets = bubble_border_->GetInsets(); - SkRect rect = { SkIntToScalar(border_insets.left() - kBorderStrokeSize), - SkIntToScalar(border_insets.top() - kBorderStrokeSize), - SkIntToScalar(size.width() - border_insets.right() + - kBorderStrokeSize), - SkIntToScalar(size.height() - border_insets.bottom() + - kBorderStrokeSize) }; - if (bubble_border_->shadow() == BubbleBorder::NO_SHADOW_OPAQUE_BORDER) { - window_mask->addRoundRect(rect, kCornerRadius, kCornerRadius); - } else { - static const int kBottomBorderShadowSize = 2; - rect.fBottom += SkIntToScalar(kBottomBorderShadowSize); - window_mask->addRect(rect); - } -} - -void BubbleFrameView::ResetWindowControls() { - close_->SetVisible(GetWidget()->widget_delegate()->ShouldShowCloseButton()); -} - -void BubbleFrameView::UpdateWindowIcon() {} - -void BubbleFrameView::UpdateWindowTitle() { - title_->SetText(GetWidget()->widget_delegate()->ShouldShowWindowTitle() ? - GetWidget()->widget_delegate()->GetWindowTitle() : base::string16()); - // Update the close button visibility too, otherwise it's not intialized. - ResetWindowControls(); -} - -void BubbleFrameView::SizeConstraintsChanged() {} - -void BubbleFrameView::SetTitleFontList(const gfx::FontList& font_list) { - title_->SetFontList(font_list); -} - -gfx::Insets BubbleFrameView::GetInsets() const { - gfx::Insets insets = content_margins_; - const int title_height = title_->text().empty() ? 0 : - title_->GetPreferredSize().height() + kTitleTopInset + kTitleBottomInset; - const int close_height = close_->visible() ? close_->height() : 0; - insets += gfx::Insets(std::max(title_height, close_height), 0, 0, 0); - return insets; -} - -gfx::Size BubbleFrameView::GetPreferredSize() const { - return GetSizeForClientSize(GetWidget()->client_view()->GetPreferredSize()); -} - -gfx::Size BubbleFrameView::GetMinimumSize() const { - return GetSizeForClientSize(GetWidget()->client_view()->GetMinimumSize()); -} - -void BubbleFrameView::Layout() { - gfx::Rect bounds(GetContentsBounds()); - bounds.Inset(GetTitleInsets()); - if (bounds.IsEmpty()) - return; - - // The close button top inset is actually smaller than the title top inset. - close_->SetPosition(gfx::Point(bounds.right() - close_->width(), - bounds.y() - 5)); - - gfx::Size title_size(title_->GetPreferredSize()); - const int title_width = std::max(0, close_->x() - bounds.x()); - title_size.SetToMin(gfx::Size(title_width, title_size.height())); - bounds.set_size(title_size); - title_->SetBoundsRect(bounds); - - if (titlebar_extra_view_) { - const int extra_width = close_->x() - title_->bounds().right(); - gfx::Size size = titlebar_extra_view_->GetPreferredSize(); - size.SetToMin(gfx::Size(std::max(0, extra_width), size.height())); - gfx::Rect titlebar_extra_view_bounds( - close_->x() - size.width(), - bounds.y(), - size.width(), - bounds.height()); - titlebar_extra_view_bounds.Subtract(bounds); - titlebar_extra_view_->SetBoundsRect(titlebar_extra_view_bounds); - } -} - -const char* BubbleFrameView::GetClassName() const { - return kViewClassName; -} - -void BubbleFrameView::ChildPreferredSizeChanged(View* child) { - if (child == titlebar_extra_view_ || child == title_) - Layout(); -} - -void BubbleFrameView::OnThemeChanged() { - UpdateWindowTitle(); - ResetWindowControls(); - UpdateWindowIcon(); -} - -void BubbleFrameView::OnNativeThemeChanged(const ui::NativeTheme* theme) { - if (bubble_border_ && bubble_border_->use_theme_background_color()) { - bubble_border_->set_background_color(GetNativeTheme()-> - GetSystemColor(ui::NativeTheme::kColorId_DialogBackground)); - SchedulePaint(); - } -} - -void BubbleFrameView::ButtonPressed(Button* sender, const ui::Event& event) { - if (sender == close_) - GetWidget()->Close(); -} - -void BubbleFrameView::SetBubbleBorder(scoped_ptr<BubbleBorder> border) { - bubble_border_ = border.get(); - SetBorder(border.Pass()); - - // Update the background, which relies on the border. - set_background(new views::BubbleBackground(bubble_border_)); -} - -void BubbleFrameView::SetTitlebarExtraView(View* view) { - DCHECK(view); - DCHECK(!titlebar_extra_view_); - AddChildView(view); - titlebar_extra_view_ = view; -} - -gfx::Rect BubbleFrameView::GetUpdatedWindowBounds(const gfx::Rect& anchor_rect, - gfx::Size client_size, - bool adjust_if_offscreen) { - gfx::Size size(GetSizeForClientSize(client_size)); - - const BubbleBorder::Arrow arrow = bubble_border_->arrow(); - if (adjust_if_offscreen && BubbleBorder::has_arrow(arrow)) { - // Try to mirror the anchoring if the bubble does not fit on the screen. - if (!bubble_border_->is_arrow_at_center(arrow)) { - MirrorArrowIfOffScreen(true, anchor_rect, size); - MirrorArrowIfOffScreen(false, anchor_rect, size); - } else { - const bool mirror_vertical = BubbleBorder::is_arrow_on_horizontal(arrow); - MirrorArrowIfOffScreen(mirror_vertical, anchor_rect, size); - OffsetArrowIfOffScreen(anchor_rect, size); - } - } - - // Calculate the bounds with the arrow in its updated location and offset. - return bubble_border_->GetBounds(anchor_rect, size); -} - -gfx::Rect BubbleFrameView::GetAvailableScreenBounds(const gfx::Rect& rect) { - // The bubble attempts to fit within the current screen bounds. - // TODO(scottmg): Native is wrong. http://crbug.com/133312 - return gfx::Screen::GetNativeScreen()->GetDisplayNearestPoint( - rect.CenterPoint()).work_area(); -} - -bool BubbleFrameView::IsCloseButtonVisible() const { - return close_->visible(); -} - -gfx::Rect BubbleFrameView::GetCloseButtonBounds() const { - return close_->bounds(); -} - -void BubbleFrameView::MirrorArrowIfOffScreen( - bool vertical, - const gfx::Rect& anchor_rect, - const gfx::Size& client_size) { - // Check if the bounds don't fit on screen. - gfx::Rect available_bounds(GetAvailableScreenBounds(anchor_rect)); - gfx::Rect window_bounds(bubble_border_->GetBounds(anchor_rect, client_size)); - if (GetOffScreenLength(available_bounds, window_bounds, vertical) > 0) { - BubbleBorder::Arrow arrow = bubble_border()->arrow(); - // Mirror the arrow and get the new bounds. - bubble_border_->set_arrow( - vertical ? BubbleBorder::vertical_mirror(arrow) : - BubbleBorder::horizontal_mirror(arrow)); - gfx::Rect mirror_bounds = - bubble_border_->GetBounds(anchor_rect, client_size); - // Restore the original arrow if mirroring doesn't show more of the bubble. - // Otherwise it should invoke parent's Layout() to layout the content based - // on the new bubble border. - if (GetOffScreenLength(available_bounds, mirror_bounds, vertical) >= - GetOffScreenLength(available_bounds, window_bounds, vertical)) - bubble_border_->set_arrow(arrow); - else if (parent()) - parent()->Layout(); - } -} - -void BubbleFrameView::OffsetArrowIfOffScreen(const gfx::Rect& anchor_rect, - const gfx::Size& client_size) { - BubbleBorder::Arrow arrow = bubble_border()->arrow(); - DCHECK(BubbleBorder::is_arrow_at_center(arrow)); - - // Get the desired bubble bounds without adjustment. - bubble_border_->set_arrow_offset(0); - gfx::Rect window_bounds(bubble_border_->GetBounds(anchor_rect, client_size)); - - gfx::Rect available_bounds(GetAvailableScreenBounds(anchor_rect)); - if (available_bounds.IsEmpty() || available_bounds.Contains(window_bounds)) - return; - - // Calculate off-screen adjustment. - const bool is_horizontal = BubbleBorder::is_arrow_on_horizontal(arrow); - int offscreen_adjust = 0; - if (is_horizontal) { - if (window_bounds.x() < available_bounds.x()) - offscreen_adjust = available_bounds.x() - window_bounds.x(); - else if (window_bounds.right() > available_bounds.right()) - offscreen_adjust = available_bounds.right() - window_bounds.right(); - } else { - if (window_bounds.y() < available_bounds.y()) - offscreen_adjust = available_bounds.y() - window_bounds.y(); - else if (window_bounds.bottom() > available_bounds.bottom()) - offscreen_adjust = available_bounds.bottom() - window_bounds.bottom(); - } - - // For center arrows, arrows are moved in the opposite direction of - // |offscreen_adjust|, e.g. positive |offscreen_adjust| means bubble - // window needs to be moved to the right and that means we need to move arrow - // to the left, and that means negative offset. - bubble_border_->set_arrow_offset( - bubble_border_->GetArrowOffset(window_bounds.size()) - offscreen_adjust); - if (offscreen_adjust) - SchedulePaint(); -} - -gfx::Size BubbleFrameView::GetSizeForClientSize( - const gfx::Size& client_size) const { - // Accommodate the width of the title bar elements. - int title_bar_width = GetInsets().width() + border()->GetInsets().width(); - if (!title_->text().empty()) - title_bar_width += kTitleLeftInset + title_->GetPreferredSize().width(); - if (close_->visible()) - title_bar_width += close_->width() + 1; - if (titlebar_extra_view_ != NULL) - title_bar_width += titlebar_extra_view_->GetPreferredSize().width(); - gfx::Size size(client_size); - size.SetToMax(gfx::Size(title_bar_width, 0)); - const gfx::Insets insets(GetInsets()); - size.Enlarge(insets.width(), insets.height()); - return size; -} - -} // namespace views
diff --git a/ui/views/bubble/bubble_frame_view.h b/ui/views/bubble/bubble_frame_view.h deleted file mode 100644 index 1d3add7..0000000 --- a/ui/views/bubble/bubble_frame_view.h +++ /dev/null
@@ -1,129 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_BUBBLE_BUBBLE_FRAME_VIEW_H_ -#define UI_VIEWS_BUBBLE_BUBBLE_FRAME_VIEW_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/gtest_prod_util.h" -#include "ui/gfx/insets.h" -#include "ui/views/controls/button/button.h" -#include "ui/views/window/non_client_view.h" - -namespace gfx { -class FontList; -} - -namespace views { - -class Label; -class LabelButton; -class BubbleBorder; - -// The non-client frame view of bubble-styled widgets. -class VIEWS_EXPORT BubbleFrameView : public NonClientFrameView, - public ButtonListener { - public: - // Internal class name. - static const char kViewClassName[]; - - explicit BubbleFrameView(const gfx::Insets& content_margins); - virtual ~BubbleFrameView(); - - // Insets to make bubble contents align horizontal with the bubble title. - // NOTE: this does not take into account whether a title actually exists. - static gfx::Insets GetTitleInsets(); - - // Creates a close button used in the corner of the dialog. - static LabelButton* CreateCloseButton(ButtonListener* listener); - - // NonClientFrameView overrides: - virtual gfx::Rect GetBoundsForClientView() const override; - virtual gfx::Rect GetWindowBoundsForClientBounds( - const gfx::Rect& client_bounds) const override; - virtual int NonClientHitTest(const gfx::Point& point) override; - virtual void GetWindowMask(const gfx::Size& size, - gfx::Path* window_mask) override; - virtual void ResetWindowControls() override; - virtual void UpdateWindowIcon() override; - virtual void UpdateWindowTitle() override; - virtual void SizeConstraintsChanged() override; - - // Set the FontList to be used for the title of the bubble. - // Caller must arrange to update the layout to have the call take effect. - void SetTitleFontList(const gfx::FontList& font_list); - - // View overrides: - virtual gfx::Insets GetInsets() const override; - virtual gfx::Size GetPreferredSize() const override; - virtual gfx::Size GetMinimumSize() const override; - virtual void Layout() override; - virtual const char* GetClassName() const override; - virtual void ChildPreferredSizeChanged(View* child) override; - virtual void OnThemeChanged() override; - virtual void OnNativeThemeChanged(const ui::NativeTheme* theme) override; - - // Overridden from ButtonListener: - virtual void ButtonPressed(Button* sender, const ui::Event& event) override; - - // Use bubble_border() and SetBubbleBorder(), not border() and SetBorder(). - BubbleBorder* bubble_border() const { return bubble_border_; } - void SetBubbleBorder(scoped_ptr<BubbleBorder> border); - - gfx::Insets content_margins() const { return content_margins_; } - - void SetTitlebarExtraView(View* view); - - // Given the size of the contents and the rect to point at, returns the bounds - // of the bubble window. The bubble's arrow location may change if the bubble - // does not fit on the monitor and |adjust_if_offscreen| is true. - gfx::Rect GetUpdatedWindowBounds(const gfx::Rect& anchor_rect, - gfx::Size client_size, - bool adjust_if_offscreen); - - protected: - // Returns the available screen bounds if the frame were to show in |rect|. - virtual gfx::Rect GetAvailableScreenBounds(const gfx::Rect& rect); - - bool IsCloseButtonVisible() const; - gfx::Rect GetCloseButtonBounds() const; - - private: - FRIEND_TEST_ALL_PREFIXES(BubbleFrameViewTest, GetBoundsForClientView); - - // Mirrors the bubble's arrow location on the |vertical| or horizontal axis, - // if the generated window bounds don't fit in the monitor bounds. - void MirrorArrowIfOffScreen(bool vertical, - const gfx::Rect& anchor_rect, - const gfx::Size& client_size); - - // Adjust the bubble's arrow offsets if the generated window bounds don't fit - // in the monitor bounds. - void OffsetArrowIfOffScreen(const gfx::Rect& anchor_rect, - const gfx::Size& client_size); - - // Calculates the size needed to accommodate the given client area. - gfx::Size GetSizeForClientSize(const gfx::Size& client_size) const; - - // The bubble border. - BubbleBorder* bubble_border_; - - // Margins between the content and the inside of the border, in pixels. - gfx::Insets content_margins_; - - // The optional title and (x) close button. - Label* title_; - LabelButton* close_; - - // When supplied, this view is placed in the titlebar between the title and - // (x) close button. - View* titlebar_extra_view_; - - DISALLOW_COPY_AND_ASSIGN(BubbleFrameView); -}; - -} // namespace views - -#endif // UI_VIEWS_BUBBLE_BUBBLE_FRAME_VIEW_H_
diff --git a/ui/views/bubble/bubble_frame_view_unittest.cc b/ui/views/bubble/bubble_frame_view_unittest.cc deleted file mode 100644 index 545ca38..0000000 --- a/ui/views/bubble/bubble_frame_view_unittest.cc +++ /dev/null
@@ -1,352 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/gfx/insets.h" -#include "ui/views/bubble/bubble_border.h" -#include "ui/views/bubble/bubble_frame_view.h" -#include "ui/views/test/views_test_base.h" -#include "ui/views/widget/widget.h" - -namespace views { - -typedef ViewsTestBase BubbleFrameViewTest; - -namespace { - -const BubbleBorder::Arrow kArrow = BubbleBorder::TOP_LEFT; -const SkColor kColor = SK_ColorRED; -const int kMargin = 6; - -class TestBubbleFrameView : public BubbleFrameView { - public: - TestBubbleFrameView() - : BubbleFrameView(gfx::Insets(kMargin, kMargin, kMargin, kMargin)), - available_bounds_(gfx::Rect(0, 0, 1000, 1000)) { - SetBubbleBorder(scoped_ptr<views::BubbleBorder>( - new BubbleBorder(kArrow, BubbleBorder::NO_SHADOW, kColor))); - } - virtual ~TestBubbleFrameView() {} - - // BubbleFrameView overrides: - virtual gfx::Rect GetAvailableScreenBounds(const gfx::Rect& rect) override { - return available_bounds_; - } - - private: - gfx::Rect available_bounds_; - - DISALLOW_COPY_AND_ASSIGN(TestBubbleFrameView); -}; - -} // namespace - -TEST_F(BubbleFrameViewTest, GetBoundsForClientView) { - TestBubbleFrameView frame; - EXPECT_EQ(kArrow, frame.bubble_border()->arrow()); - EXPECT_EQ(kColor, frame.bubble_border()->background_color()); - - int margin_x = frame.content_margins().left(); - int margin_y = frame.content_margins().top(); - gfx::Insets insets = frame.bubble_border()->GetInsets(); - EXPECT_EQ(insets.left() + margin_x, frame.GetBoundsForClientView().x()); - EXPECT_EQ(insets.top() + margin_y, frame.GetBoundsForClientView().y()); -} - -// Tests that the arrow is mirrored as needed to better fit the screen. -TEST_F(BubbleFrameViewTest, GetUpdatedWindowBounds) { - TestBubbleFrameView frame; - gfx::Rect window_bounds; - - gfx::Insets insets = frame.bubble_border()->GetInsets(); - int xposition = 95 - insets.width(); - - // Test that the info bubble displays normally when it fits. - frame.bubble_border()->set_arrow(BubbleBorder::TOP_LEFT); - window_bounds = frame.GetUpdatedWindowBounds( - gfx::Rect(100, 100, 50, 50), // |anchor_rect| - gfx::Size(500, 500), // |client_size| - true); // |adjust_if_offscreen| - EXPECT_EQ(BubbleBorder::TOP_LEFT, frame.bubble_border()->arrow()); - EXPECT_GT(window_bounds.x(), xposition); - EXPECT_GT(window_bounds.y(), 100 + 50 - 10); // -10 to roughly compensate for - // arrow overlap. - - // Test bubble not fitting on left. - frame.bubble_border()->set_arrow(BubbleBorder::TOP_RIGHT); - window_bounds = frame.GetUpdatedWindowBounds( - gfx::Rect(100, 100, 50, 50), // |anchor_rect| - gfx::Size(500, 500), // |client_size| - true); // |adjust_if_offscreen| - EXPECT_EQ(BubbleBorder::TOP_LEFT, frame.bubble_border()->arrow()); - EXPECT_GT(window_bounds.x(), xposition); - EXPECT_GT(window_bounds.y(), 100 + 50 - 10); // -10 to roughly compensate for - // arrow overlap. - - // Test bubble not fitting on left or top. - frame.bubble_border()->set_arrow(BubbleBorder::BOTTOM_RIGHT); - window_bounds = frame.GetUpdatedWindowBounds( - gfx::Rect(100, 100, 50, 50), // |anchor_rect| - gfx::Size(500, 500), // |client_size| - true); // |adjust_if_offscreen| - EXPECT_EQ(BubbleBorder::TOP_LEFT, frame.bubble_border()->arrow()); - EXPECT_GT(window_bounds.x(), xposition); - EXPECT_GT(window_bounds.y(), 100 + 50 - 10); // -10 to roughly compensate for - // arrow overlap. - - // Test bubble not fitting on top. - frame.bubble_border()->set_arrow(BubbleBorder::BOTTOM_LEFT); - window_bounds = frame.GetUpdatedWindowBounds( - gfx::Rect(100, 100, 50, 50), // |anchor_rect| - gfx::Size(500, 500), // |client_size| - true); // |adjust_if_offscreen| - EXPECT_EQ(BubbleBorder::TOP_LEFT, frame.bubble_border()->arrow()); - EXPECT_GT(window_bounds.x(), xposition); - EXPECT_GT(window_bounds.y(), 100 + 50 - 10); // -10 to roughly compensate for - // arrow overlap. - - // Test bubble not fitting on top and right. - frame.bubble_border()->set_arrow(BubbleBorder::BOTTOM_LEFT); - window_bounds = frame.GetUpdatedWindowBounds( - gfx::Rect(900, 100, 50, 50), // |anchor_rect| - gfx::Size(500, 500), // |client_size| - true); // |adjust_if_offscreen| - EXPECT_EQ(BubbleBorder::TOP_RIGHT, frame.bubble_border()->arrow()); - EXPECT_LT(window_bounds.x(), 900 + 50 - 500); - EXPECT_GT(window_bounds.y(), 100 + 50 - 10); // -10 to roughly compensate for - // arrow overlap. - - // Test bubble not fitting on right. - frame.bubble_border()->set_arrow(BubbleBorder::TOP_LEFT); - window_bounds = frame.GetUpdatedWindowBounds( - gfx::Rect(900, 100, 50, 50), // |anchor_rect| - gfx::Size(500, 500), // |client_size| - true); // |adjust_if_offscreen| - EXPECT_EQ(BubbleBorder::TOP_RIGHT, frame.bubble_border()->arrow()); - EXPECT_LT(window_bounds.x(), 900 + 50 - 500); - EXPECT_GT(window_bounds.y(), 100 + 50 - 10); // -10 to roughly compensate for - // arrow overlap. - - // Test bubble not fitting on bottom and right. - frame.bubble_border()->set_arrow(BubbleBorder::TOP_LEFT); - window_bounds = frame.GetUpdatedWindowBounds( - gfx::Rect(900, 900, 50, 50), // |anchor_rect| - gfx::Size(500, 500), // |client_size| - true); // |adjust_if_offscreen| - EXPECT_EQ(BubbleBorder::BOTTOM_RIGHT, frame.bubble_border()->arrow()); - EXPECT_LT(window_bounds.x(), 900 + 50 - 500); - EXPECT_LT(window_bounds.y(), 900 - 500 - 15); // -15 to roughly compensate - // for arrow height. - - // Test bubble not fitting at the bottom. - frame.bubble_border()->set_arrow(BubbleBorder::TOP_LEFT); - window_bounds = frame.GetUpdatedWindowBounds( - gfx::Rect(100, 900, 50, 50), // |anchor_rect| - gfx::Size(500, 500), // |client_size| - true); // |adjust_if_offscreen| - EXPECT_EQ(BubbleBorder::BOTTOM_LEFT, frame.bubble_border()->arrow()); - // The window should be right aligned with the anchor_rect. - EXPECT_LT(window_bounds.x(), 900 + 50 - 500); - EXPECT_LT(window_bounds.y(), 900 - 500 - 15); // -15 to roughly compensate - // for arrow height. - - // Test bubble not fitting at the bottom and left. - frame.bubble_border()->set_arrow(BubbleBorder::TOP_RIGHT); - window_bounds = frame.GetUpdatedWindowBounds( - gfx::Rect(100, 900, 50, 50), // |anchor_rect| - gfx::Size(500, 500), // |client_size| - true); // |adjust_if_offscreen| - EXPECT_EQ(BubbleBorder::BOTTOM_LEFT, frame.bubble_border()->arrow()); - // The window should be right aligned with the anchor_rect. - EXPECT_LT(window_bounds.x(), 900 + 50 - 500); - EXPECT_LT(window_bounds.y(), 900 - 500 - 15); // -15 to roughly compensate - // for arrow height. -} - -// Tests that the arrow is not moved when the info-bubble does not fit the -// screen but moving it would make matter worse. -TEST_F(BubbleFrameViewTest, GetUpdatedWindowBoundsMirroringFails) { - TestBubbleFrameView frame; - frame.bubble_border()->set_arrow(BubbleBorder::TOP_LEFT); - gfx::Rect window_bounds = frame.GetUpdatedWindowBounds( - gfx::Rect(400, 100, 50, 50), // |anchor_rect| - gfx::Size(500, 700), // |client_size| - true); // |adjust_if_offscreen| - EXPECT_EQ(BubbleBorder::TOP_LEFT, frame.bubble_border()->arrow()); -} - -TEST_F(BubbleFrameViewTest, TestMirroringForCenteredArrow) { - TestBubbleFrameView frame; - - // Test bubble not fitting above the anchor. - frame.bubble_border()->set_arrow(BubbleBorder::BOTTOM_CENTER); - gfx::Rect window_bounds = frame.GetUpdatedWindowBounds( - gfx::Rect(100, 100, 50, 50), // |anchor_rect| - gfx::Size(500, 700), // |client_size| - true); // |adjust_if_offscreen| - EXPECT_EQ(BubbleBorder::TOP_CENTER, frame.bubble_border()->arrow()); - - // Test bubble not fitting below the anchor. - frame.bubble_border()->set_arrow(BubbleBorder::TOP_CENTER); - window_bounds = frame.GetUpdatedWindowBounds( - gfx::Rect(300, 800, 50, 50), // |anchor_rect| - gfx::Size(500, 200), // |client_size| - true); // |adjust_if_offscreen| - EXPECT_EQ(BubbleBorder::BOTTOM_CENTER, frame.bubble_border()->arrow()); - - // Test bubble not fitting to the right of the anchor. - frame.bubble_border()->set_arrow(BubbleBorder::LEFT_CENTER); - window_bounds = frame.GetUpdatedWindowBounds( - gfx::Rect(800, 300, 50, 50), // |anchor_rect| - gfx::Size(200, 500), // |client_size| - true); // |adjust_if_offscreen| - EXPECT_EQ(BubbleBorder::RIGHT_CENTER, frame.bubble_border()->arrow()); - - // Test bubble not fitting to the left of the anchor. - frame.bubble_border()->set_arrow(BubbleBorder::RIGHT_CENTER); - window_bounds = frame.GetUpdatedWindowBounds( - gfx::Rect(100, 300, 50, 50), // |anchor_rect| - gfx::Size(500, 500), // |client_size| - true); // |adjust_if_offscreen| - EXPECT_EQ(BubbleBorder::LEFT_CENTER, frame.bubble_border()->arrow()); -} - -// Test that the arrow will not be mirrored when |adjust_if_offscreen| is false. -TEST_F(BubbleFrameViewTest, GetUpdatedWindowBoundsDontTryMirror) { - TestBubbleFrameView frame; - frame.bubble_border()->set_arrow(BubbleBorder::TOP_RIGHT); - gfx::Rect window_bounds = frame.GetUpdatedWindowBounds( - gfx::Rect(100, 900, 50, 50), // |anchor_rect| - gfx::Size(500, 500), // |client_size| - false); // |adjust_if_offscreen| - EXPECT_EQ(BubbleBorder::TOP_RIGHT, frame.bubble_border()->arrow()); - // The coordinates should be pointing to anchor_rect from TOP_RIGHT. - EXPECT_LT(window_bounds.x(), 100 + 50 - 500); - EXPECT_GT(window_bounds.y(), 900 + 50 - 10); // -10 to roughly compensate for - // arrow overlap. -} - -// Test that the center arrow is moved as needed to fit the screen. -TEST_F(BubbleFrameViewTest, GetUpdatedWindowBoundsCenterArrows) { - TestBubbleFrameView frame; - gfx::Rect window_bounds; - - // Test that the bubble displays normally when it fits. - frame.bubble_border()->set_arrow(BubbleBorder::TOP_CENTER); - window_bounds = frame.GetUpdatedWindowBounds( - gfx::Rect(500, 100, 50, 50), // |anchor_rect| - gfx::Size(500, 500), // |client_size| - true); // |adjust_if_offscreen| - EXPECT_EQ(BubbleBorder::TOP_CENTER, frame.bubble_border()->arrow()); - EXPECT_EQ(window_bounds.x() + window_bounds.width() / 2, 525); - - frame.bubble_border()->set_arrow(BubbleBorder::BOTTOM_CENTER); - window_bounds = frame.GetUpdatedWindowBounds( - gfx::Rect(500, 900, 50, 50), // |anchor_rect| - gfx::Size(500, 500), // |client_size| - true); // |adjust_if_offscreen| - EXPECT_EQ(BubbleBorder::BOTTOM_CENTER, frame.bubble_border()->arrow()); - EXPECT_EQ(window_bounds.x() + window_bounds.width() / 2, 525); - - frame.bubble_border()->set_arrow(BubbleBorder::LEFT_CENTER); - window_bounds = frame.GetUpdatedWindowBounds( - gfx::Rect(100, 400, 50, 50), // |anchor_rect| - gfx::Size(500, 500), // |client_size| - true); // |adjust_if_offscreen| - EXPECT_EQ(BubbleBorder::LEFT_CENTER, frame.bubble_border()->arrow()); - EXPECT_EQ(window_bounds.y() + window_bounds.height() / 2, 425); - - frame.bubble_border()->set_arrow(BubbleBorder::RIGHT_CENTER); - window_bounds = frame.GetUpdatedWindowBounds( - gfx::Rect(900, 400, 50, 50), // |anchor_rect| - gfx::Size(500, 500), // |client_size| - true); // |adjust_if_offscreen| - EXPECT_EQ(BubbleBorder::RIGHT_CENTER, frame.bubble_border()->arrow()); - EXPECT_EQ(window_bounds.y() + window_bounds.height() / 2, 425); - - // Test bubble not fitting left screen edge. - frame.bubble_border()->set_arrow(BubbleBorder::TOP_CENTER); - window_bounds = frame.GetUpdatedWindowBounds( - gfx::Rect(100, 100, 50, 50), // |anchor_rect| - gfx::Size(500, 500), // |client_size| - true); // |adjust_if_offscreen| - EXPECT_EQ(BubbleBorder::TOP_CENTER, frame.bubble_border()->arrow()); - EXPECT_EQ(window_bounds.x(), 0); - EXPECT_EQ(window_bounds.x() + - frame.bubble_border()->GetArrowOffset(window_bounds.size()), 125); - - frame.bubble_border()->set_arrow(BubbleBorder::BOTTOM_CENTER); - window_bounds = frame.GetUpdatedWindowBounds( - gfx::Rect(100, 900, 50, 50), // |anchor_rect| - gfx::Size(500, 500), // |client_size| - true); // |adjust_if_offscreen| - EXPECT_EQ(BubbleBorder::BOTTOM_CENTER, frame.bubble_border()->arrow()); - EXPECT_EQ(window_bounds.x(), 0); - EXPECT_EQ(window_bounds.x() + - frame.bubble_border()->GetArrowOffset(window_bounds.size()), 125); - - // Test bubble not fitting right screen edge. - frame.bubble_border()->set_arrow(BubbleBorder::TOP_CENTER); - window_bounds = frame.GetUpdatedWindowBounds( - gfx::Rect(900, 100, 50, 50), // |anchor_rect| - gfx::Size(500, 500), // |client_size| - true); // |adjust_if_offscreen| - EXPECT_EQ(BubbleBorder::TOP_CENTER, frame.bubble_border()->arrow()); - EXPECT_EQ(window_bounds.right(), 1000); - EXPECT_EQ(window_bounds.x() + - frame.bubble_border()->GetArrowOffset(window_bounds.size()), 925); - - frame.bubble_border()->set_arrow(BubbleBorder::BOTTOM_CENTER); - window_bounds = frame.GetUpdatedWindowBounds( - gfx::Rect(900, 900, 50, 50), // |anchor_rect| - gfx::Size(500, 500), // |client_size| - true); // |adjust_if_offscreen| - EXPECT_EQ(BubbleBorder::BOTTOM_CENTER, frame.bubble_border()->arrow()); - EXPECT_EQ(window_bounds.right(), 1000); - EXPECT_EQ(window_bounds.x() + - frame.bubble_border()->GetArrowOffset(window_bounds.size()), 925); - - // Test bubble not fitting top screen edge. - frame.bubble_border()->set_arrow(BubbleBorder::LEFT_CENTER); - window_bounds = frame.GetUpdatedWindowBounds( - gfx::Rect(100, 100, 50, 50), // |anchor_rect| - gfx::Size(500, 500), // |client_size| - true); // |adjust_if_offscreen| - EXPECT_EQ(BubbleBorder::LEFT_CENTER, frame.bubble_border()->arrow()); - EXPECT_EQ(window_bounds.y(), 0); - EXPECT_EQ(window_bounds.y() + - frame.bubble_border()->GetArrowOffset(window_bounds.size()), 125); - - frame.bubble_border()->set_arrow(BubbleBorder::RIGHT_CENTER); - window_bounds = frame.GetUpdatedWindowBounds( - gfx::Rect(900, 100, 50, 50), // |anchor_rect| - gfx::Size(500, 500), // |client_size| - true); // |adjust_if_offscreen| - EXPECT_EQ(BubbleBorder::RIGHT_CENTER, frame.bubble_border()->arrow()); - EXPECT_EQ(window_bounds.y(), 0); - EXPECT_EQ(window_bounds.y() + - frame.bubble_border()->GetArrowOffset(window_bounds.size()), 125); - - // Test bubble not fitting bottom screen edge. - frame.bubble_border()->set_arrow(BubbleBorder::LEFT_CENTER); - window_bounds = frame.GetUpdatedWindowBounds( - gfx::Rect(100, 900, 50, 50), // |anchor_rect| - gfx::Size(500, 500), // |client_size| - true); // |adjust_if_offscreen| - EXPECT_EQ(BubbleBorder::LEFT_CENTER, frame.bubble_border()->arrow()); - EXPECT_EQ(window_bounds.bottom(), 1000); - EXPECT_EQ(window_bounds.y() + - frame.bubble_border()->GetArrowOffset(window_bounds.size()), 925); - - frame.bubble_border()->set_arrow(BubbleBorder::RIGHT_CENTER); - window_bounds = frame.GetUpdatedWindowBounds( - gfx::Rect(900, 900, 50, 50), // |anchor_rect| - gfx::Size(500, 500), // |client_size| - true); // |adjust_if_offscreen| - EXPECT_EQ(BubbleBorder::RIGHT_CENTER, frame.bubble_border()->arrow()); - EXPECT_EQ(window_bounds.bottom(), 1000); - EXPECT_EQ(window_bounds.y() + - frame.bubble_border()->GetArrowOffset(window_bounds.size()), 925); -} - -} // namespace views
diff --git a/ui/views/bubble/bubble_window_targeter.cc b/ui/views/bubble/bubble_window_targeter.cc deleted file mode 100644 index 19e0c85..0000000 --- a/ui/views/bubble/bubble_window_targeter.cc +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/bubble/bubble_window_targeter.h" - -#include "ui/aura/window.h" -#include "ui/gfx/path.h" -#include "ui/gfx/skia_util.h" -#include "ui/views/bubble/bubble_delegate.h" -#include "ui/views/bubble/bubble_frame_view.h" - -namespace views { - -BubbleWindowTargeter::BubbleWindowTargeter(BubbleDelegateView* bubble) - : wm::MaskedWindowTargeter(bubble->GetWidget()->GetNativeView()), - bubble_(bubble) { -} - -BubbleWindowTargeter::~BubbleWindowTargeter() { -} - -bool BubbleWindowTargeter::GetHitTestMask(aura::Window* window, - gfx::Path* mask) const { - mask->addRect( - gfx::RectToSkRect(bubble_->GetBubbleFrameView()->GetContentsBounds())); - return true; -} - -} // namespace views
diff --git a/ui/views/bubble/bubble_window_targeter.h b/ui/views/bubble/bubble_window_targeter.h deleted file mode 100644 index b37eaa0..0000000 --- a/ui/views/bubble/bubble_window_targeter.h +++ /dev/null
@@ -1,33 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/views_export.h" -#include "ui/wm/core/masked_window_targeter.h" - -namespace aura { -class Window; -} - -namespace views { -class BubbleDelegateView; - -// A convenient window-targeter that uses a mask based on the content-bounds of -// the bubble-frame. -class VIEWS_EXPORT BubbleWindowTargeter - : public NON_EXPORTED_BASE(wm::MaskedWindowTargeter) { - public: - explicit BubbleWindowTargeter(BubbleDelegateView* bubble); - virtual ~BubbleWindowTargeter(); - - private: - // wm::MaskedWindowTargeter: - virtual bool GetHitTestMask(aura::Window* window, - gfx::Path* mask) const override; - - views::BubbleDelegateView* bubble_; - - DISALLOW_COPY_AND_ASSIGN(BubbleWindowTargeter); -}; - -} // namespace views
diff --git a/ui/views/bubble/bubble_window_targeter_unittest.cc b/ui/views/bubble/bubble_window_targeter_unittest.cc deleted file mode 100644 index 4ff0e0a..0000000 --- a/ui/views/bubble/bubble_window_targeter_unittest.cc +++ /dev/null
@@ -1,116 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/bubble/bubble_window_targeter.h" - -#include "ui/aura/window.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/views/bubble/bubble_border.h" -#include "ui/views/bubble/bubble_delegate.h" -#include "ui/views/test/views_test_base.h" -#include "ui/views/widget/widget.h" - -namespace views { - -namespace { - -class WidgetOwnsNativeBubble : public BubbleDelegateView { - public: - WidgetOwnsNativeBubble(View* content, BubbleBorder::Arrow arrow) - : BubbleDelegateView(content, arrow) { - } - - virtual ~WidgetOwnsNativeBubble() {} - - private: - // BubbleDelegateView: - virtual void OnBeforeBubbleWidgetInit(Widget::InitParams* params, - Widget* widget) const override { - params->ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - } - - DISALLOW_COPY_AND_ASSIGN(WidgetOwnsNativeBubble); -}; - -} // namespace - -class BubbleWindowTargeterTest : public ViewsTestBase { - public: - BubbleWindowTargeterTest() - : bubble_delegate_(NULL) { - } - virtual ~BubbleWindowTargeterTest() {} - - virtual void SetUp() override { - ViewsTestBase::SetUp(); - CreateAnchorWidget(); - CreateBubbleWidget(); - - anchor_widget()->Show(); - bubble_widget()->Show(); - } - - virtual void TearDown() override { - bubble_delegate_ = NULL; - bubble_widget_.reset(); - anchor_.reset(); - ViewsTestBase::TearDown(); - } - - Widget* anchor_widget() { return anchor_.get(); } - Widget* bubble_widget() { return bubble_widget_.get(); } - BubbleDelegateView* bubble_delegate() { return bubble_delegate_; } - - private: - void CreateAnchorWidget() { - anchor_.reset(new Widget()); - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); - params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - anchor_->Init(params); - } - - void CreateBubbleWidget() { - bubble_delegate_ = new WidgetOwnsNativeBubble( - anchor_->GetContentsView(), BubbleBorder::NONE); - bubble_delegate_->set_color(SK_ColorGREEN); - bubble_widget_.reset(BubbleDelegateView::CreateBubble(bubble_delegate_)); - } - - scoped_ptr<Widget> anchor_; - scoped_ptr<Widget> bubble_widget_; - BubbleDelegateView* bubble_delegate_; - - DISALLOW_COPY_AND_ASSIGN(BubbleWindowTargeterTest); -}; - -TEST_F(BubbleWindowTargeterTest, HitTest) { - ui::EventTarget* root = bubble_widget()->GetNativeWindow()->GetRootWindow(); - ui::EventTargeter* targeter = root->GetEventTargeter(); - aura::Window* bubble_window = bubble_widget()->GetNativeWindow(); - gfx::Rect bubble_bounds = bubble_window->GetBoundsInRootWindow(); - - { - bubble_delegate()->set_margins(gfx::Insets()); - ui::MouseEvent move1(ui::ET_MOUSE_MOVED, bubble_bounds.origin(), - bubble_bounds.origin(), ui::EF_NONE, ui::EF_NONE); - EXPECT_EQ(bubble_window, targeter->FindTargetForEvent(root, &move1)); - } - { - bubble_delegate()->set_margins(gfx::Insets(20, 20, 20, 20)); - ui::MouseEvent move1(ui::ET_MOUSE_MOVED, bubble_bounds.origin(), - bubble_bounds.origin(), ui::EF_NONE, ui::EF_NONE); - EXPECT_EQ(bubble_window, targeter->FindTargetForEvent(root, &move1)); - } - - bubble_window->SetEventTargeter(scoped_ptr<ui::EventTargeter>( - new BubbleWindowTargeter(bubble_delegate()))); - { - bubble_delegate()->set_margins(gfx::Insets(20, 20, 20, 20)); - ui::MouseEvent move1(ui::ET_MOUSE_MOVED, bubble_bounds.origin(), - bubble_bounds.origin(), ui::EF_NONE, ui::EF_NONE); - EXPECT_NE(bubble_window, targeter->FindTargetForEvent(root, &move1)); - } -} - -} // namespace views
diff --git a/ui/views/bubble/tray_bubble_view.cc b/ui/views/bubble/tray_bubble_view.cc deleted file mode 100644 index 53cb526..0000000 --- a/ui/views/bubble/tray_bubble_view.cc +++ /dev/null
@@ -1,508 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/bubble/tray_bubble_view.h" - -#include <algorithm> - -#include "third_party/skia/include/core/SkCanvas.h" -#include "third_party/skia/include/core/SkColor.h" -#include "third_party/skia/include/core/SkPaint.h" -#include "third_party/skia/include/core/SkPath.h" -#include "third_party/skia/include/effects/SkBlurImageFilter.h" -#include "ui/accessibility/ax_view_state.h" -#include "ui/aura/window.h" -#include "ui/compositor/layer.h" -#include "ui/compositor/layer_delegate.h" -#include "ui/events/event.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/insets.h" -#include "ui/gfx/path.h" -#include "ui/gfx/rect.h" -#include "ui/gfx/skia_util.h" -#include "ui/views/bubble/bubble_frame_view.h" -#include "ui/views/bubble/bubble_window_targeter.h" -#include "ui/views/layout/box_layout.h" -#include "ui/views/widget/widget.h" - -namespace { - -// Inset the arrow a bit from the edge. -const int kArrowMinOffset = 20; -const int kBubbleSpacing = 20; - -// The new theme adjusts the menus / bubbles to be flush with the shelf when -// there is no bubble. These are the offsets which need to be applied. -const int kArrowOffsetTopBottom = 4; -const int kArrowOffsetLeft = 9; -const int kArrowOffsetRight = -5; -const int kOffsetLeftRightForTopBottomOrientation = 5; - -// The sampling time for mouse position changes in ms - which is roughly a frame -// time. -const int kFrameTimeInMS = 30; -} // namespace - -namespace views { - -namespace internal { - -// Detects any mouse movement. This is needed to detect mouse movements by the -// user over the bubble if the bubble got created underneath the cursor. -class MouseMoveDetectorHost : public MouseWatcherHost { - public: - MouseMoveDetectorHost(); - virtual ~MouseMoveDetectorHost(); - - virtual bool Contains(const gfx::Point& screen_point, - MouseEventType type) override; - private: - DISALLOW_COPY_AND_ASSIGN(MouseMoveDetectorHost); -}; - -MouseMoveDetectorHost::MouseMoveDetectorHost() { -} - -MouseMoveDetectorHost::~MouseMoveDetectorHost() { -} - -bool MouseMoveDetectorHost::Contains(const gfx::Point& screen_point, - MouseEventType type) { - return false; -} - -// Custom border for TrayBubbleView. Contains special logic for GetBounds() -// to stack bubbles with no arrows correctly. Also calculates the arrow offset. -class TrayBubbleBorder : public BubbleBorder { - public: - TrayBubbleBorder(View* owner, - View* anchor, - TrayBubbleView::InitParams params) - : BubbleBorder(params.arrow, params.shadow, params.arrow_color), - owner_(owner), - anchor_(anchor), - tray_arrow_offset_(params.arrow_offset), - first_item_has_no_margin_(params.first_item_has_no_margin) { - set_alignment(params.arrow_alignment); - set_background_color(params.arrow_color); - set_paint_arrow(params.arrow_paint_type); - } - - virtual ~TrayBubbleBorder() {} - - // Overridden from BubbleBorder. - // Sets the bubble on top of the anchor when it has no arrow. - virtual gfx::Rect GetBounds(const gfx::Rect& position_relative_to, - const gfx::Size& contents_size) const override { - if (has_arrow(arrow())) { - gfx::Rect rect = - BubbleBorder::GetBounds(position_relative_to, contents_size); - if (first_item_has_no_margin_) { - if (arrow() == BubbleBorder::BOTTOM_RIGHT || - arrow() == BubbleBorder::BOTTOM_LEFT) { - rect.set_y(rect.y() + kArrowOffsetTopBottom); - int rtl_factor = base::i18n::IsRTL() ? -1 : 1; - rect.set_x(rect.x() + - rtl_factor * kOffsetLeftRightForTopBottomOrientation); - } else if (arrow() == BubbleBorder::LEFT_BOTTOM) { - rect.set_x(rect.x() + kArrowOffsetLeft); - } else if (arrow() == BubbleBorder::RIGHT_BOTTOM) { - rect.set_x(rect.x() + kArrowOffsetRight); - } - } - return rect; - } - - gfx::Size border_size(contents_size); - gfx::Insets insets = GetInsets(); - border_size.Enlarge(insets.width(), insets.height()); - const int x = position_relative_to.x() + - position_relative_to.width() / 2 - border_size.width() / 2; - // Position the bubble on top of the anchor. - const int y = position_relative_to.y() - border_size.height() + - insets.height() - kBubbleSpacing; - return gfx::Rect(x, y, border_size.width(), border_size.height()); - } - - void UpdateArrowOffset() { - int arrow_offset = 0; - if (arrow() == BubbleBorder::BOTTOM_RIGHT || - arrow() == BubbleBorder::BOTTOM_LEFT) { - // Note: tray_arrow_offset_ is relative to the anchor widget. - if (tray_arrow_offset_ == - TrayBubbleView::InitParams::kArrowDefaultOffset) { - arrow_offset = kArrowMinOffset; - } else { - const int width = owner_->GetWidget()->GetContentsView()->width(); - gfx::Point pt(tray_arrow_offset_, 0); - View::ConvertPointToScreen(anchor_->GetWidget()->GetRootView(), &pt); - View::ConvertPointFromScreen(owner_->GetWidget()->GetRootView(), &pt); - arrow_offset = pt.x(); - if (arrow() == BubbleBorder::BOTTOM_RIGHT) - arrow_offset = width - arrow_offset; - arrow_offset = std::max(arrow_offset, kArrowMinOffset); - } - } else { - if (tray_arrow_offset_ == - TrayBubbleView::InitParams::kArrowDefaultOffset) { - arrow_offset = kArrowMinOffset; - } else { - gfx::Point pt(0, tray_arrow_offset_); - View::ConvertPointToScreen(anchor_->GetWidget()->GetRootView(), &pt); - View::ConvertPointFromScreen(owner_->GetWidget()->GetRootView(), &pt); - arrow_offset = pt.y(); - arrow_offset = std::max(arrow_offset, kArrowMinOffset); - } - } - set_arrow_offset(arrow_offset); - } - - private: - View* owner_; - View* anchor_; - const int tray_arrow_offset_; - - // If true the first item should not get any additional spacing against the - // anchor (without the bubble tip the bubble should be flush to the shelf). - const bool first_item_has_no_margin_; - - DISALLOW_COPY_AND_ASSIGN(TrayBubbleBorder); -}; - -// This mask layer clips the bubble's content so that it does not overwrite the -// rounded bubble corners. -// TODO(miket): This does not work on Windows. Implement layer masking or -// alternate solutions if the TrayBubbleView is needed there in the future. -class TrayBubbleContentMask : public ui::LayerDelegate { - public: - explicit TrayBubbleContentMask(int corner_radius); - virtual ~TrayBubbleContentMask(); - - ui::Layer* layer() { return &layer_; } - - // Overridden from LayerDelegate. - virtual void OnPaintLayer(gfx::Canvas* canvas) override; - virtual void OnDelegatedFrameDamage( - const gfx::Rect& damage_rect_in_dip) override {} - virtual void OnDeviceScaleFactorChanged(float device_scale_factor) override; - virtual base::Closure PrepareForLayerBoundsChange() override; - - private: - ui::Layer layer_; - int corner_radius_; - - DISALLOW_COPY_AND_ASSIGN(TrayBubbleContentMask); -}; - -TrayBubbleContentMask::TrayBubbleContentMask(int corner_radius) - : layer_(ui::LAYER_TEXTURED), - corner_radius_(corner_radius) { - layer_.set_delegate(this); -} - -TrayBubbleContentMask::~TrayBubbleContentMask() { - layer_.set_delegate(NULL); -} - -void TrayBubbleContentMask::OnPaintLayer(gfx::Canvas* canvas) { - SkPaint paint; - paint.setAlpha(255); - paint.setStyle(SkPaint::kFill_Style); - gfx::Rect rect(layer()->bounds().size()); - canvas->DrawRoundRect(rect, corner_radius_, paint); -} - -void TrayBubbleContentMask::OnDeviceScaleFactorChanged( - float device_scale_factor) { - // Redrawing will take care of scale factor change. -} - -base::Closure TrayBubbleContentMask::PrepareForLayerBoundsChange() { - return base::Closure(); -} - -// Custom layout for the bubble-view. Does the default box-layout if there is -// enough height. Otherwise, makes sure the bottom rows are visible. -class BottomAlignedBoxLayout : public BoxLayout { - public: - explicit BottomAlignedBoxLayout(TrayBubbleView* bubble_view) - : BoxLayout(BoxLayout::kVertical, 0, 0, 0), - bubble_view_(bubble_view) { - } - - virtual ~BottomAlignedBoxLayout() {} - - private: - virtual void Layout(View* host) override { - if (host->height() >= host->GetPreferredSize().height() || - !bubble_view_->is_gesture_dragging()) { - BoxLayout::Layout(host); - return; - } - - int consumed_height = 0; - for (int i = host->child_count() - 1; - i >= 0 && consumed_height < host->height(); --i) { - View* child = host->child_at(i); - if (!child->visible()) - continue; - gfx::Size size = child->GetPreferredSize(); - child->SetBounds(0, host->height() - consumed_height - size.height(), - host->width(), size.height()); - consumed_height += size.height(); - } - } - - TrayBubbleView* bubble_view_; - - DISALLOW_COPY_AND_ASSIGN(BottomAlignedBoxLayout); -}; - -} // namespace internal - -using internal::TrayBubbleBorder; -using internal::TrayBubbleContentMask; -using internal::BottomAlignedBoxLayout; - -// static -const int TrayBubbleView::InitParams::kArrowDefaultOffset = -1; - -TrayBubbleView::InitParams::InitParams(AnchorType anchor_type, - AnchorAlignment anchor_alignment, - int min_width, - int max_width) - : anchor_type(anchor_type), - anchor_alignment(anchor_alignment), - min_width(min_width), - max_width(max_width), - max_height(0), - can_activate(false), - close_on_deactivate(true), - arrow_color(SK_ColorBLACK), - first_item_has_no_margin(false), - arrow(BubbleBorder::NONE), - arrow_offset(kArrowDefaultOffset), - arrow_paint_type(BubbleBorder::PAINT_NORMAL), - shadow(BubbleBorder::BIG_SHADOW), - arrow_alignment(BubbleBorder::ALIGN_EDGE_TO_ANCHOR_EDGE) { -} - -// static -TrayBubbleView* TrayBubbleView::Create(gfx::NativeView parent_window, - View* anchor, - Delegate* delegate, - InitParams* init_params) { - // Set arrow here so that it can be passed to the BubbleView constructor. - if (init_params->anchor_type == ANCHOR_TYPE_TRAY) { - if (init_params->anchor_alignment == ANCHOR_ALIGNMENT_BOTTOM) { - init_params->arrow = base::i18n::IsRTL() ? - BubbleBorder::BOTTOM_LEFT : BubbleBorder::BOTTOM_RIGHT; - } else if (init_params->anchor_alignment == ANCHOR_ALIGNMENT_TOP) { - init_params->arrow = BubbleBorder::TOP_LEFT; - } else if (init_params->anchor_alignment == ANCHOR_ALIGNMENT_LEFT) { - init_params->arrow = BubbleBorder::LEFT_BOTTOM; - } else { - init_params->arrow = BubbleBorder::RIGHT_BOTTOM; - } - } else { - init_params->arrow = BubbleBorder::NONE; - } - - return new TrayBubbleView(parent_window, anchor, delegate, *init_params); -} - -TrayBubbleView::TrayBubbleView(gfx::NativeView parent_window, - View* anchor, - Delegate* delegate, - const InitParams& init_params) - : BubbleDelegateView(anchor, init_params.arrow), - params_(init_params), - delegate_(delegate), - preferred_width_(init_params.min_width), - bubble_border_(NULL), - is_gesture_dragging_(false), - mouse_actively_entered_(false) { - set_parent_window(parent_window); - set_notify_enter_exit_on_child(true); - set_close_on_deactivate(init_params.close_on_deactivate); - set_margins(gfx::Insets()); - bubble_border_ = new TrayBubbleBorder(this, GetAnchorView(), params_); - SetPaintToLayer(true); - SetFillsBoundsOpaquely(true); - - bubble_content_mask_.reset( - new TrayBubbleContentMask(bubble_border_->GetBorderCornerRadius())); -} - -TrayBubbleView::~TrayBubbleView() { - mouse_watcher_.reset(); - // Inform host items (models) that their views are being destroyed. - if (delegate_) - delegate_->BubbleViewDestroyed(); -} - -void TrayBubbleView::InitializeAndShowBubble() { - // Must occur after call to BubbleDelegateView::CreateBubble(). - SetAlignment(params_.arrow_alignment); - bubble_border_->UpdateArrowOffset(); - - layer()->parent()->SetMaskLayer(bubble_content_mask_->layer()); - - GetWidget()->Show(); - GetWidget()->GetNativeWindow()->SetEventTargeter( - scoped_ptr<ui::EventTargeter>(new BubbleWindowTargeter(this))); - UpdateBubble(); -} - -void TrayBubbleView::UpdateBubble() { - SizeToContents(); - bubble_content_mask_->layer()->SetBounds(layer()->bounds()); - GetWidget()->GetRootView()->SchedulePaint(); -} - -void TrayBubbleView::SetMaxHeight(int height) { - params_.max_height = height; - if (GetWidget()) - SizeToContents(); -} - -void TrayBubbleView::SetWidth(int width) { - width = std::max(std::min(width, params_.max_width), params_.min_width); - if (preferred_width_ == width) - return; - preferred_width_ = width; - if (GetWidget()) - SizeToContents(); -} - -void TrayBubbleView::SetArrowPaintType( - views::BubbleBorder::ArrowPaintType paint_type) { - bubble_border_->set_paint_arrow(paint_type); - UpdateBubble(); -} - -gfx::Insets TrayBubbleView::GetBorderInsets() const { - return bubble_border_->GetInsets(); -} - -void TrayBubbleView::Init() { - BoxLayout* layout = new BottomAlignedBoxLayout(this); - layout->SetDefaultFlex(1); - SetLayoutManager(layout); -} - -gfx::Rect TrayBubbleView::GetAnchorRect() const { - if (!delegate_) - return gfx::Rect(); - return delegate_->GetAnchorRect(anchor_widget(), - params_.anchor_type, - params_.anchor_alignment); -} - -bool TrayBubbleView::CanActivate() const { - return params_.can_activate; -} - -NonClientFrameView* TrayBubbleView::CreateNonClientFrameView(Widget* widget) { - BubbleFrameView* frame = new BubbleFrameView(margins()); - frame->SetBubbleBorder(scoped_ptr<views::BubbleBorder>(bubble_border_)); - return frame; -} - -bool TrayBubbleView::WidgetHasHitTestMask() const { - return true; -} - -void TrayBubbleView::GetWidgetHitTestMask(gfx::Path* mask) const { - DCHECK(mask); - mask->addRect(gfx::RectToSkRect(GetBubbleFrameView()->GetContentsBounds())); -} - -gfx::Size TrayBubbleView::GetPreferredSize() const { - return gfx::Size(preferred_width_, GetHeightForWidth(preferred_width_)); -} - -gfx::Size TrayBubbleView::GetMaximumSize() const { - gfx::Size size = GetPreferredSize(); - size.set_width(params_.max_width); - return size; -} - -int TrayBubbleView::GetHeightForWidth(int width) const { - int height = GetInsets().height(); - width = std::max(width - GetInsets().width(), 0); - for (int i = 0; i < child_count(); ++i) { - const View* child = child_at(i); - if (child->visible()) - height += child->GetHeightForWidth(width); - } - - return (params_.max_height != 0) ? - std::min(height, params_.max_height) : height; -} - -void TrayBubbleView::OnMouseEntered(const ui::MouseEvent& event) { - mouse_watcher_.reset(); - if (delegate_ && !(event.flags() & ui::EF_IS_SYNTHESIZED)) { - // Coming here the user was actively moving the mouse over the bubble and - // we inform the delegate that we entered. This will prevent the bubble - // to auto close. - delegate_->OnMouseEnteredView(); - mouse_actively_entered_ = true; - } else { - // Coming here the bubble got shown and the mouse was 'accidentally' over it - // which is not a reason to prevent the bubble to auto close. As such we - // do not call the delegate, but wait for the first mouse move within the - // bubble. The used MouseWatcher will notify use of a movement and call - // |MouseMovedOutOfHost|. - mouse_watcher_.reset(new MouseWatcher( - new views::internal::MouseMoveDetectorHost(), - this)); - // Set the mouse sampling frequency to roughly a frame time so that the user - // cannot see a lag. - mouse_watcher_->set_notify_on_exit_time( - base::TimeDelta::FromMilliseconds(kFrameTimeInMS)); - mouse_watcher_->Start(); - } -} - -void TrayBubbleView::OnMouseExited(const ui::MouseEvent& event) { - // If there was a mouse watcher waiting for mouse movements we disable it - // immediately since we now leave the bubble. - mouse_watcher_.reset(); - // Do not notify the delegate of an exit if we never told it that we entered. - if (delegate_ && mouse_actively_entered_) - delegate_->OnMouseExitedView(); -} - -void TrayBubbleView::GetAccessibleState(ui::AXViewState* state) { - if (delegate_ && params_.can_activate) { - state->role = ui::AX_ROLE_WINDOW; - state->name = delegate_->GetAccessibleNameForBubble(); - } -} - -void TrayBubbleView::MouseMovedOutOfHost() { - // The mouse was accidentally over the bubble when it opened and the AutoClose - // logic was not activated. Now that the user did move the mouse we tell the - // delegate to disable AutoClose. - delegate_->OnMouseEnteredView(); - mouse_actively_entered_ = true; - mouse_watcher_->Stop(); -} - -void TrayBubbleView::ChildPreferredSizeChanged(View* child) { - SizeToContents(); -} - -void TrayBubbleView::ViewHierarchyChanged( - const ViewHierarchyChangedDetails& details) { - if (details.is_add && details.child == this) { - details.parent->SetPaintToLayer(true); - details.parent->SetFillsBoundsOpaquely(true); - details.parent->layer()->SetMasksToBounds(true); - } -} - -} // namespace views
diff --git a/ui/views/bubble/tray_bubble_view.h b/ui/views/bubble/tray_bubble_view.h deleted file mode 100644 index 8ffd58d..0000000 --- a/ui/views/bubble/tray_bubble_view.h +++ /dev/null
@@ -1,204 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_BUBBLE_TRAY_BUBBLE_VIEW_H_ -#define UI_VIEWS_BUBBLE_TRAY_BUBBLE_VIEW_H_ - -#include "base/memory/scoped_ptr.h" -#include "ui/views/bubble/bubble_delegate.h" -#include "ui/views/mouse_watcher.h" -#include "ui/views/views_export.h" - -// Specialized bubble view for bubbles associated with a tray icon (e.g. the -// Ash status area). Mostly this handles custom anchor location and arrow and -// border rendering. This also has its own delegate for handling mouse events -// and other implementation specific details. - -namespace ui { -class LocatedEvent; -} - -namespace views { -class View; -class Widget; -} - -namespace views { - -namespace internal { -class TrayBubbleBorder; -class TrayBubbleContentMask; -} - -class VIEWS_EXPORT TrayBubbleView : public views::BubbleDelegateView, - public views::MouseWatcherListener { - public: - // AnchorType differentiates between bubbles that are anchored on a tray - // element (ANCHOR_TYPE_TRAY) and display an arrow, or that are floating on - // the screen away from the tray (ANCHOR_TYPE_BUBBLE). - enum AnchorType { - ANCHOR_TYPE_TRAY, - ANCHOR_TYPE_BUBBLE, - }; - - // AnchorAlignment determines to which side of the anchor the bubble will - // align itself. - enum AnchorAlignment { - ANCHOR_ALIGNMENT_BOTTOM, - ANCHOR_ALIGNMENT_LEFT, - ANCHOR_ALIGNMENT_RIGHT, - ANCHOR_ALIGNMENT_TOP - }; - - class VIEWS_EXPORT Delegate { - public: - typedef TrayBubbleView::AnchorType AnchorType; - typedef TrayBubbleView::AnchorAlignment AnchorAlignment; - - Delegate() {} - virtual ~Delegate() {} - - // Called when the view is destroyed. Any pointers to the view should be - // cleared when this gets called. - virtual void BubbleViewDestroyed() = 0; - - // Called when the mouse enters/exits the view. - // Note: This event will only be called if the mouse gets actively moved by - // the user to enter the view. - virtual void OnMouseEnteredView() = 0; - virtual void OnMouseExitedView() = 0; - - // Called from GetAccessibleState(); should return the appropriate - // accessible name for the bubble. - virtual base::string16 GetAccessibleNameForBubble() = 0; - - // Passes responsibility for BubbleDelegateView::GetAnchorRect to the - // delegate. - virtual gfx::Rect GetAnchorRect( - views::Widget* anchor_widget, - AnchorType anchor_type, - AnchorAlignment anchor_alignment) const = 0; - - // Called when a bubble wants to hide/destroy itself (e.g. last visible - // child view was closed). - virtual void HideBubble(const TrayBubbleView* bubble_view) = 0; - - private: - DISALLOW_COPY_AND_ASSIGN(Delegate); - }; - - struct VIEWS_EXPORT InitParams { - static const int kArrowDefaultOffset; - - InitParams(AnchorType anchor_type, - AnchorAlignment anchor_alignment, - int min_width, - int max_width); - AnchorType anchor_type; - AnchorAlignment anchor_alignment; - int min_width; - int max_width; - int max_height; - bool can_activate; - bool close_on_deactivate; - SkColor arrow_color; - bool first_item_has_no_margin; - views::BubbleBorder::Arrow arrow; - int arrow_offset; - views::BubbleBorder::ArrowPaintType arrow_paint_type; - views::BubbleBorder::Shadow shadow; - views::BubbleBorder::BubbleAlignment arrow_alignment; - }; - - // Constructs and returns a TrayBubbleView. init_params may be modified. - static TrayBubbleView* Create(gfx::NativeView parent_window, - views::View* anchor, - Delegate* delegate, - InitParams* init_params); - - virtual ~TrayBubbleView(); - - // Sets up animations, and show the bubble. Must occur after CreateBubble() - // is called. - void InitializeAndShowBubble(); - - // Called whenever the bubble size or location may have changed. - void UpdateBubble(); - - // Sets the maximum bubble height and resizes the bubble. - void SetMaxHeight(int height); - - // Sets the bubble width. - void SetWidth(int width); - - // Sets whether or not to paint the bubble border arrow. - void SetArrowPaintType(views::BubbleBorder::ArrowPaintType arrow_paint_type); - - // Returns the border insets. Called by TrayEventFilter. - gfx::Insets GetBorderInsets() const; - - // Called when the delegate is destroyed. - void reset_delegate() { delegate_ = NULL; } - - Delegate* delegate() { return delegate_; } - - void set_gesture_dragging(bool dragging) { is_gesture_dragging_ = dragging; } - bool is_gesture_dragging() const { return is_gesture_dragging_; } - - // Overridden from views::WidgetDelegate. - virtual bool CanActivate() const override; - virtual views::NonClientFrameView* CreateNonClientFrameView( - views::Widget* widget) override; - virtual bool WidgetHasHitTestMask() const override; - virtual void GetWidgetHitTestMask(gfx::Path* mask) const override; - - // Overridden from views::BubbleDelegateView. - virtual gfx::Rect GetAnchorRect() const override; - - // Overridden from views::View. - virtual gfx::Size GetPreferredSize() const override; - virtual gfx::Size GetMaximumSize() const override; - virtual int GetHeightForWidth(int width) const override; - virtual void OnMouseEntered(const ui::MouseEvent& event) override; - virtual void OnMouseExited(const ui::MouseEvent& event) override; - virtual void GetAccessibleState(ui::AXViewState* state) override; - - // Overridden from MouseWatcherListener - virtual void MouseMovedOutOfHost() override; - - protected: - TrayBubbleView(gfx::NativeView parent_window, - views::View* anchor, - Delegate* delegate, - const InitParams& init_params); - - // Overridden from views::BubbleDelegateView. - virtual void Init() override; - - // Overridden from views::View. - virtual void ChildPreferredSizeChanged(View* child) override; - virtual void ViewHierarchyChanged( - const ViewHierarchyChangedDetails& details) override; - - private: - InitParams params_; - Delegate* delegate_; - int preferred_width_; - internal::TrayBubbleBorder* bubble_border_; - scoped_ptr<internal::TrayBubbleContentMask> bubble_content_mask_; - bool is_gesture_dragging_; - - // True once the mouse cursor was actively moved by the user over the bubble. - // Only then the OnMouseExitedView() event will get passed on to listeners. - bool mouse_actively_entered_; - - // Used to find any mouse movements. - scoped_ptr<MouseWatcher> mouse_watcher_; - - DISALLOW_COPY_AND_ASSIGN(TrayBubbleView); -}; - -} // namespace views - -#endif // UI_VIEWS_BUBBLE_TRAY_BUBBLE_VIEW_H_
diff --git a/ui/views/button_drag_utils.cc b/ui/views/button_drag_utils.cc deleted file mode 100644 index e3be0e7..0000000 --- a/ui/views/button_drag_utils.cc +++ /dev/null
@@ -1,78 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/button_drag_utils.h" - -#include "base/strings/utf_string_conversions.h" -#include "ui/base/dragdrop/drag_utils.h" -#include "ui/base/dragdrop/os_exchange_data.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/geometry/point.h" -#include "ui/gfx/image/image.h" -#include "ui/resources/grit/ui_resources.h" -#include "ui/views/controls/button/label_button.h" -#include "ui/views/drag_utils.h" -#include "ui/views/widget/widget.h" -#include "url/gurl.h" - -namespace button_drag_utils { - -// Maximum width of the link drag image in pixels. -static const int kLinkDragImageMaxWidth = 150; - -void SetURLAndDragImage(const GURL& url, - const base::string16& title, - const gfx::ImageSkia& icon, - const gfx::Point* press_pt, - ui::OSExchangeData* data, - views::Widget* widget) { - DCHECK(url.is_valid() && data); - data->SetURL(url, title); - SetDragImage(url, title, icon, press_pt, data, widget); -} - -void SetDragImage(const GURL& url, - const base::string16& title, - const gfx::ImageSkia& icon, - const gfx::Point* press_pt, - ui::OSExchangeData* data, - views::Widget* widget) { - // Create a button to render the drag image for us. - views::LabelButton button(NULL, - title.empty() ? base::UTF8ToUTF16(url.spec()) - : title); - button.SetTextSubpixelRenderingEnabled(false); - const ui::NativeTheme* theme = - widget ? widget->GetNativeTheme() : ui::NativeTheme::instance(); - button.SetTextColor(views::Button::STATE_NORMAL, - theme->GetSystemColor(ui::NativeTheme::kColorId_LabelEnabledColor)); - gfx::ShadowValues shadows(10, gfx::ShadowValue(gfx::Point(0,0), 1.0f, - theme->GetSystemColor(ui::NativeTheme::kColorId_LabelBackgroundColor))); - button.SetTextShadows(shadows); - button.SetMaxSize(gfx::Size(kLinkDragImageMaxWidth, 0)); - if (icon.isNull()) { - button.SetImage(views::Button::STATE_NORMAL, - *ui::ResourceBundle::GetSharedInstance().GetImageNamed( - IDR_DEFAULT_FAVICON).ToImageSkia()); - } else { - button.SetImage(views::Button::STATE_NORMAL, icon); - } - gfx::Size prefsize = button.GetPreferredSize(); - button.SetBounds(0, 0, prefsize.width(), prefsize.height()); - - gfx::Vector2d press_point; - if (press_pt) - press_point = press_pt->OffsetFromOrigin(); - else - press_point = gfx::Vector2d(prefsize.width() / 2, prefsize.height() / 2); - - // Render the image. - scoped_ptr<gfx::Canvas> canvas( - views::GetCanvasForDragImage(widget, prefsize)); - button.Paint(canvas.get(), views::CullSet()); - drag_utils::SetDragImageOnDataObject(*canvas, press_point, data); -} - -} // namespace button_drag_utils
diff --git a/ui/views/button_drag_utils.h b/ui/views/button_drag_utils.h deleted file mode 100644 index 8f1a7ee..0000000 --- a/ui/views/button_drag_utils.h +++ /dev/null
@@ -1,48 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_BUTTON_DRAG_UTILS_H_ -#define UI_VIEWS_BUTTON_DRAG_UTILS_H_ - -#include "base/strings/string16.h" -#include "ui/views/views_export.h" - -class GURL; - -namespace gfx { -class ImageSkia; -class Point; -} - -namespace ui { -class OSExchangeData; -} - -namespace views { -class Widget; -} - -namespace button_drag_utils { - -// Sets url and title on data as well as setting a suitable image for dragging. -// The image looks like that of the bookmark buttons. |press_pt| is optional -// offset; otherwise, it centers the drag image. -VIEWS_EXPORT void SetURLAndDragImage(const GURL& url, - const base::string16& title, - const gfx::ImageSkia& icon, - const gfx::Point* press_pt, - ui::OSExchangeData* data, - views::Widget* widget); - -// As above, but only sets the image. -VIEWS_EXPORT void SetDragImage(const GURL& url, - const base::string16& title, - const gfx::ImageSkia& icon, - const gfx::Point* press_pt, - ui::OSExchangeData* data, - views::Widget* widget); - -} // namespace drag_utils - -#endif // UI_VIEWS_BUTTON_DRAG_UTILS_H_
diff --git a/ui/views/color_chooser/color_chooser_listener.h b/ui/views/color_chooser/color_chooser_listener.h deleted file mode 100644 index 029e29e..0000000 --- a/ui/views/color_chooser/color_chooser_listener.h +++ /dev/null
@@ -1,26 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_COLOR_CHOOSER_COLOR_CHOOSER_LISTENER_H_ -#define UI_VIEWS_COLOR_CHOOSER_COLOR_CHOOSER_LISTENER_H_ - -#include "third_party/skia/include/core/SkColor.h" -#include "ui/views/views_export.h" - -namespace views { - -// An interface implemented by a Listener object wishing to know about the -// the results from the color chooser dialog. -class VIEWS_EXPORT ColorChooserListener { - public: - virtual void OnColorChosen(SkColor color) = 0; - virtual void OnColorChooserDialogClosed() = 0; - - protected: - virtual ~ColorChooserListener() {} -}; - -} // namespace views - -#endif // UI_VIEWS_COLOR_CHOOSER_COLOR_CHOOSER_LISTENER_H_
diff --git a/ui/views/color_chooser/color_chooser_view.cc b/ui/views/color_chooser/color_chooser_view.cc deleted file mode 100644 index 680fd30..0000000 --- a/ui/views/color_chooser/color_chooser_view.cc +++ /dev/null
@@ -1,485 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/color_chooser/color_chooser_view.h" - -#include "base/logging.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/stringprintf.h" -#include "base/strings/utf_string_conversions.h" -#include "skia/ext/refptr.h" -#include "third_party/skia/include/effects/SkGradientShader.h" -#include "ui/events/event.h" -#include "ui/events/keycodes/keyboard_codes.h" -#include "ui/gfx/canvas.h" -#include "ui/views/background.h" -#include "ui/views/border.h" -#include "ui/views/color_chooser/color_chooser_listener.h" -#include "ui/views/controls/textfield/textfield.h" -#include "ui/views/controls/textfield/textfield_controller.h" -#include "ui/views/layout/box_layout.h" -#include "ui/views/layout/grid_layout.h" -#include "ui/views/widget/widget.h" - -namespace { - -const int kHueBarWidth = 20; -const int kSaturationValueSize = 200; -const int kMarginWidth = 5; -const int kSaturationValueIndicatorSize = 6; -const int kHueIndicatorSize = 5; -const int kBorderWidth = 1; -const int kTextfieldLengthInChars = 14; - -base::string16 GetColorText(SkColor color) { - return base::ASCIIToUTF16(base::StringPrintf("#%02x%02x%02x", - SkColorGetR(color), - SkColorGetG(color), - SkColorGetB(color))); -} - -bool GetColorFromText(const base::string16& text, SkColor* result) { - if (text.size() != 6 && !(text.size() == 7 && text[0] == '#')) - return false; - - std::string input = - base::UTF16ToUTF8((text.size() == 6) ? text : text.substr(1)); - std::vector<uint8> hex; - if (!base::HexStringToBytes(input, &hex)) - return false; - - *result = SkColorSetRGB(hex[0], hex[1], hex[2]); - return true; -} - -// A view that processes mouse events and gesture events using a common -// interface. -class LocatedEventHandlerView : public views::View { - public: - virtual ~LocatedEventHandlerView() {} - - protected: - LocatedEventHandlerView() {} - - // Handles an event (mouse or gesture) at the specified location. - virtual void ProcessEventAtLocation(const gfx::Point& location) = 0; - - // views::View overrides: - virtual bool OnMousePressed(const ui::MouseEvent& event) override { - ProcessEventAtLocation(event.location()); - return true; - } - - virtual bool OnMouseDragged(const ui::MouseEvent& event) override { - ProcessEventAtLocation(event.location()); - return true; - } - - virtual void OnGestureEvent(ui::GestureEvent* event) override { - if (event->type() == ui::ET_GESTURE_TAP || - event->type() == ui::ET_GESTURE_TAP_DOWN || - event->IsScrollGestureEvent()) { - ProcessEventAtLocation(event->location()); - event->SetHandled(); - } - } - - DISALLOW_COPY_AND_ASSIGN(LocatedEventHandlerView); -}; - -void DrawGradientRect(const gfx::Rect& rect, SkColor start_color, - SkColor end_color, bool is_horizontal, - gfx::Canvas* canvas) { - SkColor colors[2] = { start_color, end_color }; - SkPoint points[2]; - points[0].iset(0, 0); - if (is_horizontal) - points[1].iset(rect.width() + 1, 0); - else - points[1].iset(0, rect.height() + 1); - skia::RefPtr<SkShader> shader(skia::AdoptRef( - SkGradientShader::CreateLinear(points, colors, NULL, 2, - SkShader::kClamp_TileMode))); - SkPaint paint; - paint.setShader(shader.get()); - canvas->DrawRect(rect, paint); -} - -} // namespace - -namespace views { - -//////////////////////////////////////////////////////////////////////////////// -// ColorChooserView::HueView -// -// The class to choose the hue of the color. It draws a vertical bar and -// the indicator for the currently selected hue. -class ColorChooserView::HueView : public LocatedEventHandlerView { - public: - explicit HueView(ColorChooserView* chooser_view); - - void OnHueChanged(SkScalar hue); - - private: - // LocatedEventHandlerView overrides: - virtual void ProcessEventAtLocation(const gfx::Point& point) override; - - // View overrides: - virtual gfx::Size GetPreferredSize() const override; - virtual void OnPaint(gfx::Canvas* canvas) override; - - ColorChooserView* chooser_view_; - int level_; - - DISALLOW_COPY_AND_ASSIGN(HueView); -}; - -ColorChooserView::HueView::HueView(ColorChooserView* chooser_view) - : chooser_view_(chooser_view), - level_(0) { - SetFocusable(false); -} - -void ColorChooserView::HueView::OnHueChanged(SkScalar hue) { - SkScalar height = SkIntToScalar(kSaturationValueSize - 1); - SkScalar hue_max = SkIntToScalar(360); - int level = SkScalarDiv(SkScalarMul(hue_max - hue, height), hue_max); - level += kBorderWidth; - if (level_ != level) { - level_ = level; - SchedulePaint(); - } -} - -void ColorChooserView::HueView::ProcessEventAtLocation( - const gfx::Point& point) { - level_ = std::max(kBorderWidth, - std::min(height() - 1 - kBorderWidth, point.y())); - int base_height = kSaturationValueSize - 1; - chooser_view_->OnHueChosen(SkScalarDiv( - SkScalarMul(SkIntToScalar(360), - SkIntToScalar(base_height - (level_ - kBorderWidth))), - SkIntToScalar(base_height))); - SchedulePaint(); -} - -gfx::Size ColorChooserView::HueView::GetPreferredSize() const { - // We put indicators on the both sides of the hue bar. - return gfx::Size(kHueBarWidth + kHueIndicatorSize * 2 + kBorderWidth * 2, - kSaturationValueSize + kBorderWidth * 2); -} - -void ColorChooserView::HueView::OnPaint(gfx::Canvas* canvas) { - SkScalar hsv[3]; - // In the hue bar, saturation and value for the color should be always 100%. - hsv[1] = SK_Scalar1; - hsv[2] = SK_Scalar1; - - canvas->FillRect(gfx::Rect(kHueIndicatorSize, 0, - kHueBarWidth + kBorderWidth, height() - 1), - SK_ColorGRAY); - int base_left = kHueIndicatorSize + kBorderWidth; - for (int y = 0; y < kSaturationValueSize; ++y) { - hsv[0] = SkScalarDiv(SkScalarMul(SkIntToScalar(360), - SkIntToScalar( - kSaturationValueSize - 1 - y)), - SkIntToScalar(kSaturationValueSize - 1)); - canvas->FillRect(gfx::Rect(base_left, y + kBorderWidth, kHueBarWidth, 1), - SkHSVToColor(hsv)); - } - - // Put the triangular indicators besides. - SkPath left_indicator_path; - SkPath right_indicator_path; - left_indicator_path.moveTo( - SK_ScalarHalf, SkIntToScalar(level_ - kHueIndicatorSize)); - left_indicator_path.lineTo( - kHueIndicatorSize, SkIntToScalar(level_)); - left_indicator_path.lineTo( - SK_ScalarHalf, SkIntToScalar(level_ + kHueIndicatorSize)); - left_indicator_path.lineTo( - SK_ScalarHalf, SkIntToScalar(level_ - kHueIndicatorSize)); - right_indicator_path.moveTo( - SkIntToScalar(width()) - SK_ScalarHalf, - SkIntToScalar(level_ - kHueIndicatorSize)); - right_indicator_path.lineTo( - SkIntToScalar(width() - kHueIndicatorSize) - SK_ScalarHalf, - SkIntToScalar(level_)); - right_indicator_path.lineTo( - SkIntToScalar(width()) - SK_ScalarHalf, - SkIntToScalar(level_ + kHueIndicatorSize)); - right_indicator_path.lineTo( - SkIntToScalar(width()) - SK_ScalarHalf, - SkIntToScalar(level_ - kHueIndicatorSize)); - - SkPaint indicator_paint; - indicator_paint.setColor(SK_ColorBLACK); - indicator_paint.setStyle(SkPaint::kFill_Style); - canvas->DrawPath(left_indicator_path, indicator_paint); - canvas->DrawPath(right_indicator_path, indicator_paint); -} - -//////////////////////////////////////////////////////////////////////////////// -// ColorChooserView::SaturationValueView -// -// The class to choose the saturation and the value of the color. It draws -// a square area and the indicator for the currently selected saturation and -// value. -class ColorChooserView::SaturationValueView : public LocatedEventHandlerView { - public: - explicit SaturationValueView(ColorChooserView* chooser_view); - - void OnHueChanged(SkScalar hue); - void OnSaturationValueChanged(SkScalar saturation, SkScalar value); - - private: - // LocatedEventHandlerView overrides: - virtual void ProcessEventAtLocation(const gfx::Point& point) override; - - // View overrides: - virtual gfx::Size GetPreferredSize() const override; - virtual void OnPaint(gfx::Canvas* canvas) override; - - ColorChooserView* chooser_view_; - SkScalar hue_; - gfx::Point marker_position_; - - DISALLOW_COPY_AND_ASSIGN(SaturationValueView); -}; - -ColorChooserView::SaturationValueView::SaturationValueView( - ColorChooserView* chooser_view) - : chooser_view_(chooser_view), - hue_(0) { - SetFocusable(false); - SetBorder(Border::CreateSolidBorder(kBorderWidth, SK_ColorGRAY)); -} - -void ColorChooserView::SaturationValueView::OnHueChanged(SkScalar hue) { - if (hue_ != hue) { - hue_ = hue; - SchedulePaint(); - } -} - -void ColorChooserView::SaturationValueView::OnSaturationValueChanged( - SkScalar saturation, - SkScalar value) { - SkScalar scalar_size = SkIntToScalar(kSaturationValueSize - 1); - int x = SkScalarFloorToInt(SkScalarMul(saturation, scalar_size)) + - kBorderWidth; - int y = SkScalarFloorToInt(SkScalarMul(SK_Scalar1 - value, scalar_size)) + - kBorderWidth; - if (gfx::Point(x, y) == marker_position_) - return; - - marker_position_.set_x(x); - marker_position_.set_y(y); - SchedulePaint(); -} - -void ColorChooserView::SaturationValueView::ProcessEventAtLocation( - const gfx::Point& point) { - SkScalar scalar_size = SkIntToScalar(kSaturationValueSize - 1); - SkScalar saturation = SkScalarDiv( - SkIntToScalar(point.x() - kBorderWidth), scalar_size); - SkScalar value = SK_Scalar1 - SkScalarDiv( - SkIntToScalar(point.y() - kBorderWidth), scalar_size); - saturation = SkScalarPin(saturation, 0, SK_Scalar1); - value = SkScalarPin(value, 0, SK_Scalar1); - OnSaturationValueChanged(saturation, value); - chooser_view_->OnSaturationValueChosen(saturation, value); -} - -gfx::Size ColorChooserView::SaturationValueView::GetPreferredSize() const { - return gfx::Size(kSaturationValueSize + kBorderWidth * 2, - kSaturationValueSize + kBorderWidth * 2); -} - -void ColorChooserView::SaturationValueView::OnPaint(gfx::Canvas* canvas) { - gfx::Rect color_bounds = bounds(); - color_bounds.Inset(GetInsets()); - - // Paints horizontal gradient first for saturation. - SkScalar hsv[3] = { hue_, SK_Scalar1, SK_Scalar1 }; - SkScalar left_hsv[3] = { hue_, 0, SK_Scalar1 }; - DrawGradientRect(color_bounds, SkHSVToColor(255, left_hsv), - SkHSVToColor(255, hsv), true /* is_horizontal */, canvas); - - // Overlays vertical gradient for value. - SkScalar hsv_bottom[3] = { 0, SK_Scalar1, 0 }; - DrawGradientRect(color_bounds, SK_ColorTRANSPARENT, - SkHSVToColor(255, hsv_bottom), false /* is_horizontal */, - canvas); - - // Draw the crosshair marker. - // The background is very dark at the bottom of the view. Use a white - // marker in that case. - SkColor indicator_color = - (marker_position_.y() > width() * 3 / 4) ? SK_ColorWHITE : SK_ColorBLACK; - canvas->FillRect( - gfx::Rect(marker_position_.x(), - marker_position_.y() - kSaturationValueIndicatorSize, - 1, kSaturationValueIndicatorSize * 2 + 1), - indicator_color); - canvas->FillRect( - gfx::Rect(marker_position_.x() - kSaturationValueIndicatorSize, - marker_position_.y(), - kSaturationValueIndicatorSize * 2 + 1, 1), - indicator_color); - - OnPaintBorder(canvas); -} - -//////////////////////////////////////////////////////////////////////////////// -// ColorChooserView::SelectedColorPatchView -// -// A view to simply show the selected color in a rectangle. -class ColorChooserView::SelectedColorPatchView : public views::View { - public: - SelectedColorPatchView(); - - void SetColor(SkColor color); - - private: - DISALLOW_COPY_AND_ASSIGN(SelectedColorPatchView); -}; - -ColorChooserView::SelectedColorPatchView::SelectedColorPatchView() { - SetFocusable(false); - SetVisible(true); - SetBorder(Border::CreateSolidBorder(kBorderWidth, SK_ColorGRAY)); -} - -void ColorChooserView::SelectedColorPatchView::SetColor(SkColor color) { - if (!background()) - set_background(Background::CreateSolidBackground(color)); - else - background()->SetNativeControlColor(color); - SchedulePaint(); -} - -//////////////////////////////////////////////////////////////////////////////// -// ColorChooserView -// - -ColorChooserView::ColorChooserView(ColorChooserListener* listener, - SkColor initial_color) - : listener_(listener) { - DCHECK(listener_); - - SetFocusable(false); - set_background(Background::CreateSolidBackground(SK_ColorLTGRAY)); - SetLayoutManager(new BoxLayout(BoxLayout::kVertical, kMarginWidth, - kMarginWidth, kMarginWidth)); - - View* container = new View(); - container->SetLayoutManager(new BoxLayout(BoxLayout::kHorizontal, 0, 0, - kMarginWidth)); - saturation_value_ = new SaturationValueView(this); - container->AddChildView(saturation_value_); - hue_ = new HueView(this); - container->AddChildView(hue_); - AddChildView(container); - - View* container2 = new View(); - GridLayout* layout = new GridLayout(container2); - container2->SetLayoutManager(layout); - ColumnSet* columns = layout->AddColumnSet(0); - columns->AddColumn( - GridLayout::LEADING, GridLayout::FILL, 0, GridLayout::USE_PREF, 0, 0); - columns->AddPaddingColumn(0, kMarginWidth); - columns->AddColumn( - GridLayout::FILL, GridLayout::FILL, 1, GridLayout::USE_PREF, 0, 0); - layout->StartRow(0, 0); - textfield_ = new Textfield(); - textfield_->set_controller(this); - textfield_->set_default_width_in_chars(kTextfieldLengthInChars); - layout->AddView(textfield_); - selected_color_patch_ = new SelectedColorPatchView(); - layout->AddView(selected_color_patch_); - AddChildView(container2); - - OnColorChanged(initial_color); -} - -ColorChooserView::~ColorChooserView() { -} - -void ColorChooserView::OnColorChanged(SkColor color) { - SkColorToHSV(color, hsv_); - hue_->OnHueChanged(hsv_[0]); - saturation_value_->OnHueChanged(hsv_[0]); - saturation_value_->OnSaturationValueChanged(hsv_[1], hsv_[2]); - selected_color_patch_->SetColor(color); - textfield_->SetText(GetColorText(color)); -} - -void ColorChooserView::OnHueChosen(SkScalar hue) { - hsv_[0] = hue; - SkColor color = SkHSVToColor(255, hsv_); - if (listener_) - listener_->OnColorChosen(color); - saturation_value_->OnHueChanged(hue); - selected_color_patch_->SetColor(color); - textfield_->SetText(GetColorText(color)); -} - -void ColorChooserView::OnSaturationValueChosen(SkScalar saturation, - SkScalar value) { - hsv_[1] = saturation; - hsv_[2] = value; - SkColor color = SkHSVToColor(255, hsv_); - if (listener_) - listener_->OnColorChosen(color); - selected_color_patch_->SetColor(color); - textfield_->SetText(GetColorText(color)); -} - -bool ColorChooserView::CanMinimize() const { - return false; -} - -View* ColorChooserView::GetInitiallyFocusedView() { - return textfield_; -} - -ui::ModalType ColorChooserView::GetModalType() const { - return ui::MODAL_TYPE_WINDOW; -} - -void ColorChooserView::WindowClosing() { - if (listener_) - listener_->OnColorChooserDialogClosed(); -} - -View* ColorChooserView::GetContentsView() { - return this; -} - -void ColorChooserView::ContentsChanged(Textfield* sender, - const base::string16& new_contents) { - SkColor color = SK_ColorBLACK; - if (GetColorFromText(new_contents, &color)) { - SkColorToHSV(color, hsv_); - if (listener_) - listener_->OnColorChosen(color); - hue_->OnHueChanged(hsv_[0]); - saturation_value_->OnHueChanged(hsv_[0]); - saturation_value_->OnSaturationValueChanged(hsv_[1], hsv_[2]); - selected_color_patch_->SetColor(color); - } -} - -bool ColorChooserView::HandleKeyEvent(Textfield* sender, - const ui::KeyEvent& key_event) { - if (key_event.key_code() != ui::VKEY_RETURN && - key_event.key_code() != ui::VKEY_ESCAPE) - return false; - - GetWidget()->Close(); - return true; -} - -} // namespace views
diff --git a/ui/views/color_chooser/color_chooser_view.h b/ui/views/color_chooser/color_chooser_view.h deleted file mode 100644 index 532e823..0000000 --- a/ui/views/color_chooser/color_chooser_view.h +++ /dev/null
@@ -1,89 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_COLOR_CHOOSER_COLOR_CHOOSER_VIEW_H_ -#define UI_VIEWS_COLOR_CHOOSER_COLOR_CHOOSER_VIEW_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "third_party/skia/include/core/SkColor.h" -#include "third_party/skia/include/core/SkScalar.h" -#include "ui/views/controls/textfield/textfield_controller.h" -#include "ui/views/views_export.h" -#include "ui/views/widget/widget_delegate.h" - -namespace views { - -class ColorChooserListener; -class Textfield; - -// ColorChooserView provides the UI to choose a color by mouse and/or keyboard. -// It is typically used for <input type="color">. Currently the user can -// choose a color by dragging over the bar for hue and the area for saturation -// and value. -class VIEWS_EXPORT ColorChooserView : public WidgetDelegateView, - public TextfieldController { - public: - ColorChooserView(ColorChooserListener* listener, SkColor initial_color); - virtual ~ColorChooserView(); - - // Called when its color value is changed in the web contents. - void OnColorChanged(SkColor color); - - // Called when the user chooses a hue from the UI. - void OnHueChosen(SkScalar hue); - - // Called when the user chooses saturation/value from the UI. - void OnSaturationValueChosen(SkScalar saturation, SkScalar value); - - float hue() const { return hsv_[0]; } - float saturation() const { return hsv_[1]; } - float value() const { return hsv_[2]; } - void set_listener(ColorChooserListener* listener) { listener_ = listener; } - - private: - class HueView; - class SaturationValueView; - class SelectedColorPatchView; - - // WidgetDelegate overrides: - virtual bool CanMinimize() const override; - virtual View* GetInitiallyFocusedView() override; - virtual ui::ModalType GetModalType() const override; - virtual void WindowClosing() override; - virtual View* GetContentsView() override; - - // TextfieldController overrides: - virtual void ContentsChanged(Textfield* sender, - const base::string16& new_contents) override; - virtual bool HandleKeyEvent(Textfield* sender, - const ui::KeyEvent& key_event) override; - - // The current color in HSV coordinate. - SkScalar hsv_[3]; - - // The pointer to the current color chooser for callbacks. It doesn't take - // ownership on |listener_| so the user of this class should take care of - // its lifetime. See chrome/browser/ui/browser.cc for example. - ColorChooserListener* listener_; - - // Child views. These are owned as part of the normal views hierarchy. - // The view of hue chooser. - HueView* hue_; - - // The view of saturation/value choosing area. - SaturationValueView* saturation_value_; - - // The textfield to write the color explicitly. - Textfield* textfield_; - - // The rectangle to denote the selected color. - SelectedColorPatchView* selected_color_patch_; - - DISALLOW_COPY_AND_ASSIGN(ColorChooserView); -}; - -} // namespace views - -#endif // UI_VIEWS_COLOR_CHOOSER_COLOR_CHOOSER_VIEW_H_
diff --git a/ui/views/color_constants.cc b/ui/views/color_constants.cc deleted file mode 100644 index a24bcc2..0000000 --- a/ui/views/color_constants.cc +++ /dev/null
@@ -1,11 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/color_constants.h" - -namespace views { - -const SkColor kWarningColor = SkColorSetRGB(0xde, 0x49, 0x32); - -} // namespace views
diff --git a/ui/views/color_constants.h b/ui/views/color_constants.h deleted file mode 100644 index 23c2420..0000000 --- a/ui/views/color_constants.h +++ /dev/null
@@ -1,17 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_COLOR_CONSTANTS_H_ -#define UI_VIEWS_COLOR_CONSTANTS_H_ - -#include "third_party/skia/include/core/SkColor.h" -#include "ui/views/views_export.h" - -namespace views { - -VIEWS_EXPORT extern const SkColor kWarningColor; - -} // namespace views - -#endif // UI_VIEWS_COLOR_CONSTANTS_H_
diff --git a/ui/views/context_menu_controller.h b/ui/views/context_menu_controller.h deleted file mode 100644 index dd137a9..0000000 --- a/ui/views/context_menu_controller.h +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTEXT_MENU_CONTROLLER_H_ -#define UI_VIEWS_CONTEXT_MENU_CONTROLLER_H_ - -#include "ui/base/ui_base_types.h" -#include "ui/views/views_export.h" - -namespace gfx { -class Point; -} - -namespace views { -class View; - -// ContextMenuController is responsible for showing the context menu for a -// View. To use a ContextMenuController invoke set_context_menu_controller on a -// View. When the appropriate user gesture occurs ShowContextMenu is invoked -// on the ContextMenuController. -// -// Setting a ContextMenuController on a view makes the view process mouse -// events. -// -// It is up to subclasses that do their own mouse processing to invoke -// the appropriate ContextMenuController method, typically by invoking super's -// implementation for mouse processing. -class VIEWS_EXPORT ContextMenuController { - public: - // Invoked to show the context menu for |source|. - // |point| is in screen coordinates. - virtual void ShowContextMenuForView(View* source, - const gfx::Point& point, - ui::MenuSourceType source_type) = 0; - - protected: - virtual ~ContextMenuController() {} -}; - -} // namespace views - -#endif // UI_VIEWS_CONTEXT_MENU_CONTROLLER_H_
diff --git a/ui/views/controls/button/blue_button.cc b/ui/views/controls/button/blue_button.cc deleted file mode 100644 index 8bae234..0000000 --- a/ui/views/controls/button/blue_button.cc +++ /dev/null
@@ -1,76 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/button/blue_button.h" - -#include "ui/base/resource/resource_bundle.h" -#include "ui/gfx/sys_color_change_listener.h" -#include "ui/resources/grit/ui_resources.h" -#include "ui/views/controls/button/label_button_border.h" - -namespace views { - -// static -const char BlueButton::kViewClassName[] = "views/BlueButton"; - -BlueButton::BlueButton(ButtonListener* listener, const base::string16& text) - : LabelButton(listener, text) { - // Inherit STYLE_BUTTON insets, minimum size, alignment, etc. - SetStyle(STYLE_BUTTON); - UpdateThemedBorder(); -} - -BlueButton::~BlueButton() {} - -void BlueButton::ResetColorsFromNativeTheme() { - LabelButton::ResetColorsFromNativeTheme(); - if (!gfx::IsInvertedColorScheme()) { - SetTextColor(STATE_NORMAL, GetNativeTheme()-> - GetSystemColor(ui::NativeTheme::kColorId_BlueButtonEnabledColor)); - SetTextColor(STATE_HOVERED, GetNativeTheme()-> - GetSystemColor(ui::NativeTheme::kColorId_BlueButtonHoverColor)); - SetTextColor(STATE_PRESSED, GetNativeTheme()-> - GetSystemColor(ui::NativeTheme::kColorId_BlueButtonPressedColor)); - SetTextColor(STATE_DISABLED, GetNativeTheme()-> - GetSystemColor(ui::NativeTheme::kColorId_BlueButtonDisabledColor)); - - label()->SetShadows(gfx::ShadowValues( - 1, - gfx::ShadowValue( - gfx::Point(0, 1), - 0, - GetNativeTheme()->GetSystemColor( - ui::NativeTheme::kColorId_BlueButtonShadowColor)))); - } -} - -const char* BlueButton::GetClassName() const { - return BlueButton::kViewClassName; -} - -scoped_ptr<LabelButtonBorder> BlueButton::CreateDefaultBorder() const { - // Insets for splitting the images. - const gfx::Insets insets(5, 5, 5, 5); - scoped_ptr<LabelButtonBorder> button_border(new LabelButtonBorder(style())); - ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); - button_border->SetPainter(false, STATE_NORMAL, Painter::CreateImagePainter( - *rb.GetImageSkiaNamed(IDR_BLUE_BUTTON_NORMAL), insets)); - button_border->SetPainter(false, STATE_HOVERED, Painter::CreateImagePainter( - *rb.GetImageSkiaNamed(IDR_BLUE_BUTTON_HOVER), insets)); - button_border->SetPainter(false, STATE_PRESSED, Painter::CreateImagePainter( - *rb.GetImageSkiaNamed(IDR_BLUE_BUTTON_PRESSED), insets)); - button_border->SetPainter(false, STATE_DISABLED, Painter::CreateImagePainter( - *rb.GetImageSkiaNamed(IDR_BLUE_BUTTON_DISABLED), insets)); - button_border->SetPainter(true, STATE_NORMAL, Painter::CreateImagePainter( - *rb.GetImageSkiaNamed(IDR_BLUE_BUTTON_FOCUSED_NORMAL), insets)); - button_border->SetPainter(true, STATE_HOVERED, Painter::CreateImagePainter( - *rb.GetImageSkiaNamed(IDR_BLUE_BUTTON_FOCUSED_HOVER), insets)); - button_border->SetPainter(true, STATE_PRESSED, Painter::CreateImagePainter( - *rb.GetImageSkiaNamed(IDR_BLUE_BUTTON_FOCUSED_PRESSED), insets)); - button_border->SetPainter(true, STATE_DISABLED, Painter::CreateImagePainter( - *rb.GetImageSkiaNamed(IDR_BLUE_BUTTON_DISABLED), insets)); - return button_border.Pass(); -} - -} // namespace views
diff --git a/ui/views/controls/button/blue_button.h b/ui/views/controls/button/blue_button.h deleted file mode 100644 index cad8245..0000000 --- a/ui/views/controls/button/blue_button.h +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_BUTTON_BLUE_BUTTON_H_ -#define UI_VIEWS_CONTROLS_BUTTON_BLUE_BUTTON_H_ - -#include "base/compiler_specific.h" -#include "ui/views/controls/button/label_button.h" - -namespace views { - -// A class representing a blue button. -class VIEWS_EXPORT BlueButton : public LabelButton { - public: - static const char kViewClassName[]; - - BlueButton(ButtonListener* listener, const base::string16& text); - virtual ~BlueButton(); - - private: - // Overridden from LabelButton: - virtual void ResetColorsFromNativeTheme() override; - virtual const char* GetClassName() const override; - virtual scoped_ptr<LabelButtonBorder> CreateDefaultBorder() const override; - - DISALLOW_COPY_AND_ASSIGN(BlueButton); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_BUTTON_BLUE_BUTTON_H_
diff --git a/ui/views/controls/button/blue_button_unittest.cc b/ui/views/controls/button/blue_button_unittest.cc deleted file mode 100644 index 908e747..0000000 --- a/ui/views/controls/button/blue_button_unittest.cc +++ /dev/null
@@ -1,59 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/button/blue_button.h" - -#include "base/strings/string16.h" -#include "base/strings/utf_string_conversions.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/skia_util.h" -#include "ui/views/controls/button/label_button_border.h" -#include "ui/views/test/views_test_base.h" - -namespace views { - -namespace { - -class TestBlueButton : public BlueButton { - public: - TestBlueButton() : BlueButton(NULL, base::ASCIIToUTF16("foo")) {} - virtual ~TestBlueButton() {} - - using BlueButton::OnNativeThemeChanged; - - private: - DISALLOW_COPY_AND_ASSIGN(TestBlueButton); -}; - -} // namespace - -typedef ViewsTestBase BlueButtonTest; - -TEST_F(BlueButtonTest, Border) { - // Compared to a normal LabelButton... - LabelButton button(NULL, base::ASCIIToUTF16("foo")); - button.SetBoundsRect(gfx::Rect(gfx::Point(0, 0), button.GetPreferredSize())); - gfx::Canvas button_canvas(button.bounds().size(), 1.0, true); - button.border()->Paint(button, &button_canvas); - - // ... a special blue border should be used. - TestBlueButton blue_button; - blue_button.SetBoundsRect(gfx::Rect(gfx::Point(0, 0), - blue_button.GetPreferredSize())); - gfx::Canvas canvas(blue_button.bounds().size(), 1.0, true); - blue_button.border()->Paint(blue_button, &canvas); - EXPECT_EQ(button.GetText(), blue_button.GetText()); - EXPECT_FALSE(gfx::BitmapsAreEqual(button_canvas.ExtractImageRep().sk_bitmap(), - canvas.ExtractImageRep().sk_bitmap())); - - // Make sure it's still used after the native theme "changes". - blue_button.OnNativeThemeChanged(NULL); - gfx::Canvas canvas2(blue_button.bounds().size(), 1.0, true); - blue_button.border()->Paint(blue_button, &canvas2); - - EXPECT_TRUE(gfx::BitmapsAreEqual(canvas.ExtractImageRep().sk_bitmap(), - canvas2.ExtractImageRep().sk_bitmap())); -} - -} // namespace views
diff --git a/ui/views/controls/button/button.cc b/ui/views/controls/button/button.cc deleted file mode 100644 index b9b8b22..0000000 --- a/ui/views/controls/button/button.cc +++ /dev/null
@@ -1,77 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/button/button.h" - -#include "base/strings/utf_string_conversions.h" -#include "ui/accessibility/ax_view_state.h" - -namespace views { - -//////////////////////////////////////////////////////////////////////////////// -// Button, static public: - -// static -Button::ButtonState Button::GetButtonStateFrom(ui::NativeTheme::State state) { - switch (state) { - case ui::NativeTheme::kDisabled: return Button::STATE_DISABLED; - case ui::NativeTheme::kHovered: return Button::STATE_HOVERED; - case ui::NativeTheme::kNormal: return Button::STATE_NORMAL; - case ui::NativeTheme::kPressed: return Button::STATE_PRESSED; - case ui::NativeTheme::kNumStates: NOTREACHED(); - } - return Button::STATE_NORMAL; -} - -//////////////////////////////////////////////////////////////////////////////// -// Button, public: - -Button::~Button() { -} - -void Button::SetTooltipText(const base::string16& tooltip_text) { - tooltip_text_ = tooltip_text; - if (accessible_name_.empty()) - accessible_name_ = tooltip_text_; - TooltipTextChanged(); -} - -void Button::SetAccessibleName(const base::string16& name) { - accessible_name_ = name; -} - -//////////////////////////////////////////////////////////////////////////////// -// Button, View overrides: - -bool Button::GetTooltipText(const gfx::Point& p, - base::string16* tooltip) const { - if (tooltip_text_.empty()) - return false; - - *tooltip = tooltip_text_; - return true; -} - -void Button::GetAccessibleState(ui::AXViewState* state) { - state->role = ui::AX_ROLE_BUTTON; - state->name = accessible_name_; -} - -//////////////////////////////////////////////////////////////////////////////// -// Button, protected: - -Button::Button(ButtonListener* listener) - : listener_(listener), - tag_(-1) { - SetAccessibilityFocusable(true); -} - -void Button::NotifyClick(const ui::Event& event) { - // We can be called when there is no listener, in cases like double clicks on - // menu buttons etc. - if (listener_) - listener_->ButtonPressed(this, event); -} - -} // namespace views
diff --git a/ui/views/controls/button/button.h b/ui/views/controls/button/button.h deleted file mode 100644 index 6347a43..0000000 --- a/ui/views/controls/button/button.h +++ /dev/null
@@ -1,91 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_BUTTON_BUTTON_H_ -#define UI_VIEWS_CONTROLS_BUTTON_BUTTON_H_ - -#include "ui/native_theme/native_theme.h" -#include "ui/views/view.h" - -namespace views { - -class Button; -class Event; - -// An interface implemented by an object to let it know that a button was -// pressed. -class VIEWS_EXPORT ButtonListener { - public: - virtual void ButtonPressed(Button* sender, const ui::Event& event) = 0; - - protected: - virtual ~ButtonListener() {} -}; - -// A View representing a button. Depending on the specific type, the button -// could be implemented by a native control or custom rendered. -class VIEWS_EXPORT Button : public View { - public: - virtual ~Button(); - - // Button states for various button sub-types. - enum ButtonState { - STATE_NORMAL = 0, - STATE_HOVERED, - STATE_PRESSED, - STATE_DISABLED, - STATE_COUNT, - }; - - // Button styles with associated images and border painters. - // TODO(msw): Add Menu, ComboBox, etc. - enum ButtonStyle { - STYLE_BUTTON = 0, - STYLE_TEXTBUTTON, - STYLE_COUNT, - }; - - static ButtonState GetButtonStateFrom(ui::NativeTheme::State state); - - void SetTooltipText(const base::string16& tooltip_text); - - int tag() const { return tag_; } - void set_tag(int tag) { tag_ = tag; } - - void SetAccessibleName(const base::string16& name); - - // Overridden from View: - virtual bool GetTooltipText(const gfx::Point& p, - base::string16* tooltip) const override; - virtual void GetAccessibleState(ui::AXViewState* state) override; - - protected: - // Construct the Button with a Listener. The listener can be NULL. This can be - // true of buttons that don't have a listener - e.g. menubuttons where there's - // no default action and checkboxes. - explicit Button(ButtonListener* listener); - - // Cause the button to notify the listener that a click occurred. - virtual void NotifyClick(const ui::Event& event); - - // The button's listener. Notified when clicked. - ButtonListener* listener_; - - private: - // The text shown in a tooltip. - base::string16 tooltip_text_; - - // Accessibility data. - base::string16 accessible_name_; - - // The id tag associated with this button. Used to disambiguate buttons in - // the ButtonListener implementation. - int tag_; - - DISALLOW_COPY_AND_ASSIGN(Button); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_BUTTON_BUTTON_H_
diff --git a/ui/views/controls/button/checkbox.cc b/ui/views/controls/button/checkbox.cc deleted file mode 100644 index 0a3a8f6..0000000 --- a/ui/views/controls/button/checkbox.cc +++ /dev/null
@@ -1,147 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/button/checkbox.h" - -#include "ui/accessibility/ax_view_state.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/resources/grit/ui_resources.h" -#include "ui/views/controls/button/label_button_border.h" -#include "ui/views/painter.h" - -namespace views { - -// static -const char Checkbox::kViewClassName[] = "Checkbox"; - -Checkbox::Checkbox(const base::string16& label) - : LabelButton(NULL, label), - checked_(false) { - SetHorizontalAlignment(gfx::ALIGN_LEFT); - scoped_ptr<LabelButtonBorder> button_border(new LabelButtonBorder(style())); - button_border->SetPainter(false, STATE_HOVERED, NULL); - button_border->SetPainter(false, STATE_PRESSED, NULL); - // Inset the trailing side by a couple pixels for the focus border. - button_border->set_insets(gfx::Insets(0, 0, 0, 2)); - SetBorder(button_border.Pass()); - SetFocusable(true); - - ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); - - // Unchecked/Unfocused images. - SetCustomImage(false, false, STATE_NORMAL, - *rb.GetImageSkiaNamed(IDR_CHECKBOX)); - SetCustomImage(false, false, STATE_HOVERED, - *rb.GetImageSkiaNamed(IDR_CHECKBOX_HOVER)); - SetCustomImage(false, false, STATE_PRESSED, - *rb.GetImageSkiaNamed(IDR_CHECKBOX_PRESSED)); - SetCustomImage(false, false, STATE_DISABLED, - *rb.GetImageSkiaNamed(IDR_CHECKBOX_DISABLED)); - - // Checked/Unfocused images. - SetCustomImage(true, false, STATE_NORMAL, - *rb.GetImageSkiaNamed(IDR_CHECKBOX_CHECKED)); - SetCustomImage(true, false, STATE_HOVERED, - *rb.GetImageSkiaNamed(IDR_CHECKBOX_CHECKED_HOVER)); - SetCustomImage(true, false, STATE_PRESSED, - *rb.GetImageSkiaNamed(IDR_CHECKBOX_CHECKED_PRESSED)); - SetCustomImage(true, false, STATE_DISABLED, - *rb.GetImageSkiaNamed(IDR_CHECKBOX_CHECKED_DISABLED)); - - // Unchecked/Focused images. - SetCustomImage(false, true, STATE_NORMAL, - *rb.GetImageSkiaNamed(IDR_CHECKBOX_FOCUSED)); - SetCustomImage(false, true, STATE_HOVERED, - *rb.GetImageSkiaNamed(IDR_CHECKBOX_FOCUSED_HOVER)); - SetCustomImage(false, true, STATE_PRESSED, - *rb.GetImageSkiaNamed(IDR_CHECKBOX_FOCUSED_PRESSED)); - - // Checked/Focused images. - SetCustomImage(true, true, STATE_NORMAL, - *rb.GetImageSkiaNamed(IDR_CHECKBOX_FOCUSED_CHECKED)); - SetCustomImage(true, true, STATE_HOVERED, - *rb.GetImageSkiaNamed(IDR_CHECKBOX_FOCUSED_CHECKED_HOVER)); - SetCustomImage(true, true, STATE_PRESSED, - *rb.GetImageSkiaNamed(IDR_CHECKBOX_FOCUSED_CHECKED_PRESSED)); - - // Limit the checkbox height to match the legacy appearance. - const gfx::Size preferred_size(LabelButton::GetPreferredSize()); - SetMinSize(gfx::Size(0, preferred_size.height() + 4)); -} - -Checkbox::~Checkbox() { -} - -void Checkbox::SetChecked(bool checked) { - checked_ = checked; - UpdateImage(); -} - -void Checkbox::Layout() { - LabelButton::Layout(); - - // Construct a focus painter that only surrounds the label area. - gfx::Rect rect = label()->GetMirroredBounds(); - rect.Inset(-2, 3); - SetFocusPainter(Painter::CreateDashedFocusPainterWithInsets( - gfx::Insets(rect.y(), rect.x(), - height() - rect.bottom(), - width() - rect.right()))); -} - -const char* Checkbox::GetClassName() const { - return kViewClassName; -} - -void Checkbox::GetAccessibleState(ui::AXViewState* state) { - LabelButton::GetAccessibleState(state); - state->role = ui::AX_ROLE_CHECK_BOX; - if (checked()) - state->AddStateFlag(ui::AX_STATE_CHECKED); -} - -void Checkbox::OnFocus() { - LabelButton::OnFocus(); - UpdateImage(); -} - -void Checkbox::OnBlur() { - LabelButton::OnBlur(); - UpdateImage(); -} - -const gfx::ImageSkia& Checkbox::GetImage(ButtonState for_state) { - const size_t checked_index = checked_ ? 1 : 0; - const size_t focused_index = HasFocus() ? 1 : 0; - if (for_state != STATE_NORMAL && - images_[checked_index][focused_index][for_state].isNull()) - return images_[checked_index][focused_index][STATE_NORMAL]; - return images_[checked_index][focused_index][for_state]; -} - -void Checkbox::SetCustomImage(bool checked, - bool focused, - ButtonState for_state, - const gfx::ImageSkia& image) { - const size_t checked_index = checked ? 1 : 0; - const size_t focused_index = focused ? 1 : 0; - images_[checked_index][focused_index][for_state] = image; - UpdateImage(); -} - -void Checkbox::NotifyClick(const ui::Event& event) { - SetChecked(!checked()); - LabelButton::NotifyClick(event); -} - -ui::NativeTheme::Part Checkbox::GetThemePart() const { - return ui::NativeTheme::kCheckbox; -} - -void Checkbox::GetExtraParams(ui::NativeTheme::ExtraParams* params) const { - LabelButton::GetExtraParams(params); - params->button.checked = checked_; -} - -} // namespace views
diff --git a/ui/views/controls/button/checkbox.h b/ui/views/controls/button/checkbox.h deleted file mode 100644 index 8f473fa..0000000 --- a/ui/views/controls/button/checkbox.h +++ /dev/null
@@ -1,68 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_BUTTON_CHECKBOX_H_ -#define UI_VIEWS_CONTROLS_BUTTON_CHECKBOX_H_ - -#include <string> - -#include "base/compiler_specific.h" -#include "base/strings/string16.h" -#include "ui/views/controls/button/label_button.h" - -namespace views { - -// A native themed class representing a checkbox. This class does not use -// platform specific objects to replicate the native platforms looks and feel. -class VIEWS_EXPORT Checkbox : public LabelButton { - public: - static const char kViewClassName[]; - - explicit Checkbox(const base::string16& label); - virtual ~Checkbox(); - - // Sets a listener for this checkbox. Checkboxes aren't required to have them - // since their state can be read independently of them being toggled. - void set_listener(ButtonListener* listener) { listener_ = listener; } - - // Sets/Gets whether or not the checkbox is checked. - virtual void SetChecked(bool checked); - bool checked() const { return checked_; } - - protected: - // Overridden from LabelButton: - virtual void Layout() override; - virtual const char* GetClassName() const override; - virtual void GetAccessibleState(ui::AXViewState* state) override; - virtual void OnFocus() override; - virtual void OnBlur() override; - virtual const gfx::ImageSkia& GetImage(ButtonState for_state) override; - - // Set the image shown for each button state depending on whether it is - // [checked] or [focused]. - void SetCustomImage(bool checked, - bool focused, - ButtonState for_state, - const gfx::ImageSkia& image); - - private: - // Overridden from Button: - virtual void NotifyClick(const ui::Event& event) override; - - virtual ui::NativeTheme::Part GetThemePart() const override; - virtual void GetExtraParams( - ui::NativeTheme::ExtraParams* params) const override; - - // True if the checkbox is checked. - bool checked_; - - // The images for each button state. - gfx::ImageSkia images_[2][2][STATE_COUNT]; - - DISALLOW_COPY_AND_ASSIGN(Checkbox); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_BUTTON_CHECKBOX_H_
diff --git a/ui/views/controls/button/custom_button.cc b/ui/views/controls/button/custom_button.cc deleted file mode 100644 index 1b5d1e8..0000000 --- a/ui/views/controls/button/custom_button.cc +++ /dev/null
@@ -1,359 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/button/custom_button.h" - -#include "ui/accessibility/ax_view_state.h" -#include "ui/events/event.h" -#include "ui/events/keycodes/keyboard_codes.h" -#include "ui/gfx/animation/throb_animation.h" -#include "ui/gfx/screen.h" -#include "ui/views/controls/button/blue_button.h" -#include "ui/views/controls/button/checkbox.h" -#include "ui/views/controls/button/image_button.h" -#include "ui/views/controls/button/label_button.h" -#include "ui/views/controls/button/menu_button.h" -#include "ui/views/controls/button/radio_button.h" -#include "ui/views/widget/widget.h" - -namespace views { - -// How long the hover animation takes if uninterrupted. -static const int kHoverFadeDurationMs = 150; - -// static -const char CustomButton::kViewClassName[] = "CustomButton"; - -//////////////////////////////////////////////////////////////////////////////// -// CustomButton, public: - -// static -const CustomButton* CustomButton::AsCustomButton(const views::View* view) { - return AsCustomButton(const_cast<views::View*>(view)); -} - -CustomButton* CustomButton::AsCustomButton(views::View* view) { - if (view) { - const char* classname = view->GetClassName(); - if (!strcmp(classname, Checkbox::kViewClassName) || - !strcmp(classname, CustomButton::kViewClassName) || - !strcmp(classname, ImageButton::kViewClassName) || - !strcmp(classname, LabelButton::kViewClassName) || - !strcmp(classname, RadioButton::kViewClassName) || - !strcmp(classname, MenuButton::kViewClassName)) { - return static_cast<CustomButton*>(view); - } - } - return NULL; -} - -CustomButton::~CustomButton() { -} - -void CustomButton::SetState(ButtonState state) { - if (state == state_) - return; - - if (animate_on_state_change_ && - (!is_throbbing_ || !hover_animation_->is_animating())) { - is_throbbing_ = false; - if (state_ == STATE_NORMAL && state == STATE_HOVERED) { - // Button is hovered from a normal state, start hover animation. - hover_animation_->Show(); - } else if ((state_ == STATE_HOVERED || state_ == STATE_PRESSED) - && state == STATE_NORMAL) { - // Button is returning to a normal state from hover, start hover - // fade animation. - hover_animation_->Hide(); - } else { - hover_animation_->Stop(); - } - } - - state_ = state; - StateChanged(); - if (state_changed_delegate_.get()) - state_changed_delegate_->StateChanged(state_); - SchedulePaint(); -} - -void CustomButton::StartThrobbing(int cycles_til_stop) { - is_throbbing_ = true; - hover_animation_->StartThrobbing(cycles_til_stop); -} - -void CustomButton::StopThrobbing() { - if (hover_animation_->is_animating()) { - hover_animation_->Stop(); - SchedulePaint(); - } -} - -void CustomButton::SetAnimationDuration(int duration) { - hover_animation_->SetSlideDuration(duration); -} - -void CustomButton::SetHotTracked(bool is_hot_tracked) { - if (state_ != STATE_DISABLED) - SetState(is_hot_tracked ? STATE_HOVERED : STATE_NORMAL); - - if (is_hot_tracked) - NotifyAccessibilityEvent(ui::AX_EVENT_FOCUS, true); -} - -bool CustomButton::IsHotTracked() const { - return state_ == STATE_HOVERED; -} - -//////////////////////////////////////////////////////////////////////////////// -// CustomButton, View overrides: - -void CustomButton::OnEnabledChanged() { - if (enabled() ? (state_ != STATE_DISABLED) : (state_ == STATE_DISABLED)) - return; - - if (enabled()) - SetState(IsMouseHovered() ? STATE_HOVERED : STATE_NORMAL); - else - SetState(STATE_DISABLED); -} - -const char* CustomButton::GetClassName() const { - return kViewClassName; -} - -bool CustomButton::OnMousePressed(const ui::MouseEvent& event) { - if (state_ != STATE_DISABLED) { - if (ShouldEnterPushedState(event) && HitTestPoint(event.location())) - SetState(STATE_PRESSED); - if (request_focus_on_press_) - RequestFocus(); - } - return true; -} - -bool CustomButton::OnMouseDragged(const ui::MouseEvent& event) { - if (state_ != STATE_DISABLED) { - if (HitTestPoint(event.location())) - SetState(ShouldEnterPushedState(event) ? STATE_PRESSED : STATE_HOVERED); - else - SetState(STATE_NORMAL); - } - return true; -} - -void CustomButton::OnMouseReleased(const ui::MouseEvent& event) { - if (state_ == STATE_DISABLED) - return; - - if (!HitTestPoint(event.location())) { - SetState(STATE_NORMAL); - return; - } - - SetState(STATE_HOVERED); - if (IsTriggerableEvent(event)) { - NotifyClick(event); - // NOTE: We may be deleted at this point (by the listener's notification - // handler). - } -} - -void CustomButton::OnMouseCaptureLost() { - // Starting a drag results in a MouseCaptureLost, we need to ignore it. - if (state_ != STATE_DISABLED && !InDrag()) - SetState(STATE_NORMAL); -} - -void CustomButton::OnMouseEntered(const ui::MouseEvent& event) { - if (state_ != STATE_DISABLED) - SetState(STATE_HOVERED); -} - -void CustomButton::OnMouseExited(const ui::MouseEvent& event) { - // Starting a drag results in a MouseExited, we need to ignore it. - if (state_ != STATE_DISABLED && !InDrag()) - SetState(STATE_NORMAL); -} - -void CustomButton::OnMouseMoved(const ui::MouseEvent& event) { - if (state_ != STATE_DISABLED) - SetState(HitTestPoint(event.location()) ? STATE_HOVERED : STATE_NORMAL); -} - -bool CustomButton::OnKeyPressed(const ui::KeyEvent& event) { - if (state_ == STATE_DISABLED) - return false; - - // Space sets button state to pushed. Enter clicks the button. This matches - // the Windows native behavior of buttons, where Space clicks the button on - // KeyRelease and Enter clicks the button on KeyPressed. - if (event.key_code() == ui::VKEY_SPACE) { - SetState(STATE_PRESSED); - } else if (event.key_code() == ui::VKEY_RETURN) { - SetState(STATE_NORMAL); - // TODO(beng): remove once NotifyClick takes ui::Event. - ui::MouseEvent synthetic_event(ui::ET_MOUSE_RELEASED, - gfx::Point(), - gfx::Point(), - ui::EF_LEFT_MOUSE_BUTTON, - ui::EF_LEFT_MOUSE_BUTTON); - NotifyClick(synthetic_event); - } else { - return false; - } - return true; -} - -bool CustomButton::OnKeyReleased(const ui::KeyEvent& event) { - if ((state_ == STATE_DISABLED) || (event.key_code() != ui::VKEY_SPACE)) - return false; - - SetState(STATE_NORMAL); - // TODO(beng): remove once NotifyClick takes ui::Event. - ui::MouseEvent synthetic_event(ui::ET_MOUSE_RELEASED, - gfx::Point(), - gfx::Point(), - ui::EF_LEFT_MOUSE_BUTTON, - ui::EF_LEFT_MOUSE_BUTTON); - NotifyClick(synthetic_event); - return true; -} - -void CustomButton::OnGestureEvent(ui::GestureEvent* event) { - if (state_ == STATE_DISABLED) { - Button::OnGestureEvent(event); - return; - } - - if (event->type() == ui::ET_GESTURE_TAP && IsTriggerableEvent(*event)) { - // Set the button state to hot and start the animation fully faded in. The - // GESTURE_END event issued immediately after will set the state to - // STATE_NORMAL beginning the fade out animation. See - // http://crbug.com/131184. - SetState(STATE_HOVERED); - hover_animation_->Reset(1.0); - NotifyClick(*event); - event->StopPropagation(); - } else if (event->type() == ui::ET_GESTURE_TAP_DOWN && - ShouldEnterPushedState(*event)) { - SetState(STATE_PRESSED); - if (request_focus_on_press_) - RequestFocus(); - event->StopPropagation(); - } else if (event->type() == ui::ET_GESTURE_TAP_CANCEL || - event->type() == ui::ET_GESTURE_END) { - SetState(STATE_NORMAL); - } - if (!event->handled()) - Button::OnGestureEvent(event); -} - -bool CustomButton::AcceleratorPressed(const ui::Accelerator& accelerator) { - SetState(STATE_NORMAL); - /* - ui::KeyEvent key_event(ui::ET_KEY_RELEASED, accelerator.key_code(), - accelerator.modifiers()); - */ - // TODO(beng): remove once NotifyClick takes ui::Event. - ui::MouseEvent synthetic_event(ui::ET_MOUSE_RELEASED, - gfx::Point(), - gfx::Point(), - ui::EF_LEFT_MOUSE_BUTTON, - ui::EF_LEFT_MOUSE_BUTTON); - NotifyClick(synthetic_event); - return true; -} - -void CustomButton::ShowContextMenu(const gfx::Point& p, - ui::MenuSourceType source_type) { - if (!context_menu_controller()) - return; - - // We're about to show the context menu. Showing the context menu likely means - // we won't get a mouse exited and reset state. Reset it now to be sure. - if (state_ != STATE_DISABLED) - SetState(STATE_NORMAL); - View::ShowContextMenu(p, source_type); -} - -void CustomButton::OnDragDone() { - SetState(STATE_NORMAL); -} - -void CustomButton::GetAccessibleState(ui::AXViewState* state) { - Button::GetAccessibleState(state); - switch (state_) { - case STATE_HOVERED: - state->AddStateFlag(ui::AX_STATE_HOVERED); - break; - case STATE_PRESSED: - state->AddStateFlag(ui::AX_STATE_PRESSED); - break; - case STATE_DISABLED: - state->AddStateFlag(ui::AX_STATE_DISABLED); - break; - case STATE_NORMAL: - case STATE_COUNT: - // No additional accessibility state set for this button state. - break; - } -} - -void CustomButton::VisibilityChanged(View* starting_from, bool visible) { - if (state_ == STATE_DISABLED) - return; - SetState(visible && IsMouseHovered() ? STATE_HOVERED : STATE_NORMAL); -} - -//////////////////////////////////////////////////////////////////////////////// -// CustomButton, gfx::AnimationDelegate implementation: - -void CustomButton::AnimationProgressed(const gfx::Animation* animation) { - SchedulePaint(); -} - -//////////////////////////////////////////////////////////////////////////////// -// CustomButton, protected: - -CustomButton::CustomButton(ButtonListener* listener) - : Button(listener), - state_(STATE_NORMAL), - animate_on_state_change_(true), - is_throbbing_(false), - triggerable_event_flags_(ui::EF_LEFT_MOUSE_BUTTON), - request_focus_on_press_(true) { - hover_animation_.reset(new gfx::ThrobAnimation(this)); - hover_animation_->SetSlideDuration(kHoverFadeDurationMs); -} - -void CustomButton::StateChanged() { -} - -bool CustomButton::IsTriggerableEvent(const ui::Event& event) { - return event.type() == ui::ET_GESTURE_TAP_DOWN || - event.type() == ui::ET_GESTURE_TAP || - (event.IsMouseEvent() && - (triggerable_event_flags_ & event.flags()) != 0); -} - -bool CustomButton::ShouldEnterPushedState(const ui::Event& event) { - return IsTriggerableEvent(event); -} - -//////////////////////////////////////////////////////////////////////////////// -// CustomButton, View overrides (protected): - -void CustomButton::ViewHierarchyChanged( - const ViewHierarchyChangedDetails& details) { - if (!details.is_add && state_ != STATE_DISABLED) - SetState(STATE_NORMAL); -} - -void CustomButton::OnBlur() { - if (IsHotTracked()) - SetState(STATE_NORMAL); -} - -} // namespace views
diff --git a/ui/views/controls/button/custom_button.h b/ui/views/controls/button/custom_button.h deleted file mode 100644 index 5b29358..0000000 --- a/ui/views/controls/button/custom_button.h +++ /dev/null
@@ -1,160 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_BUTTON_CUSTOM_BUTTON_H_ -#define UI_VIEWS_CONTROLS_BUTTON_CUSTOM_BUTTON_H_ - -#include "base/memory/scoped_ptr.h" -#include "ui/events/event_constants.h" -#include "ui/gfx/animation/animation_delegate.h" -#include "ui/views/controls/button/button.h" - -namespace gfx { -class ThrobAnimation; -} - -namespace views { - -class CustomButtonStateChangedDelegate; - -// A button with custom rendering. The base of ImageButton and LabelButton. -// Note that this type of button is not focusable by default and will not be -// part of the focus chain. Call SetFocusable(true) to make it part of the -// focus chain. -class VIEWS_EXPORT CustomButton : public Button, - public gfx::AnimationDelegate { - public: - // The menu button's class name. - static const char kViewClassName[]; - - static const CustomButton* AsCustomButton(const views::View* view); - static CustomButton* AsCustomButton(views::View* view); - - virtual ~CustomButton(); - - // Get/sets the current display state of the button. - ButtonState state() const { return state_; } - void SetState(ButtonState state); - - // Starts throbbing. See HoverAnimation for a description of cycles_til_stop. - void StartThrobbing(int cycles_til_stop); - - // Stops throbbing immediately. - void StopThrobbing(); - - // Set how long the hover animation will last for. - void SetAnimationDuration(int duration); - - void set_triggerable_event_flags(int triggerable_event_flags) { - triggerable_event_flags_ = triggerable_event_flags; - } - int triggerable_event_flags() const { return triggerable_event_flags_; } - - // Sets whether |RequestFocus| should be invoked on a mouse press. The default - // is true. - void set_request_focus_on_press(bool value) { - request_focus_on_press_ = value; - } - bool request_focus_on_press() const { return request_focus_on_press_; } - - // See description above field. - void set_animate_on_state_change(bool value) { - animate_on_state_change_ = value; - } - - void SetHotTracked(bool is_hot_tracked); - bool IsHotTracked() const; - - // Overridden from View: - virtual void OnEnabledChanged() override; - virtual const char* GetClassName() const override; - virtual bool OnMousePressed(const ui::MouseEvent& event) override; - virtual bool OnMouseDragged(const ui::MouseEvent& event) override; - virtual void OnMouseReleased(const ui::MouseEvent& event) override; - virtual void OnMouseCaptureLost() override; - virtual void OnMouseEntered(const ui::MouseEvent& event) override; - virtual void OnMouseExited(const ui::MouseEvent& event) override; - virtual void OnMouseMoved(const ui::MouseEvent& event) override; - virtual bool OnKeyPressed(const ui::KeyEvent& event) override; - virtual bool OnKeyReleased(const ui::KeyEvent& event) override; - virtual void OnGestureEvent(ui::GestureEvent* event) override; - virtual bool AcceleratorPressed(const ui::Accelerator& accelerator) override; - virtual void ShowContextMenu(const gfx::Point& p, - ui::MenuSourceType source_type) override; - virtual void OnDragDone() override; - virtual void GetAccessibleState(ui::AXViewState* state) override; - virtual void VisibilityChanged(View* starting_from, bool is_visible) override; - - // Overridden from gfx::AnimationDelegate: - virtual void AnimationProgressed(const gfx::Animation* animation) override; - - // Takes ownership of the delegate. - void set_state_changed_delegate(CustomButtonStateChangedDelegate* delegate) { - state_changed_delegate_.reset(delegate); - } - - protected: - // Construct the Button with a Listener. See comment for Button's ctor. - explicit CustomButton(ButtonListener* listener); - - // Invoked from SetState() when SetState() is passed a value that differs from - // the current state. CustomButton's implementation of StateChanged() does - // nothing; this method is provided for subclasses that wish to do something - // on state changes. - virtual void StateChanged(); - - // Returns true if the event is one that can trigger notifying the listener. - // This implementation returns true if the left mouse button is down. - virtual bool IsTriggerableEvent(const ui::Event& event); - - // Returns true if the button should become pressed when the user - // holds the mouse down over the button. For this implementation, - // we simply return IsTriggerableEvent(event). - virtual bool ShouldEnterPushedState(const ui::Event& event); - - // Overridden from View: - virtual void ViewHierarchyChanged( - const ViewHierarchyChangedDetails& details) override; - virtual void OnBlur() override; - - // The button state (defined in implementation) - ButtonState state_; - - // Hover animation. - scoped_ptr<gfx::ThrobAnimation> hover_animation_; - - private: - // Should we animate when the state changes? Defaults to true. - bool animate_on_state_change_; - - // Is the hover animation running because StartThrob was invoked? - bool is_throbbing_; - - // Mouse event flags which can trigger button actions. - int triggerable_event_flags_; - - // See description above setter. - bool request_focus_on_press_; - - scoped_ptr<CustomButtonStateChangedDelegate> state_changed_delegate_; - - DISALLOW_COPY_AND_ASSIGN(CustomButton); -}; - -// Delegate for actions taken on state changes by CustomButton. -class VIEWS_EXPORT CustomButtonStateChangedDelegate { -public: - virtual ~CustomButtonStateChangedDelegate() {} - virtual void StateChanged(Button::ButtonState state) = 0; - -protected: - CustomButtonStateChangedDelegate() {} - -private: - DISALLOW_COPY_AND_ASSIGN(CustomButtonStateChangedDelegate); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_BUTTON_CUSTOM_BUTTON_H_
diff --git a/ui/views/controls/button/custom_button_unittest.cc b/ui/views/controls/button/custom_button_unittest.cc deleted file mode 100644 index a5d97c9..0000000 --- a/ui/views/controls/button/custom_button_unittest.cc +++ /dev/null
@@ -1,171 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/button/custom_button.h" - -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/aura/test/test_cursor_client.h" -#include "ui/aura/window.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/base/layout.h" -#include "ui/gfx/screen.h" -#include "ui/views/controls/button/checkbox.h" -#include "ui/views/controls/button/image_button.h" -#include "ui/views/controls/button/label_button.h" -#include "ui/views/controls/button/menu_button.h" -#include "ui/views/controls/button/radio_button.h" -#include "ui/views/controls/link.h" -#include "ui/views/controls/textfield/textfield.h" -#include "ui/views/test/views_test_base.h" - -namespace views { - -namespace { - -class TestCustomButton : public CustomButton { - public: - explicit TestCustomButton(ButtonListener* listener) - : CustomButton(listener) { - } - - virtual ~TestCustomButton() {} - - private: - DISALLOW_COPY_AND_ASSIGN(TestCustomButton); -}; - -void PerformGesture(CustomButton* button, ui::EventType event_type) { - ui::GestureEventDetails gesture_details(event_type); - base::TimeDelta time_stamp = base::TimeDelta::FromMicroseconds(0); - ui::GestureEvent gesture_event(0, 0, 0, time_stamp, gesture_details); - button->OnGestureEvent(&gesture_event); -} - -} // namespace - -typedef ViewsTestBase CustomButtonTest; - -// Tests that hover state changes correctly when visiblity/enableness changes. -TEST_F(CustomButtonTest, HoverStateOnVisibilityChange) { - // Create a widget so that the CustomButton can query the hover state - // correctly. - scoped_ptr<Widget> widget(new Widget); - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.bounds = gfx::Rect(0, 0, 650, 650); - widget->Init(params); - widget->Show(); - - aura::test::TestCursorClient cursor_client( - widget->GetNativeView()->GetRootWindow()); - - // Position the widget in a way so that it is under the cursor. - gfx::Point cursor = gfx::Screen::GetScreenFor( - widget->GetNativeView())->GetCursorScreenPoint(); - gfx::Rect widget_bounds = widget->GetWindowBoundsInScreen(); - widget_bounds.set_origin(cursor); - widget->SetBounds(widget_bounds); - - TestCustomButton* button = new TestCustomButton(NULL); - widget->SetContentsView(button); - - gfx::Point center(10, 10); - button->OnMousePressed(ui::MouseEvent(ui::ET_MOUSE_PRESSED, center, center, - ui::EF_LEFT_MOUSE_BUTTON, - ui::EF_LEFT_MOUSE_BUTTON)); - EXPECT_EQ(CustomButton::STATE_PRESSED, button->state()); - - button->OnMouseReleased(ui::MouseEvent(ui::ET_MOUSE_RELEASED, center, center, - ui::EF_LEFT_MOUSE_BUTTON, - ui::EF_LEFT_MOUSE_BUTTON)); - EXPECT_EQ(CustomButton::STATE_HOVERED, button->state()); - - button->SetEnabled(false); - EXPECT_EQ(CustomButton::STATE_DISABLED, button->state()); - - button->SetEnabled(true); - EXPECT_EQ(CustomButton::STATE_HOVERED, button->state()); - - button->SetVisible(false); - EXPECT_EQ(CustomButton::STATE_NORMAL, button->state()); - - button->SetVisible(true); - EXPECT_EQ(CustomButton::STATE_HOVERED, button->state()); - - // In Aura views, no new hover effects are invoked if mouse events - // are disabled. - cursor_client.DisableMouseEvents(); - - button->SetEnabled(false); - EXPECT_EQ(CustomButton::STATE_DISABLED, button->state()); - - button->SetEnabled(true); - EXPECT_EQ(CustomButton::STATE_NORMAL, button->state()); - - button->SetVisible(false); - EXPECT_EQ(CustomButton::STATE_NORMAL, button->state()); - - button->SetVisible(true); - EXPECT_EQ(CustomButton::STATE_NORMAL, button->state()); -} - -// Tests that gesture events correctly change the button state. -TEST_F(CustomButtonTest, GestureEventsSetState) { - // Create a widget so that the CustomButton can query the hover state - // correctly. - scoped_ptr<Widget> widget(new Widget); - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.bounds = gfx::Rect(0, 0, 650, 650); - widget->Init(params); - widget->Show(); - - aura::test::TestCursorClient cursor_client( - widget->GetNativeView()->GetRootWindow()); - - TestCustomButton* button = new TestCustomButton(NULL); - widget->SetContentsView(button); - - EXPECT_EQ(CustomButton::STATE_NORMAL, button->state()); - - PerformGesture(button, ui::ET_GESTURE_TAP_DOWN); - EXPECT_EQ(CustomButton::STATE_PRESSED, button->state()); - - PerformGesture(button, ui::ET_GESTURE_SHOW_PRESS); - EXPECT_EQ(CustomButton::STATE_PRESSED, button->state()); - - PerformGesture(button, ui::ET_GESTURE_TAP_CANCEL); - EXPECT_EQ(CustomButton::STATE_NORMAL, button->state()); -} - -// Ensure subclasses of CustomButton are correctly recognized as CustomButton. -TEST_F(CustomButtonTest, AsCustomButton) { - base::string16 text; - - LabelButton label_button(NULL, text); - EXPECT_TRUE(CustomButton::AsCustomButton(&label_button)); - - ImageButton image_button(NULL); - EXPECT_TRUE(CustomButton::AsCustomButton(&image_button)); - - Checkbox checkbox(text); - EXPECT_TRUE(CustomButton::AsCustomButton(&checkbox)); - - RadioButton radio_button(text, 0); - EXPECT_TRUE(CustomButton::AsCustomButton(&radio_button)); - - MenuButton menu_button(NULL, text, NULL, false); - EXPECT_TRUE(CustomButton::AsCustomButton(&menu_button)); - - Label label; - EXPECT_FALSE(CustomButton::AsCustomButton(&label)); - - Link link(text); - EXPECT_FALSE(CustomButton::AsCustomButton(&link)); - - Textfield textfield; - EXPECT_FALSE(CustomButton::AsCustomButton(&textfield)); -} - -} // namespace views
diff --git a/ui/views/controls/button/image_button.cc b/ui/views/controls/button/image_button.cc deleted file mode 100644 index 1079d5e..0000000 --- a/ui/views/controls/button/image_button.cc +++ /dev/null
@@ -1,266 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/button/image_button.h" - -#include "base/strings/utf_string_conversions.h" -#include "ui/accessibility/ax_view_state.h" -#include "ui/gfx/animation/throb_animation.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/image/image_skia_operations.h" -#include "ui/gfx/scoped_canvas.h" -#include "ui/views/painter.h" -#include "ui/views/widget/widget.h" - -namespace views { - -// Default button size if no image is set. This is ignored if there is an image, -// and exists for historical reasons (any number of clients could depend on this -// behaviour). -static const int kDefaultWidth = 16; -static const int kDefaultHeight = 14; - -const char ImageButton::kViewClassName[] = "ImageButton"; - -//////////////////////////////////////////////////////////////////////////////// -// ImageButton, public: - -ImageButton::ImageButton(ButtonListener* listener) - : CustomButton(listener), - h_alignment_(ALIGN_LEFT), - v_alignment_(ALIGN_TOP), - draw_image_mirrored_(false), - focus_painter_(Painter::CreateDashedFocusPainter()) { - // By default, we request that the gfx::Canvas passed to our View::OnPaint() - // implementation is flipped horizontally so that the button's images are - // mirrored when the UI directionality is right-to-left. - EnableCanvasFlippingForRTLUI(true); -} - -ImageButton::~ImageButton() { -} - -const gfx::ImageSkia& ImageButton::GetImage(ButtonState state) const { - return images_[state]; -} - -void ImageButton::SetImage(ButtonState state, const gfx::ImageSkia* image) { - images_[state] = image ? *image : gfx::ImageSkia(); - PreferredSizeChanged(); -} - -void ImageButton::SetBackground(SkColor color, - const gfx::ImageSkia* image, - const gfx::ImageSkia* mask) { - if (image == NULL || mask == NULL) { - background_image_ = gfx::ImageSkia(); - return; - } - - background_image_ = gfx::ImageSkiaOperations::CreateButtonBackground(color, - *image, *mask); -} - -void ImageButton::SetImageAlignment(HorizontalAlignment h_align, - VerticalAlignment v_align) { - h_alignment_ = h_align; - v_alignment_ = v_align; - SchedulePaint(); -} - -void ImageButton::SetFocusPainter(scoped_ptr<Painter> focus_painter) { - focus_painter_ = focus_painter.Pass(); -} - -void ImageButton::SetMinimumImageSize(const gfx::Size& size) { - if (minimum_image_size_ == size) - return; - - minimum_image_size_ = size; - PreferredSizeChanged(); -} - -//////////////////////////////////////////////////////////////////////////////// -// ImageButton, View overrides: - -gfx::Size ImageButton::GetPreferredSize() const { - gfx::Size size(kDefaultWidth, kDefaultHeight); - if (!images_[STATE_NORMAL].isNull()) { - size = gfx::Size(images_[STATE_NORMAL].width(), - images_[STATE_NORMAL].height()); - } - - size.SetToMax(minimum_image_size_); - - gfx::Insets insets = GetInsets(); - size.Enlarge(insets.width(), insets.height()); - return size; -} - -const char* ImageButton::GetClassName() const { - return kViewClassName; -} - -void ImageButton::OnPaint(gfx::Canvas* canvas) { - // Call the base class first to paint any background/borders. - View::OnPaint(canvas); - - gfx::ImageSkia img = GetImageToPaint(); - - if (!img.isNull()) { - gfx::ScopedCanvas scoped(canvas); - if (draw_image_mirrored_) { - canvas->Translate(gfx::Vector2d(width(), 0)); - canvas->Scale(-1, 1); - } - - gfx::Point position = ComputeImagePaintPosition(img); - if (!background_image_.isNull()) - canvas->DrawImageInt(background_image_, position.x(), position.y()); - - canvas->DrawImageInt(img, position.x(), position.y()); - } - - Painter::PaintFocusPainter(this, canvas, focus_painter()); -} - -//////////////////////////////////////////////////////////////////////////////// -// ImageButton, protected: - -void ImageButton::OnFocus() { - View::OnFocus(); - if (focus_painter_.get()) - SchedulePaint(); -} - -void ImageButton::OnBlur() { - View::OnBlur(); - if (focus_painter_.get()) - SchedulePaint(); -} - -gfx::ImageSkia ImageButton::GetImageToPaint() { - gfx::ImageSkia img; - - if (!images_[STATE_HOVERED].isNull() && hover_animation_->is_animating()) { - img = gfx::ImageSkiaOperations::CreateBlendedImage(images_[STATE_NORMAL], - images_[STATE_HOVERED], hover_animation_->GetCurrentValue()); - } else { - img = images_[state_]; - } - - return !img.isNull() ? img : images_[STATE_NORMAL]; -} - -//////////////////////////////////////////////////////////////////////////////// -// ImageButton, private: - -gfx::Point ImageButton::ComputeImagePaintPosition(const gfx::ImageSkia& image) { - int x = 0, y = 0; - gfx::Rect rect = GetContentsBounds(); - - HorizontalAlignment h_alignment = h_alignment_; - if (draw_image_mirrored_) { - if (h_alignment == ALIGN_RIGHT) - h_alignment = ALIGN_LEFT; - else if (h_alignment == ALIGN_LEFT) - h_alignment = ALIGN_RIGHT; - } - - if (h_alignment == ALIGN_CENTER) - x = (rect.width() - image.width()) / 2; - else if (h_alignment == ALIGN_RIGHT) - x = rect.width() - image.width(); - - if (v_alignment_ == ALIGN_MIDDLE) - y = (rect.height() - image.height()) / 2; - else if (v_alignment_ == ALIGN_BOTTOM) - y = rect.height() - image.height(); - - x += rect.x(); - y += rect.y(); - - return gfx::Point(x, y); -} - -//////////////////////////////////////////////////////////////////////////////// -// ToggleImageButton, public: - -ToggleImageButton::ToggleImageButton(ButtonListener* listener) - : ImageButton(listener), - toggled_(false) { -} - -ToggleImageButton::~ToggleImageButton() { -} - -void ToggleImageButton::SetToggled(bool toggled) { - if (toggled == toggled_) - return; - - for (int i = 0; i < STATE_COUNT; ++i) { - gfx::ImageSkia temp = images_[i]; - images_[i] = alternate_images_[i]; - alternate_images_[i] = temp; - } - toggled_ = toggled; - SchedulePaint(); - - NotifyAccessibilityEvent(ui::AX_EVENT_VALUE_CHANGED, true); -} - -void ToggleImageButton::SetToggledImage(ButtonState state, - const gfx::ImageSkia* image) { - if (toggled_) { - images_[state] = image ? *image : gfx::ImageSkia(); - if (state_ == state) - SchedulePaint(); - } else { - alternate_images_[state] = image ? *image : gfx::ImageSkia(); - } -} - -void ToggleImageButton::SetToggledTooltipText(const base::string16& tooltip) { - toggled_tooltip_text_ = tooltip; -} - -//////////////////////////////////////////////////////////////////////////////// -// ToggleImageButton, ImageButton overrides: - -const gfx::ImageSkia& ToggleImageButton::GetImage(ButtonState state) const { - if (toggled_) - return alternate_images_[state]; - return images_[state]; -} - -void ToggleImageButton::SetImage(ButtonState state, - const gfx::ImageSkia* image) { - if (toggled_) { - alternate_images_[state] = image ? *image : gfx::ImageSkia(); - } else { - images_[state] = image ? *image : gfx::ImageSkia(); - if (state_ == state) - SchedulePaint(); - } - PreferredSizeChanged(); -} - -//////////////////////////////////////////////////////////////////////////////// -// ToggleImageButton, View overrides: - -bool ToggleImageButton::GetTooltipText(const gfx::Point& p, - base::string16* tooltip) const { - if (!toggled_ || toggled_tooltip_text_.empty()) - return Button::GetTooltipText(p, tooltip); - - *tooltip = toggled_tooltip_text_; - return true; -} - -void ToggleImageButton::GetAccessibleState(ui::AXViewState* state) { - ImageButton::GetAccessibleState(state); - GetTooltipText(gfx::Point(), &state->name); -} - -} // namespace views
diff --git a/ui/views/controls/button/image_button.h b/ui/views/controls/button/image_button.h deleted file mode 100644 index dc861c4..0000000 --- a/ui/views/controls/button/image_button.h +++ /dev/null
@@ -1,171 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_BUTTON_IMAGE_BUTTON_H_ -#define UI_VIEWS_CONTROLS_BUTTON_IMAGE_BUTTON_H_ - -#include "base/gtest_prod_util.h" -#include "base/memory/scoped_ptr.h" -#include "ui/base/layout.h" -#include "ui/gfx/image/image_skia.h" -#include "ui/views/controls/button/custom_button.h" - -namespace views { - -class Painter; - -// An image button. - -// Note that this type of button is not focusable by default and will not be -// part of the focus chain. Call SetFocusable(true) to make it part of the -// focus chain. - -class VIEWS_EXPORT ImageButton : public CustomButton { - public: - static const char kViewClassName[]; - - enum HorizontalAlignment { - ALIGN_LEFT = 0, - ALIGN_CENTER, - ALIGN_RIGHT - }; - - enum VerticalAlignment { - ALIGN_TOP = 0, - ALIGN_MIDDLE, - ALIGN_BOTTOM - }; - - explicit ImageButton(ButtonListener* listener); - virtual ~ImageButton(); - - // Returns the image for a given |state|. - virtual const gfx::ImageSkia& GetImage(ButtonState state) const; - - // Set the image the button should use for the provided state. - virtual void SetImage(ButtonState state, const gfx::ImageSkia* image); - - // Set the background details. - void SetBackground(SkColor color, - const gfx::ImageSkia* image, - const gfx::ImageSkia* mask); - - // Sets how the image is laid out within the button's bounds. - void SetImageAlignment(HorizontalAlignment h_align, - VerticalAlignment v_align); - - void SetFocusPainter(scoped_ptr<Painter> focus_painter); - - // The minimum size of the contents (not including the border). The contents - // will be at least this size, but may be larger if the image itself is - // larger. - const gfx::Size& minimum_image_size() const { return minimum_image_size_; } - void SetMinimumImageSize(const gfx::Size& size); - - // Whether we should draw our images resources horizontally flipped. - void SetDrawImageMirrored(bool mirrored) { - draw_image_mirrored_ = mirrored; - } - - // Overridden from View: - virtual gfx::Size GetPreferredSize() const override; - virtual const char* GetClassName() const override; - virtual void OnPaint(gfx::Canvas* canvas) override; - - protected: - // Overridden from View: - virtual void OnFocus() override; - virtual void OnBlur() override; - - // Returns the image to paint. This is invoked from paint and returns a value - // from images. - virtual gfx::ImageSkia GetImageToPaint(); - - // Updates button background for |scale_factor|. - void UpdateButtonBackground(ui::ScaleFactor scale_factor); - - Painter* focus_painter() { return focus_painter_.get(); } - - // The images used to render the different states of this button. - gfx::ImageSkia images_[STATE_COUNT]; - - gfx::ImageSkia background_image_; - - private: - FRIEND_TEST_ALL_PREFIXES(ImageButtonTest, Basics); - FRIEND_TEST_ALL_PREFIXES(ImageButtonTest, ImagePositionWithBorder); - FRIEND_TEST_ALL_PREFIXES(ImageButtonTest, LeftAlignedMirrored); - FRIEND_TEST_ALL_PREFIXES(ImageButtonTest, RightAlignedMirrored); - - // Returns the correct position of the image for painting. - gfx::Point ComputeImagePaintPosition(const gfx::ImageSkia& image); - - // Image alignment. - HorizontalAlignment h_alignment_; - VerticalAlignment v_alignment_; - gfx::Size minimum_image_size_; - - // Whether we draw our resources horizontally flipped. This can happen in the - // linux titlebar, where image resources were designed to be flipped so a - // small curved corner in the close button designed to fit into the frame - // resources. - bool draw_image_mirrored_; - - scoped_ptr<Painter> focus_painter_; - - DISALLOW_COPY_AND_ASSIGN(ImageButton); -}; - -//////////////////////////////////////////////////////////////////////////////// -// -// ToggleImageButton -// -// A toggle-able ImageButton. It swaps out its graphics when toggled. -// -//////////////////////////////////////////////////////////////////////////////// -class VIEWS_EXPORT ToggleImageButton : public ImageButton { - public: - explicit ToggleImageButton(ButtonListener* listener); - virtual ~ToggleImageButton(); - - // Change the toggled state. - void SetToggled(bool toggled); - - // Like ImageButton::SetImage(), but to set the graphics used for the - // "has been toggled" state. Must be called for each button state - // before the button is toggled. - void SetToggledImage(ButtonState state, const gfx::ImageSkia* image); - - // Set the tooltip text displayed when the button is toggled. - void SetToggledTooltipText(const base::string16& tooltip); - - // Overridden from ImageButton: - virtual const gfx::ImageSkia& GetImage(ButtonState state) const override; - virtual void SetImage(ButtonState state, - const gfx::ImageSkia* image) override; - - // Overridden from View: - virtual bool GetTooltipText(const gfx::Point& p, - base::string16* tooltip) const override; - virtual void GetAccessibleState(ui::AXViewState* state) override; - - private: - // The parent class's images_ member is used for the current images, - // and this array is used to hold the alternative images. - // We swap between the two when toggling. - gfx::ImageSkia alternate_images_[STATE_COUNT]; - - // True if the button is currently toggled. - bool toggled_; - - // The parent class's tooltip_text_ is displayed when not toggled, and - // this one is shown when toggled. - base::string16 toggled_tooltip_text_; - - DISALLOW_COPY_AND_ASSIGN(ToggleImageButton); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_BUTTON_IMAGE_BUTTON_H_
diff --git a/ui/views/controls/button/image_button_unittest.cc b/ui/views/controls/button/image_button_unittest.cc deleted file mode 100644 index 9ea7164..0000000 --- a/ui/views/controls/button/image_button_unittest.cc +++ /dev/null
@@ -1,163 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/base/layout.h" -#include "ui/views/border.h" -#include "ui/views/controls/button/image_button.h" -#include "ui/views/test/views_test_base.h" - -namespace { - -gfx::ImageSkia CreateTestImage(int width, int height) { - SkBitmap bitmap; - bitmap.allocN32Pixels(width, height); - return gfx::ImageSkia::CreateFrom1xBitmap(bitmap); -} - -} // namespace - -namespace views { - -typedef ViewsTestBase ImageButtonTest; - -TEST_F(ImageButtonTest, Basics) { - ImageButton button(NULL); - - // Our image to paint starts empty. - EXPECT_TRUE(button.GetImageToPaint().isNull()); - - // Without an image, buttons are 16x14 by default. - EXPECT_EQ("16x14", button.GetPreferredSize().ToString()); - - // The minimum image size should be applied even when there is no image. - button.SetMinimumImageSize(gfx::Size(5, 15)); - EXPECT_EQ("5x15", button.minimum_image_size().ToString()); - EXPECT_EQ("16x15", button.GetPreferredSize().ToString()); - - // Set a normal image. - gfx::ImageSkia normal_image = CreateTestImage(10, 20); - button.SetImage(CustomButton::STATE_NORMAL, &normal_image); - - // Image uses normal image for painting. - EXPECT_FALSE(button.GetImageToPaint().isNull()); - EXPECT_EQ(10, button.GetImageToPaint().width()); - EXPECT_EQ(20, button.GetImageToPaint().height()); - - // Preferred size is the normal button size. - EXPECT_EQ("10x20", button.GetPreferredSize().ToString()); - - // Set a pushed image. - gfx::ImageSkia pushed_image = CreateTestImage(11, 21); - button.SetImage(CustomButton::STATE_PRESSED, &pushed_image); - - // By convention, preferred size doesn't change, even though pushed image - // is bigger. - EXPECT_EQ("10x20", button.GetPreferredSize().ToString()); - - // We're still painting the normal image. - EXPECT_FALSE(button.GetImageToPaint().isNull()); - EXPECT_EQ(10, button.GetImageToPaint().width()); - EXPECT_EQ(20, button.GetImageToPaint().height()); - - // The minimum image size should make the preferred size bigger. - button.SetMinimumImageSize(gfx::Size(15, 5)); - EXPECT_EQ("15x5", button.minimum_image_size().ToString()); - EXPECT_EQ("15x20", button.GetPreferredSize().ToString()); - button.SetMinimumImageSize(gfx::Size(15, 25)); - EXPECT_EQ("15x25", button.minimum_image_size().ToString()); - EXPECT_EQ("15x25", button.GetPreferredSize().ToString()); -} - -TEST_F(ImageButtonTest, SetAndGetImage) { - ImageButton button(NULL); - - // Images start as null. - EXPECT_TRUE(button.GetImage(Button::STATE_NORMAL).isNull()); - EXPECT_TRUE(button.GetImage(Button::STATE_HOVERED).isNull()); - EXPECT_TRUE(button.GetImage(Button::STATE_PRESSED).isNull()); - EXPECT_TRUE(button.GetImage(Button::STATE_DISABLED).isNull()); - - // Setting images works as expected. - gfx::ImageSkia image1 = CreateTestImage(10, 11); - gfx::ImageSkia image2 = CreateTestImage(20, 21); - button.SetImage(Button::STATE_NORMAL, &image1); - button.SetImage(Button::STATE_HOVERED, &image2); - EXPECT_TRUE( - button.GetImage(Button::STATE_NORMAL).BackedBySameObjectAs(image1)); - EXPECT_TRUE( - button.GetImage(Button::STATE_HOVERED).BackedBySameObjectAs(image2)); - EXPECT_TRUE(button.GetImage(Button::STATE_PRESSED).isNull()); - EXPECT_TRUE(button.GetImage(Button::STATE_DISABLED).isNull()); - - // ImageButton supports NULL image pointers. - button.SetImage(Button::STATE_NORMAL, NULL); - EXPECT_TRUE(button.GetImage(Button::STATE_NORMAL).isNull()); -} - -TEST_F(ImageButtonTest, ImagePositionWithBorder) { - ImageButton button(NULL); - gfx::ImageSkia image = CreateTestImage(20, 30); - button.SetImage(CustomButton::STATE_NORMAL, &image); - - // The image should be painted at the top-left corner. - EXPECT_EQ(gfx::Point().ToString(), - button.ComputeImagePaintPosition(image).ToString()); - - button.SetBorder(views::Border::CreateEmptyBorder(10, 5, 0, 0)); - EXPECT_EQ(gfx::Point(5, 10).ToString(), - button.ComputeImagePaintPosition(image).ToString()); - - button.SetBorder(Border::NullBorder()); - button.SetBounds(0, 0, 50, 50); - EXPECT_EQ(gfx::Point().ToString(), - button.ComputeImagePaintPosition(image).ToString()); - - button.SetImageAlignment(ImageButton::ALIGN_CENTER, - ImageButton::ALIGN_MIDDLE); - EXPECT_EQ(gfx::Point(15, 10).ToString(), - button.ComputeImagePaintPosition(image).ToString()); - button.SetBorder(views::Border::CreateEmptyBorder(10, 10, 0, 0)); - EXPECT_EQ(gfx::Point(20, 15).ToString(), - button.ComputeImagePaintPosition(image).ToString()); - - // The entire button's size should take the border into account. - EXPECT_EQ(gfx::Size(30, 40).ToString(), button.GetPreferredSize().ToString()); - - // The border should be added on top of the minimum image size. - button.SetMinimumImageSize(gfx::Size(30, 5)); - EXPECT_EQ(gfx::Size(40, 40).ToString(), button.GetPreferredSize().ToString()); -} - -TEST_F(ImageButtonTest, LeftAlignedMirrored) { - ImageButton button(NULL); - gfx::ImageSkia image = CreateTestImage(20, 30); - button.SetImage(CustomButton::STATE_NORMAL, &image); - button.SetBounds(0, 0, 50, 30); - button.SetImageAlignment(ImageButton::ALIGN_LEFT, - ImageButton::ALIGN_BOTTOM); - button.SetDrawImageMirrored(true); - - // Because the coordinates are flipped, we should expect this to draw as if - // it were ALIGN_RIGHT. - EXPECT_EQ(gfx::Point(30, 0).ToString(), - button.ComputeImagePaintPosition(image).ToString()); -} - -TEST_F(ImageButtonTest, RightAlignedMirrored) { - ImageButton button(NULL); - gfx::ImageSkia image = CreateTestImage(20, 30); - button.SetImage(CustomButton::STATE_NORMAL, &image); - button.SetBounds(0, 0, 50, 30); - button.SetImageAlignment(ImageButton::ALIGN_RIGHT, - ImageButton::ALIGN_BOTTOM); - button.SetDrawImageMirrored(true); - - // Because the coordinates are flipped, we should expect this to draw as if - // it were ALIGN_LEFT. - EXPECT_EQ(gfx::Point(0, 0).ToString(), - button.ComputeImagePaintPosition(image).ToString()); -} - -} // namespace views
diff --git a/ui/views/controls/button/label_button.cc b/ui/views/controls/button/label_button.cc deleted file mode 100644 index 8dd6d67..0000000 --- a/ui/views/controls/button/label_button.cc +++ /dev/null
@@ -1,504 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/button/label_button.h" - -#include "base/lazy_instance.h" -#include "base/logging.h" -#include "ui/gfx/animation/throb_animation.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/font_list.h" -#include "ui/gfx/sys_color_change_listener.h" -#include "ui/native_theme/native_theme.h" -#include "ui/views/background.h" -#include "ui/views/controls/button/label_button_border.h" -#include "ui/views/painter.h" -#include "ui/views/window/dialog_delegate.h" - -namespace { - -// The default spacing between the icon and text. -const int kSpacing = 5; - -#if !(defined(OS_LINUX) && !defined(OS_CHROMEOS)) -// Default text and shadow colors for STYLE_BUTTON. -const SkColor kStyleButtonTextColor = SK_ColorBLACK; -const SkColor kStyleButtonShadowColor = SK_ColorWHITE; -#endif - -const gfx::FontList& GetDefaultNormalFontList() { - static base::LazyInstance<gfx::FontList>::Leaky font_list = - LAZY_INSTANCE_INITIALIZER; - return font_list.Get(); -} - -const gfx::FontList& GetDefaultBoldFontList() { - static base::LazyInstance<gfx::FontList>::Leaky font_list = - LAZY_INSTANCE_INITIALIZER; - if ((font_list.Get().GetFontStyle() & gfx::Font::BOLD) == 0) { - font_list.Get() = font_list.Get(). - DeriveWithStyle(font_list.Get().GetFontStyle() | gfx::Font::BOLD); - DCHECK_NE(font_list.Get().GetFontStyle() & gfx::Font::BOLD, 0); - } - return font_list.Get(); -} - -} // namespace - -namespace views { - -// static -const int LabelButton::kHoverAnimationDurationMs = 170; - -// static -const char LabelButton::kViewClassName[] = "LabelButton"; - -LabelButton::LabelButton(ButtonListener* listener, const base::string16& text) - : CustomButton(listener), - image_(new ImageView()), - label_(new Label()), - cached_normal_font_list_(GetDefaultNormalFontList()), - cached_bold_font_list_(GetDefaultBoldFontList()), - button_state_images_(), - button_state_colors_(), - explicitly_set_colors_(), - is_default_(false), - style_(STYLE_TEXTBUTTON), - border_is_themed_border_(true), - image_label_spacing_(kSpacing) { - SetAnimationDuration(kHoverAnimationDurationMs); - SetText(text); - - AddChildView(image_); - image_->set_interactive(false); - - AddChildView(label_); - label_->SetFontList(cached_normal_font_list_); - label_->SetAutoColorReadabilityEnabled(false); - label_->SetHorizontalAlignment(gfx::ALIGN_LEFT); - - // Initialize the colors, border, and layout. - SetStyle(style_); - - SetAccessibleName(text); -} - -LabelButton::~LabelButton() {} - -const gfx::ImageSkia& LabelButton::GetImage(ButtonState for_state) { - if (for_state != STATE_NORMAL && button_state_images_[for_state].isNull()) - return button_state_images_[STATE_NORMAL]; - return button_state_images_[for_state]; -} - -void LabelButton::SetImage(ButtonState for_state, const gfx::ImageSkia& image) { - button_state_images_[for_state] = image; - UpdateImage(); -} - -const base::string16& LabelButton::GetText() const { - return label_->text(); -} - -void LabelButton::SetText(const base::string16& text) { - SetAccessibleName(text); - label_->SetText(text); -} - -void LabelButton::SetTextColor(ButtonState for_state, SkColor color) { - button_state_colors_[for_state] = color; - if (for_state == STATE_DISABLED) - label_->SetDisabledColor(color); - else if (for_state == state()) - label_->SetEnabledColor(color); - explicitly_set_colors_[for_state] = true; -} - -void LabelButton::SetTextShadows(const gfx::ShadowValues& shadows) { - label_->SetShadows(shadows); -} - -void LabelButton::SetTextSubpixelRenderingEnabled(bool enabled) { - label_->SetSubpixelRenderingEnabled(enabled); -} - -bool LabelButton::GetTextMultiLine() const { - return label_->multi_line(); -} - -void LabelButton::SetTextMultiLine(bool text_multi_line) { - label_->SetMultiLine(text_multi_line); -} - -const gfx::FontList& LabelButton::GetFontList() const { - return label_->font_list(); -} - -void LabelButton::SetFontList(const gfx::FontList& font_list) { - cached_normal_font_list_ = font_list; - cached_bold_font_list_ = font_list.DeriveWithStyle( - font_list.GetFontStyle() | gfx::Font::BOLD); - - // STYLE_BUTTON uses bold text to indicate default buttons. - label_->SetFontList( - style_ == STYLE_BUTTON && is_default_ ? - cached_bold_font_list_ : cached_normal_font_list_); -} - -void LabelButton::SetElideBehavior(gfx::ElideBehavior elide_behavior) { - label_->SetElideBehavior(elide_behavior); -} - -gfx::HorizontalAlignment LabelButton::GetHorizontalAlignment() const { - return label_->GetHorizontalAlignment(); -} - -void LabelButton::SetHorizontalAlignment(gfx::HorizontalAlignment alignment) { - label_->SetHorizontalAlignment(alignment); - InvalidateLayout(); -} - -void LabelButton::SetMinSize(const gfx::Size& min_size) { - min_size_ = min_size; - ResetCachedPreferredSize(); -} - -void LabelButton::SetMaxSize(const gfx::Size& max_size) { - max_size_ = max_size; - ResetCachedPreferredSize(); -} - -void LabelButton::SetIsDefault(bool is_default) { - if (is_default == is_default_) - return; - is_default_ = is_default; - ui::Accelerator accel(ui::VKEY_RETURN, ui::EF_NONE); - is_default_ ? AddAccelerator(accel) : RemoveAccelerator(accel); - - // STYLE_BUTTON uses bold text to indicate default buttons. - if (style_ == STYLE_BUTTON) { - label_->SetFontList( - is_default ? cached_bold_font_list_ : cached_normal_font_list_); - } -} - -void LabelButton::SetStyle(ButtonStyle style) { - style_ = style; - // Inset the button focus rect from the actual border; roughly match Windows. - if (style == STYLE_BUTTON) { - SetFocusPainter(scoped_ptr<Painter>()); - } else { - SetFocusPainter(Painter::CreateDashedFocusPainterWithInsets( - gfx::Insets(3, 3, 3, 3))); - } - if (style == STYLE_BUTTON) { - label_->SetHorizontalAlignment(gfx::ALIGN_CENTER); - SetFocusable(true); - } - if (style == STYLE_BUTTON) - SetMinSize(gfx::Size(70, 33)); - OnNativeThemeChanged(GetNativeTheme()); - ResetCachedPreferredSize(); -} - -void LabelButton::SetImageLabelSpacing(int spacing) { - if (spacing == image_label_spacing_) - return; - image_label_spacing_ = spacing; - ResetCachedPreferredSize(); - InvalidateLayout(); -} - -void LabelButton::SetFocusPainter(scoped_ptr<Painter> focus_painter) { - focus_painter_ = focus_painter.Pass(); -} - -gfx::Size LabelButton::GetPreferredSize() const { - if (cached_preferred_size_valid_) - return cached_preferred_size_; - - // Use a temporary label copy for sizing to avoid calculation side-effects. - Label label(GetText(), cached_normal_font_list_); - label.SetShadows(label_->shadows()); - label.SetMultiLine(GetTextMultiLine()); - - if (style() == STYLE_BUTTON) { - // Some text appears wider when rendered normally than when rendered bold. - // Accommodate the widest, as buttons may show bold and shouldn't resize. - const int current_width = label.GetPreferredSize().width(); - label.SetFontList(cached_bold_font_list_); - if (label.GetPreferredSize().width() < current_width) - label.SetFontList(cached_normal_font_list_); - } - - // Calculate the required size. - const gfx::Size image_size(image_->GetPreferredSize()); - gfx::Size size(label.GetPreferredSize()); - if (image_size.width() > 0 && size.width() > 0) - size.Enlarge(image_label_spacing_, 0); - size.SetToMax(gfx::Size(0, image_size.height())); - const gfx::Insets insets(GetInsets()); - size.Enlarge(image_size.width() + insets.width(), insets.height()); - - // Make the size at least as large as the minimum size needed by the border. - size.SetToMax(border() ? border()->GetMinimumSize() : gfx::Size()); - - // Increase the minimum size monotonically with the preferred size. - size.SetToMax(min_size_); - min_size_ = size; - - // Return the largest known size clamped to the maximum size (if valid). - if (max_size_.width() > 0) - size.set_width(std::min(max_size_.width(), size.width())); - if (max_size_.height() > 0) - size.set_height(std::min(max_size_.height(), size.height())); - - // Cache this computed size, as recomputing it is an expensive operation. - cached_preferred_size_valid_ = true; - cached_preferred_size_ = size; - return cached_preferred_size_; -} - -int LabelButton::GetHeightForWidth(int w) const { - w -= GetInsets().width(); - const gfx::Size image_size(image_->GetPreferredSize()); - w -= image_size.width(); - if (image_size.width() > 0 && !GetText().empty()) - w -= image_label_spacing_; - - int height = std::max(image_size.height(), label_->GetHeightForWidth(w)); - if (border()) - height = std::max(height, border()->GetMinimumSize().height()); - - height = std::max(height, min_size_.height()); - if (max_size_.height() > 0) - height = std::min(height, max_size_.height()); - return height; -} - -void LabelButton::Layout() { - gfx::HorizontalAlignment adjusted_alignment = GetHorizontalAlignment(); - if (base::i18n::IsRTL() && adjusted_alignment != gfx::ALIGN_CENTER) - adjusted_alignment = (adjusted_alignment == gfx::ALIGN_LEFT) ? - gfx::ALIGN_RIGHT : gfx::ALIGN_LEFT; - - gfx::Rect child_area(GetChildAreaBounds()); - child_area.Inset(GetInsets()); - - gfx::Size image_size(image_->GetPreferredSize()); - image_size.SetToMin(child_area.size()); - - // The label takes any remaining width after sizing the image, unless both - // views are centered. In that case, using the tighter preferred label width - // avoids wasted space within the label that would look like awkward padding. - // Labels can paint over the full button height, including the border height. - gfx::Size label_size(child_area.width(), height()); - if (!image_size.IsEmpty() && !label_size.IsEmpty()) { - label_size.set_width(std::max(child_area.width() - - image_size.width() - image_label_spacing_, 0)); - if (adjusted_alignment == gfx::ALIGN_CENTER) { - // Ensure multi-line labels paired with images use their available width. - label_size.set_width( - std::min(label_size.width(), label_->GetPreferredSize().width())); - } - } - - gfx::Point image_origin(child_area.origin()); - image_origin.Offset(0, (child_area.height() - image_size.height()) / 2); - if (adjusted_alignment == gfx::ALIGN_CENTER) { - const int spacing = (image_size.width() > 0 && label_size.width() > 0) ? - image_label_spacing_ : 0; - const int total_width = image_size.width() + label_size.width() + - spacing; - image_origin.Offset((child_area.width() - total_width) / 2, 0); - } else if (adjusted_alignment == gfx::ALIGN_RIGHT) { - image_origin.Offset(child_area.width() - image_size.width(), 0); - } - - gfx::Point label_origin(child_area.x(), 0); - if (!image_size.IsEmpty() && adjusted_alignment != gfx::ALIGN_RIGHT) { - label_origin.set_x(image_origin.x() + image_size.width() + - image_label_spacing_); - } - - image_->SetBoundsRect(gfx::Rect(image_origin, image_size)); - label_->SetBoundsRect(gfx::Rect(label_origin, label_size)); -} - -const char* LabelButton::GetClassName() const { - return kViewClassName; -} - -scoped_ptr<LabelButtonBorder> LabelButton::CreateDefaultBorder() const { - return scoped_ptr<LabelButtonBorder>(new LabelButtonBorder(style_)); -} - -void LabelButton::SetBorder(scoped_ptr<Border> border) { - border_is_themed_border_ = false; - View::SetBorder(border.Pass()); - ResetCachedPreferredSize(); -} - -gfx::Rect LabelButton::GetChildAreaBounds() { - return GetLocalBounds(); -} - -void LabelButton::OnPaint(gfx::Canvas* canvas) { - View::OnPaint(canvas); - Painter::PaintFocusPainter(this, canvas, focus_painter_.get()); -} - -void LabelButton::OnFocus() { - View::OnFocus(); - // Typically the border renders differently when focused. - SchedulePaint(); -} - -void LabelButton::OnBlur() { - View::OnBlur(); - // Typically the border renders differently when focused. - SchedulePaint(); -} - -void LabelButton::GetExtraParams(ui::NativeTheme::ExtraParams* params) const { - params->button.checked = false; - params->button.indeterminate = false; - params->button.is_default = is_default_; - params->button.is_focused = HasFocus() && IsAccessibilityFocusable(); - params->button.has_border = false; - params->button.classic_state = 0; - params->button.background_color = label_->background_color(); -} - -void LabelButton::ResetColorsFromNativeTheme() { - const ui::NativeTheme* theme = GetNativeTheme(); - SkColor colors[STATE_COUNT] = { - theme->GetSystemColor(ui::NativeTheme::kColorId_ButtonEnabledColor), - theme->GetSystemColor(ui::NativeTheme::kColorId_ButtonHoverColor), - theme->GetSystemColor(ui::NativeTheme::kColorId_ButtonHoverColor), - theme->GetSystemColor(ui::NativeTheme::kColorId_ButtonDisabledColor), - }; - - // Certain styles do not change text color when hovered or pressed. - bool constant_text_color = false; - // Use hardcoded colors for inverted color scheme support and STYLE_BUTTON. - if (gfx::IsInvertedColorScheme()) { - constant_text_color = true; - colors[STATE_NORMAL] = SK_ColorWHITE; - label_->SetBackgroundColor(SK_ColorBLACK); - label_->set_background(Background::CreateSolidBackground(SK_ColorBLACK)); - label_->SetAutoColorReadabilityEnabled(true); - label_->SetShadows(gfx::ShadowValues()); - } else if (style() == STYLE_BUTTON) { - // TODO(erg): This is disabled on desktop linux because of the binary asset - // confusion. These details should either be pushed into ui::NativeThemeWin - // or should be obsoleted by rendering buttons with paint calls instead of - // with static assets. http://crbug.com/350498 -#if !(defined(OS_LINUX) && !defined(OS_CHROMEOS)) - constant_text_color = true; - colors[STATE_NORMAL] = kStyleButtonTextColor; - label_->SetBackgroundColor(theme->GetSystemColor( - ui::NativeTheme::kColorId_ButtonBackgroundColor)); - label_->SetAutoColorReadabilityEnabled(false); - label_->SetShadows(gfx::ShadowValues( - 1, gfx::ShadowValue(gfx::Point(0, 1), 0, kStyleButtonShadowColor))); -#endif - label_->set_background(NULL); - } else { - label_->set_background(NULL); - } - - if (constant_text_color) - colors[STATE_HOVERED] = colors[STATE_PRESSED] = colors[STATE_NORMAL]; - - for (size_t state = STATE_NORMAL; state < STATE_COUNT; ++state) { - if (!explicitly_set_colors_[state]) { - SetTextColor(static_cast<ButtonState>(state), colors[state]); - explicitly_set_colors_[state] = false; - } - } -} - -void LabelButton::UpdateImage() { - image_->SetImage(GetImage(state())); - ResetCachedPreferredSize(); -} - -void LabelButton::UpdateThemedBorder() { - // Don't override borders set by others. - if (!border_is_themed_border_) - return; - - scoped_ptr<LabelButtonBorder> label_button_border = CreateDefaultBorder(); - SetBorder(label_button_border.Pass()); - - border_is_themed_border_ = true; -} - -void LabelButton::StateChanged() { - const gfx::Size previous_image_size(image_->GetPreferredSize()); - UpdateImage(); - const SkColor color = button_state_colors_[state()]; - if (state() != STATE_DISABLED && label_->enabled_color() != color) - label_->SetEnabledColor(color); - label_->SetEnabled(state() != STATE_DISABLED); - if (image_->GetPreferredSize() != previous_image_size) - Layout(); -} - -void LabelButton::ChildPreferredSizeChanged(View* child) { - ResetCachedPreferredSize(); - PreferredSizeChanged(); -} - -void LabelButton::OnNativeThemeChanged(const ui::NativeTheme* theme) { - ResetColorsFromNativeTheme(); - UpdateThemedBorder(); - // Invalidate the layout to pickup the new insets from the border. - InvalidateLayout(); -} - -ui::NativeTheme::Part LabelButton::GetThemePart() const { - return ui::NativeTheme::kPushButton; -} - -gfx::Rect LabelButton::GetThemePaintRect() const { - return GetLocalBounds(); -} - -ui::NativeTheme::State LabelButton::GetThemeState( - ui::NativeTheme::ExtraParams* params) const { - GetExtraParams(params); - switch (state()) { - case STATE_NORMAL: return ui::NativeTheme::kNormal; - case STATE_HOVERED: return ui::NativeTheme::kHovered; - case STATE_PRESSED: return ui::NativeTheme::kPressed; - case STATE_DISABLED: return ui::NativeTheme::kDisabled; - case STATE_COUNT: NOTREACHED() << "Unknown state: " << state(); - } - return ui::NativeTheme::kNormal; -} - -const gfx::Animation* LabelButton::GetThemeAnimation() const { - return hover_animation_.get(); -} - -ui::NativeTheme::State LabelButton::GetBackgroundThemeState( - ui::NativeTheme::ExtraParams* params) const { - GetExtraParams(params); - return ui::NativeTheme::kNormal; -} - -ui::NativeTheme::State LabelButton::GetForegroundThemeState( - ui::NativeTheme::ExtraParams* params) const { - GetExtraParams(params); - return ui::NativeTheme::kHovered; -} - -void LabelButton::ResetCachedPreferredSize() { - cached_preferred_size_valid_ = false; - cached_preferred_size_= gfx::Size(); -} - -} // namespace views
diff --git a/ui/views/controls/button/label_button.h b/ui/views/controls/button/label_button.h deleted file mode 100644 index fbedf8b..0000000 --- a/ui/views/controls/button/label_button.h +++ /dev/null
@@ -1,201 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_BUTTON_LABEL_BUTTON_H_ -#define UI_VIEWS_CONTROLS_BUTTON_LABEL_BUTTON_H_ - -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "third_party/skia/include/core/SkColor.h" -#include "ui/gfx/image/image_skia.h" -#include "ui/views/controls/button/custom_button.h" -#include "ui/views/controls/image_view.h" -#include "ui/views/controls/label.h" -#include "ui/views/native_theme_delegate.h" - -namespace views { - -class LabelButtonBorder; -class Painter; - -// LabelButton is a button with text and an icon, it's not focusable by default. -class VIEWS_EXPORT LabelButton : public CustomButton, - public NativeThemeDelegate { - public: - // The length of the hover fade animation. - static const int kHoverAnimationDurationMs; - - static const char kViewClassName[]; - - LabelButton(ButtonListener* listener, const base::string16& text); - virtual ~LabelButton(); - - // Get or set the image shown for the specified button state. - // GetImage returns the image for STATE_NORMAL if the state's image is empty. - virtual const gfx::ImageSkia& GetImage(ButtonState for_state); - void SetImage(ButtonState for_state, const gfx::ImageSkia& image); - - // Get or set the text shown on the button. - const base::string16& GetText() const; - virtual void SetText(const base::string16& text); - - // Set the text color shown for the specified button state. - void SetTextColor(ButtonState for_state, SkColor color); - - // Set drop shadows underneath the text. - void SetTextShadows(const gfx::ShadowValues& shadows); - - // Sets whether subpixel rendering is used on the label. - void SetTextSubpixelRenderingEnabled(bool enabled); - - // Get or set the text's multi-line property to break on '\n', etc. - bool GetTextMultiLine() const; - void SetTextMultiLine(bool text_multi_line); - - // Get or set the font list used by this button. - const gfx::FontList& GetFontList() const; - void SetFontList(const gfx::FontList& font_list); - - // Set the elide behavior of this button. - void SetElideBehavior(gfx::ElideBehavior elide_behavior); - - // Get or set the horizontal alignment used for the button; reversed in RTL. - // The optional image will lead the text, unless the button is right-aligned. - gfx::HorizontalAlignment GetHorizontalAlignment() const; - void SetHorizontalAlignment(gfx::HorizontalAlignment alignment); - - // Call SetMinSize(gfx::Size()) to clear the monotonically increasing size. - void SetMinSize(const gfx::Size& min_size); - void SetMaxSize(const gfx::Size& max_size); - - // Get or set the option to handle the return key; false by default. - bool is_default() const { return is_default_; } - void SetIsDefault(bool is_default); - - // Get or set the button's overall style; the default is |STYLE_TEXTBUTTON|. - ButtonStyle style() const { return style_; } - void SetStyle(ButtonStyle style); - - // Set the spacing between the image and the text. Shrinking the spacing - // will not shrink the overall button size, as it is monotonically increasing. - // Call SetMinSize(gfx::Size()) to clear the size if needed. - void SetImageLabelSpacing(int spacing); - - void SetFocusPainter(scoped_ptr<Painter> focus_painter); - Painter* focus_painter() { return focus_painter_.get(); } - - // View: - virtual void SetBorder(scoped_ptr<Border> border) override; - virtual gfx::Size GetPreferredSize() const override; - virtual int GetHeightForWidth(int w) const override; - virtual void Layout() override; - virtual const char* GetClassName() const override; - - protected: - ImageView* image() const { return image_; } - Label* label() const { return label_; } - - // Returns the available area for the label and image. Subclasses can change - // these bounds if they need room to do manual painting. - virtual gfx::Rect GetChildAreaBounds(); - - // View: - virtual void OnPaint(gfx::Canvas* canvas) override; - virtual void OnFocus() override; - virtual void OnBlur() override; - virtual void OnNativeThemeChanged(const ui::NativeTheme* theme) override; - - // Fill |params| with information about the button. - virtual void GetExtraParams(ui::NativeTheme::ExtraParams* params) const; - - // Resets colors from the NativeTheme, explicitly set colors are unchanged. - virtual void ResetColorsFromNativeTheme(); - - // Creates the default border for this button. This can be overridden by - // subclasses or by LinuxUI. - virtual scoped_ptr<LabelButtonBorder> CreateDefaultBorder() const; - - // Updates the image view to contain the appropriate button state image. - void UpdateImage(); - - // Updates the border as per the NativeTheme, unless a different border was - // set with SetBorder. - void UpdateThemedBorder(); - - // NativeThemeDelegate: - virtual gfx::Rect GetThemePaintRect() const override; - - private: - FRIEND_TEST_ALL_PREFIXES(LabelButtonTest, Init); - FRIEND_TEST_ALL_PREFIXES(LabelButtonTest, Label); - FRIEND_TEST_ALL_PREFIXES(LabelButtonTest, Image); - FRIEND_TEST_ALL_PREFIXES(LabelButtonTest, LabelAndImage); - FRIEND_TEST_ALL_PREFIXES(LabelButtonTest, FontList); - - // CustomButton: - virtual void StateChanged() override; - - // View: - virtual void ChildPreferredSizeChanged(View* child) override; - - // NativeThemeDelegate: - virtual ui::NativeTheme::Part GetThemePart() const override; - virtual ui::NativeTheme::State GetThemeState( - ui::NativeTheme::ExtraParams* params) const override; - virtual const gfx::Animation* GetThemeAnimation() const override; - virtual ui::NativeTheme::State GetBackgroundThemeState( - ui::NativeTheme::ExtraParams* params) const override; - virtual ui::NativeTheme::State GetForegroundThemeState( - ui::NativeTheme::ExtraParams* params) const override; - - // Resets |cached_preferred_size_| and marks |cached_preferred_size_valid_| - // as false. - void ResetCachedPreferredSize(); - - // The image and label shown in the button. - ImageView* image_; - Label* label_; - - // The cached font lists in the normal and bold style. - gfx::FontList cached_normal_font_list_; - gfx::FontList cached_bold_font_list_; - - // The images and colors for each button state. - gfx::ImageSkia button_state_images_[STATE_COUNT]; - SkColor button_state_colors_[STATE_COUNT]; - - // Used to track whether SetTextColor() has been invoked. - bool explicitly_set_colors_[STATE_COUNT]; - - // |min_size_| increases monotonically with the preferred size. - mutable gfx::Size min_size_; - // |max_size_| may be set to clamp the preferred size. - gfx::Size max_size_; - - // Cache the last computed preferred size. - mutable gfx::Size cached_preferred_size_; - mutable bool cached_preferred_size_valid_; - - // Flag indicating default handling of the return key via an accelerator. - // Whether or not the button appears or behaves as the default button in its - // current context; - bool is_default_; - - // The button's overall style. - ButtonStyle style_; - - // True if current border was set by UpdateThemedBorder. Defaults to true. - bool border_is_themed_border_; - - // Spacing between the image and the text. - int image_label_spacing_; - - scoped_ptr<Painter> focus_painter_; - - DISALLOW_COPY_AND_ASSIGN(LabelButton); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_BUTTON_LABEL_BUTTON_H_
diff --git a/ui/views/controls/button/label_button_border.cc b/ui/views/controls/button/label_button_border.cc deleted file mode 100644 index 587e76b..0000000 --- a/ui/views/controls/button/label_button_border.cc +++ /dev/null
@@ -1,153 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/button/label_button_border.h" - -#include "base/logging.h" -#include "third_party/skia/include/core/SkPaint.h" -#include "third_party/skia/include/effects/SkLerpXfermode.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/gfx/animation/animation.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/rect.h" -#include "ui/gfx/skia_util.h" -#include "ui/gfx/sys_color_change_listener.h" -#include "ui/native_theme/native_theme.h" -#include "ui/resources/grit/ui_resources.h" -#include "ui/views/border.h" -#include "ui/views/controls/button/label_button.h" -#include "ui/views/native_theme_delegate.h" - -namespace views { - -namespace { - -// Insets for the unified button images. This assumes that the images -// are of a 9 grid, of 5x5 size each. -const int kButtonInsets = 5; - -// The text-button hot and pushed image IDs; normal is unadorned by default. -const int kTextHoveredImages[] = IMAGE_GRID(IDR_TEXTBUTTON_HOVER); -const int kTextPressedImages[] = IMAGE_GRID(IDR_TEXTBUTTON_PRESSED); - -// A helper function to paint the appropriate broder images. -void PaintHelper(LabelButtonBorder* border, - gfx::Canvas* canvas, - ui::NativeTheme::State state, - const gfx::Rect& rect, - const ui::NativeTheme::ExtraParams& extra) { - Painter* painter = - border->GetPainter(extra.button.is_focused, - Button::GetButtonStateFrom(state)); - // Paint any corresponding unfocused painter if there is no focused painter. - if (!painter && extra.button.is_focused) - painter = border->GetPainter(false, Button::GetButtonStateFrom(state)); - if (painter) - Painter::PaintPainterAt(canvas, painter, rect); -} - -} // namespace - -LabelButtonBorder::LabelButtonBorder(Button::ButtonStyle style) - : style_(style) { - ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); - const gfx::Insets insets(kButtonInsets, - kButtonInsets, - kButtonInsets, - kButtonInsets); - - if (style == Button::STYLE_BUTTON) { - set_insets(gfx::Insets(8, 13, 8, 13)); - SetPainter(false, Button::STATE_NORMAL, - Painter::CreateImagePainter( - *rb.GetImageSkiaNamed(IDR_BUTTON_NORMAL), insets)); - SetPainter(false, Button::STATE_HOVERED, - Painter::CreateImagePainter( - *rb.GetImageSkiaNamed(IDR_BUTTON_HOVER), insets)); - SetPainter(false, Button::STATE_PRESSED, - Painter::CreateImagePainter( - *rb.GetImageSkiaNamed(IDR_BUTTON_PRESSED), insets)); - SetPainter(false, Button::STATE_DISABLED, - Painter::CreateImagePainter( - *rb.GetImageSkiaNamed(IDR_BUTTON_DISABLED), insets)); - SetPainter(true, Button::STATE_NORMAL, - Painter::CreateImagePainter( - *rb.GetImageSkiaNamed(IDR_BUTTON_FOCUSED_NORMAL), insets)); - SetPainter(true, Button::STATE_HOVERED, - Painter::CreateImagePainter( - *rb.GetImageSkiaNamed(IDR_BUTTON_FOCUSED_HOVER), insets)); - SetPainter(true, Button::STATE_PRESSED, - Painter::CreateImagePainter( - *rb.GetImageSkiaNamed(IDR_BUTTON_FOCUSED_PRESSED), insets)); - SetPainter(true, Button::STATE_DISABLED, - Painter::CreateImagePainter( - *rb.GetImageSkiaNamed(IDR_BUTTON_DISABLED), insets)); - } else if (style == Button::STYLE_TEXTBUTTON) { - set_insets(gfx::Insets(5, 6, 5, 6)); - SetPainter(false, Button::STATE_HOVERED, - Painter::CreateImageGridPainter(kTextHoveredImages)); - SetPainter(false, Button::STATE_PRESSED, - Painter::CreateImageGridPainter(kTextPressedImages)); - } -} - -LabelButtonBorder::~LabelButtonBorder() {} - -void LabelButtonBorder::Paint(const View& view, gfx::Canvas* canvas) { - const NativeThemeDelegate* native_theme_delegate = - static_cast<const LabelButton*>(&view); - gfx::Rect rect(native_theme_delegate->GetThemePaintRect()); - ui::NativeTheme::ExtraParams extra; - const gfx::Animation* animation = native_theme_delegate->GetThemeAnimation(); - ui::NativeTheme::State state = native_theme_delegate->GetThemeState(&extra); - - if (animation && animation->is_animating()) { - // Linearly interpolate background and foreground painters during animation. - const SkRect sk_rect = gfx::RectToSkRect(rect); - canvas->sk_canvas()->saveLayer(&sk_rect, NULL); - state = native_theme_delegate->GetBackgroundThemeState(&extra); - PaintHelper(this, canvas, state, rect, extra); - - SkPaint paint; - skia::RefPtr<SkXfermode> sk_lerp_xfer = - skia::AdoptRef(SkLerpXfermode::Create(animation->GetCurrentValue())); - paint.setXfermode(sk_lerp_xfer.get()); - canvas->sk_canvas()->saveLayer(&sk_rect, &paint); - state = native_theme_delegate->GetForegroundThemeState(&extra); - PaintHelper(this, canvas, state, rect, extra); - canvas->sk_canvas()->restore(); - - canvas->sk_canvas()->restore(); - } else { - PaintHelper(this, canvas, state, rect, extra); - } -} - -gfx::Insets LabelButtonBorder::GetInsets() const { - return insets_; -} - -gfx::Size LabelButtonBorder::GetMinimumSize() const { - gfx::Size minimum_size; - for (int i = 0; i < 2; ++i) { - for (int j = 0; j < Button::STATE_COUNT; ++j) { - if (painters_[i][j]) - minimum_size.SetToMax(painters_[i][j]->GetMinimumSize()); - } - } - return minimum_size; -} - -Painter* LabelButtonBorder::GetPainter(bool focused, - Button::ButtonState state) { - return painters_[focused ? 1 : 0][state].get(); -} - -void LabelButtonBorder::SetPainter(bool focused, - Button::ButtonState state, - Painter* painter) { - painters_[focused ? 1 : 0][state].reset(painter); -} - -} // namespace views
diff --git a/ui/views/controls/button/label_button_border.h b/ui/views/controls/button/label_button_border.h deleted file mode 100644 index 936c898..0000000 --- a/ui/views/controls/button/label_button_border.h +++ /dev/null
@@ -1,52 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_BUTTON_LABEL_BUTTON_BORDER_H_ -#define UI_VIEWS_CONTROLS_BUTTON_LABEL_BUTTON_BORDER_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "ui/gfx/insets.h" -#include "ui/views/border.h" -#include "ui/views/controls/button/button.h" -#include "ui/views/painter.h" - -namespace views { - -// A Border that paints a LabelButton's background frame. -class VIEWS_EXPORT LabelButtonBorder : public Border { - public: - explicit LabelButtonBorder(Button::ButtonStyle style); - virtual ~LabelButtonBorder(); - - Button::ButtonStyle style() const { return style_; } - - // Overridden from Border: - virtual void Paint(const View& view, gfx::Canvas* canvas) override; - virtual gfx::Insets GetInsets() const override; - virtual gfx::Size GetMinimumSize() const override; - - void set_insets(const gfx::Insets& insets) { insets_ = insets; } - - // Get or set the painter used for the specified |focused| button |state|. - // LabelButtonBorder takes and retains ownership of |painter|. - Painter* GetPainter(bool focused, Button::ButtonState state); - void SetPainter(bool focused, Button::ButtonState state, Painter* painter); - - private: - // The painters used for each unfocused or focused button state. - scoped_ptr<Painter> painters_[2][Button::STATE_COUNT]; - - // The button style supplied in part by this border. - Button::ButtonStyle style_; - - gfx::Insets insets_; - - DISALLOW_COPY_AND_ASSIGN(LabelButtonBorder); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_BUTTON_LABEL_BUTTON_BORDER_H_
diff --git a/ui/views/controls/button/label_button_unittest.cc b/ui/views/controls/button/label_button_unittest.cc deleted file mode 100644 index f295173..0000000 --- a/ui/views/controls/button/label_button_unittest.cc +++ /dev/null
@@ -1,228 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/button/label_button.h" - -#include "base/strings/utf_string_conversions.h" -#include "third_party/skia/include/core/SkBitmap.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/font_list.h" -#include "ui/gfx/size.h" -#include "ui/gfx/text_utils.h" -#include "ui/views/test/views_test_base.h" - -using base::ASCIIToUTF16; - -namespace { - -gfx::ImageSkia CreateTestImage(int width, int height) { - SkBitmap bitmap; - bitmap.allocN32Pixels(width, height); - return gfx::ImageSkia::CreateFrom1xBitmap(bitmap); -} - -} // namespace - -namespace views { - -typedef ViewsTestBase LabelButtonTest; - -TEST_F(LabelButtonTest, Init) { - const base::string16 text(ASCIIToUTF16("abc")); - LabelButton button(NULL, text); - - EXPECT_TRUE(button.GetImage(Button::STATE_NORMAL).isNull()); - EXPECT_TRUE(button.GetImage(Button::STATE_HOVERED).isNull()); - EXPECT_TRUE(button.GetImage(Button::STATE_PRESSED).isNull()); - EXPECT_TRUE(button.GetImage(Button::STATE_DISABLED).isNull()); - - EXPECT_EQ(text, button.GetText()); - EXPECT_EQ(gfx::ALIGN_LEFT, button.GetHorizontalAlignment()); - EXPECT_FALSE(button.is_default()); - EXPECT_EQ(button.style(), Button::STYLE_TEXTBUTTON); - EXPECT_EQ(Button::STATE_NORMAL, button.state()); - - EXPECT_EQ(button.image_->parent(), &button); - EXPECT_EQ(button.label_->parent(), &button); -} - -TEST_F(LabelButtonTest, Label) { - LabelButton button(NULL, base::string16()); - EXPECT_TRUE(button.GetText().empty()); - - const gfx::FontList font_list; - const base::string16 short_text(ASCIIToUTF16("abcdefghijklm")); - const base::string16 long_text(ASCIIToUTF16("abcdefghijklmnopqrstuvwxyz")); - const int short_text_width = gfx::GetStringWidth(short_text, font_list); - const int long_text_width = gfx::GetStringWidth(long_text, font_list); - - // The width increases monotonically with string size (it does not shrink). - EXPECT_LT(button.GetPreferredSize().width(), short_text_width); - button.SetText(short_text); - EXPECT_GT(button.GetPreferredSize().height(), font_list.GetHeight()); - EXPECT_GT(button.GetPreferredSize().width(), short_text_width); - EXPECT_LT(button.GetPreferredSize().width(), long_text_width); - button.SetText(long_text); - EXPECT_GT(button.GetPreferredSize().width(), long_text_width); - button.SetText(short_text); - EXPECT_GT(button.GetPreferredSize().width(), long_text_width); - - // Clamp the size to a maximum value. - button.SetMaxSize(gfx::Size(long_text_width, 1)); - EXPECT_EQ(button.GetPreferredSize(), gfx::Size(long_text_width, 1)); - - // Clear the monotonically increasing minimum size. - button.SetMinSize(gfx::Size()); - EXPECT_GT(button.GetPreferredSize().width(), short_text_width); - EXPECT_LT(button.GetPreferredSize().width(), long_text_width); -} - -TEST_F(LabelButtonTest, Image) { - LabelButton button(NULL, base::string16()); - - const int small_size = 50, large_size = 100; - const gfx::ImageSkia small_image = CreateTestImage(small_size, small_size); - const gfx::ImageSkia large_image = CreateTestImage(large_size, large_size); - - // The width increases monotonically with image size (it does not shrink). - EXPECT_LT(button.GetPreferredSize().width(), small_size); - EXPECT_LT(button.GetPreferredSize().height(), small_size); - button.SetImage(Button::STATE_NORMAL, small_image); - EXPECT_GT(button.GetPreferredSize().width(), small_size); - EXPECT_GT(button.GetPreferredSize().height(), small_size); - EXPECT_LT(button.GetPreferredSize().width(), large_size); - EXPECT_LT(button.GetPreferredSize().height(), large_size); - button.SetImage(Button::STATE_NORMAL, large_image); - EXPECT_GT(button.GetPreferredSize().width(), large_size); - EXPECT_GT(button.GetPreferredSize().height(), large_size); - button.SetImage(Button::STATE_NORMAL, small_image); - EXPECT_GT(button.GetPreferredSize().width(), large_size); - EXPECT_GT(button.GetPreferredSize().height(), large_size); - - // Clamp the size to a maximum value. - button.SetMaxSize(gfx::Size(large_size, 1)); - EXPECT_EQ(button.GetPreferredSize(), gfx::Size(large_size, 1)); - - // Clear the monotonically increasing minimum size. - button.SetMinSize(gfx::Size()); - EXPECT_GT(button.GetPreferredSize().width(), small_size); - EXPECT_LT(button.GetPreferredSize().width(), large_size); -} - -TEST_F(LabelButtonTest, LabelAndImage) { - LabelButton button(NULL, base::string16()); - - const gfx::FontList font_list; - const base::string16 text(ASCIIToUTF16("abcdefghijklm")); - const int text_width = gfx::GetStringWidth(text, font_list); - - const int image_size = 50; - const gfx::ImageSkia image = CreateTestImage(image_size, image_size); - ASSERT_LT(font_list.GetHeight(), image_size); - - // The width increases monotonically with content size (it does not shrink). - EXPECT_LT(button.GetPreferredSize().width(), text_width); - EXPECT_LT(button.GetPreferredSize().width(), image_size); - EXPECT_LT(button.GetPreferredSize().height(), image_size); - button.SetText(text); - EXPECT_GT(button.GetPreferredSize().width(), text_width); - EXPECT_GT(button.GetPreferredSize().height(), font_list.GetHeight()); - EXPECT_LT(button.GetPreferredSize().width(), text_width + image_size); - EXPECT_LT(button.GetPreferredSize().height(), image_size); - button.SetImage(Button::STATE_NORMAL, image); - EXPECT_GT(button.GetPreferredSize().width(), text_width + image_size); - EXPECT_GT(button.GetPreferredSize().height(), image_size); - - // Layout and ensure the image is left of the label except for ALIGN_RIGHT. - // (A proper parent view or layout manager would Layout on its invalidations). - button.SetSize(button.GetPreferredSize()); - button.Layout(); - EXPECT_EQ(gfx::ALIGN_LEFT, button.GetHorizontalAlignment()); - EXPECT_LT(button.image_->bounds().right(), button.label_->bounds().x()); - button.SetHorizontalAlignment(gfx::ALIGN_CENTER); - button.Layout(); - EXPECT_EQ(gfx::ALIGN_CENTER, button.GetHorizontalAlignment()); - EXPECT_LT(button.image_->bounds().right(), button.label_->bounds().x()); - button.SetHorizontalAlignment(gfx::ALIGN_RIGHT); - button.Layout(); - EXPECT_EQ(gfx::ALIGN_RIGHT, button.GetHorizontalAlignment()); - EXPECT_LT(button.label_->bounds().right(), button.image_->bounds().x()); - - button.SetText(base::string16()); - EXPECT_GT(button.GetPreferredSize().width(), text_width + image_size); - EXPECT_GT(button.GetPreferredSize().height(), image_size); - button.SetImage(Button::STATE_NORMAL, gfx::ImageSkia()); - EXPECT_GT(button.GetPreferredSize().width(), text_width + image_size); - EXPECT_GT(button.GetPreferredSize().height(), image_size); - - // Clamp the size to a maximum value. - button.SetMaxSize(gfx::Size(image_size, 1)); - EXPECT_EQ(button.GetPreferredSize(), gfx::Size(image_size, 1)); - - // Clear the monotonically increasing minimum size. - button.SetMinSize(gfx::Size()); - EXPECT_LT(button.GetPreferredSize().width(), text_width); - EXPECT_LT(button.GetPreferredSize().width(), image_size); - EXPECT_LT(button.GetPreferredSize().height(), image_size); -} - -TEST_F(LabelButtonTest, FontList) { - const base::string16 text(ASCIIToUTF16("abc")); - LabelButton button(NULL, text); - - const gfx::FontList original_font_list = button.GetFontList(); - const gfx::FontList large_font_list = - original_font_list.DeriveWithSizeDelta(100); - const int original_width = button.GetPreferredSize().width(); - const int original_height = button.GetPreferredSize().height(); - - // The button size increases when the font size is increased. - button.SetFontList(large_font_list); - EXPECT_GT(button.GetPreferredSize().width(), original_width); - EXPECT_GT(button.GetPreferredSize().height(), original_height); - - // The button returns to its original size when the minimal size is cleared - // and the original font size is restored. - button.SetMinSize(gfx::Size()); - button.SetFontList(original_font_list); - EXPECT_EQ(original_width, button.GetPreferredSize().width()); - EXPECT_EQ(original_height, button.GetPreferredSize().height()); -} - -TEST_F(LabelButtonTest, ChangeTextSize) { - const base::string16 text(ASCIIToUTF16("abc")); - const base::string16 longer_text(ASCIIToUTF16("abcdefghijklm")); - LabelButton button(NULL, text); - - const int original_width = button.GetPreferredSize().width(); - - // The button size increases when the text size is increased. - button.SetText(longer_text); - EXPECT_GT(button.GetPreferredSize().width(), original_width); - - // The button returns to its original size when the original text is restored. - button.SetMinSize(gfx::Size()); - button.SetText(text); - EXPECT_EQ(original_width, button.GetPreferredSize().width()); -} - -TEST_F(LabelButtonTest, ChangeLabelImageSpacing) { - LabelButton button(NULL, ASCIIToUTF16("abc")); - button.SetImage(Button::STATE_NORMAL, CreateTestImage(50, 50)); - - const int kOriginalSpacing = 5; - button.SetImageLabelSpacing(kOriginalSpacing); - const int original_width = button.GetPreferredSize().width(); - - // Increasing the spacing between the text and label should increase the size. - button.SetImageLabelSpacing(2 * kOriginalSpacing); - EXPECT_GT(button.GetPreferredSize().width(), original_width); - - // The button shrinks if the original spacing is restored. - button.SetMinSize(gfx::Size()); - button.SetImageLabelSpacing(kOriginalSpacing); - EXPECT_EQ(original_width, button.GetPreferredSize().width()); -} - -} // namespace views
diff --git a/ui/views/controls/button/menu_button.cc b/ui/views/controls/button/menu_button.cc deleted file mode 100644 index debd227..0000000 --- a/ui/views/controls/button/menu_button.cc +++ /dev/null
@@ -1,318 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/button/menu_button.h" - -#include "base/strings/utf_string_conversions.h" -#include "ui/accessibility/ax_view_state.h" -#include "ui/base/dragdrop/drag_drop_types.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/events/event.h" -#include "ui/events/event_constants.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/image/image.h" -#include "ui/gfx/screen.h" -#include "ui/gfx/text_constants.h" -#include "ui/resources/grit/ui_resources.h" -#include "ui/strings/grit/ui_strings.h" -#include "ui/views/controls/button/button.h" -#include "ui/views/controls/button/menu_button_listener.h" -#include "ui/views/mouse_constants.h" -#include "ui/views/widget/root_view.h" -#include "ui/views/widget/widget.h" - -using base::TimeTicks; -using base::TimeDelta; - -namespace views { - -// Default menu offset. -static const int kDefaultMenuOffsetX = -2; -static const int kDefaultMenuOffsetY = -4; - -// static -const char MenuButton::kViewClassName[] = "MenuButton"; -const int MenuButton::kMenuMarkerPaddingLeft = 3; -const int MenuButton::kMenuMarkerPaddingRight = -1; - -//////////////////////////////////////////////////////////////////////////////// -// -// MenuButton::PressedLock -// -//////////////////////////////////////////////////////////////////////////////// - -MenuButton::PressedLock::PressedLock(MenuButton* menu_button) - : menu_button_(menu_button->weak_factory_.GetWeakPtr()) { - menu_button_->IncrementPressedLocked(); -} - -MenuButton::PressedLock::~PressedLock() { - if (menu_button_.get()) - menu_button_->DecrementPressedLocked(); -} - -//////////////////////////////////////////////////////////////////////////////// -// -// MenuButton - constructors, destructors, initialization -// -//////////////////////////////////////////////////////////////////////////////// - -MenuButton::MenuButton(ButtonListener* listener, - const base::string16& text, - MenuButtonListener* menu_button_listener, - bool show_menu_marker) - : LabelButton(listener, text), - menu_offset_(kDefaultMenuOffsetX, kDefaultMenuOffsetY), - listener_(menu_button_listener), - show_menu_marker_(show_menu_marker), - menu_marker_(ui::ResourceBundle::GetSharedInstance().GetImageNamed( - IDR_MENU_DROPARROW).ToImageSkia()), - destroyed_flag_(NULL), - pressed_lock_count_(0), - weak_factory_(this) { - SetHorizontalAlignment(gfx::ALIGN_LEFT); -} - -MenuButton::~MenuButton() { - if (destroyed_flag_) - *destroyed_flag_ = true; -} - -//////////////////////////////////////////////////////////////////////////////// -// -// MenuButton - Public APIs -// -//////////////////////////////////////////////////////////////////////////////// - -bool MenuButton::Activate() { - SetState(STATE_PRESSED); - if (listener_) { - gfx::Rect lb = GetLocalBounds(); - - // The position of the menu depends on whether or not the locale is - // right-to-left. - gfx::Point menu_position(lb.right(), lb.bottom()); - if (base::i18n::IsRTL()) - menu_position.set_x(lb.x()); - - View::ConvertPointToScreen(this, &menu_position); - if (base::i18n::IsRTL()) - menu_position.Offset(-menu_offset_.x(), menu_offset_.y()); - else - menu_position.Offset(menu_offset_.x(), menu_offset_.y()); - - int max_x_coordinate = GetMaximumScreenXCoordinate(); - if (max_x_coordinate && max_x_coordinate <= menu_position.x()) - menu_position.set_x(max_x_coordinate - 1); - - // We're about to show the menu from a mouse press. By showing from the - // mouse press event we block RootView in mouse dispatching. This also - // appears to cause RootView to get a mouse pressed BEFORE the mouse - // release is seen, which means RootView sends us another mouse press no - // matter where the user pressed. To force RootView to recalculate the - // mouse target during the mouse press we explicitly set the mouse handler - // to NULL. - static_cast<internal::RootView*>(GetWidget()->GetRootView())-> - SetMouseHandler(NULL); - - bool destroyed = false; - destroyed_flag_ = &destroyed; - - // We don't set our state here. It's handled in the MenuController code or - // by our click listener. - - listener_->OnMenuButtonClicked(this, menu_position); - - if (destroyed) { - // The menu was deleted while showing. Don't attempt any processing. - return false; - } - - destroyed_flag_ = NULL; - - menu_closed_time_ = TimeTicks::Now(); - - // We must return false here so that the RootView does not get stuck - // sending all mouse pressed events to us instead of the appropriate - // target. - return false; - } - return true; -} - -void MenuButton::OnPaint(gfx::Canvas* canvas) { - LabelButton::OnPaint(canvas); - - if (show_menu_marker_) - PaintMenuMarker(canvas); -} - -//////////////////////////////////////////////////////////////////////////////// -// -// MenuButton - Events -// -//////////////////////////////////////////////////////////////////////////////// - -gfx::Size MenuButton::GetPreferredSize() const { - gfx::Size prefsize = LabelButton::GetPreferredSize(); - if (show_menu_marker_) { - prefsize.Enlarge(menu_marker_->width() + kMenuMarkerPaddingLeft + - kMenuMarkerPaddingRight, - 0); - } - return prefsize; -} - -const char* MenuButton::GetClassName() const { - return kViewClassName; -} - -bool MenuButton::OnMousePressed(const ui::MouseEvent& event) { - RequestFocus(); - if (state() != STATE_DISABLED) { - // If we're draggable (GetDragOperations returns a non-zero value), then - // don't pop on press, instead wait for release. - if (event.IsOnlyLeftMouseButton() && - HitTestPoint(event.location()) && - GetDragOperations(event.location()) == ui::DragDropTypes::DRAG_NONE) { - TimeDelta delta = TimeTicks::Now() - menu_closed_time_; - if (delta.InMilliseconds() > kMinimumMsBetweenButtonClicks) - return Activate(); - } - } - return true; -} - -void MenuButton::OnMouseReleased(const ui::MouseEvent& event) { - // Explicitly test for left mouse button to show the menu. If we tested for - // !IsTriggerableEvent it could lead to a situation where we end up showing - // the menu and context menu (this would happen if the right button is not - // triggerable and there's a context menu). - if (GetDragOperations(event.location()) != ui::DragDropTypes::DRAG_NONE && - state() != STATE_DISABLED && !InDrag() && event.IsOnlyLeftMouseButton() && - HitTestPoint(event.location())) { - Activate(); - } else { - LabelButton::OnMouseReleased(event); - } -} - -void MenuButton::OnMouseEntered(const ui::MouseEvent& event) { - if (pressed_lock_count_ == 0) // Ignore mouse movement if state is locked. - CustomButton::OnMouseEntered(event); -} - -void MenuButton::OnMouseExited(const ui::MouseEvent& event) { - if (pressed_lock_count_ == 0) // Ignore mouse movement if state is locked. - CustomButton::OnMouseExited(event); -} - -void MenuButton::OnMouseMoved(const ui::MouseEvent& event) { - if (pressed_lock_count_ == 0) // Ignore mouse movement if state is locked. - CustomButton::OnMouseMoved(event); -} - -void MenuButton::OnGestureEvent(ui::GestureEvent* event) { - if (state() != STATE_DISABLED && event->type() == ui::ET_GESTURE_TAP && - !Activate()) { - // When |Activate()| returns |false|, it means that a menu is shown and - // has handled the gesture event. So, there is no need to further process - // the gesture event here. - return; - } - LabelButton::OnGestureEvent(event); -} - -bool MenuButton::OnKeyPressed(const ui::KeyEvent& event) { - switch (event.key_code()) { - case ui::VKEY_SPACE: - // Alt-space on windows should show the window menu. - if (event.IsAltDown()) - break; - case ui::VKEY_RETURN: - case ui::VKEY_UP: - case ui::VKEY_DOWN: { - // WARNING: we may have been deleted by the time Activate returns. - Activate(); - // This is to prevent the keyboard event from being dispatched twice. If - // the keyboard event is not handled, we pass it to the default handler - // which dispatches the event back to us causing the menu to get displayed - // again. Return true to prevent this. - return true; - } - default: - break; - } - return false; -} - -bool MenuButton::OnKeyReleased(const ui::KeyEvent& event) { - // Override CustomButton's implementation, which presses the button when - // you press space and clicks it when you release space. For a MenuButton - // we always activate the menu on key press. - return false; -} - -void MenuButton::GetAccessibleState(ui::AXViewState* state) { - CustomButton::GetAccessibleState(state); - state->role = ui::AX_ROLE_POP_UP_BUTTON; - state->default_action = l10n_util::GetStringUTF16(IDS_APP_ACCACTION_PRESS); - state->AddStateFlag(ui::AX_STATE_HASPOPUP); -} - -void MenuButton::PaintMenuMarker(gfx::Canvas* canvas) { - gfx::Insets insets = GetInsets(); - - // Using the Views mirroring infrastructure incorrectly flips icon content. - // Instead, manually mirror the position of the down arrow. - gfx::Rect arrow_bounds(width() - insets.right() - - menu_marker_->width() - kMenuMarkerPaddingRight, - height() / 2 - menu_marker_->height() / 2, - menu_marker_->width(), - menu_marker_->height()); - arrow_bounds.set_x(GetMirroredXForRect(arrow_bounds)); - canvas->DrawImageInt(*menu_marker_, arrow_bounds.x(), arrow_bounds.y()); -} - -gfx::Rect MenuButton::GetChildAreaBounds() { - gfx::Size s = size(); - - if (show_menu_marker_) { - s.set_width(s.width() - menu_marker_->width() - kMenuMarkerPaddingLeft - - kMenuMarkerPaddingRight); - } - - return gfx::Rect(s); -} - -void MenuButton::IncrementPressedLocked() { - ++pressed_lock_count_; - SetState(STATE_PRESSED); -} - -void MenuButton::DecrementPressedLocked() { - --pressed_lock_count_; - DCHECK_GE(pressed_lock_count_, 0); - - // If this was the last lock, manually reset state to "normal". We set - // "normal" and not "hot" because the likelihood is that the mouse is now - // somewhere else (user clicked elsewhere on screen to close the menu or - // selected an item) and we will inevitably refresh the hot state in the event - // the mouse _is_ over the view. - if (pressed_lock_count_ == 0) - SetState(STATE_NORMAL); -} - -int MenuButton::GetMaximumScreenXCoordinate() { - if (!GetWidget()) { - NOTREACHED(); - return 0; - } - - gfx::Rect monitor_bounds = GetWidget()->GetWorkAreaBoundsInScreen(); - return monitor_bounds.right() - 1; -} - -} // namespace views
diff --git a/ui/views/controls/button/menu_button.h b/ui/views/controls/button/menu_button.h deleted file mode 100644 index a1baf05..0000000 --- a/ui/views/controls/button/menu_button.h +++ /dev/null
@@ -1,134 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_BUTTON_MENU_BUTTON_H_ -#define UI_VIEWS_CONTROLS_BUTTON_MENU_BUTTON_H_ - -#include <string> - -#include "base/memory/weak_ptr.h" -#include "base/strings/string16.h" -#include "base/time/time.h" -#include "ui/views/background.h" -#include "ui/views/controls/button/label_button.h" - -namespace views { - -class MenuButtonListener; - -//////////////////////////////////////////////////////////////////////////////// -// -// MenuButton -// -// A button that shows a menu when the left mouse button is pushed -// -//////////////////////////////////////////////////////////////////////////////// -class VIEWS_EXPORT MenuButton : public LabelButton { - public: - // A scoped lock for keeping the MenuButton in STATE_PRESSED e.g., while a - // menu is running. These are cumulative. - class VIEWS_EXPORT PressedLock { - public: - explicit PressedLock(MenuButton* menu_button); - ~PressedLock(); - - private: - base::WeakPtr<MenuButton> menu_button_; - - DISALLOW_COPY_AND_ASSIGN(PressedLock); - }; - - static const char kViewClassName[]; - - // How much padding to put on the left and right of the menu marker. - static const int kMenuMarkerPaddingLeft; - static const int kMenuMarkerPaddingRight; - - // Create a Button. - MenuButton(ButtonListener* listener, - const base::string16& text, - MenuButtonListener* menu_button_listener, - bool show_menu_marker); - virtual ~MenuButton(); - - bool show_menu_marker() const { return show_menu_marker_; } - void set_menu_marker(const gfx::ImageSkia* menu_marker) { - menu_marker_ = menu_marker; - } - const gfx::ImageSkia* menu_marker() const { return menu_marker_; } - - const gfx::Point& menu_offset() const { return menu_offset_; } - void set_menu_offset(int x, int y) { menu_offset_.SetPoint(x, y); } - - // Activate the button (called when the button is pressed). - virtual bool Activate(); - - // Overridden from View: - virtual gfx::Size GetPreferredSize() const override; - virtual const char* GetClassName() const override; - virtual void OnPaint(gfx::Canvas* canvas) override; - virtual bool OnMousePressed(const ui::MouseEvent& event) override; - virtual void OnMouseReleased(const ui::MouseEvent& event) override; - virtual void OnMouseEntered(const ui::MouseEvent& event) override; - virtual void OnMouseExited(const ui::MouseEvent& event) override; - virtual void OnMouseMoved(const ui::MouseEvent& event) override; - virtual void OnGestureEvent(ui::GestureEvent* event) override; - virtual bool OnKeyPressed(const ui::KeyEvent& event) override; - virtual bool OnKeyReleased(const ui::KeyEvent& event) override; - virtual void GetAccessibleState(ui::AXViewState* state) override; - - protected: - // Paint the menu marker image. - void PaintMenuMarker(gfx::Canvas* canvas); - - // Overridden from LabelButton: - virtual gfx::Rect GetChildAreaBounds() override; - - // Offset of the associated menu position. - gfx::Point menu_offset_; - - private: - friend class PressedLock; - - // Increment/decrement the number of "pressed" locks this button has, and - // set the state accordingly. - void IncrementPressedLocked(); - void DecrementPressedLocked(); - - // Compute the maximum X coordinate for the current screen. MenuButtons - // use this to make sure a menu is never shown off screen. - int GetMaximumScreenXCoordinate(); - - // We use a time object in order to keep track of when the menu was closed. - // The time is used for simulating menu behavior for the menu button; that - // is, if the menu is shown and the button is pressed, we need to close the - // menu. There is no clean way to get the second click event because the - // menu is displayed using a modal loop and, unlike regular menus in Windows, - // the button is not part of the displayed menu. - base::TimeTicks menu_closed_time_; - - // Our listener. Not owned. - MenuButtonListener* listener_; - - // Whether or not we're showing a drop marker. - bool show_menu_marker_; - - // The down arrow used to differentiate the menu button from normal buttons. - const gfx::ImageSkia* menu_marker_; - - // If non-null the destuctor sets this to true. This is set while the menu is - // showing and used to detect if the menu was deleted while running. - bool* destroyed_flag_; - - // The current number of "pressed" locks this button has. - int pressed_lock_count_; - - base::WeakPtrFactory<MenuButton> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(MenuButton); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_BUTTON_MENU_BUTTON_H_
diff --git a/ui/views/controls/button/menu_button_listener.h b/ui/views/controls/button/menu_button_listener.h deleted file mode 100644 index 5a20697..0000000 --- a/ui/views/controls/button/menu_button_listener.h +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_BUTTON_MENU_BUTTON_LISTENER_H_ -#define UI_VIEWS_CONTROLS_BUTTON_MENU_BUTTON_LISTENER_H_ - -#include "ui/views/views_export.h" - -namespace gfx { -class Point; -} - -namespace views { - -class View; - -// An interface implemented by an object to let it know that a menu button was -// clicked. -class VIEWS_EXPORT MenuButtonListener { - public: - virtual void OnMenuButtonClicked(View* source, const gfx::Point& point) = 0; - - protected: - virtual ~MenuButtonListener() {} -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_BUTTON_MENU_BUTTON_LISTENER_H_
diff --git a/ui/views/controls/button/menu_button_unittest.cc b/ui/views/controls/button/menu_button_unittest.cc deleted file mode 100644 index 3b153ad..0000000 --- a/ui/views/controls/button/menu_button_unittest.cc +++ /dev/null
@@ -1,233 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/button/menu_button.h" - -#include "base/memory/scoped_ptr.h" -#include "base/strings/utf_string_conversions.h" -#include "ui/events/test/event_generator.h" -#include "ui/views/controls/button/menu_button_listener.h" -#include "ui/views/test/views_test_base.h" - -using base::ASCIIToUTF16; - -namespace views { - -class MenuButtonTest : public ViewsTestBase { - public: - MenuButtonTest() : widget_(NULL), button_(NULL) {} - virtual ~MenuButtonTest() {} - - virtual void TearDown() override { - if (widget_ && !widget_->IsClosed()) - widget_->Close(); - - ViewsTestBase::TearDown(); - } - - Widget* widget() { return widget_; } - MenuButton* button() { return button_; } - - protected: - // Creates a MenuButton with no button listener. - void CreateMenuButtonWithNoListener() { - CreateMenuButton(NULL, NULL); - } - - // Creates a MenuButton with a ButtonListener. In this case, the MenuButton - // acts like a regular button. - void CreateMenuButtonWithButtonListener(ButtonListener* button_listener) { - CreateMenuButton(button_listener, NULL); - } - - // Creates a MenuButton with a MenuButtonListener. In this case, when the - // MenuButton is pushed, it notifies the MenuButtonListener to open a - // drop-down menu. - void CreateMenuButtonWithMenuButtonListener( - MenuButtonListener* menu_button_listener) { - CreateMenuButton(NULL, menu_button_listener); - } - - private: - void CreateMenuButton(ButtonListener* button_listener, - MenuButtonListener* menu_button_listener) { - CreateWidget(); - - const base::string16 label(ASCIIToUTF16("button")); - button_ = - new MenuButton(button_listener, label, menu_button_listener, false); - button_->SetBoundsRect(gfx::Rect(0, 0, 200, 20)); - widget_->SetContentsView(button_); - - widget_->Show(); - } - - void CreateWidget() { - DCHECK(!widget_); - - widget_ = new Widget; - Widget::InitParams params = - CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); - params.bounds = gfx::Rect(0, 0, 200, 200); - widget_->Init(params); - } - - Widget* widget_; - MenuButton* button_; -}; - -class TestButtonListener : public ButtonListener { - public: - TestButtonListener() - : last_sender_(NULL), - last_sender_state_(Button::STATE_NORMAL), - last_event_type_(ui::ET_UNKNOWN) {} - virtual ~TestButtonListener() {} - - virtual void ButtonPressed(Button* sender, const ui::Event& event) override { - last_sender_ = sender; - CustomButton* custom_button = CustomButton::AsCustomButton(sender); - DCHECK(custom_button); - last_sender_state_ = custom_button->state(); - last_event_type_ = event.type(); - } - - Button* last_sender() { return last_sender_; } - Button::ButtonState last_sender_state() { return last_sender_state_; } - ui::EventType last_event_type() { return last_event_type_; } - - private: - Button* last_sender_; - Button::ButtonState last_sender_state_; - ui::EventType last_event_type_; - - DISALLOW_COPY_AND_ASSIGN(TestButtonListener); -}; - -class TestMenuButtonListener : public MenuButtonListener { - public: - TestMenuButtonListener() {} - virtual ~TestMenuButtonListener() {} - - virtual void OnMenuButtonClicked(View* source, - const gfx::Point& /*point*/) override { - last_source_ = source; - CustomButton* custom_button = CustomButton::AsCustomButton(source); - DCHECK(custom_button); - last_source_state_ = custom_button->state(); - } - - View* last_source() { return last_source_; } - Button::ButtonState last_source_state() { return last_source_state_; } - - private: - View* last_source_; - Button::ButtonState last_source_state_; -}; - -// Tests if the listener is notified correctly, when a mouse click happens on a -// MenuButton that has a regular ButtonListener. -TEST_F(MenuButtonTest, ActivateNonDropDownOnMouseClick) { - scoped_ptr<TestButtonListener> button_listener(new TestButtonListener); - CreateMenuButtonWithButtonListener(button_listener.get()); - - ui::test::EventGenerator generator(GetContext(), widget()->GetNativeWindow()); - - generator.set_current_location(gfx::Point(10, 10)); - generator.ClickLeftButton(); - - // Check that MenuButton has notified the listener on mouse-released event, - // while it was in hovered state. - EXPECT_EQ(button(), button_listener->last_sender()); - EXPECT_EQ(ui::ET_MOUSE_RELEASED, button_listener->last_event_type()); - EXPECT_EQ(Button::STATE_HOVERED, button_listener->last_sender_state()); -} - -// Tests if the listener is notified correctly when a gesture tap happens on a -// MenuButton that has a regular ButtonListener. -TEST_F(MenuButtonTest, ActivateNonDropDownOnGestureTap) { - scoped_ptr<TestButtonListener> button_listener(new TestButtonListener); - CreateMenuButtonWithButtonListener(button_listener.get()); - - ui::test::EventGenerator generator(GetContext(), widget()->GetNativeWindow()); - generator.GestureTapAt(gfx::Point(10, 10)); - - // Check that MenuButton has notified the listener on gesture tap event, while - // it was in hovered state. - EXPECT_EQ(button(), button_listener->last_sender()); - EXPECT_EQ(ui::ET_GESTURE_TAP, button_listener->last_event_type()); - EXPECT_EQ(Button::STATE_HOVERED, button_listener->last_sender_state()); -} - -// Tests if the listener is notified correctly when a mouse click happens on a -// MenuButton that has a MenuButtonListener. -TEST_F(MenuButtonTest, ActivateDropDownOnMouseClick) { - scoped_ptr<TestMenuButtonListener> menu_button_listener( - new TestMenuButtonListener); - CreateMenuButtonWithMenuButtonListener(menu_button_listener.get()); - - ui::test::EventGenerator generator(GetContext(), widget()->GetNativeWindow()); - - generator.set_current_location(gfx::Point(10, 10)); - generator.ClickLeftButton(); - - // Check that MenuButton has notified the listener, while it was in pressed - // state. - EXPECT_EQ(button(), menu_button_listener->last_source()); - EXPECT_EQ(Button::STATE_PRESSED, menu_button_listener->last_source_state()); -} - -// Tests if the listener is notified correctly when a gesture tap happens on a -// MenuButton that has a MenuButtonListener. -TEST_F(MenuButtonTest, ActivateDropDownOnGestureTap) { - scoped_ptr<TestMenuButtonListener> menu_button_listener( - new TestMenuButtonListener); - CreateMenuButtonWithMenuButtonListener(menu_button_listener.get()); - - ui::test::EventGenerator generator(GetContext(), widget()->GetNativeWindow()); - generator.GestureTapAt(gfx::Point(10, 10)); - - // Check that MenuButton has notified the listener, while it was in pressed - // state. - EXPECT_EQ(button(), menu_button_listener->last_source()); - EXPECT_EQ(Button::STATE_PRESSED, menu_button_listener->last_source_state()); -} - -// Test that the MenuButton stays pressed while there are any PressedLocks. -TEST_F(MenuButtonTest, MenuButtonPressedLock) { - CreateMenuButtonWithNoListener(); - - // Move the mouse over the button; the button should be in a hovered state. - ui::test::EventGenerator generator(GetContext(), widget()->GetNativeWindow()); - generator.MoveMouseTo(gfx::Point(10, 10)); - EXPECT_EQ(Button::STATE_HOVERED, button()->state()); - - // Introduce a PressedLock, which should make the button pressed. - scoped_ptr<MenuButton::PressedLock> pressed_lock1( - new MenuButton::PressedLock(button())); - EXPECT_EQ(Button::STATE_PRESSED, button()->state()); - - // Even if we move the mouse outside of the button, it should remain pressed. - generator.MoveMouseTo(gfx::Point(300, 10)); - EXPECT_EQ(Button::STATE_PRESSED, button()->state()); - - // Creating a new lock should obviously keep the button pressed. - scoped_ptr<MenuButton::PressedLock> pressed_lock2( - new MenuButton::PressedLock(button())); - EXPECT_EQ(Button::STATE_PRESSED, button()->state()); - - // The button should remain pressed while any locks are active. - pressed_lock1.reset(); - EXPECT_EQ(Button::STATE_PRESSED, button()->state()); - - // Reseting the final lock should return the button's state to normal... - pressed_lock2.reset(); - EXPECT_EQ(Button::STATE_NORMAL, button()->state()); - - // ...And it should respond to mouse movement again. - generator.MoveMouseTo(gfx::Point(10, 10)); - EXPECT_EQ(Button::STATE_HOVERED, button()->state()); -} - -} // namespace views
diff --git a/ui/views/controls/button/radio_button.cc b/ui/views/controls/button/radio_button.cc deleted file mode 100644 index e92b06a..0000000 --- a/ui/views/controls/button/radio_button.cc +++ /dev/null
@@ -1,143 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/button/radio_button.h" - -#include "base/logging.h" -#include "ui/accessibility/ax_view_state.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/resources/grit/ui_resources.h" -#include "ui/views/widget/widget.h" - -namespace views { - -// static -const char RadioButton::kViewClassName[] = "RadioButton"; - -RadioButton::RadioButton(const base::string16& label, int group_id) - : Checkbox(label) { - SetGroup(group_id); - - ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); - - // Unchecked/Unfocused images. - SetCustomImage(false, false, STATE_NORMAL, - *rb.GetImageSkiaNamed(IDR_RADIO)); - SetCustomImage(false, false, STATE_HOVERED, - *rb.GetImageSkiaNamed(IDR_RADIO_HOVER)); - SetCustomImage(false, false, STATE_PRESSED, - *rb.GetImageSkiaNamed(IDR_RADIO_PRESSED)); - SetCustomImage(false, false, STATE_DISABLED, - *rb.GetImageSkiaNamed(IDR_RADIO_DISABLED)); - - // Checked/Unfocused images. - SetCustomImage(true, false, STATE_NORMAL, - *rb.GetImageSkiaNamed(IDR_RADIO_CHECKED)); - SetCustomImage(true, false, STATE_HOVERED, - *rb.GetImageSkiaNamed(IDR_RADIO_CHECKED_HOVER)); - SetCustomImage(true, false, STATE_PRESSED, - *rb.GetImageSkiaNamed(IDR_RADIO_CHECKED_PRESSED)); - SetCustomImage(true, false, STATE_DISABLED, - *rb.GetImageSkiaNamed(IDR_RADIO_CHECKED_DISABLED)); - - // Unchecked/Focused images. - SetCustomImage(false, true, STATE_NORMAL, - *rb.GetImageSkiaNamed(IDR_RADIO_FOCUSED)); - SetCustomImage(false, true, STATE_HOVERED, - *rb.GetImageSkiaNamed(IDR_RADIO_FOCUSED_HOVER)); - SetCustomImage(false, true, STATE_PRESSED, - *rb.GetImageSkiaNamed(IDR_RADIO_FOCUSED_PRESSED)); - - // Checked/Focused images. - SetCustomImage(true, true, STATE_NORMAL, - *rb.GetImageSkiaNamed(IDR_RADIO_FOCUSED_CHECKED)); - SetCustomImage(true, true, STATE_HOVERED, - *rb.GetImageSkiaNamed(IDR_RADIO_FOCUSED_CHECKED_HOVER)); - SetCustomImage(true, true, STATE_PRESSED, - *rb.GetImageSkiaNamed(IDR_RADIO_FOCUSED_CHECKED_PRESSED)); -} - -RadioButton::~RadioButton() { -} - -void RadioButton::SetChecked(bool checked) { - if (checked == RadioButton::checked()) - return; - if (checked) { - // We can't just get the root view here because sometimes the radio - // button isn't attached to a root view (e.g., if it's part of a tab page - // that is currently not active). - View* container = parent(); - while (container && container->parent()) - container = container->parent(); - if (container) { - Views other; - container->GetViewsInGroup(GetGroup(), &other); - for (Views::iterator i(other.begin()); i != other.end(); ++i) { - if (*i != this) { - if (strcmp((*i)->GetClassName(), kViewClassName)) { - NOTREACHED() << "radio-button-nt has same group as other non " - "radio-button-nt views."; - continue; - } - RadioButton* peer = static_cast<RadioButton*>(*i); - peer->SetChecked(false); - } - } - } - } - Checkbox::SetChecked(checked); -} - -const char* RadioButton::GetClassName() const { - return kViewClassName; -} - -void RadioButton::GetAccessibleState(ui::AXViewState* state) { - Checkbox::GetAccessibleState(state); - state->role = ui::AX_ROLE_RADIO_BUTTON; -} - -View* RadioButton::GetSelectedViewForGroup(int group) { - Views views; - GetWidget()->GetRootView()->GetViewsInGroup(group, &views); - if (views.empty()) - return NULL; - - for (Views::const_iterator i(views.begin()); i != views.end(); ++i) { - // REVIEW: why don't we check the runtime type like is done above? - RadioButton* radio_button = static_cast<RadioButton*>(*i); - if (radio_button->checked()) - return radio_button; - } - return NULL; -} - -bool RadioButton::IsGroupFocusTraversable() const { - // When focusing a radio button with tab/shift+tab, only the selected button - // from the group should be focused. - return false; -} - -void RadioButton::OnFocus() { - Checkbox::OnFocus(); - SetChecked(true); - ui::MouseEvent event(ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(), 0, 0); - LabelButton::NotifyClick(event); -} - -void RadioButton::NotifyClick(const ui::Event& event) { - // Set the checked state to true only if we are unchecked, since we can't - // be toggled on and off like a checkbox. - if (!checked()) - SetChecked(true); - RequestFocus(); - LabelButton::NotifyClick(event); -} - -ui::NativeTheme::Part RadioButton::GetThemePart() const { - return ui::NativeTheme::kRadio; -} - -} // namespace views
diff --git a/ui/views/controls/button/radio_button.h b/ui/views/controls/button/radio_button.h deleted file mode 100644 index b24e0be..0000000 --- a/ui/views/controls/button/radio_button.h +++ /dev/null
@@ -1,45 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_BUTTON_RADIO_BUTTON_H_ -#define UI_VIEWS_CONTROLS_BUTTON_RADIO_BUTTON_H_ - -#include "base/strings/string16.h" -#include "ui/views/controls/button/checkbox.h" - -namespace views { - -// A native themed class representing a radio button. This class does not use -// platform specific objects to replicate the native platforms looks and feel. -class VIEWS_EXPORT RadioButton : public Checkbox { - public: - // The button's class name. - static const char kViewClassName[]; - - RadioButton(const base::string16& label, int group_id); - virtual ~RadioButton(); - - // Overridden from View: - virtual const char* GetClassName() const override; - virtual void GetAccessibleState(ui::AXViewState* state) override; - virtual View* GetSelectedViewForGroup(int group) override; - virtual bool IsGroupFocusTraversable() const override; - virtual void OnFocus() override; - - // Overridden from Button: - virtual void NotifyClick(const ui::Event& event) override; - - // Overridden from LabelButton: - virtual ui::NativeTheme::Part GetThemePart() const override; - - // Overridden from Checkbox: - virtual void SetChecked(bool checked) override; - - private: - DISALLOW_COPY_AND_ASSIGN(RadioButton); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_BUTTON_RADIO_BUTTON_H_
diff --git a/ui/views/controls/combobox/combobox.cc b/ui/views/controls/combobox/combobox.cc deleted file mode 100644 index 22689c7..0000000 --- a/ui/views/controls/combobox/combobox.cc +++ /dev/null
@@ -1,868 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/combobox/combobox.h" - -#include "base/bind.h" -#include "base/logging.h" -#include "base/message_loop/message_loop_proxy.h" -#include "base/strings/utf_string_conversions.h" -#include "ui/accessibility/ax_view_state.h" -#include "ui/base/models/combobox_model.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/events/event.h" -#include "ui/events/keycodes/keyboard_codes.h" -#include "ui/gfx/animation/throb_animation.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/image/image.h" -#include "ui/gfx/scoped_canvas.h" -#include "ui/gfx/text_utils.h" -#include "ui/native_theme/common_theme.h" -#include "ui/native_theme/native_theme.h" -#include "ui/resources/grit/ui_resources.h" -#include "ui/views/background.h" -#include "ui/views/color_constants.h" -#include "ui/views/controls/button/custom_button.h" -#include "ui/views/controls/button/label_button.h" -#include "ui/views/controls/combobox/combobox_listener.h" -#include "ui/views/controls/focusable_border.h" -#include "ui/views/controls/menu/menu_item_view.h" -#include "ui/views/controls/menu/menu_runner.h" -#include "ui/views/controls/menu/menu_runner_handler.h" -#include "ui/views/controls/menu/submenu_view.h" -#include "ui/views/controls/prefix_selector.h" -#include "ui/views/controls/textfield/textfield.h" -#include "ui/views/ime/input_method.h" -#include "ui/views/mouse_constants.h" -#include "ui/views/painter.h" -#include "ui/views/widget/widget.h" - -namespace views { - -namespace { - -// Menu border widths -const int kMenuBorderWidthLeft = 1; -const int kMenuBorderWidthTop = 1; -const int kMenuBorderWidthRight = 1; - -// Limit how small a combobox can be. -const int kMinComboboxWidth = 25; - -// Size of the combobox arrow margins -const int kDisclosureArrowLeftPadding = 7; -const int kDisclosureArrowRightPadding = 7; -const int kDisclosureArrowButtonLeftPadding = 11; -const int kDisclosureArrowButtonRightPadding = 12; - -// Define the id of the first item in the menu (since it needs to be > 0) -const int kFirstMenuItemId = 1000; - -// Used to indicate that no item is currently selected by the user. -const int kNoSelection = -1; - -const int kBodyButtonImages[] = IMAGE_GRID(IDR_COMBOBOX_BUTTON); -const int kHoveredBodyButtonImages[] = IMAGE_GRID(IDR_COMBOBOX_BUTTON_H); -const int kPressedBodyButtonImages[] = IMAGE_GRID(IDR_COMBOBOX_BUTTON_P); -const int kFocusedBodyButtonImages[] = IMAGE_GRID(IDR_COMBOBOX_BUTTON_F); -const int kFocusedHoveredBodyButtonImages[] = - IMAGE_GRID(IDR_COMBOBOX_BUTTON_F_H); -const int kFocusedPressedBodyButtonImages[] = - IMAGE_GRID(IDR_COMBOBOX_BUTTON_F_P); - -#define MENU_IMAGE_GRID(x) { \ - x ## _MENU_TOP, x ## _MENU_CENTER, x ## _MENU_BOTTOM, } - -const int kMenuButtonImages[] = MENU_IMAGE_GRID(IDR_COMBOBOX_BUTTON); -const int kHoveredMenuButtonImages[] = MENU_IMAGE_GRID(IDR_COMBOBOX_BUTTON_H); -const int kPressedMenuButtonImages[] = MENU_IMAGE_GRID(IDR_COMBOBOX_BUTTON_P); -const int kFocusedMenuButtonImages[] = MENU_IMAGE_GRID(IDR_COMBOBOX_BUTTON_F); -const int kFocusedHoveredMenuButtonImages[] = - MENU_IMAGE_GRID(IDR_COMBOBOX_BUTTON_F_H); -const int kFocusedPressedMenuButtonImages[] = - MENU_IMAGE_GRID(IDR_COMBOBOX_BUTTON_F_P); - -#undef MENU_IMAGE_GRID - -// The transparent button which holds a button state but is not rendered. -class TransparentButton : public CustomButton { - public: - TransparentButton(ButtonListener* listener) - : CustomButton(listener) { - SetAnimationDuration(LabelButton::kHoverAnimationDurationMs); - } - virtual ~TransparentButton() {} - - virtual bool OnMousePressed(const ui::MouseEvent& mouse_event) override { - parent()->RequestFocus(); - return true; - } - - double GetAnimationValue() const { - return hover_animation_->GetCurrentValue(); - } - - private: - DISALLOW_COPY_AND_ASSIGN(TransparentButton); -}; - -// Returns the next or previous valid index (depending on |increment|'s value). -// Skips separator or disabled indices. Returns -1 if there is no valid adjacent -// index. -int GetAdjacentIndex(ui::ComboboxModel* model, int increment, int index) { - DCHECK(increment == -1 || increment == 1); - - index += increment; - while (index >= 0 && index < model->GetItemCount()) { - if (!model->IsItemSeparatorAt(index) || !model->IsItemEnabledAt(index)) - return index; - index += increment; - } - return kNoSelection; -} - -// Returns the image resource ids of an array for the body button. -// -// TODO(hajimehoshi): This function should return the images for the 'disabled' -// status. (crbug/270052) -const int* GetBodyButtonImageIds(bool focused, - Button::ButtonState state, - size_t* num) { - DCHECK(num); - *num = 9; - switch (state) { - case Button::STATE_DISABLED: - return focused ? kFocusedBodyButtonImages : kBodyButtonImages; - case Button::STATE_NORMAL: - return focused ? kFocusedBodyButtonImages : kBodyButtonImages; - case Button::STATE_HOVERED: - return focused ? - kFocusedHoveredBodyButtonImages : kHoveredBodyButtonImages; - case Button::STATE_PRESSED: - return focused ? - kFocusedPressedBodyButtonImages : kPressedBodyButtonImages; - default: - NOTREACHED(); - } - return NULL; -} - -// Returns the image resource ids of an array for the menu button. -const int* GetMenuButtonImageIds(bool focused, - Button::ButtonState state, - size_t* num) { - DCHECK(num); - *num = 3; - switch (state) { - case Button::STATE_DISABLED: - return focused ? kFocusedMenuButtonImages : kMenuButtonImages; - case Button::STATE_NORMAL: - return focused ? kFocusedMenuButtonImages : kMenuButtonImages; - case Button::STATE_HOVERED: - return focused ? - kFocusedHoveredMenuButtonImages : kHoveredMenuButtonImages; - case Button::STATE_PRESSED: - return focused ? - kFocusedPressedMenuButtonImages : kPressedMenuButtonImages; - default: - NOTREACHED(); - } - return NULL; -} - -// Returns the images for the menu buttons. -std::vector<const gfx::ImageSkia*> GetMenuButtonImages( - bool focused, - Button::ButtonState state) { - const int* ids; - size_t num_ids; - ids = GetMenuButtonImageIds(focused, state, &num_ids); - std::vector<const gfx::ImageSkia*> images; - images.reserve(num_ids); - ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); - for (size_t i = 0; i < num_ids; i++) - images.push_back(rb.GetImageSkiaNamed(ids[i])); - return images; -} - -// Paints three images in a column at the given location. The center image is -// stretched so as to fit the given height. -void PaintImagesVertically(gfx::Canvas* canvas, - const gfx::ImageSkia& top_image, - const gfx::ImageSkia& center_image, - const gfx::ImageSkia& bottom_image, - int x, int y, int width, int height) { - canvas->DrawImageInt(top_image, - 0, 0, top_image.width(), top_image.height(), - x, y, width, top_image.height(), false); - y += top_image.height(); - int center_height = height - top_image.height() - bottom_image.height(); - canvas->DrawImageInt(center_image, - 0, 0, center_image.width(), center_image.height(), - x, y, width, center_height, false); - y += center_height; - canvas->DrawImageInt(bottom_image, - 0, 0, bottom_image.width(), bottom_image.height(), - x, y, width, bottom_image.height(), false); -} - -// Paints the arrow button. -void PaintArrowButton( - gfx::Canvas* canvas, - const std::vector<const gfx::ImageSkia*>& arrow_button_images, - int x, int height) { - PaintImagesVertically(canvas, - *arrow_button_images[0], - *arrow_button_images[1], - *arrow_button_images[2], - x, 0, arrow_button_images[0]->width(), height); -} - -} // namespace - -// static -const char Combobox::kViewClassName[] = "views/Combobox"; - -//////////////////////////////////////////////////////////////////////////////// -// Combobox, public: - -Combobox::Combobox(ui::ComboboxModel* model) - : model_(model), - style_(STYLE_NORMAL), - listener_(NULL), - selected_index_(model_->GetDefaultIndex()), - invalid_(false), - menu_(NULL), - dropdown_open_(false), - text_button_(new TransparentButton(this)), - arrow_button_(new TransparentButton(this)), - weak_ptr_factory_(this) { - model_->AddObserver(this); - UpdateFromModel(); - SetFocusable(true); - UpdateBorder(); - - // Initialize the button images. - Button::ButtonState button_states[] = { - Button::STATE_DISABLED, - Button::STATE_NORMAL, - Button::STATE_HOVERED, - Button::STATE_PRESSED, - }; - for (int i = 0; i < 2; i++) { - for (size_t state_index = 0; state_index < arraysize(button_states); - state_index++) { - Button::ButtonState state = button_states[state_index]; - size_t num; - bool focused = !!i; - const int* ids = GetBodyButtonImageIds(focused, state, &num); - body_button_painters_[focused][state].reset( - Painter::CreateImageGridPainter(ids)); - menu_button_images_[focused][state] = GetMenuButtonImages(focused, state); - } - } - - text_button_->SetVisible(true); - arrow_button_->SetVisible(true); - text_button_->SetFocusable(false); - arrow_button_->SetFocusable(false); - AddChildView(text_button_); - AddChildView(arrow_button_); -} - -Combobox::~Combobox() { - model_->RemoveObserver(this); -} - -// static -const gfx::FontList& Combobox::GetFontList() { - ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); - return rb.GetFontList(ui::ResourceBundle::BaseFont); -} - -void Combobox::SetStyle(Style style) { - if (style_ == style) - return; - - style_ = style; - if (style_ == STYLE_ACTION) - selected_index_ = 0; - - UpdateBorder(); - UpdateFromModel(); - PreferredSizeChanged(); -} - -void Combobox::ModelChanged() { - selected_index_ = std::min(0, model_->GetItemCount()); - UpdateFromModel(); - PreferredSizeChanged(); -} - -void Combobox::SetSelectedIndex(int index) { - if (style_ == STYLE_ACTION) - return; - - selected_index_ = index; - SchedulePaint(); -} - -bool Combobox::SelectValue(const base::string16& value) { - if (style_ == STYLE_ACTION) - return false; - - for (int i = 0; i < model()->GetItemCount(); ++i) { - if (value == model()->GetItemAt(i)) { - SetSelectedIndex(i); - return true; - } - } - return false; -} - -void Combobox::SetAccessibleName(const base::string16& name) { - accessible_name_ = name; -} - -void Combobox::SetInvalid(bool invalid) { - if (invalid == invalid_) - return; - - invalid_ = invalid; - - UpdateBorder(); - SchedulePaint(); -} - -ui::TextInputClient* Combobox::GetTextInputClient() { - if (!selector_) - selector_.reset(new PrefixSelector(this)); - return selector_.get(); -} - -void Combobox::Layout() { - PrefixDelegate::Layout(); - - gfx::Insets insets = GetInsets(); - int text_button_width = 0; - int arrow_button_width = 0; - - switch (style_) { - case STYLE_NORMAL: { - arrow_button_width = width(); - break; - } - case STYLE_ACTION: { - arrow_button_width = GetDisclosureArrowLeftPadding() + - ArrowSize().width() + - GetDisclosureArrowRightPadding(); - text_button_width = width() - arrow_button_width; - break; - } - } - - int arrow_button_x = std::max(0, text_button_width); - text_button_->SetBounds(0, 0, std::max(0, text_button_width), height()); - arrow_button_->SetBounds(arrow_button_x, 0, arrow_button_width, height()); -} - -bool Combobox::IsItemChecked(int id) const { - return false; -} - -bool Combobox::IsCommandEnabled(int id) const { - return model()->IsItemEnabledAt(MenuCommandToIndex(id)); -} - -void Combobox::ExecuteCommand(int id) { - selected_index_ = MenuCommandToIndex(id); - OnPerformAction(); -} - -bool Combobox::GetAccelerator(int id, ui::Accelerator* accel) const { - return false; -} - -int Combobox::GetRowCount() { - return model()->GetItemCount(); -} - -int Combobox::GetSelectedRow() { - return selected_index_; -} - -void Combobox::SetSelectedRow(int row) { - int prev_index = selected_index_; - SetSelectedIndex(row); - if (selected_index_ != prev_index) - OnPerformAction(); -} - -base::string16 Combobox::GetTextForRow(int row) { - return model()->IsItemSeparatorAt(row) ? base::string16() : - model()->GetItemAt(row); -} - -//////////////////////////////////////////////////////////////////////////////// -// Combobox, View overrides: - -gfx::Size Combobox::GetPreferredSize() const { - // The preferred size will drive the local bounds which in turn is used to set - // the minimum width for the dropdown list. - gfx::Insets insets = GetInsets(); - insets += gfx::Insets(Textfield::kTextPadding, - Textfield::kTextPadding, - Textfield::kTextPadding, - Textfield::kTextPadding); - int total_width = std::max(kMinComboboxWidth, content_size_.width()) + - insets.width() + GetDisclosureArrowLeftPadding() + - ArrowSize().width() + GetDisclosureArrowRightPadding(); - return gfx::Size(total_width, content_size_.height() + insets.height()); -} - -const char* Combobox::GetClassName() const { - return kViewClassName; -} - -bool Combobox::SkipDefaultKeyEventProcessing(const ui::KeyEvent& e) { - // Escape should close the drop down list when it is active, not host UI. - if (e.key_code() != ui::VKEY_ESCAPE || - e.IsShiftDown() || e.IsControlDown() || e.IsAltDown()) { - return false; - } - return dropdown_open_; -} - -bool Combobox::OnKeyPressed(const ui::KeyEvent& e) { - // TODO(oshima): handle IME. - DCHECK_EQ(e.type(), ui::ET_KEY_PRESSED); - - DCHECK_GE(selected_index_, 0); - DCHECK_LT(selected_index_, model()->GetItemCount()); - if (selected_index_ < 0 || selected_index_ > model()->GetItemCount()) - selected_index_ = 0; - - bool show_menu = false; - int new_index = kNoSelection; - switch (e.key_code()) { - // Show the menu on F4 without modifiers. - case ui::VKEY_F4: - if (e.IsAltDown() || e.IsAltGrDown() || e.IsControlDown()) - return false; - show_menu = true; - break; - - // Move to the next item if any, or show the menu on Alt+Down like Windows. - case ui::VKEY_DOWN: - if (e.IsAltDown()) - show_menu = true; - else - new_index = GetAdjacentIndex(model(), 1, selected_index_); - break; - - // Move to the end of the list. - case ui::VKEY_END: - case ui::VKEY_NEXT: // Page down. - new_index = GetAdjacentIndex(model(), -1, model()->GetItemCount()); - break; - - // Move to the beginning of the list. - case ui::VKEY_HOME: - case ui::VKEY_PRIOR: // Page up. - new_index = GetAdjacentIndex(model(), 1, -1); - break; - - // Move to the previous item if any. - case ui::VKEY_UP: - new_index = GetAdjacentIndex(model(), -1, selected_index_); - break; - - // Click the button only when the button style mode. - case ui::VKEY_SPACE: - if (style_ == STYLE_ACTION) { - // When pressing space, the click event will be raised after the key is - // released. - text_button_->SetState(Button::STATE_PRESSED); - } else { - return false; - } - break; - - // Click the button only when the button style mode. - case ui::VKEY_RETURN: - if (style_ != STYLE_ACTION) - return false; - OnPerformAction(); - break; - - default: - return false; - } - - if (show_menu) { - UpdateFromModel(); - ShowDropDownMenu(ui::MENU_SOURCE_KEYBOARD); - } else if (new_index != selected_index_ && new_index != kNoSelection && - style_ != STYLE_ACTION) { - DCHECK(!model()->IsItemSeparatorAt(new_index)); - selected_index_ = new_index; - OnPerformAction(); - } - - return true; -} - -bool Combobox::OnKeyReleased(const ui::KeyEvent& e) { - if (style_ != STYLE_ACTION) - return false; // crbug.com/127520 - - if (e.key_code() == ui::VKEY_SPACE && style_ == STYLE_ACTION) - OnPerformAction(); - - return false; -} - -void Combobox::OnPaint(gfx::Canvas* canvas) { - switch (style_) { - case STYLE_NORMAL: { - OnPaintBackground(canvas); - PaintText(canvas); - OnPaintBorder(canvas); - break; - } - case STYLE_ACTION: { - PaintButtons(canvas); - PaintText(canvas); - break; - } - } -} - -void Combobox::OnFocus() { - GetInputMethod()->OnFocus(); - View::OnFocus(); - // Border renders differently when focused. - SchedulePaint(); -} - -void Combobox::OnBlur() { - GetInputMethod()->OnBlur(); - if (selector_) - selector_->OnViewBlur(); - // Border renders differently when focused. - SchedulePaint(); -} - -void Combobox::GetAccessibleState(ui::AXViewState* state) { - state->role = ui::AX_ROLE_COMBO_BOX; - state->name = accessible_name_; - state->value = model_->GetItemAt(selected_index_); - state->index = selected_index_; - state->count = model_->GetItemCount(); -} - -void Combobox::OnComboboxModelChanged(ui::ComboboxModel* model) { - DCHECK_EQ(model, model_); - ModelChanged(); -} - -void Combobox::ButtonPressed(Button* sender, const ui::Event& event) { - if (!enabled()) - return; - - RequestFocus(); - - if (sender == text_button_) { - OnPerformAction(); - } else { - DCHECK_EQ(arrow_button_, sender); - // TODO(hajimehoshi): Fix the problem that the arrow button blinks when - // cliking this while the dropdown menu is opened. - const base::TimeDelta delta = base::Time::Now() - closed_time_; - if (delta.InMilliseconds() <= kMinimumMsBetweenButtonClicks) - return; - - ui::MenuSourceType source_type = ui::MENU_SOURCE_MOUSE; - if (event.IsKeyEvent()) - source_type = ui::MENU_SOURCE_KEYBOARD; - else if (event.IsGestureEvent() || event.IsTouchEvent()) - source_type = ui::MENU_SOURCE_TOUCH; - ShowDropDownMenu(source_type); - } -} - -void Combobox::UpdateFromModel() { - const gfx::FontList& font_list = Combobox::GetFontList(); - - menu_ = new MenuItemView(this); - // MenuRunner owns |menu_|. - dropdown_list_menu_runner_.reset(new MenuRunner(menu_, MenuRunner::COMBOBOX)); - - int num_items = model()->GetItemCount(); - int width = 0; - bool text_item_appended = false; - for (int i = 0; i < num_items; ++i) { - // When STYLE_ACTION is used, the first item and the following separators - // are not added to the dropdown menu. It is assumed that the first item is - // always selected and rendered on the top of the action button. - if (model()->IsItemSeparatorAt(i)) { - if (text_item_appended || style_ != STYLE_ACTION) - menu_->AppendSeparator(); - continue; - } - - base::string16 text = model()->GetItemAt(i); - - // Inserting the Unicode formatting characters if necessary so that the - // text is displayed correctly in right-to-left UIs. - base::i18n::AdjustStringForLocaleDirection(&text); - - if (style_ != STYLE_ACTION || i > 0) { - menu_->AppendMenuItem(i + kFirstMenuItemId, text, MenuItemView::NORMAL); - text_item_appended = true; - } - - if (style_ != STYLE_ACTION || i == selected_index_) - width = std::max(width, gfx::GetStringWidth(text, font_list)); - } - - content_size_.SetSize(width, font_list.GetHeight()); -} - -void Combobox::UpdateBorder() { - scoped_ptr<FocusableBorder> border(new FocusableBorder()); - if (style_ == STYLE_ACTION) - border->SetInsets(5, 10, 5, 10); - if (invalid_) - border->SetColor(kWarningColor); - SetBorder(border.Pass()); -} - -void Combobox::AdjustBoundsForRTLUI(gfx::Rect* rect) const { - rect->set_x(GetMirroredXForRect(*rect)); -} - -void Combobox::PaintText(gfx::Canvas* canvas) { - gfx::Insets insets = GetInsets(); - insets += gfx::Insets(0, Textfield::kTextPadding, 0, Textfield::kTextPadding); - - gfx::ScopedCanvas scoped_canvas(canvas); - canvas->ClipRect(GetContentsBounds()); - - int x = insets.left(); - int y = insets.top(); - int text_height = height() - insets.height(); - SkColor text_color = GetNativeTheme()->GetSystemColor( - ui::NativeTheme::kColorId_LabelEnabledColor); - - DCHECK_GE(selected_index_, 0); - DCHECK_LT(selected_index_, model()->GetItemCount()); - if (selected_index_ < 0 || selected_index_ > model()->GetItemCount()) - selected_index_ = 0; - base::string16 text = model()->GetItemAt(selected_index_); - - gfx::Size arrow_size = ArrowSize(); - int disclosure_arrow_offset = width() - arrow_size.width() - - GetDisclosureArrowLeftPadding() - GetDisclosureArrowRightPadding(); - - const gfx::FontList& font_list = Combobox::GetFontList(); - int text_width = gfx::GetStringWidth(text, font_list); - if ((text_width + insets.width()) > disclosure_arrow_offset) - text_width = disclosure_arrow_offset - insets.width(); - - gfx::Rect text_bounds(x, y, text_width, text_height); - AdjustBoundsForRTLUI(&text_bounds); - canvas->DrawStringRect(text, font_list, text_color, text_bounds); - - int arrow_x = disclosure_arrow_offset + GetDisclosureArrowLeftPadding(); - gfx::Rect arrow_bounds(arrow_x, - height() / 2 - arrow_size.height() / 2, - arrow_size.width(), - arrow_size.height()); - AdjustBoundsForRTLUI(&arrow_bounds); - - // TODO(estade): hack alert! Remove this direct call into CommonTheme. For now - // STYLE_ACTION isn't properly themed so we have to override the NativeTheme - // behavior. See crbug.com/384071 - if (style_ == STYLE_ACTION) { - ui::CommonThemePaintComboboxArrow(canvas->sk_canvas(), arrow_bounds); - } else { - ui::NativeTheme::ExtraParams ignored; - GetNativeTheme()->Paint(canvas->sk_canvas(), - ui::NativeTheme::kComboboxArrow, - ui::NativeTheme::kNormal, - arrow_bounds, - ignored); - } -} - -void Combobox::PaintButtons(gfx::Canvas* canvas) { - DCHECK(style_ == STYLE_ACTION); - - gfx::ScopedCanvas scoped_canvas(canvas); - if (base::i18n::IsRTL()) { - canvas->Translate(gfx::Vector2d(width(), 0)); - canvas->Scale(-1, 1); - } - - bool focused = HasFocus(); - const std::vector<const gfx::ImageSkia*>& arrow_button_images = - menu_button_images_[focused][ - arrow_button_->state() == Button::STATE_HOVERED ? - Button::STATE_NORMAL : arrow_button_->state()]; - - int text_button_hover_alpha = - text_button_->state() == Button::STATE_PRESSED ? 0 : - static_cast<int>(static_cast<TransparentButton*>(text_button_)-> - GetAnimationValue() * 255); - if (text_button_hover_alpha < 255) { - canvas->SaveLayerAlpha(255 - text_button_hover_alpha); - Painter* text_button_painter = - body_button_painters_[focused][ - text_button_->state() == Button::STATE_HOVERED ? - Button::STATE_NORMAL : text_button_->state()].get(); - Painter::PaintPainterAt(canvas, text_button_painter, - gfx::Rect(0, 0, text_button_->width(), height())); - canvas->Restore(); - } - if (0 < text_button_hover_alpha) { - canvas->SaveLayerAlpha(text_button_hover_alpha); - Painter* text_button_hovered_painter = - body_button_painters_[focused][Button::STATE_HOVERED].get(); - Painter::PaintPainterAt(canvas, text_button_hovered_painter, - gfx::Rect(0, 0, text_button_->width(), height())); - canvas->Restore(); - } - - int arrow_button_hover_alpha = - arrow_button_->state() == Button::STATE_PRESSED ? 0 : - static_cast<int>(static_cast<TransparentButton*>(arrow_button_)-> - GetAnimationValue() * 255); - if (arrow_button_hover_alpha < 255) { - canvas->SaveLayerAlpha(255 - arrow_button_hover_alpha); - PaintArrowButton(canvas, arrow_button_images, arrow_button_->x(), height()); - canvas->Restore(); - } - if (0 < arrow_button_hover_alpha) { - canvas->SaveLayerAlpha(arrow_button_hover_alpha); - const std::vector<const gfx::ImageSkia*>& arrow_button_hovered_images = - menu_button_images_[focused][Button::STATE_HOVERED]; - PaintArrowButton(canvas, arrow_button_hovered_images, - arrow_button_->x(), height()); - canvas->Restore(); - } -} - -void Combobox::ShowDropDownMenu(ui::MenuSourceType source_type) { - if (!dropdown_list_menu_runner_.get()) - UpdateFromModel(); - - // Extend the menu to the width of the combobox. - SubmenuView* submenu = menu_->CreateSubmenu(); - submenu->set_minimum_preferred_width( - size().width() - (kMenuBorderWidthLeft + kMenuBorderWidthRight)); - - gfx::Rect lb = GetLocalBounds(); - gfx::Point menu_position(lb.origin()); - - if (style_ == STYLE_NORMAL) { - // Inset the menu's requested position so the border of the menu lines up - // with the border of the combobox. - menu_position.set_x(menu_position.x() + kMenuBorderWidthLeft); - menu_position.set_y(menu_position.y() + kMenuBorderWidthTop); - } - lb.set_width(lb.width() - (kMenuBorderWidthLeft + kMenuBorderWidthRight)); - - View::ConvertPointToScreen(this, &menu_position); - if (menu_position.x() < 0) - menu_position.set_x(0); - - gfx::Rect bounds(menu_position, lb.size()); - - Button::ButtonState original_state = Button::STATE_NORMAL; - if (arrow_button_) { - original_state = arrow_button_->state(); - arrow_button_->SetState(Button::STATE_PRESSED); - } - dropdown_open_ = true; - MenuAnchorPosition anchor_position = - style_ == STYLE_ACTION ? MENU_ANCHOR_TOPRIGHT : MENU_ANCHOR_TOPLEFT; - if (dropdown_list_menu_runner_->RunMenuAt( - GetWidget(), NULL, bounds, anchor_position, source_type) == - MenuRunner::MENU_DELETED) { - return; - } - dropdown_open_ = false; - if (arrow_button_) - arrow_button_->SetState(original_state); - closed_time_ = base::Time::Now(); - - // Need to explicitly clear mouse handler so that events get sent - // properly after the menu finishes running. If we don't do this, then - // the first click to other parts of the UI is eaten. - SetMouseHandler(NULL); -} - -void Combobox::OnPerformAction() { - NotifyAccessibilityEvent(ui::AX_EVENT_VALUE_CHANGED, false); - SchedulePaint(); - - // This combobox may be deleted by the listener. - base::WeakPtr<Combobox> weak_ptr = weak_ptr_factory_.GetWeakPtr(); - if (listener_) - listener_->OnPerformAction(this); - - if (weak_ptr && style_ == STYLE_ACTION) - selected_index_ = 0; -} - -int Combobox::MenuCommandToIndex(int menu_command_id) const { - // (note that the id received is offset by kFirstMenuItemId) - // Revert menu ID offset to map back to combobox model. - int index = menu_command_id - kFirstMenuItemId; - DCHECK_LT(index, model()->GetItemCount()); - return index; -} - -int Combobox::GetDisclosureArrowLeftPadding() const { - switch (style_) { - case STYLE_NORMAL: - return kDisclosureArrowLeftPadding; - case STYLE_ACTION: - return kDisclosureArrowButtonLeftPadding; - } - NOTREACHED(); - return 0; -} - -int Combobox::GetDisclosureArrowRightPadding() const { - switch (style_) { - case STYLE_NORMAL: - return kDisclosureArrowRightPadding; - case STYLE_ACTION: - return kDisclosureArrowButtonRightPadding; - } - NOTREACHED(); - return 0; -} - -gfx::Size Combobox::ArrowSize() const { -#if defined(OS_LINUX) && !defined(OS_CHROMEOS) - // TODO(estade): hack alert! This should always use GetNativeTheme(). For now - // STYLE_ACTION isn't properly themed so we have to override the NativeTheme - // behavior. See crbug.com/384071 - const ui::NativeTheme* native_theme_for_arrow = style_ == STYLE_ACTION ? - ui::NativeTheme::instance() : - GetNativeTheme(); -#else - const ui::NativeTheme* native_theme_for_arrow = GetNativeTheme(); -#endif - - ui::NativeTheme::ExtraParams ignored; - return native_theme_for_arrow->GetPartSize(ui::NativeTheme::kComboboxArrow, - ui::NativeTheme::kNormal, - ignored); -} - -} // namespace views
diff --git a/ui/views/controls/combobox/combobox.h b/ui/views/controls/combobox/combobox.h deleted file mode 100644 index aabb476..0000000 --- a/ui/views/controls/combobox/combobox.h +++ /dev/null
@@ -1,233 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_COMBOBOX_COMBOBOX_H_ -#define UI_VIEWS_CONTROLS_COMBOBOX_COMBOBOX_H_ - -#include <string> - -#include "base/memory/weak_ptr.h" -#include "base/time/time.h" -#include "ui/base/models/combobox_model_observer.h" -#include "ui/gfx/animation/animation_delegate.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/views/controls/button/button.h" -#include "ui/views/controls/menu/menu_delegate.h" -#include "ui/views/controls/prefix_delegate.h" - -namespace gfx { -class FontList; -class SlideAnimation; -} - -namespace ui { -class ComboboxModel; -} - -namespace views { - -class ComboboxListener; -class ComboboxMenuRunner; -class CustomButton; -class FocusableBorder; -class MenuRunner; -class MenuRunnerHandler; -class Painter; -class PrefixSelector; - -// A non-editable combobox (aka a drop-down list or selector). -// Combobox has two distinct parts, the drop down arrow and the text. Combobox -// offers two distinct behaviors: -// * STYLE_NORMAL: typical combobox, clicking on the text and/or button shows -// the drop down, arrow keys change selection, selected index can be changed by -// the user to something other than the first item. -// * STYLE_ACTION: clicking on the text notifies the listener. The menu can be -// shown only by clicking on the arrow. The selected index is always reverted to -// 0 after the listener is notified. -class VIEWS_EXPORT Combobox : public MenuDelegate, - public PrefixDelegate, - public ui::ComboboxModelObserver, - public ButtonListener { - public: - // The style of the combobox. - enum Style { - STYLE_NORMAL, - STYLE_ACTION, - }; - - // The combobox's class name. - static const char kViewClassName[]; - - // |model| is not owned by the combobox. - explicit Combobox(ui::ComboboxModel* model); - virtual ~Combobox(); - - static const gfx::FontList& GetFontList(); - - // Sets the listener which will be called when a selection has been made. - void set_listener(ComboboxListener* listener) { listener_ = listener; } - - void SetStyle(Style style); - - // Informs the combobox that its model changed. - void ModelChanged(); - - // Gets/Sets the selected index. - int selected_index() const { return selected_index_; } - void SetSelectedIndex(int index); - - // Looks for the first occurrence of |value| in |model()|. If found, selects - // the found index and returns true. Otherwise simply noops and returns false. - bool SelectValue(const base::string16& value); - - ui::ComboboxModel* model() const { return model_; } - - // Set the accessible name of the combobox. - void SetAccessibleName(const base::string16& name); - - // Visually marks the combobox as having an invalid value selected. - // When invalid, it paints with white text on a red background. - // Callers are responsible for restoring validity with selection changes. - void SetInvalid(bool invalid); - bool invalid() const { return invalid_; } - - // Overridden from View: - virtual gfx::Size GetPreferredSize() const override; - virtual const char* GetClassName() const override; - virtual bool SkipDefaultKeyEventProcessing(const ui::KeyEvent& e) override; - virtual bool OnKeyPressed(const ui::KeyEvent& e) override; - virtual bool OnKeyReleased(const ui::KeyEvent& e) override; - virtual void OnPaint(gfx::Canvas* canvas) override; - virtual void OnFocus() override; - virtual void OnBlur() override; - virtual void GetAccessibleState(ui::AXViewState* state) override; - virtual ui::TextInputClient* GetTextInputClient() override; - virtual void Layout() override; - - // Overridden from MenuDelegate: - virtual bool IsItemChecked(int id) const override; - virtual bool IsCommandEnabled(int id) const override; - virtual void ExecuteCommand(int id) override; - virtual bool GetAccelerator(int id, - ui::Accelerator* accelerator) const override; - - // Overridden from PrefixDelegate: - virtual int GetRowCount() override; - virtual int GetSelectedRow() override; - virtual void SetSelectedRow(int row) override; - virtual base::string16 GetTextForRow(int row) override; - - // Overriden from ComboboxModelObserver: - virtual void OnComboboxModelChanged(ui::ComboboxModel* model) override; - - // Overriden from ButtonListener: - virtual void ButtonPressed(Button* sender, const ui::Event& event) override; - - private: - FRIEND_TEST_ALL_PREFIXES(ComboboxTest, Click); - FRIEND_TEST_ALL_PREFIXES(ComboboxTest, ClickButDisabled); - FRIEND_TEST_ALL_PREFIXES(ComboboxTest, NotifyOnClickWithMouse); - FRIEND_TEST_ALL_PREFIXES(ComboboxTest, ContentWidth); - - // Updates the combobox's content from its model. - void UpdateFromModel(); - - // Updates the border according to the current state. - void UpdateBorder(); - - // Given bounds within our View, this helper mirrors the bounds if necessary. - void AdjustBoundsForRTLUI(gfx::Rect* rect) const; - - // Draws the selected value of the drop down list - void PaintText(gfx::Canvas* canvas); - - // Draws the button images. - void PaintButtons(gfx::Canvas* canvas); - - // Show the drop down list - void ShowDropDownMenu(ui::MenuSourceType source_type); - - // Called when the selection is changed by the user. - void OnPerformAction(); - void NotifyPerformAction(); - void AfterPerformAction(); - - // Converts a menu command ID to a menu item index. - int MenuCommandToIndex(int menu_command_id) const; - - int GetDisclosureArrowLeftPadding() const; - int GetDisclosureArrowRightPadding() const; - - // Returns the size of the disclosure arrow. - gfx::Size ArrowSize() const; - - // Handles the clicking event. - void HandleClickEvent(); - - // Our model. Not owned. - ui::ComboboxModel* model_; - - // The visual style of this combobox. - Style style_; - - // Our listener. Not owned. Notified when the selected index change. - ComboboxListener* listener_; - - // The current selected index; -1 and means no selection. - int selected_index_; - - // True when the selection is visually denoted as invalid. - bool invalid_; - - // The accessible name of this combobox. - base::string16 accessible_name_; - - // A helper used to select entries by keyboard input. - scoped_ptr<PrefixSelector> selector_; - - // Responsible for showing the context menu. - scoped_ptr<MenuRunner> dropdown_list_menu_runner_; - - // Weak. Owned by dropdown_list_menu_runner_. - MenuItemView* menu_; - - // Is the drop down list showing - bool dropdown_open_; - - // Like MenuButton, we use a time object in order to keep track of when the - // combobox was closed. The time is used for simulating menu behavior; that - // is, if the menu is shown and the button is pressed, we need to close the - // menu. There is no clean way to get the second click event because the - // menu is displayed using a modal loop and, unlike regular menus in Windows, - // the button is not part of the displayed menu. - base::Time closed_time_; - - // The maximum dimensions of the content in the dropdown - mutable gfx::Size content_size_; - - // The painters or images that are used when |style_| is STYLE_BUTTONS. The - // first index means the state of unfocused or focused. - // The images are owned by ResourceBundle. - scoped_ptr<Painter> body_button_painters_[2][Button::STATE_COUNT]; - std::vector<const gfx::ImageSkia*> - menu_button_images_[2][Button::STATE_COUNT]; - - // The transparent buttons to handle events and render buttons. These are - // placed on top of this combobox as child views, accept event and manage the - // button states. These are not rendered but when |style_| is - // STYLE_NOTIFY_ON_CLICK, a Combobox renders the button images according to - // these button states. - // The base View takes the ownerships of these as child views. - CustomButton* text_button_; - CustomButton* arrow_button_; - - // Used for making calbacks. - base::WeakPtrFactory<Combobox> weak_ptr_factory_; - - DISALLOW_COPY_AND_ASSIGN(Combobox); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_COMBOBOX_COMBOBOX_H_
diff --git a/ui/views/controls/combobox/combobox_listener.h b/ui/views/controls/combobox/combobox_listener.h deleted file mode 100644 index 2522e03..0000000 --- a/ui/views/controls/combobox/combobox_listener.h +++ /dev/null
@@ -1,33 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_COMBOBOX_COMBOBOX_LISTENER_H_ -#define UI_VIEWS_CONTROLS_COMBOBOX_COMBOBOX_LISTENER_H_ - -#include "ui/views/views_export.h" - -namespace views { - -class Combobox; - -// Interface used to notify consumers when something interesting happens to a -// Combobox. -class VIEWS_EXPORT ComboboxListener { - public: - // Invoked when the user does the appropriate gesture that some action should - // be performed. For both STYLE_NORMAL and STYLE_ACTION this is invoked if the - // user clicks on the menu button and then clicks an item. For STYLE_NORMAL - // this is also invoked when the menu is not showing and the does a gesture to - // change the selection (for example, presses the home or end keys). This is - // not invoked when the menu is shown and the user changes the selection - // without closing the menu. - virtual void OnPerformAction(Combobox* combobox) = 0; - - protected: - virtual ~ComboboxListener() {} -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_COMBOBOX_COMBOBOX_LISTENER_H_
diff --git a/ui/views/controls/combobox/combobox_unittest.cc b/ui/views/controls/combobox/combobox_unittest.cc deleted file mode 100644 index 8a2043f..0000000 --- a/ui/views/controls/combobox/combobox_unittest.cc +++ /dev/null
@@ -1,701 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/combobox/combobox.h" - -#include <set> - -#include "base/basictypes.h" -#include "base/strings/utf_string_conversions.h" -#include "ui/base/ime/text_input_client.h" -#include "ui/base/models/combobox_model.h" -#include "ui/events/event.h" -#include "ui/events/event_constants.h" -#include "ui/events/keycodes/keyboard_codes.h" -#include "ui/views/controls/combobox/combobox_listener.h" -#include "ui/views/controls/menu/menu_runner.h" -#include "ui/views/controls/menu/menu_runner_handler.h" -#include "ui/views/ime/mock_input_method.h" -#include "ui/views/test/menu_runner_test_api.h" -#include "ui/views/test/views_test_base.h" -#include "ui/views/widget/widget.h" - -using base::ASCIIToUTF16; - -namespace views { - -namespace { - -// An dummy implementation of MenuRunnerHandler to check if the dropdown menu is -// shown or not. -class TestMenuRunnerHandler : public MenuRunnerHandler { - public: - TestMenuRunnerHandler() : executed_(false) {} - - bool executed() const { return executed_; } - - virtual MenuRunner::RunResult RunMenuAt(Widget* parent, - MenuButton* button, - const gfx::Rect& bounds, - MenuAnchorPosition anchor, - ui::MenuSourceType source_type, - int32 types) override { - executed_ = true; - return MenuRunner::NORMAL_EXIT; - } - - private: - bool executed_; - - DISALLOW_COPY_AND_ASSIGN(TestMenuRunnerHandler); -}; - -// A wrapper of Combobox to intercept the result of OnKeyPressed() and -// OnKeyReleased() methods. -class TestCombobox : public Combobox { - public: - explicit TestCombobox(ui::ComboboxModel* model) - : Combobox(model), - key_handled_(false), - key_received_(false) {} - - virtual bool OnKeyPressed(const ui::KeyEvent& e) override { - key_received_ = true; - key_handled_ = Combobox::OnKeyPressed(e); - return key_handled_; - } - - virtual bool OnKeyReleased(const ui::KeyEvent& e) override { - key_received_ = true; - key_handled_ = Combobox::OnKeyReleased(e); - return key_handled_; - } - - bool key_handled() const { return key_handled_; } - bool key_received() const { return key_received_; } - - void clear() { - key_received_ = key_handled_ = false; - } - - private: - bool key_handled_; - bool key_received_; - - DISALLOW_COPY_AND_ASSIGN(TestCombobox); -}; - -// A concrete class is needed to test the combobox. -class TestComboboxModel : public ui::ComboboxModel { - public: - TestComboboxModel() {} - virtual ~TestComboboxModel() {} - - static const int kItemCount = 10; - - // ui::ComboboxModel: - virtual int GetItemCount() const override { - return kItemCount; - } - virtual base::string16 GetItemAt(int index) override { - if (IsItemSeparatorAt(index)) { - NOTREACHED(); - return ASCIIToUTF16("SEPARATOR"); - } - return ASCIIToUTF16(index % 2 == 0 ? "PEANUT BUTTER" : "JELLY"); - } - virtual bool IsItemSeparatorAt(int index) override { - return separators_.find(index) != separators_.end(); - } - - virtual int GetDefaultIndex() const override { - // Return the first index that is not a separator. - for (int index = 0; index < kItemCount; ++index) { - if (separators_.find(index) == separators_.end()) - return index; - } - NOTREACHED(); - return 0; - } - - void SetSeparators(const std::set<int>& separators) { - separators_ = separators; - } - - private: - std::set<int> separators_; - - DISALLOW_COPY_AND_ASSIGN(TestComboboxModel); -}; - -// A combobox model which refers to a vector. -class VectorComboboxModel : public ui::ComboboxModel { - public: - explicit VectorComboboxModel(std::vector<std::string>* values) - : values_(values) {} - virtual ~VectorComboboxModel() {} - - // ui::ComboboxModel: - virtual int GetItemCount() const override { - return (int)values_->size(); - } - virtual base::string16 GetItemAt(int index) override { - return ASCIIToUTF16(values_->at(index)); - } - virtual bool IsItemSeparatorAt(int index) override { - return false; - } - - private: - std::vector<std::string>* values_; -}; - -class EvilListener : public ComboboxListener { - public: - EvilListener() : deleted_(false) {} - virtual ~EvilListener() {}; - - // ComboboxListener: - virtual void OnPerformAction(Combobox* combobox) override { - delete combobox; - deleted_ = true; - } - - bool deleted() const { return deleted_; } - - private: - bool deleted_; - - DISALLOW_COPY_AND_ASSIGN(EvilListener); -}; - -class TestComboboxListener : public views::ComboboxListener { - public: - TestComboboxListener() : perform_action_index_(-1), actions_performed_(0) {} - virtual ~TestComboboxListener() {} - - virtual void OnPerformAction(views::Combobox* combobox) override { - perform_action_index_ = combobox->selected_index(); - actions_performed_++; - } - - int perform_action_index() const { - return perform_action_index_; - } - - bool on_perform_action_called() const { - return actions_performed_ > 0; - } - - int actions_performed() const { - return actions_performed_; - } - - private: - int perform_action_index_; - int actions_performed_; - - private: - DISALLOW_COPY_AND_ASSIGN(TestComboboxListener); -}; - -} // namespace - -class ComboboxTest : public ViewsTestBase { - public: - ComboboxTest() : widget_(NULL), combobox_(NULL) {} - - virtual void TearDown() override { - if (widget_) - widget_->Close(); - ViewsTestBase::TearDown(); - } - - void InitCombobox(const std::set<int>* separators) { - model_.reset(new TestComboboxModel()); - - if (separators) - model_->SetSeparators(*separators); - - ASSERT_FALSE(combobox_); - combobox_ = new TestCombobox(model_.get()); - combobox_->set_id(1); - - widget_ = new Widget; - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.bounds = gfx::Rect(200, 200, 200, 200); - widget_->Init(params); - View* container = new View(); - widget_->SetContentsView(container); - container->AddChildView(combobox_); - - widget_->ReplaceInputMethod(new MockInputMethod); - - // Assumes the Widget is always focused. - widget_->GetInputMethod()->OnFocus(); - - combobox_->RequestFocus(); - combobox_->SizeToPreferredSize(); - } - - protected: - void SendKeyEvent(ui::KeyboardCode key_code) { - SendKeyEventWithType(key_code, ui::ET_KEY_PRESSED); - } - - void SendKeyEventWithType(ui::KeyboardCode key_code, ui::EventType type) { - ui::KeyEvent event(type, key_code, ui::EF_NONE); - widget_->GetInputMethod()->DispatchKeyEvent(event); - } - - View* GetFocusedView() { - return widget_->GetFocusManager()->GetFocusedView(); - } - - void PerformClick(const gfx::Point& point) { - ui::MouseEvent pressed_event = ui::MouseEvent(ui::ET_MOUSE_PRESSED, point, - point, - ui::EF_LEFT_MOUSE_BUTTON, - ui::EF_LEFT_MOUSE_BUTTON); - widget_->OnMouseEvent(&pressed_event); - ui::MouseEvent released_event = ui::MouseEvent(ui::ET_MOUSE_RELEASED, point, - point, - ui::EF_LEFT_MOUSE_BUTTON, - ui::EF_LEFT_MOUSE_BUTTON); - widget_->OnMouseEvent(&released_event); - } - - // We need widget to populate wrapper class. - Widget* widget_; - - // |combobox_| will be allocated InitCombobox() and then owned by |widget_|. - TestCombobox* combobox_; - - // Combobox does not take ownership of the model, hence it needs to be scoped. - scoped_ptr<TestComboboxModel> model_; -}; - -TEST_F(ComboboxTest, KeyTest) { - InitCombobox(NULL); - SendKeyEvent(ui::VKEY_END); - EXPECT_EQ(combobox_->selected_index() + 1, model_->GetItemCount()); - SendKeyEvent(ui::VKEY_HOME); - EXPECT_EQ(combobox_->selected_index(), 0); - SendKeyEvent(ui::VKEY_DOWN); - SendKeyEvent(ui::VKEY_DOWN); - EXPECT_EQ(combobox_->selected_index(), 2); - SendKeyEvent(ui::VKEY_RIGHT); - EXPECT_EQ(combobox_->selected_index(), 2); - SendKeyEvent(ui::VKEY_LEFT); - EXPECT_EQ(combobox_->selected_index(), 2); - SendKeyEvent(ui::VKEY_UP); - EXPECT_EQ(combobox_->selected_index(), 1); - SendKeyEvent(ui::VKEY_PRIOR); - EXPECT_EQ(combobox_->selected_index(), 0); - SendKeyEvent(ui::VKEY_NEXT); - EXPECT_EQ(combobox_->selected_index(), model_->GetItemCount() - 1); -} - -// Check that if a combobox is disabled before it has a native wrapper, then the -// native wrapper inherits the disabled state when it gets created. -TEST_F(ComboboxTest, DisabilityTest) { - model_.reset(new TestComboboxModel()); - - ASSERT_FALSE(combobox_); - combobox_ = new TestCombobox(model_.get()); - combobox_->SetEnabled(false); - - widget_ = new Widget; - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.bounds = gfx::Rect(100, 100, 100, 100); - widget_->Init(params); - View* container = new View(); - widget_->SetContentsView(container); - container->AddChildView(combobox_); - EXPECT_FALSE(combobox_->enabled()); -} - -// Verifies that we don't select a separator line in combobox when navigating -// through keyboard. -TEST_F(ComboboxTest, SkipSeparatorSimple) { - std::set<int> separators; - separators.insert(2); - InitCombobox(&separators); - EXPECT_EQ(0, combobox_->selected_index()); - SendKeyEvent(ui::VKEY_DOWN); - EXPECT_EQ(1, combobox_->selected_index()); - SendKeyEvent(ui::VKEY_DOWN); - EXPECT_EQ(3, combobox_->selected_index()); - SendKeyEvent(ui::VKEY_UP); - EXPECT_EQ(1, combobox_->selected_index()); - SendKeyEvent(ui::VKEY_HOME); - EXPECT_EQ(0, combobox_->selected_index()); - SendKeyEvent(ui::VKEY_PRIOR); - EXPECT_EQ(0, combobox_->selected_index()); - SendKeyEvent(ui::VKEY_END); - EXPECT_EQ(9, combobox_->selected_index()); -} - -// Verifies that we never select the separator that is in the beginning of the -// combobox list when navigating through keyboard. -TEST_F(ComboboxTest, SkipSeparatorBeginning) { - std::set<int> separators; - separators.insert(0); - InitCombobox(&separators); - EXPECT_EQ(1, combobox_->selected_index()); - SendKeyEvent(ui::VKEY_DOWN); - EXPECT_EQ(2, combobox_->selected_index()); - SendKeyEvent(ui::VKEY_DOWN); - EXPECT_EQ(3, combobox_->selected_index()); - SendKeyEvent(ui::VKEY_UP); - EXPECT_EQ(2, combobox_->selected_index()); - SendKeyEvent(ui::VKEY_HOME); - EXPECT_EQ(1, combobox_->selected_index()); - SendKeyEvent(ui::VKEY_PRIOR); - EXPECT_EQ(1, combobox_->selected_index()); - SendKeyEvent(ui::VKEY_END); - EXPECT_EQ(9, combobox_->selected_index()); -} - -// Verifies that we never select the separator that is in the end of the -// combobox list when navigating through keyboard. -TEST_F(ComboboxTest, SkipSeparatorEnd) { - std::set<int> separators; - separators.insert(TestComboboxModel::kItemCount - 1); - InitCombobox(&separators); - combobox_->SetSelectedIndex(8); - SendKeyEvent(ui::VKEY_DOWN); - EXPECT_EQ(8, combobox_->selected_index()); - SendKeyEvent(ui::VKEY_UP); - EXPECT_EQ(7, combobox_->selected_index()); - SendKeyEvent(ui::VKEY_END); - EXPECT_EQ(8, combobox_->selected_index()); -} - -// Verifies that we never select any of the adjacent separators (multiple -// consecutive) that appear in the beginning of the combobox list when -// navigating through keyboard. -TEST_F(ComboboxTest, SkipMultipleSeparatorsAtBeginning) { - std::set<int> separators; - separators.insert(0); - separators.insert(1); - separators.insert(2); - InitCombobox(&separators); - EXPECT_EQ(3, combobox_->selected_index()); - SendKeyEvent(ui::VKEY_DOWN); - EXPECT_EQ(4, combobox_->selected_index()); - SendKeyEvent(ui::VKEY_UP); - EXPECT_EQ(3, combobox_->selected_index()); - SendKeyEvent(ui::VKEY_NEXT); - EXPECT_EQ(9, combobox_->selected_index()); - SendKeyEvent(ui::VKEY_HOME); - EXPECT_EQ(3, combobox_->selected_index()); - SendKeyEvent(ui::VKEY_END); - EXPECT_EQ(9, combobox_->selected_index()); - SendKeyEvent(ui::VKEY_PRIOR); - EXPECT_EQ(3, combobox_->selected_index()); -} - -// Verifies that we never select any of the adjacent separators (multiple -// consecutive) that appear in the middle of the combobox list when navigating -// through keyboard. -TEST_F(ComboboxTest, SkipMultipleAdjacentSeparatorsAtMiddle) { - std::set<int> separators; - separators.insert(4); - separators.insert(5); - separators.insert(6); - InitCombobox(&separators); - combobox_->SetSelectedIndex(3); - SendKeyEvent(ui::VKEY_DOWN); - EXPECT_EQ(7, combobox_->selected_index()); - SendKeyEvent(ui::VKEY_UP); - EXPECT_EQ(3, combobox_->selected_index()); -} - -// Verifies that we never select any of the adjacent separators (multiple -// consecutive) that appear in the end of the combobox list when navigating -// through keyboard. -TEST_F(ComboboxTest, SkipMultipleSeparatorsAtEnd) { - std::set<int> separators; - separators.insert(7); - separators.insert(8); - separators.insert(9); - InitCombobox(&separators); - combobox_->SetSelectedIndex(6); - SendKeyEvent(ui::VKEY_DOWN); - EXPECT_EQ(6, combobox_->selected_index()); - SendKeyEvent(ui::VKEY_UP); - EXPECT_EQ(5, combobox_->selected_index()); - SendKeyEvent(ui::VKEY_HOME); - EXPECT_EQ(0, combobox_->selected_index()); - SendKeyEvent(ui::VKEY_NEXT); - EXPECT_EQ(6, combobox_->selected_index()); - SendKeyEvent(ui::VKEY_PRIOR); - EXPECT_EQ(0, combobox_->selected_index()); - SendKeyEvent(ui::VKEY_END); - EXPECT_EQ(6, combobox_->selected_index()); -} - -TEST_F(ComboboxTest, GetTextForRowTest) { - std::set<int> separators; - separators.insert(0); - separators.insert(1); - separators.insert(9); - InitCombobox(&separators); - for (int i = 0; i < combobox_->GetRowCount(); ++i) { - if (separators.count(i) != 0) { - EXPECT_TRUE(combobox_->GetTextForRow(i).empty()) << i; - } else { - EXPECT_EQ(ASCIIToUTF16(i % 2 == 0 ? "PEANUT BUTTER" : "JELLY"), - combobox_->GetTextForRow(i)) << i; - } - } -} - -// Verifies selecting the first matching value (and returning whether found). -TEST_F(ComboboxTest, SelectValue) { - InitCombobox(NULL); - ASSERT_EQ(model_->GetDefaultIndex(), combobox_->selected_index()); - EXPECT_TRUE(combobox_->SelectValue(ASCIIToUTF16("PEANUT BUTTER"))); - EXPECT_EQ(0, combobox_->selected_index()); - EXPECT_TRUE(combobox_->SelectValue(ASCIIToUTF16("JELLY"))); - EXPECT_EQ(1, combobox_->selected_index()); - EXPECT_FALSE(combobox_->SelectValue(ASCIIToUTF16("BANANAS"))); - EXPECT_EQ(1, combobox_->selected_index()); - - // With the action style, the selected index is always 0. - combobox_->SetStyle(Combobox::STYLE_ACTION); - EXPECT_FALSE(combobox_->SelectValue(ASCIIToUTF16("PEANUT BUTTER"))); - EXPECT_EQ(0, combobox_->selected_index()); - EXPECT_FALSE(combobox_->SelectValue(ASCIIToUTF16("JELLY"))); - EXPECT_EQ(0, combobox_->selected_index()); - EXPECT_FALSE(combobox_->SelectValue(ASCIIToUTF16("BANANAS"))); - EXPECT_EQ(0, combobox_->selected_index()); -} - -TEST_F(ComboboxTest, SelectIndexActionStyle) { - InitCombobox(NULL); - - // With the action style, the selected index is always 0. - combobox_->SetStyle(Combobox::STYLE_ACTION); - combobox_->SetSelectedIndex(1); - EXPECT_EQ(0, combobox_->selected_index()); - combobox_->SetSelectedIndex(2); - EXPECT_EQ(0, combobox_->selected_index()); - combobox_->SetSelectedIndex(3); - EXPECT_EQ(0, combobox_->selected_index()); -} - -TEST_F(ComboboxTest, ListenerHandlesDelete) { - TestComboboxModel model; - - // |combobox| will be deleted on change. - TestCombobox* combobox = new TestCombobox(&model); - scoped_ptr<EvilListener> evil_listener(new EvilListener()); - combobox->set_listener(evil_listener.get()); - ASSERT_NO_FATAL_FAILURE(combobox->ExecuteCommand(2)); - EXPECT_TRUE(evil_listener->deleted()); - - // With STYLE_ACTION - // |combobox| will be deleted on change. - combobox = new TestCombobox(&model); - evil_listener.reset(new EvilListener()); - combobox->set_listener(evil_listener.get()); - combobox->SetStyle(Combobox::STYLE_ACTION); - ASSERT_NO_FATAL_FAILURE(combobox->ExecuteCommand(2)); - EXPECT_TRUE(evil_listener->deleted()); -} - -TEST_F(ComboboxTest, Click) { - InitCombobox(NULL); - - TestComboboxListener listener; - combobox_->set_listener(&listener); - - combobox_->Layout(); - - // Click the left side. The menu is shown. - TestMenuRunnerHandler* test_menu_runner_handler = new TestMenuRunnerHandler(); - scoped_ptr<MenuRunnerHandler> menu_runner_handler(test_menu_runner_handler); - test::MenuRunnerTestAPI test_api( - combobox_->dropdown_list_menu_runner_.get()); - test_api.SetMenuRunnerHandler(menu_runner_handler.Pass()); - PerformClick(gfx::Point(combobox_->x() + 1, - combobox_->y() + combobox_->height() / 2)); - EXPECT_FALSE(listener.on_perform_action_called()); - EXPECT_TRUE(test_menu_runner_handler->executed()); -} - -TEST_F(ComboboxTest, ClickButDisabled) { - InitCombobox(NULL); - - TestComboboxListener listener; - combobox_->set_listener(&listener); - - combobox_->Layout(); - combobox_->SetEnabled(false); - - // Click the left side, but nothing happens since the combobox is disabled. - TestMenuRunnerHandler* test_menu_runner_handler = new TestMenuRunnerHandler(); - scoped_ptr<MenuRunnerHandler> menu_runner_handler(test_menu_runner_handler); - test::MenuRunnerTestAPI test_api( - combobox_->dropdown_list_menu_runner_.get()); - test_api.SetMenuRunnerHandler(menu_runner_handler.Pass()); - PerformClick(gfx::Point(combobox_->x() + 1, - combobox_->y() + combobox_->height() / 2)); - EXPECT_FALSE(listener.on_perform_action_called()); - EXPECT_FALSE(test_menu_runner_handler->executed()); -} - -TEST_F(ComboboxTest, NotifyOnClickWithReturnKey) { - InitCombobox(NULL); - - TestComboboxListener listener; - combobox_->set_listener(&listener); - - // With STYLE_NORMAL, the click event is ignored. - SendKeyEvent(ui::VKEY_RETURN); - EXPECT_FALSE(listener.on_perform_action_called()); - - // With STYLE_ACTION, the click event is notified. - combobox_->SetStyle(Combobox::STYLE_ACTION); - SendKeyEvent(ui::VKEY_RETURN); - EXPECT_TRUE(listener.on_perform_action_called()); - EXPECT_EQ(0, listener.perform_action_index()); -} - -TEST_F(ComboboxTest, NotifyOnClickWithSpaceKey) { - InitCombobox(NULL); - - TestComboboxListener listener; - combobox_->set_listener(&listener); - - // With STYLE_NORMAL, the click event is ignored. - SendKeyEvent(ui::VKEY_SPACE); - EXPECT_FALSE(listener.on_perform_action_called()); - SendKeyEventWithType(ui::VKEY_SPACE, ui::ET_KEY_RELEASED); - EXPECT_FALSE(listener.on_perform_action_called()); - - // With STYLE_ACTION, the click event is notified after releasing. - combobox_->SetStyle(Combobox::STYLE_ACTION); - SendKeyEvent(ui::VKEY_SPACE); - EXPECT_FALSE(listener.on_perform_action_called()); - SendKeyEventWithType(ui::VKEY_SPACE, ui::ET_KEY_RELEASED); - EXPECT_TRUE(listener.on_perform_action_called()); - EXPECT_EQ(0, listener.perform_action_index()); -} - -TEST_F(ComboboxTest, NotifyOnClickWithMouse) { - InitCombobox(NULL); - - TestComboboxListener listener; - combobox_->set_listener(&listener); - - combobox_->SetStyle(Combobox::STYLE_ACTION); - combobox_->Layout(); - - // Click the right side (arrow button). The menu is shown. - TestMenuRunnerHandler* test_menu_runner_handler = new TestMenuRunnerHandler(); - scoped_ptr<MenuRunnerHandler> menu_runner_handler(test_menu_runner_handler); - scoped_ptr<test::MenuRunnerTestAPI> test_api( - new test::MenuRunnerTestAPI(combobox_->dropdown_list_menu_runner_.get())); - test_api->SetMenuRunnerHandler(menu_runner_handler.Pass()); - - PerformClick(gfx::Point(combobox_->x() + combobox_->width() - 1, - combobox_->y() + combobox_->height() / 2)); - EXPECT_FALSE(listener.on_perform_action_called()); - EXPECT_TRUE(test_menu_runner_handler->executed()); - - // Click the left side (text button). The click event is notified. - test_menu_runner_handler = new TestMenuRunnerHandler(); - menu_runner_handler.reset(test_menu_runner_handler); - test_api.reset( - new test::MenuRunnerTestAPI(combobox_->dropdown_list_menu_runner_.get())); - test_api->SetMenuRunnerHandler(menu_runner_handler.Pass()); - PerformClick(gfx::Point(combobox_->x() + 1, - combobox_->y() + combobox_->height() / 2)); - EXPECT_TRUE(listener.on_perform_action_called()); - EXPECT_FALSE(test_menu_runner_handler->executed()); - EXPECT_EQ(0, listener.perform_action_index()); -} - -TEST_F(ComboboxTest, ConsumingPressKeyEvents) { - InitCombobox(NULL); - - EXPECT_FALSE(combobox_->OnKeyPressed( - ui::KeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_RETURN, ui::EF_NONE))); - EXPECT_FALSE(combobox_->OnKeyPressed( - ui::KeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_SPACE, ui::EF_NONE))); - - // When the combobox's style is STYLE_ACTION, pressing events of a space key - // or an enter key will be consumed. - combobox_->SetStyle(Combobox::STYLE_ACTION); - EXPECT_TRUE(combobox_->OnKeyPressed( - ui::KeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_RETURN, ui::EF_NONE))); - EXPECT_TRUE(combobox_->OnKeyPressed( - ui::KeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_SPACE, ui::EF_NONE))); -} - -TEST_F(ComboboxTest, ContentWidth) { - std::vector<std::string> values; - VectorComboboxModel model(&values); - TestCombobox combobox(&model); - - std::string long_item = "this is the long item"; - std::string short_item = "s"; - - values.resize(1); - values[0] = long_item; - combobox.ModelChanged(); - - const int long_item_width = combobox.content_size_.width(); - - values[0] = short_item; - combobox.ModelChanged(); - - const int short_item_width = combobox.content_size_.width(); - - values.resize(2); - values[0] = short_item; - values[1] = long_item; - combobox.ModelChanged(); - - // When the style is STYLE_NORMAL, the width will fit with the longest item. - combobox.SetStyle(Combobox::STYLE_NORMAL); - EXPECT_EQ(long_item_width, combobox.content_size_.width()); - - // When the style is STYLE_ACTION, the width will fit with the first items' - // width. - combobox.SetStyle(Combobox::STYLE_ACTION); - EXPECT_EQ(short_item_width, combobox.content_size_.width()); -} - -TEST_F(ComboboxTest, TypingPrefixNotifiesListener) { - InitCombobox(NULL); - - TestComboboxListener listener; - combobox_->set_listener(&listener); - - // Type the first character of the second menu item ("JELLY"). - combobox_->GetTextInputClient()->InsertChar('J', ui::EF_NONE); - EXPECT_EQ(1, listener.actions_performed()); - EXPECT_EQ(1, listener.perform_action_index()); - - // Type the second character of "JELLY", item shouldn't change and - // OnPerformAction() shouldn't be re-called. - combobox_->GetTextInputClient()->InsertChar('E', ui::EF_NONE); - EXPECT_EQ(1, listener.actions_performed()); - EXPECT_EQ(1, listener.perform_action_index()); - - // Clears the typed text. - combobox_->OnBlur(); - - // Type the first character of "PEANUT BUTTER", which should change the - // selected index and perform an action. - combobox_->GetTextInputClient()->InsertChar('P', ui::EF_NONE); - EXPECT_EQ(2, listener.actions_performed()); - EXPECT_EQ(2, listener.perform_action_index()); -} - -} // namespace views
diff --git a/ui/views/controls/focusable_border.cc b/ui/views/controls/focusable_border.cc deleted file mode 100644 index 0e4f3a2..0000000 --- a/ui/views/controls/focusable_border.cc +++ /dev/null
@@ -1,68 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/focusable_border.h" - -#include "ui/gfx/canvas.h" -#include "ui/gfx/insets.h" -#include "ui/gfx/skia_util.h" -#include "ui/native_theme/native_theme.h" - -namespace { - -const int kInsetSize = 1; - -} // namespace - -namespace views { - -FocusableBorder::FocusableBorder() - : insets_(kInsetSize, kInsetSize, kInsetSize, kInsetSize), - override_color_(SK_ColorWHITE), - use_default_color_(true) { -} - -FocusableBorder::~FocusableBorder() { -} - -void FocusableBorder::SetColor(SkColor color) { - override_color_ = color; - use_default_color_ = false; -} - -void FocusableBorder::UseDefaultColor() { - use_default_color_ = true; -} - -void FocusableBorder::Paint(const View& view, gfx::Canvas* canvas) { - SkPath path; - path.addRect(gfx::RectToSkRect(view.GetLocalBounds()), SkPath::kCW_Direction); - SkPaint paint; - paint.setStyle(SkPaint::kStroke_Style); - SkColor color = override_color_; - if (use_default_color_) { - color = view.GetNativeTheme()->GetSystemColor( - view.HasFocus() ? ui::NativeTheme::kColorId_FocusedBorderColor : - ui::NativeTheme::kColorId_UnfocusedBorderColor); - } - - paint.setColor(color); - paint.setStrokeWidth(SkIntToScalar(2)); - - canvas->DrawPath(path, paint); -} - -gfx::Insets FocusableBorder::GetInsets() const { - return insets_; -} - -gfx::Size FocusableBorder::GetMinimumSize() const { - return gfx::Size(); -} - -void FocusableBorder::SetInsets(int top, int left, int bottom, int right) { - insets_.Set(top, left, bottom, right); -} - -} // namespace views
diff --git a/ui/views/controls/focusable_border.h b/ui/views/controls/focusable_border.h deleted file mode 100644 index 9afa6ea..0000000 --- a/ui/views/controls/focusable_border.h +++ /dev/null
@@ -1,54 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_FOCUSABLE_BORDER_H_ -#define UI_VIEWS_CONTROLS_FOCUSABLE_BORDER_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "ui/views/border.h" -#include "ui/views/view.h" - -namespace gfx { -class Canvas; -class Insets; -} - -namespace views { - -// A Border class to draw a focused border around a field (e.g textfield). -class VIEWS_EXPORT FocusableBorder : public Border { - public: - FocusableBorder(); - virtual ~FocusableBorder(); - - // Sets the insets of the border. - void SetInsets(int top, int left, int bottom, int right); - - // Sets the color of this border. - void SetColor(SkColor color); - // Reverts the color of this border to the system default. - void UseDefaultColor(); - - // Overridden from Border: - virtual void Paint(const View& view, gfx::Canvas* canvas) override; - virtual gfx::Insets GetInsets() const override; - virtual gfx::Size GetMinimumSize() const override; - - private: - gfx::Insets insets_; - - // The color to paint the border when |use_default_color_| is false. - SkColor override_color_; - - // Whether the system border color should be used. True unless SetColor has - // been called. - bool use_default_color_; - - DISALLOW_COPY_AND_ASSIGN(FocusableBorder); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_FOCUSABLE_BORDER_H_
diff --git a/ui/views/controls/glow_hover_controller.cc b/ui/views/controls/glow_hover_controller.cc deleted file mode 100644 index 5ce23fa..0000000 --- a/ui/views/controls/glow_hover_controller.cc +++ /dev/null
@@ -1,128 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/glow_hover_controller.h" - -#include "third_party/skia/include/effects/SkGradientShader.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/image/image_skia.h" -#include "ui/gfx/image/image_skia_operations.h" -#include "ui/views/view.h" - -namespace views { - -// Amount to scale the opacity. -static const double kTrackOpacityScale = 0.5; -static const double kHighlightOpacityScale = 1.0; - -// How long the hover state takes. -static const int kTrackHoverDurationMs = 400; - -GlowHoverController::GlowHoverController(views::View* view) - : view_(view), - animation_(this), - opacity_scale_(kTrackOpacityScale) { - animation_.set_delegate(this); -} - -GlowHoverController::~GlowHoverController() { -} - -void GlowHoverController::SetAnimationContainer( - gfx::AnimationContainer* container) { - animation_.SetContainer(container); -} - -void GlowHoverController::SetLocation(const gfx::Point& location) { - location_ = location; - if (ShouldDraw()) - view_->SchedulePaint(); -} - -void GlowHoverController::Show(Style style) { - switch (style) { - case SUBTLE: - opacity_scale_ = kTrackOpacityScale; - animation_.SetSlideDuration(kTrackHoverDurationMs); - animation_.SetTweenType(gfx::Tween::EASE_OUT); - animation_.Show(); - break; - case PRONOUNCED: - opacity_scale_ = kHighlightOpacityScale; - // Force the end state to show immediately. - animation_.Show(); - animation_.End(); - break; - } -} - -void GlowHoverController::Hide() { - animation_.SetTweenType(gfx::Tween::EASE_IN); - animation_.Hide(); -} - -void GlowHoverController::HideImmediately() { - if (ShouldDraw()) - view_->SchedulePaint(); - animation_.Reset(); -} - -double GlowHoverController::GetAnimationValue() const { - return animation_.GetCurrentValue(); -} - -bool GlowHoverController::ShouldDraw() const { - return animation_.IsShowing() || animation_.is_animating(); -} - -void GlowHoverController::Draw(gfx::Canvas* canvas, - const gfx::ImageSkia& mask_image) const { - if (!ShouldDraw()) - return; - - // Draw a radial gradient to hover_canvas. - gfx::Canvas hover_canvas(gfx::Size(mask_image.width(), mask_image.height()), - canvas->image_scale(), - false); - - // Draw a radial gradient to hover_canvas. - int radius = view_->width() / 3; - - SkPoint center_point; - center_point.iset(location_.x(), location_.y()); - SkColor colors[2]; - int hover_alpha = - static_cast<int>(255 * opacity_scale_ * animation_.GetCurrentValue()); - colors[0] = SkColorSetARGB(hover_alpha, 255, 255, 255); - colors[1] = SkColorSetARGB(0, 255, 255, 255); - skia::RefPtr<SkShader> shader = skia::AdoptRef( - SkGradientShader::CreateRadial( - center_point, SkIntToScalar(radius), colors, NULL, 2, - SkShader::kClamp_TileMode)); - // Shader can end up null when radius = 0. - // If so, this results in default full tab glow behavior. - if (shader) { - SkPaint paint; - paint.setStyle(SkPaint::kFill_Style); - paint.setAntiAlias(true); - paint.setShader(shader.get()); - hover_canvas.DrawRect(gfx::Rect(location_.x() - radius, - location_.y() - radius, - radius * 2, radius * 2), paint); - } - gfx::ImageSkia result = gfx::ImageSkiaOperations::CreateMaskedImage( - gfx::ImageSkia(hover_canvas.ExtractImageRep()), mask_image); - canvas->DrawImageInt(result, (view_->width() - mask_image.width()) / 2, - (view_->height() - mask_image.height()) / 2); -} - -void GlowHoverController::AnimationEnded(const gfx::Animation* animation) { - view_->SchedulePaint(); -} - -void GlowHoverController::AnimationProgressed(const gfx::Animation* animation) { - view_->SchedulePaint(); -} - -} // namespace views
diff --git a/ui/views/controls/glow_hover_controller.h b/ui/views/controls/glow_hover_controller.h deleted file mode 100644 index 59d27a7..0000000 --- a/ui/views/controls/glow_hover_controller.h +++ /dev/null
@@ -1,87 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_GLOW_HOVER_CONTROLLER_H_ -#define UI_VIEWS_CONTROLS_GLOW_HOVER_CONTROLLER_H_ - -#include "ui/gfx/animation/animation_delegate.h" -#include "ui/gfx/animation/slide_animation.h" -#include "ui/views/views_export.h" - -namespace gfx { -class Canvas; -class ImageSkia; -class Point; -} - -namespace views { - -class View; - -// GlowHoverController is responsible for drawing a hover effect as is used by -// the tabstrip. Typical usage: -// OnMouseEntered() -> invoke Show(). -// OnMouseMoved() -> invoke SetLocation(). -// OnMouseExited() -> invoke Hide(). -// OnPaint() -> if ShouldDraw() returns true invoke Draw(). -// Internally GlowHoverController uses an animation to animate the glow and -// invokes SchedulePaint() back on the View as necessary. -class VIEWS_EXPORT GlowHoverController : public gfx::AnimationDelegate { - public: - enum Style { - SUBTLE, - PRONOUNCED - }; - - explicit GlowHoverController(views::View* view); - virtual ~GlowHoverController(); - - // Sets the AnimationContainer used by the animation. - void SetAnimationContainer(gfx::AnimationContainer* container); - - // Sets the location of the hover, relative to the View passed to the - // constructor. - void SetLocation(const gfx::Point& location); - - // Initiates showing the hover. - void Show(Style style); - - // Hides the hover. - void Hide(); - - // Hides the hover immediately. - void HideImmediately(); - - // Returns the value of the animation. - double GetAnimationValue() const; - - // Returns true if there is something to be drawn. Use this instead of - // invoking Draw() if creating |mask_image| is expensive. - bool ShouldDraw() const; - - // If the hover is currently visible it is drawn to the supplied canvas. - // |mask_image| is used to determine what parts of the canvas to draw on. - void Draw(gfx::Canvas* canvas, const gfx::ImageSkia& mask_image) const; - - // gfx::AnimationDelegate overrides: - virtual void AnimationEnded(const gfx::Animation* animation) override; - virtual void AnimationProgressed(const gfx::Animation* animation) override; - - private: - // View we're drawing to. - views::View* view_; - - // Opacity of the glow ramps up over time. - gfx::SlideAnimation animation_; - - // Location of the glow, relative to view. - gfx::Point location_; - double opacity_scale_; - - DISALLOW_COPY_AND_ASSIGN(GlowHoverController); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_GLOW_HOVER_CONTROLLER_H_
diff --git a/ui/views/controls/image_view.cc b/ui/views/controls/image_view.cc deleted file mode 100644 index 5b758f8..0000000 --- a/ui/views/controls/image_view.cc +++ /dev/null
@@ -1,236 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/image_view.h" - -#include "base/logging.h" -#include "base/strings/utf_string_conversions.h" -#include "third_party/skia/include/core/SkPaint.h" -#include "ui/accessibility/ax_view_state.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/insets.h" -#include "ui/views/painter.h" - -namespace views { - -namespace { - -// Returns the pixels for the bitmap in |image| at scale |image_scale|. -void* GetBitmapPixels(const gfx::ImageSkia& img, float image_scale) { - DCHECK_NE(0.0f, image_scale); - const SkBitmap& bitmap = img.GetRepresentation(image_scale).sk_bitmap(); - SkAutoLockPixels pixel_lock(bitmap); - return bitmap.getPixels(); -} - -} // namespace - -ImageView::ImageView() - : image_size_set_(false), - horiz_alignment_(CENTER), - vert_alignment_(CENTER), - interactive_(true), - last_paint_scale_(0.f), - last_painted_bitmap_pixels_(NULL), - focus_painter_(Painter::CreateDashedFocusPainter()) { -} - -ImageView::~ImageView() { -} - -void ImageView::SetImage(const gfx::ImageSkia& img) { - if (IsImageEqual(img)) - return; - - last_painted_bitmap_pixels_ = NULL; - gfx::Size pref_size(GetPreferredSize()); - image_ = img; - if (pref_size != GetPreferredSize()) - PreferredSizeChanged(); - SchedulePaint(); -} - -void ImageView::SetImage(const gfx::ImageSkia* image_skia) { - if (image_skia) { - SetImage(*image_skia); - } else { - gfx::ImageSkia t; - SetImage(t); - } -} - -const gfx::ImageSkia& ImageView::GetImage() { - return image_; -} - -void ImageView::SetImageSize(const gfx::Size& image_size) { - image_size_set_ = true; - image_size_ = image_size; - PreferredSizeChanged(); -} - -bool ImageView::GetImageSize(gfx::Size* image_size) const { - DCHECK(image_size); - if (image_size_set_) - *image_size = image_size_; - return image_size_set_; -} - -gfx::Rect ImageView::GetImageBounds() const { - gfx::Size image_size(image_size_set_ ? - image_size_ : gfx::Size(image_.width(), image_.height())); - return gfx::Rect(ComputeImageOrigin(image_size), image_size); -} - -void ImageView::ResetImageSize() { - image_size_set_ = false; -} - -void ImageView::SetFocusPainter(scoped_ptr<Painter> focus_painter) { - focus_painter_ = focus_painter.Pass(); -} - -gfx::Size ImageView::GetPreferredSize() const { - gfx::Insets insets = GetInsets(); - if (image_size_set_) { - gfx::Size image_size; - GetImageSize(&image_size); - image_size.Enlarge(insets.width(), insets.height()); - return image_size; - } - return gfx::Size(image_.width() + insets.width(), - image_.height() + insets.height()); -} - -bool ImageView::IsImageEqual(const gfx::ImageSkia& img) const { - // Even though we copy ImageSkia in SetImage() the backing store - // (ImageSkiaStorage) is not copied and may have changed since the last call - // to SetImage(). The expectation is that SetImage() with different pixels is - // treated as though the image changed. For this reason we compare not only - // the backing store but also the pixels of the last image we painted. - return image_.BackedBySameObjectAs(img) && - last_paint_scale_ != 0.0f && - last_painted_bitmap_pixels_ == GetBitmapPixels(img, last_paint_scale_); -} - -gfx::Point ImageView::ComputeImageOrigin(const gfx::Size& image_size) const { - gfx::Insets insets = GetInsets(); - - int x; - // In order to properly handle alignment of images in RTL locales, we need - // to flip the meaning of trailing and leading. For example, if the - // horizontal alignment is set to trailing, then we'll use left alignment for - // the image instead of right alignment if the UI layout is RTL. - Alignment actual_horiz_alignment = horiz_alignment_; - if (base::i18n::IsRTL() && (horiz_alignment_ != CENTER)) - actual_horiz_alignment = (horiz_alignment_ == LEADING) ? TRAILING : LEADING; - switch (actual_horiz_alignment) { - case LEADING: x = insets.left(); break; - case TRAILING: x = width() - insets.right() - image_size.width(); break; - case CENTER: x = (width() - image_size.width()) / 2; break; - default: NOTREACHED(); x = 0; break; - } - - int y; - switch (vert_alignment_) { - case LEADING: y = insets.top(); break; - case TRAILING: y = height() - insets.bottom() - image_size.height(); break; - case CENTER: y = (height() - image_size.height()) / 2; break; - default: NOTREACHED(); y = 0; break; - } - - return gfx::Point(x, y); -} - -void ImageView::OnFocus() { - View::OnFocus(); - if (focus_painter_.get()) - SchedulePaint(); -} - -void ImageView::OnBlur() { - View::OnBlur(); - if (focus_painter_.get()) - SchedulePaint(); -} - -void ImageView::OnPaint(gfx::Canvas* canvas) { - View::OnPaint(canvas); - OnPaintImage(canvas); - Painter::PaintFocusPainter(this, canvas, focus_painter_.get()); -} - -void ImageView::GetAccessibleState(ui::AXViewState* state) { - state->role = ui::AX_ROLE_IMAGE; - state->name = tooltip_text_; -} - -void ImageView::SetHorizontalAlignment(Alignment ha) { - if (ha != horiz_alignment_) { - horiz_alignment_ = ha; - SchedulePaint(); - } -} - -ImageView::Alignment ImageView::GetHorizontalAlignment() const { - return horiz_alignment_; -} - -void ImageView::SetVerticalAlignment(Alignment va) { - if (va != vert_alignment_) { - vert_alignment_ = va; - SchedulePaint(); - } -} - -ImageView::Alignment ImageView::GetVerticalAlignment() const { - return vert_alignment_; -} - -void ImageView::SetTooltipText(const base::string16& tooltip) { - tooltip_text_ = tooltip; -} - -base::string16 ImageView::GetTooltipText() const { - return tooltip_text_; -} - -bool ImageView::GetTooltipText(const gfx::Point& p, - base::string16* tooltip) const { - if (tooltip_text_.empty()) - return false; - - *tooltip = GetTooltipText(); - return true; -} - -bool ImageView::CanProcessEventsWithinSubtree() const { - return interactive_; -} - -void ImageView::OnPaintImage(gfx::Canvas* canvas) { - last_paint_scale_ = canvas->image_scale(); - last_painted_bitmap_pixels_ = NULL; - - if (image_.isNull()) - return; - - gfx::Rect image_bounds(GetImageBounds()); - if (image_bounds.IsEmpty()) - return; - - if (image_bounds.size() != gfx::Size(image_.width(), image_.height())) { - // Resize case - SkPaint paint; - paint.setFilterLevel(SkPaint::kLow_FilterLevel); - canvas->DrawImageInt(image_, 0, 0, image_.width(), image_.height(), - image_bounds.x(), image_bounds.y(), image_bounds.width(), - image_bounds.height(), true, paint); - } else { - canvas->DrawImageInt(image_, image_bounds.x(), image_bounds.y()); - } - last_painted_bitmap_pixels_ = GetBitmapPixels(image_, last_paint_scale_); -} - -} // namespace views
diff --git a/ui/views/controls/image_view.h b/ui/views/controls/image_view.h deleted file mode 100644 index 00b8209..0000000 --- a/ui/views/controls/image_view.h +++ /dev/null
@@ -1,139 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_IMAGE_VIEW_H_ -#define UI_VIEWS_CONTROLS_IMAGE_VIEW_H_ - -#include "ui/gfx/image/image_skia.h" -#include "ui/views/view.h" - -namespace gfx { -class Canvas; -} - -namespace views { - -class Painter; - -///////////////////////////////////////////////////////////////////////////// -// -// ImageView class. -// -// An ImageView can display an image from an ImageSkia. If a size is provided, -// the ImageView will resize the provided image to fit if it is too big or will -// center the image if smaller. Otherwise, the preferred size matches the -// provided image size. -// -///////////////////////////////////////////////////////////////////////////// -class VIEWS_EXPORT ImageView : public View { - public: - enum Alignment { - LEADING = 0, - CENTER, - TRAILING - }; - - ImageView(); - virtual ~ImageView(); - - // Set the image that should be displayed. - void SetImage(const gfx::ImageSkia& img); - - // Set the image that should be displayed from a pointer. Reset the image - // if the pointer is NULL. The pointer contents is copied in the receiver's - // image. - void SetImage(const gfx::ImageSkia* image_skia); - - // Returns the image currently displayed or NULL of none is currently set. - // The returned image is still owned by the ImageView. - const gfx::ImageSkia& GetImage(); - - // Set the desired image size for the receiving ImageView. - void SetImageSize(const gfx::Size& image_size); - - // Return the preferred size for the receiving view. Returns false if the - // preferred size is not defined, which means that the view uses the image - // size. - bool GetImageSize(gfx::Size* image_size) const; - - // Returns the actual bounds of the visible image inside the view. - gfx::Rect GetImageBounds() const; - - // Reset the image size to the current image dimensions. - void ResetImageSize(); - - // Set / Get the horizontal alignment. - void SetHorizontalAlignment(Alignment ha); - Alignment GetHorizontalAlignment() const; - - // Set / Get the vertical alignment. - void SetVerticalAlignment(Alignment va); - Alignment GetVerticalAlignment() const; - - // Set / Get the tooltip text. - void SetTooltipText(const base::string16& tooltip); - base::string16 GetTooltipText() const; - - void set_interactive(bool interactive) { interactive_ = interactive; } - - void SetFocusPainter(scoped_ptr<Painter> focus_painter); - - // Overriden from View: - virtual gfx::Size GetPreferredSize() const override; - virtual void OnFocus() override; - virtual void OnBlur() override; - virtual void OnPaint(gfx::Canvas* canvas) override; - virtual void GetAccessibleState(ui::AXViewState* state) override; - virtual bool GetTooltipText(const gfx::Point& p, - base::string16* tooltip) const override; - virtual bool CanProcessEventsWithinSubtree() const override; - - private: - void OnPaintImage(gfx::Canvas* canvas); - - // Returns true if |img| is the same as the last image we painted. This is - // intended to be a quick check, not exhaustive. In other words it's possible - // for this to return false even though the images are in fact equal. - bool IsImageEqual(const gfx::ImageSkia& img) const; - - // Compute the image origin given the desired size and the receiver alignment - // properties. - gfx::Point ComputeImageOrigin(const gfx::Size& image_size) const; - - // Whether the image size is set. - bool image_size_set_; - - // The actual image size. - gfx::Size image_size_; - - // The underlying image. - gfx::ImageSkia image_; - - // Horizontal alignment. - Alignment horiz_alignment_; - - // Vertical alignment. - Alignment vert_alignment_; - - // The current tooltip text. - base::string16 tooltip_text_; - - // A flag controlling hit test handling for interactivity. - bool interactive_; - - // Scale last painted at. - float last_paint_scale_; - - // Address of bytes we last painted. This is used only for comparison, so its - // safe to cache. - void* last_painted_bitmap_pixels_; - - scoped_ptr<views::Painter> focus_painter_; - - DISALLOW_COPY_AND_ASSIGN(ImageView); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_IMAGE_VIEW_H_
diff --git a/ui/views/controls/label.cc b/ui/views/controls/label.cc deleted file mode 100644 index 1078d0b..0000000 --- a/ui/views/controls/label.cc +++ /dev/null
@@ -1,548 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/label.h" - -#include <algorithm> -#include <cmath> -#include <limits> -#include <vector> - -#include "base/i18n/rtl.h" -#include "base/logging.h" -#include "base/strings/string_split.h" -#include "base/strings/string_util.h" -#include "base/strings/utf_string_conversions.h" -#include "ui/accessibility/ax_view_state.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/color_utils.h" -#include "ui/gfx/insets.h" -#include "ui/gfx/text_elider.h" -#include "ui/gfx/text_utils.h" -#include "ui/gfx/utf16_indexing.h" -#include "ui/native_theme/native_theme.h" -#include "ui/views/background.h" - -namespace { - -const int kCachedSizeLimit = 10; -const base::char16 kPasswordReplacementChar = '*'; - -} // namespace - -namespace views { - -// static -const char Label::kViewClassName[] = "Label"; -const int Label::kFocusBorderPadding = 1; - -Label::Label() { - Init(base::string16(), gfx::FontList()); -} - -Label::Label(const base::string16& text) { - Init(text, gfx::FontList()); -} - -Label::Label(const base::string16& text, const gfx::FontList& font_list) { - Init(text, font_list); -} - -Label::~Label() { -} - -void Label::SetFontList(const gfx::FontList& font_list) { - font_list_ = font_list; - ResetCachedSize(); - PreferredSizeChanged(); - SchedulePaint(); -} - -void Label::SetText(const base::string16& text) { - if (text != text_) - SetTextInternal(text); -} - -void Label::SetTextInternal(const base::string16& text) { - text_ = text; - - if (obscured_) { - size_t obscured_text_length = - static_cast<size_t>(gfx::UTF16IndexToOffset(text_, 0, text_.length())); - layout_text_.assign(obscured_text_length, kPasswordReplacementChar); - } else { - layout_text_ = text_; - } - - ResetCachedSize(); - PreferredSizeChanged(); - SchedulePaint(); -} - -void Label::SetAutoColorReadabilityEnabled(bool enabled) { - auto_color_readability_ = enabled; - RecalculateColors(); -} - -void Label::SetEnabledColor(SkColor color) { - requested_enabled_color_ = color; - enabled_color_set_ = true; - RecalculateColors(); -} - -void Label::SetDisabledColor(SkColor color) { - requested_disabled_color_ = color; - disabled_color_set_ = true; - RecalculateColors(); -} - -void Label::SetBackgroundColor(SkColor color) { - background_color_ = color; - background_color_set_ = true; - RecalculateColors(); -} - -void Label::SetShadows(const gfx::ShadowValues& shadows) { - shadows_ = shadows; - text_size_valid_ = false; -} - -void Label::SetSubpixelRenderingEnabled(bool subpixel_rendering_enabled) { - subpixel_rendering_enabled_ = subpixel_rendering_enabled; -} - -void Label::SetHorizontalAlignment(gfx::HorizontalAlignment alignment) { - // If the UI layout is right-to-left, flip the alignment direction. - if (base::i18n::IsRTL() && - (alignment == gfx::ALIGN_LEFT || alignment == gfx::ALIGN_RIGHT)) { - alignment = (alignment == gfx::ALIGN_LEFT) ? - gfx::ALIGN_RIGHT : gfx::ALIGN_LEFT; - } - if (horizontal_alignment_ != alignment) { - horizontal_alignment_ = alignment; - SchedulePaint(); - } -} - -gfx::HorizontalAlignment Label::GetHorizontalAlignment() const { - if (horizontal_alignment_ != gfx::ALIGN_TO_HEAD) - return horizontal_alignment_; - - const base::i18n::TextDirection dir = - base::i18n::GetFirstStrongCharacterDirection(layout_text_); - return dir == base::i18n::RIGHT_TO_LEFT ? gfx::ALIGN_RIGHT : gfx::ALIGN_LEFT; -} - -void Label::SetLineHeight(int height) { - if (height != line_height_) { - line_height_ = height; - ResetCachedSize(); - PreferredSizeChanged(); - SchedulePaint(); - } -} - -void Label::SetMultiLine(bool multi_line) { - DCHECK(!multi_line || (elide_behavior_ == gfx::ELIDE_TAIL || - elide_behavior_ == gfx::NO_ELIDE)); - if (multi_line != multi_line_) { - multi_line_ = multi_line; - ResetCachedSize(); - PreferredSizeChanged(); - SchedulePaint(); - } -} - -void Label::SetObscured(bool obscured) { - if (obscured != obscured_) { - obscured_ = obscured; - SetTextInternal(text_); - } -} - -void Label::SetAllowCharacterBreak(bool allow_character_break) { - if (allow_character_break != allow_character_break_) { - allow_character_break_ = allow_character_break; - ResetCachedSize(); - PreferredSizeChanged(); - SchedulePaint(); - } -} - -void Label::SetElideBehavior(gfx::ElideBehavior elide_behavior) { - DCHECK(!multi_line_ || (elide_behavior_ == gfx::ELIDE_TAIL || - elide_behavior_ == gfx::NO_ELIDE)); - if (elide_behavior != elide_behavior_) { - elide_behavior_ = elide_behavior; - ResetCachedSize(); - PreferredSizeChanged(); - SchedulePaint(); - } -} - -void Label::SetTooltipText(const base::string16& tooltip_text) { - DCHECK(handles_tooltips_); - tooltip_text_ = tooltip_text; -} - -void Label::SetHandlesTooltips(bool enabled) { - handles_tooltips_ = enabled; -} - -void Label::SizeToFit(int max_width) { - DCHECK(multi_line_); - - std::vector<base::string16> lines; - base::SplitString(layout_text_, '\n', &lines); - - int label_width = 0; - for (std::vector<base::string16>::const_iterator iter = lines.begin(); - iter != lines.end(); ++iter) { - label_width = std::max(label_width, gfx::GetStringWidth(*iter, font_list_)); - } - - label_width += GetInsets().width(); - - if (max_width > 0) - label_width = std::min(label_width, max_width); - - SetBounds(x(), y(), label_width, 0); - SizeToPreferredSize(); -} - -const base::string16& Label::GetLayoutTextForTesting() const { - return layout_text_; -} - -gfx::Insets Label::GetInsets() const { - gfx::Insets insets = View::GetInsets(); - if (focusable()) { - insets += gfx::Insets(kFocusBorderPadding, kFocusBorderPadding, - kFocusBorderPadding, kFocusBorderPadding); - } - return insets; -} - -int Label::GetBaseline() const { - return GetInsets().top() + font_list_.GetBaseline(); -} - -gfx::Size Label::GetPreferredSize() const { - // Return a size of (0, 0) if the label is not visible and if the - // collapse_when_hidden_ flag is set. - // TODO(munjal): This logic probably belongs to the View class. But for now, - // put it here since putting it in View class means all inheriting classes - // need ot respect the collapse_when_hidden_ flag. - if (!visible() && collapse_when_hidden_) - return gfx::Size(); - - gfx::Size size(GetTextSize()); - gfx::Insets insets = GetInsets(); - size.Enlarge(insets.width(), insets.height()); - return size; -} - -gfx::Size Label::GetMinimumSize() const { - gfx::Size text_size(GetTextSize()); - if ((!visible() && collapse_when_hidden_) || text_size.IsEmpty()) - return gfx::Size(); - - gfx::Size size(gfx::GetStringWidth(base::string16(gfx::kEllipsisUTF16), - font_list_), - font_list_.GetHeight()); - size.SetToMin(text_size); // The actual text may be shorter than an ellipsis. - gfx::Insets insets = GetInsets(); - size.Enlarge(insets.width(), insets.height()); - return size; -} - -int Label::GetHeightForWidth(int w) const { - if (!multi_line_) - return View::GetHeightForWidth(w); - - w = std::max(0, w - GetInsets().width()); - - for (size_t i = 0; i < cached_heights_.size(); ++i) { - const gfx::Size& s = cached_heights_[i]; - if (s.width() == w) - return s.height() + GetInsets().height(); - } - - int cache_width = w; - - int h = font_list_.GetHeight(); - const int flags = ComputeDrawStringFlags(); - gfx::Canvas::SizeStringInt( - layout_text_, font_list_, &w, &h, line_height_, flags); - cached_heights_[cached_heights_cursor_] = gfx::Size(cache_width, h); - cached_heights_cursor_ = (cached_heights_cursor_ + 1) % kCachedSizeLimit; - return h + GetInsets().height(); -} - -const char* Label::GetClassName() const { - return kViewClassName; -} - -View* Label::GetTooltipHandlerForPoint(const gfx::Point& point) { - if (!handles_tooltips_ || - (tooltip_text_.empty() && !ShouldShowDefaultTooltip())) - return NULL; - - return HitTestPoint(point) ? this : NULL; -} - -bool Label::CanProcessEventsWithinSubtree() const { - // Send events to the parent view for handling. - return false; -} - -void Label::GetAccessibleState(ui::AXViewState* state) { - state->role = ui::AX_ROLE_STATIC_TEXT; - state->AddStateFlag(ui::AX_STATE_READ_ONLY); - state->name = layout_text_; -} - -bool Label::GetTooltipText(const gfx::Point& p, base::string16* tooltip) const { - if (!handles_tooltips_) - return false; - - if (!tooltip_text_.empty()) { - tooltip->assign(tooltip_text_); - return true; - } - - if (ShouldShowDefaultTooltip()) { - *tooltip = layout_text_; - return true; - } - - return false; -} - -void Label::PaintText(gfx::Canvas* canvas, - const base::string16& text, - const gfx::Rect& text_bounds, - int flags) { - SkColor color = enabled() ? actual_enabled_color_ : actual_disabled_color_; - if (elide_behavior_ == gfx::FADE_TAIL) { - canvas->DrawFadedString(text, font_list_, color, text_bounds, flags); - } else { - canvas->DrawStringRectWithShadows(text, font_list_, color, text_bounds, - line_height_, flags, shadows_); - } - - if (HasFocus()) { - gfx::Rect focus_bounds = text_bounds; - focus_bounds.Inset(-kFocusBorderPadding, -kFocusBorderPadding); - canvas->DrawFocusRect(focus_bounds); - } -} - -gfx::Size Label::GetTextSize() const { - if (!text_size_valid_) { - // For single-line strings, we supply the largest possible width, because - // while adding NO_ELLIPSIS to the flags works on Windows for forcing - // SizeStringInt() to calculate the desired width, it doesn't seem to work - // on Linux. - int w = multi_line_ ? - GetAvailableRect().width() : std::numeric_limits<int>::max(); - int h = font_list_.GetHeight(); - // For single-line strings, ignore the available width and calculate how - // wide the text wants to be. - int flags = ComputeDrawStringFlags(); - if (!multi_line_) - flags |= gfx::Canvas::NO_ELLIPSIS; - gfx::Canvas::SizeStringInt( - layout_text_, font_list_, &w, &h, line_height_, flags); - text_size_.SetSize(w, h); - const gfx::Insets shadow_margin = -gfx::ShadowValue::GetMargin(shadows_); - text_size_.Enlarge(shadow_margin.width(), shadow_margin.height()); - text_size_valid_ = true; - } - - return text_size_; -} - -void Label::OnBoundsChanged(const gfx::Rect& previous_bounds) { - text_size_valid_ &= !multi_line_; -} - -void Label::OnPaint(gfx::Canvas* canvas) { - OnPaintBackground(canvas); - // We skip painting the focus border because it is being handled seperately by - // some subclasses of Label. We do not want View's focus border painting to - // interfere with that. - OnPaintBorder(canvas); - - base::string16 paint_text; - gfx::Rect text_bounds; - int flags = 0; - CalculateDrawStringParams(&paint_text, &text_bounds, &flags); - PaintText(canvas, paint_text, text_bounds, flags); -} - -void Label::OnNativeThemeChanged(const ui::NativeTheme* theme) { - UpdateColorsFromTheme(theme); -} - -void Label::Init(const base::string16& text, const gfx::FontList& font_list) { - font_list_ = font_list; - enabled_color_set_ = disabled_color_set_ = background_color_set_ = false; - subpixel_rendering_enabled_ = true; - auto_color_readability_ = true; - UpdateColorsFromTheme(ui::NativeTheme::instance()); - horizontal_alignment_ = gfx::ALIGN_CENTER; - line_height_ = 0; - multi_line_ = false; - obscured_ = false; - allow_character_break_ = false; - elide_behavior_ = gfx::ELIDE_TAIL; - handles_tooltips_ = true; - collapse_when_hidden_ = false; - cached_heights_.resize(kCachedSizeLimit); - ResetCachedSize(); - - SetText(text); -} - -void Label::RecalculateColors() { - actual_enabled_color_ = auto_color_readability_ ? - color_utils::GetReadableColor(requested_enabled_color_, - background_color_) : - requested_enabled_color_; - actual_disabled_color_ = auto_color_readability_ ? - color_utils::GetReadableColor(requested_disabled_color_, - background_color_) : - requested_disabled_color_; -} - -gfx::Rect Label::GetTextBounds() const { - gfx::Rect available(GetAvailableRect()); - gfx::Size text_size(GetTextSize()); - text_size.set_width(std::min(available.width(), text_size.width())); - gfx::Point origin(GetInsets().left(), GetInsets().top()); - switch (GetHorizontalAlignment()) { - case gfx::ALIGN_LEFT: - break; - case gfx::ALIGN_CENTER: - // Put any extra margin pixel on the left to match the legacy behavior - // from the use of GetTextExtentPoint32() on Windows. - origin.Offset((available.width() + 1 - text_size.width()) / 2, 0); - break; - case gfx::ALIGN_RIGHT: - origin.set_x(available.right() - text_size.width()); - break; - default: - NOTREACHED(); - break; - } - text_size.set_height(available.height()); - return gfx::Rect(origin, text_size); -} - -int Label::ComputeDrawStringFlags() const { - int flags = 0; - - // We can't use subpixel rendering if the background is non-opaque. - if (SkColorGetA(background_color_) != 0xFF || !subpixel_rendering_enabled_) - flags |= gfx::Canvas::NO_SUBPIXEL_RENDERING; - - base::i18n::TextDirection direction = - base::i18n::GetFirstStrongCharacterDirection(layout_text_); - if (direction == base::i18n::RIGHT_TO_LEFT) - flags |= gfx::Canvas::FORCE_RTL_DIRECTIONALITY; - else - flags |= gfx::Canvas::FORCE_LTR_DIRECTIONALITY; - - switch (GetHorizontalAlignment()) { - case gfx::ALIGN_LEFT: - flags |= gfx::Canvas::TEXT_ALIGN_LEFT; - break; - case gfx::ALIGN_CENTER: - flags |= gfx::Canvas::TEXT_ALIGN_CENTER; - break; - case gfx::ALIGN_RIGHT: - flags |= gfx::Canvas::TEXT_ALIGN_RIGHT; - break; - default: - NOTREACHED(); - break; - } - - if (!multi_line_) - return flags; - - flags |= gfx::Canvas::MULTI_LINE; -#if !defined(OS_WIN) - // Don't elide multiline labels on Linux. - // Todo(davemoore): Do we depend on eliding multiline text? - // Pango insists on limiting the number of lines to one if text is - // elided. You can get around this if you can pass a maximum height - // but we don't currently have that data when we call the pango code. - flags |= gfx::Canvas::NO_ELLIPSIS; -#endif - if (allow_character_break_) - flags |= gfx::Canvas::CHARACTER_BREAK; - - return flags; -} - -gfx::Rect Label::GetAvailableRect() const { - gfx::Rect bounds(size()); - bounds.Inset(GetInsets()); - return bounds; -} - -void Label::CalculateDrawStringParams(base::string16* paint_text, - gfx::Rect* text_bounds, - int* flags) const { - DCHECK(paint_text && text_bounds && flags); - - const bool forbid_ellipsis = elide_behavior_ == gfx::NO_ELIDE || - elide_behavior_ == gfx::FADE_TAIL; - if (multi_line_ || forbid_ellipsis) { - *paint_text = layout_text_; - } else { - *paint_text = gfx::ElideText(layout_text_, font_list_, - GetAvailableRect().width(), elide_behavior_); - } - - *text_bounds = GetTextBounds(); - *flags = ComputeDrawStringFlags(); - // TODO(msw): Elide multi-line text with ElideRectangleText instead. - if (!multi_line_ || forbid_ellipsis) - *flags |= gfx::Canvas::NO_ELLIPSIS; -} - -void Label::UpdateColorsFromTheme(const ui::NativeTheme* theme) { - if (!enabled_color_set_) { - requested_enabled_color_ = theme->GetSystemColor( - ui::NativeTheme::kColorId_LabelEnabledColor); - } - if (!disabled_color_set_) { - requested_disabled_color_ = theme->GetSystemColor( - ui::NativeTheme::kColorId_LabelDisabledColor); - } - if (!background_color_set_) { - background_color_ = theme->GetSystemColor( - ui::NativeTheme::kColorId_LabelBackgroundColor); - } - RecalculateColors(); -} - -void Label::ResetCachedSize() { - text_size_valid_ = false; - cached_heights_cursor_ = 0; - for (int i = 0; i < kCachedSizeLimit; ++i) - cached_heights_[i] = gfx::Size(); -} - -bool Label::ShouldShowDefaultTooltip() const { - const gfx::Size text_size = GetTextSize(); - const gfx::Size size = GetContentsBounds().size(); - return !obscured() && (text_size.width() > size.width() || - (multi_line_ && text_size.height() > size.height())); -} - -} // namespace views
diff --git a/ui/views/controls/label.h b/ui/views/controls/label.h deleted file mode 100644 index 727b6db..0000000 --- a/ui/views/controls/label.h +++ /dev/null
@@ -1,229 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_LABEL_H_ -#define UI_VIEWS_CONTROLS_LABEL_H_ - -#include <string> -#include <vector> - -#include "base/compiler_specific.h" -#include "base/gtest_prod_util.h" -#include "base/strings/string16.h" -#include "third_party/skia/include/core/SkColor.h" -#include "ui/gfx/font_list.h" -#include "ui/gfx/shadow_value.h" -#include "ui/gfx/text_constants.h" -#include "ui/views/view.h" - -namespace views { - -// A view subclass that can display a string. -class VIEWS_EXPORT Label : public View { - public: - // Internal class name. - static const char kViewClassName[]; - - // The padding for the focus border when rendering focused text. - static const int kFocusBorderPadding; - - Label(); - explicit Label(const base::string16& text); - Label(const base::string16& text, const gfx::FontList& font_list); - virtual ~Label(); - - // Gets or sets the fonts used by this label. - const gfx::FontList& font_list() const { return font_list_; } - virtual void SetFontList(const gfx::FontList& font_list); - - // Get or set the label text. - const base::string16& text() const { return text_; } - virtual void SetText(const base::string16& text); - - // Enables or disables auto-color-readability (enabled by default). If this - // is enabled, then calls to set any foreground or background color will - // trigger an automatic mapper that uses color_utils::GetReadableColor() to - // ensure that the foreground colors are readable over the background color. - void SetAutoColorReadabilityEnabled(bool enabled); - - // Sets the color. This will automatically force the color to be readable - // over the current background color, if auto color readability is enabled. - virtual void SetEnabledColor(SkColor color); - void SetDisabledColor(SkColor color); - - SkColor enabled_color() const { return actual_enabled_color_; } - - // Sets the background color. This won't be explicitly drawn, but the label - // will force the text color to be readable over it. - void SetBackgroundColor(SkColor color); - SkColor background_color() const { return background_color_; } - - // Set drop shadows underneath the text. - void SetShadows(const gfx::ShadowValues& shadows); - const gfx::ShadowValues& shadows() const { return shadows_; } - - // Sets whether subpixel rendering is used; the default is true, but this - // feature also requires an opaque background color. - void SetSubpixelRenderingEnabled(bool subpixel_rendering_enabled); - - // Sets the horizontal alignment; the argument value is mirrored in RTL UI. - void SetHorizontalAlignment(gfx::HorizontalAlignment alignment); - gfx::HorizontalAlignment GetHorizontalAlignment() const; - - // Get or set the distance in pixels between baselines of multi-line text. - // Default is 0, indicating the distance between lines should be the standard - // one for the label's text, font list, and platform. - int line_height() const { return line_height_; } - void SetLineHeight(int height); - - // Get or set if the label text can wrap on multiple lines; default is false. - bool multi_line() const { return multi_line_; } - void SetMultiLine(bool multi_line); - - // Get or set if the label text should be obscured before rendering (e.g. - // should "Password!" display as "*********"); default is false. - bool obscured() const { return obscured_; } - void SetObscured(bool obscured); - - // Sets whether multi-line text can wrap mid-word; the default is false. - void SetAllowCharacterBreak(bool allow_character_break); - - // Sets the eliding or fading behavior, applied as necessary. The default is - // to elide at the end. Eliding is not well supported for multi-line labels. - void SetElideBehavior(gfx::ElideBehavior elide_behavior); - - // Sets the tooltip text. Default behavior for a label (single-line) is to - // show the full text if it is wider than its bounds. Calling this overrides - // the default behavior and lets you set a custom tooltip. To revert to - // default behavior, call this with an empty string. - void SetTooltipText(const base::string16& tooltip_text); - - // Get or set whether this label can act as a tooltip handler; the default is - // true. Set to false whenever an ancestor view should handle tooltips - // instead. - bool handles_tooltips() const { return handles_tooltips_; } - void SetHandlesTooltips(bool enabled); - - // Resizes the label so its width is set to the width of the longest line and - // its height deduced accordingly. - // This is only intended for multi-line labels and is useful when the label's - // text contains several lines separated with \n. - // |max_width| is the maximum width that will be used (longer lines will be - // wrapped). If 0, no maximum width is enforced. - void SizeToFit(int max_width); - - // Sets whether the preferred size is empty when the label is not visible. - void set_collapse_when_hidden(bool value) { collapse_when_hidden_ = value; } - - // Get the text as displayed to the user, respecting the obscured flag. - const base::string16& GetLayoutTextForTesting() const; - - // View: - virtual gfx::Insets GetInsets() const override; - virtual int GetBaseline() const override; - virtual gfx::Size GetPreferredSize() const override; - virtual gfx::Size GetMinimumSize() const override; - virtual int GetHeightForWidth(int w) const override; - virtual const char* GetClassName() const override; - virtual View* GetTooltipHandlerForPoint(const gfx::Point& point) override; - virtual bool CanProcessEventsWithinSubtree() const override; - virtual void GetAccessibleState(ui::AXViewState* state) override; - virtual bool GetTooltipText(const gfx::Point& p, - base::string16* tooltip) const override; - - protected: - // Called by Paint to paint the text. - void PaintText(gfx::Canvas* canvas, - const base::string16& text, - const gfx::Rect& text_bounds, - int flags); - - virtual gfx::Size GetTextSize() const; - - SkColor disabled_color() const { return actual_disabled_color_; } - - // View: - virtual void OnBoundsChanged(const gfx::Rect& previous_bounds) override; - virtual void OnPaint(gfx::Canvas* canvas) override; - virtual void OnNativeThemeChanged(const ui::NativeTheme* theme) override; - - private: - // These tests call CalculateDrawStringParams in order to verify the - // calculations done for drawing text. - FRIEND_TEST_ALL_PREFIXES(LabelTest, DrawSingleLineString); - FRIEND_TEST_ALL_PREFIXES(LabelTest, DrawMultiLineString); - FRIEND_TEST_ALL_PREFIXES(LabelTest, DrawSingleLineStringInRTL); - FRIEND_TEST_ALL_PREFIXES(LabelTest, DrawMultiLineStringInRTL); - FRIEND_TEST_ALL_PREFIXES(LabelTest, DirectionalityFromText); - FRIEND_TEST_ALL_PREFIXES(LabelTest, DisableSubpixelRendering); - - // Sets both |text_| and |layout_text_| to appropriate values, taking - // the label's 'obscured' status into account. - void SetTextInternal(const base::string16& text); - - void Init(const base::string16& text, const gfx::FontList& font_list); - - void RecalculateColors(); - - // Returns where the text is drawn, in the receivers coordinate system. - gfx::Rect GetTextBounds() const; - - int ComputeDrawStringFlags() const; - - gfx::Rect GetAvailableRect() const; - - // Returns parameters to be used for the DrawString call. - void CalculateDrawStringParams(base::string16* paint_text, - gfx::Rect* text_bounds, - int* flags) const; - - // Updates any colors that have not been explicitly set from the theme. - void UpdateColorsFromTheme(const ui::NativeTheme* theme); - - // Resets |cached_heights_| and |cached_heights_cursor_| and mark - // |text_size_valid_| as false. - void ResetCachedSize(); - - bool ShouldShowDefaultTooltip() const; - - base::string16 text_; - base::string16 layout_text_; - gfx::FontList font_list_; - SkColor requested_enabled_color_; - SkColor actual_enabled_color_; - SkColor requested_disabled_color_; - SkColor actual_disabled_color_; - SkColor background_color_; - - // Set to true once the corresponding setter is invoked. - bool enabled_color_set_; - bool disabled_color_set_; - bool background_color_set_; - - bool subpixel_rendering_enabled_; - bool auto_color_readability_; - mutable gfx::Size text_size_; - mutable bool text_size_valid_; - int line_height_; - bool multi_line_; - bool obscured_; - bool allow_character_break_; - gfx::ElideBehavior elide_behavior_; - gfx::HorizontalAlignment horizontal_alignment_; - base::string16 tooltip_text_; - bool handles_tooltips_; - // Whether to collapse the label when it's not visible. - bool collapse_when_hidden_; - gfx::ShadowValues shadows_; - - // The cached heights to avoid recalculation in GetHeightForWidth(). - mutable std::vector<gfx::Size> cached_heights_; - mutable int cached_heights_cursor_; - - DISALLOW_COPY_AND_ASSIGN(Label); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_LABEL_H_
diff --git a/ui/views/controls/label_unittest.cc b/ui/views/controls/label_unittest.cc deleted file mode 100644 index 076ec46..0000000 --- a/ui/views/controls/label_unittest.cc +++ /dev/null
@@ -1,959 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/label.h" - -#include "base/i18n/rtl.h" -#include "base/strings/utf_string_conversions.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/accessibility/ax_view_state.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/gfx/canvas.h" -#include "ui/views/border.h" -#include "ui/views/test/views_test_base.h" -#include "ui/views/widget/widget.h" - -using base::ASCIIToUTF16; - -namespace views { - -typedef ViewsTestBase LabelTest; - -// All text sizing measurements (width and height) should be greater than this. -const int kMinTextDimension = 4; - -// A test utility function to set the application default text direction. -void SetRTL(bool rtl) { - // Override the current locale/direction. - base::i18n::SetICUDefaultLocale(rtl ? "he" : "en"); - EXPECT_EQ(rtl, base::i18n::IsRTL()); -} - -TEST_F(LabelTest, FontPropertySymbol) { - Label label; - std::string font_name("symbol"); - gfx::Font font(font_name, 26); - label.SetFontList(gfx::FontList(font)); - gfx::Font font_used = label.font_list().GetPrimaryFont(); - EXPECT_EQ(font_name, font_used.GetFontName()); - EXPECT_EQ(26, font_used.GetFontSize()); -} - -TEST_F(LabelTest, FontPropertyArial) { - Label label; - std::string font_name("arial"); - gfx::Font font(font_name, 30); - label.SetFontList(gfx::FontList(font)); - gfx::Font font_used = label.font_list().GetPrimaryFont(); - EXPECT_EQ(font_name, font_used.GetFontName()); - EXPECT_EQ(30, font_used.GetFontSize()); -} - -TEST_F(LabelTest, TextProperty) { - Label label; - base::string16 test_text(ASCIIToUTF16("A random string.")); - label.SetText(test_text); - EXPECT_EQ(test_text, label.text()); -} - -TEST_F(LabelTest, ColorProperty) { - Label label; - SkColor color = SkColorSetARGB(20, 40, 10, 5); - label.SetAutoColorReadabilityEnabled(false); - label.SetEnabledColor(color); - EXPECT_EQ(color, label.enabled_color()); -} - -TEST_F(LabelTest, AlignmentProperty) { - const bool was_rtl = base::i18n::IsRTL(); - - Label label; - for (size_t i = 0; i < 2; ++i) { - // Toggle the application default text direction (to try each direction). - SetRTL(!base::i18n::IsRTL()); - bool reverse_alignment = base::i18n::IsRTL(); - - // The alignment should be flipped in RTL UI. - label.SetHorizontalAlignment(gfx::ALIGN_RIGHT); - EXPECT_EQ(reverse_alignment ? gfx::ALIGN_LEFT : gfx::ALIGN_RIGHT, - label.GetHorizontalAlignment()); - label.SetHorizontalAlignment(gfx::ALIGN_LEFT); - EXPECT_EQ(reverse_alignment ? gfx::ALIGN_RIGHT : gfx::ALIGN_LEFT, - label.GetHorizontalAlignment()); - label.SetHorizontalAlignment(gfx::ALIGN_CENTER); - EXPECT_EQ(gfx::ALIGN_CENTER, label.GetHorizontalAlignment()); - - for (size_t j = 0; j < 2; ++j) { - label.SetHorizontalAlignment(gfx::ALIGN_TO_HEAD); - const bool rtl = j == 0; - label.SetText(rtl ? base::WideToUTF16(L"\x5d0") : ASCIIToUTF16("A")); - EXPECT_EQ(rtl ? gfx::ALIGN_RIGHT : gfx::ALIGN_LEFT, - label.GetHorizontalAlignment()); - } - } - - EXPECT_EQ(was_rtl, base::i18n::IsRTL()); -} - -TEST_F(LabelTest, MultiLineProperty) { - Label label; - EXPECT_FALSE(label.multi_line()); - label.SetMultiLine(true); - EXPECT_TRUE(label.multi_line()); - label.SetMultiLine(false); - EXPECT_FALSE(label.multi_line()); -} - -TEST_F(LabelTest, ObscuredProperty) { - Label label; - base::string16 test_text(ASCIIToUTF16("Password!")); - label.SetText(test_text); - - // The text should be unobscured by default. - EXPECT_FALSE(label.obscured()); - EXPECT_EQ(test_text, label.GetLayoutTextForTesting()); - EXPECT_EQ(test_text, label.text()); - - label.SetObscured(true); - EXPECT_TRUE(label.obscured()); - EXPECT_EQ(ASCIIToUTF16("*********"), label.GetLayoutTextForTesting()); - EXPECT_EQ(test_text, label.text()); - - label.SetText(test_text + test_text); - EXPECT_EQ(ASCIIToUTF16("******************"), - label.GetLayoutTextForTesting()); - EXPECT_EQ(test_text + test_text, label.text()); - - label.SetObscured(false); - EXPECT_FALSE(label.obscured()); - EXPECT_EQ(test_text + test_text, label.GetLayoutTextForTesting()); - EXPECT_EQ(test_text + test_text, label.text()); -} - -TEST_F(LabelTest, ObscuredSurrogatePair) { - // 'MUSICAL SYMBOL G CLEF': represented in UTF-16 as two characters - // forming the surrogate pair 0x0001D11E. - Label label; - base::string16 test_text = base::UTF8ToUTF16("\xF0\x9D\x84\x9E"); - label.SetText(test_text); - - label.SetObscured(true); - EXPECT_EQ(ASCIIToUTF16("*"), label.GetLayoutTextForTesting()); - EXPECT_EQ(test_text, label.text()); -} - -TEST_F(LabelTest, TooltipProperty) { - Label label; - label.SetText(ASCIIToUTF16("My cool string.")); - - // Initially, label has no bounds, its text does not fit, and therefore its - // text should be returned as the tooltip text. - base::string16 tooltip; - EXPECT_TRUE(label.GetTooltipText(gfx::Point(), &tooltip)); - EXPECT_EQ(label.text(), tooltip); - - // While tooltip handling is disabled, GetTooltipText() should fail. - label.SetHandlesTooltips(false); - EXPECT_FALSE(label.GetTooltipText(gfx::Point(), &tooltip)); - label.SetHandlesTooltips(true); - - // When set, custom tooltip text should be returned instead of the label's - // text. - base::string16 tooltip_text(ASCIIToUTF16("The tooltip!")); - label.SetTooltipText(tooltip_text); - EXPECT_TRUE(label.GetTooltipText(gfx::Point(), &tooltip)); - EXPECT_EQ(tooltip_text, tooltip); - - // While tooltip handling is disabled, GetTooltipText() should fail. - label.SetHandlesTooltips(false); - EXPECT_FALSE(label.GetTooltipText(gfx::Point(), &tooltip)); - label.SetHandlesTooltips(true); - - // When the tooltip text is set to an empty string, the original behavior is - // restored. - label.SetTooltipText(base::string16()); - EXPECT_TRUE(label.GetTooltipText(gfx::Point(), &tooltip)); - EXPECT_EQ(label.text(), tooltip); - - // While tooltip handling is disabled, GetTooltipText() should fail. - label.SetHandlesTooltips(false); - EXPECT_FALSE(label.GetTooltipText(gfx::Point(), &tooltip)); - label.SetHandlesTooltips(true); - - // Make the label big enough to hold the text - // and expect there to be no tooltip. - label.SetBounds(0, 0, 1000, 40); - EXPECT_FALSE(label.GetTooltipText(gfx::Point(), &tooltip)); - - // Shrinking the single-line label's height shouldn't trigger a tooltip. - label.SetBounds(0, 0, 1000, label.GetPreferredSize().height() / 2); - EXPECT_FALSE(label.GetTooltipText(gfx::Point(), &tooltip)); - - // Verify that explicitly set tooltip text is shown, regardless of size. - label.SetTooltipText(tooltip_text); - EXPECT_TRUE(label.GetTooltipText(gfx::Point(), &tooltip)); - EXPECT_EQ(tooltip_text, tooltip); - // Clear out the explicitly set tooltip text. - label.SetTooltipText(base::string16()); - - // Shrink the bounds and the tooltip should come back. - label.SetBounds(0, 0, 10, 10); - EXPECT_TRUE(label.GetTooltipText(gfx::Point(), &tooltip)); - - // Make the label obscured and there is no tooltip. - label.SetObscured(true); - EXPECT_FALSE(label.GetTooltipText(gfx::Point(), &tooltip)); - - // Obscuring the text shouldn't permanently clobber the tooltip. - label.SetObscured(false); - EXPECT_TRUE(label.GetTooltipText(gfx::Point(), &tooltip)); - - // Making the label multiline shouldn't eliminate the tooltip. - label.SetMultiLine(true); - EXPECT_TRUE(label.GetTooltipText(gfx::Point(), &tooltip)); - // Expanding the multiline label bounds should eliminate the tooltip. - label.SetBounds(0, 0, 1000, 1000); - EXPECT_FALSE(label.GetTooltipText(gfx::Point(), &tooltip)); - - // Verify that setting the tooltip still shows it. - label.SetTooltipText(tooltip_text); - EXPECT_TRUE(label.GetTooltipText(gfx::Point(), &tooltip)); - EXPECT_EQ(tooltip_text, tooltip); - // Clear out the tooltip. - label.SetTooltipText(base::string16()); -} - -TEST_F(LabelTest, Accessibility) { - Label label; - label.SetText(ASCIIToUTF16("My special text.")); - - ui::AXViewState state; - label.GetAccessibleState(&state); - EXPECT_EQ(ui::AX_ROLE_STATIC_TEXT, state.role); - EXPECT_EQ(label.text(), state.name); - EXPECT_TRUE(state.HasStateFlag(ui::AX_STATE_READ_ONLY)); -} - -TEST_F(LabelTest, EmptyLabelSizing) { - Label label; - const gfx::Size expected_size(0, gfx::FontList().GetHeight()); - EXPECT_EQ(expected_size, label.GetPreferredSize()); - label.SetMultiLine(!label.multi_line()); - EXPECT_EQ(expected_size, label.GetPreferredSize()); -} - -TEST_F(LabelTest, SingleLineSizing) { - Label label; - label.SetText(ASCIIToUTF16("A not so random string in one line.")); - const gfx::Size size = label.GetPreferredSize(); - EXPECT_GT(size.height(), kMinTextDimension); - EXPECT_GT(size.width(), kMinTextDimension); - - // Setting a size smaller than preferred should not change the preferred size. - label.SetSize(gfx::Size(size.width() / 2, size.height() / 2)); - EXPECT_EQ(size, label.GetPreferredSize()); - - const gfx::Insets border(10, 20, 30, 40); - label.SetBorder(Border::CreateEmptyBorder( - border.top(), border.left(), border.bottom(), border.right())); - const gfx::Size size_with_border = label.GetPreferredSize(); - EXPECT_EQ(size_with_border.height(), size.height() + border.height()); - EXPECT_EQ(size_with_border.width(), size.width() + border.width()); -} - -TEST_F(LabelTest, MultilineSmallAvailableWidthSizing) { - Label label; - label.SetMultiLine(true); - label.SetAllowCharacterBreak(true); - label.SetText(ASCIIToUTF16("Too Wide.")); - - // Check that Label can be laid out at a variety of small sizes, - // splitting the words into up to one character per line if necessary. - // Incorrect word splitting may cause infinite loops in text layout. - gfx::Size required_size = label.GetPreferredSize(); - for (int i = 1; i < required_size.width(); ++i) - EXPECT_GT(label.GetHeightForWidth(i), 0); -} - -TEST_F(LabelTest, MultiLineSizing) { - Label label; - label.SetFocusable(false); - label.SetText( - ASCIIToUTF16("A random string\nwith multiple lines\nand returns!")); - label.SetMultiLine(true); - - // GetPreferredSize - gfx::Size required_size = label.GetPreferredSize(); - EXPECT_GT(required_size.height(), kMinTextDimension); - EXPECT_GT(required_size.width(), kMinTextDimension); - - // SizeToFit with unlimited width. - label.SizeToFit(0); - int required_width = label.GetLocalBounds().width(); - EXPECT_GT(required_width, kMinTextDimension); - - // SizeToFit with limited width. - label.SizeToFit(required_width - 1); - int constrained_width = label.GetLocalBounds().width(); -#if defined(OS_WIN) - // Canvas::SizeStringInt (in ui/gfx/canvas_linux.cc) - // has to be fixed to return the size that fits to given width/height. - EXPECT_LT(constrained_width, required_width); -#endif - EXPECT_GT(constrained_width, kMinTextDimension); - - // Change the width back to the desire width. - label.SizeToFit(required_width); - EXPECT_EQ(required_width, label.GetLocalBounds().width()); - - // General tests for GetHeightForWidth. - int required_height = label.GetHeightForWidth(required_width); - EXPECT_GT(required_height, kMinTextDimension); - int height_for_constrained_width = label.GetHeightForWidth(constrained_width); -#if defined(OS_WIN) - // Canvas::SizeStringInt (in ui/gfx/canvas_linux.cc) - // has to be fixed to return the size that fits to given width/height. - EXPECT_GT(height_for_constrained_width, required_height); -#endif - // Using the constrained width or the required_width - 1 should give the - // same result for the height because the constrainted width is the tight - // width when given "required_width - 1" as the max width. - EXPECT_EQ(height_for_constrained_width, - label.GetHeightForWidth(required_width - 1)); - - // Test everything with borders. - gfx::Insets border(10, 20, 30, 40); - label.SetBorder(Border::CreateEmptyBorder( - border.top(), border.left(), border.bottom(), border.right())); - - // SizeToFit and borders. - label.SizeToFit(0); - int required_width_with_border = label.GetLocalBounds().width(); - EXPECT_EQ(required_width_with_border, required_width + border.width()); - - // GetHeightForWidth and borders. - int required_height_with_border = - label.GetHeightForWidth(required_width_with_border); - EXPECT_EQ(required_height_with_border, required_height + border.height()); - - // Test that the border width is subtracted before doing the height - // calculation. If it is, then the height will grow when width - // is shrunk. - int height1 = label.GetHeightForWidth(required_width_with_border - 1); -#if defined(OS_WIN) - // Canvas::SizeStringInt (in ui/gfx/canvas_linux.cc) - // has to be fixed to return the size that fits to given width/height. - EXPECT_GT(height1, required_height_with_border); -#endif - EXPECT_EQ(height1, height_for_constrained_width + border.height()); - - // GetPreferredSize and borders. - label.SetBounds(0, 0, 0, 0); - gfx::Size required_size_with_border = label.GetPreferredSize(); - EXPECT_EQ(required_size_with_border.height(), - required_size.height() + border.height()); - EXPECT_EQ(required_size_with_border.width(), - required_size.width() + border.width()); -} - -TEST_F(LabelTest, DirectionalityFromText) { - Label label; - label.SetBounds(0, 0, 1000, 1000); - base::string16 paint_text; - gfx::Rect text_bounds; - int flags = -1; - - // Test text starts with RTL character. - label.SetText(base::WideToUTF16(L" \x5d0\x5d1\x5d2 abc")); - label.CalculateDrawStringParams(&paint_text, &text_bounds, &flags); - EXPECT_EQ(gfx::Canvas::FORCE_RTL_DIRECTIONALITY, - flags & (gfx::Canvas::FORCE_RTL_DIRECTIONALITY | - gfx::Canvas::FORCE_LTR_DIRECTIONALITY)); - - // Test text starts with LTR character. - label.SetText(base::WideToUTF16(L"ltr \x5d0\x5d1\x5d2 abc")); - label.CalculateDrawStringParams(&paint_text, &text_bounds, &flags); - EXPECT_EQ(gfx::Canvas::FORCE_LTR_DIRECTIONALITY, - flags & (gfx::Canvas::FORCE_RTL_DIRECTIONALITY | - gfx::Canvas::FORCE_LTR_DIRECTIONALITY)); -} - -TEST_F(LabelTest, DrawSingleLineString) { - Label label; - label.SetFocusable(false); - - label.SetText(ASCIIToUTF16("Here's a string with no returns.")); - gfx::Size required_size(label.GetPreferredSize()); - gfx::Size extra(22, 8); - label.SetBounds(0, 0, required_size.width() + extra.width(), - required_size.height() + extra.height()); - - // Do some basic verifications for all three alignments. - base::string16 paint_text; - gfx::Rect text_bounds; - int flags = -1; - - // Centered text. - label.CalculateDrawStringParams(&paint_text, &text_bounds, &flags); - EXPECT_EQ(label.text(), paint_text); - // The text should be centered horizontally and vertically. - EXPECT_EQ(extra.width() / 2, text_bounds.x()); - EXPECT_EQ(0, text_bounds.y()); - EXPECT_EQ(required_size.width(), text_bounds.width()); - EXPECT_EQ(label.height(), text_bounds.height()); - EXPECT_EQ(gfx::Canvas::TEXT_ALIGN_CENTER, - flags & (gfx::Canvas::TEXT_ALIGN_LEFT | - gfx::Canvas::TEXT_ALIGN_CENTER | - gfx::Canvas::TEXT_ALIGN_RIGHT)); - - // Left aligned text. - label.SetHorizontalAlignment(gfx::ALIGN_LEFT); - paint_text.clear(); - text_bounds.SetRect(0, 0, 0, 0); - label.CalculateDrawStringParams(&paint_text, &text_bounds, &flags); - EXPECT_EQ(label.text(), paint_text); - // The text should be left aligned horizontally and centered vertically. - EXPECT_EQ(0, text_bounds.x()); - EXPECT_EQ(0, text_bounds.y()); - EXPECT_EQ(required_size.width(), text_bounds.width()); - EXPECT_EQ(label.height(), text_bounds.height()); - EXPECT_EQ(gfx::Canvas::TEXT_ALIGN_LEFT, - flags & (gfx::Canvas::TEXT_ALIGN_LEFT | - gfx::Canvas::TEXT_ALIGN_CENTER | - gfx::Canvas::TEXT_ALIGN_RIGHT)); - - // Right aligned text. - label.SetHorizontalAlignment(gfx::ALIGN_RIGHT); - paint_text.clear(); - text_bounds.SetRect(0, 0, 0, 0); - label.CalculateDrawStringParams(&paint_text, &text_bounds, &flags); - EXPECT_EQ(label.text(), paint_text); - // The text should be right aligned horizontally and centered vertically. - EXPECT_EQ(extra.width(), text_bounds.x()); - EXPECT_EQ(0, text_bounds.y()); - EXPECT_EQ(required_size.width(), text_bounds.width()); - EXPECT_EQ(label.height(), text_bounds.height()); - EXPECT_EQ(gfx::Canvas::TEXT_ALIGN_RIGHT, - flags & (gfx::Canvas::TEXT_ALIGN_LEFT | - gfx::Canvas::TEXT_ALIGN_CENTER | - gfx::Canvas::TEXT_ALIGN_RIGHT)); - - // Test single line drawing with a border. - gfx::Insets border(39, 34, 8, 96); - label.SetBorder(Border::CreateEmptyBorder( - border.top(), border.left(), border.bottom(), border.right())); - - gfx::Size required_size_with_border(label.GetPreferredSize()); - EXPECT_EQ(required_size.width() + border.width(), - required_size_with_border.width()); - EXPECT_EQ(required_size.height() + border.height(), - required_size_with_border.height()); - label.SetBounds(0, 0, required_size_with_border.width() + extra.width(), - required_size_with_border.height() + extra.height()); - - // Centered text with border. - label.SetHorizontalAlignment(gfx::ALIGN_CENTER); - paint_text.clear(); - text_bounds.SetRect(0, 0, 0, 0); - label.CalculateDrawStringParams(&paint_text, &text_bounds, &flags); - EXPECT_EQ(label.text(), paint_text); - // The text should be centered horizontally and vertically within the border. - EXPECT_EQ(border.left() + extra.width() / 2, text_bounds.x()); - EXPECT_EQ(border.top(), text_bounds.y()); - EXPECT_EQ(required_size.width(), text_bounds.width()); - EXPECT_EQ(label.GetContentsBounds().height(), text_bounds.height()); - EXPECT_EQ(gfx::Canvas::TEXT_ALIGN_CENTER, - flags & (gfx::Canvas::TEXT_ALIGN_LEFT | - gfx::Canvas::TEXT_ALIGN_CENTER | - gfx::Canvas::TEXT_ALIGN_RIGHT)); - - // Left aligned text with border. - label.SetHorizontalAlignment(gfx::ALIGN_LEFT); - paint_text.clear(); - text_bounds.SetRect(0, 0, 0, 0); - label.CalculateDrawStringParams(&paint_text, &text_bounds, &flags); - EXPECT_EQ(label.text(), paint_text); - // The text should be left aligned horizontally and centered vertically. - EXPECT_EQ(border.left(), text_bounds.x()); - EXPECT_EQ(border.top(), text_bounds.y()); - EXPECT_EQ(required_size.width(), text_bounds.width()); - EXPECT_EQ(label.GetContentsBounds().height(), text_bounds.height()); - EXPECT_EQ(gfx::Canvas::TEXT_ALIGN_LEFT, - flags & (gfx::Canvas::TEXT_ALIGN_LEFT | - gfx::Canvas::TEXT_ALIGN_CENTER | - gfx::Canvas::TEXT_ALIGN_RIGHT)); - - // Right aligned text. - label.SetHorizontalAlignment(gfx::ALIGN_RIGHT); - paint_text.clear(); - text_bounds.SetRect(0, 0, 0, 0); - label.CalculateDrawStringParams(&paint_text, &text_bounds, &flags); - EXPECT_EQ(label.text(), paint_text); - // The text should be right aligned horizontally and centered vertically. - EXPECT_EQ(border.left() + extra.width(), text_bounds.x()); - EXPECT_EQ(border.top(), text_bounds.y()); - EXPECT_EQ(required_size.width(), text_bounds.width()); - EXPECT_EQ(label.GetContentsBounds().height(), text_bounds.height()); - EXPECT_EQ(gfx::Canvas::TEXT_ALIGN_RIGHT, - flags & (gfx::Canvas::TEXT_ALIGN_LEFT | - gfx::Canvas::TEXT_ALIGN_CENTER | - gfx::Canvas::TEXT_ALIGN_RIGHT)); -} - -// Pango needs a max height to elide multiline text; that is not supported here. -TEST_F(LabelTest, DrawMultiLineString) { - Label label; - label.SetFocusable(false); - // Set a background color to prevent gfx::Canvas::NO_SUBPIXEL_RENDERING flags. - label.SetBackgroundColor(SK_ColorWHITE); - - label.SetText(ASCIIToUTF16("Another string\nwith returns\n\n!")); - label.SetMultiLine(true); - label.SizeToFit(0); - gfx::Size extra(50, 10); - label.SetBounds(label.x(), label.y(), - label.width() + extra.width(), - label.height() + extra.height()); - - // Do some basic verifications for all three alignments. - base::string16 paint_text; - gfx::Rect text_bounds; - int flags = -1; - label.CalculateDrawStringParams(&paint_text, &text_bounds, &flags); - EXPECT_EQ(label.text(), paint_text); - EXPECT_EQ(extra.width() / 2, text_bounds.x()); - EXPECT_EQ(0, text_bounds.y()); - EXPECT_GT(text_bounds.width(), kMinTextDimension); - EXPECT_EQ(text_bounds.height(), label.height()); - int expected_flags = gfx::Canvas::MULTI_LINE | - gfx::Canvas::TEXT_ALIGN_CENTER | - gfx::Canvas::FORCE_LTR_DIRECTIONALITY; -#if !defined(OS_WIN) - expected_flags |= gfx::Canvas::NO_ELLIPSIS; -#endif - EXPECT_EQ(expected_flags, expected_flags); - gfx::Rect center_bounds(text_bounds); - - label.SetHorizontalAlignment(gfx::ALIGN_LEFT); - paint_text.clear(); - text_bounds.SetRect(0, 0, 0, 0); - label.CalculateDrawStringParams(&paint_text, &text_bounds, &flags); - EXPECT_EQ(label.text(), paint_text); - EXPECT_EQ(0, text_bounds.x()); - EXPECT_EQ(0, text_bounds.y()); - EXPECT_GT(text_bounds.width(), kMinTextDimension); - EXPECT_EQ(text_bounds.height(), label.height()); - expected_flags = gfx::Canvas::MULTI_LINE | - gfx::Canvas::TEXT_ALIGN_LEFT | - gfx::Canvas::FORCE_LTR_DIRECTIONALITY; -#if !defined(OS_WIN) - expected_flags |= gfx::Canvas::NO_ELLIPSIS; -#endif - EXPECT_EQ(expected_flags, expected_flags); - - label.SetHorizontalAlignment(gfx::ALIGN_RIGHT); - paint_text.clear(); - text_bounds.SetRect(0, 0, 0, 0); - label.CalculateDrawStringParams(&paint_text, &text_bounds, &flags); - EXPECT_EQ(label.text(), paint_text); - EXPECT_EQ(extra.width(), text_bounds.x()); - EXPECT_EQ(0, text_bounds.y()); - EXPECT_GT(text_bounds.width(), kMinTextDimension); - EXPECT_EQ(text_bounds.height(), label.height()); - expected_flags = gfx::Canvas::MULTI_LINE | - gfx::Canvas::TEXT_ALIGN_RIGHT | - gfx::Canvas::FORCE_LTR_DIRECTIONALITY; -#if !defined(OS_WIN) - expected_flags |= gfx::Canvas::NO_ELLIPSIS; -#endif - EXPECT_EQ(expected_flags, expected_flags); - - // Test multiline drawing with a border. - gfx::Insets border(19, 92, 23, 2); - label.SetBorder(Border::CreateEmptyBorder( - border.top(), border.left(), border.bottom(), border.right())); - label.SizeToFit(0); - label.SetBounds(label.x(), label.y(), - label.width() + extra.width(), - label.height() + extra.height()); - - label.SetHorizontalAlignment(gfx::ALIGN_CENTER); - paint_text.clear(); - text_bounds.SetRect(0, 0, 0, 0); - label.CalculateDrawStringParams(&paint_text, &text_bounds, &flags); - EXPECT_EQ(label.text(), paint_text); - EXPECT_EQ(border.left() + extra.width() / 2, text_bounds.x()); - EXPECT_EQ(border.top(), text_bounds.y()); - EXPECT_EQ(center_bounds.width(), text_bounds.width()); - EXPECT_EQ(center_bounds.height(), text_bounds.height()); - expected_flags = gfx::Canvas::MULTI_LINE | - gfx::Canvas::TEXT_ALIGN_CENTER | - gfx::Canvas::FORCE_LTR_DIRECTIONALITY; -#if !defined(OS_WIN) - expected_flags |= gfx::Canvas::NO_ELLIPSIS; -#endif - EXPECT_EQ(expected_flags, expected_flags); - - label.SetHorizontalAlignment(gfx::ALIGN_LEFT); - paint_text.clear(); - text_bounds.SetRect(0, 0, 0, 0); - label.CalculateDrawStringParams(&paint_text, &text_bounds, &flags); - EXPECT_EQ(label.text(), paint_text); - EXPECT_EQ(border.left(), text_bounds.x()); - EXPECT_EQ(border.top(), text_bounds.y()); - EXPECT_EQ(center_bounds.width(), text_bounds.width()); - EXPECT_EQ(center_bounds.height(), text_bounds.height()); - expected_flags = gfx::Canvas::MULTI_LINE | - gfx::Canvas::TEXT_ALIGN_LEFT | - gfx::Canvas::FORCE_LTR_DIRECTIONALITY; -#if !defined(OS_WIN) - expected_flags |= gfx::Canvas::NO_ELLIPSIS; -#endif - EXPECT_EQ(expected_flags, expected_flags); - - label.SetHorizontalAlignment(gfx::ALIGN_RIGHT); - paint_text.clear(); - text_bounds.SetRect(0, 0, 0, 0); - label.CalculateDrawStringParams(&paint_text, &text_bounds, &flags); - EXPECT_EQ(label.text(), paint_text); - EXPECT_EQ(extra.width() + border.left(), text_bounds.x()); - EXPECT_EQ(border.top(), text_bounds.y()); - EXPECT_EQ(center_bounds.width(), text_bounds.width()); - EXPECT_EQ(center_bounds.height(), text_bounds.height()); - expected_flags = gfx::Canvas::MULTI_LINE | - gfx::Canvas::TEXT_ALIGN_RIGHT | - gfx::Canvas::FORCE_LTR_DIRECTIONALITY; -#if !defined(OS_WIN) - expected_flags |= gfx::Canvas::NO_ELLIPSIS; -#endif - EXPECT_EQ(expected_flags, expected_flags); -} - -TEST_F(LabelTest, DrawSingleLineStringInRTL) { - Label label; - label.SetFocusable(false); - - std::string locale = l10n_util::GetApplicationLocale(""); - base::i18n::SetICUDefaultLocale("he"); - - label.SetText(ASCIIToUTF16("Here's a string with no returns.")); - gfx::Size required_size(label.GetPreferredSize()); - gfx::Size extra(22, 8); - label.SetBounds(0, 0, required_size.width() + extra.width(), - required_size.height() + extra.height()); - - // Do some basic verifications for all three alignments. - base::string16 paint_text; - gfx::Rect text_bounds; - int flags = -1; - - // Centered text. - label.CalculateDrawStringParams(&paint_text, &text_bounds, &flags); - EXPECT_EQ(label.text(), paint_text); - // The text should be centered horizontally and vertically. - EXPECT_EQ(extra.width() / 2, text_bounds.x()); - EXPECT_EQ(0, text_bounds.y()); - EXPECT_EQ(required_size.width(), text_bounds.width()); - EXPECT_EQ(label.height(), text_bounds.height()); - EXPECT_EQ(gfx::Canvas::TEXT_ALIGN_CENTER, - flags & (gfx::Canvas::TEXT_ALIGN_LEFT | - gfx::Canvas::TEXT_ALIGN_CENTER | - gfx::Canvas::TEXT_ALIGN_RIGHT)); - - // ALIGN_LEFT label. - label.SetHorizontalAlignment(gfx::ALIGN_LEFT); - paint_text.clear(); - text_bounds.SetRect(0, 0, 0, 0); - label.CalculateDrawStringParams(&paint_text, &text_bounds, &flags); - EXPECT_EQ(label.text(), paint_text); - // The text should be right aligned horizontally and centered vertically. - EXPECT_EQ(extra.width(), text_bounds.x()); - EXPECT_EQ(0, text_bounds.y()); - EXPECT_EQ(required_size.width(), text_bounds.width()); - EXPECT_EQ(label.height(), text_bounds.height()); - EXPECT_EQ(gfx::Canvas::TEXT_ALIGN_RIGHT, - flags & (gfx::Canvas::TEXT_ALIGN_LEFT | - gfx::Canvas::TEXT_ALIGN_CENTER | - gfx::Canvas::TEXT_ALIGN_RIGHT)); - - // ALIGN_RIGHT label. - label.SetHorizontalAlignment(gfx::ALIGN_RIGHT); - paint_text.clear(); - text_bounds.SetRect(0, 0, 0, 0); - label.CalculateDrawStringParams(&paint_text, &text_bounds, &flags); - EXPECT_EQ(label.text(), paint_text); - // The text should be left aligned horizontally and centered vertically. - EXPECT_EQ(0, text_bounds.x()); - EXPECT_EQ(0, text_bounds.y()); - EXPECT_EQ(required_size.width(), text_bounds.width()); - EXPECT_EQ(label.height(), text_bounds.height()); - EXPECT_EQ(gfx::Canvas::TEXT_ALIGN_LEFT, - flags & (gfx::Canvas::TEXT_ALIGN_LEFT | - gfx::Canvas::TEXT_ALIGN_CENTER | - gfx::Canvas::TEXT_ALIGN_RIGHT)); - - - // Test single line drawing with a border. - gfx::Insets border(39, 34, 8, 96); - label.SetBorder(Border::CreateEmptyBorder( - border.top(), border.left(), border.bottom(), border.right())); - - gfx::Size required_size_with_border(label.GetPreferredSize()); - EXPECT_EQ(required_size.width() + border.width(), - required_size_with_border.width()); - EXPECT_EQ(required_size.height() + border.height(), - required_size_with_border.height()); - label.SetBounds(0, 0, required_size_with_border.width() + extra.width(), - required_size_with_border.height() + extra.height()); - - // Centered text with border. - label.SetHorizontalAlignment(gfx::ALIGN_CENTER); - paint_text.clear(); - text_bounds.SetRect(0, 0, 0, 0); - label.CalculateDrawStringParams(&paint_text, &text_bounds, &flags); - EXPECT_EQ(label.text(), paint_text); - // The text should be centered horizontally and vertically within the border. - EXPECT_EQ(border.left() + extra.width() / 2, text_bounds.x()); - EXPECT_EQ(border.top(), text_bounds.y()); - EXPECT_EQ(required_size.width(), text_bounds.width()); - EXPECT_EQ(label.GetContentsBounds().height(), text_bounds.height()); - EXPECT_EQ(gfx::Canvas::TEXT_ALIGN_CENTER, - flags & (gfx::Canvas::TEXT_ALIGN_LEFT | - gfx::Canvas::TEXT_ALIGN_CENTER | - gfx::Canvas::TEXT_ALIGN_RIGHT)); - - // ALIGN_LEFT text with border. - label.SetHorizontalAlignment(gfx::ALIGN_LEFT); - paint_text.clear(); - text_bounds.SetRect(0, 0, 0, 0); - label.CalculateDrawStringParams(&paint_text, &text_bounds, &flags); - EXPECT_EQ(label.text(), paint_text); - // The text should be right aligned horizontally and centered vertically. - EXPECT_EQ(border.left() + extra.width(), text_bounds.x()); - EXPECT_EQ(border.top(), text_bounds.y()); - EXPECT_EQ(required_size.width(), text_bounds.width()); - EXPECT_EQ(label.GetContentsBounds().height(), text_bounds.height()); - EXPECT_EQ(gfx::Canvas::TEXT_ALIGN_RIGHT, - flags & (gfx::Canvas::TEXT_ALIGN_LEFT | - gfx::Canvas::TEXT_ALIGN_CENTER | - gfx::Canvas::TEXT_ALIGN_RIGHT)); - - // ALIGN_RIGHT text. - label.SetHorizontalAlignment(gfx::ALIGN_RIGHT); - paint_text.clear(); - text_bounds.SetRect(0, 0, 0, 0); - label.CalculateDrawStringParams(&paint_text, &text_bounds, &flags); - EXPECT_EQ(label.text(), paint_text); - // The text should be left aligned horizontally and centered vertically. - EXPECT_EQ(border.left(), text_bounds.x()); - EXPECT_EQ(border.top(), text_bounds.y()); - EXPECT_EQ(required_size.width(), text_bounds.width()); - EXPECT_EQ(label.GetContentsBounds().height(), text_bounds.height()); - EXPECT_EQ(gfx::Canvas::TEXT_ALIGN_LEFT, - flags & (gfx::Canvas::TEXT_ALIGN_LEFT | - gfx::Canvas::TEXT_ALIGN_CENTER | - gfx::Canvas::TEXT_ALIGN_RIGHT)); - - // Reset locale. - base::i18n::SetICUDefaultLocale(locale); -} - -// On Linux the underlying pango routines require a max height in order to -// ellide multiline text. So until that can be resolved, we set all -// multiline lables to not ellide in Linux only. -TEST_F(LabelTest, DrawMultiLineStringInRTL) { - Label label; - label.SetFocusable(false); - - // Test for RTL. - std::string locale = l10n_util::GetApplicationLocale(""); - base::i18n::SetICUDefaultLocale("he"); - - label.SetText(ASCIIToUTF16("Another string\nwith returns\n\n!")); - label.SetMultiLine(true); - label.SizeToFit(0); - gfx::Size extra(50, 10); - label.SetBounds(label.x(), label.y(), - label.width() + extra.width(), - label.height() + extra.height()); - - // Do some basic verifications for all three alignments. - base::string16 paint_text; - gfx::Rect text_bounds; - int flags = -1; - label.CalculateDrawStringParams(&paint_text, &text_bounds, &flags); - EXPECT_EQ(label.text(), paint_text); - EXPECT_EQ(extra.width() / 2, text_bounds.x()); - EXPECT_EQ(0, text_bounds.y()); - EXPECT_GT(text_bounds.width(), kMinTextDimension); - EXPECT_EQ(text_bounds.height(), label.height()); - EXPECT_TRUE(gfx::Canvas::MULTI_LINE & flags); - EXPECT_TRUE(gfx::Canvas::TEXT_ALIGN_CENTER & flags); -#if !defined(OS_WIN) - EXPECT_TRUE(gfx::Canvas::NO_ELLIPSIS & flags); -#endif - gfx::Rect center_bounds(text_bounds); - - label.SetHorizontalAlignment(gfx::ALIGN_LEFT); - paint_text.clear(); - text_bounds.SetRect(0, 0, 0, 0); - label.CalculateDrawStringParams(&paint_text, &text_bounds, &flags); - EXPECT_EQ(label.text(), paint_text); - EXPECT_EQ(extra.width(), text_bounds.x()); - EXPECT_EQ(0, text_bounds.y()); - EXPECT_GT(text_bounds.width(), kMinTextDimension); - EXPECT_EQ(text_bounds.height(), label.height()); - EXPECT_TRUE(gfx::Canvas::MULTI_LINE & flags); - EXPECT_TRUE(gfx::Canvas::TEXT_ALIGN_RIGHT & flags); -#if !defined(OS_WIN) - EXPECT_TRUE(gfx::Canvas::NO_ELLIPSIS & flags); -#endif - - label.SetHorizontalAlignment(gfx::ALIGN_RIGHT); - paint_text.clear(); - text_bounds.SetRect(0, 0, 0, 0); - label.CalculateDrawStringParams(&paint_text, &text_bounds, &flags); - EXPECT_EQ(label.text(), paint_text); - EXPECT_EQ(0, text_bounds.x()); - EXPECT_EQ(0, text_bounds.y()); - EXPECT_GT(text_bounds.width(), kMinTextDimension); - EXPECT_EQ(text_bounds.height(), label.height()); - EXPECT_TRUE(gfx::Canvas::MULTI_LINE & flags); - EXPECT_TRUE(gfx::Canvas::TEXT_ALIGN_LEFT & flags); -#if !defined(OS_WIN) - EXPECT_TRUE(gfx::Canvas::NO_ELLIPSIS & flags); -#endif - - // Test multiline drawing with a border. - gfx::Insets border(19, 92, 23, 2); - label.SetBorder(Border::CreateEmptyBorder( - border.top(), border.left(), border.bottom(), border.right())); - label.SizeToFit(0); - label.SetBounds(label.x(), label.y(), - label.width() + extra.width(), - label.height() + extra.height()); - - label.SetHorizontalAlignment(gfx::ALIGN_CENTER); - paint_text.clear(); - text_bounds.SetRect(0, 0, 0, 0); - label.CalculateDrawStringParams(&paint_text, &text_bounds, &flags); - EXPECT_EQ(label.text(), paint_text); - EXPECT_EQ(border.left() + extra.width() / 2, text_bounds.x()); - EXPECT_EQ(border.top(), text_bounds.y()); - EXPECT_EQ(center_bounds.width(), text_bounds.width()); - EXPECT_EQ(label.GetContentsBounds().height(), text_bounds.height()); - EXPECT_TRUE(gfx::Canvas::MULTI_LINE & flags); - EXPECT_TRUE(gfx::Canvas::TEXT_ALIGN_CENTER & flags); -#if !defined(OS_WIN) - EXPECT_TRUE(gfx::Canvas::NO_ELLIPSIS & flags); -#endif - - label.SetHorizontalAlignment(gfx::ALIGN_LEFT); - paint_text.clear(); - text_bounds.SetRect(0, 0, 0, 0); - label.CalculateDrawStringParams(&paint_text, &text_bounds, &flags); - EXPECT_EQ(label.text(), paint_text); - EXPECT_EQ(border.left() + extra.width(), text_bounds.x()); - EXPECT_EQ(border.top(), text_bounds.y()); - EXPECT_EQ(center_bounds.width(), text_bounds.width()); - EXPECT_EQ(label.GetContentsBounds().height(), text_bounds.height()); - EXPECT_TRUE(gfx::Canvas::MULTI_LINE & flags); - EXPECT_TRUE(gfx::Canvas::TEXT_ALIGN_RIGHT & flags); -#if !defined(OS_WIN) - EXPECT_TRUE(gfx::Canvas::NO_ELLIPSIS & flags); -#endif - - label.SetHorizontalAlignment(gfx::ALIGN_RIGHT); - paint_text.clear(); - text_bounds.SetRect(0, 0, 0, 0); - label.CalculateDrawStringParams(&paint_text, &text_bounds, &flags); - EXPECT_EQ(label.text(), paint_text); - EXPECT_EQ(border.left(), text_bounds.x()); - EXPECT_EQ(border.top(), text_bounds.y()); - EXPECT_EQ(center_bounds.width(), text_bounds.width()); - EXPECT_EQ(label.GetContentsBounds().height(), text_bounds.height()); - EXPECT_TRUE(gfx::Canvas::MULTI_LINE & flags); - EXPECT_TRUE(gfx::Canvas::TEXT_ALIGN_LEFT & flags); -#if !defined(OS_WIN) - EXPECT_TRUE(gfx::Canvas::NO_ELLIPSIS & flags); -#endif - - // Reset Locale - base::i18n::SetICUDefaultLocale(locale); -} - -// Ensure the subpixel rendering flag and background color alpha are respected. -TEST_F(LabelTest, DisableSubpixelRendering) { - Label label; - label.SetBackgroundColor(SK_ColorWHITE); - const int flag = gfx::Canvas::NO_SUBPIXEL_RENDERING; - EXPECT_EQ(0, label.ComputeDrawStringFlags() & flag); - label.SetSubpixelRenderingEnabled(false); - EXPECT_EQ(flag, label.ComputeDrawStringFlags() & flag); - label.SetSubpixelRenderingEnabled(true); - EXPECT_EQ(0, label.ComputeDrawStringFlags() & flag); - // Text cannot be drawn with subpixel rendering on transparent backgrounds. - label.SetBackgroundColor(SkColorSetARGB(64, 255, 255, 255)); - EXPECT_EQ(flag, label.ComputeDrawStringFlags() & flag); -} - -// Check that labels support GetTooltipHandlerForPoint. -TEST_F(LabelTest, GetTooltipHandlerForPoint) { - // A root view must be defined for this test because the hit-testing - // behaviour used by GetTooltipHandlerForPoint() is defined by - // the ViewTargeter installed on the root view. - Widget widget; - Widget::InitParams init_params = - CreateParams(Widget::InitParams::TYPE_POPUP); - init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - init_params.bounds = gfx::Rect(0, 0, 200, 200); - widget.Init(init_params); - - Label label; - label.SetText( - ASCIIToUTF16("A string that's long enough to exceed the bounds")); - label.SetBounds(0, 0, 10, 10); - widget.SetContentsView(&label); - - // By default, labels start out as tooltip handlers. - ASSERT_TRUE(label.handles_tooltips()); - - // There's a default tooltip if the text is too big to fit. - EXPECT_EQ(&label, label.GetTooltipHandlerForPoint(gfx::Point(2, 2))); - - // If tooltip handling is disabled, the label should not provide a tooltip - // handler. - label.SetHandlesTooltips(false); - EXPECT_FALSE(label.GetTooltipHandlerForPoint(gfx::Point(2, 2))); - label.SetHandlesTooltips(true); - - // If there's no default tooltip, this should return NULL. - label.SetBounds(0, 0, 500, 50); - EXPECT_FALSE(label.GetTooltipHandlerForPoint(gfx::Point(2, 2))); - - label.SetTooltipText(ASCIIToUTF16("a tooltip")); - // If the point hits the label, and tooltip is set, the label should be - // returned as its tooltip handler. - EXPECT_EQ(&label, label.GetTooltipHandlerForPoint(gfx::Point(2, 2))); - - // Additionally, GetTooltipHandlerForPoint should verify that the label - // actually contains the point. - EXPECT_FALSE(label.GetTooltipHandlerForPoint(gfx::Point(2, 51))); - EXPECT_FALSE(label.GetTooltipHandlerForPoint(gfx::Point(-1, 20))); - - // Again, if tooltip handling is disabled, the label should not provide a - // tooltip handler. - label.SetHandlesTooltips(false); - EXPECT_FALSE(label.GetTooltipHandlerForPoint(gfx::Point(2, 2))); - EXPECT_FALSE(label.GetTooltipHandlerForPoint(gfx::Point(2, 51))); - EXPECT_FALSE(label.GetTooltipHandlerForPoint(gfx::Point(-1, 20))); - label.SetHandlesTooltips(true); - - // GetTooltipHandlerForPoint works should work in child bounds. - label.SetBounds(2, 2, 10, 10); - EXPECT_EQ(&label, label.GetTooltipHandlerForPoint(gfx::Point(1, 5))); - EXPECT_FALSE(label.GetTooltipHandlerForPoint(gfx::Point(3, 11))); -} - -} // namespace views
diff --git a/ui/views/controls/link.cc b/ui/views/controls/link.cc deleted file mode 100644 index d8a08a4..0000000 --- a/ui/views/controls/link.cc +++ /dev/null
@@ -1,229 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/link.h" - -#include "build/build_config.h" - -#include "base/logging.h" -#include "base/strings/utf_string_conversions.h" -#include "ui/accessibility/ax_view_state.h" -#include "ui/base/cursor/cursor.h" -#include "ui/events/event.h" -#include "ui/events/keycodes/keyboard_codes.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/color_utils.h" -#include "ui/gfx/font_list.h" -#include "ui/views/controls/link_listener.h" -#include "ui/views/native_cursor.h" - -namespace views { - -const char Link::kViewClassName[] = "Link"; - -Link::Link() : Label(base::string16()) { - Init(); -} - -Link::Link(const base::string16& title) : Label(title) { - Init(); -} - -Link::~Link() { -} - -SkColor Link::GetDefaultEnabledColor() { -#if defined(OS_WIN) - return color_utils::GetSysSkColor(COLOR_HOTLIGHT); -#else - return SkColorSetRGB(0, 51, 153); -#endif -} - -const char* Link::GetClassName() const { - return kViewClassName; -} - -gfx::NativeCursor Link::GetCursor(const ui::MouseEvent& event) { - if (!enabled()) - return gfx::kNullCursor; - return GetNativeHandCursor(); -} - -bool Link::CanProcessEventsWithinSubtree() const { - // Links need to be able to accept events (e.g., clicking) even though - // in general Labels do not. - return View::CanProcessEventsWithinSubtree(); -} - -bool Link::OnMousePressed(const ui::MouseEvent& event) { - if (!enabled() || - (!event.IsLeftMouseButton() && !event.IsMiddleMouseButton())) - return false; - SetPressed(true); - return true; -} - -bool Link::OnMouseDragged(const ui::MouseEvent& event) { - SetPressed(enabled() && - (event.IsLeftMouseButton() || event.IsMiddleMouseButton()) && - HitTestPoint(event.location())); - return true; -} - -void Link::OnMouseReleased(const ui::MouseEvent& event) { - // Change the highlight first just in case this instance is deleted - // while calling the controller - OnMouseCaptureLost(); - if (enabled() && - (event.IsLeftMouseButton() || event.IsMiddleMouseButton()) && - HitTestPoint(event.location())) { - // Focus the link on click. - RequestFocus(); - - if (listener_) - listener_->LinkClicked(this, event.flags()); - } -} - -void Link::OnMouseCaptureLost() { - SetPressed(false); -} - -bool Link::OnKeyPressed(const ui::KeyEvent& event) { - bool activate = ((event.key_code() == ui::VKEY_SPACE) || - (event.key_code() == ui::VKEY_RETURN)); - if (!activate) - return false; - - SetPressed(false); - - // Focus the link on key pressed. - RequestFocus(); - - if (listener_) - listener_->LinkClicked(this, event.flags()); - - return true; -} - -void Link::OnGestureEvent(ui::GestureEvent* event) { - if (!enabled()) - return; - - if (event->type() == ui::ET_GESTURE_TAP_DOWN) { - SetPressed(true); - } else if (event->type() == ui::ET_GESTURE_TAP) { - RequestFocus(); - if (listener_) - listener_->LinkClicked(this, event->flags()); - } else { - SetPressed(false); - return; - } - event->SetHandled(); -} - -bool Link::SkipDefaultKeyEventProcessing(const ui::KeyEvent& event) { - // Make sure we don't process space or enter as accelerators. - return (event.key_code() == ui::VKEY_SPACE) || - (event.key_code() == ui::VKEY_RETURN); -} - -void Link::GetAccessibleState(ui::AXViewState* state) { - Label::GetAccessibleState(state); - state->role = ui::AX_ROLE_LINK; -} - -void Link::OnEnabledChanged() { - RecalculateFont(); - View::OnEnabledChanged(); -} - -void Link::OnFocus() { - Label::OnFocus(); - // We render differently focused. - SchedulePaint(); -} - -void Link::OnBlur() { - Label::OnBlur(); - // We render differently focused. - SchedulePaint(); -} - -void Link::SetFontList(const gfx::FontList& font_list) { - Label::SetFontList(font_list); - RecalculateFont(); -} - -void Link::SetText(const base::string16& text) { - Label::SetText(text); - // Disable focusability for empty links. Otherwise Label::GetInsets() will - // give them an unconditional 1-px. inset on every side to allow for a focus - // border, when in this case we probably wanted zero width. - SetFocusable(!text.empty()); -} - -void Link::SetEnabledColor(SkColor color) { - requested_enabled_color_ = color; - if (!pressed_) - Label::SetEnabledColor(requested_enabled_color_); -} - -void Link::SetPressedColor(SkColor color) { - requested_pressed_color_ = color; - if (pressed_) - Label::SetEnabledColor(requested_pressed_color_); -} - -void Link::SetUnderline(bool underline) { - if (underline_ == underline) - return; - underline_ = underline; - RecalculateFont(); -} - -void Link::Init() { - listener_ = NULL; - pressed_ = false; - underline_ = true; - SetEnabledColor(GetDefaultEnabledColor()); -#if defined(OS_WIN) - SetDisabledColor(color_utils::GetSysSkColor(COLOR_WINDOWTEXT)); - SetPressedColor(SkColorSetRGB(200, 0, 0)); -#else - // TODO(beng): source from theme provider. - SetDisabledColor(SK_ColorBLACK); - SetPressedColor(SK_ColorRED); -#endif - RecalculateFont(); - - // Label::Init() calls SetText(), but if that's being called from Label(), our - // SetText() override will not be reached (because the constructed class is - // only a Label at the moment, not yet a Link). So so the set_focusable() - // call explicitly here. - SetFocusable(!text().empty()); -} - -void Link::SetPressed(bool pressed) { - if (pressed_ != pressed) { - pressed_ = pressed; - Label::SetEnabledColor(pressed_ ? - requested_pressed_color_ : requested_enabled_color_); - RecalculateFont(); - SchedulePaint(); - } -} - -void Link::RecalculateFont() { - // Underline the link iff it is enabled and |underline_| is true. - const int style = font_list().GetFontStyle(); - const int intended_style = (enabled() && underline_) ? - (style | gfx::Font::UNDERLINE) : (style & ~gfx::Font::UNDERLINE); - if (style != intended_style) - Label::SetFontList(font_list().DeriveWithStyle(intended_style)); -} - -} // namespace views
diff --git a/ui/views/controls/link.h b/ui/views/controls/link.h deleted file mode 100644 index 951de2d..0000000 --- a/ui/views/controls/link.h +++ /dev/null
@@ -1,87 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_LINK_H_ -#define UI_VIEWS_CONTROLS_LINK_H_ - -#include <string> - -#include "third_party/skia/include/core/SkColor.h" -#include "ui/views/controls/label.h" - -namespace views { - -class LinkListener; - -//////////////////////////////////////////////////////////////////////////////// -// -// Link class -// -// A Link is a label subclass that looks like an HTML link. It has a -// controller which is notified when a click occurs. -// -//////////////////////////////////////////////////////////////////////////////// -class VIEWS_EXPORT Link : public Label { - public: - Link(); - explicit Link(const base::string16& title); - virtual ~Link(); - - static SkColor GetDefaultEnabledColor(); - - const LinkListener* listener() { return listener_; } - void set_listener(LinkListener* listener) { listener_ = listener; } - - // Label: - virtual const char* GetClassName() const override; - virtual gfx::NativeCursor GetCursor(const ui::MouseEvent& event) override; - virtual bool CanProcessEventsWithinSubtree() const override; - virtual bool OnMousePressed(const ui::MouseEvent& event) override; - virtual bool OnMouseDragged(const ui::MouseEvent& event) override; - virtual void OnMouseReleased(const ui::MouseEvent& event) override; - virtual void OnMouseCaptureLost() override; - virtual bool OnKeyPressed(const ui::KeyEvent& event) override; - virtual void OnGestureEvent(ui::GestureEvent* event) override; - virtual bool SkipDefaultKeyEventProcessing( - const ui::KeyEvent& event) override; - virtual void GetAccessibleState(ui::AXViewState* state) override; - virtual void OnEnabledChanged() override; - virtual void OnFocus() override; - virtual void OnBlur() override; - virtual void SetFontList(const gfx::FontList& font_list) override; - virtual void SetText(const base::string16& text) override; - virtual void SetEnabledColor(SkColor color) override; - - void SetPressedColor(SkColor color); - void SetUnderline(bool underline); - - static const char kViewClassName[]; - - private: - void Init(); - - void SetPressed(bool pressed); - - void RecalculateFont(); - - LinkListener* listener_; - - // Whether the link should be underlined when enabled. - bool underline_; - - // Whether the link is currently pressed. - bool pressed_; - - // The color when the link is neither pressed nor disabled. - SkColor requested_enabled_color_; - - // The color when the link is pressed. - SkColor requested_pressed_color_; - - DISALLOW_COPY_AND_ASSIGN(Link); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_LINK_H_
diff --git a/ui/views/controls/link_listener.h b/ui/views/controls/link_listener.h deleted file mode 100644 index 99a6077..0000000 --- a/ui/views/controls/link_listener.h +++ /dev/null
@@ -1,25 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_LINK_LISTENER_H_ -#define UI_VIEWS_CONTROLS_LINK_LISTENER_H_ - -#include "ui/views/views_export.h" - -namespace views { - -class Link; - -// An interface implemented by an object to let it know that a link was clicked. -class VIEWS_EXPORT LinkListener { - public: - virtual void LinkClicked(Link* source, int event_flags) = 0; - - protected: - virtual ~LinkListener() {} -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_LINK_LISTENER_H_
diff --git a/ui/views/controls/menu/display_change_listener_aura.cc b/ui/views/controls/menu/display_change_listener_aura.cc deleted file mode 100644 index 7bab443..0000000 --- a/ui/views/controls/menu/display_change_listener_aura.cc +++ /dev/null
@@ -1,68 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/window.h" -#include "ui/aura/window_observer.h" -#include "ui/views/controls/menu/menu_runner.h" -#include "ui/views/widget/widget.h" - -namespace views { -namespace internal { - -// DisplayChangeListener implementation for aura. Cancels the menu any time the -// root window bounds change. -class AuraDisplayChangeListener - : public DisplayChangeListener, - public aura::WindowObserver { - public: - AuraDisplayChangeListener(Widget* widget, MenuRunner* menu_runner); - virtual ~AuraDisplayChangeListener(); - - // aura::WindowObserver overrides: - virtual void OnWindowBoundsChanged(aura::Window* window, - const gfx::Rect& old_bounds, - const gfx::Rect& new_bounds) override; - virtual void OnWindowDestroying(aura::Window* window) override; - - private: - MenuRunner* menu_runner_; - aura::Window* root_window_; - - DISALLOW_COPY_AND_ASSIGN(AuraDisplayChangeListener); -}; - -AuraDisplayChangeListener::AuraDisplayChangeListener(Widget* widget, - MenuRunner* menu_runner) - : menu_runner_(menu_runner), - root_window_(widget->GetNativeView()->GetRootWindow()) { - if (root_window_) - root_window_->AddObserver(this); -} - -AuraDisplayChangeListener::~AuraDisplayChangeListener() { - if (root_window_) - root_window_->RemoveObserver(this); -} - -void AuraDisplayChangeListener::OnWindowBoundsChanged( - aura::Window* window, - const gfx::Rect& old_bounds, - const gfx::Rect& new_bounds) { - menu_runner_->Cancel(); -} - -void AuraDisplayChangeListener::OnWindowDestroying(aura::Window* window) { - DCHECK_EQ(window, root_window_); - root_window_->RemoveObserver(this); - root_window_ = NULL; -} - -// static -DisplayChangeListener* DisplayChangeListener::Create(Widget* widget, - MenuRunner* runner) { - return new AuraDisplayChangeListener(widget, runner); -} - -} // namespace internal -} // namespace views
diff --git a/ui/views/controls/menu/menu.cc b/ui/views/controls/menu/menu.cc deleted file mode 100644 index 0cffae8..0000000 --- a/ui/views/controls/menu/menu.cc +++ /dev/null
@@ -1,146 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/menu/menu.h" - -#include "base/i18n/rtl.h" -#include "ui/gfx/image/image_skia.h" - -namespace views { - -bool Menu::Delegate::IsItemChecked(int id) const { - return false; -} - -bool Menu::Delegate::IsItemDefault(int id) const { - return false; -} - -base::string16 Menu::Delegate::GetLabel(int id) const { - return base::string16(); -} - -bool Menu::Delegate::GetAcceleratorInfo(int id, ui::Accelerator* accel) { - return false; -} - -const gfx::ImageSkia& Menu::Delegate::GetIcon(int id) const { - return GetEmptyIcon(); -} - -int Menu::Delegate::GetItemCount() const { - return 0; -} - -bool Menu::Delegate::IsItemSeparator(int id) const { - return false; -} - -bool Menu::Delegate::HasIcon(int id) const { - return false; -} - -bool Menu::Delegate::SupportsCommand(int id) const { - return true; -} - -bool Menu::Delegate::IsCommandEnabled(int id) const { - return true; -} - -bool Menu::Delegate::GetContextualLabel(int id, base::string16* out) const { - return false; -} - -bool Menu::Delegate::IsRightToLeftUILayout() const { - return base::i18n::IsRTL(); -} - -const gfx::ImageSkia& Menu::Delegate::GetEmptyIcon() const { - static const gfx::ImageSkia* empty_icon = new gfx::ImageSkia(); - return *empty_icon; -} - -Menu::Menu(Delegate* delegate, AnchorPoint anchor) - : delegate_(delegate), - anchor_(anchor) { -} - -Menu::Menu(Menu* parent) - : delegate_(parent->delegate_), - anchor_(parent->anchor_) { -} - -Menu::~Menu() { -} - -void Menu::AppendMenuItem(int item_id, - const base::string16& label, - MenuItemType type) { - AddMenuItem(-1, item_id, label, type); -} - -void Menu::AddMenuItem(int index, - int item_id, - const base::string16& label, - MenuItemType type) { - if (type == SEPARATOR) - AddSeparator(index); - else - AddMenuItemInternal(index, item_id, label, gfx::ImageSkia(), type); -} - -Menu* Menu::AppendSubMenu(int item_id, const base::string16& label) { - return AddSubMenu(-1, item_id, label); -} - -Menu* Menu::AddSubMenu(int index, int item_id, const base::string16& label) { - return AddSubMenuWithIcon(index, item_id, label, gfx::ImageSkia()); -} - -Menu* Menu::AppendSubMenuWithIcon(int item_id, - const base::string16& label, - const gfx::ImageSkia& icon) { - return AddSubMenuWithIcon(-1, item_id, label, icon); -} - -void Menu::AppendMenuItemWithLabel(int item_id, const base::string16& label) { - AddMenuItemWithLabel(-1, item_id, label); -} - -void Menu::AddMenuItemWithLabel(int index, - int item_id, - const base::string16& label) { - AddMenuItem(index, item_id, label, Menu::NORMAL); -} - -void Menu::AppendDelegateMenuItem(int item_id) { - AddDelegateMenuItem(-1, item_id); -} - -void Menu::AddDelegateMenuItem(int index, int item_id) { - AddMenuItem(index, item_id, base::string16(), Menu::NORMAL); -} - -void Menu::AppendSeparator() { - AddSeparator(-1); -} - -void Menu::AppendMenuItemWithIcon(int item_id, - const base::string16& label, - const gfx::ImageSkia& icon) { - AddMenuItemWithIcon(-1, item_id, label, icon); -} - -void Menu::AddMenuItemWithIcon(int index, - int item_id, - const base::string16& label, - const gfx::ImageSkia& icon) { - AddMenuItemInternal(index, item_id, label, icon, Menu::NORMAL); -} - -Menu::Menu() : delegate_(NULL), anchor_(TOPLEFT) { -} - -} // namespace views
diff --git a/ui/views/controls/menu/menu.h b/ui/views/controls/menu/menu.h deleted file mode 100644 index 099a98e..0000000 --- a/ui/views/controls/menu/menu.h +++ /dev/null
@@ -1,255 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_MENU_MENU_H_ -#define UI_VIEWS_CONTROLS_MENU_MENU_H_ - -#include <string> - -#include "base/basictypes.h" -#include "base/strings/string16.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/views/views_export.h" - -namespace gfx { -class ImageSkia; -class Point; -} - -namespace ui { -class Accelerator; -} - -namespace views { - -class VIEWS_EXPORT Menu { - public: - ///////////////////////////////////////////////////////////////////////////// - // - // Delegate Interface - // - // Classes implement this interface to tell the menu system more about each - // item as it is created. - // - ///////////////////////////////////////////////////////////////////////////// - class VIEWS_EXPORT Delegate { - public: - virtual ~Delegate() {} - - // Whether or not an item should be shown as checked. - virtual bool IsItemChecked(int id) const; - - // Whether or not an item should be shown as the default (using bold). - // There can only be one default menu item. - virtual bool IsItemDefault(int id) const; - - // The string shown for the menu item. - virtual base::string16 GetLabel(int id) const; - - // The delegate needs to implement this function if it wants to display - // the shortcut text next to each menu item. If there is an accelerator - // for a given item id, the implementor must return it. - virtual bool GetAcceleratorInfo(int id, ui::Accelerator* accel); - - // The icon shown for the menu item. - virtual const gfx::ImageSkia& GetIcon(int id) const; - - // The number of items to show in the menu - virtual int GetItemCount() const; - - // Whether or not an item is a separator. - virtual bool IsItemSeparator(int id) const; - - // Shows the context menu with the specified id. This is invoked when the - // user does the appropriate gesture to show a context menu. The id - // identifies the id of the menu to show the context menu for. - // is_mouse_gesture is true if this is the result of a mouse gesture. - // If this is not the result of a mouse gesture |p| is the recommended - // location to display the content menu at. In either case, |p| is in - // screen coordinates. - virtual void ShowContextMenu(Menu* source, - int id, - const gfx::Point& p, - bool is_mouse_gesture) { - } - - // Whether an item has an icon. - virtual bool HasIcon(int id) const; - - // Notification that the menu is about to be popped up. - virtual void MenuWillShow() { - } - - // Whether to create a right-to-left menu. The default implementation - // returns true if the locale's language is a right-to-left language (such - // as Hebrew) and false otherwise. This is generally the right behavior - // since there is no reason to show left-to-right menus for right-to-left - // locales. However, subclasses can override this behavior so that the menu - // is a right-to-left menu only if the view's layout is right-to-left - // (since the view can use a different layout than the locale's language - // layout). - virtual bool IsRightToLeftUILayout() const; - - // Controller - virtual bool SupportsCommand(int id) const; - virtual bool IsCommandEnabled(int id) const; - virtual bool GetContextualLabel(int id, base::string16* out) const; - virtual void ExecuteCommand(int id) { - } - - protected: - // Returns an empty icon. - const gfx::ImageSkia& GetEmptyIcon() const; - }; - - // How this popup should align itself relative to the point it is run at. - enum AnchorPoint { - TOPLEFT, - TOPRIGHT - }; - - // Different types of menu items - enum MenuItemType { - NORMAL, - CHECKBOX, - RADIO, - SEPARATOR - }; - - // Construct a Menu using the specified controller to determine command - // state. - // delegate A Menu::Delegate implementation that provides more - // information about the Menu presentation. - // anchor An alignment hint for the popup menu. - // owner The window that the menu is being brought up relative - // to. Not actually used for anything but must not be - // NULL. - Menu(Delegate* delegate, AnchorPoint anchor); - Menu(); - virtual ~Menu(); - - static Menu* Create(Delegate* delegate, - AnchorPoint anchor, - gfx::NativeView parent); - - // Creates a new menu with the contents of the system menu for the given - // parent window. The caller owns the returned pointer. - static Menu* GetSystemMenu(gfx::NativeWindow parent); - - void set_delegate(Delegate* delegate) { delegate_ = delegate; } - Delegate* delegate() const { return delegate_; } - - AnchorPoint anchor() const { return anchor_; } - - // Adds an item to this menu. - // item_id The id of the item, used to identify it in delegate callbacks - // or (if delegate is NULL) to identify the command associated - // with this item with the controller specified in the ctor. Note - // that this value should not be 0 as this has a special meaning - // ("NULL command, no item selected") - // label The text label shown. - // type The type of item. - void AppendMenuItem(int item_id, - const base::string16& label, - MenuItemType type); - void AddMenuItem(int index, - int item_id, - const base::string16& label, - MenuItemType type); - - // Append a submenu to this menu. - // The returned pointer is owned by this menu. - Menu* AppendSubMenu(int item_id, - const base::string16& label); - Menu* AddSubMenu(int index, int item_id, const base::string16& label); - - // Append a submenu with an icon to this menu - // The returned pointer is owned by this menu. - // Unless the icon is empty, calling this function forces the Menu class - // to draw the menu, instead of relying on Windows. - Menu* AppendSubMenuWithIcon(int item_id, - const base::string16& label, - const gfx::ImageSkia& icon); - virtual Menu* AddSubMenuWithIcon(int index, - int item_id, - const base::string16& label, - const gfx::ImageSkia& icon) = 0; - - // This is a convenience for standard text label menu items where the label - // is provided with this call. - void AppendMenuItemWithLabel(int item_id, const base::string16& label); - void AddMenuItemWithLabel(int index, - int item_id, - const base::string16& label); - - // This is a convenience for text label menu items where the label is - // provided by the delegate. - void AppendDelegateMenuItem(int item_id); - void AddDelegateMenuItem(int index, int item_id); - - // Adds a separator to this menu - void AppendSeparator(); - virtual void AddSeparator(int index) = 0; - - // Appends a menu item with an icon. This is for the menu item which - // needs an icon. Calling this function forces the Menu class to draw - // the menu, instead of relying on Windows. - void AppendMenuItemWithIcon(int item_id, - const base::string16& label, - const gfx::ImageSkia& icon); - virtual void AddMenuItemWithIcon(int index, - int item_id, - const base::string16& label, - const gfx::ImageSkia& icon); - - // Enables or disables the item with the specified id. - virtual void EnableMenuItemByID(int item_id, bool enabled) = 0; - virtual void EnableMenuItemAt(int index, bool enabled) = 0; - - // Sets menu label at specified index. - virtual void SetMenuLabel(int item_id, const base::string16& label) = 0; - - // Sets an icon for an item with a given item_id. Calling this function - // also forces the Menu class to draw the menu, instead of relying on Windows. - // Returns false if the item with |item_id| is not found. - virtual bool SetIcon(const gfx::ImageSkia& icon, int item_id) = 0; - - // Shows the menu, blocks until the user dismisses the menu or selects an - // item, and executes the command for the selected item (if any). - // Warning: Blocking call. Will implicitly run a message loop. - virtual void RunMenuAt(int x, int y) = 0; - - // Cancels the menu. - virtual void Cancel() = 0; - - // Returns the number of menu items. - virtual int ItemCount() = 0; - -#if defined(OS_WIN) - // Returns the underlying menu handle - virtual HMENU GetMenuHandle() const = 0; -#endif // defined(OS_WIN) - - protected: - explicit Menu(Menu* parent); - - virtual void AddMenuItemInternal(int index, - int item_id, - const base::string16& label, - const gfx::ImageSkia& icon, - MenuItemType type) = 0; - - private: - // The delegate that is being used to get information about the presentation. - Delegate* delegate_; - - // How this popup menu should be aligned relative to the point it is run at. - AnchorPoint anchor_; - - DISALLOW_COPY_AND_ASSIGN(Menu); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_MENU_MENU_H_
diff --git a/ui/views/controls/menu/menu_2.cc b/ui/views/controls/menu/menu_2.cc deleted file mode 100644 index 21bf323..0000000 --- a/ui/views/controls/menu/menu_2.cc +++ /dev/null
@@ -1,60 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/menu/menu_2.h" - -#include "ui/base/models/menu_model.h" -#include "ui/views/controls/menu/menu_listener.h" - -namespace views { - -Menu2::Menu2(ui::MenuModel* model) - : model_(model), - wrapper_(MenuWrapper::CreateWrapper(model)) { - Rebuild(); -} - -Menu2::~Menu2() {} - -HMENU Menu2::GetNativeMenu() const { - return wrapper_->GetNativeMenu(); -} - -void Menu2::RunMenuAt(const gfx::Point& point, Alignment alignment) { - wrapper_->RunMenuAt(point, alignment); -} - -void Menu2::RunContextMenuAt(const gfx::Point& point) { - RunMenuAt(point, ALIGN_TOPLEFT); -} - -void Menu2::CancelMenu() { - wrapper_->CancelMenu(); -} - -void Menu2::Rebuild() { - wrapper_->Rebuild(NULL); -} - -void Menu2::UpdateStates() { - wrapper_->UpdateStates(); -} - -MenuWrapper::MenuAction Menu2::GetMenuAction() const { - return wrapper_->GetMenuAction(); -} - -void Menu2::AddMenuListener(MenuListener* listener) { - wrapper_->AddMenuListener(listener); -} - -void Menu2::RemoveMenuListener(MenuListener* listener) { - wrapper_->RemoveMenuListener(listener); -} - -void Menu2::SetMinimumWidth(int width) { - wrapper_->SetMinimumWidth(width); -} - -} // namespace
diff --git a/ui/views/controls/menu/menu_2.h b/ui/views/controls/menu/menu_2.h deleted file mode 100644 index 9c857b2..0000000 --- a/ui/views/controls/menu/menu_2.h +++ /dev/null
@@ -1,96 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_MENU_MENU_2_H_ -#define UI_VIEWS_CONTROLS_MENU_MENU_2_H_ - -#include "base/basictypes.h" -#include "base/memory/scoped_ptr.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/views/controls/menu/menu_wrapper.h" -#include "ui/views/views_export.h" - -namespace gfx { -class Point; -} - -namespace ui { -class MenuModel; -} - -namespace views { - -// A menu. Populated from a model, and relies on a delegate to execute commands. -// -// WARNING: do NOT create and use Menu2 on the stack. Menu2 notifies the model -// of selection AFTER a delay. This means that if use a Menu2 on the stack -// ActivatedAt is never invoked. -class VIEWS_EXPORT Menu2 { - public: - // How the menu is aligned relative to the point it is shown at. - // The alignment is reversed by menu if text direction is right to left. - enum Alignment { - ALIGN_TOPLEFT, - ALIGN_TOPRIGHT - }; - - // Creates a new menu populated with the contents of |model|. - // WARNING: this populates the menu on construction by invoking methods on - // the model. As such, it is typically not safe to use this as the model - // from the constructor. EG: - // MyClass : menu_(this) {} - // is likely to have problems. - explicit Menu2(ui::MenuModel* model); - virtual ~Menu2(); - - // Runs the menu at the specified point. This method blocks until done. - // RunContextMenuAt is the same, but the alignment is the default for a - // context menu. - void RunMenuAt(const gfx::Point& point, Alignment alignment); - void RunContextMenuAt(const gfx::Point& point); - - // Cancels the active menu. - void CancelMenu(); - - // Called when the model supplying data to this menu has changed, and the menu - // must be rebuilt. - void Rebuild(); - - // Called when the states of the menu items in the menu should be refreshed - // from the model. - void UpdateStates(); - - // For submenus. - HMENU GetNativeMenu() const; - - // Get the result of the last call to RunMenuAt to determine whether an - // item was selected, the user navigated to a next or previous menu, or - // nothing. - MenuWrapper::MenuAction GetMenuAction() const; - - // Add a listener to receive a callback when the menu opens. - void AddMenuListener(MenuListener* listener); - - // Remove a menu listener. - void RemoveMenuListener(MenuListener* listener); - - // Accessors. - ui::MenuModel* model() const { return model_; } - - // Sets the minimum width of the menu. - void SetMinimumWidth(int width); - - private: - - ui::MenuModel* model_; - - // The object that actually implements the menu. - scoped_ptr<MenuWrapper> wrapper_; - - DISALLOW_COPY_AND_ASSIGN(Menu2); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_MENU_MENU_2_H_
diff --git a/ui/views/controls/menu/menu_config.cc b/ui/views/controls/menu/menu_config.cc deleted file mode 100644 index 9eaba83..0000000 --- a/ui/views/controls/menu/menu_config.cc +++ /dev/null
@@ -1,51 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/menu/menu_config.h" - -#include "build/build_config.h" - -namespace views { - -MenuConfig::MenuConfig(const ui::NativeTheme* theme) - : arrow_color(SK_ColorBLACK), - menu_vertical_border_size(3), - menu_horizontal_border_size(0), - submenu_horizontal_inset(3), - item_top_margin(4), - item_bottom_margin(3), - item_no_icon_top_margin(4), - item_no_icon_bottom_margin(4), - item_left_margin(10), - label_to_arrow_padding(10), - arrow_to_edge_padding(5), - icon_to_label_padding(10), - gutter_to_label(5), - check_width(16), - check_height(16), - radio_width(16), - arrow_width(9), - gutter_width(0), - separator_height(11), - separator_upper_height(3), - separator_lower_height(4), - separator_spacing_height(3), - render_gutter(false), - show_mnemonics(false), - scroll_arrow_height(3), - label_to_minor_text_padding(10), - item_min_height(0), - show_accelerators(true), - always_use_icon_to_label_padding(false), - align_arrow_and_shortcut(false), - offset_context_menus(false), - native_theme(theme), - show_delay(400), - corner_radius(0) { - Init(theme); -} - -MenuConfig::~MenuConfig() {} - -} // namespace views
diff --git a/ui/views/controls/menu/menu_config.h b/ui/views/controls/menu/menu_config.h deleted file mode 100644 index 3cdbccd..0000000 --- a/ui/views/controls/menu/menu_config.h +++ /dev/null
@@ -1,139 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_MENU_MENU_CONFIG_H_ -#define UI_VIEWS_CONTROLS_MENU_MENU_CONFIG_H_ - -#include "third_party/skia/include/core/SkColor.h" -#include "ui/gfx/font_list.h" -#include "ui/views/views_export.h" - -namespace ui { -class NativeTheme; -} - -namespace views { - -// Layout type information for menu items. Use the instance() method to obtain -// the MenuConfig for the current platform. -struct VIEWS_EXPORT MenuConfig { - explicit MenuConfig(const ui::NativeTheme* theme); - ~MenuConfig(); - - static const MenuConfig& instance(const ui::NativeTheme* theme); - - // Font list used by menus. - gfx::FontList font_list; - - // Color for the arrow to scroll bookmarks. - SkColor arrow_color; - - // Menu border sizes. - int menu_vertical_border_size; - int menu_horizontal_border_size; - - // Submenu horizontal inset with parent menu. This is the horizontal overlap - // between the submenu and its parent menu, not including the borders of - // submenu and parent menu. - int submenu_horizontal_inset; - - // Margins between the top of the item and the label. - int item_top_margin; - - // Margins between the bottom of the item and the label. - int item_bottom_margin; - - // Margins used if the menu doesn't have icons. - int item_no_icon_top_margin; - int item_no_icon_bottom_margin; - - // Margins between the left of the item and the icon. - int item_left_margin; - - // Padding between the label and submenu arrow. - int label_to_arrow_padding; - - // Padding between the arrow and the edge. - int arrow_to_edge_padding; - - // Padding between the icon and label. - int icon_to_label_padding; - - // Padding between the gutter and label. - int gutter_to_label; - - // Size of the check. - int check_width; - int check_height; - - // Width of the radio bullet. - int radio_width; - - // Width of the submenu arrow. - int arrow_width; - - // Width of the gutter. Only used if render_gutter is true. - int gutter_width; - - // Height of a normal separator (ui::NORMAL_SEPARATOR). - int separator_height; - - // Height of a ui::UPPER_SEPARATOR. - int separator_upper_height; - - // Height of a ui::LOWER_SEPARATOR. - int separator_lower_height; - - // Height of a ui::SPACING_SEPARATOR. - int separator_spacing_height; - - // Whether or not the gutter should be rendered. The gutter is specific to - // Vista. - bool render_gutter; - - // Are mnemonics shown? - bool show_mnemonics; - - // Height of the scroll arrow. - int scroll_arrow_height; - - // Padding between the label and minor text. Only used if there is an - // accelerator or sublabel. - int label_to_minor_text_padding; - - // Minimum height of menu item. - int item_min_height; - - // Whether the keyboard accelerators are visible. - bool show_accelerators; - - // True if icon to label padding is always added with or without icon. - bool always_use_icon_to_label_padding; - - // True if submenu arrow and shortcut right edge should be aligned. - bool align_arrow_and_shortcut; - - // True if the context menu's should be offset from the cursor position. - bool offset_context_menus; - - const ui::NativeTheme* native_theme; - - // Delay, in ms, between when menus are selected or moused over and the menu - // appears. - int show_delay; - - // Radius of the rounded corners of the menu border. Must be >= 0. - int corner_radius; - - private: - // Configures a MenuConfig as appropriate for the current platform. - void Init(const ui::NativeTheme* theme); - - // TODO: temporary until we standardize. - void InitAura(const ui::NativeTheme* theme); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_MENU_MENU_CONFIG_H_
diff --git a/ui/views/controls/menu/menu_config_aura.cc b/ui/views/controls/menu/menu_config_aura.cc deleted file mode 100644 index 911e3fa..0000000 --- a/ui/views/controls/menu/menu_config_aura.cc +++ /dev/null
@@ -1,62 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/menu/menu_config.h" - -#include "ui/base/layout.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/gfx/image/image.h" -#include "ui/gfx/image/image_skia.h" -#include "ui/native_theme/native_theme_aura.h" -#include "ui/resources/grit/ui_resources.h" -#include "ui/views/controls/menu/menu_image_util.h" - -namespace views { - -namespace { -#if defined(OS_CHROMEOS) -static const int kMenuCornerRadiusForAura = 2; -#else -static const int kMenuCornerRadiusForAura = 0; -#endif -} // namespace - -#if !defined(OS_WIN) -void MenuConfig::Init(const ui::NativeTheme* theme) { - if (theme == ui::NativeThemeAura::instance()) - InitAura(theme); -} -#endif - -void MenuConfig::InitAura(const ui::NativeTheme* theme) { - submenu_horizontal_inset = 1; - arrow_to_edge_padding = 20; - ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); - arrow_width = rb.GetImageNamed(IDR_MENU_HIERARCHY_ARROW).Width(); - gfx::ImageSkia check = GetMenuCheckImage(false); - check_height = check.height(); - item_min_height = 29; - separator_spacing_height = 7; - separator_lower_height = 8; - separator_upper_height = 8; - label_to_arrow_padding = 20; - label_to_minor_text_padding = 20; - always_use_icon_to_label_padding = true; - align_arrow_and_shortcut = true; - offset_context_menus = true; - corner_radius = kMenuCornerRadiusForAura; -} - -#if !defined(OS_WIN) -// static -const MenuConfig& MenuConfig::instance(const ui::NativeTheme* theme) { - static MenuConfig* views_instance = NULL; - if (!views_instance) - views_instance = new MenuConfig(theme ? - theme : ui::NativeTheme::instance()); - return *views_instance; -} -#endif - -} // namespace views
diff --git a/ui/views/controls/menu/menu_config_win.cc b/ui/views/controls/menu/menu_config_win.cc deleted file mode 100644 index 3f17f58..0000000 --- a/ui/views/controls/menu/menu_config_win.cc +++ /dev/null
@@ -1,96 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/menu/menu_config.h" - -#include <windows.h> -#include <uxtheme.h> -#include <Vssym32.h> - -#include "base/logging.h" -#include "base/win/scoped_gdi_object.h" -#include "base/win/win_util.h" -#include "ui/base/l10n/l10n_util_win.h" -#include "ui/gfx/color_utils.h" -#include "ui/native_theme/native_theme_aura.h" -#include "ui/native_theme/native_theme_win.h" - -using ui::NativeTheme; -using ui::NativeThemeWin; - -namespace views { - -void MenuConfig::Init(const NativeTheme* theme) { - if (theme == ui::NativeThemeAura::instance()) { - InitAura(theme); - return; - } - - arrow_color = color_utils::GetSysSkColor(COLOR_MENUTEXT); - - NONCLIENTMETRICS_XP metrics; - base::win::GetNonClientMetrics(&metrics); - l10n_util::AdjustUIFont(&(metrics.lfMenuFont)); - { - base::win::ScopedHFONT new_font(CreateFontIndirect(&metrics.lfMenuFont)); - DLOG_ASSERT(new_font.Get()); - font_list = gfx::FontList(gfx::Font(new_font)); - } - NativeTheme::ExtraParams extra; - extra.menu_check.is_radio = false; - extra.menu_check.is_selected = false; - gfx::Size check_size = NativeThemeWin::instance()->GetPartSize( - NativeTheme::kMenuCheck, NativeTheme::kNormal, extra); - if (!check_size.IsEmpty()) { - check_width = check_size.width(); - check_height = check_size.height(); - } else { - check_width = GetSystemMetrics(SM_CXMENUCHECK); - check_height = GetSystemMetrics(SM_CYMENUCHECK); - } - - extra.menu_check.is_radio = true; - gfx::Size radio_size = NativeThemeWin::instance()->GetPartSize( - NativeTheme::kMenuCheck, NativeTheme::kNormal, extra); - if (!radio_size.IsEmpty()) - radio_width = radio_size.width(); - else - radio_width = GetSystemMetrics(SM_CXMENUCHECK); - - gfx::Size arrow_size = NativeThemeWin::instance()->GetPartSize( - NativeTheme::kMenuPopupArrow, NativeTheme::kNormal, extra); - if (!arrow_size.IsEmpty()) { - arrow_width = arrow_size.width(); - } else { - // Sadly I didn't see a specify metrics for this. - arrow_width = GetSystemMetrics(SM_CXMENUCHECK); - } - - BOOL show_cues; - show_mnemonics = - (SystemParametersInfo(SPI_GETKEYBOARDCUES, 0, &show_cues, 0) && - show_cues == TRUE); - - SystemParametersInfo(SPI_GETMENUSHOWDELAY, 0, &show_delay, 0); - - separator_upper_height = 5; - separator_lower_height = 7; -} - -// static -const MenuConfig& MenuConfig::instance(const ui::NativeTheme* theme) { - // NOTE: |theme| may be NULL if used before the menu is running. - if (!theme || theme == NativeThemeWin::instance()) { - static MenuConfig* win_instance = NULL; - if (!win_instance) - win_instance = new MenuConfig(NativeThemeWin::instance()); - return *win_instance; - } - static MenuConfig* views_instance = NULL; - if (!views_instance) - views_instance = new MenuConfig(theme); - return *views_instance; -} - -} // namespace views
diff --git a/ui/views/controls/menu/menu_controller.cc b/ui/views/controls/menu/menu_controller.cc deleted file mode 100644 index 8299200..0000000 --- a/ui/views/controls/menu/menu_controller.cc +++ /dev/null
@@ -1,2315 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/menu/menu_controller.h" - -#include "base/i18n/case_conversion.h" -#include "base/i18n/rtl.h" -#include "base/strings/utf_string_conversions.h" -#include "base/time/time.h" -#include "ui/base/dragdrop/drag_utils.h" -#include "ui/base/dragdrop/os_exchange_data.h" -#include "ui/events/event.h" -#include "ui/events/event_utils.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/gfx/point.h" -#include "ui/gfx/screen.h" -#include "ui/gfx/vector2d.h" -#include "ui/native_theme/native_theme.h" -#include "ui/views/controls/button/menu_button.h" -#include "ui/views/controls/menu/menu_config.h" -#include "ui/views/controls/menu/menu_controller_delegate.h" -#include "ui/views/controls/menu/menu_host_root_view.h" -#include "ui/views/controls/menu/menu_item_view.h" -#include "ui/views/controls/menu/menu_message_loop.h" -#include "ui/views/controls/menu/menu_scroll_view_container.h" -#include "ui/views/controls/menu/submenu_view.h" -#include "ui/views/drag_utils.h" -#include "ui/views/focus/view_storage.h" -#include "ui/views/mouse_constants.h" -#include "ui/views/view.h" -#include "ui/views/view_constants.h" -#include "ui/views/views_delegate.h" -#include "ui/views/widget/root_view.h" -#include "ui/views/widget/tooltip_manager.h" -#include "ui/views/widget/widget.h" - -#if defined(OS_WIN) -#include "ui/base/win/internal_constants.h" -#include "ui/gfx/win/dpi.h" -#include "ui/views/win/hwnd_util.h" -#endif - -using base::Time; -using base::TimeDelta; -using ui::OSExchangeData; - -// Period of the scroll timer (in milliseconds). -static const int kScrollTimerMS = 30; - -// Amount of time from when the drop exits the menu and the menu is hidden. -static const int kCloseOnExitTime = 1200; - -// If a context menu is invoked by touch, we shift the menu by this offset so -// that the finger does not obscure the menu. -static const int kCenteredContextMenuYOffset = -15; - -namespace views { - -namespace { - -// When showing context menu on mouse down, the user might accidentally select -// the menu item on the subsequent mouse up. To prevent this, we add the -// following delay before the user is able to select an item. -static int menu_selection_hold_time_ms = kMinimumMsPressedToActivate; - -// The spacing offset for the bubble tip. -const int kBubbleTipSizeLeftRight = 12; -const int kBubbleTipSizeTopBottom = 11; - -// The maximum distance (in DIPS) that the mouse can be moved before it should -// trigger a mouse menu item activation (regardless of how long the menu has -// been showing). -const float kMaximumLengthMovedToActivate = 4.0f; - -// Returns true if the mnemonic of |menu| matches key. -bool MatchesMnemonic(MenuItemView* menu, base::char16 key) { - return key != 0 && menu->GetMnemonic() == key; -} - -// Returns true if |menu| doesn't have a mnemonic and first character of the its -// title is |key|. -bool TitleMatchesMnemonic(MenuItemView* menu, base::char16 key) { - if (menu->GetMnemonic()) - return false; - - base::string16 lower_title = base::i18n::ToLower(menu->title()); - return !lower_title.empty() && lower_title[0] == key; -} - -} // namespace - -// Returns the first descendant of |view| that is hot tracked. -static CustomButton* GetFirstHotTrackedView(View* view) { - if (!view) - return NULL; - CustomButton* button = CustomButton::AsCustomButton(view); - if (button) { - if (button->IsHotTracked()) - return button; - } - - for (int i = 0; i < view->child_count(); ++i) { - CustomButton* hot_view = GetFirstHotTrackedView(view->child_at(i)); - if (hot_view) - return hot_view; - } - return NULL; -} - -// Recurses through the child views of |view| returning the first view starting -// at |start| that is focusable. A value of -1 for |start| indicates to start at -// the first view (if |forward| is false, iterating starts at the last view). If -// |forward| is true the children are considered first to last, otherwise last -// to first. -static View* GetFirstFocusableView(View* view, int start, bool forward) { - if (forward) { - for (int i = start == -1 ? 0 : start; i < view->child_count(); ++i) { - View* deepest = GetFirstFocusableView(view->child_at(i), -1, forward); - if (deepest) - return deepest; - } - } else { - for (int i = start == -1 ? view->child_count() - 1 : start; i >= 0; --i) { - View* deepest = GetFirstFocusableView(view->child_at(i), -1, forward); - if (deepest) - return deepest; - } - } - return view->IsFocusable() ? view : NULL; -} - -// Returns the first child of |start| that is focusable. -static View* GetInitialFocusableView(View* start, bool forward) { - return GetFirstFocusableView(start, -1, forward); -} - -// Returns the next view after |start_at| that is focusable. Returns NULL if -// there are no focusable children of |ancestor| after |start_at|. -static View* GetNextFocusableView(View* ancestor, - View* start_at, - bool forward) { - DCHECK(ancestor->Contains(start_at)); - View* parent = start_at; - do { - View* new_parent = parent->parent(); - int index = new_parent->GetIndexOf(parent); - index += forward ? 1 : -1; - if (forward || index != -1) { - View* next = GetFirstFocusableView(new_parent, index, forward); - if (next) - return next; - } - parent = new_parent; - } while (parent != ancestor); - return NULL; -} - -// MenuScrollTask -------------------------------------------------------------- - -// MenuScrollTask is used when the SubmenuView does not all fit on screen and -// the mouse is over the scroll up/down buttons. MenuScrollTask schedules -// itself with a RepeatingTimer. When Run is invoked MenuScrollTask scrolls -// appropriately. - -class MenuController::MenuScrollTask { - public: - MenuScrollTask() : submenu_(NULL), is_scrolling_up_(false), start_y_(0) { - pixels_per_second_ = MenuItemView::pref_menu_height() * 20; - } - - void Update(const MenuController::MenuPart& part) { - if (!part.is_scroll()) { - StopScrolling(); - return; - } - DCHECK(part.submenu); - SubmenuView* new_menu = part.submenu; - bool new_is_up = (part.type == MenuController::MenuPart::SCROLL_UP); - if (new_menu == submenu_ && is_scrolling_up_ == new_is_up) - return; - - start_scroll_time_ = base::Time::Now(); - start_y_ = part.submenu->GetVisibleBounds().y(); - submenu_ = new_menu; - is_scrolling_up_ = new_is_up; - - if (!scrolling_timer_.IsRunning()) { - scrolling_timer_.Start(FROM_HERE, - TimeDelta::FromMilliseconds(kScrollTimerMS), - this, &MenuScrollTask::Run); - } - } - - void StopScrolling() { - if (scrolling_timer_.IsRunning()) { - scrolling_timer_.Stop(); - submenu_ = NULL; - } - } - - // The menu being scrolled. Returns null if not scrolling. - SubmenuView* submenu() const { return submenu_; } - - private: - void Run() { - DCHECK(submenu_); - gfx::Rect vis_rect = submenu_->GetVisibleBounds(); - const int delta_y = static_cast<int>( - (base::Time::Now() - start_scroll_time_).InMilliseconds() * - pixels_per_second_ / 1000); - vis_rect.set_y(is_scrolling_up_ ? - std::max(0, start_y_ - delta_y) : - std::min(submenu_->height() - vis_rect.height(), start_y_ + delta_y)); - submenu_->ScrollRectToVisible(vis_rect); - } - - // SubmenuView being scrolled. - SubmenuView* submenu_; - - // Direction scrolling. - bool is_scrolling_up_; - - // Timer to periodically scroll. - base::RepeatingTimer<MenuScrollTask> scrolling_timer_; - - // Time we started scrolling at. - base::Time start_scroll_time_; - - // How many pixels to scroll per second. - int pixels_per_second_; - - // Y-coordinate of submenu_view_ when scrolling started. - int start_y_; - - DISALLOW_COPY_AND_ASSIGN(MenuScrollTask); -}; - -// MenuController:SelectByCharDetails ---------------------------------------- - -struct MenuController::SelectByCharDetails { - SelectByCharDetails() - : first_match(-1), - has_multiple(false), - index_of_item(-1), - next_match(-1) { - } - - // Index of the first menu with the specified mnemonic. - int first_match; - - // If true there are multiple menu items with the same mnemonic. - bool has_multiple; - - // Index of the selected item; may remain -1. - int index_of_item; - - // If there are multiple matches this is the index of the item after the - // currently selected item whose mnemonic matches. This may remain -1 even - // though there are matches. - int next_match; -}; - -// MenuController:State ------------------------------------------------------ - -MenuController::State::State() - : item(NULL), - submenu_open(false), - anchor(MENU_ANCHOR_TOPLEFT), - context_menu(false) { -} - -MenuController::State::~State() {} - -// MenuController ------------------------------------------------------------ - -// static -MenuController* MenuController::active_instance_ = NULL; - -// static -MenuController* MenuController::GetActiveInstance() { - return active_instance_; -} - -MenuItemView* MenuController::Run(Widget* parent, - MenuButton* button, - MenuItemView* root, - const gfx::Rect& bounds, - MenuAnchorPosition position, - bool context_menu, - bool is_nested_drag, - int* result_event_flags) { - exit_type_ = EXIT_NONE; - possible_drag_ = false; - drag_in_progress_ = false; - did_initiate_drag_ = false; - closing_event_time_ = base::TimeDelta(); - menu_start_time_ = base::TimeTicks::Now(); - menu_start_mouse_press_loc_ = gfx::Point(); - - // If we are shown on mouse press, we will eat the subsequent mouse down and - // the parent widget will not be able to reset its state (it might have mouse - // capture from the mouse down). So we clear its state here. - if (parent) { - View* root_view = parent->GetRootView(); - if (root_view) { - root_view->SetMouseHandler(NULL); - const ui::Event* event = - static_cast<internal::RootView*>(root_view)->current_event(); - if (event && event->type() == ui::ET_MOUSE_PRESSED) { - gfx::Point screen_loc( - static_cast<const ui::MouseEvent*>(event)->location()); - View::ConvertPointToScreen( - static_cast<View*>(event->target()), &screen_loc); - menu_start_mouse_press_loc_ = screen_loc; - } - } - } - - bool nested_menu = showing_; - if (showing_) { - // Only support nesting of blocking_run menus, nesting of - // blocking/non-blocking shouldn't be needed. - DCHECK(blocking_run_); - - // We're already showing, push the current state. - menu_stack_.push_back( - std::make_pair(state_, make_linked_ptr(pressed_lock_.release()))); - - // The context menu should be owned by the same parent. - DCHECK_EQ(owner_, parent); - } else { - showing_ = true; - } - - // Reset current state. - pending_state_ = State(); - state_ = State(); - UpdateInitialLocation(bounds, position, context_menu); - - if (owner_) - owner_->RemoveObserver(this); - owner_ = parent; - if (owner_) - owner_->AddObserver(this); - - // Set the selection, which opens the initial menu. - SetSelection(root, SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY); - - if (!blocking_run_) { - if (!is_nested_drag) { - // Start the timer to hide the menu. This is needed as we get no - // notification when the drag has finished. - StartCancelAllTimer(); - } - return NULL; - } - - if (button) - pressed_lock_.reset(new MenuButton::PressedLock(button)); - - // Make sure Chrome doesn't attempt to shut down while the menu is showing. - if (ViewsDelegate::views_delegate) - ViewsDelegate::views_delegate->AddRef(); - - // We need to turn on nestable tasks as in some situations (pressing alt-f for - // one) the menus are run from a task. If we don't do this and are invoked - // from a task none of the tasks we schedule are processed and the menu - // appears totally broken. - message_loop_depth_++; - DCHECK_LE(message_loop_depth_, 2); - RunMessageLoop(nested_menu); - message_loop_depth_--; - - if (ViewsDelegate::views_delegate) - ViewsDelegate::views_delegate->ReleaseRef(); - - // Close any open menus. - SetSelection(NULL, SELECTION_UPDATE_IMMEDIATELY | SELECTION_EXIT); - -#if defined(OS_WIN) - // On Windows, if we select the menu item by touch and if the window at the - // location is another window on the same thread, that window gets a - // WM_MOUSEACTIVATE message and ends up activating itself, which is not - // correct. We workaround this by setting a property on the window at the - // current cursor location. We check for this property in our - // WM_MOUSEACTIVATE handler and don't activate the window if the property is - // set. - if (item_selected_by_touch_) { - item_selected_by_touch_ = false; - POINT cursor_pos; - ::GetCursorPos(&cursor_pos); - HWND window = ::WindowFromPoint(cursor_pos); - if (::GetWindowThreadProcessId(window, NULL) == - ::GetCurrentThreadId()) { - ::SetProp(window, ui::kIgnoreTouchMouseActivateForWindow, - reinterpret_cast<HANDLE>(true)); - } - } -#endif - - linked_ptr<MenuButton::PressedLock> nested_pressed_lock; - if (nested_menu) { - DCHECK(!menu_stack_.empty()); - // We're running from within a menu, restore the previous state. - // The menus are already showing, so we don't have to show them. - state_ = menu_stack_.back().first; - pending_state_ = menu_stack_.back().first; - nested_pressed_lock = menu_stack_.back().second; - menu_stack_.pop_back(); - } else { - showing_ = false; - did_capture_ = false; - } - - MenuItemView* result = result_; - // In case we're nested, reset result_. - result_ = NULL; - - if (result_event_flags) - *result_event_flags = accept_event_flags_; - - if (exit_type_ == EXIT_OUTERMOST) { - SetExitType(EXIT_NONE); - } else { - if (nested_menu && result) { - // We're nested and about to return a value. The caller might enter - // another blocking loop. We need to make sure all menus are hidden - // before that happens otherwise the menus will stay on screen. - CloseAllNestedMenus(); - SetSelection(NULL, SELECTION_UPDATE_IMMEDIATELY | SELECTION_EXIT); - - // Set exit_all_, which makes sure all nested loops exit immediately. - if (exit_type_ != EXIT_DESTROYED) - SetExitType(EXIT_ALL); - } - } - - // Reset our pressed lock to the previous state's, if there was one. - // The lock handles the case if the button was destroyed. - pressed_lock_.reset(nested_pressed_lock.release()); - - return result; -} - -void MenuController::Cancel(ExitType type) { - // If the menu has already been destroyed, no further cancellation is - // needed. We especially don't want to set the |exit_type_| to a lesser - // value. - if (exit_type_ == EXIT_DESTROYED || exit_type_ == type) - return; - - if (!showing_) { - // This occurs if we're in the process of notifying the delegate for a drop - // and the delegate cancels us. - return; - } - - MenuItemView* selected = state_.item; - SetExitType(type); - - SendMouseCaptureLostToActiveView(); - - // Hide windows immediately. - SetSelection(NULL, SELECTION_UPDATE_IMMEDIATELY | SELECTION_EXIT); - - if (!blocking_run_) { - // If we didn't block the caller we need to notify the menu, which - // triggers deleting us. - DCHECK(selected); - showing_ = false; - delegate_->DropMenuClosed( - internal::MenuControllerDelegate::NOTIFY_DELEGATE, - selected->GetRootMenuItem()); - // WARNING: the call to MenuClosed deletes us. - return; - } -} - -void MenuController::OnMousePressed(SubmenuView* source, - const ui::MouseEvent& event) { - SetSelectionOnPointerDown(source, event); -} - -void MenuController::OnMouseDragged(SubmenuView* source, - const ui::MouseEvent& event) { - MenuPart part = GetMenuPart(source, event.location()); - UpdateScrolling(part); - - if (!blocking_run_) - return; - - if (possible_drag_) { - if (View::ExceededDragThreshold(event.location() - press_pt_)) - StartDrag(source, press_pt_); - return; - } - MenuItemView* mouse_menu = NULL; - if (part.type == MenuPart::MENU_ITEM) { - if (!part.menu) - part.menu = source->GetMenuItem(); - else - mouse_menu = part.menu; - SetSelection(part.menu ? part.menu : state_.item, SELECTION_OPEN_SUBMENU); - } else if (part.type == MenuPart::NONE) { - ShowSiblingMenu(source, event.location()); - } - UpdateActiveMouseView(source, event, mouse_menu); -} - -void MenuController::OnMouseReleased(SubmenuView* source, - const ui::MouseEvent& event) { - if (!blocking_run_) - return; - - DCHECK(state_.item); - possible_drag_ = false; - DCHECK(blocking_run_); - MenuPart part = GetMenuPart(source, event.location()); - if (event.IsRightMouseButton() && part.type == MenuPart::MENU_ITEM) { - MenuItemView* menu = part.menu; - // |menu| is NULL means this event is from an empty menu or a separator. - // If it is from an empty menu, use parent context menu instead of that. - if (menu == NULL && - part.submenu->child_count() == 1 && - part.submenu->child_at(0)->id() == MenuItemView::kEmptyMenuItemViewID) { - menu = part.parent; - } - - if (menu != NULL && ShowContextMenu(menu, source, event, - ui::MENU_SOURCE_MOUSE)) - return; - } - - // We can use Ctrl+click or the middle mouse button to recursively open urls - // for selected folder menu items. If it's only a left click, show the - // contents of the folder. - if (!part.is_scroll() && part.menu && - !(part.menu->HasSubmenu() && - (event.flags() & ui::EF_LEFT_MOUSE_BUTTON))) { - if (GetActiveMouseView()) { - SendMouseReleaseToActiveView(source, event); - return; - } - // If a mouse release was received quickly after showing. - base::TimeDelta time_shown = base::TimeTicks::Now() - menu_start_time_; - if (time_shown.InMilliseconds() < menu_selection_hold_time_ms) { - // And it wasn't far from the mouse press location. - gfx::Point screen_loc(event.location()); - View::ConvertPointToScreen(source->GetScrollViewContainer(), &screen_loc); - gfx::Vector2d moved = screen_loc - menu_start_mouse_press_loc_; - if (moved.Length() < kMaximumLengthMovedToActivate) { - // Ignore the mouse release as it was likely this menu was shown under - // the mouse and the action was just a normal click. - return; - } - } - if (part.menu->GetDelegate()->ShouldExecuteCommandWithoutClosingMenu( - part.menu->GetCommand(), event)) { - part.menu->GetDelegate()->ExecuteCommand(part.menu->GetCommand(), - event.flags()); - return; - } - if (!part.menu->NonIconChildViewsCount() && - part.menu->GetDelegate()->IsTriggerableEvent(part.menu, event)) { - base::TimeDelta shown_time = base::TimeTicks::Now() - menu_start_time_; - if (!state_.context_menu || !View::ShouldShowContextMenuOnMousePress() || - shown_time.InMilliseconds() > menu_selection_hold_time_ms) { - Accept(part.menu, event.flags()); - } - return; - } - } else if (part.type == MenuPart::MENU_ITEM) { - // User either clicked on empty space, or a menu that has children. - SetSelection(part.menu ? part.menu : state_.item, - SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY); - } - SendMouseCaptureLostToActiveView(); -} - -void MenuController::OnMouseMoved(SubmenuView* source, - const ui::MouseEvent& event) { - HandleMouseLocation(source, event.location()); -} - -void MenuController::OnMouseEntered(SubmenuView* source, - const ui::MouseEvent& event) { - // MouseEntered is always followed by a mouse moved, so don't need to - // do anything here. -} - -bool MenuController::OnMouseWheel(SubmenuView* source, - const ui::MouseWheelEvent& event) { - MenuPart part = GetMenuPart(source, event.location()); - return part.submenu && part.submenu->OnMouseWheel(event); -} - -void MenuController::OnGestureEvent(SubmenuView* source, - ui::GestureEvent* event) { - MenuPart part = GetMenuPart(source, event->location()); - if (event->type() == ui::ET_GESTURE_TAP_DOWN) { - SetSelectionOnPointerDown(source, *event); - event->StopPropagation(); - } else if (event->type() == ui::ET_GESTURE_LONG_PRESS) { - if (part.type == MenuPart::MENU_ITEM && part.menu) { - if (ShowContextMenu(part.menu, source, *event, ui::MENU_SOURCE_TOUCH)) - event->StopPropagation(); - } - } else if (event->type() == ui::ET_GESTURE_TAP) { - if (!part.is_scroll() && part.menu && - !(part.menu->HasSubmenu())) { - if (part.menu->GetDelegate()->IsTriggerableEvent( - part.menu, *event)) { - Accept(part.menu, event->flags()); - item_selected_by_touch_ = true; - } - event->StopPropagation(); - } else if (part.type == MenuPart::MENU_ITEM) { - // User either tapped on empty space, or a menu that has children. - SetSelection(part.menu ? part.menu : state_.item, - SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY); - event->StopPropagation(); - } - } else if (event->type() == ui::ET_GESTURE_TAP_CANCEL && - part.menu && - part.type == MenuPart::MENU_ITEM) { - // Move the selection to the parent menu so that the selection in the - // current menu is unset. Make sure the submenu remains open by sending the - // appropriate SetSelectionTypes flags. - SetSelection(part.menu->GetParentMenuItem(), - SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY); - event->StopPropagation(); - } - - if (event->stopped_propagation()) - return; - - if (!part.submenu) - return; - part.submenu->OnGestureEvent(event); -} - -bool MenuController::GetDropFormats( - SubmenuView* source, - int* formats, - std::set<OSExchangeData::CustomFormat>* custom_formats) { - return source->GetMenuItem()->GetDelegate()->GetDropFormats( - source->GetMenuItem(), formats, custom_formats); -} - -bool MenuController::AreDropTypesRequired(SubmenuView* source) { - return source->GetMenuItem()->GetDelegate()->AreDropTypesRequired( - source->GetMenuItem()); -} - -bool MenuController::CanDrop(SubmenuView* source, const OSExchangeData& data) { - return source->GetMenuItem()->GetDelegate()->CanDrop(source->GetMenuItem(), - data); -} - -void MenuController::OnDragEntered(SubmenuView* source, - const ui::DropTargetEvent& event) { - valid_drop_coordinates_ = false; -} - -int MenuController::OnDragUpdated(SubmenuView* source, - const ui::DropTargetEvent& event) { - StopCancelAllTimer(); - - gfx::Point screen_loc(event.location()); - View::ConvertPointToScreen(source, &screen_loc); - if (valid_drop_coordinates_ && screen_loc == drop_pt_) - return last_drop_operation_; - drop_pt_ = screen_loc; - valid_drop_coordinates_ = true; - - MenuItemView* menu_item = GetMenuItemAt(source, event.x(), event.y()); - bool over_empty_menu = false; - if (!menu_item) { - // See if we're over an empty menu. - menu_item = GetEmptyMenuItemAt(source, event.x(), event.y()); - if (menu_item) - over_empty_menu = true; - } - MenuDelegate::DropPosition drop_position = MenuDelegate::DROP_NONE; - int drop_operation = ui::DragDropTypes::DRAG_NONE; - if (menu_item) { - gfx::Point menu_item_loc(event.location()); - View::ConvertPointToTarget(source, menu_item, &menu_item_loc); - MenuItemView* query_menu_item; - if (!over_empty_menu) { - int menu_item_height = menu_item->height(); - if (menu_item->HasSubmenu() && - (menu_item_loc.y() > kDropBetweenPixels && - menu_item_loc.y() < (menu_item_height - kDropBetweenPixels))) { - drop_position = MenuDelegate::DROP_ON; - } else { - drop_position = (menu_item_loc.y() < menu_item_height / 2) ? - MenuDelegate::DROP_BEFORE : MenuDelegate::DROP_AFTER; - } - query_menu_item = menu_item; - } else { - query_menu_item = menu_item->GetParentMenuItem(); - drop_position = MenuDelegate::DROP_ON; - } - drop_operation = menu_item->GetDelegate()->GetDropOperation( - query_menu_item, event, &drop_position); - - // If the menu has a submenu, schedule the submenu to open. - SetSelection(menu_item, menu_item->HasSubmenu() ? SELECTION_OPEN_SUBMENU : - SELECTION_DEFAULT); - - if (drop_position == MenuDelegate::DROP_NONE || - drop_operation == ui::DragDropTypes::DRAG_NONE) - menu_item = NULL; - } else { - SetSelection(source->GetMenuItem(), SELECTION_OPEN_SUBMENU); - } - SetDropMenuItem(menu_item, drop_position); - last_drop_operation_ = drop_operation; - return drop_operation; -} - -void MenuController::OnDragExited(SubmenuView* source) { - StartCancelAllTimer(); - - if (drop_target_) { - StopShowTimer(); - SetDropMenuItem(NULL, MenuDelegate::DROP_NONE); - } -} - -int MenuController::OnPerformDrop(SubmenuView* source, - const ui::DropTargetEvent& event) { - DCHECK(drop_target_); - // NOTE: the delegate may delete us after invoking OnPerformDrop, as such - // we don't call cancel here. - - MenuItemView* item = state_.item; - DCHECK(item); - - MenuItemView* drop_target = drop_target_; - MenuDelegate::DropPosition drop_position = drop_position_; - - // Close all menus, including any nested menus. - SetSelection(NULL, SELECTION_UPDATE_IMMEDIATELY | SELECTION_EXIT); - CloseAllNestedMenus(); - - // Set state such that we exit. - showing_ = false; - SetExitType(EXIT_ALL); - - // If over an empty menu item, drop occurs on the parent. - if (drop_target->id() == MenuItemView::kEmptyMenuItemViewID) - drop_target = drop_target->GetParentMenuItem(); - - if (!IsBlockingRun()) { - delegate_->DropMenuClosed( - internal::MenuControllerDelegate::DONT_NOTIFY_DELEGATE, - item->GetRootMenuItem()); - } - - // WARNING: the call to MenuClosed deletes us. - - return drop_target->GetDelegate()->OnPerformDrop( - drop_target, drop_position, event); -} - -void MenuController::OnDragEnteredScrollButton(SubmenuView* source, - bool is_up) { - MenuPart part; - part.type = is_up ? MenuPart::SCROLL_UP : MenuPart::SCROLL_DOWN; - part.submenu = source; - UpdateScrolling(part); - - // Do this to force the selection to hide. - SetDropMenuItem(source->GetMenuItemAt(0), MenuDelegate::DROP_NONE); - - StopCancelAllTimer(); -} - -void MenuController::OnDragExitedScrollButton(SubmenuView* source) { - StartCancelAllTimer(); - SetDropMenuItem(NULL, MenuDelegate::DROP_NONE); - StopScrolling(); -} - -void MenuController::OnDragWillStart() { - DCHECK(!drag_in_progress_); - drag_in_progress_ = true; -} - -void MenuController::OnDragComplete(bool should_close) { - DCHECK(drag_in_progress_); - drag_in_progress_ = false; - if (showing_ && should_close && GetActiveInstance() == this) { - CloseAllNestedMenus(); - Cancel(EXIT_ALL); - } -} - -void MenuController::UpdateSubmenuSelection(SubmenuView* submenu) { - if (submenu->IsShowing()) { - gfx::Point point = GetScreen()->GetCursorScreenPoint(); - const SubmenuView* root_submenu = - submenu->GetMenuItem()->GetRootMenuItem()->GetSubmenu(); - View::ConvertPointFromScreen( - root_submenu->GetWidget()->GetRootView(), &point); - HandleMouseLocation(submenu, point); - } -} - -void MenuController::OnWidgetDestroying(Widget* widget) { - DCHECK_EQ(owner_, widget); - owner_->RemoveObserver(this); - owner_ = NULL; - message_loop_->ClearOwner(); -} - -bool MenuController::IsCancelAllTimerRunningForTest() { - return cancel_all_timer_.IsRunning(); -} - -// static -void MenuController::TurnOffMenuSelectionHoldForTest() { - menu_selection_hold_time_ms = -1; -} - -void MenuController::SetSelection(MenuItemView* menu_item, - int selection_types) { - size_t paths_differ_at = 0; - std::vector<MenuItemView*> current_path; - std::vector<MenuItemView*> new_path; - BuildPathsAndCalculateDiff(pending_state_.item, menu_item, ¤t_path, - &new_path, &paths_differ_at); - - size_t current_size = current_path.size(); - size_t new_size = new_path.size(); - - bool pending_item_changed = pending_state_.item != menu_item; - if (pending_item_changed && pending_state_.item) { - CustomButton* button = GetFirstHotTrackedView(pending_state_.item); - if (button) - button->SetHotTracked(false); - } - - // Notify the old path it isn't selected. - MenuDelegate* current_delegate = - current_path.empty() ? NULL : current_path.front()->GetDelegate(); - for (size_t i = paths_differ_at; i < current_size; ++i) { - if (current_delegate && - current_path[i]->GetType() == MenuItemView::SUBMENU) { - current_delegate->WillHideMenu(current_path[i]); - } - current_path[i]->SetSelected(false); - } - - // Notify the new path it is selected. - for (size_t i = paths_differ_at; i < new_size; ++i) { - new_path[i]->ScrollRectToVisible(new_path[i]->GetLocalBounds()); - new_path[i]->SetSelected(true); - } - - if (menu_item && menu_item->GetDelegate()) - menu_item->GetDelegate()->SelectionChanged(menu_item); - - DCHECK(menu_item || (selection_types & SELECTION_EXIT) != 0); - - pending_state_.item = menu_item; - pending_state_.submenu_open = (selection_types & SELECTION_OPEN_SUBMENU) != 0; - - // Stop timers. - StopCancelAllTimer(); - // Resets show timer only when pending menu item is changed. - if (pending_item_changed) - StopShowTimer(); - - if (selection_types & SELECTION_UPDATE_IMMEDIATELY) - CommitPendingSelection(); - else if (pending_item_changed) - StartShowTimer(); - - // Notify an accessibility focus event on all menu items except for the root. - if (menu_item && - (MenuDepth(menu_item) != 1 || - menu_item->GetType() != MenuItemView::SUBMENU)) { - menu_item->NotifyAccessibilityEvent( - ui::AX_EVENT_FOCUS, true); - } -} - -void MenuController::SetSelectionOnPointerDown(SubmenuView* source, - const ui::LocatedEvent& event) { - if (!blocking_run_) - return; - - DCHECK(!GetActiveMouseView()); - - MenuPart part = GetMenuPart(source, event.location()); - if (part.is_scroll()) - return; // Ignore presses on scroll buttons. - - // When this menu is opened through a touch event, a simulated right-click - // is sent before the menu appears. Ignore it. - if ((event.flags() & ui::EF_RIGHT_MOUSE_BUTTON) && - (event.flags() & ui::EF_FROM_TOUCH)) - return; - - if (part.type == MenuPart::NONE || - (part.type == MenuPart::MENU_ITEM && part.menu && - part.menu->GetRootMenuItem() != state_.item->GetRootMenuItem())) { - // Remember the time when we repost the event. The owner can then use this - // to figure out if this menu was finished with the same click which is - // sent to it thereafter. Note that the time stamp front he event cannot be - // used since the reposting will set a new timestamp when the event gets - // processed. As such it is better to take the current time which will be - // closer to the time when it arrives again in the menu handler. - closing_event_time_ = ui::EventTimeForNow(); - - // Mouse wasn't pressed over any menu, or the active menu, cancel. - -#if defined(OS_WIN) - // We're going to close and we own the mouse capture. We need to repost the - // mouse down, otherwise the window the user clicked on won't get the event. - RepostEvent(source, event); -#endif - - // And close. - ExitType exit_type = EXIT_ALL; - if (!menu_stack_.empty()) { - // We're running nested menus. Only exit all if the mouse wasn't over one - // of the menus from the last run. - gfx::Point screen_loc(event.location()); - View::ConvertPointToScreen(source->GetScrollViewContainer(), &screen_loc); - MenuPart last_part = GetMenuPartByScreenCoordinateUsingMenu( - menu_stack_.back().first.item, screen_loc); - if (last_part.type != MenuPart::NONE) - exit_type = EXIT_OUTERMOST; - } - Cancel(exit_type); - -#if defined(OS_CHROMEOS) - // We're going to exit the menu and want to repost the event so that is - // is handled normally after the context menu has exited. We call - // RepostEvent after Cancel so that mouse capture has been released so - // that finding the event target is unaffected by the current capture. - RepostEvent(source, event); -#endif - // Do not repost events for Linux Aura because this behavior is more - // consistent with the behavior of other Linux apps. - return; - } - - // On a press we immediately commit the selection, that way a submenu - // pops up immediately rather than after a delay. - int selection_types = SELECTION_UPDATE_IMMEDIATELY; - if (!part.menu) { - part.menu = part.parent; - selection_types |= SELECTION_OPEN_SUBMENU; - } else { - if (part.menu->GetDelegate()->CanDrag(part.menu)) { - possible_drag_ = true; - press_pt_ = event.location(); - } - if (part.menu->HasSubmenu()) - selection_types |= SELECTION_OPEN_SUBMENU; - } - SetSelection(part.menu, selection_types); -} - -void MenuController::StartDrag(SubmenuView* source, - const gfx::Point& location) { - MenuItemView* item = state_.item; - DCHECK(item); - // Points are in the coordinates of the submenu, need to map to that of - // the selected item. Additionally source may not be the parent of - // the selected item, so need to map to screen first then to item. - gfx::Point press_loc(location); - View::ConvertPointToScreen(source->GetScrollViewContainer(), &press_loc); - View::ConvertPointFromScreen(item, &press_loc); - gfx::Point widget_loc(press_loc); - View::ConvertPointToWidget(item, &widget_loc); - scoped_ptr<gfx::Canvas> canvas(GetCanvasForDragImage( - source->GetWidget(), gfx::Size(item->width(), item->height()))); - item->PaintButton(canvas.get(), MenuItemView::PB_FOR_DRAG); - - OSExchangeData data; - item->GetDelegate()->WriteDragData(item, &data); - drag_utils::SetDragImageOnDataObject(*canvas, - press_loc.OffsetFromOrigin(), - &data); - StopScrolling(); - int drag_ops = item->GetDelegate()->GetDragOperations(item); - did_initiate_drag_ = true; - // TODO(varunjain): Properly determine and send DRAG_EVENT_SOURCE below. - item->GetWidget()->RunShellDrag(NULL, data, widget_loc, drag_ops, - ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE); - did_initiate_drag_ = false; -} - -bool MenuController::OnKeyDown(ui::KeyboardCode key_code) { - DCHECK(blocking_run_); - - switch (key_code) { - case ui::VKEY_UP: - IncrementSelection(-1); - break; - - case ui::VKEY_DOWN: - IncrementSelection(1); - break; - - // Handling of VK_RIGHT and VK_LEFT is different depending on the UI - // layout. - case ui::VKEY_RIGHT: - if (base::i18n::IsRTL()) - CloseSubmenu(); - else - OpenSubmenuChangeSelectionIfCan(); - break; - - case ui::VKEY_LEFT: - if (base::i18n::IsRTL()) - OpenSubmenuChangeSelectionIfCan(); - else - CloseSubmenu(); - break; - - case ui::VKEY_SPACE: - if (SendAcceleratorToHotTrackedView() == ACCELERATOR_PROCESSED_EXIT) - return false; - break; - - case ui::VKEY_F4: - if (!is_combobox_) - break; - // Fallthrough to accept or dismiss combobox menus on F4, like windows. - case ui::VKEY_RETURN: - if (pending_state_.item) { - if (pending_state_.item->HasSubmenu()) { - if (key_code == ui::VKEY_F4 && - pending_state_.item->GetSubmenu()->IsShowing()) - return false; - else - OpenSubmenuChangeSelectionIfCan(); - } else { - SendAcceleratorResultType result = SendAcceleratorToHotTrackedView(); - if (result == ACCELERATOR_NOT_PROCESSED && - pending_state_.item->enabled()) { - Accept(pending_state_.item, 0); - return false; - } else if (result == ACCELERATOR_PROCESSED_EXIT) { - return false; - } - } - } - break; - - case ui::VKEY_ESCAPE: - if (!state_.item->GetParentMenuItem() || - (!state_.item->GetParentMenuItem()->GetParentMenuItem() && - (!state_.item->HasSubmenu() || - !state_.item->GetSubmenu()->IsShowing()))) { - // User pressed escape and only one menu is shown, cancel it. - Cancel(EXIT_OUTERMOST); - return false; - } - CloseSubmenu(); - break; - - default: - break; - } - return true; -} - -MenuController::MenuController(ui::NativeTheme* theme, - bool blocking, - internal::MenuControllerDelegate* delegate) - : blocking_run_(blocking), - showing_(false), - exit_type_(EXIT_NONE), - did_capture_(false), - result_(NULL), - accept_event_flags_(0), - drop_target_(NULL), - drop_position_(MenuDelegate::DROP_UNKNOWN), - owner_(NULL), - possible_drag_(false), - drag_in_progress_(false), - did_initiate_drag_(false), - valid_drop_coordinates_(false), - last_drop_operation_(MenuDelegate::DROP_UNKNOWN), - showing_submenu_(false), - active_mouse_view_id_(ViewStorage::GetInstance()->CreateStorageID()), - delegate_(delegate), - message_loop_depth_(0), - menu_config_(theme), - closing_event_time_(base::TimeDelta()), - menu_start_time_(base::TimeTicks()), - is_combobox_(false), - item_selected_by_touch_(false), - message_loop_(MenuMessageLoop::Create()) { - active_instance_ = this; -} - -MenuController::~MenuController() { - DCHECK(!showing_); - if (owner_) - owner_->RemoveObserver(this); - if (active_instance_ == this) - active_instance_ = NULL; - StopShowTimer(); - StopCancelAllTimer(); -} - -void MenuController::RunMessageLoop(bool nested_menu) { - message_loop_->Run(this, owner_, nested_menu); -} - -MenuController::SendAcceleratorResultType - MenuController::SendAcceleratorToHotTrackedView() { - CustomButton* hot_view = GetFirstHotTrackedView(pending_state_.item); - if (!hot_view) - return ACCELERATOR_NOT_PROCESSED; - - ui::Accelerator accelerator(ui::VKEY_RETURN, ui::EF_NONE); - hot_view->AcceleratorPressed(accelerator); - CustomButton* button = static_cast<CustomButton*>(hot_view); - button->SetHotTracked(true); - return (exit_type_ == EXIT_NONE) ? - ACCELERATOR_PROCESSED : ACCELERATOR_PROCESSED_EXIT; -} - -void MenuController::UpdateInitialLocation(const gfx::Rect& bounds, - MenuAnchorPosition position, - bool context_menu) { - pending_state_.context_menu = context_menu; - pending_state_.initial_bounds = bounds; - if (bounds.height() > 1) { - // Inset the bounds slightly, otherwise drag coordinates don't line up - // nicely and menus close prematurely. - pending_state_.initial_bounds.Inset(0, 1); - } - - // Reverse anchor position for RTL languages. - if (base::i18n::IsRTL() && - (position == MENU_ANCHOR_TOPRIGHT || position == MENU_ANCHOR_TOPLEFT)) { - pending_state_.anchor = position == MENU_ANCHOR_TOPRIGHT - ? MENU_ANCHOR_TOPLEFT - : MENU_ANCHOR_TOPRIGHT; - } else { - pending_state_.anchor = position; - } - - // Calculate the bounds of the monitor we'll show menus on. Do this once to - // avoid repeated system queries for the info. - pending_state_.monitor_bounds = GetScreen()->GetDisplayNearestPoint( - bounds.origin()).work_area(); - - if (!pending_state_.monitor_bounds.Contains(bounds)) { - // Use the monitor area if the work area doesn't contain the bounds. This - // handles showing a menu from the launcher. - gfx::Rect monitor_area = GetScreen()->GetDisplayNearestPoint( - bounds.origin()).bounds(); - if (monitor_area.Contains(bounds)) - pending_state_.monitor_bounds = monitor_area; - } -} - -void MenuController::Accept(MenuItemView* item, int event_flags) { - DCHECK(IsBlockingRun()); - result_ = item; - if (item && !menu_stack_.empty() && - !item->GetDelegate()->ShouldCloseAllMenusOnExecute(item->GetCommand())) { - SetExitType(EXIT_OUTERMOST); - } else { - SetExitType(EXIT_ALL); - } - accept_event_flags_ = event_flags; -} - -bool MenuController::ShowSiblingMenu(SubmenuView* source, - const gfx::Point& mouse_location) { - if (!menu_stack_.empty() || !pressed_lock_.get()) - return false; - - View* source_view = source->GetScrollViewContainer(); - if (mouse_location.x() >= 0 && - mouse_location.x() < source_view->width() && - mouse_location.y() >= 0 && - mouse_location.y() < source_view->height()) { - // The mouse is over the menu, no need to continue. - return false; - } - - gfx::NativeWindow window_under_mouse = GetScreen()->GetWindowUnderCursor(); - // TODO(oshima): Replace with views only API. - if (!owner_ || window_under_mouse != owner_->GetNativeWindow()) - return false; - - // The user moved the mouse outside the menu and over the owning window. See - // if there is a sibling menu we should show. - gfx::Point screen_point(mouse_location); - View::ConvertPointToScreen(source_view, &screen_point); - MenuAnchorPosition anchor; - bool has_mnemonics; - MenuButton* button = NULL; - MenuItemView* alt_menu = source->GetMenuItem()->GetDelegate()-> - GetSiblingMenu(source->GetMenuItem()->GetRootMenuItem(), - screen_point, &anchor, &has_mnemonics, &button); - if (!alt_menu || (state_.item && state_.item->GetRootMenuItem() == alt_menu)) - return false; - - delegate_->SiblingMenuCreated(alt_menu); - - if (!button) { - // If the delegate returns a menu, they must also return a button. - NOTREACHED(); - return false; - } - - // There is a sibling menu, update the button state, hide the current menu - // and show the new one. - pressed_lock_.reset(new MenuButton::PressedLock(button)); - - // Need to reset capture when we show the menu again, otherwise we aren't - // going to get any events. - did_capture_ = false; - gfx::Point screen_menu_loc; - View::ConvertPointToScreen(button, &screen_menu_loc); - - // It is currently not possible to show a submenu recursively in a bubble. - DCHECK(!MenuItemView::IsBubble(anchor)); - // Subtract 1 from the height to make the popup flush with the button border. - UpdateInitialLocation(gfx::Rect(screen_menu_loc.x(), screen_menu_loc.y(), - button->width(), button->height() - 1), - anchor, state_.context_menu); - alt_menu->PrepareForRun( - false, has_mnemonics, - source->GetMenuItem()->GetRootMenuItem()->show_mnemonics_); - alt_menu->controller_ = this; - SetSelection(alt_menu, SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY); - return true; -} - -bool MenuController::ShowContextMenu(MenuItemView* menu_item, - SubmenuView* source, - const ui::LocatedEvent& event, - ui::MenuSourceType source_type) { - // Set the selection immediately, making sure the submenu is only open - // if it already was. - int selection_types = SELECTION_UPDATE_IMMEDIATELY; - if (state_.item == pending_state_.item && state_.submenu_open) - selection_types |= SELECTION_OPEN_SUBMENU; - SetSelection(pending_state_.item, selection_types); - gfx::Point loc(event.location()); - View::ConvertPointToScreen(source->GetScrollViewContainer(), &loc); - - if (menu_item->GetDelegate()->ShowContextMenu( - menu_item, menu_item->GetCommand(), loc, source_type)) { - SendMouseCaptureLostToActiveView(); - return true; - } - return false; -} - -void MenuController::CloseAllNestedMenus() { - for (std::list<NestedState>::iterator i = menu_stack_.begin(); - i != menu_stack_.end(); ++i) { - State& state = i->first; - MenuItemView* last_item = state.item; - for (MenuItemView* item = last_item; item; - item = item->GetParentMenuItem()) { - CloseMenu(item); - last_item = item; - } - state.submenu_open = false; - state.item = last_item; - } -} - -MenuItemView* MenuController::GetMenuItemAt(View* source, int x, int y) { - // Walk the view hierarchy until we find a menu item (or the root). - View* child_under_mouse = source->GetEventHandlerForPoint(gfx::Point(x, y)); - while (child_under_mouse && - child_under_mouse->id() != MenuItemView::kMenuItemViewID) { - child_under_mouse = child_under_mouse->parent(); - } - if (child_under_mouse && child_under_mouse->enabled() && - child_under_mouse->id() == MenuItemView::kMenuItemViewID) { - return static_cast<MenuItemView*>(child_under_mouse); - } - return NULL; -} - -MenuItemView* MenuController::GetEmptyMenuItemAt(View* source, int x, int y) { - View* child_under_mouse = source->GetEventHandlerForPoint(gfx::Point(x, y)); - if (child_under_mouse && - child_under_mouse->id() == MenuItemView::kEmptyMenuItemViewID) { - return static_cast<MenuItemView*>(child_under_mouse); - } - return NULL; -} - -bool MenuController::IsScrollButtonAt(SubmenuView* source, - int x, - int y, - MenuPart::Type* part) { - MenuScrollViewContainer* scroll_view = source->GetScrollViewContainer(); - View* child_under_mouse = - scroll_view->GetEventHandlerForPoint(gfx::Point(x, y)); - if (child_under_mouse && child_under_mouse->enabled()) { - if (child_under_mouse == scroll_view->scroll_up_button()) { - *part = MenuPart::SCROLL_UP; - return true; - } - if (child_under_mouse == scroll_view->scroll_down_button()) { - *part = MenuPart::SCROLL_DOWN; - return true; - } - } - return false; -} - -MenuController::MenuPart MenuController::GetMenuPart( - SubmenuView* source, - const gfx::Point& source_loc) { - gfx::Point screen_loc(source_loc); - View::ConvertPointToScreen(source->GetScrollViewContainer(), &screen_loc); - return GetMenuPartByScreenCoordinateUsingMenu(state_.item, screen_loc); -} - -MenuController::MenuPart MenuController::GetMenuPartByScreenCoordinateUsingMenu( - MenuItemView* item, - const gfx::Point& screen_loc) { - MenuPart part; - for (; item; item = item->GetParentMenuItem()) { - if (item->HasSubmenu() && item->GetSubmenu()->IsShowing() && - GetMenuPartByScreenCoordinateImpl(item->GetSubmenu(), screen_loc, - &part)) { - return part; - } - } - return part; -} - -bool MenuController::GetMenuPartByScreenCoordinateImpl( - SubmenuView* menu, - const gfx::Point& screen_loc, - MenuPart* part) { - // Is the mouse over the scroll buttons? - gfx::Point scroll_view_loc = screen_loc; - View* scroll_view_container = menu->GetScrollViewContainer(); - View::ConvertPointFromScreen(scroll_view_container, &scroll_view_loc); - if (scroll_view_loc.x() < 0 || - scroll_view_loc.x() >= scroll_view_container->width() || - scroll_view_loc.y() < 0 || - scroll_view_loc.y() >= scroll_view_container->height()) { - // Point isn't contained in menu. - return false; - } - if (IsScrollButtonAt(menu, scroll_view_loc.x(), scroll_view_loc.y(), - &(part->type))) { - part->submenu = menu; - return true; - } - - // Not over the scroll button. Check the actual menu. - if (DoesSubmenuContainLocation(menu, screen_loc)) { - gfx::Point menu_loc = screen_loc; - View::ConvertPointFromScreen(menu, &menu_loc); - part->menu = GetMenuItemAt(menu, menu_loc.x(), menu_loc.y()); - part->type = MenuPart::MENU_ITEM; - part->submenu = menu; - if (!part->menu) - part->parent = menu->GetMenuItem(); - return true; - } - - // While the mouse isn't over a menu item or the scroll buttons of menu, it - // is contained by menu and so we return true. If we didn't return true other - // menus would be searched, even though they are likely obscured by us. - return true; -} - -bool MenuController::DoesSubmenuContainLocation(SubmenuView* submenu, - const gfx::Point& screen_loc) { - gfx::Point view_loc = screen_loc; - View::ConvertPointFromScreen(submenu, &view_loc); - gfx::Rect vis_rect = submenu->GetVisibleBounds(); - return vis_rect.Contains(view_loc.x(), view_loc.y()); -} - -void MenuController::CommitPendingSelection() { - StopShowTimer(); - - size_t paths_differ_at = 0; - std::vector<MenuItemView*> current_path; - std::vector<MenuItemView*> new_path; - BuildPathsAndCalculateDiff(state_.item, pending_state_.item, ¤t_path, - &new_path, &paths_differ_at); - - // Hide the old menu. - for (size_t i = paths_differ_at; i < current_path.size(); ++i) { - if (current_path[i]->HasSubmenu()) { - current_path[i]->GetSubmenu()->Hide(); - } - } - - // Copy pending to state_, making sure to preserve the direction menus were - // opened. - std::list<bool> pending_open_direction; - state_.open_leading.swap(pending_open_direction); - state_ = pending_state_; - state_.open_leading.swap(pending_open_direction); - - int menu_depth = MenuDepth(state_.item); - if (menu_depth == 0) { - state_.open_leading.clear(); - } else { - int cached_size = static_cast<int>(state_.open_leading.size()); - DCHECK_GE(menu_depth, 0); - while (cached_size-- >= menu_depth) - state_.open_leading.pop_back(); - } - - if (!state_.item) { - // Nothing to select. - StopScrolling(); - return; - } - - // Open all the submenus preceeding the last menu item (last menu item is - // handled next). - if (new_path.size() > 1) { - for (std::vector<MenuItemView*>::iterator i = new_path.begin(); - i != new_path.end() - 1; ++i) { - OpenMenu(*i); - } - } - - if (state_.submenu_open) { - // The submenu should be open, open the submenu if the item has a submenu. - if (state_.item->HasSubmenu()) { - OpenMenu(state_.item); - } else { - state_.submenu_open = false; - } - } else if (state_.item->HasSubmenu() && - state_.item->GetSubmenu()->IsShowing()) { - state_.item->GetSubmenu()->Hide(); - } - - if (scroll_task_.get() && scroll_task_->submenu()) { - // Stop the scrolling if none of the elements of the selection contain - // the menu being scrolled. - bool found = false; - for (MenuItemView* item = state_.item; item && !found; - item = item->GetParentMenuItem()) { - found = (item->HasSubmenu() && item->GetSubmenu()->IsShowing() && - item->GetSubmenu() == scroll_task_->submenu()); - } - if (!found) - StopScrolling(); - } -} - -void MenuController::CloseMenu(MenuItemView* item) { - DCHECK(item); - if (!item->HasSubmenu()) - return; - item->GetSubmenu()->Hide(); -} - -void MenuController::OpenMenu(MenuItemView* item) { - DCHECK(item); - if (item->GetSubmenu()->IsShowing()) { - return; - } - - OpenMenuImpl(item, true); - did_capture_ = true; -} - -void MenuController::OpenMenuImpl(MenuItemView* item, bool show) { - // TODO(oshima|sky): Don't show the menu if drag is in progress and - // this menu doesn't support drag drop. See crbug.com/110495. - if (show) { - int old_count = item->GetSubmenu()->child_count(); - item->GetDelegate()->WillShowMenu(item); - if (old_count != item->GetSubmenu()->child_count()) { - // If the number of children changed then we may need to add empty items. - item->AddEmptyMenus(); - } - } - bool prefer_leading = - state_.open_leading.empty() ? true : state_.open_leading.back(); - bool resulting_direction; - gfx::Rect bounds = MenuItemView::IsBubble(state_.anchor) ? - CalculateBubbleMenuBounds(item, prefer_leading, &resulting_direction) : - CalculateMenuBounds(item, prefer_leading, &resulting_direction); - state_.open_leading.push_back(resulting_direction); - bool do_capture = (!did_capture_ && blocking_run_); - showing_submenu_ = true; - if (show) { - // Menus are the only place using kGroupingPropertyKey, so any value (other - // than 0) is fine. - const int kGroupingId = 1001; - item->GetSubmenu()->ShowAt(owner_, bounds, do_capture); - item->GetSubmenu()->GetWidget()->SetNativeWindowProperty( - TooltipManager::kGroupingPropertyKey, - reinterpret_cast<void*>(kGroupingId)); - } else { - item->GetSubmenu()->Reposition(bounds); - } - showing_submenu_ = false; -} - -void MenuController::MenuChildrenChanged(MenuItemView* item) { - DCHECK(item); - // Menu shouldn't be updated during drag operation. - DCHECK(!GetActiveMouseView()); - - // If the current item or pending item is a descendant of the item - // that changed, move the selection back to the changed item. - const MenuItemView* ancestor = state_.item; - while (ancestor && ancestor != item) - ancestor = ancestor->GetParentMenuItem(); - if (!ancestor) { - ancestor = pending_state_.item; - while (ancestor && ancestor != item) - ancestor = ancestor->GetParentMenuItem(); - if (!ancestor) - return; - } - SetSelection(item, SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY); - if (item->HasSubmenu()) - OpenMenuImpl(item, false); -} - -void MenuController::BuildPathsAndCalculateDiff( - MenuItemView* old_item, - MenuItemView* new_item, - std::vector<MenuItemView*>* old_path, - std::vector<MenuItemView*>* new_path, - size_t* first_diff_at) { - DCHECK(old_path && new_path && first_diff_at); - BuildMenuItemPath(old_item, old_path); - BuildMenuItemPath(new_item, new_path); - - size_t common_size = std::min(old_path->size(), new_path->size()); - - // Find the first difference between the two paths, when the loop - // returns, diff_i is the first index where the two paths differ. - for (size_t i = 0; i < common_size; ++i) { - if ((*old_path)[i] != (*new_path)[i]) { - *first_diff_at = i; - return; - } - } - - *first_diff_at = common_size; -} - -void MenuController::BuildMenuItemPath(MenuItemView* item, - std::vector<MenuItemView*>* path) { - if (!item) - return; - BuildMenuItemPath(item->GetParentMenuItem(), path); - path->push_back(item); -} - -void MenuController::StartShowTimer() { - show_timer_.Start(FROM_HERE, - TimeDelta::FromMilliseconds(menu_config_.show_delay), - this, &MenuController::CommitPendingSelection); -} - -void MenuController::StopShowTimer() { - show_timer_.Stop(); -} - -void MenuController::StartCancelAllTimer() { - cancel_all_timer_.Start(FROM_HERE, - TimeDelta::FromMilliseconds(kCloseOnExitTime), - this, &MenuController::CancelAll); -} - -void MenuController::StopCancelAllTimer() { - cancel_all_timer_.Stop(); -} - -gfx::Rect MenuController::CalculateMenuBounds(MenuItemView* item, - bool prefer_leading, - bool* is_leading) { - DCHECK(item); - - SubmenuView* submenu = item->GetSubmenu(); - DCHECK(submenu); - - gfx::Size pref = submenu->GetScrollViewContainer()->GetPreferredSize(); - - // Don't let the menu go too wide. - pref.set_width(std::min(pref.width(), - item->GetDelegate()->GetMaxWidthForMenu(item))); - if (!state_.monitor_bounds.IsEmpty()) - pref.set_width(std::min(pref.width(), state_.monitor_bounds.width())); - - // Assume we can honor prefer_leading. - *is_leading = prefer_leading; - - int x, y; - - const MenuConfig& menu_config = item->GetMenuConfig(); - - if (!item->GetParentMenuItem()) { - // First item, position relative to initial location. - x = state_.initial_bounds.x(); - - // Offsets for context menu prevent menu items being selected by - // simply opening the menu (bug 142992). - if (menu_config.offset_context_menus && state_.context_menu) - x += 1; - - y = state_.initial_bounds.bottom(); - if (state_.anchor == MENU_ANCHOR_TOPRIGHT) { - x = x + state_.initial_bounds.width() - pref.width(); - if (menu_config.offset_context_menus && state_.context_menu) - x -= 1; - } else if (state_.anchor == MENU_ANCHOR_BOTTOMCENTER) { - x = x - (pref.width() - state_.initial_bounds.width()) / 2; - if (pref.height() > - state_.initial_bounds.y() + kCenteredContextMenuYOffset) { - // Menu does not fit above the anchor. We move it to below. - y = state_.initial_bounds.y() - kCenteredContextMenuYOffset; - } else { - y = std::max(0, state_.initial_bounds.y() - pref.height()) + - kCenteredContextMenuYOffset; - } - } - - if (!state_.monitor_bounds.IsEmpty() && - y + pref.height() > state_.monitor_bounds.bottom()) { - // The menu doesn't fit fully below the button on the screen. The menu - // position with respect to the bounds will be preserved if it has - // already been drawn. When the requested positioning is below the bounds - // it will shrink the menu to make it fit below. - // If the requested positioning is best fit, it will first try to fit the - // menu below. If that does not fit it will try to place it above. If - // that will not fit it will place it at the bottom of the work area and - // moving it off the initial_bounds region to avoid overlap. - // In all other requested position styles it will be flipped above and - // the height will be shrunken to the usable height. - if (item->actual_menu_position() == MenuItemView::POSITION_BELOW_BOUNDS) { - pref.set_height(std::min(pref.height(), - state_.monitor_bounds.bottom() - y)); - } else if (item->actual_menu_position() == - MenuItemView::POSITION_BEST_FIT) { - MenuItemView::MenuPosition orientation = - MenuItemView::POSITION_BELOW_BOUNDS; - if (state_.monitor_bounds.height() < pref.height()) { - // Handle very tall menus. - pref.set_height(state_.monitor_bounds.height()); - y = state_.monitor_bounds.y(); - } else if (state_.monitor_bounds.y() + pref.height() < - state_.initial_bounds.y()) { - // Flipping upwards if there is enough space. - y = state_.initial_bounds.y() - pref.height(); - orientation = MenuItemView::POSITION_ABOVE_BOUNDS; - } else { - // It is allowed to move the menu a bit around in order to get the - // best fit and to avoid showing scroll elements. - y = state_.monitor_bounds.bottom() - pref.height(); - } - if (orientation == MenuItemView::POSITION_BELOW_BOUNDS) { - // The menu should never overlap the owning button. So move it. - // We use the anchor view style to determine the preferred position - // relative to the owning button. - if (state_.anchor == MENU_ANCHOR_TOPLEFT) { - // The menu starts with the same x coordinate as the owning button. - if (x + state_.initial_bounds.width() + pref.width() > - state_.monitor_bounds.right()) - x -= pref.width(); // Move the menu to the left of the button. - else - x += state_.initial_bounds.width(); // Move the menu right. - } else { - // The menu should end with the same x coordinate as the owning - // button. - if (state_.monitor_bounds.x() > - state_.initial_bounds.x() - pref.width()) - x = state_.initial_bounds.right(); // Move right of the button. - else - x = state_.initial_bounds.x() - pref.width(); // Move left. - } - } - item->set_actual_menu_position(orientation); - } else { - pref.set_height(std::min(pref.height(), - state_.initial_bounds.y() - state_.monitor_bounds.y())); - y = state_.initial_bounds.y() - pref.height(); - item->set_actual_menu_position(MenuItemView::POSITION_ABOVE_BOUNDS); - } - } else if (item->actual_menu_position() == - MenuItemView::POSITION_ABOVE_BOUNDS) { - pref.set_height(std::min(pref.height(), - state_.initial_bounds.y() - state_.monitor_bounds.y())); - y = state_.initial_bounds.y() - pref.height(); - } else { - item->set_actual_menu_position(MenuItemView::POSITION_BELOW_BOUNDS); - } - if (state_.monitor_bounds.width() != 0 && - menu_config.offset_context_menus && state_.context_menu) { - if (x + pref.width() > state_.monitor_bounds.right()) - x = state_.initial_bounds.x() - pref.width() - 1; - if (x < state_.monitor_bounds.x()) - x = state_.monitor_bounds.x(); - } - } else { - // Not the first menu; position it relative to the bounds of the menu - // item. - gfx::Point item_loc; - View::ConvertPointToScreen(item, &item_loc); - - // We must make sure we take into account the UI layout. If the layout is - // RTL, then a 'leading' menu is positioned to the left of the parent menu - // item and not to the right. - bool layout_is_rtl = base::i18n::IsRTL(); - bool create_on_the_right = (prefer_leading && !layout_is_rtl) || - (!prefer_leading && layout_is_rtl); - int submenu_horizontal_inset = menu_config.submenu_horizontal_inset; - - if (create_on_the_right) { - x = item_loc.x() + item->width() - submenu_horizontal_inset; - if (state_.monitor_bounds.width() != 0 && - x + pref.width() > state_.monitor_bounds.right()) { - if (layout_is_rtl) - *is_leading = true; - else - *is_leading = false; - x = item_loc.x() - pref.width() + submenu_horizontal_inset; - } - } else { - x = item_loc.x() - pref.width() + submenu_horizontal_inset; - if (state_.monitor_bounds.width() != 0 && x < state_.monitor_bounds.x()) { - if (layout_is_rtl) - *is_leading = false; - else - *is_leading = true; - x = item_loc.x() + item->width() - submenu_horizontal_inset; - } - } - y = item_loc.y() - menu_config.menu_vertical_border_size; - if (state_.monitor_bounds.width() != 0) { - pref.set_height(std::min(pref.height(), state_.monitor_bounds.height())); - if (y + pref.height() > state_.monitor_bounds.bottom()) - y = state_.monitor_bounds.bottom() - pref.height(); - if (y < state_.monitor_bounds.y()) - y = state_.monitor_bounds.y(); - } - } - - if (state_.monitor_bounds.width() != 0) { - if (x + pref.width() > state_.monitor_bounds.right()) - x = state_.monitor_bounds.right() - pref.width(); - if (x < state_.monitor_bounds.x()) - x = state_.monitor_bounds.x(); - } - return gfx::Rect(x, y, pref.width(), pref.height()); -} - -gfx::Rect MenuController::CalculateBubbleMenuBounds(MenuItemView* item, - bool prefer_leading, - bool* is_leading) { - DCHECK(item); - DCHECK(!item->GetParentMenuItem()); - - // Assume we can honor prefer_leading. - *is_leading = prefer_leading; - - SubmenuView* submenu = item->GetSubmenu(); - DCHECK(submenu); - - gfx::Size pref = submenu->GetScrollViewContainer()->GetPreferredSize(); - const gfx::Rect& owner_bounds = pending_state_.initial_bounds; - - // First the size gets reduced to the possible space. - if (!state_.monitor_bounds.IsEmpty()) { - int max_width = state_.monitor_bounds.width(); - int max_height = state_.monitor_bounds.height(); - // In case of bubbles, the maximum width is limited by the space - // between the display corner and the target area + the tip size. - if (state_.anchor == MENU_ANCHOR_BUBBLE_LEFT) { - max_width = owner_bounds.x() - state_.monitor_bounds.x() + - kBubbleTipSizeLeftRight; - } else if (state_.anchor == MENU_ANCHOR_BUBBLE_RIGHT) { - max_width = state_.monitor_bounds.right() - owner_bounds.right() + - kBubbleTipSizeLeftRight; - } else if (state_.anchor == MENU_ANCHOR_BUBBLE_ABOVE) { - max_height = owner_bounds.y() - state_.monitor_bounds.y() + - kBubbleTipSizeTopBottom; - } else if (state_.anchor == MENU_ANCHOR_BUBBLE_BELOW) { - max_height = state_.monitor_bounds.bottom() - owner_bounds.bottom() + - kBubbleTipSizeTopBottom; - } - // The space for the menu to cover should never get empty. - DCHECK_GE(max_width, kBubbleTipSizeLeftRight); - DCHECK_GE(max_height, kBubbleTipSizeTopBottom); - pref.set_width(std::min(pref.width(), max_width)); - pref.set_height(std::min(pref.height(), max_height)); - } - // Also make sure that the menu does not go too wide. - pref.set_width(std::min(pref.width(), - item->GetDelegate()->GetMaxWidthForMenu(item))); - - int x, y; - if (state_.anchor == MENU_ANCHOR_BUBBLE_ABOVE || - state_.anchor == MENU_ANCHOR_BUBBLE_BELOW) { - if (state_.anchor == MENU_ANCHOR_BUBBLE_ABOVE) - y = owner_bounds.y() - pref.height() + kBubbleTipSizeTopBottom; - else - y = owner_bounds.bottom() - kBubbleTipSizeTopBottom; - - x = owner_bounds.CenterPoint().x() - pref.width() / 2; - int x_old = x; - if (x < state_.monitor_bounds.x()) { - x = state_.monitor_bounds.x(); - } else if (x + pref.width() > state_.monitor_bounds.right()) { - x = state_.monitor_bounds.right() - pref.width(); - } - submenu->GetScrollViewContainer()->SetBubbleArrowOffset( - pref.width() / 2 - x + x_old); - } else { - if (state_.anchor == MENU_ANCHOR_BUBBLE_RIGHT) - x = owner_bounds.right() - kBubbleTipSizeLeftRight; - else - x = owner_bounds.x() - pref.width() + kBubbleTipSizeLeftRight; - - y = owner_bounds.CenterPoint().y() - pref.height() / 2; - int y_old = y; - if (y < state_.monitor_bounds.y()) { - y = state_.monitor_bounds.y(); - } else if (y + pref.height() > state_.monitor_bounds.bottom()) { - y = state_.monitor_bounds.bottom() - pref.height(); - } - submenu->GetScrollViewContainer()->SetBubbleArrowOffset( - pref.height() / 2 - y + y_old); - } - return gfx::Rect(x, y, pref.width(), pref.height()); -} - -// static -int MenuController::MenuDepth(MenuItemView* item) { - return item ? (MenuDepth(item->GetParentMenuItem()) + 1) : 0; -} - -void MenuController::IncrementSelection(int delta) { - MenuItemView* item = pending_state_.item; - DCHECK(item); - if (pending_state_.submenu_open && item->HasSubmenu() && - item->GetSubmenu()->IsShowing()) { - // A menu is selected and open, but none of its children are selected, - // select the first menu item. - if (item->GetSubmenu()->GetMenuItemCount()) { - SetSelection(item->GetSubmenu()->GetMenuItemAt(0), SELECTION_DEFAULT); - return; - } - } - - if (item->has_children()) { - CustomButton* button = GetFirstHotTrackedView(item); - if (button) { - button->SetHotTracked(false); - View* to_make_hot = GetNextFocusableView(item, button, delta == 1); - CustomButton* button_hot = CustomButton::AsCustomButton(to_make_hot); - if (button_hot) { - button_hot->SetHotTracked(true); - return; - } - } else { - View* to_make_hot = GetInitialFocusableView(item, delta == 1); - CustomButton* button_hot = CustomButton::AsCustomButton(to_make_hot); - if (button_hot) { - button_hot->SetHotTracked(true); - return; - } - } - } - - MenuItemView* parent = item->GetParentMenuItem(); - if (parent) { - int parent_count = parent->GetSubmenu()->GetMenuItemCount(); - if (parent_count > 1) { - for (int i = 0; i < parent_count; ++i) { - if (parent->GetSubmenu()->GetMenuItemAt(i) == item) { - MenuItemView* to_select = - FindNextSelectableMenuItem(parent, i, delta); - if (!to_select) - break; - SetSelection(to_select, SELECTION_DEFAULT); - View* to_make_hot = GetInitialFocusableView(to_select, delta == 1); - CustomButton* button_hot = CustomButton::AsCustomButton(to_make_hot); - if (button_hot) - button_hot->SetHotTracked(true); - break; - } - } - } - } -} - -MenuItemView* MenuController::FindNextSelectableMenuItem(MenuItemView* parent, - int index, - int delta) { - int start_index = index; - int parent_count = parent->GetSubmenu()->GetMenuItemCount(); - // Loop through the menu items skipping any invisible menus. The loop stops - // when we wrap or find a visible child. - do { - index = (index + delta + parent_count) % parent_count; - if (index == start_index) - return NULL; - MenuItemView* child = parent->GetSubmenu()->GetMenuItemAt(index); - if (child->visible()) - return child; - } while (index != start_index); - return NULL; -} - -void MenuController::OpenSubmenuChangeSelectionIfCan() { - MenuItemView* item = pending_state_.item; - if (item->HasSubmenu() && item->enabled()) { - if (item->GetSubmenu()->GetMenuItemCount() > 0) { - SetSelection(item->GetSubmenu()->GetMenuItemAt(0), - SELECTION_UPDATE_IMMEDIATELY); - } else { - // No menu items, just show the sub-menu. - SetSelection(item, SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY); - } - } -} - -void MenuController::CloseSubmenu() { - MenuItemView* item = state_.item; - DCHECK(item); - if (!item->GetParentMenuItem()) - return; - if (item->HasSubmenu() && item->GetSubmenu()->IsShowing()) - SetSelection(item, SELECTION_UPDATE_IMMEDIATELY); - else if (item->GetParentMenuItem()->GetParentMenuItem()) - SetSelection(item->GetParentMenuItem(), SELECTION_UPDATE_IMMEDIATELY); -} - -MenuController::SelectByCharDetails MenuController::FindChildForMnemonic( - MenuItemView* parent, - base::char16 key, - bool (*match_function)(MenuItemView* menu, base::char16 mnemonic)) { - SubmenuView* submenu = parent->GetSubmenu(); - DCHECK(submenu); - SelectByCharDetails details; - - for (int i = 0, menu_item_count = submenu->GetMenuItemCount(); - i < menu_item_count; ++i) { - MenuItemView* child = submenu->GetMenuItemAt(i); - if (child->enabled() && child->visible()) { - if (child == pending_state_.item) - details.index_of_item = i; - if (match_function(child, key)) { - if (details.first_match == -1) - details.first_match = i; - else - details.has_multiple = true; - if (details.next_match == -1 && details.index_of_item != -1 && - i > details.index_of_item) - details.next_match = i; - } - } - } - return details; -} - -bool MenuController::AcceptOrSelect(MenuItemView* parent, - const SelectByCharDetails& details) { - // This should only be invoked if there is a match. - DCHECK(details.first_match != -1); - DCHECK(parent->HasSubmenu()); - SubmenuView* submenu = parent->GetSubmenu(); - DCHECK(submenu); - if (!details.has_multiple) { - // There's only one match, activate it (or open if it has a submenu). - if (submenu->GetMenuItemAt(details.first_match)->HasSubmenu()) { - SetSelection(submenu->GetMenuItemAt(details.first_match), - SELECTION_OPEN_SUBMENU | SELECTION_UPDATE_IMMEDIATELY); - } else { - Accept(submenu->GetMenuItemAt(details.first_match), 0); - return true; - } - } else if (details.index_of_item == -1 || details.next_match == -1) { - SetSelection(submenu->GetMenuItemAt(details.first_match), - SELECTION_DEFAULT); - } else { - SetSelection(submenu->GetMenuItemAt(details.next_match), - SELECTION_DEFAULT); - } - return false; -} - -bool MenuController::SelectByChar(base::char16 character) { - base::char16 char_array[] = { character, 0 }; - base::char16 key = base::i18n::ToLower(char_array)[0]; - MenuItemView* item = pending_state_.item; - if (!item->HasSubmenu() || !item->GetSubmenu()->IsShowing()) - item = item->GetParentMenuItem(); - DCHECK(item); - DCHECK(item->HasSubmenu()); - DCHECK(item->GetSubmenu()); - if (item->GetSubmenu()->GetMenuItemCount() == 0) - return false; - - // Look for matches based on mnemonic first. - SelectByCharDetails details = - FindChildForMnemonic(item, key, &MatchesMnemonic); - if (details.first_match != -1) - return AcceptOrSelect(item, details); - - if (is_combobox_) { - item->GetSubmenu()->GetTextInputClient()->InsertChar(character, 0); - } else { - // If no mnemonics found, look at first character of titles. - details = FindChildForMnemonic(item, key, &TitleMatchesMnemonic); - if (details.first_match != -1) - return AcceptOrSelect(item, details); - } - - return false; -} - -void MenuController::RepostEvent(SubmenuView* source, - const ui::LocatedEvent& event) { - if (!event.IsMouseEvent()) { - // TODO(rbyers): Gesture event repost is tricky to get right - // crbug.com/170987. - DCHECK(event.IsGestureEvent()); - return; - } - -#if defined(OS_WIN) - if (!state_.item) { - // We some times get an event after closing all the menus. Ignore it. Make - // sure the menu is in fact not visible. If the menu is visible, then - // we're in a bad state where we think the menu isn't visibile but it is. - DCHECK(!source->GetWidget()->IsVisible()); - return; - } - - state_.item->GetRootMenuItem()->GetSubmenu()->ReleaseCapture(); -#endif - - gfx::Point screen_loc(event.location()); - View::ConvertPointToScreen(source->GetScrollViewContainer(), &screen_loc); - gfx::NativeView native_view = source->GetWidget()->GetNativeView(); - if (!native_view) - return; - - gfx::Screen* screen = gfx::Screen::GetScreenFor(native_view); - gfx::NativeWindow window = screen->GetWindowAtScreenPoint(screen_loc); - -#if defined(OS_WIN) - // Convert screen_loc to pixels for the Win32 API's like WindowFromPoint, - // PostMessage/SendMessage to work correctly. These API's expect the - // coordinates to be in pixels. - // PostMessage() to metro windows isn't allowed (access will be denied). Don't - // try to repost with Win32 if the window under the mouse press is in metro. - if (!ViewsDelegate::views_delegate || - !ViewsDelegate::views_delegate->IsWindowInMetro(window)) { - gfx::Point screen_loc_pixels = gfx::win::DIPToScreenPoint(screen_loc); - HWND target_window = window ? HWNDForNativeWindow(window) : - WindowFromPoint(screen_loc_pixels.ToPOINT()); - HWND source_window = HWNDForNativeView(native_view); - if (!target_window || !source_window || - GetWindowThreadProcessId(source_window, NULL) != - GetWindowThreadProcessId(target_window, NULL)) { - // Even though we have mouse capture, windows generates a mouse event if - // the other window is in a separate thread. Only repost an event if - // |target_window| and |source_window| were created on the same thread, - // else double events can occur and lead to bad behavior. - return; - } - - // Determine whether the click was in the client area or not. - // NOTE: WM_NCHITTEST coordinates are relative to the screen. - LPARAM coords = MAKELPARAM(screen_loc_pixels.x(), screen_loc_pixels.y()); - LRESULT nc_hit_result = SendMessage(target_window, WM_NCHITTEST, 0, coords); - const bool client_area = nc_hit_result == HTCLIENT; - - // TODO(sky): this isn't right. The event to generate should correspond with - // the event we just got. MouseEvent only tells us what is down, which may - // differ. Need to add ability to get changed button from MouseEvent. - int event_type; - int flags = event.flags(); - if (flags & ui::EF_LEFT_MOUSE_BUTTON) { - event_type = client_area ? WM_LBUTTONDOWN : WM_NCLBUTTONDOWN; - } else if (flags & ui::EF_MIDDLE_MOUSE_BUTTON) { - event_type = client_area ? WM_MBUTTONDOWN : WM_NCMBUTTONDOWN; - } else if (flags & ui::EF_RIGHT_MOUSE_BUTTON) { - event_type = client_area ? WM_RBUTTONDOWN : WM_NCRBUTTONDOWN; - } else { - NOTREACHED(); - return; - } - - int window_x = screen_loc_pixels.x(); - int window_y = screen_loc_pixels.y(); - if (client_area) { - POINT pt = { window_x, window_y }; - ScreenToClient(target_window, &pt); - window_x = pt.x; - window_y = pt.y; - } - - WPARAM target = client_area ? event.native_event().wParam : nc_hit_result; - LPARAM window_coords = MAKELPARAM(window_x, window_y); - PostMessage(target_window, event_type, target, window_coords); - return; - } -#endif - // Non-Windows Aura or |window| is in metro mode. - if (!window) - return; - - message_loop_->RepostEventToWindow(event, window, screen_loc); -} - -void MenuController::SetDropMenuItem( - MenuItemView* new_target, - MenuDelegate::DropPosition new_position) { - if (new_target == drop_target_ && new_position == drop_position_) - return; - - if (drop_target_) { - drop_target_->GetParentMenuItem()->GetSubmenu()->SetDropMenuItem( - NULL, MenuDelegate::DROP_NONE); - } - drop_target_ = new_target; - drop_position_ = new_position; - if (drop_target_) { - drop_target_->GetParentMenuItem()->GetSubmenu()->SetDropMenuItem( - drop_target_, drop_position_); - } -} - -void MenuController::UpdateScrolling(const MenuPart& part) { - if (!part.is_scroll() && !scroll_task_.get()) - return; - - if (!scroll_task_.get()) - scroll_task_.reset(new MenuScrollTask()); - scroll_task_->Update(part); -} - -void MenuController::StopScrolling() { - scroll_task_.reset(NULL); -} - -void MenuController::UpdateActiveMouseView(SubmenuView* event_source, - const ui::MouseEvent& event, - View* target_menu) { - View* target = NULL; - gfx::Point target_menu_loc(event.location()); - if (target_menu && target_menu->has_children()) { - // Locate the deepest child view to send events to. This code assumes we - // don't have to walk up the tree to find a view interested in events. This - // is currently true for the cases we are embedding views, but if we embed - // more complex hierarchies it'll need to change. - View::ConvertPointToScreen(event_source->GetScrollViewContainer(), - &target_menu_loc); - View::ConvertPointFromScreen(target_menu, &target_menu_loc); - target = target_menu->GetEventHandlerForPoint(target_menu_loc); - if (target == target_menu || !target->enabled()) - target = NULL; - } - View* active_mouse_view = GetActiveMouseView(); - if (target != active_mouse_view) { - SendMouseCaptureLostToActiveView(); - active_mouse_view = target; - SetActiveMouseView(active_mouse_view); - if (active_mouse_view) { - gfx::Point target_point(target_menu_loc); - View::ConvertPointToTarget( - target_menu, active_mouse_view, &target_point); - ui::MouseEvent mouse_entered_event(ui::ET_MOUSE_ENTERED, - target_point, target_point, - 0, 0); - active_mouse_view->OnMouseEntered(mouse_entered_event); - - ui::MouseEvent mouse_pressed_event(ui::ET_MOUSE_PRESSED, - target_point, target_point, - event.flags(), - event.changed_button_flags()); - active_mouse_view->OnMousePressed(mouse_pressed_event); - } - } - - if (active_mouse_view) { - gfx::Point target_point(target_menu_loc); - View::ConvertPointToTarget(target_menu, active_mouse_view, &target_point); - ui::MouseEvent mouse_dragged_event(ui::ET_MOUSE_DRAGGED, - target_point, target_point, - event.flags(), - event.changed_button_flags()); - active_mouse_view->OnMouseDragged(mouse_dragged_event); - } -} - -void MenuController::SendMouseReleaseToActiveView(SubmenuView* event_source, - const ui::MouseEvent& event) { - View* active_mouse_view = GetActiveMouseView(); - if (!active_mouse_view) - return; - - gfx::Point target_loc(event.location()); - View::ConvertPointToScreen(event_source->GetScrollViewContainer(), - &target_loc); - View::ConvertPointFromScreen(active_mouse_view, &target_loc); - ui::MouseEvent release_event(ui::ET_MOUSE_RELEASED, target_loc, target_loc, - event.flags(), event.changed_button_flags()); - // Reset active mouse view before sending mouse released. That way if it calls - // back to us, we aren't in a weird state. - SetActiveMouseView(NULL); - active_mouse_view->OnMouseReleased(release_event); -} - -void MenuController::SendMouseCaptureLostToActiveView() { - View* active_mouse_view = GetActiveMouseView(); - if (!active_mouse_view) - return; - - // Reset the active_mouse_view_ before sending mouse capture lost. That way if - // it calls back to us, we aren't in a weird state. - SetActiveMouseView(NULL); - active_mouse_view->OnMouseCaptureLost(); -} - -void MenuController::SetActiveMouseView(View* view) { - if (view) - ViewStorage::GetInstance()->StoreView(active_mouse_view_id_, view); - else - ViewStorage::GetInstance()->RemoveView(active_mouse_view_id_); -} - -View* MenuController::GetActiveMouseView() { - return ViewStorage::GetInstance()->RetrieveView(active_mouse_view_id_); -} - -void MenuController::SetExitType(ExitType type) { - exit_type_ = type; - // Exit nested message loops as soon as possible. We do this as - // MessagePumpDispatcher is only invoked before native events, which means - // its entirely possible for a Widget::CloseNow() task to be processed before - // the next native message. We quite the nested message loop as soon as - // possible to avoid having deleted views classes (such as widgets and - // rootviews) on the stack when the nested message loop stops. - // - // It's safe to invoke QuitNestedMessageLoop() multiple times, it only effects - // the current loop. - bool quit_now = message_loop_->ShouldQuitNow() && exit_type_ != EXIT_NONE && - message_loop_depth_; - if (quit_now) - TerminateNestedMessageLoop(); -} - -void MenuController::TerminateNestedMessageLoop() { - message_loop_->QuitNow(); -} - -void MenuController::HandleMouseLocation(SubmenuView* source, - const gfx::Point& mouse_location) { - if (showing_submenu_) - return; - - // Ignore mouse events if we're closing the menu. - if (exit_type_ != EXIT_NONE) - return; - - MenuPart part = GetMenuPart(source, mouse_location); - - UpdateScrolling(part); - - if (!blocking_run_) - return; - - if (part.type == MenuPart::NONE && ShowSiblingMenu(source, mouse_location)) - return; - - if (part.type == MenuPart::MENU_ITEM && part.menu) { - SetSelection(part.menu, SELECTION_OPEN_SUBMENU); - } else if (!part.is_scroll() && pending_state_.item && - pending_state_.item->GetParentMenuItem() && - (!pending_state_.item->HasSubmenu() || - !pending_state_.item->GetSubmenu()->IsShowing())) { - // On exit if the user hasn't selected an item with a submenu, move the - // selection back to the parent menu item. - SetSelection(pending_state_.item->GetParentMenuItem(), - SELECTION_OPEN_SUBMENU); - } -} - -gfx::Screen* MenuController::GetScreen() { - Widget* root = owner_ ? owner_->GetTopLevelWidget() : NULL; - return root ? gfx::Screen::GetScreenFor(root->GetNativeView()) - : gfx::Screen::GetNativeScreen(); -} - -} // namespace views
diff --git a/ui/views/controls/menu/menu_controller.h b/ui/views/controls/menu/menu_controller.h deleted file mode 100644 index 6da540d..0000000 --- a/ui/views/controls/menu/menu_controller.h +++ /dev/null
@@ -1,641 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_MENU_MENU_CONTROLLER_H_ -#define UI_VIEWS_CONTROLS_MENU_MENU_CONTROLLER_H_ - -#include "build/build_config.h" - -#include <list> -#include <set> -#include <vector> - -#include "base/compiler_specific.h" -#include "base/memory/linked_ptr.h" -#include "base/memory/scoped_ptr.h" -#include "base/timer/timer.h" -#include "ui/events/event.h" -#include "ui/events/event_constants.h" -#include "ui/events/platform/platform_event_dispatcher.h" -#include "ui/views/controls/button/menu_button.h" -#include "ui/views/controls/menu/menu_config.h" -#include "ui/views/controls/menu/menu_delegate.h" -#include "ui/views/widget/widget_observer.h" - -namespace base { -class MessagePumpDispatcher; -} -namespace gfx { -class Screen; -} -namespace ui { -class NativeTheme; -class OSExchangeData; -class ScopedEventDispatcher; -} -namespace views { - -class MenuButton; -class MenuHostRootView; -class MenuItemView; -class MenuMessageLoop; -class MouseEvent; -class SubmenuView; -class View; - -namespace internal { -class MenuControllerDelegate; -class MenuEventDispatcher; -class MenuMessagePumpDispatcher; -class MenuRunnerImpl; -} - -// MenuController ------------------------------------------------------------- - -// MenuController is used internally by the various menu classes to manage -// showing, selecting and drag/drop for menus. All relevant events are -// forwarded to the MenuController from SubmenuView and MenuHost. -class VIEWS_EXPORT MenuController : public WidgetObserver { - public: - // Enumeration of how the menu should exit. - enum ExitType { - // Don't exit. - EXIT_NONE, - - // All menus, including nested, should be exited. - EXIT_ALL, - - // Only the outermost menu should be exited. - EXIT_OUTERMOST, - - // This is set if the menu is being closed as the result of one of the menus - // being destroyed. - EXIT_DESTROYED - }; - - // If a menu is currently active, this returns the controller for it. - static MenuController* GetActiveInstance(); - - // Runs the menu at the specified location. If the menu was configured to - // block, the selected item is returned. If the menu does not block this - // returns NULL immediately. - MenuItemView* Run(Widget* parent, - MenuButton* button, - MenuItemView* root, - const gfx::Rect& bounds, - MenuAnchorPosition position, - bool context_menu, - bool is_nested_drag, - int* event_flags); - - // Whether or not Run blocks. - bool IsBlockingRun() const { return blocking_run_; } - - bool in_nested_run() const { return !menu_stack_.empty(); } - - // Whether or not drag operation is in progress. - bool drag_in_progress() const { return drag_in_progress_; } - - // Whether the MenuController initiated the drag in progress. False if there - // is no drag in progress. - bool did_initiate_drag() const { return did_initiate_drag_; } - - // Returns the owner of child windows. - // WARNING: this may be NULL. - Widget* owner() { return owner_; } - - // Get the anchor position wich is used to show this menu. - MenuAnchorPosition GetAnchorPosition() { return state_.anchor; } - - // Cancels the current Run. See ExitType for a description of what happens - // with the various parameters. - void Cancel(ExitType type); - - // An alternative to Cancel(EXIT_ALL) that can be used with a OneShotTimer. - void CancelAll() { Cancel(EXIT_ALL); } - - // Returns the current exit type. This returns a value other than EXIT_NONE if - // the menu is being canceled. - ExitType exit_type() const { return exit_type_; } - - // Returns the time from the event which closed the menu - or 0. - base::TimeDelta closing_event_time() const { return closing_event_time_; } - - void set_is_combobox(bool is_combobox) { is_combobox_ = is_combobox; } - - // Various events, forwarded from the submenu. - // - // NOTE: the coordinates of the events are in that of the - // MenuScrollViewContainer. - void OnMousePressed(SubmenuView* source, const ui::MouseEvent& event); - void OnMouseDragged(SubmenuView* source, const ui::MouseEvent& event); - void OnMouseReleased(SubmenuView* source, const ui::MouseEvent& event); - void OnMouseMoved(SubmenuView* source, const ui::MouseEvent& event); - void OnMouseEntered(SubmenuView* source, const ui::MouseEvent& event); - bool OnMouseWheel(SubmenuView* source, const ui::MouseWheelEvent& event); - void OnGestureEvent(SubmenuView* source, ui::GestureEvent* event); - - bool GetDropFormats( - SubmenuView* source, - int* formats, - std::set<ui::OSExchangeData::CustomFormat>* custom_formats); - bool AreDropTypesRequired(SubmenuView* source); - bool CanDrop(SubmenuView* source, const ui::OSExchangeData& data); - void OnDragEntered(SubmenuView* source, const ui::DropTargetEvent& event); - int OnDragUpdated(SubmenuView* source, const ui::DropTargetEvent& event); - void OnDragExited(SubmenuView* source); - int OnPerformDrop(SubmenuView* source, const ui::DropTargetEvent& event); - - // Invoked from the scroll buttons of the MenuScrollViewContainer. - void OnDragEnteredScrollButton(SubmenuView* source, bool is_up); - void OnDragExitedScrollButton(SubmenuView* source); - - // Called by the Widget when a drag is about to start on a child view. This - // could be initiated by one of our MenuItemViews, or could be through another - // child View. - void OnDragWillStart(); - - // Called by the Widget when the drag has completed. |should_close| - // corresponds to whether or not the menu should close. - void OnDragComplete(bool should_close); - - // Update the submenu's selection based on the current mouse location - void UpdateSubmenuSelection(SubmenuView* source); - - // WidgetObserver overrides: - virtual void OnWidgetDestroying(Widget* widget) override; - - // Only used for testing. - bool IsCancelAllTimerRunningForTest(); - - // Only used for testing. - static void TurnOffMenuSelectionHoldForTest(); - - private: - friend class internal::MenuEventDispatcher; - friend class internal::MenuMessagePumpDispatcher; - friend class internal::MenuRunnerImpl; - friend class MenuControllerTest; - friend class MenuHostRootView; - friend class MenuItemView; - friend class SubmenuView; - - class MenuScrollTask; - - struct SelectByCharDetails; - - // Values supplied to SetSelection. - enum SetSelectionTypes { - SELECTION_DEFAULT = 0, - - // If set submenus are opened immediately, otherwise submenus are only - // openned after a timer fires. - SELECTION_UPDATE_IMMEDIATELY = 1 << 0, - - // If set and the menu_item has a submenu, the submenu is shown. - SELECTION_OPEN_SUBMENU = 1 << 1, - - // SetSelection is being invoked as the result exiting or cancelling the - // menu. This is used for debugging. - SELECTION_EXIT = 1 << 2, - }; - - // Result type for SendAcceleratorToHotTrackedView - enum SendAcceleratorResultType { - // Accelerator is not sent because of no hot tracked views. - ACCELERATOR_NOT_PROCESSED, - - // Accelerator is sent to the hot tracked views. - ACCELERATOR_PROCESSED, - - // Same as above and the accelerator causes the exit of the menu. - ACCELERATOR_PROCESSED_EXIT - }; - - // Tracks selection information. - struct State { - State(); - ~State(); - - // The selected menu item. - MenuItemView* item; - - // If item has a submenu this indicates if the submenu is showing. - bool submenu_open; - - // Bounds passed to the run menu. Used for positioning the first menu. - gfx::Rect initial_bounds; - - // Position of the initial menu. - MenuAnchorPosition anchor; - - // The direction child menus have opened in. - std::list<bool> open_leading; - - // Bounds for the monitor we're showing on. - gfx::Rect monitor_bounds; - - // Is the current menu a context menu. - bool context_menu; - }; - - // Used by GetMenuPart to indicate the menu part at a particular location. - struct MenuPart { - // Type of part. - enum Type { - NONE, - MENU_ITEM, - SCROLL_UP, - SCROLL_DOWN - }; - - MenuPart() : type(NONE), menu(NULL), parent(NULL), submenu(NULL) {} - - // Convenience for testing type == SCROLL_DOWN or type == SCROLL_UP. - bool is_scroll() const { return type == SCROLL_DOWN || type == SCROLL_UP; } - - // Type of part. - Type type; - - // If type is MENU_ITEM, this is the menu item the mouse is over, otherwise - // this is NULL. - // NOTE: if type is MENU_ITEM and the mouse is not over a valid menu item - // but is over a menu (for example, the mouse is over a separator or - // empty menu), this is NULL and parent is the menu the mouse was - // clicked on. - MenuItemView* menu; - - // If type is MENU_ITEM but the mouse is not over a menu item this is the - // parent of the menu item the user clicked on. Otherwise this is NULL. - MenuItemView* parent; - - // This is the submenu the mouse is over. - SubmenuView* submenu; - }; - - // Sets the selection to |menu_item|. A value of NULL unselects - // everything. |types| is a bitmask of |SetSelectionTypes|. - // - // Internally this updates pending_state_ immediatley. state_ is only updated - // immediately if SELECTION_UPDATE_IMMEDIATELY is set. If - // SELECTION_UPDATE_IMMEDIATELY is not set CommitPendingSelection is invoked - // to show/hide submenus and update state_. - void SetSelection(MenuItemView* menu_item, int types); - - void SetSelectionOnPointerDown(SubmenuView* source, - const ui::LocatedEvent& event); - void StartDrag(SubmenuView* source, const gfx::Point& location); - - // Key processing. The return value of this is returned from Dispatch. - // In other words, if this returns false (which happens if escape was - // pressed, or a matching mnemonic was found) the message loop returns. - bool OnKeyDown(ui::KeyboardCode key_code); - - // Creates a MenuController. If |blocking| is true a nested message loop is - // started in |Run|. - MenuController(ui::NativeTheme* theme, - bool blocking, - internal::MenuControllerDelegate* delegate); - - virtual ~MenuController(); - - // Runs the platform specific bits of the message loop. If |nested_menu| is - // true we're being asked to run a menu from within a menu (eg a context - // menu). - void RunMessageLoop(bool nested_menu); - - // AcceleratorPressed is invoked on the hot tracked view if it exists. - SendAcceleratorResultType SendAcceleratorToHotTrackedView(); - - void UpdateInitialLocation(const gfx::Rect& bounds, - MenuAnchorPosition position, - bool context_menu); - - // Invoked when the user accepts the selected item. This is only used - // when blocking. This schedules the loop to quit. - void Accept(MenuItemView* item, int event_flags); - - bool ShowSiblingMenu(SubmenuView* source, const gfx::Point& mouse_location); - - // Shows a context menu for |menu_item| as a result of a located event if - // appropriate. This is invoked on long press and releasing the right mouse - // button. Returns whether a context menu was shown. - bool ShowContextMenu(MenuItemView* menu_item, - SubmenuView* source, - const ui::LocatedEvent& event, - ui::MenuSourceType source_type); - - // Closes all menus, including any menus of nested invocations of Run. - void CloseAllNestedMenus(); - - // Gets the enabled menu item at the specified location. - // If over_any_menu is non-null it is set to indicate whether the location - // is over any menu. It is possible for this to return NULL, but - // over_any_menu to be true. For example, the user clicked on a separator. - MenuItemView* GetMenuItemAt(View* menu, int x, int y); - - // If there is an empty menu item at the specified location, it is returned. - MenuItemView* GetEmptyMenuItemAt(View* source, int x, int y); - - // Returns true if the coordinate is over the scroll buttons of the - // SubmenuView's MenuScrollViewContainer. If true is returned, part is set to - // indicate which scroll button the coordinate is. - bool IsScrollButtonAt(SubmenuView* source, - int x, - int y, - MenuPart::Type* part); - - // Returns the target for the mouse event. The coordinates are in terms of - // source's scroll view container. - MenuPart GetMenuPart(SubmenuView* source, const gfx::Point& source_loc); - - // Returns the target for mouse events. The search is done through |item| and - // all its parents. - MenuPart GetMenuPartByScreenCoordinateUsingMenu(MenuItemView* item, - const gfx::Point& screen_loc); - - // Implementation of GetMenuPartByScreenCoordinate for a single menu. Returns - // true if the supplied SubmenuView contains the location in terms of the - // screen. If it does, part is set appropriately and true is returned. - bool GetMenuPartByScreenCoordinateImpl(SubmenuView* menu, - const gfx::Point& screen_loc, - MenuPart* part); - - // Returns true if the SubmenuView contains the specified location. This does - // NOT included the scroll buttons, only the submenu view. - bool DoesSubmenuContainLocation(SubmenuView* submenu, - const gfx::Point& screen_loc); - - // Opens/Closes the necessary menus such that state_ matches that of - // pending_state_. This is invoked if submenus are not opened immediately, - // but after a delay. - void CommitPendingSelection(); - - // If item has a submenu, it is closed. This does NOT update the selection - // in anyway. - void CloseMenu(MenuItemView* item); - - // If item has a submenu, it is opened. This does NOT update the selection - // in anyway. - void OpenMenu(MenuItemView* item); - - // Implementation of OpenMenu. If |show| is true, this invokes show on the - // menu, otherwise Reposition is invoked. - void OpenMenuImpl(MenuItemView* item, bool show); - - // Invoked when the children of a menu change and the menu is showing. - // This closes any submenus and resizes the submenu. - void MenuChildrenChanged(MenuItemView* item); - - // Builds the paths of the two menu items into the two paths, and - // sets first_diff_at to the location of the first difference between the - // two paths. - void BuildPathsAndCalculateDiff(MenuItemView* old_item, - MenuItemView* new_item, - std::vector<MenuItemView*>* old_path, - std::vector<MenuItemView*>* new_path, - size_t* first_diff_at); - - // Builds the path for the specified item. - void BuildMenuItemPath(MenuItemView* item, std::vector<MenuItemView*>* path); - - // Starts/stops the timer that commits the pending state to state - // (opens/closes submenus). - void StartShowTimer(); - void StopShowTimer(); - - // Starts/stops the timer cancel the menu. This is used during drag and - // drop when the drop enters/exits the menu. - void StartCancelAllTimer(); - void StopCancelAllTimer(); - - // Calculates the bounds of the menu to show. is_leading is set to match the - // direction the menu opened in. - gfx::Rect CalculateMenuBounds(MenuItemView* item, - bool prefer_leading, - bool* is_leading); - - // Calculates the bubble bounds of the menu to show. is_leading is set to - // match the direction the menu opened in. - gfx::Rect CalculateBubbleMenuBounds(MenuItemView* item, - bool prefer_leading, - bool* is_leading); - - // Returns the depth of the menu. - static int MenuDepth(MenuItemView* item); - - // Selects the next/previous menu item. - void IncrementSelection(int delta); - - // Returns the next selectable child menu item of |parent| starting at |index| - // and incrementing index by |delta|. If there are no more selected menu items - // NULL is returned. - MenuItemView* FindNextSelectableMenuItem(MenuItemView* parent, - int index, - int delta); - - // If the selected item has a submenu and it isn't currently open, the - // the selection is changed such that the menu opens immediately. - void OpenSubmenuChangeSelectionIfCan(); - - // If possible, closes the submenu. - void CloseSubmenu(); - - // Returns details about which menu items match the mnemonic |key|. - // |match_function| is used to determine which menus match. - SelectByCharDetails FindChildForMnemonic( - MenuItemView* parent, - base::char16 key, - bool (*match_function)(MenuItemView* menu, base::char16 mnemonic)); - - // Selects or accepts the appropriate menu item based on |details|. Returns - // true if |Accept| was invoked (which happens if there aren't multiple item - // with the same mnemonic and the item to select does not have a submenu). - bool AcceptOrSelect(MenuItemView* parent, const SelectByCharDetails& details); - - // Selects by mnemonic, and if that doesn't work tries the first character of - // the title. Returns true if a match was selected and the menu should exit. - bool SelectByChar(base::char16 key); - - // For Windows and Aura we repost an event for some events that dismiss - // the context menu. The event is then reprocessed to cause its result - // if the context menu had not been present. - // On non-aura Windows, a new mouse event is generated and posted to - // the window (if there is one) at the location of the event. On - // aura, the event is reposted on the RootWindow. - void RepostEvent(SubmenuView* source, const ui::LocatedEvent& event); - - // Sets the drop target to new_item. - void SetDropMenuItem(MenuItemView* new_item, - MenuDelegate::DropPosition position); - - // Starts/stops scrolling as appropriate. part gives the part the mouse is - // over. - void UpdateScrolling(const MenuPart& part); - - // Stops scrolling. - void StopScrolling(); - - // Updates active mouse view from the location of the event and sends it - // the appropriate events. This is used to send mouse events to child views so - // that they react to click-drag-release as if the user clicked on the view - // itself. - void UpdateActiveMouseView(SubmenuView* event_source, - const ui::MouseEvent& event, - View* target_menu); - - // Sends a mouse release event to the current active mouse view and sets - // it to null. - void SendMouseReleaseToActiveView(SubmenuView* event_source, - const ui::MouseEvent& event); - - // Sends a mouse capture lost event to the current active mouse view and sets - // it to null. - void SendMouseCaptureLostToActiveView(); - - // Sets/gets the active mouse view. See UpdateActiveMouseView() for details. - void SetActiveMouseView(View* view); - View* GetActiveMouseView(); - - // Sets exit type. Calling this can terminate the active nested message-loop. - void SetExitType(ExitType type); - - // Terminates the current nested message-loop. - void TerminateNestedMessageLoop(); - - // Returns true if SetExitType() should quit the message loop. - bool ShouldQuitNow() const; - - // Handles the mouse location event on the submenu |source|. - void HandleMouseLocation(SubmenuView* source, - const gfx::Point& mouse_location); - - // Retrieve an appropriate Screen. - gfx::Screen* GetScreen(); - - // The active instance. - static MenuController* active_instance_; - - // If true, Run blocks. If false, Run doesn't block and this is used for - // drag and drop. Note that the semantics for drag and drop are slightly - // different: cancel timer is kicked off any time the drag moves outside the - // menu, mouse events do nothing... - bool blocking_run_; - - // If true, we're showing. - bool showing_; - - // Indicates what to exit. - ExitType exit_type_; - - // Whether we did a capture. We do a capture only if we're blocking and - // the mouse was down when Run. - bool did_capture_; - - // As the user drags the mouse around pending_state_ changes immediately. - // When the user stops moving/dragging the mouse (or clicks the mouse) - // pending_state_ is committed to state_, potentially resulting in - // opening or closing submenus. This gives a slight delayed effect to - // submenus as the user moves the mouse around. This is done so that as the - // user moves the mouse all submenus don't immediately pop. - State pending_state_; - State state_; - - // If the user accepted the selection, this is the result. - MenuItemView* result_; - - // The event flags when the user selected the menu. - int accept_event_flags_; - - // If not empty, it means we're nested. When Run is invoked from within - // Run, the current state (state_) is pushed onto menu_stack_. This allows - // MenuController to restore the state when the nested run returns. - typedef std::pair<State, linked_ptr<MenuButton::PressedLock> > NestedState; - std::list<NestedState> menu_stack_; - - // As the mouse moves around submenus are not opened immediately. Instead - // they open after this timer fires. - base::OneShotTimer<MenuController> show_timer_; - - // Used to invoke CancelAll(). This is used during drag and drop to hide the - // menu after the mouse moves out of the of the menu. This is necessitated by - // the lack of an ability to detect when the drag has completed from the drop - // side. - base::OneShotTimer<MenuController> cancel_all_timer_; - - // Drop target. - MenuItemView* drop_target_; - MenuDelegate::DropPosition drop_position_; - - // Owner of child windows. - // WARNING: this may be NULL. - Widget* owner_; - - // Indicates a possible drag operation. - bool possible_drag_; - - // True when drag operation is in progress. - bool drag_in_progress_; - - // True when the drag operation in progress was initiated by the - // MenuController for a child MenuItemView (as opposed to initiated separately - // by a child View). - bool did_initiate_drag_; - - // Location the mouse was pressed at. Used to detect d&d. - gfx::Point press_pt_; - - // We get a slew of drag updated messages as the mouse is over us. To avoid - // continually processing whether we can drop, we cache the coordinates. - bool valid_drop_coordinates_; - gfx::Point drop_pt_; - int last_drop_operation_; - - // If true, we're in the middle of invoking ShowAt on a submenu. - bool showing_submenu_; - - // Task for scrolling the menu. If non-null indicates a scroll is currently - // underway. - scoped_ptr<MenuScrollTask> scroll_task_; - - // The lock to keep the menu button pressed while a menu is visible. - scoped_ptr<MenuButton::PressedLock> pressed_lock_; - - // ViewStorage id used to store the view mouse drag events are forwarded to. - // See UpdateActiveMouseView() for details. - const int active_mouse_view_id_; - - internal::MenuControllerDelegate* delegate_; - - // How deep we are in nested message loops. This should be at most 2 (when - // showing a context menu from a menu). - int message_loop_depth_; - - views::MenuConfig menu_config_; - - // The timestamp of the event which closed the menu - or 0 otherwise. - base::TimeDelta closing_event_time_; - - // Time when the menu is first shown. - base::TimeTicks menu_start_time_; - - // If a mouse press triggered this menu, this will have its location (in - // screen coordinates). Otherwise this will be (0, 0). - gfx::Point menu_start_mouse_press_loc_; - - // Controls behavior differences between a combobox and other types of menu - // (like a context menu). - bool is_combobox_; - - // Set to true if the menu item was selected by touch. - bool item_selected_by_touch_; - - scoped_ptr<MenuMessageLoop> message_loop_; - - DISALLOW_COPY_AND_ASSIGN(MenuController); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_MENU_MENU_CONTROLLER_H_
diff --git a/ui/views/controls/menu/menu_controller_delegate.h b/ui/views/controls/menu/menu_controller_delegate.h deleted file mode 100644 index 6472aea..0000000 --- a/ui/views/controls/menu/menu_controller_delegate.h +++ /dev/null
@@ -1,40 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_MENU_MENU_CONTROLLER_DELEGATE_H_ -#define UI_VIEWS_CONTROLS_MENU_MENU_CONTROLLER_DELEGATE_H_ - -namespace views { - -class MenuItemView; - -// This is internal as there should be no need for usage of this class outside -// of views. -namespace internal { - -// Used by MenuController to notify of interesting events that are intended for -// the class using MenuController. This is implemented by MenuRunnerImpl. -class MenuControllerDelegate { - public: - enum NotifyType { - NOTIFY_DELEGATE, - DONT_NOTIFY_DELEGATE - }; - - // Invoked when MenuController closes a menu and the MenuController was - // configured for drop (MenuRunner::FOR_DROP). - virtual void DropMenuClosed(NotifyType type, MenuItemView* menu) = 0; - - // Invoked when the MenuDelegate::GetSiblingMenu() returns non-NULL. - virtual void SiblingMenuCreated(MenuItemView* menu) = 0; - - protected: - virtual ~MenuControllerDelegate() {} -}; - -} // namespace internal - -} // namespace view - -#endif // UI_VIEWS_CONTROLS_MENU_MENU_CONTROLLER_DELEGATE_H_
diff --git a/ui/views/controls/menu/menu_controller_unittest.cc b/ui/views/controls/menu/menu_controller_unittest.cc deleted file mode 100644 index ba4dd13..0000000 --- a/ui/views/controls/menu/menu_controller_unittest.cc +++ /dev/null
@@ -1,272 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/menu/menu_controller.h" - -#include "base/run_loop.h" -#include "ui/aura/scoped_window_targeter.h" -#include "ui/aura/window.h" -#include "ui/events/event_targeter.h" -#include "ui/events/platform/platform_event_source.h" -#include "ui/views/controls/menu/menu_item_view.h" -#include "ui/views/test/views_test_base.h" -#include "ui/wm/public/dispatcher_client.h" - -#if defined(OS_WIN) -#include "base/message_loop/message_pump_dispatcher.h" -#elif defined(USE_X11) -#include <X11/Xlib.h> -#undef Bool -#undef None -#include "ui/events/test/events_test_utils_x11.h" -#include "ui/events/x/device_data_manager_x11.h" -#elif defined(USE_OZONE) -#include "ui/events/event.h" -#endif - -namespace views { - -namespace { - -class TestMenuItemView : public MenuItemView { - public: - TestMenuItemView() : MenuItemView(NULL) {} - virtual ~TestMenuItemView() {} - - private: - DISALLOW_COPY_AND_ASSIGN(TestMenuItemView); -}; - -class TestPlatformEventSource : public ui::PlatformEventSource { - public: - TestPlatformEventSource() { -#if defined(USE_X11) - ui::DeviceDataManagerX11::CreateInstance(); -#endif - } - virtual ~TestPlatformEventSource() {} - - uint32_t Dispatch(const ui::PlatformEvent& event) { - return DispatchEvent(event); - } - - private: - DISALLOW_COPY_AND_ASSIGN(TestPlatformEventSource); -}; - -class TestNullTargeter : public ui::EventTargeter { - public: - TestNullTargeter() {} - virtual ~TestNullTargeter() {} - - virtual ui::EventTarget* FindTargetForEvent(ui::EventTarget* root, - ui::Event* event) override { - return NULL; - } - - private: - DISALLOW_COPY_AND_ASSIGN(TestNullTargeter); -}; - -class TestDispatcherClient : public aura::client::DispatcherClient { - public: - TestDispatcherClient() : dispatcher_(NULL) {} - virtual ~TestDispatcherClient() {} - - base::MessagePumpDispatcher* dispatcher() { - return dispatcher_; - } - - // aura::client::DispatcherClient: - virtual void PrepareNestedLoopClosures( - base::MessagePumpDispatcher* dispatcher, - base::Closure* run_closure, - base::Closure* quit_closure) override { - scoped_ptr<base::RunLoop> run_loop(new base::RunLoop()); - *quit_closure = run_loop->QuitClosure(); - *run_closure = base::Bind(&TestDispatcherClient::RunNestedDispatcher, - base::Unretained(this), - base::Passed(&run_loop), - dispatcher); - } - - private: - void RunNestedDispatcher(scoped_ptr<base::RunLoop> run_loop, - base::MessagePumpDispatcher* dispatcher) { - base::AutoReset<base::MessagePumpDispatcher*> reset_dispatcher(&dispatcher_, - dispatcher); - base::MessageLoopForUI* loop = base::MessageLoopForUI::current(); - base::MessageLoop::ScopedNestableTaskAllower allow(loop); - run_loop->Run(); - } - - base::MessagePumpDispatcher* dispatcher_; - - DISALLOW_COPY_AND_ASSIGN(TestDispatcherClient); -}; - -} // namespace - -class MenuControllerTest : public ViewsTestBase { - public: - MenuControllerTest() : controller_(NULL) {} - virtual ~MenuControllerTest() { - ResetMenuController(); - } - - // Dispatches |count| number of items, each in a separate iteration of the - // message-loop, by posting a task. - void Step3_DispatchEvents(int count) { - base::MessageLoopForUI* loop = base::MessageLoopForUI::current(); - base::MessageLoop::ScopedNestableTaskAllower allow(loop); - controller_->exit_type_ = MenuController::EXIT_ALL; - - DispatchEvent(); - if (count) { - base::MessageLoop::current()->PostTask( - FROM_HERE, - base::Bind(&MenuControllerTest::Step3_DispatchEvents, - base::Unretained(this), - count - 1)); - } else { - EXPECT_TRUE(run_loop_->running()); - run_loop_->Quit(); - } - } - - // Runs a nested message-loop that does not involve the menu itself. - void Step2_RunNestedLoop() { - base::MessageLoopForUI* loop = base::MessageLoopForUI::current(); - base::MessageLoop::ScopedNestableTaskAllower allow(loop); - base::MessageLoop::current()->PostTask( - FROM_HERE, - base::Bind(&MenuControllerTest::Step3_DispatchEvents, - base::Unretained(this), - 3)); - run_loop_.reset(new base::RunLoop()); - run_loop_->Run(); - } - - void Step1_RunMenu() { - base::MessageLoop::current()->PostTask( - FROM_HERE, - base::Bind(&MenuControllerTest::Step2_RunNestedLoop, - base::Unretained(this))); - scoped_ptr<Widget> owner(CreateOwnerWidget()); - RunMenu(owner.get()); - } - - scoped_ptr<Widget> CreateOwnerWidget() { - scoped_ptr<Widget> widget(new Widget); - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget->Init(params); - widget->Show(); - - aura::client::SetDispatcherClient( - widget->GetNativeWindow()->GetRootWindow(), &dispatcher_client_); - return widget.Pass(); - } - - void RunMenu(views::Widget* owner) { - scoped_ptr<TestMenuItemView> menu_item(new TestMenuItemView); - ResetMenuController(); - controller_ = new MenuController(NULL, true, NULL); - controller_->owner_ = owner; - controller_->showing_ = true; - controller_->SetSelection(menu_item.get(), - MenuController::SELECTION_UPDATE_IMMEDIATELY); - controller_->RunMessageLoop(false); - } - -#if defined(USE_X11) - void DispatchEscapeAndExpect(MenuController::ExitType exit_type) { - ui::ScopedXI2Event key_event; - key_event.InitKeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_ESCAPE, 0); - event_source_.Dispatch(key_event); - EXPECT_EQ(exit_type, controller_->exit_type()); - controller_->exit_type_ = MenuController::EXIT_ALL; - DispatchEvent(); - } -#endif - - void DispatchEvent() { -#if defined(USE_X11) - XEvent xevent; - memset(&xevent, 0, sizeof(xevent)); - event_source_.Dispatch(&xevent); -#elif defined(OS_WIN) - MSG msg; - memset(&msg, 0, sizeof(MSG)); - dispatcher_client_.dispatcher()->Dispatch(msg); -#elif defined(USE_OZONE) - ui::KeyEvent event(' ', ui::VKEY_SPACE, ui::EF_NONE); - event_source_.Dispatch(&event); -#else -#error Unsupported platform -#endif - } - - private: - void ResetMenuController() { - if (controller_) { - // These properties are faked by RunMenu for the purposes of testing and - // need to be undone before we call the destructor. - controller_->owner_ = NULL; - controller_->showing_ = false; - delete controller_; - controller_ = NULL; - } - } - - // A weak pointer to the MenuController owned by this class. - MenuController* controller_; - scoped_ptr<base::RunLoop> run_loop_; - TestPlatformEventSource event_source_; - TestDispatcherClient dispatcher_client_; - - DISALLOW_COPY_AND_ASSIGN(MenuControllerTest); -}; - -TEST_F(MenuControllerTest, Basic) { - base::MessageLoop::ScopedNestableTaskAllower allow_nested( - base::MessageLoop::current()); - message_loop()->PostTask( - FROM_HERE, - base::Bind(&MenuControllerTest::Step1_RunMenu, base::Unretained(this))); -} - -#if defined(OS_LINUX) && defined(USE_X11) -// Tests that an event targeter which blocks events will be honored by the menu -// event dispatcher. -TEST_F(MenuControllerTest, EventTargeter) { - { - // Verify that the menu handles the escape key under normal circumstances. - scoped_ptr<Widget> owner(CreateOwnerWidget()); - message_loop()->PostTask( - FROM_HERE, - base::Bind(&MenuControllerTest::DispatchEscapeAndExpect, - base::Unretained(this), - MenuController::EXIT_OUTERMOST)); - RunMenu(owner.get()); - } - - { - // With the NULL targeter instantiated and assigned we expect the menu to - // not handle the key event. - scoped_ptr<Widget> owner(CreateOwnerWidget()); - aura::ScopedWindowTargeter scoped_targeter( - owner->GetNativeWindow()->GetRootWindow(), - scoped_ptr<ui::EventTargeter>(new TestNullTargeter)); - message_loop()->PostTask( - FROM_HERE, - base::Bind(&MenuControllerTest::DispatchEscapeAndExpect, - base::Unretained(this), - MenuController::EXIT_NONE)); - RunMenu(owner.get()); - } -} -#endif - -} // namespace views
diff --git a/ui/views/controls/menu/menu_delegate.cc b/ui/views/controls/menu/menu_delegate.cc deleted file mode 100644 index 461dfc3..0000000 --- a/ui/views/controls/menu/menu_delegate.cc +++ /dev/null
@@ -1,174 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/menu/menu_delegate.h" - -#include "ui/events/event.h" -#include "ui/views/controls/menu/menu_config.h" - -namespace views { - -MenuDelegate::~MenuDelegate() {} - -bool MenuDelegate::IsItemChecked(int id) const { - return false; -} - -base::string16 MenuDelegate::GetLabel(int id) const { - return base::string16(); -} - -const gfx::FontList* MenuDelegate::GetLabelFontList(int id) const { - return NULL; -} - -bool MenuDelegate::GetShouldUseDisabledEmphasizedForegroundColor( - int command_id) const { - return false; -} - -bool MenuDelegate::GetBackgroundColor(int command_id, - bool is_hovered, - SkColor* override_color) const { - return false; -} - -bool MenuDelegate::GetForegroundColor(int command_id, - bool is_hovered, - SkColor* override_color) const { - return false; -} - -base::string16 MenuDelegate::GetTooltipText(int id, - const gfx::Point& screen_loc) const { - return base::string16(); -} - -bool MenuDelegate::GetAccelerator(int id, ui::Accelerator* accelerator) const { - return false; -} - -bool MenuDelegate::ShowContextMenu(MenuItemView* source, - int id, - const gfx::Point& p, - ui::MenuSourceType source_type) { - return false; -} - -bool MenuDelegate::SupportsCommand(int id) const { - return true; -} - -bool MenuDelegate::IsCommandEnabled(int id) const { - return true; -} - -bool MenuDelegate::IsCommandVisible(int id) const { - return true; -} - -bool MenuDelegate::GetContextualLabel(int id, base::string16* out) const { - return false; -} - -bool MenuDelegate::ShouldCloseAllMenusOnExecute(int id) { - return true; -} - -void MenuDelegate::ExecuteCommand(int id, int mouse_event_flags) { - ExecuteCommand(id); -} - -bool MenuDelegate::ShouldExecuteCommandWithoutClosingMenu(int id, - const ui::Event& e) { - return false; -} - -bool MenuDelegate::IsTriggerableEvent(MenuItemView* source, - const ui::Event& e) { - return e.type() == ui::ET_GESTURE_TAP || - e.type() == ui::ET_GESTURE_TAP_DOWN || - (e.IsMouseEvent() && (e.flags() & - (ui::EF_LEFT_MOUSE_BUTTON | ui::EF_RIGHT_MOUSE_BUTTON))); -} - -bool MenuDelegate::CanDrop(MenuItemView* menu, const OSExchangeData& data) { - return false; -} - -bool MenuDelegate::GetDropFormats( - MenuItemView* menu, - int* formats, - std::set<OSExchangeData::CustomFormat>* custom_formats) { - return false; -} - -bool MenuDelegate::AreDropTypesRequired(MenuItemView* menu) { - return false; -} - -int MenuDelegate::GetDropOperation(MenuItemView* item, - const ui::DropTargetEvent& event, - DropPosition* position) { - NOTREACHED() << "If you override CanDrop, you need to override this too"; - return ui::DragDropTypes::DRAG_NONE; -} - -int MenuDelegate::OnPerformDrop(MenuItemView* menu, - DropPosition position, - const ui::DropTargetEvent& event) { - NOTREACHED() << "If you override CanDrop, you need to override this too"; - return ui::DragDropTypes::DRAG_NONE; -} - -bool MenuDelegate::CanDrag(MenuItemView* menu) { - return false; -} - -void MenuDelegate::WriteDragData(MenuItemView* sender, OSExchangeData* data) { - NOTREACHED() << "If you override CanDrag, you must override this too."; -} - -int MenuDelegate::GetDragOperations(MenuItemView* sender) { - NOTREACHED() << "If you override CanDrag, you must override this too."; - return 0; -} - -bool MenuDelegate::ShouldCloseOnDragComplete() { - return true; -} - -MenuItemView* MenuDelegate::GetSiblingMenu(MenuItemView* menu, - const gfx::Point& screen_point, - MenuAnchorPosition* anchor, - bool* has_mnemonics, - MenuButton** button) { - return NULL; -} - -int MenuDelegate::GetMaxWidthForMenu(MenuItemView* menu) { - // NOTE: this needs to be large enough to accommodate the wrench menu with - // big fonts. - return 800; -} - -void MenuDelegate::WillShowMenu(MenuItemView* menu) { -} - -void MenuDelegate::WillHideMenu(MenuItemView* menu) { -} - -void MenuDelegate::GetHorizontalIconMargins(int command_id, - int icon_size, - int* left_margin, - int* right_margin) const { - *left_margin = 0; - *right_margin = 0; -} - -bool MenuDelegate::ShouldReserveSpaceForSubmenuIndicator() const { - return true; -} - -} // namespace views
diff --git a/ui/views/controls/menu/menu_delegate.h b/ui/views/controls/menu/menu_delegate.h deleted file mode 100644 index c75a090..0000000 --- a/ui/views/controls/menu/menu_delegate.h +++ /dev/null
@@ -1,256 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_MENU_MENU_DELEGATE_H_ -#define UI_VIEWS_CONTROLS_MENU_MENU_DELEGATE_H_ - -#include <set> -#include <string> - -#include "base/logging.h" -#include "base/strings/string16.h" -#include "third_party/skia/include/core/SkColor.h" -#include "ui/base/dragdrop/drag_drop_types.h" -#include "ui/base/dragdrop/os_exchange_data.h" -#include "ui/base/ui_base_types.h" -#include "ui/views/controls/menu/menu_types.h" -#include "ui/views/views_export.h" - -using ui::OSExchangeData; - -namespace gfx { -class FontList; -class Point; -} - -namespace ui { -class Accelerator; -class DropTargetEvent; -} - -namespace views { - -class MenuButton; -class MenuItemView; - -// MenuDelegate -------------------------------------------------------------- - -// Delegate for a menu. This class is used as part of MenuItemView, see it -// for details. -// TODO(sky): merge this with ui::MenuModel. -class VIEWS_EXPORT MenuDelegate { - public: - // Used during drag and drop to indicate where the drop indicator should - // be rendered. - enum DropPosition { - DROP_UNKNOWN = -1, - - // Indicates a drop is not allowed here. - DROP_NONE, - - // Indicates the drop should occur before the item. - DROP_BEFORE, - - // Indicates the drop should occur after the item. - DROP_AFTER, - - // Indicates the drop should occur on the item. - DROP_ON - }; - - virtual ~MenuDelegate(); - - // Whether or not an item should be shown as checked. This is invoked for - // radio buttons and check buttons. - virtual bool IsItemChecked(int id) const; - - // The string shown for the menu item. This is only invoked when an item is - // added with an empty label. - virtual base::string16 GetLabel(int id) const; - - // The font for the menu item label. - virtual const gfx::FontList* GetLabelFontList(int id) const; - - // Whether this item should be displayed with a bolder color when disabled. - virtual bool GetShouldUseDisabledEmphasizedForegroundColor( - int command_id) const; - - // Override the text color of a given menu item dependent on the - // |command_id| and its |is_hovered| state. Returns true if it chooses to - // override the color. - // - // TODO(erg): Remove this interface. Injecting raw colors into the menu - // circumvents the NativeTheme. - virtual bool GetForegroundColor(int command_id, - bool is_hovered, - SkColor* override_color) const; - - // Override the background color of a given menu item dependent on the - // |command_id| and its |is_hovered| state. Returns true if it chooses to - // override the color. - // - // TODO(erg): Remove this interface. Injecting raw colors into the menu - // circumvents the NativeTheme. - virtual bool GetBackgroundColor(int command_id, - bool is_hovered, - SkColor* override_color) const; - - // The tooltip shown for the menu item. This is invoked when the user - // hovers over the item, and no tooltip text has been set for that item. - virtual base::string16 GetTooltipText(int id, - const gfx::Point& screen_loc) const; - - // If there is an accelerator for the menu item with id |id| it is set in - // |accelerator| and true is returned. - virtual bool GetAccelerator(int id, ui::Accelerator* accelerator) const; - - // Shows the context menu with the specified id. This is invoked when the - // user does the appropriate gesture to show a context menu. The id - // identifies the id of the menu to show the context menu for. - // is_mouse_gesture is true if this is the result of a mouse gesture. - // If this is not the result of a mouse gesture |p| is the recommended - // location to display the content menu at. In either case, |p| is in - // screen coordinates. - // Returns true if a context menu was displayed, otherwise false - virtual bool ShowContextMenu(MenuItemView* source, - int id, - const gfx::Point& p, - ui::MenuSourceType source_type); - - // Controller - virtual bool SupportsCommand(int id) const; - virtual bool IsCommandEnabled(int id) const; - virtual bool IsCommandVisible(int id) const; - virtual bool GetContextualLabel(int id, base::string16* out) const; - virtual void ExecuteCommand(int id) { - } - - // If nested menus are showing (nested menus occur when a menu shows a context - // menu) this is invoked to determine if all the menus should be closed when - // the user selects the menu with the command |id|. This returns true to - // indicate that all menus should be closed. Return false if only the - // context menu should be closed. - virtual bool ShouldCloseAllMenusOnExecute(int id); - - // Executes the specified command. mouse_event_flags give the flags of the - // mouse event that triggered this to be invoked (ui::MouseEvent - // flags). mouse_event_flags is 0 if this is triggered by a user gesture - // other than a mouse event. - virtual void ExecuteCommand(int id, int mouse_event_flags); - - // Returns true if ExecuteCommand() should be invoked while leaving the - // menu open. Default implementation returns true. - virtual bool ShouldExecuteCommandWithoutClosingMenu(int id, - const ui::Event& e); - - // Returns true if the specified event is one the user can use to trigger, or - // accept, the item. Defaults to left or right mouse buttons or tap. - virtual bool IsTriggerableEvent(MenuItemView* view, const ui::Event& e); - - // Invoked to determine if drops can be accepted for a submenu. This is - // ONLY invoked for menus that have submenus and indicates whether or not - // a drop can occur on any of the child items of the item. For example, - // consider the following menu structure: - // - // A - // B - // C - // - // Where A has a submenu with children B and C. This is ONLY invoked for - // A, not B and C. - // - - // To restrict which children can be dropped on override GetDropOperation. - virtual bool CanDrop(MenuItemView* menu, const OSExchangeData& data); - - // See view for a description of this method. - virtual bool GetDropFormats( - MenuItemView* menu, - int* formats, - std::set<OSExchangeData::CustomFormat>* custom_formats); - - // See view for a description of this method. - virtual bool AreDropTypesRequired(MenuItemView* menu); - - // Returns the drop operation for the specified target menu item. This is - // only invoked if CanDrop returned true for the parent menu. position - // is set based on the location of the mouse, reset to specify a different - // position. - // - // If a drop should not be allowed, returned ui::DragDropTypes::DRAG_NONE. - virtual int GetDropOperation(MenuItemView* item, - const ui::DropTargetEvent& event, - DropPosition* position); - - // Invoked to perform the drop operation. This is ONLY invoked if CanDrop() - // returned true for the parent menu item, and GetDropOperation() returned an - // operation other than ui::DragDropTypes::DRAG_NONE. - // - // |menu| is the menu the drop occurred on. - virtual int OnPerformDrop(MenuItemView* menu, - DropPosition position, - const ui::DropTargetEvent& event); - - // Invoked to determine if it is possible for the user to drag the specified - // menu item. - virtual bool CanDrag(MenuItemView* menu); - - // Invoked to write the data for a drag operation to data. sender is the - // MenuItemView being dragged. - virtual void WriteDragData(MenuItemView* sender, OSExchangeData* data); - - // Invoked to determine the drag operations for a drag session of sender. - // See DragDropTypes for possible values. - virtual int GetDragOperations(MenuItemView* sender); - - // Notification the menu has closed. This is only sent when running the - // menu for a drop. - virtual void DropMenuClosed(MenuItemView* menu) { - } - - // Returns true if the menu should close upon a drag completing. Defaults to - // true. This is only invoked for drag and drop operations performed on child - // Views that are not MenuItemViews. - virtual bool ShouldCloseOnDragComplete(); - - // Notification that the user has highlighted the specified item. - virtual void SelectionChanged(MenuItemView* menu) { - } - - // If the user drags the mouse outside the bounds of the menu the delegate - // is queried for a sibling menu to show. If this returns non-null the - // current menu is hidden, and the menu returned from this method is shown. - // - // The delegate owns the returned menu, not the controller. - virtual MenuItemView* GetSiblingMenu(MenuItemView* menu, - const gfx::Point& screen_point, - MenuAnchorPosition* anchor, - bool* has_mnemonics, - MenuButton** button); - - // Returns the max width menus can grow to be. - virtual int GetMaxWidthForMenu(MenuItemView* menu); - - // Invoked prior to a menu being shown. - virtual void WillShowMenu(MenuItemView* menu); - - // Invoked prior to a menu being hidden. - virtual void WillHideMenu(MenuItemView* menu); - - // Returns additional horizontal spacing for the icon of the given item. - // The |command_id| specifies the item of interest, the |icon_size| tells the - // function the size of the icon and it will then return |left_margin| - // and |right_margin| accordingly. Note: Negative values can be returned. - virtual void GetHorizontalIconMargins(int command_id, - int icon_size, - int* left_margin, - int* right_margin) const; - // Returns true if the labels should reserve additional spacing for e.g. - // submenu indicators at the end of the line. - virtual bool ShouldReserveSpaceForSubmenuIndicator() const; -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_MENU_MENU_DELEGATE_H_
diff --git a/ui/views/controls/menu/menu_event_dispatcher_linux.cc b/ui/views/controls/menu/menu_event_dispatcher_linux.cc deleted file mode 100644 index 181ba24..0000000 --- a/ui/views/controls/menu/menu_event_dispatcher_linux.cc +++ /dev/null
@@ -1,91 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/menu/menu_event_dispatcher_linux.h" - -#include "base/memory/scoped_ptr.h" -#include "ui/aura/window.h" -#include "ui/events/event_utils.h" -#include "ui/events/keycodes/keyboard_code_conversion.h" -#include "ui/events/keycodes/keyboard_codes.h" -#include "ui/views/controls/menu/menu_controller.h" -#include "ui/views/widget/widget.h" - -namespace views { -namespace internal { - -MenuEventDispatcher::MenuEventDispatcher(MenuController* controller) - : menu_controller_(controller) {} - -MenuEventDispatcher::~MenuEventDispatcher() {} - -bool MenuEventDispatcher::CanDispatchEvent(const ui::PlatformEvent& event) { - return true; -} - -uint32_t MenuEventDispatcher::DispatchEvent(const ui::PlatformEvent& event) { - bool should_quit = false; - bool should_perform_default = true; - bool should_process_event = true; - - // Check if the event should be handled. - scoped_ptr<ui::Event> ui_event(ui::EventFromNative(event)); - if (ui_event && menu_controller_->owner()) { - aura::Window* menu_window = menu_controller_->owner()->GetNativeWindow(); - aura::Window* target_window = static_cast<aura::Window*>( - static_cast<ui::EventTarget*>(menu_window->GetRootWindow())-> - GetEventTargeter()->FindTargetForEvent(menu_window, - ui_event.get())); - // TODO(flackr): The event shouldn't be handled if target_window is not - // menu_window, however the event targeter does not properly target the - // open menu. For now, we allow targeters to prevent handling by the menu. - if (!target_window) - should_process_event = false; - } - - if (menu_controller_->exit_type() == MenuController::EXIT_ALL || - menu_controller_->exit_type() == MenuController::EXIT_DESTROYED) { - should_quit = true; - } else if (should_process_event) { - switch (ui::EventTypeFromNative(event)) { - case ui::ET_KEY_PRESSED: { - if (!menu_controller_->OnKeyDown(ui::KeyboardCodeFromNative(event))) { - should_quit = true; - should_perform_default = false; - break; - } - - // Do not check mnemonics if the Alt or Ctrl modifiers are pressed. - int flags = ui::EventFlagsFromNative(event); - if ((flags & (ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN)) == 0) { - char c = ui::GetCharacterFromKeyCode( - ui::KeyboardCodeFromNative(event), flags); - if (menu_controller_->SelectByChar(c)) { - should_quit = true; - should_perform_default = false; - break; - } - } - should_quit = false; - should_perform_default = false; - break; - } - case ui::ET_KEY_RELEASED: - should_quit = false; - should_perform_default = false; - break; - default: - break; - } - } - - if (should_quit || menu_controller_->exit_type() != MenuController::EXIT_NONE) - menu_controller_->TerminateNestedMessageLoop(); - - return should_perform_default ? ui::POST_DISPATCH_PERFORM_DEFAULT - : ui::POST_DISPATCH_NONE; -} - -} // namespace internal -} // namespace views
diff --git a/ui/views/controls/menu/menu_event_dispatcher_linux.h b/ui/views/controls/menu/menu_event_dispatcher_linux.h deleted file mode 100644 index a516d2e..0000000 --- a/ui/views/controls/menu/menu_event_dispatcher_linux.h +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/macros.h" -#include "ui/events/platform/platform_event_dispatcher.h" - -namespace views { - -class MenuController; - -namespace internal { - -// A message-pump dispatcher object used to dispatch events from the nested -// message-loop initiated by the MenuController. -class MenuEventDispatcher : public ui::PlatformEventDispatcher { - public: - explicit MenuEventDispatcher(MenuController* menu_controller); - virtual ~MenuEventDispatcher(); - - private: - // ui::PlatformEventDispatcher: - virtual bool CanDispatchEvent(const ui::PlatformEvent& event) override; - virtual uint32_t DispatchEvent(const ui::PlatformEvent& event) override; - - MenuController* menu_controller_; - - DISALLOW_COPY_AND_ASSIGN(MenuEventDispatcher); -}; - -} // namespace internal -} // namespace views
diff --git a/ui/views/controls/menu/menu_host.cc b/ui/views/controls/menu/menu_host.cc deleted file mode 100644 index 3a8217f..0000000 --- a/ui/views/controls/menu/menu_host.cc +++ /dev/null
@@ -1,168 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/menu/menu_host.h" - -#include "base/auto_reset.h" -#include "base/debug/trace_event.h" -#include "ui/events/gestures/gesture_recognizer.h" -#include "ui/gfx/path.h" -#include "ui/native_theme/native_theme.h" -#include "ui/views/controls/menu/menu_controller.h" -#include "ui/views/controls/menu/menu_host_root_view.h" -#include "ui/views/controls/menu/menu_item_view.h" -#include "ui/views/controls/menu/menu_scroll_view_container.h" -#include "ui/views/controls/menu/submenu_view.h" -#include "ui/views/round_rect_painter.h" -#include "ui/views/widget/native_widget_private.h" -#include "ui/views/widget/widget.h" - -namespace views { - -//////////////////////////////////////////////////////////////////////////////// -// MenuHost, public: - -MenuHost::MenuHost(SubmenuView* submenu) - : submenu_(submenu), - destroying_(false), - ignore_capture_lost_(false) { - set_auto_release_capture(false); -} - -MenuHost::~MenuHost() { -} - -void MenuHost::InitMenuHost(Widget* parent, - const gfx::Rect& bounds, - View* contents_view, - bool do_capture) { - TRACE_EVENT0("views", "MenuHost::InitMenuHost"); - Widget::InitParams params(Widget::InitParams::TYPE_MENU); - const MenuController* menu_controller = - submenu_->GetMenuItem()->GetMenuController(); - const MenuConfig& menu_config = submenu_->GetMenuItem()->GetMenuConfig(); - bool rounded_border = menu_controller && menu_config.corner_radius > 0; - bool bubble_border = submenu_->GetScrollViewContainer() && - submenu_->GetScrollViewContainer()->HasBubbleBorder(); - params.shadow_type = bubble_border ? Widget::InitParams::SHADOW_TYPE_NONE - : Widget::InitParams::SHADOW_TYPE_DROP; - params.opacity = (bubble_border || rounded_border) ? - Widget::InitParams::TRANSLUCENT_WINDOW : - Widget::InitParams::OPAQUE_WINDOW; - params.parent = parent ? parent->GetNativeView() : NULL; - params.bounds = bounds; - Init(params); - - SetContentsView(contents_view); - ShowMenuHost(do_capture); -} - -bool MenuHost::IsMenuHostVisible() { - return IsVisible(); -} - -void MenuHost::ShowMenuHost(bool do_capture) { - // Doing a capture may make us get capture lost. Ignore it while we're in the - // process of showing. - base::AutoReset<bool> reseter(&ignore_capture_lost_, true); - ShowInactive(); - if (do_capture) { - // Cancel existing touches, so we don't miss some touch release/cancel - // events due to the menu taking capture. - ui::GestureRecognizer::Get()->TransferEventsTo(NULL, NULL); - native_widget_private()->SetCapture(); - } -} - -void MenuHost::HideMenuHost() { - ignore_capture_lost_ = true; - ReleaseMenuHostCapture(); - Hide(); - ignore_capture_lost_ = false; -} - -void MenuHost::DestroyMenuHost() { - HideMenuHost(); - destroying_ = true; - static_cast<MenuHostRootView*>(GetRootView())->ClearSubmenu(); - Close(); -} - -void MenuHost::SetMenuHostBounds(const gfx::Rect& bounds) { - SetBounds(bounds); -} - -void MenuHost::ReleaseMenuHostCapture() { - if (native_widget_private()->HasCapture()) - native_widget_private()->ReleaseCapture(); -} - -//////////////////////////////////////////////////////////////////////////////// -// MenuHost, Widget overrides: - -internal::RootView* MenuHost::CreateRootView() { - return new MenuHostRootView(this, submenu_); -} - -void MenuHost::OnMouseCaptureLost() { - if (destroying_ || ignore_capture_lost_) - return; - MenuController* menu_controller = - submenu_->GetMenuItem()->GetMenuController(); - if (menu_controller && !menu_controller->drag_in_progress()) - menu_controller->CancelAll(); - Widget::OnMouseCaptureLost(); -} - -void MenuHost::OnNativeWidgetDestroyed() { - if (!destroying_) { - // We weren't explicitly told to destroy ourselves, which means the menu was - // deleted out from under us (the window we're parented to was closed). Tell - // the SubmenuView to drop references to us. - submenu_->MenuHostDestroyed(); - } - Widget::OnNativeWidgetDestroyed(); -} - -void MenuHost::OnOwnerClosing() { - if (destroying_) - return; - - MenuController* menu_controller = - submenu_->GetMenuItem()->GetMenuController(); - if (menu_controller && !menu_controller->drag_in_progress()) - menu_controller->CancelAll(); -} - -void MenuHost::OnDragWillStart() { - MenuController* menu_controller = - submenu_->GetMenuItem()->GetMenuController(); - DCHECK(menu_controller); - menu_controller->OnDragWillStart(); -} - -void MenuHost::OnDragComplete() { - MenuController* menu_controller = - submenu_->GetMenuItem()->GetMenuController(); - if (destroying_ || !menu_controller) - return; - - bool should_close = true; - // If the view came from outside menu code (i.e., not a MenuItemView), we - // should consult the MenuDelegate to determine whether or not to close on - // exit. - if (!menu_controller->did_initiate_drag()) { - MenuDelegate* menu_delegate = submenu_->GetMenuItem()->GetDelegate(); - should_close = - menu_delegate ? menu_delegate->ShouldCloseOnDragComplete() : should_close; - } - menu_controller->OnDragComplete(should_close); - - // We may have lost capture in the drag and drop, but are remaining open. - // Return capture so we get MouseCaptureLost events. - if (!should_close) - native_widget_private()->SetCapture(); -} - -} // namespace views
diff --git a/ui/views/controls/menu/menu_host.h b/ui/views/controls/menu/menu_host.h deleted file mode 100644 index 31ad7de..0000000 --- a/ui/views/controls/menu/menu_host.h +++ /dev/null
@@ -1,80 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_MENU_MENU_HOST_H_ -#define UI_VIEWS_CONTROLS_MENU_MENU_HOST_H_ - -#include "base/compiler_specific.h" -#include "ui/gfx/rect.h" -#include "ui/views/widget/widget.h" - -namespace views { - -class NativeWidget; -class SubmenuView; -class View; -class Widget; - -// SubmenuView uses a MenuHost to house the SubmenuView. -// -// SubmenuView owns the MenuHost. When SubmenuView is done with the MenuHost -// |DestroyMenuHost| is invoked. The one exception to this is if the native -// OS destroys the widget out from under us, in which case |MenuHostDestroyed| -// is invoked back on the SubmenuView and the SubmenuView then drops references -// to the MenuHost. -class MenuHost : public Widget { - public: - explicit MenuHost(SubmenuView* submenu); - virtual ~MenuHost(); - - // Initializes and shows the MenuHost. - // WARNING: |parent| may be NULL. - void InitMenuHost(Widget* parent, - const gfx::Rect& bounds, - View* contents_view, - bool do_capture); - - // Returns true if the menu host is visible. - bool IsMenuHostVisible(); - - // Shows the menu host. If |do_capture| is true the menu host should do a - // mouse grab. - void ShowMenuHost(bool do_capture); - - // Hides the menu host. - void HideMenuHost(); - - // Destroys and deletes the menu host. - void DestroyMenuHost(); - - // Sets the bounds of the menu host. - void SetMenuHostBounds(const gfx::Rect& bounds); - - // Releases a mouse grab installed by |ShowMenuHost|. - void ReleaseMenuHostCapture(); - - private: - // Overridden from Widget: - virtual internal::RootView* CreateRootView() override; - virtual void OnMouseCaptureLost() override; - virtual void OnNativeWidgetDestroyed() override; - virtual void OnOwnerClosing() override; - virtual void OnDragWillStart() override; - virtual void OnDragComplete() override; - - // The view we contain. - SubmenuView* submenu_; - - // If true, DestroyMenuHost has been invoked. - bool destroying_; - - // If true and capture is lost we don't notify the delegate. - bool ignore_capture_lost_; - - DISALLOW_COPY_AND_ASSIGN(MenuHost); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_MENU_MENU_HOST_H_
diff --git a/ui/views/controls/menu/menu_host_root_view.cc b/ui/views/controls/menu/menu_host_root_view.cc deleted file mode 100644 index 1bc834a..0000000 --- a/ui/views/controls/menu/menu_host_root_view.cc +++ /dev/null
@@ -1,79 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/menu/menu_host_root_view.h" - -#include "ui/views/controls/menu/menu_controller.h" -#include "ui/views/controls/menu/menu_item_view.h" -#include "ui/views/controls/menu/submenu_view.h" - -namespace views { - -MenuHostRootView::MenuHostRootView(Widget* widget, - SubmenuView* submenu) - : internal::RootView(widget), - submenu_(submenu), - forward_drag_to_menu_controller_(true) { -} - -bool MenuHostRootView::OnMousePressed(const ui::MouseEvent& event) { - forward_drag_to_menu_controller_ = - !GetLocalBounds().Contains(event.location()) || - !RootView::OnMousePressed(event) || - DoesEventTargetEmptyMenuItem(event); - - if (forward_drag_to_menu_controller_ && GetMenuController()) - GetMenuController()->OnMousePressed(submenu_, event); - return true; -} - -bool MenuHostRootView::OnMouseDragged(const ui::MouseEvent& event) { - if (forward_drag_to_menu_controller_ && GetMenuController()) { - GetMenuController()->OnMouseDragged(submenu_, event); - return true; - } - return RootView::OnMouseDragged(event); -} - -void MenuHostRootView::OnMouseReleased(const ui::MouseEvent& event) { - RootView::OnMouseReleased(event); - if (forward_drag_to_menu_controller_ && GetMenuController()) { - forward_drag_to_menu_controller_ = false; - GetMenuController()->OnMouseReleased(submenu_, event); - } -} - -void MenuHostRootView::OnMouseMoved(const ui::MouseEvent& event) { - RootView::OnMouseMoved(event); - if (GetMenuController()) - GetMenuController()->OnMouseMoved(submenu_, event); -} - -bool MenuHostRootView::OnMouseWheel(const ui::MouseWheelEvent& event) { - return GetMenuController() && - GetMenuController()->OnMouseWheel(submenu_, event); -} - -void MenuHostRootView::OnEventProcessingFinished(ui::Event* event) { - RootView::OnEventProcessingFinished(event); - - // Forward unhandled gesture events to our menu controller. - // TODO(tdanderson): Investigate whether this should be moved into a - // post-target handler installed on |this| instead - // (invoked only if event->target() == this). - if (event->IsGestureEvent() && !event->handled() && GetMenuController()) - GetMenuController()->OnGestureEvent(submenu_, event->AsGestureEvent()); -} - -MenuController* MenuHostRootView::GetMenuController() { - return submenu_ ? submenu_->GetMenuItem()->GetMenuController() : NULL; -} - -bool MenuHostRootView::DoesEventTargetEmptyMenuItem( - const ui::MouseEvent& event) { - View* view = GetEventHandlerForPoint(event.location()); - return view && view->id() == MenuItemView::kEmptyMenuItemViewID; -} - -} // namespace views
diff --git a/ui/views/controls/menu/menu_host_root_view.h b/ui/views/controls/menu/menu_host_root_view.h deleted file mode 100644 index f08c813..0000000 --- a/ui/views/controls/menu/menu_host_root_view.h +++ /dev/null
@@ -1,55 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_MENU_MENU_HOST_ROOT_VIEW_H_ -#define UI_VIEWS_CONTROLS_MENU_MENU_HOST_ROOT_VIEW_H_ - -#include "ui/views/widget/root_view.h" - -namespace views { - -class MenuController; -class SubmenuView; - -// MenuHostRootView is the RootView of the window showing the menu. -// SubmenuView's scroll view is added as a child of MenuHostRootView. -// MenuHostRootView forwards relevant events to the MenuController. -// -// As all the menu items are owned by the root menu item, care must be taken -// such that when MenuHostRootView is deleted it doesn't delete the menu items. -class MenuHostRootView : public internal::RootView { - public: - MenuHostRootView(Widget* widget, SubmenuView* submenu); - - void ClearSubmenu() { submenu_ = NULL; } - - // Overridden from View: - virtual bool OnMousePressed(const ui::MouseEvent& event) override; - virtual bool OnMouseDragged(const ui::MouseEvent& event) override; - virtual void OnMouseReleased(const ui::MouseEvent& event) override; - virtual void OnMouseMoved(const ui::MouseEvent& event) override; - virtual bool OnMouseWheel(const ui::MouseWheelEvent& event) override; - - private: - // ui::EventProcessor: - virtual void OnEventProcessingFinished(ui::Event* event) override; - - // Returns the MenuController for this MenuHostRootView. - MenuController* GetMenuController(); - - // Returns true if event targets EmptyMenu. - bool DoesEventTargetEmptyMenuItem(const ui::MouseEvent& event); - - // The SubmenuView we contain. - SubmenuView* submenu_; - - // Whether mouse dragged/released should be forwarded to the MenuController. - bool forward_drag_to_menu_controller_; - - DISALLOW_COPY_AND_ASSIGN(MenuHostRootView); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_MENU_MENU_HOST_ROOT_VIEW_H_
diff --git a/ui/views/controls/menu/menu_image_util.cc b/ui/views/controls/menu/menu_image_util.cc deleted file mode 100644 index 84f33bd..0000000 --- a/ui/views/controls/menu/menu_image_util.cc +++ /dev/null
@@ -1,169 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/menu/menu_image_util.h" - -#include "base/i18n/rtl.h" -#include "base/logging.h" -#include "third_party/skia/include/effects/SkGradientShader.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/image/canvas_image_source.h" -#include "ui/gfx/image/image.h" -#include "ui/gfx/image/image_skia.h" -#include "ui/gfx/image/image_skia_source.h" -#include "ui/gfx/point.h" -#include "ui/gfx/size.h" -#include "ui/resources/grit/ui_resources.h" - -namespace { - -// Size of the radio button inciator. -const int kSelectedIndicatorSize = 5; -const int kIndicatorSize = 10; - -// Used for the radio indicator. See theme_draw for details. -const double kGradientStop = .5; -const SkColor kGradient0 = SkColorSetRGB(255, 255, 255); -const SkColor kGradient1 = SkColorSetRGB(255, 255, 255); -const SkColor kGradient2 = SkColorSetRGB(0xD8, 0xD8, 0xD8); -const SkColor kBaseStroke = SkColorSetRGB(0x8F, 0x8F, 0x8F); -const SkColor kRadioButtonIndicatorGradient0 = SkColorSetRGB(0, 0, 0); -const SkColor kRadioButtonIndicatorGradient1 = SkColorSetRGB(0x83, 0x83, 0x83); -const SkColor kIndicatorStroke = SkColorSetRGB(0, 0, 0); - -class RadioButtonImageSource : public gfx::CanvasImageSource { - public: - explicit RadioButtonImageSource(bool selected) - : CanvasImageSource(gfx::Size(kIndicatorSize + 2, kIndicatorSize + 2), - false), - selected_(selected) { - } - virtual ~RadioButtonImageSource() {} - - virtual void Draw(gfx::Canvas* canvas) override { - canvas->Translate(gfx::Vector2d(1, 1)); - - SkPoint gradient_points[3]; - gradient_points[0].iset(0, 0); - gradient_points[1].iset(0, - static_cast<int>(kIndicatorSize * kGradientStop)); - gradient_points[2].iset(0, kIndicatorSize); - SkColor gradient_colors[3] = { kGradient0, kGradient1, kGradient2 }; - skia::RefPtr<SkShader> shader = skia::AdoptRef( - SkGradientShader::CreateLinear( - gradient_points, gradient_colors, NULL, arraysize(gradient_points), - SkShader::kClamp_TileMode)); - SkPaint paint; - paint.setStyle(SkPaint::kFill_Style); - paint.setAntiAlias(true); - paint.setShader(shader.get()); - int radius = kIndicatorSize / 2; - canvas->sk_canvas()->drawCircle(radius, radius, radius, paint); - paint.setStrokeWidth(SkIntToScalar(0)); - paint.setShader(NULL); - paint.setStyle(SkPaint::kStroke_Style); - paint.setColor(kBaseStroke); - canvas->sk_canvas()->drawCircle(radius, radius, radius, paint); - - if (selected_) { - SkPoint selected_gradient_points[2]; - selected_gradient_points[0].iset(0, 0); - selected_gradient_points[1].iset(0, kSelectedIndicatorSize); - SkColor selected_gradient_colors[2] = { kRadioButtonIndicatorGradient0, - kRadioButtonIndicatorGradient1 }; - shader = skia::AdoptRef( - SkGradientShader::CreateLinear( - selected_gradient_points, selected_gradient_colors, NULL, - arraysize(selected_gradient_points), SkShader::kClamp_TileMode)); - paint.setShader(shader.get()); - paint.setStyle(SkPaint::kFill_Style); - canvas->sk_canvas()->drawCircle(radius, radius, - kSelectedIndicatorSize / 2, paint); - - paint.setStrokeWidth(SkIntToScalar(0)); - paint.setShader(NULL); - paint.setStyle(SkPaint::kStroke_Style); - paint.setColor(kIndicatorStroke); - canvas->sk_canvas()->drawCircle(radius, radius, - kSelectedIndicatorSize / 2, paint); - } - } - - private: - bool selected_; - - DISALLOW_COPY_AND_ASSIGN(RadioButtonImageSource); -}; - -class SubmenuArrowImageSource : public gfx::CanvasImageSource { - public: - SubmenuArrowImageSource(int image_id) - : gfx::CanvasImageSource(ui::ResourceBundle::GetSharedInstance(). - GetImageNamed(image_id).ToImageSkia()->size(), false), - image_id_(image_id) {} - virtual ~SubmenuArrowImageSource() {} - - virtual void Draw(gfx::Canvas* canvas) override { - ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); - const gfx::ImageSkia* r = rb.GetImageNamed(image_id_).ToImageSkia(); - canvas->Scale(-1, 1); - canvas->DrawImageInt(*r, - r->width(), 0); - } - - private: - static gfx::Size GetSubmenuArrowSize() { - return ui::ResourceBundle::GetSharedInstance() - .GetImageNamed(IDR_MENU_HIERARCHY_ARROW).ToImageSkia()->size(); - } - - int image_id_; - - DISALLOW_COPY_AND_ASSIGN(SubmenuArrowImageSource); -}; - -gfx::ImageSkia GetRtlSubmenuArrowImage(bool rtl, - bool dark_background) { - int image_id = dark_background ? IDR_MENU_HIERARCHY_ARROW_DARK_BACKGROUND : - IDR_MENU_HIERARCHY_ARROW; - - if (!rtl) { - return ui::ResourceBundle::GetSharedInstance().GetImageNamed(image_id). - AsImageSkia(); - } - - static gfx::ImageSkia* kRtlArrow = NULL; - static gfx::ImageSkia* kRtlArrowDarkBg = NULL; - gfx::ImageSkia** image = dark_background ? &kRtlArrowDarkBg : &kRtlArrow; - - if (!*image) { - SubmenuArrowImageSource* source = new SubmenuArrowImageSource(image_id); - *image = new gfx::ImageSkia(source, source->size()); - } - - return **image; -} - -} // namespace - -namespace views { - -gfx::ImageSkia GetMenuCheckImage(bool dark_background) { - int image_id = dark_background ? IDR_MENU_CHECK_CHECKED_DARK_BACKGROUND : - IDR_MENU_CHECK_CHECKED; - return ui::ResourceBundle::GetSharedInstance().GetImageNamed(image_id). - AsImageSkia(); -} - -gfx::ImageSkia GetRadioButtonImage(bool selected) { - int image_id = selected ? IDR_MENU_RADIO_SELECTED : IDR_MENU_RADIO_EMPTY; - return ui::ResourceBundle::GetSharedInstance().GetImageNamed(image_id). - AsImageSkia(); -} - -gfx::ImageSkia GetSubmenuArrowImage(bool dark_background) { - return GetRtlSubmenuArrowImage(base::i18n::IsRTL(), dark_background); -} - -} // namespace views
diff --git a/ui/views/controls/menu/menu_image_util.h b/ui/views/controls/menu/menu_image_util.h deleted file mode 100644 index 93645c8..0000000 --- a/ui/views/controls/menu/menu_image_util.h +++ /dev/null
@@ -1,33 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_MENU_MENU_IMAGE_UTIL_H_ -#define UI_VIEWS_CONTROLS_MENU_MENU_IMAGE_UTIL_H_ - -namespace gfx { -class ImageSkia; -} - -namespace views { - -// Returns the Menu Check box image (always checked). -// The returned image is global object and should not be freed. -// |dark_background| should be true if the check will be displayed on a -// dark background (such as a hovered menu item). -gfx::ImageSkia GetMenuCheckImage(bool dark_background); - -// Return the RadioButton image for given state. -// It returns the "selected" image when |selected| is -// true, or the "unselected" image if false. -// The returned image is global object and should not be freed. -gfx::ImageSkia GetRadioButtonImage(bool selected); - -// Returns the image for submenu arrow for current RTL setting. -// |dark_background| should be true if the check will be displayed on a -// dark background (such as a hovered menu item). -gfx::ImageSkia GetSubmenuArrowImage(bool dark_background); - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_MENU_MENU_IMAGE_UTIL_H_
diff --git a/ui/views/controls/menu/menu_insertion_delegate_win.h b/ui/views/controls/menu/menu_insertion_delegate_win.h deleted file mode 100644 index b6f3697..0000000 --- a/ui/views/controls/menu/menu_insertion_delegate_win.h +++ /dev/null
@@ -1,23 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_MENU_MENU_INSERTION_DELEGATE_WIN_H_ -#define UI_VIEWS_CONTROLS_MENU_MENU_INSERTION_DELEGATE_WIN_H_ - -#include <windows.h> - -namespace views { - -class MenuInsertionDelegateWin { - public: - // Returns the index to insert items into the menu at. - virtual int GetInsertionIndex(HMENU native_menu) = 0; - - protected: - virtual ~MenuInsertionDelegateWin() {} -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_MENU_MENU_INSERTION_DELEGATE_WIN_H_
diff --git a/ui/views/controls/menu/menu_item_view.cc b/ui/views/controls/menu/menu_item_view.cc deleted file mode 100644 index 6b11d3a..0000000 --- a/ui/views/controls/menu/menu_item_view.cc +++ /dev/null
@@ -1,1086 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/menu/menu_item_view.h" - -#include "base/i18n/case_conversion.h" -#include "base/stl_util.h" -#include "base/strings/utf_string_conversions.h" -#include "ui/accessibility/ax_view_state.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/base/models/menu_model.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/geometry/rect.h" -#include "ui/gfx/geometry/vector2d.h" -#include "ui/gfx/image/image.h" -#include "ui/gfx/text_utils.h" -#include "ui/native_theme/common_theme.h" -#include "ui/resources/grit/ui_resources.h" -#include "ui/strings/grit/ui_strings.h" -#include "ui/views/controls/button/menu_button.h" -#include "ui/views/controls/image_view.h" -#include "ui/views/controls/menu/menu_config.h" -#include "ui/views/controls/menu/menu_controller.h" -#include "ui/views/controls/menu/menu_image_util.h" -#include "ui/views/controls/menu/menu_scroll_view_container.h" -#include "ui/views/controls/menu/menu_separator.h" -#include "ui/views/controls/menu/submenu_view.h" -#include "ui/views/widget/widget.h" - -namespace views { - -namespace { - -// EmptyMenuMenuItem --------------------------------------------------------- - -// EmptyMenuMenuItem is used when a menu has no menu items. EmptyMenuMenuItem -// is itself a MenuItemView, but it uses a different ID so that it isn't -// identified as a MenuItemView. - -class EmptyMenuMenuItem : public MenuItemView { - public: - explicit EmptyMenuMenuItem(MenuItemView* parent) - : MenuItemView(parent, 0, EMPTY) { - // Set this so that we're not identified as a normal menu item. - set_id(kEmptyMenuItemViewID); - SetTitle(l10n_util::GetStringUTF16(IDS_APP_MENU_EMPTY_SUBMENU)); - SetEnabled(false); - } - - virtual bool GetTooltipText(const gfx::Point& p, - base::string16* tooltip) const override { - // Empty menu items shouldn't have a tooltip. - return false; - } - - private: - DISALLOW_COPY_AND_ASSIGN(EmptyMenuMenuItem); -}; - -} // namespace - -// Padding between child views. -static const int kChildXPadding = 8; - -// MenuItemView --------------------------------------------------------------- - -// static -const int MenuItemView::kMenuItemViewID = 1001; - -// static -const int MenuItemView::kEmptyMenuItemViewID = - MenuItemView::kMenuItemViewID + 1; - -// static -int MenuItemView::icon_area_width_ = 0; - -// static -int MenuItemView::label_start_; - -// static -int MenuItemView::item_right_margin_; - -// static -int MenuItemView::pref_menu_height_; - -// static -const char MenuItemView::kViewClassName[] = "MenuItemView"; - -MenuItemView::MenuItemView(MenuDelegate* delegate) - : delegate_(delegate), - controller_(NULL), - canceled_(false), - parent_menu_item_(NULL), - type_(SUBMENU), - selected_(false), - command_(0), - submenu_(NULL), - has_mnemonics_(false), - show_mnemonics_(false), - has_icons_(false), - icon_view_(NULL), - top_margin_(-1), - bottom_margin_(-1), - left_icon_margin_(0), - right_icon_margin_(0), - requested_menu_position_(POSITION_BEST_FIT), - actual_menu_position_(requested_menu_position_), - use_right_margin_(true) { - // NOTE: don't check the delegate for NULL, UpdateMenuPartSizes() supplies a - // NULL delegate. - Init(NULL, 0, SUBMENU, delegate); -} - -void MenuItemView::ChildPreferredSizeChanged(View* child) { - invalidate_dimensions(); - PreferredSizeChanged(); -} - -bool MenuItemView::GetTooltipText(const gfx::Point& p, - base::string16* tooltip) const { - *tooltip = tooltip_; - if (!tooltip->empty()) - return true; - - if (GetType() == SEPARATOR) - return false; - - const MenuController* controller = GetMenuController(); - if (!controller || controller->exit_type() != MenuController::EXIT_NONE) { - // Either the menu has been closed or we're in the process of closing the - // menu. Don't attempt to query the delegate as it may no longer be valid. - return false; - } - - const MenuItemView* root_menu_item = GetRootMenuItem(); - if (root_menu_item->canceled_) { - // TODO(sky): if |canceled_| is true, controller->exit_type() should be - // something other than EXIT_NONE, but crash reports seem to indicate - // otherwise. Figure out why this is needed. - return false; - } - - const MenuDelegate* delegate = GetDelegate(); - CHECK(delegate); - gfx::Point location(p); - ConvertPointToScreen(this, &location); - *tooltip = delegate->GetTooltipText(command_, location); - return !tooltip->empty(); -} - -void MenuItemView::GetAccessibleState(ui::AXViewState* state) { - state->role = ui::AX_ROLE_MENU_ITEM; - - base::string16 item_text; - if (IsContainer()) { - // The first child is taking over, just use its accessible name instead of - // |title_|. - View* child = child_at(0); - ui::AXViewState state; - child->GetAccessibleState(&state); - item_text = state.name; - } else { - item_text = title_; - } - state->name = GetAccessibleNameForMenuItem(item_text, GetMinorText()); - - switch (GetType()) { - case SUBMENU: - state->AddStateFlag(ui::AX_STATE_HASPOPUP); - break; - case CHECKBOX: - case RADIO: - if (GetDelegate()->IsItemChecked(GetCommand())) - state->AddStateFlag(ui::AX_STATE_CHECKED); - break; - case NORMAL: - case SEPARATOR: - case EMPTY: - // No additional accessibility states currently for these menu states. - break; - } -} - -// static -bool MenuItemView::IsBubble(MenuAnchorPosition anchor) { - return anchor == MENU_ANCHOR_BUBBLE_LEFT || - anchor == MENU_ANCHOR_BUBBLE_RIGHT || - anchor == MENU_ANCHOR_BUBBLE_ABOVE || - anchor == MENU_ANCHOR_BUBBLE_BELOW; -} - -// static -base::string16 MenuItemView::GetAccessibleNameForMenuItem( - const base::string16& item_text, const base::string16& minor_text) { - base::string16 accessible_name = item_text; - - // Filter out the "&" for accessibility clients. - size_t index = 0; - const base::char16 amp = '&'; - while ((index = accessible_name.find(amp, index)) != base::string16::npos && - index + 1 < accessible_name.length()) { - accessible_name.replace(index, accessible_name.length() - index, - accessible_name.substr(index + 1)); - - // Special case for "&&" (escaped for "&"). - if (accessible_name[index] == '&') - ++index; - } - - // Append subtext. - if (!minor_text.empty()) { - accessible_name.push_back(' '); - accessible_name.append(minor_text); - } - - return accessible_name; -} - -void MenuItemView::Cancel() { - if (controller_ && !canceled_) { - canceled_ = true; - controller_->Cancel(MenuController::EXIT_ALL); - } -} - -MenuItemView* MenuItemView::AddMenuItemAt( - int index, - int item_id, - const base::string16& label, - const base::string16& sublabel, - const base::string16& minor_text, - const gfx::ImageSkia& icon, - Type type, - ui::MenuSeparatorType separator_style) { - DCHECK_NE(type, EMPTY); - DCHECK_LE(0, index); - if (!submenu_) - CreateSubmenu(); - DCHECK_GE(submenu_->child_count(), index); - if (type == SEPARATOR) { - submenu_->AddChildViewAt(new MenuSeparator(this, separator_style), index); - return NULL; - } - MenuItemView* item = new MenuItemView(this, item_id, type); - if (label.empty() && GetDelegate()) - item->SetTitle(GetDelegate()->GetLabel(item_id)); - else - item->SetTitle(label); - item->SetSubtitle(sublabel); - item->SetMinorText(minor_text); - if (!icon.isNull()) - item->SetIcon(icon); - if (type == SUBMENU) - item->CreateSubmenu(); - if (GetDelegate() && !GetDelegate()->IsCommandVisible(item_id)) - item->SetVisible(false); - submenu_->AddChildViewAt(item, index); - return item; -} - -void MenuItemView::RemoveMenuItemAt(int index) { - DCHECK(submenu_); - DCHECK_LE(0, index); - DCHECK_GT(submenu_->child_count(), index); - - View* item = submenu_->child_at(index); - DCHECK(item); - submenu_->RemoveChildView(item); - - // RemoveChildView() does not delete the item, which is a good thing - // in case a submenu is being displayed while items are being removed. - // Deletion will be done by ChildrenChanged() or at destruction. - removed_items_.push_back(item); -} - -MenuItemView* MenuItemView::AppendMenuItem(int item_id, - const base::string16& label, - Type type) { - return AppendMenuItemImpl(item_id, label, base::string16(), base::string16(), - gfx::ImageSkia(), type, ui::NORMAL_SEPARATOR); -} - -MenuItemView* MenuItemView::AppendSubMenu(int item_id, - const base::string16& label) { - return AppendMenuItemImpl(item_id, label, base::string16(), base::string16(), - gfx::ImageSkia(), SUBMENU, ui::NORMAL_SEPARATOR); -} - -MenuItemView* MenuItemView::AppendSubMenuWithIcon(int item_id, - const base::string16& label, - const gfx::ImageSkia& icon) { - return AppendMenuItemImpl(item_id, label, base::string16(), base::string16(), - icon, SUBMENU, ui::NORMAL_SEPARATOR); -} - -MenuItemView* MenuItemView::AppendMenuItemWithLabel( - int item_id, - const base::string16& label) { - return AppendMenuItem(item_id, label, NORMAL); -} - -MenuItemView* MenuItemView::AppendDelegateMenuItem(int item_id) { - return AppendMenuItem(item_id, base::string16(), NORMAL); -} - -void MenuItemView::AppendSeparator() { - AppendMenuItemImpl(0, base::string16(), base::string16(), base::string16(), - gfx::ImageSkia(), SEPARATOR, ui::NORMAL_SEPARATOR); -} - -MenuItemView* MenuItemView::AppendMenuItemWithIcon(int item_id, - const base::string16& label, - const gfx::ImageSkia& icon) { - return AppendMenuItemImpl(item_id, label, base::string16(), base::string16(), - icon, NORMAL, ui::NORMAL_SEPARATOR); -} - -MenuItemView* MenuItemView::AppendMenuItemImpl( - int item_id, - const base::string16& label, - const base::string16& sublabel, - const base::string16& minor_text, - const gfx::ImageSkia& icon, - Type type, - ui::MenuSeparatorType separator_style) { - const int index = submenu_ ? submenu_->child_count() : 0; - return AddMenuItemAt(index, item_id, label, sublabel, minor_text, icon, type, - separator_style); -} - -SubmenuView* MenuItemView::CreateSubmenu() { - if (!submenu_) - submenu_ = new SubmenuView(this); - return submenu_; -} - -bool MenuItemView::HasSubmenu() const { - return (submenu_ != NULL); -} - -SubmenuView* MenuItemView::GetSubmenu() const { - return submenu_; -} - -void MenuItemView::SetTitle(const base::string16& title) { - title_ = title; - invalidate_dimensions(); // Triggers preferred size recalculation. -} - -void MenuItemView::SetSubtitle(const base::string16& subtitle) { - subtitle_ = subtitle; - invalidate_dimensions(); // Triggers preferred size recalculation. -} - -void MenuItemView::SetMinorText(const base::string16& minor_text) { - minor_text_ = minor_text; - invalidate_dimensions(); // Triggers preferred size recalculation. -} - -void MenuItemView::SetSelected(bool selected) { - selected_ = selected; - SchedulePaint(); -} - -void MenuItemView::SetTooltip(const base::string16& tooltip, int item_id) { - MenuItemView* item = GetMenuItemByID(item_id); - DCHECK(item); - item->tooltip_ = tooltip; -} - -void MenuItemView::SetIcon(const gfx::ImageSkia& icon, int item_id) { - MenuItemView* item = GetMenuItemByID(item_id); - DCHECK(item); - item->SetIcon(icon); -} - -void MenuItemView::SetIcon(const gfx::ImageSkia& icon) { - if (icon.isNull()) { - SetIconView(NULL); - return; - } - - ImageView* icon_view = new ImageView(); - icon_view->SetImage(&icon); - SetIconView(icon_view); -} - -void MenuItemView::SetIconView(View* icon_view) { - if (icon_view_) { - RemoveChildView(icon_view_); - delete icon_view_; - icon_view_ = NULL; - } - if (icon_view) { - AddChildView(icon_view); - icon_view_ = icon_view; - } - Layout(); - SchedulePaint(); -} - -void MenuItemView::OnPaint(gfx::Canvas* canvas) { - PaintButton(canvas, PB_NORMAL); -} - -gfx::Size MenuItemView::GetPreferredSize() const { - const MenuItemDimensions& dimensions(GetDimensions()); - return gfx::Size(dimensions.standard_width + dimensions.children_width, - dimensions.height); -} - -int MenuItemView::GetHeightForWidth(int width) const { - // If this isn't a container, we can just use the preferred size's height. - if (!IsContainer()) - return GetPreferredSize().height(); - - int height = child_at(0)->GetHeightForWidth(width); - if (!icon_view_ && GetRootMenuItem()->has_icons()) - height = std::max(height, GetMenuConfig().check_height); - height += GetBottomMargin() + GetTopMargin(); - - return height; -} - -const MenuItemView::MenuItemDimensions& MenuItemView::GetDimensions() const { - if (!is_dimensions_valid()) - dimensions_ = CalculateDimensions(); - DCHECK(is_dimensions_valid()); - return dimensions_; -} - -MenuController* MenuItemView::GetMenuController() { - return GetRootMenuItem()->controller_; -} - -const MenuController* MenuItemView::GetMenuController() const { - return GetRootMenuItem()->controller_; -} - -MenuDelegate* MenuItemView::GetDelegate() { - return GetRootMenuItem()->delegate_; -} - -const MenuDelegate* MenuItemView::GetDelegate() const { - return GetRootMenuItem()->delegate_; -} - -MenuItemView* MenuItemView::GetRootMenuItem() { - return const_cast<MenuItemView*>( - static_cast<const MenuItemView*>(this)->GetRootMenuItem()); -} - -const MenuItemView* MenuItemView::GetRootMenuItem() const { - const MenuItemView* item = this; - for (const MenuItemView* parent = GetParentMenuItem(); parent; - parent = item->GetParentMenuItem()) - item = parent; - return item; -} - -base::char16 MenuItemView::GetMnemonic() { - if (!GetRootMenuItem()->has_mnemonics_) - return 0; - - size_t index = 0; - do { - index = title_.find('&', index); - if (index != base::string16::npos) { - if (index + 1 != title_.size() && title_[index + 1] != '&') { - base::char16 char_array[] = { title_[index + 1], 0 }; - // TODO(jshin): What about Turkish locale? See http://crbug.com/81719. - // If the mnemonic is capital I and the UI language is Turkish, - // lowercasing it results in 'small dotless i', which is different - // from a 'dotted i'. Similar issues may exist for az and lt locales. - return base::i18n::ToLower(char_array)[0]; - } - index++; - } - } while (index != base::string16::npos); - return 0; -} - -MenuItemView* MenuItemView::GetMenuItemByID(int id) { - if (GetCommand() == id) - return this; - if (!HasSubmenu()) - return NULL; - for (int i = 0; i < GetSubmenu()->child_count(); ++i) { - View* child = GetSubmenu()->child_at(i); - if (child->id() == MenuItemView::kMenuItemViewID) { - MenuItemView* result = static_cast<MenuItemView*>(child)-> - GetMenuItemByID(id); - if (result) - return result; - } - } - return NULL; -} - -void MenuItemView::ChildrenChanged() { - MenuController* controller = GetMenuController(); - if (controller) { - // Handles the case where we were empty and are no longer empty. - RemoveEmptyMenus(); - - // Handles the case where we were not empty, but now are. - AddEmptyMenus(); - - controller->MenuChildrenChanged(this); - - if (submenu_) { - // Force a paint and layout. This handles the case of the top - // level window's size remaining the same, resulting in no - // change to the submenu's size and no layout. - submenu_->Layout(); - submenu_->SchedulePaint(); - // Update the menu selection after layout. - controller->UpdateSubmenuSelection(submenu_); - } - } - - STLDeleteElements(&removed_items_); -} - -void MenuItemView::Layout() { - if (!has_children()) - return; - - if (IsContainer()) { - View* child = child_at(0); - gfx::Size size = child->GetPreferredSize(); - child->SetBounds(0, GetTopMargin(), size.width(), size.height()); - } else { - // Child views are laid out right aligned and given the full height. To - // right align start with the last view and progress to the first. - int x = width() - (use_right_margin_ ? item_right_margin_ : 0); - for (int i = child_count() - 1; i >= 0; --i) { - View* child = child_at(i); - if (icon_view_ && (icon_view_ == child)) - continue; - int width = child->GetPreferredSize().width(); - child->SetBounds(x - width, 0, width, height()); - x -= width - kChildXPadding; - } - // Position |icon_view|. - const MenuConfig& config = GetMenuConfig(); - if (icon_view_) { - icon_view_->SizeToPreferredSize(); - gfx::Size size = icon_view_->GetPreferredSize(); - int x = config.item_left_margin + left_icon_margin_ + - (icon_area_width_ - size.width()) / 2; - if (type_ == CHECKBOX || type_ == RADIO) - x = label_start_; - int y = - (height() + GetTopMargin() - GetBottomMargin() - size.height()) / 2; - icon_view_->SetPosition(gfx::Point(x, y)); - } - } -} - -void MenuItemView::SetMargins(int top_margin, int bottom_margin) { - top_margin_ = top_margin; - bottom_margin_ = bottom_margin; - - invalidate_dimensions(); -} - -const MenuConfig& MenuItemView::GetMenuConfig() const { - const MenuController* controller = GetMenuController(); - if (controller) - return controller->menu_config_; - return MenuConfig::instance(NULL); -} - -MenuItemView::MenuItemView(MenuItemView* parent, - int command, - MenuItemView::Type type) - : delegate_(NULL), - controller_(NULL), - canceled_(false), - parent_menu_item_(parent), - type_(type), - selected_(false), - command_(command), - submenu_(NULL), - has_mnemonics_(false), - show_mnemonics_(false), - has_icons_(false), - icon_view_(NULL), - top_margin_(-1), - bottom_margin_(-1), - left_icon_margin_(0), - right_icon_margin_(0), - requested_menu_position_(POSITION_BEST_FIT), - actual_menu_position_(requested_menu_position_), - use_right_margin_(true) { - Init(parent, command, type, NULL); -} - -MenuItemView::~MenuItemView() { - delete submenu_; - STLDeleteElements(&removed_items_); -} - -const char* MenuItemView::GetClassName() const { - return kViewClassName; -} - -// Calculates all sizes that we can from the OS. -// -// This is invoked prior to Running a menu. -void MenuItemView::UpdateMenuPartSizes() { - const MenuConfig& config = GetMenuConfig(); - - item_right_margin_ = config.label_to_arrow_padding + config.arrow_width + - config.arrow_to_edge_padding; - icon_area_width_ = config.check_width; - if (has_icons_) - icon_area_width_ = std::max(icon_area_width_, GetMaxIconViewWidth()); - - label_start_ = config.item_left_margin + icon_area_width_; - int padding = 0; - if (config.always_use_icon_to_label_padding) { - padding = config.icon_to_label_padding; - } else if (config.render_gutter) { - padding = config.item_left_margin; - } else { - padding = (has_icons_ || HasChecksOrRadioButtons()) ? - config.icon_to_label_padding : 0; - } - label_start_ += padding; - - if (config.render_gutter) - label_start_ += config.gutter_width + config.gutter_to_label; - - EmptyMenuMenuItem menu_item(this); - menu_item.set_controller(GetMenuController()); - pref_menu_height_ = menu_item.GetPreferredSize().height(); -} - -void MenuItemView::Init(MenuItemView* parent, - int command, - MenuItemView::Type type, - MenuDelegate* delegate) { - delegate_ = delegate; - controller_ = NULL; - canceled_ = false; - parent_menu_item_ = parent; - type_ = type; - selected_ = false; - command_ = command; - submenu_ = NULL; - show_mnemonics_ = false; - // Assign our ID, this allows SubmenuItemView to find MenuItemViews. - set_id(kMenuItemViewID); - has_icons_ = false; - - // Don't request enabled status from the root menu item as it is just - // a container for real items. EMPTY items will be disabled. - MenuDelegate* root_delegate = GetDelegate(); - if (parent && type != EMPTY && root_delegate) - SetEnabled(root_delegate->IsCommandEnabled(command)); -} - -void MenuItemView::PrepareForRun(bool is_first_menu, - bool has_mnemonics, - bool show_mnemonics) { - // Currently we only support showing the root. - DCHECK(!parent_menu_item_); - - // Force us to have a submenu. - CreateSubmenu(); - actual_menu_position_ = requested_menu_position_; - canceled_ = false; - - has_mnemonics_ = has_mnemonics; - show_mnemonics_ = has_mnemonics && show_mnemonics; - - AddEmptyMenus(); - - if (is_first_menu) { - // Only update the menu size if there are no menus showing, otherwise - // things may shift around. - UpdateMenuPartSizes(); - } -} - -int MenuItemView::GetDrawStringFlags() { - int flags = 0; - if (base::i18n::IsRTL()) - flags |= gfx::Canvas::TEXT_ALIGN_RIGHT; - else - flags |= gfx::Canvas::TEXT_ALIGN_LEFT; - - if (GetRootMenuItem()->has_mnemonics_) { - if (GetMenuConfig().show_mnemonics || GetRootMenuItem()->show_mnemonics_) { - flags |= gfx::Canvas::SHOW_PREFIX; - } else { - flags |= gfx::Canvas::HIDE_PREFIX; - } - } - return flags; -} - -const gfx::FontList& MenuItemView::GetFontList() const { - const MenuDelegate* delegate = GetDelegate(); - if (delegate) { - const gfx::FontList* font_list = delegate->GetLabelFontList(GetCommand()); - if (font_list) - return *font_list; - } - return GetMenuConfig().font_list; -} - -void MenuItemView::AddEmptyMenus() { - DCHECK(HasSubmenu()); - if (!submenu_->has_children()) { - submenu_->AddChildViewAt(new EmptyMenuMenuItem(this), 0); - } else { - for (int i = 0, item_count = submenu_->GetMenuItemCount(); i < item_count; - ++i) { - MenuItemView* child = submenu_->GetMenuItemAt(i); - if (child->HasSubmenu()) - child->AddEmptyMenus(); - } - } -} - -void MenuItemView::RemoveEmptyMenus() { - DCHECK(HasSubmenu()); - // Iterate backwards as we may end up removing views, which alters the child - // view count. - for (int i = submenu_->child_count() - 1; i >= 0; --i) { - View* child = submenu_->child_at(i); - if (child->id() == MenuItemView::kMenuItemViewID) { - MenuItemView* menu_item = static_cast<MenuItemView*>(child); - if (menu_item->HasSubmenu()) - menu_item->RemoveEmptyMenus(); - } else if (child->id() == EmptyMenuMenuItem::kEmptyMenuItemViewID) { - submenu_->RemoveChildView(child); - delete child; - child = NULL; - } - } -} - -void MenuItemView::AdjustBoundsForRTLUI(gfx::Rect* rect) const { - rect->set_x(GetMirroredXForRect(*rect)); -} - -void MenuItemView::PaintButton(gfx::Canvas* canvas, PaintButtonMode mode) { - const MenuConfig& config = GetMenuConfig(); - bool render_selection = - (mode == PB_NORMAL && IsSelected() && - parent_menu_item_->GetSubmenu()->GetShowSelection(this) && - (NonIconChildViewsCount() == 0)); - - MenuDelegate *delegate = GetDelegate(); - // Render the background. As MenuScrollViewContainer draws the background, we - // only need the background when we want it to look different, as when we're - // selected. - ui::NativeTheme* native_theme = GetNativeTheme(); - SkColor override_color; - if (delegate && delegate->GetBackgroundColor(GetCommand(), - render_selection, - &override_color)) { - canvas->DrawColor(override_color); - } else if (render_selection) { - gfx::Rect item_bounds(0, 0, width(), height()); - AdjustBoundsForRTLUI(&item_bounds); - - native_theme->Paint(canvas->sk_canvas(), - ui::NativeTheme::kMenuItemBackground, - ui::NativeTheme::kHovered, - item_bounds, - ui::NativeTheme::ExtraParams()); - } - - const int icon_x = config.item_left_margin + left_icon_margin_; - const int top_margin = GetTopMargin(); - const int bottom_margin = GetBottomMargin(); - const int available_height = height() - top_margin - bottom_margin; - - // Render the check. - if (type_ == CHECKBOX && delegate->IsItemChecked(GetCommand())) { - gfx::ImageSkia check = GetMenuCheckImage(render_selection); - // Don't use config.check_width here as it's padded - // to force more padding (AURA). - gfx::Rect check_bounds(icon_x, - top_margin + (available_height - check.height()) / 2, - check.width(), - check.height()); - AdjustBoundsForRTLUI(&check_bounds); - canvas->DrawImageInt(check, check_bounds.x(), check_bounds.y()); - } else if (type_ == RADIO) { - gfx::ImageSkia image = - GetRadioButtonImage(delegate->IsItemChecked(GetCommand())); - gfx::Rect radio_bounds(icon_x, - top_margin + (available_height - image.height()) / 2, - image.width(), - image.height()); - AdjustBoundsForRTLUI(&radio_bounds); - canvas->DrawImageInt(image, radio_bounds.x(), radio_bounds.y()); - } - - // Render the foreground. - ui::NativeTheme::ColorId color_id; - if (enabled()) { - color_id = render_selection ? - ui::NativeTheme::kColorId_SelectedMenuItemForegroundColor: - ui::NativeTheme::kColorId_EnabledMenuItemForegroundColor; - } else { - bool emphasized = delegate && - delegate->GetShouldUseDisabledEmphasizedForegroundColor( - GetCommand()); - color_id = emphasized ? - ui::NativeTheme::kColorId_DisabledEmphasizedMenuItemForegroundColor : - ui::NativeTheme::kColorId_DisabledMenuItemForegroundColor; - } - SkColor fg_color = native_theme->GetSystemColor(color_id); - SkColor override_foreground_color; - if (delegate && delegate->GetForegroundColor(GetCommand(), - render_selection, - &override_foreground_color)) - fg_color = override_foreground_color; - - const gfx::FontList& font_list = GetFontList(); - int accel_width = parent_menu_item_->GetSubmenu()->max_minor_text_width(); - int label_start = GetLabelStartForThisItem(); - - int width = this->width() - label_start - accel_width - - (!delegate || - delegate->ShouldReserveSpaceForSubmenuIndicator() ? - item_right_margin_ : config.arrow_to_edge_padding); - gfx::Rect text_bounds(label_start, top_margin, width, - subtitle_.empty() ? available_height - : available_height / 2); - text_bounds.set_x(GetMirroredXForRect(text_bounds)); - int flags = GetDrawStringFlags(); - if (mode == PB_FOR_DRAG) - flags |= gfx::Canvas::NO_SUBPIXEL_RENDERING; - canvas->DrawStringRectWithFlags(title(), font_list, fg_color, text_bounds, - flags); - if (!subtitle_.empty()) { - canvas->DrawStringRectWithFlags( - subtitle_, - font_list, - GetNativeTheme()->GetSystemColor( - ui::NativeTheme::kColorId_ButtonDisabledColor), - text_bounds + gfx::Vector2d(0, font_list.GetHeight()), - flags); - } - - PaintMinorText(canvas, render_selection); - - // Render the submenu indicator (arrow). - if (HasSubmenu()) { - gfx::ImageSkia arrow = GetSubmenuArrowImage(render_selection); - gfx::Rect arrow_bounds(this->width() - config.arrow_width - - config.arrow_to_edge_padding, - top_margin + (available_height - arrow.height()) / 2, - config.arrow_width, - arrow.height()); - AdjustBoundsForRTLUI(&arrow_bounds); - canvas->DrawImageInt(arrow, arrow_bounds.x(), arrow_bounds.y()); - } -} - -void MenuItemView::PaintMinorText(gfx::Canvas* canvas, - bool render_selection) { - base::string16 minor_text = GetMinorText(); - if (minor_text.empty()) - return; - - int available_height = height() - GetTopMargin() - GetBottomMargin(); - int max_accel_width = - parent_menu_item_->GetSubmenu()->max_minor_text_width(); - const MenuConfig& config = GetMenuConfig(); - int accel_right_margin = config.align_arrow_and_shortcut ? - config.arrow_to_edge_padding : item_right_margin_; - gfx::Rect accel_bounds(width() - accel_right_margin - max_accel_width, - GetTopMargin(), max_accel_width, available_height); - accel_bounds.set_x(GetMirroredXForRect(accel_bounds)); - int flags = GetDrawStringFlags(); - flags &= ~(gfx::Canvas::TEXT_ALIGN_RIGHT | gfx::Canvas::TEXT_ALIGN_LEFT); - if (base::i18n::IsRTL()) - flags |= gfx::Canvas::TEXT_ALIGN_LEFT; - else - flags |= gfx::Canvas::TEXT_ALIGN_RIGHT; - canvas->DrawStringRectWithFlags( - minor_text, - GetFontList(), - GetNativeTheme()->GetSystemColor(render_selection ? - ui::NativeTheme::kColorId_SelectedMenuItemForegroundColor : - ui::NativeTheme::kColorId_ButtonDisabledColor), - accel_bounds, - flags); -} - -void MenuItemView::DestroyAllMenuHosts() { - if (!HasSubmenu()) - return; - - submenu_->Close(); - for (int i = 0, item_count = submenu_->GetMenuItemCount(); i < item_count; - ++i) { - submenu_->GetMenuItemAt(i)->DestroyAllMenuHosts(); - } -} - -int MenuItemView::GetTopMargin() const { - if (top_margin_ >= 0) - return top_margin_; - - const MenuItemView* root = GetRootMenuItem(); - return root && root->has_icons_ - ? GetMenuConfig().item_top_margin : - GetMenuConfig().item_no_icon_top_margin; -} - -int MenuItemView::GetBottomMargin() const { - if (bottom_margin_ >= 0) - return bottom_margin_; - - const MenuItemView* root = GetRootMenuItem(); - return root && root->has_icons_ - ? GetMenuConfig().item_bottom_margin : - GetMenuConfig().item_no_icon_bottom_margin; -} - -gfx::Size MenuItemView::GetChildPreferredSize() const { - if (!has_children()) - return gfx::Size(); - - if (IsContainer()) - return child_at(0)->GetPreferredSize(); - - int width = 0; - for (int i = 0; i < child_count(); ++i) { - const View* child = child_at(i); - if (icon_view_ && (icon_view_ == child)) - continue; - if (i) - width += kChildXPadding; - width += child->GetPreferredSize().width(); - } - int height = 0; - if (icon_view_) - height = icon_view_->GetPreferredSize().height(); - - // If there is no icon view it returns a height of 0 to indicate that - // we should use the title height instead. - return gfx::Size(width, height); -} - -MenuItemView::MenuItemDimensions MenuItemView::CalculateDimensions() const { - gfx::Size child_size = GetChildPreferredSize(); - - MenuItemDimensions dimensions; - // Get the container height. - dimensions.children_width = child_size.width(); - dimensions.height = child_size.height(); - // Adjust item content height if menu has both items with and without icons. - // This way all menu items will have the same height. - if (!icon_view_ && GetRootMenuItem()->has_icons()) { - dimensions.height = std::max(dimensions.height, - GetMenuConfig().check_height); - } - dimensions.height += GetBottomMargin() + GetTopMargin(); - - // In case of a container, only the container size needs to be filled. - if (IsContainer()) - return dimensions; - - // Determine the length of the label text. - const gfx::FontList& font_list = GetFontList(); - - // Get Icon margin overrides for this particular item. - const MenuDelegate* delegate = GetDelegate(); - if (delegate) { - delegate->GetHorizontalIconMargins(command_, - icon_area_width_, - &left_icon_margin_, - &right_icon_margin_); - } else { - left_icon_margin_ = 0; - right_icon_margin_ = 0; - } - int label_start = GetLabelStartForThisItem(); - - int string_width = gfx::GetStringWidth(title_, font_list); - if (!subtitle_.empty()) { - string_width = std::max(string_width, - gfx::GetStringWidth(subtitle_, font_list)); - } - - dimensions.standard_width = string_width + label_start + - item_right_margin_; - // Determine the length of the right-side text. - base::string16 minor_text = GetMinorText(); - dimensions.minor_text_width = - minor_text.empty() ? 0 : gfx::GetStringWidth(minor_text, font_list); - - // Determine the height to use. - dimensions.height = - std::max(dimensions.height, - (subtitle_.empty() ? 0 : font_list.GetHeight()) + - font_list.GetHeight() + GetBottomMargin() + GetTopMargin()); - dimensions.height = std::max(dimensions.height, - GetMenuConfig().item_min_height); - return dimensions; -} - -int MenuItemView::GetLabelStartForThisItem() const { - int label_start = label_start_ + left_icon_margin_ + right_icon_margin_; - if ((type_ == CHECKBOX || type_ == RADIO) && icon_view_) { - label_start += icon_view_->size().width() + - GetMenuConfig().icon_to_label_padding; - } - return label_start; -} - -base::string16 MenuItemView::GetMinorText() const { - if (id() == kEmptyMenuItemViewID) { - // Don't query the delegate for menus that represent no children. - return base::string16(); - } - - ui::Accelerator accelerator; - if (GetMenuConfig().show_accelerators && GetDelegate() && GetCommand() && - GetDelegate()->GetAccelerator(GetCommand(), &accelerator)) { - return accelerator.GetShortcutText(); - } - - return minor_text_; -} - -bool MenuItemView::IsContainer() const { - // Let the first child take over |this| when we only have one child and no - // title. - return (NonIconChildViewsCount() == 1) && title_.empty(); -} - -int MenuItemView::NonIconChildViewsCount() const { - // Note that what child_count() returns is the number of children, - // not the number of menu items. - return child_count() - (icon_view_ ? 1 : 0); -} - -int MenuItemView::GetMaxIconViewWidth() const { - int width = 0; - for (int i = 0; i < submenu_->GetMenuItemCount(); ++i) { - MenuItemView* menu_item = submenu_->GetMenuItemAt(i); - int temp_width = 0; - if (menu_item->GetType() == CHECKBOX || - menu_item->GetType() == RADIO) { - // If this item has a radio or checkbox, the icon will not affect - // alignment of other items. - continue; - } else if (menu_item->HasSubmenu()) { - temp_width = menu_item->GetMaxIconViewWidth(); - } else if (menu_item->icon_view()) { - temp_width = menu_item->icon_view()->GetPreferredSize().width(); - } - width = std::max(width, temp_width); - } - return width; -} - -bool MenuItemView::HasChecksOrRadioButtons() const { - for (int i = 0; i < submenu_->GetMenuItemCount(); ++i) { - MenuItemView* menu_item = submenu_->GetMenuItemAt(i); - if (menu_item->HasSubmenu()) { - if (menu_item->HasChecksOrRadioButtons()) - return true; - } else { - const Type& type = menu_item->GetType(); - if (type == CHECKBOX || type == RADIO) - return true; - } - } - return false; -} - -} // namespace views
diff --git a/ui/views/controls/menu/menu_item_view.h b/ui/views/controls/menu/menu_item_view.h deleted file mode 100644 index cc4150e..0000000 --- a/ui/views/controls/menu/menu_item_view.h +++ /dev/null
@@ -1,525 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_MENU_MENU_ITEM_VIEW_H_ -#define UI_VIEWS_CONTROLS_MENU_MENU_ITEM_VIEW_H_ - -#include <string> -#include <vector> - -#include "base/compiler_specific.h" -#include "base/logging.h" -#include "base/strings/string16.h" -#include "build/build_config.h" -#include "ui/base/models/menu_separator_types.h" -#include "ui/gfx/image/image_skia.h" -#include "ui/views/controls/menu/menu_config.h" -#include "ui/views/controls/menu/menu_types.h" -#include "ui/views/view.h" - -#if defined(OS_WIN) -#include <windows.h> - -#include "ui/native_theme/native_theme.h" -#endif - -namespace gfx { -class FontList; -} - -namespace views { - -namespace internal { -class MenuRunnerImpl; -} - -class MenuController; -class MenuDelegate; -class SubmenuView; - -// MenuItemView -------------------------------------------------------------- - -// MenuItemView represents a single menu item with a label and optional icon. -// Each MenuItemView may also contain a submenu, which in turn may contain -// any number of child MenuItemViews. -// -// To use a menu create an initial MenuItemView using the constructor that -// takes a MenuDelegate, then create any number of child menu items by way -// of the various AddXXX methods. -// -// MenuItemView is itself a View, which means you can add Views to each -// MenuItemView. This is normally NOT want you want, rather add other child -// Views to the submenu of the MenuItemView. Any child views of the MenuItemView -// that are focusable can be navigated to by way of the up/down arrow and can be -// activated by way of space/return keys. Activating a focusable child results -// in |AcceleratorPressed| being invoked. Note, that as menus try not to steal -// focus from the hosting window child views do not actually get focus. Instead -// |SetHotTracked| is used as the user navigates around. -// -// To show the menu use MenuRunner. See MenuRunner for details on how to run -// (show) the menu as well as for details on the life time of the menu. - -class VIEWS_EXPORT MenuItemView : public View { - public: - friend class MenuController; - - // The menu item view's class name. - static const char kViewClassName[]; - - // ID used to identify menu items. - static const int kMenuItemViewID; - - // ID used to identify empty menu items. - static const int kEmptyMenuItemViewID; - - // Different types of menu items. EMPTY is a special type for empty - // menus that is only used internally. - enum Type { - NORMAL, - SUBMENU, - CHECKBOX, - RADIO, - SEPARATOR, - EMPTY - }; - - // Where the menu should be drawn, above or below the bounds (when - // the bounds is non-empty). POSITION_BEST_FIT (default) positions - // the menu below the bounds unless the menu does not fit on the - // screen and the re is more space above. - enum MenuPosition { - POSITION_BEST_FIT, - POSITION_ABOVE_BOUNDS, - POSITION_BELOW_BOUNDS - }; - - // The data structure which is used for the menu size - struct MenuItemDimensions { - MenuItemDimensions() - : standard_width(0), - children_width(0), - minor_text_width(0), - height(0) {} - - // Width of everything except the accelerator and children views. - int standard_width; - // The width of all contained views of the item. - int children_width; - // The amount of space needed to accommodate the subtext. - int minor_text_width; - // The height of the menu item. - int height; - }; - - // Constructor for use with the top level menu item. This menu is never - // shown to the user, rather its use as the parent for all menu items. - explicit MenuItemView(MenuDelegate* delegate); - - // Overridden from View: - virtual bool GetTooltipText(const gfx::Point& p, - base::string16* tooltip) const override; - virtual void GetAccessibleState(ui::AXViewState* state) override; - - // Returns the preferred height of menu items. This is only valid when the - // menu is about to be shown. - static int pref_menu_height() { return pref_menu_height_; } - - // X-coordinate of where the label starts. - static int label_start() { return label_start_; } - - // Returns if a given |anchor| is a bubble or not. - static bool IsBubble(MenuAnchorPosition anchor); - - // Returns the accessible name to be used with screen readers. Mnemonics are - // removed and the menu item accelerator text is appended. - static base::string16 GetAccessibleNameForMenuItem( - const base::string16& item_text, const base::string16& accelerator_text); - - // Hides and cancels the menu. This does nothing if the menu is not open. - void Cancel(); - - // Add an item to the menu at a specified index. ChildrenChanged() should - // called after adding menu items if the menu may be active. - MenuItemView* AddMenuItemAt(int index, - int item_id, - const base::string16& label, - const base::string16& sublabel, - const base::string16& minor_text, - const gfx::ImageSkia& icon, - Type type, - ui::MenuSeparatorType separator_style); - - // Remove an item from the menu at a specified index. The removed MenuItemView - // is deleted when ChildrenChanged() is invoked. - void RemoveMenuItemAt(int index); - - // Appends an item to this menu. - // item_id The id of the item, used to identify it in delegate callbacks - // or (if delegate is NULL) to identify the command associated - // with this item with the controller specified in the ctor. Note - // that this value should not be 0 as this has a special meaning - // ("NULL command, no item selected") - // label The text label shown. - // type The type of item. - MenuItemView* AppendMenuItem(int item_id, - const base::string16& label, - Type type); - - // Append a submenu to this menu. - // The returned pointer is owned by this menu. - MenuItemView* AppendSubMenu(int item_id, - const base::string16& label); - - // Append a submenu with an icon to this menu. - // The returned pointer is owned by this menu. - MenuItemView* AppendSubMenuWithIcon(int item_id, - const base::string16& label, - const gfx::ImageSkia& icon); - - // This is a convenience for standard text label menu items where the label - // is provided with this call. - MenuItemView* AppendMenuItemWithLabel(int item_id, - const base::string16& label); - - // This is a convenience for text label menu items where the label is - // provided by the delegate. - MenuItemView* AppendDelegateMenuItem(int item_id); - - // Adds a separator to this menu - void AppendSeparator(); - - // Appends a menu item with an icon. This is for the menu item which - // needs an icon. Calling this function forces the Menu class to draw - // the menu, instead of relying on Windows. - MenuItemView* AppendMenuItemWithIcon(int item_id, - const base::string16& label, - const gfx::ImageSkia& icon); - - // All the AppendXXX methods funnel into this. - MenuItemView* AppendMenuItemImpl(int item_id, - const base::string16& label, - const base::string16& sublabel, - const base::string16& minor_text, - const gfx::ImageSkia& icon, - Type type, - ui::MenuSeparatorType separator_style); - - // Returns the view that contains child menu items. If the submenu has - // not been creates, this creates it. - virtual SubmenuView* CreateSubmenu(); - - // Returns true if this menu item has a submenu. - virtual bool HasSubmenu() const; - - // Returns the view containing child menu items. - virtual SubmenuView* GetSubmenu() const; - - // Returns the parent menu item. - MenuItemView* GetParentMenuItem() { return parent_menu_item_; } - const MenuItemView* GetParentMenuItem() const { return parent_menu_item_; } - - // Sets/Gets the title. - void SetTitle(const base::string16& title); - const base::string16& title() const { return title_; } - - // Sets the subtitle. - void SetSubtitle(const base::string16& subtitle); - - // Sets the minor text. - void SetMinorText(const base::string16& minor_text); - - // Returns the type of this menu. - const Type& GetType() const { return type_; } - - // Sets whether this item is selected. This is invoked as the user moves - // the mouse around the menu while open. - void SetSelected(bool selected); - - // Returns true if the item is selected. - bool IsSelected() const { return selected_; } - - // Sets the |tooltip| for a menu item view with |item_id| identifier. - void SetTooltip(const base::string16& tooltip, int item_id); - - // Sets the icon for the descendant identified by item_id. - void SetIcon(const gfx::ImageSkia& icon, int item_id); - - // Sets the icon of this menu item. - void SetIcon(const gfx::ImageSkia& icon); - - // Sets the view used to render the icon. This clobbers any icon set via - // SetIcon(). MenuItemView takes ownership of |icon_view|. - void SetIconView(View* icon_view); - View* icon_view() { return icon_view_; } - - // Sets the command id of this menu item. - void SetCommand(int command) { command_ = command; } - - // Returns the command id of this item. - int GetCommand() const { return command_; } - - // Paints the menu item. - virtual void OnPaint(gfx::Canvas* canvas) override; - - // Returns the preferred size of this item. - virtual gfx::Size GetPreferredSize() const override; - - // Gets the preferred height for the given |width|. This is only different - // from GetPreferredSize().width() if the item has a child view with flexible - // dimensions. - virtual int GetHeightForWidth(int width) const override; - - // Return the preferred dimensions of the item in pixel. - const MenuItemDimensions& GetDimensions() const; - - // Returns the object responsible for controlling showing the menu. - MenuController* GetMenuController(); - const MenuController* GetMenuController() const; - - // Returns the delegate. This returns the delegate of the root menu item. - MenuDelegate* GetDelegate(); - const MenuDelegate* GetDelegate() const; - void set_delegate(MenuDelegate* delegate) { delegate_ = delegate; } - - // Returns the root parent, or this if this has no parent. - MenuItemView* GetRootMenuItem(); - const MenuItemView* GetRootMenuItem() const; - - // Returns the mnemonic for this MenuItemView, or 0 if this MenuItemView - // doesn't have a mnemonic. - base::char16 GetMnemonic(); - - // Do we have icons? This only has effect on the top menu. Turning this on - // makes the menus slightly wider and taller. - void set_has_icons(bool has_icons) { - has_icons_ = has_icons; - } - bool has_icons() const { return has_icons_; } - - // Returns the descendant with the specified command. - MenuItemView* GetMenuItemByID(int id); - - // Invoke if you remove/add children to the menu while it's showing. This - // recalculates the bounds. - void ChildrenChanged(); - - // Sizes any child views. - virtual void Layout() override; - - // Returns true if the menu has mnemonics. This only useful on the root menu - // item. - bool has_mnemonics() const { return has_mnemonics_; } - - // Set top and bottom margins in pixels. If no margin is set or a - // negative margin is specified then MenuConfig values are used. - void SetMargins(int top_margin, int bottom_margin); - - // Suppress the right margin if this is set to false. - void set_use_right_margin(bool use_right_margin) { - use_right_margin_ = use_right_margin; - } - - // Returns a reference to MenuConfig to be used with this menu. - const MenuConfig& GetMenuConfig() const; - - protected: - // Creates a MenuItemView. This is used by the various AddXXX methods. - MenuItemView(MenuItemView* parent, int command, Type type); - - // MenuRunner owns MenuItemView and should be the only one deleting it. - virtual ~MenuItemView(); - - virtual void ChildPreferredSizeChanged(View* child) override; - - virtual const char* GetClassName() const override; - - // Returns the preferred size (and padding) of any children. - virtual gfx::Size GetChildPreferredSize() const; - - // Returns the various margins. - int GetTopMargin() const; - int GetBottomMargin() const; - - private: - friend class internal::MenuRunnerImpl; // For access to ~MenuItemView. - - enum PaintButtonMode { PB_NORMAL, PB_FOR_DRAG }; - - // Calculates all sizes that we can from the OS. - // - // This is invoked prior to Running a menu. - void UpdateMenuPartSizes(); - - // Called by the two constructors to initialize this menu item. - void Init(MenuItemView* parent, - int command, - MenuItemView::Type type, - MenuDelegate* delegate); - - // The RunXXX methods call into this to set up the necessary state before - // running. |is_first_menu| is true if no menus are currently showing. - void PrepareForRun(bool is_first_menu, - bool has_mnemonics, - bool show_mnemonics); - - // Returns the flags passed to DrawStringRect. - int GetDrawStringFlags(); - - // Returns the font list to use for menu text. - const gfx::FontList& GetFontList() const; - - // If this menu item has no children a child is added showing it has no - // children. Otherwise AddEmtpyMenus is recursively invoked on child menu - // items that have children. - void AddEmptyMenus(); - - // Undoes the work of AddEmptyMenus. - void RemoveEmptyMenus(); - - // Given bounds within our View, this helper routine mirrors the bounds if - // necessary. - void AdjustBoundsForRTLUI(gfx::Rect* rect) const; - - // Actual paint implementation. If mode is PB_FOR_DRAG, portions of the menu - // are not rendered. - void PaintButton(gfx::Canvas* canvas, PaintButtonMode mode); - - // Paints the right-side text. - void PaintMinorText(gfx::Canvas* canvas, bool render_selection); - - // Destroys the window used to display this menu and recursively destroys - // the windows used to display all descendants. - void DestroyAllMenuHosts(); - - // Returns the text that should be displayed on the end (right) of the menu - // item. This will be the accelerator (if one exists), otherwise |subtitle_|. - base::string16 GetMinorText() const; - - // Calculates and returns the MenuItemDimensions. - MenuItemDimensions CalculateDimensions() const; - - // Get the horizontal position at which to draw the menu item's label. - int GetLabelStartForThisItem() const; - - // Used by MenuController to cache the menu position in use by the - // active menu. - MenuPosition actual_menu_position() const { return actual_menu_position_; } - void set_actual_menu_position(MenuPosition actual_menu_position) { - actual_menu_position_ = actual_menu_position; - } - - void set_controller(MenuController* controller) { controller_ = controller; } - - // Returns true if this MenuItemView contains a single child - // that is responsible for rendering the content. - bool IsContainer() const; - - // Returns number of child views excluding icon_view. - int NonIconChildViewsCount() const; - - // Returns the max icon width; recurses over submenus. - int GetMaxIconViewWidth() const; - - // Returns true if the menu has items with a checkbox or a radio button. - bool HasChecksOrRadioButtons() const; - - void invalidate_dimensions() { dimensions_.height = 0; } - bool is_dimensions_valid() const { return dimensions_.height > 0; } - - // The delegate. This is only valid for the root menu item. You shouldn't - // use this directly, instead use GetDelegate() which walks the tree as - // as necessary. - MenuDelegate* delegate_; - - // The controller for the run operation, or NULL if the menu isn't showing. - MenuController* controller_; - - // Used to detect when Cancel was invoked. - bool canceled_; - - // Our parent. - MenuItemView* parent_menu_item_; - - // Type of menu. NOTE: MenuItemView doesn't itself represent SEPARATOR, - // that is handled by an entirely different view class. - Type type_; - - // Whether we're selected. - bool selected_; - - // Command id. - int command_; - - // Submenu, created via CreateSubmenu. - SubmenuView* submenu_; - - // Title. - base::string16 title_; - - // Subtitle/sublabel. - base::string16 subtitle_; - - // Minor text. - base::string16 minor_text_; - - // Does the title have a mnemonic? Only useful on the root menu item. - bool has_mnemonics_; - - // Should we show the mnemonic? Mnemonics are shown if this is true or - // MenuConfig says mnemonics should be shown. Only used on the root menu item. - bool show_mnemonics_; - - // Set if menu has icons or icon_views (applies to root menu item only). - bool has_icons_; - - // Pointer to a view with a menu icon. - View* icon_view_; - - // The tooltip to show on hover for this menu item. - base::string16 tooltip_; - - // Width of a menu icon area. - static int icon_area_width_; - - // X-coordinate of where the label starts. - static int label_start_; - - // Margins between the right of the item and the label. - static int item_right_margin_; - - // Preferred height of menu items. Reset every time a menu is run. - static int pref_menu_height_; - - // Cached dimensions. This is cached as text sizing calculations are quite - // costly. - mutable MenuItemDimensions dimensions_; - - // Removed items to be deleted in ChildrenChanged(). - std::vector<View*> removed_items_; - - // Margins in pixels. - int top_margin_; - int bottom_margin_; - - // Horizontal icon margins in pixels, which can differ between MenuItems. - // These values will be set in the layout process. - mutable int left_icon_margin_; - mutable int right_icon_margin_; - - // |menu_position_| is the requested position with respect to the bounds. - // |actual_menu_position_| is used by the controller to cache the - // position of the menu being shown. - MenuPosition requested_menu_position_; - MenuPosition actual_menu_position_; - - // If set to false, the right margin will be removed for menu lines - // containing other elements. - bool use_right_margin_; - - DISALLOW_COPY_AND_ASSIGN(MenuItemView); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_MENU_MENU_ITEM_VIEW_H_
diff --git a/ui/views/controls/menu/menu_item_view_unittest.cc b/ui/views/controls/menu/menu_item_view_unittest.cc deleted file mode 100644 index 961d90c..0000000 --- a/ui/views/controls/menu/menu_item_view_unittest.cc +++ /dev/null
@@ -1,76 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/menu/menu_item_view.h" - -#include "base/strings/string16.h" -#include "base/strings/utf_string_conversions.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/views/controls/menu/submenu_view.h" -#include "ui/views/view.h" - -namespace { - -// A simple View class that will match its height to the available width. -class SquareView : public views::View { - public: - SquareView() {} - virtual ~SquareView() {} - - private: - virtual gfx::Size GetPreferredSize() const override { - return gfx::Size(1, 1); - } - virtual int GetHeightForWidth(int width) const override { - return width; - } -}; - -// A MenuItemView implementation with a public destructor (so we can clean up -// in tests). -class TestMenuItemView : public views::MenuItemView { - public: - TestMenuItemView() : views::MenuItemView(NULL) {} - virtual ~TestMenuItemView() {} -}; - -} // namespace - -TEST(MenuItemViewUnitTest, TestMenuItemViewWithFlexibleWidthChild) { - TestMenuItemView root_menu; - root_menu.set_owned_by_client(); - - // Append a normal MenuItemView. - views::MenuItemView* label_view = - root_menu.AppendMenuItemWithLabel(1, base::ASCIIToUTF16("item 1")); - - // Append a second MenuItemView that has a child SquareView. - views::MenuItemView* flexible_view = - root_menu.AppendMenuItemWithLabel(2, base::string16()); - flexible_view->AddChildView(new SquareView()); - // Set margins to 0 so that we know width should match height. - flexible_view->SetMargins(0, 0); - - views::SubmenuView* submenu = root_menu.GetSubmenu(); - - // The first item should be the label view. - ASSERT_EQ(label_view, submenu->GetMenuItemAt(0)); - gfx::Size label_size = label_view->GetPreferredSize(); - - // The second item should be the flexible view. - ASSERT_EQ(flexible_view, submenu->GetMenuItemAt(1)); - gfx::Size flexible_size = flexible_view->GetPreferredSize(); - - // The flexible view's "preferred size" should be 1x1... - EXPECT_EQ(flexible_size, gfx::Size(1, 1)); - - // ...but it should use whatever space is available to make a square. - int flex_height = flexible_view->GetHeightForWidth(label_size.width()); - EXPECT_EQ(label_size.width(), flex_height); - - // The submenu should be tall enough to allow for both menu items at the given - // width. - EXPECT_EQ(label_size.height() + flex_height, - submenu->GetPreferredSize().height()); -}
diff --git a/ui/views/controls/menu/menu_listener.cc b/ui/views/controls/menu/menu_listener.cc deleted file mode 100644 index 4b86833..0000000 --- a/ui/views/controls/menu/menu_listener.cc +++ /dev/null
@@ -1,15 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/menu/menu_listener.h" - -namespace views { - -MenuListener::MenuListener() { -} - -MenuListener::~MenuListener() { -} - -} // namespace views
diff --git a/ui/views/controls/menu/menu_listener.h b/ui/views/controls/menu/menu_listener.h deleted file mode 100644 index 19cfb68..0000000 --- a/ui/views/controls/menu/menu_listener.h +++ /dev/null
@@ -1,26 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_MENU_MENU_LISTENER_H_ -#define UI_VIEWS_CONTROLS_MENU_MENU_LISTENER_H_ - -#include "ui/views/views_export.h" - -namespace views { - -// An interface for clients that want a notification when a menu is opened. -class VIEWS_EXPORT MenuListener { - public: - MenuListener(); - - // This will be called after the menu has actually opened. - virtual void OnMenuOpened() = 0; - - protected: - virtual ~MenuListener(); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_MENU_MENU_LISTENER_H_
diff --git a/ui/views/controls/menu/menu_message_loop.h b/ui/views/controls/menu/menu_message_loop.h deleted file mode 100644 index a435d85..0000000 --- a/ui/views/controls/menu/menu_message_loop.h +++ /dev/null
@@ -1,57 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_MENU_MENU_MESSAGE_LOOP_H_ -#define UI_VIEWS_CONTROLS_MENU_MENU_MESSAGE_LOOP_H_ - -#include "ui/gfx/native_widget_types.h" - -namespace gfx { -class Point; -} - -namespace ui { -class LocatedEvent; -} - -namespace views { - -class MenuController; -class Widget; - -// Interface used by MenuController to run a nested message loop while -// showing a menu, allowing for platform specific implementations. -class MenuMessageLoop { - public: - virtual ~MenuMessageLoop() {} - - // Create a platform specific instance. - static MenuMessageLoop* Create(); - - // Runs the platform specific bits of the message loop. If |nested_menu| is - // true we're being asked to run a menu from within a menu (eg a context - // menu). - virtual void Run(MenuController*, Widget* owner, bool nested_menu) = 0; - - // Returns true if it is a good time to call QuitNow(). - // Returns false otherwise, for example if a drag and drop is in progress. - virtual bool ShouldQuitNow() const = 0; - - // Quit an earlier call to Run(). - virtual void QuitNow() = 0; - - // Repost |event| to |window|. - // |screen_loc| is the event's location in screen coordinates. - virtual void RepostEventToWindow(const ui::LocatedEvent& event, - gfx::NativeWindow window, - const gfx::Point& screen_loc) = 0; - - // Clear any references to the owner widget that was passed into the previous - // call to Run(). - virtual void ClearOwner() = 0; -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_MENU_MENU_MESSAGE_LOOP_H_
diff --git a/ui/views/controls/menu/menu_message_loop_aura.cc b/ui/views/controls/menu/menu_message_loop_aura.cc deleted file mode 100644 index a2b7651..0000000 --- a/ui/views/controls/menu/menu_message_loop_aura.cc +++ /dev/null
@@ -1,202 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/menu/menu_message_loop_aura.h" - -#if defined(OS_WIN) -#include <windowsx.h> -#endif - -#include "base/run_loop.h" -#include "ui/aura/client/screen_position_client.h" -#include "ui/aura/env.h" -#include "ui/aura/window.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/aura/window_tree_host.h" -#include "ui/events/event.h" -#include "ui/events/platform/platform_event_source.h" -#include "ui/events/platform/scoped_event_dispatcher.h" -#include "ui/views/controls/menu/menu_controller.h" -#include "ui/views/widget/widget.h" -#include "ui/wm/public/activation_change_observer.h" -#include "ui/wm/public/activation_client.h" -#include "ui/wm/public/dispatcher_client.h" -#include "ui/wm/public/drag_drop_client.h" - -#if defined(OS_WIN) -#include "ui/base/win/internal_constants.h" -#include "ui/views/controls/menu/menu_message_pump_dispatcher_win.h" -#include "ui/views/win/hwnd_util.h" -#else -#include "ui/views/controls/menu/menu_event_dispatcher_linux.h" -#endif - -using aura::client::ScreenPositionClient; - -namespace views { - -namespace { - -aura::Window* GetOwnerRootWindow(views::Widget* owner) { - return owner ? owner->GetNativeWindow()->GetRootWindow() : NULL; -} - -// ActivationChangeObserverImpl is used to observe activation changes and close -// the menu. Additionally it listens for the root window to be destroyed and -// cancel the menu as well. -class ActivationChangeObserverImpl - : public aura::client::ActivationChangeObserver, - public aura::WindowObserver, - public ui::EventHandler { - public: - ActivationChangeObserverImpl(MenuController* controller, aura::Window* root) - : controller_(controller), root_(root) { - aura::client::GetActivationClient(root_)->AddObserver(this); - root_->AddObserver(this); - root_->AddPreTargetHandler(this); - } - - virtual ~ActivationChangeObserverImpl() { Cleanup(); } - - // aura::client::ActivationChangeObserver: - virtual void OnWindowActivated(aura::Window* gained_active, - aura::Window* lost_active) override { - if (!controller_->drag_in_progress()) - controller_->CancelAll(); - } - - // aura::WindowObserver: - virtual void OnWindowDestroying(aura::Window* window) override { Cleanup(); } - - // ui::EventHandler: - virtual void OnCancelMode(ui::CancelModeEvent* event) override { - controller_->CancelAll(); - } - - private: - void Cleanup() { - if (!root_) - return; - // The ActivationClient may have been destroyed by the time we get here. - aura::client::ActivationClient* client = - aura::client::GetActivationClient(root_); - if (client) - client->RemoveObserver(this); - root_->RemovePreTargetHandler(this); - root_->RemoveObserver(this); - root_ = NULL; - } - - MenuController* controller_; - aura::Window* root_; - - DISALLOW_COPY_AND_ASSIGN(ActivationChangeObserverImpl); -}; - -} // namespace - -// static -MenuMessageLoop* MenuMessageLoop::Create() { - return new MenuMessageLoopAura; -} - -MenuMessageLoopAura::MenuMessageLoopAura() : owner_(NULL) { -} - -MenuMessageLoopAura::~MenuMessageLoopAura() { -} - -void MenuMessageLoopAura::RepostEventToWindow(const ui::LocatedEvent& event, - gfx::NativeWindow window, - const gfx::Point& screen_loc) { - aura::Window* root = window->GetRootWindow(); - ScreenPositionClient* spc = aura::client::GetScreenPositionClient(root); - if (!spc) - return; - - gfx::Point root_loc(screen_loc); - spc->ConvertPointFromScreen(root, &root_loc); - - ui::MouseEvent clone(static_cast<const ui::MouseEvent&>(event)); - clone.set_location(root_loc); - clone.set_root_location(root_loc); - root->GetHost()->dispatcher()->RepostEvent(clone); -} - -void MenuMessageLoopAura::Run(MenuController* controller, - Widget* owner, - bool nested_menu) { - // |owner_| may be NULL. - owner_ = owner; - aura::Window* root = GetOwnerRootWindow(owner_); - // It is possible for the same MenuMessageLoopAura to start a nested - // message-loop while it is already running a nested loop. So make sure the - // quit-closure gets reset to the outer loop's quit-closure once the innermost - // loop terminates. - base::AutoReset<base::Closure> reset_quit_closure(&message_loop_quit_, - base::Closure()); - -#if defined(OS_WIN) - internal::MenuMessagePumpDispatcher nested_dispatcher(controller); - if (root) { - scoped_ptr<ActivationChangeObserverImpl> observer; - if (!nested_menu) - observer.reset(new ActivationChangeObserverImpl(controller, root)); - aura::client::DispatcherRunLoop run_loop( - aura::client::GetDispatcherClient(root), &nested_dispatcher); - message_loop_quit_ = run_loop.QuitClosure(); - run_loop.Run(); - } else { - base::MessageLoopForUI* loop = base::MessageLoopForUI::current(); - base::MessageLoop::ScopedNestableTaskAllower allow(loop); - base::RunLoop run_loop(&nested_dispatcher); - message_loop_quit_ = run_loop.QuitClosure(); - run_loop.Run(); - } -#else - internal::MenuEventDispatcher event_dispatcher(controller); - scoped_ptr<ui::ScopedEventDispatcher> old_dispatcher = - nested_dispatcher_.Pass(); - if (ui::PlatformEventSource::GetInstance()) { - nested_dispatcher_ = - ui::PlatformEventSource::GetInstance()->OverrideDispatcher( - &event_dispatcher); - } - if (root) { - scoped_ptr<ActivationChangeObserverImpl> observer; - if (!nested_menu) - observer.reset(new ActivationChangeObserverImpl(controller, root)); - aura::client::DispatcherRunLoop run_loop( - aura::client::GetDispatcherClient(root), NULL); - message_loop_quit_ = run_loop.QuitClosure(); - run_loop.Run(); - } else { - base::MessageLoopForUI* loop = base::MessageLoopForUI::current(); - base::MessageLoop::ScopedNestableTaskAllower allow(loop); - base::RunLoop run_loop; - message_loop_quit_ = run_loop.QuitClosure(); - run_loop.Run(); - } - nested_dispatcher_ = old_dispatcher.Pass(); -#endif -} - -bool MenuMessageLoopAura::ShouldQuitNow() const { - aura::Window* root = GetOwnerRootWindow(owner_); - return !aura::client::GetDragDropClient(root) || - !aura::client::GetDragDropClient(root)->IsDragDropInProgress(); -} - -void MenuMessageLoopAura::QuitNow() { - CHECK(!message_loop_quit_.is_null()); - message_loop_quit_.Run(); - // Restore the previous dispatcher. - nested_dispatcher_.reset(); -} - -void MenuMessageLoopAura::ClearOwner() { - owner_ = NULL; -} - -} // namespace views
diff --git a/ui/views/controls/menu/menu_message_loop_aura.h b/ui/views/controls/menu/menu_message_loop_aura.h deleted file mode 100644 index 1e58059..0000000 --- a/ui/views/controls/menu/menu_message_loop_aura.h +++ /dev/null
@@ -1,52 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_MENU_MENU_MESSAGE_LOOP_AURA_H_ -#define UI_VIEWS_CONTROLS_MENU_MENU_MESSAGE_LOOP_AURA_H_ - -#include "base/callback.h" -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "ui/views/controls/menu/menu_message_loop.h" - -namespace base { -class MessagePumpDispatcher; -} - -namespace ui { -class ScopedEventDispatcher; -} - -namespace views { - -class MenuMessageLoopAura : public MenuMessageLoop { - public: - MenuMessageLoopAura(); - virtual ~MenuMessageLoopAura(); - - // Overridden from MenuMessageLoop: - virtual void Run(MenuController* controller, - Widget* owner, - bool nested_menu) override; - virtual bool ShouldQuitNow() const override; - virtual void QuitNow() override; - virtual void RepostEventToWindow(const ui::LocatedEvent& event, - gfx::NativeWindow window, - const gfx::Point& screen_loc) override; - virtual void ClearOwner() override; - - private: - // Owner of child windows. - // WARNING: this may be NULL. - Widget* owner_; - - scoped_ptr<ui::ScopedEventDispatcher> nested_dispatcher_; - base::Closure message_loop_quit_; - - DISALLOW_COPY_AND_ASSIGN(MenuMessageLoopAura); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_MENU_MENU_MESSAGE_LOOP_AURA_H_
diff --git a/ui/views/controls/menu/menu_message_pump_dispatcher_win.cc b/ui/views/controls/menu/menu_message_pump_dispatcher_win.cc deleted file mode 100644 index 8f905d0..0000000 --- a/ui/views/controls/menu/menu_message_pump_dispatcher_win.cc +++ /dev/null
@@ -1,95 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/menu/menu_message_pump_dispatcher_win.h" - -#include <windowsx.h> - -#include "ui/events/event_utils.h" -#include "ui/events/keycodes/keyboard_code_conversion.h" -#include "ui/events/keycodes/keyboard_codes.h" -#include "ui/views/controls/menu/menu_controller.h" -#include "ui/views/controls/menu/menu_item_view.h" - -namespace views { -namespace internal { - -MenuMessagePumpDispatcher::MenuMessagePumpDispatcher(MenuController* controller) - : menu_controller_(controller) {} - -MenuMessagePumpDispatcher::~MenuMessagePumpDispatcher() {} - -uint32_t MenuMessagePumpDispatcher::Dispatch(const MSG& msg) { - DCHECK(menu_controller_->IsBlockingRun()); - - bool should_quit = false; - bool should_perform_default = true; - if (menu_controller_->exit_type() == MenuController::EXIT_ALL || - menu_controller_->exit_type() == MenuController::EXIT_DESTROYED) { - should_quit = true; - } else { - // NOTE: we don't get WM_ACTIVATE or anything else interesting in here. - switch (msg.message) { - case WM_CONTEXTMENU: { - MenuItemView* item = menu_controller_->pending_state_.item; - if (item && item->GetRootMenuItem() != item) { - gfx::Point screen_loc(0, item->height()); - View::ConvertPointToScreen(item, &screen_loc); - ui::MenuSourceType source_type = ui::MENU_SOURCE_MOUSE; - if (GET_X_LPARAM(msg.lParam) == -1 && GET_Y_LPARAM(msg.lParam) == -1) - source_type = ui::MENU_SOURCE_KEYBOARD; - item->GetDelegate()->ShowContextMenu( - item, item->GetCommand(), screen_loc, source_type); - } - should_quit = false; - should_perform_default = false; - break; - } - - // NOTE: focus wasn't changed when the menu was shown. As such, don't - // dispatch key events otherwise the focused window will get the events. - case WM_KEYDOWN: { - bool result = - menu_controller_->OnKeyDown(ui::KeyboardCodeFromNative(msg)); - TranslateMessage(&msg); - should_perform_default = false; - should_quit = !result; - break; - } - case WM_CHAR: { - should_quit = menu_controller_->SelectByChar( - static_cast<base::char16>(msg.wParam)); - should_perform_default = false; - break; - } - case WM_KEYUP: - case WM_SYSKEYUP: - // We may have been shown on a system key, as such don't do anything - // here. If another system key is pushed we'll get a WM_SYSKEYDOWN and - // close the menu. - should_quit = false; - should_perform_default = false; - break; - - case WM_CANCELMODE: - case WM_SYSKEYDOWN: - // Exit immediately on system keys. - menu_controller_->Cancel(MenuController::EXIT_ALL); - should_quit = true; - should_perform_default = false; - break; - - default: - break; - } - } - - if (should_quit || menu_controller_->exit_type() != MenuController::EXIT_NONE) - menu_controller_->TerminateNestedMessageLoop(); - return should_perform_default ? POST_DISPATCH_PERFORM_DEFAULT - : POST_DISPATCH_NONE; -} - -} // namespace internal -} // namespace views
diff --git a/ui/views/controls/menu/menu_message_pump_dispatcher_win.h b/ui/views/controls/menu/menu_message_pump_dispatcher_win.h deleted file mode 100644 index 9f84171..0000000 --- a/ui/views/controls/menu/menu_message_pump_dispatcher_win.h +++ /dev/null
@@ -1,36 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_MENU_MENU_MESSAGE_PUMP_DISPATCHER_WIN_H_ -#define UI_VIEWS_CONTROLS_MENU_MENU_MESSAGE_PUMP_DISPATCHER_WIN_H_ - -#include "base/macros.h" -#include "base/message_loop/message_pump_dispatcher.h" - -namespace views { - -class MenuController; - -namespace internal { - -// A message-pump dispatcher object used to dispatch events from the nested -// message-loop initiated by the MenuController. -class MenuMessagePumpDispatcher : public base::MessagePumpDispatcher { - public: - explicit MenuMessagePumpDispatcher(MenuController* menu_controller); - virtual ~MenuMessagePumpDispatcher(); - - private: - // base::MessagePumpDispatcher: - virtual uint32_t Dispatch(const base::NativeEvent& event) override; - - MenuController* menu_controller_; - - DISALLOW_COPY_AND_ASSIGN(MenuMessagePumpDispatcher); -}; - -} // namespace internal -} // namespace views - -#endif // UI_VIEWS_CONTROLS_MENU_MENU_MESSAGE_PUMP_DISPATCHER_WIN_H_
diff --git a/ui/views/controls/menu/menu_model_adapter.cc b/ui/views/controls/menu/menu_model_adapter.cc deleted file mode 100644 index 195658f..0000000 --- a/ui/views/controls/menu/menu_model_adapter.cc +++ /dev/null
@@ -1,292 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/menu/menu_model_adapter.h" - -#include "base/logging.h" -#include "ui/base/models/menu_model.h" -#include "ui/gfx/image/image.h" -#include "ui/views/controls/menu/menu_item_view.h" -#include "ui/views/controls/menu/submenu_view.h" -#include "ui/views/views_delegate.h" - -namespace views { - -MenuModelAdapter::MenuModelAdapter(ui::MenuModel* menu_model) - : menu_model_(menu_model), - triggerable_event_flags_(ui::EF_LEFT_MOUSE_BUTTON | - ui::EF_RIGHT_MOUSE_BUTTON) { - DCHECK(menu_model); -} - -MenuModelAdapter::~MenuModelAdapter() { -} - -void MenuModelAdapter::BuildMenu(MenuItemView* menu) { - DCHECK(menu); - - // Clear the menu. - if (menu->HasSubmenu()) { - const int subitem_count = menu->GetSubmenu()->child_count(); - for (int i = 0; i < subitem_count; ++i) - menu->RemoveMenuItemAt(0); - } - - // Leave entries in the map if the menu is being shown. This - // allows the map to find the menu model of submenus being closed - // so ui::MenuModel::MenuClosed() can be called. - if (!menu->GetMenuController()) - menu_map_.clear(); - menu_map_[menu] = menu_model_; - - // Repopulate the menu. - BuildMenuImpl(menu, menu_model_); - menu->ChildrenChanged(); -} - -MenuItemView* MenuModelAdapter::CreateMenu() { - MenuItemView* item = new MenuItemView(this); - BuildMenu(item); - return item; -} - -// Static. -MenuItemView* MenuModelAdapter::AddMenuItemFromModelAt(ui::MenuModel* model, - int model_index, - MenuItemView* menu, - int menu_index, - int item_id) { - gfx::Image icon; - model->GetIconAt(model_index, &icon); - base::string16 label, sublabel, minor_text; - ui::MenuSeparatorType separator_style = ui::NORMAL_SEPARATOR; - MenuItemView::Type type; - ui::MenuModel::ItemType menu_type = model->GetTypeAt(model_index); - - switch (menu_type) { - case ui::MenuModel::TYPE_COMMAND: - type = MenuItemView::NORMAL; - label = model->GetLabelAt(model_index); - sublabel = model->GetSublabelAt(model_index); - minor_text = model->GetMinorTextAt(model_index); - break; - case ui::MenuModel::TYPE_CHECK: - type = MenuItemView::CHECKBOX; - label = model->GetLabelAt(model_index); - sublabel = model->GetSublabelAt(model_index); - minor_text = model->GetMinorTextAt(model_index); - break; - case ui::MenuModel::TYPE_RADIO: - type = MenuItemView::RADIO; - label = model->GetLabelAt(model_index); - sublabel = model->GetSublabelAt(model_index); - minor_text = model->GetMinorTextAt(model_index); - break; - case ui::MenuModel::TYPE_SEPARATOR: - icon = gfx::Image(); - type = MenuItemView::SEPARATOR; - separator_style = model->GetSeparatorTypeAt(model_index); - break; - case ui::MenuModel::TYPE_SUBMENU: - type = MenuItemView::SUBMENU; - label = model->GetLabelAt(model_index); - sublabel = model->GetSublabelAt(model_index); - minor_text = model->GetMinorTextAt(model_index); - break; - default: - NOTREACHED(); - type = MenuItemView::NORMAL; - break; - } - - return menu->AddMenuItemAt( - menu_index, - item_id, - label, - sublabel, - minor_text, - icon.IsEmpty() ? gfx::ImageSkia() : *icon.ToImageSkia(), - type, - separator_style); -} - -// Static. -MenuItemView* MenuModelAdapter::AppendMenuItemFromModel(ui::MenuModel* model, - int model_index, - MenuItemView* menu, - int item_id) { - const int menu_index = menu->HasSubmenu() ? - menu->GetSubmenu()->child_count() : 0; - return AddMenuItemFromModelAt(model, model_index, menu, menu_index, item_id); -} - - -MenuItemView* MenuModelAdapter::AppendMenuItem(MenuItemView* menu, - ui::MenuModel* model, - int index) { - return AppendMenuItemFromModel(model, index, menu, - model->GetCommandIdAt(index)); -} - -// MenuModelAdapter, MenuDelegate implementation: - -void MenuModelAdapter::ExecuteCommand(int id) { - ui::MenuModel* model = menu_model_; - int index = 0; - if (ui::MenuModel::GetModelAndIndexForCommandId(id, &model, &index)) { - model->ActivatedAt(index); - return; - } - - NOTREACHED(); -} - -void MenuModelAdapter::ExecuteCommand(int id, int mouse_event_flags) { - ui::MenuModel* model = menu_model_; - int index = 0; - if (ui::MenuModel::GetModelAndIndexForCommandId(id, &model, &index)) { - model->ActivatedAt(index, mouse_event_flags); - return; - } - - NOTREACHED(); -} - -bool MenuModelAdapter::IsTriggerableEvent(MenuItemView* source, - const ui::Event& e) { - return e.type() == ui::ET_GESTURE_TAP || - e.type() == ui::ET_GESTURE_TAP_DOWN || - (e.IsMouseEvent() && (triggerable_event_flags_ & e.flags()) != 0); -} - -bool MenuModelAdapter::GetAccelerator(int id, - ui::Accelerator* accelerator) const { - ui::MenuModel* model = menu_model_; - int index = 0; - if (ui::MenuModel::GetModelAndIndexForCommandId(id, &model, &index)) - return model->GetAcceleratorAt(index, accelerator); - - NOTREACHED(); - return false; -} - -base::string16 MenuModelAdapter::GetLabel(int id) const { - ui::MenuModel* model = menu_model_; - int index = 0; - if (ui::MenuModel::GetModelAndIndexForCommandId(id, &model, &index)) - return model->GetLabelAt(index); - - NOTREACHED(); - return base::string16(); -} - -const gfx::FontList* MenuModelAdapter::GetLabelFontList(int id) const { - ui::MenuModel* model = menu_model_; - int index = 0; - if (ui::MenuModel::GetModelAndIndexForCommandId(id, &model, &index)) { - const gfx::FontList* font_list = model->GetLabelFontListAt(index); - if (font_list) - return font_list; - } - - // This line may be reached for the empty menu item. - return MenuDelegate::GetLabelFontList(id); -} - -bool MenuModelAdapter::IsCommandEnabled(int id) const { - ui::MenuModel* model = menu_model_; - int index = 0; - if (ui::MenuModel::GetModelAndIndexForCommandId(id, &model, &index)) - return model->IsEnabledAt(index); - - NOTREACHED(); - return false; -} - -bool MenuModelAdapter::IsCommandVisible(int id) const { - ui::MenuModel* model = menu_model_; - int index = 0; - if (ui::MenuModel::GetModelAndIndexForCommandId(id, &model, &index)) - return model->IsVisibleAt(index); - - NOTREACHED(); - return false; -} - -bool MenuModelAdapter::IsItemChecked(int id) const { - ui::MenuModel* model = menu_model_; - int index = 0; - if (ui::MenuModel::GetModelAndIndexForCommandId(id, &model, &index)) - return model->IsItemCheckedAt(index); - - NOTREACHED(); - return false; -} - -void MenuModelAdapter::SelectionChanged(MenuItemView* menu) { - // Ignore selection of the root menu. - if (menu == menu->GetRootMenuItem()) - return; - - const int id = menu->GetCommand(); - ui::MenuModel* model = menu_model_; - int index = 0; - if (ui::MenuModel::GetModelAndIndexForCommandId(id, &model, &index)) { - model->HighlightChangedTo(index); - return; - } - - NOTREACHED(); -} - -void MenuModelAdapter::WillShowMenu(MenuItemView* menu) { - // Look up the menu model for this menu. - const std::map<MenuItemView*, ui::MenuModel*>::const_iterator map_iterator = - menu_map_.find(menu); - if (map_iterator != menu_map_.end()) { - map_iterator->second->MenuWillShow(); - return; - } - - NOTREACHED(); -} - -void MenuModelAdapter::WillHideMenu(MenuItemView* menu) { - // Look up the menu model for this menu. - const std::map<MenuItemView*, ui::MenuModel*>::const_iterator map_iterator = - menu_map_.find(menu); - if (map_iterator != menu_map_.end()) { - map_iterator->second->MenuClosed(); - return; - } - - NOTREACHED(); -} - -// MenuModelAdapter, private: - -void MenuModelAdapter::BuildMenuImpl(MenuItemView* menu, ui::MenuModel* model) { - DCHECK(menu); - DCHECK(model); - bool has_icons = model->HasIcons(); - const int item_count = model->GetItemCount(); - for (int i = 0; i < item_count; ++i) { - MenuItemView* item = AppendMenuItem(menu, model, i); - - if (model->GetTypeAt(i) == ui::MenuModel::TYPE_SUBMENU) { - DCHECK(item); - DCHECK_EQ(MenuItemView::SUBMENU, item->GetType()); - ui::MenuModel* submodel = model->GetSubmenuModelAt(i); - DCHECK(submodel); - BuildMenuImpl(item, submodel); - has_icons = has_icons || item->has_icons(); - - menu_map_[item] = submodel; - } - } - - menu->set_has_icons(has_icons); -} - -} // namespace views
diff --git a/ui/views/controls/menu/menu_model_adapter.h b/ui/views/controls/menu/menu_model_adapter.h deleted file mode 100644 index 54ce037..0000000 --- a/ui/views/controls/menu/menu_model_adapter.h +++ /dev/null
@@ -1,100 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_MENU_MENU_MODEL_ADAPTER_H_ -#define UI_VIEWS_CONTROLS_MENU_MENU_MODEL_ADAPTER_H_ - -#include <map> - -#include "ui/views/controls/menu/menu_delegate.h" - -namespace ui { -class MenuModel; -} - -namespace views { -class MenuItemView; - -// This class wraps an instance of ui::MenuModel with the -// views::MenuDelegate interface required by views::MenuItemView. -class VIEWS_EXPORT MenuModelAdapter : public MenuDelegate { - public: - // The caller retains ownership of the ui::MenuModel instance and - // must ensure it exists for the lifetime of the adapter. - explicit MenuModelAdapter(ui::MenuModel* menu_model); - virtual ~MenuModelAdapter(); - - // Populate a MenuItemView menu with the ui::MenuModel items - // (including submenus). - virtual void BuildMenu(MenuItemView* menu); - - // Convenience for creating and populating a menu. The caller owns the - // returned MenuItemView. - MenuItemView* CreateMenu(); - - void set_triggerable_event_flags(int triggerable_event_flags) { - triggerable_event_flags_ = triggerable_event_flags; - } - int triggerable_event_flags() const { return triggerable_event_flags_; } - - // Creates a menu item for the specified entry in the model and adds it as - // a child to |menu| at the specified |menu_index|. - static MenuItemView* AddMenuItemFromModelAt(ui::MenuModel* model, - int model_index, - MenuItemView* menu, - int menu_index, - int item_id); - - // Creates a menu item for the specified entry in the model and appends it as - // a child to |menu|. - static MenuItemView* AppendMenuItemFromModel(ui::MenuModel* model, - int model_index, - MenuItemView* menu, - int item_id); - - protected: - // Create and add a menu item to |menu| for the item at index |index| in - // |model|. Subclasses override this to allow custom items to be added to the - // menu. - virtual MenuItemView* AppendMenuItem(MenuItemView* menu, - ui::MenuModel* model, - int index); - - // views::MenuDelegate implementation. - virtual void ExecuteCommand(int id) override; - virtual void ExecuteCommand(int id, int mouse_event_flags) override; - virtual bool IsTriggerableEvent(MenuItemView* source, - const ui::Event& e) override; - virtual bool GetAccelerator(int id, - ui::Accelerator* accelerator) const override; - virtual base::string16 GetLabel(int id) const override; - virtual const gfx::FontList* GetLabelFontList(int id) const override; - virtual bool IsCommandEnabled(int id) const override; - virtual bool IsCommandVisible(int id) const override; - virtual bool IsItemChecked(int id) const override; - virtual void SelectionChanged(MenuItemView* menu) override; - virtual void WillShowMenu(MenuItemView* menu) override; - virtual void WillHideMenu(MenuItemView* menu) override; - - private: - // Implementation of BuildMenu(). - void BuildMenuImpl(MenuItemView* menu, ui::MenuModel* model); - - // Container of ui::MenuModel pointers as encountered by preorder - // traversal. The first element is always the top-level model - // passed to the constructor. - ui::MenuModel* menu_model_; - - // Mouse event flags which can trigger menu actions. - int triggerable_event_flags_; - - // Map MenuItems to MenuModels. Used to implement WillShowMenu(). - std::map<MenuItemView*, ui::MenuModel*> menu_map_; - - DISALLOW_COPY_AND_ASSIGN(MenuModelAdapter); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_MENU_MENU_MODEL_ADAPTER_H_
diff --git a/ui/views/controls/menu/menu_model_adapter_unittest.cc b/ui/views/controls/menu/menu_model_adapter_unittest.cc deleted file mode 100644 index b98fba0..0000000 --- a/ui/views/controls/menu/menu_model_adapter_unittest.cc +++ /dev/null
@@ -1,309 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/menu/menu_model_adapter.h" - -#include "base/strings/utf_string_conversions.h" -#include "ui/base/models/menu_model.h" -#include "ui/base/models/menu_model_delegate.h" -#include "ui/views/controls/menu/menu_item_view.h" -#include "ui/views/controls/menu/menu_runner.h" -#include "ui/views/controls/menu/submenu_view.h" -#include "ui/views/test/views_test_base.h" - -namespace { - -// Base command id for test menu and its submenu. -const int kRootIdBase = 100; -const int kSubmenuIdBase = 200; - -class MenuModelBase : public ui::MenuModel { - public: - explicit MenuModelBase(int command_id_base) - : command_id_base_(command_id_base), - last_activation_(-1) { - } - - virtual ~MenuModelBase() { - } - - // ui::MenuModel implementation: - - virtual bool HasIcons() const override { - return false; - } - - virtual int GetItemCount() const override { - return static_cast<int>(items_.size()); - } - - virtual ItemType GetTypeAt(int index) const override { - return items_[index].type; - } - - virtual ui::MenuSeparatorType GetSeparatorTypeAt( - int index) const override { - return ui::NORMAL_SEPARATOR; - } - - virtual int GetCommandIdAt(int index) const override { - return index + command_id_base_; - } - - virtual base::string16 GetLabelAt(int index) const override { - return items_[index].label; - } - - virtual bool IsItemDynamicAt(int index) const override { - return false; - } - - virtual const gfx::FontList* GetLabelFontListAt(int index) const override { - return NULL; - } - - virtual bool GetAcceleratorAt(int index, - ui::Accelerator* accelerator) const override { - return false; - } - - virtual bool IsItemCheckedAt(int index) const override { - return false; - } - - virtual int GetGroupIdAt(int index) const override { - return 0; - } - - virtual bool GetIconAt(int index, gfx::Image* icon) override { - return false; - } - - virtual ui::ButtonMenuItemModel* GetButtonMenuItemAt( - int index) const override { - return NULL; - } - - virtual bool IsEnabledAt(int index) const override { - return true; - } - - virtual bool IsVisibleAt(int index) const override { - return true; - } - - virtual MenuModel* GetSubmenuModelAt(int index) const override { - return items_[index].submenu; - } - - virtual void HighlightChangedTo(int index) override { - } - - virtual void ActivatedAt(int index) override { - set_last_activation(index); - } - - virtual void ActivatedAt(int index, int event_flags) override { - ActivatedAt(index); - } - - virtual void MenuWillShow() override { - } - - virtual void MenuClosed() override { - } - - virtual void SetMenuModelDelegate( - ui::MenuModelDelegate* delegate) override { - } - - virtual ui::MenuModelDelegate* GetMenuModelDelegate() const override { - return NULL; - } - - // Item definition. - struct Item { - Item(ItemType item_type, - const std::string& item_label, - ui::MenuModel* item_submenu) - : type(item_type), - label(base::ASCIIToUTF16(item_label)), - submenu(item_submenu) { - } - - ItemType type; - base::string16 label; - ui::MenuModel* submenu; - }; - - const Item& GetItemDefinition(int index) { - return items_[index]; - } - - // Access index argument to ActivatedAt(). - int last_activation() const { return last_activation_; } - void set_last_activation(int last_activation) { - last_activation_ = last_activation; - } - - protected: - std::vector<Item> items_; - - private: - int command_id_base_; - int last_activation_; - - DISALLOW_COPY_AND_ASSIGN(MenuModelBase); -}; - -class SubmenuModel : public MenuModelBase { - public: - SubmenuModel() : MenuModelBase(kSubmenuIdBase) { - items_.push_back(Item(TYPE_COMMAND, "submenu item 0", NULL)); - items_.push_back(Item(TYPE_COMMAND, "submenu item 1", NULL)); - } - - virtual ~SubmenuModel() { - } - - private: - DISALLOW_COPY_AND_ASSIGN(SubmenuModel); -}; - -class RootModel : public MenuModelBase { - public: - RootModel() : MenuModelBase(kRootIdBase) { - submenu_model_.reset(new SubmenuModel); - - items_.push_back(Item(TYPE_COMMAND, "command 0", NULL)); - items_.push_back(Item(TYPE_CHECK, "check 1", NULL)); - items_.push_back(Item(TYPE_SEPARATOR, "", NULL)); - items_.push_back(Item(TYPE_SUBMENU, "submenu 3", submenu_model_.get())); - items_.push_back(Item(TYPE_RADIO, "radio 4", NULL)); - } - - virtual ~RootModel() { - } - - private: - scoped_ptr<MenuModel> submenu_model_; - - DISALLOW_COPY_AND_ASSIGN(RootModel); -}; - -} // namespace - -namespace views { - -typedef ViewsTestBase MenuModelAdapterTest; - -TEST_F(MenuModelAdapterTest, BasicTest) { - // Build model and adapter. - RootModel model; - views::MenuModelAdapter delegate(&model); - - // Create menu. Build menu twice to check that rebuilding works properly. - MenuItemView* menu = new views::MenuItemView(&delegate); - // MenuRunner takes ownership of menu. - scoped_ptr<MenuRunner> menu_runner(new MenuRunner(menu, 0)); - delegate.BuildMenu(menu); - delegate.BuildMenu(menu); - EXPECT_TRUE(menu->HasSubmenu()); - - // Check top level menu items. - views::SubmenuView* item_container = menu->GetSubmenu(); - EXPECT_EQ(5, item_container->child_count()); - - for (int i = 0; i < item_container->child_count(); ++i) { - const MenuModelBase::Item& model_item = model.GetItemDefinition(i); - - const int id = i + kRootIdBase; - MenuItemView* item = menu->GetMenuItemByID(id); - if (!item) { - EXPECT_EQ(ui::MenuModel::TYPE_SEPARATOR, model_item.type); - continue; - } - - // Check placement. - EXPECT_EQ(i, menu->GetSubmenu()->GetIndexOf(item)); - - // Check type. - switch (model_item.type) { - case ui::MenuModel::TYPE_COMMAND: - EXPECT_EQ(views::MenuItemView::NORMAL, item->GetType()); - break; - case ui::MenuModel::TYPE_CHECK: - EXPECT_EQ(views::MenuItemView::CHECKBOX, item->GetType()); - break; - case ui::MenuModel::TYPE_RADIO: - EXPECT_EQ(views::MenuItemView::RADIO, item->GetType()); - break; - case ui::MenuModel::TYPE_SEPARATOR: - case ui::MenuModel::TYPE_BUTTON_ITEM: - break; - case ui::MenuModel::TYPE_SUBMENU: - EXPECT_EQ(views::MenuItemView::SUBMENU, item->GetType()); - break; - } - - // Check activation. - static_cast<views::MenuDelegate*>(&delegate)->ExecuteCommand(id); - EXPECT_EQ(i, model.last_activation()); - model.set_last_activation(-1); - } - - // Check submenu items. - views::MenuItemView* submenu = menu->GetMenuItemByID(103); - views::SubmenuView* subitem_container = submenu->GetSubmenu(); - EXPECT_EQ(2, subitem_container->child_count()); - - for (int i = 0; i < subitem_container->child_count(); ++i) { - MenuModelBase* submodel = static_cast<MenuModelBase*>( - model.GetSubmenuModelAt(3)); - EXPECT_TRUE(submodel); - - const MenuModelBase::Item& model_item = submodel->GetItemDefinition(i); - - const int id = i + kSubmenuIdBase; - MenuItemView* item = menu->GetMenuItemByID(id); - if (!item) { - EXPECT_EQ(ui::MenuModel::TYPE_SEPARATOR, model_item.type); - continue; - } - - // Check placement. - EXPECT_EQ(i, submenu->GetSubmenu()->GetIndexOf(item)); - - // Check type. - switch (model_item.type) { - case ui::MenuModel::TYPE_COMMAND: - EXPECT_EQ(views::MenuItemView::NORMAL, item->GetType()); - break; - case ui::MenuModel::TYPE_CHECK: - EXPECT_EQ(views::MenuItemView::CHECKBOX, item->GetType()); - break; - case ui::MenuModel::TYPE_RADIO: - EXPECT_EQ(views::MenuItemView::RADIO, item->GetType()); - break; - case ui::MenuModel::TYPE_SEPARATOR: - case ui::MenuModel::TYPE_BUTTON_ITEM: - break; - case ui::MenuModel::TYPE_SUBMENU: - EXPECT_EQ(views::MenuItemView::SUBMENU, item->GetType()); - break; - } - - // Check activation. - static_cast<views::MenuDelegate*>(&delegate)->ExecuteCommand(id); - EXPECT_EQ(i, submodel->last_activation()); - submodel->set_last_activation(-1); - } - - // Check that selecting the root item is safe. The MenuModel does - // not care about the root so MenuModelAdapter should do nothing - // (not hit the NOTREACHED check) when the root is selected. - static_cast<views::MenuDelegate*>(&delegate)->SelectionChanged(menu); -} - -} // namespace views
diff --git a/ui/views/controls/menu/menu_runner.cc b/ui/views/controls/menu/menu_runner.cc deleted file mode 100644 index c302cb7..0000000 --- a/ui/views/controls/menu/menu_runner.cc +++ /dev/null
@@ -1,79 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/menu/menu_runner.h" - -#include "ui/views/controls/menu/menu_runner_handler.h" -#include "ui/views/controls/menu/menu_runner_impl.h" - -namespace views { - -MenuRunner::MenuRunner(ui::MenuModel* menu_model, int32 run_types) - : run_types_(run_types), - impl_(internal::MenuRunnerImplInterface::Create(menu_model, run_types)) { -} - -MenuRunner::MenuRunner(MenuItemView* menu_view, int32 run_types) - : run_types_(run_types), impl_(new internal::MenuRunnerImpl(menu_view)) { -} - -MenuRunner::~MenuRunner() { - impl_->Release(); -} - -MenuRunner::RunResult MenuRunner::RunMenuAt(Widget* parent, - MenuButton* button, - const gfx::Rect& bounds, - MenuAnchorPosition anchor, - ui::MenuSourceType source_type) { - if (runner_handler_.get()) { - return runner_handler_->RunMenuAt( - parent, button, bounds, anchor, source_type, run_types_); - } - - // The parent of the nested menu will have created a DisplayChangeListener, so - // we avoid creating a DisplayChangeListener if nested. Drop menus are - // transient, so we don't cancel in that case. - if ((run_types_ & (IS_NESTED | FOR_DROP)) == 0 && parent) { - display_change_listener_.reset( - internal::DisplayChangeListener::Create(parent, this)); - } - - if (run_types_ & CONTEXT_MENU) { - switch (source_type) { - case ui::MENU_SOURCE_NONE: - case ui::MENU_SOURCE_KEYBOARD: - case ui::MENU_SOURCE_MOUSE: - anchor = MENU_ANCHOR_TOPLEFT; - break; - case ui::MENU_SOURCE_TOUCH: - case ui::MENU_SOURCE_TOUCH_EDIT_MENU: - anchor = MENU_ANCHOR_BOTTOMCENTER; - break; - default: - break; - } - } - - return impl_->RunMenuAt(parent, button, bounds, anchor, run_types_); -} - -bool MenuRunner::IsRunning() const { - return impl_->IsRunning(); -} - -void MenuRunner::Cancel() { - impl_->Cancel(); -} - -base::TimeDelta MenuRunner::closing_event_time() const { - return impl_->GetClosingEventTime(); -} - -void MenuRunner::SetRunnerHandler( - scoped_ptr<MenuRunnerHandler> runner_handler) { - runner_handler_ = runner_handler.Pass(); -} - -} // namespace views
diff --git a/ui/views/controls/menu/menu_runner.h b/ui/views/controls/menu/menu_runner.h deleted file mode 100644 index 1744c93..0000000 --- a/ui/views/controls/menu/menu_runner.h +++ /dev/null
@@ -1,170 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_H_ -#define UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "ui/base/ui_base_types.h" -#include "ui/views/controls/menu/menu_types.h" -#include "ui/views/views_export.h" - -namespace base { -class TimeDelta; -} - -namespace gfx { -class Rect; -} - -namespace ui { -class MenuModel; -} - -namespace views { - -class MenuButton; -class MenuItemView; -class MenuModelAdapter; -class MenuRunnerHandler; -class Widget; - -namespace internal { -class DisplayChangeListener; -class MenuRunnerImplInterface; -} - -namespace test { -class MenuRunnerTestAPI; -} - -// MenuRunner is responsible for showing (running) the menu and additionally -// owning the MenuItemView. RunMenuAt() runs a nested message loop. It is safe -// to delete MenuRunner at any point, but MenuRunner internally only deletes the -// MenuItemView *after* the nested message loop completes. If MenuRunner is -// deleted while the menu is showing the delegate of the menu is reset. This is -// done to ensure delegates aren't notified after they may have been deleted. -// -// NOTE: while you can delete a MenuRunner at any point, the nested message loop -// won't return immediately. This means if you delete the object that owns -// the MenuRunner while the menu is running, your object is effectively still -// on the stack. A return value of MENU_DELETED indicated this. In most cases -// if RunMenuAt() returns MENU_DELETED, you should return immediately. -// -// Similarly you should avoid creating MenuRunner on the stack. Doing so means -// MenuRunner may not be immediately destroyed if your object is destroyed, -// resulting in possible callbacks to your now deleted object. Instead you -// should define MenuRunner as a scoped_ptr in your class so that when your -// object is destroyed MenuRunner initiates the proper cleanup and ensures your -// object isn't accessed again. -class VIEWS_EXPORT MenuRunner { - public: - enum RunTypes { - // The menu has mnemonics. - HAS_MNEMONICS = 1 << 0, - - // The menu is a nested context menu. For example, click a folder on the - // bookmark bar, then right click an entry to get its context menu. - IS_NESTED = 1 << 1, - - // Used for showing a menu during a drop operation. This does NOT block the - // caller, instead the delegate is notified when the menu closes via the - // DropMenuClosed method. - FOR_DROP = 1 << 2, - - // The menu is a context menu (not necessarily nested), for example right - // click on a link on a website in the browser. - CONTEXT_MENU = 1 << 3, - - // The menu should behave like a Windows native Combobox dropdow menu. - // This behavior includes accepting the pending item and closing on F4. - COMBOBOX = 1 << 4, - - // A child view is performing a drag-and-drop operation, so the menu should - // stay open (even if it doesn't receive drag updated events). In this case, - // the caller is responsible for closing the menu upon completion of the - // drag-and-drop. - NESTED_DRAG = 1 << 5, - }; - - enum RunResult { - // Indicates RunMenuAt is returning because the MenuRunner was deleted. - MENU_DELETED, - - // Indicates RunMenuAt returned and MenuRunner was not deleted. - NORMAL_EXIT - }; - - // Creates a new MenuRunner. - // |run_types| is a bitmask of RunTypes. - MenuRunner(ui::MenuModel* menu_model, int32 run_types); - MenuRunner(MenuItemView* menu, int32 run_types); - ~MenuRunner(); - - // Runs the menu. If this returns MENU_DELETED the method is returning - // because the MenuRunner was deleted. - // Typically callers should NOT do any processing if this returns - // MENU_DELETED. - // If |anchor| uses a |BUBBLE_..| type, the bounds will get determined by - // using |bounds| as the thing to point at in screen coordinates. - RunResult RunMenuAt(Widget* parent, - MenuButton* button, - const gfx::Rect& bounds, - MenuAnchorPosition anchor, - ui::MenuSourceType source_type) WARN_UNUSED_RESULT; - - // Returns true if we're in a nested message loop running the menu. - bool IsRunning() const; - - // Hides and cancels the menu. This does nothing if the menu is not open. - void Cancel(); - - // Returns the time from the event which closed the menu - or 0. - base::TimeDelta closing_event_time() const; - - private: - friend class test::MenuRunnerTestAPI; - - // Sets an implementation of RunMenuAt. This is intended to be used at test. - void SetRunnerHandler(scoped_ptr<MenuRunnerHandler> runner_handler); - - const int32 run_types_; - - // We own this. No scoped_ptr because it is destroyed by calling Release(). - internal::MenuRunnerImplInterface* impl_; - - // An implementation of RunMenuAt. This is usually NULL and ignored. If this - // is not NULL, this implementation will be used. - scoped_ptr<MenuRunnerHandler> runner_handler_; - - scoped_ptr<internal::DisplayChangeListener> display_change_listener_; - - DISALLOW_COPY_AND_ASSIGN(MenuRunner); -}; - -namespace internal { - -// DisplayChangeListener is intended to listen for changes in the display size -// and cancel the menu. DisplayChangeListener is created when the menu is -// shown. -class DisplayChangeListener { - public: - virtual ~DisplayChangeListener() {} - - // Creates the platform specified DisplayChangeListener, or NULL if there - // isn't one. Caller owns the returned value. - static DisplayChangeListener* Create(Widget* parent, - MenuRunner* runner); - - protected: - DisplayChangeListener() {} -}; - -} // namespace internal - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_H_
diff --git a/ui/views/controls/menu/menu_runner_handler.h b/ui/views/controls/menu/menu_runner_handler.h deleted file mode 100644 index 47d75c8..0000000 --- a/ui/views/controls/menu/menu_runner_handler.h +++ /dev/null
@@ -1,31 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_HANDLER_H_ -#define UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_HANDLER_H_ - -#include "base/basictypes.h" - -namespace views { - -class MenuButton; -class MenuItemView; -class Widget; - -// Used internally by MenuRunner to show the menu. Can be set in tests (see -// MenuRunnerTestApi) for mocking running of the menu. -class VIEWS_EXPORT MenuRunnerHandler { - public: - virtual ~MenuRunnerHandler() {} - virtual MenuRunner::RunResult RunMenuAt(Widget* parent, - MenuButton* button, - const gfx::Rect& bounds, - MenuAnchorPosition anchor, - ui::MenuSourceType source_type, - int32 types) = 0; -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_HANDLER_H_
diff --git a/ui/views/controls/menu/menu_runner_impl.cc b/ui/views/controls/menu/menu_runner_impl.cc deleted file mode 100644 index 4167be9..0000000 --- a/ui/views/controls/menu/menu_runner_impl.cc +++ /dev/null
@@ -1,217 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/menu/menu_runner_impl.h" - -#include "ui/native_theme/native_theme.h" -#include "ui/views/controls/button/menu_button.h" -#include "ui/views/controls/menu/menu_controller.h" -#include "ui/views/controls/menu/menu_delegate.h" -#include "ui/views/controls/menu/menu_item_view.h" -#include "ui/views/controls/menu/menu_runner_impl_adapter.h" -#include "ui/views/widget/widget.h" - -#if defined(OS_WIN) -#include "base/win/win_util.h" -#endif - -namespace views { -namespace internal { - -#if !defined(OS_MACOSX) -MenuRunnerImplInterface* MenuRunnerImplInterface::Create( - ui::MenuModel* menu_model, - int32 run_types) { - return new MenuRunnerImplAdapter(menu_model); -} -#endif - -MenuRunnerImpl::MenuRunnerImpl(MenuItemView* menu) - : menu_(menu), - running_(false), - delete_after_run_(false), - for_drop_(false), - controller_(NULL), - owns_controller_(false), - closing_event_time_(base::TimeDelta()), - weak_factory_(this) { -} - -bool MenuRunnerImpl::IsRunning() const { - return running_; -} - -void MenuRunnerImpl::Release() { - if (running_) { - if (delete_after_run_) - return; // We already canceled. - - // The menu is running a nested message loop, we can't delete it now - // otherwise the stack would be in a really bad state (many frames would - // have deleted objects on them). Instead cancel the menu, when it returns - // Holder will delete itself. - delete_after_run_ = true; - - // Swap in a different delegate. That way we know the original MenuDelegate - // won't be notified later on (when it's likely already been deleted). - if (!empty_delegate_.get()) - empty_delegate_.reset(new MenuDelegate()); - menu_->set_delegate(empty_delegate_.get()); - - DCHECK(controller_); - // Release is invoked when MenuRunner is destroyed. Assume this is happening - // because the object referencing the menu has been destroyed and the menu - // button is no longer valid. - controller_->Cancel(MenuController::EXIT_DESTROYED); - } else { - delete this; - } -} - -MenuRunner::RunResult MenuRunnerImpl::RunMenuAt(Widget* parent, - MenuButton* button, - const gfx::Rect& bounds, - MenuAnchorPosition anchor, - int32 run_types) { - closing_event_time_ = base::TimeDelta(); - if (running_) { - // Ignore requests to show the menu while it's already showing. MenuItemView - // doesn't handle this very well (meaning it crashes). - return MenuRunner::NORMAL_EXIT; - } - - MenuController* controller = MenuController::GetActiveInstance(); - if (controller) { - if ((run_types & MenuRunner::IS_NESTED) != 0) { - if (!controller->IsBlockingRun()) { - controller->CancelAll(); - controller = NULL; - } - } else { - // There's some other menu open and we're not nested. Cancel the menu. - controller->CancelAll(); - if ((run_types & MenuRunner::FOR_DROP) == 0) { - // We can't open another menu, otherwise the message loop would become - // twice nested. This isn't necessarily a problem, but generally isn't - // expected. - return MenuRunner::NORMAL_EXIT; - } - // Drop menus don't block the message loop, so it's ok to create a new - // MenuController. - controller = NULL; - } - } - - running_ = true; - for_drop_ = (run_types & MenuRunner::FOR_DROP) != 0; - bool has_mnemonics = (run_types & MenuRunner::HAS_MNEMONICS) != 0; - owns_controller_ = false; - if (!controller) { - // No menus are showing, show one. - ui::NativeTheme* theme = - parent ? parent->GetNativeTheme() : ui::NativeTheme::instance(); - controller = new MenuController(theme, !for_drop_, this); - owns_controller_ = true; - } - controller->set_is_combobox((run_types & MenuRunner::COMBOBOX) != 0); - controller_ = controller; - menu_->set_controller(controller_); - menu_->PrepareForRun(owns_controller_, - has_mnemonics, - !for_drop_ && ShouldShowMnemonics(button)); - - // Run the loop. - int mouse_event_flags = 0; - MenuItemView* result = - controller->Run(parent, - button, - menu_, - bounds, - anchor, - (run_types & MenuRunner::CONTEXT_MENU) != 0, - (run_types & MenuRunner::NESTED_DRAG) != 0, - &mouse_event_flags); - // Get the time of the event which closed this menu. - closing_event_time_ = controller->closing_event_time(); - if (for_drop_) { - // Drop menus return immediately. We finish processing in DropMenuClosed. - return MenuRunner::NORMAL_EXIT; - } - return MenuDone(result, mouse_event_flags); -} - -void MenuRunnerImpl::Cancel() { - if (running_) - controller_->Cancel(MenuController::EXIT_ALL); -} - -base::TimeDelta MenuRunnerImpl::GetClosingEventTime() const { - return closing_event_time_; -} - -void MenuRunnerImpl::DropMenuClosed(NotifyType type, MenuItemView* menu) { - MenuDone(NULL, 0); - - if (type == NOTIFY_DELEGATE && menu->GetDelegate()) { - // Delegate is null when invoked from the destructor. - menu->GetDelegate()->DropMenuClosed(menu); - } -} - -void MenuRunnerImpl::SiblingMenuCreated(MenuItemView* menu) { - if (menu != menu_ && sibling_menus_.count(menu) == 0) - sibling_menus_.insert(menu); -} - -MenuRunnerImpl::~MenuRunnerImpl() { - delete menu_; - for (std::set<MenuItemView*>::iterator i = sibling_menus_.begin(); - i != sibling_menus_.end(); - ++i) - delete *i; -} - -MenuRunner::RunResult MenuRunnerImpl::MenuDone(MenuItemView* result, - int mouse_event_flags) { - menu_->RemoveEmptyMenus(); - menu_->set_controller(NULL); - - if (owns_controller_) { - // We created the controller and need to delete it. - delete controller_; - owns_controller_ = false; - } - controller_ = NULL; - // Make sure all the windows we created to show the menus have been - // destroyed. - menu_->DestroyAllMenuHosts(); - if (delete_after_run_) { - delete this; - return MenuRunner::MENU_DELETED; - } - running_ = false; - if (result && menu_->GetDelegate()) { - // Executing the command may also delete this. - base::WeakPtr<MenuRunnerImpl> ref(weak_factory_.GetWeakPtr()); - menu_->GetDelegate()->ExecuteCommand(result->GetCommand(), - mouse_event_flags); - if (!ref) - return MenuRunner::MENU_DELETED; - } - return MenuRunner::NORMAL_EXIT; -} - -bool MenuRunnerImpl::ShouldShowMnemonics(MenuButton* button) { - // Show mnemonics if the button has focus or alt is pressed. - bool show_mnemonics = button ? button->HasFocus() : false; -#if defined(OS_WIN) - // This is only needed on Windows. - if (!show_mnemonics) - show_mnemonics = base::win::IsAltPressed(); -#endif - return show_mnemonics; -} - -} // namespace internal -} // namespace views
diff --git a/ui/views/controls/menu/menu_runner_impl.h b/ui/views/controls/menu/menu_runner_impl.h deleted file mode 100644 index 910f4b7..0000000 --- a/ui/views/controls/menu/menu_runner_impl.h +++ /dev/null
@@ -1,94 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_IMPL_H_ -#define UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_IMPL_H_ - -#include "ui/views/controls/menu/menu_runner_impl_interface.h" - -#include <set> - -#include "base/memory/weak_ptr.h" -#include "base/time/time.h" -#include "ui/views/controls/menu/menu_controller_delegate.h" - -namespace views { - -class MenuController; -class MenuDelegate; -class MenuItemView; - -namespace internal { - -// A menu runner implementation that uses views::MenuItemView to show a menu. -class MenuRunnerImpl : public MenuRunnerImplInterface, - public MenuControllerDelegate { - public: - explicit MenuRunnerImpl(MenuItemView* menu); - - virtual bool IsRunning() const override; - virtual void Release() override; - virtual MenuRunner::RunResult RunMenuAt(Widget* parent, - MenuButton* button, - const gfx::Rect& bounds, - MenuAnchorPosition anchor, - int32 run_types) override; - virtual void Cancel() override; - virtual base::TimeDelta GetClosingEventTime() const override; - - // MenuControllerDelegate: - virtual void DropMenuClosed(NotifyType type, MenuItemView* menu) override; - virtual void SiblingMenuCreated(MenuItemView* menu) override; - - private: - virtual ~MenuRunnerImpl(); - - // Cleans up after the menu is no longer showing. |result| is the menu that - // the user selected, or NULL if nothing was selected. - MenuRunner::RunResult MenuDone(MenuItemView* result, int mouse_event_flags); - - // Returns true if mnemonics should be shown in the menu. - bool ShouldShowMnemonics(MenuButton* button); - - // The menu. We own this. We don't use scoped_ptr as the destructor is - // protected and we're a friend. - MenuItemView* menu_; - - // Any sibling menus. Does not include |menu_|. We own these too. - std::set<MenuItemView*> sibling_menus_; - - // Created and set as the delegate of the MenuItemView if Release() is - // invoked. This is done to make sure the delegate isn't notified after - // Release() is invoked. We do this as we assume the delegate is no longer - // valid if MenuRunner has been deleted. - scoped_ptr<MenuDelegate> empty_delegate_; - - // Are we in run waiting for it to return? - bool running_; - - // Set if |running_| and Release() has been invoked. - bool delete_after_run_; - - // Are we running for a drop? - bool for_drop_; - - // The controller. - MenuController* controller_; - - // Do we own the controller? - bool owns_controller_; - - // The timestamp of the event which closed the menu - or 0. - base::TimeDelta closing_event_time_; - - // Used to detect deletion of |this| when notifying delegate of success. - base::WeakPtrFactory<MenuRunnerImpl> weak_factory_; - - DISALLOW_COPY_AND_ASSIGN(MenuRunnerImpl); -}; - -} // namespace internal -} // namespace views - -#endif // UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_IMPL_H_
diff --git a/ui/views/controls/menu/menu_runner_impl_adapter.cc b/ui/views/controls/menu/menu_runner_impl_adapter.cc deleted file mode 100644 index 2e6822e..0000000 --- a/ui/views/controls/menu/menu_runner_impl_adapter.cc +++ /dev/null
@@ -1,48 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/menu/menu_runner_impl_adapter.h" - -#include "ui/views/controls/menu/menu_model_adapter.h" -#include "ui/views/controls/menu/menu_runner_impl.h" - -namespace views { -namespace internal { - -MenuRunnerImplAdapter::MenuRunnerImplAdapter(ui::MenuModel* menu_model) - : menu_model_adapter_(new MenuModelAdapter(menu_model)), - impl_(new MenuRunnerImpl(menu_model_adapter_->CreateMenu())) { -} - -bool MenuRunnerImplAdapter::IsRunning() const { - return impl_->IsRunning(); -} - -void MenuRunnerImplAdapter::Release() { - impl_->Release(); - delete this; -} - -MenuRunner::RunResult MenuRunnerImplAdapter::RunMenuAt( - Widget* parent, - MenuButton* button, - const gfx::Rect& bounds, - MenuAnchorPosition anchor, - int32 types) { - return impl_->RunMenuAt(parent, button, bounds, anchor, types); -} - -void MenuRunnerImplAdapter::Cancel() { - impl_->Cancel(); -} - -base::TimeDelta MenuRunnerImplAdapter::GetClosingEventTime() const { - return impl_->GetClosingEventTime(); -} - -MenuRunnerImplAdapter::~MenuRunnerImplAdapter() { -} - -} // namespace internal -} // namespace views
diff --git a/ui/views/controls/menu/menu_runner_impl_adapter.h b/ui/views/controls/menu/menu_runner_impl_adapter.h deleted file mode 100644 index eba68c4..0000000 --- a/ui/views/controls/menu/menu_runner_impl_adapter.h +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_IMPL_ADAPTER_H_ -#define UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_IMPL_ADAPTER_H_ - -#include "ui/views/controls/menu/menu_runner_impl_interface.h" - -namespace views { -namespace internal { - -class MenuRunnerImpl; - -// Given a MenuModel, adapts MenuRunnerImpl which expects a MenuItemView. -class MenuRunnerImplAdapter : public MenuRunnerImplInterface { - public: - explicit MenuRunnerImplAdapter(ui::MenuModel* menu_model); - - // MenuRunnerImplInterface: - virtual bool IsRunning() const override; - virtual void Release() override; - virtual MenuRunner::RunResult RunMenuAt(Widget* parent, - MenuButton* button, - const gfx::Rect& bounds, - MenuAnchorPosition anchor, - int32 types) override; - virtual void Cancel() override; - virtual base::TimeDelta GetClosingEventTime() const override; - - private: - virtual ~MenuRunnerImplAdapter(); - - scoped_ptr<MenuModelAdapter> menu_model_adapter_; - MenuRunnerImpl* impl_; - - DISALLOW_COPY_AND_ASSIGN(MenuRunnerImplAdapter); -}; - -} // namespace internal -} // namespace views - -#endif // UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_IMPL_ADAPTER_H_
diff --git a/ui/views/controls/menu/menu_runner_impl_interface.h b/ui/views/controls/menu/menu_runner_impl_interface.h deleted file mode 100644 index 0914cba..0000000 --- a/ui/views/controls/menu/menu_runner_impl_interface.h +++ /dev/null
@@ -1,55 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_IMPL_INTERFACE_H_ -#define UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_IMPL_INTERFACE_H_ - -#include "ui/views/controls/menu/menu_runner.h" - -namespace views { - -class MenuItemView; - -namespace internal { - -// An abstract interface for menu runner implementations. -// Invoke Release() to destroy. Release() deletes immediately if the menu isn't -// showing. If the menu is showing Release() cancels the menu and when the -// nested RunMenuAt() call returns deletes itself and the menu. -class MenuRunnerImplInterface { - public: - // Creates a concrete instance for running |menu_model|. - // |run_types| is a bitmask of MenuRunner::RunTypes. - static MenuRunnerImplInterface* Create(ui::MenuModel* menu_model, - int32 run_types); - - // Returns true if we're in a nested message loop running the menu. - virtual bool IsRunning() const = 0; - - // See description above class for details. - virtual void Release() = 0; - - // Runs the menu. See MenuRunner::RunMenuAt for more details. - virtual MenuRunner::RunResult RunMenuAt(Widget* parent, - MenuButton* button, - const gfx::Rect& bounds, - MenuAnchorPosition anchor, - int32 run_types) - WARN_UNUSED_RESULT = 0; - - // Hides and cancels the menu. - virtual void Cancel() = 0; - - // Returns the time from the event which closed the menu - or 0. - virtual base::TimeDelta GetClosingEventTime() const = 0; - - protected: - // Call Release() to delete. - virtual ~MenuRunnerImplInterface() {} -}; - -} // namespace internal -} // namespace views - -#endif // UI_VIEWS_CONTROLS_MENU_MENU_RUNNER_IMPL_INTERFACE_H_
diff --git a/ui/views/controls/menu/menu_scroll_view_container.cc b/ui/views/controls/menu/menu_scroll_view_container.cc deleted file mode 100644 index 2d3db74..0000000 --- a/ui/views/controls/menu/menu_scroll_view_container.cc +++ /dev/null
@@ -1,334 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/menu/menu_scroll_view_container.h" - -#include "third_party/skia/include/core/SkPaint.h" -#include "third_party/skia/include/core/SkPath.h" -#include "ui/accessibility/ax_view_state.h" -#include "ui/gfx/canvas.h" -#include "ui/native_theme/native_theme_aura.h" -#include "ui/views/border.h" -#include "ui/views/bubble/bubble_border.h" -#include "ui/views/controls/menu/menu_config.h" -#include "ui/views/controls/menu/menu_controller.h" -#include "ui/views/controls/menu/menu_item_view.h" -#include "ui/views/controls/menu/submenu_view.h" -#include "ui/views/round_rect_painter.h" - -using ui::NativeTheme; - -namespace views { - -namespace { - -static const int kBorderPaddingDueToRoundedCorners = 1; - -// MenuScrollButton ------------------------------------------------------------ - -// MenuScrollButton is used for the scroll buttons when not all menu items fit -// on screen. MenuScrollButton forwards appropriate events to the -// MenuController. - -class MenuScrollButton : public View { - public: - MenuScrollButton(SubmenuView* host, bool is_up) - : host_(host), - is_up_(is_up), - // Make our height the same as that of other MenuItemViews. - pref_height_(MenuItemView::pref_menu_height()) { - } - - virtual gfx::Size GetPreferredSize() const override { - return gfx::Size( - host_->GetMenuItem()->GetMenuConfig().scroll_arrow_height * 2 - 1, - pref_height_); - } - - virtual bool CanDrop(const OSExchangeData& data) override { - DCHECK(host_->GetMenuItem()->GetMenuController()); - return true; // Always return true so that drop events are targeted to us. - } - - virtual void OnDragEntered(const ui::DropTargetEvent& event) override { - DCHECK(host_->GetMenuItem()->GetMenuController()); - host_->GetMenuItem()->GetMenuController()->OnDragEnteredScrollButton( - host_, is_up_); - } - - virtual int OnDragUpdated(const ui::DropTargetEvent& event) override { - return ui::DragDropTypes::DRAG_NONE; - } - - virtual void OnDragExited() override { - DCHECK(host_->GetMenuItem()->GetMenuController()); - host_->GetMenuItem()->GetMenuController()->OnDragExitedScrollButton(host_); - } - - virtual int OnPerformDrop(const ui::DropTargetEvent& event) override { - return ui::DragDropTypes::DRAG_NONE; - } - - virtual void OnPaint(gfx::Canvas* canvas) override { - const MenuConfig& config = host_->GetMenuItem()->GetMenuConfig(); - - // The background. - gfx::Rect item_bounds(0, 0, width(), height()); - NativeTheme::ExtraParams extra; - extra.menu_item.is_selected = false; - GetNativeTheme()->Paint(canvas->sk_canvas(), - NativeTheme::kMenuItemBackground, - NativeTheme::kNormal, item_bounds, extra); - - // Then the arrow. - int x = width() / 2; - int y = (height() - config.scroll_arrow_height) / 2; - - int x_left = x - config.scroll_arrow_height; - int x_right = x + config.scroll_arrow_height; - int y_bottom; - - if (!is_up_) { - y_bottom = y; - y = y_bottom + config.scroll_arrow_height; - } else { - y_bottom = y + config.scroll_arrow_height; - } - SkPath path; - path.setFillType(SkPath::kWinding_FillType); - path.moveTo(SkIntToScalar(x), SkIntToScalar(y)); - path.lineTo(SkIntToScalar(x_left), SkIntToScalar(y_bottom)); - path.lineTo(SkIntToScalar(x_right), SkIntToScalar(y_bottom)); - path.lineTo(SkIntToScalar(x), SkIntToScalar(y)); - SkPaint paint; - paint.setStyle(SkPaint::kFill_Style); - paint.setAntiAlias(true); - paint.setColor(config.arrow_color); - canvas->DrawPath(path, paint); - } - - private: - // SubmenuView we were created for. - SubmenuView* host_; - - // Direction of the button. - bool is_up_; - - // Preferred height. - int pref_height_; - - DISALLOW_COPY_AND_ASSIGN(MenuScrollButton); -}; - -} // namespace - -// MenuScrollView -------------------------------------------------------------- - -// MenuScrollView is a viewport for the SubmenuView. It's reason to exist is so -// that ScrollRectToVisible works. -// -// NOTE: It is possible to use ScrollView directly (after making it deal with -// null scrollbars), but clicking on a child of ScrollView forces the window to -// become active, which we don't want. As we really only need a fraction of -// what ScrollView does, so we use a one off variant. - -class MenuScrollViewContainer::MenuScrollView : public View { - public: - explicit MenuScrollView(View* child) { - AddChildView(child); - } - - virtual void ScrollRectToVisible(const gfx::Rect& rect) override { - // NOTE: this assumes we only want to scroll in the y direction. - - // If the rect is already visible, do not scroll. - if (GetLocalBounds().Contains(rect)) - return; - - // Scroll just enough so that the rect is visible. - int dy = 0; - if (rect.bottom() > GetLocalBounds().bottom()) - dy = rect.bottom() - GetLocalBounds().bottom(); - else - dy = rect.y(); - - // Convert rect.y() to view's coordinates and make sure we don't show past - // the bottom of the view. - View* child = GetContents(); - child->SetY(-std::max(0, std::min( - child->GetPreferredSize().height() - this->height(), - dy - child->y()))); - } - - // Returns the contents, which is the SubmenuView. - View* GetContents() { - return child_at(0); - } - - private: - DISALLOW_COPY_AND_ASSIGN(MenuScrollView); -}; - -// MenuScrollViewContainer ---------------------------------------------------- - -MenuScrollViewContainer::MenuScrollViewContainer(SubmenuView* content_view) - : content_view_(content_view), - arrow_(BubbleBorder::NONE), - bubble_border_(NULL) { - scroll_up_button_ = new MenuScrollButton(content_view, true); - scroll_down_button_ = new MenuScrollButton(content_view, false); - AddChildView(scroll_up_button_); - AddChildView(scroll_down_button_); - - scroll_view_ = new MenuScrollView(content_view); - AddChildView(scroll_view_); - - arrow_ = BubbleBorderTypeFromAnchor( - content_view_->GetMenuItem()->GetMenuController()->GetAnchorPosition()); - - if (arrow_ != BubbleBorder::NONE) - CreateBubbleBorder(); - else - CreateDefaultBorder(); -} - -bool MenuScrollViewContainer::HasBubbleBorder() { - return arrow_ != BubbleBorder::NONE; -} - -void MenuScrollViewContainer::SetBubbleArrowOffset(int offset) { - DCHECK(HasBubbleBorder()); - bubble_border_->set_arrow_offset(offset); -} - -void MenuScrollViewContainer::OnPaintBackground(gfx::Canvas* canvas) { - if (background()) { - View::OnPaintBackground(canvas); - return; - } - - gfx::Rect bounds(0, 0, width(), height()); - NativeTheme::ExtraParams extra; - const MenuConfig& menu_config = content_view_->GetMenuItem()->GetMenuConfig(); - extra.menu_background.corner_radius = menu_config.corner_radius; - GetNativeTheme()->Paint(canvas->sk_canvas(), - NativeTheme::kMenuPopupBackground, NativeTheme::kNormal, bounds, extra); -} - -void MenuScrollViewContainer::Layout() { - gfx::Insets insets = GetInsets(); - int x = insets.left(); - int y = insets.top(); - int width = View::width() - insets.width(); - int content_height = height() - insets.height(); - if (!scroll_up_button_->visible()) { - scroll_view_->SetBounds(x, y, width, content_height); - scroll_view_->Layout(); - return; - } - - gfx::Size pref = scroll_up_button_->GetPreferredSize(); - scroll_up_button_->SetBounds(x, y, width, pref.height()); - content_height -= pref.height(); - - const int scroll_view_y = y + pref.height(); - - pref = scroll_down_button_->GetPreferredSize(); - scroll_down_button_->SetBounds(x, height() - pref.height() - insets.top(), - width, pref.height()); - content_height -= pref.height(); - - scroll_view_->SetBounds(x, scroll_view_y, width, content_height); - scroll_view_->Layout(); -} - -gfx::Size MenuScrollViewContainer::GetPreferredSize() const { - gfx::Size prefsize = scroll_view_->GetContents()->GetPreferredSize(); - gfx::Insets insets = GetInsets(); - prefsize.Enlarge(insets.width(), insets.height()); - return prefsize; -} - -void MenuScrollViewContainer::GetAccessibleState( - ui::AXViewState* state) { - // Get the name from the submenu view. - content_view_->GetAccessibleState(state); - - // Now change the role. - state->role = ui::AX_ROLE_MENU_BAR; - // Some AT (like NVDA) will not process focus events on menu item children - // unless a parent claims to be focused. - state->AddStateFlag(ui::AX_STATE_FOCUSED); -} - -void MenuScrollViewContainer::OnBoundsChanged( - const gfx::Rect& previous_bounds) { - gfx::Size content_pref = scroll_view_->GetContents()->GetPreferredSize(); - scroll_up_button_->SetVisible(content_pref.height() > height()); - scroll_down_button_->SetVisible(content_pref.height() > height()); - Layout(); -} - -void MenuScrollViewContainer::CreateDefaultBorder() { - arrow_ = BubbleBorder::NONE; - bubble_border_ = NULL; - - const MenuConfig& menu_config = - content_view_->GetMenuItem()->GetMenuConfig(); - - bool use_border = true; - int padding = menu_config.corner_radius > 0 ? - kBorderPaddingDueToRoundedCorners : 0; - -#if defined(USE_AURA) && !(defined(OS_LINUX) && !defined(OS_CHROMEOS)) - if (menu_config.native_theme == ui::NativeThemeAura::instance()) { - // In case of NativeThemeAura the border gets drawn with the shadow. - // Furthermore no additional padding is wanted. - use_border = false; - padding = 0; - } -#endif - - int top = menu_config.menu_vertical_border_size + padding; - int left = menu_config.menu_horizontal_border_size + padding; - int bottom = menu_config.menu_vertical_border_size + padding; - int right = menu_config.menu_horizontal_border_size + padding; - - if (use_border) { - SetBorder(views::Border::CreateBorderPainter( - new views::RoundRectPainter( - menu_config.native_theme->GetSystemColor( - ui::NativeTheme::kColorId_MenuBorderColor), - menu_config.corner_radius), - gfx::Insets(top, left, bottom, right))); - } else { - SetBorder(Border::CreateEmptyBorder(top, left, bottom, right)); - } -} - -void MenuScrollViewContainer::CreateBubbleBorder() { - bubble_border_ = new BubbleBorder(arrow_, - BubbleBorder::SMALL_SHADOW, - SK_ColorWHITE); - SetBorder(scoped_ptr<Border>(bubble_border_)); - set_background(new BubbleBackground(bubble_border_)); -} - -BubbleBorder::Arrow MenuScrollViewContainer::BubbleBorderTypeFromAnchor( - MenuAnchorPosition anchor) { - switch (anchor) { - case MENU_ANCHOR_BUBBLE_LEFT: - return BubbleBorder::RIGHT_CENTER; - case MENU_ANCHOR_BUBBLE_RIGHT: - return BubbleBorder::LEFT_CENTER; - case MENU_ANCHOR_BUBBLE_ABOVE: - return BubbleBorder::BOTTOM_CENTER; - case MENU_ANCHOR_BUBBLE_BELOW: - return BubbleBorder::TOP_CENTER; - default: - return BubbleBorder::NONE; - } -} - -} // namespace views
diff --git a/ui/views/controls/menu/menu_scroll_view_container.h b/ui/views/controls/menu/menu_scroll_view_container.h deleted file mode 100644 index fb0c2ff..0000000 --- a/ui/views/controls/menu/menu_scroll_view_container.h +++ /dev/null
@@ -1,75 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_MENU_MENU_SCROLL_VIEW_CONTAINER_H_ -#define UI_VIEWS_CONTROLS_MENU_MENU_SCROLL_VIEW_CONTAINER_H_ - -#include "ui/views/view.h" -#include "ui/views/bubble/bubble_border.h" -#include "ui/views/controls/menu/menu_types.h" - -namespace views { - -class SubmenuView; - -// MenuScrollViewContainer contains the SubmenuView (through a MenuScrollView) -// and two scroll buttons. The scroll buttons are only visible and enabled if -// the preferred height of the SubmenuView is bigger than our bounds. -class MenuScrollViewContainer : public View { - public: - explicit MenuScrollViewContainer(SubmenuView* content_view); - - // Returns the buttons for scrolling up/down. - View* scroll_down_button() const { return scroll_down_button_; } - View* scroll_up_button() const { return scroll_up_button_; } - - // External function to check if the bubble border is usd. - bool HasBubbleBorder(); - - // Offsets the Arrow from the default location. - void SetBubbleArrowOffset(int offset); - - // View overrides. - virtual void OnPaintBackground(gfx::Canvas* canvas) override; - virtual void Layout() override; - virtual gfx::Size GetPreferredSize() const override; - virtual void GetAccessibleState(ui::AXViewState* state) override; - - protected: - // View override. - virtual void OnBoundsChanged(const gfx::Rect& previous_bounds) override; - - private: - // Create the default border. - void CreateDefaultBorder(); - - // Create the bubble border. - void CreateBubbleBorder(); - - BubbleBorder::Arrow BubbleBorderTypeFromAnchor(MenuAnchorPosition anchor); - - class MenuScrollView; - - // The scroll buttons. - View* scroll_up_button_; - View* scroll_down_button_; - - // The scroll view. - MenuScrollView* scroll_view_; - - // The content view. - SubmenuView* content_view_; - - // If set the currently set border is a bubble border. - BubbleBorder::Arrow arrow_; - - // Weak reference to the currently set border. - BubbleBorder* bubble_border_; - - DISALLOW_COPY_AND_ASSIGN(MenuScrollViewContainer); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_MENU_MENU_SCROLL_VIEW_CONTAINER_H_
diff --git a/ui/views/controls/menu/menu_separator.h b/ui/views/controls/menu/menu_separator.h deleted file mode 100644 index feb629a..0000000 --- a/ui/views/controls/menu/menu_separator.h +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_MENU_MENU_SEPARATOR_H_ -#define UI_VIEWS_CONTROLS_MENU_MENU_SEPARATOR_H_ - -#include "base/compiler_specific.h" -#include "ui/base/models/menu_separator_types.h" -#include "ui/views/view.h" - -namespace views { - -class MenuItemView; - -class MenuSeparator : public View { - public: - MenuSeparator(MenuItemView* parent, ui::MenuSeparatorType type) - : type_(type), - parent_menu_item_(parent) {} - - // View overrides. - virtual void OnPaint(gfx::Canvas* canvas) override; - virtual gfx::Size GetPreferredSize() const override; - - private: - // Gets the bounds where the separator should be painted. - gfx::Rect GetPaintBounds(); - - void OnPaintAura(gfx::Canvas* canvas); - - // The type of the separator. - const ui::MenuSeparatorType type_; - - // Our parent. - MenuItemView* parent_menu_item_; - - DISALLOW_COPY_AND_ASSIGN(MenuSeparator); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_MENU_MENU_SEPARATOR_H_
diff --git a/ui/views/controls/menu/menu_separator_views.cc b/ui/views/controls/menu/menu_separator_views.cc deleted file mode 100644 index cf5a8fb..0000000 --- a/ui/views/controls/menu/menu_separator_views.cc +++ /dev/null
@@ -1,72 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/menu/menu_separator.h" - -#include "third_party/skia/include/core/SkColor.h" -#include "ui/gfx/canvas.h" -#include "ui/native_theme/native_theme.h" -#include "ui/views/controls/menu/menu_config.h" -#include "ui/views/controls/menu/menu_item_view.h" - -namespace { - -const int kSeparatorHeight = 1; - -} // namespace - -namespace views { - -#if !defined(OS_WIN) -void MenuSeparator::OnPaint(gfx::Canvas* canvas) { - OnPaintAura(canvas); -} -#endif - -gfx::Size MenuSeparator::GetPreferredSize() const { - const MenuConfig& menu_config = parent_menu_item_->GetMenuConfig(); - int height = menu_config.separator_height; - switch(type_) { - case ui::SPACING_SEPARATOR: - height = menu_config.separator_spacing_height; - break; - case ui::LOWER_SEPARATOR: - height = menu_config.separator_lower_height; - break; - case ui::UPPER_SEPARATOR: - height = menu_config.separator_upper_height; - break; - default: - height = menu_config.separator_height; - break; - } - return gfx::Size(10, // Just in case we're the only item in a menu. - height); -} - -gfx::Rect MenuSeparator::GetPaintBounds() { - int pos = 0; - switch (type_) { - case ui::LOWER_SEPARATOR: - pos = height() - kSeparatorHeight; - break; - case ui::SPACING_SEPARATOR: - return gfx::Rect(); - case ui::UPPER_SEPARATOR: - break; - default: - pos = height() / 2; - break; - } - - return gfx::Rect(0, pos, width(), kSeparatorHeight); -} - -void MenuSeparator::OnPaintAura(gfx::Canvas* canvas) { - canvas->FillRect(GetPaintBounds(), - GetNativeTheme()->GetSystemColor( - ui::NativeTheme::kColorId_MenuSeparatorColor)); -} - -} // namespace views
diff --git a/ui/views/controls/menu/menu_separator_win.cc b/ui/views/controls/menu/menu_separator_win.cc deleted file mode 100644 index 98a70ba..0000000 --- a/ui/views/controls/menu/menu_separator_win.cc +++ /dev/null
@@ -1,60 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/menu/menu_separator.h" - -#include <windows.h> -#include <uxtheme.h> -#include <Vssym32.h> - -#include "ui/gfx/canvas.h" -#include "ui/gfx/rect.h" -#include "ui/gfx/win/dpi.h" -#include "ui/native_theme/native_theme.h" -#include "ui/native_theme/native_theme_aura.h" -#include "ui/views/controls/menu/menu_config.h" -#include "ui/views/controls/menu/menu_item_view.h" - -namespace views { - -void MenuSeparator::OnPaint(gfx::Canvas* canvas) { - const MenuConfig& config = parent_menu_item_->GetMenuConfig(); - - if (config.native_theme == ui::NativeThemeAura::instance()) { - OnPaintAura(canvas); - return; - } - - gfx::Rect separator_bounds = GetPaintBounds(); - if (config.render_gutter) { - // If render_gutter is true, we're on Vista and need to render the - // gutter, then indent the separator from the gutter. - gfx::Rect gutter_bounds(MenuItemView::label_start() - - config.gutter_to_label - config.gutter_width, 0, - config.gutter_width, height()); - ui::NativeTheme::ExtraParams extra; - config.native_theme->Paint( - canvas->sk_canvas(), ui::NativeTheme::kMenuPopupGutter, - ui::NativeTheme::kNormal, gutter_bounds, extra); - separator_bounds.set_x(gutter_bounds.x() + config.gutter_width); - } - - ui::NativeTheme::ExtraParams extra; - extra.menu_separator.has_gutter = config.render_gutter; - - // Hack to get the separator to display correctly on Windows where we may - // have fractional scales. We move the separator 1 pixel down to ensure that - // it falls within the clipping rect which is scaled up. - float device_scale = gfx::win::GetDeviceScaleFactor(); - bool is_fractional_scale = - (device_scale - static_cast<int>(device_scale) != 0); - if (is_fractional_scale && separator_bounds.y() == 0) - separator_bounds.set_y(1); - - config.native_theme->Paint( - canvas->sk_canvas(), ui::NativeTheme::kMenuPopupSeparator, - ui::NativeTheme::kNormal, separator_bounds, extra); -} - -} // namespace views
diff --git a/ui/views/controls/menu/menu_types.h b/ui/views/controls/menu/menu_types.h deleted file mode 100644 index 160dd5a..0000000 --- a/ui/views/controls/menu/menu_types.h +++ /dev/null
@@ -1,26 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_MENU_MENU_TYPES_H_ -#define UI_VIEWS_CONTROLS_MENU_MENU_TYPES_H_ - -namespace views { - -// Where a popup menu should be anchored to for non-RTL languages. The opposite -// position will be used if base::i18n:IsRTL() is true. The BUBBLE flags are -// used when the menu should get enclosed by a bubble. Note that BUBBLE flags -// should only be used with menus which have no children. -enum MenuAnchorPosition { - MENU_ANCHOR_TOPLEFT, - MENU_ANCHOR_TOPRIGHT, - MENU_ANCHOR_BOTTOMCENTER, - MENU_ANCHOR_BUBBLE_LEFT, - MENU_ANCHOR_BUBBLE_RIGHT, - MENU_ANCHOR_BUBBLE_ABOVE, - MENU_ANCHOR_BUBBLE_BELOW -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_MENU_MENU_TYPES_H_
diff --git a/ui/views/controls/menu/menu_wrapper.h b/ui/views/controls/menu/menu_wrapper.h deleted file mode 100644 index 39a6fc5..0000000 --- a/ui/views/controls/menu/menu_wrapper.h +++ /dev/null
@@ -1,74 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_MENU_MENU_WRAPPER_H_ -#define UI_VIEWS_CONTROLS_MENU_MENU_WRAPPER_H_ - -#include "ui/gfx/native_widget_types.h" -#include "ui/views/views_export.h" - -namespace gfx { -class Point; -} - -namespace ui { -class MenuModel; -} - -namespace views { - -class MenuInsertionDelegateWin; -class MenuListener; - -// An interface that wraps an object that implements a menu. -class VIEWS_EXPORT MenuWrapper { - public: - // All of the possible actions that can result from RunMenuAt. - enum MenuAction { - MENU_ACTION_NONE, // Menu cancelled, or never opened. - MENU_ACTION_SELECTED, // An item was selected. - MENU_ACTION_PREVIOUS, // User wants to navigate to the previous menu. - MENU_ACTION_NEXT, // User wants to navigate to the next menu. - }; - - virtual ~MenuWrapper() {} - - // Creates the appropriate instance of this wrapper for the current platform. - static MenuWrapper* CreateWrapper(ui::MenuModel* model); - - // Runs the menu at the specified point. This blocks until done. - virtual void RunMenuAt(const gfx::Point& point, int alignment) = 0; - - // Cancels the active menu. - virtual void CancelMenu() = 0; - - // Called when the model supplying data to this menu has changed, and the menu - // must be rebuilt. - virtual void Rebuild(MenuInsertionDelegateWin* delegate) = 0; - - // Called when the states of the items in the menu must be updated from the - // model. - virtual void UpdateStates() = 0; - - // Retrieve a native menu handle. - virtual HMENU GetNativeMenu() const = 0; - - // Get the result of the last call to RunMenuAt to determine whether an - // item was selected, the user navigated to a next or previous menu, or - // nothing. - virtual MenuAction GetMenuAction() const = 0; - - // Add a listener to receive a callback when the menu opens. - virtual void AddMenuListener(MenuListener* listener) = 0; - - // Remove a menu listener. - virtual void RemoveMenuListener(MenuListener* listener) = 0; - - // Sets the minimum width of the menu. - virtual void SetMinimumWidth(int width) = 0; -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_MENU_MENU_WRAPPER_H_
diff --git a/ui/views/controls/menu/native_menu_win.cc b/ui/views/controls/menu/native_menu_win.cc deleted file mode 100644 index a3930f2..0000000 --- a/ui/views/controls/menu/native_menu_win.cc +++ /dev/null
@@ -1,760 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/menu/native_menu_win.h" - -#include <Windowsx.h> - -#include "base/bind.h" -#include "base/logging.h" -#include "base/message_loop/message_loop.h" -#include "base/stl_util.h" -#include "base/strings/string_util.h" -#include "base/win/wrapped_window_proc.h" -#include "ui/base/accelerators/accelerator.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/base/l10n/l10n_util_win.h" -#include "ui/base/models/menu_model.h" -#include "ui/events/keycodes/keyboard_codes.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/font_list.h" -#include "ui/gfx/geometry/rect.h" -#include "ui/gfx/image/image.h" -#include "ui/gfx/image/image_skia.h" -#include "ui/gfx/text_utils.h" -#include "ui/gfx/win/hwnd_util.h" -#include "ui/native_theme/native_theme.h" -#include "ui/native_theme/native_theme_win.h" -#include "ui/views/controls/menu/menu_2.h" -#include "ui/views/controls/menu/menu_config.h" -#include "ui/views/controls/menu/menu_insertion_delegate_win.h" -#include "ui/views/controls/menu/menu_listener.h" -#include "ui/views/layout/layout_constants.h" - -using ui::NativeTheme; - -namespace views { - -// The width of an icon, including the pixels between the icon and -// the item label. -static const int kIconWidth = 23; -// Margins between the top of the item and the label. -static const int kItemTopMargin = 3; -// Margins between the bottom of the item and the label. -static const int kItemBottomMargin = 4; -// Margins between the left of the item and the icon. -static const int kItemLeftMargin = 4; -// The width for displaying the sub-menu arrow. -static const int kArrowWidth = 10; - -struct NativeMenuWin::ItemData { - // The Windows API requires that whoever creates the menus must own the - // strings used for labels, and keep them around for the lifetime of the - // created menu. So be it. - base::string16 label; - - // Someone needs to own submenus, it may as well be us. - scoped_ptr<Menu2> submenu; - - // We need a pointer back to the containing menu in various circumstances. - NativeMenuWin* native_menu_win; - - // The index of the item within the menu's model. - int model_index; -}; - -// Returns the NativeMenuWin for a particular HMENU. -static NativeMenuWin* GetNativeMenuWinFromHMENU(HMENU hmenu) { - MENUINFO mi = {0}; - mi.cbSize = sizeof(mi); - mi.fMask = MIM_MENUDATA | MIM_STYLE; - GetMenuInfo(hmenu, &mi); - return reinterpret_cast<NativeMenuWin*>(mi.dwMenuData); -} - -// A window that receives messages from Windows relevant to the native menu -// structure we have constructed in NativeMenuWin. -class NativeMenuWin::MenuHostWindow { - public: - explicit MenuHostWindow(NativeMenuWin* parent) : parent_(parent) { - RegisterClass(); - hwnd_ = CreateWindowEx(l10n_util::GetExtendedStyles(), kWindowClassName, - L"", 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, NULL, NULL); - gfx::CheckWindowCreated(hwnd_); - gfx::SetWindowUserData(hwnd_, this); - } - - ~MenuHostWindow() { - DestroyWindow(hwnd_); - } - - HWND hwnd() const { return hwnd_; } - - private: - static const wchar_t* kWindowClassName; - - void RegisterClass() { - static bool registered = false; - if (registered) - return; - - WNDCLASSEX window_class; - base::win::InitializeWindowClass( - kWindowClassName, - &base::win::WrappedWindowProc<MenuHostWindowProc>, - CS_DBLCLKS, - 0, - 0, - NULL, - reinterpret_cast<HBRUSH>(COLOR_WINDOW+1), - NULL, - NULL, - NULL, - &window_class); - ATOM clazz = RegisterClassEx(&window_class); - CHECK(clazz); - registered = true; - } - - // Converts the WPARAM value passed to WM_MENUSELECT into an index - // corresponding to the menu item that was selected. - int GetMenuItemIndexFromWPARAM(HMENU menu, WPARAM w_param) const { - int count = GetMenuItemCount(menu); - // For normal command menu items, Windows passes a command id as the LOWORD - // of WPARAM for WM_MENUSELECT. We need to walk forward through the menu - // items to find an item with a matching ID. Ugh! - for (int i = 0; i < count; ++i) { - MENUITEMINFO mii = {0}; - mii.cbSize = sizeof(mii); - mii.fMask = MIIM_ID; - GetMenuItemInfo(menu, i, MF_BYPOSITION, &mii); - if (mii.wID == w_param) - return i; - } - // If we didn't find a matching command ID, this means a submenu has been - // selected instead, and rather than passing a command ID in - // LOWORD(w_param), Windows has actually passed us a position, so we just - // return it. - return w_param; - } - - NativeMenuWin::ItemData* GetItemData(ULONG_PTR item_data) { - return reinterpret_cast<NativeMenuWin::ItemData*>(item_data); - } - - // Called when the user selects a specific item. - void OnMenuCommand(int position, HMENU menu) { - NativeMenuWin* menu_win = GetNativeMenuWinFromHMENU(menu); - ui::MenuModel* model = menu_win->model_; - NativeMenuWin* root_menu = menu_win; - while (root_menu->parent_) - root_menu = root_menu->parent_; - - // Only notify the model if it didn't already send out notification. - // See comment in MenuMessageHook for details. - if (root_menu->menu_action_ == MenuWrapper::MENU_ACTION_NONE) - model->ActivatedAt(position); - } - - // Called as the user moves their mouse or arrows through the contents of the - // menu. - void OnMenuSelect(WPARAM w_param, HMENU menu) { - if (!menu) - return; // menu is null when closing on XP. - - int position = GetMenuItemIndexFromWPARAM(menu, w_param); - if (position >= 0) - GetNativeMenuWinFromHMENU(menu)->model_->HighlightChangedTo(position); - } - - // Called by Windows to measure the size of an owner-drawn menu item. - void OnMeasureItem(WPARAM w_param, MEASUREITEMSTRUCT* measure_item_struct) { - NativeMenuWin::ItemData* data = GetItemData(measure_item_struct->itemData); - if (data) { - gfx::FontList font_list; - measure_item_struct->itemWidth = - gfx::GetStringWidth(data->label, font_list) + - kIconWidth + kItemLeftMargin + views::kItemLabelSpacing - - GetSystemMetrics(SM_CXMENUCHECK); - if (data->submenu.get()) - measure_item_struct->itemWidth += kArrowWidth; - // If the label contains an accelerator, make room for tab. - if (data->label.find(L'\t') != base::string16::npos) - measure_item_struct->itemWidth += gfx::GetStringWidth(L" ", font_list); - measure_item_struct->itemHeight = - font_list.GetHeight() + kItemBottomMargin + kItemTopMargin; - } else { - // Measure separator size. - measure_item_struct->itemHeight = GetSystemMetrics(SM_CYMENU) / 2; - measure_item_struct->itemWidth = 0; - } - } - - // Called by Windows to paint an owner-drawn menu item. - void OnDrawItem(UINT w_param, DRAWITEMSTRUCT* draw_item_struct) { - HDC dc = draw_item_struct->hDC; - COLORREF prev_bg_color, prev_text_color; - - // Set background color and text color - if (draw_item_struct->itemState & ODS_SELECTED) { - prev_bg_color = SetBkColor(dc, GetSysColor(COLOR_HIGHLIGHT)); - prev_text_color = SetTextColor(dc, GetSysColor(COLOR_HIGHLIGHTTEXT)); - } else { - prev_bg_color = SetBkColor(dc, GetSysColor(COLOR_MENU)); - if (draw_item_struct->itemState & ODS_DISABLED) - prev_text_color = SetTextColor(dc, GetSysColor(COLOR_GRAYTEXT)); - else - prev_text_color = SetTextColor(dc, GetSysColor(COLOR_MENUTEXT)); - } - - if (draw_item_struct->itemData) { - NativeMenuWin::ItemData* data = GetItemData(draw_item_struct->itemData); - // Draw the background. - HBRUSH hbr = CreateSolidBrush(GetBkColor(dc)); - FillRect(dc, &draw_item_struct->rcItem, hbr); - DeleteObject(hbr); - - // Draw the label. - RECT rect = draw_item_struct->rcItem; - rect.top += kItemTopMargin; - // Should we add kIconWidth only when icon.width() != 0 ? - rect.left += kItemLeftMargin + kIconWidth; - rect.right -= views::kItemLabelSpacing; - UINT format = DT_TOP | DT_SINGLELINE; - // Check whether the mnemonics should be underlined. - BOOL underline_mnemonics; - SystemParametersInfo(SPI_GETKEYBOARDCUES, 0, &underline_mnemonics, 0); - if (!underline_mnemonics) - format |= DT_HIDEPREFIX; - gfx::FontList font_list; - HGDIOBJ old_font = static_cast<HFONT>( - SelectObject(dc, font_list.GetPrimaryFont().GetNativeFont())); - - // If an accelerator is specified (with a tab delimiting the rest of the - // label from the accelerator), we have to justify the fist part on the - // left and the accelerator on the right. - // TODO(jungshik): This will break in RTL UI. Currently, he/ar use the - // window system UI font and will not hit here. - base::string16 label = data->label; - base::string16 accel; - base::string16::size_type tab_pos = label.find(L'\t'); - if (tab_pos != base::string16::npos) { - accel = label.substr(tab_pos); - label = label.substr(0, tab_pos); - } - DrawTextEx(dc, const_cast<wchar_t*>(label.data()), - static_cast<int>(label.size()), &rect, format | DT_LEFT, NULL); - if (!accel.empty()) - DrawTextEx(dc, const_cast<wchar_t*>(accel.data()), - static_cast<int>(accel.size()), &rect, - format | DT_RIGHT, NULL); - SelectObject(dc, old_font); - - ui::MenuModel::ItemType type = - data->native_menu_win->model_->GetTypeAt(data->model_index); - - // Draw the icon after the label, otherwise it would be covered - // by the label. - gfx::Image icon; - if (data->native_menu_win->model_->GetIconAt(data->model_index, &icon)) { - // We currently don't support items with both icons and checkboxes. - const gfx::ImageSkia* skia_icon = icon.ToImageSkia(); - DCHECK(type != ui::MenuModel::TYPE_CHECK); - gfx::Canvas canvas( - skia_icon->GetRepresentation(1.0f), - false); - skia::DrawToNativeContext( - canvas.sk_canvas(), dc, - draw_item_struct->rcItem.left + kItemLeftMargin, - draw_item_struct->rcItem.top + (draw_item_struct->rcItem.bottom - - draw_item_struct->rcItem.top - skia_icon->height()) / 2, NULL); - } else if (type == ui::MenuModel::TYPE_CHECK && - data->native_menu_win->model_->IsItemCheckedAt( - data->model_index)) { - // Manually render a checkbox. - ui::NativeThemeWin* native_theme = ui::NativeThemeWin::instance(); - const MenuConfig& config = MenuConfig::instance(native_theme); - NativeTheme::State state; - if (draw_item_struct->itemState & ODS_DISABLED) { - state = NativeTheme::kDisabled; - } else { - state = draw_item_struct->itemState & ODS_SELECTED ? - NativeTheme::kHovered : NativeTheme::kNormal; - } - gfx::Canvas canvas(gfx::Size(config.check_width, config.check_height), - 1.0f, - false); - NativeTheme::ExtraParams extra; - extra.menu_check.is_radio = false; - gfx::Rect bounds(0, 0, config.check_width, config.check_height); - - // Draw the background and the check. - native_theme->Paint( - canvas.sk_canvas(), NativeTheme::kMenuCheckBackground, - state, bounds, extra); - native_theme->Paint( - canvas.sk_canvas(), NativeTheme::kMenuCheck, state, bounds, extra); - - // Draw checkbox to menu. - skia::DrawToNativeContext(canvas.sk_canvas(), dc, - draw_item_struct->rcItem.left + kItemLeftMargin, - draw_item_struct->rcItem.top + (draw_item_struct->rcItem.bottom - - draw_item_struct->rcItem.top - config.check_height) / 2, NULL); - } - - } else { - // Draw the separator - draw_item_struct->rcItem.top += - (draw_item_struct->rcItem.bottom - draw_item_struct->rcItem.top) / 3; - DrawEdge(dc, &draw_item_struct->rcItem, EDGE_ETCHED, BF_TOP); - } - - SetBkColor(dc, prev_bg_color); - SetTextColor(dc, prev_text_color); - } - - bool ProcessWindowMessage(HWND window, - UINT message, - WPARAM w_param, - LPARAM l_param, - LRESULT* l_result) { - switch (message) { - case WM_MENUCOMMAND: - OnMenuCommand(w_param, reinterpret_cast<HMENU>(l_param)); - *l_result = 0; - return true; - case WM_MENUSELECT: - OnMenuSelect(LOWORD(w_param), reinterpret_cast<HMENU>(l_param)); - *l_result = 0; - return true; - case WM_MEASUREITEM: - OnMeasureItem(w_param, reinterpret_cast<MEASUREITEMSTRUCT*>(l_param)); - *l_result = 0; - return true; - case WM_DRAWITEM: - OnDrawItem(w_param, reinterpret_cast<DRAWITEMSTRUCT*>(l_param)); - *l_result = 0; - return true; - // TODO(beng): bring over owner draw from old menu system. - } - return false; - } - - static LRESULT CALLBACK MenuHostWindowProc(HWND window, - UINT message, - WPARAM w_param, - LPARAM l_param) { - MenuHostWindow* host = - reinterpret_cast<MenuHostWindow*>(gfx::GetWindowUserData(window)); - // host is null during initial construction. - LRESULT l_result = 0; - if (!host || !host->ProcessWindowMessage(window, message, w_param, l_param, - &l_result)) { - return DefWindowProc(window, message, w_param, l_param); - } - return l_result; - } - - HWND hwnd_; - NativeMenuWin* parent_; - - DISALLOW_COPY_AND_ASSIGN(MenuHostWindow); -}; - -struct NativeMenuWin::HighlightedMenuItemInfo { - HighlightedMenuItemInfo() - : has_parent(false), - has_submenu(false), - menu(NULL), - position(-1) { - } - - bool has_parent; - bool has_submenu; - - // The menu and position. These are only set for non-disabled menu items. - NativeMenuWin* menu; - int position; -}; - -// static -const wchar_t* NativeMenuWin::MenuHostWindow::kWindowClassName = - L"ViewsMenuHostWindow"; - -//////////////////////////////////////////////////////////////////////////////// -// NativeMenuWin, public: - -NativeMenuWin::NativeMenuWin(ui::MenuModel* model, HWND system_menu_for) - : model_(model), - menu_(NULL), - owner_draw_(l10n_util::NeedOverrideDefaultUIFont(NULL, NULL) && - !system_menu_for), - system_menu_for_(system_menu_for), - first_item_index_(0), - menu_action_(MENU_ACTION_NONE), - menu_to_select_(NULL), - position_to_select_(-1), - menu_to_select_factory_(this), - parent_(NULL), - destroyed_flag_(NULL) { -} - -NativeMenuWin::~NativeMenuWin() { - if (destroyed_flag_) - *destroyed_flag_ = true; - STLDeleteContainerPointers(items_.begin(), items_.end()); - DestroyMenu(menu_); -} - -//////////////////////////////////////////////////////////////////////////////// -// NativeMenuWin, MenuWrapper implementation: - -void NativeMenuWin::RunMenuAt(const gfx::Point& point, int alignment) { - CreateHostWindow(); - UpdateStates(); - UINT flags = TPM_LEFTBUTTON | TPM_RIGHTBUTTON | TPM_RECURSE; - flags |= GetAlignmentFlags(alignment); - menu_action_ = MENU_ACTION_NONE; - - // Set a hook function so we can listen for keyboard events while the - // menu is open, and store a pointer to this object in a static - // variable so the hook has access to it (ugly, but it's the - // only way). - open_native_menu_win_ = this; - HHOOK hhook = SetWindowsHookEx(WH_MSGFILTER, MenuMessageHook, - GetModuleHandle(NULL), ::GetCurrentThreadId()); - - // Mark that any registered listeners have not been called for this particular - // opening of the menu. - listeners_called_ = false; - - // Command dispatch is done through WM_MENUCOMMAND, handled by the host - // window. - menu_to_select_ = NULL; - position_to_select_ = -1; - menu_to_select_factory_.InvalidateWeakPtrs(); - bool destroyed = false; - destroyed_flag_ = &destroyed; - model_->MenuWillShow(); - TrackPopupMenu(menu_, flags, point.x(), point.y(), 0, host_window_->hwnd(), - NULL); - UnhookWindowsHookEx(hhook); - open_native_menu_win_ = NULL; - if (destroyed) - return; - destroyed_flag_ = NULL; - if (menu_to_select_) { - // Folks aren't too happy if we notify immediately. In particular, notifying - // the delegate can cause destruction leaving the stack in a weird - // state. Instead post a task, then notify. This mirrors what WM_MENUCOMMAND - // does. - menu_to_select_factory_.InvalidateWeakPtrs(); - base::MessageLoop::current()->PostTask( - FROM_HERE, - base::Bind(&NativeMenuWin::DelayedSelect, - menu_to_select_factory_.GetWeakPtr())); - menu_action_ = MENU_ACTION_SELECTED; - } - // Send MenuClosed after we schedule the select, otherwise MenuClosed is - // processed after the select (MenuClosed posts a delayed task too). - model_->MenuClosed(); -} - -void NativeMenuWin::CancelMenu() { - EndMenu(); -} - -void NativeMenuWin::Rebuild(MenuInsertionDelegateWin* delegate) { - ResetNativeMenu(); - items_.clear(); - - owner_draw_ = model_->HasIcons() || owner_draw_; - first_item_index_ = delegate ? delegate->GetInsertionIndex(menu_) : 0; - for (int menu_index = first_item_index_; - menu_index < first_item_index_ + model_->GetItemCount(); ++menu_index) { - int model_index = menu_index - first_item_index_; - if (model_->GetTypeAt(model_index) == ui::MenuModel::TYPE_SEPARATOR) - AddSeparatorItemAt(menu_index, model_index); - else - AddMenuItemAt(menu_index, model_index); - } -} - -void NativeMenuWin::UpdateStates() { - // A depth-first walk of the menu items, updating states. - int model_index = 0; - std::vector<ItemData*>::const_iterator it; - for (it = items_.begin(); it != items_.end(); ++it, ++model_index) { - int menu_index = model_index + first_item_index_; - SetMenuItemState(menu_index, model_->IsEnabledAt(model_index), - model_->IsItemCheckedAt(model_index), false); - if (model_->IsItemDynamicAt(model_index)) { - // TODO(atwilson): Update the icon as well (http://crbug.com/66508). - SetMenuItemLabel(menu_index, model_index, - model_->GetLabelAt(model_index)); - } - Menu2* submenu = (*it)->submenu.get(); - if (submenu) - submenu->UpdateStates(); - } -} - -HMENU NativeMenuWin::GetNativeMenu() const { - return menu_; -} - -NativeMenuWin::MenuAction NativeMenuWin::GetMenuAction() const { - return menu_action_; -} - -void NativeMenuWin::AddMenuListener(MenuListener* listener) { - listeners_.AddObserver(listener); -} - -void NativeMenuWin::RemoveMenuListener(MenuListener* listener) { - listeners_.RemoveObserver(listener); -} - -void NativeMenuWin::SetMinimumWidth(int width) { - NOTIMPLEMENTED(); -} - -//////////////////////////////////////////////////////////////////////////////// -// NativeMenuWin, private: - -// static -NativeMenuWin* NativeMenuWin::open_native_menu_win_ = NULL; - -void NativeMenuWin::DelayedSelect() { - if (menu_to_select_) - menu_to_select_->model_->ActivatedAt(position_to_select_); -} - -// static -bool NativeMenuWin::GetHighlightedMenuItemInfo( - HMENU menu, - HighlightedMenuItemInfo* info) { - for (int i = 0; i < ::GetMenuItemCount(menu); i++) { - UINT state = ::GetMenuState(menu, i, MF_BYPOSITION); - if (state & MF_HILITE) { - if (state & MF_POPUP) { - HMENU submenu = GetSubMenu(menu, i); - if (GetHighlightedMenuItemInfo(submenu, info)) - info->has_parent = true; - else - info->has_submenu = true; - } else if (!(state & MF_SEPARATOR) && !(state & MF_DISABLED)) { - info->menu = GetNativeMenuWinFromHMENU(menu); - info->position = i; - } - return true; - } - } - return false; -} - -// static -LRESULT CALLBACK NativeMenuWin::MenuMessageHook( - int n_code, WPARAM w_param, LPARAM l_param) { - LRESULT result = CallNextHookEx(NULL, n_code, w_param, l_param); - - NativeMenuWin* this_ptr = open_native_menu_win_; - if (!this_ptr) - return result; - - // The first time this hook is called, that means the menu has successfully - // opened, so call the callback function on all of our listeners. - if (!this_ptr->listeners_called_) { - FOR_EACH_OBSERVER(MenuListener, this_ptr->listeners_, OnMenuOpened()); - this_ptr->listeners_called_ = true; - } - - MSG* msg = reinterpret_cast<MSG*>(l_param); - if (msg->message == WM_LBUTTONUP || msg->message == WM_RBUTTONUP) { - HighlightedMenuItemInfo info; - if (GetHighlightedMenuItemInfo(this_ptr->menu_, &info) && info.menu) { - // It appears that when running a menu by way of TrackPopupMenu(Ex) win32 - // gets confused if the underlying window paints itself. As its very easy - // for the underlying window to repaint itself (especially since some menu - // items trigger painting of the tabstrip on mouse over) we have this - // workaround. When the mouse is released on a menu item we remember the - // menu item and end the menu. When the nested message loop returns we - // schedule a task to notify the model. It's still possible to get a - // WM_MENUCOMMAND, so we have to be careful that we don't notify the model - // twice. - this_ptr->menu_to_select_ = info.menu; - this_ptr->position_to_select_ = info.position; - EndMenu(); - } - } else if (msg->message == WM_KEYDOWN) { - HighlightedMenuItemInfo info; - if (GetHighlightedMenuItemInfo(this_ptr->menu_, &info)) { - if (msg->wParam == VK_LEFT && !info.has_parent) { - this_ptr->menu_action_ = MENU_ACTION_PREVIOUS; - ::EndMenu(); - } else if (msg->wParam == VK_RIGHT && !info.has_parent && - !info.has_submenu) { - this_ptr->menu_action_ = MENU_ACTION_NEXT; - ::EndMenu(); - } - } - } - - return result; -} - -bool NativeMenuWin::IsSeparatorItemAt(int menu_index) const { - MENUITEMINFO mii = {0}; - mii.cbSize = sizeof(mii); - mii.fMask = MIIM_FTYPE; - GetMenuItemInfo(menu_, menu_index, MF_BYPOSITION, &mii); - return !!(mii.fType & MF_SEPARATOR); -} - -void NativeMenuWin::AddMenuItemAt(int menu_index, int model_index) { - MENUITEMINFO mii = {0}; - mii.cbSize = sizeof(mii); - mii.fMask = MIIM_FTYPE | MIIM_ID | MIIM_DATA; - if (!owner_draw_) - mii.fType = MFT_STRING; - else - mii.fType = MFT_OWNERDRAW; - - ItemData* item_data = new ItemData; - item_data->label = base::string16(); - ui::MenuModel::ItemType type = model_->GetTypeAt(model_index); - if (type == ui::MenuModel::TYPE_SUBMENU) { - item_data->submenu.reset(new Menu2(model_->GetSubmenuModelAt(model_index))); - mii.fMask |= MIIM_SUBMENU; - mii.hSubMenu = item_data->submenu->GetNativeMenu(); - GetNativeMenuWinFromHMENU(mii.hSubMenu)->parent_ = this; - } else { - if (type == ui::MenuModel::TYPE_RADIO) - mii.fType |= MFT_RADIOCHECK; - mii.wID = model_->GetCommandIdAt(model_index); - } - item_data->native_menu_win = this; - item_data->model_index = model_index; - items_.insert(items_.begin() + model_index, item_data); - mii.dwItemData = reinterpret_cast<ULONG_PTR>(item_data); - UpdateMenuItemInfoForString(&mii, model_index, - model_->GetLabelAt(model_index)); - InsertMenuItem(menu_, menu_index, TRUE, &mii); -} - -void NativeMenuWin::AddSeparatorItemAt(int menu_index, int model_index) { - MENUITEMINFO mii = {0}; - mii.cbSize = sizeof(mii); - mii.fMask = MIIM_FTYPE; - mii.fType = MFT_SEPARATOR; - // Insert a dummy entry into our label list so we can index directly into it - // using item indices if need be. - items_.insert(items_.begin() + model_index, new ItemData); - InsertMenuItem(menu_, menu_index, TRUE, &mii); -} - -void NativeMenuWin::SetMenuItemState(int menu_index, bool enabled, bool checked, - bool is_default) { - if (IsSeparatorItemAt(menu_index)) - return; - - UINT state = enabled ? MFS_ENABLED : MFS_DISABLED; - if (checked) - state |= MFS_CHECKED; - if (is_default) - state |= MFS_DEFAULT; - - MENUITEMINFO mii = {0}; - mii.cbSize = sizeof(mii); - mii.fMask = MIIM_STATE; - mii.fState = state; - SetMenuItemInfo(menu_, menu_index, MF_BYPOSITION, &mii); -} - -void NativeMenuWin::SetMenuItemLabel(int menu_index, - int model_index, - const base::string16& label) { - if (IsSeparatorItemAt(menu_index)) - return; - - MENUITEMINFO mii = {0}; - mii.cbSize = sizeof(mii); - UpdateMenuItemInfoForString(&mii, model_index, label); - SetMenuItemInfo(menu_, menu_index, MF_BYPOSITION, &mii); -} - -void NativeMenuWin::UpdateMenuItemInfoForString(MENUITEMINFO* mii, - int model_index, - const base::string16& label) { - base::string16 formatted = label; - ui::MenuModel::ItemType type = model_->GetTypeAt(model_index); - // Strip out any tabs, otherwise they get interpreted as accelerators and can - // lead to weird behavior. - ReplaceSubstringsAfterOffset(&formatted, 0, L"\t", L" "); - if (type != ui::MenuModel::TYPE_SUBMENU) { - // Add accelerator details to the label if provided. - ui::Accelerator accelerator(ui::VKEY_UNKNOWN, ui::EF_NONE); - if (model_->GetAcceleratorAt(model_index, &accelerator)) { - formatted += L"\t"; - formatted += accelerator.GetShortcutText(); - } - } - - // Update the owned string, since Windows will want us to keep this new - // version around. - items_[model_index]->label = formatted; - - // Give Windows a pointer to the label string. - mii->fMask |= MIIM_STRING; - mii->dwTypeData = - const_cast<wchar_t*>(items_[model_index]->label.c_str()); -} - -UINT NativeMenuWin::GetAlignmentFlags(int alignment) const { - UINT alignment_flags = TPM_TOPALIGN; - if (alignment == Menu2::ALIGN_TOPLEFT) - alignment_flags |= TPM_LEFTALIGN; - else if (alignment == Menu2::ALIGN_TOPRIGHT) - alignment_flags |= TPM_RIGHTALIGN; - return alignment_flags; -} - -void NativeMenuWin::ResetNativeMenu() { - if (IsWindow(system_menu_for_)) { - if (menu_) - GetSystemMenu(system_menu_for_, TRUE); - menu_ = GetSystemMenu(system_menu_for_, FALSE); - } else { - if (menu_) - DestroyMenu(menu_); - menu_ = CreatePopupMenu(); - // Rather than relying on the return value of TrackPopupMenuEx, which is - // always a command identifier, instead we tell the menu to notify us via - // our host window and the WM_MENUCOMMAND message. - MENUINFO mi = {0}; - mi.cbSize = sizeof(mi); - mi.fMask = MIM_STYLE | MIM_MENUDATA; - mi.dwStyle = MNS_NOTIFYBYPOS; - mi.dwMenuData = reinterpret_cast<ULONG_PTR>(this); - SetMenuInfo(menu_, &mi); - } -} - -void NativeMenuWin::CreateHostWindow() { - // This only gets called from RunMenuAt, and as such there is only ever one - // host window per menu hierarchy, no matter how many NativeMenuWin objects - // exist wrapping submenus. - if (!host_window_.get()) - host_window_.reset(new MenuHostWindow(this)); -} - -//////////////////////////////////////////////////////////////////////////////// -// MenuWrapper, public: - -// static -MenuWrapper* MenuWrapper::CreateWrapper(ui::MenuModel* model) { - return new NativeMenuWin(model, NULL); -} - -} // namespace views
diff --git a/ui/views/controls/menu/native_menu_win.h b/ui/views/controls/menu/native_menu_win.h deleted file mode 100644 index 39dc37e..0000000 --- a/ui/views/controls/menu/native_menu_win.h +++ /dev/null
@@ -1,169 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_MENU_NATIVE_MENU_WIN_H_ -#define UI_VIEWS_CONTROLS_MENU_NATIVE_MENU_WIN_H_ - -#include <vector> - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "base/memory/weak_ptr.h" -#include "base/observer_list.h" -#include "base/strings/string16.h" -#include "ui/views/controls/menu/menu_wrapper.h" -#include "ui/views/views_export.h" - -namespace ui { -class MenuModel; -} - -namespace views { - -// A Windows implementation of MenuWrapper. -// TODO(beng): rename to MenuWin once the old class is dead. -class VIEWS_EXPORT NativeMenuWin : public MenuWrapper { - public: - // Construct a NativeMenuWin, with a model and delegate. If |system_menu_for| - // is non-NULL, the NativeMenuWin wraps the system menu for that window. - // The caller owns the model and the delegate. - NativeMenuWin(ui::MenuModel* model, HWND system_menu_for); - virtual ~NativeMenuWin(); - - // Overridden from MenuWrapper: - virtual void RunMenuAt(const gfx::Point& point, int alignment) override; - virtual void CancelMenu() override; - virtual void Rebuild(MenuInsertionDelegateWin* delegate) override; - virtual void UpdateStates() override; - virtual HMENU GetNativeMenu() const override; - virtual MenuAction GetMenuAction() const override; - virtual void AddMenuListener(MenuListener* listener) override; - virtual void RemoveMenuListener(MenuListener* listener) override; - virtual void SetMinimumWidth(int width) override; - - private: - // IMPORTANT: Note about indices. - // Functions in this class deal in two index spaces: - // 1. menu_index - the index of an item within the actual Windows - // native menu. - // 2. model_index - the index of the item within our model. - // These two are most often but not always the same value! The - // notable exception is when this object is used to wrap the - // Windows System Menu. In this instance, the model indices start - // at 0, but the insertion index into the existing menu is not. - // It is important to take this into consideration when editing the - // code in the functions in this class. - - struct HighlightedMenuItemInfo; - - // Returns true if the item at the specified index is a separator. - bool IsSeparatorItemAt(int menu_index) const; - - // Add items. See note above about indices. - void AddMenuItemAt(int menu_index, int model_index); - void AddSeparatorItemAt(int menu_index, int model_index); - - // Sets the state of the item at the specified index. - void SetMenuItemState(int menu_index, - bool enabled, - bool checked, - bool is_default); - - // Sets the label of the item at the specified index. - void SetMenuItemLabel(int menu_index, - int model_index, - const base::string16& label); - - // Updates the local data structure with the correctly formatted version of - // |label| at the specified model_index, and adds string data to |mii| if - // the menu is not owner-draw. That's a mouthful. This function exists because - // of the peculiarities of the Windows menu API. - void UpdateMenuItemInfoForString(MENUITEMINFO* mii, - int model_index, - const base::string16& label); - - // Returns the alignment flags to be passed to TrackPopupMenuEx, based on the - // supplied alignment and the UI text direction. - UINT GetAlignmentFlags(int alignment) const; - - // Resets the native menu stored in |menu_| by destroying any old menu then - // creating a new empty one. - void ResetNativeMenu(); - - // Creates the host window that receives notifications from the menu. - void CreateHostWindow(); - - // Callback from task to notify menu it was selected. - void DelayedSelect(); - - // Given a menu that's currently popped-up, find the currently highlighted - // item. Returns true if a highlighted item was found. - static bool GetHighlightedMenuItemInfo(HMENU menu, - HighlightedMenuItemInfo* info); - - // Hook to receive keyboard events while the menu is open. - static LRESULT CALLBACK MenuMessageHook( - int n_code, WPARAM w_param, LPARAM l_param); - - // Our attached model and delegate. - ui::MenuModel* model_; - - HMENU menu_; - - // True if the contents of menu items in this menu are drawn by the menu host - // window, rather than Windows. - bool owner_draw_; - - // An object that collects all of the data associated with an individual menu - // item. - struct ItemData; - std::vector<ItemData*> items_; - - // The window that receives notifications from the menu. - class MenuHostWindow; - friend MenuHostWindow; - scoped_ptr<MenuHostWindow> host_window_; - - // The HWND this menu is the system menu for, or NULL if the menu is not a - // system menu. - HWND system_menu_for_; - - // The index of the first item in the model in the menu. - int first_item_index_; - - // The action that took place during the call to RunMenuAt. - MenuAction menu_action_; - - // A list of listeners to call when the menu opens. - ObserverList<MenuListener> listeners_; - - // Keep track of whether the listeners have already been called at least - // once. - bool listeners_called_; - - // See comment in MenuMessageHook for details on these. - NativeMenuWin* menu_to_select_; - int position_to_select_; - base::WeakPtrFactory<NativeMenuWin> menu_to_select_factory_; - - // If we're a submenu, this is our parent. - NativeMenuWin* parent_; - - // If non-null the destructor sets this to true. This is set to non-null while - // the menu is showing. It is used to detect if the menu was deleted while - // running. - bool* destroyed_flag_; - - // Ugly: a static pointer to the instance of this class that currently - // has a menu open, because our hook function that receives keyboard - // events doesn't have a mechanism to get a user data pointer. - static NativeMenuWin* open_native_menu_win_; - - DISALLOW_COPY_AND_ASSIGN(NativeMenuWin); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_MENU_NATIVE_MENU_WIN_H_
diff --git a/ui/views/controls/menu/submenu_view.cc b/ui/views/controls/menu/submenu_view.cc deleted file mode 100644 index e368740..0000000 --- a/ui/views/controls/menu/submenu_view.cc +++ /dev/null
@@ -1,511 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/menu/submenu_view.h" - -#include <algorithm> - -#include "base/compiler_specific.h" -#include "ui/accessibility/ax_view_state.h" -#include "ui/events/event.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/geometry/safe_integer_conversions.h" -#include "ui/views/controls/menu/menu_config.h" -#include "ui/views/controls/menu/menu_controller.h" -#include "ui/views/controls/menu/menu_host.h" -#include "ui/views/controls/menu/menu_item_view.h" -#include "ui/views/controls/menu/menu_scroll_view_container.h" -#include "ui/views/widget/root_view.h" -#include "ui/views/widget/widget.h" - -namespace { - -// Height of the drop indicator. This should be an even number. -const int kDropIndicatorHeight = 2; - -// Color of the drop indicator. -const SkColor kDropIndicatorColor = SK_ColorBLACK; - -} // namespace - -namespace views { - -// static -const char SubmenuView::kViewClassName[] = "SubmenuView"; - -SubmenuView::SubmenuView(MenuItemView* parent) - : parent_menu_item_(parent), - host_(NULL), - drop_item_(NULL), - drop_position_(MenuDelegate::DROP_NONE), - scroll_view_container_(NULL), - max_minor_text_width_(0), - minimum_preferred_width_(0), - resize_open_menu_(false), - scroll_animator_(new ScrollAnimator(this)), - roundoff_error_(0), - prefix_selector_(this) { - DCHECK(parent); - // We'll delete ourselves, otherwise the ScrollView would delete us on close. - set_owned_by_client(); -} - -SubmenuView::~SubmenuView() { - // The menu may not have been closed yet (it will be hidden, but not - // necessarily closed). - Close(); - - delete scroll_view_container_; -} - -int SubmenuView::GetMenuItemCount() { - int count = 0; - for (int i = 0; i < child_count(); ++i) { - if (child_at(i)->id() == MenuItemView::kMenuItemViewID) - count++; - } - return count; -} - -MenuItemView* SubmenuView::GetMenuItemAt(int index) { - for (int i = 0, count = 0; i < child_count(); ++i) { - if (child_at(i)->id() == MenuItemView::kMenuItemViewID && - count++ == index) { - return static_cast<MenuItemView*>(child_at(i)); - } - } - NOTREACHED(); - return NULL; -} - -void SubmenuView::ChildPreferredSizeChanged(View* child) { - if (!resize_open_menu_) - return; - - MenuItemView *item = GetMenuItem(); - MenuController* controller = item->GetMenuController(); - - if (controller) { - bool dir; - gfx::Rect bounds = controller->CalculateMenuBounds(item, false, &dir); - Reposition(bounds); - } -} - -void SubmenuView::Layout() { - // We're in a ScrollView, and need to set our width/height ourselves. - if (!parent()) - return; - - // Use our current y, unless it means part of the menu isn't visible anymore. - int pref_height = GetPreferredSize().height(); - int new_y; - if (pref_height > parent()->height()) - new_y = std::max(parent()->height() - pref_height, y()); - else - new_y = 0; - SetBounds(x(), new_y, parent()->width(), pref_height); - - gfx::Insets insets = GetInsets(); - int x = insets.left(); - int y = insets.top(); - int menu_item_width = width() - insets.width(); - for (int i = 0; i < child_count(); ++i) { - View* child = child_at(i); - if (child->visible()) { - int child_height = child->GetHeightForWidth(menu_item_width); - child->SetBounds(x, y, menu_item_width, child_height); - y += child_height; - } - } -} - -gfx::Size SubmenuView::GetPreferredSize() const { - if (!has_children()) - return gfx::Size(); - - max_minor_text_width_ = 0; - // The maximum width of items which contain maybe a label and multiple views. - int max_complex_width = 0; - // The max. width of items which contain a label and maybe an accelerator. - int max_simple_width = 0; - - // We perform the size calculation in two passes. In the first pass, we - // calculate the width of the menu. In the second, we calculate the height - // using that width. This allows views that have flexible widths to adjust - // accordingly. - for (int i = 0; i < child_count(); ++i) { - const View* child = child_at(i); - if (!child->visible()) - continue; - if (child->id() == MenuItemView::kMenuItemViewID) { - const MenuItemView* menu = static_cast<const MenuItemView*>(child); - const MenuItemView::MenuItemDimensions& dimensions = - menu->GetDimensions(); - max_simple_width = std::max( - max_simple_width, dimensions.standard_width); - max_minor_text_width_ = - std::max(max_minor_text_width_, dimensions.minor_text_width); - max_complex_width = std::max(max_complex_width, - dimensions.standard_width + dimensions.children_width); - } else { - max_complex_width = std::max(max_complex_width, - child->GetPreferredSize().width()); - } - } - if (max_minor_text_width_ > 0) { - max_minor_text_width_ += - GetMenuItem()->GetMenuConfig().label_to_minor_text_padding; - } - // Finish calculating our optimum width. - gfx::Insets insets = GetInsets(); - int width = std::max(max_complex_width, - std::max(max_simple_width + max_minor_text_width_ + - insets.width(), - minimum_preferred_width_ - 2 * insets.width())); - - // Then, the height for that width. - int height = 0; - int menu_item_width = width - insets.width(); - for (int i = 0; i < child_count(); ++i) { - const View* child = child_at(i); - height += child->visible() ? child->GetHeightForWidth(menu_item_width) : 0; - } - - return gfx::Size(width, height + insets.height()); -} - -void SubmenuView::GetAccessibleState(ui::AXViewState* state) { - // Inherit most of the state from the parent menu item, except the role. - if (GetMenuItem()) - GetMenuItem()->GetAccessibleState(state); - state->role = ui::AX_ROLE_MENU_LIST_POPUP; -} - -ui::TextInputClient* SubmenuView::GetTextInputClient() { - return &prefix_selector_; -} - -void SubmenuView::PaintChildren(gfx::Canvas* canvas, - const views::CullSet& cull_set) { - View::PaintChildren(canvas, cull_set); - - if (drop_item_ && drop_position_ != MenuDelegate::DROP_ON) - PaintDropIndicator(canvas, drop_item_, drop_position_); -} - -bool SubmenuView::GetDropFormats( - int* formats, - std::set<OSExchangeData::CustomFormat>* custom_formats) { - DCHECK(GetMenuItem()->GetMenuController()); - return GetMenuItem()->GetMenuController()->GetDropFormats(this, formats, - custom_formats); -} - -bool SubmenuView::AreDropTypesRequired() { - DCHECK(GetMenuItem()->GetMenuController()); - return GetMenuItem()->GetMenuController()->AreDropTypesRequired(this); -} - -bool SubmenuView::CanDrop(const OSExchangeData& data) { - DCHECK(GetMenuItem()->GetMenuController()); - return GetMenuItem()->GetMenuController()->CanDrop(this, data); -} - -void SubmenuView::OnDragEntered(const ui::DropTargetEvent& event) { - DCHECK(GetMenuItem()->GetMenuController()); - GetMenuItem()->GetMenuController()->OnDragEntered(this, event); -} - -int SubmenuView::OnDragUpdated(const ui::DropTargetEvent& event) { - DCHECK(GetMenuItem()->GetMenuController()); - return GetMenuItem()->GetMenuController()->OnDragUpdated(this, event); -} - -void SubmenuView::OnDragExited() { - DCHECK(GetMenuItem()->GetMenuController()); - GetMenuItem()->GetMenuController()->OnDragExited(this); -} - -int SubmenuView::OnPerformDrop(const ui::DropTargetEvent& event) { - DCHECK(GetMenuItem()->GetMenuController()); - return GetMenuItem()->GetMenuController()->OnPerformDrop(this, event); -} - -bool SubmenuView::OnMouseWheel(const ui::MouseWheelEvent& e) { - gfx::Rect vis_bounds = GetVisibleBounds(); - int menu_item_count = GetMenuItemCount(); - if (vis_bounds.height() == height() || !menu_item_count) { - // All menu items are visible, nothing to scroll. - return true; - } - - // Find the index of the first menu item whose y-coordinate is >= visible - // y-coordinate. - int i = 0; - while ((i < menu_item_count) && (GetMenuItemAt(i)->y() < vis_bounds.y())) - ++i; - if (i == menu_item_count) - return true; - int first_vis_index = std::max(0, - (GetMenuItemAt(i)->y() == vis_bounds.y()) ? i : i - 1); - - // If the first item isn't entirely visible, make it visible, otherwise make - // the next/previous one entirely visible. If enough wasn't scrolled to show - // any new rows, then just scroll the amount so that smooth scrolling using - // the trackpad is possible. - int delta = abs(e.y_offset() / ui::MouseWheelEvent::kWheelDelta); - if (delta == 0) - return OnScroll(0, e.y_offset()); - for (bool scroll_up = (e.y_offset() > 0); delta != 0; --delta) { - int scroll_target; - if (scroll_up) { - if (GetMenuItemAt(first_vis_index)->y() == vis_bounds.y()) { - if (first_vis_index == 0) - break; - first_vis_index--; - } - scroll_target = GetMenuItemAt(first_vis_index)->y(); - } else { - if (first_vis_index + 1 == menu_item_count) - break; - scroll_target = GetMenuItemAt(first_vis_index + 1)->y(); - if (GetMenuItemAt(first_vis_index)->y() == vis_bounds.y()) - first_vis_index++; - } - ScrollRectToVisible(gfx::Rect(gfx::Point(0, scroll_target), - vis_bounds.size())); - vis_bounds = GetVisibleBounds(); - } - - return true; -} - -void SubmenuView::OnGestureEvent(ui::GestureEvent* event) { - bool handled = true; - switch (event->type()) { - case ui::ET_GESTURE_SCROLL_BEGIN: - scroll_animator_->Stop(); - break; - case ui::ET_GESTURE_SCROLL_UPDATE: - handled = OnScroll(0, event->details().scroll_y()); - break; - case ui::ET_GESTURE_SCROLL_END: - break; - case ui::ET_SCROLL_FLING_START: - if (event->details().velocity_y() != 0.0f) - scroll_animator_->Start(0, event->details().velocity_y()); - break; - case ui::ET_GESTURE_TAP_DOWN: - case ui::ET_SCROLL_FLING_CANCEL: - if (scroll_animator_->is_scrolling()) - scroll_animator_->Stop(); - else - handled = false; - break; - default: - handled = false; - break; - } - if (handled) - event->SetHandled(); -} - -int SubmenuView::GetRowCount() { - return GetMenuItemCount(); -} - -int SubmenuView::GetSelectedRow() { - int row = 0; - for (int i = 0; i < child_count(); ++i) { - if (child_at(i)->id() != MenuItemView::kMenuItemViewID) - continue; - - if (static_cast<MenuItemView*>(child_at(i))->IsSelected()) - return row; - - row++; - } - - return -1; -} - -void SubmenuView::SetSelectedRow(int row) { - GetMenuItem()->GetMenuController()->SetSelection( - GetMenuItemAt(row), - MenuController::SELECTION_DEFAULT); -} - -base::string16 SubmenuView::GetTextForRow(int row) { - return GetMenuItemAt(row)->title(); -} - -bool SubmenuView::IsShowing() { - return host_ && host_->IsMenuHostVisible(); -} - -void SubmenuView::ShowAt(Widget* parent, - const gfx::Rect& bounds, - bool do_capture) { - if (host_) { - host_->ShowMenuHost(do_capture); - } else { - host_ = new MenuHost(this); - // Force construction of the scroll view container. - GetScrollViewContainer(); - // Force a layout since our preferred size may not have changed but our - // content may have. - InvalidateLayout(); - host_->InitMenuHost(parent, bounds, scroll_view_container_, do_capture); - } - - GetScrollViewContainer()->NotifyAccessibilityEvent( - ui::AX_EVENT_MENU_START, - true); - NotifyAccessibilityEvent( - ui::AX_EVENT_MENU_POPUP_START, - true); -} - -void SubmenuView::Reposition(const gfx::Rect& bounds) { - if (host_) - host_->SetMenuHostBounds(bounds); -} - -void SubmenuView::Close() { - if (host_) { - NotifyAccessibilityEvent(ui::AX_EVENT_MENU_POPUP_END, true); - GetScrollViewContainer()->NotifyAccessibilityEvent( - ui::AX_EVENT_MENU_END, true); - - host_->DestroyMenuHost(); - host_ = NULL; - } -} - -void SubmenuView::Hide() { - if (host_) - host_->HideMenuHost(); - if (scroll_animator_->is_scrolling()) - scroll_animator_->Stop(); -} - -void SubmenuView::ReleaseCapture() { - if (host_) - host_->ReleaseMenuHostCapture(); -} - -bool SubmenuView::SkipDefaultKeyEventProcessing(const ui::KeyEvent& e) { - return views::FocusManager::IsTabTraversalKeyEvent(e); -} - -MenuItemView* SubmenuView::GetMenuItem() const { - return parent_menu_item_; -} - -void SubmenuView::SetDropMenuItem(MenuItemView* item, - MenuDelegate::DropPosition position) { - if (drop_item_ == item && drop_position_ == position) - return; - SchedulePaintForDropIndicator(drop_item_, drop_position_); - drop_item_ = item; - drop_position_ = position; - SchedulePaintForDropIndicator(drop_item_, drop_position_); -} - -bool SubmenuView::GetShowSelection(MenuItemView* item) { - if (drop_item_ == NULL) - return true; - // Something is being dropped on one of this menus items. Show the - // selection if the drop is on the passed in item and the drop position is - // ON. - return (drop_item_ == item && drop_position_ == MenuDelegate::DROP_ON); -} - -MenuScrollViewContainer* SubmenuView::GetScrollViewContainer() { - if (!scroll_view_container_) { - scroll_view_container_ = new MenuScrollViewContainer(this); - // Otherwise MenuHost would delete us. - scroll_view_container_->set_owned_by_client(); - } - return scroll_view_container_; -} - -void SubmenuView::MenuHostDestroyed() { - host_ = NULL; - GetMenuItem()->GetMenuController()->Cancel(MenuController::EXIT_DESTROYED); -} - -const char* SubmenuView::GetClassName() const { - return kViewClassName; -} - -void SubmenuView::OnBoundsChanged(const gfx::Rect& previous_bounds) { - SchedulePaint(); -} - -void SubmenuView::PaintDropIndicator(gfx::Canvas* canvas, - MenuItemView* item, - MenuDelegate::DropPosition position) { - if (position == MenuDelegate::DROP_NONE) - return; - - gfx::Rect bounds = CalculateDropIndicatorBounds(item, position); - canvas->FillRect(bounds, kDropIndicatorColor); -} - -void SubmenuView::SchedulePaintForDropIndicator( - MenuItemView* item, - MenuDelegate::DropPosition position) { - if (item == NULL) - return; - - if (position == MenuDelegate::DROP_ON) { - item->SchedulePaint(); - } else if (position != MenuDelegate::DROP_NONE) { - SchedulePaintInRect(CalculateDropIndicatorBounds(item, position)); - } -} - -gfx::Rect SubmenuView::CalculateDropIndicatorBounds( - MenuItemView* item, - MenuDelegate::DropPosition position) { - DCHECK(position != MenuDelegate::DROP_NONE); - gfx::Rect item_bounds = item->bounds(); - switch (position) { - case MenuDelegate::DROP_BEFORE: - item_bounds.Offset(0, -kDropIndicatorHeight / 2); - item_bounds.set_height(kDropIndicatorHeight); - return item_bounds; - - case MenuDelegate::DROP_AFTER: - item_bounds.Offset(0, item_bounds.height() - kDropIndicatorHeight / 2); - item_bounds.set_height(kDropIndicatorHeight); - return item_bounds; - - default: - // Don't render anything for on. - return gfx::Rect(); - } -} - -bool SubmenuView::OnScroll(float dx, float dy) { - const gfx::Rect& vis_bounds = GetVisibleBounds(); - const gfx::Rect& full_bounds = bounds(); - int x = vis_bounds.x(); - float y_f = vis_bounds.y() - dy - roundoff_error_; - int y = gfx::ToRoundedInt(y_f); - roundoff_error_ = y - y_f; - // clamp y to [0, full_height - vis_height) - y = std::min(y, full_bounds.height() - vis_bounds.height() - 1); - y = std::max(y, 0); - gfx::Rect new_vis_bounds(x, y, vis_bounds.width(), vis_bounds.height()); - if (new_vis_bounds != vis_bounds) { - ScrollRectToVisible(new_vis_bounds); - return true; - } - return false; -} - -} // namespace views
diff --git a/ui/views/controls/menu/submenu_view.h b/ui/views/controls/menu/submenu_view.h deleted file mode 100644 index c475988..0000000 --- a/ui/views/controls/menu/submenu_view.h +++ /dev/null
@@ -1,228 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_MENU_SUBMENU_VIEW_H_ -#define UI_VIEWS_CONTROLS_MENU_SUBMENU_VIEW_H_ - -#include <string> - -#include "base/compiler_specific.h" -#include "ui/views/animation/scroll_animator.h" -#include "ui/views/controls/menu/menu_delegate.h" -#include "ui/views/controls/prefix_delegate.h" -#include "ui/views/controls/prefix_selector.h" -#include "ui/views/view.h" - -namespace views { - -class MenuHost; -class MenuItemView; -class MenuScrollViewContainer; - -// SubmenuView is the parent of all menu items. -// -// SubmenuView has the following responsibilities: -// . It positions and sizes all child views (any type of View may be added, -// not just MenuItemViews). -// . Forwards the appropriate events to the MenuController. This allows the -// MenuController to update the selection as the user moves the mouse around. -// . Renders the drop indicator during a drop operation. -// . Shows and hides the window (a NativeWidget) when the menu is shown on -// screen. -// -// SubmenuView is itself contained in a MenuScrollViewContainer. -// MenuScrollViewContainer handles showing as much of the SubmenuView as the -// screen allows. If the SubmenuView is taller than the screen, scroll buttons -// are provided that allow the user to see all the menu items. -class VIEWS_EXPORT SubmenuView : public PrefixDelegate, - public ScrollDelegate { - public: - // The submenu's class name. - static const char kViewClassName[]; - - // Creates a SubmenuView for the specified menu item. - explicit SubmenuView(MenuItemView* parent); - virtual ~SubmenuView(); - - // Returns the number of child views that are MenuItemViews. - // MenuItemViews are identified by ID. - int GetMenuItemCount(); - - // Returns the MenuItemView at the specified index. - MenuItemView* GetMenuItemAt(int index); - - // Positions and sizes the child views. This tiles the views vertically, - // giving each child the available width. - virtual void Layout() override; - virtual gfx::Size GetPreferredSize() const override; - - // Override from View. - virtual void GetAccessibleState(ui::AXViewState* state) override; - virtual ui::TextInputClient* GetTextInputClient() override; - - // Painting. - virtual void PaintChildren(gfx::Canvas* canvas, - const views::CullSet& cull_view) override; - - // Drag and drop methods. These are forwarded to the MenuController. - virtual bool GetDropFormats( - int* formats, - std::set<OSExchangeData::CustomFormat>* custom_formats) override; - virtual bool AreDropTypesRequired() override; - virtual bool CanDrop(const OSExchangeData& data) override; - virtual void OnDragEntered(const ui::DropTargetEvent& event) override; - virtual int OnDragUpdated(const ui::DropTargetEvent& event) override; - virtual void OnDragExited() override; - virtual int OnPerformDrop(const ui::DropTargetEvent& event) override; - - // Scrolls on menu item boundaries. - virtual bool OnMouseWheel(const ui::MouseWheelEvent& e) override; - - // Overridden from ui::EventHandler. - // Scrolls on menu item boundaries. - virtual void OnGestureEvent(ui::GestureEvent* event) override; - - // Overridden from PrefixDelegate. - virtual int GetRowCount() override; - virtual int GetSelectedRow() override; - virtual void SetSelectedRow(int row) override; - virtual base::string16 GetTextForRow(int row) override; - - // Returns true if the menu is showing. - bool IsShowing(); - - // Shows the menu at the specified location. Coordinates are in screen - // coordinates. max_width gives the max width the view should be. - void ShowAt(Widget* parent, const gfx::Rect& bounds, bool do_capture); - - // Resets the bounds of the submenu to |bounds|. - void Reposition(const gfx::Rect& bounds); - - // Closes the menu, destroying the host. - void Close(); - - // Hides the hosting window. - // - // The hosting window is hidden first, then deleted (Close) when the menu is - // done running. This is done to avoid deletion ordering dependencies. In - // particular, during drag and drop (and when a modal dialog is shown as - // a result of choosing a context menu) it is possible that an event is - // being processed by the host, so that host is on the stack when we need to - // close the window. If we closed the window immediately (and deleted it), - // when control returned back to host we would crash as host was deleted. - void Hide(); - - // If mouse capture was grabbed, it is released. Does nothing if mouse was - // not captured. - void ReleaseCapture(); - - // Overriden from View to prevent tab from doing anything. - virtual bool SkipDefaultKeyEventProcessing(const ui::KeyEvent& e) override; - - // Returns the parent menu item we're showing children for. - MenuItemView* GetMenuItem() const; - - // Set the drop item and position. - void SetDropMenuItem(MenuItemView* item, - MenuDelegate::DropPosition position); - - // Returns whether the selection should be shown for the specified item. - // The selection is NOT shown during drag and drop when the drop is over - // the menu. - bool GetShowSelection(MenuItemView* item); - - // Returns the container for the SubmenuView. - MenuScrollViewContainer* GetScrollViewContainer(); - - // Invoked if the menu is prematurely destroyed. This can happen if the window - // closes while the menu is shown. If invoked the SubmenuView must drop all - // references to the MenuHost as the MenuHost is about to be deleted. - void MenuHostDestroyed(); - - // Max width of minor text (accelerator or subtitle) in child menu items. This - // doesn't include children's children, only direct children. - int max_minor_text_width() const { return max_minor_text_width_; } - - // Minimum width of menu in pixels (default 0). This becomes the smallest - // width returned by GetPreferredSize(). - void set_minimum_preferred_width(int minimum_preferred_width) { - minimum_preferred_width_ = minimum_preferred_width; - } - - // Automatically resize menu if a subview's preferred size changes. - bool resize_open_menu() const { return resize_open_menu_; } - void set_resize_open_menu(bool resize_open_menu) { - resize_open_menu_ = resize_open_menu; - } - - protected: - // Overridden from View: - virtual const char* GetClassName() const override; - - // View method. Overridden to schedule a paint. We do this so that when - // scrolling occurs, everything is repainted correctly. - virtual void OnBoundsChanged(const gfx::Rect& previous_bounds) override; - - virtual void ChildPreferredSizeChanged(View* child) override; - - private: - // Paints the drop indicator. This is only invoked if item is non-NULL and - // position is not DROP_NONE. - void PaintDropIndicator(gfx::Canvas* canvas, - MenuItemView* item, - MenuDelegate::DropPosition position); - - void SchedulePaintForDropIndicator(MenuItemView* item, - MenuDelegate::DropPosition position); - - // Calculates the location of th edrop indicator. - gfx::Rect CalculateDropIndicatorBounds(MenuItemView* item, - MenuDelegate::DropPosition position); - - // Implementation of ScrollDelegate - virtual bool OnScroll(float dx, float dy) override; - - // Parent menu item. - MenuItemView* parent_menu_item_; - - // Widget subclass used to show the children. This is deleted when we invoke - // |DestroyMenuHost|, or |MenuHostDestroyed| is invoked back on us. - MenuHost* host_; - - // If non-null, indicates a drop is in progress and drop_item is the item - // the drop is over. - MenuItemView* drop_item_; - - // Position of the drop. - MenuDelegate::DropPosition drop_position_; - - // Ancestor of the SubmenuView, lazily created. - MenuScrollViewContainer* scroll_view_container_; - - // See description above getter. - mutable int max_minor_text_width_; - - // Minimum width returned in GetPreferredSize(). - int minimum_preferred_width_; - - // Reposition open menu when contained views change size. - bool resize_open_menu_; - - // The submenu's scroll animator - scoped_ptr<ScrollAnimator> scroll_animator_; - - // Difference between current position and cumulative deltas passed to - // OnScroll. - // TODO(tdresser): This should be removed when raw pixel scrolling for views - // is enabled. See crbug.com/329354. - float roundoff_error_; - - PrefixSelector prefix_selector_; - - DISALLOW_COPY_AND_ASSIGN(SubmenuView); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_MENU_SUBMENU_VIEW_H_
diff --git a/ui/views/controls/message_box_view.cc b/ui/views/controls/message_box_view.cc deleted file mode 100644 index 2c0f102..0000000 --- a/ui/views/controls/message_box_view.cc +++ /dev/null
@@ -1,244 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/message_box_view.h" - -#include "base/i18n/rtl.h" -#include "base/message_loop/message_loop.h" -#include "base/strings/string_split.h" -#include "base/strings/utf_string_conversions.h" -#include "ui/accessibility/ax_view_state.h" -#include "ui/base/clipboard/clipboard.h" -#include "ui/base/clipboard/scoped_clipboard_writer.h" -#include "ui/views/controls/button/checkbox.h" -#include "ui/views/controls/label.h" -#include "ui/views/controls/link.h" -#include "ui/views/controls/scroll_view.h" -#include "ui/views/controls/textfield/textfield.h" -#include "ui/views/layout/box_layout.h" -#include "ui/views/layout/grid_layout.h" -#include "ui/views/layout/layout_constants.h" -#include "ui/views/widget/widget.h" -#include "ui/views/window/client_view.h" -#include "ui/views/window/dialog_delegate.h" - -namespace { - -const int kDefaultMessageWidth = 320; - -// Paragraph separators are defined in -// http://www.unicode.org/Public/6.0.0/ucd/extracted/DerivedBidiClass.txt -// -// # Bidi_Class=Paragraph_Separator -// -// 000A ; B # Cc <control-000A> -// 000D ; B # Cc <control-000D> -// 001C..001E ; B # Cc [3] <control-001C>..<control-001E> -// 0085 ; B # Cc <control-0085> -// 2029 ; B # Zp PARAGRAPH SEPARATOR -bool IsParagraphSeparator(base::char16 c) { - return ( c == 0x000A || c == 0x000D || c == 0x001C || c == 0x001D || - c == 0x001E || c == 0x0085 || c == 0x2029); -} - -// Splits |text| into a vector of paragraphs. -// Given an example "\nabc\ndef\n\n\nhij\n", the split results should be: -// "", "abc", "def", "", "", "hij", and "". -void SplitStringIntoParagraphs(const base::string16& text, - std::vector<base::string16>* paragraphs) { - paragraphs->clear(); - - size_t start = 0; - for (size_t i = 0; i < text.length(); ++i) { - if (IsParagraphSeparator(text[i])) { - paragraphs->push_back(text.substr(start, i - start)); - start = i + 1; - } - } - paragraphs->push_back(text.substr(start, text.length() - start)); -} - -} // namespace - -namespace views { - -/////////////////////////////////////////////////////////////////////////////// -// MessageBoxView, public: - -MessageBoxView::InitParams::InitParams(const base::string16& message) - : options(NO_OPTIONS), - message(message), - message_width(kDefaultMessageWidth), - inter_row_vertical_spacing(kRelatedControlVerticalSpacing) {} - -MessageBoxView::InitParams::~InitParams() { -} - -MessageBoxView::MessageBoxView(const InitParams& params) - : prompt_field_(NULL), - checkbox_(NULL), - link_(NULL), - message_width_(params.message_width) { - Init(params); -} - -MessageBoxView::~MessageBoxView() {} - -base::string16 MessageBoxView::GetInputText() { - return prompt_field_ ? prompt_field_->text() : base::string16(); -} - -bool MessageBoxView::IsCheckBoxSelected() { - return checkbox_ ? checkbox_->checked() : false; -} - -void MessageBoxView::SetCheckBoxLabel(const base::string16& label) { - if (!checkbox_) - checkbox_ = new Checkbox(label); - else - checkbox_->SetText(label); - ResetLayoutManager(); -} - -void MessageBoxView::SetCheckBoxSelected(bool selected) { - if (!checkbox_) - return; - checkbox_->SetChecked(selected); -} - -void MessageBoxView::SetLink(const base::string16& text, - LinkListener* listener) { - if (text.empty()) { - DCHECK(!listener); - delete link_; - link_ = NULL; - } else { - DCHECK(listener); - if (!link_) { - link_ = new Link(); - link_->SetHorizontalAlignment(gfx::ALIGN_LEFT); - } - link_->SetText(text); - link_->set_listener(listener); - } - ResetLayoutManager(); -} - -void MessageBoxView::GetAccessibleState(ui::AXViewState* state) { - state->role = ui::AX_ROLE_ALERT; -} - -/////////////////////////////////////////////////////////////////////////////// -// MessageBoxView, View overrides: - -void MessageBoxView::ViewHierarchyChanged( - const ViewHierarchyChangedDetails& details) { - if (details.child == this && details.is_add) { - if (prompt_field_) - prompt_field_->SelectAll(true); - - NotifyAccessibilityEvent(ui::AX_EVENT_ALERT, true); - } -} - -bool MessageBoxView::AcceleratorPressed(const ui::Accelerator& accelerator) { - // We only accepts Ctrl-C. - DCHECK(accelerator.key_code() == 'C' && accelerator.IsCtrlDown()); - - // We must not intercept Ctrl-C when we have a text box and it's focused. - if (prompt_field_ && prompt_field_->HasFocus()) - return false; - - ui::ScopedClipboardWriter scw(ui::CLIPBOARD_TYPE_COPY_PASTE); - base::string16 text = message_labels_[0]->text(); - for (size_t i = 1; i < message_labels_.size(); ++i) - text += message_labels_[i]->text(); - scw.WriteText(text); - return true; -} - -/////////////////////////////////////////////////////////////////////////////// -// MessageBoxView, private: - -void MessageBoxView::Init(const InitParams& params) { - if (params.options & DETECT_DIRECTIONALITY) { - std::vector<base::string16> texts; - SplitStringIntoParagraphs(params.message, &texts); - for (size_t i = 0; i < texts.size(); ++i) { - Label* message_label = new Label(texts[i]); - // Avoid empty multi-line labels, which have a height of 0. - message_label->SetMultiLine(!texts[i].empty()); - message_label->SetAllowCharacterBreak(true); - message_label->SetHorizontalAlignment(gfx::ALIGN_TO_HEAD); - message_labels_.push_back(message_label); - } - } else { - Label* message_label = new Label(params.message); - message_label->SetMultiLine(true); - message_label->SetAllowCharacterBreak(true); - message_label->SetHorizontalAlignment(gfx::ALIGN_LEFT); - message_labels_.push_back(message_label); - } - - if (params.options & HAS_PROMPT_FIELD) { - prompt_field_ = new Textfield; - prompt_field_->SetText(params.default_prompt); - } - - inter_row_vertical_spacing_ = params.inter_row_vertical_spacing; - - ResetLayoutManager(); -} - -void MessageBoxView::ResetLayoutManager() { - // Initialize the Grid Layout Manager used for this dialog box. - GridLayout* layout = GridLayout::CreatePanel(this); - SetLayoutManager(layout); - - // Add the column set for the message displayed at the top of the dialog box. - const int message_column_view_set_id = 0; - ColumnSet* column_set = layout->AddColumnSet(message_column_view_set_id); - column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1, - GridLayout::FIXED, message_width_, 0); - - // Column set for extra elements, if any. - const int extra_column_view_set_id = 1; - if (prompt_field_ || checkbox_ || link_) { - column_set = layout->AddColumnSet(extra_column_view_set_id); - column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1, - GridLayout::USE_PREF, 0, 0); - } - - const int kMaxScrollViewHeight = 600; - views::View* message_contents = new views::View(); - message_contents->SetLayoutManager( - new views::BoxLayout(views::BoxLayout::kVertical, 0, 0, 0)); - for (size_t i = 0; i < message_labels_.size(); ++i) - message_contents->AddChildView(message_labels_[i]); - ScrollView* scroll_view = new views::ScrollView(); - scroll_view->ClipHeightTo(0, kMaxScrollViewHeight); - scroll_view->SetContents(message_contents); - layout->StartRow(0, message_column_view_set_id); - layout->AddView(scroll_view); - - if (prompt_field_) { - layout->AddPaddingRow(0, inter_row_vertical_spacing_); - layout->StartRow(0, extra_column_view_set_id); - layout->AddView(prompt_field_); - } - - if (checkbox_) { - layout->AddPaddingRow(0, inter_row_vertical_spacing_); - layout->StartRow(0, extra_column_view_set_id); - layout->AddView(checkbox_); - } - - if (link_) { - layout->AddPaddingRow(0, inter_row_vertical_spacing_); - layout->StartRow(0, extra_column_view_set_id); - layout->AddView(link_); - } -} - -} // namespace views
diff --git a/ui/views/controls/message_box_view.h b/ui/views/controls/message_box_view.h deleted file mode 100644 index 9123995..0000000 --- a/ui/views/controls/message_box_view.h +++ /dev/null
@@ -1,118 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_MESSAGE_BOX_VIEW_H_ -#define UI_VIEWS_CONTROLS_MESSAGE_BOX_VIEW_H_ - -#include <vector> - -#include "base/strings/string16.h" -#include "ui/views/view.h" - -namespace views { - -class Checkbox; -class Label; -class Link; -class LinkListener; -class Textfield; - -// This class displays the contents of a message box. It is intended for use -// within a constrained window, and has options for a message, prompt, OK -// and Cancel buttons. -class VIEWS_EXPORT MessageBoxView : public View { - public: - enum Options { - NO_OPTIONS = 0, - // For a message from a web page (not from Chrome's UI), such as script - // dialog text, each paragraph's directionality is auto-detected using the - // directionality of the paragraph's first strong character's. Please refer - // to HTML5 spec for details. - // http://dev.w3.org/html5/spec/Overview.html#text-rendered-in-native-user-interfaces: - // The spec does not say anything about alignment. And we choose to - // align all paragraphs according to the direction of the first paragraph. - DETECT_DIRECTIONALITY = 1 << 0, - HAS_PROMPT_FIELD = 1 << 1, - }; - - struct VIEWS_EXPORT InitParams { - explicit InitParams(const base::string16& message); - ~InitParams(); - - uint16 options; - base::string16 message; - base::string16 default_prompt; - int message_width; - int inter_row_vertical_spacing; - }; - - explicit MessageBoxView(const InitParams& params); - - virtual ~MessageBoxView(); - - // Returns the text box. - views::Textfield* text_box() { return prompt_field_; } - - // Returns user entered data in the prompt field. - base::string16 GetInputText(); - - // Returns true if a checkbox is selected, false otherwise. (And false if - // the message box has no checkbox.) - bool IsCheckBoxSelected(); - - // Adds a checkbox with the specified label to the message box if this is the - // first call. Otherwise, it changes the label of the current checkbox. To - // start, the message box has no checkbox until this function is called. - void SetCheckBoxLabel(const base::string16& label); - - // Sets the state of the check-box. - void SetCheckBoxSelected(bool selected); - - // Sets the text and the listener of the link. If |text| is empty, the link - // is removed. - void SetLink(const base::string16& text, LinkListener* listener); - - // View: - virtual void GetAccessibleState(ui::AXViewState* state) override; - - protected: - // View: - virtual void ViewHierarchyChanged( - const ViewHierarchyChangedDetails& details) override; - // Handles Ctrl-C and writes the message in the system clipboard. - virtual bool AcceleratorPressed(const ui::Accelerator& accelerator) override; - - private: - // Sets up the layout manager and initializes the message labels and prompt - // field. This should only be called once, from the constructor. - void Init(const InitParams& params); - - // Sets up the layout manager based on currently initialized views. Should be - // called when a view is initialized or changed. - void ResetLayoutManager(); - - // Message for the message box. - std::vector<Label*> message_labels_; - - // Input text field for the message box. - Textfield* prompt_field_; - - // Checkbox for the message box. - Checkbox* checkbox_; - - // Link displayed at the bottom of the view. - Link* link_; - - // Maximum width of the message label. - int message_width_; - - // Spacing between rows in the grid layout. - int inter_row_vertical_spacing_; - - DISALLOW_COPY_AND_ASSIGN(MessageBoxView); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_MESSAGE_BOX_VIEW_H_
diff --git a/ui/views/controls/native/native_view_host.cc b/ui/views/controls/native/native_view_host.cc deleted file mode 100644 index d706fc3..0000000 --- a/ui/views/controls/native/native_view_host.cc +++ /dev/null
@@ -1,223 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/native/native_view_host.h" - -#include "base/logging.h" -#include "ui/base/cursor/cursor.h" -#include "ui/gfx/canvas.h" -#include "ui/views/accessibility/native_view_accessibility.h" -#include "ui/views/controls/native/native_view_host_wrapper.h" -#include "ui/views/widget/widget.h" - -namespace views { - -// static -const char NativeViewHost::kViewClassName[] = "NativeViewHost"; -const char kWidgetNativeViewHostKey[] = "WidgetNativeViewHost"; - -//////////////////////////////////////////////////////////////////////////////// -// NativeViewHost, public: - -NativeViewHost::NativeViewHost() - : native_view_(NULL), - fast_resize_(false), - fast_resize_at_last_layout_(false), - focus_view_(NULL) { -} - -NativeViewHost::~NativeViewHost() { -} - -void NativeViewHost::Attach(gfx::NativeView native_view) { - DCHECK(native_view); - DCHECK(!native_view_); - native_view_ = native_view; - // If set_focus_view() has not been invoked, this view is the one that should - // be seen as focused when the native view receives focus. - if (!focus_view_) - focus_view_ = this; - native_wrapper_->AttachNativeView(); - Layout(); - - Widget* widget = Widget::GetWidgetForNativeView(native_view); - if (widget) - widget->SetNativeWindowProperty(kWidgetNativeViewHostKey, this); -} - -void NativeViewHost::Detach() { - Detach(false); -} - -void NativeViewHost::SetPreferredSize(const gfx::Size& size) { - preferred_size_ = size; - PreferredSizeChanged(); -} - -void NativeViewHost::NativeViewDestroyed() { - // Detach so we can clear our state and notify the native_wrapper_ to release - // ref on the native view. - Detach(true); -} - -//////////////////////////////////////////////////////////////////////////////// -// NativeViewHost, View overrides: - -gfx::Size NativeViewHost::GetPreferredSize() const { - return preferred_size_; -} - -void NativeViewHost::Layout() { - if (!native_view_ || !native_wrapper_.get()) - return; - - gfx::Rect vis_bounds = GetVisibleBounds(); - bool visible = !vis_bounds.IsEmpty(); - - if (visible && !fast_resize_) { - if (vis_bounds.size() != size()) { - // Only a portion of the Widget is really visible. - int x = vis_bounds.x(); - int y = vis_bounds.y(); - native_wrapper_->InstallClip(x, y, vis_bounds.width(), - vis_bounds.height()); - } else if (native_wrapper_->HasInstalledClip()) { - // The whole widget is visible but we installed a clip on the widget, - // uninstall it. - native_wrapper_->UninstallClip(); - } - } - - if (visible) { - // Since widgets know nothing about the View hierarchy (they are direct - // children of the Widget that hosts our View hierarchy) they need to be - // positioned in the coordinate system of the Widget, not the current - // view. Also, they should be positioned respecting the border insets - // of the native view. - gfx::Rect local_bounds = ConvertRectToWidget(GetContentsBounds()); - native_wrapper_->ShowWidget(local_bounds.x(), local_bounds.y(), - local_bounds.width(), - local_bounds.height()); - } else { - native_wrapper_->HideWidget(); - } - fast_resize_at_last_layout_ = visible && fast_resize_; -} - -void NativeViewHost::OnPaint(gfx::Canvas* canvas) { - // Paint background if there is one. NativeViewHost needs to paint - // a background when it is hosted in a TabbedPane. For Gtk implementation, - // NativeTabbedPaneGtk uses a NativeWidgetGtk as page container and because - // NativeWidgetGtk hook "expose" with its root view's paint, we need to - // fill the content. Otherwise, the tab page's background is not properly - // cleared. For Windows case, it appears okay to not paint background because - // we don't have a container window in-between. However if you want to use - // customized background, then this becomes necessary. - OnPaintBackground(canvas); - - // The area behind our window is black, so during a fast resize (where our - // content doesn't draw over the full size of our native view, and the native - // view background color doesn't show up), we need to cover that blackness - // with something so that fast resizes don't result in black flash. - // - // It would be nice if this used some approximation of the page's - // current background color. - if (native_wrapper_->HasInstalledClip()) - canvas->FillRect(GetLocalBounds(), SK_ColorWHITE); -} - -void NativeViewHost::VisibilityChanged(View* starting_from, bool is_visible) { - Layout(); -} - -bool NativeViewHost::GetNeedsNotificationWhenVisibleBoundsChange() const { - // The native widget is placed relative to the root. As such, we need to - // know when the position of any ancestor changes, or our visibility relative - // to other views changed as it'll effect our position relative to the root. - return true; -} - -void NativeViewHost::OnVisibleBoundsChanged() { - Layout(); -} - -void NativeViewHost::ViewHierarchyChanged( - const ViewHierarchyChangedDetails& details) { - views::Widget* this_widget = GetWidget(); - - // A non-NULL |details.move_view| indicates a move operation i.e. |this| is - // is being reparented. If the previous and new parents belong to the same - // widget, don't remove |this| from the widget. This saves resources from - // removing from widget and immediately followed by adding to widget; in - // particular, there wouldn't be spurious visibilitychange events for web - // contents of |WebView|. - if (details.move_view && this_widget && - details.move_view->GetWidget() == this_widget) { - return; - } - - if (details.is_add && this_widget) { - if (!native_wrapper_.get()) - native_wrapper_.reset(NativeViewHostWrapper::CreateWrapper(this)); - native_wrapper_->AddedToWidget(); - } else if (!details.is_add) { - native_wrapper_->RemovedFromWidget(); - } -} - -const char* NativeViewHost::GetClassName() const { - return kViewClassName; -} - -void NativeViewHost::OnFocus() { - native_wrapper_->SetFocus(); - NotifyAccessibilityEvent(ui::AX_EVENT_FOCUS, true); -} - -gfx::NativeViewAccessible NativeViewHost::GetNativeViewAccessible() { - if (native_wrapper_.get()) { - gfx::NativeViewAccessible accessible_view = - native_wrapper_->GetNativeViewAccessible(); - if (accessible_view) - return accessible_view; - } - - return View::GetNativeViewAccessible(); -} - -gfx::NativeCursor NativeViewHost::GetCursor(const ui::MouseEvent& event) { - return native_wrapper_->GetCursor(event.x(), event.y()); -} - -//////////////////////////////////////////////////////////////////////////////// -// NativeViewHost, private: - -void NativeViewHost::Detach(bool destroyed) { - if (native_view_) { - if (!destroyed) { - Widget* widget = Widget::GetWidgetForNativeView(native_view_); - if (widget) - widget->SetNativeWindowProperty(kWidgetNativeViewHostKey, NULL); - ClearFocus(); - } - native_wrapper_->NativeViewDetaching(destroyed); - native_view_ = NULL; - } -} - -void NativeViewHost::ClearFocus() { - FocusManager* focus_manager = GetFocusManager(); - if (!focus_manager || !focus_manager->GetFocusedView()) - return; - - Widget::Widgets widgets; - Widget::GetAllChildWidgets(native_view(), &widgets); - for (Widget::Widgets::iterator i = widgets.begin(); i != widgets.end(); ++i) { - focus_manager->ViewRemoved((*i)->GetRootView()); - if (!focus_manager->GetFocusedView()) - return; - } -} - -} // namespace views
diff --git a/ui/views/controls/native/native_view_host.h b/ui/views/controls/native/native_view_host.h deleted file mode 100644 index db8d7bb..0000000 --- a/ui/views/controls/native/native_view_host.h +++ /dev/null
@@ -1,134 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_NATIVE_NATIVE_VIEW_HOST_H_ -#define UI_VIEWS_CONTROLS_NATIVE_NATIVE_VIEW_HOST_H_ - -#include <string> - -#include "ui/gfx/native_widget_types.h" -#include "ui/views/view.h" - -namespace views { -namespace test { -class NativeViewHostTestBase; -} - -class NativeViewHostWrapper; - -// If a NativeViewHost's native view is a Widget, this native window -// property is set on the widget, pointing to the owning NativeViewHost. -extern const char kWidgetNativeViewHostKey[]; - -// A View type that hosts a gfx::NativeView. The bounds of the native view are -// kept in sync with the bounds of this view as it is moved and sized. -// Under the hood, a platform-specific NativeViewHostWrapper implementation does -// the platform-specific work of manipulating the underlying OS widget type. -class VIEWS_EXPORT NativeViewHost : public View { - public: - // The NativeViewHost's class name. - static const char kViewClassName[]; - - NativeViewHost(); - virtual ~NativeViewHost(); - - // Attach a gfx::NativeView to this View. Its bounds will be kept in sync - // with the bounds of this View until Detach is called. - // - // Because native views are positioned in the coordinates of their parent - // native view, this function should only be called after this View has been - // added to a View hierarchy hosted within a valid Widget. - void Attach(gfx::NativeView native_view); - - // Detach the attached native view. Its bounds and visibility will no - // longer be manipulated by this View. The native view may be destroyed and - // detached before calling this function, and this has no effect in that case. - void Detach(); - - // Sets a preferred size for the native view attached to this View. - void SetPreferredSize(const gfx::Size& size); - - // A NativeViewHost has an associated focus View so that the focus of the - // native control and of the View are kept in sync. In simple cases where the - // NativeViewHost directly wraps a native window as is, the associated view - // is this View. In other cases where the NativeViewHost is part of another - // view (such as TextField), the actual View is not the NativeViewHost and - // this method must be called to set that. - // This method must be called before Attach(). - void set_focus_view(View* view) { focus_view_ = view; } - View* focus_view() { return focus_view_; } - - // Fast resizing will move the native view and clip its visible region, this - // will result in white areas and will not resize the content (so scrollbars - // will be all wrong and content will flow offscreen). Only use this - // when you're doing extremely quick, high-framerate vertical resizes - // and don't care about accuracy. Make sure you do a real resize at the - // end. USE WITH CAUTION. - void set_fast_resize(bool fast_resize) { fast_resize_ = fast_resize; } - bool fast_resize() const { return fast_resize_; } - - // Value of fast_resize() the last time Layout() was invoked. - bool fast_resize_at_last_layout() const { - return fast_resize_at_last_layout_; - } - - // Accessor for |native_view_|. - gfx::NativeView native_view() const { return native_view_; } - - void NativeViewDestroyed(); - - // Overridden from View: - virtual gfx::Size GetPreferredSize() const override; - virtual void Layout() override; - virtual void OnPaint(gfx::Canvas* canvas) override; - virtual void VisibilityChanged(View* starting_from, bool is_visible) override; - virtual void OnFocus() override; - virtual gfx::NativeViewAccessible GetNativeViewAccessible() override; - virtual gfx::NativeCursor GetCursor(const ui::MouseEvent& event) override; - - protected: - virtual bool GetNeedsNotificationWhenVisibleBoundsChange() const override; - virtual void OnVisibleBoundsChanged() override; - virtual void ViewHierarchyChanged( - const ViewHierarchyChangedDetails& details) override; - virtual const char* GetClassName() const override; - - private: - friend class test::NativeViewHostTestBase; - - // Detach the native view. |destroyed| is true if the native view is - // detached because it's being destroyed, or false otherwise. - void Detach(bool destroyed); - - // Invokes ViewRemoved() on the FocusManager for all the child Widgets of our - // NativeView. This is used when detaching to ensure the FocusManager doesn't - // have a reference to a View that is no longer reachable. - void ClearFocus(); - - // The attached native view. There is exactly one native_view_ attached. - gfx::NativeView native_view_; - - // A platform-specific wrapper that does the OS-level manipulation of the - // attached gfx::NativeView. - scoped_ptr<NativeViewHostWrapper> native_wrapper_; - - // The preferred size of this View - gfx::Size preferred_size_; - - // True if the native view is being resized using the fast method described - // in the setter/accessor above. - bool fast_resize_; - - // Value of |fast_resize_| during the last call to Layout. - bool fast_resize_at_last_layout_; - - // The view that should be given focus when this NativeViewHost is focused. - View* focus_view_; - - DISALLOW_COPY_AND_ASSIGN(NativeViewHost); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_NATIVE_NATIVE_VIEW_HOST_H_
diff --git a/ui/views/controls/native/native_view_host_aura.cc b/ui/views/controls/native/native_view_host_aura.cc deleted file mode 100644 index 75c281f..0000000 --- a/ui/views/controls/native/native_view_host_aura.cc +++ /dev/null
@@ -1,235 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/native/native_view_host_aura.h" - -#include "base/logging.h" -#include "ui/aura/client/aura_constants.h" -#include "ui/aura/client/focus_client.h" -#include "ui/aura/window.h" -#include "ui/aura/window_delegate.h" -#include "ui/base/cursor/cursor.h" -#include "ui/base/hit_test.h" -#include "ui/views/controls/native/native_view_host.h" -#include "ui/views/view_constants_aura.h" -#include "ui/views/widget/widget.h" - -namespace views { - -class NativeViewHostAura::ClippingWindowDelegate : public aura::WindowDelegate { - public: - ClippingWindowDelegate() : native_view_(NULL) {} - virtual ~ClippingWindowDelegate() {} - - void set_native_view(aura::Window* native_view) { - native_view_ = native_view; - } - - virtual gfx::Size GetMinimumSize() const override { return gfx::Size(); } - virtual gfx::Size GetMaximumSize() const override { return gfx::Size(); } - virtual void OnBoundsChanged(const gfx::Rect& old_bounds, - const gfx::Rect& new_bounds) override {} - virtual gfx::NativeCursor GetCursor(const gfx::Point& point) override { - return gfx::kNullCursor; - } - virtual int GetNonClientComponent(const gfx::Point& point) const override { - return HTCLIENT; - } - virtual bool ShouldDescendIntoChildForEventHandling( - aura::Window* child, - const gfx::Point& location) override { return true; } - virtual bool CanFocus() override { - // Ask the hosted native view's delegate because directly calling - // aura::Window::CanFocus() will call back into this when checking whether - // parents can focus. - return native_view_ && native_view_->delegate() - ? native_view_->delegate()->CanFocus() - : true; - } - virtual void OnCaptureLost() override {} - virtual void OnPaint(gfx::Canvas* canvas) override {} - virtual void OnDeviceScaleFactorChanged(float device_scale_factor) override {} - virtual void OnWindowDestroying(aura::Window* window) override {} - virtual void OnWindowDestroyed(aura::Window* window) override {} - virtual void OnWindowTargetVisibilityChanged(bool visible) override {} - virtual bool HasHitTestMask() const override { return false; } - virtual void GetHitTestMask(gfx::Path* mask) const override {} - - private: - aura::Window* native_view_; -}; - -NativeViewHostAura::NativeViewHostAura(NativeViewHost* host) - : host_(host), - clipping_window_delegate_(new ClippingWindowDelegate()), - clipping_window_(clipping_window_delegate_.get()) { - // Set the type so descendant views (including popups) get positioned - // appropriately. - clipping_window_.SetType(ui::wm::WINDOW_TYPE_CONTROL); - clipping_window_.Init(aura::WINDOW_LAYER_NOT_DRAWN); - clipping_window_.set_owned_by_parent(false); - clipping_window_.SetName("NativeViewHostAuraClip"); - clipping_window_.layer()->SetMasksToBounds(true); - clipping_window_.SetProperty(views::kHostViewKey, static_cast<View*>(host_)); -} - -NativeViewHostAura::~NativeViewHostAura() { - if (host_->native_view()) { - host_->native_view()->RemoveObserver(this); - host_->native_view()->ClearProperty(views::kHostViewKey); - host_->native_view()->ClearProperty(aura::client::kHostWindowKey); - clipping_window_.ClearProperty(views::kHostViewKey); - if (host_->native_view()->parent() == &clipping_window_) - clipping_window_.RemoveChild(host_->native_view()); - } -} - -//////////////////////////////////////////////////////////////////////////////// -// NativeViewHostAura, NativeViewHostWrapper implementation: -void NativeViewHostAura::AttachNativeView() { - clipping_window_delegate_->set_native_view(host_->native_view()); - host_->native_view()->AddObserver(this); - host_->native_view()->SetProperty(views::kHostViewKey, - static_cast<View*>(host_)); - AddClippingWindow(); -} - -void NativeViewHostAura::NativeViewDetaching(bool destroyed) { - clipping_window_delegate_->set_native_view(NULL); - RemoveClippingWindow(); - if (!destroyed) { - host_->native_view()->RemoveObserver(this); - host_->native_view()->ClearProperty(views::kHostViewKey); - host_->native_view()->ClearProperty(aura::client::kHostWindowKey); - host_->native_view()->Hide(); - if (host_->native_view()->parent()) - Widget::ReparentNativeView(host_->native_view(), NULL); - } -} - -void NativeViewHostAura::AddedToWidget() { - if (!host_->native_view()) - return; - - AddClippingWindow(); - if (host_->IsDrawn()) - host_->native_view()->Show(); - else - host_->native_view()->Hide(); - host_->Layout(); -} - -void NativeViewHostAura::RemovedFromWidget() { - if (host_->native_view()) { - host_->native_view()->Hide(); - host_->native_view()->ClearProperty(aura::client::kHostWindowKey); - if (host_->native_view()->parent()) - host_->native_view()->parent()->RemoveChild(host_->native_view()); - RemoveClippingWindow(); - } -} - -void NativeViewHostAura::InstallClip(int x, int y, int w, int h) { - clip_rect_.reset( - new gfx::Rect(host_->ConvertRectToWidget(gfx::Rect(x, y, w, h)))); -} - -bool NativeViewHostAura::HasInstalledClip() { - return clip_rect_; -} - -void NativeViewHostAura::UninstallClip() { - clip_rect_.reset(); -} - -void NativeViewHostAura::ShowWidget(int x, int y, int w, int h) { - int width = w; - int height = h; - if (host_->fast_resize()) { - gfx::Point origin(x, y); - views::View::ConvertPointFromWidget(host_, &origin); - InstallClip(origin.x(), origin.y(), w, h); - width = host_->native_view()->bounds().width(); - height = host_->native_view()->bounds().height(); - } - clipping_window_.SetBounds(clip_rect_ ? *clip_rect_ - : gfx::Rect(x, y, w, h)); - - gfx::Point clip_offset = clipping_window_.bounds().origin(); - host_->native_view()->SetBounds( - gfx::Rect(x - clip_offset.x(), y - clip_offset.y(), width, height)); - host_->native_view()->Show(); - clipping_window_.Show(); -} - -void NativeViewHostAura::HideWidget() { - host_->native_view()->Hide(); - clipping_window_.Hide(); -} - -void NativeViewHostAura::SetFocus() { - aura::Window* window = host_->native_view(); - aura::client::FocusClient* client = aura::client::GetFocusClient(window); - if (client) - client->FocusWindow(window); -} - -gfx::NativeViewAccessible NativeViewHostAura::GetNativeViewAccessible() { - return NULL; -} - -gfx::NativeCursor NativeViewHostAura::GetCursor(int x, int y) { - if (host_->native_view()) - return host_->native_view()->GetCursor(gfx::Point(x, y)); - return gfx::kNullCursor; -} - -void NativeViewHostAura::OnWindowDestroying(aura::Window* window) { - DCHECK(window == host_->native_view()); - clipping_window_delegate_->set_native_view(NULL); -} - -void NativeViewHostAura::OnWindowDestroyed(aura::Window* window) { - DCHECK(window == host_->native_view()); - host_->NativeViewDestroyed(); -} - -// static -NativeViewHostWrapper* NativeViewHostWrapper::CreateWrapper( - NativeViewHost* host) { - return new NativeViewHostAura(host); -} - -void NativeViewHostAura::AddClippingWindow() { - RemoveClippingWindow(); - - host_->native_view()->SetProperty(aura::client::kHostWindowKey, - host_->GetWidget()->GetNativeView()); - Widget::ReparentNativeView(host_->native_view(), - &clipping_window_); - if (host_->GetWidget()->GetNativeView()) { - Widget::ReparentNativeView(&clipping_window_, - host_->GetWidget()->GetNativeView()); - } -} - -void NativeViewHostAura::RemoveClippingWindow() { - clipping_window_.Hide(); - if (host_->native_view()) - host_->native_view()->ClearProperty(aura::client::kHostWindowKey); - - if (host_->native_view()->parent() == &clipping_window_) { - if (host_->GetWidget() && host_->GetWidget()->GetNativeView()) { - Widget::ReparentNativeView(host_->native_view(), - host_->GetWidget()->GetNativeView()); - } else { - clipping_window_.RemoveChild(host_->native_view()); - } - host_->native_view()->SetBounds(clipping_window_.bounds()); - } - if (clipping_window_.parent()) - clipping_window_.parent()->RemoveChild(&clipping_window_); -} - -} // namespace views
diff --git a/ui/views/controls/native/native_view_host_aura.h b/ui/views/controls/native/native_view_host_aura.h deleted file mode 100644 index 149bb41..0000000 --- a/ui/views/controls/native/native_view_host_aura.h +++ /dev/null
@@ -1,73 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_NATIVE_NATIVE_VIEW_HOST_AURA_H_ -#define UI_VIEWS_CONTROLS_NATIVE_NATIVE_VIEW_HOST_AURA_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "ui/aura/window.h" -#include "ui/aura/window_observer.h" -#include "ui/views/controls/native/native_view_host_wrapper.h" -#include "ui/views/views_export.h" - -namespace views { - -class NativeViewHost; - -// Aura implementation of NativeViewHostWrapper. -class VIEWS_EXPORT NativeViewHostAura : public NativeViewHostWrapper, - public aura::WindowObserver { - public: - explicit NativeViewHostAura(NativeViewHost* host); - virtual ~NativeViewHostAura(); - - // Overridden from NativeViewHostWrapper: - virtual void AttachNativeView() override; - virtual void NativeViewDetaching(bool destroyed) override; - virtual void AddedToWidget() override; - virtual void RemovedFromWidget() override; - virtual void InstallClip(int x, int y, int w, int h) override; - virtual bool HasInstalledClip() override; - virtual void UninstallClip() override; - virtual void ShowWidget(int x, int y, int w, int h) override; - virtual void HideWidget() override; - virtual void SetFocus() override; - virtual gfx::NativeViewAccessible GetNativeViewAccessible() override; - virtual gfx::NativeCursor GetCursor(int x, int y) override; - - private: - friend class NativeViewHostAuraTest; - - class ClippingWindowDelegate; - - // Overridden from aura::WindowObserver: - virtual void OnWindowDestroying(aura::Window* window) override; - virtual void OnWindowDestroyed(aura::Window* window) override; - - // Reparents the native view with the clipping window existing between it and - // its old parent, so that the fast resize path works. - void AddClippingWindow(); - - // If the native view has been reparented via AddClippingWindow, this call - // undoes it. - void RemoveClippingWindow(); - - // Our associated NativeViewHost. - NativeViewHost* host_; - - scoped_ptr<ClippingWindowDelegate> clipping_window_delegate_; - - // Window that exists between the native view and the parent that allows for - // clipping to occur. This is positioned in the coordinate space of - // host_->GetWidget(). - aura::Window clipping_window_; - scoped_ptr<gfx::Rect> clip_rect_; - - DISALLOW_COPY_AND_ASSIGN(NativeViewHostAura); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_NATIVE_NATIVE_VIEW_HOST_AURA_H_
diff --git a/ui/views/controls/native/native_view_host_aura_unittest.cc b/ui/views/controls/native/native_view_host_aura_unittest.cc deleted file mode 100644 index 1a40ab7..0000000 --- a/ui/views/controls/native/native_view_host_aura_unittest.cc +++ /dev/null
@@ -1,349 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/native/native_view_host_aura.h" - -#include "base/basictypes.h" -#include "base/memory/scoped_ptr.h" -#include "ui/aura/client/aura_constants.h" -#include "ui/aura/window.h" -#include "ui/base/cursor/cursor.h" -#include "ui/views/controls/native/native_view_host.h" -#include "ui/views/controls/native/native_view_host_test_base.h" -#include "ui/views/view.h" -#include "ui/views/view_constants_aura.h" -#include "ui/views/widget/widget.h" - -namespace views { - -// Observer watching for window visibility and bounds change events. This is -// used to verify that the child and clipping window operations are done in the -// right order. -class NativeViewHostWindowObserver : public aura::WindowObserver { - public: - enum EventType { - EVENT_NONE, - EVENT_SHOWN, - EVENT_HIDDEN, - EVENT_BOUNDS_CHANGED, - }; - - struct EventDetails { - EventType type; - aura::Window* window; - gfx::Rect bounds; - bool operator!=(const EventDetails& rhs) { - return type != rhs.type || window != rhs.window || bounds != rhs.bounds; - } - }; - - NativeViewHostWindowObserver() {} - virtual ~NativeViewHostWindowObserver() {} - - const std::vector<EventDetails>& events() const { return events_; } - - // aura::WindowObserver overrides - virtual void OnWindowVisibilityChanged(aura::Window* window, - bool visible) override { - EventDetails event; - event.type = visible ? EVENT_SHOWN : EVENT_HIDDEN; - event.window = window; - event.bounds = window->GetBoundsInRootWindow(); - - // Dedupe events as a single Hide() call can result in several - // notifications. - if (events_.size() == 0u || events_.back() != event) - events_.push_back(event); - } - - virtual void OnWindowBoundsChanged(aura::Window* window, - const gfx::Rect& old_bounds, - const gfx::Rect& new_bounds) override { - EventDetails event; - event.type = EVENT_BOUNDS_CHANGED; - event.window = window; - event.bounds = window->GetBoundsInRootWindow(); - events_.push_back(event); - } - - private: - std::vector<EventDetails> events_; - gfx::Rect bounds_at_visibility_changed_; - - DISALLOW_COPY_AND_ASSIGN(NativeViewHostWindowObserver); -}; - -class NativeViewHostAuraTest : public test::NativeViewHostTestBase { - public: - NativeViewHostAuraTest() { - } - - NativeViewHostAura* native_host() { - return static_cast<NativeViewHostAura*>(GetNativeWrapper()); - } - - Widget* child() { - return child_.get(); - } - - aura::Window* clipping_window() { return &(native_host()->clipping_window_); } - - void CreateHost() { - CreateTopLevel(); - CreateTestingHost(); - child_.reset(CreateChildForHost(toplevel()->GetNativeView(), - toplevel()->GetRootView(), - new View, - host())); - } - - private: - scoped_ptr<Widget> child_; - - DISALLOW_COPY_AND_ASSIGN(NativeViewHostAuraTest); -}; - -// Verifies NativeViewHostAura stops observing native view on destruction. -TEST_F(NativeViewHostAuraTest, StopObservingNativeViewOnDestruct) { - CreateHost(); - aura::Window* child_win = child()->GetNativeView(); - NativeViewHostAura* aura_host = native_host(); - - EXPECT_TRUE(child_win->HasObserver(aura_host)); - DestroyHost(); - EXPECT_FALSE(child_win->HasObserver(aura_host)); -} - -// Tests that the kHostViewKey is correctly set and cleared. -TEST_F(NativeViewHostAuraTest, HostViewPropertyKey) { - // Create the NativeViewHost and attach a NativeView. - CreateHost(); - aura::Window* child_win = child()->GetNativeView(); - EXPECT_EQ(host(), child_win->GetProperty(views::kHostViewKey)); - EXPECT_EQ(host()->GetWidget()->GetNativeView(), - child_win->GetProperty(aura::client::kHostWindowKey)); - EXPECT_EQ(host(), clipping_window()->GetProperty(views::kHostViewKey)); - - host()->Detach(); - EXPECT_FALSE(child_win->GetProperty(views::kHostViewKey)); - EXPECT_FALSE(child_win->GetProperty(aura::client::kHostWindowKey)); - EXPECT_TRUE(clipping_window()->GetProperty(views::kHostViewKey)); - - host()->Attach(child_win); - EXPECT_EQ(host(), child_win->GetProperty(views::kHostViewKey)); - EXPECT_EQ(host()->GetWidget()->GetNativeView(), - child_win->GetProperty(aura::client::kHostWindowKey)); - EXPECT_EQ(host(), clipping_window()->GetProperty(views::kHostViewKey)); - - DestroyHost(); - EXPECT_FALSE(child_win->GetProperty(views::kHostViewKey)); - EXPECT_FALSE(child_win->GetProperty(aura::client::kHostWindowKey)); -} - -// Tests that the NativeViewHost reports the cursor set on its native view. -TEST_F(NativeViewHostAuraTest, CursorForNativeView) { - CreateHost(); - - toplevel()->SetCursor(ui::kCursorHand); - child()->SetCursor(ui::kCursorWait); - ui::MouseEvent move_event(ui::ET_MOUSE_MOVED, gfx::Point(0, 0), - gfx::Point(0, 0), 0, 0); - - EXPECT_EQ(ui::kCursorWait, host()->GetCursor(move_event).native_type()); - - DestroyHost(); -} - -// Test that destroying the top level widget before destroying the attached -// NativeViewHost works correctly. Specifically the associated NVH should be -// destroyed and there shouldn't be any errors. -TEST_F(NativeViewHostAuraTest, DestroyWidget) { - ResetHostDestroyedCount(); - CreateHost(); - ReleaseHost(); - EXPECT_EQ(0, host_destroyed_count()); - DestroyTopLevel(); - EXPECT_EQ(1, host_destroyed_count()); -} - -// Test that the fast resize path places the clipping and content windows were -// they are supposed to be. -TEST_F(NativeViewHostAuraTest, FastResizePath) { - CreateHost(); - toplevel()->SetBounds(gfx::Rect(20, 20, 100, 100)); - - // Without fast resize, the clipping window should size to the native view - // with the native view positioned at the origin of the clipping window and - // the clipping window positioned where the native view was requested. - host()->set_fast_resize(false); - native_host()->ShowWidget(5, 10, 100, 100); - EXPECT_EQ(gfx::Rect(0, 0, 100, 100).ToString(), - host()->native_view()->bounds().ToString()); - EXPECT_EQ(gfx::Rect(5, 10, 100, 100).ToString(), - clipping_window()->bounds().ToString()); - - // With fast resize, the native view should remain the same size but be - // clipped the requested size. - host()->set_fast_resize(true); - native_host()->ShowWidget(10, 25, 50, 50); - EXPECT_EQ(gfx::Rect(0, 0, 100, 100).ToString(), - host()->native_view()->bounds().ToString()); - EXPECT_EQ(gfx::Rect(10, 25, 50, 50).ToString(), - clipping_window()->bounds().ToString()); - - // Turning off fast resize should make the native view start resizing again. - host()->set_fast_resize(false); - native_host()->ShowWidget(10, 25, 50, 50); - EXPECT_EQ(gfx::Rect(0, 0, 50, 50).ToString(), - host()->native_view()->bounds().ToString()); - EXPECT_EQ(gfx::Rect(10, 25, 50, 50).ToString(), - clipping_window()->bounds().ToString()); - - DestroyHost(); -} - -// Test installing and uninstalling a clip. -TEST_F(NativeViewHostAuraTest, InstallClip) { - CreateHost(); - toplevel()->SetBounds(gfx::Rect(20, 20, 100, 100)); - - // Without a clip, the clipping window should always be positioned at the - // requested coordinates with the native view positioned at the origin of the - // clipping window. - native_host()->ShowWidget(10, 20, 100, 100); - EXPECT_EQ(gfx::Rect(0, 0, 100, 100).ToString(), - host()->native_view()->bounds().ToString()); - EXPECT_EQ(gfx::Rect(10, 20, 100, 100).ToString(), - clipping_window()->bounds().ToString()); - - // Clip to the bottom right quarter of the native view. - native_host()->InstallClip(60, 70, 50, 50); - native_host()->ShowWidget(10, 20, 100, 100); - EXPECT_EQ(gfx::Rect(-50, -50, 100, 100).ToString(), - host()->native_view()->bounds().ToString()); - EXPECT_EQ(gfx::Rect(60, 70, 50, 50).ToString(), - clipping_window()->bounds().ToString()); - - // Clip to the center of the native view. - native_host()->InstallClip(35, 45, 50, 50); - native_host()->ShowWidget(10, 20, 100, 100); - EXPECT_EQ(gfx::Rect(-25, -25, 100, 100).ToString(), - host()->native_view()->bounds().ToString()); - EXPECT_EQ(gfx::Rect(35, 45, 50, 50).ToString(), - clipping_window()->bounds().ToString()); - - // Uninstalling the clip should make the clipping window match the native view - // again. - native_host()->UninstallClip(); - native_host()->ShowWidget(10, 20, 100, 100); - EXPECT_EQ(gfx::Rect(0, 0, 100, 100).ToString(), - host()->native_view()->bounds().ToString()); - EXPECT_EQ(gfx::Rect(10, 20, 100, 100).ToString(), - clipping_window()->bounds().ToString()); - - DestroyHost(); -} - -// Ensure native view is parented to the root window after detaching. This is -// a regression test for http://crbug.com/389261. -TEST_F(NativeViewHostAuraTest, ParentAfterDetach) { - CreateHost(); - aura::Window* child_win = child()->GetNativeView(); - aura::Window* root_window = child_win->GetRootWindow(); - aura::WindowTreeHost* child_win_tree_host = child_win->GetHost(); - - host()->Detach(); - EXPECT_EQ(root_window, child_win->GetRootWindow()); - EXPECT_EQ(child_win_tree_host, child_win->GetHost()); - - DestroyHost(); -} - -// Ensure the clipping window is hidden before setting the native view's bounds. -// This is a regression test for http://crbug.com/388699. -TEST_F(NativeViewHostAuraTest, RemoveClippingWindowOrder) { - CreateHost(); - toplevel()->SetBounds(gfx::Rect(20, 20, 100, 100)); - native_host()->ShowWidget(10, 20, 100, 100); - - NativeViewHostWindowObserver test_observer; - clipping_window()->AddObserver(&test_observer); - child()->GetNativeView()->AddObserver(&test_observer); - - host()->Detach(); - - ASSERT_EQ(3u, test_observer.events().size()); - EXPECT_EQ(NativeViewHostWindowObserver::EVENT_HIDDEN, - test_observer.events()[0].type); - EXPECT_EQ(clipping_window(), test_observer.events()[0].window); - EXPECT_EQ(NativeViewHostWindowObserver::EVENT_BOUNDS_CHANGED, - test_observer.events()[1].type); - EXPECT_EQ(child()->GetNativeView(), test_observer.events()[1].window); - EXPECT_EQ(NativeViewHostWindowObserver::EVENT_HIDDEN, - test_observer.events()[2].type); - EXPECT_EQ(child()->GetNativeView(), test_observer.events()[2].window); - - clipping_window()->RemoveObserver(&test_observer); - child()->GetNativeView()->RemoveObserver(&test_observer); - - DestroyHost(); -} - -// Ensure the native view receives the correct bounds notification when it is -// attached. This is a regression test for https://crbug.com/399420. -TEST_F(NativeViewHostAuraTest, Attach) { - CreateHost(); - host()->Detach(); - - child()->GetNativeView()->SetBounds(gfx::Rect(0, 0, 0, 0)); - toplevel()->SetBounds(gfx::Rect(0, 0, 100, 100)); - host()->SetBounds(10, 10, 80, 80); - - NativeViewHostWindowObserver test_observer; - child()->GetNativeView()->AddObserver(&test_observer); - - host()->Attach(child()->GetNativeView()); - - ASSERT_EQ(3u, test_observer.events().size()); - EXPECT_EQ(NativeViewHostWindowObserver::EVENT_BOUNDS_CHANGED, - test_observer.events()[0].type); - EXPECT_EQ(child()->GetNativeView(), test_observer.events()[0].window); - EXPECT_EQ(gfx::Rect(10, 10, 80, 80).ToString(), - test_observer.events()[0].bounds.ToString()); - EXPECT_EQ(NativeViewHostWindowObserver::EVENT_SHOWN, - test_observer.events()[1].type); - EXPECT_EQ(child()->GetNativeView(), test_observer.events()[1].window); - EXPECT_EQ(gfx::Rect(10, 10, 80, 80).ToString(), - test_observer.events()[1].bounds.ToString()); - EXPECT_EQ(NativeViewHostWindowObserver::EVENT_SHOWN, - test_observer.events()[2].type); - EXPECT_EQ(clipping_window(), test_observer.events()[2].window); - EXPECT_EQ(gfx::Rect(10, 10, 80, 80).ToString(), - test_observer.events()[2].bounds.ToString()); - - child()->GetNativeView()->RemoveObserver(&test_observer); - DestroyHost(); -} - -// Ensure the clipping window is hidden with the native view. This is a -// regression test for https://crbug.com/408877. -TEST_F(NativeViewHostAuraTest, SimpleShowAndHide) { - CreateHost(); - - toplevel()->SetBounds(gfx::Rect(20, 20, 100, 100)); - toplevel()->Show(); - - host()->SetBounds(10, 10, 80, 80); - EXPECT_TRUE(clipping_window()->IsVisible()); - EXPECT_TRUE(child()->IsVisible()); - - host()->SetVisible(false); - EXPECT_FALSE(clipping_window()->IsVisible()); - EXPECT_FALSE(child()->IsVisible()); - - DestroyHost(); - DestroyTopLevel(); -} - -} // namespace views
diff --git a/ui/views/controls/native/native_view_host_test_base.cc b/ui/views/controls/native/native_view_host_test_base.cc deleted file mode 100644 index f8f957c..0000000 --- a/ui/views/controls/native/native_view_host_test_base.cc +++ /dev/null
@@ -1,80 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/native/native_view_host_test_base.h" - -#include "ui/views/controls/native/native_view_host.h" -#include "ui/views/widget/widget.h" - -namespace views { -namespace test { - -// Testing wrapper of the NativeViewHost. -class NativeViewHostTestBase::NativeViewHostTesting : public NativeViewHost { - public: - explicit NativeViewHostTesting(NativeViewHostTestBase* owner) - : owner_(owner) {} - virtual ~NativeViewHostTesting() { owner_->host_destroyed_count_++; } - - private: - NativeViewHostTestBase* owner_; - - DISALLOW_COPY_AND_ASSIGN(NativeViewHostTesting); -}; - -NativeViewHostTestBase::NativeViewHostTestBase() : host_destroyed_count_(0) { -} - -NativeViewHostTestBase::~NativeViewHostTestBase() { -} - -void NativeViewHostTestBase::CreateTopLevel() { - toplevel_.reset(new Widget); - Widget::InitParams toplevel_params = - CreateParams(Widget::InitParams::TYPE_WINDOW); - toplevel_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - toplevel_->Init(toplevel_params); -} - -void NativeViewHostTestBase::CreateTestingHost() { - host_.reset(new NativeViewHostTesting(this)); -} - -Widget* NativeViewHostTestBase::CreateChildForHost( - gfx::NativeView native_parent_view, - View* parent_view, - View* contents_view, - NativeViewHost* host) { - Widget* child = new Widget; - Widget::InitParams child_params(Widget::InitParams::TYPE_CONTROL); - child_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - child_params.parent = native_parent_view; - child->Init(child_params); - child->SetContentsView(contents_view); - - // Owned by |parent_view|. - parent_view->AddChildView(host); - host->Attach(child->GetNativeView()); - - return child; -} - -void NativeViewHostTestBase::DestroyTopLevel() { - toplevel_.reset(); -} - -void NativeViewHostTestBase::DestroyHost() { - host_.reset(); -} - -NativeViewHost* NativeViewHostTestBase::ReleaseHost() { - return host_.release(); -} - -NativeViewHostWrapper* NativeViewHostTestBase::GetNativeWrapper() { - return host_->native_wrapper_.get(); -} - -} // namespace test -} // namespace views
diff --git a/ui/views/controls/native/native_view_host_test_base.h b/ui/views/controls/native/native_view_host_test_base.h deleted file mode 100644 index ce98fb4..0000000 --- a/ui/views/controls/native/native_view_host_test_base.h +++ /dev/null
@@ -1,62 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/macros.h" -#include "base/memory/scoped_ptr.h" -#include "ui/views/test/views_test_base.h" - -namespace views { - -class NativeViewHost; -class NativeViewHostWrapper; -class Widget; - -namespace test { - -// Base class for NativeViewHost tests on different platforms. -class NativeViewHostTestBase : public ViewsTestBase { - public: - NativeViewHostTestBase(); - virtual ~NativeViewHostTestBase(); - - // Create the |toplevel_| widget. - void CreateTopLevel(); - - // Create a testing |host_| that tracks destructor calls. - void CreateTestingHost(); - - // The number of times a host created by CreateHost() has been destroyed. - int host_destroyed_count() { return host_destroyed_count_; } - void ResetHostDestroyedCount() { host_destroyed_count_ = 0; } - - // Create a child widget whose native parent is |native_parent_view|, uses - // |contents_view|, and is attached to |host| which is added as a child to - // |parent_view|. This effectively borrows the native content view from a - // newly created child Widget, and attaches it to |host|. - Widget* CreateChildForHost(gfx::NativeView native_parent_view, - View* parent_view, - View* contents_view, - NativeViewHost* host); - - Widget* toplevel() { return toplevel_.get(); } - void DestroyTopLevel(); - - NativeViewHost* host() { return host_.get(); } - void DestroyHost(); - NativeViewHost* ReleaseHost(); - - NativeViewHostWrapper* GetNativeWrapper(); - - private: - class NativeViewHostTesting; - - scoped_ptr<Widget> toplevel_; - scoped_ptr<NativeViewHost> host_; - int host_destroyed_count_; - - DISALLOW_COPY_AND_ASSIGN(NativeViewHostTestBase); -}; - -} // namespace test -} // namespace views
diff --git a/ui/views/controls/native/native_view_host_unittest.cc b/ui/views/controls/native/native_view_host_unittest.cc deleted file mode 100644 index d5fb543..0000000 --- a/ui/views/controls/native/native_view_host_unittest.cc +++ /dev/null
@@ -1,273 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/native/native_view_host.h" - -#include "base/basictypes.h" -#include "base/memory/scoped_ptr.h" -#include "ui/aura/window.h" -#include "ui/views/controls/native/native_view_host_test_base.h" -#include "ui/views/test/views_test_base.h" -#include "ui/views/widget/widget.h" - -namespace views { - -class NativeViewHostTest : public test::NativeViewHostTestBase { - public: - NativeViewHostTest() { - } - - virtual void SetUp() override { - ViewsTestBase::SetUp(); - CreateTopLevel(); - } - - private: - DISALLOW_COPY_AND_ASSIGN(NativeViewHostTest); -}; - -namespace { - -// View implementation used by NativeViewHierarchyChanged to count number of -// times NativeViewHierarchyChanged() is invoked. -class NativeViewHierarchyChangedTestView : public View { - public: - NativeViewHierarchyChangedTestView() : notification_count_(0) { - } - - void ResetCount() { - notification_count_ = 0; - } - - int notification_count() const { return notification_count_; } - - // Overriden from View: - virtual void NativeViewHierarchyChanged() override { - ++notification_count_; - View::NativeViewHierarchyChanged(); - } - - private: - int notification_count_; - - DISALLOW_COPY_AND_ASSIGN(NativeViewHierarchyChangedTestView); -}; - -aura::Window* GetNativeParent(aura::Window* window) { - return window->parent(); -} - -class ViewHierarchyChangedTestHost : public NativeViewHost { - public: - ViewHierarchyChangedTestHost() - : num_parent_changes_(0) { - } - - void ResetParentChanges() { - num_parent_changes_ = 0; - } - - int num_parent_changes() const { - return num_parent_changes_; - } - - // Overriden from NativeViewHost: - virtual void ViewHierarchyChanged( - const ViewHierarchyChangedDetails& details) override { - gfx::NativeView parent_before = native_view() ? - GetNativeParent(native_view()) : NULL; - NativeViewHost::ViewHierarchyChanged(details); - gfx::NativeView parent_after = native_view() ? - GetNativeParent(native_view()) : NULL; - if (parent_before != parent_after) - ++num_parent_changes_; - } - - private: - int num_parent_changes_; - - DISALLOW_COPY_AND_ASSIGN(ViewHierarchyChangedTestHost); -}; - -} // namespace - -// Verifies NativeViewHierarchyChanged is sent. -TEST_F(NativeViewHostTest, NativeViewHierarchyChanged) { - // Create a child widget. - NativeViewHierarchyChangedTestView* test_view = - new NativeViewHierarchyChangedTestView; - NativeViewHost* host = new NativeViewHost; - scoped_ptr<Widget> child(CreateChildForHost(toplevel()->GetNativeView(), - toplevel()->GetRootView(), - test_view, - host)); -#if defined(USE_AURA) - // Two notifications are generated from inserting the native view into the - // clipping window and then inserting the clipping window into the root - // window. - EXPECT_EQ(2, test_view->notification_count()); -#else - EXPECT_EQ(0, test_view->notification_count()); -#endif - test_view->ResetCount(); - - // Detaching should send a NativeViewHierarchyChanged() notification and - // change the parent. - host->Detach(); -#if defined(USE_AURA) - // Two notifications are generated from removing the native view from the - // clipping window and then reparenting it to the root window. - EXPECT_EQ(2, test_view->notification_count()); -#else - EXPECT_EQ(1, test_view->notification_count()); -#endif - EXPECT_NE(toplevel()->GetNativeView(), - GetNativeParent(child->GetNativeView())); - test_view->ResetCount(); - - // Attaching should send a NativeViewHierarchyChanged() notification and - // reset the parent. - host->Attach(child->GetNativeView()); -#if defined(USE_AURA) - // There is a clipping window inserted above the native view that needs to be - // accounted for when looking at the relationship between the native views. - EXPECT_EQ(2, test_view->notification_count()); - EXPECT_EQ(toplevel()->GetNativeView(), - GetNativeParent(GetNativeParent(child->GetNativeView()))); -#else - EXPECT_EQ(1, test_view->notification_count()); - EXPECT_EQ(toplevel()->GetNativeView(), - GetNativeParent(child->GetNativeView())); -#endif -} - -// Verifies ViewHierarchyChanged handles NativeViewHost remove, add and move -// (reparent) operations with correct parent changes. -// This exercises the non-recursive code paths in -// View::PropagateRemoveNotifications() and View::PropagateAddNotifications(). -TEST_F(NativeViewHostTest, ViewHierarchyChangedForHost) { - // Original tree: - // toplevel - // +-- host0 (NativeViewHost) - // +-- child0 (Widget, attached to host0) - // +-- test_host (ViewHierarchyChangedTestHost) - // +-- test_child (Widget, attached to test_host) - // +-- host1 (NativeViewHost) - // +-- child1 (Widget, attached to host1) - - // Add two children widgets attached to a NativeViewHost, and a test - // grandchild as child widget of host0. - NativeViewHost* host0 = new NativeViewHost; - scoped_ptr<Widget> child0(CreateChildForHost(toplevel()->GetNativeView(), - toplevel()->GetRootView(), - new View, - host0)); - NativeViewHost* host1 = new NativeViewHost; - scoped_ptr<Widget> child1(CreateChildForHost(toplevel()->GetNativeView(), - toplevel()->GetRootView(), - new View, - host1)); - ViewHierarchyChangedTestHost* test_host = new ViewHierarchyChangedTestHost; - scoped_ptr<Widget> test_child(CreateChildForHost(host0->native_view(), - host0, - new View, - test_host)); - - // Remove test_host from host0, expect 1 parent change. - test_host->ResetParentChanges(); - EXPECT_EQ(0, test_host->num_parent_changes()); - host0->RemoveChildView(test_host); - EXPECT_EQ(1, test_host->num_parent_changes()); - - // Add test_host back to host0, expect 1 parent change. - test_host->ResetParentChanges(); - EXPECT_EQ(0, test_host->num_parent_changes()); - host0->AddChildView(test_host); - EXPECT_EQ(1, test_host->num_parent_changes()); - - // Reparent test_host to host1, expect no parent change because the old and - // new parents, host0 and host1, belong to the same toplevel widget. - test_host->ResetParentChanges(); - EXPECT_EQ(0, test_host->num_parent_changes()); - host1->AddChildView(test_host); - EXPECT_EQ(0, test_host->num_parent_changes()); - - // Reparent test_host to contents view of child0, expect 2 parent changes - // because the old parent belongs to the toplevel widget whereas the new - // parent belongs to the child0. - test_host->ResetParentChanges(); - EXPECT_EQ(0, test_host->num_parent_changes()); - child0->GetContentsView()->AddChildView(test_host); - EXPECT_EQ(2, test_host->num_parent_changes()); -} - -// Verifies ViewHierarchyChanged handles NativeViewHost's parent remove, add and -// move (reparent) operations with correct parent changes. -// This exercises the recursive code paths in -// View::PropagateRemoveNotifications() and View::PropagateAddNotifications(). -TEST_F(NativeViewHostTest, ViewHierarchyChangedForHostParent) { - // Original tree: - // toplevel - // +-- view0 (View) - // +-- host0 (NativeViewHierarchyChangedTestHost) - // +-- child0 (Widget, attached to host0) - // +-- view1 (View) - // +-- host1 (NativeViewHierarchyChangedTestHost) - // +-- child1 (Widget, attached to host1) - - // Add two children views. - View* view0 = new View; - toplevel()->GetRootView()->AddChildView(view0); - View* view1 = new View; - toplevel()->GetRootView()->AddChildView(view1); - - // To each child view, add a child widget. - ViewHierarchyChangedTestHost* host0 = new ViewHierarchyChangedTestHost; - scoped_ptr<Widget> child0(CreateChildForHost(toplevel()->GetNativeView(), - view0, - new View, - host0)); - ViewHierarchyChangedTestHost* host1 = new ViewHierarchyChangedTestHost; - scoped_ptr<Widget> child1(CreateChildForHost(toplevel()->GetNativeView(), - view1, - new View, - host1)); - - // Remove view0 from top level, expect 1 parent change. - host0->ResetParentChanges(); - EXPECT_EQ(0, host0->num_parent_changes()); - toplevel()->GetRootView()->RemoveChildView(view0); - EXPECT_EQ(1, host0->num_parent_changes()); - - // Add view0 back to top level, expect 1 parent change. - host0->ResetParentChanges(); - EXPECT_EQ(0, host0->num_parent_changes()); - toplevel()->GetRootView()->AddChildView(view0); - EXPECT_EQ(1, host0->num_parent_changes()); - - // Reparent view0 to view1, expect no parent change because the old and new - // parents of both view0 and view1 belong to the same toplevel widget. - host0->ResetParentChanges(); - host1->ResetParentChanges(); - EXPECT_EQ(0, host0->num_parent_changes()); - EXPECT_EQ(0, host1->num_parent_changes()); - view1->AddChildView(view0); - EXPECT_EQ(0, host0->num_parent_changes()); - EXPECT_EQ(0, host1->num_parent_changes()); - - // Restore original view hierarchy by adding back view0 to top level. - // Then, reparent view1 to contents view of child0. - // Expect 2 parent changes because the old parent belongs to the toplevel - // widget whereas the new parent belongs to the 1st child widget. - toplevel()->GetRootView()->AddChildView(view0); - host0->ResetParentChanges(); - host1->ResetParentChanges(); - EXPECT_EQ(0, host0->num_parent_changes()); - EXPECT_EQ(0, host1->num_parent_changes()); - child0->GetContentsView()->AddChildView(view1); - EXPECT_EQ(0, host0->num_parent_changes()); - EXPECT_EQ(2, host1->num_parent_changes()); -} - -} // namespace views
diff --git a/ui/views/controls/native/native_view_host_wrapper.h b/ui/views/controls/native/native_view_host_wrapper.h deleted file mode 100644 index 1f9330b..0000000 --- a/ui/views/controls/native/native_view_host_wrapper.h +++ /dev/null
@@ -1,81 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_NATIVE_NATIVE_VIEW_HOST_WRAPPER_H_ -#define UI_VIEWS_CONTROLS_NATIVE_NATIVE_VIEW_HOST_WRAPPER_H_ - -#include "ui/gfx/native_widget_types.h" -#include "ui/views/views_export.h" - -namespace views { - -class NativeViewHost; - -// An interface that implemented by an object that wraps a gfx::NativeView on -// a specific platform, used to perform platform specific operations on that -// native view when attached, detached, moved and sized. -class VIEWS_EXPORT NativeViewHostWrapper { - public: - virtual ~NativeViewHostWrapper() {} - - // Called at the end of NativeViewHost::Attach, allowing the wrapper to - // perform platform-specific operations that need to occur to complete - // attaching the gfx::NativeView. - virtual void AttachNativeView() = 0; - - // Called before the attached gfx::NativeView is detached from the - // NativeViewHost, allowing the wrapper to perform platform-specific - // cleanup. |destroyed| is true if the native view is detached - // because it's being destroyed, or false otherwise. - virtual void NativeViewDetaching(bool destroyed) = 0; - - // Called when our associated NativeViewHost is added to a View hierarchy - // rooted at a valid Widget. - virtual void AddedToWidget() = 0; - - // Called when our associated NativeViewHost is removed from a View hierarchy - // rooted at a valid Widget. - virtual void RemovedFromWidget() = 0; - - // Installs a clip on the gfx::NativeView. These values are in the coordinate - // space of the Widget, so if this method is called from ShowWidget - // then the values need to be translated. - virtual void InstallClip(int x, int y, int w, int h) = 0; - - // Whether or not a clip has been installed on the wrapped gfx::NativeView. - virtual bool HasInstalledClip() = 0; - - // Removes the clip installed on the gfx::NativeView by way of InstallClip. A - // following call to ShowWidget should occur after calling this method to - // position the gfx::NativeView correctly, since the clipping process may have - // adjusted its position. - virtual void UninstallClip() = 0; - - // Shows the gfx::NativeView at the specified position (relative to the parent - // native view). - virtual void ShowWidget(int x, int y, int w, int h) = 0; - - // Hides the gfx::NativeView. NOTE: this may be invoked when the native view - // is already hidden. - virtual void HideWidget() = 0; - - // Sets focus to the gfx::NativeView. - virtual void SetFocus() = 0; - - // Return the native view accessible corresponding to the wrapped native - // view. - virtual gfx::NativeViewAccessible GetNativeViewAccessible() = 0; - - // Returns the native cursor corresponding to the point (x, y) - // in the native view. - virtual gfx::NativeCursor GetCursor(int x, int y) = 0; - - // Creates a platform-specific instance of an object implementing this - // interface. - static NativeViewHostWrapper* CreateWrapper(NativeViewHost* host); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_NATIVE_NATIVE_VIEW_HOST_WRAPPER_H_
diff --git a/ui/views/controls/prefix_delegate.h b/ui/views/controls/prefix_delegate.h deleted file mode 100644 index 07d8598..0000000 --- a/ui/views/controls/prefix_delegate.h +++ /dev/null
@@ -1,34 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_PREFIX_DELEGATE_H_ -#define UI_VIEWS_CONTROLS_PREFIX_DELEGATE_H_ - -#include "ui/views/view.h" - -namespace views { - -// An interface used to expose lists of items for selection by text input. -class VIEWS_EXPORT PrefixDelegate : public View { - public: - // Returns the total number of selectable items. - virtual int GetRowCount() = 0; - - // Returns the row of the currently selected item, or -1 if no item is - // selected. - virtual int GetSelectedRow() = 0; - - // Sets the selection to the specified row. - virtual void SetSelectedRow(int row) = 0; - - // Returns the item at the specified row. - virtual base::string16 GetTextForRow(int row) = 0; - - protected: - virtual ~PrefixDelegate() {} -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_PREFIX_DELEGATE_H_
diff --git a/ui/views/controls/prefix_selector.cc b/ui/views/controls/prefix_selector.cc deleted file mode 100644 index c901edd..0000000 --- a/ui/views/controls/prefix_selector.cc +++ /dev/null
@@ -1,204 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/prefix_selector.h" - -#include "base/i18n/case_conversion.h" -#include "ui/base/ime/text_input_type.h" -#include "ui/gfx/range/range.h" -#include "ui/views/controls/prefix_delegate.h" -#include "ui/views/widget/widget.h" - -namespace views { - -namespace { - -const int64 kTimeBeforeClearingMS = 1000; - -void ConvertRectToScreen(const views::View* src, gfx::Rect* r) { - DCHECK(src); - - gfx::Point new_origin = r->origin(); - views::View::ConvertPointToScreen(src, &new_origin); - r->set_origin(new_origin); -} - -} // namespace - -PrefixSelector::PrefixSelector(PrefixDelegate* delegate) - : prefix_delegate_(delegate) { -} - -PrefixSelector::~PrefixSelector() { -} - -void PrefixSelector::OnViewBlur() { - ClearText(); -} - -void PrefixSelector::SetCompositionText( - const ui::CompositionText& composition) { -} - -void PrefixSelector::ConfirmCompositionText() { -} - -void PrefixSelector::ClearCompositionText() { -} - -void PrefixSelector::InsertText(const base::string16& text) { - OnTextInput(text); -} - -void PrefixSelector::InsertChar(base::char16 ch, int flags) { - OnTextInput(base::string16(1, ch)); -} - -gfx::NativeWindow PrefixSelector::GetAttachedWindow() const { - return prefix_delegate_->GetWidget()->GetNativeWindow(); -} - -ui::TextInputType PrefixSelector::GetTextInputType() const { - return ui::TEXT_INPUT_TYPE_TEXT; -} - -ui::TextInputMode PrefixSelector::GetTextInputMode() const { - return ui::TEXT_INPUT_MODE_DEFAULT; -} - -bool PrefixSelector::CanComposeInline() const { - return false; -} - -gfx::Rect PrefixSelector::GetCaretBounds() const { - gfx::Rect rect(prefix_delegate_->GetVisibleBounds().origin(), gfx::Size()); - // TextInputClient::GetCaretBounds is expected to return a value in screen - // coordinates. - ConvertRectToScreen(prefix_delegate_, &rect); - return rect; -} - -bool PrefixSelector::GetCompositionCharacterBounds(uint32 index, - gfx::Rect* rect) const { - // TextInputClient::GetCompositionCharacterBounds is expected to fill |rect| - // in screen coordinates and GetCaretBounds returns screen coordinates. - *rect = GetCaretBounds(); - return false; -} - -bool PrefixSelector::HasCompositionText() const { - return false; -} - -bool PrefixSelector::GetTextRange(gfx::Range* range) const { - *range = gfx::Range(); - return false; -} - -bool PrefixSelector::GetCompositionTextRange(gfx::Range* range) const { - *range = gfx::Range(); - return false; -} - -bool PrefixSelector::GetSelectionRange(gfx::Range* range) const { - *range = gfx::Range(); - return false; -} - -bool PrefixSelector::SetSelectionRange(const gfx::Range& range) { - return false; -} - -bool PrefixSelector::DeleteRange(const gfx::Range& range) { - return false; -} - -bool PrefixSelector::GetTextFromRange(const gfx::Range& range, - base::string16* text) const { - return false; -} - -void PrefixSelector::OnInputMethodChanged() { - ClearText(); -} - -bool PrefixSelector::ChangeTextDirectionAndLayoutAlignment( - base::i18n::TextDirection direction) { - return true; -} - -void PrefixSelector::ExtendSelectionAndDelete(size_t before, size_t after) { -} - -void PrefixSelector::EnsureCaretInRect(const gfx::Rect& rect) { -} - -void PrefixSelector::OnCandidateWindowShown() { -} - -void PrefixSelector::OnCandidateWindowUpdated() { -} - -void PrefixSelector::OnCandidateWindowHidden() { -} - -bool PrefixSelector::IsEditingCommandEnabled(int command_id) { - return false; -} - -void PrefixSelector::ExecuteEditingCommand(int command_id) { -} - -void PrefixSelector::OnTextInput(const base::string16& text) { - // Small hack to filter out 'tab' and 'enter' input, as the expectation is - // that they are control characters and will not affect the currently-active - // prefix. - if (text.length() == 1 && - (text[0] == L'\t' || text[0] == L'\r' || text[0] == L'\n')) - return; - - const int row_count = prefix_delegate_->GetRowCount(); - if (row_count == 0) - return; - - // Search for |text| if it has been a while since the user typed, otherwise - // append |text| to |current_text_| and search for that. If it has been a - // while search after the current row, otherwise search starting from the - // current row. - int row = std::max(0, prefix_delegate_->GetSelectedRow()); - const base::TimeTicks now(base::TimeTicks::Now()); - if ((now - time_of_last_key_).InMilliseconds() < kTimeBeforeClearingMS) { - current_text_ += text; - } else { - current_text_ = text; - if (prefix_delegate_->GetSelectedRow() >= 0) - row = (row + 1) % row_count; - } - time_of_last_key_ = now; - - const int start_row = row; - const base::string16 lower_text(base::i18n::ToLower(current_text_)); - do { - if (TextAtRowMatchesText(row, lower_text)) { - prefix_delegate_->SetSelectedRow(row); - return; - } - row = (row + 1) % row_count; - } while (row != start_row); -} - -bool PrefixSelector::TextAtRowMatchesText(int row, - const base::string16& lower_text) { - const base::string16 model_text( - base::i18n::ToLower(prefix_delegate_->GetTextForRow(row))); - return (model_text.size() >= lower_text.size()) && - (model_text.compare(0, lower_text.size(), lower_text) == 0); -} - -void PrefixSelector::ClearText() { - current_text_.clear(); - time_of_last_key_ = base::TimeTicks(); -} - -} // namespace views
diff --git a/ui/views/controls/prefix_selector.h b/ui/views/controls/prefix_selector.h deleted file mode 100644 index 615f239..0000000 --- a/ui/views/controls/prefix_selector.h +++ /dev/null
@@ -1,83 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_PREFIX_SELECTOR_H_ -#define UI_VIEWS_CONTROLS_PREFIX_SELECTOR_H_ - -#include "base/strings/string16.h" -#include "base/time/time.h" -#include "ui/base/ime/text_input_client.h" -#include "ui/views/views_export.h" - -namespace views { - -class PrefixDelegate; - -// PrefixSelector is used to change the selection in a view as the user -// types characters. -class VIEWS_EXPORT PrefixSelector : public ui::TextInputClient { - public: - explicit PrefixSelector(PrefixDelegate* delegate); - virtual ~PrefixSelector(); - - // Invoked from the view when it loses focus. - void OnViewBlur(); - - // ui::TextInputClient: - virtual void SetCompositionText( - const ui::CompositionText& composition) override; - virtual void ConfirmCompositionText() override; - virtual void ClearCompositionText() override; - virtual void InsertText(const base::string16& text) override; - virtual void InsertChar(base::char16 ch, int flags) override; - virtual gfx::NativeWindow GetAttachedWindow() const override; - virtual ui::TextInputType GetTextInputType() const override; - virtual ui::TextInputMode GetTextInputMode() const override; - virtual bool CanComposeInline() const override; - virtual gfx::Rect GetCaretBounds() const override; - virtual bool GetCompositionCharacterBounds(uint32 index, - gfx::Rect* rect) const override; - virtual bool HasCompositionText() const override; - virtual bool GetTextRange(gfx::Range* range) const override; - virtual bool GetCompositionTextRange(gfx::Range* range) const override; - virtual bool GetSelectionRange(gfx::Range* range) const override; - virtual bool SetSelectionRange(const gfx::Range& range) override; - virtual bool DeleteRange(const gfx::Range& range) override; - virtual bool GetTextFromRange(const gfx::Range& range, - base::string16* text) const override; - virtual void OnInputMethodChanged() override; - virtual bool ChangeTextDirectionAndLayoutAlignment( - base::i18n::TextDirection direction) override; - virtual void ExtendSelectionAndDelete(size_t before, size_t after) override; - virtual void EnsureCaretInRect(const gfx::Rect& rect) override; - virtual void OnCandidateWindowShown() override; - virtual void OnCandidateWindowUpdated() override; - virtual void OnCandidateWindowHidden() override; - - virtual bool IsEditingCommandEnabled(int command_id) override; - virtual void ExecuteEditingCommand(int command_id) override; - - private: - // Invoked when text is typed. Tries to change the selection appropriately. - void OnTextInput(const base::string16& text); - - // Returns true if the text of the node at |row| starts with |lower_text|. - bool TextAtRowMatchesText(int row, const base::string16& lower_text); - - // Clears |current_text_| and resets |time_of_last_key_|. - void ClearText(); - - PrefixDelegate* prefix_delegate_; - - // Time OnTextInput() was last invoked. - base::TimeTicks time_of_last_key_; - - base::string16 current_text_; - - DISALLOW_COPY_AND_ASSIGN(PrefixSelector); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_PREFIX_SELECTOR_H_
diff --git a/ui/views/controls/prefix_selector_unittest.cc b/ui/views/controls/prefix_selector_unittest.cc deleted file mode 100644 index ce04180..0000000 --- a/ui/views/controls/prefix_selector_unittest.cc +++ /dev/null
@@ -1,91 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/prefix_selector.h" - -#include <string> - -#include "base/strings/string_util.h" -#include "base/strings/utf_string_conversions.h" -#include "ui/views/controls/prefix_delegate.h" -#include "ui/views/test/views_test_base.h" - -using base::ASCIIToUTF16; - -namespace views { - -class TestPrefixDelegate : public PrefixDelegate { - public: - TestPrefixDelegate() : selected_row_(0) { - rows_.push_back(ASCIIToUTF16("aardvark")); - rows_.push_back(ASCIIToUTF16("antelope")); - rows_.push_back(ASCIIToUTF16("badger")); - rows_.push_back(ASCIIToUTF16("gnu")); - } - - virtual ~TestPrefixDelegate() {} - - virtual int GetRowCount() override { - return static_cast<int>(rows_.size()); - } - - virtual int GetSelectedRow() override { - return selected_row_; - } - - virtual void SetSelectedRow(int row) override { - selected_row_ = row; - } - - virtual base::string16 GetTextForRow(int row) override { - return rows_[row]; - } - - private: - std::vector<base::string16> rows_; - int selected_row_; - - DISALLOW_COPY_AND_ASSIGN(TestPrefixDelegate); -}; - -class PrefixSelectorTest : public ViewsTestBase { - public: - PrefixSelectorTest() { - selector_.reset(new PrefixSelector(&delegate_)); - } - - protected: - scoped_ptr<PrefixSelector> selector_; - TestPrefixDelegate delegate_; - - private: - DISALLOW_COPY_AND_ASSIGN(PrefixSelectorTest); -}; - -TEST_F(PrefixSelectorTest, PrefixSelect) { - selector_->InsertText(ASCIIToUTF16("an")); - EXPECT_EQ(1, delegate_.GetSelectedRow()); - - // Invoke OnViewBlur() to reset time. - selector_->OnViewBlur(); - selector_->InsertText(ASCIIToUTF16("a")); - EXPECT_EQ(0, delegate_.GetSelectedRow()); - - selector_->OnViewBlur(); - selector_->InsertText(ASCIIToUTF16("g")); - EXPECT_EQ(3, delegate_.GetSelectedRow()); - - selector_->OnViewBlur(); - selector_->InsertText(ASCIIToUTF16("b")); - selector_->InsertText(ASCIIToUTF16("a")); - EXPECT_EQ(2, delegate_.GetSelectedRow()); - - selector_->OnViewBlur(); - selector_->InsertText(ASCIIToUTF16("\t")); - selector_->InsertText(ASCIIToUTF16("b")); - selector_->InsertText(ASCIIToUTF16("a")); - EXPECT_EQ(2, delegate_.GetSelectedRow()); -} - -} // namespace views
diff --git a/ui/views/controls/progress_bar.cc b/ui/views/controls/progress_bar.cc deleted file mode 100644 index 0d6ed17..0000000 --- a/ui/views/controls/progress_bar.cc +++ /dev/null
@@ -1,323 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/progress_bar.h" - -#include <algorithm> -#include <string> - -#include "base/logging.h" -#include "third_party/skia/include/core/SkPaint.h" -#include "third_party/skia/include/core/SkXfermode.h" -#include "third_party/skia/include/effects/SkGradientShader.h" -#include "ui/accessibility/ax_view_state.h" -#include "ui/gfx/canvas.h" - -namespace { - -// Progress bar's border width. -const int kBorderWidth = 1; - -// Corner radius for the progress bar's border. -const int kCornerRadius = 2; - -// The width of the highlight at the right of the progress bar. -const int kHighlightWidth = 18; - -const SkColor kBackgroundColor = SkColorSetRGB(230, 230, 230); -const SkColor kBackgroundBorderColor = SkColorSetRGB(208, 208, 208); -const SkColor kBarBorderColor = SkColorSetRGB(65, 137, 237); -const SkColor kBarTopColor = SkColorSetRGB(110, 188, 249); -const SkColor kBarColorStart = SkColorSetRGB(86, 167, 247); -const SkColor kBarColorEnd = SkColorSetRGB(76, 148, 245); -const SkColor kBarHighlightEnd = SkColorSetRGB(114, 206, 251); -const SkColor kDisabledBarBorderColor = SkColorSetRGB(191, 191, 191); -const SkColor kDisabledBarColorStart = SkColorSetRGB(224, 224, 224); -const SkColor kDisabledBarColorEnd = SkColorSetRGB(212, 212, 212); - -void AddRoundRectPathWithPadding(int x, int y, - int w, int h, - int corner_radius, - SkScalar padding, - SkPath* path) { - DCHECK(path); - SkRect rect; - rect.set( - SkIntToScalar(x) + padding, SkIntToScalar(y) + padding, - SkIntToScalar(x + w) - padding, SkIntToScalar(y + h) - padding); - path->addRoundRect( - rect, - SkIntToScalar(corner_radius) - padding, - SkIntToScalar(corner_radius) - padding); -} - -void AddRoundRectPath(int x, int y, - int w, int h, - int corner_radius, - SkPath* path) { - AddRoundRectPathWithPadding(x, y, w, h, corner_radius, SK_ScalarHalf, path); -} - -void FillRoundRect(gfx::Canvas* canvas, - int x, int y, - int w, int h, - int corner_radius, - const SkColor colors[], - const SkScalar points[], - int count, - bool gradient_horizontal) { - SkPath path; - AddRoundRectPath(x, y, w, h, corner_radius, &path); - SkPaint paint; - paint.setStyle(SkPaint::kFill_Style); - paint.setFlags(SkPaint::kAntiAlias_Flag); - - SkPoint p[2]; - p[0].iset(x, y); - if (gradient_horizontal) { - p[1].iset(x + w, y); - } else { - p[1].iset(x, y + h); - } - skia::RefPtr<SkShader> s = skia::AdoptRef(SkGradientShader::CreateLinear( - p, colors, points, count, SkShader::kClamp_TileMode)); - paint.setShader(s.get()); - - canvas->DrawPath(path, paint); -} - -void FillRoundRect(gfx::Canvas* canvas, - int x, int y, - int w, int h, - int corner_radius, - SkColor gradient_start_color, - SkColor gradient_end_color, - bool gradient_horizontal) { - if (gradient_start_color != gradient_end_color) { - SkColor colors[2] = { gradient_start_color, gradient_end_color }; - FillRoundRect(canvas, x, y, w, h, corner_radius, - colors, NULL, 2, gradient_horizontal); - } else { - SkPath path; - AddRoundRectPath(x, y, w, h, corner_radius, &path); - SkPaint paint; - paint.setStyle(SkPaint::kFill_Style); - paint.setFlags(SkPaint::kAntiAlias_Flag); - paint.setColor(gradient_start_color); - canvas->DrawPath(path, paint); - } -} - -void StrokeRoundRect(gfx::Canvas* canvas, - int x, int y, - int w, int h, - int corner_radius, - SkColor stroke_color, - int stroke_width) { - SkPath path; - AddRoundRectPath(x, y, w, h, corner_radius, &path); - SkPaint paint; - paint.setShader(NULL); - paint.setColor(stroke_color); - paint.setStyle(SkPaint::kStroke_Style); - paint.setFlags(SkPaint::kAntiAlias_Flag); - paint.setStrokeWidth(SkIntToScalar(stroke_width)); - canvas->DrawPath(path, paint); -} - -} // namespace - -namespace views { - -// static -const char ProgressBar::kViewClassName[] = "ProgressBar"; - -ProgressBar::ProgressBar() - : min_display_value_(0.0), - max_display_value_(1.0), - current_value_(0.0) { -} - -ProgressBar::~ProgressBar() { -} - -double ProgressBar::GetNormalizedValue() const { - const double capped_value = std::min( - std::max(current_value_, min_display_value_), max_display_value_); - return (capped_value - min_display_value_) / - (max_display_value_ - min_display_value_); -} - -void ProgressBar::SetDisplayRange(double min_display_value, - double max_display_value) { - if (min_display_value != min_display_value_ || - max_display_value != max_display_value_) { - DCHECK(min_display_value < max_display_value); - min_display_value_ = min_display_value; - max_display_value_ = max_display_value; - SchedulePaint(); - } -} - -void ProgressBar::SetValue(double value) { - if (value != current_value_) { - current_value_ = value; - SchedulePaint(); - } -} - -void ProgressBar::SetTooltipText(const base::string16& tooltip_text) { - tooltip_text_ = tooltip_text; -} - -bool ProgressBar::GetTooltipText(const gfx::Point& p, - base::string16* tooltip) const { - DCHECK(tooltip); - *tooltip = tooltip_text_; - return !tooltip_text_.empty(); -} - -void ProgressBar::GetAccessibleState(ui::AXViewState* state) { - state->role = ui::AX_ROLE_PROGRESS_INDICATOR; - state->AddStateFlag(ui::AX_STATE_READ_ONLY); -} - -gfx::Size ProgressBar::GetPreferredSize() const { - gfx::Size pref_size(100, 11); - gfx::Insets insets = GetInsets(); - pref_size.Enlarge(insets.width(), insets.height()); - return pref_size; -} - -const char* ProgressBar::GetClassName() const { - return kViewClassName; -} - -void ProgressBar::OnPaint(gfx::Canvas* canvas) { - gfx::Rect content_bounds = GetContentsBounds(); - int bar_left = content_bounds.x(); - int bar_top = content_bounds.y(); - int bar_width = content_bounds.width(); - int bar_height = content_bounds.height(); - - const int progress_width = - static_cast<int>(bar_width * GetNormalizedValue() + 0.5); - - // Draw background. - FillRoundRect(canvas, - bar_left, bar_top, bar_width, bar_height, - kCornerRadius, - kBackgroundColor, kBackgroundColor, - false); - StrokeRoundRect(canvas, - bar_left, bar_top, - bar_width, bar_height, - kCornerRadius, - kBackgroundBorderColor, - kBorderWidth); - - if (progress_width > 1) { - // Draw inner if wide enough. - if (progress_width > kBorderWidth * 2) { - canvas->Save(); - - SkPath inner_path; - AddRoundRectPathWithPadding( - bar_left, bar_top, progress_width, bar_height, - kCornerRadius, - 0, - &inner_path); - canvas->ClipPath(inner_path, false); - - const SkColor bar_colors[] = { - kBarTopColor, - kBarTopColor, - kBarColorStart, - kBarColorEnd, - kBarColorEnd, - }; - // We want a thin 1-pixel line for kBarTopColor. - SkScalar scalar_height = SkIntToScalar(bar_height); - SkScalar highlight_width = SkScalarDiv(SK_Scalar1, scalar_height); - SkScalar border_width = SkScalarDiv(SkIntToScalar(kBorderWidth), - scalar_height); - const SkScalar bar_points[] = { - 0, - border_width, - border_width + highlight_width, - SK_Scalar1 - border_width, - SK_Scalar1, - }; - - const SkColor disabled_bar_colors[] = { - kDisabledBarColorStart, - kDisabledBarColorStart, - kDisabledBarColorEnd, - kDisabledBarColorEnd, - }; - - const SkScalar disabled_bar_points[] = { - 0, - border_width, - SK_Scalar1 - border_width, - SK_Scalar1 - }; - - // Do not start from (kBorderWidth, kBorderWidth) because it makes gaps - // between the inner and the border. - FillRoundRect(canvas, - bar_left, bar_top, - progress_width, bar_height, - kCornerRadius, - enabled() ? bar_colors : disabled_bar_colors, - enabled() ? bar_points : disabled_bar_points, - enabled() ? arraysize(bar_colors) : - arraysize(disabled_bar_colors), - false); - - if (enabled()) { - // Draw the highlight to the right. - const SkColor highlight_colors[] = { - SkColorSetA(kBarHighlightEnd, 0), - kBarHighlightEnd, - kBarHighlightEnd, - }; - const SkScalar highlight_points[] = { - 0, - SK_Scalar1 - SkScalarDiv(SkIntToScalar(kBorderWidth), scalar_height), - SK_Scalar1, - }; - SkPaint paint; - paint.setStyle(SkPaint::kFill_Style); - paint.setFlags(SkPaint::kAntiAlias_Flag); - - SkPoint p[2]; - int highlight_left = - std::max(0, progress_width - kHighlightWidth - kBorderWidth); - p[0].iset(highlight_left, 0); - p[1].iset(progress_width, 0); - skia::RefPtr<SkShader> s = - skia::AdoptRef(SkGradientShader::CreateLinear( - p, highlight_colors, highlight_points, - arraysize(highlight_colors), SkShader::kClamp_TileMode)); - paint.setShader(s.get()); - paint.setXfermodeMode(SkXfermode::kSrcOver_Mode); - canvas->DrawRect(gfx::Rect(highlight_left, 0, - kHighlightWidth + kBorderWidth, bar_height), - paint); - } - - canvas->Restore(); - } - - // Draw bar stroke - StrokeRoundRect(canvas, - bar_left, bar_top, progress_width, bar_height, - kCornerRadius, - enabled() ? kBarBorderColor : kDisabledBarBorderColor, - kBorderWidth); - } -} - -} // namespace views
diff --git a/ui/views/controls/progress_bar.h b/ui/views/controls/progress_bar.h deleted file mode 100644 index e844d2f..0000000 --- a/ui/views/controls/progress_bar.h +++ /dev/null
@@ -1,68 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_PROGRESS_BAR_H_ -#define UI_VIEWS_CONTROLS_PROGRESS_BAR_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "ui/views/view.h" - -namespace views { - -// Progress bar is a control that indicates progress visually. -class VIEWS_EXPORT ProgressBar : public View { - public: - // The value range defaults to [0.0, 1.0]. - ProgressBar(); - virtual ~ProgressBar(); - - double current_value() const { return current_value_; } - - // Gets a normalized current value in [0.0, 1.0] range based on current value - // range and the min/max display value range. - double GetNormalizedValue() const; - - // Sets the inclusive range of values to be displayed. Values outside of the - // range will be capped when displayed. - void SetDisplayRange(double min_display_value, double max_display_value); - - // Sets the current value. Values outside of the range [min_display_value_, - // max_display_value_] will be stored unmodified and capped for display. - void SetValue(double value); - - // Sets the tooltip text. Default behavior for a progress bar is to show no - // tooltip on mouse hover. Calling this lets you set a custom tooltip. To - // revert to default behavior, call this with an empty string. - void SetTooltipText(const base::string16& tooltip_text); - - // Overridden from View: - virtual bool GetTooltipText(const gfx::Point& p, - base::string16* tooltip) const override; - virtual void GetAccessibleState(ui::AXViewState* state) override; - - private: - static const char kViewClassName[]; - - // Overridden from View: - virtual gfx::Size GetPreferredSize() const override; - virtual const char* GetClassName() const override; - virtual void OnPaint(gfx::Canvas* canvas) override; - - // Inclusive range used when displaying values. - double min_display_value_; - double max_display_value_; - - // Current value. May be outside of [min_display_value_, max_display_value_]. - double current_value_; - - // Tooltip text. - base::string16 tooltip_text_; - - DISALLOW_COPY_AND_ASSIGN(ProgressBar); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_PROGRESS_BAR_H_
diff --git a/ui/views/controls/progress_bar_unittest.cc b/ui/views/controls/progress_bar_unittest.cc deleted file mode 100644 index b9067b2..0000000 --- a/ui/views/controls/progress_bar_unittest.cc +++ /dev/null
@@ -1,35 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/progress_bar.h" - -#include "base/strings/utf_string_conversions.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/accessibility/ax_view_state.h" - -namespace views { - -TEST(ProgressBarTest, TooltipTextProperty) { - ProgressBar bar; - base::string16 tooltip = base::ASCIIToUTF16("Some text"); - EXPECT_FALSE(bar.GetTooltipText(gfx::Point(), &tooltip)); - EXPECT_EQ(base::string16(), tooltip); - base::string16 tooltip_text = base::ASCIIToUTF16("My progress"); - bar.SetTooltipText(tooltip_text); - EXPECT_TRUE(bar.GetTooltipText(gfx::Point(), &tooltip)); - EXPECT_EQ(tooltip_text, tooltip); -} - -TEST(ProgressBarTest, Accessibility) { - ProgressBar bar; - bar.SetValue(62); - - ui::AXViewState state; - bar.GetAccessibleState(&state); - EXPECT_EQ(ui::AX_ROLE_PROGRESS_INDICATOR, state.role); - EXPECT_EQ(base::string16(), state.name); - EXPECT_TRUE(state.HasStateFlag(ui::AX_STATE_READ_ONLY)); -} - -} // namespace views
diff --git a/ui/views/controls/resize_area.cc b/ui/views/controls/resize_area.cc deleted file mode 100644 index 6675910..0000000 --- a/ui/views/controls/resize_area.cc +++ /dev/null
@@ -1,79 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/resize_area.h" - -#include "base/logging.h" -#include "ui/accessibility/ax_view_state.h" -#include "ui/base/cursor/cursor.h" -#include "ui/views/controls/resize_area_delegate.h" -#include "ui/views/native_cursor.h" - -namespace views { - -const char ResizeArea::kViewClassName[] = "ResizeArea"; - -//////////////////////////////////////////////////////////////////////////////// -// ResizeArea - -ResizeArea::ResizeArea(ResizeAreaDelegate* delegate) - : delegate_(delegate), - initial_position_(0) { -} - -ResizeArea::~ResizeArea() { -} - -const char* ResizeArea::GetClassName() const { - return kViewClassName; -} - -gfx::NativeCursor ResizeArea::GetCursor(const ui::MouseEvent& event) { - return enabled() ? GetNativeEastWestResizeCursor() - : gfx::kNullCursor; -} - -bool ResizeArea::OnMousePressed(const ui::MouseEvent& event) { - if (!event.IsOnlyLeftMouseButton()) - return false; - - // The resize area obviously will move once you start dragging so we need to - // convert coordinates to screen coordinates so that we don't lose our - // bearings. - gfx::Point point(event.x(), 0); - View::ConvertPointToScreen(this, &point); - initial_position_ = point.x(); - - return true; -} - -bool ResizeArea::OnMouseDragged(const ui::MouseEvent& event) { - if (!event.IsLeftMouseButton()) - return false; - - ReportResizeAmount(event.x(), false); - return true; -} - -void ResizeArea::OnMouseReleased(const ui::MouseEvent& event) { - ReportResizeAmount(event.x(), true); -} - -void ResizeArea::OnMouseCaptureLost() { - ReportResizeAmount(initial_position_, true); -} - -void ResizeArea::GetAccessibleState(ui::AXViewState* state) { - state->role = ui::AX_ROLE_SPLITTER; -} - -void ResizeArea::ReportResizeAmount(int resize_amount, bool last_update) { - gfx::Point point(resize_amount, 0); - View::ConvertPointToScreen(this, &point); - resize_amount = point.x() - initial_position_; - delegate_->OnResize(base::i18n::IsRTL() ? -resize_amount : resize_amount, - last_update); -} - -} // namespace views
diff --git a/ui/views/controls/resize_area.h b/ui/views/controls/resize_area.h deleted file mode 100644 index 661c2b6..0000000 --- a/ui/views/controls/resize_area.h +++ /dev/null
@@ -1,53 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_RESIZE_AREA_H_ -#define UI_VIEWS_CONTROLS_RESIZE_AREA_H_ - -#include <string> - -#include "ui/views/view.h" - -namespace views { - -class ResizeAreaDelegate; - -//////////////////////////////////////////////////////////////////////////////// -// -// An invisible area that acts like a horizontal resizer. -// -//////////////////////////////////////////////////////////////////////////////// -class VIEWS_EXPORT ResizeArea : public View { - public: - static const char kViewClassName[]; - - explicit ResizeArea(ResizeAreaDelegate* delegate); - virtual ~ResizeArea(); - - // Overridden from views::View: - virtual const char* GetClassName() const override; - virtual gfx::NativeCursor GetCursor(const ui::MouseEvent& event) override; - virtual bool OnMousePressed(const ui::MouseEvent& event) override; - virtual bool OnMouseDragged(const ui::MouseEvent& event) override; - virtual void OnMouseReleased(const ui::MouseEvent& event) override; - virtual void OnMouseCaptureLost() override; - virtual void GetAccessibleState(ui::AXViewState* state) override; - - private: - // Report the amount the user resized by to the delegate, accounting for - // directionality. - void ReportResizeAmount(int resize_amount, bool last_update); - - // The delegate to notify when we have updates. - ResizeAreaDelegate* delegate_; - - // The mouse position at start (in screen coordinates). - int initial_position_; - - DISALLOW_COPY_AND_ASSIGN(ResizeArea); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_RESIZE_AREA_H_
diff --git a/ui/views/controls/resize_area_delegate.h b/ui/views/controls/resize_area_delegate.h deleted file mode 100644 index cc5e133..0000000 --- a/ui/views/controls/resize_area_delegate.h +++ /dev/null
@@ -1,28 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_RESIZE_AREA_DELEGATE_H_ -#define UI_VIEWS_CONTROLS_RESIZE_AREA_DELEGATE_H_ - -namespace views { - -// An interface implemented by objects that want to be notified about the resize -// event. -class ResizeAreaDelegate { - public: - // OnResize is sent when resizing is detected. |resize_amount| specifies the - // number of pixels that the user wants to resize by, and can be negative or - // positive (depending on direction of dragging and flips according to - // locale directionality: dragging to the left in LTR locales gives negative - // |resize_amount| but positive amount for RTL). |done_resizing| is true if - // the user has released the mouse. - virtual void OnResize(int resize_amount, bool done_resizing) = 0; - - protected: - virtual ~ResizeAreaDelegate() {} -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_RESIZE_AREA_DELEGATE_H_
diff --git a/ui/views/controls/scroll_view.cc b/ui/views/controls/scroll_view.cc deleted file mode 100644 index 8a05f92..0000000 --- a/ui/views/controls/scroll_view.cc +++ /dev/null
@@ -1,644 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/scroll_view.h" - -#include "base/logging.h" -#include "ui/events/event.h" -#include "ui/gfx/canvas.h" -#include "ui/native_theme/native_theme.h" -#include "ui/views/border.h" -#include "ui/views/controls/scrollbar/native_scroll_bar.h" -#include "ui/views/widget/root_view.h" - -namespace views { - -const char ScrollView::kViewClassName[] = "ScrollView"; - -namespace { - -// Subclass of ScrollView that resets the border when the theme changes. -class ScrollViewWithBorder : public views::ScrollView { - public: - ScrollViewWithBorder() {} - - // View overrides; - virtual void OnNativeThemeChanged(const ui::NativeTheme* theme) override { - SetBorder(Border::CreateSolidBorder( - 1, - theme->GetSystemColor(ui::NativeTheme::kColorId_UnfocusedBorderColor))); - } - - private: - DISALLOW_COPY_AND_ASSIGN(ScrollViewWithBorder); -}; - -class ScrollCornerView : public views::View { - public: - ScrollCornerView() {} - - virtual void OnPaint(gfx::Canvas* canvas) override { - ui::NativeTheme::ExtraParams ignored; - GetNativeTheme()->Paint(canvas->sk_canvas(), - ui::NativeTheme::kScrollbarCorner, - ui::NativeTheme::kNormal, - GetLocalBounds(), - ignored); - } - - private: - DISALLOW_COPY_AND_ASSIGN(ScrollCornerView); -}; - -// Returns the position for the view so that it isn't scrolled off the visible -// region. -int CheckScrollBounds(int viewport_size, int content_size, int current_pos) { - int max = std::max(content_size - viewport_size, 0); - if (current_pos < 0) - return 0; - if (current_pos > max) - return max; - return current_pos; -} - -// Make sure the content is not scrolled out of bounds -void CheckScrollBounds(View* viewport, View* view) { - if (!view) - return; - - int x = CheckScrollBounds(viewport->width(), view->width(), -view->x()); - int y = CheckScrollBounds(viewport->height(), view->height(), -view->y()); - - // This is no op if bounds are the same - view->SetBounds(-x, -y, view->width(), view->height()); -} - -// Used by ScrollToPosition() to make sure the new position fits within the -// allowed scroll range. -int AdjustPosition(int current_position, - int new_position, - int content_size, - int viewport_size) { - if (-current_position == new_position) - return new_position; - if (new_position < 0) - return 0; - const int max_position = std::max(0, content_size - viewport_size); - return (new_position > max_position) ? max_position : new_position; -} - -} // namespace - -// Viewport contains the contents View of the ScrollView. -class ScrollView::Viewport : public View { - public: - Viewport() {} - virtual ~Viewport() {} - - virtual const char* GetClassName() const override { - return "ScrollView::Viewport"; - } - - virtual void ScrollRectToVisible(const gfx::Rect& rect) override { - if (!has_children() || !parent()) - return; - - View* contents = child_at(0); - gfx::Rect scroll_rect(rect); - scroll_rect.Offset(-contents->x(), -contents->y()); - static_cast<ScrollView*>(parent())->ScrollContentsRegionToBeVisible( - scroll_rect); - } - - virtual void ChildPreferredSizeChanged(View* child) override { - if (parent()) - parent()->Layout(); - } - - private: - DISALLOW_COPY_AND_ASSIGN(Viewport); -}; - -ScrollView::ScrollView() - : contents_(NULL), - contents_viewport_(new Viewport()), - header_(NULL), - header_viewport_(new Viewport()), - horiz_sb_(new NativeScrollBar(true)), - vert_sb_(new NativeScrollBar(false)), - corner_view_(new ScrollCornerView()), - min_height_(-1), - max_height_(-1), - hide_horizontal_scrollbar_(false) { - set_notify_enter_exit_on_child(true); - - AddChildView(contents_viewport_); - AddChildView(header_viewport_); - - // Don't add the scrollbars as children until we discover we need them - // (ShowOrHideScrollBar). - horiz_sb_->SetVisible(false); - horiz_sb_->set_controller(this); - vert_sb_->SetVisible(false); - vert_sb_->set_controller(this); - corner_view_->SetVisible(false); -} - -ScrollView::~ScrollView() { - // The scrollbars may not have been added, delete them to ensure they get - // deleted. - delete horiz_sb_; - delete vert_sb_; - delete corner_view_; -} - -// static -ScrollView* ScrollView::CreateScrollViewWithBorder() { - return new ScrollViewWithBorder(); -} - -void ScrollView::SetContents(View* a_view) { - SetHeaderOrContents(contents_viewport_, a_view, &contents_); -} - -void ScrollView::SetHeader(View* header) { - SetHeaderOrContents(header_viewport_, header, &header_); -} - -gfx::Rect ScrollView::GetVisibleRect() const { - if (!contents_) - return gfx::Rect(); - return gfx::Rect(-contents_->x(), -contents_->y(), - contents_viewport_->width(), contents_viewport_->height()); -} - -void ScrollView::ClipHeightTo(int min_height, int max_height) { - min_height_ = min_height; - max_height_ = max_height; -} - -int ScrollView::GetScrollBarWidth() const { - return vert_sb_ ? vert_sb_->GetLayoutSize() : 0; -} - -int ScrollView::GetScrollBarHeight() const { - return horiz_sb_ ? horiz_sb_->GetLayoutSize() : 0; -} - -void ScrollView::SetHorizontalScrollBar(ScrollBar* horiz_sb) { - DCHECK(horiz_sb); - horiz_sb->SetVisible(horiz_sb_->visible()); - delete horiz_sb_; - horiz_sb->set_controller(this); - horiz_sb_ = horiz_sb; -} - -void ScrollView::SetVerticalScrollBar(ScrollBar* vert_sb) { - DCHECK(vert_sb); - vert_sb->SetVisible(vert_sb_->visible()); - delete vert_sb_; - vert_sb->set_controller(this); - vert_sb_ = vert_sb; -} - -gfx::Size ScrollView::GetPreferredSize() const { - if (!is_bounded()) - return View::GetPreferredSize(); - - gfx::Size size = contents()->GetPreferredSize(); - size.SetToMax(gfx::Size(size.width(), min_height_)); - size.SetToMin(gfx::Size(size.width(), max_height_)); - gfx::Insets insets = GetInsets(); - size.Enlarge(insets.width(), insets.height()); - return size; -} - -int ScrollView::GetHeightForWidth(int width) const { - if (!is_bounded()) - return View::GetHeightForWidth(width); - - gfx::Insets insets = GetInsets(); - width = std::max(0, width - insets.width()); - int height = contents()->GetHeightForWidth(width) + insets.height(); - return std::min(std::max(height, min_height_), max_height_); -} - -void ScrollView::Layout() { - if (is_bounded()) { - int content_width = width(); - int content_height = contents()->GetHeightForWidth(content_width); - if (content_height > height()) { - content_width = std::max(content_width - GetScrollBarWidth(), 0); - content_height = contents()->GetHeightForWidth(content_width); - } - if (contents()->bounds().size() != gfx::Size(content_width, content_height)) - contents()->SetBounds(0, 0, content_width, content_height); - } - - // Most views will want to auto-fit the available space. Most of them want to - // use all available width (without overflowing) and only overflow in - // height. Examples are HistoryView, MostVisitedView, DownloadTabView, etc. - // Other views want to fit in both ways. An example is PrintView. To make both - // happy, assume a vertical scrollbar but no horizontal scrollbar. To override - // this default behavior, the inner view has to calculate the available space, - // used ComputeScrollBarsVisibility() to use the same calculation that is done - // here and sets its bound to fit within. - gfx::Rect viewport_bounds = GetContentsBounds(); - const int contents_x = viewport_bounds.x(); - const int contents_y = viewport_bounds.y(); - if (viewport_bounds.IsEmpty()) { - // There's nothing to layout. - return; - } - - const int header_height = - std::min(viewport_bounds.height(), - header_ ? header_->GetPreferredSize().height() : 0); - viewport_bounds.set_height( - std::max(0, viewport_bounds.height() - header_height)); - viewport_bounds.set_y(viewport_bounds.y() + header_height); - // viewport_size is the total client space available. - gfx::Size viewport_size = viewport_bounds.size(); - // Assumes a vertical scrollbar since most of the current views are designed - // for this. - int horiz_sb_height = GetScrollBarHeight(); - int vert_sb_width = GetScrollBarWidth(); - viewport_bounds.set_width(viewport_bounds.width() - vert_sb_width); - // Update the bounds right now so the inner views can fit in it. - contents_viewport_->SetBoundsRect(viewport_bounds); - - // Give |contents_| a chance to update its bounds if it depends on the - // viewport. - if (contents_) - contents_->Layout(); - - bool should_layout_contents = false; - bool horiz_sb_required = false; - bool vert_sb_required = false; - if (contents_) { - gfx::Size content_size = contents_->size(); - ComputeScrollBarsVisibility(viewport_size, - content_size, - &horiz_sb_required, - &vert_sb_required); - } - bool corner_view_required = horiz_sb_required && vert_sb_required; - // Take action. - SetControlVisibility(horiz_sb_, horiz_sb_required); - SetControlVisibility(vert_sb_, vert_sb_required); - SetControlVisibility(corner_view_, corner_view_required); - - // Non-default. - if (horiz_sb_required) { - viewport_bounds.set_height( - std::max(0, viewport_bounds.height() - horiz_sb_height)); - should_layout_contents = true; - } - // Default. - if (!vert_sb_required) { - viewport_bounds.set_width(viewport_bounds.width() + vert_sb_width); - should_layout_contents = true; - } - - if (horiz_sb_required) { - int height_offset = horiz_sb_->GetContentOverlapSize(); - horiz_sb_->SetBounds(0, - viewport_bounds.bottom() - height_offset, - viewport_bounds.right(), - horiz_sb_height + height_offset); - } - if (vert_sb_required) { - int width_offset = vert_sb_->GetContentOverlapSize(); - vert_sb_->SetBounds(viewport_bounds.right() - width_offset, - 0, - vert_sb_width + width_offset, - viewport_bounds.bottom()); - } - if (corner_view_required) { - // Show the resize corner. - corner_view_->SetBounds(viewport_bounds.right(), - viewport_bounds.bottom(), - vert_sb_width, - horiz_sb_height); - } - - // Update to the real client size with the visible scrollbars. - contents_viewport_->SetBoundsRect(viewport_bounds); - if (should_layout_contents && contents_) - contents_->Layout(); - - header_viewport_->SetBounds(contents_x, contents_y, - viewport_bounds.width(), header_height); - if (header_) - header_->Layout(); - - CheckScrollBounds(header_viewport_, header_); - CheckScrollBounds(contents_viewport_, contents_); - SchedulePaint(); - UpdateScrollBarPositions(); -} - -bool ScrollView::OnKeyPressed(const ui::KeyEvent& event) { - bool processed = false; - - // Give vertical scrollbar priority - if (vert_sb_->visible()) - processed = vert_sb_->OnKeyPressed(event); - - if (!processed && horiz_sb_->visible()) - processed = horiz_sb_->OnKeyPressed(event); - - return processed; -} - -bool ScrollView::OnMouseWheel(const ui::MouseWheelEvent& e) { - bool processed = false; - - if (vert_sb_->visible()) - processed = vert_sb_->OnMouseWheel(e); - - if (horiz_sb_->visible()) - processed = horiz_sb_->OnMouseWheel(e) || processed; - - return processed; -} - -void ScrollView::OnMouseEntered(const ui::MouseEvent& event) { - if (horiz_sb_) - horiz_sb_->OnMouseEnteredScrollView(event); - if (vert_sb_) - vert_sb_->OnMouseEnteredScrollView(event); -} - -void ScrollView::OnMouseExited(const ui::MouseEvent& event) { - if (horiz_sb_) - horiz_sb_->OnMouseExitedScrollView(event); - if (vert_sb_) - vert_sb_->OnMouseExitedScrollView(event); -} - -void ScrollView::OnGestureEvent(ui::GestureEvent* event) { - // If the event happened on one of the scrollbars, then those events are - // sent directly to the scrollbars. Otherwise, only scroll events are sent to - // the scrollbars. - bool scroll_event = event->type() == ui::ET_GESTURE_SCROLL_UPDATE || - event->type() == ui::ET_GESTURE_SCROLL_BEGIN || - event->type() == ui::ET_GESTURE_SCROLL_END || - event->type() == ui::ET_SCROLL_FLING_START; - - if (vert_sb_->visible()) { - if (vert_sb_->bounds().Contains(event->location()) || scroll_event) - vert_sb_->OnGestureEvent(event); - } - if (!event->handled() && horiz_sb_->visible()) { - if (horiz_sb_->bounds().Contains(event->location()) || scroll_event) - horiz_sb_->OnGestureEvent(event); - } -} - -const char* ScrollView::GetClassName() const { - return kViewClassName; -} - -void ScrollView::ScrollToPosition(ScrollBar* source, int position) { - if (!contents_) - return; - - if (source == horiz_sb_ && horiz_sb_->visible()) { - position = AdjustPosition(contents_->x(), position, contents_->width(), - contents_viewport_->width()); - if (-contents_->x() == position) - return; - contents_->SetX(-position); - if (header_) { - header_->SetX(-position); - header_->SchedulePaintInRect(header_->GetVisibleBounds()); - } - } else if (source == vert_sb_ && vert_sb_->visible()) { - position = AdjustPosition(contents_->y(), position, contents_->height(), - contents_viewport_->height()); - if (-contents_->y() == position) - return; - contents_->SetY(-position); - } - contents_->SchedulePaintInRect(contents_->GetVisibleBounds()); -} - -int ScrollView::GetScrollIncrement(ScrollBar* source, bool is_page, - bool is_positive) { - bool is_horizontal = source->IsHorizontal(); - int amount = 0; - if (contents_) { - if (is_page) { - amount = contents_->GetPageScrollIncrement( - this, is_horizontal, is_positive); - } else { - amount = contents_->GetLineScrollIncrement( - this, is_horizontal, is_positive); - } - if (amount > 0) - return amount; - } - // No view, or the view didn't return a valid amount. - if (is_page) { - return is_horizontal ? contents_viewport_->width() : - contents_viewport_->height(); - } - return is_horizontal ? contents_viewport_->width() / 5 : - contents_viewport_->height() / 5; -} - -void ScrollView::SetHeaderOrContents(View* parent, - View* new_view, - View** member) { - if (*member == new_view) - return; - - delete *member; - *member = new_view; - if (*member) - parent->AddChildView(*member); - Layout(); -} - -void ScrollView::ScrollContentsRegionToBeVisible(const gfx::Rect& rect) { - if (!contents_ || (!horiz_sb_->visible() && !vert_sb_->visible())) - return; - - // Figure out the maximums for this scroll view. - const int contents_max_x = - std::max(contents_viewport_->width(), contents_->width()); - const int contents_max_y = - std::max(contents_viewport_->height(), contents_->height()); - - // Make sure x and y are within the bounds of [0,contents_max_*]. - int x = std::max(0, std::min(contents_max_x, rect.x())); - int y = std::max(0, std::min(contents_max_y, rect.y())); - - // Figure out how far and down the rectangle will go taking width - // and height into account. This will be "clipped" by the viewport. - const int max_x = std::min(contents_max_x, - x + std::min(rect.width(), contents_viewport_->width())); - const int max_y = std::min(contents_max_y, - y + std::min(rect.height(), contents_viewport_->height())); - - // See if the rect is already visible. Note the width is (max_x - x) - // and the height is (max_y - y) to take into account the clipping of - // either viewport or the content size. - const gfx::Rect vis_rect = GetVisibleRect(); - if (vis_rect.Contains(gfx::Rect(x, y, max_x - x, max_y - y))) - return; - - // Shift contents_'s X and Y so that the region is visible. If we - // need to shift up or left from where we currently are then we need - // to get it so that the content appears in the upper/left - // corner. This is done by setting the offset to -X or -Y. For down - // or right shifts we need to make sure it appears in the - // lower/right corner. This is calculated by taking max_x or max_y - // and scaling it back by the size of the viewport. - const int new_x = - (vis_rect.x() > x) ? x : std::max(0, max_x - contents_viewport_->width()); - const int new_y = - (vis_rect.y() > y) ? y : std::max(0, max_y - - contents_viewport_->height()); - - contents_->SetX(-new_x); - if (header_) - header_->SetX(-new_x); - contents_->SetY(-new_y); - UpdateScrollBarPositions(); -} - -void ScrollView::ComputeScrollBarsVisibility(const gfx::Size& vp_size, - const gfx::Size& content_size, - bool* horiz_is_shown, - bool* vert_is_shown) const { - // Try to fit both ways first, then try vertical bar only, then horizontal - // bar only, then defaults to both shown. - if (content_size.width() <= vp_size.width() && - content_size.height() <= vp_size.height()) { - *horiz_is_shown = false; - *vert_is_shown = false; - } else if (content_size.width() <= vp_size.width() - GetScrollBarWidth()) { - *horiz_is_shown = false; - *vert_is_shown = true; - } else if (content_size.height() <= vp_size.height() - GetScrollBarHeight()) { - *horiz_is_shown = true; - *vert_is_shown = false; - } else { - *horiz_is_shown = true; - *vert_is_shown = true; - } - - if (hide_horizontal_scrollbar_) - *horiz_is_shown = false; -} - -// Make sure that a single scrollbar is created and visible as needed -void ScrollView::SetControlVisibility(View* control, bool should_show) { - if (!control) - return; - if (should_show) { - if (!control->visible()) { - AddChildView(control); - control->SetVisible(true); - } - } else { - RemoveChildView(control); - control->SetVisible(false); - } -} - -void ScrollView::UpdateScrollBarPositions() { - if (!contents_) - return; - - if (horiz_sb_->visible()) { - int vw = contents_viewport_->width(); - int cw = contents_->width(); - int origin = contents_->x(); - horiz_sb_->Update(vw, cw, -origin); - } - if (vert_sb_->visible()) { - int vh = contents_viewport_->height(); - int ch = contents_->height(); - int origin = contents_->y(); - vert_sb_->Update(vh, ch, -origin); - } -} - -// VariableRowHeightScrollHelper ---------------------------------------------- - -VariableRowHeightScrollHelper::VariableRowHeightScrollHelper( - Controller* controller) : controller_(controller) { -} - -VariableRowHeightScrollHelper::~VariableRowHeightScrollHelper() { -} - -int VariableRowHeightScrollHelper::GetPageScrollIncrement( - ScrollView* scroll_view, bool is_horizontal, bool is_positive) { - if (is_horizontal) - return 0; - // y coordinate is most likely negative. - int y = abs(scroll_view->contents()->y()); - int vis_height = scroll_view->contents()->parent()->height(); - if (is_positive) { - // Align the bottom most row to the top of the view. - int bottom = std::min(scroll_view->contents()->height() - 1, - y + vis_height); - RowInfo bottom_row_info = GetRowInfo(bottom); - // If 0, ScrollView will provide a default value. - return std::max(0, bottom_row_info.origin - y); - } else { - // Align the row on the previous page to to the top of the view. - int last_page_y = y - vis_height; - RowInfo last_page_info = GetRowInfo(std::max(0, last_page_y)); - if (last_page_y != last_page_info.origin) - return std::max(0, y - last_page_info.origin - last_page_info.height); - return std::max(0, y - last_page_info.origin); - } -} - -int VariableRowHeightScrollHelper::GetLineScrollIncrement( - ScrollView* scroll_view, bool is_horizontal, bool is_positive) { - if (is_horizontal) - return 0; - // y coordinate is most likely negative. - int y = abs(scroll_view->contents()->y()); - RowInfo row = GetRowInfo(y); - if (is_positive) { - return row.height - (y - row.origin); - } else if (y == row.origin) { - row = GetRowInfo(std::max(0, row.origin - 1)); - return y - row.origin; - } else { - return y - row.origin; - } -} - -VariableRowHeightScrollHelper::RowInfo - VariableRowHeightScrollHelper::GetRowInfo(int y) { - return controller_->GetRowInfo(y); -} - -// FixedRowHeightScrollHelper ----------------------------------------------- - -FixedRowHeightScrollHelper::FixedRowHeightScrollHelper(int top_margin, - int row_height) - : VariableRowHeightScrollHelper(NULL), - top_margin_(top_margin), - row_height_(row_height) { - DCHECK_GT(row_height, 0); -} - -VariableRowHeightScrollHelper::RowInfo - FixedRowHeightScrollHelper::GetRowInfo(int y) { - if (y < top_margin_) - return RowInfo(0, top_margin_); - return RowInfo((y - top_margin_) / row_height_ * row_height_ + top_margin_, - row_height_); -} - -} // namespace views
diff --git a/ui/views/controls/scroll_view.h b/ui/views/controls/scroll_view.h deleted file mode 100644 index 4dfcdfc..0000000 --- a/ui/views/controls/scroll_view.h +++ /dev/null
@@ -1,225 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_SCROLL_VIEW_H_ -#define UI_VIEWS_CONTROLS_SCROLL_VIEW_H_ - -#include <string> - -#include "base/compiler_specific.h" -#include "ui/views/controls/scrollbar/scroll_bar.h" - -namespace views { - -///////////////////////////////////////////////////////////////////////////// -// -// ScrollView class -// -// A ScrollView is used to make any View scrollable. The view is added to -// a viewport which takes care of clipping. -// -// In this current implementation both horizontal and vertical scrollbars are -// added as needed. -// -// The scrollview supports keyboard UI and mousewheel. -// -///////////////////////////////////////////////////////////////////////////// - -class VIEWS_EXPORT ScrollView : public View, public ScrollBarController { - public: - static const char kViewClassName[]; - - ScrollView(); - - virtual ~ScrollView(); - - // Creates a ScrollView with a theme specific border. - static ScrollView* CreateScrollViewWithBorder(); - - // Set the contents. Any previous contents will be deleted. The contents - // is the view that needs to scroll. - void SetContents(View* a_view); - const View* contents() const { return contents_; } - View* contents() { return contents_; } - - // Sets the header, deleting the previous header. - void SetHeader(View* header); - - // Returns the visible region of the content View. - gfx::Rect GetVisibleRect() const; - - void set_hide_horizontal_scrollbar(bool visible) { - hide_horizontal_scrollbar_ = visible; - } - - // Turns this scroll view into a bounded scroll view, with a fixed height. - // By default, a ScrollView will stretch to fill its outer container. - void ClipHeightTo(int min_height, int max_height); - - // Returns whether or not the ScrollView is bounded (as set by ClipHeightTo). - bool is_bounded() const { return max_height_ >= 0 && min_height_ >= 0; } - - // Retrieves the width/height of scrollbars. These return 0 if the scrollbar - // has not yet been created. - int GetScrollBarWidth() const; - int GetScrollBarHeight() const; - - // Returns the horizontal/vertical scrollbar. This may return NULL. - const ScrollBar* horizontal_scroll_bar() const { return horiz_sb_; } - const ScrollBar* vertical_scroll_bar() const { return vert_sb_; } - - // Customize the scrollbar design. ScrollView takes the ownership of the - // specified ScrollBar. |horiz_sb| and |vert_sb| cannot be NULL. - void SetHorizontalScrollBar(ScrollBar* horiz_sb); - void SetVerticalScrollBar(ScrollBar* vert_sb); - - // View overrides: - virtual gfx::Size GetPreferredSize() const override; - virtual int GetHeightForWidth(int width) const override; - virtual void Layout() override; - virtual bool OnKeyPressed(const ui::KeyEvent& event) override; - virtual bool OnMouseWheel(const ui::MouseWheelEvent& e) override; - virtual void OnMouseEntered(const ui::MouseEvent& event) override; - virtual void OnMouseExited(const ui::MouseEvent& event) override; - virtual void OnGestureEvent(ui::GestureEvent* event) override; - virtual const char* GetClassName() const override; - - // ScrollBarController overrides: - virtual void ScrollToPosition(ScrollBar* source, int position) override; - virtual int GetScrollIncrement(ScrollBar* source, - bool is_page, - bool is_positive) override; - - private: - FRIEND_TEST_ALL_PREFIXES(ScrollViewTest, CornerViewVisibility); - class Viewport; - - // Used internally by SetHeader() and SetContents() to reset the view. Sets - // |member| to |new_view|. If |new_view| is non-null it is added to |parent|. - void SetHeaderOrContents(View* parent, View* new_view, View** member); - - // Scrolls the minimum amount necessary to make the specified rectangle - // visible, in the coordinates of the contents view. The specified rectangle - // is constrained by the bounds of the contents view. This has no effect if - // the contents have not been set. - void ScrollContentsRegionToBeVisible(const gfx::Rect& rect); - - // Computes the visibility of both scrollbars, taking in account the view port - // and content sizes. - void ComputeScrollBarsVisibility(const gfx::Size& viewport_size, - const gfx::Size& content_size, - bool* horiz_is_shown, - bool* vert_is_shown) const; - - // Shows or hides the scrollbar/corner_view based on the value of - // |should_show|. - void SetControlVisibility(View* control, bool should_show); - - // Update the scrollbars positions given viewport and content sizes. - void UpdateScrollBarPositions(); - - // The current contents and its viewport. |contents_| is contained in - // |contents_viewport_|. - View* contents_; - View* contents_viewport_; - - // The current header and its viewport. |header_| is contained in - // |header_viewport_|. - View* header_; - View* header_viewport_; - - // Horizontal scrollbar. - ScrollBar* horiz_sb_; - - // Vertical scrollbar. - ScrollBar* vert_sb_; - - // Corner view. - View* corner_view_; - - // The min and max height for the bounded scroll view. These are negative - // values if the view is not bounded. - int min_height_; - int max_height_; - - // If true, never show the horizontal scrollbar (even if the contents is wider - // than the viewport). - bool hide_horizontal_scrollbar_; - - DISALLOW_COPY_AND_ASSIGN(ScrollView); -}; - -// VariableRowHeightScrollHelper is intended for views that contain rows of -// varying height. To use a VariableRowHeightScrollHelper create one supplying -// a Controller and delegate GetPageScrollIncrement and GetLineScrollIncrement -// to the helper. VariableRowHeightScrollHelper calls back to the -// Controller to determine row boundaries. -class VariableRowHeightScrollHelper { - public: - // The origin and height of a row. - struct RowInfo { - RowInfo(int origin, int height) : origin(origin), height(height) {} - - // Origin of the row. - int origin; - - // Height of the row. - int height; - }; - - // Used to determine row boundaries. - class Controller { - public: - // Returns the origin and size of the row at the specified location. - virtual VariableRowHeightScrollHelper::RowInfo GetRowInfo(int y) = 0; - }; - - // Creates a new VariableRowHeightScrollHelper. Controller is - // NOT deleted by this VariableRowHeightScrollHelper. - explicit VariableRowHeightScrollHelper(Controller* controller); - virtual ~VariableRowHeightScrollHelper(); - - // Delegate the View methods of the same name to these. The scroll amount is - // determined by querying the Controller for the appropriate row to scroll - // to. - int GetPageScrollIncrement(ScrollView* scroll_view, - bool is_horizontal, bool is_positive); - int GetLineScrollIncrement(ScrollView* scroll_view, - bool is_horizontal, bool is_positive); - - protected: - // Returns the row information for the row at the specified location. This - // calls through to the method of the same name on the controller. - virtual RowInfo GetRowInfo(int y); - - private: - Controller* controller_; - - DISALLOW_COPY_AND_ASSIGN(VariableRowHeightScrollHelper); -}; - -// FixedRowHeightScrollHelper is intended for views that contain fixed height -// height rows. To use a FixedRowHeightScrollHelper delegate -// GetPageScrollIncrement and GetLineScrollIncrement to it. -class FixedRowHeightScrollHelper : public VariableRowHeightScrollHelper { - public: - // Creates a FixedRowHeightScrollHelper. top_margin gives the distance from - // the top of the view to the first row, and may be 0. row_height gives the - // height of each row. - FixedRowHeightScrollHelper(int top_margin, int row_height); - - protected: - // Calculates the bounds of the row from the top margin and row height. - virtual RowInfo GetRowInfo(int y) override; - - private: - int top_margin_; - int row_height_; - - DISALLOW_COPY_AND_ASSIGN(FixedRowHeightScrollHelper); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_SCROLL_VIEW_H_
diff --git a/ui/views/controls/scroll_view_unittest.cc b/ui/views/controls/scroll_view_unittest.cc deleted file mode 100644 index 9baa4d3..0000000 --- a/ui/views/controls/scroll_view_unittest.cc +++ /dev/null
@@ -1,378 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/scroll_view.h" - -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/views/controls/scrollbar/overlay_scroll_bar.h" -#include "ui/views/test/test_views.h" - -namespace views { - -namespace { - -const int kWidth = 100; -const int kMinHeight = 50; -const int kMaxHeight = 100; - -// View implementation that allows setting the preferred size. -class CustomView : public View { - public: - CustomView() {} - - void SetPreferredSize(const gfx::Size& size) { - preferred_size_ = size; - PreferredSizeChanged(); - } - - virtual gfx::Size GetPreferredSize() const override { - return preferred_size_; - } - - virtual void Layout() override { - gfx::Size pref = GetPreferredSize(); - int width = pref.width(); - int height = pref.height(); - if (parent()) { - width = std::max(parent()->width(), width); - height = std::max(parent()->height(), height); - } - SetBounds(x(), y(), width, height); - } - - private: - gfx::Size preferred_size_; - - DISALLOW_COPY_AND_ASSIGN(CustomView); -}; - -} // namespace - -// Verifies the viewport is sized to fit the available space. -TEST(ScrollViewTest, ViewportSizedToFit) { - ScrollView scroll_view; - View* contents = new View; - scroll_view.SetContents(contents); - scroll_view.SetBoundsRect(gfx::Rect(0, 0, 100, 100)); - scroll_view.Layout(); - EXPECT_EQ("0,0 100x100", contents->parent()->bounds().ToString()); -} - -// Verifies the scrollbars are added as necessary. -TEST(ScrollViewTest, ScrollBars) { - ScrollView scroll_view; - View* contents = new View; - scroll_view.SetContents(contents); - scroll_view.SetBoundsRect(gfx::Rect(0, 0, 100, 100)); - - // Size the contents such that vertical scrollbar is needed. - contents->SetBounds(0, 0, 50, 400); - scroll_view.Layout(); - EXPECT_EQ(100 - scroll_view.GetScrollBarWidth(), contents->parent()->width()); - EXPECT_EQ(100, contents->parent()->height()); - EXPECT_TRUE(!scroll_view.horizontal_scroll_bar() || - !scroll_view.horizontal_scroll_bar()->visible()); - ASSERT_TRUE(scroll_view.vertical_scroll_bar() != NULL); - EXPECT_TRUE(scroll_view.vertical_scroll_bar()->visible()); - - // Size the contents such that horizontal scrollbar is needed. - contents->SetBounds(0, 0, 400, 50); - scroll_view.Layout(); - EXPECT_EQ(100, contents->parent()->width()); - EXPECT_EQ(100 - scroll_view.GetScrollBarHeight(), - contents->parent()->height()); - ASSERT_TRUE(scroll_view.horizontal_scroll_bar() != NULL); - EXPECT_TRUE(scroll_view.horizontal_scroll_bar()->visible()); - EXPECT_TRUE(!scroll_view.vertical_scroll_bar() || - !scroll_view.vertical_scroll_bar()->visible()); - - // Both horizontal and vertical. - contents->SetBounds(0, 0, 300, 400); - scroll_view.Layout(); - EXPECT_EQ(100 - scroll_view.GetScrollBarWidth(), contents->parent()->width()); - EXPECT_EQ(100 - scroll_view.GetScrollBarHeight(), - contents->parent()->height()); - ASSERT_TRUE(scroll_view.horizontal_scroll_bar() != NULL); - EXPECT_TRUE(scroll_view.horizontal_scroll_bar()->visible()); - ASSERT_TRUE(scroll_view.vertical_scroll_bar() != NULL); - EXPECT_TRUE(scroll_view.vertical_scroll_bar()->visible()); -} - -// Assertions around adding a header. -TEST(ScrollViewTest, Header) { - ScrollView scroll_view; - View* contents = new View; - CustomView* header = new CustomView; - scroll_view.SetHeader(header); - View* header_parent = header->parent(); - scroll_view.SetContents(contents); - scroll_view.SetBoundsRect(gfx::Rect(0, 0, 100, 100)); - scroll_view.Layout(); - // |header|s preferred size is empty, which should result in all space going - // to contents. - EXPECT_EQ("0,0 100x0", header->parent()->bounds().ToString()); - EXPECT_EQ("0,0 100x100", contents->parent()->bounds().ToString()); - - // Get the header a height of 20. - header->SetPreferredSize(gfx::Size(10, 20)); - EXPECT_EQ("0,0 100x20", header->parent()->bounds().ToString()); - EXPECT_EQ("0,20 100x80", contents->parent()->bounds().ToString()); - - // Remove the header. - scroll_view.SetHeader(NULL); - // SetHeader(NULL) deletes header. - header = NULL; - EXPECT_EQ("0,0 100x0", header_parent->bounds().ToString()); - EXPECT_EQ("0,0 100x100", contents->parent()->bounds().ToString()); -} - -// Verifies the scrollbars are added as necessary when a header is present. -TEST(ScrollViewTest, ScrollBarsWithHeader) { - ScrollView scroll_view; - View* contents = new View; - scroll_view.SetContents(contents); - CustomView* header = new CustomView; - scroll_view.SetHeader(header); - scroll_view.SetBoundsRect(gfx::Rect(0, 0, 100, 100)); - - header->SetPreferredSize(gfx::Size(10, 20)); - - // Size the contents such that vertical scrollbar is needed. - contents->SetBounds(0, 0, 50, 400); - scroll_view.Layout(); - EXPECT_EQ(0, contents->parent()->x()); - EXPECT_EQ(20, contents->parent()->y()); - EXPECT_EQ(100 - scroll_view.GetScrollBarWidth(), contents->parent()->width()); - EXPECT_EQ(80, contents->parent()->height()); - EXPECT_EQ(0, header->parent()->x()); - EXPECT_EQ(0, header->parent()->y()); - EXPECT_EQ(100 - scroll_view.GetScrollBarWidth(), header->parent()->width()); - EXPECT_EQ(20, header->parent()->height()); - EXPECT_TRUE(!scroll_view.horizontal_scroll_bar() || - !scroll_view.horizontal_scroll_bar()->visible()); - ASSERT_TRUE(scroll_view.vertical_scroll_bar() != NULL); - EXPECT_TRUE(scroll_view.vertical_scroll_bar()->visible()); - - // Size the contents such that horizontal scrollbar is needed. - contents->SetBounds(0, 0, 400, 50); - scroll_view.Layout(); - EXPECT_EQ(0, contents->parent()->x()); - EXPECT_EQ(20, contents->parent()->y()); - EXPECT_EQ(100, contents->parent()->width()); - EXPECT_EQ(100 - scroll_view.GetScrollBarHeight() - 20, - contents->parent()->height()); - EXPECT_EQ(0, header->parent()->x()); - EXPECT_EQ(0, header->parent()->y()); - EXPECT_EQ(100, header->parent()->width()); - EXPECT_EQ(20, header->parent()->height()); - ASSERT_TRUE(scroll_view.horizontal_scroll_bar() != NULL); - EXPECT_TRUE(scroll_view.horizontal_scroll_bar()->visible()); - EXPECT_TRUE(!scroll_view.vertical_scroll_bar() || - !scroll_view.vertical_scroll_bar()->visible()); - - // Both horizontal and vertical. - contents->SetBounds(0, 0, 300, 400); - scroll_view.Layout(); - EXPECT_EQ(0, contents->parent()->x()); - EXPECT_EQ(20, contents->parent()->y()); - EXPECT_EQ(100 - scroll_view.GetScrollBarWidth(), contents->parent()->width()); - EXPECT_EQ(100 - scroll_view.GetScrollBarHeight() - 20, - contents->parent()->height()); - EXPECT_EQ(0, header->parent()->x()); - EXPECT_EQ(0, header->parent()->y()); - EXPECT_EQ(100 - scroll_view.GetScrollBarWidth(), header->parent()->width()); - EXPECT_EQ(20, header->parent()->height()); - ASSERT_TRUE(scroll_view.horizontal_scroll_bar() != NULL); - EXPECT_TRUE(scroll_view.horizontal_scroll_bar()->visible()); - ASSERT_TRUE(scroll_view.vertical_scroll_bar() != NULL); - EXPECT_TRUE(scroll_view.vertical_scroll_bar()->visible()); -} - -// Verifies the header scrolls horizontally with the content. -TEST(ScrollViewTest, HeaderScrollsWithContent) { - ScrollView scroll_view; - CustomView* contents = new CustomView; - scroll_view.SetContents(contents); - contents->SetPreferredSize(gfx::Size(500, 500)); - - CustomView* header = new CustomView; - scroll_view.SetHeader(header); - header->SetPreferredSize(gfx::Size(500, 20)); - - scroll_view.SetBoundsRect(gfx::Rect(0, 0, 100, 100)); - EXPECT_EQ("0,0", contents->bounds().origin().ToString()); - EXPECT_EQ("0,0", header->bounds().origin().ToString()); - - // Scroll the horizontal scrollbar. - ASSERT_TRUE(scroll_view.horizontal_scroll_bar()); - scroll_view.ScrollToPosition( - const_cast<ScrollBar*>(scroll_view.horizontal_scroll_bar()), 1); - EXPECT_EQ("-1,0", contents->bounds().origin().ToString()); - EXPECT_EQ("-1,0", header->bounds().origin().ToString()); - - // Scrolling the vertical scrollbar shouldn't effect the header. - ASSERT_TRUE(scroll_view.vertical_scroll_bar()); - scroll_view.ScrollToPosition( - const_cast<ScrollBar*>(scroll_view.vertical_scroll_bar()), 1); - EXPECT_EQ("-1,-1", contents->bounds().origin().ToString()); - EXPECT_EQ("-1,0", header->bounds().origin().ToString()); -} - -// Verifies ScrollRectToVisible() on the child works. -TEST(ScrollViewTest, ScrollRectToVisible) { - ScrollView scroll_view; - CustomView* contents = new CustomView; - scroll_view.SetContents(contents); - contents->SetPreferredSize(gfx::Size(500, 1000)); - - scroll_view.SetBoundsRect(gfx::Rect(0, 0, 100, 100)); - scroll_view.Layout(); - EXPECT_EQ("0,0", contents->bounds().origin().ToString()); - - // Scroll to y=405 height=10, this should make the y position of the content - // at (405 + 10) - viewport_height (scroll region bottom aligned). - contents->ScrollRectToVisible(gfx::Rect(0, 405, 10, 10)); - const int viewport_height = contents->parent()->height(); - EXPECT_EQ(-(415 - viewport_height), contents->y()); - - // Scroll to the current y-location and 10x10; should do nothing. - contents->ScrollRectToVisible(gfx::Rect(0, -contents->y(), 10, 10)); - EXPECT_EQ(-(415 - viewport_height), contents->y()); -} - -// Verifies ClipHeightTo() uses the height of the content when it is between the -// minimum and maximum height values. -TEST(ScrollViewTest, ClipHeightToNormalContentHeight) { - ScrollView scroll_view; - - scroll_view.ClipHeightTo(kMinHeight, kMaxHeight); - - const int kNormalContentHeight = 75; - scroll_view.SetContents( - new views::StaticSizedView(gfx::Size(kWidth, kNormalContentHeight))); - - EXPECT_EQ(gfx::Size(kWidth, kNormalContentHeight), - scroll_view.GetPreferredSize()); - - scroll_view.SizeToPreferredSize(); - scroll_view.Layout(); - - EXPECT_EQ(gfx::Size(kWidth, kNormalContentHeight), - scroll_view.contents()->size()); - EXPECT_EQ(gfx::Size(kWidth, kNormalContentHeight), scroll_view.size()); -} - -// Verifies ClipHeightTo() uses the minimum height when the content is shorter -// thamn the minimum height value. -TEST(ScrollViewTest, ClipHeightToShortContentHeight) { - ScrollView scroll_view; - - scroll_view.ClipHeightTo(kMinHeight, kMaxHeight); - - const int kShortContentHeight = 10; - scroll_view.SetContents( - new views::StaticSizedView(gfx::Size(kWidth, kShortContentHeight))); - - EXPECT_EQ(gfx::Size(kWidth, kMinHeight), scroll_view.GetPreferredSize()); - - scroll_view.SizeToPreferredSize(); - scroll_view.Layout(); - - EXPECT_EQ(gfx::Size(kWidth, kShortContentHeight), - scroll_view.contents()->size()); - EXPECT_EQ(gfx::Size(kWidth, kMinHeight), scroll_view.size()); -} - -// Verifies ClipHeightTo() uses the maximum height when the content is longer -// thamn the maximum height value. -TEST(ScrollViewTest, ClipHeightToTallContentHeight) { - ScrollView scroll_view; - - // Use a scrollbar that is disabled by default, so the width of the content is - // not affected. - scroll_view.SetVerticalScrollBar(new views::OverlayScrollBar(false)); - - scroll_view.ClipHeightTo(kMinHeight, kMaxHeight); - - const int kTallContentHeight = 1000; - scroll_view.SetContents( - new views::StaticSizedView(gfx::Size(kWidth, kTallContentHeight))); - - EXPECT_EQ(gfx::Size(kWidth, kMaxHeight), scroll_view.GetPreferredSize()); - - scroll_view.SizeToPreferredSize(); - scroll_view.Layout(); - - EXPECT_EQ(gfx::Size(kWidth, kTallContentHeight), - scroll_view.contents()->size()); - EXPECT_EQ(gfx::Size(kWidth, kMaxHeight), scroll_view.size()); -} - -// Verifies that when ClipHeightTo() produces a scrollbar, it reduces the width -// of the inner content of the ScrollView. -TEST(ScrollViewTest, ClipHeightToScrollbarUsesWidth) { - ScrollView scroll_view; - - scroll_view.ClipHeightTo(kMinHeight, kMaxHeight); - - // Create a view that will be much taller than it is wide. - scroll_view.SetContents(new views::ProportionallySizedView(1000)); - - // Without any width, it will default to 0,0 but be overridden by min height. - scroll_view.SizeToPreferredSize(); - EXPECT_EQ(gfx::Size(0, kMinHeight), scroll_view.GetPreferredSize()); - - gfx::Size new_size(kWidth, scroll_view.GetHeightForWidth(kWidth)); - scroll_view.SetSize(new_size); - scroll_view.Layout(); - - int scroll_bar_width = scroll_view.GetScrollBarWidth(); - int expected_width = kWidth - scroll_bar_width; - EXPECT_EQ(scroll_view.contents()->size().width(), expected_width); - EXPECT_EQ(scroll_view.contents()->size().height(), 1000 * expected_width); - EXPECT_EQ(gfx::Size(kWidth, kMaxHeight), scroll_view.size()); -} - -TEST(ScrollViewTest, CornerViewVisibility) { - ScrollView scroll_view; - View* contents = new View; - scroll_view.SetContents(contents); - scroll_view.SetBoundsRect(gfx::Rect(0, 0, 100, 100)); - View* corner_view = scroll_view.corner_view_; - - // Corner view should be visible when both scrollbars are visible. - contents->SetBounds(0, 0, 200, 200); - scroll_view.Layout(); - EXPECT_EQ(&scroll_view, corner_view->parent()); - EXPECT_TRUE(corner_view->visible()); - - // Corner view should be aligned to the scrollbars. - EXPECT_EQ(scroll_view.vertical_scroll_bar()->x(), corner_view->x()); - EXPECT_EQ(scroll_view.horizontal_scroll_bar()->y(), corner_view->y()); - EXPECT_EQ(scroll_view.GetScrollBarWidth(), corner_view->width()); - EXPECT_EQ(scroll_view.GetScrollBarHeight(), corner_view->height()); - - // Corner view should be removed when only the vertical scrollbar is visible. - contents->SetBounds(0, 0, 50, 200); - scroll_view.Layout(); - EXPECT_FALSE(corner_view->parent()); - - // ... or when only the horizontal scrollbar is visible. - contents->SetBounds(0, 0, 200, 50); - scroll_view.Layout(); - EXPECT_FALSE(corner_view->parent()); - - // ... or when no scrollbar is visible. - contents->SetBounds(0, 0, 50, 50); - scroll_view.Layout(); - EXPECT_FALSE(corner_view->parent()); - - // Corner view should reappear when both scrollbars reappear. - contents->SetBounds(0, 0, 200, 200); - scroll_view.Layout(); - EXPECT_EQ(&scroll_view, corner_view->parent()); - EXPECT_TRUE(corner_view->visible()); -} - -} // namespace views
diff --git a/ui/views/controls/scrollbar/base_scroll_bar.cc b/ui/views/controls/scrollbar/base_scroll_bar.cc deleted file mode 100644 index 117fe34..0000000 --- a/ui/views/controls/scrollbar/base_scroll_bar.cc +++ /dev/null
@@ -1,517 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/scrollbar/base_scroll_bar.h" - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "base/callback.h" -#include "base/compiler_specific.h" -#include "base/message_loop/message_loop.h" -#include "base/strings/string16.h" -#include "base/strings/utf_string_conversions.h" -#include "build/build_config.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/events/event.h" -#include "ui/events/keycodes/keyboard_codes.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/geometry/safe_integer_conversions.h" -#include "ui/strings/grit/ui_strings.h" -#include "ui/views/controls/menu/menu_item_view.h" -#include "ui/views/controls/menu/menu_runner.h" -#include "ui/views/controls/scroll_view.h" -#include "ui/views/controls/scrollbar/base_scroll_bar_thumb.h" -#include "ui/views/widget/widget.h" - -#if defined(OS_LINUX) -#include "ui/gfx/screen.h" -#endif - -#undef min -#undef max - -namespace views { - -/////////////////////////////////////////////////////////////////////////////// -// BaseScrollBar, public: - -BaseScrollBar::BaseScrollBar(bool horizontal, BaseScrollBarThumb* thumb) - : ScrollBar(horizontal), - thumb_(thumb), - contents_size_(0), - contents_scroll_offset_(0), - viewport_size_(0), - thumb_track_state_(CustomButton::STATE_NORMAL), - last_scroll_amount_(SCROLL_NONE), - repeater_(base::Bind(&BaseScrollBar::TrackClicked, - base::Unretained(this))), - context_menu_mouse_position_(0) { - AddChildView(thumb_); - - set_context_menu_controller(this); - thumb_->set_context_menu_controller(this); -} - -void BaseScrollBar::ScrollByAmount(ScrollAmount amount) { - int offset = contents_scroll_offset_; - switch (amount) { - case SCROLL_START: - offset = GetMinPosition(); - break; - case SCROLL_END: - offset = GetMaxPosition(); - break; - case SCROLL_PREV_LINE: - offset -= GetScrollIncrement(false, false); - offset = std::max(GetMinPosition(), offset); - break; - case SCROLL_NEXT_LINE: - offset += GetScrollIncrement(false, true); - offset = std::min(GetMaxPosition(), offset); - break; - case SCROLL_PREV_PAGE: - offset -= GetScrollIncrement(true, false); - offset = std::max(GetMinPosition(), offset); - break; - case SCROLL_NEXT_PAGE: - offset += GetScrollIncrement(true, true); - offset = std::min(GetMaxPosition(), offset); - break; - default: - break; - } - contents_scroll_offset_ = offset; - ScrollContentsToOffset(); -} - -BaseScrollBar::~BaseScrollBar() { -} - -void BaseScrollBar::ScrollToThumbPosition(int thumb_position, - bool scroll_to_middle) { - contents_scroll_offset_ = - CalculateContentsOffset(thumb_position, scroll_to_middle); - if (contents_scroll_offset_ < GetMinPosition()) { - contents_scroll_offset_ = GetMinPosition(); - } else if (contents_scroll_offset_ > GetMaxPosition()) { - contents_scroll_offset_ = GetMaxPosition(); - } - ScrollContentsToOffset(); - SchedulePaint(); -} - -bool BaseScrollBar::ScrollByContentsOffset(int contents_offset) { - int old_offset = contents_scroll_offset_; - contents_scroll_offset_ -= contents_offset; - if (contents_scroll_offset_ < GetMinPosition()) { - contents_scroll_offset_ = GetMinPosition(); - } else if (contents_scroll_offset_ > GetMaxPosition()) { - contents_scroll_offset_ = GetMaxPosition(); - } - if (old_offset == contents_scroll_offset_) - return false; - - ScrollContentsToOffset(); - return true; -} - -void BaseScrollBar::OnThumbStateChanged(CustomButton::ButtonState old_state, - CustomButton::ButtonState new_state) { - if (old_state == CustomButton::STATE_PRESSED && - new_state == CustomButton::STATE_NORMAL && - GetThumbTrackState() == CustomButton::STATE_HOVERED) { - SetThumbTrackState(CustomButton::STATE_NORMAL); - } -} - -/////////////////////////////////////////////////////////////////////////////// -// BaseScrollBar, View implementation: - -bool BaseScrollBar::OnMousePressed(const ui::MouseEvent& event) { - if (event.IsOnlyLeftMouseButton()) - ProcessPressEvent(event); - return true; -} - -void BaseScrollBar::OnMouseReleased(const ui::MouseEvent& event) { - SetState(HitTestPoint(event.location()) ? - CustomButton::STATE_HOVERED : CustomButton::STATE_NORMAL); -} - -void BaseScrollBar::OnMouseCaptureLost() { - SetState(CustomButton::STATE_NORMAL); -} - -void BaseScrollBar::OnMouseEntered(const ui::MouseEvent& event) { - SetThumbTrackState(CustomButton::STATE_HOVERED); -} - -void BaseScrollBar::OnMouseExited(const ui::MouseEvent& event) { - if (GetThumbTrackState() == CustomButton::STATE_HOVERED) - SetState(CustomButton::STATE_NORMAL); -} - -bool BaseScrollBar::OnKeyPressed(const ui::KeyEvent& event) { - ScrollAmount amount = SCROLL_NONE; - switch (event.key_code()) { - case ui::VKEY_UP: - if (!IsHorizontal()) - amount = SCROLL_PREV_LINE; - break; - case ui::VKEY_DOWN: - if (!IsHorizontal()) - amount = SCROLL_NEXT_LINE; - break; - case ui::VKEY_LEFT: - if (IsHorizontal()) - amount = SCROLL_PREV_LINE; - break; - case ui::VKEY_RIGHT: - if (IsHorizontal()) - amount = SCROLL_NEXT_LINE; - break; - case ui::VKEY_PRIOR: - amount = SCROLL_PREV_PAGE; - break; - case ui::VKEY_NEXT: - amount = SCROLL_NEXT_PAGE; - break; - case ui::VKEY_HOME: - amount = SCROLL_START; - break; - case ui::VKEY_END: - amount = SCROLL_END; - break; - default: - break; - } - if (amount != SCROLL_NONE) { - ScrollByAmount(amount); - return true; - } - return false; -} - -bool BaseScrollBar::OnMouseWheel(const ui::MouseWheelEvent& event) { - OnScroll(event.x_offset(), event.y_offset()); - return true; -} - -void BaseScrollBar::OnGestureEvent(ui::GestureEvent* event) { - // If a fling is in progress, then stop the fling for any incoming gesture - // event (except for the GESTURE_END event that is generated at the end of the - // fling). - if (scroll_animator_.get() && scroll_animator_->is_scrolling() && - (event->type() != ui::ET_GESTURE_END || - event->details().touch_points() > 1)) { - scroll_animator_->Stop(); - } - - if (event->type() == ui::ET_GESTURE_TAP_DOWN) { - ProcessPressEvent(*event); - event->SetHandled(); - return; - } - - if (event->type() == ui::ET_GESTURE_LONG_PRESS) { - // For a long-press, the repeater started in tap-down should continue. So - // return early. - return; - } - - SetState(CustomButton::STATE_NORMAL); - - if (event->type() == ui::ET_GESTURE_TAP) { - // TAP_DOWN would have already scrolled some amount. So scrolling again on - // TAP is not necessary. - event->SetHandled(); - return; - } - - if (event->type() == ui::ET_GESTURE_SCROLL_BEGIN || - event->type() == ui::ET_GESTURE_SCROLL_END) { - event->SetHandled(); - return; - } - - if (event->type() == ui::ET_GESTURE_SCROLL_UPDATE) { - float scroll_amount_f; - int scroll_amount; - if (IsHorizontal()) { - scroll_amount_f = event->details().scroll_x() - roundoff_error_.x(); - scroll_amount = gfx::ToRoundedInt(scroll_amount_f); - roundoff_error_.set_x(scroll_amount - scroll_amount_f); - } else { - scroll_amount_f = event->details().scroll_y() - roundoff_error_.y(); - scroll_amount = gfx::ToRoundedInt(scroll_amount_f); - roundoff_error_.set_y(scroll_amount - scroll_amount_f); - } - if (ScrollByContentsOffset(scroll_amount)) - event->SetHandled(); - return; - } - - if (event->type() == ui::ET_SCROLL_FLING_START) { - if (!scroll_animator_.get()) - scroll_animator_.reset(new ScrollAnimator(this)); - scroll_animator_->Start( - IsHorizontal() ? event->details().velocity_x() : 0.f, - IsHorizontal() ? 0.f : event->details().velocity_y()); - event->SetHandled(); - } -} - -/////////////////////////////////////////////////////////////////////////////// -// BaseScrollBar, ScrollDelegate implementation: - -bool BaseScrollBar::OnScroll(float dx, float dy) { - return IsHorizontal() ? ScrollByContentsOffset(dx) : - ScrollByContentsOffset(dy); -} - -/////////////////////////////////////////////////////////////////////////////// -// BaseScrollBar, ContextMenuController implementation: - -enum ScrollBarContextMenuCommands { - ScrollBarContextMenuCommand_ScrollHere = 1, - ScrollBarContextMenuCommand_ScrollStart, - ScrollBarContextMenuCommand_ScrollEnd, - ScrollBarContextMenuCommand_ScrollPageUp, - ScrollBarContextMenuCommand_ScrollPageDown, - ScrollBarContextMenuCommand_ScrollPrev, - ScrollBarContextMenuCommand_ScrollNext -}; - -void BaseScrollBar::ShowContextMenuForView(View* source, - const gfx::Point& p, - ui::MenuSourceType source_type) { - Widget* widget = GetWidget(); - gfx::Rect widget_bounds = widget->GetWindowBoundsInScreen(); - gfx::Point temp_pt(p.x() - widget_bounds.x(), p.y() - widget_bounds.y()); - View::ConvertPointFromWidget(this, &temp_pt); - context_menu_mouse_position_ = IsHorizontal() ? temp_pt.x() : temp_pt.y(); - - views::MenuItemView* menu = new views::MenuItemView(this); - // MenuRunner takes ownership of |menu|. - menu_runner_.reset(new MenuRunner( - menu, MenuRunner::HAS_MNEMONICS | views::MenuRunner::CONTEXT_MENU)); - menu->AppendDelegateMenuItem(ScrollBarContextMenuCommand_ScrollHere); - menu->AppendSeparator(); - menu->AppendDelegateMenuItem(ScrollBarContextMenuCommand_ScrollStart); - menu->AppendDelegateMenuItem(ScrollBarContextMenuCommand_ScrollEnd); - menu->AppendSeparator(); - menu->AppendDelegateMenuItem(ScrollBarContextMenuCommand_ScrollPageUp); - menu->AppendDelegateMenuItem(ScrollBarContextMenuCommand_ScrollPageDown); - menu->AppendSeparator(); - menu->AppendDelegateMenuItem(ScrollBarContextMenuCommand_ScrollPrev); - menu->AppendDelegateMenuItem(ScrollBarContextMenuCommand_ScrollNext); - if (menu_runner_->RunMenuAt(GetWidget(), - NULL, - gfx::Rect(p, gfx::Size()), - MENU_ANCHOR_TOPLEFT, - source_type) == MenuRunner::MENU_DELETED) { - return; - } -} - -/////////////////////////////////////////////////////////////////////////////// -// BaseScrollBar, Menu::Delegate implementation: - -base::string16 BaseScrollBar::GetLabel(int id) const { - int ids_value = 0; - switch (id) { - case ScrollBarContextMenuCommand_ScrollHere: - ids_value = IDS_APP_SCROLLBAR_CXMENU_SCROLLHERE; - break; - case ScrollBarContextMenuCommand_ScrollStart: - ids_value = IsHorizontal() ? IDS_APP_SCROLLBAR_CXMENU_SCROLLLEFTEDGE - : IDS_APP_SCROLLBAR_CXMENU_SCROLLHOME; - break; - case ScrollBarContextMenuCommand_ScrollEnd: - ids_value = IsHorizontal() ? IDS_APP_SCROLLBAR_CXMENU_SCROLLRIGHTEDGE - : IDS_APP_SCROLLBAR_CXMENU_SCROLLEND; - break; - case ScrollBarContextMenuCommand_ScrollPageUp: - ids_value = IDS_APP_SCROLLBAR_CXMENU_SCROLLPAGEUP; - break; - case ScrollBarContextMenuCommand_ScrollPageDown: - ids_value = IDS_APP_SCROLLBAR_CXMENU_SCROLLPAGEDOWN; - break; - case ScrollBarContextMenuCommand_ScrollPrev: - ids_value = IsHorizontal() ? IDS_APP_SCROLLBAR_CXMENU_SCROLLLEFT - : IDS_APP_SCROLLBAR_CXMENU_SCROLLUP; - break; - case ScrollBarContextMenuCommand_ScrollNext: - ids_value = IsHorizontal() ? IDS_APP_SCROLLBAR_CXMENU_SCROLLRIGHT - : IDS_APP_SCROLLBAR_CXMENU_SCROLLDOWN; - break; - default: - NOTREACHED() << "Invalid BaseScrollBar Context Menu command!"; - } - - return ids_value ? l10n_util::GetStringUTF16(ids_value) : base::string16(); -} - -bool BaseScrollBar::IsCommandEnabled(int id) const { - switch (id) { - case ScrollBarContextMenuCommand_ScrollPageUp: - case ScrollBarContextMenuCommand_ScrollPageDown: - return !IsHorizontal(); - } - return true; -} - -void BaseScrollBar::ExecuteCommand(int id) { - switch (id) { - case ScrollBarContextMenuCommand_ScrollHere: - ScrollToThumbPosition(context_menu_mouse_position_, true); - break; - case ScrollBarContextMenuCommand_ScrollStart: - ScrollByAmount(SCROLL_START); - break; - case ScrollBarContextMenuCommand_ScrollEnd: - ScrollByAmount(SCROLL_END); - break; - case ScrollBarContextMenuCommand_ScrollPageUp: - ScrollByAmount(SCROLL_PREV_PAGE); - break; - case ScrollBarContextMenuCommand_ScrollPageDown: - ScrollByAmount(SCROLL_NEXT_PAGE); - break; - case ScrollBarContextMenuCommand_ScrollPrev: - ScrollByAmount(SCROLL_PREV_LINE); - break; - case ScrollBarContextMenuCommand_ScrollNext: - ScrollByAmount(SCROLL_NEXT_LINE); - break; - } -} - -/////////////////////////////////////////////////////////////////////////////// -// BaseScrollBar, ScrollBar implementation: - -void BaseScrollBar::Update(int viewport_size, - int content_size, - int contents_scroll_offset) { - ScrollBar::Update(viewport_size, content_size, contents_scroll_offset); - - // Make sure contents_size is always > 0 to avoid divide by zero errors in - // calculations throughout this code. - contents_size_ = std::max(1, content_size); - - viewport_size_ = std::max(1, viewport_size); - - if (content_size < 0) - content_size = 0; - if (contents_scroll_offset < 0) - contents_scroll_offset = 0; - if (contents_scroll_offset > content_size) - contents_scroll_offset = content_size; - contents_scroll_offset_ = contents_scroll_offset; - - // Thumb Height and Thumb Pos. - // The height of the thumb is the ratio of the Viewport height to the - // content size multiplied by the height of the thumb track. - double ratio = static_cast<double>(viewport_size) / contents_size_; - int thumb_size = static_cast<int>(ratio * GetTrackSize()); - thumb_->SetSize(thumb_size); - - int thumb_position = CalculateThumbPosition(contents_scroll_offset); - thumb_->SetPosition(thumb_position); -} - -int BaseScrollBar::GetPosition() const { - return thumb_->GetPosition(); -} - -/////////////////////////////////////////////////////////////////////////////// -// BaseScrollBar, protected: - -BaseScrollBarThumb* BaseScrollBar::GetThumb() const { - return thumb_; -} - -CustomButton::ButtonState BaseScrollBar::GetThumbTrackState() const { - return thumb_track_state_; -} - -void BaseScrollBar::ScrollToPosition(int position) { - controller()->ScrollToPosition(this, position); -} - -int BaseScrollBar::GetScrollIncrement(bool is_page, bool is_positive) { - return controller()->GetScrollIncrement(this, is_page, is_positive); -} - -/////////////////////////////////////////////////////////////////////////////// -// BaseScrollBar, private: - -int BaseScrollBar::GetThumbSizeForTest() { - return thumb_->GetSize(); -} - -void BaseScrollBar::ProcessPressEvent(const ui::LocatedEvent& event) { - SetThumbTrackState(CustomButton::STATE_PRESSED); - gfx::Rect thumb_bounds = thumb_->bounds(); - if (IsHorizontal()) { - if (GetMirroredXInView(event.x()) < thumb_bounds.x()) { - last_scroll_amount_ = SCROLL_PREV_PAGE; - } else if (GetMirroredXInView(event.x()) > thumb_bounds.right()) { - last_scroll_amount_ = SCROLL_NEXT_PAGE; - } - } else { - if (event.y() < thumb_bounds.y()) { - last_scroll_amount_ = SCROLL_PREV_PAGE; - } else if (event.y() > thumb_bounds.bottom()) { - last_scroll_amount_ = SCROLL_NEXT_PAGE; - } - } - TrackClicked(); - repeater_.Start(); -} - -void BaseScrollBar::SetState(CustomButton::ButtonState state) { - SetThumbTrackState(state); - repeater_.Stop(); -} - -void BaseScrollBar::TrackClicked() { - if (last_scroll_amount_ != SCROLL_NONE) - ScrollByAmount(last_scroll_amount_); -} - -void BaseScrollBar::ScrollContentsToOffset() { - ScrollToPosition(contents_scroll_offset_); - thumb_->SetPosition(CalculateThumbPosition(contents_scroll_offset_)); -} - -int BaseScrollBar::GetTrackSize() const { - gfx::Rect track_bounds = GetTrackBounds(); - return IsHorizontal() ? track_bounds.width() : track_bounds.height(); -} - -int BaseScrollBar::CalculateThumbPosition(int contents_scroll_offset) const { - // In some combination of viewport_size and contents_size_, the result of - // simple division can be rounded and there could be 1 pixel gap even when the - // contents scroll down to the bottom. See crbug.com/244671 - if (contents_scroll_offset + viewport_size_ == contents_size_) { - int track_size = GetTrackSize(); - return track_size - (viewport_size_ * GetTrackSize() / contents_size_); - } - return (contents_scroll_offset * GetTrackSize()) / contents_size_; -} - -int BaseScrollBar::CalculateContentsOffset(int thumb_position, - bool scroll_to_middle) const { - if (scroll_to_middle) - thumb_position = thumb_position - (thumb_->GetSize() / 2); - return (thumb_position * contents_size_) / GetTrackSize(); -} - -void BaseScrollBar::SetThumbTrackState(CustomButton::ButtonState state) { - thumb_track_state_ = state; - SchedulePaint(); -} - -} // namespace views
diff --git a/ui/views/controls/scrollbar/base_scroll_bar.h b/ui/views/controls/scrollbar/base_scroll_bar.h deleted file mode 100644 index b68e22a..0000000 --- a/ui/views/controls/scrollbar/base_scroll_bar.h +++ /dev/null
@@ -1,192 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_SCROLLBAR_BASE_SCROLL_BAR_H_ -#define UI_VIEWS_CONTROLS_SCROLLBAR_BASE_SCROLL_BAR_H_ - -#include "base/gtest_prod_util.h" -#include "ui/views/animation/scroll_animator.h" -#include "ui/views/context_menu_controller.h" -#include "ui/views/controls/button/image_button.h" -#include "ui/views/controls/menu/menu_delegate.h" -#include "ui/views/controls/scrollbar/scroll_bar.h" -#include "ui/views/repeat_controller.h" - -namespace views { - -class BaseScrollBarThumb; -class MenuRunner; - -/////////////////////////////////////////////////////////////////////////////// -// -// BaseScrollBar -// -/////////////////////////////////////////////////////////////////////////////// -class VIEWS_EXPORT BaseScrollBar : public ScrollBar, - public ScrollDelegate, - public ContextMenuController, - public MenuDelegate { - public: - BaseScrollBar(bool horizontal, BaseScrollBarThumb* thumb); - virtual ~BaseScrollBar(); - - // Get the bounds of the "track" area that the thumb is free to slide within. - virtual gfx::Rect GetTrackBounds() const = 0; - - // An enumeration of different amounts of incremental scroll, representing - // events sent from different parts of the UI/keyboard. - enum ScrollAmount { - SCROLL_NONE = 0, - SCROLL_START, - SCROLL_END, - SCROLL_PREV_LINE, - SCROLL_NEXT_LINE, - SCROLL_PREV_PAGE, - SCROLL_NEXT_PAGE, - }; - - // Scroll the contents by the specified type (see ScrollAmount above). - void ScrollByAmount(ScrollAmount amount); - - // Scroll the contents to the appropriate position given the supplied - // position of the thumb (thumb track coordinates). If |scroll_to_middle| is - // true, then the conversion assumes |thumb_position| is in the middle of the - // thumb rather than the top. - void ScrollToThumbPosition(int thumb_position, bool scroll_to_middle); - - // Scroll the contents by the specified offset (contents coordinates). - bool ScrollByContentsOffset(int contents_offset); - - // Called when the thumb state has been changed from |old_state| to - // |new_state|. - void OnThumbStateChanged(CustomButton::ButtonState old_state, - CustomButton::ButtonState new_state); - - // View overrides: - virtual gfx::Size GetPreferredSize() const override = 0; - virtual void Layout() override = 0; - virtual bool OnMousePressed(const ui::MouseEvent& event) override; - virtual void OnMouseReleased(const ui::MouseEvent& event) override; - virtual void OnMouseCaptureLost() override; - virtual void OnMouseEntered(const ui::MouseEvent& event) override; - virtual void OnMouseExited(const ui::MouseEvent& event) override; - virtual bool OnKeyPressed(const ui::KeyEvent& event) override; - virtual bool OnMouseWheel(const ui::MouseWheelEvent& event) override; - - // ui::EventHandler overrides: - virtual void OnGestureEvent(ui::GestureEvent* event) override; - - // ScrollBar overrides: - virtual void Update(int viewport_size, - int content_size, - int contents_scroll_offset) override; - virtual int GetLayoutSize() const override = 0; - virtual int GetPosition() const override; - - // ScrollDelegate overrides: - virtual bool OnScroll(float dx, float dy) override; - - // ContextMenuController overrides: - virtual void ShowContextMenuForView(View* source, - const gfx::Point& point, - ui::MenuSourceType source_type) override; - - // Menu::Delegate overrides: - virtual base::string16 GetLabel(int id) const override; - virtual bool IsCommandEnabled(int id) const override; - virtual void ExecuteCommand(int id) override; - - protected: - // View overrides: - virtual void OnPaint(gfx::Canvas* canvas) override = 0; - - BaseScrollBarThumb* GetThumb() const; - CustomButton::ButtonState GetThumbTrackState() const; - - // Wrapper functions that calls the controller. We need this since native - // scrollbars wrap around a different scrollbar. When calling the controller - // we need to pass in the appropriate scrollbar. For normal scrollbars it's - // the |this| scrollbar, for native scrollbars it's the native scrollbar used - // to create this. - virtual void ScrollToPosition(int position); - virtual int GetScrollIncrement(bool is_page, bool is_positive); - - private: - FRIEND_TEST_ALL_PREFIXES(NativeScrollBarTest, ScrollBarFitsToBottom); - int GetThumbSizeForTest(); - - // Changes to 'pushed' state and starts a timer to scroll repeatedly. - void ProcessPressEvent(const ui::LocatedEvent& event); - - // Sets state to |state| and stops the repeater. - void SetState(CustomButton::ButtonState state); - - // Called when the mouse is pressed down in the track area. - void TrackClicked(); - - // Responsible for scrolling the contents and also updating the UI to the - // current value of the Scroll Offset. - void ScrollContentsToOffset(); - - // Returns the size (width or height) of the track area of the ScrollBar. - int GetTrackSize() const; - - // Calculate the position of the thumb within the track based on the - // specified scroll offset of the contents. - int CalculateThumbPosition(int contents_scroll_offset) const; - - // Calculates the current value of the contents offset (contents coordinates) - // based on the current thumb position (thumb track coordinates). See - // |ScrollToThumbPosition| for an explanation of |scroll_to_middle|. - int CalculateContentsOffset(int thumb_position, - bool scroll_to_middle) const; - - // Called when the state of the thumb track changes (e.g. by the user - // pressing the mouse button down in it). - void SetThumbTrackState(CustomButton::ButtonState state); - - BaseScrollBarThumb* thumb_; - - // The size of the scrolled contents, in pixels. - int contents_size_; - - // The current amount the contents is offset by in the viewport. - int contents_scroll_offset_; - - // The current size of the view port, in pixels. - int viewport_size_; - - // The state of the scrollbar track. Typically, the track will highlight when - // the user presses the mouse on them (during page scrolling). - CustomButton::ButtonState thumb_track_state_; - - // The last amount of incremental scroll that this scrollbar performed. This - // is accessed by the callbacks for the auto-repeat up/down buttons to know - // what direction to repeatedly scroll in. - ScrollAmount last_scroll_amount_; - - // An instance of a RepeatController which scrolls the scrollbar continuously - // as the user presses the mouse button down on the up/down buttons or the - // track. - RepeatController repeater_; - - // The position of the mouse within the scroll bar when the context menu - // was invoked. - int context_menu_mouse_position_; - - scoped_ptr<MenuRunner> menu_runner_; - scoped_ptr<ScrollAnimator> scroll_animator_; - - // Difference between current position and cumulative deltas obtained from - // scroll update events. - // TODO(tdresser): This should be removed when raw pixel scrolling for views - // is enabled. See crbug.com/329354. - gfx::Vector2dF roundoff_error_; - - DISALLOW_COPY_AND_ASSIGN(BaseScrollBar); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_SCROLLBAR_BASE_SCROLL_BAR_H_
diff --git a/ui/views/controls/scrollbar/base_scroll_bar_button.cc b/ui/views/controls/scrollbar/base_scroll_bar_button.cc deleted file mode 100644 index 0a765c4..0000000 --- a/ui/views/controls/scrollbar/base_scroll_bar_button.cc +++ /dev/null
@@ -1,48 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/scrollbar/base_scroll_bar_button.h" - -#include "base/bind.h" -#include "base/bind_helpers.h" -#include "ui/gfx/screen.h" - -namespace views { - -BaseScrollBarButton::BaseScrollBarButton(ButtonListener* listener) - : CustomButton(listener), - repeater_(base::Bind(&BaseScrollBarButton::RepeaterNotifyClick, - base::Unretained(this))) { -} - -BaseScrollBarButton::~BaseScrollBarButton() { -} - -bool BaseScrollBarButton::OnMousePressed(const ui::MouseEvent& event) { - Button::NotifyClick(event); - repeater_.Start(); - return true; -} - -void BaseScrollBarButton::OnMouseReleased(const ui::MouseEvent& event) { - OnMouseCaptureLost(); -} - -void BaseScrollBarButton::OnMouseCaptureLost() { - repeater_.Stop(); -} - -void BaseScrollBarButton::RepeaterNotifyClick() { - // TODO(sky): See if we can convert to using |Screen| everywhere. - // TODO(scottmg): Native is wrong: http://crbug.com/133312 - gfx::Point cursor_point = - gfx::Screen::GetNativeScreen()->GetCursorScreenPoint(); - ui::MouseEvent event(ui::ET_MOUSE_RELEASED, - cursor_point, cursor_point, - ui::EF_LEFT_MOUSE_BUTTON, - ui::EF_LEFT_MOUSE_BUTTON); - Button::NotifyClick(event); -} - -} // namespace views
diff --git a/ui/views/controls/scrollbar/base_scroll_bar_button.h b/ui/views/controls/scrollbar/base_scroll_bar_button.h deleted file mode 100644 index b264e6d..0000000 --- a/ui/views/controls/scrollbar/base_scroll_bar_button.h +++ /dev/null
@@ -1,49 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_SCROLLBAR_BASE_SCROLL_BAR_BUTTON_H_ -#define UI_VIEWS_CONTROLS_SCROLLBAR_BASE_SCROLL_BAR_BUTTON_H_ - -#include "ui/views/controls/button/custom_button.h" - -#include "ui/views/repeat_controller.h" - -#if defined(OS_LINUX) -#include "ui/gfx/screen.h" -#endif - -namespace views { - -/////////////////////////////////////////////////////////////////////////////// -// -// ScrollBarButton -// -// A button that activates on mouse pressed rather than released, and that -// continues to fire the clicked action as the mouse button remains pressed -// down on the button. -// -/////////////////////////////////////////////////////////////////////////////// -class VIEWS_EXPORT BaseScrollBarButton : public CustomButton { - public: - explicit BaseScrollBarButton(ButtonListener* listener); - virtual ~BaseScrollBarButton(); - - protected: - virtual bool OnMousePressed(const ui::MouseEvent& event) override; - virtual void OnMouseReleased(const ui::MouseEvent& event) override; - virtual void OnMouseCaptureLost() override; - - private: - void RepeaterNotifyClick(); - - // The repeat controller that we use to repeatedly click the button when the - // mouse button is down. - RepeatController repeater_; - - DISALLOW_COPY_AND_ASSIGN(BaseScrollBarButton); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_SCROLLBAR_BASE_SCROLL_BAR_BUTTON_H_
diff --git a/ui/views/controls/scrollbar/base_scroll_bar_thumb.cc b/ui/views/controls/scrollbar/base_scroll_bar_thumb.cc deleted file mode 100644 index 2e40640..0000000 --- a/ui/views/controls/scrollbar/base_scroll_bar_thumb.cc +++ /dev/null
@@ -1,135 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/scrollbar/base_scroll_bar_thumb.h" - -#include "ui/gfx/canvas.h" -#include "ui/gfx/rect.h" -#include "ui/views/controls/scrollbar/base_scroll_bar.h" - -namespace { -// The distance the mouse can be dragged outside the bounds of the thumb during -// dragging before the scrollbar will snap back to its regular position. -static const int kScrollThumbDragOutSnap = 100; -} - -namespace views { - -BaseScrollBarThumb::BaseScrollBarThumb(BaseScrollBar* scroll_bar) - : scroll_bar_(scroll_bar), - drag_start_position_(-1), - mouse_offset_(-1), - state_(CustomButton::STATE_NORMAL) { -} - -BaseScrollBarThumb::~BaseScrollBarThumb() { -} - -void BaseScrollBarThumb::SetSize(int size) { - // Make sure the thumb is never sized smaller than its minimum possible - // display size. - gfx::Size prefsize = GetPreferredSize(); - size = std::max(size, scroll_bar_->IsHorizontal() ? prefsize.width() : - prefsize.height()); - gfx::Rect thumb_bounds = bounds(); - if (scroll_bar_->IsHorizontal()) { - thumb_bounds.set_width(size); - } else { - thumb_bounds.set_height(size); - } - SetBoundsRect(thumb_bounds); -} - -int BaseScrollBarThumb::GetSize() const { - if (scroll_bar_->IsHorizontal()) - return width(); - return height(); -} - -void BaseScrollBarThumb::SetPosition(int position) { - gfx::Rect thumb_bounds = bounds(); - gfx::Rect track_bounds = scroll_bar_->GetTrackBounds(); - if (scroll_bar_->IsHorizontal()) { - thumb_bounds.set_x(track_bounds.x() + position); - } else { - thumb_bounds.set_y(track_bounds.y() + position); - } - SetBoundsRect(thumb_bounds); -} - -int BaseScrollBarThumb::GetPosition() const { - gfx::Rect track_bounds = scroll_bar_->GetTrackBounds(); - if (scroll_bar_->IsHorizontal()) - return x() - track_bounds.x(); - return y() - track_bounds.y(); -} - -void BaseScrollBarThumb::OnMouseEntered(const ui::MouseEvent& event) { - SetState(CustomButton::STATE_HOVERED); -} - -void BaseScrollBarThumb::OnMouseExited(const ui::MouseEvent& event) { - SetState(CustomButton::STATE_NORMAL); -} - -bool BaseScrollBarThumb::OnMousePressed(const ui::MouseEvent& event) { - mouse_offset_ = scroll_bar_->IsHorizontal() ? event.x() : event.y(); - drag_start_position_ = GetPosition(); - SetState(CustomButton::STATE_PRESSED); - return true; -} - -bool BaseScrollBarThumb::OnMouseDragged(const ui::MouseEvent& event) { - // If the user moves the mouse more than |kScrollThumbDragOutSnap| outside - // the bounds of the thumb, the scrollbar will snap the scroll back to the - // point it was at before the drag began. - if (scroll_bar_->IsHorizontal()) { - if ((event.y() < y() - kScrollThumbDragOutSnap) || - (event.y() > (y() + height() + kScrollThumbDragOutSnap))) { - scroll_bar_->ScrollToThumbPosition(drag_start_position_, false); - return true; - } - } else { - if ((event.x() < x() - kScrollThumbDragOutSnap) || - (event.x() > (x() + width() + kScrollThumbDragOutSnap))) { - scroll_bar_->ScrollToThumbPosition(drag_start_position_, false); - return true; - } - } - if (scroll_bar_->IsHorizontal()) { - int thumb_x = event.x() - mouse_offset_; - if (base::i18n::IsRTL()) - thumb_x *= -1; - scroll_bar_->ScrollToThumbPosition(GetPosition() + thumb_x, false); - } else { - int thumb_y = event.y() - mouse_offset_; - scroll_bar_->ScrollToThumbPosition(GetPosition() + thumb_y, false); - } - return true; -} - -void BaseScrollBarThumb::OnMouseReleased(const ui::MouseEvent& event) { - SetState(HitTestPoint(event.location()) ? - CustomButton::STATE_HOVERED : CustomButton::STATE_NORMAL); -} - -void BaseScrollBarThumb::OnMouseCaptureLost() { - SetState(CustomButton::STATE_HOVERED); -} - -CustomButton::ButtonState BaseScrollBarThumb::GetState() const { - return state_; -} - -void BaseScrollBarThumb::SetState(CustomButton::ButtonState state) { - if (state_ == state) - return; - - CustomButton::ButtonState old_state = state_; - state_ = state; - scroll_bar_->OnThumbStateChanged(old_state, state); - SchedulePaint(); -} - -} // namespace views
diff --git a/ui/views/controls/scrollbar/base_scroll_bar_thumb.h b/ui/views/controls/scrollbar/base_scroll_bar_thumb.h deleted file mode 100644 index 5e9dbc6..0000000 --- a/ui/views/controls/scrollbar/base_scroll_bar_thumb.h +++ /dev/null
@@ -1,83 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_SCROLLBAR_BASE_SCROLL_BAR_THUMB_H_ -#define UI_VIEWS_CONTROLS_SCROLLBAR_BASE_SCROLL_BAR_THUMB_H_ - -#include "ui/gfx/size.h" -#include "ui/views/controls/button/custom_button.h" -#include "ui/views/controls/scrollbar/scroll_bar.h" -#include "ui/views/view.h" - -namespace gfx { -class Canvas; -} - -namespace views { - -class BaseScrollBar; - -/////////////////////////////////////////////////////////////////////////////// -// -// BaseScrollBarThumb -// -// A view that acts as the thumb in the scroll bar track that the user can -// drag to scroll the associated contents view within the viewport. -// -/////////////////////////////////////////////////////////////////////////////// -class VIEWS_EXPORT BaseScrollBarThumb : public View { - public: - explicit BaseScrollBarThumb(BaseScrollBar* scroll_bar); - virtual ~BaseScrollBarThumb(); - - // Sets the size (width or height) of the thumb to the specified value. - void SetSize(int size); - - // Retrieves the size (width or height) of the thumb. - int GetSize() const; - - // Sets the position of the thumb on the x or y axis. - void SetPosition(int position); - - // Gets the position of the thumb on the x or y axis. - int GetPosition() const; - - // View overrides: - virtual gfx::Size GetPreferredSize() const override = 0; - - protected: - // View overrides: - virtual void OnPaint(gfx::Canvas* canvas) override = 0; - virtual void OnMouseEntered(const ui::MouseEvent& event) override; - virtual void OnMouseExited(const ui::MouseEvent& event) override; - virtual bool OnMousePressed(const ui::MouseEvent& event) override; - virtual bool OnMouseDragged(const ui::MouseEvent& event) override; - virtual void OnMouseReleased(const ui::MouseEvent& event) override; - virtual void OnMouseCaptureLost() override; - - CustomButton::ButtonState GetState() const; - // Update our state and schedule a repaint when the mouse moves over us. - void SetState(CustomButton::ButtonState state); - - BaseScrollBar* scroll_bar() { return scroll_bar_; } - - private: - // The BaseScrollBar that owns us. - BaseScrollBar* scroll_bar_; - - int drag_start_position_; - - // The position of the mouse on the scroll axis relative to the top of this - // View when the drag started. - int mouse_offset_; - - // The current state of the thumb button. - CustomButton::ButtonState state_; - - DISALLOW_COPY_AND_ASSIGN(BaseScrollBarThumb); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_SCROLLBAR_BASE_SCROLL_BAR_THUMB_H_
diff --git a/ui/views/controls/scrollbar/kennedy_scroll_bar.cc b/ui/views/controls/scrollbar/kennedy_scroll_bar.cc deleted file mode 100644 index 13a7823..0000000 --- a/ui/views/controls/scrollbar/kennedy_scroll_bar.cc +++ /dev/null
@@ -1,107 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/scrollbar/kennedy_scroll_bar.h" - -#include "third_party/skia/include/core/SkColor.h" -#include "third_party/skia/include/core/SkXfermode.h" -#include "ui/gfx/canvas.h" -#include "ui/views/background.h" -#include "ui/views/border.h" -#include "ui/views/controls/scrollbar/base_scroll_bar_thumb.h" - -namespace views { -namespace { - -const int kScrollbarWidth = 10; -const int kThumbMinimumSize = kScrollbarWidth * 2; -const SkColor kBorderColor = SkColorSetARGB(32, 0, 0, 0); -const SkColor kThumbHoverColor = SkColorSetARGB(128, 0, 0, 0); -const SkColor kThumbDefaultColor = SkColorSetARGB(64, 0, 0, 0); -const SkColor kTrackHoverColor = SkColorSetARGB(32, 0, 0, 0); - -class KennedyScrollBarThumb : public BaseScrollBarThumb { - public: - explicit KennedyScrollBarThumb(BaseScrollBar* scroll_bar); - virtual ~KennedyScrollBarThumb(); - - protected: - // View overrides: - virtual gfx::Size GetPreferredSize() const override; - virtual void OnPaint(gfx::Canvas* canvas) override; - - private: - DISALLOW_COPY_AND_ASSIGN(KennedyScrollBarThumb); -}; - -KennedyScrollBarThumb::KennedyScrollBarThumb(BaseScrollBar* scroll_bar) - : BaseScrollBarThumb(scroll_bar) { -} - -KennedyScrollBarThumb::~KennedyScrollBarThumb() { -} - -gfx::Size KennedyScrollBarThumb::GetPreferredSize() const { - return gfx::Size(kThumbMinimumSize, kThumbMinimumSize); -} - -void KennedyScrollBarThumb::OnPaint(gfx::Canvas* canvas) { - gfx::Rect local_bounds(GetLocalBounds()); - canvas->FillRect(local_bounds, - (GetState() == CustomButton::STATE_HOVERED || - GetState() == CustomButton::STATE_PRESSED) ? - kThumbHoverColor : kThumbDefaultColor); - canvas->DrawRect(local_bounds, kBorderColor); -} - -} // namespace - -KennedyScrollBar::KennedyScrollBar(bool horizontal) - : BaseScrollBar(horizontal, new KennedyScrollBarThumb(this)) { - set_notify_enter_exit_on_child(true); -} - -KennedyScrollBar::~KennedyScrollBar() { -} - -gfx::Rect KennedyScrollBar::GetTrackBounds() const { - gfx::Rect local_bounds(GetLocalBounds()); - gfx::Size track_size = local_bounds.size(); - track_size.SetToMax(GetThumb()->size()); - local_bounds.set_size(track_size); - return local_bounds; -} - -int KennedyScrollBar::GetLayoutSize() const { - return kScrollbarWidth; -} - -gfx::Size KennedyScrollBar::GetPreferredSize() const { - return GetTrackBounds().size(); -} - -void KennedyScrollBar::Layout() { - gfx::Rect thumb_bounds = GetTrackBounds(); - BaseScrollBarThumb* thumb = GetThumb(); - if (IsHorizontal()) { - thumb_bounds.set_x(thumb->x()); - thumb_bounds.set_width(thumb->width()); - } else { - thumb_bounds.set_y(thumb->y()); - thumb_bounds.set_height(thumb->height()); - } - thumb->SetBoundsRect(thumb_bounds); -} - -void KennedyScrollBar::OnPaint(gfx::Canvas* canvas) { - CustomButton::ButtonState state = GetThumbTrackState(); - if ((state == CustomButton::STATE_HOVERED) || - (state == CustomButton::STATE_PRESSED)) { - gfx::Rect local_bounds(GetLocalBounds()); - canvas->FillRect(local_bounds, kTrackHoverColor); - canvas->DrawRect(local_bounds, kBorderColor); - } -} - -} // namespace views
diff --git a/ui/views/controls/scrollbar/kennedy_scroll_bar.h b/ui/views/controls/scrollbar/kennedy_scroll_bar.h deleted file mode 100644 index bd67a05..0000000 --- a/ui/views/controls/scrollbar/kennedy_scroll_bar.h +++ /dev/null
@@ -1,38 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_SCROLLBAR_KENNEDY_SCROLL_BAR_H_ -#define UI_VIEWS_CONTROLS_SCROLLBAR_KENNEDY_SCROLL_BAR_H_ - -#include "ui/views/controls/scrollbar/base_scroll_bar.h" - -namespace views { - -// The scrollbar of kennedy style. Transparent track and grey rectangle -// thumb. Right now it doesn't have the way to share the background, -// so it will accept the background color instead. -class VIEWS_EXPORT KennedyScrollBar : public BaseScrollBar { - public: - explicit KennedyScrollBar(bool horizontal); - virtual ~KennedyScrollBar(); - - protected: - // BaseScrollBar overrides: - virtual gfx::Rect GetTrackBounds() const override; - - // ScrollBar overrides: - virtual int GetLayoutSize() const override; - - // View overrides: - virtual gfx::Size GetPreferredSize() const override; - virtual void Layout() override; - virtual void OnPaint(gfx::Canvas* canvas) override; - - private: - DISALLOW_COPY_AND_ASSIGN(KennedyScrollBar); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_SCROLLBAR_KENNEDY_SCROLL_BAR_H_
diff --git a/ui/views/controls/scrollbar/native_scroll_bar.cc b/ui/views/controls/scrollbar/native_scroll_bar.cc deleted file mode 100644 index a768af5..0000000 --- a/ui/views/controls/scrollbar/native_scroll_bar.cc +++ /dev/null
@@ -1,113 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/scrollbar/native_scroll_bar.h" - -#include <algorithm> -#include <string> - -#include "base/message_loop/message_loop.h" -#include "ui/events/event.h" -#include "ui/views/controls/scrollbar/native_scroll_bar_views.h" -#include "ui/views/controls/scrollbar/native_scroll_bar_wrapper.h" -#include "ui/views/widget/widget.h" - -namespace views { - -// static -const char NativeScrollBar::kViewClassName[] = "NativeScrollBar"; - -//////////////////////////////////////////////////////////////////////////////// -// NativeScrollBar, public: -NativeScrollBar::NativeScrollBar(bool is_horizontal) - : ScrollBar(is_horizontal), - native_wrapper_(NULL) { -} - -NativeScrollBar::~NativeScrollBar() { -} - -// static -int NativeScrollBar::GetHorizontalScrollBarHeight( - const ui::NativeTheme* theme) { - return NativeScrollBarWrapper::GetHorizontalScrollBarHeight(theme); -} - -// static -int NativeScrollBar::GetVerticalScrollBarWidth( - const ui::NativeTheme* theme) { - return NativeScrollBarWrapper::GetVerticalScrollBarWidth(theme); -} - -//////////////////////////////////////////////////////////////////////////////// -// NativeScrollBar, View overrides: -gfx::Size NativeScrollBar::GetPreferredSize() const { - if (native_wrapper_) - return native_wrapper_->GetView()->GetPreferredSize(); - return gfx::Size(); -} - -void NativeScrollBar::Layout() { - if (native_wrapper_) { - native_wrapper_->GetView()->SetBounds(0, 0, width(), height()); - native_wrapper_->GetView()->Layout(); - } -} - -void NativeScrollBar::ViewHierarchyChanged( - const ViewHierarchyChangedDetails& details) { - if (details.is_add && !native_wrapper_ && GetWidget()) { - native_wrapper_ = NativeScrollBarWrapper::CreateWrapper(this); - AddChildView(native_wrapper_->GetView()); - } -} - -const char* NativeScrollBar::GetClassName() const { - return kViewClassName; -} - -// Overridden from View for keyboard UI. -bool NativeScrollBar::OnKeyPressed(const ui::KeyEvent& event) { - if (!native_wrapper_) - return false; - return native_wrapper_->GetView()->OnKeyPressed(event); -} - -void NativeScrollBar::OnGestureEvent(ui::GestureEvent* event) { - if (!native_wrapper_) - return; - native_wrapper_->GetView()->OnGestureEvent(event); -} - -bool NativeScrollBar::OnMouseWheel(const ui::MouseWheelEvent& event) { - if (!native_wrapper_) - return false; - return native_wrapper_->GetView()->OnMouseWheel(event); -} - -//////////////////////////////////////////////////////////////////////////////// -// NativeScrollBar, ScrollBar overrides: -void NativeScrollBar::Update(int viewport_size, - int content_size, - int current_pos) { - ScrollBar::Update(viewport_size, content_size, current_pos); - - if (native_wrapper_) - native_wrapper_->Update(viewport_size, content_size, current_pos); -} - -int NativeScrollBar::GetLayoutSize() const { - return IsHorizontal() ? - GetHorizontalScrollBarHeight(GetNativeTheme()) : - GetVerticalScrollBarWidth(GetNativeTheme()); -} - -int NativeScrollBar::GetPosition() const { - if (!native_wrapper_) - return 0; - return native_wrapper_->GetPosition(); -} - -} // namespace views -
diff --git a/ui/views/controls/scrollbar/native_scroll_bar.h b/ui/views/controls/scrollbar/native_scroll_bar.h deleted file mode 100644 index 8536111..0000000 --- a/ui/views/controls/scrollbar/native_scroll_bar.h +++ /dev/null
@@ -1,71 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_SCROLLBAR_NATIVE_SCROLL_BAR_H_ -#define UI_VIEWS_CONTROLS_SCROLLBAR_NATIVE_SCROLL_BAR_H_ - -#include <string> - -#include "base/compiler_specific.h" -#include "base/gtest_prod_util.h" -#include "ui/views/controls/scrollbar/scroll_bar.h" -#include "ui/views/view.h" - -namespace ui { -class NativeTheme; -} - -namespace views { - -class NativeScrollBarWrapper; - -// The NativeScrollBar class is a scrollbar that uses platform's -// native control. -class VIEWS_EXPORT NativeScrollBar : public ScrollBar { - public: - // The scroll-bar's class name. - static const char kViewClassName[]; - - // Create new scrollbar, either horizontal or vertical. - explicit NativeScrollBar(bool is_horiz); - virtual ~NativeScrollBar(); - - // Return the system sizes. - static int GetHorizontalScrollBarHeight(const ui::NativeTheme* theme); - static int GetVerticalScrollBarWidth(const ui::NativeTheme* theme); - - private: - friend class NativeScrollBarTest; - FRIEND_TEST_ALL_PREFIXES(NativeScrollBarTest, Scrolling); - - // Overridden from View. - virtual gfx::Size GetPreferredSize() const override; - virtual void Layout() override; - virtual void ViewHierarchyChanged( - const ViewHierarchyChangedDetails& details) override; - virtual const char* GetClassName() const override; - - // Overrideen from View for keyboard UI purpose. - virtual bool OnKeyPressed(const ui::KeyEvent& event) override; - virtual bool OnMouseWheel(const ui::MouseWheelEvent& e) override; - - // Overridden from ui::EventHandler. - virtual void OnGestureEvent(ui::GestureEvent* event) override; - - // Overridden from ScrollBar. - virtual void Update(int viewport_size, - int content_size, - int current_pos) override; - virtual int GetPosition() const override; - virtual int GetLayoutSize() const override; - - // init border - NativeScrollBarWrapper* native_wrapper_; - - DISALLOW_COPY_AND_ASSIGN(NativeScrollBar); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_SCROLLBAR_NATIVE_SCROLL_BAR_H_
diff --git a/ui/views/controls/scrollbar/native_scroll_bar_views.cc b/ui/views/controls/scrollbar/native_scroll_bar_views.cc deleted file mode 100644 index 4ffa8df..0000000 --- a/ui/views/controls/scrollbar/native_scroll_bar_views.cc +++ /dev/null
@@ -1,424 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/scrollbar/native_scroll_bar_views.h" - -#include "base/logging.h" -#include "ui/events/keycodes/keyboard_codes.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/path.h" -#include "ui/views/controls/button/custom_button.h" -#include "ui/views/controls/focusable_border.h" -#include "ui/views/controls/scrollbar/base_scroll_bar_button.h" -#include "ui/views/controls/scrollbar/base_scroll_bar_thumb.h" -#include "ui/views/controls/scrollbar/native_scroll_bar.h" -#include "ui/views/controls/scrollbar/scroll_bar.h" - -namespace views { - -namespace { - -// Wrapper for the scroll buttons. -class ScrollBarButton : public BaseScrollBarButton { - public: - enum Type { - UP, - DOWN, - LEFT, - RIGHT, - }; - - ScrollBarButton(ButtonListener* listener, Type type); - virtual ~ScrollBarButton(); - - virtual gfx::Size GetPreferredSize() const override; - virtual const char* GetClassName() const override { - return "ScrollBarButton"; - } - - protected: - virtual void OnPaint(gfx::Canvas* canvas) override; - - private: - ui::NativeTheme::ExtraParams GetNativeThemeParams() const; - ui::NativeTheme::Part GetNativeThemePart() const; - ui::NativeTheme::State GetNativeThemeState() const; - - Type type_; -}; - -// Wrapper for the scroll thumb -class ScrollBarThumb : public BaseScrollBarThumb { - public: - explicit ScrollBarThumb(BaseScrollBar* scroll_bar); - virtual ~ScrollBarThumb(); - - virtual gfx::Size GetPreferredSize() const override; - virtual const char* GetClassName() const override { - return "ScrollBarThumb"; - } - - protected: - virtual void OnPaint(gfx::Canvas* canvas) override; - - private: - ui::NativeTheme::ExtraParams GetNativeThemeParams() const; - ui::NativeTheme::Part GetNativeThemePart() const; - ui::NativeTheme::State GetNativeThemeState() const; - - ScrollBar* scroll_bar_; -}; - -///////////////////////////////////////////////////////////////////////////// -// ScrollBarButton - -ScrollBarButton::ScrollBarButton(ButtonListener* listener, Type type) - : BaseScrollBarButton(listener), - type_(type) { - SetFocusable(false); - SetAccessibilityFocusable(false); -} - -ScrollBarButton::~ScrollBarButton() { -} - -gfx::Size ScrollBarButton::GetPreferredSize() const { - return GetNativeTheme()->GetPartSize(GetNativeThemePart(), - GetNativeThemeState(), - GetNativeThemeParams()); -} - -void ScrollBarButton::OnPaint(gfx::Canvas* canvas) { - gfx::Rect bounds(GetPreferredSize()); - GetNativeTheme()->Paint(canvas->sk_canvas(), GetNativeThemePart(), - GetNativeThemeState(), bounds, - GetNativeThemeParams()); -} - -ui::NativeTheme::ExtraParams - ScrollBarButton::GetNativeThemeParams() const { - ui::NativeTheme::ExtraParams params; - - switch (state_) { - case CustomButton::STATE_HOVERED: - params.scrollbar_arrow.is_hovering = true; - break; - default: - params.scrollbar_arrow.is_hovering = false; - break; - } - - return params; -} - -ui::NativeTheme::Part - ScrollBarButton::GetNativeThemePart() const { - switch (type_) { - case UP: - return ui::NativeTheme::kScrollbarUpArrow; - case DOWN: - return ui::NativeTheme::kScrollbarDownArrow; - case LEFT: - return ui::NativeTheme::kScrollbarLeftArrow; - case RIGHT: - return ui::NativeTheme::kScrollbarRightArrow; - default: - return ui::NativeTheme::kScrollbarUpArrow; - } -} - -ui::NativeTheme::State - ScrollBarButton::GetNativeThemeState() const { - ui::NativeTheme::State state; - - switch (state_) { - case CustomButton::STATE_HOVERED: - state = ui::NativeTheme::kHovered; - break; - case CustomButton::STATE_PRESSED: - state = ui::NativeTheme::kPressed; - break; - case CustomButton::STATE_DISABLED: - state = ui::NativeTheme::kDisabled; - break; - case CustomButton::STATE_NORMAL: - default: - state = ui::NativeTheme::kNormal; - break; - } - - return state; -} - -///////////////////////////////////////////////////////////////////////////// -// ScrollBarThumb - -ScrollBarThumb::ScrollBarThumb(BaseScrollBar* scroll_bar) - : BaseScrollBarThumb(scroll_bar), - scroll_bar_(scroll_bar) { - SetFocusable(false); - SetAccessibilityFocusable(false); -} - -ScrollBarThumb::~ScrollBarThumb() { -} - -gfx::Size ScrollBarThumb::GetPreferredSize() const { - return GetNativeTheme()->GetPartSize(GetNativeThemePart(), - GetNativeThemeState(), - GetNativeThemeParams()); -} - -void ScrollBarThumb::OnPaint(gfx::Canvas* canvas) { - const gfx::Rect local_bounds(GetLocalBounds()); - const ui::NativeTheme::State theme_state = GetNativeThemeState(); - const ui::NativeTheme::ExtraParams extra_params(GetNativeThemeParams()); - GetNativeTheme()->Paint(canvas->sk_canvas(), - GetNativeThemePart(), - theme_state, - local_bounds, - extra_params); - const ui::NativeTheme::Part gripper_part = scroll_bar_->IsHorizontal() ? - ui::NativeTheme::kScrollbarHorizontalGripper : - ui::NativeTheme::kScrollbarVerticalGripper; - GetNativeTheme()->Paint(canvas->sk_canvas(), gripper_part, theme_state, - local_bounds, extra_params); -} - -ui::NativeTheme::ExtraParams ScrollBarThumb::GetNativeThemeParams() const { - // This gives the behavior we want. - ui::NativeTheme::ExtraParams params; - params.scrollbar_thumb.is_hovering = - (GetState() != CustomButton::STATE_HOVERED); - return params; -} - -ui::NativeTheme::Part ScrollBarThumb::GetNativeThemePart() const { - if (scroll_bar_->IsHorizontal()) - return ui::NativeTheme::kScrollbarHorizontalThumb; - return ui::NativeTheme::kScrollbarVerticalThumb; -} - -ui::NativeTheme::State ScrollBarThumb::GetNativeThemeState() const { - ui::NativeTheme::State state; - - switch (GetState()) { - case CustomButton::STATE_HOVERED: - state = ui::NativeTheme::kHovered; - break; - case CustomButton::STATE_PRESSED: - state = ui::NativeTheme::kPressed; - break; - case CustomButton::STATE_DISABLED: - state = ui::NativeTheme::kDisabled; - break; - case CustomButton::STATE_NORMAL: - default: - state = ui::NativeTheme::kNormal; - break; - } - - return state; -} - -} // namespace - -//////////////////////////////////////////////////////////////////////////////// -// NativeScrollBarViews, public: - -const char NativeScrollBarViews::kViewClassName[] = "NativeScrollBarViews"; - -NativeScrollBarViews::NativeScrollBarViews(NativeScrollBar* scroll_bar) - : BaseScrollBar(scroll_bar->IsHorizontal(), - new ScrollBarThumb(this)), - native_scroll_bar_(scroll_bar) { - set_controller(native_scroll_bar_->controller()); - - if (native_scroll_bar_->IsHorizontal()) { - prev_button_ = new ScrollBarButton(this, ScrollBarButton::LEFT); - next_button_ = new ScrollBarButton(this, ScrollBarButton::RIGHT); - - part_ = ui::NativeTheme::kScrollbarHorizontalTrack; - } else { - prev_button_ = new ScrollBarButton(this, ScrollBarButton::UP); - next_button_ = new ScrollBarButton(this, ScrollBarButton::DOWN); - - part_ = ui::NativeTheme::kScrollbarVerticalTrack; - } - - state_ = ui::NativeTheme::kNormal; - - AddChildView(prev_button_); - AddChildView(next_button_); - - prev_button_->set_context_menu_controller(this); - next_button_->set_context_menu_controller(this); -} - -NativeScrollBarViews::~NativeScrollBarViews() { -} - -//////////////////////////////////////////////////////////////////////////////// -// NativeScrollBarViews, View overrides: - -void NativeScrollBarViews::Layout() { - gfx::Size size = prev_button_->GetPreferredSize(); - prev_button_->SetBounds(0, 0, size.width(), size.height()); - - if (native_scroll_bar_->IsHorizontal()) { - next_button_->SetBounds(width() - size.width(), 0, - size.width(), size.height()); - } else { - next_button_->SetBounds(0, height() - size.height(), - size.width(), size.height()); - } - - GetThumb()->SetBoundsRect(GetTrackBounds()); -} - -void NativeScrollBarViews::OnPaint(gfx::Canvas* canvas) { - gfx::Rect bounds = GetTrackBounds(); - - if (bounds.IsEmpty()) - return; - - params_.scrollbar_track.track_x = bounds.x(); - params_.scrollbar_track.track_y = bounds.y(); - params_.scrollbar_track.track_width = bounds.width(); - params_.scrollbar_track.track_height = bounds.height(); - params_.scrollbar_track.classic_state = 0; - - GetNativeTheme()->Paint(canvas->sk_canvas(), part_, state_, bounds, params_); -} - -gfx::Size NativeScrollBarViews::GetPreferredSize() const { - const ui::NativeTheme* theme = native_scroll_bar_->GetNativeTheme(); - if (native_scroll_bar_->IsHorizontal()) - return gfx::Size(0, GetHorizontalScrollBarHeight(theme)); - return gfx::Size(GetVerticalScrollBarWidth(theme), 0); -} - -const char* NativeScrollBarViews::GetClassName() const { - return kViewClassName; -} - -int NativeScrollBarViews::GetLayoutSize() const { - gfx::Size size = prev_button_->GetPreferredSize(); - return IsHorizontal() ? size.height() : size.width(); -} - -void NativeScrollBarViews::ScrollToPosition(int position) { - controller()->ScrollToPosition(native_scroll_bar_, position); -} - -int NativeScrollBarViews::GetScrollIncrement(bool is_page, bool is_positive) { - return controller()->GetScrollIncrement(native_scroll_bar_, - is_page, - is_positive); -} - -////////////////////////////////////////////////////////////////////////////// -// BaseButton::ButtonListener overrides: - -void NativeScrollBarViews::ButtonPressed(Button* sender, - const ui::Event& event) { - if (sender == prev_button_) { - ScrollByAmount(SCROLL_PREV_LINE); - } else if (sender == next_button_) { - ScrollByAmount(SCROLL_NEXT_LINE); - } -} - -//////////////////////////////////////////////////////////////////////////////// -// NativeScrollBarViews, NativeScrollBarWrapper overrides: - -int NativeScrollBarViews::GetPosition() const { - return BaseScrollBar::GetPosition(); -} - -View* NativeScrollBarViews::GetView() { - return this; -} - -void NativeScrollBarViews::Update(int viewport_size, - int content_size, - int current_pos) { - BaseScrollBar::Update(viewport_size, content_size, current_pos); -} - -//////////////////////////////////////////////////////////////////////////////// -// NativeScrollBarViews, private: - -gfx::Rect NativeScrollBarViews::GetTrackBounds() const { - gfx::Rect bounds = GetLocalBounds(); - gfx::Size size = prev_button_->GetPreferredSize(); - BaseScrollBarThumb* thumb = GetThumb(); - - if (native_scroll_bar_->IsHorizontal()) { - bounds.set_x(bounds.x() + size.width()); - bounds.set_width(std::max(0, bounds.width() - 2 * size.width())); - bounds.set_height(thumb->GetPreferredSize().height()); - } else { - bounds.set_y(bounds.y() + size.height()); - bounds.set_height(std::max(0, bounds.height() - 2 * size.height())); - bounds.set_width(thumb->GetPreferredSize().width()); - } - - return bounds; -} - -//////////////////////////////////////////////////////////////////////////////// -// NativewScrollBarWrapper, public: - -// static -NativeScrollBarWrapper* NativeScrollBarWrapper::CreateWrapper( - NativeScrollBar* scroll_bar) { - return new NativeScrollBarViews(scroll_bar); -} - -// static -int NativeScrollBarWrapper::GetHorizontalScrollBarHeight( - const ui::NativeTheme* theme) { - if (!theme) - theme = ui::NativeTheme::instance(); - ui::NativeTheme::ExtraParams button_params; - button_params.scrollbar_arrow.is_hovering = false; - gfx::Size button_size = theme->GetPartSize( - ui::NativeTheme::kScrollbarLeftArrow, - ui::NativeTheme::kNormal, - button_params); - - ui::NativeTheme::ExtraParams thumb_params; - thumb_params.scrollbar_thumb.is_hovering = false; - gfx::Size track_size = theme->GetPartSize( - ui::NativeTheme::kScrollbarHorizontalThumb, - ui::NativeTheme::kNormal, - thumb_params); - - return std::max(track_size.height(), button_size.height()); -} - -// static -int NativeScrollBarWrapper::GetVerticalScrollBarWidth( - const ui::NativeTheme* theme) { - if (!theme) - theme = ui::NativeTheme::instance(); - ui::NativeTheme::ExtraParams button_params; - button_params.scrollbar_arrow.is_hovering = false; - gfx::Size button_size = theme->GetPartSize( - ui::NativeTheme::kScrollbarUpArrow, - ui::NativeTheme::kNormal, - button_params); - - ui::NativeTheme::ExtraParams thumb_params; - thumb_params.scrollbar_thumb.is_hovering = false; - gfx::Size track_size = theme->GetPartSize( - ui::NativeTheme::kScrollbarVerticalThumb, - ui::NativeTheme::kNormal, - thumb_params); - - return std::max(track_size.width(), button_size.width()); -} - -} // namespace views
diff --git a/ui/views/controls/scrollbar/native_scroll_bar_views.h b/ui/views/controls/scrollbar/native_scroll_bar_views.h deleted file mode 100644 index 9dd6b6d..0000000 --- a/ui/views/controls/scrollbar/native_scroll_bar_views.h +++ /dev/null
@@ -1,80 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_SCROLLBAR_NATIVE_SCROLL_BAR_VIEWS_H_ -#define UI_VIEWS_CONTROLS_SCROLLBAR_NATIVE_SCROLL_BAR_VIEWS_H_ - -#include "base/compiler_specific.h" -#include "ui/gfx/point.h" -#include "ui/native_theme/native_theme.h" -#include "ui/views/controls/button/button.h" -#include "ui/views/controls/scrollbar/base_scroll_bar.h" -#include "ui/views/controls/scrollbar/native_scroll_bar_wrapper.h" -#include "ui/views/view.h" - -namespace gfx { -class Canvas; -} - -namespace views { - -class NativeScrollBar; - -// Views implementation for the scrollbar. -class VIEWS_EXPORT NativeScrollBarViews : public BaseScrollBar, - public ButtonListener, - public NativeScrollBarWrapper { - public: - static const char kViewClassName[]; - - // Creates new scrollbar, either horizontal or vertical. - explicit NativeScrollBarViews(NativeScrollBar* native_scroll_bar); - virtual ~NativeScrollBarViews(); - - private: - // View overrides: - virtual void Layout() override; - virtual void OnPaint(gfx::Canvas* canvas) override; - virtual gfx::Size GetPreferredSize() const override; - virtual const char* GetClassName() const override; - - // ScrollBar overrides: - virtual int GetLayoutSize() const override; - - // BaseScrollBar overrides: - virtual void ScrollToPosition(int position) override; - virtual int GetScrollIncrement(bool is_page, bool is_positive) override; - - // BaseButton::ButtonListener overrides: - virtual void ButtonPressed(Button* sender, - const ui::Event& event) override; - - // NativeScrollBarWrapper overrides: - virtual int GetPosition() const override; - virtual View* GetView() override; - virtual void Update(int viewport_size, - int content_size, - int current_pos) override; - - // Returns the area for the track. This is the area of the scrollbar minus - // the size of the arrow buttons. - virtual gfx::Rect GetTrackBounds() const override; - - // The NativeScrollBar we are bound to. - NativeScrollBar* native_scroll_bar_; - - // The scroll bar buttons (Up/Down, Left/Right). - Button* prev_button_; - Button* next_button_; - - ui::NativeTheme::ExtraParams params_; - ui::NativeTheme::Part part_; - ui::NativeTheme::State state_; - - DISALLOW_COPY_AND_ASSIGN(NativeScrollBarViews); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_SCROLLBAR_NATIVE_SCROLL_BAR_VIEWS_H_
diff --git a/ui/views/controls/scrollbar/native_scroll_bar_wrapper.h b/ui/views/controls/scrollbar/native_scroll_bar_wrapper.h deleted file mode 100644 index 6f4e45a..0000000 --- a/ui/views/controls/scrollbar/native_scroll_bar_wrapper.h +++ /dev/null
@@ -1,45 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_SCROLLBAR_NATIVE_SCROLL_BAR_WRAPPER_H_ -#define UI_VIEWS_CONTROLS_SCROLLBAR_NATIVE_SCROLL_BAR_WRAPPER_H_ - -#include "ui/views/views_export.h" - -namespace ui { -class NativeTheme; -} - -namespace views { - -class NativeScrollBar; -class View; - -// A specialization of NativeControlWrapper that hosts a platform-native -// scroll bar. -class VIEWS_EXPORT NativeScrollBarWrapper { - public: - virtual ~NativeScrollBarWrapper() {} - - // Updates the scroll bar appearance given a viewport size, content size and - // current position. - virtual void Update(int viewport_size, int content_size, int current_pos) = 0; - - // Retrieves the views::View that hosts the native control. - virtual View* GetView() = 0; - - // Returns the position of the scrollbar. - virtual int GetPosition() const = 0; - - // Creates an appropriate NativeScrollBarWrapper for the platform. - static NativeScrollBarWrapper* CreateWrapper(NativeScrollBar* button); - - // Returns the system sizes of vertical/horizontal scroll bars. - static int GetVerticalScrollBarWidth(const ui::NativeTheme* theme); - static int GetHorizontalScrollBarHeight(const ui::NativeTheme* theme); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_SCROLLBAR_NATIVE_SCROLL_BAR_WRAPPER_H_
diff --git a/ui/views/controls/scrollbar/overlay_scroll_bar.cc b/ui/views/controls/scrollbar/overlay_scroll_bar.cc deleted file mode 100644 index ad54fd7..0000000 --- a/ui/views/controls/scrollbar/overlay_scroll_bar.cc +++ /dev/null
@@ -1,161 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/scrollbar/overlay_scroll_bar.h" - -#include "third_party/skia/include/core/SkColor.h" -#include "third_party/skia/include/core/SkXfermode.h" -#include "ui/gfx/canvas.h" -#include "ui/views/background.h" -#include "ui/views/border.h" -#include "ui/views/controls/scrollbar/base_scroll_bar_thumb.h" - -namespace views { -namespace { - -const int kScrollbarWidth = 10; -const int kThumbInsetInside = 3; -const int kThumbInsetFromEdge = 1; -const int kThumbCornerRadius = 2; -const int kThumbMinimumSize = kScrollbarWidth; -const int kThumbHoverAlpha = 128; -const int kThumbDefaultAlpha = 64; - -class OverlayScrollBarThumb : public BaseScrollBarThumb, - public gfx::AnimationDelegate { - public: - explicit OverlayScrollBarThumb(BaseScrollBar* scroll_bar); - virtual ~OverlayScrollBarThumb(); - - protected: - // View overrides: - virtual gfx::Size GetPreferredSize() const override; - virtual void OnPaint(gfx::Canvas* canvas) override; - - // gfx::AnimationDelegate overrides: - virtual void AnimationProgressed(const gfx::Animation* animation) override; - - private: - double animation_opacity_; - DISALLOW_COPY_AND_ASSIGN(OverlayScrollBarThumb); -}; - -OverlayScrollBarThumb::OverlayScrollBarThumb(BaseScrollBar* scroll_bar) - : BaseScrollBarThumb(scroll_bar), - animation_opacity_(0.0) { - // This is necessary, otherwise the thumb will be rendered below the views if - // those views paint to their own layers. - SetPaintToLayer(true); - SetFillsBoundsOpaquely(false); -} - -OverlayScrollBarThumb::~OverlayScrollBarThumb() { -} - -gfx::Size OverlayScrollBarThumb::GetPreferredSize() const { - return gfx::Size(kThumbMinimumSize, kThumbMinimumSize); -} - -void OverlayScrollBarThumb::OnPaint(gfx::Canvas* canvas) { - gfx::Rect local_bounds(GetLocalBounds()); - SkPaint paint; - int alpha = kThumbDefaultAlpha * animation_opacity_; - if (GetState() == CustomButton::STATE_HOVERED) { - alpha = kThumbHoverAlpha * animation_opacity_; - } else if(GetState() == CustomButton::STATE_PRESSED) { - // If we are in pressed state, no need to worry about animation, - // just display the deeper color. - alpha = kThumbHoverAlpha; - } - - paint.setStyle(SkPaint::kFill_Style); - paint.setColor(SkColorSetARGB(alpha, 0, 0, 0)); - canvas->DrawRoundRect(local_bounds, kThumbCornerRadius, paint); -} - -void OverlayScrollBarThumb::AnimationProgressed( - const gfx::Animation* animation) { - animation_opacity_ = animation->GetCurrentValue(); - SchedulePaint(); -} - -} // namespace - -OverlayScrollBar::OverlayScrollBar(bool horizontal) - : BaseScrollBar(horizontal, new OverlayScrollBarThumb(this)), - animation_(static_cast<OverlayScrollBarThumb*>(GetThumb())) { - set_notify_enter_exit_on_child(true); -} - -OverlayScrollBar::~OverlayScrollBar() { -} - -gfx::Rect OverlayScrollBar::GetTrackBounds() const { - gfx::Rect local_bounds(GetLocalBounds()); - if (IsHorizontal()) { - local_bounds.Inset(kThumbInsetFromEdge, kThumbInsetInside, - kThumbInsetFromEdge, kThumbInsetFromEdge); - } else { - local_bounds.Inset(kThumbInsetInside, kThumbInsetFromEdge, - kThumbInsetFromEdge, kThumbInsetFromEdge); - } - gfx::Size track_size = local_bounds.size(); - track_size.SetToMax(GetThumb()->size()); - local_bounds.set_size(track_size); - return local_bounds; -} - -int OverlayScrollBar::GetLayoutSize() const { - return 0; -} - -int OverlayScrollBar::GetContentOverlapSize() const { - return kScrollbarWidth; -} - -void OverlayScrollBar::OnMouseEnteredScrollView(const ui::MouseEvent& event) { - animation_.Show(); -} - -void OverlayScrollBar::OnMouseExitedScrollView(const ui::MouseEvent& event) { - animation_.Hide(); -} - -void OverlayScrollBar::OnGestureEvent(ui::GestureEvent* event) { - switch (event->type()) { - case ui::ET_GESTURE_SCROLL_BEGIN: - animation_.Show(); - break; - case ui::ET_GESTURE_SCROLL_END: - case ui::ET_SCROLL_FLING_START: - case ui::ET_GESTURE_END: - animation_.Hide(); - break; - default: - break; - } - BaseScrollBar::OnGestureEvent(event); -} - -gfx::Size OverlayScrollBar::GetPreferredSize() const { - return gfx::Size(); -} - -void OverlayScrollBar::Layout() { - gfx::Rect thumb_bounds = GetTrackBounds(); - BaseScrollBarThumb* thumb = GetThumb(); - if (IsHorizontal()) { - thumb_bounds.set_x(thumb->x()); - thumb_bounds.set_width(thumb->width()); - } else { - thumb_bounds.set_y(thumb->y()); - thumb_bounds.set_height(thumb->height()); - } - thumb->SetBoundsRect(thumb_bounds); -} - -void OverlayScrollBar::OnPaint(gfx::Canvas* canvas) { -} - -} // namespace views
diff --git a/ui/views/controls/scrollbar/overlay_scroll_bar.h b/ui/views/controls/scrollbar/overlay_scroll_bar.h deleted file mode 100644 index 20cb755..0000000 --- a/ui/views/controls/scrollbar/overlay_scroll_bar.h +++ /dev/null
@@ -1,42 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_SCROLLBAR_OVERLAY_SCROLL_BAR_H_ -#define UI_VIEWS_CONTROLS_SCROLLBAR_OVERLAY_SCROLL_BAR_H_ - -#include "ui/gfx/animation/slide_animation.h" -#include "ui/views/controls/scrollbar/base_scroll_bar.h" - -namespace views { - -// The transparent scrollbar which overlays its contents. -class VIEWS_EXPORT OverlayScrollBar : public BaseScrollBar { - public: - explicit OverlayScrollBar(bool horizontal); - virtual ~OverlayScrollBar(); - - protected: - // BaseScrollBar overrides: - virtual gfx::Rect GetTrackBounds() const override; - virtual void OnGestureEvent(ui::GestureEvent* event) override; - - // ScrollBar overrides: - virtual int GetLayoutSize() const override; - virtual int GetContentOverlapSize() const override; - virtual void OnMouseEnteredScrollView(const ui::MouseEvent& event) override; - virtual void OnMouseExitedScrollView(const ui::MouseEvent& event) override; - - // View overrides: - virtual gfx::Size GetPreferredSize() const override; - virtual void Layout() override; - virtual void OnPaint(gfx::Canvas* canvas) override; - - private: - gfx::SlideAnimation animation_; - DISALLOW_COPY_AND_ASSIGN(OverlayScrollBar); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_SCROLLBAR_OVERLAY_SCROLL_BAR_H_
diff --git a/ui/views/controls/scrollbar/scroll_bar.cc b/ui/views/controls/scrollbar/scroll_bar.cc deleted file mode 100644 index 014cf3b..0000000 --- a/ui/views/controls/scrollbar/scroll_bar.cc +++ /dev/null
@@ -1,50 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/scrollbar/scroll_bar.h" - -#include "ui/accessibility/ax_view_state.h" - -namespace views { - -ScrollBar::~ScrollBar() { -} - -void ScrollBar::GetAccessibleState(ui::AXViewState* state) { - state->role = ui::AX_ROLE_SCROLL_BAR; -} - -bool ScrollBar::IsHorizontal() const { - return is_horiz_; -} - -void ScrollBar::Update(int viewport_size, int content_size, int current_pos) { - max_pos_ = std::max(0, content_size - viewport_size); -} - -int ScrollBar::GetMaxPosition() const { - return max_pos_; -} - -int ScrollBar::GetMinPosition() const { - return 0; -} - -int ScrollBar::GetContentOverlapSize() const { - return 0; -} - -void ScrollBar::OnMouseEnteredScrollView(const ui::MouseEvent& event) { -} - -void ScrollBar::OnMouseExitedScrollView(const ui::MouseEvent& event) { -} - -ScrollBar::ScrollBar(bool is_horiz) - : is_horiz_(is_horiz), - controller_(NULL), - max_pos_(0) { -} - -} // namespace views
diff --git a/ui/views/controls/scrollbar/scroll_bar.h b/ui/views/controls/scrollbar/scroll_bar.h deleted file mode 100644 index 2a711d6..0000000 --- a/ui/views/controls/scrollbar/scroll_bar.h +++ /dev/null
@@ -1,114 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_SCROLLBAR_SCROLL_BAR_H_ -#define UI_VIEWS_CONTROLS_SCROLLBAR_SCROLL_BAR_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "ui/views/view.h" -#include "ui/views/views_export.h" - -namespace views { - -class ScrollBar; - -///////////////////////////////////////////////////////////////////////////// -// -// ScrollBarController -// -// ScrollBarController defines the method that should be implemented to -// receive notification from a scrollbar -// -///////////////////////////////////////////////////////////////////////////// -class VIEWS_EXPORT ScrollBarController { - public: - // Invoked by the scrollbar when the scrolling position changes - // This method typically implements the actual scrolling. - // - // The provided position is expressed in pixels. It is the new X or Y - // position which is in the GetMinPosition() / GetMaxPosition range. - virtual void ScrollToPosition(ScrollBar* source, int position) = 0; - - // Returns the amount to scroll. The amount to scroll may be requested in - // two different amounts. If is_page is true the 'page scroll' amount is - // requested. The page scroll amount typically corresponds to the - // visual size of the view. If is_page is false, the 'line scroll' amount - // is being requested. The line scroll amount typically corresponds to the - // size of one row/column. - // - // The return value should always be positive. A value <= 0 results in - // scrolling by a fixed amount. - virtual int GetScrollIncrement(ScrollBar* source, - bool is_page, - bool is_positive) = 0; -}; - -///////////////////////////////////////////////////////////////////////////// -// -// ScrollBar -// -// A View subclass to wrap to implement a ScrollBar. Our current windows -// version simply wraps a native windows scrollbar. -// -// A scrollbar is either horizontal or vertical -// -///////////////////////////////////////////////////////////////////////////// -class VIEWS_EXPORT ScrollBar : public View { - public: - virtual ~ScrollBar(); - - // Overridden from View: - virtual void GetAccessibleState(ui::AXViewState* state) override; - - // Returns whether this scrollbar is horizontal. - bool IsHorizontal() const; - - void set_controller(ScrollBarController* controller) { - controller_ = controller; - } - ScrollBarController* controller() const { return controller_; } - - // Update the scrollbar appearance given a viewport size, content size and - // current position - virtual void Update(int viewport_size, int content_size, int current_pos); - - // Returns the max and min positions. - int GetMaxPosition() const; - int GetMinPosition() const; - - // Returns the position of the scrollbar. - virtual int GetPosition() const = 0; - - // Get the width or height of this scrollbar, for use in layout calculations. - // For a vertical scrollbar, this is the width of the scrollbar, likewise it - // is the height for a horizontal scrollbar. - virtual int GetLayoutSize() const = 0; - - // Get the width or height for this scrollbar which overlaps with the content. - // Default is 0. - virtual int GetContentOverlapSize() const; - - virtual void OnMouseEnteredScrollView(const ui::MouseEvent& event); - virtual void OnMouseExitedScrollView(const ui::MouseEvent& event); - - protected: - // Create new scrollbar, either horizontal or vertical. These are protected - // since you need to be creating either a NativeScrollBar or a - // ImageScrollBar. - explicit ScrollBar(bool is_horiz); - - private: - const bool is_horiz_; - - ScrollBarController* controller_; - - int max_pos_; - - DISALLOW_COPY_AND_ASSIGN(ScrollBar); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_SCROLLBAR_SCROLL_BAR_H_
diff --git a/ui/views/controls/scrollbar/scrollbar_unittest.cc b/ui/views/controls/scrollbar/scrollbar_unittest.cc deleted file mode 100644 index 295ac2c..0000000 --- a/ui/views/controls/scrollbar/scrollbar_unittest.cc +++ /dev/null
@@ -1,170 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/scrollbar/native_scroll_bar.h" -#include "ui/views/controls/scrollbar/native_scroll_bar_views.h" -#include "ui/views/controls/scrollbar/scroll_bar.h" -#include "ui/views/test/views_test_base.h" -#include "ui/views/widget/widget.h" - -namespace { - -// The Scrollbar controller. This is the widget that should do the real -// scrolling of contents. -class TestScrollBarController : public views::ScrollBarController { - public: - virtual ~TestScrollBarController() {} - - virtual void ScrollToPosition(views::ScrollBar* source, - int position) override { - last_source = source; - last_position = position; - } - - virtual int GetScrollIncrement(views::ScrollBar* source, - bool is_page, - bool is_positive) override { - last_source = source; - last_is_page = is_page; - last_is_positive = is_positive; - - if (is_page) - return 20; - return 10; - } - - // We save the last values in order to assert the corectness of the scroll - // operation. - views::ScrollBar* last_source; - bool last_is_positive; - bool last_is_page; - int last_position; -}; - -} // namespace - -namespace views { - -class NativeScrollBarTest : public ViewsTestBase { - public: - NativeScrollBarTest() : widget_(NULL), scrollbar_(NULL) {} - - virtual void SetUp() { - ViewsTestBase::SetUp(); - controller_.reset(new TestScrollBarController()); - - ASSERT_FALSE(scrollbar_); - native_scrollbar_ = new NativeScrollBar(true); - native_scrollbar_->SetBounds(0, 0, 100, 100); - native_scrollbar_->set_controller(controller_.get()); - - widget_ = new Widget; - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.bounds = gfx::Rect(0, 0, 100, 100); - widget_->Init(params); - View* container = new View(); - widget_->SetContentsView(container); - container->AddChildView(native_scrollbar_); - - scrollbar_ = - static_cast<NativeScrollBarViews*>(native_scrollbar_->native_wrapper_); - scrollbar_->SetBounds(0, 0, 100, 100); - scrollbar_->Update(100, 200, 0); - - track_size_ = scrollbar_->GetTrackBounds().width(); - } - - virtual void TearDown() { - widget_->Close(); - ViewsTestBase::TearDown(); - } - - protected: - Widget* widget_; - - // This is the native scrollbar the Views one wraps around. - NativeScrollBar* native_scrollbar_; - - // This is the Views scrollbar. - BaseScrollBar* scrollbar_; - - // Keep track of the size of the track. This is how we can tell when we - // scroll to the middle. - int track_size_; - - scoped_ptr<TestScrollBarController> controller_; -}; - -// TODO(dnicoara) Can't run the test on Windows since the scrollbar |Part| -// isn't handled in NativeTheme. -#if defined(OS_WIN) -#define MAYBE_Scrolling DISABLED_Scrolling -#define MAYBE_ScrollBarFitsToBottom DISABLED_ScrollBarFitsToBottom -#else -#define MAYBE_Scrolling Scrolling -#define MAYBE_ScrollBarFitsToBottom ScrollBarFitsToBottom -#endif - -TEST_F(NativeScrollBarTest, MAYBE_Scrolling) { - EXPECT_EQ(scrollbar_->GetPosition(), 0); - EXPECT_EQ(scrollbar_->GetMaxPosition(), 100); - EXPECT_EQ(scrollbar_->GetMinPosition(), 0); - - // Scroll to middle. - scrollbar_->ScrollToThumbPosition(track_size_ / 4, false); - EXPECT_EQ(controller_->last_position, 50); - EXPECT_EQ(controller_->last_source, native_scrollbar_); - - // Scroll to the end. - scrollbar_->ScrollToThumbPosition(track_size_ / 2, false); - EXPECT_EQ(controller_->last_position, 100); - - // Overscroll. Last position should be the maximum position. - scrollbar_->ScrollToThumbPosition(track_size_, false); - EXPECT_EQ(controller_->last_position, 100); - - // Underscroll. Last position should be the minimum position. - scrollbar_->ScrollToThumbPosition(-10, false); - EXPECT_EQ(controller_->last_position, 0); - - // Test the different fixed scrolling amounts. Generally used by buttons, - // or click on track. - scrollbar_->ScrollToThumbPosition(0, false); - scrollbar_->ScrollByAmount(BaseScrollBar::SCROLL_NEXT_LINE); - EXPECT_EQ(controller_->last_position, 10); - - scrollbar_->ScrollByAmount(BaseScrollBar::SCROLL_PREV_LINE); - EXPECT_EQ(controller_->last_position, 0); - - scrollbar_->ScrollByAmount(BaseScrollBar::SCROLL_NEXT_PAGE); - EXPECT_EQ(controller_->last_position, 20); - - scrollbar_->ScrollByAmount(BaseScrollBar::SCROLL_PREV_PAGE); - EXPECT_EQ(controller_->last_position, 0); -} - -TEST_F(NativeScrollBarTest, MAYBE_ScrollBarFitsToBottom) { - scrollbar_->Update(100, 199, 0); - EXPECT_EQ(0, scrollbar_->GetPosition()); - EXPECT_EQ(99, scrollbar_->GetMaxPosition()); - EXPECT_EQ(0, scrollbar_->GetMinPosition()); - - scrollbar_->Update(100, 199, 99); - EXPECT_EQ( - scrollbar_->GetTrackBounds().width() - scrollbar_->GetThumbSizeForTest(), - scrollbar_->GetPosition()); -} - -TEST_F(NativeScrollBarTest, ScrollToEndAfterShrinkAndExpand) { - // Scroll to the end of the content. - scrollbar_->Update(100, 101, 0); - EXPECT_TRUE(scrollbar_->ScrollByContentsOffset(-1)); - // Shrink and then re-exapnd the content. - scrollbar_->Update(100, 100, 0); - scrollbar_->Update(100, 101, 0); - // Ensure the scrollbar allows scrolling to the end. - EXPECT_TRUE(scrollbar_->ScrollByContentsOffset(-1)); -} - -} // namespace views
diff --git a/ui/views/controls/separator.cc b/ui/views/controls/separator.cc deleted file mode 100644 index a8fe6da..0000000 --- a/ui/views/controls/separator.cc +++ /dev/null
@@ -1,49 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/separator.h" - -#include "ui/accessibility/ax_view_state.h" -#include "ui/gfx/canvas.h" - -namespace views { - -// static -const char Separator::kViewClassName[] = "Separator"; - -// The separator height in pixels. -const int kSeparatorHeight = 1; - -// Default color of the separator. -const SkColor kDefaultColor = SkColorSetARGB(255, 233, 233, 233); - -Separator::Separator(Orientation orientation) : orientation_(orientation) { - SetFocusable(false); -} - -Separator::~Separator() { -} - -//////////////////////////////////////////////////////////////////////////////// -// Separator, View overrides: - -gfx::Size Separator::GetPreferredSize() const { - if (orientation_ == HORIZONTAL) - return gfx::Size(width(), kSeparatorHeight); - return gfx::Size(kSeparatorHeight, height()); -} - -void Separator::GetAccessibleState(ui::AXViewState* state) { - state->role = ui::AX_ROLE_SPLITTER; -} - -void Separator::Paint(gfx::Canvas* canvas, const views::CullSet& cull_set) { - canvas->FillRect(bounds(), kDefaultColor); -} - -const char* Separator::GetClassName() const { - return kViewClassName; -} - -} // namespace views
diff --git a/ui/views/controls/separator.h b/ui/views/controls/separator.h deleted file mode 100644 index 7c964b7..0000000 --- a/ui/views/controls/separator.h +++ /dev/null
@@ -1,45 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_SEPARATOR_H_ -#define UI_VIEWS_CONTROLS_SEPARATOR_H_ - -#include <string> - -#include "ui/views/view.h" - -namespace views { - -// The Separator class is a view that shows a line used to visually separate -// other views. - -class VIEWS_EXPORT Separator : public View { - public: - enum Orientation { - HORIZONTAL, - VERTICAL - }; - - // The separator's class name. - static const char kViewClassName[]; - - explicit Separator(Orientation orientation); - virtual ~Separator(); - - // Overridden from View: - virtual gfx::Size GetPreferredSize() const override; - virtual void GetAccessibleState(ui::AXViewState* state) override; - virtual void Paint(gfx::Canvas* canvas, - const views::CullSet& cull_set) override; - virtual const char* GetClassName() const override; - - private: - const Orientation orientation_; - - DISALLOW_COPY_AND_ASSIGN(Separator); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_SEPARATOR_H_
diff --git a/ui/views/controls/single_split_view.cc b/ui/views/controls/single_split_view.cc deleted file mode 100644 index fe50141..0000000 --- a/ui/views/controls/single_split_view.cc +++ /dev/null
@@ -1,253 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/single_split_view.h" - -#include "skia/ext/skia_utils_win.h" -#include "ui/accessibility/ax_view_state.h" -#include "ui/base/cursor/cursor.h" -#include "ui/gfx/canvas.h" -#include "ui/views/background.h" -#include "ui/views/controls/single_split_view_listener.h" -#include "ui/views/native_cursor.h" - -namespace views { - -// static -const char SingleSplitView::kViewClassName[] = "SingleSplitView"; - -// Size of the divider in pixels. -static const int kDividerSize = 4; - -SingleSplitView::SingleSplitView(View* leading, - View* trailing, - Orientation orientation, - SingleSplitViewListener* listener) - : is_horizontal_(orientation == HORIZONTAL_SPLIT), - divider_offset_(-1), - resize_leading_on_bounds_change_(true), - resize_disabled_(false), - listener_(listener) { - AddChildView(leading); - AddChildView(trailing); -#if defined(OS_WIN) - set_background( - views::Background::CreateSolidBackground( - skia::COLORREFToSkColor(GetSysColor(COLOR_3DFACE)))); -#endif -} - -void SingleSplitView::Layout() { - gfx::Rect leading_bounds; - gfx::Rect trailing_bounds; - CalculateChildrenBounds(bounds(), &leading_bounds, &trailing_bounds); - - if (has_children()) { - if (child_at(0)->visible()) - child_at(0)->SetBoundsRect(leading_bounds); - if (child_count() > 1) { - if (child_at(1)->visible()) - child_at(1)->SetBoundsRect(trailing_bounds); - } - } - - // Invoke super's implementation so that the children are layed out. - View::Layout(); -} - -const char* SingleSplitView::GetClassName() const { - return kViewClassName; -} - -void SingleSplitView::GetAccessibleState(ui::AXViewState* state) { - state->role = ui::AX_ROLE_GROUP; - state->name = accessible_name_; -} - -gfx::Size SingleSplitView::GetPreferredSize() const { - int width = 0; - int height = 0; - for (int i = 0; i < 2 && i < child_count(); ++i) { - const View* view = child_at(i); - gfx::Size pref = view->GetPreferredSize(); - if (is_horizontal_) { - width += pref.width(); - height = std::max(height, pref.height()); - } else { - width = std::max(width, pref.width()); - height += pref.height(); - } - } - if (is_horizontal_) - width += GetDividerSize(); - else - height += GetDividerSize(); - return gfx::Size(width, height); -} - -gfx::NativeCursor SingleSplitView::GetCursor(const ui::MouseEvent& event) { - if (!IsPointInDivider(event.location())) - return gfx::kNullCursor; - return is_horizontal_ ? GetNativeEastWestResizeCursor() - : GetNativeNorthSouthResizeCursor(); -} - -int SingleSplitView::GetDividerSize() const { - bool both_visible = child_count() > 1 && child_at(0)->visible() && - child_at(1)->visible(); - return both_visible && !resize_disabled_ ? kDividerSize : 0; -} - -void SingleSplitView::CalculateChildrenBounds( - const gfx::Rect& bounds, - gfx::Rect* leading_bounds, - gfx::Rect* trailing_bounds) const { - bool is_leading_visible = has_children() && child_at(0)->visible(); - bool is_trailing_visible = child_count() > 1 && child_at(1)->visible(); - - if (!is_leading_visible && !is_trailing_visible) { - *leading_bounds = gfx::Rect(); - *trailing_bounds = gfx::Rect(); - return; - } - - int divider_at; - - if (!is_trailing_visible) { - divider_at = GetPrimaryAxisSize(bounds.width(), bounds.height()); - } else if (!is_leading_visible) { - divider_at = 0; - } else { - divider_at = - CalculateDividerOffset(divider_offset_, this->bounds(), bounds); - divider_at = NormalizeDividerOffset(divider_at, bounds); - } - - int divider_size = GetDividerSize(); - - if (is_horizontal_) { - *leading_bounds = gfx::Rect(0, 0, divider_at, bounds.height()); - *trailing_bounds = - gfx::Rect(divider_at + divider_size, 0, - std::max(0, bounds.width() - divider_at - divider_size), - bounds.height()); - } else { - *leading_bounds = gfx::Rect(0, 0, bounds.width(), divider_at); - *trailing_bounds = - gfx::Rect(0, divider_at + divider_size, bounds.width(), - std::max(0, bounds.height() - divider_at - divider_size)); - } -} - -void SingleSplitView::SetAccessibleName(const base::string16& name) { - accessible_name_ = name; -} - -bool SingleSplitView::OnMousePressed(const ui::MouseEvent& event) { - if (!IsPointInDivider(event.location())) - return false; - drag_info_.initial_mouse_offset = GetPrimaryAxisSize(event.x(), event.y()); - drag_info_.initial_divider_offset = - NormalizeDividerOffset(divider_offset_, bounds()); - return true; -} - -bool SingleSplitView::OnMouseDragged(const ui::MouseEvent& event) { - if (child_count() < 2) - return false; - - int delta_offset = GetPrimaryAxisSize(event.x(), event.y()) - - drag_info_.initial_mouse_offset; - if (is_horizontal_ && base::i18n::IsRTL()) - delta_offset *= -1; - // Honor the first child's minimum size when resizing. - gfx::Size min = child_at(0)->GetMinimumSize(); - int new_size = std::max(GetPrimaryAxisSize(min.width(), min.height()), - drag_info_.initial_divider_offset + delta_offset); - - // Honor the second child's minimum size, and don't let the view - // get bigger than our width. - min = child_at(1)->GetMinimumSize(); - new_size = std::min(GetPrimaryAxisSize() - kDividerSize - - GetPrimaryAxisSize(min.width(), min.height()), new_size); - - if (new_size != divider_offset_) { - set_divider_offset(new_size); - if (!listener_ || listener_->SplitHandleMoved(this)) - Layout(); - } - return true; -} - -void SingleSplitView::OnMouseCaptureLost() { - if (child_count() < 2) - return; - - if (drag_info_.initial_divider_offset != divider_offset_) { - set_divider_offset(drag_info_.initial_divider_offset); - if (!listener_ || listener_->SplitHandleMoved(this)) - Layout(); - } -} - -void SingleSplitView::OnBoundsChanged(const gfx::Rect& previous_bounds) { - divider_offset_ = CalculateDividerOffset(divider_offset_, previous_bounds, - bounds()); -} - -bool SingleSplitView::IsPointInDivider(const gfx::Point& p) { - if (resize_disabled_) - return false; - - if (child_count() < 2) - return false; - - if (!child_at(0)->visible() || !child_at(1)->visible()) - return false; - - int divider_relative_offset; - if (is_horizontal_) { - divider_relative_offset = - p.x() - child_at(base::i18n::IsRTL() ? 1 : 0)->width(); - } else { - divider_relative_offset = p.y() - child_at(0)->height(); - } - return (divider_relative_offset >= 0 && - divider_relative_offset < GetDividerSize()); -} - -int SingleSplitView::CalculateDividerOffset( - int divider_offset, - const gfx::Rect& previous_bounds, - const gfx::Rect& new_bounds) const { - if (resize_leading_on_bounds_change_ && divider_offset != -1) { - // We do not update divider_offset on minimize (to zero) and on restore - // (to largest value). As a result we get back to the original value upon - // window restore. - bool is_minimize_or_restore = - previous_bounds.height() == 0 || new_bounds.height() == 0; - if (!is_minimize_or_restore) { - if (is_horizontal_) - divider_offset += new_bounds.width() - previous_bounds.width(); - else - divider_offset += new_bounds.height() - previous_bounds.height(); - - if (divider_offset < 0) - divider_offset = GetDividerSize(); - } - } - return divider_offset; -} - -int SingleSplitView::NormalizeDividerOffset(int divider_offset, - const gfx::Rect& bounds) const { - int primary_axis_size = GetPrimaryAxisSize(bounds.width(), bounds.height()); - if (divider_offset < 0) - // primary_axis_size may < GetDividerSize during initial layout. - return std::max(0, (primary_axis_size - GetDividerSize()) / 2); - return std::min(divider_offset, - std::max(primary_axis_size - GetDividerSize(), 0)); -} - -} // namespace views
diff --git a/ui/views/controls/single_split_view.h b/ui/views/controls/single_split_view.h deleted file mode 100644 index 4581e40..0000000 --- a/ui/views/controls/single_split_view.h +++ /dev/null
@@ -1,147 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_SINGLE_SPLIT_VIEW_H_ -#define UI_VIEWS_CONTROLS_SINGLE_SPLIT_VIEW_H_ - -#include "base/gtest_prod_util.h" -#include "ui/views/view.h" - -namespace views { - -class SingleSplitViewListener; - -// SingleSplitView lays out two views next to each other, either horizontally -// or vertically. A splitter exists between the two views that the user can -// drag around to resize the views. -// SingleSplitViewListener's SplitHandleMoved notification helps to monitor user -// initiated layout changes. -class VIEWS_EXPORT SingleSplitView : public View { - public: - enum Orientation { - HORIZONTAL_SPLIT, - VERTICAL_SPLIT - }; - - static const char kViewClassName[]; - - SingleSplitView(View* leading, - View* trailing, - Orientation orientation, - SingleSplitViewListener* listener); - - virtual void Layout() override; - virtual const char* GetClassName() const override; - - virtual void GetAccessibleState(ui::AXViewState* state) override; - - // SingleSplitView's preferred size is the sum of the preferred widths - // and the max of the heights. - virtual gfx::Size GetPreferredSize() const override; - - // Overriden to return a resize cursor when over the divider. - virtual gfx::NativeCursor GetCursor(const ui::MouseEvent& event) override; - - Orientation orientation() const { - return is_horizontal_ ? HORIZONTAL_SPLIT : VERTICAL_SPLIT; - } - - void set_orientation(Orientation orientation) { - is_horizontal_ = orientation == HORIZONTAL_SPLIT; - } - - void set_divider_offset(int divider_offset) { - divider_offset_ = divider_offset; - } - int divider_offset() const { return divider_offset_; } - - int GetDividerSize() const; - - void set_resize_disabled(bool resize_disabled) { - resize_disabled_ = resize_disabled; - } - bool is_resize_disabled() const { return resize_disabled_; } - - // Sets whether the leading component is resized when the split views size - // changes. The default is true. A value of false results in the trailing - // component resizing on a bounds change. - void set_resize_leading_on_bounds_change(bool resize) { - resize_leading_on_bounds_change_ = resize; - } - - // Calculates ideal leading and trailing view bounds according to the given - // split view |bounds|, current divider offset and children visiblity. - // Does not change children view bounds. - void CalculateChildrenBounds(const gfx::Rect& bounds, - gfx::Rect* leading_bounds, - gfx::Rect* trailing_bounds) const; - - void SetAccessibleName(const base::string16& name); - - protected: - // View overrides. - virtual bool OnMousePressed(const ui::MouseEvent& event) override; - virtual bool OnMouseDragged(const ui::MouseEvent& event) override; - virtual void OnMouseCaptureLost() override; - virtual void OnBoundsChanged(const gfx::Rect& previous_bounds) override; - - private: - // This test calls OnMouse* functions. - FRIEND_TEST_ALL_PREFIXES(SingleSplitViewTest, MouseDrag); - - // Returns true if |x| or |y| is over the divider. - bool IsPointInDivider(const gfx::Point& p); - - // Calculates the new |divider_offset| based on the changes of split view - // bounds. - int CalculateDividerOffset(int divider_offset, - const gfx::Rect& previous_bounds, - const gfx::Rect& new_bounds) const; - - // Returns divider offset within primary axis size range for given split - // view |bounds|. - int NormalizeDividerOffset(int divider_offset, const gfx::Rect& bounds) const; - - // Returns width in case of horizontal split and height otherwise. - int GetPrimaryAxisSize() const { - return GetPrimaryAxisSize(width(), height()); - } - - int GetPrimaryAxisSize(int h, int v) const { - return is_horizontal_ ? h : v; - } - - // Used to track drag info. - struct DragInfo { - // The initial coordinate of the mouse when the user started the drag. - int initial_mouse_offset; - // The initial position of the divider when the user started the drag. - int initial_divider_offset; - }; - - DragInfo drag_info_; - - // Orientation of the split view. - bool is_horizontal_; - - // Position of the divider. - int divider_offset_; - - bool resize_leading_on_bounds_change_; - - // Whether resizing is disabled. - bool resize_disabled_; - - // Listener to notify about user initiated handle movements. Not owned. - SingleSplitViewListener* listener_; - - // The accessible name of this view. - base::string16 accessible_name_; - - DISALLOW_COPY_AND_ASSIGN(SingleSplitView); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_SINGLE_SPLIT_VIEW_H_
diff --git a/ui/views/controls/single_split_view_listener.h b/ui/views/controls/single_split_view_listener.h deleted file mode 100644 index 0d589c9..0000000 --- a/ui/views/controls/single_split_view_listener.h +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_SINGLE_SPLIT_VIEW_LISTENER_H_ -#define UI_VIEWS_CONTROLS_SINGLE_SPLIT_VIEW_LISTENER_H_ - -#include "ui/views/views_export.h" - -namespace views { - -class SingleSplitView; - -// An interface implemented by objects that want to be notified when the -// splitter moves. -class VIEWS_EXPORT SingleSplitViewListener { - public: - // Invoked when split handle is moved by the user. |sender|'s divider_offset - // is already set to the new value, but Layout has not happened yet. - // Returns false if the layout has been handled by the listener, returns - // true if |sender| should do it by itself. - virtual bool SplitHandleMoved(SingleSplitView* sender) = 0; - - protected: - virtual ~SingleSplitViewListener() {} -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_SINGLE_SPLIT_VIEW_LISTENER_H_
diff --git a/ui/views/controls/single_split_view_unittest.cc b/ui/views/controls/single_split_view_unittest.cc deleted file mode 100644 index de24285..0000000 --- a/ui/views/controls/single_split_view_unittest.cc +++ /dev/null
@@ -1,230 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/single_split_view.h" - -#include "base/logging.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/views/controls/single_split_view_listener.h" - -namespace { - -static void VerifySplitViewLayout(const views::SingleSplitView& split) { - ASSERT_EQ(2, split.child_count()); - - const views::View* leading = split.child_at(0); - const views::View* trailing = split.child_at(1); - - if (split.bounds().IsEmpty()) { - EXPECT_TRUE(leading->bounds().IsEmpty()); - EXPECT_TRUE(trailing->bounds().IsEmpty()); - return; - } - - EXPECT_FALSE(leading->bounds().IsEmpty()); - EXPECT_FALSE(trailing->bounds().IsEmpty()); - EXPECT_FALSE(leading->bounds().Intersects(trailing->bounds())); - - if (split.orientation() == views::SingleSplitView::HORIZONTAL_SPLIT) { - EXPECT_EQ(leading->bounds().height(), split.bounds().height()); - EXPECT_EQ(trailing->bounds().height(), split.bounds().height()); - EXPECT_LT(leading->bounds().width() + trailing->bounds().width(), - split.bounds().width()); - } else if (split.orientation() == views::SingleSplitView::VERTICAL_SPLIT) { - EXPECT_EQ(leading->bounds().width(), split.bounds().width()); - EXPECT_EQ(trailing->bounds().width(), split.bounds().width()); - EXPECT_LT(leading->bounds().height() + trailing->bounds().height(), - split.bounds().height()); - } else { - NOTREACHED(); - } -} - -class SingleSplitViewListenerImpl : public views::SingleSplitViewListener { - public: - SingleSplitViewListenerImpl() : count_(0) {} - - virtual bool SplitHandleMoved(views::SingleSplitView* sender) override { - ++count_; - return false; - } - - int count() const { return count_; } - - private: - int count_; - - DISALLOW_COPY_AND_ASSIGN(SingleSplitViewListenerImpl); -}; - -class MinimumSizedView: public views::View { - public: - MinimumSizedView(gfx::Size min_size) : min_size_(min_size) {} - - private: - gfx::Size min_size_; - virtual gfx::Size GetMinimumSize() const override; -}; - -gfx::Size MinimumSizedView::GetMinimumSize() const { - return min_size_; -} - -} // namespace - -namespace views { - -TEST(SingleSplitViewTest, Resize) { - // Test cases to iterate through for horizontal and vertical split views. - struct TestCase { - // Split view resize policy for this test case. - bool resize_leading_on_bounds_change; - // Split view size to set. - int primary_axis_size; - int secondary_axis_size; - // Expected divider offset. - int divider_offset; - } test_cases[] = { - // The initial split size is 100x100, divider at 33. - { true, 100, 100, 33 }, - // Grow the split view, leading view should grow. - { true, 1000, 100, 933 }, - // Shrink the split view, leading view should shrink. - { true, 200, 100, 133 }, - // Minimize the split view, divider should not move. - { true, 0, 0, 133 }, - // Restore the split view, divider should not move. - { false, 500, 100, 133 }, - // Resize the split view by secondary axis, divider should not move. - { false, 500, 600, 133 } - }; - - SingleSplitView::Orientation orientations[] = { - SingleSplitView::HORIZONTAL_SPLIT, - SingleSplitView::VERTICAL_SPLIT - }; - - for (size_t orientation = 0; orientation < arraysize(orientations); - ++orientation) { - // Create a split view. - SingleSplitView split( - new View(), new View(), orientations[orientation], NULL); - - // Set initial size and divider offset. - EXPECT_EQ(test_cases[0].primary_axis_size, - test_cases[0].secondary_axis_size); - split.SetBounds(0, 0, test_cases[0].primary_axis_size, - test_cases[0].secondary_axis_size); - split.set_divider_offset(test_cases[0].divider_offset); - split.Layout(); - - // Run all test cases. - for (size_t i = 0; i < arraysize(test_cases); ++i) { - split.set_resize_leading_on_bounds_change( - test_cases[i].resize_leading_on_bounds_change); - if (split.orientation() == SingleSplitView::HORIZONTAL_SPLIT) { - split.SetBounds(0, 0, test_cases[i].primary_axis_size, - test_cases[i].secondary_axis_size); - } else { - split.SetBounds(0, 0, test_cases[i].secondary_axis_size, - test_cases[i].primary_axis_size); - } - - EXPECT_EQ(test_cases[i].divider_offset, split.divider_offset()); - VerifySplitViewLayout(split); - } - - // Special cases, one of the child views is hidden. - split.child_at(0)->SetVisible(false); - split.Layout(); - - EXPECT_EQ(split.size(), split.child_at(1)->size()); - - split.child_at(0)->SetVisible(true); - split.child_at(1)->SetVisible(false); - split.Layout(); - - EXPECT_EQ(split.size(), split.child_at(0)->size()); - } -} - -TEST(SingleSplitViewTest, MouseDrag) { - const int kMinimumChildSize = 25; - MinimumSizedView *child0 = - new MinimumSizedView(gfx::Size(5, kMinimumChildSize)); - MinimumSizedView *child1 = - new MinimumSizedView(gfx::Size(5, kMinimumChildSize)); - SingleSplitViewListenerImpl listener; - SingleSplitView split( - child0, child1, SingleSplitView::VERTICAL_SPLIT, &listener); - - const int kTotalSplitSize = 100; - split.SetBounds(0, 0, 10, kTotalSplitSize); - const int kInitialDividerOffset = 33; - const int kMouseOffset = 2; // Mouse offset in the divider. - const int kMouseMoveDelta = 7; - split.set_divider_offset(kInitialDividerOffset); - split.Layout(); - - gfx::Point press_point(7, kInitialDividerOffset + kMouseOffset); - ui::MouseEvent mouse_pressed( - ui::ET_MOUSE_PRESSED, press_point, press_point, 0, 0); - ASSERT_TRUE(split.OnMousePressed(mouse_pressed)); - EXPECT_EQ(kInitialDividerOffset, split.divider_offset()); - EXPECT_EQ(0, listener.count()); - - // Drag divider to the bottom. - gfx::Point drag_1_point( - 5, kInitialDividerOffset + kMouseOffset + kMouseMoveDelta); - ui::MouseEvent mouse_dragged_1( - ui::ET_MOUSE_DRAGGED, drag_1_point, drag_1_point, 0, 0); - ASSERT_TRUE(split.OnMouseDragged(mouse_dragged_1)); - EXPECT_EQ(kInitialDividerOffset + kMouseMoveDelta, split.divider_offset()); - EXPECT_EQ(1, listener.count()); - - // Drag divider to the top, beyond first child minimum size. - gfx::Point drag_2_point( - 7, kMinimumChildSize - 5); - ui::MouseEvent mouse_dragged_2( - ui::ET_MOUSE_DRAGGED, drag_2_point, drag_2_point, 0,0 ); - ASSERT_TRUE(split.OnMouseDragged(mouse_dragged_2)); - EXPECT_EQ(kMinimumChildSize, split.divider_offset()); - EXPECT_EQ(2, listener.count()); - - // Drag divider to the bottom, beyond second child minimum size. - gfx::Point drag_3_point( - 7, kTotalSplitSize - kMinimumChildSize + 5); - ui::MouseEvent mouse_dragged_3( - ui::ET_MOUSE_DRAGGED, drag_3_point, drag_3_point, 0, 0); - ASSERT_TRUE(split.OnMouseDragged(mouse_dragged_3)); - EXPECT_EQ(kTotalSplitSize - kMinimumChildSize - split.GetDividerSize(), - split.divider_offset()); - EXPECT_EQ(3, listener.count()); - - // Drag divider between childs' minimum sizes. - gfx::Point drag_4_point( - 6, kInitialDividerOffset + kMouseOffset + kMouseMoveDelta * 2); - ui::MouseEvent mouse_dragged_4( - ui::ET_MOUSE_DRAGGED, drag_4_point, drag_4_point, 0, 0); - ASSERT_TRUE(split.OnMouseDragged(mouse_dragged_4)); - EXPECT_EQ(kInitialDividerOffset + kMouseMoveDelta * 2, - split.divider_offset()); - EXPECT_EQ(4, listener.count()); - - gfx::Point release_point( - 7, kInitialDividerOffset + kMouseOffset + kMouseMoveDelta * 2); - ui::MouseEvent mouse_released( - ui::ET_MOUSE_RELEASED, release_point, release_point, 0, 0); - split.OnMouseReleased(mouse_released); - EXPECT_EQ(kInitialDividerOffset + kMouseMoveDelta * 2, - split.divider_offset()); - - // Expect intial offset after a system/user gesture cancels the drag. - // This shouldn't occur after mouse release, but it's sufficient for testing. - split.OnMouseCaptureLost(); - EXPECT_EQ(kInitialDividerOffset, split.divider_offset()); - EXPECT_EQ(5, listener.count()); -} - -} // namespace views
diff --git a/ui/views/controls/slide_out_view.cc b/ui/views/controls/slide_out_view.cc deleted file mode 100644 index d3cafec..0000000 --- a/ui/views/controls/slide_out_view.cc +++ /dev/null
@@ -1,96 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/slide_out_view.h" - -#include "ui/compositor/layer.h" -#include "ui/compositor/scoped_layer_animation_settings.h" -#include "ui/gfx/transform.h" - -namespace views { - -SlideOutView::SlideOutView() - : gesture_scroll_amount_(0.f) { - // If accelerated compositing is not available, this widget tracks the - // OnSlideOut event but does not render any visible changes. - SetPaintToLayer(true); - SetFillsBoundsOpaquely(false); -} - -SlideOutView::~SlideOutView() { -} - -void SlideOutView::OnGestureEvent(ui::GestureEvent* event) { - if (event->type() == ui::ET_SCROLL_FLING_START) { - // The threshold for the fling velocity is computed empirically. - // The unit is in pixels/second. - const float kFlingThresholdForClose = 800.f; - if (fabsf(event->details().velocity_x()) > kFlingThresholdForClose) { - SlideOutAndClose(event->details().velocity_x() < 0 ? SLIDE_LEFT : - SLIDE_RIGHT); - event->StopPropagation(); - return; - } - RestoreVisualState(); - return; - } - - if (!event->IsScrollGestureEvent()) - return; - - if (event->type() == ui::ET_GESTURE_SCROLL_BEGIN) { - gesture_scroll_amount_ = 0.f; - } else if (event->type() == ui::ET_GESTURE_SCROLL_UPDATE) { - // The scroll-update events include the incremental scroll amount. - gesture_scroll_amount_ += event->details().scroll_x(); - - gfx::Transform transform; - transform.Translate(gesture_scroll_amount_, 0.0); - layer()->SetTransform(transform); - layer()->SetOpacity( - 1.f - std::min(fabsf(gesture_scroll_amount_) / width(), 1.f)); - - } else if (event->type() == ui::ET_GESTURE_SCROLL_END) { - const float kScrollRatioForClosingNotification = 0.5f; - float scrolled_ratio = fabsf(gesture_scroll_amount_) / width(); - if (scrolled_ratio >= kScrollRatioForClosingNotification) { - SlideOutAndClose(gesture_scroll_amount_ < 0 ? SLIDE_LEFT : SLIDE_RIGHT); - event->StopPropagation(); - return; - } - RestoreVisualState(); - } - - event->SetHandled(); -} - -void SlideOutView::RestoreVisualState() { - // Restore the layer state. - const int kSwipeRestoreDurationMS = 150; - ui::ScopedLayerAnimationSettings settings(layer()->GetAnimator()); - settings.SetTransitionDuration( - base::TimeDelta::FromMilliseconds(kSwipeRestoreDurationMS)); - layer()->SetTransform(gfx::Transform()); - layer()->SetOpacity(1.f); -} - -void SlideOutView::SlideOutAndClose(SlideDirection direction) { - const int kSwipeOutTotalDurationMS = 150; - int swipe_out_duration = kSwipeOutTotalDurationMS * layer()->opacity(); - ui::ScopedLayerAnimationSettings settings(layer()->GetAnimator()); - settings.SetTransitionDuration( - base::TimeDelta::FromMilliseconds(swipe_out_duration)); - settings.AddObserver(this); - - gfx::Transform transform; - transform.Translate(direction == SLIDE_LEFT ? -width() : width(), 0.0); - layer()->SetTransform(transform); - layer()->SetOpacity(0.f); -} - -void SlideOutView::OnImplicitAnimationsCompleted() { - OnSlideOut(); -} - -} // namespace views
diff --git a/ui/views/controls/slide_out_view.h b/ui/views/controls/slide_out_view.h deleted file mode 100644 index 46b4135..0000000 --- a/ui/views/controls/slide_out_view.h +++ /dev/null
@@ -1,50 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_SLIDE_OUT_VIEW_H_ -#define UI_VIEWS_CONTROLS_SLIDE_OUT_VIEW_H_ - -#include "ui/compositor/layer_animation_observer.h" -#include "ui/views/view.h" -#include "ui/views/views_export.h" - -namespace views { - -// A View that can be closed by a slide-out touch gesture. -class VIEWS_EXPORT SlideOutView : public views::View, - public ui::ImplicitAnimationObserver { - public: - SlideOutView(); - virtual ~SlideOutView(); - - protected: - // Called when user intends to close the View by sliding it out. - virtual void OnSlideOut() = 0; - - // Overridden from views::View. - virtual void OnGestureEvent(ui::GestureEvent* event) override; - - private: - enum SlideDirection { - SLIDE_LEFT, - SLIDE_RIGHT, - }; - - // Restores the transform and opacity of the view. - void RestoreVisualState(); - - // Slides the view out and closes it after the animation. - void SlideOutAndClose(SlideDirection direction); - - // Overridden from ImplicitAnimationObserver. - virtual void OnImplicitAnimationsCompleted() override; - - float gesture_scroll_amount_; - - DISALLOW_COPY_AND_ASSIGN(SlideOutView); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_SLIDE_OUT_VIEW_H_
diff --git a/ui/views/controls/slider.cc b/ui/views/controls/slider.cc deleted file mode 100644 index 71d719e..0000000 --- a/ui/views/controls/slider.cc +++ /dev/null
@@ -1,364 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/slider.h" - -#include <algorithm> - -#include "base/logging.h" -#include "base/message_loop/message_loop.h" -#include "base/strings/stringprintf.h" -#include "base/strings/utf_string_conversions.h" -#include "third_party/skia/include/core/SkCanvas.h" -#include "third_party/skia/include/core/SkColor.h" -#include "third_party/skia/include/core/SkPaint.h" -#include "ui/accessibility/ax_view_state.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/events/event.h" -#include "ui/gfx/animation/slide_animation.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/point.h" -#include "ui/gfx/rect.h" -#include "ui/resources/grit/ui_resources.h" -#include "ui/views/widget/widget.h" - -namespace { -const int kSlideValueChangeDurationMS = 150; - -const int kBarImagesActive[] = { - IDR_SLIDER_ACTIVE_LEFT, - IDR_SLIDER_ACTIVE_CENTER, - IDR_SLIDER_PRESSED_CENTER, - IDR_SLIDER_PRESSED_RIGHT, -}; - -const int kBarImagesDisabled[] = { - IDR_SLIDER_DISABLED_LEFT, - IDR_SLIDER_DISABLED_CENTER, - IDR_SLIDER_DISABLED_CENTER, - IDR_SLIDER_DISABLED_RIGHT, -}; - -// The image chunks. -enum BorderElements { - LEFT, - CENTER_LEFT, - CENTER_RIGHT, - RIGHT, -}; -} // namespace - -namespace views { - -Slider::Slider(SliderListener* listener, Orientation orientation) - : listener_(listener), - orientation_(orientation), - value_(0.f), - keyboard_increment_(0.1f), - animating_value_(0.f), - value_is_valid_(false), - accessibility_events_enabled_(true), - focus_border_color_(0), - bar_active_images_(kBarImagesActive), - bar_disabled_images_(kBarImagesDisabled) { - EnableCanvasFlippingForRTLUI(true); - SetFocusable(true); - UpdateState(true); -} - -Slider::~Slider() { -} - -void Slider::SetValue(float value) { - SetValueInternal(value, VALUE_CHANGED_BY_API); -} - -void Slider::SetKeyboardIncrement(float increment) { - keyboard_increment_ = increment; -} - -void Slider::SetValueInternal(float value, SliderChangeReason reason) { - bool old_value_valid = value_is_valid_; - - value_is_valid_ = true; - if (value < 0.0) - value = 0.0; - else if (value > 1.0) - value = 1.0; - if (value_ == value) - return; - float old_value = value_; - value_ = value; - if (listener_) - listener_->SliderValueChanged(this, value_, old_value, reason); - - if (old_value_valid && base::MessageLoop::current()) { - // Do not animate when setting the value of the slider for the first time. - // There is no message-loop when running tests. So we cannot animate then. - animating_value_ = old_value; - move_animation_.reset(new gfx::SlideAnimation(this)); - move_animation_->SetSlideDuration(kSlideValueChangeDurationMS); - move_animation_->Show(); - AnimationProgressed(move_animation_.get()); - } else { - SchedulePaint(); - } - if (accessibility_events_enabled_ && GetWidget()) { - NotifyAccessibilityEvent( - ui::AX_EVENT_VALUE_CHANGED, true); - } -} - -void Slider::PrepareForMove(const gfx::Point& point) { - // Try to remember the position of the mouse cursor on the button. - gfx::Insets inset = GetInsets(); - gfx::Rect content = GetContentsBounds(); - float value = move_animation_.get() && move_animation_->is_animating() ? - animating_value_ : value_; - - // For the horizontal orientation. - const int thumb_x = value * (content.width() - thumb_->width()); - const int candidate_x = (base::i18n::IsRTL() ? - width() - (point.x() - inset.left()) : - point.x() - inset.left()) - thumb_x; - if (candidate_x >= 0 && candidate_x < thumb_->width()) - initial_button_offset_.set_x(candidate_x); - else - initial_button_offset_.set_x(thumb_->width() / 2); - - // For the vertical orientation. - const int thumb_y = (1.0 - value) * (content.height() - thumb_->height()); - const int candidate_y = point.y() - thumb_y; - if (candidate_y >= 0 && candidate_y < thumb_->height()) - initial_button_offset_.set_y(candidate_y); - else - initial_button_offset_.set_y(thumb_->height() / 2); -} - -void Slider::MoveButtonTo(const gfx::Point& point) { - gfx::Insets inset = GetInsets(); - // Calculate the value. - if (orientation_ == HORIZONTAL) { - int amount = base::i18n::IsRTL() ? - width() - inset.left() - point.x() - initial_button_offset_.x() : - point.x() - inset.left() - initial_button_offset_.x(); - SetValueInternal(static_cast<float>(amount) / - (width() - inset.width() - thumb_->width()), - VALUE_CHANGED_BY_USER); - } else { - SetValueInternal( - 1.0f - static_cast<float>(point.y() - initial_button_offset_.y()) / - (height() - thumb_->height()), - VALUE_CHANGED_BY_USER); - } -} - -void Slider::UpdateState(bool control_on) { - ResourceBundle& rb = ResourceBundle::GetSharedInstance(); - if (control_on) { - thumb_ = rb.GetImageNamed(IDR_SLIDER_ACTIVE_THUMB).ToImageSkia(); - for (int i = 0; i < 4; ++i) - images_[i] = rb.GetImageNamed(bar_active_images_[i]).ToImageSkia(); - } else { - thumb_ = rb.GetImageNamed(IDR_SLIDER_DISABLED_THUMB).ToImageSkia(); - for (int i = 0; i < 4; ++i) - images_[i] = rb.GetImageNamed(bar_disabled_images_[i]).ToImageSkia(); - } - bar_height_ = images_[LEFT]->height(); - SchedulePaint(); -} - -void Slider::SetAccessibleName(const base::string16& name) { - accessible_name_ = name; -} - -void Slider::OnPaintFocus(gfx::Canvas* canvas) { - if (!HasFocus()) - return; - - if (!focus_border_color_) { - canvas->DrawFocusRect(GetLocalBounds()); - } else if (HasFocus()) { - canvas->DrawSolidFocusRect( - gfx::Rect(1, 1, width() - 3, height() - 3), - focus_border_color_); - } -} - -gfx::Size Slider::GetPreferredSize() const { - const int kSizeMajor = 200; - const int kSizeMinor = 40; - - if (orientation_ == HORIZONTAL) - return gfx::Size(std::max(width(), kSizeMajor), kSizeMinor); - return gfx::Size(kSizeMinor, std::max(height(), kSizeMajor)); -} - -void Slider::OnPaint(gfx::Canvas* canvas) { - gfx::Rect content = GetContentsBounds(); - float value = move_animation_.get() && move_animation_->is_animating() ? - animating_value_ : value_; - if (orientation_ == HORIZONTAL) { - // Paint slider bar with image resources. - - // Inset the slider bar a little bit, so that the left or the right end of - // the slider bar will not be exposed under the thumb button when the thumb - // button slides to the left most or right most position. - const int kBarInsetX = 2; - int bar_width = content.width() - kBarInsetX * 2; - int bar_cy = content.height() / 2 - bar_height_ / 2; - - int w = content.width() - thumb_->width(); - int full = value * w; - int middle = std::max(full, images_[LEFT]->width()); - - canvas->Save(); - canvas->Translate(gfx::Vector2d(kBarInsetX, bar_cy)); - canvas->DrawImageInt(*images_[LEFT], 0, 0); - canvas->DrawImageInt(*images_[RIGHT], - bar_width - images_[RIGHT]->width(), - 0); - canvas->TileImageInt(*images_[CENTER_LEFT], - images_[LEFT]->width(), - 0, - middle - images_[LEFT]->width(), - bar_height_); - canvas->TileImageInt(*images_[CENTER_RIGHT], - middle, - 0, - bar_width - middle - images_[RIGHT]->width(), - bar_height_); - canvas->Restore(); - - // Paint slider thumb. - int button_cx = content.x() + full; - int thumb_y = content.height() / 2 - thumb_->height() / 2; - canvas->DrawImageInt(*thumb_, button_cx, thumb_y); - } else { - // TODO(jennyz): draw vertical slider bar with resources. - // TODO(sad): The painting code should use NativeTheme for various - // platforms. - const int kButtonRadius = thumb_->width() / 2; - const int kLineThickness = bar_height_ / 2; - const SkColor kFullColor = SkColorSetARGB(125, 0, 0, 0); - const SkColor kEmptyColor = SkColorSetARGB(50, 0, 0, 0); - - int h = content.height() - thumb_->height(); - int full = value * h; - int empty = h - full; - int x = content.width() / 2 - kLineThickness / 2; - canvas->FillRect(gfx::Rect(x, content.y() + kButtonRadius, - kLineThickness, empty), - kEmptyColor); - canvas->FillRect(gfx::Rect(x, content.y() + empty + 2 * kButtonRadius, - kLineThickness, full), - kFullColor); - - // TODO(mtomasz): We draw a thumb here because so far it is the same - // for horizontal and vertical orientations. If it is different, then - // we will need a separate resource. - int button_cy = content.y() + h - full; - int thumb_x = content.width() / 2 - thumb_->width() / 2; - canvas->DrawImageInt(*thumb_, thumb_x, button_cy); - } - View::OnPaint(canvas); - OnPaintFocus(canvas); -} - -bool Slider::OnMousePressed(const ui::MouseEvent& event) { - if (!event.IsOnlyLeftMouseButton()) - return false; - OnSliderDragStarted(); - PrepareForMove(event.location()); - MoveButtonTo(event.location()); - return true; -} - -bool Slider::OnMouseDragged(const ui::MouseEvent& event) { - MoveButtonTo(event.location()); - return true; -} - -void Slider::OnMouseReleased(const ui::MouseEvent& event) { - OnSliderDragEnded(); -} - -bool Slider::OnKeyPressed(const ui::KeyEvent& event) { - if (orientation_ == HORIZONTAL) { - if (event.key_code() == ui::VKEY_LEFT) { - SetValueInternal(value_ - keyboard_increment_, VALUE_CHANGED_BY_USER); - return true; - } else if (event.key_code() == ui::VKEY_RIGHT) { - SetValueInternal(value_ + keyboard_increment_, VALUE_CHANGED_BY_USER); - return true; - } - } else { - if (event.key_code() == ui::VKEY_DOWN) { - SetValueInternal(value_ - keyboard_increment_, VALUE_CHANGED_BY_USER); - return true; - } else if (event.key_code() == ui::VKEY_UP) { - SetValueInternal(value_ + keyboard_increment_, VALUE_CHANGED_BY_USER); - return true; - } - } - return false; -} - -void Slider::OnFocus() { - View::OnFocus(); - SchedulePaint(); -} - -void Slider::OnBlur() { - View::OnBlur(); - SchedulePaint(); -} - -void Slider::OnGestureEvent(ui::GestureEvent* event) { - switch (event->type()) { - // In a multi point gesture only the touch point will generate - // an ET_GESTURE_TAP_DOWN event. - case ui::ET_GESTURE_TAP_DOWN: - OnSliderDragStarted(); - PrepareForMove(event->location()); - // Intentional fall through to next case. - case ui::ET_GESTURE_SCROLL_BEGIN: - case ui::ET_GESTURE_SCROLL_UPDATE: - MoveButtonTo(event->location()); - event->SetHandled(); - break; - case ui::ET_GESTURE_END: - MoveButtonTo(event->location()); - event->SetHandled(); - if (event->details().touch_points() <= 1) - OnSliderDragEnded(); - break; - default: - break; - } -} - -void Slider::AnimationProgressed(const gfx::Animation* animation) { - animating_value_ = animation->CurrentValueBetween(animating_value_, value_); - SchedulePaint(); -} - -void Slider::GetAccessibleState(ui::AXViewState* state) { - state->role = ui::AX_ROLE_SLIDER; - state->name = accessible_name_; - state->value = base::UTF8ToUTF16( - base::StringPrintf("%d%%", static_cast<int>(value_ * 100 + 0.5))); -} - -void Slider::OnSliderDragStarted() { - if (listener_) - listener_->SliderDragStarted(this); -} - -void Slider::OnSliderDragEnded() { - if (listener_) - listener_->SliderDragEnded(this); -} - -} // namespace views
diff --git a/ui/views/controls/slider.h b/ui/views/controls/slider.h deleted file mode 100644 index e6a521a..0000000 --- a/ui/views/controls/slider.h +++ /dev/null
@@ -1,145 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_SLIDER_H_ -#define UI_VIEWS_CONTROLS_SLIDER_H_ - -#include "ui/gfx/animation/animation_delegate.h" -#include "ui/views/view.h" -#include "ui/views/views_export.h" - -typedef unsigned int SkColor; - -namespace gfx { -class ImageSkia; -class SlideAnimation; -} - -namespace views { - -namespace test { -class SliderTestApi; -} - -class Slider; - -enum SliderChangeReason { - VALUE_CHANGED_BY_USER, // value was changed by the user (by clicking, e.g.) - VALUE_CHANGED_BY_API, // value was changed by a call to SetValue. -}; - -class VIEWS_EXPORT SliderListener { - public: - virtual void SliderValueChanged(Slider* sender, - float value, - float old_value, - SliderChangeReason reason) = 0; - - // Invoked when a drag starts or ends (more specifically, when the mouse - // button is pressed or released). - virtual void SliderDragStarted(Slider* sender) {} - virtual void SliderDragEnded(Slider* sender) {} - - protected: - virtual ~SliderListener() {} -}; - -class VIEWS_EXPORT Slider : public View, public gfx::AnimationDelegate { - public: - enum Orientation { - HORIZONTAL, - VERTICAL - }; - - Slider(SliderListener* listener, Orientation orientation); - virtual ~Slider(); - - float value() const { return value_; } - void SetValue(float value); - - // Set the delta used for changing the value via keyboard. - void SetKeyboardIncrement(float increment); - - void SetAccessibleName(const base::string16& name); - - void set_enable_accessibility_events(bool enabled) { - accessibility_events_enabled_ = enabled; - } - - void set_focus_border_color(SkColor color) { focus_border_color_ = color; } - - // Update UI based on control on/off state. - void UpdateState(bool control_on); - - private: - friend class test::SliderTestApi; - - void SetValueInternal(float value, SliderChangeReason reason); - - // Should be called on the Mouse Down event. Used to calculate relative - // position of the mouse cursor (or the touch point) on the button to - // accurately move the button using the MoveButtonTo() method. - void PrepareForMove(const gfx::Point& point); - - // Moves the button to the specified point and updates the value accordingly. - void MoveButtonTo(const gfx::Point& point); - - void OnPaintFocus(gfx::Canvas* canvas); - - // Notify the listener_, if not NULL, that dragging started. - void OnSliderDragStarted(); - - // Notify the listener_, if not NULL, that dragging ended. - void OnSliderDragEnded(); - - // views::View overrides: - virtual gfx::Size GetPreferredSize() const override; - virtual void OnPaint(gfx::Canvas* canvas) override; - virtual bool OnMousePressed(const ui::MouseEvent& event) override; - virtual bool OnMouseDragged(const ui::MouseEvent& event) override; - virtual void OnMouseReleased(const ui::MouseEvent& event) override; - virtual bool OnKeyPressed(const ui::KeyEvent& event) override; - virtual void GetAccessibleState(ui::AXViewState* state) override; - virtual void OnFocus() override; - virtual void OnBlur() override; - - // ui::EventHandler overrides: - virtual void OnGestureEvent(ui::GestureEvent* event) override; - - // gfx::AnimationDelegate overrides: - virtual void AnimationProgressed(const gfx::Animation* animation) override; - - void set_listener(SliderListener* listener) { - listener_ = listener; - } - - SliderListener* listener_; - Orientation orientation_; - - scoped_ptr<gfx::SlideAnimation> move_animation_; - - float value_; - float keyboard_increment_; - float animating_value_; - bool value_is_valid_; - base::string16 accessible_name_; - bool accessibility_events_enabled_; - SkColor focus_border_color_; - - // Relative position of the mouse cursor (or the touch point) on the slider's - // button. - gfx::Point initial_button_offset_; - - const int* bar_active_images_; - const int* bar_disabled_images_; - const gfx::ImageSkia* thumb_; - const gfx::ImageSkia* images_[4]; - int bar_height_; - - DISALLOW_COPY_AND_ASSIGN(Slider); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_SLIDER_H_
diff --git a/ui/views/controls/slider_unittest.cc b/ui/views/controls/slider_unittest.cc deleted file mode 100644 index 23be9e9..0000000 --- a/ui/views/controls/slider_unittest.cc +++ /dev/null
@@ -1,382 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/slider.h" - -#include <string> - -#include "base/memory/scoped_ptr.h" -#include "base/strings/string_util.h" -#include "base/strings/utf_string_conversions.h" -#include "base/time/time.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/events/event.h" -#include "ui/events/gesture_event_details.h" -#include "ui/events/test/event_generator.h" -#include "ui/views/test/slider_test_api.h" -#include "ui/views/test/views_test_base.h" -#include "ui/views/view.h" -#include "ui/views/widget/widget.h" -#include "ui/views/widget/widget_delegate.h" - -namespace { - -// A views::SliderListener that tracks simple event call history. -class TestSliderListener : public views::SliderListener { - public: - TestSliderListener(); - virtual ~TestSliderListener(); - - int last_event_epoch() { - return last_event_epoch_; - } - - int last_drag_started_epoch() { - return last_drag_started_epoch_; - } - - int last_drag_ended_epoch() { - return last_drag_ended_epoch_; - } - - views::Slider* last_drag_started_sender() { - return last_drag_started_sender_; - } - - views::Slider* last_drag_ended_sender() { - return last_drag_ended_sender_; - } - - // Resets the state of this as if it were newly created. - virtual void ResetCallHistory(); - - // views::SliderListener: - virtual void SliderValueChanged(views::Slider* sender, - float value, - float old_value, - views::SliderChangeReason reason) override; - virtual void SliderDragStarted(views::Slider* sender) override; - virtual void SliderDragEnded(views::Slider* sender) override; - - private: - // The epoch of the last event. - int last_event_epoch_; - // The epoch of the last time SliderDragStarted was called. - int last_drag_started_epoch_; - // The epoch of the last time SliderDragEnded was called. - int last_drag_ended_epoch_; - // The sender from the last SliderDragStarted call. - views::Slider* last_drag_started_sender_; - // The sender from the last SliderDragEnded call. - views::Slider* last_drag_ended_sender_; - - DISALLOW_COPY_AND_ASSIGN(TestSliderListener); -}; - -TestSliderListener::TestSliderListener() - : last_event_epoch_(0), - last_drag_started_epoch_(-1), - last_drag_ended_epoch_(-1), - last_drag_started_sender_(NULL), - last_drag_ended_sender_(NULL) { -} - -TestSliderListener::~TestSliderListener() { - last_drag_started_sender_ = NULL; - last_drag_ended_sender_ = NULL; -} - -void TestSliderListener::ResetCallHistory() { - last_event_epoch_ = 0; - last_drag_started_epoch_ = -1; - last_drag_ended_epoch_ = -1; - last_drag_started_sender_ = NULL; - last_drag_ended_sender_ = NULL; -} - -void TestSliderListener::SliderValueChanged(views::Slider* sender, - float value, - float old_value, - views::SliderChangeReason reason) { - ++last_event_epoch_; -} - -void TestSliderListener::SliderDragStarted(views::Slider* sender) { - last_drag_started_sender_ = sender; - last_drag_started_epoch_ = ++last_event_epoch_; -} - -void TestSliderListener::SliderDragEnded(views::Slider* sender) { - last_drag_ended_sender_ = sender; - last_drag_ended_epoch_ = ++last_event_epoch_; -} - -} // namespace - -namespace views { - -// Base test fixture for Slider tests. -class SliderTest : public views::ViewsTestBase { - public: - explicit SliderTest(Slider::Orientation orientation); - virtual ~SliderTest(); - - protected: - Slider* slider() { - return slider_; - } - - TestSliderListener& slider_listener() { - return slider_listener_; - } - - int max_x() { - return max_x_; - } - - int max_y() { - return max_y_; - } - - virtual void ClickAt(int x, int y); - - // testing::Test: - virtual void SetUp() override; - virtual void TearDown() override; - - ui::test::EventGenerator* event_generator() { - return event_generator_.get(); - } - - private: - // The Slider's orientation - Slider::Orientation orientation_; - // The Slider to be tested. - Slider* slider_; - // A simple SliderListener test double. - TestSliderListener slider_listener_; - // Stores the default locale at test setup so it can be restored - // during test teardown. - std::string default_locale_; - // The maximum x value within the bounds of the slider. - int max_x_; - // The maximum y value within the bounds of the slider. - int max_y_; - // The widget container for the slider being tested. - views::Widget* widget_; - // An event generator. - scoped_ptr<ui::test::EventGenerator> event_generator_; - - DISALLOW_COPY_AND_ASSIGN(SliderTest); -}; - -SliderTest::SliderTest(Slider::Orientation orientation) - : orientation_(orientation), - slider_(NULL), - default_locale_(""), - max_x_(0), - max_y_(0) { -} - -SliderTest::~SliderTest() { -} - -void SliderTest::SetUp() { - views::ViewsTestBase::SetUp(); - - slider_ = new Slider(NULL, orientation_); - View* view = slider_; - gfx::Size size = view->GetPreferredSize(); - view->SetSize(size); - max_x_ = size.width() - 1; - max_y_ = size.height() - 1; - default_locale_ = l10n_util::GetApplicationLocale(""); - - views::Widget::InitParams init_params(CreateParams( - views::Widget::InitParams::TYPE_WINDOW_FRAMELESS)); - init_params.bounds = gfx::Rect(size); - - widget_ = new views::Widget(); - widget_->Init(init_params); - widget_->SetContentsView(slider_); - widget_->Show(); - - event_generator_.reset(new ui::test::EventGenerator( - GetContext(), widget_->GetNativeWindow())); -} - -void SliderTest::TearDown() { - if (widget_ && !widget_->IsClosed()) - widget_->Close(); - - base::i18n::SetICUDefaultLocale(default_locale_); - - views::ViewsTestBase::TearDown(); -} - -void SliderTest::ClickAt(int x, int y) { - gfx::Point point(x, y); - event_generator_->MoveMouseTo(point); - event_generator_->ClickLeftButton(); -} - -// Test fixture for horizontally oriented slider tests. -class HorizontalSliderTest : public SliderTest { - public: - HorizontalSliderTest(); - virtual ~HorizontalSliderTest(); - - private: - DISALLOW_COPY_AND_ASSIGN(HorizontalSliderTest); -}; - -HorizontalSliderTest::HorizontalSliderTest() - : SliderTest(Slider::HORIZONTAL) { -} - -HorizontalSliderTest::~HorizontalSliderTest() { -} - -// Test fixture for vertically oriented slider tests. -class VerticalSliderTest : public SliderTest { - public: - VerticalSliderTest(); - virtual ~VerticalSliderTest(); - - private: - DISALLOW_COPY_AND_ASSIGN(VerticalSliderTest); -}; - -VerticalSliderTest::VerticalSliderTest() - : SliderTest(Slider::VERTICAL) { -} - -VerticalSliderTest::~VerticalSliderTest() { -} - -TEST_F(HorizontalSliderTest, UpdateFromClickHorizontal) { - ClickAt(0, 0); - EXPECT_EQ(0.0f, slider()->value()); - - ClickAt(max_x(), 0); - EXPECT_EQ(1.0f, slider()->value()); -} - -TEST_F(VerticalSliderTest, UpdateFromClickVertical) { - ClickAt(0, 0); - EXPECT_EQ(1.0f, slider()->value()); - - ClickAt(0, max_y()); - EXPECT_EQ(0.0f, slider()->value()); -} - -TEST_F(HorizontalSliderTest, UpdateFromClickRTLHorizontal) { - base::i18n::SetICUDefaultLocale("he"); - - ClickAt(0, 0); - EXPECT_EQ(1.0f, slider()->value()); - - ClickAt(max_x(), 0); - EXPECT_EQ(0.0f, slider()->value()); -} - -// Test the slider location after a tap gesture. -TEST_F(HorizontalSliderTest, SliderValueForTapGesture) { - // Tap below the minimum. - slider()->SetValue(0.5); - event_generator()->GestureTapAt(gfx::Point(0, 0)); - EXPECT_FLOAT_EQ(0, slider()->value()); - - // Tap above the maximum. - slider()->SetValue(0.5); - event_generator()->GestureTapAt(gfx::Point(max_x(), max_y())); - EXPECT_FLOAT_EQ(1, slider()->value()); - - // Tap somwhere in the middle. - slider()->SetValue(0.5); - event_generator()->GestureTapAt(gfx::Point(0.75 * max_x(), 0.75 * max_y())); - EXPECT_NEAR(0.75, slider()->value(), 0.03); -} - -// Test the slider location after a scroll gesture. -TEST_F(HorizontalSliderTest, SliderValueForScrollGesture) { - // Scroll below the minimum. - slider()->SetValue(0.5); - event_generator()->GestureScrollSequence( - gfx::Point(0.5 * max_x(), 0.5 * max_y()), - gfx::Point(0, 0), - base::TimeDelta::FromMilliseconds(10), - 5 /* steps */); - EXPECT_EQ(0, slider()->value()); - - // Scroll above the maximum. - slider()->SetValue(0.5); - event_generator()->GestureScrollSequence( - gfx::Point(0.5 * max_x(), 0.5 * max_y()), - gfx::Point(max_x(), max_y()), - base::TimeDelta::FromMilliseconds(10), - 5 /* steps */); - EXPECT_EQ(1, slider()->value()); - - // Scroll somewhere in the middle. - slider()->SetValue(0.25); - event_generator()->GestureScrollSequence( - gfx::Point(0.25 * max_x(), 0.25 * max_y()), - gfx::Point(0.75 * max_x(), 0.75 * max_y()), - base::TimeDelta::FromMilliseconds(10), - 5 /* steps */); - EXPECT_NEAR(0.75, slider()->value(), 0.03); -} - -// Verifies the correct SliderListener events are raised for a tap gesture. -TEST_F(HorizontalSliderTest, SliderListenerEventsForTapGesture) { - test::SliderTestApi slider_test_api(slider()); - slider_test_api.SetListener(&slider_listener()); - - event_generator()->GestureTapAt(gfx::Point(0, 0)); - EXPECT_EQ(1, slider_listener().last_drag_started_epoch()); - EXPECT_EQ(2, slider_listener().last_drag_ended_epoch()); - EXPECT_EQ(slider(), slider_listener().last_drag_started_sender()); - EXPECT_EQ(slider(), slider_listener().last_drag_ended_sender()); -} - -// Verifies the correct SliderListener events are raised for a scroll gesture. -TEST_F(HorizontalSliderTest, SliderListenerEventsForScrollGesture) { - test::SliderTestApi slider_test_api(slider()); - slider_test_api.SetListener(&slider_listener()); - - event_generator()->GestureScrollSequence( - gfx::Point(0.25 * max_x(), 0.25 * max_y()), - gfx::Point(0.75 * max_x(), 0.75 * max_y()), - base::TimeDelta::FromMilliseconds(0), - 5 /* steps */); - - EXPECT_EQ(1, slider_listener().last_drag_started_epoch()); - EXPECT_GT(slider_listener().last_drag_ended_epoch(), - slider_listener().last_drag_started_epoch()); - EXPECT_EQ(slider(), slider_listener().last_drag_started_sender()); - EXPECT_EQ(slider(), slider_listener().last_drag_ended_sender()); -} - -// Verifies the correct SliderListener events are raised for a multi -// finger scroll gesture. -TEST_F(HorizontalSliderTest, SliderListenerEventsForMultiFingerScrollGesture) { - test::SliderTestApi slider_test_api(slider()); - slider_test_api.SetListener(&slider_listener()); - - gfx::Point points[] = {gfx::Point(0, 0.1 * max_y()), - gfx::Point(0, 0.2 * max_y())}; - event_generator()->GestureMultiFingerScroll(2 /* count */, points, - 0 /* event_separation_time_ms */, 5 /* steps */, - 2 /* move_x */, 0 /* move_y */); - - EXPECT_EQ(1, slider_listener().last_drag_started_epoch()); - EXPECT_GT(slider_listener().last_drag_ended_epoch(), - slider_listener().last_drag_started_epoch()); - EXPECT_EQ(slider(), slider_listener().last_drag_started_sender()); - EXPECT_EQ(slider(), slider_listener().last_drag_ended_sender()); -} - -} // namespace views
diff --git a/ui/views/controls/styled_label.cc b/ui/views/controls/styled_label.cc deleted file mode 100644 index 700e62a..0000000 --- a/ui/views/controls/styled_label.cc +++ /dev/null
@@ -1,325 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/styled_label.h" - -#include <vector> - -#include "base/strings/string_util.h" -#include "ui/gfx/font_list.h" -#include "ui/gfx/text_elider.h" -#include "ui/native_theme/native_theme.h" -#include "ui/views/controls/label.h" -#include "ui/views/controls/link.h" -#include "ui/views/controls/styled_label_listener.h" - -namespace views { - - -// Helpers -------------------------------------------------------------------- - -namespace { - -// Calculates the height of a line of text. Currently returns the height of -// a label. -int CalculateLineHeight(const gfx::FontList& font_list) { - Label label; - label.SetFontList(font_list); - return label.GetPreferredSize().height(); -} - -scoped_ptr<Label> CreateLabelRange( - const base::string16& text, - const gfx::FontList& font_list, - const StyledLabel::RangeStyleInfo& style_info, - views::LinkListener* link_listener) { - scoped_ptr<Label> result; - - if (style_info.is_link) { - Link* link = new Link(text); - link->set_listener(link_listener); - link->SetUnderline((style_info.font_style & gfx::Font::UNDERLINE) != 0); - result.reset(link); - } else { - result.reset(new Label(text)); - } - - result->SetEnabledColor(style_info.color); - result->SetFontList(font_list); - - if (!style_info.tooltip.empty()) - result->SetTooltipText(style_info.tooltip); - if (style_info.font_style != gfx::Font::NORMAL) { - result->SetFontList( - result->font_list().DeriveWithStyle(style_info.font_style)); - } - - return result.Pass(); -} - -} // namespace - - -// StyledLabel::RangeStyleInfo ------------------------------------------------ - -StyledLabel::RangeStyleInfo::RangeStyleInfo() - : font_style(gfx::Font::NORMAL), - color(ui::NativeTheme::instance()->GetSystemColor( - ui::NativeTheme::kColorId_LabelEnabledColor)), - disable_line_wrapping(false), - is_link(false) {} - -StyledLabel::RangeStyleInfo::~RangeStyleInfo() {} - -// static -StyledLabel::RangeStyleInfo StyledLabel::RangeStyleInfo::CreateForLink() { - RangeStyleInfo result; - result.disable_line_wrapping = true; - result.is_link = true; - result.color = Link::GetDefaultEnabledColor(); - return result; -} - - -// StyledLabel::StyleRange ---------------------------------------------------- - -bool StyledLabel::StyleRange::operator<( - const StyledLabel::StyleRange& other) const { - return range.start() < other.range.start(); -} - - -// StyledLabel ---------------------------------------------------------------- - -StyledLabel::StyledLabel(const base::string16& text, - StyledLabelListener* listener) - : specified_line_height_(0), - listener_(listener), - displayed_on_background_color_set_(false), - auto_color_readability_enabled_(true) { - base::TrimWhitespace(text, base::TRIM_TRAILING, &text_); -} - -StyledLabel::~StyledLabel() {} - -void StyledLabel::SetText(const base::string16& text) { - text_ = text; - style_ranges_.clear(); - RemoveAllChildViews(true); - PreferredSizeChanged(); -} - -void StyledLabel::SetBaseFontList(const gfx::FontList& font_list) { - font_list_ = font_list; - PreferredSizeChanged(); -} - -void StyledLabel::AddStyleRange(const gfx::Range& range, - const RangeStyleInfo& style_info) { - DCHECK(!range.is_reversed()); - DCHECK(!range.is_empty()); - DCHECK(gfx::Range(0, text_.size()).Contains(range)); - - // Insert the new range in sorted order. - StyleRanges new_range; - new_range.push_front(StyleRange(range, style_info)); - style_ranges_.merge(new_range); - - PreferredSizeChanged(); -} - -void StyledLabel::SetDefaultStyle(const RangeStyleInfo& style_info) { - default_style_info_ = style_info; - PreferredSizeChanged(); -} - -void StyledLabel::SetLineHeight(int line_height) { - specified_line_height_ = line_height; - PreferredSizeChanged(); -} - -void StyledLabel::SetDisplayedOnBackgroundColor(SkColor color) { - displayed_on_background_color_ = color; - displayed_on_background_color_set_ = true; -} - -gfx::Insets StyledLabel::GetInsets() const { - gfx::Insets insets = View::GetInsets(); - - // We need a focus border iff we contain a link that will have a focus border. - // That in turn will be true only if the link is non-empty. - for (StyleRanges::const_iterator i(style_ranges_.begin()); - i != style_ranges_.end(); ++i) { - if (i->style_info.is_link && !i->range.is_empty()) { - const gfx::Insets focus_border_padding( - Label::kFocusBorderPadding, Label::kFocusBorderPadding, - Label::kFocusBorderPadding, Label::kFocusBorderPadding); - insets += focus_border_padding; - break; - } - } - - return insets; -} - -int StyledLabel::GetHeightForWidth(int w) const { - if (w != calculated_size_.width()) { - // TODO(erg): Munge the const-ness of the style label. CalculateAndDoLayout - // doesn't actually make any changes to member variables when |dry_run| is - // set to true. In general, the mutating and non-mutating parts shouldn't - // be in the same codepath. - calculated_size_ = - const_cast<StyledLabel*>(this)->CalculateAndDoLayout(w, true); - } - return calculated_size_.height(); -} - -void StyledLabel::Layout() { - calculated_size_ = CalculateAndDoLayout(GetLocalBounds().width(), false); -} - -void StyledLabel::PreferredSizeChanged() { - calculated_size_ = gfx::Size(); - View::PreferredSizeChanged(); -} - -void StyledLabel::LinkClicked(Link* source, int event_flags) { - if (listener_) - listener_->StyledLabelLinkClicked(link_targets_[source], event_flags); -} - -gfx::Size StyledLabel::CalculateAndDoLayout(int width, bool dry_run) { - if (!dry_run) { - RemoveAllChildViews(true); - link_targets_.clear(); - } - - width -= GetInsets().width(); - if (width <= 0 || text_.empty()) - return gfx::Size(); - - const int line_height = specified_line_height_ > 0 ? specified_line_height_ - : CalculateLineHeight(font_list_); - // The index of the line we're on. - int line = 0; - // The x position (in pixels) of the line we're on, relative to content - // bounds. - int x = 0; - - base::string16 remaining_string = text_; - StyleRanges::const_iterator current_range = style_ranges_.begin(); - - // Iterate over the text, creating a bunch of labels and links and laying them - // out in the appropriate positions. - while (!remaining_string.empty()) { - // Don't put whitespace at beginning of a line with an exception for the - // first line (so the text's leading whitespace is respected). - if (x == 0 && line > 0) { - base::TrimWhitespace(remaining_string, base::TRIM_LEADING, - &remaining_string); - } - - gfx::Range range(gfx::Range::InvalidRange()); - if (current_range != style_ranges_.end()) - range = current_range->range; - - const size_t position = text_.size() - remaining_string.size(); - - const gfx::Rect chunk_bounds(x, 0, width - x, 2 * line_height); - std::vector<base::string16> substrings; - gfx::FontList text_font_list = font_list_; - // If the start of the remaining text is inside a styled range, the font - // style may differ from the base font. The font specified by the range - // should be used when eliding text. - if (position >= range.start()) { - text_font_list = text_font_list.DeriveWithStyle( - current_range->style_info.font_style); - } - gfx::ElideRectangleText(remaining_string, - text_font_list, - chunk_bounds.width(), - chunk_bounds.height(), - gfx::IGNORE_LONG_WORDS, - &substrings); - - DCHECK(!substrings.empty()); - base::string16 chunk = substrings[0]; - if (chunk.empty()) { - // Nothing fits on this line. Start a new line. - // If x is 0, first line may have leading whitespace that doesn't fit in a - // single line, so try trimming those. Otherwise there is no room for - // anything; abort. - if (x == 0) { - if (line == 0) { - base::TrimWhitespace(remaining_string, base::TRIM_LEADING, - &remaining_string); - continue; - } - break; - } - - x = 0; - line++; - continue; - } - - scoped_ptr<Label> label; - if (position >= range.start()) { - const RangeStyleInfo& style_info = current_range->style_info; - - if (style_info.disable_line_wrapping && chunk.size() < range.length() && - position == range.start() && x != 0) { - // If the chunk should not be wrapped, try to fit it entirely on the - // next line. - x = 0; - line++; - continue; - } - - chunk = chunk.substr(0, std::min(chunk.size(), range.end() - position)); - - label = CreateLabelRange(chunk, font_list_, style_info, this); - - if (style_info.is_link && !dry_run) - link_targets_[label.get()] = range; - - if (position + chunk.size() >= range.end()) - ++current_range; - } else { - // This chunk is normal text. - if (position + chunk.size() > range.start()) - chunk = chunk.substr(0, range.start() - position); - label = CreateLabelRange(chunk, font_list_, default_style_info_, this); - } - - if (displayed_on_background_color_set_) - label->SetBackgroundColor(displayed_on_background_color_); - label->SetAutoColorReadabilityEnabled(auto_color_readability_enabled_); - - // Calculate the size of the optional focus border, and overlap by that - // amount. Otherwise, "<a>link</a>," will render as "link ,". - gfx::Insets focus_border_insets(label->GetInsets()); - focus_border_insets += -label->View::GetInsets(); - const gfx::Size view_size = label->GetPreferredSize(); - if (!dry_run) { - label->SetBoundsRect(gfx::Rect( - gfx::Point(GetInsets().left() + x - focus_border_insets.left(), - GetInsets().top() + line * line_height - - focus_border_insets.top()), - view_size)); - AddChildView(label.release()); - } - x += view_size.width() - focus_border_insets.width(); - - remaining_string = remaining_string.substr(chunk.size()); - } - - // The user-specified line height only applies to interline spacing, so the - // final line's height is unaffected. - int total_height = line * line_height + - CalculateLineHeight(font_list_) + GetInsets().height(); - return gfx::Size(width, total_height); -} - -} // namespace views
diff --git a/ui/views/controls/styled_label.h b/ui/views/controls/styled_label.h deleted file mode 100644 index 8382b8e..0000000 --- a/ui/views/controls/styled_label.h +++ /dev/null
@@ -1,164 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_STYLED_LABEL_H_ -#define UI_VIEWS_CONTROLS_STYLED_LABEL_H_ - -#include <list> -#include <map> - -#include "base/basictypes.h" -#include "base/strings/string16.h" -#include "third_party/skia/include/core/SkColor.h" -#include "ui/gfx/font_list.h" -#include "ui/gfx/range/range.h" -#include "ui/gfx/size.h" -#include "ui/views/controls/link_listener.h" -#include "ui/views/view.h" - -namespace views { - -class Link; -class StyledLabelListener; - -// A class which can apply mixed styles to a block of text. Currently, text is -// always multiline. Trailing whitespace in the styled label text is not -// supported and will be trimmed on StyledLabel construction. Leading -// whitespace is respected, provided not only whitespace fits in the first line. -// In this case, leading whitespace is ignored. -class VIEWS_EXPORT StyledLabel : public View, public LinkListener { - public: - // Parameters that define label style for a styled label's text range. - struct VIEWS_EXPORT RangeStyleInfo { - RangeStyleInfo(); - ~RangeStyleInfo(); - - // Creates a range style info with default values for link. - static RangeStyleInfo CreateForLink(); - - // The font style that will be applied to the range. Should be a bitmask of - // values defined in gfx::Font::FontStyle (BOLD, ITALIC, UNDERLINE). - int font_style; - - // The text color for the range. - SkColor color; - - // Tooltip for the range. - base::string16 tooltip; - - // If set, the whole range will be put on a single line. - bool disable_line_wrapping; - - // If set, the range will be created as a link. - bool is_link; - }; - - // Note that any trailing whitespace in |text| will be trimmed. - StyledLabel(const base::string16& text, StyledLabelListener* listener); - virtual ~StyledLabel(); - - // Sets the text to be displayed, and clears any previous styling. - void SetText(const base::string16& text); - - // Sets the fonts used by all labels. Can be augemented by styling set by - // AddStyleRange and SetDefaultStyle. - void SetBaseFontList(const gfx::FontList& font_list); - - // Marks the given range within |text_| with style defined by |style_info|. - // |range| must be contained in |text_|. - void AddStyleRange(const gfx::Range& range, const RangeStyleInfo& style_info); - - // Sets the default style to use for any part of the text that isn't within - // a range set by AddStyleRange. - void SetDefaultStyle(const RangeStyleInfo& style_info); - - // Get or set the distance in pixels between baselines of multi-line text. - // Default is 0, indicating the distance between lines should be the standard - // one for the label's text, font list, and platform. - void SetLineHeight(int height); - - // Sets the color of the background on which the label is drawn. This won't - // be explicitly drawn, but the label will force the text color to be - // readable over it. - void SetDisplayedOnBackgroundColor(SkColor color); - SkColor displayed_on_background_color() const { - return displayed_on_background_color_; - } - - void set_auto_color_readability_enabled(bool auto_color_readability) { - auto_color_readability_enabled_ = auto_color_readability; - } - - // View implementation: - virtual gfx::Insets GetInsets() const override; - virtual int GetHeightForWidth(int w) const override; - virtual void Layout() override; - virtual void PreferredSizeChanged() override; - - // LinkListener implementation: - virtual void LinkClicked(Link* source, int event_flags) override; - - private: - struct StyleRange { - StyleRange(const gfx::Range& range, - const RangeStyleInfo& style_info) - : range(range), - style_info(style_info) { - } - ~StyleRange() {} - - bool operator<(const StyleRange& other) const; - - gfx::Range range; - RangeStyleInfo style_info; - }; - typedef std::list<StyleRange> StyleRanges; - - // Calculates how to layout child views, creates them and sets their size - // and position. |width| is the horizontal space, in pixels, that the view - // has to work with. If |dry_run| is true, the view hierarchy is not touched. - // The return value is the necessary size. - gfx::Size CalculateAndDoLayout(int width, bool dry_run); - - // The text to display. - base::string16 text_; - - // Fonts used to display text. Can be augmented by RangeStyleInfo. - gfx::FontList font_list_; - - // Line height. - int specified_line_height_; - - // The default style to use for any part of the text that isn't within - // a range in |style_ranges_|. - RangeStyleInfo default_style_info_; - - // The listener that will be informed of link clicks. - StyledLabelListener* listener_; - - // The ranges that should be linkified, sorted by start position. - StyleRanges style_ranges_; - - // A mapping from a view to the range it corresponds to in |text_|. Only views - // that correspond to ranges with is_link style set will be added to the map. - std::map<View*, gfx::Range> link_targets_; - - // This variable saves the result of the last GetHeightForWidth call in order - // to avoid repeated calculation. - mutable gfx::Size calculated_size_; - - // Background color on which the label is drawn, for auto color readability. - SkColor displayed_on_background_color_; - bool displayed_on_background_color_set_; - - // Controls whether the text is automatically re-colored to be readable on the - // background. - bool auto_color_readability_enabled_; - - DISALLOW_COPY_AND_ASSIGN(StyledLabel); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_STYLED_LABEL_H_
diff --git a/ui/views/controls/styled_label_listener.h b/ui/views/controls/styled_label_listener.h deleted file mode 100644 index 13c08fd..0000000 --- a/ui/views/controls/styled_label_listener.h +++ /dev/null
@@ -1,28 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_STYLED_LABEL_LISTENER_H_ -#define UI_VIEWS_CONTROLS_STYLED_LABEL_LISTENER_H_ - -#include "ui/views/views_export.h" - -namespace gfx { -class Range; -} - -namespace views { - -// A listener interface for StyledLabel. -class VIEWS_EXPORT StyledLabelListener { - public: - virtual void StyledLabelLinkClicked(const gfx::Range& range, - int event_flags) = 0; - - protected: - virtual ~StyledLabelListener() {} -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_STYLED_LABEL_LISTENER_H_
diff --git a/ui/views/controls/styled_label_unittest.cc b/ui/views/controls/styled_label_unittest.cc deleted file mode 100644 index 144e03f..0000000 --- a/ui/views/controls/styled_label_unittest.cc +++ /dev/null
@@ -1,425 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <string> - -#include "base/basictypes.h" -#include "base/memory/scoped_ptr.h" -#include "base/strings/utf_string_conversions.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "third_party/skia/include/core/SkColor.h" -#include "ui/gfx/font_list.h" -#include "ui/views/border.h" -#include "ui/views/controls/link.h" -#include "ui/views/controls/styled_label.h" -#include "ui/views/controls/styled_label_listener.h" -#include "ui/views/test/views_test_base.h" -#include "ui/views/widget/widget.h" - -using base::ASCIIToUTF16; - -namespace views { - -class StyledLabelTest : public ViewsTestBase, public StyledLabelListener { - public: - StyledLabelTest() {} - virtual ~StyledLabelTest() {} - - // StyledLabelListener implementation. - virtual void StyledLabelLinkClicked(const gfx::Range& range, - int event_flags) override {} - - protected: - StyledLabel* styled() { return styled_.get(); } - - void InitStyledLabel(const std::string& ascii_text) { - styled_.reset(new StyledLabel(ASCIIToUTF16(ascii_text), this)); - styled_->set_owned_by_client(); - } - - int StyledLabelContentHeightForWidth(int w) { - return styled_->GetHeightForWidth(w) - styled_->GetInsets().height(); - } - - private: - scoped_ptr<StyledLabel> styled_; - - DISALLOW_COPY_AND_ASSIGN(StyledLabelTest); -}; - -TEST_F(StyledLabelTest, NoWrapping) { - const std::string text("This is a test block of text"); - InitStyledLabel(text); - Label label(ASCIIToUTF16(text)); - const gfx::Size label_preferred_size = label.GetPreferredSize(); - EXPECT_EQ(label_preferred_size.height(), - StyledLabelContentHeightForWidth(label_preferred_size.width() * 2)); -} - -TEST_F(StyledLabelTest, TrailingWhitespaceiIgnored) { - const std::string text("This is a test block of text "); - InitStyledLabel(text); - - styled()->SetBounds(0, 0, 1000, 1000); - styled()->Layout(); - - ASSERT_EQ(1, styled()->child_count()); - ASSERT_EQ(std::string(Label::kViewClassName), - styled()->child_at(0)->GetClassName()); - EXPECT_EQ(ASCIIToUTF16("This is a test block of text"), - static_cast<Label*>(styled()->child_at(0))->text()); -} - -TEST_F(StyledLabelTest, RespectLeadingWhitespace) { - const std::string text(" This is a test block of text"); - InitStyledLabel(text); - - styled()->SetBounds(0, 0, 1000, 1000); - styled()->Layout(); - - ASSERT_EQ(1, styled()->child_count()); - ASSERT_EQ(std::string(Label::kViewClassName), - styled()->child_at(0)->GetClassName()); - EXPECT_EQ(ASCIIToUTF16(" This is a test block of text"), - static_cast<Label*>(styled()->child_at(0))->text()); -} - -TEST_F(StyledLabelTest, FirstLineNotEmptyWhenLeadingWhitespaceTooLong) { - const std::string text(" a"); - InitStyledLabel(text); - - Label label(ASCIIToUTF16(text)); - gfx::Size label_preferred_size = label.GetPreferredSize(); - - styled()->SetBounds(0, 0, label_preferred_size.width() / 2, 1000); - styled()->Layout(); - - ASSERT_EQ(1, styled()->child_count()); - ASSERT_EQ(std::string(Label::kViewClassName), - styled()->child_at(0)->GetClassName()); - EXPECT_EQ(ASCIIToUTF16("a"), - static_cast<Label*>(styled()->child_at(0))->text()); -} - -TEST_F(StyledLabelTest, BasicWrapping) { - const std::string text("This is a test block of text"); - InitStyledLabel(text); - Label label(ASCIIToUTF16(text.substr(0, text.size() * 2 / 3))); - gfx::Size label_preferred_size = label.GetPreferredSize(); - EXPECT_EQ(label_preferred_size.height() * 2, - StyledLabelContentHeightForWidth(label_preferred_size.width())); - - // Also respect the border. - styled()->SetBorder(Border::CreateEmptyBorder(3, 3, 3, 3)); - styled()->SetBounds( - 0, - 0, - styled()->GetInsets().width() + label_preferred_size.width(), - styled()->GetInsets().height() + 2 * label_preferred_size.height()); - styled()->Layout(); - ASSERT_EQ(2, styled()->child_count()); - EXPECT_EQ(3, styled()->child_at(0)->x()); - EXPECT_EQ(3, styled()->child_at(0)->y()); - EXPECT_EQ(styled()->height() - 3, styled()->child_at(1)->bounds().bottom()); -} - -TEST_F(StyledLabelTest, CreateLinks) { - const std::string text("This is a test block of text."); - InitStyledLabel(text); - - // Without links, there should be no focus border. - EXPECT_TRUE(styled()->GetInsets().empty()); - - // Now let's add some links. - styled()->AddStyleRange(gfx::Range(0, 1), - StyledLabel::RangeStyleInfo::CreateForLink()); - styled()->AddStyleRange(gfx::Range(1, 2), - StyledLabel::RangeStyleInfo::CreateForLink()); - styled()->AddStyleRange(gfx::Range(10, 11), - StyledLabel::RangeStyleInfo::CreateForLink()); - styled()->AddStyleRange(gfx::Range(12, 13), - StyledLabel::RangeStyleInfo::CreateForLink()); - - // Now there should be a focus border because there are non-empty Links. - EXPECT_FALSE(styled()->GetInsets().empty()); - - // Verify layout creates the right number of children. - styled()->SetBounds(0, 0, 1000, 1000); - styled()->Layout(); - EXPECT_EQ(7, styled()->child_count()); -} - -TEST_F(StyledLabelTest, DontBreakLinks) { - const std::string text("This is a test block of text, "); - const std::string link_text("and this should be a link"); - InitStyledLabel(text + link_text); - styled()->AddStyleRange( - gfx::Range(text.size(), text.size() + link_text.size()), - StyledLabel::RangeStyleInfo::CreateForLink()); - - Label label(ASCIIToUTF16(text + link_text.substr(0, link_text.size() / 2))); - gfx::Size label_preferred_size = label.GetPreferredSize(); - int pref_height = styled()->GetHeightForWidth(label_preferred_size.width()); - EXPECT_EQ(label_preferred_size.height() * 2, - pref_height - styled()->GetInsets().height()); - - styled()->SetBounds(0, 0, label_preferred_size.width(), pref_height); - styled()->Layout(); - ASSERT_EQ(2, styled()->child_count()); - // The label has no focus border while the link (and thus overall styled - // label) does, so the label should be inset by the width of the focus border. - EXPECT_EQ(Label::kFocusBorderPadding, styled()->child_at(0)->x()); - EXPECT_EQ(0, styled()->child_at(1)->x()); -} - -TEST_F(StyledLabelTest, StyledRangeWithDisabledLineWrapping) { - const std::string text("This is a test block of text, "); - const std::string unbreakable_text("and this should not be broken"); - InitStyledLabel(text + unbreakable_text); - StyledLabel::RangeStyleInfo style_info; - style_info.disable_line_wrapping = true; - styled()->AddStyleRange( - gfx::Range(text.size(), text.size() + unbreakable_text.size()), - style_info); - - Label label(ASCIIToUTF16( - text + unbreakable_text.substr(0, unbreakable_text.size() / 2))); - gfx::Size label_preferred_size = label.GetPreferredSize(); - int pref_height = styled()->GetHeightForWidth(label_preferred_size.width()); - EXPECT_EQ(label_preferred_size.height() * 2, - pref_height - styled()->GetInsets().height()); - - styled()->SetBounds(0, 0, label_preferred_size.width(), pref_height); - styled()->Layout(); - ASSERT_EQ(2, styled()->child_count()); - EXPECT_EQ(0, styled()->child_at(0)->x()); - EXPECT_EQ(0, styled()->child_at(1)->x()); -} - -TEST_F(StyledLabelTest, StyledRangeUnderlined) { - const std::string text("This is a test block of text, "); - const std::string underlined_text("and this should be undelined"); - InitStyledLabel(text + underlined_text); - StyledLabel::RangeStyleInfo style_info; - style_info.font_style = gfx::Font::UNDERLINE; - styled()->AddStyleRange( - gfx::Range(text.size(), text.size() + underlined_text.size()), - style_info); - - styled()->SetBounds(0, 0, 1000, 1000); - styled()->Layout(); - - ASSERT_EQ(2, styled()->child_count()); - ASSERT_EQ(std::string(Label::kViewClassName), - styled()->child_at(1)->GetClassName()); - EXPECT_EQ( - gfx::Font::UNDERLINE, - static_cast<Label*>(styled()->child_at(1))->font_list().GetFontStyle()); -} - -TEST_F(StyledLabelTest, StyledRangeBold) { - const std::string bold_text( - "This is a block of text whose style will be set to BOLD in the test"); - const std::string text(" normal text"); - InitStyledLabel(bold_text + text); - - StyledLabel::RangeStyleInfo style_info; - style_info.font_style = gfx::Font::BOLD; - styled()->AddStyleRange(gfx::Range(0, bold_text.size()), style_info); - - // Calculate the bold text width if it were a pure label view, both with bold - // and normal style. - Label label(ASCIIToUTF16(bold_text)); - const gfx::Size normal_label_size = label.GetPreferredSize(); - label.SetFontList(label.font_list().DeriveWithStyle(gfx::Font::BOLD)); - const gfx::Size bold_label_size = label.GetPreferredSize(); - - ASSERT_GE(bold_label_size.width(), normal_label_size.width()); - - // Set the width so |bold_text| doesn't fit on a single line with bold style, - // but does with normal font style. - int styled_width = (normal_label_size.width() + bold_label_size.width()) / 2; - int pref_height = styled()->GetHeightForWidth(styled_width); - - // Sanity check that |bold_text| with normal font style would fit on a single - // line in a styled label with width |styled_width|. - StyledLabel unstyled(ASCIIToUTF16(bold_text), this); - unstyled.SetBounds(0, 0, styled_width, pref_height); - unstyled.Layout(); - EXPECT_EQ(1, unstyled.child_count()); - - styled()->SetBounds(0, 0, styled_width, pref_height); - styled()->Layout(); - - ASSERT_EQ(3, styled()->child_count()); - - // The bold text should be broken up into two parts. - ASSERT_EQ(std::string(Label::kViewClassName), - styled()->child_at(0)->GetClassName()); - EXPECT_EQ( - gfx::Font::BOLD, - static_cast<Label*>(styled()->child_at(0))->font_list().GetFontStyle()); - ASSERT_EQ(std::string(Label::kViewClassName), - styled()->child_at(1)->GetClassName()); - EXPECT_EQ( - gfx::Font::BOLD, - static_cast<Label*>(styled()->child_at(1))->font_list().GetFontStyle()); - ASSERT_EQ(std::string(Label::kViewClassName), - styled()->child_at(2)->GetClassName()); - EXPECT_EQ( - gfx::Font::NORMAL, - static_cast<Label*>(styled()->child_at(2))->font_list().GetFontStyle()); - - // The second bold part should start on a new line. - EXPECT_EQ(0, styled()->child_at(0)->x()); - EXPECT_EQ(0, styled()->child_at(1)->x()); - EXPECT_EQ(styled()->child_at(1)->bounds().right(), - styled()->child_at(2)->x()); -} - -TEST_F(StyledLabelTest, Color) { - const std::string text_red("RED"); - const std::string text_link("link"); - const std::string text("word"); - InitStyledLabel(text_red + text_link + text); - - StyledLabel::RangeStyleInfo style_info_red; - style_info_red.color = SK_ColorRED; - styled()->AddStyleRange(gfx::Range(0, text_red.size()), style_info_red); - - StyledLabel::RangeStyleInfo style_info_link = - StyledLabel::RangeStyleInfo::CreateForLink(); - styled()->AddStyleRange(gfx::Range(text_red.size(), - text_red.size() + text_link.size()), - style_info_link); - - styled()->SetBounds(0, 0, 1000, 1000); - styled()->Layout(); - - Widget* widget = new Widget(); - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - widget->Init(params); - View* container = new View(); - widget->SetContentsView(container); - container->AddChildView(styled()); - - // Obtain the default text color for a label. - Label* label = new Label(ASCIIToUTF16(text)); - container->AddChildView(label); - const SkColor kDefaultTextColor = label->enabled_color(); - - // Obtain the default text color for a link; - Link* link = new Link(ASCIIToUTF16(text_link)); - container->AddChildView(link); - const SkColor kDefaultLinkColor = link->enabled_color(); - - EXPECT_EQ(SK_ColorRED, - static_cast<Label*>(styled()->child_at(0))->enabled_color()); - EXPECT_EQ(kDefaultLinkColor, - static_cast<Label*>(styled()->child_at(1))->enabled_color()); - EXPECT_EQ(kDefaultTextColor, - static_cast<Label*>(styled()->child_at(2))->enabled_color()); - - // Test adjusted color readability. - styled()->SetDisplayedOnBackgroundColor(SK_ColorBLACK); - styled()->Layout(); - label->SetBackgroundColor(SK_ColorBLACK); - - const SkColor kAdjustedTextColor = label->enabled_color(); - EXPECT_NE(kAdjustedTextColor, kDefaultTextColor); - EXPECT_EQ(kAdjustedTextColor, - static_cast<Label*>(styled()->child_at(2))->enabled_color()); - - widget->CloseNow(); -} - -TEST_F(StyledLabelTest, StyledRangeWithTooltip) { - const std::string text("This is a test block of text, "); - const std::string tooltip_text("this should have a tooltip,"); - const std::string normal_text(" this should not have a tooltip, "); - const std::string link_text("and this should be a link"); - - const size_t tooltip_start = text.size(); - const size_t link_start = - text.size() + tooltip_text.size() + normal_text.size(); - - InitStyledLabel(text + tooltip_text + normal_text + link_text); - StyledLabel::RangeStyleInfo tooltip_style; - tooltip_style.tooltip = ASCIIToUTF16("tooltip"); - styled()->AddStyleRange( - gfx::Range(tooltip_start, tooltip_start + tooltip_text.size()), - tooltip_style); - styled()->AddStyleRange(gfx::Range(link_start, link_start + link_text.size()), - StyledLabel::RangeStyleInfo::CreateForLink()); - - // Break line inside the range with the tooltip. - Label label(ASCIIToUTF16( - text + tooltip_text.substr(0, tooltip_text.size() - 3))); - gfx::Size label_preferred_size = label.GetPreferredSize(); - int pref_height = styled()->GetHeightForWidth(label_preferred_size.width()); - EXPECT_EQ(label_preferred_size.height() * 3, - pref_height - styled()->GetInsets().height()); - - styled()->SetBounds(0, 0, label_preferred_size.width(), pref_height); - styled()->Layout(); - - EXPECT_EQ(label_preferred_size.width(), styled()->width()); - - ASSERT_EQ(5, styled()->child_count()); - // The labels have no focus border while the link (and thus overall styled - // label) does, so the labels should be inset by the width of the focus - // border. - EXPECT_EQ(Label::kFocusBorderPadding, styled()->child_at(0)->x()); - EXPECT_EQ(styled()->child_at(0)->bounds().right(), - styled()->child_at(1)->x()); - EXPECT_EQ(Label::kFocusBorderPadding, styled()->child_at(2)->x()); - EXPECT_EQ(styled()->child_at(2)->bounds().right(), - styled()->child_at(3)->x()); - EXPECT_EQ(0, styled()->child_at(4)->x()); - - base::string16 tooltip; - EXPECT_TRUE( - styled()->child_at(1)->GetTooltipText(gfx::Point(1, 1), &tooltip)); - EXPECT_EQ(ASCIIToUTF16("tooltip"), tooltip); - EXPECT_TRUE( - styled()->child_at(2)->GetTooltipText(gfx::Point(1, 1), &tooltip)); - EXPECT_EQ(ASCIIToUTF16("tooltip"), tooltip); -} - -TEST_F(StyledLabelTest, SetBaseFontList) { - const std::string text("This is a test block of text."); - InitStyledLabel(text); - std::string font_name("arial"); - gfx::Font font(font_name, 30); - styled()->SetBaseFontList(gfx::FontList(font)); - Label label(ASCIIToUTF16(text), gfx::FontList(font)); - - styled()->SetBounds(0, - 0, - label.GetPreferredSize().width(), - label.GetPreferredSize().height()); - - // Make sure we have the same sizing as a label. - EXPECT_EQ(label.GetPreferredSize().height(), styled()->height()); - EXPECT_EQ(label.GetPreferredSize().width(), styled()->width()); -} - -TEST_F(StyledLabelTest, LineHeight) { - const std::string text("one"); - InitStyledLabel(text); - int default_height = styled()->GetHeightForWidth(100); - const std::string newline_text("one\ntwo\nthree"); - InitStyledLabel(newline_text); - styled()->SetLineHeight(18); - EXPECT_EQ(18 * 2 + default_height, styled()->GetHeightForWidth(100)); -} - -TEST_F(StyledLabelTest, HandleEmptyLayout) { - const std::string text("This is a test block of text."); - InitStyledLabel(text); - styled()->Layout(); - EXPECT_EQ(0, styled()->child_count()); -} - -} // namespace views
diff --git a/ui/views/controls/tabbed_pane/tabbed_pane.cc b/ui/views/controls/tabbed_pane/tabbed_pane.cc deleted file mode 100644 index aa4b307..0000000 --- a/ui/views/controls/tabbed_pane/tabbed_pane.cc +++ /dev/null
@@ -1,375 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/tabbed_pane/tabbed_pane.h" - -#include "base/logging.h" -#include "ui/accessibility/ax_view_state.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/events/keycodes/keyboard_codes.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/font_list.h" -#include "ui/views/controls/label.h" -#include "ui/views/controls/tabbed_pane/tabbed_pane_listener.h" -#include "ui/views/layout/layout_manager.h" -#include "ui/views/widget/widget.h" - -namespace { - -// TODO(markusheintz|msw): Use NativeTheme colors. -const SkColor kTabTitleColor_Inactive = SkColorSetRGB(0x64, 0x64, 0x64); -const SkColor kTabTitleColor_Active = SK_ColorBLACK; -const SkColor kTabTitleColor_Hovered = SK_ColorBLACK; -const SkColor kTabBorderColor = SkColorSetRGB(0xC8, 0xC8, 0xC8); -const SkScalar kTabBorderThickness = 1.0f; - -} // namespace - -namespace views { - -// static -const char TabbedPane::kViewClassName[] = "TabbedPane"; - -// The tab view shown in the tab strip. -class Tab : public View { - public: - Tab(TabbedPane* tabbed_pane, const base::string16& title, View* contents); - virtual ~Tab(); - - View* contents() const { return contents_; } - - bool selected() const { return contents_->visible(); } - void SetSelected(bool selected); - - // Overridden from View: - virtual bool OnMousePressed(const ui::MouseEvent& event) override; - virtual void OnMouseEntered(const ui::MouseEvent& event) override; - virtual void OnMouseExited(const ui::MouseEvent& event) override; - virtual void OnGestureEvent(ui::GestureEvent* event) override; - virtual gfx::Size GetPreferredSize() const override; - virtual void Layout() override; - - private: - enum TabState { - TAB_INACTIVE, - TAB_ACTIVE, - TAB_HOVERED, - }; - - void SetState(TabState tab_state); - - TabbedPane* tabbed_pane_; - Label* title_; - gfx::Size preferred_title_size_; - TabState tab_state_; - // The content view associated with this tab. - View* contents_; - - DISALLOW_COPY_AND_ASSIGN(Tab); -}; - -// The tab strip shown above the tab contents. -class TabStrip : public View { - public: - explicit TabStrip(TabbedPane* tabbed_pane); - virtual ~TabStrip(); - - // Overridden from View: - virtual gfx::Size GetPreferredSize() const override; - virtual void Layout() override; - virtual void OnPaint(gfx::Canvas* canvas) override; - - private: - TabbedPane* tabbed_pane_; - - DISALLOW_COPY_AND_ASSIGN(TabStrip); -}; - -Tab::Tab(TabbedPane* tabbed_pane, const base::string16& title, View* contents) - : tabbed_pane_(tabbed_pane), - title_(new Label(title, - ui::ResourceBundle::GetSharedInstance().GetFontList( - ui::ResourceBundle::BoldFont))), - tab_state_(TAB_ACTIVE), - contents_(contents) { - // Calculate this now while the font list is guaranteed to be bold. - preferred_title_size_ = title_->GetPreferredSize(); - - SetState(TAB_INACTIVE); - AddChildView(title_); -} - -Tab::~Tab() {} - -void Tab::SetSelected(bool selected) { - contents_->SetVisible(selected); - SetState(selected ? TAB_ACTIVE : TAB_INACTIVE); -} - -bool Tab::OnMousePressed(const ui::MouseEvent& event) { - if (event.IsOnlyLeftMouseButton() && - GetLocalBounds().Contains(event.location())) - tabbed_pane_->SelectTab(this); - return true; -} - -void Tab::OnMouseEntered(const ui::MouseEvent& event) { - SetState(selected() ? TAB_ACTIVE : TAB_HOVERED); -} - -void Tab::OnMouseExited(const ui::MouseEvent& event) { - SetState(selected() ? TAB_ACTIVE : TAB_INACTIVE); -} - -void Tab::OnGestureEvent(ui::GestureEvent* event) { - switch (event->type()) { - case ui::ET_GESTURE_TAP_DOWN: - // Fallthrough. - case ui::ET_GESTURE_TAP: - // SelectTab also sets the right tab color. - tabbed_pane_->SelectTab(this); - break; - case ui::ET_GESTURE_TAP_CANCEL: - SetState(selected() ? TAB_ACTIVE : TAB_INACTIVE); - break; - default: - break; - } - event->SetHandled(); -} - -gfx::Size Tab::GetPreferredSize() const { - gfx::Size size(preferred_title_size_); - size.Enlarge(21, 9); - const int kTabMinWidth = 54; - if (size.width() < kTabMinWidth) - size.set_width(kTabMinWidth); - return size; -} - -void Tab::Layout() { - gfx::Rect bounds = GetLocalBounds(); - bounds.Inset(0, 1, 0, 0); - bounds.ClampToCenteredSize(preferred_title_size_); - title_->SetBoundsRect(bounds); -} - -void Tab::SetState(TabState tab_state) { - if (tab_state == tab_state_) - return; - tab_state_ = tab_state; - - ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); - switch (tab_state) { - case TAB_INACTIVE: - title_->SetEnabledColor(kTabTitleColor_Inactive); - title_->SetFontList(rb.GetFontList(ui::ResourceBundle::BaseFont)); - break; - case TAB_ACTIVE: - title_->SetEnabledColor(kTabTitleColor_Active); - title_->SetFontList(rb.GetFontList(ui::ResourceBundle::BoldFont)); - break; - case TAB_HOVERED: - title_->SetEnabledColor(kTabTitleColor_Hovered); - title_->SetFontList(rb.GetFontList(ui::ResourceBundle::BaseFont)); - break; - } - SchedulePaint(); -} - -TabStrip::TabStrip(TabbedPane* tabbed_pane) : tabbed_pane_(tabbed_pane) {} - -TabStrip::~TabStrip() {} - -gfx::Size TabStrip::GetPreferredSize() const { - gfx::Size size; - for (int i = 0; i < child_count(); ++i) { - const gfx::Size child_size = child_at(i)->GetPreferredSize(); - size.SetSize(size.width() + child_size.width(), - std::max(size.height(), child_size.height())); - } - return size; -} - -void TabStrip::Layout() { - const int kTabOffset = 9; - int x = kTabOffset; // Layout tabs with an offset to the tabstrip border. - for (int i = 0; i < child_count(); ++i) { - gfx::Size ps = child_at(i)->GetPreferredSize(); - child_at(i)->SetBounds(x, 0, ps.width(), ps.height()); - x = child_at(i)->bounds().right(); - } -} - -void TabStrip::OnPaint(gfx::Canvas* canvas) { - OnPaintBackground(canvas); - - // Draw the TabStrip border. - SkPaint paint; - paint.setColor(kTabBorderColor); - paint.setStrokeWidth(kTabBorderThickness); - SkScalar line_y = SkIntToScalar(height()) - (kTabBorderThickness / 2); - SkScalar line_end = SkIntToScalar(width()); - int selected_tab_index = tabbed_pane_->selected_tab_index(); - if (selected_tab_index >= 0) { - Tab* selected_tab = tabbed_pane_->GetTabAt(selected_tab_index); - SkPath path; - SkScalar tab_height = - SkIntToScalar(selected_tab->height()) - kTabBorderThickness; - SkScalar tab_width = - SkIntToScalar(selected_tab->width()) - kTabBorderThickness; - SkScalar tab_start = SkIntToScalar(selected_tab->GetMirroredX()); - path.moveTo(0, line_y); - path.rLineTo(tab_start, 0); - path.rLineTo(0, -tab_height); - path.rLineTo(tab_width, 0); - path.rLineTo(0, tab_height); - path.lineTo(line_end, line_y); - - SkPaint paint; - paint.setStyle(SkPaint::kStroke_Style); - paint.setColor(kTabBorderColor); - paint.setStrokeWidth(kTabBorderThickness); - canvas->DrawPath(path, paint); - } else { - canvas->sk_canvas()->drawLine(0, line_y, line_end, line_y, paint); - } -} - -TabbedPane::TabbedPane() - : listener_(NULL), - tab_strip_(new TabStrip(this)), - contents_(new View()), - selected_tab_index_(-1) { - SetFocusable(true); - AddChildView(tab_strip_); - AddChildView(contents_); -} - -TabbedPane::~TabbedPane() {} - -int TabbedPane::GetTabCount() { - DCHECK_EQ(tab_strip_->child_count(), contents_->child_count()); - return contents_->child_count(); -} - -View* TabbedPane::GetSelectedTab() { - return selected_tab_index() < 0 ? - NULL : GetTabAt(selected_tab_index())->contents(); -} - -void TabbedPane::AddTab(const base::string16& title, View* contents) { - AddTabAtIndex(tab_strip_->child_count(), title, contents); -} - -void TabbedPane::AddTabAtIndex(int index, - const base::string16& title, - View* contents) { - DCHECK(index >= 0 && index <= GetTabCount()); - contents->SetVisible(false); - - tab_strip_->AddChildViewAt(new Tab(this, title, contents), index); - contents_->AddChildViewAt(contents, index); - if (selected_tab_index() < 0) - SelectTabAt(index); - - PreferredSizeChanged(); -} - -void TabbedPane::SelectTabAt(int index) { - DCHECK(index >= 0 && index < GetTabCount()); - if (index == selected_tab_index()) - return; - - if (selected_tab_index() >= 0) - GetTabAt(selected_tab_index())->SetSelected(false); - - selected_tab_index_ = index; - Tab* tab = GetTabAt(index); - tab->SetSelected(true); - tab_strip_->SchedulePaint(); - - FocusManager* focus_manager = tab->contents()->GetFocusManager(); - if (focus_manager) { - const View* focused_view = focus_manager->GetFocusedView(); - if (focused_view && contents_->Contains(focused_view) && - !tab->contents()->Contains(focused_view)) - focus_manager->SetFocusedView(tab->contents()); - } - - if (listener()) - listener()->TabSelectedAt(index); -} - -void TabbedPane::SelectTab(Tab* tab) { - const int index = tab_strip_->GetIndexOf(tab); - if (index >= 0) - SelectTabAt(index); -} - -gfx::Size TabbedPane::GetPreferredSize() const { - gfx::Size size; - for (int i = 0; i < contents_->child_count(); ++i) - size.SetToMax(contents_->child_at(i)->GetPreferredSize()); - size.Enlarge(0, tab_strip_->GetPreferredSize().height()); - return size; -} - -Tab* TabbedPane::GetTabAt(int index) { - return static_cast<Tab*>(tab_strip_->child_at(index)); -} - -void TabbedPane::Layout() { - const gfx::Size size = tab_strip_->GetPreferredSize(); - tab_strip_->SetBounds(0, 0, width(), size.height()); - contents_->SetBounds(0, tab_strip_->bounds().bottom(), width(), - std::max(0, height() - size.height())); - for (int i = 0; i < contents_->child_count(); ++i) - contents_->child_at(i)->SetSize(contents_->size()); -} - -void TabbedPane::ViewHierarchyChanged( - const ViewHierarchyChangedDetails& details) { - if (details.is_add) { - // Support navigating tabs by Ctrl+Tab and Ctrl+Shift+Tab. - AddAccelerator(ui::Accelerator(ui::VKEY_TAB, - ui::EF_CONTROL_DOWN | ui::EF_SHIFT_DOWN)); - AddAccelerator(ui::Accelerator(ui::VKEY_TAB, ui::EF_CONTROL_DOWN)); - } -} - -bool TabbedPane::AcceleratorPressed(const ui::Accelerator& accelerator) { - // Handle Ctrl+Tab and Ctrl+Shift+Tab navigation of pages. - DCHECK(accelerator.key_code() == ui::VKEY_TAB && accelerator.IsCtrlDown()); - const int tab_count = GetTabCount(); - if (tab_count <= 1) - return false; - const int increment = accelerator.IsShiftDown() ? -1 : 1; - int next_tab_index = (selected_tab_index() + increment) % tab_count; - // Wrap around. - if (next_tab_index < 0) - next_tab_index += tab_count; - SelectTabAt(next_tab_index); - return true; -} - -const char* TabbedPane::GetClassName() const { - return kViewClassName; -} - -void TabbedPane::OnFocus() { - View::OnFocus(); - - View* selected_tab = GetSelectedTab(); - if (selected_tab) { - selected_tab->NotifyAccessibilityEvent( - ui::AX_EVENT_FOCUS, true); - } -} - -void TabbedPane::GetAccessibleState(ui::AXViewState* state) { - state->role = ui::AX_ROLE_TAB_LIST; -} - -} // namespace views
diff --git a/ui/views/controls/tabbed_pane/tabbed_pane.h b/ui/views/controls/tabbed_pane/tabbed_pane.h deleted file mode 100644 index c404808..0000000 --- a/ui/views/controls/tabbed_pane/tabbed_pane.h +++ /dev/null
@@ -1,90 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_TABBED_PANE_TABBED_PANE_H_ -#define UI_VIEWS_CONTROLS_TABBED_PANE_TABBED_PANE_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/strings/string16.h" -#include "ui/views/view.h" - -namespace views { - -class Tab; -class TabbedPaneListener; -class TabStrip; - -// TabbedPane is a view that shows tabs. When the user clicks on a tab, the -// associated view is displayed. -class VIEWS_EXPORT TabbedPane : public View { - public: - // Internal class name. - static const char kViewClassName[]; - - TabbedPane(); - virtual ~TabbedPane(); - - TabbedPaneListener* listener() const { return listener_; } - void set_listener(TabbedPaneListener* listener) { listener_ = listener; } - - int selected_tab_index() const { return selected_tab_index_; } - - // Returns the number of tabs. - int GetTabCount(); - - // Returns the contents of the selected tab or NULL if there is none. - View* GetSelectedTab(); - - // Adds a new tab at the end of this TabbedPane with the specified |title|. - // |contents| is the view displayed when the tab is selected and is owned by - // the TabbedPane. - void AddTab(const base::string16& title, View* contents); - - // Adds a new tab at |index| with |title|. |contents| is the view displayed - // when the tab is selected and is owned by the TabbedPane. If the tabbed pane - // is currently empty, the new tab is selected. - void AddTabAtIndex(int index, const base::string16& title, View* contents); - - // Selects the tab at |index|, which must be valid. - void SelectTabAt(int index); - - // Selects |tab| (the tabstrip view, not its content) if it is valid. - void SelectTab(Tab* tab); - - // Overridden from View: - virtual gfx::Size GetPreferredSize() const override; - virtual const char* GetClassName() const override; - - private: - friend class TabStrip; - - // Get the Tab (the tabstrip view, not its content) at the valid |index|. - Tab* GetTabAt(int index); - - // Overridden from View: - virtual void Layout() override; - virtual void ViewHierarchyChanged( - const ViewHierarchyChangedDetails& details) override; - virtual bool AcceleratorPressed(const ui::Accelerator& accelerator) override; - virtual void OnFocus() override; - virtual void GetAccessibleState(ui::AXViewState* state) override; - - // A listener notified when tab selection changes. Weak, not owned. - TabbedPaneListener* listener_; - - // The tab strip and contents container. The child indices of these members - // correspond to match each Tab with its respective content View. - TabStrip* tab_strip_; - View* contents_; - - // The selected tab index or -1 if invalid. - int selected_tab_index_; - - DISALLOW_COPY_AND_ASSIGN(TabbedPane); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_TABBED_PANE_TABBED_PANE_H_
diff --git a/ui/views/controls/tabbed_pane/tabbed_pane_listener.h b/ui/views/controls/tabbed_pane/tabbed_pane_listener.h deleted file mode 100644 index 83376f7..0000000 --- a/ui/views/controls/tabbed_pane/tabbed_pane_listener.h +++ /dev/null
@@ -1,25 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_TABBED_PANE_TABBED_PANE_LISTENER_H_ -#define UI_VIEWS_CONTROLS_TABBED_PANE_TABBED_PANE_LISTENER_H_ - -#include "ui/views/views_export.h" - -namespace views { - -// An interface implemented by an object to let it know that a tabbed pane was -// selected by the user at the specified index. -class VIEWS_EXPORT TabbedPaneListener { - public: - // Called when the tab at |index| is selected by the user. - virtual void TabSelectedAt(int index) = 0; - - protected: - virtual ~TabbedPaneListener() {} -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_TABBED_PANE_TABBED_PANE_LISTENER_H_
diff --git a/ui/views/controls/tabbed_pane/tabbed_pane_unittest.cc b/ui/views/controls/tabbed_pane/tabbed_pane_unittest.cc deleted file mode 100644 index 8a4acd4..0000000 --- a/ui/views/controls/tabbed_pane/tabbed_pane_unittest.cc +++ /dev/null
@@ -1,95 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/memory/scoped_ptr.h" -#include "base/message_loop/message_loop.h" -#include "base/strings/utf_string_conversions.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/views/controls/tabbed_pane/tabbed_pane.h" -#include "ui/views/test/views_test_base.h" - -using base::ASCIIToUTF16; - -namespace views { - -namespace { - -// A view for testing that takes a fixed preferred size upon construction. -class FixedSizeView : public View { - public: - explicit FixedSizeView(const gfx::Size& size) - : size_(size) {} - - // Overridden from View: - virtual gfx::Size GetPreferredSize() const override { - return size_; - } - - private: - const gfx::Size size_; - - DISALLOW_COPY_AND_ASSIGN(FixedSizeView); -}; - -typedef ViewsTestBase TabbedPaneTest; - -// Tests TabbedPane::GetPreferredSize() and TabbedPane::Layout(). -TEST_F(TabbedPaneTest, SizeAndLayout) { - scoped_ptr<TabbedPane> tabbed_pane(new TabbedPane()); - View* child1 = new FixedSizeView(gfx::Size(20, 10)); - tabbed_pane->AddTab(ASCIIToUTF16("tab1"), child1); - View* child2 = new FixedSizeView(gfx::Size(5, 5)); - tabbed_pane->AddTab(ASCIIToUTF16("tab2"), child2); - tabbed_pane->SelectTabAt(0); - - // The |tabbed_pane| implementation of Views has no border by default. - // Therefore it should be as wide as the widest tab. The native Windows - // tabbed pane has a border that used up extra space. Therefore the preferred - // width is larger than the largest child. - gfx::Size pref(tabbed_pane->GetPreferredSize()); - EXPECT_GE(pref.width(), 20); - EXPECT_GT(pref.height(), 10); - - // The bounds of our children should be smaller than the tabbed pane's bounds. - tabbed_pane->SetBounds(0, 0, 100, 200); - RunPendingMessages(); - gfx::Rect bounds(child1->bounds()); - EXPECT_GT(bounds.width(), 0); - // The |tabbed_pane| has no border. Therefore the children should be as wide - // as the |tabbed_pane|. - EXPECT_LE(bounds.width(), 100); - EXPECT_GT(bounds.height(), 0); - EXPECT_LT(bounds.height(), 200); - - // If we switch to the other tab, it should get assigned the same bounds. - tabbed_pane->SelectTabAt(1); - EXPECT_EQ(bounds, child2->bounds()); -} - -TEST_F(TabbedPaneTest, AddAndSelect) { - scoped_ptr<TabbedPane> tabbed_pane(new TabbedPane()); - // Add several tabs; only the first should be a selected automatically. - for (int i = 0; i < 3; ++i) { - View* tab = new View(); - tabbed_pane->AddTab(ASCIIToUTF16("tab"), tab); - EXPECT_EQ(i + 1, tabbed_pane->GetTabCount()); - EXPECT_EQ(0, tabbed_pane->selected_tab_index()); - } - - // Select each tab. - for (int i = 0; i < tabbed_pane->GetTabCount(); ++i) { - tabbed_pane->SelectTabAt(i); - EXPECT_EQ(i, tabbed_pane->selected_tab_index()); - } - - // Add a tab at index 0, it should not be selected automatically. - View* tab0 = new View(); - tabbed_pane->AddTabAtIndex(0, ASCIIToUTF16("tab0"), tab0); - EXPECT_NE(tab0, tabbed_pane->GetSelectedTab()); - EXPECT_NE(0, tabbed_pane->selected_tab_index()); -} - -} // namespace - -} // namespace views
diff --git a/ui/views/controls/table/table_grouper.h b/ui/views/controls/table/table_grouper.h deleted file mode 100644 index ce100e4..0000000 --- a/ui/views/controls/table/table_grouper.h +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_TABLE_TABLE_GROUPER_H_ -#define UI_VIEWS_CONTROLS_TABLE_TABLE_GROUPER_H_ - -#include "ui/views/views_export.h" - -namespace views { - -struct VIEWS_EXPORT GroupRange { - int start; - int length; -}; - -// TableGrouper is used by TableView to group a set of rows and treat them -// as one. Rows that fall in the same group are selected together and sorted -// together. -class VIEWS_EXPORT TableGrouper { - public: - virtual void GetGroupRange(int model_index, GroupRange* range) = 0; - - protected: - virtual ~TableGrouper() {} -}; - -} - -#endif // UI_VIEWS_CONTROLS_TABLE_GROUP_TABLE_VIEW_H_
diff --git a/ui/views/controls/table/table_header.cc b/ui/views/controls/table/table_header.cc deleted file mode 100644 index a9d730f..0000000 --- a/ui/views/controls/table/table_header.cc +++ /dev/null
@@ -1,278 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/table/table_header.h" - -#include "third_party/skia/include/core/SkColor.h" -#include "ui/base/cursor/cursor.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/text_utils.h" -#include "ui/native_theme/native_theme.h" -#include "ui/views/background.h" -#include "ui/views/controls/table/table_utils.h" -#include "ui/views/controls/table/table_view.h" -#include "ui/views/native_cursor.h" - -namespace views { - -namespace { - -const int kVerticalPadding = 4; - -// The minimum width we allow a column to go down to. -const int kMinColumnWidth = 10; - -// Distace from edge columns can be resized by. -const int kResizePadding = 5; - -// Amount of space above/below the separator. -const int kSeparatorPadding = 4; - -const SkColor kTextColor = SK_ColorBLACK; -const SkColor kBackgroundColor1 = SkColorSetRGB(0xF9, 0xF9, 0xF9); -const SkColor kBackgroundColor2 = SkColorSetRGB(0xE8, 0xE8, 0xE8); -const SkColor kSeparatorColor = SkColorSetRGB(0xAA, 0xAA, 0xAA); - -// Size of the sort indicator (doesn't include padding). -const int kSortIndicatorSize = 8; - -} // namespace - -// static -const int TableHeader::kHorizontalPadding = 7; -// static -const int TableHeader::kSortIndicatorWidth = kSortIndicatorSize + - TableHeader::kHorizontalPadding * 2; - -typedef std::vector<TableView::VisibleColumn> Columns; - -TableHeader::TableHeader(TableView* table) : table_(table) { - set_background(Background::CreateVerticalGradientBackground( - kBackgroundColor1, kBackgroundColor2)); -} - -TableHeader::~TableHeader() { -} - -void TableHeader::Layout() { - SetBounds(x(), y(), table_->width(), GetPreferredSize().height()); -} - -void TableHeader::OnPaint(gfx::Canvas* canvas) { - // Paint the background and a separator at the bottom. The separator color - // matches that of the border around the scrollview. - OnPaintBackground(canvas); - SkColor border_color = GetNativeTheme()->GetSystemColor( - ui::NativeTheme::kColorId_UnfocusedBorderColor); - canvas->DrawLine(gfx::Point(0, height() - 1), - gfx::Point(width(), height() - 1), border_color); - - const Columns& columns = table_->visible_columns(); - const int sorted_column_id = table_->sort_descriptors().empty() ? -1 : - table_->sort_descriptors()[0].column_id; - for (size_t i = 0; i < columns.size(); ++i) { - if (columns[i].width >= 2) { - const int separator_x = GetMirroredXInView( - columns[i].x + columns[i].width - 1); - canvas->DrawLine(gfx::Point(separator_x, kSeparatorPadding), - gfx::Point(separator_x, height() - kSeparatorPadding), - kSeparatorColor); - } - - const int x = columns[i].x + kHorizontalPadding; - int width = columns[i].width - kHorizontalPadding - kHorizontalPadding; - if (width <= 0) - continue; - - const int title_width = - gfx::GetStringWidth(columns[i].column.title, font_list_); - const bool paint_sort_indicator = - (columns[i].column.id == sorted_column_id && - title_width + kSortIndicatorWidth <= width); - - if (paint_sort_indicator && - columns[i].column.alignment == ui::TableColumn::RIGHT) { - width -= kSortIndicatorWidth; - } - - canvas->DrawStringRectWithFlags( - columns[i].column.title, font_list_, kTextColor, - gfx::Rect(GetMirroredXWithWidthInView(x, width), kVerticalPadding, - width, height() - kVerticalPadding * 2), - TableColumnAlignmentToCanvasAlignment(columns[i].column.alignment)); - - if (paint_sort_indicator) { - SkPaint paint; - paint.setColor(kTextColor); - paint.setStyle(SkPaint::kFill_Style); - paint.setAntiAlias(true); - - int indicator_x = 0; - ui::TableColumn::Alignment alignment = columns[i].column.alignment; - if (base::i18n::IsRTL()) { - if (alignment == ui::TableColumn::LEFT) - alignment = ui::TableColumn::RIGHT; - else if (alignment == ui::TableColumn::RIGHT) - alignment = ui::TableColumn::LEFT; - } - switch (alignment) { - case ui::TableColumn::LEFT: - indicator_x = x + title_width; - break; - case ui::TableColumn::CENTER: - indicator_x = x + width / 2; - break; - case ui::TableColumn::RIGHT: - indicator_x = x + width; - break; - } - - const int scale = base::i18n::IsRTL() ? -1 : 1; - indicator_x += (kSortIndicatorWidth - kSortIndicatorSize) / 2; - indicator_x = GetMirroredXInView(indicator_x); - int indicator_y = height() / 2 - kSortIndicatorSize / 2; - SkPath indicator_path; - if (table_->sort_descriptors()[0].ascending) { - indicator_path.moveTo( - SkIntToScalar(indicator_x), - SkIntToScalar(indicator_y + kSortIndicatorSize)); - indicator_path.lineTo( - SkIntToScalar(indicator_x + kSortIndicatorSize * scale), - SkIntToScalar(indicator_y + kSortIndicatorSize)); - indicator_path.lineTo( - SkIntToScalar(indicator_x + kSortIndicatorSize / 2 * scale), - SkIntToScalar(indicator_y)); - } else { - indicator_path.moveTo(SkIntToScalar(indicator_x), - SkIntToScalar(indicator_y)); - indicator_path.lineTo( - SkIntToScalar(indicator_x + kSortIndicatorSize * scale), - SkIntToScalar(indicator_y)); - indicator_path.lineTo( - SkIntToScalar(indicator_x + kSortIndicatorSize / 2 * scale), - SkIntToScalar(indicator_y + kSortIndicatorSize)); - } - indicator_path.close(); - canvas->DrawPath(indicator_path, paint); - } - } -} - -gfx::Size TableHeader::GetPreferredSize() const { - return gfx::Size(1, kVerticalPadding * 2 + font_list_.GetHeight()); -} - -gfx::NativeCursor TableHeader::GetCursor(const ui::MouseEvent& event) { - return GetResizeColumn(GetMirroredXInView(event.x())) != -1 ? - GetNativeColumnResizeCursor() : View::GetCursor(event); -} - -bool TableHeader::OnMousePressed(const ui::MouseEvent& event) { - if (event.IsOnlyLeftMouseButton()) { - StartResize(event); - return true; - } - - // Return false so that context menus on ancestors work. - return false; -} - -bool TableHeader::OnMouseDragged(const ui::MouseEvent& event) { - ContinueResize(event); - return true; -} - -void TableHeader::OnMouseReleased(const ui::MouseEvent& event) { - const bool was_resizing = resize_details_ != NULL; - resize_details_.reset(); - if (!was_resizing && event.IsOnlyLeftMouseButton()) - ToggleSortOrder(event); -} - -void TableHeader::OnMouseCaptureLost() { - if (is_resizing()) { - table_->SetVisibleColumnWidth(resize_details_->column_index, - resize_details_->initial_width); - } - resize_details_.reset(); -} - -void TableHeader::OnGestureEvent(ui::GestureEvent* event) { - switch (event->type()) { - case ui::ET_GESTURE_TAP: - if (!resize_details_.get()) - ToggleSortOrder(*event); - break; - case ui::ET_GESTURE_SCROLL_BEGIN: - StartResize(*event); - break; - case ui::ET_GESTURE_SCROLL_UPDATE: - ContinueResize(*event); - break; - case ui::ET_GESTURE_SCROLL_END: - resize_details_.reset(); - break; - default: - return; - } - event->SetHandled(); -} - -bool TableHeader::StartResize(const ui::LocatedEvent& event) { - if (is_resizing()) - return false; - - const int index = GetResizeColumn(GetMirroredXInView(event.x())); - if (index == -1) - return false; - - resize_details_.reset(new ColumnResizeDetails); - resize_details_->column_index = index; - resize_details_->initial_x = event.root_location().x(); - resize_details_->initial_width = table_->visible_columns()[index].width; - return true; -} - -void TableHeader::ContinueResize(const ui::LocatedEvent& event) { - if (!is_resizing()) - return; - - const int scale = base::i18n::IsRTL() ? -1 : 1; - const int delta = scale * - (event.root_location().x() - resize_details_->initial_x); - table_->SetVisibleColumnWidth( - resize_details_->column_index, - std::max(kMinColumnWidth, resize_details_->initial_width + delta)); -} - -void TableHeader::ToggleSortOrder(const ui::LocatedEvent& event) { - if (table_->visible_columns().empty()) - return; - - const int x = GetMirroredXInView(event.x()); - const int index = GetClosestVisibleColumnIndex(table_, x); - const TableView::VisibleColumn& column(table_->visible_columns()[index]); - if (x >= column.x && x < column.x + column.width && event.y() >= 0 && - event.y() < height()) - table_->ToggleSortOrder(index); -} - -int TableHeader::GetResizeColumn(int x) const { - const Columns& columns(table_->visible_columns()); - if (columns.empty()) - return -1; - - const int index = GetClosestVisibleColumnIndex(table_, x); - DCHECK_NE(-1, index); - const TableView::VisibleColumn& column(table_->visible_columns()[index]); - if (index > 0 && x >= column.x - kResizePadding && - x <= column.x + kResizePadding) { - return index - 1; - } - const int max_x = column.x + column.width; - return (x >= max_x - kResizePadding && x <= max_x + kResizePadding) ? - index : -1; -} - -} // namespace views
diff --git a/ui/views/controls/table/table_header.h b/ui/views/controls/table/table_header.h deleted file mode 100644 index 55c0949..0000000 --- a/ui/views/controls/table/table_header.h +++ /dev/null
@@ -1,85 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_TABLE_TABLE_HEADER_H_ -#define UI_VIEWS_CONTROLS_TABLE_TABLE_HEADER_H_ - -#include "ui/gfx/font_list.h" -#include "ui/views/view.h" -#include "ui/views/views_export.h" - -namespace views { - -class TableView; - -// Views used to render the header for the table. -class VIEWS_EXPORT TableHeader : public views::View { - public: - // Amount the text is padded on the left/right side. - static const int kHorizontalPadding; - - // Amount of space reserved for the indicator and padding. - static const int kSortIndicatorWidth; - - explicit TableHeader(TableView* table); - virtual ~TableHeader(); - - const gfx::FontList& font_list() const { return font_list_; } - - // views::View overrides. - virtual void Layout() override; - virtual void OnPaint(gfx::Canvas* canvas) override; - virtual gfx::Size GetPreferredSize() const override; - virtual gfx::NativeCursor GetCursor(const ui::MouseEvent& event) override; - virtual bool OnMousePressed(const ui::MouseEvent& event) override; - virtual bool OnMouseDragged(const ui::MouseEvent& event) override; - virtual void OnMouseReleased(const ui::MouseEvent& event) override; - virtual void OnMouseCaptureLost() override; - virtual void OnGestureEvent(ui::GestureEvent* event) override; - - private: - // Used to track the column being resized. - struct ColumnResizeDetails { - ColumnResizeDetails() : column_index(0), initial_x(0), initial_width(0) {} - - // Index into table_->visible_columns() that is being resized. - int column_index; - - // X-coordinate of the mouse at the time the resize started. - int initial_x; - - // Width of the column when the drag started. - int initial_width; - }; - - // If not already resizing and |event| is over a resizable column starts - // resizing. - bool StartResize(const ui::LocatedEvent& event); - - // Continues a resize operation. Does nothing if not in the process of - // resizing. - void ContinueResize(const ui::LocatedEvent& event); - - // Toggles the sort order of the column at the location in |event|. - void ToggleSortOrder(const ui::LocatedEvent& event); - - // Returns the column to resize given the specified x-coordinate, or -1 if |x| - // is not in the resize range of any columns. - int GetResizeColumn(int x) const; - - bool is_resizing() const { return resize_details_.get() != NULL; } - - const gfx::FontList font_list_; - - TableView* table_; - - // If non-null a resize is in progress. - scoped_ptr<ColumnResizeDetails> resize_details_; - - DISALLOW_COPY_AND_ASSIGN(TableHeader); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_TABLE_TABLE_HEADER_H_
diff --git a/ui/views/controls/table/table_utils.cc b/ui/views/controls/table/table_utils.cc deleted file mode 100644 index 393c22d..0000000 --- a/ui/views/controls/table/table_utils.cc +++ /dev/null
@@ -1,117 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/table/table_utils.h" - -#include "base/logging.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/font_list.h" -#include "ui/gfx/text_utils.h" -#include "ui/views/controls/table/table_view.h" - -namespace views { - -const int kUnspecifiedColumnWidth = 90; - -int WidthForContent(const gfx::FontList& header_font_list, - const gfx::FontList& content_font_list, - int padding, - int header_padding, - const ui::TableColumn& column, - ui::TableModel* model) { - int width = header_padding; - if (!column.title.empty()) - width = gfx::GetStringWidth(column.title, header_font_list) + - header_padding; - - for (int i = 0, row_count = model->RowCount(); i < row_count; ++i) { - const int cell_width = - gfx::GetStringWidth(model->GetText(i, column.id), content_font_list); - width = std::max(width, cell_width); - } - return width + padding; -} - -std::vector<int> CalculateTableColumnSizes( - int width, - int first_column_padding, - const gfx::FontList& header_font_list, - const gfx::FontList& content_font_list, - int padding, - int header_padding, - const std::vector<ui::TableColumn>& columns, - ui::TableModel* model) { - float total_percent = 0; - int non_percent_width = 0; - std::vector<int> content_widths(columns.size(), 0); - for (size_t i = 0; i < columns.size(); ++i) { - const ui::TableColumn& column(columns[i]); - if (column.width <= 0) { - if (column.percent > 0) { - total_percent += column.percent; - // Make sure there is at least enough room for the header. - content_widths[i] = gfx::GetStringWidth(column.title, header_font_list) - + padding + header_padding; - } else { - content_widths[i] = WidthForContent(header_font_list, content_font_list, - padding, header_padding, column, - model); - if (i == 0) - content_widths[i] += first_column_padding; - } - non_percent_width += content_widths[i]; - } else { - content_widths[i] = column.width; - non_percent_width += column.width; - } - } - - std::vector<int> widths; - const int available_width = width - non_percent_width; - for (size_t i = 0; i < columns.size(); ++i) { - const ui::TableColumn& column = columns[i]; - int column_width = content_widths[i]; - if (column.width <= 0 && column.percent > 0 && available_width > 0) { - column_width += static_cast<int>(available_width * - (column.percent / total_percent)); - } - widths.push_back(column_width == 0 ? kUnspecifiedColumnWidth : - column_width); - } - - // If no columns have specified a percent give the last column all the extra - // space. - if (!columns.empty() && total_percent == 0.f && available_width > 0 && - columns.back().width <= 0 && columns.back().percent == 0.f) { - widths.back() += available_width; - } - - return widths; -} - -int TableColumnAlignmentToCanvasAlignment( - ui::TableColumn::Alignment alignment) { - switch (alignment) { - case ui::TableColumn::LEFT: - return gfx::Canvas::TEXT_ALIGN_LEFT; - case ui::TableColumn::CENTER: - return gfx::Canvas::TEXT_ALIGN_CENTER; - case ui::TableColumn::RIGHT: - return gfx::Canvas::TEXT_ALIGN_RIGHT; - } - NOTREACHED(); - return gfx::Canvas::TEXT_ALIGN_LEFT; -} - -int GetClosestVisibleColumnIndex(const TableView* table, int x) { - const std::vector<TableView::VisibleColumn>& columns( - table->visible_columns()); - for (size_t i = 0; i < columns.size(); ++i) { - if (x <= columns[i].x + columns[i].width) - return static_cast<int>(i); - } - return static_cast<int>(columns.size()) - 1; -} - -} // namespace views
diff --git a/ui/views/controls/table/table_utils.h b/ui/views/controls/table/table_utils.h deleted file mode 100644 index ec38710..0000000 --- a/ui/views/controls/table/table_utils.h +++ /dev/null
@@ -1,57 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_TABLE_TABLE_UTILS_H_ -#define UI_VIEWS_CONTROLS_TABLE_TABLE_UTILS_H_ - -#include <vector> - -#include "ui/base/models/table_model.h" -#include "ui/views/views_export.h" - -namespace gfx { -class FontList; -} - -namespace views { - -class TableView; - -VIEWS_EXPORT extern const int kUnspecifiedColumnWidth; - -// Returns the width needed to display the contents of the specified column. -// This is used internally by CalculateTableColumnSizes() and generally not -// useful by itself. |header_padding| is padding added to the header. -VIEWS_EXPORT int WidthForContent(const gfx::FontList& header_font_list, - const gfx::FontList& content_font_list, - int padding, - int header_padding, - const ui::TableColumn& column, - ui::TableModel* model); - -// Determines the width for each of the specified columns. |width| is the width -// to fit the columns into. |header_font_list| the font list used to draw the -// header and |content_font_list| the header used to draw the content. |padding| -// is extra horizontal spaced added to each cell, and |header_padding| added to -// the width needed for the header. -VIEWS_EXPORT std::vector<int> CalculateTableColumnSizes( - int width, - int first_column_padding, - const gfx::FontList& header_font_list, - const gfx::FontList& content_font_list, - int padding, - int header_padding, - const std::vector<ui::TableColumn>& columns, - ui::TableModel* model); - -// Converts a TableColumn::Alignment to the alignment for drawing the string. -int TableColumnAlignmentToCanvasAlignment(ui::TableColumn::Alignment alignment); - -// Returns the index of the closest visible column index to |x|. Return value is -// in terms of table->visible_columns(). -int GetClosestVisibleColumnIndex(const TableView* table, int x); - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_TABLE_TABLE_UTILS_H_
diff --git a/ui/views/controls/table/table_utils_unittest.cc b/ui/views/controls/table/table_utils_unittest.cc deleted file mode 100644 index 98b1fd2..0000000 --- a/ui/views/controls/table/table_utils_unittest.cc +++ /dev/null
@@ -1,124 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/table/table_utils.h" - -#include "base/strings/string_number_conversions.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/gfx/font_list.h" -#include "ui/views/controls/table/test_table_model.h" - -using ui::TableColumn; -using ui::TableModel; - -namespace views { - -namespace { - -std::string IntVectorToString(const std::vector<int>& values) { - std::string result; - for (size_t i = 0; i < values.size(); ++i) { - if (i != 0) - result += ","; - result += base::IntToString(values[i]); - } - return result; -} - -ui::TableColumn CreateTableColumnWithWidth(int width) { - ui::TableColumn column; - column.width = width; - return column; -} - -} // namespace - -// Verifies columns with a specified width is honored. -TEST(TableUtilsTest, SetWidthHonored) { - TestTableModel model(4); - std::vector<TableColumn> columns; - columns.push_back(CreateTableColumnWithWidth(20)); - columns.push_back(CreateTableColumnWithWidth(30)); - gfx::FontList font_list; - std::vector<int> result(CalculateTableColumnSizes( - 100, 0, font_list, font_list, 0, 0, columns, &model)); - EXPECT_EQ("20,30", IntVectorToString(result)); - - // Same with some padding, it should be ignored. - result = CalculateTableColumnSizes( - 100, 0, font_list, font_list, 2, 0, columns, &model); - EXPECT_EQ("20,30", IntVectorToString(result)); - - // Same with not enough space, it shouldn't matter. - result = CalculateTableColumnSizes( - 10, 0, font_list, font_list, 2, 0, columns, &model); - EXPECT_EQ("20,30", IntVectorToString(result)); -} - -// Verifies if no size is specified the last column gets all the available -// space. -TEST(TableUtilsTest, LastColumnGetsAllSpace) { - TestTableModel model(4); - std::vector<TableColumn> columns; - columns.push_back(ui::TableColumn()); - columns.push_back(ui::TableColumn()); - gfx::FontList font_list; - std::vector<int> result(CalculateTableColumnSizes( - 500, 0, font_list, font_list, 0, 0, columns, &model)); - EXPECT_NE(0, result[0]); - EXPECT_GE(result[1], - WidthForContent(font_list, font_list, 0, 0, columns[1], &model)); - EXPECT_EQ(500, result[0] + result[1]); -} - -// Verifies a single column with a percent=1 is resized correctly. -TEST(TableUtilsTest, SingleResizableColumn) { - TestTableModel model(4); - std::vector<TableColumn> columns; - columns.push_back(ui::TableColumn()); - columns.push_back(ui::TableColumn()); - columns.push_back(ui::TableColumn()); - columns[2].percent = 1.0f; - gfx::FontList font_list; - std::vector<int> result(CalculateTableColumnSizes( - 500, 0, font_list, font_list, 0, 0, columns, &model)); - EXPECT_EQ(result[0], - WidthForContent(font_list, font_list, 0, 0, columns[0], &model)); - EXPECT_EQ(result[1], - WidthForContent(font_list, font_list, 0, 0, columns[1], &model)); - EXPECT_EQ(500 - result[0] - result[1], result[2]); - - // The same with a slightly larger width passed in. - result = CalculateTableColumnSizes( - 1000, 0, font_list, font_list, 0, 0, columns, &model); - EXPECT_EQ(result[0], - WidthForContent(font_list, font_list, 0, 0, columns[0], &model)); - EXPECT_EQ(result[1], - WidthForContent(font_list, font_list, 0, 0, columns[1], &model)); - EXPECT_EQ(1000 - result[0] - result[1], result[2]); - - // Verify padding for the first column is honored. - result = CalculateTableColumnSizes( - 1000, 10, font_list, font_list, 0, 0, columns, &model); - EXPECT_EQ(result[0], - WidthForContent(font_list, font_list, 0, 0, columns[0], &model) - + 10); - EXPECT_EQ(result[1], - WidthForContent(font_list, font_list, 0, 0, columns[1], &model)); - EXPECT_EQ(1000 - result[0] - result[1], result[2]); - - // Just enough space to show the first two columns. Should force last column - // to min size. - result = CalculateTableColumnSizes( - 1000, 0, font_list, font_list, 0, 0, columns, &model); - result = CalculateTableColumnSizes( - result[0] + result[1], 0, font_list, font_list, 0, 0, columns, &model); - EXPECT_EQ(result[0], - WidthForContent(font_list, font_list, 0, 0, columns[0], &model)); - EXPECT_EQ(result[1], - WidthForContent(font_list, font_list, 0, 0, columns[1], &model)); - EXPECT_EQ(kUnspecifiedColumnWidth, result[2]); -} - -} // namespace views
diff --git a/ui/views/controls/table/table_view.cc b/ui/views/controls/table/table_view.cc deleted file mode 100644 index e5120d4..0000000 --- a/ui/views/controls/table/table_view.cc +++ /dev/null
@@ -1,908 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/table/table_view.h" - -#include <map> - -#include "base/auto_reset.h" -#include "base/i18n/rtl.h" -#include "ui/events/event.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/image/image_skia.h" -#include "ui/gfx/rect_conversions.h" -#include "ui/gfx/skia_util.h" -#include "ui/gfx/text_utils.h" -#include "ui/native_theme/native_theme.h" -#include "ui/views/controls/scroll_view.h" -#include "ui/views/controls/table/table_grouper.h" -#include "ui/views/controls/table/table_header.h" -#include "ui/views/controls/table/table_utils.h" -#include "ui/views/controls/table/table_view_observer.h" -#include "ui/views/controls/table/table_view_row_background_painter.h" - -// Padding around the text (on each side). -static const int kTextVerticalPadding = 3; -static const int kTextHorizontalPadding = 6; - -// Size of images. -static const int kImageSize = 16; - -static const int kGroupingIndicatorSize = 6; - -namespace views { - -namespace { - -// Returns result, unless ascending is false in which case -result is returned. -int SwapCompareResult(int result, bool ascending) { - return ascending ? result : -result; -} - -// Populates |model_index_to_range_start| based on the |grouper|. -void GetModelIndexToRangeStart(TableGrouper* grouper, - int row_count, - std::map<int, int>* model_index_to_range_start) { - for (int model_index = 0; model_index < row_count;) { - GroupRange range; - grouper->GetGroupRange(model_index, &range); - DCHECK_GT(range.length, 0); - for (int range_counter = 0; range_counter < range.length; range_counter++) - (*model_index_to_range_start)[range_counter + model_index] = model_index; - model_index += range.length; - } -} - -// Returns the color id for the background of selected text. |has_focus| -// indicates if the table has focus. -ui::NativeTheme::ColorId text_background_color_id(bool has_focus) { - return has_focus ? - ui::NativeTheme::kColorId_TableSelectionBackgroundFocused : - ui::NativeTheme::kColorId_TableSelectionBackgroundUnfocused; -} - -// Returns the color id for text. |has_focus| indicates if the table has focus. -ui::NativeTheme::ColorId selected_text_color_id(bool has_focus) { - return has_focus ? ui::NativeTheme::kColorId_TableSelectedText : - ui::NativeTheme::kColorId_TableSelectedTextUnfocused; -} - -} // namespace - -// Used as the comparator to sort the contents of the table. -struct TableView::SortHelper { - explicit SortHelper(TableView* table) : table(table) {} - - bool operator()(int model_index1, int model_index2) { - return table->CompareRows(model_index1, model_index2) < 0; - } - - TableView* table; -}; - -// Used as the comparator to sort the contents of the table when a TableGrouper -// is present. When groups are present we sort the groups based on the first row -// in the group and within the groups we keep the same order as the model. -struct TableView::GroupSortHelper { - explicit GroupSortHelper(TableView* table) : table(table) {} - - bool operator()(int model_index1, int model_index2) { - const int range1 = model_index_to_range_start[model_index1]; - const int range2 = model_index_to_range_start[model_index2]; - if (range1 == range2) { - // The two rows are in the same group, sort so that items in the same - // group always appear in the same order. - return model_index1 < model_index2; - } - return table->CompareRows(range1, range2) < 0; - } - - TableView* table; - std::map<int, int> model_index_to_range_start; -}; - -TableView::VisibleColumn::VisibleColumn() : x(0), width(0) {} - -TableView::VisibleColumn::~VisibleColumn() {} - -TableView::PaintRegion::PaintRegion() - : min_row(0), - max_row(0), - min_column(0), - max_column(0) { -} - -TableView::PaintRegion::~PaintRegion() {} - -TableView::TableView(ui::TableModel* model, - const std::vector<ui::TableColumn>& columns, - TableTypes table_type, - bool single_selection) - : model_(NULL), - columns_(columns), - header_(NULL), - table_type_(table_type), - single_selection_(single_selection), - table_view_observer_(NULL), - row_height_(font_list_.GetHeight() + kTextVerticalPadding * 2), - last_parent_width_(0), - layout_width_(0), - grouper_(NULL), - in_set_visible_column_width_(false) { - for (size_t i = 0; i < columns.size(); ++i) { - VisibleColumn visible_column; - visible_column.column = columns[i]; - visible_columns_.push_back(visible_column); - } - SetFocusable(true); - SetModel(model); -} - -TableView::~TableView() { - if (model_) - model_->SetObserver(NULL); -} - -// TODO: this doesn't support arbitrarily changing the model, rename this to -// ClearModel() or something. -void TableView::SetModel(ui::TableModel* model) { - if (model == model_) - return; - - if (model_) - model_->SetObserver(NULL); - model_ = model; - selection_model_.Clear(); - if (model_) - model_->SetObserver(this); -} - -View* TableView::CreateParentIfNecessary() { - ScrollView* scroll_view = ScrollView::CreateScrollViewWithBorder(); - scroll_view->SetContents(this); - CreateHeaderIfNecessary(); - if (header_) - scroll_view->SetHeader(header_); - return scroll_view; -} - -void TableView::SetRowBackgroundPainter( - scoped_ptr<TableViewRowBackgroundPainter> painter) { - row_background_painter_ = painter.Pass(); -} - -void TableView::SetGrouper(TableGrouper* grouper) { - grouper_ = grouper; - SortItemsAndUpdateMapping(); -} - -int TableView::RowCount() const { - return model_ ? model_->RowCount() : 0; -} - -int TableView::SelectedRowCount() { - return static_cast<int>(selection_model_.size()); -} - -void TableView::Select(int model_row) { - if (!model_) - return; - - SelectByViewIndex(model_row == -1 ? -1 : ModelToView(model_row)); -} - -int TableView::FirstSelectedRow() { - return SelectedRowCount() == 0 ? -1 : selection_model_.selected_indices()[0]; -} - -void TableView::SetColumnVisibility(int id, bool is_visible) { - if (is_visible == IsColumnVisible(id)) - return; - - if (is_visible) { - VisibleColumn visible_column; - visible_column.column = FindColumnByID(id); - visible_columns_.push_back(visible_column); - } else { - for (size_t i = 0; i < visible_columns_.size(); ++i) { - if (visible_columns_[i].column.id == id) { - visible_columns_.erase(visible_columns_.begin() + i); - break; - } - } - } - UpdateVisibleColumnSizes(); - PreferredSizeChanged(); - SchedulePaint(); - if (header_) - header_->SchedulePaint(); -} - -void TableView::ToggleSortOrder(int visible_column_index) { - DCHECK(visible_column_index >= 0 && - visible_column_index < static_cast<int>(visible_columns_.size())); - if (!visible_columns_[visible_column_index].column.sortable) - return; - const int column_id = visible_columns_[visible_column_index].column.id; - SortDescriptors sort(sort_descriptors_); - if (!sort.empty() && sort[0].column_id == column_id) { - sort[0].ascending = !sort[0].ascending; - } else { - SortDescriptor descriptor(column_id, true); - sort.insert(sort.begin(), descriptor); - // Only persist two sort descriptors. - if (sort.size() > 2) - sort.resize(2); - } - SetSortDescriptors(sort); -} - -bool TableView::IsColumnVisible(int id) const { - for (size_t i = 0; i < visible_columns_.size(); ++i) { - if (visible_columns_[i].column.id == id) - return true; - } - return false; -} - -void TableView::AddColumn(const ui::TableColumn& col) { - DCHECK(!HasColumn(col.id)); - columns_.push_back(col); -} - -bool TableView::HasColumn(int id) const { - for (size_t i = 0; i < columns_.size(); ++i) { - if (columns_[i].id == id) - return true; - } - return false; -} - -void TableView::SetVisibleColumnWidth(int index, int width) { - DCHECK(index >= 0 && index < static_cast<int>(visible_columns_.size())); - if (visible_columns_[index].width == width) - return; - base::AutoReset<bool> reseter(&in_set_visible_column_width_, true); - visible_columns_[index].width = width; - for (size_t i = index + 1; i < visible_columns_.size(); ++i) { - visible_columns_[i].x = - visible_columns_[i - 1].x + visible_columns_[i - 1].width; - } - PreferredSizeChanged(); - SchedulePaint(); -} - -int TableView::ModelToView(int model_index) const { - if (!is_sorted()) - return model_index; - DCHECK_GE(model_index, 0) << " negative model_index " << model_index; - DCHECK_LT(model_index, RowCount()) << " out of bounds model_index " << - model_index; - return model_to_view_[model_index]; -} - -int TableView::ViewToModel(int view_index) const { - if (!is_sorted()) - return view_index; - DCHECK_GE(view_index, 0) << " negative view_index " << view_index; - DCHECK_LT(view_index, RowCount()) << " out of bounds view_index " << - view_index; - return view_to_model_[view_index]; -} - -void TableView::Layout() { - // parent()->parent() is the scrollview. When its width changes we force - // recalculating column sizes. - View* scroll_view = parent() ? parent()->parent() : NULL; - if (scroll_view) { - const int scroll_view_width = scroll_view->GetContentsBounds().width(); - if (scroll_view_width != last_parent_width_) { - last_parent_width_ = scroll_view_width; - if (!in_set_visible_column_width_) { - // Layout to the parent (the Viewport), which differs from - // |scroll_view_width| when scrollbars are present. - layout_width_ = parent()->width(); - UpdateVisibleColumnSizes(); - } - } - } - // We have to override Layout like this since we're contained in a ScrollView. - gfx::Size pref = GetPreferredSize(); - int width = pref.width(); - int height = pref.height(); - if (parent()) { - width = std::max(parent()->width(), width); - height = std::max(parent()->height(), height); - } - SetBounds(x(), y(), width, height); -} - -gfx::Size TableView::GetPreferredSize() const { - int width = 50; - if (header_ && !visible_columns_.empty()) - width = visible_columns_.back().x + visible_columns_.back().width; - return gfx::Size(width, RowCount() * row_height_); -} - -bool TableView::OnKeyPressed(const ui::KeyEvent& event) { - if (!HasFocus()) - return false; - - switch (event.key_code()) { - case ui::VKEY_A: - // control-a selects all. - if (event.IsControlDown() && !single_selection_ && RowCount()) { - ui::ListSelectionModel selection_model; - selection_model.SetSelectedIndex(selection_model_.active()); - for (int i = 0; i < RowCount(); ++i) - selection_model.AddIndexToSelection(i); - SetSelectionModel(selection_model); - return true; - } - break; - - case ui::VKEY_HOME: - if (RowCount()) - SelectByViewIndex(0); - return true; - - case ui::VKEY_END: - if (RowCount()) - SelectByViewIndex(RowCount() - 1); - return true; - - case ui::VKEY_UP: - AdvanceSelection(ADVANCE_DECREMENT); - return true; - - case ui::VKEY_DOWN: - AdvanceSelection(ADVANCE_INCREMENT); - return true; - - default: - break; - } - if (table_view_observer_) - table_view_observer_->OnKeyDown(event.key_code()); - return false; -} - -bool TableView::OnMousePressed(const ui::MouseEvent& event) { - RequestFocus(); - if (!event.IsOnlyLeftMouseButton()) - return true; - - const int row = event.y() / row_height_; - if (row < 0 || row >= RowCount()) - return true; - - if (event.GetClickCount() == 2) { - SelectByViewIndex(row); - if (table_view_observer_) - table_view_observer_->OnDoubleClick(); - } else if (event.GetClickCount() == 1) { - ui::ListSelectionModel new_model; - ConfigureSelectionModelForEvent(event, &new_model); - SetSelectionModel(new_model); - } - - return true; -} - -void TableView::OnGestureEvent(ui::GestureEvent* event) { - if (event->type() != ui::ET_GESTURE_TAP) - return; - - const int row = event->y() / row_height_; - if (row < 0 || row >= RowCount()) - return; - - event->StopPropagation(); - ui::ListSelectionModel new_model; - ConfigureSelectionModelForEvent(*event, &new_model); - SetSelectionModel(new_model); -} - -bool TableView::GetTooltipText(const gfx::Point& p, - base::string16* tooltip) const { - return GetTooltipImpl(p, tooltip, NULL); -} - -bool TableView::GetTooltipTextOrigin(const gfx::Point& p, - gfx::Point* loc) const { - return GetTooltipImpl(p, NULL, loc); -} - -void TableView::OnModelChanged() { - selection_model_.Clear(); - NumRowsChanged(); -} - -void TableView::OnItemsChanged(int start, int length) { - SortItemsAndUpdateMapping(); -} - -void TableView::OnItemsAdded(int start, int length) { - for (int i = 0; i < length; ++i) - selection_model_.IncrementFrom(start); - NumRowsChanged(); -} - -void TableView::OnItemsRemoved(int start, int length) { - // Determine the currently selected index in terms of the view. We inline the - // implementation here since ViewToModel() has DCHECKs that fail since the - // model has changed but |model_to_view_| has not been updated yet. - const int previously_selected_model_index = FirstSelectedRow(); - int previously_selected_view_index = previously_selected_model_index; - if (previously_selected_model_index != -1 && is_sorted()) - previously_selected_view_index = - model_to_view_[previously_selected_model_index]; - for (int i = 0; i < length; ++i) - selection_model_.DecrementFrom(start); - NumRowsChanged(); - // If the selection was empty and is no longer empty select the same visual - // index. - if (selection_model_.empty() && previously_selected_view_index != -1 && - RowCount()) { - selection_model_.SetSelectedIndex( - ViewToModel(std::min(RowCount() - 1, previously_selected_view_index))); - } - if (table_view_observer_) - table_view_observer_->OnSelectionChanged(); -} - -gfx::Point TableView::GetKeyboardContextMenuLocation() { - int first_selected = FirstSelectedRow(); - gfx::Rect vis_bounds(GetVisibleBounds()); - int y = vis_bounds.height() / 2; - if (first_selected != -1) { - gfx::Rect cell_bounds(GetRowBounds(first_selected)); - if (cell_bounds.bottom() >= vis_bounds.y() && - cell_bounds.bottom() < vis_bounds.bottom()) { - y = cell_bounds.bottom(); - } - } - gfx::Point screen_loc(0, y); - if (base::i18n::IsRTL()) - screen_loc.set_x(width()); - ConvertPointToScreen(this, &screen_loc); - return screen_loc; -} - -void TableView::OnPaint(gfx::Canvas* canvas) { - // Don't invoke View::OnPaint so that we can render our own focus border. - - canvas->DrawColor(GetNativeTheme()->GetSystemColor( - ui::NativeTheme::kColorId_TableBackground)); - - if (!RowCount() || visible_columns_.empty()) - return; - - const PaintRegion region(GetPaintRegion(GetPaintBounds(canvas))); - if (region.min_column == -1) - return; // No need to paint anything. - - const SkColor selected_bg_color = GetNativeTheme()->GetSystemColor( - text_background_color_id(HasFocus())); - const SkColor fg_color = GetNativeTheme()->GetSystemColor( - ui::NativeTheme::kColorId_TableText); - const SkColor selected_fg_color = GetNativeTheme()->GetSystemColor( - selected_text_color_id(HasFocus())); - for (int i = region.min_row; i < region.max_row; ++i) { - const int model_index = ViewToModel(i); - const bool is_selected = selection_model_.IsSelected(model_index); - if (is_selected) { - canvas->FillRect(GetRowBounds(i), selected_bg_color); - } else if (row_background_painter_) { - row_background_painter_->PaintRowBackground(model_index, - GetRowBounds(i), - canvas); - } - if (selection_model_.active() == i && HasFocus()) - canvas->DrawFocusRect(GetRowBounds(i)); - for (int j = region.min_column; j < region.max_column; ++j) { - const gfx::Rect cell_bounds(GetCellBounds(i, j)); - int text_x = kTextHorizontalPadding + cell_bounds.x(); - - // Provide space for the grouping indicator, but draw it separately. - if (j == 0 && grouper_) - text_x += kGroupingIndicatorSize + kTextHorizontalPadding; - - // Always paint the icon in the first visible column. - if (j == 0 && table_type_ == ICON_AND_TEXT) { - gfx::ImageSkia image = model_->GetIcon(model_index); - if (!image.isNull()) { - int image_x = GetMirroredXWithWidthInView(text_x, kImageSize); - canvas->DrawImageInt( - image, 0, 0, image.width(), image.height(), - image_x, - cell_bounds.y() + (cell_bounds.height() - kImageSize) / 2, - kImageSize, kImageSize, true); - } - text_x += kImageSize + kTextHorizontalPadding; - } - if (text_x < cell_bounds.right() - kTextHorizontalPadding) { - canvas->DrawStringRectWithFlags( - model_->GetText(model_index, visible_columns_[j].column.id), - font_list_, is_selected ? selected_fg_color : fg_color, - gfx::Rect(GetMirroredXWithWidthInView( - text_x, cell_bounds.right() - text_x - kTextHorizontalPadding), - cell_bounds.y() + kTextVerticalPadding, - cell_bounds.right() - text_x, - cell_bounds.height() - kTextVerticalPadding * 2), - TableColumnAlignmentToCanvasAlignment( - visible_columns_[j].column.alignment)); - } - } - } - - if (!grouper_ || region.min_column > 0) - return; - - const SkColor grouping_color = GetNativeTheme()->GetSystemColor( - ui::NativeTheme::kColorId_TableGroupingIndicatorColor); - SkPaint grouping_paint; - grouping_paint.setColor(grouping_color); - grouping_paint.setStyle(SkPaint::kFill_Style); - grouping_paint.setAntiAlias(true); - const int group_indicator_x = GetMirroredXInView(GetCellBounds(0, 0).x() + - kTextHorizontalPadding + kGroupingIndicatorSize / 2); - for (int i = region.min_row; i < region.max_row; ) { - const int model_index = ViewToModel(i); - GroupRange range; - grouper_->GetGroupRange(model_index, &range); - DCHECK_GT(range.length, 0); - // The order of rows in a group is consistent regardless of sort, so it's ok - // to do this calculation. - const int start = i - (model_index - range.start); - const int last = start + range.length - 1; - const gfx::Rect start_cell_bounds(GetCellBounds(start, 0)); - if (start != last) { - const gfx::Rect last_cell_bounds(GetCellBounds(last, 0)); - canvas->FillRect(gfx::Rect( - group_indicator_x - kGroupingIndicatorSize / 2, - start_cell_bounds.CenterPoint().y(), - kGroupingIndicatorSize, - last_cell_bounds.y() - start_cell_bounds.y()), - grouping_color); - canvas->DrawCircle(gfx::Point(group_indicator_x, - last_cell_bounds.CenterPoint().y()), - kGroupingIndicatorSize / 2, grouping_paint); - } - canvas->DrawCircle(gfx::Point(group_indicator_x, - start_cell_bounds.CenterPoint().y()), - kGroupingIndicatorSize / 2, grouping_paint); - i = last + 1; - } -} - -void TableView::OnFocus() { - SchedulePaintForSelection(); -} - -void TableView::OnBlur() { - SchedulePaintForSelection(); -} - -void TableView::NumRowsChanged() { - SortItemsAndUpdateMapping(); - PreferredSizeChanged(); - SchedulePaint(); -} - -void TableView::SetSortDescriptors(const SortDescriptors& sort_descriptors) { - sort_descriptors_ = sort_descriptors; - SortItemsAndUpdateMapping(); - if (header_) - header_->SchedulePaint(); -} - -void TableView::SortItemsAndUpdateMapping() { - if (!is_sorted()) { - view_to_model_.clear(); - model_to_view_.clear(); - } else { - const int row_count = RowCount(); - view_to_model_.resize(row_count); - model_to_view_.resize(row_count); - for (int i = 0; i < row_count; ++i) - view_to_model_[i] = i; - if (grouper_) { - GroupSortHelper sort_helper(this); - GetModelIndexToRangeStart(grouper_, RowCount(), - &sort_helper.model_index_to_range_start); - std::sort(view_to_model_.begin(), view_to_model_.end(), sort_helper); - } else { - std::sort(view_to_model_.begin(), view_to_model_.end(), SortHelper(this)); - } - for (int i = 0; i < row_count; ++i) - model_to_view_[view_to_model_[i]] = i; - model_->ClearCollator(); - } - SchedulePaint(); -} - -int TableView::CompareRows(int model_row1, int model_row2) { - const int sort_result = model_->CompareValues( - model_row1, model_row2, sort_descriptors_[0].column_id); - if (sort_result == 0 && sort_descriptors_.size() > 1) { - // Try the secondary sort. - return SwapCompareResult( - model_->CompareValues(model_row1, model_row2, - sort_descriptors_[1].column_id), - sort_descriptors_[1].ascending); - } - return SwapCompareResult(sort_result, sort_descriptors_[0].ascending); -} - -gfx::Rect TableView::GetRowBounds(int row) const { - return gfx::Rect(0, row * row_height_, width(), row_height_); -} - -gfx::Rect TableView::GetCellBounds(int row, int visible_column_index) const { - if (!header_) - return GetRowBounds(row); - const VisibleColumn& vis_col(visible_columns_[visible_column_index]); - return gfx::Rect(vis_col.x, row * row_height_, vis_col.width, row_height_); -} - -void TableView::AdjustCellBoundsForText(int visible_column_index, - gfx::Rect* bounds) const { - int text_x = kTextHorizontalPadding + bounds->x(); - if (visible_column_index == 0) { - if (grouper_) - text_x += kGroupingIndicatorSize + kTextHorizontalPadding; - if (table_type_ == ICON_AND_TEXT) - text_x += kImageSize + kTextHorizontalPadding; - } - bounds->set_x(text_x); - bounds->set_width( - std::max(0, bounds->right() - kTextHorizontalPadding - text_x)); -} - -void TableView::CreateHeaderIfNecessary() { - // Only create a header if there is more than one column or the title of the - // only column is not empty. - if (header_ || (columns_.size() == 1 && columns_[0].title.empty())) - return; - - header_ = new TableHeader(this); -} - -void TableView::UpdateVisibleColumnSizes() { - if (!header_) - return; - - std::vector<ui::TableColumn> columns; - for (size_t i = 0; i < visible_columns_.size(); ++i) - columns.push_back(visible_columns_[i].column); - - int first_column_padding = 0; - if (table_type_ == ICON_AND_TEXT && header_) - first_column_padding += kImageSize + kTextHorizontalPadding; - if (grouper_) - first_column_padding += kGroupingIndicatorSize + kTextHorizontalPadding; - - std::vector<int> sizes = views::CalculateTableColumnSizes( - layout_width_, first_column_padding, header_->font_list(), font_list_, - std::max(kTextHorizontalPadding, TableHeader::kHorizontalPadding) * 2, - TableHeader::kSortIndicatorWidth, columns, model_); - DCHECK_EQ(visible_columns_.size(), sizes.size()); - int x = 0; - for (size_t i = 0; i < visible_columns_.size(); ++i) { - visible_columns_[i].x = x; - visible_columns_[i].width = sizes[i]; - x += sizes[i]; - } -} - -TableView::PaintRegion TableView::GetPaintRegion( - const gfx::Rect& bounds) const { - DCHECK(!visible_columns_.empty()); - DCHECK(RowCount()); - - PaintRegion region; - region.min_row = std::min(RowCount() - 1, - std::max(0, bounds.y() / row_height_)); - region.max_row = bounds.bottom() / row_height_; - if (bounds.bottom() % row_height_ != 0) - region.max_row++; - region.max_row = std::min(region.max_row, RowCount()); - - if (!header_) { - region.max_column = 1; - return region; - } - - const int paint_x = GetMirroredXForRect(bounds); - const int paint_max_x = paint_x + bounds.width(); - region.min_column = -1; - region.max_column = visible_columns_.size(); - for (size_t i = 0; i < visible_columns_.size(); ++i) { - int max_x = visible_columns_[i].x + visible_columns_[i].width; - if (region.min_column == -1 && max_x >= paint_x) - region.min_column = static_cast<int>(i); - if (region.min_column != -1 && visible_columns_[i].x >= paint_max_x) { - region.max_column = i; - break; - } - } - return region; -} - -gfx::Rect TableView::GetPaintBounds(gfx::Canvas* canvas) const { - SkRect sk_clip_rect; - if (canvas->sk_canvas()->getClipBounds(&sk_clip_rect)) - return gfx::ToEnclosingRect(gfx::SkRectToRectF(sk_clip_rect)); - return GetVisibleBounds(); -} - -void TableView::SchedulePaintForSelection() { - if (selection_model_.size() == 1) { - const int first_model_row = FirstSelectedRow(); - SchedulePaintInRect(GetRowBounds(ModelToView(first_model_row))); - if (first_model_row != selection_model_.active()) - SchedulePaintInRect(GetRowBounds(ModelToView(selection_model_.active()))); - } else if (selection_model_.size() > 1) { - SchedulePaint(); - } -} - -ui::TableColumn TableView::FindColumnByID(int id) const { - for (size_t i = 0; i < columns_.size(); ++i) { - if (columns_[i].id == id) - return columns_[i]; - } - NOTREACHED(); - return ui::TableColumn(); -} - -void TableView::SelectByViewIndex(int view_index) { - ui::ListSelectionModel new_selection; - if (view_index != -1) { - SelectRowsInRangeFrom(view_index, true, &new_selection); - new_selection.set_anchor(ViewToModel(view_index)); - new_selection.set_active(ViewToModel(view_index)); - } - - SetSelectionModel(new_selection); -} - -void TableView::SetSelectionModel(const ui::ListSelectionModel& new_selection) { - if (new_selection.Equals(selection_model_)) - return; - - SchedulePaintForSelection(); - selection_model_.Copy(new_selection); - SchedulePaintForSelection(); - - // Scroll the group for the active item to visible. - if (selection_model_.active() != -1) { - gfx::Rect vis_rect(GetVisibleBounds()); - const GroupRange range(GetGroupRange(selection_model_.active())); - const int start_y = GetRowBounds(ModelToView(range.start)).y(); - const int end_y = - GetRowBounds(ModelToView(range.start + range.length - 1)).bottom(); - vis_rect.set_y(start_y); - vis_rect.set_height(end_y - start_y); - ScrollRectToVisible(vis_rect); - } - - if (table_view_observer_) - table_view_observer_->OnSelectionChanged(); -} - -void TableView::AdvanceSelection(AdvanceDirection direction) { - if (selection_model_.active() == -1) { - SelectByViewIndex(0); - return; - } - int view_index = ModelToView(selection_model_.active()); - if (direction == ADVANCE_DECREMENT) - view_index = std::max(0, view_index - 1); - else - view_index = std::min(RowCount() - 1, view_index + 1); - SelectByViewIndex(view_index); -} - -void TableView::ConfigureSelectionModelForEvent( - const ui::LocatedEvent& event, - ui::ListSelectionModel* model) const { - const int view_index = event.y() / row_height_; - DCHECK(view_index >= 0 && view_index < RowCount()); - - if (selection_model_.anchor() == -1 || - single_selection_ || - (!event.IsControlDown() && !event.IsShiftDown())) { - SelectRowsInRangeFrom(view_index, true, model); - model->set_anchor(ViewToModel(view_index)); - model->set_active(ViewToModel(view_index)); - return; - } - if ((event.IsControlDown() && event.IsShiftDown()) || event.IsShiftDown()) { - // control-shift: copy existing model and make sure rows between anchor and - // |view_index| are selected. - // shift: reset selection so that only rows between anchor and |view_index| - // are selected. - if (event.IsControlDown() && event.IsShiftDown()) - model->Copy(selection_model_); - else - model->set_anchor(selection_model_.anchor()); - for (int i = std::min(view_index, ModelToView(model->anchor())), - end = std::max(view_index, ModelToView(model->anchor())); - i <= end; ++i) { - SelectRowsInRangeFrom(i, true, model); - } - model->set_active(ViewToModel(view_index)); - } else { - DCHECK(event.IsControlDown()); - // Toggle the selection state of |view_index| and set the anchor/active to - // it and don't change the state of any other rows. - model->Copy(selection_model_); - model->set_anchor(ViewToModel(view_index)); - model->set_active(ViewToModel(view_index)); - SelectRowsInRangeFrom(view_index, - !model->IsSelected(ViewToModel(view_index)), - model); - } -} - -void TableView::SelectRowsInRangeFrom(int view_index, - bool select, - ui::ListSelectionModel* model) const { - const GroupRange range(GetGroupRange(ViewToModel(view_index))); - for (int i = 0; i < range.length; ++i) { - if (select) - model->AddIndexToSelection(range.start + i); - else - model->RemoveIndexFromSelection(range.start + i); - } -} - -GroupRange TableView::GetGroupRange(int model_index) const { - GroupRange range; - if (grouper_) { - grouper_->GetGroupRange(model_index, &range); - } else { - range.start = model_index; - range.length = 1; - } - return range; -} - -bool TableView::GetTooltipImpl(const gfx::Point& location, - base::string16* tooltip, - gfx::Point* tooltip_origin) const { - const int row = location.y() / row_height_; - if (row < 0 || row >= RowCount() || visible_columns_.empty()) - return false; - - const int x = GetMirroredXInView(location.x()); - const int column = GetClosestVisibleColumnIndex(this, x); - if (x < visible_columns_[column].x || - x > (visible_columns_[column].x + visible_columns_[column].width)) - return false; - - const base::string16 text(model_->GetText(ViewToModel(row), - visible_columns_[column].column.id)); - if (text.empty()) - return false; - - gfx::Rect cell_bounds(GetCellBounds(row, column)); - AdjustCellBoundsForText(column, &cell_bounds); - const int right = std::min(GetVisibleBounds().right(), cell_bounds.right()); - if (right > cell_bounds.x() && - gfx::GetStringWidth(text, font_list_) <= (right - cell_bounds.x())) - return false; - - if (tooltip) - *tooltip = text; - if (tooltip_origin) { - tooltip_origin->SetPoint(cell_bounds.x(), - cell_bounds.y() + kTextVerticalPadding); - } - return true; -} - -} // namespace views
diff --git a/ui/views/controls/table/table_view.h b/ui/views/controls/table/table_view.h deleted file mode 100644 index c1a9162..0000000 --- a/ui/views/controls/table/table_view.h +++ /dev/null
@@ -1,349 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_TABLE_TABLE_VIEW_VIEWS_H_ -#define UI_VIEWS_CONTROLS_TABLE_TABLE_VIEW_VIEWS_H_ - -#include <vector> - -#include "base/memory/scoped_ptr.h" -#include "ui/base/models/list_selection_model.h" -#include "ui/base/models/table_model.h" -#include "ui/base/models/table_model_observer.h" -#include "ui/gfx/font_list.h" -#include "ui/views/view.h" -#include "ui/views/views_export.h" - -// A TableView is a view that displays multiple rows with any number of columns. -// TableView is driven by a TableModel. The model returns the contents -// to display. TableModel also has an Observer which is used to notify -// TableView of changes to the model so that the display may be updated -// appropriately. -// -// TableView itself has an observer that is notified when the selection -// changes. -// -// When a table is sorted the model coordinates do not necessarily match the -// view coordinates. All table methods are in terms of the model. If you need to -// convert to view coordinates use ModelToView(). -// -// Sorting is done by a locale sensitive string sort. You can customize the -// sort by way of overriding TableModel::CompareValues(). -namespace views { - -struct GroupRange; -class TableGrouper; -class TableHeader; -class TableViewObserver; -class TableViewRowBackgroundPainter; -class TableViewTestHelper; - -// The cells in the first column of a table can contain: -// - only text -// - a small icon (16x16) and some text -// - a check box and some text -enum TableTypes { - TEXT_ONLY = 0, - ICON_AND_TEXT, -}; - -class VIEWS_EXPORT TableView - : public views::View, - public ui::TableModelObserver { - public: - // Used to track a visible column. Useful only for the header. - struct VIEWS_EXPORT VisibleColumn { - VisibleColumn(); - ~VisibleColumn(); - - // The column. - ui::TableColumn column; - - // Starting x-coordinate of the column. - int x; - - // Width of the column. - int width; - }; - - // Describes a sorted column. - struct VIEWS_EXPORT SortDescriptor { - SortDescriptor() : column_id(-1), ascending(true) {} - SortDescriptor(int column_id, bool ascending) - : column_id(column_id), - ascending(ascending) {} - - // ID of the sorted column. - int column_id; - - // Is the sort ascending? - bool ascending; - }; - - typedef std::vector<SortDescriptor> SortDescriptors; - - // Creates a new table using the model and columns specified. - // The table type applies to the content of the first column (text, icon and - // text, checkbox and text). - TableView(ui::TableModel* model, - const std::vector<ui::TableColumn>& columns, - TableTypes table_type, - bool single_selection); - virtual ~TableView(); - - // Assigns a new model to the table view, detaching the old one if present. - // If |model| is NULL, the table view cannot be used after this call. This - // should be called in the containing view's destructor to avoid destruction - // issues when the model needs to be deleted before the table. - void SetModel(ui::TableModel* model); - ui::TableModel* model() const { return model_; } - - // Returns a new ScrollView that contains the receiver. - View* CreateParentIfNecessary(); - - void SetRowBackgroundPainter( - scoped_ptr<TableViewRowBackgroundPainter> painter); - - // Sets the TableGrouper. TableView does not own |grouper| (common use case is - // to have TableModel implement TableGrouper). - void SetGrouper(TableGrouper* grouper); - - // Returns the number of rows in the TableView. - int RowCount() const; - - // Returns the number of selected rows. - // TODO(sky): remove this and force callers to use selection_model(). - int SelectedRowCount(); - - // Selects the specified item, making sure it's visible. - void Select(int model_row); - - // Returns the first selected row in terms of the model. - int FirstSelectedRow(); - - const ui::ListSelectionModel& selection_model() const { - return selection_model_; - } - - // Changes the visibility of the specified column (by id). - void SetColumnVisibility(int id, bool is_visible); - bool IsColumnVisible(int id) const; - - // Adds the specified column. |col| is not made visible. - void AddColumn(const ui::TableColumn& col); - - // Returns true if the column with the specified id is known (either visible - // or not). - bool HasColumn(int id) const; - - // TODO(sky): rename to set_observer(). - void SetObserver(TableViewObserver* observer) { - table_view_observer_ = observer; - } - TableViewObserver* observer() const { return table_view_observer_; } - - const std::vector<VisibleColumn>& visible_columns() const { - return visible_columns_; - } - - // Sets the width of the column. |index| is in terms of |visible_columns_|. - void SetVisibleColumnWidth(int index, int width); - - // Toggles the sort order of the specified visible column index. - void ToggleSortOrder(int visible_column_index); - - const SortDescriptors& sort_descriptors() const { return sort_descriptors_; } - bool is_sorted() const { return !sort_descriptors_.empty(); } - - // Maps from the index in terms of the model to that of the view. - int ModelToView(int model_index) const; - - // Maps from the index in terms of the view to that of the model. - int ViewToModel(int view_index) const; - - int row_height() const { return row_height_; } - - // View overrides: - virtual void Layout() override; - virtual gfx::Size GetPreferredSize() const override; - virtual bool OnKeyPressed(const ui::KeyEvent& event) override; - virtual bool OnMousePressed(const ui::MouseEvent& event) override; - virtual void OnGestureEvent(ui::GestureEvent* event) override; - virtual bool GetTooltipText(const gfx::Point& p, - base::string16* tooltip) const override; - virtual bool GetTooltipTextOrigin(const gfx::Point& p, - gfx::Point* loc) const override; - - // ui::TableModelObserver overrides: - virtual void OnModelChanged() override; - virtual void OnItemsChanged(int start, int length) override; - virtual void OnItemsAdded(int start, int length) override; - virtual void OnItemsRemoved(int start, int length) override; - - protected: - // View overrides: - virtual gfx::Point GetKeyboardContextMenuLocation() override; - virtual void OnPaint(gfx::Canvas* canvas) override; - virtual void OnFocus() override; - virtual void OnBlur() override; - - private: - friend class TableViewTestHelper; - struct GroupSortHelper; - struct SortHelper; - - // Used during painting to determine the range of cells that need to be - // painted. - // NOTE: the row indices returned by this are in terms of the view and column - // indices in terms of |visible_columns_|. - struct VIEWS_EXPORT PaintRegion { - PaintRegion(); - ~PaintRegion(); - - int min_row; - int max_row; - int min_column; - int max_column; - }; - - // Used by AdvanceSelection() to determine the direction to change the - // selection. - enum AdvanceDirection { - ADVANCE_DECREMENT, - ADVANCE_INCREMENT, - }; - - // Invoked when the number of rows changes in some way. - void NumRowsChanged(); - - // Resets the sort descriptions. - void SetSortDescriptors(const SortDescriptors& sort_descriptors); - - // Does the actual sort and updates the mappings (|view_to_model_| and - // |model_to_view_|) appropriately. - void SortItemsAndUpdateMapping(); - - // Used to sort the two rows. Returns a value < 0, == 0 or > 0 indicating - // whether the row2 comes before row1, row2 is the same as row1 or row1 comes - // after row2. This invokes CompareValues on the model with the sorted column. - int CompareRows(int model_row1, int model_row2); - - // Returns the bounds of the specified row. - gfx::Rect GetRowBounds(int row) const; - - // Returns the bounds of the specified cell. |visible_column_index| indexes - // into |visible_columns_|. - gfx::Rect GetCellBounds(int row, int visible_column_index) const; - - // Adjusts |bounds| based on where the text should be painted. |bounds| comes - // from GetCellBounds() and |visible_column_index| is the corresponding column - // (in terms of |visible_columns_|). - void AdjustCellBoundsForText(int visible_column_index, - gfx::Rect* bounds) const; - - // Creates |header_| if necessary. - void CreateHeaderIfNecessary(); - - // Updates the |x| and |width| of each of the columns in |visible_columns_|. - void UpdateVisibleColumnSizes(); - - // Returns the cells that need to be painted for the specified region. - // |bounds| is in terms of |this|. - PaintRegion GetPaintRegion(const gfx::Rect& bounds) const; - - // Returns the bounds that need to be painted based on the clip set on - // |canvas|. - gfx::Rect GetPaintBounds(gfx::Canvas* canvas) const; - - // Invokes SchedulePaint() for the selected rows. - void SchedulePaintForSelection(); - - // Returns the TableColumn matching the specified id. - ui::TableColumn FindColumnByID(int id) const; - - // Sets the selection to the specified index (in terms of the view). - void SelectByViewIndex(int view_index); - - // Sets the selection model to |new_selection|. - void SetSelectionModel(const ui::ListSelectionModel& new_selection); - - // Advances the selection (from the active index) in the specified direction. - void AdvanceSelection(AdvanceDirection direction); - - // Sets |model| appropriately based on a event. - void ConfigureSelectionModelForEvent(const ui::LocatedEvent& event, - ui::ListSelectionModel* model) const; - - // Set the selection state of row at |view_index| to |select|, additionally - // any other rows in the GroupRange containing |view_index| are updated as - // well. This does not change the anchor or active index of |model|. - void SelectRowsInRangeFrom(int view_index, - bool select, - ui::ListSelectionModel* model) const; - - // Returns the range of the specified model index. If a TableGrouper has not - // been set this returns a group with a start of |model_index| and length of - // 1. - GroupRange GetGroupRange(int model_index) const; - - // Used by both GetTooltipText methods. Returns true if there is a tooltip and - // sets |tooltip| and/or |tooltip_origin| as appropriate, each of which may be - // NULL. - bool GetTooltipImpl(const gfx::Point& location, - base::string16* tooltip, - gfx::Point* tooltip_origin) const; - - ui::TableModel* model_; - - std::vector<ui::TableColumn> columns_; - - // The set of visible columns. The values of these point to |columns_|. This - // may contain a subset of |columns_|. - std::vector<VisibleColumn> visible_columns_; - - // The header. This is only created if more than one column is specified or - // the first column has a non-empty title. - TableHeader* header_; - - const TableTypes table_type_; - - const bool single_selection_; - - // TODO(sky): rename to observer_. - TableViewObserver* table_view_observer_; - - // The selection, in terms of the model. - ui::ListSelectionModel selection_model_; - - gfx::FontList font_list_; - - int row_height_; - - // Width of the ScrollView last time Layout() was invoked. Used to determine - // when we should invoke UpdateVisibleColumnSizes(). - int last_parent_width_; - - // The width we layout to. This may differ from |last_parent_width_|. - int layout_width_; - - // Current sort. - SortDescriptors sort_descriptors_; - - // Mappings used when sorted. - std::vector<int> view_to_model_; - std::vector<int> model_to_view_; - - scoped_ptr<TableViewRowBackgroundPainter> row_background_painter_; - - TableGrouper* grouper_; - - // True if in SetVisibleColumnWidth(). - bool in_set_visible_column_width_; - - DISALLOW_COPY_AND_ASSIGN(TableView); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_TABLE_TABLE_VIEW_VIEWS_H_
diff --git a/ui/views/controls/table/table_view_observer.h b/ui/views/controls/table/table_view_observer.h deleted file mode 100644 index 9cea260..0000000 --- a/ui/views/controls/table/table_view_observer.h +++ /dev/null
@@ -1,36 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_TABLE_TABLE_VIEW_OBSERVER_H_ -#define UI_VIEWS_CONTROLS_TABLE_TABLE_VIEW_OBSERVER_H_ - -#include "ui/events/keycodes/keyboard_codes.h" -#include "ui/views/views_export.h" - -namespace views { - -class TableView; -class TableView2; - -// TableViewObserver is notified about the TableView selection. -class VIEWS_EXPORT TableViewObserver { - public: - virtual ~TableViewObserver() {} - - // Invoked when the selection changes. - virtual void OnSelectionChanged() = 0; - - // Optional method invoked when the user double clicks on the table. - virtual void OnDoubleClick() {} - - // Optional method invoked when the user middle clicks on the table. - virtual void OnMiddleClick() {} - - // Optional method invoked when the user hits a key with the table in focus. - virtual void OnKeyDown(ui::KeyboardCode virtual_keycode) {} -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_TABLE_TABLE_VIEW_OBSERVER_H_
diff --git a/ui/views/controls/table/table_view_row_background_painter.h b/ui/views/controls/table/table_view_row_background_painter.h deleted file mode 100644 index f904131..0000000 --- a/ui/views/controls/table/table_view_row_background_painter.h +++ /dev/null
@@ -1,29 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_TABLE_TABLE_VIEW_ROW_BACKGROUND_PAINTER_H_ -#define UI_VIEWS_CONTROLS_TABLE_TABLE_VIEW_ROW_BACKGROUND_PAINTER_H_ - -#include "ui/views/views_export.h" - -namespace gfx { -class Canvas; -class Rect; -} - -namespace views { - -// TableViewRowBackgroundPainter is used to paint the background of a row in the -// table. -class VIEWS_EXPORT TableViewRowBackgroundPainter { - public: - virtual ~TableViewRowBackgroundPainter() {} - virtual void PaintRowBackground(int model_index, - const gfx::Rect& row_bounds, - gfx::Canvas* canvas) = 0; -}; - -} - -#endif // UI_VIEWS_CONTROLS_TABLE_TABLE_VIEW_ROW_BACKGROUND_PAINTER_H_
diff --git a/ui/views/controls/table/table_view_unittest.cc b/ui/views/controls/table/table_view_unittest.cc deleted file mode 100644 index 535c650..0000000 --- a/ui/views/controls/table/table_view_unittest.cc +++ /dev/null
@@ -1,845 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/table/table_view.h" - -#include "base/strings/string_number_conversions.h" -#include "base/strings/utf_string_conversions.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/views/controls/table/table_grouper.h" -#include "ui/views/controls/table/table_header.h" -#include "ui/views/controls/table/table_view_observer.h" - -// Put the tests in the views namespace to make it easier to declare them as -// friend classes. -namespace views { - -class TableViewTestHelper { - public: - explicit TableViewTestHelper(TableView* table) : table_(table) {} - - std::string GetPaintRegion(const gfx::Rect& bounds) { - TableView::PaintRegion region(table_->GetPaintRegion(bounds)); - return "rows=" + base::IntToString(region.min_row) + " " + - base::IntToString(region.max_row) + " cols=" + - base::IntToString(region.min_column) + " " + - base::IntToString(region.max_column); - } - - size_t visible_col_count() { - return table_->visible_columns().size(); - } - - TableHeader* header() { return table_->header_; } - - private: - TableView* table_; - - DISALLOW_COPY_AND_ASSIGN(TableViewTestHelper); -}; - -namespace { - -// TestTableModel2 ------------------------------------------------------------- - -// Trivial TableModel implementation that is backed by a vector of vectors. -// Provides methods for adding/removing/changing the contents that notify the -// observer appropriately. -// -// Initial contents are: -// 0, 1 -// 1, 1 -// 2, 2 -// 3, 0 -class TestTableModel2 : public ui::TableModel { - public: - TestTableModel2(); - - // Adds a new row at index |row| with values |c1_value| and |c2_value|. - void AddRow(int row, int c1_value, int c2_value); - - // Removes the row at index |row|. - void RemoveRow(int row); - - // Changes the values of the row at |row|. - void ChangeRow(int row, int c1_value, int c2_value); - - // ui::TableModel: - virtual int RowCount() override; - virtual base::string16 GetText(int row, int column_id) override; - virtual void SetObserver(ui::TableModelObserver* observer) override; - virtual int CompareValues(int row1, int row2, int column_id) override; - - private: - ui::TableModelObserver* observer_; - - // The data. - std::vector<std::vector<int> > rows_; - - DISALLOW_COPY_AND_ASSIGN(TestTableModel2); -}; - -TestTableModel2::TestTableModel2() : observer_(NULL) { - AddRow(0, 0, 1); - AddRow(1, 1, 1); - AddRow(2, 2, 2); - AddRow(3, 3, 0); -} - -void TestTableModel2::AddRow(int row, int c1_value, int c2_value) { - DCHECK(row >= 0 && row <= static_cast<int>(rows_.size())); - std::vector<int> new_row; - new_row.push_back(c1_value); - new_row.push_back(c2_value); - rows_.insert(rows_.begin() + row, new_row); - if (observer_) - observer_->OnItemsAdded(row, 1); -} -void TestTableModel2::RemoveRow(int row) { - DCHECK(row >= 0 && row <= static_cast<int>(rows_.size())); - rows_.erase(rows_.begin() + row); - if (observer_) - observer_->OnItemsRemoved(row, 1); -} - -void TestTableModel2::ChangeRow(int row, int c1_value, int c2_value) { - DCHECK(row >= 0 && row < static_cast<int>(rows_.size())); - rows_[row][0] = c1_value; - rows_[row][1] = c2_value; - if (observer_) - observer_->OnItemsChanged(row, 1); -} - -int TestTableModel2::RowCount() { - return static_cast<int>(rows_.size()); -} - -base::string16 TestTableModel2::GetText(int row, int column_id) { - return base::IntToString16(rows_[row][column_id]); -} - -void TestTableModel2::SetObserver(ui::TableModelObserver* observer) { - observer_ = observer; -} - -int TestTableModel2::CompareValues(int row1, int row2, int column_id) { - return rows_[row1][column_id] - rows_[row2][column_id]; -} - -// Returns the view to model mapping as a string. -std::string GetViewToModelAsString(TableView* table) { - std::string result; - for (int i = 0; i < table->RowCount(); ++i) { - if (i != 0) - result += " "; - result += base::IntToString(table->ViewToModel(i)); - } - return result; -} - -// Returns the model to view mapping as a string. -std::string GetModelToViewAsString(TableView* table) { - std::string result; - for (int i = 0; i < table->RowCount(); ++i) { - if (i != 0) - result += " "; - result += base::IntToString(table->ModelToView(i)); - } - return result; -} - -class TestTableView : public TableView { - public: - TestTableView(ui::TableModel* model, - const std::vector<ui::TableColumn>& columns) - : TableView(model, columns, TEXT_ONLY, false) { - } - - // View overrides: - virtual bool HasFocus() const override { - // Overriden so key processing works. - return true; - } - - private: - DISALLOW_COPY_AND_ASSIGN(TestTableView); -}; - -} // namespace - -class TableViewTest : public testing::Test { - public: - TableViewTest() : table_(NULL) {} - - virtual void SetUp() override { - model_.reset(new TestTableModel2); - std::vector<ui::TableColumn> columns(2); - columns[0].title = base::ASCIIToUTF16("Title Column 0"); - columns[0].sortable = true; - columns[1].title = base::ASCIIToUTF16("Title Column 1"); - columns[1].id = 1; - columns[1].sortable = true; - table_ = new TestTableView(model_.get(), columns); - parent_.reset(table_->CreateParentIfNecessary()); - parent_->SetBounds(0, 0, 10000, 10000); - parent_->Layout(); - helper_.reset(new TableViewTestHelper(table_)); - } - - void ClickOnRow(int row, int flags) { - const int y = row * table_->row_height(); - const ui::MouseEvent pressed(ui::ET_MOUSE_PRESSED, gfx::Point(0, y), - gfx::Point(0, y), - ui::EF_LEFT_MOUSE_BUTTON | flags, - ui::EF_LEFT_MOUSE_BUTTON); - table_->OnMousePressed(pressed); - } - - void TapOnRow(int row) { - const int y = row * table_->row_height(); - const ui::GestureEventDetails event_details(ui::ET_GESTURE_TAP); - ui::GestureEvent tap(0, y, 0, base::TimeDelta(), event_details); - table_->OnGestureEvent(&tap); - } - - // Returns the state of the selection model as a string. The format is: - // 'active=X anchor=X selection=X X X...'. - std::string SelectionStateAsString() const { - const ui::ListSelectionModel& model(table_->selection_model()); - std::string result = "active=" + base::IntToString(model.active()) + - " anchor=" + base::IntToString(model.anchor()) + - " selection="; - const ui::ListSelectionModel::SelectedIndices& selection( - model.selected_indices()); - for (size_t i = 0; i < selection.size(); ++i) { - if (i != 0) - result += " "; - result += base::IntToString(selection[i]); - } - return result; - } - - void PressKey(ui::KeyboardCode code) { - ui::KeyEvent event(ui::ET_KEY_PRESSED, code, ui::EF_NONE); - table_->OnKeyPressed(event); - } - - protected: - scoped_ptr<TestTableModel2> model_; - - // Owned by |parent_|. - TableView* table_; - - scoped_ptr<TableViewTestHelper> helper_; - - private: - scoped_ptr<View> parent_; - - DISALLOW_COPY_AND_ASSIGN(TableViewTest); -}; - -// Verifies GetPaintRegion. -TEST_F(TableViewTest, GetPaintRegion) { - // Two columns should be visible. - EXPECT_EQ(2u, helper_->visible_col_count()); - - EXPECT_EQ("rows=0 4 cols=0 2", helper_->GetPaintRegion(table_->bounds())); - EXPECT_EQ("rows=0 4 cols=0 1", - helper_->GetPaintRegion(gfx::Rect(0, 0, 1, table_->height()))); -} - -// Verifies SetColumnVisibility(). -TEST_F(TableViewTest, ColumnVisibility) { - // Two columns should be visible. - EXPECT_EQ(2u, helper_->visible_col_count()); - - // Should do nothing (column already visible). - table_->SetColumnVisibility(0, true); - EXPECT_EQ(2u, helper_->visible_col_count()); - - // Hide the first column. - table_->SetColumnVisibility(0, false); - ASSERT_EQ(1u, helper_->visible_col_count()); - EXPECT_EQ(1, table_->visible_columns()[0].column.id); - EXPECT_EQ("rows=0 4 cols=0 1", helper_->GetPaintRegion(table_->bounds())); - - // Hide the second column. - table_->SetColumnVisibility(1, false); - EXPECT_EQ(0u, helper_->visible_col_count()); - - // Show the second column. - table_->SetColumnVisibility(1, true); - ASSERT_EQ(1u, helper_->visible_col_count()); - EXPECT_EQ(1, table_->visible_columns()[0].column.id); - EXPECT_EQ("rows=0 4 cols=0 1", helper_->GetPaintRegion(table_->bounds())); - - // Show the first column. - table_->SetColumnVisibility(0, true); - ASSERT_EQ(2u, helper_->visible_col_count()); - EXPECT_EQ(1, table_->visible_columns()[0].column.id); - EXPECT_EQ(0, table_->visible_columns()[1].column.id); - EXPECT_EQ("rows=0 4 cols=0 2", helper_->GetPaintRegion(table_->bounds())); -} - -// Verifies resizing a column works. -TEST_F(TableViewTest, Resize) { - const int x = table_->visible_columns()[0].width; - EXPECT_NE(0, x); - // Drag the mouse 1 pixel to the left. - const ui::MouseEvent pressed(ui::ET_MOUSE_PRESSED, gfx::Point(x, 0), - gfx::Point(x, 0), ui::EF_LEFT_MOUSE_BUTTON, - ui::EF_LEFT_MOUSE_BUTTON); - helper_->header()->OnMousePressed(pressed); - const ui::MouseEvent dragged(ui::ET_MOUSE_DRAGGED, gfx::Point(x - 1, 0), - gfx::Point(x - 1, 0), ui::EF_LEFT_MOUSE_BUTTON, - 0); - helper_->header()->OnMouseDragged(dragged); - - // This should shrink the first column and pull the second column in. - EXPECT_EQ(x - 1, table_->visible_columns()[0].width); - EXPECT_EQ(x - 1, table_->visible_columns()[1].x); -} - -// Verifies resizing a column works with a gesture. -TEST_F(TableViewTest, ResizeViaGesture) { - const int x = table_->visible_columns()[0].width; - EXPECT_NE(0, x); - // Drag the mouse 1 pixel to the left. - ui::GestureEvent scroll_begin( - x, - 0, - 0, - base::TimeDelta(), - ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_BEGIN)); - helper_->header()->OnGestureEvent(&scroll_begin); - ui::GestureEvent scroll_update( - x - 1, - 0, - 0, - base::TimeDelta(), - ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_UPDATE)); - helper_->header()->OnGestureEvent(&scroll_update); - - // This should shrink the first column and pull the second column in. - EXPECT_EQ(x - 1, table_->visible_columns()[0].width); - EXPECT_EQ(x - 1, table_->visible_columns()[1].x); -} - -// Assertions for table sorting. -TEST_F(TableViewTest, Sort) { - // Toggle the sort order of the first column, shouldn't change anything. - table_->ToggleSortOrder(0); - ASSERT_EQ(1u, table_->sort_descriptors().size()); - EXPECT_EQ(0, table_->sort_descriptors()[0].column_id); - EXPECT_TRUE(table_->sort_descriptors()[0].ascending); - EXPECT_EQ("0 1 2 3", GetViewToModelAsString(table_)); - EXPECT_EQ("0 1 2 3", GetModelToViewAsString(table_)); - - // Invert the sort (first column descending). - table_->ToggleSortOrder(0); - ASSERT_EQ(1u, table_->sort_descriptors().size()); - EXPECT_EQ(0, table_->sort_descriptors()[0].column_id); - EXPECT_FALSE(table_->sort_descriptors()[0].ascending); - EXPECT_EQ("3 2 1 0", GetViewToModelAsString(table_)); - EXPECT_EQ("3 2 1 0", GetModelToViewAsString(table_)); - - // Change cell 0x3 to -1, meaning we have 0, 1, 2, -1 (in the first column). - model_->ChangeRow(3, -1, 0); - ASSERT_EQ(1u, table_->sort_descriptors().size()); - EXPECT_EQ(0, table_->sort_descriptors()[0].column_id); - EXPECT_FALSE(table_->sort_descriptors()[0].ascending); - EXPECT_EQ("2 1 0 3", GetViewToModelAsString(table_)); - EXPECT_EQ("2 1 0 3", GetModelToViewAsString(table_)); - - // Invert sort again (first column ascending). - table_->ToggleSortOrder(0); - ASSERT_EQ(1u, table_->sort_descriptors().size()); - EXPECT_EQ(0, table_->sort_descriptors()[0].column_id); - EXPECT_TRUE(table_->sort_descriptors()[0].ascending); - EXPECT_EQ("3 0 1 2", GetViewToModelAsString(table_)); - EXPECT_EQ("1 2 3 0", GetModelToViewAsString(table_)); - - // Add a row so that model has 0, 3, 1, 2, -1. - model_->AddRow(1, 3, 4); - ASSERT_EQ(1u, table_->sort_descriptors().size()); - EXPECT_EQ(0, table_->sort_descriptors()[0].column_id); - EXPECT_TRUE(table_->sort_descriptors()[0].ascending); - EXPECT_EQ("4 0 2 3 1", GetViewToModelAsString(table_)); - EXPECT_EQ("1 4 2 3 0", GetModelToViewAsString(table_)); - - // Delete the first row, ending up with 3, 1, 2, -1. - model_->RemoveRow(0); - ASSERT_EQ(1u, table_->sort_descriptors().size()); - EXPECT_EQ(0, table_->sort_descriptors()[0].column_id); - EXPECT_TRUE(table_->sort_descriptors()[0].ascending); - EXPECT_EQ("3 1 2 0", GetViewToModelAsString(table_)); - EXPECT_EQ("3 1 2 0", GetModelToViewAsString(table_)); -} - -// Verfies clicking on the header sorts. -TEST_F(TableViewTest, SortOnMouse) { - EXPECT_TRUE(table_->sort_descriptors().empty()); - - const int x = table_->visible_columns()[0].width / 2; - EXPECT_NE(0, x); - // Press and release the mouse. - const ui::MouseEvent pressed(ui::ET_MOUSE_PRESSED, gfx::Point(x, 0), - gfx::Point(x, 0), ui::EF_LEFT_MOUSE_BUTTON, - ui::EF_LEFT_MOUSE_BUTTON); - // The header must return true, else it won't normally get the release. - EXPECT_TRUE(helper_->header()->OnMousePressed(pressed)); - const ui::MouseEvent release(ui::ET_MOUSE_RELEASED, gfx::Point(x, 0), - gfx::Point(x, 0), ui::EF_LEFT_MOUSE_BUTTON, - ui::EF_LEFT_MOUSE_BUTTON); - helper_->header()->OnMouseReleased(release); - - ASSERT_EQ(1u, table_->sort_descriptors().size()); - EXPECT_EQ(0, table_->sort_descriptors()[0].column_id); - EXPECT_TRUE(table_->sort_descriptors()[0].ascending); -} - -namespace { - -class TableGrouperImpl : public TableGrouper { - public: - TableGrouperImpl() {} - - void SetRanges(const std::vector<int>& ranges) { - ranges_ = ranges; - } - - // TableGrouper overrides: - virtual void GetGroupRange(int model_index, GroupRange* range) override { - int offset = 0; - size_t range_index = 0; - for (; range_index < ranges_.size() && offset < model_index; ++range_index) - offset += ranges_[range_index]; - - if (offset == model_index) { - range->start = model_index; - range->length = ranges_[range_index]; - } else { - range->start = offset - ranges_[range_index - 1]; - range->length = ranges_[range_index - 1]; - } - } - - private: - std::vector<int> ranges_; - - DISALLOW_COPY_AND_ASSIGN(TableGrouperImpl); -}; - -} // namespace - -// Assertions around grouping. -TEST_F(TableViewTest, Grouping) { - // Configure the grouper so that there are two groups: - // A 0 - // 1 - // B 2 - // 3 - TableGrouperImpl grouper; - std::vector<int> ranges; - ranges.push_back(2); - ranges.push_back(2); - grouper.SetRanges(ranges); - table_->SetGrouper(&grouper); - - // Toggle the sort order of the first column, shouldn't change anything. - table_->ToggleSortOrder(0); - ASSERT_EQ(1u, table_->sort_descriptors().size()); - EXPECT_EQ(0, table_->sort_descriptors()[0].column_id); - EXPECT_TRUE(table_->sort_descriptors()[0].ascending); - EXPECT_EQ("0 1 2 3", GetViewToModelAsString(table_)); - EXPECT_EQ("0 1 2 3", GetModelToViewAsString(table_)); - - // Sort descending, resulting: - // B 2 - // 3 - // A 0 - // 1 - table_->ToggleSortOrder(0); - ASSERT_EQ(1u, table_->sort_descriptors().size()); - EXPECT_EQ(0, table_->sort_descriptors()[0].column_id); - EXPECT_FALSE(table_->sort_descriptors()[0].ascending); - EXPECT_EQ("2 3 0 1", GetViewToModelAsString(table_)); - EXPECT_EQ("2 3 0 1", GetModelToViewAsString(table_)); - - // Change the entry in the 4th row to -1. The model now becomes: - // A 0 - // 1 - // B 2 - // -1 - // Since the first entry in the range didn't change the sort isn't impacted. - model_->ChangeRow(3, -1, 0); - ASSERT_EQ(1u, table_->sort_descriptors().size()); - EXPECT_EQ(0, table_->sort_descriptors()[0].column_id); - EXPECT_FALSE(table_->sort_descriptors()[0].ascending); - EXPECT_EQ("2 3 0 1", GetViewToModelAsString(table_)); - EXPECT_EQ("2 3 0 1", GetModelToViewAsString(table_)); - - // Change the entry in the 3rd row to -1. The model now becomes: - // A 0 - // 1 - // B -1 - // -1 - model_->ChangeRow(2, -1, 0); - ASSERT_EQ(1u, table_->sort_descriptors().size()); - EXPECT_EQ(0, table_->sort_descriptors()[0].column_id); - EXPECT_FALSE(table_->sort_descriptors()[0].ascending); - EXPECT_EQ("0 1 2 3", GetViewToModelAsString(table_)); - EXPECT_EQ("0 1 2 3", GetModelToViewAsString(table_)); - - // Toggle to ascending sort. - table_->ToggleSortOrder(0); - ASSERT_EQ(1u, table_->sort_descriptors().size()); - EXPECT_EQ(0, table_->sort_descriptors()[0].column_id); - EXPECT_TRUE(table_->sort_descriptors()[0].ascending); - EXPECT_EQ("2 3 0 1", GetViewToModelAsString(table_)); - EXPECT_EQ("2 3 0 1", GetModelToViewAsString(table_)); -} - -namespace { - -class TableViewObserverImpl : public TableViewObserver { - public: - TableViewObserverImpl() : selection_changed_count_(0) {} - - int GetChangedCountAndClear() { - const int count = selection_changed_count_; - selection_changed_count_ = 0; - return count; - } - - // TableViewObserver overrides: - virtual void OnSelectionChanged() override { - selection_changed_count_++; - } - - private: - int selection_changed_count_; - - DISALLOW_COPY_AND_ASSIGN(TableViewObserverImpl); -}; - -} // namespace - -// Assertions around changing the selection. -TEST_F(TableViewTest, Selection) { - TableViewObserverImpl observer; - table_->SetObserver(&observer); - - // Initially no selection. - EXPECT_EQ("active=-1 anchor=-1 selection=", SelectionStateAsString()); - - // Select the last row. - table_->Select(3); - EXPECT_EQ(1, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=3 anchor=3 selection=3", SelectionStateAsString()); - - // Change sort, shouldn't notify of change (toggle twice so that order - // actually changes). - table_->ToggleSortOrder(0); - table_->ToggleSortOrder(0); - EXPECT_EQ(0, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=3 anchor=3 selection=3", SelectionStateAsString()); - - // Remove the selected row, this should notify of a change and update the - // selection. - model_->RemoveRow(3); - EXPECT_EQ(1, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=2 anchor=2 selection=2", SelectionStateAsString()); - - // Insert a row, since the selection in terms of the original model hasn't - // changed the observer is not notified. - model_->AddRow(0, 1, 2); - EXPECT_EQ(0, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=3 anchor=3 selection=3", SelectionStateAsString()); - - table_->SetObserver(NULL); -} - -// Verifies selection works by way of a gesture. -TEST_F(TableViewTest, SelectOnTap) { - // Initially no selection. - EXPECT_EQ("active=-1 anchor=-1 selection=", SelectionStateAsString()); - - TableViewObserverImpl observer; - table_->SetObserver(&observer); - - // Click on the first row, should select it. - TapOnRow(0); - EXPECT_EQ(1, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=0 anchor=0 selection=0", SelectionStateAsString()); - - table_->SetObserver(NULL); -} - -// Verifies up/down correctly navigates through groups. -TEST_F(TableViewTest, KeyUpDown) { - // Configure the grouper so that there are three groups: - // A 0 - // 1 - // B 5 - // C 2 - // 3 - model_->AddRow(2, 5, 0); - TableGrouperImpl grouper; - std::vector<int> ranges; - ranges.push_back(2); - ranges.push_back(1); - ranges.push_back(2); - grouper.SetRanges(ranges); - table_->SetGrouper(&grouper); - - TableViewObserverImpl observer; - table_->SetObserver(&observer); - - // Initially no selection. - EXPECT_EQ("active=-1 anchor=-1 selection=", SelectionStateAsString()); - - PressKey(ui::VKEY_DOWN); - EXPECT_EQ(1, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=0 anchor=0 selection=0 1", SelectionStateAsString()); - - PressKey(ui::VKEY_DOWN); - EXPECT_EQ(1, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=1 anchor=1 selection=0 1", SelectionStateAsString()); - - PressKey(ui::VKEY_DOWN); - EXPECT_EQ(1, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=2 anchor=2 selection=2", SelectionStateAsString()); - - PressKey(ui::VKEY_DOWN); - EXPECT_EQ(1, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=3 anchor=3 selection=3 4", SelectionStateAsString()); - - PressKey(ui::VKEY_DOWN); - EXPECT_EQ(1, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=4 anchor=4 selection=3 4", SelectionStateAsString()); - - PressKey(ui::VKEY_DOWN); - EXPECT_EQ(0, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=4 anchor=4 selection=3 4", SelectionStateAsString()); - - PressKey(ui::VKEY_UP); - EXPECT_EQ(1, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=3 anchor=3 selection=3 4", SelectionStateAsString()); - - PressKey(ui::VKEY_UP); - EXPECT_EQ(1, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=2 anchor=2 selection=2", SelectionStateAsString()); - - PressKey(ui::VKEY_UP); - EXPECT_EQ(1, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=1 anchor=1 selection=0 1", SelectionStateAsString()); - - PressKey(ui::VKEY_UP); - EXPECT_EQ(1, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=0 anchor=0 selection=0 1", SelectionStateAsString()); - - PressKey(ui::VKEY_UP); - EXPECT_EQ(0, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=0 anchor=0 selection=0 1", SelectionStateAsString()); - - // Sort the table descending by column 1, view now looks like: - // B 5 model: 2 - // C 2 3 - // 3 4 - // A 0 0 - // 1 1 - table_->ToggleSortOrder(0); - table_->ToggleSortOrder(0); - - EXPECT_EQ("2 3 4 0 1", GetViewToModelAsString(table_)); - - table_->Select(-1); - EXPECT_EQ("active=-1 anchor=-1 selection=", SelectionStateAsString()); - - observer.GetChangedCountAndClear(); - // Up with nothing selected selects the first row. - PressKey(ui::VKEY_UP); - EXPECT_EQ(1, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=2 anchor=2 selection=2", SelectionStateAsString()); - - PressKey(ui::VKEY_DOWN); - EXPECT_EQ(1, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=3 anchor=3 selection=3 4", SelectionStateAsString()); - - PressKey(ui::VKEY_DOWN); - EXPECT_EQ(1, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=4 anchor=4 selection=3 4", SelectionStateAsString()); - - PressKey(ui::VKEY_DOWN); - EXPECT_EQ(1, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=0 anchor=0 selection=0 1", SelectionStateAsString()); - - PressKey(ui::VKEY_DOWN); - EXPECT_EQ(1, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=1 anchor=1 selection=0 1", SelectionStateAsString()); - - PressKey(ui::VKEY_DOWN); - EXPECT_EQ(0, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=1 anchor=1 selection=0 1", SelectionStateAsString()); - - PressKey(ui::VKEY_UP); - EXPECT_EQ(1, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=0 anchor=0 selection=0 1", SelectionStateAsString()); - - PressKey(ui::VKEY_UP); - EXPECT_EQ(1, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=4 anchor=4 selection=3 4", SelectionStateAsString()); - - PressKey(ui::VKEY_UP); - EXPECT_EQ(1, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=3 anchor=3 selection=3 4", SelectionStateAsString()); - - PressKey(ui::VKEY_UP); - EXPECT_EQ(1, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=2 anchor=2 selection=2", SelectionStateAsString()); - - PressKey(ui::VKEY_UP); - EXPECT_EQ(0, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=2 anchor=2 selection=2", SelectionStateAsString()); - - table_->SetObserver(NULL); -} - -// Verifies home/end do the right thing. -TEST_F(TableViewTest, HomeEnd) { - // Configure the grouper so that there are three groups: - // A 0 - // 1 - // B 5 - // C 2 - // 3 - model_->AddRow(2, 5, 0); - TableGrouperImpl grouper; - std::vector<int> ranges; - ranges.push_back(2); - ranges.push_back(1); - ranges.push_back(2); - grouper.SetRanges(ranges); - table_->SetGrouper(&grouper); - - TableViewObserverImpl observer; - table_->SetObserver(&observer); - - // Initially no selection. - EXPECT_EQ("active=-1 anchor=-1 selection=", SelectionStateAsString()); - - PressKey(ui::VKEY_HOME); - EXPECT_EQ(1, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=0 anchor=0 selection=0 1", SelectionStateAsString()); - - PressKey(ui::VKEY_END); - EXPECT_EQ(1, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=4 anchor=4 selection=3 4", SelectionStateAsString()); - - table_->SetObserver(NULL); -} - -// Verifies multiple selection gestures work (control-click, shift-click ...). -TEST_F(TableViewTest, Multiselection) { - // Configure the grouper so that there are three groups: - // A 0 - // 1 - // B 5 - // C 2 - // 3 - model_->AddRow(2, 5, 0); - TableGrouperImpl grouper; - std::vector<int> ranges; - ranges.push_back(2); - ranges.push_back(1); - ranges.push_back(2); - grouper.SetRanges(ranges); - table_->SetGrouper(&grouper); - - // Initially no selection. - EXPECT_EQ("active=-1 anchor=-1 selection=", SelectionStateAsString()); - - TableViewObserverImpl observer; - table_->SetObserver(&observer); - - // Click on the first row, should select it and the second row. - ClickOnRow(0, 0); - EXPECT_EQ(1, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=0 anchor=0 selection=0 1", SelectionStateAsString()); - - // Click on the last row, should select it and the row before it. - ClickOnRow(4, 0); - EXPECT_EQ(1, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=4 anchor=4 selection=3 4", SelectionStateAsString()); - - // Shift click on the third row, should extend selection to it. - ClickOnRow(2, ui::EF_SHIFT_DOWN); - EXPECT_EQ(1, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=2 anchor=4 selection=2 3 4", SelectionStateAsString()); - - // Control click on third row, should toggle it. - ClickOnRow(2, ui::EF_CONTROL_DOWN); - EXPECT_EQ(1, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=2 anchor=2 selection=3 4", SelectionStateAsString()); - - // Control-shift click on second row, should extend selection to it. - ClickOnRow(1, ui::EF_CONTROL_DOWN | ui::EF_SHIFT_DOWN); - EXPECT_EQ(1, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=1 anchor=2 selection=0 1 2 3 4", SelectionStateAsString()); - - // Click on last row again. - ClickOnRow(4, 0); - EXPECT_EQ(1, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=4 anchor=4 selection=3 4", SelectionStateAsString()); - - table_->SetObserver(NULL); -} - -// Verifies multiple selection gestures work when sorted. -TEST_F(TableViewTest, MultiselectionWithSort) { - // Configure the grouper so that there are three groups: - // A 0 - // 1 - // B 5 - // C 2 - // 3 - model_->AddRow(2, 5, 0); - TableGrouperImpl grouper; - std::vector<int> ranges; - ranges.push_back(2); - ranges.push_back(1); - ranges.push_back(2); - grouper.SetRanges(ranges); - table_->SetGrouper(&grouper); - - // Sort the table descending by column 1, view now looks like: - // B 5 model: 2 - // C 2 3 - // 3 4 - // A 0 0 - // 1 1 - table_->ToggleSortOrder(0); - table_->ToggleSortOrder(0); - - // Initially no selection. - EXPECT_EQ("active=-1 anchor=-1 selection=", SelectionStateAsString()); - - TableViewObserverImpl observer; - table_->SetObserver(&observer); - - // Click on the third row, should select it and the second row. - ClickOnRow(2, 0); - EXPECT_EQ(1, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=4 anchor=4 selection=3 4", SelectionStateAsString()); - - // Extend selection to first row. - ClickOnRow(0, ui::EF_SHIFT_DOWN); - EXPECT_EQ(1, observer.GetChangedCountAndClear()); - EXPECT_EQ("active=2 anchor=4 selection=2 3 4", SelectionStateAsString()); - - table_->SetObserver(NULL); -} - -} // namespace views
diff --git a/ui/views/controls/table/test_table_model.cc b/ui/views/controls/table/test_table_model.cc deleted file mode 100644 index fde158e..0000000 --- a/ui/views/controls/table/test_table_model.cc +++ /dev/null
@@ -1,38 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/table/test_table_model.h" - -#include "base/strings/string_number_conversions.h" -#include "base/strings/utf_string_conversions.h" -#include "third_party/skia/include/core/SkBitmap.h" -#include "ui/base/models/table_model_observer.h" -#include "ui/gfx/image/image_skia.h" - -TestTableModel::TestTableModel(int row_count) - : row_count_(row_count), - observer_(NULL) { -} - -TestTableModel::~TestTableModel() { -} - -int TestTableModel::RowCount() { - return row_count_; -} - -base::string16 TestTableModel::GetText(int row, int column_id) { - return base::ASCIIToUTF16(base::IntToString(row) + "x" + - base::IntToString(column_id)); -} - -gfx::ImageSkia TestTableModel::GetIcon(int row) { - SkBitmap bitmap; - bitmap.setInfo(SkImageInfo::MakeN32Premul(16, 16)); - return gfx::ImageSkia::CreateFrom1xBitmap(bitmap); -} - -void TestTableModel::SetObserver(ui::TableModelObserver* observer) { - observer_ = observer; -}
diff --git a/ui/views/controls/table/test_table_model.h b/ui/views/controls/table/test_table_model.h deleted file mode 100644 index a06db77..0000000 --- a/ui/views/controls/table/test_table_model.h +++ /dev/null
@@ -1,29 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_TABLE_TEST_TABLE_MODEL_H_ -#define UI_VIEWS_CONTROLS_TABLE_TEST_TABLE_MODEL_H_ - -#include "base/compiler_specific.h" -#include "ui/base/models/table_model.h" - -class TestTableModel : public ui::TableModel { - public: - explicit TestTableModel(int row_count); - virtual ~TestTableModel(); - - // ui::TableModel overrides: - virtual int RowCount() override; - virtual base::string16 GetText(int row, int column_id) override; - virtual gfx::ImageSkia GetIcon(int row) override; - virtual void SetObserver(ui::TableModelObserver* observer) override; - - private: - int row_count_; - ui::TableModelObserver* observer_; - - DISALLOW_COPY_AND_ASSIGN(TestTableModel); -}; - -#endif // UI_VIEWS_CONTROLS_TABLE_TEST_TABLE_MODEL_H_
diff --git a/ui/views/controls/textfield/OWNERS b/ui/views/controls/textfield/OWNERS deleted file mode 100644 index b1b0e2d..0000000 --- a/ui/views/controls/textfield/OWNERS +++ /dev/null
@@ -1,3 +0,0 @@ -msw@chromium.org -oshima@chromium.org -pkasting@chromium.org
diff --git a/ui/views/controls/textfield/textfield.cc b/ui/views/controls/textfield/textfield.cc deleted file mode 100644 index cd4c7e4..0000000 --- a/ui/views/controls/textfield/textfield.cc +++ /dev/null
@@ -1,1823 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/textfield/textfield.h" - -#include <string> - -#include "base/debug/trace_event.h" -#include "ui/accessibility/ax_view_state.h" -#include "ui/base/clipboard/scoped_clipboard_writer.h" -#include "ui/base/cursor/cursor.h" -#include "ui/base/dragdrop/drag_drop_types.h" -#include "ui/base/dragdrop/drag_utils.h" -#include "ui/base/ui_base_switches_util.h" -#include "ui/compositor/scoped_animation_duration_scale_mode.h" -#include "ui/events/event.h" -#include "ui/events/keycodes/keyboard_codes.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/display.h" -#include "ui/gfx/insets.h" -#include "ui/gfx/screen.h" -#include "ui/native_theme/native_theme.h" -#include "ui/strings/grit/ui_strings.h" -#include "ui/views/background.h" -#include "ui/views/controls/focusable_border.h" -#include "ui/views/controls/label.h" -#include "ui/views/controls/menu/menu_runner.h" -#include "ui/views/controls/native/native_view_host.h" -#include "ui/views/controls/textfield/textfield_controller.h" -#include "ui/views/drag_utils.h" -#include "ui/views/ime/input_method.h" -#include "ui/views/metrics.h" -#include "ui/views/native_cursor.h" -#include "ui/views/painter.h" -#include "ui/views/views_delegate.h" -#include "ui/views/widget/widget.h" - -#if defined(OS_WIN) -#include "base/win/win_util.h" -#endif - -#if defined(OS_LINUX) && !defined(OS_CHROMEOS) -#include "base/strings/utf_string_conversions.h" -#include "ui/events/linux/text_edit_command_auralinux.h" -#include "ui/events/linux/text_edit_key_bindings_delegate_auralinux.h" -#endif - -namespace views { - -namespace { - -// Default placeholder text color. -const SkColor kDefaultPlaceholderTextColor = SK_ColorLTGRAY; - -const int kNoCommand = 0; - -void ConvertRectToScreen(const View* src, gfx::Rect* r) { - DCHECK(src); - - gfx::Point new_origin = r->origin(); - View::ConvertPointToScreen(src, &new_origin); - r->set_origin(new_origin); -} - -// Get the drag selection timer delay, respecting animation scaling for testing. -int GetDragSelectionDelay() { - switch (ui::ScopedAnimationDurationScaleMode::duration_scale_mode()) { - case ui::ScopedAnimationDurationScaleMode::NORMAL_DURATION: return 100; - case ui::ScopedAnimationDurationScaleMode::FAST_DURATION: return 25; - case ui::ScopedAnimationDurationScaleMode::SLOW_DURATION: return 400; - case ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION: return 1; - case ui::ScopedAnimationDurationScaleMode::ZERO_DURATION: return 0; - } - return 100; -} - -// Get the default command for a given key |event| and selection state. -int GetCommandForKeyEvent(const ui::KeyEvent& event, bool has_selection) { - if (event.type() != ui::ET_KEY_PRESSED || event.IsUnicodeKeyCode()) - return kNoCommand; - - const bool shift = event.IsShiftDown(); - const bool control = event.IsControlDown(); - const bool alt = event.IsAltDown() || event.IsAltGrDown(); - switch (event.key_code()) { - case ui::VKEY_Z: - if (control && !shift && !alt) - return IDS_APP_UNDO; - return (control && shift && !alt) ? IDS_APP_REDO : kNoCommand; - case ui::VKEY_Y: - return (control && !alt) ? IDS_APP_REDO : kNoCommand; - case ui::VKEY_A: - return (control && !alt) ? IDS_APP_SELECT_ALL : kNoCommand; - case ui::VKEY_X: - return (control && !alt) ? IDS_APP_CUT : kNoCommand; - case ui::VKEY_C: - return (control && !alt) ? IDS_APP_COPY : kNoCommand; - case ui::VKEY_V: - return (control && !alt) ? IDS_APP_PASTE : kNoCommand; - case ui::VKEY_RIGHT: - // Ignore alt+right, which may be a browser navigation shortcut. - if (alt) - return kNoCommand; - if (!shift) - return control ? IDS_MOVE_WORD_RIGHT : IDS_MOVE_RIGHT; - return control ? IDS_MOVE_WORD_RIGHT_AND_MODIFY_SELECTION : - IDS_MOVE_RIGHT_AND_MODIFY_SELECTION; - case ui::VKEY_LEFT: - // Ignore alt+left, which may be a browser navigation shortcut. - if (alt) - return kNoCommand; - if (!shift) - return control ? IDS_MOVE_WORD_LEFT : IDS_MOVE_LEFT; - return control ? IDS_MOVE_WORD_LEFT_AND_MODIFY_SELECTION : - IDS_MOVE_LEFT_AND_MODIFY_SELECTION; - case ui::VKEY_HOME: - return shift ? IDS_MOVE_TO_BEGINNING_OF_LINE_AND_MODIFY_SELECTION : - IDS_MOVE_TO_BEGINNING_OF_LINE; - case ui::VKEY_END: - return shift ? IDS_MOVE_TO_END_OF_LINE_AND_MODIFY_SELECTION : - IDS_MOVE_TO_END_OF_LINE; - case ui::VKEY_BACK: - if (!control || has_selection) - return IDS_DELETE_BACKWARD; -#if defined(OS_LINUX) - // Only erase by line break on Linux and ChromeOS. - if (shift) - return IDS_DELETE_TO_BEGINNING_OF_LINE; -#endif - return IDS_DELETE_WORD_BACKWARD; - case ui::VKEY_DELETE: - if (!control || has_selection) - return (shift && has_selection) ? IDS_APP_CUT : IDS_DELETE_FORWARD; -#if defined(OS_LINUX) - // Only erase by line break on Linux and ChromeOS. - if (shift) - return IDS_DELETE_TO_END_OF_LINE; -#endif - return IDS_DELETE_WORD_FORWARD; - case ui::VKEY_INSERT: - if (control && !shift) - return IDS_APP_COPY; - return (shift && !control) ? IDS_APP_PASTE : kNoCommand; - default: - return kNoCommand; - } -} - -#if defined(OS_LINUX) && !defined(OS_CHROMEOS) -// Convert a custom text edit |command| to the equivalent views command ID. -int GetViewsCommand(const ui::TextEditCommandAuraLinux& command, bool rtl) { - const bool select = command.extend_selection(); - switch (command.command_id()) { - case ui::TextEditCommandAuraLinux::COPY: - return IDS_APP_COPY; - case ui::TextEditCommandAuraLinux::CUT: - return IDS_APP_CUT; - case ui::TextEditCommandAuraLinux::DELETE_BACKWARD: - return IDS_DELETE_BACKWARD; - case ui::TextEditCommandAuraLinux::DELETE_FORWARD: - return IDS_DELETE_FORWARD; - case ui::TextEditCommandAuraLinux::DELETE_TO_BEGINING_OF_LINE: - case ui::TextEditCommandAuraLinux::DELETE_TO_BEGINING_OF_PARAGRAPH: - return IDS_DELETE_TO_BEGINNING_OF_LINE; - case ui::TextEditCommandAuraLinux::DELETE_TO_END_OF_LINE: - case ui::TextEditCommandAuraLinux::DELETE_TO_END_OF_PARAGRAPH: - return IDS_DELETE_TO_END_OF_LINE; - case ui::TextEditCommandAuraLinux::DELETE_WORD_BACKWARD: - return IDS_DELETE_WORD_BACKWARD; - case ui::TextEditCommandAuraLinux::DELETE_WORD_FORWARD: - return IDS_DELETE_WORD_FORWARD; - case ui::TextEditCommandAuraLinux::INSERT_TEXT: - return kNoCommand; - case ui::TextEditCommandAuraLinux::MOVE_BACKWARD: - if (rtl) - return select ? IDS_MOVE_RIGHT_AND_MODIFY_SELECTION : IDS_MOVE_RIGHT; - return select ? IDS_MOVE_LEFT_AND_MODIFY_SELECTION : IDS_MOVE_LEFT; - case ui::TextEditCommandAuraLinux::MOVE_DOWN: - return IDS_MOVE_DOWN; - case ui::TextEditCommandAuraLinux::MOVE_FORWARD: - if (rtl) - return select ? IDS_MOVE_LEFT_AND_MODIFY_SELECTION : IDS_MOVE_LEFT; - return select ? IDS_MOVE_RIGHT_AND_MODIFY_SELECTION : IDS_MOVE_RIGHT; - case ui::TextEditCommandAuraLinux::MOVE_LEFT: - return select ? IDS_MOVE_LEFT_AND_MODIFY_SELECTION : IDS_MOVE_LEFT; - case ui::TextEditCommandAuraLinux::MOVE_PAGE_DOWN: - case ui::TextEditCommandAuraLinux::MOVE_PAGE_UP: - return kNoCommand; - case ui::TextEditCommandAuraLinux::MOVE_RIGHT: - return select ? IDS_MOVE_RIGHT_AND_MODIFY_SELECTION : IDS_MOVE_RIGHT; - case ui::TextEditCommandAuraLinux::MOVE_TO_BEGINING_OF_DOCUMENT: - case ui::TextEditCommandAuraLinux::MOVE_TO_BEGINING_OF_LINE: - case ui::TextEditCommandAuraLinux::MOVE_TO_BEGINING_OF_PARAGRAPH: - return select ? IDS_MOVE_TO_BEGINNING_OF_LINE_AND_MODIFY_SELECTION : - IDS_MOVE_TO_BEGINNING_OF_LINE; - case ui::TextEditCommandAuraLinux::MOVE_TO_END_OF_DOCUMENT: - case ui::TextEditCommandAuraLinux::MOVE_TO_END_OF_LINE: - case ui::TextEditCommandAuraLinux::MOVE_TO_END_OF_PARAGRAPH: - return select ? IDS_MOVE_TO_END_OF_LINE_AND_MODIFY_SELECTION : - IDS_MOVE_TO_END_OF_LINE; - case ui::TextEditCommandAuraLinux::MOVE_UP: - return IDS_MOVE_UP; - case ui::TextEditCommandAuraLinux::MOVE_WORD_BACKWARD: - if (rtl) { - return select ? IDS_MOVE_WORD_RIGHT_AND_MODIFY_SELECTION : - IDS_MOVE_WORD_RIGHT; - } - return select ? IDS_MOVE_WORD_LEFT_AND_MODIFY_SELECTION : - IDS_MOVE_WORD_LEFT; - case ui::TextEditCommandAuraLinux::MOVE_WORD_FORWARD: - if (rtl) { - return select ? IDS_MOVE_WORD_LEFT_AND_MODIFY_SELECTION : - IDS_MOVE_WORD_LEFT; - } - return select ? IDS_MOVE_WORD_RIGHT_AND_MODIFY_SELECTION : - IDS_MOVE_WORD_RIGHT; - case ui::TextEditCommandAuraLinux::MOVE_WORD_LEFT: - return select ? IDS_MOVE_WORD_LEFT_AND_MODIFY_SELECTION : - IDS_MOVE_WORD_LEFT; - case ui::TextEditCommandAuraLinux::MOVE_WORD_RIGHT: - return select ? IDS_MOVE_WORD_RIGHT_AND_MODIFY_SELECTION : - IDS_MOVE_WORD_RIGHT; - case ui::TextEditCommandAuraLinux::PASTE: - return IDS_APP_PASTE; - case ui::TextEditCommandAuraLinux::SELECT_ALL: - return IDS_APP_SELECT_ALL; - case ui::TextEditCommandAuraLinux::SET_MARK: - case ui::TextEditCommandAuraLinux::UNSELECT: - case ui::TextEditCommandAuraLinux::INVALID_COMMAND: - return kNoCommand; - } - return kNoCommand; -} -#endif - -} // namespace - -// static -const char Textfield::kViewClassName[] = "Textfield"; -const int Textfield::kTextPadding = 3; - -// static -size_t Textfield::GetCaretBlinkMs() { - static const size_t default_value = 500; -#if defined(OS_WIN) - static const size_t system_value = ::GetCaretBlinkTime(); - if (system_value != 0) - return (system_value == INFINITE) ? 0 : system_value; -#endif - return default_value; -} - -Textfield::Textfield() - : model_(new TextfieldModel(this)), - controller_(NULL), - read_only_(false), - default_width_in_chars_(0), - use_default_text_color_(true), - use_default_background_color_(true), - use_default_selection_text_color_(true), - use_default_selection_background_color_(true), - text_color_(SK_ColorBLACK), - background_color_(SK_ColorWHITE), - selection_text_color_(SK_ColorWHITE), - selection_background_color_(SK_ColorBLUE), - placeholder_text_color_(kDefaultPlaceholderTextColor), - text_input_type_(ui::TEXT_INPUT_TYPE_TEXT), - performing_user_action_(false), - skip_input_method_cancel_composition_(false), - cursor_visible_(false), - drop_cursor_visible_(false), - initiating_drag_(false), - aggregated_clicks_(0), - drag_start_display_offset_(0), - touch_handles_hidden_due_to_scroll_(false), - weak_ptr_factory_(this) { - set_context_menu_controller(this); - set_drag_controller(this); - SetBorder(scoped_ptr<Border>(new FocusableBorder())); - SetFocusable(true); - - if (ViewsDelegate::views_delegate) { - password_reveal_duration_ = ViewsDelegate::views_delegate-> - GetDefaultTextfieldObscuredRevealDuration(); - } -} - -Textfield::~Textfield() {} - -void Textfield::SetReadOnly(bool read_only) { - // Update read-only without changing the focusable state (or active, etc.). - read_only_ = read_only; - if (GetInputMethod()) - GetInputMethod()->OnTextInputTypeChanged(this); - SetColor(GetTextColor()); - UpdateBackgroundColor(); -} - -void Textfield::SetTextInputType(ui::TextInputType type) { - GetRenderText()->SetObscured(type == ui::TEXT_INPUT_TYPE_PASSWORD); - text_input_type_ = type; - OnCaretBoundsChanged(); - if (GetInputMethod()) - GetInputMethod()->OnTextInputTypeChanged(this); - SchedulePaint(); -} - -void Textfield::SetText(const base::string16& new_text) { - model_->SetText(new_text); - OnCaretBoundsChanged(); - SchedulePaint(); - NotifyAccessibilityEvent(ui::AX_EVENT_TEXT_CHANGED, true); -} - -void Textfield::AppendText(const base::string16& new_text) { - if (new_text.empty()) - return; - model_->Append(new_text); - OnCaretBoundsChanged(); - SchedulePaint(); -} - -void Textfield::InsertOrReplaceText(const base::string16& new_text) { - if (new_text.empty()) - return; - model_->InsertText(new_text); - OnCaretBoundsChanged(); - SchedulePaint(); -} - -base::i18n::TextDirection Textfield::GetTextDirection() const { - return GetRenderText()->GetTextDirection(); -} - -base::string16 Textfield::GetSelectedText() const { - return model_->GetSelectedText(); -} - -void Textfield::SelectAll(bool reversed) { - model_->SelectAll(reversed); - UpdateSelectionClipboard(); - UpdateAfterChange(false, true); -} - -void Textfield::SelectWordAt(const gfx::Point& point) { - model_->MoveCursorTo(point, false); - model_->SelectWord(); - UpdateAfterChange(false, true); -} - -void Textfield::ClearSelection() { - model_->ClearSelection(); - UpdateAfterChange(false, true); -} - -bool Textfield::HasSelection() const { - return !GetSelectedRange().is_empty(); -} - -SkColor Textfield::GetTextColor() const { - if (!use_default_text_color_) - return text_color_; - - return GetNativeTheme()->GetSystemColor(read_only() ? - ui::NativeTheme::kColorId_TextfieldReadOnlyColor : - ui::NativeTheme::kColorId_TextfieldDefaultColor); -} - -void Textfield::SetTextColor(SkColor color) { - text_color_ = color; - use_default_text_color_ = false; - SetColor(color); -} - -void Textfield::UseDefaultTextColor() { - use_default_text_color_ = true; - SetColor(GetTextColor()); -} - -SkColor Textfield::GetBackgroundColor() const { - if (!use_default_background_color_) - return background_color_; - - return GetNativeTheme()->GetSystemColor(read_only() ? - ui::NativeTheme::kColorId_TextfieldReadOnlyBackground : - ui::NativeTheme::kColorId_TextfieldDefaultBackground); -} - -void Textfield::SetBackgroundColor(SkColor color) { - background_color_ = color; - use_default_background_color_ = false; - UpdateBackgroundColor(); -} - -void Textfield::UseDefaultBackgroundColor() { - use_default_background_color_ = true; - UpdateBackgroundColor(); -} - -SkColor Textfield::GetSelectionTextColor() const { - return use_default_selection_text_color_ ? - GetNativeTheme()->GetSystemColor( - ui::NativeTheme::kColorId_TextfieldSelectionColor) : - selection_text_color_; -} - -void Textfield::SetSelectionTextColor(SkColor color) { - selection_text_color_ = color; - use_default_selection_text_color_ = false; - GetRenderText()->set_selection_color(GetSelectionTextColor()); - SchedulePaint(); -} - -void Textfield::UseDefaultSelectionTextColor() { - use_default_selection_text_color_ = true; - GetRenderText()->set_selection_color(GetSelectionTextColor()); - SchedulePaint(); -} - -void Textfield::SetShadows(const gfx::ShadowValues& shadows) { - GetRenderText()->set_shadows(shadows); - SchedulePaint(); -} - -SkColor Textfield::GetSelectionBackgroundColor() const { - return use_default_selection_background_color_ ? - GetNativeTheme()->GetSystemColor( - ui::NativeTheme::kColorId_TextfieldSelectionBackgroundFocused) : - selection_background_color_; -} - -void Textfield::SetSelectionBackgroundColor(SkColor color) { - selection_background_color_ = color; - use_default_selection_background_color_ = false; - GetRenderText()->set_selection_background_focused_color( - GetSelectionBackgroundColor()); - SchedulePaint(); -} - -void Textfield::UseDefaultSelectionBackgroundColor() { - use_default_selection_background_color_ = true; - GetRenderText()->set_selection_background_focused_color( - GetSelectionBackgroundColor()); - SchedulePaint(); -} - -bool Textfield::GetCursorEnabled() const { - return GetRenderText()->cursor_enabled(); -} - -void Textfield::SetCursorEnabled(bool enabled) { - GetRenderText()->SetCursorEnabled(enabled); -} - -const gfx::FontList& Textfield::GetFontList() const { - return GetRenderText()->font_list(); -} - -void Textfield::SetFontList(const gfx::FontList& font_list) { - GetRenderText()->SetFontList(font_list); - OnCaretBoundsChanged(); - PreferredSizeChanged(); -} - -base::string16 Textfield::GetPlaceholderText() const { - return placeholder_text_; -} - -gfx::HorizontalAlignment Textfield::GetHorizontalAlignment() const { - return GetRenderText()->horizontal_alignment(); -} - -void Textfield::SetHorizontalAlignment(gfx::HorizontalAlignment alignment) { - GetRenderText()->SetHorizontalAlignment(alignment); -} - -void Textfield::ShowImeIfNeeded() { - if (enabled() && !read_only()) - GetInputMethod()->ShowImeIfNeeded(); -} - -bool Textfield::IsIMEComposing() const { - return model_->HasCompositionText(); -} - -const gfx::Range& Textfield::GetSelectedRange() const { - return GetRenderText()->selection(); -} - -void Textfield::SelectRange(const gfx::Range& range) { - model_->SelectRange(range); - UpdateAfterChange(false, true); -} - -const gfx::SelectionModel& Textfield::GetSelectionModel() const { - return GetRenderText()->selection_model(); -} - -void Textfield::SelectSelectionModel(const gfx::SelectionModel& sel) { - model_->SelectSelectionModel(sel); - UpdateAfterChange(false, true); -} - -size_t Textfield::GetCursorPosition() const { - return model_->GetCursorPosition(); -} - -void Textfield::SetColor(SkColor value) { - GetRenderText()->SetColor(value); - SchedulePaint(); -} - -void Textfield::ApplyColor(SkColor value, const gfx::Range& range) { - GetRenderText()->ApplyColor(value, range); - SchedulePaint(); -} - -void Textfield::SetStyle(gfx::TextStyle style, bool value) { - GetRenderText()->SetStyle(style, value); - SchedulePaint(); -} - -void Textfield::ApplyStyle(gfx::TextStyle style, - bool value, - const gfx::Range& range) { - GetRenderText()->ApplyStyle(style, value, range); - SchedulePaint(); -} - -void Textfield::ClearEditHistory() { - model_->ClearEditHistory(); -} - -void Textfield::SetAccessibleName(const base::string16& name) { - accessible_name_ = name; -} - -void Textfield::ExecuteCommand(int command_id) { - ExecuteCommand(command_id, ui::EF_NONE); -} - -void Textfield::SetFocusPainter(scoped_ptr<Painter> focus_painter) { - focus_painter_ = focus_painter.Pass(); -} - -bool Textfield::HasTextBeingDragged() { - return initiating_drag_; -} - -//////////////////////////////////////////////////////////////////////////////// -// Textfield, View overrides: - -gfx::Insets Textfield::GetInsets() const { - gfx::Insets insets = View::GetInsets(); - insets += gfx::Insets(kTextPadding, kTextPadding, kTextPadding, kTextPadding); - return insets; -} - -int Textfield::GetBaseline() const { - return GetInsets().top() + GetRenderText()->GetBaseline(); -} - -gfx::Size Textfield::GetPreferredSize() const { - const gfx::Insets& insets = GetInsets(); - return gfx::Size(GetFontList().GetExpectedTextWidth(default_width_in_chars_) + - insets.width(), GetFontList().GetHeight() + insets.height()); -} - -const char* Textfield::GetClassName() const { - return kViewClassName; -} - -gfx::NativeCursor Textfield::GetCursor(const ui::MouseEvent& event) { - bool in_selection = GetRenderText()->IsPointInSelection(event.location()); - bool drag_event = event.type() == ui::ET_MOUSE_DRAGGED; - bool text_cursor = !initiating_drag_ && (drag_event || !in_selection); - return text_cursor ? GetNativeIBeamCursor() : gfx::kNullCursor; -} - -bool Textfield::OnMousePressed(const ui::MouseEvent& event) { - TrackMouseClicks(event); - - if (!controller_ || !controller_->HandleMouseEvent(this, event)) { - if (event.IsOnlyLeftMouseButton() || event.IsOnlyRightMouseButton()) { - RequestFocus(); - ShowImeIfNeeded(); - } - - if (event.IsOnlyLeftMouseButton()) { - OnBeforeUserAction(); - initiating_drag_ = false; - switch (aggregated_clicks_) { - case 0: - if (GetRenderText()->IsPointInSelection(event.location())) - initiating_drag_ = true; - else - MoveCursorTo(event.location(), event.IsShiftDown()); - break; - case 1: - SelectWordAt(event.location()); - double_click_word_ = GetRenderText()->selection(); - break; - case 2: - SelectAll(false); - break; - default: - NOTREACHED(); - } - OnAfterUserAction(); - } - -#if defined(OS_LINUX) && !defined(OS_CHROMEOS) - if (event.IsOnlyMiddleMouseButton()) { - if (GetRenderText()->IsPointInSelection(event.location())) { - OnBeforeUserAction(); - ClearSelection(); - ui::ScopedClipboardWriter( - ui::CLIPBOARD_TYPE_SELECTION).WriteText(base::string16()); - OnAfterUserAction(); - } else if (!read_only()) { - PasteSelectionClipboard(event); - } - } -#endif - } - - return true; -} - -bool Textfield::OnMouseDragged(const ui::MouseEvent& event) { - last_drag_location_ = event.location(); - - // Don't adjust the cursor on a potential drag and drop, or if the mouse - // movement from the last mouse click does not exceed the drag threshold. - if (initiating_drag_ || !event.IsOnlyLeftMouseButton() || - !ExceededDragThreshold(last_drag_location_ - last_click_location_)) { - return true; - } - - // A timer is used to continuously scroll while selecting beyond side edges. - if ((event.location().x() > 0 && event.location().x() < size().width()) || - GetDragSelectionDelay() == 0) { - drag_selection_timer_.Stop(); - SelectThroughLastDragLocation(); - } else if (!drag_selection_timer_.IsRunning()) { - drag_selection_timer_.Start( - FROM_HERE, base::TimeDelta::FromMilliseconds(GetDragSelectionDelay()), - this, &Textfield::SelectThroughLastDragLocation); - } - - return true; -} - -void Textfield::OnMouseReleased(const ui::MouseEvent& event) { - OnBeforeUserAction(); - drag_selection_timer_.Stop(); - // Cancel suspected drag initiations, the user was clicking in the selection. - if (initiating_drag_) - MoveCursorTo(event.location(), false); - initiating_drag_ = false; - UpdateSelectionClipboard(); - OnAfterUserAction(); -} - -bool Textfield::OnKeyPressed(const ui::KeyEvent& event) { - // Since HandleKeyEvent() might destroy |this|, get a weak pointer and verify - // it isn't null before proceeding. - base::WeakPtr<Textfield> textfield(weak_ptr_factory_.GetWeakPtr()); - - bool handled = controller_ && controller_->HandleKeyEvent(this, event); - - if (!textfield) - return handled; - -#if defined(OS_LINUX) && !defined(OS_CHROMEOS) - ui::TextEditKeyBindingsDelegateAuraLinux* delegate = - ui::GetTextEditKeyBindingsDelegate(); - std::vector<ui::TextEditCommandAuraLinux> commands; - if (!handled && delegate && delegate->MatchEvent(event, &commands)) { - const bool rtl = GetTextDirection() == base::i18n::RIGHT_TO_LEFT; - for (size_t i = 0; i < commands.size(); ++i) { - const int command = GetViewsCommand(commands[i], rtl); - if (IsCommandIdEnabled(command)) { - ExecuteCommand(command); - handled = true; - } - } - return handled; - } -#endif - - const int command = GetCommandForKeyEvent(event, HasSelection()); - if (!handled && IsCommandIdEnabled(command)) { - ExecuteCommand(command); - handled = true; - } - return handled; -} - -ui::TextInputClient* Textfield::GetTextInputClient() { - return read_only_ ? NULL : this; -} - -void Textfield::OnGestureEvent(ui::GestureEvent* event) { - switch (event->type()) { - case ui::ET_GESTURE_TAP_DOWN: - RequestFocus(); - ShowImeIfNeeded(); - event->SetHandled(); - break; - case ui::ET_GESTURE_TAP: - if (event->details().tap_count() == 1) { - if (!GetRenderText()->IsPointInSelection(event->location())) { - OnBeforeUserAction(); - MoveCursorTo(event->location(), false); - OnAfterUserAction(); - } - } else if (event->details().tap_count() == 2) { - OnBeforeUserAction(); - SelectWordAt(event->location()); - OnAfterUserAction(); - } else { - OnBeforeUserAction(); - SelectAll(false); - OnAfterUserAction(); - } - CreateTouchSelectionControllerAndNotifyIt(); -#if defined(OS_WIN) - if (!read_only()) - base::win::DisplayVirtualKeyboard(); -#endif - event->SetHandled(); - break; - case ui::ET_GESTURE_LONG_PRESS: - if (!GetRenderText()->IsPointInSelection(event->location())) { - // If long-press happens outside selection, select word and try to - // activate touch selection. - OnBeforeUserAction(); - SelectWordAt(event->location()); - OnAfterUserAction(); - CreateTouchSelectionControllerAndNotifyIt(); - // If touch selection activated successfully, mark event as handled so - // that the regular context menu is not shown. - if (touch_selection_controller_) - event->SetHandled(); - } else { - // If long-press happens on the selection, deactivate touch selection - // and try to initiate drag-drop. If drag-drop is not enabled, context - // menu will be shown. Event is not marked as handled to let Views - // handle drag-drop or context menu. - DestroyTouchSelection(); - initiating_drag_ = switches::IsTouchDragDropEnabled(); - } - break; - case ui::ET_GESTURE_LONG_TAP: - // If touch selection is enabled, the context menu on long tap will be - // shown by the |touch_selection_controller_|, hence we mark the event - // handled so Views does not try to show context menu on it. - if (touch_selection_controller_) - event->SetHandled(); - break; - case ui::ET_GESTURE_SCROLL_BEGIN: - touch_handles_hidden_due_to_scroll_ = touch_selection_controller_ != NULL; - DestroyTouchSelection(); - drag_start_location_ = event->location(); - drag_start_display_offset_ = - GetRenderText()->GetUpdatedDisplayOffset().x(); - event->SetHandled(); - break; - case ui::ET_GESTURE_SCROLL_UPDATE: { - int new_offset = drag_start_display_offset_ + event->location().x() - - drag_start_location_.x(); - GetRenderText()->SetDisplayOffset(new_offset); - SchedulePaint(); - event->SetHandled(); - break; - } - case ui::ET_GESTURE_SCROLL_END: - case ui::ET_SCROLL_FLING_START: - if (touch_handles_hidden_due_to_scroll_) { - CreateTouchSelectionControllerAndNotifyIt(); - touch_handles_hidden_due_to_scroll_ = false; - } - event->SetHandled(); - break; - default: - return; - } -} - -void Textfield::AboutToRequestFocusFromTabTraversal(bool reverse) { - SelectAll(false); -} - -bool Textfield::SkipDefaultKeyEventProcessing(const ui::KeyEvent& event) { -#if defined(OS_LINUX) && !defined(OS_CHROMEOS) - // Skip any accelerator handling that conflicts with custom keybindings. - ui::TextEditKeyBindingsDelegateAuraLinux* delegate = - ui::GetTextEditKeyBindingsDelegate(); - std::vector<ui::TextEditCommandAuraLinux> commands; - if (delegate && delegate->MatchEvent(event, &commands)) { - const bool rtl = GetTextDirection() == base::i18n::RIGHT_TO_LEFT; - for (size_t i = 0; i < commands.size(); ++i) - if (IsCommandIdEnabled(GetViewsCommand(commands[i], rtl))) - return true; - } -#endif - - // Skip backspace accelerator handling; editable textfields handle this key. - // Also skip processing Windows [Alt]+<num-pad digit> Unicode alt-codes. - const bool is_backspace = event.key_code() == ui::VKEY_BACK; - return (is_backspace && !read_only()) || event.IsUnicodeKeyCode(); -} - -bool Textfield::GetDropFormats( - int* formats, - std::set<OSExchangeData::CustomFormat>* custom_formats) { - if (!enabled() || read_only()) - return false; - // TODO(msw): Can we support URL, FILENAME, etc.? - *formats = ui::OSExchangeData::STRING; - if (controller_) - controller_->AppendDropFormats(formats, custom_formats); - return true; -} - -bool Textfield::CanDrop(const OSExchangeData& data) { - int formats; - std::set<OSExchangeData::CustomFormat> custom_formats; - GetDropFormats(&formats, &custom_formats); - return enabled() && !read_only() && - data.HasAnyFormat(formats, custom_formats); -} - -int Textfield::OnDragUpdated(const ui::DropTargetEvent& event) { - DCHECK(CanDrop(event.data())); - gfx::RenderText* render_text = GetRenderText(); - const gfx::Range& selection = render_text->selection(); - drop_cursor_position_ = render_text->FindCursorPosition(event.location()); - bool in_selection = !selection.is_empty() && - selection.Contains(gfx::Range(drop_cursor_position_.caret_pos())); - drop_cursor_visible_ = !in_selection; - // TODO(msw): Pan over text when the user drags to the visible text edge. - OnCaretBoundsChanged(); - SchedulePaint(); - - if (initiating_drag_) { - if (in_selection) - return ui::DragDropTypes::DRAG_NONE; - return event.IsControlDown() ? ui::DragDropTypes::DRAG_COPY : - ui::DragDropTypes::DRAG_MOVE; - } - return ui::DragDropTypes::DRAG_COPY | ui::DragDropTypes::DRAG_MOVE; -} - -void Textfield::OnDragExited() { - drop_cursor_visible_ = false; - SchedulePaint(); -} - -int Textfield::OnPerformDrop(const ui::DropTargetEvent& event) { - DCHECK(CanDrop(event.data())); - drop_cursor_visible_ = false; - - if (controller_) { - int drag_operation = controller_->OnDrop(event.data()); - if (drag_operation != ui::DragDropTypes::DRAG_NONE) - return drag_operation; - } - - gfx::RenderText* render_text = GetRenderText(); - DCHECK(!initiating_drag_ || - !render_text->IsPointInSelection(event.location())); - OnBeforeUserAction(); - skip_input_method_cancel_composition_ = true; - - gfx::SelectionModel drop_destination_model = - render_text->FindCursorPosition(event.location()); - base::string16 new_text; - event.data().GetString(&new_text); - - // Delete the current selection for a drag and drop within this view. - const bool move = initiating_drag_ && !event.IsControlDown() && - event.source_operations() & ui::DragDropTypes::DRAG_MOVE; - if (move) { - // Adjust the drop destination if it is on or after the current selection. - size_t pos = drop_destination_model.caret_pos(); - pos -= render_text->selection().Intersect(gfx::Range(0, pos)).length(); - model_->DeleteSelectionAndInsertTextAt(new_text, pos); - } else { - model_->MoveCursorTo(drop_destination_model); - // Drop always inserts text even if the textfield is not in insert mode. - model_->InsertText(new_text); - } - skip_input_method_cancel_composition_ = false; - UpdateAfterChange(true, true); - OnAfterUserAction(); - return move ? ui::DragDropTypes::DRAG_MOVE : ui::DragDropTypes::DRAG_COPY; -} - -void Textfield::OnDragDone() { - initiating_drag_ = false; - drop_cursor_visible_ = false; -} - -void Textfield::GetAccessibleState(ui::AXViewState* state) { - state->role = ui::AX_ROLE_TEXT_FIELD; - state->name = accessible_name_; - if (read_only()) - state->AddStateFlag(ui::AX_STATE_READ_ONLY); - if (text_input_type_ == ui::TEXT_INPUT_TYPE_PASSWORD) - state->AddStateFlag(ui::AX_STATE_PROTECTED); - state->value = text(); - - const gfx::Range range = GetSelectedRange(); - state->selection_start = range.start(); - state->selection_end = range.end(); - - if (!read_only()) { - state->set_value_callback = - base::Bind(&Textfield::AccessibilitySetValue, - weak_ptr_factory_.GetWeakPtr()); - } -} - -void Textfield::OnBoundsChanged(const gfx::Rect& previous_bounds) { - // Textfield insets include a reasonable amount of whitespace on all sides of - // the default font list. Fallback fonts with larger heights may paint over - // the vertical whitespace as needed. Alternate solutions involve undesirable - // behavior like changing the default font size, shrinking some fallback fonts - // beyond their legibility, or enlarging controls dynamically with content. - gfx::Rect bounds = GetContentsBounds(); - // GetContentsBounds() does not actually use the local GetInsets() override. - bounds.Inset(gfx::Insets(0, kTextPadding, 0, kTextPadding)); - GetRenderText()->SetDisplayRect(bounds); - OnCaretBoundsChanged(); -} - -bool Textfield::GetNeedsNotificationWhenVisibleBoundsChange() const { - return true; -} - -void Textfield::OnVisibleBoundsChanged() { - if (touch_selection_controller_) - touch_selection_controller_->SelectionChanged(); -} - -void Textfield::OnEnabledChanged() { - View::OnEnabledChanged(); - if (GetInputMethod()) - GetInputMethod()->OnTextInputTypeChanged(this); - SchedulePaint(); -} - -void Textfield::OnPaint(gfx::Canvas* canvas) { - OnPaintBackground(canvas); - PaintTextAndCursor(canvas); - OnPaintBorder(canvas); -} - -void Textfield::OnFocus() { - GetRenderText()->set_focused(true); - cursor_visible_ = true; - SchedulePaint(); - GetInputMethod()->OnFocus(); - OnCaretBoundsChanged(); - - const size_t caret_blink_ms = Textfield::GetCaretBlinkMs(); - if (caret_blink_ms != 0) { - cursor_repaint_timer_.Start(FROM_HERE, - base::TimeDelta::FromMilliseconds(caret_blink_ms), this, - &Textfield::UpdateCursor); - } - - View::OnFocus(); - SchedulePaint(); -} - -void Textfield::OnBlur() { - GetRenderText()->set_focused(false); - GetInputMethod()->OnBlur(); - cursor_repaint_timer_.Stop(); - if (cursor_visible_) { - cursor_visible_ = false; - RepaintCursor(); - } - - DestroyTouchSelection(); - - // Border typically draws focus indicator. - SchedulePaint(); -} - -gfx::Point Textfield::GetKeyboardContextMenuLocation() { - return GetCaretBounds().bottom_right(); -} - -void Textfield::OnNativeThemeChanged(const ui::NativeTheme* theme) { - gfx::RenderText* render_text = GetRenderText(); - render_text->SetColor(GetTextColor()); - UpdateBackgroundColor(); - render_text->set_cursor_color(GetTextColor()); - render_text->set_selection_color(GetSelectionTextColor()); - render_text->set_selection_background_focused_color( - GetSelectionBackgroundColor()); -} - -//////////////////////////////////////////////////////////////////////////////// -// Textfield, TextfieldModel::Delegate overrides: - -void Textfield::OnCompositionTextConfirmedOrCleared() { - if (!skip_input_method_cancel_composition_) - GetInputMethod()->CancelComposition(this); -} - -//////////////////////////////////////////////////////////////////////////////// -// Textfield, ContextMenuController overrides: - -void Textfield::ShowContextMenuForView(View* source, - const gfx::Point& point, - ui::MenuSourceType source_type) { - UpdateContextMenu(); - ignore_result(context_menu_runner_->RunMenuAt(GetWidget(), - NULL, - gfx::Rect(point, gfx::Size()), - MENU_ANCHOR_TOPLEFT, - source_type)); -} - -//////////////////////////////////////////////////////////////////////////////// -// Textfield, DragController overrides: - -void Textfield::WriteDragDataForView(View* sender, - const gfx::Point& press_pt, - OSExchangeData* data) { - const base::string16& selected_text(GetSelectedText()); - data->SetString(selected_text); - Label label(selected_text, GetFontList()); - label.SetBackgroundColor(GetBackgroundColor()); - label.SetSubpixelRenderingEnabled(false); - gfx::Size size(label.GetPreferredSize()); - gfx::NativeView native_view = GetWidget()->GetNativeView(); - gfx::Display display = gfx::Screen::GetScreenFor(native_view)-> - GetDisplayNearestWindow(native_view); - size.SetToMin(gfx::Size(display.size().width(), height())); - label.SetBoundsRect(gfx::Rect(size)); - scoped_ptr<gfx::Canvas> canvas( - GetCanvasForDragImage(GetWidget(), label.size())); - label.SetEnabledColor(GetTextColor()); -#if defined(OS_LINUX) && !defined(OS_CHROMEOS) - // Desktop Linux Aura does not yet support transparency in drag images. - canvas->DrawColor(GetBackgroundColor()); -#endif - label.Paint(canvas.get(), views::CullSet()); - const gfx::Vector2d kOffset(-15, 0); - drag_utils::SetDragImageOnDataObject(*canvas, kOffset, data); - if (controller_) - controller_->OnWriteDragData(data); -} - -int Textfield::GetDragOperationsForView(View* sender, const gfx::Point& p) { - int drag_operations = ui::DragDropTypes::DRAG_COPY; - if (!enabled() || text_input_type_ == ui::TEXT_INPUT_TYPE_PASSWORD || - !GetRenderText()->IsPointInSelection(p)) { - drag_operations = ui::DragDropTypes::DRAG_NONE; - } else if (sender == this && !read_only()) { - drag_operations = - ui::DragDropTypes::DRAG_MOVE | ui::DragDropTypes::DRAG_COPY; - } - if (controller_) - controller_->OnGetDragOperationsForTextfield(&drag_operations); - return drag_operations; -} - -bool Textfield::CanStartDragForView(View* sender, - const gfx::Point& press_pt, - const gfx::Point& p) { - return initiating_drag_ && GetRenderText()->IsPointInSelection(press_pt); -} - -//////////////////////////////////////////////////////////////////////////////// -// Textfield, ui::TouchEditable overrides: - -void Textfield::SelectRect(const gfx::Point& start, const gfx::Point& end) { - if (GetTextInputType() == ui::TEXT_INPUT_TYPE_NONE) - return; - - gfx::SelectionModel start_caret = GetRenderText()->FindCursorPosition(start); - gfx::SelectionModel end_caret = GetRenderText()->FindCursorPosition(end); - gfx::SelectionModel selection( - gfx::Range(start_caret.caret_pos(), end_caret.caret_pos()), - end_caret.caret_affinity()); - - OnBeforeUserAction(); - SelectSelectionModel(selection); - OnAfterUserAction(); -} - -void Textfield::MoveCaretTo(const gfx::Point& point) { - SelectRect(point, point); -} - -void Textfield::GetSelectionEndPoints(gfx::Rect* p1, gfx::Rect* p2) { - gfx::RenderText* render_text = GetRenderText(); - const gfx::SelectionModel& sel = render_text->selection_model(); - gfx::SelectionModel start_sel = - render_text->GetSelectionModelForSelectionStart(); - *p1 = render_text->GetCursorBounds(start_sel, true); - *p2 = render_text->GetCursorBounds(sel, true); -} - -gfx::Rect Textfield::GetBounds() { - return GetLocalBounds(); -} - -gfx::NativeView Textfield::GetNativeView() const { - return GetWidget()->GetNativeView(); -} - -void Textfield::ConvertPointToScreen(gfx::Point* point) { - View::ConvertPointToScreen(this, point); -} - -void Textfield::ConvertPointFromScreen(gfx::Point* point) { - View::ConvertPointFromScreen(this, point); -} - -bool Textfield::DrawsHandles() { - return false; -} - -void Textfield::OpenContextMenu(const gfx::Point& anchor) { - DestroyTouchSelection(); - ShowContextMenu(anchor, ui::MENU_SOURCE_TOUCH_EDIT_MENU); -} - -void Textfield::DestroyTouchSelection() { - touch_selection_controller_.reset(); -} - -//////////////////////////////////////////////////////////////////////////////// -// Textfield, ui::SimpleMenuModel::Delegate overrides: - -bool Textfield::IsCommandIdChecked(int command_id) const { - return true; -} - -bool Textfield::IsCommandIdEnabled(int command_id) const { - base::string16 result; - bool editable = !read_only(); - bool readable = text_input_type_ != ui::TEXT_INPUT_TYPE_PASSWORD; - switch (command_id) { - case IDS_APP_UNDO: - return editable && model_->CanUndo(); - case IDS_APP_REDO: - return editable && model_->CanRedo(); - case IDS_APP_CUT: - return editable && readable && model_->HasSelection(); - case IDS_APP_COPY: - return readable && model_->HasSelection(); - case IDS_APP_PASTE: - ui::Clipboard::GetForCurrentThread()->ReadText( - ui::CLIPBOARD_TYPE_COPY_PASTE, &result); - return editable && !result.empty(); - case IDS_APP_DELETE: - return editable && model_->HasSelection(); - case IDS_APP_SELECT_ALL: - return !text().empty(); - case IDS_DELETE_FORWARD: - case IDS_DELETE_BACKWARD: - case IDS_DELETE_TO_BEGINNING_OF_LINE: - case IDS_DELETE_TO_END_OF_LINE: - case IDS_DELETE_WORD_BACKWARD: - case IDS_DELETE_WORD_FORWARD: - return editable; - case IDS_MOVE_LEFT: - case IDS_MOVE_LEFT_AND_MODIFY_SELECTION: - case IDS_MOVE_RIGHT: - case IDS_MOVE_RIGHT_AND_MODIFY_SELECTION: - case IDS_MOVE_WORD_LEFT: - case IDS_MOVE_WORD_LEFT_AND_MODIFY_SELECTION: - case IDS_MOVE_WORD_RIGHT: - case IDS_MOVE_WORD_RIGHT_AND_MODIFY_SELECTION: - case IDS_MOVE_TO_BEGINNING_OF_LINE: - case IDS_MOVE_TO_BEGINNING_OF_LINE_AND_MODIFY_SELECTION: - case IDS_MOVE_TO_END_OF_LINE: - case IDS_MOVE_TO_END_OF_LINE_AND_MODIFY_SELECTION: - return true; - default: - return false; - } -} - -bool Textfield::GetAcceleratorForCommandId(int command_id, - ui::Accelerator* accelerator) { - return false; -} - -void Textfield::ExecuteCommand(int command_id, int event_flags) { - DestroyTouchSelection(); - if (!IsCommandIdEnabled(command_id)) - return; - - bool text_changed = false; - bool cursor_changed = false; - bool rtl = GetTextDirection() == base::i18n::RIGHT_TO_LEFT; - gfx::VisualCursorDirection begin = rtl ? gfx::CURSOR_RIGHT : gfx::CURSOR_LEFT; - gfx::VisualCursorDirection end = rtl ? gfx::CURSOR_LEFT : gfx::CURSOR_RIGHT; - gfx::SelectionModel selection_model = GetSelectionModel(); - - OnBeforeUserAction(); - switch (command_id) { - case IDS_APP_UNDO: - text_changed = cursor_changed = model_->Undo(); - break; - case IDS_APP_REDO: - text_changed = cursor_changed = model_->Redo(); - break; - case IDS_APP_CUT: - text_changed = cursor_changed = Cut(); - break; - case IDS_APP_COPY: - Copy(); - break; - case IDS_APP_PASTE: - text_changed = cursor_changed = Paste(); - break; - case IDS_APP_DELETE: - text_changed = cursor_changed = model_->Delete(); - break; - case IDS_APP_SELECT_ALL: - SelectAll(false); - break; - case IDS_DELETE_BACKWARD: - text_changed = cursor_changed = model_->Backspace(); - break; - case IDS_DELETE_FORWARD: - text_changed = cursor_changed = model_->Delete(); - break; - case IDS_DELETE_TO_END_OF_LINE: - model_->MoveCursor(gfx::LINE_BREAK, end, true); - text_changed = cursor_changed = model_->Delete(); - break; - case IDS_DELETE_TO_BEGINNING_OF_LINE: - model_->MoveCursor(gfx::LINE_BREAK, begin, true); - text_changed = cursor_changed = model_->Backspace(); - break; - case IDS_DELETE_WORD_BACKWARD: - model_->MoveCursor(gfx::WORD_BREAK, begin, true); - text_changed = cursor_changed = model_->Backspace(); - break; - case IDS_DELETE_WORD_FORWARD: - model_->MoveCursor(gfx::WORD_BREAK, end, true); - text_changed = cursor_changed = model_->Delete(); - break; - case IDS_MOVE_LEFT: - model_->MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, false); - break; - case IDS_MOVE_LEFT_AND_MODIFY_SELECTION: - model_->MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, true); - break; - case IDS_MOVE_RIGHT: - model_->MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, false); - break; - case IDS_MOVE_RIGHT_AND_MODIFY_SELECTION: - model_->MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, true); - break; - case IDS_MOVE_WORD_LEFT: - model_->MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, false); - break; - case IDS_MOVE_WORD_LEFT_AND_MODIFY_SELECTION: - model_->MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, true); - break; - case IDS_MOVE_WORD_RIGHT: - model_->MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, false); - break; - case IDS_MOVE_WORD_RIGHT_AND_MODIFY_SELECTION: - model_->MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, true); - break; - case IDS_MOVE_TO_BEGINNING_OF_LINE: - model_->MoveCursor(gfx::LINE_BREAK, begin, false); - break; - case IDS_MOVE_TO_BEGINNING_OF_LINE_AND_MODIFY_SELECTION: - model_->MoveCursor(gfx::LINE_BREAK, begin, true); - break; - case IDS_MOVE_TO_END_OF_LINE: - model_->MoveCursor(gfx::LINE_BREAK, end, false); - break; - case IDS_MOVE_TO_END_OF_LINE_AND_MODIFY_SELECTION: - model_->MoveCursor(gfx::LINE_BREAK, end, true); - break; - default: - NOTREACHED(); - break; - } - - cursor_changed |= GetSelectionModel() != selection_model; - if (cursor_changed) - UpdateSelectionClipboard(); - UpdateAfterChange(text_changed, cursor_changed); - OnAfterUserAction(); -} - -//////////////////////////////////////////////////////////////////////////////// -// Textfield, ui::TextInputClient overrides: - -void Textfield::SetCompositionText(const ui::CompositionText& composition) { - if (GetTextInputType() == ui::TEXT_INPUT_TYPE_NONE) - return; - - OnBeforeUserAction(); - skip_input_method_cancel_composition_ = true; - model_->SetCompositionText(composition); - skip_input_method_cancel_composition_ = false; - UpdateAfterChange(true, true); - OnAfterUserAction(); -} - -void Textfield::ConfirmCompositionText() { - if (!model_->HasCompositionText()) - return; - - OnBeforeUserAction(); - skip_input_method_cancel_composition_ = true; - model_->ConfirmCompositionText(); - skip_input_method_cancel_composition_ = false; - UpdateAfterChange(true, true); - OnAfterUserAction(); -} - -void Textfield::ClearCompositionText() { - if (!model_->HasCompositionText()) - return; - - OnBeforeUserAction(); - skip_input_method_cancel_composition_ = true; - model_->CancelCompositionText(); - skip_input_method_cancel_composition_ = false; - UpdateAfterChange(true, true); - OnAfterUserAction(); -} - -void Textfield::InsertText(const base::string16& new_text) { - // TODO(suzhe): Filter invalid characters. - if (GetTextInputType() == ui::TEXT_INPUT_TYPE_NONE || new_text.empty()) - return; - - OnBeforeUserAction(); - skip_input_method_cancel_composition_ = true; - if (GetRenderText()->insert_mode()) - model_->InsertText(new_text); - else - model_->ReplaceText(new_text); - skip_input_method_cancel_composition_ = false; - UpdateAfterChange(true, true); - OnAfterUserAction(); -} - -void Textfield::InsertChar(base::char16 ch, int flags) { - const int kControlModifierMask = ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN | - ui::EF_COMMAND_DOWN | ui::EF_ALTGR_DOWN | - ui::EF_MOD3_DOWN; - - // Filter out all control characters, including tab and new line characters, - // and all characters with Alt modifier. But allow characters with the AltGr - // modifier. On Windows AltGr is represented by Alt+Ctrl, and on Linux it's a - // different flag that we don't care about. - const bool should_insert_char = - ((ch >= 0x20 && ch < 0x7F) || ch > 0x9F) && - (flags & kControlModifierMask) != ui::EF_ALT_DOWN; - if (GetTextInputType() == ui::TEXT_INPUT_TYPE_NONE || !should_insert_char) - return; - - OnBeforeUserAction(); - skip_input_method_cancel_composition_ = true; - if (GetRenderText()->insert_mode()) - model_->InsertChar(ch); - else - model_->ReplaceChar(ch); - skip_input_method_cancel_composition_ = false; - - UpdateAfterChange(true, true); - OnAfterUserAction(); - - if (text_input_type_ == ui::TEXT_INPUT_TYPE_PASSWORD && - password_reveal_duration_ != base::TimeDelta()) { - const size_t change_offset = model_->GetCursorPosition(); - DCHECK_GT(change_offset, 0u); - RevealPasswordChar(change_offset - 1); - } -} - -gfx::NativeWindow Textfield::GetAttachedWindow() const { - // Imagine the following hierarchy. - // [NativeWidget A] - FocusManager - // [View] - // [NativeWidget B] - // [View] - // [View X] - // An important thing is that [NativeWidget A] owns Win32 input focus even - // when [View X] is logically focused by FocusManager. As a result, an Win32 - // IME may want to interact with the native view of [NativeWidget A] rather - // than that of [NativeWidget B]. This is why we need to call - // GetTopLevelWidget() here. - return GetWidget()->GetTopLevelWidget()->GetNativeWindow(); -} - -ui::TextInputType Textfield::GetTextInputType() const { - if (read_only() || !enabled()) - return ui::TEXT_INPUT_TYPE_NONE; - return text_input_type_; -} - -ui::TextInputMode Textfield::GetTextInputMode() const { - return ui::TEXT_INPUT_MODE_DEFAULT; -} - -bool Textfield::CanComposeInline() const { - return true; -} - -gfx::Rect Textfield::GetCaretBounds() const { - gfx::Rect rect = GetRenderText()->GetUpdatedCursorBounds(); - ConvertRectToScreen(this, &rect); - return rect; -} - -bool Textfield::GetCompositionCharacterBounds(uint32 index, - gfx::Rect* rect) const { - DCHECK(rect); - if (!HasCompositionText()) - return false; - gfx::RenderText* render_text = GetRenderText(); - const gfx::Range& composition_range = render_text->GetCompositionRange(); - DCHECK(!composition_range.is_empty()); - - size_t text_index = composition_range.start() + index; - if (composition_range.end() <= text_index) - return false; - if (!render_text->IsValidCursorIndex(text_index)) { - text_index = render_text->IndexOfAdjacentGrapheme( - text_index, gfx::CURSOR_BACKWARD); - } - if (text_index < composition_range.start()) - return false; - const gfx::SelectionModel caret(text_index, gfx::CURSOR_BACKWARD); - *rect = render_text->GetCursorBounds(caret, false); - ConvertRectToScreen(this, rect); - return true; -} - -bool Textfield::HasCompositionText() const { - return model_->HasCompositionText(); -} - -bool Textfield::GetTextRange(gfx::Range* range) const { - if (!ImeEditingAllowed()) - return false; - - model_->GetTextRange(range); - return true; -} - -bool Textfield::GetCompositionTextRange(gfx::Range* range) const { - if (!ImeEditingAllowed()) - return false; - - model_->GetCompositionTextRange(range); - return true; -} - -bool Textfield::GetSelectionRange(gfx::Range* range) const { - if (!ImeEditingAllowed()) - return false; - *range = GetRenderText()->selection(); - return true; -} - -bool Textfield::SetSelectionRange(const gfx::Range& range) { - if (!ImeEditingAllowed() || !range.IsValid()) - return false; - OnBeforeUserAction(); - SelectRange(range); - OnAfterUserAction(); - return true; -} - -bool Textfield::DeleteRange(const gfx::Range& range) { - if (!ImeEditingAllowed() || range.is_empty()) - return false; - - OnBeforeUserAction(); - model_->SelectRange(range); - if (model_->HasSelection()) { - model_->DeleteSelection(); - UpdateAfterChange(true, true); - } - OnAfterUserAction(); - return true; -} - -bool Textfield::GetTextFromRange(const gfx::Range& range, - base::string16* range_text) const { - if (!ImeEditingAllowed() || !range.IsValid()) - return false; - - gfx::Range text_range; - if (!GetTextRange(&text_range) || !text_range.Contains(range)) - return false; - - *range_text = model_->GetTextFromRange(range); - return true; -} - -void Textfield::OnInputMethodChanged() {} - -bool Textfield::ChangeTextDirectionAndLayoutAlignment( - base::i18n::TextDirection direction) { - // Restore text directionality mode when the indicated direction matches the - // current forced mode; otherwise, force the mode indicated. This helps users - // manage BiDi text layout without getting stuck in forced LTR or RTL modes. - const gfx::DirectionalityMode mode = direction == base::i18n::RIGHT_TO_LEFT ? - gfx::DIRECTIONALITY_FORCE_RTL : gfx::DIRECTIONALITY_FORCE_LTR; - if (mode == GetRenderText()->directionality_mode()) - GetRenderText()->SetDirectionalityMode(gfx::DIRECTIONALITY_FROM_TEXT); - else - GetRenderText()->SetDirectionalityMode(mode); - SchedulePaint(); - return true; -} - -void Textfield::ExtendSelectionAndDelete(size_t before, size_t after) { - gfx::Range range = GetRenderText()->selection(); - DCHECK_GE(range.start(), before); - - range.set_start(range.start() - before); - range.set_end(range.end() + after); - gfx::Range text_range; - if (GetTextRange(&text_range) && text_range.Contains(range)) - DeleteRange(range); -} - -void Textfield::EnsureCaretInRect(const gfx::Rect& rect) {} - -void Textfield::OnCandidateWindowShown() {} - -void Textfield::OnCandidateWindowUpdated() {} - -void Textfield::OnCandidateWindowHidden() {} - -bool Textfield::IsEditingCommandEnabled(int command_id) { - return IsCommandIdEnabled(command_id); -} - -void Textfield::ExecuteEditingCommand(int command_id) { - ExecuteCommand(command_id); -} - -//////////////////////////////////////////////////////////////////////////////// -// Textfield, protected: - -gfx::RenderText* Textfield::GetRenderText() const { - return model_->render_text(); -} - -base::string16 Textfield::GetSelectionClipboardText() const { - base::string16 selection_clipboard_text; - ui::Clipboard::GetForCurrentThread()->ReadText( - ui::CLIPBOARD_TYPE_SELECTION, &selection_clipboard_text); - return selection_clipboard_text; -} - -//////////////////////////////////////////////////////////////////////////////// -// Textfield, private: - -void Textfield::AccessibilitySetValue(const base::string16& new_value) { - if (!read_only()) { - SetText(new_value); - ClearSelection(); - } -} - -void Textfield::UpdateBackgroundColor() { - const SkColor color = GetBackgroundColor(); - set_background(Background::CreateSolidBackground(color)); - GetRenderText()->set_background_is_transparent(SkColorGetA(color) != 0xFF); - SchedulePaint(); -} - -void Textfield::UpdateAfterChange(bool text_changed, bool cursor_changed) { - if (text_changed) { - if (controller_) - controller_->ContentsChanged(this, text()); - NotifyAccessibilityEvent(ui::AX_EVENT_TEXT_CHANGED, true); - } - if (cursor_changed) { - cursor_visible_ = true; - RepaintCursor(); - if (cursor_repaint_timer_.IsRunning()) - cursor_repaint_timer_.Reset(); - if (!text_changed) { - // TEXT_CHANGED implies TEXT_SELECTION_CHANGED, so we only need to fire - // this if only the selection changed. - NotifyAccessibilityEvent(ui::AX_EVENT_TEXT_SELECTION_CHANGED, true); - } - } - if (text_changed || cursor_changed) { - OnCaretBoundsChanged(); - SchedulePaint(); - } -} - -void Textfield::UpdateCursor() { - const size_t caret_blink_ms = Textfield::GetCaretBlinkMs(); - cursor_visible_ = !cursor_visible_ || (caret_blink_ms == 0); - RepaintCursor(); -} - -void Textfield::RepaintCursor() { - gfx::Rect r(GetRenderText()->GetUpdatedCursorBounds()); - r.Inset(-1, -1, -1, -1); - SchedulePaintInRect(r); -} - -void Textfield::PaintTextAndCursor(gfx::Canvas* canvas) { - TRACE_EVENT0("views", "Textfield::PaintTextAndCursor"); - canvas->Save(); - - // Draw placeholder text if needed. - gfx::RenderText* render_text = GetRenderText(); - if (text().empty() && !GetPlaceholderText().empty()) { - canvas->DrawStringRect(GetPlaceholderText(), GetFontList(), - placeholder_text_color(), render_text->display_rect()); - } - - // Draw the text, cursor, and selection. - render_text->set_cursor_visible(cursor_visible_ && !drop_cursor_visible_ && - !HasSelection()); - render_text->Draw(canvas); - - // Draw the detached drop cursor that marks where the text will be dropped. - if (drop_cursor_visible_) - render_text->DrawCursor(canvas, drop_cursor_position_); - - canvas->Restore(); -} - -void Textfield::MoveCursorTo(const gfx::Point& point, bool select) { - if (model_->MoveCursorTo(point, select)) - UpdateAfterChange(false, true); -} - -void Textfield::SelectThroughLastDragLocation() { - OnBeforeUserAction(); - model_->MoveCursorTo(last_drag_location_, true); - if (aggregated_clicks_ == 1) { - model_->SelectWord(); - // Expand the selection so the initially selected word remains selected. - gfx::Range selection = GetRenderText()->selection(); - const size_t min = std::min(selection.GetMin(), - double_click_word_.GetMin()); - const size_t max = std::max(selection.GetMax(), - double_click_word_.GetMax()); - const bool reversed = selection.is_reversed(); - selection.set_start(reversed ? max : min); - selection.set_end(reversed ? min : max); - model_->SelectRange(selection); - } - UpdateAfterChange(false, true); - OnAfterUserAction(); -} - -void Textfield::OnCaretBoundsChanged() { - if (GetInputMethod()) - GetInputMethod()->OnCaretBoundsChanged(this); - if (touch_selection_controller_) - touch_selection_controller_->SelectionChanged(); -} - -void Textfield::OnBeforeUserAction() { - DCHECK(!performing_user_action_); - performing_user_action_ = true; - if (controller_) - controller_->OnBeforeUserAction(this); -} - -void Textfield::OnAfterUserAction() { - if (controller_) - controller_->OnAfterUserAction(this); - DCHECK(performing_user_action_); - performing_user_action_ = false; -} - -bool Textfield::Cut() { - if (!read_only() && text_input_type_ != ui::TEXT_INPUT_TYPE_PASSWORD && - model_->Cut()) { - if (controller_) - controller_->OnAfterCutOrCopy(ui::CLIPBOARD_TYPE_COPY_PASTE); - return true; - } - return false; -} - -bool Textfield::Copy() { - if (text_input_type_ != ui::TEXT_INPUT_TYPE_PASSWORD && model_->Copy()) { - if (controller_) - controller_->OnAfterCutOrCopy(ui::CLIPBOARD_TYPE_COPY_PASTE); - return true; - } - return false; -} - -bool Textfield::Paste() { - if (!read_only() && model_->Paste()) { - if (controller_) - controller_->OnAfterPaste(); - return true; - } - return false; -} - -void Textfield::UpdateContextMenu() { - if (!context_menu_contents_.get()) { - context_menu_contents_.reset(new ui::SimpleMenuModel(this)); - context_menu_contents_->AddItemWithStringId(IDS_APP_UNDO, IDS_APP_UNDO); - context_menu_contents_->AddSeparator(ui::NORMAL_SEPARATOR); - context_menu_contents_->AddItemWithStringId(IDS_APP_CUT, IDS_APP_CUT); - context_menu_contents_->AddItemWithStringId(IDS_APP_COPY, IDS_APP_COPY); - context_menu_contents_->AddItemWithStringId(IDS_APP_PASTE, IDS_APP_PASTE); - context_menu_contents_->AddItemWithStringId(IDS_APP_DELETE, IDS_APP_DELETE); - context_menu_contents_->AddSeparator(ui::NORMAL_SEPARATOR); - context_menu_contents_->AddItemWithStringId(IDS_APP_SELECT_ALL, - IDS_APP_SELECT_ALL); - if (controller_) - controller_->UpdateContextMenu(context_menu_contents_.get()); - } - context_menu_runner_.reset( - new MenuRunner(context_menu_contents_.get(), - MenuRunner::HAS_MNEMONICS | MenuRunner::CONTEXT_MENU)); -} - -void Textfield::TrackMouseClicks(const ui::MouseEvent& event) { - if (event.IsOnlyLeftMouseButton()) { - base::TimeDelta time_delta = event.time_stamp() - last_click_time_; - if (time_delta.InMilliseconds() <= GetDoubleClickInterval() && - !ExceededDragThreshold(event.location() - last_click_location_)) { - // Upon clicking after a triple click, the count should go back to double - // click and alternate between double and triple. This assignment maps - // 0 to 1, 1 to 2, 2 to 1. - aggregated_clicks_ = (aggregated_clicks_ % 2) + 1; - } else { - aggregated_clicks_ = 0; - } - last_click_time_ = event.time_stamp(); - last_click_location_ = event.location(); - } -} - -bool Textfield::ImeEditingAllowed() const { - // Disallow input method editing of password fields. - ui::TextInputType t = GetTextInputType(); - return (t != ui::TEXT_INPUT_TYPE_NONE && t != ui::TEXT_INPUT_TYPE_PASSWORD); -} - -void Textfield::RevealPasswordChar(int index) { - GetRenderText()->SetObscuredRevealIndex(index); - SchedulePaint(); - - if (index != -1) { - password_reveal_timer_.Start(FROM_HERE, password_reveal_duration_, - base::Bind(&Textfield::RevealPasswordChar, - weak_ptr_factory_.GetWeakPtr(), -1)); - } -} - -void Textfield::CreateTouchSelectionControllerAndNotifyIt() { - if (!HasFocus()) - return; - - if (!touch_selection_controller_) { - touch_selection_controller_.reset( - ui::TouchSelectionController::create(this)); - } - if (touch_selection_controller_) - touch_selection_controller_->SelectionChanged(); -} - -void Textfield::UpdateSelectionClipboard() const { -#if defined(OS_LINUX) && !defined(OS_CHROMEOS) - if (performing_user_action_ && HasSelection()) { - ui::ScopedClipboardWriter( - ui::CLIPBOARD_TYPE_SELECTION).WriteText(GetSelectedText()); - if (controller_) - controller_->OnAfterCutOrCopy(ui::CLIPBOARD_TYPE_SELECTION); - } -#endif -} - -void Textfield::PasteSelectionClipboard(const ui::MouseEvent& event) { - DCHECK(event.IsOnlyMiddleMouseButton()); - DCHECK(!read_only()); - base::string16 selection_clipboard_text = GetSelectionClipboardText(); - if (!selection_clipboard_text.empty()) { - OnBeforeUserAction(); - gfx::Range range = GetSelectionModel().selection(); - gfx::LogicalCursorDirection affinity = GetSelectionModel().caret_affinity(); - const gfx::SelectionModel mouse = - GetRenderText()->FindCursorPosition(event.location()); - model_->MoveCursorTo(mouse); - model_->InsertText(selection_clipboard_text); - // Update the new selection range as needed. - if (range.GetMin() >= mouse.caret_pos()) { - const size_t length = selection_clipboard_text.length(); - range = gfx::Range(range.start() + length, range.end() + length); - } - model_->MoveCursorTo(gfx::SelectionModel(range, affinity)); - UpdateAfterChange(true, true); - OnAfterUserAction(); - } -} - -} // namespace views
diff --git a/ui/views/controls/textfield/textfield.h b/ui/views/controls/textfield/textfield.h deleted file mode 100644 index 53f0ee6..0000000 --- a/ui/views/controls/textfield/textfield.h +++ /dev/null
@@ -1,483 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_TEXTFIELD_TEXTFIELD_H_ -#define UI_VIEWS_CONTROLS_TEXTFIELD_TEXTFIELD_H_ - -#include <string> - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "base/memory/weak_ptr.h" -#include "base/strings/string16.h" -#include "base/timer/timer.h" -#include "third_party/skia/include/core/SkColor.h" -#include "ui/base/ime/text_input_client.h" -#include "ui/base/ime/text_input_type.h" -#include "ui/base/models/simple_menu_model.h" -#include "ui/base/touch/touch_editing_controller.h" -#include "ui/events/keycodes/keyboard_codes.h" -#include "ui/gfx/font_list.h" -#include "ui/gfx/range/range.h" -#include "ui/gfx/selection_model.h" -#include "ui/gfx/text_constants.h" -#include "ui/views/context_menu_controller.h" -#include "ui/views/controls/textfield/textfield_model.h" -#include "ui/views/drag_controller.h" -#include "ui/views/view.h" - -namespace views { - -class MenuRunner; -class Painter; -class TextfieldController; - -// A views/skia textfield implementation. No platform-specific code is used. -class VIEWS_EXPORT Textfield : public View, - public TextfieldModel::Delegate, - public ContextMenuController, - public DragController, - public ui::TouchEditable, - public ui::TextInputClient { - public: - // The textfield's class name. - static const char kViewClassName[]; - - // The preferred size of the padding to be used around textfield text. - static const int kTextPadding; - - // Returns the text cursor blink time in milliseconds, or 0 for no blinking. - static size_t GetCaretBlinkMs(); - - Textfield(); - virtual ~Textfield(); - - // Set the controller for this textfield. - void set_controller(TextfieldController* controller) { - controller_ = controller; - } - - // Gets/Sets whether or not the Textfield is read-only. - bool read_only() const { return read_only_; } - void SetReadOnly(bool read_only); - - // Sets the input type; displays only asterisks for TEXT_INPUT_TYPE_PASSWORD. - void SetTextInputType(ui::TextInputType type); - - // Gets the text currently displayed in the Textfield. - const base::string16& text() const { return model_->text(); } - - // Sets the text currently displayed in the Textfield. This doesn't - // change the cursor position if the current cursor is within the - // new text's range, or moves the cursor to the end if the cursor is - // out of the new text's range. - void SetText(const base::string16& new_text); - - // Appends the given string to the previously-existing text in the field. - void AppendText(const base::string16& new_text); - - // Inserts |new_text| at the cursor position, replacing any selected text. - void InsertOrReplaceText(const base::string16& new_text); - - // Returns the text direction. - base::i18n::TextDirection GetTextDirection() const; - - // Returns the text that is currently selected. - base::string16 GetSelectedText() const; - - // Select the entire text range. If |reversed| is true, the range will end at - // the logical beginning of the text; this generally shows the leading portion - // of text that overflows its display area. - void SelectAll(bool reversed); - - // A convenience method to select the word closest to |point|. - void SelectWordAt(const gfx::Point& point); - - // Clears the selection within the edit field and sets the caret to the end. - void ClearSelection(); - - // Checks if there is any selected text. - bool HasSelection() const; - - // Gets/sets the text color to be used when painting the Textfield. - // Call UseDefaultTextColor() to restore the default system color. - SkColor GetTextColor() const; - void SetTextColor(SkColor color); - void UseDefaultTextColor(); - - // Gets/sets the background color to be used when painting the Textfield. - // Call UseDefaultBackgroundColor() to restore the default system color. - SkColor GetBackgroundColor() const; - void SetBackgroundColor(SkColor color); - void UseDefaultBackgroundColor(); - - // Gets/sets the selection text color to be used when painting the Textfield. - // Call UseDefaultSelectionTextColor() to restore the default system color. - SkColor GetSelectionTextColor() const; - void SetSelectionTextColor(SkColor color); - void UseDefaultSelectionTextColor(); - - // Gets/sets the selection background color to be used when painting the - // Textfield. Call UseDefaultSelectionBackgroundColor() to restore the default - // system color. - SkColor GetSelectionBackgroundColor() const; - void SetSelectionBackgroundColor(SkColor color); - void UseDefaultSelectionBackgroundColor(); - - // Set drop shadows underneath the text. - void SetShadows(const gfx::ShadowValues& shadows); - - // Gets/Sets whether or not the cursor is enabled. - bool GetCursorEnabled() const; - void SetCursorEnabled(bool enabled); - - // Gets/Sets the fonts used when rendering the text within the Textfield. - const gfx::FontList& GetFontList() const; - void SetFontList(const gfx::FontList& font_list); - - // Sets the default width of the text control. See default_width_in_chars_. - void set_default_width_in_chars(int default_width) { - default_width_in_chars_ = default_width; - } - - // Sets the text to display when empty. - void set_placeholder_text(const base::string16& text) { - placeholder_text_ = text; - } - virtual base::string16 GetPlaceholderText() const; - - SkColor placeholder_text_color() const { return placeholder_text_color_; } - void set_placeholder_text_color(SkColor color) { - placeholder_text_color_ = color; - } - - // Get or set the horizontal alignment used for the button from the underlying - // RenderText object. - gfx::HorizontalAlignment GetHorizontalAlignment() const; - void SetHorizontalAlignment(gfx::HorizontalAlignment alignment); - - // Displays a virtual keyboard or alternate input view if enabled. - void ShowImeIfNeeded(); - - // Returns whether or not an IME is composing text. - bool IsIMEComposing() const; - - // Gets the selected logical text range. - const gfx::Range& GetSelectedRange() const; - - // Selects the specified logical text range. - void SelectRange(const gfx::Range& range); - - // Gets the text selection model. - const gfx::SelectionModel& GetSelectionModel() const; - - // Sets the specified text selection model. - void SelectSelectionModel(const gfx::SelectionModel& sel); - - // Returns the current cursor position. - size_t GetCursorPosition() const; - - // Set the text color over the entire text or a logical character range. - // Empty and invalid ranges are ignored. - void SetColor(SkColor value); - void ApplyColor(SkColor value, const gfx::Range& range); - - // Set various text styles over the entire text or a logical character range. - // The respective |style| is applied if |value| is true, or removed if false. - // Empty and invalid ranges are ignored. - void SetStyle(gfx::TextStyle style, bool value); - void ApplyStyle(gfx::TextStyle style, bool value, const gfx::Range& range); - - // Clears Edit history. - void ClearEditHistory(); - - // Set the accessible name of the text field. - void SetAccessibleName(const base::string16& name); - - // Performs the action associated with the specified command id. - void ExecuteCommand(int command_id); - - void SetFocusPainter(scoped_ptr<Painter> focus_painter); - - // Returns whether there is a drag operation originating from the textfield. - bool HasTextBeingDragged(); - - // View overrides: - virtual gfx::Insets GetInsets() const override; - virtual int GetBaseline() const override; - virtual gfx::Size GetPreferredSize() const override; - virtual const char* GetClassName() const override; - virtual gfx::NativeCursor GetCursor(const ui::MouseEvent& event) override; - virtual bool OnMousePressed(const ui::MouseEvent& event) override; - virtual bool OnMouseDragged(const ui::MouseEvent& event) override; - virtual void OnMouseReleased(const ui::MouseEvent& event) override; - virtual bool OnKeyPressed(const ui::KeyEvent& event) override; - virtual ui::TextInputClient* GetTextInputClient() override; - virtual void OnGestureEvent(ui::GestureEvent* event) override; - virtual void AboutToRequestFocusFromTabTraversal(bool reverse) override; - virtual bool SkipDefaultKeyEventProcessing( - const ui::KeyEvent& event) override; - virtual bool GetDropFormats( - int* formats, - std::set<ui::OSExchangeData::CustomFormat>* custom_formats) override; - virtual bool CanDrop(const ui::OSExchangeData& data) override; - virtual int OnDragUpdated(const ui::DropTargetEvent& event) override; - virtual void OnDragExited() override; - virtual int OnPerformDrop(const ui::DropTargetEvent& event) override; - virtual void OnDragDone() override; - virtual void GetAccessibleState(ui::AXViewState* state) override; - virtual void OnBoundsChanged(const gfx::Rect& previous_bounds) override; - virtual bool GetNeedsNotificationWhenVisibleBoundsChange() const override; - virtual void OnVisibleBoundsChanged() override; - virtual void OnEnabledChanged() override; - virtual void OnPaint(gfx::Canvas* canvas) override; - virtual void OnFocus() override; - virtual void OnBlur() override; - virtual gfx::Point GetKeyboardContextMenuLocation() override; - virtual void OnNativeThemeChanged(const ui::NativeTheme* theme) override; - - // TextfieldModel::Delegate overrides: - virtual void OnCompositionTextConfirmedOrCleared() override; - - // ContextMenuController overrides: - virtual void ShowContextMenuForView(View* source, - const gfx::Point& point, - ui::MenuSourceType source_type) override; - - // DragController overrides: - virtual void WriteDragDataForView(View* sender, - const gfx::Point& press_pt, - ui::OSExchangeData* data) override; - virtual int GetDragOperationsForView(View* sender, - const gfx::Point& p) override; - virtual bool CanStartDragForView(View* sender, - const gfx::Point& press_pt, - const gfx::Point& p) override; - - // ui::TouchEditable overrides: - virtual void SelectRect(const gfx::Point& start, - const gfx::Point& end) override; - virtual void MoveCaretTo(const gfx::Point& point) override; - virtual void GetSelectionEndPoints(gfx::Rect* p1, gfx::Rect* p2) override; - virtual gfx::Rect GetBounds() override; - virtual gfx::NativeView GetNativeView() const override; - virtual void ConvertPointToScreen(gfx::Point* point) override; - virtual void ConvertPointFromScreen(gfx::Point* point) override; - virtual bool DrawsHandles() override; - virtual void OpenContextMenu(const gfx::Point& anchor) override; - virtual void DestroyTouchSelection() override; - - // ui::SimpleMenuModel::Delegate overrides: - virtual bool IsCommandIdChecked(int command_id) const override; - virtual bool IsCommandIdEnabled(int command_id) const override; - virtual bool GetAcceleratorForCommandId( - int command_id, - ui::Accelerator* accelerator) override; - virtual void ExecuteCommand(int command_id, int event_flags) override; - - // ui::TextInputClient overrides: - virtual void SetCompositionText( - const ui::CompositionText& composition) override; - virtual void ConfirmCompositionText() override; - virtual void ClearCompositionText() override; - virtual void InsertText(const base::string16& text) override; - virtual void InsertChar(base::char16 ch, int flags) override; - virtual gfx::NativeWindow GetAttachedWindow() const override; - virtual ui::TextInputType GetTextInputType() const override; - virtual ui::TextInputMode GetTextInputMode() const override; - virtual bool CanComposeInline() const override; - virtual gfx::Rect GetCaretBounds() const override; - virtual bool GetCompositionCharacterBounds(uint32 index, - gfx::Rect* rect) const override; - virtual bool HasCompositionText() const override; - virtual bool GetTextRange(gfx::Range* range) const override; - virtual bool GetCompositionTextRange(gfx::Range* range) const override; - virtual bool GetSelectionRange(gfx::Range* range) const override; - virtual bool SetSelectionRange(const gfx::Range& range) override; - virtual bool DeleteRange(const gfx::Range& range) override; - virtual bool GetTextFromRange(const gfx::Range& range, - base::string16* text) const override; - virtual void OnInputMethodChanged() override; - virtual bool ChangeTextDirectionAndLayoutAlignment( - base::i18n::TextDirection direction) override; - virtual void ExtendSelectionAndDelete(size_t before, size_t after) override; - virtual void EnsureCaretInRect(const gfx::Rect& rect) override; - virtual void OnCandidateWindowShown() override; - virtual void OnCandidateWindowUpdated() override; - virtual void OnCandidateWindowHidden() override; - virtual bool IsEditingCommandEnabled(int command_id) override; - virtual void ExecuteEditingCommand(int command_id) override; - - protected: - // Returns the TextfieldModel's text/cursor/selection rendering model. - gfx::RenderText* GetRenderText() const; - - gfx::Point last_click_location() const { return last_click_location_; } - - // Get the text from the selection clipboard. - virtual base::string16 GetSelectionClipboardText() const; - - private: - friend class TextfieldTestApi; - - // Handles a request to change the value of this text field from software - // using an accessibility API (typically automation software, screen readers - // don't normally use this). Sets the value and clears the selection. - void AccessibilitySetValue(const base::string16& new_value); - - // Updates the painted background color. - void UpdateBackgroundColor(); - - // Does necessary updates when the text and/or cursor position changes. - void UpdateAfterChange(bool text_changed, bool cursor_changed); - - // A callback function to periodically update the cursor state. - void UpdateCursor(); - - // Repaint the cursor. - void RepaintCursor(); - - void PaintTextAndCursor(gfx::Canvas* canvas); - - // Helper function to call MoveCursorTo on the TextfieldModel. - void MoveCursorTo(const gfx::Point& point, bool select); - - // Helper function to update the selection on a mouse drag. - void SelectThroughLastDragLocation(); - - // Convenience method to notify the InputMethod and TouchSelectionController. - void OnCaretBoundsChanged(); - - // Convenience method to call TextfieldController::OnBeforeUserAction(); - void OnBeforeUserAction(); - - // Convenience method to call TextfieldController::OnAfterUserAction(); - void OnAfterUserAction(); - - // Calls |model_->Cut()| and notifies TextfieldController on success. - bool Cut(); - - // Calls |model_->Copy()| and notifies TextfieldController on success. - bool Copy(); - - // Calls |model_->Paste()| and calls TextfieldController::ContentsChanged() - // explicitly if paste succeeded. - bool Paste(); - - // Utility function to prepare the context menu. - void UpdateContextMenu(); - - // Tracks the mouse clicks for single/double/triple clicks. - void TrackMouseClicks(const ui::MouseEvent& event); - - // Returns true if the current text input type allows access by the IME. - bool ImeEditingAllowed() const; - - // Reveals the password character at |index| for a set duration. - // If |index| is -1, the existing revealed character will be reset. - void RevealPasswordChar(int index); - - void CreateTouchSelectionControllerAndNotifyIt(); - - // Updates the selection clipboard to any non-empty text selection. - void UpdateSelectionClipboard() const; - - // Pastes the selection clipboard for the specified mouse event. - void PasteSelectionClipboard(const ui::MouseEvent& event); - - // The text model. - scoped_ptr<TextfieldModel> model_; - - // This is the current listener for events from this Textfield. - TextfieldController* controller_; - - // True if this Textfield cannot accept input and is read-only. - bool read_only_; - - // The default number of average characters for the width of this text field. - // This will be reported as the "desired size". Defaults to 0. - int default_width_in_chars_; - - scoped_ptr<Painter> focus_painter_; - - // Flags indicating whether various system colors should be used, and if not, - // what overriding color values should be used instead. - bool use_default_text_color_; - bool use_default_background_color_; - bool use_default_selection_text_color_; - bool use_default_selection_background_color_; - SkColor text_color_; - SkColor background_color_; - SkColor selection_text_color_; - SkColor selection_background_color_; - - // Text to display when empty. - base::string16 placeholder_text_; - - // Placeholder text color. - SkColor placeholder_text_color_; - - // The accessible name of the text field. - base::string16 accessible_name_; - - // The input type of this text field. - ui::TextInputType text_input_type_; - - // The duration and timer to reveal the last typed password character. - base::TimeDelta password_reveal_duration_; - base::OneShotTimer<Textfield> password_reveal_timer_; - - // Tracks whether a user action is being performed; i.e. OnBeforeUserAction() - // has been called, but OnAfterUserAction() has not yet been called. - bool performing_user_action_; - - // True if InputMethod::CancelComposition() should not be called. - bool skip_input_method_cancel_composition_; - - // The text editing cursor repaint timer and visibility. - base::RepeatingTimer<Textfield> cursor_repaint_timer_; - bool cursor_visible_; - - // The drop cursor is a visual cue for where dragged text will be dropped. - bool drop_cursor_visible_; - gfx::SelectionModel drop_cursor_position_; - - // Is the user potentially dragging and dropping from this view? - bool initiating_drag_; - - // A timer and point used to modify the selection when dragging. - base::RepeatingTimer<Textfield> drag_selection_timer_; - gfx::Point last_drag_location_; - - // State variables used to track double and triple clicks. - size_t aggregated_clicks_; - base::TimeDelta last_click_time_; - gfx::Point last_click_location_; - gfx::Range double_click_word_; - - scoped_ptr<ui::TouchSelectionController> touch_selection_controller_; - - // Used to track touch drag starting location and offset to enable touch - // scrolling. - gfx::Point drag_start_location_; - int drag_start_display_offset_; - - // Tracks if touch editing handles are hidden because user has started - // scrolling. If |true|, handles are shown after scrolling ends. - bool touch_handles_hidden_due_to_scroll_; - - // Context menu related members. - scoped_ptr<ui::SimpleMenuModel> context_menu_contents_; - scoped_ptr<views::MenuRunner> context_menu_runner_; - - // Used to bind callback functions to this object. - base::WeakPtrFactory<Textfield> weak_ptr_factory_; - - DISALLOW_COPY_AND_ASSIGN(Textfield); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_TEXTFIELD_TEXTFIELD_H_
diff --git a/ui/views/controls/textfield/textfield_controller.cc b/ui/views/controls/textfield/textfield_controller.cc deleted file mode 100644 index 1d90f3c..0000000 --- a/ui/views/controls/textfield/textfield_controller.cc +++ /dev/null
@@ -1,26 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/textfield/textfield_controller.h" - -#include "ui/base/dragdrop/drag_drop_types.h" -#include "ui/events/event.h" - -namespace views { - -bool TextfieldController::HandleKeyEvent(Textfield* sender, - const ui::KeyEvent& key_event) { - return false; -} - -bool TextfieldController::HandleMouseEvent(Textfield* sender, - const ui::MouseEvent& mouse_event) { - return false; -} - -int TextfieldController::OnDrop(const ui::OSExchangeData& data) { - return ui::DragDropTypes::DRAG_NONE; -} - -} // namespace views
diff --git a/ui/views/controls/textfield/textfield_controller.h b/ui/views/controls/textfield/textfield_controller.h deleted file mode 100644 index 4a01d38..0000000 --- a/ui/views/controls/textfield/textfield_controller.h +++ /dev/null
@@ -1,88 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_TEXTFIELD_TEXTFIELD_CONTROLLER_H_ -#define UI_VIEWS_CONTROLS_TEXTFIELD_TEXTFIELD_CONTROLLER_H_ - -#include <set> - -#include "base/strings/string16.h" -#include "ui/base/dragdrop/os_exchange_data.h" -#include "ui/views/views_export.h" - -namespace ui { -class KeyEvent; -class MouseEvent; -class SimpleMenuModel; -} // namespace ui - -namespace views { - -class Textfield; - -// This defines the callback interface for other code to be notified of changes -// in the state of a text field. -class VIEWS_EXPORT TextfieldController { - public: - // This method is called whenever the text in the field is changed by the - // user. It won't be called if the text is changed by calling - // Textfield::SetText() or Textfield::AppendText(). - virtual void ContentsChanged(Textfield* sender, - const base::string16& new_contents) {} - - // This method is called to get notified about keystrokes in the edit. - // Returns true if the message was handled and should not be processed - // further. If it returns false the processing continues. - virtual bool HandleKeyEvent(Textfield* sender, - const ui::KeyEvent& key_event); - - // This method is called to get notified about mouse events in the edit. - // Returns true if the message was handled and should not be processed - // further. Currently, only mouse down events are sent here. - virtual bool HandleMouseEvent(Textfield* sender, - const ui::MouseEvent& mouse_event); - - // Called before performing a user action that may change the textfield. - // It's currently only supported by Views implementation. - virtual void OnBeforeUserAction(Textfield* sender) {} - - // Called after performing a user action that may change the textfield. - // It's currently only supported by Views implementation. - virtual void OnAfterUserAction(Textfield* sender) {} - - // Called after performing a Cut or Copy operation. - virtual void OnAfterCutOrCopy(ui::ClipboardType clipboard_type) {} - - // Called after performing a Paste operation. - virtual void OnAfterPaste() {} - - // Called after the textfield has written drag data to give the controller a - // chance to modify the drag data. - virtual void OnWriteDragData(ui::OSExchangeData* data) {} - - // Called after the textfield has set default drag operations to give the - // controller a chance to update them. - virtual void OnGetDragOperationsForTextfield(int* drag_operations) {} - - // Enables the controller to append to the accepted drop formats. - virtual void AppendDropFormats( - int* formats, - std::set<ui::OSExchangeData::CustomFormat>* custom_formats) {} - - // Called when a drop of dragged data happens on the textfield. This method is - // called before regular handling of the drop. If this returns a drag - // operation other than |ui::DragDropTypes::DRAG_NONE|, regular handling is - // skipped. - virtual int OnDrop(const ui::OSExchangeData& data); - - // Gives the controller a chance to modify the context menu contents. - virtual void UpdateContextMenu(ui::SimpleMenuModel* menu_contents) {} - - protected: - virtual ~TextfieldController() {} -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_TEXTFIELD_TEXTFIELD_CONTROLLER_H_
diff --git a/ui/views/controls/textfield/textfield_model.cc b/ui/views/controls/textfield/textfield_model.cc deleted file mode 100644 index fba7e11..0000000 --- a/ui/views/controls/textfield/textfield_model.cc +++ /dev/null
@@ -1,769 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/textfield/textfield_model.h" - -#include <algorithm> - -#include "base/logging.h" -#include "base/stl_util.h" -#include "ui/base/clipboard/clipboard.h" -#include "ui/base/clipboard/scoped_clipboard_writer.h" -#include "ui/gfx/range/range.h" -#include "ui/gfx/utf16_indexing.h" - -namespace views { - -namespace internal { - -// Edit holds state information to undo/redo editing changes. Editing operations -// are merged when possible, like when characters are typed in sequence. Calling -// Commit() marks an edit as an independent operation that shouldn't be merged. -class Edit { - public: - enum Type { - INSERT_EDIT, - DELETE_EDIT, - REPLACE_EDIT, - }; - - virtual ~Edit() {} - - // Revert the change made by this edit in |model|. - void Undo(TextfieldModel* model) { - model->ModifyText(new_text_start_, new_text_end(), - old_text_, old_text_start_, - old_cursor_pos_); - } - - // Apply the change of this edit to the |model|. - void Redo(TextfieldModel* model) { - model->ModifyText(old_text_start_, old_text_end(), - new_text_, new_text_start_, - new_cursor_pos_); - } - - // Try to merge the |edit| into this edit and returns true on success. The - // merged edit will be deleted after redo and should not be reused. - bool Merge(const Edit* edit) { - // Don't merge if previous edit is DELETE. This happens when a - // user deletes characters then hits return. In this case, the - // delete should be treated as separate edit that can be undone - // and should not be merged with the replace edit. - if (type_ != DELETE_EDIT && edit->force_merge()) { - MergeReplace(edit); - return true; - } - return mergeable() && edit->mergeable() && DoMerge(edit); - } - - // Commits the edit and marks as un-mergeable. - void Commit() { merge_type_ = DO_NOT_MERGE; } - - private: - friend class InsertEdit; - friend class ReplaceEdit; - friend class DeleteEdit; - - Edit(Type type, - MergeType merge_type, - size_t old_cursor_pos, - const base::string16& old_text, - size_t old_text_start, - bool delete_backward, - size_t new_cursor_pos, - const base::string16& new_text, - size_t new_text_start) - : type_(type), - merge_type_(merge_type), - old_cursor_pos_(old_cursor_pos), - old_text_(old_text), - old_text_start_(old_text_start), - delete_backward_(delete_backward), - new_cursor_pos_(new_cursor_pos), - new_text_(new_text), - new_text_start_(new_text_start) { - } - - // Each type of edit provides its own specific merge implementation. - virtual bool DoMerge(const Edit* edit) = 0; - - Type type() const { return type_; } - - // Can this edit be merged? - bool mergeable() const { return merge_type_ == MERGEABLE; } - - // Should this edit be forcibly merged with the previous edit? - bool force_merge() const { return merge_type_ == FORCE_MERGE; } - - // Returns the end index of the |old_text_|. - size_t old_text_end() const { return old_text_start_ + old_text_.length(); } - - // Returns the end index of the |new_text_|. - size_t new_text_end() const { return new_text_start_ + new_text_.length(); } - - // Merge the replace edit into the current edit. This handles the special case - // where an omnibox autocomplete string is set after a new character is typed. - void MergeReplace(const Edit* edit) { - CHECK_EQ(REPLACE_EDIT, edit->type_); - CHECK_EQ(0U, edit->old_text_start_); - CHECK_EQ(0U, edit->new_text_start_); - base::string16 old_text = edit->old_text_; - old_text.erase(new_text_start_, new_text_.length()); - old_text.insert(old_text_start_, old_text_); - // SetText() replaces entire text. Set |old_text_| to the entire - // replaced text with |this| edit undone. - old_text_ = old_text; - old_text_start_ = edit->old_text_start_; - delete_backward_ = false; - - new_text_ = edit->new_text_; - new_text_start_ = edit->new_text_start_; - merge_type_ = DO_NOT_MERGE; - } - - Type type_; - - // True if the edit can be marged. - MergeType merge_type_; - // Old cursor position. - size_t old_cursor_pos_; - // Deleted text by this edit. - base::string16 old_text_; - // The index of |old_text_|. - size_t old_text_start_; - // True if the deletion is made backward. - bool delete_backward_; - // New cursor position. - size_t new_cursor_pos_; - // Added text. - base::string16 new_text_; - // The index of |new_text_| - size_t new_text_start_; - - DISALLOW_COPY_AND_ASSIGN(Edit); -}; - -class InsertEdit : public Edit { - public: - InsertEdit(bool mergeable, const base::string16& new_text, size_t at) - : Edit(INSERT_EDIT, - mergeable ? MERGEABLE : DO_NOT_MERGE, - at /* old cursor */, - base::string16(), - at, - false /* N/A */, - at + new_text.length() /* new cursor */, - new_text, - at) { - } - - // Edit implementation. - virtual bool DoMerge(const Edit* edit) override { - if (edit->type() != INSERT_EDIT || new_text_end() != edit->new_text_start_) - return false; - // If continuous edit, merge it. - // TODO(oshima): gtk splits edits between whitespace. Find out what - // we want to here and implement if necessary. - new_text_ += edit->new_text_; - new_cursor_pos_ = edit->new_cursor_pos_; - return true; - } -}; - -class ReplaceEdit : public Edit { - public: - ReplaceEdit(MergeType merge_type, - const base::string16& old_text, - size_t old_cursor_pos, - size_t old_text_start, - bool backward, - size_t new_cursor_pos, - const base::string16& new_text, - size_t new_text_start) - : Edit(REPLACE_EDIT, merge_type, - old_cursor_pos, - old_text, - old_text_start, - backward, - new_cursor_pos, - new_text, - new_text_start) { - } - - // Edit implementation. - virtual bool DoMerge(const Edit* edit) override { - if (edit->type() == DELETE_EDIT || - new_text_end() != edit->old_text_start_ || - edit->old_text_start_ != edit->new_text_start_) - return false; - old_text_ += edit->old_text_; - new_text_ += edit->new_text_; - new_cursor_pos_ = edit->new_cursor_pos_; - return true; - } -}; - -class DeleteEdit : public Edit { - public: - DeleteEdit(bool mergeable, - const base::string16& text, - size_t text_start, - bool backward) - : Edit(DELETE_EDIT, - mergeable ? MERGEABLE : DO_NOT_MERGE, - (backward ? text_start + text.length() : text_start), - text, - text_start, - backward, - text_start, - base::string16(), - text_start) { - } - - // Edit implementation. - virtual bool DoMerge(const Edit* edit) override { - if (edit->type() != DELETE_EDIT) - return false; - - if (delete_backward_) { - // backspace can be merged only with backspace at the same position. - if (!edit->delete_backward_ || old_text_start_ != edit->old_text_end()) - return false; - old_text_start_ = edit->old_text_start_; - old_text_ = edit->old_text_ + old_text_; - new_cursor_pos_ = edit->new_cursor_pos_; - } else { - // delete can be merged only with delete at the same position. - if (edit->delete_backward_ || old_text_start_ != edit->old_text_start_) - return false; - old_text_ += edit->old_text_; - } - return true; - } -}; - -} // namespace internal - -namespace { - -// Returns the first segment that is visually emphasized. Usually it's used for -// representing the target clause (on Windows). Returns an invalid range if -// there is no such a range. -gfx::Range GetFirstEmphasizedRange(const ui::CompositionText& composition) { - for (size_t i = 0; i < composition.underlines.size(); ++i) { - const ui::CompositionUnderline& underline = composition.underlines[i]; - if (underline.thick) - return gfx::Range(underline.start_offset, underline.end_offset); - } - return gfx::Range::InvalidRange(); -} - -} // namespace - -using internal::Edit; -using internal::DeleteEdit; -using internal::InsertEdit; -using internal::ReplaceEdit; -using internal::MergeType; -using internal::DO_NOT_MERGE; -using internal::FORCE_MERGE; -using internal::MERGEABLE; - -///////////////////////////////////////////////////////////////// -// TextfieldModel: public - -TextfieldModel::Delegate::~Delegate() {} - -TextfieldModel::TextfieldModel(Delegate* delegate) - : delegate_(delegate), - render_text_(gfx::RenderText::CreateInstance()), - current_edit_(edit_history_.end()) { -} - -TextfieldModel::~TextfieldModel() { - ClearEditHistory(); - ClearComposition(); -} - -bool TextfieldModel::SetText(const base::string16& new_text) { - bool changed = false; - if (HasCompositionText()) { - ConfirmCompositionText(); - changed = true; - } - if (text() != new_text) { - if (changed) // No need to remember composition. - Undo(); - size_t old_cursor = GetCursorPosition(); - // SetText moves the cursor to the end. - size_t new_cursor = new_text.length(); - SelectAll(false); - // If there is a composition text, don't merge with previous edit. - // Otherwise, force merge the edits. - ExecuteAndRecordReplace(changed ? DO_NOT_MERGE : FORCE_MERGE, - old_cursor, new_cursor, new_text, 0U); - render_text_->SetCursorPosition(new_cursor); - } - ClearSelection(); - return changed; -} - -void TextfieldModel::Append(const base::string16& new_text) { - if (HasCompositionText()) - ConfirmCompositionText(); - size_t save = GetCursorPosition(); - MoveCursor(gfx::LINE_BREAK, - render_text_->GetVisualDirectionOfLogicalEnd(), - false); - InsertText(new_text); - render_text_->SetCursorPosition(save); - ClearSelection(); -} - -bool TextfieldModel::Delete() { - if (HasCompositionText()) { - // No undo/redo for composition text. - CancelCompositionText(); - return true; - } - if (HasSelection()) { - DeleteSelection(); - return true; - } - if (text().length() > GetCursorPosition()) { - size_t cursor_position = GetCursorPosition(); - size_t next_grapheme_index = render_text_->IndexOfAdjacentGrapheme( - cursor_position, gfx::CURSOR_FORWARD); - ExecuteAndRecordDelete(gfx::Range(cursor_position, next_grapheme_index), - true); - return true; - } - return false; -} - -bool TextfieldModel::Backspace() { - if (HasCompositionText()) { - // No undo/redo for composition text. - CancelCompositionText(); - return true; - } - if (HasSelection()) { - DeleteSelection(); - return true; - } - size_t cursor_position = GetCursorPosition(); - if (cursor_position > 0) { - // Delete one code point, which may be two UTF-16 words. - size_t previous_char = gfx::UTF16OffsetToIndex(text(), cursor_position, -1); - ExecuteAndRecordDelete(gfx::Range(cursor_position, previous_char), true); - return true; - } - return false; -} - -size_t TextfieldModel::GetCursorPosition() const { - return render_text_->cursor_position(); -} - -void TextfieldModel::MoveCursor(gfx::BreakType break_type, - gfx::VisualCursorDirection direction, - bool select) { - if (HasCompositionText()) - ConfirmCompositionText(); - render_text_->MoveCursor(break_type, direction, select); -} - -bool TextfieldModel::MoveCursorTo(const gfx::SelectionModel& cursor) { - if (HasCompositionText()) { - ConfirmCompositionText(); - // ConfirmCompositionText() updates cursor position. Need to reflect it in - // the SelectionModel parameter of MoveCursorTo(). - gfx::Range range(render_text_->selection().start(), cursor.caret_pos()); - if (!range.is_empty()) - return render_text_->SelectRange(range); - return render_text_->MoveCursorTo( - gfx::SelectionModel(cursor.caret_pos(), cursor.caret_affinity())); - } - return render_text_->MoveCursorTo(cursor); -} - -bool TextfieldModel::MoveCursorTo(const gfx::Point& point, bool select) { - if (HasCompositionText()) - ConfirmCompositionText(); - gfx::SelectionModel cursor = render_text_->FindCursorPosition(point); - if (select) - cursor.set_selection_start(render_text_->selection().start()); - return render_text_->MoveCursorTo(cursor); -} - -base::string16 TextfieldModel::GetSelectedText() const { - return text().substr(render_text_->selection().GetMin(), - render_text_->selection().length()); -} - -void TextfieldModel::SelectRange(const gfx::Range& range) { - if (HasCompositionText()) - ConfirmCompositionText(); - render_text_->SelectRange(range); -} - -void TextfieldModel::SelectSelectionModel(const gfx::SelectionModel& sel) { - if (HasCompositionText()) - ConfirmCompositionText(); - render_text_->MoveCursorTo(sel); -} - -void TextfieldModel::SelectAll(bool reversed) { - if (HasCompositionText()) - ConfirmCompositionText(); - render_text_->SelectAll(reversed); -} - -void TextfieldModel::SelectWord() { - if (HasCompositionText()) - ConfirmCompositionText(); - render_text_->SelectWord(); -} - -void TextfieldModel::ClearSelection() { - if (HasCompositionText()) - ConfirmCompositionText(); - render_text_->ClearSelection(); -} - -bool TextfieldModel::CanUndo() { - return edit_history_.size() && current_edit_ != edit_history_.end(); -} - -bool TextfieldModel::CanRedo() { - if (!edit_history_.size()) - return false; - // There is no redo iff the current edit is the last element in the history. - EditHistory::iterator iter = current_edit_; - return iter == edit_history_.end() || // at the top. - ++iter != edit_history_.end(); -} - -bool TextfieldModel::Undo() { - if (!CanUndo()) - return false; - DCHECK(!HasCompositionText()); - if (HasCompositionText()) - CancelCompositionText(); - - base::string16 old = text(); - size_t old_cursor = GetCursorPosition(); - (*current_edit_)->Commit(); - (*current_edit_)->Undo(this); - - if (current_edit_ == edit_history_.begin()) - current_edit_ = edit_history_.end(); - else - current_edit_--; - return old != text() || old_cursor != GetCursorPosition(); -} - -bool TextfieldModel::Redo() { - if (!CanRedo()) - return false; - DCHECK(!HasCompositionText()); - if (HasCompositionText()) - CancelCompositionText(); - - if (current_edit_ == edit_history_.end()) - current_edit_ = edit_history_.begin(); - else - current_edit_ ++; - base::string16 old = text(); - size_t old_cursor = GetCursorPosition(); - (*current_edit_)->Redo(this); - return old != text() || old_cursor != GetCursorPosition(); -} - -bool TextfieldModel::Cut() { - if (!HasCompositionText() && HasSelection() && !render_text_->obscured()) { - ui::ScopedClipboardWriter( - ui::CLIPBOARD_TYPE_COPY_PASTE).WriteText(GetSelectedText()); - // A trick to let undo/redo handle cursor correctly. - // Undoing CUT moves the cursor to the end of the change rather - // than beginning, unlike Delete/Backspace. - // TODO(oshima): Change Delete/Backspace to use DeleteSelection, - // update DeleteEdit and remove this trick. - const gfx::Range& selection = render_text_->selection(); - render_text_->SelectRange(gfx::Range(selection.end(), selection.start())); - DeleteSelection(); - return true; - } - return false; -} - -bool TextfieldModel::Copy() { - if (!HasCompositionText() && HasSelection() && !render_text_->obscured()) { - ui::ScopedClipboardWriter( - ui::CLIPBOARD_TYPE_COPY_PASTE).WriteText(GetSelectedText()); - return true; - } - return false; -} - -bool TextfieldModel::Paste() { - base::string16 result; - ui::Clipboard::GetForCurrentThread()->ReadText(ui::CLIPBOARD_TYPE_COPY_PASTE, - &result); - if (result.empty()) - return false; - - InsertTextInternal(result, false); - return true; -} - -bool TextfieldModel::HasSelection() const { - return !render_text_->selection().is_empty(); -} - -void TextfieldModel::DeleteSelection() { - DCHECK(!HasCompositionText()); - DCHECK(HasSelection()); - ExecuteAndRecordDelete(render_text_->selection(), false); -} - -void TextfieldModel::DeleteSelectionAndInsertTextAt( - const base::string16& new_text, - size_t position) { - if (HasCompositionText()) - CancelCompositionText(); - ExecuteAndRecordReplace(DO_NOT_MERGE, - GetCursorPosition(), - position + new_text.length(), - new_text, - position); -} - -base::string16 TextfieldModel::GetTextFromRange(const gfx::Range& range) const { - if (range.IsValid() && range.GetMin() < text().length()) - return text().substr(range.GetMin(), range.length()); - return base::string16(); -} - -void TextfieldModel::GetTextRange(gfx::Range* range) const { - *range = gfx::Range(0, text().length()); -} - -void TextfieldModel::SetCompositionText( - const ui::CompositionText& composition) { - if (HasCompositionText()) - CancelCompositionText(); - else if (HasSelection()) - DeleteSelection(); - - if (composition.text.empty()) - return; - - size_t cursor = GetCursorPosition(); - base::string16 new_text = text(); - render_text_->SetText(new_text.insert(cursor, composition.text)); - gfx::Range range(cursor, cursor + composition.text.length()); - render_text_->SetCompositionRange(range); - gfx::Range emphasized_range = GetFirstEmphasizedRange(composition); - if (emphasized_range.IsValid()) { - // This is a workaround due to the lack of support in RenderText to draw - // a thick underline. In a composition returned from an IME, the segment - // emphasized by a thick underline usually represents the target clause. - // Because the target clause is more important than the actual selection - // range (or caret position) in the composition here we use a selection-like - // marker instead to show this range. - // TODO(yukawa, msw): Support thick underlines and remove this workaround. - render_text_->SelectRange(gfx::Range( - cursor + emphasized_range.GetMin(), - cursor + emphasized_range.GetMax())); - } else if (!composition.selection.is_empty()) { - render_text_->SelectRange(gfx::Range( - cursor + composition.selection.GetMin(), - cursor + composition.selection.GetMax())); - } else { - render_text_->SetCursorPosition(cursor + composition.selection.end()); - } -} - -void TextfieldModel::ConfirmCompositionText() { - DCHECK(HasCompositionText()); - gfx::Range range = render_text_->GetCompositionRange(); - base::string16 composition = text().substr(range.start(), range.length()); - // TODO(oshima): current behavior on ChromeOS is a bit weird and not - // sure exactly how this should work. Find out and fix if necessary. - AddOrMergeEditHistory(new InsertEdit(false, composition, range.start())); - render_text_->SetCursorPosition(range.end()); - ClearComposition(); - if (delegate_) - delegate_->OnCompositionTextConfirmedOrCleared(); -} - -void TextfieldModel::CancelCompositionText() { - DCHECK(HasCompositionText()); - gfx::Range range = render_text_->GetCompositionRange(); - ClearComposition(); - base::string16 new_text = text(); - render_text_->SetText(new_text.erase(range.start(), range.length())); - render_text_->SetCursorPosition(range.start()); - if (delegate_) - delegate_->OnCompositionTextConfirmedOrCleared(); -} - -void TextfieldModel::ClearComposition() { - render_text_->SetCompositionRange(gfx::Range::InvalidRange()); -} - -void TextfieldModel::GetCompositionTextRange(gfx::Range* range) const { - *range = gfx::Range(render_text_->GetCompositionRange()); -} - -bool TextfieldModel::HasCompositionText() const { - return !render_text_->GetCompositionRange().is_empty(); -} - -void TextfieldModel::ClearEditHistory() { - STLDeleteElements(&edit_history_); - current_edit_ = edit_history_.end(); -} - -///////////////////////////////////////////////////////////////// -// TextfieldModel: private - -void TextfieldModel::InsertTextInternal(const base::string16& new_text, - bool mergeable) { - if (HasCompositionText()) { - CancelCompositionText(); - ExecuteAndRecordInsert(new_text, mergeable); - } else if (HasSelection()) { - ExecuteAndRecordReplaceSelection(mergeable ? MERGEABLE : DO_NOT_MERGE, - new_text); - } else { - ExecuteAndRecordInsert(new_text, mergeable); - } -} - -void TextfieldModel::ReplaceTextInternal(const base::string16& new_text, - bool mergeable) { - if (HasCompositionText()) { - CancelCompositionText(); - } else if (!HasSelection()) { - size_t cursor = GetCursorPosition(); - const gfx::SelectionModel& model = render_text_->selection_model(); - // When there is no selection, the default is to replace the next grapheme - // with |new_text|. So, need to find the index of next grapheme first. - size_t next = - render_text_->IndexOfAdjacentGrapheme(cursor, gfx::CURSOR_FORWARD); - if (next == model.caret_pos()) - render_text_->MoveCursorTo(model); - else - render_text_->SelectRange(gfx::Range(next, model.caret_pos())); - } - // Edit history is recorded in InsertText. - InsertTextInternal(new_text, mergeable); -} - -void TextfieldModel::ClearRedoHistory() { - if (edit_history_.begin() == edit_history_.end()) - return; - if (current_edit_ == edit_history_.end()) { - ClearEditHistory(); - return; - } - EditHistory::iterator delete_start = current_edit_; - delete_start++; - STLDeleteContainerPointers(delete_start, edit_history_.end()); - edit_history_.erase(delete_start, edit_history_.end()); -} - -void TextfieldModel::ExecuteAndRecordDelete(gfx::Range range, bool mergeable) { - size_t old_text_start = range.GetMin(); - const base::string16 old_text = text().substr(old_text_start, range.length()); - bool backward = range.is_reversed(); - Edit* edit = new DeleteEdit(mergeable, old_text, old_text_start, backward); - bool delete_edit = AddOrMergeEditHistory(edit); - edit->Redo(this); - if (delete_edit) - delete edit; -} - -void TextfieldModel::ExecuteAndRecordReplaceSelection( - MergeType merge_type, - const base::string16& new_text) { - size_t new_text_start = render_text_->selection().GetMin(); - size_t new_cursor_pos = new_text_start + new_text.length(); - ExecuteAndRecordReplace(merge_type, - GetCursorPosition(), - new_cursor_pos, - new_text, - new_text_start); -} - -void TextfieldModel::ExecuteAndRecordReplace(MergeType merge_type, - size_t old_cursor_pos, - size_t new_cursor_pos, - const base::string16& new_text, - size_t new_text_start) { - size_t old_text_start = render_text_->selection().GetMin(); - bool backward = render_text_->selection().is_reversed(); - Edit* edit = new ReplaceEdit(merge_type, - GetSelectedText(), - old_cursor_pos, - old_text_start, - backward, - new_cursor_pos, - new_text, - new_text_start); - bool delete_edit = AddOrMergeEditHistory(edit); - edit->Redo(this); - if (delete_edit) - delete edit; -} - -void TextfieldModel::ExecuteAndRecordInsert(const base::string16& new_text, - bool mergeable) { - Edit* edit = new InsertEdit(mergeable, new_text, GetCursorPosition()); - bool delete_edit = AddOrMergeEditHistory(edit); - edit->Redo(this); - if (delete_edit) - delete edit; -} - -bool TextfieldModel::AddOrMergeEditHistory(Edit* edit) { - ClearRedoHistory(); - - if (current_edit_ != edit_history_.end() && (*current_edit_)->Merge(edit)) { - // If a current edit exists and has been merged with a new edit, don't add - // to the history, and return true to delete |edit| after redo. - return true; - } - edit_history_.push_back(edit); - if (current_edit_ == edit_history_.end()) { - // If there is no redoable edit, this is the 1st edit because RedoHistory - // has been already deleted. - DCHECK_EQ(1u, edit_history_.size()); - current_edit_ = edit_history_.begin(); - } else { - current_edit_++; - } - return false; -} - -void TextfieldModel::ModifyText(size_t delete_from, - size_t delete_to, - const base::string16& new_text, - size_t new_text_insert_at, - size_t new_cursor_pos) { - DCHECK_LE(delete_from, delete_to); - base::string16 old_text = text(); - ClearComposition(); - if (delete_from != delete_to) - render_text_->SetText(old_text.erase(delete_from, delete_to - delete_from)); - if (!new_text.empty()) - render_text_->SetText(old_text.insert(new_text_insert_at, new_text)); - render_text_->SetCursorPosition(new_cursor_pos); - // TODO(oshima): Select text that was just undone, like Mac (but not GTK). -} - -} // namespace views
diff --git a/ui/views/controls/textfield/textfield_model.h b/ui/views/controls/textfield/textfield_model.h deleted file mode 100644 index 6ae3398..0000000 --- a/ui/views/controls/textfield/textfield_model.h +++ /dev/null
@@ -1,292 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_TEXTFIELD_TEXTFIELD_MODEL_H_ -#define UI_VIEWS_CONTROLS_TEXTFIELD_TEXTFIELD_MODEL_H_ - -#include <list> -#include <vector> - -#include "base/gtest_prod_util.h" -#include "base/memory/scoped_ptr.h" -#include "base/strings/string16.h" -#include "ui/base/ime/composition_text.h" -#include "ui/gfx/render_text.h" -#include "ui/gfx/text_constants.h" -#include "ui/views/views_export.h" - -namespace views { - -namespace internal { -// Internal Edit class that keeps track of edits for undo/redo. -class Edit; - -// The types of merge behavior implemented by Edit operations. -enum MergeType { - // The edit should not usually be merged with next edit. - DO_NOT_MERGE, - // The edit should be merged with next edit when possible. - MERGEABLE, - // The edit should be merged with the prior edit, even if marked DO_NOT_MERGE. - FORCE_MERGE, -}; - -} // namespace internal - -// A model that represents text content for a views::Textfield. -// It supports editing, selection and cursor manipulation. -class VIEWS_EXPORT TextfieldModel { - public: - // Delegate interface implemented by the textfield view class to provide - // additional functionalities required by the model. - class VIEWS_EXPORT Delegate { - public: - // Called when the current composition text is confirmed or cleared. - virtual void OnCompositionTextConfirmedOrCleared() = 0; - - protected: - virtual ~Delegate(); - }; - - explicit TextfieldModel(Delegate* delegate); - virtual ~TextfieldModel(); - - // Edit related methods. - - const base::string16& text() const { return render_text_->text(); } - // Sets the text. Returns true if the text has been modified. The current - // composition text will be confirmed first. Setting the same text will not - // add edit history because it's not user visible change nor user-initiated - // change. This allow a client code to set the same text multiple times - // without worrying about messing edit history. - bool SetText(const base::string16& new_text); - - gfx::RenderText* render_text() { return render_text_.get(); } - - // Inserts given |new_text| at the current cursor position. - // The current composition text will be cleared. - void InsertText(const base::string16& new_text) { - InsertTextInternal(new_text, false); - } - - // Inserts a character at the current cursor position. - void InsertChar(base::char16 c) { - InsertTextInternal(base::string16(&c, 1), true); - } - - // Replaces characters at the current position with characters in given text. - // The current composition text will be cleared. - void ReplaceText(const base::string16& new_text) { - ReplaceTextInternal(new_text, false); - } - - // Replaces the char at the current position with given character. - void ReplaceChar(base::char16 c) { - ReplaceTextInternal(base::string16(&c, 1), true); - } - - // Appends the text. - // The current composition text will be confirmed. - void Append(const base::string16& new_text); - - // Deletes the first character after the current cursor position (as if, the - // the user has pressed delete key in the textfield). Returns true if - // the deletion is successful. - // If there is composition text, it'll be deleted instead. - bool Delete(); - - // Deletes the first character before the current cursor position (as if, the - // the user has pressed backspace key in the textfield). Returns true if - // the removal is successful. - // If there is composition text, it'll be deleted instead. - bool Backspace(); - - // Cursor related methods. - - // Returns the current cursor position. - size_t GetCursorPosition() const; - - // Moves the cursor, see RenderText for additional details. - // The current composition text will be confirmed. - void MoveCursor(gfx::BreakType break_type, - gfx::VisualCursorDirection direction, - bool select); - - // Updates the cursor to the specified selection model. Any composition text - // will be confirmed, which may alter the specified selection range start. - bool MoveCursorTo(const gfx::SelectionModel& cursor); - - // Helper function to call MoveCursorTo on the TextfieldModel. - bool MoveCursorTo(const gfx::Point& point, bool select); - - // Selection related methods. - - // Returns the selected text. - base::string16 GetSelectedText() const; - - // The current composition text will be confirmed. The selection starts with - // the range's start position, and ends with the range's end position, - // therefore the cursor position becomes the end position. - void SelectRange(const gfx::Range& range); - - // The current composition text will be confirmed. - // render_text_'s selection model is set to |sel|. - void SelectSelectionModel(const gfx::SelectionModel& sel); - - // Select the entire text range. If |reversed| is true, the range will end at - // the logical beginning of the text; this generally shows the leading portion - // of text that overflows its display area. - // The current composition text will be confirmed. - void SelectAll(bool reversed); - - // Selects the word at which the cursor is currently positioned. If there is a - // non-empty selection, the selection bounds are extended to their nearest - // word boundaries. - // The current composition text will be confirmed. - void SelectWord(); - - // Clears selection. - // The current composition text will be confirmed. - void ClearSelection(); - - // Returns true if there is an undoable edit. - bool CanUndo(); - - // Returns true if there is an redoable edit. - bool CanRedo(); - - // Undo edit. Returns true if undo changed the text. - bool Undo(); - - // Redo edit. Returns true if redo changed the text. - bool Redo(); - - // Cuts the currently selected text and puts it to clipboard. Returns true - // if text has changed after cutting. - bool Cut(); - - // Copies the currently selected text and puts it to clipboard. Returns true - // if something was copied to the clipboard. - bool Copy(); - - // Pastes text from the clipboard at current cursor position. Returns true - // if any text is pasted. - bool Paste(); - - // Tells if any text is selected, even if the selection is in composition - // text. - bool HasSelection() const; - - // Deletes the selected text. This method shouldn't be called with - // composition text. - void DeleteSelection(); - - // Deletes the selected text (if any) and insert text at given position. - void DeleteSelectionAndInsertTextAt(const base::string16& new_text, - size_t position); - - // Retrieves the text content in a given range. - base::string16 GetTextFromRange(const gfx::Range& range) const; - - // Retrieves the range containing all text in the model. - void GetTextRange(gfx::Range* range) const; - - // Sets composition text and attributes. If there is composition text already, - // it'll be replaced by the new one. Otherwise, current selection will be - // replaced. If there is no selection, the composition text will be inserted - // at the insertion point. - // Any changes to the model except text insertion will confirm the current - // composition text. - void SetCompositionText(const ui::CompositionText& composition); - - // Converts current composition text into final content. - void ConfirmCompositionText(); - - // Removes current composition text. - void CancelCompositionText(); - - // Retrieves the range of current composition text. - void GetCompositionTextRange(gfx::Range* range) const; - - // Returns true if there is composition text. - bool HasCompositionText() const; - - // Clears all edit history. - void ClearEditHistory(); - - private: - friend class internal::Edit; - - FRIEND_TEST_ALL_PREFIXES(TextfieldModelTest, UndoRedo_BasicTest); - FRIEND_TEST_ALL_PREFIXES(TextfieldModelTest, UndoRedo_CutCopyPasteTest); - FRIEND_TEST_ALL_PREFIXES(TextfieldModelTest, UndoRedo_ReplaceTest); - - // Insert the given |new_text|. |mergeable| indicates if this insert operation - // can be merged with previous edits in the history. - void InsertTextInternal(const base::string16& new_text, bool mergeable); - - // Replace the current text with the given |new_text|. |mergeable| indicates - // if this replace operation can be merged with previous edits in the history. - void ReplaceTextInternal(const base::string16& new_text, bool mergeable); - - // Clears redo history. - void ClearRedoHistory(); - - // Executes and records edit operations. - void ExecuteAndRecordDelete(gfx::Range range, bool mergeable); - void ExecuteAndRecordReplaceSelection(internal::MergeType merge_type, - const base::string16& new_text); - void ExecuteAndRecordReplace(internal::MergeType merge_type, - size_t old_cursor_pos, - size_t new_cursor_pos, - const base::string16& new_text, - size_t new_text_start); - void ExecuteAndRecordInsert(const base::string16& new_text, bool mergeable); - - // Adds or merge |edit| into edit history. Return true if the edit - // has been merged and must be deleted after redo. - bool AddOrMergeEditHistory(internal::Edit* edit); - - // Modify the text buffer in following way: - // 1) Delete the string from |delete_from| to |delte_to|. - // 2) Insert the |new_text| at the index |new_text_insert_at|. - // Note that the index is after deletion. - // 3) Move the cursor to |new_cursor_pos|. - void ModifyText(size_t delete_from, - size_t delete_to, - const base::string16& new_text, - size_t new_text_insert_at, - size_t new_cursor_pos); - - void ClearComposition(); - - // The TextfieldModel::Delegate instance should be provided by the owner. - Delegate* delegate_; - - // The stylized text, cursor, selection, and the visual layout model. - scoped_ptr<gfx::RenderText> render_text_; - - typedef std::list<internal::Edit*> EditHistory; - EditHistory edit_history_; - - // An iterator that points to the current edit that can be undone. - // This iterator moves from the |end()|, meaining no edit to undo, - // to the last element (one before |end()|), meaning no edit to redo. - // - // There is no edit to undo (== end()) when: - // 1) in initial state. (nothing to undo) - // 2) very 1st edit is undone. - // 3) all edit history is removed. - // There is no edit to redo (== last element or no element) when: - // 1) in initial state. (nothing to redo) - // 2) new edit is added. (redo history is cleared) - // 3) redone all undone edits. - EditHistory::iterator current_edit_; - - DISALLOW_COPY_AND_ASSIGN(TextfieldModel); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_TEXTFIELD_TEXTFIELD_MODEL_H_
diff --git a/ui/views/controls/textfield/textfield_model_unittest.cc b/ui/views/controls/textfield/textfield_model_unittest.cc deleted file mode 100644 index e5b1dfd..0000000 --- a/ui/views/controls/textfield/textfield_model_unittest.cc +++ /dev/null
@@ -1,1482 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <vector> - -#include "base/auto_reset.h" -#include "base/memory/scoped_ptr.h" -#include "base/message_loop/message_loop.h" -#include "base/strings/string16.h" -#include "base/strings/utf_string_conversions.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/base/clipboard/clipboard.h" -#include "ui/base/clipboard/scoped_clipboard_writer.h" -#include "ui/gfx/range/range.h" -#include "ui/gfx/render_text.h" -#include "ui/views/controls/textfield/textfield.h" -#include "ui/views/controls/textfield/textfield_model.h" -#include "ui/views/test/test_views_delegate.h" -#include "ui/views/test/views_test_base.h" - -#if defined(OS_WIN) -#include "base/win/windows_version.h" -#endif - -#define EXPECT_STR_EQ(ascii, utf16) EXPECT_EQ(base::ASCIIToUTF16(ascii), utf16) - -namespace { - -struct WordAndCursor { - WordAndCursor(const wchar_t* w, size_t c) : word(w), cursor(c) {} - - const wchar_t* word; - size_t cursor; -}; - -void MoveCursorTo(views::TextfieldModel& model, size_t pos) { - model.MoveCursorTo(gfx::SelectionModel(pos, gfx::CURSOR_FORWARD)); -} - -} // namespace - -namespace views { - -class TextfieldModelTest : public ViewsTestBase, - public TextfieldModel::Delegate { - public: - TextfieldModelTest() - : ViewsTestBase(), - composition_text_confirmed_or_cleared_(false) { - } - - virtual void OnCompositionTextConfirmedOrCleared() override { - composition_text_confirmed_or_cleared_ = true; - } - - protected: - void ResetModel(TextfieldModel* model) const { - model->SetText(base::string16()); - model->ClearEditHistory(); - } - - bool composition_text_confirmed_or_cleared_; - - private: - DISALLOW_COPY_AND_ASSIGN(TextfieldModelTest); -}; - -TEST_F(TextfieldModelTest, EditString) { - TextfieldModel model(NULL); - // Append two strings. - model.Append(base::ASCIIToUTF16("HILL")); - EXPECT_STR_EQ("HILL", model.text()); - model.Append(base::ASCIIToUTF16("WORLD")); - EXPECT_STR_EQ("HILLWORLD", model.text()); - - // Insert "E" and replace "I" with "L" to make "HELLO". - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, false); - model.InsertChar('E'); - EXPECT_STR_EQ("HEILLWORLD", model.text()); - model.ReplaceChar('L'); - EXPECT_STR_EQ("HELLLWORLD", model.text()); - model.ReplaceChar('L'); - model.ReplaceChar('O'); - EXPECT_STR_EQ("HELLOWORLD", model.text()); - - // Delete 6th char "W", then delete 5th char "O". - EXPECT_EQ(5U, model.GetCursorPosition()); - EXPECT_TRUE(model.Delete()); - EXPECT_STR_EQ("HELLOORLD", model.text()); - EXPECT_TRUE(model.Backspace()); - EXPECT_EQ(4U, model.GetCursorPosition()); - EXPECT_STR_EQ("HELLORLD", model.text()); - - // Move the cursor to start; backspace should fail. - model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_LEFT, false); - EXPECT_FALSE(model.Backspace()); - EXPECT_STR_EQ("HELLORLD", model.text()); - // Move the cursor to the end; delete should fail, but backspace should work. - model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, false); - EXPECT_FALSE(model.Delete()); - EXPECT_STR_EQ("HELLORLD", model.text()); - EXPECT_TRUE(model.Backspace()); - EXPECT_STR_EQ("HELLORL", model.text()); - - MoveCursorTo(model, 5); - model.ReplaceText(base::ASCIIToUTF16(" WOR")); - EXPECT_STR_EQ("HELLO WORL", model.text()); -} - -TEST_F(TextfieldModelTest, EditString_SimpleRTL) { - TextfieldModel model(NULL); - // Append two strings. - model.Append(base::WideToUTF16(L"\x05d0\x05d1\x05d2")); - EXPECT_EQ(base::WideToUTF16(L"\x05d0\x05d1\x05d2"), model.text()); - model.Append(base::WideToUTF16(L"\x05e0\x05e1\x05e2")); - EXPECT_EQ(base::WideToUTF16(L"\x05d0\x05d1\x05d2\x05e0\x05e1\x05e2"), - model.text()); - - // Insert "\x05f0". - MoveCursorTo(model, 1); - model.InsertChar(0x05f0); - EXPECT_EQ(base::WideToUTF16(L"\x05d0\x05f0\x05d1\x05d2\x05e0\x05e1\x05e2"), - model.text()); - - // Replace "\x05d1" with "\x05f1". - model.ReplaceChar(0x05f1); - EXPECT_EQ(base::WideToUTF16(L"\x05d0\x05f0\x5f1\x05d2\x05e0\x05e1\x05e2"), - model.text()); - - // Test Delete and backspace. - EXPECT_EQ(3U, model.GetCursorPosition()); - EXPECT_TRUE(model.Delete()); - EXPECT_EQ(base::WideToUTF16(L"\x05d0\x05f0\x5f1\x05e0\x05e1\x05e2"), - model.text()); - EXPECT_TRUE(model.Backspace()); - EXPECT_EQ(2U, model.GetCursorPosition()); - EXPECT_EQ(base::WideToUTF16(L"\x05d0\x05f0\x05e0\x05e1\x05e2"), model.text()); -} - -TEST_F(TextfieldModelTest, EditString_ComplexScript) { - // TODO(msw): XP fails due to lack of font support: http://crbug.com/106450 - bool on_windows_xp = false; -#if defined(OS_WIN) - on_windows_xp = base::win::GetVersion() < base::win::VERSION_VISTA; -#endif - - TextfieldModel model(NULL); - - // Append two Hindi strings. - model.Append(base::WideToUTF16(L"\x0915\x093f\x0915\x094d\x0915")); - EXPECT_EQ(base::WideToUTF16(L"\x0915\x093f\x0915\x094d\x0915"), model.text()); - model.Append(base::WideToUTF16(L"\x0915\x094d\x092e\x094d")); - EXPECT_EQ(base::WideToUTF16( - L"\x0915\x093f\x0915\x094d\x0915\x0915\x094d\x092e\x094d"), model.text()); - - if (!on_windows_xp) { - // Ensure the cursor cannot be placed in the middle of a grapheme. - MoveCursorTo(model, 1); - EXPECT_EQ(0U, model.GetCursorPosition()); - - MoveCursorTo(model, 2); - EXPECT_EQ(2U, model.GetCursorPosition()); - model.InsertChar('a'); - EXPECT_EQ(base::WideToUTF16( - L"\x0915\x093f\x0061\x0915\x094d\x0915\x0915\x094d\x092e\x094d"), - model.text()); - - // ReplaceChar will replace the whole grapheme. - model.ReplaceChar('b'); - // TODO(xji): temporarily disable in platform Win since the complex script - // characters turned into empty square due to font regression. So, not able - // to test 2 characters belong to the same grapheme. -#if defined(OS_LINUX) - EXPECT_EQ(base::WideToUTF16( - L"\x0915\x093f\x0061\x0062\x0915\x0915\x094d\x092e\x094d"), - model.text()); -#endif - EXPECT_EQ(4U, model.GetCursorPosition()); - } - - // Delete should delete the whole grapheme. - MoveCursorTo(model, 0); - // TODO(xji): temporarily disable in platform Win since the complex script - // characters turned into empty square due to font regression. So, not able - // to test 2 characters belong to the same grapheme. -#if defined(OS_LINUX) - EXPECT_TRUE(model.Delete()); - EXPECT_EQ(base::WideToUTF16(L"\x0061\x0062\x0915\x0915\x094d\x092e\x094d"), - model.text()); - MoveCursorTo(model, model.text().length()); - EXPECT_EQ(model.text().length(), model.GetCursorPosition()); - EXPECT_TRUE(model.Backspace()); - EXPECT_EQ(base::WideToUTF16(L"\x0061\x0062\x0915\x0915\x094d\x092e"), - model.text()); -#endif - - // Test cursor position and deletion for Hindi Virama. - model.SetText(base::WideToUTF16(L"\x0D38\x0D4D\x0D15\x0D16\x0D2E")); - MoveCursorTo(model, 0); - EXPECT_EQ(0U, model.GetCursorPosition()); - - if (!on_windows_xp) { - MoveCursorTo(model, 1); - EXPECT_EQ(0U, model.GetCursorPosition()); - MoveCursorTo(model, 3); - EXPECT_EQ(3U, model.GetCursorPosition()); - } - - // TODO(asvitkine): Temporarily disable the following check on Windows. It - // seems Windows treats "\x0D38\x0D4D\x0D15" as a single grapheme. -#if !defined(OS_WIN) - MoveCursorTo(model, 2); - EXPECT_EQ(2U, model.GetCursorPosition()); - EXPECT_TRUE(model.Backspace()); - EXPECT_EQ(base::WideToUTF16(L"\x0D38\x0D15\x0D16\x0D2E"), model.text()); -#endif - - model.SetText( - base::WideToUTF16(L"\x05d5\x05b7\x05D9\x05B0\x05D4\x05B4\x05D9")); - MoveCursorTo(model, 0); - EXPECT_TRUE(model.Delete()); - EXPECT_TRUE(model.Delete()); - EXPECT_TRUE(model.Delete()); - EXPECT_TRUE(model.Delete()); - EXPECT_EQ(base::WideToUTF16(L""), model.text()); - - // The first 2 characters are not strong directionality characters. - model.SetText( - base::WideToUTF16(L"\x002C\x0020\x05D1\x05BC\x05B7\x05E9\x05BC")); - model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_LEFT, false); - EXPECT_TRUE(model.Backspace()); - EXPECT_EQ(base::WideToUTF16(L"\x002C\x0020\x05D1\x05BC\x05B7\x05E9"), - model.text()); -} - -TEST_F(TextfieldModelTest, EmptyString) { - TextfieldModel model(NULL); - EXPECT_EQ(base::string16(), model.text()); - EXPECT_EQ(base::string16(), model.GetSelectedText()); - - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, true); - EXPECT_EQ(0U, model.GetCursorPosition()); - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, true); - EXPECT_EQ(0U, model.GetCursorPosition()); - - EXPECT_EQ(base::string16(), model.GetSelectedText()); - - EXPECT_FALSE(model.Delete()); - EXPECT_FALSE(model.Backspace()); -} - -TEST_F(TextfieldModelTest, Selection) { - TextfieldModel model(NULL); - model.Append(base::ASCIIToUTF16("HELLO")); - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, false); - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, true); - EXPECT_STR_EQ("E", model.GetSelectedText()); - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, true); - EXPECT_STR_EQ("EL", model.GetSelectedText()); - - model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_LEFT, true); - EXPECT_STR_EQ("H", model.GetSelectedText()); - model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, true); - EXPECT_STR_EQ("ELLO", model.GetSelectedText()); - model.ClearSelection(); - EXPECT_EQ(base::string16(), model.GetSelectedText()); - - // SelectAll(false) selects towards the end. - model.SelectAll(false); - EXPECT_STR_EQ("HELLO", model.GetSelectedText()); - EXPECT_EQ(gfx::Range(0, 5), model.render_text()->selection()); - - // SelectAll(true) selects towards the beginning. - model.SelectAll(true); - EXPECT_STR_EQ("HELLO", model.GetSelectedText()); - EXPECT_EQ(gfx::Range(5, 0), model.render_text()->selection()); - - // Select and move cursor. - model.SelectRange(gfx::Range(1U, 3U)); - EXPECT_STR_EQ("EL", model.GetSelectedText()); - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, false); - EXPECT_EQ(1U, model.GetCursorPosition()); - model.SelectRange(gfx::Range(1U, 3U)); - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, false); - EXPECT_EQ(3U, model.GetCursorPosition()); - - // Select all and move cursor. - model.SelectAll(false); - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, false); - EXPECT_EQ(0U, model.GetCursorPosition()); - model.SelectAll(false); - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, false); - EXPECT_EQ(5U, model.GetCursorPosition()); -} - -TEST_F(TextfieldModelTest, Selection_BidiWithNonSpacingMarks) { - // Selection is a logical operation. And it should work with the arrow - // keys doing visual movements, while the selection is logical between - // the (logical) start and end points. Selection is simply defined as - // the portion of text between the logical positions of the start and end - // caret positions. - TextfieldModel model(NULL); - // TODO(xji): temporarily disable in platform Win since the complex script - // characters turned into empty square due to font regression. So, not able - // to test 2 characters belong to the same grapheme. -#if defined(OS_LINUX) - model.Append(base::WideToUTF16( - L"abc\x05E9\x05BC\x05C1\x05B8\x05E0\x05B8" L"def")); - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, false); - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, false); - - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, true); - EXPECT_EQ(gfx::Range(2, 3), model.render_text()->selection()); - EXPECT_EQ(base::WideToUTF16(L"c"), model.GetSelectedText()); - - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, true); - EXPECT_EQ(gfx::Range(2, 7), model.render_text()->selection()); - EXPECT_EQ(base::WideToUTF16(L"c\x05E9\x05BC\x05C1\x05B8"), - model.GetSelectedText()); - - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, true); - EXPECT_EQ(gfx::Range(2, 3), model.render_text()->selection()); - EXPECT_EQ(base::WideToUTF16(L"c"), model.GetSelectedText()); - - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, true); - EXPECT_EQ(gfx::Range(2, 10), model.render_text()->selection()); - EXPECT_EQ(base::WideToUTF16(L"c\x05E9\x05BC\x05C1\x05B8\x05E0\x05B8" L"d"), - model.GetSelectedText()); - - model.ClearSelection(); - EXPECT_EQ(base::string16(), model.GetSelectedText()); - model.SelectAll(false); - EXPECT_EQ( - base::WideToUTF16(L"abc\x05E9\x05BC\x05C1\x05B8\x05E0\x05B8" L"def"), - model.GetSelectedText()); -#endif - - // In case of "aBc", this test shows how to select "aB" or "Bc", assume 'B' is - // an RTL character. - model.SetText(base::WideToUTF16(L"a\x05E9" L"b")); - MoveCursorTo(model, 0); - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, true); - EXPECT_EQ(base::WideToUTF16(L"a"), model.GetSelectedText()); - - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, true); - EXPECT_EQ(base::WideToUTF16(L"a"), model.GetSelectedText()); - - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, true); - EXPECT_EQ(base::WideToUTF16(L"a\x05E9" L"b"), model.GetSelectedText()); - - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, false); - EXPECT_EQ(3U, model.GetCursorPosition()); - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, true); - EXPECT_EQ(base::WideToUTF16(L"b"), model.GetSelectedText()); - - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, true); - EXPECT_EQ(base::WideToUTF16(L"b"), model.GetSelectedText()); - - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, true); - EXPECT_EQ(base::WideToUTF16(L"a\x05E9" L"b"), model.GetSelectedText()); - - model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_LEFT, false); - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, true); - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, true); - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, true); - EXPECT_EQ(base::WideToUTF16(L"a\x05E9"), model.GetSelectedText()); - - model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, false); - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, true); - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, true); - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, true); - EXPECT_EQ(base::WideToUTF16(L"\x05E9" L"b"), model.GetSelectedText()); - - model.ClearSelection(); - EXPECT_EQ(base::string16(), model.GetSelectedText()); - model.SelectAll(false); - EXPECT_EQ(base::WideToUTF16(L"a\x05E9" L"b"), model.GetSelectedText()); -} - -TEST_F(TextfieldModelTest, SelectionAndEdit) { - TextfieldModel model(NULL); - model.Append(base::ASCIIToUTF16("HELLO")); - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, false); - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, true); - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, true); // "EL" - EXPECT_TRUE(model.Backspace()); - EXPECT_STR_EQ("HLO", model.text()); - - model.Append(base::ASCIIToUTF16("ILL")); - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, true); - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, true); // "LO" - EXPECT_TRUE(model.Delete()); - EXPECT_STR_EQ("HILL", model.text()); - EXPECT_EQ(1U, model.GetCursorPosition()); - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, true); // "I" - model.InsertChar('E'); - EXPECT_STR_EQ("HELL", model.text()); - model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_LEFT, false); - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, true); // "H" - model.ReplaceChar('B'); - EXPECT_STR_EQ("BELL", model.text()); - model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, false); - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, true); - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, true); // "ELL" - model.ReplaceChar('E'); - EXPECT_STR_EQ("BEE", model.text()); -} - -TEST_F(TextfieldModelTest, Word) { - TextfieldModel model(NULL); - model.Append( - base::ASCIIToUTF16("The answer to Life, the Universe, and Everything")); - model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, false); - EXPECT_EQ(3U, model.GetCursorPosition()); - model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, false); - EXPECT_EQ(10U, model.GetCursorPosition()); - model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, false); - model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, false); - EXPECT_EQ(18U, model.GetCursorPosition()); - - // Should passes the non word char ',' - model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, true); - EXPECT_EQ(23U, model.GetCursorPosition()); - EXPECT_STR_EQ(", the", model.GetSelectedText()); - - // Move to the end. - model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, true); - model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, true); - model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, true); - EXPECT_STR_EQ(", the Universe, and Everything", model.GetSelectedText()); - // Should be safe to go next word at the end. - model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, true); - EXPECT_STR_EQ(", the Universe, and Everything", model.GetSelectedText()); - model.InsertChar('2'); - EXPECT_EQ(19U, model.GetCursorPosition()); - - // Now backwards. - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, false); // leave 2. - model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, true); - EXPECT_EQ(14U, model.GetCursorPosition()); - EXPECT_STR_EQ("Life", model.GetSelectedText()); - model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, true); - EXPECT_STR_EQ("to Life", model.GetSelectedText()); - model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, true); - model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, true); - model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, true); // Now at start. - EXPECT_STR_EQ("The answer to Life", model.GetSelectedText()); - // Should be safe to go to the previous word at the beginning. - model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, true); - EXPECT_STR_EQ("The answer to Life", model.GetSelectedText()); - model.ReplaceChar('4'); - EXPECT_EQ(base::string16(), model.GetSelectedText()); - EXPECT_STR_EQ("42", model.text()); -} - -TEST_F(TextfieldModelTest, SetText) { - TextfieldModel model(NULL); - model.Append(base::ASCIIToUTF16("HELLO")); - model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, false); - model.SetText(base::ASCIIToUTF16("GOODBYE")); - EXPECT_STR_EQ("GOODBYE", model.text()); - // SetText move the cursor to the end of the new text. - EXPECT_EQ(7U, model.GetCursorPosition()); - model.SelectAll(false); - EXPECT_STR_EQ("GOODBYE", model.GetSelectedText()); - model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, false); - EXPECT_EQ(7U, model.GetCursorPosition()); - - model.SetText(base::ASCIIToUTF16("BYE")); - // Setting shorter string moves the cursor to the end of the new string. - EXPECT_EQ(3U, model.GetCursorPosition()); - EXPECT_EQ(base::string16(), model.GetSelectedText()); - model.SetText(base::string16()); - EXPECT_EQ(0U, model.GetCursorPosition()); -} - -TEST_F(TextfieldModelTest, Clipboard) { - ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); - const base::string16 initial_clipboard_text = - base::ASCIIToUTF16("initial text"); - ui::ScopedClipboardWriter(ui::CLIPBOARD_TYPE_COPY_PASTE) - .WriteText(initial_clipboard_text); - - base::string16 clipboard_text; - TextfieldModel model(NULL); - model.Append(base::ASCIIToUTF16("HELLO WORLD")); - - // Cut with an empty selection should do nothing. - model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, false); - EXPECT_FALSE(model.Cut()); - clipboard->ReadText(ui::CLIPBOARD_TYPE_COPY_PASTE, &clipboard_text); - EXPECT_EQ(initial_clipboard_text, clipboard_text); - EXPECT_STR_EQ("HELLO WORLD", model.text()); - EXPECT_EQ(11U, model.GetCursorPosition()); - - // Copy with an empty selection should do nothing. - model.Copy(); - clipboard->ReadText(ui::CLIPBOARD_TYPE_COPY_PASTE, &clipboard_text); - EXPECT_EQ(initial_clipboard_text, clipboard_text); - EXPECT_STR_EQ("HELLO WORLD", model.text()); - EXPECT_EQ(11U, model.GetCursorPosition()); - - // Cut on obscured (password) text should do nothing. - model.render_text()->SetObscured(true); - model.SelectAll(false); - EXPECT_FALSE(model.Cut()); - clipboard->ReadText(ui::CLIPBOARD_TYPE_COPY_PASTE, &clipboard_text); - EXPECT_EQ(initial_clipboard_text, clipboard_text); - EXPECT_STR_EQ("HELLO WORLD", model.text()); - EXPECT_STR_EQ("HELLO WORLD", model.GetSelectedText()); - - // Copy on obscured (password) text should do nothing. - model.SelectAll(false); - EXPECT_FALSE(model.Copy()); - clipboard->ReadText(ui::CLIPBOARD_TYPE_COPY_PASTE, &clipboard_text); - EXPECT_EQ(initial_clipboard_text, clipboard_text); - EXPECT_STR_EQ("HELLO WORLD", model.text()); - EXPECT_STR_EQ("HELLO WORLD", model.GetSelectedText()); - - // Cut with non-empty selection. - model.render_text()->SetObscured(false); - model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, false); - model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, true); - EXPECT_TRUE(model.Cut()); - clipboard->ReadText(ui::CLIPBOARD_TYPE_COPY_PASTE, &clipboard_text); - EXPECT_STR_EQ("WORLD", clipboard_text); - EXPECT_STR_EQ("HELLO ", model.text()); - EXPECT_EQ(6U, model.GetCursorPosition()); - - // Copy with non-empty selection. - model.SelectAll(false); - EXPECT_TRUE(model.Copy()); - clipboard->ReadText(ui::CLIPBOARD_TYPE_COPY_PASTE, &clipboard_text); - EXPECT_STR_EQ("HELLO ", clipboard_text); - EXPECT_STR_EQ("HELLO ", model.text()); - EXPECT_EQ(6U, model.GetCursorPosition()); - - // Test that paste works regardless of the obscured bit. - model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, false); - EXPECT_TRUE(model.Paste()); - EXPECT_STR_EQ("HELLO HELLO ", model.text()); - EXPECT_EQ(12U, model.GetCursorPosition()); - model.render_text()->SetObscured(true); - EXPECT_TRUE(model.Paste()); - EXPECT_STR_EQ("HELLO HELLO HELLO ", model.text()); - EXPECT_EQ(18U, model.GetCursorPosition()); -} - -static void SelectWordTestVerifier( - const TextfieldModel& model, - const base::string16 &expected_selected_string, - size_t expected_cursor_pos) { - EXPECT_EQ(expected_selected_string, model.GetSelectedText()); - EXPECT_EQ(expected_cursor_pos, model.GetCursorPosition()); -} - -TEST_F(TextfieldModelTest, SelectWordTest) { - TextfieldModel model(NULL); - model.Append(base::ASCIIToUTF16(" HELLO !! WO RLD ")); - - // Test when cursor is at the beginning. - model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_LEFT, false); - model.SelectWord(); - SelectWordTestVerifier(model, base::ASCIIToUTF16(" "), 2U); - - // Test when cursor is at the beginning of a word. - MoveCursorTo(model, 2); - model.SelectWord(); - SelectWordTestVerifier(model, base::ASCIIToUTF16("HELLO"), 7U); - - // Test when cursor is at the end of a word. - MoveCursorTo(model, 15); - model.SelectWord(); - SelectWordTestVerifier(model, base::ASCIIToUTF16(" "), 20U); - - // Test when cursor is somewhere in a non-alpha-numeric fragment. - for (size_t cursor_pos = 8; cursor_pos < 13U; cursor_pos++) { - MoveCursorTo(model, cursor_pos); - model.SelectWord(); - SelectWordTestVerifier(model, base::ASCIIToUTF16(" !! "), 13U); - } - - // Test when cursor is somewhere in a whitespace fragment. - MoveCursorTo(model, 17); - model.SelectWord(); - SelectWordTestVerifier(model, base::ASCIIToUTF16(" "), 20U); - - // Test when cursor is at the end. - model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, false); - model.SelectWord(); - SelectWordTestVerifier(model, base::ASCIIToUTF16(" "), 24U); -} - -// TODO(xji): temporarily disable in platform Win since the complex script -// characters and Chinese characters are turned into empty square due to font -// regression. -#if defined(OS_LINUX) -TEST_F(TextfieldModelTest, SelectWordTest_MixScripts) { - TextfieldModel model(NULL); - std::vector<WordAndCursor> word_and_cursor; - word_and_cursor.push_back(WordAndCursor(L"a\x05d0", 2)); - word_and_cursor.push_back(WordAndCursor(L"a\x05d0", 2)); - word_and_cursor.push_back(WordAndCursor(L"\x05d1\x05d2", 5)); - word_and_cursor.push_back(WordAndCursor(L"\x05d1\x05d2", 5)); - word_and_cursor.push_back(WordAndCursor(L" ", 3)); - word_and_cursor.push_back(WordAndCursor(L"a\x05d0", 2)); - word_and_cursor.push_back(WordAndCursor(L"\x0915\x094d\x0915", 9)); - word_and_cursor.push_back(WordAndCursor(L"\x0915\x094d\x0915", 9)); - word_and_cursor.push_back(WordAndCursor(L" ", 10)); - word_and_cursor.push_back(WordAndCursor(L"\x4E2D\x56FD", 12)); - word_and_cursor.push_back(WordAndCursor(L"\x4E2D\x56FD", 12)); - word_and_cursor.push_back(WordAndCursor(L"\x82B1", 13)); - word_and_cursor.push_back(WordAndCursor(L"\x5929", 14)); - - // The text consists of Ascii, Hebrew, Hindi with Virama sign, and Chinese. - model.SetText(base::WideToUTF16(L"a\x05d0 \x05d1\x05d2 \x0915\x094d\x0915 " - L"\x4E2D\x56FD\x82B1\x5929")); - for (size_t i = 0; i < word_and_cursor.size(); ++i) { - model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_LEFT, false); - for (size_t j = 0; j < i; ++j) - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, false); - model.SelectWord(); - SelectWordTestVerifier(model, base::WideToUTF16(word_and_cursor[i].word), - word_and_cursor[i].cursor); - } -} -#endif - -TEST_F(TextfieldModelTest, RangeTest) { - TextfieldModel model(NULL); - model.Append(base::ASCIIToUTF16("HELLO WORLD")); - model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_LEFT, false); - gfx::Range range = model.render_text()->selection(); - EXPECT_TRUE(range.is_empty()); - EXPECT_EQ(0U, range.start()); - EXPECT_EQ(0U, range.end()); - - model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, true); - range = model.render_text()->selection(); - EXPECT_FALSE(range.is_empty()); - EXPECT_FALSE(range.is_reversed()); - EXPECT_EQ(0U, range.start()); - EXPECT_EQ(5U, range.end()); - - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, true); - range = model.render_text()->selection(); - EXPECT_FALSE(range.is_empty()); - EXPECT_EQ(0U, range.start()); - EXPECT_EQ(4U, range.end()); - - model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, true); - range = model.render_text()->selection(); - EXPECT_TRUE(range.is_empty()); - EXPECT_EQ(0U, range.start()); - EXPECT_EQ(0U, range.end()); - - // now from the end. - model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, false); - range = model.render_text()->selection(); - EXPECT_TRUE(range.is_empty()); - EXPECT_EQ(11U, range.start()); - EXPECT_EQ(11U, range.end()); - - model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, true); - range = model.render_text()->selection(); - EXPECT_FALSE(range.is_empty()); - EXPECT_TRUE(range.is_reversed()); - EXPECT_EQ(11U, range.start()); - EXPECT_EQ(6U, range.end()); - - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, true); - range = model.render_text()->selection(); - EXPECT_FALSE(range.is_empty()); - EXPECT_TRUE(range.is_reversed()); - EXPECT_EQ(11U, range.start()); - EXPECT_EQ(7U, range.end()); - - model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, true); - range = model.render_text()->selection(); - EXPECT_TRUE(range.is_empty()); - EXPECT_EQ(11U, range.start()); - EXPECT_EQ(11U, range.end()); - - // Select All - model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_LEFT, true); - range = model.render_text()->selection(); - EXPECT_FALSE(range.is_empty()); - EXPECT_TRUE(range.is_reversed()); - EXPECT_EQ(11U, range.start()); - EXPECT_EQ(0U, range.end()); -} - -TEST_F(TextfieldModelTest, SelectRangeTest) { - TextfieldModel model(NULL); - model.Append(base::ASCIIToUTF16("HELLO WORLD")); - gfx::Range range(0, 6); - EXPECT_FALSE(range.is_reversed()); - model.SelectRange(range); - EXPECT_STR_EQ("HELLO ", model.GetSelectedText()); - - range = gfx::Range(6, 1); - EXPECT_TRUE(range.is_reversed()); - model.SelectRange(range); - EXPECT_STR_EQ("ELLO ", model.GetSelectedText()); - - range = gfx::Range(2, 1000); - EXPECT_FALSE(range.is_reversed()); - model.SelectRange(range); - EXPECT_STR_EQ("LLO WORLD", model.GetSelectedText()); - - range = gfx::Range(1000, 3); - EXPECT_TRUE(range.is_reversed()); - model.SelectRange(range); - EXPECT_STR_EQ("LO WORLD", model.GetSelectedText()); - - range = gfx::Range(0, 0); - EXPECT_TRUE(range.is_empty()); - model.SelectRange(range); - EXPECT_TRUE(model.GetSelectedText().empty()); - - range = gfx::Range(3, 3); - EXPECT_TRUE(range.is_empty()); - model.SelectRange(range); - EXPECT_TRUE(model.GetSelectedText().empty()); - - range = gfx::Range(1000, 100); - EXPECT_FALSE(range.is_empty()); - model.SelectRange(range); - EXPECT_TRUE(model.GetSelectedText().empty()); - - range = gfx::Range(1000, 1000); - EXPECT_TRUE(range.is_empty()); - model.SelectRange(range); - EXPECT_TRUE(model.GetSelectedText().empty()); -} - -TEST_F(TextfieldModelTest, SelectionTest) { - TextfieldModel model(NULL); - model.Append(base::ASCIIToUTF16("HELLO WORLD")); - model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_LEFT, false); - gfx::Range selection = model.render_text()->selection(); - EXPECT_EQ(gfx::Range(0), selection); - - model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, true); - selection = model.render_text()->selection(); - EXPECT_EQ(gfx::Range(0, 5), selection); - - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, true); - selection = model.render_text()->selection(); - EXPECT_EQ(gfx::Range(0, 4), selection); - - model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, true); - selection = model.render_text()->selection(); - EXPECT_EQ(gfx::Range(0), selection); - - // now from the end. - model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, false); - selection = model.render_text()->selection(); - EXPECT_EQ(gfx::Range(11), selection); - - model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, true); - selection = model.render_text()->selection(); - EXPECT_EQ(gfx::Range(11, 6), selection); - - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, true); - selection = model.render_text()->selection(); - EXPECT_EQ(gfx::Range(11, 7), selection); - - model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, true); - selection = model.render_text()->selection(); - EXPECT_EQ(gfx::Range(11), selection); - - // Select All - model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_LEFT, true); - selection = model.render_text()->selection(); - EXPECT_EQ(gfx::Range(11, 0), selection); -} - -TEST_F(TextfieldModelTest, SelectSelectionModelTest) { - TextfieldModel model(NULL); - model.Append(base::ASCIIToUTF16("HELLO WORLD")); - model.SelectSelectionModel(gfx::SelectionModel(gfx::Range(0, 6), - gfx::CURSOR_BACKWARD)); - EXPECT_STR_EQ("HELLO ", model.GetSelectedText()); - - model.SelectSelectionModel(gfx::SelectionModel(gfx::Range(6, 1), - gfx::CURSOR_FORWARD)); - EXPECT_STR_EQ("ELLO ", model.GetSelectedText()); - - model.SelectSelectionModel(gfx::SelectionModel(gfx::Range(2, 1000), - gfx::CURSOR_BACKWARD)); - EXPECT_STR_EQ("LLO WORLD", model.GetSelectedText()); - - model.SelectSelectionModel(gfx::SelectionModel(gfx::Range(1000, 3), - gfx::CURSOR_FORWARD)); - EXPECT_STR_EQ("LO WORLD", model.GetSelectedText()); - - model.SelectSelectionModel(gfx::SelectionModel(0, gfx::CURSOR_FORWARD)); - EXPECT_TRUE(model.GetSelectedText().empty()); - - model.SelectSelectionModel(gfx::SelectionModel(3, gfx::CURSOR_FORWARD)); - EXPECT_TRUE(model.GetSelectedText().empty()); - - model.SelectSelectionModel(gfx::SelectionModel(gfx::Range(1000, 100), - gfx::CURSOR_FORWARD)); - EXPECT_TRUE(model.GetSelectedText().empty()); - - model.SelectSelectionModel(gfx::SelectionModel(1000, gfx::CURSOR_BACKWARD)); - EXPECT_TRUE(model.GetSelectedText().empty()); -} - -TEST_F(TextfieldModelTest, CompositionTextTest) { - TextfieldModel model(this); - model.Append(base::ASCIIToUTF16("1234590")); - model.SelectRange(gfx::Range(5, 5)); - EXPECT_FALSE(model.HasSelection()); - EXPECT_EQ(5U, model.GetCursorPosition()); - - gfx::Range range; - model.GetTextRange(&range); - EXPECT_EQ(gfx::Range(0, 7), range); - - ui::CompositionText composition; - composition.text = base::ASCIIToUTF16("678"); - composition.underlines.push_back(ui::CompositionUnderline(0, 3, 0, false)); - - // Cursor should be at the end of composition when characters are just typed. - composition.selection = gfx::Range(3, 3); - model.SetCompositionText(composition); - EXPECT_TRUE(model.HasCompositionText()); - EXPECT_FALSE(model.HasSelection()); - - // Cancel the composition. - model.CancelCompositionText(); - composition_text_confirmed_or_cleared_ = false; - - // Restart composition with targeting "67" in "678". - composition.selection = gfx::Range(0, 2); - composition.underlines.clear(); - composition.underlines.push_back(ui::CompositionUnderline(0, 2, 0, true)); - composition.underlines.push_back(ui::CompositionUnderline(2, 3, 0, false)); - model.SetCompositionText(composition); - EXPECT_TRUE(model.HasCompositionText()); - EXPECT_TRUE(model.HasSelection()); - EXPECT_EQ(gfx::Range(5, 7), model.render_text()->selection()); - - model.GetTextRange(&range); - EXPECT_EQ(10U, range.end()); - EXPECT_STR_EQ("1234567890", model.text()); - - model.GetCompositionTextRange(&range); - EXPECT_EQ(gfx::Range(5, 8), range); - // Check the composition text. - EXPECT_STR_EQ("456", model.GetTextFromRange(gfx::Range(3, 6))); - EXPECT_EQ(gfx::Range(5, 7), model.render_text()->selection()); - - EXPECT_FALSE(composition_text_confirmed_or_cleared_); - model.CancelCompositionText(); - EXPECT_TRUE(composition_text_confirmed_or_cleared_); - composition_text_confirmed_or_cleared_ = false; - EXPECT_FALSE(model.HasCompositionText()); - EXPECT_FALSE(model.HasSelection()); - EXPECT_EQ(5U, model.GetCursorPosition()); - - model.SetCompositionText(composition); - EXPECT_STR_EQ("1234567890", model.text()); - EXPECT_TRUE(model.SetText(base::ASCIIToUTF16("1234567890"))); - EXPECT_TRUE(composition_text_confirmed_or_cleared_); - composition_text_confirmed_or_cleared_ = false; - model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, false); - - model.SetCompositionText(composition); - EXPECT_STR_EQ("1234567890678", model.text()); - - model.InsertText(base::UTF8ToUTF16("-")); - EXPECT_TRUE(composition_text_confirmed_or_cleared_); - composition_text_confirmed_or_cleared_ = false; - EXPECT_STR_EQ("1234567890-", model.text()); - EXPECT_FALSE(model.HasCompositionText()); - EXPECT_FALSE(model.HasSelection()); - - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, true); - EXPECT_STR_EQ("-", model.GetSelectedText()); - model.SetCompositionText(composition); - EXPECT_STR_EQ("1234567890678", model.text()); - - model.ReplaceText(base::UTF8ToUTF16("-")); - EXPECT_TRUE(composition_text_confirmed_or_cleared_); - composition_text_confirmed_or_cleared_ = false; - EXPECT_STR_EQ("1234567890-", model.text()); - EXPECT_FALSE(model.HasCompositionText()); - EXPECT_FALSE(model.HasSelection()); - - model.SetCompositionText(composition); - model.Append(base::UTF8ToUTF16("-")); - EXPECT_TRUE(composition_text_confirmed_or_cleared_); - composition_text_confirmed_or_cleared_ = false; - EXPECT_STR_EQ("1234567890-678-", model.text()); - - model.SetCompositionText(composition); - model.Delete(); - EXPECT_TRUE(composition_text_confirmed_or_cleared_); - composition_text_confirmed_or_cleared_ = false; - EXPECT_STR_EQ("1234567890-678-", model.text()); - - model.SetCompositionText(composition); - model.Backspace(); - EXPECT_TRUE(composition_text_confirmed_or_cleared_); - composition_text_confirmed_or_cleared_ = false; - EXPECT_STR_EQ("1234567890-678-", model.text()); - - model.SetText(base::string16()); - model.SetCompositionText(composition); - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, false); - EXPECT_TRUE(composition_text_confirmed_or_cleared_); - composition_text_confirmed_or_cleared_ = false; - EXPECT_STR_EQ("678", model.text()); - EXPECT_EQ(2U, model.GetCursorPosition()); - - model.SetCompositionText(composition); - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, false); - EXPECT_TRUE(composition_text_confirmed_or_cleared_); - composition_text_confirmed_or_cleared_ = false; - EXPECT_STR_EQ("676788", model.text()); - EXPECT_EQ(6U, model.GetCursorPosition()); - - model.SetCompositionText(composition); - model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_LEFT, false); - EXPECT_TRUE(composition_text_confirmed_or_cleared_); - composition_text_confirmed_or_cleared_ = false; - EXPECT_STR_EQ("676788678", model.text()); - - model.SetText(base::string16()); - model.SetCompositionText(composition); - model.MoveCursor(gfx::WORD_BREAK, gfx::CURSOR_RIGHT, false); - EXPECT_TRUE(composition_text_confirmed_or_cleared_); - composition_text_confirmed_or_cleared_ = false; - - model.SetCompositionText(composition); - model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_LEFT, true); - EXPECT_TRUE(composition_text_confirmed_or_cleared_); - composition_text_confirmed_or_cleared_ = false; - EXPECT_STR_EQ("678678", model.text()); - - model.SetCompositionText(composition); - model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, false); - EXPECT_TRUE(composition_text_confirmed_or_cleared_); - composition_text_confirmed_or_cleared_ = false; - EXPECT_STR_EQ("678", model.text()); - - model.SetCompositionText(composition); - gfx::SelectionModel sel( - gfx::Range(model.render_text()->selection().start(), 0), - gfx::CURSOR_FORWARD); - model.MoveCursorTo(sel); - EXPECT_TRUE(composition_text_confirmed_or_cleared_); - composition_text_confirmed_or_cleared_ = false; - EXPECT_STR_EQ("678678", model.text()); - - model.SetCompositionText(composition); - model.SelectRange(gfx::Range(0, 3)); - EXPECT_TRUE(composition_text_confirmed_or_cleared_); - composition_text_confirmed_or_cleared_ = false; - EXPECT_STR_EQ("678", model.text()); - - model.SetCompositionText(composition); - model.SelectAll(false); - EXPECT_TRUE(composition_text_confirmed_or_cleared_); - composition_text_confirmed_or_cleared_ = false; - EXPECT_STR_EQ("678", model.text()); - - model.SetCompositionText(composition); - model.SelectWord(); - EXPECT_TRUE(composition_text_confirmed_or_cleared_); - composition_text_confirmed_or_cleared_ = false; - EXPECT_STR_EQ("678", model.text()); - - model.SetCompositionText(composition); - model.ClearSelection(); - EXPECT_TRUE(composition_text_confirmed_or_cleared_); - composition_text_confirmed_or_cleared_ = false; - - model.SetCompositionText(composition); - EXPECT_FALSE(model.Cut()); - EXPECT_FALSE(composition_text_confirmed_or_cleared_); -} - -TEST_F(TextfieldModelTest, UndoRedo_BasicTest) { - TextfieldModel model(NULL); - model.InsertChar('a'); - EXPECT_FALSE(model.Redo()); // There is nothing to redo. - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("", model.text()); - EXPECT_TRUE(model.Redo()); - EXPECT_STR_EQ("a", model.text()); - - // Continuous inserts are treated as one edit. - model.InsertChar('b'); - model.InsertChar('c'); - EXPECT_STR_EQ("abc", model.text()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("a", model.text()); - EXPECT_EQ(1U, model.GetCursorPosition()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("", model.text()); - EXPECT_EQ(0U, model.GetCursorPosition()); - - // Undoing further shouldn't change the text. - EXPECT_FALSE(model.Undo()); - EXPECT_STR_EQ("", model.text()); - EXPECT_FALSE(model.Undo()); - EXPECT_STR_EQ("", model.text()); - EXPECT_EQ(0U, model.GetCursorPosition()); - - // Redoing to the latest text. - EXPECT_TRUE(model.Redo()); - EXPECT_STR_EQ("a", model.text()); - EXPECT_EQ(1U, model.GetCursorPosition()); - EXPECT_TRUE(model.Redo()); - EXPECT_STR_EQ("abc", model.text()); - EXPECT_EQ(3U, model.GetCursorPosition()); - - // Backspace =============================== - EXPECT_TRUE(model.Backspace()); - EXPECT_STR_EQ("ab", model.text()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("abc", model.text()); - EXPECT_EQ(3U, model.GetCursorPosition()); - EXPECT_TRUE(model.Redo()); - EXPECT_STR_EQ("ab", model.text()); - EXPECT_EQ(2U, model.GetCursorPosition()); - // Continous backspaces are treated as one edit. - EXPECT_TRUE(model.Backspace()); - EXPECT_TRUE(model.Backspace()); - EXPECT_STR_EQ("", model.text()); - // Extra backspace shouldn't affect the history. - EXPECT_FALSE(model.Backspace()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("ab", model.text()); - EXPECT_EQ(2U, model.GetCursorPosition()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("abc", model.text()); - EXPECT_EQ(3U, model.GetCursorPosition()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("a", model.text()); - EXPECT_EQ(1U, model.GetCursorPosition()); - - // Clear history - model.ClearEditHistory(); - EXPECT_FALSE(model.Undo()); - EXPECT_FALSE(model.Redo()); - EXPECT_STR_EQ("a", model.text()); - EXPECT_EQ(1U, model.GetCursorPosition()); - - // Delete =============================== - model.SetText(base::ASCIIToUTF16("ABCDE")); - model.ClearEditHistory(); - MoveCursorTo(model, 2); - EXPECT_TRUE(model.Delete()); - EXPECT_STR_EQ("ABDE", model.text()); - model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_LEFT, false); - EXPECT_TRUE(model.Delete()); - EXPECT_STR_EQ("BDE", model.text()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("ABDE", model.text()); - EXPECT_EQ(0U, model.GetCursorPosition()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("ABCDE", model.text()); - EXPECT_EQ(2U, model.GetCursorPosition()); - EXPECT_TRUE(model.Redo()); - EXPECT_STR_EQ("ABDE", model.text()); - EXPECT_EQ(2U, model.GetCursorPosition()); - // Continous deletes are treated as one edit. - EXPECT_TRUE(model.Delete()); - EXPECT_TRUE(model.Delete()); - EXPECT_STR_EQ("AB", model.text()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("ABDE", model.text()); - EXPECT_EQ(2U, model.GetCursorPosition()); - EXPECT_TRUE(model.Redo()); - EXPECT_STR_EQ("AB", model.text()); - EXPECT_EQ(2U, model.GetCursorPosition()); -} - -TEST_F(TextfieldModelTest, UndoRedo_SetText) { - // This is to test the undo/redo behavior of omnibox. - TextfieldModel model(NULL); - model.InsertChar('w'); - EXPECT_STR_EQ("w", model.text()); - EXPECT_EQ(1U, model.GetCursorPosition()); - model.SetText(base::ASCIIToUTF16("www.google.com")); - EXPECT_EQ(14U, model.GetCursorPosition()); - EXPECT_STR_EQ("www.google.com", model.text()); - model.SelectRange(gfx::Range(14, 1)); - model.InsertChar('w'); - EXPECT_STR_EQ("ww", model.text()); - model.SetText(base::ASCIIToUTF16("www.google.com")); - model.SelectRange(gfx::Range(14, 2)); - model.InsertChar('w'); - EXPECT_STR_EQ("www", model.text()); - model.SetText(base::ASCIIToUTF16("www.google.com")); - model.SelectRange(gfx::Range(14, 3)); - model.InsertChar('.'); - EXPECT_STR_EQ("www.", model.text()); - model.SetText(base::ASCIIToUTF16("www.google.com")); - model.SelectRange(gfx::Range(14, 4)); - model.InsertChar('y'); - EXPECT_STR_EQ("www.y", model.text()); - model.SetText(base::ASCIIToUTF16("www.youtube.com")); - EXPECT_STR_EQ("www.youtube.com", model.text()); - EXPECT_EQ(15U, model.GetCursorPosition()); - - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("www.google.com", model.text()); - EXPECT_EQ(4U, model.GetCursorPosition()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("www.google.com", model.text()); - EXPECT_EQ(3U, model.GetCursorPosition()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("www.google.com", model.text()); - EXPECT_EQ(2U, model.GetCursorPosition()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("www.google.com", model.text()); - EXPECT_EQ(1U, model.GetCursorPosition()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("", model.text()); - EXPECT_EQ(0U, model.GetCursorPosition()); - EXPECT_FALSE(model.Undo()); - EXPECT_TRUE(model.Redo()); - EXPECT_STR_EQ("www.google.com", model.text()); - EXPECT_EQ(1U, model.GetCursorPosition()); - EXPECT_TRUE(model.Redo()); - EXPECT_STR_EQ("www.google.com", model.text()); - EXPECT_EQ(2U, model.GetCursorPosition()); - EXPECT_TRUE(model.Redo()); - EXPECT_STR_EQ("www.google.com", model.text()); - EXPECT_EQ(3U, model.GetCursorPosition()); - EXPECT_TRUE(model.Redo()); - EXPECT_STR_EQ("www.google.com", model.text()); - EXPECT_EQ(4U, model.GetCursorPosition()); - EXPECT_TRUE(model.Redo()); - EXPECT_STR_EQ("www.youtube.com", model.text()); - EXPECT_EQ(5U, model.GetCursorPosition()); - EXPECT_FALSE(model.Redo()); -} - -TEST_F(TextfieldModelTest, UndoRedo_BackspaceThenSetText) { - // This is to test the undo/redo behavior of omnibox. - TextfieldModel model(NULL); - model.InsertChar('w'); - EXPECT_STR_EQ("w", model.text()); - EXPECT_EQ(1U, model.GetCursorPosition()); - model.SetText(base::ASCIIToUTF16("www.google.com")); - EXPECT_EQ(14U, model.GetCursorPosition()); - EXPECT_STR_EQ("www.google.com", model.text()); - model.SetText(base::ASCIIToUTF16("www.google.com")); // Confirm the text. - model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, false); - EXPECT_EQ(14U, model.GetCursorPosition()); - EXPECT_TRUE(model.Backspace()); - EXPECT_TRUE(model.Backspace()); - EXPECT_STR_EQ("www.google.c", model.text()); - // Autocomplete sets the text. - model.SetText(base::ASCIIToUTF16("www.google.com/search=www.google.c")); - EXPECT_STR_EQ("www.google.com/search=www.google.c", model.text()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("www.google.c", model.text()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("www.google.com", model.text()); -} - -TEST_F(TextfieldModelTest, UndoRedo_CutCopyPasteTest) { - TextfieldModel model(NULL); - model.SetText(base::ASCIIToUTF16("ABCDE")); - EXPECT_FALSE(model.Redo()); // There is nothing to redo. - // Test Cut. - model.SelectRange(gfx::Range(1, 3)); - model.Cut(); - EXPECT_STR_EQ("ADE", model.text()); - EXPECT_EQ(1U, model.GetCursorPosition()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("ABCDE", model.text()); - EXPECT_EQ(3U, model.GetCursorPosition()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("", model.text()); - EXPECT_EQ(0U, model.GetCursorPosition()); - EXPECT_FALSE(model.Undo()); // There is no more to undo. - EXPECT_STR_EQ("", model.text()); - EXPECT_TRUE(model.Redo()); - EXPECT_STR_EQ("ABCDE", model.text()); - EXPECT_EQ(5U, model.GetCursorPosition()); - EXPECT_TRUE(model.Redo()); - EXPECT_STR_EQ("ADE", model.text()); - EXPECT_EQ(1U, model.GetCursorPosition()); - EXPECT_FALSE(model.Redo()); // There is no more to redo. - EXPECT_STR_EQ("ADE", model.text()); - - model.Paste(); - model.Paste(); - model.Paste(); - EXPECT_STR_EQ("ABCBCBCDE", model.text()); - EXPECT_EQ(7U, model.GetCursorPosition()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("ABCBCDE", model.text()); - EXPECT_EQ(5U, model.GetCursorPosition()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("ABCDE", model.text()); - EXPECT_EQ(3U, model.GetCursorPosition()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("ADE", model.text()); - EXPECT_EQ(1U, model.GetCursorPosition()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("ABCDE", model.text()); - EXPECT_EQ(3U, model.GetCursorPosition()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("", model.text()); - EXPECT_EQ(0U, model.GetCursorPosition()); - EXPECT_FALSE(model.Undo()); - EXPECT_STR_EQ("", model.text()); - EXPECT_TRUE(model.Redo()); - EXPECT_STR_EQ("ABCDE", model.text()); - EXPECT_EQ(5U, model.GetCursorPosition()); - - // Test Redo. - EXPECT_TRUE(model.Redo()); - EXPECT_STR_EQ("ADE", model.text()); - EXPECT_EQ(1U, model.GetCursorPosition()); - EXPECT_TRUE(model.Redo()); - EXPECT_STR_EQ("ABCDE", model.text()); - EXPECT_EQ(3U, model.GetCursorPosition()); - EXPECT_TRUE(model.Redo()); - EXPECT_STR_EQ("ABCBCDE", model.text()); - EXPECT_EQ(5U, model.GetCursorPosition()); - EXPECT_TRUE(model.Redo()); - EXPECT_STR_EQ("ABCBCBCDE", model.text()); - EXPECT_EQ(7U, model.GetCursorPosition()); - EXPECT_FALSE(model.Redo()); - - // Test using SelectRange. - model.SelectRange(gfx::Range(1, 3)); - EXPECT_TRUE(model.Cut()); - EXPECT_STR_EQ("ABCBCDE", model.text()); - EXPECT_EQ(1U, model.GetCursorPosition()); - model.SelectRange(gfx::Range(1, 1)); - EXPECT_FALSE(model.Cut()); - model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, false); - EXPECT_TRUE(model.Paste()); - EXPECT_STR_EQ("ABCBCDEBC", model.text()); - EXPECT_EQ(9U, model.GetCursorPosition()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("ABCBCDE", model.text()); - EXPECT_EQ(7U, model.GetCursorPosition()); - // An empty cut shouldn't create an edit. - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("ABCBCBCDE", model.text()); - EXPECT_EQ(3U, model.GetCursorPosition()); - - // Test Copy. - ResetModel(&model); - model.SetText(base::ASCIIToUTF16("12345")); - EXPECT_STR_EQ("12345", model.text()); - EXPECT_EQ(5U, model.GetCursorPosition()); - model.SelectRange(gfx::Range(1, 3)); - model.Copy(); // Copy "23". - EXPECT_STR_EQ("12345", model.text()); - EXPECT_EQ(3U, model.GetCursorPosition()); - model.Paste(); // Paste "23" into "23". - EXPECT_STR_EQ("12345", model.text()); - EXPECT_EQ(3U, model.GetCursorPosition()); - model.Paste(); - EXPECT_STR_EQ("1232345", model.text()); - EXPECT_EQ(5U, model.GetCursorPosition()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("12345", model.text()); - EXPECT_EQ(3U, model.GetCursorPosition()); - // TODO(oshima): Change the return type from bool to enum. - EXPECT_FALSE(model.Undo()); // No text change. - EXPECT_STR_EQ("12345", model.text()); - EXPECT_EQ(3U, model.GetCursorPosition()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("", model.text()); - EXPECT_FALSE(model.Undo()); - // Test Redo. - EXPECT_TRUE(model.Redo()); - EXPECT_STR_EQ("12345", model.text()); - EXPECT_EQ(5U, model.GetCursorPosition()); - EXPECT_TRUE(model.Redo()); - EXPECT_STR_EQ("12345", model.text()); // For 1st paste - EXPECT_EQ(3U, model.GetCursorPosition()); - EXPECT_TRUE(model.Redo()); - EXPECT_STR_EQ("1232345", model.text()); - EXPECT_EQ(5U, model.GetCursorPosition()); - EXPECT_FALSE(model.Redo()); - EXPECT_STR_EQ("1232345", model.text()); - - // Test using SelectRange. - model.SelectRange(gfx::Range(1, 3)); - model.Copy(); - EXPECT_STR_EQ("1232345", model.text()); - model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, false); - EXPECT_TRUE(model.Paste()); - EXPECT_STR_EQ("123234523", model.text()); - EXPECT_EQ(9U, model.GetCursorPosition()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("1232345", model.text()); - EXPECT_EQ(7U, model.GetCursorPosition()); -} - -TEST_F(TextfieldModelTest, UndoRedo_CursorTest) { - TextfieldModel model(NULL); - model.InsertChar('a'); - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_LEFT, false); - model.MoveCursor(gfx::CHARACTER_BREAK, gfx::CURSOR_RIGHT, false); - model.InsertChar('b'); - // Moving the cursor shouldn't create a new edit. - EXPECT_STR_EQ("ab", model.text()); - EXPECT_FALSE(model.Redo()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("", model.text()); - EXPECT_FALSE(model.Undo()); - EXPECT_STR_EQ("", model.text()); - EXPECT_TRUE(model.Redo()); - EXPECT_STR_EQ("ab", model.text()); - EXPECT_EQ(2U, model.GetCursorPosition()); - EXPECT_FALSE(model.Redo()); -} - -void RunInsertReplaceTest(TextfieldModel& model) { - const bool reverse = model.render_text()->selection().is_reversed(); - model.InsertChar('1'); - model.InsertChar('2'); - model.InsertChar('3'); - EXPECT_STR_EQ("a123d", model.text()); - EXPECT_EQ(4U, model.GetCursorPosition()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("abcd", model.text()); - EXPECT_EQ(reverse ? 1U : 3U, model.GetCursorPosition()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("", model.text()); - EXPECT_EQ(0U, model.GetCursorPosition()); - EXPECT_FALSE(model.Undo()); - EXPECT_TRUE(model.Redo()); - EXPECT_STR_EQ("abcd", model.text()); - EXPECT_EQ(4U, model.GetCursorPosition()); - EXPECT_TRUE(model.Redo()); - EXPECT_STR_EQ("a123d", model.text()); - EXPECT_EQ(4U, model.GetCursorPosition()); - EXPECT_FALSE(model.Redo()); -} - -void RunOverwriteReplaceTest(TextfieldModel& model) { - const bool reverse = model.render_text()->selection().is_reversed(); - model.ReplaceChar('1'); - model.ReplaceChar('2'); - model.ReplaceChar('3'); - model.ReplaceChar('4'); - EXPECT_STR_EQ("a1234", model.text()); - EXPECT_EQ(5U, model.GetCursorPosition()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("abcd", model.text()); - EXPECT_EQ(reverse ? 1U : 3U, model.GetCursorPosition()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("", model.text()); - EXPECT_EQ(0U, model.GetCursorPosition()); - EXPECT_FALSE(model.Undo()); - EXPECT_TRUE(model.Redo()); - EXPECT_STR_EQ("abcd", model.text()); - EXPECT_EQ(4U, model.GetCursorPosition()); - EXPECT_TRUE(model.Redo()); - EXPECT_STR_EQ("a1234", model.text()); - EXPECT_EQ(5U, model.GetCursorPosition()); - EXPECT_FALSE(model.Redo()); -} - -TEST_F(TextfieldModelTest, UndoRedo_ReplaceTest) { - { - SCOPED_TRACE("Select forwards and insert."); - TextfieldModel model(NULL); - model.SetText(base::ASCIIToUTF16("abcd")); - model.SelectRange(gfx::Range(1, 3)); - RunInsertReplaceTest(model); - } - { - SCOPED_TRACE("Select reversed and insert."); - TextfieldModel model(NULL); - model.SetText(base::ASCIIToUTF16("abcd")); - model.SelectRange(gfx::Range(3, 1)); - RunInsertReplaceTest(model); - } - { - SCOPED_TRACE("Select forwards and overwrite."); - TextfieldModel model(NULL); - model.SetText(base::ASCIIToUTF16("abcd")); - model.SelectRange(gfx::Range(1, 3)); - RunOverwriteReplaceTest(model); - } - { - SCOPED_TRACE("Select reversed and overwrite."); - TextfieldModel model(NULL); - model.SetText(base::ASCIIToUTF16("abcd")); - model.SelectRange(gfx::Range(3, 1)); - RunOverwriteReplaceTest(model); - } -} - -TEST_F(TextfieldModelTest, UndoRedo_CompositionText) { - TextfieldModel model(NULL); - - ui::CompositionText composition; - composition.text = base::ASCIIToUTF16("abc"); - composition.underlines.push_back(ui::CompositionUnderline(0, 3, 0, false)); - composition.selection = gfx::Range(2, 3); - - model.SetText(base::ASCIIToUTF16("ABCDE")); - model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, false); - model.InsertChar('x'); - EXPECT_STR_EQ("ABCDEx", model.text()); - EXPECT_TRUE(model.Undo()); // set composition should forget undone edit. - model.SetCompositionText(composition); - EXPECT_TRUE(model.HasCompositionText()); - EXPECT_TRUE(model.HasSelection()); - EXPECT_STR_EQ("ABCDEabc", model.text()); - - // Confirm the composition. - model.ConfirmCompositionText(); - EXPECT_STR_EQ("ABCDEabc", model.text()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("ABCDE", model.text()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("", model.text()); - EXPECT_TRUE(model.Redo()); - EXPECT_STR_EQ("ABCDE", model.text()); - EXPECT_TRUE(model.Redo()); - EXPECT_STR_EQ("ABCDEabc", model.text()); - EXPECT_FALSE(model.Redo()); - - // Cancel the composition. - model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_LEFT, false); - model.SetCompositionText(composition); - EXPECT_STR_EQ("abcABCDEabc", model.text()); - model.CancelCompositionText(); - EXPECT_STR_EQ("ABCDEabc", model.text()); - EXPECT_FALSE(model.Redo()); - EXPECT_STR_EQ("ABCDEabc", model.text()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("ABCDE", model.text()); - EXPECT_TRUE(model.Redo()); - EXPECT_STR_EQ("ABCDEabc", model.text()); - EXPECT_FALSE(model.Redo()); - - // Call SetText with the same text as the result. - ResetModel(&model); - model.SetText(base::ASCIIToUTF16("ABCDE")); - model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, false); - model.SetCompositionText(composition); - EXPECT_STR_EQ("ABCDEabc", model.text()); - model.SetText(base::ASCIIToUTF16("ABCDEabc")); - EXPECT_STR_EQ("ABCDEabc", model.text()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("ABCDE", model.text()); - EXPECT_TRUE(model.Redo()); - EXPECT_STR_EQ("ABCDEabc", model.text()); - EXPECT_FALSE(model.Redo()); - - // Call SetText with a different result; the composition should be forgotten. - ResetModel(&model); - model.SetText(base::ASCIIToUTF16("ABCDE")); - model.MoveCursor(gfx::LINE_BREAK, gfx::CURSOR_RIGHT, false); - model.SetCompositionText(composition); - EXPECT_STR_EQ("ABCDEabc", model.text()); - model.SetText(base::ASCIIToUTF16("1234")); - EXPECT_STR_EQ("1234", model.text()); - EXPECT_TRUE(model.Undo()); - EXPECT_STR_EQ("ABCDE", model.text()); - EXPECT_TRUE(model.Redo()); - EXPECT_STR_EQ("1234", model.text()); - EXPECT_FALSE(model.Redo()); - - // TODO(oshima): Test the behavior with an IME. -} - -} // namespace views
diff --git a/ui/views/controls/textfield/textfield_test_api.cc b/ui/views/controls/textfield/textfield_test_api.cc deleted file mode 100644 index be45d24..0000000 --- a/ui/views/controls/textfield/textfield_test_api.cc +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/textfield/textfield_test_api.h" - -namespace views { - -TextfieldTestApi::TextfieldTestApi(Textfield* textfield) - : textfield_(textfield) { - DCHECK(textfield); -} - -void TextfieldTestApi::UpdateContextMenu() { - textfield_->UpdateContextMenu(); -} - -gfx::RenderText* TextfieldTestApi::GetRenderText() const { - return textfield_->GetRenderText(); -} - -void TextfieldTestApi::CreateTouchSelectionControllerAndNotifyIt() { - textfield_->CreateTouchSelectionControllerAndNotifyIt(); -} - -void TextfieldTestApi::ResetTouchSelectionController() { - textfield_->touch_selection_controller_.reset(); -} - -} // namespace views
diff --git a/ui/views/controls/textfield/textfield_test_api.h b/ui/views/controls/textfield/textfield_test_api.h deleted file mode 100644 index 1af2ffc..0000000 --- a/ui/views/controls/textfield/textfield_test_api.h +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_TEXTFIELD_TEXTFIELD_TEST_API_H_ -#define UI_VIEWS_CONTROLS_TEXTFIELD_TEXTFIELD_TEST_API_H_ - -#include "ui/views/controls/textfield/textfield.h" - -namespace views { - -// Helper class to access internal state of Textfield in tests. -class TextfieldTestApi { - public: - explicit TextfieldTestApi(Textfield* textfield); - - void UpdateContextMenu(); - - gfx::RenderText* GetRenderText() const; - - void CreateTouchSelectionControllerAndNotifyIt(); - - void ResetTouchSelectionController(); - - TextfieldModel* model() const { return textfield_->model_.get(); } - - ui::MenuModel* context_menu_contents() const { - return textfield_->context_menu_contents_.get(); - } - - ui::TouchSelectionController* touch_selection_controller() const { - return textfield_->touch_selection_controller_.get(); - } - - private: - Textfield* textfield_; - - DISALLOW_COPY_AND_ASSIGN(TextfieldTestApi); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_TEXTFIELD_TEXTFIELD_TEST_API_H_
diff --git a/ui/views/controls/textfield/textfield_unittest.cc b/ui/views/controls/textfield/textfield_unittest.cc deleted file mode 100644 index 560bb41..0000000 --- a/ui/views/controls/textfield/textfield_unittest.cc +++ /dev/null
@@ -1,2073 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/textfield/textfield.h" - -#include <set> -#include <string> -#include <vector> - -#include "base/command_line.h" -#include "base/pickle.h" -#include "base/strings/string16.h" -#include "base/strings/utf_string_conversions.h" -#include "ui/base/clipboard/clipboard.h" -#include "ui/base/clipboard/scoped_clipboard_writer.h" -#include "ui/base/dragdrop/drag_drop_types.h" -#include "ui/base/ime/text_input_client.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/base/ui_base_switches.h" -#include "ui/base/ui_base_switches_util.h" -#include "ui/events/event.h" -#include "ui/events/keycodes/keyboard_codes.h" -#include "ui/gfx/render_text.h" -#include "ui/strings/grit/ui_strings.h" -#include "ui/views/controls/textfield/textfield_controller.h" -#include "ui/views/controls/textfield/textfield_model.h" -#include "ui/views/controls/textfield/textfield_test_api.h" -#include "ui/views/focus/focus_manager.h" -#include "ui/views/ime/mock_input_method.h" -#include "ui/views/test/test_views_delegate.h" -#include "ui/views/test/views_test_base.h" -#include "ui/views/widget/widget.h" -#include "url/gurl.h" - -#if defined(OS_WIN) -#include "base/win/windows_version.h" -#endif - -#if defined(OS_LINUX) && !defined(OS_CHROMEOS) -#include "ui/events/linux/text_edit_key_bindings_delegate_auralinux.h" -#endif - -#if defined(USE_X11) -#include "ui/events/event_utils.h" -#endif - -using base::ASCIIToUTF16; -using base::UTF8ToUTF16; -using base::WideToUTF16; - -#define EXPECT_STR_EQ(ascii, utf16) EXPECT_EQ(ASCIIToUTF16(ascii), utf16) - -namespace { - -const base::char16 kHebrewLetterSamekh = 0x05E1; - -// A Textfield wrapper to intercept OnKey[Pressed|Released]() ressults. -class TestTextfield : public views::Textfield { - public: - TestTextfield() - : Textfield(), - key_handled_(false), - key_received_(false), - weak_ptr_factory_(this) {} - - virtual bool OnKeyPressed(const ui::KeyEvent& e) override { - key_received_ = true; - - // Since OnKeyPressed() might destroy |this|, get a weak pointer and - // verify it isn't null before writing the bool value to key_handled_. - base::WeakPtr<TestTextfield> textfield(weak_ptr_factory_.GetWeakPtr()); - bool key = views::Textfield::OnKeyPressed(e); - - if (!textfield) - return key; - - key_handled_ = key; - - return key_handled_; - } - - virtual bool OnKeyReleased(const ui::KeyEvent& e) override { - key_received_ = true; - key_handled_ = views::Textfield::OnKeyReleased(e); - return key_handled_; - } - - bool key_handled() const { return key_handled_; } - bool key_received() const { return key_received_; } - - void clear() { key_received_ = key_handled_ = false; } - - private: - bool key_handled_; - bool key_received_; - - base::WeakPtrFactory<TestTextfield> weak_ptr_factory_; - - DISALLOW_COPY_AND_ASSIGN(TestTextfield); -}; - -// Convenience to make constructing a GestureEvent simpler. -class GestureEventForTest : public ui::GestureEvent { - public: - GestureEventForTest(int x, int y, ui::GestureEventDetails details) - : GestureEvent(x, y, 0, base::TimeDelta(), details) {} - - private: - DISALLOW_COPY_AND_ASSIGN(GestureEventForTest); -}; - -// This controller will happily destroy the target textfield passed on -// construction when a key event is triggered. -class TextfieldDestroyerController : public views::TextfieldController { - public: - explicit TextfieldDestroyerController(views::Textfield* target) - : target_(target) { - target_->set_controller(this); - } - - views::Textfield* target() { return target_.get(); } - - // views::TextfieldController: - virtual bool HandleKeyEvent(views::Textfield* sender, - const ui::KeyEvent& key_event) override { - target_.reset(); - return false; - } - - private: - scoped_ptr<views::Textfield> target_; -}; - -base::string16 GetClipboardText(ui::ClipboardType type) { - base::string16 text; - ui::Clipboard::GetForCurrentThread()->ReadText(type, &text); - return text; -} - -void SetClipboardText(ui::ClipboardType type, const std::string& text) { - ui::ScopedClipboardWriter(type).WriteText(ASCIIToUTF16(text)); -} - -} // namespace - -namespace views { - -class TextfieldTest : public ViewsTestBase, public TextfieldController { - public: - TextfieldTest() - : widget_(NULL), - textfield_(NULL), - model_(NULL), - input_method_(NULL), - on_before_user_action_(0), - on_after_user_action_(0), - copied_to_clipboard_(ui::CLIPBOARD_TYPE_LAST) { - } - - // ::testing::Test: - virtual void SetUp() { - ViewsTestBase::SetUp(); - } - - virtual void TearDown() { - if (widget_) - widget_->Close(); - ViewsTestBase::TearDown(); - } - - ui::ClipboardType GetAndResetCopiedToClipboard() { - ui::ClipboardType clipboard_type = copied_to_clipboard_; - copied_to_clipboard_ = ui::CLIPBOARD_TYPE_LAST; - return clipboard_type; - } - - // TextfieldController: - virtual void ContentsChanged(Textfield* sender, - const base::string16& new_contents) override { - // Paste calls TextfieldController::ContentsChanged() explicitly even if the - // paste action did not change the content. So |new_contents| may match - // |last_contents_|. For more info, see http://crbug.com/79002 - last_contents_ = new_contents; - } - - virtual void OnBeforeUserAction(Textfield* sender) override { - ++on_before_user_action_; - } - - virtual void OnAfterUserAction(Textfield* sender) override { - ++on_after_user_action_; - } - - virtual void OnAfterCutOrCopy(ui::ClipboardType clipboard_type) override { - copied_to_clipboard_ = clipboard_type; - } - - void InitTextfield() { - InitTextfields(1); - } - - void InitTextfields(int count) { - ASSERT_FALSE(textfield_); - textfield_ = new TestTextfield(); - textfield_->set_controller(this); - widget_ = new Widget(); - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.bounds = gfx::Rect(100, 100, 100, 100); - widget_->Init(params); - View* container = new View(); - widget_->SetContentsView(container); - container->AddChildView(textfield_); - textfield_->SetBoundsRect(params.bounds); - textfield_->set_id(1); - test_api_.reset(new TextfieldTestApi(textfield_)); - - for (int i = 1; i < count; i++) { - Textfield* textfield = new Textfield(); - container->AddChildView(textfield); - textfield->set_id(i + 1); - } - - model_ = test_api_->model(); - model_->ClearEditHistory(); - - input_method_ = new MockInputMethod(); - widget_->ReplaceInputMethod(input_method_); - - // Activate the widget and focus the textfield for input handling. - widget_->Activate(); - textfield_->RequestFocus(); - } - - ui::MenuModel* GetContextMenuModel() { - test_api_->UpdateContextMenu(); - return test_api_->context_menu_contents(); - } - - protected: - void SendKeyEvent(ui::KeyboardCode key_code, - bool alt, - bool shift, - bool control, - bool caps_lock) { - int flags = (alt ? ui::EF_ALT_DOWN : 0) | - (shift ? ui::EF_SHIFT_DOWN : 0) | - (control ? ui::EF_CONTROL_DOWN : 0) | - (caps_lock ? ui::EF_CAPS_LOCK_DOWN : 0); - ui::KeyEvent event(ui::ET_KEY_PRESSED, key_code, flags); - input_method_->DispatchKeyEvent(event); - } - - void SendKeyEvent(ui::KeyboardCode key_code, bool shift, bool control) { - SendKeyEvent(key_code, false, shift, control, false); - } - - void SendKeyEvent(ui::KeyboardCode key_code) { - SendKeyEvent(key_code, false, false); - } - - void SendKeyEvent(base::char16 ch) { - if (ch < 0x80) { - ui::KeyboardCode code = - ch == ' ' ? ui::VKEY_SPACE : - static_cast<ui::KeyboardCode>(ui::VKEY_A + ch - 'a'); - SendKeyEvent(code); - } else { - ui::KeyEvent event(ch, ui::VKEY_UNKNOWN, ui::EF_NONE); - input_method_->DispatchKeyEvent(event); - } - } - - View* GetFocusedView() { - return widget_->GetFocusManager()->GetFocusedView(); - } - - int GetCursorPositionX(int cursor_pos) { - return test_api_->GetRenderText()->GetCursorBounds( - gfx::SelectionModel(cursor_pos, gfx::CURSOR_FORWARD), false).x(); - } - - // Get the current cursor bounds. - gfx::Rect GetCursorBounds() { - return test_api_->GetRenderText()->GetUpdatedCursorBounds(); - } - - // Get the cursor bounds of |sel|. - gfx::Rect GetCursorBounds(const gfx::SelectionModel& sel) { - return test_api_->GetRenderText()->GetCursorBounds(sel, true); - } - - gfx::Rect GetDisplayRect() { - return test_api_->GetRenderText()->display_rect(); - } - - // Mouse click on the point whose x-axis is |bound|'s x plus |x_offset| and - // y-axis is in the middle of |bound|'s vertical range. - void MouseClick(const gfx::Rect bound, int x_offset) { - gfx::Point point(bound.x() + x_offset, bound.y() + bound.height() / 2); - ui::MouseEvent click(ui::ET_MOUSE_PRESSED, point, point, - ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); - textfield_->OnMousePressed(click); - ui::MouseEvent release(ui::ET_MOUSE_RELEASED, point, point, - ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); - textfield_->OnMouseReleased(release); - } - - // This is to avoid double/triple click. - void NonClientMouseClick() { - ui::MouseEvent click(ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(), - ui::EF_LEFT_MOUSE_BUTTON | ui::EF_IS_NON_CLIENT, - ui::EF_LEFT_MOUSE_BUTTON); - textfield_->OnMousePressed(click); - ui::MouseEvent release(ui::ET_MOUSE_RELEASED, gfx::Point(), gfx::Point(), - ui::EF_LEFT_MOUSE_BUTTON | ui::EF_IS_NON_CLIENT, - ui::EF_LEFT_MOUSE_BUTTON); - textfield_->OnMouseReleased(release); - } - - // Simulates a complete tap. - void Tap(const gfx::Point& point) { - GestureEventForTest begin( - point.x(), point.y(), ui::GestureEventDetails(ui::ET_GESTURE_BEGIN)); - textfield_->OnGestureEvent(&begin); - - GestureEventForTest tap_down( - point.x(), point.y(), ui::GestureEventDetails(ui::ET_GESTURE_TAP_DOWN)); - textfield_->OnGestureEvent(&tap_down); - - GestureEventForTest show_press( - point.x(), - point.y(), - ui::GestureEventDetails(ui::ET_GESTURE_SHOW_PRESS)); - textfield_->OnGestureEvent(&show_press); - - ui::GestureEventDetails tap_details(ui::ET_GESTURE_TAP); - tap_details.set_tap_count(1); - GestureEventForTest tap(point.x(), point.y(), tap_details); - textfield_->OnGestureEvent(&tap); - - GestureEventForTest end( - point.x(), point.y(), ui::GestureEventDetails(ui::ET_GESTURE_END)); - textfield_->OnGestureEvent(&end); - } - - void VerifyTextfieldContextMenuContents(bool textfield_has_selection, - bool can_undo, - ui::MenuModel* menu) { - EXPECT_EQ(can_undo, menu->IsEnabledAt(0 /* UNDO */)); - EXPECT_TRUE(menu->IsEnabledAt(1 /* Separator */)); - EXPECT_EQ(textfield_has_selection, menu->IsEnabledAt(2 /* CUT */)); - EXPECT_EQ(textfield_has_selection, menu->IsEnabledAt(3 /* COPY */)); - EXPECT_NE(GetClipboardText(ui::CLIPBOARD_TYPE_COPY_PASTE).empty(), - menu->IsEnabledAt(4 /* PASTE */)); - EXPECT_EQ(textfield_has_selection, menu->IsEnabledAt(5 /* DELETE */)); - EXPECT_TRUE(menu->IsEnabledAt(6 /* Separator */)); - EXPECT_TRUE(menu->IsEnabledAt(7 /* SELECT ALL */)); - } - - // We need widget to populate wrapper class. - Widget* widget_; - - TestTextfield* textfield_; - scoped_ptr<TextfieldTestApi> test_api_; - TextfieldModel* model_; - - // The string from Controller::ContentsChanged callback. - base::string16 last_contents_; - - // For testing input method related behaviors. - MockInputMethod* input_method_; - - // Indicates how many times OnBeforeUserAction() is called. - int on_before_user_action_; - - // Indicates how many times OnAfterUserAction() is called. - int on_after_user_action_; - - private: - ui::ClipboardType copied_to_clipboard_; - - DISALLOW_COPY_AND_ASSIGN(TextfieldTest); -}; - -TEST_F(TextfieldTest, ModelChangesTest) { - InitTextfield(); - - // TextfieldController::ContentsChanged() shouldn't be called when changing - // text programmatically. - last_contents_.clear(); - textfield_->SetText(ASCIIToUTF16("this is")); - - EXPECT_STR_EQ("this is", model_->text()); - EXPECT_STR_EQ("this is", textfield_->text()); - EXPECT_TRUE(last_contents_.empty()); - - textfield_->AppendText(ASCIIToUTF16(" a test")); - EXPECT_STR_EQ("this is a test", model_->text()); - EXPECT_STR_EQ("this is a test", textfield_->text()); - EXPECT_TRUE(last_contents_.empty()); - - EXPECT_EQ(base::string16(), textfield_->GetSelectedText()); - textfield_->SelectAll(false); - EXPECT_STR_EQ("this is a test", textfield_->GetSelectedText()); - EXPECT_TRUE(last_contents_.empty()); -} - -TEST_F(TextfieldTest, KeyTest) { - InitTextfield(); - // Event flags: key, alt, shift, ctrl, caps-lock. - SendKeyEvent(ui::VKEY_T, false, true, false, false); - SendKeyEvent(ui::VKEY_E, false, false, false, false); - SendKeyEvent(ui::VKEY_X, false, true, false, true); - SendKeyEvent(ui::VKEY_T, false, false, false, true); - SendKeyEvent(ui::VKEY_1, false, true, false, false); - SendKeyEvent(ui::VKEY_1, false, false, false, false); - SendKeyEvent(ui::VKEY_1, false, true, false, true); - SendKeyEvent(ui::VKEY_1, false, false, false, true); - EXPECT_STR_EQ("TexT!1!1", textfield_->text()); -} - -TEST_F(TextfieldTest, ControlAndSelectTest) { - // Insert a test string in a textfield. - InitTextfield(); - textfield_->SetText(ASCIIToUTF16("one two three")); - SendKeyEvent(ui::VKEY_HOME, false /* shift */, false /* control */); - SendKeyEvent(ui::VKEY_RIGHT, true, false); - SendKeyEvent(ui::VKEY_RIGHT, true, false); - SendKeyEvent(ui::VKEY_RIGHT, true, false); - - EXPECT_STR_EQ("one", textfield_->GetSelectedText()); - - // Test word select. - SendKeyEvent(ui::VKEY_RIGHT, true, true); - EXPECT_STR_EQ("one two", textfield_->GetSelectedText()); - SendKeyEvent(ui::VKEY_RIGHT, true, true); - EXPECT_STR_EQ("one two three", textfield_->GetSelectedText()); - SendKeyEvent(ui::VKEY_LEFT, true, true); - EXPECT_STR_EQ("one two ", textfield_->GetSelectedText()); - SendKeyEvent(ui::VKEY_LEFT, true, true); - EXPECT_STR_EQ("one ", textfield_->GetSelectedText()); - - // Replace the selected text. - SendKeyEvent(ui::VKEY_Z, true, false); - SendKeyEvent(ui::VKEY_E, true, false); - SendKeyEvent(ui::VKEY_R, true, false); - SendKeyEvent(ui::VKEY_O, true, false); - SendKeyEvent(ui::VKEY_SPACE, false, false); - EXPECT_STR_EQ("ZERO two three", textfield_->text()); - - SendKeyEvent(ui::VKEY_END, true, false); - EXPECT_STR_EQ("two three", textfield_->GetSelectedText()); - SendKeyEvent(ui::VKEY_HOME, true, false); - EXPECT_STR_EQ("ZERO ", textfield_->GetSelectedText()); -} - -TEST_F(TextfieldTest, InsertionDeletionTest) { - // Insert a test string in a textfield. - InitTextfield(); - for (size_t i = 0; i < 10; i++) - SendKeyEvent(static_cast<ui::KeyboardCode>(ui::VKEY_A + i)); - EXPECT_STR_EQ("abcdefghij", textfield_->text()); - - // Test the delete and backspace keys. - textfield_->SelectRange(gfx::Range(5)); - for (int i = 0; i < 3; i++) - SendKeyEvent(ui::VKEY_BACK); - EXPECT_STR_EQ("abfghij", textfield_->text()); - for (int i = 0; i < 3; i++) - SendKeyEvent(ui::VKEY_DELETE); - EXPECT_STR_EQ("abij", textfield_->text()); - - // Select all and replace with "k". - textfield_->SelectAll(false); - SendKeyEvent(ui::VKEY_K); - EXPECT_STR_EQ("k", textfield_->text()); - - // Delete the previous word from cursor. - textfield_->SetText(ASCIIToUTF16("one two three four")); - SendKeyEvent(ui::VKEY_END); - SendKeyEvent(ui::VKEY_BACK, false, false, true, false); - EXPECT_STR_EQ("one two three ", textfield_->text()); - - // Delete to a line break on Linux and ChromeOS, to a word break on Windows. - SendKeyEvent(ui::VKEY_LEFT, false, false, true, false); - SendKeyEvent(ui::VKEY_BACK, false, true, true, false); -#if defined(OS_LINUX) - EXPECT_STR_EQ("three ", textfield_->text()); -#else - EXPECT_STR_EQ("one three ", textfield_->text()); -#endif - - // Delete the next word from cursor. - textfield_->SetText(ASCIIToUTF16("one two three four")); - SendKeyEvent(ui::VKEY_HOME); - SendKeyEvent(ui::VKEY_DELETE, false, false, true, false); - EXPECT_STR_EQ(" two three four", textfield_->text()); - - // Delete to a line break on Linux and ChromeOS, to a word break on Windows. - SendKeyEvent(ui::VKEY_RIGHT, false, false, true, false); - SendKeyEvent(ui::VKEY_DELETE, false, true, true, false); -#if defined(OS_LINUX) - EXPECT_STR_EQ(" two", textfield_->text()); -#else - EXPECT_STR_EQ(" two four", textfield_->text()); -#endif -} - -TEST_F(TextfieldTest, PasswordTest) { - InitTextfield(); - textfield_->SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD); - EXPECT_EQ(ui::TEXT_INPUT_TYPE_PASSWORD, textfield_->GetTextInputType()); - EXPECT_TRUE(textfield_->enabled()); - EXPECT_TRUE(textfield_->IsFocusable()); - - last_contents_.clear(); - textfield_->SetText(ASCIIToUTF16("password")); - // Ensure text() and the callback returns the actual text instead of "*". - EXPECT_STR_EQ("password", textfield_->text()); - EXPECT_TRUE(last_contents_.empty()); - model_->SelectAll(false); - SetClipboardText(ui::CLIPBOARD_TYPE_COPY_PASTE, "foo"); - - // Cut and copy should be disabled. - EXPECT_FALSE(textfield_->IsCommandIdEnabled(IDS_APP_CUT)); - textfield_->ExecuteCommand(IDS_APP_CUT, 0); - SendKeyEvent(ui::VKEY_X, false, true); - EXPECT_FALSE(textfield_->IsCommandIdEnabled(IDS_APP_COPY)); - textfield_->ExecuteCommand(IDS_APP_COPY, 0); - SendKeyEvent(ui::VKEY_C, false, true); - SendKeyEvent(ui::VKEY_INSERT, false, true); - EXPECT_STR_EQ("foo", GetClipboardText(ui::CLIPBOARD_TYPE_COPY_PASTE)); - EXPECT_STR_EQ("password", textfield_->text()); - // [Shift]+[Delete] should just delete without copying text to the clipboard. - textfield_->SelectAll(false); - SendKeyEvent(ui::VKEY_DELETE, true, false); - - // Paste should work normally. - EXPECT_TRUE(textfield_->IsCommandIdEnabled(IDS_APP_PASTE)); - textfield_->ExecuteCommand(IDS_APP_PASTE, 0); - SendKeyEvent(ui::VKEY_V, false, true); - SendKeyEvent(ui::VKEY_INSERT, true, false); - EXPECT_STR_EQ("foo", GetClipboardText(ui::CLIPBOARD_TYPE_COPY_PASTE)); - EXPECT_STR_EQ("foofoofoo", textfield_->text()); -} - -TEST_F(TextfieldTest, TextInputType) { - InitTextfield(); - - // Defaults to TEXT - EXPECT_EQ(ui::TEXT_INPUT_TYPE_TEXT, textfield_->GetTextInputType()); - - // And can be set. - textfield_->SetTextInputType(ui::TEXT_INPUT_TYPE_URL); - EXPECT_EQ(ui::TEXT_INPUT_TYPE_URL, textfield_->GetTextInputType()); - textfield_->SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD); - EXPECT_EQ(ui::TEXT_INPUT_TYPE_PASSWORD, textfield_->GetTextInputType()); - - // Readonly textfields have type NONE - textfield_->SetReadOnly(true); - EXPECT_EQ(ui::TEXT_INPUT_TYPE_NONE, textfield_->GetTextInputType()); - - textfield_->SetReadOnly(false); - EXPECT_EQ(ui::TEXT_INPUT_TYPE_PASSWORD, textfield_->GetTextInputType()); - - // As do disabled textfields - textfield_->SetEnabled(false); - EXPECT_EQ(ui::TEXT_INPUT_TYPE_NONE, textfield_->GetTextInputType()); - - textfield_->SetEnabled(true); - EXPECT_EQ(ui::TEXT_INPUT_TYPE_PASSWORD, textfield_->GetTextInputType()); -} - -TEST_F(TextfieldTest, OnKeyPress) { - InitTextfield(); - - // Character keys are handled by the input method. - SendKeyEvent(ui::VKEY_A); - EXPECT_TRUE(textfield_->key_received()); - EXPECT_FALSE(textfield_->key_handled()); - textfield_->clear(); - - // Arrow keys and home/end are handled by the textfield. - SendKeyEvent(ui::VKEY_LEFT); - EXPECT_TRUE(textfield_->key_received()); - EXPECT_TRUE(textfield_->key_handled()); - textfield_->clear(); - - SendKeyEvent(ui::VKEY_RIGHT); - EXPECT_TRUE(textfield_->key_received()); - EXPECT_TRUE(textfield_->key_handled()); - textfield_->clear(); - - SendKeyEvent(ui::VKEY_HOME); - EXPECT_TRUE(textfield_->key_received()); - EXPECT_TRUE(textfield_->key_handled()); - textfield_->clear(); - - SendKeyEvent(ui::VKEY_END); - EXPECT_TRUE(textfield_->key_received()); - EXPECT_TRUE(textfield_->key_handled()); - textfield_->clear(); - - // F24, up/down key won't be handled. - SendKeyEvent(ui::VKEY_F24); - EXPECT_TRUE(textfield_->key_received()); - EXPECT_FALSE(textfield_->key_handled()); - textfield_->clear(); - - SendKeyEvent(ui::VKEY_UP); - EXPECT_TRUE(textfield_->key_received()); - EXPECT_FALSE(textfield_->key_handled()); - textfield_->clear(); - - SendKeyEvent(ui::VKEY_DOWN); - EXPECT_TRUE(textfield_->key_received()); - EXPECT_FALSE(textfield_->key_handled()); - textfield_->clear(); -} - -// Tests that default key bindings are handled even with a delegate installed. -TEST_F(TextfieldTest, OnKeyPressBinding) { - InitTextfield(); - -#if defined(OS_LINUX) && !defined(OS_CHROMEOS) - // Install a TextEditKeyBindingsDelegateAuraLinux that does nothing. - class TestDelegate : public ui::TextEditKeyBindingsDelegateAuraLinux { - public: - TestDelegate() {} - virtual ~TestDelegate() {} - - virtual bool MatchEvent( - const ui::Event& event, - std::vector<ui::TextEditCommandAuraLinux>* commands) override { - return false; - } - - private: - DISALLOW_COPY_AND_ASSIGN(TestDelegate); - }; - - TestDelegate delegate; - ui::SetTextEditKeyBindingsDelegate(&delegate); -#endif - - SendKeyEvent(ui::VKEY_A, false, false); - EXPECT_STR_EQ("a", textfield_->text()); - textfield_->clear(); - - // Undo/Redo command keys are handled by the textfield. - SendKeyEvent(ui::VKEY_Z, false, true); - EXPECT_TRUE(textfield_->key_received()); - EXPECT_TRUE(textfield_->key_handled()); - EXPECT_TRUE(textfield_->text().empty()); - textfield_->clear(); - - SendKeyEvent(ui::VKEY_Z, true, true); - EXPECT_TRUE(textfield_->key_received()); - EXPECT_TRUE(textfield_->key_handled()); - EXPECT_STR_EQ("a", textfield_->text()); - textfield_->clear(); - -#if defined(OS_LINUX) && !defined(OS_CHROMEOS) - ui::SetTextEditKeyBindingsDelegate(NULL); -#endif -} - -TEST_F(TextfieldTest, CursorMovement) { - InitTextfield(); - - // Test with trailing whitespace. - textfield_->SetText(ASCIIToUTF16("one two hre ")); - - // Send the cursor at the end. - SendKeyEvent(ui::VKEY_END); - - // Ctrl+Left should move the cursor just before the last word. - SendKeyEvent(ui::VKEY_LEFT, false, true); - SendKeyEvent(ui::VKEY_T); - EXPECT_STR_EQ("one two thre ", textfield_->text()); - EXPECT_STR_EQ("one two thre ", last_contents_); - - // Ctrl+Right should move the cursor to the end of the last word. - SendKeyEvent(ui::VKEY_RIGHT, false, true); - SendKeyEvent(ui::VKEY_E); - EXPECT_STR_EQ("one two three ", textfield_->text()); - EXPECT_STR_EQ("one two three ", last_contents_); - - // Ctrl+Right again should move the cursor to the end. - SendKeyEvent(ui::VKEY_RIGHT, false, true); - SendKeyEvent(ui::VKEY_BACK); - EXPECT_STR_EQ("one two three", textfield_->text()); - EXPECT_STR_EQ("one two three", last_contents_); - - // Test with leading whitespace. - textfield_->SetText(ASCIIToUTF16(" ne two")); - - // Send the cursor at the beginning. - SendKeyEvent(ui::VKEY_HOME); - - // Ctrl+Right, then Ctrl+Left should move the cursor to the beginning of the - // first word. - SendKeyEvent(ui::VKEY_RIGHT, false, true); - SendKeyEvent(ui::VKEY_LEFT, false, true); - SendKeyEvent(ui::VKEY_O); - EXPECT_STR_EQ(" one two", textfield_->text()); - EXPECT_STR_EQ(" one two", last_contents_); - - // Ctrl+Left to move the cursor to the beginning of the first word. - SendKeyEvent(ui::VKEY_LEFT, false, true); - // Ctrl+Left again should move the cursor back to the very beginning. - SendKeyEvent(ui::VKEY_LEFT, false, true); - SendKeyEvent(ui::VKEY_DELETE); - EXPECT_STR_EQ("one two", textfield_->text()); - EXPECT_STR_EQ("one two", last_contents_); -} - -TEST_F(TextfieldTest, FocusTraversalTest) { - InitTextfields(3); - textfield_->RequestFocus(); - - EXPECT_EQ(1, GetFocusedView()->id()); - widget_->GetFocusManager()->AdvanceFocus(false); - EXPECT_EQ(2, GetFocusedView()->id()); - widget_->GetFocusManager()->AdvanceFocus(false); - EXPECT_EQ(3, GetFocusedView()->id()); - // Cycle back to the first textfield. - widget_->GetFocusManager()->AdvanceFocus(false); - EXPECT_EQ(1, GetFocusedView()->id()); - - widget_->GetFocusManager()->AdvanceFocus(true); - EXPECT_EQ(3, GetFocusedView()->id()); - widget_->GetFocusManager()->AdvanceFocus(true); - EXPECT_EQ(2, GetFocusedView()->id()); - widget_->GetFocusManager()->AdvanceFocus(true); - EXPECT_EQ(1, GetFocusedView()->id()); - // Cycle back to the last textfield. - widget_->GetFocusManager()->AdvanceFocus(true); - EXPECT_EQ(3, GetFocusedView()->id()); - - // Request focus should still work. - textfield_->RequestFocus(); - EXPECT_EQ(1, GetFocusedView()->id()); - - // Test if clicking on textfield view sets the focus. - widget_->GetFocusManager()->AdvanceFocus(true); - EXPECT_EQ(3, GetFocusedView()->id()); - ui::MouseEvent click(ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(), - ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); - textfield_->OnMousePressed(click); - EXPECT_EQ(1, GetFocusedView()->id()); -} - -TEST_F(TextfieldTest, ContextMenuDisplayTest) { - InitTextfield(); - EXPECT_TRUE(textfield_->context_menu_controller()); - textfield_->SetText(ASCIIToUTF16("hello world")); - ui::Clipboard::GetForCurrentThread()->Clear(ui::CLIPBOARD_TYPE_COPY_PASTE); - textfield_->ClearEditHistory(); - EXPECT_TRUE(GetContextMenuModel()); - VerifyTextfieldContextMenuContents(false, false, GetContextMenuModel()); - - textfield_->SelectAll(false); - VerifyTextfieldContextMenuContents(true, false, GetContextMenuModel()); - - SendKeyEvent(ui::VKEY_T); - VerifyTextfieldContextMenuContents(false, true, GetContextMenuModel()); - - textfield_->SelectAll(false); - VerifyTextfieldContextMenuContents(true, true, GetContextMenuModel()); - - // Exercise the "paste enabled?" check in the verifier. - SetClipboardText(ui::CLIPBOARD_TYPE_COPY_PASTE, "Test"); - VerifyTextfieldContextMenuContents(true, true, GetContextMenuModel()); -} - -TEST_F(TextfieldTest, DoubleAndTripleClickTest) { - InitTextfield(); - textfield_->SetText(ASCIIToUTF16("hello world")); - ui::MouseEvent click(ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(), - ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); - ui::MouseEvent release(ui::ET_MOUSE_RELEASED, gfx::Point(), gfx::Point(), - ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); - ui::MouseEvent double_click( - ui::ET_MOUSE_PRESSED, gfx::Point(), gfx::Point(), - ui::EF_LEFT_MOUSE_BUTTON | ui::EF_IS_DOUBLE_CLICK, - ui::EF_LEFT_MOUSE_BUTTON); - - // Test for double click. - textfield_->OnMousePressed(click); - textfield_->OnMouseReleased(release); - EXPECT_TRUE(textfield_->GetSelectedText().empty()); - textfield_->OnMousePressed(double_click); - textfield_->OnMouseReleased(release); - EXPECT_STR_EQ("hello", textfield_->GetSelectedText()); - - // Test for triple click. - textfield_->OnMousePressed(click); - textfield_->OnMouseReleased(release); - EXPECT_STR_EQ("hello world", textfield_->GetSelectedText()); - - // Another click should reset back to double click. - textfield_->OnMousePressed(click); - textfield_->OnMouseReleased(release); - EXPECT_STR_EQ("hello", textfield_->GetSelectedText()); -} - -TEST_F(TextfieldTest, DragToSelect) { - InitTextfield(); - textfield_->SetText(ASCIIToUTF16("hello world")); - const int kStart = GetCursorPositionX(5); - const int kEnd = 500; - gfx::Point start_point(kStart, 0); - gfx::Point end_point(kEnd, 0); - ui::MouseEvent click_a(ui::ET_MOUSE_PRESSED, start_point, start_point, - ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); - ui::MouseEvent click_b(ui::ET_MOUSE_PRESSED, end_point, end_point, - ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); - ui::MouseEvent drag_left(ui::ET_MOUSE_DRAGGED, gfx::Point(), gfx::Point(), - ui::EF_LEFT_MOUSE_BUTTON, 0); - ui::MouseEvent drag_right(ui::ET_MOUSE_DRAGGED, end_point, end_point, - ui::EF_LEFT_MOUSE_BUTTON, 0); - ui::MouseEvent release(ui::ET_MOUSE_RELEASED, end_point, end_point, - ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); - textfield_->OnMousePressed(click_a); - EXPECT_TRUE(textfield_->GetSelectedText().empty()); - // Check that dragging left selects the beginning of the string. - textfield_->OnMouseDragged(drag_left); - base::string16 text_left = textfield_->GetSelectedText(); - EXPECT_STR_EQ("hello", text_left); - // Check that dragging right selects the rest of the string. - textfield_->OnMouseDragged(drag_right); - base::string16 text_right = textfield_->GetSelectedText(); - EXPECT_STR_EQ(" world", text_right); - // Check that releasing in the same location does not alter the selection. - textfield_->OnMouseReleased(release); - EXPECT_EQ(text_right, textfield_->GetSelectedText()); - // Check that dragging from beyond the text length works too. - textfield_->OnMousePressed(click_b); - textfield_->OnMouseDragged(drag_left); - textfield_->OnMouseReleased(release); - EXPECT_EQ(textfield_->text(), textfield_->GetSelectedText()); -} - -#if defined(OS_WIN) -TEST_F(TextfieldTest, DragAndDrop_AcceptDrop) { - InitTextfield(); - textfield_->SetText(ASCIIToUTF16("hello world")); - - ui::OSExchangeData data; - base::string16 string(ASCIIToUTF16("string ")); - data.SetString(string); - int formats = 0; - std::set<OSExchangeData::CustomFormat> custom_formats; - - // Ensure that disabled textfields do not accept drops. - textfield_->SetEnabled(false); - EXPECT_FALSE(textfield_->GetDropFormats(&formats, &custom_formats)); - EXPECT_EQ(0, formats); - EXPECT_TRUE(custom_formats.empty()); - EXPECT_FALSE(textfield_->CanDrop(data)); - textfield_->SetEnabled(true); - - // Ensure that read-only textfields do not accept drops. - textfield_->SetReadOnly(true); - EXPECT_FALSE(textfield_->GetDropFormats(&formats, &custom_formats)); - EXPECT_EQ(0, formats); - EXPECT_TRUE(custom_formats.empty()); - EXPECT_FALSE(textfield_->CanDrop(data)); - textfield_->SetReadOnly(false); - - // Ensure that enabled and editable textfields do accept drops. - EXPECT_TRUE(textfield_->GetDropFormats(&formats, &custom_formats)); - EXPECT_EQ(ui::OSExchangeData::STRING, formats); - EXPECT_TRUE(custom_formats.empty()); - EXPECT_TRUE(textfield_->CanDrop(data)); - gfx::Point drop_point(GetCursorPositionX(6), 0); - ui::DropTargetEvent drop(data, drop_point, drop_point, - ui::DragDropTypes::DRAG_COPY | ui::DragDropTypes::DRAG_MOVE); - EXPECT_EQ(ui::DragDropTypes::DRAG_COPY | ui::DragDropTypes::DRAG_MOVE, - textfield_->OnDragUpdated(drop)); - EXPECT_EQ(ui::DragDropTypes::DRAG_COPY, textfield_->OnPerformDrop(drop)); - EXPECT_STR_EQ("hello string world", textfield_->text()); - - // Ensure that textfields do not accept non-OSExchangeData::STRING types. - ui::OSExchangeData bad_data; - bad_data.SetFilename(base::FilePath(FILE_PATH_LITERAL("x"))); - ui::OSExchangeData::CustomFormat fmt = ui::Clipboard::GetBitmapFormatType(); - bad_data.SetPickledData(fmt, Pickle()); - bad_data.SetFileContents(base::FilePath(L"x"), "x"); - bad_data.SetHtml(base::string16(ASCIIToUTF16("x")), GURL("x.org")); - ui::OSExchangeData::DownloadFileInfo download(base::FilePath(), NULL); - bad_data.SetDownloadFileInfo(download); - EXPECT_FALSE(textfield_->CanDrop(bad_data)); -} -#endif - -TEST_F(TextfieldTest, DragAndDrop_InitiateDrag) { - InitTextfield(); - textfield_->SetText(ASCIIToUTF16("hello string world")); - - // Ensure the textfield will provide selected text for drag data. - base::string16 string; - ui::OSExchangeData data; - const gfx::Range kStringRange(6, 12); - textfield_->SelectRange(kStringRange); - const gfx::Point kStringPoint(GetCursorPositionX(9), 0); - textfield_->WriteDragDataForView(NULL, kStringPoint, &data); - EXPECT_TRUE(data.GetString(&string)); - EXPECT_EQ(textfield_->GetSelectedText(), string); - - // Ensure that disabled textfields do not support drag operations. - textfield_->SetEnabled(false); - EXPECT_EQ(ui::DragDropTypes::DRAG_NONE, - textfield_->GetDragOperationsForView(NULL, kStringPoint)); - textfield_->SetEnabled(true); - // Ensure that textfields without selections do not support drag operations. - textfield_->ClearSelection(); - EXPECT_EQ(ui::DragDropTypes::DRAG_NONE, - textfield_->GetDragOperationsForView(NULL, kStringPoint)); - textfield_->SelectRange(kStringRange); - // Ensure that password textfields do not support drag operations. - textfield_->SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD); - EXPECT_EQ(ui::DragDropTypes::DRAG_NONE, - textfield_->GetDragOperationsForView(NULL, kStringPoint)); - textfield_->SetTextInputType(ui::TEXT_INPUT_TYPE_TEXT); - // Ensure that textfields only initiate drag operations inside the selection. - ui::MouseEvent press_event(ui::ET_MOUSE_PRESSED, kStringPoint, kStringPoint, - ui::EF_LEFT_MOUSE_BUTTON, - ui::EF_LEFT_MOUSE_BUTTON); - textfield_->OnMousePressed(press_event); - EXPECT_EQ(ui::DragDropTypes::DRAG_NONE, - textfield_->GetDragOperationsForView(NULL, gfx::Point())); - EXPECT_FALSE(textfield_->CanStartDragForView(NULL, gfx::Point(), - gfx::Point())); - EXPECT_EQ(ui::DragDropTypes::DRAG_COPY, - textfield_->GetDragOperationsForView(NULL, kStringPoint)); - EXPECT_TRUE(textfield_->CanStartDragForView(NULL, kStringPoint, - gfx::Point())); - // Ensure that textfields support local moves. - EXPECT_EQ(ui::DragDropTypes::DRAG_MOVE | ui::DragDropTypes::DRAG_COPY, - textfield_->GetDragOperationsForView(textfield_, kStringPoint)); -} - -TEST_F(TextfieldTest, DragAndDrop_ToTheRight) { - InitTextfield(); - textfield_->SetText(ASCIIToUTF16("hello world")); - - base::string16 string; - ui::OSExchangeData data; - int formats = 0; - int operations = 0; - std::set<OSExchangeData::CustomFormat> custom_formats; - - // Start dragging "ello". - textfield_->SelectRange(gfx::Range(1, 5)); - gfx::Point point(GetCursorPositionX(3), 0); - ui::MouseEvent click_a(ui::ET_MOUSE_PRESSED, point, point, - ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); - textfield_->OnMousePressed(click_a); - EXPECT_TRUE(textfield_->CanStartDragForView(textfield_, click_a.location(), - gfx::Point())); - operations = textfield_->GetDragOperationsForView(textfield_, - click_a.location()); - EXPECT_EQ(ui::DragDropTypes::DRAG_MOVE | ui::DragDropTypes::DRAG_COPY, - operations); - textfield_->WriteDragDataForView(NULL, click_a.location(), &data); - EXPECT_TRUE(data.GetString(&string)); - EXPECT_EQ(textfield_->GetSelectedText(), string); - EXPECT_TRUE(textfield_->GetDropFormats(&formats, &custom_formats)); - EXPECT_EQ(ui::OSExchangeData::STRING, formats); - EXPECT_TRUE(custom_formats.empty()); - - // Drop "ello" after "w". - const gfx::Point kDropPoint(GetCursorPositionX(7), 0); - EXPECT_TRUE(textfield_->CanDrop(data)); - ui::DropTargetEvent drop_a(data, kDropPoint, kDropPoint, operations); - EXPECT_EQ(ui::DragDropTypes::DRAG_MOVE, textfield_->OnDragUpdated(drop_a)); - EXPECT_EQ(ui::DragDropTypes::DRAG_MOVE, textfield_->OnPerformDrop(drop_a)); - EXPECT_STR_EQ("h welloorld", textfield_->text()); - textfield_->OnDragDone(); - - // Undo/Redo the drag&drop change. - SendKeyEvent(ui::VKEY_Z, false, true); - EXPECT_STR_EQ("hello world", textfield_->text()); - SendKeyEvent(ui::VKEY_Z, false, true); - EXPECT_STR_EQ("", textfield_->text()); - SendKeyEvent(ui::VKEY_Z, false, true); - EXPECT_STR_EQ("", textfield_->text()); - SendKeyEvent(ui::VKEY_Y, false, true); - EXPECT_STR_EQ("hello world", textfield_->text()); - SendKeyEvent(ui::VKEY_Y, false, true); - EXPECT_STR_EQ("h welloorld", textfield_->text()); - SendKeyEvent(ui::VKEY_Y, false, true); - EXPECT_STR_EQ("h welloorld", textfield_->text()); -} - -TEST_F(TextfieldTest, DragAndDrop_ToTheLeft) { - InitTextfield(); - textfield_->SetText(ASCIIToUTF16("hello world")); - - base::string16 string; - ui::OSExchangeData data; - int formats = 0; - int operations = 0; - std::set<OSExchangeData::CustomFormat> custom_formats; - - // Start dragging " worl". - textfield_->SelectRange(gfx::Range(5, 10)); - gfx::Point point(GetCursorPositionX(7), 0); - ui::MouseEvent click_a(ui::ET_MOUSE_PRESSED, point, point, - ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); - textfield_->OnMousePressed(click_a); - EXPECT_TRUE(textfield_->CanStartDragForView(textfield_, click_a.location(), - gfx::Point())); - operations = textfield_->GetDragOperationsForView(textfield_, - click_a.location()); - EXPECT_EQ(ui::DragDropTypes::DRAG_MOVE | ui::DragDropTypes::DRAG_COPY, - operations); - textfield_->WriteDragDataForView(NULL, click_a.location(), &data); - EXPECT_TRUE(data.GetString(&string)); - EXPECT_EQ(textfield_->GetSelectedText(), string); - EXPECT_TRUE(textfield_->GetDropFormats(&formats, &custom_formats)); - EXPECT_EQ(ui::OSExchangeData::STRING, formats); - EXPECT_TRUE(custom_formats.empty()); - - // Drop " worl" after "h". - EXPECT_TRUE(textfield_->CanDrop(data)); - gfx::Point drop_point(GetCursorPositionX(1), 0); - ui::DropTargetEvent drop_a(data, drop_point, drop_point, operations); - EXPECT_EQ(ui::DragDropTypes::DRAG_MOVE, textfield_->OnDragUpdated(drop_a)); - EXPECT_EQ(ui::DragDropTypes::DRAG_MOVE, textfield_->OnPerformDrop(drop_a)); - EXPECT_STR_EQ("h worlellod", textfield_->text()); - textfield_->OnDragDone(); - - // Undo/Redo the drag&drop change. - SendKeyEvent(ui::VKEY_Z, false, true); - EXPECT_STR_EQ("hello world", textfield_->text()); - SendKeyEvent(ui::VKEY_Z, false, true); - EXPECT_STR_EQ("", textfield_->text()); - SendKeyEvent(ui::VKEY_Z, false, true); - EXPECT_STR_EQ("", textfield_->text()); - SendKeyEvent(ui::VKEY_Y, false, true); - EXPECT_STR_EQ("hello world", textfield_->text()); - SendKeyEvent(ui::VKEY_Y, false, true); - EXPECT_STR_EQ("h worlellod", textfield_->text()); - SendKeyEvent(ui::VKEY_Y, false, true); - EXPECT_STR_EQ("h worlellod", textfield_->text()); -} - -TEST_F(TextfieldTest, DragAndDrop_Canceled) { - InitTextfield(); - textfield_->SetText(ASCIIToUTF16("hello world")); - - // Start dragging "worl". - textfield_->SelectRange(gfx::Range(6, 10)); - gfx::Point point(GetCursorPositionX(8), 0); - ui::MouseEvent click(ui::ET_MOUSE_PRESSED, point, point, - ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); - textfield_->OnMousePressed(click); - ui::OSExchangeData data; - textfield_->WriteDragDataForView(NULL, click.location(), &data); - EXPECT_TRUE(textfield_->CanDrop(data)); - // Drag the text over somewhere valid, outside the current selection. - gfx::Point drop_point(GetCursorPositionX(2), 0); - ui::DropTargetEvent drop(data, drop_point, drop_point, - ui::DragDropTypes::DRAG_MOVE); - EXPECT_EQ(ui::DragDropTypes::DRAG_MOVE, textfield_->OnDragUpdated(drop)); - // "Cancel" the drag, via move and release over the selection, and OnDragDone. - gfx::Point drag_point(GetCursorPositionX(9), 0); - ui::MouseEvent drag(ui::ET_MOUSE_DRAGGED, drag_point, drag_point, - ui::EF_LEFT_MOUSE_BUTTON, 0); - ui::MouseEvent release(ui::ET_MOUSE_RELEASED, drag_point, drag_point, - ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); - textfield_->OnMouseDragged(drag); - textfield_->OnMouseReleased(release); - textfield_->OnDragDone(); - EXPECT_EQ(ASCIIToUTF16("hello world"), textfield_->text()); -} - -TEST_F(TextfieldTest, ReadOnlyTest) { - InitTextfield(); - textfield_->SetText(ASCIIToUTF16("read only")); - textfield_->SetReadOnly(true); - EXPECT_TRUE(textfield_->enabled()); - EXPECT_TRUE(textfield_->IsFocusable()); - - SendKeyEvent(ui::VKEY_HOME); - EXPECT_EQ(0U, textfield_->GetCursorPosition()); - SendKeyEvent(ui::VKEY_END); - EXPECT_EQ(9U, textfield_->GetCursorPosition()); - - SendKeyEvent(ui::VKEY_LEFT, false, false); - EXPECT_EQ(8U, textfield_->GetCursorPosition()); - SendKeyEvent(ui::VKEY_LEFT, false, true); - EXPECT_EQ(5U, textfield_->GetCursorPosition()); - SendKeyEvent(ui::VKEY_LEFT, true, true); - EXPECT_EQ(0U, textfield_->GetCursorPosition()); - EXPECT_STR_EQ("read ", textfield_->GetSelectedText()); - textfield_->SelectAll(false); - EXPECT_STR_EQ("read only", textfield_->GetSelectedText()); - - // Cut should be disabled. - SetClipboardText(ui::CLIPBOARD_TYPE_COPY_PASTE, "Test"); - EXPECT_FALSE(textfield_->IsCommandIdEnabled(IDS_APP_CUT)); - textfield_->ExecuteCommand(IDS_APP_CUT, 0); - SendKeyEvent(ui::VKEY_X, false, true); - SendKeyEvent(ui::VKEY_DELETE, true, false); - EXPECT_STR_EQ("Test", GetClipboardText(ui::CLIPBOARD_TYPE_COPY_PASTE)); - EXPECT_STR_EQ("read only", textfield_->text()); - - // Paste should be disabled. - EXPECT_FALSE(textfield_->IsCommandIdEnabled(IDS_APP_PASTE)); - textfield_->ExecuteCommand(IDS_APP_PASTE, 0); - SendKeyEvent(ui::VKEY_V, false, true); - SendKeyEvent(ui::VKEY_INSERT, true, false); - EXPECT_STR_EQ("read only", textfield_->text()); - - // Copy should work normally. - SetClipboardText(ui::CLIPBOARD_TYPE_COPY_PASTE, "Test"); - EXPECT_TRUE(textfield_->IsCommandIdEnabled(IDS_APP_COPY)); - textfield_->ExecuteCommand(IDS_APP_COPY, 0); - EXPECT_STR_EQ("read only", GetClipboardText(ui::CLIPBOARD_TYPE_COPY_PASTE)); - SetClipboardText(ui::CLIPBOARD_TYPE_COPY_PASTE, "Test"); - SendKeyEvent(ui::VKEY_C, false, true); - EXPECT_STR_EQ("read only", GetClipboardText(ui::CLIPBOARD_TYPE_COPY_PASTE)); - SetClipboardText(ui::CLIPBOARD_TYPE_COPY_PASTE, "Test"); - SendKeyEvent(ui::VKEY_INSERT, false, true); - EXPECT_STR_EQ("read only", GetClipboardText(ui::CLIPBOARD_TYPE_COPY_PASTE)); - - // SetText should work even in read only mode. - textfield_->SetText(ASCIIToUTF16(" four five six ")); - EXPECT_STR_EQ(" four five six ", textfield_->text()); - - textfield_->SelectAll(false); - EXPECT_STR_EQ(" four five six ", textfield_->GetSelectedText()); - - // Text field is unmodifiable and selection shouldn't change. - SendKeyEvent(ui::VKEY_DELETE); - EXPECT_STR_EQ(" four five six ", textfield_->GetSelectedText()); - SendKeyEvent(ui::VKEY_BACK); - EXPECT_STR_EQ(" four five six ", textfield_->GetSelectedText()); - SendKeyEvent(ui::VKEY_T); - EXPECT_STR_EQ(" four five six ", textfield_->GetSelectedText()); -} - -TEST_F(TextfieldTest, TextInputClientTest) { - InitTextfield(); - ui::TextInputClient* client = textfield_->GetTextInputClient(); - EXPECT_TRUE(client); - EXPECT_EQ(ui::TEXT_INPUT_TYPE_TEXT, client->GetTextInputType()); - - textfield_->SetText(ASCIIToUTF16("0123456789")); - gfx::Range range; - EXPECT_TRUE(client->GetTextRange(&range)); - EXPECT_EQ(0U, range.start()); - EXPECT_EQ(10U, range.end()); - - EXPECT_TRUE(client->SetSelectionRange(gfx::Range(1, 4))); - EXPECT_TRUE(client->GetSelectionRange(&range)); - EXPECT_EQ(gfx::Range(1, 4), range); - - base::string16 substring; - EXPECT_TRUE(client->GetTextFromRange(range, &substring)); - EXPECT_STR_EQ("123", substring); - - EXPECT_TRUE(client->DeleteRange(range)); - EXPECT_STR_EQ("0456789", textfield_->text()); - - ui::CompositionText composition; - composition.text = UTF8ToUTF16("321"); - // Set composition through input method. - input_method_->Clear(); - input_method_->SetCompositionTextForNextKey(composition); - textfield_->clear(); - - on_before_user_action_ = on_after_user_action_ = 0; - SendKeyEvent(ui::VKEY_A); - EXPECT_TRUE(textfield_->key_received()); - EXPECT_FALSE(textfield_->key_handled()); - EXPECT_TRUE(client->HasCompositionText()); - EXPECT_TRUE(client->GetCompositionTextRange(&range)); - EXPECT_STR_EQ("0321456789", textfield_->text()); - EXPECT_EQ(gfx::Range(1, 4), range); - EXPECT_EQ(1, on_before_user_action_); - EXPECT_EQ(1, on_after_user_action_); - - input_method_->SetResultTextForNextKey(UTF8ToUTF16("123")); - on_before_user_action_ = on_after_user_action_ = 0; - textfield_->clear(); - SendKeyEvent(ui::VKEY_A); - EXPECT_TRUE(textfield_->key_received()); - EXPECT_FALSE(textfield_->key_handled()); - EXPECT_FALSE(client->HasCompositionText()); - EXPECT_FALSE(input_method_->cancel_composition_called()); - EXPECT_STR_EQ("0123456789", textfield_->text()); - EXPECT_EQ(1, on_before_user_action_); - EXPECT_EQ(1, on_after_user_action_); - - input_method_->Clear(); - input_method_->SetCompositionTextForNextKey(composition); - textfield_->clear(); - SendKeyEvent(ui::VKEY_A); - EXPECT_TRUE(client->HasCompositionText()); - EXPECT_STR_EQ("0123321456789", textfield_->text()); - - on_before_user_action_ = on_after_user_action_ = 0; - textfield_->clear(); - SendKeyEvent(ui::VKEY_RIGHT); - EXPECT_FALSE(client->HasCompositionText()); - EXPECT_TRUE(input_method_->cancel_composition_called()); - EXPECT_TRUE(textfield_->key_received()); - EXPECT_TRUE(textfield_->key_handled()); - EXPECT_STR_EQ("0123321456789", textfield_->text()); - EXPECT_EQ(8U, textfield_->GetCursorPosition()); - EXPECT_EQ(1, on_before_user_action_); - EXPECT_EQ(1, on_after_user_action_); - - textfield_->clear(); - textfield_->SetText(ASCIIToUTF16("0123456789")); - EXPECT_TRUE(client->SetSelectionRange(gfx::Range(5, 5))); - client->ExtendSelectionAndDelete(4, 2); - EXPECT_STR_EQ("0789", textfield_->text()); - - // On{Before,After}UserAction should be called by whatever user action - // triggers clearing or setting a selection if appropriate. - on_before_user_action_ = on_after_user_action_ = 0; - textfield_->clear(); - textfield_->ClearSelection(); - textfield_->SelectAll(false); - EXPECT_EQ(0, on_before_user_action_); - EXPECT_EQ(0, on_after_user_action_); - - input_method_->Clear(); - textfield_->SetReadOnly(true); - EXPECT_TRUE(input_method_->text_input_type_changed()); - EXPECT_FALSE(textfield_->GetTextInputClient()); - - textfield_->SetReadOnly(false); - input_method_->Clear(); - textfield_->SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD); - EXPECT_TRUE(input_method_->text_input_type_changed()); - EXPECT_TRUE(textfield_->GetTextInputClient()); -} - -TEST_F(TextfieldTest, UndoRedoTest) { - InitTextfield(); - SendKeyEvent(ui::VKEY_A); - EXPECT_STR_EQ("a", textfield_->text()); - SendKeyEvent(ui::VKEY_Z, false, true); - EXPECT_STR_EQ("", textfield_->text()); - SendKeyEvent(ui::VKEY_Z, false, true); - EXPECT_STR_EQ("", textfield_->text()); - SendKeyEvent(ui::VKEY_Y, false, true); - EXPECT_STR_EQ("a", textfield_->text()); - SendKeyEvent(ui::VKEY_Y, false, true); - EXPECT_STR_EQ("a", textfield_->text()); - - // AppendText - textfield_->AppendText(ASCIIToUTF16("b")); - last_contents_.clear(); // AppendText doesn't call ContentsChanged. - EXPECT_STR_EQ("ab", textfield_->text()); - SendKeyEvent(ui::VKEY_Z, false, true); - EXPECT_STR_EQ("a", textfield_->text()); - SendKeyEvent(ui::VKEY_Y, false, true); - EXPECT_STR_EQ("ab", textfield_->text()); - - // SetText - SendKeyEvent(ui::VKEY_C); - // Undo'ing append moves the cursor to the end for now. - // A no-op SetText won't add a new edit; see TextfieldModel::SetText. - EXPECT_STR_EQ("abc", textfield_->text()); - textfield_->SetText(ASCIIToUTF16("abc")); - EXPECT_STR_EQ("abc", textfield_->text()); - SendKeyEvent(ui::VKEY_Z, false, true); - EXPECT_STR_EQ("ab", textfield_->text()); - SendKeyEvent(ui::VKEY_Y, false, true); - EXPECT_STR_EQ("abc", textfield_->text()); - SendKeyEvent(ui::VKEY_Y, false, true); - EXPECT_STR_EQ("abc", textfield_->text()); - textfield_->SetText(ASCIIToUTF16("123")); - textfield_->SetText(ASCIIToUTF16("123")); - EXPECT_STR_EQ("123", textfield_->text()); - SendKeyEvent(ui::VKEY_END, false, false); - SendKeyEvent(ui::VKEY_4, false, false); - EXPECT_STR_EQ("1234", textfield_->text()); - last_contents_.clear(); - SendKeyEvent(ui::VKEY_Z, false, true); - EXPECT_STR_EQ("123", textfield_->text()); - SendKeyEvent(ui::VKEY_Z, false, true); - // the insert edit "c" and set edit "123" are merged to single edit, - // so text becomes "ab" after undo. - EXPECT_STR_EQ("ab", textfield_->text()); - SendKeyEvent(ui::VKEY_Z, false, true); - EXPECT_STR_EQ("a", textfield_->text()); - SendKeyEvent(ui::VKEY_Y, false, true); - EXPECT_STR_EQ("ab", textfield_->text()); - SendKeyEvent(ui::VKEY_Y, false, true); - EXPECT_STR_EQ("123", textfield_->text()); - SendKeyEvent(ui::VKEY_Y, false, true); - EXPECT_STR_EQ("1234", textfield_->text()); - - // Undoing to the same text shouldn't call ContentsChanged. - SendKeyEvent(ui::VKEY_A, false, true); // select all - SendKeyEvent(ui::VKEY_A); - EXPECT_STR_EQ("a", textfield_->text()); - SendKeyEvent(ui::VKEY_B); - SendKeyEvent(ui::VKEY_C); - EXPECT_STR_EQ("abc", textfield_->text()); - SendKeyEvent(ui::VKEY_Z, false, true); - EXPECT_STR_EQ("1234", textfield_->text()); - SendKeyEvent(ui::VKEY_Y, false, true); - EXPECT_STR_EQ("abc", textfield_->text()); - - // Delete/Backspace - SendKeyEvent(ui::VKEY_BACK); - EXPECT_STR_EQ("ab", textfield_->text()); - SendKeyEvent(ui::VKEY_HOME); - SendKeyEvent(ui::VKEY_DELETE); - EXPECT_STR_EQ("b", textfield_->text()); - SendKeyEvent(ui::VKEY_A, false, true); - SendKeyEvent(ui::VKEY_DELETE); - EXPECT_STR_EQ("", textfield_->text()); - SendKeyEvent(ui::VKEY_Z, false, true); - EXPECT_STR_EQ("b", textfield_->text()); - SendKeyEvent(ui::VKEY_Z, false, true); - EXPECT_STR_EQ("ab", textfield_->text()); - SendKeyEvent(ui::VKEY_Z, false, true); - EXPECT_STR_EQ("abc", textfield_->text()); - SendKeyEvent(ui::VKEY_Y, false, true); - EXPECT_STR_EQ("ab", textfield_->text()); - SendKeyEvent(ui::VKEY_Y, false, true); - EXPECT_STR_EQ("b", textfield_->text()); - SendKeyEvent(ui::VKEY_Y, false, true); - EXPECT_STR_EQ("", textfield_->text()); - SendKeyEvent(ui::VKEY_Y, false, true); - EXPECT_STR_EQ("", textfield_->text()); -} - -TEST_F(TextfieldTest, CutCopyPaste) { - InitTextfield(); - - // Ensure IDS_APP_CUT cuts. - textfield_->SetText(ASCIIToUTF16("123")); - textfield_->SelectAll(false); - EXPECT_TRUE(textfield_->IsCommandIdEnabled(IDS_APP_CUT)); - textfield_->ExecuteCommand(IDS_APP_CUT, 0); - EXPECT_STR_EQ("123", GetClipboardText(ui::CLIPBOARD_TYPE_COPY_PASTE)); - EXPECT_STR_EQ("", textfield_->text()); - EXPECT_EQ(ui::CLIPBOARD_TYPE_COPY_PASTE, GetAndResetCopiedToClipboard()); - - // Ensure [Ctrl]+[x] cuts and [Ctrl]+[Alt][x] does nothing. - textfield_->SetText(ASCIIToUTF16("456")); - textfield_->SelectAll(false); - SendKeyEvent(ui::VKEY_X, true, false, true, false); - EXPECT_STR_EQ("123", GetClipboardText(ui::CLIPBOARD_TYPE_COPY_PASTE)); - EXPECT_STR_EQ("456", textfield_->text()); - EXPECT_EQ(ui::CLIPBOARD_TYPE_LAST, GetAndResetCopiedToClipboard()); - SendKeyEvent(ui::VKEY_X, false, true); - EXPECT_STR_EQ("456", GetClipboardText(ui::CLIPBOARD_TYPE_COPY_PASTE)); - EXPECT_STR_EQ("", textfield_->text()); - EXPECT_EQ(ui::CLIPBOARD_TYPE_COPY_PASTE, GetAndResetCopiedToClipboard()); - - // Ensure [Shift]+[Delete] cuts. - textfield_->SetText(ASCIIToUTF16("123")); - textfield_->SelectAll(false); - SendKeyEvent(ui::VKEY_DELETE, true, false); - EXPECT_STR_EQ("123", GetClipboardText(ui::CLIPBOARD_TYPE_COPY_PASTE)); - EXPECT_STR_EQ("", textfield_->text()); - EXPECT_EQ(ui::CLIPBOARD_TYPE_COPY_PASTE, GetAndResetCopiedToClipboard()); - - // Ensure IDS_APP_COPY copies. - textfield_->SetText(ASCIIToUTF16("789")); - textfield_->SelectAll(false); - EXPECT_TRUE(textfield_->IsCommandIdEnabled(IDS_APP_COPY)); - textfield_->ExecuteCommand(IDS_APP_COPY, 0); - EXPECT_STR_EQ("789", GetClipboardText(ui::CLIPBOARD_TYPE_COPY_PASTE)); - EXPECT_EQ(ui::CLIPBOARD_TYPE_COPY_PASTE, GetAndResetCopiedToClipboard()); - - // Ensure [Ctrl]+[c] copies and [Ctrl]+[Alt][c] does nothing. - textfield_->SetText(ASCIIToUTF16("012")); - textfield_->SelectAll(false); - SendKeyEvent(ui::VKEY_C, true, false, true, false); - EXPECT_STR_EQ("789", GetClipboardText(ui::CLIPBOARD_TYPE_COPY_PASTE)); - EXPECT_EQ(ui::CLIPBOARD_TYPE_LAST, GetAndResetCopiedToClipboard()); - SendKeyEvent(ui::VKEY_C, false, true); - EXPECT_STR_EQ("012", GetClipboardText(ui::CLIPBOARD_TYPE_COPY_PASTE)); - EXPECT_EQ(ui::CLIPBOARD_TYPE_COPY_PASTE, GetAndResetCopiedToClipboard()); - - // Ensure [Ctrl]+[Insert] copies. - textfield_->SetText(ASCIIToUTF16("345")); - textfield_->SelectAll(false); - SendKeyEvent(ui::VKEY_INSERT, false, true); - EXPECT_STR_EQ("345", GetClipboardText(ui::CLIPBOARD_TYPE_COPY_PASTE)); - EXPECT_STR_EQ("345", textfield_->text()); - EXPECT_EQ(ui::CLIPBOARD_TYPE_COPY_PASTE, GetAndResetCopiedToClipboard()); - - // Ensure IDS_APP_PASTE, [Ctrl]+[V], and [Shift]+[Insert] pastes; - // also ensure that [Ctrl]+[Alt]+[V] does nothing. - SetClipboardText(ui::CLIPBOARD_TYPE_COPY_PASTE, "abc"); - textfield_->SetText(base::string16()); - EXPECT_TRUE(textfield_->IsCommandIdEnabled(IDS_APP_PASTE)); - textfield_->ExecuteCommand(IDS_APP_PASTE, 0); - EXPECT_STR_EQ("abc", textfield_->text()); - SendKeyEvent(ui::VKEY_V, false, true); - EXPECT_STR_EQ("abcabc", textfield_->text()); - SendKeyEvent(ui::VKEY_INSERT, true, false); - EXPECT_STR_EQ("abcabcabc", textfield_->text()); - SendKeyEvent(ui::VKEY_V, true, false, true, false); - EXPECT_STR_EQ("abcabcabc", textfield_->text()); - - // Ensure [Ctrl]+[Shift]+[Insert] is a no-op. - textfield_->SelectAll(false); - SendKeyEvent(ui::VKEY_INSERT, true, true); - EXPECT_STR_EQ("abc", GetClipboardText(ui::CLIPBOARD_TYPE_COPY_PASTE)); - EXPECT_STR_EQ("abcabcabc", textfield_->text()); - EXPECT_EQ(ui::CLIPBOARD_TYPE_LAST, GetAndResetCopiedToClipboard()); -} - -TEST_F(TextfieldTest, OvertypeMode) { - InitTextfield(); - // Overtype mode should be disabled (no-op [Insert]). - textfield_->SetText(ASCIIToUTF16("2")); - SendKeyEvent(ui::VKEY_HOME); - SendKeyEvent(ui::VKEY_INSERT); - SendKeyEvent(ui::VKEY_1, false, false); - EXPECT_STR_EQ("12", textfield_->text()); -} - -TEST_F(TextfieldTest, TextCursorDisplayTest) { - InitTextfield(); - // LTR-RTL string in LTR context. - SendKeyEvent('a'); - EXPECT_STR_EQ("a", textfield_->text()); - int x = GetCursorBounds().x(); - int prev_x = x; - - SendKeyEvent('b'); - EXPECT_STR_EQ("ab", textfield_->text()); - x = GetCursorBounds().x(); - EXPECT_LT(prev_x, x); - prev_x = x; - - SendKeyEvent(0x05E1); - EXPECT_EQ(WideToUTF16(L"ab\x05E1"), textfield_->text()); - x = GetCursorBounds().x(); - EXPECT_EQ(prev_x, x); - - SendKeyEvent(0x05E2); - EXPECT_EQ(WideToUTF16(L"ab\x05E1\x5E2"), textfield_->text()); - x = GetCursorBounds().x(); - EXPECT_EQ(prev_x, x); - - // Clear text. - SendKeyEvent(ui::VKEY_A, false, true); - SendKeyEvent('\n'); - - // RTL-LTR string in LTR context. - SendKeyEvent(0x05E1); - EXPECT_EQ(WideToUTF16(L"\x05E1"), textfield_->text()); - x = GetCursorBounds().x(); - EXPECT_EQ(GetDisplayRect().x(), x); - prev_x = x; - - SendKeyEvent(0x05E2); - EXPECT_EQ(WideToUTF16(L"\x05E1\x05E2"), textfield_->text()); - x = GetCursorBounds().x(); - EXPECT_EQ(prev_x, x); - - SendKeyEvent('a'); - EXPECT_EQ(WideToUTF16(L"\x05E1\x5E2" L"a"), textfield_->text()); - x = GetCursorBounds().x(); - EXPECT_LT(prev_x, x); - prev_x = x; - - SendKeyEvent('b'); - EXPECT_EQ(WideToUTF16(L"\x05E1\x5E2" L"ab"), textfield_->text()); - x = GetCursorBounds().x(); - EXPECT_LT(prev_x, x); -} - -TEST_F(TextfieldTest, TextCursorDisplayInRTLTest) { - std::string locale = l10n_util::GetApplicationLocale(""); - base::i18n::SetICUDefaultLocale("he"); - - InitTextfield(); - // LTR-RTL string in RTL context. - SendKeyEvent('a'); - EXPECT_STR_EQ("a", textfield_->text()); - int x = GetCursorBounds().x(); - EXPECT_EQ(GetDisplayRect().right() - 1, x); - int prev_x = x; - - SendKeyEvent('b'); - EXPECT_STR_EQ("ab", textfield_->text()); - x = GetCursorBounds().x(); - EXPECT_EQ(prev_x, x); - - SendKeyEvent(0x05E1); - EXPECT_EQ(WideToUTF16(L"ab\x05E1"), textfield_->text()); - x = GetCursorBounds().x(); - EXPECT_GT(prev_x, x); - prev_x = x; - - SendKeyEvent(0x05E2); - EXPECT_EQ(WideToUTF16(L"ab\x05E1\x5E2"), textfield_->text()); - x = GetCursorBounds().x(); - EXPECT_GT(prev_x, x); - - SendKeyEvent(ui::VKEY_A, false, true); - SendKeyEvent('\n'); - - // RTL-LTR string in RTL context. - SendKeyEvent(0x05E1); - EXPECT_EQ(WideToUTF16(L"\x05E1"), textfield_->text()); - x = GetCursorBounds().x(); - prev_x = x; - - SendKeyEvent(0x05E2); - EXPECT_EQ(WideToUTF16(L"\x05E1\x05E2"), textfield_->text()); - x = GetCursorBounds().x(); - EXPECT_GT(prev_x, x); - prev_x = x; - - SendKeyEvent('a'); - EXPECT_EQ(WideToUTF16(L"\x05E1\x5E2" L"a"), textfield_->text()); - x = GetCursorBounds().x(); - EXPECT_EQ(prev_x, x); - prev_x = x; - - SendKeyEvent('b'); - EXPECT_EQ(WideToUTF16(L"\x05E1\x5E2" L"ab"), textfield_->text()); - x = GetCursorBounds().x(); - EXPECT_EQ(prev_x, x); - - // Reset locale. - base::i18n::SetICUDefaultLocale(locale); -} - -TEST_F(TextfieldTest, HitInsideTextAreaTest) { - InitTextfield(); - textfield_->SetText(WideToUTF16(L"ab\x05E1\x5E2")); - std::vector<gfx::Rect> cursor_bounds; - - // Save each cursor bound. - gfx::SelectionModel sel(0, gfx::CURSOR_FORWARD); - cursor_bounds.push_back(GetCursorBounds(sel)); - - sel = gfx::SelectionModel(1, gfx::CURSOR_BACKWARD); - gfx::Rect bound = GetCursorBounds(sel); - sel = gfx::SelectionModel(1, gfx::CURSOR_FORWARD); - EXPECT_EQ(bound.x(), GetCursorBounds(sel).x()); - cursor_bounds.push_back(bound); - - // Check that a cursor at the end of the Latin portion of the text is at the - // same position as a cursor placed at the end of the RTL Hebrew portion. - sel = gfx::SelectionModel(2, gfx::CURSOR_BACKWARD); - bound = GetCursorBounds(sel); - sel = gfx::SelectionModel(4, gfx::CURSOR_BACKWARD); - EXPECT_EQ(bound.x(), GetCursorBounds(sel).x()); - cursor_bounds.push_back(bound); - - sel = gfx::SelectionModel(3, gfx::CURSOR_BACKWARD); - bound = GetCursorBounds(sel); - sel = gfx::SelectionModel(3, gfx::CURSOR_FORWARD); - EXPECT_EQ(bound.x(), GetCursorBounds(sel).x()); - cursor_bounds.push_back(bound); - - sel = gfx::SelectionModel(2, gfx::CURSOR_FORWARD); - bound = GetCursorBounds(sel); - sel = gfx::SelectionModel(4, gfx::CURSOR_FORWARD); - EXPECT_EQ(bound.x(), GetCursorBounds(sel).x()); - cursor_bounds.push_back(bound); - - // Expected cursor position when clicking left and right of each character. - size_t cursor_pos_expected[] = {0, 1, 1, 2, 4, 3, 3, 2}; - - int index = 0; - for (int i = 0; i < static_cast<int>(cursor_bounds.size() - 1); ++i) { - int half_width = (cursor_bounds[i + 1].x() - cursor_bounds[i].x()) / 2; - MouseClick(cursor_bounds[i], half_width / 2); - EXPECT_EQ(cursor_pos_expected[index++], textfield_->GetCursorPosition()); - - // To avoid trigger double click. Not using sleep() since it takes longer - // for the test to run if using sleep(). - NonClientMouseClick(); - - MouseClick(cursor_bounds[i + 1], - (half_width / 2)); - EXPECT_EQ(cursor_pos_expected[index++], textfield_->GetCursorPosition()); - - NonClientMouseClick(); - } -} - -TEST_F(TextfieldTest, HitOutsideTextAreaTest) { - InitTextfield(); - - // LTR-RTL string in LTR context. - textfield_->SetText(WideToUTF16(L"ab\x05E1\x5E2")); - - SendKeyEvent(ui::VKEY_HOME); - gfx::Rect bound = GetCursorBounds(); - MouseClick(bound, -10); - EXPECT_EQ(bound, GetCursorBounds()); - - SendKeyEvent(ui::VKEY_END); - bound = GetCursorBounds(); - MouseClick(bound, 10); - EXPECT_EQ(bound, GetCursorBounds()); - - NonClientMouseClick(); - - // RTL-LTR string in LTR context. - textfield_->SetText(WideToUTF16(L"\x05E1\x5E2" L"ab")); - - SendKeyEvent(ui::VKEY_HOME); - bound = GetCursorBounds(); - MouseClick(bound, 10); - EXPECT_EQ(bound, GetCursorBounds()); - - SendKeyEvent(ui::VKEY_END); - bound = GetCursorBounds(); - MouseClick(bound, -10); - EXPECT_EQ(bound, GetCursorBounds()); -} - -TEST_F(TextfieldTest, HitOutsideTextAreaInRTLTest) { - std::string locale = l10n_util::GetApplicationLocale(""); - base::i18n::SetICUDefaultLocale("he"); - - InitTextfield(); - - // RTL-LTR string in RTL context. - textfield_->SetText(WideToUTF16(L"\x05E1\x5E2" L"ab")); - SendKeyEvent(ui::VKEY_HOME); - gfx::Rect bound = GetCursorBounds(); - MouseClick(bound, 10); - EXPECT_EQ(bound, GetCursorBounds()); - - SendKeyEvent(ui::VKEY_END); - bound = GetCursorBounds(); - MouseClick(bound, -10); - EXPECT_EQ(bound, GetCursorBounds()); - - NonClientMouseClick(); - - // LTR-RTL string in RTL context. - textfield_->SetText(WideToUTF16(L"ab\x05E1\x5E2")); - SendKeyEvent(ui::VKEY_HOME); - bound = GetCursorBounds(); - MouseClick(bound, -10); - EXPECT_EQ(bound, GetCursorBounds()); - - SendKeyEvent(ui::VKEY_END); - bound = GetCursorBounds(); - MouseClick(bound, 10); - EXPECT_EQ(bound, GetCursorBounds()); - - // Reset locale. - base::i18n::SetICUDefaultLocale(locale); -} - -TEST_F(TextfieldTest, OverflowTest) { - InitTextfield(); - - base::string16 str; - for (int i = 0; i < 500; ++i) - SendKeyEvent('a'); - SendKeyEvent(kHebrewLetterSamekh); - EXPECT_TRUE(GetDisplayRect().Contains(GetCursorBounds())); - - // Test mouse pointing. - MouseClick(GetCursorBounds(), -1); - EXPECT_EQ(500U, textfield_->GetCursorPosition()); - - // Clear text. - SendKeyEvent(ui::VKEY_A, false, true); - SendKeyEvent('\n'); - - for (int i = 0; i < 500; ++i) - SendKeyEvent(kHebrewLetterSamekh); - SendKeyEvent('a'); - EXPECT_TRUE(GetDisplayRect().Contains(GetCursorBounds())); - - MouseClick(GetCursorBounds(), -1); - EXPECT_EQ(501U, textfield_->GetCursorPosition()); -} - -TEST_F(TextfieldTest, OverflowInRTLTest) { - std::string locale = l10n_util::GetApplicationLocale(""); - base::i18n::SetICUDefaultLocale("he"); - - InitTextfield(); - - base::string16 str; - for (int i = 0; i < 500; ++i) - SendKeyEvent('a'); - SendKeyEvent(kHebrewLetterSamekh); - EXPECT_TRUE(GetDisplayRect().Contains(GetCursorBounds())); - - MouseClick(GetCursorBounds(), 1); - EXPECT_EQ(501U, textfield_->GetCursorPosition()); - - // Clear text. - SendKeyEvent(ui::VKEY_A, false, true); - SendKeyEvent('\n'); - - for (int i = 0; i < 500; ++i) - SendKeyEvent(kHebrewLetterSamekh); - SendKeyEvent('a'); - EXPECT_TRUE(GetDisplayRect().Contains(GetCursorBounds())); - - MouseClick(GetCursorBounds(), 1); - EXPECT_EQ(500U, textfield_->GetCursorPosition()); - - // Reset locale. - base::i18n::SetICUDefaultLocale(locale); -} - -TEST_F(TextfieldTest, GetCompositionCharacterBoundsTest) { - InitTextfield(); - ui::CompositionText composition; - composition.text = UTF8ToUTF16("abc123"); - const uint32 char_count = static_cast<uint32>(composition.text.length()); - ui::TextInputClient* client = textfield_->GetTextInputClient(); - - // Compare the composition character bounds with surrounding cursor bounds. - for (uint32 i = 0; i < char_count; ++i) { - composition.selection = gfx::Range(i); - client->SetCompositionText(composition); - gfx::Point cursor_origin = GetCursorBounds().origin(); - views::View::ConvertPointToScreen(textfield_, &cursor_origin); - - composition.selection = gfx::Range(i + 1); - client->SetCompositionText(composition); - gfx::Point next_cursor_bottom_left = GetCursorBounds().bottom_left(); - views::View::ConvertPointToScreen(textfield_, &next_cursor_bottom_left); - - gfx::Rect character; - EXPECT_TRUE(client->GetCompositionCharacterBounds(i, &character)); - EXPECT_EQ(character.origin(), cursor_origin) << " i=" << i; - EXPECT_EQ(character.bottom_right(), next_cursor_bottom_left) << " i=" << i; - } - - // Return false if the index is out of range. - gfx::Rect rect; - EXPECT_FALSE(client->GetCompositionCharacterBounds(char_count, &rect)); - EXPECT_FALSE(client->GetCompositionCharacterBounds(char_count + 1, &rect)); - EXPECT_FALSE(client->GetCompositionCharacterBounds(char_count + 100, &rect)); -} - -TEST_F(TextfieldTest, GetCompositionCharacterBounds_ComplexText) { - InitTextfield(); - - const base::char16 kUtf16Chars[] = { - // U+0020 SPACE - 0x0020, - // U+1F408 (CAT) as surrogate pair - 0xd83d, 0xdc08, - // U+5642 as Ideographic Variation Sequences - 0x5642, 0xDB40, 0xDD00, - // U+260E (BLACK TELEPHONE) as Emoji Variation Sequences - 0x260E, 0xFE0F, - // U+0020 SPACE - 0x0020, - }; - const size_t kUtf16CharsCount = arraysize(kUtf16Chars); - - ui::CompositionText composition; - composition.text.assign(kUtf16Chars, kUtf16Chars + kUtf16CharsCount); - ui::TextInputClient* client = textfield_->GetTextInputClient(); - client->SetCompositionText(composition); - - // Make sure GetCompositionCharacterBounds never fails for index. - gfx::Rect rects[kUtf16CharsCount]; - gfx::Rect prev_cursor = GetCursorBounds(); - for (uint32 i = 0; i < kUtf16CharsCount; ++i) - EXPECT_TRUE(client->GetCompositionCharacterBounds(i, &rects[i])); - - // Here we might expect the following results but it actually depends on how - // Uniscribe or HarfBuzz treats them with given font. - // - rects[1] == rects[2] - // - rects[3] == rects[4] == rects[5] - // - rects[6] == rects[7] -} - -// The word we select by double clicking should remain selected regardless of -// where we drag the mouse afterwards without releasing the left button. -TEST_F(TextfieldTest, KeepInitiallySelectedWord) { - InitTextfield(); - - textfield_->SetText(ASCIIToUTF16("abc def ghi")); - - textfield_->SelectRange(gfx::Range(5, 5)); - const gfx::Rect middle_cursor = GetCursorBounds(); - textfield_->SelectRange(gfx::Range(0, 0)); - const gfx::Point beginning = GetCursorBounds().origin(); - - // Double click, but do not release the left button. - MouseClick(middle_cursor, 0); - const gfx::Point middle(middle_cursor.x(), - middle_cursor.y() + middle_cursor.height() / 2); - ui::MouseEvent press_event(ui::ET_MOUSE_PRESSED, middle, middle, - ui::EF_LEFT_MOUSE_BUTTON, - ui::EF_LEFT_MOUSE_BUTTON); - textfield_->OnMousePressed(press_event); - EXPECT_EQ(gfx::Range(4, 7), textfield_->GetSelectedRange()); - - // Drag the mouse to the beginning of the textfield. - ui::MouseEvent drag_event(ui::ET_MOUSE_DRAGGED, beginning, beginning, - ui::EF_LEFT_MOUSE_BUTTON, 0); - textfield_->OnMouseDragged(drag_event); - EXPECT_EQ(gfx::Range(7, 0), textfield_->GetSelectedRange()); -} - -#if defined(OS_LINUX) && !defined(OS_CHROMEOS) -// flaky: http://crbug.com/396477 -TEST_F(TextfieldTest, DISABLED_SelectionClipboard) { - InitTextfield(); - textfield_->SetText(ASCIIToUTF16("0123")); - gfx::Point point_1(GetCursorPositionX(1), 0); - gfx::Point point_2(GetCursorPositionX(2), 0); - gfx::Point point_3(GetCursorPositionX(3), 0); - gfx::Point point_4(GetCursorPositionX(4), 0); - - // Text selected by the mouse should be placed on the selection clipboard. - ui::MouseEvent press(ui::ET_MOUSE_PRESSED, point_1, point_1, - ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); - textfield_->OnMousePressed(press); - ui::MouseEvent drag(ui::ET_MOUSE_DRAGGED, point_3, point_3, - ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); - textfield_->OnMouseDragged(drag); - ui::MouseEvent release(ui::ET_MOUSE_RELEASED, point_3, point_3, - ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); - textfield_->OnMouseReleased(release); - EXPECT_EQ(gfx::Range(1, 3), textfield_->GetSelectedRange()); - EXPECT_STR_EQ("12", GetClipboardText(ui::CLIPBOARD_TYPE_SELECTION)); - - // Select-all should update the selection clipboard. - SendKeyEvent(ui::VKEY_A, false, true); - EXPECT_EQ(gfx::Range(0, 4), textfield_->GetSelectedRange()); - EXPECT_STR_EQ("0123", GetClipboardText(ui::CLIPBOARD_TYPE_SELECTION)); - EXPECT_EQ(ui::CLIPBOARD_TYPE_SELECTION, GetAndResetCopiedToClipboard()); - - // Shift-click selection modifications should update the clipboard. - NonClientMouseClick(); - ui::MouseEvent press_2(ui::ET_MOUSE_PRESSED, point_2, point_2, - ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); - press_2.set_flags(press_2.flags() | ui::EF_SHIFT_DOWN); -#if defined(USE_X11) - ui::UpdateX11EventForFlags(&press_2); -#endif - textfield_->OnMousePressed(press_2); - ui::MouseEvent release_2(ui::ET_MOUSE_RELEASED, point_2, point_2, - ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); - textfield_->OnMouseReleased(release_2); - EXPECT_EQ(gfx::Range(0, 2), textfield_->GetSelectedRange()); - EXPECT_STR_EQ("01", GetClipboardText(ui::CLIPBOARD_TYPE_SELECTION)); - EXPECT_EQ(ui::CLIPBOARD_TYPE_SELECTION, GetAndResetCopiedToClipboard()); - - // Shift-Left/Right should update the selection clipboard. - SendKeyEvent(ui::VKEY_RIGHT, true, false); - EXPECT_STR_EQ("012", GetClipboardText(ui::CLIPBOARD_TYPE_SELECTION)); - EXPECT_EQ(ui::CLIPBOARD_TYPE_SELECTION, GetAndResetCopiedToClipboard()); - SendKeyEvent(ui::VKEY_LEFT, true, false); - EXPECT_STR_EQ("01", GetClipboardText(ui::CLIPBOARD_TYPE_SELECTION)); - EXPECT_EQ(ui::CLIPBOARD_TYPE_SELECTION, GetAndResetCopiedToClipboard()); - SendKeyEvent(ui::VKEY_RIGHT, true, true); - EXPECT_STR_EQ("0123", GetClipboardText(ui::CLIPBOARD_TYPE_SELECTION)); - EXPECT_EQ(ui::CLIPBOARD_TYPE_SELECTION, GetAndResetCopiedToClipboard()); - - // Moving the cursor without a selection should not change the clipboard. - SendKeyEvent(ui::VKEY_LEFT, false, false); - EXPECT_EQ(gfx::Range(0, 0), textfield_->GetSelectedRange()); - EXPECT_STR_EQ("0123", GetClipboardText(ui::CLIPBOARD_TYPE_SELECTION)); - EXPECT_EQ(ui::CLIPBOARD_TYPE_LAST, GetAndResetCopiedToClipboard()); - - // Middle clicking should paste at the mouse (not cursor) location. - ui::MouseEvent middle(ui::ET_MOUSE_PRESSED, point_4, point_4, - ui::EF_MIDDLE_MOUSE_BUTTON, ui::EF_MIDDLE_MOUSE_BUTTON); - textfield_->OnMousePressed(middle); - EXPECT_STR_EQ("01230123", textfield_->text()); - EXPECT_EQ(gfx::Range(0, 0), textfield_->GetSelectedRange()); - EXPECT_STR_EQ("0123", GetClipboardText(ui::CLIPBOARD_TYPE_SELECTION)); - - // Middle click pasting should adjust trailing cursors. - textfield_->SelectRange(gfx::Range(5, 5)); - textfield_->OnMousePressed(middle); - EXPECT_STR_EQ("012301230123", textfield_->text()); - EXPECT_EQ(gfx::Range(9, 9), textfield_->GetSelectedRange()); - - // Middle click pasting should adjust trailing selections. - textfield_->SelectRange(gfx::Range(7, 9)); - textfield_->OnMousePressed(middle); - EXPECT_STR_EQ("0123012301230123", textfield_->text()); - EXPECT_EQ(gfx::Range(11, 13), textfield_->GetSelectedRange()); - - // Middle clicking in the selection should clear the clipboard and selection. - textfield_->SelectRange(gfx::Range(2, 6)); - textfield_->OnMousePressed(middle); - EXPECT_STR_EQ("0123012301230123", textfield_->text()); - EXPECT_EQ(gfx::Range(6, 6), textfield_->GetSelectedRange()); - EXPECT_TRUE(GetClipboardText(ui::CLIPBOARD_TYPE_SELECTION).empty()); - - // Double and triple clicking should update the clipboard contents. - textfield_->SetText(ASCIIToUTF16("ab cd ef")); - gfx::Point word(GetCursorPositionX(4), 0); - ui::MouseEvent press_word(ui::ET_MOUSE_PRESSED, word, word, - ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); - textfield_->OnMousePressed(press_word); - ui::MouseEvent release_word(ui::ET_MOUSE_RELEASED, word, word, - ui::EF_LEFT_MOUSE_BUTTON, - ui::EF_LEFT_MOUSE_BUTTON); - textfield_->OnMouseReleased(release_word); - ui::MouseEvent double_click(ui::ET_MOUSE_PRESSED, word, word, - ui::EF_LEFT_MOUSE_BUTTON | ui::EF_IS_DOUBLE_CLICK, - ui::EF_LEFT_MOUSE_BUTTON); - textfield_->OnMousePressed(double_click); - textfield_->OnMouseReleased(release_word); - EXPECT_EQ(gfx::Range(3, 5), textfield_->GetSelectedRange()); - EXPECT_STR_EQ("cd", GetClipboardText(ui::CLIPBOARD_TYPE_SELECTION)); - EXPECT_EQ(ui::CLIPBOARD_TYPE_SELECTION, GetAndResetCopiedToClipboard()); - textfield_->OnMousePressed(press_word); - textfield_->OnMouseReleased(release_word); - EXPECT_EQ(gfx::Range(0, 8), textfield_->GetSelectedRange()); - EXPECT_STR_EQ("ab cd ef", GetClipboardText(ui::CLIPBOARD_TYPE_SELECTION)); - EXPECT_EQ(ui::CLIPBOARD_TYPE_SELECTION, GetAndResetCopiedToClipboard()); - - // Selecting a range of text without any user interaction should not change - // the clipboard content. - textfield_->SelectRange(gfx::Range(0, 3)); - EXPECT_STR_EQ("ab ", textfield_->GetSelectedText()); - EXPECT_STR_EQ("ab cd ef", GetClipboardText(ui::CLIPBOARD_TYPE_SELECTION)); - EXPECT_EQ(ui::CLIPBOARD_TYPE_LAST, GetAndResetCopiedToClipboard()); - - SetClipboardText(ui::CLIPBOARD_TYPE_SELECTION, "other"); - textfield_->SelectAll(false); - EXPECT_STR_EQ("other", GetClipboardText(ui::CLIPBOARD_TYPE_SELECTION)); - EXPECT_EQ(ui::CLIPBOARD_TYPE_LAST, GetAndResetCopiedToClipboard()); -} -#endif - -// Touch selection and dragging currently only works for chromeos. -#if defined(OS_CHROMEOS) -TEST_F(TextfieldTest, TouchSelectionAndDraggingTest) { - InitTextfield(); - textfield_->SetText(ASCIIToUTF16("hello world")); - EXPECT_FALSE(test_api_->touch_selection_controller()); - const int x = GetCursorPositionX(2); - CommandLine::ForCurrentProcess()->AppendSwitch(switches::kEnableTouchEditing); - - // Tapping on the textfield should turn on the TouchSelectionController. - ui::GestureEventDetails tap_details(ui::ET_GESTURE_TAP); - tap_details.set_tap_count(1); - GestureEventForTest tap(x, 0, tap_details); - textfield_->OnGestureEvent(&tap); - EXPECT_TRUE(test_api_->touch_selection_controller()); - - // Un-focusing the textfield should reset the TouchSelectionController - textfield_->GetFocusManager()->ClearFocus(); - EXPECT_FALSE(test_api_->touch_selection_controller()); - textfield_->RequestFocus(); - - // With touch editing enabled, long press should not show context menu. - // Instead, select word and invoke TouchSelectionController. - GestureEventForTest long_press_1( - x, 0, ui::GestureEventDetails(ui::ET_GESTURE_LONG_PRESS)); - textfield_->OnGestureEvent(&long_press_1); - EXPECT_STR_EQ("hello", textfield_->GetSelectedText()); - EXPECT_TRUE(test_api_->touch_selection_controller()); - EXPECT_TRUE(long_press_1.handled()); - - // With touch drag drop enabled, long pressing in the selected region should - // start a drag and remove TouchSelectionController. - ASSERT_TRUE(switches::IsTouchDragDropEnabled()); - GestureEventForTest long_press_2( - x, 0, ui::GestureEventDetails(ui::ET_GESTURE_LONG_PRESS)); - textfield_->OnGestureEvent(&long_press_2); - EXPECT_STR_EQ("hello", textfield_->GetSelectedText()); - EXPECT_FALSE(test_api_->touch_selection_controller()); - EXPECT_FALSE(long_press_2.handled()); - - // After disabling touch drag drop, long pressing again in the selection - // region should not do anything. - CommandLine::ForCurrentProcess()->AppendSwitch( - switches::kDisableTouchDragDrop); - ASSERT_FALSE(switches::IsTouchDragDropEnabled()); - GestureEventForTest long_press_3( - x, 0, ui::GestureEventDetails(ui::ET_GESTURE_LONG_PRESS)); - textfield_->OnGestureEvent(&long_press_3); - EXPECT_STR_EQ("hello", textfield_->GetSelectedText()); - EXPECT_FALSE(test_api_->touch_selection_controller()); - EXPECT_FALSE(long_press_3.handled()); -} -#endif - -TEST_F(TextfieldTest, TouchSelectionInUnfocusableTextfield) { - CommandLine::ForCurrentProcess()->AppendSwitch(switches::kEnableTouchEditing); - - InitTextfield(); - textfield_->SetText(ASCIIToUTF16("hello world")); - gfx::Point touch_point(GetCursorPositionX(2), 0); - - // Disable textfield and tap on it. Touch text selection should not get - // activated. - textfield_->SetEnabled(false); - Tap(touch_point); - EXPECT_FALSE(test_api_->touch_selection_controller()); - textfield_->SetEnabled(true); - - // Make textfield unfocusable and tap on it. Touch text selection should not - // get activated. - textfield_->SetFocusable(false); - Tap(touch_point); - EXPECT_FALSE(textfield_->HasFocus()); - EXPECT_FALSE(test_api_->touch_selection_controller()); - textfield_->SetFocusable(true); -} - -// Long_Press gesture in Textfield can initiate a drag and drop now. -TEST_F(TextfieldTest, TestLongPressInitiatesDragDrop) { - InitTextfield(); - textfield_->SetText(ASCIIToUTF16("Hello string world")); - - // Ensure the textfield will provide selected text for drag data. - textfield_->SelectRange(gfx::Range(6, 12)); - const gfx::Point kStringPoint(GetCursorPositionX(9), 0); - - // Enable touch-drag-drop to make long press effective. - CommandLine::ForCurrentProcess()->AppendSwitch( - switches::kEnableTouchDragDrop); - - // Create a long press event in the selected region should start a drag. - GestureEventForTest long_press( - kStringPoint.x(), - kStringPoint.y(), - ui::GestureEventDetails(ui::ET_GESTURE_LONG_PRESS)); - textfield_->OnGestureEvent(&long_press); - EXPECT_TRUE(textfield_->CanStartDragForView(NULL, kStringPoint, - kStringPoint)); -} - -TEST_F(TextfieldTest, GetTextfieldBaseline_FontFallbackTest) { - InitTextfield(); - textfield_->SetText(UTF8ToUTF16("abc")); - const int old_baseline = textfield_->GetBaseline(); - - // Set text which may fall back to a font which has taller baseline than - // the default font. - textfield_->SetText(UTF8ToUTF16("\xE0\xB9\x91")); - const int new_baseline = textfield_->GetBaseline(); - - // Regardless of the text, the baseline must be the same. - EXPECT_EQ(new_baseline, old_baseline); -} - -// Tests that a textfield view can be destroyed from OnKeyEvent() on its -// controller and it does not crash. -TEST_F(TextfieldTest, DestroyingTextfieldFromOnKeyEvent) { - InitTextfield(); - - // The controller assumes ownership of the textfield. - TextfieldDestroyerController controller(textfield_); - EXPECT_TRUE(controller.target()); - - // Send a key to trigger OnKeyEvent(). - SendKeyEvent('X'); - - EXPECT_FALSE(controller.target()); -} - -} // namespace views
diff --git a/ui/views/controls/throbber.cc b/ui/views/controls/throbber.cc deleted file mode 100644 index d1d5c1d..0000000 --- a/ui/views/controls/throbber.cc +++ /dev/null
@@ -1,168 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/throbber.h" - -#include "base/time/time.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/image/image.h" -#include "ui/gfx/image/image_skia.h" -#include "ui/resources/grit/ui_resources.h" - -using base::Time; -using base::TimeDelta; - -namespace views { - -Throbber::Throbber(int frame_time_ms, - bool paint_while_stopped) - : running_(false), - paint_while_stopped_(paint_while_stopped), - frames_(NULL), - frame_time_(TimeDelta::FromMilliseconds(frame_time_ms)) { - SetFrames(ui::ResourceBundle::GetSharedInstance().GetImageNamed( - IDR_THROBBER).ToImageSkia()); -} - -Throbber::~Throbber() { - Stop(); -} - -void Throbber::Start() { - if (running_) - return; - - start_time_ = Time::Now(); - - timer_.Start(FROM_HERE, frame_time_ - TimeDelta::FromMilliseconds(10), - this, &Throbber::Run); - - running_ = true; - - SchedulePaint(); // paint right away -} - -void Throbber::Stop() { - if (!running_) - return; - - timer_.Stop(); - - running_ = false; - SchedulePaint(); // Important if we're not painting while stopped -} - -void Throbber::SetFrames(const gfx::ImageSkia* frames) { - frames_ = frames; - DCHECK(frames_->width() > 0 && frames_->height() > 0); - DCHECK(frames_->width() % frames_->height() == 0); - frame_count_ = frames_->width() / frames_->height(); - PreferredSizeChanged(); -} - -void Throbber::Run() { - DCHECK(running_); - - SchedulePaint(); -} - -gfx::Size Throbber::GetPreferredSize() const { - return gfx::Size(frames_->height(), frames_->height()); -} - -void Throbber::OnPaint(gfx::Canvas* canvas) { - if (!running_ && !paint_while_stopped_) - return; - - const TimeDelta elapsed_time = Time::Now() - start_time_; - const int current_frame = - static_cast<int>(elapsed_time / frame_time_) % frame_count_; - - int image_size = frames_->height(); - int image_offset = current_frame * image_size; - canvas->DrawImageInt(*frames_, - image_offset, 0, image_size, image_size, - 0, 0, image_size, image_size, - false); -} - - - -// Smoothed throbber --------------------------------------------------------- - - -// Delay after work starts before starting throbber, in milliseconds. -static const int kStartDelay = 200; - -// Delay after work stops before stopping, in milliseconds. -static const int kStopDelay = 50; - - -SmoothedThrobber::SmoothedThrobber(int frame_time_ms) - : Throbber(frame_time_ms, /* paint_while_stopped= */ false), - start_delay_ms_(kStartDelay), - stop_delay_ms_(kStopDelay) { -} - -SmoothedThrobber::~SmoothedThrobber() {} - -void SmoothedThrobber::Start() { - stop_timer_.Stop(); - - if (!running_ && !start_timer_.IsRunning()) { - start_timer_.Start(FROM_HERE, TimeDelta::FromMilliseconds(start_delay_ms_), - this, &SmoothedThrobber::StartDelayOver); - } -} - -void SmoothedThrobber::StartDelayOver() { - Throbber::Start(); -} - -void SmoothedThrobber::Stop() { - if (!running_) - start_timer_.Stop(); - - stop_timer_.Stop(); - stop_timer_.Start(FROM_HERE, TimeDelta::FromMilliseconds(stop_delay_ms_), - this, &SmoothedThrobber::StopDelayOver); -} - -void SmoothedThrobber::StopDelayOver() { - Throbber::Stop(); -} - -// Checkmark throbber --------------------------------------------------------- - -CheckmarkThrobber::CheckmarkThrobber() - : Throbber(kFrameTimeMs, false), - checked_(false), - checkmark_(ui::ResourceBundle::GetSharedInstance().GetImageNamed( - IDR_CHECKMARK).ToImageSkia()) { -} - -void CheckmarkThrobber::SetChecked(bool checked) { - bool changed = checked != checked_; - if (changed) { - checked_ = checked; - SchedulePaint(); - } -} - -void CheckmarkThrobber::OnPaint(gfx::Canvas* canvas) { - if (running_) { - // Let the throbber throb... - Throbber::OnPaint(canvas); - return; - } - // Otherwise we paint our tick mark or nothing depending on our state. - if (checked_) { - int checkmark_x = (width() - checkmark_->width()) / 2; - int checkmark_y = (height() - checkmark_->height()) / 2; - canvas->DrawImageInt(*checkmark_, checkmark_x, checkmark_y); - } -} - -} // namespace views
diff --git a/ui/views/controls/throbber.h b/ui/views/controls/throbber.h deleted file mode 100644 index 493cffe..0000000 --- a/ui/views/controls/throbber.h +++ /dev/null
@@ -1,127 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_THROBBER_H_ -#define UI_VIEWS_CONTROLS_THROBBER_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/time/time.h" -#include "base/timer/timer.h" -#include "ui/views/view.h" - -namespace gfx { -class ImageSkia; -} - -namespace views { - -// Throbbers display an animation, usually used as a status indicator. - -class VIEWS_EXPORT Throbber : public View { - public: - // |frame_time_ms| is the amount of time that should elapse between frames - // (in milliseconds) - // If |paint_while_stopped| is false, this view will be invisible when not - // running. - Throbber(int frame_time_ms, bool paint_while_stopped); - Throbber(int frame_time_ms, bool paint_while_stopped, gfx::ImageSkia* frames); - virtual ~Throbber(); - - // Start and stop the throbber animation - virtual void Start(); - virtual void Stop(); - - // Set custom throbber frames. Otherwise IDR_THROBBER is loaded. - void SetFrames(const gfx::ImageSkia* frames); - - // Overridden from View: - virtual gfx::Size GetPreferredSize() const override; - virtual void OnPaint(gfx::Canvas* canvas) override; - - protected: - // Specifies whether the throbber is currently animating or not - bool running_; - - private: - void Run(); - - bool paint_while_stopped_; - int frame_count_; // How many frames we have. - base::Time start_time_; // Time when Start was called. - const gfx::ImageSkia* frames_; // Frames images. - base::TimeDelta frame_time_; // How long one frame is displayed. - base::RepeatingTimer<Throbber> timer_; // Used to schedule Run calls. - - DISALLOW_COPY_AND_ASSIGN(Throbber); -}; - -// A SmoothedThrobber is a throbber that is representing potentially short -// and nonoverlapping bursts of work. SmoothedThrobber ignores small -// pauses in the work stops and starts, and only starts its throbber after -// a small amount of work time has passed. -class VIEWS_EXPORT SmoothedThrobber : public Throbber { - public: - explicit SmoothedThrobber(int frame_delay_ms); - SmoothedThrobber(int frame_delay_ms, gfx::ImageSkia* frames); - virtual ~SmoothedThrobber(); - - virtual void Start() override; - virtual void Stop() override; - - void set_start_delay_ms(int value) { start_delay_ms_ = value; } - void set_stop_delay_ms(int value) { stop_delay_ms_ = value; } - - private: - // Called when the startup-delay timer fires - // This function starts the actual throbbing. - void StartDelayOver(); - - // Called when the shutdown-delay timer fires. - // This function stops the actual throbbing. - void StopDelayOver(); - - // Delay after work starts before starting throbber, in milliseconds. - int start_delay_ms_; - - // Delay after work stops before stopping, in milliseconds. - int stop_delay_ms_; - - base::OneShotTimer<SmoothedThrobber> start_timer_; - base::OneShotTimer<SmoothedThrobber> stop_timer_; - - DISALLOW_COPY_AND_ASSIGN(SmoothedThrobber); -}; - -// A CheckmarkThrobber is a special variant of throbber that has three states: -// 1. not yet completed (which paints nothing) -// 2. working (which paints the throbber animation) -// 3. completed (which paints a checkmark) -// -class VIEWS_EXPORT CheckmarkThrobber : public Throbber { - public: - CheckmarkThrobber(); - - // If checked is true, the throbber stops spinning and displays a checkmark. - // If checked is false, the throbber stops spinning and displays nothing. - void SetChecked(bool checked); - - // Overridden from Throbber: - virtual void OnPaint(gfx::Canvas* canvas) override; - - private: - static const int kFrameTimeMs = 30; - - // Whether or not we should display a checkmark. - bool checked_; - - // The checkmark image. - const gfx::ImageSkia* checkmark_; - - DISALLOW_COPY_AND_ASSIGN(CheckmarkThrobber); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_THROBBER_H_
diff --git a/ui/views/controls/tree/tree_view.cc b/ui/views/controls/tree/tree_view.cc deleted file mode 100644 index 4650620..0000000 --- a/ui/views/controls/tree/tree_view.cc +++ /dev/null
@@ -1,1044 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/tree/tree_view.h" - -#include <algorithm> - -#include "base/i18n/rtl.h" -#include "base/message_loop/message_loop.h" -#include "ui/accessibility/ax_view_state.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/events/event.h" -#include "ui/events/keycodes/keyboard_codes.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/geometry/rect.h" -#include "ui/gfx/image/image.h" -#include "ui/gfx/rect_conversions.h" -#include "ui/gfx/skia_util.h" -#include "ui/native_theme/native_theme.h" -#include "ui/resources/grit/ui_resources.h" -#include "ui/views/controls/prefix_selector.h" -#include "ui/views/controls/scroll_view.h" -#include "ui/views/controls/textfield/textfield.h" -#include "ui/views/controls/tree/tree_view_controller.h" -#include "ui/views/ime/input_method.h" - -using ui::TreeModel; -using ui::TreeModelNode; - -namespace views { - -// Insets around the view. -static const int kHorizontalInset = 2; -static const int kVerticalInset = 2; -// Padding before/after the image. -static const int kImagePadding = 4; -// Size of the arrow region. -static const int kArrowRegionSize = 12; -// Padding around the text (on each side). -static const int kTextVerticalPadding = 3; -static const int kTextHorizontalPadding = 2; -// How much children are indented from their parent. -static const int kIndent = 20; - -// static -const char TreeView::kViewClassName[] = "TreeView"; - -namespace { - -// Returns the color id for the background of selected text. |has_focus| -// indicates if the tree has focus. -ui::NativeTheme::ColorId text_background_color_id(bool has_focus) { - return has_focus ? - ui::NativeTheme::kColorId_TreeSelectionBackgroundFocused : - ui::NativeTheme::kColorId_TreeSelectionBackgroundUnfocused; -} - -// Returns the color id for text. |has_focus| indicates if the tree has focus -// and |is_selected| is true if the item is selected. -ui::NativeTheme::ColorId text_color_id(bool has_focus, bool is_selected) { - if (is_selected) { - if (has_focus) - return ui::NativeTheme::kColorId_TreeSelectedText; - return ui::NativeTheme::kColorId_TreeSelectedTextUnfocused; - } - return ui::NativeTheme::kColorId_TreeText; -} - -} // namespace - -TreeView::TreeView() - : model_(NULL), - selected_node_(NULL), - editing_(false), - editor_(NULL), - focus_manager_(NULL), - auto_expand_children_(false), - editable_(true), - controller_(NULL), - root_shown_(true), - row_height_(font_list_.GetHeight() + kTextVerticalPadding * 2) { - SetFocusable(true); - closed_icon_ = *ui::ResourceBundle::GetSharedInstance().GetImageNamed( - (base::i18n::IsRTL() ? IDR_FOLDER_CLOSED_RTL - : IDR_FOLDER_CLOSED)).ToImageSkia(); - open_icon_ = *ui::ResourceBundle::GetSharedInstance().GetImageNamed( - (base::i18n::IsRTL() ? IDR_FOLDER_OPEN_RTL - : IDR_FOLDER_OPEN)).ToImageSkia(); - text_offset_ = closed_icon_.width() + kImagePadding + kImagePadding + - kArrowRegionSize; -} - -TreeView::~TreeView() { - if (model_) - model_->RemoveObserver(this); - if (focus_manager_) { - focus_manager_->RemoveFocusChangeListener(this); - focus_manager_ = NULL; - } -} - -View* TreeView::CreateParentIfNecessary() { - ScrollView* scroll_view = ScrollView::CreateScrollViewWithBorder(); - scroll_view->SetContents(this); - return scroll_view; -} - -void TreeView::SetModel(TreeModel* model) { - if (model == model_) - return; - if (model_) - model_->RemoveObserver(this); - - CancelEdit(); - - model_ = model; - selected_node_ = NULL; - icons_.clear(); - if (model_) { - model_->AddObserver(this); - model_->GetIcons(&icons_); - - root_.RemoveAll(); - ConfigureInternalNode(model_->GetRoot(), &root_); - LoadChildren(&root_); - root_.set_is_expanded(true); - if (root_shown_) - selected_node_ = &root_; - else if (root_.child_count()) - selected_node_ = root_.GetChild(0); - } - DrawnNodesChanged(); -} - -void TreeView::SetEditable(bool editable) { - if (editable == editable_) - return; - editable_ = editable; - CancelEdit(); -} - -void TreeView::StartEditing(TreeModelNode* node) { - DCHECK(node); - // Cancel the current edit. - CancelEdit(); - // Make sure all ancestors are expanded. - if (model_->GetParent(node)) - Expand(model_->GetParent(node)); - // Select the node, else if the user commits the edit the selection reverts. - SetSelectedNode(node); - if (GetSelectedNode() != node) - return; // Selection failed for some reason, don't start editing. - DCHECK(!editing_); - editing_ = true; - if (!editor_) { - editor_ = new Textfield; - // Add the editor immediately as GetPreferredSize returns the wrong thing if - // not parented. - AddChildView(editor_); - editor_->SetFontList(font_list_); - empty_editor_size_ = editor_->GetPreferredSize(); - editor_->set_controller(this); - } - editor_->SetText(selected_node_->model_node()->GetTitle()); - LayoutEditor(); - editor_->SetVisible(true); - SchedulePaintForNode(selected_node_); - editor_->RequestFocus(); - editor_->SelectAll(false); - - // Listen for focus changes so that we can cancel editing. - focus_manager_ = GetFocusManager(); - if (focus_manager_) - focus_manager_->AddFocusChangeListener(this); - - // Accelerators to commit/cancel edit. - AddAccelerator(ui::Accelerator(ui::VKEY_RETURN, ui::EF_NONE)); - AddAccelerator(ui::Accelerator(ui::VKEY_ESCAPE, ui::EF_NONE)); -} - -void TreeView::CancelEdit() { - if (!editing_) - return; - - // WARNING: don't touch |selected_node_|, it may be bogus. - - editing_ = false; - if (focus_manager_) { - focus_manager_->RemoveFocusChangeListener(this); - focus_manager_ = NULL; - } - editor_->SetVisible(false); - SchedulePaint(); - - RemoveAccelerator(ui::Accelerator(ui::VKEY_RETURN, ui::EF_NONE)); - RemoveAccelerator(ui::Accelerator(ui::VKEY_ESCAPE, ui::EF_NONE)); -} - -void TreeView::CommitEdit() { - if (!editing_) - return; - - DCHECK(selected_node_); - const bool editor_has_focus = editor_->HasFocus(); - model_->SetTitle(GetSelectedNode(), editor_->text()); - CancelEdit(); - if (editor_has_focus) - RequestFocus(); -} - -TreeModelNode* TreeView::GetEditingNode() { - return editing_ ? selected_node_->model_node() : NULL; -} - -void TreeView::SetSelectedNode(TreeModelNode* model_node) { - if (editing_ || model_node != selected_node_) - CancelEdit(); - if (model_node && model_->GetParent(model_node)) - Expand(model_->GetParent(model_node)); - if (model_node && model_node == root_.model_node() && !root_shown_) - return; // Ignore requests to select the root when not shown. - InternalNode* node = model_node ? GetInternalNodeForModelNode( - model_node, CREATE_IF_NOT_LOADED) : NULL; - bool was_empty_selection = (selected_node_ == NULL); - bool changed = (selected_node_ != node); - if (changed) { - SchedulePaintForNode(selected_node_); - selected_node_ = node; - if (selected_node_ == &root_ && !root_shown_) - selected_node_ = NULL; - if (selected_node_ && selected_node_ != &root_) - Expand(model_->GetParent(selected_node_->model_node())); - SchedulePaintForNode(selected_node_); - } - - if (selected_node_) - ScrollRectToVisible(GetBoundsForNode(selected_node_)); - - // Notify controller if the old selection was empty to handle the case of - // remove explicitly resetting selected_node_ before invoking this. - if (controller_ && (changed || was_empty_selection)) - controller_->OnTreeViewSelectionChanged(this); - - if (changed) { - // TODO(dmazzoni): Decide if EVENT_SELECTION_CHANGED is a better choice for - // sub-item selection event. - NotifyAccessibilityEvent(ui::AX_EVENT_FOCUS, true); - } -} - -TreeModelNode* TreeView::GetSelectedNode() { - return selected_node_ ? selected_node_->model_node() : NULL; -} - -void TreeView::Collapse(ui::TreeModelNode* model_node) { - // Don't collapse the root if the root isn't shown, otherwise nothing is - // displayed. - if (model_node == root_.model_node() && !root_shown_) - return; - InternalNode* node = - GetInternalNodeForModelNode(model_node, DONT_CREATE_IF_NOT_LOADED); - if (!node) - return; - bool was_expanded = IsExpanded(model_node); - if (node->is_expanded()) { - if (selected_node_ && selected_node_->HasAncestor(node)) - SetSelectedNode(model_node); - node->set_is_expanded(false); - } - if (was_expanded) - DrawnNodesChanged(); -} - -void TreeView::Expand(TreeModelNode* node) { - if (ExpandImpl(node)) - DrawnNodesChanged(); - // TODO: need to support auto_expand_children_. -} - -void TreeView::ExpandAll(TreeModelNode* node) { - DCHECK(node); - // Expand the node. - bool expanded_at_least_one = ExpandImpl(node); - // And recursively expand all the children. - for (int i = model_->GetChildCount(node) - 1; i >= 0; --i) { - TreeModelNode* child = model_->GetChild(node, i); - if (ExpandImpl(child)) - expanded_at_least_one = true; - } - if (expanded_at_least_one) - DrawnNodesChanged(); -} - -bool TreeView::IsExpanded(TreeModelNode* model_node) { - if (!model_node) { - // NULL check primarily for convenience for uses in this class so don't have - // to add NULL checks every where we look up the parent. - return true; - } - InternalNode* node = GetInternalNodeForModelNode( - model_node, DONT_CREATE_IF_NOT_LOADED); - if (!node) - return false; - - while (node) { - if (!node->is_expanded()) - return false; - node = node->parent(); - } - return true; -} - -void TreeView::SetRootShown(bool root_shown) { - if (root_shown_ == root_shown) - return; - root_shown_ = root_shown; - if (!root_shown_ && selected_node_ == &root_) { - if (model_->GetChildCount(root_.model_node())) - SetSelectedNode(model_->GetChild(root_.model_node(), 0)); - else - SetSelectedNode(NULL); - } - DrawnNodesChanged(); -} - -ui::TreeModelNode* TreeView::GetNodeForRow(int row) { - int depth = 0; - InternalNode* node = GetNodeByRow(row, &depth); - return node ? node->model_node() : NULL; -} - -int TreeView::GetRowForNode(ui::TreeModelNode* node) { - InternalNode* internal_node = - GetInternalNodeForModelNode(node, DONT_CREATE_IF_NOT_LOADED); - if (!internal_node) - return -1; - int depth = 0; - return GetRowForInternalNode(internal_node, &depth); -} - -void TreeView::Layout() { - int width = preferred_size_.width(); - int height = preferred_size_.height(); - if (parent()) { - width = std::max(parent()->width(), width); - height = std::max(parent()->height(), height); - } - SetBounds(x(), y(), width, height); - LayoutEditor(); -} - -gfx::Size TreeView::GetPreferredSize() const { - return preferred_size_; -} - -bool TreeView::AcceleratorPressed(const ui::Accelerator& accelerator) { - if (accelerator.key_code() == ui::VKEY_RETURN) { - CommitEdit(); - } else { - DCHECK_EQ(ui::VKEY_ESCAPE, accelerator.key_code()); - CancelEdit(); - RequestFocus(); - } - return true; -} - -bool TreeView::OnMousePressed(const ui::MouseEvent& event) { - return OnClickOrTap(event); -} - -ui::TextInputClient* TreeView::GetTextInputClient() { - if (!selector_) - selector_.reset(new PrefixSelector(this)); - return selector_.get(); -} - -void TreeView::OnGestureEvent(ui::GestureEvent* event) { - if (event->type() == ui::ET_GESTURE_TAP) { - if (OnClickOrTap(*event)) - event->SetHandled(); - } -} - -void TreeView::ShowContextMenu(const gfx::Point& p, - ui::MenuSourceType source_type) { - if (!model_) - return; - if (source_type == ui::MENU_SOURCE_MOUSE) { - // Only invoke View's implementation (which notifies the - // ContextMenuController) if over a node. - gfx::Point local_point(p); - ConvertPointFromScreen(this, &local_point); - int row = (local_point.y() - kVerticalInset) / row_height_; - int depth = 0; - InternalNode* node = GetNodeByRow(row, &depth); - if (!node) - return; - gfx::Rect bounds(GetBoundsForNodeImpl(node, row, depth)); - if (!bounds.Contains(local_point)) - return; - } - View::ShowContextMenu(p, source_type); -} - -void TreeView::GetAccessibleState(ui::AXViewState* state) { - state->role = ui::AX_ROLE_TREE; - state->AddStateFlag(ui::AX_STATE_READ_ONLY); - if (!selected_node_) - return; - - // Get selected item info. - state->role = ui::AX_ROLE_TREE_ITEM; - state->name = selected_node_->model_node()->GetTitle(); -} - -const char* TreeView::GetClassName() const { - return kViewClassName; -} - -void TreeView::TreeNodesAdded(TreeModel* model, - TreeModelNode* parent, - int start, - int count) { - InternalNode* parent_node = - GetInternalNodeForModelNode(parent, DONT_CREATE_IF_NOT_LOADED); - if (!parent_node || !parent_node->loaded_children()) - return; - for (int i = 0; i < count; ++i) { - InternalNode* child = new InternalNode; - ConfigureInternalNode(model_->GetChild(parent, start + i), child); - parent_node->Add(child, start + i); - } - if (IsExpanded(parent)) - DrawnNodesChanged(); -} - -void TreeView::TreeNodesRemoved(TreeModel* model, - TreeModelNode* parent, - int start, - int count) { - InternalNode* parent_node = - GetInternalNodeForModelNode(parent, DONT_CREATE_IF_NOT_LOADED); - if (!parent_node || !parent_node->loaded_children()) - return; - bool reset_selection = false; - for (int i = 0; i < count; ++i) { - InternalNode* child_removing = parent_node->GetChild(start); - if (selected_node_ && selected_node_->HasAncestor(child_removing)) - reset_selection = true; - delete parent_node->Remove(child_removing); - } - if (reset_selection) { - // selected_node_ is no longer valid (at the time we enter this function - // its model_node() is likely deleted). Explicitly NULL out the field - // rather than invoking SetSelectedNode() otherwise, we'll try and use a - // deleted value. - selected_node_ = NULL; - TreeModelNode* to_select = parent; - if (parent == root_.model_node() && !root_shown_) { - to_select = model_->GetChildCount(parent) > 0 ? - model_->GetChild(parent, 0) : NULL; - } - SetSelectedNode(to_select); - } - if (IsExpanded(parent)) - DrawnNodesChanged(); -} - -void TreeView::TreeNodeChanged(TreeModel* model, TreeModelNode* model_node) { - InternalNode* node = - GetInternalNodeForModelNode(model_node, DONT_CREATE_IF_NOT_LOADED); - if (!node) - return; - int old_width = node->text_width(); - UpdateNodeTextWidth(node); - if (old_width != node->text_width() && - ((node == &root_ && root_shown_) || - (node != &root_ && IsExpanded(node->parent()->model_node())))) { - DrawnNodesChanged(); - } -} - -void TreeView::ContentsChanged(Textfield* sender, - const base::string16& new_contents) { -} - -bool TreeView::HandleKeyEvent(Textfield* sender, - const ui::KeyEvent& key_event) { - switch (key_event.key_code()) { - case ui::VKEY_RETURN: - CommitEdit(); - return true; - - case ui::VKEY_ESCAPE: - CancelEdit(); - RequestFocus(); - return true; - - default: - return false; - } -} - -void TreeView::OnWillChangeFocus(View* focused_before, View* focused_now) { -} - -void TreeView::OnDidChangeFocus(View* focused_before, View* focused_now) { - CommitEdit(); -} - -int TreeView::GetRowCount() { - int row_count = root_.NumExpandedNodes(); - if (!root_shown_) - row_count--; - return row_count; -} - -int TreeView::GetSelectedRow() { - ui::TreeModelNode* model_node = GetSelectedNode(); - return model_node ? GetRowForNode(model_node) : -1; -} - -void TreeView::SetSelectedRow(int row) { - SetSelectedNode(GetNodeForRow(row)); -} - -base::string16 TreeView::GetTextForRow(int row) { - return GetNodeForRow(row)->GetTitle(); -} - -gfx::Point TreeView::GetKeyboardContextMenuLocation() { - int y = height() / 2; - if (selected_node_) { - gfx::Rect node_bounds(GetBoundsForNode(selected_node_)); - gfx::Rect vis_bounds(GetVisibleBounds()); - if (node_bounds.y() >= vis_bounds.y() && - node_bounds.y() < vis_bounds.bottom()) { - y = node_bounds.y(); - } - } - gfx::Point screen_loc(0, y); - if (base::i18n::IsRTL()) - screen_loc.set_x(width()); - ConvertPointToScreen(this, &screen_loc); - return screen_loc; -} - -bool TreeView::OnKeyPressed(const ui::KeyEvent& event) { - if (!HasFocus()) - return false; - - switch (event.key_code()) { - case ui::VKEY_F2: - if (!editing_) { - TreeModelNode* selected_node = GetSelectedNode(); - if (selected_node && (!controller_ || - controller_->CanEdit(this, selected_node))) { - StartEditing(selected_node); - } - } - return true; - - case ui::VKEY_UP: - case ui::VKEY_DOWN: - IncrementSelection(event.key_code() == ui::VKEY_UP ? - INCREMENT_PREVIOUS : INCREMENT_NEXT); - return true; - - case ui::VKEY_LEFT: - if (base::i18n::IsRTL()) - ExpandOrSelectChild(); - else - CollapseOrSelectParent(); - return true; - - case ui::VKEY_RIGHT: - if (base::i18n::IsRTL()) - CollapseOrSelectParent(); - else - ExpandOrSelectChild(); - return true; - - default: - break; - } - return false; -} - -void TreeView::OnPaint(gfx::Canvas* canvas) { - // Don't invoke View::OnPaint so that we can render our own focus border. - canvas->DrawColor(GetNativeTheme()->GetSystemColor( - ui::NativeTheme::kColorId_TreeBackground)); - - int min_y, max_y; - { - SkRect sk_clip_rect; - if (canvas->sk_canvas()->getClipBounds(&sk_clip_rect)) { - // Pixels partially inside the clip rect should be included. - gfx::Rect clip_rect = gfx::ToEnclosingRect( - gfx::SkRectToRectF(sk_clip_rect)); - min_y = clip_rect.y(); - max_y = clip_rect.bottom(); - } else { - gfx::Rect vis_bounds = GetVisibleBounds(); - min_y = vis_bounds.y(); - max_y = vis_bounds.bottom(); - } - } - - int min_row = std::max(0, (min_y - kVerticalInset) / row_height_); - int max_row = (max_y - kVerticalInset) / row_height_; - if ((max_y - kVerticalInset) % row_height_ != 0) - max_row++; - int current_row = root_row(); - PaintRows(canvas, min_row, max_row, &root_, root_depth(), ¤t_row); -} - -void TreeView::OnFocus() { - GetInputMethod()->OnFocus(); - View::OnFocus(); - SchedulePaintForNode(selected_node_); - - // Notify the InputMethod so that it knows to query the TextInputClient. - if (GetInputMethod()) - GetInputMethod()->OnCaretBoundsChanged(this); -} - -void TreeView::OnBlur() { - GetInputMethod()->OnBlur(); - SchedulePaintForNode(selected_node_); - if (selector_) - selector_->OnViewBlur(); -} - -bool TreeView::OnClickOrTap(const ui::LocatedEvent& event) { - CommitEdit(); - RequestFocus(); - - int row = (event.y() - kVerticalInset) / row_height_; - int depth = 0; - InternalNode* node = GetNodeByRow(row, &depth); - if (node) { - gfx::Rect bounds(GetBoundsForNodeImpl(node, row, depth)); - if (bounds.Contains(event.location())) { - int relative_x = event.x() - bounds.x(); - if (base::i18n::IsRTL()) - relative_x = bounds.width() - relative_x; - if (relative_x < kArrowRegionSize && - model_->GetChildCount(node->model_node())) { - if (node->is_expanded()) - Collapse(node->model_node()); - else - Expand(node->model_node()); - } else if (relative_x > kArrowRegionSize) { - SetSelectedNode(node->model_node()); - bool should_toggle = false; - if (event.type() == ui::ET_GESTURE_TAP) { - const ui::GestureEvent& gesture = - static_cast<const ui::GestureEvent&>(event); - should_toggle = gesture.details().tap_count() == 2; - } else { - should_toggle = (event.flags() & ui::EF_IS_DOUBLE_CLICK) != 0; - } - if (should_toggle) { - if (node->is_expanded()) - Collapse(node->model_node()); - else - Expand(node->model_node()); - } - } - } - } - return true; -} - -void TreeView::LoadChildren(InternalNode* node) { - DCHECK_EQ(0, node->child_count()); - DCHECK(!node->loaded_children()); - node->set_loaded_children(true); - for (int i = 0, child_count = model_->GetChildCount(node->model_node()); - i < child_count; ++i) { - InternalNode* child = new InternalNode; - ConfigureInternalNode(model_->GetChild(node->model_node(), i), child); - node->Add(child, node->child_count()); - } -} - -void TreeView::ConfigureInternalNode(TreeModelNode* model_node, - InternalNode* node) { - node->Reset(model_node); - UpdateNodeTextWidth(node); -} - -void TreeView::UpdateNodeTextWidth(InternalNode* node) { - int width = 0, height = 0; - gfx::Canvas::SizeStringInt(node->model_node()->GetTitle(), font_list_, - &width, &height, 0, gfx::Canvas::NO_ELLIPSIS); - node->set_text_width(width); -} - -void TreeView::DrawnNodesChanged() { - UpdatePreferredSize(); - PreferredSizeChanged(); - SchedulePaint(); -} - -void TreeView::UpdatePreferredSize() { - preferred_size_ = gfx::Size(); - if (!model_) - return; - - preferred_size_.SetSize( - root_.GetMaxWidth(text_offset_, root_shown_ ? 1 : 0) + - kTextHorizontalPadding * 2, - row_height_ * GetRowCount() + kVerticalInset * 2); -} - -void TreeView::LayoutEditor() { - if (!editing_) - return; - - DCHECK(selected_node_); - // Position the editor so that its text aligns with the text we drew. - gfx::Rect row_bounds = GetBoundsForNode(selected_node_); - row_bounds.set_x( - GetMirroredXWithWidthInView(row_bounds.x(), row_bounds.width())); - row_bounds.set_x(row_bounds.x() + text_offset_); - row_bounds.set_width(row_bounds.width() - text_offset_); - row_bounds.Inset(kTextHorizontalPadding, kTextVerticalPadding); - row_bounds.Inset(-empty_editor_size_.width() / 2, - -(empty_editor_size_.height() - font_list_.GetHeight()) / 2); - // Give a little extra space for editing. - row_bounds.set_width(row_bounds.width() + 50); - editor_->SetBoundsRect(row_bounds); - editor_->Layout(); -} - -void TreeView::SchedulePaintForNode(InternalNode* node) { - if (!node) - return; // Explicitly allow NULL to be passed in. - SchedulePaintInRect(GetBoundsForNode(node)); -} - -void TreeView::PaintRows(gfx::Canvas* canvas, - int min_row, - int max_row, - InternalNode* node, - int depth, - int* row) { - if (*row >= max_row) - return; - - if (*row >= min_row && *row < max_row) - PaintRow(canvas, node, *row, depth); - (*row)++; - if (!node->is_expanded()) - return; - depth++; - for (int i = 0; i < node->child_count() && *row < max_row; ++i) - PaintRows(canvas, min_row, max_row, node->GetChild(i), depth, row); -} - -void TreeView::PaintRow(gfx::Canvas* canvas, - InternalNode* node, - int row, - int depth) { - gfx::Rect bounds(GetBoundsForNodeImpl(node, row, depth)); - - if (model_->GetChildCount(node->model_node())) - PaintExpandControl(canvas, bounds, node->is_expanded()); - - // Paint the icon. - gfx::ImageSkia icon; - int icon_index = model_->GetIconIndex(node->model_node()); - if (icon_index != -1) - icon = icons_[icon_index]; - else if (node == selected_node_) - icon = open_icon_; - else - icon = closed_icon_; - int icon_x = kArrowRegionSize + kImagePadding + - (open_icon_.width() - icon.width()) / 2; - if (base::i18n::IsRTL()) - icon_x = bounds.right() - icon_x - open_icon_.width(); - else - icon_x += bounds.x(); - canvas->DrawImageInt( - icon, icon_x, - bounds.y() + (bounds.height() - icon.height()) / 2); - - if (!editing_ || node != selected_node_) { - gfx::Rect text_bounds(bounds.x() + text_offset_, bounds.y(), - bounds.width() - text_offset_, bounds.height()); - if (base::i18n::IsRTL()) - text_bounds.set_x(bounds.x()); - if (node == selected_node_) { - const SkColor bg_color = GetNativeTheme()->GetSystemColor( - text_background_color_id(HasFocus())); - canvas->FillRect(text_bounds, bg_color); - if (HasFocus()) - canvas->DrawFocusRect(text_bounds); - } - const ui::NativeTheme::ColorId color_id = - text_color_id(HasFocus(), node == selected_node_); - const gfx::Rect internal_bounds( - text_bounds.x() + kTextHorizontalPadding, - text_bounds.y() + kTextVerticalPadding, - text_bounds.width() - kTextHorizontalPadding * 2, - text_bounds.height() - kTextVerticalPadding * 2); - canvas->DrawStringRect(node->model_node()->GetTitle(), font_list_, - GetNativeTheme()->GetSystemColor(color_id), - internal_bounds); - } -} - -void TreeView::PaintExpandControl(gfx::Canvas* canvas, - const gfx::Rect& node_bounds, - bool expanded) { - int center_x; - if (base::i18n::IsRTL()) { - center_x = node_bounds.right() - kArrowRegionSize + - (kArrowRegionSize - 4) / 2; - } else { - center_x = node_bounds.x() + (kArrowRegionSize - 4) / 2; - } - int center_y = node_bounds.y() + node_bounds.height() / 2; - const SkColor arrow_color = GetNativeTheme()->GetSystemColor( - ui::NativeTheme::kColorId_TreeArrow); - // TODO: this should come from an image. - if (!expanded) { - int delta = base::i18n::IsRTL() ? 1 : -1; - for (int i = 0; i < 4; ++i) { - canvas->FillRect(gfx::Rect(center_x + delta * (2 - i), - center_y - (3 - i), 1, (3 - i) * 2 + 1), - arrow_color); - } - } else { - center_y -= 2; - for (int i = 0; i < 4; ++i) { - canvas->FillRect(gfx::Rect(center_x - (3 - i), center_y + i, - (3 - i) * 2 + 1, 1), arrow_color); - } - } -} - -TreeView::InternalNode* TreeView::GetInternalNodeForModelNode( - ui::TreeModelNode* model_node, - GetInternalNodeCreateType create_type) { - if (model_node == root_.model_node()) - return &root_; - InternalNode* parent_internal_node = - GetInternalNodeForModelNode(model_->GetParent(model_node), create_type); - if (!parent_internal_node) - return NULL; - if (!parent_internal_node->loaded_children()) { - if (create_type == DONT_CREATE_IF_NOT_LOADED) - return NULL; - LoadChildren(parent_internal_node); - } - return parent_internal_node->GetChild( - model_->GetIndexOf(parent_internal_node->model_node(), model_node)); -} - -gfx::Rect TreeView::GetBoundsForNode(InternalNode* node) { - int row, depth; - row = GetRowForInternalNode(node, &depth); - return GetBoundsForNodeImpl(node, row, depth); -} - -gfx::Rect TreeView::GetBoundsForNodeImpl(InternalNode* node, - int row, - int depth) { - gfx::Rect rect(depth * kIndent + kHorizontalInset, - row * row_height_ + kVerticalInset, - text_offset_ + node->text_width() + - kTextHorizontalPadding * 2, - row_height_); - rect.set_x(GetMirroredXWithWidthInView(rect.x(), rect.width())); - return rect; -} - -int TreeView::GetRowForInternalNode(InternalNode* node, int* depth) { - DCHECK(!node->parent() || IsExpanded(node->parent()->model_node())); - *depth = -1; - int row = -1; - InternalNode* tmp_node = node; - while (tmp_node->parent()) { - int index_in_parent = tmp_node->parent()->GetIndexOf(tmp_node); - (*depth)++; - row++; // For node. - for (int i = 0; i < index_in_parent; ++i) - row += tmp_node->parent()->GetChild(i)->NumExpandedNodes(); - tmp_node = tmp_node->parent(); - } - if (root_shown_) { - (*depth)++; - row++; - } - return row; -} - -TreeView::InternalNode* TreeView::GetNodeByRow(int row, int* depth) { - int current_row = root_row(); - *depth = 0; - return GetNodeByRowImpl(&root_, row, root_depth(), ¤t_row, depth); -} - -TreeView::InternalNode* TreeView::GetNodeByRowImpl(InternalNode* node, - int target_row, - int current_depth, - int* current_row, - int* node_depth) { - if (*current_row == target_row) { - *node_depth = current_depth; - return node; - } - (*current_row)++; - if (node->is_expanded()) { - current_depth++; - for (int i = 0; i < node->child_count(); ++i) { - InternalNode* result = GetNodeByRowImpl( - node->GetChild(i), target_row, current_depth, current_row, - node_depth); - if (result) - return result; - } - } - return NULL; -} - -void TreeView::IncrementSelection(IncrementType type) { - if (!model_) - return; - - if (!GetSelectedNode()) { - // If nothing is selected select the first or last node. - if (!root_.child_count()) - return; - if (type == INCREMENT_PREVIOUS) { - int row_count = GetRowCount(); - int depth = 0; - DCHECK(row_count); - InternalNode* node = GetNodeByRow(row_count - 1, &depth); - SetSelectedNode(node->model_node()); - } else if (root_shown_) { - SetSelectedNode(root_.model_node()); - } else { - SetSelectedNode(root_.GetChild(0)->model_node()); - } - return; - } - - int depth = 0; - int delta = type == INCREMENT_PREVIOUS ? -1 : 1; - int row = GetRowForInternalNode(selected_node_, &depth); - int new_row = std::min(GetRowCount() - 1, std::max(0, row + delta)); - if (new_row == row) - return; // At the end/beginning. - SetSelectedNode(GetNodeByRow(new_row, &depth)->model_node()); -} - -void TreeView::CollapseOrSelectParent() { - if (selected_node_) { - if (selected_node_->is_expanded()) - Collapse(selected_node_->model_node()); - else if (selected_node_->parent()) - SetSelectedNode(selected_node_->parent()->model_node()); - } -} - -void TreeView::ExpandOrSelectChild() { - if (selected_node_) { - if (!selected_node_->is_expanded()) - Expand(selected_node_->model_node()); - else if (selected_node_->child_count()) - SetSelectedNode(selected_node_->GetChild(0)->model_node()); - } -} - -bool TreeView::ExpandImpl(TreeModelNode* model_node) { - TreeModelNode* parent = model_->GetParent(model_node); - if (!parent) { - // Node should be the root. - DCHECK_EQ(root_.model_node(), model_node); - bool was_expanded = root_.is_expanded(); - root_.set_is_expanded(true); - return !was_expanded; - } - - // Expand all the parents. - bool return_value = ExpandImpl(parent); - InternalNode* internal_node = - GetInternalNodeForModelNode(model_node, CREATE_IF_NOT_LOADED); - DCHECK(internal_node); - if (!internal_node->is_expanded()) { - if (!internal_node->loaded_children()) - LoadChildren(internal_node); - internal_node->set_is_expanded(true); - return_value = true; - } - return return_value; -} - -// InternalNode ---------------------------------------------------------------- - -TreeView::InternalNode::InternalNode() - : model_node_(NULL), - loaded_children_(false), - is_expanded_(false), - text_width_(0) { -} - -TreeView::InternalNode::~InternalNode() { -} - -void TreeView::InternalNode::Reset(ui::TreeModelNode* node) { - model_node_ = node; - loaded_children_ = false; - is_expanded_ = false; - text_width_ = 0; -} - -int TreeView::InternalNode::NumExpandedNodes() const { - int result = 1; // For this. - if (!is_expanded_) - return result; - for (int i = 0; i < child_count(); ++i) - result += GetChild(i)->NumExpandedNodes(); - return result; -} - -int TreeView::InternalNode::GetMaxWidth(int indent, int depth) { - int max_width = text_width_ + indent * depth; - if (!is_expanded_) - return max_width; - for (int i = 0; i < child_count(); ++i) { - max_width = std::max(max_width, - GetChild(i)->GetMaxWidth(indent, depth + 1)); - } - return max_width; -} - -} // namespace views
diff --git a/ui/views/controls/tree/tree_view.h b/ui/views/controls/tree/tree_view.h deleted file mode 100644 index dcecc9f..0000000 --- a/ui/views/controls/tree/tree_view.h +++ /dev/null
@@ -1,397 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_TREE_TREE_VIEW_VIEWS_H_ -#define UI_VIEWS_CONTROLS_TREE_TREE_VIEW_VIEWS_H_ - -#include <vector> - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "ui/base/models/tree_node_model.h" -#include "ui/gfx/font_list.h" -#include "ui/gfx/image/image_skia.h" -#include "ui/views/controls/prefix_delegate.h" -#include "ui/views/controls/textfield/textfield_controller.h" -#include "ui/views/focus/focus_manager.h" -#include "ui/views/view.h" - -namespace gfx { -class Rect; -} // namespace gfx - -namespace views { - -class Textfield; -class TreeViewController; -class PrefixSelector; - -// TreeView displays hierarchical data as returned from a TreeModel. The user -// can expand, collapse and edit the items. A Controller may be attached to -// receive notification of selection changes and restrict editing. -// -// Note on implementation. This implementation doesn't scale well. In particular -// it does not store any row information, but instead calculates it as -// necessary. But it's more than adequate for current uses. -class VIEWS_EXPORT TreeView : public ui::TreeModelObserver, - public TextfieldController, - public FocusChangeListener, - public PrefixDelegate { - public: - // The tree view's class name. - static const char kViewClassName[]; - - TreeView(); - virtual ~TreeView(); - - // Returns new ScrollPane that contains the receiver. - View* CreateParentIfNecessary(); - - // Sets the model. TreeView does not take ownership of the model. - void SetModel(ui::TreeModel* model); - ui::TreeModel* model() const { return model_; } - - // Sets whether to automatically expand children when a parent node is - // expanded. The default is false. If true, when a node in the tree is - // expanded for the first time, its children are also automatically expanded. - // If a node is subsequently collapsed and expanded again, the children - // will not be automatically expanded. - void set_auto_expand_children(bool auto_expand_children) { - auto_expand_children_ = auto_expand_children; - } - - // Sets whether the user can edit the nodes. The default is true. If true, - // the Controller is queried to determine if a particular node can be edited. - void SetEditable(bool editable); - - // Edits the specified node. This cancels the current edit and expands all - // parents of node. - void StartEditing(ui::TreeModelNode* node); - - // Cancels the current edit. Does nothing if not editing. - void CancelEdit(); - - // Commits the current edit. Does nothing if not editing. - void CommitEdit(); - - // If the user is editing a node, it is returned. If the user is not - // editing a node, NULL is returned. - ui::TreeModelNode* GetEditingNode(); - - // Selects the specified node. This expands all the parents of node. - void SetSelectedNode(ui::TreeModelNode* model_node); - - // Returns the selected node, or NULL if nothing is selected. - ui::TreeModelNode* GetSelectedNode(); - - // Marks |model_node| as collapsed. This only effects the UI if node and all - // its parents are expanded (IsExpanded(model_node) returns true). - void Collapse(ui::TreeModelNode* model_node); - - // Make sure node and all its parents are expanded. - void Expand(ui::TreeModelNode* node); - - // Invoked from ExpandAll(). Expands the supplied node and recursively - // invokes itself with all children. - void ExpandAll(ui::TreeModelNode* node); - - // Returns true if the specified node is expanded. - bool IsExpanded(ui::TreeModelNode* model_node); - - // Sets whether the root is shown. If true, the root node of the tree is - // shown, if false only the children of the root are shown. The default is - // true. - void SetRootShown(bool root_visible); - - // Sets the controller, which may be null. TreeView does not take ownership - // of the controller. - void SetController(TreeViewController* controller) { - controller_ = controller; - } - - // Returns the node for the specified row, or NULL for an invalid row index. - ui::TreeModelNode* GetNodeForRow(int row); - - // Maps a node to a row, returns -1 if node is not valid. - int GetRowForNode(ui::TreeModelNode* node); - - views::Textfield* editor() { return editor_; } - - // View overrides: - virtual void Layout() override; - virtual gfx::Size GetPreferredSize() const override; - virtual bool AcceleratorPressed(const ui::Accelerator& accelerator) override; - virtual bool OnMousePressed(const ui::MouseEvent& event) override; - virtual ui::TextInputClient* GetTextInputClient() override; - virtual void OnGestureEvent(ui::GestureEvent* event) override; - virtual void ShowContextMenu(const gfx::Point& p, - ui::MenuSourceType source_type) override; - virtual void GetAccessibleState(ui::AXViewState* state) override; - virtual const char* GetClassName() const override; - - // TreeModelObserver overrides: - virtual void TreeNodesAdded(ui::TreeModel* model, - ui::TreeModelNode* parent, - int start, - int count) override; - virtual void TreeNodesRemoved(ui::TreeModel* model, - ui::TreeModelNode* parent, - int start, - int count) override; - virtual void TreeNodeChanged(ui::TreeModel* model, - ui::TreeModelNode* model_node) override; - - // TextfieldController overrides: - virtual void ContentsChanged(Textfield* sender, - const base::string16& new_contents) override; - virtual bool HandleKeyEvent(Textfield* sender, - const ui::KeyEvent& key_event) override; - - // FocusChangeListener overrides: - virtual void OnWillChangeFocus(View* focused_before, - View* focused_now) override; - virtual void OnDidChangeFocus(View* focused_before, - View* focused_now) override; - - // PrefixDelegate overrides: - virtual int GetRowCount() override; - virtual int GetSelectedRow() override; - virtual void SetSelectedRow(int row) override; - virtual base::string16 GetTextForRow(int row) override; - - protected: - // View overrides: - virtual gfx::Point GetKeyboardContextMenuLocation() override; - virtual bool OnKeyPressed(const ui::KeyEvent& event) override; - virtual void OnPaint(gfx::Canvas* canvas) override; - virtual void OnFocus() override; - virtual void OnBlur() override; - - private: - friend class TreeViewTest; - - // Selects, expands or collapses nodes in the tree. Consistent behavior for - // tap gesture and click events. - bool OnClickOrTap(const ui::LocatedEvent& event); - - // InternalNode is used to track information about the set of nodes displayed - // by TreeViewViews. - class InternalNode : public ui::TreeNode<InternalNode> { - public: - InternalNode(); - virtual ~InternalNode(); - - // Resets the state from |node|. - void Reset(ui::TreeModelNode* node); - - // The model node this InternalNode represents. - ui::TreeModelNode* model_node() { return model_node_; } - - // Whether the node is expanded. - void set_is_expanded(bool expanded) { is_expanded_ = expanded; } - bool is_expanded() const { return is_expanded_; } - - // Whether children have been loaded. - void set_loaded_children(bool value) { loaded_children_ = value; } - bool loaded_children() const { return loaded_children_; } - - // Width needed to display the string. - void set_text_width(int width) { text_width_ = width; } - int text_width() const { return text_width_; } - - // Returns the total number of descendants (including this node). - int NumExpandedNodes() const; - - // Returns the max width of all descendants (including this node). |indent| - // is how many pixels each child is indented and |depth| is the depth of - // this node from its parent. - int GetMaxWidth(int indent, int depth); - - private: - // The node from the model. - ui::TreeModelNode* model_node_; - - // Whether the children have been loaded. - bool loaded_children_; - - bool is_expanded_; - - int text_width_; - - DISALLOW_COPY_AND_ASSIGN(InternalNode); - }; - - // Used by GetInternalNodeForModelNode. - enum GetInternalNodeCreateType { - // If an InternalNode hasn't been created yet, create it. - CREATE_IF_NOT_LOADED, - - // Don't create an InternalNode if one hasn't been created yet. - DONT_CREATE_IF_NOT_LOADED, - }; - - // Used by IncrementSelection. - enum IncrementType { - // Selects the next node. - INCREMENT_NEXT, - - // Selects the previous node. - INCREMENT_PREVIOUS - }; - - // Row of the root node. This varies depending upon whether the root is - // visible. - int root_row() const { return root_shown_ ? 0 : -1; } - - // Depth of the root node. - int root_depth() const { return root_shown_ ? 0 : -1; } - - // Loads the children of the specified node. - void LoadChildren(InternalNode* node); - - // Configures an InternalNode from a node from the model. This is used - // when a node changes as well as when loading. - void ConfigureInternalNode(ui::TreeModelNode* model_node, InternalNode* node); - - // Sets |node|s text_width. - void UpdateNodeTextWidth(InternalNode* node); - - // Invoked when the set of drawn nodes changes. - void DrawnNodesChanged(); - - // Updates |preferred_size_| from the state of the UI. - void UpdatePreferredSize(); - - // Positions |editor_|. - void LayoutEditor(); - - // Schedules a paint for |node|. - void SchedulePaintForNode(InternalNode* node); - - // Recursively paints rows from |min_row| to |max_row|. |node| is the node for - // the row |*row|. |row| is updated as this walks the tree. Depth is the depth - // of |*row|. - void PaintRows(gfx::Canvas* canvas, - int min_row, - int max_row, - InternalNode* node, - int depth, - int* row); - - // Invoked to paint a single node. - void PaintRow(gfx::Canvas* canvas, - InternalNode* node, - int row, - int depth); - - // Paints the expand control given the specified nodes bounds. - void PaintExpandControl(gfx::Canvas* canvas, - const gfx::Rect& node_bounds, - bool expanded); - - // Returns the InternalNode for a model node. |create_type| indicates wheter - // this should load InternalNode or not. - InternalNode* GetInternalNodeForModelNode( - ui::TreeModelNode* model_node, - GetInternalNodeCreateType create_type); - - // Returns the bounds for a node. - gfx::Rect GetBoundsForNode(InternalNode* node); - - // Implementation of GetBoundsForNode. Separated out as some callers already - // know the row/depth. - gfx::Rect GetBoundsForNodeImpl(InternalNode* node, int row, int depth); - - // Returns the row and depth of a node. - int GetRowForInternalNode(InternalNode* node, int* depth); - - // Returns the row and depth of the specified node. - InternalNode* GetNodeByRow(int row, int* depth); - - // Implementation of GetNodeByRow. |curent_row| is updated as we iterate. - InternalNode* GetNodeByRowImpl(InternalNode* node, - int target_row, - int current_depth, - int* current_row, - int* node_depth); - - // Increments the selection. Invoked in response to up/down arrow. - void IncrementSelection(IncrementType type); - - // If the current node is expanded, it's collapsed, otherwise selection is - // moved to the parent. - void CollapseOrSelectParent(); - - // If the selected node is collapsed, it's expanded. Otherwise the first child - // is seleected. - void ExpandOrSelectChild(); - - // Implementation of Expand(). Returns true if at least one node was expanded - // that previously wasn't. - bool ExpandImpl(ui::TreeModelNode* model_node); - - // The model, may be null. - ui::TreeModel* model_; - - // Default icons for closed/open. - gfx::ImageSkia closed_icon_; - gfx::ImageSkia open_icon_; - - // Icons from the model. - std::vector<gfx::ImageSkia> icons_; - - // The root node. - InternalNode root_; - - // The selected node, may be NULL. - InternalNode* selected_node_; - - bool editing_; - - // The editor; lazily created and never destroyed (well, until TreeView is - // destroyed). Hidden when no longer editing. We do this avoid destruction - // problems. - Textfield* editor_; - - // Preferred size of |editor_| with no content. - gfx::Size empty_editor_size_; - - // If non-NULL we've attached a listener to this focus manager. Used to know - // when focus is changing to another view so that we can cancel the edit. - FocusManager* focus_manager_; - - // Whether to automatically expand children when a parent node is expanded. - bool auto_expand_children_; - - // Whether the user can edit the items. - bool editable_; - - // The controller. - TreeViewController* controller_; - - // Whether or not the root is shown in the tree. - bool root_shown_; - - // Cached preferred size. - gfx::Size preferred_size_; - - // Font list used to display text. - gfx::FontList font_list_; - - // Height of each row. Based on font and some padding. - int row_height_; - - // Offset the text is drawn at. This accounts for the size of the expand - // control, icon and offsets. - int text_offset_; - - scoped_ptr<PrefixSelector> selector_; - - DISALLOW_COPY_AND_ASSIGN(TreeView); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_TREE_TREE_VIEW_VIEWS_H_
diff --git a/ui/views/controls/tree/tree_view_controller.cc b/ui/views/controls/tree/tree_view_controller.cc deleted file mode 100644 index 670d0ed..0000000 --- a/ui/views/controls/tree/tree_view_controller.cc +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/tree/tree_view_controller.h" - -#include "ui/base/models/tree_model.h" -#include "ui/views/controls/tree/tree_view.h" - -namespace views { - -bool TreeViewController::CanEdit(TreeView* tree_view, ui::TreeModelNode* node) { - return true; -} - -TreeViewController::~TreeViewController() { -} - -} // namespace views
diff --git a/ui/views/controls/tree/tree_view_controller.h b/ui/views/controls/tree/tree_view_controller.h deleted file mode 100644 index b1ebf2b..0000000 --- a/ui/views/controls/tree/tree_view_controller.h +++ /dev/null
@@ -1,38 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_TREE_TREE_VIEW_CONTROLLER_H_ -#define UI_VIEWS_CONTROLS_TREE_TREE_VIEW_CONTROLLER_H_ - -#include "ui/events/keycodes/keyboard_codes.h" -#include "ui/views/views_export.h" - -namespace ui { -class TreeModelNode; -} - -namespace views { - -class TreeView; - -// TreeViewController --------------------------------------------------------- - -// Controller for the treeview. -class VIEWS_EXPORT TreeViewController { - public: - // Notification that the selection of the tree view has changed. Use - // GetSelectedNode to find the current selection. - virtual void OnTreeViewSelectionChanged(TreeView* tree_view) = 0; - - // Returns true if the node can be edited. This is only used if the - // TreeView is editable. - virtual bool CanEdit(TreeView* tree_view, ui::TreeModelNode* node); - - protected: - virtual ~TreeViewController(); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_TREE_TREE_VIEW_CONTROLLER_H_
diff --git a/ui/views/controls/tree/tree_view_unittest.cc b/ui/views/controls/tree/tree_view_unittest.cc deleted file mode 100644 index bf73da9..0000000 --- a/ui/views/controls/tree/tree_view_unittest.cc +++ /dev/null
@@ -1,424 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/tree/tree_view.h" - -#include <string> - -#include "base/strings/string_util.h" -#include "base/strings/utf_string_conversions.h" -#include "ui/base/models/tree_node_model.h" -#include "ui/views/controls/prefix_selector.h" -#include "ui/views/controls/textfield/textfield.h" -#include "ui/views/test/views_test_base.h" - -using ui::TreeModel; -using ui::TreeModelNode; -using ui::TreeNode; - -using base::ASCIIToUTF16; - -namespace views { - -class TestNode : public TreeNode<TestNode> { - public: - TestNode() {} - virtual ~TestNode() {} - - private: - DISALLOW_COPY_AND_ASSIGN(TestNode); -}; - -// Creates the following structure: -// 'root' -// 'a' -// 'b' -// 'b1' -// 'c' -class TreeViewTest : public ViewsTestBase { - public: - TreeViewTest() : model_(new TestNode) { - static_cast<TestNode*>(model_.GetRoot())->SetTitle(ASCIIToUTF16("root")); - Add(model_.GetRoot(), 0, "a"); - Add(Add(model_.GetRoot(), 1, "b"), 0, "b1"); - Add(model_.GetRoot(), 2, "c"); - } - - protected: - TestNode* Add(TestNode* parent, - int index, - const std::string& title); - - std::string TreeViewContentsAsString(); - - std::string GetSelectedNodeTitle(); - - std::string GetEditingNodeTitle(); - - TestNode* GetNodeByTitle(const std::string& title); - - void IncrementSelection(bool next); - void CollapseOrSelectParent(); - void ExpandOrSelectChild(); - int GetRowCount(); - PrefixSelector* selector() { return tree_.selector_.get(); } - - ui::TreeNodeModel<TestNode > model_; - TreeView tree_; - - private: - std::string InternalNodeAsString(TreeView::InternalNode* node); - - TestNode* GetNodeByTitleImpl(TestNode* node, const base::string16& title); - - DISALLOW_COPY_AND_ASSIGN(TreeViewTest); -}; - -TestNode* TreeViewTest::Add(TestNode* parent, - int index, - const std::string& title) { - TestNode* new_node = new TestNode; - new_node->SetTitle(ASCIIToUTF16(title)); - model_.Add(parent, new_node, index); - return new_node; -} - -std::string TreeViewTest::TreeViewContentsAsString() { - return InternalNodeAsString(&tree_.root_); -} - -std::string TreeViewTest::GetSelectedNodeTitle() { - TreeModelNode* model_node = tree_.GetSelectedNode(); - return model_node ? base::UTF16ToASCII(model_node->GetTitle()) - : std::string(); -} - -std::string TreeViewTest::GetEditingNodeTitle() { - TreeModelNode* model_node = tree_.GetEditingNode(); - return model_node ? base::UTF16ToASCII(model_node->GetTitle()) - : std::string(); -} - -TestNode* TreeViewTest::GetNodeByTitle(const std::string& title) { - return GetNodeByTitleImpl(model_.GetRoot(), ASCIIToUTF16(title)); -} - -void TreeViewTest::IncrementSelection(bool next) { - tree_.IncrementSelection(next ? TreeView::INCREMENT_NEXT : - TreeView::INCREMENT_PREVIOUS); -} - -void TreeViewTest::CollapseOrSelectParent() { - tree_.CollapseOrSelectParent(); -} - -void TreeViewTest::ExpandOrSelectChild() { - tree_.ExpandOrSelectChild(); -} - -int TreeViewTest::GetRowCount() { - return tree_.GetRowCount(); -} - -TestNode* TreeViewTest::GetNodeByTitleImpl(TestNode* node, - const base::string16& title) { - if (node->GetTitle() == title) - return node; - for (int i = 0; i < node->child_count(); ++i) { - TestNode* child = GetNodeByTitleImpl(node->GetChild(i), title); - if (child) - return child; - } - return NULL; -} - -std::string TreeViewTest::InternalNodeAsString( - TreeView::InternalNode* node) { - std::string result = base::UTF16ToASCII(node->model_node()->GetTitle()); - if (node->is_expanded() && node->child_count()) { - result += " ["; - for (int i = 0; i < node->child_count(); ++i) { - if (i > 0) - result += " "; - result += InternalNodeAsString(node->GetChild(i)); - } - result += "]"; - } - return result; -} - -// Verifies setting model correctly updates internal state. -TEST_F(TreeViewTest, SetModel) { - tree_.SetModel(&model_); - EXPECT_EQ("root [a b c]", TreeViewContentsAsString()); - EXPECT_EQ("root", GetSelectedNodeTitle()); - EXPECT_EQ(4, GetRowCount()); -} - -// Verifies SetSelectedNode works. -TEST_F(TreeViewTest, SetSelectedNode) { - tree_.SetModel(&model_); - EXPECT_EQ("root", GetSelectedNodeTitle()); - - // NULL should clear the selection. - tree_.SetSelectedNode(NULL); - EXPECT_EQ(std::string(), GetSelectedNodeTitle()); - - // Select 'c'. - tree_.SetSelectedNode(GetNodeByTitle("c")); - EXPECT_EQ("c", GetSelectedNodeTitle()); - - // Select 'b1', which should expand 'b'. - tree_.SetSelectedNode(GetNodeByTitle("b1")); - EXPECT_EQ("root [a b [b1] c]", TreeViewContentsAsString()); - EXPECT_EQ("b1", GetSelectedNodeTitle()); -} - -// Makes sure SetRootShown doesn't blow up. -TEST_F(TreeViewTest, HideRoot) { - tree_.SetModel(&model_); - tree_.SetRootShown(false); - EXPECT_EQ("root [a b c]", TreeViewContentsAsString()); - EXPECT_EQ("a", GetSelectedNodeTitle()); - EXPECT_EQ(3, GetRowCount()); -} - -// Expands a node and verifies the children are loaded correctly. -TEST_F(TreeViewTest, Expand) { - tree_.SetModel(&model_); - tree_.Expand(GetNodeByTitle("b1")); - EXPECT_EQ("root [a b [b1] c]", TreeViewContentsAsString()); - EXPECT_EQ("root",GetSelectedNodeTitle()); - EXPECT_EQ(5, GetRowCount()); -} - -// Collapes a node and verifies state. -TEST_F(TreeViewTest, Collapse) { - tree_.SetModel(&model_); - tree_.Expand(GetNodeByTitle("b1")); - EXPECT_EQ("root [a b [b1] c]", TreeViewContentsAsString()); - EXPECT_EQ(5, GetRowCount()); - tree_.SetSelectedNode(GetNodeByTitle("b1")); - EXPECT_EQ("b1", GetSelectedNodeTitle()); - tree_.Collapse(GetNodeByTitle("b")); - EXPECT_EQ("root [a b c]", TreeViewContentsAsString()); - // Selected node should have moved to 'b' - EXPECT_EQ("b", GetSelectedNodeTitle()); - EXPECT_EQ(4, GetRowCount()); -} - -// Verifies adding nodes works. -TEST_F(TreeViewTest, TreeNodesAdded) { - tree_.SetModel(&model_); - EXPECT_EQ("root [a b c]", TreeViewContentsAsString()); - // Add a node between b and c. - Add(model_.GetRoot(), 2, "B"); - EXPECT_EQ("root [a b B c]", TreeViewContentsAsString()); - EXPECT_EQ("root", GetSelectedNodeTitle()); - EXPECT_EQ(5, GetRowCount()); - - // Add a child of b1, which hasn't been loaded and shouldn't do anything. - Add(GetNodeByTitle("b1"), 0, "b11"); - EXPECT_EQ("root [a b B c]", TreeViewContentsAsString()); - EXPECT_EQ("root", GetSelectedNodeTitle()); - EXPECT_EQ(5, GetRowCount()); - - // Add a child of b, which isn't expanded yet, so it shouldn't effect - // anything. - Add(GetNodeByTitle("b"), 1, "b2"); - EXPECT_EQ("root [a b B c]", TreeViewContentsAsString()); - EXPECT_EQ("root", GetSelectedNodeTitle()); - EXPECT_EQ(5, GetRowCount()); - - // Expand b and make sure b2 is there. - tree_.Expand(GetNodeByTitle("b")); - EXPECT_EQ("root [a b [b1 b2] B c]", TreeViewContentsAsString()); - EXPECT_EQ("root",GetSelectedNodeTitle()); - EXPECT_EQ(7, GetRowCount()); -} - -// Verifies removing nodes works. -TEST_F(TreeViewTest, TreeNodesRemoved) { - // Add c1 as a child of c and c11 as a child of c1. - Add(Add(GetNodeByTitle("c"), 0, "c1"), 0, "c11"); - tree_.SetModel(&model_); - - // Remove c11, which shouldn't have any effect on the tree. - EXPECT_EQ("root [a b c]", TreeViewContentsAsString()); - EXPECT_EQ("root", GetSelectedNodeTitle()); - EXPECT_EQ(4, GetRowCount()); - - // Expand b1, then collapse it and remove its only child, b1. This shouldn't - // effect the tree. - tree_.Expand(GetNodeByTitle("b")); - tree_.Collapse(GetNodeByTitle("b")); - delete model_.Remove(GetNodeByTitle("b1")->parent(), GetNodeByTitle("b1")); - EXPECT_EQ("root [a b c]", TreeViewContentsAsString()); - EXPECT_EQ("root", GetSelectedNodeTitle()); - EXPECT_EQ(4, GetRowCount()); - - // Remove 'b'. - delete model_.Remove(GetNodeByTitle("b")->parent(), GetNodeByTitle("b")); - EXPECT_EQ("root [a c]", TreeViewContentsAsString()); - EXPECT_EQ("root", GetSelectedNodeTitle()); - EXPECT_EQ(3, GetRowCount()); - - // Remove 'c11', shouldn't visually change anything. - delete model_.Remove(GetNodeByTitle("c11")->parent(), GetNodeByTitle("c11")); - EXPECT_EQ("root [a c]", TreeViewContentsAsString()); - EXPECT_EQ("root", GetSelectedNodeTitle()); - EXPECT_EQ(3, GetRowCount()); - - // Select 'c1', remove 'c' and make sure selection changes. - tree_.SetSelectedNode(GetNodeByTitle("c1")); - EXPECT_EQ("c1", GetSelectedNodeTitle()); - delete model_.Remove(GetNodeByTitle("c")->parent(), GetNodeByTitle("c")); - EXPECT_EQ("root [a]", TreeViewContentsAsString()); - EXPECT_EQ("root", GetSelectedNodeTitle()); - EXPECT_EQ(2, GetRowCount()); - - tree_.SetRootShown(false); - // Add 'b' select it and remove it. Because we're not showing the root - // selection should change to 'a'. - Add(GetNodeByTitle("root"), 1, "b"); - tree_.SetSelectedNode(GetNodeByTitle("b")); - delete model_.Remove(GetNodeByTitle("b")->parent(), GetNodeByTitle("b")); - EXPECT_EQ("root [a]", TreeViewContentsAsString()); - EXPECT_EQ("a", GetSelectedNodeTitle()); - EXPECT_EQ(1, GetRowCount()); -} - -// Verifies changing a node title works. -TEST_F(TreeViewTest, TreeNodeChanged) { - // Add c1 as a child of c and c11 as a child of c1. - Add(Add(GetNodeByTitle("c"), 0, "c1"), 0, "c11"); - tree_.SetModel(&model_); - - // Change c11, shouldn't do anything. - model_.SetTitle(GetNodeByTitle("c11"), ASCIIToUTF16("c11.new")); - EXPECT_EQ("root [a b c]", TreeViewContentsAsString()); - EXPECT_EQ("root", GetSelectedNodeTitle()); - EXPECT_EQ(4, GetRowCount()); - - // Change 'b1', shouldn't do anything. - model_.SetTitle(GetNodeByTitle("b1"), ASCIIToUTF16("b1.new")); - EXPECT_EQ("root [a b c]", TreeViewContentsAsString()); - EXPECT_EQ("root", GetSelectedNodeTitle()); - EXPECT_EQ(4, GetRowCount()); - - // Change 'b'. - model_.SetTitle(GetNodeByTitle("b"), ASCIIToUTF16("b.new")); - EXPECT_EQ("root [a b.new c]", TreeViewContentsAsString()); - EXPECT_EQ("root", GetSelectedNodeTitle()); - EXPECT_EQ(4, GetRowCount()); -} - -// Verifies IncrementSelection() works. -TEST_F(TreeViewTest, IncrementSelection) { - tree_.SetModel(&model_); - - IncrementSelection(true); - EXPECT_EQ("a", GetSelectedNodeTitle()); - IncrementSelection(true); - EXPECT_EQ("b", GetSelectedNodeTitle()); - IncrementSelection(true); - tree_.Expand(GetNodeByTitle("b")); - IncrementSelection(false); - EXPECT_EQ("b1", GetSelectedNodeTitle()); - IncrementSelection(true); - EXPECT_EQ("c", GetSelectedNodeTitle()); - IncrementSelection(true); - EXPECT_EQ("c", GetSelectedNodeTitle()); - - tree_.SetRootShown(false); - tree_.SetSelectedNode(GetNodeByTitle("a")); - EXPECT_EQ("a", GetSelectedNodeTitle()); - IncrementSelection(false); - EXPECT_EQ("a", GetSelectedNodeTitle()); -} - -// Verifies CollapseOrSelectParent works. -TEST_F(TreeViewTest, CollapseOrSelectParent) { - tree_.SetModel(&model_); - - tree_.SetSelectedNode(GetNodeByTitle("root")); - CollapseOrSelectParent(); - EXPECT_EQ("root", TreeViewContentsAsString()); - EXPECT_EQ("root", GetSelectedNodeTitle()); - - // Hide the root, which should implicitly expand the root. - tree_.SetRootShown(false); - EXPECT_EQ("root [a b c]", TreeViewContentsAsString()); - EXPECT_EQ("a", GetSelectedNodeTitle()); - - tree_.SetSelectedNode(GetNodeByTitle("b1")); - EXPECT_EQ("root [a b [b1] c]", TreeViewContentsAsString()); - EXPECT_EQ("b1", GetSelectedNodeTitle()); - CollapseOrSelectParent(); - EXPECT_EQ("root [a b [b1] c]", TreeViewContentsAsString()); - EXPECT_EQ("b", GetSelectedNodeTitle()); - CollapseOrSelectParent(); - EXPECT_EQ("root [a b c]", TreeViewContentsAsString()); - EXPECT_EQ("b", GetSelectedNodeTitle()); -} - -// Verifies ExpandOrSelectChild works. -TEST_F(TreeViewTest, ExpandOrSelectChild) { - tree_.SetModel(&model_); - - tree_.SetSelectedNode(GetNodeByTitle("root")); - ExpandOrSelectChild(); - EXPECT_EQ("root [a b c]", TreeViewContentsAsString()); - EXPECT_EQ("a", GetSelectedNodeTitle()); - - ExpandOrSelectChild(); - EXPECT_EQ("root [a b c]", TreeViewContentsAsString()); - EXPECT_EQ("a", GetSelectedNodeTitle()); - - tree_.SetSelectedNode(GetNodeByTitle("b")); - ExpandOrSelectChild(); - EXPECT_EQ("root [a b [b1] c]", TreeViewContentsAsString()); - EXPECT_EQ("b", GetSelectedNodeTitle()); - ExpandOrSelectChild(); - EXPECT_EQ("root [a b [b1] c]", TreeViewContentsAsString()); - EXPECT_EQ("b1", GetSelectedNodeTitle()); - ExpandOrSelectChild(); - EXPECT_EQ("root [a b [b1] c]", TreeViewContentsAsString()); - EXPECT_EQ("b1", GetSelectedNodeTitle()); -} - -// Verify selection is properly updated on each keystroke. -TEST_F(TreeViewTest, SelectOnKeyStroke) { - tree_.SetModel(&model_); - tree_.ExpandAll(model_.GetRoot()); - tree_.GetTextInputClient(); - selector()->InsertText(ASCIIToUTF16("b")); - EXPECT_EQ("b", GetSelectedNodeTitle()); - selector()->InsertText(ASCIIToUTF16("1")); - EXPECT_EQ("b1", GetSelectedNodeTitle()); - - // Invoke OnViewBlur() to reset time. - selector()->OnViewBlur(); - selector()->InsertText(ASCIIToUTF16("z")); - EXPECT_EQ("b1", GetSelectedNodeTitle()); - - selector()->OnViewBlur(); - selector()->InsertText(ASCIIToUTF16("a")); - EXPECT_EQ("a", GetSelectedNodeTitle()); -} - -// Verifies edits are committed when focus is lost. -TEST_F(TreeViewTest, CommitOnFocusLost) { - tree_.SetModel(&model_); - - tree_.SetSelectedNode(GetNodeByTitle("root")); - ExpandOrSelectChild(); - tree_.SetEditable(true); - tree_.StartEditing(GetNodeByTitle("a")); - tree_.editor()->SetText(ASCIIToUTF16("a changed")); - tree_.OnDidChangeFocus(NULL, NULL); - EXPECT_TRUE(GetNodeByTitle("a changed") != NULL); -} - -} // namespace views
diff --git a/ui/views/controls/webview/BUILD.gn b/ui/views/controls/webview/BUILD.gn deleted file mode 100644 index 6671139..0000000 --- a/ui/views/controls/webview/BUILD.gn +++ /dev/null
@@ -1,67 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -component("webview") { - sources = [ - "unhandled_keyboard_event_handler.cc", - "unhandled_keyboard_event_handler.h", - "unhandled_keyboard_event_handler_linux.cc", - "unhandled_keyboard_event_handler_win.cc", - "web_dialog_view.cc", - "web_dialog_view.h", - "webview.cc", - "webview.h", - "webview_export.h", - ] - - defines = [ "WEBVIEW_IMPLEMENTATION" ] - - deps = [ - "//base:i18n", - "//base/third_party/dynamic_annotations", - "//ipc", - "//skia", - "//ui/accessibility", - "//ui/base", - "//ui/events", - "//ui/events:events_base", - "//ui/web_dialogs", - "//url", - ] - - public_deps = [ - "//base", - "//content/public/browser", - "//ui/aura", - "//ui/gfx", - "//ui/gfx/geometry", - "//ui/views", - ] -} - -source_set("test_support") { - testonly = true - sources = [ - "../../test/webview_test_helper.cc", - "../../test/webview_test_helper.h", - ] - - public_deps = [ - ":webview", - ] - deps = [ - "//base", - "//content", - "//content/test:test_support", - "//ipc:test_support", - "//skia", - "//testing/gtest", - "//ui/base", - "//ui/events", - "//ui/gfx", - "//ui/gfx/geometry", - "//ui/views", - "//ui/views:test_support", - ] -}
diff --git a/ui/views/controls/webview/DEPS b/ui/views/controls/webview/DEPS deleted file mode 100644 index 70d0458..0000000 --- a/ui/views/controls/webview/DEPS +++ /dev/null
@@ -1,7 +0,0 @@ -include_rules = [ - "+content/public", - "+ui/views", - "+ui/web_dialogs", - "+content/browser/web_contents/web_contents_impl.h", - "+content/test/test_content_browser_client.h", -]
diff --git a/ui/views/controls/webview/unhandled_keyboard_event_handler.cc b/ui/views/controls/webview/unhandled_keyboard_event_handler.cc deleted file mode 100644 index 0a43353..0000000 --- a/ui/views/controls/webview/unhandled_keyboard_event_handler.cc +++ /dev/null
@@ -1,12 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/webview/unhandled_keyboard_event_handler.h" - -namespace views { - -UnhandledKeyboardEventHandler::~UnhandledKeyboardEventHandler() { -} - -} // namespace views
diff --git a/ui/views/controls/webview/unhandled_keyboard_event_handler.h b/ui/views/controls/webview/unhandled_keyboard_event_handler.h deleted file mode 100644 index 6d30baf..0000000 --- a/ui/views/controls/webview/unhandled_keyboard_event_handler.h +++ /dev/null
@@ -1,42 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_WEBVIEW_UNHANDLED_KEYBOARD_EVENT_HANDLER_H_ -#define UI_VIEWS_CONTROLS_WEBVIEW_UNHANDLED_KEYBOARD_EVENT_HANDLER_H_ - -#include "base/basictypes.h" -#include "ui/views/controls/webview/webview_export.h" - -namespace content { -struct NativeWebKeyboardEvent; -} - -namespace views { -class FocusManager; - -// This class handles unhandled keyboard messages coming back from the renderer -// process. -class WEBVIEW_EXPORT UnhandledKeyboardEventHandler { - public: - UnhandledKeyboardEventHandler(); - ~UnhandledKeyboardEventHandler(); - - void HandleKeyboardEvent(const content::NativeWebKeyboardEvent& event, - FocusManager* focus_manager); - - private: - // Whether to ignore the next Char keyboard event. - // If a RawKeyDown event was handled as a shortcut key, then we're done - // handling it and should eat any Char event that the translate phase may - // have produced from it. (Handling this event may cause undesirable effects, - // such as a beep if DefWindowProc() has no default handling for the given - // Char.) - bool ignore_next_char_event_; - - DISALLOW_COPY_AND_ASSIGN(UnhandledKeyboardEventHandler); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_WEBVIEW_UNHANDLED_KEYBOARD_EVENT_HANDLER_H_
diff --git a/ui/views/controls/webview/unhandled_keyboard_event_handler_linux.cc b/ui/views/controls/webview/unhandled_keyboard_event_handler_linux.cc deleted file mode 100644 index 45c51ad..0000000 --- a/ui/views/controls/webview/unhandled_keyboard_event_handler_linux.cc +++ /dev/null
@@ -1,63 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/webview/unhandled_keyboard_event_handler.h" - -#include "base/logging.h" -#include "content/public/browser/native_web_keyboard_event.h" -#include "ui/events/event.h" -#include "ui/views/focus/focus_manager.h" - -using content::NativeWebKeyboardEvent; - -namespace views { - -UnhandledKeyboardEventHandler::UnhandledKeyboardEventHandler() - : ignore_next_char_event_(false) { -} - -void UnhandledKeyboardEventHandler::HandleKeyboardEvent( - const NativeWebKeyboardEvent& event, - FocusManager* focus_manager) { - if (!focus_manager) { - NOTREACHED(); - return; - } - - // Previous calls to TranslateMessage can generate Char events as well as - // RawKeyDown events, even if the latter triggered an accelerator. In these - // cases, we discard the Char events. - if (event.type == blink::WebInputEvent::Char && ignore_next_char_event_) { - ignore_next_char_event_ = false; - return; - } - // It's necessary to reset this flag, because a RawKeyDown event may not - // always generate a Char event. - ignore_next_char_event_ = false; - - if (event.type == blink::WebInputEvent::RawKeyDown) { - ui::Accelerator accelerator( - static_cast<ui::KeyboardCode>(event.windowsKeyCode), - content::GetModifiersFromNativeWebKeyboardEvent(event)); - - // This is tricky: we want to set ignore_next_char_event_ if - // ProcessAccelerator returns true. But ProcessAccelerator might delete - // |this| if the accelerator is a "close tab" one. So we speculatively - // set the flag and fix it if no event was handled. - ignore_next_char_event_ = true; - - if (focus_manager->ProcessAccelerator(accelerator)) { - return; - } - - // ProcessAccelerator didn't handle the accelerator, so we know both - // that |this| is still valid, and that we didn't want to set the flag. - ignore_next_char_event_ = false; - } - - if (event.os_event && !event.skip_in_browser) - focus_manager->OnKeyEvent(*static_cast<ui::KeyEvent*>(event.os_event)); -} - -} // namespace views
diff --git a/ui/views/controls/webview/unhandled_keyboard_event_handler_win.cc b/ui/views/controls/webview/unhandled_keyboard_event_handler_win.cc deleted file mode 100644 index 463ef7e..0000000 --- a/ui/views/controls/webview/unhandled_keyboard_event_handler_win.cc +++ /dev/null
@@ -1,66 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/webview/unhandled_keyboard_event_handler.h" - -#include "base/logging.h" -#include "content/public/browser/native_web_keyboard_event.h" -#include "ui/events/event.h" -#include "ui/views/focus/focus_manager.h" - -using content::NativeWebKeyboardEvent; - -namespace views { - -UnhandledKeyboardEventHandler::UnhandledKeyboardEventHandler() { - ignore_next_char_event_ = false; -} - -void UnhandledKeyboardEventHandler::HandleKeyboardEvent( - const NativeWebKeyboardEvent& event, - FocusManager* focus_manager) { - if (!focus_manager) { - NOTREACHED(); - return; - } - // Previous calls to TranslateMessage can generate Char events as well as - // RawKeyDown events, even if the latter triggered an accelerator. In these - // cases, we discard the Char events. - if (event.type == blink::WebInputEvent::Char && ignore_next_char_event_) { - ignore_next_char_event_ = false; - return; - } - // It's necessary to reset this flag, because a RawKeyDown event may not - // always generate a Char event. - ignore_next_char_event_ = false; - - if (event.type == blink::WebInputEvent::RawKeyDown) { - ui::Accelerator accelerator( - static_cast<ui::KeyboardCode>(event.windowsKeyCode), - content::GetModifiersFromNativeWebKeyboardEvent(event)); - - // This is tricky: we want to set ignore_next_char_event_ if - // ProcessAccelerator returns true. But ProcessAccelerator might delete - // |this| if the accelerator is a "close tab" one. So we speculatively - // set the flag and fix it if no event was handled. - ignore_next_char_event_ = true; - - if (focus_manager->ProcessAccelerator(accelerator)) { - return; - } - - // ProcessAccelerator didn't handle the accelerator, so we know both - // that |this| is still valid, and that we didn't want to set the flag. - ignore_next_char_event_ = false; - } - - // Any unhandled keyboard/character messages should be defproced. - // This allows stuff like F10, etc to work correctly. - if (!event.os_event) - return; - const MSG& message(event.os_event->native_event()); - DefWindowProc(message.hwnd, message.message, message.wParam, message.lParam); -} - -} // namespace views
diff --git a/ui/views/controls/webview/web_dialog_view.cc b/ui/views/controls/webview/web_dialog_view.cc deleted file mode 100644 index ffb5cba..0000000 --- a/ui/views/controls/webview/web_dialog_view.cc +++ /dev/null
@@ -1,351 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/webview/web_dialog_view.h" - -#include <vector> - -#include "base/strings/utf_string_conversions.h" -#include "content/public/browser/browser_context.h" -#include "content/public/browser/native_web_keyboard_event.h" -#include "content/public/browser/notification_details.h" -#include "content/public/browser/notification_source.h" -#include "content/public/browser/notification_types.h" -#include "content/public/browser/render_frame_host.h" -#include "content/public/browser/web_contents.h" -#include "ui/events/event.h" -#include "ui/events/keycodes/keyboard_codes.h" -#include "ui/views/controls/webview/webview.h" -#include "ui/views/layout/fill_layout.h" -#include "ui/views/widget/native_widget_private.h" -#include "ui/views/widget/root_view.h" -#include "ui/views/widget/widget.h" -#include "ui/web_dialogs/web_dialog_delegate.h" -#include "ui/web_dialogs/web_dialog_ui.h" - -using content::NativeWebKeyboardEvent; -using content::WebContents; -using content::WebUIMessageHandler; -using ui::WebDialogDelegate; -using ui::WebDialogUI; -using ui::WebDialogWebContentsDelegate; - -namespace views { - -//////////////////////////////////////////////////////////////////////////////// -// WebDialogView, public: - -WebDialogView::WebDialogView( - content::BrowserContext* context, - WebDialogDelegate* delegate, - WebContentsHandler* handler) - : ClientView(NULL, NULL), - WebDialogWebContentsDelegate(context, handler), - delegate_(delegate), - web_view_(new views::WebView(context)), - is_attempting_close_dialog_(false), - before_unload_fired_(false), - closed_via_webui_(false), - close_contents_called_(false) { - web_view_->set_allow_accelerators(true); - AddChildView(web_view_); - set_contents_view(web_view_); - SetLayoutManager(new views::FillLayout); - // Pressing the ESC key will close the dialog. - AddAccelerator(ui::Accelerator(ui::VKEY_ESCAPE, ui::EF_NONE)); -} - -WebDialogView::~WebDialogView() { -} - -content::WebContents* WebDialogView::web_contents() { - return web_view_->web_contents(); -} - -//////////////////////////////////////////////////////////////////////////////// -// WebDialogView, views::View implementation: - -gfx::Size WebDialogView::GetPreferredSize() const { - gfx::Size out; - if (delegate_) - delegate_->GetDialogSize(&out); - return out; -} - -gfx::Size WebDialogView::GetMinimumSize() const { - gfx::Size out; - if (delegate_) - delegate_->GetMinimumDialogSize(&out); - return out; -} - -bool WebDialogView::AcceleratorPressed(const ui::Accelerator& accelerator) { - // Pressing ESC closes the dialog. - DCHECK_EQ(ui::VKEY_ESCAPE, accelerator.key_code()); - if (GetWidget()) - GetWidget()->Close(); - return true; -} - -void WebDialogView::ViewHierarchyChanged( - const ViewHierarchyChangedDetails& details) { - if (details.is_add && GetWidget()) - InitDialog(); -} - -bool WebDialogView::CanClose() { - // Don't close UI if |delegate_| does not allow users to close it by - // clicking on "x" button or pressing Esc shortcut key on hosting dialog. - if (!delegate_->CanCloseDialog() && !close_contents_called_) - return false; - - // If CloseContents() is called before CanClose(), which is called by - // RenderViewHostImpl::ClosePageIgnoringUnloadEvents, it indicates - // beforeunload event should not be fired during closing. - if ((is_attempting_close_dialog_ && before_unload_fired_) || - close_contents_called_) { - is_attempting_close_dialog_ = false; - before_unload_fired_ = false; - return true; - } - - if (!is_attempting_close_dialog_) { - // Fire beforeunload event when user attempts to close the dialog. - is_attempting_close_dialog_ = true; - web_view_->web_contents()->DispatchBeforeUnload(false); - } - return false; -} - -//////////////////////////////////////////////////////////////////////////////// -// WebDialogView, views::WidgetDelegate implementation: - -bool WebDialogView::CanResize() const { - if (delegate_) - return delegate_->CanResizeDialog(); - return true; -} - -ui::ModalType WebDialogView::GetModalType() const { - return GetDialogModalType(); -} - -base::string16 WebDialogView::GetWindowTitle() const { - if (delegate_) - return delegate_->GetDialogTitle(); - return base::string16(); -} - -std::string WebDialogView::GetWindowName() const { - if (delegate_) - return delegate_->GetDialogName(); - return std::string(); -} - -void WebDialogView::WindowClosing() { - // If we still have a delegate that means we haven't notified it of the - // dialog closing. This happens if the user clicks the Close button on the - // dialog. - if (delegate_) - OnDialogClosed(""); -} - -views::View* WebDialogView::GetContentsView() { - return this; -} - -views::ClientView* WebDialogView::CreateClientView(views::Widget* widget) { - return this; -} - -views::View* WebDialogView::GetInitiallyFocusedView() { - return web_view_; -} - -bool WebDialogView::ShouldShowWindowTitle() const { - return ShouldShowDialogTitle(); -} - -views::Widget* WebDialogView::GetWidget() { - return View::GetWidget(); -} - -const views::Widget* WebDialogView::GetWidget() const { - return View::GetWidget(); -} - -//////////////////////////////////////////////////////////////////////////////// -// WebDialogDelegate implementation: - -ui::ModalType WebDialogView::GetDialogModalType() const { - if (delegate_) - return delegate_->GetDialogModalType(); - return ui::MODAL_TYPE_NONE; -} - -base::string16 WebDialogView::GetDialogTitle() const { - return GetWindowTitle(); -} - -GURL WebDialogView::GetDialogContentURL() const { - if (delegate_) - return delegate_->GetDialogContentURL(); - return GURL(); -} - -void WebDialogView::GetWebUIMessageHandlers( - std::vector<WebUIMessageHandler*>* handlers) const { - if (delegate_) - delegate_->GetWebUIMessageHandlers(handlers); -} - -void WebDialogView::GetDialogSize(gfx::Size* size) const { - if (delegate_) - delegate_->GetDialogSize(size); -} - -void WebDialogView::GetMinimumDialogSize(gfx::Size* size) const { - if (delegate_) - delegate_->GetMinimumDialogSize(size); -} - -std::string WebDialogView::GetDialogArgs() const { - if (delegate_) - return delegate_->GetDialogArgs(); - return std::string(); -} - -void WebDialogView::OnDialogShown(content::WebUI* webui, - content::RenderViewHost* render_view_host) { - if (delegate_) - delegate_->OnDialogShown(webui, render_view_host); -} - -void WebDialogView::OnDialogClosed(const std::string& json_retval) { - Detach(); - if (delegate_) { - // Store the dialog content area size. - delegate_->StoreDialogSize(GetContentsBounds().size()); - } - - if (GetWidget()) - GetWidget()->Close(); - - if (delegate_) { - delegate_->OnDialogClosed(json_retval); - delegate_ = NULL; // We will not communicate further with the delegate. - } -} - -void WebDialogView::OnDialogCloseFromWebUI(const std::string& json_retval) { - closed_via_webui_ = true; - dialog_close_retval_ = json_retval; - if (GetWidget()) - GetWidget()->Close(); -} - -void WebDialogView::OnCloseContents(WebContents* source, - bool* out_close_dialog) { - if (delegate_) - delegate_->OnCloseContents(source, out_close_dialog); -} - -bool WebDialogView::ShouldShowDialogTitle() const { - if (delegate_) - return delegate_->ShouldShowDialogTitle(); - return true; -} - -bool WebDialogView::HandleContextMenu( - const content::ContextMenuParams& params) { - if (delegate_) - return delegate_->HandleContextMenu(params); - return WebDialogWebContentsDelegate::HandleContextMenu(params); -} - -//////////////////////////////////////////////////////////////////////////////// -// content::WebContentsDelegate implementation: - -void WebDialogView::MoveContents(WebContents* source, const gfx::Rect& pos) { - // The contained web page wishes to resize itself. We let it do this because - // if it's a dialog we know about, we trust it not to be mean to the user. - GetWidget()->SetBounds(pos); -} - -// A simplified version of BrowserView::HandleKeyboardEvent(). -// We don't handle global keyboard shortcuts here, but that's fine since -// they're all browser-specific. (This may change in the future.) -void WebDialogView::HandleKeyboardEvent(content::WebContents* source, - const NativeWebKeyboardEvent& event) { - if (!event.os_event) - return; - - GetWidget()->native_widget_private()->RepostNativeEvent(event.os_event); -} - -void WebDialogView::CloseContents(WebContents* source) { - close_contents_called_ = true; - bool close_dialog = false; - OnCloseContents(source, &close_dialog); - if (close_dialog) - OnDialogClosed(closed_via_webui_ ? dialog_close_retval_ : std::string()); -} - -content::WebContents* WebDialogView::OpenURLFromTab( - content::WebContents* source, - const content::OpenURLParams& params) { - content::WebContents* new_contents = NULL; - if (delegate_ && - delegate_->HandleOpenURLFromTab(source, params, &new_contents)) { - return new_contents; - } - return WebDialogWebContentsDelegate::OpenURLFromTab(source, params); -} - -void WebDialogView::AddNewContents(content::WebContents* source, - content::WebContents* new_contents, - WindowOpenDisposition disposition, - const gfx::Rect& initial_pos, - bool user_gesture, - bool* was_blocked) { - if (delegate_ && delegate_->HandleAddNewContents( - source, new_contents, disposition, initial_pos, user_gesture)) { - return; - } - WebDialogWebContentsDelegate::AddNewContents( - source, new_contents, disposition, initial_pos, user_gesture, - was_blocked); -} - -void WebDialogView::LoadingStateChanged(content::WebContents* source, - bool to_different_document) { - if (delegate_) - delegate_->OnLoadingStateChanged(source); -} - -void WebDialogView::BeforeUnloadFired(content::WebContents* tab, - bool proceed, - bool* proceed_to_fire_unload) { - before_unload_fired_ = true; - *proceed_to_fire_unload = proceed; -} - -//////////////////////////////////////////////////////////////////////////////// -// WebDialogView, private: - -void WebDialogView::InitDialog() { - content::WebContents* web_contents = web_view_->GetWebContents(); - if (web_contents->GetDelegate() == this) - return; - - web_contents->SetDelegate(this); - - // Set the delegate. This must be done before loading the page. See - // the comment above WebDialogUI in its header file for why. - WebDialogUI::SetDelegate(web_contents, this); - - web_view_->LoadInitialURL(GetDialogContentURL()); -} - -} // namespace views
diff --git a/ui/views/controls/webview/web_dialog_view.h b/ui/views/controls/webview/web_dialog_view.h deleted file mode 100644 index 40d7616..0000000 --- a/ui/views/controls/webview/web_dialog_view.h +++ /dev/null
@@ -1,156 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_WEBVIEW_WEB_DIALOG_VIEW_H_ -#define UI_VIEWS_CONTROLS_WEBVIEW_WEB_DIALOG_VIEW_H_ - -#include <string> -#include <vector> - -#include "base/gtest_prod_util.h" -#include "base/memory/scoped_ptr.h" -#include "ui/gfx/size.h" -#include "ui/views/controls/webview/webview_export.h" -#include "ui/views/widget/widget_delegate.h" -#include "ui/views/window/client_view.h" -#include "ui/web_dialogs/web_dialog_delegate.h" -#include "ui/web_dialogs/web_dialog_web_contents_delegate.h" - -namespace content { -class BrowserContext; -} - -namespace views { -class WebView; - -//////////////////////////////////////////////////////////////////////////////// -// -// WebDialogView is a view used to display an web dialog to the user. The -// content of the dialogs is determined by the delegate -// (ui::WebDialogDelegate), but is basically a file URL along with a -// JSON input string. The HTML is supposed to show a UI to the user and is -// expected to send back a JSON file as a return value. -// -//////////////////////////////////////////////////////////////////////////////// -// -// TODO(akalin): Make WebDialogView contain an WebDialogWebContentsDelegate -// instead of inheriting from it to avoid violating the "no multiple -// inheritance" rule. -class WEBVIEW_EXPORT WebDialogView : public views::ClientView, - public ui::WebDialogWebContentsDelegate, - public ui::WebDialogDelegate, - public views::WidgetDelegate { - public: - // |handler| must not be NULL and this class takes the ownership. - WebDialogView(content::BrowserContext* context, - ui::WebDialogDelegate* delegate, - WebContentsHandler* handler); - virtual ~WebDialogView(); - - // For testing. - content::WebContents* web_contents(); - - // Overridden from views::ClientView: - virtual gfx::Size GetPreferredSize() const override; - virtual gfx::Size GetMinimumSize() const override; - virtual bool AcceleratorPressed(const ui::Accelerator& accelerator) - override; - virtual void ViewHierarchyChanged( - const ViewHierarchyChangedDetails& details) override; - virtual bool CanClose() override; - - // Overridden from views::WidgetDelegate: - virtual bool CanResize() const override; - virtual ui::ModalType GetModalType() const override; - virtual base::string16 GetWindowTitle() const override; - virtual std::string GetWindowName() const override; - virtual void WindowClosing() override; - virtual views::View* GetContentsView() override; - virtual ClientView* CreateClientView(views::Widget* widget) override; - virtual views::View* GetInitiallyFocusedView() override; - virtual bool ShouldShowWindowTitle() const override; - virtual views::Widget* GetWidget() override; - virtual const views::Widget* GetWidget() const override; - - // Overridden from ui::WebDialogDelegate: - virtual ui::ModalType GetDialogModalType() const override; - virtual base::string16 GetDialogTitle() const override; - virtual GURL GetDialogContentURL() const override; - virtual void GetWebUIMessageHandlers( - std::vector<content::WebUIMessageHandler*>* handlers) const override; - virtual void GetDialogSize(gfx::Size* size) const override; - virtual void GetMinimumDialogSize(gfx::Size* size) const override; - virtual std::string GetDialogArgs() const override; - virtual void OnDialogShown( - content::WebUI* webui, - content::RenderViewHost* render_view_host) override; - virtual void OnDialogClosed(const std::string& json_retval) override; - virtual void OnDialogCloseFromWebUI( - const std::string& json_retval) override; - virtual void OnCloseContents(content::WebContents* source, - bool* out_close_dialog) override; - virtual bool ShouldShowDialogTitle() const override; - virtual bool HandleContextMenu( - const content::ContextMenuParams& params) override; - - // Overridden from content::WebContentsDelegate: - virtual void MoveContents(content::WebContents* source, - const gfx::Rect& pos) override; - virtual void HandleKeyboardEvent( - content::WebContents* source, - const content::NativeWebKeyboardEvent& event) override; - virtual void CloseContents(content::WebContents* source) override; - virtual content::WebContents* OpenURLFromTab( - content::WebContents* source, - const content::OpenURLParams& params) override; - virtual void AddNewContents(content::WebContents* source, - content::WebContents* new_contents, - WindowOpenDisposition disposition, - const gfx::Rect& initial_pos, - bool user_gesture, - bool* was_blocked) override; - virtual void LoadingStateChanged(content::WebContents* source, - bool to_different_document) override; - virtual void BeforeUnloadFired(content::WebContents* tab, - bool proceed, - bool* proceed_to_fire_unload) override; - - private: - FRIEND_TEST_ALL_PREFIXES(WebDialogBrowserTest, WebContentRendered); - - // Initializes the contents of the dialog. - void InitDialog(); - - // This view is a delegate to the HTML content since it needs to get notified - // about when the dialog is closing. For all other actions (besides dialog - // closing) we delegate to the creator of this view, which we keep track of - // using this variable. - ui::WebDialogDelegate* delegate_; - - views::WebView* web_view_; - - // Whether user is attempting to close the dialog and we are processing - // beforeunload event. - bool is_attempting_close_dialog_; - - // Whether beforeunload event has been fired and we have finished processing - // beforeunload event. - bool before_unload_fired_; - - // Whether the dialog is closed from WebUI in response to a "dialogClose" - // message. - bool closed_via_webui_; - - // A json string returned to WebUI from a "dialogClose" message. - std::string dialog_close_retval_; - - // Whether CloseContents() has been called. - bool close_contents_called_; - - DISALLOW_COPY_AND_ASSIGN(WebDialogView); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_WEBVIEW_WEB_DIALOG_VIEW_H_
diff --git a/ui/views/controls/webview/webview.cc b/ui/views/controls/webview/webview.cc deleted file mode 100644 index f17c534..0000000 --- a/ui/views/controls/webview/webview.cc +++ /dev/null
@@ -1,375 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/webview/webview.h" - -#include "content/public/browser/browser_accessibility_state.h" -#include "content/public/browser/browser_context.h" -#include "content/public/browser/navigation_controller.h" -#include "content/public/browser/render_view_host.h" -#include "content/public/browser/render_widget_host_view.h" -#include "content/public/browser/web_contents.h" -#include "ipc/ipc_message.h" -#include "ui/accessibility/ax_enums.h" -#include "ui/accessibility/ax_view_state.h" -#include "ui/base/ui_base_switches_util.h" -#include "ui/events/event.h" -#include "ui/views/accessibility/native_view_accessibility.h" -#include "ui/views/controls/native/native_view_host.h" -#include "ui/views/focus/focus_manager.h" -#include "ui/views/views_delegate.h" - -namespace views { - -// static -const char WebView::kViewClassName[] = "WebView"; - -//////////////////////////////////////////////////////////////////////////////// -// WebView, public: - -WebView::WebView(content::BrowserContext* browser_context) - : holder_(new NativeViewHost()), - embed_fullscreen_widget_mode_enabled_(false), - is_embedding_fullscreen_widget_(false), - browser_context_(browser_context), - allow_accelerators_(false) { - AddChildView(holder_); // Takes ownership of |holder_|. - NativeViewAccessibility::RegisterWebView(this); -} - -WebView::~WebView() { - SetWebContents(NULL); // Make sure all necessary tear-down takes place. - NativeViewAccessibility::UnregisterWebView(this); -} - -content::WebContents* WebView::GetWebContents() { - if (!web_contents()) { - wc_owner_.reset(CreateWebContents(browser_context_)); - wc_owner_->SetDelegate(this); - SetWebContents(wc_owner_.get()); - } - return web_contents(); -} - -void WebView::SetWebContents(content::WebContents* replacement) { - if (replacement == web_contents()) - return; - DetachWebContents(); - WebContentsObserver::Observe(replacement); - // web_contents() now returns |replacement| from here onwards. - SetFocusable(!!web_contents()); - if (wc_owner_ != replacement) - wc_owner_.reset(); - if (embed_fullscreen_widget_mode_enabled_) { - is_embedding_fullscreen_widget_ = - web_contents() && web_contents()->GetFullscreenRenderWidgetHostView(); - } else { - DCHECK(!is_embedding_fullscreen_widget_); - } - AttachWebContents(); - NotifyMaybeTextInputClientChanged(); -} - -void WebView::SetEmbedFullscreenWidgetMode(bool enable) { - DCHECK(!web_contents()) - << "Cannot change mode while a WebContents is attached."; - embed_fullscreen_widget_mode_enabled_ = enable; -} - -void WebView::LoadInitialURL(const GURL& url) { - GetWebContents()->GetController().LoadURL( - url, content::Referrer(), ui::PAGE_TRANSITION_AUTO_TOPLEVEL, - std::string()); -} - -void WebView::SetFastResize(bool fast_resize) { - holder_->set_fast_resize(fast_resize); -} - -void WebView::OnWebContentsFocused(content::WebContents* web_contents) { - FocusManager* focus_manager = GetFocusManager(); - if (focus_manager) - focus_manager->SetFocusedView(this); -} - -void WebView::SetPreferredSize(const gfx::Size& preferred_size) { - preferred_size_ = preferred_size; - PreferredSizeChanged(); -} - -//////////////////////////////////////////////////////////////////////////////// -// WebView, View overrides: - -const char* WebView::GetClassName() const { - return kViewClassName; -} - -ui::TextInputClient* WebView::GetTextInputClient() { - // This function delegates the text input handling to the underlying - // content::RenderWidgetHostView. So when the underlying RWHV is destroyed or - // replaced with another one, we have to notify the FocusManager through - // FocusManager::OnTextInputClientChanged() that the focused TextInputClient - // needs to be updated. - if (switches::IsTextInputFocusManagerEnabled() && - web_contents() && !web_contents()->IsBeingDestroyed()) { - content::RenderWidgetHostView* host_view = - is_embedding_fullscreen_widget_ ? - web_contents()->GetFullscreenRenderWidgetHostView() : - web_contents()->GetRenderWidgetHostView(); - if (host_view) - return host_view->GetTextInputClient(); - } - return NULL; -} - -scoped_ptr<content::WebContents> WebView::SwapWebContents( - scoped_ptr<content::WebContents> new_web_contents) { - if (wc_owner_) - wc_owner_->SetDelegate(NULL); - scoped_ptr<content::WebContents> old_web_contents(wc_owner_.Pass()); - wc_owner_ = new_web_contents.Pass(); - if (wc_owner_) - wc_owner_->SetDelegate(this); - SetWebContents(wc_owner_.get()); - return old_web_contents.Pass(); -} - -void WebView::OnBoundsChanged(const gfx::Rect& previous_bounds) { - // In most cases, the holder is simply sized to fill this WebView's bounds. - // Only WebContentses that are in fullscreen mode and being screen-captured - // will engage the special layout/sizing behavior. - gfx::Rect holder_bounds(bounds().size()); - if (!embed_fullscreen_widget_mode_enabled_ || - !web_contents() || - web_contents()->GetCapturerCount() == 0 || - web_contents()->GetPreferredSize().IsEmpty() || - !(is_embedding_fullscreen_widget_ || - (web_contents()->GetDelegate() && - web_contents()->GetDelegate()-> - IsFullscreenForTabOrPending(web_contents())))) { - holder_->SetBoundsRect(holder_bounds); - return; - } - - // Size the holder to the capture video resolution and center it. If this - // WebView is not large enough to contain the holder at the preferred size, - // scale down to fit (preserving aspect ratio). - const gfx::Size capture_size = web_contents()->GetPreferredSize(); - if (capture_size.width() <= holder_bounds.width() && - capture_size.height() <= holder_bounds.height()) { - // No scaling, just centering. - holder_bounds.ClampToCenteredSize(capture_size); - } else { - // Scale down, preserving aspect ratio, and center. - // TODO(miu): This is basically media::ComputeLetterboxRegion(), and it - // looks like others have written this code elsewhere. Let's considate - // into a shared function ui/gfx/geometry or around there. - const int64 x = static_cast<int64>(capture_size.width()) * - holder_bounds.height(); - const int64 y = static_cast<int64>(capture_size.height()) * - holder_bounds.width(); - if (y < x) { - holder_bounds.ClampToCenteredSize(gfx::Size( - holder_bounds.width(), static_cast<int>(y / capture_size.width()))); - } else { - holder_bounds.ClampToCenteredSize(gfx::Size( - static_cast<int>(x / capture_size.height()), holder_bounds.height())); - } - } - - holder_->SetBoundsRect(holder_bounds); -} - -void WebView::ViewHierarchyChanged( - const ViewHierarchyChangedDetails& details) { - if (details.is_add) - AttachWebContents(); -} - -bool WebView::SkipDefaultKeyEventProcessing(const ui::KeyEvent& event) { - if (allow_accelerators_) - return FocusManager::IsTabTraversalKeyEvent(event); - - // Don't look-up accelerators or tab-traversal if we are showing a non-crashed - // TabContents. - // We'll first give the page a chance to process the key events. If it does - // not process them, they'll be returned to us and we'll treat them as - // accelerators then. - return web_contents() && !web_contents()->IsCrashed(); -} - -void WebView::OnFocus() { - if (web_contents()) - web_contents()->Focus(); -} - -void WebView::AboutToRequestFocusFromTabTraversal(bool reverse) { - if (web_contents()) - web_contents()->FocusThroughTabTraversal(reverse); -} - -void WebView::GetAccessibleState(ui::AXViewState* state) { - state->role = ui::AX_ROLE_GROUP; -} - -gfx::NativeViewAccessible WebView::GetNativeViewAccessible() { - if (web_contents()) { - content::RenderWidgetHostView* host_view = - web_contents()->GetRenderWidgetHostView(); - if (host_view) - return host_view->GetNativeViewAccessible(); - } - return View::GetNativeViewAccessible(); -} - -gfx::Size WebView::GetPreferredSize() const { - if (preferred_size_ == gfx::Size()) - return View::GetPreferredSize(); - else - return preferred_size_; -} - -//////////////////////////////////////////////////////////////////////////////// -// WebView, content::WebContentsDelegate implementation: - -void WebView::WebContentsFocused(content::WebContents* web_contents) { - DCHECK(wc_owner_.get()); - // The WebView is only the delegate of WebContentses it creates itself. - OnWebContentsFocused(wc_owner_.get()); -} - -bool WebView::EmbedsFullscreenWidget() const { - DCHECK(wc_owner_.get()); - return embed_fullscreen_widget_mode_enabled_; -} - -//////////////////////////////////////////////////////////////////////////////// -// WebView, content::WebContentsObserver implementation: - -void WebView::RenderViewDeleted(content::RenderViewHost* render_view_host) { - NotifyMaybeTextInputClientChanged(); -} - -void WebView::RenderProcessGone(base::TerminationStatus status) { - NotifyMaybeTextInputClientChanged(); -} - -void WebView::RenderViewHostChanged(content::RenderViewHost* old_host, - content::RenderViewHost* new_host) { - FocusManager* const focus_manager = GetFocusManager(); - if (focus_manager && focus_manager->GetFocusedView() == this) - OnFocus(); - NotifyMaybeTextInputClientChanged(); -} - -void WebView::DidShowFullscreenWidget(int routing_id) { - if (embed_fullscreen_widget_mode_enabled_) - ReattachForFullscreenChange(true); -} - -void WebView::DidDestroyFullscreenWidget(int routing_id) { - if (embed_fullscreen_widget_mode_enabled_) - ReattachForFullscreenChange(false); -} - -void WebView::DidToggleFullscreenModeForTab(bool entered_fullscreen) { - if (embed_fullscreen_widget_mode_enabled_) - ReattachForFullscreenChange(entered_fullscreen); -} - -void WebView::DidAttachInterstitialPage() { - NotifyMaybeTextInputClientChanged(); -} - -void WebView::DidDetachInterstitialPage() { - NotifyMaybeTextInputClientChanged(); -} - -//////////////////////////////////////////////////////////////////////////////// -// WebView, private: - -void WebView::AttachWebContents() { - // Prevents attachment if the WebView isn't already in a Widget, or it's - // already attached. - if (!GetWidget() || !web_contents()) - return; - - const gfx::NativeView view_to_attach = is_embedding_fullscreen_widget_ ? - web_contents()->GetFullscreenRenderWidgetHostView()->GetNativeView() : - web_contents()->GetNativeView(); - OnBoundsChanged(bounds()); - if (holder_->native_view() == view_to_attach) - return; - - holder_->Attach(view_to_attach); - - // The view will not be focused automatically when it is attached, so we need - // to pass on focus to it if the FocusManager thinks the view is focused. Note - // that not every Widget has a focus manager. - FocusManager* const focus_manager = GetFocusManager(); - if (focus_manager && focus_manager->GetFocusedView() == this) - OnFocus(); - -#if defined(OS_WIN) - if (!is_embedding_fullscreen_widget_) { - web_contents()->SetParentNativeViewAccessible( - parent()->GetNativeViewAccessible()); - } -#endif -} - -void WebView::DetachWebContents() { - if (web_contents()) { - holder_->Detach(); -#if defined(OS_WIN) - if (!is_embedding_fullscreen_widget_) - web_contents()->SetParentNativeViewAccessible(NULL); -#endif - } -} - -void WebView::ReattachForFullscreenChange(bool enter_fullscreen) { - DCHECK(embed_fullscreen_widget_mode_enabled_); - const bool web_contents_has_separate_fs_widget = - web_contents() && web_contents()->GetFullscreenRenderWidgetHostView(); - if (is_embedding_fullscreen_widget_ || web_contents_has_separate_fs_widget) { - // Shutting down or starting up the embedding of the separate fullscreen - // widget. Need to detach and re-attach to a different native view. - DetachWebContents(); - is_embedding_fullscreen_widget_ = - enter_fullscreen && web_contents_has_separate_fs_widget; - AttachWebContents(); - } else { - // Entering or exiting "non-Flash" fullscreen mode, where the native view is - // the same. So, do not change attachment. - OnBoundsChanged(bounds()); - } - NotifyMaybeTextInputClientChanged(); -} - -void WebView::NotifyMaybeTextInputClientChanged() { - // Update the TextInputClient as needed; see GetTextInputClient(). - FocusManager* const focus_manager = GetFocusManager(); - if (focus_manager) - focus_manager->OnTextInputClientChanged(this); -} - -content::WebContents* WebView::CreateWebContents( - content::BrowserContext* browser_context) { - content::WebContents* contents = NULL; - if (ViewsDelegate::views_delegate) { - contents = ViewsDelegate::views_delegate->CreateWebContents( - browser_context, NULL); - } - - if (!contents) { - content::WebContents::CreateParams create_params( - browser_context, NULL); - return content::WebContents::Create(create_params); - } - - return contents; -} - -} // namespace views
diff --git a/ui/views/controls/webview/webview.gyp b/ui/views/controls/webview/webview.gyp deleted file mode 100644 index af284b7..0000000 --- a/ui/views/controls/webview/webview.gyp +++ /dev/null
@@ -1,45 +0,0 @@ -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -{ - 'variables': { - 'chromium_code': 1, - }, - 'targets': [ - { - # GN version: //ui/views/controls/webview - 'target_name': 'webview', - 'type': '<(component)', - 'dependencies': [ - '../../../../base/base.gyp:base', - '../../../../base/base.gyp:base_i18n', - '../../../../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', - '../../../../content/content.gyp:content_browser', - '../../../../skia/skia.gyp:skia', - '../../../../url/url.gyp:url_lib', - '../../../base/ui_base.gyp:ui_base', - '../../../events/events.gyp:events', - '../../../gfx/gfx.gyp:gfx', - '../../../gfx/gfx.gyp:gfx_geometry', - '../../../web_dialogs/web_dialogs.gyp:web_dialogs', - '../../views.gyp:views', - ], - 'defines': [ - 'WEBVIEW_IMPLEMENTATION', - ], - 'sources': [ - # Note: file list duplicated in GN build. - 'unhandled_keyboard_event_handler.cc', - 'unhandled_keyboard_event_handler.h', - 'unhandled_keyboard_event_handler_linux.cc', - 'unhandled_keyboard_event_handler_win.cc', - 'web_dialog_view.cc', - 'web_dialog_view.h', - 'webview.cc', - 'webview.h', - 'webview_export.h', - ], - }, - ], -}
diff --git a/ui/views/controls/webview/webview.h b/ui/views/controls/webview/webview.h deleted file mode 100644 index f5fe3c8..0000000 --- a/ui/views/controls/webview/webview.h +++ /dev/null
@@ -1,161 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_WEBVIEW_WEBVIEW_H_ -#define UI_VIEWS_CONTROLS_WEBVIEW_WEBVIEW_H_ - -#include "base/basictypes.h" -#include "base/memory/scoped_ptr.h" -#include "content/public/browser/web_contents_delegate.h" -#include "content/public/browser/web_contents_observer.h" -#include "ui/views/accessibility/native_view_accessibility.h" -#include "ui/views/controls/webview/webview_export.h" -#include "ui/views/view.h" - -namespace views { - -class NativeViewHost; - -// Provides a view of a WebContents instance. WebView can be used standalone, -// creating and displaying an internally-owned WebContents; or within a full -// browser where the browser swaps its own WebContents instances in/out (e.g., -// for browser tabs). -// -// WebView creates and owns a single child view, a NativeViewHost, which will -// hold and display the native view provided by a WebContents. -// -// EmbedFullscreenWidgetMode: When enabled, WebView will observe for WebContents -// fullscreen changes and automatically swap the normal native view with the -// fullscreen native view (if different). In addition, if the WebContents is -// being screen-captured, the view will be centered within WebView, sized to -// the aspect ratio of the capture video resolution, and scaling will be avoided -// whenever possible. -class WEBVIEW_EXPORT WebView : public View, - public content::WebContentsDelegate, - public content::WebContentsObserver { - public: - static const char kViewClassName[]; - - explicit WebView(content::BrowserContext* browser_context); - ~WebView() override; - - // This creates a WebContents if none is yet associated with this WebView. The - // WebView owns this implicitly created WebContents. - content::WebContents* GetWebContents(); - - // WebView does not assume ownership of WebContents set via this method, only - // those it implicitly creates via GetWebContents() above. - void SetWebContents(content::WebContents* web_contents); - - // If |mode| is true, WebView will register itself with WebContents as a - // WebContentsObserver, monitor for the showing/destruction of fullscreen - // render widgets, and alter its child view hierarchy to embed the fullscreen - // widget or restore the normal WebContentsView. - void SetEmbedFullscreenWidgetMode(bool mode); - - content::BrowserContext* browser_context() { return browser_context_; } - - // Loads the initial URL to display in the attached WebContents. Creates the - // WebContents if none is attached yet. Note that this is intended as a - // convenience for loading the initial URL, and so URLs are navigated with - // PAGE_TRANSITION_AUTO_TOPLEVEL, so this is not intended as a general purpose - // navigation method - use WebContents' API directly. - void LoadInitialURL(const GURL& url); - - // Controls how the attached WebContents is resized. - // false = WebContents' views' bounds are updated continuously as the - // WebView's bounds change (default). - // true = WebContents' views' position is updated continuously but its size - // is not (which may result in some clipping or under-painting) until - // a continuous size operation completes. This allows for smoother - // resizing performance during interactive resizes and animations. - void SetFastResize(bool fast_resize); - - // Called when the WebContents is focused. - // TODO(beng): This view should become a WebContentsViewObserver when a - // WebContents is attached, and not rely on the delegate to - // forward this notification. - void OnWebContentsFocused(content::WebContents* web_contents); - - // When used to host UI, we need to explicitly allow accelerators to be - // processed. Default is false. - void set_allow_accelerators(bool allow_accelerators) { - allow_accelerators_ = allow_accelerators; - } - - // Sets the preferred size. If empty, View's implementation of - // GetPreferredSize() is used. - void SetPreferredSize(const gfx::Size& preferred_size); - - // Overridden from View: - const char* GetClassName() const override; - ui::TextInputClient* GetTextInputClient() override; - - protected: - // Swaps the owned WebContents |wc_owner_| with |new_web_contents|. Returns - // the previously owned WebContents. - scoped_ptr<content::WebContents> SwapWebContents( - scoped_ptr<content::WebContents> new_web_contents); - - // Overridden from View: - void OnBoundsChanged(const gfx::Rect& previous_bounds) override; - void ViewHierarchyChanged( - const ViewHierarchyChangedDetails& details) override; - bool SkipDefaultKeyEventProcessing(const ui::KeyEvent& event) override; - void OnFocus() override; - void AboutToRequestFocusFromTabTraversal(bool reverse) override; - void GetAccessibleState(ui::AXViewState* state) override; - gfx::NativeViewAccessible GetNativeViewAccessible() override; - gfx::Size GetPreferredSize() const override; - - // Overridden from content::WebContentsDelegate: - void WebContentsFocused(content::WebContents* web_contents) override; - bool EmbedsFullscreenWidget() const override; - - // Overridden from content::WebContentsObserver: - void RenderViewDeleted(content::RenderViewHost* render_view_host) override; - void RenderProcessGone(base::TerminationStatus status) override; - void RenderViewHostChanged(content::RenderViewHost* old_host, - content::RenderViewHost* new_host) override; - void DidShowFullscreenWidget(int routing_id) override; - void DidDestroyFullscreenWidget(int routing_id) override; - void DidToggleFullscreenModeForTab(bool entered_fullscreen) override; - void DidAttachInterstitialPage() override; - void DidDetachInterstitialPage() override; - // Workaround for MSVC++ linker bug/feature that requires - // instantiation of the inline IPC::Listener methods in all translation units. - void OnChannelConnected(int32 peer_id) override {} - void OnChannelError() override {} - void OnBadMessageReceived(const IPC::Message& message) override {} - - private: - void AttachWebContents(); - void DetachWebContents(); - void ReattachForFullscreenChange(bool enter_fullscreen); - void NotifyMaybeTextInputClientChanged(); - - // Create a regular or test web contents (based on whether we're running - // in a unit test or not). - content::WebContents* CreateWebContents( - content::BrowserContext* browser_context); - - NativeViewHost* const holder_; - // Non-NULL if |web_contents()| was created and is owned by this WebView. - scoped_ptr<content::WebContents> wc_owner_; - // When true, WebView auto-embeds fullscreen widgets as a child view. - bool embed_fullscreen_widget_mode_enabled_; - // Set to true while WebView is embedding a fullscreen widget view as a child - // view instead of the normal WebContentsView render view. Note: This will be - // false in the case of non-Flash fullscreen. - bool is_embedding_fullscreen_widget_; - content::BrowserContext* browser_context_; - bool allow_accelerators_; - gfx::Size preferred_size_; - - DISALLOW_COPY_AND_ASSIGN(WebView); -}; - -} // namespace views - -#endif // UI_VIEWS_CONTROLS_WEBVIEW_WEBVIEW_H_
diff --git a/ui/views/controls/webview/webview_export.h b/ui/views/controls/webview/webview_export.h deleted file mode 100644 index 2b071cc..0000000 --- a/ui/views/controls/webview/webview_export.h +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CONTROLS_WEBVIEW_WEBVIEW_EXPORT_H_ -#define UI_VIEWS_CONTROLS_WEBVIEW_WEBVIEW_EXPORT_H_ - -// Defines WEBVIEW_EXPORT so that functionality implemented by the webview -// module can be exported to consumers. - -#if defined(COMPONENT_BUILD) -#if defined(WIN32) - -#if defined(WEBVIEW_IMPLEMENTATION) -#define WEBVIEW_EXPORT __declspec(dllexport) -#else -#define WEBVIEW_EXPORT __declspec(dllimport) -#endif // defined(WEBVIEW_IMPLEMENTATION) - -#else // defined(WIN32) -#if defined(WEBVIEW_IMPLEMENTATION) -#define WEBVIEW_EXPORT __attribute__((visibility("default"))) -#else -#define WEBVIEW_EXPORT -#endif -#endif - -#else // defined(COMPONENT_BUILD) -#define WEBVIEW_EXPORT -#endif - -#endif // UI_VIEWS_CONTROLS_WEBVIEW_WEBVIEW_EXPORT_H_
diff --git a/ui/views/controls/webview/webview_interactive_uitest.cc b/ui/views/controls/webview/webview_interactive_uitest.cc deleted file mode 100644 index 1ccfc33..0000000 --- a/ui/views/controls/webview/webview_interactive_uitest.cc +++ /dev/null
@@ -1,82 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/webview/webview.h" - -#include "base/command_line.h" -#include "base/memory/scoped_ptr.h" -#include "content/public/browser/web_contents.h" -#include "content/public/test/test_browser_context.h" -#include "content/public/test/test_browser_thread.h" -#include "ui/base/ime/text_input_focus_manager.h" -#include "ui/base/ui_base_switches.h" -#include "ui/gl/gl_surface.h" -#include "ui/views/test/webview_test_helper.h" -#include "ui/views/test/widget_test.h" - -namespace { - -class WebViewInteractiveUiTest : public views::test::WidgetTest { - public: - WebViewInteractiveUiTest() - : ui_thread_(content::BrowserThread::UI, base::MessageLoop::current()) {} - - virtual void SetUp() override { - gfx::GLSurface::InitializeOneOffForTests(); - WidgetTest::SetUp(); - } - - protected: - content::BrowserContext* browser_context() { return &browser_context_; } - - private: - content::TestBrowserContext browser_context_; - views::WebViewTestHelper webview_test_helper_; - content::TestBrowserThread ui_thread_; - - DISALLOW_COPY_AND_ASSIGN(WebViewInteractiveUiTest); -}; - -TEST_F(WebViewInteractiveUiTest, TextInputClientIsUpToDate) { - // WebViewInteractiveUiTest.TextInputClientIsUpToDate needs - // kEnableTextInputFocusManager flag to be enabled. - base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess(); - cmd_line->AppendSwitch(switches::kEnableTextInputFocusManager); - - // Create a top level widget and a webview as its content. - views::Widget* widget = CreateTopLevelFramelessPlatformWidget(); - views::WebView* webview = new views::WebView(browser_context()); - widget->SetContentsView(webview); - widget->Show(); - webview->RequestFocus(); - - ui::TextInputFocusManager* text_input_focus_manager = - ui::TextInputFocusManager::GetInstance(); - const ui::TextInputClient* null_text_input_client = NULL; - EXPECT_EQ(null_text_input_client, webview->GetTextInputClient()); - EXPECT_EQ(text_input_focus_manager->GetFocusedTextInputClient(), - webview->GetTextInputClient()); - - // Case 1: Creates a new WebContents. - webview->GetWebContents(); - webview->RequestFocus(); - ui::TextInputClient* client1 = webview->GetTextInputClient(); - EXPECT_NE(null_text_input_client, client1); - EXPECT_EQ(text_input_focus_manager->GetFocusedTextInputClient(), client1); - - // Case 2: Replaces a WebContents by SetWebContents(). - content::WebContents::CreateParams params(browser_context()); - scoped_ptr<content::WebContents> web_contents( - content::WebContents::Create(params)); - webview->SetWebContents(web_contents.get()); - ui::TextInputClient* client2 = webview->GetTextInputClient(); - EXPECT_NE(null_text_input_client, client2); - EXPECT_EQ(text_input_focus_manager->GetFocusedTextInputClient(), client2); - EXPECT_NE(client1, client2); - - widget->Close(); - RunPendingMessages(); -} - -} // namespace
diff --git a/ui/views/controls/webview/webview_tests.gyp b/ui/views/controls/webview/webview_tests.gyp deleted file mode 100644 index f85385b..0000000 --- a/ui/views/controls/webview/webview_tests.gyp +++ /dev/null
@@ -1,45 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -{ - 'variables': { - 'chromium_code': 1, - }, - 'targets': [ - { - # GN version: //ui/views/controls/webview:test_support - 'target_name': 'webview_test_support', - 'type': 'static_library', - 'dependencies': [ - '../../../../base/base.gyp:base', - '../../../../content/content.gyp:content', - '../../../../content/content_shell_and_tests.gyp:test_support_content', - '../../../../ipc/ipc.gyp:test_support_ipc', - '../../../../skia/skia.gyp:skia', - '../../../../testing/gtest.gyp:gtest', - '../../../base/ui_base.gyp:ui_base', - '../../../events/events.gyp:events', - '../../../gfx/gfx.gyp:gfx', - '../../../gfx/gfx.gyp:gfx_geometry', - '../../views.gyp:views', - '../../views.gyp:views_test_support', - 'webview.gyp:webview', - ], - 'include_dirs': [ - '../../../..', - ], - 'sources': [ - '../../test/webview_test_helper.cc', - '../../test/webview_test_helper.h', - ], - 'conditions': [ - ['use_aura==1', { - 'dependencies': [ - '../../../aura/aura.gyp:aura', - ], - }], - ], - }, - ], -}
diff --git a/ui/views/controls/webview/webview_unittest.cc b/ui/views/controls/webview/webview_unittest.cc deleted file mode 100644 index 93cb915..0000000 --- a/ui/views/controls/webview/webview_unittest.cc +++ /dev/null
@@ -1,231 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/controls/webview/webview.h" - -#include "base/memory/scoped_ptr.h" -#include "content/browser/web_contents/web_contents_impl.h" -#include "content/public/browser/web_contents_observer.h" -#include "content/public/test/test_browser_context.h" -#include "content/public/test/test_browser_thread.h" -#include "content/public/test/web_contents_tester.h" -#include "content/test/test_content_browser_client.h" -#include "ui/aura/window.h" -#include "ui/views/test/test_views_delegate.h" -#include "ui/views/test/widget_test.h" - -namespace { - -// Provides functionality to create a test WebContents. -class WebViewTestViewsDelegate : public views::TestViewsDelegate { - public: - WebViewTestViewsDelegate() {} - virtual ~WebViewTestViewsDelegate() {} - - // Overriden from TestViewsDelegate. - virtual content::WebContents* CreateWebContents( - content::BrowserContext* browser_context, - content::SiteInstance* site_instance) override { - return content::WebContentsTester::CreateTestWebContents(browser_context, - site_instance); - } - - private: - DISALLOW_COPY_AND_ASSIGN(WebViewTestViewsDelegate); -}; - -// Provides functionality to test a WebView. -class WebViewUnitTest : public views::test::WidgetTest { - public: - WebViewUnitTest() - : ui_thread_(content::BrowserThread::UI, base::MessageLoop::current()), - file_blocking_thread_(content::BrowserThread::FILE_USER_BLOCKING, - base::MessageLoop::current()), - io_thread_(content::BrowserThread::IO, base::MessageLoop::current()) {} - - virtual ~WebViewUnitTest() {} - - virtual void SetUp() override { - // The ViewsDelegate is deleted when the ViewsTestBase class is torn down. - WidgetTest::set_views_delegate(new WebViewTestViewsDelegate); - browser_context_.reset(new content::TestBrowserContext); - WidgetTest::SetUp(); - // Set the test content browser client to avoid pulling in needless - // dependencies from content. - SetBrowserClientForTesting(&test_browser_client_); - } - - virtual void TearDown() override { - browser_context_.reset(NULL); - // Flush the message loop to execute pending relase tasks as this would - // upset ASAN and Valgrind. - RunPendingMessages(); - WidgetTest::TearDown(); - } - - protected: - content::BrowserContext* browser_context() { return browser_context_.get(); } - - private: - content::TestBrowserThread ui_thread_; - content::TestBrowserThread file_blocking_thread_; - content::TestBrowserThread io_thread_; - scoped_ptr<content::TestBrowserContext> browser_context_; - scoped_ptr<WebViewTestViewsDelegate> views_delegate_; - content::TestContentBrowserClient test_browser_client_; - - DISALLOW_COPY_AND_ASSIGN(WebViewUnitTest); -}; - -// Provides functionaity to observe events on a WebContents like WasShown/ -// WasHidden/WebContentsDestroyed. -class WebViewTestWebContentsObserver : public content::WebContentsObserver { - public: - WebViewTestWebContentsObserver(content::WebContents* web_contents) - : web_contents_(static_cast<content::WebContentsImpl*>(web_contents)), - was_shown_(false), - shown_count_(0), - hidden_count_(0) { - content::WebContentsObserver::Observe(web_contents); - } - - virtual ~WebViewTestWebContentsObserver() { - if (web_contents_) - content::WebContentsObserver::Observe(NULL); - } - - virtual void WebContentsDestroyed() override { - DCHECK(web_contents_); - content::WebContentsObserver::Observe(NULL); - web_contents_ = NULL; - } - - virtual void WasShown() override { - valid_root_while_shown_ = - web_contents()->GetNativeView()->GetRootWindow() != NULL; - was_shown_ = true; - ++shown_count_; - } - - virtual void WasHidden() override { - was_shown_ = false; - ++hidden_count_; - } - - bool was_shown() const { return was_shown_; } - - int shown_count() const { return shown_count_; } - - int hidden_count() const { return hidden_count_; } - - bool valid_root_while_shown() const { return valid_root_while_shown_; } - - private: - content::WebContentsImpl* web_contents_; - bool was_shown_; - int32 shown_count_; - int32 hidden_count_; - // Set to true if the view containing the webcontents has a valid root window. - bool valid_root_while_shown_; - - DISALLOW_COPY_AND_ASSIGN(WebViewTestWebContentsObserver); -}; - -// Tests that attaching and detaching a WebContents to a WebView makes the -// WebContents visible and hidden respectively. -TEST_F(WebViewUnitTest, TestWebViewAttachDetachWebContents) { - // Create a top level widget and a webview as its content. - views::Widget* parent = CreateTopLevelFramelessPlatformWidget(); - parent->SetBounds(gfx::Rect(0, 10, 100, 100)); - - views::Widget* widget = CreateChildNativeWidgetWithParent(parent); - widget->SetBounds(gfx::Rect(0, 10, 100, 100)); - views::WebView* webview = new views::WebView(browser_context()); - widget->SetContentsView(webview); - parent->Show(); - widget->Show(); - - // Case 1: Create a new WebContents and set it in the webview via - // SetWebContents. This should make the WebContents visible. - content::WebContents::CreateParams params(browser_context()); - scoped_ptr<content::WebContents> web_contents1( - content::WebContents::Create(params)); - WebViewTestWebContentsObserver observer1(web_contents1.get()); - EXPECT_FALSE(observer1.was_shown()); - - webview->SetWebContents(web_contents1.get()); - EXPECT_TRUE(observer1.was_shown()); - EXPECT_TRUE(web_contents1->GetNativeView()->IsVisible()); - EXPECT_EQ(observer1.shown_count(), 1); - EXPECT_EQ(observer1.hidden_count(), 0); - EXPECT_TRUE(observer1.valid_root_while_shown()); - - // Case 2: Create another WebContents and replace the current WebContents - // via SetWebContents(). This should hide the current WebContents and show - // the new one. - content::WebContents::CreateParams params2(browser_context()); - scoped_ptr<content::WebContents> web_contents2( - content::WebContents::Create(params2)); - - WebViewTestWebContentsObserver observer2(web_contents2.get()); - EXPECT_FALSE(observer2.was_shown()); - - // Setting the new WebContents should hide the existing one. - webview->SetWebContents(web_contents2.get()); - EXPECT_FALSE(observer1.was_shown()); - EXPECT_TRUE(observer2.was_shown()); - EXPECT_TRUE(observer2.valid_root_while_shown()); - - // WebContents1 should not get stray show calls when WebContents2 is set. - EXPECT_EQ(observer1.shown_count(), 1); - EXPECT_EQ(observer1.hidden_count(), 1); - EXPECT_EQ(observer2.shown_count(), 1); - EXPECT_EQ(observer2.hidden_count(), 0); - - // Case 3: Test that attaching to a hidden webview does not show the web - // contents. - webview->SetVisible(false); - EXPECT_EQ(1, observer2.hidden_count()); // Now hidden. - - EXPECT_EQ(1, observer1.shown_count()); - webview->SetWebContents(web_contents1.get()); - EXPECT_EQ(1, observer1.shown_count()); - - // Nothing else should change. - EXPECT_EQ(1, observer1.hidden_count()); - EXPECT_EQ(1, observer2.shown_count()); - EXPECT_EQ(1, observer2.hidden_count()); - - // Case 4: Test that making the webview visible when a window has an invisible - // parent does not make the web contents visible. - parent->Hide(); - webview->SetVisible(true); - // TODO(tapted): The following line is wrong, the shown_count() should still - // be 1, until the parent window is made visible on the line after. - EXPECT_EQ(2, observer1.shown_count()); - parent->Show(); - EXPECT_EQ(2, observer1.shown_count()); - parent->Hide(); - EXPECT_EQ(2, observer1.hidden_count()); - - // Case 5: Test that moving from a hidden parent to a visible parent makes the - // web contents visible. - views::Widget* parent2 = CreateTopLevelFramelessPlatformWidget(); - parent2->SetBounds(gfx::Rect(0, 10, 100, 100)); - parent2->Show(); - - EXPECT_EQ(2, observer1.shown_count()); - // Note: that reparenting the windows directly, after the windows have been - // created, e.g., views::Widget::ReparentNativeView(widget, parent2), is not a - // supported use case. Instead, move the WebView over. - parent2->SetContentsView(webview); - EXPECT_EQ(3, observer1.shown_count()); - - widget->Close(); - parent->Close(); - parent2->Close(); - RunPendingMessages(); -} - -} // namespace
diff --git a/ui/views/corewm/DEPS b/ui/views/corewm/DEPS deleted file mode 100644 index a2d52d6..0000000 --- a/ui/views/corewm/DEPS +++ /dev/null
@@ -1,57 +0,0 @@ -# This code should not depend on Views. - -include_rules = [ - "-ui/views", - "+ui/views/corewm", - "+ui/views/views_export.h", -] - -# TODO: temporary, don't add more. -specific_include_rules = { - "tooltip_controller.cc": [ - "+ui/views/widget/tooltip_manager.h", - ], - - "tooltip_aura.cc": [ - "+ui/views/background.h", - "+ui/views/border.h", - "+ui/views/widget/widget.h", - ], - - "desktop_capture_controller_unittest.cc": [ - "+ui/views/test/views_test_base.h", - "+ui/views/view.h", - "+ui/views/widget/desktop_aura/desktop_native_widget_aura.h", - "+ui/views/widget/desktop_aura/desktop_screen_position_client.h", - "+ui/views/widget/root_view.h", - "+ui/views/widget/widget.h", - ], - - "tooltip_controller_unittest.cc": [ - "+ui/views/test/desktop_test_views_delegate.h", - "+ui/views/test/test_views_delegate.h", - "+ui/views/view.h", - "+ui/views/widget/desktop_aura/desktop_native_widget_aura.h", - "+ui/views/widget/desktop_aura/desktop_screen.h", - "+ui/views/widget/tooltip_manager.h", - "+ui/views/widget/widget.h", - ], - - "tooltip_aura.h": [ - "+ui/views/controls/label.h", - "+ui/views/widget/widget_observer.h", - ], - - "tooltip_controller_test_helper.h": [ - "+ui/views/view.h", - ], - - "capture_controller_unittest.cc": [ - "+ui/views/test/views_test_base.h", - "+ui/views/view.h", - "+ui/views/widget/desktop_aura/desktop_native_widget_aura.h", - "+ui/views/widget/desktop_aura/desktop_screen_position_client.h", - "+ui/views/widget/root_view.h", - "+ui/views/widget/widget.h", - ], -}
diff --git a/ui/views/corewm/README.chromium b/ui/views/corewm/README.chromium deleted file mode 100644 index cfb2b6a..0000000 --- a/ui/views/corewm/README.chromium +++ /dev/null
@@ -1,2 +0,0 @@ -This directory contains window-manager code that is shared by Ash and the -Desktop Aura implementation.
diff --git a/ui/views/corewm/capture_controller_unittest.cc b/ui/views/corewm/capture_controller_unittest.cc deleted file mode 100644 index da2ca72..0000000 --- a/ui/views/corewm/capture_controller_unittest.cc +++ /dev/null
@@ -1,168 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/capture_controller.h" - -#include "base/logging.h" -#include "ui/aura/env.h" -#include "ui/aura/test/aura_test_base.h" -#include "ui/aura/test/test_screen.h" -#include "ui/aura/test/test_window_delegate.h" -#include "ui/aura/window.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/events/event.h" -#include "ui/events/event_utils.h" -#include "ui/events/test/event_generator.h" -#include "ui/views/test/views_test_base.h" -#include "ui/views/view.h" -#include "ui/views/widget/root_view.h" -#include "ui/views/widget/widget.h" - -#if !defined(OS_CHROMEOS) -#include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" -#include "ui/views/widget/desktop_aura/desktop_screen_position_client.h" -#endif - -namespace views { - -class CaptureControllerTest : public aura::test::AuraTestBase { - public: - CaptureControllerTest() {} - - virtual void SetUp() override { - AuraTestBase::SetUp(); - capture_controller_.reset(new wm::ScopedCaptureClient(root_window())); - - second_host_.reset(aura::WindowTreeHost::Create(gfx::Rect(0, 0, 800, 600))); - second_host_->InitHost(); - second_host_->window()->Show(); - second_host_->SetBounds(gfx::Rect(800, 600)); - second_capture_controller_.reset( - new wm::ScopedCaptureClient(second_host_->window())); - -#if !defined(OS_CHROMEOS) - desktop_position_client_.reset( - new DesktopScreenPositionClient(root_window())); - - second_desktop_position_client_.reset( - new DesktopScreenPositionClient(second_host_->window())); -#endif - } - - virtual void TearDown() override { - RunAllPendingInMessageLoop(); - -#if !defined(OS_CHROMEOS) - second_desktop_position_client_.reset(); -#endif - second_capture_controller_.reset(); - - // Kill any active compositors before we hit the compositor shutdown paths. - second_host_.reset(); - -#if !defined(OS_CHROMEOS) - desktop_position_client_.reset(); -#endif - capture_controller_.reset(); - - AuraTestBase::TearDown(); - } - - aura::Window* GetCaptureWindow() { - return capture_controller_->capture_client()->GetCaptureWindow(); - } - - aura::Window* GetSecondCaptureWindow() { - return second_capture_controller_->capture_client()->GetCaptureWindow(); - } - - scoped_ptr<wm::ScopedCaptureClient> capture_controller_; - scoped_ptr<aura::WindowTreeHost> second_host_; - scoped_ptr<wm::ScopedCaptureClient> second_capture_controller_; -#if !defined(OS_CHROMEOS) - scoped_ptr<aura::client::ScreenPositionClient> desktop_position_client_; - scoped_ptr<aura::client::ScreenPositionClient> - second_desktop_position_client_; -#endif - - DISALLOW_COPY_AND_ASSIGN(CaptureControllerTest); -}; - -// Makes sure that internal details that are set on mouse down (such as -// mouse_pressed_handler()) are cleared when another root window takes capture. -TEST_F(CaptureControllerTest, ResetMouseEventHandlerOnCapture) { - // Create a window inside the WindowEventDispatcher. - scoped_ptr<aura::Window> w1(CreateNormalWindow(1, root_window(), NULL)); - - // Make a synthesized mouse down event. Ensure that the WindowEventDispatcher - // will dispatch further mouse events to |w1|. - ui::MouseEvent mouse_pressed_event(ui::ET_MOUSE_PRESSED, gfx::Point(5, 5), - gfx::Point(5, 5), 0, 0); - DispatchEventUsingWindowDispatcher(&mouse_pressed_event); - EXPECT_EQ(w1.get(), host()->dispatcher()->mouse_pressed_handler()); - - // Build a window in the second WindowEventDispatcher. - scoped_ptr<aura::Window> w2( - CreateNormalWindow(2, second_host_->window(), NULL)); - - // The act of having the second window take capture should clear out mouse - // pressed handler in the first WindowEventDispatcher. - w2->SetCapture(); - EXPECT_EQ(NULL, host()->dispatcher()->mouse_pressed_handler()); -} - -// Makes sure that when one window gets capture, it forces the release on the -// other. This is needed has to be handled explicitly on Linux, and is a sanity -// check on Windows. -TEST_F(CaptureControllerTest, ResetOtherWindowCaptureOnCapture) { - // Create a window inside the WindowEventDispatcher. - scoped_ptr<aura::Window> w1(CreateNormalWindow(1, root_window(), NULL)); - w1->SetCapture(); - // Both capture clients should return the same capture window. - EXPECT_EQ(w1.get(), GetCaptureWindow()); - EXPECT_EQ(w1.get(), GetSecondCaptureWindow()); - - // Build a window in the second WindowEventDispatcher and give it capture. - // Both capture clients should return the same capture window. - scoped_ptr<aura::Window> w2( - CreateNormalWindow(2, second_host_->window(), NULL)); - w2->SetCapture(); - EXPECT_EQ(w2.get(), GetCaptureWindow()); - EXPECT_EQ(w2.get(), GetSecondCaptureWindow()); -} - -// Verifies the touch target for the WindowEventDispatcher gets reset on -// releasing capture. -TEST_F(CaptureControllerTest, TouchTargetResetOnCaptureChange) { - // Create a window inside the WindowEventDispatcher. - scoped_ptr<aura::Window> w1(CreateNormalWindow(1, root_window(), NULL)); - ui::test::EventGenerator event_generator1(root_window()); - event_generator1.PressTouch(); - w1->SetCapture(); - // Both capture clients should return the same capture window. - EXPECT_EQ(w1.get(), GetCaptureWindow()); - EXPECT_EQ(w1.get(), GetSecondCaptureWindow()); - - // Build a window in the second WindowEventDispatcher and give it capture. - // Both capture clients should return the same capture window. - scoped_ptr<aura::Window> w2( - CreateNormalWindow(2, second_host_->window(), NULL)); - w2->SetCapture(); - EXPECT_EQ(w2.get(), GetCaptureWindow()); - EXPECT_EQ(w2.get(), GetSecondCaptureWindow()); - - // Release capture on the window. Releasing capture should reset the touch - // target of the first WindowEventDispatcher (as it no longer contains the - // capture target). - w2->ReleaseCapture(); - EXPECT_EQ(static_cast<aura::Window*>(NULL), GetCaptureWindow()); - EXPECT_EQ(static_cast<aura::Window*>(NULL), GetSecondCaptureWindow()); - ui::TouchEvent touch_event( - ui::ET_TOUCH_PRESSED, gfx::Point(), 0, 0, ui::EventTimeForNow(), 1.0f, - 1.0f, 1.0f, 1.0f); - EXPECT_EQ(static_cast<ui::GestureConsumer*>(w2.get()), - ui::GestureRecognizer::Get()->GetTouchLockedTarget(touch_event)); -} - -} // namespace views
diff --git a/ui/views/corewm/cursor_height_provider_win.cc b/ui/views/corewm/cursor_height_provider_win.cc deleted file mode 100644 index 0d28d38..0000000 --- a/ui/views/corewm/cursor_height_provider_win.cc +++ /dev/null
@@ -1,146 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/corewm/cursor_height_provider_win.h" - -#include <windows.h> -#include <algorithm> -#include <map> - -#include "base/basictypes.h" -#include "base/memory/scoped_ptr.h" -#include "base/win/scoped_hdc.h" - -namespace { -typedef scoped_ptr<uint32_t> PixelData; -typedef std::map<HCURSOR, int> HeightStorage; - -const uint32_t kBitsPeruint32 = sizeof(uint32_t) * 8; -// All bits are 1 for transparent portion of monochromatic mask. -const uint32_t kTransparentMask = 0xffffffff; -// This is height of default pointer arrow in Windows 7. -const int kDefaultHeight = 20; -// Masks are monochromatic. -const size_t kNumberOfColors = 2; -const size_t KHeaderAndPalette = - sizeof(BITMAPINFOHEADER) + kNumberOfColors * sizeof(RGBQUAD); - -static HeightStorage* cached_heights = NULL; - -// Extracts the pixel data of provided bitmap -PixelData GetBitmapData(HBITMAP handle, const BITMAPINFO& info, HDC hdc) { - PixelData data; - // Masks are monochromatic. - DCHECK_EQ(info.bmiHeader.biBitCount, 1); - if (info.bmiHeader.biBitCount != 1) - return data.Pass(); - - // When getting pixel data palette is appended to memory pointed by - // BITMAPINFO passed so allocate additional memory to store additional data. - scoped_ptr<BITMAPINFO> header( - reinterpret_cast<BITMAPINFO*>(new char[KHeaderAndPalette])); - memcpy(header.get(), &(info.bmiHeader), sizeof(info.bmiHeader)); - - data.reset(new uint32_t[info.bmiHeader.biSizeImage / sizeof(uint32_t)]); - - int result = GetDIBits(hdc, - handle, - 0, - info.bmiHeader.biHeight, - data.get(), - header.get(), - DIB_RGB_COLORS); - - if (result == 0) - data.reset(); - - return data.Pass(); -} - -// Checks if the specifed row is transparent in provided bitmap. -bool IsRowTransparent(const PixelData& data, - const uint32_t row_size, - const uint32_t last_byte_mask, - const uint32_t y) { - // Set the padding bits to 1 to make mask matching easier. - *(data.get() + (y + 1) * row_size - 1) |= last_byte_mask; - for (uint32_t i = y * row_size; i < (y + 1) * row_size; ++i) { - if (*(data.get() + i) != kTransparentMask) - return false; - } - return true; -} - -// Gets the vertical offset between specified cursor's hotpoint and it's bottom. -// -// Gets the cursor image data and extract cursor's visible height. -// Based on that get's what should be the vertical offset between cursor's -// hot point and the tooltip. -int CalculateCursorHeight(HCURSOR cursor_handle) { - base::win::ScopedGetDC hdc(NULL); - - ICONINFO icon = {0}; - GetIconInfo(cursor_handle, &icon); - - BITMAPINFO bitmap_info = {0}; - bitmap_info.bmiHeader.biSize = sizeof(bitmap_info.bmiHeader); - if (GetDIBits(hdc, icon.hbmMask, 0, 0, NULL, &bitmap_info, DIB_RGB_COLORS) == - 0) - return kDefaultHeight; - - // Rows are padded to full DWORDs. OR with this mask will set them to 1 - // to simplify matching with |transparent_mask|. - uint32_t last_byte_mask = 0xFFFFFFFF; - const unsigned char bits_to_shift = sizeof(last_byte_mask) * 8 - - (bitmap_info.bmiHeader.biWidth % kBitsPeruint32); - if (bits_to_shift != kBitsPeruint32) - last_byte_mask = (last_byte_mask << bits_to_shift); - else - last_byte_mask = 0; - - const uint32_t row_size = - (bitmap_info.bmiHeader.biWidth + kBitsPeruint32 - 1) / kBitsPeruint32; - PixelData data(GetBitmapData(icon.hbmMask, bitmap_info, hdc)); - if (data == NULL) - return kDefaultHeight; - - const int cursor_height = GetSystemMetrics(SM_CYCURSOR); - // Crash data seems to indicate cursor_height may be bigger than the bitmap. - int i = std::max(0, static_cast<int>(bitmap_info.bmiHeader.biHeight) - - cursor_height); - for (; i < bitmap_info.bmiHeader.biHeight; ++i) { - if (!IsRowTransparent(data, row_size, last_byte_mask, i)) { - i--; - break; - } - } - return bitmap_info.bmiHeader.biHeight - i - icon.yHotspot; -} - -} // namespace - -namespace views { -namespace corewm { - -int GetCurrentCursorVisibleHeight() { - CURSORINFO cursor = {0}; - cursor.cbSize = sizeof(cursor); - GetCursorInfo(&cursor); - - if (cached_heights == NULL) - cached_heights = new HeightStorage; - - HeightStorage::const_iterator cached_height = - cached_heights->find(cursor.hCursor); - if (cached_height != cached_heights->end()) - return cached_height->second; - - const int height = CalculateCursorHeight(cursor.hCursor); - (*cached_heights)[cursor.hCursor] = height; - - return height; -} - -} // namespace corewm -} // namespace views
diff --git a/ui/views/corewm/cursor_height_provider_win.h b/ui/views/corewm/cursor_height_provider_win.h deleted file mode 100644 index c931344..0000000 --- a/ui/views/corewm/cursor_height_provider_win.h +++ /dev/null
@@ -1,21 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_COREWM_CURSOR_HEIGHT_PROVIDER_WIN_H_ -#define UI_VIEWS_COREWM_CURSOR_HEIGHT_PROVIDER_WIN_H_ - -namespace views { -namespace corewm { - -// Gets the visible height of current cursor. -// -// The height is offset between cursor's hot point and it's -// bottom edge, derived from first non-transparent row of cursor's mask. - -int GetCurrentCursorVisibleHeight(); - -} // namespace corewm -} // namespace views - -#endif // UI_VIEWS_COREWM_CURSOR_HEIGHT_PROVIDER_WIN_H_
diff --git a/ui/views/corewm/desktop_capture_controller_unittest.cc b/ui/views/corewm/desktop_capture_controller_unittest.cc deleted file mode 100644 index 85c9c79..0000000 --- a/ui/views/corewm/desktop_capture_controller_unittest.cc +++ /dev/null
@@ -1,202 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/capture_controller.h" - -#include "base/logging.h" -#include "base/path_service.h" -#include "ui/aura/env.h" -#include "ui/aura/test/test_window_delegate.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/aura/window_tree_host.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/base/ui_base_paths.h" -#include "ui/events/event.h" -#include "ui/events/test/event_generator.h" -#include "ui/gl/gl_surface.h" -#include "ui/views/test/views_test_base.h" -#include "ui/views/view.h" -#include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" -#include "ui/views/widget/desktop_aura/desktop_screen_position_client.h" -#include "ui/views/widget/root_view.h" -#include "ui/views/widget/widget.h" - -// NOTE: these tests do native capture, so they have to be in -// interactive_ui_tests. - -namespace views { - -class DesktopCaptureControllerTest : public ViewsTestBase { - public: - DesktopCaptureControllerTest() {} - virtual ~DesktopCaptureControllerTest() {} - - virtual void SetUp() override { - gfx::GLSurface::InitializeOneOffForTests(); - ui::RegisterPathProvider(); - base::FilePath ui_test_pak_path; - ASSERT_TRUE(PathService::Get(ui::UI_TEST_PAK, &ui_test_pak_path)); - ui::ResourceBundle::InitSharedInstanceWithPakPath(ui_test_pak_path); - - ViewsTestBase::SetUp(); - } -}; - -// This class provides functionality to verify whether the View instance -// received the gesture event. -class DesktopViewInputTest : public View { - public: - DesktopViewInputTest() - : received_gesture_event_(false) {} - - virtual void OnGestureEvent(ui::GestureEvent* event) override { - received_gesture_event_ = true; - return View::OnGestureEvent(event); - } - - // Resets state maintained by this class. - void Reset() { - received_gesture_event_ = false; - } - - bool received_gesture_event() const { return received_gesture_event_; } - - private: - bool received_gesture_event_; - - DISALLOW_COPY_AND_ASSIGN(DesktopViewInputTest); -}; - -views::Widget* CreateWidget() { - views::Widget* widget = new views::Widget; - views::Widget::InitParams params; - params.type = views::Widget::InitParams::TYPE_WINDOW_FRAMELESS; - params.accept_events = true; - params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.native_widget = new DesktopNativeWidgetAura(widget); - params.bounds = gfx::Rect(0, 0, 200, 100); - widget->Init(params); - widget->Show(); - return widget; -} - -// Verifies mouse handlers are reset when a window gains capture. Specifically -// creates two widgets, does a mouse press in one, sets capture in the other and -// verifies state is reset in the first. -TEST_F(DesktopCaptureControllerTest, ResetMouseHandlers) { - scoped_ptr<Widget> w1(CreateWidget()); - scoped_ptr<Widget> w2(CreateWidget()); - ui::test::EventGenerator generator1(w1->GetNativeView()->GetRootWindow()); - generator1.MoveMouseToCenterOf(w1->GetNativeView()); - generator1.PressLeftButton(); - EXPECT_FALSE(w1->HasCapture()); - aura::WindowEventDispatcher* w1_dispatcher = - w1->GetNativeView()->GetHost()->dispatcher(); - EXPECT_TRUE(w1_dispatcher->mouse_pressed_handler() != NULL); - EXPECT_TRUE(w1_dispatcher->mouse_moved_handler() != NULL); - w2->SetCapture(w2->GetRootView()); - EXPECT_TRUE(w2->HasCapture()); - EXPECT_TRUE(w1_dispatcher->mouse_pressed_handler() == NULL); - EXPECT_TRUE(w1_dispatcher->mouse_moved_handler() == NULL); - w2->ReleaseCapture(); - RunPendingMessages(); -} - -// Tests aura::Window capture and whether gesture events are sent to the window -// which has capture. -// The test case creates two visible widgets and sets capture to the underlying -// aura::Windows one by one. It then sends a gesture event and validates whether -// the window which had capture receives the gesture. -// TODO(sky): move this test, it should be part of ScopedCaptureClient tests. -TEST_F(DesktopCaptureControllerTest, CaptureWindowInputEventTest) { - scoped_ptr<aura::client::ScreenPositionClient> desktop_position_client1; - scoped_ptr<aura::client::ScreenPositionClient> desktop_position_client2; - - scoped_ptr<Widget> widget1(new Widget()); - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - scoped_ptr<wm::ScopedCaptureClient> scoped_capture_client( - new wm::ScopedCaptureClient(params.context->GetRootWindow())); - aura::client::CaptureClient* capture_client = - scoped_capture_client->capture_client(); - params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.bounds = gfx::Rect(50, 50, 650, 650); - widget1->Init(params); - internal::RootView* root1 = - static_cast<internal::RootView*>(widget1->GetRootView()); - - desktop_position_client1.reset( - new DesktopScreenPositionClient(params.context->GetRootWindow())); - aura::client::SetScreenPositionClient( - widget1->GetNativeView()->GetRootWindow(), - desktop_position_client1.get()); - - DesktopViewInputTest* v1 = new DesktopViewInputTest(); - v1->SetBoundsRect(gfx::Rect(0, 0, 300, 300)); - root1->AddChildView(v1); - widget1->Show(); - - scoped_ptr<Widget> widget2(new Widget()); - - params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.bounds = gfx::Rect(50, 50, 650, 650); - widget2->Init(params); - - internal::RootView* root2 = - static_cast<internal::RootView*>(widget2->GetRootView()); - desktop_position_client2.reset( - new DesktopScreenPositionClient(params.context->GetRootWindow())); - aura::client::SetScreenPositionClient( - widget2->GetNativeView()->GetRootWindow(), - desktop_position_client2.get()); - ui::EventDispatchDetails details; - - DesktopViewInputTest* v2 = new DesktopViewInputTest(); - v2->SetBoundsRect(gfx::Rect(0, 0, 300, 300)); - root2->AddChildView(v2); - widget2->Show(); - - EXPECT_FALSE(widget1->GetNativeView()->HasCapture()); - EXPECT_FALSE(widget2->GetNativeView()->HasCapture()); - EXPECT_EQ(reinterpret_cast<aura::Window*>(0), - capture_client->GetCaptureWindow()); - - widget1->GetNativeView()->SetCapture(); - EXPECT_TRUE(widget1->GetNativeView()->HasCapture()); - EXPECT_FALSE(widget2->GetNativeView()->HasCapture()); - EXPECT_EQ(capture_client->GetCaptureWindow(), widget1->GetNativeView()); - - ui::GestureEvent g1(80, - 80, - 0, - base::TimeDelta(), - ui::GestureEventDetails(ui::ET_GESTURE_LONG_PRESS)); - details = root1->OnEventFromSource(&g1); - EXPECT_FALSE(details.dispatcher_destroyed); - EXPECT_FALSE(details.target_destroyed); - - EXPECT_TRUE(v1->received_gesture_event()); - EXPECT_FALSE(v2->received_gesture_event()); - v1->Reset(); - v2->Reset(); - - widget2->GetNativeView()->SetCapture(); - - EXPECT_FALSE(widget1->GetNativeView()->HasCapture()); - EXPECT_TRUE(widget2->GetNativeView()->HasCapture()); - EXPECT_EQ(capture_client->GetCaptureWindow(), widget2->GetNativeView()); - - details = root2->OnEventFromSource(&g1); - EXPECT_FALSE(details.dispatcher_destroyed); - EXPECT_FALSE(details.target_destroyed); - - EXPECT_TRUE(v2->received_gesture_event()); - EXPECT_FALSE(v1->received_gesture_event()); - - widget1->CloseNow(); - widget2->CloseNow(); - RunPendingMessages(); -} - -} // namespace views
diff --git a/ui/views/corewm/tooltip.h b/ui/views/corewm/tooltip.h deleted file mode 100644 index 7fb15bc..0000000 --- a/ui/views/corewm/tooltip.h +++ /dev/null
@@ -1,46 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_COREWM_TOOLTIP_H_ -#define UI_VIEWS_COREWM_TOOLTIP_H_ - -#include "base/strings/string16.h" -#include "ui/views/views_export.h" - -namespace aura { -class Window; -} - -namespace gfx { -class Point; -} - -namespace views { -namespace corewm { - -// Tooltip is responsible for showing the tooltip in an appropriate manner. -// Tooltip is used by TooltipController. -class VIEWS_EXPORT Tooltip { - public: - virtual ~Tooltip() {} - - // Updates the text on the tooltip and resizes to fit. - virtual void SetText(aura::Window* window, - const base::string16& tooltip_text, - const gfx::Point& location) = 0; - - // Shows the tooltip at the specified location (in screen coordinates). - virtual void Show() = 0; - - // Hides the tooltip. - virtual void Hide() = 0; - - // Is the tooltip visibile? - virtual bool IsVisible() = 0; -}; - -} // namespace corewm -} // namespace views - -#endif // UI_VIEWS_COREWM_TOOLTIP_H_
diff --git a/ui/views/corewm/tooltip_aura.cc b/ui/views/corewm/tooltip_aura.cc deleted file mode 100644 index 02117a8..0000000 --- a/ui/views/corewm/tooltip_aura.cc +++ /dev/null
@@ -1,238 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/corewm/tooltip_aura.h" - -#include "base/strings/string_split.h" -#include "ui/aura/window.h" -#include "ui/aura/window_tree_host.h" -#include "ui/gfx/screen.h" -#include "ui/gfx/text_elider.h" -#include "ui/gfx/text_utils.h" -#include "ui/native_theme/native_theme.h" -#include "ui/views/background.h" -#include "ui/views/border.h" -#include "ui/views/widget/widget.h" - -namespace { - -// Max visual tooltip width. If a tooltip is greater than this width, it will -// be wrapped. -const int kTooltipMaxWidthPixels = 400; - -const size_t kMaxLines = 10; - -// FIXME: get cursor offset from actual cursor size. -const int kCursorOffsetX = 10; -const int kCursorOffsetY = 15; - -// Creates a widget of type TYPE_TOOLTIP -views::Widget* CreateTooltipWidget(aura::Window* tooltip_window) { - views::Widget* widget = new views::Widget; - views::Widget::InitParams params; - // For aura, since we set the type to TYPE_TOOLTIP, the widget will get - // auto-parented to the right container. - params.type = views::Widget::InitParams::TYPE_TOOLTIP; - params.context = tooltip_window; - DCHECK(params.context); - params.keep_on_top = true; - params.accept_events = false; - widget->Init(params); - return widget; -} - -} // namespace - -namespace views { -namespace corewm { - -TooltipAura::TooltipAura(gfx::ScreenType screen_type) - : screen_type_(screen_type), - widget_(NULL), - tooltip_window_(NULL) { - label_.set_owned_by_client(); - label_.SetMultiLine(true); - - const int kHorizontalPadding = 3; - const int kVerticalPadding = 2; - label_.SetBorder(Border::CreateEmptyBorder( - kVerticalPadding, kHorizontalPadding, - kVerticalPadding, kHorizontalPadding)); -} - -TooltipAura::~TooltipAura() { - DestroyWidget(); -} - -// static -void TooltipAura::TrimTooltipToFit(const gfx::FontList& font_list, - int max_width, - base::string16* text, - int* width, - int* line_count) { - *width = 0; - *line_count = 0; - - // Determine the available width for the tooltip. - int available_width = std::min(kTooltipMaxWidthPixels, max_width); - - std::vector<base::string16> lines; - base::SplitString(*text, '\n', &lines); - std::vector<base::string16> result_lines; - - // Format each line to fit. - for (std::vector<base::string16>::iterator l = lines.begin(); - l != lines.end(); ++l) { - // We break the line at word boundaries, then stuff as many words as we can - // in the available width to the current line, and move the remaining words - // to a new line. - std::vector<base::string16> words; - base::SplitStringDontTrim(*l, ' ', &words); - int current_width = 0; - base::string16 line; - for (std::vector<base::string16>::iterator w = words.begin(); - w != words.end(); ++w) { - base::string16 word = *w; - if (w + 1 != words.end()) - word.push_back(' '); - int word_width = gfx::GetStringWidth(word, font_list); - if (current_width + word_width > available_width) { - // Current width will exceed the available width. Must start a new line. - if (!line.empty()) - result_lines.push_back(line); - current_width = 0; - line.clear(); - } - current_width += word_width; - line.append(word); - } - result_lines.push_back(line); - } - - // Clamp number of lines to |kMaxLines|. - if (result_lines.size() > kMaxLines) { - result_lines.resize(kMaxLines); - // Add ellipses character to last line. - result_lines[kMaxLines - 1] = gfx::TruncateString( - result_lines.back(), result_lines.back().length() - 1, gfx::WORD_BREAK); - } - *line_count = result_lines.size(); - - // Flatten the result. - base::string16 result; - for (std::vector<base::string16>::iterator l = result_lines.begin(); - l != result_lines.end(); ++l) { - if (!result.empty()) - result.push_back('\n'); - int line_width = gfx::GetStringWidth(*l, font_list); - // Since we only break at word boundaries, it could happen that due to some - // very long word, line_width is greater than the available_width. In such - // case, we simply truncate at available_width and add ellipses at the end. - if (line_width > available_width) { - *width = available_width; - result.append(gfx::ElideText(*l, font_list, available_width, - gfx::ELIDE_TAIL)); - } else { - *width = std::max(*width, line_width); - result.append(*l); - } - } - *text = result; -} - -int TooltipAura::GetMaxWidth(const gfx::Point& location) const { - // TODO(varunjain): implementation duplicated in tooltip_manager_aura. Figure - // out a way to merge. - gfx::Screen* screen = gfx::Screen::GetScreenByType(screen_type_); - gfx::Rect display_bounds(screen->GetDisplayNearestPoint(location).bounds()); - return (display_bounds.width() + 1) / 2; -} - -void TooltipAura::SetTooltipBounds(const gfx::Point& mouse_pos, - const gfx::Size& tooltip_size) { - gfx::Rect tooltip_rect(mouse_pos, tooltip_size); - tooltip_rect.Offset(kCursorOffsetX, kCursorOffsetY); - gfx::Screen* screen = gfx::Screen::GetScreenByType(screen_type_); - gfx::Rect display_bounds(screen->GetDisplayNearestPoint(mouse_pos).bounds()); - - // If tooltip is out of bounds on the x axis, we simply shift it - // horizontally by the offset. - if (tooltip_rect.right() > display_bounds.right()) { - int h_offset = tooltip_rect.right() - display_bounds.right(); - tooltip_rect.Offset(-h_offset, 0); - } - - // If tooltip is out of bounds on the y axis, we flip it to appear above the - // mouse cursor instead of below. - if (tooltip_rect.bottom() > display_bounds.bottom()) - tooltip_rect.set_y(mouse_pos.y() - tooltip_size.height()); - - tooltip_rect.AdjustToFit(display_bounds); - widget_->SetBounds(tooltip_rect); -} - -void TooltipAura::DestroyWidget() { - if (widget_) { - widget_->RemoveObserver(this); - widget_->Close(); - widget_ = NULL; - } -} - -void TooltipAura::SetText(aura::Window* window, - const base::string16& tooltip_text, - const gfx::Point& location) { - tooltip_window_ = window; - int max_width = 0; - int line_count = 0; - base::string16 trimmed_text(tooltip_text); - TrimTooltipToFit(label_.font_list(), GetMaxWidth(location), &trimmed_text, - &max_width, &line_count); - label_.SetText(trimmed_text); - - if (!widget_) { - widget_ = CreateTooltipWidget(tooltip_window_); - widget_->SetContentsView(&label_); - widget_->AddObserver(this); - } - - label_.SizeToFit(max_width + label_.GetInsets().width()); - SetTooltipBounds(location, label_.size()); - - ui::NativeTheme* native_theme = widget_->GetNativeTheme(); - label_.set_background( - views::Background::CreateSolidBackground( - native_theme->GetSystemColor( - ui::NativeTheme::kColorId_TooltipBackground))); - - label_.SetAutoColorReadabilityEnabled(false); - label_.SetEnabledColor(native_theme->GetSystemColor( - ui::NativeTheme::kColorId_TooltipText)); -} - -void TooltipAura::Show() { - if (widget_) { - widget_->Show(); - widget_->StackAtTop(); - } -} - -void TooltipAura::Hide() { - tooltip_window_ = NULL; - if (widget_) - widget_->Hide(); -} - -bool TooltipAura::IsVisible() { - return widget_ && widget_->IsVisible(); -} - -void TooltipAura::OnWidgetDestroying(views::Widget* widget) { - DCHECK_EQ(widget_, widget); - widget_ = NULL; - tooltip_window_ = NULL; -} - -} // namespace corewm -} // namespace views
diff --git a/ui/views/corewm/tooltip_aura.h b/ui/views/corewm/tooltip_aura.h deleted file mode 100644 index 24976b9..0000000 --- a/ui/views/corewm/tooltip_aura.h +++ /dev/null
@@ -1,80 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_COREWM_TOOLTIP_AURA_H_ -#define UI_VIEWS_COREWM_TOOLTIP_AURA_H_ - -#include "ui/gfx/screen_type_delegate.h" -#include "ui/views/controls/label.h" -#include "ui/views/corewm/tooltip.h" -#include "ui/views/widget/widget_observer.h" - -namespace gfx { -class FontList; -} // namespace gfx - -namespace views { - -class Widget; - -namespace corewm { - -// Implementation of Tooltip that shows the tooltip using a Widget and Label. -class VIEWS_EXPORT TooltipAura : public Tooltip, public WidgetObserver { - public: - explicit TooltipAura(gfx::ScreenType screen_type); - virtual ~TooltipAura(); - - // Trims the tooltip to fit in the width |max_width|, setting |text| to the - // clipped result, |width| to the width (in pixels) of the clipped text - // and |line_count| to the number of lines of text in the tooltip. |font_list| - // is used to layout |text|. |max_width| comes from GetMaxWidth(). - static void TrimTooltipToFit(const gfx::FontList& font_list, - int max_width, - base::string16* text, - int* width, - int* line_count); - - private: - // Returns the max width of the tooltip when shown at the specified location. - int GetMaxWidth(const gfx::Point& location) const; - - // Adjusts the bounds given by the arguments to fit inside the desktop - // and applies the adjusted bounds to the label_. - void SetTooltipBounds(const gfx::Point& mouse_pos, - const gfx::Size& tooltip_size); - - // Destroys |widget_|. - void DestroyWidget(); - - // Tooltip: - virtual void SetText(aura::Window* window, - const base::string16& tooltip_text, - const gfx::Point& location) override; - virtual void Show() override; - virtual void Hide() override; - virtual bool IsVisible() override; - - // WidgetObserver: - virtual void OnWidgetDestroying(Widget* widget) override; - - const gfx::ScreenType screen_type_; - - // The label showing the tooltip. - Label label_; - - // The widget containing the tooltip. May be NULL. - Widget* widget_; - - // The window we're showing the tooltip for. Never NULL and valid while - // showing. - aura::Window* tooltip_window_; - - DISALLOW_COPY_AND_ASSIGN(TooltipAura); -}; - -} // namespace corewm -} // namespace views - -#endif // UI_VIEWS_COREWM_TOOLTIP_AURA_H_
diff --git a/ui/views/corewm/tooltip_aura_unittest.cc b/ui/views/corewm/tooltip_aura_unittest.cc deleted file mode 100644 index a77db2f..0000000 --- a/ui/views/corewm/tooltip_aura_unittest.cc +++ /dev/null
@@ -1,131 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/corewm/tooltip_aura.h" - -#include "base/strings/utf_string_conversions.h" -#include "ui/aura/test/aura_test_base.h" -#include "ui/gfx/font_list.h" -#include "ui/gfx/text_elider.h" -#include "ui/gfx/text_utils.h" - -using base::ASCIIToUTF16; -using base::UTF8ToUTF16; - -namespace views { -namespace corewm { - -typedef aura::test::AuraTestBase TooltipAuraTest; - -TEST_F(TooltipAuraTest, TrimTooltipToFitTests) { - const gfx::FontList font_list; - const int max_width = 4000; - base::string16 tooltip; - int width, line_count, expect_lines; - int max_pixel_width = 400; // copied from constants in tooltip_controller.cc - int max_lines = 10; // copied from constants in tooltip_controller.cc - size_t tooltip_len; - - // Error in computed size vs. expected size should not be greater than the - // size of the longest word. - int error_in_pixel_width = gfx::GetStringWidth(ASCIIToUTF16("tooltip"), - font_list); - - // Long tooltips should wrap to next line - tooltip.clear(); - width = line_count = -1; - expect_lines = 3; - for (; gfx::GetStringWidth(tooltip, font_list) <= - (expect_lines - 1) * max_pixel_width;) - tooltip.append(ASCIIToUTF16("This is part of the tooltip")); - tooltip_len = tooltip.length(); - TooltipAura::TrimTooltipToFit(font_list, max_width, &tooltip, &width, - &line_count); - EXPECT_NEAR(max_pixel_width, width, error_in_pixel_width); - EXPECT_EQ(expect_lines, line_count); - EXPECT_EQ(tooltip_len + expect_lines - 1, tooltip.length()); - - // More than |max_lines| lines should get truncated at 10 lines. - tooltip.clear(); - width = line_count = -1; - expect_lines = 13; - for (; gfx::GetStringWidth(tooltip, font_list) <= - (expect_lines - 1) * max_pixel_width;) - tooltip.append(ASCIIToUTF16("This is part of the tooltip")); - TooltipAura::TrimTooltipToFit(font_list, max_width, &tooltip, &width, - &line_count); - EXPECT_NEAR(max_pixel_width, width, error_in_pixel_width); - EXPECT_EQ(max_lines, line_count); - - // Long multi line tooltips should wrap individual lines. - tooltip.clear(); - width = line_count = -1; - expect_lines = 4; - for (; gfx::GetStringWidth(tooltip, font_list) <= - (expect_lines - 2) * max_pixel_width;) - tooltip.append(ASCIIToUTF16("This is part of the tooltip")); - tooltip.insert(tooltip.length() / 2, ASCIIToUTF16("\n")); - tooltip_len = tooltip.length(); - TooltipAura::TrimTooltipToFit(font_list, max_width, &tooltip, &width, - &line_count); - EXPECT_NEAR(max_pixel_width, width, error_in_pixel_width); - EXPECT_EQ(expect_lines, line_count); - // We may have inserted the line break above near a space which will get - // trimmed. Hence we may be off by 1 in the final tooltip length calculation. - EXPECT_NEAR(tooltip_len + expect_lines - 2, tooltip.length(), 1); - -#if !defined(OS_WIN) - // Tooltip with really long word gets elided. - tooltip.clear(); - width = line_count = -1; - tooltip = UTF8ToUTF16(std::string('a', max_pixel_width)); - TooltipAura::TrimTooltipToFit(font_list, max_width, &tooltip, &width, - &line_count); - EXPECT_NEAR(max_pixel_width, width, 5); - EXPECT_EQ(1, line_count); - EXPECT_EQ(gfx::ElideText(UTF8ToUTF16(std::string('a', max_pixel_width)), - font_list, max_pixel_width, gfx::ELIDE_TAIL), - tooltip); -#endif - - // Normal small tooltip should stay as is. - tooltip.clear(); - width = line_count = -1; - tooltip = ASCIIToUTF16("Small Tooltip"); - TooltipAura::TrimTooltipToFit(font_list, max_width, &tooltip, &width, - &line_count); - EXPECT_EQ(gfx::GetStringWidth(ASCIIToUTF16("Small Tooltip"), font_list), - width); - EXPECT_EQ(1, line_count); - EXPECT_EQ(ASCIIToUTF16("Small Tooltip"), tooltip); - - // Normal small multi-line tooltip should stay as is. - tooltip.clear(); - width = line_count = -1; - tooltip = ASCIIToUTF16("Multi line\nTooltip"); - TooltipAura::TrimTooltipToFit(font_list, max_width, &tooltip, &width, - &line_count); - int expected_width = gfx::GetStringWidth(ASCIIToUTF16("Multi line"), - font_list); - expected_width = std::max(expected_width, - gfx::GetStringWidth(ASCIIToUTF16("Tooltip"), - font_list)); - EXPECT_EQ(expected_width, width); - EXPECT_EQ(2, line_count); - EXPECT_EQ(ASCIIToUTF16("Multi line\nTooltip"), tooltip); - - // Whitespaces in tooltips are preserved. - tooltip.clear(); - width = line_count = -1; - tooltip = ASCIIToUTF16("Small Tool t\tip"); - TooltipAura::TrimTooltipToFit(font_list, max_width, &tooltip, &width, - &line_count); - EXPECT_EQ(gfx::GetStringWidth(ASCIIToUTF16("Small Tool t\tip"), font_list), - width); - EXPECT_EQ(1, line_count); - EXPECT_EQ(ASCIIToUTF16("Small Tool t\tip"), tooltip); -} - -} // namespace corewm -} // namespace views
diff --git a/ui/views/corewm/tooltip_controller.cc b/ui/views/corewm/tooltip_controller.cc deleted file mode 100644 index b1ffc1c..0000000 --- a/ui/views/corewm/tooltip_controller.cc +++ /dev/null
@@ -1,368 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/corewm/tooltip_controller.h" - -#include <vector> - -#include "base/strings/string_util.h" -#include "base/time/time.h" -#include "ui/aura/client/capture_client.h" -#include "ui/aura/client/cursor_client.h" -#include "ui/aura/client/screen_position_client.h" -#include "ui/aura/env.h" -#include "ui/aura/window.h" -#include "ui/events/event.h" -#include "ui/gfx/font.h" -#include "ui/gfx/rect.h" -#include "ui/gfx/screen.h" -#include "ui/views/corewm/tooltip.h" -#include "ui/views/widget/tooltip_manager.h" -#include "ui/wm/public/drag_drop_client.h" - -namespace views { -namespace corewm { -namespace { - -const int kTooltipTimeoutMs = 500; -const int kDefaultTooltipShownTimeoutMs = 10000; - -// Returns true if |target| is a valid window to get the tooltip from. -// |event_target| is the original target from the event and |target| the window -// at the same location. -bool IsValidTarget(aura::Window* event_target, aura::Window* target) { - if (!target || (event_target == target)) - return true; - - void* event_target_grouping_id = event_target->GetNativeWindowProperty( - TooltipManager::kGroupingPropertyKey); - void* target_grouping_id = target->GetNativeWindowProperty( - TooltipManager::kGroupingPropertyKey); - return event_target_grouping_id && - event_target_grouping_id == target_grouping_id; -} - -// Returns the target (the Window tooltip text comes from) based on the event. -// If a Window other than event.target() is returned, |location| is adjusted -// to be in the coordinates of the returned Window. -aura::Window* GetTooltipTarget(const ui::MouseEvent& event, - gfx::Point* location) { - switch (event.type()) { - case ui::ET_MOUSE_CAPTURE_CHANGED: - // On windows we can get a capture changed without an exit. We need to - // reset state when this happens else the tooltip may incorrectly show. - return NULL; - case ui::ET_MOUSE_EXITED: - return NULL; - case ui::ET_MOUSE_MOVED: - case ui::ET_MOUSE_DRAGGED: { - aura::Window* event_target = static_cast<aura::Window*>(event.target()); - if (!event_target) - return NULL; - - // If a window other than |event_target| has capture, ignore the event. - // This can happen when RootWindow creates events when showing/hiding, or - // the system generates an extra event. We have to check - // GetGlobalCaptureWindow() as Windows does not use a singleton - // CaptureClient. - if (!event_target->HasCapture()) { - aura::Window* root = event_target->GetRootWindow(); - if (root) { - aura::client::CaptureClient* capture_client = - aura::client::GetCaptureClient(root); - if (capture_client) { - aura::Window* capture_window = - capture_client->GetGlobalCaptureWindow(); - if (capture_window && event_target != capture_window) - return NULL; - } - } - return event_target; - } - - // If |target| has capture all events go to it, even if the mouse is - // really over another window. Find the real window the mouse is over. - gfx::Point screen_loc(event.location()); - aura::client::GetScreenPositionClient(event_target->GetRootWindow())-> - ConvertPointToScreen(event_target, &screen_loc); - gfx::Screen* screen = gfx::Screen::GetScreenFor(event_target); - aura::Window* target = screen->GetWindowAtScreenPoint(screen_loc); - if (!target) - return NULL; - gfx::Point target_loc(screen_loc); - aura::client::GetScreenPositionClient(target->GetRootWindow())-> - ConvertPointFromScreen(target, &target_loc); - aura::Window* screen_target = target->GetEventHandlerForPoint(target_loc); - if (!IsValidTarget(event_target, screen_target)) - return NULL; - - aura::Window::ConvertPointToTarget(screen_target, target, &target_loc); - *location = target_loc; - return screen_target; - } - default: - NOTREACHED(); - break; - } - return NULL; -} - -} // namespace - -//////////////////////////////////////////////////////////////////////////////// -// TooltipController public: - -TooltipController::TooltipController(scoped_ptr<Tooltip> tooltip) - : tooltip_window_(NULL), - tooltip_id_(NULL), - tooltip_window_at_mouse_press_(NULL), - tooltip_(tooltip.Pass()), - tooltips_enabled_(true) { - tooltip_timer_.Start(FROM_HERE, - base::TimeDelta::FromMilliseconds(kTooltipTimeoutMs), - this, &TooltipController::TooltipTimerFired); -} - -TooltipController::~TooltipController() { - if (tooltip_window_) - tooltip_window_->RemoveObserver(this); -} - -void TooltipController::UpdateTooltip(aura::Window* target) { - // If tooltip is visible, we may want to hide it. If it is not, we are ok. - if (tooltip_window_ == target && tooltip_->IsVisible()) - UpdateIfRequired(); - - // Reset |tooltip_window_at_mouse_press_| if the moving within the same window - // but over a region that has different tooltip text. By resetting - // |tooltip_window_at_mouse_press_| we ensure the next time the timer fires - // we'll requery for the tooltip text. - // This handles the case of clicking on a view, moving within the same window - // but over a different view, than back to the original. - if (tooltip_window_at_mouse_press_ && - target == tooltip_window_at_mouse_press_ && - aura::client::GetTooltipText(target) != tooltip_text_at_mouse_press_) { - tooltip_window_at_mouse_press_ = NULL; - } - - // If we had stopped the tooltip timer for some reason, we must restart it if - // there is a change in the tooltip. - if (!tooltip_timer_.IsRunning()) { - if (tooltip_window_ != target || (tooltip_window_ && - tooltip_text_ != aura::client::GetTooltipText(tooltip_window_))) { - tooltip_timer_.Start(FROM_HERE, - base::TimeDelta::FromMilliseconds(kTooltipTimeoutMs), - this, &TooltipController::TooltipTimerFired); - } - } -} - -void TooltipController::SetTooltipShownTimeout(aura::Window* target, - int timeout_in_ms) { - tooltip_shown_timeout_map_[target] = timeout_in_ms; -} - -void TooltipController::SetTooltipsEnabled(bool enable) { - if (tooltips_enabled_ == enable) - return; - tooltips_enabled_ = enable; - UpdateTooltip(tooltip_window_); -} - -void TooltipController::OnKeyEvent(ui::KeyEvent* event) { - // On key press, we want to hide the tooltip and not show it until change. - // This is the same behavior as hiding tooltips on timeout. Hence, we can - // simply simulate a timeout. - if (tooltip_shown_timer_.IsRunning()) { - tooltip_shown_timer_.Stop(); - TooltipShownTimerFired(); - } -} - -void TooltipController::OnMouseEvent(ui::MouseEvent* event) { - switch (event->type()) { - case ui::ET_MOUSE_CAPTURE_CHANGED: - case ui::ET_MOUSE_EXITED: - case ui::ET_MOUSE_MOVED: - case ui::ET_MOUSE_DRAGGED: { - curr_mouse_loc_ = event->location(); - aura::Window* target = NULL; - // Avoid a call to gfx::Screen::GetWindowAtScreenPoint() since it can be - // very expensive on X11 in cases when the tooltip is hidden anyway. - if (tooltips_enabled_ && - !aura::Env::GetInstance()->IsMouseButtonDown() && - !IsDragDropInProgress()) { - target = GetTooltipTarget(*event, &curr_mouse_loc_); - } - SetTooltipWindow(target); - if (tooltip_timer_.IsRunning()) - tooltip_timer_.Reset(); - - if (tooltip_->IsVisible()) - UpdateIfRequired(); - break; - } - case ui::ET_MOUSE_PRESSED: - if ((event->flags() & ui::EF_IS_NON_CLIENT) == 0) { - aura::Window* target = static_cast<aura::Window*>(event->target()); - // We don't get a release for non-client areas. - tooltip_window_at_mouse_press_ = target; - if (target) - tooltip_text_at_mouse_press_ = aura::client::GetTooltipText(target); - } - tooltip_->Hide(); - break; - case ui::ET_MOUSEWHEEL: - // Hide the tooltip for click, release, drag, wheel events. - if (tooltip_->IsVisible()) - tooltip_->Hide(); - break; - default: - break; - } -} - -void TooltipController::OnTouchEvent(ui::TouchEvent* event) { - // TODO(varunjain): need to properly implement tooltips for - // touch events. - // Hide the tooltip for touch events. - tooltip_->Hide(); - SetTooltipWindow(NULL); -} - -void TooltipController::OnCancelMode(ui::CancelModeEvent* event) { - tooltip_->Hide(); - SetTooltipWindow(NULL); -} - -void TooltipController::OnWindowDestroyed(aura::Window* window) { - if (tooltip_window_ == window) { - tooltip_->Hide(); - tooltip_shown_timeout_map_.erase(tooltip_window_); - tooltip_window_ = NULL; - } -} - -//////////////////////////////////////////////////////////////////////////////// -// TooltipController private: - -void TooltipController::TooltipTimerFired() { - UpdateIfRequired(); -} - -void TooltipController::TooltipShownTimerFired() { - tooltip_->Hide(); - - // Since the user presumably no longer needs the tooltip, we also stop the - // tooltip timer so that tooltip does not pop back up. We will restart this - // timer if the tooltip changes (see UpdateTooltip()). - tooltip_timer_.Stop(); -} - -void TooltipController::UpdateIfRequired() { - if (!tooltips_enabled_ || - aura::Env::GetInstance()->IsMouseButtonDown() || - IsDragDropInProgress() || !IsCursorVisible()) { - tooltip_->Hide(); - return; - } - - base::string16 tooltip_text; - if (tooltip_window_) - tooltip_text = aura::client::GetTooltipText(tooltip_window_); - - // If the user pressed a mouse button. We will hide the tooltip and not show - // it until there is a change in the tooltip. - if (tooltip_window_at_mouse_press_) { - if (tooltip_window_ == tooltip_window_at_mouse_press_ && - tooltip_text == tooltip_text_at_mouse_press_) { - tooltip_->Hide(); - return; - } - tooltip_window_at_mouse_press_ = NULL; - } - - // If the uniqueness indicator is different from the previously encountered - // one, we should force tooltip update - const void* tooltip_id = aura::client::GetTooltipId(tooltip_window_); - bool ids_differ = false; - ids_differ = tooltip_id_ != tooltip_id; - tooltip_id_ = tooltip_id; - - // We add the !tooltip_->IsVisible() below because when we come here from - // TooltipTimerFired(), the tooltip_text may not have changed but we still - // want to update the tooltip because the timer has fired. - // If we come here from UpdateTooltip(), we have already checked for tooltip - // visibility and this check below will have no effect. - if (tooltip_text_ != tooltip_text || !tooltip_->IsVisible() || ids_differ) { - tooltip_shown_timer_.Stop(); - tooltip_text_ = tooltip_text; - base::string16 trimmed_text(tooltip_text_); - views::TooltipManager::TrimTooltipText(&trimmed_text); - // If the string consists entirely of whitespace, then don't both showing it - // (an empty tooltip is useless). - base::string16 whitespace_removed_text; - base::TrimWhitespace(trimmed_text, base::TRIM_ALL, - &whitespace_removed_text); - if (whitespace_removed_text.empty()) { - tooltip_->Hide(); - } else { - gfx::Point widget_loc = curr_mouse_loc_ + - tooltip_window_->GetBoundsInScreen().OffsetFromOrigin(); - tooltip_->SetText(tooltip_window_, whitespace_removed_text, widget_loc); - tooltip_->Show(); - int timeout = GetTooltipShownTimeout(); - if (timeout > 0) { - tooltip_shown_timer_.Start(FROM_HERE, - base::TimeDelta::FromMilliseconds(timeout), - this, &TooltipController::TooltipShownTimerFired); - } - } - } -} - -bool TooltipController::IsTooltipVisible() { - return tooltip_->IsVisible(); -} - -bool TooltipController::IsDragDropInProgress() { - if (!tooltip_window_) - return false; - aura::client::DragDropClient* client = - aura::client::GetDragDropClient(tooltip_window_->GetRootWindow()); - return client && client->IsDragDropInProgress(); -} - -bool TooltipController::IsCursorVisible() { - if (!tooltip_window_) - return false; - aura::Window* root = tooltip_window_->GetRootWindow(); - if (!root) - return false; - aura::client::CursorClient* cursor_client = - aura::client::GetCursorClient(root); - // |cursor_client| may be NULL in tests, treat NULL as always visible. - return !cursor_client || cursor_client->IsCursorVisible(); -} - -int TooltipController::GetTooltipShownTimeout() { - std::map<aura::Window*, int>::const_iterator it = - tooltip_shown_timeout_map_.find(tooltip_window_); - if (it == tooltip_shown_timeout_map_.end()) - return kDefaultTooltipShownTimeoutMs; - return it->second; -} - -void TooltipController::SetTooltipWindow(aura::Window* target) { - if (tooltip_window_ == target) - return; - if (tooltip_window_) - tooltip_window_->RemoveObserver(this); - tooltip_window_ = target; - if (tooltip_window_) - tooltip_window_->AddObserver(this); -} - -} // namespace corewm -} // namespace views
diff --git a/ui/views/corewm/tooltip_controller.h b/ui/views/corewm/tooltip_controller.h deleted file mode 100644 index 8242725..0000000 --- a/ui/views/corewm/tooltip_controller.h +++ /dev/null
@@ -1,111 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_COREWM_TOOLTIP_CONTROLLER_H_ -#define UI_VIEWS_COREWM_TOOLTIP_CONTROLLER_H_ - -#include <map> - -#include "base/memory/scoped_ptr.h" -#include "base/strings/string16.h" -#include "base/timer/timer.h" -#include "ui/aura/window_observer.h" -#include "ui/events/event_handler.h" -#include "ui/gfx/point.h" -#include "ui/views/views_export.h" -#include "ui/wm/public/tooltip_client.h" - -namespace aura { -class Window; -} - -namespace views { -namespace corewm { - -class Tooltip; - -namespace test { -class TooltipControllerTestHelper; -} // namespace test - -// TooltipController provides tooltip functionality for aura. -class VIEWS_EXPORT TooltipController : public aura::client::TooltipClient, - public ui::EventHandler, - public aura::WindowObserver { - public: - explicit TooltipController(scoped_ptr<Tooltip> tooltip); - virtual ~TooltipController(); - - // Overridden from aura::client::TooltipClient. - virtual void UpdateTooltip(aura::Window* target) override; - virtual void SetTooltipShownTimeout(aura::Window* target, - int timeout_in_ms) override; - virtual void SetTooltipsEnabled(bool enable) override; - - // Overridden from ui::EventHandler. - virtual void OnKeyEvent(ui::KeyEvent* event) override; - virtual void OnMouseEvent(ui::MouseEvent* event) override; - virtual void OnTouchEvent(ui::TouchEvent* event) override; - virtual void OnCancelMode(ui::CancelModeEvent* event) override; - - // Overridden from aura::WindowObserver. - virtual void OnWindowDestroyed(aura::Window* window) override; - - const gfx::Point& mouse_location() const { return curr_mouse_loc_; } - - private: - friend class test::TooltipControllerTestHelper; - - void TooltipTimerFired(); - void TooltipShownTimerFired(); - - // Updates the tooltip if required (if there is any change in the tooltip - // text, tooltip id or the aura::Window). - void UpdateIfRequired(); - - // Only used in tests. - bool IsTooltipVisible(); - - bool IsDragDropInProgress(); - - // Returns true if the cursor is visible. - bool IsCursorVisible(); - - int GetTooltipShownTimeout(); - - // Sets tooltip window to |target| if it is different from existing window. - // Calls RemoveObserver on the existing window if it is not NULL. - // Calls AddObserver on the new window if it is not NULL. - void SetTooltipWindow(aura::Window* target); - - aura::Window* tooltip_window_; - base::string16 tooltip_text_; - const void* tooltip_id_; - - // These fields are for tracking state when the user presses a mouse button. - aura::Window* tooltip_window_at_mouse_press_; - base::string16 tooltip_text_at_mouse_press_; - - scoped_ptr<Tooltip> tooltip_; - - base::RepeatingTimer<TooltipController> tooltip_timer_; - - // Timer to timeout the life of an on-screen tooltip. We hide the tooltip when - // this timer fires. - base::OneShotTimer<TooltipController> tooltip_shown_timer_; - - // Location of the last event in |tooltip_window_|'s coordinates. - gfx::Point curr_mouse_loc_; - - bool tooltips_enabled_; - - std::map<aura::Window*, int> tooltip_shown_timeout_map_; - - DISALLOW_COPY_AND_ASSIGN(TooltipController); -}; - -} // namespace corewm -} // namespace views - -#endif // UI_VIEWS_COREWM_TOOLTIP_CONTROLLER_H_
diff --git a/ui/views/corewm/tooltip_controller_test_helper.cc b/ui/views/corewm/tooltip_controller_test_helper.cc deleted file mode 100644 index f96b08d..0000000 --- a/ui/views/corewm/tooltip_controller_test_helper.cc +++ /dev/null
@@ -1,65 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/corewm/tooltip_controller_test_helper.h" - -#include "ui/aura/window.h" -#include "ui/views/corewm/tooltip_controller.h" - -namespace views { -namespace corewm { -namespace test { - -TooltipControllerTestHelper::TooltipControllerTestHelper( - TooltipController* controller) - : controller_(controller) { -} - -TooltipControllerTestHelper::~TooltipControllerTestHelper() { -} - -base::string16 TooltipControllerTestHelper::GetTooltipText() { - return controller_->tooltip_text_; -} - -aura::Window* TooltipControllerTestHelper::GetTooltipWindow() { - return controller_->tooltip_window_; -} - -void TooltipControllerTestHelper::FireTooltipTimer() { - controller_->TooltipTimerFired(); -} - -bool TooltipControllerTestHelper::IsTooltipTimerRunning() { - return controller_->tooltip_timer_.IsRunning(); -} - -void TooltipControllerTestHelper::FireTooltipShownTimer() { - controller_->tooltip_shown_timer_.Stop(); - controller_->TooltipShownTimerFired(); -} - -bool TooltipControllerTestHelper::IsTooltipShownTimerRunning() { - return controller_->tooltip_shown_timer_.IsRunning(); -} - -bool TooltipControllerTestHelper::IsTooltipVisible() { - return controller_->IsTooltipVisible(); -} - -TooltipTestView::TooltipTestView() { -} - -TooltipTestView::~TooltipTestView() { -} - -bool TooltipTestView::GetTooltipText(const gfx::Point& p, - base::string16* tooltip) const { - *tooltip = tooltip_text_; - return true; -} - -} // namespace test -} // namespace corewm -} // namespace views
diff --git a/ui/views/corewm/tooltip_controller_test_helper.h b/ui/views/corewm/tooltip_controller_test_helper.h deleted file mode 100644 index 310a00c..0000000 --- a/ui/views/corewm/tooltip_controller_test_helper.h +++ /dev/null
@@ -1,73 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_COREWM_TOOLTIP_CONTROLLER_TEST_HELPER_H_ -#define UI_VIEWS_COREWM_TOOLTIP_CONTROLLER_TEST_HELPER_H_ - -#include "base/logging.h" -#include "base/strings/string16.h" -#include "ui/views/view.h" -#include "ui/views/views_export.h" - -namespace aura { -class Window; -} - -namespace views { -namespace corewm { - -class TooltipController; - -namespace test { - -// TooltipControllerTestHelper provides access to TooltipControllers private -// state. -class TooltipControllerTestHelper { - public: - explicit TooltipControllerTestHelper(TooltipController* controller); - ~TooltipControllerTestHelper(); - - TooltipController* controller() { return controller_; } - - // These are mostly cover methods for TooltipController private methods. - base::string16 GetTooltipText(); - aura::Window* GetTooltipWindow(); - void FireTooltipTimer(); - bool IsTooltipTimerRunning(); - void FireTooltipShownTimer(); - bool IsTooltipShownTimerRunning(); - bool IsTooltipVisible(); - - private: - TooltipController* controller_; - - DISALLOW_COPY_AND_ASSIGN(TooltipControllerTestHelper); -}; - -// Trivial View subclass that lets you set the tooltip text. -class TooltipTestView : public views::View { - public: - TooltipTestView(); - virtual ~TooltipTestView(); - - void set_tooltip_text(base::string16 tooltip_text) { - tooltip_text_ = tooltip_text; - } - - // Overridden from views::View - virtual bool GetTooltipText(const gfx::Point& p, - base::string16* tooltip) const override; - - private: - base::string16 tooltip_text_; - - DISALLOW_COPY_AND_ASSIGN(TooltipTestView); -}; - - -} // namespace test -} // namespace corewm -} // namespace views - -#endif // UI_VIEWS_COREWM_TOOLTIP_CONTROLLER_TEST_HELPER_H_
diff --git a/ui/views/corewm/tooltip_controller_unittest.cc b/ui/views/corewm/tooltip_controller_unittest.cc deleted file mode 100644 index e083439..0000000 --- a/ui/views/corewm/tooltip_controller_unittest.cc +++ /dev/null
@@ -1,832 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/corewm/tooltip_controller.h" - -#include "base/strings/utf_string_conversions.h" -#include "ui/aura/client/cursor_client.h" -#include "ui/aura/client/screen_position_client.h" -#include "ui/aura/env.h" -#include "ui/aura/test/aura_test_base.h" -#include "ui/aura/test/test_screen.h" -#include "ui/aura/test/test_window_delegate.h" -#include "ui/aura/window.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/events/test/event_generator.h" -#include "ui/gfx/font.h" -#include "ui/gfx/point.h" -#include "ui/gfx/screen.h" -#include "ui/gfx/screen_type_delegate.h" -#include "ui/gfx/text_elider.h" -#include "ui/views/corewm/tooltip_aura.h" -#include "ui/views/corewm/tooltip_controller_test_helper.h" -#include "ui/views/test/desktop_test_views_delegate.h" -#include "ui/views/test/test_views_delegate.h" -#include "ui/views/view.h" -#include "ui/views/widget/tooltip_manager.h" -#include "ui/views/widget/widget.h" -#include "ui/wm/core/default_activation_client.h" -#include "ui/wm/core/wm_state.h" -#include "ui/wm/public/tooltip_client.h" -#include "ui/wm/public/window_types.h" - -#if defined(OS_WIN) -#include "ui/base/win/scoped_ole_initializer.h" -#endif - -#if !defined(OS_CHROMEOS) -#include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" -#include "ui/views/widget/desktop_aura/desktop_screen.h" -#endif - -using base::ASCIIToUTF16; - -namespace views { -namespace corewm { -namespace test { -namespace { - -views::Widget* CreateWidget(aura::Window* root) { - views::Widget* widget = new views::Widget; - views::Widget::InitParams params; - params.type = views::Widget::InitParams::TYPE_WINDOW_FRAMELESS; - params.accept_events = true; - params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; -#if defined(OS_CHROMEOS) - params.parent = root; -#else - params.native_widget = new DesktopNativeWidgetAura(widget); -#endif - params.bounds = gfx::Rect(0, 0, 200, 100); - widget->Init(params); - widget->Show(); - return widget; -} - -TooltipController* GetController(Widget* widget) { - return static_cast<TooltipController*>( - aura::client::GetTooltipClient( - widget->GetNativeWindow()->GetRootWindow())); -} - -} // namespace - -class TooltipControllerTest : public aura::test::AuraTestBase { - public: - TooltipControllerTest() : view_(NULL) {} - virtual ~TooltipControllerTest() {} - - virtual void SetUp() override { -#if defined(OS_CHROMEOS) - views_delegate_.reset(new TestViewsDelegate); -#else - views_delegate_.reset(new DesktopTestViewsDelegate); -#endif - - aura::test::AuraTestBase::SetUp(); - new wm::DefaultActivationClient(root_window()); -#if defined(OS_CHROMEOS) - controller_.reset(new TooltipController( - scoped_ptr<views::corewm::Tooltip>( - new views::corewm::TooltipAura(gfx::SCREEN_TYPE_ALTERNATE)))); - root_window()->AddPreTargetHandler(controller_.get()); - SetTooltipClient(root_window(), controller_.get()); -#endif - widget_.reset(CreateWidget(root_window())); - widget_->SetContentsView(new View); - view_ = new TooltipTestView; - widget_->GetContentsView()->AddChildView(view_); - view_->SetBoundsRect(widget_->GetContentsView()->GetLocalBounds()); - helper_.reset(new TooltipControllerTestHelper( - GetController(widget_.get()))); - generator_.reset(new ui::test::EventGenerator(GetRootWindow())); - } - - virtual void TearDown() override { -#if defined(OS_CHROMEOS) - root_window()->RemovePreTargetHandler(controller_.get()); - aura::client::SetTooltipClient(root_window(), NULL); - controller_.reset(); -#endif - generator_.reset(); - helper_.reset(); - widget_.reset(); - aura::test::AuraTestBase::TearDown(); - views_delegate_.reset(); - } - - protected: - aura::Window* GetWindow() { - return widget_->GetNativeWindow(); - } - - aura::Window* GetRootWindow() { - return GetWindow()->GetRootWindow(); - } - - TooltipTestView* PrepareSecondView() { - TooltipTestView* view2 = new TooltipTestView; - widget_->GetContentsView()->AddChildView(view2); - view_->SetBounds(0, 0, 100, 100); - view2->SetBounds(100, 0, 100, 100); - return view2; - } - - scoped_ptr<views::Widget> widget_; - TooltipTestView* view_; - scoped_ptr<TooltipControllerTestHelper> helper_; - scoped_ptr<ui::test::EventGenerator> generator_; - - private: - scoped_ptr<TooltipController> controller_; - - scoped_ptr<views::TestViewsDelegate> views_delegate_; - -#if defined(OS_WIN) - ui::ScopedOleInitializer ole_initializer_; -#endif - - DISALLOW_COPY_AND_ASSIGN(TooltipControllerTest); -}; - -TEST_F(TooltipControllerTest, ViewTooltip) { - view_->set_tooltip_text(ASCIIToUTF16("Tooltip Text")); - EXPECT_EQ(base::string16(), helper_->GetTooltipText()); - EXPECT_EQ(NULL, helper_->GetTooltipWindow()); - generator_->MoveMouseToCenterOf(GetWindow()); - - EXPECT_EQ(GetWindow(), GetRootWindow()->GetEventHandlerForPoint( - generator_->current_location())); - base::string16 expected_tooltip = ASCIIToUTF16("Tooltip Text"); - EXPECT_EQ(expected_tooltip, aura::client::GetTooltipText(GetWindow())); - EXPECT_EQ(base::string16(), helper_->GetTooltipText()); - EXPECT_EQ(GetWindow(), helper_->GetTooltipWindow()); - - // Fire tooltip timer so tooltip becomes visible. - helper_->FireTooltipTimer(); - - EXPECT_TRUE(helper_->IsTooltipVisible()); - generator_->MoveMouseBy(1, 0); - - EXPECT_TRUE(helper_->IsTooltipVisible()); - EXPECT_EQ(expected_tooltip, aura::client::GetTooltipText(GetWindow())); - EXPECT_EQ(expected_tooltip, helper_->GetTooltipText()); - EXPECT_EQ(GetWindow(), helper_->GetTooltipWindow()); -} - -TEST_F(TooltipControllerTest, TooltipsInMultipleViews) { - view_->set_tooltip_text(ASCIIToUTF16("Tooltip Text")); - EXPECT_EQ(base::string16(), helper_->GetTooltipText()); - EXPECT_EQ(NULL, helper_->GetTooltipWindow()); - - PrepareSecondView(); - aura::Window* window = GetWindow(); - aura::Window* root_window = GetRootWindow(); - - // Fire tooltip timer so tooltip becomes visible. - generator_->MoveMouseRelativeTo(window, view_->bounds().CenterPoint()); - helper_->FireTooltipTimer(); - EXPECT_TRUE(helper_->IsTooltipVisible()); - for (int i = 0; i < 49; ++i) { - generator_->MoveMouseBy(1, 0); - EXPECT_TRUE(helper_->IsTooltipVisible()); - EXPECT_EQ(window, root_window->GetEventHandlerForPoint( - generator_->current_location())); - base::string16 expected_tooltip = ASCIIToUTF16("Tooltip Text"); - EXPECT_EQ(expected_tooltip, aura::client::GetTooltipText(window)); - EXPECT_EQ(expected_tooltip, helper_->GetTooltipText()); - EXPECT_EQ(window, helper_->GetTooltipWindow()); - } - for (int i = 0; i < 49; ++i) { - generator_->MoveMouseBy(1, 0); - EXPECT_FALSE(helper_->IsTooltipVisible()); - EXPECT_EQ(window, root_window->GetEventHandlerForPoint( - generator_->current_location())); - base::string16 expected_tooltip; // = "" - EXPECT_EQ(expected_tooltip, aura::client::GetTooltipText(window)); - EXPECT_EQ(expected_tooltip, helper_->GetTooltipText()); - EXPECT_EQ(window, helper_->GetTooltipWindow()); - } -} - -TEST_F(TooltipControllerTest, EnableOrDisableTooltips) { - view_->set_tooltip_text(ASCIIToUTF16("Tooltip Text")); - EXPECT_EQ(base::string16(), helper_->GetTooltipText()); - EXPECT_EQ(NULL, helper_->GetTooltipWindow()); - - generator_->MoveMouseRelativeTo(GetWindow(), view_->bounds().CenterPoint()); - base::string16 expected_tooltip = ASCIIToUTF16("Tooltip Text"); - - // Fire tooltip timer so tooltip becomes visible. - helper_->FireTooltipTimer(); - EXPECT_TRUE(helper_->IsTooltipVisible()); - - // Disable tooltips and check again. - helper_->controller()->SetTooltipsEnabled(false); - EXPECT_FALSE(helper_->IsTooltipVisible()); - helper_->FireTooltipTimer(); - EXPECT_FALSE(helper_->IsTooltipVisible()); - - // Enable tooltips back and check again. - helper_->controller()->SetTooltipsEnabled(true); - EXPECT_FALSE(helper_->IsTooltipVisible()); - helper_->FireTooltipTimer(); - EXPECT_TRUE(helper_->IsTooltipVisible()); -} - -// Verifies tooltip isn't shown if tooltip text consists entirely of whitespace. -TEST_F(TooltipControllerTest, DontShowEmptyTooltips) { - view_->set_tooltip_text(ASCIIToUTF16(" ")); - EXPECT_EQ(base::string16(), helper_->GetTooltipText()); - EXPECT_EQ(NULL, helper_->GetTooltipWindow()); - - generator_->MoveMouseRelativeTo(GetWindow(), view_->bounds().CenterPoint()); - - helper_->FireTooltipTimer(); - EXPECT_FALSE(helper_->IsTooltipVisible()); -} - -TEST_F(TooltipControllerTest, TooltipHidesOnKeyPressAndStaysHiddenUntilChange) { - view_->set_tooltip_text(ASCIIToUTF16("Tooltip Text for view 1")); - EXPECT_EQ(base::string16(), helper_->GetTooltipText()); - EXPECT_EQ(NULL, helper_->GetTooltipWindow()); - - TooltipTestView* view2 = PrepareSecondView(); - view2->set_tooltip_text(ASCIIToUTF16("Tooltip Text for view 2")); - - aura::Window* window = GetWindow(); - - // Fire tooltip timer so tooltip becomes visible. - generator_->MoveMouseRelativeTo(window, view_->bounds().CenterPoint()); - helper_->FireTooltipTimer(); - EXPECT_TRUE(helper_->IsTooltipVisible()); - EXPECT_TRUE(helper_->IsTooltipShownTimerRunning()); - - generator_->PressKey(ui::VKEY_1, 0); - EXPECT_FALSE(helper_->IsTooltipVisible()); - EXPECT_FALSE(helper_->IsTooltipTimerRunning()); - EXPECT_FALSE(helper_->IsTooltipShownTimerRunning()); - - // Moving the mouse inside |view1| should not change the state of the tooltip - // or the timers. - for (int i = 0; i < 49; i++) { - generator_->MoveMouseBy(1, 0); - EXPECT_FALSE(helper_->IsTooltipVisible()); - EXPECT_FALSE(helper_->IsTooltipTimerRunning()); - EXPECT_FALSE(helper_->IsTooltipShownTimerRunning()); - EXPECT_EQ(window, - GetRootWindow()->GetEventHandlerForPoint( - generator_->current_location())); - base::string16 expected_tooltip = ASCIIToUTF16("Tooltip Text for view 1"); - EXPECT_EQ(expected_tooltip, aura::client::GetTooltipText(window)); - EXPECT_EQ(expected_tooltip, helper_->GetTooltipText()); - EXPECT_EQ(window, helper_->GetTooltipWindow()); - } - - // Now we move the mouse on to |view2|. It should re-start the tooltip timer. - generator_->MoveMouseBy(1, 0); - EXPECT_TRUE(helper_->IsTooltipTimerRunning()); - helper_->FireTooltipTimer(); - EXPECT_TRUE(helper_->IsTooltipVisible()); - EXPECT_TRUE(helper_->IsTooltipShownTimerRunning()); - base::string16 expected_tooltip = ASCIIToUTF16("Tooltip Text for view 2"); - EXPECT_EQ(expected_tooltip, aura::client::GetTooltipText(window)); - EXPECT_EQ(expected_tooltip, helper_->GetTooltipText()); - EXPECT_EQ(window, helper_->GetTooltipWindow()); -} - -TEST_F(TooltipControllerTest, TooltipHidesOnTimeoutAndStaysHiddenUntilChange) { - view_->set_tooltip_text(ASCIIToUTF16("Tooltip Text for view 1")); - EXPECT_EQ(base::string16(), helper_->GetTooltipText()); - EXPECT_EQ(NULL, helper_->GetTooltipWindow()); - - TooltipTestView* view2 = PrepareSecondView(); - view2->set_tooltip_text(ASCIIToUTF16("Tooltip Text for view 2")); - - aura::Window* window = GetWindow(); - - // Fire tooltip timer so tooltip becomes visible. - generator_->MoveMouseRelativeTo(window, view_->bounds().CenterPoint()); - helper_->FireTooltipTimer(); - EXPECT_TRUE(helper_->IsTooltipVisible()); - EXPECT_TRUE(helper_->IsTooltipShownTimerRunning()); - - helper_->FireTooltipShownTimer(); - EXPECT_FALSE(helper_->IsTooltipVisible()); - EXPECT_FALSE(helper_->IsTooltipTimerRunning()); - EXPECT_FALSE(helper_->IsTooltipShownTimerRunning()); - - // Moving the mouse inside |view1| should not change the state of the tooltip - // or the timers. - for (int i = 0; i < 49; ++i) { - generator_->MoveMouseBy(1, 0); - EXPECT_FALSE(helper_->IsTooltipVisible()); - EXPECT_FALSE(helper_->IsTooltipTimerRunning()); - EXPECT_FALSE(helper_->IsTooltipShownTimerRunning()); - EXPECT_EQ(window, GetRootWindow()->GetEventHandlerForPoint( - generator_->current_location())); - base::string16 expected_tooltip = ASCIIToUTF16("Tooltip Text for view 1"); - EXPECT_EQ(expected_tooltip, aura::client::GetTooltipText(window)); - EXPECT_EQ(expected_tooltip, helper_->GetTooltipText()); - EXPECT_EQ(window, helper_->GetTooltipWindow()); - } - - // Now we move the mouse on to |view2|. It should re-start the tooltip timer. - generator_->MoveMouseBy(1, 0); - EXPECT_TRUE(helper_->IsTooltipTimerRunning()); - helper_->FireTooltipTimer(); - EXPECT_TRUE(helper_->IsTooltipVisible()); - EXPECT_TRUE(helper_->IsTooltipShownTimerRunning()); - base::string16 expected_tooltip = ASCIIToUTF16("Tooltip Text for view 2"); - EXPECT_EQ(expected_tooltip, aura::client::GetTooltipText(window)); - EXPECT_EQ(expected_tooltip, helper_->GetTooltipText()); - EXPECT_EQ(window, helper_->GetTooltipWindow()); -} - -// Verifies a mouse exit event hides the tooltips. -TEST_F(TooltipControllerTest, HideOnExit) { - view_->set_tooltip_text(ASCIIToUTF16("Tooltip Text")); - generator_->MoveMouseToCenterOf(GetWindow()); - base::string16 expected_tooltip = ASCIIToUTF16("Tooltip Text"); - EXPECT_EQ(expected_tooltip, aura::client::GetTooltipText(GetWindow())); - EXPECT_EQ(base::string16(), helper_->GetTooltipText()); - EXPECT_EQ(GetWindow(), helper_->GetTooltipWindow()); - - // Fire tooltip timer so tooltip becomes visible. - helper_->FireTooltipTimer(); - - EXPECT_TRUE(helper_->IsTooltipVisible()); - generator_->SendMouseExit(); - EXPECT_FALSE(helper_->IsTooltipVisible()); -} - -TEST_F(TooltipControllerTest, ReshowOnClickAfterEnterExit) { - // Owned by |view_|. - TooltipTestView* v1 = new TooltipTestView; - TooltipTestView* v2 = new TooltipTestView; - view_->AddChildView(v1); - view_->AddChildView(v2); - gfx::Rect view_bounds(view_->GetLocalBounds()); - view_bounds.set_height(view_bounds.height() / 2); - v1->SetBoundsRect(view_bounds); - view_bounds.set_y(view_bounds.height()); - v2->SetBoundsRect(view_bounds); - const base::string16 v1_tt(ASCIIToUTF16("v1")); - const base::string16 v2_tt(ASCIIToUTF16("v2")); - v1->set_tooltip_text(v1_tt); - v2->set_tooltip_text(v2_tt); - - gfx::Point v1_point(1, 1); - View::ConvertPointToWidget(v1, &v1_point); - generator_->MoveMouseRelativeTo(GetWindow(), v1_point); - - // Fire tooltip timer so tooltip becomes visible. - helper_->FireTooltipTimer(); - EXPECT_TRUE(helper_->IsTooltipVisible()); - EXPECT_EQ(v1_tt, helper_->GetTooltipText()); - - // Press the mouse, move to v2 and back to v1. - generator_->ClickLeftButton(); - - gfx::Point v2_point(1, 1); - View::ConvertPointToWidget(v2, &v2_point); - generator_->MoveMouseRelativeTo(GetWindow(), v2_point); - generator_->MoveMouseRelativeTo(GetWindow(), v1_point); - - helper_->FireTooltipTimer(); - EXPECT_TRUE(helper_->IsTooltipVisible()); - EXPECT_EQ(v1_tt, helper_->GetTooltipText()); -} - -namespace { - -// Returns the index of |window| in its parent's children. -int IndexInParent(const aura::Window* window) { - aura::Window::Windows::const_iterator i = - std::find(window->parent()->children().begin(), - window->parent()->children().end(), - window); - return i == window->parent()->children().end() ? -1 : - static_cast<int>(i - window->parent()->children().begin()); -} - -class TestScreenPositionClient : public aura::client::ScreenPositionClient { - public: - TestScreenPositionClient() {} - virtual ~TestScreenPositionClient() {} - - // ScreenPositionClient overrides: - virtual void ConvertPointToScreen(const aura::Window* window, - gfx::Point* point) override { - } - virtual void ConvertPointFromScreen(const aura::Window* window, - gfx::Point* point) override { - } - virtual void ConvertHostPointToScreen(aura::Window* root_gwindow, - gfx::Point* point) override { - NOTREACHED(); - } - virtual void SetBounds(aura::Window* window, - const gfx::Rect& bounds, - const gfx::Display& display) override { - window->SetBounds(bounds); - } - - private: - DISALLOW_COPY_AND_ASSIGN(TestScreenPositionClient); -}; - -} // namespace - -class TooltipControllerCaptureTest : public TooltipControllerTest { - public: - TooltipControllerCaptureTest() {} - virtual ~TooltipControllerCaptureTest() {} - - virtual void SetUp() override { - TooltipControllerTest::SetUp(); - aura::client::SetScreenPositionClient(GetRootWindow(), - &screen_position_client_); -#if !defined(OS_CHROMEOS) - desktop_screen_.reset(CreateDesktopScreen()); - gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE, - desktop_screen_.get()); -#endif - } - - virtual void TearDown() override { -#if !defined(OS_CHROMEOS) - gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE, test_screen()); - desktop_screen_.reset(); -#endif - aura::client::SetScreenPositionClient(GetRootWindow(), NULL); - TooltipControllerTest::TearDown(); - } - - private: - TestScreenPositionClient screen_position_client_; - scoped_ptr<gfx::Screen> desktop_screen_; - - DISALLOW_COPY_AND_ASSIGN(TooltipControllerCaptureTest); -}; - -// Verifies when capture is released the TooltipController resets state. -// Flaky on all builders. http://crbug.com/388268 -TEST_F(TooltipControllerCaptureTest, DISABLED_CloseOnCaptureLost) { - view_->GetWidget()->SetCapture(view_); - RunAllPendingInMessageLoop(); - view_->set_tooltip_text(ASCIIToUTF16("Tooltip Text")); - generator_->MoveMouseToCenterOf(GetWindow()); - base::string16 expected_tooltip = ASCIIToUTF16("Tooltip Text"); - EXPECT_EQ(expected_tooltip, aura::client::GetTooltipText(GetWindow())); - EXPECT_EQ(base::string16(), helper_->GetTooltipText()); - EXPECT_EQ(GetWindow(), helper_->GetTooltipWindow()); - - // Fire tooltip timer so tooltip becomes visible. - helper_->FireTooltipTimer(); - - EXPECT_TRUE(helper_->IsTooltipVisible()); - view_->GetWidget()->ReleaseCapture(); - EXPECT_FALSE(helper_->IsTooltipVisible()); - EXPECT_TRUE(helper_->GetTooltipWindow() == NULL); -} - -// Disabled on linux as DesktopScreenX11::GetWindowAtScreenPoint() doesn't -// consider z-order. -#if defined(OS_LINUX) && !defined(OS_CHROMEOS) -#define MAYBE_Capture DISABLED_Capture -#else -#define MAYBE_Capture Capture -#endif -// Verifies the correct window is found for tooltips when there is a capture. -TEST_F(TooltipControllerCaptureTest, MAYBE_Capture) { - const base::string16 tooltip_text(ASCIIToUTF16("1")); - const base::string16 tooltip_text2(ASCIIToUTF16("2")); - - widget_->SetBounds(gfx::Rect(0, 0, 200, 200)); - view_->set_tooltip_text(tooltip_text); - - scoped_ptr<views::Widget> widget2(CreateWidget(root_window())); - widget2->SetContentsView(new View); - TooltipTestView* view2 = new TooltipTestView; - widget2->GetContentsView()->AddChildView(view2); - view2->set_tooltip_text(tooltip_text2); - widget2->SetBounds(gfx::Rect(0, 0, 200, 200)); - view2->SetBoundsRect(widget2->GetContentsView()->GetLocalBounds()); - - widget_->SetCapture(view_); - EXPECT_TRUE(widget_->HasCapture()); - widget2->Show(); - EXPECT_GE(IndexInParent(widget2->GetNativeWindow()), - IndexInParent(widget_->GetNativeWindow())); - - generator_->MoveMouseRelativeTo(widget_->GetNativeWindow(), - view_->bounds().CenterPoint()); - - EXPECT_TRUE(helper_->IsTooltipTimerRunning()); - helper_->FireTooltipTimer(); - // Even though the mouse is over a window with a tooltip it shouldn't be - // picked up because the windows don't have the same value for - // |TooltipManager::kGroupingPropertyKey|. - EXPECT_TRUE(helper_->GetTooltipText().empty()); - - // Now make both the windows have same transient value for - // kGroupingPropertyKey. In this case the tooltip should be picked up from - // |widget2| (because the mouse is over it). - const int grouping_key = 1; - widget_->SetNativeWindowProperty(TooltipManager::kGroupingPropertyKey, - reinterpret_cast<void*>(grouping_key)); - widget2->SetNativeWindowProperty(TooltipManager::kGroupingPropertyKey, - reinterpret_cast<void*>(grouping_key)); - generator_->MoveMouseBy(1, 10); - EXPECT_TRUE(helper_->IsTooltipTimerRunning()); - helper_->FireTooltipTimer(); - EXPECT_EQ(tooltip_text2, helper_->GetTooltipText()); - - widget2.reset(); -} - -namespace { - -class TestTooltip : public Tooltip { - public: - TestTooltip() : is_visible_(false) {} - virtual ~TestTooltip() {} - - const base::string16& tooltip_text() const { return tooltip_text_; } - - // Tooltip: - virtual void SetText(aura::Window* window, - const base::string16& tooltip_text, - const gfx::Point& location) override { - tooltip_text_ = tooltip_text; - location_ = location; - } - virtual void Show() override { - is_visible_ = true; - } - virtual void Hide() override { - is_visible_ = false; - } - virtual bool IsVisible() override { - return is_visible_; - } - const gfx::Point& location() { return location_; } - - private: - bool is_visible_; - base::string16 tooltip_text_; - gfx::Point location_; - - DISALLOW_COPY_AND_ASSIGN(TestTooltip); -}; - -} // namespace - -// Use for tests that don't depend upon views. -class TooltipControllerTest2 : public aura::test::AuraTestBase { - public: - TooltipControllerTest2() : test_tooltip_(new TestTooltip) {} - virtual ~TooltipControllerTest2() {} - - virtual void SetUp() override { - wm_state_.reset(new wm::WMState); - aura::test::AuraTestBase::SetUp(); - new wm::DefaultActivationClient(root_window()); - controller_.reset(new TooltipController( - scoped_ptr<corewm::Tooltip>(test_tooltip_))); - root_window()->AddPreTargetHandler(controller_.get()); - SetTooltipClient(root_window(), controller_.get()); - helper_.reset(new TooltipControllerTestHelper(controller_.get())); - generator_.reset(new ui::test::EventGenerator(root_window())); - } - - virtual void TearDown() override { - root_window()->RemovePreTargetHandler(controller_.get()); - aura::client::SetTooltipClient(root_window(), NULL); - controller_.reset(); - generator_.reset(); - helper_.reset(); - aura::test::AuraTestBase::TearDown(); - wm_state_.reset(); - } - - protected: - // Owned by |controller_|. - TestTooltip* test_tooltip_; - scoped_ptr<TooltipControllerTestHelper> helper_; - scoped_ptr<ui::test::EventGenerator> generator_; - - private: - scoped_ptr<TooltipController> controller_; - scoped_ptr<wm::WMState> wm_state_; - - DISALLOW_COPY_AND_ASSIGN(TooltipControllerTest2); -}; - -TEST_F(TooltipControllerTest2, VerifyLeadingTrailingWhitespaceStripped) { - aura::test::TestWindowDelegate test_delegate; - scoped_ptr<aura::Window> window( - CreateNormalWindow(100, root_window(), &test_delegate)); - window->SetBounds(gfx::Rect(0, 0, 300, 300)); - base::string16 tooltip_text(ASCIIToUTF16(" \nx ")); - aura::client::SetTooltipText(window.get(), &tooltip_text); - generator_->MoveMouseToCenterOf(window.get()); - helper_->FireTooltipTimer(); - EXPECT_EQ(ASCIIToUTF16("x"), test_tooltip_->tooltip_text()); -} - -// Verifies that tooltip is hidden and tooltip window closed upon cancel mode. -TEST_F(TooltipControllerTest2, CloseOnCancelMode) { - aura::test::TestWindowDelegate test_delegate; - scoped_ptr<aura::Window> window( - CreateNormalWindow(100, root_window(), &test_delegate)); - window->SetBounds(gfx::Rect(0, 0, 300, 300)); - base::string16 tooltip_text(ASCIIToUTF16("Tooltip Text")); - aura::client::SetTooltipText(window.get(), &tooltip_text); - generator_->MoveMouseToCenterOf(window.get()); - - // Fire tooltip timer so tooltip becomes visible. - helper_->FireTooltipTimer(); - EXPECT_TRUE(helper_->IsTooltipVisible()); - - // Send OnCancelMode event and verify that tooltip becomes invisible and - // the tooltip window is closed. - ui::CancelModeEvent event; - helper_->controller()->OnCancelMode(&event); - EXPECT_FALSE(helper_->IsTooltipVisible()); - EXPECT_TRUE(helper_->GetTooltipWindow() == NULL); -} - -// Use for tests that need both views and a TestTooltip. -class TooltipControllerTest3 : public aura::test::AuraTestBase { - public: - TooltipControllerTest3() : test_tooltip_(new TestTooltip) {} - virtual ~TooltipControllerTest3() {} - - virtual void SetUp() override { - wm_state_.reset(new wm::WMState); - aura::test::AuraTestBase::SetUp(); - new wm::DefaultActivationClient(root_window()); - - widget_.reset(CreateWidget(root_window())); - widget_->SetContentsView(new View); - view_ = new TooltipTestView; - widget_->GetContentsView()->AddChildView(view_); - view_->SetBoundsRect(widget_->GetContentsView()->GetLocalBounds()); - - generator_.reset(new ui::test::EventGenerator(GetRootWindow())); - controller_.reset(new TooltipController( - scoped_ptr<views::corewm::Tooltip>(test_tooltip_))); - GetRootWindow()->RemovePreTargetHandler( - static_cast<TooltipController*>(aura::client::GetTooltipClient( - widget_->GetNativeWindow()->GetRootWindow()))); - GetRootWindow()->AddPreTargetHandler(controller_.get()); - helper_.reset(new TooltipControllerTestHelper(controller_.get())); - SetTooltipClient(GetRootWindow(), controller_.get()); - } - - virtual void TearDown() override { - GetRootWindow()->RemovePreTargetHandler(controller_.get()); - aura::client::SetTooltipClient(GetRootWindow(), NULL); - - controller_.reset(); - generator_.reset(); - helper_.reset(); - widget_.reset(); - aura::test::AuraTestBase::TearDown(); - wm_state_.reset(); - } - - aura::Window* GetWindow() { return widget_->GetNativeWindow(); } - - protected: - // Owned by |controller_|. - TestTooltip* test_tooltip_; - scoped_ptr<TooltipControllerTestHelper> helper_; - scoped_ptr<ui::test::EventGenerator> generator_; - scoped_ptr<views::Widget> widget_; - TooltipTestView* view_; - - private: - scoped_ptr<TooltipController> controller_; - scoped_ptr<wm::WMState> wm_state_; - -#if defined(OS_WIN) - ui::ScopedOleInitializer ole_initializer_; -#endif - - aura::Window* GetRootWindow() { return GetWindow()->GetRootWindow(); } - - DISALLOW_COPY_AND_ASSIGN(TooltipControllerTest3); -}; - -TEST_F(TooltipControllerTest3, TooltipPositionChangesOnTwoViewsWithSameLabel) { - // Owned by |view_|. - // These two views have the same tooltip text - TooltipTestView* v1 = new TooltipTestView; - TooltipTestView* v2 = new TooltipTestView; - // v1_1 is a view inside v1 that has an identical tooltip text to that of v1 - // and v2 - TooltipTestView* v1_1 = new TooltipTestView; - // v2_1 is a view inside v2 that has an identical tooltip text to that of v1 - // and v2 - TooltipTestView* v2_1 = new TooltipTestView; - // v2_2 is a view inside v2 with the tooltip text different from all the - // others - TooltipTestView* v2_2 = new TooltipTestView; - - // Setup all the views' relations - view_->AddChildView(v1); - view_->AddChildView(v2); - v1->AddChildView(v1_1); - v2->AddChildView(v2_1); - v2->AddChildView(v2_2); - const base::string16 reference_string( - base::ASCIIToUTF16("Identical Tooltip Text")); - const base::string16 alternative_string( - base::ASCIIToUTF16("Another Shrubbery")); - v1->set_tooltip_text(reference_string); - v2->set_tooltip_text(reference_string); - v1_1->set_tooltip_text(reference_string); - v2_1->set_tooltip_text(reference_string); - v2_2->set_tooltip_text(alternative_string); - - // Set views' bounds - gfx::Rect view_bounds(view_->GetLocalBounds()); - view_bounds.set_height(view_bounds.height() / 2); - v1->SetBoundsRect(view_bounds); - v1_1->SetBounds(0, 0, 3, 3); - view_bounds.set_y(view_bounds.height()); - v2->SetBoundsRect(view_bounds); - v2_2->SetBounds(view_bounds.width() - 3, view_bounds.height() - 3, 3, 3); - v2_1->SetBounds(0, 0, 3, 3); - - // Test whether a toolbar appears on v1 - gfx::Point center = v1->bounds().CenterPoint(); - generator_->MoveMouseRelativeTo(GetWindow(), center); - helper_->FireTooltipTimer(); - EXPECT_TRUE(helper_->IsTooltipVisible()); - EXPECT_EQ(reference_string, helper_->GetTooltipText()); - gfx::Point tooltip_bounds1 = test_tooltip_->location(); - - // Test whether the toolbar changes position on mouse over v2 - center = v2->bounds().CenterPoint(); - generator_->MoveMouseRelativeTo(GetWindow(), center); - helper_->FireTooltipTimer(); - EXPECT_TRUE(helper_->IsTooltipVisible()); - EXPECT_EQ(reference_string, helper_->GetTooltipText()); - gfx::Point tooltip_bounds2 = test_tooltip_->location(); - - EXPECT_NE(tooltip_bounds1, gfx::Point()); - EXPECT_NE(tooltip_bounds2, gfx::Point()); - EXPECT_NE(tooltip_bounds1, tooltip_bounds2); - - // Test if the toolbar does not change position on encountering a contained - // view with the same tooltip text - center = v2_1->GetLocalBounds().CenterPoint(); - views::View::ConvertPointToTarget(v2_1, view_, ¢er); - generator_->MoveMouseRelativeTo(GetWindow(), center); - helper_->FireTooltipTimer(); - gfx::Point tooltip_bounds2_1 = test_tooltip_->location(); - - EXPECT_NE(tooltip_bounds2, tooltip_bounds2_1); - EXPECT_TRUE(helper_->IsTooltipVisible()); - EXPECT_EQ(reference_string, helper_->GetTooltipText()); - - // Test if the toolbar changes position on encountering a contained - // view with a different tooltip text - center = v2_2->GetLocalBounds().CenterPoint(); - views::View::ConvertPointToTarget(v2_2, view_, ¢er); - generator_->MoveMouseRelativeTo(GetWindow(), center); - helper_->FireTooltipTimer(); - gfx::Point tooltip_bounds2_2 = test_tooltip_->location(); - - EXPECT_NE(tooltip_bounds2_1, tooltip_bounds2_2); - EXPECT_TRUE(helper_->IsTooltipVisible()); - EXPECT_EQ(alternative_string, helper_->GetTooltipText()); - - // Test if moving from a view that is contained by a larger view, both with - // the same tooltip text, does not change tooltip's position. - center = v1_1->GetLocalBounds().CenterPoint(); - views::View::ConvertPointToTarget(v1_1, view_, ¢er); - generator_->MoveMouseRelativeTo(GetWindow(), center); - helper_->FireTooltipTimer(); - gfx::Point tooltip_bounds1_1 = test_tooltip_->location(); - - EXPECT_TRUE(helper_->IsTooltipVisible()); - EXPECT_EQ(reference_string, helper_->GetTooltipText()); - - center = v1->bounds().CenterPoint(); - generator_->MoveMouseRelativeTo(GetWindow(), center); - helper_->FireTooltipTimer(); - tooltip_bounds1 = test_tooltip_->location(); - - EXPECT_NE(tooltip_bounds1_1, tooltip_bounds1); - EXPECT_EQ(reference_string, helper_->GetTooltipText()); -} - -} // namespace test -} // namespace corewm -} // namespace views
diff --git a/ui/views/corewm/tooltip_win.cc b/ui/views/corewm/tooltip_win.cc deleted file mode 100644 index 4d2a4ba..0000000 --- a/ui/views/corewm/tooltip_win.cc +++ /dev/null
@@ -1,151 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/corewm/tooltip_win.h" - -#include <winuser.h> - -#include "base/debug/stack_trace.h" -#include "base/i18n/rtl.h" -#include "base/logging.h" -#include "ui/base/l10n/l10n_util_win.h" -#include "ui/gfx/rect.h" -#include "ui/gfx/screen.h" -#include "ui/gfx/win/dpi.h" -#include "ui/views/corewm/cursor_height_provider_win.h" - -namespace views { -namespace corewm { - -TooltipWin::TooltipWin(HWND parent) - : parent_hwnd_(parent), - tooltip_hwnd_(NULL), - showing_(false) { - memset(&toolinfo_, 0, sizeof(toolinfo_)); - toolinfo_.cbSize = sizeof(toolinfo_); - toolinfo_.uFlags = TTF_IDISHWND | TTF_TRACK | TTF_ABSOLUTE; - toolinfo_.uId = reinterpret_cast<UINT_PTR>(parent_hwnd_); - toolinfo_.hwnd = parent_hwnd_; - toolinfo_.lpszText = NULL; - toolinfo_.lpReserved = NULL; - SetRectEmpty(&toolinfo_.rect); -} - -TooltipWin::~TooltipWin() { - if (tooltip_hwnd_) - DestroyWindow(tooltip_hwnd_); -} - -bool TooltipWin::HandleNotify(int w_param, NMHDR* l_param, LRESULT* l_result) { - if (tooltip_hwnd_ == NULL) - return false; - - switch (l_param->code) { - case TTN_POP: - showing_ = false; - return true; - case TTN_SHOW: - *l_result = TRUE; - PositionTooltip(); - showing_ = true; - return true; - default: - break; - } - return false; -} - -bool TooltipWin::EnsureTooltipWindow() { - if (tooltip_hwnd_) - return true; - - tooltip_hwnd_ = CreateWindowEx( - WS_EX_TRANSPARENT | l10n_util::GetExtendedTooltipStyles(), - TOOLTIPS_CLASS, NULL, TTS_NOPREFIX | WS_POPUP, 0, 0, 0, 0, - parent_hwnd_, NULL, NULL, NULL); - if (!tooltip_hwnd_) { - PLOG(WARNING) << "tooltip creation failed, disabling tooltips"; - return false; - } - - l10n_util::AdjustUIFontForWindow(tooltip_hwnd_); - - SendMessage(tooltip_hwnd_, TTM_ADDTOOL, 0, - reinterpret_cast<LPARAM>(&toolinfo_)); - return true; -} - -void TooltipWin::PositionTooltip() { - // This code only runs for non-metro, so GetNativeScreen() is fine. - gfx::Point screen_point = gfx::win::DIPToScreenPoint(location_); - const int cursoroffset = GetCurrentCursorVisibleHeight(); - screen_point.Offset(0, cursoroffset); - - DWORD tooltip_size = SendMessage(tooltip_hwnd_, TTM_GETBUBBLESIZE, 0, - reinterpret_cast<LPARAM>(&toolinfo_)); - const gfx::Size size(LOWORD(tooltip_size), HIWORD(tooltip_size)); - - const gfx::Display display( - gfx::Screen::GetNativeScreen()->GetDisplayNearestPoint(screen_point)); - - gfx::Rect tooltip_bounds(screen_point, size); - tooltip_bounds.AdjustToFit(gfx::win::DIPToScreenRect(display.work_area())); - SetWindowPos(tooltip_hwnd_, NULL, tooltip_bounds.x(), tooltip_bounds.y(), 0, - 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE); -} - -void TooltipWin::SetText(aura::Window* window, - const base::string16& tooltip_text, - const gfx::Point& location) { - if (!EnsureTooltipWindow()) - return; - - // See comment in header for details on why |location_| is needed. - location_ = location; - - // Without this we get a flicker of the tooltip appearing at 0x0. Not sure - // why. - SetWindowPos(tooltip_hwnd_, NULL, 0, 0, 0, 0, - SWP_HIDEWINDOW | SWP_NOACTIVATE | SWP_NOMOVE | - SWP_NOREPOSITION | SWP_NOSIZE | SWP_NOZORDER); - - base::string16 adjusted_text(tooltip_text); - base::i18n::AdjustStringForLocaleDirection(&adjusted_text); - toolinfo_.lpszText = const_cast<WCHAR*>(adjusted_text.c_str()); - SendMessage(tooltip_hwnd_, TTM_SETTOOLINFO, 0, - reinterpret_cast<LPARAM>(&toolinfo_)); - - // This code only runs for non-metro, so GetNativeScreen() is fine. - const gfx::Point screen_point = gfx::win::DIPToScreenPoint(location_); - gfx::Display display( - gfx::Screen::GetNativeScreen()->GetDisplayNearestPoint(screen_point)); - const gfx::Rect monitor_bounds = display.bounds(); - int max_width = (monitor_bounds.width() + 1) / 2; - SendMessage(tooltip_hwnd_, TTM_SETMAXTIPWIDTH, 0, max_width); -} - -void TooltipWin::Show() { - if (!EnsureTooltipWindow()) - return; - - SendMessage(tooltip_hwnd_, TTM_TRACKACTIVATE, - TRUE, reinterpret_cast<LPARAM>(&toolinfo_)); - SetWindowPos(tooltip_hwnd_, HWND_TOPMOST, 0, 0, 0, 0, - SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOSIZE); -} - -void TooltipWin::Hide() { - if (!tooltip_hwnd_) - return; - - SendMessage(tooltip_hwnd_, TTM_TRACKACTIVATE, FALSE, - reinterpret_cast<LPARAM>(&toolinfo_)); -} - -bool TooltipWin::IsVisible() { - return showing_; -} - -} // namespace corewm -} // namespace views
diff --git a/ui/views/corewm/tooltip_win.h b/ui/views/corewm/tooltip_win.h deleted file mode 100644 index 23ee640..0000000 --- a/ui/views/corewm/tooltip_win.h +++ /dev/null
@@ -1,70 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_COREWM_TOOLTIP_WIN_H_ -#define UI_VIEWS_COREWM_TOOLTIP_WIN_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/strings/string16.h" -#include "ui/gfx/point.h" -#include "ui/views/corewm/tooltip.h" - -#include <windows.h> -#include <commctrl.h> - -namespace views { -namespace corewm { - -// Implementation of Tooltip that uses the native win32 control for showing the -// tooltip. -class VIEWS_EXPORT TooltipWin : public Tooltip { - public: - explicit TooltipWin(HWND parent); - virtual ~TooltipWin(); - - // HandleNotify() is forwarded from DesktopWindowTreeHostWin to keep the - // native tooltip in sync. - bool HandleNotify(int w_param, NMHDR* l_param, LRESULT* l_result); - - private: - // Ensures |tooltip_hwnd_| is valid. Returns true if valid, false if there - // a problem creating |tooltip_hwnd_|. - bool EnsureTooltipWindow(); - - // Sets the position of the tooltip. - void PositionTooltip(); - - // Tooltip: - virtual void SetText(aura::Window* window, - const base::string16& tooltip_text, - const gfx::Point& location) override; - virtual void Show() override; - virtual void Hide() override; - virtual bool IsVisible() override; - - // The window |tooltip_hwnd_| is parented to. - HWND parent_hwnd_; - - // Shows the tooltip. - HWND tooltip_hwnd_; - - // Used to modify the tooltip. - TOOLINFO toolinfo_; - - // Is the tooltip showing? - bool showing_; - - // Location to show the tooltip at. In order to position the tooltip we need - // to know the size. The size is only available from TTN_SHOW, so we have to - // cache it. - gfx::Point location_; - - DISALLOW_COPY_AND_ASSIGN(TooltipWin); -}; - -} // namespace corewm -} // namespace views - -#endif // UI_VIEWS_COREWM_TOOLTIP_WIN_H_
diff --git a/ui/views/cull_set.cc b/ui/views/cull_set.cc deleted file mode 100644 index 65566e0..0000000 --- a/ui/views/cull_set.cc +++ /dev/null
@@ -1,26 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/cull_set.h" - -namespace views { - -CullSet::CullSet() { -} - -CullSet::~CullSet() { -} - -CullSet::CullSet(scoped_ptr<base::hash_set<intptr_t> > cull_set) - : cull_set_(cull_set.Pass()) { -} - -bool CullSet::ShouldPaint(const View* view) const { - if (cull_set_) - return (cull_set_->count(reinterpret_cast<intptr_t>(view)) > 0); - - return true; -} - -} // namespace views
diff --git a/ui/views/cull_set.h b/ui/views/cull_set.h deleted file mode 100644 index 03f7cff..0000000 --- a/ui/views/cull_set.h +++ /dev/null
@@ -1,47 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_CULL_SET_H_ -#define UI_VIEWS_CULL_SET_H_ - -#include "base/containers/hash_tables.h" -#include "base/macros.h" -#include "base/memory/scoped_ptr.h" -#include "ui/views/views_export.h" - -namespace views { - -class View; - -// A CullSet defines a set of View pointers which have been possibly culled -// from painting or other bounds-checking operations. It wraps a set of -// pointers to views, or NULL if no such set is available. -class VIEWS_EXPORT CullSet { - public: - // Default constructor builds a CullSet that will always return true for - // ShouldPaint(). - CullSet(); - ~CullSet(); - - // Wraps a set of pointers to Views, as might be provided by - // gfx::RTree::Query(), that intersect the damage rect and therefore need - // to be painted. CullSet takes ownership of the provided pointer. - CullSet(scoped_ptr<base::hash_set<intptr_t> > cull_set); - - // Returns true if |view| needs to be painted. - bool ShouldPaint(const View* view) const; - - private: - friend class BoundsTreeTestView; - - // The set of Views that collided with the query rectangle provided to the - // RTree data structure, or NULL if one is not available. - scoped_ptr<base::hash_set<intptr_t> > cull_set_; - - DISALLOW_COPY_AND_ASSIGN(CullSet); -}; - -} // namespace views - -#endif // UI_VIEWS_CULL_SET_H_
diff --git a/ui/views/debug_utils.cc b/ui/views/debug_utils.cc deleted file mode 100644 index 12b4759..0000000 --- a/ui/views/debug_utils.cc +++ /dev/null
@@ -1,75 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/debug_utils.h" - -#include <ostream> - -#include "base/logging.h" -#include "base/strings/utf_string_conversions.h" -#include "ui/views/view.h" - -namespace views { -namespace { -void PrintViewHierarchyImp(const View* view, - int indent, - std::wostringstream* out) { - int ind = indent; - while (ind-- > 0) - *out << L' '; - *out << base::UTF8ToWide(view->GetClassName()); - *out << L' '; - *out << view->id(); - *out << L' '; - *out << view->x() << L"," << view->y() << L","; - *out << view->bounds().right() << L"," << view->bounds().bottom(); - *out << L' '; - *out << view; - *out << L'\n'; - - for (int i = 0, count = view->child_count(); i < count; ++i) - PrintViewHierarchyImp(view->child_at(i), indent + 2, out); -} - -void PrintFocusHierarchyImp(const View* view, - int indent, - std::wostringstream* out) { - int ind = indent; - while (ind-- > 0) - *out << L' '; - *out << base::UTF8ToWide(view->GetClassName()); - *out << L' '; - *out << view->id(); - *out << L' '; - *out << view->GetClassName(); - *out << L' '; - *out << view; - *out << L'\n'; - - if (view->child_count() > 0) - PrintFocusHierarchyImp(view->child_at(0), indent + 2, out); - - const View* next_focusable = view->GetNextFocusableView(); - if (next_focusable) - PrintFocusHierarchyImp(next_focusable, indent, out); -} -} // namespace - -void PrintViewHierarchy(const View* view) { - std::wostringstream out; - out << L"View hierarchy:\n"; - PrintViewHierarchyImp(view, 0, &out); - // Error so users in the field can generate and upload logs. - LOG(ERROR) << out.str(); -} - -void PrintFocusHierarchy(const View* view) { - std::wostringstream out; - out << L"Focus hierarchy:\n"; - PrintFocusHierarchyImp(view, 0, &out); - // Error so users in the field can generate and upload logs. - LOG(ERROR) << out.str(); -} - -} // namespace views
diff --git a/ui/views/debug_utils.h b/ui/views/debug_utils.h deleted file mode 100644 index feb4aaa..0000000 --- a/ui/views/debug_utils.h +++ /dev/null
@@ -1,22 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_DEBUG_UTILS_H_ -#define UI_VIEWS_DEBUG_UTILS_H_ - -#include "ui/views/views_export.h" - -namespace views { - -class View; - -// Log the view hierarchy. -VIEWS_EXPORT void PrintViewHierarchy(const View* view); - -// Log the focus traversal hierarchy. -VIEWS_EXPORT void PrintFocusHierarchy(const View* view); - -} // namespace views - -#endif // UI_VIEWS_DEBUG_UTILS_H_
diff --git a/ui/views/drag_controller.h b/ui/views/drag_controller.h deleted file mode 100644 index eace6a9..0000000 --- a/ui/views/drag_controller.h +++ /dev/null
@@ -1,49 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_DRAG_CONTROLLER_H_ -#define UI_VIEWS_DRAG_CONTROLLER_H_ - -#include "ui/views/views_export.h" - -namespace gfx { -class Point; -} - -namespace ui { -class OSExchangeData; -} - -namespace views { -class View; - -// DragController is responsible for writing drag data for a view, as well as -// supplying the supported drag operations. Use DragController if you don't -// want to subclass. -class VIEWS_EXPORT DragController { - public: - // Writes the data for the drag. - virtual void WriteDragDataForView(View* sender, - const gfx::Point& press_pt, - ui::OSExchangeData* data) = 0; - - // Returns the supported drag operations (see DragDropTypes for possible - // values). A drag is only started if this returns a non-zero value. - virtual int GetDragOperationsForView(View* sender, - const gfx::Point& p) = 0; - - // Returns true if a drag operation can be started. - // |press_pt| represents the coordinates where the mouse was initially - // pressed down. |p| is the current mouse coordinates. - virtual bool CanStartDragForView(View* sender, - const gfx::Point& press_pt, - const gfx::Point& p) = 0; - - protected: - virtual ~DragController() {} -}; - -} // namespace views - -#endif // UI_VIEWS_DRAG_CONTROLLER_H_
diff --git a/ui/views/drag_utils.cc b/ui/views/drag_utils.cc deleted file mode 100644 index 0fd5e5e..0000000 --- a/ui/views/drag_utils.cc +++ /dev/null
@@ -1,39 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/drag_utils.h" - -#include "ui/gfx/canvas.h" -#include "ui/gfx/display.h" -#include "ui/gfx/screen.h" -#include "ui/gfx/size.h" -#include "ui/views/widget/widget.h" - -namespace { - -float GetDeviceScaleForNativeView(views::Widget* widget) { - float device_scale = 1.0f; - // The following code should work on other platforms as well. But we do not - // yet care about device scale factor on other platforms. So to keep drag and - // drop behavior on other platforms un-touched, we wrap this in the #if guard. - if (widget && widget->GetNativeView()) { - gfx::NativeView view = widget->GetNativeView(); - gfx::Display display = gfx::Screen::GetScreenFor(view)-> - GetDisplayNearestWindow(view); - device_scale = display.device_scale_factor(); - } - return device_scale; -} - -} // namespace - -namespace views { - -gfx::Canvas* GetCanvasForDragImage(views::Widget* widget, - const gfx::Size& canvas_size) { - float device_scale = GetDeviceScaleForNativeView(widget); - return new gfx::Canvas(canvas_size, device_scale, false); -} - -} // namespace views
diff --git a/ui/views/drag_utils.h b/ui/views/drag_utils.h deleted file mode 100644 index 158f5cd..0000000 --- a/ui/views/drag_utils.h +++ /dev/null
@@ -1,39 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_DRAG_UTILS_H_ -#define UI_VIEWS_DRAG_UTILS_H_ - -#include "ui/base/dragdrop/drag_drop_types.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/views/views_export.h" - -namespace gfx { -class Canvas; -class Point; -class Size; -} - -namespace ui { -class OSExchangeData; -} - -namespace views { -class Widget; - -// Starts a drag operation. This blocks until the drag operation completes. -VIEWS_EXPORT void RunShellDrag(gfx::NativeView view, - const ui::OSExchangeData& data, - const gfx::Point& location, - int operation, - ui::DragDropTypes::DragEventSource source); - -// Returns a canvas that can be used to draw the drag image. Caller owns the -// returned object. |widget| is Widget hosting the view being dragged. -VIEWS_EXPORT gfx::Canvas* GetCanvasForDragImage(Widget* widget, - const gfx::Size& canvas_size); - -} // namespace views - -#endif // UI_VIEWS_DRAG_UTILS_H_
diff --git a/ui/views/drag_utils_aura.cc b/ui/views/drag_utils_aura.cc deleted file mode 100644 index cb64199..0000000 --- a/ui/views/drag_utils_aura.cc +++ /dev/null
@@ -1,27 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/drag_utils.h" - -#include "ui/aura/window.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/wm/public/drag_drop_client.h" - -namespace views { - -void RunShellDrag(gfx::NativeView view, - const ui::OSExchangeData& data, - const gfx::Point& location, - int operation, - ui::DragDropTypes::DragEventSource source) { - gfx::Point root_location(location); - aura::Window* root_window = view->GetRootWindow(); - aura::Window::ConvertPointToTarget(view, root_window, &root_location); - if (aura::client::GetDragDropClient(root_window)) { - aura::client::GetDragDropClient(root_window)->StartDragAndDrop( - data, root_window, view, root_location, operation, source); - } -} - -} // namespace views
diff --git a/ui/views/examples/BUILD.gn b/ui/views/examples/BUILD.gn deleted file mode 100644 index 52f070f..0000000 --- a/ui/views/examples/BUILD.gn +++ /dev/null
@@ -1,160 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -import("//build/config/ui.gni") - -component("views_examples_lib") { - testonly = true - - sources = [ - "bubble_example.cc", - "bubble_example.h", - "button_example.cc", - "button_example.h", - "checkbox_example.cc", - "checkbox_example.h", - "combobox_example.cc", - "combobox_example.h", - "double_split_view_example.cc", - "double_split_view_example.h", - "example_base.cc", - "example_base.h", - "example_combobox_model.cc", - "example_combobox_model.h", - "examples_window.cc", - "examples_window.h", - "label_example.cc", - "label_example.h", - "link_example.cc", - "link_example.h", - "message_box_example.cc", - "message_box_example.h", - "menu_example.cc", - "menu_example.h", - "multiline_example.cc", - "multiline_example.h", - "progress_bar_example.cc", - "progress_bar_example.h", - "radio_button_example.cc", - "radio_button_example.h", - "scroll_view_example.cc", - "scroll_view_example.h", - "single_split_view_example.cc", - "single_split_view_example.h", - "slider_example.cc", - "slider_example.h", - "tabbed_pane_example.cc", - "tabbed_pane_example.h", - "table_example.cc", - "table_example.h", - "text_example.cc", - "text_example.h", - "textfield_example.cc", - "textfield_example.h", - "throbber_example.cc", - "throbber_example.h", - "tree_view_example.cc", - "tree_view_example.h", - "views_examples_export.h", - "widget_example.cc", - "widget_example.h", - ] - - defines = [ "VIEWS_EXAMPLES_IMPLEMENTATION" ] - - deps = [ - "//base", - "//skia", - "//third_party/icu", - "//ui/base", - "//ui/events", - "//ui/gfx", - "//ui/gfx/geometry", - "//ui/resources", - "//ui/resources:ui_test_pak", - "//ui/views", - ] - - if (is_win) { - deps += [ "//third_party/wtl" ] - - # TODO(jschuh): crbug.com/167187 fix size_t to int truncations. - cflags = [ "/wd4267" ] - } - - if (use_aura) { - deps += [ "//ui/aura" ] - } -} - -executable("views_examples_exe") { - testonly = true - - sources = [ - "examples_main.cc", - ] - - deps = [ - ":views_examples_lib", - "//base", - "//base:i18n", - "//ui/base", - "//ui/compositor", - "//ui/compositor:test_support", - "//ui/gfx", - "//ui/gl", - "//ui/resources:ui_test_pak", - "//ui/views", - "//ui/views:test_support", - "//ui/wm", - ] - - if (use_aura) { - deps += [ "//ui/aura" ] - } - if (use_x11) { - deps += [ "//ui/gfx/x" ] - } -} - -component("views_examples_with_content_lib") { - testonly = true - sources = [ - "examples_window_with_content.cc", - "examples_window_with_content.h", - "views_examples_with_content_export.h", - "webview_example.cc", - "webview_example.h", - ] - - defines = [ "VIEWS_EXAMPLES_WITH_CONTENT_IMPLEMENTATION" ] - - deps = [ - ":views_examples_lib", - "//base", - "//content", - "//skia", - "//ui/events", - "//ui/views", - "//ui/views/controls/webview", - "//url", - ] -} - -executable("views_examples_with_content_exe") { - testonly = true - - sources = [ - "examples_with_content_main_exe.cc", - ] - - defines = [ "VIEWS_EXAMPLES_WITH_CONTENT_IMPLEMENTATION" ] - - deps = [ - ":views_examples_with_content_lib", - "//base", - "//content", - "//ui/views_content_client", - ] -}
diff --git a/ui/views/examples/DEPS b/ui/views/examples/DEPS deleted file mode 100644 index 06e440b..0000000 --- a/ui/views/examples/DEPS +++ /dev/null
@@ -1,7 +0,0 @@ -include_rules = [ - "+content/public", - "+content/shell", - "+sandbox", - "+ui/gl/gl_surface.h", # To initialize GL bindings. - "+ui/views_content_client", -]
diff --git a/ui/views/examples/bubble_example.cc b/ui/views/examples/bubble_example.cc deleted file mode 100644 index 907611a..0000000 --- a/ui/views/examples/bubble_example.cc +++ /dev/null
@@ -1,119 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/examples/bubble_example.h" - -#include "base/strings/utf_string_conversions.h" -#include "ui/views/bubble/bubble_delegate.h" -#include "ui/views/controls/button/label_button.h" -#include "ui/views/controls/label.h" -#include "ui/views/layout/box_layout.h" -#include "ui/views/widget/widget.h" - -using base::ASCIIToUTF16; - -namespace views { -namespace examples { - -namespace { - -SkColor colors[] = { SK_ColorWHITE, SK_ColorGRAY, SK_ColorCYAN, 0xFFC1B1E1 }; - -BubbleBorder::Arrow arrows[] = { - BubbleBorder::TOP_LEFT, BubbleBorder::TOP_CENTER, - BubbleBorder::TOP_RIGHT, BubbleBorder::RIGHT_TOP, - BubbleBorder::RIGHT_CENTER, BubbleBorder::RIGHT_BOTTOM, - BubbleBorder::BOTTOM_RIGHT, BubbleBorder::BOTTOM_CENTER, - BubbleBorder::BOTTOM_LEFT, BubbleBorder::LEFT_BOTTOM, - BubbleBorder::LEFT_CENTER, BubbleBorder::LEFT_TOP }; - -base::string16 GetArrowName(BubbleBorder::Arrow arrow) { - switch (arrow) { - case BubbleBorder::TOP_LEFT: return ASCIIToUTF16("TOP_LEFT"); - case BubbleBorder::TOP_RIGHT: return ASCIIToUTF16("TOP_RIGHT"); - case BubbleBorder::BOTTOM_LEFT: return ASCIIToUTF16("BOTTOM_LEFT"); - case BubbleBorder::BOTTOM_RIGHT: return ASCIIToUTF16("BOTTOM_RIGHT"); - case BubbleBorder::LEFT_TOP: return ASCIIToUTF16("LEFT_TOP"); - case BubbleBorder::RIGHT_TOP: return ASCIIToUTF16("RIGHT_TOP"); - case BubbleBorder::LEFT_BOTTOM: return ASCIIToUTF16("LEFT_BOTTOM"); - case BubbleBorder::RIGHT_BOTTOM: return ASCIIToUTF16("RIGHT_BOTTOM"); - case BubbleBorder::TOP_CENTER: return ASCIIToUTF16("TOP_CENTER"); - case BubbleBorder::BOTTOM_CENTER: return ASCIIToUTF16("BOTTOM_CENTER"); - case BubbleBorder::LEFT_CENTER: return ASCIIToUTF16("LEFT_CENTER"); - case BubbleBorder::RIGHT_CENTER: return ASCIIToUTF16("RIGHT_CENTER"); - case BubbleBorder::NONE: return ASCIIToUTF16("NONE"); - case BubbleBorder::FLOAT: return ASCIIToUTF16("FLOAT"); - } - return ASCIIToUTF16("INVALID"); -} - -class ExampleBubble : public BubbleDelegateView { - public: - ExampleBubble(View* anchor, BubbleBorder::Arrow arrow) - : BubbleDelegateView(anchor, arrow) {} - - protected: - virtual void Init() override { - SetLayoutManager(new BoxLayout(BoxLayout::kVertical, 50, 50, 0)); - AddChildView(new Label(GetArrowName(arrow()))); - } - - private: - DISALLOW_COPY_AND_ASSIGN(ExampleBubble); -}; - -} // namespace - -BubbleExample::BubbleExample() : ExampleBase("Bubble") {} - -BubbleExample::~BubbleExample() {} - -void BubbleExample::CreateExampleView(View* container) { - PrintStatus("Click with optional modifiers: [Ctrl] for set_arrow(NONE), " - "[Alt] for set_arrow(FLOAT), or [Shift] to reverse the arrow iteration."); - container->SetLayoutManager(new BoxLayout(BoxLayout::kHorizontal, 0, 0, 10)); - no_shadow_ = new LabelButton(this, ASCIIToUTF16("No Shadow")); - container->AddChildView(no_shadow_); - big_shadow_ = new LabelButton(this, ASCIIToUTF16("Big Shadow")); - container->AddChildView(big_shadow_); - small_shadow_ = new LabelButton(this, ASCIIToUTF16("Small Shadow")); - container->AddChildView(small_shadow_); - align_to_edge_ = new LabelButton(this, ASCIIToUTF16("Align To Edge")); - container->AddChildView(align_to_edge_); - persistent_ = new LabelButton(this, ASCIIToUTF16("Persistent")); - container->AddChildView(persistent_); -} - -void BubbleExample::ButtonPressed(Button* sender, const ui::Event& event) { - static int arrow_index = 0, color_index = 0; - static const int count = arraysize(arrows); - arrow_index = (arrow_index + count + (event.IsShiftDown() ? -1 : 1)) % count; - BubbleBorder::Arrow arrow = arrows[arrow_index]; - if (event.IsControlDown()) - arrow = BubbleBorder::NONE; - else if (event.IsAltDown()) - arrow = BubbleBorder::FLOAT; - - ExampleBubble* bubble = new ExampleBubble(sender, arrow); - bubble->set_color(colors[(color_index++) % arraysize(colors)]); - - if (sender == no_shadow_) - bubble->set_shadow(BubbleBorder::NO_SHADOW); - else if (sender == big_shadow_) - bubble->set_shadow(BubbleBorder::BIG_SHADOW); - else if (sender == small_shadow_) - bubble->set_shadow(BubbleBorder::SMALL_SHADOW); - - if (sender == persistent_) - bubble->set_close_on_deactivate(false); - - BubbleDelegateView::CreateBubble(bubble); - if (sender == align_to_edge_) - bubble->SetAlignment(BubbleBorder::ALIGN_EDGE_TO_ANCHOR_EDGE); - - bubble->GetWidget()->Show(); -} - -} // namespace examples -} // namespace views
diff --git a/ui/views/examples/bubble_example.h b/ui/views/examples/bubble_example.h deleted file mode 100644 index eb5625c..0000000 --- a/ui/views/examples/bubble_example.h +++ /dev/null
@@ -1,40 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_EXAMPLES_BUBBLE_EXAMPLE_H_ -#define UI_VIEWS_EXAMPLES_BUBBLE_EXAMPLE_H_ - -#include "ui/views/controls/button/button.h" -#include "ui/views/examples/example_base.h" - -namespace views { -namespace examples { - -// A Bubble example. -class VIEWS_EXAMPLES_EXPORT BubbleExample : public ExampleBase, - public ButtonListener { - public: - BubbleExample(); - virtual ~BubbleExample(); - - // ExampleBase: - virtual void CreateExampleView(View* container) override; - - private: - // ButtonListener: - virtual void ButtonPressed(Button* sender, const ui::Event& event) override; - - Button* no_shadow_; - Button* big_shadow_; - Button* small_shadow_; - Button* align_to_edge_; - Button* persistent_; - - DISALLOW_COPY_AND_ASSIGN(BubbleExample); -}; - -} // namespace examples -} // namespace views - -#endif // UI_VIEWS_EXAMPLES_BUBBLE_EXAMPLE_H_
diff --git a/ui/views/examples/button_example.cc b/ui/views/examples/button_example.cc deleted file mode 100644 index 100b4ce..0000000 --- a/ui/views/examples/button_example.cc +++ /dev/null
@@ -1,117 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/examples/button_example.h" - -#include "base/strings/utf_string_conversions.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/gfx/image/image.h" -#include "ui/resources/grit/ui_resources.h" -#include "ui/views/background.h" -#include "ui/views/controls/button/blue_button.h" -#include "ui/views/controls/button/image_button.h" -#include "ui/views/controls/button/label_button.h" -#include "ui/views/layout/box_layout.h" -#include "ui/views/view.h" - -using base::ASCIIToUTF16; - -namespace { -const char kLabelButton[] = "Label Button"; -const char kMultiLineText[] = "Multi-Line\nButton Text Is Here To Stay!\n123"; -const char kLongText[] = "Start of Really Really Really Really Really Really " - "Really Really Really Really Really Really Really " - "Really Really Really Really Really Long Button Text"; -} // namespace - -namespace views { -namespace examples { - -ButtonExample::ButtonExample() - : ExampleBase("Button"), - label_button_(NULL), - image_button_(NULL), - icon_(NULL), - count_(0) { - ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); - icon_ = rb.GetImageNamed(IDR_CLOSE_H).ToImageSkia(); -} - -ButtonExample::~ButtonExample() { -} - -void ButtonExample::CreateExampleView(View* container) { - container->set_background(Background::CreateSolidBackground(SK_ColorWHITE)); - container->SetLayoutManager(new BoxLayout(BoxLayout::kVertical, 10, 10, 10)); - - label_button_ = new LabelButton(this, ASCIIToUTF16(kLabelButton)); - label_button_->SetFocusable(true); - container->AddChildView(label_button_); - - LabelButton* disabled_button = - new LabelButton(this, ASCIIToUTF16("Disabled Button")); - disabled_button->SetStyle(Button::STYLE_BUTTON); - disabled_button->SetState(Button::STATE_DISABLED); - container->AddChildView(disabled_button); - - container->AddChildView(new BlueButton(this, ASCIIToUTF16("Blue Button"))); - - ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); - image_button_ = new ImageButton(this); - image_button_->SetFocusable(true); - image_button_->SetImage(ImageButton::STATE_NORMAL, - rb.GetImageNamed(IDR_CLOSE).ToImageSkia()); - image_button_->SetImage(ImageButton::STATE_HOVERED, - rb.GetImageNamed(IDR_CLOSE_H).ToImageSkia()); - image_button_->SetImage(ImageButton::STATE_PRESSED, - rb.GetImageNamed(IDR_CLOSE_P).ToImageSkia()); - container->AddChildView(image_button_); -} - -void ButtonExample::LabelButtonPressed(const ui::Event& event) { - PrintStatus("Label Button Pressed! count: %d", ++count_); - if (event.IsControlDown()) { - if (event.IsShiftDown()) { - if (event.IsAltDown()) { - label_button_->SetTextMultiLine(!label_button_->GetTextMultiLine()); - label_button_->SetText(ASCIIToUTF16( - label_button_->GetTextMultiLine() ? kMultiLineText : kLabelButton)); - } else { - label_button_->SetText(ASCIIToUTF16( - label_button_->GetText().empty() ? kLongText : - label_button_->GetText().length() > 50 ? kLabelButton : "")); - } - } else if (event.IsAltDown()) { - label_button_->SetImage(Button::STATE_NORMAL, - label_button_->GetImage(Button::STATE_NORMAL).isNull() ? - *icon_ : gfx::ImageSkia()); - } else { - label_button_->SetHorizontalAlignment( - static_cast<gfx::HorizontalAlignment>( - (label_button_->GetHorizontalAlignment() + 1) % 3)); - } - } else if (event.IsShiftDown()) { - if (event.IsAltDown()) { - label_button_->SetFocusable(!label_button_->IsFocusable()); - } else { - label_button_->SetStyle(static_cast<Button::ButtonStyle>( - (label_button_->style() + 1) % Button::STYLE_COUNT)); - } - } else if (event.IsAltDown()) { - label_button_->SetIsDefault(!label_button_->is_default()); - } else { - label_button_->SetMinSize(gfx::Size()); - } - example_view()->GetLayoutManager()->Layout(example_view()); -} - -void ButtonExample::ButtonPressed(Button* sender, const ui::Event& event) { - if (sender == label_button_) - LabelButtonPressed(event); - else - PrintStatus("Image Button Pressed! count: %d", ++count_); -} - -} // namespace examples -} // namespace views
diff --git a/ui/views/examples/button_example.h b/ui/views/examples/button_example.h deleted file mode 100644 index 8fc2c60..0000000 --- a/ui/views/examples/button_example.h +++ /dev/null
@@ -1,50 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_EXAMPLES_BUTTON_EXAMPLE_H_ -#define UI_VIEWS_EXAMPLES_BUTTON_EXAMPLE_H_ - -#include "base/macros.h" -#include "ui/views/controls/button/button.h" -#include "ui/views/examples/example_base.h" - -namespace views { - -class ImageButton; -class LabelButton; - -namespace examples { - -// ButtonExample simply counts the number of clicks. -class VIEWS_EXAMPLES_EXPORT ButtonExample : public ExampleBase, - public ButtonListener { - public: - ButtonExample(); - virtual ~ButtonExample(); - - // ExampleBase: - virtual void CreateExampleView(View* container) override; - - private: - void LabelButtonPressed(const ui::Event& event); - - // ButtonListener: - virtual void ButtonPressed(Button* sender, const ui::Event& event) override; - - // Example buttons. - LabelButton* label_button_; - ImageButton* image_button_; - - const gfx::ImageSkia* icon_; - - // The number of times the buttons are pressed. - int count_; - - DISALLOW_COPY_AND_ASSIGN(ButtonExample); -}; - -} // namespace examples -} // namespace views - -#endif // UI_VIEWS_EXAMPLES_BUTTON_EXAMPLE_H_
diff --git a/ui/views/examples/checkbox_example.cc b/ui/views/examples/checkbox_example.cc deleted file mode 100644 index b25dd8e..0000000 --- a/ui/views/examples/checkbox_example.cc +++ /dev/null
@@ -1,34 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/examples/checkbox_example.h" - -#include "base/strings/stringprintf.h" -#include "base/strings/utf_string_conversions.h" -#include "ui/views/controls/button/checkbox.h" -#include "ui/views/controls/button/radio_button.h" -#include "ui/views/layout/fill_layout.h" - -namespace views { -namespace examples { - -CheckboxExample::CheckboxExample() : ExampleBase("Checkbox"), count_(0) { -} - -CheckboxExample::~CheckboxExample() { -} - -void CheckboxExample::CreateExampleView(View* container) { - button_ = new Checkbox(base::ASCIIToUTF16("Checkbox")); - button_->set_listener(this); - container->SetLayoutManager(new FillLayout); - container->AddChildView(button_); -} - -void CheckboxExample::ButtonPressed(Button* sender, const ui::Event& event) { - PrintStatus("Pressed! count: %d", ++count_); -} - -} // namespace examples -} // namespace views
diff --git a/ui/views/examples/checkbox_example.h b/ui/views/examples/checkbox_example.h deleted file mode 100644 index d95f1f4..0000000 --- a/ui/views/examples/checkbox_example.h +++ /dev/null
@@ -1,42 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_EXAMPLES_CHECKBOX_EXAMPLE_H_ -#define UI_VIEWS_EXAMPLES_CHECKBOX_EXAMPLE_H_ - -#include "base/macros.h" -#include "ui/views/controls/button/button.h" -#include "ui/views/examples/example_base.h" - -namespace views { -class Checkbox; - -namespace examples { - -// CheckboxExample exercises a Checkbox control. -class VIEWS_EXAMPLES_EXPORT CheckboxExample : public ExampleBase, - public ButtonListener { - public: - CheckboxExample(); - virtual ~CheckboxExample(); - - // ExampleBase: - virtual void CreateExampleView(View* container) override; - - private: - // ButtonListener: - virtual void ButtonPressed(Button* sender, const ui::Event& event) override; - - // The only control in this test. - Checkbox* button_; - - int count_; - - DISALLOW_COPY_AND_ASSIGN(CheckboxExample); -}; - -} // namespace examples -} // namespace views - -#endif // UI_VIEWS_EXAMPLES_CHECKBOX_EXAMPLE_H_
diff --git a/ui/views/examples/combobox_example.cc b/ui/views/examples/combobox_example.cc deleted file mode 100644 index ed07379..0000000 --- a/ui/views/examples/combobox_example.cc +++ /dev/null
@@ -1,54 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/examples/combobox_example.h" - -#include "base/strings/stringprintf.h" -#include "base/strings/utf_string_conversions.h" -#include "ui/views/controls/combobox/combobox.h" -#include "ui/views/layout/fill_layout.h" - -namespace views { -namespace examples { - -ComboboxModelExample::ComboboxModelExample() { -} - -ComboboxModelExample::~ComboboxModelExample() { -} - -int ComboboxModelExample::GetItemCount() const { - return 10; -} - -base::string16 ComboboxModelExample::GetItemAt(int index) { - return base::UTF8ToUTF16(base::StringPrintf("Item %d", index)); -} - -ComboboxExample::ComboboxExample() : ExampleBase("Combo Box"), combobox_(NULL) { -} - -ComboboxExample::~ComboboxExample() { - // Delete |combobox_| first as it references |combobox_model_|. - delete combobox_; - combobox_ = NULL; -} - -void ComboboxExample::CreateExampleView(View* container) { - combobox_ = new Combobox(&combobox_model_); - combobox_->set_listener(this); - combobox_->SetSelectedIndex(3); - - container->SetLayoutManager(new FillLayout); - container->AddChildView(combobox_); -} - -void ComboboxExample::OnPerformAction(Combobox* combobox) { - DCHECK_EQ(combobox_, combobox); - PrintStatus("Selected: %s", base::UTF16ToUTF8(combobox_model_.GetItemAt( - combobox->selected_index())).c_str()); -} - -} // namespace examples -} // namespace views
diff --git a/ui/views/examples/combobox_example.h b/ui/views/examples/combobox_example.h deleted file mode 100644 index 3ea1c24..0000000 --- a/ui/views/examples/combobox_example.h +++ /dev/null
@@ -1,52 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_EXAMPLES_COMBOBOX_EXAMPLE_H_ -#define UI_VIEWS_EXAMPLES_COMBOBOX_EXAMPLE_H_ - -#include "base/macros.h" -#include "ui/base/models/combobox_model.h" -#include "ui/views/controls/combobox/combobox_listener.h" -#include "ui/views/examples/example_base.h" - -namespace views { -namespace examples { - -// A combobox model implementation that generates a list of "Item <index>". -class VIEWS_EXAMPLES_EXPORT ComboboxModelExample : public ui::ComboboxModel { - public: - ComboboxModelExample(); - virtual ~ComboboxModelExample(); - - // ui::ComboboxModel: - virtual int GetItemCount() const override; - virtual base::string16 GetItemAt(int index) override; - - private: - DISALLOW_COPY_AND_ASSIGN(ComboboxModelExample); -}; - -class VIEWS_EXAMPLES_EXPORT ComboboxExample : public ExampleBase, - public ComboboxListener { - public: - ComboboxExample(); - virtual ~ComboboxExample(); - - // ExampleBase: - virtual void CreateExampleView(View* container) override; - - private: - // ComboboxListener: - virtual void OnPerformAction(Combobox* combobox) override; - - ComboboxModelExample combobox_model_; - Combobox* combobox_; - - DISALLOW_COPY_AND_ASSIGN(ComboboxExample); -}; - -} // namespace examples -} // namespace views - -#endif // UI_VIEWS_EXAMPLES_COMBOBOX_EXAMPLE_H_
diff --git a/ui/views/examples/double_split_view_example.cc b/ui/views/examples/double_split_view_example.cc deleted file mode 100644 index dc794e6..0000000 --- a/ui/views/examples/double_split_view_example.cc +++ /dev/null
@@ -1,82 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/examples/double_split_view_example.h" - -#include "ui/views/background.h" -#include "ui/views/controls/single_split_view.h" -#include "ui/views/layout/grid_layout.h" - -namespace views { -namespace examples { - -namespace { - -// DoubleSplitViews's content, which draws gradient color on background. -class SplittedView : public View { - public: - SplittedView(); - virtual ~SplittedView(); - - void SetColor(SkColor from, SkColor to); - - // View: - virtual gfx::Size GetMinimumSize() const override; - - private: - DISALLOW_COPY_AND_ASSIGN(SplittedView); -}; - -SplittedView::SplittedView() { - SetColor(SK_ColorRED, SK_ColorGREEN); -} - -SplittedView::~SplittedView() { -} - -void SplittedView::SetColor(SkColor from, SkColor to) { - set_background(Background::CreateVerticalGradientBackground(from, to)); -} - -gfx::Size SplittedView::GetMinimumSize() const { - return gfx::Size(10, 10); -} - -} // namespace - -DoubleSplitViewExample::DoubleSplitViewExample() - : ExampleBase("Double Split View") { -} - -DoubleSplitViewExample::~DoubleSplitViewExample() { -} - -void DoubleSplitViewExample::CreateExampleView(View* container) { - SplittedView* splitted_view_1 = new SplittedView(); - SplittedView* splitted_view_2 = new SplittedView(); - SplittedView* splitted_view_3 = new SplittedView(); - - inner_single_split_view_ = new SingleSplitView( - splitted_view_1, splitted_view_2, - SingleSplitView::HORIZONTAL_SPLIT, - NULL); - - outer_single_split_view_ = new SingleSplitView( - inner_single_split_view_, splitted_view_3, - SingleSplitView::HORIZONTAL_SPLIT, - NULL); - - GridLayout* layout = new GridLayout(container); - container->SetLayoutManager(layout); - - // Add scroll view. - ColumnSet* column_set = layout->AddColumnSet(0); - column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1, - GridLayout::USE_PREF, 0, 0); - layout->StartRow(1, 0); - layout->AddView(outer_single_split_view_); -} - -} // namespace examples -} // namespace views
diff --git a/ui/views/examples/double_split_view_example.h b/ui/views/examples/double_split_view_example.h deleted file mode 100644 index c83b8cb..0000000 --- a/ui/views/examples/double_split_view_example.h +++ /dev/null
@@ -1,35 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_EXAMPLES_DOUBLE_SPLIT_VIEW_EXAMPLE_H_ -#define UI_VIEWS_EXAMPLES_DOUBLE_SPLIT_VIEW_EXAMPLE_H_ - -#include "base/macros.h" -#include "ui/views/examples/example_base.h" - -namespace views { -class SingleSplitView; - -namespace examples { - -class VIEWS_EXAMPLES_EXPORT DoubleSplitViewExample : public ExampleBase { - public: - DoubleSplitViewExample(); - virtual ~DoubleSplitViewExample(); - - // ExampleBase: - virtual void CreateExampleView(View* container) override; - - private: - // The SingleSplitViews to be embedded. - SingleSplitView* outer_single_split_view_; - SingleSplitView* inner_single_split_view_; - - DISALLOW_COPY_AND_ASSIGN(DoubleSplitViewExample); -}; - -} // namespace examples -} // namespace views - -#endif // UI_VIEWS_EXAMPLES_DOUBLE_SPLIT_VIEW_EXAMPLE_H_
diff --git a/ui/views/examples/example_base.cc b/ui/views/examples/example_base.cc deleted file mode 100644 index bb216f9..0000000 --- a/ui/views/examples/example_base.cc +++ /dev/null
@@ -1,68 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/examples/example_base.h" - -#include <stdarg.h> - -#include "base/strings/stringprintf.h" -#include "ui/views/view.h" - -namespace views { -namespace examples { - -// Logs the specified string to the status area of the examples window. -// This function can only be called if there is a visible examples window. -void LogStatus(const std::string& status); - -namespace { - -// TODO(oshima): Check if this special container is still necessary. -class ContainerView : public View { - public: - explicit ContainerView(ExampleBase* base) - : example_view_created_(false), - example_base_(base) { - } - - private: - // View: - virtual void ViewHierarchyChanged( - const ViewHierarchyChangedDetails& details) override { - View::ViewHierarchyChanged(details); - // We're not using child == this because a Widget may not be - // available when this is added to the hierarchy. - if (details.is_add && GetWidget() && !example_view_created_) { - example_view_created_ = true; - example_base_->CreateExampleView(this); - } - } - - // True if the example view has already been created, or false otherwise. - bool example_view_created_; - - ExampleBase* example_base_; - - DISALLOW_COPY_AND_ASSIGN(ContainerView); -}; - -} // namespace - -ExampleBase::~ExampleBase() {} - -ExampleBase::ExampleBase(const char* title) : example_title_(title) { - container_ = new ContainerView(this); -} - -// Prints a message in the status area, at the bottom of the window. -void ExampleBase::PrintStatus(const char* format, ...) { - va_list ap; - va_start(ap, format); - std::string msg; - base::StringAppendV(&msg, format, ap); - LogStatus(msg); -} - -} // namespace examples -} // namespace views
diff --git a/ui/views/examples/example_base.h b/ui/views/examples/example_base.h deleted file mode 100644 index f841eb9..0000000 --- a/ui/views/examples/example_base.h +++ /dev/null
@@ -1,54 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_EXAMPLES_EXAMPLE_BASE_H_ -#define UI_VIEWS_EXAMPLES_EXAMPLE_BASE_H_ - -#include <string> - -#include "base/macros.h" -#include "ui/views/examples/views_examples_export.h" - -namespace views { -class View; - -namespace examples { - -class VIEWS_EXAMPLES_EXPORT ExampleBase { - public: - virtual ~ExampleBase(); - - // Sub-classes should creates and add the views to the given parent. - virtual void CreateExampleView(View* parent) = 0; - - const std::string& example_title() const { return example_title_; } - View* example_view() { return container_; } - - protected: - explicit ExampleBase(const char* title); - - View* container() { return container_; } - - // Prints a message in the status area, at the bottom of the window. - void PrintStatus(const char* format, ...); - - // Converts an boolean value to "on" or "off". - const char* BoolToOnOff(bool value) { - return value ? "on" : "off"; - } - - private: - // Name of the example - used as title in the combobox list. - std::string example_title_; - - // The view that contains the views example. - View* container_; - - DISALLOW_COPY_AND_ASSIGN(ExampleBase); -}; - -} // namespace examples -} // namespace views - -#endif // UI_VIEWS_EXAMPLES_EXAMPLE_BASE_H_
diff --git a/ui/views/examples/example_combobox_model.cc b/ui/views/examples/example_combobox_model.cc deleted file mode 100644 index a1160e7..0000000 --- a/ui/views/examples/example_combobox_model.cc +++ /dev/null
@@ -1,28 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/examples/example_combobox_model.h" - -#include "base/strings/utf_string_conversions.h" - -namespace views { -namespace examples { - -ExampleComboboxModel::ExampleComboboxModel(const char** strings, int count) - : strings_(strings), count_(count) { -} - -ExampleComboboxModel::~ExampleComboboxModel() { -} - -int ExampleComboboxModel::GetItemCount() const { - return count_; -} - -base::string16 ExampleComboboxModel::GetItemAt(int index) { - return base::ASCIIToUTF16(strings_[index]); -} - -} // namespace examples -} // namespace views
diff --git a/ui/views/examples/example_combobox_model.h b/ui/views/examples/example_combobox_model.h deleted file mode 100644 index 4988c60..0000000 --- a/ui/views/examples/example_combobox_model.h +++ /dev/null
@@ -1,33 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_EXAMPLES_EXAMPLE_COMBOBOX_MODEL_H_ -#define UI_VIEWS_EXAMPLES_EXAMPLE_COMBOBOX_MODEL_H_ - -#include "base/macros.h" -#include "ui/base/models/combobox_model.h" - -namespace views { -namespace examples { - -class ExampleComboboxModel : public ui::ComboboxModel { - public: - ExampleComboboxModel(const char** strings, int count); - virtual ~ExampleComboboxModel(); - - // ui::ComboboxModel: - virtual int GetItemCount() const override; - virtual base::string16 GetItemAt(int index) override; - - private: - const char** strings_; - int count_; - - DISALLOW_COPY_AND_ASSIGN(ExampleComboboxModel); -}; - -} // namespace examples -} // namespace views - -#endif // UI_VIEWS_EXAMPLES_EXAMPLE_COMBOBOX_MODEL_H_
diff --git a/ui/views/examples/examples.gyp b/ui/views/examples/examples.gyp deleted file mode 100644 index a2fa62f..0000000 --- a/ui/views/examples/examples.gyp +++ /dev/null
@@ -1,195 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. -{ - 'variables': { - 'chromium_code': 1, - }, - 'targets': [ - { - # GN version: //ui/views/examples - 'target_name': 'views_examples_lib', - 'type': '<(component)', - 'dependencies': [ - '../../../base/base.gyp:base', - '../../../skia/skia.gyp:skia', - '../../../third_party/icu/icu.gyp:icui18n', - '../../../third_party/icu/icu.gyp:icuuc', - '../../base/ui_base.gyp:ui_base', - '../../events/events.gyp:events', - '../../gfx/gfx.gyp:gfx', - '../../gfx/gfx.gyp:gfx_geometry', - '../../resources/ui_resources.gyp:ui_resources', - '../../resources/ui_resources.gyp:ui_test_pak', - '../views.gyp:views', - ], - 'include_dirs': [ - '../../..', - ], - 'defines': [ - 'VIEWS_EXAMPLES_IMPLEMENTATION', - ], - 'sources': [ - # Note: sources list duplicated in GN build. - 'bubble_example.cc', - 'bubble_example.h', - 'button_example.cc', - 'button_example.h', - 'checkbox_example.cc', - 'checkbox_example.h', - 'combobox_example.cc', - 'combobox_example.h', - 'double_split_view_example.cc', - 'double_split_view_example.h', - 'example_base.cc', - 'example_base.h', - 'example_combobox_model.cc', - 'example_combobox_model.h', - 'examples_window.cc', - 'examples_window.h', - 'label_example.cc', - 'label_example.h', - 'link_example.cc', - 'link_example.h', - 'message_box_example.cc', - 'message_box_example.h', - 'menu_example.cc', - 'menu_example.h', - 'multiline_example.cc', - 'multiline_example.h', - 'progress_bar_example.cc', - 'progress_bar_example.h', - 'radio_button_example.cc', - 'radio_button_example.h', - 'scroll_view_example.cc', - 'scroll_view_example.h', - 'single_split_view_example.cc', - 'single_split_view_example.h', - 'slider_example.cc', - 'slider_example.h', - 'tabbed_pane_example.cc', - 'tabbed_pane_example.h', - 'table_example.cc', - 'table_example.h', - 'text_example.cc', - 'text_example.h', - 'textfield_example.cc', - 'textfield_example.h', - 'throbber_example.cc', - 'throbber_example.h', - 'tree_view_example.cc', - 'tree_view_example.h', - 'views_examples_export.h', - 'widget_example.cc', - 'widget_example.h', - ], - 'conditions': [ - ['OS=="win"', { - 'include_dirs': [ - '../../../third_party/wtl/include', - ], - # TODO(jschuh): crbug.com/167187 fix size_t to int truncations. - 'msvs_disabled_warnings': [ 4267, ], - }], - ['use_aura==1', { - 'dependencies': [ - '../../aura/aura.gyp:aura', - ], - }], - ], - }, # target_name: views_examples_lib - { - # GN version: //ui/views/examples:views_examples_exe - 'target_name': 'views_examples_exe', - 'type': 'executable', - 'dependencies': [ - '../../../base/base.gyp:base', - '../../../base/base.gyp:base_i18n', - '../../base/ui_base.gyp:ui_base', - '../../compositor/compositor.gyp:compositor', - '../../compositor/compositor.gyp:compositor_test_support', - '../../gfx/gfx.gyp:gfx', - '../../resources/ui_resources.gyp:ui_test_pak', - '../views.gyp:views', - '../views.gyp:views_test_support', - 'views_examples_lib', - ], - 'sources': [ - # Note: sources list duplicated in GN build. - 'examples_main.cc', - ], - 'conditions': [ - ['use_aura==1', { - 'dependencies': [ - '../../aura/aura.gyp:aura', - ], - }], - ], - }, # target_name: views_examples_exe - { - # GN version: //ui/views/examples:views_examples_with_content_lib - 'target_name': 'views_examples_with_content_lib', - 'type': '<(component)', - 'dependencies': [ - '../../../base/base.gyp:base', - '../../../content/content.gyp:content', - '../../../skia/skia.gyp:skia', - '../../../url/url.gyp:url_lib', - '../../events/events.gyp:events', - '../controls/webview/webview.gyp:webview', - '../views.gyp:views', - 'views_examples_lib', - ], - 'defines': [ - 'VIEWS_EXAMPLES_WITH_CONTENT_IMPLEMENTATION', - ], - 'sources': [ - # Note: sources list duplicated in GN build. - 'examples_window_with_content.cc', - 'examples_window_with_content.h', - 'views_examples_with_content_export.h', - 'webview_example.cc', - 'webview_example.h', - ], - }, # target_name: views_examples_with_content_lib - { - # GN version: //ui/views/examples/views_examples_with_content_exe - 'target_name': 'views_examples_with_content_exe', - 'type': 'executable', - 'dependencies': [ - '../../../base/base.gyp:base', - '../../../content/content.gyp:content', - '../../views_content_client/views_content_client.gyp:views_content_client', - 'views_examples_with_content_lib', - ], - 'sources': [ - # Note: sources list duplicated in GN build. - 'examples_with_content_main_exe.cc', - ], - 'conditions': [ - ['OS=="win"', { - 'link_settings': { - 'libraries': [ - '-limm32.lib', - '-loleacc.lib', - ] - }, - 'msvs_settings': { - 'VCManifestTool': { - 'AdditionalManifestFiles': [ - 'views_examples.exe.manifest', - ], - }, - 'VCLinkerTool': { - 'SubSystem': '2', # Set /SUBSYSTEM:WINDOWS - }, - }, - 'dependencies': [ - '../../../sandbox/sandbox.gyp:sandbox', - '../../../content/content.gyp:content_startup_helper_win', - ], - }], - ], - }, # target_name: views_examples_with_content_exe - ], -}
diff --git a/ui/views/examples/examples_main.cc b/ui/views/examples/examples_main.cc deleted file mode 100644 index a751a0d..0000000 --- a/ui/views/examples/examples_main.cc +++ /dev/null
@@ -1,104 +0,0 @@ -// Copyright 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/at_exit.h" -#include "base/command_line.h" -#include "base/files/file_path.h" -#include "base/i18n/icu_util.h" -#include "base/message_loop/message_loop.h" -#include "base/path_service.h" -#include "base/run_loop.h" -#include "ui/base/ime/input_method_initializer.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/base/ui_base_paths.h" -#include "ui/compositor/test/in_process_context_factory.h" -#include "ui/gfx/screen.h" -#include "ui/gl/gl_surface.h" -#include "ui/views/examples/example_base.h" -#include "ui/views/examples/examples_window.h" -#include "ui/views/test/desktop_test_views_delegate.h" - -#if defined(USE_AURA) -#include "ui/aura/env.h" -#include "ui/wm/core/wm_state.h" -#endif - -#if !defined(OS_CHROMEOS) && defined(USE_AURA) -#include "ui/views/widget/desktop_aura/desktop_screen.h" -#endif - -#if defined(OS_WIN) -#include "ui/base/win/scoped_ole_initializer.h" -#endif - -#if defined(USE_X11) -#include "ui/gfx/x/x11_connection.h" -#endif - -int main(int argc, char** argv) { -#if defined(OS_WIN) - ui::ScopedOleInitializer ole_initializer_; -#endif - - CommandLine::Init(argc, argv); - - base::AtExitManager at_exit; - -#if defined(USE_X11) - // This demo uses InProcessContextFactory which uses X on a separate Gpu - // thread. - gfx::InitializeThreadedX11(); -#endif - - gfx::GLSurface::InitializeOneOff(); - - // The ContextFactory must exist before any Compositors are created. - scoped_ptr<ui::InProcessContextFactory> context_factory( - new ui::InProcessContextFactory()); - - base::MessageLoopForUI message_loop; - - base::i18n::InitializeICU(); - - ui::RegisterPathProvider(); - - base::FilePath ui_test_pak_path; - DCHECK(PathService::Get(ui::UI_TEST_PAK, &ui_test_pak_path)); - ui::ResourceBundle::InitSharedInstanceWithPakPath(ui_test_pak_path); - -#if defined(USE_AURA) - aura::Env::CreateInstance(true); - aura::Env::GetInstance()->set_context_factory(context_factory.get()); -#endif - ui::InitializeInputMethodForTesting(); - - { - views::DesktopTestViewsDelegate views_delegate; -#if defined(USE_AURA) - wm::WMState wm_state; -#endif -#if !defined(OS_CHROMEOS) && defined(USE_AURA) - scoped_ptr<gfx::Screen> desktop_screen(views::CreateDesktopScreen()); - gfx::Screen::SetScreenInstance(gfx::SCREEN_TYPE_NATIVE, - desktop_screen.get()); -#endif - - views::examples::ShowExamplesWindow( - views::examples::QUIT_ON_CLOSE, - NULL, - scoped_ptr<ScopedVector<views::examples::ExampleBase> >()); - - base::RunLoop().Run(); - - ui::ResourceBundle::CleanupSharedInstance(); - } - - ui::ShutdownInputMethod(); - -#if defined(USE_AURA) - aura::Env::DeleteInstance(); -#endif - - return 0; -}
diff --git a/ui/views/examples/examples_window.cc b/ui/views/examples/examples_window.cc deleted file mode 100644 index 040fcdc..0000000 --- a/ui/views/examples/examples_window.cc +++ /dev/null
@@ -1,235 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/examples/examples_window.h" - -#include <algorithm> -#include <string> - -#include "base/memory/scoped_vector.h" -#include "base/strings/utf_string_conversions.h" -#include "ui/base/models/combobox_model.h" -#include "ui/base/ui_base_paths.h" -#include "ui/views/background.h" -#include "ui/views/controls/combobox/combobox.h" -#include "ui/views/controls/label.h" -#include "ui/views/examples/bubble_example.h" -#include "ui/views/examples/button_example.h" -#include "ui/views/examples/checkbox_example.h" -#include "ui/views/examples/combobox_example.h" -#include "ui/views/examples/double_split_view_example.h" -#include "ui/views/examples/label_example.h" -#include "ui/views/examples/link_example.h" -#include "ui/views/examples/menu_example.h" -#include "ui/views/examples/message_box_example.h" -#include "ui/views/examples/multiline_example.h" -#include "ui/views/examples/progress_bar_example.h" -#include "ui/views/examples/radio_button_example.h" -#include "ui/views/examples/scroll_view_example.h" -#include "ui/views/examples/single_split_view_example.h" -#include "ui/views/examples/slider_example.h" -#include "ui/views/examples/tabbed_pane_example.h" -#include "ui/views/examples/table_example.h" -#include "ui/views/examples/text_example.h" -#include "ui/views/examples/textfield_example.h" -#include "ui/views/examples/throbber_example.h" -#include "ui/views/examples/tree_view_example.h" -#include "ui/views/examples/widget_example.h" -#include "ui/views/layout/fill_layout.h" -#include "ui/views/layout/grid_layout.h" -#include "ui/views/widget/widget.h" -#include "ui/views/widget/widget_delegate.h" - -namespace views { -namespace examples { - -typedef scoped_ptr<ScopedVector<ExampleBase> > ScopedExamples; - -namespace { - -// Creates the default set of examples. Caller owns the result. -ScopedExamples CreateExamples() { - ScopedExamples examples(new ScopedVector<ExampleBase>); - examples->push_back(new BubbleExample); - examples->push_back(new ButtonExample); - examples->push_back(new CheckboxExample); - examples->push_back(new ComboboxExample); - examples->push_back(new DoubleSplitViewExample); - examples->push_back(new LabelExample); - examples->push_back(new LinkExample); - examples->push_back(new MenuExample); - examples->push_back(new MessageBoxExample); - examples->push_back(new MultilineExample); - examples->push_back(new ProgressBarExample); - examples->push_back(new RadioButtonExample); - examples->push_back(new ScrollViewExample); - examples->push_back(new SingleSplitViewExample); - examples->push_back(new SliderExample); - examples->push_back(new TabbedPaneExample); - examples->push_back(new TableExample); - examples->push_back(new TextExample); - examples->push_back(new TextfieldExample); - examples->push_back(new ThrobberExample); - examples->push_back(new TreeViewExample); - examples->push_back(new WidgetExample); - return examples.Pass(); -} - -struct ExampleTitleCompare { - bool operator() (ExampleBase* a, ExampleBase* b) { - return a->example_title() < b->example_title(); - } -}; - -ScopedExamples GetExamplesToShow(ScopedExamples extra) { - ScopedExamples examples(CreateExamples()); - if (extra.get()) { - examples->insert(examples->end(), extra->begin(), extra->end()); - extra->weak_clear(); - } - std::sort(examples->begin(), examples->end(), ExampleTitleCompare()); - return examples.Pass(); -} - -} // namespace - -// Model for the examples that are being added via AddExample(). -class ComboboxModelExampleList : public ui::ComboboxModel { - public: - ComboboxModelExampleList() {} - virtual ~ComboboxModelExampleList() {} - - void SetExamples(ScopedExamples examples) { - example_list_.swap(*examples); - } - - // ui::ComboboxModel: - virtual int GetItemCount() const override { return example_list_.size(); } - virtual base::string16 GetItemAt(int index) override { - return base::UTF8ToUTF16(example_list_[index]->example_title()); - } - - View* GetItemViewAt(int index) { - return example_list_[index]->example_view(); - } - - private: - ScopedVector<ExampleBase> example_list_; - - DISALLOW_COPY_AND_ASSIGN(ComboboxModelExampleList); -}; - -class ExamplesWindowContents : public WidgetDelegateView, - public ComboboxListener { - public: - ExamplesWindowContents(Operation operation, ScopedExamples examples) - : combobox_(new Combobox(&combobox_model_)), - example_shown_(new View), - status_label_(new Label), - operation_(operation) { - instance_ = this; - combobox_->set_listener(this); - combobox_model_.SetExamples(examples.Pass()); - combobox_->ModelChanged(); - - set_background(Background::CreateStandardPanelBackground()); - GridLayout* layout = new GridLayout(this); - SetLayoutManager(layout); - ColumnSet* column_set = layout->AddColumnSet(0); - column_set->AddPaddingColumn(0, 5); - column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1, - GridLayout::USE_PREF, 0, 0); - column_set->AddPaddingColumn(0, 5); - layout->AddPaddingRow(0, 5); - layout->StartRow(0 /* no expand */, 0); - layout->AddView(combobox_); - - if (combobox_model_.GetItemCount() > 0) { - layout->StartRow(1, 0); - example_shown_->SetLayoutManager(new FillLayout()); - example_shown_->AddChildView(combobox_model_.GetItemViewAt(0)); - layout->AddView(example_shown_); - } - - layout->StartRow(0 /* no expand */, 0); - layout->AddView(status_label_); - layout->AddPaddingRow(0, 5); - } - - virtual ~ExamplesWindowContents() { - // Delete |combobox_| first as it references |combobox_model_|. - delete combobox_; - combobox_ = NULL; - } - - // Prints a message in the status area, at the bottom of the window. - void SetStatus(const std::string& status) { - status_label_->SetText(base::UTF8ToUTF16(status)); - } - - static ExamplesWindowContents* instance() { return instance_; } - - private: - // WidgetDelegateView: - virtual bool CanResize() const override { return true; } - virtual bool CanMaximize() const override { return true; } - virtual bool CanMinimize() const override { return true; } - virtual base::string16 GetWindowTitle() const override { - return base::ASCIIToUTF16("Views Examples"); - } - virtual View* GetContentsView() override { return this; } - virtual void WindowClosing() override { - instance_ = NULL; - if (operation_ == QUIT_ON_CLOSE) - base::MessageLoopForUI::current()->Quit(); - } - - // ComboboxListener: - virtual void OnPerformAction(Combobox* combobox) override { - DCHECK_EQ(combobox, combobox_); - DCHECK(combobox->selected_index() < combobox_model_.GetItemCount()); - example_shown_->RemoveAllChildViews(false); - example_shown_->AddChildView(combobox_model_.GetItemViewAt( - combobox->selected_index())); - example_shown_->RequestFocus(); - SetStatus(std::string()); - Layout(); - } - - static ExamplesWindowContents* instance_; - ComboboxModelExampleList combobox_model_; - Combobox* combobox_; - View* example_shown_; - Label* status_label_; - const Operation operation_; - - DISALLOW_COPY_AND_ASSIGN(ExamplesWindowContents); -}; - -// static -ExamplesWindowContents* ExamplesWindowContents::instance_ = NULL; - -void ShowExamplesWindow(Operation operation, - gfx::NativeWindow window_context, - ScopedExamples extra_examples) { - if (ExamplesWindowContents::instance()) { - ExamplesWindowContents::instance()->GetWidget()->Activate(); - } else { - ScopedExamples examples(GetExamplesToShow(extra_examples.Pass())); - Widget* widget = new Widget; - Widget::InitParams params; - params.delegate = new ExamplesWindowContents(operation, examples.Pass()); - params.context = window_context; - params.bounds = gfx::Rect(0, 0, 850, 300); - widget->Init(params); - widget->Show(); - } -} - -void LogStatus(const std::string& string) { - ExamplesWindowContents::instance()->SetStatus(string); -} - -} // namespace examples -} // namespace views
diff --git a/ui/views/examples/examples_window.h b/ui/views/examples/examples_window.h deleted file mode 100644 index 3393895..0000000 --- a/ui/views/examples/examples_window.h +++ /dev/null
@@ -1,38 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_EXAMPLES_EXAMPLES_WINDOW_H_ -#define UI_VIEWS_EXAMPLES_EXAMPLES_WINDOW_H_ - -#include "base/memory/scoped_ptr.h" -#include "base/memory/scoped_vector.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/views/examples/views_examples_export.h" - -namespace aura { -class Window; -} - -namespace views { -namespace examples { - -class ExampleBase; - -enum Operation { - DO_NOTHING_ON_CLOSE = 0, - QUIT_ON_CLOSE, -}; - -// 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( - Operation operation, - gfx::NativeWindow window_context, - scoped_ptr<ScopedVector<ExampleBase> > extra_examples); - -} // namespace examples -} // namespace views - -#endif // UI_VIEWS_EXAMPLES_EXAMPLES_WINDOW_H_
diff --git a/ui/views/examples/examples_window_with_content.cc b/ui/views/examples/examples_window_with_content.cc deleted file mode 100644 index bbc88b2..0000000 --- a/ui/views/examples/examples_window_with_content.cc +++ /dev/null
@@ -1,23 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/examples/examples_window_with_content.h" - -#include "content/public/browser/browser_context.h" -#include "ui/views/examples/webview_example.h" - -namespace views { -namespace examples { - -void ShowExamplesWindowWithContent(Operation operation, - content::BrowserContext* browser_context, - gfx::NativeWindow window_context) { - scoped_ptr<ScopedVector<ExampleBase> > extra_examples( - new ScopedVector<ExampleBase>); - extra_examples->push_back(new WebViewExample(browser_context)); - ShowExamplesWindow(operation, window_context, extra_examples.Pass()); -} - -} // namespace examples -} // namespace views
diff --git a/ui/views/examples/examples_window_with_content.h b/ui/views/examples/examples_window_with_content.h deleted file mode 100644 index 945201b..0000000 --- a/ui/views/examples/examples_window_with_content.h +++ /dev/null
@@ -1,28 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_EXAMPLES_EXAMPLES_WINDOW_WITH_CONTENT_H_ -#define UI_VIEWS_EXAMPLES_EXAMPLES_WINDOW_WITH_CONTENT_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 { -namespace examples { - -// Shows a window with the views examples in it. -VIEWS_EXAMPLES_WITH_CONTENT_EXPORT void ShowExamplesWindowWithContent( - Operation operation, - content::BrowserContext* browser_context, - gfx::NativeWindow window_context); - -} // namespace examples -} // namespace views - -#endif // UI_VIEWS_EXAMPLES_EXAMPLES_WINDOW_WITH_CONTENT_H_
diff --git a/ui/views/examples/examples_with_content_main_exe.cc b/ui/views/examples/examples_with_content_main_exe.cc deleted file mode 100644 index 6d5613e..0000000 --- a/ui/views/examples/examples_with_content_main_exe.cc +++ /dev/null
@@ -1,49 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/bind.h" -#include "content/public/browser/browser_context.h" -#include "ui/views/examples/examples_window_with_content.h" -#include "ui/views_content_client/views_content_client.h" - -#if defined(OS_WIN) -#include "content/public/app/startup_helper_win.h" -#include "sandbox/win/src/sandbox_types.h" -#endif - -namespace { - -void ShowContentExampleWindow(content::BrowserContext* browser_context, - gfx::NativeWindow window_context) { - views::examples::ShowExamplesWindowWithContent(views::examples::QUIT_ON_CLOSE, - 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) { - content::BrowserContext::SaveSessionState(NULL); - NOTREACHED(); - } -} - -} // namespace - -#if defined(OS_WIN) -int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t*, int) { - sandbox::SandboxInterfaceInfo sandbox_info = {0}; - content::InitializeSandboxInfo(&sandbox_info); - ui::ViewsContentClient views_content_client(instance, &sandbox_info); -#else -int main(int argc, const char** argv) { - ui::ViewsContentClient views_content_client(argc, argv); -#endif - - views_content_client.set_task(base::Bind(&ShowContentExampleWindow)); - return views_content_client.RunMain(); -}
diff --git a/ui/views/examples/label_example.cc b/ui/views/examples/label_example.cc deleted file mode 100644 index 89e3223..0000000 --- a/ui/views/examples/label_example.cc +++ /dev/null
@@ -1,215 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/examples/label_example.h" - -#include "base/strings/utf_string_conversions.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/layout/box_layout.h" -#include "ui/views/layout/grid_layout.h" -#include "ui/views/view.h" - -using base::ASCIIToUTF16; -using base::WideToUTF16; - -namespace views { -namespace examples { - -namespace { - -const char* kElideBehaviors[] = { "No Elide", "Truncate", "Elide Head", - "Elide Middle", "Elide Tail", "Elide Email", "Fade Tail" }; -const char* kAlignments[] = { "Left", "Center", "Right", "Head" }; - -// A Label with a clamped preferred width to demonstrate eliding or wrapping. -class PreferredSizeLabel : public Label { - public: - PreferredSizeLabel() : Label() { - SetBorder(Border::CreateSolidBorder(1, SK_ColorGRAY)); - } - virtual ~PreferredSizeLabel() {} - - // Label: - virtual gfx::Size GetPreferredSize() const override { - return gfx::Size(50, Label::GetPreferredSize().height()); - } - - private: - DISALLOW_COPY_AND_ASSIGN(PreferredSizeLabel); -}; - -} // namespace - -LabelExample::LabelExample() - : ExampleBase("Label"), - textfield_(NULL), - alignment_(NULL), - elide_behavior_(NULL), - multiline_(NULL), - shadows_(NULL), - custom_label_(NULL) { -} - -LabelExample::~LabelExample() { - // Remove the views first as some reference combobox models. - container()->RemoveAllChildViews(true); -} - -void LabelExample::CreateExampleView(View* container) { - // A very simple label example, followed by additional helpful examples. - container->SetLayoutManager(new BoxLayout(BoxLayout::kVertical, 0, 0, 10)); - Label* label = new Label(ASCIIToUTF16("Hello world!")); - container->AddChildView(label); - - const wchar_t hello_world_hebrew[] = - L"\x5e9\x5dc\x5d5\x5dd \x5d4\x5e2\x5d5\x5dc\x5dd!"; - label = new Label(WideToUTF16(hello_world_hebrew)); - label->SetHorizontalAlignment(gfx::ALIGN_RIGHT); - container->AddChildView(label); - - label = new Label(WideToUTF16(L"A UTF16 surrogate pair: \x5d0\x5b0")); - label->SetHorizontalAlignment(gfx::ALIGN_RIGHT); - container->AddChildView(label); - - label = new Label(ASCIIToUTF16("A left-aligned blue label.")); - label->SetHorizontalAlignment(gfx::ALIGN_LEFT); - label->SetEnabledColor(SK_ColorBLUE); - container->AddChildView(label); - - label = new Label(WideToUTF16(L"Password!")); - label->SetObscured(true); - container->AddChildView(label); - - label = new Label(ASCIIToUTF16("A Courier-18 label with shadows.")); - label->SetFontList(gfx::FontList("Courier, 18px")); - gfx::ShadowValues shadows(1, gfx::ShadowValue(gfx::Point(), 1, SK_ColorRED)); - gfx::ShadowValue shadow(gfx::Point(2, 2), 0, SK_ColorGRAY); - shadows.push_back(shadow); - label->SetShadows(shadows); - container->AddChildView(label); - - label = new PreferredSizeLabel(); - label->SetText(ASCIIToUTF16("A long label will elide toward its logical end " - "if the text's width exceeds the label's available width.")); - container->AddChildView(label); - - label = new PreferredSizeLabel(); - label->SetText(ASCIIToUTF16("A multi-line label will wrap onto subsequent " - "lines if the text's width exceeds the label's available width, which is " - "helpful for extemely long text used to demonstrate line wrapping.")); - label->SetMultiLine(true); - container->AddChildView(label); - - AddCustomLabel(container); -} - -void LabelExample::ButtonPressed(Button* button, const ui::Event& event) { - if (button == multiline_) { - custom_label_->SetMultiLine(multiline_->checked()); - } else if (button == shadows_) { - gfx::ShadowValues shadows; - if (shadows_->checked()) { - shadows.push_back(gfx::ShadowValue(gfx::Point(), 1, SK_ColorRED)); - shadows.push_back(gfx::ShadowValue(gfx::Point(2, 2), 0, SK_ColorGRAY)); - } - custom_label_->SetShadows(shadows); - } - custom_label_->parent()->parent()->Layout(); - custom_label_->SchedulePaint(); -} - -void LabelExample::OnPerformAction(Combobox* combobox) { - if (combobox == alignment_) { - custom_label_->SetHorizontalAlignment( - static_cast<gfx::HorizontalAlignment>(combobox->selected_index())); - } else if (combobox == elide_behavior_) { - custom_label_->SetElideBehavior( - static_cast<gfx::ElideBehavior>(combobox->selected_index())); - } -} - -void LabelExample::ContentsChanged(Textfield* sender, - const base::string16& new_contents) { - custom_label_->SetText(new_contents); - custom_label_->parent()->parent()->Layout(); -} - -void LabelExample::AddCustomLabel(View* container) { - View* control_container = new View(); - control_container->SetBorder(Border::CreateSolidBorder(2, SK_ColorGRAY)); - control_container->set_background( - Background::CreateSolidBackground(SK_ColorLTGRAY)); - GridLayout* layout = GridLayout::CreatePanel(control_container); - control_container->SetLayoutManager(layout); - - ColumnSet* column_set = layout->AddColumnSet(0); - column_set->AddColumn(GridLayout::LEADING, GridLayout::FILL, - 0.0f, GridLayout::USE_PREF, 0, 0); - column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, - 1.0f, GridLayout::USE_PREF, 0, 0); - - layout->StartRow(0, 0); - layout->AddView(new Label(ASCIIToUTF16("Content: "))); - textfield_ = new Textfield(); - textfield_->SetText(ASCIIToUTF16("Use the provided controls to configure the " - "content and presentation of this custom label.")); - textfield_->SetSelectionRange(gfx::Range()); - textfield_->set_controller(this); - layout->AddView(textfield_); - - alignment_ = AddCombobox(layout, "Alignment: ", kAlignments, - arraysize(kAlignments)); - elide_behavior_ = AddCombobox(layout, "Elide Behavior: ", kElideBehaviors, - arraysize(kElideBehaviors)); - - column_set = layout->AddColumnSet(1); - column_set->AddColumn(GridLayout::LEADING, GridLayout::LEADING, - 0, GridLayout::USE_PREF, 0, 0); - column_set->AddColumn(GridLayout::LEADING, GridLayout::LEADING, - 0, GridLayout::USE_PREF, 0, 0); - layout->StartRow(0, 1); - multiline_ = new Checkbox(base::ASCIIToUTF16("Multiline")); - multiline_->set_listener(this); - layout->AddView(multiline_); - shadows_ = new Checkbox(base::ASCIIToUTF16("Shadows")); - shadows_->set_listener(this); - layout->AddView(shadows_); - layout->AddPaddingRow(0, 8); - - column_set = layout->AddColumnSet(2); - column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, - 1, GridLayout::USE_PREF, 0, 0); - layout->StartRow(0, 2); - custom_label_ = new PreferredSizeLabel(); - custom_label_->SetHorizontalAlignment(gfx::ALIGN_LEFT); - custom_label_->SetElideBehavior(gfx::NO_ELIDE); - custom_label_->SetText(textfield_->text()); - layout->AddView(custom_label_); - - container->AddChildView(control_container); -} - -Combobox* LabelExample::AddCombobox(GridLayout* layout, - const char* name, - const char** strings, - int count) { - layout->StartRow(0, 0); - layout->AddView(new Label(base::ASCIIToUTF16(name))); - ExampleComboboxModel* model = new ExampleComboboxModel(strings, count); - example_combobox_models_.push_back(model); - Combobox* combobox = new Combobox(model); - combobox->SetSelectedIndex(0); - combobox->set_listener(this); - layout->AddView(combobox); - return combobox; -} - -} // namespace examples -} // namespace views
diff --git a/ui/views/examples/label_example.h b/ui/views/examples/label_example.h deleted file mode 100644 index f597742..0000000 --- a/ui/views/examples/label_example.h +++ /dev/null
@@ -1,69 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_EXAMPLES_LABEL_EXAMPLE_H_ -#define UI_VIEWS_EXAMPLES_LABEL_EXAMPLE_H_ - -#include "base/macros.h" -#include "ui/views/controls/button/button.h" -#include "ui/views/controls/combobox/combobox_listener.h" -#include "ui/views/controls/textfield/textfield_controller.h" -#include "ui/views/examples/example_base.h" - -namespace views { - -class Checkbox; -class GridLayout; -class Label; - -namespace examples { - -class ExampleComboboxModel; - -class VIEWS_EXAMPLES_EXPORT LabelExample : public ExampleBase, - public ButtonListener, - public ComboboxListener, - public TextfieldController { - public: - LabelExample(); - virtual ~LabelExample(); - - // ExampleBase: - virtual void CreateExampleView(View* container) override; - - // ButtonListener: - virtual void ButtonPressed(Button* button, const ui::Event& event) override; - - // ComboboxListener: - virtual void OnPerformAction(Combobox* combobox) override; - - // TextfieldController: - virtual void ContentsChanged(Textfield* sender, - const base::string16& new_contents) 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(GridLayout* layout, - const char* name, - const char** strings, - int count); - - Textfield* textfield_; - Combobox* alignment_; - Combobox* elide_behavior_; - ScopedVector<ExampleComboboxModel> example_combobox_models_; - Checkbox* multiline_; - Checkbox* shadows_; - Label* custom_label_; - - DISALLOW_COPY_AND_ASSIGN(LabelExample); -}; - -} // namespace examples -} // namespace views - -#endif // UI_VIEWS_EXAMPLES_LABEL_EXAMPLE_H_
diff --git a/ui/views/examples/link_example.cc b/ui/views/examples/link_example.cc deleted file mode 100644 index 3795c8c..0000000 --- a/ui/views/examples/link_example.cc +++ /dev/null
@@ -1,34 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/examples/link_example.h" - -#include "base/strings/utf_string_conversions.h" -#include "ui/views/controls/link.h" -#include "ui/views/layout/fill_layout.h" -#include "ui/views/view.h" - -namespace views { -namespace examples { - -LinkExample::LinkExample() : ExampleBase("Link") { -} - -LinkExample::~LinkExample() { -} - -void LinkExample::CreateExampleView(View* container) { - link_ = new Link(base::ASCIIToUTF16("Click me!")); - link_->set_listener(this); - - container->SetLayoutManager(new FillLayout); - container->AddChildView(link_); -} - -void LinkExample::LinkClicked(Link* source, int event_flags) { - PrintStatus("Link clicked"); -} - -} // namespace examples -} // namespace views
diff --git a/ui/views/examples/link_example.h b/ui/views/examples/link_example.h deleted file mode 100644 index fa6bb57..0000000 --- a/ui/views/examples/link_example.h +++ /dev/null
@@ -1,36 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_EXAMPLES_LINK_EXAMPLE_H_ -#define UI_VIEWS_EXAMPLES_LINK_EXAMPLE_H_ - -#include "base/macros.h" -#include "ui/views/controls/link_listener.h" -#include "ui/views/examples/example_base.h" - -namespace views { -namespace examples { - -class VIEWS_EXAMPLES_EXPORT LinkExample : public ExampleBase, - public LinkListener { - public: - LinkExample(); - virtual ~LinkExample(); - - // ExampleBase: - virtual void CreateExampleView(View* container) override; - - private: - // LinkListener: - virtual void LinkClicked(Link* source, int event_flags) override; - - Link* link_; - - DISALLOW_COPY_AND_ASSIGN(LinkExample); -}; - -} // namespace examples -} // namespace views - -#endif // UI_VIEWS_EXAMPLES_LINK_EXAMPLE_H_
diff --git a/ui/views/examples/menu_example.cc b/ui/views/examples/menu_example.cc deleted file mode 100644 index 1b95457..0000000 --- a/ui/views/examples/menu_example.cc +++ /dev/null
@@ -1,225 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/examples/menu_example.h" - -#include <set> - -#include "base/strings/utf_string_conversions.h" -#include "ui/base/models/simple_menu_model.h" -#include "ui/views/controls/button/menu_button.h" -#include "ui/views/controls/button/menu_button_listener.h" -#include "ui/views/controls/menu/menu_runner.h" -#include "ui/views/layout/fill_layout.h" -#include "ui/views/view.h" -#include "ui/views/widget/widget.h" - -using base::ASCIIToUTF16; - -namespace views { -namespace examples { - -namespace { - -class ExampleMenuModel : public ui::SimpleMenuModel, - public ui::SimpleMenuModel::Delegate { - public: - ExampleMenuModel(); - - // ui::SimpleMenuModel::Delegate: - virtual bool IsCommandIdChecked(int command_id) const override; - virtual bool IsCommandIdEnabled(int command_id) const override; - virtual bool GetAcceleratorForCommandId( - int command_id, - ui::Accelerator* accelerator) override; - virtual 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, - }; - - scoped_ptr<ui::SimpleMenuModel> submenu_; - std::set<int> checked_fruits_; - int current_encoding_command_id_; - - DISALLOW_COPY_AND_ASSIGN(ExampleMenuModel); -}; - -class ExampleMenuButton : public MenuButton, public MenuButtonListener { - public: - explicit ExampleMenuButton(const base::string16& test); - virtual ~ExampleMenuButton(); - - private: - // MenuButtonListener: - virtual void OnMenuButtonClicked(View* source, - const gfx::Point& point) override; - - ui::SimpleMenuModel* GetMenuModel(); - - scoped_ptr<ExampleMenuModel> menu_model_; - scoped_ptr<MenuRunner> menu_runner_; - - DISALLOW_COPY_AND_ASSIGN(ExampleMenuButton); -}; - -// ExampleMenuModel --------------------------------------------------------- - -ExampleMenuModel::ExampleMenuModel() - : ui::SimpleMenuModel(this), - current_encoding_command_id_(COMMAND_SELECT_ASCII) { - AddItem(COMMAND_DO_SOMETHING, ASCIIToUTF16("Do Something")); - AddSeparator(ui::NORMAL_SEPARATOR); - AddRadioItem(COMMAND_SELECT_ASCII, ASCIIToUTF16("ASCII"), - GROUP_MAKE_DECISION); - AddRadioItem(COMMAND_SELECT_UTF8, ASCIIToUTF16("UTF-8"), - GROUP_MAKE_DECISION); - AddRadioItem(COMMAND_SELECT_UTF16, ASCIIToUTF16("UTF-16"), - GROUP_MAKE_DECISION); - AddSeparator(ui::NORMAL_SEPARATOR); - AddCheckItem(COMMAND_CHECK_APPLE, ASCIIToUTF16("Apple")); - AddCheckItem(COMMAND_CHECK_ORANGE, ASCIIToUTF16("Orange")); - AddCheckItem(COMMAND_CHECK_KIWI, ASCIIToUTF16("Kiwi")); - AddSeparator(ui::NORMAL_SEPARATOR); - AddItem(COMMAND_GO_HOME, ASCIIToUTF16("Go Home")); - - submenu_.reset(new ui::SimpleMenuModel(this)); - submenu_->AddItem(COMMAND_DO_SOMETHING, ASCIIToUTF16("Do Something 2")); - AddSubMenu(0, ASCIIToUTF16("Submenu"), 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; -} - -bool ExampleMenuModel::GetAcceleratorForCommandId( - int command_id, - ui::Accelerator* accelerator) { - // We don't use this in the example. - return false; -} - -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. - std::set<int>::iterator 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 base::string16& test) - : MenuButton(NULL, test, this, true) { -} - -ExampleMenuButton::~ExampleMenuButton() { -} - -void ExampleMenuButton::OnMenuButtonClicked(View* source, - const gfx::Point& point) { - menu_runner_.reset(new MenuRunner(GetMenuModel(), MenuRunner::HAS_MNEMONICS)); - - if (menu_runner_->RunMenuAt(source->GetWidget()->GetTopLevelWidget(), - this, - gfx::Rect(point, gfx::Size()), - MENU_ANCHOR_TOPRIGHT, - ui::MENU_SOURCE_NONE) == - MenuRunner::MENU_DELETED) { - return; - } -} - -ui::SimpleMenuModel* ExampleMenuButton::GetMenuModel() { - if (!menu_model_.get()) - menu_model_.reset(new ExampleMenuModel); - return menu_model_.get(); -} - -} // namespace - -MenuExample::MenuExample() : ExampleBase("Menu") { -} - -MenuExample::~MenuExample() { -} - -void MenuExample::CreateExampleView(View* container) { - // We add a button to open a menu. - ExampleMenuButton* menu_button = new ExampleMenuButton( - ASCIIToUTF16("Open a menu")); - container->SetLayoutManager(new FillLayout); - container->AddChildView(menu_button); -} - -} // namespace examples -} // namespace views
diff --git a/ui/views/examples/menu_example.h b/ui/views/examples/menu_example.h deleted file mode 100644 index af370b3..0000000 --- a/ui/views/examples/menu_example.h +++ /dev/null
@@ -1,31 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_EXAMPLES_MENU_EXAMPLE_H_ -#define UI_VIEWS_EXAMPLES_MENU_EXAMPLE_H_ - -#include "base/macros.h" -#include "ui/views/examples/example_base.h" - -namespace views { -namespace examples { - -// MenuExample demonstrates how to use the MenuModelAdapter and MenuRunner -// classes. -class VIEWS_EXAMPLES_EXPORT MenuExample : public ExampleBase { - public: - MenuExample(); - virtual ~MenuExample(); - - // ExampleBase: - virtual void CreateExampleView(View* container) override; - - private: - DISALLOW_COPY_AND_ASSIGN(MenuExample); -}; - -} // namespace examples -} // namespace views - -#endif // UI_VIEWS_EXAMPLES_MENU_EXAMPLE_H_
diff --git a/ui/views/examples/message_box_example.cc b/ui/views/examples/message_box_example.cc deleted file mode 100644 index cb9e924..0000000 --- a/ui/views/examples/message_box_example.cc +++ /dev/null
@@ -1,68 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/examples/message_box_example.h" - -#include "base/strings/utf_string_conversions.h" -#include "ui/views/controls/button/label_button.h" -#include "ui/views/controls/message_box_view.h" -#include "ui/views/layout/grid_layout.h" -#include "ui/views/view.h" - -using base::ASCIIToUTF16; - -namespace views { -namespace examples { - -MessageBoxExample::MessageBoxExample() : ExampleBase("Message Box View") { -} - -MessageBoxExample::~MessageBoxExample() { -} - -void MessageBoxExample::CreateExampleView(View* container) { - message_box_view_ = new MessageBoxView( - MessageBoxView::InitParams(ASCIIToUTF16("Hello, world!"))); - status_ = new LabelButton(this, ASCIIToUTF16("Show Status")); - toggle_ = new LabelButton(this, ASCIIToUTF16("Toggle Checkbox")); - - GridLayout* layout = new GridLayout(container); - container->SetLayoutManager(layout); - - message_box_view_->SetCheckBoxLabel(ASCIIToUTF16("Check Box")); - - const int message_box_column = 0; - ColumnSet* column_set = layout->AddColumnSet(message_box_column); - column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1, - GridLayout::USE_PREF, 0, 0); - layout->StartRow(1 /* expand */, message_box_column); - layout->AddView(message_box_view_); - - const int button_column = 1; - column_set = layout->AddColumnSet(button_column); - column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, - 0.5f, GridLayout::USE_PREF, 0, 0); - column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, - 0.5f, GridLayout::USE_PREF, 0, 0); - - layout->StartRow(0 /* no expand */, button_column); - - layout->AddView(status_); - layout->AddView(toggle_); -} - -void MessageBoxExample::ButtonPressed(Button* sender, const ui::Event& event) { - if (sender == status_) { - message_box_view_->SetCheckBoxLabel( - ASCIIToUTF16(BoolToOnOff(message_box_view_->IsCheckBoxSelected()))); - PrintStatus(message_box_view_->IsCheckBoxSelected() ? - "Check Box Selected" : "Check Box Not Selected"); - } else if (sender == toggle_) { - message_box_view_->SetCheckBoxSelected( - !message_box_view_->IsCheckBoxSelected()); - } -} - -} // namespace examples -} // namespace views
diff --git a/ui/views/examples/message_box_example.h b/ui/views/examples/message_box_example.h deleted file mode 100644 index fe3ba67..0000000 --- a/ui/views/examples/message_box_example.h +++ /dev/null
@@ -1,47 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_EXAMPLES_MESSAGE_BOX_EXAMPLE_H_ -#define UI_VIEWS_EXAMPLES_MESSAGE_BOX_EXAMPLE_H_ - -#include <string> - -#include "base/macros.h" -#include "ui/views/controls/button/button.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 ButtonListener { - public: - MessageBoxExample(); - virtual ~MessageBoxExample(); - - // ExampleBase: - virtual void CreateExampleView(View* container) override; - - private: - // ButtonListener: - virtual void ButtonPressed(Button* sender, const ui::Event& event) override; - - // The MessageBoxView to be tested. - MessageBoxView* message_box_view_; - - // Control buttons to show the status and toggle checkbox in the - // message box. - Button* status_; - Button* toggle_; - - DISALLOW_COPY_AND_ASSIGN(MessageBoxExample); -}; - -} // namespace examples -} // namespace views - -#endif // UI_VIEWS_EXAMPLES_MESSAGE_BOX_EXAMPLE_H_
diff --git a/ui/views/examples/multiline_example.cc b/ui/views/examples/multiline_example.cc deleted file mode 100644 index d2d69cc..0000000 --- a/ui/views/examples/multiline_example.cc +++ /dev/null
@@ -1,191 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/examples/multiline_example.h" - -#include "base/strings/utf_string_conversions.h" -#include "ui/events/event.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/layout/grid_layout.h" -#include "ui/views/view.h" - -using base::ASCIIToUTF16; - -namespace views { -namespace 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() : Label() {} - virtual ~PreferredSizeLabel() {} - - // Label: - virtual gfx::Size GetPreferredSize() const override { - return gfx::Size(50, Label::GetPreferredSize().height()); - } - - private: - DISALLOW_COPY_AND_ASSIGN(PreferredSizeLabel); -}; - -} // namespace - -// A simple View that hosts a RenderText object. -class MultilineExample::RenderTextView : public View { - public: - RenderTextView() : render_text_(gfx::RenderText::CreateInstance()) { - render_text_->SetHorizontalAlignment(gfx::ALIGN_CENTER); - render_text_->SetColor(SK_ColorBLACK); - render_text_->SetMultiline(true); - SetBorder(Border::CreateSolidBorder(2, SK_ColorGRAY)); - } - - virtual void OnPaint(gfx::Canvas* canvas) override { - View::OnPaint(canvas); - render_text_->Draw(canvas); - } - - virtual gfx::Size GetPreferredSize() 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; - } - - virtual 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 SetText(const base::string16& 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 color_range = ClampRange(gfx::Range(1, 21), range_max); - 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_->SetColor(SK_ColorBLACK); - render_text_->ApplyColor(0xFFFF0000, color_range); - render_text_->SetStyle(gfx::DIAGONAL_STRIKE, false); - render_text_->ApplyStyle(gfx::DIAGONAL_STRIKE, true, color_range); - render_text_->SetStyle(gfx::UNDERLINE, false); - render_text_->ApplyStyle(gfx::UNDERLINE, true, color_range); - render_text_->ApplyStyle(gfx::BOLD, true, bold_range); - render_text_->ApplyStyle(gfx::ITALIC, true, italic_range); - InvalidateLayout(); - } - - private: - virtual void OnBoundsChanged(const gfx::Rect& previous_bounds) override { - gfx::Rect bounds = GetLocalBounds(); - bounds.Inset(GetInsets()); - render_text_->SetDisplayRect(bounds); - } - - scoped_ptr<gfx::RenderText> render_text_; - - DISALLOW_COPY_AND_ASSIGN(RenderTextView); -}; - -MultilineExample::MultilineExample() - : ExampleBase("Multiline RenderText"), - render_text_view_(NULL), - label_(NULL), - textfield_(NULL), - label_checkbox_(NULL) { -} - -MultilineExample::~MultilineExample() { -} - -void MultilineExample::CreateExampleView(View* container) { - const base::string16 kTestString = base::WideToUTF16(L"qwerty" - L"\x627\x644\x631\x626\x64A\x633\x64A\x629" - L"asdfgh"); - - render_text_view_ = new RenderTextView(); - render_text_view_->SetText(kTestString); - - label_ = new PreferredSizeLabel(); - label_->SetText(kTestString); - label_->SetMultiLine(true); - label_->SetBorder(Border::CreateSolidBorder(2, SK_ColorCYAN)); - - label_checkbox_ = new Checkbox(ASCIIToUTF16("views::Label:")); - label_checkbox_->SetChecked(true); - label_checkbox_->set_listener(this); - label_checkbox_->set_request_focus_on_press(false); - - textfield_ = new Textfield(); - textfield_->set_controller(this); - textfield_->SetText(kTestString); - - GridLayout* layout = new GridLayout(container); - container->SetLayoutManager(layout); - - ColumnSet* column_set = layout->AddColumnSet(0); - column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, - 0.0f, GridLayout::USE_PREF, 0, 0); - column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, - 1.0f, GridLayout::FIXED, 0, 0); - - layout->StartRow(0, 0); - layout->AddView(new Label(ASCIIToUTF16("gfx::RenderText:"))); - layout->AddView(render_text_view_); - - layout->StartRow(0, 0); - layout->AddView(label_checkbox_); - layout->AddView(label_); - - layout->StartRow(0, 0); - layout->AddView(new Label(ASCIIToUTF16("Sample Text:"))); - layout->AddView(textfield_); -} - -void MultilineExample::ContentsChanged(Textfield* sender, - const base::string16& new_contents) { - render_text_view_->SetText(new_contents); - if (label_checkbox_->checked()) - label_->SetText(new_contents); - container()->Layout(); - container()->SchedulePaint(); -} - -void MultilineExample::ButtonPressed(Button* sender, const ui::Event& event) { - DCHECK_EQ(sender, label_checkbox_); - label_->SetText(label_checkbox_->checked() ? textfield_->text() : - base::string16()); - container()->Layout(); - container()->SchedulePaint(); -} - -} // namespace examples -} // namespace views
diff --git a/ui/views/examples/multiline_example.h b/ui/views/examples/multiline_example.h deleted file mode 100644 index 8b0888c..0000000 --- a/ui/views/examples/multiline_example.h +++ /dev/null
@@ -1,54 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_EXAMPLES_MULTILINE_EXAMPLE_H_ -#define UI_VIEWS_EXAMPLES_MULTILINE_EXAMPLE_H_ - -#include "base/macros.h" -#include "ui/views/controls/button/button.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 ButtonListener { - public: - MultilineExample(); - virtual ~MultilineExample(); - - // ExampleBase: - virtual void CreateExampleView(View* container) override; - - // ButtonListener: - virtual void ButtonPressed(Button* sender, const ui::Event& event) override; - - private: - class RenderTextView; - - // TextfieldController: - virtual void ContentsChanged(Textfield* sender, - const base::string16& new_contents) override; - - RenderTextView* render_text_view_; - Label* label_; - Textfield* textfield_; - - // Checkbox to enable and disable text rendering in |label_|. - Checkbox* label_checkbox_; - - DISALLOW_COPY_AND_ASSIGN(MultilineExample); -}; - -} // namespace examples -} // namespace views - -#endif // UI_VIEWS_EXAMPLES_MULTILINE_EXAMPLE_H_
diff --git a/ui/views/examples/progress_bar_example.cc b/ui/views/examples/progress_bar_example.cc deleted file mode 100644 index 8a860f2..0000000 --- a/ui/views/examples/progress_bar_example.cc +++ /dev/null
@@ -1,72 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/examples/progress_bar_example.h" - -#include <algorithm> - -#include "base/strings/utf_string_conversions.h" -#include "ui/views/controls/button/label_button.h" -#include "ui/views/controls/progress_bar.h" -#include "ui/views/layout/grid_layout.h" -#include "ui/views/view.h" - -namespace { - -const double kStepSize = 0.1; - -double SetToMax(double percent) { - return std::min(std::max(percent, 0.0), 1.0); -} - -} // namespace - -namespace views { -namespace examples { - -ProgressBarExample::ProgressBarExample() - : ExampleBase("Progress Bar"), - minus_button_(NULL), - plus_button_(NULL), - progress_bar_(NULL), - current_percent_(0.0) { -} - -ProgressBarExample::~ProgressBarExample() { -} - -void ProgressBarExample::CreateExampleView(View* container) { - GridLayout* layout = new GridLayout(container); - container->SetLayoutManager(layout); - - ColumnSet* column_set = layout->AddColumnSet(0); - column_set->AddColumn(GridLayout::LEADING, GridLayout::FILL, - 0, GridLayout::USE_PREF, 0, 0); - column_set->AddPaddingColumn(0, 8); - column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, - 1, GridLayout::USE_PREF, 0, 0); - column_set->AddPaddingColumn(0, 8); - column_set->AddColumn(GridLayout::TRAILING, GridLayout::FILL, - 0, GridLayout::USE_PREF, 0, 0); - - layout->StartRow(0, 0); - minus_button_ = new LabelButton(this, base::ASCIIToUTF16("-")); - layout->AddView(minus_button_); - progress_bar_ = new ProgressBar(); - layout->AddView(progress_bar_); - plus_button_ = new LabelButton(this, base::ASCIIToUTF16("+")); - layout->AddView(plus_button_); -} - -void ProgressBarExample::ButtonPressed(Button* sender, const ui::Event& event) { - if (sender == minus_button_) - current_percent_ = SetToMax(current_percent_ - kStepSize); - else if (sender == plus_button_) - current_percent_ = SetToMax(current_percent_ + kStepSize); - - progress_bar_->SetValue(current_percent_); -} - -} // namespace examples -} // namespace views
diff --git a/ui/views/examples/progress_bar_example.h b/ui/views/examples/progress_bar_example.h deleted file mode 100644 index c3291d1..0000000 --- a/ui/views/examples/progress_bar_example.h +++ /dev/null
@@ -1,41 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_EXAMPLES_PROGRESS_BAR_EXAMPLE_H_ -#define UI_VIEWS_EXAMPLES_PROGRESS_BAR_EXAMPLE_H_ - -#include "base/macros.h" -#include "ui/views/controls/button/button.h" -#include "ui/views/examples/example_base.h" - -namespace views { -class ProgressBar; - -namespace examples { - -class VIEWS_EXAMPLES_EXPORT ProgressBarExample : public ExampleBase, - public ButtonListener { - public: - ProgressBarExample(); - virtual ~ProgressBarExample(); - - // ExampleBase: - virtual void CreateExampleView(View* container) override; - - private: - // ButtonListener: - virtual void ButtonPressed(Button* button, const ui::Event& event) override; - - Button* minus_button_; - Button* plus_button_; - ProgressBar* progress_bar_; - double current_percent_; - - DISALLOW_COPY_AND_ASSIGN(ProgressBarExample); -}; - -} // namespace examples -} // namespace views - -#endif // UI_VIEWS_EXAMPLES_PROGRESS_BAR_EXAMPLE_H_
diff --git a/ui/views/examples/radio_button_example.cc b/ui/views/examples/radio_button_example.cc deleted file mode 100644 index 5e3c7dd..0000000 --- a/ui/views/examples/radio_button_example.cc +++ /dev/null
@@ -1,69 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/examples/radio_button_example.h" - -#include "base/strings/stringprintf.h" -#include "base/strings/utf_string_conversions.h" -#include "ui/views/controls/button/label_button.h" -#include "ui/views/controls/button/radio_button.h" -#include "ui/views/layout/grid_layout.h" -#include "ui/views/view.h" - -namespace views { -namespace examples { - -RadioButtonExample::RadioButtonExample() - : ExampleBase("Radio Button"), - count_(0) { -} - -RadioButtonExample::~RadioButtonExample() { -} - -void RadioButtonExample::CreateExampleView(View* container) { - select_ = new LabelButton(this, base::ASCIIToUTF16("Select")); - status_ = new LabelButton(this, base::ASCIIToUTF16("Show Status")); - - int group = 1; - for (size_t i = 0; i < arraysize(radio_buttons_); ++i) { - radio_buttons_[i] = new RadioButton( - base::UTF8ToUTF16(base::StringPrintf( - "Radio %d in group %d", static_cast<int>(i) + 1, group)), - group); - radio_buttons_[i]->set_listener(this); - } - - GridLayout* layout = new GridLayout(container); - container->SetLayoutManager(layout); - - ColumnSet* column_set = layout->AddColumnSet(0); - column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, - 1.0f, GridLayout::USE_PREF, 0, 0); - for (size_t i = 0; i < arraysize(radio_buttons_); ++i) { - layout->StartRow(0, 0); - layout->AddView(radio_buttons_[i]); - } - layout->StartRow(0, 0); - layout->AddView(select_); - layout->StartRow(0, 0); - layout->AddView(status_); -} - -void RadioButtonExample::ButtonPressed(Button* sender, const ui::Event& event) { - if (sender == select_) { - radio_buttons_[2]->SetChecked(true); - } else if (sender == status_) { - // Show the state of radio buttons. - PrintStatus("Group: 1:%s, 2:%s, 3:%s", - BoolToOnOff(radio_buttons_[0]->checked()), - BoolToOnOff(radio_buttons_[1]->checked()), - BoolToOnOff(radio_buttons_[2]->checked())); - } else { - PrintStatus("Pressed! count:%d", ++count_); - } -} - -} // namespace examples -} // namespace views
diff --git a/ui/views/examples/radio_button_example.h b/ui/views/examples/radio_button_example.h deleted file mode 100644 index 844e315..0000000 --- a/ui/views/examples/radio_button_example.h +++ /dev/null
@@ -1,50 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_EXAMPLES_RADIO_BUTTON_EXAMPLE_H_ -#define UI_VIEWS_EXAMPLES_RADIO_BUTTON_EXAMPLE_H_ - -#include <string> - -#include "base/macros.h" -#include "ui/views/controls/button/button.h" -#include "ui/views/examples/example_base.h" - -namespace views { - -class LabelButton; -class RadioButton; - -namespace examples { - -class VIEWS_EXAMPLES_EXPORT RadioButtonExample : public ExampleBase, - public ButtonListener { - public: - RadioButtonExample(); - virtual ~RadioButtonExample(); - - // ExampleBase: - virtual void CreateExampleView(View* container) override; - - private: - // ButtonListener: - virtual void ButtonPressed(Button* sender, const ui::Event& event) override; - - // Group of 3 radio buttons. - RadioButton* radio_buttons_[3]; - - // Control button to select radio buttons, and show the status of buttons. - LabelButton* select_; - LabelButton* status_; - - // The number of times the button is pressed. - int count_; - - DISALLOW_COPY_AND_ASSIGN(RadioButtonExample); -}; - -} // namespace examples -} // namespace views - -#endif // UI_VIEWS_EXAMPLES_RADIO_BUTTON_EXAMPLE_H_
diff --git a/ui/views/examples/scroll_view_example.cc b/ui/views/examples/scroll_view_example.cc deleted file mode 100644 index f6abfce..0000000 --- a/ui/views/examples/scroll_view_example.cc +++ /dev/null
@@ -1,117 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/examples/scroll_view_example.h" - -#include "base/strings/stringprintf.h" -#include "base/strings/utf_string_conversions.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/layout/grid_layout.h" -#include "ui/views/view.h" - -using base::ASCIIToUTF16; - -namespace views { -namespace examples { - -// ScrollView's content, which draws gradient color on background. -// TODO(oshima): add child views as well. -class ScrollViewExample::ScrollableView : public View { - public: - ScrollableView() { - SetColor(SK_ColorRED, SK_ColorCYAN); - AddChildView(new LabelButton(NULL, ASCIIToUTF16("Button"))); - AddChildView(new RadioButton(ASCIIToUTF16("Radio Button"), 0)); - } - - virtual gfx::Size GetPreferredSize() const override { - return gfx::Size(width(), height()); - } - - void SetColor(SkColor from, SkColor to) { - set_background(Background::CreateVerticalGradientBackground(from, to)); - } - - void PlaceChildY(int index, int y) { - View* view = child_at(index); - gfx::Size size = view->GetPreferredSize(); - view->SetBounds(0, y, size.width(), size.height()); - } - - virtual void Layout() override { - PlaceChildY(0, 0); - PlaceChildY(1, height() / 2); - SizeToPreferredSize(); - } - - private: - DISALLOW_COPY_AND_ASSIGN(ScrollableView); -}; - -ScrollViewExample::ScrollViewExample() : ExampleBase("Scroll View") { -} - -ScrollViewExample::~ScrollViewExample() { -} - -void ScrollViewExample::CreateExampleView(View* container) { - wide_ = new LabelButton(this, ASCIIToUTF16("Wide")); - tall_ = new LabelButton(this, ASCIIToUTF16("Tall")); - big_square_ = new LabelButton(this, ASCIIToUTF16("Big Square")); - small_square_ = new LabelButton(this, ASCIIToUTF16("Small Square")); - scroll_to_ = new LabelButton(this, ASCIIToUTF16("Scroll to")); - scrollable_ = new ScrollableView(); - scroll_view_ = new ScrollView(); - scroll_view_->SetContents(scrollable_); - scrollable_->SetBounds(0, 0, 1000, 100); - scrollable_->SetColor(SK_ColorYELLOW, SK_ColorCYAN); - - GridLayout* layout = new GridLayout(container); - container->SetLayoutManager(layout); - - // Add scroll view. - ColumnSet* column_set = layout->AddColumnSet(0); - column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1, - GridLayout::USE_PREF, 0, 0); - layout->StartRow(1, 0); - layout->AddView(scroll_view_); - - // Add control buttons. - column_set = layout->AddColumnSet(1); - for (int i = 0; i < 5; i++) { - column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1, - GridLayout::USE_PREF, 0, 0); - } - layout->StartRow(0, 1); - layout->AddView(wide_); - layout->AddView(tall_); - layout->AddView(big_square_); - layout->AddView(small_square_); - layout->AddView(scroll_to_); -} - -void ScrollViewExample::ButtonPressed(Button* sender, const ui::Event& event) { - if (sender == wide_) { - scrollable_->SetBounds(0, 0, 1000, 100); - scrollable_->SetColor(SK_ColorYELLOW, SK_ColorCYAN); - } else if (sender == tall_) { - scrollable_->SetBounds(0, 0, 100, 1000); - scrollable_->SetColor(SK_ColorRED, SK_ColorCYAN); - } else if (sender == big_square_) { - scrollable_->SetBounds(0, 0, 1000, 1000); - scrollable_->SetColor(SK_ColorRED, SK_ColorGREEN); - } else if (sender == small_square_) { - scrollable_->SetBounds(0, 0, 100, 100); - scrollable_->SetColor(SK_ColorYELLOW, SK_ColorGREEN); - } else if (sender == scroll_to_) { - scroll_view_->contents()->ScrollRectToVisible( - gfx::Rect(20, 500, 1000, 500)); - } - scroll_view_->Layout(); -} - -} // namespace examples -} // namespace views
diff --git a/ui/views/examples/scroll_view_example.h b/ui/views/examples/scroll_view_example.h deleted file mode 100644 index b3fd3bf..0000000 --- a/ui/views/examples/scroll_view_example.h +++ /dev/null
@@ -1,55 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_EXAMPLES_SCROLL_VIEW_EXAMPLE_H_ -#define UI_VIEWS_EXAMPLES_SCROLL_VIEW_EXAMPLE_H_ - -#include <string> - -#include "base/macros.h" -#include "ui/views/controls/button/button.h" -#include "ui/views/controls/scroll_view.h" -#include "ui/views/examples/example_base.h" - -namespace views { - -class LabelButton; - -namespace examples { - -class VIEWS_EXAMPLES_EXPORT ScrollViewExample : public ExampleBase, - public ButtonListener { - public: - ScrollViewExample(); - virtual ~ScrollViewExample(); - - // ExampleBase: - virtual void CreateExampleView(View* container) override; - - private: - // ButtonListener: - virtual void ButtonPressed(Button* sender, const ui::Event& event) override; - - // Control buttons to change the size of scrollable and jump to - // predefined position. - LabelButton* wide_; - LabelButton* tall_; - LabelButton* big_square_; - LabelButton* small_square_; - LabelButton* scroll_to_; - - class ScrollableView; - // The content of the scroll view. - ScrollableView* scrollable_; - - // The scroll view to test. - ScrollView* scroll_view_; - - DISALLOW_COPY_AND_ASSIGN(ScrollViewExample); -}; - -} // namespace examples -} // namespace views - -#endif // UI_VIEWS_EXAMPLES_SCROLL_VIEW_EXAMPLE_H_
diff --git a/ui/views/examples/single_split_view_example.cc b/ui/views/examples/single_split_view_example.cc deleted file mode 100644 index 21dd88e..0000000 --- a/ui/views/examples/single_split_view_example.cc +++ /dev/null
@@ -1,91 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/examples/single_split_view_example.h" - -#include "ui/views/background.h" -#include "ui/views/controls/single_split_view.h" -#include "ui/views/layout/grid_layout.h" - -namespace views { -namespace examples { -namespace { - -// SingleSplitView's content, which draws gradient color on background. -class SplittedView : public View { - public: - SplittedView(); - virtual ~SplittedView(); - - void SetColor(SkColor from, SkColor to); - - private: - // View: - virtual gfx::Size GetPreferredSize() const override; - virtual gfx::Size GetMinimumSize() const override; - virtual void Layout() override; - - DISALLOW_COPY_AND_ASSIGN(SplittedView); -}; - -SplittedView::SplittedView() { - SetColor(SK_ColorRED, SK_ColorGREEN); -} - -SplittedView::~SplittedView() { -} - -void SplittedView::SetColor(SkColor from, SkColor to) { - set_background(Background::CreateVerticalGradientBackground(from, to)); -} - -gfx::Size SplittedView::GetPreferredSize() const { - return gfx::Size(width(), height()); -} - -gfx::Size SplittedView::GetMinimumSize() const { - return gfx::Size(10, 10); -} - -void SplittedView::Layout() { - SizeToPreferredSize(); -} - -} // namespace - -SingleSplitViewExample::SingleSplitViewExample() - : ExampleBase("Single Split View") { -} - -SingleSplitViewExample::~SingleSplitViewExample() { -} - -void SingleSplitViewExample::CreateExampleView(View* container) { - SplittedView* splitted_view_1 = new SplittedView; - SplittedView* splitted_view_2 = new SplittedView; - - splitted_view_1->SetColor(SK_ColorYELLOW, SK_ColorCYAN); - - single_split_view_ = new SingleSplitView( - splitted_view_1, splitted_view_2, - SingleSplitView::HORIZONTAL_SPLIT, - this); - - GridLayout* layout = new GridLayout(container); - container->SetLayoutManager(layout); - - ColumnSet* column_set = layout->AddColumnSet(0); - column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1, - GridLayout::USE_PREF, 0, 0); - layout->StartRow(1, 0); - layout->AddView(single_split_view_); -} - -bool SingleSplitViewExample::SplitHandleMoved(SingleSplitView* sender) { - PrintStatus("Splitter moved"); - return true; -} - -} // namespace examples -} // namespace views
diff --git a/ui/views/examples/single_split_view_example.h b/ui/views/examples/single_split_view_example.h deleted file mode 100644 index b53c5c3..0000000 --- a/ui/views/examples/single_split_view_example.h +++ /dev/null
@@ -1,37 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_EXAMPLES_SINGLE_SPLIT_VIEW_EXAMPLE_H_ -#define UI_VIEWS_EXAMPLES_SINGLE_SPLIT_VIEW_EXAMPLE_H_ - -#include "base/macros.h" -#include "ui/views/controls/single_split_view_listener.h" -#include "ui/views/examples/example_base.h" - -namespace views { -namespace examples { - -class VIEWS_EXAMPLES_EXPORT SingleSplitViewExample - : public ExampleBase, - public SingleSplitViewListener { - public: - SingleSplitViewExample(); - virtual ~SingleSplitViewExample(); - - // ExampleBase: - virtual void CreateExampleView(View* container) override; - - private: - // SingleSplitViewListener: - virtual bool SplitHandleMoved(SingleSplitView* sender) override; - - SingleSplitView* single_split_view_; - - DISALLOW_COPY_AND_ASSIGN(SingleSplitViewExample); -}; - -} // namespace examples -} // namespace views - -#endif // UI_VIEWS_EXAMPLES_SINGLE_SPLIT_VIEW_EXAMPLE_H_
diff --git a/ui/views/examples/slider_example.cc b/ui/views/examples/slider_example.cc deleted file mode 100644 index 89f7856..0000000 --- a/ui/views/examples/slider_example.cc +++ /dev/null
@@ -1,45 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/examples/slider_example.h" - -#include "base/strings/stringprintf.h" -#include "base/strings/utf_string_conversions.h" -#include "ui/views/controls/label.h" -#include "ui/views/layout/box_layout.h" -#include "ui/views/view.h" - -namespace views { -namespace examples { - -SliderExample::SliderExample() - : ExampleBase("Slider"), - slider_(NULL), - label_(NULL) { -} - -SliderExample::~SliderExample() { -} - -void SliderExample::CreateExampleView(View* container) { - label_ = new Label(); - slider_ = new Slider(this, Slider::HORIZONTAL); - - slider_->SetValue(0.5); - - container->SetLayoutManager(new BoxLayout(BoxLayout::kHorizontal, 3, 3, 3)); - container->AddChildView(slider_); - container->AddChildView(label_); -} - -void SliderExample::SliderValueChanged(Slider* sender, - float value, - float old_value, - SliderChangeReason reason) { - label_->SetText(base::ASCIIToUTF16(base::StringPrintf("%.3lf", value))); -} - -} // namespace examples -} // namespace views -
diff --git a/ui/views/examples/slider_example.h b/ui/views/examples/slider_example.h deleted file mode 100644 index b27099b..0000000 --- a/ui/views/examples/slider_example.h +++ /dev/null
@@ -1,42 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_EXAMPLES_SLIDER_EXAMPLE_H_ -#define UI_VIEWS_EXAMPLES_SLIDER_EXAMPLE_H_ - -#include "base/macros.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(); - virtual ~SliderExample(); - - // ExampleBase: - virtual void CreateExampleView(View* container) override; - - private: - // SliderListener: - virtual void SliderValueChanged(Slider* sender, - float value, - float old_value, - SliderChangeReason reason) override; - - Slider* slider_; - Label* label_; - - DISALLOW_COPY_AND_ASSIGN(SliderExample); -}; - -} // namespace examples -} // namespace views - -#endif // UI_VIEWS_EXAMPLES_SLIDER_EXAMPLE_H_
diff --git a/ui/views/examples/tabbed_pane_example.cc b/ui/views/examples/tabbed_pane_example.cc deleted file mode 100644 index 087c77b..0000000 --- a/ui/views/examples/tabbed_pane_example.cc +++ /dev/null
@@ -1,88 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/examples/tabbed_pane_example.h" - -#include "base/strings/utf_string_conversions.h" -#include "ui/views/controls/button/label_button.h" -#include "ui/views/controls/tabbed_pane/tabbed_pane.h" -#include "ui/views/layout/grid_layout.h" - -using base::ASCIIToUTF16; - -namespace views { -namespace examples { - -TabbedPaneExample::TabbedPaneExample() : ExampleBase("Tabbed Pane") { -} - -TabbedPaneExample::~TabbedPaneExample() { -} - -void TabbedPaneExample::CreateExampleView(View* container) { - tabbed_pane_ = new TabbedPane(); - tabbed_pane_->set_listener(this); - add_ = new LabelButton(this, ASCIIToUTF16("Add")); - add_at_ = new LabelButton(this, ASCIIToUTF16("Add At 1")); - select_at_ = new LabelButton(this, ASCIIToUTF16("Select At 1")); - - GridLayout* layout = new GridLayout(container); - container->SetLayoutManager(layout); - - const int tabbed_pane_column = 0; - ColumnSet* column_set = layout->AddColumnSet(tabbed_pane_column); - column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, - 1.0f, GridLayout::USE_PREF, 0, 0); - layout->StartRow(1 /* expand */, tabbed_pane_column); - layout->AddView(tabbed_pane_); - - // Create a few tabs with a button first. - AddButton("Tab 1"); - AddButton("Tab 2"); - - // Add control buttons horizontally. - const int button_column = 1; - column_set = layout->AddColumnSet(button_column); - for (int i = 0; i < 3; i++) { - column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, - 1.0f, GridLayout::USE_PREF, 0, 0); - } - - layout->StartRow(0 /* no expand */, button_column); - layout->AddView(add_); - layout->AddView(add_at_); - layout->AddView(select_at_); -} - -void TabbedPaneExample::ButtonPressed(Button* sender, const ui::Event& event) { - if (sender == add_) { - AddButton("Added"); - } else if (sender == add_at_) { - const base::string16 label = ASCIIToUTF16("Added at 1"); - tabbed_pane_->AddTabAtIndex(1, label, new LabelButton(NULL, label)); - } else if (sender == select_at_) { - if (tabbed_pane_->GetTabCount() > 1) - tabbed_pane_->SelectTabAt(1); - } - PrintStatus(); -} - -void TabbedPaneExample::TabSelectedAt(int index) { - // Just print the status when selection changes. - PrintStatus(); -} - -void TabbedPaneExample::PrintStatus() { - ExampleBase::PrintStatus("Tab Count:%d, Selected Tab:%d", - tabbed_pane_->GetTabCount(), - tabbed_pane_->selected_tab_index()); -} - -void TabbedPaneExample::AddButton(const std::string& label) { - LabelButton* button = new LabelButton(NULL, ASCIIToUTF16(label)); - tabbed_pane_->AddTab(ASCIIToUTF16(label), button); -} - -} // namespace examples -} // namespace views
diff --git a/ui/views/examples/tabbed_pane_example.h b/ui/views/examples/tabbed_pane_example.h deleted file mode 100644 index a211a75..0000000 --- a/ui/views/examples/tabbed_pane_example.h +++ /dev/null
@@ -1,57 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_EXAMPLES_TABBED_PANE_EXAMPLE_H_ -#define UI_VIEWS_EXAMPLES_TABBED_PANE_EXAMPLE_H_ - -#include <string> - -#include "base/macros.h" -#include "ui/views/controls/button/button.h" -#include "ui/views/controls/tabbed_pane/tabbed_pane_listener.h" -#include "ui/views/examples/example_base.h" - -namespace views { -class TabbedPane; - -namespace examples { - -// A TabbedPane example tests adding and selecting tabs. -class VIEWS_EXAMPLES_EXPORT TabbedPaneExample : public ExampleBase, - public ButtonListener, - public TabbedPaneListener { - public: - TabbedPaneExample(); - virtual ~TabbedPaneExample(); - - // ExampleBase: - virtual void CreateExampleView(View* container) override; - - private: - // ButtonListener: - virtual void ButtonPressed(Button* sender, const ui::Event& event) override; - - // TabbedPaneListener: - virtual void TabSelectedAt(int index) override; - - // Print the status of the tab in the status area. - void PrintStatus(); - - void AddButton(const std::string& label); - - // The tabbed pane to be tested. - TabbedPane* tabbed_pane_; - - // Control buttons to add and select tabs. - Button* add_; - Button* add_at_; - Button* select_at_; - - DISALLOW_COPY_AND_ASSIGN(TabbedPaneExample); -}; - -} // namespace examples -} // namespace views - -#endif // UI_VIEWS_EXAMPLES_TABBED_PANE_EXAMPLE_H_
diff --git a/ui/views/examples/table_example.cc b/ui/views/examples/table_example.cc deleted file mode 100644 index abdfebb..0000000 --- a/ui/views/examples/table_example.cc +++ /dev/null
@@ -1,180 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/examples/table_example.h" - -#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/gfx/image/image_skia.h" -#include "ui/views/controls/button/checkbox.h" -#include "ui/views/layout/grid_layout.h" - -using base::ASCIIToUTF16; - -namespace views { -namespace examples { - -namespace { - -ui::TableColumn TestTableColumn(int id, const std::string& title) { - ui::TableColumn column; - column.id = id; - column.title = ASCIIToUTF16(title.c_str()); - column.sortable = true; - return column; -} - -} // namespace - -TableExample::TableExample() : ExampleBase("Table") , table_(NULL) { -} - -TableExample::~TableExample() { - // Delete the view before the model. - delete table_; - table_ = NULL; -} - -void TableExample::CreateExampleView(View* container) { - column1_visible_checkbox_ = new Checkbox( - ASCIIToUTF16("Fruit column visible")); - column1_visible_checkbox_->SetChecked(true); - column1_visible_checkbox_->set_listener(this); - column2_visible_checkbox_ = new Checkbox( - ASCIIToUTF16("Color column visible")); - column2_visible_checkbox_->SetChecked(true); - column2_visible_checkbox_->set_listener(this); - column3_visible_checkbox_ = new Checkbox( - ASCIIToUTF16("Origin column visible")); - column3_visible_checkbox_->SetChecked(true); - column3_visible_checkbox_->set_listener(this); - column4_visible_checkbox_ = new Checkbox( - ASCIIToUTF16("Price column visible")); - column4_visible_checkbox_->SetChecked(true); - column4_visible_checkbox_->set_listener(this); - - GridLayout* layout = new GridLayout(container); - container->SetLayoutManager(layout); - - std::vector<ui::TableColumn> columns; - columns.push_back(TestTableColumn(0, "Fruit")); - columns[0].percent = 1; - columns.push_back(TestTableColumn(1, "Color")); - columns.push_back(TestTableColumn(2, "Origin")); - columns.push_back(TestTableColumn(3, "Price")); - columns.back().alignment = ui::TableColumn::RIGHT; - table_ = new TableView(this, columns, ICON_AND_TEXT, true); - table_->SetGrouper(this); - table_->SetObserver(this); - icon1_.allocN32Pixels(16, 16); - SkCanvas canvas1(icon1_); - canvas1.drawColor(SK_ColorRED); - - icon2_.allocN32Pixels(16, 16); - SkCanvas canvas2(icon2_); - canvas2.drawColor(SK_ColorBLUE); - - ColumnSet* column_set = layout->AddColumnSet(0); - column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, 1, - GridLayout::USE_PREF, 0, 0); - layout->StartRow(1 /* expand */, 0); - layout->AddView(table_->CreateParentIfNecessary()); - - column_set = layout->AddColumnSet(1); - column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, - 0.5f, GridLayout::USE_PREF, 0, 0); - column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, - 0.5f, GridLayout::USE_PREF, 0, 0); - column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, - 0.5f, GridLayout::USE_PREF, 0, 0); - column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, - 0.5f, GridLayout::USE_PREF, 0, 0); - - layout->StartRow(0 /* no expand */, 1); - - layout->AddView(column1_visible_checkbox_); - layout->AddView(column2_visible_checkbox_); - layout->AddView(column3_visible_checkbox_); - layout->AddView(column4_visible_checkbox_); -} - -int TableExample::RowCount() { - return 10; -} - -base::string16 TableExample::GetText(int row, int column_id) { - if (row == -1) - return base::string16(); - - const char* const cells[5][4] = { - { "Orange", "Orange", "South america", "$5" }, - { "Apple", "Green", "Canada", "$3" }, - { "Blue berries", "Blue", "Mexico", "$10.3" }, - { "Strawberries", "Red", "California", "$7" }, - { "Cantaloupe", "Orange", "South america", "$5" }, - }; - return ASCIIToUTF16(cells[row % 5][column_id]); -} - -gfx::ImageSkia TableExample::GetIcon(int row) { - SkBitmap row_icon = row % 2 ? icon1_ : icon2_; - return gfx::ImageSkia::CreateFrom1xBitmap(row_icon); -} - -void TableExample::SetObserver(ui::TableModelObserver* observer) {} - -void TableExample::GetGroupRange(int 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", - base::UTF16ToASCII(GetText(table_->selection_model().active(), - 0)).c_str()); -} - -void TableExample::OnDoubleClick() { - PrintStatus("Double Click: %s", - base::UTF16ToASCII(GetText(table_->selection_model().active(), - 0)).c_str()); -} - -void TableExample::OnMiddleClick() {} - -void TableExample::OnKeyDown(ui::KeyboardCode virtual_keycode) {} - -void TableExample::ButtonPressed(Button* sender, const ui::Event& event) { - int index = 0; - bool show = true; - if (sender == column1_visible_checkbox_) { - index = 0; - show = column1_visible_checkbox_->checked(); - } else if (sender == column2_visible_checkbox_) { - index = 1; - show = column2_visible_checkbox_->checked(); - } else if (sender == column3_visible_checkbox_) { - index = 2; - show = column3_visible_checkbox_->checked(); - } else if (sender == column4_visible_checkbox_) { - index = 3; - show = column4_visible_checkbox_->checked(); - } - table_->SetColumnVisibility(index, show); -} - -} // namespace examples -} // namespace views
diff --git a/ui/views/examples/table_example.h b/ui/views/examples/table_example.h deleted file mode 100644 index 5f51316..0000000 --- a/ui/views/examples/table_example.h +++ /dev/null
@@ -1,77 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_EXAMPLES_TABLE_EXAMPLE_H_ -#define UI_VIEWS_EXAMPLES_TABLE_EXAMPLE_H_ - -#include <string> - -#include "base/macros.h" -#include "third_party/skia/include/core/SkBitmap.h" -#include "ui/base/models/table_model.h" -#include "ui/views/controls/button/button.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" - -namespace gfx { -class ImageSkia; -} - -namespace views { -class Checkbox; -class TableView; - -namespace examples { - -class VIEWS_EXAMPLES_EXPORT TableExample : public ExampleBase, - public ui::TableModel, - public TableGrouper, - public TableViewObserver, - public ButtonListener { - public: - TableExample(); - virtual ~TableExample(); - - // ExampleBase: - virtual void CreateExampleView(View* container) override; - - // ui::TableModel: - virtual int RowCount() override; - virtual base::string16 GetText(int row, int column_id) override; - virtual gfx::ImageSkia GetIcon(int row) override; - virtual void SetObserver(ui::TableModelObserver* observer) override; - - // TableGrouper: - virtual void GetGroupRange(int model_index, GroupRange* range) override; - - // TableViewObserver: - virtual void OnSelectionChanged() override; - virtual void OnDoubleClick() override; - virtual void OnMiddleClick() override; - virtual void OnKeyDown(ui::KeyboardCode virtual_keycode) override; - - // ButtonListener: - virtual void ButtonPressed(Button* sender, const ui::Event& event) override; - - private: - // The table to be tested. - TableView* table_; - - Checkbox* column1_visible_checkbox_; - Checkbox* column2_visible_checkbox_; - Checkbox* column3_visible_checkbox_; - Checkbox* column4_visible_checkbox_; - - SkBitmap icon1_; - SkBitmap icon2_; - - DISALLOW_COPY_AND_ASSIGN(TableExample); -}; - -} // namespace examples -} // namespace views - -#endif // UI_VIEWS_EXAMPLES_TABLE_EXAMPLE_H_
diff --git a/ui/views/examples/text_example.cc b/ui/views/examples/text_example.cc deleted file mode 100644 index 4dcf113..0000000 --- a/ui/views/examples/text_example.cc +++ /dev/null
@@ -1,265 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/examples/text_example.h" - -#include "base/strings/utf_string_conversions.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/layout/grid_layout.h" -#include "ui/views/view.h" - -namespace views { -namespace examples { - -namespace { - -// Number of columns in the view layout. -const int kNumColumns = 10; - -const char kShortText[] = "The quick brown fox jumps over the lazy dog."; -const char kLongText[] = - "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod " - "tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim " - "veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea " - "commodo consequat.\nDuis aute irure dolor in reprehenderit in voluptate " - "velit esse cillum dolore eu fugiat nulla pariatur.\n\nExcepteur sint " - "occaecat cupidatat non proident, sunt in culpa qui officia deserunt " - "mollit anim id est laborum."; -const char kAmpersandText[] = - "The quick && &brown fo&x jumps over the lazy dog."; -const wchar_t kRightToLeftText[] = - L"\x5e9\x5dc\x5d5\x5dd \x5d4\x5e2\x5d5\x5dc\x5dd! " - L"\x5e9\x5dc\x5d5\x5dd \x5d4\x5e2\x5d5\x5dc\x5dd! " - L"\x5e9\x5dc\x5d5\x5dd \x5d4\x5e2\x5d5\x5dc\x5dd! " - L"\x5e9\x5dc\x5d5\x5dd \x5d4\x5e2\x5d5\x5dc\x5dd! " - L"\x5e9\x5dc\x5d5\x5dd \x5d4\x5e2\x5d5\x5dc\x5dd! " - L"\x5e9\x5dc\x5d5\x5dd \x5d4\x5e2\x5d5\x5dc\x5dd! " - L"\x5e9\x5dc\x5d5\x5dd \x5d4\x5e2\x5d5\x5dc\x5dd! " - L"\x5e9\x5dc\x5d5\x5dd \x5d4\x5e2\x5d5\x5dc\x5dd!"; - -const char* kTextExamples[] = { "Short", "Long", "Ampersands", "RTL Hebrew", }; -const char* kElideBehaviors[] = { "Elide", "No Elide", "Fade", }; -const char* kPrefixOptions[] = { "Default", "Show", "Hide", }; -const char* kHorizontalAligments[] = { "Default", "Left", "Center", "Right", }; - -// Toggles bit |flag| on |flags| based on state of |checkbox|. -void SetFlagFromCheckbox(Checkbox* checkbox, int* flags, int flag) { - if (checkbox->checked()) - *flags |= flag; - else - *flags &= ~flag; -} - -} // namespace - -// TextExample's content view, which draws stylized string. -class TextExample::TextExampleView : public View { - public: - TextExampleView() - : text_(base::ASCIIToUTF16(kShortText)), - flags_(0), - halo_(false), - elide_(gfx::NO_ELIDE) { - } - - virtual void OnPaint(gfx::Canvas* canvas) override { - View::OnPaint(canvas); - const gfx::Rect bounds = GetContentsBounds(); - const SkColor color = SK_ColorDKGRAY; - if (elide_ == gfx::FADE_TAIL) { - canvas->DrawFadedString(text_, font_list_, color, bounds, flags_); - } else if (halo_) { - canvas->DrawStringRectWithHalo(text_, font_list_, color, SK_ColorYELLOW, - bounds, flags_); - } else { - canvas->DrawStringRectWithFlags(text_, font_list_, color, bounds, flags_); - } - } - - int flags() const { return flags_; } - void set_flags(int flags) { flags_ = flags; } - void set_text(const base::string16& text) { text_ = text; } - void set_halo(bool halo) { halo_ = halo; } - void set_elide(gfx::ElideBehavior elide) { elide_ = elide; } - - int GetStyle() const { return font_list_.GetFontStyle(); } - void SetStyle(int style) { font_list_ = font_list_.DeriveWithStyle(style); } - - private: - // The font used for drawing the text. - gfx::FontList font_list_; - - // The text to draw. - base::string16 text_; - - // Text flags for passing to |DrawStringRect()|. - int flags_; - - // A flag to draw a halo around the text. - bool halo_; - - // The eliding, fading, or truncating behavior. - gfx::ElideBehavior elide_; - - DISALLOW_COPY_AND_ASSIGN(TextExampleView); -}; - -TextExample::TextExample() : ExampleBase("Text Styles") {} - -TextExample::~TextExample() { - // Remove the views first as some reference combobox models. - container()->RemoveAllChildViews(true); -} - -Checkbox* TextExample::AddCheckbox(GridLayout* layout, const char* name) { - Checkbox* checkbox = new Checkbox(base::ASCIIToUTF16(name)); - checkbox->set_listener(this); - layout->AddView(checkbox); - return checkbox; -} - -Combobox* TextExample::AddCombobox(GridLayout* layout, - const char* name, - const char** strings, - int count) { - layout->StartRow(0, 0); - layout->AddView(new Label(base::ASCIIToUTF16(name))); - ExampleComboboxModel* model = new ExampleComboboxModel(strings, count); - example_combobox_model_.push_back(model); - Combobox* combobox = new Combobox(model); - combobox->SetSelectedIndex(0); - combobox->set_listener(this); - layout->AddView(combobox, kNumColumns - 1, 1); - return combobox; -} - -void TextExample::CreateExampleView(View* container) { - text_view_ = new TextExampleView; - text_view_->SetBorder(Border::CreateSolidBorder(1, SK_ColorGRAY)); - GridLayout* layout = new GridLayout(container); - container->SetLayoutManager(layout); - layout->AddPaddingRow(0, 8); - - ColumnSet* column_set = layout->AddColumnSet(0); - column_set->AddPaddingColumn(0, 8); - column_set->AddColumn(GridLayout::LEADING, GridLayout::FILL, - 0.1f, GridLayout::USE_PREF, 0, 0); - for (int i = 0; i < kNumColumns - 1; i++) - column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, - 0.1f, GridLayout::USE_PREF, 0, 0); - column_set->AddPaddingColumn(0, 8); - - h_align_cb_ = AddCombobox(layout, "H-Align", kHorizontalAligments, - arraysize(kHorizontalAligments)); - eliding_cb_ = AddCombobox(layout, "Eliding", kElideBehaviors, - arraysize(kElideBehaviors)); - prefix_cb_ = AddCombobox(layout, "Prefix", kPrefixOptions, - arraysize(kPrefixOptions)); - text_cb_ = AddCombobox(layout, "Example Text", kTextExamples, - arraysize(kTextExamples)); - - layout->StartRow(0, 0); - multiline_checkbox_ = AddCheckbox(layout, "Multiline"); - break_checkbox_ = AddCheckbox(layout, "Character Break"); - halo_checkbox_ = AddCheckbox(layout, "Halo"); - bold_checkbox_ = AddCheckbox(layout, "Bold"); - italic_checkbox_ = AddCheckbox(layout, "Italic"); - underline_checkbox_ = AddCheckbox(layout, "Underline"); - - layout->AddPaddingRow(0, 20); - column_set = layout->AddColumnSet(1); - column_set->AddPaddingColumn(0, 16); - column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, - 1, GridLayout::USE_PREF, 0, 0); - column_set->AddPaddingColumn(0, 16); - layout->StartRow(1, 1); - layout->AddView(text_view_); - layout->AddPaddingRow(0, 8); -} - -void TextExample::ButtonPressed(Button* button, const ui::Event& event) { - int flags = text_view_->flags(); - int style = text_view_->GetStyle(); - SetFlagFromCheckbox(multiline_checkbox_, &flags, gfx::Canvas::MULTI_LINE); - SetFlagFromCheckbox(break_checkbox_, &flags, gfx::Canvas::CHARACTER_BREAK); - SetFlagFromCheckbox(bold_checkbox_, &style, gfx::Font::BOLD); - SetFlagFromCheckbox(italic_checkbox_, &style, gfx::Font::ITALIC); - SetFlagFromCheckbox(underline_checkbox_, &style, gfx::Font::UNDERLINE); - text_view_->set_halo(halo_checkbox_->checked()); - text_view_->set_flags(flags); - text_view_->SetStyle(style); - text_view_->SchedulePaint(); -} - -void TextExample::OnPerformAction(Combobox* combobox) { - int flags = text_view_->flags(); - if (combobox == h_align_cb_) { - flags &= ~(gfx::Canvas::TEXT_ALIGN_LEFT | - gfx::Canvas::TEXT_ALIGN_CENTER | - gfx::Canvas::TEXT_ALIGN_RIGHT); - switch (combobox->selected_index()) { - 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; - } - } else if (combobox == text_cb_) { - switch (combobox->selected_index()) { - case 0: - text_view_->set_text(base::ASCIIToUTF16(kShortText)); - break; - case 1: - text_view_->set_text(base::ASCIIToUTF16(kLongText)); - break; - case 2: - text_view_->set_text(base::ASCIIToUTF16(kAmpersandText)); - break; - case 3: - text_view_->set_text(base::WideToUTF16(kRightToLeftText)); - break; - } - } else if (combobox == eliding_cb_) { - switch (combobox->selected_index()) { - case 0: - text_view_->set_elide(gfx::ELIDE_TAIL); - break; - case 1: - text_view_->set_elide(gfx::NO_ELIDE); - break; - case 2: - text_view_->set_elide(gfx::FADE_TAIL); - break; - } - } else if (combobox == prefix_cb_) { - flags &= ~(gfx::Canvas::SHOW_PREFIX | gfx::Canvas::HIDE_PREFIX); - switch (combobox->selected_index()) { - case 0: - break; - case 1: - flags |= gfx::Canvas::SHOW_PREFIX; - break; - case 2: - flags |= gfx::Canvas::HIDE_PREFIX; - break; - } - } - text_view_->set_flags(flags); - text_view_->SchedulePaint(); -} - -} // namespace examples -} // namespace views
diff --git a/ui/views/examples/text_example.h b/ui/views/examples/text_example.h deleted file mode 100644 index dd4bffc..0000000 --- a/ui/views/examples/text_example.h +++ /dev/null
@@ -1,92 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_EXAMPLES_TEXT_EXAMPLE_H_ -#define UI_VIEWS_EXAMPLES_TEXT_EXAMPLE_H_ - -#include "base/macros.h" -#include "base/memory/scoped_vector.h" -#include "ui/views/controls/button/button.h" -#include "ui/views/controls/combobox/combobox_listener.h" -#include "ui/views/examples/example_base.h" - -namespace views { -class Checkbox; -class GridLayout; - -namespace examples { - -class ExampleComboboxModel; - -class VIEWS_EXAMPLES_EXPORT TextExample : public ExampleBase, - public ButtonListener, - public ComboboxListener { - public: - TextExample(); - virtual ~TextExample(); - - // ExampleBase: - virtual void CreateExampleView(View* container) override; - - private: - // Creates and adds a check box to the layout. - Checkbox* AddCheckbox(GridLayout* layout, const char* name); - - // Creates and adds a combobox to the layout. - Combobox* AddCombobox(GridLayout* layout, - const char* name, - const char** strings, - int count); - - // ButtonListener: - virtual void ButtonPressed(Button* button, const ui::Event& event) override; - - // ComboboxListener: - virtual void OnPerformAction(Combobox* combobox) override; - - class TextExampleView; - // The content of the scroll view. - TextExampleView* text_view_; - - // Combo box for horizontal text alignment. - Combobox* h_align_cb_; - - // Combo box for text eliding style. - Combobox* eliding_cb_; - - // Combo box for ampersand prefix show / hide behavior. - Combobox* prefix_cb_; - - // Combo box to choose one of the sample texts. - Combobox* text_cb_; - - // Check box to enable/disable multiline text drawing. - Checkbox* multiline_checkbox_; - - // Check box to enable/disable character break behavior. - Checkbox* break_checkbox_; - - // Check box to enable/disable text halo. - Checkbox* halo_checkbox_; - - // Check box to enable/disable bold style. - Checkbox* bold_checkbox_; - - // Check box to enable/disable italic style. - Checkbox* italic_checkbox_; - - // Check box to enable/disable underline style. - Checkbox* underline_checkbox_; - - // We create a model for each of the combobox, so we need to keep them - // around until destruction time. - ScopedVector<ExampleComboboxModel> example_combobox_model_; - - DISALLOW_COPY_AND_ASSIGN(TextExample); -}; - -} // namespace examples -} // namespace views - -#endif // UI_VIEWS_EXAMPLES_TEXT_EXAMPLE_H_
diff --git a/ui/views/examples/textfield_example.cc b/ui/views/examples/textfield_example.cc deleted file mode 100644 index 7dae434..0000000 --- a/ui/views/examples/textfield_example.cc +++ /dev/null
@@ -1,144 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/examples/textfield_example.h" - -#include "base/strings/utf_string_conversions.h" -#include "ui/events/event.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/layout/grid_layout.h" -#include "ui/views/view.h" - -using base::ASCIIToUTF16; -using base::UTF16ToUTF8; - -namespace views { -namespace examples { - -TextfieldExample::TextfieldExample() - : ExampleBase("Textfield"), - name_(NULL), - password_(NULL), - read_only_(NULL), - show_password_(NULL), - clear_all_(NULL), - append_(NULL), - set_(NULL), - set_style_(NULL) { -} - -TextfieldExample::~TextfieldExample() { -} - -void TextfieldExample::CreateExampleView(View* container) { - name_ = new Textfield(); - password_ = new Textfield(); - password_->SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD); - password_->set_placeholder_text(ASCIIToUTF16("password")); - read_only_ = new Textfield(); - read_only_->SetReadOnly(true); - read_only_->SetText(ASCIIToUTF16("read only")); - show_password_ = new LabelButton(this, ASCIIToUTF16("Show password")); - clear_all_ = new LabelButton(this, ASCIIToUTF16("Clear All")); - append_ = new LabelButton(this, ASCIIToUTF16("Append")); - set_ = new LabelButton(this, ASCIIToUTF16("Set")); - set_style_ = new LabelButton(this, ASCIIToUTF16("Set Styles")); - name_->set_controller(this); - password_->set_controller(this); - - GridLayout* layout = new GridLayout(container); - container->SetLayoutManager(layout); - - ColumnSet* column_set = layout->AddColumnSet(0); - column_set->AddColumn(GridLayout::LEADING, GridLayout::FILL, - 0.2f, GridLayout::USE_PREF, 0, 0); - column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, - 0.8f, GridLayout::USE_PREF, 0, 0); - layout->StartRow(0, 0); - layout->AddView(new Label(ASCIIToUTF16("Name:"))); - layout->AddView(name_); - layout->StartRow(0, 0); - layout->AddView(new Label(ASCIIToUTF16("Password:"))); - layout->AddView(password_); - layout->StartRow(0, 0); - layout->AddView(new Label(ASCIIToUTF16("Read Only:"))); - layout->AddView(read_only_); - layout->StartRow(0, 0); - layout->AddView(show_password_); - layout->StartRow(0, 0); - layout->AddView(clear_all_); - layout->StartRow(0, 0); - layout->AddView(append_); - layout->StartRow(0, 0); - layout->AddView(set_); - layout->StartRow(0, 0); - layout->AddView(set_style_); -} - -void TextfieldExample::ContentsChanged(Textfield* sender, - const base::string16& new_contents) { - if (sender == name_) { - PrintStatus("Name [%s]", UTF16ToUTF8(new_contents).c_str()); - } else if (sender == password_) { - PrintStatus("Password [%s]", UTF16ToUTF8(new_contents).c_str()); - } else if (sender == read_only_) { - PrintStatus("Read Only [%s]", UTF16ToUTF8(new_contents).c_str()); - } -} - -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::ButtonPressed(Button* sender, const ui::Event& event) { - if (sender == show_password_) { - PrintStatus("Password [%s]", UTF16ToUTF8(password_->text()).c_str()); - } else if (sender == clear_all_) { - base::string16 empty; - name_->SetText(empty); - password_->SetText(empty); - read_only_->SetText(empty); - } else if (sender == append_) { - name_->AppendText(ASCIIToUTF16("[append]")); - password_->AppendText(ASCIIToUTF16("[append]")); - read_only_->AppendText(ASCIIToUTF16("[append]")); - } else if (sender == set_) { - name_->SetText(ASCIIToUTF16("[set]")); - password_->SetText(ASCIIToUTF16("[set]")); - read_only_->SetText(ASCIIToUTF16("[set]")); - } else if (sender == set_style_) { - if (!name_->text().empty()) { - name_->SetColor(SK_ColorGREEN); - name_->SetStyle(gfx::BOLD, true); - - if (name_->text().length() >= 5) { - size_t fifth = name_->text().length() / 5; - const gfx::Range big_range(1 * fifth, 4 * fifth); - name_->ApplyStyle(gfx::BOLD, false, big_range); - name_->ApplyStyle(gfx::UNDERLINE, true, big_range); - name_->ApplyColor(SK_ColorBLUE, big_range); - - const gfx::Range small_range(2 * fifth, 3 * fifth); - name_->ApplyStyle(gfx::ITALIC, true, small_range); - name_->ApplyStyle(gfx::UNDERLINE, false, small_range); - name_->ApplyStyle(gfx::DIAGONAL_STRIKE, true, small_range); - name_->ApplyColor(SK_ColorRED, small_range); - } - } - } -} - -} // namespace examples -} // namespace views
diff --git a/ui/views/examples/textfield_example.h b/ui/views/examples/textfield_example.h deleted file mode 100644 index 31aaaa9..0000000 --- a/ui/views/examples/textfield_example.h +++ /dev/null
@@ -1,62 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_EXAMPLES_TEXTFIELD_EXAMPLE_H_ -#define UI_VIEWS_EXAMPLES_TEXTFIELD_EXAMPLE_H_ - -#include <string> - -#include "base/macros.h" -#include "ui/views/controls/button/button.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 ButtonListener { - public: - TextfieldExample(); - virtual ~TextfieldExample(); - - // ExampleBase: - virtual void CreateExampleView(View* container) override; - - private: - // TextfieldController: - virtual void ContentsChanged(Textfield* sender, - const base::string16& new_contents) override; - virtual bool HandleKeyEvent(Textfield* sender, - const ui::KeyEvent& key_event) override; - virtual bool HandleMouseEvent(Textfield* sender, - const ui::MouseEvent& mouse_event) override; - - // ButtonListener: - virtual void ButtonPressed(Button* sender, const ui::Event& event) override; - - // Textfields for name and password. - Textfield* name_; - Textfield* password_; - Textfield* read_only_; - - // Various buttons to control textfield. - LabelButton* show_password_; - LabelButton* clear_all_; - LabelButton* append_; - LabelButton* set_; - LabelButton* set_style_; - - DISALLOW_COPY_AND_ASSIGN(TextfieldExample); -}; - -} // namespace examples -} // namespace views - -#endif // UI_VIEWS_EXAMPLES_TEXTFIELD_EXAMPLE_H_
diff --git a/ui/views/examples/throbber_example.cc b/ui/views/examples/throbber_example.cc deleted file mode 100644 index 51bbf3d..0000000 --- a/ui/views/examples/throbber_example.cc +++ /dev/null
@@ -1,61 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/examples/throbber_example.h" - -#include "ui/views/controls/throbber.h" -#include "ui/views/layout/fill_layout.h" -#include "ui/views/view.h" - -namespace views { -namespace examples { - -namespace { - -// Time in ms per throbber frame. -const int kThrobberFrameMs = 60; - -class ThrobberView : public View { - public: - ThrobberView() { - throbber_ = new Throbber(kThrobberFrameMs, false); - AddChildView(throbber_); - throbber_->SetVisible(true); - throbber_->Start(); - } - - virtual gfx::Size GetPreferredSize() const override { - return gfx::Size(width(), height()); - } - - virtual void Layout() override { - View* child = child_at(0); - gfx::Size ps = child->GetPreferredSize(); - child->SetBounds((width() - ps.width()) / 2, - (height() - ps.height()) / 2, - ps.width(), ps.height()); - SizeToPreferredSize(); - } - - private: - Throbber* throbber_; - - DISALLOW_COPY_AND_ASSIGN(ThrobberView); -}; - -} // namespace - -ThrobberExample::ThrobberExample() : ExampleBase("Throbber") { -} - -ThrobberExample::~ThrobberExample() { -} - -void ThrobberExample::CreateExampleView(View* container) { - container->SetLayoutManager(new FillLayout()); - container->AddChildView(new ThrobberView()); -} - -} // namespace examples -} // namespace views
diff --git a/ui/views/examples/throbber_example.h b/ui/views/examples/throbber_example.h deleted file mode 100644 index dcac287..0000000 --- a/ui/views/examples/throbber_example.h +++ /dev/null
@@ -1,29 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_EXAMPLES_THROBBER_EXAMPLE_H_ -#define UI_VIEWS_EXAMPLES_THROBBER_EXAMPLE_H_ - -#include "base/macros.h" -#include "ui/views/examples/example_base.h" - -namespace views { -namespace examples { - -class VIEWS_EXAMPLES_EXPORT ThrobberExample : public ExampleBase { - public: - ThrobberExample(); - virtual ~ThrobberExample(); - - // ExampleBase: - virtual void CreateExampleView(View* container) override; - - private: - DISALLOW_COPY_AND_ASSIGN(ThrobberExample); -}; - -} // namespace examples -} // namespace views - -#endif // UI_VIEWS_EXAMPLES_THROBBER_EXAMPLE_H_
diff --git a/ui/views/examples/tree_view_example.cc b/ui/views/examples/tree_view_example.cc deleted file mode 100644 index 5da97f7..0000000 --- a/ui/views/examples/tree_view_example.cc +++ /dev/null
@@ -1,178 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/examples/tree_view_example.h" - -#include "base/strings/utf_string_conversions.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/tree/tree_view.h" -#include "ui/views/layout/grid_layout.h" - -using base::ASCIIToUTF16; - -namespace views { -namespace examples { - -TreeViewExample::TreeViewExample() - : ExampleBase("Tree View"), - tree_view_(NULL), - model_(new NodeType(ASCIIToUTF16("root"), 1)) { -} - -TreeViewExample::~TreeViewExample() { - // Delete the view before the model. - delete tree_view_; - tree_view_ = NULL; -} - -void TreeViewExample::CreateExampleView(View* container) { - // Add some sample data. - NodeType* colors_node = new NodeType(ASCIIToUTF16("colors"), 1); - model_.GetRoot()->Add(colors_node, 0); - colors_node->Add(new NodeType(ASCIIToUTF16("red"), 1), 0); - colors_node->Add(new NodeType(ASCIIToUTF16("green"), 1), 1); - colors_node->Add(new NodeType(ASCIIToUTF16("blue"), 1), 2); - - NodeType* sheep_node = new NodeType(ASCIIToUTF16("sheep"), 1); - model_.GetRoot()->Add(sheep_node, 0); - sheep_node->Add(new NodeType(ASCIIToUTF16("Sheep 1"), 1), 0); - sheep_node->Add(new NodeType(ASCIIToUTF16("Sheep 2"), 1), 1); - - tree_view_ = new TreeView(); - tree_view_->set_context_menu_controller(this); - tree_view_->SetRootShown(false); - tree_view_->SetModel(&model_); - tree_view_->SetController(this); - add_ = new LabelButton(this, ASCIIToUTF16("Add")); - add_->SetFocusable(true); - remove_ = new LabelButton(this, ASCIIToUTF16("Remove")); - remove_->SetFocusable(true); - change_title_ = new LabelButton(this, ASCIIToUTF16("Change Title")); - change_title_->SetFocusable(true); - - GridLayout* layout = new GridLayout(container); - container->SetLayoutManager(layout); - - const int tree_view_column = 0; - ColumnSet* column_set = layout->AddColumnSet(tree_view_column); - column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, - 1.0f, GridLayout::USE_PREF, 0, 0); - layout->StartRow(1 /* expand */, tree_view_column); - layout->AddView(tree_view_->CreateParentIfNecessary()); - - // Add control buttons horizontally. - const int button_column = 1; - column_set = layout->AddColumnSet(button_column); - for (int i = 0; i < 3; i++) { - column_set->AddColumn(GridLayout::FILL, GridLayout::FILL, - 1.0f, GridLayout::USE_PREF, 0, 0); - } - - layout->StartRow(0 /* no expand */, button_column); - layout->AddView(add_); - layout->AddView(remove_); - layout->AddView(change_title_); -} - -void TreeViewExample::AddNewNode() { - NodeType* selected_node = - static_cast<NodeType*>(tree_view_->GetSelectedNode()); - if (!selected_node) - selected_node = model_.GetRoot(); - NodeType* new_node = new NodeType(selected_node->GetTitle(), 1); - model_.Add(selected_node, new_node, selected_node->child_count()); - tree_view_->SetSelectedNode(new_node); -} - -bool TreeViewExample::IsCommandIdEnabled(int command_id) { - return command_id != ID_REMOVE || - tree_view_->GetSelectedNode() != model_.GetRoot(); -} - -void TreeViewExample::ButtonPressed(Button* sender, const ui::Event& event) { - NodeType* selected_node = - static_cast<NodeType*>(tree_view_->GetSelectedNode()); - if (sender == add_) { - AddNewNode(); - } else if (sender == remove_) { - DCHECK(selected_node); - DCHECK_NE(model_.GetRoot(), selected_node); - model_.Remove(selected_node->parent(), selected_node); - } else if (sender == change_title_) { - DCHECK(selected_node); - model_.SetTitle(selected_node, - selected_node->GetTitle() + ASCIIToUTF16("new")); - } -} - -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::ShowContextMenuForView(View* source, - const gfx::Point& point, - ui::MenuSourceType source_type) { - ui::SimpleMenuModel context_menu_model(this); - context_menu_model.AddItem(ID_EDIT, ASCIIToUTF16("Edit")); - context_menu_model.AddItem(ID_REMOVE, ASCIIToUTF16("Remove")); - context_menu_model.AddItem(ID_ADD, ASCIIToUTF16("Add")); - context_menu_runner_.reset(new MenuRunner(&context_menu_model, 0)); - if (context_menu_runner_->RunMenuAt(source->GetWidget(), - NULL, - gfx::Rect(point, gfx::Size()), - MENU_ANCHOR_TOPLEFT, - source_type) == - MenuRunner::MENU_DELETED) { - return; - } -} - -bool TreeViewExample::IsCommandIdChecked(int command_id) const { - return false; -} - -bool TreeViewExample::IsCommandIdEnabled(int command_id) const { - return const_cast<TreeViewExample*>(this)->IsCommandIdEnabled(command_id); -} - -bool TreeViewExample::GetAcceleratorForCommandId( - int command_id, - ui::Accelerator* accelerator) { - return false; -} - -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(); - } -} - -} // namespace examples -} // namespace views
diff --git a/ui/views/examples/tree_view_example.h b/ui/views/examples/tree_view_example.h deleted file mode 100644 index 4678b2a..0000000 --- a/ui/views/examples/tree_view_example.h +++ /dev/null
@@ -1,90 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_EXAMPLES_TREE_VIEW_EXAMPLE_H_ -#define UI_VIEWS_EXAMPLES_TREE_VIEW_EXAMPLE_H_ - -#include "base/macros.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/button/button.h" -#include "ui/views/controls/tree/tree_view_controller.h" -#include "ui/views/examples/example_base.h" - -namespace views { - -class MenuRunner; -class TreeView; - -namespace examples { - -class VIEWS_EXAMPLES_EXPORT TreeViewExample - : public ExampleBase, - public ButtonListener, - public TreeViewController, - public ContextMenuController, - public ui::SimpleMenuModel::Delegate { - public: - TreeViewExample(); - virtual ~TreeViewExample(); - - // ExampleBase: - virtual void CreateExampleView(View* container) override; - - private: - // IDs used by the context menu. - enum MenuIDs { - ID_EDIT, - ID_REMOVE, - ID_ADD - }; - - // Adds a new node. - void AddNewNode(); - - // Non-const version of IsCommandIdEnabled. - bool IsCommandIdEnabled(int command_id); - - // ButtonListener: - virtual void ButtonPressed(Button* sender, const ui::Event& event) override; - - // TreeViewController: - virtual void OnTreeViewSelectionChanged(TreeView* tree_view) override; - virtual bool CanEdit(TreeView* tree_view, ui::TreeModelNode* node) override; - - // ContextMenuController: - virtual void ShowContextMenuForView(View* source, - const gfx::Point& point, - ui::MenuSourceType source_type) override; - - // SimpleMenuModel::Delegate: - virtual bool IsCommandIdChecked(int command_id) const override; - virtual bool IsCommandIdEnabled(int command_id) const override; - virtual bool GetAcceleratorForCommandId( - int command_id, - ui::Accelerator* accelerator) override; - virtual void ExecuteCommand(int command_id, int event_flags) override; - - // The tree view to be tested. - TreeView* tree_view_; - - // Control buttons to modify the model. - Button* add_; - Button* remove_; - Button* change_title_; - - typedef ui::TreeNodeWithValue<int> NodeType; - - ui::TreeNodeModel<NodeType> model_; - - scoped_ptr<MenuRunner> context_menu_runner_; - - DISALLOW_COPY_AND_ASSIGN(TreeViewExample); -}; - -} // namespace examples -} // namespace views - -#endif // UI_VIEWS_EXAMPLES_TREE_VIEW_EXAMPLE_H_
diff --git a/ui/views/examples/views_examples.exe.manifest b/ui/views/examples/views_examples.exe.manifest deleted file mode 100644 index 79c35aa..0000000 --- a/ui/views/examples/views_examples.exe.manifest +++ /dev/null
@@ -1,20 +0,0 @@ -<?xml version="1.0" encoding="UTF-8" standalone="yes"?> -<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> - - <!--The compatibility section will be merged from build/win/compatibility.manifest --> - - <dependency> - <dependentAssembly> - <assemblyIdentity type="Win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="X86" publicKeyToken="6595b64144ccf1df" language="*"></assemblyIdentity> - </dependentAssembly> - </dependency> - - <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> - <security> - <requestedPrivileges> - <requestedExecutionLevel level="asInvoker" /> - </requestedPrivileges> - </security> - </trustInfo> - -</assembly> \ No newline at end of file
diff --git a/ui/views/examples/views_examples_export.h b/ui/views/examples/views_examples_export.h deleted file mode 100644 index 7ea226b..0000000 --- a/ui/views/examples/views_examples_export.h +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef 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_
diff --git a/ui/views/examples/views_examples_with_content_export.h b/ui/views/examples/views_examples_with_content_export.h deleted file mode 100644 index ede8b17..0000000 --- a/ui/views/examples/views_examples_with_content_export.h +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef 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_
diff --git a/ui/views/examples/webview_example.cc b/ui/views/examples/webview_example.cc deleted file mode 100644 index feae6b9..0000000 --- a/ui/views/examples/webview_example.cc +++ /dev/null
@@ -1,34 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/examples/webview_example.h" - -#include "content/public/browser/browser_context.h" -#include "content/public/browser/web_contents.h" -#include "ui/views/controls/webview/webview.h" -#include "ui/views/layout/fill_layout.h" - -namespace views { -namespace examples { - -WebViewExample::WebViewExample(content::BrowserContext* browser_context) - : ExampleBase("WebView"), - webview_(NULL), - browser_context_(browser_context) { -} - -WebViewExample::~WebViewExample() { -} - -void WebViewExample::CreateExampleView(View* container) { - webview_ = new WebView(browser_context_); - container->SetLayoutManager(new FillLayout); - container->AddChildView(webview_); - - webview_->LoadInitialURL(GURL("http://www.google.com/")); - webview_->web_contents()->Focus(); -} - -} // namespace examples -} // namespace views
diff --git a/ui/views/examples/webview_example.h b/ui/views/examples/webview_example.h deleted file mode 100644 index e55aced..0000000 --- a/ui/views/examples/webview_example.h +++ /dev/null
@@ -1,38 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_EXAMPLES_WEBVIEW_EXAMPLE_H_ -#define UI_VIEWS_EXAMPLES_WEBVIEW_EXAMPLE_H_ - -#include "base/macros.h" -#include "ui/views/examples/example_base.h" - -namespace content { -class BrowserContext; -} - -namespace views { -class WebView; - -namespace examples { - -class WebViewExample : public ExampleBase { - public: - explicit WebViewExample(content::BrowserContext* browser_context); - virtual ~WebViewExample(); - - // ExampleBase: - virtual void CreateExampleView(View* container) override; - - private: - WebView* webview_; - content::BrowserContext* browser_context_; - - DISALLOW_COPY_AND_ASSIGN(WebViewExample); -}; - -} // namespace examples -} // namespace views - -#endif // UI_VIEWS_EXAMPLES_WEBVIEW_EXAMPLE_H_
diff --git a/ui/views/examples/widget_example.cc b/ui/views/examples/widget_example.cc deleted file mode 100644 index 2c061b7..0000000 --- a/ui/views/examples/widget_example.cc +++ /dev/null
@@ -1,129 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/examples/widget_example.h" - -#include "base/strings/utf_string_conversions.h" -#include "ui/views/background.h" -#include "ui/views/controls/button/label_button.h" -#include "ui/views/controls/label.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 base::ASCIIToUTF16; - -namespace views { -namespace examples { - -namespace { - -class DialogExample : public DialogDelegateView { - public: - DialogExample(); - virtual ~DialogExample(); - virtual base::string16 GetWindowTitle() const override; - virtual View* CreateExtraView() override; - virtual View* CreateTitlebarExtraView() override; - virtual View* CreateFootnoteView() override; -}; - -DialogExample::DialogExample() { - set_background(Background::CreateSolidBackground(SK_ColorGRAY)); - SetLayoutManager(new BoxLayout(BoxLayout::kVertical, 10, 10, 10)); - AddChildView(new Label(ASCIIToUTF16("Dialog contents label!"))); -} - -DialogExample::~DialogExample() {} - -base::string16 DialogExample::GetWindowTitle() const { - return ASCIIToUTF16("Dialog Widget Example"); -} - -View* DialogExample::CreateExtraView() { - LabelButton* button = new LabelButton(NULL, ASCIIToUTF16("Extra button!")); - button->SetStyle(Button::STYLE_BUTTON); - return button; -} - -View* DialogExample::CreateTitlebarExtraView() { - Label* label = new Label(ASCIIToUTF16("Extra view!")); - label->SetEnabledColor(SK_ColorBLUE); - return label; -} - -View* DialogExample::CreateFootnoteView() { - return new Label(ASCIIToUTF16("Footnote label!")); -} - -} // namespace - -WidgetExample::WidgetExample() : ExampleBase("Widget") { -} - -WidgetExample::~WidgetExample() { -} - -void WidgetExample::CreateExampleView(View* container) { - container->SetLayoutManager(new BoxLayout(BoxLayout::kHorizontal, 0, 0, 10)); - BuildButton(container, "Popup widget", POPUP); - BuildButton(container, "Dialog widget", DIALOG); -#if defined(OS_LINUX) - // Windows does not support TYPE_CONTROL top-level widgets. - BuildButton(container, "Child widget", CHILD); -#endif -} - -void WidgetExample::BuildButton(View* container, - const std::string& label, - int tag) { - LabelButton* button = new LabelButton(this, ASCIIToUTF16(label)); - button->SetFocusable(true); - button->set_tag(tag); - container->AddChildView(button); -} - -void WidgetExample::ShowWidget(View* sender, Widget::InitParams params) { - // Setup shared Widget heirarchy and bounds parameters. - params.parent = sender->GetWidget()->GetNativeView(); - params.bounds = gfx::Rect(sender->GetBoundsInScreen().CenterPoint(), - gfx::Size(300, 200)); - - Widget* widget = new Widget(); - widget->Init(params); - - // If the Widget has no contents by default, add a view with a 'Close' button. - if (!widget->GetContentsView()) { - View* contents = new View(); - contents->SetLayoutManager(new BoxLayout(BoxLayout::kHorizontal, 0, 0, 0)); - contents->set_background(Background::CreateSolidBackground(SK_ColorGRAY)); - BuildButton(contents, "Close", CLOSE_WIDGET); - widget->SetContentsView(contents); - } - - widget->Show(); -} - -void WidgetExample::ButtonPressed(Button* sender, const ui::Event& event) { - switch (sender->tag()) { - case POPUP: - ShowWidget(sender, Widget::InitParams(Widget::InitParams::TYPE_POPUP)); - break; - case DIALOG: { - DialogDelegate::CreateDialogWidget(new DialogExample(), NULL, - sender->GetWidget()->GetNativeView())->Show(); - break; - } - case CHILD: - ShowWidget(sender, Widget::InitParams(Widget::InitParams::TYPE_CONTROL)); - break; - case CLOSE_WIDGET: - sender->GetWidget()->Close(); - break; - } -} - -} // namespace examples -} // namespace views
diff --git a/ui/views/examples/widget_example.h b/ui/views/examples/widget_example.h deleted file mode 100644 index 44e1840..0000000 --- a/ui/views/examples/widget_example.h +++ /dev/null
@@ -1,52 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_EXAMPLES_WIDGET_EXAMPLE_H_ -#define UI_VIEWS_EXAMPLES_WIDGET_EXAMPLE_H_ - -#include <string> - -#include "base/macros.h" -#include "ui/views/controls/button/button.h" -#include "ui/views/examples/example_base.h" -#include "ui/views/widget/widget.h" - -namespace views { -namespace examples { - -// WidgetExample demonstrates how to create a popup widget. -class VIEWS_EXAMPLES_EXPORT WidgetExample : public ExampleBase, - public ButtonListener { - public: - WidgetExample(); - virtual ~WidgetExample(); - - // ExampleBase: - virtual void CreateExampleView(View* container) override; - - private: - // Button tags used to identify various commands. - enum Command { - POPUP, // Show a popup widget. - DIALOG, // Show a dialog widget. - CHILD, // Show a child widget. - CLOSE_WIDGET, // Close the sender button's widget. - }; - - // Construct a button with the specified |label| and |tag| in |container|. - void BuildButton(View* container, const std::string& label, int tag); - - // Construct a Widget for |sender|, initialize with |params|, and call Show(). - void ShowWidget(View* sender, Widget::InitParams params); - - // ButtonListener: - virtual void ButtonPressed(Button* sender, const ui::Event& event) override; - - DISALLOW_COPY_AND_ASSIGN(WidgetExample); -}; - -} // namespace examples -} // namespace views - -#endif // UI_VIEWS_EXAMPLES_WIDGET_EXAMPLE_H_
diff --git a/ui/views/focus/external_focus_tracker.cc b/ui/views/focus/external_focus_tracker.cc deleted file mode 100644 index 293c2e0..0000000 --- a/ui/views/focus/external_focus_tracker.cc +++ /dev/null
@@ -1,72 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/focus/external_focus_tracker.h" - -#include "base/logging.h" -#include "ui/views/focus/view_storage.h" -#include "ui/views/view.h" - -namespace views { - -ExternalFocusTracker::ExternalFocusTracker(View* parent_view, - FocusManager* focus_manager) - : focus_manager_(focus_manager), - parent_view_(parent_view) { - DCHECK(parent_view); - view_storage_ = ViewStorage::GetInstance(); - last_focused_view_storage_id_ = view_storage_->CreateStorageID(); - // Store the view which is focused when we're created. - if (focus_manager_) - StartTracking(); -} - -ExternalFocusTracker::~ExternalFocusTracker() { - view_storage_->RemoveView(last_focused_view_storage_id_); - 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 = - view_storage_->RetrieveView(last_focused_view_storage_id_); - 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) { - view_storage_->RemoveView(last_focused_view_storage_id_); - // If the view is NULL, remove the last focused view from storage, but don't - // try to store NULL. - if (view != NULL) - view_storage_->StoreView(last_focused_view_storage_id_, view); -} - -void ExternalFocusTracker::StartTracking() { - StoreLastFocusedView(focus_manager_->GetFocusedView()); - focus_manager_->AddFocusChangeListener(this); -} - -} // namespace views
diff --git a/ui/views/focus/external_focus_tracker.h b/ui/views/focus/external_focus_tracker.h deleted file mode 100644 index 3cfacb3..0000000 --- a/ui/views/focus/external_focus_tracker.h +++ /dev/null
@@ -1,80 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_FOCUS_EXTERNAL_FOCUS_TRACKER_H_ -#define UI_VIEWS_FOCUS_EXTERNAL_FOCUS_TRACKER_H_ - -#include "base/compiler_specific.h" -#include "ui/views/focus/focus_manager.h" - -namespace views { - -class View; -class ViewStorage; - -// 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); - virtual ~ExternalFocusTracker(); - - // FocusChangeListener: - virtual void OnWillChangeFocus(View* focused_before, - View* focused_now) override; - virtual 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. - FocusManager* focus_manager_; - - // ID of the last focused view, which we store in view_storage_. - int last_focused_view_storage_id_; - - // Used to store the last focused view which is not a child of - // ExternalFocusTracker. - ViewStorage* view_storage_; - - // The parent view of views which we should not track focus changes to. We - // also do not track changes to parent_view_ itself. - View* parent_view_; - - DISALLOW_COPY_AND_ASSIGN(ExternalFocusTracker); -}; - -} // namespace views - -#endif // UI_VIEWS_FOCUS_EXTERNAL_FOCUS_TRACKER_H_
diff --git a/ui/views/focus/focus_manager.cc b/ui/views/focus/focus_manager.cc deleted file mode 100644 index 8dec8ea..0000000 --- a/ui/views/focus/focus_manager.cc +++ /dev/null
@@ -1,613 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/focus/focus_manager.h" - -#include <algorithm> -#include <vector> - -#include "base/auto_reset.h" -#include "base/logging.h" -#include "build/build_config.h" -#include "ui/base/accelerators/accelerator.h" -#include "ui/base/ime/input_method.h" -#include "ui/base/ime/text_input_client.h" -#include "ui/base/ime/text_input_focus_manager.h" -#include "ui/base/ui_base_switches_util.h" -#include "ui/events/event.h" -#include "ui/events/keycodes/keyboard_codes.h" -#include "ui/views/focus/focus_manager_delegate.h" -#include "ui/views/focus/focus_search.h" -#include "ui/views/focus/view_storage.h" -#include "ui/views/focus/widget_focus_manager.h" -#include "ui/views/view.h" -#include "ui/views/widget/root_view.h" -#include "ui/views/widget/widget.h" -#include "ui/views/widget/widget_delegate.h" - -namespace views { - -namespace { - -} // namespace - -bool FocusManager::shortcut_handling_suspended_ = false; -bool FocusManager::arrow_key_traversal_enabled_ = false; - -FocusManager::FocusManager(Widget* widget, FocusManagerDelegate* delegate) - : widget_(widget), - delegate_(delegate), - focused_view_(NULL), - accelerator_manager_(new ui::AcceleratorManager), - focus_change_reason_(kReasonDirectFocusChange), - is_changing_focus_(false) { - DCHECK(widget_); - stored_focused_view_storage_id_ = - ViewStorage::GetInstance()->CreateStorageID(); -} - -FocusManager::~FocusManager() { -} - -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; - - int modifiers = ui::EF_NONE; - if (event.IsShiftDown()) - modifiers |= ui::EF_SHIFT_DOWN; - if (event.IsControlDown()) - modifiers |= ui::EF_CONTROL_DOWN; - if (event.IsAltDown()) - modifiers |= ui::EF_ALT_DOWN; -#if defined(OS_MACOSX) || defined(OS_CHROMEOS) - if (event.IsCommandDown()) - modifiers |= ui::EF_COMMAND_DOWN; -#endif - ui::Accelerator accelerator(event.key_code(), modifiers); - accelerator.set_type(event.type()); - accelerator.set_is_repeat(event.IsRepeat()); - - 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 (arrow_key_traversal_enabled_ && ProcessArrowKeyTraversal(event)) - return false; - - // Intercept arrow key messages to switch between grouped views. - if (focused_view_ && focused_view_->GetGroup() != -1 && - (key_code == ui::VKEY_UP || key_code == ui::VKEY_DOWN || - key_code == ui::VKEY_LEFT || key_code == ui::VKEY_RIGHT)) { - bool next = (key_code == ui::VKEY_RIGHT || key_code == ui::VKEY_DOWN); - View::Views views; - focused_view_->parent()->GetViewsInGroup(focused_view_->GetGroup(), - &views); - View::Views::const_iterator i( - std::find(views.begin(), views.end(), focused_view_)); - DCHECK(i != views.end()); - int index = static_cast<int>(i - views.begin()); - index += next ? 1 : -1; - if (index < 0) { - index = static_cast<int>(views.size()) - 1; - } else if (index >= static_cast<int>(views.size())) { - index = 0; - } - SetFocusedViewWithReason(views[index], kReasonFocusTraversal); - 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; -} - -void FocusManager::ValidateFocusedView() { - if (focused_view_ && !ContainsView(focused_view_)) - ClearFocus(); -} - -// 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 : false; -} - -void FocusManager::AdvanceFocus(bool reverse) { - View* v = GetNextFocusableView(focused_view_, NULL, 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_) - SetFocusedViewWithReason(v, kReasonFocusTraversal); - } -} - -void FocusManager::ClearNativeFocus() { - // Keep the top root window focused so we get keyboard events. - widget_->ClearNativeFocus(); -} - -bool FocusManager::RotatePaneFocus(Direction direction, - FocusCycleWrappingBehavior wrap) { - // 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. - int count = static_cast<int>(panes.size()); - if (count == 0) - return false; - - // Initialize |index| to an appropriate starting index if nothing is - // focused initially. - int index = 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) { - for (int i = 0; i < count; i++) { - if (panes[i] && panes[i]->Contains(focused_view)) { - index = i; - break; - } - } - } - - // Rotate focus. - int start_index = index; - for (;;) { - if (direction == kBackward) - index--; - else - index++; - - if (wrap == kNoWrap && (index >= count || index < 0)) - return false; - index = (index + count) % count; - - // Ensure that we don't loop more than once. - if (index == start_index) - break; - - views::View* pane = panes[index]; - DCHECK(pane); - - if (!pane->visible()) - continue; - - pane->RequestFocus(); - focused_view = GetFocusedView(); - if (pane == focused_view || pane->Contains(focused_view)) - return true; - } - - return false; -} - -View* FocusManager::GetNextFocusableView(View* original_starting_view, - Widget* starting_widget, - bool reverse, - bool dont_loop) { - FocusTraversable* focus_traversable = NULL; - - // Let's revalidate the focused view. - ValidateFocusedView(); - - View* starting_view = NULL; - 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_; - 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; - } else { - // 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 = NULL; - View* new_starting_view = NULL; - // When we are going backward, the parent view might gain the next focus. - bool check_starting_view = reverse; - v = parent_focus_traversable->GetFocusSearch()->FindNextFocusableView( - starting_view, reverse, FocusSearch::UP, - check_starting_view, &new_focus_traversable, &new_starting_view); - - if (new_focus_traversable) { - DCHECK(!v); - - // There is a FocusTraversable, traverse it down. - v = FindFocusableView(new_focus_traversable, NULL, 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) { - // Easy, just clear the selection and press tab again. - // By calling with NULL as the starting view, we'll start from either - // the starting views widget or |widget_|. - Widget* widget = original_starting_view->GetWidget(); - if (widget->widget_delegate()->ShouldAdvanceFocusToTopLevelWidget()) - widget = widget_; - return GetNextFocusableView(NULL, widget, reverse, true); - } - } - return NULL; -} - -void FocusManager::SetFocusedViewWithReason( - View* view, FocusChangeReason reason) { - if (focused_view_ == view) { - // In the case that the widget lost the focus and gained it back without - // changing the focused view, we have to make the text input client focused. - // TODO(yukishiino): Remove this hack once we fix http://crbug.com/383236 - FocusTextInputClient(focused_view_); - return; - } - - base::AutoReset<bool> auto_changing_focus(&is_changing_focus_, true); - // Update the reason for the focus change (since this is checked by - // some listeners), then notify all listeners. - focus_change_reason_ = reason; - FOR_EACH_OBSERVER(FocusChangeListener, focus_change_listeners_, - OnWillChangeFocus(focused_view_, view)); - - View* old_focused_view = focused_view_; - focused_view_ = view; - if (old_focused_view) { - old_focused_view->Blur(); - BlurTextInputClient(old_focused_view); - } - // 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_) { - FocusTextInputClient(focused_view_); - focused_view_->Focus(); - } - - FOR_EACH_OBSERVER(FocusChangeListener, focus_change_listeners_, - OnDidChangeFocus(old_focused_view, focused_view_)); -} - -void FocusManager::ClearFocus() { - // SetFocusedView(NULL) is going to clear out the stored view to. We need to - // persist it in this case. - views::View* focused_view = GetStoredFocusView(); - SetFocusedView(NULL); - 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_ && !focused_view_->IsAccessibilityFocusable()) { - AdvanceFocus(false); - if (focused_view_ && !focused_view_->IsAccessibilityFocusable()) - 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 NULL), 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(NULL); - 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, kReasonFocusRestore); - } else { - // This usually just sets the focus if this view is focusable, but - // let the view override RequestFocus if necessary. - view->RequestFocus(); - - // If it succeeded, the reason would be incorrect; set it to - // focus restore. - if (focused_view_ == view) - focus_change_reason_ = kReasonFocusRestore; - } - } - return true; - } - return false; -} - -void FocusManager::SetStoredFocusView(View* focus_view) { - ViewStorage* view_storage = ViewStorage::GetInstance(); - if (!view_storage) { - // This should never happen but bug 981648 seems to indicate it could. - NOTREACHED(); - return; - } - - // TODO(jcivelli): when a TabContents containing a popup is closed, the focus - // is stored twice causing an assert. We should find a better alternative than - // removing the view from the storage explicitly. - view_storage->RemoveView(stored_focused_view_storage_id_); - - if (!focus_view) - return; - - view_storage->StoreView(stored_focused_view_storage_id_, focus_view); -} - -View* FocusManager::GetStoredFocusView() { - ViewStorage* view_storage = ViewStorage::GetInstance(); - if (!view_storage) { - // This should never happen but bug 981648 seems to indicate it could. - NOTREACHED(); - return NULL; - } - - return view_storage->RetrieveView(stored_focused_view_storage_id_); -} - -void FocusManager::ClearStoredFocusedView() { - SetStoredFocusView(NULL); -} - -void FocusManager::OnTextInputClientChanged(View* view) { - if (view == focused_view_) - FocusTextInputClient(view); -} - -void FocusManager::FocusTextInputClient(View* view) { - if (!switches::IsTextInputFocusManagerEnabled()) - return; - - // If the widget is not active, do not steal the text input focus. - if (!widget_->IsActive()) - return; - - ui::TextInputClient* text_input_client = - view ? view->GetTextInputClient() : NULL; - ui::TextInputFocusManager::GetInstance()-> - FocusTextInputClient(text_input_client); - ui::InputMethod* input_method = widget_->GetHostInputMethod(); - if (input_method) { - input_method->OnTextInputTypeChanged(text_input_client); - input_method->OnCaretBoundsChanged(text_input_client); - } -} - -void FocusManager::BlurTextInputClient(View* view) { - if (!switches::IsTextInputFocusManagerEnabled()) - return; - - ui::TextInputClient* text_input_client = - view ? view->GetTextInputClient() : NULL; - if (text_input_client && text_input_client->HasCompositionText()) { - text_input_client->ConfirmCompositionText(); - ui::InputMethod* input_method = widget_->GetHostInputMethod(); - if (input_method && input_method->GetTextInputClient() == text_input_client) - input_method->CancelComposition(text_input_client); - } - ui::TextInputFocusManager::GetInstance()-> - BlurTextInputClient(text_input_client); -} - -// 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 = NULL; - View* new_starting_view = NULL; - View* v = focus_traversable->GetFocusSearch()->FindNextFocusableView( - starting_view, - reverse, - FocusSearch::DOWN, - false, - &new_focus_traversable, - &new_starting_view); - - // Let's go down the FocusTraversable tree as much as we can. - while (new_focus_traversable) { - DCHECK(!v); - focus_traversable = new_focus_traversable; - new_focus_traversable = NULL; - starting_view = NULL; - v = focus_traversable->GetFocusSearch()->FindNextFocusableView( - starting_view, - reverse, - FocusSearch::DOWN, - false, - &new_focus_traversable, - &new_starting_view); - } - 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_.get()) - return delegate_->ProcessAccelerator(accelerator); - return false; -} - -ui::AcceleratorTarget* FocusManager::GetCurrentTargetForAccelerator( - const ui::Accelerator& accelerator) const { - ui::AcceleratorTarget* target = - accelerator_manager_->GetCurrentTarget(accelerator); - if (!target && delegate_.get()) - target = delegate_->GetCurrentTargetForAccelerator(accelerator); - return target; -} - -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(); -} - -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. - if (focused_view_ && removed->Contains(focused_view_)) - SetFocusedView(NULL); -} - -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()) - return false; - - const int key_code = event.key_code(); - if (key_code == ui::VKEY_LEFT || key_code == ui::VKEY_UP) { - AdvanceFocus(true); - return true; - } - if (key_code == ui::VKEY_RIGHT || key_code == ui::VKEY_DOWN) { - AdvanceFocus(false); - return true; - } - - return false; -} - -} // namespace views
diff --git a/ui/views/focus/focus_manager.h b/ui/views/focus/focus_manager.h deleted file mode 100644 index bce8549..0000000 --- a/ui/views/focus/focus_manager.h +++ /dev/null
@@ -1,384 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_FOCUS_FOCUS_MANAGER_H_ -#define UI_VIEWS_FOCUS_FOCUS_MANAGER_H_ - -#include <list> -#include <map> - -#include "base/basictypes.h" -#include "base/memory/scoped_ptr.h" -#include "base/observer_list.h" -#include "ui/base/accelerators/accelerator.h" -#include "ui/base/accelerators/accelerator_manager.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/views/views_export.h" - -// The FocusManager class is used to handle focus traversal, store/restore -// focused views and handle keyboard accelerators. -// -// There are 2 types of focus: -// - the native focus, which is the focus that an gfx::NativeView has. -// - the view focus, which is the focus that a views::View has. -// -// Each native view must register with their Focus Manager so the focus manager -// gets notified when they are focused (and keeps track of the native focus) and -// as well so that the tab key events can be intercepted. -// They can provide when they register a View that is kept in synch in term of -// focus. This is used in NativeControl for example, where a View wraps an -// actual native window. -// This is already done for you if you subclass the NativeControl class or if -// you use the NativeViewHost class. -// -// When creating a top window (derived from views::Widget) that is not a child -// window, it creates and owns a FocusManager to manage the focus for itself and -// all its child windows. -// -// The FocusTraversable interface exposes the methods a class should implement -// in order to be able to be focus traversed when tab key is pressed. -// RootViews implement FocusTraversable. -// The FocusManager contains a top FocusTraversable instance, which is the top -// RootView. -// -// If you just use views, then the focus traversal is handled for you by the -// RootView. The default traversal order is the order in which the views have -// been added to their container. You can modify this order by using the View -// method SetNextFocusableView(). -// -// If you are embedding a native view containing a nested RootView (for example -// by adding a NativeControl that contains a NativeWidgetWin 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 our example: -// hwnd_view_container_->GetWidget()->SetFocusTraversableParent( -// native_control); -// -// Note that FocusTraversable do not have to be RootViews: AccessibleToolbarView -// is FocusTraversable. - -namespace ui { -class AcceleratorManager; -class AcceleratorTarget; -class EventHandler; -class KeyEvent; -} - -namespace views { - -class FocusManagerDelegate; -class FocusSearch; -class View; -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() {} -}; - -// 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() {} -}; - -class VIEWS_EXPORT FocusManager { - public: - // The reason why the focus changed. - enum FocusChangeReason { - // The focus changed because the user traversed focusable views using - // keys like Tab or Shift+Tab. - kReasonFocusTraversal, - - // The focus changed due to restoring the focus. - kReasonFocusRestore, - - // The focus changed due to a click or a shortcut to jump directly to - // a particular view. - kReasonDirectFocusChange - }; - - // TODO: use Direction in place of bool reverse throughout. - enum Direction { - kForward, - kBackward - }; - - enum FocusCycleWrappingBehavior { - kWrap, - kNoWrap - }; - - FocusManager(Widget* widget, FocusManagerDelegate* delegate); - virtual ~FocusManager(); - - // 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) { - SetFocusedViewWithReason(view, kReasonDirectFocusChange); - } - - // 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(); - - // Validates the focused view, clearing it if the window it belongs too is not - // attached to the window hierarchy anymore. - void ValidateFocusedView(); - - // 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 - otherwise 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(); - - // Clears the stored focused view. - void ClearStoredFocusedView(); - - // Returns true if in the process of changing the focused view. - bool is_changing_focus() const { return is_changing_focus_; } - - // Changes the text input focus to |view->GetTextInputClient()| iff |view| - // is focused. Views must call this method when their internal - // TextInputClient instance changes. - void OnTextInputClientChanged(View* view); - - // Moves the text input focus into/out from |view|. - void FocusTextInputClient(View* view); - void BlurTextInputClient(View* view); - - // Disable shortcut handling. - static 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); - - // Returns the AcceleratorTarget that should be activated for the specified - // keyboard accelerator, or NULL if no view is registered for that keyboard - // accelerator. - ui::AcceleratorTarget* GetCurrentTargetForAccelerator( - const ui::Accelerator& accelertor) 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, FocusCycleWrappingBehavior wrap); - - // 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 consuled to determine which - // Widget to start from. See - // WidgetDelegate::ShouldAdvanceFocusToTopLevelWidget() 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); - - 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); - - // Keeps track of whether shortcut handling is currently suspended. - static bool shortcut_handling_suspended_; - - // Whether arrow key traversal is enabled. - static bool arrow_key_traversal_enabled_; - - // The top-level Widget this FocusManager is associated with. - Widget* widget_; - - // The object which handles an accelerator when |accelerator_manager_| doesn't - // handle it. - scoped_ptr<FocusManagerDelegate> delegate_; - - // The view that currently is focused. - View* focused_view_; - - // The AcceleratorManager this FocusManager is associated with. - scoped_ptr<ui::AcceleratorManager> accelerator_manager_; - - // The storage id used in the ViewStorage to store/restore the view that last - // had focus. - int stored_focused_view_storage_id_; - - // The reason why the focus most recently changed. - FocusChangeReason focus_change_reason_; - - // The list of registered FocusChange listeners. - ObserverList<FocusChangeListener, true> focus_change_listeners_; - - // See description above getter. - bool is_changing_focus_; - - DISALLOW_COPY_AND_ASSIGN(FocusManager); -}; - -} // namespace views - -#endif // UI_VIEWS_FOCUS_FOCUS_MANAGER_H_
diff --git a/ui/views/focus/focus_manager_delegate.h b/ui/views/focus/focus_manager_delegate.h deleted file mode 100644 index ca9bd71..0000000 --- a/ui/views/focus/focus_manager_delegate.h +++ /dev/null
@@ -1,39 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef 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; -class AcceleratorTarget; -} - -namespace views { - -// Delegate interface for views::FocusManager. -class VIEWS_EXPORT FocusManagerDelegate { - public: - virtual ~FocusManagerDelegate() {} - - // 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; - - // Returns the AcceleratorTarget that should be activated for the specified - // keyboard accelerator, or NULL if no view is registered for that keyboard - // accelerator. - virtual ui::AcceleratorTarget* GetCurrentTargetForAccelerator( - const ui::Accelerator& accelerator) const = 0; -}; - -} // namespace views - -#endif // UI_VIEWS_FOCUS_FOCUS_MANAGER_DELEGATE_H_
diff --git a/ui/views/focus/focus_manager_factory.cc b/ui/views/focus/focus_manager_factory.cc deleted file mode 100644 index bcbbfba..0000000 --- a/ui/views/focus/focus_manager_factory.cc +++ /dev/null
@@ -1,55 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/focus/focus_manager_factory.h" - -#include "base/compiler_specific.h" -#include "ui/views/focus/focus_manager.h" - -namespace views { - -namespace { - -class DefaultFocusManagerFactory : public FocusManagerFactory { - public: - DefaultFocusManagerFactory() : FocusManagerFactory() {} - virtual ~DefaultFocusManagerFactory() {} - - protected: - virtual FocusManager* CreateFocusManager(Widget* widget, - bool desktop_widget) override { - return new FocusManager(widget, NULL /* delegate */); - } - - private: - DISALLOW_COPY_AND_ASSIGN(DefaultFocusManagerFactory); -}; - -FocusManagerFactory* focus_manager_factory = NULL; - -} // namespace - -FocusManagerFactory::FocusManagerFactory() { -} - -FocusManagerFactory::~FocusManagerFactory() { -} - -// static -FocusManager* FocusManagerFactory::Create(Widget* widget, - bool desktop_widget) { - if (!focus_manager_factory) - focus_manager_factory = new DefaultFocusManagerFactory(); - return focus_manager_factory->CreateFocusManager(widget, desktop_widget); -} - -// static -void FocusManagerFactory::Install(FocusManagerFactory* f) { - if (f == focus_manager_factory) - return; - delete focus_manager_factory; - focus_manager_factory = f ? f : new DefaultFocusManagerFactory(); -} - -} // namespace views
diff --git a/ui/views/focus/focus_manager_factory.h b/ui/views/focus/focus_manager_factory.h deleted file mode 100644 index 6f13b24..0000000 --- a/ui/views/focus/focus_manager_factory.h +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_FOCUS_FOCUS_MANAGER_FACTORY_H_ -#define UI_VIEWS_FOCUS_FOCUS_MANAGER_FACTORY_H_ - -#include "base/basictypes.h" -#include "ui/views/views_export.h" - -namespace views { - -class FocusManager; -class Widget; - -// A factory to create FocusManager. This is used in unit tests -// to inject a custom factory. -class VIEWS_EXPORT FocusManagerFactory { - public: - // Create a FocusManager for the given |widget| using installe Factory. - static FocusManager* Create(Widget* widget, bool desktop_widget); - - // Installs FocusManagerFactory. If |factory| is NULL, it resets - // to the default factory which creates plain FocusManager. - static void Install(FocusManagerFactory* factory); - - protected: - FocusManagerFactory(); - virtual ~FocusManagerFactory(); - - // Create a FocusManager for the given |widget|. - // The |desktop_widget| bool is true for widgets created in the desktop and - // false for widgets created in the shell. - virtual FocusManager* CreateFocusManager(Widget* widget, - bool desktop_widget) = 0; - - private: - DISALLOW_COPY_AND_ASSIGN(FocusManagerFactory); -}; - -} // namespace views - -#endif // UI_VIEWS_FOCUS_FOCUS_MANAGER_FACTORY_H_
diff --git a/ui/views/focus/focus_manager_unittest.cc b/ui/views/focus/focus_manager_unittest.cc deleted file mode 100644 index f6d9a43..0000000 --- a/ui/views/focus/focus_manager_unittest.cc +++ /dev/null
@@ -1,920 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/focus/focus_manager.h" - -#include <utility> -#include <vector> - -#include "base/command_line.h" -#include "base/strings/utf_string_conversions.h" -#include "ui/aura/client/focus_client.h" -#include "ui/aura/window.h" -#include "ui/base/accelerators/accelerator.h" -#include "ui/base/ime/dummy_text_input_client.h" -#include "ui/base/ime/text_input_focus_manager.h" -#include "ui/base/ui_base_switches.h" -#include "ui/events/keycodes/keyboard_codes.h" -#include "ui/views/accessible_pane_view.h" -#include "ui/views/controls/button/label_button.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/widget/widget.h" - -namespace views { - -enum FocusTestEventType { - ON_FOCUS = 0, - ON_BLUR -}; - -struct FocusTestEvent { - FocusTestEvent(FocusTestEventType type, int view_id) - : type(type), - view_id(view_id) { - } - - FocusTestEventType type; - int view_id; -}; - -class SimpleTestView : public View { - public: - SimpleTestView(std::vector<FocusTestEvent>* event_list, int view_id) - : event_list_(event_list) { - SetFocusable(true); - set_id(view_id); - } - - virtual void OnFocus() override { - event_list_->push_back(FocusTestEvent(ON_FOCUS, id())); - } - - virtual void OnBlur() override { - event_list_->push_back(FocusTestEvent(ON_BLUR, id())); - } - - private: - std::vector<FocusTestEvent>* event_list_; - - DISALLOW_COPY_AND_ASSIGN(SimpleTestView); -}; - -// 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); - - 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); - - 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); -} - -TEST_F(FocusManagerTest, FocusChangeListener) { - View* view1 = new View(); - view1->SetFocusable(true); - View* view2 = new View(); - view2->SetFocusable(true); - 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 = NULL; - - 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) { - TestWidgetFocusChangeListener widget_listener; - AddWidgetFocusChangeListener(&widget_listener); - - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); - params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.bounds = gfx::Rect(10, 10, 100, 100); - params.parent = GetWidget()->GetNativeView(); - - scoped_ptr<Widget> widget1(new Widget); - widget1->Init(params); - widget1->Show(); - - scoped_ptr<Widget> widget2(new Widget); - widget2->Init(params); - widget2->Show(); - - widget_listener.ClearFocusChanges(); - gfx::NativeView native_view1 = widget1->GetNativeView(); - aura::client::GetFocusClient(native_view1)->FocusWindow(native_view1); - ASSERT_EQ(2, static_cast<int>(widget_listener.focus_changes().size())); - EXPECT_EQ(native_view1, widget_listener.focus_changes()[0].second); - EXPECT_EQ(native_view1, widget_listener.focus_changes()[1].second); - - widget_listener.ClearFocusChanges(); - gfx::NativeView native_view2 = widget2->GetNativeView(); - aura::client::GetFocusClient(native_view2)->FocusWindow(native_view2); - ASSERT_EQ(2, static_cast<int>(widget_listener.focus_changes().size())); - EXPECT_EQ(NativeViewPair(native_view1, native_view2), - widget_listener.focus_changes()[0]); - EXPECT_EQ(NativeViewPair(native_view1, native_view2), - widget_listener.focus_changes()[1]); -} - -// Counts accelerator calls. -class TestAcceleratorTarget : public ui::AcceleratorTarget { - public: - explicit TestAcceleratorTarget(bool process_accelerator) - : accelerator_count_(0), - process_accelerator_(process_accelerator), - can_handle_accelerators_(true) {} - - virtual bool AcceleratorPressed(const ui::Accelerator& accelerator) override { - ++accelerator_count_; - return process_accelerator_; - } - - virtual bool CanHandleAccelerators() const override { - return can_handle_accelerators_; - } - - int accelerator_count() const { return accelerator_count_; } - - void set_can_handle_accelerators(bool can_handle_accelerators) { - can_handle_accelerators_ = can_handle_accelerators; - } - - private: - int accelerator_count_; // number of times that the accelerator is activated - bool process_accelerator_; // return value of AcceleratorPressed - bool can_handle_accelerators_; // return value of CanHandleAccelerators - - DISALLOW_COPY_AND_ASSIGN(TestAcceleratorTarget); -}; - -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); - - TestAcceleratorTarget return_target(true); - TestAcceleratorTarget escape_target(true); - EXPECT_EQ(return_target.accelerator_count(), 0); - EXPECT_EQ(escape_target.accelerator_count(), 0); - EXPECT_EQ(NULL, - focus_manager->GetCurrentTargetForAccelerator(return_accelerator)); - EXPECT_EQ(NULL, - focus_manager->GetCurrentTargetForAccelerator(escape_accelerator)); - - // Register targets. - focus_manager->RegisterAccelerator(return_accelerator, - ui::AcceleratorManager::kNormalPriority, - &return_target); - focus_manager->RegisterAccelerator(escape_accelerator, - ui::AcceleratorManager::kNormalPriority, - &escape_target); - - // Checks if the correct target is registered. - EXPECT_EQ(&return_target, - focus_manager->GetCurrentTargetForAccelerator(return_accelerator)); - EXPECT_EQ(&escape_target, - focus_manager->GetCurrentTargetForAccelerator(escape_accelerator)); - - // 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. - TestAcceleratorTarget return_target2(true); - EXPECT_EQ(return_target2.accelerator_count(), 0); - focus_manager->RegisterAccelerator(return_accelerator, - ui::AcceleratorManager::kNormalPriority, - &return_target2); - EXPECT_EQ(&return_target2, - focus_manager->GetCurrentTargetForAccelerator(return_accelerator)); - - // 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. - TestAcceleratorTarget return_target3(false); - EXPECT_EQ(return_target3.accelerator_count(), 0); - focus_manager->RegisterAccelerator(return_accelerator, - ui::AcceleratorManager::kNormalPriority, - &return_target3); - EXPECT_EQ(&return_target3, - focus_manager->GetCurrentTargetForAccelerator(return_accelerator)); - - // 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); - EXPECT_EQ(&return_target3, - focus_manager->GetCurrentTargetForAccelerator(return_accelerator)); - - // 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); - - // Now there is no target registered. - EXPECT_EQ(NULL, - focus_manager->GetCurrentTargetForAccelerator(return_accelerator)); - EXPECT_EQ(NULL, - focus_manager->GetCurrentTargetForAccelerator(escape_accelerator)); - - // 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); - - TestAcceleratorTarget escape_target_high(true); - TestAcceleratorTarget escape_target_normal(true); - EXPECT_EQ(escape_target_high.accelerator_count(), 0); - EXPECT_EQ(escape_target_normal.accelerator_count(), 0); - EXPECT_EQ(NULL, - focus_manager->GetCurrentTargetForAccelerator(escape_accelerator)); - EXPECT_FALSE(focus_manager->HasPriorityHandler(escape_accelerator)); - - // Register high priority target. - focus_manager->RegisterAccelerator(escape_accelerator, - ui::AcceleratorManager::kHighPriority, - &escape_target_high); - EXPECT_EQ(&escape_target_high, - focus_manager->GetCurrentTargetForAccelerator(escape_accelerator)); - 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_EQ(&escape_target_high, - focus_manager->GetCurrentTargetForAccelerator(escape_accelerator)); - 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_EQ(&escape_target_normal, - focus_manager->GetCurrentTargetForAccelerator(escape_accelerator)); - 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_EQ(&escape_target_high, - focus_manager->GetCurrentTargetForAccelerator(escape_accelerator)); - 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_EQ(&escape_target_high, - focus_manager->GetCurrentTargetForAccelerator(escape_accelerator)); - 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_EQ(NULL, - focus_manager->GetCurrentTargetForAccelerator(escape_accelerator)); - 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); - - TestAcceleratorTarget return_target1(true); - 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::AcceleratorTarget { - public: - SelfUnregisteringAcceleratorTarget(ui::Accelerator accelerator, - FocusManager* focus_manager) - : accelerator_(accelerator), - focus_manager_(focus_manager), - accelerator_count_(0) { - } - - virtual bool AcceleratorPressed(const ui::Accelerator& accelerator) override { - ++accelerator_count_; - focus_manager_->UnregisterAccelerator(accelerator, this); - return true; - } - - virtual bool CanHandleAccelerators() const override { - return true; - } - - int accelerator_count() const { return accelerator_count_; } - - private: - ui::Accelerator accelerator_; - FocusManager* focus_manager_; - int accelerator_count_; - - DISALLOW_COPY_AND_ASSIGN(SelfUnregisteringAcceleratorTarget); -}; - -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); - EXPECT_EQ(NULL, - focus_manager->GetCurrentTargetForAccelerator(return_accelerator)); - - // Register the target. - focus_manager->RegisterAccelerator(return_accelerator, - ui::AcceleratorManager::kNormalPriority, - &target); - EXPECT_EQ(&target, - focus_manager->GetCurrentTargetForAccelerator(return_accelerator)); - - // Hitting the return key. The target will be unregistered. - EXPECT_TRUE(focus_manager->ProcessAccelerator(return_accelerator)); - EXPECT_EQ(target.accelerator_count(), 1); - EXPECT_EQ(NULL, - focus_manager->GetCurrentTargetForAccelerator(return_accelerator)); - - // Hitting the return key again; nothing should happen. - EXPECT_FALSE(focus_manager->ProcessAccelerator(return_accelerator)); - EXPECT_EQ(target.accelerator_count(), 1); -} - -class FocusManagerDtorTest : public FocusManagerTest { - protected: - typedef std::vector<std::string> DtorTrackVector; - - class FocusManagerDtorTracked : public FocusManager { - public: - FocusManagerDtorTracked(Widget* widget, DtorTrackVector* dtor_tracker) - : FocusManager(widget, NULL /* delegate */), - dtor_tracker_(dtor_tracker) { - } - - virtual ~FocusManagerDtorTracked() { - dtor_tracker_->push_back("FocusManagerDtorTracked"); - } - - DtorTrackVector* dtor_tracker_; - - private: - DISALLOW_COPY_AND_ASSIGN(FocusManagerDtorTracked); - }; - - class TestFocusManagerFactory : public FocusManagerFactory { - public: - explicit TestFocusManagerFactory(DtorTrackVector* dtor_tracker) - : dtor_tracker_(dtor_tracker) { - } - - virtual FocusManager* CreateFocusManager(Widget* widget, - bool desktop_widget) override { - return new FocusManagerDtorTracked(widget, dtor_tracker_); - } - - private: - DtorTrackVector* dtor_tracker_; - DISALLOW_COPY_AND_ASSIGN(TestFocusManagerFactory); - }; - - class LabelButtonDtorTracked : public LabelButton { - public: - LabelButtonDtorTracked(const base::string16& text, - DtorTrackVector* dtor_tracker) - : LabelButton(NULL, text), - dtor_tracker_(dtor_tracker) { - SetStyle(STYLE_BUTTON); - }; - virtual ~LabelButtonDtorTracked() { - dtor_tracker_->push_back("LabelButtonDtorTracked"); - } - - DtorTrackVector* dtor_tracker_; - }; - - class WindowDtorTracked : public Widget { - public: - explicit WindowDtorTracked(DtorTrackVector* dtor_tracker) - : dtor_tracker_(dtor_tracker) { - } - - virtual ~WindowDtorTracked() { - dtor_tracker_->push_back("WindowDtorTracked"); - } - - DtorTrackVector* dtor_tracker_; - }; - - virtual void SetUp() { - ViewsTestBase::SetUp(); - FocusManagerFactory::Install(new TestFocusManagerFactory(&dtor_tracker_)); - // Create WindowDtorTracked that uses FocusManagerDtorTracked. - Widget* widget = new WindowDtorTracked(&dtor_tracker_); - Widget::InitParams params; - params.delegate = this; - params.bounds = gfx::Rect(0, 0, 100, 100); - widget->Init(params); - - tracked_focus_manager_ = - static_cast<FocusManagerDtorTracked*>(GetFocusManager()); - widget->Show(); - } - - virtual void TearDown() { - FocusManagerFactory::Install(NULL); - ViewsTestBase::TearDown(); - } - - FocusManager* tracked_focus_manager_; - DtorTrackVector dtor_tracker_; -}; - -namespace { - -class FocusInAboutToRequestFocusFromTabTraversalView : public View { - public: - FocusInAboutToRequestFocusFromTabTraversalView() : view_to_focus_(NULL) {} - - void set_view_to_focus(View* view) { view_to_focus_ = view; } - - virtual void AboutToRequestFocusFromTabTraversal(bool reverse) override { - view_to_focus_->RequestFocus(); - } - - private: - views::View* view_to_focus_; - - DISALLOW_COPY_AND_ASSIGN(FocusInAboutToRequestFocusFromTabTraversalView); -}; -} // 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->SetFocusable(true); - GetContentsView()->AddChildView(v1); - - FocusInAboutToRequestFocusFromTabTraversalView* v2 = - new FocusInAboutToRequestFocusFromTabTraversalView; - v2->SetFocusable(true); - v2->set_view_to_focus(v1); - GetContentsView()->AddChildView(v2); - - views::View* v3 = new View; - v3->SetFocusable(true); - 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->SetFocusable(true); - pane1->AddChildView(v1); - - views::View* v2 = new View; - v2->SetFocusable(true); - pane1->AddChildView(v2); - - views::AccessiblePaneView* pane2 = new AccessiblePaneView(); - GetContentsView()->AddChildView(pane2); - - views::View* v3 = new View; - v3->SetFocusable(true); - pane2->AddChildView(v3); - - views::View* v4 = new View; - v4->SetFocusable(true); - 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. - EXPECT_TRUE(focus_manager->RotatePaneFocus( - FocusManager::kForward, FocusManager::kWrap)); - 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( - FocusManager::kForward, FocusManager::kWrap)); - 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( - FocusManager::kForward, FocusManager::kWrap)); - EXPECT_EQ(v1, focus_manager->GetFocusedView()); - - // Advance backwards. - EXPECT_TRUE(focus_manager->RotatePaneFocus( - FocusManager::kBackward, FocusManager::kWrap)); - EXPECT_EQ(v3, focus_manager->GetFocusedView()); - - EXPECT_TRUE(focus_manager->RotatePaneFocus( - FocusManager::kBackward, FocusManager::kWrap)); - 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( - FocusManager::kForward, FocusManager::kNoWrap)); - EXPECT_EQ(v3, focus_manager->GetFocusedView()); - - EXPECT_FALSE(focus_manager->RotatePaneFocus( - FocusManager::kForward, FocusManager::kNoWrap)); - 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->SetFocusable(true); - GetContentsView()->AddChildView(v1); - - views::View* v2 = new View; - v2->SetFocusable(true); - 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: - FocusManagerArrowKeyTraversalTest() - : previous_arrow_key_traversal_enabled_(false) { - } - virtual ~FocusManagerArrowKeyTraversalTest() {} - - // FocusManagerTest overrides: - virtual void SetUp() override { - FocusManagerTest::SetUp(); - - previous_arrow_key_traversal_enabled_ = - FocusManager::arrow_key_traversal_enabled(); - } - virtual void TearDown() override { - FocusManager::set_arrow_key_traversal_enabled( - previous_arrow_key_traversal_enabled_); - FocusManagerTest::TearDown(); - } - - private: - bool previous_arrow_key_traversal_enabled_; - - DISALLOW_COPY_AND_ASSIGN(FocusManagerArrowKeyTraversalTest); -}; - -} // namespace - -TEST_F(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->SetFocusable(true); - 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(right_key); - EXPECT_EQ(v[1], focus_manager->GetFocusedView()); - focus_manager->OnKeyEvent(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, StoreFocusedView) { - View view; - GetFocusManager()->SetFocusedView(&view); - GetFocusManager()->StoreFocusedView(false); - EXPECT_EQ(NULL, GetFocusManager()->GetFocusedView()); - EXPECT_TRUE(GetFocusManager()->RestoreFocusedView()); - EXPECT_EQ(&view, GetFocusManager()->GetStoredFocusView()); - - // Repeat with |true|. - GetFocusManager()->SetFocusedView(&view); - GetFocusManager()->StoreFocusedView(true); - EXPECT_EQ(NULL, GetFocusManager()->GetFocusedView()); - EXPECT_TRUE(GetFocusManager()->RestoreFocusedView()); - EXPECT_EQ(&view, GetFocusManager()->GetStoredFocusView()); -} - -class TextInputTestView : public View { - public: - TextInputTestView() {} - - virtual ui::TextInputClient* GetTextInputClient() override { - return &text_input_client_; - } - - private: - ui::DummyTextInputClient text_input_client_; - - DISALLOW_COPY_AND_ASSIGN(TextInputTestView); -}; - -TEST_F(FocusManagerTest, TextInputClient) { - base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess(); - cmd_line->AppendSwitch(switches::kEnableTextInputFocusManager); - - View* view = new TextInputTestView; - ui::TextInputClient* text_input_client = view->GetTextInputClient(); - view->SetFocusable(true); - GetContentsView()->AddChildView(view); - ui::TextInputFocusManager* text_input_focus_manager = - ui::TextInputFocusManager::GetInstance(); - - GetFocusManager()->SetFocusedView(view); - EXPECT_EQ(view, GetFocusManager()->GetFocusedView()); - EXPECT_EQ(text_input_client, - text_input_focus_manager->GetFocusedTextInputClient()); - GetFocusManager()->StoreFocusedView(false); - EXPECT_TRUE(GetFocusManager()->RestoreFocusedView()); - EXPECT_EQ(text_input_client, - text_input_focus_manager->GetFocusedTextInputClient()); - - // Repeat with |true|. - GetFocusManager()->SetFocusedView(view); - EXPECT_EQ(view, GetFocusManager()->GetFocusedView()); - EXPECT_EQ(text_input_client, - text_input_focus_manager->GetFocusedTextInputClient()); - GetFocusManager()->StoreFocusedView(true); - EXPECT_TRUE(GetFocusManager()->RestoreFocusedView()); - EXPECT_EQ(text_input_client, - text_input_focus_manager->GetFocusedTextInputClient()); - - // Focus the view twice in a row. - GetFocusManager()->SetFocusedView(view); - EXPECT_EQ(text_input_client, - text_input_focus_manager->GetFocusedTextInputClient()); - ui::TextInputFocusManager::GetInstance()->FocusTextInputClient(NULL); - GetFocusManager()->SetFocusedView(view); - EXPECT_EQ(text_input_client, - text_input_focus_manager->GetFocusedTextInputClient()); -} - -namespace { - -// Trivial WidgetDelegate implementation that allows setting return value of -// ShouldAdvanceFocusToTopLevelWidget(). -class AdvanceFocusWidgetDelegate : public WidgetDelegate { - public: - explicit AdvanceFocusWidgetDelegate(Widget* widget) - : widget_(widget), - should_advance_focus_to_parent_(false) {} - virtual ~AdvanceFocusWidgetDelegate() {} - - void set_should_advance_focus_to_parent(bool value) { - should_advance_focus_to_parent_ = value; - } - - // WidgetDelegate overrides: - virtual bool ShouldAdvanceFocusToTopLevelWidget() const override { - return should_advance_focus_to_parent_; - } - virtual Widget* GetWidget() override { return widget_; } - virtual const Widget* GetWidget() const override { return widget_; } - - private: - Widget* widget_; - bool should_advance_focus_to_parent_; - - DISALLOW_COPY_AND_ASSIGN(AdvanceFocusWidgetDelegate); -}; - -} // 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->SetFocusable(true); - widget_view->SetBounds(20, 0, 20, 20); - GetContentsView()->AddChildView(widget_view); - - // Create a widget with two views, focus the second. - scoped_ptr<AdvanceFocusWidgetDelegate> delegate; - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); - params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.child = true; - params.bounds = gfx::Rect(10, 10, 100, 100); - params.parent = GetWidget()->GetNativeView(); - Widget child_widget; - delegate.reset(new AdvanceFocusWidgetDelegate(&child_widget)); - params.delegate = delegate.get(); - child_widget.Init(params); - View* view1 = new View; - view1->SetFocusable(true); - view1->SetBounds(0, 0, 20, 20); - View* view2 = new View; - view2->SetFocusable(true); - 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()); - - // Allow focus to go to the parent, and focus backwards which should now move - // up |widget_view| (in the parent). - delegate->set_should_advance_focus_to_parent(true); - GetFocusManager()->AdvanceFocus(true); - EXPECT_EQ(widget_view, GetFocusManager()->GetFocusedView()); -} - -} // namespace views
diff --git a/ui/views/focus/focus_search.cc b/ui/views/focus/focus_search.cc deleted file mode 100644 index 2507b34..0000000 --- a/ui/views/focus/focus_search.cc +++ /dev/null
@@ -1,275 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/logging.h" -#include "ui/views/focus/focus_manager.h" -#include "ui/views/focus/focus_search.h" -#include "ui/views/view.h" - -namespace views { - -FocusSearch::FocusSearch(View* root, bool cycle, bool accessibility_mode) - : root_(root), - cycle_(cycle), - accessibility_mode_(accessibility_mode) { -} - -View* FocusSearch::FindNextFocusableView(View* starting_view, - bool reverse, - Direction direction, - bool check_starting_view, - FocusTraversable** focus_traversable, - View** focus_traversable_view) { - *focus_traversable = NULL; - *focus_traversable_view = NULL; - - if (!root_->has_children()) { - NOTREACHED(); - // Nothing to focus on here. - return NULL; - } - - 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 = reverse ? root_->child_at(root_->child_count() - 1) : - root_->child_at(0); - // If there was no starting view, then the one we select is a potential - // focus candidate. - check_starting_view = true; - } else { - // The starting view should be a direct or indirect child of the root. - DCHECK(Contains(root_, starting_view)); - } - - View* v = NULL; - if (!reverse) { - v = FindNextFocusableViewImpl(starting_view, check_starting_view, - true, - (direction == DOWN), - starting_view_group, - 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 = (direction == DOWN) && !IsFocusable(starting_view); - v = FindPreviousFocusableViewImpl(starting_view, check_starting_view, - true, - can_go_down, - starting_view_group, - 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 = NULL; - - // If |cycle_| is true, prefer to keep cycling rather than returning NULL. - if (cycle_ && !v && initial_starting_view) { - v = FindNextFocusableView(NULL, reverse, direction, check_starting_view, - focus_traversable, focus_traversable_view); - DCHECK(IsFocusable(v)); - return v; - } - - // Doing some sanity checks. - if (v) { - DCHECK(IsFocusable(v)); - return v; - } - if (*focus_traversable) { - DCHECK(*focus_traversable_view); - return NULL; - } - // Nothing found. - return NULL; -} - -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) { - if (accessibility_mode_) - 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() : NULL; -} - -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, - bool check_starting_view, - bool can_go_up, - bool can_go_down, - int skip_group_id, - FocusTraversable** focus_traversable, - View** focus_traversable_view) { - if (check_starting_view) { - 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 NULL; - } - } - - // First let's try the left child. - if (can_go_down) { - if (starting_view->has_children()) { - View* v = FindNextFocusableViewImpl(starting_view->child_at(0), - true, false, true, skip_group_id, - focus_traversable, - focus_traversable_view); - if (v || *focus_traversable) - return v; - } - } - - // Then try the right sibling. - View* sibling = starting_view->GetNextFocusableView(); - if (sibling) { - View* v = FindNextFocusableViewImpl(sibling, - true, false, true, skip_group_id, - 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_) { - sibling = parent->GetNextFocusableView(); - if (sibling) { - return FindNextFocusableViewImpl(sibling, - true, true, true, - skip_group_id, - focus_traversable, - focus_traversable_view); - } - parent = GetParent(parent); - } - } - - // We found nothing. - return NULL; -} - -// 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, - bool check_starting_view, - bool can_go_up, - bool can_go_down, - int skip_group_id, - FocusTraversable** focus_traversable, - View** focus_traversable_view) { - // 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 NULL; - } - - if (starting_view->has_children()) { - View* view = - starting_view->child_at(starting_view->child_count() - 1); - View* v = FindPreviousFocusableViewImpl(view, true, false, true, - skip_group_id, - 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 && - 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, - true, true, true, - skip_group_id, - focus_traversable, - focus_traversable_view); - } - - // Then go up the parent. - if (can_go_up) { - View* parent = GetParent(starting_view); - if (parent) - return FindPreviousFocusableViewImpl(parent, - true, true, false, - skip_group_id, - focus_traversable, - focus_traversable_view); - } - - // We found nothing. - return NULL; -} - -} // namespace views
diff --git a/ui/views/focus/focus_search.h b/ui/views/focus/focus_search.h deleted file mode 100644 index 76b367f..0000000 --- a/ui/views/focus/focus_search.h +++ /dev/null
@@ -1,128 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_FOCUS_FOCUS_SEARCH_H_ -#define UI_VIEWS_FOCUS_FOCUS_SEARCH_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 Direction { - UP = 0, - DOWN - }; - - // 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); - virtual ~FocusSearch() {} - - // 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). - // - |reverse| whether we should find the next (reverse is false) or the - // previous (reverse is true) view. - // - |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| is true if starting_view may obtain the next focus. - // - |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, - bool reverse, - Direction direction, - bool check_starting_view, - 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). - 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, - bool check_starting_view, - bool can_go_up, - bool can_go_down, - int skip_group_id, - FocusTraversable** focus_traversable, - View** focus_traversable_view); - - // Same as FindNextFocusableViewImpl but returns the previous focusable view. - View* FindPreviousFocusableViewImpl(View* starting_view, - bool check_starting_view, - bool can_go_up, - bool can_go_down, - int skip_group_id, - FocusTraversable** focus_traversable, - View** focus_traversable_view); - - View* root_; - bool cycle_; - bool accessibility_mode_; - - DISALLOW_COPY_AND_ASSIGN(FocusSearch); -}; - -} // namespace views - -#endif // UI_VIEWS_FOCUS_FOCUS_SEARCH_H_
diff --git a/ui/views/focus/focus_traversal_unittest.cc b/ui/views/focus/focus_traversal_unittest.cc deleted file mode 100644 index db55e9d..0000000 --- a/ui/views/focus/focus_traversal_unittest.cc +++ /dev/null
@@ -1,779 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/focus/focus_manager.h" - -#include "base/run_loop.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/utf_string_conversions.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/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/test/focus_manager_test.h" -#include "ui/views/widget/root_view.h" -#include "ui/views/widget/widget.h" - -using base::ASCIIToUTF16; - -namespace views { - -namespace { - -int count = 1; - -const int kTopCheckBoxID = count++; // 1 -const int kLeftContainerID = count++; -const int kAppleLabelID = count++; -const int kAppleTextfieldID = count++; -const int kOrangeLabelID = count++; // 5 -const int kOrangeTextfieldID = count++; -const int kBananaLabelID = count++; -const int kBananaTextfieldID = count++; -const int kKiwiLabelID = count++; -const int kKiwiTextfieldID = count++; // 10 -const int kFruitButtonID = count++; -const int kFruitCheckBoxID = count++; -const int kComboboxID = count++; - -const int kRightContainerID = count++; -const int kAsparagusButtonID = count++; // 15 -const int kBroccoliButtonID = count++; -const int kCauliflowerButtonID = count++; - -const int kInnerContainerID = count++; -const int kScrollViewID = count++; -const int kRosettaLinkID = count++; // 20 -const int kStupeurEtTremblementLinkID = count++; -const int kDinerGameLinkID = count++; -const int kRidiculeLinkID = count++; -const int kClosetLinkID = count++; -const int kVisitingLinkID = count++; // 25 -const int kAmelieLinkID = count++; -const int kJoyeuxNoelLinkID = count++; -const int kCampingLinkID = count++; -const int kBriceDeNiceLinkID = count++; -const int kTaxiLinkID = count++; // 30 -const int kAsterixLinkID = count++; - -const int kOKButtonID = count++; -const int kCancelButtonID = count++; -const int kHelpButtonID = count++; - -const int kStyleContainerID = count++; // 35 -const int kBoldCheckBoxID = count++; -const int kItalicCheckBoxID = count++; -const int kUnderlinedCheckBoxID = count++; -const int kStyleHelpLinkID = count++; -const int kStyleTextEditID = count++; // 40 - -const int kSearchContainerID = count++; -const int kSearchTextfieldID = count++; -const int kSearchButtonID = count++; -const int kHelpLinkID = count++; - -const int kThumbnailContainerID = count++; // 45 -const int kThumbnailStarID = count++; -const int kThumbnailSuperStarID = count++; - -class DummyComboboxModel : public ui::ComboboxModel { - public: - // Overridden from ui::ComboboxModel: - virtual int GetItemCount() const override { return 10; } - virtual base::string16 GetItemAt(int index) override { - return ASCIIToUTF16("Item ") + base::IntToString16(index); - } -}; - -// A View that can act as a pane. -class PaneView : public View, public FocusTraversable { - public: - PaneView() : focus_search_(NULL) {} - - // 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: - virtual FocusTraversable* GetPaneFocusTraversable() override { - if (focus_search_) - return this; - else - return NULL; - } - - // Overridden from FocusTraversable: - virtual views::FocusSearch* GetFocusSearch() override { - return focus_search_; - } - virtual FocusTraversable* GetFocusTraversableParent() override { - return NULL; - } - virtual View* GetFocusTraversableParentView() override { - return NULL; - } - - private: - FocusSearch* focus_search_; -}; - -// 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(View* child) : child_(child), widget_(NULL) { - DCHECK(child); - SetFocusable(false); - } - - virtual ~BorderView() {} - - virtual internal::RootView* GetContentsRootView() { - return static_cast<internal::RootView*>(widget_->GetRootView()); - } - - virtual FocusTraversable* GetFocusTraversable() override { - return static_cast<internal::RootView*>(widget_->GetRootView()); - } - - virtual void ViewHierarchyChanged( - const ViewHierarchyChangedDetails& details) override { - NativeViewHost::ViewHierarchyChanged(details); - - if (details.child == this && details.is_add) { - if (!widget_) { - widget_ = new Widget; - Widget::InitParams params(Widget::InitParams::TYPE_CONTROL); - params.parent = details.parent->GetWidget()->GetNativeView(); - widget_->Init(params); - widget_->SetFocusTraversableParentView(this); - widget_->SetContentsView(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: - View* child_; - Widget* widget_; - - DISALLOW_COPY_AND_ASSIGN(BorderView); -}; - -} // namespace - -class FocusTraversalTest : public FocusManagerTest { - public: - virtual ~FocusTraversalTest(); - - virtual void InitContentView() override; - - protected: - FocusTraversalTest(); - - View* FindViewByID(int id) { - View* view = GetContentsView()->GetViewByID(id); - if (view) - return view; - if (style_tab_) - view = style_tab_->GetSelectedTab()->GetViewByID(id); - if (view) - return view; - view = search_border_view_->GetContentsRootView()->GetViewByID(id); - if (view) - return view; - return NULL; - } - - protected: - TabbedPane* style_tab_; - BorderView* search_border_view_; - DummyComboboxModel combobox_model_; - PaneView* left_container_; - PaneView* right_container_; - - DISALLOW_COPY_AND_ASSIGN(FocusTraversalTest); -}; - -FocusTraversalTest::FocusTraversalTest() - : style_tab_(NULL), - search_border_view_(NULL) { -} - -FocusTraversalTest::~FocusTraversalTest() { -} - -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 * kTopCheckBoxID - // PaneView kLeftContainerID - // Label kAppleLabelID - // Textfield * kAppleTextfieldID - // Label kOrangeLabelID - // Textfield * kOrangeTextfieldID - // Label kBananaLabelID - // Textfield * kBananaTextfieldID - // Label kKiwiLabelID - // Textfield * kKiwiTextfieldID - // NativeButton * kFruitButtonID - // Checkbox * kFruitCheckBoxID - // Combobox * kComboboxID - // PaneView kRightContainerID - // RadioButton * kAsparagusButtonID - // RadioButton * kBroccoliButtonID - // RadioButton * kCauliflowerButtonID - // View kInnerContainerID - // ScrollView kScrollViewID - // View - // Link * kRosettaLinkID - // Link * kStupeurEtTremblementLinkID - // Link * kDinerGameLinkID - // Link * kRidiculeLinkID - // Link * kClosetLinkID - // Link * kVisitingLinkID - // Link * kAmelieLinkID - // Link * kJoyeuxNoelLinkID - // Link * kCampingLinkID - // Link * kBriceDeNiceLinkID - // Link * kTaxiLinkID - // Link * kAsterixLinkID - // NativeButton * kOKButtonID - // NativeButton * kCancelButtonID - // NativeButton * kHelpButtonID - // TabbedPane * kStyleContainerID - // View - // Checkbox * kBoldCheckBoxID - // Checkbox * kItalicCheckBoxID - // Checkbox * kUnderlinedCheckBoxID - // Link * kStyleHelpLinkID - // Textfield * kStyleTextEditID - // Other - // BorderView kSearchContainerID - // View - // Textfield * kSearchTextfieldID - // NativeButton * kSearchButtonID - // Link * kHelpLinkID - // View * kThumbnailContainerID - // NativeButton * kThumbnailStarID - // NativeButton * kThumbnailSuperStarID - - GetContentsView()->set_background( - Background::CreateSolidBackground(SK_ColorWHITE)); - - Checkbox* cb = new Checkbox(ASCIIToUTF16("This is a checkbox")); - GetContentsView()->AddChildView(cb); - // In this fast paced world, who really has time for non hard-coded layout? - cb->SetBounds(10, 10, 200, 20); - cb->set_id(kTopCheckBoxID); - - left_container_ = new PaneView(); - left_container_->SetBorder(Border::CreateSolidBorder(1, SK_ColorBLACK)); - left_container_->set_background( - Background::CreateSolidBackground(240, 240, 240)); - left_container_->set_id(kLeftContainerID); - GetContentsView()->AddChildView(left_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; - - Label* label = new Label(ASCIIToUTF16("Apple:")); - label->set_id(kAppleLabelID); - left_container_->AddChildView(label); - label->SetBounds(label_x, y, label_width, label_height); - - Textfield* text_field = new Textfield(); - text_field->set_id(kAppleTextfieldID); - left_container_->AddChildView(text_field); - text_field->SetBounds(label_x + label_width + 5, y, - text_field_width, label_height); - - y += label_height + gap_between_labels; - - label = new Label(ASCIIToUTF16("Orange:")); - label->set_id(kOrangeLabelID); - left_container_->AddChildView(label); - label->SetBounds(label_x, y, label_width, label_height); - - text_field = new Textfield(); - text_field->set_id(kOrangeTextfieldID); - left_container_->AddChildView(text_field); - text_field->SetBounds(label_x + label_width + 5, y, - text_field_width, label_height); - - y += label_height + gap_between_labels; - - label = new Label(ASCIIToUTF16("Banana:")); - label->set_id(kBananaLabelID); - left_container_->AddChildView(label); - label->SetBounds(label_x, y, label_width, label_height); - - text_field = new Textfield(); - text_field->set_id(kBananaTextfieldID); - left_container_->AddChildView(text_field); - text_field->SetBounds(label_x + label_width + 5, y, - text_field_width, label_height); - - y += label_height + gap_between_labels; - - label = new Label(ASCIIToUTF16("Kiwi:")); - label->set_id(kKiwiLabelID); - left_container_->AddChildView(label); - label->SetBounds(label_x, y, label_width, label_height); - - text_field = new Textfield(); - text_field->set_id(kKiwiTextfieldID); - left_container_->AddChildView(text_field); - text_field->SetBounds(label_x + label_width + 5, y, - text_field_width, label_height); - - y += label_height + gap_between_labels; - - LabelButton* button = new LabelButton(NULL, ASCIIToUTF16("Click me")); - button->SetStyle(Button::STYLE_BUTTON); - button->SetBounds(label_x, y + 10, 80, 30); - button->set_id(kFruitButtonID); - left_container_->AddChildView(button); - y += 40; - - cb = new Checkbox(ASCIIToUTF16("This is another check box")); - cb->SetBounds(label_x + label_width + 5, y, 180, 20); - cb->set_id(kFruitCheckBoxID); - left_container_->AddChildView(cb); - y += 20; - - Combobox* combobox = new Combobox(&combobox_model_); - combobox->SetBounds(label_x + label_width + 5, y, 150, 30); - combobox->set_id(kComboboxID); - left_container_->AddChildView(combobox); - - right_container_ = new PaneView(); - right_container_->SetBorder(Border::CreateSolidBorder(1, SK_ColorBLACK)); - right_container_->set_background( - Background::CreateSolidBackground(240, 240, 240)); - right_container_->set_id(kRightContainerID); - GetContentsView()->AddChildView(right_container_); - right_container_->SetBounds(270, 35, 300, 200); - - y = 10; - int radio_button_height = 18; - int gap_between_radio_buttons = 10; - RadioButton* radio_button = new RadioButton(ASCIIToUTF16("Asparagus"), 1); - radio_button->set_id(kAsparagusButtonID); - right_container_->AddChildView(radio_button); - radio_button->SetBounds(5, y, 70, radio_button_height); - radio_button->SetGroup(1); - y += radio_button_height + gap_between_radio_buttons; - radio_button = new RadioButton(ASCIIToUTF16("Broccoli"), 1); - radio_button->set_id(kBroccoliButtonID); - right_container_->AddChildView(radio_button); - radio_button->SetBounds(5, y, 70, radio_button_height); - radio_button->SetGroup(1); - RadioButton* radio_button_to_check = radio_button; - y += radio_button_height + gap_between_radio_buttons; - radio_button = new RadioButton(ASCIIToUTF16("Cauliflower"), 1); - radio_button->set_id(kCauliflowerButtonID); - right_container_->AddChildView(radio_button); - radio_button->SetBounds(5, y, 70, radio_button_height); - radio_button->SetGroup(1); - y += radio_button_height + gap_between_radio_buttons; - - View* inner_container = new View(); - inner_container->SetBorder(Border::CreateSolidBorder(1, SK_ColorBLACK)); - inner_container->set_background( - Background::CreateSolidBackground(230, 230, 230)); - inner_container->set_id(kInnerContainerID); - right_container_->AddChildView(inner_container); - inner_container->SetBounds(100, 10, 150, 180); - - ScrollView* scroll_view = new ScrollView(); - scroll_view->set_id(kScrollViewID); - inner_container->AddChildView(scroll_view); - scroll_view->SetBounds(1, 1, 148, 178); - - View* scroll_content = new View(); - scroll_content->SetBounds(0, 0, 200, 200); - scroll_content->set_background( - Background::CreateSolidBackground(200, 200, 200)); - scroll_view->SetContents(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[] = { - kRosettaLinkID, kStupeurEtTremblementLinkID, kDinerGameLinkID, - kRidiculeLinkID, kClosetLinkID, kVisitingLinkID, kAmelieLinkID, - kJoyeuxNoelLinkID, kCampingLinkID, kBriceDeNiceLinkID, - kTaxiLinkID, kAsterixLinkID - }; - - DCHECK(arraysize(kTitles) == arraysize(kIDs)); - - y = 5; - for (size_t i = 0; i < arraysize(kTitles); ++i) { - Link* link = new Link(ASCIIToUTF16(kTitles[i])); - link->SetHorizontalAlignment(gfx::ALIGN_LEFT); - link->set_id(kIDs[i]); - scroll_content->AddChildView(link); - link->SetBounds(5, y, 300, 15); - y += 15; - } - - y = 250; - int width = 60; - button = new LabelButton(NULL, ASCIIToUTF16("OK")); - button->SetStyle(Button::STYLE_BUTTON); - button->set_id(kOKButtonID); - button->SetIsDefault(true); - - GetContentsView()->AddChildView(button); - button->SetBounds(150, y, width, 30); - - button = new LabelButton(NULL, ASCIIToUTF16("Cancel")); - button->SetStyle(Button::STYLE_BUTTON); - button->set_id(kCancelButtonID); - GetContentsView()->AddChildView(button); - button->SetBounds(220, y, width, 30); - - button = new LabelButton(NULL, ASCIIToUTF16("Help")); - button->SetStyle(Button::STYLE_BUTTON); - button->set_id(kHelpButtonID); - GetContentsView()->AddChildView(button); - button->SetBounds(290, y, width, 30); - - y += 40; - - View* contents = NULL; - Link* link = NULL; - - // Left bottom box with style checkboxes. - contents = new View(); - contents->set_background(Background::CreateSolidBackground(SK_ColorWHITE)); - cb = new Checkbox(ASCIIToUTF16("Bold")); - contents->AddChildView(cb); - cb->SetBounds(10, 10, 50, 20); - cb->set_id(kBoldCheckBoxID); - - cb = new Checkbox(ASCIIToUTF16("Italic")); - contents->AddChildView(cb); - cb->SetBounds(70, 10, 50, 20); - cb->set_id(kItalicCheckBoxID); - - cb = new Checkbox(ASCIIToUTF16("Underlined")); - contents->AddChildView(cb); - cb->SetBounds(130, 10, 70, 20); - cb->set_id(kUnderlinedCheckBoxID); - - link = new Link(ASCIIToUTF16("Help")); - contents->AddChildView(link); - link->SetBounds(10, 35, 70, 10); - link->set_id(kStyleHelpLinkID); - - text_field = new Textfield(); - contents->AddChildView(text_field); - text_field->SetBounds(10, 50, 100, 20); - text_field->set_id(kStyleTextEditID); - - style_tab_ = new TabbedPane(); - style_tab_->set_id(kStyleContainerID); - GetContentsView()->AddChildView(style_tab_); - style_tab_->SetBounds(10, y, 210, 100); - style_tab_->AddTab(ASCIIToUTF16("Style"), contents); - style_tab_->AddTab(ASCIIToUTF16("Other"), new View()); - - // Right bottom box with search. - contents = new View(); - contents->set_background(Background::CreateSolidBackground(SK_ColorWHITE)); - text_field = new Textfield(); - contents->AddChildView(text_field); - text_field->SetBounds(10, 10, 100, 20); - text_field->set_id(kSearchTextfieldID); - - button = new LabelButton(NULL, ASCIIToUTF16("Search")); - button->SetStyle(Button::STYLE_BUTTON); - contents->AddChildView(button); - button->SetBounds(112, 5, 60, 30); - button->set_id(kSearchButtonID); - - link = new Link(ASCIIToUTF16("Help")); - link->SetHorizontalAlignment(gfx::ALIGN_LEFT); - link->set_id(kHelpLinkID); - contents->AddChildView(link); - link->SetBounds(175, 10, 30, 20); - - search_border_view_ = new BorderView(contents); - search_border_view_->set_id(kSearchContainerID); - - GetContentsView()->AddChildView(search_border_view_); - search_border_view_->SetBounds(300, y, 240, 50); - - y += 60; - - contents = new View(); - contents->SetFocusable(true); - contents->set_background(Background::CreateSolidBackground(SK_ColorBLUE)); - contents->set_id(kThumbnailContainerID); - button = new LabelButton(NULL, ASCIIToUTF16("Star")); - button->SetStyle(Button::STYLE_BUTTON); - contents->AddChildView(button); - button->SetBounds(5, 5, 50, 30); - button->set_id(kThumbnailStarID); - button = new LabelButton(NULL, ASCIIToUTF16("SuperStar")); - button->SetStyle(Button::STYLE_BUTTON); - contents->AddChildView(button); - button->SetBounds(60, 5, 100, 30); - button->set_id(kThumbnailSuperStarID); - - GetContentsView()->AddChildView(contents); - contents->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); -} - -TEST_F(FocusTraversalTest, NormalTraversal) { - const int kTraversalIDs[] = { kTopCheckBoxID, kAppleTextfieldID, - kOrangeTextfieldID, kBananaTextfieldID, kKiwiTextfieldID, - kFruitButtonID, kFruitCheckBoxID, kComboboxID, kBroccoliButtonID, - kRosettaLinkID, kStupeurEtTremblementLinkID, - kDinerGameLinkID, kRidiculeLinkID, kClosetLinkID, kVisitingLinkID, - kAmelieLinkID, kJoyeuxNoelLinkID, kCampingLinkID, kBriceDeNiceLinkID, - kTaxiLinkID, kAsterixLinkID, kOKButtonID, kCancelButtonID, kHelpButtonID, - kStyleContainerID, kBoldCheckBoxID, kItalicCheckBoxID, - kUnderlinedCheckBoxID, kStyleHelpLinkID, kStyleTextEditID, - kSearchTextfieldID, kSearchButtonID, kHelpLinkID, - kThumbnailContainerID, kThumbnailStarID, kThumbnailSuperStarID }; - - // Let's traverse the whole focus hierarchy (several times, to make sure it - // loops OK). - GetFocusManager()->ClearFocus(); - for (int i = 0; i < 3; ++i) { - for (size_t j = 0; j < arraysize(kTraversalIDs); j++) { - GetFocusManager()->AdvanceFocus(false); - View* focused_view = GetFocusManager()->GetFocusedView(); - EXPECT_TRUE(focused_view != NULL); - if (focused_view) - EXPECT_EQ(kTraversalIDs[j], focused_view->id()); - } - } - - // Let's traverse in reverse order. - GetFocusManager()->ClearFocus(); - for (int i = 0; i < 3; ++i) { - for (int j = arraysize(kTraversalIDs) - 1; j >= 0; --j) { - GetFocusManager()->AdvanceFocus(true); - View* focused_view = GetFocusManager()->GetFocusedView(); - EXPECT_TRUE(focused_view != NULL); - if (focused_view) - EXPECT_EQ(kTraversalIDs[j], focused_view->id()); - } - } -} - -TEST_F(FocusTraversalTest, TraversalWithNonEnabledViews) { - const int kDisabledIDs[] = { - kBananaTextfieldID, kFruitCheckBoxID, kComboboxID, kAsparagusButtonID, - kCauliflowerButtonID, kClosetLinkID, kVisitingLinkID, kBriceDeNiceLinkID, - kTaxiLinkID, kAsterixLinkID, kHelpButtonID, kBoldCheckBoxID, - kSearchTextfieldID, kHelpLinkID }; - - const int kTraversalIDs[] = { kTopCheckBoxID, kAppleTextfieldID, - kOrangeTextfieldID, kKiwiTextfieldID, kFruitButtonID, kBroccoliButtonID, - kRosettaLinkID, kStupeurEtTremblementLinkID, kDinerGameLinkID, - kRidiculeLinkID, kAmelieLinkID, kJoyeuxNoelLinkID, kCampingLinkID, - kOKButtonID, kCancelButtonID, kStyleContainerID, kItalicCheckBoxID, - kUnderlinedCheckBoxID, kStyleHelpLinkID, kStyleTextEditID, - kSearchButtonID, kThumbnailContainerID, kThumbnailStarID, - kThumbnailSuperStarID }; - - // Let's disable some views. - for (size_t i = 0; i < arraysize(kDisabledIDs); i++) { - View* v = FindViewByID(kDisabledIDs[i]); - ASSERT_TRUE(v != NULL); - v->SetEnabled(false); - } - - View* focused_view; - // Let's do one traversal (several times, to make sure it loops ok). - GetFocusManager()->ClearFocus(); - for (int i = 0; i < 3; ++i) { - for (size_t j = 0; j < arraysize(kTraversalIDs); j++) { - GetFocusManager()->AdvanceFocus(false); - focused_view = GetFocusManager()->GetFocusedView(); - EXPECT_TRUE(focused_view != NULL); - if (focused_view) - EXPECT_EQ(kTraversalIDs[j], focused_view->id()); - } - } - - // Same thing in reverse. - GetFocusManager()->ClearFocus(); - for (int i = 0; i < 3; ++i) { - for (int j = arraysize(kTraversalIDs) - 1; j >= 0; --j) { - GetFocusManager()->AdvanceFocus(true); - focused_view = GetFocusManager()->GetFocusedView(); - EXPECT_TRUE(focused_view != NULL); - if (focused_view) - EXPECT_EQ(kTraversalIDs[j], focused_view->id()); - } - } -} - -TEST_F(FocusTraversalTest, TraversalWithInvisibleViews) { - const int kInvisibleIDs[] = { kTopCheckBoxID, kOKButtonID, - kThumbnailContainerID }; - - const int kTraversalIDs[] = { kAppleTextfieldID, kOrangeTextfieldID, - kBananaTextfieldID, kKiwiTextfieldID, kFruitButtonID, kFruitCheckBoxID, - kComboboxID, kBroccoliButtonID, kRosettaLinkID, - kStupeurEtTremblementLinkID, kDinerGameLinkID, kRidiculeLinkID, - kClosetLinkID, kVisitingLinkID, kAmelieLinkID, kJoyeuxNoelLinkID, - kCampingLinkID, kBriceDeNiceLinkID, kTaxiLinkID, kAsterixLinkID, - kCancelButtonID, kHelpButtonID, kStyleContainerID, kBoldCheckBoxID, - kItalicCheckBoxID, kUnderlinedCheckBoxID, kStyleHelpLinkID, - kStyleTextEditID, kSearchTextfieldID, kSearchButtonID, kHelpLinkID }; - - - // Let's make some views invisible. - for (size_t i = 0; i < arraysize(kInvisibleIDs); i++) { - View* v = FindViewByID(kInvisibleIDs[i]); - ASSERT_TRUE(v != NULL); - v->SetVisible(false); - } - - View* focused_view; - // Let's do one traversal (several times, to make sure it loops ok). - GetFocusManager()->ClearFocus(); - for (int i = 0; i < 3; ++i) { - for (size_t j = 0; j < arraysize(kTraversalIDs); j++) { - GetFocusManager()->AdvanceFocus(false); - focused_view = GetFocusManager()->GetFocusedView(); - EXPECT_TRUE(focused_view != NULL); - if (focused_view) - EXPECT_EQ(kTraversalIDs[j], focused_view->id()); - } - } - - // Same thing in reverse. - GetFocusManager()->ClearFocus(); - for (int i = 0; i < 3; ++i) { - for (int j = arraysize(kTraversalIDs) - 1; j >= 0; --j) { - GetFocusManager()->AdvanceFocus(true); - focused_view = GetFocusManager()->GetFocusedView(); - EXPECT_TRUE(focused_view != NULL); - if (focused_view) - EXPECT_EQ(kTraversalIDs[j], focused_view->id()); - } - } -} - -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[] = { - kAppleTextfieldID, - kOrangeTextfieldID, kBananaTextfieldID, kKiwiTextfieldID, - kFruitButtonID, kFruitCheckBoxID, kComboboxID }; - - FocusSearch focus_search_left(left_container_, true, false); - left_container_->EnablePaneFocus(&focus_search_left); - FindViewByID(kComboboxID)->RequestFocus(); - - // Traverse the focus hierarchy within the pane several times. - for (int i = 0; i < 3; ++i) { - for (size_t j = 0; j < arraysize(kLeftTraversalIDs); j++) { - GetFocusManager()->AdvanceFocus(false); - View* focused_view = GetFocusManager()->GetFocusedView(); - EXPECT_TRUE(focused_view != NULL); - if (focused_view) - EXPECT_EQ(kLeftTraversalIDs[j], focused_view->id()); - } - } - - // Traverse in reverse order. - FindViewByID(kAppleTextfieldID)->RequestFocus(); - for (int i = 0; i < 3; ++i) { - for (int j = arraysize(kLeftTraversalIDs) - 1; j >= 0; --j) { - GetFocusManager()->AdvanceFocus(true); - View* focused_view = GetFocusManager()->GetFocusedView(); - EXPECT_TRUE(focused_view != NULL); - if (focused_view) - EXPECT_EQ(kLeftTraversalIDs[j], focused_view->id()); - } - } - - // 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[] = { - kBroccoliButtonID, kDinerGameLinkID, kRidiculeLinkID, - kClosetLinkID, kVisitingLinkID, kAmelieLinkID, kJoyeuxNoelLinkID, - kCampingLinkID, kBriceDeNiceLinkID, kTaxiLinkID, kAsterixLinkID }; - - FocusSearch focus_search_right(right_container_, true, true); - right_container_->EnablePaneFocus(&focus_search_right); - FindViewByID(kRosettaLinkID)->SetFocusable(false); - FindViewByID(kStupeurEtTremblementLinkID)->SetFocusable(false); - FindViewByID(kDinerGameLinkID)->SetAccessibilityFocusable(true); - FindViewByID(kDinerGameLinkID)->SetFocusable(false); - FindViewByID(kAsterixLinkID)->RequestFocus(); - - // Traverse the focus hierarchy within the pane several times. - for (int i = 0; i < 3; ++i) { - for (size_t j = 0; j < arraysize(kRightTraversalIDs); j++) { - GetFocusManager()->AdvanceFocus(false); - View* focused_view = GetFocusManager()->GetFocusedView(); - EXPECT_TRUE(focused_view != NULL); - if (focused_view) - EXPECT_EQ(kRightTraversalIDs[j], focused_view->id()); - } - } - - // Traverse in reverse order. - FindViewByID(kBroccoliButtonID)->RequestFocus(); - for (int i = 0; i < 3; ++i) { - for (int j = arraysize(kRightTraversalIDs) - 1; j >= 0; --j) { - GetFocusManager()->AdvanceFocus(true); - View* focused_view = GetFocusManager()->GetFocusedView(); - EXPECT_TRUE(focused_view != NULL); - if (focused_view) - EXPECT_EQ(kRightTraversalIDs[j], focused_view->id()); - } - } -} - -} // namespace views
diff --git a/ui/views/focus/view_storage.cc b/ui/views/focus/view_storage.cc deleted file mode 100644 index 0c7f170..0000000 --- a/ui/views/focus/view_storage.cc +++ /dev/null
@@ -1,116 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/focus/view_storage.h" - -#include <algorithm> - -#include "base/logging.h" -#include "base/memory/singleton.h" -#include "base/stl_util.h" - -namespace views { - -// static -ViewStorage* ViewStorage::GetInstance() { - return Singleton<ViewStorage>::get(); -} - -ViewStorage::ViewStorage() : view_storage_next_id_(0) { -} - -ViewStorage::~ViewStorage() { - STLDeleteContainerPairSecondPointers(view_to_ids_.begin(), - view_to_ids_.end()); -} - -int ViewStorage::CreateStorageID() { - return view_storage_next_id_++; -} - -void ViewStorage::StoreView(int storage_id, View* view) { - DCHECK(view); - std::map<int, View*>::iterator iter = id_to_view_.find(storage_id); - - if (iter != id_to_view_.end()) { - NOTREACHED(); - RemoveView(storage_id); - } - - id_to_view_[storage_id] = view; - - std::vector<int>* ids = NULL; - std::map<View*, std::vector<int>*>::iterator id_iter = - view_to_ids_.find(view); - if (id_iter == view_to_ids_.end()) { - ids = new std::vector<int>(); - view_to_ids_[view] = ids; - } else { - ids = id_iter->second; - } - ids->push_back(storage_id); -} - -View* ViewStorage::RetrieveView(int storage_id) { - std::map<int, View*>::iterator iter = id_to_view_.find(storage_id); - if (iter == id_to_view_.end()) - return NULL; - return iter->second; -} - -void ViewStorage::RemoveView(int storage_id) { - EraseView(storage_id, false); -} - -void ViewStorage::ViewRemoved(View* removed) { - // Let's first retrieve the ids for that view. - std::map<View*, std::vector<int>*>::iterator ids_iter = - view_to_ids_.find(removed); - - if (ids_iter == view_to_ids_.end()) { - // That view is not in the view storage. - return; - } - - std::vector<int>* ids = ids_iter->second; - DCHECK(!ids->empty()); - EraseView((*ids)[0], true); -} - -void ViewStorage::EraseView(int storage_id, bool remove_all_ids) { - // Remove the view from id_to_view_location_. - std::map<int, View*>::iterator view_iter = id_to_view_.find(storage_id); - if (view_iter == id_to_view_.end()) - return; - - View* view = view_iter->second; - id_to_view_.erase(view_iter); - - // Also update view_to_ids_. - std::map<View*, std::vector<int>*>::iterator ids_iter = - view_to_ids_.find(view); - DCHECK(ids_iter != view_to_ids_.end()); - std::vector<int>* ids = ids_iter->second; - - if (remove_all_ids) { - for (size_t i = 0; i < ids->size(); ++i) { - view_iter = id_to_view_.find((*ids)[i]); - if (view_iter != id_to_view_.end()) - id_to_view_.erase(view_iter); - } - ids->clear(); - } else { - std::vector<int>::iterator id_iter = - std::find(ids->begin(), ids->end(), storage_id); - DCHECK(id_iter != ids->end()); - ids->erase(id_iter); - } - - if (ids->empty()) { - delete ids; - view_to_ids_.erase(ids_iter); - } -} - -} // namespace views
diff --git a/ui/views/focus/view_storage.h b/ui/views/focus/view_storage.h deleted file mode 100644 index 5e36f3c..0000000 --- a/ui/views/focus/view_storage.h +++ /dev/null
@@ -1,75 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_FOCUS_VIEW_STORAGE_H_ -#define UI_VIEWS_FOCUS_VIEW_STORAGE_H_ - -#include <map> -#include <vector> - -#include "base/basictypes.h" -#include "ui/views/views_export.h" - -template <typename T> struct DefaultSingletonTraits; - -// This class is a simple storage place for storing/retrieving views. It is -// used for example in the FocusManager to store/restore focused views when the -// main window becomes active/inactive. -// It automatically removes a view from the storage if the view is removed from -// the tree hierarchy or when the view is destroyed, which ever comes first. -// -// To use it, you first need to create a view storage id that can then be used -// to store/retrieve views. - -namespace views { -class View; - -class VIEWS_EXPORT ViewStorage { - public: - // Returns the global ViewStorage instance. - // It is guaranted to be non NULL. - static ViewStorage* GetInstance(); - - // Returns a unique storage id that can be used to store/retrieve views. - int CreateStorageID(); - - // Associates |view| with the specified |storage_id|. - void StoreView(int storage_id, View* view); - - // Returns the view associated with |storage_id| if any, NULL otherwise. - View* RetrieveView(int storage_id); - - // Removes the view associated with |storage_id| if any. - void RemoveView(int storage_id); - - // Notifies the ViewStorage that a view was removed from its parent somewhere. - void ViewRemoved(View* removed); - - size_t view_count() const { return view_to_ids_.size(); } - - private: - friend struct DefaultSingletonTraits<ViewStorage>; - - ViewStorage(); - ~ViewStorage(); - - // Removes the view associated with |storage_id|. If |remove_all_ids| is true, - // all other mapping pointing to the same view are removed as well. - void EraseView(int storage_id, bool remove_all_ids); - - // Next id for the view storage. - int view_storage_next_id_; - - // The association id to View used for the view storage. - std::map<int, View*> id_to_view_; - - // Association View to id, used to speed up view notification removal. - std::map<View*, std::vector<int>*> view_to_ids_; - - DISALLOW_COPY_AND_ASSIGN(ViewStorage); -}; - -} // namespace views - -#endif // UI_VIEWS_FOCUS_VIEW_STORAGE_H_
diff --git a/ui/views/focus/widget_focus_manager.cc b/ui/views/focus/widget_focus_manager.cc deleted file mode 100644 index d50d490..0000000 --- a/ui/views/focus/widget_focus_manager.cc +++ /dev/null
@@ -1,50 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/focus/widget_focus_manager.h" - -#include "base/memory/singleton.h" - -namespace views { - -// WidgetFocusManager ---------------------------------------------------------- - -// static -WidgetFocusManager* WidgetFocusManager::GetInstance() { - return Singleton<WidgetFocusManager>::get(); -} - -void WidgetFocusManager::AddFocusChangeListener( - WidgetFocusChangeListener* listener) { - focus_change_listeners_.AddObserver(listener); -} - -void WidgetFocusManager::RemoveFocusChangeListener( - WidgetFocusChangeListener* listener) { - focus_change_listeners_.RemoveObserver(listener); -} - -void WidgetFocusManager::OnWidgetFocusEvent(gfx::NativeView focused_before, - gfx::NativeView focused_now) { - if (enabled_ && focused_before != focused_now) { - FOR_EACH_OBSERVER(WidgetFocusChangeListener, focus_change_listeners_, - OnNativeFocusChange(focused_before, focused_now)); - } -} - -WidgetFocusManager::WidgetFocusManager() : enabled_(true) {} - -WidgetFocusManager::~WidgetFocusManager() {} - -// AutoNativeNotificationDisabler ---------------------------------------------- - -AutoNativeNotificationDisabler::AutoNativeNotificationDisabler() { - WidgetFocusManager::GetInstance()->DisableNotifications(); -} - -AutoNativeNotificationDisabler::~AutoNativeNotificationDisabler() { - WidgetFocusManager::GetInstance()->EnableNotifications(); -} - -} // namespace views
diff --git a/ui/views/focus/widget_focus_manager.h b/ui/views/focus/widget_focus_manager.h deleted file mode 100644 index 6d2036c..0000000 --- a/ui/views/focus/widget_focus_manager.h +++ /dev/null
@@ -1,81 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_FOCUS_WIDGET_FOCUS_MANAGER_H_ -#define UI_VIEWS_FOCUS_WIDGET_FOCUS_MANAGER_H_ - -#include "base/basictypes.h" -#include "base/observer_list.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/views/views_export.h" - -template <typename T> struct DefaultSingletonTraits; - -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 OnNativeFocusChange(gfx::NativeView focused_before, - gfx::NativeView focused_now) = 0; - - protected: - virtual ~WidgetFocusChangeListener() {} -}; - -class VIEWS_EXPORT WidgetFocusManager { - public: - // Returns the singleton instance. - static WidgetFocusManager* GetInstance(); - - // Adds/removes a WidgetFocusChangeListener |listener| to the set of - // active listeners. - void AddFocusChangeListener(WidgetFocusChangeListener* listener); - void RemoveFocusChangeListener(WidgetFocusChangeListener* listener); - - // To be called when native-focus shifts from |focused_before| to - // |focused_now|. - // TODO(port) : Invocations to this routine are only implemented for - // the Win32 platform. Calls need to be placed appropriately for - // non-Windows environments. - void OnWidgetFocusEvent(gfx::NativeView focused_before, - gfx::NativeView focused_now); - - // Enable/Disable notification of registered listeners during calls - // to OnWidgetFocusEvent. Used to prevent unwanted focus changes from - // propagating notifications. - void EnableNotifications() { enabled_ = true; } - void DisableNotifications() { enabled_ = false; } - - private: - friend struct DefaultSingletonTraits<WidgetFocusManager>; - - WidgetFocusManager(); - ~WidgetFocusManager(); - - ObserverList<WidgetFocusChangeListener> focus_change_listeners_; - - bool enabled_; - - DISALLOW_COPY_AND_ASSIGN(WidgetFocusManager); -}; - -// A basic helper class that is used to disable native focus change -// notifications within a scope. -class VIEWS_EXPORT AutoNativeNotificationDisabler { - public: - AutoNativeNotificationDisabler(); - ~AutoNativeNotificationDisabler(); - - private: - DISALLOW_COPY_AND_ASSIGN(AutoNativeNotificationDisabler); -}; - -} // namespace views - -#endif // UI_VIEWS_FOCUS_WIDGET_FOCUS_MANAGER_H_
diff --git a/ui/views/ime/OWNERS b/ui/views/ime/OWNERS deleted file mode 100644 index 9f6409a..0000000 --- a/ui/views/ime/OWNERS +++ /dev/null
@@ -1,6 +0,0 @@ -# primary reviewer -yukishiino@chromium.org - -# backup reviewers. -mukai@chromium.org -nona@chromium.org
diff --git a/ui/views/ime/input_method.h b/ui/views/ime/input_method.h deleted file mode 100644 index ffb5ae9..0000000 --- a/ui/views/ime/input_method.h +++ /dev/null
@@ -1,128 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_IME_INPUT_METHOD_H_ -#define UI_VIEWS_IME_INPUT_METHOD_H_ - -#include <string> - -#include "base/basictypes.h" -#include "base/event_types.h" -#include "base/i18n/rtl.h" -#include "ui/base/ime/text_input_type.h" -#include "ui/views/views_export.h" - -namespace ui { -class KeyEvent; -class TextInputClient; -} // namespace ui - -namespace views { - -namespace internal { -class InputMethodDelegate; -} // namespace internal - -class View; -class Widget; - -// An interface implemented by an object that encapsulates a native input method -// service provided by the underlying operation system. Input method services -// are typically bound to individual native windows (HWND, aura::Window, etc.). -// In Views, only the top-level Widgets get keyboard focus, so this API is -// designed to be bound to top-level Widgets. -class VIEWS_EXPORT InputMethod { - public: - -#if defined(OS_WIN) - typedef LRESULT NativeEventResult; -#else - typedef int32 NativeEventResult; -#endif - - virtual ~InputMethod() {} - - // Sets the delegate used by this InputMethod instance. - // This should only be called by the owner Widget or testing code. - virtual void SetDelegate(internal::InputMethodDelegate* delegate) = 0; - - // Initialize the InputMethod object and attach it to the given |widget|. - // The |widget| must already be initialized. - virtual void Init(Widget* widget) = 0; - - // Called when the top-level Widget gains or loses keyboard focus. - // These should only be called by the Widget that owns this InputMethod. - virtual void OnFocus() = 0; - virtual void OnBlur() = 0; - - // Called when the focused window receives native IME messages that are not - // translated into other predefined event callbacks. Currently this method is - // used only for IME functionalities specific to Windows. - // TODO(ime): Break down these messages into platform-neutral methods. - virtual bool OnUntranslatedIMEMessage(const base::NativeEvent& event, - NativeEventResult* result) = 0; - - // Dispatch a key event to the input method. The key event will be dispatched - // back to the caller via InputMethodDelegate::DispatchKeyEventPostIME(), once - // it has been processed by the input method. It should only be called by the - // top-level Widget that owns this InputMethod instance, or other related - // platform-specific code, such as a message dispatcher. - virtual void DispatchKeyEvent(const ui::KeyEvent& key) = 0; - - // Called by the focused |view| whenever its text input type has changed. - // Before calling this method, the focused |view| must confirm or clear any - // existing composition text and call InputMethod::CancelComposition() when - // necessary. This method has no effect if |view| is not focused. - virtual void OnTextInputTypeChanged(View* view) = 0; - - // Called by the focused |view| whenever its caret bounds have changed. - // This method has no effect if |view| is not focused. - virtual void OnCaretBoundsChanged(View* view) = 0; - - // Called by the focused |view| to cancel the ongoing composition session. - // This method has no effect if |view| is not focused. - virtual void CancelComposition(View* view) = 0; - - // Called by the focused client whenever its input locale is changed. - // This method is currently used only on Windows. - // This method does not take a parameter of View for historical reasons. - // TODO(ime): Consider to take a parameter of View. - virtual void OnInputLocaleChanged() = 0; - - // Returns the locale of current keyboard layout or input method, as a BCP-47 - // tag, or an empty string if the input method cannot provide it. - virtual std::string GetInputLocale() = 0; - - // Returns true if the input method is ready to process keyboard events and - // generate composition or text results. It is not necessary to notify - // inactive input methods of caret bounds or text input type changes. - // Note: TextInputClient::InsertChar() may be called to send input to the text - // input client even if the input method is not active. - virtual bool IsActive() = 0; - - // Returns the focused text input client, or NULL if the Widget is not active, - // has no focused View, or if the focused View does not support text input. - virtual ui::TextInputClient* GetTextInputClient() const = 0; - - // Gets the text input type of the focused text input client. Returns - // ui::TEXT_INPUT_TYPE_NONE if there is no focused text input client. - virtual ui::TextInputType GetTextInputType() const = 0; - - // Returns true if we know for sure that a candidate window (or IME suggest, - // etc.) is open. Returns false if no popup window is open or the detection - // of IME popups is not supported. - virtual bool IsCandidatePopupOpen() const = 0; - - // Displays an on screen keyboard if enabled. - virtual void ShowImeIfNeeded() = 0; - - // Returns true if the input method is a mock instance used for testing. - virtual bool IsMock() const = 0; - - // TODO(suzhe): Support mouse/touch event. -}; - -} // namespace views - -#endif // UI_VIEWS_IME_INPUT_METHOD_H_
diff --git a/ui/views/ime/input_method_base.cc b/ui/views/ime/input_method_base.cc deleted file mode 100644 index 784746b..0000000 --- a/ui/views/ime/input_method_base.cc +++ /dev/null
@@ -1,108 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/ime/input_method_base.h" - -#include "base/logging.h" -#include "ui/base/ime/text_input_client.h" -#include "ui/events/event.h" -#include "ui/views/view.h" -#include "ui/views/widget/widget.h" - -namespace views { - -InputMethodBase::InputMethodBase() : delegate_(NULL), widget_(NULL) {} - -InputMethodBase::~InputMethodBase() { - DetachFromWidget(); -} - -void InputMethodBase::SetDelegate(internal::InputMethodDelegate* delegate) { - DCHECK(delegate); - delegate_ = delegate; -} - -void InputMethodBase::Init(Widget* widget) { - DCHECK(widget); - DCHECK(widget->GetFocusManager()); - DCHECK(!widget_) << "The input method is already initialized."; - - widget_ = widget; - // Alert the InputMethod of the Widget's currently focused view. - View* focused = widget->GetFocusManager()->GetFocusedView(); - if (focused) - OnWillChangeFocus(NULL, focused); - widget->GetFocusManager()->AddFocusChangeListener(this); -} - -views::View* InputMethodBase::GetFocusedView() const { - return widget_ ? widget_->GetFocusManager()->GetFocusedView() : NULL; -} - -void InputMethodBase::OnTextInputTypeChanged(View* view) {} - -ui::TextInputClient* InputMethodBase::GetTextInputClient() const { - return (widget_ && widget_->IsActive() && GetFocusedView()) ? - GetFocusedView()->GetTextInputClient() : NULL; -} - -ui::TextInputType InputMethodBase::GetTextInputType() const { - ui::TextInputClient* client = GetTextInputClient(); - return client ? client->GetTextInputType() : ui::TEXT_INPUT_TYPE_NONE; -} - -bool InputMethodBase::IsMock() const { - return false; -} - -void InputMethodBase::OnWillChangeFocus(View* focused_before, View* focused) {} - -void InputMethodBase::OnDidChangeFocus(View* focused_before, View* focused) {} - -bool InputMethodBase::IsViewFocused(View* view) const { - return widget_ && widget_->IsActive() && view && GetFocusedView() == view; -} - -bool InputMethodBase::IsTextInputTypeNone() const { - return GetTextInputType() == ui::TEXT_INPUT_TYPE_NONE; -} - -void InputMethodBase::OnInputMethodChanged() const { - ui::TextInputClient* client = GetTextInputClient(); - if (client && client->GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE) - client->OnInputMethodChanged(); -} - -void InputMethodBase::DispatchKeyEventPostIME(const ui::KeyEvent& key) const { - if (delegate_) - delegate_->DispatchKeyEventPostIME(key); -} - -bool InputMethodBase::GetCaretBoundsInWidget(gfx::Rect* rect) const { - DCHECK(rect); - ui::TextInputClient* client = GetTextInputClient(); - if (!client || client->GetTextInputType() == ui::TEXT_INPUT_TYPE_NONE) - return false; - - gfx::Rect caret_bounds = client->GetCaretBounds(); - gfx::Point caret_origin = caret_bounds.origin(); - View::ConvertPointFromScreen(GetFocusedView(), &caret_origin); - caret_bounds.set_origin(caret_origin); - *rect = GetFocusedView()->ConvertRectToWidget(caret_bounds); - - // Convert coordinates if the focused view is inside a child Widget. - if (GetFocusedView()->GetWidget() != widget_) - return Widget::ConvertRect(GetFocusedView()->GetWidget(), widget_, rect); - return true; -} - -void InputMethodBase::DetachFromWidget() { - if (!widget_) - return; - - widget_->GetFocusManager()->RemoveFocusChangeListener(this); - widget_ = NULL; -} - -} // namespace views
diff --git a/ui/views/ime/input_method_base.h b/ui/views/ime/input_method_base.h deleted file mode 100644 index 4410796..0000000 --- a/ui/views/ime/input_method_base.h +++ /dev/null
@@ -1,79 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_IME_INPUT_METHOD_BASE_H_ -#define UI_VIEWS_IME_INPUT_METHOD_BASE_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "ui/views/focus/focus_manager.h" -#include "ui/views/ime/input_method.h" -#include "ui/views/ime/input_method_delegate.h" - -namespace gfx { -class Rect; -} - -namespace ui { -class KeyEvent; -} - -namespace views { - -// A helper that provides functionality shared by InputMethod implementations. -class VIEWS_EXPORT InputMethodBase : public InputMethod, - public FocusChangeListener { - public: - InputMethodBase(); - virtual ~InputMethodBase(); - - // Overridden from InputMethod. - virtual void SetDelegate(internal::InputMethodDelegate* delegate) override; - virtual void Init(Widget* widget) override; - virtual void OnTextInputTypeChanged(View* view) override; - virtual ui::TextInputClient* GetTextInputClient() const override; - virtual ui::TextInputType GetTextInputType() const override; - virtual bool IsMock() const override; - - // Overridden from FocusChangeListener. - virtual void OnWillChangeFocus(View* focused_before, View* focused) override; - virtual void OnDidChangeFocus(View* focused_before, View* focused) override; - - protected: - internal::InputMethodDelegate* delegate() const { return delegate_; } - Widget* widget() const { return widget_; } - View* GetFocusedView() const; - - // Returns true only if the View is focused and its Widget is active. - bool IsViewFocused(View* view) const; - - // Returns true if there is no focused text input client or its type is none. - bool IsTextInputTypeNone() const; - - // Calls the focused text input client's OnInputMethodChanged() method. - // This has no effect if the text input type is ui::TEXT_INPUT_TYPE_NONE. - void OnInputMethodChanged() const; - - // Convenience method to call delegate_->DispatchKeyEventPostIME(). - void DispatchKeyEventPostIME(const ui::KeyEvent& key) const; - - // Gets the current text input client's caret bounds in Widget's coordinates. - // Returns false if the current text input client doesn't support text input. - bool GetCaretBoundsInWidget(gfx::Rect* rect) const; - - // Removes any state installed on |widget_| and NULLs it out. Use if the - // widget is in a state such that it should no longer be used (such as when - // this is in its destructor). - void DetachFromWidget(); - - private: - internal::InputMethodDelegate* delegate_; - Widget* widget_; - - DISALLOW_COPY_AND_ASSIGN(InputMethodBase); -}; - -} // namespace views - -#endif // UI_VIEWS_IME_INPUT_METHOD_BASE_H_
diff --git a/ui/views/ime/input_method_bridge.cc b/ui/views/ime/input_method_bridge.cc deleted file mode 100644 index 8e321f0..0000000 --- a/ui/views/ime/input_method_bridge.cc +++ /dev/null
@@ -1,348 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/ime/input_method_bridge.h" - -#include "ui/base/ime/input_method.h" -#include "ui/base/ime/input_method_observer.h" -#include "ui/events/event.h" -#include "ui/gfx/rect.h" -#include "ui/views/view.h" -#include "ui/views/widget/widget.h" - -namespace views { - -// InputMethodBridge::HostObserver class --------------------------------------- - -// An observer class for observing the host input method. When the host input -// method is destroyed, it will null out the |host_| field on the -// InputMethodBridge object. -class InputMethodBridge::HostObserver : public ui::InputMethodObserver { - public: - explicit HostObserver(InputMethodBridge* bridge); - virtual ~HostObserver(); - - virtual void OnTextInputTypeChanged( - const ui::TextInputClient* client) override {} - virtual void OnFocus() override {} - virtual void OnBlur() override {} - virtual void OnCaretBoundsChanged( - const ui::TextInputClient* client) override {} - virtual void OnTextInputStateChanged( - const ui::TextInputClient* client) override {} - virtual void OnInputMethodDestroyed( - const ui::InputMethod* input_method) override; - virtual void OnShowImeIfNeeded() override {} - - private: - InputMethodBridge* bridge_; - - DISALLOW_COPY_AND_ASSIGN(HostObserver); -}; - -InputMethodBridge::HostObserver::HostObserver(InputMethodBridge* bridge) - : bridge_(bridge) { - bridge_->host_->AddObserver(this); -} - -InputMethodBridge::HostObserver::~HostObserver() { - if (bridge_->host_) - bridge_->host_->RemoveObserver(this); -} - -void InputMethodBridge::HostObserver::OnInputMethodDestroyed( - const ui::InputMethod* input_method) { - DCHECK_EQ(bridge_->host_, input_method); - bridge_->host_->RemoveObserver(this); - bridge_->host_ = NULL; -} - -// InputMethodBridge class ----------------------------------------------------- - -InputMethodBridge::InputMethodBridge(internal::InputMethodDelegate* delegate, - ui::InputMethod* host, - bool shared_input_method) - : host_(host), - shared_input_method_(shared_input_method) { - DCHECK(host_); - SetDelegate(delegate); - - host_observer_.reset(new HostObserver(this)); -} - -InputMethodBridge::~InputMethodBridge() { - // By the time we get here it's very likely |widget_|'s NativeWidget has been - // destroyed. This means any calls to |widget_| that go to the NativeWidget, - // such as IsActive(), will crash. SetFocusedTextInputClient() may callback to - // this and go into |widget_|. NULL out |widget_| so we don't attempt to use - // it. - DetachFromWidget(); - - // Host input method might have been destroyed at this point. - if (host_) - host_->DetachTextInputClient(this); -} - -void InputMethodBridge::OnFocus() { - DCHECK(host_); - - // Direct the shared IME to send TextInputClient messages to |this| object. - if (shared_input_method_ || !host_->GetTextInputClient()) - host_->SetFocusedTextInputClient(this); - - // TODO(yusukes): We don't need to call OnTextInputTypeChanged() once we move - // text input type tracker code to ui::InputMethodBase. - if (GetFocusedView()) { - OnTextInputTypeChanged(GetFocusedView()); - OnCaretBoundsChanged(GetFocusedView()); - } -} - -void InputMethodBridge::OnBlur() { - DCHECK(host_); - - if (HasCompositionText()) { - ConfirmCompositionText(); - host_->CancelComposition(this); - } - - if (host_->GetTextInputClient() == this) - host_->SetFocusedTextInputClient(NULL); -} - -bool InputMethodBridge::OnUntranslatedIMEMessage(const base::NativeEvent& event, - NativeEventResult* result) { - DCHECK(host_); - - return host_->OnUntranslatedIMEMessage(event, result); -} - -void InputMethodBridge::DispatchKeyEvent(const ui::KeyEvent& key) { - DCHECK(key.type() == ui::ET_KEY_PRESSED || key.type() == ui::ET_KEY_RELEASED); - - // We can just dispatch the event here since the |key| is already processed by - // the system-wide IME. - DispatchKeyEventPostIME(key); -} - -void InputMethodBridge::OnTextInputTypeChanged(View* view) { - DCHECK(host_); - - if (IsViewFocused(view)) - host_->OnTextInputTypeChanged(this); - InputMethodBase::OnTextInputTypeChanged(view); -} - -void InputMethodBridge::OnCaretBoundsChanged(View* view) { - DCHECK(host_); - - if (IsViewFocused(view) && !IsTextInputTypeNone()) - host_->OnCaretBoundsChanged(this); -} - -void InputMethodBridge::CancelComposition(View* view) { - DCHECK(host_); - - if (IsViewFocused(view)) - host_->CancelComposition(this); -} - -void InputMethodBridge::OnInputLocaleChanged() { - DCHECK(host_); - - host_->OnInputLocaleChanged(); -} - -std::string InputMethodBridge::GetInputLocale() { - DCHECK(host_); - - return host_->GetInputLocale(); -} - -bool InputMethodBridge::IsActive() { - DCHECK(host_); - - return host_->IsActive(); -} - -bool InputMethodBridge::IsCandidatePopupOpen() const { - DCHECK(host_); - - return host_->IsCandidatePopupOpen(); -} - -void InputMethodBridge::ShowImeIfNeeded() { - DCHECK(host_); - host_->ShowImeIfNeeded(); -} - -// Overridden from TextInputClient. Forward an event from the system-wide IME -// to the text input |client|, which is e.g. views::Textfield. -void InputMethodBridge::SetCompositionText( - const ui::CompositionText& composition) { - TextInputClient* client = GetTextInputClient(); - if (client) - client->SetCompositionText(composition); -} - -void InputMethodBridge::ConfirmCompositionText() { - TextInputClient* client = GetTextInputClient(); - if (client) - client->ConfirmCompositionText(); -} - -void InputMethodBridge::ClearCompositionText() { - TextInputClient* client = GetTextInputClient(); - if (client) - client->ClearCompositionText(); -} - -void InputMethodBridge::InsertText(const base::string16& text) { - TextInputClient* client = GetTextInputClient(); - if (client) - client->InsertText(text); -} - -void InputMethodBridge::InsertChar(base::char16 ch, int flags) { - TextInputClient* client = GetTextInputClient(); - if (client) - client->InsertChar(ch, flags); -} - -gfx::NativeWindow InputMethodBridge::GetAttachedWindow() const { - TextInputClient* client = GetTextInputClient(); - return client ? - client->GetAttachedWindow() : static_cast<gfx::NativeWindow>(NULL); -} - -ui::TextInputType InputMethodBridge::GetTextInputType() const { - TextInputClient* client = GetTextInputClient(); - return client ? client->GetTextInputType() : ui::TEXT_INPUT_TYPE_NONE; -} - -ui::TextInputMode InputMethodBridge::GetTextInputMode() const { - TextInputClient* client = GetTextInputClient(); - return client ? client->GetTextInputMode() : ui::TEXT_INPUT_MODE_DEFAULT; -} - -bool InputMethodBridge::CanComposeInline() const { - TextInputClient* client = GetTextInputClient(); - return client ? client->CanComposeInline() : true; -} - -gfx::Rect InputMethodBridge::GetCaretBounds() const { - TextInputClient* client = GetTextInputClient(); - if (!client) - return gfx::Rect(); - - return client->GetCaretBounds(); -} - -bool InputMethodBridge::GetCompositionCharacterBounds(uint32 index, - gfx::Rect* rect) const { - DCHECK(rect); - TextInputClient* client = GetTextInputClient(); - if (!client) - return false; - - return client->GetCompositionCharacterBounds(index, rect); -} - -bool InputMethodBridge::HasCompositionText() const { - TextInputClient* client = GetTextInputClient(); - return client ? client->HasCompositionText() : false; -} - -bool InputMethodBridge::GetTextRange(gfx::Range* range) const { - TextInputClient* client = GetTextInputClient(); - return client ? client->GetTextRange(range) : false; -} - -bool InputMethodBridge::GetCompositionTextRange(gfx::Range* range) const { - TextInputClient* client = GetTextInputClient(); - return client ? client->GetCompositionTextRange(range) : false; -} - -bool InputMethodBridge::GetSelectionRange(gfx::Range* range) const { - TextInputClient* client = GetTextInputClient(); - return client ? client->GetSelectionRange(range) : false; -} - -bool InputMethodBridge::SetSelectionRange(const gfx::Range& range) { - TextInputClient* client = GetTextInputClient(); - return client ? client->SetSelectionRange(range) : false; -} - -bool InputMethodBridge::DeleteRange(const gfx::Range& range) { - TextInputClient* client = GetTextInputClient(); - return client ? client->DeleteRange(range) : false; -} - -bool InputMethodBridge::GetTextFromRange(const gfx::Range& range, - base::string16* text) const { - TextInputClient* client = GetTextInputClient(); - return client ? client->GetTextFromRange(range, text) : false; -} - -void InputMethodBridge::OnInputMethodChanged() { - TextInputClient* client = GetTextInputClient(); - if (client) - client->OnInputMethodChanged(); -} - -bool InputMethodBridge::ChangeTextDirectionAndLayoutAlignment( - base::i18n::TextDirection direction) { - TextInputClient* client = GetTextInputClient(); - return client ? - client->ChangeTextDirectionAndLayoutAlignment(direction) : false; -} - -void InputMethodBridge::ExtendSelectionAndDelete(size_t before, size_t after) { - TextInputClient* client = GetTextInputClient(); - if (client) - client->ExtendSelectionAndDelete(before, after); -} - -void InputMethodBridge::EnsureCaretInRect(const gfx::Rect& rect) { - TextInputClient* client = GetTextInputClient(); - if (client) - client->EnsureCaretInRect(rect); -} - -void InputMethodBridge::OnCandidateWindowShown() { -} - -void InputMethodBridge::OnCandidateWindowUpdated() { -} - -void InputMethodBridge::OnCandidateWindowHidden() { -} - -bool InputMethodBridge::IsEditingCommandEnabled(int command_id) { - return false; -} - -void InputMethodBridge::ExecuteEditingCommand(int command_id) { -} - -// Overridden from FocusChangeListener. -void InputMethodBridge::OnWillChangeFocus(View* focused_before, View* focused) { - if (HasCompositionText()) { - ConfirmCompositionText(); - CancelComposition(focused_before); - } -} - -void InputMethodBridge::OnDidChangeFocus(View* focused_before, View* focused) { - DCHECK_EQ(GetFocusedView(), focused); - OnTextInputTypeChanged(focused); - OnCaretBoundsChanged(focused); -} - -ui::InputMethod* InputMethodBridge::GetHostInputMethod() const { - return host_; -} - - -} // namespace views
diff --git a/ui/views/ime/input_method_bridge.h b/ui/views/ime/input_method_bridge.h deleted file mode 100644 index 43fb947..0000000 --- a/ui/views/ime/input_method_bridge.h +++ /dev/null
@@ -1,109 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_IME_INPUT_METHOD_BRIDGE_H_ -#define UI_VIEWS_IME_INPUT_METHOD_BRIDGE_H_ - -#include <string> - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "ui/base/ime/text_input_client.h" -#include "ui/gfx/rect.h" -#include "ui/views/ime/input_method_base.h" - -namespace ui { -class InputMethod; -} // namespace ui - -namespace views { - -class View; - -// A "bridge" InputMethod implementation for views top-level widgets, which just -// sends/receives IME related events to/from a system-wide ui::InputMethod -// object. -class InputMethodBridge : public InputMethodBase, - public ui::TextInputClient { - public: - // |shared_input_method| indicates if |host| is shared among other top level - // widgets. - InputMethodBridge(internal::InputMethodDelegate* delegate, - ui::InputMethod* host, - bool shared_input_method); - virtual ~InputMethodBridge(); - - // Overridden from InputMethod: - virtual void OnFocus() override; - virtual void OnBlur() override; - virtual bool OnUntranslatedIMEMessage(const base::NativeEvent& event, - NativeEventResult* result) override; - virtual void DispatchKeyEvent(const ui::KeyEvent& key) override; - virtual void OnTextInputTypeChanged(View* view) override; - virtual void OnCaretBoundsChanged(View* view) override; - virtual void CancelComposition(View* view) override; - virtual void OnInputLocaleChanged() override; - virtual std::string GetInputLocale() override; - virtual bool IsActive() override; - virtual bool IsCandidatePopupOpen() const override; - virtual void ShowImeIfNeeded() override; - - // Overridden from TextInputClient: - virtual void SetCompositionText( - const ui::CompositionText& composition) override; - virtual void ConfirmCompositionText() override; - virtual void ClearCompositionText() override; - virtual void InsertText(const base::string16& text) override; - virtual void InsertChar(base::char16 ch, int flags) override; - virtual gfx::NativeWindow GetAttachedWindow() const override; - virtual ui::TextInputType GetTextInputType() const override; - virtual ui::TextInputMode GetTextInputMode() const override; - virtual bool CanComposeInline() const override; - virtual gfx::Rect GetCaretBounds() const override; - virtual bool GetCompositionCharacterBounds(uint32 index, - gfx::Rect* rect) const override; - virtual bool HasCompositionText() const override; - virtual bool GetTextRange(gfx::Range* range) const override; - virtual bool GetCompositionTextRange(gfx::Range* range) const override; - virtual bool GetSelectionRange(gfx::Range* range) const override; - virtual bool SetSelectionRange(const gfx::Range& range) override; - virtual bool DeleteRange(const gfx::Range& range) override; - virtual bool GetTextFromRange(const gfx::Range& range, - base::string16* text) const override; - virtual void OnInputMethodChanged() override; - virtual bool ChangeTextDirectionAndLayoutAlignment( - base::i18n::TextDirection direction) override; - virtual void ExtendSelectionAndDelete(size_t before, size_t after) override; - virtual void EnsureCaretInRect(const gfx::Rect& rect) override; - virtual void OnCandidateWindowShown() override; - virtual void OnCandidateWindowUpdated() override; - virtual void OnCandidateWindowHidden() override; - virtual bool IsEditingCommandEnabled(int command_id) override; - virtual void ExecuteEditingCommand(int command_id) override; - - // Overridden from FocusChangeListener. - virtual void OnWillChangeFocus(View* focused_before, View* focused) override; - virtual void OnDidChangeFocus(View* focused_before, View* focused) override; - - ui::InputMethod* GetHostInputMethod() const; - - private: - class HostObserver; - - void UpdateViewFocusState(); - - ui::InputMethod* host_; - - // An observer observing the host input method for cases that the host input - // method is destroyed before this bridge input method. - scoped_ptr<HostObserver> host_observer_; - - const bool shared_input_method_; - - DISALLOW_COPY_AND_ASSIGN(InputMethodBridge); -}; - -} // namespace views - -#endif // UI_VIEWS_IME_INPUT_METHOD_BRIDGE_H_
diff --git a/ui/views/ime/input_method_bridge_unittest.cc b/ui/views/ime/input_method_bridge_unittest.cc deleted file mode 100644 index 64144cf..0000000 --- a/ui/views/ime/input_method_bridge_unittest.cc +++ /dev/null
@@ -1,50 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/client/aura_constants.h" -#include "ui/aura/window.h" -#include "ui/base/ime/dummy_input_method_delegate.h" -#include "ui/base/ime/input_method_minimal.h" -#include "ui/base/ime/text_input_client.h" -#include "ui/views/ime/input_method.h" -#include "ui/views/test/views_test_base.h" -#include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" -#include "ui/views/widget/native_widget_aura.h" -#include "ui/views/widget/widget.h" - -namespace views { - -typedef ViewsTestBase InputMethodBridgeTest; - -TEST_F(InputMethodBridgeTest, DestructTest) { - ui::internal::DummyInputMethodDelegate input_method_delegate; - ui::InputMethodMinimal input_method(&input_method_delegate); - - GetContext()->SetProperty(aura::client::kRootWindowInputMethodKey, - static_cast<ui::InputMethod*>(&input_method)); - - Widget* toplevel = new Widget; - Widget::InitParams toplevel_params = - CreateParams(Widget::InitParams::TYPE_WINDOW); - // |child| owns |native_widget|. - toplevel_params.native_widget = new DesktopNativeWidgetAura(toplevel); - toplevel->Init(toplevel_params); - - Widget* child = new Widget; - Widget::InitParams child_params = - CreateParams(Widget::InitParams::TYPE_POPUP); - child_params.parent = toplevel->GetNativeView(); - // |child| owns |native_widget|. - child_params.native_widget = new NativeWidgetAura(child); - child->Init(child_params); - - child->GetInputMethod()->OnFocus(); - - toplevel->CloseNow(); - - GetContext()->SetProperty(aura::client::kRootWindowInputMethodKey, - static_cast<ui::InputMethod*>(NULL)); -} - -} // namespace views
diff --git a/ui/views/ime/input_method_delegate.h b/ui/views/ime/input_method_delegate.h deleted file mode 100644 index 59bc9dc..0000000 --- a/ui/views/ime/input_method_delegate.h +++ /dev/null
@@ -1,31 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_IME_INPUT_METHOD_DELEGATE_H_ -#define UI_VIEWS_IME_INPUT_METHOD_DELEGATE_H_ - -#include "ui/views/views_export.h" - -namespace ui { -class KeyEvent; -} - -namespace views { - -namespace internal { - -// An interface implemented by the object that handles events sent back from an -// InputMethod implementation. -class VIEWS_EXPORT InputMethodDelegate { - public: - virtual ~InputMethodDelegate() {} - - // Dispatch a key event already processed by the input method. - virtual void DispatchKeyEventPostIME(const ui::KeyEvent& key) = 0; -}; - -} // namespace internal -} // namespace views - -#endif // UI_VIEWS_IME_INPUT_METHOD_DELEGATE_H_
diff --git a/ui/views/ime/mock_input_method.cc b/ui/views/ime/mock_input_method.cc deleted file mode 100644 index b7611da..0000000 --- a/ui/views/ime/mock_input_method.cc +++ /dev/null
@@ -1,192 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/ime/mock_input_method.h" - -#include "base/basictypes.h" -#include "base/logging.h" -#include "ui/base/ime/text_input_client.h" -#include "ui/events/event.h" -#include "ui/events/keycodes/keyboard_codes.h" -#include "ui/views/widget/widget.h" - -namespace views { - -MockInputMethod::MockInputMethod() - : composition_changed_(false), - focus_changed_(false), - untranslated_ime_message_called_(false), - text_input_type_changed_(false), - caret_bounds_changed_(false), - cancel_composition_called_(false), - input_locale_changed_(false), - locale_("en-US"), - active_(true) { -} - -MockInputMethod::MockInputMethod(internal::InputMethodDelegate* delegate) - : composition_changed_(false), - focus_changed_(false), - untranslated_ime_message_called_(false), - text_input_type_changed_(false), - caret_bounds_changed_(false), - cancel_composition_called_(false), - input_locale_changed_(false), - locale_("en-US"), - active_(true) { - SetDelegate(delegate); -} - -MockInputMethod::~MockInputMethod() { -} - -void MockInputMethod::Init(Widget* widget) { - InputMethodBase::Init(widget); -} - -void MockInputMethod::OnFocus() {} - -void MockInputMethod::OnBlur() {} - -bool MockInputMethod::OnUntranslatedIMEMessage( - const base::NativeEvent& event, - NativeEventResult* result) { - untranslated_ime_message_called_ = true; - if (result) - *result = InputMethod::NativeEventResult(); - return false; -} - -void MockInputMethod::DispatchKeyEvent(const ui::KeyEvent& key) { - bool handled = (composition_changed_ || result_text_.length()) && - !IsTextInputTypeNone(); - - ClearStates(); - if (handled) { - DCHECK(!key.is_char()); - ui::KeyEvent mock_key(ui::ET_KEY_PRESSED, - ui::VKEY_PROCESSKEY, - key.flags()); - DispatchKeyEventPostIME(mock_key); - } else { - DispatchKeyEventPostIME(key); - } - - if (focus_changed_) - return; - - ui::TextInputClient* client = GetTextInputClient(); - if (client) { - if (handled) { - if (result_text_.length()) - client->InsertText(result_text_); - if (composition_changed_) { - if (composition_.text.length()) - client->SetCompositionText(composition_); - else - client->ClearCompositionText(); - } - } else if (key.type() == ui::ET_KEY_PRESSED) { - base::char16 ch = key.GetCharacter(); - client->InsertChar(ch, key.flags()); - } - } - - ClearResult(); -} - -void MockInputMethod::OnTextInputTypeChanged(View* view) { - if (IsViewFocused(view)) - text_input_type_changed_ = true; - InputMethodBase::OnTextInputTypeChanged(view); -} - -void MockInputMethod::OnCaretBoundsChanged(View* view) { - if (IsViewFocused(view)) - caret_bounds_changed_ = true; -} - -void MockInputMethod::CancelComposition(View* view) { - if (IsViewFocused(view)) { - cancel_composition_called_ = true; - ClearResult(); - } -} - -void MockInputMethod::OnInputLocaleChanged() { - input_locale_changed_ = true; -} - -std::string MockInputMethod::GetInputLocale() { - return locale_; -} - -bool MockInputMethod::IsActive() { - return active_; -} - -bool MockInputMethod::IsCandidatePopupOpen() const { - return false; -} - -void MockInputMethod::ShowImeIfNeeded() { -} - -bool MockInputMethod::IsMock() const { - return true; -} - -void MockInputMethod::OnWillChangeFocus(View* focused_before, View* focused) { - ui::TextInputClient* client = GetTextInputClient(); - if (client && client->HasCompositionText()) - client->ConfirmCompositionText(); - focus_changed_ = true; - ClearResult(); -} - -void MockInputMethod::Clear() { - ClearStates(); - ClearResult(); -} - -void MockInputMethod::SetCompositionTextForNextKey( - const ui::CompositionText& composition) { - composition_changed_ = true; - composition_ = composition; -} - -void MockInputMethod::SetResultTextForNextKey(const base::string16& result) { - result_text_ = result; -} - -void MockInputMethod::SetInputLocale(const std::string& locale) { - if (locale_ != locale) { - locale_ = locale; - OnInputMethodChanged(); - } -} - -void MockInputMethod::SetActive(bool active) { - if (active_ != active) { - active_ = active; - OnInputMethodChanged(); - } -} - -void MockInputMethod::ClearStates() { - focus_changed_ = false; - untranslated_ime_message_called_ = false; - text_input_type_changed_ = false; - caret_bounds_changed_ = false; - cancel_composition_called_ = false; - input_locale_changed_ = false; -} - -void MockInputMethod::ClearResult() { - composition_.Clear(); - composition_changed_ = false; - result_text_.clear(); -} - -} // namespace views
diff --git a/ui/views/ime/mock_input_method.h b/ui/views/ime/mock_input_method.h deleted file mode 100644 index e55c4df..0000000 --- a/ui/views/ime/mock_input_method.h +++ /dev/null
@@ -1,97 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_IME_MOCK_INPUT_METHOD_H_ -#define UI_VIEWS_IME_MOCK_INPUT_METHOD_H_ - -#include <string> - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "ui/base/ime/composition_text.h" -#include "ui/views/ime/input_method_base.h" -#include "ui/views/view.h" - -namespace views { - -// A mock InputMethod implementation for testing purpose. -class VIEWS_EXPORT MockInputMethod : public InputMethodBase { - public: - MockInputMethod(); - explicit MockInputMethod(internal::InputMethodDelegate* delegate); - virtual ~MockInputMethod(); - - // Overridden from InputMethod: - virtual void Init(Widget* widget) override; - virtual void OnFocus() override; - virtual void OnBlur() override; - virtual bool OnUntranslatedIMEMessage(const base::NativeEvent& event, - NativeEventResult* result) override; - virtual void DispatchKeyEvent(const ui::KeyEvent& key) override; - virtual void OnTextInputTypeChanged(View* view) override; - virtual void OnCaretBoundsChanged(View* view) override; - virtual void CancelComposition(View* view) override; - virtual void OnInputLocaleChanged() override; - virtual std::string GetInputLocale() override; - virtual bool IsActive() override; - virtual bool IsCandidatePopupOpen() const override; - virtual void ShowImeIfNeeded() override; - virtual bool IsMock() const override; - - bool focus_changed() const { return focus_changed_; } - bool untranslated_ime_message_called() const { - return untranslated_ime_message_called_; - } - bool text_input_type_changed() const { return text_input_type_changed_; } - bool caret_bounds_changed() const { return caret_bounds_changed_; } - bool cancel_composition_called() const { return cancel_composition_called_; } - bool input_locale_changed() const { return input_locale_changed_; } - - // Clears all internal states and result. - void Clear(); - - void SetCompositionTextForNextKey(const ui::CompositionText& composition); - void SetResultTextForNextKey(const base::string16& result); - - void SetInputLocale(const std::string& locale); - void SetActive(bool active); - - private: - // Overridden from InputMethodBase. - virtual void OnWillChangeFocus(View* focused_before, View* focused) override; - - // Clears boolean states defined below. - void ClearStates(); - - // Clears only composition information and result text. - void ClearResult(); - - // Composition information for the next key event. It'll be cleared - // automatically after dispatching the next key event. - ui::CompositionText composition_; - bool composition_changed_; - - // Result text for the next key event. It'll be cleared automatically after - // dispatching the next key event. - base::string16 result_text_; - - // Record call state of corresponding methods. They will be set to false - // automatically before dispatching a key event. - bool focus_changed_; - bool untranslated_ime_message_called_; - bool text_input_type_changed_; - bool caret_bounds_changed_; - bool cancel_composition_called_; - bool input_locale_changed_; - - // To mock corresponding input method prooperties. - std::string locale_; - bool active_; - - DISALLOW_COPY_AND_ASSIGN(MockInputMethod); -}; - -} // namespace views - -#endif // UI_VIEWS_IME_MOCK_INPUT_METHOD_H_
diff --git a/ui/views/ime/null_input_method.cc b/ui/views/ime/null_input_method.cc deleted file mode 100644 index 666d6cf..0000000 --- a/ui/views/ime/null_input_method.cc +++ /dev/null
@@ -1,62 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/ime/null_input_method.h" - -namespace views { - -NullInputMethod::NullInputMethod() {} - -void NullInputMethod::SetDelegate( - internal::InputMethodDelegate* /* delegate */) {} - -void NullInputMethod::Init(Widget* /* widget */) {} - -void NullInputMethod::OnFocus() {} - -void NullInputMethod::OnBlur() {} - -bool NullInputMethod::OnUntranslatedIMEMessage( - const base::NativeEvent& /* event */, - NativeEventResult* /* result */) { - return false; -} - -void NullInputMethod::DispatchKeyEvent(const ui::KeyEvent& /* key */) {} - -void NullInputMethod::OnTextInputTypeChanged(View* /* view */) {} - -void NullInputMethod::OnCaretBoundsChanged(View* /* view */) {} - -void NullInputMethod::CancelComposition(View* /* view */) {} - -void NullInputMethod::OnInputLocaleChanged() {} - -std::string NullInputMethod::GetInputLocale() { - return std::string(); -} - -bool NullInputMethod::IsActive() { - return false; -} - -ui::TextInputClient* NullInputMethod::GetTextInputClient() const { - return NULL; -} - -ui::TextInputType NullInputMethod::GetTextInputType() const { - return ui::TEXT_INPUT_TYPE_NONE; -} - -bool NullInputMethod::IsCandidatePopupOpen() const { - return false; -} - -void NullInputMethod::ShowImeIfNeeded() {} - -bool NullInputMethod::IsMock() const { - return false; -} - -} // namespace views
diff --git a/ui/views/ime/null_input_method.h b/ui/views/ime/null_input_method.h deleted file mode 100644 index 29142e6..0000000 --- a/ui/views/ime/null_input_method.h +++ /dev/null
@@ -1,50 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_IME_NULL_INPUT_METHOD_H_ -#define UI_VIEWS_IME_NULL_INPUT_METHOD_H_ - -#include "base/compiler_specific.h" -#include "base/macros.h" -#include "ui/views/ime/input_method.h" - -namespace views { - -// An implementation of views::InputMethod which does nothing. -// -// We're working on removing views::InputMethod{,Base,Bridge} and going to use -// only ui::InputMethod. Use this class instead of views::InputMethodBridge -// with ui::TextInputFocusManager to effectively eliminate the -// views::InputMethod layer. -class NullInputMethod : public InputMethod { - public: - NullInputMethod(); - - // Overridden from InputMethod: - virtual void SetDelegate(internal::InputMethodDelegate* delegate) override; - virtual void Init(Widget* widget) override; - virtual void OnFocus() override; - virtual void OnBlur() override; - virtual bool OnUntranslatedIMEMessage(const base::NativeEvent& event, - NativeEventResult* result) override; - virtual void DispatchKeyEvent(const ui::KeyEvent& key) override; - virtual void OnTextInputTypeChanged(View* view) override; - virtual void OnCaretBoundsChanged(View* view) override; - virtual void CancelComposition(View* view) override; - virtual void OnInputLocaleChanged() override; - virtual std::string GetInputLocale() override; - virtual bool IsActive() override; - virtual ui::TextInputClient* GetTextInputClient() const override; - virtual ui::TextInputType GetTextInputType() const override; - virtual bool IsCandidatePopupOpen() const override; - virtual void ShowImeIfNeeded() override; - virtual bool IsMock() const override; - - private: - DISALLOW_COPY_AND_ASSIGN(NullInputMethod); -}; - -} // namespace views - -#endif // UI_VIEWS_IME_NULL_INPUT_METHOD_H_
diff --git a/ui/views/layout/box_layout.cc b/ui/views/layout/box_layout.cc deleted file mode 100644 index 4864dd6..0000000 --- a/ui/views/layout/box_layout.cc +++ /dev/null
@@ -1,316 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/layout/box_layout.h" - -#include "ui/gfx/rect.h" -#include "ui/views/view.h" - -namespace views { - -BoxLayout::BoxLayout(BoxLayout::Orientation orientation, - int inside_border_horizontal_spacing, - int inside_border_vertical_spacing, - int between_child_spacing) - : orientation_(orientation), - inside_border_insets_(inside_border_vertical_spacing, - inside_border_horizontal_spacing, - inside_border_vertical_spacing, - inside_border_horizontal_spacing), - between_child_spacing_(between_child_spacing), - main_axis_alignment_(MAIN_AXIS_ALIGNMENT_START), - cross_axis_alignment_(CROSS_AXIS_ALIGNMENT_STRETCH), - default_flex_(0), - minimum_cross_axis_size_(0), - host_(NULL) { -} - -BoxLayout::~BoxLayout() { -} - -void BoxLayout::SetFlexForView(const View* view, int flex_weight) { - DCHECK(host_); - DCHECK(view); - DCHECK_EQ(host_, view->parent()); - DCHECK_GE(flex_weight, 0); - flex_map_[view] = flex_weight; -} - -void BoxLayout::ClearFlexForView(const View* view) { - DCHECK(view); - flex_map_.erase(view); -} - -void BoxLayout::SetDefaultFlex(int default_flex) { - DCHECK_GE(default_flex, 0); - default_flex_ = default_flex; -} - -void BoxLayout::Layout(View* host) { - DCHECK_EQ(host_, host); - gfx::Rect child_area(host->GetLocalBounds()); - child_area.Inset(host->GetInsets()); - child_area.Inset(inside_border_insets_); - - int total_main_axis_size = 0; - int num_visible = 0; - int flex_sum = 0; - // Calculate the total size of children in the main axis. - for (int i = 0; i < host->child_count(); ++i) { - View* child = host->child_at(i); - if (!child->visible()) - continue; - total_main_axis_size += - MainAxisSizeForView(child, child_area.width()) + between_child_spacing_; - ++num_visible; - flex_sum += GetFlexForView(child); - } - - if (!num_visible) - return; - - total_main_axis_size -= between_child_spacing_; - // Free space can be negative indicating that the views want to overflow. - int main_free_space = MainAxisSize(child_area) - total_main_axis_size; - { - int position = MainAxisPosition(child_area); - int size = MainAxisSize(child_area); - if (!flex_sum) { - switch (main_axis_alignment_) { - case MAIN_AXIS_ALIGNMENT_START: - break; - case MAIN_AXIS_ALIGNMENT_CENTER: - position += main_free_space / 2; - size = total_main_axis_size; - break; - case MAIN_AXIS_ALIGNMENT_END: - position += main_free_space; - size = total_main_axis_size; - break; - default: - NOTREACHED(); - break; - } - } - gfx::Rect new_child_area(child_area); - SetMainAxisPosition(position, &new_child_area); - SetMainAxisSize(size, &new_child_area); - child_area.Intersect(new_child_area); - } - - int main_position = MainAxisPosition(child_area); - int total_padding = 0; - int current_flex = 0; - for (int i = 0; i < host->child_count(); ++i) { - View* child = host->child_at(i); - if (!child->visible()) - continue; - - // Calculate cross axis size. - gfx::Rect bounds(child_area); - SetMainAxisPosition(main_position, &bounds); - if (cross_axis_alignment_ != CROSS_AXIS_ALIGNMENT_STRETCH) { - int free_space = CrossAxisSize(bounds) - CrossAxisSizeForView(child); - int position = CrossAxisPosition(bounds); - if (cross_axis_alignment_ == CROSS_AXIS_ALIGNMENT_CENTER) { - position += free_space / 2; - } else if (cross_axis_alignment_ == CROSS_AXIS_ALIGNMENT_END) { - position += free_space; - } - SetCrossAxisPosition(position, &bounds); - SetCrossAxisSize(CrossAxisSizeForView(child), &bounds); - } - - // Calculate flex padding. - int current_padding = 0; - if (GetFlexForView(child) > 0) { - current_flex += GetFlexForView(child); - int quot = (main_free_space * current_flex) / flex_sum; - int rem = (main_free_space * current_flex) % flex_sum; - current_padding = quot - total_padding; - // Use the current remainder to round to the nearest pixel. - if (std::abs(rem) * 2 >= flex_sum) - current_padding += main_free_space > 0 ? 1 : -1; - total_padding += current_padding; - } - - // Set main axis size. - int child_main_axis_size = MainAxisSizeForView(child, child_area.width()); - SetMainAxisSize(child_main_axis_size + current_padding, &bounds); - if (MainAxisSize(bounds) > 0 || GetFlexForView(child) > 0) - main_position += MainAxisSize(bounds) + between_child_spacing_; - - // Clamp child view bounds to |child_area|. - bounds.Intersect(child_area); - child->SetBoundsRect(bounds); - } - - // Flex views should have grown/shrunk to consume all free space. - if (flex_sum) - DCHECK_EQ(total_padding, main_free_space); -} - -gfx::Size BoxLayout::GetPreferredSize(const View* host) const { - DCHECK_EQ(host_, host); - // Calculate the child views' preferred width. - int width = 0; - if (orientation_ == kVertical) { - for (int i = 0; i < host->child_count(); ++i) { - const View* child = host->child_at(i); - if (!child->visible()) - continue; - - width = std::max(width, child->GetPreferredSize().width()); - } - width = std::max(width, minimum_cross_axis_size_); - } - - return GetPreferredSizeForChildWidth(host, width); -} - -int BoxLayout::GetPreferredHeightForWidth(const View* host, int width) const { - DCHECK_EQ(host_, host); - int child_width = width - NonChildSize(host).width(); - return GetPreferredSizeForChildWidth(host, child_width).height(); -} - -void BoxLayout::Installed(View* host) { - DCHECK(!host_); - host_ = host; -} - -void BoxLayout::Uninstalled(View* host) { - DCHECK_EQ(host_, host); - host_ = NULL; - flex_map_.clear(); -} - -void BoxLayout::ViewRemoved(View* host, View* view) { - ClearFlexForView(view); -} - -int BoxLayout::GetFlexForView(const View* view) const { - std::map<const View*, int>::const_iterator it = flex_map_.find(view); - if (it == flex_map_.end()) - return default_flex_; - - return it->second; -} - -int BoxLayout::MainAxisSize(const gfx::Rect& rect) const { - return orientation_ == kHorizontal ? rect.width() : rect.height(); -} - -int BoxLayout::MainAxisPosition(const gfx::Rect& rect) const { - return orientation_ == kHorizontal ? rect.x() : rect.y(); -} - -void BoxLayout::SetMainAxisSize(int size, gfx::Rect* rect) const { - if (orientation_ == kHorizontal) - rect->set_width(size); - else - rect->set_height(size); -} - -void BoxLayout::SetMainAxisPosition(int position, gfx::Rect* rect) const { - if (orientation_ == kHorizontal) - rect->set_x(position); - else - rect->set_y(position); -} - -int BoxLayout::CrossAxisSize(const gfx::Rect& rect) const { - return orientation_ == kVertical ? rect.width() : rect.height(); -} - -int BoxLayout::CrossAxisPosition(const gfx::Rect& rect) const { - return orientation_ == kVertical ? rect.x() : rect.y(); -} - -void BoxLayout::SetCrossAxisSize(int size, gfx::Rect* rect) const { - if (orientation_ == kVertical) - rect->set_width(size); - else - rect->set_height(size); -} - -void BoxLayout::SetCrossAxisPosition(int position, gfx::Rect* rect) const { - if (orientation_ == kVertical) - rect->set_x(position); - else - rect->set_y(position); -} - -int BoxLayout::MainAxisSizeForView(const View* view, - int child_area_width) const { - return orientation_ == kHorizontal - ? view->GetPreferredSize().width() - : view->GetHeightForWidth(cross_axis_alignment_ == - CROSS_AXIS_ALIGNMENT_STRETCH - ? child_area_width - : view->GetPreferredSize().width()); -} - -int BoxLayout::CrossAxisSizeForView(const View* view) const { - return orientation_ == kVertical - ? view->GetPreferredSize().width() - : view->GetHeightForWidth(view->GetPreferredSize().width()); -} - -gfx::Size BoxLayout::GetPreferredSizeForChildWidth(const View* host, - int child_area_width) const { - gfx::Rect child_area_bounds; - - if (orientation_ == kHorizontal) { - // Horizontal layouts ignore |child_area_width|, meaning they mimic the - // default behavior of GridLayout::GetPreferredHeightForWidth(). - // TODO(estade): fix this if it ever becomes a problem. - int position = 0; - for (int i = 0; i < host->child_count(); ++i) { - const View* child = host->child_at(i); - if (!child->visible()) - continue; - - gfx::Size size(child->GetPreferredSize()); - if (size.IsEmpty()) - continue; - - gfx::Rect child_bounds(position, 0, size.width(), size.height()); - child_area_bounds.Union(child_bounds); - position += size.width() + between_child_spacing_; - } - child_area_bounds.set_height( - std::max(child_area_bounds.height(), minimum_cross_axis_size_)); - } else { - int height = 0; - for (int i = 0; i < host->child_count(); ++i) { - const View* child = host->child_at(i); - if (!child->visible()) - continue; - - // Use the child area width for getting the height if the child is - // supposed to stretch. Use its preferred size otherwise. - int extra_height = MainAxisSizeForView(child, child_area_width); - // Only add |between_child_spacing_| if this is not the only child. - if (height != 0 && extra_height > 0) - height += between_child_spacing_; - height += extra_height; - } - - child_area_bounds.set_width(child_area_width); - child_area_bounds.set_height(height); - } - - gfx::Size non_child_size = NonChildSize(host); - return gfx::Size(child_area_bounds.width() + non_child_size.width(), - child_area_bounds.height() + non_child_size.height()); -} - -gfx::Size BoxLayout::NonChildSize(const View* host) const { - gfx::Insets insets(host->GetInsets()); - return gfx::Size(insets.width() + inside_border_insets_.width(), - insets.height() + inside_border_insets_.height()); -} - -} // namespace views
diff --git a/ui/views/layout/box_layout.h b/ui/views/layout/box_layout.h deleted file mode 100644 index b07afaf..0000000 --- a/ui/views/layout/box_layout.h +++ /dev/null
@@ -1,177 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_LAYOUT_BOX_LAYOUT_H_ -#define UI_VIEWS_LAYOUT_BOX_LAYOUT_H_ - -#include <map> - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "ui/gfx/insets.h" -#include "ui/views/layout/layout_manager.h" - -namespace gfx { -class Rect; -class Size; -} - -namespace views { - -class View; - -// A Layout manager that arranges child views vertically or horizontally in a -// side-by-side fashion with spacing around and between the child views. The -// child views are always sized according to their preferred size. If the -// host's bounds provide insufficient space, child views will be clamped. -// Excess space will not be distributed. -class VIEWS_EXPORT BoxLayout : public LayoutManager { - public: - enum Orientation { - kHorizontal, - kVertical, - }; - - // This specifies where along the main axis the children should be laid out. - // e.g. a horizontal layout of MAIN_AXIS_ALIGNMENT_END will result in the - // child views being right-aligned. - enum MainAxisAlignment { - MAIN_AXIS_ALIGNMENT_START, - MAIN_AXIS_ALIGNMENT_CENTER, - MAIN_AXIS_ALIGNMENT_END, - // TODO(calamity): Add MAIN_AXIS_ALIGNMENT_JUSTIFY which spreads blank space - // in-between the child views. - }; - - // This specifies where along the cross axis the children should be laid out. - // e.g. a horizontal layout of CROSS_AXIS_ALIGNMENT_END will result in the - // child views being bottom-aligned. - enum CrossAxisAlignment { - // This causes the child view to stretch to fit the host in the cross axis. - CROSS_AXIS_ALIGNMENT_STRETCH, - CROSS_AXIS_ALIGNMENT_START, - CROSS_AXIS_ALIGNMENT_CENTER, - CROSS_AXIS_ALIGNMENT_END, - }; - - // Use |inside_border_horizontal_spacing| and - // |inside_border_vertical_spacing| to add additional space between the child - // view area and the host view border. |between_child_spacing| controls the - // space in between child views. - BoxLayout(Orientation orientation, - int inside_border_horizontal_spacing, - int inside_border_vertical_spacing, - int between_child_spacing); - virtual ~BoxLayout(); - - void set_main_axis_alignment(MainAxisAlignment main_axis_alignment) { - main_axis_alignment_ = main_axis_alignment; - } - - void set_cross_axis_alignment(CrossAxisAlignment cross_axis_alignment) { - cross_axis_alignment_ = cross_axis_alignment; - } - - void set_inside_border_insets(const gfx::Insets& insets) { - inside_border_insets_ = insets; - } - - void set_minimum_cross_axis_size(int size) { - minimum_cross_axis_size_ = size; - } - - // Sets the flex weight for the given |view|. Using the preferred size as - // the basis, free space along the main axis is distributed to views in the - // ratio of their flex weights. Similarly, if the views will overflow the - // parent, space is subtracted in these ratios. - // - // A flex of 0 means this view is not resized. Flex values must not be - // negative. - void SetFlexForView(const View* view, int flex); - - // Clears the flex for the given |view|, causing it to use the default - // flex. - void ClearFlexForView(const View* view); - - // Sets the flex for views to use when none is specified. - void SetDefaultFlex(int default_flex); - - // Overridden from views::LayoutManager: - virtual void Installed(View* host) override; - virtual void Uninstalled(View* host) override; - virtual void ViewRemoved(View* host, View* view) override; - virtual void Layout(View* host) override; - virtual gfx::Size GetPreferredSize(const View* host) const override; - virtual int GetPreferredHeightForWidth(const View* host, - int width) const override; - - private: - // Returns the flex for the specified |view|. - int GetFlexForView(const View* view) const; - - // Returns the size and position along the main axis of |rect|. - int MainAxisSize(const gfx::Rect& rect) const; - int MainAxisPosition(const gfx::Rect& rect) const; - - // Sets the size and position along the main axis of |rect|. - void SetMainAxisSize(int size, gfx::Rect* rect) const; - void SetMainAxisPosition(int position, gfx::Rect* rect) const; - - // Returns the size and position along the cross axis of |rect|. - int CrossAxisSize(const gfx::Rect& rect) const; - int CrossAxisPosition(const gfx::Rect& rect) const; - - // Sets the size and position along the cross axis of |rect|. - void SetCrossAxisSize(int size, gfx::Rect* rect) const; - void SetCrossAxisPosition(int size, gfx::Rect* rect) const; - - // Returns the main axis size for the given view. |child_area_width| is needed - // to calculate the height of the view when the orientation is vertical. - int MainAxisSizeForView(const View* view, int child_area_width) const; - - // Returns the cross axis size for the given view. - int CrossAxisSizeForView(const View* view) const; - - // The preferred size for the dialog given the width of the child area. - gfx::Size GetPreferredSizeForChildWidth(const View* host, - int child_area_width) const; - - // The amount of space the layout requires in addition to any space for the - // child views. - gfx::Size NonChildSize(const View* host) const; - - const Orientation orientation_; - - // Spacing between child views and host view border. - gfx::Insets inside_border_insets_; - - // Spacing to put in between child views. - const int between_child_spacing_; - - // The alignment of children in the main axis. This is - // MAIN_AXIS_ALIGNMENT_START by default. - MainAxisAlignment main_axis_alignment_; - - // The alignment of children in the cross axis. This is - // CROSS_AXIS_ALIGNMENT_STRETCH by default. - CrossAxisAlignment cross_axis_alignment_; - - // A map of views to their flex weights. - std::map<const View*, int> flex_map_; - - // The flex weight for views if none is set. Defaults to 0. - int default_flex_; - - // The minimum cross axis size for the layout. - int minimum_cross_axis_size_; - - // The view that this BoxLayout is managing the layout for. - views::View* host_; - - DISALLOW_IMPLICIT_CONSTRUCTORS(BoxLayout); -}; - -} // namespace views - -#endif // UI_VIEWS_LAYOUT_BOX_LAYOUT_H_
diff --git a/ui/views/layout/box_layout_unittest.cc b/ui/views/layout/box_layout_unittest.cc deleted file mode 100644 index 708d2fe..0000000 --- a/ui/views/layout/box_layout_unittest.cc +++ /dev/null
@@ -1,613 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/layout/box_layout.h" - -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/views/test/test_views.h" -#include "ui/views/view.h" - -namespace views { - -namespace { - -class BoxLayoutTest : public testing::Test { - public: - virtual void SetUp() override { - host_.reset(new View); - } - - scoped_ptr<View> host_; -}; - -} // namespace - -TEST_F(BoxLayoutTest, Empty) { - BoxLayout* layout = new BoxLayout(BoxLayout::kHorizontal, 10, 10, 20); - host_->SetLayoutManager(layout); - EXPECT_EQ(gfx::Size(20, 20), layout->GetPreferredSize(host_.get())); -} - -TEST_F(BoxLayoutTest, AlignmentHorizontal) { - BoxLayout* layout = new BoxLayout(BoxLayout::kHorizontal, 0, 0, 0); - host_->SetLayoutManager(layout); - View* v1 = new StaticSizedView(gfx::Size(10, 20)); - host_->AddChildView(v1); - View* v2 = new StaticSizedView(gfx::Size(10, 10)); - host_->AddChildView(v2); - EXPECT_EQ(gfx::Size(20, 20), layout->GetPreferredSize(host_.get())); - host_->SetBounds(0, 0, 20, 20); - host_->Layout(); - EXPECT_EQ(gfx::Rect(0, 0, 10, 20), v1->bounds()); - EXPECT_EQ(gfx::Rect(10, 0, 10, 20), v2->bounds()); -} - -TEST_F(BoxLayoutTest, AlignmentVertical) { - BoxLayout* layout = new BoxLayout(BoxLayout::kVertical, 0, 0, 0); - host_->SetLayoutManager(layout); - View* v1 = new StaticSizedView(gfx::Size(20, 10)); - host_->AddChildView(v1); - View* v2 = new StaticSizedView(gfx::Size(10, 10)); - host_->AddChildView(v2); - EXPECT_EQ(gfx::Size(20, 20), layout->GetPreferredSize(host_.get())); - host_->SetBounds(0, 0, 20, 20); - host_->Layout(); - EXPECT_EQ(gfx::Rect(0, 0, 20, 10), v1->bounds()); - EXPECT_EQ(gfx::Rect(0, 10, 20, 10), v2->bounds()); -} - -TEST_F(BoxLayoutTest, SetInsideBorderInsets) { - BoxLayout* layout = new BoxLayout(BoxLayout::kHorizontal, 10, 20, 0); - host_->SetLayoutManager(layout); - View* v1 = new StaticSizedView(gfx::Size(10, 20)); - host_->AddChildView(v1); - View* v2 = new StaticSizedView(gfx::Size(10, 10)); - host_->AddChildView(v2); - EXPECT_EQ(gfx::Size(40, 60), layout->GetPreferredSize(host_.get())); - host_->SetBounds(0, 0, 40, 60); - host_->Layout(); - EXPECT_EQ(gfx::Rect(10, 20, 10, 20), v1->bounds()); - EXPECT_EQ(gfx::Rect(20, 20, 10, 20), v2->bounds()); - - layout->set_inside_border_insets( - gfx::Insets(5, 10, 15, 20)); - EXPECT_EQ(gfx::Size(50, 40), layout->GetPreferredSize(host_.get())); - host_->SetBounds(0, 0, 50, 40); - host_->Layout(); - EXPECT_EQ(gfx::Rect(10, 5, 10, 20), v1->bounds()); - EXPECT_EQ(gfx::Rect(20, 5, 10, 20), v2->bounds()); -} - -TEST_F(BoxLayoutTest, Spacing) { - BoxLayout* layout = new BoxLayout(BoxLayout::kHorizontal, 7, 7, 8); - host_->SetLayoutManager(layout); - View* v1 = new StaticSizedView(gfx::Size(10, 20)); - host_->AddChildView(v1); - View* v2 = new StaticSizedView(gfx::Size(10, 20)); - host_->AddChildView(v2); - EXPECT_EQ(gfx::Size(42, 34), layout->GetPreferredSize(host_.get())); - host_->SetBounds(0, 0, 100, 100); - host_->Layout(); - EXPECT_EQ(gfx::Rect(7, 7, 10, 86), v1->bounds()); - EXPECT_EQ(gfx::Rect(25, 7, 10, 86), v2->bounds()); -} - -TEST_F(BoxLayoutTest, Overflow) { - BoxLayout* layout = new BoxLayout(BoxLayout::kHorizontal, 0, 0, 0); - host_->SetLayoutManager(layout); - View* v1 = new StaticSizedView(gfx::Size(20, 20)); - host_->AddChildView(v1); - View* v2 = new StaticSizedView(gfx::Size(10, 20)); - host_->AddChildView(v2); - host_->SetBounds(0, 0, 10, 10); - - // Overflows by positioning views at the start and truncating anything that - // doesn't fit. - host_->Layout(); - EXPECT_EQ(gfx::Rect(0, 0, 10, 10), v1->bounds()); - EXPECT_EQ(gfx::Rect(0, 0, 0, 0), v2->bounds()); - - // All values of main axis alignment should overflow in the same manner. - layout->set_main_axis_alignment(BoxLayout::MAIN_AXIS_ALIGNMENT_START); - host_->Layout(); - EXPECT_EQ(gfx::Rect(0, 0, 10, 10), v1->bounds()); - EXPECT_EQ(gfx::Rect(0, 0, 0, 0), v2->bounds()); - - layout->set_main_axis_alignment(BoxLayout::MAIN_AXIS_ALIGNMENT_CENTER); - host_->Layout(); - EXPECT_EQ(gfx::Rect(0, 0, 10, 10), v1->bounds()); - EXPECT_EQ(gfx::Rect(0, 0, 0, 0), v2->bounds()); - - layout->set_main_axis_alignment(BoxLayout::MAIN_AXIS_ALIGNMENT_END); - host_->Layout(); - EXPECT_EQ(gfx::Rect(0, 0, 10, 10), v1->bounds()); - EXPECT_EQ(gfx::Rect(0, 0, 0, 0), v2->bounds()); -} - -TEST_F(BoxLayoutTest, NoSpace) { - BoxLayout* layout = new BoxLayout(BoxLayout::kHorizontal, 10, 10, 10); - host_->SetLayoutManager(layout); - View* childView = new StaticSizedView(gfx::Size(20, 20)); - host_->AddChildView(childView); - host_->SetBounds(0, 0, 10, 10); - host_->Layout(); - EXPECT_EQ(gfx::Rect(0, 0, 0, 0), childView->bounds()); -} - -TEST_F(BoxLayoutTest, InvisibleChild) { - BoxLayout* layout = new BoxLayout(BoxLayout::kHorizontal, 10, 10, 10); - host_->SetLayoutManager(layout); - View* v1 = new StaticSizedView(gfx::Size(20, 20)); - v1->SetVisible(false); - host_->AddChildView(v1); - View* v2 = new StaticSizedView(gfx::Size(10, 10)); - host_->AddChildView(v2); - EXPECT_EQ(gfx::Size(30, 30), layout->GetPreferredSize(host_.get())); - host_->SetBounds(0, 0, 30, 30); - host_->Layout(); - EXPECT_EQ(gfx::Rect(10, 10, 10, 10), v2->bounds()); -} - -TEST_F(BoxLayoutTest, UseHeightForWidth) { - BoxLayout* layout = new BoxLayout(BoxLayout::kVertical, 0, 0, 0); - host_->SetLayoutManager(layout); - View* v1 = new StaticSizedView(gfx::Size(20, 10)); - host_->AddChildView(v1); - ProportionallySizedView* v2 = new ProportionallySizedView(2); - v2->set_preferred_width(10); - host_->AddChildView(v2); - EXPECT_EQ(gfx::Size(20, 50), layout->GetPreferredSize(host_.get())); - - host_->SetBounds(0, 0, 20, 50); - host_->Layout(); - EXPECT_EQ(gfx::Rect(0, 0, 20, 10), v1->bounds()); - EXPECT_EQ(gfx::Rect(0, 10, 20, 40), v2->bounds()); - - EXPECT_EQ(110, layout->GetPreferredHeightForWidth(host_.get(), 50)); - - // Test without horizontal stretching of the views. - layout->set_cross_axis_alignment(BoxLayout::CROSS_AXIS_ALIGNMENT_END); - EXPECT_EQ(gfx::Size(20, 30).ToString(), - layout->GetPreferredSize(host_.get()).ToString()); - - host_->SetBounds(0, 0, 20, 30); - host_->Layout(); - EXPECT_EQ(gfx::Rect(0, 0, 20, 10), v1->bounds()); - EXPECT_EQ(gfx::Rect(10, 10, 10, 20), v2->bounds()); - - EXPECT_EQ(30, layout->GetPreferredHeightForWidth(host_.get(), 50)); -} - -TEST_F(BoxLayoutTest, EmptyPreferredSize) { - for (size_t i = 0; i < 2; i++) { - BoxLayout::Orientation orientation = i == 0 ? BoxLayout::kHorizontal : - BoxLayout::kVertical; - host_->RemoveAllChildViews(true); - host_->SetLayoutManager(new BoxLayout(orientation, 0, 0, 5)); - View* v1 = new StaticSizedView(gfx::Size()); - host_->AddChildView(v1); - View* v2 = new StaticSizedView(gfx::Size(10, 10)); - host_->AddChildView(v2); - host_->SizeToPreferredSize(); - host_->Layout(); - - EXPECT_EQ(v2->GetPreferredSize().width(), host_->bounds().width()) << i; - EXPECT_EQ(v2->GetPreferredSize().height(), host_->bounds().height()) << i; - EXPECT_EQ(v1->GetPreferredSize().width(), v1->bounds().width()) << i; - EXPECT_EQ(v1->GetPreferredSize().height(), v1->bounds().height()) << i; - EXPECT_EQ(v2->GetPreferredSize().width(), v2->bounds().width()) << i; - EXPECT_EQ(v2->GetPreferredSize().height(), v2->bounds().height()) << i; - } -} - -TEST_F(BoxLayoutTest, MainAxisAlignmentHorizontal) { - BoxLayout* layout = new BoxLayout(BoxLayout::kHorizontal, 10, 10, 10); - host_->SetLayoutManager(layout); - - View* v1 = new StaticSizedView(gfx::Size(20, 20)); - host_->AddChildView(v1); - View* v2 = new StaticSizedView(gfx::Size(10, 10)); - host_->AddChildView(v2); - - host_->SetBounds(0, 0, 100, 40); - - // Align children to the horizontal start by default. - host_->Layout(); - EXPECT_EQ(gfx::Rect(10, 10, 20, 20).ToString(), v1->bounds().ToString()); - EXPECT_EQ(gfx::Rect(40, 10, 10, 20).ToString(), v2->bounds().ToString()); - - // Ensure same results for MAIN_AXIS_ALIGNMENT_START. - layout->set_main_axis_alignment(BoxLayout::MAIN_AXIS_ALIGNMENT_START); - host_->Layout(); - EXPECT_EQ(gfx::Rect(10, 10, 20, 20).ToString(), v1->bounds().ToString()); - EXPECT_EQ(gfx::Rect(40, 10, 10, 20).ToString(), v2->bounds().ToString()); - - // Aligns children to the center horizontally. - layout->set_main_axis_alignment(BoxLayout::MAIN_AXIS_ALIGNMENT_CENTER); - host_->Layout(); - EXPECT_EQ(gfx::Rect(30, 10, 20, 20).ToString(), v1->bounds().ToString()); - EXPECT_EQ(gfx::Rect(60, 10, 10, 20).ToString(), v2->bounds().ToString()); - - // Aligns children to the end of the host horizontally, accounting for the - // inside border spacing. - layout->set_main_axis_alignment(BoxLayout::MAIN_AXIS_ALIGNMENT_END); - host_->Layout(); - EXPECT_EQ(gfx::Rect(50, 10, 20, 20).ToString(), v1->bounds().ToString()); - EXPECT_EQ(gfx::Rect(80, 10, 10, 20).ToString(), v2->bounds().ToString()); -} - -TEST_F(BoxLayoutTest, MainAxisAlignmentVertical) { - BoxLayout* layout = new BoxLayout(BoxLayout::kVertical, 10, 10, 10); - host_->SetLayoutManager(layout); - - View* v1 = new StaticSizedView(gfx::Size(20, 20)); - host_->AddChildView(v1); - View* v2 = new StaticSizedView(gfx::Size(10, 10)); - host_->AddChildView(v2); - - host_->SetBounds(0, 0, 40, 100); - - // Align children to the vertical start by default. - host_->Layout(); - EXPECT_EQ(gfx::Rect(10, 10, 20, 20).ToString(), v1->bounds().ToString()); - EXPECT_EQ(gfx::Rect(10, 40, 20, 10).ToString(), v2->bounds().ToString()); - - // Ensure same results for MAIN_AXIS_ALIGNMENT_START. - layout->set_main_axis_alignment(BoxLayout::MAIN_AXIS_ALIGNMENT_START); - host_->Layout(); - EXPECT_EQ(gfx::Rect(10, 10, 20, 20).ToString(), v1->bounds().ToString()); - EXPECT_EQ(gfx::Rect(10, 40, 20, 10).ToString(), v2->bounds().ToString()); - - // Aligns children to the center vertically. - layout->set_main_axis_alignment(BoxLayout::MAIN_AXIS_ALIGNMENT_CENTER); - host_->Layout(); - EXPECT_EQ(gfx::Rect(10, 30, 20, 20).ToString(), v1->bounds().ToString()); - EXPECT_EQ(gfx::Rect(10, 60, 20, 10).ToString(), v2->bounds().ToString()); - - // Aligns children to the end of the host vertically, accounting for the - // inside border spacing. - layout->set_main_axis_alignment(BoxLayout::MAIN_AXIS_ALIGNMENT_END); - host_->Layout(); - EXPECT_EQ(gfx::Rect(10, 50, 20, 20).ToString(), v1->bounds().ToString()); - EXPECT_EQ(gfx::Rect(10, 80, 20, 10).ToString(), v2->bounds().ToString()); -} - -TEST_F(BoxLayoutTest, CrossAxisAlignmentHorizontal) { - BoxLayout* layout = new BoxLayout(BoxLayout::kHorizontal, 10, 10, 10); - host_->SetLayoutManager(layout); - - View* v1 = new StaticSizedView(gfx::Size(20, 20)); - host_->AddChildView(v1); - View* v2 = new StaticSizedView(gfx::Size(10, 10)); - host_->AddChildView(v2); - - host_->SetBounds(0, 0, 100, 60); - - // Stretch children to fill the available height by default. - host_->Layout(); - EXPECT_EQ(gfx::Rect(10, 10, 20, 40).ToString(), v1->bounds().ToString()); - EXPECT_EQ(gfx::Rect(40, 10, 10, 40).ToString(), v2->bounds().ToString()); - - // Ensure same results for CROSS_AXIS_ALIGNMENT_STRETCH. - layout->set_cross_axis_alignment(BoxLayout::CROSS_AXIS_ALIGNMENT_STRETCH); - host_->Layout(); - EXPECT_EQ(gfx::Rect(10, 10, 20, 40).ToString(), v1->bounds().ToString()); - EXPECT_EQ(gfx::Rect(40, 10, 10, 40).ToString(), v2->bounds().ToString()); - - // Aligns children to the start vertically. - layout->set_cross_axis_alignment(BoxLayout::CROSS_AXIS_ALIGNMENT_START); - host_->Layout(); - EXPECT_EQ(gfx::Rect(10, 10, 20, 20).ToString(), v1->bounds().ToString()); - EXPECT_EQ(gfx::Rect(40, 10, 10, 10).ToString(), v2->bounds().ToString()); - - // Aligns children to the center vertically. - layout->set_cross_axis_alignment(BoxLayout::CROSS_AXIS_ALIGNMENT_CENTER); - host_->Layout(); - EXPECT_EQ(gfx::Rect(10, 20, 20, 20).ToString(), v1->bounds().ToString()); - EXPECT_EQ(gfx::Rect(40, 25, 10, 10).ToString(), v2->bounds().ToString()); - - // Aligns children to the end of the host vertically, accounting for the - // inside border spacing. - layout->set_cross_axis_alignment(BoxLayout::CROSS_AXIS_ALIGNMENT_END); - host_->Layout(); - EXPECT_EQ(gfx::Rect(10, 30, 20, 20).ToString(), v1->bounds().ToString()); - EXPECT_EQ(gfx::Rect(40, 40, 10, 10).ToString(), v2->bounds().ToString()); -} - -TEST_F(BoxLayoutTest, CrossAxisAlignmentVertical) { - BoxLayout* layout = new BoxLayout(BoxLayout::kVertical, 10, 10, 10); - host_->SetLayoutManager(layout); - - View* v1 = new StaticSizedView(gfx::Size(20, 20)); - host_->AddChildView(v1); - View* v2 = new StaticSizedView(gfx::Size(10, 10)); - host_->AddChildView(v2); - - host_->SetBounds(0, 0, 60, 100); - - // Stretch children to fill the available width by default. - host_->Layout(); - EXPECT_EQ(gfx::Rect(10, 10, 40, 20).ToString(), v1->bounds().ToString()); - EXPECT_EQ(gfx::Rect(10, 40, 40, 10).ToString(), v2->bounds().ToString()); - - // Ensure same results for CROSS_AXIS_ALIGNMENT_STRETCH. - layout->set_cross_axis_alignment(BoxLayout::CROSS_AXIS_ALIGNMENT_STRETCH); - host_->Layout(); - EXPECT_EQ(gfx::Rect(10, 10, 40, 20).ToString(), v1->bounds().ToString()); - EXPECT_EQ(gfx::Rect(10, 40, 40, 10).ToString(), v2->bounds().ToString()); - - // Aligns children to the start horizontally. - layout->set_cross_axis_alignment(BoxLayout::CROSS_AXIS_ALIGNMENT_START); - host_->Layout(); - EXPECT_EQ(gfx::Rect(10, 10, 20, 20).ToString(), v1->bounds().ToString()); - EXPECT_EQ(gfx::Rect(10, 40, 10, 10).ToString(), v2->bounds().ToString()); - - // Aligns children to the center horizontally. - layout->set_cross_axis_alignment(BoxLayout::CROSS_AXIS_ALIGNMENT_CENTER); - host_->Layout(); - EXPECT_EQ(gfx::Rect(20, 10, 20, 20).ToString(), v1->bounds().ToString()); - EXPECT_EQ(gfx::Rect(25, 40, 10, 10).ToString(), v2->bounds().ToString()); - - // Aligns children to the end of the host horizontally, accounting for the - // inside border spacing. - layout->set_cross_axis_alignment(BoxLayout::CROSS_AXIS_ALIGNMENT_END); - host_->Layout(); - EXPECT_EQ(gfx::Rect(30, 10, 20, 20).ToString(), v1->bounds().ToString()); - EXPECT_EQ(gfx::Rect(40, 40, 10, 10).ToString(), v2->bounds().ToString()); -} - -TEST_F(BoxLayoutTest, FlexAll) { - BoxLayout* layout = new BoxLayout(BoxLayout::kHorizontal, 10, 10, 10); - host_->SetLayoutManager(layout); - layout->SetDefaultFlex(1); - - View* v1 = new StaticSizedView(gfx::Size(20, 20)); - host_->AddChildView(v1); - View* v2 = new StaticSizedView(gfx::Size(10, 10)); - host_->AddChildView(v2); - View* v3 = new StaticSizedView(gfx::Size(30, 30)); - host_->AddChildView(v3); - EXPECT_EQ(gfx::Size(100, 50), layout->GetPreferredSize(host_.get())); - - host_->SetBounds(0, 0, 120, 50); - host_->Layout(); - EXPECT_EQ(gfx::Rect(10, 10, 27, 30).ToString(), v1->bounds().ToString()); - EXPECT_EQ(gfx::Rect(47, 10, 16, 30).ToString(), v2->bounds().ToString()); - EXPECT_EQ(gfx::Rect(73, 10, 37, 30).ToString(), v3->bounds().ToString()); -} - -TEST_F(BoxLayoutTest, FlexGrowVertical) { - BoxLayout* layout = new BoxLayout(BoxLayout::kVertical, 10, 10, 10); - host_->SetLayoutManager(layout); - - View* v1 = new StaticSizedView(gfx::Size(20, 20)); - host_->AddChildView(v1); - View* v2 = new StaticSizedView(gfx::Size(10, 10)); - host_->AddChildView(v2); - View* v3 = new StaticSizedView(gfx::Size(30, 30)); - host_->AddChildView(v3); - - host_->SetBounds(0, 0, 50, 130); - - // Views don't fill the available space by default. - host_->Layout(); - EXPECT_EQ(gfx::Rect(10, 10, 30, 20).ToString(), v1->bounds().ToString()); - EXPECT_EQ(gfx::Rect(10, 40, 30, 10).ToString(), v2->bounds().ToString()); - EXPECT_EQ(gfx::Rect(10, 60, 30, 30).ToString(), v3->bounds().ToString()); - - std::vector<BoxLayout::MainAxisAlignment> main_alignments; - main_alignments.push_back(BoxLayout::MAIN_AXIS_ALIGNMENT_START); - main_alignments.push_back(BoxLayout::MAIN_AXIS_ALIGNMENT_CENTER); - main_alignments.push_back(BoxLayout::MAIN_AXIS_ALIGNMENT_END); - - for (size_t i = 0; i < main_alignments.size(); ++i) { - layout->set_main_axis_alignment(main_alignments[i]); - - // Set the first view to consume all free space. - layout->SetFlexForView(v1, 1); - layout->ClearFlexForView(v2); - layout->ClearFlexForView(v3); - host_->Layout(); - EXPECT_EQ(gfx::Rect(10, 10, 30, 50).ToString(), v1->bounds().ToString()); - EXPECT_EQ(gfx::Rect(10, 70, 30, 10).ToString(), v2->bounds().ToString()); - EXPECT_EQ(gfx::Rect(10, 90, 30, 30).ToString(), v3->bounds().ToString()); - - // Set the third view to take 2/3s of the free space and leave the first - // view - // with 1/3. - layout->SetFlexForView(v3, 2); - host_->Layout(); - EXPECT_EQ(gfx::Rect(10, 10, 30, 30).ToString(), v1->bounds().ToString()); - EXPECT_EQ(gfx::Rect(10, 50, 30, 10).ToString(), v2->bounds().ToString()); - EXPECT_EQ(gfx::Rect(10, 70, 30, 50).ToString(), v3->bounds().ToString()); - - // Clear the previously set flex values and set the second view to take all - // the free space. - layout->ClearFlexForView(v1); - layout->SetFlexForView(v2, 1); - layout->ClearFlexForView(v3); - host_->Layout(); - EXPECT_EQ(gfx::Rect(10, 10, 30, 20).ToString(), v1->bounds().ToString()); - EXPECT_EQ(gfx::Rect(10, 40, 30, 40).ToString(), v2->bounds().ToString()); - EXPECT_EQ(gfx::Rect(10, 90, 30, 30).ToString(), v3->bounds().ToString()); - } -} - -TEST_F(BoxLayoutTest, FlexGrowHorizontalWithRemainder) { - BoxLayout* layout = new BoxLayout(BoxLayout::kHorizontal, 0, 0, 0); - host_->SetLayoutManager(layout); - layout->SetDefaultFlex(1); - std::vector<View*> views; - for (int i = 0; i < 5; ++i) { - View* view = new StaticSizedView(gfx::Size(10, 10)); - views.push_back(view); - host_->AddChildView(view); - } - - EXPECT_EQ(gfx::Size(50, 10), layout->GetPreferredSize(host_.get())); - - host_->SetBounds(0, 0, 52, 10); - host_->Layout(); - // The 2nd and 4th views should have an extra pixel as they correspond to 20.8 - // and 41.6 which round up. - EXPECT_EQ(gfx::Rect(0, 0, 10, 10).ToString(), views[0]->bounds().ToString()); - EXPECT_EQ(gfx::Rect(10, 0, 11, 10).ToString(), views[1]->bounds().ToString()); - EXPECT_EQ(gfx::Rect(21, 0, 10, 10).ToString(), views[2]->bounds().ToString()); - EXPECT_EQ(gfx::Rect(31, 0, 11, 10).ToString(), views[3]->bounds().ToString()); - EXPECT_EQ(gfx::Rect(42, 0, 10, 10).ToString(), views[4]->bounds().ToString()); -} - -TEST_F(BoxLayoutTest, FlexGrowHorizontalWithRemainder2) { - BoxLayout* layout = new BoxLayout(BoxLayout::kHorizontal, 0, 0, 0); - host_->SetLayoutManager(layout); - layout->SetDefaultFlex(1); - std::vector<View*> views; - for (int i = 0; i < 4; ++i) { - View* view = new StaticSizedView(gfx::Size(1, 10)); - views.push_back(view); - host_->AddChildView(view); - } - - EXPECT_EQ(gfx::Size(4, 10), layout->GetPreferredSize(host_.get())); - - host_->SetBounds(0, 0, 10, 10); - host_->Layout(); - // The 1st and 3rd views should have an extra pixel as they correspond to 2.5 - // and 7.5 which round up. - EXPECT_EQ(gfx::Rect(0, 0, 3, 10).ToString(), views[0]->bounds().ToString()); - EXPECT_EQ(gfx::Rect(3, 0, 2, 10).ToString(), views[1]->bounds().ToString()); - EXPECT_EQ(gfx::Rect(5, 0, 3, 10).ToString(), views[2]->bounds().ToString()); - EXPECT_EQ(gfx::Rect(8, 0, 2, 10).ToString(), views[3]->bounds().ToString()); -} - -TEST_F(BoxLayoutTest, FlexShrinkHorizontal) { - BoxLayout* layout = new BoxLayout(BoxLayout::kHorizontal, 10, 10, 10); - host_->SetLayoutManager(layout); - - View* v1 = new StaticSizedView(gfx::Size(20, 20)); - host_->AddChildView(v1); - View* v2 = new StaticSizedView(gfx::Size(10, 10)); - host_->AddChildView(v2); - View* v3 = new StaticSizedView(gfx::Size(30, 30)); - host_->AddChildView(v3); - - host_->SetBounds(0, 0, 85, 50); - - // Truncate width by default. - host_->Layout(); - EXPECT_EQ(gfx::Rect(10, 10, 20, 30).ToString(), v1->bounds().ToString()); - EXPECT_EQ(gfx::Rect(40, 10, 10, 30).ToString(), v2->bounds().ToString()); - EXPECT_EQ(gfx::Rect(60, 10, 15, 30).ToString(), v3->bounds().ToString()); - - std::vector<BoxLayout::MainAxisAlignment> main_alignments; - main_alignments.push_back(BoxLayout::MAIN_AXIS_ALIGNMENT_START); - main_alignments.push_back(BoxLayout::MAIN_AXIS_ALIGNMENT_CENTER); - main_alignments.push_back(BoxLayout::MAIN_AXIS_ALIGNMENT_END); - - for (size_t i = 0; i < main_alignments.size(); ++i) { - layout->set_main_axis_alignment(main_alignments[i]); - - // Set the first view to shrink as much as necessary. - layout->SetFlexForView(v1, 1); - layout->ClearFlexForView(v2); - layout->ClearFlexForView(v3); - host_->Layout(); - EXPECT_EQ(gfx::Rect(10, 10, 5, 30).ToString(), v1->bounds().ToString()); - EXPECT_EQ(gfx::Rect(25, 10, 10, 30).ToString(), v2->bounds().ToString()); - EXPECT_EQ(gfx::Rect(45, 10, 30, 30).ToString(), v3->bounds().ToString()); - - // Set the third view to shrink 2/3s of the free space and leave the first - // view with 1/3. - layout->SetFlexForView(v3, 2); - host_->Layout(); - EXPECT_EQ(gfx::Rect(10, 10, 15, 30).ToString(), v1->bounds().ToString()); - EXPECT_EQ(gfx::Rect(35, 10, 10, 30).ToString(), v2->bounds().ToString()); - EXPECT_EQ(gfx::Rect(55, 10, 20, 30).ToString(), v3->bounds().ToString()); - - // Clear the previously set flex values and set the second view to take all - // the free space with MAIN_AXIS_ALIGNMENT_END set. This causes the second - // view to shrink to zero and the third view still doesn't fit so it - // overflows. - layout->ClearFlexForView(v1); - layout->SetFlexForView(v2, 2); - layout->ClearFlexForView(v3); - host_->Layout(); - EXPECT_EQ(gfx::Rect(10, 10, 20, 30).ToString(), v1->bounds().ToString()); - // Conceptually this view is at 10, 40, 0, 0. - EXPECT_EQ(gfx::Rect(0, 0, 0, 0).ToString(), v2->bounds().ToString()); - EXPECT_EQ(gfx::Rect(50, 10, 25, 30).ToString(), v3->bounds().ToString()); - } -} - -TEST_F(BoxLayoutTest, FlexShrinkVerticalWithRemainder) { - BoxLayout* layout = new BoxLayout(BoxLayout::kVertical, 0, 0, 0); - host_->SetLayoutManager(layout); - View* v1 = new StaticSizedView(gfx::Size(20, 10)); - host_->AddChildView(v1); - View* v2 = new StaticSizedView(gfx::Size(20, 20)); - host_->AddChildView(v2); - View* v3 = new StaticSizedView(gfx::Size(20, 10)); - host_->AddChildView(v3); - host_->SetBounds(0, 0, 20, 20); - - std::vector<BoxLayout::MainAxisAlignment> main_alignments; - main_alignments.push_back(BoxLayout::MAIN_AXIS_ALIGNMENT_START); - main_alignments.push_back(BoxLayout::MAIN_AXIS_ALIGNMENT_CENTER); - main_alignments.push_back(BoxLayout::MAIN_AXIS_ALIGNMENT_END); - - for (size_t i = 0; i < main_alignments.size(); ++i) { - layout->set_main_axis_alignment(main_alignments[i]); - - // The first view shrinks by 1/3 of the excess, the second view shrinks by - // 2/3 of the excess and the third view should maintain its preferred size. - layout->SetFlexForView(v1, 1); - layout->SetFlexForView(v2, 2); - layout->ClearFlexForView(v3); - host_->Layout(); - EXPECT_EQ(gfx::Rect(0, 0, 20, 3).ToString(), v1->bounds().ToString()); - EXPECT_EQ(gfx::Rect(0, 3, 20, 7).ToString(), v2->bounds().ToString()); - EXPECT_EQ(gfx::Rect(0, 10, 20, 10).ToString(), v3->bounds().ToString()); - - // The second view shrinks to 2/3 of the excess, the third view shrinks to - // 1/3 of the excess and the first view should maintain its preferred size. - layout->ClearFlexForView(v1); - layout->SetFlexForView(v2, 2); - layout->SetFlexForView(v3, 1); - host_->Layout(); - EXPECT_EQ(gfx::Rect(0, 0, 20, 10).ToString(), v1->bounds().ToString()); - EXPECT_EQ(gfx::Rect(0, 10, 20, 7).ToString(), v2->bounds().ToString()); - EXPECT_EQ(gfx::Rect(0, 17, 20, 3).ToString(), v3->bounds().ToString()); - - // Each view shrinks equally to fit within the available space. - layout->SetFlexForView(v1, 1); - layout->SetFlexForView(v2, 1); - layout->SetFlexForView(v3, 1); - host_->Layout(); - EXPECT_EQ(gfx::Rect(0, 0, 20, 3).ToString(), v1->bounds().ToString()); - EXPECT_EQ(gfx::Rect(0, 3, 20, 14).ToString(), v2->bounds().ToString()); - EXPECT_EQ(gfx::Rect(0, 17, 20, 3).ToString(), v3->bounds().ToString()); - } -} - -TEST_F(BoxLayoutTest, MinimumCrossAxisVertical) { - BoxLayout* layout = new BoxLayout(BoxLayout::kVertical, 0, 0, 0); - host_->SetLayoutManager(layout); - View* v1 = new StaticSizedView(gfx::Size(20, 10)); - host_->AddChildView(v1); - layout->set_minimum_cross_axis_size(30); - - EXPECT_EQ(gfx::Size(30, 10), layout->GetPreferredSize(host_.get())); -} - -TEST_F(BoxLayoutTest, MinimumCrossAxisHorizontal) { - BoxLayout* layout = new BoxLayout(BoxLayout::kHorizontal, 0, 0, 0); - host_->SetLayoutManager(layout); - View* v1 = new StaticSizedView(gfx::Size(20, 10)); - host_->AddChildView(v1); - layout->set_minimum_cross_axis_size(30); - - EXPECT_EQ(gfx::Size(20, 30), layout->GetPreferredSize(host_.get())); -} - -} // namespace views
diff --git a/ui/views/layout/fill_layout.cc b/ui/views/layout/fill_layout.cc deleted file mode 100644 index 2137546..0000000 --- a/ui/views/layout/fill_layout.cc +++ /dev/null
@@ -1,41 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/layout/fill_layout.h" - -#include "base/logging.h" - -namespace views { - -FillLayout::FillLayout() {} - -FillLayout::~FillLayout() {} - -void FillLayout::Layout(View* host) { - if (!host->has_children()) - return; - - View* frame_view = host->child_at(0); - frame_view->SetBoundsRect(host->GetContentsBounds()); -} - -gfx::Size FillLayout::GetPreferredSize(const View* host) const { - if (!host->has_children()) - return gfx::Size(); - DCHECK_EQ(1, host->child_count()); - gfx::Rect rect(host->child_at(0)->GetPreferredSize()); - rect.Inset(-host->GetInsets()); - return rect.size(); -} - -int FillLayout::GetPreferredHeightForWidth(const View* host, int width) const { - if (!host->has_children()) - return 0; - DCHECK_EQ(1, host->child_count()); - const gfx::Insets insets = host->GetInsets(); - return host->child_at(0)->GetHeightForWidth(width - insets.width()) + - insets.height(); -} - -} // namespace views
diff --git a/ui/views/layout/fill_layout.h b/ui/views/layout/fill_layout.h deleted file mode 100644 index 7496f7c..0000000 --- a/ui/views/layout/fill_layout.h +++ /dev/null
@@ -1,38 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_LAYOUT_FILL_LAYOUT_H_ -#define UI_VIEWS_LAYOUT_FILL_LAYOUT_H_ - -#include "base/compiler_specific.h" -#include "ui/views/layout/layout_manager.h" -#include "ui/views/view.h" - -namespace views { - -/////////////////////////////////////////////////////////////////////////////// -// -// FillLayout -// A simple LayoutManager that causes the associated view's one child to be -// sized to match the bounds of its parent. -// -/////////////////////////////////////////////////////////////////////////////// -class VIEWS_EXPORT FillLayout : public LayoutManager { - public: - FillLayout(); - virtual ~FillLayout(); - - // Overridden from LayoutManager: - virtual void Layout(View* host) override; - virtual gfx::Size GetPreferredSize(const View* host) const override; - virtual int GetPreferredHeightForWidth(const View* host, - int width) const override; - - private: - DISALLOW_COPY_AND_ASSIGN(FillLayout); -}; - -} // namespace views - -#endif // UI_VIEWS_LAYOUT_FILL_LAYOUT_H_
diff --git a/ui/views/layout/grid_layout.cc b/ui/views/layout/grid_layout.cc deleted file mode 100644 index 99b39f2..0000000 --- a/ui/views/layout/grid_layout.cc +++ /dev/null
@@ -1,1064 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/layout/grid_layout.h" - -#include <algorithm> - -#include "base/logging.h" -#include "base/stl_util.h" -#include "ui/gfx/insets.h" -#include "ui/views/layout/layout_constants.h" -#include "ui/views/view.h" -#include "ui/views/window/dialog_delegate.h" - -namespace views { - -// LayoutElement ------------------------------------------------------ - -// A LayoutElement has a size and location along one axis. It contains -// methods that are used along both axis. -class LayoutElement { - public: - // Invokes ResetSize on all the layout elements. - template <class T> - static void ResetSizes(std::vector<T*>* elements) { - // Reset the layout width of each column. - for (typename std::vector<T*>::iterator i = elements->begin(); - i != elements->end(); ++i) { - (*i)->ResetSize(); - } - } - - // Sets the location of each element to be the sum of the sizes of the - // preceding elements. - template <class T> - static void CalculateLocationsFromSize(std::vector<T*>* elements) { - // Reset the layout width of each column. - int location = 0; - for (typename std::vector<T*>::iterator i = elements->begin(); - i != elements->end(); ++i) { - (*i)->SetLocation(location); - location += (*i)->Size(); - } - } - - // Distributes delta among the resizable elements. - // Each resizable element is given ResizePercent / total_percent * delta - // pixels extra of space. - template <class T> - static void DistributeDelta(int delta, std::vector<T*>* elements) { - if (delta == 0) - return; - - float total_percent = 0; - int resize_count = 0; - for (typename std::vector<T*>::iterator i = elements->begin(); - i != elements->end(); ++i) { - total_percent += (*i)->ResizePercent(); - if ((*i)->ResizePercent() > 0) - resize_count++; - } - if (total_percent == 0) { - // None of the elements are resizable, return. - return; - } - int remaining = delta; - int resized = resize_count; - for (typename std::vector<T*>::iterator i = elements->begin(); - i != elements->end(); ++i) { - T* element = *i; - if (element->ResizePercent() > 0) { - int to_give; - if (--resized == 0) { - to_give = remaining; - } else { - to_give = static_cast<int>(delta * - (element->resize_percent_ / total_percent)); - remaining -= to_give; - } - element->SetSize(element->Size() + to_give); - } - } - } - - // Returns the sum of the size of the elements from start to start + length. - template <class T> - static int TotalSize(int start, int length, std::vector<T*>* elements) { - DCHECK(start >= 0 && length > 0 && - start + length <= static_cast<int>(elements->size())); - int size = 0; - for (int i = start, max = start + length; i < max; ++i) { - size += (*elements)[i]->Size(); - } - return size; - } - - explicit LayoutElement(float resize_percent) - : resize_percent_(resize_percent) { - DCHECK(resize_percent >= 0); - } - - virtual ~LayoutElement() {} - - void SetLocation(int location) { - location_ = location; - } - - int Location() { - return location_; - } - - // Adjusts the size of this LayoutElement to be the max of the current size - // and the specified size. - virtual void AdjustSize(int size) { - size_ = std::max(size_, size); - } - - // Resets the size to the initial size. This sets the size to 0, but - // subclasses that have a different initial size should override. - virtual void ResetSize() { - SetSize(0); - } - - void SetSize(int size) { - size_ = size; - } - - int Size() { - return size_; - } - - void SetResizePercent(float percent) { - resize_percent_ = percent; - } - - float ResizePercent() { - return resize_percent_; - } - - bool IsResizable() { - return resize_percent_ > 0; - } - - private: - float resize_percent_; - int location_; - int size_; - - DISALLOW_COPY_AND_ASSIGN(LayoutElement); -}; - -// Column ------------------------------------------------------------- - -// As the name implies, this represents a Column. Column contains default -// values for views originating in this column. -class Column : public LayoutElement { - public: - Column(GridLayout::Alignment h_align, - GridLayout::Alignment v_align, - float resize_percent, - GridLayout::SizeType size_type, - int fixed_width, - int min_width, - bool is_padding) - : LayoutElement(resize_percent), - h_align_(h_align), - v_align_(v_align), - size_type_(size_type), - same_size_column_(-1), - fixed_width_(fixed_width), - min_width_(min_width), - is_padding_(is_padding), - master_column_(NULL) {} - - virtual ~Column() {} - - GridLayout::Alignment h_align() { return h_align_; } - GridLayout::Alignment v_align() { return v_align_; } - - virtual void ResetSize() override; - - private: - friend class ColumnSet; - friend class GridLayout; - - Column* GetLastMasterColumn(); - - // Determines the max size of all linked columns, and sets each column - // to that size. This should only be used for the master column. - void UnifySameSizedColumnSizes(); - - virtual void AdjustSize(int size) override; - - const GridLayout::Alignment h_align_; - const GridLayout::Alignment v_align_; - const GridLayout::SizeType size_type_; - int same_size_column_; - const int fixed_width_; - const int min_width_; - - const bool is_padding_; - - // If multiple columns have their sizes linked, one is the - // master column. The master column is identified by the - // master_column field being equal to itself. The master columns - // same_size_columns field contains the set of Columns with the - // the same size. Columns who are linked to other columns, but - // are not the master column have their master_column pointing to - // one of the other linked columns. Use the method GetLastMasterColumn - // to resolve the true master column. - std::vector<Column*> same_size_columns_; - Column* master_column_; - - DISALLOW_COPY_AND_ASSIGN(Column); -}; - -void Column::ResetSize() { - if (size_type_ == GridLayout::FIXED) { - SetSize(fixed_width_); - } else { - SetSize(min_width_); - } -} - -Column* Column::GetLastMasterColumn() { - if (master_column_ == NULL) { - return NULL; - } - if (master_column_ == this) { - return this; - } - return master_column_->GetLastMasterColumn(); -} - -void Column::UnifySameSizedColumnSizes() { - DCHECK(master_column_ == this); - - // Accumulate the size first. - int size = 0; - for (std::vector<Column*>::iterator i = same_size_columns_.begin(); - i != same_size_columns_.end(); ++i) { - size = std::max(size, (*i)->Size()); - } - - // Then apply it. - for (std::vector<Column*>::iterator i = same_size_columns_.begin(); - i != same_size_columns_.end(); ++i) { - (*i)->SetSize(size); - } -} - -void Column::AdjustSize(int size) { - if (size_type_ == GridLayout::USE_PREF) - LayoutElement::AdjustSize(size); -} - -// Row ------------------------------------------------------------- - -class Row : public LayoutElement { - public: - Row(int height, float resize_percent, ColumnSet* column_set) - : LayoutElement(resize_percent), - height_(height), - column_set_(column_set), - max_ascent_(0), - max_descent_(0) { - } - - virtual ~Row() {} - - virtual void ResetSize() override { - max_ascent_ = max_descent_ = 0; - SetSize(height_); - } - - ColumnSet* column_set() { - return column_set_; - } - - // Adjusts the size to accomodate the specified ascent/descent. - void AdjustSizeForBaseline(int ascent, int descent) { - max_ascent_ = std::max(ascent, max_ascent_); - max_descent_ = std::max(descent, max_descent_); - AdjustSize(max_ascent_ + max_descent_); - } - - int max_ascent() const { - return max_ascent_; - } - - int max_descent() const { - return max_descent_; - } - - private: - const int height_; - // The column set used for this row; null for padding rows. - ColumnSet* column_set_; - - int max_ascent_; - int max_descent_; - - DISALLOW_COPY_AND_ASSIGN(Row); -}; - -// ViewState ------------------------------------------------------------- - -// Identifies the location in the grid of a particular view, along with -// placement information and size information. -struct ViewState { - ViewState(ColumnSet* column_set, View* view, int start_col, int start_row, - int col_span, int row_span, GridLayout::Alignment h_align, - GridLayout::Alignment v_align, int pref_width, int pref_height) - : column_set(column_set), - view(view), - start_col(start_col), - start_row(start_row), - col_span(col_span), - row_span(row_span), - h_align(h_align), - v_align(v_align), - pref_width_fixed(pref_width > 0), - pref_height_fixed(pref_height > 0), - pref_width(pref_width), - pref_height(pref_height), - remaining_width(0), - remaining_height(0), - baseline(-1) { - DCHECK(view && start_col >= 0 && start_row >= 0 && col_span > 0 && - row_span > 0 && start_col < column_set->num_columns() && - (start_col + col_span) <= column_set->num_columns()); - } - - ColumnSet* const column_set; - View* const view; - const int start_col; - const int start_row; - const int col_span; - const int row_span; - const GridLayout::Alignment h_align; - const GridLayout::Alignment v_align; - - // If true, the pref_width/pref_height were explicitly set and the view's - // preferred size is ignored. - const bool pref_width_fixed; - const bool pref_height_fixed; - - // The preferred width/height. These are reset during the layout process. - int pref_width; - int pref_height; - - // Used during layout. Gives how much width/height has not yet been - // distributed to the columns/rows the view is in. - int remaining_width; - int remaining_height; - - // The baseline. Only used if the view is vertically aligned along the - // baseline. - int baseline; -}; - -static bool CompareByColumnSpan(const ViewState* v1, const ViewState* v2) { - return v1->col_span < v2->col_span; -} - -static bool CompareByRowSpan(const ViewState* v1, const ViewState* v2) { - return v1->row_span < v2->row_span; -} - -// ColumnSet ------------------------------------------------------------- - -ColumnSet::ColumnSet(int id) : id_(id) { -} - -ColumnSet::~ColumnSet() { - STLDeleteElements(&columns_); -} - -void ColumnSet::AddPaddingColumn(float resize_percent, int width) { - AddColumn(GridLayout::FILL, GridLayout::FILL, resize_percent, - GridLayout::FIXED, width, width, true); -} - -void ColumnSet::AddColumn(GridLayout::Alignment h_align, - GridLayout::Alignment v_align, - float resize_percent, - GridLayout::SizeType size_type, - int fixed_width, - int min_width) { - AddColumn(h_align, v_align, resize_percent, size_type, fixed_width, - min_width, false); -} - - -void ColumnSet::LinkColumnSizes(int first, ...) { - va_list marker; - va_start(marker, first); - DCHECK(first >= 0 && first < num_columns()); - for (int last = first, next = va_arg(marker, int); next != -1; - next = va_arg(marker, int)) { - DCHECK(next >= 0 && next < num_columns()); - columns_[last]->same_size_column_ = next; - last = next; - } - va_end(marker); -} - -void ColumnSet::AddColumn(GridLayout::Alignment h_align, - GridLayout::Alignment v_align, - float resize_percent, - GridLayout::SizeType size_type, - int fixed_width, - int min_width, - bool is_padding) { - Column* column = new Column(h_align, v_align, resize_percent, size_type, - fixed_width, min_width, is_padding); - columns_.push_back(column); -} - -void ColumnSet::AddViewState(ViewState* view_state) { - // view_states are ordered by column_span (in ascending order). - std::vector<ViewState*>::iterator i = std::lower_bound(view_states_.begin(), - view_states_.end(), - view_state, - CompareByColumnSpan); - view_states_.insert(i, view_state); -} - -void ColumnSet::CalculateMasterColumns() { - for (std::vector<Column*>::iterator i = columns_.begin(); - i != columns_.end(); ++i) { - Column* column = *i; - int same_size_column_index = column->same_size_column_; - if (same_size_column_index != -1) { - DCHECK(same_size_column_index >= 0 && - same_size_column_index < static_cast<int>(columns_.size())); - Column* master_column = column->master_column_; - Column* same_size_column = columns_[same_size_column_index]; - Column* same_size_column_master = same_size_column->master_column_; - if (master_column == NULL) { - // Current column is not linked to any other column. - if (same_size_column_master == NULL) { - // Both columns are not linked. - column->master_column_ = column; - same_size_column->master_column_ = column; - column->same_size_columns_.push_back(same_size_column); - column->same_size_columns_.push_back(column); - } else { - // Column to link to is linked with other columns. - // Add current column to list of linked columns in other columns - // master column. - same_size_column->GetLastMasterColumn()-> - same_size_columns_.push_back(column); - // And update the master column for the current column to that - // of the same sized column. - column->master_column_ = same_size_column; - } - } else { - // Current column is already linked with another column. - if (same_size_column_master == NULL) { - // Column to link with is not linked to any other columns. - // Update it's master_column. - same_size_column->master_column_ = column; - // Add linked column to list of linked column. - column->GetLastMasterColumn()->same_size_columns_. - push_back(same_size_column); - } else if (column->GetLastMasterColumn() != - same_size_column->GetLastMasterColumn()) { - // The two columns are already linked with other columns. - std::vector<Column*>* same_size_columns = - &(column->GetLastMasterColumn()->same_size_columns_); - std::vector<Column*>* other_same_size_columns = - &(same_size_column->GetLastMasterColumn()->same_size_columns_); - // Add all the columns from the others master to current columns - // master. - same_size_columns->insert(same_size_columns->end(), - other_same_size_columns->begin(), - other_same_size_columns->end()); - // The other master is no longer a master, clear its vector of - // linked columns, and reset its master_column. - other_same_size_columns->clear(); - same_size_column->GetLastMasterColumn()->master_column_ = column; - } - } - } - } - AccumulateMasterColumns(); -} - -void ColumnSet::AccumulateMasterColumns() { - DCHECK(master_columns_.empty()); - for (std::vector<Column*>::iterator i = columns_.begin(); - i != columns_.end(); ++i) { - Column* column = *i; - Column* master_column = column->GetLastMasterColumn(); - if (master_column && - std::find(master_columns_.begin(), master_columns_.end(), - master_column) == master_columns_.end()) { - master_columns_.push_back(master_column); - } - // At this point, GetLastMasterColumn may not == master_column - // (may have to go through a few Columns)_. Reset master_column to - // avoid hops. - column->master_column_ = master_column; - } -} - -void ColumnSet::UnifySameSizedColumnSizes() { - for (std::vector<Column*>::iterator i = master_columns_.begin(); - i != master_columns_.end(); ++i) { - (*i)->UnifySameSizedColumnSizes(); - } -} - -void ColumnSet::UpdateRemainingWidth(ViewState* view_state) { - for (int i = view_state->start_col, - max_col = view_state->start_col + view_state->col_span; - i < max_col; ++i) { - view_state->remaining_width -= columns_[i]->Size(); - } -} - -void ColumnSet::DistributeRemainingWidth(ViewState* view_state) { - // This is nearly the same as that for rows, but differs in so far as how - // Rows and Columns are treated. Rows have two states, resizable or not. - // Columns have three, resizable, USE_PREF or not resizable. This results - // in slightly different handling for distributing unaccounted size. - int width = view_state->remaining_width; - if (width <= 0) { - // The columns this view is in are big enough to accommodate it. - return; - } - - // Determine which columns are resizable, and which have a size type - // of USE_PREF. - int resizable_columns = 0; - int pref_size_columns = 0; - int start_col = view_state->start_col; - int max_col = view_state->start_col + view_state->col_span; - float total_resize = 0; - for (int i = start_col; i < max_col; ++i) { - if (columns_[i]->IsResizable()) { - total_resize += columns_[i]->ResizePercent(); - resizable_columns++; - } else if (columns_[i]->size_type_ == GridLayout::USE_PREF) { - pref_size_columns++; - } - } - - if (resizable_columns > 0) { - // There are resizable columns, give them the remaining width. The extra - // width is distributed using the resize values of each column. - int remaining_width = width; - for (int i = start_col, resize_i = 0; i < max_col; ++i) { - if (columns_[i]->IsResizable()) { - resize_i++; - int delta = (resize_i == resizable_columns) ? remaining_width : - static_cast<int>(width * columns_[i]->ResizePercent() / - total_resize); - remaining_width -= delta; - columns_[i]->SetSize(columns_[i]->Size() + delta); - } - } - } else if (pref_size_columns > 0) { - // None of the columns are resizable, distribute the width among those - // that use the preferred size. - int to_distribute = width / pref_size_columns; - for (int i = start_col; i < max_col; ++i) { - if (columns_[i]->size_type_ == GridLayout::USE_PREF) { - width -= to_distribute; - if (width < to_distribute) - to_distribute += width; - columns_[i]->SetSize(columns_[i]->Size() + to_distribute); - } - } - } -} - -int ColumnSet::LayoutWidth() { - int width = 0; - for (std::vector<Column*>::iterator i = columns_.begin(); - i != columns_.end(); ++i) { - width += (*i)->Size(); - } - return width; -} - -int ColumnSet::GetColumnWidth(int start_col, int col_span) { - return LayoutElement::TotalSize(start_col, col_span, &columns_); -} - -void ColumnSet::ResetColumnXCoordinates() { - LayoutElement::CalculateLocationsFromSize(&columns_); -} - -void ColumnSet::CalculateSize() { - gfx::Size pref; - // Reset the preferred and remaining sizes. - for (std::vector<ViewState*>::iterator i = view_states_.begin(); - i != view_states_.end(); ++i) { - ViewState* view_state = *i; - if (!view_state->pref_width_fixed || !view_state->pref_height_fixed) { - pref = view_state->view->GetPreferredSize(); - if (!view_state->pref_width_fixed) - view_state->pref_width = pref.width(); - if (!view_state->pref_height_fixed) - view_state->pref_height = pref.height(); - } - view_state->remaining_width = pref.width(); - view_state->remaining_height = pref.height(); - } - - // Let layout element reset the sizes for us. - LayoutElement::ResetSizes(&columns_); - - // Distribute the size of each view with a col span == 1. - std::vector<ViewState*>::iterator view_state_iterator = - view_states_.begin(); - for (; view_state_iterator != view_states_.end() && - (*view_state_iterator)->col_span == 1; ++view_state_iterator) { - ViewState* view_state = *view_state_iterator; - Column* column = columns_[view_state->start_col]; - column->AdjustSize(view_state->pref_width); - view_state->remaining_width -= column->Size(); - } - - // Make sure all linked columns have the same size. - UnifySameSizedColumnSizes(); - - // Distribute the size of each view with a column span > 1. - for (; view_state_iterator != view_states_.end(); ++view_state_iterator) { - ViewState* view_state = *view_state_iterator; - - // Update the remaining_width from columns this view_state touches. - UpdateRemainingWidth(view_state); - - // Distribute the remaining width. - DistributeRemainingWidth(view_state); - - // Update the size of linked columns. - // This may need to be combined with previous step. - UnifySameSizedColumnSizes(); - } -} - -void ColumnSet::Resize(int delta) { - LayoutElement::DistributeDelta(delta, &columns_); -} - -// GridLayout ------------------------------------------------------------- - -GridLayout::GridLayout(View* host) - : host_(host), - calculated_master_columns_(false), - remaining_row_span_(0), - current_row_(-1), - next_column_(0), - current_row_col_set_(NULL), - adding_view_(false) { - DCHECK(host); -} - -GridLayout::~GridLayout() { - STLDeleteElements(&column_sets_); - STLDeleteElements(&view_states_); - STLDeleteElements(&rows_); -} - -// static -GridLayout* GridLayout::CreatePanel(View* host) { - GridLayout* layout = new GridLayout(host); - layout->SetInsets(kPanelVertMargin, kButtonHEdgeMarginNew, - kPanelVertMargin, kButtonHEdgeMarginNew); - return layout; -} - -void GridLayout::SetInsets(int top, int left, int bottom, int right) { - insets_.Set(top, left, bottom, right); -} - -void GridLayout::SetInsets(const gfx::Insets& insets) { - insets_ = insets; -} - -ColumnSet* GridLayout::AddColumnSet(int id) { - DCHECK(GetColumnSet(id) == NULL); - ColumnSet* column_set = new ColumnSet(id); - column_sets_.push_back(column_set); - return column_set; -} - -ColumnSet* GridLayout::GetColumnSet(int id) { - for (std::vector<ColumnSet*>::iterator i = column_sets_.begin(); - i != column_sets_.end(); ++i) { - if ((*i)->id_ == id) { - return *i; - } - } - return NULL; -} - -void GridLayout::StartRowWithPadding(float vertical_resize, int column_set_id, - float padding_resize, int padding) { - AddPaddingRow(padding_resize, padding); - StartRow(vertical_resize, column_set_id); -} - -void GridLayout::StartRow(float vertical_resize, int column_set_id) { - ColumnSet* column_set = GetColumnSet(column_set_id); - DCHECK(column_set); - AddRow(new Row(0, vertical_resize, column_set)); -} - -void GridLayout::AddPaddingRow(float vertical_resize, int pixel_count) { - AddRow(new Row(pixel_count, vertical_resize, NULL)); -} - -void GridLayout::SkipColumns(int col_count) { - DCHECK(col_count > 0); - next_column_ += col_count; - DCHECK(current_row_col_set_ && - next_column_ <= current_row_col_set_->num_columns()); - SkipPaddingColumns(); -} - -void GridLayout::AddView(View* view) { - AddView(view, 1, 1); -} - -void GridLayout::AddView(View* view, int col_span, int row_span) { - DCHECK(current_row_col_set_ && - next_column_ < current_row_col_set_->num_columns()); - Column* column = current_row_col_set_->columns_[next_column_]; - AddView(view, col_span, row_span, column->h_align(), column->v_align()); -} - -void GridLayout::AddView(View* view, int col_span, int row_span, - Alignment h_align, Alignment v_align) { - AddView(view, col_span, row_span, h_align, v_align, 0, 0); -} - -void GridLayout::AddView(View* view, int col_span, int row_span, - Alignment h_align, Alignment v_align, - int pref_width, int pref_height) { - DCHECK(current_row_col_set_ && col_span > 0 && row_span > 0 && - (next_column_ + col_span) <= current_row_col_set_->num_columns()); - // We don't support baseline alignment of views spanning rows. Please add if - // you need it. - DCHECK(v_align != BASELINE || row_span == 1); - ViewState* state = - new ViewState(current_row_col_set_, view, next_column_, current_row_, - col_span, row_span, h_align, v_align, pref_width, - pref_height); - AddViewState(state); -} - -static void CalculateSize(int pref_size, GridLayout::Alignment alignment, - int* location, int* size) { - if (alignment != GridLayout::FILL) { - int available_size = *size; - *size = std::min(*size, pref_size); - switch (alignment) { - case GridLayout::LEADING: - // Nothing to do, location already points to start. - break; - case GridLayout::BASELINE: // If we were asked to align on baseline, but - // the view doesn't have a baseline, fall back - // to center. - case GridLayout::CENTER: - *location += (available_size - *size) / 2; - break; - case GridLayout::TRAILING: - *location = *location + available_size - *size; - break; - default: - NOTREACHED(); - } - } -} - -void GridLayout::Installed(View* host) { - DCHECK(host_ == host); -} - -void GridLayout::Uninstalled(View* host) { - DCHECK(host_ == host); -} - -void GridLayout::ViewAdded(View* host, View* view) { - DCHECK(host_ == host && adding_view_); -} - -void GridLayout::ViewRemoved(View* host, View* view) { - DCHECK(host_ == host); -} - -void GridLayout::Layout(View* host) { - DCHECK(host_ == host); - // SizeRowsAndColumns sets the size and location of each row/column, but - // not of the views. - gfx::Size pref; - SizeRowsAndColumns(true, host_->width(), host_->height(), &pref); - - // Size each view. - for (std::vector<ViewState*>::iterator i = view_states_.begin(); - i != view_states_.end(); ++i) { - ViewState* view_state = *i; - ColumnSet* column_set = view_state->column_set; - View* view = (*i)->view; - DCHECK(view); - int x = column_set->columns_[view_state->start_col]->Location() + - insets_.left(); - int width = column_set->GetColumnWidth(view_state->start_col, - view_state->col_span); - CalculateSize(view_state->pref_width, view_state->h_align, - &x, &width); - int y = rows_[view_state->start_row]->Location() + insets_.top(); - int height = LayoutElement::TotalSize(view_state->start_row, - view_state->row_span, &rows_); - if (view_state->v_align == BASELINE && view_state->baseline != -1) { - y += rows_[view_state->start_row]->max_ascent() - view_state->baseline; - height = view_state->pref_height; - } else { - CalculateSize(view_state->pref_height, view_state->v_align, &y, &height); - } - view->SetBounds(x, y, width, height); - } -} - -gfx::Size GridLayout::GetPreferredSize(const View* host) const { - DCHECK(host_ == host); - gfx::Size out; - SizeRowsAndColumns(false, 0, 0, &out); - out.SetSize(std::max(out.width(), minimum_size_.width()), - std::max(out.height(), minimum_size_.height())); - return out; -} - -int GridLayout::GetPreferredHeightForWidth(const View* host, int width) const { - DCHECK(host_ == host); - gfx::Size pref; - SizeRowsAndColumns(false, width, 0, &pref); - return pref.height(); -} - -void GridLayout::SizeRowsAndColumns(bool layout, int width, int height, - gfx::Size* pref) const { - // Make sure the master columns have been calculated. - CalculateMasterColumnsIfNecessary(); - pref->SetSize(0, 0); - if (rows_.empty()) - return; - - // Calculate the preferred width of each of the columns. Some views' - // preferred heights are derived from their width, as such we need to - // calculate the size of the columns first. - for (std::vector<ColumnSet*>::iterator i = column_sets_.begin(); - i != column_sets_.end(); ++i) { - (*i)->CalculateSize(); - pref->set_width(std::max(pref->width(), (*i)->LayoutWidth())); - } - pref->set_width(pref->width() + insets_.width()); - - // Go over the columns again and set them all to the size we settled for. - width = width ? width : pref->width(); - for (std::vector<ColumnSet*>::iterator i = column_sets_.begin(); - i != column_sets_.end(); ++i) { - // We're doing a layout, divy up any extra space. - (*i)->Resize(width - (*i)->LayoutWidth() - insets_.left() - - insets_.right()); - // And reset the x coordinates. - (*i)->ResetColumnXCoordinates(); - } - - // Reset the height of each row. - LayoutElement::ResetSizes(&rows_); - - // Do the following: - // . If the view is aligned along it's baseline, obtain the baseline from the - // view and update the rows ascent/descent. - // . Reset the remaining_height of each view state. - // . If the width the view will be given is different than it's pref, ask - // for the height given a particularly width. - for (std::vector<ViewState*>::iterator i= view_states_.begin(); - i != view_states_.end() ; ++i) { - ViewState* view_state = *i; - view_state->remaining_height = view_state->pref_height; - - if (view_state->v_align == BASELINE) - view_state->baseline = view_state->view->GetBaseline(); - - if (view_state->h_align == FILL) { - // The view is resizable. As the pref height may vary with the width, - // ask for the pref again. - int actual_width = - view_state->column_set->GetColumnWidth(view_state->start_col, - view_state->col_span); - if (actual_width != view_state->pref_width && - !view_state->pref_height_fixed) { - // The width this view will get differs from its preferred. Some Views - // pref height varies with its width; ask for the preferred again. - view_state->pref_height = - view_state->view->GetHeightForWidth(actual_width); - view_state->remaining_height = view_state->pref_height; - } - } - } - - // Update the height/ascent/descent of each row from the views. - std::vector<ViewState*>::iterator view_states_iterator = view_states_.begin(); - for (; view_states_iterator != view_states_.end() && - (*view_states_iterator)->row_span == 1; ++view_states_iterator) { - ViewState* view_state = *view_states_iterator; - Row* row = rows_[view_state->start_row]; - row->AdjustSize(view_state->remaining_height); - if (view_state->baseline != -1 && - view_state->baseline <= view_state->pref_height) { - row->AdjustSizeForBaseline(view_state->baseline, - view_state->pref_height - view_state->baseline); - } - view_state->remaining_height = 0; - } - - // Distribute the height of each view with a row span > 1. - for (; view_states_iterator != view_states_.end(); ++view_states_iterator) { - ViewState* view_state = *view_states_iterator; - - // Update the remaining_width from columns this view_state touches. - UpdateRemainingHeightFromRows(view_state); - - // Distribute the remaining height. - DistributeRemainingHeight(view_state); - } - - // Update the location of each of the rows. - LayoutElement::CalculateLocationsFromSize(&rows_); - - // We now know the preferred height, set it here. - pref->set_height(rows_[rows_.size() - 1]->Location() + - rows_[rows_.size() - 1]->Size() + insets_.height()); - - if (layout && height != pref->height()) { - // We're doing a layout, and the height differs from the preferred height, - // divy up the extra space. - LayoutElement::DistributeDelta(height - pref->height(), &rows_); - - // Reset y locations. - LayoutElement::CalculateLocationsFromSize(&rows_); - } -} - -void GridLayout::CalculateMasterColumnsIfNecessary() const { - if (!calculated_master_columns_) { - calculated_master_columns_ = true; - for (std::vector<ColumnSet*>::iterator i = column_sets_.begin(); - i != column_sets_.end(); ++i) { - (*i)->CalculateMasterColumns(); - } - } -} - -void GridLayout::AddViewState(ViewState* view_state) { - DCHECK(view_state->view && (view_state->view->parent() == NULL || - view_state->view->parent() == host_)); - if (!view_state->view->parent()) { - adding_view_ = true; - host_->AddChildView(view_state->view); - adding_view_ = false; - } - remaining_row_span_ = std::max(remaining_row_span_, view_state->row_span); - next_column_ += view_state->col_span; - current_row_col_set_->AddViewState(view_state); - // view_states are ordered by row_span (in ascending order). - std::vector<ViewState*>::iterator i = std::lower_bound(view_states_.begin(), - view_states_.end(), - view_state, - CompareByRowSpan); - view_states_.insert(i, view_state); - SkipPaddingColumns(); -} - -void GridLayout::AddRow(Row* row) { - current_row_++; - remaining_row_span_--; - // GridLayout requires that if you add a View with a row span you use the same - // column set for each of the rows the view lands it. This DCHECK verifies - // that. - DCHECK(remaining_row_span_ <= 0 || - row->column_set() == NULL || - row->column_set() == GetLastValidColumnSet()); - next_column_ = 0; - rows_.push_back(row); - current_row_col_set_ = row->column_set(); - SkipPaddingColumns(); -} - -void GridLayout::UpdateRemainingHeightFromRows(ViewState* view_state) const { - for (int i = 0, start_row = view_state->start_row; - i < view_state->row_span; ++i) { - view_state->remaining_height -= rows_[i + start_row]->Size(); - } -} - -void GridLayout::DistributeRemainingHeight(ViewState* view_state) const { - int height = view_state->remaining_height; - if (height <= 0) - return; - - // Determine the number of resizable rows the view touches. - int resizable_rows = 0; - int start_row = view_state->start_row; - int max_row = view_state->start_row + view_state->row_span; - for (int i = start_row; i < max_row; ++i) { - if (rows_[i]->IsResizable()) { - resizable_rows++; - } - } - - if (resizable_rows > 0) { - // There are resizable rows, give the remaining height to them. - int to_distribute = height / resizable_rows; - for (int i = start_row; i < max_row; ++i) { - if (rows_[i]->IsResizable()) { - height -= to_distribute; - if (height < to_distribute) { - // Give all slop to the last column. - to_distribute += height; - } - rows_[i]->SetSize(rows_[i]->Size() + to_distribute); - } - } - } else { - // None of the rows are resizable, divy the remaining height up equally - // among all rows the view touches. - int each_row_height = height / view_state->row_span; - for (int i = start_row; i < max_row; ++i) { - height -= each_row_height; - if (height < each_row_height) - each_row_height += height; - rows_[i]->SetSize(rows_[i]->Size() + each_row_height); - } - view_state->remaining_height = 0; - } -} - -void GridLayout::SkipPaddingColumns() { - if (!current_row_col_set_) - return; - while (next_column_ < current_row_col_set_->num_columns() && - current_row_col_set_->columns_[next_column_]->is_padding_) { - next_column_++; - } -} - -ColumnSet* GridLayout::GetLastValidColumnSet() { - for (int i = current_row_ - 1; i >= 0; --i) { - if (rows_[i]->column_set()) - return rows_[i]->column_set(); - } - return NULL; -} - -} // namespace views
diff --git a/ui/views/layout/grid_layout.h b/ui/views/layout/grid_layout.h deleted file mode 100644 index ad228d5..0000000 --- a/ui/views/layout/grid_layout.h +++ /dev/null
@@ -1,376 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_LAYOUT_GRID_LAYOUT_H_ -#define UI_VIEWS_LAYOUT_GRID_LAYOUT_H_ - -#include <string> -#include <vector> - -#include "base/compiler_specific.h" -#include "ui/gfx/insets.h" -#include "ui/views/layout/layout_manager.h" -#include "ui/views/view.h" - -// GridLayout is a LayoutManager that positions child Views in a grid. You -// define the structure of the Grid first, then add the Views. -// The following creates a trivial grid with two columns separated by -// a column with padding: -// ColumnSet* columns = layout->AddColumnSet(0); // Give this column an -// // identifier of 0. -// columns->AddColumn(FILL, // Views are horizontally resized to fill column. -// FILL, // Views starting in this column are vertically -// // resized. -// 1, // This column has a resize weight of 1. -// USE_PREF, // Use the preferred size of the view. -// 0, // Ignored for USE_PREF. -// 0); // A minimum width of 0. -// columns->AddPaddingColumn(0, // The padding column is not resizable. -// 10); // And has a width of 10 pixels. -// columns->AddColumn(FILL, FILL, 0, USE_PREF, 0, 0); -// Now add the views: -// // First start a row. -// layout->StartRow(0, // This row isn't vertically resizable. -// 0); // The column set to use for this row. -// layout->AddView(v1); -// Notice you need not skip over padding columns, that's done for you. -// layout->AddView(v2); -// -// When adding a Column you give it the default alignment for all views -// originating in that column. You can override this for specific views -// when adding them. For example, the following forces a View to have -// a horizontal and vertical alignment of leading regardless of that defined -// for the column: -// layout->AddView(v1, 1, 1, LEADING, LEADING); -// -// If the View using GridLayout is given a size bigger than the preferred, -// columns and rows with a resize percent > 0 are resized. Each column/row -// is given resize_percent / total_resize_percent * extra_pixels extra -// pixels. Only Views with an Alignment of FILL are given extra space, others -// are aligned in the provided space. -// -// GridLayout allows you to define multiple column sets. When you start a -// new row you specify the id of the column set the row is to use. -// -// GridLayout allows you to force columns to have the same width. This is -// done using the LinkColumnSizes method. -// -// AddView takes care of adding the View to the View the GridLayout was -// created with. -namespace views { - -class Column; -class ColumnSet; -class Row; -class View; - -struct ViewState; - -class VIEWS_EXPORT GridLayout : public LayoutManager { - public: - // An enumeration of the possible alignments supported by GridLayout. - enum Alignment { - // Leading equates to left along the horizontal axis, and top along the - // vertical axis. - LEADING, - - // Centers the view along the axis. - CENTER, - - // Trailing equals to right along the horizontal axis, and bottom along - // the vertical axis. - TRAILING, - - // The view is resized to fill the space. - FILL, - - // The view is aligned along the baseline. This is only valid for the - // vertical axis. - BASELINE - }; - - // An enumeration of the possible ways the size of a column may be obtained. - enum SizeType { - // The column size is fixed. - FIXED, - - // The preferred size of the view is used to determine the column size. - USE_PREF - }; - - explicit GridLayout(View* host); - virtual ~GridLayout(); - - // Creates a GridLayout with kPanel*Margin insets. - static GridLayout* CreatePanel(View* host); - - // Sets the insets. All views are placed relative to these offsets. - void SetInsets(int top, int left, int bottom, int right); - void SetInsets(const gfx::Insets& insets); - - // Creates a new column set with the specified id and returns it. - // The id is later used when starting a new row. - // GridLayout takes ownership of the ColumnSet and will delete it when - // the GridLayout is deleted. - ColumnSet* AddColumnSet(int id); - - // Returns the column set for the specified id, or NULL if one doesn't exist. - ColumnSet* GetColumnSet(int id); - - // Adds a padding row. Padding rows typically don't have any views, and - // but are used to provide vertical white space between views. - // Size specifies the height of the row. - void AddPaddingRow(float vertical_resize, int size); - - // A convenience for AddPaddingRow followed by StartRow. - void StartRowWithPadding(float vertical_resize, int column_set_id, - float padding_resize, int padding); - - // Starts a new row with the specified column set. - void StartRow(float vertical_resize, int column_set_id); - - // Advances past columns. Use this when the current column should not - // contain any views. - void SkipColumns(int col_count); - - // Adds a view using the default alignment from the column. The added - // view has a column and row span of 1. - // As a convenience this adds the view to the host. The view becomes owned - // by the host, and NOT this GridLayout. - void AddView(View* view); - - // Adds a view using the default alignment from the column. - // As a convenience this adds the view to the host. The view becomes owned - // by the host, and NOT this GridLayout. - void AddView(View* view, int col_span, int row_span); - - // Adds a view with the specified alignment and spans. - // As a convenience this adds the view to the host. The view becomes owned - // by the host, and NOT this GridLayout. - void AddView(View* view, int col_span, int row_span, Alignment h_align, - Alignment v_align); - - // Adds a view with the specified alignment and spans. If - // pref_width/pref_height is > 0 then the preferred width/height of the view - // is fixed to the specified value. - // As a convenience this adds the view to the host. The view becomes owned - // by the host, and NOT this GridLayout. - void AddView(View* view, int col_span, int row_span, - Alignment h_align, Alignment v_align, - int pref_width, int pref_height); - - // Notification we've been installed on a particular host. Checks that host - // is the same as the View supplied in the constructor. - virtual void Installed(View* host) override; - - // Notification we've been uninstalled on a particular host. Checks that host - // is the same as the View supplied in the constructor. - virtual void Uninstalled(View* host) override; - - // Notification that a view has been added. - virtual void ViewAdded(View* host, View* view) override; - - // Notification that a view has been removed. - virtual void ViewRemoved(View* host, View* view) override; - - // Layouts out the components. - virtual void Layout(View* host) override; - - // Returns the preferred size for the GridLayout. - virtual gfx::Size GetPreferredSize(const View* host) const override; - - virtual int GetPreferredHeightForWidth(const View* host, - int width) const override; - - void set_minimum_size(const gfx::Size& size) { minimum_size_ = size; } - - private: - // As both Layout and GetPreferredSize need to do nearly the same thing, - // they both call into this method. This sizes the Columns/Rows as - // appropriate. If layout is true, width/height give the width/height the - // of the host, otherwise they are ignored. - void SizeRowsAndColumns(bool layout, - int width, - int height, - gfx::Size* pref) const; - - // Calculates the master columns of all the column sets. See Column for - // a description of what a master column is. - void CalculateMasterColumnsIfNecessary() const; - - // This is called internally from AddView. It adds the ViewState to the - // appropriate structures, and updates internal fields such as next_column_. - void AddViewState(ViewState* view_state); - - // Adds the Row to rows_, as well as updating next_column_, - // current_row_col_set ... - void AddRow(Row* row); - - // As the name says, updates the remaining_height of the ViewState for - // all Rows the supplied ViewState touches. - void UpdateRemainingHeightFromRows(ViewState* state) const; - - // If the view state's remaining height is > 0, it is distributed among - // the rows the view state touches. This is used during layout to make - // sure the Rows can accommodate a view. - void DistributeRemainingHeight(ViewState* state) const; - - // Advances next_column_ past any padding columns. - void SkipPaddingColumns(); - - // Returns the column set of the last non-padding row. - ColumnSet* GetLastValidColumnSet(); - - // The view we were created with. We don't own this. - View* const host_; - - // Whether or not we've calculated the master/linked columns. - mutable bool calculated_master_columns_; - - // Used to verify a view isn't added with a row span that expands into - // another column structure. - int remaining_row_span_; - - // Current row. - int current_row_; - - // Current column. - int next_column_; - - // Column set for the current row. This is null for padding rows. - ColumnSet* current_row_col_set_; - - // Insets. - gfx::Insets insets_; - - // Set to true when adding a View. - bool adding_view_; - - // ViewStates. This is ordered by row_span in ascending order. - mutable std::vector<ViewState*> view_states_; - - // ColumnSets. - mutable std::vector<ColumnSet*> column_sets_; - - // Rows. - mutable std::vector<Row*> rows_; - - // Minimum preferred size. - gfx::Size minimum_size_; - - DISALLOW_COPY_AND_ASSIGN(GridLayout); -}; - -// ColumnSet is used to define a set of columns. GridLayout may have any -// number of ColumnSets. You don't create a ColumnSet directly, instead -// use the AddColumnSet method of GridLayout. -class VIEWS_EXPORT ColumnSet { - public: - ~ColumnSet(); - - // Adds a column for padding. When adding views, padding columns are - // automatically skipped. For example, if you create a column set with - // two columns separated by a padding column, the second AddView automatically - // skips past the padding column. That is, to add two views, do: - // layout->AddView(v1); layout->AddView(v2);, not: - // layout->AddView(v1); layout->SkipColumns(1); layout->AddView(v2); - // See class description for details on |resize_percent|. - void AddPaddingColumn(float resize_percent, int width); - - // Adds a column. The alignment gives the default alignment for views added - // with no explicit alignment. fixed_width gives a specific width for the - // column, and is only used if size_type == FIXED. min_width gives the - // minimum width for the column. - // - // If none of the columns in a columnset are resizable, the views are only - // made as wide as the widest views in each column, even if extra space is - // provided. In other words, GridLayout does not automatically resize views - // unless the column is marked as resizable. - // See class description for details on |resize_percent|. - void AddColumn(GridLayout::Alignment h_align, - GridLayout::Alignment v_align, - float resize_percent, - GridLayout::SizeType size_type, - int fixed_width, - int min_width); - - // Forces the specified columns to have the same size. The size of - // linked columns is that of the max of the specified columns. This - // must end with -1. For example, the following forces the first and - // second column to have the same size: - // LinkColumnSizes(0, 1, -1); - void LinkColumnSizes(int first, ...); - - // ID of this ColumnSet. - int id() const { return id_; } - - int num_columns() const { return static_cast<int>(columns_.size()); } - - private: - friend class GridLayout; - - explicit ColumnSet(int id); - - void AddColumn(GridLayout::Alignment h_align, - GridLayout::Alignment v_align, - float resize_percent, - GridLayout::SizeType size_type, - int fixed_width, - int min_width, - bool is_padding); - - void AddViewState(ViewState* view_state); - - // Set description of these. - void CalculateMasterColumns(); - void AccumulateMasterColumns(); - - // Sets the size of each linked column to be the same. - void UnifySameSizedColumnSizes(); - - // Updates the remaining width field of the ViewState from that of the - // columns the view spans. - void UpdateRemainingWidth(ViewState* view_state); - - // Makes sure the columns touched by view state are big enough for the - // view. - void DistributeRemainingWidth(ViewState* view_state); - - // Returns the total size needed for this ColumnSet. - int LayoutWidth(); - - // Returns the width of the specified columns. - int GetColumnWidth(int start_col, int col_span); - - // Updates the x coordinate of each column from the previous ones. - // NOTE: this doesn't include the insets. - void ResetColumnXCoordinates(); - - // Calculate the preferred width of each view in this column set, as well - // as updating the remaining_width. - void CalculateSize(); - - // Distributes delta amoung the resizable columns. - void Resize(int delta); - - // ID for this columnset. - const int id_; - - // The columns. - std::vector<Column*> columns_; - - // The ViewStates. This is sorted based on column_span in ascending - // order. - std::vector<ViewState*> view_states_; - - // The master column of those columns that are linked. See Column - // for a description of what the master column is. - std::vector<Column*> master_columns_; - - DISALLOW_COPY_AND_ASSIGN(ColumnSet); -}; - -} // namespace views - -#endif // UI_VIEWS_LAYOUT_GRID_LAYOUT_H_
diff --git a/ui/views/layout/grid_layout_unittest.cc b/ui/views/layout/grid_layout_unittest.cc deleted file mode 100644 index 72f5053..0000000 --- a/ui/views/layout/grid_layout_unittest.cc +++ /dev/null
@@ -1,669 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/layout/grid_layout.h" - -#include "base/compiler_specific.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/views/view.h" - -namespace views { - -void ExpectViewBoundsEquals(int x, int y, int w, int h, - const View* view) { - EXPECT_EQ(x, view->x()); - EXPECT_EQ(y, view->y()); - EXPECT_EQ(w, view->width()); - EXPECT_EQ(h, view->height()); -} - -class SettableSizeView : public View { - public: - explicit SettableSizeView(const gfx::Size& pref) { - pref_ = pref; - } - - virtual gfx::Size GetPreferredSize() const override { - return pref_; - } - - private: - gfx::Size pref_; -}; - -// A view with fixed circumference that trades height for width. -class FlexibleView : public View { - public: - explicit FlexibleView(int circumference) { - circumference_ = circumference; - } - - virtual gfx::Size GetPreferredSize() const override { - return gfx::Size(0, circumference_ / 2); - } - - virtual int GetHeightForWidth(int width) const override { - return std::max(0, circumference_ / 2 - width); - } - - private: - int circumference_; -}; - -class GridLayoutTest : public testing::Test { - public: - GridLayoutTest() : layout(&host) {} - - void RemoveAll() { - for (int i = host.child_count() - 1; i >= 0; i--) - host.RemoveChildView(host.child_at(i)); - } - - void GetPreferredSize() { - pref = layout.GetPreferredSize(&host); - } - - gfx::Size pref; - gfx::Rect bounds; - View host; - GridLayout layout; -}; - -class GridLayoutAlignmentTest : public testing::Test { - public: - GridLayoutAlignmentTest() - : v1(gfx::Size(10, 20)), - layout(&host) {} - - void RemoveAll() { - for (int i = host.child_count() - 1; i >= 0; i--) - host.RemoveChildView(host.child_at(i)); - } - - void TestAlignment(GridLayout::Alignment alignment, gfx::Rect* bounds) { - ColumnSet* c1 = layout.AddColumnSet(0); - c1->AddColumn(alignment, alignment, 1, GridLayout::USE_PREF, 0, 0); - layout.StartRow(1, 0); - layout.AddView(&v1); - gfx::Size pref = layout.GetPreferredSize(&host); - EXPECT_EQ(gfx::Size(10, 20), pref); - host.SetBounds(0, 0, 100, 100); - layout.Layout(&host); - *bounds = v1.bounds(); - RemoveAll(); - } - - View host; - SettableSizeView v1; - GridLayout layout; -}; - -TEST_F(GridLayoutAlignmentTest, Fill) { - gfx::Rect bounds; - TestAlignment(GridLayout::FILL, &bounds); - EXPECT_EQ(gfx::Rect(0, 0, 100, 100), bounds); -} - -TEST_F(GridLayoutAlignmentTest, Leading) { - gfx::Rect bounds; - TestAlignment(GridLayout::LEADING, &bounds); - EXPECT_EQ(gfx::Rect(0, 0, 10, 20), bounds); -} - -TEST_F(GridLayoutAlignmentTest, Center) { - gfx::Rect bounds; - TestAlignment(GridLayout::CENTER, &bounds); - EXPECT_EQ(gfx::Rect(45, 40, 10, 20), bounds); -} - -TEST_F(GridLayoutAlignmentTest, Trailing) { - gfx::Rect bounds; - TestAlignment(GridLayout::TRAILING, &bounds); - EXPECT_EQ(gfx::Rect(90, 80, 10, 20), bounds); -} - -TEST_F(GridLayoutTest, TwoColumns) { - SettableSizeView v1(gfx::Size(10, 20)); - SettableSizeView v2(gfx::Size(20, 20)); - ColumnSet* c1 = layout.AddColumnSet(0); - c1->AddColumn(GridLayout::LEADING, GridLayout::LEADING, - 0, GridLayout::USE_PREF, 0, 0); - c1->AddColumn(GridLayout::LEADING, GridLayout::LEADING, - 0, GridLayout::USE_PREF, 0, 0); - layout.StartRow(0, 0); - layout.AddView(&v1); - layout.AddView(&v2); - - GetPreferredSize(); - EXPECT_EQ(gfx::Size(30, 20), pref); - - host.SetBounds(0, 0, pref.width(), pref.height()); - layout.Layout(&host); - ExpectViewBoundsEquals(0, 0, 10, 20, &v1); - ExpectViewBoundsEquals(10, 0, 20, 20, &v2); - - RemoveAll(); -} - -TEST_F(GridLayoutTest, ColSpan1) { - SettableSizeView v1(gfx::Size(100, 20)); - SettableSizeView v2(gfx::Size(10, 40)); - ColumnSet* c1 = layout.AddColumnSet(0); - c1->AddColumn(GridLayout::LEADING, GridLayout::LEADING, - 0, GridLayout::USE_PREF, 0, 0); - c1->AddColumn(GridLayout::LEADING, GridLayout::LEADING, - 1, GridLayout::USE_PREF, 0, 0); - layout.StartRow(0, 0); - layout.AddView(&v1, 2, 1); - layout.StartRow(0, 0); - layout.AddView(&v2); - - GetPreferredSize(); - EXPECT_EQ(gfx::Size(100, 60), pref); - - host.SetBounds(0, 0, pref.width(), pref.height()); - layout.Layout(&host); - ExpectViewBoundsEquals(0, 0, 100, 20, &v1); - ExpectViewBoundsEquals(0, 20, 10, 40, &v2); - - RemoveAll(); -} - -TEST_F(GridLayoutTest, ColSpan2) { - SettableSizeView v1(gfx::Size(100, 20)); - SettableSizeView v2(gfx::Size(10, 20)); - ColumnSet* c1 = layout.AddColumnSet(0); - c1->AddColumn(GridLayout::LEADING, GridLayout::LEADING, - 1, GridLayout::USE_PREF, 0, 0); - c1->AddColumn(GridLayout::LEADING, GridLayout::LEADING, - 0, GridLayout::USE_PREF, 0, 0); - layout.StartRow(0, 0); - layout.AddView(&v1, 2, 1); - layout.StartRow(0, 0); - layout.SkipColumns(1); - layout.AddView(&v2); - - GetPreferredSize(); - EXPECT_EQ(gfx::Size(100, 40), pref); - - host.SetBounds(0, 0, pref.width(), pref.height()); - layout.Layout(&host); - ExpectViewBoundsEquals(0, 0, 100, 20, &v1); - ExpectViewBoundsEquals(90, 20, 10, 20, &v2); - - RemoveAll(); -} - -TEST_F(GridLayoutTest, ColSpan3) { - SettableSizeView v1(gfx::Size(100, 20)); - SettableSizeView v2(gfx::Size(10, 20)); - SettableSizeView v3(gfx::Size(10, 20)); - ColumnSet* c1 = layout.AddColumnSet(0); - c1->AddColumn(GridLayout::LEADING, GridLayout::LEADING, - 0, GridLayout::USE_PREF, 0, 0); - c1->AddColumn(GridLayout::LEADING, GridLayout::LEADING, - 0, GridLayout::USE_PREF, 0, 0); - layout.StartRow(0, 0); - layout.AddView(&v1, 2, 1); - layout.StartRow(0, 0); - layout.AddView(&v2); - layout.AddView(&v3); - - GetPreferredSize(); - EXPECT_EQ(gfx::Size(100, 40), pref); - - host.SetBounds(0, 0, pref.width(), pref.height()); - layout.Layout(&host); - ExpectViewBoundsEquals(0, 0, 100, 20, &v1); - ExpectViewBoundsEquals(0, 20, 10, 20, &v2); - ExpectViewBoundsEquals(50, 20, 10, 20, &v3); - - RemoveAll(); -} - - -TEST_F(GridLayoutTest, ColSpan4) { - ColumnSet* set = layout.AddColumnSet(0); - - set->AddColumn(GridLayout::LEADING, GridLayout::LEADING, 0, - GridLayout::USE_PREF, 0, 0); - set->AddColumn(GridLayout::LEADING, GridLayout::LEADING, 0, - GridLayout::USE_PREF, 0, 0); - - SettableSizeView v1(gfx::Size(10, 10)); - SettableSizeView v2(gfx::Size(10, 10)); - SettableSizeView v3(gfx::Size(25, 20)); - layout.StartRow(0, 0); - layout.AddView(&v1); - layout.AddView(&v2); - layout.StartRow(0, 0); - layout.AddView(&v3, 2, 1); - - GetPreferredSize(); - EXPECT_EQ(gfx::Size(25, 30), pref); - - host.SetBounds(0, 0, pref.width(), pref.height()); - layout.Layout(&host); - ExpectViewBoundsEquals(0, 0, 10, 10, &v1); - ExpectViewBoundsEquals(12, 0, 10, 10, &v2); - ExpectViewBoundsEquals(0, 10, 25, 20, &v3); - - RemoveAll(); -} - -// Verifies the sizing of a view that doesn't start in the first column -// and has a column span > 1 (crbug.com/254092). -TEST_F(GridLayoutTest, ColSpanStartSecondColumn) { - ColumnSet* set = layout.AddColumnSet(0); - - set->AddColumn(GridLayout::FILL, GridLayout::FILL, 0, - GridLayout::USE_PREF, 0, 0); - set->AddColumn(GridLayout::FILL, GridLayout::FILL, 0, - GridLayout::USE_PREF, 0, 0); - set->AddColumn(GridLayout::FILL, GridLayout::FILL, 0, - GridLayout::FIXED, 10, 0); - - SettableSizeView v1(gfx::Size(10, 10)); - SettableSizeView v2(gfx::Size(20, 10)); - - layout.StartRow(0, 0); - layout.AddView(&v1); - layout.AddView(&v2, 2, 1); - - GetPreferredSize(); - EXPECT_EQ(gfx::Size(30, 10), pref); - - host.SetBounds(0, 0, pref.width(), pref.height()); - layout.Layout(&host); - ExpectViewBoundsEquals(0, 0, 10, 10, &v1); - ExpectViewBoundsEquals(10, 0, 20, 10, &v2); - - RemoveAll(); -} - -TEST_F(GridLayoutTest, SameSizeColumns) { - SettableSizeView v1(gfx::Size(50, 20)); - SettableSizeView v2(gfx::Size(10, 10)); - ColumnSet* c1 = layout.AddColumnSet(0); - c1->AddColumn(GridLayout::LEADING, GridLayout::LEADING, - 0, GridLayout::USE_PREF, 0, 0); - c1->AddColumn(GridLayout::LEADING, GridLayout::LEADING, - 0, GridLayout::USE_PREF, 0, 0); - c1->LinkColumnSizes(0, 1, -1); - layout.StartRow(0, 0); - layout.AddView(&v1); - layout.AddView(&v2); - - gfx::Size pref = layout.GetPreferredSize(&host); - EXPECT_EQ(gfx::Size(100, 20), pref); - - host.SetBounds(0, 0, pref.width(), pref.height()); - layout.Layout(&host); - ExpectViewBoundsEquals(0, 0, 50, 20, &v1); - ExpectViewBoundsEquals(50, 0, 10, 10, &v2); - - RemoveAll(); -} - -TEST_F(GridLayoutTest, HorizontalResizeTest1) { - SettableSizeView v1(gfx::Size(50, 20)); - SettableSizeView v2(gfx::Size(10, 10)); - ColumnSet* c1 = layout.AddColumnSet(0); - c1->AddColumn(GridLayout::FILL, GridLayout::LEADING, - 1, GridLayout::USE_PREF, 0, 0); - c1->AddColumn(GridLayout::LEADING, GridLayout::LEADING, - 0, GridLayout::USE_PREF, 0, 0); - layout.StartRow(0, 0); - layout.AddView(&v1); - layout.AddView(&v2); - - host.SetBounds(0, 0, 110, 20); - layout.Layout(&host); - ExpectViewBoundsEquals(0, 0, 100, 20, &v1); - ExpectViewBoundsEquals(100, 0, 10, 10, &v2); - - RemoveAll(); -} - -TEST_F(GridLayoutTest, HorizontalResizeTest2) { - SettableSizeView v1(gfx::Size(50, 20)); - SettableSizeView v2(gfx::Size(10, 10)); - ColumnSet* c1 = layout.AddColumnSet(0); - c1->AddColumn(GridLayout::FILL, GridLayout::LEADING, - 1, GridLayout::USE_PREF, 0, 0); - c1->AddColumn(GridLayout::TRAILING, GridLayout::LEADING, - 1, GridLayout::USE_PREF, 0, 0); - layout.StartRow(0, 0); - layout.AddView(&v1); - layout.AddView(&v2); - - host.SetBounds(0, 0, 120, 20); - layout.Layout(&host); - ExpectViewBoundsEquals(0, 0, 80, 20, &v1); - ExpectViewBoundsEquals(110, 0, 10, 10, &v2); - - RemoveAll(); -} - -// Tests that space leftover due to rounding is distributed to the last -// resizable column. -TEST_F(GridLayoutTest, HorizontalResizeTest3) { - SettableSizeView v1(gfx::Size(10, 10)); - SettableSizeView v2(gfx::Size(10, 10)); - SettableSizeView v3(gfx::Size(10, 10)); - ColumnSet* c1 = layout.AddColumnSet(0); - c1->AddColumn(GridLayout::FILL, GridLayout::LEADING, - 1, GridLayout::USE_PREF, 0, 0); - c1->AddColumn(GridLayout::FILL, GridLayout::LEADING, - 1, GridLayout::USE_PREF, 0, 0); - c1->AddColumn(GridLayout::TRAILING, GridLayout::LEADING, - 0, GridLayout::USE_PREF, 0, 0); - layout.StartRow(0, 0); - layout.AddView(&v1); - layout.AddView(&v2); - layout.AddView(&v3); - - host.SetBounds(0, 0, 31, 10); - layout.Layout(&host); - ExpectViewBoundsEquals(0, 0, 10, 10, &v1); - ExpectViewBoundsEquals(10, 0, 11, 10, &v2); - ExpectViewBoundsEquals(21, 0, 10, 10, &v3); - - RemoveAll(); -} - -TEST_F(GridLayoutTest, TestVerticalResize1) { - SettableSizeView v1(gfx::Size(50, 20)); - SettableSizeView v2(gfx::Size(10, 10)); - ColumnSet* c1 = layout.AddColumnSet(0); - c1->AddColumn(GridLayout::FILL, GridLayout::FILL, - 1, GridLayout::USE_PREF, 0, 0); - layout.StartRow(1, 0); - layout.AddView(&v1); - layout.StartRow(0, 0); - layout.AddView(&v2); - - GetPreferredSize(); - EXPECT_EQ(gfx::Size(50, 30), pref); - - host.SetBounds(0, 0, 50, 100); - layout.Layout(&host); - ExpectViewBoundsEquals(0, 0, 50, 90, &v1); - ExpectViewBoundsEquals(0, 90, 50, 10, &v2); - - RemoveAll(); -} - -TEST_F(GridLayoutTest, Insets) { - SettableSizeView v1(gfx::Size(10, 20)); - ColumnSet* c1 = layout.AddColumnSet(0); - layout.SetInsets(1, 2, 3, 4); - c1->AddColumn(GridLayout::LEADING, GridLayout::LEADING, - 0, GridLayout::USE_PREF, 0, 0); - layout.StartRow(0, 0); - layout.AddView(&v1); - - GetPreferredSize(); - EXPECT_EQ(gfx::Size(16, 24), pref); - - host.SetBounds(0, 0, pref.width(), pref.height()); - layout.Layout(&host); - ExpectViewBoundsEquals(2, 1, 10, 20, &v1); - - RemoveAll(); -} - -TEST_F(GridLayoutTest, FixedSize) { - layout.SetInsets(2, 2, 2, 2); - - ColumnSet* set = layout.AddColumnSet(0); - - int column_count = 4; - int title_width = 100; - int row_count = 2; - int pref_width = 10; - int pref_height = 20; - - for (int i = 0; i < column_count; ++i) { - set->AddColumn(GridLayout::CENTER, - GridLayout::CENTER, - 0, - GridLayout::FIXED, - title_width, - title_width); - } - - for (int row = 0; row < row_count; ++row) { - layout.StartRow(0, 0); - for (int col = 0; col < column_count; ++col) { - layout.AddView(new SettableSizeView(gfx::Size(pref_width, pref_height))); - } - } - - layout.Layout(&host); - - for (int i = 0; i < column_count; ++i) { - for (int row = 0; row < row_count; ++row) { - View* view = host.child_at(row * column_count + i); - ExpectViewBoundsEquals( - 2 + title_width * i + (title_width - pref_width) / 2, - 2 + pref_height * row, - pref_width, - pref_height, view); - } - } - - GetPreferredSize(); - EXPECT_EQ(gfx::Size(column_count * title_width + 4, - row_count * pref_height + 4), pref); -} - -TEST_F(GridLayoutTest, RowSpanWithPaddingRow) { - ColumnSet* set = layout.AddColumnSet(0); - - set->AddColumn(GridLayout::CENTER, - GridLayout::CENTER, - 0, - GridLayout::FIXED, - 10, - 10); - - layout.StartRow(0, 0); - layout.AddView(new SettableSizeView(gfx::Size(10, 10)), 1, 2); - layout.AddPaddingRow(0, 10); -} - -TEST_F(GridLayoutTest, RowSpan) { - ColumnSet* set = layout.AddColumnSet(0); - - set->AddColumn(GridLayout::LEADING, - GridLayout::LEADING, - 0, - GridLayout::USE_PREF, - 0, - 0); - set->AddColumn(GridLayout::LEADING, - GridLayout::LEADING, - 0, - GridLayout::USE_PREF, - 0, - 0); - - layout.StartRow(0, 0); - layout.AddView(new SettableSizeView(gfx::Size(20, 10))); - layout.AddView(new SettableSizeView(gfx::Size(20, 40)), 1, 2); - layout.StartRow(1, 0); - View* s3 = new SettableSizeView(gfx::Size(20, 10)); - layout.AddView(s3); - - GetPreferredSize(); - EXPECT_EQ(gfx::Size(40, 40), pref); - - host.SetBounds(0, 0, pref.width(), pref.height()); - layout.Layout(&host); - ExpectViewBoundsEquals(0, 10, 20, 10, s3); -} - -TEST_F(GridLayoutTest, RowSpan2) { - ColumnSet* set = layout.AddColumnSet(0); - - set->AddColumn(GridLayout::LEADING, GridLayout::LEADING, - 0, GridLayout::USE_PREF, 0, 0); - set->AddColumn(GridLayout::LEADING, GridLayout::LEADING, - 0,GridLayout::USE_PREF, 0, 0); - - layout.StartRow(0, 0); - layout.AddView(new SettableSizeView(gfx::Size(20, 20))); - View* s3 = new SettableSizeView(gfx::Size(64, 64)); - layout.AddView(s3, 1, 3); - - layout.AddPaddingRow(0, 10); - - layout.StartRow(0, 0); - layout.AddView(new SettableSizeView(gfx::Size(10, 20))); - - GetPreferredSize(); - EXPECT_EQ(gfx::Size(84, 64), pref); - - host.SetBounds(0, 0, pref.width(), pref.height()); - layout.Layout(&host); - ExpectViewBoundsEquals(20, 0, 64, 64, s3); -} - -TEST_F(GridLayoutTest, FixedViewWidth) { - ColumnSet* set = layout.AddColumnSet(0); - - set->AddColumn(GridLayout::LEADING, GridLayout::LEADING, - 0, GridLayout::USE_PREF, 0, 0); - set->AddColumn(GridLayout::LEADING, GridLayout::LEADING, - 0,GridLayout::USE_PREF, 0, 0); - - layout.StartRow(0, 0); - View* view = new SettableSizeView(gfx::Size(30, 40)); - layout.AddView(view, 1, 1, GridLayout::LEADING, GridLayout::LEADING, 10, 0); - - GetPreferredSize(); - EXPECT_EQ(10, pref.width()); - EXPECT_EQ(40, pref.height()); - - host.SetBounds(0, 0, pref.width(), pref.height()); - layout.Layout(&host); - ExpectViewBoundsEquals(0, 0, 10, 40, view); -} - -TEST_F(GridLayoutTest, FixedViewHeight) { - ColumnSet* set = layout.AddColumnSet(0); - - set->AddColumn(GridLayout::LEADING, GridLayout::LEADING, - 0, GridLayout::USE_PREF, 0, 0); - set->AddColumn(GridLayout::LEADING, GridLayout::LEADING, - 0,GridLayout::USE_PREF, 0, 0); - - layout.StartRow(0, 0); - View* view = new SettableSizeView(gfx::Size(30, 40)); - layout.AddView(view, 1, 1, GridLayout::LEADING, GridLayout::LEADING, 0, 10); - - GetPreferredSize(); - EXPECT_EQ(30, pref.width()); - EXPECT_EQ(10, pref.height()); - - host.SetBounds(0, 0, pref.width(), pref.height()); - layout.Layout(&host); - ExpectViewBoundsEquals(0, 0, 30, 10, view); -} - -// Make sure that for views that span columns the underlying columns are resized -// based on the resize percent of the column. -TEST_F(GridLayoutTest, ColumnSpanResizing) { - ColumnSet* set = layout.AddColumnSet(0); - - set->AddColumn(GridLayout::FILL, GridLayout::CENTER, - 2, GridLayout::USE_PREF, 0, 0); - set->AddColumn(GridLayout::FILL, GridLayout::CENTER, - 4, GridLayout::USE_PREF, 0, 0); - - layout.StartRow(0, 0); - // span_view spans two columns and is twice as big the views added below. - View* span_view = new SettableSizeView(gfx::Size(12, 40)); - layout.AddView(span_view, 2, 1, GridLayout::LEADING, GridLayout::LEADING); - - layout.StartRow(0, 0); - View* view1 = new SettableSizeView(gfx::Size(2, 40)); - View* view2 = new SettableSizeView(gfx::Size(4, 40)); - layout.AddView(view1); - layout.AddView(view2); - - host.SetBounds(0, 0, 12, 80); - layout.Layout(&host); - - ExpectViewBoundsEquals(0, 0, 12, 40, span_view); - - // view1 should be 4 pixels wide - // column_pref + (remaining_width * column_resize / total_column_resize) = - // 2 + (6 * 2 / 6). - ExpectViewBoundsEquals(0, 40, 4, 40, view1); - - // And view2 should be 8 pixels wide: - // 4 + (6 * 4 / 6). - ExpectViewBoundsEquals(4, 40, 8, 40, view2); -} - -// Check that GetPreferredSize() takes resizing of columns into account when -// there is additional space in the case we have column sets of different -// preferred sizes. -TEST_F(GridLayoutTest, ColumnResizingOnGetPreferredSize) { - ColumnSet* set = layout.AddColumnSet(0); - set->AddColumn(GridLayout::FILL, GridLayout::CENTER, - 1, GridLayout::USE_PREF, 0, 0); - - set = layout.AddColumnSet(1); - set->AddColumn(GridLayout::FILL, GridLayout::CENTER, - 1, GridLayout::USE_PREF, 0, 0); - - set = layout.AddColumnSet(2); - set->AddColumn(GridLayout::FILL, GridLayout::CENTER, - 1, GridLayout::USE_PREF, 0, 0); - - // Make a row containing a flexible view that trades width for height. - layout.StartRow(0, 0); - View* view1 = new FlexibleView(100); - layout.AddView(view1, 1, 1, GridLayout::FILL, GridLayout::LEADING); - - // The second row contains a view of fixed size that will enforce a column - // width of 20 pixels. - layout.StartRow(0, 1); - View* view2 = new SettableSizeView(gfx::Size(20, 20)); - layout.AddView(view2, 1, 1, GridLayout::FILL, GridLayout::LEADING); - - // Add another flexible view in row three in order to ensure column set - // ordering doesn't influence sizing behaviour. - layout.StartRow(0, 2); - View* view3 = new FlexibleView(40); - layout.AddView(view3, 1, 1, GridLayout::FILL, GridLayout::LEADING); - - // We expect a height of 50: 30 from the variable width view in the first row - // plus 20 from the statically sized view in the second row. The flexible - // view in the third row should contribute no height. - EXPECT_EQ(gfx::Size(20, 50), layout.GetPreferredSize(&host)); -} - -TEST_F(GridLayoutTest, MinimumPreferredSize) { - SettableSizeView v1(gfx::Size(10, 20)); - ColumnSet* set = layout.AddColumnSet(0); - set->AddColumn(GridLayout::FILL, GridLayout::FILL, - 0, GridLayout::USE_PREF, 0, 0); - layout.StartRow(0, 0); - layout.AddView(&v1); - - GetPreferredSize(); - EXPECT_EQ(gfx::Size(10, 20), pref); - - layout.set_minimum_size(gfx::Size(40, 40)); - GetPreferredSize(); - EXPECT_EQ(gfx::Size(40, 40), pref); - - RemoveAll(); -} - -} // namespace views
diff --git a/ui/views/layout/layout_constants.h b/ui/views/layout/layout_constants.h deleted file mode 100644 index 1cee4c0..0000000 --- a/ui/views/layout/layout_constants.h +++ /dev/null
@@ -1,85 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_LAYOUT_LAYOUT_CONSTANTS_H_ -#define UI_VIEWS_LAYOUT_LAYOUT_CONSTANTS_H_ - -// This file contains some constants we use to implement our standard panel -// layout. -// see: spec 21/4 - -namespace views { - -// Left or right margin. -const int kPanelHorizMargin = 13; - -// Top or bottom margin. -const int kPanelVertMargin = 13; - -// If some UI has some sub UI. Indent horizontally by the following value. -const int kPanelHorizIndentation = 24; - -// When several controls are aligned vertically, the baseline should be spaced -// by the following number of pixels. -const int kPanelVerticalSpacing = 32; - -// Vertical spacing between sub UI. -const int kPanelSubVerticalSpacing = 24; - -// Vertical spacing between a label and some control. -const int kLabelToControlVerticalSpacing = 8; - -// Small horizontal spacing between controls that are logically related. -const int kRelatedControlSmallHorizontalSpacing = 8; - -// Horizontal spacing between controls that are logically related. -const int kRelatedControlHorizontalSpacing = 8; - -// Vertical spacing between controls that are logically related. -const int kRelatedControlVerticalSpacing = 8; - -// Small vertical spacing between controls that are logically related. -const int kRelatedControlSmallVerticalSpacing = 4; - -// Horizontal spacing between controls that are logically unrelated. -const int kUnrelatedControlHorizontalSpacing = 12; - -// Larger horizontal spacing between unrelated controls. -const int kUnrelatedControlLargeHorizontalSpacing = 20; - -// Vertical spacing between controls that are logically unrelated. -const int kUnrelatedControlVerticalSpacing = 20; - -// Larger vertical spacing between unrelated controls. -const int kUnrelatedControlLargeVerticalSpacing = 30; - -// Vertical spacing between the edge of the window and the -// top or bottom of a button. -const int kButtonVEdgeMargin = 9; - -// Vertical spacing between the edge of the window and the -// left or right of a button. -const int kButtonHEdgeMargin = 13; - -// Vertical spacing between the edge of the window and the -// top or bottom of a button (when using new style dialogs). -const int kButtonVEdgeMarginNew = 20; - -// Vertical spacing between the edge of the window and the -// left or right of a button (when using new style dialogs). -const int kButtonHEdgeMarginNew = 20; - -// Horizontal spacing between buttons that are logically related. -const int kRelatedButtonHSpacing = 6; - -// Indent of checkboxes relative to related text. -const int kCheckboxIndent = 10; - -// Horizontal spacing between the end of an item (i.e. an icon or a checkbox) -// and the start of its corresponding text. -const int kItemLabelSpacing = 10; - -} // namespace views - -#endif // UI_VIEWS_LAYOUT_LAYOUT_CONSTANTS_H_
diff --git a/ui/views/layout/layout_manager.cc b/ui/views/layout/layout_manager.cc deleted file mode 100644 index 9a79ce7..0000000 --- a/ui/views/layout/layout_manager.cc +++ /dev/null
@@ -1,31 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/layout/layout_manager.h" - -#include "ui/views/view.h" - -namespace views { - -LayoutManager::~LayoutManager() { -} - -void LayoutManager::Installed(View* host) { -} - -void LayoutManager::Uninstalled(View* host) { -} - -int LayoutManager::GetPreferredHeightForWidth(const View* host, - int width) const { - return GetPreferredSize(host).height(); -} - -void LayoutManager::ViewAdded(View* host, View* view) { -} - -void LayoutManager::ViewRemoved(View* host, View* view) { -} - -} // namespace views
diff --git a/ui/views/layout/layout_manager.h b/ui/views/layout/layout_manager.h deleted file mode 100644 index d10e09e..0000000 --- a/ui/views/layout/layout_manager.h +++ /dev/null
@@ -1,60 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_LAYOUT_LAYOUT_MANAGER_H_ -#define UI_VIEWS_LAYOUT_LAYOUT_MANAGER_H_ - -#include "ui/views/views_export.h" - -namespace gfx { -class Size; -} - -namespace views { - -class View; - -///////////////////////////////////////////////////////////////////////////// -// -// LayoutManager interface -// -// The LayoutManager interface provides methods to handle the sizing of -// the children of a View according to implementation-specific heuristics. -// -///////////////////////////////////////////////////////////////////////////// -class VIEWS_EXPORT LayoutManager { - public: - virtual ~LayoutManager(); - - // Notification that this LayoutManager has been installed on a particular - // host. - virtual void Installed(View* host); - - // Notification that this LayoutManager has been uninstalled on a particular - // host. - virtual void Uninstalled(View* host); - - // Lay out the children of |host| according to implementation-specific - // heuristics. The graphics used during painting is provided to allow for - // string sizing. - virtual void Layout(View* host) = 0; - - // Return the preferred size which is the size required to give each - // children their respective preferred size. - virtual gfx::Size GetPreferredSize(const View* host) const = 0; - - // Returns the preferred height for the specified width. The default - // implementation returns the value from GetPreferredSize. - virtual int GetPreferredHeightForWidth(const View* host, int width) const; - - // Notification that a view has been added. - virtual void ViewAdded(View* host, View* view); - - // Notification that a view has been removed. - virtual void ViewRemoved(View* host, View* view); -}; - -} // namespace views - -#endif // UI_VIEWS_LAYOUT_LAYOUT_MANAGER_H_
diff --git a/ui/views/masked_targeter_delegate.cc b/ui/views/masked_targeter_delegate.cc deleted file mode 100644 index d0c697e..0000000 --- a/ui/views/masked_targeter_delegate.cc +++ /dev/null
@@ -1,34 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/masked_targeter_delegate.h" - -#include "ui/gfx/path.h" -#include "ui/gfx/skia_util.h" -#include "ui/views/view.h" - -namespace views { - -bool MaskedTargeterDelegate::DoesIntersectRect(const View* target, - const gfx::Rect& rect) const { - // Early return if |rect| does not even intersect the rectangular bounds - // of |target|. - if (!ViewTargeterDelegate::DoesIntersectRect(target, rect)) - return false; - - // Early return if |mask| is not a valid hit test mask. - gfx::Path mask; - if (!GetHitTestMask(&mask)) - return false; - - // Return whether or not |rect| intersects the custom hit test mask - // of |target|. - SkRegion clip_region; - clip_region.setRect(0, 0, target->width(), target->height()); - SkRegion mask_region; - return mask_region.setPath(mask, clip_region) && - mask_region.intersects(RectToSkIRect(rect)); -} - -} // namespace views
diff --git a/ui/views/masked_targeter_delegate.h b/ui/views/masked_targeter_delegate.h deleted file mode 100644 index ee8701c..0000000 --- a/ui/views/masked_targeter_delegate.h +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_MASKED_TARGETER_DELEGATE_H_ -#define UI_VIEWS_MASKED_TARGETER_DELEGATE_H_ - -#include "ui/base/ui_base_types.h" -#include "ui/views/view_targeter_delegate.h" -#include "ui/views/views_export.h" - -namespace gfx { -class Path; -class Rect; -} - -namespace views { -class View; - -// Defines the default behaviour for hit-testing a rectangular region against -// the bounds of a View having a custom-shaped hit test mask. Views define -// such a mask by extending this class. -class VIEWS_EXPORT MaskedTargeterDelegate : public ViewTargeterDelegate { - public: - MaskedTargeterDelegate() {} - virtual ~MaskedTargeterDelegate() {} - - // Sets the hit-test mask for the view which implements this interface, - // in that view's local coordinate space. Returns whether a valid mask - // has been set in |mask|. - virtual bool GetHitTestMask(gfx::Path* mask) const = 0; - - // ViewTargeterDelegate: - virtual bool DoesIntersectRect(const View* target, - const gfx::Rect& rect) const override; - - private: - DISALLOW_COPY_AND_ASSIGN(MaskedTargeterDelegate); -}; - -} // namespace views - -#endif // UI_VIEWS_MASKED_TARGETER_DELEGATE_H_
diff --git a/ui/views/metrics.cc b/ui/views/metrics.cc deleted file mode 100644 index 842ae66..0000000 --- a/ui/views/metrics.cc +++ /dev/null
@@ -1,11 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/metrics.h" - -namespace views { - -const int kDefaultMenuShowDelay = 400; - -} // namespace views
diff --git a/ui/views/metrics.h b/ui/views/metrics.h deleted file mode 100644 index 0331ae1..0000000 --- a/ui/views/metrics.h +++ /dev/null
@@ -1,27 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_METRICS_H_ -#define UI_VIEWS_METRICS_H_ - -#include "ui/views/views_export.h" - -namespace views { - -// NOTE: All times in this file are/should be expressed in milliseconds. - -// The default value for how long to wait before showing a menu button on hover. -// This value is used if the OS doesn't supply one. -extern const int kDefaultMenuShowDelay; - -// Returns the amount of time between double clicks. -VIEWS_EXPORT int GetDoubleClickInterval(); - -// Returns the amount of time to wait from hovering over a menu button until -// showing the menu. -VIEWS_EXPORT int GetMenuShowDelay(); - -} // namespace views - -#endif // UI_VIEWS_METRICS_H_
diff --git a/ui/views/metrics_aura.cc b/ui/views/metrics_aura.cc deleted file mode 100644 index 046baa8..0000000 --- a/ui/views/metrics_aura.cc +++ /dev/null
@@ -1,40 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/metrics.h" - -#if defined(OS_WIN) -#include <windows.h> -#endif - -namespace { - -// Default double click interval in milliseconds. -const int kDefaultDoubleClickInterval = 500; - -} // namespace - -namespace views { - -int GetDoubleClickInterval() { -#if defined(OS_WIN) - return ::GetDoubleClickTime(); -#else - // TODO(jennyz): This value may need to be adjusted on different platforms. - return kDefaultDoubleClickInterval; -#endif -} - -int GetMenuShowDelay() { -#if defined(OS_WIN) - static DWORD delay = 0; - if (!delay && !SystemParametersInfo(SPI_GETMENUSHOWDELAY, 0, &delay, 0)) - delay = kDefaultMenuShowDelay; - return delay; -#else - return 0; -#endif -} - -} // namespace views
diff --git a/ui/views/mouse_constants.h b/ui/views/mouse_constants.h deleted file mode 100644 index a0dce80..0000000 --- a/ui/views/mouse_constants.h +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_MOUSE_CONSTANTS_H_ -#define UI_VIEWS_MOUSE_CONSTANTS_H_ - -#include "base/basictypes.h" - -namespace views { - -// The amount of time the mouse should be down before a mouse release is -// considered intentional. This is to prevent spurious mouse releases from -// activating controls, especially when some UI element is revealed under the -// source of the activation (ex. menus showing underneath menu buttons). -const int kMinimumMsPressedToActivate = 200; - -// The amount of time, in milliseconds, between clicks until they're -// considered intentionally different. -const int kMinimumMsBetweenButtonClicks = 100; - -} // namespace views - -#endif // UI_VIEWS_MOUSE_CONSTANTS_H_
diff --git a/ui/views/mouse_watcher.h b/ui/views/mouse_watcher.h deleted file mode 100644 index 9327fe6..0000000 --- a/ui/views/mouse_watcher.h +++ /dev/null
@@ -1,100 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_MOUSE_WATCHER_H_ -#define UI_VIEWS_MOUSE_WATCHER_H_ - -#include "base/basictypes.h" -#include "base/memory/scoped_ptr.h" -#include "base/time/time.h" -#include "ui/gfx/insets.h" -#include "ui/views/views_export.h" - -namespace gfx { -class Point; -} - -namespace views { - -// MouseWatcherListener is notified when the mouse moves outside the host. -class VIEWS_EXPORT MouseWatcherListener { - public: - virtual void MouseMovedOutOfHost() = 0; - - protected: - virtual ~MouseWatcherListener(); -}; - -// The MouseWatcherHost determines what region is to be monitored. -class VIEWS_EXPORT MouseWatcherHost { - public: - // The MouseEventType can be used as a hint. - enum MouseEventType { - // The mouse moved within the window which was current when the MouseWatcher - // was created. - MOUSE_MOVE, - // The mouse moved exited the window which was current when the MouseWatcher - // was created. - MOUSE_EXIT - }; - - virtual ~MouseWatcherHost(); - - // Return false when the mouse has moved outside the monitored region. - virtual bool Contains(const gfx::Point& screen_point, - MouseEventType type) = 0; -}; - -// MouseWatcher is used to watch mouse movement and notify its listener when the -// mouse moves outside the bounds of a MouseWatcherHost. -class VIEWS_EXPORT MouseWatcher { - public: - // Creates a new MouseWatcher. The |listener| will be notified when the |host| - // determines that the mouse has moved outside its monitored region. - // |host| will be owned by the watcher and deleted upon completion. - MouseWatcher(MouseWatcherHost* host, MouseWatcherListener* listener); - ~MouseWatcher(); - - // Sets the amount to delay before notifying the listener when the mouse exits - // the host by way of going to another window. - void set_notify_on_exit_time(base::TimeDelta time) { - notify_on_exit_time_ = time; - } - - // Starts watching mouse movements. When the mouse moves outside the bounds of - // the host the listener is notified. |Start| may be invoked any number of - // times. If the mouse moves outside the bounds of the host the listener is - // notified and watcher stops watching events. - void Start(); - - // Stops watching mouse events. - void Stop(); - - private: - class Observer; - - // Are we currently observing events? - bool is_observing() const { return observer_.get() != NULL; } - - // Notifies the listener and stops watching events. - void NotifyListener(); - - // Host we're listening for events over. - scoped_ptr<MouseWatcherHost> host_; - - // Our listener. - MouseWatcherListener* listener_; - - // Does the actual work of listening for mouse events. - scoped_ptr<Observer> observer_; - - // See description above setter. - base::TimeDelta notify_on_exit_time_; - - DISALLOW_COPY_AND_ASSIGN(MouseWatcher); -}; - -} // namespace views - -#endif // UI_VIEWS_MOUSE_WATCHER_H_
diff --git a/ui/views/mouse_watcher_aura.cc b/ui/views/mouse_watcher_aura.cc deleted file mode 100644 index 6fa463b..0000000 --- a/ui/views/mouse_watcher_aura.cc +++ /dev/null
@@ -1,125 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/mouse_watcher.h" - -#include "base/bind.h" -#include "base/compiler_specific.h" -#include "base/event_types.h" -#include "base/memory/weak_ptr.h" -#include "base/message_loop/message_loop.h" -#include "ui/aura/env.h" -#include "ui/aura/window.h" -#include "ui/events/event.h" -#include "ui/events/event_constants.h" -#include "ui/events/event_handler.h" -#include "ui/events/event_utils.h" -#include "ui/gfx/screen.h" - -namespace views { - -// Amount of time between when the mouse moves outside the Host's zone and when -// the listener is notified. -const int kNotifyListenerTimeMs = 300; - -class MouseWatcher::Observer : public ui::EventHandler { - public: - explicit Observer(MouseWatcher* mouse_watcher) - : mouse_watcher_(mouse_watcher), - notify_listener_factory_(this) { - aura::Env::GetInstance()->AddPreTargetHandler(this); - } - - virtual ~Observer() { - aura::Env::GetInstance()->RemovePreTargetHandler(this); - } - - // ui::EventHandler implementation: - virtual void OnMouseEvent(ui::MouseEvent* event) override { - switch (event->type()) { - case ui::ET_MOUSE_MOVED: - case ui::ET_MOUSE_DRAGGED: - HandleMouseEvent(MouseWatcherHost::MOUSE_MOVE); - break; - case ui::ET_MOUSE_EXITED: - HandleMouseEvent(MouseWatcherHost::MOUSE_EXIT); - break; - default: - break; - } - } - - private: - MouseWatcherHost* host() const { return mouse_watcher_->host_.get(); } - - // Called when a mouse event we're interested is seen. - void HandleMouseEvent(MouseWatcherHost::MouseEventType event_type) { - // It's safe to use last_mouse_location() here as this function is invoked - // during event dispatching. - if (!host()->Contains(aura::Env::GetInstance()->last_mouse_location(), - event_type)) { - // Mouse moved outside the host's zone, start a timer to notify the - // listener. - if (!notify_listener_factory_.HasWeakPtrs()) { - base::MessageLoop::current()->PostDelayedTask( - FROM_HERE, - base::Bind(&Observer::NotifyListener, - notify_listener_factory_.GetWeakPtr()), - event_type == MouseWatcherHost::MOUSE_MOVE - ? base::TimeDelta::FromMilliseconds(kNotifyListenerTimeMs) - : mouse_watcher_->notify_on_exit_time_); - } - } else { - // Mouse moved quickly out of the host and then into it again, so cancel - // the timer. - notify_listener_factory_.InvalidateWeakPtrs(); - } - } - - void NotifyListener() { - mouse_watcher_->NotifyListener(); - // WARNING: we've been deleted. - } - - private: - MouseWatcher* mouse_watcher_; - - // A factory that is used to construct a delayed callback to the listener. - base::WeakPtrFactory<Observer> notify_listener_factory_; - - DISALLOW_COPY_AND_ASSIGN(Observer); -}; - -MouseWatcherListener::~MouseWatcherListener() { -} - -MouseWatcherHost::~MouseWatcherHost() { -} - -MouseWatcher::MouseWatcher(MouseWatcherHost* host, - MouseWatcherListener* listener) - : host_(host), - listener_(listener), - notify_on_exit_time_(base::TimeDelta::FromMilliseconds( - kNotifyListenerTimeMs)) { -} - -MouseWatcher::~MouseWatcher() { -} - -void MouseWatcher::Start() { - if (!is_observing()) - observer_.reset(new Observer(this)); -} - -void MouseWatcher::Stop() { - observer_.reset(NULL); -} - -void MouseWatcher::NotifyListener() { - observer_.reset(NULL); - listener_->MouseMovedOutOfHost(); -} - -} // namespace views
diff --git a/ui/views/mouse_watcher_view_host.cc b/ui/views/mouse_watcher_view_host.cc deleted file mode 100644 index 54412cf..0000000 --- a/ui/views/mouse_watcher_view_host.cc +++ /dev/null
@@ -1,56 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/mouse_watcher_view_host.h" - -#include "ui/gfx/screen.h" -#include "ui/views/view.h" -#include "ui/views/widget/widget.h" - -namespace views { - -MouseWatcherViewHost::MouseWatcherViewHost(View* view, - const gfx::Insets& hot_zone_insets) - : view_(view), - hot_zone_insets_(hot_zone_insets) { -} - -MouseWatcherViewHost::~MouseWatcherViewHost() { -} - -bool MouseWatcherViewHost::Contains( - const gfx::Point& screen_point, - MouseEventType type) { - bool in_view = IsCursorInViewZone(screen_point); - if (!in_view || (type == MOUSE_EXIT && !IsMouseOverWindow())) - return false; - return true; -} - -// Returns whether or not the cursor is currently in the view's "zone" which -// is defined as a slightly larger region than the view. -bool MouseWatcherViewHost::IsCursorInViewZone(const gfx::Point& screen_point) { - gfx::Rect bounds = view_->GetLocalBounds(); - gfx::Point view_topleft(bounds.origin()); - View::ConvertPointToScreen(view_, &view_topleft); - bounds.set_origin(view_topleft); - bounds.SetRect(view_topleft.x() - hot_zone_insets_.left(), - view_topleft.y() - hot_zone_insets_.top(), - bounds.width() + hot_zone_insets_.width(), - bounds.height() + hot_zone_insets_.height()); - - return bounds.Contains(screen_point.x(), screen_point.y()); -} - -// Returns true if the mouse is over the view's window. -bool MouseWatcherViewHost::IsMouseOverWindow() { - Widget* widget = view_->GetWidget(); - if (!widget) - return false; - - return gfx::Screen::GetScreenFor(widget->GetNativeView())-> - GetWindowUnderCursor() == widget->GetNativeWindow(); -} - -} // namespace views
diff --git a/ui/views/mouse_watcher_view_host.h b/ui/views/mouse_watcher_view_host.h deleted file mode 100644 index ada3444..0000000 --- a/ui/views/mouse_watcher_view_host.h +++ /dev/null
@@ -1,42 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_MOUSE_WATCHER_VIEW_HOST_H_ -#define UI_VIEWS_MOUSE_WATCHER_VIEW_HOST_H_ - -#include "ui/views/mouse_watcher.h" - -namespace views { - -class View; - -class VIEWS_EXPORT MouseWatcherViewHost : public MouseWatcherHost { - public: - // Creates a new MouseWatcherViewHost. |hot_zone_insets| is added to the - // bounds of the view to determine the active zone. For example, if - // |hot_zone_insets.bottom()| is 10, then the listener is not notified if - // the y coordinate is between the origin of the view and height of the view - // plus 10. - MouseWatcherViewHost(View* view, const gfx::Insets& hot_zone_insets); - virtual ~MouseWatcherViewHost(); - - // MouseWatcherHost. - virtual bool Contains(const gfx::Point& screen_point, - MouseEventType type) override; - - private: - bool IsCursorInViewZone(const gfx::Point& screen_point); - bool IsMouseOverWindow(); - - // View we're listening for events over. - View* view_; - // Insets added to the bounds of the view. - const gfx::Insets hot_zone_insets_; - - DISALLOW_COPY_AND_ASSIGN(MouseWatcherViewHost); -}; - -} // namespace views - -#endif // UI_VIEWS_MOUSE_WATCHER_VIEW_HOST_H_
diff --git a/ui/views/native_cursor.h b/ui/views/native_cursor.h deleted file mode 100644 index 81f6e21..0000000 --- a/ui/views/native_cursor.h +++ /dev/null
@@ -1,21 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_NATIVE_CURSOR_H_ -#define UI_VIEWS_NATIVE_CURSOR_H_ - -#include "ui/gfx/native_widget_types.h" -#include "ui/views/views_export.h" - -namespace views { - -VIEWS_EXPORT gfx::NativeCursor GetNativeIBeamCursor(); -VIEWS_EXPORT gfx::NativeCursor GetNativeHandCursor(); -VIEWS_EXPORT gfx::NativeCursor GetNativeColumnResizeCursor(); -VIEWS_EXPORT gfx::NativeCursor GetNativeEastWestResizeCursor(); -VIEWS_EXPORT gfx::NativeCursor GetNativeNorthSouthResizeCursor(); - -} // namespace views - -#endif // UI_VIEWS_NATIVE_CURSOR_H_
diff --git a/ui/views/native_cursor_aura.cc b/ui/views/native_cursor_aura.cc deleted file mode 100644 index cafe684..0000000 --- a/ui/views/native_cursor_aura.cc +++ /dev/null
@@ -1,31 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/native_cursor.h" - -#include "ui/base/cursor/cursor.h" - -namespace views { - -gfx::NativeCursor GetNativeIBeamCursor() { - return ui::kCursorIBeam; -} - -gfx::NativeCursor GetNativeHandCursor() { - return ui::kCursorHand; -} - -gfx::NativeCursor GetNativeColumnResizeCursor() { - return ui::kCursorColumnResize; -} - -gfx::NativeCursor GetNativeEastWestResizeCursor() { - return ui::kCursorEastWestResize; -} - -gfx::NativeCursor GetNativeNorthSouthResizeCursor() { - return ui::kCursorNorthSouthResize; -} - -} // namespace views
diff --git a/ui/views/native_theme_delegate.h b/ui/views/native_theme_delegate.h deleted file mode 100644 index f17f164..0000000 --- a/ui/views/native_theme_delegate.h +++ /dev/null
@@ -1,52 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_NATIVE_THEME_DELEGATE_H_ -#define UI_VIEWS_NATIVE_THEME_DELEGATE_H_ - -#include "ui/gfx/rect.h" -#include "ui/native_theme/native_theme.h" -#include "ui/views/views_export.h" - -namespace views { - -// A delagate that supports animating transtions between different native -// theme states. This delegate can be used to control a native theme Border -// or Painter object. -// -// If animation is ongoing, the native theme border or painter will -// composite the foreground state over the backgroud state using an alpha -// between 0 and 255 based on the current value of the animation. -class VIEWS_EXPORT NativeThemeDelegate { - public: - virtual ~NativeThemeDelegate() {} - - // Get the native theme part that should be drawn. - virtual ui::NativeTheme::Part GetThemePart() const = 0; - - // Get the rectangle that should be painted. - virtual gfx::Rect GetThemePaintRect() const = 0; - - // Get the state of the part, along with any extra data needed for drawing. - virtual ui::NativeTheme::State GetThemeState( - ui::NativeTheme::ExtraParams* params) const = 0; - - // If the native theme drawign should be animated, return the Animation object - // that controlls it. If no animation is ongoing, NULL may be returned. - virtual const gfx::Animation* GetThemeAnimation() const = 0; - - // If animation is onging, this returns the background native theme state. - virtual ui::NativeTheme::State GetBackgroundThemeState( - ui::NativeTheme::ExtraParams* params) const = 0; - - // If animation is onging, this returns the foreground native theme state. - // This state will be composited over the background using an alpha value - // based on the current value of the animation. - virtual ui::NativeTheme::State GetForegroundThemeState( - ui::NativeTheme::ExtraParams* params) const = 0; -}; - -} // namespace views - -#endif // UI_VIEWS_NATIVE_THEME_DELEGATE_H_
diff --git a/ui/views/painter.cc b/ui/views/painter.cc deleted file mode 100644 index 37a5a30..0000000 --- a/ui/views/painter.cc +++ /dev/null
@@ -1,323 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/painter.h" - -#include "base/logging.h" -#include "base/memory/scoped_ptr.h" -#include "third_party/skia/include/effects/SkGradientShader.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/image/image.h" -#include "ui/gfx/image/image_skia.h" -#include "ui/gfx/image/image_skia_operations.h" -#include "ui/gfx/insets.h" -#include "ui/gfx/nine_image_painter.h" -#include "ui/gfx/point.h" -#include "ui/gfx/rect.h" -#include "ui/views/view.h" - -namespace views { - -namespace { - -// DashedFocusPainter ---------------------------------------------------------- - -class DashedFocusPainter : public Painter { - public: - explicit DashedFocusPainter(const gfx::Insets& insets); - virtual ~DashedFocusPainter(); - - // Painter: - virtual gfx::Size GetMinimumSize() const override; - virtual void Paint(gfx::Canvas* canvas, const gfx::Size& size) override; - - private: - const gfx::Insets insets_; - - DISALLOW_COPY_AND_ASSIGN(DashedFocusPainter); -}; - -DashedFocusPainter::DashedFocusPainter(const gfx::Insets& insets) - : insets_(insets) { -} - -DashedFocusPainter::~DashedFocusPainter() { -} - -gfx::Size DashedFocusPainter::GetMinimumSize() const { - return gfx::Size(); -} - -void DashedFocusPainter::Paint(gfx::Canvas* canvas, const gfx::Size& size) { - gfx::Rect rect(size); - rect.Inset(insets_); - canvas->DrawFocusRect(rect); -} - -// SolidFocusPainter ----------------------------------------------------------- - -class SolidFocusPainter : public Painter { - public: - SolidFocusPainter(SkColor color, const gfx::Insets& insets); - virtual ~SolidFocusPainter(); - - // Painter: - virtual gfx::Size GetMinimumSize() const override; - virtual void Paint(gfx::Canvas* canvas, const gfx::Size& size) override; - - private: - const SkColor color_; - const gfx::Insets insets_; - - DISALLOW_COPY_AND_ASSIGN(SolidFocusPainter); -}; - -SolidFocusPainter::SolidFocusPainter(SkColor color, - const gfx::Insets& insets) - : color_(color), - insets_(insets) { -} - -SolidFocusPainter::~SolidFocusPainter() { -} - -gfx::Size SolidFocusPainter::GetMinimumSize() const { - return gfx::Size(); -} - -void SolidFocusPainter::Paint(gfx::Canvas* canvas, const gfx::Size& size) { - gfx::Rect rect(size); - rect.Inset(insets_); - canvas->DrawSolidFocusRect(rect, color_); -} - -// GradientPainter ------------------------------------------------------------ - -class GradientPainter : public Painter { - public: - GradientPainter(bool horizontal, - SkColor* colors, - SkScalar* pos, - size_t count); - virtual ~GradientPainter(); - - // Painter: - virtual gfx::Size GetMinimumSize() const override; - virtual void Paint(gfx::Canvas* canvas, const gfx::Size& size) override; - - private: - // If |horizontal_| is true then the gradient is painted horizontally. - bool horizontal_; - // The gradient colors. - scoped_ptr<SkColor[]> colors_; - // The relative positions of the corresponding gradient colors. - scoped_ptr<SkScalar[]> pos_; - // The number of elements in |colors_| and |pos_|. - size_t count_; - - DISALLOW_COPY_AND_ASSIGN(GradientPainter); -}; - -GradientPainter::GradientPainter(bool horizontal, - SkColor* colors, - SkScalar* pos, - size_t count) - : horizontal_(horizontal), - colors_(new SkColor[count]), - pos_(new SkScalar[count]), - count_(count) { - for (size_t i = 0; i < count_; ++i) { - pos_[i] = pos[i]; - colors_[i] = colors[i]; - } -} - -GradientPainter::~GradientPainter() { -} - -gfx::Size GradientPainter::GetMinimumSize() const { - return gfx::Size(); -} - -void GradientPainter::Paint(gfx::Canvas* canvas, const gfx::Size& size) { - SkPaint paint; - SkPoint p[2]; - p[0].iset(0, 0); - if (horizontal_) - p[1].iset(size.width(), 0); - else - p[1].iset(0, size.height()); - - skia::RefPtr<SkShader> s = skia::AdoptRef(SkGradientShader::CreateLinear( - p, colors_.get(), pos_.get(), count_, SkShader::kClamp_TileMode)); - paint.setStyle(SkPaint::kFill_Style); - paint.setShader(s.get()); - - canvas->sk_canvas()->drawRectCoords(SkIntToScalar(0), SkIntToScalar(0), - SkIntToScalar(size.width()), - SkIntToScalar(size.height()), paint); -} - -// ImagePainter --------------------------------------------------------------- - -// ImagePainter stores and paints nine images as a scalable grid. -class ImagePainter : public Painter { - public: - // Constructs an ImagePainter with the specified image resource ids. - // See CreateImageGridPainter()'s comment regarding image ID count and order. - explicit ImagePainter(const int image_ids[]); - - // Constructs an ImagePainter with the specified image and insets. - ImagePainter(const gfx::ImageSkia& image, const gfx::Insets& insets); - - virtual ~ImagePainter(); - - // Painter: - virtual gfx::Size GetMinimumSize() const override; - virtual void Paint(gfx::Canvas* canvas, const gfx::Size& size) override; - - private: - scoped_ptr<gfx::NineImagePainter> nine_painter_; - - DISALLOW_COPY_AND_ASSIGN(ImagePainter); -}; - -ImagePainter::ImagePainter(const int image_ids[]) - : nine_painter_(ui::CreateNineImagePainter(image_ids)) { -} - -ImagePainter::ImagePainter(const gfx::ImageSkia& image, - const gfx::Insets& insets) - : nine_painter_(new gfx::NineImagePainter(image, insets)) { -} - -ImagePainter::~ImagePainter() { -} - -gfx::Size ImagePainter::GetMinimumSize() const { - return nine_painter_->GetMinimumSize(); -} - -void ImagePainter::Paint(gfx::Canvas* canvas, const gfx::Size& size) { - nine_painter_->Paint(canvas, gfx::Rect(size)); -} - -} // namespace - - -// Painter -------------------------------------------------------------------- - -Painter::Painter() { -} - -Painter::~Painter() { -} - -// static -void Painter::PaintPainterAt(gfx::Canvas* canvas, - Painter* painter, - const gfx::Rect& rect) { - DCHECK(canvas && painter); - canvas->Save(); - canvas->Translate(rect.OffsetFromOrigin()); - painter->Paint(canvas, rect.size()); - canvas->Restore(); -} - -// static -void Painter::PaintFocusPainter(View* view, - gfx::Canvas* canvas, - Painter* focus_painter) { - if (focus_painter && view->HasFocus()) - PaintPainterAt(canvas, focus_painter, view->GetLocalBounds()); -} - -// static -Painter* Painter::CreateHorizontalGradient(SkColor c1, SkColor c2) { - SkColor colors[2]; - colors[0] = c1; - colors[1] = c2; - SkScalar pos[] = {0, 1}; - return new GradientPainter(true, colors, pos, 2); -} - -// static -Painter* Painter::CreateVerticalGradient(SkColor c1, SkColor c2) { - SkColor colors[2]; - colors[0] = c1; - colors[1] = c2; - SkScalar pos[] = {0, 1}; - return new GradientPainter(false, colors, pos, 2); -} - -// static -Painter* Painter::CreateVerticalMultiColorGradient(SkColor* colors, - SkScalar* pos, - size_t count) { - return new GradientPainter(false, colors, pos, count); -} - -// static -Painter* Painter::CreateImagePainter(const gfx::ImageSkia& image, - const gfx::Insets& insets) { - return new ImagePainter(image, insets); -} - -// static -Painter* Painter::CreateImageGridPainter(const int image_ids[]) { - return new ImagePainter(image_ids); -} - -// static -scoped_ptr<Painter> Painter::CreateDashedFocusPainter() { - return scoped_ptr<Painter>(new DashedFocusPainter(gfx::Insets())).Pass(); -} - -// static -scoped_ptr<Painter> Painter::CreateDashedFocusPainterWithInsets( - const gfx::Insets& insets) { - return scoped_ptr<Painter>(new DashedFocusPainter(insets)).Pass(); -} - -// static -scoped_ptr<Painter> Painter::CreateSolidFocusPainter( - SkColor color, - const gfx::Insets& insets) { - return scoped_ptr<Painter>(new SolidFocusPainter(color, insets)).Pass(); -} - -// HorizontalPainter ---------------------------------------------------------- - -HorizontalPainter::HorizontalPainter(const int image_resource_names[]) { - ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); - for (int i = 0; i < 3; ++i) - images_[i] = rb.GetImageNamed(image_resource_names[i]).ToImageSkia(); - DCHECK_EQ(images_[LEFT]->height(), images_[CENTER]->height()); - DCHECK_EQ(images_[LEFT]->height(), images_[RIGHT]->height()); -} - -HorizontalPainter::~HorizontalPainter() { -} - -gfx::Size HorizontalPainter::GetMinimumSize() const { - return gfx::Size( - images_[LEFT]->width() + images_[CENTER]->width() + - images_[RIGHT]->width(), images_[LEFT]->height()); -} - -void HorizontalPainter::Paint(gfx::Canvas* canvas, const gfx::Size& size) { - if (size.width() < GetMinimumSize().width()) - return; // No room to paint. - - canvas->DrawImageInt(*images_[LEFT], 0, 0); - canvas->DrawImageInt(*images_[RIGHT], size.width() - images_[RIGHT]->width(), - 0); - canvas->TileImageInt( - *images_[CENTER], images_[LEFT]->width(), 0, - size.width() - images_[LEFT]->width() - images_[RIGHT]->width(), - images_[LEFT]->height()); -} - -} // namespace views
diff --git a/ui/views/painter.h b/ui/views/painter.h deleted file mode 100644 index e703150..0000000 --- a/ui/views/painter.h +++ /dev/null
@@ -1,122 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_PAINTER_H_ -#define UI_VIEWS_PAINTER_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "third_party/skia/include/core/SkColor.h" -#include "ui/base/nine_image_painter_factory.h" -#include "ui/views/views_export.h" - -namespace gfx { -class Canvas; -class ImageSkia; -class Insets; -class Rect; -class Size; -} - -namespace views { - -class View; - -// Painter, as the name implies, is responsible for painting in a particular -// region. Think of Painter as a Border or Background that can be painted -// in any region of a View. -class VIEWS_EXPORT Painter { - public: - Painter(); - virtual ~Painter(); - - // A convenience method for painting a Painter in a particular region. - // This translates the canvas to x/y and paints the painter. - static void PaintPainterAt(gfx::Canvas* canvas, - Painter* painter, - const gfx::Rect& rect); - - // Convenience that paints |focus_painter| only if |view| HasFocus() and - // |focus_painter| is non-NULL. - static void PaintFocusPainter(View* view, - gfx::Canvas* canvas, - Painter* focus_painter); - - // Creates a painter that draws a gradient between the two colors. - static Painter* CreateHorizontalGradient(SkColor c1, SkColor c2); - static Painter* CreateVerticalGradient(SkColor c1, SkColor c2); - - // Creates a painter that draws a multi-color gradient. |colors| contains the - // gradient colors and |pos| the relative positions of the colors. The first - // element in |pos| must be 0.0 and the last element 1.0. |count| contains - // the number of elements in |colors| and |pos|. - static Painter* CreateVerticalMultiColorGradient(SkColor* colors, - SkScalar* pos, - size_t count); - - // Creates a painter that divides |image| into nine regions. The four corners - // are rendered at the size specified in insets (eg. the upper-left corner is - // rendered at 0 x 0 with a size of insets.left() x insets.top()). The center - // and edge images are stretched to fill the painted area. - static Painter* CreateImagePainter(const gfx::ImageSkia& image, - const gfx::Insets& insets); - - // Creates a painter that paints images in a scalable grid. The images must - // share widths by column and heights by row. The corners are painted at full - // size, while center and edge images are stretched to fill the painted area. - // The center image may be zero (to be skipped). This ordering must be used: - // Top-Left/Top/Top-Right/Left/[Center]/Right/Bottom-Left/Bottom/Bottom-Right. - static Painter* CreateImageGridPainter(const int image_ids[]); - - // Factory methods for creating painters intended for rendering focus. - static scoped_ptr<Painter> CreateDashedFocusPainter(); - static scoped_ptr<Painter> CreateDashedFocusPainterWithInsets( - const gfx::Insets& insets); - static scoped_ptr<Painter> CreateSolidFocusPainter(SkColor color, - const gfx::Insets& insets); - - // Returns the minimum size this painter can paint without obvious graphical - // problems (e.g. overlapping images). - virtual gfx::Size GetMinimumSize() const = 0; - - // Paints the painter in the specified region. - virtual void Paint(gfx::Canvas* canvas, const gfx::Size& size) = 0; - - private: - DISALLOW_COPY_AND_ASSIGN(Painter); -}; - -// HorizontalPainter paints 3 images into a box: left, center and right. The -// left and right images are drawn to size at the left/right edges of the -// region. The center is tiled in the remaining space. All images must have the -// same height. -class VIEWS_EXPORT HorizontalPainter : public Painter { - public: - // Constructs a new HorizontalPainter loading the specified image names. - // The images must be in the order left, right and center. - explicit HorizontalPainter(const int image_resource_names[]); - virtual ~HorizontalPainter(); - - // Painter: - virtual gfx::Size GetMinimumSize() const override; - virtual void Paint(gfx::Canvas* canvas, const gfx::Size& size) override; - - private: - // The image chunks. - enum BorderElements { - LEFT, - CENTER, - RIGHT - }; - - // NOTE: the images are owned by ResourceBundle. Don't free them. - const gfx::ImageSkia* images_[3]; - - DISALLOW_COPY_AND_ASSIGN(HorizontalPainter); -}; - -} // namespace views - -#endif // UI_VIEWS_PAINTER_H_
diff --git a/ui/views/rect_based_targeting_utils.cc b/ui/views/rect_based_targeting_utils.cc deleted file mode 100644 index de4d346..0000000 --- a/ui/views/rect_based_targeting_utils.cc +++ /dev/null
@@ -1,33 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/rect_based_targeting_utils.h" - -#include "ui/gfx/point.h" -#include "ui/gfx/rect.h" - -namespace views { - -bool UsePointBasedTargeting(const gfx::Rect& rect) { - return rect.width() == 1 && rect.height() == 1; -} - -float PercentCoveredBy(const gfx::Rect& rect_1, const gfx::Rect& rect_2) { - gfx::Rect intersection(rect_1); - intersection.Intersect(rect_2); - int intersect_area = intersection.size().GetArea(); - int rect_1_area = rect_1.size().GetArea(); - return rect_1_area ? - static_cast<float>(intersect_area) / static_cast<float>(rect_1_area) : 0; -} - -int DistanceSquaredFromCenterToPoint(const gfx::Point& point, - const gfx::Rect& rect) { - gfx::Point center_point = rect.CenterPoint(); - int dx = center_point.x() - point.x(); - int dy = center_point.y() - point.y(); - return (dx * dx) + (dy * dy); -} - -} // namespace views
diff --git a/ui/views/rect_based_targeting_utils.h b/ui/views/rect_based_targeting_utils.h deleted file mode 100644 index 94da5a5..0000000 --- a/ui/views/rect_based_targeting_utils.h +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_RECT_BASED_TARGETING_UTILS_H_ -#define UI_RECT_BASED_TARGETING_UTILS_H_ - -#include "ui/views/views_export.h" - -namespace gfx { -class Point; -class Rect; -} - -namespace views { - -// Returns true if |rect| is 1x1. -VIEWS_EXPORT bool UsePointBasedTargeting(const gfx::Rect& rect); - -// Returns the percentage of |rect_1|'s area that is covered by |rect_2|. -VIEWS_EXPORT float PercentCoveredBy(const gfx::Rect& rect_1, - const gfx::Rect& rect_2); - -// Returns the square of the distance from |point| to the center of |rect|. -VIEWS_EXPORT int DistanceSquaredFromCenterToPoint(const gfx::Point& point, - const gfx::Rect& rect); - -} // namespace views - -#endif // UI_RECT_BASED_TARGETING_UTILS_H_
diff --git a/ui/views/rect_based_targeting_utils_unittest.cc b/ui/views/rect_based_targeting_utils_unittest.cc deleted file mode 100644 index 134119b..0000000 --- a/ui/views/rect_based_targeting_utils_unittest.cc +++ /dev/null
@@ -1,70 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/rect_based_targeting_utils.h" - -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/gfx/rect.h" - -namespace views { - -TEST(RectBasedTargetingUtils, UsePointBasedTargeting) { - gfx::Rect rect_1(gfx::Point(-22, 30), gfx::Size(1, 1)); - gfx::Rect rect_2(gfx::Point(0, 0), gfx::Size(34, 55)); - gfx::Rect rect_3(gfx::Point(12, 12), gfx::Size(1, 0)); - gfx::Rect rect_4(gfx::Point(12, 120), gfx::Size(0, 0)); - - EXPECT_TRUE(UsePointBasedTargeting(rect_1)); - EXPECT_FALSE(UsePointBasedTargeting(rect_2)); - EXPECT_FALSE(UsePointBasedTargeting(rect_3)); - EXPECT_FALSE(UsePointBasedTargeting(rect_4)); -} - -TEST(RectBasedTargetingUtils, PercentCoveredBy) { - gfx::Rect rect_1(gfx::Point(0, 0), gfx::Size(300, 120)); - gfx::Rect rect_2(gfx::Point(20, 10), gfx::Size(30, 90)); - gfx::Rect rect_3(gfx::Point(160, 50), gfx::Size(150, 85)); - gfx::Rect rect_4(gfx::Point(20, 55), gfx::Size(0, 15)); - float error = 0.001f; - - // Passing in identical rectangles. - EXPECT_FLOAT_EQ(1.0f, PercentCoveredBy(rect_1, rect_1)); - - // |rect_1| completely contains |rect_2|. - EXPECT_FLOAT_EQ(0.075f, PercentCoveredBy(rect_1, rect_2)); - EXPECT_FLOAT_EQ(1.0f, PercentCoveredBy(rect_2, rect_1)); - - // |rect_2| and |rect_3| do not intersect. - EXPECT_FLOAT_EQ(0.0f, PercentCoveredBy(rect_2, rect_3)); - - // |rect_1| and |rect_3| have a nonzero area of intersection which - // is smaller than the area of either rectangle. - EXPECT_NEAR(0.272f, PercentCoveredBy(rect_1, rect_3), error); - EXPECT_NEAR(0.768f, PercentCoveredBy(rect_3, rect_1), error); - - // |rect_4| has no area. - EXPECT_FLOAT_EQ(0.0f, PercentCoveredBy(rect_2, rect_4)); - EXPECT_FLOAT_EQ(0.0f, PercentCoveredBy(rect_4, rect_2)); -} - -TEST(RectBasedTargetingUtils, DistanceSquaredFromCenterToPoint) { - gfx::Rect rect_1(gfx::Point(0, 0), gfx::Size(10, 10)); - gfx::Rect rect_2(gfx::Point(20, 0), gfx::Size(80, 10)); - gfx::Rect rect_3(gfx::Point(0, 20), gfx::Size(10, 20)); - - gfx::Point point_1(5, 5); - gfx::Point point_2(25, 5); - gfx::Point point_3(11, 15); - gfx::Point point_4(33, 44); - - EXPECT_EQ(0, DistanceSquaredFromCenterToPoint(point_1, rect_1)); - EXPECT_EQ(1225, DistanceSquaredFromCenterToPoint(point_2, rect_2)); - EXPECT_EQ(3025, DistanceSquaredFromCenterToPoint(point_1, rect_2)); - EXPECT_EQ(1025, DistanceSquaredFromCenterToPoint(point_2, rect_3)); - EXPECT_EQ(2501, DistanceSquaredFromCenterToPoint(point_3, rect_2)); - EXPECT_EQ(136, DistanceSquaredFromCenterToPoint(point_3, rect_1)); - EXPECT_EQ(980, DistanceSquaredFromCenterToPoint(point_4, rect_3)); -} - -} // namespace views
diff --git a/ui/views/repeat_controller.cc b/ui/views/repeat_controller.cc deleted file mode 100644 index dd90aaa..0000000 --- a/ui/views/repeat_controller.cc +++ /dev/null
@@ -1,45 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/repeat_controller.h" - -using base::TimeDelta; - -namespace views { - -// The delay before the first and then subsequent repeats. Values taken from -// XUL code: http://mxr.mozilla.org/seamonkey/source/layout/xul/base/src/nsRepeatService.cpp#52 -const int kInitialRepeatDelay = 250; -const int kRepeatDelay = 50; - -/////////////////////////////////////////////////////////////////////////////// -// RepeatController, public: - -RepeatController::RepeatController(const base::Closure& callback) - : callback_(callback) { -} - -RepeatController::~RepeatController() { -} - -void RepeatController::Start() { - // The first timer is slightly longer than subsequent repeats. - timer_.Start(FROM_HERE, TimeDelta::FromMilliseconds(kInitialRepeatDelay), - this, &RepeatController::Run); -} - -void RepeatController::Stop() { - timer_.Stop(); -} - -/////////////////////////////////////////////////////////////////////////////// -// RepeatController, private: - -void RepeatController::Run() { - timer_.Start(FROM_HERE, TimeDelta::FromMilliseconds(kRepeatDelay), this, - &RepeatController::Run); - callback_.Run(); -} - -} // namespace views
diff --git a/ui/views/repeat_controller.h b/ui/views/repeat_controller.h deleted file mode 100644 index 3a93ea5..0000000 --- a/ui/views/repeat_controller.h +++ /dev/null
@@ -1,49 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_REPEAT_CONTROLLER_H_ -#define UI_VIEWS_REPEAT_CONTROLLER_H_ - -#include "base/callback.h" -#include "base/timer/timer.h" - -namespace views { - -/////////////////////////////////////////////////////////////////////////////// -// -// RepeatController -// -// An object that handles auto-repeating UI actions. There is a longer initial -// delay after which point repeats become constant. Users provide a callback -// that is notified when each repeat occurs so that they can perform the -// associated action. -// -/////////////////////////////////////////////////////////////////////////////// -class RepeatController { - public: - // The RepeatController takes ownership of this callback object. - explicit RepeatController(const base::Closure& callback); - virtual ~RepeatController(); - - // Start repeating. - void Start(); - - // Stop repeating. - void Stop(); - - private: - // Called when the timer expires. - void Run(); - - // The current timer. - base::OneShotTimer<RepeatController> timer_; - - base::Closure callback_; - - DISALLOW_COPY_AND_ASSIGN(RepeatController); -}; - -} // namespace views - -#endif // UI_VIEWS_REPEAT_CONTROLLER_H_
diff --git a/ui/views/round_rect_painter.cc b/ui/views/round_rect_painter.cc deleted file mode 100644 index 1b96a12..0000000 --- a/ui/views/round_rect_painter.cc +++ /dev/null
@@ -1,39 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/round_rect_painter.h" - -#include "ui/gfx/canvas.h" -#include "ui/gfx/path.h" -#include "ui/gfx/skia_util.h" - -namespace views { - -RoundRectPainter::RoundRectPainter(SkColor border_color, int corner_radius) - : border_color_(border_color), - corner_radius_(corner_radius) { -} - -RoundRectPainter::~RoundRectPainter() { -} - -gfx::Size RoundRectPainter::GetMinimumSize() const { - return gfx::Size(1, 1); -} - -void RoundRectPainter::Paint(gfx::Canvas* canvas, const gfx::Size& size) { - SkPaint paint; - paint.setColor(border_color_); - paint.setStyle(SkPaint::kStroke_Style); - paint.setStrokeWidth(1); - paint.setFlags(SkPaint::kAntiAlias_Flag); - gfx::Rect rect(size); - rect.Inset(0, 0, 1, 1); - SkRect skia_rect = gfx::RectToSkRect(rect); - skia_rect.offset(.5, .5); - canvas->sk_canvas()->drawRoundRect(skia_rect, SkIntToScalar(corner_radius_), - SkIntToScalar(corner_radius_), paint); -} - -} // namespace views
diff --git a/ui/views/round_rect_painter.h b/ui/views/round_rect_painter.h deleted file mode 100644 index e498e8c..0000000 --- a/ui/views/round_rect_painter.h +++ /dev/null
@@ -1,39 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_ROUNDED_RECT_PAINTER_H_ -#define UI_VIEWS_ROUNDED_RECT_PAINTER_H_ - -#include "ui/gfx/rect.h" -#include "ui/views/painter.h" -#include "ui/views/views_export.h" - -namespace gfx { -class Canvas; -class Path; -class Size; -} - -namespace views { - -// Painter to draw a border with rounded corners. -class VIEWS_EXPORT RoundRectPainter : public Painter { - public: - RoundRectPainter(SkColor border_color, int corner_radius); - virtual ~RoundRectPainter(); - - // Painter: - virtual gfx::Size GetMinimumSize() const override; - virtual void Paint(gfx::Canvas* canvas, const gfx::Size& size) override; - - private: - const SkColor border_color_; - const int corner_radius_; - - DISALLOW_COPY_AND_ASSIGN(RoundRectPainter); -}; - -} // namespace views - -#endif // UI_VIEWS_ROUNDED_RECT_PAINTER_H_
diff --git a/ui/views/run_all_unittests.cc b/ui/views/run_all_unittests.cc deleted file mode 100644 index bf7624c..0000000 --- a/ui/views/run_all_unittests.cc +++ /dev/null
@@ -1,46 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/basictypes.h" -#include "base/bind.h" -#include "base/compiler_specific.h" -#include "base/path_service.h" -#include "base/test/launcher/unit_test_launcher.h" -#include "base/test/test_suite.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/base/ui_base_paths.h" -#include "ui/gl/gl_surface.h" - -class ViewTestSuite : public base::TestSuite { - public: - ViewTestSuite(int argc, char** argv) : base::TestSuite(argc, argv) {} - - protected: - virtual void Initialize() override { - base::TestSuite::Initialize(); - gfx::GLSurface::InitializeOneOffForTests(); - ui::RegisterPathProvider(); - - base::FilePath ui_test_pak_path; - ASSERT_TRUE(PathService::Get(ui::UI_TEST_PAK, &ui_test_pak_path)); - ui::ResourceBundle::InitSharedInstanceWithPakPath(ui_test_pak_path); - } - - virtual void Shutdown() override { - ui::ResourceBundle::CleanupSharedInstance(); - base::TestSuite::Shutdown(); - } - - private: - DISALLOW_COPY_AND_ASSIGN(ViewTestSuite); -}; - -int main(int argc, char** argv) { - ViewTestSuite test_suite(argc, argv); - - return base::LaunchUnitTests( - argc, argv, base::Bind(&ViewTestSuite::Run, - base::Unretained(&test_suite))); -}
diff --git a/ui/views/shadow_border.cc b/ui/views/shadow_border.cc deleted file mode 100644 index 3cd21c9..0000000 --- a/ui/views/shadow_border.cc +++ /dev/null
@@ -1,56 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/shadow_border.h" - -#include "ui/gfx/canvas.h" -#include "ui/gfx/insets.h" -#include "ui/gfx/rect.h" -#include "ui/gfx/shadow_value.h" -#include "ui/gfx/skia_util.h" -#include "ui/views/view.h" - -namespace views { - -ShadowBorder::ShadowBorder(int blur, - SkColor color, - int vertical_offset, - int horizontal_offset) - : views::Border(), - blur_(blur), - color_(color), - vertical_offset_(vertical_offset), - horizontal_offset_(horizontal_offset) {} - -ShadowBorder::~ShadowBorder() {} - -// TODO(sidharthms): Re-painting a shadow looper on every paint call may yield -// poor performance. Ideally we should be caching the border to bitmaps. -void ShadowBorder::Paint(const views::View& view, gfx::Canvas* canvas) { - SkPaint paint; - std::vector<gfx::ShadowValue> shadows; - shadows.push_back(gfx::ShadowValue(gfx::Point(), blur_, color_)); - skia::RefPtr<SkDrawLooper> looper = gfx::CreateShadowDrawLooper(shadows); - paint.setLooper(looper.get()); - paint.setColor(SK_ColorTRANSPARENT); - paint.setStrokeJoin(SkPaint::kRound_Join); - gfx::Rect bounds(view.size()); - // TODO(pkasting): This isn't right if one of the offsets is larger than - // (blur_ / 2). - bounds.Inset(gfx::Insets(blur_ / 2, blur_ / 2, blur_ / 2, blur_ / 2)); - canvas->DrawRect(bounds, paint); -} - -gfx::Insets ShadowBorder::GetInsets() const { - return gfx::Insets(blur_ / 2 - vertical_offset_, - blur_ / 2 - horizontal_offset_, - blur_ / 2 + vertical_offset_, - blur_ / 2 + horizontal_offset_); -} - -gfx::Size ShadowBorder::GetMinimumSize() const { - return gfx::Size(blur_, blur_); -} - -} // namespace views
diff --git a/ui/views/shadow_border.h b/ui/views/shadow_border.h deleted file mode 100644 index b6aff3f..0000000 --- a/ui/views/shadow_border.h +++ /dev/null
@@ -1,48 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_SHADOW_BORDER_H_ -#define UI_VIEWS_SHADOW_BORDER_H_ - -#include "third_party/skia/include/core/SkColor.h" -#include "ui/views/border.h" -#include "ui/views/views_export.h" - -namespace views { - -// Creates a css box-shadow like border which fades into SK_ColorTRANSPARENT. -class VIEWS_EXPORT ShadowBorder : public views::Border { - public: - ShadowBorder(int blur, - SkColor color, - int vertical_offset, - int horizontal_offset); - virtual ~ShadowBorder(); - - protected: - // Overridden from views::Border: - virtual void Paint(const views::View& view, gfx::Canvas* canvas) override; - virtual gfx::Insets GetInsets() const override; - virtual gfx::Size GetMinimumSize() const override; - - private: - // Blur amount of the shadow in pixels. For details on how blur is defined see - // comments for blur_ in class ShadowValue. - const int blur_; - - // Shadow color. - const SkColor color_; - - // Number of pixels to shift shadow to bottom. - const int vertical_offset_; - - // Number of pixels to shift shadow to right. - const int horizontal_offset_; - - DISALLOW_COPY_AND_ASSIGN(ShadowBorder); -}; - -} // namespace views - -#endif // UI_VIEWS_SHADOW_BORDER_H_
diff --git a/ui/views/test/DEPS b/ui/views/test/DEPS deleted file mode 100644 index b969a40..0000000 --- a/ui/views/test/DEPS +++ /dev/null
@@ -1,3 +0,0 @@ -include_rules = [ - "+content/public/test", -]
diff --git a/ui/views/test/capture_tracking_view.cc b/ui/views/test/capture_tracking_view.cc deleted file mode 100644 index 921980d..0000000 --- a/ui/views/test/capture_tracking_view.cc +++ /dev/null
@@ -1,28 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/test/capture_tracking_view.h" - -namespace views { -namespace test { - -CaptureTrackingView::CaptureTrackingView() - : got_press_(false), - got_capture_lost_(false) { -} - -CaptureTrackingView::~CaptureTrackingView() { -} - -bool CaptureTrackingView::OnMousePressed(const ui::MouseEvent& event) { - got_press_ = true; - return true; -} - -void CaptureTrackingView::OnMouseCaptureLost() { - got_capture_lost_ = true; -} - -} // namespace test -} // namespace views
diff --git a/ui/views/test/capture_tracking_view.h b/ui/views/test/capture_tracking_view.h deleted file mode 100644 index a80cab0..0000000 --- a/ui/views/test/capture_tracking_view.h +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_TEST_CAPTURE_TRACKING_VIEW_ -#define UI_VIEWS_TEST_CAPTURE_TRACKING_VIEW_ - -#include "base/compiler_specific.h" -#include "ui/views/view.h" - -namespace views { -namespace test { - -// Used to track OnMousePressed() and OnMouseCaptureLost(). -class CaptureTrackingView : public views::View { - public: - CaptureTrackingView(); - virtual ~CaptureTrackingView(); - - // Returns true if OnMousePressed() has been invoked. - bool got_press() const { return got_press_; } - - // Returns true if OnMouseCaptureLost() has been invoked. - bool got_capture_lost() const { return got_capture_lost_; } - - void reset() { got_press_ = got_capture_lost_ = false; } - - // Overridden from views::View - virtual bool OnMousePressed(const ui::MouseEvent& event) override; - virtual void OnMouseCaptureLost() override; - - private: - // See description above getters. - bool got_press_; - bool got_capture_lost_; - - DISALLOW_COPY_AND_ASSIGN(CaptureTrackingView); -}; - -} // namespace test -} // namespace views - -#endif // UI_VIEWS_TEST_CAPTURE_TRACKING_VIEW_
diff --git a/ui/views/test/desktop_test_views_delegate.h b/ui/views/test/desktop_test_views_delegate.h deleted file mode 100644 index 26d24c2..0000000 --- a/ui/views/test/desktop_test_views_delegate.h +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_TEST_DESKTOP_TEST_VIEWS_DELEGATE_H_ -#define UI_VIEWS_TEST_DESKTOP_TEST_VIEWS_DELEGATE_H_ - -#include "ui/views/test/test_views_delegate.h" - -namespace views { - -// Most aura test code is written assuming a single RootWindow view, however, -// at higher levels like content_browsertests and -// views_examples_with_content_exe, we must use the Desktop variants. -class DesktopTestViewsDelegate : public TestViewsDelegate { - public: - DesktopTestViewsDelegate(); - virtual ~DesktopTestViewsDelegate(); - - // Overridden from ViewsDelegate: - virtual void OnBeforeWidgetInit(Widget::InitParams* params, - internal::NativeWidgetDelegate* delegate) override; - - private: - DISALLOW_COPY_AND_ASSIGN(DesktopTestViewsDelegate); -}; - -} // namespace views - -#endif
diff --git a/ui/views/test/desktop_test_views_delegate_aura.cc b/ui/views/test/desktop_test_views_delegate_aura.cc deleted file mode 100644 index 96f6391..0000000 --- a/ui/views/test/desktop_test_views_delegate_aura.cc +++ /dev/null
@@ -1,38 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/test/desktop_test_views_delegate.h" - -#include "ui/views/widget/native_widget_aura.h" - -#if !defined(OS_CHROMEOS) -#include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" -#endif - -namespace views { - -DesktopTestViewsDelegate::DesktopTestViewsDelegate() {} - -DesktopTestViewsDelegate::~DesktopTestViewsDelegate() {} - -void DesktopTestViewsDelegate::OnBeforeWidgetInit( - Widget::InitParams* params, - internal::NativeWidgetDelegate* delegate) { -#if !defined(OS_CHROMEOS) - // If we already have a native_widget, we don't have to try to come - // up with one. - if (params->native_widget) - return; - - if (params->parent && - params->type != views::Widget::InitParams::TYPE_MENU && - params->type != views::Widget::InitParams::TYPE_TOOLTIP) { - params->native_widget = new views::NativeWidgetAura(delegate); - } else { - params->native_widget = new views::DesktopNativeWidgetAura(delegate); - } -#endif -} - -} // namespace views
diff --git a/ui/views/test/focus_manager_test.cc b/ui/views/test/focus_manager_test.cc deleted file mode 100644 index cb1cb9d..0000000 --- a/ui/views/test/focus_manager_test.cc +++ /dev/null
@@ -1,143 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/test/focus_manager_test.h" - -#include <algorithm> - -#include "ui/views/focus/focus_manager.h" -#include "ui/views/widget/widget.h" - -namespace views { - -//////////////////////////////////////////////////////////////////////////////// -// FocusManagerTest, public: - -FocusManagerTest::FocusManagerTest() - : contents_view_(new View), - focus_change_listener_(NULL), - widget_focus_change_listener_(NULL) { -} - -FocusManagerTest::~FocusManagerTest() { -} - -FocusManager* FocusManagerTest::GetFocusManager() { - return GetWidget()->GetFocusManager(); -} - -//////////////////////////////////////////////////////////////////////////////// -// FocusManagerTest, ViewTestBase overrides: - -void FocusManagerTest::SetUp() { - ViewsTestBase::SetUp(); - - Widget* widget = new Widget; - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); - params.delegate = this; - params.bounds = gfx::Rect(0, 0, 1024, 768); - widget->Init(params); - - InitContentView(); - widget->Show(); -} - -void FocusManagerTest::TearDown() { - if (focus_change_listener_) - GetFocusManager()->RemoveFocusChangeListener(focus_change_listener_); - if (widget_focus_change_listener_) { - WidgetFocusManager::GetInstance()->RemoveFocusChangeListener( - widget_focus_change_listener_); - } - GetWidget()->Close(); - - // Flush the message loop to make application verifiers happy. - RunPendingMessages(); - ViewsTestBase::TearDown(); -} - -//////////////////////////////////////////////////////////////////////////////// -// FocusManagerTest, WidgetDelegate implementation: - -View* FocusManagerTest::GetContentsView() { - return contents_view_; -} - -Widget* FocusManagerTest::GetWidget() { - return contents_view_->GetWidget(); -} - -const Widget* FocusManagerTest::GetWidget() const { - return contents_view_->GetWidget(); -} - -void FocusManagerTest::GetAccessiblePanes(std::vector<View*>* panes) { - std::copy(accessible_panes_.begin(), accessible_panes_.end(), - std::back_inserter(*panes)); -} - -//////////////////////////////////////////////////////////////////////////////// -// FocusManagerTest, protected: - -void FocusManagerTest::InitContentView() { -} - -void FocusManagerTest::AddFocusChangeListener(FocusChangeListener* listener) { - ASSERT_FALSE(focus_change_listener_); - focus_change_listener_ = listener; - GetFocusManager()->AddFocusChangeListener(listener); -} - -void FocusManagerTest::AddWidgetFocusChangeListener( - WidgetFocusChangeListener* listener) { - ASSERT_FALSE(widget_focus_change_listener_); - widget_focus_change_listener_ = listener; - WidgetFocusManager::GetInstance()->AddFocusChangeListener(listener); -} - -void FocusManagerTest::SetAccessiblePanes(const std::vector<View*>& panes) { - accessible_panes_ = panes; -} - -//////////////////////////////////////////////////////////////////////////////// -// TestFocusChangeListener - -TestFocusChangeListener::TestFocusChangeListener() { -} - -TestFocusChangeListener::~TestFocusChangeListener() { -} - -void TestFocusChangeListener::OnWillChangeFocus(View* focused_before, - View* focused_now) { - focus_changes_.push_back(ViewPair(focused_before, focused_now)); -} -void TestFocusChangeListener::OnDidChangeFocus(View* focused_before, - View* focused_now) { -} - -void TestFocusChangeListener::ClearFocusChanges() { - focus_changes_.clear(); -} - -//////////////////////////////////////////////////////////////////////////////// -// TestWidgetFocusChangeListener - -TestWidgetFocusChangeListener::TestWidgetFocusChangeListener() { -} - -TestWidgetFocusChangeListener::~TestWidgetFocusChangeListener() { -} - -void TestWidgetFocusChangeListener::ClearFocusChanges() { - focus_changes_.clear(); -} - -void TestWidgetFocusChangeListener::OnNativeFocusChange( - gfx::NativeView focused_before, - gfx::NativeView focused_now) { - focus_changes_.push_back(NativeViewPair(focused_before, focused_now)); -} - -} // namespace views
diff --git a/ui/views/test/focus_manager_test.h b/ui/views/test/focus_manager_test.h deleted file mode 100644 index 39184d2..0000000 --- a/ui/views/test/focus_manager_test.h +++ /dev/null
@@ -1,106 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_TEST_FOCUS_MANAGER_TEST_H_ -#define UI_VIEWS_TEST_FOCUS_MANAGER_TEST_H_ - -#include "ui/views/focus/focus_manager.h" -#include "ui/views/focus/widget_focus_manager.h" -#include "ui/views/test/views_test_base.h" -#include "ui/views/widget/widget_delegate.h" - -namespace views { - -class FocusChangeListener; - -class FocusManagerTest : public ViewsTestBase, public WidgetDelegate { - public: - FocusManagerTest(); - virtual ~FocusManagerTest(); - - // Convenience to obtain the focus manager for the test's hosting widget. - FocusManager* GetFocusManager(); - - // Overridden from ViewsTestBase: - virtual void SetUp() override; - virtual void TearDown() override; - - // Overridden from WidgetDelegate: - virtual View* GetContentsView() override; - virtual Widget* GetWidget() override; - virtual const Widget* GetWidget() const override; - virtual void GetAccessiblePanes(std::vector<View*>* panes) override; - - protected: - // Called after the Widget is initialized and the content view is added. - // Override to add controls to the layout. - virtual void InitContentView(); - - void AddFocusChangeListener(FocusChangeListener* listener); - void AddWidgetFocusChangeListener(WidgetFocusChangeListener* listener); - - // For testing FocusManager::RotatePaneFocus(). - void SetAccessiblePanes(const std::vector<View*>& panes); - - private: - View* contents_view_; - FocusChangeListener* focus_change_listener_; - WidgetFocusChangeListener* widget_focus_change_listener_; - std::vector<View*> accessible_panes_; - - DISALLOW_COPY_AND_ASSIGN(FocusManagerTest); -}; - -typedef std::pair<View*, View*> ViewPair; - -// Use to record focus change notifications. -class TestFocusChangeListener : public FocusChangeListener { - public: - TestFocusChangeListener(); - virtual ~TestFocusChangeListener(); - - const std::vector<ViewPair>& focus_changes() const { return focus_changes_; } - void ClearFocusChanges(); - - // Overridden from FocusChangeListener: - virtual void OnWillChangeFocus(View* focused_before, - View* focused_now) override; - virtual void OnDidChangeFocus(View* focused_before, - View* focused_now) override; - - private: - // A vector of which views lost/gained focus. - std::vector<ViewPair> focus_changes_; - - DISALLOW_COPY_AND_ASSIGN(TestFocusChangeListener); -}; - -typedef std::pair<gfx::NativeView, gfx::NativeView> NativeViewPair; - -// Use to record widget focus change notifications. -class TestWidgetFocusChangeListener : public WidgetFocusChangeListener { - public: - TestWidgetFocusChangeListener(); - virtual ~TestWidgetFocusChangeListener(); - - const std::vector<NativeViewPair>& focus_changes() const { - return focus_changes_; - } - void ClearFocusChanges(); - - // Overridden from WidgetFocusChangeListener: - virtual void OnNativeFocusChange(gfx::NativeView focused_before, - gfx::NativeView focused_now) override; - - private: - // Pairs of (focused_before, focused_now) parameters we've received via calls - // to OnNativeFocusChange(), in oldest-to-newest-received order. - std::vector<NativeViewPair> focus_changes_; - - DISALLOW_COPY_AND_ASSIGN(TestWidgetFocusChangeListener); -}; - -} // namespace views - -#endif // UI_VIEWS_TEST_FOCUS_MANAGER_TEST_H_
diff --git a/ui/views/test/menu_runner_test_api.cc b/ui/views/test/menu_runner_test_api.cc deleted file mode 100644 index c297700..0000000 --- a/ui/views/test/menu_runner_test_api.cc +++ /dev/null
@@ -1,26 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/test/menu_runner_test_api.h" - -#include "ui/views/controls/menu/menu_runner.h" -#include "ui/views/controls/menu/menu_runner_handler.h" - -namespace views { -namespace test { - -MenuRunnerTestAPI::MenuRunnerTestAPI(MenuRunner* menu_runner) - : menu_runner_(menu_runner) { -} - -MenuRunnerTestAPI::~MenuRunnerTestAPI() { -} - -void MenuRunnerTestAPI::SetMenuRunnerHandler( - scoped_ptr<MenuRunnerHandler> menu_runner_handler) { - menu_runner_->SetRunnerHandler(menu_runner_handler.Pass()); -} - -} // test -} // views
diff --git a/ui/views/test/menu_runner_test_api.h b/ui/views/test/menu_runner_test_api.h deleted file mode 100644 index a9e2b8e..0000000 --- a/ui/views/test/menu_runner_test_api.h +++ /dev/null
@@ -1,37 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_TEST_MENU_RUNNER_TEST_API_H_ -#define UI_VIEWS_TEST_MENU_RUNNER_TEST_API_H_ - -#include "base/basictypes.h" -#include "base/memory/scoped_ptr.h" - -namespace views { - -class MenuRunner; -class MenuRunnerHandler; - -namespace test { - -// A wrapper of MenuRunner to use testing methods of MenuRunner. -class MenuRunnerTestAPI { - public: - explicit MenuRunnerTestAPI(MenuRunner* menu_runner); - ~MenuRunnerTestAPI(); - - // Sets the menu runner handler. - void SetMenuRunnerHandler(scoped_ptr<MenuRunnerHandler> menu_runner_handler); - - private: - MenuRunner* menu_runner_; - - DISALLOW_COPY_AND_ASSIGN(MenuRunnerTestAPI); -}; - -} // namespace test - -} // namespace views - -#endif // UI_VIEWS_TEST_MENU_RUNNER_TEST_API_H_
diff --git a/ui/views/test/slider_test_api.cc b/ui/views/test/slider_test_api.cc deleted file mode 100644 index 243fa55..0000000 --- a/ui/views/test/slider_test_api.cc +++ /dev/null
@@ -1,23 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/test/slider_test_api.h" - -#include "ui/views/controls/slider.h" - -namespace views { -namespace test { - -SliderTestApi::SliderTestApi(Slider* slider) : slider_(slider) { -} - -SliderTestApi::~SliderTestApi() { -} - -void SliderTestApi::SetListener(SliderListener* listener) { - slider_->set_listener(listener); -} - -} // namespace test -} // namespace views
diff --git a/ui/views/test/slider_test_api.h b/ui/views/test/slider_test_api.h deleted file mode 100644 index 749ff4e..0000000 --- a/ui/views/test/slider_test_api.h +++ /dev/null
@@ -1,38 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_TEST_SLIDER_TEST_API_H_ -#define UI_VIEWS_TEST_SLIDER_TEST_API_H_ - -#include "base/basictypes.h" - -namespace views { - -class Slider; -class SliderListener; - -namespace test { - -// Can be used to update the private state of a views::Slider instance during a -// test. Updating the private state of an already created instance reduces -// the amount of test setup and test fixture code required. -class SliderTestApi { - public: - explicit SliderTestApi(Slider* slider); - virtual ~SliderTestApi(); - - // Set the SliderListener on the Slider. - void SetListener(SliderListener* listener); - - private: - Slider* slider_; - - DISALLOW_COPY_AND_ASSIGN(SliderTestApi); -}; - -} // namespace test - -} // namespace views - -#endif // UI_VIEWS_TEST_SLIDER_TEST_API_H_
diff --git a/ui/views/test/test_views.cc b/ui/views/test/test_views.cc deleted file mode 100644 index 320ec8e..0000000 --- a/ui/views/test/test_views.cc +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/test/test_views.h" - -namespace views { - -StaticSizedView::StaticSizedView(const gfx::Size& size) : size_(size) {} - -StaticSizedView::~StaticSizedView() {} - -gfx::Size StaticSizedView::GetPreferredSize() const { - return size_; -} - -ProportionallySizedView::ProportionallySizedView(int factor) - : factor_(factor), preferred_width_(-1) {} - -ProportionallySizedView::~ProportionallySizedView() {} - -int ProportionallySizedView::GetHeightForWidth(int w) const { - return w * factor_; -} - -gfx::Size ProportionallySizedView::GetPreferredSize() const { - if (preferred_width_ >= 0) - return gfx::Size(preferred_width_, GetHeightForWidth(preferred_width_)); - return View::GetPreferredSize(); -} - -} // namespace views
diff --git a/ui/views/test/test_views.h b/ui/views/test/test_views.h deleted file mode 100644 index 429e59f..0000000 --- a/ui/views/test/test_views.h +++ /dev/null
@@ -1,51 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_TEST_TEST_VIEWS_H_ -#define UI_VIEWS_TEST_TEST_VIEWS_H_ - -#include "base/memory/scoped_ptr.h" -#include "ui/views/view.h" - -namespace views { - -// A view that requests a set amount of space. -class StaticSizedView : public View { - public: - explicit StaticSizedView(const gfx::Size& size); - virtual ~StaticSizedView(); - - virtual gfx::Size GetPreferredSize() const override; - - private: - gfx::Size size_; - - DISALLOW_COPY_AND_ASSIGN(StaticSizedView); -}; - -// A view that accomodates testing layouts that use GetHeightForWidth. -class ProportionallySizedView : public View { - public: - explicit ProportionallySizedView(int factor); - virtual ~ProportionallySizedView(); - - void set_preferred_width(int width) { preferred_width_ = width; } - - virtual int GetHeightForWidth(int w) const override; - virtual gfx::Size GetPreferredSize() const override; - - private: - // The multiplicative factor between width and height, i.e. - // height = width * factor_. - int factor_; - - // The width used as the preferred size. -1 if not used. - int preferred_width_; - - DISALLOW_COPY_AND_ASSIGN(ProportionallySizedView); -}; - -} // namespace views - -#endif // UI_VIEWS_TEST_TEST_VIEWS_H_
diff --git a/ui/views/test/test_views_delegate.h b/ui/views/test/test_views_delegate.h deleted file mode 100644 index 20802e7..0000000 --- a/ui/views/test/test_views_delegate.h +++ /dev/null
@@ -1,54 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_TEST_TEST_VIEWS_DELEGATE_H_ -#define UI_VIEWS_TEST_TEST_VIEWS_DELEGATE_H_ - -#include "base/memory/scoped_ptr.h" -#include "ui/views/views_delegate.h" - -namespace wm { -class WMState; -} - -namespace views { - -class TestViewsDelegate : public ViewsDelegate { - public: - TestViewsDelegate(); - virtual ~TestViewsDelegate(); - - // If set to |true|, forces widgets that do not provide a native widget to use - // DesktopNativeWidgetAura instead of whatever the default native widget would - // be. This has no effect on ChromeOS. - void set_use_desktop_native_widgets(bool desktop) { - use_desktop_native_widgets_ = desktop; - } - - void set_use_transparent_windows(bool transparent) { - use_transparent_windows_ = transparent; - } - - // ViewsDelegate: - virtual void OnBeforeWidgetInit( - Widget::InitParams* params, - internal::NativeWidgetDelegate* delegate) override; - - private: - bool use_desktop_native_widgets_; - - bool use_transparent_windows_; - -#if defined(USE_AURA) - scoped_ptr<wm::WMState> wm_state_; - - ui::ContextFactory* context_factory_; -#endif - - DISALLOW_COPY_AND_ASSIGN(TestViewsDelegate); -}; - -} // namespace views - -#endif // UI_VIEWS_TEST_TEST_VIEWS_DELEGATE_H_
diff --git a/ui/views/test/test_views_delegate_aura.cc b/ui/views/test/test_views_delegate_aura.cc deleted file mode 100644 index 62efccf..0000000 --- a/ui/views/test/test_views_delegate_aura.cc +++ /dev/null
@@ -1,45 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/test/test_views_delegate.h" - -#include "ui/wm/core/wm_state.h" - -#if !defined(OS_CHROMEOS) -#include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" -#endif // !defined(OS_CHROMEOS) - - -namespace views { - -TestViewsDelegate::TestViewsDelegate() - : use_desktop_native_widgets_(false), - use_transparent_windows_(false) { - DCHECK(!ViewsDelegate::views_delegate); - ViewsDelegate::views_delegate = this; -#if defined(USE_AURA) - wm_state_.reset(new wm::WMState); -#endif -} - -TestViewsDelegate::~TestViewsDelegate() { - if (ViewsDelegate::views_delegate == this) - ViewsDelegate::views_delegate = NULL; -} - -void TestViewsDelegate::OnBeforeWidgetInit( - Widget::InitParams* params, - internal::NativeWidgetDelegate* delegate) { - if (params->opacity == Widget::InitParams::INFER_OPACITY) { - params->opacity = use_transparent_windows_ ? - Widget::InitParams::TRANSLUCENT_WINDOW : - Widget::InitParams::OPAQUE_WINDOW; - } -#if !defined(OS_CHROMEOS) - if (!params->native_widget && use_desktop_native_widgets_) - params->native_widget = new DesktopNativeWidgetAura(delegate); -#endif // !defined(OS_CHROMEOS) -} - -} // namespace views
diff --git a/ui/views/test/test_views_delegate_mac.mm b/ui/views/test/test_views_delegate_mac.mm deleted file mode 100644 index 79b620b..0000000 --- a/ui/views/test/test_views_delegate_mac.mm +++ /dev/null
@@ -1,36 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/test/test_views_delegate.h" - -#include "ui/views/widget/native_widget_mac.h" - -namespace views { - -TestViewsDelegate::TestViewsDelegate() - : use_desktop_native_widgets_(false), - use_transparent_windows_(false) { - DCHECK(!ViewsDelegate::views_delegate); - ViewsDelegate::views_delegate = this; -} - -TestViewsDelegate::~TestViewsDelegate() { - if (ViewsDelegate::views_delegate == this) - ViewsDelegate::views_delegate = NULL; -} - -void TestViewsDelegate::OnBeforeWidgetInit( - Widget::InitParams* params, - internal::NativeWidgetDelegate* delegate) { - if (params->opacity == Widget::InitParams::INFER_OPACITY) { - params->opacity = use_transparent_windows_ ? - Widget::InitParams::TRANSLUCENT_WINDOW : - Widget::InitParams::OPAQUE_WINDOW; - } - // TODO(tapted): This should return a *Desktop*NativeWidgetMac. - if (!params->native_widget && use_desktop_native_widgets_) - params->native_widget = new NativeWidgetMac(delegate); -} - -} // namespace views
diff --git a/ui/views/test/test_widget_observer.cc b/ui/views/test/test_widget_observer.cc deleted file mode 100644 index 160f25b..0000000 --- a/ui/views/test/test_widget_observer.cc +++ /dev/null
@@ -1,29 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/test/test_widget_observer.h" - -#include "base/logging.h" -#include "ui/views/widget/widget.h" - -namespace views { -namespace test { - -TestWidgetObserver::TestWidgetObserver(Widget* widget) - : widget_(widget) { - widget_->AddObserver(this); -} - -TestWidgetObserver::~TestWidgetObserver() { - if (widget_) - widget_->RemoveObserver(this); -} - -void TestWidgetObserver::OnWidgetDestroying(Widget* widget) { - DCHECK_EQ(widget_, widget); - widget_ = NULL; -} - -} // namespace test -} // namespace views
diff --git a/ui/views/test/test_widget_observer.h b/ui/views/test/test_widget_observer.h deleted file mode 100644 index 064db84..0000000 --- a/ui/views/test/test_widget_observer.h +++ /dev/null
@@ -1,37 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_TEST_TEST_WIDGET_OBSERVER_H_ -#define UI_VIEWS_TEST_TEST_WIDGET_OBSERVER_H_ - -#include <stddef.h> - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "ui/views/widget/widget_observer.h" - -namespace views { -namespace test { - -// A Widget observer class used in the tests below to observe bubbles closing. -class TestWidgetObserver : public WidgetObserver { - public: - explicit TestWidgetObserver(Widget* widget); - virtual ~TestWidgetObserver(); - - bool widget_closed() const { return widget_ == NULL; } - - private: - // WidgetObserver overrides: - virtual void OnWidgetDestroying(Widget* widget) override; - - Widget* widget_; - - DISALLOW_COPY_AND_ASSIGN(TestWidgetObserver); -}; - -} // namespace test -} // namespace views - -#endif // UI_VIEWS_TEST_TEST_WIDGET_OBSERVER_H_
diff --git a/ui/views/test/views_test_base.cc b/ui/views/test/views_test_base.cc deleted file mode 100644 index ade40e8..0000000 --- a/ui/views/test/views_test_base.cc +++ /dev/null
@@ -1,72 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/test/views_test_base.h" - -#include "base/run_loop.h" -#include "ui/base/clipboard/clipboard.h" -#include "ui/base/ime/input_method_initializer.h" -#include "ui/compositor/test/context_factories_for_test.h" -#include "ui/views/test/views_test_helper.h" - -namespace views { - -ViewsTestBase::ViewsTestBase() - : setup_called_(false), - teardown_called_(false) { -} - -ViewsTestBase::~ViewsTestBase() { - CHECK(setup_called_) - << "You have overridden SetUp but never called super class's SetUp"; - CHECK(teardown_called_) - << "You have overridden TearDown but never called super class's TearDown"; -} - -void ViewsTestBase::SetUp() { - testing::Test::SetUp(); - setup_called_ = true; - if (!views_delegate_.get()) - views_delegate_.reset(new TestViewsDelegate()); - // The ContextFactory must exist before any Compositors are created. - bool enable_pixel_output = false; - ui::ContextFactory* context_factory = - ui::InitializeContextFactoryForTests(enable_pixel_output); - - test_helper_.reset(ViewsTestHelper::Create(&message_loop_, context_factory)); - test_helper_->SetUp(); - ui::InitializeInputMethodForTesting(); -} - -void ViewsTestBase::TearDown() { - ui::Clipboard::DestroyClipboardForCurrentThread(); - - // Flush the message loop because we have pending release tasks - // and these tasks if un-executed would upset Valgrind. - RunPendingMessages(); - teardown_called_ = true; - views_delegate_.reset(); - testing::Test::TearDown(); - ui::ShutdownInputMethodForTesting(); - test_helper_->TearDown(); - ui::TerminateContextFactoryForTests(); -} - -void ViewsTestBase::RunPendingMessages() { - base::RunLoop run_loop; - run_loop.RunUntilIdle(); -} - -Widget::InitParams ViewsTestBase::CreateParams( - Widget::InitParams::Type type) { - Widget::InitParams params(type); - params.context = GetContext(); - return params; -} - -gfx::NativeWindow ViewsTestBase::GetContext() { - return test_helper_->GetContext(); -} - -} // namespace views
diff --git a/ui/views/test/views_test_base.h b/ui/views/test/views_test_base.h deleted file mode 100644 index 9339da3..0000000 --- a/ui/views/test/views_test_base.h +++ /dev/null
@@ -1,68 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_TEST_VIEWS_TEST_BASE_H_ -#define UI_VIEWS_TEST_VIEWS_TEST_BASE_H_ - -#include "base/memory/scoped_ptr.h" -#include "base/message_loop/message_loop.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "testing/platform_test.h" -#include "ui/views/test/test_views_delegate.h" - -#if defined(OS_WIN) -#include "ui/base/win/scoped_ole_initializer.h" -#endif - -namespace views { - -class ViewsTestHelper; - -// A base class for views unit test. It creates a message loop necessary -// to drive UI events and takes care of OLE initialization for windows. -class ViewsTestBase : public PlatformTest { - public: - ViewsTestBase(); - virtual ~ViewsTestBase(); - - // testing::Test: - virtual void SetUp() override; - virtual void TearDown() override; - - void RunPendingMessages(); - - // Creates a widget of |type| with any platform specific data for use in - // cross-platform tests. - Widget::InitParams CreateParams(Widget::InitParams::Type type); - - protected: - TestViewsDelegate& views_delegate() const { return *views_delegate_.get(); } - - void set_views_delegate(TestViewsDelegate* views_delegate) { - views_delegate_.reset(views_delegate); - } - - base::MessageLoopForUI* message_loop() { return &message_loop_; } - - // Returns a context view. In aura builds, this will be the - // RootWindow. Everywhere else, NULL. - gfx::NativeWindow GetContext(); - - private: - base::MessageLoopForUI message_loop_; - scoped_ptr<TestViewsDelegate> views_delegate_; - scoped_ptr<ViewsTestHelper> test_helper_; - bool setup_called_; - bool teardown_called_; - -#if defined(OS_WIN) - ui::ScopedOleInitializer ole_initializer_; -#endif - - DISALLOW_COPY_AND_ASSIGN(ViewsTestBase); -}; - -} // namespace views - -#endif // UI_VIEWS_TEST_VIEWS_TEST_BASE_H_
diff --git a/ui/views/test/views_test_helper.cc b/ui/views/test/views_test_helper.cc deleted file mode 100644 index 75588a6..0000000 --- a/ui/views/test/views_test_helper.cc +++ /dev/null
@@ -1,25 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/test/views_test_helper.h" - -namespace views { - -ViewsTestHelper::ViewsTestHelper() { -} - -ViewsTestHelper::~ViewsTestHelper() { -} - -void ViewsTestHelper::SetUp() { -} - -void ViewsTestHelper::TearDown() { -} - -gfx::NativeWindow ViewsTestHelper::GetContext() { - return NULL; -} - -} // namespace views
diff --git a/ui/views/test/views_test_helper.h b/ui/views/test/views_test_helper.h deleted file mode 100644 index 8d73333..0000000 --- a/ui/views/test/views_test_helper.h +++ /dev/null
@@ -1,47 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_TEST_VIEWS_TEST_HELPER_H_ -#define UI_VIEWS_TEST_VIEWS_TEST_HELPER_H_ - -#include "ui/gfx/native_widget_types.h" - -namespace base { -class MessageLoopForUI; -} - -namespace ui { -class ContextFactory; -} - -namespace views { - -// A helper class owned by tests that performs platform specific initialization -// required for running tests. -class ViewsTestHelper { - public: - explicit ViewsTestHelper(); - virtual ~ViewsTestHelper(); - - // Create a platform specific instance. - static ViewsTestHelper* Create(base::MessageLoopForUI* message_loop, - ui::ContextFactory* context_factory); - - // Creates objects that are needed for tests. - virtual void SetUp(); - - // Clean up objects that were created for tests. - virtual void TearDown(); - - // Returns a context view. In aura builds, this will be the - // RootWindow. Everywhere else, NULL. - virtual gfx::NativeWindow GetContext(); - - private: - DISALLOW_COPY_AND_ASSIGN(ViewsTestHelper); -}; - -} // namespace views - -#endif // UI_VIEWS_TEST_VIEWS_TEST_HELPER_H_
diff --git a/ui/views/test/views_test_helper_aura.cc b/ui/views/test/views_test_helper_aura.cc deleted file mode 100644 index 5bc83d3..0000000 --- a/ui/views/test/views_test_helper_aura.cc +++ /dev/null
@@ -1,45 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/test/views_test_helper_aura.h" - -#include "ui/aura/test/aura_test_helper.h" -#include "ui/wm/core/capture_controller.h" -#include "ui/wm/core/default_activation_client.h" -#include "ui/wm/core/wm_state.h" - -namespace views { - -// static -ViewsTestHelper* ViewsTestHelper::Create(base::MessageLoopForUI* message_loop, - ui::ContextFactory* context_factory) { - return new ViewsTestHelperAura(message_loop, context_factory); -} - -ViewsTestHelperAura::ViewsTestHelperAura(base::MessageLoopForUI* message_loop, - ui::ContextFactory* context_factory) - : context_factory_(context_factory) { - aura_test_helper_.reset(new aura::test::AuraTestHelper(message_loop)); -} - -ViewsTestHelperAura::~ViewsTestHelperAura() { -} - -void ViewsTestHelperAura::SetUp() { - aura_test_helper_->SetUp(context_factory_); - new wm::DefaultActivationClient(aura_test_helper_->root_window()); - wm_state_.reset(new wm::WMState); -} - -void ViewsTestHelperAura::TearDown() { - aura_test_helper_->TearDown(); - wm_state_.reset(); - CHECK(!wm::ScopedCaptureClient::IsActive()); -} - -gfx::NativeWindow ViewsTestHelperAura::GetContext() { - return aura_test_helper_->root_window(); -} - -} // namespace views
diff --git a/ui/views/test/views_test_helper_aura.h b/ui/views/test/views_test_helper_aura.h deleted file mode 100644 index 87d48ae..0000000 --- a/ui/views/test/views_test_helper_aura.h +++ /dev/null
@@ -1,50 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_TEST_VIEWS_TEST_HELPER_AURA_H_ -#define UI_VIEWS_TEST_VIEWS_TEST_HELPER_AURA_H_ - -#include "base/compiler_specific.h" -#include "base/macros.h" -#include "base/memory/scoped_ptr.h" -#include "ui/views/test/views_test_helper.h" - -namespace aura { -namespace test { -class AuraTestHelper; -} -} - -namespace base { -class MessageLoopForUI; -} - -namespace wm { -class WMState; -} - -namespace views { - -class ViewsTestHelperAura : public ViewsTestHelper { - public: - ViewsTestHelperAura(base::MessageLoopForUI* message_loop, - ui::ContextFactory* context_factory); - virtual ~ViewsTestHelperAura(); - - // Overridden from ViewsTestHelper: - virtual void SetUp() override; - virtual void TearDown() override; - virtual gfx::NativeWindow GetContext() override; - - private: - ui::ContextFactory* context_factory_; - scoped_ptr<aura::test::AuraTestHelper> aura_test_helper_; - scoped_ptr<wm::WMState> wm_state_; - - DISALLOW_COPY_AND_ASSIGN(ViewsTestHelperAura); -}; - -} // namespace views - -#endif // UI_VIEWS_TEST_VIEWS_TEST_HELPER_AURA_H_
diff --git a/ui/views/test/views_test_helper_mac.h b/ui/views/test/views_test_helper_mac.h deleted file mode 100644 index 61491ae..0000000 --- a/ui/views/test/views_test_helper_mac.h +++ /dev/null
@@ -1,31 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_TEST_VIEWS_TEST_HELPER_MAC_H_ -#define UI_VIEWS_TEST_VIEWS_TEST_HELPER_MAC_H_ - -#include "base/memory/scoped_ptr.h" -#include "ui/views/test/views_test_helper.h" - -namespace ui { -class ScopedAnimationDurationScaleMode; -} - -namespace views { - -class ViewsTestHelperMac : public ViewsTestHelper { - public: - ViewsTestHelperMac(); - virtual ~ViewsTestHelperMac(); - - private: - // Disable animations during tests. - scoped_ptr<ui::ScopedAnimationDurationScaleMode> zero_duration_mode_; - - DISALLOW_COPY_AND_ASSIGN(ViewsTestHelperMac); -}; - -} // namespace views - -#endif // UI_VIEWS_TEST_VIEWS_TEST_HELPER_MAC_H_
diff --git a/ui/views/test/views_test_helper_mac.mm b/ui/views/test/views_test_helper_mac.mm deleted file mode 100644 index a50f4aa..0000000 --- a/ui/views/test/views_test_helper_mac.mm +++ /dev/null
@@ -1,27 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/test/views_test_helper_mac.h" - -#include "ui/compositor/scoped_animation_duration_scale_mode.h" -#include "ui/views/test/event_generator_delegate_mac.h" - -namespace views { - -// static -ViewsTestHelper* ViewsTestHelper::Create(base::MessageLoopForUI* message_loop, - ui::ContextFactory* context_factory) { - return new ViewsTestHelperMac; -} - -ViewsTestHelperMac::ViewsTestHelperMac() - : zero_duration_mode_(new ui::ScopedAnimationDurationScaleMode( - ui::ScopedAnimationDurationScaleMode::ZERO_DURATION)) { - test::InitializeMacEventGeneratorDelegate(); -} - -ViewsTestHelperMac::~ViewsTestHelperMac() { -} - -} // namespace views
diff --git a/ui/views/test/views_unittest.manifest b/ui/views/test/views_unittest.manifest deleted file mode 100644 index 76c6380..0000000 --- a/ui/views/test/views_unittest.manifest +++ /dev/null
@@ -1,8 +0,0 @@ -<?xml version="1.0" encoding="UTF-8" standalone="yes"?> -<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> - <dependency> - <dependentAssembly> - <assemblyIdentity type="Win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*"></assemblyIdentity> - </dependentAssembly> - </dependency> -</assembly>
diff --git a/ui/views/test/webview_test_helper.cc b/ui/views/test/webview_test_helper.cc deleted file mode 100644 index 81ac7b4..0000000 --- a/ui/views/test/webview_test_helper.cc +++ /dev/null
@@ -1,25 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/test/webview_test_helper.h" - -#include "content/public/test/test_content_client_initializer.h" -#include "ui/views/controls/webview/webview.h" - -namespace views { - -WebViewTestHelper::WebViewTestHelper() { - test_content_client_initializer_.reset( - new content::TestContentClientInitializer()); - - // Setup to register a new RenderViewHost factory which manufactures - // mock render process hosts. This ensures that we never create a 'real' - // render view host since support for it doesn't exist in unit tests. - test_content_client_initializer_->CreateTestRenderViewHosts(); -} - -WebViewTestHelper::~WebViewTestHelper() { -} - -} // namespace views
diff --git a/ui/views/test/webview_test_helper.h b/ui/views/test/webview_test_helper.h deleted file mode 100644 index c0fbdbf..0000000 --- a/ui/views/test/webview_test_helper.h +++ /dev/null
@@ -1,34 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_TEST_WEB_VIEW_TEST_HELPER_H_ -#define UI_VIEWS_TEST_WEB_VIEW_TEST_HELPER_H_ - -#include "base/memory/scoped_ptr.h" - -namespace base { -class MessageLoopForUI; -} - -namespace content { -class TestContentClientInitializer; -} // namespace content - -namespace views { - -class WebViewTestHelper { - public: - WebViewTestHelper(); - virtual ~WebViewTestHelper(); - - private: - scoped_ptr<content::TestContentClientInitializer> - test_content_client_initializer_; - - DISALLOW_COPY_AND_ASSIGN(WebViewTestHelper); -}; - -} // namespace views - -#endif // UI_VIEWS_TEST_WEB_VIEW_TEST_HELPER_H_
diff --git a/ui/views/test/widget_test.cc b/ui/views/test/widget_test.cc deleted file mode 100644 index 4f2705d..0000000 --- a/ui/views/test/widget_test.cc +++ /dev/null
@@ -1,107 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/test/widget_test.h" - -#include "ui/gfx/native_widget_types.h" -#include "ui/views/widget/root_view.h" - -namespace views { -namespace test { - -// A widget that assumes mouse capture always works. It won't in testing, so we -// mock it. -NativeWidgetCapture::NativeWidgetCapture( - internal::NativeWidgetDelegate* delegate) - : PlatformNativeWidget(delegate), - mouse_capture_(false) {} - -NativeWidgetCapture::~NativeWidgetCapture() {} - -void NativeWidgetCapture::SetCapture() { - mouse_capture_ = true; -} - -void NativeWidgetCapture::ReleaseCapture() { - if (mouse_capture_) - delegate()->OnMouseCaptureLost(); - mouse_capture_ = false; -} - -bool NativeWidgetCapture::HasCapture() const { - return mouse_capture_; -} - -WidgetTest::WidgetTest() {} -WidgetTest::~WidgetTest() {} - -NativeWidget* WidgetTest::CreatePlatformNativeWidget( - internal::NativeWidgetDelegate* delegate) { - return new NativeWidgetCapture(delegate); -} - -Widget* WidgetTest::CreateTopLevelPlatformWidget() { - Widget* toplevel = new Widget; - Widget::InitParams toplevel_params = - CreateParams(Widget::InitParams::TYPE_WINDOW); - toplevel_params.native_widget = CreatePlatformNativeWidget(toplevel); - toplevel->Init(toplevel_params); - return toplevel; -} - -Widget* WidgetTest::CreateTopLevelFramelessPlatformWidget() { - Widget* toplevel = new Widget; - Widget::InitParams toplevel_params = - CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); - toplevel_params.native_widget = CreatePlatformNativeWidget(toplevel); - toplevel->Init(toplevel_params); - return toplevel; -} - -Widget* WidgetTest::CreateChildPlatformWidget( - gfx::NativeView parent_native_view) { - Widget* child = new Widget; - Widget::InitParams child_params = - CreateParams(Widget::InitParams::TYPE_CONTROL); - child_params.native_widget = CreatePlatformNativeWidget(child); - child_params.parent = parent_native_view; - child->Init(child_params); - child->SetContentsView(new View); - return child; -} - -Widget* WidgetTest::CreateTopLevelNativeWidget() { - Widget* toplevel = new Widget; - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); - toplevel->Init(params); - return toplevel; -} - -Widget* WidgetTest::CreateChildNativeWidgetWithParent(Widget* parent) { - Widget* child = new Widget; - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_CONTROL); - params.parent = parent->GetNativeView(); - child->Init(params); - child->SetContentsView(new View); - return child; -} - -Widget* WidgetTest::CreateChildNativeWidget() { - return CreateChildNativeWidgetWithParent(NULL); -} - -View* WidgetTest::GetMousePressedHandler(internal::RootView* root_view) { - return root_view->mouse_pressed_handler_; -} - -View* WidgetTest::GetMouseMoveHandler(internal::RootView* root_view) { - return root_view->mouse_move_handler_; -} - -View* WidgetTest::GetGestureHandler(internal::RootView* root_view) { - return root_view->gesture_handler_; -} - -} // namespace test -} // namespace views
diff --git a/ui/views/test/widget_test.h b/ui/views/test/widget_test.h deleted file mode 100644 index dfeca47..0000000 --- a/ui/views/test/widget_test.h +++ /dev/null
@@ -1,108 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_TEST_WIDGET_TEST_H_ -#define UI_VIEWS_TEST_WIDGET_TEST_H_ - -#include "ui/gfx/native_widget_types.h" -#include "ui/views/test/views_test_base.h" - -#if defined(USE_AURA) -#include "ui/views/widget/native_widget_aura.h" -#if !defined(OS_CHROMEOS) -#include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" -#endif -#elif defined(OS_MACOSX) -#include "ui/views/widget/native_widget_mac.h" -#endif - -namespace ui { -class EventProcessor; -} - -namespace views { - -class NativeWidget; -class Widget; - -#if defined(USE_AURA) -typedef NativeWidgetAura PlatformNativeWidget; -#if !defined(OS_CHROMEOS) -typedef DesktopNativeWidgetAura PlatformDesktopNativeWidget; -#endif -#elif defined(OS_MACOSX) -typedef NativeWidgetMac PlatformNativeWidget; -typedef NativeWidgetMac PlatformDesktopNativeWidget; -#endif - -namespace internal { - -class RootView; - -} // namespace internal - -namespace test { - -// A widget that assumes mouse capture always works. It won't on Aura in -// testing, so we mock it. -class NativeWidgetCapture : public PlatformNativeWidget { - public: - explicit NativeWidgetCapture(internal::NativeWidgetDelegate* delegate); - virtual ~NativeWidgetCapture(); - - virtual void SetCapture() override; - virtual void ReleaseCapture() override; - virtual bool HasCapture() const override; - - private: - bool mouse_capture_; - - DISALLOW_COPY_AND_ASSIGN(NativeWidgetCapture); -}; - -class WidgetTest : public ViewsTestBase { - public: - WidgetTest(); - virtual ~WidgetTest(); - - NativeWidget* CreatePlatformNativeWidget( - internal::NativeWidgetDelegate* delegate); - - Widget* CreateTopLevelPlatformWidget(); - - Widget* CreateTopLevelFramelessPlatformWidget(); - - Widget* CreateChildPlatformWidget(gfx::NativeView parent_native_view); - - Widget* CreateTopLevelNativeWidget(); - - Widget* CreateChildNativeWidgetWithParent(Widget* parent); - - Widget* CreateChildNativeWidget(); - - View* GetMousePressedHandler(internal::RootView* root_view); - - View* GetMouseMoveHandler(internal::RootView* root_view); - - View* GetGestureHandler(internal::RootView* root_view); - - // Simulate a OS-level destruction of the native widget held by |widget|. - static void SimulateNativeDestroy(Widget* widget); - - // Return true if |window| is visible according to the native platform. - static bool IsNativeWindowVisible(gfx::NativeWindow window); - - // Return the event processor for |widget|. On aura platforms, this is an - // aura::WindowEventDispatcher. Otherwise, it is a bridge to the OS event - // processor. - static ui::EventProcessor* GetEventProcessor(Widget* widget); - - private: - DISALLOW_COPY_AND_ASSIGN(WidgetTest); -}; - -} // namespace test -} // namespace views - -#endif // UI_VIEWS_TEST_WIDGET_TEST_H_
diff --git a/ui/views/test/widget_test_aura.cc b/ui/views/test/widget_test_aura.cc deleted file mode 100644 index 1b2dd13..0000000 --- a/ui/views/test/widget_test_aura.cc +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/test/widget_test.h" - -#include "ui/aura/window.h" -#include "ui/aura/window_tree_host.h" -#include "ui/views/widget/widget.h" - -namespace views { -namespace test { - -// static -void WidgetTest::SimulateNativeDestroy(Widget* widget) { - delete widget->GetNativeView(); -} - -// static -bool WidgetTest::IsNativeWindowVisible(gfx::NativeWindow window) { - return window->IsVisible(); -} - -// static -ui::EventProcessor* WidgetTest::GetEventProcessor(Widget* widget) { - return widget->GetNativeWindow()->GetHost()->event_processor(); -} - -} // namespace test -} // namespace views
diff --git a/ui/views/test/widget_test_mac.mm b/ui/views/test/widget_test_mac.mm deleted file mode 100644 index 3a3017b..0000000 --- a/ui/views/test/widget_test_mac.mm +++ /dev/null
@@ -1,35 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/test/widget_test.h" - -#include <Cocoa/Cocoa.h> - -#import "base/mac/scoped_nsobject.h" -#include "ui/views/widget/root_view.h" - -namespace views { -namespace test { - -// static -void WidgetTest::SimulateNativeDestroy(Widget* widget) { - // Retain the window while closing it, otherwise the window may lose its last - // owner before -[NSWindow close] completes (this offends AppKit). Usually - // this reference will exist on an event delivered to the runloop. - base::scoped_nsobject<NSWindow> window([widget->GetNativeWindow() retain]); - [window close]; -} - -// static -bool WidgetTest::IsNativeWindowVisible(gfx::NativeWindow window) { - return [window isVisible]; -} - -// static -ui::EventProcessor* WidgetTest::GetEventProcessor(Widget* widget) { - return static_cast<internal::RootView*>(widget->GetRootView()); -} - -} // namespace test -} // namespace views
diff --git a/ui/views/test/x11_property_change_waiter.cc b/ui/views/test/x11_property_change_waiter.cc deleted file mode 100644 index cdfd31d..0000000 --- a/ui/views/test/x11_property_change_waiter.cc +++ /dev/null
@@ -1,84 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/test/x11_property_change_waiter.h" - -#include <X11/Xlib.h> - -#include "base/run_loop.h" -#include "ui/events/platform/platform_event_source.h" -#include "ui/events/platform/scoped_event_dispatcher.h" -#include "ui/gfx/x/x11_atom_cache.h" - -namespace views { - -X11PropertyChangeWaiter::X11PropertyChangeWaiter(XID window, - const char* property) - : x_window_(window), - property_(property), - wait_(true), - old_event_mask_(0) { - Display* display = gfx::GetXDisplay(); - - // Ensure that we are listening to PropertyNotify events for |window|. This - // is not the case for windows which were not created by - // DesktopWindowTreeHostX11. - XWindowAttributes attributes; - XGetWindowAttributes(display, x_window_, &attributes); - old_event_mask_ = attributes.your_event_mask; - XSelectInput(display, x_window_, old_event_mask_ | PropertyChangeMask); - - const char* kAtomsToCache[] = { property, NULL }; - atom_cache_.reset(new ui::X11AtomCache(display, kAtomsToCache)); - - // Override the dispatcher so that we get events before - // DesktopWindowTreeHostX11 does. We must do this because - // DesktopWindowTreeHostX11 stops propagation. - dispatcher_ = ui::PlatformEventSource::GetInstance()-> - OverrideDispatcher(this).Pass(); -} - -X11PropertyChangeWaiter::~X11PropertyChangeWaiter() { - XSelectInput(gfx::GetXDisplay(), x_window_, old_event_mask_); -} - -void X11PropertyChangeWaiter::Wait() { - if (!wait_) - return; - - base::RunLoop run_loop; - quit_closure_ = run_loop.QuitClosure(); - run_loop.Run(); - - dispatcher_.reset(); -} - -bool X11PropertyChangeWaiter::ShouldKeepOnWaiting( - const ui::PlatformEvent& event) { - // Stop waiting once we get a property change. - return true; -} - -bool X11PropertyChangeWaiter::CanDispatchEvent(const ui::PlatformEvent& event) { - NOTREACHED(); - return true; -} - -uint32_t X11PropertyChangeWaiter::DispatchEvent( - const ui::PlatformEvent& event) { - if (!wait_ || - event->type != PropertyNotify || - event->xproperty.window != x_window_ || - event->xproperty.atom != atom_cache_->GetAtom(property_) || - ShouldKeepOnWaiting(event)) { - return ui::POST_DISPATCH_PERFORM_DEFAULT; - } - - wait_ = false; - if (!quit_closure_.is_null()) - quit_closure_.Run(); - return ui::POST_DISPATCH_PERFORM_DEFAULT; -} - -} // namespace views
diff --git a/ui/views/test/x11_property_change_waiter.h b/ui/views/test/x11_property_change_waiter.h deleted file mode 100644 index af4ef71..0000000 --- a/ui/views/test/x11_property_change_waiter.h +++ /dev/null
@@ -1,64 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_TEST_X11_PROPERTY_CHANGE_WAITER_H_ -#define UI_VIEWS_TEST_X11_PROPERTY_CHANGE_WAITER_H_ - -#include "base/callback.h" -#include "base/memory/scoped_ptr.h" -#include "ui/events/platform/platform_event_dispatcher.h" -#include "ui/events/platform/platform_event_types.h" -#include "ui/gfx/x/x11_types.h" - -namespace ui { -class ScopedEventDispatcher; -class X11AtomCache; -} - -namespace views { - -// Blocks till the value of |property| on |window| changes. -class X11PropertyChangeWaiter : public ui::PlatformEventDispatcher { - public: - X11PropertyChangeWaiter(XID window, const char* property); - virtual ~X11PropertyChangeWaiter(); - - // Blocks till the value of |property_| changes. - virtual void Wait(); - - protected: - // Returns whether the run loop can exit. - virtual bool ShouldKeepOnWaiting(const ui::PlatformEvent& event); - - XID xwindow() const { - return x_window_; - } - - private: - // ui::PlatformEventDispatcher: - virtual bool CanDispatchEvent(const ui::PlatformEvent& event) override; - virtual uint32_t DispatchEvent(const ui::PlatformEvent& event) override; - - XID x_window_; - const char* property_; - - // Whether Wait() should block. - bool wait_; - - // Ends the run loop. - base::Closure quit_closure_; - - // The event mask to be restored upon X11PropertyChangeWaiter's destruction. - long old_event_mask_; - - scoped_ptr<ui::ScopedEventDispatcher> dispatcher_; - - scoped_ptr<ui::X11AtomCache> atom_cache_; - - DISALLOW_COPY_AND_ASSIGN(X11PropertyChangeWaiter); -}; - -} // namespace views - -#endif // UI_VIEWS_TEST_X11_PROPERTY_CHANGE_WAITER_H_
diff --git a/ui/views/touchui/OWNERS b/ui/views/touchui/OWNERS deleted file mode 100644 index b8e32c1..0000000 --- a/ui/views/touchui/OWNERS +++ /dev/null
@@ -1 +0,0 @@ -sadrul@chromium.org
diff --git a/ui/views/touchui/touch_editing_menu.cc b/ui/views/touchui/touch_editing_menu.cc deleted file mode 100644 index 771bfb3..0000000 --- a/ui/views/touchui/touch_editing_menu.cc +++ /dev/null
@@ -1,163 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/touchui/touch_editing_menu.h" - -#include "base/strings/utf_string_conversions.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/font_list.h" -#include "ui/gfx/insets.h" -#include "ui/gfx/text_utils.h" -#include "ui/strings/grit/ui_strings.h" -#include "ui/views/bubble/bubble_border.h" -#include "ui/views/bubble/bubble_frame_view.h" -#include "ui/views/controls/button/custom_button.h" -#include "ui/views/controls/button/label_button.h" -#include "ui/views/controls/button/label_button_border.h" -#include "ui/views/layout/box_layout.h" -#include "ui/views/widget/widget.h" - -namespace { - -const int kMenuCommands[] = {IDS_APP_CUT, - IDS_APP_COPY, - IDS_APP_PASTE}; -const int kSpacingBetweenButtons = 2; -const int kButtonSeparatorColor = SkColorSetARGB(13, 0, 0, 0); -const int kMenuButtonHeight = 38; -const int kMenuButtonWidth = 63; -const int kMenuMargin = 1; - -const char* kEllipsesButtonText = "..."; -const int kEllipsesButtonTag = -1; -} // namespace - -namespace views { - -TouchEditingMenuView::TouchEditingMenuView( - TouchEditingMenuController* controller, - const gfx::Rect& anchor_rect, - const gfx::Size& handle_image_size, - gfx::NativeView context) - : BubbleDelegateView(NULL, views::BubbleBorder::BOTTOM_CENTER), - controller_(controller) { - set_shadow(views::BubbleBorder::SMALL_SHADOW); - set_parent_window(context); - set_margins(gfx::Insets(kMenuMargin, kMenuMargin, kMenuMargin, kMenuMargin)); - set_can_activate(false); - set_adjust_if_offscreen(true); - - SetLayoutManager(new BoxLayout(BoxLayout::kHorizontal, 0, 0, - kSpacingBetweenButtons)); - CreateButtons(); - - // After buttons are created, check if there is enough room between handles to - // show the menu and adjust anchor rect properly if needed, just in case the - // menu is needed to be shown under the selection. - gfx::Rect adjusted_anchor_rect(anchor_rect); - int menu_width = GetPreferredSize().width(); - if (menu_width > anchor_rect.width() - handle_image_size.width()) - adjusted_anchor_rect.Inset(0, 0, 0, -handle_image_size.height()); - SetAnchorRect(adjusted_anchor_rect); - - views::BubbleDelegateView::CreateBubble(this); - GetWidget()->Show(); -} - -TouchEditingMenuView::~TouchEditingMenuView() { -} - -// static -TouchEditingMenuView* TouchEditingMenuView::Create( - TouchEditingMenuController* controller, - const gfx::Rect& anchor_rect, - const gfx::Size& handle_image_size, - gfx::NativeView context) { - if (controller) { - for (size_t i = 0; i < arraysize(kMenuCommands); i++) { - if (controller->IsCommandIdEnabled(kMenuCommands[i])) { - return new TouchEditingMenuView(controller, anchor_rect, - handle_image_size, context); - } - } - } - return NULL; -} - -void TouchEditingMenuView::Close() { - if (GetWidget()) { - controller_ = NULL; - GetWidget()->Close(); - } -} - -void TouchEditingMenuView::WindowClosing() { - views::BubbleDelegateView::WindowClosing(); - if (controller_) - controller_->OnMenuClosed(this); -} - -void TouchEditingMenuView::ButtonPressed(Button* sender, - const ui::Event& event) { - if (controller_) { - if (sender->tag() != kEllipsesButtonTag) - controller_->ExecuteCommand(sender->tag(), event.flags()); - else - controller_->OpenContextMenu(); - } -} - -void TouchEditingMenuView::OnPaint(gfx::Canvas* canvas) { - BubbleDelegateView::OnPaint(canvas); - - // Draw separator bars. - for (int i = 0; i < child_count() - 1; ++i) { - View* child = child_at(i); - int x = child->bounds().right() + kSpacingBetweenButtons / 2; - canvas->FillRect(gfx::Rect(x, 0, 1, child->height()), - kButtonSeparatorColor); - } -} - -void TouchEditingMenuView::CreateButtons() { - RemoveAllChildViews(true); - for (size_t i = 0; i < arraysize(kMenuCommands); i++) { - int command_id = kMenuCommands[i]; - if (controller_ && controller_->IsCommandIdEnabled(command_id)) { - Button* button = CreateButton(l10n_util::GetStringUTF16(command_id), - command_id); - AddChildView(button); - } - } - - // Finally, add ellipses button. - AddChildView(CreateButton( - base::UTF8ToUTF16(kEllipsesButtonText), kEllipsesButtonTag)); - Layout(); -} - -Button* TouchEditingMenuView::CreateButton(const base::string16& title, - int tag) { - base::string16 label = gfx::RemoveAcceleratorChar(title, '&', NULL, NULL); - LabelButton* button = new LabelButton(this, label); - button->SetFocusable(true); - button->set_request_focus_on_press(false); - const gfx::FontList& font_list = - ui::ResourceBundle::GetSharedInstance().GetFontList( - ui::ResourceBundle::SmallFont); - scoped_ptr<LabelButtonBorder> button_border( - new LabelButtonBorder(button->style())); - int v_border = (kMenuButtonHeight - font_list.GetHeight()) / 2; - int h_border = (kMenuButtonWidth - gfx::GetStringWidth(label, font_list)) / 2; - button_border->set_insets( - gfx::Insets(v_border, h_border, v_border, h_border)); - button->SetBorder(button_border.Pass()); - button->SetFontList(font_list); - button->set_tag(tag); - return button; -} - -} // namespace views
diff --git a/ui/views/touchui/touch_editing_menu.h b/ui/views/touchui/touch_editing_menu.h deleted file mode 100644 index 0dfff49..0000000 --- a/ui/views/touchui/touch_editing_menu.h +++ /dev/null
@@ -1,83 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_TOUCHUI_TOUCH_EDITING_MENU_H_ -#define UI_VIEWS_TOUCHUI_TOUCH_EDITING_MENU_H_ - -#include "ui/gfx/point.h" -#include "ui/views/bubble/bubble_delegate.h" -#include "ui/views/controls/button/button.h" -#include "ui/views/views_export.h" - -namespace gfx { -class Canvas; -} - -namespace views { -class TouchEditingMenuView; -class Widget; - -class VIEWS_EXPORT TouchEditingMenuController { - public: - // Checks if the specified menu command is supported. - virtual bool IsCommandIdEnabled(int command_id) const = 0; - - // Send a context menu command to the controller. - virtual void ExecuteCommand(int command_id, int event_flags) = 0; - - // Tell the controller that user has selected the context menu button. - virtual void OpenContextMenu() = 0; - - // Called when the menu is closed. - virtual void OnMenuClosed(TouchEditingMenuView* menu) = 0; - - protected: - virtual ~TouchEditingMenuController() {} -}; - -// A View that displays the touch context menu. -class VIEWS_EXPORT TouchEditingMenuView : public BubbleDelegateView, - public ButtonListener { - public: - virtual ~TouchEditingMenuView(); - - // If there are no actions available for the menu, returns NULL. Otherwise, - // returns a new instance of TouchEditingMenuView. - static TouchEditingMenuView* Create(TouchEditingMenuController* controller, - const gfx::Rect& anchor_rect, - const gfx::Size& handle_image_size, - gfx::NativeView context); - - void Close(); - - private: - TouchEditingMenuView(TouchEditingMenuController* controller, - const gfx::Rect& anchor_rect, - const gfx::Size& handle_image_size, - gfx::NativeView context); - - // views::WidgetDelegate overrides: - virtual void WindowClosing() override; - - // Overridden from ButtonListener. - virtual void ButtonPressed(Button* sender, const ui::Event& event) override; - - // Overridden from BubbleDelegateView. - virtual void OnPaint(gfx::Canvas* canvas) override; - - // Queries the |controller_| for what elements to show in the menu and sizes - // the menu appropriately. - void CreateButtons(); - - // Helper method to create a single button. - Button* CreateButton(const base::string16& title, int tag); - - TouchEditingMenuController* controller_; - - DISALLOW_COPY_AND_ASSIGN(TouchEditingMenuView); -}; - -} // namespace views - -#endif // UI_VIEWS_TOUCHUI_TOUCH_SELECTION_CONTROLLER_IMPL_H_
diff --git a/ui/views/touchui/touch_selection_controller_impl.cc b/ui/views/touchui/touch_selection_controller_impl.cc deleted file mode 100644 index 36b73d1..0000000 --- a/ui/views/touchui/touch_selection_controller_impl.cc +++ /dev/null
@@ -1,634 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/touchui/touch_selection_controller_impl.h" - -#include "base/time/time.h" -#include "ui/aura/client/cursor_client.h" -#include "ui/aura/env.h" -#include "ui/aura/window.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/image/image.h" -#include "ui/gfx/path.h" -#include "ui/gfx/rect.h" -#include "ui/gfx/screen.h" -#include "ui/gfx/size.h" -#include "ui/resources/grit/ui_resources.h" -#include "ui/strings/grit/ui_strings.h" -#include "ui/views/widget/widget.h" -#include "ui/wm/core/masked_window_targeter.h" -#include "ui/wm/core/window_animations.h" - -namespace { - -// Constants defining the visual attributes of selection handles -const int kSelectionHandleLineWidth = 1; -const SkColor kSelectionHandleLineColor = - SkColorSetRGB(0x42, 0x81, 0xf4); - -// When a handle is dragged, the drag position reported to the client view is -// offset vertically to represent the cursor position. This constant specifies -// the offset in pixels above the "O" (see pic below). This is required because -// say if this is zero, that means the drag position we report is the point -// right above the "O" or the bottom most point of the cursor "|". In that case, -// a vertical movement of even one pixel will make the handle jump to the line -// below it. So when the user just starts dragging, the handle will jump to the -// next line if the user makes any vertical movement. It is correct but -// looks/feels weird. So we have this non-zero offset to prevent this jumping. -// -// Editing handle widget showing the difference between the position of the -// ET_GESTURE_SCROLL_UPDATE event and the drag position reported to the client: -// _____ -// | |<-|---- Drag position reported to client -// _ | O | -// Vertical Padding __| | <-|---- ET_GESTURE_SCROLL_UPDATE position -// |_ |_____|<--- Editing handle widget -// -// | | -// T -// Horizontal Padding -// -const int kSelectionHandleVerticalDragOffset = 5; - -// Padding around the selection handle defining the area that will be included -// in the touch target to make dragging the handle easier (see pic above). -const int kSelectionHandleHorizPadding = 10; -const int kSelectionHandleVertPadding = 20; - -const int kContextMenuTimoutMs = 200; - -const int kSelectionHandleQuickFadeDurationMs = 50; - -// Minimum height for selection handle bar. If the bar height is going to be -// less than this value, handle will not be shown. -const int kSelectionHandleBarMinHeight = 5; -// Maximum amount that selection handle bar can stick out of client view's -// boundaries. -const int kSelectionHandleBarBottomAllowance = 3; - -// Creates a widget to host SelectionHandleView. -views::Widget* CreateTouchSelectionPopupWidget( - gfx::NativeView context, - views::WidgetDelegate* widget_delegate) { - views::Widget* widget = new views::Widget; - views::Widget::InitParams params(views::Widget::InitParams::TYPE_POPUP); - params.opacity = views::Widget::InitParams::TRANSLUCENT_WINDOW; - params.shadow_type = views::Widget::InitParams::SHADOW_TYPE_NONE; - params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.parent = context; - params.delegate = widget_delegate; - widget->Init(params); - return widget; -} - -gfx::Image* GetHandleImage() { - static gfx::Image* handle_image = NULL; - if (!handle_image) { - handle_image = &ui::ResourceBundle::GetSharedInstance().GetImageNamed( - IDR_TEXT_SELECTION_HANDLE); - } - return handle_image; -} - -gfx::Size GetHandleImageSize() { - return GetHandleImage()->Size(); -} - -// Cannot use gfx::UnionRect since it does not work for empty rects. -gfx::Rect Union(const gfx::Rect& r1, const gfx::Rect& r2) { - int rx = std::min(r1.x(), r2.x()); - int ry = std::min(r1.y(), r2.y()); - int rr = std::max(r1.right(), r2.right()); - int rb = std::max(r1.bottom(), r2.bottom()); - - return gfx::Rect(rx, ry, rr - rx, rb - ry); -} - -// Convenience methods to convert a |rect| from screen to the |client|'s -// coordinate system and vice versa. -// Note that this is not quite correct because it does not take into account -// transforms such as rotation and scaling. This should be in TouchEditable. -// TODO(varunjain): Fix this. -gfx::Rect ConvertFromScreen(ui::TouchEditable* client, const gfx::Rect& rect) { - gfx::Point origin = rect.origin(); - client->ConvertPointFromScreen(&origin); - return gfx::Rect(origin, rect.size()); -} -gfx::Rect ConvertToScreen(ui::TouchEditable* client, const gfx::Rect& rect) { - gfx::Point origin = rect.origin(); - client->ConvertPointToScreen(&origin); - return gfx::Rect(origin, rect.size()); -} - -} // namespace - -namespace views { - -typedef TouchSelectionControllerImpl::EditingHandleView EditingHandleView; - -class TouchHandleWindowTargeter : public wm::MaskedWindowTargeter { - public: - TouchHandleWindowTargeter(aura::Window* window, - EditingHandleView* handle_view); - - virtual ~TouchHandleWindowTargeter() {} - - private: - // wm::MaskedWindowTargeter: - virtual bool GetHitTestMask(aura::Window* window, - gfx::Path* mask) const override; - - EditingHandleView* handle_view_; - - DISALLOW_COPY_AND_ASSIGN(TouchHandleWindowTargeter); -}; - -// A View that displays the text selection handle. -class TouchSelectionControllerImpl::EditingHandleView - : public views::WidgetDelegateView { - public: - EditingHandleView(TouchSelectionControllerImpl* controller, - gfx::NativeView context) - : controller_(controller), - drag_offset_(0), - draw_invisible_(false) { - widget_.reset(CreateTouchSelectionPopupWidget(context, this)); - widget_->SetContentsView(this); - - aura::Window* window = widget_->GetNativeWindow(); - window->SetEventTargeter(scoped_ptr<ui::EventTargeter>( - new TouchHandleWindowTargeter(window, this))); - - // We are owned by the TouchSelectionController. - set_owned_by_client(); - } - - virtual ~EditingHandleView() { - SetWidgetVisible(false, false); - } - - // Overridden from views::WidgetDelegateView: - virtual bool WidgetHasHitTestMask() const override { - return true; - } - - virtual void GetWidgetHitTestMask(gfx::Path* mask) const override { - gfx::Size image_size = GetHandleImageSize(); - mask->addRect(SkIntToScalar(0), SkIntToScalar(selection_rect_.height()), - SkIntToScalar(image_size.width()) + 2 * kSelectionHandleHorizPadding, - SkIntToScalar(selection_rect_.height() + image_size.height() + - kSelectionHandleVertPadding)); - } - - virtual void DeleteDelegate() override { - // We are owned and deleted by TouchSelectionController. - } - - // Overridden from views::View: - virtual void OnPaint(gfx::Canvas* canvas) override { - if (draw_invisible_) - return; - gfx::Size image_size = GetHandleImageSize(); - int cursor_pos_x = image_size.width() / 2 - kSelectionHandleLineWidth + - kSelectionHandleHorizPadding; - - // Draw the cursor line. - canvas->FillRect( - gfx::Rect(cursor_pos_x, 0, - 2 * kSelectionHandleLineWidth + 1, selection_rect_.height()), - kSelectionHandleLineColor); - - // Draw the handle image. - canvas->DrawImageInt(*GetHandleImage()->ToImageSkia(), - kSelectionHandleHorizPadding, selection_rect_.height()); - } - - virtual void OnGestureEvent(ui::GestureEvent* event) override { - event->SetHandled(); - switch (event->type()) { - case ui::ET_GESTURE_SCROLL_BEGIN: - widget_->SetCapture(this); - controller_->SetDraggingHandle(this); - drag_offset_ = event->y() - selection_rect_.height() + - kSelectionHandleVerticalDragOffset; - break; - case ui::ET_GESTURE_SCROLL_UPDATE: { - gfx::Point drag_pos(event->location().x(), - event->location().y() - drag_offset_); - controller_->SelectionHandleDragged(drag_pos); - break; - } - case ui::ET_GESTURE_SCROLL_END: - case ui::ET_SCROLL_FLING_START: - widget_->ReleaseCapture(); - controller_->SetDraggingHandle(NULL); - break; - default: - break; - } - } - - virtual gfx::Size GetPreferredSize() const override { - gfx::Size image_size = GetHandleImageSize(); - return gfx::Size(image_size.width() + 2 * kSelectionHandleHorizPadding, - image_size.height() + selection_rect_.height() + - kSelectionHandleVertPadding); - } - - bool IsWidgetVisible() const { - return widget_->IsVisible(); - } - - void SetWidgetVisible(bool visible, bool quick) { - if (widget_->IsVisible() == visible) - return; - wm::SetWindowVisibilityAnimationDuration( - widget_->GetNativeView(), - base::TimeDelta::FromMilliseconds( - quick ? kSelectionHandleQuickFadeDurationMs : 0)); - if (visible) - widget_->Show(); - else - widget_->Hide(); - } - - void SetSelectionRectInScreen(const gfx::Rect& rect) { - gfx::Size image_size = GetHandleImageSize(); - selection_rect_ = rect; - gfx::Rect widget_bounds( - rect.x() - image_size.width() / 2 - kSelectionHandleHorizPadding, - rect.y(), - image_size.width() + 2 * kSelectionHandleHorizPadding, - rect.height() + image_size.height() + kSelectionHandleVertPadding); - widget_->SetBounds(widget_bounds); - } - - gfx::Point GetScreenPosition() { - return widget_->GetClientAreaBoundsInScreen().origin(); - } - - void SetDrawInvisible(bool draw_invisible) { - if (draw_invisible_ == draw_invisible) - return; - draw_invisible_ = draw_invisible; - SchedulePaint(); - } - - const gfx::Rect& selection_rect() const { return selection_rect_; } - - private: - scoped_ptr<Widget> widget_; - TouchSelectionControllerImpl* controller_; - gfx::Rect selection_rect_; - - // Vertical offset between the scroll event position and the drag position - // reported to the client view (see the ASCII figure at the top of the file - // and its description for more details). - int drag_offset_; - - // If set to true, the handle will not draw anything, hence providing an empty - // widget. We need this because we may want to stop showing the handle while - // it is being dragged. Since it is being dragged, we cannot destroy the - // handle. - bool draw_invisible_; - - DISALLOW_COPY_AND_ASSIGN(EditingHandleView); -}; - -TouchHandleWindowTargeter::TouchHandleWindowTargeter( - aura::Window* window, - EditingHandleView* handle_view) - : wm::MaskedWindowTargeter(window), - handle_view_(handle_view) { -} - -bool TouchHandleWindowTargeter::GetHitTestMask(aura::Window* window, - gfx::Path* mask) const { - const gfx::Rect& selection_rect = handle_view_->selection_rect(); - gfx::Size image_size = GetHandleImageSize(); - mask->addRect(SkIntToScalar(0), SkIntToScalar(selection_rect.height()), - SkIntToScalar(image_size.width()) + 2 * kSelectionHandleHorizPadding, - SkIntToScalar(selection_rect.height() + image_size.height() + - kSelectionHandleVertPadding)); - return true; -} - -TouchSelectionControllerImpl::TouchSelectionControllerImpl( - ui::TouchEditable* client_view) - : client_view_(client_view), - client_widget_(NULL), - selection_handle_1_(new EditingHandleView(this, - client_view->GetNativeView())), - selection_handle_2_(new EditingHandleView(this, - client_view->GetNativeView())), - cursor_handle_(new EditingHandleView(this, - client_view->GetNativeView())), - context_menu_(NULL), - dragging_handle_(NULL) { - aura::Window* client_window = client_view_->GetNativeView(); - client_window->AddObserver(this); - client_widget_ = Widget::GetTopLevelWidgetForNativeView(client_window); - if (client_widget_) - client_widget_->AddObserver(this); - aura::Env::GetInstance()->AddPreTargetHandler(this); -} - -TouchSelectionControllerImpl::~TouchSelectionControllerImpl() { - HideContextMenu(); - aura::Env::GetInstance()->RemovePreTargetHandler(this); - if (client_widget_) - client_widget_->RemoveObserver(this); - client_view_->GetNativeView()->RemoveObserver(this); -} - -void TouchSelectionControllerImpl::SelectionChanged() { - gfx::Rect r1, r2; - client_view_->GetSelectionEndPoints(&r1, &r2); - gfx::Rect screen_rect_1 = ConvertToScreen(client_view_, r1); - gfx::Rect screen_rect_2 = ConvertToScreen(client_view_, r2); - gfx::Rect client_bounds = client_view_->GetBounds(); - if (r1.y() < client_bounds.y()) - r1.Inset(0, client_bounds.y() - r1.y(), 0, 0); - if (r2.y() < client_bounds.y()) - r2.Inset(0, client_bounds.y() - r2.y(), 0, 0); - gfx::Rect screen_rect_1_clipped = ConvertToScreen(client_view_, r1); - gfx::Rect screen_rect_2_clipped = ConvertToScreen(client_view_, r2); - if (screen_rect_1_clipped == selection_end_point_1_clipped_ && - screen_rect_2_clipped == selection_end_point_2_clipped_) - return; - - selection_end_point_1_ = screen_rect_1; - selection_end_point_2_ = screen_rect_2; - selection_end_point_1_clipped_ = screen_rect_1_clipped; - selection_end_point_2_clipped_ = screen_rect_2_clipped; - - if (client_view_->DrawsHandles()) { - UpdateContextMenu(); - return; - } - if (dragging_handle_) { - // We need to reposition only the selection handle that is being dragged. - // The other handle stays the same. Also, the selection handle being dragged - // will always be at the end of selection, while the other handle will be at - // the start. - // If the new location of this handle is out of client view, its widget - // should not get hidden, since it should still receive touch events. - // Hence, we are not using |SetHandleSelectionRect()| method here. - dragging_handle_->SetSelectionRectInScreen(screen_rect_2_clipped); - - // Temporary fix for selection handle going outside a window. On a webpage, - // the page should scroll if the selection handle is dragged outside the - // window. That does not happen currently. So we just hide the handle for - // now. - // TODO(varunjain): Fix this: crbug.com/269003 - dragging_handle_->SetDrawInvisible(!ShouldShowHandleFor(r2)); - - if (dragging_handle_ != cursor_handle_.get()) { - // The non-dragging-handle might have recently become visible. - EditingHandleView* non_dragging_handle = selection_handle_1_.get(); - if (dragging_handle_ == selection_handle_1_) { - non_dragging_handle = selection_handle_2_.get(); - // if handle 1 is being dragged, it is corresponding to the end of - // selection and the other handle to the start of selection. - selection_end_point_1_ = screen_rect_2; - selection_end_point_2_ = screen_rect_1; - selection_end_point_1_clipped_ = screen_rect_2_clipped; - selection_end_point_2_clipped_ = screen_rect_1_clipped; - } - SetHandleSelectionRect(non_dragging_handle, r1, screen_rect_1_clipped); - } - } else { - UpdateContextMenu(); - - // Check if there is any selection at all. - if (screen_rect_1.origin() == screen_rect_2.origin()) { - selection_handle_1_->SetWidgetVisible(false, false); - selection_handle_2_->SetWidgetVisible(false, false); - SetHandleSelectionRect(cursor_handle_.get(), r1, screen_rect_1_clipped); - return; - } - - cursor_handle_->SetWidgetVisible(false, false); - SetHandleSelectionRect(selection_handle_1_.get(), r1, - screen_rect_1_clipped); - SetHandleSelectionRect(selection_handle_2_.get(), r2, - screen_rect_2_clipped); - } -} - -bool TouchSelectionControllerImpl::IsHandleDragInProgress() { - return !!dragging_handle_; -} - -void TouchSelectionControllerImpl::HideHandles(bool quick) { - selection_handle_1_->SetWidgetVisible(false, quick); - selection_handle_2_->SetWidgetVisible(false, quick); - cursor_handle_->SetWidgetVisible(false, quick); -} - -void TouchSelectionControllerImpl::SetDraggingHandle( - EditingHandleView* handle) { - dragging_handle_ = handle; - if (dragging_handle_) - HideContextMenu(); - else - StartContextMenuTimer(); -} - -void TouchSelectionControllerImpl::SelectionHandleDragged( - const gfx::Point& drag_pos) { - DCHECK(dragging_handle_); - gfx::Point drag_pos_in_client = drag_pos; - ConvertPointToClientView(dragging_handle_, &drag_pos_in_client); - - if (dragging_handle_ == cursor_handle_.get()) { - client_view_->MoveCaretTo(drag_pos_in_client); - return; - } - - // Find the stationary selection handle. - gfx::Rect fixed_handle_rect = selection_end_point_1_; - if (selection_handle_1_ == dragging_handle_) - fixed_handle_rect = selection_end_point_2_; - - // Find selection end points in client_view's coordinate system. - gfx::Point p2 = fixed_handle_rect.origin(); - p2.Offset(0, fixed_handle_rect.height() / 2); - client_view_->ConvertPointFromScreen(&p2); - - // Instruct client_view to select the region between p1 and p2. The position - // of |fixed_handle| is the start and that of |dragging_handle| is the end - // of selection. - client_view_->SelectRect(p2, drag_pos_in_client); -} - -void TouchSelectionControllerImpl::ConvertPointToClientView( - EditingHandleView* source, gfx::Point* point) { - View::ConvertPointToScreen(source, point); - client_view_->ConvertPointFromScreen(point); -} - -void TouchSelectionControllerImpl::SetHandleSelectionRect( - EditingHandleView* handle, - const gfx::Rect& rect, - const gfx::Rect& rect_in_screen) { - handle->SetWidgetVisible(ShouldShowHandleFor(rect), false); - if (handle->IsWidgetVisible()) - handle->SetSelectionRectInScreen(rect_in_screen); -} - -bool TouchSelectionControllerImpl::ShouldShowHandleFor( - const gfx::Rect& rect) const { - if (rect.height() < kSelectionHandleBarMinHeight) - return false; - gfx::Rect bounds = client_view_->GetBounds(); - bounds.Inset(0, 0, 0, -kSelectionHandleBarBottomAllowance); - return bounds.Contains(rect); -} - -bool TouchSelectionControllerImpl::IsCommandIdEnabled(int command_id) const { - return client_view_->IsCommandIdEnabled(command_id); -} - -void TouchSelectionControllerImpl::ExecuteCommand(int command_id, - int event_flags) { - HideContextMenu(); - client_view_->ExecuteCommand(command_id, event_flags); -} - -void TouchSelectionControllerImpl::OpenContextMenu() { - // Context menu should appear centered on top of the selected region. - const gfx::Rect rect = context_menu_->GetAnchorRect(); - const gfx::Point anchor(rect.CenterPoint().x(), rect.y()); - HideContextMenu(); - client_view_->OpenContextMenu(anchor); -} - -void TouchSelectionControllerImpl::OnMenuClosed(TouchEditingMenuView* menu) { - if (menu == context_menu_) - context_menu_ = NULL; -} - -void TouchSelectionControllerImpl::OnAncestorWindowTransformed( - aura::Window* window, - aura::Window* ancestor) { - client_view_->DestroyTouchSelection(); -} - -void TouchSelectionControllerImpl::OnWidgetClosing(Widget* widget) { - DCHECK_EQ(client_widget_, widget); - client_widget_ = NULL; -} - -void TouchSelectionControllerImpl::OnWidgetBoundsChanged( - Widget* widget, - const gfx::Rect& new_bounds) { - DCHECK_EQ(client_widget_, widget); - SelectionChanged(); -} - -void TouchSelectionControllerImpl::OnKeyEvent(ui::KeyEvent* event) { - client_view_->DestroyTouchSelection(); -} - -void TouchSelectionControllerImpl::OnMouseEvent(ui::MouseEvent* event) { - aura::client::CursorClient* cursor_client = aura::client::GetCursorClient( - client_view_->GetNativeView()->GetRootWindow()); - if (!cursor_client || cursor_client->IsMouseEventsEnabled()) - client_view_->DestroyTouchSelection(); -} - -void TouchSelectionControllerImpl::OnScrollEvent(ui::ScrollEvent* event) { - client_view_->DestroyTouchSelection(); -} - -void TouchSelectionControllerImpl::ContextMenuTimerFired() { - // Get selection end points in client_view's space. - gfx::Rect end_rect_1_in_screen; - gfx::Rect end_rect_2_in_screen; - if (cursor_handle_->IsWidgetVisible()) { - end_rect_1_in_screen = selection_end_point_1_clipped_; - end_rect_2_in_screen = end_rect_1_in_screen; - } else { - end_rect_1_in_screen = selection_end_point_1_clipped_; - end_rect_2_in_screen = selection_end_point_2_clipped_; - } - - // Convert from screen to client. - gfx::Rect end_rect_1(ConvertFromScreen(client_view_, end_rect_1_in_screen)); - gfx::Rect end_rect_2(ConvertFromScreen(client_view_, end_rect_2_in_screen)); - - // if selection is completely inside the view, we display the context menu - // in the middle of the end points on the top. Else, we show it above the - // visible handle. If no handle is visible, we do not show the menu. - gfx::Rect menu_anchor; - if (ShouldShowHandleFor(end_rect_1) && - ShouldShowHandleFor(end_rect_2)) - menu_anchor = Union(end_rect_1_in_screen,end_rect_2_in_screen); - else if (ShouldShowHandleFor(end_rect_1)) - menu_anchor = end_rect_1_in_screen; - else if (ShouldShowHandleFor(end_rect_2)) - menu_anchor = end_rect_2_in_screen; - else - return; - - DCHECK(!context_menu_); - context_menu_ = TouchEditingMenuView::Create(this, menu_anchor, - GetHandleImageSize(), - client_view_->GetNativeView()); -} - -void TouchSelectionControllerImpl::StartContextMenuTimer() { - if (context_menu_timer_.IsRunning()) - return; - context_menu_timer_.Start( - FROM_HERE, - base::TimeDelta::FromMilliseconds(kContextMenuTimoutMs), - this, - &TouchSelectionControllerImpl::ContextMenuTimerFired); -} - -void TouchSelectionControllerImpl::UpdateContextMenu() { - // Hide context menu to be shown when the timer fires. - HideContextMenu(); - StartContextMenuTimer(); -} - -void TouchSelectionControllerImpl::HideContextMenu() { - if (context_menu_) - context_menu_->Close(); - context_menu_ = NULL; - context_menu_timer_.Stop(); -} - -gfx::NativeView TouchSelectionControllerImpl::GetCursorHandleNativeView() { - return cursor_handle_->GetWidget()->GetNativeView(); -} - -gfx::Point TouchSelectionControllerImpl::GetSelectionHandle1Position() { - return selection_handle_1_->GetScreenPosition(); -} - -gfx::Point TouchSelectionControllerImpl::GetSelectionHandle2Position() { - return selection_handle_2_->GetScreenPosition(); -} - -gfx::Point TouchSelectionControllerImpl::GetCursorHandlePosition() { - return cursor_handle_->GetScreenPosition(); -} - -bool TouchSelectionControllerImpl::IsSelectionHandle1Visible() { - return selection_handle_1_->IsWidgetVisible(); -} - -bool TouchSelectionControllerImpl::IsSelectionHandle2Visible() { - return selection_handle_2_->IsWidgetVisible(); -} - -bool TouchSelectionControllerImpl::IsCursorHandleVisible() { - return cursor_handle_->IsWidgetVisible(); -} - -} // namespace views
diff --git a/ui/views/touchui/touch_selection_controller_impl.h b/ui/views/touchui/touch_selection_controller_impl.h deleted file mode 100644 index 158666c..0000000 --- a/ui/views/touchui/touch_selection_controller_impl.h +++ /dev/null
@@ -1,140 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_UI_VIEWS_TOUCHUI_TOUCH_SELECTION_CONTROLLER_IMPL_H_ -#define UI_UI_VIEWS_TOUCHUI_TOUCH_SELECTION_CONTROLLER_IMPL_H_ - -#include "base/timer/timer.h" -#include "ui/aura/window_observer.h" -#include "ui/base/touch/touch_editing_controller.h" -#include "ui/gfx/point.h" -#include "ui/views/touchui/touch_editing_menu.h" -#include "ui/views/view.h" -#include "ui/views/views_export.h" - -namespace views { - -namespace test { -class WidgetTestInteractive; -} - -// Touch specific implementation of TouchSelectionController. Responsible for -// displaying selection handles and menu elements relevant in a touch interface. -class VIEWS_EXPORT TouchSelectionControllerImpl - : public ui::TouchSelectionController, - public TouchEditingMenuController, - public aura::WindowObserver, - public WidgetObserver, - public ui::EventHandler { - public: - class EditingHandleView; - - // Use TextSelectionController::create(). - explicit TouchSelectionControllerImpl( - ui::TouchEditable* client_view); - - virtual ~TouchSelectionControllerImpl(); - - // TextSelectionController. - virtual void SelectionChanged() override; - virtual bool IsHandleDragInProgress() override; - virtual void HideHandles(bool quick) override; - - private: - friend class TouchSelectionControllerImplTest; - friend class test::WidgetTestInteractive; - - void SetDraggingHandle(EditingHandleView* handle); - - // Callback to inform the client view that the selection handle has been - // dragged, hence selection may need to be updated. - void SelectionHandleDragged(const gfx::Point& drag_pos); - - // Convenience method to convert a point from a selection handle's coordinate - // system to that of the client view. - void ConvertPointToClientView(EditingHandleView* source, gfx::Point* point); - - // Convenience method to set a handle's selection rect and hide it if it is - // located out of client view. - void SetHandleSelectionRect(EditingHandleView* handle, const gfx::Rect& rect, - const gfx::Rect& rect_in_screen); - - // Checks if handle should be shown for a selection end-point at |rect|. - // |rect| should be the clipped version of the selection end-point. - bool ShouldShowHandleFor(const gfx::Rect& rect) const; - - // Overridden from TouchEditingMenuController. - virtual bool IsCommandIdEnabled(int command_id) const override; - virtual void ExecuteCommand(int command_id, int event_flags) override; - virtual void OpenContextMenu() override; - virtual void OnMenuClosed(TouchEditingMenuView* menu) override; - - // Overriden from aura::WindowObserver. - virtual void OnAncestorWindowTransformed(aura::Window* source, - aura::Window* window) override; - - // Overridden from WidgetObserver. We will observe the widget backing the - // |client_view_| so that when its moved/resized, we can update the selection - // handles appropriately. - virtual void OnWidgetClosing(Widget* widget) override; - virtual void OnWidgetBoundsChanged(Widget* widget, - const gfx::Rect& new_bounds) override; - - // Overriden from ui::EventHandler. - virtual void OnKeyEvent(ui::KeyEvent* event) override; - virtual void OnMouseEvent(ui::MouseEvent* event) override; - virtual void OnScrollEvent(ui::ScrollEvent* event) override; - - // Time to show context menu. - void ContextMenuTimerFired(); - - void StartContextMenuTimer(); - - // Convenience method to update the position/visibility of the context menu. - void UpdateContextMenu(); - - // Convenience method for hiding context menu. - void HideContextMenu(); - - // Convenience methods for testing. - gfx::NativeView GetCursorHandleNativeView(); - gfx::Point GetSelectionHandle1Position(); - gfx::Point GetSelectionHandle2Position(); - gfx::Point GetCursorHandlePosition(); - bool IsSelectionHandle1Visible(); - bool IsSelectionHandle2Visible(); - bool IsCursorHandleVisible(); - - ui::TouchEditable* client_view_; - Widget* client_widget_; - scoped_ptr<EditingHandleView> selection_handle_1_; - scoped_ptr<EditingHandleView> selection_handle_2_; - scoped_ptr<EditingHandleView> cursor_handle_; - TouchEditingMenuView* context_menu_; - - // Timer to trigger |context_menu| (|context_menu| is not shown if the - // selection handles are being updated. It appears only when the handles are - // stationary for a certain amount of time). - base::OneShotTimer<TouchSelectionControllerImpl> context_menu_timer_; - - // Pointer to the SelectionHandleView being dragged during a drag session. - EditingHandleView* dragging_handle_; - - // Selection end points. In cursor mode, the two end points are the same and - // correspond to |cursor_handle_|; otherwise, they correspond to - // |selection_handle_1_| and |selection_handle_2_|, respectively. These - // values should be used when selection end points are needed rather than - // position of handles which might be invalid when handles are hidden. - gfx::Rect selection_end_point_1_; - gfx::Rect selection_end_point_2_; - // Selection end points, clipped to client view's boundaries. - gfx::Rect selection_end_point_1_clipped_; - gfx::Rect selection_end_point_2_clipped_; - - DISALLOW_COPY_AND_ASSIGN(TouchSelectionControllerImpl); -}; - -} // namespace views - -#endif // UI_UI_VIEWS_TOUCHUI_TOUCH_SELECTION_CONTROLLER_IMPL_H_
diff --git a/ui/views/touchui/touch_selection_controller_impl_unittest.cc b/ui/views/touchui/touch_selection_controller_impl_unittest.cc deleted file mode 100644 index 214b3c7..0000000 --- a/ui/views/touchui/touch_selection_controller_impl_unittest.cc +++ /dev/null
@@ -1,852 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/command_line.h" -#include "base/strings/utf_string_conversions.h" -#include "ui/aura/client/screen_position_client.h" -#include "ui/aura/window.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/base/touch/touch_editing_controller.h" -#include "ui/base/ui_base_switches.h" -#include "ui/events/test/event_generator.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/point.h" -#include "ui/gfx/rect.h" -#include "ui/gfx/render_text.h" -#include "ui/resources/grit/ui_resources.h" -#include "ui/views/controls/textfield/textfield.h" -#include "ui/views/controls/textfield/textfield_test_api.h" -#include "ui/views/test/views_test_base.h" -#include "ui/views/touchui/touch_selection_controller_impl.h" -#include "ui/views/views_touch_selection_controller_factory.h" -#include "ui/views/widget/widget.h" - -using base::ASCIIToUTF16; -using base::UTF16ToUTF8; -using base::WideToUTF16; - -namespace { -// Should match kSelectionHandlePadding in touch_selection_controller. -const int kPadding = 10; - -// Should match kSelectionHandleBarMinHeight in touch_selection_controller. -const int kBarMinHeight = 5; - -// Should match kSelectionHandleBarBottomAllowance in -// touch_selection_controller. -const int kBarBottomAllowance = 3; - -// Should match kMenuButtonWidth in touch_editing_menu. -const int kMenuButtonWidth = 63; - -// Should match size of kMenuCommands array in touch_editing_menu. -const int kMenuCommandCount = 3; - -gfx::Image* GetHandleImage() { - static gfx::Image* handle_image = NULL; - if (!handle_image) { - handle_image = &ui::ResourceBundle::GetSharedInstance().GetImageNamed( - IDR_TEXT_SELECTION_HANDLE); - } - return handle_image; -} - -gfx::Size GetHandleImageSize() { - return GetHandleImage()->Size(); -} -} // namespace - -namespace views { - -class TouchSelectionControllerImplTest : public ViewsTestBase { - public: - TouchSelectionControllerImplTest() - : textfield_widget_(NULL), - widget_(NULL), - textfield_(NULL), - views_tsc_factory_(new ViewsTouchSelectionControllerFactory) { - CommandLine::ForCurrentProcess()->AppendSwitch( - switches::kEnableTouchEditing); - ui::TouchSelectionControllerFactory::SetInstance(views_tsc_factory_.get()); - } - - virtual ~TouchSelectionControllerImplTest() { - ui::TouchSelectionControllerFactory::SetInstance(NULL); - } - - virtual void TearDown() { - if (textfield_widget_ && !textfield_widget_->IsClosed()) - textfield_widget_->Close(); - if (widget_ && !widget_->IsClosed()) - widget_->Close(); - ViewsTestBase::TearDown(); - } - - void CreateTextfield() { - textfield_ = new Textfield(); - textfield_widget_ = new Widget; - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.bounds = gfx::Rect(0, 0, 200, 200); - textfield_widget_->Init(params); - View* container = new View(); - textfield_widget_->SetContentsView(container); - container->AddChildView(textfield_); - - textfield_->SetBoundsRect(gfx::Rect(0, 0, 200, 20)); - textfield_->set_id(1); - textfield_widget_->Show(); - - textfield_->RequestFocus(); - - textfield_test_api_.reset(new TextfieldTestApi(textfield_)); - } - - void CreateWidget() { - widget_ = new Widget; - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.bounds = gfx::Rect(0, 0, 200, 200); - widget_->Init(params); - widget_->Show(); - } - - protected: - static bool IsCursorHandleVisibleFor( - ui::TouchSelectionController* controller) { - TouchSelectionControllerImpl* impl = - static_cast<TouchSelectionControllerImpl*>(controller); - return impl->IsCursorHandleVisible(); - } - - gfx::Rect GetCursorRect(const gfx::SelectionModel& sel) { - return textfield_test_api_->GetRenderText()->GetCursorBounds(sel, true); - } - - gfx::Point GetCursorPosition(const gfx::SelectionModel& sel) { - gfx::Rect cursor_bounds = GetCursorRect(sel); - return gfx::Point(cursor_bounds.x(), cursor_bounds.y()); - } - - TouchSelectionControllerImpl* GetSelectionController() { - return static_cast<TouchSelectionControllerImpl*>( - textfield_test_api_->touch_selection_controller()); - } - - void StartTouchEditing() { - textfield_test_api_->CreateTouchSelectionControllerAndNotifyIt(); - } - - void EndTouchEditing() { - textfield_test_api_->ResetTouchSelectionController(); - } - - void SimulateSelectionHandleDrag(gfx::Point p, int selection_handle) { - TouchSelectionControllerImpl* controller = GetSelectionController(); - // Do the work of OnMousePressed(). - if (selection_handle == 1) - controller->SetDraggingHandle(controller->selection_handle_1_.get()); - else - controller->SetDraggingHandle(controller->selection_handle_2_.get()); - - // Offset the drag position by the selection handle radius since it is - // supposed to be in the coordinate system of the handle. - p.Offset(GetHandleImageSize().width() / 2 + kPadding, 0); - controller->SelectionHandleDragged(p); - - // Do the work of OnMouseReleased(). - controller->dragging_handle_ = NULL; - } - - gfx::NativeView GetCursorHandleNativeView() { - return GetSelectionController()->GetCursorHandleNativeView(); - } - - gfx::Point GetSelectionHandle1Position() { - return GetSelectionController()->GetSelectionHandle1Position(); - } - - gfx::Point GetSelectionHandle2Position() { - return GetSelectionController()->GetSelectionHandle2Position(); - } - - gfx::Point GetCursorHandlePosition() { - return GetSelectionController()->GetCursorHandlePosition(); - } - - bool IsSelectionHandle1Visible() { - return GetSelectionController()->IsSelectionHandle1Visible(); - } - - bool IsSelectionHandle2Visible() { - return GetSelectionController()->IsSelectionHandle2Visible(); - } - - bool IsCursorHandleVisible() { - return GetSelectionController()->IsCursorHandleVisible(); - } - - gfx::RenderText* GetRenderText() { - return textfield_test_api_->GetRenderText(); - } - - gfx::Point GetCursorHandleDragPoint() { - gfx::Point point = GetCursorHandlePosition(); - const gfx::SelectionModel& sel = textfield_->GetSelectionModel(); - int cursor_height = GetCursorRect(sel).height(); - point.Offset(GetHandleImageSize().width() / 2 + kPadding, - GetHandleImageSize().height() / 2 + cursor_height); - return point; - } - - Widget* textfield_widget_; - Widget* widget_; - - Textfield* textfield_; - scoped_ptr<TextfieldTestApi> textfield_test_api_; - scoped_ptr<ViewsTouchSelectionControllerFactory> views_tsc_factory_; - - private: - DISALLOW_COPY_AND_ASSIGN(TouchSelectionControllerImplTest); -}; - -// If textfield has selection, this macro verifies that the selection handles -// are visible and at the correct positions (at the end points of selection). -// |cursor_at_selection_handle_1| is used to decide whether selection -// handle 1's position is matched against the start of selection or the end. -#define VERIFY_HANDLE_POSITIONS(cursor_at_selection_handle_1) \ -{ \ - gfx::SelectionModel sel = textfield_->GetSelectionModel(); \ - if (textfield_->HasSelection()) { \ - EXPECT_TRUE(IsSelectionHandle1Visible()); \ - EXPECT_TRUE(IsSelectionHandle2Visible()); \ - EXPECT_FALSE(IsCursorHandleVisible()); \ - gfx::SelectionModel sel_start = GetRenderText()-> \ - GetSelectionModelForSelectionStart(); \ - gfx::Point selection_start = GetCursorPosition(sel_start); \ - gfx::Point selection_end = GetCursorPosition(sel); \ - gfx::Point sh1 = GetSelectionHandle1Position(); \ - gfx::Point sh2 = GetSelectionHandle2Position(); \ - sh1.Offset(GetHandleImageSize().width() / 2 + kPadding, 0); \ - sh2.Offset(GetHandleImageSize().width() / 2 + kPadding, 0); \ - if (cursor_at_selection_handle_1) { \ - EXPECT_EQ(sh1, selection_end); \ - EXPECT_EQ(sh2, selection_start); \ - } else { \ - EXPECT_EQ(sh1, selection_start); \ - EXPECT_EQ(sh2, selection_end); \ - } \ - } else { \ - EXPECT_FALSE(IsSelectionHandle1Visible()); \ - EXPECT_FALSE(IsSelectionHandle2Visible()); \ - EXPECT_TRUE(IsCursorHandleVisible()); \ - gfx::Point cursor_pos = GetCursorPosition(sel); \ - gfx::Point ch_pos = GetCursorHandlePosition(); \ - ch_pos.Offset(GetHandleImageSize().width() / 2 + kPadding, 0); \ - EXPECT_EQ(ch_pos, cursor_pos); \ - } \ -} - -// Tests that the selection handles are placed appropriately when selection in -// a Textfield changes. -TEST_F(TouchSelectionControllerImplTest, SelectionInTextfieldTest) { - CreateTextfield(); - textfield_->SetText(ASCIIToUTF16("some text")); - // Tap the textfield to invoke touch selection. - ui::GestureEventDetails details(ui::ET_GESTURE_TAP); - details.set_tap_count(1); - ui::GestureEvent tap(0, 0, 0, base::TimeDelta(), details); - textfield_->OnGestureEvent(&tap); - - // Test selecting a range. - textfield_->SelectRange(gfx::Range(3, 7)); - VERIFY_HANDLE_POSITIONS(false); - - // Test selecting everything. - textfield_->SelectAll(false); - VERIFY_HANDLE_POSITIONS(false); - - // Test with no selection. - textfield_->ClearSelection(); - VERIFY_HANDLE_POSITIONS(false); - - // Test with lost focus. - textfield_widget_->GetFocusManager()->ClearFocus(); - EXPECT_FALSE(GetSelectionController()); - - // Test with focus re-gained. - textfield_widget_->GetFocusManager()->SetFocusedView(textfield_); - EXPECT_FALSE(GetSelectionController()); - textfield_->OnGestureEvent(&tap); - VERIFY_HANDLE_POSITIONS(false); -} - -// Tests that the selection handles are placed appropriately in bidi text. -TEST_F(TouchSelectionControllerImplTest, SelectionInBidiTextfieldTest) { - CreateTextfield(); - textfield_->SetText(WideToUTF16(L"abc\x05d0\x05d1\x05d2")); - // Tap the textfield to invoke touch selection. - ui::GestureEventDetails details(ui::ET_GESTURE_TAP); - details.set_tap_count(1); - ui::GestureEvent tap(0, 0, 0, base::TimeDelta(), details); - textfield_->OnGestureEvent(&tap); - - // Test cursor at run boundary and with empty selection. - textfield_->SelectSelectionModel( - gfx::SelectionModel(3, gfx::CURSOR_BACKWARD)); - VERIFY_HANDLE_POSITIONS(false); - - // Test selection range inside one run and starts or ends at run boundary. - textfield_->SelectRange(gfx::Range(2, 3)); - VERIFY_HANDLE_POSITIONS(false); - - textfield_->SelectRange(gfx::Range(3, 2)); - VERIFY_HANDLE_POSITIONS(false); - - textfield_->SelectRange(gfx::Range(3, 4)); - VERIFY_HANDLE_POSITIONS(false); - - textfield_->SelectRange(gfx::Range(4, 3)); - VERIFY_HANDLE_POSITIONS(false); - - textfield_->SelectRange(gfx::Range(3, 6)); - VERIFY_HANDLE_POSITIONS(false); - - textfield_->SelectRange(gfx::Range(6, 3)); - VERIFY_HANDLE_POSITIONS(false); - - // Test selection range accross runs. - textfield_->SelectRange(gfx::Range(0, 6)); - VERIFY_HANDLE_POSITIONS(false); - - textfield_->SelectRange(gfx::Range(6, 0)); - VERIFY_HANDLE_POSITIONS(false); - - textfield_->SelectRange(gfx::Range(1, 4)); - VERIFY_HANDLE_POSITIONS(false); - - textfield_->SelectRange(gfx::Range(4, 1)); - VERIFY_HANDLE_POSITIONS(false); -} - -// Tests if the SelectRect callback is called appropriately when selection -// handles are moved. -TEST_F(TouchSelectionControllerImplTest, SelectRectCallbackTest) { - CreateTextfield(); - textfield_->SetText(ASCIIToUTF16("textfield with selected text")); - // Tap the textfield to invoke touch selection. - ui::GestureEventDetails details(ui::ET_GESTURE_TAP); - details.set_tap_count(1); - ui::GestureEvent tap(0, 0, 0, base::TimeDelta(), details); - textfield_->OnGestureEvent(&tap); - textfield_->SelectRange(gfx::Range(3, 7)); - - EXPECT_EQ(UTF16ToUTF8(textfield_->GetSelectedText()), "tfie"); - VERIFY_HANDLE_POSITIONS(false); - - // Drag selection handle 2 to right by 3 chars. - const gfx::FontList& font_list = textfield_->GetFontList(); - int x = gfx::Canvas::GetStringWidth(ASCIIToUTF16("ld "), font_list); - SimulateSelectionHandleDrag(gfx::Point(x, 0), 2); - EXPECT_EQ(UTF16ToUTF8(textfield_->GetSelectedText()), "tfield "); - VERIFY_HANDLE_POSITIONS(false); - - // Drag selection handle 1 to the left by a large amount (selection should - // just stick to the beginning of the textfield). - SimulateSelectionHandleDrag(gfx::Point(-50, 0), 1); - EXPECT_EQ(UTF16ToUTF8(textfield_->GetSelectedText()), "textfield "); - VERIFY_HANDLE_POSITIONS(true); - - // Drag selection handle 1 across selection handle 2. - x = gfx::Canvas::GetStringWidth(ASCIIToUTF16("textfield with "), font_list); - SimulateSelectionHandleDrag(gfx::Point(x, 0), 1); - EXPECT_EQ(UTF16ToUTF8(textfield_->GetSelectedText()), "with "); - VERIFY_HANDLE_POSITIONS(true); - - // Drag selection handle 2 across selection handle 1. - x = gfx::Canvas::GetStringWidth(ASCIIToUTF16("with selected "), font_list); - SimulateSelectionHandleDrag(gfx::Point(x, 0), 2); - EXPECT_EQ(UTF16ToUTF8(textfield_->GetSelectedText()), "selected "); - VERIFY_HANDLE_POSITIONS(false); -} - -TEST_F(TouchSelectionControllerImplTest, SelectRectInBidiCallbackTest) { - CreateTextfield(); - textfield_->SetText(WideToUTF16(L"abc\x05e1\x05e2\x05e3" L"def")); - // Tap the textfield to invoke touch selection. - ui::GestureEventDetails details(ui::ET_GESTURE_TAP); - details.set_tap_count(1); - ui::GestureEvent tap(0, 0, 0, base::TimeDelta(), details); - textfield_->OnGestureEvent(&tap); - - // Select [c] from left to right. - textfield_->SelectRange(gfx::Range(2, 3)); - EXPECT_EQ(WideToUTF16(L"c"), textfield_->GetSelectedText()); - VERIFY_HANDLE_POSITIONS(false); - - // Drag selection handle 2 to right by 1 char. - const gfx::FontList& font_list = textfield_->GetFontList(); - int x = gfx::Canvas::GetStringWidth(WideToUTF16(L"\x05e3"), font_list); - SimulateSelectionHandleDrag(gfx::Point(x, 0), 2); - EXPECT_EQ(WideToUTF16(L"c\x05e1\x05e2"), textfield_->GetSelectedText()); - VERIFY_HANDLE_POSITIONS(false); - - // Drag selection handle 1 to left by 1 char. - x = gfx::Canvas::GetStringWidth(WideToUTF16(L"b"), font_list); - SimulateSelectionHandleDrag(gfx::Point(-x, 0), 1); - EXPECT_EQ(WideToUTF16(L"bc\x05e1\x05e2"), textfield_->GetSelectedText()); - VERIFY_HANDLE_POSITIONS(true); - - // Select [c] from right to left. - textfield_->SelectRange(gfx::Range(3, 2)); - EXPECT_EQ(WideToUTF16(L"c"), textfield_->GetSelectedText()); - VERIFY_HANDLE_POSITIONS(false); - - // Drag selection handle 1 to right by 1 char. - x = gfx::Canvas::GetStringWidth(WideToUTF16(L"\x05e3"), font_list); - SimulateSelectionHandleDrag(gfx::Point(x, 0), 1); - EXPECT_EQ(WideToUTF16(L"c\x05e1\x05e2"), textfield_->GetSelectedText()); - VERIFY_HANDLE_POSITIONS(true); - - // Drag selection handle 2 to left by 1 char. - x = gfx::Canvas::GetStringWidth(WideToUTF16(L"b"), font_list); - SimulateSelectionHandleDrag(gfx::Point(-x, 0), 2); - EXPECT_EQ(WideToUTF16(L"bc\x05e1\x05e2"), textfield_->GetSelectedText()); - VERIFY_HANDLE_POSITIONS(false); - - // Select [\x5e1] from right to left. - textfield_->SelectRange(gfx::Range(3, 4)); - EXPECT_EQ(WideToUTF16(L"\x05e1"), textfield_->GetSelectedText()); - VERIFY_HANDLE_POSITIONS(false); - - /* TODO(xji): for bidi text "abcDEF" whose display is "abcFEDhij", when click - right of 'D' and select [D] then move the left selection handle to left - by one character, it should select [ED], instead it selects [F]. - Reason: click right of 'D' and left of 'h' return the same x-axis position, - pass this position to FindCursorPosition() returns index of 'h'. which - means the selection start changed from 3 to 6. - Need further investigation on whether this is a bug in Pango and how to - work around it. - // Drag selection handle 2 to left by 1 char. - x = gfx::Canvas::GetStringWidth(WideToUTF16(L"\x05e2"), font_list); - SimulateSelectionHandleDrag(gfx::Point(-x, 0), 2); - EXPECT_EQ(WideToUTF16(L"\x05e1\x05e2"), textfield_->GetSelectedText()); - VERIFY_HANDLE_POSITIONS(false); - */ - - // Drag selection handle 1 to right by 1 char. - x = gfx::Canvas::GetStringWidth(WideToUTF16(L"d"), font_list); - SimulateSelectionHandleDrag(gfx::Point(x, 0), 1); - EXPECT_EQ(WideToUTF16(L"\x05e2\x05e3" L"d"), textfield_->GetSelectedText()); - VERIFY_HANDLE_POSITIONS(true); - - // Select [\x5e1] from left to right. - textfield_->SelectRange(gfx::Range(4, 3)); - EXPECT_EQ(WideToUTF16(L"\x05e1"), textfield_->GetSelectedText()); - VERIFY_HANDLE_POSITIONS(false); - - /* TODO(xji): see detail of above commented out test case. - // Drag selection handle 1 to left by 1 char. - x = gfx::Canvas::GetStringWidth(WideToUTF16(L"\x05e2"), font_list); - SimulateSelectionHandleDrag(gfx::Point(-x, 0), 1); - EXPECT_EQ(WideToUTF16(L"\x05e1\x05e2"), textfield_->GetSelectedText()); - VERIFY_HANDLE_POSITIONS(true); - */ - - // Drag selection handle 2 to right by 1 char. - x = gfx::Canvas::GetStringWidth(WideToUTF16(L"d"), font_list); - SimulateSelectionHandleDrag(gfx::Point(x, 0), 2); - EXPECT_EQ(WideToUTF16(L"\x05e2\x05e3" L"d"), textfield_->GetSelectedText()); - VERIFY_HANDLE_POSITIONS(false); - - // Select [\x05r3] from right to left. - textfield_->SelectRange(gfx::Range(5, 6)); - EXPECT_EQ(WideToUTF16(L"\x05e3"), textfield_->GetSelectedText()); - VERIFY_HANDLE_POSITIONS(false); - - // Drag selection handle 2 to left by 1 char. - x = gfx::Canvas::GetStringWidth(WideToUTF16(L"c"), font_list); - SimulateSelectionHandleDrag(gfx::Point(-x, 0), 2); - EXPECT_EQ(WideToUTF16(L"c\x05e1\x05e2"), textfield_->GetSelectedText()); - VERIFY_HANDLE_POSITIONS(false); - - // Drag selection handle 1 to right by 1 char. - x = gfx::Canvas::GetStringWidth(WideToUTF16(L"\x05e2"), font_list); - SimulateSelectionHandleDrag(gfx::Point(x, 0), 1); - EXPECT_EQ(WideToUTF16(L"c\x05e1"), textfield_->GetSelectedText()); - VERIFY_HANDLE_POSITIONS(true); - - // Select [\x05r3] from left to right. - textfield_->SelectRange(gfx::Range(6, 5)); - EXPECT_EQ(WideToUTF16(L"\x05e3"), textfield_->GetSelectedText()); - VERIFY_HANDLE_POSITIONS(false); - - // Drag selection handle 1 to left by 1 char. - x = gfx::Canvas::GetStringWidth(WideToUTF16(L"c"), font_list); - SimulateSelectionHandleDrag(gfx::Point(-x, 0), 1); - EXPECT_EQ(WideToUTF16(L"c\x05e1\x05e2"), textfield_->GetSelectedText()); - VERIFY_HANDLE_POSITIONS(true); - - // Drag selection handle 2 to right by 1 char. - x = gfx::Canvas::GetStringWidth(WideToUTF16(L"\x05e2"), font_list); - SimulateSelectionHandleDrag(gfx::Point(x, 0), 2); - EXPECT_EQ(WideToUTF16(L"c\x05e1"), textfield_->GetSelectedText()); - VERIFY_HANDLE_POSITIONS(false); -} - -TEST_F(TouchSelectionControllerImplTest, - HiddenSelectionHandleRetainsCursorPosition) { - // Create a textfield with lots of text in it. - CreateTextfield(); - std::string textfield_text("some text"); - for (int i = 0; i < 10; ++i) - textfield_text += textfield_text; - textfield_->SetText(ASCIIToUTF16(textfield_text)); - - // Tap the textfield to invoke selection. - ui::GestureEventDetails details(ui::ET_GESTURE_TAP); - details.set_tap_count(1); - ui::GestureEvent tap(0, 0, 0, base::TimeDelta(), details); - textfield_->OnGestureEvent(&tap); - - // Select some text such that one handle is hidden. - textfield_->SelectRange(gfx::Range(10, textfield_text.length())); - - // Check that one selection handle is hidden. - EXPECT_FALSE(IsSelectionHandle1Visible()); - EXPECT_TRUE(IsSelectionHandle2Visible()); - EXPECT_EQ(gfx::Range(10, textfield_text.length()), - textfield_->GetSelectedRange()); - - // Drag the visible handle around and make sure the selection end point of the - // invisible handle does not change. - size_t visible_handle_position = textfield_->GetSelectedRange().end(); - for (int i = 0; i < 10; ++i) { - SimulateSelectionHandleDrag(gfx::Point(-10, 0), 2); - // Make sure that the visible handle is being dragged. - EXPECT_NE(visible_handle_position, textfield_->GetSelectedRange().end()); - visible_handle_position = textfield_->GetSelectedRange().end(); - EXPECT_EQ((size_t) 10, textfield_->GetSelectedRange().start()); - } -} - -TEST_F(TouchSelectionControllerImplTest, - DoubleTapInTextfieldWithCursorHandleShouldSelectText) { - CreateTextfield(); - textfield_->SetText(ASCIIToUTF16("some text")); - ui::test::EventGenerator generator( - textfield_->GetWidget()->GetNativeView()->GetRootWindow()); - - // Tap the textfield to invoke touch selection. - generator.GestureTapAt(gfx::Point(10, 10)); - - // Cursor handle should be visible. - EXPECT_FALSE(textfield_->HasSelection()); - VERIFY_HANDLE_POSITIONS(false); - - // Double tap on the cursor handle position. We want to check that the cursor - // handle is not eating the event and that the event is falling through to the - // textfield. - gfx::Point cursor_pos = GetCursorHandlePosition(); - cursor_pos.Offset(GetHandleImageSize().width() / 2 + kPadding, 0); - generator.GestureTapAt(cursor_pos); - generator.GestureTapAt(cursor_pos); - EXPECT_TRUE(textfield_->HasSelection()); -} - -// A simple implementation of TouchEditable that allows faking cursor position -// inside its boundaries. -class TestTouchEditable : public ui::TouchEditable { - public: - explicit TestTouchEditable(aura::Window* window) - : window_(window) { - DCHECK(window); - } - - void set_bounds(const gfx::Rect& bounds) { - bounds_ = bounds; - } - - void set_cursor_rect(const gfx::Rect& cursor_rect) { - cursor_rect_ = cursor_rect; - } - - virtual ~TestTouchEditable() {} - - private: - // Overridden from ui::TouchEditable. - virtual void SelectRect( - const gfx::Point& start, const gfx::Point& end) override { - NOTREACHED(); - } - virtual void MoveCaretTo(const gfx::Point& point) override { - NOTREACHED(); - } - virtual void GetSelectionEndPoints(gfx::Rect* p1, gfx::Rect* p2) override { - *p1 = *p2 = cursor_rect_; - } - virtual gfx::Rect GetBounds() override { - return gfx::Rect(bounds_.size()); - } - virtual gfx::NativeView GetNativeView() const override { - return window_; - } - virtual void ConvertPointToScreen(gfx::Point* point) override { - aura::client::ScreenPositionClient* screen_position_client = - aura::client::GetScreenPositionClient(window_->GetRootWindow()); - if (screen_position_client) - screen_position_client->ConvertPointToScreen(window_, point); - } - virtual void ConvertPointFromScreen(gfx::Point* point) override { - aura::client::ScreenPositionClient* screen_position_client = - aura::client::GetScreenPositionClient(window_->GetRootWindow()); - if (screen_position_client) - screen_position_client->ConvertPointFromScreen(window_, point); - } - virtual bool DrawsHandles() override { - return false; - } - virtual void OpenContextMenu(const gfx::Point& anchor) override { - NOTREACHED(); - } - virtual void DestroyTouchSelection() override { - NOTREACHED(); - } - - // Overridden from ui::SimpleMenuModel::Delegate. - virtual bool IsCommandIdChecked(int command_id) const override { - NOTREACHED(); - return false; - } - virtual bool IsCommandIdEnabled(int command_id) const override { - NOTREACHED(); - return false; - } - virtual bool GetAcceleratorForCommandId( - int command_id, - ui::Accelerator* accelerator) override { - NOTREACHED(); - return false; - } - virtual void ExecuteCommand(int command_id, int event_flags) override { - NOTREACHED(); - } - - aura::Window* window_; - - // Boundaries of the client view. - gfx::Rect bounds_; - - // Cursor position inside the client view. - gfx::Rect cursor_rect_; - - DISALLOW_COPY_AND_ASSIGN(TestTouchEditable); -}; - -// Tests if the touch editing handle is shown or hidden properly according to -// the cursor position relative to the client boundaries. -TEST_F(TouchSelectionControllerImplTest, - VisibilityOfHandleRegardingClientBounds) { - CreateWidget(); - - TestTouchEditable touch_editable(widget_->GetNativeView()); - scoped_ptr<ui::TouchSelectionController> touch_selection_controller( - ui::TouchSelectionController::create(&touch_editable)); - - touch_editable.set_bounds(gfx::Rect(0, 0, 100, 20)); - - // Put the cursor completely inside the client bounds. Handle should be - // visible. - touch_editable.set_cursor_rect(gfx::Rect(2, 0, 1, 20)); - touch_selection_controller->SelectionChanged(); - EXPECT_TRUE(IsCursorHandleVisibleFor(touch_selection_controller.get())); - - // Move the cursor up such that |kBarMinHeight| pixels are still in the client - // bounds. Handle should still be visible. - touch_editable.set_cursor_rect(gfx::Rect(2, kBarMinHeight - 20, 1, 20)); - touch_selection_controller->SelectionChanged(); - EXPECT_TRUE(IsCursorHandleVisibleFor(touch_selection_controller.get())); - - // Move the cursor up such that less than |kBarMinHeight| pixels are in the - // client bounds. Handle should be hidden. - touch_editable.set_cursor_rect(gfx::Rect(2, kBarMinHeight - 20 - 1, 1, 20)); - touch_selection_controller->SelectionChanged(); - EXPECT_FALSE(IsCursorHandleVisibleFor(touch_selection_controller.get())); - - // Move the Cursor down such that |kBarBottomAllowance| pixels are out of the - // client bounds. Handle should be visible. - touch_editable.set_cursor_rect(gfx::Rect(2, kBarBottomAllowance, 1, 20)); - touch_selection_controller->SelectionChanged(); - EXPECT_TRUE(IsCursorHandleVisibleFor(touch_selection_controller.get())); - - // Move the cursor down such that more than |kBarBottomAllowance| pixels are - // out of the client bounds. Handle should be hidden. - touch_editable.set_cursor_rect(gfx::Rect(2, kBarBottomAllowance + 1, 1, 20)); - touch_selection_controller->SelectionChanged(); - EXPECT_FALSE(IsCursorHandleVisibleFor(touch_selection_controller.get())); - - touch_selection_controller.reset(); -} - -TEST_F(TouchSelectionControllerImplTest, HandlesStackAboveParent) { - ui::EventTarget* root = GetContext(); - ui::EventTargeter* targeter = root->GetEventTargeter(); - - // Create the first window containing a Views::Textfield. - CreateTextfield(); - aura::Window* window1 = textfield_widget_->GetNativeView(); - - // Start touch editing, check that the handle is above the first window, and - // end touch editing. - StartTouchEditing(); - gfx::Point test_point = GetCursorHandleDragPoint(); - ui::MouseEvent test_event1(ui::ET_MOUSE_MOVED, test_point, test_point, - ui::EF_NONE, ui::EF_NONE); - EXPECT_EQ(GetCursorHandleNativeView(), - targeter->FindTargetForEvent(root, &test_event1)); - EndTouchEditing(); - - // Create the second (empty) window over the first one. - CreateWidget(); - aura::Window* window2 = widget_->GetNativeView(); - - // Start touch editing (in the first window) and check that the handle is not - // above the second window. - StartTouchEditing(); - ui::MouseEvent test_event2(ui::ET_MOUSE_MOVED, test_point, test_point, - ui::EF_NONE, ui::EF_NONE); - EXPECT_EQ(window2, targeter->FindTargetForEvent(root, &test_event2)); - - // Move the first window to top and check that the handle is kept above the - // first window. - window1->GetRootWindow()->StackChildAtTop(window1); - ui::MouseEvent test_event3(ui::ET_MOUSE_MOVED, test_point, test_point, - ui::EF_NONE, ui::EF_NONE); - EXPECT_EQ(GetCursorHandleNativeView(), - targeter->FindTargetForEvent(root, &test_event3)); -} - -// A simple implementation of TouchEditingMenuController that enables all -// available commands. -class TestTouchEditingMenuController : public TouchEditingMenuController { - public: - TestTouchEditingMenuController() {} - virtual ~TestTouchEditingMenuController() {} - - // Overriden from TouchEditingMenuController. - virtual bool IsCommandIdEnabled(int command_id) const override { - // Return true, since we want the menu to have all |kMenuCommandCount| - // available commands. - return true; - } - virtual void ExecuteCommand(int command_id, int event_flags) override { - NOTREACHED(); - } - virtual void OpenContextMenu() override { - NOTREACHED(); - } - virtual void OnMenuClosed(TouchEditingMenuView* menu) override {} - - private: - DISALLOW_COPY_AND_ASSIGN(TestTouchEditingMenuController); -}; - -// Tests if anchor rect for touch editing quick menu is adjusted correctly based -// on the distance of handles. -TEST_F(TouchSelectionControllerImplTest, QuickMenuAdjustsAnchorRect) { - CreateWidget(); - aura::Window* window = widget_->GetNativeView(); - - scoped_ptr<TestTouchEditingMenuController> quick_menu_controller( - new TestTouchEditingMenuController()); - - // Some arbitrary size for touch editing handle image. - gfx::Size handle_image_size(10, 10); - - // Calculate the width of quick menu. In addition to |kMenuCommandCount| - // commands, there is an item for ellipsis. - int quick_menu_width = (kMenuCommandCount + 1) * kMenuButtonWidth + - kMenuCommandCount; - - // Set anchor rect's width a bit smaller than the quick menu width plus handle - // image width and check that anchor rect's height is adjusted. - gfx::Rect anchor_rect( - 0, 0, quick_menu_width + handle_image_size.width() - 10, 20); - TouchEditingMenuView* quick_menu(TouchEditingMenuView::Create( - quick_menu_controller.get(), anchor_rect, handle_image_size, window)); - anchor_rect.Inset(0, 0, 0, -handle_image_size.height()); - EXPECT_EQ(anchor_rect.ToString(), quick_menu->GetAnchorRect().ToString()); - - // Set anchor rect's width a bit greater than the quick menu width plus handle - // image width and check that anchor rect's height is not adjusted. - anchor_rect = - gfx::Rect(0, 0, quick_menu_width + handle_image_size.width() + 10, 20); - quick_menu = TouchEditingMenuView::Create( - quick_menu_controller.get(), anchor_rect, handle_image_size, window); - EXPECT_EQ(anchor_rect.ToString(), quick_menu->GetAnchorRect().ToString()); - - // Close the widget, hence quick menus, before quick menu controller goes out - // of scope. - widget_->CloseNow(); - widget_ = NULL; -} - -TEST_F(TouchSelectionControllerImplTest, MouseEventDeactivatesTouchSelection) { - CreateTextfield(); - EXPECT_FALSE(GetSelectionController()); - - ui::test::EventGenerator generator( - textfield_widget_->GetNativeView()->GetRootWindow()); - - generator.set_current_location(gfx::Point(5, 5)); - RunPendingMessages(); - - // Start touch editing; then move mouse over the textfield and ensure it - // deactivates touch selection. - StartTouchEditing(); - EXPECT_TRUE(GetSelectionController()); - generator.MoveMouseTo(gfx::Point(5, 10)); - RunPendingMessages(); - EXPECT_FALSE(GetSelectionController()); - - generator.MoveMouseTo(gfx::Point(5, 50)); - RunPendingMessages(); - - // Start touch editing; then move mouse out of the textfield, but inside the - // winow and ensure it deactivates touch selection. - StartTouchEditing(); - EXPECT_TRUE(GetSelectionController()); - generator.MoveMouseTo(gfx::Point(5, 55)); - RunPendingMessages(); - EXPECT_FALSE(GetSelectionController()); - - generator.MoveMouseTo(gfx::Point(5, 500)); - RunPendingMessages(); - - // Start touch editing; then move mouse out of the textfield and window and - // ensure it deactivates touch selection. - StartTouchEditing(); - EXPECT_TRUE(GetSelectionController()); - generator.MoveMouseTo(5, 505); - RunPendingMessages(); - EXPECT_FALSE(GetSelectionController()); -} - -TEST_F(TouchSelectionControllerImplTest, KeyEventDeactivatesTouchSelection) { - CreateTextfield(); - EXPECT_FALSE(GetSelectionController()); - - ui::test::EventGenerator generator( - textfield_widget_->GetNativeView()->GetRootWindow()); - - RunPendingMessages(); - - // Start touch editing; then press a key and ensure it deactivates touch - // selection. - StartTouchEditing(); - EXPECT_TRUE(GetSelectionController()); - generator.PressKey(ui::VKEY_A, 0); - RunPendingMessages(); - EXPECT_FALSE(GetSelectionController()); -} - -} // namespace views
diff --git a/ui/views/view.cc b/ui/views/view.cc deleted file mode 100644 index e85f228..0000000 --- a/ui/views/view.cc +++ /dev/null
@@ -1,2465 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#define _USE_MATH_DEFINES // For VC++ to get M_PI. This has to be first. - -#include "ui/views/view.h" - -#include <algorithm> -#include <cmath> - -#include "base/debug/trace_event.h" -#include "base/logging.h" -#include "base/memory/scoped_ptr.h" -#include "base/message_loop/message_loop.h" -#include "base/strings/stringprintf.h" -#include "base/strings/utf_string_conversions.h" -#include "third_party/skia/include/core/SkRect.h" -#include "ui/accessibility/ax_enums.h" -#include "ui/base/cursor/cursor.h" -#include "ui/base/dragdrop/drag_drop_types.h" -#include "ui/compositor/compositor.h" -#include "ui/compositor/dip_util.h" -#include "ui/compositor/layer.h" -#include "ui/compositor/layer_animator.h" -#include "ui/events/event_target_iterator.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/interpolated_transform.h" -#include "ui/gfx/path.h" -#include "ui/gfx/point3_f.h" -#include "ui/gfx/point_conversions.h" -#include "ui/gfx/scoped_canvas.h" -#include "ui/gfx/screen.h" -#include "ui/gfx/skia_util.h" -#include "ui/gfx/transform.h" -#include "ui/native_theme/native_theme.h" -#include "ui/views/accessibility/native_view_accessibility.h" -#include "ui/views/background.h" -#include "ui/views/border.h" -#include "ui/views/context_menu_controller.h" -#include "ui/views/drag_controller.h" -#include "ui/views/focus/view_storage.h" -#include "ui/views/layout/layout_manager.h" -#include "ui/views/views_delegate.h" -#include "ui/views/widget/native_widget_private.h" -#include "ui/views/widget/root_view.h" -#include "ui/views/widget/tooltip_manager.h" -#include "ui/views/widget/widget.h" - -#if defined(OS_WIN) -#include "base/win/scoped_gdi_object.h" -#endif - -namespace { - -#if defined(OS_WIN) -const bool kContextMenuOnMousePress = false; -#else -const bool kContextMenuOnMousePress = true; -#endif - -// Default horizontal drag threshold in pixels. -// Same as what gtk uses. -const int kDefaultHorizontalDragThreshold = 8; - -// Default vertical drag threshold in pixels. -// Same as what gtk uses. -const int kDefaultVerticalDragThreshold = 8; - -// Returns the top view in |view|'s hierarchy. -const views::View* GetHierarchyRoot(const views::View* view) { - const views::View* root = view; - while (root && root->parent()) - root = root->parent(); - return root; -} - -} // namespace - -namespace views { - -namespace internal { - -} // namespace internal - -// static -ViewsDelegate* ViewsDelegate::views_delegate = NULL; - -// static -const char View::kViewClassName[] = "View"; - -//////////////////////////////////////////////////////////////////////////////// -// View, public: - -// Creation and lifetime ------------------------------------------------------- - -View::View() - : owned_by_client_(false), - id_(0), - group_(-1), - parent_(NULL), - visible_(true), - enabled_(true), - notify_enter_exit_on_child_(false), - registered_for_visible_bounds_notification_(false), - root_bounds_dirty_(true), - clip_insets_(0, 0, 0, 0), - needs_layout_(true), - snap_layer_to_pixel_boundary_(false), - flip_canvas_on_paint_for_rtl_ui_(false), - paint_to_layer_(false), - accelerator_focus_manager_(NULL), - registered_accelerator_count_(0), - next_focusable_view_(NULL), - previous_focusable_view_(NULL), - focusable_(false), - accessibility_focusable_(false), - context_menu_controller_(NULL), - drag_controller_(NULL), - native_view_accessibility_(NULL) { -} - -View::~View() { - if (parent_) - parent_->RemoveChildView(this); - - ViewStorage::GetInstance()->ViewRemoved(this); - - for (Views::const_iterator i(children_.begin()); i != children_.end(); ++i) { - (*i)->parent_ = NULL; - if (!(*i)->owned_by_client_) - delete *i; - } - - // Release ownership of the native accessibility object, but it's - // reference-counted on some platforms, so it may not be deleted right away. - if (native_view_accessibility_) - native_view_accessibility_->Destroy(); -} - -// Tree operations ------------------------------------------------------------- - -const Widget* View::GetWidget() const { - // The root view holds a reference to this view hierarchy's Widget. - return parent_ ? parent_->GetWidget() : NULL; -} - -Widget* View::GetWidget() { - return const_cast<Widget*>(const_cast<const View*>(this)->GetWidget()); -} - -void View::AddChildView(View* view) { - if (view->parent_ == this) - return; - AddChildViewAt(view, child_count()); -} - -void View::AddChildViewAt(View* view, int index) { - CHECK_NE(view, this) << "You cannot add a view as its own child"; - DCHECK_GE(index, 0); - DCHECK_LE(index, child_count()); - - // If |view| has a parent, remove it from its parent. - View* parent = view->parent_; - ui::NativeTheme* old_theme = NULL; - if (parent) { - old_theme = view->GetNativeTheme(); - if (parent == this) { - ReorderChildView(view, index); - return; - } - parent->DoRemoveChildView(view, true, true, false, this); - } - - // Sets the prev/next focus views. - InitFocusSiblings(view, index); - - // Let's insert the view. - view->parent_ = this; - children_.insert(children_.begin() + index, view); - - // Instruct the view to recompute its root bounds on next Paint(). - view->SetRootBoundsDirty(true); - - views::Widget* widget = GetWidget(); - if (widget) { - const ui::NativeTheme* new_theme = view->GetNativeTheme(); - if (new_theme != old_theme) - view->PropagateNativeThemeChanged(new_theme); - } - - ViewHierarchyChangedDetails details(true, this, view, parent); - - for (View* v = this; v; v = v->parent_) - v->ViewHierarchyChangedImpl(false, details); - - view->PropagateAddNotifications(details); - UpdateTooltip(); - if (widget) { - RegisterChildrenForVisibleBoundsNotification(view); - if (view->visible()) - view->SchedulePaint(); - } - - if (layout_manager_.get()) - layout_manager_->ViewAdded(this, view); - - ReorderLayers(); - - // Make sure the visibility of the child layers are correct. - // If any of the parent View is hidden, then the layers of the subtree - // rooted at |this| should be hidden. Otherwise, all the child layers should - // inherit the visibility of the owner View. - UpdateLayerVisibility(); -} - -void View::ReorderChildView(View* view, int index) { - DCHECK_EQ(view->parent_, this); - if (index < 0) - index = child_count() - 1; - else if (index >= child_count()) - return; - if (children_[index] == view) - return; - - const Views::iterator i(std::find(children_.begin(), children_.end(), view)); - DCHECK(i != children_.end()); - children_.erase(i); - - // Unlink the view first - View* next_focusable = view->next_focusable_view_; - View* prev_focusable = view->previous_focusable_view_; - if (prev_focusable) - prev_focusable->next_focusable_view_ = next_focusable; - if (next_focusable) - next_focusable->previous_focusable_view_ = prev_focusable; - - // Add it in the specified index now. - InitFocusSiblings(view, index); - children_.insert(children_.begin() + index, view); - - ReorderLayers(); -} - -void View::RemoveChildView(View* view) { - DoRemoveChildView(view, true, true, false, NULL); -} - -void View::RemoveAllChildViews(bool delete_children) { - while (!children_.empty()) - DoRemoveChildView(children_.front(), false, false, delete_children, NULL); - UpdateTooltip(); -} - -bool View::Contains(const View* view) const { - for (const View* v = view; v; v = v->parent_) { - if (v == this) - return true; - } - return false; -} - -int View::GetIndexOf(const View* view) const { - Views::const_iterator i(std::find(children_.begin(), children_.end(), view)); - return i != children_.end() ? static_cast<int>(i - children_.begin()) : -1; -} - -// Size and disposition -------------------------------------------------------- - -void View::SetBounds(int x, int y, int width, int height) { - SetBoundsRect(gfx::Rect(x, y, std::max(0, width), std::max(0, height))); -} - -void View::SetBoundsRect(const gfx::Rect& bounds) { - if (bounds == bounds_) { - if (needs_layout_) { - needs_layout_ = false; - Layout(); - } - return; - } - - if (visible_) { - // Paint where the view is currently. - SchedulePaintBoundsChanged( - bounds_.size() == bounds.size() ? SCHEDULE_PAINT_SIZE_SAME : - SCHEDULE_PAINT_SIZE_CHANGED); - } - - gfx::Rect prev = bounds_; - bounds_ = bounds; - BoundsChanged(prev); -} - -void View::SetSize(const gfx::Size& size) { - SetBounds(x(), y(), size.width(), size.height()); -} - -void View::SetPosition(const gfx::Point& position) { - SetBounds(position.x(), position.y(), width(), height()); -} - -void View::SetX(int x) { - SetBounds(x, y(), width(), height()); -} - -void View::SetY(int y) { - SetBounds(x(), y, width(), height()); -} - -gfx::Rect View::GetContentsBounds() const { - gfx::Rect contents_bounds(GetLocalBounds()); - if (border_.get()) - contents_bounds.Inset(border_->GetInsets()); - return contents_bounds; -} - -gfx::Rect View::GetLocalBounds() const { - return gfx::Rect(size()); -} - -gfx::Rect View::GetLayerBoundsInPixel() const { - return layer()->GetTargetBounds(); -} - -gfx::Insets View::GetInsets() const { - return border_.get() ? border_->GetInsets() : gfx::Insets(); -} - -gfx::Rect View::GetVisibleBounds() const { - if (!IsDrawn()) - return gfx::Rect(); - gfx::Rect vis_bounds(GetLocalBounds()); - gfx::Rect ancestor_bounds; - const View* view = this; - gfx::Transform transform; - - while (view != NULL && !vis_bounds.IsEmpty()) { - transform.ConcatTransform(view->GetTransform()); - gfx::Transform translation; - translation.Translate(static_cast<float>(view->GetMirroredX()), - static_cast<float>(view->y())); - transform.ConcatTransform(translation); - - vis_bounds = view->ConvertRectToParent(vis_bounds); - const View* ancestor = view->parent_; - if (ancestor != NULL) { - ancestor_bounds.SetRect(0, 0, ancestor->width(), ancestor->height()); - vis_bounds.Intersect(ancestor_bounds); - } else if (!view->GetWidget()) { - // If the view has no Widget, we're not visible. Return an empty rect. - return gfx::Rect(); - } - view = ancestor; - } - if (vis_bounds.IsEmpty()) - return vis_bounds; - // Convert back to this views coordinate system. - gfx::RectF views_vis_bounds(vis_bounds); - transform.TransformRectReverse(&views_vis_bounds); - // Partially visible pixels should be considered visible. - return gfx::ToEnclosingRect(views_vis_bounds); -} - -gfx::Rect View::GetBoundsInScreen() const { - gfx::Point origin; - View::ConvertPointToScreen(this, &origin); - return gfx::Rect(origin, size()); -} - -gfx::Size View::GetPreferredSize() const { - if (layout_manager_.get()) - return layout_manager_->GetPreferredSize(this); - return gfx::Size(); -} - -int View::GetBaseline() const { - return -1; -} - -void View::SizeToPreferredSize() { - gfx::Size prefsize = GetPreferredSize(); - if ((prefsize.width() != width()) || (prefsize.height() != height())) - SetBounds(x(), y(), prefsize.width(), prefsize.height()); -} - -gfx::Size View::GetMinimumSize() const { - return GetPreferredSize(); -} - -gfx::Size View::GetMaximumSize() const { - return gfx::Size(); -} - -int View::GetHeightForWidth(int w) const { - if (layout_manager_.get()) - return layout_manager_->GetPreferredHeightForWidth(this, w); - return GetPreferredSize().height(); -} - -void View::SetVisible(bool visible) { - if (visible != visible_) { - // If the View is currently visible, schedule paint to refresh parent. - // TODO(beng): not sure we should be doing this if we have a layer. - if (visible_) - SchedulePaint(); - - visible_ = visible; - AdvanceFocusIfNecessary(); - - // Notify the parent. - if (parent_) - parent_->ChildVisibilityChanged(this); - - // This notifies all sub-views recursively. - PropagateVisibilityNotifications(this, visible_); - UpdateLayerVisibility(); - - // If we are newly visible, schedule paint. - if (visible_) { - SchedulePaint(); - } else { - // We're never painted when hidden, so no need to be in the BoundsTree. - BoundsTree* bounds_tree = GetBoundsTreeFromPaintRoot(); - if (bounds_tree) - RemoveRootBounds(bounds_tree); - } - } -} - -bool View::IsDrawn() const { - return visible_ && parent_ ? parent_->IsDrawn() : false; -} - -void View::SetEnabled(bool enabled) { - if (enabled != enabled_) { - enabled_ = enabled; - AdvanceFocusIfNecessary(); - OnEnabledChanged(); - } -} - -void View::OnEnabledChanged() { - SchedulePaint(); -} - -// Transformations ------------------------------------------------------------- - -gfx::Transform View::GetTransform() const { - return layer() ? layer()->transform() : gfx::Transform(); -} - -void View::SetTransform(const gfx::Transform& transform) { - if (transform.IsIdentity()) { - if (layer()) { - layer()->SetTransform(transform); - if (!paint_to_layer_) - DestroyLayer(); - } else { - // Nothing. - } - } else { - if (!layer()) - CreateLayer(); - layer()->SetTransform(transform); - layer()->ScheduleDraw(); - } -} - -void View::SetPaintToLayer(bool paint_to_layer) { - if (paint_to_layer_ == paint_to_layer) - return; - - // If this is a change in state we will also need to update bounds trees. - if (paint_to_layer) { - // Gaining a layer means becoming a paint root. We must remove ourselves - // from our old paint root, if we had one. Traverse up view tree to find old - // paint root. - View* old_paint_root = parent_; - while (old_paint_root && !old_paint_root->IsPaintRoot()) - old_paint_root = old_paint_root->parent_; - - // Remove our and our children's bounds from the old tree. This will also - // mark all of our bounds as dirty. - if (old_paint_root && old_paint_root->bounds_tree_) - RemoveRootBounds(old_paint_root->bounds_tree_.get()); - - } else { - // Losing a layer means we are no longer a paint root, so delete our - // bounds tree and mark ourselves as dirty for future insertion into our - // new paint root's bounds tree. - bounds_tree_.reset(); - SetRootBoundsDirty(true); - } - - paint_to_layer_ = paint_to_layer; - if (paint_to_layer_ && !layer()) { - CreateLayer(); - } else if (!paint_to_layer_ && layer()) { - DestroyLayer(); - } -} - -// RTL positioning ------------------------------------------------------------- - -gfx::Rect View::GetMirroredBounds() const { - gfx::Rect bounds(bounds_); - bounds.set_x(GetMirroredX()); - return bounds; -} - -gfx::Point View::GetMirroredPosition() const { - return gfx::Point(GetMirroredX(), y()); -} - -int View::GetMirroredX() const { - return parent_ ? parent_->GetMirroredXForRect(bounds_) : x(); -} - -int View::GetMirroredXForRect(const gfx::Rect& bounds) const { - return base::i18n::IsRTL() ? - (width() - bounds.x() - bounds.width()) : bounds.x(); -} - -int View::GetMirroredXInView(int x) const { - return base::i18n::IsRTL() ? width() - x : x; -} - -int View::GetMirroredXWithWidthInView(int x, int w) const { - return base::i18n::IsRTL() ? width() - x - w : x; -} - -// Layout ---------------------------------------------------------------------- - -void View::Layout() { - needs_layout_ = false; - - // If we have a layout manager, let it handle the layout for us. - if (layout_manager_.get()) - layout_manager_->Layout(this); - - // Make sure to propagate the Layout() call to any children that haven't - // received it yet through the layout manager and need to be laid out. This - // is needed for the case when the child requires a layout but its bounds - // weren't changed by the layout manager. If there is no layout manager, we - // just propagate the Layout() call down the hierarchy, so whoever receives - // the call can take appropriate action. - for (int i = 0, count = child_count(); i < count; ++i) { - View* child = child_at(i); - if (child->needs_layout_ || !layout_manager_.get()) { - child->needs_layout_ = false; - child->Layout(); - } - } -} - -void View::InvalidateLayout() { - // Always invalidate up. This is needed to handle the case of us already being - // valid, but not our parent. - needs_layout_ = true; - if (parent_) - parent_->InvalidateLayout(); -} - -LayoutManager* View::GetLayoutManager() const { - return layout_manager_.get(); -} - -void View::SetLayoutManager(LayoutManager* layout_manager) { - if (layout_manager_.get()) - layout_manager_->Uninstalled(this); - - layout_manager_.reset(layout_manager); - if (layout_manager_.get()) - layout_manager_->Installed(this); -} - -void View::SnapLayerToPixelBoundary() { - if (!layer()) - return; - - if (snap_layer_to_pixel_boundary_ && layer()->parent() && - layer()->GetCompositor()) { - ui::SnapLayerToPhysicalPixelBoundary(layer()->parent(), layer()); - } else { - // Reset the offset. - layer()->SetSubpixelPositionOffset(gfx::Vector2dF()); - } -} - -// Attributes ------------------------------------------------------------------ - -const char* View::GetClassName() const { - return kViewClassName; -} - -const View* View::GetAncestorWithClassName(const std::string& name) const { - for (const View* view = this; view; view = view->parent_) { - if (!strcmp(view->GetClassName(), name.c_str())) - return view; - } - return NULL; -} - -View* View::GetAncestorWithClassName(const std::string& name) { - return const_cast<View*>(const_cast<const View*>(this)-> - GetAncestorWithClassName(name)); -} - -const View* View::GetViewByID(int id) const { - if (id == id_) - return const_cast<View*>(this); - - for (int i = 0, count = child_count(); i < count; ++i) { - const View* view = child_at(i)->GetViewByID(id); - if (view) - return view; - } - return NULL; -} - -View* View::GetViewByID(int id) { - return const_cast<View*>(const_cast<const View*>(this)->GetViewByID(id)); -} - -void View::SetGroup(int gid) { - // Don't change the group id once it's set. - DCHECK(group_ == -1 || group_ == gid); - group_ = gid; -} - -int View::GetGroup() const { - return group_; -} - -bool View::IsGroupFocusTraversable() const { - return true; -} - -void View::GetViewsInGroup(int group, Views* views) { - if (group_ == group) - views->push_back(this); - - for (int i = 0, count = child_count(); i < count; ++i) - child_at(i)->GetViewsInGroup(group, views); -} - -View* View::GetSelectedViewForGroup(int group) { - Views views; - GetWidget()->GetRootView()->GetViewsInGroup(group, &views); - return views.empty() ? NULL : views[0]; -} - -// Coordinate conversion ------------------------------------------------------- - -// static -void View::ConvertPointToTarget(const View* source, - const View* target, - gfx::Point* point) { - DCHECK(source); - DCHECK(target); - if (source == target) - return; - - const View* root = GetHierarchyRoot(target); - CHECK_EQ(GetHierarchyRoot(source), root); - - if (source != root) - source->ConvertPointForAncestor(root, point); - - if (target != root) - target->ConvertPointFromAncestor(root, point); -} - -// static -void View::ConvertRectToTarget(const View* source, - const View* target, - gfx::RectF* rect) { - DCHECK(source); - DCHECK(target); - if (source == target) - return; - - const View* root = GetHierarchyRoot(target); - CHECK_EQ(GetHierarchyRoot(source), root); - - if (source != root) - source->ConvertRectForAncestor(root, rect); - - if (target != root) - target->ConvertRectFromAncestor(root, rect); -} - -// static -void View::ConvertPointToWidget(const View* src, gfx::Point* p) { - DCHECK(src); - DCHECK(p); - - src->ConvertPointForAncestor(NULL, p); -} - -// static -void View::ConvertPointFromWidget(const View* dest, gfx::Point* p) { - DCHECK(dest); - DCHECK(p); - - dest->ConvertPointFromAncestor(NULL, p); -} - -// static -void View::ConvertPointToScreen(const View* src, gfx::Point* p) { - DCHECK(src); - DCHECK(p); - - // If the view is not connected to a tree, there's nothing we can do. - const Widget* widget = src->GetWidget(); - if (widget) { - ConvertPointToWidget(src, p); - *p += widget->GetClientAreaBoundsInScreen().OffsetFromOrigin(); - } -} - -// static -void View::ConvertPointFromScreen(const View* dst, gfx::Point* p) { - DCHECK(dst); - DCHECK(p); - - const views::Widget* widget = dst->GetWidget(); - if (!widget) - return; - *p -= widget->GetClientAreaBoundsInScreen().OffsetFromOrigin(); - views::View::ConvertPointFromWidget(dst, p); -} - -gfx::Rect View::ConvertRectToParent(const gfx::Rect& rect) const { - gfx::RectF x_rect = rect; - GetTransform().TransformRect(&x_rect); - x_rect.Offset(GetMirroredPosition().OffsetFromOrigin()); - // Pixels we partially occupy in the parent should be included. - return gfx::ToEnclosingRect(x_rect); -} - -gfx::Rect View::ConvertRectToWidget(const gfx::Rect& rect) const { - gfx::Rect x_rect = rect; - for (const View* v = this; v; v = v->parent_) - x_rect = v->ConvertRectToParent(x_rect); - return x_rect; -} - -// Painting -------------------------------------------------------------------- - -void View::SchedulePaint() { - SchedulePaintInRect(GetLocalBounds()); -} - -void View::SchedulePaintInRect(const gfx::Rect& rect) { - if (!visible_) - return; - - if (layer()) { - layer()->SchedulePaint(rect); - } else if (parent_) { - // Translate the requested paint rect to the parent's coordinate system - // then pass this notification up to the parent. - parent_->SchedulePaintInRect(ConvertRectToParent(rect)); - } -} - -void View::Paint(gfx::Canvas* canvas, const CullSet& cull_set) { - // The cull_set may allow us to skip painting without canvas construction or - // even canvas rect intersection. - if (cull_set.ShouldPaint(this)) { - TRACE_EVENT1("views", "View::Paint", "class", GetClassName()); - - gfx::ScopedCanvas scoped_canvas(canvas); - - // Paint this View and its children, setting the clip rect to the bounds - // of this View and translating the origin to the local bounds' top left - // point. - // - // Note that the X (or left) position we pass to ClipRectInt takes into - // consideration whether or not the view uses a right-to-left layout so that - // we paint our view in its mirrored position if need be. - gfx::Rect clip_rect = bounds(); - clip_rect.Inset(clip_insets_); - if (parent_) - clip_rect.set_x(parent_->GetMirroredXForRect(clip_rect)); - canvas->ClipRect(clip_rect); - if (canvas->IsClipEmpty()) - return; - - // Non-empty clip, translate the graphics such that 0,0 corresponds to where - // this view is located (related to its parent). - canvas->Translate(GetMirroredPosition().OffsetFromOrigin()); - canvas->Transform(GetTransform()); - - // If we are a paint root, we need to construct our own CullSet object for - // propagation to our children. - if (IsPaintRoot()) { - if (!bounds_tree_) - bounds_tree_.reset(new BoundsTree(2, 5)); - - // Recompute our bounds tree as needed. - UpdateRootBounds(bounds_tree_.get(), gfx::Vector2d()); - - // Grab the clip rect from the supplied canvas to use as the query rect. - gfx::Rect canvas_bounds; - if (!canvas->GetClipBounds(&canvas_bounds)) { - NOTREACHED() << "Failed to get clip bounds from the canvas!"; - return; - } - - // Now query our bounds_tree_ for a set of damaged views that intersect - // our canvas bounds. - scoped_ptr<base::hash_set<intptr_t> > damaged_views( - new base::hash_set<intptr_t>()); - bounds_tree_->AppendIntersectingRecords( - canvas_bounds, damaged_views.get()); - // Construct a CullSet to wrap the damaged views set, it will delete it - // for us on scope exit. - CullSet paint_root_cull_set(damaged_views.Pass()); - // Paint all descendents using our new cull set. - PaintCommon(canvas, paint_root_cull_set); - } else { - // Not a paint root, so we can proceed as normal. - PaintCommon(canvas, cull_set); - } - } -} - -void View::set_background(Background* b) { - background_.reset(b); -} - -void View::SetBorder(scoped_ptr<Border> b) { border_ = b.Pass(); } - -ui::ThemeProvider* View::GetThemeProvider() const { - const Widget* widget = GetWidget(); - return widget ? widget->GetThemeProvider() : NULL; -} - -const ui::NativeTheme* View::GetNativeTheme() const { - const Widget* widget = GetWidget(); - return widget ? widget->GetNativeTheme() : ui::NativeTheme::instance(); -} - -// Input ----------------------------------------------------------------------- - -View* View::GetEventHandlerForPoint(const gfx::Point& point) { - return GetEventHandlerForRect(gfx::Rect(point, gfx::Size(1, 1))); -} - -View* View::GetEventHandlerForRect(const gfx::Rect& rect) { - return GetEffectiveViewTargeter()->TargetForRect(this, rect); -} - -bool View::CanProcessEventsWithinSubtree() const { - return true; -} - -View* View::GetTooltipHandlerForPoint(const gfx::Point& point) { - // TODO(tdanderson): Move this implementation into ViewTargetDelegate. - if (!HitTestPoint(point) || !CanProcessEventsWithinSubtree()) - return NULL; - - // Walk the child Views recursively looking for the View that most - // tightly encloses the specified point. - for (int i = child_count() - 1; i >= 0; --i) { - View* child = child_at(i); - if (!child->visible()) - continue; - - gfx::Point point_in_child_coords(point); - ConvertPointToTarget(this, child, &point_in_child_coords); - View* handler = child->GetTooltipHandlerForPoint(point_in_child_coords); - if (handler) - return handler; - } - return this; -} - -gfx::NativeCursor View::GetCursor(const ui::MouseEvent& event) { -#if defined(OS_WIN) - static ui::Cursor arrow; - if (!arrow.platform()) - arrow.SetPlatformCursor(LoadCursor(NULL, IDC_ARROW)); - return arrow; -#else - return gfx::kNullCursor; -#endif -} - -bool View::HitTestPoint(const gfx::Point& point) const { - return HitTestRect(gfx::Rect(point, gfx::Size(1, 1))); -} - -bool View::HitTestRect(const gfx::Rect& rect) const { - return GetEffectiveViewTargeter()->DoesIntersectRect(this, rect); -} - -bool View::IsMouseHovered() { - // If we haven't yet been placed in an onscreen view hierarchy, we can't be - // hovered. - if (!GetWidget()) - return false; - - // If mouse events are disabled, then the mouse cursor is invisible and - // is therefore not hovering over this button. - if (!GetWidget()->IsMouseEventsEnabled()) - return false; - - gfx::Point cursor_pos(gfx::Screen::GetScreenFor( - GetWidget()->GetNativeView())->GetCursorScreenPoint()); - ConvertPointFromScreen(this, &cursor_pos); - return HitTestPoint(cursor_pos); -} - -bool View::OnMousePressed(const ui::MouseEvent& event) { - return false; -} - -bool View::OnMouseDragged(const ui::MouseEvent& event) { - return false; -} - -void View::OnMouseReleased(const ui::MouseEvent& event) { -} - -void View::OnMouseCaptureLost() { -} - -void View::OnMouseMoved(const ui::MouseEvent& event) { -} - -void View::OnMouseEntered(const ui::MouseEvent& event) { -} - -void View::OnMouseExited(const ui::MouseEvent& event) { -} - -void View::SetMouseHandler(View* new_mouse_handler) { - // |new_mouse_handler| may be NULL. - if (parent_) - parent_->SetMouseHandler(new_mouse_handler); -} - -bool View::OnKeyPressed(const ui::KeyEvent& event) { - return false; -} - -bool View::OnKeyReleased(const ui::KeyEvent& event) { - return false; -} - -bool View::OnMouseWheel(const ui::MouseWheelEvent& event) { - return false; -} - -void View::OnKeyEvent(ui::KeyEvent* event) { - bool consumed = (event->type() == ui::ET_KEY_PRESSED) ? OnKeyPressed(*event) : - OnKeyReleased(*event); - if (consumed) - event->StopPropagation(); -} - -void View::OnMouseEvent(ui::MouseEvent* event) { - switch (event->type()) { - case ui::ET_MOUSE_PRESSED: - if (ProcessMousePressed(*event)) - event->SetHandled(); - return; - - case ui::ET_MOUSE_MOVED: - if ((event->flags() & (ui::EF_LEFT_MOUSE_BUTTON | - ui::EF_RIGHT_MOUSE_BUTTON | - ui::EF_MIDDLE_MOUSE_BUTTON)) == 0) { - OnMouseMoved(*event); - return; - } - // FALL-THROUGH - case ui::ET_MOUSE_DRAGGED: - if (ProcessMouseDragged(*event)) - event->SetHandled(); - return; - - case ui::ET_MOUSE_RELEASED: - ProcessMouseReleased(*event); - return; - - case ui::ET_MOUSEWHEEL: - if (OnMouseWheel(*static_cast<ui::MouseWheelEvent*>(event))) - event->SetHandled(); - break; - - case ui::ET_MOUSE_ENTERED: - if (event->flags() & ui::EF_TOUCH_ACCESSIBILITY) - NotifyAccessibilityEvent(ui::AX_EVENT_HOVER, true); - OnMouseEntered(*event); - break; - - case ui::ET_MOUSE_EXITED: - OnMouseExited(*event); - break; - - default: - return; - } -} - -void View::OnScrollEvent(ui::ScrollEvent* event) { -} - -void View::OnTouchEvent(ui::TouchEvent* event) { - NOTREACHED() << "Views should not receive touch events."; -} - -void View::OnGestureEvent(ui::GestureEvent* event) { -} - -ui::TextInputClient* View::GetTextInputClient() { - return NULL; -} - -InputMethod* View::GetInputMethod() { - Widget* widget = GetWidget(); - return widget ? widget->GetInputMethod() : NULL; -} - -const InputMethod* View::GetInputMethod() const { - const Widget* widget = GetWidget(); - return widget ? widget->GetInputMethod() : NULL; -} - -scoped_ptr<ViewTargeter> -View::SetEventTargeter(scoped_ptr<ViewTargeter> targeter) { - scoped_ptr<ViewTargeter> old_targeter = targeter_.Pass(); - targeter_ = targeter.Pass(); - return old_targeter.Pass(); -} - -ViewTargeter* View::GetEffectiveViewTargeter() const { - DCHECK(GetWidget()); - ViewTargeter* view_targeter = targeter(); - if (!view_targeter) - view_targeter = GetWidget()->GetRootView()->targeter(); - CHECK(view_targeter); - return view_targeter; -} - -bool View::CanAcceptEvent(const ui::Event& event) { - return IsDrawn(); -} - -ui::EventTarget* View::GetParentTarget() { - return parent_; -} - -scoped_ptr<ui::EventTargetIterator> View::GetChildIterator() { - return scoped_ptr<ui::EventTargetIterator>( - new ui::EventTargetIteratorImpl<View>(children_)); -} - -ui::EventTargeter* View::GetEventTargeter() { - return targeter_.get(); -} - -void View::ConvertEventToTarget(ui::EventTarget* target, - ui::LocatedEvent* event) { - event->ConvertLocationToTarget(this, static_cast<View*>(target)); -} - -// Accelerators ---------------------------------------------------------------- - -void View::AddAccelerator(const ui::Accelerator& accelerator) { - if (!accelerators_.get()) - accelerators_.reset(new std::vector<ui::Accelerator>()); - - if (std::find(accelerators_->begin(), accelerators_->end(), accelerator) == - accelerators_->end()) { - accelerators_->push_back(accelerator); - } - RegisterPendingAccelerators(); -} - -void View::RemoveAccelerator(const ui::Accelerator& accelerator) { - if (!accelerators_.get()) { - NOTREACHED() << "Removing non-existing accelerator"; - return; - } - - std::vector<ui::Accelerator>::iterator i( - std::find(accelerators_->begin(), accelerators_->end(), accelerator)); - if (i == accelerators_->end()) { - NOTREACHED() << "Removing non-existing accelerator"; - return; - } - - size_t index = i - accelerators_->begin(); - accelerators_->erase(i); - if (index >= registered_accelerator_count_) { - // The accelerator is not registered to FocusManager. - return; - } - --registered_accelerator_count_; - - // Providing we are attached to a Widget and registered with a focus manager, - // we should de-register from that focus manager now. - if (GetWidget() && accelerator_focus_manager_) - accelerator_focus_manager_->UnregisterAccelerator(accelerator, this); -} - -void View::ResetAccelerators() { - if (accelerators_.get()) - UnregisterAccelerators(false); -} - -bool View::AcceleratorPressed(const ui::Accelerator& accelerator) { - return false; -} - -bool View::CanHandleAccelerators() const { - return enabled() && IsDrawn() && GetWidget() && GetWidget()->IsVisible(); -} - -// Focus ----------------------------------------------------------------------- - -bool View::HasFocus() const { - const FocusManager* focus_manager = GetFocusManager(); - return focus_manager && (focus_manager->GetFocusedView() == this); -} - -View* View::GetNextFocusableView() { - return next_focusable_view_; -} - -const View* View::GetNextFocusableView() const { - return next_focusable_view_; -} - -View* View::GetPreviousFocusableView() { - return previous_focusable_view_; -} - -void View::SetNextFocusableView(View* view) { - if (view) - view->previous_focusable_view_ = this; - next_focusable_view_ = view; -} - -void View::SetFocusable(bool focusable) { - if (focusable_ == focusable) - return; - - focusable_ = focusable; - AdvanceFocusIfNecessary(); -} - -bool View::IsFocusable() const { - return focusable_ && enabled_ && IsDrawn(); -} - -bool View::IsAccessibilityFocusable() const { - return (focusable_ || accessibility_focusable_) && enabled_ && IsDrawn(); -} - -void View::SetAccessibilityFocusable(bool accessibility_focusable) { - if (accessibility_focusable_ == accessibility_focusable) - return; - - accessibility_focusable_ = accessibility_focusable; - AdvanceFocusIfNecessary(); -} - -FocusManager* View::GetFocusManager() { - Widget* widget = GetWidget(); - return widget ? widget->GetFocusManager() : NULL; -} - -const FocusManager* View::GetFocusManager() const { - const Widget* widget = GetWidget(); - return widget ? widget->GetFocusManager() : NULL; -} - -void View::RequestFocus() { - FocusManager* focus_manager = GetFocusManager(); - if (focus_manager && IsFocusable()) - focus_manager->SetFocusedView(this); -} - -bool View::SkipDefaultKeyEventProcessing(const ui::KeyEvent& event) { - return false; -} - -FocusTraversable* View::GetFocusTraversable() { - return NULL; -} - -FocusTraversable* View::GetPaneFocusTraversable() { - return NULL; -} - -// Tooltips -------------------------------------------------------------------- - -bool View::GetTooltipText(const gfx::Point& p, base::string16* tooltip) const { - return false; -} - -bool View::GetTooltipTextOrigin(const gfx::Point& p, gfx::Point* loc) const { - return false; -} - -// Context menus --------------------------------------------------------------- - -void View::ShowContextMenu(const gfx::Point& p, - ui::MenuSourceType source_type) { - if (!context_menu_controller_) - return; - - context_menu_controller_->ShowContextMenuForView(this, p, source_type); -} - -// static -bool View::ShouldShowContextMenuOnMousePress() { - return kContextMenuOnMousePress; -} - -// Drag and drop --------------------------------------------------------------- - -bool View::GetDropFormats( - int* formats, - std::set<OSExchangeData::CustomFormat>* custom_formats) { - return false; -} - -bool View::AreDropTypesRequired() { - return false; -} - -bool View::CanDrop(const OSExchangeData& data) { - // TODO(sky): when I finish up migration, this should default to true. - return false; -} - -void View::OnDragEntered(const ui::DropTargetEvent& event) { -} - -int View::OnDragUpdated(const ui::DropTargetEvent& event) { - return ui::DragDropTypes::DRAG_NONE; -} - -void View::OnDragExited() { -} - -int View::OnPerformDrop(const ui::DropTargetEvent& event) { - return ui::DragDropTypes::DRAG_NONE; -} - -void View::OnDragDone() { -} - -// static -bool View::ExceededDragThreshold(const gfx::Vector2d& delta) { - return (abs(delta.x()) > GetHorizontalDragThreshold() || - abs(delta.y()) > GetVerticalDragThreshold()); -} - -// Accessibility---------------------------------------------------------------- - -gfx::NativeViewAccessible View::GetNativeViewAccessible() { - if (!native_view_accessibility_) - native_view_accessibility_ = NativeViewAccessibility::Create(this); - if (native_view_accessibility_) - return native_view_accessibility_->GetNativeObject(); - return NULL; -} - -void View::NotifyAccessibilityEvent( - ui::AXEvent event_type, - bool send_native_event) { - if (ViewsDelegate::views_delegate) - ViewsDelegate::views_delegate->NotifyAccessibilityEvent(this, event_type); - - if (send_native_event && GetWidget()) { - if (!native_view_accessibility_) - native_view_accessibility_ = NativeViewAccessibility::Create(this); - if (native_view_accessibility_) - native_view_accessibility_->NotifyAccessibilityEvent(event_type); - } -} - -// Scrolling ------------------------------------------------------------------- - -void View::ScrollRectToVisible(const gfx::Rect& rect) { - // We must take RTL UI mirroring into account when adjusting the position of - // the region. - if (parent_) { - gfx::Rect scroll_rect(rect); - scroll_rect.Offset(GetMirroredX(), y()); - parent_->ScrollRectToVisible(scroll_rect); - } -} - -int View::GetPageScrollIncrement(ScrollView* scroll_view, - bool is_horizontal, bool is_positive) { - return 0; -} - -int View::GetLineScrollIncrement(ScrollView* scroll_view, - bool is_horizontal, bool is_positive) { - return 0; -} - -//////////////////////////////////////////////////////////////////////////////// -// View, protected: - -// Size and disposition -------------------------------------------------------- - -void View::OnBoundsChanged(const gfx::Rect& previous_bounds) { -} - -void View::PreferredSizeChanged() { - InvalidateLayout(); - if (parent_) - parent_->ChildPreferredSizeChanged(this); -} - -bool View::GetNeedsNotificationWhenVisibleBoundsChange() const { - return false; -} - -void View::OnVisibleBoundsChanged() { -} - -// Tree operations ------------------------------------------------------------- - -void View::ViewHierarchyChanged(const ViewHierarchyChangedDetails& details) { -} - -void View::VisibilityChanged(View* starting_from, bool is_visible) { -} - -void View::NativeViewHierarchyChanged() { - FocusManager* focus_manager = GetFocusManager(); - if (accelerator_focus_manager_ != focus_manager) { - UnregisterAccelerators(true); - - if (focus_manager) - RegisterPendingAccelerators(); - } -} - -// Painting -------------------------------------------------------------------- - -void View::PaintChildren(gfx::Canvas* canvas, const CullSet& cull_set) { - TRACE_EVENT1("views", "View::PaintChildren", "class", GetClassName()); - for (int i = 0, count = child_count(); i < count; ++i) - if (!child_at(i)->layer()) - child_at(i)->Paint(canvas, cull_set); -} - -void View::OnPaint(gfx::Canvas* canvas) { - TRACE_EVENT1("views", "View::OnPaint", "class", GetClassName()); - OnPaintBackground(canvas); - OnPaintBorder(canvas); -} - -void View::OnPaintBackground(gfx::Canvas* canvas) { - if (background_.get()) { - TRACE_EVENT2("views", "View::OnPaintBackground", - "width", canvas->sk_canvas()->getDevice()->width(), - "height", canvas->sk_canvas()->getDevice()->height()); - background_->Paint(canvas, this); - } -} - -void View::OnPaintBorder(gfx::Canvas* canvas) { - if (border_.get()) { - TRACE_EVENT2("views", "View::OnPaintBorder", - "width", canvas->sk_canvas()->getDevice()->width(), - "height", canvas->sk_canvas()->getDevice()->height()); - border_->Paint(*this, canvas); - } -} - -bool View::IsPaintRoot() { - return paint_to_layer_ || !parent_; -} - -// Accelerated Painting -------------------------------------------------------- - -void View::SetFillsBoundsOpaquely(bool fills_bounds_opaquely) { - // This method should not have the side-effect of creating the layer. - if (layer()) - layer()->SetFillsBoundsOpaquely(fills_bounds_opaquely); -} - -gfx::Vector2d View::CalculateOffsetToAncestorWithLayer( - ui::Layer** layer_parent) { - if (layer()) { - if (layer_parent) - *layer_parent = layer(); - return gfx::Vector2d(); - } - if (!parent_) - return gfx::Vector2d(); - - return gfx::Vector2d(GetMirroredX(), y()) + - parent_->CalculateOffsetToAncestorWithLayer(layer_parent); -} - -void View::UpdateParentLayer() { - if (!layer()) - return; - - ui::Layer* parent_layer = NULL; - gfx::Vector2d offset(GetMirroredX(), y()); - - if (parent_) - offset += parent_->CalculateOffsetToAncestorWithLayer(&parent_layer); - - ReparentLayer(offset, parent_layer); -} - -void View::MoveLayerToParent(ui::Layer* parent_layer, - const gfx::Point& point) { - gfx::Point local_point(point); - if (parent_layer != layer()) - local_point.Offset(GetMirroredX(), y()); - if (layer() && parent_layer != layer()) { - parent_layer->Add(layer()); - SetLayerBounds(gfx::Rect(local_point.x(), local_point.y(), - width(), height())); - } else { - for (int i = 0, count = child_count(); i < count; ++i) - child_at(i)->MoveLayerToParent(parent_layer, local_point); - } -} - -void View::UpdateLayerVisibility() { - bool visible = visible_; - for (const View* v = parent_; visible && v && !v->layer(); v = v->parent_) - visible = v->visible(); - - UpdateChildLayerVisibility(visible); -} - -void View::UpdateChildLayerVisibility(bool ancestor_visible) { - if (layer()) { - layer()->SetVisible(ancestor_visible && visible_); - } else { - for (int i = 0, count = child_count(); i < count; ++i) - child_at(i)->UpdateChildLayerVisibility(ancestor_visible && visible_); - } -} - -void View::UpdateChildLayerBounds(const gfx::Vector2d& offset) { - if (layer()) { - SetLayerBounds(GetLocalBounds() + offset); - } else { - for (int i = 0, count = child_count(); i < count; ++i) { - View* child = child_at(i); - child->UpdateChildLayerBounds( - offset + gfx::Vector2d(child->GetMirroredX(), child->y())); - } - } -} - -void View::OnPaintLayer(gfx::Canvas* canvas) { - if (!layer() || !layer()->fills_bounds_opaquely()) - canvas->DrawColor(SK_ColorBLACK, SkXfermode::kClear_Mode); - PaintCommon(canvas, CullSet()); -} - -void View::OnDelegatedFrameDamage( - const gfx::Rect& damage_rect_in_dip) { -} - -void View::OnDeviceScaleFactorChanged(float device_scale_factor) { - snap_layer_to_pixel_boundary_ = - (device_scale_factor - std::floor(device_scale_factor)) != 0.0f; - SnapLayerToPixelBoundary(); - // Repainting with new scale factor will paint the content at the right scale. -} - -base::Closure View::PrepareForLayerBoundsChange() { - return base::Closure(); -} - -void View::ReorderLayers() { - View* v = this; - while (v && !v->layer()) - v = v->parent(); - - Widget* widget = GetWidget(); - if (!v) { - if (widget) { - ui::Layer* layer = widget->GetLayer(); - if (layer) - widget->GetRootView()->ReorderChildLayers(layer); - } - } else { - v->ReorderChildLayers(v->layer()); - } - - if (widget) { - // Reorder the widget's child NativeViews in case a child NativeView is - // associated with a view (eg via a NativeViewHost). Always do the - // reordering because the associated NativeView's layer (if it has one) - // is parented to the widget's layer regardless of whether the host view has - // an ancestor with a layer. - widget->ReorderNativeViews(); - } -} - -void View::ReorderChildLayers(ui::Layer* parent_layer) { - if (layer() && layer() != parent_layer) { - DCHECK_EQ(parent_layer, layer()->parent()); - parent_layer->StackAtBottom(layer()); - } else { - // Iterate backwards through the children so that a child with a layer - // which is further to the back is stacked above one which is further to - // the front. - for (Views::reverse_iterator it(children_.rbegin()); - it != children_.rend(); ++it) { - (*it)->ReorderChildLayers(parent_layer); - } - } -} - -// Input ----------------------------------------------------------------------- - -View::DragInfo* View::GetDragInfo() { - return parent_ ? parent_->GetDragInfo() : NULL; -} - -// Focus ----------------------------------------------------------------------- - -void View::OnFocus() { - // TODO(beng): Investigate whether it's possible for us to move this to - // Focus(). - // By default, we clear the native focus. This ensures that no visible native - // view as the focus and that we still receive keyboard inputs. - FocusManager* focus_manager = GetFocusManager(); - if (focus_manager) - focus_manager->ClearNativeFocus(); - - // TODO(beng): Investigate whether it's possible for us to move this to - // Focus(). - // Notify assistive technologies of the focus change. - NotifyAccessibilityEvent(ui::AX_EVENT_FOCUS, true); -} - -void View::OnBlur() { -} - -void View::Focus() { - OnFocus(); -} - -void View::Blur() { - OnBlur(); -} - -// Tooltips -------------------------------------------------------------------- - -void View::TooltipTextChanged() { - Widget* widget = GetWidget(); - // TooltipManager may be null if there is a problem creating it. - if (widget && widget->GetTooltipManager()) - widget->GetTooltipManager()->TooltipTextChanged(this); -} - -// Context menus --------------------------------------------------------------- - -gfx::Point View::GetKeyboardContextMenuLocation() { - gfx::Rect vis_bounds = GetVisibleBounds(); - gfx::Point screen_point(vis_bounds.x() + vis_bounds.width() / 2, - vis_bounds.y() + vis_bounds.height() / 2); - ConvertPointToScreen(this, &screen_point); - return screen_point; -} - -// Drag and drop --------------------------------------------------------------- - -int View::GetDragOperations(const gfx::Point& press_pt) { - return drag_controller_ ? - drag_controller_->GetDragOperationsForView(this, press_pt) : - ui::DragDropTypes::DRAG_NONE; -} - -void View::WriteDragData(const gfx::Point& press_pt, OSExchangeData* data) { - DCHECK(drag_controller_); - drag_controller_->WriteDragDataForView(this, press_pt, data); -} - -bool View::InDrag() { - Widget* widget = GetWidget(); - return widget ? widget->dragged_view() == this : false; -} - -int View::GetHorizontalDragThreshold() { - // TODO(jennyz): This value may need to be adjusted for different platforms - // and for different display density. - return kDefaultHorizontalDragThreshold; -} - -int View::GetVerticalDragThreshold() { - // TODO(jennyz): This value may need to be adjusted for different platforms - // and for different display density. - return kDefaultVerticalDragThreshold; -} - -// Debugging ------------------------------------------------------------------- - -#if !defined(NDEBUG) - -std::string View::PrintViewGraph(bool first) { - return DoPrintViewGraph(first, this); -} - -std::string View::DoPrintViewGraph(bool first, View* view_with_children) { - // 64-bit pointer = 16 bytes of hex + "0x" + '\0' = 19. - const size_t kMaxPointerStringLength = 19; - - std::string result; - - if (first) - result.append("digraph {\n"); - - // Node characteristics. - char p[kMaxPointerStringLength]; - - const std::string class_name(GetClassName()); - size_t base_name_index = class_name.find_last_of('/'); - if (base_name_index == std::string::npos) - base_name_index = 0; - else - base_name_index++; - - char bounds_buffer[512]; - - // Information about current node. - base::snprintf(p, arraysize(bounds_buffer), "%p", view_with_children); - result.append(" N"); - result.append(p + 2); - result.append(" [label=\""); - - result.append(class_name.substr(base_name_index).c_str()); - - base::snprintf(bounds_buffer, - arraysize(bounds_buffer), - "\\n bounds: (%d, %d), (%dx%d)", - bounds().x(), - bounds().y(), - bounds().width(), - bounds().height()); - result.append(bounds_buffer); - - gfx::DecomposedTransform decomp; - if (!GetTransform().IsIdentity() && - gfx::DecomposeTransform(&decomp, GetTransform())) { - base::snprintf(bounds_buffer, - arraysize(bounds_buffer), - "\\n translation: (%f, %f)", - decomp.translate[0], - decomp.translate[1]); - result.append(bounds_buffer); - - base::snprintf(bounds_buffer, - arraysize(bounds_buffer), - "\\n rotation: %3.2f", - std::acos(decomp.quaternion[3]) * 360.0 / M_PI); - result.append(bounds_buffer); - - base::snprintf(bounds_buffer, - arraysize(bounds_buffer), - "\\n scale: (%2.4f, %2.4f)", - decomp.scale[0], - decomp.scale[1]); - result.append(bounds_buffer); - } - - result.append("\""); - if (!parent_) - result.append(", shape=box"); - if (layer()) { - if (layer()->has_external_content()) - result.append(", color=green"); - else - result.append(", color=red"); - - if (layer()->fills_bounds_opaquely()) - result.append(", style=filled"); - } - result.append("]\n"); - - // Link to parent. - if (parent_) { - char pp[kMaxPointerStringLength]; - - base::snprintf(pp, kMaxPointerStringLength, "%p", parent_); - result.append(" N"); - result.append(pp + 2); - result.append(" -> N"); - result.append(p + 2); - result.append("\n"); - } - - // Children. - for (int i = 0, count = view_with_children->child_count(); i < count; ++i) - result.append(view_with_children->child_at(i)->PrintViewGraph(false)); - - if (first) - result.append("}\n"); - - return result; -} -#endif - -//////////////////////////////////////////////////////////////////////////////// -// View, private: - -// DropInfo -------------------------------------------------------------------- - -void View::DragInfo::Reset() { - possible_drag = false; - start_pt = gfx::Point(); -} - -void View::DragInfo::PossibleDrag(const gfx::Point& p) { - possible_drag = true; - start_pt = p; -} - -// Painting -------------------------------------------------------------------- - -void View::SchedulePaintBoundsChanged(SchedulePaintType type) { - // If we have a layer and the View's size did not change, we do not need to - // schedule any paints since the layer will be redrawn at its new location - // during the next Draw() cycle in the compositor. - if (!layer() || type == SCHEDULE_PAINT_SIZE_CHANGED) { - // Otherwise, if the size changes or we don't have a layer then we need to - // use SchedulePaint to invalidate the area occupied by the View. - SchedulePaint(); - } else if (parent_ && type == SCHEDULE_PAINT_SIZE_SAME) { - // The compositor doesn't Draw() until something on screen changes, so - // if our position changes but nothing is being animated on screen, then - // tell the compositor to redraw the scene. We know layer() exists due to - // the above if clause. - layer()->ScheduleDraw(); - } -} - -void View::PaintCommon(gfx::Canvas* canvas, const CullSet& cull_set) { - if (!visible_) - return; - - { - // If the View we are about to paint requested the canvas to be flipped, we - // should change the transform appropriately. - // The canvas mirroring is undone once the View is done painting so that we - // don't pass the canvas with the mirrored transform to Views that didn't - // request the canvas to be flipped. - gfx::ScopedCanvas scoped(canvas); - if (FlipCanvasOnPaintForRTLUI()) { - canvas->Translate(gfx::Vector2d(width(), 0)); - canvas->Scale(-1, 1); - } - - OnPaint(canvas); - } - - PaintChildren(canvas, cull_set); -} - -// Tree operations ------------------------------------------------------------- - -void View::DoRemoveChildView(View* view, - bool update_focus_cycle, - bool update_tool_tip, - bool delete_removed_view, - View* new_parent) { - DCHECK(view); - - const Views::iterator i(std::find(children_.begin(), children_.end(), view)); - scoped_ptr<View> view_to_be_deleted; - if (i != children_.end()) { - if (update_focus_cycle) { - // Let's remove the view from the focus traversal. - View* next_focusable = view->next_focusable_view_; - View* prev_focusable = view->previous_focusable_view_; - if (prev_focusable) - prev_focusable->next_focusable_view_ = next_focusable; - if (next_focusable) - next_focusable->previous_focusable_view_ = prev_focusable; - } - - if (GetWidget()) { - UnregisterChildrenForVisibleBoundsNotification(view); - if (view->visible()) - view->SchedulePaint(); - GetWidget()->NotifyWillRemoveView(view); - } - - // Remove the bounds of this child and any of its descendants from our - // paint root bounds tree. - BoundsTree* bounds_tree = GetBoundsTreeFromPaintRoot(); - if (bounds_tree) - view->RemoveRootBounds(bounds_tree); - - view->PropagateRemoveNotifications(this, new_parent); - view->parent_ = NULL; - view->UpdateLayerVisibility(); - - if (delete_removed_view && !view->owned_by_client_) - view_to_be_deleted.reset(view); - - children_.erase(i); - } - - if (update_tool_tip) - UpdateTooltip(); - - if (layout_manager_.get()) - layout_manager_->ViewRemoved(this, view); -} - -void View::PropagateRemoveNotifications(View* old_parent, View* new_parent) { - for (int i = 0, count = child_count(); i < count; ++i) - child_at(i)->PropagateRemoveNotifications(old_parent, new_parent); - - ViewHierarchyChangedDetails details(false, old_parent, this, new_parent); - for (View* v = this; v; v = v->parent_) - v->ViewHierarchyChangedImpl(true, details); -} - -void View::PropagateAddNotifications( - const ViewHierarchyChangedDetails& details) { - for (int i = 0, count = child_count(); i < count; ++i) - child_at(i)->PropagateAddNotifications(details); - ViewHierarchyChangedImpl(true, details); -} - -void View::PropagateNativeViewHierarchyChanged() { - for (int i = 0, count = child_count(); i < count; ++i) - child_at(i)->PropagateNativeViewHierarchyChanged(); - NativeViewHierarchyChanged(); -} - -void View::ViewHierarchyChangedImpl( - bool register_accelerators, - const ViewHierarchyChangedDetails& details) { - if (register_accelerators) { - if (details.is_add) { - // If you get this registration, you are part of a subtree that has been - // added to the view hierarchy. - if (GetFocusManager()) - RegisterPendingAccelerators(); - } else { - if (details.child == this) - UnregisterAccelerators(true); - } - } - - if (details.is_add && layer() && !layer()->parent()) { - UpdateParentLayer(); - Widget* widget = GetWidget(); - if (widget) - widget->UpdateRootLayers(); - } else if (!details.is_add && details.child == this) { - // Make sure the layers belonging to the subtree rooted at |child| get - // removed from layers that do not belong in the same subtree. - OrphanLayers(); - Widget* widget = GetWidget(); - if (widget) - widget->UpdateRootLayers(); - } - - ViewHierarchyChanged(details); - details.parent->needs_layout_ = true; -} - -void View::PropagateNativeThemeChanged(const ui::NativeTheme* theme) { - for (int i = 0, count = child_count(); i < count; ++i) - child_at(i)->PropagateNativeThemeChanged(theme); - OnNativeThemeChanged(theme); -} - -// Size and disposition -------------------------------------------------------- - -void View::PropagateVisibilityNotifications(View* start, bool is_visible) { - for (int i = 0, count = child_count(); i < count; ++i) - child_at(i)->PropagateVisibilityNotifications(start, is_visible); - VisibilityChangedImpl(start, is_visible); -} - -void View::VisibilityChangedImpl(View* starting_from, bool is_visible) { - VisibilityChanged(starting_from, is_visible); -} - -void View::BoundsChanged(const gfx::Rect& previous_bounds) { - // Mark our bounds as dirty for the paint root, also see if we need to - // recompute our children's bounds due to origin change. - bool origin_changed = - previous_bounds.OffsetFromOrigin() != bounds_.OffsetFromOrigin(); - SetRootBoundsDirty(origin_changed); - - if (visible_) { - // Paint the new bounds. - SchedulePaintBoundsChanged( - bounds_.size() == previous_bounds.size() ? SCHEDULE_PAINT_SIZE_SAME : - SCHEDULE_PAINT_SIZE_CHANGED); - } - - if (layer()) { - if (parent_) { - SetLayerBounds(GetLocalBounds() + - gfx::Vector2d(GetMirroredX(), y()) + - parent_->CalculateOffsetToAncestorWithLayer(NULL)); - } else { - SetLayerBounds(bounds_); - } - } else { - // If our bounds have changed, then any descendant layer bounds may have - // changed. Update them accordingly. - UpdateChildLayerBounds(CalculateOffsetToAncestorWithLayer(NULL)); - } - - OnBoundsChanged(previous_bounds); - - if (previous_bounds.size() != size()) { - needs_layout_ = false; - Layout(); - } - - if (GetNeedsNotificationWhenVisibleBoundsChange()) - OnVisibleBoundsChanged(); - - // Notify interested Views that visible bounds within the root view may have - // changed. - if (descendants_to_notify_.get()) { - for (Views::iterator i(descendants_to_notify_->begin()); - i != descendants_to_notify_->end(); ++i) { - (*i)->OnVisibleBoundsChanged(); - } - } -} - -// static -void View::RegisterChildrenForVisibleBoundsNotification(View* view) { - if (view->GetNeedsNotificationWhenVisibleBoundsChange()) - view->RegisterForVisibleBoundsNotification(); - for (int i = 0; i < view->child_count(); ++i) - RegisterChildrenForVisibleBoundsNotification(view->child_at(i)); -} - -// static -void View::UnregisterChildrenForVisibleBoundsNotification(View* view) { - if (view->GetNeedsNotificationWhenVisibleBoundsChange()) - view->UnregisterForVisibleBoundsNotification(); - for (int i = 0; i < view->child_count(); ++i) - UnregisterChildrenForVisibleBoundsNotification(view->child_at(i)); -} - -void View::RegisterForVisibleBoundsNotification() { - if (registered_for_visible_bounds_notification_) - return; - - registered_for_visible_bounds_notification_ = true; - for (View* ancestor = parent_; ancestor; ancestor = ancestor->parent_) - ancestor->AddDescendantToNotify(this); -} - -void View::UnregisterForVisibleBoundsNotification() { - if (!registered_for_visible_bounds_notification_) - return; - - registered_for_visible_bounds_notification_ = false; - for (View* ancestor = parent_; ancestor; ancestor = ancestor->parent_) - ancestor->RemoveDescendantToNotify(this); -} - -void View::AddDescendantToNotify(View* view) { - DCHECK(view); - if (!descendants_to_notify_.get()) - descendants_to_notify_.reset(new Views); - descendants_to_notify_->push_back(view); -} - -void View::RemoveDescendantToNotify(View* view) { - DCHECK(view && descendants_to_notify_.get()); - Views::iterator i(std::find( - descendants_to_notify_->begin(), descendants_to_notify_->end(), view)); - DCHECK(i != descendants_to_notify_->end()); - descendants_to_notify_->erase(i); - if (descendants_to_notify_->empty()) - descendants_to_notify_.reset(); -} - -void View::SetLayerBounds(const gfx::Rect& bounds) { - layer()->SetBounds(bounds); - SnapLayerToPixelBoundary(); -} - -void View::SetRootBoundsDirty(bool origin_changed) { - root_bounds_dirty_ = true; - - if (origin_changed) { - // Inform our children that their root bounds are dirty, as their relative - // coordinates in paint root space have changed since ours have changed. - for (Views::const_iterator i(children_.begin()); i != children_.end(); - ++i) { - if (!(*i)->IsPaintRoot()) - (*i)->SetRootBoundsDirty(origin_changed); - } - } -} - -void View::UpdateRootBounds(BoundsTree* tree, const gfx::Vector2d& offset) { - // If we're not visible no need to update BoundsTree. When we are made visible - // the BoundsTree will be updated appropriately. - if (!visible_) - return; - - if (!root_bounds_dirty_ && children_.empty()) - return; - - // No need to recompute bounds if we haven't flagged ours as dirty. - TRACE_EVENT1("views", "View::UpdateRootBounds", "class", GetClassName()); - - // Add our own offset to the provided offset, for our own bounds update and - // for propagation to our children if needed. - gfx::Vector2d view_offset = offset + GetMirroredBounds().OffsetFromOrigin(); - - // If our bounds have changed we must re-insert our new bounds to the tree. - if (root_bounds_dirty_) { - root_bounds_dirty_ = false; - gfx::Rect bounds( - view_offset.x(), view_offset.y(), bounds_.width(), bounds_.height()); - tree->Insert(bounds, reinterpret_cast<intptr_t>(this)); - } - - // Update our children's bounds if needed. - for (Views::const_iterator i(children_.begin()); i != children_.end(); ++i) { - // We don't descend in to layer views for bounds recomputation, as they - // manage their own RTree as paint roots. - if (!(*i)->IsPaintRoot()) - (*i)->UpdateRootBounds(tree, view_offset); - } -} - -void View::RemoveRootBounds(BoundsTree* tree) { - tree->Remove(reinterpret_cast<intptr_t>(this)); - - root_bounds_dirty_ = true; - - for (Views::const_iterator i(children_.begin()); i != children_.end(); ++i) { - if (!(*i)->IsPaintRoot()) - (*i)->RemoveRootBounds(tree); - } -} - -View::BoundsTree* View::GetBoundsTreeFromPaintRoot() { - BoundsTree* bounds_tree = bounds_tree_.get(); - View* paint_root = this; - while (!bounds_tree && !paint_root->IsPaintRoot()) { - // Assumption is that if IsPaintRoot() is false then parent_ is valid. - DCHECK(paint_root); - paint_root = paint_root->parent_; - bounds_tree = paint_root->bounds_tree_.get(); - } - - return bounds_tree; -} - -// Transformations ------------------------------------------------------------- - -bool View::GetTransformRelativeTo(const View* ancestor, - gfx::Transform* transform) const { - const View* p = this; - - while (p && p != ancestor) { - transform->ConcatTransform(p->GetTransform()); - gfx::Transform translation; - translation.Translate(static_cast<float>(p->GetMirroredX()), - static_cast<float>(p->y())); - transform->ConcatTransform(translation); - - p = p->parent_; - } - - return p == ancestor; -} - -// Coordinate conversion ------------------------------------------------------- - -bool View::ConvertPointForAncestor(const View* ancestor, - gfx::Point* point) const { - gfx::Transform trans; - // TODO(sad): Have some way of caching the transformation results. - bool result = GetTransformRelativeTo(ancestor, &trans); - gfx::Point3F p(*point); - trans.TransformPoint(&p); - *point = gfx::ToFlooredPoint(p.AsPointF()); - return result; -} - -bool View::ConvertPointFromAncestor(const View* ancestor, - gfx::Point* point) const { - gfx::Transform trans; - bool result = GetTransformRelativeTo(ancestor, &trans); - gfx::Point3F p(*point); - trans.TransformPointReverse(&p); - *point = gfx::ToFlooredPoint(p.AsPointF()); - return result; -} - -bool View::ConvertRectForAncestor(const View* ancestor, - gfx::RectF* rect) const { - gfx::Transform trans; - // TODO(sad): Have some way of caching the transformation results. - bool result = GetTransformRelativeTo(ancestor, &trans); - trans.TransformRect(rect); - return result; -} - -bool View::ConvertRectFromAncestor(const View* ancestor, - gfx::RectF* rect) const { - gfx::Transform trans; - bool result = GetTransformRelativeTo(ancestor, &trans); - trans.TransformRectReverse(rect); - return result; -} - -// Accelerated painting -------------------------------------------------------- - -void View::CreateLayer() { - // A new layer is being created for the view. So all the layers of the - // sub-tree can inherit the visibility of the corresponding view. - for (int i = 0, count = child_count(); i < count; ++i) - child_at(i)->UpdateChildLayerVisibility(true); - - SetLayer(new ui::Layer()); - layer()->set_delegate(this); -#if !defined(NDEBUG) - layer()->set_name(GetClassName()); -#endif - - UpdateParentLayers(); - UpdateLayerVisibility(); - - // The new layer needs to be ordered in the layer tree according - // to the view tree. Children of this layer were added in order - // in UpdateParentLayers(). - if (parent()) - parent()->ReorderLayers(); - - Widget* widget = GetWidget(); - if (widget) - widget->UpdateRootLayers(); -} - -void View::UpdateParentLayers() { - // Attach all top-level un-parented layers. - if (layer() && !layer()->parent()) { - UpdateParentLayer(); - } else { - for (int i = 0, count = child_count(); i < count; ++i) - child_at(i)->UpdateParentLayers(); - } -} - -void View::OrphanLayers() { - if (layer()) { - if (layer()->parent()) - layer()->parent()->Remove(layer()); - - // The layer belonging to this View has already been orphaned. It is not - // necessary to orphan the child layers. - return; - } - for (int i = 0, count = child_count(); i < count; ++i) - child_at(i)->OrphanLayers(); -} - -void View::ReparentLayer(const gfx::Vector2d& offset, ui::Layer* parent_layer) { - layer()->SetBounds(GetLocalBounds() + offset); - DCHECK_NE(layer(), parent_layer); - if (parent_layer) - parent_layer->Add(layer()); - layer()->SchedulePaint(GetLocalBounds()); - MoveLayerToParent(layer(), gfx::Point()); -} - -void View::DestroyLayer() { - ui::Layer* new_parent = layer()->parent(); - std::vector<ui::Layer*> children = layer()->children(); - for (size_t i = 0; i < children.size(); ++i) { - layer()->Remove(children[i]); - if (new_parent) - new_parent->Add(children[i]); - } - - LayerOwner::DestroyLayer(); - - if (new_parent) - ReorderLayers(); - - UpdateChildLayerBounds(CalculateOffsetToAncestorWithLayer(NULL)); - - SchedulePaint(); - - Widget* widget = GetWidget(); - if (widget) - widget->UpdateRootLayers(); -} - -// Input ----------------------------------------------------------------------- - -bool View::ProcessMousePressed(const ui::MouseEvent& event) { - int drag_operations = - (enabled_ && event.IsOnlyLeftMouseButton() && - HitTestPoint(event.location())) ? - GetDragOperations(event.location()) : 0; - ContextMenuController* context_menu_controller = event.IsRightMouseButton() ? - context_menu_controller_ : 0; - View::DragInfo* drag_info = GetDragInfo(); - - // TODO(sky): for debugging 360238. - int storage_id = 0; - if (event.IsOnlyRightMouseButton() && context_menu_controller && - kContextMenuOnMousePress && HitTestPoint(event.location())) { - ViewStorage* view_storage = ViewStorage::GetInstance(); - storage_id = view_storage->CreateStorageID(); - view_storage->StoreView(storage_id, this); - } - - const bool enabled = enabled_; - const bool result = OnMousePressed(event); - - if (!enabled) - return result; - - if (event.IsOnlyRightMouseButton() && context_menu_controller && - kContextMenuOnMousePress) { - // Assume that if there is a context menu controller we won't be deleted - // from mouse pressed. - gfx::Point location(event.location()); - if (HitTestPoint(location)) { - if (storage_id != 0) - CHECK_EQ(this, ViewStorage::GetInstance()->RetrieveView(storage_id)); - ConvertPointToScreen(this, &location); - ShowContextMenu(location, ui::MENU_SOURCE_MOUSE); - return true; - } - } - - // WARNING: we may have been deleted, don't use any View variables. - if (drag_operations != ui::DragDropTypes::DRAG_NONE) { - drag_info->PossibleDrag(event.location()); - return true; - } - return !!context_menu_controller || result; -} - -bool View::ProcessMouseDragged(const ui::MouseEvent& event) { - // Copy the field, that way if we're deleted after drag and drop no harm is - // done. - ContextMenuController* context_menu_controller = context_menu_controller_; - const bool possible_drag = GetDragInfo()->possible_drag; - if (possible_drag && - ExceededDragThreshold(GetDragInfo()->start_pt - event.location()) && - (!drag_controller_ || - drag_controller_->CanStartDragForView( - this, GetDragInfo()->start_pt, event.location()))) { - DoDrag(event, GetDragInfo()->start_pt, - ui::DragDropTypes::DRAG_EVENT_SOURCE_MOUSE); - } else { - if (OnMouseDragged(event)) - return true; - // Fall through to return value based on context menu controller. - } - // WARNING: we may have been deleted. - return (context_menu_controller != NULL) || possible_drag; -} - -void View::ProcessMouseReleased(const ui::MouseEvent& event) { - if (!kContextMenuOnMousePress && context_menu_controller_ && - event.IsOnlyRightMouseButton()) { - // Assume that if there is a context menu controller we won't be deleted - // from mouse released. - gfx::Point location(event.location()); - OnMouseReleased(event); - if (HitTestPoint(location)) { - ConvertPointToScreen(this, &location); - ShowContextMenu(location, ui::MENU_SOURCE_MOUSE); - } - } else { - OnMouseReleased(event); - } - // WARNING: we may have been deleted. -} - -// Accelerators ---------------------------------------------------------------- - -void View::RegisterPendingAccelerators() { - if (!accelerators_.get() || - registered_accelerator_count_ == accelerators_->size()) { - // No accelerators are waiting for registration. - return; - } - - if (!GetWidget()) { - // The view is not yet attached to a widget, defer registration until then. - return; - } - - accelerator_focus_manager_ = GetFocusManager(); - if (!accelerator_focus_manager_) { - // Some crash reports seem to show that we may get cases where we have no - // focus manager (see bug #1291225). This should never be the case, just - // making sure we don't crash. - NOTREACHED(); - return; - } - for (std::vector<ui::Accelerator>::const_iterator i( - accelerators_->begin() + registered_accelerator_count_); - i != accelerators_->end(); ++i) { - accelerator_focus_manager_->RegisterAccelerator( - *i, ui::AcceleratorManager::kNormalPriority, this); - } - registered_accelerator_count_ = accelerators_->size(); -} - -void View::UnregisterAccelerators(bool leave_data_intact) { - if (!accelerators_.get()) - return; - - if (GetWidget()) { - if (accelerator_focus_manager_) { - accelerator_focus_manager_->UnregisterAccelerators(this); - accelerator_focus_manager_ = NULL; - } - if (!leave_data_intact) { - accelerators_->clear(); - accelerators_.reset(); - } - registered_accelerator_count_ = 0; - } -} - -// Focus ----------------------------------------------------------------------- - -void View::InitFocusSiblings(View* v, int index) { - int count = child_count(); - - if (count == 0) { - v->next_focusable_view_ = NULL; - v->previous_focusable_view_ = NULL; - } else { - if (index == count) { - // We are inserting at the end, but the end of the child list may not be - // the last focusable element. Let's try to find an element with no next - // focusable element to link to. - View* last_focusable_view = NULL; - for (Views::iterator i(children_.begin()); i != children_.end(); ++i) { - if (!(*i)->next_focusable_view_) { - last_focusable_view = *i; - break; - } - } - if (last_focusable_view == NULL) { - // Hum... there is a cycle in the focus list. Let's just insert ourself - // after the last child. - View* prev = children_[index - 1]; - v->previous_focusable_view_ = prev; - v->next_focusable_view_ = prev->next_focusable_view_; - prev->next_focusable_view_->previous_focusable_view_ = v; - prev->next_focusable_view_ = v; - } else { - last_focusable_view->next_focusable_view_ = v; - v->next_focusable_view_ = NULL; - v->previous_focusable_view_ = last_focusable_view; - } - } else { - View* prev = children_[index]->GetPreviousFocusableView(); - v->previous_focusable_view_ = prev; - v->next_focusable_view_ = children_[index]; - if (prev) - prev->next_focusable_view_ = v; - children_[index]->previous_focusable_view_ = v; - } - } -} - -void View::AdvanceFocusIfNecessary() { - // Focus should only be advanced if this is the focused view and has become - // unfocusable. If the view is still focusable or is not focused, we can - // return early avoiding furthur unnecessary checks. Focusability check is - // performed first as it tends to be faster. - if (IsAccessibilityFocusable() || !HasFocus()) - return; - - FocusManager* focus_manager = GetFocusManager(); - if (focus_manager) - focus_manager->AdvanceFocusIfNecessary(); -} - -// System events --------------------------------------------------------------- - -void View::PropagateThemeChanged() { - for (int i = child_count() - 1; i >= 0; --i) - child_at(i)->PropagateThemeChanged(); - OnThemeChanged(); -} - -void View::PropagateLocaleChanged() { - for (int i = child_count() - 1; i >= 0; --i) - child_at(i)->PropagateLocaleChanged(); - OnLocaleChanged(); -} - -// Tooltips -------------------------------------------------------------------- - -void View::UpdateTooltip() { - Widget* widget = GetWidget(); - // TODO(beng): The TooltipManager NULL check can be removed when we - // consolidate Init() methods and make views_unittests Init() all - // Widgets that it uses. - if (widget && widget->GetTooltipManager()) - widget->GetTooltipManager()->UpdateTooltip(); -} - -// Drag and drop --------------------------------------------------------------- - -bool View::DoDrag(const ui::LocatedEvent& event, - const gfx::Point& press_pt, - ui::DragDropTypes::DragEventSource source) { - int drag_operations = GetDragOperations(press_pt); - if (drag_operations == ui::DragDropTypes::DRAG_NONE) - return false; - - Widget* widget = GetWidget(); - // We should only start a drag from an event, implying we have a widget. - DCHECK(widget); - - // Don't attempt to start a drag while in the process of dragging. This is - // especially important on X where we can get multiple mouse move events when - // we start the drag. - if (widget->dragged_view()) - return false; - - OSExchangeData data; - WriteDragData(press_pt, &data); - - // Message the RootView to do the drag and drop. That way if we're removed - // the RootView can detect it and avoid calling us back. - gfx::Point widget_location(event.location()); - ConvertPointToWidget(this, &widget_location); - widget->RunShellDrag(this, data, widget_location, drag_operations, source); - // WARNING: we may have been deleted. - return true; -} - -} // namespace views
diff --git a/ui/views/view.h b/ui/views/view.h deleted file mode 100644 index ae9513d..0000000 --- a/ui/views/view.h +++ /dev/null
@@ -1,1609 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_VIEW_H_ -#define UI_VIEWS_VIEW_H_ - -#include <algorithm> -#include <map> -#include <set> -#include <string> -#include <vector> - -#include "base/compiler_specific.h" -#include "base/i18n/rtl.h" -#include "base/logging.h" -#include "base/memory/scoped_ptr.h" -#include "build/build_config.h" -#include "ui/accessibility/ax_enums.h" -#include "ui/base/accelerators/accelerator.h" -#include "ui/base/dragdrop/drag_drop_types.h" -#include "ui/base/dragdrop/drop_target_event.h" -#include "ui/base/dragdrop/os_exchange_data.h" -#include "ui/base/ui_base_types.h" -#include "ui/compositor/layer_delegate.h" -#include "ui/compositor/layer_owner.h" -#include "ui/events/event.h" -#include "ui/events/event_target.h" -#include "ui/gfx/geometry/r_tree.h" -#include "ui/gfx/insets.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/gfx/rect.h" -#include "ui/gfx/vector2d.h" -#include "ui/views/cull_set.h" -#include "ui/views/view_targeter.h" -#include "ui/views/views_export.h" - -#if defined(OS_WIN) -#include "base/win/scoped_comptr.h" -#endif - -using ui::OSExchangeData; - -namespace gfx { -class Canvas; -class Insets; -class Path; -class Transform; -} - -namespace ui { -struct AXViewState; -class Compositor; -class Layer; -class NativeTheme; -class TextInputClient; -class Texture; -class ThemeProvider; -} - -namespace views { - -class Background; -class Border; -class ContextMenuController; -class DragController; -class FocusManager; -class FocusTraversable; -class InputMethod; -class LayoutManager; -class NativeViewAccessibility; -class ScrollView; -class Widget; - -namespace internal { -class PreEventDispatchHandler; -class PostEventDispatchHandler; -class RootView; -} - -///////////////////////////////////////////////////////////////////////////// -// -// View class -// -// A View is a rectangle within the views View hierarchy. It is the base -// class for all Views. -// -// A View is a container of other Views (there is no such thing as a Leaf -// View - makes code simpler, reduces type conversion headaches, design -// mistakes etc) -// -// The View contains basic properties for sizing (bounds), layout (flex, -// orientation, etc), painting of children and event dispatch. -// -// The View also uses a simple Box Layout Manager similar to XUL's -// SprocketLayout system. Alternative Layout Managers implementing the -// LayoutManager interface can be used to lay out children if required. -// -// It is up to the subclass to implement Painting and storage of subclass - -// specific properties and functionality. -// -// Unless otherwise documented, views is not thread safe and should only be -// accessed from the main thread. -// -///////////////////////////////////////////////////////////////////////////// -class VIEWS_EXPORT View : public ui::LayerDelegate, - public ui::LayerOwner, - public ui::AcceleratorTarget, - public ui::EventTarget { - public: - typedef std::vector<View*> Views; - - struct ViewHierarchyChangedDetails { - ViewHierarchyChangedDetails() - : is_add(false), - parent(NULL), - child(NULL), - move_view(NULL) {} - - ViewHierarchyChangedDetails(bool is_add, - View* parent, - View* child, - View* move_view) - : is_add(is_add), - parent(parent), - child(child), - move_view(move_view) {} - - bool is_add; - // New parent if |is_add| is true, old parent if |is_add| is false. - View* parent; - // The view being added or removed. - View* child; - // If this is a move (reparent), meaning AddChildViewAt() is invoked with an - // existing parent, then a notification for the remove is sent first, - // followed by one for the add. This case can be distinguished by a - // non-NULL |move_view|. - // For the remove part of move, |move_view| is the new parent of the View - // being removed. - // For the add part of move, |move_view| is the old parent of the View being - // added. - View* move_view; - }; - - // Creation and lifetime ----------------------------------------------------- - - View(); - ~View() override; - - // By default a View is owned by its parent unless specified otherwise here. - void set_owned_by_client() { owned_by_client_ = true; } - - // Tree operations ----------------------------------------------------------- - - // Get the Widget that hosts this View, if any. - virtual const Widget* GetWidget() const; - virtual Widget* GetWidget(); - - // Adds |view| as a child of this view, optionally at |index|. - void AddChildView(View* view); - void AddChildViewAt(View* view, int index); - - // Moves |view| to the specified |index|. A negative value for |index| moves - // the view at the end. - void ReorderChildView(View* view, int index); - - // Removes |view| from this view. The view's parent will change to NULL. - void RemoveChildView(View* view); - - // Removes all the children from this view. If |delete_children| is true, - // the views are deleted, unless marked as not parent owned. - void RemoveAllChildViews(bool delete_children); - - int child_count() const { return static_cast<int>(children_.size()); } - bool has_children() const { return !children_.empty(); } - - // Returns the child view at |index|. - const View* child_at(int index) const { - DCHECK_GE(index, 0); - DCHECK_LT(index, child_count()); - return children_[index]; - } - View* child_at(int index) { - return const_cast<View*>(const_cast<const View*>(this)->child_at(index)); - } - - // Returns the parent view. - const View* parent() const { return parent_; } - View* parent() { return parent_; } - - // Returns true if |view| is contained within this View's hierarchy, even as - // an indirect descendant. Will return true if child is also this view. - bool Contains(const View* view) const; - - // Returns the index of |view|, or -1 if |view| is not a child of this view. - int GetIndexOf(const View* view) const; - - // Size and disposition ------------------------------------------------------ - // Methods for obtaining and modifying the position and size of the view. - // Position is in the coordinate system of the view's parent. - // Position is NOT flipped for RTL. See "RTL positioning" for RTL-sensitive - // position accessors. - // Transformations are not applied on the size/position. For example, if - // bounds is (0, 0, 100, 100) and it is scaled by 0.5 along the X axis, the - // width will still be 100 (although when painted, it will be 50x50, painted - // at location (0, 0)). - - void SetBounds(int x, int y, int width, int height); - void SetBoundsRect(const gfx::Rect& bounds); - void SetSize(const gfx::Size& size); - void SetPosition(const gfx::Point& position); - void SetX(int x); - void SetY(int y); - - // No transformation is applied on the size or the locations. - const gfx::Rect& bounds() const { return bounds_; } - int x() const { return bounds_.x(); } - int y() const { return bounds_.y(); } - int width() const { return bounds_.width(); } - int height() const { return bounds_.height(); } - const gfx::Size& size() const { return bounds_.size(); } - - // Returns the bounds of the content area of the view, i.e. the rectangle - // enclosed by the view's border. - gfx::Rect GetContentsBounds() const; - - // Returns the bounds of the view in its own coordinates (i.e. position is - // 0, 0). - gfx::Rect GetLocalBounds() const; - - // Returns the bounds of the layer in its own pixel coordinates. - gfx::Rect GetLayerBoundsInPixel() const; - - // Returns the insets of the current border. If there is no border an empty - // insets is returned. - virtual gfx::Insets GetInsets() const; - - // Returns the visible bounds of the receiver in the receivers coordinate - // system. - // - // When traversing the View hierarchy in order to compute the bounds, the - // function takes into account the mirroring setting and transformation for - // each View and therefore it will return the mirrored and transformed version - // of the visible bounds if need be. - gfx::Rect GetVisibleBounds() const; - - // Return the bounds of the View in screen coordinate system. - gfx::Rect GetBoundsInScreen() const; - - // Returns the baseline of this view, or -1 if this view has no baseline. The - // return value is relative to the preferred height. - virtual int GetBaseline() const; - - // Get the size the View would like to be, if enough space were available. - virtual gfx::Size GetPreferredSize() const; - - // Convenience method that sizes this view to its preferred size. - void SizeToPreferredSize(); - - // Gets the minimum size of the view. View's implementation invokes - // GetPreferredSize. - virtual gfx::Size GetMinimumSize() const; - - // Gets the maximum size of the view. Currently only used for sizing shell - // windows. - virtual gfx::Size GetMaximumSize() const; - - // Return the height necessary to display this view with the provided width. - // View's implementation returns the value from getPreferredSize.cy. - // Override if your View's preferred height depends upon the width (such - // as with Labels). - virtual int GetHeightForWidth(int w) const; - - // Sets whether this view is visible. Painting is scheduled as needed. Also, - // clears focus if the focused view or one of its ancestors is set to be - // hidden. - virtual void SetVisible(bool visible); - - // Return whether a view is visible - bool visible() const { return visible_; } - - // Returns true if this view is drawn on screen. - virtual bool IsDrawn() const; - - // Set whether this view is enabled. A disabled view does not receive keyboard - // or mouse inputs. If |enabled| differs from the current value, SchedulePaint - // is invoked. Also, clears focus if the focused view is disabled. - void SetEnabled(bool enabled); - - // Returns whether the view is enabled. - bool enabled() const { return enabled_; } - - // This indicates that the view completely fills its bounds in an opaque - // color. This doesn't affect compositing but is a hint to the compositor to - // optimize painting. - // Note that this method does not implicitly create a layer if one does not - // already exist for the View, but is a no-op in that case. - void SetFillsBoundsOpaquely(bool fills_bounds_opaquely); - - // Transformations ----------------------------------------------------------- - - // Methods for setting transformations for a view (e.g. rotation, scaling). - - gfx::Transform GetTransform() const; - - // Clipping parameters. Clipping is done relative to the view bounds. - void set_clip_insets(gfx::Insets clip_insets) { clip_insets_ = clip_insets; } - - // Sets the transform to the supplied transform. - void SetTransform(const gfx::Transform& transform); - - // Sets whether this view paints to a layer. A view paints to a layer if - // either of the following are true: - // . the view has a non-identity transform. - // . SetPaintToLayer(true) has been invoked. - // View creates the Layer only when it exists in a Widget with a non-NULL - // Compositor. - void SetPaintToLayer(bool paint_to_layer); - - // RTL positioning ----------------------------------------------------------- - - // Methods for accessing the bounds and position of the view, relative to its - // parent. The position returned is mirrored if the parent view is using a RTL - // layout. - // - // NOTE: in the vast majority of the cases, the mirroring implementation is - // transparent to the View subclasses and therefore you should use the - // bounds() accessor instead. - gfx::Rect GetMirroredBounds() const; - gfx::Point GetMirroredPosition() const; - int GetMirroredX() const; - - // Given a rectangle specified in this View's coordinate system, the function - // computes the 'left' value for the mirrored rectangle within this View. If - // the View's UI layout is not right-to-left, then bounds.x() is returned. - // - // UI mirroring is transparent to most View subclasses and therefore there is - // no need to call this routine from anywhere within your subclass - // implementation. - int GetMirroredXForRect(const gfx::Rect& rect) const; - - // Given the X coordinate of a point inside the View, this function returns - // the mirrored X coordinate of the point if the View's UI layout is - // right-to-left. If the layout is left-to-right, the same X coordinate is - // returned. - // - // Following are a few examples of the values returned by this function for - // a View with the bounds {0, 0, 100, 100} and a right-to-left layout: - // - // GetMirroredXCoordinateInView(0) -> 100 - // GetMirroredXCoordinateInView(20) -> 80 - // GetMirroredXCoordinateInView(99) -> 1 - int GetMirroredXInView(int x) const; - - // Given a X coordinate and a width inside the View, this function returns - // the mirrored X coordinate if the View's UI layout is right-to-left. If the - // layout is left-to-right, the same X coordinate is returned. - // - // Following are a few examples of the values returned by this function for - // a View with the bounds {0, 0, 100, 100} and a right-to-left layout: - // - // GetMirroredXCoordinateInView(0, 10) -> 90 - // GetMirroredXCoordinateInView(20, 20) -> 60 - int GetMirroredXWithWidthInView(int x, int w) const; - - // Layout -------------------------------------------------------------------- - - // Lay out the child Views (set their bounds based on sizing heuristics - // specific to the current Layout Manager) - virtual void Layout(); - - // TODO(beng): I think we should remove this. - // Mark this view and all parents to require a relayout. This ensures the - // next call to Layout() will propagate to this view, even if the bounds of - // parent views do not change. - void InvalidateLayout(); - - // Gets/Sets the Layout Manager used by this view to size and place its - // children. - // The LayoutManager is owned by the View and is deleted when the view is - // deleted, or when a new LayoutManager is installed. - LayoutManager* GetLayoutManager() const; - void SetLayoutManager(LayoutManager* layout); - - // Adjust the layer's offset so that it snaps to the physical pixel boundary. - // This has no effect if the view does not have an associated layer. - void SnapLayerToPixelBoundary(); - - // Attributes ---------------------------------------------------------------- - - // The view class name. - static const char kViewClassName[]; - - // Return the receiving view's class name. A view class is a string which - // uniquely identifies the view class. It is intended to be used as a way to - // find out during run time if a view can be safely casted to a specific view - // subclass. The default implementation returns kViewClassName. - virtual const char* GetClassName() const; - - // Returns the first ancestor, starting at this, whose class name is |name|. - // Returns null if no ancestor has the class name |name|. - const View* GetAncestorWithClassName(const std::string& name) const; - View* GetAncestorWithClassName(const std::string& name); - - // Recursively descends the view tree starting at this view, and returns - // the first child that it encounters that has the given ID. - // Returns NULL if no matching child view is found. - virtual const View* GetViewByID(int id) const; - virtual View* GetViewByID(int id); - - // Gets and sets the ID for this view. ID should be unique within the subtree - // that you intend to search for it. 0 is the default ID for views. - int id() const { return id_; } - void set_id(int id) { id_ = id; } - - // A group id is used to tag views which are part of the same logical group. - // Focus can be moved between views with the same group using the arrow keys. - // Groups are currently used to implement radio button mutual exclusion. - // The group id is immutable once it's set. - void SetGroup(int gid); - // Returns the group id of the view, or -1 if the id is not set yet. - int GetGroup() const; - - // If this returns true, the views from the same group can each be focused - // when moving focus with the Tab/Shift-Tab key. If this returns false, - // only the selected view from the group (obtained with - // GetSelectedViewForGroup()) is focused. - virtual bool IsGroupFocusTraversable() const; - - // Fills |views| with all the available views which belong to the provided - // |group|. - void GetViewsInGroup(int group, Views* views); - - // Returns the View that is currently selected in |group|. - // The default implementation simply returns the first View found for that - // group. - virtual View* GetSelectedViewForGroup(int group); - - // Coordinate conversion ----------------------------------------------------- - - // Note that the utility coordinate conversions functions always operate on - // the mirrored position of the child Views if the parent View uses a - // right-to-left UI layout. - - // Convert a point from the coordinate system of one View to another. - // - // |source| and |target| must be in the same widget, but doesn't need to be in - // the same view hierarchy. - // Neither |source| nor |target| can be NULL. - static void ConvertPointToTarget(const View* source, - const View* target, - gfx::Point* point); - - // Convert |rect| from the coordinate system of |source| to the coordinate - // system of |target|. - // - // |source| and |target| must be in the same widget, but doesn't need to be in - // the same view hierarchy. - // Neither |source| nor |target| can be NULL. - static void ConvertRectToTarget(const View* source, - const View* target, - gfx::RectF* rect); - - // Convert a point from a View's coordinate system to that of its Widget. - static void ConvertPointToWidget(const View* src, gfx::Point* point); - - // Convert a point from the coordinate system of a View's Widget to that - // View's coordinate system. - static void ConvertPointFromWidget(const View* dest, gfx::Point* p); - - // Convert a point from a View's coordinate system to that of the screen. - static void ConvertPointToScreen(const View* src, gfx::Point* point); - - // Convert a point from a View's coordinate system to that of the screen. - static void ConvertPointFromScreen(const View* dst, gfx::Point* point); - - // Applies transformation on the rectangle, which is in the view's coordinate - // system, to convert it into the parent's coordinate system. - gfx::Rect ConvertRectToParent(const gfx::Rect& rect) const; - - // Converts a rectangle from this views coordinate system to its widget - // coordinate system. - gfx::Rect ConvertRectToWidget(const gfx::Rect& rect) const; - - // Painting ------------------------------------------------------------------ - - // Mark all or part of the View's bounds as dirty (needing repaint). - // |r| is in the View's coordinates. - // Rectangle |r| should be in the view's coordinate system. The - // transformations are applied to it to convert it into the parent coordinate - // system before propagating SchedulePaint up the view hierarchy. - // TODO(beng): Make protected. - virtual void SchedulePaint(); - virtual void SchedulePaintInRect(const gfx::Rect& r); - - // Called by the framework to paint a View. Performs translation and clipping - // for View coordinates and language direction as required, allows the View - // to paint itself via the various OnPaint*() event handlers and then paints - // the hierarchy beneath it. - virtual void Paint(gfx::Canvas* canvas, const CullSet& cull_set); - - // The background object is owned by this object and may be NULL. - void set_background(Background* b); - const Background* background() const { return background_.get(); } - Background* background() { return background_.get(); } - - // The border object is owned by this object and may be NULL. - virtual void SetBorder(scoped_ptr<Border> b); - const Border* border() const { return border_.get(); } - Border* border() { return border_.get(); } - - // Get the theme provider from the parent widget. - ui::ThemeProvider* GetThemeProvider() const; - - // Returns the NativeTheme to use for this View. This calls through to - // GetNativeTheme() on the Widget this View is in. If this View is not in a - // Widget this returns ui::NativeTheme::instance(). - ui::NativeTheme* GetNativeTheme() { - return const_cast<ui::NativeTheme*>( - const_cast<const View*>(this)->GetNativeTheme()); - } - const ui::NativeTheme* GetNativeTheme() const; - - // RTL painting -------------------------------------------------------------- - - // This method determines whether the gfx::Canvas object passed to - // View::Paint() needs to be transformed such that anything drawn on the - // canvas object during View::Paint() is flipped horizontally. - // - // By default, this function returns false (which is the initial value of - // |flip_canvas_on_paint_for_rtl_ui_|). View subclasses that need to paint on - // a flipped gfx::Canvas when the UI layout is right-to-left need to call - // EnableCanvasFlippingForRTLUI(). - bool FlipCanvasOnPaintForRTLUI() const { - return flip_canvas_on_paint_for_rtl_ui_ ? base::i18n::IsRTL() : false; - } - - // Enables or disables flipping of the gfx::Canvas during View::Paint(). - // Note that if canvas flipping is enabled, the canvas will be flipped only - // if the UI layout is right-to-left; that is, the canvas will be flipped - // only if base::i18n::IsRTL() returns true. - // - // Enabling canvas flipping is useful for leaf views that draw an image that - // needs to be flipped horizontally when the UI layout is right-to-left - // (views::Button, for example). This method is helpful for such classes - // because their drawing logic stays the same and they can become agnostic to - // the UI directionality. - void EnableCanvasFlippingForRTLUI(bool enable) { - flip_canvas_on_paint_for_rtl_ui_ = enable; - } - - // Input --------------------------------------------------------------------- - // The points, rects, mouse locations, and touch locations in the following - // functions are in the view's coordinates, except for a RootView. - - // A convenience function which calls into GetEventHandlerForRect() with - // a 1x1 rect centered at |point|. |point| is in the local coordinate - // space of |this|. - View* GetEventHandlerForPoint(const gfx::Point& point); - - // Returns the View that should be the target of an event having |rect| as - // its location, or NULL if no such target exists. |rect| is in the local - // coordinate space of |this|. - View* GetEventHandlerForRect(const gfx::Rect& rect); - - // Returns the deepest visible descendant that contains the specified point - // and supports tooltips. If the view does not contain the point, returns - // NULL. - virtual View* GetTooltipHandlerForPoint(const gfx::Point& point); - - // Return the cursor that should be used for this view or the default cursor. - // The event location is in the receiver's coordinate system. The caller is - // responsible for managing the lifetime of the returned object, though that - // lifetime may vary from platform to platform. On Windows and Aura, - // the cursor is a shared resource. - virtual gfx::NativeCursor GetCursor(const ui::MouseEvent& event); - - // A convenience function which calls HitTestRect() with a rect of size - // 1x1 and an origin of |point|. |point| is in the local coordinate space - // of |this|. - bool HitTestPoint(const gfx::Point& point) const; - - // Returns true if |rect| intersects this view's bounds. |rect| is in the - // local coordinate space of |this|. - bool HitTestRect(const gfx::Rect& rect) const; - - // Returns true if this view or any of its descendants are permitted to - // be the target of an event. - virtual bool CanProcessEventsWithinSubtree() const; - - // Returns true if the mouse cursor is over |view| and mouse events are - // enabled. - bool IsMouseHovered(); - - // This method is invoked when the user clicks on this view. - // The provided event is in the receiver's coordinate system. - // - // Return true if you processed the event and want to receive subsequent - // MouseDraggged and MouseReleased events. This also stops the event from - // bubbling. If you return false, the event will bubble through parent - // views. - // - // If you remove yourself from the tree while processing this, event bubbling - // stops as if you returned true, but you will not receive future events. - // The return value is ignored in this case. - // - // Default implementation returns true if a ContextMenuController has been - // set, false otherwise. Override as needed. - // - virtual bool OnMousePressed(const ui::MouseEvent& event); - - // This method is invoked when the user clicked on this control. - // and is still moving the mouse with a button pressed. - // The provided event is in the receiver's coordinate system. - // - // Return true if you processed the event and want to receive - // subsequent MouseDragged and MouseReleased events. - // - // Default implementation returns true if a ContextMenuController has been - // set, false otherwise. Override as needed. - // - virtual bool OnMouseDragged(const ui::MouseEvent& event); - - // This method is invoked when the user releases the mouse - // button. The event is in the receiver's coordinate system. - // - // Default implementation notifies the ContextMenuController is appropriate. - // Subclasses that wish to honor the ContextMenuController should invoke - // super. - virtual void OnMouseReleased(const ui::MouseEvent& event); - - // This method is invoked when the mouse press/drag was canceled by a - // system/user gesture. - virtual void OnMouseCaptureLost(); - - // This method is invoked when the mouse is above this control - // The event is in the receiver's coordinate system. - // - // Default implementation does nothing. Override as needed. - virtual void OnMouseMoved(const ui::MouseEvent& event); - - // This method is invoked when the mouse enters this control. - // - // Default implementation does nothing. Override as needed. - virtual void OnMouseEntered(const ui::MouseEvent& event); - - // This method is invoked when the mouse exits this control - // The provided event location is always (0, 0) - // Default implementation does nothing. Override as needed. - virtual void OnMouseExited(const ui::MouseEvent& event); - - // Set the MouseHandler for a drag session. - // - // A drag session is a stream of mouse events starting - // with a MousePressed event, followed by several MouseDragged - // events and finishing with a MouseReleased event. - // - // This method should be only invoked while processing a - // MouseDragged or MousePressed event. - // - // All further mouse dragged and mouse up events will be sent - // the MouseHandler, even if it is reparented to another window. - // - // The MouseHandler is automatically cleared when the control - // comes back from processing the MouseReleased event. - // - // Note: if the mouse handler is no longer connected to a - // view hierarchy, events won't be sent. - // - // TODO(sky): rename this. - virtual void SetMouseHandler(View* new_mouse_handler); - - // Invoked when a key is pressed or released. - // Subclasser should return true if the event has been processed and false - // otherwise. If the event has not been processed, the parent will be given a - // chance. - virtual bool OnKeyPressed(const ui::KeyEvent& event); - virtual bool OnKeyReleased(const ui::KeyEvent& event); - - // Invoked when the user uses the mousewheel. Implementors should return true - // if the event has been processed and false otherwise. This message is sent - // if the view is focused. If the event has not been processed, the parent - // will be given a chance. - virtual bool OnMouseWheel(const ui::MouseWheelEvent& event); - - - // See field for description. - void set_notify_enter_exit_on_child(bool notify) { - notify_enter_exit_on_child_ = notify; - } - bool notify_enter_exit_on_child() const { - return notify_enter_exit_on_child_; - } - - // Returns the View's TextInputClient instance or NULL if the View doesn't - // support text input. - virtual ui::TextInputClient* GetTextInputClient(); - - // Convenience method to retrieve the InputMethod associated with the - // Widget that contains this view. Returns NULL if this view is not part of a - // view hierarchy with a Widget. - virtual InputMethod* GetInputMethod(); - virtual const InputMethod* GetInputMethod() const; - - // Sets a new ViewTargeter for the view, and returns the previous - // ViewTargeter. - scoped_ptr<ViewTargeter> SetEventTargeter(scoped_ptr<ViewTargeter> targeter); - - // Returns the ViewTargeter installed on |this| if one exists, - // otherwise returns the ViewTargeter installed on our root view. - // The return value is guaranteed to be non-null. - ViewTargeter* GetEffectiveViewTargeter() const; - - ViewTargeter* targeter() const { return targeter_.get(); } - - // Overridden from ui::EventTarget: - bool CanAcceptEvent(const ui::Event& event) override; - ui::EventTarget* GetParentTarget() override; - scoped_ptr<ui::EventTargetIterator> GetChildIterator() override; - ui::EventTargeter* GetEventTargeter() override; - void ConvertEventToTarget(ui::EventTarget* target, - ui::LocatedEvent* event) override; - - // Overridden from ui::EventHandler: - void OnKeyEvent(ui::KeyEvent* event) override; - void OnMouseEvent(ui::MouseEvent* event) override; - void OnScrollEvent(ui::ScrollEvent* event) override; - void OnTouchEvent(ui::TouchEvent* event) final; - void OnGestureEvent(ui::GestureEvent* event) override; - - // Accelerators -------------------------------------------------------------- - - // Sets a keyboard accelerator for that view. When the user presses the - // accelerator key combination, the AcceleratorPressed method is invoked. - // Note that you can set multiple accelerators for a view by invoking this - // method several times. Note also that AcceleratorPressed is invoked only - // when CanHandleAccelerators() is true. - virtual void AddAccelerator(const ui::Accelerator& accelerator); - - // Removes the specified accelerator for this view. - virtual void RemoveAccelerator(const ui::Accelerator& accelerator); - - // Removes all the keyboard accelerators for this view. - virtual void ResetAccelerators(); - - // Overridden from AcceleratorTarget: - bool AcceleratorPressed(const ui::Accelerator& accelerator) override; - - // Returns whether accelerators are enabled for this view. Accelerators are - // enabled if the containing widget is visible and the view is enabled() and - // IsDrawn() - bool CanHandleAccelerators() const override; - - // Focus --------------------------------------------------------------------- - - // Returns whether this view currently has the focus. - virtual bool HasFocus() const; - - // Returns the view that should be selected next when pressing Tab. - View* GetNextFocusableView(); - const View* GetNextFocusableView() const; - - // Returns the view that should be selected next when pressing Shift-Tab. - View* GetPreviousFocusableView(); - - // Sets the component that should be selected next when pressing Tab, and - // makes the current view the precedent view of the specified one. - // Note that by default views are linked in the order they have been added to - // their container. Use this method if you want to modify the order. - // IMPORTANT NOTE: loops in the focus hierarchy are not supported. - void SetNextFocusableView(View* view); - - // Sets whether this view is capable of taking focus. It will clear focus if - // the focused view is set to be non-focusable. - // Note that this is false by default so that a view used as a container does - // not get the focus. - void SetFocusable(bool focusable); - - // Returns true if this view is |focusable_|, |enabled_| and drawn. - bool IsFocusable() const; - - // Return whether this view is focusable when the user requires full keyboard - // access, even though it may not be normally focusable. - bool IsAccessibilityFocusable() const; - - // Set whether this view can be made focusable if the user requires - // full keyboard access, even though it's not normally focusable. It will - // clear focus if the focused view is set to be non-focusable. - // Note that this is false by default. - void SetAccessibilityFocusable(bool accessibility_focusable); - - // Convenience method to retrieve the FocusManager associated with the - // Widget that contains this view. This can return NULL if this view is not - // part of a view hierarchy with a Widget. - virtual FocusManager* GetFocusManager(); - virtual const FocusManager* GetFocusManager() const; - - // Request keyboard focus. The receiving view will become the focused view. - virtual void RequestFocus(); - - // Invoked when a view is about to be requested for focus due to the focus - // traversal. Reverse is this request was generated going backward - // (Shift-Tab). - virtual void AboutToRequestFocusFromTabTraversal(bool reverse) {} - - // Invoked when a key is pressed before the key event is processed (and - // potentially eaten) by the focus manager for tab traversal, accelerators and - // other focus related actions. - // The default implementation returns false, ensuring that tab traversal and - // accelerators processing is performed. - // Subclasses should return true if they want to process the key event and not - // have it processed as an accelerator (if any) or as a tab traversal (if the - // key event is for the TAB key). In that case, OnKeyPressed will - // subsequently be invoked for that event. - virtual bool SkipDefaultKeyEventProcessing(const ui::KeyEvent& event); - - // Subclasses that contain traversable children that are not directly - // accessible through the children hierarchy should return the associated - // FocusTraversable for the focus traversal to work properly. - virtual FocusTraversable* GetFocusTraversable(); - - // Subclasses that can act as a "pane" must implement their own - // FocusTraversable to keep the focus trapped within the pane. - // If this method returns an object, any view that's a direct or - // indirect child of this view will always use this FocusTraversable - // rather than the one from the widget. - virtual FocusTraversable* GetPaneFocusTraversable(); - - // Tooltips ------------------------------------------------------------------ - - // Gets the tooltip for this View. If the View does not have a tooltip, - // return false. If the View does have a tooltip, copy the tooltip into - // the supplied string and return true. - // Any time the tooltip text that a View is displaying changes, it must - // invoke TooltipTextChanged. - // |p| provides the coordinates of the mouse (relative to this view). - virtual bool GetTooltipText(const gfx::Point& p, - base::string16* tooltip) const; - - // Returns the location (relative to this View) for the text on the tooltip - // to display. If false is returned (the default), the tooltip is placed at - // a default position. - virtual bool GetTooltipTextOrigin(const gfx::Point& p, gfx::Point* loc) const; - - // Context menus ------------------------------------------------------------- - - // Sets the ContextMenuController. Setting this to non-null makes the View - // process mouse events. - ContextMenuController* context_menu_controller() { - return context_menu_controller_; - } - void set_context_menu_controller(ContextMenuController* menu_controller) { - context_menu_controller_ = menu_controller; - } - - // Provides default implementation for context menu handling. The default - // implementation calls the ShowContextMenu of the current - // ContextMenuController (if it is not NULL). Overridden in subclassed views - // to provide right-click menu display triggerd by the keyboard (i.e. for the - // Chrome toolbar Back and Forward buttons). No source needs to be specified, - // as it is always equal to the current View. - virtual void ShowContextMenu(const gfx::Point& p, - ui::MenuSourceType source_type); - - // On some platforms, we show context menu on mouse press instead of release. - // This method returns true for those platforms. - static bool ShouldShowContextMenuOnMousePress(); - - // Drag and drop ------------------------------------------------------------- - - DragController* drag_controller() { return drag_controller_; } - void set_drag_controller(DragController* drag_controller) { - drag_controller_ = drag_controller; - } - - // During a drag and drop session when the mouse moves the view under the - // mouse is queried for the drop types it supports by way of the - // GetDropFormats methods. If the view returns true and the drag site can - // provide data in one of the formats, the view is asked if the drop data - // is required before any other drop events are sent. Once the - // data is available the view is asked if it supports the drop (by way of - // the CanDrop method). If a view returns true from CanDrop, - // OnDragEntered is sent to the view when the mouse first enters the view, - // as the mouse moves around within the view OnDragUpdated is invoked. - // If the user releases the mouse over the view and OnDragUpdated returns a - // valid drop, then OnPerformDrop is invoked. If the mouse moves outside the - // view or over another view that wants the drag, OnDragExited is invoked. - // - // Similar to mouse events, the deepest view under the mouse is first checked - // if it supports the drop (Drop). If the deepest view under - // the mouse does not support the drop, the ancestors are walked until one - // is found that supports the drop. - - // Override and return the set of formats that can be dropped on this view. - // |formats| is a bitmask of the formats defined bye OSExchangeData::Format. - // The default implementation returns false, which means the view doesn't - // support dropping. - virtual bool GetDropFormats( - int* formats, - std::set<OSExchangeData::CustomFormat>* custom_formats); - - // Override and return true if the data must be available before any drop - // methods should be invoked. The default is false. - virtual bool AreDropTypesRequired(); - - // A view that supports drag and drop must override this and return true if - // data contains a type that may be dropped on this view. - virtual bool CanDrop(const OSExchangeData& data); - - // OnDragEntered is invoked when the mouse enters this view during a drag and - // drop session and CanDrop returns true. This is immediately - // followed by an invocation of OnDragUpdated, and eventually one of - // OnDragExited or OnPerformDrop. - virtual void OnDragEntered(const ui::DropTargetEvent& event); - - // Invoked during a drag and drop session while the mouse is over the view. - // This should return a bitmask of the DragDropTypes::DragOperation supported - // based on the location of the event. Return 0 to indicate the drop should - // not be accepted. - virtual int OnDragUpdated(const ui::DropTargetEvent& event); - - // Invoked during a drag and drop session when the mouse exits the views, or - // when the drag session was canceled and the mouse was over the view. - virtual void OnDragExited(); - - // Invoked during a drag and drop session when OnDragUpdated returns a valid - // operation and the user release the mouse. - virtual int OnPerformDrop(const ui::DropTargetEvent& event); - - // Invoked from DoDrag after the drag completes. This implementation does - // nothing, and is intended for subclasses to do cleanup. - virtual void OnDragDone(); - - // Returns true if the mouse was dragged enough to start a drag operation. - // delta_x and y are the distance the mouse was dragged. - static bool ExceededDragThreshold(const gfx::Vector2d& delta); - - // Accessibility ------------------------------------------------------------- - - // Modifies |state| to reflect the current accessible state of this view. - virtual void GetAccessibleState(ui::AXViewState* state) { } - - // Returns an instance of the native accessibility interface for this view. - virtual gfx::NativeViewAccessible GetNativeViewAccessible(); - - // Notifies assistive technology that an accessibility event has - // occurred on this view, such as when the view is focused or when its - // value changes. Pass true for |send_native_event| except for rare - // cases where the view is a native control that's already sending a - // native accessibility event and the duplicate event would cause - // problems. - void NotifyAccessibilityEvent(ui::AXEvent event_type, - bool send_native_event); - - // Scrolling ----------------------------------------------------------------- - // TODO(beng): Figure out if this can live somewhere other than View, i.e. - // closer to ScrollView. - - // Scrolls the specified region, in this View's coordinate system, to be - // visible. View's implementation passes the call onto the parent View (after - // adjusting the coordinates). It is up to views that only show a portion of - // the child view, such as Viewport, to override appropriately. - virtual void ScrollRectToVisible(const gfx::Rect& rect); - - // The following methods are used by ScrollView to determine the amount - // to scroll relative to the visible bounds of the view. For example, a - // return value of 10 indicates the scrollview should scroll 10 pixels in - // the appropriate direction. - // - // Each method takes the following parameters: - // - // is_horizontal: if true, scrolling is along the horizontal axis, otherwise - // the vertical axis. - // is_positive: if true, scrolling is by a positive amount. Along the - // vertical axis scrolling by a positive amount equates to - // scrolling down. - // - // The return value should always be positive and gives the number of pixels - // to scroll. ScrollView interprets a return value of 0 (or negative) - // to scroll by a default amount. - // - // See VariableRowHeightScrollHelper and FixedRowHeightScrollHelper for - // implementations of common cases. - virtual int GetPageScrollIncrement(ScrollView* scroll_view, - bool is_horizontal, bool is_positive); - virtual int GetLineScrollIncrement(ScrollView* scroll_view, - bool is_horizontal, bool is_positive); - - protected: - // Used to track a drag. RootView passes this into - // ProcessMousePressed/Dragged. - struct DragInfo { - // Sets possible_drag to false and start_x/y to 0. This is invoked by - // RootView prior to invoke ProcessMousePressed. - void Reset(); - - // Sets possible_drag to true and start_pt to the specified point. - // This is invoked by the target view if it detects the press may generate - // a drag. - void PossibleDrag(const gfx::Point& p); - - // Whether the press may generate a drag. - bool possible_drag; - - // Coordinates of the mouse press. - gfx::Point start_pt; - }; - - // Size and disposition ------------------------------------------------------ - - // Override to be notified when the bounds of the view have changed. - virtual void OnBoundsChanged(const gfx::Rect& previous_bounds); - - // Called when the preferred size of a child view changed. This gives the - // parent an opportunity to do a fresh layout if that makes sense. - virtual void ChildPreferredSizeChanged(View* child) {} - - // Called when the visibility of a child view changed. This gives the parent - // an opportunity to do a fresh layout if that makes sense. - virtual void ChildVisibilityChanged(View* child) {} - - // Invalidates the layout and calls ChildPreferredSizeChanged on the parent - // if there is one. Be sure to call View::PreferredSizeChanged when - // overriding such that the layout is properly invalidated. - virtual void PreferredSizeChanged(); - - // Override returning true when the view needs to be notified when its visible - // bounds relative to the root view may have changed. Only used by - // NativeViewHost. - virtual bool GetNeedsNotificationWhenVisibleBoundsChange() const; - - // Notification that this View's visible bounds relative to the root view may - // have changed. The visible bounds are the region of the View not clipped by - // its ancestors. This is used for clipping NativeViewHost. - virtual void OnVisibleBoundsChanged(); - - // Override to be notified when the enabled state of this View has - // changed. The default implementation calls SchedulePaint() on this View. - virtual void OnEnabledChanged(); - - bool needs_layout() const { return needs_layout_; } - - // Tree operations ----------------------------------------------------------- - - // This method is invoked when the tree changes. - // - // When a view is removed, it is invoked for all children and grand - // children. For each of these views, a notification is sent to the - // view and all parents. - // - // When a view is added, a notification is sent to the view, all its - // parents, and all its children (and grand children) - // - // Default implementation does nothing. Override to perform operations - // required when a view is added or removed from a view hierarchy - // - // Refer to comments in struct |ViewHierarchyChangedDetails| for |details|. - virtual void ViewHierarchyChanged(const ViewHierarchyChangedDetails& details); - - // When SetVisible() changes the visibility of a view, this method is - // invoked for that view as well as all the children recursively. - virtual void VisibilityChanged(View* starting_from, bool is_visible); - - // This method is invoked when the parent NativeView of the widget that the - // view is attached to has changed and the view hierarchy has not changed. - // ViewHierarchyChanged() is called when the parent NativeView of the widget - // that the view is attached to is changed as a result of changing the view - // hierarchy. Overriding this method is useful for tracking which - // FocusManager manages this view. - virtual void NativeViewHierarchyChanged(); - - // Painting ------------------------------------------------------------------ - - // Responsible for calling Paint() on child Views. Override to control the - // order child Views are painted. - virtual void PaintChildren(gfx::Canvas* canvas, const CullSet& cull_set); - - // Override to provide rendering in any part of the View's bounds. Typically - // this is the "contents" of the view. If you override this method you will - // have to call the subsequent OnPaint*() methods manually. - virtual void OnPaint(gfx::Canvas* canvas); - - // Override to paint a background before any content is drawn. Typically this - // is done if you are satisfied with a default OnPaint handler but wish to - // supply a different background. - virtual void OnPaintBackground(gfx::Canvas* canvas); - - // Override to paint a border not specified by SetBorder(). - virtual void OnPaintBorder(gfx::Canvas* canvas); - - // Returns true if this View is the root for paint events, and should - // therefore maintain a |bounds_tree_| member and use it for paint damage rect - // calculations. - virtual bool IsPaintRoot(); - - // Accelerated painting ------------------------------------------------------ - - // Returns the offset from this view to the nearest ancestor with a layer. If - // |layer_parent| is non-NULL it is set to the nearest ancestor with a layer. - virtual gfx::Vector2d CalculateOffsetToAncestorWithLayer( - ui::Layer** layer_parent); - - // Updates the view's layer's parent. Called when a view is added to a view - // hierarchy, responsible for parenting the view's layer to the enclosing - // layer in the hierarchy. - virtual void UpdateParentLayer(); - - // If this view has a layer, the layer is reparented to |parent_layer| and its - // bounds is set based on |point|. If this view does not have a layer, then - // recurses through all children. This is used when adding a layer to an - // existing view to make sure all descendants that have layers are parented to - // the right layer. - void MoveLayerToParent(ui::Layer* parent_layer, const gfx::Point& point); - - // Called to update the bounds of any child layers within this View's - // hierarchy when something happens to the hierarchy. - void UpdateChildLayerBounds(const gfx::Vector2d& offset); - - // Overridden from ui::LayerDelegate: - void OnPaintLayer(gfx::Canvas* canvas) override; - void OnDelegatedFrameDamage(const gfx::Rect& damage_rect_in_dip) override; - void OnDeviceScaleFactorChanged(float device_scale_factor) override; - base::Closure PrepareForLayerBoundsChange() override; - - // Finds the layer that this view paints to (it may belong to an ancestor - // view), then reorders the immediate children of that layer to match the - // order of the view tree. - virtual void ReorderLayers(); - - // This reorders the immediate children of |*parent_layer| to match the - // order of the view tree. Child layers which are owned by a view are - // reordered so that they are below any child layers not owned by a view. - // Widget::ReorderNativeViews() should be called to reorder any child layers - // with an associated view. Widget::ReorderNativeViews() may reorder layers - // below layers owned by a view. - virtual void ReorderChildLayers(ui::Layer* parent_layer); - - // Input --------------------------------------------------------------------- - - virtual DragInfo* GetDragInfo(); - - // Focus --------------------------------------------------------------------- - - // Returns last value passed to SetFocusable(). Use IsFocusable() to determine - // if a view can take focus right now. - bool focusable() const { return focusable_; } - - // Override to be notified when focus has changed either to or from this View. - virtual void OnFocus(); - virtual void OnBlur(); - - // Handle view focus/blur events for this view. - void Focus(); - void Blur(); - - // System events ------------------------------------------------------------- - - // Called when the UI theme (not the NativeTheme) has changed, overriding - // allows individual Views to do special cleanup and processing (such as - // dropping resource caches). To dispatch a theme changed notification, call - // Widget::ThemeChanged(). - virtual void OnThemeChanged() {} - - // Called when the locale has changed, overriding allows individual Views to - // update locale-dependent strings. - // To dispatch a locale changed notification, call Widget::LocaleChanged(). - virtual void OnLocaleChanged() {} - - // Tooltips ------------------------------------------------------------------ - - // Views must invoke this when the tooltip text they are to display changes. - void TooltipTextChanged(); - - // Context menus ------------------------------------------------------------- - - // Returns the location, in screen coordinates, to show the context menu at - // when the context menu is shown from the keyboard. This implementation - // returns the middle of the visible region of this view. - // - // This method is invoked when the context menu is shown by way of the - // keyboard. - virtual gfx::Point GetKeyboardContextMenuLocation(); - - // Drag and drop ------------------------------------------------------------- - - // These are cover methods that invoke the method of the same name on - // the DragController. Subclasses may wish to override rather than install - // a DragController. - // See DragController for a description of these methods. - virtual int GetDragOperations(const gfx::Point& press_pt); - virtual void WriteDragData(const gfx::Point& press_pt, OSExchangeData* data); - - // Returns whether we're in the middle of a drag session that was initiated - // by us. - bool InDrag(); - - // Returns how much the mouse needs to move in one direction to start a - // drag. These methods cache in a platform-appropriate way. These values are - // used by the public static method ExceededDragThreshold(). - static int GetHorizontalDragThreshold(); - static int GetVerticalDragThreshold(); - - // NativeTheme --------------------------------------------------------------- - - // Invoked when the NativeTheme associated with this View changes. - virtual void OnNativeThemeChanged(const ui::NativeTheme* theme) {} - - // Debugging ----------------------------------------------------------------- - -#if !defined(NDEBUG) - // Returns string containing a graph of the views hierarchy in graphViz DOT - // language (http://graphviz.org/). Can be called within debugger and save - // to a file to compile/view. - // Note: Assumes initial call made with first = true. - virtual std::string PrintViewGraph(bool first); - - // Some classes may own an object which contains the children to displayed in - // the views hierarchy. The above function gives the class the flexibility to - // decide which object should be used to obtain the children, but this - // function makes the decision explicit. - std::string DoPrintViewGraph(bool first, View* view_with_children); -#endif - - private: - friend class internal::PreEventDispatchHandler; - friend class internal::PostEventDispatchHandler; - friend class internal::RootView; - friend class FocusManager; - friend class Widget; - - typedef gfx::RTree<intptr_t> BoundsTree; - - // Painting ----------------------------------------------------------------- - - enum SchedulePaintType { - // Indicates the size is the same (only the origin changed). - SCHEDULE_PAINT_SIZE_SAME, - - // Indicates the size changed (and possibly the origin). - SCHEDULE_PAINT_SIZE_CHANGED - }; - - // Invoked before and after the bounds change to schedule painting the old and - // new bounds. - void SchedulePaintBoundsChanged(SchedulePaintType type); - - // Common Paint() code shared by accelerated and non-accelerated code paths to - // invoke OnPaint() on the View. - void PaintCommon(gfx::Canvas* canvas, const CullSet& cull_set); - - // Tree operations ----------------------------------------------------------- - - // Removes |view| from the hierarchy tree. If |update_focus_cycle| is true, - // the next and previous focusable views of views pointing to this view are - // updated. If |update_tool_tip| is true, the tooltip is updated. If - // |delete_removed_view| is true, the view is also deleted (if it is parent - // owned). If |new_parent| is not NULL, the remove is the result of - // AddChildView() to a new parent. For this case, |new_parent| is the View - // that |view| is going to be added to after the remove completes. - void DoRemoveChildView(View* view, - bool update_focus_cycle, - bool update_tool_tip, - bool delete_removed_view, - View* new_parent); - - // Call ViewHierarchyChanged() for all child views and all parents. - // |old_parent| is the original parent of the View that was removed. - // If |new_parent| is not NULL, the View that was removed will be reparented - // to |new_parent| after the remove operation. - void PropagateRemoveNotifications(View* old_parent, View* new_parent); - - // Call ViewHierarchyChanged() for all children. - void PropagateAddNotifications(const ViewHierarchyChangedDetails& details); - - // Propagates NativeViewHierarchyChanged() notification through all the - // children. - void PropagateNativeViewHierarchyChanged(); - - // Takes care of registering/unregistering accelerators if - // |register_accelerators| true and calls ViewHierarchyChanged(). - void ViewHierarchyChangedImpl(bool register_accelerators, - const ViewHierarchyChangedDetails& details); - - // Invokes OnNativeThemeChanged() on this and all descendants. - void PropagateNativeThemeChanged(const ui::NativeTheme* theme); - - // Size and disposition ------------------------------------------------------ - - // Call VisibilityChanged() recursively for all children. - void PropagateVisibilityNotifications(View* from, bool is_visible); - - // Registers/unregisters accelerators as necessary and calls - // VisibilityChanged(). - void VisibilityChangedImpl(View* starting_from, bool is_visible); - - // Responsible for propagating bounds change notifications to relevant - // views. - void BoundsChanged(const gfx::Rect& previous_bounds); - - // Visible bounds notification registration. - // When a view is added to a hierarchy, it and all its children are asked if - // they need to be registered for "visible bounds within root" notifications - // (see comment on OnVisibleBoundsChanged()). If they do, they are registered - // with every ancestor between them and the root of the hierarchy. - static void RegisterChildrenForVisibleBoundsNotification(View* view); - static void UnregisterChildrenForVisibleBoundsNotification(View* view); - void RegisterForVisibleBoundsNotification(); - void UnregisterForVisibleBoundsNotification(); - - // Adds/removes view to the list of descendants that are notified any time - // this views location and possibly size are changed. - void AddDescendantToNotify(View* view); - void RemoveDescendantToNotify(View* view); - - // Sets the layer's bounds given in DIP coordinates. - void SetLayerBounds(const gfx::Rect& bounds_in_dip); - - // Sets the bit indicating that the cached bounds for this object within the - // root view bounds tree are no longer valid. If |origin_changed| is true sets - // the same bit for all of our children as well. - void SetRootBoundsDirty(bool origin_changed); - - // If needed, updates the bounds rectangle in paint root coordinate space - // in the supplied RTree. Recurses to children for recomputation as well. - void UpdateRootBounds(BoundsTree* bounds_tree, const gfx::Vector2d& offset); - - // Remove self and all children from the supplied bounds tree. This is used, - // for example, when a view gets a layer and therefore becomes paint root. It - // needs to remove all references to itself and its children from any previous - // paint root that may have been tracking it. - void RemoveRootBounds(BoundsTree* bounds_tree); - - // Traverse up the View hierarchy to the first ancestor that is a paint root - // and return a pointer to its |bounds_tree_| or NULL if no tree is found. - BoundsTree* GetBoundsTreeFromPaintRoot(); - - // Transformations ----------------------------------------------------------- - - // Returns in |transform| the transform to get from coordinates of |ancestor| - // to this. Returns true if |ancestor| is found. If |ancestor| is not found, - // or NULL, |transform| is set to convert from root view coordinates to this. - bool GetTransformRelativeTo(const View* ancestor, - gfx::Transform* transform) const; - - // Coordinate conversion ----------------------------------------------------- - - // Convert a point in the view's coordinate to an ancestor view's coordinate - // system using necessary transformations. Returns whether the point was - // successfully converted to the ancestor's coordinate system. - bool ConvertPointForAncestor(const View* ancestor, gfx::Point* point) const; - - // Convert a point in the ancestor's coordinate system to the view's - // coordinate system using necessary transformations. Returns whether the - // point was successfully converted from the ancestor's coordinate system - // to the view's coordinate system. - bool ConvertPointFromAncestor(const View* ancestor, gfx::Point* point) const; - - // Convert a rect in the view's coordinate to an ancestor view's coordinate - // system using necessary transformations. Returns whether the rect was - // successfully converted to the ancestor's coordinate system. - bool ConvertRectForAncestor(const View* ancestor, gfx::RectF* rect) const; - - // Convert a rect in the ancestor's coordinate system to the view's - // coordinate system using necessary transformations. Returns whether the - // rect was successfully converted from the ancestor's coordinate system - // to the view's coordinate system. - bool ConvertRectFromAncestor(const View* ancestor, gfx::RectF* rect) const; - - // Accelerated painting ------------------------------------------------------ - - // Creates the layer and related fields for this view. - void CreateLayer(); - - // Parents all un-parented layers within this view's hierarchy to this view's - // layer. - void UpdateParentLayers(); - - // Parents this view's layer to |parent_layer|, and sets its bounds and other - // properties in accordance to |offset|, the view's offset from the - // |parent_layer|. - void ReparentLayer(const gfx::Vector2d& offset, ui::Layer* parent_layer); - - // Called to update the layer visibility. The layer will be visible if the - // View itself, and all its parent Views are visible. This also updates - // visibility of the child layers. - void UpdateLayerVisibility(); - void UpdateChildLayerVisibility(bool visible); - - // Orphans the layers in this subtree that are parented to layers outside of - // this subtree. - void OrphanLayers(); - - // Destroys the layer associated with this view, and reparents any descendants - // to the destroyed layer's parent. - void DestroyLayer(); - - // Input --------------------------------------------------------------------- - - bool ProcessMousePressed(const ui::MouseEvent& event); - bool ProcessMouseDragged(const ui::MouseEvent& event); - void ProcessMouseReleased(const ui::MouseEvent& event); - - // Accelerators -------------------------------------------------------------- - - // Registers this view's keyboard accelerators that are not registered to - // FocusManager yet, if possible. - void RegisterPendingAccelerators(); - - // Unregisters all the keyboard accelerators associated with this view. - // |leave_data_intact| if true does not remove data from accelerators_ array, - // so it could be re-registered with other focus manager - void UnregisterAccelerators(bool leave_data_intact); - - // Focus --------------------------------------------------------------------- - - // Initialize the previous/next focusable views of the specified view relative - // to the view at the specified index. - void InitFocusSiblings(View* view, int index); - - // Helper function to advance focus, in case the currently focused view has - // become unfocusable. - void AdvanceFocusIfNecessary(); - - // System events ------------------------------------------------------------- - - // Used to propagate theme changed notifications from the root view to all - // views in the hierarchy. - virtual void PropagateThemeChanged(); - - // Used to propagate locale changed notifications from the root view to all - // views in the hierarchy. - virtual void PropagateLocaleChanged(); - - // Tooltips ------------------------------------------------------------------ - - // Propagates UpdateTooltip() to the TooltipManager for the Widget. - // This must be invoked any time the View hierarchy changes in such a way - // the view under the mouse differs. For example, if the bounds of a View is - // changed, this is invoked. Similarly, as Views are added/removed, this - // is invoked. - void UpdateTooltip(); - - // Drag and drop ------------------------------------------------------------- - - // Starts a drag and drop operation originating from this view. This invokes - // WriteDragData to write the data and GetDragOperations to determine the - // supported drag operations. When done, OnDragDone is invoked. |press_pt| is - // in the view's coordinate system. - // Returns true if a drag was started. - bool DoDrag(const ui::LocatedEvent& event, - const gfx::Point& press_pt, - ui::DragDropTypes::DragEventSource source); - - ////////////////////////////////////////////////////////////////////////////// - - // Creation and lifetime ----------------------------------------------------- - - // False if this View is owned by its parent - i.e. it will be deleted by its - // parent during its parents destruction. False is the default. - bool owned_by_client_; - - // Attributes ---------------------------------------------------------------- - - // The id of this View. Used to find this View. - int id_; - - // The group of this view. Some view subclasses use this id to find other - // views of the same group. For example radio button uses this information - // to find other radio buttons. - int group_; - - // Tree operations ----------------------------------------------------------- - - // This view's parent. - View* parent_; - - // This view's children. - Views children_; - - // Size and disposition ------------------------------------------------------ - - // This View's bounds in the parent coordinate system. - gfx::Rect bounds_; - - // Whether this view is visible. - bool visible_; - - // Whether this view is enabled. - bool enabled_; - - // When this flag is on, a View receives a mouse-enter and mouse-leave event - // even if a descendant View is the event-recipient for the real mouse - // events. When this flag is turned on, and mouse moves from outside of the - // view into a child view, both the child view and this view receives - // mouse-enter event. Similarly, if the mouse moves from inside a child view - // and out of this view, then both views receive a mouse-leave event. - // When this flag is turned off, if the mouse moves from inside this view into - // a child view, then this view receives a mouse-leave event. When this flag - // is turned on, it does not receive the mouse-leave event in this case. - // When the mouse moves from inside the child view out of the child view but - // still into this view, this view receives a mouse-enter event if this flag - // is turned off, but doesn't if this flag is turned on. - // This flag is initialized to false. - bool notify_enter_exit_on_child_; - - // Whether or not RegisterViewForVisibleBoundsNotification on the RootView - // has been invoked. - bool registered_for_visible_bounds_notification_; - - // List of descendants wanting notification when their visible bounds change. - scoped_ptr<Views> descendants_to_notify_; - - // True if the bounds on this object have changed since the last time the - // paint root view constructed the spatial database. - bool root_bounds_dirty_; - - // If this View IsPaintRoot() then this will be a pointer to a spatial data - // structure where we will keep the bounding boxes of all our children, for - // efficient paint damage rectangle intersection. - scoped_ptr<BoundsTree> bounds_tree_; - - // Transformations ----------------------------------------------------------- - - // Clipping parameters. skia transformation matrix does not give us clipping. - // So we do it ourselves. - gfx::Insets clip_insets_; - - // Layout -------------------------------------------------------------------- - - // Whether the view needs to be laid out. - bool needs_layout_; - - // The View's LayoutManager defines the sizing heuristics applied to child - // Views. The default is absolute positioning according to bounds_. - scoped_ptr<LayoutManager> layout_manager_; - - // Whether this View's layer should be snapped to the pixel boundary. - bool snap_layer_to_pixel_boundary_; - - // Painting ------------------------------------------------------------------ - - // Background - scoped_ptr<Background> background_; - - // Border. - scoped_ptr<Border> border_; - - // RTL painting -------------------------------------------------------------- - - // Indicates whether or not the gfx::Canvas object passed to View::Paint() - // is going to be flipped horizontally (using the appropriate transform) on - // right-to-left locales for this View. - bool flip_canvas_on_paint_for_rtl_ui_; - - // Accelerated painting ------------------------------------------------------ - - bool paint_to_layer_; - - // Accelerators -------------------------------------------------------------- - - // Focus manager accelerators registered on. - FocusManager* accelerator_focus_manager_; - - // The list of accelerators. List elements in the range - // [0, registered_accelerator_count_) are already registered to FocusManager, - // and the rest are not yet. - scoped_ptr<std::vector<ui::Accelerator> > accelerators_; - size_t registered_accelerator_count_; - - // Focus --------------------------------------------------------------------- - - // Next view to be focused when the Tab key is pressed. - View* next_focusable_view_; - - // Next view to be focused when the Shift-Tab key combination is pressed. - View* previous_focusable_view_; - - // Whether this view can be focused. - bool focusable_; - - // Whether this view is focusable if the user requires full keyboard access, - // even though it may not be normally focusable. - bool accessibility_focusable_; - - // Context menus ------------------------------------------------------------- - - // The menu controller. - ContextMenuController* context_menu_controller_; - - // Drag and drop ------------------------------------------------------------- - - DragController* drag_controller_; - - // Input -------------------------------------------------------------------- - - scoped_ptr<ViewTargeter> targeter_; - - // Accessibility ------------------------------------------------------------- - - // Belongs to this view, but it's reference-counted on some platforms - // so we can't use a scoped_ptr. It's dereferenced in the destructor. - NativeViewAccessibility* native_view_accessibility_; - - DISALLOW_COPY_AND_ASSIGN(View); -}; - -} // namespace views - -#endif // UI_VIEWS_VIEW_H_
diff --git a/ui/views/view_constants.cc b/ui/views/view_constants.cc deleted file mode 100644 index 63a5a22..0000000 --- a/ui/views/view_constants.cc +++ /dev/null
@@ -1,13 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/view_constants.h" - -namespace views { - -const int kAutoscrollSize = 10; -const int kAutoscrollRowTimerMS = 200; -const int kDropBetweenPixels = 5; - -} // namespace views
diff --git a/ui/views/view_constants.h b/ui/views/view_constants.h deleted file mode 100644 index 2b0171f..0000000 --- a/ui/views/view_constants.h +++ /dev/null
@@ -1,27 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_VIEW_CONSTANTS_H_ -#define UI_VIEWS_VIEW_CONSTANTS_H_ - -#include "ui/views/views_export.h" - -namespace views { - -// Size (width or height) within which the user can hold the mouse and the -// view should scroll. -VIEWS_EXPORT extern const int kAutoscrollSize; - -// Time in milliseconds to autoscroll by a row. This is used during drag and -// drop. -VIEWS_EXPORT extern const int kAutoscrollRowTimerMS; - -// Used to determine whether a drop is on an item or before/after it. If a drop -// occurs kDropBetweenPixels from the top/bottom it is considered before/after -// the item, otherwise it is on the item. -VIEWS_EXPORT extern const int kDropBetweenPixels; - -} // namespace views - -#endif // UI_VIEWS_VIEW_CONSTANTS_H_
diff --git a/ui/views/view_constants_aura.cc b/ui/views/view_constants_aura.cc deleted file mode 100644 index caf964a..0000000 --- a/ui/views/view_constants_aura.cc +++ /dev/null
@@ -1,18 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/view_constants_aura.h" - -#include "ui/aura/window_property.h" -#include "ui/views/view.h" - -DECLARE_EXPORTED_WINDOW_PROPERTY_TYPE(VIEWS_EXPORT, views::View*); - -namespace views { - -DEFINE_WINDOW_PROPERTY_KEY(views::View*, kHostViewKey, NULL); - -DEFINE_WINDOW_PROPERTY_KEY(bool, kDesktopRootWindow, false); - -} // namespace views
diff --git a/ui/views/view_constants_aura.h b/ui/views/view_constants_aura.h deleted file mode 100644 index 1ca2820..0000000 --- a/ui/views/view_constants_aura.h +++ /dev/null
@@ -1,26 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_VIEW_CONSTANTS_AURA_H_ -#define UI_VIEWS_VIEW_CONSTANTS_AURA_H_ - -#include "ui/aura/window.h" -#include "ui/views/views_export.h" - -namespace views { -class View; - -// A property key to indicate the view the window is associated with. If -// specified, the z-order of the view, relative to other views, dictates the -// z-order of the window and its associated layer. The associated view must -// have the same parent widget as the window on which the property is set. -VIEWS_EXPORT extern const aura::WindowProperty<View*>* const kHostViewKey; - -// A property key to indicate if a window is a desktop root window or not. -// This property is currently set during creation of desktop root window. -VIEWS_EXPORT extern const aura::WindowProperty<bool>* const kDesktopRootWindow; - -} // namespace views - -#endif // UI_VIEWS_VIEW_CONSTANTS_AURA_H_
diff --git a/ui/views/view_model.cc b/ui/views/view_model.cc deleted file mode 100644 index 14f60e0..0000000 --- a/ui/views/view_model.cc +++ /dev/null
@@ -1,79 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/view_model.h" - -#include "base/logging.h" -#include "ui/views/view.h" - -namespace views { - -ViewModelBase::~ViewModelBase() { - // view are owned by their parent, no need to delete them. -} - -void ViewModelBase::Remove(int index) { - if (index == -1) - return; - - check_index(index); - entries_.erase(entries_.begin() + index); -} - -void ViewModelBase::Move(int index, int target_index) { - DCHECK_LT(index, static_cast<int>(entries_.size())); - DCHECK_GE(index, 0); - DCHECK_LT(target_index, static_cast<int>(entries_.size())); - DCHECK_GE(target_index, 0); - - if (index == target_index) - return; - Entry entry(entries_[index]); - entries_.erase(entries_.begin() + index); - entries_.insert(entries_.begin() + target_index, entry); -} - -void ViewModelBase::MoveViewOnly(int index, int target_index) { - if (index == target_index) - return; - if (target_index < index) { - View* view = entries_[index].view; - for (int i = index; i > target_index; --i) - entries_[i].view = entries_[i - 1].view; - entries_[target_index].view = view; - } else { - View* view = entries_[index].view; - for (int i = index; i < target_index; ++i) - entries_[i].view = entries_[i + 1].view; - entries_[target_index].view = view; - } -} - -void ViewModelBase::Clear() { - Entries entries; - entries.swap(entries_); - for (size_t i = 0; i < entries.size(); ++i) - delete entries[i].view; -} - -int ViewModelBase::GetIndexOfView(const View* view) const { - for (size_t i = 0; i < entries_.size(); ++i) { - if (entries_[i].view == view) - return static_cast<int>(i); - } - return -1; -} - -ViewModelBase::ViewModelBase() { -} - -void ViewModelBase::AddUnsafe(View* view, int index) { - DCHECK_LE(index, static_cast<int>(entries_.size())); - DCHECK_GE(index, 0); - Entry entry; - entry.view = view; - entries_.insert(entries_.begin() + index, entry); -} - -} // namespace views
diff --git a/ui/views/view_model.h b/ui/views/view_model.h deleted file mode 100644 index 8fff26b..0000000 --- a/ui/views/view_model.h +++ /dev/null
@@ -1,132 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_VIEW_MODEL_H_ -#define UI_VIEWS_VIEW_MODEL_H_ - -#include <vector> - -#include "base/basictypes.h" -#include "base/logging.h" -#include "ui/gfx/rect.h" -#include "ui/views/views_export.h" - -namespace views { - -class View; -class ViewModelUtils; - -// Internal implementation of the templated ViewModelT class. Provides -// non-templated "unsafe" methods for ViewModelT to wrap around. Any methods -// that allow insertion of or access to a View* should be protected, and have a -// public method in the ViewModelT subclass that provides type-safe access to -// the correct View subclass. -class VIEWS_EXPORT ViewModelBase { - public: - ~ViewModelBase(); - - // Removes the view at the specified index. This does not actually remove the - // view from the view hierarchy. - void Remove(int index); - - // Moves the view at |index| to |target_index|. |target_index| is in terms - // of the model *after* the view at |index| is removed. - void Move(int index, int target_index); - - // Variant of Move() that leaves the bounds as is. That is, after invoking - // this the bounds of the view at |target_index| (and all other indices) are - // exactly the same as the bounds of the view at |target_index| before - // invoking this. - void MoveViewOnly(int index, int target_index); - - // Returns the number of views. - int view_size() const { return static_cast<int>(entries_.size()); } - - // Removes and deletes all the views. - void Clear(); - - void set_ideal_bounds(int index, const gfx::Rect& bounds) { - check_index(index); - entries_[index].ideal_bounds = bounds; - } - - const gfx::Rect& ideal_bounds(int index) const { - check_index(index); - return entries_[index].ideal_bounds; - } - - // Returns the index of the specified view, or -1 if the view isn't in the - // model. - int GetIndexOfView(const View* view) const; - - protected: - ViewModelBase(); - - // Returns the view at the specified index. Note: Most users should use - // view_at() in the subclass, to get a view of the correct type. (Do not call - // ViewAtBase then static_cast to the desired type.) - View* ViewAtBase(int index) const { - check_index(index); - return entries_[index].view; - } - - // Adds |view| to this model. This does not add |view| to a view hierarchy, - // only to this model. - void AddUnsafe(View* view, int index); - - private: - // For access to ViewAtBase(). - friend class ViewModelUtils; - - struct Entry { - Entry() : view(NULL) {} - - View* view; - gfx::Rect ideal_bounds; - }; - typedef std::vector<Entry> Entries; - -#if !defined(NDEBUG) - void check_index(int index) const { - DCHECK_LT(index, static_cast<int>(entries_.size())); - DCHECK_GE(index, 0); - } -#else - void check_index(int index) const {} -#endif - - Entries entries_; - - DISALLOW_COPY_AND_ASSIGN(ViewModelBase); -}; - -// ViewModelT is used to track an 'interesting' set of a views. Often times -// during animations views are removed after a delay, which makes for tricky -// coordinate conversion as you have to account for the possibility of the -// indices from the model not lining up with those you expect. This class lets -// you define the 'interesting' views and operate on those views. -template <class T> -class ViewModelT : public ViewModelBase { - public: - ViewModelT<T>() {} - - // Adds |view| to this model. This does not add |view| to a view hierarchy, - // only to this model. - void Add(T* view, int index) { AddUnsafe(view, index); } - - // Returns the view at the specified index. - T* view_at(int index) const { return static_cast<T*>(ViewAtBase(index)); } - - private: - DISALLOW_COPY_AND_ASSIGN(ViewModelT<T>); -}; - -// ViewModel is a collection of views with no specfic type. If all views have -// the same type, the use of ViewModelT is preferred so that the views can be -// retrieved without potentially unsafe downcasts. -typedef ViewModelT<View> ViewModel; - -} // namespace views - -#endif // UI_VIEWS_VIEW_MODEL_H_
diff --git a/ui/views/view_model_unittest.cc b/ui/views/view_model_unittest.cc deleted file mode 100644 index fd4156e..0000000 --- a/ui/views/view_model_unittest.cc +++ /dev/null
@@ -1,96 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/view_model.h" - -#include "base/strings/string_number_conversions.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/views/view.h" - -namespace views { - -namespace { - -// Returns a string containing the x-coordinate of each of the views in |model|. -std::string BoundsString(const ViewModel& model) { - std::string result; - for (int i = 0; i < model.view_size(); ++i) { - if (i != 0) - result += " "; - result += base::IntToString(model.ideal_bounds(i).x()); - } - return result; -} - -// Returns a string containing the id of each of the views in |model|. -std::string ViewIDsString(const ViewModel& model) { - std::string result; - for (int i = 0; i < model.view_size(); ++i) { - if (i != 0) - result += " "; - result += base::IntToString(model.view_at(i)->id()); - } - return result; -} - -} // namespace - -TEST(ViewModel, BasicAssertions) { - View v1; - ViewModel model; - model.Add(&v1, 0); - EXPECT_EQ(1, model.view_size()); - EXPECT_EQ(&v1, model.view_at(0)); - gfx::Rect v1_bounds(1, 2, 3, 4); - model.set_ideal_bounds(0, v1_bounds); - EXPECT_EQ(v1_bounds, model.ideal_bounds(0)); - EXPECT_EQ(0, model.GetIndexOfView(&v1)); -} - -TEST(ViewModel, Move) { - View v1, v2, v3; - v1.set_id(0); - v2.set_id(1); - v3.set_id(2); - ViewModel model; - model.Add(&v1, 0); - model.Add(&v2, 1); - model.Add(&v3, 2); - model.Move(0, 2); - EXPECT_EQ("1 2 0", ViewIDsString(model)); - - model.Move(2, 0); - EXPECT_EQ("0 1 2", ViewIDsString(model)); -} - -TEST(ViewModel, MoveViewOnly) { - View v1, v2, v3; - v1.set_id(0); - v2.set_id(1); - v3.set_id(2); - ViewModel model; - model.Add(&v1, 0); - model.Add(&v2, 1); - model.Add(&v3, 2); - model.set_ideal_bounds(0, gfx::Rect(10, 0, 1, 2)); - model.set_ideal_bounds(1, gfx::Rect(11, 0, 1, 2)); - model.set_ideal_bounds(2, gfx::Rect(12, 0, 1, 2)); - model.MoveViewOnly(0, 2); - EXPECT_EQ("1 2 0", ViewIDsString(model)); - EXPECT_EQ("10 11 12", BoundsString(model)); - - model.MoveViewOnly(2, 0); - EXPECT_EQ("0 1 2", ViewIDsString(model)); - EXPECT_EQ("10 11 12", BoundsString(model)); - - model.MoveViewOnly(0, 1); - EXPECT_EQ("1 0 2", ViewIDsString(model)); - EXPECT_EQ("10 11 12", BoundsString(model)); - - model.MoveViewOnly(1, 0); - EXPECT_EQ("0 1 2", ViewIDsString(model)); - EXPECT_EQ("10 11 12", BoundsString(model)); -} - -} // namespace views
diff --git a/ui/views/view_model_utils.cc b/ui/views/view_model_utils.cc deleted file mode 100644 index 4bb3ac4..0000000 --- a/ui/views/view_model_utils.cc +++ /dev/null
@@ -1,82 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/view_model_utils.h" - -#include <algorithm> - -#include "ui/views/view.h" -#include "ui/views/view_model.h" - -namespace views { - -namespace { - -// Used in calculating ideal bounds. -int primary_axis_coordinate(ViewModelUtils::Alignment alignment, - int x, - int y) { - return alignment == ViewModelUtils::HORIZONTAL ? x : y; -} - -} // namespace - -// static -void ViewModelUtils::SetViewBoundsToIdealBounds(const ViewModelBase& model) { - for (int i = 0; i < model.view_size(); ++i) - model.ViewAtBase(i)->SetBoundsRect(model.ideal_bounds(i)); -} - -// static -bool ViewModelUtils::IsAtIdealBounds(const ViewModelBase& model) { - for (int i = 0; i < model.view_size(); ++i) { - View* view = model.ViewAtBase(i); - if (view->bounds() != model.ideal_bounds(i)) - return false; - } - return true; -} - -// static -int ViewModelUtils::DetermineMoveIndex(const ViewModelBase& model, - View* view, - Alignment alignment, - int x, - int y) { - int value = primary_axis_coordinate(alignment, x, y); - int current_index = model.GetIndexOfView(view); - DCHECK_NE(-1, current_index); - for (int i = 0; i < current_index; ++i) { - int mid_point = primary_axis_coordinate( - alignment, - model.ideal_bounds(i).x() + model.ideal_bounds(i).width() / 2, - model.ideal_bounds(i).y() + model.ideal_bounds(i).height() / 2); - if (value < mid_point) - return i; - } - - if (current_index + 1 == model.view_size()) - return current_index; - - // For indices after the current index ignore the bounds of the view being - // dragged. This keeps the view from bouncing around as moved. - int delta = primary_axis_coordinate( - alignment, - model.ideal_bounds(current_index + 1).x() - - model.ideal_bounds(current_index).x(), - model.ideal_bounds(current_index + 1).y() - - model.ideal_bounds(current_index).y()); - for (int i = current_index + 1; i < model.view_size(); ++i) { - const gfx::Rect& bounds(model.ideal_bounds(i)); - int mid_point = primary_axis_coordinate( - alignment, - bounds.x() + bounds.width() / 2 - delta, - bounds.y() + bounds.height() / 2 - delta); - if (value < mid_point) - return i - 1; - } - return model.view_size() - 1; -} - -} // namespace views
diff --git a/ui/views/view_model_utils.h b/ui/views/view_model_utils.h deleted file mode 100644 index a01fecb..0000000 --- a/ui/views/view_model_utils.h +++ /dev/null
@@ -1,42 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_VIEW_MODEL_UTILS_H_ -#define UI_VIEWS_VIEW_MODEL_UTILS_H_ - -#include "base/basictypes.h" -#include "ui/views/views_export.h" - -namespace views { - -class View; -class ViewModelBase; - -class VIEWS_EXPORT ViewModelUtils { - public: - enum Alignment { - HORIZONTAL, - VERTICAL - }; - - // Sets the bounds of each view to its ideal bounds. - static void SetViewBoundsToIdealBounds(const ViewModelBase& model); - - // Returns true if the Views in |model| are at their ideal bounds. - static bool IsAtIdealBounds(const ViewModelBase& model); - - // Returns the index to move |view| to based on a coordinate of |x| and |y|. - static int DetermineMoveIndex(const ViewModelBase& model, - View* view, - Alignment alignment, - int x, - int y); - - private: - DISALLOW_IMPLICIT_CONSTRUCTORS(ViewModelUtils); -}; - -} // namespace views - -#endif // UI_VIEWS_VIEW_MODEL_UTILS_H_
diff --git a/ui/views/view_model_utils_unittest.cc b/ui/views/view_model_utils_unittest.cc deleted file mode 100644 index 92004b7..0000000 --- a/ui/views/view_model_utils_unittest.cc +++ /dev/null
@@ -1,77 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/view_model_utils.h" - -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/views/view.h" -#include "ui/views/view_model.h" - -namespace views { - -// Makes sure SetViewBoundsToIdealBounds updates the view appropriately. -TEST(ViewModelUtils, SetViewBoundsToIdealBounds) { - View v1; - ViewModel model; - model.Add(&v1, 0); - gfx::Rect v1_bounds(1, 2, 3, 4); - model.set_ideal_bounds(0, v1_bounds); - ViewModelUtils::SetViewBoundsToIdealBounds(model); - EXPECT_EQ(v1_bounds, v1.bounds()); -} - -// Assertions for DetermineMoveIndex. -TEST(ViewModelUtils, DetermineMoveIndex) { - View v1, v2, v3; - ViewModel model; - model.Add(&v1, 0); - model.Add(&v2, 1); - model.Add(&v3, 2); - model.set_ideal_bounds(0, gfx::Rect(0, 0, 10, 10)); - model.set_ideal_bounds(1, gfx::Rect(10, 0, 1000, 10)); - model.set_ideal_bounds(2, gfx::Rect(1010, 0, 2, 10)); - - EXPECT_EQ(0, ViewModelUtils::DetermineMoveIndex( - model, &v1, ViewModelUtils::HORIZONTAL, -10, 0)); - EXPECT_EQ(0, ViewModelUtils::DetermineMoveIndex( - model, &v1, ViewModelUtils::HORIZONTAL, 4, 0)); - EXPECT_EQ(1, ViewModelUtils::DetermineMoveIndex( - model, &v1, ViewModelUtils::HORIZONTAL, 506, 0)); - EXPECT_EQ(2, ViewModelUtils::DetermineMoveIndex( - model, &v1, ViewModelUtils::HORIZONTAL, 1010, 0)); - EXPECT_EQ(2, ViewModelUtils::DetermineMoveIndex( - model, &v1, ViewModelUtils::HORIZONTAL, 2000, 0)); - - EXPECT_EQ(0, ViewModelUtils::DetermineMoveIndex( - model, &v2, ViewModelUtils::HORIZONTAL, -10, 0)); - EXPECT_EQ(0, ViewModelUtils::DetermineMoveIndex( - model, &v2, ViewModelUtils::HORIZONTAL, 4, 0)); - EXPECT_EQ(2, ViewModelUtils::DetermineMoveIndex( - model, &v2, ViewModelUtils::HORIZONTAL, 12, 0)); - - // Try the same when vertical. - model.set_ideal_bounds(0, gfx::Rect(0, 0, 10, 10)); - model.set_ideal_bounds(1, gfx::Rect(0, 10, 10, 1000)); - model.set_ideal_bounds(2, gfx::Rect(0, 1010, 10, 2)); - - EXPECT_EQ(0, ViewModelUtils::DetermineMoveIndex( - model, &v1, ViewModelUtils::VERTICAL, 0, -10)); - EXPECT_EQ(0, ViewModelUtils::DetermineMoveIndex( - model, &v1, ViewModelUtils::VERTICAL, 0, 4)); - EXPECT_EQ(1, ViewModelUtils::DetermineMoveIndex( - model, &v1, ViewModelUtils::VERTICAL, 0, 506)); - EXPECT_EQ(2, ViewModelUtils::DetermineMoveIndex( - model, &v1, ViewModelUtils::VERTICAL, 0, 1010)); - EXPECT_EQ(2, ViewModelUtils::DetermineMoveIndex( - model, &v1, ViewModelUtils::VERTICAL, 0, 2000)); - - EXPECT_EQ(0, ViewModelUtils::DetermineMoveIndex( - model, &v2, ViewModelUtils::VERTICAL, 0, -10)); - EXPECT_EQ(0, ViewModelUtils::DetermineMoveIndex( - model, &v2, ViewModelUtils::VERTICAL, 0, 4)); - EXPECT_EQ(2, ViewModelUtils::DetermineMoveIndex( - model, &v2, ViewModelUtils::VERTICAL, 0, 12)); -} - -} // namespace views
diff --git a/ui/views/view_targeter.cc b/ui/views/view_targeter.cc deleted file mode 100644 index 3c5af01..0000000 --- a/ui/views/view_targeter.cc +++ /dev/null
@@ -1,114 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/view_targeter.h" - -#include "ui/events/event_target.h" -#include "ui/views/focus/focus_manager.h" -#include "ui/views/view.h" -#include "ui/views/view_targeter_delegate.h" - -namespace views { - -ViewTargeter::ViewTargeter(ViewTargeterDelegate* delegate) - : delegate_(delegate) { - DCHECK(delegate_); -} - -ViewTargeter::~ViewTargeter() {} - -bool ViewTargeter::DoesIntersectRect(const View* target, - const gfx::Rect& rect) const { - return delegate_->DoesIntersectRect(target, rect); -} - -View* ViewTargeter::TargetForRect(View* root, const gfx::Rect& rect) const { - return delegate_->TargetForRect(root, rect); -} - -ui::EventTarget* ViewTargeter::FindTargetForEvent(ui::EventTarget* root, - ui::Event* event) { - View* view = static_cast<View*>(root); - - if (event->IsKeyEvent()) - return FindTargetForKeyEvent(view, *static_cast<ui::KeyEvent*>(event)); - - if (event->IsScrollEvent()) { - return FindTargetForScrollEvent(view, - *static_cast<ui::ScrollEvent*>(event)); - } - - if (event->IsGestureEvent()) { - ui::GestureEvent* gesture = event->AsGestureEvent(); - View* gesture_target = FindTargetForGestureEvent(view, *gesture); - root->ConvertEventToTarget(gesture_target, gesture); - return gesture_target; - } - - NOTREACHED() << "ViewTargeter does not yet support this event type."; - return NULL; -} - -ui::EventTarget* ViewTargeter::FindNextBestTarget( - ui::EventTarget* previous_target, - ui::Event* event) { - if (!previous_target) - return NULL; - - if (event->IsGestureEvent()) { - ui::GestureEvent* gesture = event->AsGestureEvent(); - ui::EventTarget* next_target = - FindNextBestTargetForGestureEvent(previous_target, *gesture); - previous_target->ConvertEventToTarget(next_target, gesture); - return next_target; - } - - return previous_target->GetParentTarget(); -} - -bool ViewTargeter::SubtreeCanAcceptEvent( - ui::EventTarget* target, - const ui::LocatedEvent& event) const { - NOTREACHED(); - return false; -} - -bool ViewTargeter::EventLocationInsideBounds( - ui::EventTarget* target, - const ui::LocatedEvent& event) const { - NOTREACHED(); - return false; -} - -View* ViewTargeter::FindTargetForKeyEvent(View* root, const ui::KeyEvent& key) { - if (root->GetFocusManager()) - return root->GetFocusManager()->GetFocusedView(); - return NULL; -} - -View* ViewTargeter::FindTargetForScrollEvent(View* root, - const ui::ScrollEvent& scroll) { - gfx::Rect rect(scroll.location(), gfx::Size(1, 1)); - return root->GetEffectiveViewTargeter()->TargetForRect(root, rect); -} - -View* ViewTargeter::FindTargetForGestureEvent(View* root, - const ui::GestureEvent& gesture) { - // TODO(tdanderson): The only code path that performs targeting for gestures - // uses the ViewTargeter installed on the RootView (i.e., - // a RootViewTargeter). Provide a default implementation - // here if we need to be able to perform gesture targeting - // starting at an arbitrary node in a Views tree. - NOTREACHED(); - return NULL; -} - -ui::EventTarget* ViewTargeter::FindNextBestTargetForGestureEvent( - ui::EventTarget* previous_target, - const ui::GestureEvent& gesture) { - NOTREACHED(); - return NULL; -} - -} // namespace views
diff --git a/ui/views/view_targeter.h b/ui/views/view_targeter.h deleted file mode 100644 index 572f106..0000000 --- a/ui/views/view_targeter.h +++ /dev/null
@@ -1,67 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_VIEW_TARGETER_H_ -#define UI_VIEWS_VIEW_TARGETER_H_ - -#include "ui/events/event_targeter.h" -#include "ui/views/views_export.h" - -namespace views { - -namespace internal { -class RootView; -} // namespace internal - -class View; -class ViewTargeterDelegate; - -// A ViewTargeter is installed on a View that wishes to use the custom -// hit-testing or event-targeting behaviour defined by |delegate|. -class VIEWS_EXPORT ViewTargeter : public ui::EventTargeter { - public: - explicit ViewTargeter(ViewTargeterDelegate* delegate); - ~ViewTargeter() override; - - // A call-through to DoesIntersectRect() on |delegate_|. - bool DoesIntersectRect(const View* target, const gfx::Rect& rect) const; - - // A call-through to TargetForRect() on |delegate_|. - View* TargetForRect(View* root, const gfx::Rect& rect) const; - - protected: - // ui::EventTargeter: - ui::EventTarget* FindTargetForEvent(ui::EventTarget* root, - ui::Event* event) override; - ui::EventTarget* FindNextBestTarget(ui::EventTarget* previous_target, - ui::Event* event) override; - bool SubtreeCanAcceptEvent(ui::EventTarget* target, - const ui::LocatedEvent& event) const override; - bool EventLocationInsideBounds(ui::EventTarget* target, - const ui::LocatedEvent& event) const override; - - private: - // TODO(tdanderson): Un-friend RootView once RootView::DispatchGestureEvent() - // has been removed. - friend class internal::RootView; - - View* FindTargetForKeyEvent(View* root, const ui::KeyEvent& key); - View* FindTargetForScrollEvent(View* root, const ui::ScrollEvent& scroll); - - virtual View* FindTargetForGestureEvent(View* root, - const ui::GestureEvent& gesture); - virtual ui::EventTarget* FindNextBestTargetForGestureEvent( - ui::EventTarget* previous_target, - const ui::GestureEvent& gesture); - - // ViewTargeter does not own the |delegate_|, but |delegate_| must - // outlive the targeter. - ViewTargeterDelegate* delegate_; - - DISALLOW_COPY_AND_ASSIGN(ViewTargeter); -}; - -} // namespace views - -#endif // UI_VIEWS_VIEW_TARGETER_H_
diff --git a/ui/views/view_targeter_delegate.cc b/ui/views/view_targeter_delegate.cc deleted file mode 100644 index 7d4556a..0000000 --- a/ui/views/view_targeter_delegate.cc +++ /dev/null
@@ -1,104 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/view_targeter_delegate.h" - -#include "ui/gfx/rect_conversions.h" -#include "ui/views/rect_based_targeting_utils.h" -#include "ui/views/view.h" - -namespace { - -// The minimum percentage of a view's area that needs to be covered by a rect -// representing a touch region in order for that view to be considered by the -// rect-based targeting algorithm. -static const float kRectTargetOverlap = 0.6f; - -} // namespace - -namespace views { - -// TODO(tdanderson): Move the contents of rect_based_targeting_utils.(h|cc) -// into here. - -bool ViewTargeterDelegate::DoesIntersectRect(const View* target, - const gfx::Rect& rect) const { - return target->GetLocalBounds().Intersects(rect); -} - -View* ViewTargeterDelegate::TargetForRect(View* root, const gfx::Rect& rect) { - // |rect_view| represents the current best candidate to return - // if rect-based targeting (i.e., fuzzing) is used. - // |rect_view_distance| is used to keep track of the distance - // between the center point of |rect_view| and the center - // point of |rect|. - View* rect_view = NULL; - int rect_view_distance = INT_MAX; - - // |point_view| represents the view that would have been returned - // from this function call if point-based targeting were used. - View* point_view = NULL; - - for (int i = root->child_count() - 1; i >= 0; --i) { - View* child = root->child_at(i); - - if (!child->CanProcessEventsWithinSubtree()) - continue; - - // Ignore any children which are invisible or do not intersect |rect|. - if (!child->visible()) - continue; - gfx::RectF rect_in_child_coords_f(rect); - View::ConvertRectToTarget(root, child, &rect_in_child_coords_f); - gfx::Rect rect_in_child_coords = gfx::ToEnclosingRect( - rect_in_child_coords_f); - if (!child->HitTestRect(rect_in_child_coords)) - continue; - - View* cur_view = child->GetEventHandlerForRect(rect_in_child_coords); - - if (views::UsePointBasedTargeting(rect)) - return cur_view; - - gfx::RectF cur_view_bounds_f(cur_view->GetLocalBounds()); - View::ConvertRectToTarget(cur_view, root, &cur_view_bounds_f); - gfx::Rect cur_view_bounds = gfx::ToEnclosingRect( - cur_view_bounds_f); - if (views::PercentCoveredBy(cur_view_bounds, rect) >= kRectTargetOverlap) { - // |cur_view| is a suitable candidate for rect-based targeting. - // Check to see if it is the closest suitable candidate so far. - gfx::Point touch_center(rect.CenterPoint()); - int cur_dist = views::DistanceSquaredFromCenterToPoint(touch_center, - cur_view_bounds); - if (!rect_view || cur_dist < rect_view_distance) { - rect_view = cur_view; - rect_view_distance = cur_dist; - } - } else if (!rect_view && !point_view) { - // Rect-based targeting has not yielded any candidates so far. Check - // if point-based targeting would have selected |cur_view|. - gfx::Point point_in_child_coords(rect_in_child_coords.CenterPoint()); - if (child->HitTestPoint(point_in_child_coords)) - point_view = child->GetEventHandlerForPoint(point_in_child_coords); - } - } - - if (views::UsePointBasedTargeting(rect) || (!rect_view && !point_view)) - return root; - - // If |root| is a suitable candidate for rect-based targeting, check to - // see if it is closer than the current best suitable candidate so far. - gfx::Rect local_bounds(root->GetLocalBounds()); - if (views::PercentCoveredBy(local_bounds, rect) >= kRectTargetOverlap) { - gfx::Point touch_center(rect.CenterPoint()); - int cur_dist = views::DistanceSquaredFromCenterToPoint(touch_center, - local_bounds); - if (!rect_view || cur_dist < rect_view_distance) - rect_view = root; - } - - return rect_view ? rect_view : point_view; -} - -} // namespace views
diff --git a/ui/views/view_targeter_delegate.h b/ui/views/view_targeter_delegate.h deleted file mode 100644 index 0ad461a..0000000 --- a/ui/views/view_targeter_delegate.h +++ /dev/null
@@ -1,50 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_VIEW_TARGETER_DELEGATE_H_ -#define UI_VIEWS_VIEW_TARGETER_DELEGATE_H_ - -#include "base/macros.h" -#include "ui/views/views_export.h" - -namespace gfx { -class Rect; -} - -namespace views { -class View; - -// Defines the default behaviour for hit-testing and event-targeting against a -// View using a rectangular region representing an event's location. Views -// wishing to define custom hit-testing or event-targeting behaviour do so by -// extending ViewTargeterDelegate and then installing a ViewTargeter on -// themselves. -class VIEWS_EXPORT ViewTargeterDelegate { - public: - ViewTargeterDelegate() {} - virtual ~ViewTargeterDelegate() {} - - // Returns true if the bounds of |target| intersects |rect|, where |rect| - // is in the local coodinate space of |target|. Overrides of this method by - // a View subclass should enforce DCHECK_EQ(this, target). - virtual bool DoesIntersectRect(const View* target, - const gfx::Rect& rect) const; - - // If point-based targeting should be used, return the deepest visible - // descendant of |root| that contains the center point of |rect|. - // If rect-based targeting (i.e., fuzzing) should be used, return the - // closest visible descendant of |root| having at least kRectTargetOverlap of - // its area covered by |rect|. If no such descendant exists, return the - // deepest visible descendant of |root| that contains the center point of - // |rect|. See http://goo.gl/3Jp2BD for more information about rect-based - // targeting. - virtual View* TargetForRect(View* root, const gfx::Rect& rect); - - private: - DISALLOW_COPY_AND_ASSIGN(ViewTargeterDelegate); -}; - -} // namespace views - -#endif // UI_VIEWS_VIEW_TARGETER_DELEGATE_H_
diff --git a/ui/views/view_targeter_unittest.cc b/ui/views/view_targeter_unittest.cc deleted file mode 100644 index a3acb46..0000000 --- a/ui/views/view_targeter_unittest.cc +++ /dev/null
@@ -1,673 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/view_targeter.h" - -#include "ui/events/event_targeter.h" -#include "ui/events/event_utils.h" -#include "ui/gfx/path.h" -#include "ui/views/masked_targeter_delegate.h" -#include "ui/views/test/views_test_base.h" -#include "ui/views/view_targeter.h" -#include "ui/views/view_targeter_delegate.h" -#include "ui/views/widget/root_view.h" - -namespace views { - -// A derived class of View used for testing purposes. -class TestingView : public View, public ViewTargeterDelegate { - public: - TestingView() : can_process_events_within_subtree_(true) {} - virtual ~TestingView() {} - - // Reset all test state. - void Reset() { can_process_events_within_subtree_ = true; } - - void set_can_process_events_within_subtree(bool can_process) { - can_process_events_within_subtree_ = can_process; - } - - // A call-through function to ViewTargeterDelegate::DoesIntersectRect(). - bool TestDoesIntersectRect(const View* target, const gfx::Rect& rect) const { - return DoesIntersectRect(target, rect); - } - - // View: - virtual bool CanProcessEventsWithinSubtree() const override { - return can_process_events_within_subtree_; - } - - private: - // Value to return from CanProcessEventsWithinSubtree(). - bool can_process_events_within_subtree_; - - DISALLOW_COPY_AND_ASSIGN(TestingView); -}; - -// A derived class of View having a triangular-shaped hit test mask. -class TestMaskedView : public View, public MaskedTargeterDelegate { - public: - TestMaskedView() {} - virtual ~TestMaskedView() {} - - // A call-through function to MaskedTargeterDelegate::DoesIntersectRect(). - bool TestDoesIntersectRect(const View* target, const gfx::Rect& rect) const { - return DoesIntersectRect(target, rect); - } - - private: - // MaskedTargeterDelegate: - virtual bool GetHitTestMask(gfx::Path* mask) const override { - DCHECK(mask); - SkScalar w = SkIntToScalar(width()); - SkScalar h = SkIntToScalar(height()); - - // Create a triangular mask within the bounds of this View. - mask->moveTo(w / 2, 0); - mask->lineTo(w, h); - mask->lineTo(0, h); - mask->close(); - return true; - } - - DISALLOW_COPY_AND_ASSIGN(TestMaskedView); -}; - -namespace test { - -// TODO(tdanderson): Clean up this test suite by moving common code/state into -// ViewTargeterTest and overriding SetUp(), TearDown(), etc. -// See crbug.com/355680. -class ViewTargeterTest : public ViewsTestBase { - public: - ViewTargeterTest() {} - virtual ~ViewTargeterTest() {} - - void SetGestureHandler(internal::RootView* root_view, View* handler) { - root_view->gesture_handler_ = handler; - } - - void SetGestureHandlerSetBeforeProcessing(internal::RootView* root_view, - bool set) { - root_view->gesture_handler_set_before_processing_ = set; - } - - private: - DISALLOW_COPY_AND_ASSIGN(ViewTargeterTest); -}; - -namespace { - -gfx::Point ConvertPointFromWidgetToView(View* view, const gfx::Point& p) { - gfx::Point tmp(p); - View::ConvertPointToTarget(view->GetWidget()->GetRootView(), view, &tmp); - return tmp; -} - -gfx::Rect ConvertRectFromWidgetToView(View* view, const gfx::Rect& r) { - gfx::Rect tmp(r); - tmp.set_origin(ConvertPointFromWidgetToView(view, r.origin())); - return tmp; -} - -} // namespace - -// Verifies that the the functions ViewTargeter::FindTargetForEvent() -// and ViewTargeter::FindNextBestTarget() are implemented correctly -// for key events. -TEST_F(ViewTargeterTest, ViewTargeterForKeyEvents) { - Widget widget; - Widget::InitParams init_params = - CreateParams(Widget::InitParams::TYPE_POPUP); - init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(init_params); - - View* content = new View; - View* child = new View; - View* grandchild = new View; - - widget.SetContentsView(content); - content->AddChildView(child); - child->AddChildView(grandchild); - - grandchild->SetFocusable(true); - grandchild->RequestFocus(); - - internal::RootView* root_view = - static_cast<internal::RootView*>(widget.GetRootView()); - ui::EventTargeter* targeter = root_view->targeter(); - - ui::KeyEvent key_event('a', ui::VKEY_A, ui::EF_NONE); - - // The focused view should be the initial target of the event. - ui::EventTarget* current_target = targeter->FindTargetForEvent(root_view, - &key_event); - EXPECT_EQ(grandchild, static_cast<View*>(current_target)); - - // Verify that FindNextBestTarget() will return the parent view of the - // argument (and NULL if the argument has no parent view). - current_target = targeter->FindNextBestTarget(grandchild, &key_event); - EXPECT_EQ(child, static_cast<View*>(current_target)); - current_target = targeter->FindNextBestTarget(child, &key_event); - EXPECT_EQ(content, static_cast<View*>(current_target)); - current_target = targeter->FindNextBestTarget(content, &key_event); - EXPECT_EQ(widget.GetRootView(), static_cast<View*>(current_target)); - current_target = targeter->FindNextBestTarget(widget.GetRootView(), - &key_event); - EXPECT_EQ(NULL, static_cast<View*>(current_target)); -} - -// Verifies that the the functions ViewTargeter::FindTargetForEvent() -// and ViewTargeter::FindNextBestTarget() are implemented correctly -// for scroll events. -TEST_F(ViewTargeterTest, ViewTargeterForScrollEvents) { - Widget widget; - Widget::InitParams init_params = - CreateParams(Widget::InitParams::TYPE_POPUP); - init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - init_params.bounds = gfx::Rect(0, 0, 200, 200); - widget.Init(init_params); - - // The coordinates used for SetBounds() are in the parent coordinate space. - View* content = new View; - content->SetBounds(0, 0, 100, 100); - View* child = new View; - child->SetBounds(50, 50, 20, 20); - View* grandchild = new View; - grandchild->SetBounds(0, 0, 5, 5); - - widget.SetContentsView(content); - content->AddChildView(child); - child->AddChildView(grandchild); - - internal::RootView* root_view = - static_cast<internal::RootView*>(widget.GetRootView()); - ui::EventTargeter* targeter = root_view->targeter(); - - // The event falls within the bounds of |child| and |content| but not - // |grandchild|, so |child| should be the initial target for the event. - ui::ScrollEvent scroll(ui::ET_SCROLL, - gfx::Point(60, 60), - ui::EventTimeForNow(), - 0, - 0, 3, - 0, 3, - 2); - ui::EventTarget* current_target = targeter->FindTargetForEvent(root_view, - &scroll); - EXPECT_EQ(child, static_cast<View*>(current_target)); - - // Verify that FindNextBestTarget() will return the parent view of the - // argument (and NULL if the argument has no parent view). - current_target = targeter->FindNextBestTarget(child, &scroll); - EXPECT_EQ(content, static_cast<View*>(current_target)); - current_target = targeter->FindNextBestTarget(content, &scroll); - EXPECT_EQ(widget.GetRootView(), static_cast<View*>(current_target)); - current_target = targeter->FindNextBestTarget(widget.GetRootView(), - &scroll); - EXPECT_EQ(NULL, static_cast<View*>(current_target)); - - // The event falls outside of the original specified bounds of |content|, - // |child|, and |grandchild|. But since |content| is the contents view, - // and contents views are resized to fill the entire area of the root - // view, the event's initial target should still be |content|. - scroll = ui::ScrollEvent(ui::ET_SCROLL, - gfx::Point(150, 150), - ui::EventTimeForNow(), - 0, - 0, 3, - 0, 3, - 2); - current_target = targeter->FindTargetForEvent(root_view, &scroll); - EXPECT_EQ(content, static_cast<View*>(current_target)); -} - -// Convenience to make constructing a GestureEvent simpler. -class GestureEventForTest : public ui::GestureEvent { - public: - GestureEventForTest(ui::EventType type, int x, int y) - : GestureEvent(x, - y, - 0, - base::TimeDelta(), - ui::GestureEventDetails(type)) {} - - GestureEventForTest(ui::GestureEventDetails details) - : GestureEvent(details.bounding_box().CenterPoint().x(), - details.bounding_box().CenterPoint().y(), - 0, - base::TimeDelta(), - details) {} -}; - -// Verifies that the the functions ViewTargeter::FindTargetForEvent() -// and ViewTargeter::FindNextBestTarget() are implemented correctly -// for gesture events. -TEST_F(ViewTargeterTest, ViewTargeterForGestureEvents) { - Widget widget; - Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP); - init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - init_params.bounds = gfx::Rect(0, 0, 200, 200); - widget.Init(init_params); - - // The coordinates used for SetBounds() are in the parent coordinate space. - View* content = new View; - content->SetBounds(0, 0, 100, 100); - View* child = new View; - child->SetBounds(50, 50, 20, 20); - View* grandchild = new View; - grandchild->SetBounds(0, 0, 5, 5); - - widget.SetContentsView(content); - content->AddChildView(child); - child->AddChildView(grandchild); - - internal::RootView* root_view = - static_cast<internal::RootView*>(widget.GetRootView()); - ui::EventTargeter* targeter = root_view->targeter(); - - // Define some gesture events for testing. - gfx::Rect bounding_box(gfx::Point(46, 46), gfx::Size(8, 8)); - gfx::Point center_point(bounding_box.CenterPoint()); - ui::GestureEventDetails details(ui::ET_GESTURE_TAP); - details.set_bounding_box(bounding_box); - GestureEventForTest tap(details); - details = ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_BEGIN); - details.set_bounding_box(bounding_box); - GestureEventForTest scroll_begin(details); - details = ui::GestureEventDetails(ui::ET_GESTURE_END); - details.set_bounding_box(bounding_box); - GestureEventForTest end(details); - - // Assume that the view currently handling gestures has been set as - // |grandchild| by a previous gesture event. Thus subsequent TAP and - // SCROLL_BEGIN events should be initially targeted to |grandchild|, and - // re-targeting should be prohibited for TAP but permitted for - // GESTURE_SCROLL_BEGIN (which should be re-targeted to the parent of - // |grandchild|). - SetGestureHandlerSetBeforeProcessing(root_view, true); - SetGestureHandler(root_view, grandchild); - EXPECT_EQ(grandchild, targeter->FindTargetForEvent(root_view, &tap)); - EXPECT_EQ(NULL, targeter->FindNextBestTarget(grandchild, &tap)); - EXPECT_EQ(grandchild, targeter->FindTargetForEvent(root_view, &scroll_begin)); - EXPECT_EQ(child, targeter->FindNextBestTarget(grandchild, &scroll_begin)); - - // GESTURE_END events should be targeted to the existing gesture handler, - // but re-targeting should be prohibited. - EXPECT_EQ(grandchild, targeter->FindTargetForEvent(root_view, &end)); - EXPECT_EQ(NULL, targeter->FindNextBestTarget(grandchild, &end)); - - // Assume that the view currently handling gestures is still set as - // |grandchild|, but this was not done by a previous gesture. Thus we are - // in the process of finding the View to which subsequent gestures will be - // dispatched, so TAP and SCROLL_BEGIN events should be re-targeted up - // the ancestor chain. - SetGestureHandlerSetBeforeProcessing(root_view, false); - EXPECT_EQ(child, targeter->FindNextBestTarget(grandchild, &tap)); - EXPECT_EQ(child, targeter->FindNextBestTarget(grandchild, &scroll_begin)); - - // GESTURE_END events are not permitted to be re-targeted up the ancestor - // chain; they are only ever targeted in the case where the gesture handler - // was established by a previous gesture. - EXPECT_EQ(NULL, targeter->FindNextBestTarget(grandchild, &end)); - - // Assume that the default gesture handler was set by the previous gesture, - // but that this handler is currently NULL. No gesture events should be - // re-targeted in this case (regardless of the view that is passed in to - // FindNextBestTarget() as the previous target). - SetGestureHandler(root_view, NULL); - SetGestureHandlerSetBeforeProcessing(root_view, true); - EXPECT_EQ(NULL, targeter->FindNextBestTarget(child, &tap)); - EXPECT_EQ(NULL, targeter->FindNextBestTarget(NULL, &tap)); - EXPECT_EQ(NULL, targeter->FindNextBestTarget(content, &scroll_begin)); - EXPECT_EQ(NULL, targeter->FindNextBestTarget(content, &end)); - - // Reset the locations of the gesture events to be in the root view - // coordinate space since we are about to call FindTargetForEvent() - // again (calls to FindTargetForEvent() and FindNextBestTarget() - // mutate the location of the gesture events to be in the coordinate - // space of the returned view). - details = ui::GestureEventDetails(ui::ET_GESTURE_TAP); - details.set_bounding_box(bounding_box); - tap = GestureEventForTest(details); - details = ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_BEGIN); - details.set_bounding_box(bounding_box); - scroll_begin = GestureEventForTest(details); - details = ui::GestureEventDetails(ui::ET_GESTURE_END); - details.set_bounding_box(bounding_box); - end = GestureEventForTest(details); - - // If no default gesture handler is currently set, targeting should be - // performed using the location of the gesture event for a TAP and a - // SCROLL_BEGIN. - SetGestureHandlerSetBeforeProcessing(root_view, false); - EXPECT_EQ(grandchild, targeter->FindTargetForEvent(root_view, &tap)); - EXPECT_EQ(grandchild, targeter->FindTargetForEvent(root_view, &scroll_begin)); - - // If no default gesture handler is currently set, GESTURE_END events - // should never be re-targeted to any View. - EXPECT_EQ(NULL, targeter->FindNextBestTarget(NULL, &end)); - EXPECT_EQ(NULL, targeter->FindNextBestTarget(child, &end)); -} - -// Tests that the contents view is targeted instead of the root view for -// gesture events that should be targeted to the contents view. Also -// tests that the root view is targeted for gesture events which should -// not be targeted to any other view in the views tree. -TEST_F(ViewTargeterTest, TargetContentsAndRootView) { - Widget widget; - Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP); - init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - init_params.bounds = gfx::Rect(0, 0, 200, 200); - widget.Init(init_params); - - // The coordinates used for SetBounds() are in the parent coordinate space. - View* content = new View; - content->SetBounds(0, 0, 100, 100); - widget.SetContentsView(content); - - internal::RootView* root_view = - static_cast<internal::RootView*>(widget.GetRootView()); - ui::EventTargeter* targeter = root_view->targeter(); - - // A gesture event located entirely within the contents view should - // target the contents view. - gfx::Rect bounding_box(gfx::Point(96, 96), gfx::Size(8, 8)); - gfx::Point center_point(bounding_box.CenterPoint()); - ui::GestureEventDetails details(ui::ET_GESTURE_TAP); - details.set_bounding_box(bounding_box); - GestureEventForTest tap(details); - - EXPECT_EQ(content, targeter->FindTargetForEvent(root_view, &tap)); - - // A gesture event not located entirely within the contents view but - // having its center within the contents view should target - // the contents view. - bounding_box = gfx::Rect(gfx::Point(194, 100), gfx::Size(8, 8)); - details.set_bounding_box(bounding_box); - center_point = bounding_box.CenterPoint(); - tap = GestureEventForTest(details); - - EXPECT_EQ(content, targeter->FindTargetForEvent(root_view, &tap)); - - // A gesture event with its center not located within the contents - // view but that overlaps the contents view by at least 60% should - // target the contents view. - bounding_box = gfx::Rect(gfx::Point(50, 0), gfx::Size(400, 200)); - details.set_bounding_box(bounding_box); - center_point = bounding_box.CenterPoint(); - tap = GestureEventForTest(details); - - EXPECT_EQ(content, targeter->FindTargetForEvent(root_view, &tap)); - - // A gesture event not overlapping the contents view by at least - // 60% and not having its center within the contents view should - // be targeted to the root view. - bounding_box = gfx::Rect(gfx::Point(196, 100), gfx::Size(8, 8)); - details.set_bounding_box(bounding_box); - center_point = bounding_box.CenterPoint(); - tap = GestureEventForTest(details); - - EXPECT_EQ(widget.GetRootView(), - targeter->FindTargetForEvent(root_view, &tap)); - - // A gesture event completely outside the contents view should be targeted - // to the root view. - bounding_box = gfx::Rect(gfx::Point(205, 100), gfx::Size(8, 8)); - details.set_bounding_box(bounding_box); - center_point = bounding_box.CenterPoint(); - tap = GestureEventForTest(details); - - EXPECT_EQ(widget.GetRootView(), - targeter->FindTargetForEvent(root_view, &tap)); - - // A gesture event with dimensions 1x1 located entirely within the - // contents view should target the contents view. - bounding_box = gfx::Rect(gfx::Point(175, 100), gfx::Size(1, 1)); - details.set_bounding_box(bounding_box); - center_point = bounding_box.CenterPoint(); - tap = GestureEventForTest(details); - - EXPECT_EQ(content, targeter->FindTargetForEvent(root_view, &tap)); - - // A gesture event with dimensions 1x1 located entirely outside the - // contents view should be targeted to the root view. - bounding_box = gfx::Rect(gfx::Point(205, 100), gfx::Size(1, 1)); - details.set_bounding_box(bounding_box); - center_point = bounding_box.CenterPoint(); - tap = GestureEventForTest(details); - - EXPECT_EQ(widget.GetRootView(), - targeter->FindTargetForEvent(root_view, &tap)); -} - -// Tests that calls to FindTargetForEvent() and FindNextBestTarget() change -// the location of a gesture event to be in the correct coordinate space. -TEST_F(ViewTargeterTest, GestureEventCoordinateConversion) { - Widget widget; - Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP); - init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - init_params.bounds = gfx::Rect(0, 0, 200, 200); - widget.Init(init_params); - - // The coordinates used for SetBounds() are in the parent coordinate space. - View* content = new View; - content->SetBounds(0, 0, 100, 100); - View* child = new View; - child->SetBounds(50, 50, 20, 20); - View* grandchild = new View; - grandchild->SetBounds(5, 5, 10, 10); - View* great_grandchild = new View; - great_grandchild->SetBounds(3, 3, 4, 4); - - widget.SetContentsView(content); - content->AddChildView(child); - child->AddChildView(grandchild); - grandchild->AddChildView(great_grandchild); - - internal::RootView* root_view = - static_cast<internal::RootView*>(widget.GetRootView()); - ui::EventTargeter* targeter = root_view->targeter(); - - // Define a GESTURE_TAP event with a bounding box centered at (60, 60) - // in root view coordinates with width and height of 4. - gfx::Rect bounding_box(gfx::Point(58, 58), gfx::Size(4, 4)); - gfx::Point center_point(bounding_box.CenterPoint()); - ui::GestureEventDetails details(ui::ET_GESTURE_TAP); - details.set_bounding_box(bounding_box); - GestureEventForTest tap(details); - - // Calculate the location of the gesture in each of the different - // coordinate spaces. - gfx::Point location_in_root(center_point); - EXPECT_EQ(gfx::Point(60, 60), location_in_root); - gfx::Point location_in_great_grandchild( - ConvertPointFromWidgetToView(great_grandchild, location_in_root)); - EXPECT_EQ(gfx::Point(2, 2), location_in_great_grandchild); - gfx::Point location_in_grandchild( - ConvertPointFromWidgetToView(grandchild, location_in_root)); - EXPECT_EQ(gfx::Point(5, 5), location_in_grandchild); - gfx::Point location_in_child( - ConvertPointFromWidgetToView(child, location_in_root)); - EXPECT_EQ(gfx::Point(10, 10), location_in_child); - gfx::Point location_in_content( - ConvertPointFromWidgetToView(content, location_in_root)); - EXPECT_EQ(gfx::Point(60, 60), location_in_content); - - // Verify the location of |tap| is in screen coordinates. - EXPECT_EQ(gfx::Point(60, 60), tap.location()); - - // The initial target should be |great_grandchild| and the location of - // the event should be changed into the coordinate space of the target. - EXPECT_EQ(great_grandchild, targeter->FindTargetForEvent(root_view, &tap)); - EXPECT_EQ(location_in_great_grandchild, tap.location()); - SetGestureHandler(root_view, great_grandchild); - - // The next target should be |grandchild| and the location of - // the event should be changed into the coordinate space of the target. - EXPECT_EQ(grandchild, targeter->FindNextBestTarget(great_grandchild, &tap)); - EXPECT_EQ(location_in_grandchild, tap.location()); - SetGestureHandler(root_view, grandchild); - - // The next target should be |child| and the location of - // the event should be changed into the coordinate space of the target. - EXPECT_EQ(child, targeter->FindNextBestTarget(grandchild, &tap)); - EXPECT_EQ(location_in_child, tap.location()); - SetGestureHandler(root_view, child); - - // The next target should be |content| and the location of - // the event should be changed into the coordinate space of the target. - EXPECT_EQ(content, targeter->FindNextBestTarget(child, &tap)); - EXPECT_EQ(location_in_content, tap.location()); - SetGestureHandler(root_view, content); - - // The next target should be |root_view| and the location of - // the event should be changed into the coordinate space of the target. - EXPECT_EQ(widget.GetRootView(), targeter->FindNextBestTarget(content, &tap)); - EXPECT_EQ(location_in_root, tap.location()); - SetGestureHandler(root_view, widget.GetRootView()); - - // The next target should be NULL and the location of the event should - // remain unchanged. - EXPECT_EQ(NULL, targeter->FindNextBestTarget(widget.GetRootView(), &tap)); - EXPECT_EQ(location_in_root, tap.location()); -} - -// Tests that the functions ViewTargeterDelegate::DoesIntersectRect() -// and MaskedTargeterDelegate::DoesIntersectRect() work as intended when -// called on views which are derived from ViewTargeterDelegate. -// Also verifies that ViewTargeterDelegate::DoesIntersectRect() can -// be called from the ViewTargeter installed on RootView. -TEST_F(ViewTargeterTest, DoesIntersectRect) { - Widget widget; - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.bounds = gfx::Rect(0, 0, 650, 650); - widget.Init(params); - - internal::RootView* root_view = - static_cast<internal::RootView*>(widget.GetRootView()); - ViewTargeter* view_targeter = root_view->targeter(); - - // The coordinates used for SetBounds() are in the parent coordinate space. - TestingView v2; - TestMaskedView v1, v3; - v1.SetBounds(0, 0, 200, 200); - v2.SetBounds(300, 0, 300, 300); - v3.SetBounds(0, 0, 100, 100); - root_view->AddChildView(&v1); - root_view->AddChildView(&v2); - v2.AddChildView(&v3); - - // The coordinates used below are in the local coordinate space of the - // view that is passed in as an argument. - - // Hit tests against |v1|, which has a hit test mask. - EXPECT_TRUE(v1.TestDoesIntersectRect(&v1, gfx::Rect(0, 0, 200, 200))); - EXPECT_TRUE(v1.TestDoesIntersectRect(&v1, gfx::Rect(-10, -10, 110, 12))); - EXPECT_TRUE(v1.TestDoesIntersectRect(&v1, gfx::Rect(112, 142, 1, 1))); - EXPECT_FALSE(v1.TestDoesIntersectRect(&v1, gfx::Rect(0, 0, 20, 20))); - EXPECT_FALSE(v1.TestDoesIntersectRect(&v1, gfx::Rect(-10, -10, 90, 12))); - EXPECT_FALSE(v1.TestDoesIntersectRect(&v1, gfx::Rect(150, 49, 1, 1))); - - // Hit tests against |v2|, which does not have a hit test mask. - EXPECT_TRUE(v2.TestDoesIntersectRect(&v2, gfx::Rect(0, 0, 200, 200))); - EXPECT_TRUE(v2.TestDoesIntersectRect(&v2, gfx::Rect(-10, 250, 60, 60))); - EXPECT_TRUE(v2.TestDoesIntersectRect(&v2, gfx::Rect(250, 250, 1, 1))); - EXPECT_FALSE(v2.TestDoesIntersectRect(&v2, gfx::Rect(-10, 250, 7, 7))); - EXPECT_FALSE(v2.TestDoesIntersectRect(&v2, gfx::Rect(-1, -1, 1, 1))); - - // Hit tests against |v3|, which has a hit test mask and is a child of |v2|. - EXPECT_TRUE(v3.TestDoesIntersectRect(&v3, gfx::Rect(0, 0, 50, 50))); - EXPECT_TRUE(v3.TestDoesIntersectRect(&v3, gfx::Rect(90, 90, 1, 1))); - EXPECT_FALSE(v3.TestDoesIntersectRect(&v3, gfx::Rect(10, 125, 50, 50))); - EXPECT_FALSE(v3.TestDoesIntersectRect(&v3, gfx::Rect(110, 110, 1, 1))); - - // Verify that hit-testing is performed correctly when using the - // call-through function ViewTargeter::DoesIntersectRect(). - EXPECT_TRUE(view_targeter->DoesIntersectRect(root_view, - gfx::Rect(0, 0, 50, 50))); - EXPECT_FALSE(view_targeter->DoesIntersectRect(root_view, - gfx::Rect(-20, -20, 10, 10))); -} - -// Tests that calls made directly on the hit-testing methods in View -// (HitTestPoint(), HitTestRect(), etc.) return the correct values. -TEST_F(ViewTargeterTest, HitTestCallsOnView) { - // The coordinates in this test are in the coordinate space of the root view. - Widget* widget = new Widget; - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - widget->Init(params); - View* root_view = widget->GetRootView(); - root_view->SetBoundsRect(gfx::Rect(0, 0, 500, 500)); - - // |v1| has no hit test mask. No ViewTargeter is installed on |v1|, which - // means that View::HitTestRect() will call into the targeter installed on - // the root view instead when we hit test against |v1|. - gfx::Rect v1_bounds = gfx::Rect(0, 0, 100, 100); - TestingView* v1 = new TestingView(); - v1->SetBoundsRect(v1_bounds); - root_view->AddChildView(v1); - - // |v2| has a triangular hit test mask. Install a ViewTargeter on |v2| which - // will be called into by View::HitTestRect(). - gfx::Rect v2_bounds = gfx::Rect(105, 0, 100, 100); - TestMaskedView* v2 = new TestMaskedView(); - v2->SetBoundsRect(v2_bounds); - root_view->AddChildView(v2); - ViewTargeter* view_targeter = new ViewTargeter(v2); - v2->SetEventTargeter(make_scoped_ptr(view_targeter)); - - gfx::Point v1_centerpoint = v1_bounds.CenterPoint(); - gfx::Point v2_centerpoint = v2_bounds.CenterPoint(); - gfx::Point v1_origin = v1_bounds.origin(); - gfx::Point v2_origin = v2_bounds.origin(); - gfx::Rect r1(10, 10, 110, 15); - gfx::Rect r2(106, 1, 98, 98); - gfx::Rect r3(0, 0, 300, 300); - gfx::Rect r4(115, 342, 200, 10); - - // Test calls into View::HitTestPoint(). - EXPECT_TRUE( - v1->HitTestPoint(ConvertPointFromWidgetToView(v1, v1_centerpoint))); - EXPECT_TRUE( - v2->HitTestPoint(ConvertPointFromWidgetToView(v2, v2_centerpoint))); - - EXPECT_TRUE(v1->HitTestPoint(ConvertPointFromWidgetToView(v1, v1_origin))); - EXPECT_FALSE(v2->HitTestPoint(ConvertPointFromWidgetToView(v2, v2_origin))); - - // Test calls into View::HitTestRect(). - EXPECT_TRUE(v1->HitTestRect(ConvertRectFromWidgetToView(v1, r1))); - EXPECT_FALSE(v2->HitTestRect(ConvertRectFromWidgetToView(v2, r1))); - - EXPECT_FALSE(v1->HitTestRect(ConvertRectFromWidgetToView(v1, r2))); - EXPECT_TRUE(v2->HitTestRect(ConvertRectFromWidgetToView(v2, r2))); - - EXPECT_TRUE(v1->HitTestRect(ConvertRectFromWidgetToView(v1, r3))); - EXPECT_TRUE(v2->HitTestRect(ConvertRectFromWidgetToView(v2, r3))); - - EXPECT_FALSE(v1->HitTestRect(ConvertRectFromWidgetToView(v1, r4))); - EXPECT_FALSE(v2->HitTestRect(ConvertRectFromWidgetToView(v2, r4))); - - // Test calls into View::GetEventHandlerForPoint(). - EXPECT_EQ(v1, root_view->GetEventHandlerForPoint(v1_centerpoint)); - EXPECT_EQ(v2, root_view->GetEventHandlerForPoint(v2_centerpoint)); - - EXPECT_EQ(v1, root_view->GetEventHandlerForPoint(v1_origin)); - EXPECT_EQ(root_view, root_view->GetEventHandlerForPoint(v2_origin)); - - // Test calls into View::GetTooltipHandlerForPoint(). - EXPECT_EQ(v1, root_view->GetTooltipHandlerForPoint(v1_centerpoint)); - EXPECT_EQ(v2, root_view->GetTooltipHandlerForPoint(v2_centerpoint)); - - EXPECT_EQ(v1, root_view->GetTooltipHandlerForPoint(v1_origin)); - EXPECT_EQ(root_view, root_view->GetTooltipHandlerForPoint(v2_origin)); - - EXPECT_FALSE(v1->GetTooltipHandlerForPoint(v2_origin)); - - widget->CloseNow(); -} - -} // namespace test -} // namespace views
diff --git a/ui/views/view_unittest.cc b/ui/views/view_unittest.cc deleted file mode 100644 index 4f15a21..0000000 --- a/ui/views/view_unittest.cc +++ /dev/null
@@ -1,3707 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <map> - -#include "base/memory/scoped_ptr.h" -#include "base/rand_util.h" -#include "base/strings/string_util.h" -#include "base/strings/stringprintf.h" -#include "base/strings/utf_string_conversions.h" -#include "ui/base/accelerators/accelerator.h" -#include "ui/base/clipboard/clipboard.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/compositor/compositor.h" -#include "ui/compositor/layer.h" -#include "ui/compositor/layer_animator.h" -#include "ui/compositor/test/draw_waiter_for_test.h" -#include "ui/events/event.h" -#include "ui/events/keycodes/keyboard_codes.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/path.h" -#include "ui/gfx/transform.h" -#include "ui/strings/grit/ui_strings.h" -#include "ui/views/background.h" -#include "ui/views/controls/native/native_view_host.h" -#include "ui/views/controls/scroll_view.h" -#include "ui/views/controls/textfield/textfield.h" -#include "ui/views/focus/view_storage.h" -#include "ui/views/test/views_test_base.h" -#include "ui/views/view.h" -#include "ui/views/views_delegate.h" -#include "ui/views/widget/native_widget.h" -#include "ui/views/widget/root_view.h" -#include "ui/views/window/dialog_client_view.h" -#include "ui/views/window/dialog_delegate.h" - -using base::ASCIIToUTF16; - -namespace { - -// Returns true if |ancestor| is an ancestor of |layer|. -bool LayerIsAncestor(const ui::Layer* ancestor, const ui::Layer* layer) { - while (layer && layer != ancestor) - layer = layer->parent(); - return layer == ancestor; -} - -// Convenience functions for walking a View tree. -const views::View* FirstView(const views::View* view) { - const views::View* v = view; - while (v->has_children()) - v = v->child_at(0); - return v; -} - -const views::View* NextView(const views::View* view) { - const views::View* v = view; - const views::View* parent = v->parent(); - if (!parent) - return NULL; - int next = parent->GetIndexOf(v) + 1; - if (next != parent->child_count()) - return FirstView(parent->child_at(next)); - return parent; -} - -// Convenience functions for walking a Layer tree. -const ui::Layer* FirstLayer(const ui::Layer* layer) { - const ui::Layer* l = layer; - while (l->children().size() > 0) - l = l->children()[0]; - return l; -} - -const ui::Layer* NextLayer(const ui::Layer* layer) { - const ui::Layer* parent = layer->parent(); - if (!parent) - return NULL; - const std::vector<ui::Layer*> children = parent->children(); - size_t index; - for (index = 0; index < children.size(); index++) { - if (children[index] == layer) - break; - } - size_t next = index + 1; - if (next < children.size()) - return FirstLayer(children[next]); - return parent; -} - -// Given the root nodes of a View tree and a Layer tree, makes sure the two -// trees are in sync. -bool ViewAndLayerTreeAreConsistent(const views::View* view, - const ui::Layer* layer) { - const views::View* v = FirstView(view); - const ui::Layer* l = FirstLayer(layer); - while (v && l) { - // Find the view with a layer. - while (v && !v->layer()) - v = NextView(v); - EXPECT_TRUE(v); - if (!v) - return false; - - // Check if the View tree and the Layer tree are in sync. - EXPECT_EQ(l, v->layer()); - if (v->layer() != l) - return false; - - // Check if the visibility states of the View and the Layer are in sync. - EXPECT_EQ(l->IsDrawn(), v->IsDrawn()); - if (v->IsDrawn() != l->IsDrawn()) { - for (const views::View* vv = v; vv; vv = vv->parent()) - LOG(ERROR) << "V: " << vv << " " << vv->visible() << " " - << vv->IsDrawn() << " " << vv->layer(); - for (const ui::Layer* ll = l; ll; ll = ll->parent()) - LOG(ERROR) << "L: " << ll << " " << ll->IsDrawn(); - return false; - } - - // Check if the size of the View and the Layer are in sync. - EXPECT_EQ(l->bounds(), v->bounds()); - if (v->bounds() != l->bounds()) - return false; - - if (v == view || l == layer) - return v == view && l == layer; - - v = NextView(v); - l = NextLayer(l); - } - - return false; -} - -// Constructs a View tree with the specified depth. -void ConstructTree(views::View* view, int depth) { - if (depth == 0) - return; - int count = base::RandInt(1, 5); - for (int i = 0; i < count; i++) { - views::View* v = new views::View; - view->AddChildView(v); - if (base::RandDouble() > 0.5) - v->SetPaintToLayer(true); - if (base::RandDouble() < 0.2) - v->SetVisible(false); - - ConstructTree(v, depth - 1); - } -} - -void ScrambleTree(views::View* view) { - int count = view->child_count(); - if (count == 0) - return; - for (int i = 0; i < count; i++) { - ScrambleTree(view->child_at(i)); - } - - if (count > 1) { - int a = base::RandInt(0, count - 1); - int b = base::RandInt(0, count - 1); - - views::View* view_a = view->child_at(a); - views::View* view_b = view->child_at(b); - view->ReorderChildView(view_a, b); - view->ReorderChildView(view_b, a); - } - - if (!view->layer() && base::RandDouble() < 0.1) - view->SetPaintToLayer(true); - - if (base::RandDouble() < 0.1) - view->SetVisible(!view->visible()); -} - -} // namespace - -namespace views { - -typedef ViewsTestBase ViewTest; - -// A derived class for testing purpose. -class TestView : public View { - public: - TestView() - : View(), - delete_on_pressed_(false), - native_theme_(NULL), - can_process_events_within_subtree_(true) {} - virtual ~TestView() {} - - // Reset all test state - void Reset() { - did_change_bounds_ = false; - last_mouse_event_type_ = 0; - location_.SetPoint(0, 0); - received_mouse_enter_ = false; - received_mouse_exit_ = false; - last_clip_.setEmpty(); - accelerator_count_map_.clear(); - can_process_events_within_subtree_ = true; - } - - // Exposed as public for testing. - void DoFocus() { - views::View::Focus(); - } - - void DoBlur() { - views::View::Blur(); - } - - bool focusable() const { return View::focusable(); } - - void set_can_process_events_within_subtree(bool can_process) { - can_process_events_within_subtree_ = can_process; - } - - virtual bool CanProcessEventsWithinSubtree() const override { - return can_process_events_within_subtree_; - } - - virtual void OnBoundsChanged(const gfx::Rect& previous_bounds) override; - virtual bool OnMousePressed(const ui::MouseEvent& event) override; - virtual bool OnMouseDragged(const ui::MouseEvent& event) override; - virtual void OnMouseReleased(const ui::MouseEvent& event) override; - virtual void OnMouseEntered(const ui::MouseEvent& event) override; - virtual void OnMouseExited(const ui::MouseEvent& event) override; - - virtual void Paint(gfx::Canvas* canvas, const CullSet& cull_set) override; - virtual void SchedulePaintInRect(const gfx::Rect& rect) override; - virtual bool AcceleratorPressed(const ui::Accelerator& accelerator) override; - - virtual void OnNativeThemeChanged(const ui::NativeTheme* native_theme) - override; - - // OnBoundsChanged. - bool did_change_bounds_; - gfx::Rect new_bounds_; - - // MouseEvent. - int last_mouse_event_type_; - gfx::Point location_; - bool received_mouse_enter_; - bool received_mouse_exit_; - bool delete_on_pressed_; - - // Painting. - std::vector<gfx::Rect> scheduled_paint_rects_; - - // Painting. - SkRect last_clip_; - - // Accelerators. - std::map<ui::Accelerator, int> accelerator_count_map_; - - // Native theme. - const ui::NativeTheme* native_theme_; - - // Value to return from CanProcessEventsWithinSubtree(). - bool can_process_events_within_subtree_; -}; - -//////////////////////////////////////////////////////////////////////////////// -// OnBoundsChanged -//////////////////////////////////////////////////////////////////////////////// - -void TestView::OnBoundsChanged(const gfx::Rect& previous_bounds) { - did_change_bounds_ = true; - new_bounds_ = bounds(); -} - -TEST_F(ViewTest, OnBoundsChanged) { - TestView v; - - gfx::Rect prev_rect(0, 0, 200, 200); - gfx::Rect new_rect(100, 100, 250, 250); - - v.SetBoundsRect(prev_rect); - v.Reset(); - v.SetBoundsRect(new_rect); - - EXPECT_TRUE(v.did_change_bounds_); - EXPECT_EQ(v.new_bounds_, new_rect); - EXPECT_EQ(v.bounds(), new_rect); -} - -//////////////////////////////////////////////////////////////////////////////// -// MouseEvent -//////////////////////////////////////////////////////////////////////////////// - -bool TestView::OnMousePressed(const ui::MouseEvent& event) { - last_mouse_event_type_ = event.type(); - location_.SetPoint(event.x(), event.y()); - if (delete_on_pressed_) - delete this; - return true; -} - -bool TestView::OnMouseDragged(const ui::MouseEvent& event) { - last_mouse_event_type_ = event.type(); - location_.SetPoint(event.x(), event.y()); - return true; -} - -void TestView::OnMouseReleased(const ui::MouseEvent& event) { - last_mouse_event_type_ = event.type(); - location_.SetPoint(event.x(), event.y()); -} - -void TestView::OnMouseEntered(const ui::MouseEvent& event) { - received_mouse_enter_ = true; -} - -void TestView::OnMouseExited(const ui::MouseEvent& event) { - received_mouse_exit_ = true; -} - -TEST_F(ViewTest, MouseEvent) { - TestView* v1 = new TestView(); - v1->SetBoundsRect(gfx::Rect(0, 0, 300, 300)); - - TestView* v2 = new TestView(); - v2->SetBoundsRect(gfx::Rect(100, 100, 100, 100)); - - scoped_ptr<Widget> widget(new Widget); - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.bounds = gfx::Rect(50, 50, 650, 650); - widget->Init(params); - internal::RootView* root = - static_cast<internal::RootView*>(widget->GetRootView()); - - root->AddChildView(v1); - v1->AddChildView(v2); - - v1->Reset(); - v2->Reset(); - - gfx::Point p1(110, 120); - ui::MouseEvent pressed(ui::ET_MOUSE_PRESSED, p1, p1, - ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); - root->OnMousePressed(pressed); - EXPECT_EQ(v2->last_mouse_event_type_, ui::ET_MOUSE_PRESSED); - EXPECT_EQ(v2->location_.x(), 10); - EXPECT_EQ(v2->location_.y(), 20); - // Make sure v1 did not receive the event - EXPECT_EQ(v1->last_mouse_event_type_, 0); - - // Drag event out of bounds. Should still go to v2 - v1->Reset(); - v2->Reset(); - gfx::Point p2(50, 40); - ui::MouseEvent dragged(ui::ET_MOUSE_DRAGGED, p2, p2, - ui::EF_LEFT_MOUSE_BUTTON, 0); - root->OnMouseDragged(dragged); - EXPECT_EQ(v2->last_mouse_event_type_, ui::ET_MOUSE_DRAGGED); - EXPECT_EQ(v2->location_.x(), -50); - EXPECT_EQ(v2->location_.y(), -60); - // Make sure v1 did not receive the event - EXPECT_EQ(v1->last_mouse_event_type_, 0); - - // Releasted event out of bounds. Should still go to v2 - v1->Reset(); - v2->Reset(); - ui::MouseEvent released(ui::ET_MOUSE_RELEASED, gfx::Point(), gfx::Point(), 0, - 0); - root->OnMouseReleased(released); - EXPECT_EQ(v2->last_mouse_event_type_, ui::ET_MOUSE_RELEASED); - EXPECT_EQ(v2->location_.x(), -100); - EXPECT_EQ(v2->location_.y(), -100); - // Make sure v1 did not receive the event - EXPECT_EQ(v1->last_mouse_event_type_, 0); - - widget->CloseNow(); -} - -// Confirm that a view can be deleted as part of processing a mouse press. -TEST_F(ViewTest, DeleteOnPressed) { - TestView* v1 = new TestView(); - v1->SetBoundsRect(gfx::Rect(0, 0, 300, 300)); - - TestView* v2 = new TestView(); - v2->SetBoundsRect(gfx::Rect(100, 100, 100, 100)); - - v1->Reset(); - v2->Reset(); - - scoped_ptr<Widget> widget(new Widget); - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.bounds = gfx::Rect(50, 50, 650, 650); - widget->Init(params); - View* root = widget->GetRootView(); - - root->AddChildView(v1); - v1->AddChildView(v2); - - v2->delete_on_pressed_ = true; - gfx::Point point(110, 120); - ui::MouseEvent pressed(ui::ET_MOUSE_PRESSED, point, point, - ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); - root->OnMousePressed(pressed); - EXPECT_EQ(0, v1->child_count()); - - widget->CloseNow(); -} - -//////////////////////////////////////////////////////////////////////////////// -// Painting -//////////////////////////////////////////////////////////////////////////////// - -void TestView::Paint(gfx::Canvas* canvas, const CullSet& cull_set) { - canvas->sk_canvas()->getClipBounds(&last_clip_); -} - -void TestView::SchedulePaintInRect(const gfx::Rect& rect) { - scheduled_paint_rects_.push_back(rect); - View::SchedulePaintInRect(rect); -} - -void CheckRect(const SkRect& check_rect, const SkRect& target_rect) { - EXPECT_EQ(target_rect.fLeft, check_rect.fLeft); - EXPECT_EQ(target_rect.fRight, check_rect.fRight); - EXPECT_EQ(target_rect.fTop, check_rect.fTop); - EXPECT_EQ(target_rect.fBottom, check_rect.fBottom); -} - -TEST_F(ViewTest, RemoveNotification) { - ViewStorage* vs = ViewStorage::GetInstance(); - Widget* widget = new Widget; - widget->Init(CreateParams(Widget::InitParams::TYPE_POPUP)); - View* root_view = widget->GetRootView(); - - View* v1 = new View; - int s1 = vs->CreateStorageID(); - vs->StoreView(s1, v1); - root_view->AddChildView(v1); - View* v11 = new View; - int s11 = vs->CreateStorageID(); - vs->StoreView(s11, v11); - v1->AddChildView(v11); - View* v111 = new View; - int s111 = vs->CreateStorageID(); - vs->StoreView(s111, v111); - v11->AddChildView(v111); - View* v112 = new View; - int s112 = vs->CreateStorageID(); - vs->StoreView(s112, v112); - v11->AddChildView(v112); - View* v113 = new View; - int s113 = vs->CreateStorageID(); - vs->StoreView(s113, v113); - v11->AddChildView(v113); - View* v1131 = new View; - int s1131 = vs->CreateStorageID(); - vs->StoreView(s1131, v1131); - v113->AddChildView(v1131); - View* v12 = new View; - int s12 = vs->CreateStorageID(); - vs->StoreView(s12, v12); - v1->AddChildView(v12); - - View* v2 = new View; - int s2 = vs->CreateStorageID(); - vs->StoreView(s2, v2); - root_view->AddChildView(v2); - View* v21 = new View; - int s21 = vs->CreateStorageID(); - vs->StoreView(s21, v21); - v2->AddChildView(v21); - View* v211 = new View; - int s211 = vs->CreateStorageID(); - vs->StoreView(s211, v211); - v21->AddChildView(v211); - - size_t stored_views = vs->view_count(); - - // Try removing a leaf view. - v21->RemoveChildView(v211); - EXPECT_EQ(stored_views - 1, vs->view_count()); - EXPECT_EQ(NULL, vs->RetrieveView(s211)); - delete v211; // We won't use this one anymore. - - // Now try removing a view with a hierarchy of depth 1. - v11->RemoveChildView(v113); - EXPECT_EQ(stored_views - 3, vs->view_count()); - EXPECT_EQ(NULL, vs->RetrieveView(s113)); - EXPECT_EQ(NULL, vs->RetrieveView(s1131)); - delete v113; // We won't use this one anymore. - - // Now remove even more. - root_view->RemoveChildView(v1); - EXPECT_EQ(NULL, vs->RetrieveView(s1)); - EXPECT_EQ(NULL, vs->RetrieveView(s11)); - EXPECT_EQ(NULL, vs->RetrieveView(s12)); - EXPECT_EQ(NULL, vs->RetrieveView(s111)); - EXPECT_EQ(NULL, vs->RetrieveView(s112)); - - // Put v1 back for more tests. - root_view->AddChildView(v1); - vs->StoreView(s1, v1); - - // Synchronously closing the window deletes the view hierarchy, which should - // remove all its views from ViewStorage. - widget->CloseNow(); - EXPECT_EQ(stored_views - 10, vs->view_count()); - EXPECT_EQ(NULL, vs->RetrieveView(s1)); - EXPECT_EQ(NULL, vs->RetrieveView(s12)); - EXPECT_EQ(NULL, vs->RetrieveView(s11)); - EXPECT_EQ(NULL, vs->RetrieveView(s12)); - EXPECT_EQ(NULL, vs->RetrieveView(s21)); - EXPECT_EQ(NULL, vs->RetrieveView(s111)); - EXPECT_EQ(NULL, vs->RetrieveView(s112)); -} - -namespace { - -void RotateCounterclockwise(gfx::Transform* transform) { - transform->matrix().set3x3(0, -1, 0, - 1, 0, 0, - 0, 0, 1); -} - -void RotateClockwise(gfx::Transform* transform) { - transform->matrix().set3x3( 0, 1, 0, - -1, 0, 0, - 0, 0, 1); -} - -} // namespace - -// Tests the correctness of the rect-based targeting algorithm implemented in -// View::GetEventHandlerForRect(). See http://goo.gl/3Jp2BD for a description -// of rect-based targeting. -TEST_F(ViewTest, GetEventHandlerForRect) { - Widget* widget = new Widget; - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - widget->Init(params); - View* root_view = widget->GetRootView(); - root_view->SetBoundsRect(gfx::Rect(0, 0, 500, 500)); - - // Have this hierarchy of views (the coordinates here are all in - // the root view's coordinate space): - // v1 (0, 0, 100, 100) - // v2 (150, 0, 250, 100) - // v3 (0, 200, 150, 100) - // v31 (10, 210, 80, 80) - // v32 (110, 210, 30, 80) - // v4 (300, 200, 100, 100) - // v41 (310, 210, 80, 80) - // v411 (370, 275, 10, 5) - // v5 (450, 197, 30, 36) - // v51 (450, 200, 30, 30) - - // The coordinates used for SetBounds are in parent coordinates. - - TestView* v1 = new TestView; - v1->SetBounds(0, 0, 100, 100); - root_view->AddChildView(v1); - - TestView* v2 = new TestView; - v2->SetBounds(150, 0, 250, 100); - root_view->AddChildView(v2); - - TestView* v3 = new TestView; - v3->SetBounds(0, 200, 150, 100); - root_view->AddChildView(v3); - - TestView* v4 = new TestView; - v4->SetBounds(300, 200, 100, 100); - root_view->AddChildView(v4); - - TestView* v31 = new TestView; - v31->SetBounds(10, 10, 80, 80); - v3->AddChildView(v31); - - TestView* v32 = new TestView; - v32->SetBounds(110, 10, 30, 80); - v3->AddChildView(v32); - - TestView* v41 = new TestView; - v41->SetBounds(10, 10, 80, 80); - v4->AddChildView(v41); - - TestView* v411 = new TestView; - v411->SetBounds(60, 65, 10, 5); - v41->AddChildView(v411); - - TestView* v5 = new TestView; - v5->SetBounds(450, 197, 30, 36); - root_view->AddChildView(v5); - - TestView* v51 = new TestView; - v51->SetBounds(0, 3, 30, 30); - v5->AddChildView(v51); - - // |touch_rect| does not intersect any descendant view of |root_view|. - gfx::Rect touch_rect(105, 105, 30, 45); - View* result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(root_view, result_view); - result_view = NULL; - - // Covers |v1| by at least 60%. - touch_rect.SetRect(15, 15, 100, 100); - result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(v1, result_view); - result_view = NULL; - - // Intersects |v1| but does not cover it by at least 60%. The center - // of |touch_rect| is within |v1|. - touch_rect.SetRect(50, 50, 5, 10); - result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(v1, result_view); - result_view = NULL; - - // Intersects |v1| but does not cover it by at least 60%. The center - // of |touch_rect| is not within |v1|. - touch_rect.SetRect(95, 96, 21, 22); - result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(root_view, result_view); - result_view = NULL; - - // Intersects |v1| and |v2|, but only covers |v2| by at least 60%. - touch_rect.SetRect(95, 10, 300, 120); - result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(v2, result_view); - result_view = NULL; - - // Covers both |v1| and |v2| by at least 60%, but the center point - // of |touch_rect| is closer to the center point of |v2|. - touch_rect.SetRect(20, 20, 400, 100); - result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(v2, result_view); - result_view = NULL; - - // Covers both |v1| and |v2| by at least 60%, but the center point - // of |touch_rect| is closer to the center point of |v1|. - touch_rect.SetRect(-700, -15, 1050, 110); - result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(v1, result_view); - result_view = NULL; - - // A mouse click within |v1| will target |v1|. - touch_rect.SetRect(15, 15, 1, 1); - result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(v1, result_view); - result_view = NULL; - - // Intersects |v3| and |v31| by at least 60% and the center point - // of |touch_rect| is closer to the center point of |v31|. - touch_rect.SetRect(0, 200, 110, 100); - result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(v31, result_view); - result_view = NULL; - - // Intersects |v3| and |v31|, but neither by at least 60%. The - // center point of |touch_rect| lies within |v31|. - touch_rect.SetRect(80, 280, 15, 15); - result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(v31, result_view); - result_view = NULL; - - // Covers |v3|, |v31|, and |v32| all by at least 60%, and the - // center point of |touch_rect| is closest to the center point - // of |v32|. - touch_rect.SetRect(0, 200, 200, 100); - result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(v32, result_view); - result_view = NULL; - - // Intersects all of |v3|, |v31|, and |v32|, but only covers - // |v31| and |v32| by at least 60%. The center point of - // |touch_rect| is closest to the center point of |v32|. - touch_rect.SetRect(30, 225, 180, 115); - result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(v32, result_view); - result_view = NULL; - - // A mouse click at the corner of |v3| will target |v3|. - touch_rect.SetRect(0, 200, 1, 1); - result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(v3, result_view); - result_view = NULL; - - // A mouse click within |v32| will target |v32|. - touch_rect.SetRect(112, 211, 1, 1); - result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(v32, result_view); - result_view = NULL; - - // Covers all of |v4|, |v41|, and |v411| by at least 60%. - // The center point of |touch_rect| is equally close to - // the center points of |v4| and |v41|. - touch_rect.SetRect(310, 210, 80, 80); - result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(v41, result_view); - result_view = NULL; - - // Intersects all of |v4|, |v41|, and |v411| but only covers - // |v411| by at least 60%. - touch_rect.SetRect(370, 275, 7, 5); - result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(v411, result_view); - result_view = NULL; - - // Intersects |v4| and |v41| but covers neither by at least 60%. - // The center point of |touch_rect| is equally close to the center - // points of |v4| and |v41|. - touch_rect.SetRect(345, 245, 7, 7); - result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(v41, result_view); - result_view = NULL; - - // Intersects all of |v4|, |v41|, and |v411| and covers none of - // them by at least 60%. The center point of |touch_rect| lies - // within |v411|. - touch_rect.SetRect(368, 272, 4, 6); - result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(v411, result_view); - result_view = NULL; - - // Intersects all of |v4|, |v41|, and |v411| and covers none of - // them by at least 60%. The center point of |touch_rect| lies - // within |v41|. - touch_rect.SetRect(365, 270, 7, 7); - result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(v41, result_view); - result_view = NULL; - - // Intersects all of |v4|, |v41|, and |v411| and covers none of - // them by at least 60%. The center point of |touch_rect| lies - // within |v4|. - touch_rect.SetRect(205, 275, 200, 2); - result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(v4, result_view); - result_view = NULL; - - // Intersects all of |v4|, |v41|, and |v411| but only covers - // |v41| by at least 60%. - touch_rect.SetRect(310, 210, 61, 66); - result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(v41, result_view); - result_view = NULL; - - // A mouse click within |v411| will target |v411|. - touch_rect.SetRect(372, 275, 1, 1); - result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(v411, result_view); - result_view = NULL; - - // A mouse click within |v41| will target |v41|. - touch_rect.SetRect(350, 215, 1, 1); - result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(v41, result_view); - result_view = NULL; - - // Covers |v3|, |v4|, and all of their descendants by at - // least 60%. The center point of |touch_rect| is closest - // to the center point of |v32|. - touch_rect.SetRect(0, 200, 400, 100); - result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(v32, result_view); - result_view = NULL; - - // Intersects all of |v2|, |v3|, |v32|, |v4|, |v41|, and |v411|. - // Covers |v2|, |v32|, |v4|, |v41|, and |v411| by at least 60%. - // The center point of |touch_rect| is closest to the center - // point of |root_view|. - touch_rect.SetRect(110, 15, 375, 450); - result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(root_view, result_view); - result_view = NULL; - - // Covers all views (except |v5| and |v51|) by at least 60%. The - // center point of |touch_rect| is equally close to the center - // points of |v2| and |v32|. One is not a descendant of the other, - // so in this case the view selected is arbitrary (i.e., - // it depends only on the ordering of nodes in the views - // hierarchy). - touch_rect.SetRect(0, 0, 400, 300); - result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(v32, result_view); - result_view = NULL; - - // Covers |v5| and |v51| by at least 60%, and the center point of - // the touch is located within both views. Since both views share - // the same center point, the child view should be selected. - touch_rect.SetRect(440, 190, 40, 40); - result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(v51, result_view); - result_view = NULL; - - // Covers |v5| and |v51| by at least 60%, but the center point of - // the touch is not located within either view. Since both views - // share the same center point, the child view should be selected. - touch_rect.SetRect(455, 187, 60, 60); - result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(v51, result_view); - result_view = NULL; - - // Covers neither |v5| nor |v51| by at least 60%, but the center - // of the touch is located within |v51|. - touch_rect.SetRect(450, 197, 10, 10); - result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(v51, result_view); - result_view = NULL; - - // Covers neither |v5| nor |v51| by at least 60% but intersects both. - // The center point is located outside of both views. - touch_rect.SetRect(433, 180, 24, 24); - result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(root_view, result_view); - result_view = NULL; - - // Only intersects |v5| but does not cover it by at least 60%. The - // center point of the touch region is located within |v5|. - touch_rect.SetRect(449, 196, 3, 3); - result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(v5, result_view); - result_view = NULL; - - // A mouse click within |v5| (but not |v51|) should target |v5|. - touch_rect.SetRect(462, 199, 1, 1); - result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(v5, result_view); - result_view = NULL; - - // A mouse click |v5| and |v51| should target the child view. - touch_rect.SetRect(452, 226, 1, 1); - result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(v51, result_view); - result_view = NULL; - - // A mouse click on the center of |v5| and |v51| should target - // the child view. - touch_rect.SetRect(465, 215, 1, 1); - result_view = root_view->GetEventHandlerForRect(touch_rect); - EXPECT_EQ(v51, result_view); - result_view = NULL; - - widget->CloseNow(); -} - -// Tests that GetEventHandlerForRect() and GetTooltipHandlerForPoint() behave -// as expected when different views in the view hierarchy return false -// when CanProcessEventsWithinSubtree() is called. -TEST_F(ViewTest, CanProcessEventsWithinSubtree) { - Widget* widget = new Widget; - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - widget->Init(params); - View* root_view = widget->GetRootView(); - root_view->SetBoundsRect(gfx::Rect(0, 0, 500, 500)); - - // Have this hierarchy of views (the coords here are in the coordinate - // space of the root view): - // v (0, 0, 100, 100) - // - v_child (0, 0, 20, 30) - // - v_grandchild (5, 5, 5, 15) - - TestView* v = new TestView; - v->SetBounds(0, 0, 100, 100); - root_view->AddChildView(v); - v->set_notify_enter_exit_on_child(true); - - TestView* v_child = new TestView; - v_child->SetBounds(0, 0, 20, 30); - v->AddChildView(v_child); - - TestView* v_grandchild = new TestView; - v_grandchild->SetBounds(5, 5, 5, 15); - v_child->AddChildView(v_grandchild); - - v->Reset(); - v_child->Reset(); - v_grandchild->Reset(); - - // Define rects and points within the views in the hierarchy. - gfx::Rect rect_in_v_grandchild(7, 7, 3, 3); - gfx::Point point_in_v_grandchild(rect_in_v_grandchild.origin()); - gfx::Rect rect_in_v_child(12, 3, 5, 5); - gfx::Point point_in_v_child(rect_in_v_child.origin()); - gfx::Rect rect_in_v(50, 50, 25, 30); - gfx::Point point_in_v(rect_in_v.origin()); - - // When all three views return true when CanProcessEventsWithinSubtree() - // is called, targeting should behave as expected. - - View* result_view = root_view->GetEventHandlerForRect(rect_in_v_grandchild); - EXPECT_EQ(v_grandchild, result_view); - result_view = NULL; - result_view = root_view->GetTooltipHandlerForPoint(point_in_v_grandchild); - EXPECT_EQ(v_grandchild, result_view); - result_view = NULL; - - result_view = root_view->GetEventHandlerForRect(rect_in_v_child); - EXPECT_EQ(v_child, result_view); - result_view = NULL; - result_view = root_view->GetTooltipHandlerForPoint(point_in_v_child); - EXPECT_EQ(v_child, result_view); - result_view = NULL; - - result_view = root_view->GetEventHandlerForRect(rect_in_v); - EXPECT_EQ(v, result_view); - result_view = NULL; - result_view = root_view->GetTooltipHandlerForPoint(point_in_v); - EXPECT_EQ(v, result_view); - result_view = NULL; - - // When |v_grandchild| returns false when CanProcessEventsWithinSubtree() - // is called, then |v_grandchild| cannot be returned as a target. - - v_grandchild->set_can_process_events_within_subtree(false); - - result_view = root_view->GetEventHandlerForRect(rect_in_v_grandchild); - EXPECT_EQ(v_child, result_view); - result_view = NULL; - result_view = root_view->GetTooltipHandlerForPoint(point_in_v_grandchild); - EXPECT_EQ(v_child, result_view); - result_view = NULL; - - result_view = root_view->GetEventHandlerForRect(rect_in_v_child); - EXPECT_EQ(v_child, result_view); - result_view = NULL; - result_view = root_view->GetTooltipHandlerForPoint(point_in_v_child); - EXPECT_EQ(v_child, result_view); - result_view = NULL; - - result_view = root_view->GetEventHandlerForRect(rect_in_v); - EXPECT_EQ(v, result_view); - result_view = NULL; - result_view = root_view->GetTooltipHandlerForPoint(point_in_v); - EXPECT_EQ(v, result_view); - - // When |v_grandchild| returns false when CanProcessEventsWithinSubtree() - // is called, then NULL should be returned as a target if we call - // GetTooltipHandlerForPoint() with |v_grandchild| as the root of the - // views tree. Note that the location must be in the coordinate space - // of the root view (|v_grandchild| in this case), so use (1, 1). - - result_view = v_grandchild; - result_view = v_grandchild->GetTooltipHandlerForPoint(gfx::Point(1, 1)); - EXPECT_EQ(NULL, result_view); - result_view = NULL; - - // When |v_child| returns false when CanProcessEventsWithinSubtree() - // is called, then neither |v_child| nor |v_grandchild| can be returned - // as a target (|v| should be returned as the target for each case). - - v_grandchild->Reset(); - v_child->set_can_process_events_within_subtree(false); - - result_view = root_view->GetEventHandlerForRect(rect_in_v_grandchild); - EXPECT_EQ(v, result_view); - result_view = NULL; - result_view = root_view->GetTooltipHandlerForPoint(point_in_v_grandchild); - EXPECT_EQ(v, result_view); - result_view = NULL; - - result_view = root_view->GetEventHandlerForRect(rect_in_v_child); - EXPECT_EQ(v, result_view); - result_view = NULL; - result_view = root_view->GetTooltipHandlerForPoint(point_in_v_child); - EXPECT_EQ(v, result_view); - result_view = NULL; - - result_view = root_view->GetEventHandlerForRect(rect_in_v); - EXPECT_EQ(v, result_view); - result_view = NULL; - result_view = root_view->GetTooltipHandlerForPoint(point_in_v); - EXPECT_EQ(v, result_view); - result_view = NULL; - - // When |v| returns false when CanProcessEventsWithinSubtree() - // is called, then none of |v|, |v_child|, and |v_grandchild| can be returned - // as a target (|root_view| should be returned as the target for each case). - - v_child->Reset(); - v->set_can_process_events_within_subtree(false); - - result_view = root_view->GetEventHandlerForRect(rect_in_v_grandchild); - EXPECT_EQ(root_view, result_view); - result_view = NULL; - result_view = root_view->GetTooltipHandlerForPoint(point_in_v_grandchild); - EXPECT_EQ(root_view, result_view); - result_view = NULL; - - result_view = root_view->GetEventHandlerForRect(rect_in_v_child); - EXPECT_EQ(root_view, result_view); - result_view = NULL; - result_view = root_view->GetTooltipHandlerForPoint(point_in_v_child); - EXPECT_EQ(root_view, result_view); - result_view = NULL; - - result_view = root_view->GetEventHandlerForRect(rect_in_v); - EXPECT_EQ(root_view, result_view); - result_view = NULL; - result_view = root_view->GetTooltipHandlerForPoint(point_in_v); - EXPECT_EQ(root_view, result_view); -} - -TEST_F(ViewTest, NotifyEnterExitOnChild) { - Widget* widget = new Widget; - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - widget->Init(params); - View* root_view = widget->GetRootView(); - root_view->SetBoundsRect(gfx::Rect(0, 0, 500, 500)); - - // Have this hierarchy of views (the coords here are in root coord): - // v1 (0, 0, 100, 100) - // - v11 (0, 0, 20, 30) - // - v111 (5, 5, 5, 15) - // - v12 (50, 10, 30, 90) - // - v121 (60, 20, 10, 10) - // v2 (105, 0, 100, 100) - // - v21 (120, 10, 50, 20) - - TestView* v1 = new TestView; - v1->SetBounds(0, 0, 100, 100); - root_view->AddChildView(v1); - v1->set_notify_enter_exit_on_child(true); - - TestView* v11 = new TestView; - v11->SetBounds(0, 0, 20, 30); - v1->AddChildView(v11); - - TestView* v111 = new TestView; - v111->SetBounds(5, 5, 5, 15); - v11->AddChildView(v111); - - TestView* v12 = new TestView; - v12->SetBounds(50, 10, 30, 90); - v1->AddChildView(v12); - - TestView* v121 = new TestView; - v121->SetBounds(10, 10, 10, 10); - v12->AddChildView(v121); - - TestView* v2 = new TestView; - v2->SetBounds(105, 0, 100, 100); - root_view->AddChildView(v2); - - TestView* v21 = new TestView; - v21->SetBounds(15, 10, 50, 20); - v2->AddChildView(v21); - - v1->Reset(); - v11->Reset(); - v111->Reset(); - v12->Reset(); - v121->Reset(); - v2->Reset(); - v21->Reset(); - - // Move the mouse in v111. - gfx::Point p1(6, 6); - ui::MouseEvent move1(ui::ET_MOUSE_MOVED, p1, p1, 0, 0); - root_view->OnMouseMoved(move1); - EXPECT_TRUE(v111->received_mouse_enter_); - EXPECT_FALSE(v11->last_mouse_event_type_); - EXPECT_TRUE(v1->received_mouse_enter_); - - v111->Reset(); - v1->Reset(); - - // Now, move into v121. - gfx::Point p2(65, 21); - ui::MouseEvent move2(ui::ET_MOUSE_MOVED, p2, p2, 0, 0); - root_view->OnMouseMoved(move2); - EXPECT_TRUE(v111->received_mouse_exit_); - EXPECT_TRUE(v121->received_mouse_enter_); - EXPECT_FALSE(v1->last_mouse_event_type_); - - v111->Reset(); - v121->Reset(); - - // Now, move into v11. - gfx::Point p3(1, 1); - ui::MouseEvent move3(ui::ET_MOUSE_MOVED, p3, p3, 0, 0); - root_view->OnMouseMoved(move3); - EXPECT_TRUE(v121->received_mouse_exit_); - EXPECT_TRUE(v11->received_mouse_enter_); - EXPECT_FALSE(v1->last_mouse_event_type_); - - v121->Reset(); - v11->Reset(); - - // Move to v21. - gfx::Point p4(121, 15); - ui::MouseEvent move4(ui::ET_MOUSE_MOVED, p4, p4, 0, 0); - root_view->OnMouseMoved(move4); - EXPECT_TRUE(v21->received_mouse_enter_); - EXPECT_FALSE(v2->last_mouse_event_type_); - EXPECT_TRUE(v11->received_mouse_exit_); - EXPECT_TRUE(v1->received_mouse_exit_); - - v21->Reset(); - v11->Reset(); - v1->Reset(); - - // Move to v1. - gfx::Point p5(21, 0); - ui::MouseEvent move5(ui::ET_MOUSE_MOVED, p5, p5, 0, 0); - root_view->OnMouseMoved(move5); - EXPECT_TRUE(v21->received_mouse_exit_); - EXPECT_TRUE(v1->received_mouse_enter_); - - v21->Reset(); - v1->Reset(); - - // Now, move into v11. - gfx::Point p6(15, 15); - ui::MouseEvent mouse6(ui::ET_MOUSE_MOVED, p6, p6, 0, 0); - root_view->OnMouseMoved(mouse6); - EXPECT_TRUE(v11->received_mouse_enter_); - EXPECT_FALSE(v1->last_mouse_event_type_); - - v11->Reset(); - v1->Reset(); - - // Move back into v1. Although |v1| had already received an ENTER for mouse6, - // and the mouse remains inside |v1| the whole time, it receives another ENTER - // when the mouse leaves v11. - gfx::Point p7(21, 0); - ui::MouseEvent mouse7(ui::ET_MOUSE_MOVED, p7, p7, 0, 0); - root_view->OnMouseMoved(mouse7); - EXPECT_TRUE(v11->received_mouse_exit_); - EXPECT_FALSE(v1->received_mouse_enter_); - - widget->CloseNow(); -} - -TEST_F(ViewTest, Textfield) { - const base::string16 kText = ASCIIToUTF16( - "Reality is that which, when you stop believing it, doesn't go away."); - const base::string16 kExtraText = ASCIIToUTF16("Pretty deep, Philip!"); - - Widget* widget = new Widget; - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.bounds = gfx::Rect(0, 0, 100, 100); - widget->Init(params); - View* root_view = widget->GetRootView(); - - Textfield* textfield = new Textfield(); - root_view->AddChildView(textfield); - - // Test setting, appending text. - textfield->SetText(kText); - EXPECT_EQ(kText, textfield->text()); - textfield->AppendText(kExtraText); - EXPECT_EQ(kText + kExtraText, textfield->text()); - textfield->SetText(base::string16()); - EXPECT_TRUE(textfield->text().empty()); - - // Test selection related methods. - textfield->SetText(kText); - EXPECT_TRUE(textfield->GetSelectedText().empty()); - textfield->SelectAll(false); - EXPECT_EQ(kText, textfield->text()); - textfield->ClearSelection(); - EXPECT_TRUE(textfield->GetSelectedText().empty()); - - widget->CloseNow(); -} - -// Tests that the Textfield view respond appropiately to cut/copy/paste. -TEST_F(ViewTest, TextfieldCutCopyPaste) { - const base::string16 kNormalText = ASCIIToUTF16("Normal"); - const base::string16 kReadOnlyText = ASCIIToUTF16("Read only"); - const base::string16 kPasswordText = - ASCIIToUTF16("Password! ** Secret stuff **"); - - ui::Clipboard* clipboard = ui::Clipboard::GetForCurrentThread(); - - Widget* widget = new Widget; - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.bounds = gfx::Rect(0, 0, 100, 100); - widget->Init(params); - View* root_view = widget->GetRootView(); - - Textfield* normal = new Textfield(); - Textfield* read_only = new Textfield(); - read_only->SetReadOnly(true); - Textfield* password = new Textfield(); - password->SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD); - - root_view->AddChildView(normal); - root_view->AddChildView(read_only); - root_view->AddChildView(password); - - normal->SetText(kNormalText); - read_only->SetText(kReadOnlyText); - password->SetText(kPasswordText); - - // - // Test cut. - // - - normal->SelectAll(false); - normal->ExecuteCommand(IDS_APP_CUT); - base::string16 result; - clipboard->ReadText(ui::CLIPBOARD_TYPE_COPY_PASTE, &result); - EXPECT_EQ(kNormalText, result); - normal->SetText(kNormalText); // Let's revert to the original content. - - read_only->SelectAll(false); - read_only->ExecuteCommand(IDS_APP_CUT); - result.clear(); - clipboard->ReadText(ui::CLIPBOARD_TYPE_COPY_PASTE, &result); - // Cut should have failed, so the clipboard content should not have changed. - EXPECT_EQ(kNormalText, result); - - password->SelectAll(false); - password->ExecuteCommand(IDS_APP_CUT); - result.clear(); - clipboard->ReadText(ui::CLIPBOARD_TYPE_COPY_PASTE, &result); - // Cut should have failed, so the clipboard content should not have changed. - EXPECT_EQ(kNormalText, result); - - // - // Test copy. - // - - // Start with |read_only| to observe a change in clipboard text. - read_only->SelectAll(false); - read_only->ExecuteCommand(IDS_APP_COPY); - result.clear(); - clipboard->ReadText(ui::CLIPBOARD_TYPE_COPY_PASTE, &result); - EXPECT_EQ(kReadOnlyText, result); - - normal->SelectAll(false); - normal->ExecuteCommand(IDS_APP_COPY); - result.clear(); - clipboard->ReadText(ui::CLIPBOARD_TYPE_COPY_PASTE, &result); - EXPECT_EQ(kNormalText, result); - - password->SelectAll(false); - password->ExecuteCommand(IDS_APP_COPY); - result.clear(); - clipboard->ReadText(ui::CLIPBOARD_TYPE_COPY_PASTE, &result); - // Text cannot be copied from an obscured field; the clipboard won't change. - EXPECT_EQ(kNormalText, result); - - // - // Test paste. - // - - // Attempting to paste kNormalText in a read-only text-field should fail. - read_only->SelectAll(false); - read_only->ExecuteCommand(IDS_APP_PASTE); - EXPECT_EQ(kReadOnlyText, read_only->text()); - - password->SelectAll(false); - password->ExecuteCommand(IDS_APP_PASTE); - EXPECT_EQ(kNormalText, password->text()); - - // Copy from |read_only| to observe a change in the normal textfield text. - read_only->SelectAll(false); - read_only->ExecuteCommand(IDS_APP_COPY); - normal->SelectAll(false); - normal->ExecuteCommand(IDS_APP_PASTE); - EXPECT_EQ(kReadOnlyText, normal->text()); - widget->CloseNow(); -} - -//////////////////////////////////////////////////////////////////////////////// -// Accelerators -//////////////////////////////////////////////////////////////////////////////// -bool TestView::AcceleratorPressed(const ui::Accelerator& accelerator) { - accelerator_count_map_[accelerator]++; - return true; -} - -// TODO: these tests were initially commented out when getting aura to -// run. Figure out if still valuable and either nuke or fix. -#if 0 -TEST_F(ViewTest, ActivateAccelerator) { - // Register a keyboard accelerator before the view is added to a window. - ui::Accelerator return_accelerator(ui::VKEY_RETURN, ui::EF_NONE); - TestView* view = new TestView(); - view->Reset(); - view->AddAccelerator(return_accelerator); - EXPECT_EQ(view->accelerator_count_map_[return_accelerator], 0); - - // Create a window and add the view as its child. - scoped_ptr<Widget> widget(new Widget); - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.bounds = gfx::Rect(0, 0, 100, 100); - widget->Init(params); - View* root = widget->GetRootView(); - root->AddChildView(view); - widget->Show(); - - // Get the focus manager. - FocusManager* focus_manager = widget->GetFocusManager(); - ASSERT_TRUE(focus_manager); - - // Hit the return key and see if it takes effect. - EXPECT_TRUE(focus_manager->ProcessAccelerator(return_accelerator)); - EXPECT_EQ(view->accelerator_count_map_[return_accelerator], 1); - - // Hit the escape key. Nothing should happen. - ui::Accelerator escape_accelerator(ui::VKEY_ESCAPE, ui::EF_NONE); - EXPECT_FALSE(focus_manager->ProcessAccelerator(escape_accelerator)); - EXPECT_EQ(view->accelerator_count_map_[return_accelerator], 1); - EXPECT_EQ(view->accelerator_count_map_[escape_accelerator], 0); - - // Now register the escape key and hit it again. - view->AddAccelerator(escape_accelerator); - EXPECT_TRUE(focus_manager->ProcessAccelerator(escape_accelerator)); - EXPECT_EQ(view->accelerator_count_map_[return_accelerator], 1); - EXPECT_EQ(view->accelerator_count_map_[escape_accelerator], 1); - - // Remove the return key accelerator. - view->RemoveAccelerator(return_accelerator); - EXPECT_FALSE(focus_manager->ProcessAccelerator(return_accelerator)); - EXPECT_EQ(view->accelerator_count_map_[return_accelerator], 1); - EXPECT_EQ(view->accelerator_count_map_[escape_accelerator], 1); - - // Add it again. Hit the return key and the escape key. - view->AddAccelerator(return_accelerator); - EXPECT_TRUE(focus_manager->ProcessAccelerator(return_accelerator)); - EXPECT_EQ(view->accelerator_count_map_[return_accelerator], 2); - EXPECT_EQ(view->accelerator_count_map_[escape_accelerator], 1); - EXPECT_TRUE(focus_manager->ProcessAccelerator(escape_accelerator)); - EXPECT_EQ(view->accelerator_count_map_[return_accelerator], 2); - EXPECT_EQ(view->accelerator_count_map_[escape_accelerator], 2); - - // Remove all the accelerators. - view->ResetAccelerators(); - EXPECT_FALSE(focus_manager->ProcessAccelerator(return_accelerator)); - EXPECT_EQ(view->accelerator_count_map_[return_accelerator], 2); - EXPECT_EQ(view->accelerator_count_map_[escape_accelerator], 2); - EXPECT_FALSE(focus_manager->ProcessAccelerator(escape_accelerator)); - EXPECT_EQ(view->accelerator_count_map_[return_accelerator], 2); - EXPECT_EQ(view->accelerator_count_map_[escape_accelerator], 2); - - widget->CloseNow(); -} - -TEST_F(ViewTest, HiddenViewWithAccelerator) { - ui::Accelerator return_accelerator(ui::VKEY_RETURN, ui::EF_NONE); - TestView* view = new TestView(); - view->Reset(); - view->AddAccelerator(return_accelerator); - EXPECT_EQ(view->accelerator_count_map_[return_accelerator], 0); - - scoped_ptr<Widget> widget(new Widget); - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.bounds = gfx::Rect(0, 0, 100, 100); - widget->Init(params); - View* root = widget->GetRootView(); - root->AddChildView(view); - widget->Show(); - - FocusManager* focus_manager = widget->GetFocusManager(); - ASSERT_TRUE(focus_manager); - - view->SetVisible(false); - EXPECT_FALSE(focus_manager->ProcessAccelerator(return_accelerator)); - - view->SetVisible(true); - EXPECT_TRUE(focus_manager->ProcessAccelerator(return_accelerator)); - - widget->CloseNow(); -} - -TEST_F(ViewTest, ViewInHiddenWidgetWithAccelerator) { - ui::Accelerator return_accelerator(ui::VKEY_RETURN, ui::EF_NONE); - TestView* view = new TestView(); - view->Reset(); - view->AddAccelerator(return_accelerator); - EXPECT_EQ(view->accelerator_count_map_[return_accelerator], 0); - - scoped_ptr<Widget> widget(new Widget); - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.bounds = gfx::Rect(0, 0, 100, 100); - widget->Init(params); - View* root = widget->GetRootView(); - root->AddChildView(view); - - FocusManager* focus_manager = widget->GetFocusManager(); - ASSERT_TRUE(focus_manager); - - EXPECT_FALSE(focus_manager->ProcessAccelerator(return_accelerator)); - EXPECT_EQ(0, view->accelerator_count_map_[return_accelerator]); - - widget->Show(); - EXPECT_TRUE(focus_manager->ProcessAccelerator(return_accelerator)); - EXPECT_EQ(1, view->accelerator_count_map_[return_accelerator]); - - widget->Hide(); - EXPECT_FALSE(focus_manager->ProcessAccelerator(return_accelerator)); - EXPECT_EQ(1, view->accelerator_count_map_[return_accelerator]); - - widget->CloseNow(); -} - -//////////////////////////////////////////////////////////////////////////////// -// Mouse-wheel message rerouting -//////////////////////////////////////////////////////////////////////////////// -class ScrollableTestView : public View { - public: - ScrollableTestView() { } - - virtual gfx::Size GetPreferredSize() { - return gfx::Size(100, 10000); - } - - virtual void Layout() { - SizeToPreferredSize(); - } -}; - -class TestViewWithControls : public View { - public: - TestViewWithControls() { - text_field_ = new Textfield(); - AddChildView(text_field_); - } - - Textfield* text_field_; -}; - -class SimpleWidgetDelegate : public WidgetDelegate { - public: - explicit SimpleWidgetDelegate(View* contents) : contents_(contents) { } - - virtual void DeleteDelegate() { delete this; } - - virtual View* GetContentsView() { return contents_; } - - virtual Widget* GetWidget() { return contents_->GetWidget(); } - virtual const Widget* GetWidget() const { return contents_->GetWidget(); } - - private: - View* contents_; -}; - -// Tests that the mouse-wheel messages are correctly rerouted to the window -// under the mouse. -// TODO(jcampan): http://crbug.com/10572 Disabled as it fails on the Vista build -// bot. -// Note that this fails for a variety of reasons: -// - focused view is apparently reset across window activations and never -// properly restored -// - this test depends on you not having any other window visible open under the -// area that it opens the test windows. --beng -TEST_F(ViewTest, DISABLED_RerouteMouseWheelTest) { - TestViewWithControls* view_with_controls = new TestViewWithControls(); - Widget* window1 = Widget::CreateWindowWithBounds( - new SimpleWidgetDelegate(view_with_controls), - gfx::Rect(0, 0, 100, 100)); - window1->Show(); - ScrollView* scroll_view = new ScrollView(); - scroll_view->SetContents(new ScrollableTestView()); - Widget* window2 = Widget::CreateWindowWithBounds( - new SimpleWidgetDelegate(scroll_view), - gfx::Rect(200, 200, 100, 100)); - window2->Show(); - EXPECT_EQ(0, scroll_view->GetVisibleRect().y()); - - // Make the window1 active, as this is what it would be in real-world. - window1->Activate(); - - // Let's send a mouse-wheel message to the different controls and check that - // it is rerouted to the window under the mouse (effectively scrolling the - // scroll-view). - - // First to the Window's HWND. - ::SendMessage(view_with_controls->GetWidget()->GetNativeView(), - WM_MOUSEWHEEL, MAKEWPARAM(0, -20), MAKELPARAM(250, 250)); - EXPECT_EQ(20, scroll_view->GetVisibleRect().y()); - - window1->CloseNow(); - window2->CloseNow(); -} -#endif // 0 - -//////////////////////////////////////////////////////////////////////////////// -// Native view hierachy -//////////////////////////////////////////////////////////////////////////////// -class ToplevelWidgetObserverView : public View { - public: - ToplevelWidgetObserverView() : toplevel_(NULL) { - } - virtual ~ToplevelWidgetObserverView() { - } - - // View overrides: - virtual void ViewHierarchyChanged( - const ViewHierarchyChangedDetails& details) override { - if (details.is_add) { - toplevel_ = GetWidget() ? GetWidget()->GetTopLevelWidget() : NULL; - } else { - toplevel_ = NULL; - } - } - virtual void NativeViewHierarchyChanged() override { - toplevel_ = GetWidget() ? GetWidget()->GetTopLevelWidget() : NULL; - } - - Widget* toplevel() { return toplevel_; } - - private: - Widget* toplevel_; - - DISALLOW_COPY_AND_ASSIGN(ToplevelWidgetObserverView); -}; - -// Test that a view can track the current top level widget by overriding -// View::ViewHierarchyChanged() and View::NativeViewHierarchyChanged(). -TEST_F(ViewTest, NativeViewHierarchyChanged) { - scoped_ptr<Widget> toplevel1(new Widget); - Widget::InitParams toplevel1_params = - CreateParams(Widget::InitParams::TYPE_POPUP); - toplevel1_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - toplevel1->Init(toplevel1_params); - - scoped_ptr<Widget> toplevel2(new Widget); - Widget::InitParams toplevel2_params = - CreateParams(Widget::InitParams::TYPE_POPUP); - toplevel2_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - toplevel2->Init(toplevel2_params); - - Widget* child = new Widget; - Widget::InitParams child_params(Widget::InitParams::TYPE_CONTROL); - child_params.parent = toplevel1->GetNativeView(); - child->Init(child_params); - - ToplevelWidgetObserverView* observer_view = - new ToplevelWidgetObserverView(); - EXPECT_EQ(NULL, observer_view->toplevel()); - - child->SetContentsView(observer_view); - EXPECT_EQ(toplevel1, observer_view->toplevel()); - - Widget::ReparentNativeView(child->GetNativeView(), - toplevel2->GetNativeView()); - EXPECT_EQ(toplevel2, observer_view->toplevel()); - - observer_view->parent()->RemoveChildView(observer_view); - EXPECT_EQ(NULL, observer_view->toplevel()); - - // Make |observer_view| |child|'s contents view again so that it gets deleted - // with the widget. - child->SetContentsView(observer_view); -} - -//////////////////////////////////////////////////////////////////////////////// -// Transformations -//////////////////////////////////////////////////////////////////////////////// - -class TransformPaintView : public TestView { - public: - TransformPaintView() {} - virtual ~TransformPaintView() {} - - void ClearScheduledPaintRect() { - scheduled_paint_rect_ = gfx::Rect(); - } - - gfx::Rect scheduled_paint_rect() const { return scheduled_paint_rect_; } - - // Overridden from View: - virtual void SchedulePaintInRect(const gfx::Rect& rect) override { - gfx::Rect xrect = ConvertRectToParent(rect); - scheduled_paint_rect_.Union(xrect); - } - - private: - gfx::Rect scheduled_paint_rect_; - - DISALLOW_COPY_AND_ASSIGN(TransformPaintView); -}; - -TEST_F(ViewTest, TransformPaint) { - TransformPaintView* v1 = new TransformPaintView(); - v1->SetBoundsRect(gfx::Rect(0, 0, 500, 300)); - - TestView* v2 = new TestView(); - v2->SetBoundsRect(gfx::Rect(100, 100, 200, 100)); - - Widget* widget = new Widget; - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.bounds = gfx::Rect(50, 50, 650, 650); - widget->Init(params); - widget->Show(); - View* root = widget->GetRootView(); - - root->AddChildView(v1); - v1->AddChildView(v2); - - // At this moment, |v2| occupies (100, 100) to (300, 200) in |root|. - v1->ClearScheduledPaintRect(); - v2->SchedulePaint(); - - EXPECT_EQ(gfx::Rect(100, 100, 200, 100), v1->scheduled_paint_rect()); - - // Rotate |v1| counter-clockwise. - gfx::Transform transform; - RotateCounterclockwise(&transform); - transform.matrix().set(1, 3, 500.0); - v1->SetTransform(transform); - - // |v2| now occupies (100, 200) to (200, 400) in |root|. - - v1->ClearScheduledPaintRect(); - v2->SchedulePaint(); - - EXPECT_EQ(gfx::Rect(100, 200, 100, 200), v1->scheduled_paint_rect()); - - widget->CloseNow(); -} - -TEST_F(ViewTest, TransformEvent) { - TestView* v1 = new TestView(); - v1->SetBoundsRect(gfx::Rect(0, 0, 500, 300)); - - TestView* v2 = new TestView(); - v2->SetBoundsRect(gfx::Rect(100, 100, 200, 100)); - - Widget* widget = new Widget; - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.bounds = gfx::Rect(50, 50, 650, 650); - widget->Init(params); - View* root = widget->GetRootView(); - - root->AddChildView(v1); - v1->AddChildView(v2); - - // At this moment, |v2| occupies (100, 100) to (300, 200) in |root|. - - // Rotate |v1| counter-clockwise. - gfx::Transform transform(v1->GetTransform()); - RotateCounterclockwise(&transform); - transform.matrix().set(1, 3, 500.0); - v1->SetTransform(transform); - - // |v2| now occupies (100, 200) to (200, 400) in |root|. - v1->Reset(); - v2->Reset(); - - gfx::Point p1(110, 210); - ui::MouseEvent pressed(ui::ET_MOUSE_PRESSED, p1, p1, - ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); - root->OnMousePressed(pressed); - EXPECT_EQ(0, v1->last_mouse_event_type_); - EXPECT_EQ(ui::ET_MOUSE_PRESSED, v2->last_mouse_event_type_); - EXPECT_EQ(190, v2->location_.x()); - EXPECT_EQ(10, v2->location_.y()); - - ui::MouseEvent released(ui::ET_MOUSE_RELEASED, gfx::Point(), gfx::Point(), 0, - 0); - root->OnMouseReleased(released); - - // Now rotate |v2| inside |v1| clockwise. - transform = v2->GetTransform(); - RotateClockwise(&transform); - transform.matrix().set(0, 3, 100.f); - v2->SetTransform(transform); - - // Now, |v2| occupies (100, 100) to (200, 300) in |v1|, and (100, 300) to - // (300, 400) in |root|. - - v1->Reset(); - v2->Reset(); - - gfx::Point point2(110, 320); - ui::MouseEvent p2(ui::ET_MOUSE_PRESSED, point2, point2, - ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); - root->OnMousePressed(p2); - EXPECT_EQ(0, v1->last_mouse_event_type_); - EXPECT_EQ(ui::ET_MOUSE_PRESSED, v2->last_mouse_event_type_); - EXPECT_EQ(10, v2->location_.x()); - EXPECT_EQ(20, v2->location_.y()); - - root->OnMouseReleased(released); - - v1->SetTransform(gfx::Transform()); - v2->SetTransform(gfx::Transform()); - - TestView* v3 = new TestView(); - v3->SetBoundsRect(gfx::Rect(10, 10, 20, 30)); - v2->AddChildView(v3); - - // Rotate |v3| clockwise with respect to |v2|. - transform = v1->GetTransform(); - RotateClockwise(&transform); - transform.matrix().set(0, 3, 30.f); - v3->SetTransform(transform); - - // Scale |v2| with respect to |v1| along both axis. - transform = v2->GetTransform(); - transform.matrix().set(0, 0, 0.8f); - transform.matrix().set(1, 1, 0.5f); - v2->SetTransform(transform); - - // |v3| occupies (108, 105) to (132, 115) in |root|. - - v1->Reset(); - v2->Reset(); - v3->Reset(); - - gfx::Point point(112, 110); - ui::MouseEvent p3(ui::ET_MOUSE_PRESSED, point, point, - ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); - root->OnMousePressed(p3); - - EXPECT_EQ(ui::ET_MOUSE_PRESSED, v3->last_mouse_event_type_); - EXPECT_EQ(10, v3->location_.x()); - EXPECT_EQ(25, v3->location_.y()); - - root->OnMouseReleased(released); - - v1->SetTransform(gfx::Transform()); - v2->SetTransform(gfx::Transform()); - v3->SetTransform(gfx::Transform()); - - v1->Reset(); - v2->Reset(); - v3->Reset(); - - // Rotate |v3| clockwise with respect to |v2|, and scale it along both axis. - transform = v3->GetTransform(); - RotateClockwise(&transform); - transform.matrix().set(0, 3, 30.f); - // Rotation sets some scaling transformation. Using SetScale would overwrite - // that and pollute the rotation. So combine the scaling with the existing - // transforamtion. - gfx::Transform scale; - scale.Scale(0.8f, 0.5f); - transform.ConcatTransform(scale); - v3->SetTransform(transform); - - // Translate |v2| with respect to |v1|. - transform = v2->GetTransform(); - transform.matrix().set(0, 3, 10.f); - transform.matrix().set(1, 3, 10.f); - v2->SetTransform(transform); - - // |v3| now occupies (120, 120) to (144, 130) in |root|. - - gfx::Point point3(124, 125); - ui::MouseEvent p4(ui::ET_MOUSE_PRESSED, point3, point3, - ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); - root->OnMousePressed(p4); - - EXPECT_EQ(ui::ET_MOUSE_PRESSED, v3->last_mouse_event_type_); - EXPECT_EQ(10, v3->location_.x()); - EXPECT_EQ(25, v3->location_.y()); - - root->OnMouseReleased(released); - - widget->CloseNow(); -} - -TEST_F(ViewTest, TransformVisibleBound) { - gfx::Rect viewport_bounds(0, 0, 100, 100); - - scoped_ptr<Widget> widget(new Widget); - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.bounds = viewport_bounds; - widget->Init(params); - widget->GetRootView()->SetBoundsRect(viewport_bounds); - - View* viewport = new View; - widget->SetContentsView(viewport); - View* contents = new View; - viewport->AddChildView(contents); - viewport->SetBoundsRect(viewport_bounds); - contents->SetBoundsRect(gfx::Rect(0, 0, 100, 200)); - - View* child = new View; - contents->AddChildView(child); - child->SetBoundsRect(gfx::Rect(10, 90, 50, 50)); - EXPECT_EQ(gfx::Rect(0, 0, 50, 10), child->GetVisibleBounds()); - - // Rotate |child| counter-clockwise - gfx::Transform transform; - RotateCounterclockwise(&transform); - transform.matrix().set(1, 3, 50.f); - child->SetTransform(transform); - EXPECT_EQ(gfx::Rect(40, 0, 10, 50), child->GetVisibleBounds()); - - widget->CloseNow(); -} - -//////////////////////////////////////////////////////////////////////////////// -// OnVisibleBoundsChanged() - -class VisibleBoundsView : public View { - public: - VisibleBoundsView() : received_notification_(false) {} - virtual ~VisibleBoundsView() {} - - bool received_notification() const { return received_notification_; } - void set_received_notification(bool received) { - received_notification_ = received; - } - - private: - // Overridden from View: - virtual bool GetNeedsNotificationWhenVisibleBoundsChange() const override { - return true; - } - virtual void OnVisibleBoundsChanged() override { - received_notification_ = true; - } - - bool received_notification_; - - DISALLOW_COPY_AND_ASSIGN(VisibleBoundsView); -}; - -TEST_F(ViewTest, OnVisibleBoundsChanged) { - gfx::Rect viewport_bounds(0, 0, 100, 100); - - scoped_ptr<Widget> widget(new Widget); - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.bounds = viewport_bounds; - widget->Init(params); - widget->GetRootView()->SetBoundsRect(viewport_bounds); - - View* viewport = new View; - widget->SetContentsView(viewport); - View* contents = new View; - viewport->AddChildView(contents); - viewport->SetBoundsRect(viewport_bounds); - contents->SetBoundsRect(gfx::Rect(0, 0, 100, 200)); - - // Create a view that cares about visible bounds notifications, and position - // it just outside the visible bounds of the viewport. - VisibleBoundsView* child = new VisibleBoundsView; - contents->AddChildView(child); - child->SetBoundsRect(gfx::Rect(10, 110, 50, 50)); - - // The child bound should be fully clipped. - EXPECT_TRUE(child->GetVisibleBounds().IsEmpty()); - - // Now scroll the contents, but not enough to make the child visible. - contents->SetY(contents->y() - 1); - - // We should have received the notification since the visible bounds may have - // changed (even though they didn't). - EXPECT_TRUE(child->received_notification()); - EXPECT_TRUE(child->GetVisibleBounds().IsEmpty()); - child->set_received_notification(false); - - // Now scroll the contents, this time by enough to make the child visible by - // one pixel. - contents->SetY(contents->y() - 10); - EXPECT_TRUE(child->received_notification()); - EXPECT_EQ(1, child->GetVisibleBounds().height()); - child->set_received_notification(false); - - widget->CloseNow(); -} - -TEST_F(ViewTest, SetBoundsPaint) { - TestView top_view; - TestView* child_view = new TestView; - - top_view.SetBoundsRect(gfx::Rect(0, 0, 100, 100)); - top_view.scheduled_paint_rects_.clear(); - child_view->SetBoundsRect(gfx::Rect(10, 10, 20, 20)); - top_view.AddChildView(child_view); - - top_view.scheduled_paint_rects_.clear(); - child_view->SetBoundsRect(gfx::Rect(30, 30, 20, 20)); - EXPECT_EQ(2U, top_view.scheduled_paint_rects_.size()); - - // There should be 2 rects, spanning from (10, 10) to (50, 50). - gfx::Rect paint_rect = top_view.scheduled_paint_rects_[0]; - paint_rect.Union(top_view.scheduled_paint_rects_[1]); - EXPECT_EQ(gfx::Rect(10, 10, 40, 40), paint_rect); -} - -// Assertions around painting and focus gain/lost. -TEST_F(ViewTest, FocusBlurPaints) { - TestView parent_view; - TestView* child_view1 = new TestView; // Owned by |parent_view|. - - parent_view.SetBoundsRect(gfx::Rect(0, 0, 100, 100)); - - child_view1->SetBoundsRect(gfx::Rect(0, 0, 20, 20)); - parent_view.AddChildView(child_view1); - - parent_view.scheduled_paint_rects_.clear(); - child_view1->scheduled_paint_rects_.clear(); - - // Focus change shouldn't trigger paints. - child_view1->DoFocus(); - - EXPECT_TRUE(parent_view.scheduled_paint_rects_.empty()); - EXPECT_TRUE(child_view1->scheduled_paint_rects_.empty()); - - child_view1->DoBlur(); - EXPECT_TRUE(parent_view.scheduled_paint_rects_.empty()); - EXPECT_TRUE(child_view1->scheduled_paint_rects_.empty()); -} - -// Verifies SetBounds(same bounds) doesn't trigger a SchedulePaint(). -TEST_F(ViewTest, SetBoundsSameBoundsDoesntSchedulePaint) { - TestView view; - - view.SetBoundsRect(gfx::Rect(0, 0, 100, 100)); - view.InvalidateLayout(); - view.scheduled_paint_rects_.clear(); - view.SetBoundsRect(gfx::Rect(0, 0, 100, 100)); - EXPECT_TRUE(view.scheduled_paint_rects_.empty()); -} - -// Verifies AddChildView() and RemoveChildView() schedule appropriate paints. -TEST_F(ViewTest, AddAndRemoveSchedulePaints) { - gfx::Rect viewport_bounds(0, 0, 100, 100); - - // We have to put the View hierarchy into a Widget or no paints will be - // scheduled. - scoped_ptr<Widget> widget(new Widget); - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.bounds = viewport_bounds; - widget->Init(params); - widget->GetRootView()->SetBoundsRect(viewport_bounds); - - TestView* parent_view = new TestView; - widget->SetContentsView(parent_view); - parent_view->SetBoundsRect(viewport_bounds); - parent_view->scheduled_paint_rects_.clear(); - - View* child_view = new View; - child_view->SetBoundsRect(gfx::Rect(0, 0, 20, 20)); - parent_view->AddChildView(child_view); - ASSERT_EQ(1U, parent_view->scheduled_paint_rects_.size()); - EXPECT_EQ(child_view->bounds(), parent_view->scheduled_paint_rects_.front()); - - parent_view->scheduled_paint_rects_.clear(); - parent_view->RemoveChildView(child_view); - scoped_ptr<View> child_deleter(child_view); - ASSERT_EQ(1U, parent_view->scheduled_paint_rects_.size()); - EXPECT_EQ(child_view->bounds(), parent_view->scheduled_paint_rects_.front()); - - widget->CloseNow(); -} - -// Tests conversion methods with a transform. -TEST_F(ViewTest, ConversionsWithTransform) { - TestView top_view; - - // View hierarchy used to test scale transforms. - TestView* child = new TestView; - TestView* child_child = new TestView; - - // View used to test a rotation transform. - TestView* child_2 = new TestView; - - top_view.AddChildView(child); - child->AddChildView(child_child); - - top_view.SetBoundsRect(gfx::Rect(0, 0, 1000, 1000)); - - child->SetBoundsRect(gfx::Rect(7, 19, 500, 500)); - gfx::Transform transform; - transform.Scale(3.0, 4.0); - child->SetTransform(transform); - - child_child->SetBoundsRect(gfx::Rect(17, 13, 100, 100)); - transform.MakeIdentity(); - transform.Scale(5.0, 7.0); - child_child->SetTransform(transform); - - top_view.AddChildView(child_2); - child_2->SetBoundsRect(gfx::Rect(700, 725, 100, 100)); - transform.MakeIdentity(); - RotateClockwise(&transform); - child_2->SetTransform(transform); - - // Sanity check to make sure basic transforms act as expected. - { - gfx::Transform transform; - transform.Translate(110.0, -110.0); - transform.Scale(100.0, 55.0); - transform.Translate(1.0, 1.0); - - // convert to a 3x3 matrix. - const SkMatrix& matrix = transform.matrix(); - - EXPECT_EQ(210, matrix.getTranslateX()); - EXPECT_EQ(-55, matrix.getTranslateY()); - EXPECT_EQ(100, matrix.getScaleX()); - EXPECT_EQ(55, matrix.getScaleY()); - EXPECT_EQ(0, matrix.getSkewX()); - EXPECT_EQ(0, matrix.getSkewY()); - } - - { - gfx::Transform transform; - transform.Translate(1.0, 1.0); - gfx::Transform t2; - t2.Scale(100.0, 55.0); - gfx::Transform t3; - t3.Translate(110.0, -110.0); - transform.ConcatTransform(t2); - transform.ConcatTransform(t3); - - // convert to a 3x3 matrix - const SkMatrix& matrix = transform.matrix(); - - EXPECT_EQ(210, matrix.getTranslateX()); - EXPECT_EQ(-55, matrix.getTranslateY()); - EXPECT_EQ(100, matrix.getScaleX()); - EXPECT_EQ(55, matrix.getScaleY()); - EXPECT_EQ(0, matrix.getSkewX()); - EXPECT_EQ(0, matrix.getSkewY()); - } - - // Conversions from child->top and top->child. - { - gfx::Point point(5, 5); - View::ConvertPointToTarget(child, &top_view, &point); - EXPECT_EQ(22, point.x()); - EXPECT_EQ(39, point.y()); - - gfx::RectF rect(5.0f, 5.0f, 10.0f, 20.0f); - View::ConvertRectToTarget(child, &top_view, &rect); - EXPECT_FLOAT_EQ(22.0f, rect.x()); - EXPECT_FLOAT_EQ(39.0f, rect.y()); - EXPECT_FLOAT_EQ(30.0f, rect.width()); - EXPECT_FLOAT_EQ(80.0f, rect.height()); - - point.SetPoint(22, 39); - View::ConvertPointToTarget(&top_view, child, &point); - EXPECT_EQ(5, point.x()); - EXPECT_EQ(5, point.y()); - - rect.SetRect(22.0f, 39.0f, 30.0f, 80.0f); - View::ConvertRectToTarget(&top_view, child, &rect); - EXPECT_FLOAT_EQ(5.0f, rect.x()); - EXPECT_FLOAT_EQ(5.0f, rect.y()); - EXPECT_FLOAT_EQ(10.0f, rect.width()); - EXPECT_FLOAT_EQ(20.0f, rect.height()); - } - - // Conversions from child_child->top and top->child_child. - { - gfx::Point point(5, 5); - View::ConvertPointToTarget(child_child, &top_view, &point); - EXPECT_EQ(133, point.x()); - EXPECT_EQ(211, point.y()); - - gfx::RectF rect(5.0f, 5.0f, 10.0f, 20.0f); - View::ConvertRectToTarget(child_child, &top_view, &rect); - EXPECT_FLOAT_EQ(133.0f, rect.x()); - EXPECT_FLOAT_EQ(211.0f, rect.y()); - EXPECT_FLOAT_EQ(150.0f, rect.width()); - EXPECT_FLOAT_EQ(560.0f, rect.height()); - - point.SetPoint(133, 211); - View::ConvertPointToTarget(&top_view, child_child, &point); - EXPECT_EQ(5, point.x()); - EXPECT_EQ(5, point.y()); - - rect.SetRect(133.0f, 211.0f, 150.0f, 560.0f); - View::ConvertRectToTarget(&top_view, child_child, &rect); - EXPECT_FLOAT_EQ(5.0f, rect.x()); - EXPECT_FLOAT_EQ(5.0f, rect.y()); - EXPECT_FLOAT_EQ(10.0f, rect.width()); - EXPECT_FLOAT_EQ(20.0f, rect.height()); - } - - // Conversions from child_child->child and child->child_child - { - gfx::Point point(5, 5); - View::ConvertPointToTarget(child_child, child, &point); - EXPECT_EQ(42, point.x()); - EXPECT_EQ(48, point.y()); - - gfx::RectF rect(5.0f, 5.0f, 10.0f, 20.0f); - View::ConvertRectToTarget(child_child, child, &rect); - EXPECT_FLOAT_EQ(42.0f, rect.x()); - EXPECT_FLOAT_EQ(48.0f, rect.y()); - EXPECT_FLOAT_EQ(50.0f, rect.width()); - EXPECT_FLOAT_EQ(140.0f, rect.height()); - - point.SetPoint(42, 48); - View::ConvertPointToTarget(child, child_child, &point); - EXPECT_EQ(5, point.x()); - EXPECT_EQ(5, point.y()); - - rect.SetRect(42.0f, 48.0f, 50.0f, 140.0f); - View::ConvertRectToTarget(child, child_child, &rect); - EXPECT_FLOAT_EQ(5.0f, rect.x()); - EXPECT_FLOAT_EQ(5.0f, rect.y()); - EXPECT_FLOAT_EQ(10.0f, rect.width()); - EXPECT_FLOAT_EQ(20.0f, rect.height()); - } - - // Conversions from top_view to child with a value that should be negative. - // This ensures we don't round up with negative numbers. - { - gfx::Point point(6, 18); - View::ConvertPointToTarget(&top_view, child, &point); - EXPECT_EQ(-1, point.x()); - EXPECT_EQ(-1, point.y()); - - float error = 0.01f; - gfx::RectF rect(6.0f, 18.0f, 10.0f, 39.0f); - View::ConvertRectToTarget(&top_view, child, &rect); - EXPECT_NEAR(-0.33f, rect.x(), error); - EXPECT_NEAR(-0.25f, rect.y(), error); - EXPECT_NEAR(3.33f, rect.width(), error); - EXPECT_NEAR(9.75f, rect.height(), error); - } - - // Rect conversions from top_view->child_2 and child_2->top_view. - { - gfx::RectF rect(50.0f, 55.0f, 20.0f, 30.0f); - View::ConvertRectToTarget(child_2, &top_view, &rect); - EXPECT_FLOAT_EQ(615.0f, rect.x()); - EXPECT_FLOAT_EQ(775.0f, rect.y()); - EXPECT_FLOAT_EQ(30.0f, rect.width()); - EXPECT_FLOAT_EQ(20.0f, rect.height()); - - rect.SetRect(615.0f, 775.0f, 30.0f, 20.0f); - View::ConvertRectToTarget(&top_view, child_2, &rect); - EXPECT_FLOAT_EQ(50.0f, rect.x()); - EXPECT_FLOAT_EQ(55.0f, rect.y()); - EXPECT_FLOAT_EQ(20.0f, rect.width()); - EXPECT_FLOAT_EQ(30.0f, rect.height()); - } -} - -// Tests conversion methods to and from screen coordinates. -TEST_F(ViewTest, ConversionsToFromScreen) { - scoped_ptr<Widget> widget(new Widget); - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.bounds = gfx::Rect(50, 50, 650, 650); - widget->Init(params); - - View* child = new View; - widget->GetRootView()->AddChildView(child); - child->SetBounds(10, 10, 100, 200); - gfx::Transform t; - t.Scale(0.5, 0.5); - child->SetTransform(t); - - gfx::Point point_in_screen(100, 90); - gfx::Point point_in_child(80, 60); - - gfx::Point point = point_in_screen; - View::ConvertPointFromScreen(child, &point); - EXPECT_EQ(point_in_child.ToString(), point.ToString()); - - View::ConvertPointToScreen(child, &point); - EXPECT_EQ(point_in_screen.ToString(), point.ToString()); -} - -// Tests conversion methods for rectangles. -TEST_F(ViewTest, ConvertRectWithTransform) { - scoped_ptr<Widget> widget(new Widget); - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.bounds = gfx::Rect(50, 50, 650, 650); - widget->Init(params); - View* root = widget->GetRootView(); - - TestView* v1 = new TestView; - TestView* v2 = new TestView; - root->AddChildView(v1); - v1->AddChildView(v2); - - v1->SetBoundsRect(gfx::Rect(10, 10, 500, 500)); - v2->SetBoundsRect(gfx::Rect(20, 20, 100, 200)); - - // |v2| now occupies (30, 30) to (130, 230) in |widget| - gfx::Rect rect(5, 5, 15, 40); - EXPECT_EQ(gfx::Rect(25, 25, 15, 40), v2->ConvertRectToParent(rect)); - EXPECT_EQ(gfx::Rect(35, 35, 15, 40), v2->ConvertRectToWidget(rect)); - - // Rotate |v2| - gfx::Transform t2; - RotateCounterclockwise(&t2); - t2.matrix().set(1, 3, 100.f); - v2->SetTransform(t2); - - // |v2| now occupies (30, 30) to (230, 130) in |widget| - EXPECT_EQ(gfx::Rect(25, 100, 40, 15), v2->ConvertRectToParent(rect)); - EXPECT_EQ(gfx::Rect(35, 110, 40, 15), v2->ConvertRectToWidget(rect)); - - // Scale down |v1| - gfx::Transform t1; - t1.Scale(0.5, 0.5); - v1->SetTransform(t1); - - // The rectangle should remain the same for |v1|. - EXPECT_EQ(gfx::Rect(25, 100, 40, 15), v2->ConvertRectToParent(rect)); - - // |v2| now occupies (20, 20) to (120, 70) in |widget| - EXPECT_EQ(gfx::Rect(22, 60, 21, 8).ToString(), - v2->ConvertRectToWidget(rect).ToString()); - - widget->CloseNow(); -} - -class ObserverView : public View { - public: - ObserverView(); - virtual ~ObserverView(); - - void ResetTestState(); - - bool has_add_details() const { return has_add_details_; } - bool has_remove_details() const { return has_remove_details_; } - - const ViewHierarchyChangedDetails& add_details() const { - return add_details_; - } - - const ViewHierarchyChangedDetails& remove_details() const { - return remove_details_; - } - - private: - // View: - virtual void ViewHierarchyChanged( - const ViewHierarchyChangedDetails& details) override; - - bool has_add_details_; - bool has_remove_details_; - ViewHierarchyChangedDetails add_details_; - ViewHierarchyChangedDetails remove_details_; - - DISALLOW_COPY_AND_ASSIGN(ObserverView); -}; - -ObserverView::ObserverView() - : has_add_details_(false), - has_remove_details_(false) { -} - -ObserverView::~ObserverView() {} - -void ObserverView::ResetTestState() { - has_add_details_ = false; - has_remove_details_ = false; - add_details_ = ViewHierarchyChangedDetails(); - remove_details_ = ViewHierarchyChangedDetails(); -} - -void ObserverView::ViewHierarchyChanged( - const ViewHierarchyChangedDetails& details) { - if (details.is_add) { - has_add_details_ = true; - add_details_ = details; - } else { - has_remove_details_ = true; - remove_details_ = details; - } -} - -// Verifies that the ViewHierarchyChanged() notification is sent correctly when -// a child view is added or removed to all the views in the hierarchy (up and -// down). -// The tree looks like this: -// v1 -// +-- v2 -// +-- v3 -// +-- v4 (starts here, then get reparented to v1) -TEST_F(ViewTest, ViewHierarchyChanged) { - ObserverView v1; - - ObserverView* v3 = new ObserverView(); - - // Add |v3| to |v2|. - scoped_ptr<ObserverView> v2(new ObserverView()); - v2->AddChildView(v3); - - // Make sure both |v2| and |v3| receive the ViewHierarchyChanged() - // notification. - EXPECT_TRUE(v2->has_add_details()); - EXPECT_FALSE(v2->has_remove_details()); - EXPECT_EQ(v2.get(), v2->add_details().parent); - EXPECT_EQ(v3, v2->add_details().child); - EXPECT_EQ(NULL, v2->add_details().move_view); - - EXPECT_TRUE(v3->has_add_details()); - EXPECT_FALSE(v3->has_remove_details()); - EXPECT_EQ(v2.get(), v3->add_details().parent); - EXPECT_EQ(v3, v3->add_details().child); - EXPECT_EQ(NULL, v3->add_details().move_view); - - // Reset everything to the initial state. - v2->ResetTestState(); - v3->ResetTestState(); - - // Add |v2| to v1. - v1.AddChildView(v2.get()); - - // Verifies that |v2| is the child view *added* and the parent view is |v1|. - // Make sure all the views (v1, v2, v3) received _that_ information. - EXPECT_TRUE(v1.has_add_details()); - EXPECT_FALSE(v1.has_remove_details()); - EXPECT_EQ(&v1, v1.add_details().parent); - EXPECT_EQ(v2.get(), v1.add_details().child); - EXPECT_EQ(NULL, v1.add_details().move_view); - - EXPECT_TRUE(v2->has_add_details()); - EXPECT_FALSE(v2->has_remove_details()); - EXPECT_EQ(&v1, v2->add_details().parent); - EXPECT_EQ(v2.get(), v2->add_details().child); - EXPECT_EQ(NULL, v2->add_details().move_view); - - EXPECT_TRUE(v3->has_add_details()); - EXPECT_FALSE(v3->has_remove_details()); - EXPECT_EQ(&v1, v3->add_details().parent); - EXPECT_EQ(v2.get(), v3->add_details().child); - EXPECT_EQ(NULL, v3->add_details().move_view); - - // Reset everything to the initial state. - v1.ResetTestState(); - v2->ResetTestState(); - v3->ResetTestState(); - - // Remove |v2| from |v1|. - v1.RemoveChildView(v2.get()); - - // Verifies that |v2| is the child view *removed* and the parent view is |v1|. - // Make sure all the views (v1, v2, v3) received _that_ information. - EXPECT_FALSE(v1.has_add_details()); - EXPECT_TRUE(v1.has_remove_details()); - EXPECT_EQ(&v1, v1.remove_details().parent); - EXPECT_EQ(v2.get(), v1.remove_details().child); - EXPECT_EQ(NULL, v1.remove_details().move_view); - - EXPECT_FALSE(v2->has_add_details()); - EXPECT_TRUE(v2->has_remove_details()); - EXPECT_EQ(&v1, v2->remove_details().parent); - EXPECT_EQ(v2.get(), v2->remove_details().child); - EXPECT_EQ(NULL, v2->remove_details().move_view); - - EXPECT_FALSE(v3->has_add_details()); - EXPECT_TRUE(v3->has_remove_details()); - EXPECT_EQ(&v1, v3->remove_details().parent); - EXPECT_EQ(v3, v3->remove_details().child); - EXPECT_EQ(NULL, v3->remove_details().move_view); - - // Verifies notifications when reparenting a view. - ObserverView* v4 = new ObserverView(); - // Add |v4| to |v2|. - v2->AddChildView(v4); - - // Reset everything to the initial state. - v1.ResetTestState(); - v2->ResetTestState(); - v3->ResetTestState(); - v4->ResetTestState(); - - // Reparent |v4| to |v1|. - v1.AddChildView(v4); - - // Verifies that all views receive the correct information for all the child, - // parent and move views. - - // |v1| is the new parent, |v4| is the child for add, |v2| is the old parent. - EXPECT_TRUE(v1.has_add_details()); - EXPECT_FALSE(v1.has_remove_details()); - EXPECT_EQ(&v1, v1.add_details().parent); - EXPECT_EQ(v4, v1.add_details().child); - EXPECT_EQ(v2.get(), v1.add_details().move_view); - - // |v2| is the old parent, |v4| is the child for remove, |v1| is the new - // parent. - EXPECT_FALSE(v2->has_add_details()); - EXPECT_TRUE(v2->has_remove_details()); - EXPECT_EQ(v2.get(), v2->remove_details().parent); - EXPECT_EQ(v4, v2->remove_details().child); - EXPECT_EQ(&v1, v2->remove_details().move_view); - - // |v3| is not impacted by this operation, and hence receives no notification. - EXPECT_FALSE(v3->has_add_details()); - EXPECT_FALSE(v3->has_remove_details()); - - // |v4| is the reparented child, so it receives notifications for the remove - // and then the add. |v2| is its old parent, |v1| is its new parent. - EXPECT_TRUE(v4->has_remove_details()); - EXPECT_TRUE(v4->has_add_details()); - EXPECT_EQ(v2.get(), v4->remove_details().parent); - EXPECT_EQ(&v1, v4->add_details().parent); - EXPECT_EQ(v4, v4->add_details().child); - EXPECT_EQ(v4, v4->remove_details().child); - EXPECT_EQ(&v1, v4->remove_details().move_view); - EXPECT_EQ(v2.get(), v4->add_details().move_view); -} - -// Verifies if the child views added under the root are all deleted when calling -// RemoveAllChildViews. -// The tree looks like this: -// root -// +-- child1 -// +-- foo -// +-- bar0 -// +-- bar1 -// +-- bar2 -// +-- child2 -// +-- child3 -TEST_F(ViewTest, RemoveAllChildViews) { - View root; - - View* child1 = new View; - root.AddChildView(child1); - - for (int i = 0; i < 2; ++i) - root.AddChildView(new View); - - View* foo = new View; - child1->AddChildView(foo); - - // Add some nodes to |foo|. - for (int i = 0; i < 3; ++i) - foo->AddChildView(new View); - - EXPECT_EQ(3, root.child_count()); - EXPECT_EQ(1, child1->child_count()); - EXPECT_EQ(3, foo->child_count()); - - // Now remove all child views from root. - root.RemoveAllChildViews(true); - - EXPECT_EQ(0, root.child_count()); - EXPECT_FALSE(root.has_children()); -} - -TEST_F(ViewTest, Contains) { - View v1; - View* v2 = new View; - View* v3 = new View; - - v1.AddChildView(v2); - v2->AddChildView(v3); - - EXPECT_FALSE(v1.Contains(NULL)); - EXPECT_TRUE(v1.Contains(&v1)); - EXPECT_TRUE(v1.Contains(v2)); - EXPECT_TRUE(v1.Contains(v3)); - - EXPECT_FALSE(v2->Contains(NULL)); - EXPECT_TRUE(v2->Contains(v2)); - EXPECT_FALSE(v2->Contains(&v1)); - EXPECT_TRUE(v2->Contains(v3)); - - EXPECT_FALSE(v3->Contains(NULL)); - EXPECT_TRUE(v3->Contains(v3)); - EXPECT_FALSE(v3->Contains(&v1)); - EXPECT_FALSE(v3->Contains(v2)); -} - -// Verifies if GetIndexOf() returns the correct index for the specified child -// view. -// The tree looks like this: -// root -// +-- child1 -// +-- foo1 -// +-- child2 -TEST_F(ViewTest, GetIndexOf) { - View root; - - View* child1 = new View; - root.AddChildView(child1); - - View* child2 = new View; - root.AddChildView(child2); - - View* foo1 = new View; - child1->AddChildView(foo1); - - EXPECT_EQ(-1, root.GetIndexOf(NULL)); - EXPECT_EQ(-1, root.GetIndexOf(&root)); - EXPECT_EQ(0, root.GetIndexOf(child1)); - EXPECT_EQ(1, root.GetIndexOf(child2)); - EXPECT_EQ(-1, root.GetIndexOf(foo1)); - - EXPECT_EQ(-1, child1->GetIndexOf(NULL)); - EXPECT_EQ(-1, child1->GetIndexOf(&root)); - EXPECT_EQ(-1, child1->GetIndexOf(child1)); - EXPECT_EQ(-1, child1->GetIndexOf(child2)); - EXPECT_EQ(0, child1->GetIndexOf(foo1)); - - EXPECT_EQ(-1, child2->GetIndexOf(NULL)); - EXPECT_EQ(-1, child2->GetIndexOf(&root)); - EXPECT_EQ(-1, child2->GetIndexOf(child2)); - EXPECT_EQ(-1, child2->GetIndexOf(child1)); - EXPECT_EQ(-1, child2->GetIndexOf(foo1)); -} - -// Verifies that the child views can be reordered correctly. -TEST_F(ViewTest, ReorderChildren) { - View root; - - View* child = new View(); - root.AddChildView(child); - - View* foo1 = new View(); - child->AddChildView(foo1); - View* foo2 = new View(); - child->AddChildView(foo2); - View* foo3 = new View(); - child->AddChildView(foo3); - foo1->SetFocusable(true); - foo2->SetFocusable(true); - foo3->SetFocusable(true); - - ASSERT_EQ(0, child->GetIndexOf(foo1)); - ASSERT_EQ(1, child->GetIndexOf(foo2)); - ASSERT_EQ(2, child->GetIndexOf(foo3)); - ASSERT_EQ(foo2, foo1->GetNextFocusableView()); - ASSERT_EQ(foo3, foo2->GetNextFocusableView()); - ASSERT_EQ(NULL, foo3->GetNextFocusableView()); - - // Move |foo2| at the end. - child->ReorderChildView(foo2, -1); - ASSERT_EQ(0, child->GetIndexOf(foo1)); - ASSERT_EQ(1, child->GetIndexOf(foo3)); - ASSERT_EQ(2, child->GetIndexOf(foo2)); - ASSERT_EQ(foo3, foo1->GetNextFocusableView()); - ASSERT_EQ(foo2, foo3->GetNextFocusableView()); - ASSERT_EQ(NULL, foo2->GetNextFocusableView()); - - // Move |foo1| at the end. - child->ReorderChildView(foo1, -1); - ASSERT_EQ(0, child->GetIndexOf(foo3)); - ASSERT_EQ(1, child->GetIndexOf(foo2)); - ASSERT_EQ(2, child->GetIndexOf(foo1)); - ASSERT_EQ(NULL, foo1->GetNextFocusableView()); - ASSERT_EQ(foo2, foo1->GetPreviousFocusableView()); - ASSERT_EQ(foo2, foo3->GetNextFocusableView()); - ASSERT_EQ(foo1, foo2->GetNextFocusableView()); - - // Move |foo2| to the front. - child->ReorderChildView(foo2, 0); - ASSERT_EQ(0, child->GetIndexOf(foo2)); - ASSERT_EQ(1, child->GetIndexOf(foo3)); - ASSERT_EQ(2, child->GetIndexOf(foo1)); - ASSERT_EQ(NULL, foo1->GetNextFocusableView()); - ASSERT_EQ(foo3, foo1->GetPreviousFocusableView()); - ASSERT_EQ(foo3, foo2->GetNextFocusableView()); - ASSERT_EQ(foo1, foo3->GetNextFocusableView()); -} - -// Verifies that GetViewByID returns the correctly child view from the specified -// ID. -// The tree looks like this: -// v1 -// +-- v2 -// +-- v3 -// +-- v4 -TEST_F(ViewTest, GetViewByID) { - View v1; - const int kV1ID = 1; - v1.set_id(kV1ID); - - View v2; - const int kV2ID = 2; - v2.set_id(kV2ID); - - View v3; - const int kV3ID = 3; - v3.set_id(kV3ID); - - View v4; - const int kV4ID = 4; - v4.set_id(kV4ID); - - const int kV5ID = 5; - - v1.AddChildView(&v2); - v2.AddChildView(&v3); - v2.AddChildView(&v4); - - EXPECT_EQ(&v1, v1.GetViewByID(kV1ID)); - EXPECT_EQ(&v2, v1.GetViewByID(kV2ID)); - EXPECT_EQ(&v4, v1.GetViewByID(kV4ID)); - - EXPECT_EQ(NULL, v1.GetViewByID(kV5ID)); // No V5 exists. - EXPECT_EQ(NULL, v2.GetViewByID(kV1ID)); // It can get only from child views. - - const int kGroup = 1; - v3.SetGroup(kGroup); - v4.SetGroup(kGroup); - - View::Views views; - v1.GetViewsInGroup(kGroup, &views); - EXPECT_EQ(2U, views.size()); - - View::Views::const_iterator i(std::find(views.begin(), views.end(), &v3)); - EXPECT_NE(views.end(), i); - - i = std::find(views.begin(), views.end(), &v4); - EXPECT_NE(views.end(), i); -} - -TEST_F(ViewTest, AddExistingChild) { - View v1, v2, v3; - - v1.AddChildView(&v2); - v1.AddChildView(&v3); - EXPECT_EQ(0, v1.GetIndexOf(&v2)); - EXPECT_EQ(1, v1.GetIndexOf(&v3)); - - // Check that there's no change in order when adding at same index. - v1.AddChildViewAt(&v2, 0); - EXPECT_EQ(0, v1.GetIndexOf(&v2)); - EXPECT_EQ(1, v1.GetIndexOf(&v3)); - v1.AddChildViewAt(&v3, 1); - EXPECT_EQ(0, v1.GetIndexOf(&v2)); - EXPECT_EQ(1, v1.GetIndexOf(&v3)); - - // Add it at a different index and check for change in order. - v1.AddChildViewAt(&v2, 1); - EXPECT_EQ(1, v1.GetIndexOf(&v2)); - EXPECT_EQ(0, v1.GetIndexOf(&v3)); - v1.AddChildViewAt(&v2, 0); - EXPECT_EQ(0, v1.GetIndexOf(&v2)); - EXPECT_EQ(1, v1.GetIndexOf(&v3)); - - // Check that calling |AddChildView()| does not change the order. - v1.AddChildView(&v2); - EXPECT_EQ(0, v1.GetIndexOf(&v2)); - EXPECT_EQ(1, v1.GetIndexOf(&v3)); - v1.AddChildView(&v3); - EXPECT_EQ(0, v1.GetIndexOf(&v2)); - EXPECT_EQ(1, v1.GetIndexOf(&v3)); -} - -//////////////////////////////////////////////////////////////////////////////// -// FocusManager -//////////////////////////////////////////////////////////////////////////////// - -// A widget that always claims to be active, regardless of its real activation -// status. -class ActiveWidget : public Widget { - public: - ActiveWidget() {} - virtual ~ActiveWidget() {} - - virtual bool IsActive() const override { - return true; - } - - private: - DISALLOW_COPY_AND_ASSIGN(ActiveWidget); -}; - -TEST_F(ViewTest, AdvanceFocusIfNecessaryForUnfocusableView) { - // Create a widget with two views and give the first one focus. - ActiveWidget widget; - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(params); - - View* view1 = new View(); - view1->SetFocusable(true); - widget.GetRootView()->AddChildView(view1); - View* view2 = new View(); - view2->SetFocusable(true); - widget.GetRootView()->AddChildView(view2); - - FocusManager* focus_manager = widget.GetFocusManager(); - ASSERT_TRUE(focus_manager); - - focus_manager->SetFocusedView(view1); - EXPECT_EQ(view1, focus_manager->GetFocusedView()); - - // Disable the focused view and check if the next view gets focused. - view1->SetEnabled(false); - EXPECT_EQ(view2, focus_manager->GetFocusedView()); - - // Re-enable and re-focus. - view1->SetEnabled(true); - focus_manager->SetFocusedView(view1); - EXPECT_EQ(view1, focus_manager->GetFocusedView()); - - // Hide the focused view and check it the next view gets focused. - view1->SetVisible(false); - EXPECT_EQ(view2, focus_manager->GetFocusedView()); - - // Re-show and re-focus. - view1->SetVisible(true); - focus_manager->SetFocusedView(view1); - EXPECT_EQ(view1, focus_manager->GetFocusedView()); - - // Set the focused view as not focusable and check if the next view gets - // focused. - view1->SetFocusable(false); - EXPECT_EQ(view2, focus_manager->GetFocusedView()); -} - -//////////////////////////////////////////////////////////////////////////////// -// Layers -//////////////////////////////////////////////////////////////////////////////// - -namespace { - -// Test implementation of LayerAnimator. -class TestLayerAnimator : public ui::LayerAnimator { - public: - TestLayerAnimator(); - - const gfx::Rect& last_bounds() const { return last_bounds_; } - - // LayerAnimator. - virtual void SetBounds(const gfx::Rect& bounds) override; - - protected: - virtual ~TestLayerAnimator() { } - - private: - gfx::Rect last_bounds_; - - DISALLOW_COPY_AND_ASSIGN(TestLayerAnimator); -}; - -TestLayerAnimator::TestLayerAnimator() - : ui::LayerAnimator(base::TimeDelta::FromMilliseconds(0)) { -} - -void TestLayerAnimator::SetBounds(const gfx::Rect& bounds) { - last_bounds_ = bounds; -} - -} // namespace - -class ViewLayerTest : public ViewsTestBase { - public: - ViewLayerTest() : widget_(NULL) {} - - virtual ~ViewLayerTest() { - } - - // Returns the Layer used by the RootView. - ui::Layer* GetRootLayer() { - return widget()->GetLayer(); - } - - virtual void SetUp() override { - ViewTest::SetUp(); - widget_ = new Widget; - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.bounds = gfx::Rect(50, 50, 200, 200); - widget_->Init(params); - widget_->Show(); - widget_->GetRootView()->SetBounds(0, 0, 200, 200); - } - - virtual void TearDown() override { - widget_->CloseNow(); - ViewsTestBase::TearDown(); - } - - Widget* widget() { return widget_; } - - private: - Widget* widget_; -}; - - -TEST_F(ViewLayerTest, LayerToggling) { - // Because we lazily create textures the calls to DrawTree are necessary to - // ensure we trigger creation of textures. - ui::Layer* root_layer = widget()->GetLayer(); - View* content_view = new View; - widget()->SetContentsView(content_view); - - // Create v1, give it a bounds and verify everything is set up correctly. - View* v1 = new View; - v1->SetPaintToLayer(true); - EXPECT_TRUE(v1->layer() != NULL); - v1->SetBoundsRect(gfx::Rect(20, 30, 140, 150)); - content_view->AddChildView(v1); - ASSERT_TRUE(v1->layer() != NULL); - EXPECT_EQ(root_layer, v1->layer()->parent()); - EXPECT_EQ(gfx::Rect(20, 30, 140, 150), v1->layer()->bounds()); - - // Create v2 as a child of v1 and do basic assertion testing. - View* v2 = new View; - v1->AddChildView(v2); - EXPECT_TRUE(v2->layer() == NULL); - v2->SetBoundsRect(gfx::Rect(10, 20, 30, 40)); - v2->SetPaintToLayer(true); - ASSERT_TRUE(v2->layer() != NULL); - EXPECT_EQ(v1->layer(), v2->layer()->parent()); - EXPECT_EQ(gfx::Rect(10, 20, 30, 40), v2->layer()->bounds()); - - // Turn off v1s layer. v2 should still have a layer but its parent should have - // changed. - v1->SetPaintToLayer(false); - EXPECT_TRUE(v1->layer() == NULL); - EXPECT_TRUE(v2->layer() != NULL); - EXPECT_EQ(root_layer, v2->layer()->parent()); - ASSERT_EQ(1u, root_layer->children().size()); - EXPECT_EQ(root_layer->children()[0], v2->layer()); - // The bounds of the layer should have changed to be relative to the root view - // now. - EXPECT_EQ(gfx::Rect(30, 50, 30, 40), v2->layer()->bounds()); - - // Make v1 have a layer again and verify v2s layer is wired up correctly. - gfx::Transform transform; - transform.Scale(2.0, 2.0); - v1->SetTransform(transform); - EXPECT_TRUE(v1->layer() != NULL); - EXPECT_TRUE(v2->layer() != NULL); - EXPECT_EQ(root_layer, v1->layer()->parent()); - EXPECT_EQ(v1->layer(), v2->layer()->parent()); - ASSERT_EQ(1u, root_layer->children().size()); - EXPECT_EQ(root_layer->children()[0], v1->layer()); - ASSERT_EQ(1u, v1->layer()->children().size()); - EXPECT_EQ(v1->layer()->children()[0], v2->layer()); - EXPECT_EQ(gfx::Rect(10, 20, 30, 40), v2->layer()->bounds()); -} - -// Verifies turning on a layer wires up children correctly. -TEST_F(ViewLayerTest, NestedLayerToggling) { - View* content_view = new View; - widget()->SetContentsView(content_view); - - // Create v1, give it a bounds and verify everything is set up correctly. - View* v1 = new View; - content_view->AddChildView(v1); - v1->SetBoundsRect(gfx::Rect(20, 30, 140, 150)); - - View* v2 = new View; - v1->AddChildView(v2); - - View* v3 = new View; - v3->SetPaintToLayer(true); - v2->AddChildView(v3); - ASSERT_TRUE(v3->layer() != NULL); - - // At this point we have v1-v2-v3. v3 has a layer, v1 and v2 don't. - - v1->SetPaintToLayer(true); - EXPECT_EQ(v1->layer(), v3->layer()->parent()); -} - -TEST_F(ViewLayerTest, LayerAnimator) { - View* content_view = new View; - widget()->SetContentsView(content_view); - - View* v1 = new View; - content_view->AddChildView(v1); - v1->SetPaintToLayer(true); - EXPECT_TRUE(v1->layer() != NULL); - - TestLayerAnimator* animator = new TestLayerAnimator(); - v1->layer()->SetAnimator(animator); - - gfx::Rect bounds(1, 2, 3, 4); - v1->SetBoundsRect(bounds); - EXPECT_EQ(bounds, animator->last_bounds()); - // TestLayerAnimator doesn't update the layer. - EXPECT_NE(bounds, v1->layer()->bounds()); -} - -// Verifies the bounds of a layer are updated if the bounds of ancestor that -// doesn't have a layer change. -TEST_F(ViewLayerTest, BoundsChangeWithLayer) { - View* content_view = new View; - widget()->SetContentsView(content_view); - - View* v1 = new View; - content_view->AddChildView(v1); - v1->SetBoundsRect(gfx::Rect(20, 30, 140, 150)); - - View* v2 = new View; - v2->SetBoundsRect(gfx::Rect(10, 11, 40, 50)); - v1->AddChildView(v2); - v2->SetPaintToLayer(true); - ASSERT_TRUE(v2->layer() != NULL); - EXPECT_EQ(gfx::Rect(30, 41, 40, 50), v2->layer()->bounds()); - - v1->SetPosition(gfx::Point(25, 36)); - EXPECT_EQ(gfx::Rect(35, 47, 40, 50), v2->layer()->bounds()); - - v2->SetPosition(gfx::Point(11, 12)); - EXPECT_EQ(gfx::Rect(36, 48, 40, 50), v2->layer()->bounds()); - - // Bounds of the layer should change even if the view is not invisible. - v1->SetVisible(false); - v1->SetPosition(gfx::Point(20, 30)); - EXPECT_EQ(gfx::Rect(31, 42, 40, 50), v2->layer()->bounds()); - - v2->SetVisible(false); - v2->SetBoundsRect(gfx::Rect(10, 11, 20, 30)); - EXPECT_EQ(gfx::Rect(30, 41, 20, 30), v2->layer()->bounds()); -} - -// Make sure layers are positioned correctly in RTL. -TEST_F(ViewLayerTest, BoundInRTL) { - std::string locale = l10n_util::GetApplicationLocale(std::string()); - base::i18n::SetICUDefaultLocale("he"); - - View* view = new View; - widget()->SetContentsView(view); - - int content_width = view->width(); - - // |v1| is initially not attached to anything. So its layer will have the same - // bounds as the view. - View* v1 = new View; - v1->SetPaintToLayer(true); - v1->SetBounds(10, 10, 20, 10); - EXPECT_EQ(gfx::Rect(10, 10, 20, 10), - v1->layer()->bounds()); - - // Once |v1| is attached to the widget, its layer will get RTL-appropriate - // bounds. - view->AddChildView(v1); - EXPECT_EQ(gfx::Rect(content_width - 30, 10, 20, 10), - v1->layer()->bounds()); - gfx::Rect l1bounds = v1->layer()->bounds(); - - // Now attach a View to the widget first, then create a layer for it. Make - // sure the bounds are correct. - View* v2 = new View; - v2->SetBounds(50, 10, 30, 10); - EXPECT_FALSE(v2->layer()); - view->AddChildView(v2); - v2->SetPaintToLayer(true); - EXPECT_EQ(gfx::Rect(content_width - 80, 10, 30, 10), - v2->layer()->bounds()); - gfx::Rect l2bounds = v2->layer()->bounds(); - - view->SetPaintToLayer(true); - EXPECT_EQ(l1bounds, v1->layer()->bounds()); - EXPECT_EQ(l2bounds, v2->layer()->bounds()); - - // Move one of the views. Make sure the layer is positioned correctly - // afterwards. - v1->SetBounds(v1->x() - 5, v1->y(), v1->width(), v1->height()); - l1bounds.set_x(l1bounds.x() + 5); - EXPECT_EQ(l1bounds, v1->layer()->bounds()); - - view->SetPaintToLayer(false); - EXPECT_EQ(l1bounds, v1->layer()->bounds()); - EXPECT_EQ(l2bounds, v2->layer()->bounds()); - - // Move a view again. - v2->SetBounds(v2->x() + 5, v2->y(), v2->width(), v2->height()); - l2bounds.set_x(l2bounds.x() - 5); - EXPECT_EQ(l2bounds, v2->layer()->bounds()); - - // Reset locale. - base::i18n::SetICUDefaultLocale(locale); -} - -// Makes sure a transform persists after toggling the visibility. -TEST_F(ViewLayerTest, ToggleVisibilityWithTransform) { - View* view = new View; - gfx::Transform transform; - transform.Scale(2.0, 2.0); - view->SetTransform(transform); - widget()->SetContentsView(view); - EXPECT_EQ(2.0f, view->GetTransform().matrix().get(0, 0)); - - view->SetVisible(false); - EXPECT_EQ(2.0f, view->GetTransform().matrix().get(0, 0)); - - view->SetVisible(true); - EXPECT_EQ(2.0f, view->GetTransform().matrix().get(0, 0)); -} - -// Verifies a transform persists after removing/adding a view with a transform. -TEST_F(ViewLayerTest, ResetTransformOnLayerAfterAdd) { - View* view = new View; - gfx::Transform transform; - transform.Scale(2.0, 2.0); - view->SetTransform(transform); - widget()->SetContentsView(view); - EXPECT_EQ(2.0f, view->GetTransform().matrix().get(0, 0)); - ASSERT_TRUE(view->layer() != NULL); - EXPECT_EQ(2.0f, view->layer()->transform().matrix().get(0, 0)); - - View* parent = view->parent(); - parent->RemoveChildView(view); - parent->AddChildView(view); - - EXPECT_EQ(2.0f, view->GetTransform().matrix().get(0, 0)); - ASSERT_TRUE(view->layer() != NULL); - EXPECT_EQ(2.0f, view->layer()->transform().matrix().get(0, 0)); -} - -// Makes sure that layer visibility is correct after toggling View visibility. -TEST_F(ViewLayerTest, ToggleVisibilityWithLayer) { - View* content_view = new View; - widget()->SetContentsView(content_view); - - // The view isn't attached to a widget or a parent view yet. But it should - // still have a layer, but the layer should not be attached to the root - // layer. - View* v1 = new View; - v1->SetPaintToLayer(true); - EXPECT_TRUE(v1->layer()); - EXPECT_FALSE(LayerIsAncestor(widget()->GetCompositor()->root_layer(), - v1->layer())); - - // Once the view is attached to a widget, its layer should be attached to the - // root layer and visible. - content_view->AddChildView(v1); - EXPECT_TRUE(LayerIsAncestor(widget()->GetCompositor()->root_layer(), - v1->layer())); - EXPECT_TRUE(v1->layer()->IsDrawn()); - - v1->SetVisible(false); - EXPECT_FALSE(v1->layer()->IsDrawn()); - - v1->SetVisible(true); - EXPECT_TRUE(v1->layer()->IsDrawn()); - - widget()->Hide(); - EXPECT_FALSE(v1->layer()->IsDrawn()); - - widget()->Show(); - EXPECT_TRUE(v1->layer()->IsDrawn()); -} - -// Tests that the layers in the subtree are orphaned after a View is removed -// from the parent. -TEST_F(ViewLayerTest, OrphanLayerAfterViewRemove) { - View* content_view = new View; - widget()->SetContentsView(content_view); - - View* v1 = new View; - content_view->AddChildView(v1); - - View* v2 = new View; - v1->AddChildView(v2); - v2->SetPaintToLayer(true); - EXPECT_TRUE(LayerIsAncestor(widget()->GetCompositor()->root_layer(), - v2->layer())); - EXPECT_TRUE(v2->layer()->IsDrawn()); - - content_view->RemoveChildView(v1); - - EXPECT_FALSE(LayerIsAncestor(widget()->GetCompositor()->root_layer(), - v2->layer())); - - // Reparent |v2|. - content_view->AddChildView(v2); - delete v1; - v1 = NULL; - EXPECT_TRUE(LayerIsAncestor(widget()->GetCompositor()->root_layer(), - v2->layer())); - EXPECT_TRUE(v2->layer()->IsDrawn()); -} - -class PaintTrackingView : public View { - public: - PaintTrackingView() : painted_(false) { - } - - bool painted() const { return painted_; } - void set_painted(bool value) { painted_ = value; } - - virtual void OnPaint(gfx::Canvas* canvas) override { - painted_ = true; - } - - private: - bool painted_; - - DISALLOW_COPY_AND_ASSIGN(PaintTrackingView); -}; - -// Makes sure child views with layers aren't painted when paint starts at an -// ancestor. -TEST_F(ViewLayerTest, DontPaintChildrenWithLayers) { - PaintTrackingView* content_view = new PaintTrackingView; - widget()->SetContentsView(content_view); - content_view->SetPaintToLayer(true); - GetRootLayer()->GetCompositor()->ScheduleDraw(); - ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor()); - GetRootLayer()->SchedulePaint(gfx::Rect(0, 0, 10, 10)); - content_view->set_painted(false); - // content_view no longer has a dirty rect. Paint from the root and make sure - // PaintTrackingView isn't painted. - GetRootLayer()->GetCompositor()->ScheduleDraw(); - ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor()); - EXPECT_FALSE(content_view->painted()); - - // Make content_view have a dirty rect, paint the layers and make sure - // PaintTrackingView is painted. - content_view->layer()->SchedulePaint(gfx::Rect(0, 0, 10, 10)); - GetRootLayer()->GetCompositor()->ScheduleDraw(); - ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor()); - EXPECT_TRUE(content_view->painted()); -} - -// Tests that the visibility of child layers are updated correctly when a View's -// visibility changes. -TEST_F(ViewLayerTest, VisibilityChildLayers) { - View* v1 = new View; - v1->SetPaintToLayer(true); - widget()->SetContentsView(v1); - - View* v2 = new View; - v1->AddChildView(v2); - - View* v3 = new View; - v2->AddChildView(v3); - v3->SetVisible(false); - - View* v4 = new View; - v4->SetPaintToLayer(true); - v3->AddChildView(v4); - - EXPECT_TRUE(v1->layer()->IsDrawn()); - EXPECT_FALSE(v4->layer()->IsDrawn()); - - v2->SetVisible(false); - EXPECT_TRUE(v1->layer()->IsDrawn()); - EXPECT_FALSE(v4->layer()->IsDrawn()); - - v2->SetVisible(true); - EXPECT_TRUE(v1->layer()->IsDrawn()); - EXPECT_FALSE(v4->layer()->IsDrawn()); - - v2->SetVisible(false); - EXPECT_TRUE(v1->layer()->IsDrawn()); - EXPECT_FALSE(v4->layer()->IsDrawn()); - EXPECT_TRUE(ViewAndLayerTreeAreConsistent(v1, v1->layer())); - - v3->SetVisible(true); - EXPECT_TRUE(v1->layer()->IsDrawn()); - EXPECT_FALSE(v4->layer()->IsDrawn()); - EXPECT_TRUE(ViewAndLayerTreeAreConsistent(v1, v1->layer())); - - // Reparent |v3| to |v1|. - v1->AddChildView(v3); - EXPECT_TRUE(v1->layer()->IsDrawn()); - EXPECT_TRUE(v4->layer()->IsDrawn()); - EXPECT_TRUE(ViewAndLayerTreeAreConsistent(v1, v1->layer())); -} - -// This test creates a random View tree, and then randomly reorders child views, -// reparents views etc. Unrelated changes can appear to break this test. So -// marking this as FLAKY. -TEST_F(ViewLayerTest, DISABLED_ViewLayerTreesInSync) { - View* content = new View; - content->SetPaintToLayer(true); - widget()->SetContentsView(content); - widget()->Show(); - - ConstructTree(content, 5); - EXPECT_TRUE(ViewAndLayerTreeAreConsistent(content, content->layer())); - - ScrambleTree(content); - EXPECT_TRUE(ViewAndLayerTreeAreConsistent(content, content->layer())); - - ScrambleTree(content); - EXPECT_TRUE(ViewAndLayerTreeAreConsistent(content, content->layer())); - - ScrambleTree(content); - EXPECT_TRUE(ViewAndLayerTreeAreConsistent(content, content->layer())); -} - -// Verifies when views are reordered the layer is also reordered. The widget is -// providing the parent layer. -TEST_F(ViewLayerTest, ReorderUnderWidget) { - View* content = new View; - widget()->SetContentsView(content); - View* c1 = new View; - c1->SetPaintToLayer(true); - content->AddChildView(c1); - View* c2 = new View; - c2->SetPaintToLayer(true); - content->AddChildView(c2); - - ui::Layer* parent_layer = c1->layer()->parent(); - ASSERT_TRUE(parent_layer); - ASSERT_EQ(2u, parent_layer->children().size()); - EXPECT_EQ(c1->layer(), parent_layer->children()[0]); - EXPECT_EQ(c2->layer(), parent_layer->children()[1]); - - // Move c1 to the front. The layers should have moved too. - content->ReorderChildView(c1, -1); - EXPECT_EQ(c1->layer(), parent_layer->children()[1]); - EXPECT_EQ(c2->layer(), parent_layer->children()[0]); -} - -// Verifies that the layer of a view can be acquired properly. -TEST_F(ViewLayerTest, AcquireLayer) { - View* content = new View; - widget()->SetContentsView(content); - scoped_ptr<View> c1(new View); - c1->SetPaintToLayer(true); - EXPECT_TRUE(c1->layer()); - content->AddChildView(c1.get()); - - scoped_ptr<ui::Layer> layer(c1->AcquireLayer()); - EXPECT_EQ(layer.get(), c1->layer()); - - scoped_ptr<ui::Layer> layer2(c1->RecreateLayer()); - EXPECT_NE(c1->layer(), layer2.get()); - - // Destroy view before destroying layer. - c1.reset(); -} - -// Verify the z-order of the layers as a result of calling RecreateLayer(). -TEST_F(ViewLayerTest, RecreateLayerZOrder) { - scoped_ptr<View> v(new View()); - v->SetPaintToLayer(true); - - View* v1 = new View(); - v1->SetPaintToLayer(true); - v->AddChildView(v1); - View* v2 = new View(); - v2->SetPaintToLayer(true); - v->AddChildView(v2); - - // Test the initial z-order. - const std::vector<ui::Layer*>& child_layers_pre = v->layer()->children(); - ASSERT_EQ(2u, child_layers_pre.size()); - EXPECT_EQ(v1->layer(), child_layers_pre[0]); - EXPECT_EQ(v2->layer(), child_layers_pre[1]); - - scoped_ptr<ui::Layer> v1_old_layer(v1->RecreateLayer()); - - // Test the new layer order. We expect: |v1| |v1_old_layer| |v2|. - // for |v1| and |v2|. - const std::vector<ui::Layer*>& child_layers_post = v->layer()->children(); - ASSERT_EQ(3u, child_layers_post.size()); - EXPECT_EQ(v1->layer(), child_layers_post[0]); - EXPECT_EQ(v1_old_layer, child_layers_post[1]); - EXPECT_EQ(v2->layer(), child_layers_post[2]); -} - -// Verify the z-order of the layers as a result of calling RecreateLayer when -// the widget is the parent with the layer. -TEST_F(ViewLayerTest, RecreateLayerZOrderWidgetParent) { - View* v = new View(); - widget()->SetContentsView(v); - - View* v1 = new View(); - v1->SetPaintToLayer(true); - v->AddChildView(v1); - View* v2 = new View(); - v2->SetPaintToLayer(true); - v->AddChildView(v2); - - ui::Layer* root_layer = GetRootLayer(); - - // Test the initial z-order. - const std::vector<ui::Layer*>& child_layers_pre = root_layer->children(); - ASSERT_EQ(2u, child_layers_pre.size()); - EXPECT_EQ(v1->layer(), child_layers_pre[0]); - EXPECT_EQ(v2->layer(), child_layers_pre[1]); - - scoped_ptr<ui::Layer> v1_old_layer(v1->RecreateLayer()); - - // Test the new layer order. We expect: |v1| |v1_old_layer| |v2|. - const std::vector<ui::Layer*>& child_layers_post = root_layer->children(); - ASSERT_EQ(3u, child_layers_post.size()); - EXPECT_EQ(v1->layer(), child_layers_post[0]); - EXPECT_EQ(v1_old_layer, child_layers_post[1]); - EXPECT_EQ(v2->layer(), child_layers_post[2]); -} - -// Verifies RecreateLayer() moves all Layers over, even those that don't have -// a View. -TEST_F(ViewLayerTest, RecreateLayerMovesNonViewChildren) { - View v; - v.SetPaintToLayer(true); - View child; - child.SetPaintToLayer(true); - v.AddChildView(&child); - ASSERT_TRUE(v.layer() != NULL); - ASSERT_EQ(1u, v.layer()->children().size()); - EXPECT_EQ(v.layer()->children()[0], child.layer()); - - ui::Layer layer(ui::LAYER_NOT_DRAWN); - v.layer()->Add(&layer); - v.layer()->StackAtBottom(&layer); - - scoped_ptr<ui::Layer> old_layer(v.RecreateLayer()); - - // All children should be moved from old layer to new layer. - ASSERT_TRUE(old_layer.get() != NULL); - EXPECT_TRUE(old_layer->children().empty()); - - // And new layer should have the two children. - ASSERT_TRUE(v.layer() != NULL); - ASSERT_EQ(2u, v.layer()->children().size()); - EXPECT_EQ(v.layer()->children()[0], &layer); - EXPECT_EQ(v.layer()->children()[1], child.layer()); -} - -class BoundsTreeTestView : public View { - public: - BoundsTreeTestView() {} - - virtual void PaintChildren(gfx::Canvas* canvas, - const CullSet& cull_set) override { - // Save out a copy of the cull_set before calling the base implementation. - last_cull_set_.clear(); - if (cull_set.cull_set_) { - for (base::hash_set<intptr_t>::iterator it = cull_set.cull_set_->begin(); - it != cull_set.cull_set_->end(); - ++it) { - last_cull_set_.insert(reinterpret_cast<View*>(*it)); - } - } - View::PaintChildren(canvas, cull_set); - } - - std::set<View*> last_cull_set_; -}; - -TEST_F(ViewLayerTest, BoundsTreePaintUpdatesCullSet) { - BoundsTreeTestView* test_view = new BoundsTreeTestView; - widget()->SetContentsView(test_view); - - View* v1 = new View(); - v1->SetBoundsRect(gfx::Rect(10, 15, 150, 151)); - test_view->AddChildView(v1); - - View* v2 = new View(); - v2->SetBoundsRect(gfx::Rect(20, 33, 40, 50)); - v1->AddChildView(v2); - - // Schedule a full-view paint to get everyone's rectangles updated. - test_view->SchedulePaintInRect(test_view->bounds()); - GetRootLayer()->GetCompositor()->ScheduleDraw(); - ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor()); - - // Now we have test_view - v1 - v2. Damage to only test_view should only - // return root_view and test_view. - test_view->SchedulePaintInRect(gfx::Rect(0, 0, 1, 1)); - GetRootLayer()->GetCompositor()->ScheduleDraw(); - ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor()); - EXPECT_EQ(2U, test_view->last_cull_set_.size()); - EXPECT_EQ(1U, test_view->last_cull_set_.count(widget()->GetRootView())); - EXPECT_EQ(1U, test_view->last_cull_set_.count(test_view)); - - // Damage to v1 only should only return root_view, test_view, and v1. - test_view->SchedulePaintInRect(gfx::Rect(11, 16, 1, 1)); - GetRootLayer()->GetCompositor()->ScheduleDraw(); - ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor()); - EXPECT_EQ(3U, test_view->last_cull_set_.size()); - EXPECT_EQ(1U, test_view->last_cull_set_.count(widget()->GetRootView())); - EXPECT_EQ(1U, test_view->last_cull_set_.count(test_view)); - EXPECT_EQ(1U, test_view->last_cull_set_.count(v1)); - - // A Damage rect inside v2 should get all 3 views back in the |last_cull_set_| - // on call to TestView::Paint(), along with the widget root view. - test_view->SchedulePaintInRect(gfx::Rect(31, 49, 1, 1)); - GetRootLayer()->GetCompositor()->ScheduleDraw(); - ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor()); - EXPECT_EQ(4U, test_view->last_cull_set_.size()); - EXPECT_EQ(1U, test_view->last_cull_set_.count(widget()->GetRootView())); - EXPECT_EQ(1U, test_view->last_cull_set_.count(test_view)); - EXPECT_EQ(1U, test_view->last_cull_set_.count(v1)); - EXPECT_EQ(1U, test_view->last_cull_set_.count(v2)); -} - -TEST_F(ViewLayerTest, BoundsTreeWithRTL) { - std::string locale = l10n_util::GetApplicationLocale(std::string()); - base::i18n::SetICUDefaultLocale("ar"); - - BoundsTreeTestView* test_view = new BoundsTreeTestView; - widget()->SetContentsView(test_view); - - // Add child views, which should be in RTL coordinate space of parent view. - View* v1 = new View; - v1->SetBoundsRect(gfx::Rect(10, 12, 25, 26)); - test_view->AddChildView(v1); - - View* v2 = new View; - v2->SetBoundsRect(gfx::Rect(5, 6, 7, 8)); - v1->AddChildView(v2); - - // Schedule a full-view paint to get everyone's rectangles updated. - test_view->SchedulePaintInRect(test_view->bounds()); - GetRootLayer()->GetCompositor()->ScheduleDraw(); - ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor()); - - // Damage to the right side of the parent view should touch both child views. - gfx::Rect rtl_damage(test_view->bounds().width() - 16, 18, 1, 1); - test_view->SchedulePaintInRect(rtl_damage); - GetRootLayer()->GetCompositor()->ScheduleDraw(); - ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor()); - EXPECT_EQ(4U, test_view->last_cull_set_.size()); - EXPECT_EQ(1U, test_view->last_cull_set_.count(widget()->GetRootView())); - EXPECT_EQ(1U, test_view->last_cull_set_.count(test_view)); - EXPECT_EQ(1U, test_view->last_cull_set_.count(v1)); - EXPECT_EQ(1U, test_view->last_cull_set_.count(v2)); - - // Damage to the left side of the parent view should only touch the - // container views. - gfx::Rect ltr_damage(16, 18, 1, 1); - test_view->SchedulePaintInRect(ltr_damage); - GetRootLayer()->GetCompositor()->ScheduleDraw(); - ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor()); - EXPECT_EQ(2U, test_view->last_cull_set_.size()); - EXPECT_EQ(1U, test_view->last_cull_set_.count(widget()->GetRootView())); - EXPECT_EQ(1U, test_view->last_cull_set_.count(test_view)); - - // Reset locale. - base::i18n::SetICUDefaultLocale(locale); -} - -TEST_F(ViewLayerTest, BoundsTreeSetBoundsChangesCullSet) { - BoundsTreeTestView* test_view = new BoundsTreeTestView; - widget()->SetContentsView(test_view); - - View* v1 = new View; - v1->SetBoundsRect(gfx::Rect(5, 6, 100, 101)); - test_view->AddChildView(v1); - - View* v2 = new View; - v2->SetBoundsRect(gfx::Rect(20, 33, 40, 50)); - v1->AddChildView(v2); - - // Schedule a full-view paint to get everyone's rectangles updated. - test_view->SchedulePaintInRect(test_view->bounds()); - GetRootLayer()->GetCompositor()->ScheduleDraw(); - ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor()); - - // Move v1 to a new origin out of the way of our next query. - v1->SetBoundsRect(gfx::Rect(50, 60, 100, 101)); - // The move will force a repaint. - GetRootLayer()->GetCompositor()->ScheduleDraw(); - ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor()); - - // Schedule a paint with damage rect where v1 used to be. - test_view->SchedulePaintInRect(gfx::Rect(5, 6, 10, 11)); - GetRootLayer()->GetCompositor()->ScheduleDraw(); - ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor()); - - // Should only have picked up root_view and test_view. - EXPECT_EQ(2U, test_view->last_cull_set_.size()); - EXPECT_EQ(1U, test_view->last_cull_set_.count(widget()->GetRootView())); - EXPECT_EQ(1U, test_view->last_cull_set_.count(test_view)); -} - -TEST_F(ViewLayerTest, BoundsTreeLayerChangeMakesNewTree) { - BoundsTreeTestView* test_view = new BoundsTreeTestView; - widget()->SetContentsView(test_view); - - View* v1 = new View; - v1->SetBoundsRect(gfx::Rect(5, 10, 15, 20)); - test_view->AddChildView(v1); - - View* v2 = new View; - v2->SetBoundsRect(gfx::Rect(1, 2, 3, 4)); - v1->AddChildView(v2); - - // Schedule a full-view paint to get everyone's rectangles updated. - test_view->SchedulePaintInRect(test_view->bounds()); - GetRootLayer()->GetCompositor()->ScheduleDraw(); - ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor()); - - // Set v1 to paint to its own layer, it should remove itself from the - // test_view heiarchy and no longer intersect with damage rects in that cull - // set. - v1->SetPaintToLayer(true); - - // Schedule another full-view paint. - test_view->SchedulePaintInRect(test_view->bounds()); - GetRootLayer()->GetCompositor()->ScheduleDraw(); - ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor()); - // v1 and v2 should no longer be present in the test_view cull_set. - EXPECT_EQ(2U, test_view->last_cull_set_.size()); - EXPECT_EQ(0U, test_view->last_cull_set_.count(v1)); - EXPECT_EQ(0U, test_view->last_cull_set_.count(v2)); - - // Now set v1 back to not painting to a layer. - v1->SetPaintToLayer(false); - // Schedule another full-view paint. - test_view->SchedulePaintInRect(test_view->bounds()); - GetRootLayer()->GetCompositor()->ScheduleDraw(); - ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor()); - // We should be back to the full cull set including v1 and v2. - EXPECT_EQ(4U, test_view->last_cull_set_.size()); - EXPECT_EQ(1U, test_view->last_cull_set_.count(widget()->GetRootView())); - EXPECT_EQ(1U, test_view->last_cull_set_.count(test_view)); - EXPECT_EQ(1U, test_view->last_cull_set_.count(v1)); - EXPECT_EQ(1U, test_view->last_cull_set_.count(v2)); -} - -TEST_F(ViewLayerTest, BoundsTreeRemoveChildRemovesBounds) { - BoundsTreeTestView* test_view = new BoundsTreeTestView; - widget()->SetContentsView(test_view); - - View* v1 = new View; - v1->SetBoundsRect(gfx::Rect(5, 10, 15, 20)); - test_view->AddChildView(v1); - - View* v2 = new View; - v2->SetBoundsRect(gfx::Rect(1, 2, 3, 4)); - v1->AddChildView(v2); - - // Schedule a full-view paint to get everyone's rectangles updated. - test_view->SchedulePaintInRect(test_view->bounds()); - GetRootLayer()->GetCompositor()->ScheduleDraw(); - ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor()); - - // Now remove v1 from the root view. - test_view->RemoveChildView(v1); - - // Schedule another full-view paint. - test_view->SchedulePaintInRect(test_view->bounds()); - GetRootLayer()->GetCompositor()->ScheduleDraw(); - ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor()); - // v1 and v2 should no longer be present in the test_view cull_set. - EXPECT_EQ(2U, test_view->last_cull_set_.size()); - EXPECT_EQ(0U, test_view->last_cull_set_.count(v1)); - EXPECT_EQ(0U, test_view->last_cull_set_.count(v2)); - - // View v1 and v2 are no longer part of view hierarchy and therefore won't be - // deleted with that hierarchy. - delete v1; -} - -TEST_F(ViewLayerTest, BoundsTreeMoveViewMovesBounds) { - BoundsTreeTestView* test_view = new BoundsTreeTestView; - widget()->SetContentsView(test_view); - - // Build hierarchy v1 - v2 - v3. - View* v1 = new View; - v1->SetBoundsRect(gfx::Rect(20, 30, 150, 160)); - test_view->AddChildView(v1); - - View* v2 = new View; - v2->SetBoundsRect(gfx::Rect(5, 10, 40, 50)); - v1->AddChildView(v2); - - View* v3 = new View; - v3->SetBoundsRect(gfx::Rect(1, 2, 3, 4)); - v2->AddChildView(v3); - - // Schedule a full-view paint and ensure all views are present in the cull. - test_view->SchedulePaintInRect(test_view->bounds()); - GetRootLayer()->GetCompositor()->ScheduleDraw(); - ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor()); - EXPECT_EQ(5U, test_view->last_cull_set_.size()); - EXPECT_EQ(1U, test_view->last_cull_set_.count(widget()->GetRootView())); - EXPECT_EQ(1U, test_view->last_cull_set_.count(test_view)); - EXPECT_EQ(1U, test_view->last_cull_set_.count(v1)); - EXPECT_EQ(1U, test_view->last_cull_set_.count(v2)); - EXPECT_EQ(1U, test_view->last_cull_set_.count(v3)); - - // Build an unrelated view hierarchy and move v2 in to it. - scoped_ptr<Widget> test_widget(new Widget); - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.bounds = gfx::Rect(10, 10, 500, 500); - params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - test_widget->Init(params); - test_widget->Show(); - BoundsTreeTestView* widget_view = new BoundsTreeTestView; - test_widget->SetContentsView(widget_view); - widget_view->AddChildView(v2); - - // Now schedule full-view paints in both widgets. - test_view->SchedulePaintInRect(test_view->bounds()); - widget_view->SchedulePaintInRect(widget_view->bounds()); - GetRootLayer()->GetCompositor()->ScheduleDraw(); - ui::DrawWaiterForTest::Wait(GetRootLayer()->GetCompositor()); - - // Only v1 should be present in the first cull set. - EXPECT_EQ(3U, test_view->last_cull_set_.size()); - EXPECT_EQ(1U, test_view->last_cull_set_.count(widget()->GetRootView())); - EXPECT_EQ(1U, test_view->last_cull_set_.count(test_view)); - EXPECT_EQ(1U, test_view->last_cull_set_.count(v1)); - - // We should find v2 and v3 in the widget_view cull_set. - EXPECT_EQ(4U, widget_view->last_cull_set_.size()); - EXPECT_EQ(1U, widget_view->last_cull_set_.count(test_widget->GetRootView())); - EXPECT_EQ(1U, widget_view->last_cull_set_.count(widget_view)); - EXPECT_EQ(1U, widget_view->last_cull_set_.count(v2)); - EXPECT_EQ(1U, widget_view->last_cull_set_.count(v3)); -} - -namespace { - -std::string ToString(const gfx::Vector2dF& vector) { - return base::StringPrintf("%.2f %0.2f", vector.x(), vector.y()); -} - -} // namespace - -TEST_F(ViewLayerTest, SnapLayerToPixel) { - View* v1 = new View; - - View* v11 = new View; - v1->AddChildView(v11); - - widget()->SetContentsView(v1); - - const gfx::Size& size = GetRootLayer()->GetCompositor()->size(); - GetRootLayer()->GetCompositor()->SetScaleAndSize(1.25f, size); - - v11->SetBoundsRect(gfx::Rect(1, 1, 10, 10)); - v1->SetBoundsRect(gfx::Rect(1, 1, 10, 10)); - v11->SetPaintToLayer(true); - - EXPECT_EQ("0.40 0.40", ToString(v11->layer()->subpixel_position_offset())); - - // Creating a layer in parent should update the child view's layer offset. - v1->SetPaintToLayer(true); - EXPECT_EQ("-0.20 -0.20", ToString(v1->layer()->subpixel_position_offset())); - EXPECT_EQ("-0.20 -0.20", ToString(v11->layer()->subpixel_position_offset())); - - // DSF change should get propagated and update offsets. - GetRootLayer()->GetCompositor()->SetScaleAndSize(1.5f, size); - EXPECT_EQ("0.33 0.33", ToString(v1->layer()->subpixel_position_offset())); - EXPECT_EQ("0.33 0.33", ToString(v11->layer()->subpixel_position_offset())); - - // Deleting parent's layer should update the child view's layer's offset. - v1->SetPaintToLayer(false); - EXPECT_EQ("0.00 0.00", ToString(v11->layer()->subpixel_position_offset())); - - // Setting parent view should update the child view's layer's offset. - v1->SetBoundsRect(gfx::Rect(2, 2, 10, 10)); - EXPECT_EQ("0.33 0.33", ToString(v11->layer()->subpixel_position_offset())); - - // Setting integral DSF should reset the offset. - GetRootLayer()->GetCompositor()->SetScaleAndSize(2.0f, size); - EXPECT_EQ("0.00 0.00", ToString(v11->layer()->subpixel_position_offset())); -} - -TEST_F(ViewTest, FocusableAssertions) { - // View subclasses may change insets based on whether they are focusable, - // which effects the preferred size. To avoid preferred size changing around - // these Views need to key off the last value set to SetFocusable(), not - // whether the View is focusable right now. For this reason it's important - // that focusable() return the last value passed to SetFocusable and not - // whether the View is focusable right now. - TestView view; - view.SetFocusable(true); - EXPECT_TRUE(view.focusable()); - view.SetEnabled(false); - EXPECT_TRUE(view.focusable()); - view.SetFocusable(false); - EXPECT_FALSE(view.focusable()); -} - -// Verifies when a view is deleted it is removed from ViewStorage. -TEST_F(ViewTest, UpdateViewStorageOnDelete) { - ViewStorage* view_storage = ViewStorage::GetInstance(); - const int storage_id = view_storage->CreateStorageID(); - { - View view; - view_storage->StoreView(storage_id, &view); - } - EXPECT_TRUE(view_storage->RetrieveView(storage_id) == NULL); -} - -//////////////////////////////////////////////////////////////////////////////// -// NativeTheme -//////////////////////////////////////////////////////////////////////////////// - -void TestView::OnNativeThemeChanged(const ui::NativeTheme* native_theme) { - native_theme_ = native_theme; -} - -TEST_F(ViewTest, OnNativeThemeChanged) { - TestView* test_view = new TestView(); - EXPECT_FALSE(test_view->native_theme_); - TestView* test_view_child = new TestView(); - EXPECT_FALSE(test_view_child->native_theme_); - - // Child view added before the widget hierarchy exists should get the - // new native theme notification. - test_view->AddChildView(test_view_child); - - scoped_ptr<Widget> widget(new Widget); - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); - params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget->Init(params); - - widget->GetRootView()->AddChildView(test_view); - EXPECT_TRUE(test_view->native_theme_); - EXPECT_EQ(widget->GetNativeTheme(), test_view->native_theme_); - EXPECT_TRUE(test_view_child->native_theme_); - EXPECT_EQ(widget->GetNativeTheme(), test_view_child->native_theme_); - - // Child view added after the widget hierarchy exists should also get the - // notification. - TestView* test_view_child_2 = new TestView(); - test_view->AddChildView(test_view_child_2); - EXPECT_TRUE(test_view_child_2->native_theme_); - EXPECT_EQ(widget->GetNativeTheme(), test_view_child_2->native_theme_); - - widget->CloseNow(); -} - -} // namespace views
diff --git a/ui/views/view_unittest_aura.cc b/ui/views/view_unittest_aura.cc deleted file mode 100644 index 5b64910..0000000 --- a/ui/views/view_unittest_aura.cc +++ /dev/null
@@ -1,160 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/view.h" - -#include "base/memory/scoped_ptr.h" -#include "ui/aura/window.h" -#include "ui/compositor/layer.h" -#include "ui/compositor/layer_tree_owner.h" -#include "ui/compositor/test/test_layers.h" -#include "ui/gfx/geometry/rect.h" -#include "ui/views/test/views_test_base.h" -#include "ui/views/view_constants_aura.h" -#include "ui/views/widget/widget.h" -#include "ui/wm/core/window_util.h" - -namespace views { - -namespace { - -// Creates a widget of TYPE_CONTROL. -// The caller takes ownership of the returned widget. -Widget* CreateControlWidget(aura::Window* parent, const gfx::Rect& bounds) { - Widget::InitParams params(Widget::InitParams::TYPE_CONTROL); - params.parent = parent; - params.bounds = bounds; - Widget* widget = new Widget(); - widget->Init(params); - return widget; -} - -// Returns a view with a layer with the passed in |bounds| and |layer_name|. -// The caller takes ownership of the returned view. -View* CreateViewWithLayer(const gfx::Rect& bounds, const char* layer_name) { - View* view = new View(); - view->SetBoundsRect(bounds); - view->SetPaintToLayer(true); - view->layer()->set_name(layer_name); - return view; -} - -} // namespace - -typedef ViewsTestBase ViewAuraTest; - -// Test that wm::RecreateLayers() recreates the layers for all child windows and -// all child views and that the z-order of the recreated layers matches that of -// the original layers. -// Test hierarchy: -// w1 -// +-- v1 -// +-- v2 (no layer) -// +-- v3 (no layer) -// +-- v4 -// +-- w2 -// +-- v5 -// +-- v6 -// +-- v7 -// +-- v8 -// +-- v9 -TEST_F(ViewAuraTest, RecreateLayersWithWindows) { - Widget* w1 = CreateControlWidget(GetContext(), gfx::Rect(0, 0, 100, 100)); - w1->GetNativeView()->layer()->set_name("w1"); - - View* v2 = new View(); - v2->SetBounds(0, 1, 100, 101); - View* v3 = new View(); - v3->SetBounds(0, 2, 100, 102); - View* w2_host_view = new View(); - - View* v1 = CreateViewWithLayer(gfx::Rect(0, 3, 100, 103), "v1"); - ui::Layer* v1_layer = v1->layer(); - w1->GetRootView()->AddChildView(v1); - w1->GetRootView()->AddChildView(v2); - v2->AddChildView(v3); - View* v4 = CreateViewWithLayer(gfx::Rect(0, 4, 100, 104), "v4"); - ui::Layer* v4_layer = v4->layer(); - v2->AddChildView(v4); - - w1->GetRootView()->AddChildView(w2_host_view); - View* v7 = CreateViewWithLayer(gfx::Rect(0, 4, 100, 104), "v7"); - ui::Layer* v7_layer = v7->layer(); - w1->GetRootView()->AddChildView(v7); - - View* v8 = CreateViewWithLayer(gfx::Rect(0, 4, 100, 104), "v8"); - ui::Layer* v8_layer = v8->layer(); - v7->AddChildView(v8); - - View* v9 = CreateViewWithLayer(gfx::Rect(0, 4, 100, 104), "v9"); - ui::Layer* v9_layer = v9->layer(); - v7->AddChildView(v9); - - Widget* w2 = - CreateControlWidget(w1->GetNativeView(), gfx::Rect(0, 5, 100, 105)); - w2->GetNativeView()->layer()->set_name("w2"); - w2->GetNativeView()->SetProperty(kHostViewKey, w2_host_view); - - View* v5 = CreateViewWithLayer(gfx::Rect(0, 6, 100, 106), "v5"); - w2->GetRootView()->AddChildView(v5); - View* v6 = CreateViewWithLayer(gfx::Rect(0, 7, 100, 107), "v6"); - ui::Layer* v6_layer = v6->layer(); - v5->AddChildView(v6); - - // Test the initial order of the layers. - ui::Layer* w1_layer = w1->GetNativeView()->layer(); - ASSERT_EQ("w1", w1_layer->name()); - ASSERT_EQ("v1 v4 w2 v7", ui::test::ChildLayerNamesAsString(*w1_layer)); - ui::Layer* w2_layer = w1_layer->children()[2]; - ASSERT_EQ("v5", ui::test::ChildLayerNamesAsString(*w2_layer)); - ui::Layer* v5_layer = w2_layer->children()[0]; - ASSERT_EQ("v6", ui::test::ChildLayerNamesAsString(*v5_layer)); - - { - scoped_ptr<ui::LayerTreeOwner> cloned_owner( - wm::RecreateLayers(w1->GetNativeView())); - EXPECT_EQ(w1_layer, cloned_owner->root()); - EXPECT_NE(w1_layer, w1->GetNativeView()->layer()); - - // The old layers should still exist and have the same hierarchy. - ASSERT_EQ("w1", w1_layer->name()); - ASSERT_EQ("v1 v4 w2 v7", ui::test::ChildLayerNamesAsString(*w1_layer)); - ASSERT_EQ("v5", ui::test::ChildLayerNamesAsString(*w2_layer)); - ASSERT_EQ("v6", ui::test::ChildLayerNamesAsString(*v5_layer)); - EXPECT_EQ("v8 v9", ui::test::ChildLayerNamesAsString(*v7_layer)); - - ASSERT_EQ(4u, w1_layer->children().size()); - EXPECT_EQ(v1_layer, w1_layer->children()[0]); - EXPECT_EQ(v4_layer, w1_layer->children()[1]); - EXPECT_EQ(w2_layer, w1_layer->children()[2]); - EXPECT_EQ(v7_layer, w1_layer->children()[3]); - - ASSERT_EQ(1u, w2_layer->children().size()); - EXPECT_EQ(v5_layer, w2_layer->children()[0]); - - ASSERT_EQ(1u, v5_layer->children().size()); - EXPECT_EQ(v6_layer, v5_layer->children()[0]); - - ASSERT_EQ(0u, v6_layer->children().size()); - - EXPECT_EQ(2u, v7_layer->children().size()); - EXPECT_EQ(v8_layer, v7_layer->children()[0]); - EXPECT_EQ(v9_layer, v7_layer->children()[1]); - - // The cloned layers should have the same hierarchy as old. - ui::Layer* w1_new_layer = w1->GetNativeView()->layer(); - EXPECT_EQ("w1", w1_new_layer->name()); - ASSERT_EQ("v1 v4 w2 v7", ui::test::ChildLayerNamesAsString(*w1_new_layer)); - ui::Layer* w2_new_layer = w1_new_layer->children()[2]; - ASSERT_EQ("v5", ui::test::ChildLayerNamesAsString(*w2_new_layer)); - ui::Layer* v5_new_layer = w2_new_layer->children()[0]; - ASSERT_EQ("v6", ui::test::ChildLayerNamesAsString(*v5_new_layer)); - ui::Layer* v7_new_layer = w1_new_layer->children()[3]; - ASSERT_EQ("v8 v9", ui::test::ChildLayerNamesAsString(*v7_new_layer)); - } - // The views and the widgets are destroyed when AuraTestHelper::TearDown() - // destroys root_window(). -} - -} // namespace views
diff --git a/ui/views/views.gyp b/ui/views/views.gyp deleted file mode 100644 index 31ac238..0000000 --- a/ui/views/views.gyp +++ /dev/null
@@ -1,746 +0,0 @@ -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. -{ - 'variables': { - 'chromium_code': 1, - # Sources lists shared with GN build. - 'views_sources': [ - 'accessibility/native_view_accessibility.cc', - 'accessibility/native_view_accessibility.h', - 'accessibility/native_view_accessibility_win.cc', - 'accessibility/native_view_accessibility_win.h', - 'accessible_pane_view.cc', - 'accessible_pane_view.h', - 'animation/bounds_animator.cc', - 'animation/bounds_animator.h', - 'animation/scroll_animator.cc', - 'animation/scroll_animator.h', - 'background.cc', - 'background.h', - 'border.cc', - 'border.h', - 'bubble/bubble_border.cc', - 'bubble/bubble_border.h', - 'bubble/bubble_delegate.cc', - 'bubble/bubble_delegate.h', - 'bubble/bubble_frame_view.cc', - 'bubble/bubble_frame_view.h', - 'button_drag_utils.cc', - 'button_drag_utils.h', - 'color_chooser/color_chooser_listener.h', - 'color_chooser/color_chooser_view.cc', - 'color_chooser/color_chooser_view.h', - 'color_constants.cc', - 'color_constants.h', - 'context_menu_controller.h', - 'controls/button/blue_button.cc', - 'controls/button/blue_button.h', - 'controls/button/button.cc', - 'controls/button/button.h', - 'controls/button/checkbox.cc', - 'controls/button/checkbox.h', - 'controls/button/custom_button.cc', - 'controls/button/custom_button.h', - 'controls/button/image_button.cc', - 'controls/button/image_button.h', - 'controls/button/label_button.cc', - 'controls/button/label_button.h', - 'controls/button/label_button_border.cc', - 'controls/button/label_button_border.h', - 'controls/button/menu_button.cc', - 'controls/button/menu_button.h', - 'controls/button/menu_button_listener.h', - 'controls/button/radio_button.cc', - 'controls/button/radio_button.h', - 'controls/combobox/combobox.cc', - 'controls/combobox/combobox.h', - 'controls/combobox/combobox_listener.h', - 'controls/focusable_border.cc', - 'controls/focusable_border.h', - 'controls/glow_hover_controller.cc', - 'controls/glow_hover_controller.h', - 'controls/image_view.cc', - 'controls/image_view.h', - 'controls/label.cc', - 'controls/label.h', - 'controls/link.cc', - 'controls/link.h', - 'controls/link_listener.h', - 'controls/menu/display_change_listener_aura.cc', - 'controls/menu/menu.cc', - 'controls/menu/menu.h', - 'controls/menu/menu_config.cc', - 'controls/menu/menu_config.h', - 'controls/menu/menu_config_aura.cc', - 'controls/menu/menu_config_win.cc', - 'controls/menu/menu_controller.cc', - 'controls/menu/menu_controller.h', - 'controls/menu/menu_controller_delegate.h', - 'controls/menu/menu_event_dispatcher_linux.cc', - 'controls/menu/menu_event_dispatcher_linux.h', - 'controls/menu/menu_delegate.cc', - 'controls/menu/menu_delegate.h', - 'controls/menu/menu_message_pump_dispatcher_win.cc', - 'controls/menu/menu_message_pump_dispatcher_win.h', - 'controls/menu/menu_message_loop.h', - 'controls/menu/menu_message_loop_aura.cc', - 'controls/menu/menu_message_loop_aura.h', - 'controls/menu/menu_host.cc', - 'controls/menu/menu_host.h', - 'controls/menu/menu_host_root_view.cc', - 'controls/menu/menu_host_root_view.h', - 'controls/menu/menu_insertion_delegate_win.h', - 'controls/menu/menu_item_view.cc', - 'controls/menu/menu_item_view.h', - 'controls/menu/menu_listener.cc', - 'controls/menu/menu_listener.h', - 'controls/menu/menu_model_adapter.cc', - 'controls/menu/menu_model_adapter.h', - 'controls/menu/menu_runner.cc', - 'controls/menu/menu_runner.h', - 'controls/menu/menu_runner_handler.h', - 'controls/menu/menu_runner_impl.cc', - 'controls/menu/menu_runner_impl.h', - 'controls/menu/menu_runner_impl_adapter.cc', - 'controls/menu/menu_runner_impl_adapter.h', - 'controls/menu/menu_runner_impl_interface.h', - 'controls/menu/menu_scroll_view_container.cc', - 'controls/menu/menu_scroll_view_container.h', - 'controls/menu/menu_separator.h', - 'controls/menu/menu_separator_views.cc', - 'controls/menu/menu_separator_win.cc', - 'controls/menu/menu_types.h', - 'controls/menu/native_menu_win.cc', - 'controls/menu/native_menu_win.h', - 'controls/menu/menu_image_util.cc', - 'controls/menu/menu_image_util.h', - 'controls/menu/submenu_view.cc', - 'controls/menu/submenu_view.h', - 'controls/message_box_view.cc', - 'controls/message_box_view.h', - 'controls/native/native_view_host.cc', - 'controls/native/native_view_host.h', - 'controls/native/native_view_host_aura.cc', - 'controls/native/native_view_host_aura.h', - 'controls/prefix_delegate.h', - 'controls/prefix_selector.cc', - 'controls/prefix_selector.h', - 'controls/progress_bar.cc', - 'controls/progress_bar.h', - 'controls/resize_area.cc', - 'controls/resize_area.h', - 'controls/resize_area_delegate.h', - 'controls/scroll_view.cc', - 'controls/scroll_view.h', - 'controls/scrollbar/base_scroll_bar.cc', - 'controls/scrollbar/base_scroll_bar.h', - 'controls/scrollbar/base_scroll_bar_button.cc', - 'controls/scrollbar/base_scroll_bar_button.h', - 'controls/scrollbar/base_scroll_bar_thumb.cc', - 'controls/scrollbar/base_scroll_bar_thumb.h', - 'controls/scrollbar/kennedy_scroll_bar.cc', - 'controls/scrollbar/kennedy_scroll_bar.h', - 'controls/scrollbar/native_scroll_bar_views.cc', - 'controls/scrollbar/native_scroll_bar_views.h', - 'controls/scrollbar/native_scroll_bar_wrapper.h', - 'controls/scrollbar/native_scroll_bar.cc', - 'controls/scrollbar/native_scroll_bar.h', - 'controls/scrollbar/overlay_scroll_bar.cc', - 'controls/scrollbar/overlay_scroll_bar.h', - 'controls/scrollbar/scroll_bar.cc', - 'controls/scrollbar/scroll_bar.h', - 'controls/separator.cc', - 'controls/separator.h', - 'controls/single_split_view.cc', - 'controls/single_split_view.h', - 'controls/single_split_view_listener.h', - 'controls/slide_out_view.cc', - 'controls/slide_out_view.h', - 'controls/slider.cc', - 'controls/slider.h', - 'controls/styled_label.cc', - 'controls/styled_label.h', - 'controls/styled_label_listener.h', - 'controls/tabbed_pane/tabbed_pane.cc', - 'controls/tabbed_pane/tabbed_pane.h', - 'controls/tabbed_pane/tabbed_pane_listener.h', - 'controls/table/table_header.cc', - 'controls/table/table_header.h', - 'controls/table/table_utils.cc', - 'controls/table/table_utils.h', - 'controls/table/table_view.cc', - 'controls/table/table_view.h', - 'controls/table/table_view_observer.h', - 'controls/table/table_view_row_background_painter.h', - 'controls/textfield/textfield.cc', - 'controls/textfield/textfield.h', - 'controls/textfield/textfield_controller.cc', - 'controls/textfield/textfield_controller.h', - 'controls/textfield/textfield_model.cc', - 'controls/textfield/textfield_model.h', - 'controls/throbber.cc', - 'controls/throbber.h', - 'controls/tree/tree_view.cc', - 'controls/tree/tree_view.h', - 'controls/tree/tree_view_controller.cc', - 'controls/tree/tree_view_controller.h', - 'cull_set.cc', - 'cull_set.h', - 'debug_utils.cc', - 'debug_utils.h', - 'drag_controller.h', - 'drag_utils.cc', - 'drag_utils.h', - 'drag_utils_aura.cc', - 'focus/external_focus_tracker.cc', - 'focus/external_focus_tracker.h', - 'focus/focus_manager.cc', - 'focus/focus_manager.h', - 'focus/focus_manager_delegate.h', - 'focus/focus_manager_factory.cc', - 'focus/focus_manager_factory.h', - 'focus/focus_search.cc', - 'focus/focus_search.h', - 'focus/view_storage.cc', - 'focus/view_storage.h', - 'focus/widget_focus_manager.cc', - 'focus/widget_focus_manager.h', - 'ime/input_method.h', - 'ime/input_method_base.cc', - 'ime/input_method_base.h', - 'ime/input_method_bridge.cc', - 'ime/input_method_bridge.h', - 'ime/input_method_delegate.h', - 'ime/mock_input_method.cc', - 'ime/mock_input_method.h', - 'ime/null_input_method.cc', - 'ime/null_input_method.h', - 'layout/box_layout.cc', - 'layout/box_layout.h', - 'layout/fill_layout.cc', - 'layout/fill_layout.h', - 'layout/grid_layout.cc', - 'layout/grid_layout.h', - 'layout/layout_constants.h', - 'layout/layout_manager.cc', - 'layout/layout_manager.h', - 'masked_targeter_delegate.cc', - 'masked_targeter_delegate.h', - 'metrics.cc', - 'metrics.h', - 'metrics_aura.cc', - 'mouse_constants.h', - 'mouse_watcher.h', - 'mouse_watcher_aura.cc', - 'native_cursor.h', - 'native_cursor_aura.cc', - 'native_theme_delegate.h', - 'painter.cc', - 'painter.h', - 'rect_based_targeting_utils.cc', - 'rect_based_targeting_utils.h', - 'repeat_controller.cc', - 'repeat_controller.h', - 'round_rect_painter.cc', - 'round_rect_painter.h', - 'shadow_border.cc', - 'shadow_border.h', - 'view.cc', - 'view.h', - 'view_constants.cc', - 'view_constants.h', - 'view_constants_aura.cc', - 'view_constants_aura.h', - 'view_model.cc', - 'view_model.h', - 'view_model_utils.cc', - 'view_model_utils.h', - 'view_targeter.cc', - 'view_targeter.h', - 'view_targeter_delegate.cc', - 'view_targeter_delegate.h', - 'views_switches.cc', - 'views_switches.h', - 'views_delegate.cc', - 'views_delegate.h', - 'views_touch_selection_controller_factory.h', - 'views_touch_selection_controller_factory_aura.cc', - 'widget/drop_helper.cc', - 'widget/drop_helper.h', - 'widget/root_view.cc', - 'widget/root_view.h', - 'widget/root_view_targeter.cc', - 'widget/root_view_targeter.h', - 'widget/monitor_win.cc', - 'widget/monitor_win.h', - 'widget/native_widget.h', - 'widget/native_widget_aura.cc', - 'widget/native_widget_aura.h', - 'widget/native_widget_delegate.h', - 'widget/native_widget_private.h', - 'widget/tooltip_manager_aura.cc', - 'widget/tooltip_manager_aura.h', - 'widget/tooltip_manager.cc', - 'widget/tooltip_manager.h', - 'widget/widget.cc', - 'widget/widget.h', - 'widget/widget_aura_utils.cc', - 'widget/widget_aura_utils.h', - 'widget/widget_delegate.cc', - 'widget/widget_delegate.h', - 'widget/widget_deletion_observer.cc', - 'widget/widget_deletion_observer.h', - 'widget/widget_observer.h', - 'widget/widget_removals_observer.h', - 'window/client_view.cc', - 'window/client_view.h', - 'window/custom_frame_view.cc', - 'window/custom_frame_view.h', - 'window/dialog_client_view.cc', - 'window/dialog_client_view.h', - 'window/dialog_delegate.cc', - 'window/dialog_delegate.h', - 'window/frame_background.cc', - 'window/frame_background.h', - 'window/frame_buttons.h', - 'window/native_frame_view.cc', - 'window/native_frame_view.h', - 'window/non_client_view.cc', - 'window/non_client_view.h', - 'window/window_button_order_provider.cc', - 'window/window_button_order_provider.h', - 'window/window_resources.h', - 'window/window_shape.cc', - 'window/window_shape.h', - ], - 'views_win_sources': [ - 'controls/menu/menu_wrapper.h', - 'controls/menu/menu_2.cc', - 'controls/menu/menu_2.h', - 'win/fullscreen_handler.cc', - 'win/fullscreen_handler.h', - 'win/hwnd_message_handler.cc', - 'win/hwnd_message_handler.h', - 'win/hwnd_message_handler_delegate.h', - 'win/hwnd_util.h', - 'win/hwnd_util_aurawin.cc', - 'win/scoped_fullscreen_visibility.cc', - 'win/scoped_fullscreen_visibility.h', - 'widget/widget_hwnd_utils.cc', - 'widget/widget_hwnd_utils.h', - ], - 'views_aura_sources': [ - 'accessibility/ax_aura_obj_cache.cc', - 'accessibility/ax_aura_obj_cache.h', - 'accessibility/ax_view_obj_wrapper.cc', - 'accessibility/ax_view_obj_wrapper.h', - 'accessibility/ax_widget_obj_wrapper.cc', - 'accessibility/ax_widget_obj_wrapper.h', - 'accessibility/ax_window_obj_wrapper.cc', - 'accessibility/ax_window_obj_wrapper.h', - 'bubble/bubble_window_targeter.cc', - 'bubble/bubble_window_targeter.h', - 'bubble/tray_bubble_view.cc', - 'bubble/tray_bubble_view.h', - 'corewm/cursor_height_provider_win.cc', - 'corewm/cursor_height_provider_win.h', - 'corewm/tooltip.h', - 'corewm/tooltip_aura.cc', - 'corewm/tooltip_aura.h', - 'corewm/tooltip_controller.cc', - 'corewm/tooltip_controller.h', - 'corewm/tooltip_win.cc', - 'corewm/tooltip_win.h', - 'mouse_watcher_view_host.cc', - 'mouse_watcher_view_host.h', - 'touchui/touch_editing_menu.cc', - 'touchui/touch_editing_menu.h', - 'touchui/touch_selection_controller_impl.cc', - 'touchui/touch_selection_controller_impl.h', - 'widget/window_reorderer.cc', - 'widget/window_reorderer.h', - ], - 'views_test_support_sources': [ - 'controls/textfield/textfield_test_api.cc', - 'controls/textfield/textfield_test_api.h', - 'test/capture_tracking_view.cc', - 'test/capture_tracking_view.h', - 'test/desktop_test_views_delegate.h', - 'test/desktop_test_views_delegate_aura.cc', - 'test/focus_manager_test.h', - 'test/focus_manager_test.cc', - 'test/menu_runner_test_api.cc', - 'test/menu_runner_test_api.h', - 'test/slider_test_api.cc', - 'test/slider_test_api.h', - 'test/test_views.cc', - 'test/test_views.h', - 'test/test_views_delegate.h', - 'test/test_views_delegate_aura.cc', - 'test/test_views_delegate_mac.mm', - 'test/test_widget_observer.cc', - 'test/test_widget_observer.h', - 'test/views_test_base.cc', - 'test/views_test_base.h', - 'test/views_test_helper.cc', - 'test/views_test_helper.h', - 'test/views_test_helper_aura.cc', - 'test/views_test_helper_aura.h', - 'test/views_test_helper_mac.h', - 'test/views_test_helper_mac.mm', - 'test/widget_test.cc', - 'test/widget_test.h', - 'test/widget_test_aura.cc', - 'test/widget_test_mac.mm', - 'test/x11_property_change_waiter.cc', - 'test/x11_property_change_waiter.h', - ], - 'views_test_support_aura_sources': [ - 'corewm/tooltip_controller_test_helper.cc', - 'corewm/tooltip_controller_test_helper.h', - ], - 'views_unittests_sources': [ - 'accessibility/native_view_accessibility_unittest.cc', - 'accessibility/native_view_accessibility_win_unittest.cc', - 'accessible_pane_view_unittest.cc', - 'animation/bounds_animator_unittest.cc', - 'bubble/bubble_border_unittest.cc', - 'bubble/bubble_delegate_unittest.cc', - 'bubble/bubble_frame_view_unittest.cc', - 'bubble/bubble_window_targeter_unittest.cc', - 'controls/button/blue_button_unittest.cc', - 'controls/button/custom_button_unittest.cc', - 'controls/button/image_button_unittest.cc', - 'controls/button/label_button_unittest.cc', - 'controls/button/menu_button_unittest.cc', - 'controls/combobox/combobox_unittest.cc', - 'controls/label_unittest.cc', - 'controls/menu/menu_controller_unittest.cc', - 'controls/menu/menu_item_view_unittest.cc', - 'controls/menu/menu_model_adapter_unittest.cc', - 'controls/native/native_view_host_aura_unittest.cc', - 'controls/native/native_view_host_test_base.h', - 'controls/native/native_view_host_test_base.cc', - 'controls/native/native_view_host_unittest.cc', - 'controls/prefix_selector_unittest.cc', - 'controls/progress_bar_unittest.cc', - 'controls/scrollbar/scrollbar_unittest.cc', - 'controls/scroll_view_unittest.cc', - 'controls/single_split_view_unittest.cc', - 'controls/slider_unittest.cc', - 'controls/styled_label_unittest.cc', - 'controls/tabbed_pane/tabbed_pane_unittest.cc', - 'controls/table/table_utils_unittest.cc', - 'controls/table/table_view_unittest.cc', - 'controls/table/test_table_model.cc', - 'controls/table/test_table_model.h', - 'controls/textfield/textfield_unittest.cc', - 'controls/textfield/textfield_model_unittest.cc', - 'controls/tree/tree_view_unittest.cc', - 'focus/focus_manager_unittest.cc', - 'focus/focus_traversal_unittest.cc', - 'ime/input_method_bridge_unittest.cc', - 'layout/box_layout_unittest.cc', - 'layout/grid_layout_unittest.cc', - 'rect_based_targeting_utils_unittest.cc', - 'run_all_unittests.cc', - 'view_model_unittest.cc', - 'view_model_utils_unittest.cc', - 'view_targeter_unittest.cc', - 'view_unittest.cc', - 'view_unittest_aura.cc', - 'widget/native_widget_aura_unittest.cc', - 'widget/native_widget_unittest.cc', - 'widget/root_view_unittest.cc', - 'widget/widget_unittest.cc', - 'widget/window_reorderer_unittest.cc', - 'window/custom_frame_view_unittest.cc', - 'window/dialog_client_view_unittest.cc', - 'window/dialog_delegate_unittest.cc', - ], - 'views_unittests_aura_sources': [ - 'corewm/capture_controller_unittest.cc', - 'corewm/tooltip_aura_unittest.cc', - 'corewm/tooltip_controller_unittest.cc', - 'touchui/touch_selection_controller_impl_unittest.cc', - ], - }, - 'targets': [ - { - # GN version: //ui/views - 'target_name': 'views', - 'type': '<(component)', - 'dependencies': [ - '../../base/base.gyp:base', - '../../base/base.gyp:base_i18n', - '../../base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', - '../../skia/skia.gyp:skia', - '../../third_party/icu/icu.gyp:icui18n', - '../../third_party/icu/icu.gyp:icuuc', - '../../url/url.gyp:url_lib', - '../accessibility/accessibility.gyp:accessibility', - '../base/ui_base.gyp:ui_base', - '../compositor/compositor.gyp:compositor', - '../events/events.gyp:events', - '../events/events.gyp:events_base', - '../events/platform/events_platform.gyp:events_platform', - '../gfx/gfx.gyp:gfx', - '../gfx/gfx.gyp:gfx_geometry', - '../native_theme/native_theme.gyp:native_theme', - '../resources/ui_resources.gyp:ui_resources', - '../strings/ui_strings.gyp:ui_strings', - ], - 'defines': [ - 'VIEWS_IMPLEMENTATION', - ], - 'sources': [ - '<@(views_sources)', - ], - 'conditions': [ - ['use_ash==0', { - 'sources!': [ - 'bubble/tray_bubble_view.cc', - 'bubble/tray_bubble_view.h', - ], - }], - ['chromeos==0 and use_x11==1', { - 'dependencies': [ - '../display/display.gyp:display_util', - ], - }], - ['OS=="linux" and chromeos==0', { - 'dependencies': [ - '../shell_dialogs/shell_dialogs.gyp:shell_dialogs', - ], - 'sources!': [ - 'window/window_button_order_provider.cc', - ], - }, { # OS=="linux" and chromeos==0 - 'sources/': [ - ['exclude', 'linux_ui'], - ], - }], - ['OS=="win"', { - 'sources': [ - '<@(views_win_sources)', - ], - 'dependencies': [ - # For accessibility - '../../third_party/iaccessible2/iaccessible2.gyp:iaccessible2', - ], - 'include_dirs': [ - '../../third_party/wtl/include', - ], - 'link_settings': { - 'libraries': [ - '-limm32.lib', - '-loleacc.lib', - ], - 'msvs_settings': { - 'VCLinkerTool': { - 'DelayLoadDLLs': [ - 'user32.dll', - ], - }, - }, - }, - # TODO(jschuh): crbug.com/167187 fix size_t to int truncations. - 'msvs_disabled_warnings': [ 4267, ], - }], - ['use_ozone==1', { - 'dependencies': [ - '../ozone/ozone.gyp:ozone', - ], - }], - ['use_x11==1', { - 'dependencies': [ - '../../build/linux/system.gyp:x11', - '../../build/linux/system.gyp:xrandr', - '../events/platform/x11/x11_events_platform.gyp:x11_events_platform', - ], - }], - ['use_aura==1', { - 'sources': [ - '<@(views_aura_sources)', - ], - 'dependencies': [ - '../aura/aura.gyp:aura', - '../wm/wm.gyp:wm', - ], - }], - ], - }, # target_name: views - { - # GN version: //ui/views:test_support - 'target_name': 'views_test_support', - 'type': 'static_library', - 'dependencies': [ - '../../base/base.gyp:base', - '../../ipc/ipc.gyp:test_support_ipc', - '../../skia/skia.gyp:skia', - '../../testing/gtest.gyp:gtest', - '../base/ui_base.gyp:ui_base', - '../compositor/compositor.gyp:compositor', - '../compositor/compositor.gyp:compositor_test_support', - '../events/events.gyp:events', - '../events/events.gyp:events_test_support', - '../events/platform/events_platform.gyp:events_platform', - '../gfx/gfx.gyp:gfx', - '../gfx/gfx.gyp:gfx_geometry', - 'views', - ], - 'include_dirs': [ - '..', - ], - 'sources': [ - '<@(views_test_support_sources)', - ], - 'conditions': [ - ['use_aura==1', { - 'sources': [ '<@(views_test_support_aura_sources)' ], - 'dependencies': [ - '../aura/aura.gyp:aura', - '../aura/aura.gyp:aura_test_support', - '../wm/wm.gyp:wm', - ], - }], - ], - }, # target_name: views_test_support - { - # GN version: //ui/views:views_unittests - 'target_name': 'views_unittests', - 'type': 'executable', - 'dependencies': [ - '../../base/base.gyp:base', - '../../base/base.gyp:base_i18n', - '../../base/base.gyp:test_support_base', - '../../skia/skia.gyp:skia', - '../../testing/gtest.gyp:gtest', - '../../third_party/icu/icu.gyp:icui18n', - '../../third_party/icu/icu.gyp:icuuc', - '../../url/url.gyp:url_lib', - '../accessibility/accessibility.gyp:accessibility', - '../base/ui_base.gyp:ui_base', - '../base/ui_base.gyp:ui_base_test_support', - '../compositor/compositor.gyp:compositor', - '../events/events.gyp:events', - '../events/events.gyp:events_base', - '../events/events.gyp:events_test_support', - '../gfx/gfx.gyp:gfx', - '../gfx/gfx.gyp:gfx_geometry', - '../resources/ui_resources.gyp:ui_resources', - '../resources/ui_resources.gyp:ui_test_pak', - '../strings/ui_strings.gyp:ui_strings', - 'views', - 'views_test_support', - ], - 'include_dirs': [ - '..', - ], - 'sources': [ - '<@(views_unittests_sources)', - ], - 'conditions': [ - ['chromeos==1', { - 'sources!': [ - 'ime/input_method_bridge_unittest.cc', - ], - }], - ['OS=="win"', { - 'dependencies': [ - '../../third_party/iaccessible2/iaccessible2.gyp:iaccessible2', - ], - 'link_settings': { - 'libraries': [ - '-limm32.lib', - '-loleacc.lib', - '-lcomctl32.lib', - ] - }, - 'include_dirs': [ - '../third_party/wtl/include', - ], - 'msvs_settings': { - 'VCManifestTool': { - 'AdditionalManifestFiles': [ - '$(ProjectDir)\\test\\views_unittest.manifest', - ], - }, - }, - }], - ['OS=="win" and win_use_allocator_shim==1', { - 'dependencies': [ - '../../base/allocator/allocator.gyp:allocator', - ], - }], - ['OS=="linux" and use_allocator!="none"', { - # See http://crbug.com/162998#c4 for why this is needed. - 'dependencies': [ - '../../base/allocator/allocator.gyp:allocator', - ], - }], - ['use_x11==1', { - 'dependencies': [ - '../../build/linux/system.gyp:x11', - '../../build/linux/system.gyp:xext', - '../events/platform/x11/x11_events_platform.gyp:x11_events_platform', - ], - }], - ['use_ozone==1', { - 'sources!': [ - 'corewm/capture_controller_unittest.cc', - ], - }], - ['use_aura==1', { - 'sources': [ '<@(views_unittests_aura_sources)' ], - 'dependencies': [ - '../aura/aura.gyp:aura', - '../aura/aura.gyp:aura_test_support', - '../wm/wm.gyp:wm', - ], - }], - ['use_x11==1', { - 'dependencies': [ - '../events/platform/x11/x11_events_platform.gyp:x11_events_platform', - ], - }], - ], - }, # target_name: views_unittests - ], # targets - 'conditions': [ - ['OS=="mac"', { - 'targets': [ - { - # GN version: //ui/views:macviews_interactive_ui_tests - 'target_name': 'macviews_interactive_ui_tests', - 'type': 'executable', - 'dependencies': [ - '../../base/base.gyp:base', - '../../base/base.gyp:test_support_base', - '../../skia/skia.gyp:skia', - '../../testing/gtest.gyp:gtest', - '../compositor/compositor.gyp:compositor_test_support', - '../resources/ui_resources.gyp:ui_resources', - '../resources/ui_resources.gyp:ui_test_pak', - '../strings/ui_strings.gyp:ui_strings', - 'views', - 'views_test_support', - ], - 'sources': [ - 'run_all_unittests.cc', - 'widget/native_widget_mac_interactive_uitest.mm', - ], - 'conditions': [ - ['use_aura == 1', { - 'dependencies': [ - '../aura/aura.gyp:aura', - '../wm/wm.gyp:wm', - ], - }], - ], - }, # target_name: macviews_interactive_ui_tests - ], # targets - }], - ], # conditions -}
diff --git a/ui/views/views_delegate.cc b/ui/views/views_delegate.cc deleted file mode 100644 index c1c7ca6..0000000 --- a/ui/views/views_delegate.cc +++ /dev/null
@@ -1,97 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/views_delegate.h" - -#include "ui/views/views_touch_selection_controller_factory.h" - -namespace views { - -ViewsDelegate::ViewsDelegate() - : views_tsc_factory_(new ViewsTouchSelectionControllerFactory) { - ui::TouchSelectionControllerFactory::SetInstance(views_tsc_factory_.get()); -} - -ViewsDelegate::~ViewsDelegate() { - ui::TouchSelectionControllerFactory::SetInstance(NULL); -} - -void ViewsDelegate::SaveWindowPlacement(const Widget* widget, - const std::string& window_name, - const gfx::Rect& bounds, - ui::WindowShowState show_state) { -} - -bool ViewsDelegate::GetSavedWindowPlacement( - const Widget* widget, - const std::string& window_name, - gfx::Rect* bounds, - ui::WindowShowState* show_state) const { - return false; -} - -void ViewsDelegate::NotifyAccessibilityEvent(View* view, - ui::AXEvent event_type) { -} - -void ViewsDelegate::NotifyMenuItemFocused(const base::string16& menu_name, - const base::string16& menu_item_name, - int item_index, - int item_count, - bool has_submenu) { -} - -#if defined(OS_WIN) -HICON ViewsDelegate::GetDefaultWindowIcon() const { - return NULL; -} - -bool ViewsDelegate::IsWindowInMetro(gfx::NativeWindow window) const { - return false; -} -#elif defined(OS_LINUX) && !defined(OS_CHROMEOS) -gfx::ImageSkia* ViewsDelegate::GetDefaultWindowIcon() const { - return NULL; -} -#endif - -NonClientFrameView* ViewsDelegate::CreateDefaultNonClientFrameView( - Widget* widget) { - return NULL; -} - -void ViewsDelegate::AddRef() { -} - -void ViewsDelegate::ReleaseRef() { -} - -content::WebContents* ViewsDelegate::CreateWebContents( - content::BrowserContext* browser_context, - content::SiteInstance* site_instance) { - return NULL; -} - -base::TimeDelta ViewsDelegate::GetDefaultTextfieldObscuredRevealDuration() { - return base::TimeDelta(); -} - -bool ViewsDelegate::WindowManagerProvidesTitleBar(bool maximized) { - return false; -} - -#if defined(USE_AURA) -ui::ContextFactory* ViewsDelegate::GetContextFactory() { - return NULL; -} -#endif - -#if defined(OS_WIN) -int ViewsDelegate::GetAppbarAutohideEdges(HMONITOR monitor, - const base::Closure& callback) { - return EDGE_BOTTOM; -} -#endif - -} // namespace views
diff --git a/ui/views/views_delegate.h b/ui/views/views_delegate.h deleted file mode 100644 index 0175c8b..0000000 --- a/ui/views/views_delegate.h +++ /dev/null
@@ -1,160 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_VIEWS_DELEGATE_H_ -#define UI_VIEWS_VIEWS_DELEGATE_H_ - -#include <string> - -#if defined(OS_WIN) -#include <windows.h> -#endif - -#include "base/strings/string16.h" -#include "ui/accessibility/ax_enums.h" -#include "ui/base/ui_base_types.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/views/views_export.h" -#include "ui/views/widget/widget.h" - -namespace base { -class TimeDelta; -} - -namespace content { -class WebContents; -class BrowserContext; -class SiteInstance; -} - -namespace gfx { -class ImageSkia; -class Rect; -} - -namespace ui { -class ContextFactory; -} - -namespace views { - -class NativeWidget; -class NonClientFrameView; -class ViewsTouchSelectionControllerFactory; -class View; -class Widget; -namespace internal { -class NativeWidgetDelegate; -} - -// ViewsDelegate is an interface implemented by an object using the views -// framework. It is used to obtain various high level application utilities -// and perform some actions such as window placement saving. -// -// The embedding app must set views_delegate to assign its ViewsDelegate -// implementation. -class VIEWS_EXPORT ViewsDelegate { - public: -#if defined(OS_WIN) - enum AppbarAutohideEdge { - EDGE_TOP = 1 << 0, - EDGE_LEFT = 1 << 1, - EDGE_BOTTOM = 1 << 2, - EDGE_RIGHT = 1 << 3, - }; -#endif - - ViewsDelegate(); - virtual ~ViewsDelegate(); - - // Saves the position, size and "show" state for the window with the - // specified name. - virtual void SaveWindowPlacement(const Widget* widget, - const std::string& window_name, - const gfx::Rect& bounds, - ui::WindowShowState show_state); - - // Retrieves the saved position and size and "show" state for the window with - // the specified name. - virtual bool GetSavedWindowPlacement(const Widget* widget, - const std::string& window_name, - gfx::Rect* bounds, - ui::WindowShowState* show_state) const; - - virtual void NotifyAccessibilityEvent(View* view, ui::AXEvent event_type); - - // For accessibility, notify the delegate that a menu item was focused - // so that alternate feedback (speech / magnified text) can be provided. - virtual void NotifyMenuItemFocused(const base::string16& menu_name, - const base::string16& menu_item_name, - int item_index, - int item_count, - bool has_submenu); - -#if defined(OS_WIN) - // Retrieves the default window icon to use for windows if none is specified. - virtual HICON GetDefaultWindowIcon() const; - // Returns true if the window passed in is in the Windows 8 metro - // environment. - virtual bool IsWindowInMetro(gfx::NativeWindow window) const; -#elif defined(OS_LINUX) && !defined(OS_CHROMEOS) - virtual gfx::ImageSkia* GetDefaultWindowIcon() const; -#endif - - // Creates a default NonClientFrameView to be used for windows that don't - // specify their own. If this function returns NULL, the - // views::CustomFrameView type will be used. - virtual NonClientFrameView* CreateDefaultNonClientFrameView(Widget* widget); - - // AddRef/ReleaseRef are invoked while a menu is visible. They are used to - // ensure we don't attempt to exit while a menu is showing. - virtual void AddRef(); - virtual void ReleaseRef(); - - // Creates a web contents. This will return NULL unless overriden. - virtual content::WebContents* CreateWebContents( - content::BrowserContext* browser_context, - content::SiteInstance* site_instance); - - // Gives the platform a chance to modify the properties of a Widget. - virtual void OnBeforeWidgetInit(Widget::InitParams* params, - internal::NativeWidgetDelegate* delegate) = 0; - - // Returns the default obscured text reveal duration. - virtual base::TimeDelta GetDefaultTextfieldObscuredRevealDuration(); - - // Returns true if the operating system's window manager will always provide a - // title bar with caption buttons (ignoring the setting to - // |remove_standard_frame| in InitParams). If |maximized|, this applies to - // maximized windows; otherwise to restored windows. - virtual bool WindowManagerProvidesTitleBar(bool maximized); - -#if defined(USE_AURA) - // Returns the context factory for new windows. - virtual ui::ContextFactory* GetContextFactory(); -#endif - -#if defined(OS_WIN) - // Starts a query for the appbar autohide edges of the specified monitor and - // returns the current value. If the query finds the edges have changed from - // the current value, |callback| is subsequently invoked. If the edges have - // not changed, |callback| is never run. - // - // The return value is a bitmask of AppbarAutohideEdge. - virtual int GetAppbarAutohideEdges(HMONITOR monitor, - const base::Closure& callback); -#endif - - // The active ViewsDelegate used by the views system. - static ViewsDelegate* views_delegate; - - private: - scoped_ptr<ViewsTouchSelectionControllerFactory> views_tsc_factory_; - - DISALLOW_COPY_AND_ASSIGN(ViewsDelegate); -}; - -} // namespace views - -#endif // UI_VIEWS_VIEWS_DELEGATE_H_
diff --git a/ui/views/views_export.h b/ui/views/views_export.h deleted file mode 100644 index 05a7ead..0000000 --- a/ui/views/views_export.h +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_VIEWS_EXPORT_H_ -#define UI_VIEWS_VIEWS_EXPORT_H_ - -// Defines VIEWS_EXPORT so that functionality implemented by the Views module -// can be exported to consumers. - -#if defined(COMPONENT_BUILD) -#if defined(WIN32) - -#if defined(VIEWS_IMPLEMENTATION) -#define VIEWS_EXPORT __declspec(dllexport) -#else -#define VIEWS_EXPORT __declspec(dllimport) -#endif // defined(VIEWS_IMPLEMENTATION) - -#else // defined(WIN32) -#if defined(VIEWS_IMPLEMENTATION) -#define VIEWS_EXPORT __attribute__((visibility("default"))) -#else -#define VIEWS_EXPORT -#endif -#endif - -#else // defined(COMPONENT_BUILD) -#define VIEWS_EXPORT -#endif - -#endif // UI_VIEWS_VIEWS_EXPORT_H_
diff --git a/ui/views/views_switches.cc b/ui/views/views_switches.cc deleted file mode 100644 index 344f594..0000000 --- a/ui/views/views_switches.cc +++ /dev/null
@@ -1,38 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/views_switches.h" - -#include "base/command_line.h" - -namespace views { -namespace switches { - -// Please keep alphabetized. - -// Specifies if a heuristic should be used to determine the most probable -// target of a gesture, where the touch region is represented by a rectangle. -const char kDisableViewsRectBasedTargeting[] = - "disable-views-rect-based-targeting"; - -#if defined(USE_X11) && !defined(OS_CHROMEOS) -// When enabled, tries to get a transparent X11 visual so that we can have -// per-pixel alpha in windows. -// -// TODO(erg): Remove this switch once we've stabilized the code -// path. http://crbug.com/369209 -const char kEnableTransparentVisuals[] = "enable-transparent-visuals"; -#endif - -bool IsRectBasedTargetingEnabled() { -#if defined(OS_CHROMEOS) || defined(OS_WIN) || defined(OS_LINUX) - return !base::CommandLine::ForCurrentProcess()-> - HasSwitch(kDisableViewsRectBasedTargeting); -#else - return false; -#endif -} - -} // namespace switches -} // namespace views
diff --git a/ui/views/views_switches.h b/ui/views/views_switches.h deleted file mode 100644 index 0fb09db..0000000 --- a/ui/views/views_switches.h +++ /dev/null
@@ -1,28 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_VIEWS_SWITCHES_H_ -#define UI_VIEWS_VIEWS_SWITCHES_H_ - -#include "ui/views/views_export.h" - -#include "build/build_config.h" - -namespace views { -namespace switches { - -// Please keep alphabetized. -VIEWS_EXPORT extern const char kDisableViewsRectBasedTargeting[]; - -#if defined(USE_X11) && !defined(OS_CHROMEOS) -VIEWS_EXPORT extern const char kEnableTransparentVisuals[]; -#endif - -// Returns true if rect-based targeting in views should be used. -VIEWS_EXPORT bool IsRectBasedTargetingEnabled(); - -} // namespace switches -} // namespace views - -#endif // UI_VIEWS_VIEWS_SWITCHES_H_
diff --git a/ui/views/views_touch_selection_controller_factory.h b/ui/views/views_touch_selection_controller_factory.h deleted file mode 100644 index 9ddaa8f..0000000 --- a/ui/views/views_touch_selection_controller_factory.h +++ /dev/null
@@ -1,25 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_UI_VIEWS_VIEWS_TOUCH_SELECTION_CONTROLLER_FACTORY_H_ -#define UI_UI_VIEWS_VIEWS_TOUCH_SELECTION_CONTROLLER_FACTORY_H_ - -#include "ui/base/touch/touch_editing_controller.h" -#include "ui/views/views_export.h" - -namespace views { - -class VIEWS_EXPORT ViewsTouchSelectionControllerFactory - : public ui::TouchSelectionControllerFactory { - public: - ViewsTouchSelectionControllerFactory(); - - // Overridden from ui::TouchSelectionControllerFactory. - virtual ui::TouchSelectionController* create( - ui::TouchEditable* client_view) override; -}; - -} // namespace views - -#endif // UI_UI_VIEWS_TOUCHUI_TOUCH_SELECTION_CONTROLLER_IMPL_H_
diff --git a/ui/views/views_touch_selection_controller_factory_aura.cc b/ui/views/views_touch_selection_controller_factory_aura.cc deleted file mode 100644 index a28da03..0000000 --- a/ui/views/views_touch_selection_controller_factory_aura.cc +++ /dev/null
@@ -1,22 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/views_touch_selection_controller_factory.h" - -#include "ui/base/ui_base_switches_util.h" -#include "ui/views/touchui/touch_selection_controller_impl.h" - -namespace views { - -ViewsTouchSelectionControllerFactory::ViewsTouchSelectionControllerFactory() { -} - -ui::TouchSelectionController* ViewsTouchSelectionControllerFactory::create( - ui::TouchEditable* client_view) { - if (switches::IsTouchEditingEnabled()) - return new views::TouchSelectionControllerImpl(client_view); - return NULL; -} - -} // namespace views
diff --git a/ui/views/widget/OWNERS b/ui/views/widget/OWNERS deleted file mode 100644 index c487030..0000000 --- a/ui/views/widget/OWNERS +++ /dev/null
@@ -1 +0,0 @@ -per-file native_widget_mac*=tapted@chromium.org
diff --git a/ui/views/widget/drop_helper.cc b/ui/views/widget/drop_helper.cc deleted file mode 100644 index ace1f90..0000000 --- a/ui/views/widget/drop_helper.cc +++ /dev/null
@@ -1,156 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/widget/drop_helper.h" - -#include "ui/base/dragdrop/drag_drop_types.h" -#include "ui/views/view.h" -#include "ui/views/widget/widget.h" - -namespace views { - -DropHelper::DropHelper(View* root_view) - : root_view_(root_view), - target_view_(NULL), - deepest_view_(NULL) { -} - -DropHelper::~DropHelper() { -} - -void DropHelper::ResetTargetViewIfEquals(View* view) { - if (target_view_ == view) - target_view_ = NULL; - if (deepest_view_ == view) - deepest_view_ = NULL; -} - -int DropHelper::OnDragOver(const OSExchangeData& data, - const gfx::Point& root_view_location, - int drag_operation) { - View* view = CalculateTargetViewImpl(root_view_location, data, true, - &deepest_view_); - - if (view != target_view_) { - // Target changed notify old drag exited, then new drag entered. - NotifyDragExit(); - target_view_ = view; - NotifyDragEntered(data, root_view_location, drag_operation); - } - - return NotifyDragOver(data, root_view_location, drag_operation); -} - -void DropHelper::OnDragExit() { - NotifyDragExit(); - deepest_view_ = target_view_ = NULL; -} - -int DropHelper::OnDrop(const OSExchangeData& data, - const gfx::Point& root_view_location, - int drag_operation) { - View* drop_view = target_view_; - deepest_view_ = target_view_ = NULL; - if (!drop_view) - return ui::DragDropTypes::DRAG_NONE; - - if (drag_operation == ui::DragDropTypes::DRAG_NONE) { - drop_view->OnDragExited(); - return ui::DragDropTypes::DRAG_NONE; - } - - gfx::Point view_location(root_view_location); - View* root_view = drop_view->GetWidget()->GetRootView(); - View::ConvertPointToTarget(root_view, drop_view, &view_location); - ui::DropTargetEvent drop_event(data, view_location, view_location, - drag_operation); - return drop_view->OnPerformDrop(drop_event); -} - -View* DropHelper::CalculateTargetView( - const gfx::Point& root_view_location, - const OSExchangeData& data, - bool check_can_drop) { - return CalculateTargetViewImpl(root_view_location, data, check_can_drop, - NULL); -} - -View* DropHelper::CalculateTargetViewImpl( - const gfx::Point& root_view_location, - const OSExchangeData& data, - bool check_can_drop, - View** deepest_view) { - View* view = root_view_->GetEventHandlerForPoint(root_view_location); - if (view == deepest_view_) { - // The view the mouse is over hasn't changed; reuse the target. - return target_view_; - } - if (deepest_view) - *deepest_view = view; - // TODO(sky): for the time being these are separate. Once I port chrome menu - // I can switch to the #else implementation and nuke the OS_WIN - // implementation. -#if defined(OS_WIN) - // View under mouse changed, which means a new view may want the drop. - // Walk the tree, stopping at target_view_ as we know it'll accept the - // drop. - while (view && view != target_view_ && - (!view->enabled() || !view->CanDrop(data))) { - view = view->parent(); - } -#else - int formats = 0; - std::set<OSExchangeData::CustomFormat> custom_formats; - while (view && view != target_view_) { - if (view->enabled() && - view->GetDropFormats(&formats, &custom_formats) && - data.HasAnyFormat(formats, custom_formats) && - (!check_can_drop || view->CanDrop(data))) { - // Found the view. - return view; - } - formats = 0; - custom_formats.clear(); - view = view->parent(); - } -#endif - return view; -} - -void DropHelper::NotifyDragEntered(const OSExchangeData& data, - const gfx::Point& root_view_location, - int drag_operation) { - if (!target_view_) - return; - - gfx::Point target_view_location(root_view_location); - View::ConvertPointToTarget(root_view_, target_view_, &target_view_location); - ui::DropTargetEvent enter_event(data, - target_view_location, - target_view_location, - drag_operation); - target_view_->OnDragEntered(enter_event); -} - -int DropHelper::NotifyDragOver(const OSExchangeData& data, - const gfx::Point& root_view_location, - int drag_operation) { - if (!target_view_) - return ui::DragDropTypes::DRAG_NONE; - - gfx::Point target_view_location(root_view_location); - View::ConvertPointToTarget(root_view_, target_view_, &target_view_location); - ui::DropTargetEvent enter_event(data, - target_view_location, - target_view_location, - drag_operation); - return target_view_->OnDragUpdated(enter_event); -} - -void DropHelper::NotifyDragExit() { - if (target_view_) - target_view_->OnDragExited(); -} - -} // namespace views
diff --git a/ui/views/widget/drop_helper.h b/ui/views/widget/drop_helper.h deleted file mode 100644 index 9247e1e..0000000 --- a/ui/views/widget/drop_helper.h +++ /dev/null
@@ -1,107 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_WIDGET_DROP_HELPER_H_ -#define UI_VIEWS_WIDGET_DROP_HELPER_H_ - -#include "base/basictypes.h" - -namespace gfx { -class Point; -} // namespace gfx - -namespace ui { -class OSExchangeData; -} // namespace ui -using ui::OSExchangeData; - -namespace views { - -class RootView; -class View; - -// DropHelper provides support for managing the view a drop is going to occur -// at during dnd as well as sending the view the appropriate dnd methods. -// DropHelper is intended to be used by a class that interacts with the system -// drag and drop. The system class invokes OnDragOver as the mouse moves, -// then either OnDragExit or OnDrop when the drop is done. -class DropHelper { - public: - explicit DropHelper(View* root_view); - ~DropHelper(); - - // Current view drop events are targeted at, may be NULL. - View* target_view() const { return target_view_; } - - // Returns the RootView the DropHelper was created with. - View* root_view() const { return root_view_; } - - // Resets the target_view_ to NULL if it equals view. - // - // This is invoked when a View is removed from the RootView to make sure - // we don't target a view that was removed during dnd. - void ResetTargetViewIfEquals(View* view); - - // Invoked when a the mouse is dragged over the root view during a drag and - // drop operation. This method returns a bitmask of the types in DragDropTypes - // for the target view. If no view wants the drop, DRAG_NONE is returned. - int OnDragOver(const OSExchangeData& data, - const gfx::Point& root_view_location, - int drag_operation); - - // Invoked when a the mouse is dragged out of the root view during a drag and - // drop operation. - void OnDragExit(); - - // Invoked when the user drops data on the root view during a drag and drop - // operation. See OnDragOver for details on return type. - // - // NOTE: implementations must invoke OnDragOver before invoking this, - // supplying the return value from OnDragOver as the drag_operation. - int OnDrop(const OSExchangeData& data, - const gfx::Point& root_view_location, - int drag_operation); - - // Calculates the target view for a drop given the specified location in - // the coordinate system of the rootview. This tries to avoid continually - // querying CanDrop by returning target_view_ if the mouse is still over - // target_view_. - View* CalculateTargetView(const gfx::Point& root_view_location, - const OSExchangeData& data, - bool check_can_drop); - - private: - // Implementation of CalculateTargetView. If |deepest_view| is non-NULL it is - // set to the deepest descendant of the RootView that contains the point - // |root_view_location| - View* CalculateTargetViewImpl(const gfx::Point& root_view_location, - const OSExchangeData& data, - bool check_can_drop, - View** deepest_view); - - // Methods to send the appropriate drop notification to the targeted view. - // These do nothing if the target view is NULL. - void NotifyDragEntered(const OSExchangeData& data, - const gfx::Point& root_view_location, - int drag_operation); - int NotifyDragOver(const OSExchangeData& data, - const gfx::Point& root_view_location, - int drag_operation); - void NotifyDragExit(); - - // RootView we were created for. - View* root_view_; - - // View we're targeting events at. - View* target_view_; - - // The deepest view under the current drop coordinate. - View* deepest_view_; - - DISALLOW_COPY_AND_ASSIGN(DropHelper); -}; - -} // namespace views - -#endif // UI_VIEWS_WIDGET_DROP_HELPER_H_
diff --git a/ui/views/widget/monitor_win.cc b/ui/views/widget/monitor_win.cc deleted file mode 100644 index 1220671..0000000 --- a/ui/views/widget/monitor_win.cc +++ /dev/null
@@ -1,26 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/widget/monitor_win.h" - -#include <windows.h> - -#include "base/logging.h" -#include "ui/gfx/rect.h" - -namespace views { - -gfx::Rect GetMonitorBoundsForRect(const gfx::Rect& rect) { - RECT p_rect = rect.ToRECT(); - HMONITOR monitor = MonitorFromRect(&p_rect, MONITOR_DEFAULTTONEAREST); - if (monitor) { - MONITORINFO mi = { sizeof(MONITORINFO) }; - GetMonitorInfo(monitor, &mi); - return gfx::Rect(mi.rcWork); - } - NOTREACHED(); - return gfx::Rect(); -} - -} // namespace views
diff --git a/ui/views/widget/monitor_win.h b/ui/views/widget/monitor_win.h deleted file mode 100644 index ef4d3dd..0000000 --- a/ui/views/widget/monitor_win.h +++ /dev/null
@@ -1,22 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_WIDGET_MONITOR_WIN_H_ -#define UI_VIEWS_WIDGET_MONITOR_WIN_H_ - -#include "ui/views/views_export.h" - -namespace gfx { -class Rect; -} - -namespace views { - -// Returns the bounds for the monitor that contains the largest area of -// intersection with the specified rectangle. -VIEWS_EXPORT gfx::Rect GetMonitorBoundsForRect(const gfx::Rect& rect); - -} // namespace views - -#endif // UI_VIEWS_WIDGET_MONITOR_WIN_H_
diff --git a/ui/views/widget/native_widget.h b/ui/views/widget/native_widget.h deleted file mode 100644 index d01265f..0000000 --- a/ui/views/widget/native_widget.h +++ /dev/null
@@ -1,37 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_WIDGET_NATIVE_WIDGET_H_ -#define UI_VIEWS_WIDGET_NATIVE_WIDGET_H_ - -#include "ui/views/widget/widget.h" - -namespace views { -namespace internal { -class NativeWidgetPrivate; -} - -//////////////////////////////////////////////////////////////////////////////// -// NativeWidget interface -// -// An interface that serves as the public API base for the -// internal::NativeWidget interface that Widget uses to communicate with a -// backend-specific native widget implementation. This is the only component of -// this interface that is publicly visible, and exists solely for exposure via -// Widget's native_widget() accessor, which code occasionally static_casts to -// a known implementation in platform-specific code. -// -class VIEWS_EXPORT NativeWidget { - public: - virtual ~NativeWidget() {} - - private: - friend class Widget; - - virtual internal::NativeWidgetPrivate* AsNativeWidgetPrivate() = 0; -}; - -} // namespace views - -#endif // UI_VIEWS_WIDGET_NATIVE_WIDGET_H_
diff --git a/ui/views/widget/native_widget_aura.cc b/ui/views/widget/native_widget_aura.cc deleted file mode 100644 index a4f2807..0000000 --- a/ui/views/widget/native_widget_aura.cc +++ /dev/null
@@ -1,1137 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/widget/native_widget_aura.h" - -#include "base/bind.h" -#include "base/strings/string_util.h" -#include "third_party/skia/include/core/SkRegion.h" -#include "ui/aura/client/aura_constants.h" -#include "ui/aura/client/cursor_client.h" -#include "ui/aura/client/focus_client.h" -#include "ui/aura/client/screen_position_client.h" -#include "ui/aura/client/window_tree_client.h" -#include "ui/aura/env.h" -#include "ui/aura/window.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/aura/window_observer.h" -#include "ui/base/dragdrop/os_exchange_data.h" -#include "ui/base/ui_base_switches_util.h" -#include "ui/base/ui_base_types.h" -#include "ui/compositor/layer.h" -#include "ui/events/event.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/font_list.h" -#include "ui/gfx/screen.h" -#include "ui/native_theme/native_theme_aura.h" -#include "ui/views/drag_utils.h" -#include "ui/views/ime/input_method_bridge.h" -#include "ui/views/ime/null_input_method.h" -#include "ui/views/views_delegate.h" -#include "ui/views/widget/drop_helper.h" -#include "ui/views/widget/native_widget_delegate.h" -#include "ui/views/widget/root_view.h" -#include "ui/views/widget/tooltip_manager_aura.h" -#include "ui/views/widget/widget_aura_utils.h" -#include "ui/views/widget/widget_delegate.h" -#include "ui/views/widget/window_reorderer.h" -#include "ui/wm/core/shadow_types.h" -#include "ui/wm/core/window_util.h" -#include "ui/wm/public/activation_client.h" -#include "ui/wm/public/drag_drop_client.h" -#include "ui/wm/public/window_move_client.h" -#include "ui/wm/public/window_types.h" - -#if defined(OS_WIN) -#include "base/win/scoped_gdi_object.h" -#include "base/win/win_util.h" -#include "ui/base/l10n/l10n_util_win.h" -#endif - -namespace views { - -namespace { - -void SetRestoreBounds(aura::Window* window, const gfx::Rect& bounds) { - window->SetProperty(aura::client::kRestoreBoundsKey, new gfx::Rect(bounds)); -} - -} // namespace - -//////////////////////////////////////////////////////////////////////////////// -// NativeWidgetAura, public: - -NativeWidgetAura::NativeWidgetAura(internal::NativeWidgetDelegate* delegate) - : delegate_(delegate), - window_(new aura::Window(this)), - ownership_(Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET), - destroying_(false), - cursor_(gfx::kNullCursor), - saved_window_state_(ui::SHOW_STATE_DEFAULT), - close_widget_factory_(this) { - aura::client::SetFocusChangeObserver(window_, this); - aura::client::SetActivationChangeObserver(window_, this); -} - -// static -void NativeWidgetAura::RegisterNativeWidgetForWindow( - internal::NativeWidgetPrivate* native_widget, - aura::Window* window) { - window->set_user_data(native_widget); -} - -//////////////////////////////////////////////////////////////////////////////// -// NativeWidgetAura, internal::NativeWidgetPrivate implementation: - -void NativeWidgetAura::InitNativeWidget(const Widget::InitParams& params) { - // Aura needs to know which desktop (Ash or regular) will manage this widget. - // See Widget::InitParams::context for details. - DCHECK(params.parent || params.context); - - ownership_ = params.ownership; - - RegisterNativeWidgetForWindow(this, window_); - window_->SetType(GetAuraWindowTypeForWidgetType(params.type)); - window_->SetProperty(aura::client::kShowStateKey, params.show_state); - if (params.type == Widget::InitParams::TYPE_BUBBLE) - aura::client::SetHideOnDeactivate(window_, true); - window_->SetTransparent( - params.opacity == Widget::InitParams::TRANSLUCENT_WINDOW); - window_->Init(params.layer_type); - if (params.shadow_type == Widget::InitParams::SHADOW_TYPE_NONE) - SetShadowType(window_, wm::SHADOW_TYPE_NONE); - else if (params.shadow_type == Widget::InitParams::SHADOW_TYPE_DROP) - SetShadowType(window_, wm::SHADOW_TYPE_RECTANGULAR); - if (params.type == Widget::InitParams::TYPE_CONTROL) - window_->Show(); - - delegate_->OnNativeWidgetCreated(false); - - gfx::Rect window_bounds = params.bounds; - gfx::NativeView parent = params.parent; - gfx::NativeView context = params.context; - if (!params.child) { - // Set up the transient child before the window is added. This way the - // LayoutManager knows the window has a transient parent. - if (parent && parent->type() != ui::wm::WINDOW_TYPE_UNKNOWN) { - wm::AddTransientChild(parent, window_); - if (!context) - context = parent; - parent = NULL; - } - // SetAlwaysOnTop before SetParent so that always-on-top container is used. - SetAlwaysOnTop(params.keep_on_top); - // Make sure we have a real |window_bounds|. - if (parent && window_bounds == gfx::Rect()) { - // If a parent is specified but no bounds are given, - // use the origin of the parent's display so that the widget - // will be added to the same display as the parent. - gfx::Rect bounds = gfx::Screen::GetScreenFor(parent)-> - GetDisplayNearestWindow(parent).bounds(); - window_bounds.set_origin(bounds.origin()); - } - } - - // Set properties before adding to the parent so that its layout manager sees - // the correct values. - OnSizeConstraintsChanged(); - - if (parent) { - parent->AddChild(window_); - } else { - aura::client::ParentWindowWithContext( - window_, context->GetRootWindow(), window_bounds); - } - - // Start observing property changes. - window_->AddObserver(this); - - // Wait to set the bounds until we have a parent. That way we can know our - // true state/bounds (the LayoutManager may enforce a particular - // state/bounds). - if (IsMaximized()) - SetRestoreBounds(window_, window_bounds); - else - SetBounds(window_bounds); - window_->set_ignore_events(!params.accept_events); - DCHECK(GetWidget()->GetRootView()); - if (params.type != Widget::InitParams::TYPE_TOOLTIP) - tooltip_manager_.reset(new views::TooltipManagerAura(GetWidget())); - - drop_helper_.reset(new DropHelper(GetWidget()->GetRootView())); - if (params.type != Widget::InitParams::TYPE_TOOLTIP && - params.type != Widget::InitParams::TYPE_POPUP) { - aura::client::SetDragDropDelegate(window_, this); - } - - aura::client::SetActivationDelegate(window_, this); - - window_reorderer_.reset(new WindowReorderer(window_, - GetWidget()->GetRootView())); -} - -NonClientFrameView* NativeWidgetAura::CreateNonClientFrameView() { - return NULL; -} - -bool NativeWidgetAura::ShouldUseNativeFrame() const { - // There is only one frame type for aura. - return false; -} - -bool NativeWidgetAura::ShouldWindowContentsBeTransparent() const { - return false; -} - -void NativeWidgetAura::FrameTypeChanged() { - // This is called when the Theme has changed; forward the event to the root - // widget. - GetWidget()->ThemeChanged(); - GetWidget()->GetRootView()->SchedulePaint(); -} - -Widget* NativeWidgetAura::GetWidget() { - return delegate_->AsWidget(); -} - -const Widget* NativeWidgetAura::GetWidget() const { - return delegate_->AsWidget(); -} - -gfx::NativeView NativeWidgetAura::GetNativeView() const { - return window_; -} - -gfx::NativeWindow NativeWidgetAura::GetNativeWindow() const { - return window_; -} - -Widget* NativeWidgetAura::GetTopLevelWidget() { - NativeWidgetPrivate* native_widget = GetTopLevelNativeWidget(GetNativeView()); - return native_widget ? native_widget->GetWidget() : NULL; -} - -const ui::Compositor* NativeWidgetAura::GetCompositor() const { - return window_ ? window_->layer()->GetCompositor() : NULL; -} - -ui::Compositor* NativeWidgetAura::GetCompositor() { - return window_ ? window_->layer()->GetCompositor() : NULL; -} - -ui::Layer* NativeWidgetAura::GetLayer() { - return window_ ? window_->layer() : NULL; -} - -void NativeWidgetAura::ReorderNativeViews() { - window_reorderer_->ReorderChildWindows(); -} - -void NativeWidgetAura::ViewRemoved(View* view) { - DCHECK(drop_helper_.get() != NULL); - drop_helper_->ResetTargetViewIfEquals(view); -} - -void NativeWidgetAura::SetNativeWindowProperty(const char* name, void* value) { - if (window_) - window_->SetNativeWindowProperty(name, value); -} - -void* NativeWidgetAura::GetNativeWindowProperty(const char* name) const { - return window_ ? window_->GetNativeWindowProperty(name) : NULL; -} - -TooltipManager* NativeWidgetAura::GetTooltipManager() const { - return tooltip_manager_.get(); -} - -void NativeWidgetAura::SetCapture() { - if (window_) - window_->SetCapture(); -} - -void NativeWidgetAura::ReleaseCapture() { - if (window_) - window_->ReleaseCapture(); -} - -bool NativeWidgetAura::HasCapture() const { - return window_ && window_->HasCapture(); -} - -InputMethod* NativeWidgetAura::CreateInputMethod() { - if (!window_) - return NULL; - - if (switches::IsTextInputFocusManagerEnabled()) - return new NullInputMethod(); - - aura::Window* root_window = window_->GetRootWindow(); - ui::InputMethod* host = - root_window->GetProperty(aura::client::kRootWindowInputMethodKey); - return new InputMethodBridge(this, host, true); -} - -internal::InputMethodDelegate* NativeWidgetAura::GetInputMethodDelegate() { - return this; -} - -ui::InputMethod* NativeWidgetAura::GetHostInputMethod() { - aura::Window* root_window = window_->GetRootWindow(); - return root_window->GetProperty(aura::client::kRootWindowInputMethodKey); -} - -void NativeWidgetAura::CenterWindow(const gfx::Size& size) { - if (!window_) - return; - - gfx::Rect parent_bounds(window_->parent()->GetBoundsInRootWindow()); - // When centering window, we take the intersection of the host and - // the parent. We assume the root window represents the visible - // rect of a single screen. - gfx::Rect work_area = gfx::Screen::GetScreenFor(window_)-> - GetDisplayNearestWindow(window_).work_area(); - - aura::client::ScreenPositionClient* screen_position_client = - aura::client::GetScreenPositionClient(window_->GetRootWindow()); - if (screen_position_client) { - gfx::Point origin = work_area.origin(); - screen_position_client->ConvertPointFromScreen(window_->GetRootWindow(), - &origin); - work_area.set_origin(origin); - } - - parent_bounds.Intersect(work_area); - - // If |window_|'s transient parent's bounds are big enough to fit it, then we - // center it with respect to the transient parent. - if (wm::GetTransientParent(window_)) { - gfx::Rect transient_parent_rect = - wm::GetTransientParent(window_)->GetBoundsInRootWindow(); - transient_parent_rect.Intersect(work_area); - if (transient_parent_rect.height() >= size.height() && - transient_parent_rect.width() >= size.width()) - parent_bounds = transient_parent_rect; - } - - gfx::Rect window_bounds( - parent_bounds.x() + (parent_bounds.width() - size.width()) / 2, - parent_bounds.y() + (parent_bounds.height() - size.height()) / 2, - size.width(), - size.height()); - // Don't size the window bigger than the parent, otherwise the user may not be - // able to close or move it. - window_bounds.AdjustToFit(parent_bounds); - - // Convert the bounds back relative to the parent. - gfx::Point origin = window_bounds.origin(); - aura::Window::ConvertPointToTarget(window_->GetRootWindow(), - window_->parent(), &origin); - window_bounds.set_origin(origin); - window_->SetBounds(window_bounds); -} - -void NativeWidgetAura::GetWindowPlacement( - gfx::Rect* bounds, - ui::WindowShowState* show_state) const { - // The interface specifies returning restored bounds, not current bounds. - *bounds = GetRestoredBounds(); - *show_state = window_ ? window_->GetProperty(aura::client::kShowStateKey) : - ui::SHOW_STATE_DEFAULT; -} - -bool NativeWidgetAura::SetWindowTitle(const base::string16& title) { - if (!window_) - return false; - if (window_->title() == title) - return false; - window_->SetTitle(title); - return true; -} - -void NativeWidgetAura::SetWindowIcons(const gfx::ImageSkia& window_icon, - const gfx::ImageSkia& app_icon) { - // Aura doesn't have window icons. -} - -void NativeWidgetAura::InitModalType(ui::ModalType modal_type) { - if (modal_type != ui::MODAL_TYPE_NONE) - window_->SetProperty(aura::client::kModalKey, modal_type); -} - -gfx::Rect NativeWidgetAura::GetWindowBoundsInScreen() const { - return window_ ? window_->GetBoundsInScreen() : gfx::Rect(); -} - -gfx::Rect NativeWidgetAura::GetClientAreaBoundsInScreen() const { - // View-to-screen coordinate system transformations depend on this returning - // the full window bounds, for example View::ConvertPointToScreen(). - return window_ ? window_->GetBoundsInScreen() : gfx::Rect(); -} - -gfx::Rect NativeWidgetAura::GetRestoredBounds() const { - if (!window_) - return gfx::Rect(); - - // Restored bounds should only be relevant if the window is minimized or - // maximized. However, in some places the code expects GetRestoredBounds() - // to return the current window bounds if the window is not in either state. - if (IsMinimized() || IsMaximized() || IsFullscreen()) { - // Restore bounds are in screen coordinates, no need to convert. - gfx::Rect* restore_bounds = - window_->GetProperty(aura::client::kRestoreBoundsKey); - if (restore_bounds) - return *restore_bounds; - } - return window_->GetBoundsInScreen(); -} - -void NativeWidgetAura::SetBounds(const gfx::Rect& bounds) { - if (!window_) - return; - - aura::Window* root = window_->GetRootWindow(); - if (root) { - aura::client::ScreenPositionClient* screen_position_client = - aura::client::GetScreenPositionClient(root); - if (screen_position_client) { - gfx::Display dst_display = - gfx::Screen::GetScreenFor(window_)->GetDisplayMatching(bounds); - screen_position_client->SetBounds(window_, bounds, dst_display); - return; - } - } - window_->SetBounds(bounds); -} - -void NativeWidgetAura::SetSize(const gfx::Size& size) { - if (window_) - window_->SetBounds(gfx::Rect(window_->bounds().origin(), size)); -} - -void NativeWidgetAura::StackAbove(gfx::NativeView native_view) { - if (window_ && window_->parent() && - window_->parent() == native_view->parent()) - window_->parent()->StackChildAbove(window_, native_view); -} - -void NativeWidgetAura::StackAtTop() { - if (window_) - window_->parent()->StackChildAtTop(window_); -} - -void NativeWidgetAura::StackBelow(gfx::NativeView native_view) { - if (window_ && window_->parent() && - window_->parent() == native_view->parent()) - window_->parent()->StackChildBelow(window_, native_view); -} - -void NativeWidgetAura::SetShape(gfx::NativeRegion region) { - if (window_) - window_->layer()->SetAlphaShape(make_scoped_ptr(region)); - else - delete region; -} - -void NativeWidgetAura::Close() { - // |window_| may already be deleted by parent window. This can happen - // when this widget is child widget or has transient parent - // and ownership is WIDGET_OWNS_NATIVE_WIDGET. - DCHECK(window_ || - ownership_ == Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET); - if (window_) { - window_->SuppressPaint(); - Hide(); - window_->SetProperty(aura::client::kModalKey, ui::MODAL_TYPE_NONE); - } - - if (!close_widget_factory_.HasWeakPtrs()) { - base::MessageLoop::current()->PostTask( - FROM_HERE, - base::Bind(&NativeWidgetAura::CloseNow, - close_widget_factory_.GetWeakPtr())); - } -} - -void NativeWidgetAura::CloseNow() { - delete window_; -} - -void NativeWidgetAura::Show() { - ShowWithWindowState(ui::SHOW_STATE_NORMAL); -} - -void NativeWidgetAura::Hide() { - if (window_) - window_->Hide(); -} - -void NativeWidgetAura::ShowMaximizedWithBounds( - const gfx::Rect& restored_bounds) { - SetRestoreBounds(window_, restored_bounds); - ShowWithWindowState(ui::SHOW_STATE_MAXIMIZED); -} - -void NativeWidgetAura::ShowWithWindowState(ui::WindowShowState state) { - if (!window_) - return; - - if (state == ui::SHOW_STATE_MAXIMIZED || state == ui::SHOW_STATE_FULLSCREEN) - window_->SetProperty(aura::client::kShowStateKey, state); - window_->Show(); - if (delegate_->CanActivate()) { - if (state != ui::SHOW_STATE_INACTIVE) - Activate(); - // SetInitialFocus() should be always be called, even for - // SHOW_STATE_INACTIVE. If the window has to stay inactive, the method will - // do the right thing. - SetInitialFocus(state); - } -} - -bool NativeWidgetAura::IsVisible() const { - return window_ && window_->IsVisible(); -} - -void NativeWidgetAura::Activate() { - if (!window_) - return; - - // We don't necessarily have a root window yet. This can happen with - // constrained windows. - if (window_->GetRootWindow()) { - aura::client::GetActivationClient(window_->GetRootWindow())->ActivateWindow( - window_); - } - if (window_->GetProperty(aura::client::kDrawAttentionKey)) - window_->SetProperty(aura::client::kDrawAttentionKey, false); -} - -void NativeWidgetAura::Deactivate() { - if (!window_) - return; - aura::client::GetActivationClient(window_->GetRootWindow())->DeactivateWindow( - window_); -} - -bool NativeWidgetAura::IsActive() const { - return window_ && wm::IsActiveWindow(window_); -} - -void NativeWidgetAura::SetAlwaysOnTop(bool on_top) { - if (window_) - window_->SetProperty(aura::client::kAlwaysOnTopKey, on_top); -} - -bool NativeWidgetAura::IsAlwaysOnTop() const { - return window_ && window_->GetProperty(aura::client::kAlwaysOnTopKey); -} - -void NativeWidgetAura::SetVisibleOnAllWorkspaces(bool always_visible) { - // Not implemented on chromeos or for child widgets. -} - -void NativeWidgetAura::Maximize() { - if (window_) - window_->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MAXIMIZED); -} - -void NativeWidgetAura::Minimize() { - if (window_) - window_->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MINIMIZED); -} - -bool NativeWidgetAura::IsMaximized() const { - return window_ && window_->GetProperty(aura::client::kShowStateKey) == - ui::SHOW_STATE_MAXIMIZED; -} - -bool NativeWidgetAura::IsMinimized() const { - return window_ && window_->GetProperty(aura::client::kShowStateKey) == - ui::SHOW_STATE_MINIMIZED; -} - -void NativeWidgetAura::Restore() { - if (window_) - window_->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_NORMAL); -} - -void NativeWidgetAura::SetFullscreen(bool fullscreen) { - if (!window_ || IsFullscreen() == fullscreen) - return; // Nothing to do. - - // Save window state before entering full screen so that it could restored - // when exiting full screen. - if (fullscreen) - saved_window_state_ = window_->GetProperty(aura::client::kShowStateKey); - - window_->SetProperty( - aura::client::kShowStateKey, - fullscreen ? ui::SHOW_STATE_FULLSCREEN : saved_window_state_); -} - -bool NativeWidgetAura::IsFullscreen() const { - return window_ && window_->GetProperty(aura::client::kShowStateKey) == - ui::SHOW_STATE_FULLSCREEN; -} - -void NativeWidgetAura::SetOpacity(unsigned char opacity) { - if (window_) - window_->layer()->SetOpacity(opacity / 255.0); -} - -void NativeWidgetAura::SetUseDragFrame(bool use_drag_frame) { - NOTIMPLEMENTED(); -} - -void NativeWidgetAura::FlashFrame(bool flash) { - if (window_) - window_->SetProperty(aura::client::kDrawAttentionKey, flash); -} - -void NativeWidgetAura::RunShellDrag(View* view, - const ui::OSExchangeData& data, - const gfx::Point& location, - int operation, - ui::DragDropTypes::DragEventSource source) { - if (window_) - views::RunShellDrag(window_, data, location, operation, source); -} - -void NativeWidgetAura::SchedulePaintInRect(const gfx::Rect& rect) { - if (window_) - window_->SchedulePaintInRect(rect); -} - -void NativeWidgetAura::SetCursor(gfx::NativeCursor cursor) { - cursor_ = cursor; - aura::client::CursorClient* cursor_client = - aura::client::GetCursorClient(window_->GetRootWindow()); - if (cursor_client) - cursor_client->SetCursor(cursor); -} - -bool NativeWidgetAura::IsMouseEventsEnabled() const { - if (!window_) - return false; - aura::client::CursorClient* cursor_client = - aura::client::GetCursorClient(window_->GetRootWindow()); - return cursor_client ? cursor_client->IsMouseEventsEnabled() : true; -} - -void NativeWidgetAura::ClearNativeFocus() { - aura::client::FocusClient* client = aura::client::GetFocusClient(window_); - if (window_ && client && window_->Contains(client->GetFocusedWindow())) - client->ResetFocusWithinActiveWindow(window_); -} - -gfx::Rect NativeWidgetAura::GetWorkAreaBoundsInScreen() const { - if (!window_) - return gfx::Rect(); - return gfx::Screen::GetScreenFor(window_)-> - GetDisplayNearestWindow(window_).work_area(); -} - -Widget::MoveLoopResult NativeWidgetAura::RunMoveLoop( - const gfx::Vector2d& drag_offset, - Widget::MoveLoopSource source, - Widget::MoveLoopEscapeBehavior escape_behavior) { - // |escape_behavior| is only needed on windows when running the native message - // loop. - if (!window_ || !window_->GetRootWindow()) - return Widget::MOVE_LOOP_CANCELED; - aura::client::WindowMoveClient* move_client = - aura::client::GetWindowMoveClient(window_->GetRootWindow()); - if (!move_client) - return Widget::MOVE_LOOP_CANCELED; - - SetCapture(); - aura::client::WindowMoveSource window_move_source = - source == Widget::MOVE_LOOP_SOURCE_MOUSE ? - aura::client::WINDOW_MOVE_SOURCE_MOUSE : - aura::client::WINDOW_MOVE_SOURCE_TOUCH; - if (move_client->RunMoveLoop(window_, drag_offset, window_move_source) == - aura::client::MOVE_SUCCESSFUL) { - return Widget::MOVE_LOOP_SUCCESSFUL; - } - return Widget::MOVE_LOOP_CANCELED; -} - -void NativeWidgetAura::EndMoveLoop() { - if (!window_ || !window_->GetRootWindow()) - return; - aura::client::WindowMoveClient* move_client = - aura::client::GetWindowMoveClient(window_->GetRootWindow()); - if (move_client) - move_client->EndMoveLoop(); -} - -void NativeWidgetAura::SetVisibilityChangedAnimationsEnabled(bool value) { - if (window_) - window_->SetProperty(aura::client::kAnimationsDisabledKey, !value); -} - -ui::NativeTheme* NativeWidgetAura::GetNativeTheme() const { - return ui::NativeThemeAura::instance(); -} - -void NativeWidgetAura::OnRootViewLayout() { -} - -bool NativeWidgetAura::IsTranslucentWindowOpacitySupported() const { - return true; -} - -void NativeWidgetAura::OnSizeConstraintsChanged() { - window_->SetProperty(aura::client::kCanMaximizeKey, - GetWidget()->widget_delegate()->CanMaximize()); - window_->SetProperty(aura::client::kCanMinimizeKey, - GetWidget()->widget_delegate()->CanMinimize()); - window_->SetProperty(aura::client::kCanResizeKey, - GetWidget()->widget_delegate()->CanResize()); -} - -void NativeWidgetAura::RepostNativeEvent(gfx::NativeEvent native_event) { - OnEvent(native_event); -} - -//////////////////////////////////////////////////////////////////////////////// -// NativeWidgetAura, views::InputMethodDelegate implementation: - -void NativeWidgetAura::DispatchKeyEventPostIME(const ui::KeyEvent& key) { - FocusManager* focus_manager = GetWidget()->GetFocusManager(); - delegate_->OnKeyEvent(const_cast<ui::KeyEvent*>(&key)); - if (key.handled() || !focus_manager) - return; - focus_manager->OnKeyEvent(key); -} - -//////////////////////////////////////////////////////////////////////////////// -// NativeWidgetAura, aura::WindowDelegate implementation: - -gfx::Size NativeWidgetAura::GetMinimumSize() const { - return delegate_->GetMinimumSize(); -} - -gfx::Size NativeWidgetAura::GetMaximumSize() const { - // If a window have a maximum size, the window should not be - // maximizable. - DCHECK(delegate_->GetMaximumSize().IsEmpty() || - !window_->GetProperty(aura::client::kCanMaximizeKey)); - return delegate_->GetMaximumSize(); -} - -void NativeWidgetAura::OnBoundsChanged(const gfx::Rect& old_bounds, - const gfx::Rect& new_bounds) { - // Assume that if the old bounds was completely empty a move happened. This - // handles the case of a maximize animation acquiring the layer (acquiring a - // layer results in clearing the bounds). - if (old_bounds.origin() != new_bounds.origin() || - (old_bounds == gfx::Rect(0, 0, 0, 0) && !new_bounds.IsEmpty())) { - delegate_->OnNativeWidgetMove(); - } - if (old_bounds.size() != new_bounds.size()) - delegate_->OnNativeWidgetSizeChanged(new_bounds.size()); -} - -gfx::NativeCursor NativeWidgetAura::GetCursor(const gfx::Point& point) { - return cursor_; -} - -int NativeWidgetAura::GetNonClientComponent(const gfx::Point& point) const { - return delegate_->GetNonClientComponent(point); -} - -bool NativeWidgetAura::ShouldDescendIntoChildForEventHandling( - aura::Window* child, - const gfx::Point& location) { - views::WidgetDelegate* widget_delegate = GetWidget()->widget_delegate(); - if (widget_delegate && - !widget_delegate->ShouldDescendIntoChildForEventHandling(child, location)) - return false; - - // Don't descend into |child| if there is a view with a Layer that contains - // the point and is stacked above |child|s layer. - typedef std::vector<ui::Layer*> Layers; - const Layers& root_layers(delegate_->GetRootLayers()); - if (root_layers.empty()) - return true; - - Layers::const_iterator child_layer_iter( - std::find(window_->layer()->children().begin(), - window_->layer()->children().end(), child->layer())); - if (child_layer_iter == window_->layer()->children().end()) - return true; - - for (std::vector<ui::Layer*>::const_reverse_iterator i = root_layers.rbegin(); - i != root_layers.rend(); ++i) { - ui::Layer* layer = *i; - if (layer->visible() && layer->bounds().Contains(location)) { - Layers::const_iterator root_layer_iter( - std::find(window_->layer()->children().begin(), - window_->layer()->children().end(), layer)); - if (root_layer_iter > child_layer_iter) - return false; - } - } - return true; -} - -bool NativeWidgetAura::CanFocus() { - return ShouldActivate(); -} - -void NativeWidgetAura::OnCaptureLost() { - delegate_->OnMouseCaptureLost(); -} - -void NativeWidgetAura::OnPaint(gfx::Canvas* canvas) { - delegate_->OnNativeWidgetPaint(canvas); -} - -void NativeWidgetAura::OnDeviceScaleFactorChanged(float device_scale_factor) { - // Repainting with new scale factor will paint the content at the right scale. -} - -void NativeWidgetAura::OnWindowDestroying(aura::Window* window) { - window_->RemoveObserver(this); - delegate_->OnNativeWidgetDestroying(); - - // If the aura::Window is destroyed, we can no longer show tooltips. - tooltip_manager_.reset(); -} - -void NativeWidgetAura::OnWindowDestroyed(aura::Window* window) { - window_ = NULL; - delegate_->OnNativeWidgetDestroyed(); - if (ownership_ == Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET) - delete this; -} - -void NativeWidgetAura::OnWindowTargetVisibilityChanged(bool visible) { - delegate_->OnNativeWidgetVisibilityChanged(visible); -} - -bool NativeWidgetAura::HasHitTestMask() const { - return delegate_->HasHitTestMask(); -} - -void NativeWidgetAura::GetHitTestMask(gfx::Path* mask) const { - DCHECK(mask); - delegate_->GetHitTestMask(mask); -} - -//////////////////////////////////////////////////////////////////////////////// -// NativeWidgetAura, aura::WindowObserver implementation: - -void NativeWidgetAura::OnWindowPropertyChanged(aura::Window* window, - const void* key, - intptr_t old) { - if (key == aura::client::kShowStateKey) - delegate_->OnNativeWidgetWindowShowStateChanged(); -} - -//////////////////////////////////////////////////////////////////////////////// -// NativeWidgetAura, ui::EventHandler implementation: - -void NativeWidgetAura::OnKeyEvent(ui::KeyEvent* event) { - DCHECK(window_); - if (event->is_char()) { - // If a ui::InputMethod object is attached to the root window, character - // events are handled inside the object and are not passed to this function. - // If such object is not attached, character events might be sent (e.g. on - // Windows). In this case, we just skip these. - return; - } - // Renderer may send a key event back to us if the key event wasn't handled, - // and the window may be invisible by that time. - if (!window_->IsVisible()) - return; - InputMethod* input_method = GetWidget()->GetInputMethod(); - if (!input_method) - return; - input_method->DispatchKeyEvent(*event); - if (switches::IsTextInputFocusManagerEnabled()) { - FocusManager* focus_manager = GetWidget()->GetFocusManager(); - delegate_->OnKeyEvent(event); - if (!event->handled() && focus_manager) - focus_manager->OnKeyEvent(*event); - } - event->SetHandled(); -} - -void NativeWidgetAura::OnMouseEvent(ui::MouseEvent* event) { - DCHECK(window_); - DCHECK(window_->IsVisible()); - if (event->type() == ui::ET_MOUSEWHEEL) { - delegate_->OnMouseEvent(event); - if (event->handled()) - return; - } - - if (tooltip_manager_.get()) - tooltip_manager_->UpdateTooltip(); - TooltipManagerAura::UpdateTooltipManagerForCapture(GetWidget()); - delegate_->OnMouseEvent(event); -} - -void NativeWidgetAura::OnScrollEvent(ui::ScrollEvent* event) { - delegate_->OnScrollEvent(event); -} - -void NativeWidgetAura::OnGestureEvent(ui::GestureEvent* event) { - DCHECK(window_); - DCHECK(window_->IsVisible() || event->IsEndingEvent()); - delegate_->OnGestureEvent(event); -} - -//////////////////////////////////////////////////////////////////////////////// -// NativeWidgetAura, aura::client::ActivationDelegate implementation: - -bool NativeWidgetAura::ShouldActivate() const { - return delegate_->CanActivate(); -} - -//////////////////////////////////////////////////////////////////////////////// -// NativeWidgetAura, aura::client::ActivationChangeObserver implementation: - -void NativeWidgetAura::OnWindowActivated(aura::Window* gained_active, - aura::Window* lost_active) { - DCHECK(window_ == gained_active || window_ == lost_active); - if (GetWidget()->GetFocusManager()) { - if (window_ == gained_active) - GetWidget()->GetFocusManager()->RestoreFocusedView(); - else if (window_ == lost_active) - GetWidget()->GetFocusManager()->StoreFocusedView(true); - } - delegate_->OnNativeWidgetActivationChanged(window_ == gained_active); -} - -//////////////////////////////////////////////////////////////////////////////// -// NativeWidgetAura, aura::client::FocusChangeObserver: - -void NativeWidgetAura::OnWindowFocused(aura::Window* gained_focus, - aura::Window* lost_focus) { - if (window_ == gained_focus) { - // In aura, it is possible for child native widgets to take input and focus, - // this differs from the behavior on windows. - if (GetWidget()->GetInputMethod()) // Null in tests. - GetWidget()->GetInputMethod()->OnFocus(); - delegate_->OnNativeFocus(lost_focus); - } else if (window_ == lost_focus) { - // GetInputMethod() recreates the input method if it's previously been - // destroyed. If we get called during destruction, the input method will be - // gone, and creating a new one and telling it that we lost the focus will - // trigger a DCHECK (the new input method doesn't think that we have the - // focus and doesn't expect a blur). OnBlur() shouldn't be called during - // destruction unless WIDGET_OWNS_NATIVE_WIDGET is set (which is just the - // case in tests). - if (!destroying_) { - if (GetWidget()->GetInputMethod()) - GetWidget()->GetInputMethod()->OnBlur(); - } else { - DCHECK_EQ(ownership_, Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET); - } - - delegate_->OnNativeBlur(gained_focus); - } -} - -//////////////////////////////////////////////////////////////////////////////// -// NativeWidgetAura, aura::WindowDragDropDelegate implementation: - -void NativeWidgetAura::OnDragEntered(const ui::DropTargetEvent& event) { - DCHECK(drop_helper_.get() != NULL); - last_drop_operation_ = drop_helper_->OnDragOver(event.data(), - event.location(), event.source_operations()); -} - -int NativeWidgetAura::OnDragUpdated(const ui::DropTargetEvent& event) { - DCHECK(drop_helper_.get() != NULL); - last_drop_operation_ = drop_helper_->OnDragOver(event.data(), - event.location(), event.source_operations()); - return last_drop_operation_; -} - -void NativeWidgetAura::OnDragExited() { - DCHECK(drop_helper_.get() != NULL); - drop_helper_->OnDragExit(); -} - -int NativeWidgetAura::OnPerformDrop(const ui::DropTargetEvent& event) { - DCHECK(drop_helper_.get() != NULL); - return drop_helper_->OnDrop(event.data(), event.location(), - last_drop_operation_); -} - -//////////////////////////////////////////////////////////////////////////////// -// NativeWidgetAura, protected: - -NativeWidgetAura::~NativeWidgetAura() { - destroying_ = true; - if (ownership_ == Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET) - delete delegate_; - else - CloseNow(); -} - -//////////////////////////////////////////////////////////////////////////////// -// NativeWidgetAura, private: - -void NativeWidgetAura::SetInitialFocus(ui::WindowShowState show_state) { - // The window does not get keyboard messages unless we focus it. - if (!GetWidget()->SetInitialFocus(show_state)) - window_->Focus(); -} - -//////////////////////////////////////////////////////////////////////////////// -// Widget, public: - -// static -void Widget::CloseAllSecondaryWidgets() { -} - -bool Widget::ConvertRect(const Widget* source, - const Widget* target, - gfx::Rect* rect) { - return false; -} - -namespace internal { - -//////////////////////////////////////////////////////////////////////////////// -// internal::NativeWidgetPrivate, public: - -// static -NativeWidgetPrivate* NativeWidgetPrivate::CreateNativeWidget( - internal::NativeWidgetDelegate* delegate) { - return new NativeWidgetAura(delegate); -} - -// static -NativeWidgetPrivate* NativeWidgetPrivate::GetNativeWidgetForNativeView( - gfx::NativeView native_view) { - // Cast must match type supplied to RegisterNativeWidgetForWindow(). - return reinterpret_cast<NativeWidgetPrivate*>(native_view->user_data()); -} - -// static -NativeWidgetPrivate* NativeWidgetPrivate::GetNativeWidgetForNativeWindow( - gfx::NativeWindow native_window) { - // Cast must match type supplied to RegisterNativeWidgetForWindow(). - return reinterpret_cast<NativeWidgetPrivate*>(native_window->user_data()); -} - -// static -NativeWidgetPrivate* NativeWidgetPrivate::GetTopLevelNativeWidget( - gfx::NativeView native_view) { - aura::Window* window = native_view; - NativeWidgetPrivate* top_level_native_widget = NULL; - while (window) { - NativeWidgetPrivate* native_widget = GetNativeWidgetForNativeView(window); - if (native_widget) - top_level_native_widget = native_widget; - window = window->parent(); - } - return top_level_native_widget; -} - -// static -void NativeWidgetPrivate::GetAllChildWidgets(gfx::NativeView native_view, - Widget::Widgets* children) { - { - // Code expects widget for |native_view| to be added to |children|. - NativeWidgetPrivate* native_widget = static_cast<NativeWidgetPrivate*>( - GetNativeWidgetForNativeView(native_view)); - if (native_widget && native_widget->GetWidget()) - children->insert(native_widget->GetWidget()); - } - - const aura::Window::Windows& child_windows = native_view->children(); - for (aura::Window::Windows::const_iterator i = child_windows.begin(); - i != child_windows.end(); ++i) { - GetAllChildWidgets((*i), children); - } -} - -// static -void NativeWidgetPrivate::GetAllOwnedWidgets(gfx::NativeView native_view, - Widget::Widgets* owned) { - const aura::Window::Windows& transient_children = - wm::GetTransientChildren(native_view); - for (aura::Window::Windows::const_iterator i = transient_children.begin(); - i != transient_children.end(); ++i) { - NativeWidgetPrivate* native_widget = static_cast<NativeWidgetPrivate*>( - GetNativeWidgetForNativeView(*i)); - if (native_widget && native_widget->GetWidget()) - owned->insert(native_widget->GetWidget()); - GetAllOwnedWidgets((*i), owned); - } -} - -// static -void NativeWidgetPrivate::ReparentNativeView(gfx::NativeView native_view, - gfx::NativeView new_parent) { - DCHECK(native_view != new_parent); - - gfx::NativeView previous_parent = native_view->parent(); - if (previous_parent == new_parent) - return; - - Widget::Widgets widgets; - GetAllChildWidgets(native_view, &widgets); - - // First notify all the widgets that they are being disassociated - // from their previous parent. - for (Widget::Widgets::iterator it = widgets.begin(); - it != widgets.end(); ++it) { - (*it)->NotifyNativeViewHierarchyWillChange(); - } - - if (new_parent) { - new_parent->AddChild(native_view); - } else { - // The following looks weird, but it's the equivalent of what aura has - // always done. (The previous behaviour of aura::Window::SetParent() used - // NULL as a special value that meant ask the WindowTreeClient where things - // should go.) - // - // This probably isn't strictly correct, but its an invariant that a Window - // in use will be attached to a RootWindow, so we can't just call - // RemoveChild here. The only possible thing that could assign a RootWindow - // in this case is the stacking client of the current RootWindow. This - // matches our previous behaviour; the global stacking client would almost - // always reattach the window to the same RootWindow. - aura::Window* root_window = native_view->GetRootWindow(); - aura::client::ParentWindowWithContext( - native_view, root_window, root_window->GetBoundsInScreen()); - } - - // And now, notify them that they have a brand new parent. - for (Widget::Widgets::iterator it = widgets.begin(); - it != widgets.end(); ++it) { - (*it)->NotifyNativeViewHierarchyChanged(); - } -} - -// static -bool NativeWidgetPrivate::IsMouseButtonDown() { - return aura::Env::GetInstance()->IsMouseButtonDown(); -} - -// static -gfx::FontList NativeWidgetPrivate::GetWindowTitleFontList() { -#if defined(OS_WIN) - NONCLIENTMETRICS_XP ncm; - base::win::GetNonClientMetrics(&ncm); - l10n_util::AdjustUIFont(&(ncm.lfCaptionFont)); - base::win::ScopedHFONT caption_font(CreateFontIndirect(&(ncm.lfCaptionFont))); - return gfx::FontList(gfx::Font(caption_font)); -#else - return gfx::FontList(); -#endif -} - -} // namespace internal -} // namespace views
diff --git a/ui/views/widget/native_widget_aura.h b/ui/views/widget/native_widget_aura.h deleted file mode 100644 index 969f478..0000000 --- a/ui/views/widget/native_widget_aura.h +++ /dev/null
@@ -1,238 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_WIDGET_NATIVE_WIDGET_AURA_H_ -#define UI_VIEWS_WIDGET_NATIVE_WIDGET_AURA_H_ - -#include "base/memory/scoped_vector.h" -#include "base/memory/weak_ptr.h" -#include "ui/aura/client/focus_change_observer.h" -#include "ui/aura/window_delegate.h" -#include "ui/aura/window_observer.h" -#include "ui/base/cursor/cursor.h" -#include "ui/events/event_constants.h" -#include "ui/views/ime/input_method_delegate.h" -#include "ui/views/views_export.h" -#include "ui/views/widget/native_widget_private.h" -#include "ui/wm/public/activation_change_observer.h" -#include "ui/wm/public/activation_delegate.h" -#include "ui/wm/public/drag_drop_delegate.h" - -namespace aura { -class Window; -} -namespace gfx { -class FontList; -} - -namespace views { - -class DropHelper; -class TooltipManagerAura; -class WindowReorderer; - -class VIEWS_EXPORT NativeWidgetAura - : public internal::NativeWidgetPrivate, - public internal::InputMethodDelegate, - public aura::WindowDelegate, - public aura::WindowObserver, - public aura::client::ActivationDelegate, - public aura::client::ActivationChangeObserver, - public aura::client::FocusChangeObserver, - public aura::client::DragDropDelegate { - public: - explicit NativeWidgetAura(internal::NativeWidgetDelegate* delegate); - - // Called internally by NativeWidgetAura and DesktopNativeWidgetAura to - // associate |native_widget| with |window|. - static void RegisterNativeWidgetForWindow( - internal::NativeWidgetPrivate* native_widget, - aura::Window* window); - - // Overridden from internal::NativeWidgetPrivate: - virtual void InitNativeWidget(const Widget::InitParams& params) override; - virtual NonClientFrameView* CreateNonClientFrameView() override; - virtual bool ShouldUseNativeFrame() const override; - virtual bool ShouldWindowContentsBeTransparent() const override; - virtual void FrameTypeChanged() override; - virtual Widget* GetWidget() override; - virtual const Widget* GetWidget() const override; - virtual gfx::NativeView GetNativeView() const override; - virtual gfx::NativeWindow GetNativeWindow() const override; - virtual Widget* GetTopLevelWidget() override; - virtual const ui::Compositor* GetCompositor() const override; - virtual ui::Compositor* GetCompositor() override; - virtual ui::Layer* GetLayer() override; - virtual void ReorderNativeViews() override; - virtual void ViewRemoved(View* view) override; - virtual void SetNativeWindowProperty(const char* name, void* value) override; - virtual void* GetNativeWindowProperty(const char* name) const override; - virtual TooltipManager* GetTooltipManager() const override; - virtual void SetCapture() override; - virtual void ReleaseCapture() override; - virtual bool HasCapture() const override; - virtual InputMethod* CreateInputMethod() override; - virtual internal::InputMethodDelegate* GetInputMethodDelegate() override; - virtual ui::InputMethod* GetHostInputMethod() override; - virtual void CenterWindow(const gfx::Size& size) override; - virtual void GetWindowPlacement( - gfx::Rect* bounds, - ui::WindowShowState* maximized) const override; - virtual bool SetWindowTitle(const base::string16& title) override; - virtual void SetWindowIcons(const gfx::ImageSkia& window_icon, - const gfx::ImageSkia& app_icon) override; - virtual void InitModalType(ui::ModalType modal_type) override; - virtual gfx::Rect GetWindowBoundsInScreen() const override; - virtual gfx::Rect GetClientAreaBoundsInScreen() const override; - virtual gfx::Rect GetRestoredBounds() const override; - virtual void SetBounds(const gfx::Rect& bounds) override; - virtual void SetSize(const gfx::Size& size) override; - virtual void StackAbove(gfx::NativeView native_view) override; - virtual void StackAtTop() override; - virtual void StackBelow(gfx::NativeView native_view) override; - virtual void SetShape(gfx::NativeRegion shape) override; - virtual void Close() override; - virtual void CloseNow() override; - virtual void Show() override; - virtual void Hide() override; - virtual void ShowMaximizedWithBounds( - const gfx::Rect& restored_bounds) override; - virtual void ShowWithWindowState(ui::WindowShowState state) override; - virtual bool IsVisible() const override; - virtual void Activate() override; - virtual void Deactivate() override; - virtual bool IsActive() const override; - virtual void SetAlwaysOnTop(bool always_on_top) override; - virtual bool IsAlwaysOnTop() const override; - virtual void SetVisibleOnAllWorkspaces(bool always_visible) override; - virtual void Maximize() override; - virtual void Minimize() override; - virtual bool IsMaximized() const override; - virtual bool IsMinimized() const override; - virtual void Restore() override; - virtual void SetFullscreen(bool fullscreen) override; - virtual bool IsFullscreen() const override; - virtual void SetOpacity(unsigned char opacity) override; - virtual void SetUseDragFrame(bool use_drag_frame) override; - virtual void FlashFrame(bool flash_frame) override; - virtual void RunShellDrag(View* view, - const ui::OSExchangeData& data, - const gfx::Point& location, - int operation, - ui::DragDropTypes::DragEventSource source) override; - virtual void SchedulePaintInRect(const gfx::Rect& rect) override; - virtual void SetCursor(gfx::NativeCursor cursor) override; - virtual bool IsMouseEventsEnabled() const override; - virtual void ClearNativeFocus() override; - virtual gfx::Rect GetWorkAreaBoundsInScreen() const override; - virtual Widget::MoveLoopResult RunMoveLoop( - const gfx::Vector2d& drag_offset, - Widget::MoveLoopSource source, - Widget::MoveLoopEscapeBehavior escape_behavior) override; - virtual void EndMoveLoop() override; - virtual void SetVisibilityChangedAnimationsEnabled(bool value) override; - virtual ui::NativeTheme* GetNativeTheme() const override; - virtual void OnRootViewLayout() override; - virtual bool IsTranslucentWindowOpacitySupported() const override; - virtual void OnSizeConstraintsChanged() override; - virtual void RepostNativeEvent(gfx::NativeEvent native_event) override; - - // Overridden from views::InputMethodDelegate: - virtual void DispatchKeyEventPostIME(const ui::KeyEvent& key) override; - - // Overridden from aura::WindowDelegate: - virtual gfx::Size GetMinimumSize() const override; - virtual gfx::Size GetMaximumSize() const override; - virtual void OnBoundsChanged(const gfx::Rect& old_bounds, - const gfx::Rect& new_bounds) override; - virtual gfx::NativeCursor GetCursor(const gfx::Point& point) override; - virtual int GetNonClientComponent(const gfx::Point& point) const override; - virtual bool ShouldDescendIntoChildForEventHandling( - aura::Window* child, - const gfx::Point& location) override; - virtual bool CanFocus() override; - virtual void OnCaptureLost() override; - virtual void OnPaint(gfx::Canvas* canvas) override; - virtual void OnDeviceScaleFactorChanged(float device_scale_factor) override; - virtual void OnWindowDestroying(aura::Window* window) override; - virtual void OnWindowDestroyed(aura::Window* window) override; - virtual void OnWindowTargetVisibilityChanged(bool visible) override; - virtual bool HasHitTestMask() const override; - virtual void GetHitTestMask(gfx::Path* mask) const override; - - // Overridden from aura::WindowObserver: - virtual void OnWindowPropertyChanged(aura::Window* window, - const void* key, - intptr_t old) override; - - // Overridden from ui::EventHandler: - virtual void OnKeyEvent(ui::KeyEvent* event) override; - virtual void OnMouseEvent(ui::MouseEvent* event) override; - virtual void OnScrollEvent(ui::ScrollEvent* event) override; - virtual void OnGestureEvent(ui::GestureEvent* event) override; - - // Overridden from aura::client::ActivationDelegate: - virtual bool ShouldActivate() const override; - - // Overridden from aura::client::ActivationChangeObserver: - virtual void OnWindowActivated(aura::Window* gained_active, - aura::Window* lost_active) override; - - // Overridden from aura::client::FocusChangeObserver: - virtual void OnWindowFocused(aura::Window* gained_focus, - aura::Window* lost_focus) override; - - // Overridden from aura::client::DragDropDelegate: - virtual void OnDragEntered(const ui::DropTargetEvent& event) override; - virtual int OnDragUpdated(const ui::DropTargetEvent& event) override; - virtual void OnDragExited() override; - virtual int OnPerformDrop(const ui::DropTargetEvent& event) override; - - protected: - virtual ~NativeWidgetAura(); - - internal::NativeWidgetDelegate* delegate() { return delegate_; } - - private: - class ActiveWindowObserver; - - void SetInitialFocus(ui::WindowShowState show_state); - - internal::NativeWidgetDelegate* delegate_; - - // WARNING: set to NULL when destroyed. As the Widget is not necessarily - // destroyed along with |window_| all usage of |window_| should first verify - // non-NULL. - aura::Window* window_; - - // See class documentation for Widget in widget.h for a note about ownership. - Widget::InitParams::Ownership ownership_; - - // Are we in the destructor? - bool destroying_; - - gfx::NativeCursor cursor_; - - // The saved window state for exiting full screen state. - ui::WindowShowState saved_window_state_; - - scoped_ptr<TooltipManagerAura> tooltip_manager_; - - // Reorders child windows of |window_| associated with a view based on the - // order of the associated views in the widget's view hierarchy. - scoped_ptr<WindowReorderer> window_reorderer_; - - scoped_ptr<DropHelper> drop_helper_; - int last_drop_operation_; - - // The following factory is used for calls to close the NativeWidgetAura - // instance. - base::WeakPtrFactory<NativeWidgetAura> close_widget_factory_; - - DISALLOW_COPY_AND_ASSIGN(NativeWidgetAura); -}; - -} // namespace views - -#endif // UI_VIEWS_WIDGET_NATIVE_WIDGET_AURA_H_
diff --git a/ui/views/widget/native_widget_aura_unittest.cc b/ui/views/widget/native_widget_aura_unittest.cc deleted file mode 100644 index 6ca6f34..0000000 --- a/ui/views/widget/native_widget_aura_unittest.cc +++ /dev/null
@@ -1,486 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/widget/native_widget_aura.h" - -#include "base/basictypes.h" -#include "base/command_line.h" -#include "base/memory/scoped_ptr.h" -#include "base/message_loop/message_loop.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/aura/client/aura_constants.h" -#include "ui/aura/env.h" -#include "ui/aura/layout_manager.h" -#include "ui/aura/test/aura_test_base.h" -#include "ui/aura/window.h" -#include "ui/aura/window_tree_host.h" -#include "ui/events/event.h" -#include "ui/events/event_utils.h" -#include "ui/gfx/screen.h" -#include "ui/views/layout/fill_layout.h" -#include "ui/views/widget/root_view.h" -#include "ui/views/widget/widget_delegate.h" -#include "ui/wm/core/default_activation_client.h" - -namespace views { -namespace { - -NativeWidgetAura* Init(aura::Window* parent, Widget* widget) { - Widget::InitParams params(Widget::InitParams::TYPE_POPUP); - params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.parent = parent; - widget->Init(params); - return static_cast<NativeWidgetAura*>(widget->native_widget()); -} - -class NativeWidgetAuraTest : public aura::test::AuraTestBase { - public: - NativeWidgetAuraTest() {} - virtual ~NativeWidgetAuraTest() {} - - // testing::Test overrides: - virtual void SetUp() override { - AuraTestBase::SetUp(); - new wm::DefaultActivationClient(root_window()); - host()->SetBounds(gfx::Rect(640, 480)); - } - - private: - DISALLOW_COPY_AND_ASSIGN(NativeWidgetAuraTest); -}; - -TEST_F(NativeWidgetAuraTest, CenterWindowLargeParent) { - // Make a parent window larger than the host represented by - // WindowEventDispatcher. - scoped_ptr<aura::Window> parent(new aura::Window(NULL)); - parent->Init(aura::WINDOW_LAYER_NOT_DRAWN); - parent->SetBounds(gfx::Rect(0, 0, 1024, 800)); - scoped_ptr<Widget> widget(new Widget()); - NativeWidgetAura* window = Init(parent.get(), widget.get()); - - window->CenterWindow(gfx::Size(100, 100)); - EXPECT_EQ(gfx::Rect( (640 - 100) / 2, - (480 - 100) / 2, - 100, 100), - window->GetNativeWindow()->bounds()); - widget->CloseNow(); -} - -TEST_F(NativeWidgetAuraTest, CenterWindowSmallParent) { - // Make a parent window smaller than the host represented by - // WindowEventDispatcher. - scoped_ptr<aura::Window> parent(new aura::Window(NULL)); - parent->Init(aura::WINDOW_LAYER_NOT_DRAWN); - parent->SetBounds(gfx::Rect(0, 0, 480, 320)); - scoped_ptr<Widget> widget(new Widget()); - NativeWidgetAura* window = Init(parent.get(), widget.get()); - - window->CenterWindow(gfx::Size(100, 100)); - EXPECT_EQ(gfx::Rect( (480 - 100) / 2, - (320 - 100) / 2, - 100, 100), - window->GetNativeWindow()->bounds()); - widget->CloseNow(); -} - -// Verifies CenterWindow() constrains to parent size. -TEST_F(NativeWidgetAuraTest, CenterWindowSmallParentNotAtOrigin) { - // Make a parent window smaller than the host represented by - // WindowEventDispatcher and offset it slightly from the origin. - scoped_ptr<aura::Window> parent(new aura::Window(NULL)); - parent->Init(aura::WINDOW_LAYER_NOT_DRAWN); - parent->SetBounds(gfx::Rect(20, 40, 480, 320)); - scoped_ptr<Widget> widget(new Widget()); - NativeWidgetAura* window = Init(parent.get(), widget.get()); - window->CenterWindow(gfx::Size(500, 600)); - - // |window| should be no bigger than |parent|. - EXPECT_EQ("20,40 480x320", window->GetNativeWindow()->bounds().ToString()); - widget->CloseNow(); -} - -class TestLayoutManagerBase : public aura::LayoutManager { - public: - TestLayoutManagerBase() {} - virtual ~TestLayoutManagerBase() {} - - // aura::LayoutManager: - virtual void OnWindowResized() override {} - virtual void OnWindowAddedToLayout(aura::Window* child) override {} - virtual void OnWillRemoveWindowFromLayout(aura::Window* child) override {} - virtual void OnWindowRemovedFromLayout(aura::Window* child) override {} - virtual void OnChildWindowVisibilityChanged(aura::Window* child, - bool visible) override {} - virtual void SetChildBounds(aura::Window* child, - const gfx::Rect& requested_bounds) override {} - - private: - DISALLOW_COPY_AND_ASSIGN(TestLayoutManagerBase); -}; - -// Used by ShowMaximizedDoesntBounceAround. See it for details. -class MaximizeLayoutManager : public TestLayoutManagerBase { - public: - MaximizeLayoutManager() {} - virtual ~MaximizeLayoutManager() {} - - private: - // aura::LayoutManager: - virtual void OnWindowAddedToLayout(aura::Window* child) override { - // This simulates what happens when adding a maximized window. - SetChildBoundsDirect(child, gfx::Rect(0, 0, 300, 300)); - } - - DISALLOW_COPY_AND_ASSIGN(MaximizeLayoutManager); -}; - -// This simulates BrowserView, which creates a custom RootView so that -// OnNativeWidgetSizeChanged that is invoked during Init matters. -class TestWidget : public views::Widget { - public: - TestWidget() : did_size_change_more_than_once_(false) { - } - - // Returns true if the size changes to a non-empty size, and then to another - // size. - bool did_size_change_more_than_once() const { - return did_size_change_more_than_once_; - } - - virtual void OnNativeWidgetSizeChanged(const gfx::Size& new_size) override { - if (last_size_.IsEmpty()) - last_size_ = new_size; - else if (!did_size_change_more_than_once_ && new_size != last_size_) - did_size_change_more_than_once_ = true; - Widget::OnNativeWidgetSizeChanged(new_size); - } - - private: - bool did_size_change_more_than_once_; - gfx::Size last_size_; - - DISALLOW_COPY_AND_ASSIGN(TestWidget); -}; - -// Verifies the size of the widget doesn't change more than once during Init if -// the window ends up maximized. This is important as otherwise -// RenderWidgetHostViewAura ends up getting resized during construction, which -// leads to noticable flashes. -TEST_F(NativeWidgetAuraTest, ShowMaximizedDoesntBounceAround) { - root_window()->SetBounds(gfx::Rect(0, 0, 640, 480)); - root_window()->SetLayoutManager(new MaximizeLayoutManager); - scoped_ptr<TestWidget> widget(new TestWidget()); - Widget::InitParams params(Widget::InitParams::TYPE_WINDOW); - params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.parent = NULL; - params.context = root_window(); - params.show_state = ui::SHOW_STATE_MAXIMIZED; - params.bounds = gfx::Rect(10, 10, 100, 200); - widget->Init(params); - EXPECT_FALSE(widget->did_size_change_more_than_once()); - widget->CloseNow(); -} - -class PropertyTestLayoutManager : public TestLayoutManagerBase { - public: - PropertyTestLayoutManager() : added_(false) {} - virtual ~PropertyTestLayoutManager() {} - - bool added() const { return added_; } - - private: - // aura::LayoutManager: - virtual void OnWindowAddedToLayout(aura::Window* child) override { - EXPECT_TRUE(child->GetProperty(aura::client::kCanMaximizeKey)); - EXPECT_TRUE(child->GetProperty(aura::client::kCanMinimizeKey)); - EXPECT_TRUE(child->GetProperty(aura::client::kCanResizeKey)); - added_ = true; - } - - bool added_; - - DISALLOW_COPY_AND_ASSIGN(PropertyTestLayoutManager); -}; - -class PropertyTestWidgetDelegate : public views::WidgetDelegate { - public: - explicit PropertyTestWidgetDelegate(Widget* widget) : widget_(widget) {} - virtual ~PropertyTestWidgetDelegate() {} - - private: - // views::WidgetDelegate: - virtual bool CanMaximize() const override { - return true; - } - virtual bool CanMinimize() const override { - return true; - } - virtual bool CanResize() const override { - return true; - } - virtual void DeleteDelegate() override { - delete this; - } - virtual Widget* GetWidget() override { - return widget_; - } - virtual const Widget* GetWidget() const override { - return widget_; - } - - Widget* widget_; - DISALLOW_COPY_AND_ASSIGN(PropertyTestWidgetDelegate); -}; - -// Verifies that the kCanMaximizeKey/kCanMinimizeKey/kCanResizeKey have the -// correct value when added to the layout manager. -TEST_F(NativeWidgetAuraTest, TestPropertiesWhenAddedToLayout) { - root_window()->SetBounds(gfx::Rect(0, 0, 640, 480)); - PropertyTestLayoutManager* layout_manager = new PropertyTestLayoutManager(); - root_window()->SetLayoutManager(layout_manager); - scoped_ptr<TestWidget> widget(new TestWidget()); - Widget::InitParams params(Widget::InitParams::TYPE_WINDOW); - params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.delegate = new PropertyTestWidgetDelegate(widget.get()); - params.parent = NULL; - params.context = root_window(); - widget->Init(params); - EXPECT_TRUE(layout_manager->added()); - widget->CloseNow(); -} - -TEST_F(NativeWidgetAuraTest, GetClientAreaScreenBounds) { - // Create a widget. - Widget::InitParams params(Widget::InitParams::TYPE_WINDOW); - params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.context = root_window(); - params.bounds.SetRect(10, 20, 300, 400); - scoped_ptr<Widget> widget(new Widget()); - widget->Init(params); - - // For Aura, client area bounds match window bounds. - gfx::Rect client_bounds = widget->GetClientAreaBoundsInScreen(); - EXPECT_EQ(10, client_bounds.x()); - EXPECT_EQ(20, client_bounds.y()); - EXPECT_EQ(300, client_bounds.width()); - EXPECT_EQ(400, client_bounds.height()); -} - -// View subclass that tracks whether it has gotten a gesture event. -class GestureTrackingView : public views::View { - public: - GestureTrackingView() - : got_gesture_event_(false), - consume_gesture_event_(true) {} - - void set_consume_gesture_event(bool value) { - consume_gesture_event_ = value; - } - - void clear_got_gesture_event() { - got_gesture_event_ = false; - } - bool got_gesture_event() const { - return got_gesture_event_; - } - - // View overrides: - virtual void OnGestureEvent(ui::GestureEvent* event) override { - got_gesture_event_ = true; - if (consume_gesture_event_) - event->StopPropagation(); - } - - private: - // Was OnGestureEvent() invoked? - bool got_gesture_event_; - - // Dictates what OnGestureEvent() returns. - bool consume_gesture_event_; - - DISALLOW_COPY_AND_ASSIGN(GestureTrackingView); -}; - -// Verifies a capture isn't set on touch press and that the view that gets -// the press gets the release. -TEST_F(NativeWidgetAuraTest, DontCaptureOnGesture) { - // Create two views (both sized the same). |child| is configured not to - // consume the gesture event. - GestureTrackingView* view = new GestureTrackingView(); - GestureTrackingView* child = new GestureTrackingView(); - child->set_consume_gesture_event(false); - view->SetLayoutManager(new FillLayout); - view->AddChildView(child); - scoped_ptr<TestWidget> widget(new TestWidget()); - Widget::InitParams params(Widget::InitParams::TYPE_WINDOW_FRAMELESS); - params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.context = root_window(); - params.bounds = gfx::Rect(0, 0, 100, 200); - widget->Init(params); - widget->SetContentsView(view); - widget->Show(); - - ui::TouchEvent press( - ui::ET_TOUCH_PRESSED, gfx::Point(41, 51), 1, ui::EventTimeForNow()); - ui::EventDispatchDetails details = - event_processor()->OnEventFromSource(&press); - ASSERT_FALSE(details.dispatcher_destroyed); - // Both views should get the press. - EXPECT_TRUE(view->got_gesture_event()); - EXPECT_TRUE(child->got_gesture_event()); - view->clear_got_gesture_event(); - child->clear_got_gesture_event(); - // Touch events should not automatically grab capture. - EXPECT_FALSE(widget->HasCapture()); - - // Release touch. Only |view| should get the release since that it consumed - // the press. - ui::TouchEvent release( - ui::ET_TOUCH_RELEASED, gfx::Point(250, 251), 1, ui::EventTimeForNow()); - details = event_processor()->OnEventFromSource(&release); - ASSERT_FALSE(details.dispatcher_destroyed); - EXPECT_TRUE(view->got_gesture_event()); - EXPECT_FALSE(child->got_gesture_event()); - view->clear_got_gesture_event(); - - // Work around for bug in NativeWidgetAura. - // TODO: fix bug and remove this. - widget->Close(); -} - -// Verifies views with layers are targeted for events properly. -TEST_F(NativeWidgetAuraTest, PreferViewLayersToChildWindows) { - // Create two widgets: |parent| and |child|. |child| is a child of |parent|. - views::View* parent_root = new views::View; - scoped_ptr<Widget> parent(new Widget()); - Widget::InitParams parent_params(Widget::InitParams::TYPE_WINDOW_FRAMELESS); - parent_params.ownership = - views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - parent_params.context = root_window(); - parent->Init(parent_params); - parent->SetContentsView(parent_root); - parent->SetBounds(gfx::Rect(0, 0, 400, 400)); - parent->Show(); - - scoped_ptr<Widget> child(new Widget()); - Widget::InitParams child_params(Widget::InitParams::TYPE_CONTROL); - child_params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - child_params.parent = parent->GetNativeWindow(); - child->Init(child_params); - child->SetBounds(gfx::Rect(0, 0, 200, 200)); - child->Show(); - - // Point is over |child|. - EXPECT_EQ(child->GetNativeWindow(), - parent->GetNativeWindow()->GetEventHandlerForPoint( - gfx::Point(50, 50))); - - // Create a view with a layer and stack it at the bottom (below |child|). - views::View* view_with_layer = new views::View; - parent_root->AddChildView(view_with_layer); - view_with_layer->SetBounds(0, 0, 50, 50); - view_with_layer->SetPaintToLayer(true); - - // Make sure that |child| still gets the event. - EXPECT_EQ(child->GetNativeWindow(), - parent->GetNativeWindow()->GetEventHandlerForPoint( - gfx::Point(20, 20))); - - // Move |view_with_layer| to the top and make sure it gets the - // event when the point is within |view_with_layer|'s bounds. - view_with_layer->layer()->parent()->StackAtTop( - view_with_layer->layer()); - EXPECT_EQ(parent->GetNativeWindow(), - parent->GetNativeWindow()->GetEventHandlerForPoint( - gfx::Point(20, 20))); - - // Point is over |child|, it should get the event. - EXPECT_EQ(child->GetNativeWindow(), - parent->GetNativeWindow()->GetEventHandlerForPoint( - gfx::Point(70, 70))); - - delete view_with_layer; - view_with_layer = NULL; - - EXPECT_EQ(child->GetNativeWindow(), - parent->GetNativeWindow()->GetEventHandlerForPoint( - gfx::Point(20, 20))); - - // Work around for bug in NativeWidgetAura. - // TODO: fix bug and remove this. - parent->Close(); -} - -// Verifies that widget->FlashFrame() sets aura::client::kDrawAttentionKey, -// and activating the window clears it. -TEST_F(NativeWidgetAuraTest, FlashFrame) { - scoped_ptr<Widget> widget(new Widget()); - Widget::InitParams params(Widget::InitParams::TYPE_WINDOW); - params.context = root_window(); - params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget->Init(params); - aura::Window* window = widget->GetNativeWindow(); - EXPECT_FALSE(window->GetProperty(aura::client::kDrawAttentionKey)); - widget->FlashFrame(true); - EXPECT_TRUE(window->GetProperty(aura::client::kDrawAttentionKey)); - widget->FlashFrame(false); - EXPECT_FALSE(window->GetProperty(aura::client::kDrawAttentionKey)); - widget->FlashFrame(true); - EXPECT_TRUE(window->GetProperty(aura::client::kDrawAttentionKey)); - widget->Activate(); - EXPECT_FALSE(window->GetProperty(aura::client::kDrawAttentionKey)); -} - -TEST_F(NativeWidgetAuraTest, NoCrashOnThemeAfterClose) { - scoped_ptr<aura::Window> parent(new aura::Window(NULL)); - parent->Init(aura::WINDOW_LAYER_NOT_DRAWN); - parent->SetBounds(gfx::Rect(0, 0, 480, 320)); - scoped_ptr<Widget> widget(new Widget()); - Init(parent.get(), widget.get()); - widget->Show(); - widget->Close(); - base::MessageLoop::current()->RunUntilIdle(); - widget->GetNativeTheme(); // Shouldn't crash. -} - -// Used to track calls to WidgetDelegate::OnWidgetMove(). -class MoveTestWidgetDelegate : public WidgetDelegateView { - public: - MoveTestWidgetDelegate() : got_move_(false) {} - virtual ~MoveTestWidgetDelegate() {} - - void ClearGotMove() { got_move_ = false; } - bool got_move() const { return got_move_; } - - // WidgetDelegate overrides: - virtual void OnWidgetMove() override { got_move_ = true; } - - private: - bool got_move_; - - DISALLOW_COPY_AND_ASSIGN(MoveTestWidgetDelegate); -}; - -// This test simulates what happens when a window is normally maximized. That -// is, it's layer is acquired for animation then the window is maximized. -// Acquiring the layer resets the bounds of the window. This test verifies the -// Widget is still notified correctly of a move in this case. -TEST_F(NativeWidgetAuraTest, OnWidgetMovedInvokedAfterAcquireLayer) { - // |delegate| deletes itself when the widget is destroyed. - MoveTestWidgetDelegate* delegate = new MoveTestWidgetDelegate; - Widget* widget = - Widget::CreateWindowWithContextAndBounds(delegate, - root_window(), - gfx::Rect(10, 10, 100, 200)); - widget->Show(); - delegate->ClearGotMove(); - // Simulate a maximize with animation. - delete widget->GetNativeView()->RecreateLayer().release(); - widget->SetBounds(gfx::Rect(0, 0, 500, 500)); - EXPECT_TRUE(delegate->got_move()); - widget->CloseNow(); -} - -} // namespace -} // namespace views
diff --git a/ui/views/widget/native_widget_delegate.h b/ui/views/widget/native_widget_delegate.h deleted file mode 100644 index 5ab2a6d..0000000 --- a/ui/views/widget/native_widget_delegate.h +++ /dev/null
@@ -1,162 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_WIDGET_NATIVE_WIDGET_DELEGATE_H_ -#define UI_VIEWS_WIDGET_NATIVE_WIDGET_DELEGATE_H_ - -#include <vector> - -#include "ui/events/event_constants.h" -#include "ui/views/views_export.h" - -namespace gfx { -class Canvas; -class Path; -class Point; -class Size; -} - -namespace ui { -class GestureEvent; -class KeyEvent; -class Layer; -class MouseEvent; -class TouchEvent; -class ScrollEvent; -} - -namespace views { -class InputMethod; -class Widget; - -namespace internal { - -//////////////////////////////////////////////////////////////////////////////// -// NativeWidgetDelegate -// -// An interface implemented by the object that handles events sent by a -// NativeWidget implementation. -// -class VIEWS_EXPORT NativeWidgetDelegate { - public: - virtual ~NativeWidgetDelegate() {} - - // Returns true if the window is modal. - virtual bool IsModal() const = 0; - - // Returns true if the window is a dialog box. - virtual bool IsDialogBox() const = 0; - - // Returns true if the window can be activated. - virtual bool CanActivate() const = 0; - - virtual bool IsInactiveRenderingDisabled() const = 0; - virtual void EnableInactiveRendering() = 0; - - // Called when the activation state of a window has changed. - virtual void OnNativeWidgetActivationChanged(bool active) = 0; - - // Called when native focus moves from one native view to another. - virtual void OnNativeFocus(gfx::NativeView focused_view) = 0; - virtual void OnNativeBlur(gfx::NativeView focused_view) = 0; - - // Called when the window is about to be shown/hidden. - virtual void OnNativeWidgetVisibilityChanging(bool visible) = 0; - - // Called when the window is shown/hidden. - virtual void OnNativeWidgetVisibilityChanged(bool visible) = 0; - - // Called when the native widget is created. - // The |desktop_widget| bool is true for widgets created in the desktop and - // false for widgets created in the shell. - virtual void OnNativeWidgetCreated(bool desktop_widget) = 0; - - // Called just before the native widget is destroyed. This is the delegate's - // last chance to do anything with the native widget handle. - virtual void OnNativeWidgetDestroying() = 0; - - // Called just after the native widget is destroyed. - virtual void OnNativeWidgetDestroyed() = 0; - - // Returns the smallest size the window can be resized to by the user. - virtual gfx::Size GetMinimumSize() const = 0; - - // Returns the largest size the window can be resized to by the user. - virtual gfx::Size GetMaximumSize() const = 0; - - // Called when the NativeWidget changed position. - virtual void OnNativeWidgetMove() = 0; - - // Called when the NativeWidget changed size to |new_size|. - // This may happen at the same time as OnNativeWidgetWindowShowStateChanged, - // e.g. maximize. - virtual void OnNativeWidgetSizeChanged(const gfx::Size& new_size) = 0; - - // Called when the NativeWidget changes its window state. - // This may happen at the same time as OnNativeWidgetSizeChanged, e.g. - // maximize. - virtual void OnNativeWidgetWindowShowStateChanged() = 0; - - // Called when the user begins/ends to change the bounds of the window. - virtual void OnNativeWidgetBeginUserBoundsChange() = 0; - virtual void OnNativeWidgetEndUserBoundsChange() = 0; - - // Returns true if the delegate has a FocusManager. - virtual bool HasFocusManager() const = 0; - - // Paints the widget using acceleration. If the widget is not using - // accelerated painting this returns false and does nothing. - virtual bool OnNativeWidgetPaintAccelerated( - const gfx::Rect& dirty_region) = 0; - - // Paints the rootview in the canvas. This will also refresh the compositor - // tree if necessary when accelerated painting is enabled. - virtual void OnNativeWidgetPaint(gfx::Canvas* canvas) = 0; - - // Returns the non-client component (see ui/base/hit_test.h) containing - // |point|, in client coordinates. - virtual int GetNonClientComponent(const gfx::Point& point) = 0; - - // Mouse and key event handlers. - virtual void OnKeyEvent(ui::KeyEvent* event) = 0; - virtual void OnMouseEvent(ui::MouseEvent* event) = 0; - virtual void OnMouseCaptureLost() = 0; - - virtual void OnScrollEvent(ui::ScrollEvent* event) = 0; - virtual void OnGestureEvent(ui::GestureEvent* event) = 0; - - // Runs the specified native command. Returns true if the command is handled. - virtual bool ExecuteCommand(int command_id) = 0; - - // Returns the input method of the widget this delegate is associated with. - // Note that this does not use the top level widget, so may return NULL - // if the widget doesn't have input method. - virtual InputMethod* GetInputMethodDirect() = 0; - - // Returns the child Layers of the Widgets layer that were created by Views. - virtual const std::vector<ui::Layer*>& GetRootLayers() = 0; - - // Returns true if window has a hit-test mask. - virtual bool HasHitTestMask() const = 0; - - // Provides the hit-test mask if HasHitTestMask above returns true. - virtual void GetHitTestMask(gfx::Path* mask) const = 0; - - // - virtual Widget* AsWidget() = 0; - virtual const Widget* AsWidget() const = 0; - - // Sets-up the focus manager with the view that should have focus when the - // window is shown the first time. It takes the intended |show_state| of the - // window in order to decide whether the window should be focused now or - // later. Returns true if the initial focus has been set or the window should - // not set the initial focus, or false if the caller should set the initial - // focus (if any). - virtual bool SetInitialFocus(ui::WindowShowState show_state) = 0; -}; - -} // namespace internal -} // namespace views - -#endif // UI_VIEWS_WIDGET_NATIVE_WIDGET_DELEGATE_H_
diff --git a/ui/views/widget/native_widget_private.h b/ui/views/widget/native_widget_private.h deleted file mode 100644 index cd52012..0000000 --- a/ui/views/widget/native_widget_private.h +++ /dev/null
@@ -1,240 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_WIDGET_NATIVE_WIDGET_PRIVATE_H_ -#define UI_VIEWS_WIDGET_NATIVE_WIDGET_PRIVATE_H_ - -#include "base/strings/string16.h" -#include "ui/base/ui_base_types.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/views/widget/native_widget.h" - -namespace gfx { -class FontList; -class ImageSkia; -class Rect; -} - -namespace ui { -class InputMethod; -class NativeTheme; -class OSExchangeData; -} - -namespace views { -class InputMethod; -class TooltipManager; -namespace internal { -class InputMethodDelegate; - -//////////////////////////////////////////////////////////////////////////////// -// NativeWidgetPrivate interface -// -// A NativeWidget subclass internal to views that provides Widget a conduit for -// communication with a backend-specific native widget implementation. -// -// Many of the methods here are pass-thrus for Widget, and as such there is no -// documentation for them here. In that case, see methods of the same name in -// widget.h. -// -// IMPORTANT: This type is intended for use only by the views system and for -// NativeWidget implementations. This file should not be included -// in code that does not fall into one of these use cases. -// -class VIEWS_EXPORT NativeWidgetPrivate : public NativeWidget { - public: - virtual ~NativeWidgetPrivate() {} - - // Creates an appropriate default NativeWidgetPrivate implementation for the - // current OS/circumstance. - static NativeWidgetPrivate* CreateNativeWidget( - internal::NativeWidgetDelegate* delegate); - - static NativeWidgetPrivate* GetNativeWidgetForNativeView( - gfx::NativeView native_view); - static NativeWidgetPrivate* GetNativeWidgetForNativeWindow( - gfx::NativeWindow native_window); - - // Retrieves the top NativeWidgetPrivate in the hierarchy containing the given - // NativeView, or NULL if there is no NativeWidgetPrivate that contains it. - static NativeWidgetPrivate* GetTopLevelNativeWidget( - gfx::NativeView native_view); - - static void GetAllChildWidgets(gfx::NativeView native_view, - Widget::Widgets* children); - static void GetAllOwnedWidgets(gfx::NativeView native_view, - Widget::Widgets* owned); - static void ReparentNativeView(gfx::NativeView native_view, - gfx::NativeView new_parent); - - // Returns true if any mouse button is currently down. - static bool IsMouseButtonDown(); - - static gfx::FontList GetWindowTitleFontList(); - - // Initializes the NativeWidget. - virtual void InitNativeWidget(const Widget::InitParams& params) = 0; - - // Returns a NonClientFrameView for the widget's NonClientView, or NULL if - // the NativeWidget wants no special NonClientFrameView. - virtual NonClientFrameView* CreateNonClientFrameView() = 0; - - virtual bool ShouldUseNativeFrame() const = 0; - virtual bool ShouldWindowContentsBeTransparent() const = 0; - virtual void FrameTypeChanged() = 0; - - // Returns the Widget associated with this NativeWidget. This function is - // guaranteed to return non-NULL for the lifetime of the NativeWidget. - virtual Widget* GetWidget() = 0; - virtual const Widget* GetWidget() const = 0; - - // Returns the NativeView/Window associated with this NativeWidget. - virtual gfx::NativeView GetNativeView() const = 0; - virtual gfx::NativeWindow GetNativeWindow() const = 0; - - // Returns the topmost Widget in a hierarchy. - virtual Widget* GetTopLevelWidget() = 0; - - // Returns the Compositor, or NULL if there isn't one associated with this - // NativeWidget. - virtual const ui::Compositor* GetCompositor() const = 0; - virtual ui::Compositor* GetCompositor() = 0; - - // Returns the NativeWidget's layer, if any. - virtual ui::Layer* GetLayer() = 0; - - // Reorders the widget's child NativeViews which are associated to the view - // tree (eg via a NativeViewHost) to match the z-order of the views in the - // view tree. The z-order of views with layers relative to views with - // associated NativeViews is used to reorder the NativeView layers. This - // method assumes that the widget's child layers which are owned by a view are - // already in the correct z-order relative to each other and does no - // reordering if there are no views with an associated NativeView. - virtual void ReorderNativeViews() = 0; - - // Notifies the NativeWidget that a view was removed from the Widget's view - // hierarchy. - virtual void ViewRemoved(View* view) = 0; - - // Sets/Gets a native window property on the underlying native window object. - // Returns NULL if the property does not exist. Setting the property value to - // NULL removes the property. - virtual void SetNativeWindowProperty(const char* name, void* value) = 0; - virtual void* GetNativeWindowProperty(const char* name) const = 0; - - // Returns the native widget's tooltip manager. Called from the View hierarchy - // to update tooltips. - virtual TooltipManager* GetTooltipManager() const = 0; - - // Sets or releases event capturing for this native widget. - virtual void SetCapture() = 0; - virtual void ReleaseCapture() = 0; - - // Returns true if this native widget is capturing events. - virtual bool HasCapture() const = 0; - - // Returns the InputMethod for this native widget. - // Note that all widgets in a widget hierarchy share the same input method. - // TODO(suzhe): rename to GetInputMethod() when NativeWidget implementation - // class doesn't inherit Widget anymore. - virtual InputMethod* CreateInputMethod() = 0; - - // Returns the InputMethodDelegate for this native widget. - virtual InputMethodDelegate* GetInputMethodDelegate() = 0; - - // Returns the ui::InputMethod for this native widget. - // TODO(yukishiino): Rename this method to GetInputMethod once we remove - // views::InputMethod. - virtual ui::InputMethod* GetHostInputMethod() = 0; - - // Centers the window and sizes it to the specified size. - virtual void CenterWindow(const gfx::Size& size) = 0; - - // Retrieves the window's current restored bounds and "show" state, for - // persisting. - virtual void GetWindowPlacement( - gfx::Rect* bounds, - ui::WindowShowState* show_state) const = 0; - - // Sets the NativeWindow title. Returns true if the title changed. - virtual bool SetWindowTitle(const base::string16& title) = 0; - - // Sets the Window icons. |window_icon| is a 16x16 icon suitable for use in - // a title bar. |app_icon| is a larger size for use in the host environment - // app switching UI. - virtual void SetWindowIcons(const gfx::ImageSkia& window_icon, - const gfx::ImageSkia& app_icon) = 0; - - // Initializes the modal type of the window to |modal_type|. Called from - // NativeWidgetDelegate::OnNativeWidgetCreated() before the widget is - // initially parented. - virtual void InitModalType(ui::ModalType modal_type) = 0; - - // See method documentation in Widget. - virtual gfx::Rect GetWindowBoundsInScreen() const = 0; - virtual gfx::Rect GetClientAreaBoundsInScreen() const = 0; - virtual gfx::Rect GetRestoredBounds() const = 0; - virtual void SetBounds(const gfx::Rect& bounds) = 0; - virtual void SetSize(const gfx::Size& size) = 0; - virtual void StackAbove(gfx::NativeView native_view) = 0; - virtual void StackAtTop() = 0; - virtual void StackBelow(gfx::NativeView native_view) = 0; - virtual void SetShape(gfx::NativeRegion shape) = 0; - virtual void Close() = 0; - virtual void CloseNow() = 0; - virtual void Show() = 0; - virtual void Hide() = 0; - // Invoked if the initial show should maximize the window. |restored_bounds| - // is the bounds of the window when not maximized. - virtual void ShowMaximizedWithBounds(const gfx::Rect& restored_bounds) = 0; - virtual void ShowWithWindowState(ui::WindowShowState show_state) = 0; - virtual bool IsVisible() const = 0; - virtual void Activate() = 0; - virtual void Deactivate() = 0; - virtual bool IsActive() const = 0; - virtual void SetAlwaysOnTop(bool always_on_top) = 0; - virtual bool IsAlwaysOnTop() const = 0; - virtual void SetVisibleOnAllWorkspaces(bool always_visible) = 0; - virtual void Maximize() = 0; - virtual void Minimize() = 0; - virtual bool IsMaximized() const = 0; - virtual bool IsMinimized() const = 0; - virtual void Restore() = 0; - virtual void SetFullscreen(bool fullscreen) = 0; - virtual bool IsFullscreen() const = 0; - virtual void SetOpacity(unsigned char opacity) = 0; - virtual void SetUseDragFrame(bool use_drag_frame) = 0; - virtual void FlashFrame(bool flash) = 0; - virtual void RunShellDrag(View* view, - const ui::OSExchangeData& data, - const gfx::Point& location, - int operation, - ui::DragDropTypes::DragEventSource source) = 0; - virtual void SchedulePaintInRect(const gfx::Rect& rect) = 0; - virtual void SetCursor(gfx::NativeCursor cursor) = 0; - virtual bool IsMouseEventsEnabled() const = 0; - virtual void ClearNativeFocus() = 0; - virtual gfx::Rect GetWorkAreaBoundsInScreen() const = 0; - virtual Widget::MoveLoopResult RunMoveLoop( - const gfx::Vector2d& drag_offset, - Widget::MoveLoopSource source, - Widget::MoveLoopEscapeBehavior escape_behavior) = 0; - virtual void EndMoveLoop() = 0; - virtual void SetVisibilityChangedAnimationsEnabled(bool value) = 0; - virtual ui::NativeTheme* GetNativeTheme() const = 0; - virtual void OnRootViewLayout() = 0; - virtual bool IsTranslucentWindowOpacitySupported() const = 0; - virtual void OnSizeConstraintsChanged() = 0; - - // Repost an unhandled event to the native widget for default OS processing. - virtual void RepostNativeEvent(gfx::NativeEvent native_event) = 0; - - // Overridden from NativeWidget: - virtual internal::NativeWidgetPrivate* AsNativeWidgetPrivate() override; -}; - -} // namespace internal -} // namespace views - -#endif // UI_VIEWS_WIDGET_NATIVE_WIDGET_PRIVATE_H_
diff --git a/ui/views/widget/native_widget_unittest.cc b/ui/views/widget/native_widget_unittest.cc deleted file mode 100644 index 9002e9d..0000000 --- a/ui/views/widget/native_widget_unittest.cc +++ /dev/null
@@ -1,99 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/views/controls/native/native_view_host.h" -#include "ui/views/test/views_test_base.h" -#include "ui/views/view.h" -#include "ui/views/widget/native_widget_private.h" -#include "ui/views/widget/widget.h" - -namespace views { - -class ScopedTestWidget { - public: - explicit ScopedTestWidget(internal::NativeWidgetPrivate* native_widget) - : native_widget_(native_widget) { - } - ~ScopedTestWidget() { - // |CloseNow| deletes both |native_widget_| and its associated - // |Widget|. - native_widget_->GetWidget()->CloseNow(); - } - - internal::NativeWidgetPrivate* operator->() const { - return native_widget_; - } - internal::NativeWidgetPrivate* get() const { return native_widget_; } - - private: - internal::NativeWidgetPrivate* native_widget_; - DISALLOW_COPY_AND_ASSIGN(ScopedTestWidget); -}; - -class NativeWidgetTest : public ViewsTestBase { - public: - NativeWidgetTest() {} - virtual ~NativeWidgetTest() {} - - internal::NativeWidgetPrivate* CreateNativeWidgetOfType( - Widget::InitParams::Type type) { - Widget* widget = new Widget; - Widget::InitParams params = CreateParams(type); - params.ownership = views::Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET; - params.bounds = gfx::Rect(10, 10, 200, 200); - widget->Init(params); - return widget->native_widget_private(); - } - - internal::NativeWidgetPrivate* CreateNativeWidget() { - return CreateNativeWidgetOfType(Widget::InitParams::TYPE_POPUP); - } - - internal::NativeWidgetPrivate* CreateNativeSubWidget() { - return CreateNativeWidgetOfType(Widget::InitParams::TYPE_CONTROL); - } - - private: - DISALLOW_COPY_AND_ASSIGN(NativeWidgetTest); -}; - -TEST_F(NativeWidgetTest, CreateNativeWidget) { - ScopedTestWidget widget(CreateNativeWidget()); - EXPECT_TRUE(widget->GetWidget()->GetNativeView() != NULL); -} - -TEST_F(NativeWidgetTest, GetNativeWidgetForNativeView) { - ScopedTestWidget widget(CreateNativeWidget()); - EXPECT_EQ(widget.get(), - internal::NativeWidgetPrivate::GetNativeWidgetForNativeView( - widget->GetWidget()->GetNativeView())); -} - -// |widget| has the toplevel NativeWidget. -TEST_F(NativeWidgetTest, GetTopLevelNativeWidget1) { - ScopedTestWidget widget(CreateNativeWidget()); - EXPECT_EQ(widget.get(), - internal::NativeWidgetPrivate::GetTopLevelNativeWidget( - widget->GetWidget()->GetNativeView())); -} - -// |toplevel_widget| has the toplevel NativeWidget. -TEST_F(NativeWidgetTest, GetTopLevelNativeWidget2) { - ScopedTestWidget toplevel_widget(CreateNativeWidget()); - - // |toplevel_widget| owns |child_host|. - NativeViewHost* child_host = new NativeViewHost; - toplevel_widget->GetWidget()->SetContentsView(child_host); - - // |child_host| owns |child_widget|. - internal::NativeWidgetPrivate* child_widget = CreateNativeSubWidget(); - child_host->Attach(child_widget->GetWidget()->GetNativeView()); - - EXPECT_EQ(toplevel_widget.get(), - internal::NativeWidgetPrivate::GetTopLevelNativeWidget( - child_widget->GetWidget()->GetNativeView())); -} - -} // namespace views
diff --git a/ui/views/widget/root_view.cc b/ui/views/widget/root_view.cc deleted file mode 100644 index 38fe053..0000000 --- a/ui/views/widget/root_view.cc +++ /dev/null
@@ -1,732 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/widget/root_view.h" - -#include <algorithm> - -#include "base/logging.h" -#include "base/message_loop/message_loop.h" -#include "ui/accessibility/ax_view_state.h" -#include "ui/base/cursor/cursor.h" -#include "ui/base/dragdrop/drag_drop_types.h" -#include "ui/base/ui_base_switches_util.h" -#include "ui/compositor/layer.h" -#include "ui/events/event.h" -#include "ui/events/keycodes/keyboard_codes.h" -#include "ui/gfx/canvas.h" -#include "ui/views/drag_controller.h" -#include "ui/views/focus/view_storage.h" -#include "ui/views/layout/fill_layout.h" -#include "ui/views/view_targeter.h" -#include "ui/views/widget/root_view_targeter.h" -#include "ui/views/widget/widget.h" -#include "ui/views/widget/widget_delegate.h" - -typedef ui::EventDispatchDetails DispatchDetails; - -namespace views { -namespace internal { - -namespace { - -enum EventType { - EVENT_ENTER, - EVENT_EXIT -}; - -class MouseEnterExitEvent : public ui::MouseEvent { - public: - MouseEnterExitEvent(const ui::MouseEvent& event, ui::EventType type) - : ui::MouseEvent(event, - static_cast<View*>(NULL), - static_cast<View*>(NULL)) { - DCHECK(type == ui::ET_MOUSE_ENTERED || - type == ui::ET_MOUSE_EXITED); - SetType(type); - } - - virtual ~MouseEnterExitEvent() {} -}; - -} // namespace - -// This event handler receives events in the pre-target phase and takes care of -// the following: -// - Shows keyboard-triggered context menus. -class PreEventDispatchHandler : public ui::EventHandler { - public: - explicit PreEventDispatchHandler(View* owner) - : owner_(owner) { - } - virtual ~PreEventDispatchHandler() {} - - private: - // ui::EventHandler: - virtual void OnKeyEvent(ui::KeyEvent* event) override { - CHECK_EQ(ui::EP_PRETARGET, event->phase()); - if (event->handled()) - return; - - View* v = NULL; - if (owner_->GetFocusManager()) // Can be NULL in unittests. - v = owner_->GetFocusManager()->GetFocusedView(); - - // Special case to handle keyboard-triggered context menus. - if (v && v->enabled() && ((event->key_code() == ui::VKEY_APPS) || - (event->key_code() == ui::VKEY_F10 && event->IsShiftDown()))) { - // Clamp the menu location within the visible bounds of each ancestor view - // to avoid showing the menu over a completely different view or window. - gfx::Point location = v->GetKeyboardContextMenuLocation(); - for (View* parent = v->parent(); parent; parent = parent->parent()) { - const gfx::Rect& parent_bounds = parent->GetBoundsInScreen(); - location.SetToMax(parent_bounds.origin()); - location.SetToMin(parent_bounds.bottom_right()); - } - v->ShowContextMenu(location, ui::MENU_SOURCE_KEYBOARD); - event->StopPropagation(); - } - } - - View* owner_; - - DISALLOW_COPY_AND_ASSIGN(PreEventDispatchHandler); -}; - -// This event handler receives events in the post-target phase and takes care of -// the following: -// - Generates context menu, or initiates drag-and-drop, from gesture events. -class PostEventDispatchHandler : public ui::EventHandler { - public: - PostEventDispatchHandler() - : touch_dnd_enabled_(::switches::IsTouchDragDropEnabled()) { - } - virtual ~PostEventDispatchHandler() {} - - private: - // Overridden from ui::EventHandler: - virtual void OnGestureEvent(ui::GestureEvent* event) override { - DCHECK_EQ(ui::EP_POSTTARGET, event->phase()); - if (event->handled()) - return; - - View* target = static_cast<View*>(event->target()); - gfx::Point location = event->location(); - if (touch_dnd_enabled_ && - event->type() == ui::ET_GESTURE_LONG_PRESS && - (!target->drag_controller() || - target->drag_controller()->CanStartDragForView( - target, location, location))) { - if (target->DoDrag(*event, location, - ui::DragDropTypes::DRAG_EVENT_SOURCE_TOUCH)) { - event->StopPropagation(); - return; - } - } - - if (target->context_menu_controller() && - (event->type() == ui::ET_GESTURE_LONG_PRESS || - event->type() == ui::ET_GESTURE_LONG_TAP || - event->type() == ui::ET_GESTURE_TWO_FINGER_TAP)) { - gfx::Point screen_location(location); - View::ConvertPointToScreen(target, &screen_location); - target->ShowContextMenu(screen_location, ui::MENU_SOURCE_TOUCH); - event->StopPropagation(); - } - } - - bool touch_dnd_enabled_; - - DISALLOW_COPY_AND_ASSIGN(PostEventDispatchHandler); -}; - -// static -const char RootView::kViewClassName[] = "RootView"; - -//////////////////////////////////////////////////////////////////////////////// -// RootView, public: - -// Creation and lifetime ------------------------------------------------------- - -RootView::RootView(Widget* widget) - : widget_(widget), - mouse_pressed_handler_(NULL), - mouse_move_handler_(NULL), - last_click_handler_(NULL), - explicit_mouse_handler_(false), - last_mouse_event_flags_(0), - last_mouse_event_x_(-1), - last_mouse_event_y_(-1), - gesture_handler_(NULL), - gesture_handler_set_before_processing_(false), - pre_dispatch_handler_(new internal::PreEventDispatchHandler(this)), - post_dispatch_handler_(new internal::PostEventDispatchHandler), - focus_search_(this, false, false), - focus_traversable_parent_(NULL), - focus_traversable_parent_view_(NULL), - event_dispatch_target_(NULL), - old_dispatch_target_(NULL) { - AddPreTargetHandler(pre_dispatch_handler_.get()); - AddPostTargetHandler(post_dispatch_handler_.get()); - SetEventTargeter(scoped_ptr<ViewTargeter>(new RootViewTargeter(this, this))); -} - -RootView::~RootView() { - // If we have children remove them explicitly so to make sure a remove - // notification is sent for each one of them. - if (has_children()) - RemoveAllChildViews(true); -} - -// Tree operations ------------------------------------------------------------- - -void RootView::SetContentsView(View* contents_view) { - DCHECK(contents_view && GetWidget()->native_widget()) << - "Can't be called until after the native widget is created!"; - // The ContentsView must be set up _after_ the window is created so that its - // Widget pointer is valid. - SetLayoutManager(new FillLayout); - if (has_children()) - RemoveAllChildViews(true); - AddChildView(contents_view); - - // Force a layout now, since the attached hierarchy won't be ready for the - // containing window's bounds. Note that we call Layout directly rather than - // calling the widget's size changed handler, since the RootView's bounds may - // not have changed, which will cause the Layout not to be done otherwise. - Layout(); -} - -View* RootView::GetContentsView() { - return child_count() > 0 ? child_at(0) : NULL; -} - -void RootView::NotifyNativeViewHierarchyChanged() { - PropagateNativeViewHierarchyChanged(); -} - -// Focus ----------------------------------------------------------------------- - -void RootView::SetFocusTraversableParent(FocusTraversable* focus_traversable) { - DCHECK(focus_traversable != this); - focus_traversable_parent_ = focus_traversable; -} - -void RootView::SetFocusTraversableParentView(View* view) { - focus_traversable_parent_view_ = view; -} - -// System events --------------------------------------------------------------- - -void RootView::ThemeChanged() { - View::PropagateThemeChanged(); -} - -void RootView::LocaleChanged() { - View::PropagateLocaleChanged(); -} - -//////////////////////////////////////////////////////////////////////////////// -// RootView, FocusTraversable implementation: - -FocusSearch* RootView::GetFocusSearch() { - return &focus_search_; -} - -FocusTraversable* RootView::GetFocusTraversableParent() { - return focus_traversable_parent_; -} - -View* RootView::GetFocusTraversableParentView() { - return focus_traversable_parent_view_; -} - -//////////////////////////////////////////////////////////////////////////////// -// RootView, ui::EventProcessor overrides: - -ui::EventTarget* RootView::GetRootTarget() { - return this; -} - -void RootView::OnEventProcessingStarted(ui::Event* event) { - if (!event->IsGestureEvent()) - return; - - ui::GestureEvent* gesture_event = event->AsGestureEvent(); - - // Do not process ui::ET_GESTURE_BEGIN events. - if (gesture_event->type() == ui::ET_GESTURE_BEGIN) { - event->SetHandled(); - return; - } - - // Do not process ui::ET_GESTURE_END events if they do not correspond to the - // removal of the final touch point or if no gesture handler has already - // been set. - if (gesture_event->type() == ui::ET_GESTURE_END && - (gesture_event->details().touch_points() > 1 || - !gesture_handler_)) { - event->SetHandled(); - return; - } - - // Do not process subsequent gesture scroll events if no handler was set for - // a ui::ET_GESTURE_SCROLL_BEGIN event. - if (!gesture_handler_ && - (gesture_event->type() == ui::ET_GESTURE_SCROLL_UPDATE || - gesture_event->type() == ui::ET_GESTURE_SCROLL_END || - gesture_event->type() == ui::ET_SCROLL_FLING_START)) { - event->SetHandled(); - return; - } - - gesture_handler_set_before_processing_ = !!gesture_handler_; -} - -void RootView::OnEventProcessingFinished(ui::Event* event) { - // If |event| was not handled and |gesture_handler_| was not set by the - // dispatch of a previous gesture event, then no default gesture handler - // should be set prior to the next gesture event being received. - if (event->IsGestureEvent() && - !event->handled() && - !gesture_handler_set_before_processing_) { - gesture_handler_ = NULL; - } -} - -//////////////////////////////////////////////////////////////////////////////// -// RootView, View overrides: - -const Widget* RootView::GetWidget() const { - return widget_; -} - -Widget* RootView::GetWidget() { - return const_cast<Widget*>(const_cast<const RootView*>(this)->GetWidget()); -} - -bool RootView::IsDrawn() const { - return visible(); -} - -void RootView::Layout() { - View::Layout(); - widget_->OnRootViewLayout(); -} - -const char* RootView::GetClassName() const { - return kViewClassName; -} - -void RootView::SchedulePaintInRect(const gfx::Rect& rect) { - if (layer()) { - layer()->SchedulePaint(rect); - } else { - gfx::Rect xrect = ConvertRectToParent(rect); - gfx::Rect invalid_rect = gfx::IntersectRects(GetLocalBounds(), xrect); - if (!invalid_rect.IsEmpty()) - widget_->SchedulePaintInRect(invalid_rect); - } -} - -bool RootView::OnMousePressed(const ui::MouseEvent& event) { - UpdateCursor(event); - SetMouseLocationAndFlags(event); - - // If mouse_pressed_handler_ is non null, we are currently processing - // a pressed -> drag -> released session. In that case we send the - // event to mouse_pressed_handler_ - if (mouse_pressed_handler_) { - ui::MouseEvent mouse_pressed_event(event, static_cast<View*>(this), - mouse_pressed_handler_); - drag_info_.Reset(); - ui::EventDispatchDetails dispatch_details = - DispatchEvent(mouse_pressed_handler_, &mouse_pressed_event); - if (dispatch_details.dispatcher_destroyed) - return true; - return true; - } - DCHECK(!explicit_mouse_handler_); - - bool hit_disabled_view = false; - // Walk up the tree until we find a view that wants the mouse event. - for (mouse_pressed_handler_ = GetEventHandlerForPoint(event.location()); - mouse_pressed_handler_ && (mouse_pressed_handler_ != this); - mouse_pressed_handler_ = mouse_pressed_handler_->parent()) { - DVLOG(1) << "OnMousePressed testing " - << mouse_pressed_handler_->GetClassName(); - if (!mouse_pressed_handler_->enabled()) { - // Disabled views should eat events instead of propagating them upwards. - hit_disabled_view = true; - break; - } - - // See if this view wants to handle the mouse press. - ui::MouseEvent mouse_pressed_event(event, static_cast<View*>(this), - mouse_pressed_handler_); - - // Remove the double-click flag if the handler is different than the - // one which got the first click part of the double-click. - if (mouse_pressed_handler_ != last_click_handler_) - mouse_pressed_event.set_flags(event.flags() & ~ui::EF_IS_DOUBLE_CLICK); - - drag_info_.Reset(); - ui::EventDispatchDetails dispatch_details = - DispatchEvent(mouse_pressed_handler_, &mouse_pressed_event); - if (dispatch_details.dispatcher_destroyed) - return mouse_pressed_event.handled(); - - // The view could have removed itself from the tree when handling - // OnMousePressed(). In this case, the removal notification will have - // reset mouse_pressed_handler_ to NULL out from under us. Detect this - // case and stop. (See comments in view.h.) - // - // NOTE: Don't return true here, because we don't want the frame to - // forward future events to us when there's no handler. - if (!mouse_pressed_handler_) - break; - - // If the view handled the event, leave mouse_pressed_handler_ set and - // return true, which will cause subsequent drag/release events to get - // forwarded to that view. - if (mouse_pressed_event.handled()) { - last_click_handler_ = mouse_pressed_handler_; - DVLOG(1) << "OnMousePressed handled by " - << mouse_pressed_handler_->GetClassName(); - return true; - } - } - - // Reset mouse_pressed_handler_ to indicate that no processing is occurring. - mouse_pressed_handler_ = NULL; - - // In the event that a double-click is not handled after traversing the - // entire hierarchy (even as a single-click when sent to a different view), - // it must be marked as handled to avoid anything happening from default - // processing if it the first click-part was handled by us. - if (last_click_handler_ && (event.flags() & ui::EF_IS_DOUBLE_CLICK)) - hit_disabled_view = true; - - last_click_handler_ = NULL; - return hit_disabled_view; -} - -bool RootView::OnMouseDragged(const ui::MouseEvent& event) { - CHECK_EQ(ui::ET_MOUSE_DRAGGED, event.type()); - if (mouse_pressed_handler_) { - SetMouseLocationAndFlags(event); - - ui::MouseEvent mouse_event(event, static_cast<View*>(this), - mouse_pressed_handler_); - ui::EventDispatchDetails dispatch_details = - DispatchEvent(mouse_pressed_handler_, &mouse_event); - if (dispatch_details.dispatcher_destroyed) - return false; - } - return false; -} - -void RootView::OnMouseReleased(const ui::MouseEvent& event) { - UpdateCursor(event); - - if (mouse_pressed_handler_) { - ui::MouseEvent mouse_released(event, static_cast<View*>(this), - mouse_pressed_handler_); - // We allow the view to delete us from the event dispatch callback. As such, - // configure state such that we're done first, then call View. - View* mouse_pressed_handler = mouse_pressed_handler_; - SetMouseHandler(NULL); - ui::EventDispatchDetails dispatch_details = - DispatchEvent(mouse_pressed_handler, &mouse_released); - if (dispatch_details.dispatcher_destroyed) - return; - } -} - -void RootView::OnMouseCaptureLost() { - // TODO: this likely needs to reset touch handler too. - - if (mouse_pressed_handler_ || gesture_handler_) { - // Synthesize a release event for UpdateCursor. - if (mouse_pressed_handler_) { - gfx::Point last_point(last_mouse_event_x_, last_mouse_event_y_); - ui::MouseEvent release_event(ui::ET_MOUSE_RELEASED, - last_point, last_point, - last_mouse_event_flags_, - 0); - UpdateCursor(release_event); - } - // We allow the view to delete us from OnMouseCaptureLost. As such, - // configure state such that we're done first, then call View. - View* mouse_pressed_handler = mouse_pressed_handler_; - View* gesture_handler = gesture_handler_; - SetMouseHandler(NULL); - if (mouse_pressed_handler) - mouse_pressed_handler->OnMouseCaptureLost(); - else - gesture_handler->OnMouseCaptureLost(); - // WARNING: we may have been deleted. - } -} - -void RootView::OnMouseMoved(const ui::MouseEvent& event) { - CHECK_EQ(ui::ET_MOUSE_MOVED, event.type()); - View* v = GetEventHandlerForPoint(event.location()); - // Find the first enabled view, or the existing move handler, whichever comes - // first. The check for the existing handler is because if a view becomes - // disabled while handling moves, it's wrong to suddenly send ET_MOUSE_EXITED - // and ET_MOUSE_ENTERED events, because the mouse hasn't actually exited yet. - while (v && !v->enabled() && (v != mouse_move_handler_)) - v = v->parent(); - if (v && v != this) { - if (v != mouse_move_handler_) { - if (mouse_move_handler_ != NULL && - (!mouse_move_handler_->notify_enter_exit_on_child() || - !mouse_move_handler_->Contains(v))) { - MouseEnterExitEvent exit(event, ui::ET_MOUSE_EXITED); - exit.ConvertLocationToTarget(static_cast<View*>(this), - mouse_move_handler_); - ui::EventDispatchDetails dispatch_details = - DispatchEvent(mouse_move_handler_, &exit); - if (dispatch_details.dispatcher_destroyed) - return; - NotifyEnterExitOfDescendant(event, ui::ET_MOUSE_EXITED, - mouse_move_handler_, v); - } - View* old_handler = mouse_move_handler_; - mouse_move_handler_ = v; - if (!mouse_move_handler_->notify_enter_exit_on_child() || - !mouse_move_handler_->Contains(old_handler)) { - MouseEnterExitEvent entered(event, ui::ET_MOUSE_ENTERED); - entered.ConvertLocationToTarget(static_cast<View*>(this), - mouse_move_handler_); - ui::EventDispatchDetails dispatch_details = - DispatchEvent(mouse_move_handler_, &entered); - if (dispatch_details.dispatcher_destroyed) - return; - NotifyEnterExitOfDescendant(event, ui::ET_MOUSE_ENTERED, - mouse_move_handler_, old_handler); - } - } - ui::MouseEvent moved_event(event, static_cast<View*>(this), - mouse_move_handler_); - mouse_move_handler_->OnMouseMoved(moved_event); - // TODO(tdanderson): It may be possible to avoid setting the cursor twice - // (once here and once from CompoundEventFilter) on a - // mousemove. See crbug.com/351469. - if (!(moved_event.flags() & ui::EF_IS_NON_CLIENT)) - widget_->SetCursor(mouse_move_handler_->GetCursor(moved_event)); - } else if (mouse_move_handler_ != NULL) { - MouseEnterExitEvent exited(event, ui::ET_MOUSE_EXITED); - ui::EventDispatchDetails dispatch_details = - DispatchEvent(mouse_move_handler_, &exited); - if (dispatch_details.dispatcher_destroyed) - return; - NotifyEnterExitOfDescendant(event, ui::ET_MOUSE_EXITED, - mouse_move_handler_, v); - // On Aura the non-client area extends slightly outside the root view for - // some windows. Let the non-client cursor handling code set the cursor - // as we do above. - if (!(event.flags() & ui::EF_IS_NON_CLIENT)) - widget_->SetCursor(gfx::kNullCursor); - mouse_move_handler_ = NULL; - } -} - -void RootView::OnMouseExited(const ui::MouseEvent& event) { - if (mouse_move_handler_ != NULL) { - MouseEnterExitEvent exited(event, ui::ET_MOUSE_EXITED); - ui::EventDispatchDetails dispatch_details = - DispatchEvent(mouse_move_handler_, &exited); - if (dispatch_details.dispatcher_destroyed) - return; - NotifyEnterExitOfDescendant(event, ui::ET_MOUSE_EXITED, - mouse_move_handler_, NULL); - mouse_move_handler_ = NULL; - } -} - -bool RootView::OnMouseWheel(const ui::MouseWheelEvent& event) { - for (View* v = GetEventHandlerForPoint(event.location()); - v && v != this && !event.handled(); v = v->parent()) { - ui::EventDispatchDetails dispatch_details = - DispatchEvent(v, const_cast<ui::MouseWheelEvent*>(&event)); - if (dispatch_details.dispatcher_destroyed || - dispatch_details.target_destroyed) { - return event.handled(); - } - } - return event.handled(); -} - -void RootView::SetMouseHandler(View* new_mh) { - // If we're clearing the mouse handler, clear explicit_mouse_handler_ as well. - explicit_mouse_handler_ = (new_mh != NULL); - mouse_pressed_handler_ = new_mh; - gesture_handler_ = new_mh; - drag_info_.Reset(); -} - -void RootView::GetAccessibleState(ui::AXViewState* state) { - state->name = widget_->widget_delegate()->GetAccessibleWindowTitle(); - state->role = widget_->widget_delegate()->GetAccessibleWindowRole(); -} - -void RootView::UpdateParentLayer() { - if (layer()) - ReparentLayer(gfx::Vector2d(GetMirroredX(), y()), widget_->GetLayer()); -} - -//////////////////////////////////////////////////////////////////////////////// -// RootView, protected: - -void RootView::ViewHierarchyChanged( - const ViewHierarchyChangedDetails& details) { - widget_->ViewHierarchyChanged(details); - - if (!details.is_add) { - if (!explicit_mouse_handler_ && mouse_pressed_handler_ == details.child) - mouse_pressed_handler_ = NULL; - if (mouse_move_handler_ == details.child) - mouse_move_handler_ = NULL; - if (gesture_handler_ == details.child) - gesture_handler_ = NULL; - if (event_dispatch_target_ == details.child) - event_dispatch_target_ = NULL; - if (old_dispatch_target_ == details.child) - old_dispatch_target_ = NULL; - } -} - -void RootView::VisibilityChanged(View* /*starting_from*/, bool is_visible) { - if (!is_visible) { - // When the root view is being hidden (e.g. when widget is minimized) - // handlers are reset, so that after it is reshown, events are not captured - // by old handlers. - explicit_mouse_handler_ = false; - mouse_pressed_handler_ = NULL; - mouse_move_handler_ = NULL; - gesture_handler_ = NULL; - event_dispatch_target_ = NULL; - old_dispatch_target_ = NULL; - } -} - -void RootView::OnPaint(gfx::Canvas* canvas) { - if (!layer() || !layer()->fills_bounds_opaquely()) - canvas->DrawColor(SK_ColorBLACK, SkXfermode::kClear_Mode); - - View::OnPaint(canvas); -} - -gfx::Vector2d RootView::CalculateOffsetToAncestorWithLayer( - ui::Layer** layer_parent) { - gfx::Vector2d offset(View::CalculateOffsetToAncestorWithLayer(layer_parent)); - if (!layer() && layer_parent) - *layer_parent = widget_->GetLayer(); - return offset; -} - -View::DragInfo* RootView::GetDragInfo() { - return &drag_info_; -} - -//////////////////////////////////////////////////////////////////////////////// -// RootView, private: - -// Input ----------------------------------------------------------------------- - -void RootView::UpdateCursor(const ui::MouseEvent& event) { - if (!(event.flags() & ui::EF_IS_NON_CLIENT)) { - View* v = GetEventHandlerForPoint(event.location()); - ui::MouseEvent me(event, static_cast<View*>(this), v); - widget_->SetCursor(v->GetCursor(me)); - } -} - -void RootView::SetMouseLocationAndFlags(const ui::MouseEvent& event) { - last_mouse_event_flags_ = event.flags(); - last_mouse_event_x_ = event.x(); - last_mouse_event_y_ = event.y(); -} - -void RootView::NotifyEnterExitOfDescendant(const ui::MouseEvent& event, - ui::EventType type, - View* view, - View* sibling) { - for (View* p = view->parent(); p; p = p->parent()) { - if (!p->notify_enter_exit_on_child()) - continue; - if (sibling && p->Contains(sibling)) - break; - // It is necessary to recreate the notify-event for each dispatch, since one - // of the callbacks can mark the event as handled, and that would cause - // incorrect event dispatch. - MouseEnterExitEvent notify_event(event, type); - ui::EventDispatchDetails dispatch_details = DispatchEvent(p, ¬ify_event); - if (dispatch_details.dispatcher_destroyed || - dispatch_details.target_destroyed) { - return; - } - } -} - -bool RootView::CanDispatchToTarget(ui::EventTarget* target) { - return event_dispatch_target_ == target; -} - -ui::EventDispatchDetails RootView::PreDispatchEvent(ui::EventTarget* target, - ui::Event* event) { - View* view = static_cast<View*>(target); - if (event->IsGestureEvent()) { - // Update |gesture_handler_| to indicate which View is currently handling - // gesture events. - // TODO(tdanderson): Look into moving this to PostDispatchEvent() and - // using |event_dispatch_target_| instead of - // |gesture_handler_| to detect if the view has been - // removed from the tree. - gesture_handler_ = view; - - // Disabled views are permitted to be targets of gesture events, but - // gesture events should never actually be dispatched to them. Prevent - // dispatch by marking the event as handled. - if (!view->enabled()) - event->SetHandled(); - } - - old_dispatch_target_ = event_dispatch_target_; - event_dispatch_target_ = view; - return DispatchDetails(); -} - -ui::EventDispatchDetails RootView::PostDispatchEvent(ui::EventTarget* target, - const ui::Event& event) { - // The GESTURE_END event corresponding to the removal of the final touch - // point marks the end of a gesture sequence, so reset |gesture_handler_| - // to NULL. - if (event.type() == ui::ET_GESTURE_END) { - // In case a drag was in progress, reset all the handlers. Otherwise, just - // reset the gesture handler. - if (gesture_handler_ && gesture_handler_ == mouse_pressed_handler_) - SetMouseHandler(NULL); - else - gesture_handler_ = NULL; - } - - DispatchDetails details; - if (target != event_dispatch_target_) - details.target_destroyed = true; - - event_dispatch_target_ = old_dispatch_target_; - old_dispatch_target_ = NULL; - -#ifndef NDEBUG - DCHECK(!event_dispatch_target_ || Contains(event_dispatch_target_)); -#endif - - return details; -} - -} // namespace internal -} // namespace views
diff --git a/ui/views/widget/root_view.h b/ui/views/widget/root_view.h deleted file mode 100644 index ad2ca4c..0000000 --- a/ui/views/widget/root_view.h +++ /dev/null
@@ -1,236 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_WIDGET_ROOT_VIEW_H_ -#define UI_VIEWS_WIDGET_ROOT_VIEW_H_ - -#include <string> - -#include "base/memory/ref_counted.h" -#include "ui/events/event_processor.h" -#include "ui/views/focus/focus_manager.h" -#include "ui/views/focus/focus_search.h" -#include "ui/views/view.h" -#include "ui/views/view_targeter_delegate.h" - -namespace views { - -namespace test { -class ViewTargeterTest; -class WidgetTest; -} - -class RootViewTargeter; -class Widget; - -// This is a views-internal API and should not be used externally. -// Widget exposes this object as a View*. -namespace internal { -class PreEventDispatchHandler; - -//////////////////////////////////////////////////////////////////////////////// -// RootView class -// -// The RootView is the root of a View hierarchy. A RootView is attached to a -// Widget. The Widget is responsible for receiving events from the host -// environment, converting them to views-compatible events and then forwarding -// them to the RootView for propagation into the View hierarchy. -// -// A RootView can have only one child, called its "Contents View" which is -// sized to fill the bounds of the RootView (and hence the client area of the -// Widget). Call SetContentsView() after the associated Widget has been -// initialized to attach the contents view to the RootView. -// TODO(beng): Enforce no other callers to AddChildView/tree functions by -// overriding those methods as private here. -// TODO(beng): Clean up API further, make Widget a friend. -// TODO(sky): We don't really want to export this class. -// -class VIEWS_EXPORT RootView : public View, - public ViewTargeterDelegate, - public FocusTraversable, - public ui::EventProcessor { - public: - static const char kViewClassName[]; - - // Creation and lifetime ----------------------------------------------------- - explicit RootView(Widget* widget); - virtual ~RootView(); - - // Tree operations ----------------------------------------------------------- - - // Sets the "contents view" of the RootView. This is the single child view - // that is responsible for laying out the contents of the widget. - void SetContentsView(View* contents_view); - View* GetContentsView(); - - // Called when parent of the host changed. - void NotifyNativeViewHierarchyChanged(); - - // Focus --------------------------------------------------------------------- - - // Used to set the FocusTraversable parent after the view has been created - // (typically when the hierarchy changes and this RootView is added/removed). - virtual void SetFocusTraversableParent(FocusTraversable* focus_traversable); - - // Used to set the View parent after the view has been created. - virtual void SetFocusTraversableParentView(View* view); - - // System events ------------------------------------------------------------- - - // Public API for broadcasting theme change notifications to this View - // hierarchy. - void ThemeChanged(); - - // Public API for broadcasting locale change notifications to this View - // hierarchy. - void LocaleChanged(); - - // Overridden from FocusTraversable: - virtual FocusSearch* GetFocusSearch() override; - virtual FocusTraversable* GetFocusTraversableParent() override; - virtual View* GetFocusTraversableParentView() override; - - // Overridden from ui::EventProcessor: - virtual ui::EventTarget* GetRootTarget() override; - virtual void OnEventProcessingStarted(ui::Event* event) override; - virtual void OnEventProcessingFinished(ui::Event* event) override; - - // Overridden from View: - virtual const Widget* GetWidget() const override; - virtual Widget* GetWidget() override; - virtual bool IsDrawn() const override; - virtual void Layout() override; - virtual const char* GetClassName() const override; - virtual void SchedulePaintInRect(const gfx::Rect& rect) override; - virtual bool OnMousePressed(const ui::MouseEvent& event) override; - virtual bool OnMouseDragged(const ui::MouseEvent& event) override; - virtual void OnMouseReleased(const ui::MouseEvent& event) override; - virtual void OnMouseCaptureLost() override; - virtual void OnMouseMoved(const ui::MouseEvent& event) override; - virtual void OnMouseExited(const ui::MouseEvent& event) override; - virtual bool OnMouseWheel(const ui::MouseWheelEvent& event) override; - virtual void SetMouseHandler(View* new_mouse_handler) override; - virtual void GetAccessibleState(ui::AXViewState* state) override; - virtual void UpdateParentLayer() override; - - protected: - // Overridden from View: - virtual void ViewHierarchyChanged( - const ViewHierarchyChangedDetails& details) override; - virtual void VisibilityChanged(View* starting_from, bool is_visible) override; - virtual void OnPaint(gfx::Canvas* canvas) override; - virtual gfx::Vector2d CalculateOffsetToAncestorWithLayer( - ui::Layer** layer_parent) override; - virtual View::DragInfo* GetDragInfo() override; - - private: - friend class ::views::RootViewTargeter; - friend class ::views::View; - friend class ::views::Widget; - friend class ::views::test::ViewTargeterTest; - friend class ::views::test::WidgetTest; - - // Input --------------------------------------------------------------------- - - // Update the cursor given a mouse event. This is called by non mouse_move - // event handlers to honor the cursor desired by views located under the - // cursor during drag operations. The location of the mouse should be in the - // current coordinate system (i.e. any necessary transformation should be - // applied to the point prior to calling this). - void UpdateCursor(const ui::MouseEvent& event); - - // Updates the last_mouse_* fields from e. The location of the mouse should be - // in the current coordinate system (i.e. any necessary transformation should - // be applied to the point prior to calling this). - void SetMouseLocationAndFlags(const ui::MouseEvent& event); - - // |view| is the view receiving |event|. This function sends the event to all - // the Views up the hierarchy that has |notify_enter_exit_on_child_| flag - // turned on, but does not contain |sibling|. - void NotifyEnterExitOfDescendant(const ui::MouseEvent& event, - ui::EventType type, - View* view, - View* sibling); - - // Overridden from ui::EventDispatcherDelegate: - virtual bool CanDispatchToTarget(ui::EventTarget* target) override; - virtual ui::EventDispatchDetails PreDispatchEvent(ui::EventTarget* target, - ui::Event* event) override; - virtual ui::EventDispatchDetails PostDispatchEvent( - ui::EventTarget* target, const ui::Event& event) override; - - ////////////////////////////////////////////////////////////////////////////// - // Tree operations ----------------------------------------------------------- - - // The host Widget - Widget* widget_; - - // Input --------------------------------------------------------------------- - - // TODO(tdanderson): Consider moving the input-related members into - // ViewTargeter / RootViewTargeter. - - // The view currently handing down - drag - up - View* mouse_pressed_handler_; - - // The view currently handling enter / exit - View* mouse_move_handler_; - - // The last view to handle a mouse click, so that we can determine if - // a double-click lands on the same view as its single-click part. - View* last_click_handler_; - - // true if mouse_pressed_handler_ has been explicitly set - bool explicit_mouse_handler_; - - // Last position/flag of a mouse press/drag. Used if capture stops and we need - // to synthesize a release. - int last_mouse_event_flags_; - int last_mouse_event_x_; - int last_mouse_event_y_; - - // The View currently handling gesture events. - View* gesture_handler_; - - // Used to indicate if the |gesture_handler_| member was set prior to the - // processing of the current event (i.e., if |gesture_handler_| was set - // by the dispatch of a previous gesture event). - // TODO(tdanderson): It may be possible to eliminate the need for this - // member if |event_dispatch_target_| can be used in - // its place. - bool gesture_handler_set_before_processing_; - - scoped_ptr<internal::PreEventDispatchHandler> pre_dispatch_handler_; - scoped_ptr<internal::PostEventDispatchHandler> post_dispatch_handler_; - - // Focus --------------------------------------------------------------------- - - // The focus search algorithm. - FocusSearch focus_search_; - - // Whether this root view belongs to the current active window. - // bool activated_; - - // The parent FocusTraversable, used for focus traversal. - FocusTraversable* focus_traversable_parent_; - - // The View that contains this RootView. This is used when we have RootView - // wrapped inside native components, and is used for the focus traversal. - View* focus_traversable_parent_view_; - - View* event_dispatch_target_; - View* old_dispatch_target_; - - // Drag and drop ------------------------------------------------------------- - - // Tracks drag state for a view. - View::DragInfo drag_info_; - - DISALLOW_IMPLICIT_CONSTRUCTORS(RootView); -}; - -} // namespace internal -} // namespace views - -#endif // UI_VIEWS_WIDGET_ROOT_VIEW_H_
diff --git a/ui/views/widget/root_view_targeter.cc b/ui/views/widget/root_view_targeter.cc deleted file mode 100644 index 6cc41f2..0000000 --- a/ui/views/widget/root_view_targeter.cc +++ /dev/null
@@ -1,77 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/widget/root_view_targeter.h" - -#include "ui/views/view.h" -#include "ui/views/view_targeter_delegate.h" -#include "ui/views/views_switches.h" -#include "ui/views/widget/root_view.h" -#include "ui/views/widget/widget.h" - -namespace views { - -RootViewTargeter::RootViewTargeter(ViewTargeterDelegate* delegate, - internal::RootView* root_view) - : ViewTargeter(delegate), root_view_(root_view) { -} - -RootViewTargeter::~RootViewTargeter() { -} - -View* RootViewTargeter::FindTargetForGestureEvent( - View* root, - const ui::GestureEvent& gesture) { - CHECK_EQ(root, root_view_); - - // Return the default gesture handler if one is already set. - if (root_view_->gesture_handler_) { - CHECK(root_view_->gesture_handler_set_before_processing_); - return root_view_->gesture_handler_; - } - - // If rect-based targeting is enabled, use the gesture's bounding box to - // determine the target. Otherwise use the center point of the gesture's - // bounding box to determine the target. - gfx::Rect rect(gesture.location(), gfx::Size(1, 1)); - if (views::switches::IsRectBasedTargetingEnabled() && - !gesture.details().bounding_box().IsEmpty()) { - // TODO(tdanderson): Pass in the bounding box to GetEventHandlerForRect() - // once crbug.com/313392 is resolved. - rect.set_size(gesture.details().bounding_box().size()); - rect.Offset(-rect.width() / 2, -rect.height() / 2); - } - - return root->GetEffectiveViewTargeter()->TargetForRect(root, rect); -} - -ui::EventTarget* RootViewTargeter::FindNextBestTargetForGestureEvent( - ui::EventTarget* previous_target, - const ui::GestureEvent& gesture) { - // ET_GESTURE_END events should only ever be targeted to the default - // gesture handler set by a previous gesture, if one exists. Thus we do not - // permit any re-targeting of ET_GESTURE_END events. - if (gesture.type() == ui::ET_GESTURE_END) - return NULL; - - // Prohibit re-targeting of gesture events (except for GESTURE_SCROLL_BEGIN - // events) if the default gesture handler was set by the dispatch of a - // previous gesture event. - if (root_view_->gesture_handler_set_before_processing_ && - gesture.type() != ui::ET_GESTURE_SCROLL_BEGIN) { - return NULL; - } - - // If |gesture_handler_| is NULL, it is either because the view was removed - // from the tree by the previous dispatch of |gesture| or because |gesture| is - // the GESTURE_END event corresponding to the removal of the last touch - // point. In either case, no further re-targeting of |gesture| should be - // permitted. - if (!root_view_->gesture_handler_) - return NULL; - - return previous_target->GetParentTarget(); -} - -} // namespace views
diff --git a/ui/views/widget/root_view_targeter.h b/ui/views/widget/root_view_targeter.h deleted file mode 100644 index 6b10a4e..0000000 --- a/ui/views/widget/root_view_targeter.h +++ /dev/null
@@ -1,47 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_WIDGET_ROOT_VIEW_TARGETER_H_ -#define UI_VIEWS_WIDGET_ROOT_VIEW_TARGETER_H_ - -#include "ui/views/view_targeter.h" -#include "ui/views/views_export.h" - -namespace views { - -namespace internal { -class RootView; -} // namespace internal - -class View; -class ViewTargeterDelegate; - -// A derived class of ViewTargeter that defines targeting logic for cases -// needing to access the members of RootView. For example, when determining the -// target of a gesture event, we need to know if a previous gesture has already -// established the View to which all subsequent gestures should be targeted. -class VIEWS_EXPORT RootViewTargeter : public ViewTargeter { - public: - RootViewTargeter(ViewTargeterDelegate* delegate, - internal::RootView* root_view); - virtual ~RootViewTargeter(); - - private: - // ViewTargeter: - virtual View* FindTargetForGestureEvent( - View* root, - const ui::GestureEvent& gesture) override; - virtual ui::EventTarget* FindNextBestTargetForGestureEvent( - ui::EventTarget* previous_target, - const ui::GestureEvent& gesture) override; - - // A pointer to the RootView on which |this| is installed. - internal::RootView* root_view_; - - DISALLOW_COPY_AND_ASSIGN(RootViewTargeter); -}; - -} // namespace views - -#endif // UI_VIEWS_WIDGET_ROOT_VIEW_TARGETER_H_
diff --git a/ui/views/widget/root_view_unittest.cc b/ui/views/widget/root_view_unittest.cc deleted file mode 100644 index 21b1cc2..0000000 --- a/ui/views/widget/root_view_unittest.cc +++ /dev/null
@@ -1,345 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/widget/root_view.h" - -#include "ui/views/context_menu_controller.h" -#include "ui/views/test/views_test_base.h" -#include "ui/views/view_targeter.h" -#include "ui/views/widget/root_view.h" - -namespace views { -namespace test { - -typedef ViewsTestBase RootViewTest; - -class DeleteOnKeyEventView : public View { - public: - explicit DeleteOnKeyEventView(bool* set_on_key) : set_on_key_(set_on_key) {} - virtual ~DeleteOnKeyEventView() {} - - virtual bool OnKeyPressed(const ui::KeyEvent& event) override { - *set_on_key_ = true; - delete this; - return true; - } - - private: - // Set to true in OnKeyPressed(). - bool* set_on_key_; - - DISALLOW_COPY_AND_ASSIGN(DeleteOnKeyEventView); -}; - -// Verifies deleting a View in OnKeyPressed() doesn't crash and that the -// target is marked as destroyed in the returned EventDispatchDetails. -TEST_F(RootViewTest, DeleteViewDuringKeyEventDispatch) { - Widget widget; - Widget::InitParams init_params = - CreateParams(Widget::InitParams::TYPE_POPUP); - init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(init_params); - - bool got_key_event = false; - - View* content = new View; - widget.SetContentsView(content); - - View* child = new DeleteOnKeyEventView(&got_key_event); - content->AddChildView(child); - - // Give focus to |child| so that it will be the target of the key event. - child->SetFocusable(true); - child->RequestFocus(); - - internal::RootView* root_view = - static_cast<internal::RootView*>(widget.GetRootView()); - ViewTargeter* view_targeter = new ViewTargeter(root_view); - root_view->SetEventTargeter(make_scoped_ptr(view_targeter)); - - ui::KeyEvent key_event(ui::ET_KEY_PRESSED, ui::VKEY_ESCAPE, ui::EF_NONE); - ui::EventDispatchDetails details = root_view->OnEventFromSource(&key_event); - EXPECT_TRUE(details.target_destroyed); - EXPECT_FALSE(details.dispatcher_destroyed); - EXPECT_TRUE(got_key_event); -} - -// Tracks whether a context menu is shown. -class TestContextMenuController : public ContextMenuController { - public: - TestContextMenuController() - : show_context_menu_calls_(0), - menu_source_view_(NULL), - menu_source_type_(ui::MENU_SOURCE_NONE) { - } - virtual ~TestContextMenuController() {} - - int show_context_menu_calls() const { return show_context_menu_calls_; } - View* menu_source_view() const { return menu_source_view_; } - ui::MenuSourceType menu_source_type() const { return menu_source_type_; } - - void Reset() { - show_context_menu_calls_ = 0; - menu_source_view_ = NULL; - menu_source_type_ = ui::MENU_SOURCE_NONE; - } - - // ContextMenuController: - virtual void ShowContextMenuForView( - View* source, - const gfx::Point& point, - ui::MenuSourceType source_type) override { - show_context_menu_calls_++; - menu_source_view_ = source; - menu_source_type_ = source_type; - } - - private: - int show_context_menu_calls_; - View* menu_source_view_; - ui::MenuSourceType menu_source_type_; - - DISALLOW_COPY_AND_ASSIGN(TestContextMenuController); -}; - -// Tests that context menus are shown for certain key events (Shift+F10 -// and VKEY_APPS) by the pre-target handler installed on RootView. -TEST_F(RootViewTest, ContextMenuFromKeyEvent) { - Widget widget; - Widget::InitParams init_params = - CreateParams(Widget::InitParams::TYPE_POPUP); - init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(init_params); - internal::RootView* root_view = - static_cast<internal::RootView*>(widget.GetRootView()); - - TestContextMenuController controller; - View* focused_view = new View; - focused_view->set_context_menu_controller(&controller); - widget.SetContentsView(focused_view); - focused_view->SetFocusable(true); - focused_view->RequestFocus(); - - // No context menu should be shown for a keypress of 'A'. - ui::KeyEvent nomenu_key_event('a', ui::VKEY_A, ui::EF_NONE); - ui::EventDispatchDetails details = - root_view->OnEventFromSource(&nomenu_key_event); - EXPECT_FALSE(details.target_destroyed); - EXPECT_FALSE(details.dispatcher_destroyed); - EXPECT_EQ(0, controller.show_context_menu_calls()); - EXPECT_EQ(NULL, controller.menu_source_view()); - EXPECT_EQ(ui::MENU_SOURCE_NONE, controller.menu_source_type()); - controller.Reset(); - - // A context menu should be shown for a keypress of Shift+F10. - ui::KeyEvent menu_key_event( - ui::ET_KEY_PRESSED, ui::VKEY_F10, ui::EF_SHIFT_DOWN); - details = root_view->OnEventFromSource(&menu_key_event); - EXPECT_FALSE(details.target_destroyed); - EXPECT_FALSE(details.dispatcher_destroyed); - EXPECT_EQ(1, controller.show_context_menu_calls()); - EXPECT_EQ(focused_view, controller.menu_source_view()); - EXPECT_EQ(ui::MENU_SOURCE_KEYBOARD, controller.menu_source_type()); - controller.Reset(); - - // A context menu should be shown for a keypress of VKEY_APPS. - ui::KeyEvent menu_key_event2(ui::ET_KEY_PRESSED, ui::VKEY_APPS, ui::EF_NONE); - details = root_view->OnEventFromSource(&menu_key_event2); - EXPECT_FALSE(details.target_destroyed); - EXPECT_FALSE(details.dispatcher_destroyed); - EXPECT_EQ(1, controller.show_context_menu_calls()); - EXPECT_EQ(focused_view, controller.menu_source_view()); - EXPECT_EQ(ui::MENU_SOURCE_KEYBOARD, controller.menu_source_type()); - controller.Reset(); -} - -// View which handles all gesture events. -class GestureHandlingView : public View { - public: - GestureHandlingView() { - } - - virtual ~GestureHandlingView() { - } - - virtual void OnGestureEvent(ui::GestureEvent* event) override { - event->SetHandled(); - } - - private: - DISALLOW_COPY_AND_ASSIGN(GestureHandlingView); -}; - -// Tests that context menus are shown for long press by the post-target handler -// installed on the RootView only if the event is targetted at a view which can -// show a context menu. -TEST_F(RootViewTest, ContextMenuFromLongPress) { - Widget widget; - Widget::InitParams init_params = - CreateParams(Widget::InitParams::TYPE_POPUP); - init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - init_params.bounds = gfx::Rect(100, 100); - widget.Init(init_params); - internal::RootView* root_view = - static_cast<internal::RootView*>(widget.GetRootView()); - - // Create a view capable of showing the context menu with two children one of - // which handles all gesture events (e.g. a button). - TestContextMenuController controller; - View* parent_view = new View; - parent_view->set_context_menu_controller(&controller); - widget.SetContentsView(parent_view); - - View* gesture_handling_child_view = new GestureHandlingView; - gesture_handling_child_view->SetBoundsRect(gfx::Rect(10, 10)); - parent_view->AddChildView(gesture_handling_child_view); - - View* other_child_view = new View; - other_child_view->SetBoundsRect(gfx::Rect(20, 0, 10, 10)); - parent_view->AddChildView(other_child_view); - - // |parent_view| should not show a context menu as a result of a long press on - // |gesture_handling_child_view|. - ui::GestureEvent long_press1( - 5, - 5, - 0, - base::TimeDelta(), - ui::GestureEventDetails(ui::ET_GESTURE_LONG_PRESS)); - ui::EventDispatchDetails details = root_view->OnEventFromSource(&long_press1); - - ui::GestureEvent end1( - 5, 5, 0, base::TimeDelta(), ui::GestureEventDetails(ui::ET_GESTURE_END)); - details = root_view->OnEventFromSource(&end1); - - EXPECT_FALSE(details.target_destroyed); - EXPECT_FALSE(details.dispatcher_destroyed); - EXPECT_EQ(0, controller.show_context_menu_calls()); - controller.Reset(); - - // |parent_view| should show a context menu as a result of a long press on - // |other_child_view|. - ui::GestureEvent long_press2( - 25, - 5, - 0, - base::TimeDelta(), - ui::GestureEventDetails(ui::ET_GESTURE_LONG_PRESS)); - details = root_view->OnEventFromSource(&long_press2); - - ui::GestureEvent end2( - 25, 5, 0, base::TimeDelta(), ui::GestureEventDetails(ui::ET_GESTURE_END)); - details = root_view->OnEventFromSource(&end2); - - EXPECT_FALSE(details.target_destroyed); - EXPECT_FALSE(details.dispatcher_destroyed); - EXPECT_EQ(1, controller.show_context_menu_calls()); - controller.Reset(); - - // |parent_view| should show a context menu as a result of a long press on - // itself. - ui::GestureEvent long_press3( - 50, - 50, - 0, - base::TimeDelta(), - ui::GestureEventDetails(ui::ET_GESTURE_LONG_PRESS)); - details = root_view->OnEventFromSource(&long_press3); - - ui::GestureEvent end3( - 25, 5, 0, base::TimeDelta(), ui::GestureEventDetails(ui::ET_GESTURE_END)); - details = root_view->OnEventFromSource(&end3); - - EXPECT_FALSE(details.target_destroyed); - EXPECT_FALSE(details.dispatcher_destroyed); - EXPECT_EQ(1, controller.show_context_menu_calls()); -} - -// Tests that context menus are not shown for disabled views on a long press. -TEST_F(RootViewTest, ContextMenuFromLongPressOnDisabledView) { - Widget widget; - Widget::InitParams init_params = - CreateParams(Widget::InitParams::TYPE_POPUP); - init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - init_params.bounds = gfx::Rect(100, 100); - widget.Init(init_params); - internal::RootView* root_view = - static_cast<internal::RootView*>(widget.GetRootView()); - - // Create a view capable of showing the context menu with two children one of - // which handles all gesture events (e.g. a button). Also mark this view - // as disabled. - TestContextMenuController controller; - View* parent_view = new View; - parent_view->set_context_menu_controller(&controller); - parent_view->SetEnabled(false); - widget.SetContentsView(parent_view); - - View* gesture_handling_child_view = new GestureHandlingView; - gesture_handling_child_view->SetBoundsRect(gfx::Rect(10, 10)); - parent_view->AddChildView(gesture_handling_child_view); - - View* other_child_view = new View; - other_child_view->SetBoundsRect(gfx::Rect(20, 0, 10, 10)); - parent_view->AddChildView(other_child_view); - - // |parent_view| should not show a context menu as a result of a long press on - // |gesture_handling_child_view|. - ui::GestureEvent long_press1( - 5, - 5, - 0, - base::TimeDelta(), - ui::GestureEventDetails(ui::ET_GESTURE_LONG_PRESS)); - ui::EventDispatchDetails details = root_view->OnEventFromSource(&long_press1); - - ui::GestureEvent end1( - 5, 5, 0, base::TimeDelta(), ui::GestureEventDetails(ui::ET_GESTURE_END)); - details = root_view->OnEventFromSource(&end1); - - EXPECT_FALSE(details.target_destroyed); - EXPECT_FALSE(details.dispatcher_destroyed); - EXPECT_EQ(0, controller.show_context_menu_calls()); - controller.Reset(); - - // |parent_view| should not show a context menu as a result of a long press on - // |other_child_view|. - ui::GestureEvent long_press2( - 25, - 5, - 0, - base::TimeDelta(), - ui::GestureEventDetails(ui::ET_GESTURE_LONG_PRESS)); - details = root_view->OnEventFromSource(&long_press2); - - ui::GestureEvent end2( - 25, 5, 0, base::TimeDelta(), ui::GestureEventDetails(ui::ET_GESTURE_END)); - details = root_view->OnEventFromSource(&end2); - - EXPECT_FALSE(details.target_destroyed); - EXPECT_FALSE(details.dispatcher_destroyed); - EXPECT_EQ(0, controller.show_context_menu_calls()); - controller.Reset(); - - // |parent_view| should not show a context menu as a result of a long press on - // itself. - ui::GestureEvent long_press3( - 50, - 50, - 0, - base::TimeDelta(), - ui::GestureEventDetails(ui::ET_GESTURE_LONG_PRESS)); - details = root_view->OnEventFromSource(&long_press3); - - ui::GestureEvent end3( - 25, 5, 0, base::TimeDelta(), ui::GestureEventDetails(ui::ET_GESTURE_END)); - details = root_view->OnEventFromSource(&end3); - - EXPECT_FALSE(details.target_destroyed); - EXPECT_FALSE(details.dispatcher_destroyed); - EXPECT_EQ(0, controller.show_context_menu_calls()); -} - -} // namespace test -} // namespace views
diff --git a/ui/views/widget/tooltip_manager.cc b/ui/views/widget/tooltip_manager.cc deleted file mode 100644 index 00bd036..0000000 --- a/ui/views/widget/tooltip_manager.cc +++ /dev/null
@@ -1,36 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/widget/tooltip_manager.h" - -#include "ui/gfx/rect.h" -#include "ui/gfx/screen.h" -#include "ui/gfx/text_elider.h" - -namespace views { - -const size_t kMaxTooltipLength = 1024; - -// static -const char TooltipManager::kGroupingPropertyKey[] = "GroupingPropertyKey"; - -// static -int TooltipManager::GetMaxWidth(int x, int y, gfx::NativeView context) { - return GetMaxWidth(gfx::Screen::GetScreenFor(context)->GetDisplayNearestPoint( - gfx::Point(x, y))); -} - -// static -int TooltipManager::GetMaxWidth(const gfx::Display& display) { - return (display.bounds().width() + 1) / 2; -} - -// static -void TooltipManager::TrimTooltipText(base::string16* text) { - // Clamp the tooltip length to kMaxTooltipLength so that we don't - // accidentally DOS the user with a mega tooltip. - *text = gfx::TruncateString(*text, kMaxTooltipLength, gfx::WORD_BREAK); -} - -} // namespace views
diff --git a/ui/views/widget/tooltip_manager.h b/ui/views/widget/tooltip_manager.h deleted file mode 100644 index 923b19d..0000000 --- a/ui/views/widget/tooltip_manager.h +++ /dev/null
@@ -1,69 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_WIDGET_TOOLTIP_MANAGER_H_ -#define UI_VIEWS_WIDGET_TOOLTIP_MANAGER_H_ - -#include <string> - -#include "base/basictypes.h" -#include "base/strings/string16.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/views/views_export.h" - -namespace gfx { -class Display; -class FontList; -} // namespace gfx - -namespace views { - -class View; - -// TooltipManager takes care of the wiring to support tooltips for Views. You -// almost never need to interact directly with TooltipManager, rather look to -// the various tooltip methods on View. -class VIEWS_EXPORT TooltipManager { - public: - // When a NativeView has capture all events are delivered to it. In some - // situations, such as menus, we want the tooltip to be shown for the - // NativeView the mouse is over, even if it differs from the NativeView that - // has capture (with menus the first menu shown has capture). To enable this - // if the NativeView that has capture has the same value for the property - // |kGroupingPropertyKey| as the NativeView the mouse is over the tooltip is - // shown. - static const char kGroupingPropertyKey[]; - - TooltipManager() {} - virtual ~TooltipManager() {} - - // Returns the height of tooltips. This should only be invoked from within - // GetTooltipTextOrigin. - static int GetTooltipHeight(); - - // Returns the maximum width of the tooltip. |x| and |y| give the location - // the tooltip is to be displayed on in screen coordinates. |context| is - // used to determine which gfx::Screen should be used. - static int GetMaxWidth(int x, int y, gfx::NativeView context); - - // Same as GetMaxWidth(), but takes a Display. - static int GetMaxWidth(const gfx::Display& display); - - // If necessary trims the text of a tooltip to ensure we don't try to display - // a mega-tooltip. - static void TrimTooltipText(base::string16* text); - - // Returns the font list used for tooltips. - virtual const gfx::FontList& GetFontList() const = 0; - - // Notification that the view hierarchy has changed in some way. - virtual void UpdateTooltip() = 0; - - // Invoked when the tooltip text changes for the specified views. - virtual void TooltipTextChanged(View* view) = 0; -}; - -} // namespace views - -#endif // UI_VIEWS_WIDGET_TOOLTIP_MANAGER_H_
diff --git a/ui/views/widget/tooltip_manager_aura.cc b/ui/views/widget/tooltip_manager_aura.cc deleted file mode 100644 index 99ae9e6..0000000 --- a/ui/views/widget/tooltip_manager_aura.cc +++ /dev/null
@@ -1,146 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/widget/tooltip_manager_aura.h" - -#include "base/logging.h" -#include "ui/aura/client/screen_position_client.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/aura/window_tree_host.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/gfx/rect.h" -#include "ui/gfx/screen.h" -#include "ui/views/widget/widget.h" -#include "ui/wm/public/tooltip_client.h" - -namespace views { - -// static -int TooltipManager::GetTooltipHeight() { - // Not used for linux and chromeos. - NOTIMPLEMENTED(); - return 0; -} - -//////////////////////////////////////////////////////////////////////////////// -// TooltipManagerAura public: - -TooltipManagerAura::TooltipManagerAura(Widget* widget) : widget_(widget) { - aura::client::SetTooltipText(GetWindow(), &tooltip_text_); -} - -TooltipManagerAura::~TooltipManagerAura() { - aura::client::SetTooltipText(GetWindow(), NULL); -} - -// static -const gfx::FontList& TooltipManagerAura::GetDefaultFontList() { - return ui::ResourceBundle::GetSharedInstance().GetFontList( - ui::ResourceBundle::BaseFont); -} - -// static -void TooltipManagerAura::UpdateTooltipManagerForCapture(Widget* source) { - if (!source->HasCapture()) - return; - - aura::Window* root_window = source->GetNativeView()->GetRootWindow(); - if (!root_window) - return; - - gfx::Point screen_loc( - root_window->GetHost()->dispatcher()->GetLastMouseLocationInRoot()); - aura::client::ScreenPositionClient* screen_position_client = - aura::client::GetScreenPositionClient(root_window); - if (!screen_position_client) - return; - screen_position_client->ConvertPointToScreen(root_window, &screen_loc); - gfx::Screen* screen = gfx::Screen::GetScreenFor(root_window); - aura::Window* target = screen->GetWindowAtScreenPoint(screen_loc); - if (!target) - return; - gfx::Point target_loc(screen_loc); - screen_position_client = - aura::client::GetScreenPositionClient(target->GetRootWindow()); - if (!screen_position_client) - return; - screen_position_client->ConvertPointFromScreen(target, &target_loc); - target = target->GetEventHandlerForPoint(target_loc); - while (target) { - Widget* target_widget = Widget::GetWidgetForNativeView(target); - if (target_widget == source) - return; - - if (target_widget) { - if (target_widget->GetTooltipManager()) - target_widget->GetTooltipManager()->UpdateTooltip(); - return; - } - target = target->parent(); - } -} - -//////////////////////////////////////////////////////////////////////////////// -// TooltipManagerAura, TooltipManager implementation: - -const gfx::FontList& TooltipManagerAura::GetFontList() const { - return GetDefaultFontList(); -} - -void TooltipManagerAura::UpdateTooltip() { - aura::Window* root_window = GetWindow()->GetRootWindow(); - if (aura::client::GetTooltipClient(root_window)) { - gfx::Point view_point = - root_window->GetHost()->dispatcher()->GetLastMouseLocationInRoot(); - aura::Window::ConvertPointToTarget(root_window, GetWindow(), &view_point); - View* view = GetViewUnderPoint(view_point); - UpdateTooltipForTarget(view, view_point, root_window); - } -} - -void TooltipManagerAura::TooltipTextChanged(View* view) { - aura::Window* root_window = GetWindow()->GetRootWindow(); - if (aura::client::GetTooltipClient(root_window)) { - gfx::Point view_point = - root_window->GetHost()->dispatcher()->GetLastMouseLocationInRoot(); - aura::Window::ConvertPointToTarget(root_window, GetWindow(), &view_point); - View* target = GetViewUnderPoint(view_point); - if (target != view) - return; - UpdateTooltipForTarget(view, view_point, root_window); - } -} - -View* TooltipManagerAura::GetViewUnderPoint(const gfx::Point& point) { - View* root_view = widget_->GetRootView(); - if (root_view) - return root_view->GetTooltipHandlerForPoint(point); - return NULL; -} - -void TooltipManagerAura::UpdateTooltipForTarget(View* target, - const gfx::Point& point, - aura::Window* root_window) { - if (target) { - gfx::Point view_point = point; - View::ConvertPointFromWidget(target, &view_point); - base::string16 new_tooltip_text; - if (!target->GetTooltipText(view_point, &new_tooltip_text)) - tooltip_text_.clear(); - else - tooltip_text_ = new_tooltip_text; - } else { - tooltip_text_.clear(); - } - - aura::client::SetTooltipId(GetWindow(), target); - - aura::client::GetTooltipClient(root_window)->UpdateTooltip(GetWindow()); -} - -aura::Window* TooltipManagerAura::GetWindow() { - return widget_->GetNativeView(); -} - -} // namespace views.
diff --git a/ui/views/widget/tooltip_manager_aura.h b/ui/views/widget/tooltip_manager_aura.h deleted file mode 100644 index 73266a1..0000000 --- a/ui/views/widget/tooltip_manager_aura.h +++ /dev/null
@@ -1,62 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_WIDGET_TOOLTIP_MANAGER_AURA_H_ -#define UI_VIEWS_WIDGET_TOOLTIP_MANAGER_AURA_H_ - -#include "base/compiler_specific.h" -#include "base/strings/string16.h" -#include "ui/gfx/point.h" -#include "ui/views/widget/tooltip_manager.h" - -namespace aura { -class Window; -} - -namespace gfx { -class FontList; -} - -namespace views { - -class Widget; - -// TooltipManager implementation for Aura. -class TooltipManagerAura : public TooltipManager { - public: - explicit TooltipManagerAura(Widget* widget); - virtual ~TooltipManagerAura(); - - // If |source| has capture this finds the Widget under the mouse and invokes - // UpdateTooltip() on it's TooltipManager. This is necessary as when capture - // is held mouse events are only delivered to the Window that has capture even - // though we may show tooltips for the Window under the mouse. - static void UpdateTooltipManagerForCapture(Widget* source); - - // Returns the FontList used by all TooltipManagerAuras. - static const gfx::FontList& GetDefaultFontList(); - - // TooltipManager: - virtual const gfx::FontList& GetFontList() const override; - virtual void UpdateTooltip() override; - virtual void TooltipTextChanged(View* view) override; - - private: - View* GetViewUnderPoint(const gfx::Point& point); - void UpdateTooltipForTarget(View* target, - const gfx::Point& point, - aura::Window* root_window); - - // Returns the Window the tooltip text is installed on. - aura::Window* GetWindow(); - - Widget* widget_; - base::string16 tooltip_text_; - - DISALLOW_COPY_AND_ASSIGN(TooltipManagerAura); -}; - -} // namespace views - -#endif // UI_VIEWS_WIDGET_TOOLTIP_MANAGER_AURA_H_
diff --git a/ui/views/widget/widget.cc b/ui/views/widget/widget.cc deleted file mode 100644 index 8469f6d..0000000 --- a/ui/views/widget/widget.cc +++ /dev/null
@@ -1,1519 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/widget/widget.h" - -#include "base/debug/trace_event.h" -#include "base/logging.h" -#include "base/message_loop/message_loop.h" -#include "base/strings/utf_string_conversions.h" -#include "ui/base/cursor/cursor.h" -#include "ui/base/default_theme_provider.h" -#include "ui/base/hit_test.h" -#include "ui/base/l10n/l10n_font_util.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/compositor/compositor.h" -#include "ui/compositor/layer.h" -#include "ui/events/event.h" -#include "ui/gfx/image/image_skia.h" -#include "ui/gfx/screen.h" -#include "ui/views/controls/menu/menu_controller.h" -#include "ui/views/focus/focus_manager.h" -#include "ui/views/focus/focus_manager_factory.h" -#include "ui/views/focus/view_storage.h" -#include "ui/views/focus/widget_focus_manager.h" -#include "ui/views/ime/input_method.h" -#include "ui/views/views_delegate.h" -#include "ui/views/widget/native_widget_private.h" -#include "ui/views/widget/root_view.h" -#include "ui/views/widget/tooltip_manager.h" -#include "ui/views/widget/widget_delegate.h" -#include "ui/views/widget/widget_deletion_observer.h" -#include "ui/views/widget/widget_observer.h" -#include "ui/views/widget/widget_removals_observer.h" -#include "ui/views/window/custom_frame_view.h" -#include "ui/views/window/dialog_delegate.h" - -namespace views { - -namespace { - -// If |view| has a layer the layer is added to |layers|. Else this recurses -// through the children. This is used to build a list of the layers created by -// views that are direct children of the Widgets layer. -void BuildRootLayers(View* view, std::vector<ui::Layer*>* layers) { - if (view->layer()) { - layers->push_back(view->layer()); - } else { - for (int i = 0; i < view->child_count(); ++i) - BuildRootLayers(view->child_at(i), layers); - } -} - -// Create a native widget implementation. -// First, use the supplied one if non-NULL. -// Finally, make a default one. -NativeWidget* CreateNativeWidget(NativeWidget* native_widget, - internal::NativeWidgetDelegate* delegate) { - if (!native_widget) { - native_widget = - internal::NativeWidgetPrivate::CreateNativeWidget(delegate); - } - return native_widget; -} - -} // namespace - -// A default implementation of WidgetDelegate, used by Widget when no -// WidgetDelegate is supplied. -class DefaultWidgetDelegate : public WidgetDelegate { - public: - explicit DefaultWidgetDelegate(Widget* widget) : widget_(widget) { - } - virtual ~DefaultWidgetDelegate() {} - - // Overridden from WidgetDelegate: - virtual void DeleteDelegate() override { - delete this; - } - virtual Widget* GetWidget() override { - return widget_; - } - virtual const Widget* GetWidget() const override { - return widget_; - } - virtual bool ShouldAdvanceFocusToTopLevelWidget() const override { - // In most situations where a Widget is used without a delegate the Widget - // is used as a container, so that we want focus to advance to the top-level - // widget. A good example of this is the find bar. - return true; - } - - private: - Widget* widget_; - - DISALLOW_COPY_AND_ASSIGN(DefaultWidgetDelegate); -}; - -//////////////////////////////////////////////////////////////////////////////// -// Widget, InitParams: - -Widget::InitParams::InitParams() - : type(TYPE_WINDOW), - delegate(NULL), - child(false), - opacity(INFER_OPACITY), - accept_events(true), - activatable(ACTIVATABLE_DEFAULT), - keep_on_top(false), - visible_on_all_workspaces(false), - ownership(NATIVE_WIDGET_OWNS_WIDGET), - mirror_origin_in_rtl(false), - shadow_type(SHADOW_TYPE_DEFAULT), - remove_standard_frame(false), - use_system_default_icon(false), - show_state(ui::SHOW_STATE_DEFAULT), - double_buffer(false), - parent(NULL), - native_widget(NULL), - desktop_window_tree_host(NULL), - layer_type(aura::WINDOW_LAYER_TEXTURED), - context(NULL), - force_show_in_taskbar(false) { -} - -Widget::InitParams::InitParams(Type type) - : type(type), - delegate(NULL), - child(false), - opacity(INFER_OPACITY), - accept_events(true), - activatable(ACTIVATABLE_DEFAULT), - keep_on_top(type == TYPE_MENU || type == TYPE_DRAG), - visible_on_all_workspaces(false), - ownership(NATIVE_WIDGET_OWNS_WIDGET), - mirror_origin_in_rtl(false), - shadow_type(SHADOW_TYPE_DEFAULT), - remove_standard_frame(false), - use_system_default_icon(false), - show_state(ui::SHOW_STATE_DEFAULT), - double_buffer(false), - parent(NULL), - native_widget(NULL), - desktop_window_tree_host(NULL), - layer_type(aura::WINDOW_LAYER_TEXTURED), - context(NULL), - force_show_in_taskbar(false) { -} - -Widget::InitParams::~InitParams() { -} - -//////////////////////////////////////////////////////////////////////////////// -// Widget, public: - -Widget::Widget() - : native_widget_(NULL), - widget_delegate_(NULL), - non_client_view_(NULL), - dragged_view_(NULL), - ownership_(InitParams::NATIVE_WIDGET_OWNS_WIDGET), - is_secondary_widget_(true), - frame_type_(FRAME_TYPE_DEFAULT), - disable_inactive_rendering_(false), - widget_closed_(false), - saved_show_state_(ui::SHOW_STATE_DEFAULT), - focus_on_creation_(true), - is_top_level_(false), - native_widget_initialized_(false), - native_widget_destroyed_(false), - ignore_capture_loss_(false), - last_mouse_event_was_move_(false), - auto_release_capture_(true), - root_layers_dirty_(false), - movement_disabled_(false), - observer_manager_(this) { -} - -Widget::~Widget() { - DestroyRootView(); - if (ownership_ == InitParams::WIDGET_OWNS_NATIVE_WIDGET) { - delete native_widget_; - } else { - DCHECK(native_widget_destroyed_) - << "Destroying a widget with a live native widget. " - << "Widget probably should use WIDGET_OWNS_NATIVE_WIDGET ownership."; - } -} - -// static -Widget* Widget::CreateWindow(WidgetDelegate* delegate) { - return CreateWindowWithBounds(delegate, gfx::Rect()); -} - -// static -Widget* Widget::CreateWindowWithBounds(WidgetDelegate* delegate, - const gfx::Rect& bounds) { - Widget* widget = new Widget; - Widget::InitParams params; - params.bounds = bounds; - params.delegate = delegate; - widget->Init(params); - return widget; -} - -// static -Widget* Widget::CreateWindowWithParent(WidgetDelegate* delegate, - gfx::NativeView parent) { - return CreateWindowWithParentAndBounds(delegate, parent, gfx::Rect()); -} - -// static -Widget* Widget::CreateWindowWithParentAndBounds(WidgetDelegate* delegate, - gfx::NativeView parent, - const gfx::Rect& bounds) { - Widget* widget = new Widget; - Widget::InitParams params; - params.delegate = delegate; - params.parent = parent; - params.bounds = bounds; - widget->Init(params); - return widget; -} - -// static -Widget* Widget::CreateWindowWithContext(WidgetDelegate* delegate, - gfx::NativeWindow context) { - return CreateWindowWithContextAndBounds(delegate, context, gfx::Rect()); -} - -// static -Widget* Widget::CreateWindowWithContextAndBounds(WidgetDelegate* delegate, - gfx::NativeWindow context, - const gfx::Rect& bounds) { - Widget* widget = new Widget; - Widget::InitParams params; - params.delegate = delegate; - params.context = context; - params.bounds = bounds; - widget->Init(params); - return widget; -} - -// static -Widget* Widget::GetWidgetForNativeView(gfx::NativeView native_view) { - internal::NativeWidgetPrivate* native_widget = - internal::NativeWidgetPrivate::GetNativeWidgetForNativeView(native_view); - return native_widget ? native_widget->GetWidget() : NULL; -} - -// static -Widget* Widget::GetWidgetForNativeWindow(gfx::NativeWindow native_window) { - internal::NativeWidgetPrivate* native_widget = - internal::NativeWidgetPrivate::GetNativeWidgetForNativeWindow( - native_window); - return native_widget ? native_widget->GetWidget() : NULL; -} - -// static -Widget* Widget::GetTopLevelWidgetForNativeView(gfx::NativeView native_view) { - internal::NativeWidgetPrivate* native_widget = - internal::NativeWidgetPrivate::GetTopLevelNativeWidget(native_view); - return native_widget ? native_widget->GetWidget() : NULL; -} - - -// static -void Widget::GetAllChildWidgets(gfx::NativeView native_view, - Widgets* children) { - internal::NativeWidgetPrivate::GetAllChildWidgets(native_view, children); -} - -// static -void Widget::GetAllOwnedWidgets(gfx::NativeView native_view, - Widgets* owned) { - internal::NativeWidgetPrivate::GetAllOwnedWidgets(native_view, owned); -} - -// static -void Widget::ReparentNativeView(gfx::NativeView native_view, - gfx::NativeView new_parent) { - internal::NativeWidgetPrivate::ReparentNativeView(native_view, new_parent); -} - -// static -int Widget::GetLocalizedContentsWidth(int col_resource_id) { - return ui::GetLocalizedContentsWidthForFont(col_resource_id, - ResourceBundle::GetSharedInstance().GetFont(ResourceBundle::BaseFont)); -} - -// static -int Widget::GetLocalizedContentsHeight(int row_resource_id) { - return ui::GetLocalizedContentsHeightForFont(row_resource_id, - ResourceBundle::GetSharedInstance().GetFont(ResourceBundle::BaseFont)); -} - -// static -gfx::Size Widget::GetLocalizedContentsSize(int col_resource_id, - int row_resource_id) { - return gfx::Size(GetLocalizedContentsWidth(col_resource_id), - GetLocalizedContentsHeight(row_resource_id)); -} - -// static -bool Widget::RequiresNonClientView(InitParams::Type type) { - return type == InitParams::TYPE_WINDOW || - type == InitParams::TYPE_PANEL || - type == InitParams::TYPE_BUBBLE; -} - -void Widget::Init(const InitParams& in_params) { - TRACE_EVENT0("views", "Widget::Init"); - InitParams params = in_params; - - params.child |= (params.type == InitParams::TYPE_CONTROL); - is_top_level_ = !params.child; - - if (params.opacity == views::Widget::InitParams::INFER_OPACITY && - params.type != views::Widget::InitParams::TYPE_WINDOW && - params.type != views::Widget::InitParams::TYPE_PANEL) - params.opacity = views::Widget::InitParams::OPAQUE_WINDOW; - - if (ViewsDelegate::views_delegate) - ViewsDelegate::views_delegate->OnBeforeWidgetInit(¶ms, this); - - if (params.opacity == views::Widget::InitParams::INFER_OPACITY) - params.opacity = views::Widget::InitParams::OPAQUE_WINDOW; - - bool can_activate = false; - if (params.activatable != InitParams::ACTIVATABLE_DEFAULT) { - can_activate = (params.activatable == InitParams::ACTIVATABLE_YES); - } else if (params.type != InitParams::TYPE_CONTROL && - params.type != InitParams::TYPE_POPUP && - params.type != InitParams::TYPE_MENU && - params.type != InitParams::TYPE_TOOLTIP && - params.type != InitParams::TYPE_DRAG) { - can_activate = true; - params.activatable = InitParams::ACTIVATABLE_YES; - } else { - can_activate = false; - params.activatable = InitParams::ACTIVATABLE_NO; - } - - widget_delegate_ = params.delegate ? - params.delegate : new DefaultWidgetDelegate(this); - widget_delegate_->set_can_activate(can_activate); - - ownership_ = params.ownership; - native_widget_ = CreateNativeWidget(params.native_widget, this)-> - AsNativeWidgetPrivate(); - root_view_.reset(CreateRootView()); - default_theme_provider_.reset(new ui::DefaultThemeProvider); - native_widget_->InitNativeWidget(params); - if (RequiresNonClientView(params.type)) { - non_client_view_ = new NonClientView; - non_client_view_->SetFrameView(CreateNonClientFrameView()); - // Create the ClientView, add it to the NonClientView and add the - // NonClientView to the RootView. This will cause everything to be parented. - non_client_view_->set_client_view(widget_delegate_->CreateClientView(this)); - non_client_view_->SetOverlayView(widget_delegate_->CreateOverlayView()); - SetContentsView(non_client_view_); - // Initialize the window's title before setting the window's initial bounds; - // the frame view's preferred height may depend on the presence of a title. - UpdateWindowTitle(); - non_client_view_->ResetWindowControls(); - SetInitialBounds(params.bounds); - if (params.show_state == ui::SHOW_STATE_MAXIMIZED) - Maximize(); - else if (params.show_state == ui::SHOW_STATE_MINIMIZED) - Minimize(); - } else if (params.delegate) { - SetContentsView(params.delegate->GetContentsView()); - SetInitialBoundsForFramelessWindow(params.bounds); - } - // This must come after SetContentsView() or it might not be able to find - // the correct NativeTheme (on Linux). See http://crbug.com/384492 - observer_manager_.Add(GetNativeTheme()); - native_widget_initialized_ = true; -} - -// Unconverted methods (see header) -------------------------------------------- - -gfx::NativeView Widget::GetNativeView() const { - return native_widget_->GetNativeView(); -} - -gfx::NativeWindow Widget::GetNativeWindow() const { - return native_widget_->GetNativeWindow(); -} - -void Widget::AddObserver(WidgetObserver* observer) { - observers_.AddObserver(observer); -} - -void Widget::RemoveObserver(WidgetObserver* observer) { - observers_.RemoveObserver(observer); -} - -bool Widget::HasObserver(WidgetObserver* observer) { - return observers_.HasObserver(observer); -} - -void Widget::AddRemovalsObserver(WidgetRemovalsObserver* observer) { - removals_observers_.AddObserver(observer); -} - -void Widget::RemoveRemovalsObserver(WidgetRemovalsObserver* observer) { - removals_observers_.RemoveObserver(observer); -} - -bool Widget::HasRemovalsObserver(WidgetRemovalsObserver* observer) { - return removals_observers_.HasObserver(observer); -} - -bool Widget::GetAccelerator(int cmd_id, ui::Accelerator* accelerator) const { - return false; -} - -void Widget::ViewHierarchyChanged( - const View::ViewHierarchyChangedDetails& details) { - if (!details.is_add) { - if (details.child == dragged_view_) - dragged_view_ = NULL; - FocusManager* focus_manager = GetFocusManager(); - if (focus_manager) - focus_manager->ViewRemoved(details.child); - ViewStorage::GetInstance()->ViewRemoved(details.child); - native_widget_->ViewRemoved(details.child); - } -} - -void Widget::NotifyNativeViewHierarchyWillChange() { - FocusManager* focus_manager = GetFocusManager(); - // We are being removed from a window hierarchy. Treat this as - // the root_view_ being removed. - if (focus_manager) - focus_manager->ViewRemoved(root_view_.get()); -} - -void Widget::NotifyNativeViewHierarchyChanged() { - root_view_->NotifyNativeViewHierarchyChanged(); -} - -void Widget::NotifyWillRemoveView(View* view) { - FOR_EACH_OBSERVER(WidgetRemovalsObserver, - removals_observers_, - OnWillRemoveView(this, view)); -} - -// Converted methods (see header) ---------------------------------------------- - -Widget* Widget::GetTopLevelWidget() { - return const_cast<Widget*>( - static_cast<const Widget*>(this)->GetTopLevelWidget()); -} - -const Widget* Widget::GetTopLevelWidget() const { - // GetTopLevelNativeWidget doesn't work during destruction because - // property is gone after gobject gets deleted. Short circuit here - // for toplevel so that InputMethod can remove itself from - // focus manager. - return is_top_level() ? this : native_widget_->GetTopLevelWidget(); -} - -void Widget::SetContentsView(View* view) { - // Do not SetContentsView() again if it is already set to the same view. - if (view == GetContentsView()) - return; - root_view_->SetContentsView(view); - if (non_client_view_ != view) { - // |non_client_view_| can only be non-NULL here if RequiresNonClientView() - // was true when the widget was initialized. Creating widgets with non - // client views and then setting the contents view can cause subtle - // problems on Windows, where the native widget thinks there is still a - // |non_client_view_|. If you get this error, either use a different type - // when initializing the widget, or don't call SetContentsView(). - DCHECK(!non_client_view_); - non_client_view_ = NULL; - } -} - -View* Widget::GetContentsView() { - return root_view_->GetContentsView(); -} - -gfx::Rect Widget::GetWindowBoundsInScreen() const { - return native_widget_->GetWindowBoundsInScreen(); -} - -gfx::Rect Widget::GetClientAreaBoundsInScreen() const { - return native_widget_->GetClientAreaBoundsInScreen(); -} - -gfx::Rect Widget::GetRestoredBounds() const { - return native_widget_->GetRestoredBounds(); -} - -void Widget::SetBounds(const gfx::Rect& bounds) { - native_widget_->SetBounds(bounds); -} - -void Widget::SetSize(const gfx::Size& size) { - native_widget_->SetSize(size); -} - -void Widget::CenterWindow(const gfx::Size& size) { - native_widget_->CenterWindow(size); -} - -void Widget::SetBoundsConstrained(const gfx::Rect& bounds) { - gfx::Rect work_area = - gfx::Screen::GetScreenFor(GetNativeView())->GetDisplayNearestPoint( - bounds.origin()).work_area(); - if (work_area.IsEmpty()) { - SetBounds(bounds); - } else { - // Inset the work area slightly. - work_area.Inset(10, 10, 10, 10); - work_area.AdjustToFit(bounds); - SetBounds(work_area); - } -} - -void Widget::SetVisibilityChangedAnimationsEnabled(bool value) { - native_widget_->SetVisibilityChangedAnimationsEnabled(value); -} - -Widget::MoveLoopResult Widget::RunMoveLoop( - const gfx::Vector2d& drag_offset, - MoveLoopSource source, - MoveLoopEscapeBehavior escape_behavior) { - return native_widget_->RunMoveLoop(drag_offset, source, escape_behavior); -} - -void Widget::EndMoveLoop() { - native_widget_->EndMoveLoop(); -} - -void Widget::StackAboveWidget(Widget* widget) { - native_widget_->StackAbove(widget->GetNativeView()); -} - -void Widget::StackAbove(gfx::NativeView native_view) { - native_widget_->StackAbove(native_view); -} - -void Widget::StackAtTop() { - native_widget_->StackAtTop(); -} - -void Widget::StackBelow(gfx::NativeView native_view) { - native_widget_->StackBelow(native_view); -} - -void Widget::SetShape(gfx::NativeRegion shape) { - native_widget_->SetShape(shape); -} - -void Widget::Close() { - if (widget_closed_) { - // It appears we can hit this code path if you close a modal dialog then - // close the last browser before the destructor is hit, which triggers - // invoking Close again. - return; - } - - bool can_close = true; - if (non_client_view_) - can_close = non_client_view_->CanClose(); - if (can_close) { - SaveWindowPlacement(); - - // During tear-down the top-level focus manager becomes unavailable to - // GTK tabbed panes and their children, so normal deregistration via - // |FormManager::ViewRemoved()| calls are fouled. We clear focus here - // to avoid these redundant steps and to avoid accessing deleted views - // that may have been in focus. - if (is_top_level() && focus_manager_.get()) - focus_manager_->SetFocusedView(NULL); - - FOR_EACH_OBSERVER(WidgetObserver, observers_, OnWidgetClosing(this)); - native_widget_->Close(); - widget_closed_ = true; - } -} - -void Widget::CloseNow() { - FOR_EACH_OBSERVER(WidgetObserver, observers_, OnWidgetClosing(this)); - native_widget_->CloseNow(); -} - -bool Widget::IsClosed() const { - return widget_closed_; -} - -void Widget::Show() { - TRACE_EVENT0("views", "Widget::Show"); - if (non_client_view_) { - // While initializing, the kiosk mode will go to full screen before the - // widget gets shown. In that case we stay in full screen mode, regardless - // of the |saved_show_state_| member. - if (saved_show_state_ == ui::SHOW_STATE_MAXIMIZED && - !initial_restored_bounds_.IsEmpty() && - !IsFullscreen()) { - native_widget_->ShowMaximizedWithBounds(initial_restored_bounds_); - } else { - native_widget_->ShowWithWindowState( - IsFullscreen() ? ui::SHOW_STATE_FULLSCREEN : saved_show_state_); - } - // |saved_show_state_| only applies the first time the window is shown. - // If we don't reset the value the window may be shown maximized every time - // it is subsequently shown after being hidden. - saved_show_state_ = ui::SHOW_STATE_NORMAL; - } else { - CanActivate() - ? native_widget_->Show() - : native_widget_->ShowWithWindowState(ui::SHOW_STATE_INACTIVE); - } -} - -void Widget::Hide() { - native_widget_->Hide(); -} - -void Widget::ShowInactive() { - // If this gets called with saved_show_state_ == ui::SHOW_STATE_MAXIMIZED, - // call SetBounds()with the restored bounds to set the correct size. This - // normally should not happen, but if it does we should avoid showing unsized - // windows. - if (saved_show_state_ == ui::SHOW_STATE_MAXIMIZED && - !initial_restored_bounds_.IsEmpty()) { - SetBounds(initial_restored_bounds_); - saved_show_state_ = ui::SHOW_STATE_NORMAL; - } - native_widget_->ShowWithWindowState(ui::SHOW_STATE_INACTIVE); -} - -void Widget::Activate() { - native_widget_->Activate(); -} - -void Widget::Deactivate() { - native_widget_->Deactivate(); -} - -bool Widget::IsActive() const { - return native_widget_->IsActive(); -} - -void Widget::DisableInactiveRendering() { - SetInactiveRenderingDisabled(true); -} - -void Widget::SetAlwaysOnTop(bool on_top) { - native_widget_->SetAlwaysOnTop(on_top); -} - -bool Widget::IsAlwaysOnTop() const { - return native_widget_->IsAlwaysOnTop(); -} - -void Widget::SetVisibleOnAllWorkspaces(bool always_visible) { - native_widget_->SetVisibleOnAllWorkspaces(always_visible); -} - -void Widget::Maximize() { - native_widget_->Maximize(); -} - -void Widget::Minimize() { - native_widget_->Minimize(); -} - -void Widget::Restore() { - native_widget_->Restore(); -} - -bool Widget::IsMaximized() const { - return native_widget_->IsMaximized(); -} - -bool Widget::IsMinimized() const { - return native_widget_->IsMinimized(); -} - -void Widget::SetFullscreen(bool fullscreen) { - if (IsFullscreen() == fullscreen) - return; - - native_widget_->SetFullscreen(fullscreen); - - if (non_client_view_) - non_client_view_->Layout(); -} - -bool Widget::IsFullscreen() const { - return native_widget_->IsFullscreen(); -} - -void Widget::SetOpacity(unsigned char opacity) { - native_widget_->SetOpacity(opacity); -} - -void Widget::SetUseDragFrame(bool use_drag_frame) { - native_widget_->SetUseDragFrame(use_drag_frame); -} - -void Widget::FlashFrame(bool flash) { - native_widget_->FlashFrame(flash); -} - -View* Widget::GetRootView() { - return root_view_.get(); -} - -const View* Widget::GetRootView() const { - return root_view_.get(); -} - -bool Widget::IsVisible() const { - return native_widget_->IsVisible(); -} - -ui::ThemeProvider* Widget::GetThemeProvider() const { - const Widget* root_widget = GetTopLevelWidget(); - if (root_widget && root_widget != this) { - // Attempt to get the theme provider, and fall back to the default theme - // provider if not found. - ui::ThemeProvider* provider = root_widget->GetThemeProvider(); - if (provider) - return provider; - - provider = root_widget->default_theme_provider_.get(); - if (provider) - return provider; - } - return default_theme_provider_.get(); -} - -const ui::NativeTheme* Widget::GetNativeTheme() const { - return native_widget_->GetNativeTheme(); -} - -FocusManager* Widget::GetFocusManager() { - Widget* toplevel_widget = GetTopLevelWidget(); - return toplevel_widget ? toplevel_widget->focus_manager_.get() : NULL; -} - -const FocusManager* Widget::GetFocusManager() const { - const Widget* toplevel_widget = GetTopLevelWidget(); - return toplevel_widget ? toplevel_widget->focus_manager_.get() : NULL; -} - -InputMethod* Widget::GetInputMethod() { - return const_cast<InputMethod*>( - const_cast<const Widget*>(this)->GetInputMethod()); -} - -const InputMethod* Widget::GetInputMethod() const { - if (is_top_level()) { - if (!input_method_.get()) - input_method_ = const_cast<Widget*>(this)->CreateInputMethod().Pass(); - return input_method_.get(); - } else { - const Widget* toplevel = GetTopLevelWidget(); - // If GetTopLevelWidget() returns itself which is not toplevel, - // the widget is detached from toplevel widget. - // TODO(oshima): Fix GetTopLevelWidget() to return NULL - // if there is no toplevel. We probably need to add GetTopMostWidget() - // to replace some use cases. - return (toplevel && toplevel != this) ? toplevel->GetInputMethod() : NULL; - } -} - -ui::InputMethod* Widget::GetHostInputMethod() { - return native_widget_private()->GetHostInputMethod(); -} - -void Widget::RunShellDrag(View* view, - const ui::OSExchangeData& data, - const gfx::Point& location, - int operation, - ui::DragDropTypes::DragEventSource source) { - dragged_view_ = view; - OnDragWillStart(); - native_widget_->RunShellDrag(view, data, location, operation, source); - // If the view is removed during the drag operation, dragged_view_ is set to - // NULL. - if (view && dragged_view_ == view) { - dragged_view_ = NULL; - view->OnDragDone(); - } - OnDragComplete(); -} - -void Widget::SchedulePaintInRect(const gfx::Rect& rect) { - native_widget_->SchedulePaintInRect(rect); -} - -void Widget::SetCursor(gfx::NativeCursor cursor) { - native_widget_->SetCursor(cursor); -} - -bool Widget::IsMouseEventsEnabled() const { - return native_widget_->IsMouseEventsEnabled(); -} - -void Widget::SetNativeWindowProperty(const char* name, void* value) { - native_widget_->SetNativeWindowProperty(name, value); -} - -void* Widget::GetNativeWindowProperty(const char* name) const { - return native_widget_->GetNativeWindowProperty(name); -} - -void Widget::UpdateWindowTitle() { - if (!non_client_view_) - return; - - // Update the native frame's text. We do this regardless of whether or not - // the native frame is being used, since this also updates the taskbar, etc. - base::string16 window_title = widget_delegate_->GetWindowTitle(); - base::i18n::AdjustStringForLocaleDirection(&window_title); - if (!native_widget_->SetWindowTitle(window_title)) - return; - non_client_view_->UpdateWindowTitle(); - - // If the non-client view is rendering its own title, it'll need to relayout - // now and to get a paint update later on. - non_client_view_->Layout(); -} - -void Widget::UpdateWindowIcon() { - if (non_client_view_) - non_client_view_->UpdateWindowIcon(); - native_widget_->SetWindowIcons(widget_delegate_->GetWindowIcon(), - widget_delegate_->GetWindowAppIcon()); -} - -FocusTraversable* Widget::GetFocusTraversable() { - return static_cast<internal::RootView*>(root_view_.get()); -} - -void Widget::ThemeChanged() { - root_view_->ThemeChanged(); -} - -void Widget::LocaleChanged() { - root_view_->LocaleChanged(); -} - -void Widget::SetFocusTraversableParent(FocusTraversable* parent) { - root_view_->SetFocusTraversableParent(parent); -} - -void Widget::SetFocusTraversableParentView(View* parent_view) { - root_view_->SetFocusTraversableParentView(parent_view); -} - -void Widget::ClearNativeFocus() { - native_widget_->ClearNativeFocus(); -} - -NonClientFrameView* Widget::CreateNonClientFrameView() { - NonClientFrameView* frame_view = - widget_delegate_->CreateNonClientFrameView(this); - if (!frame_view) - frame_view = native_widget_->CreateNonClientFrameView(); - if (!frame_view && ViewsDelegate::views_delegate) { - frame_view = - ViewsDelegate::views_delegate->CreateDefaultNonClientFrameView(this); - } - if (frame_view) - return frame_view; - - CustomFrameView* custom_frame_view = new CustomFrameView; - custom_frame_view->Init(this); - return custom_frame_view; -} - -bool Widget::ShouldUseNativeFrame() const { - if (frame_type_ != FRAME_TYPE_DEFAULT) - return frame_type_ == FRAME_TYPE_FORCE_NATIVE; - return native_widget_->ShouldUseNativeFrame(); -} - -bool Widget::ShouldWindowContentsBeTransparent() const { - return native_widget_->ShouldWindowContentsBeTransparent(); -} - -void Widget::DebugToggleFrameType() { - if (frame_type_ == FRAME_TYPE_DEFAULT) { - frame_type_ = ShouldUseNativeFrame() ? FRAME_TYPE_FORCE_CUSTOM : - FRAME_TYPE_FORCE_NATIVE; - } else { - frame_type_ = frame_type_ == FRAME_TYPE_FORCE_CUSTOM ? - FRAME_TYPE_FORCE_NATIVE : FRAME_TYPE_FORCE_CUSTOM; - } - FrameTypeChanged(); -} - -void Widget::FrameTypeChanged() { - native_widget_->FrameTypeChanged(); -} - -const ui::Compositor* Widget::GetCompositor() const { - return native_widget_->GetCompositor(); -} - -ui::Compositor* Widget::GetCompositor() { - return native_widget_->GetCompositor(); -} - -ui::Layer* Widget::GetLayer() { - return native_widget_->GetLayer(); -} - -void Widget::ReorderNativeViews() { - native_widget_->ReorderNativeViews(); -} - -void Widget::UpdateRootLayers() { - // Calculate the layers requires traversing the tree, and since nearly any - // mutation of the tree can trigger this call we delay until absolutely - // necessary. - root_layers_dirty_ = true; -} - -const NativeWidget* Widget::native_widget() const { - return native_widget_; -} - -NativeWidget* Widget::native_widget() { - return native_widget_; -} - -void Widget::SetCapture(View* view) { - if (!native_widget_->HasCapture()) { - native_widget_->SetCapture(); - - // Early return if setting capture was unsuccessful. - if (!native_widget_->HasCapture()) - return; - } - - root_view_->SetMouseHandler(view); -} - -void Widget::ReleaseCapture() { - if (native_widget_->HasCapture()) - native_widget_->ReleaseCapture(); -} - -bool Widget::HasCapture() { - return native_widget_->HasCapture(); -} - -TooltipManager* Widget::GetTooltipManager() { - return native_widget_->GetTooltipManager(); -} - -const TooltipManager* Widget::GetTooltipManager() const { - return native_widget_->GetTooltipManager(); -} - -gfx::Rect Widget::GetWorkAreaBoundsInScreen() const { - return native_widget_->GetWorkAreaBoundsInScreen(); -} - -void Widget::SynthesizeMouseMoveEvent() { - last_mouse_event_was_move_ = false; - ui::MouseEvent mouse_event(ui::ET_MOUSE_MOVED, - last_mouse_event_position_, - last_mouse_event_position_, - ui::EF_IS_SYNTHESIZED, 0); - root_view_->OnMouseMoved(mouse_event); -} - -void Widget::OnRootViewLayout() { - native_widget_->OnRootViewLayout(); -} - -bool Widget::IsTranslucentWindowOpacitySupported() const { - return native_widget_->IsTranslucentWindowOpacitySupported(); -} - -void Widget::OnSizeConstraintsChanged() { - native_widget_->OnSizeConstraintsChanged(); - non_client_view_->SizeConstraintsChanged(); -} - -void Widget::OnOwnerClosing() { -} - -//////////////////////////////////////////////////////////////////////////////// -// Widget, NativeWidgetDelegate implementation: - -bool Widget::IsModal() const { - return widget_delegate_->GetModalType() != ui::MODAL_TYPE_NONE; -} - -bool Widget::IsDialogBox() const { - return !!widget_delegate_->AsDialogDelegate(); -} - -bool Widget::CanActivate() const { - return widget_delegate_->CanActivate(); -} - -bool Widget::IsInactiveRenderingDisabled() const { - return disable_inactive_rendering_; -} - -void Widget::EnableInactiveRendering() { - SetInactiveRenderingDisabled(false); -} - -void Widget::OnNativeWidgetActivationChanged(bool active) { - // On windows we may end up here before we've completed initialization (from - // an WM_NCACTIVATE). If that happens the WidgetDelegate likely doesn't know - // the Widget and will crash attempting to access it. - if (!active && native_widget_initialized_) - SaveWindowPlacement(); - - FOR_EACH_OBSERVER(WidgetObserver, observers_, - OnWidgetActivationChanged(this, active)); - - // During window creation, the widget gets focused without activation, and in - // that case, the focus manager cannot set the appropriate text input client - // because the widget is not active. Thus we have to notify the focus manager - // not only when the focus changes but also when the widget gets activated. - // See crbug.com/377479 for details. - views::FocusManager* focus_manager = GetFocusManager(); - if (focus_manager) { - if (active) - focus_manager->FocusTextInputClient(focus_manager->GetFocusedView()); - else - focus_manager->BlurTextInputClient(focus_manager->GetFocusedView()); - } - - if (IsVisible() && non_client_view()) - non_client_view()->frame_view()->SchedulePaint(); -} - -void Widget::OnNativeFocus(gfx::NativeView old_focused_view) { - WidgetFocusManager::GetInstance()->OnWidgetFocusEvent(old_focused_view, - GetNativeView()); -} - -void Widget::OnNativeBlur(gfx::NativeView new_focused_view) { - WidgetFocusManager::GetInstance()->OnWidgetFocusEvent(GetNativeView(), - new_focused_view); -} - -void Widget::OnNativeWidgetVisibilityChanging(bool visible) { - FOR_EACH_OBSERVER(WidgetObserver, observers_, - OnWidgetVisibilityChanging(this, visible)); -} - -void Widget::OnNativeWidgetVisibilityChanged(bool visible) { - View* root = GetRootView(); - if (root) - root->PropagateVisibilityNotifications(root, visible); - FOR_EACH_OBSERVER(WidgetObserver, observers_, - OnWidgetVisibilityChanged(this, visible)); - if (GetCompositor() && root && root->layer()) - root->layer()->SetVisible(visible); -} - -void Widget::OnNativeWidgetCreated(bool desktop_widget) { - if (is_top_level()) - focus_manager_.reset(FocusManagerFactory::Create(this, desktop_widget)); - - native_widget_->InitModalType(widget_delegate_->GetModalType()); - - FOR_EACH_OBSERVER(WidgetObserver, observers_, OnWidgetCreated(this)); -} - -void Widget::OnNativeWidgetDestroying() { - // Tell the focus manager (if any) that root_view is being removed - // in case that the focused view is under this root view. - if (GetFocusManager()) - GetFocusManager()->ViewRemoved(root_view_.get()); - FOR_EACH_OBSERVER(WidgetObserver, observers_, OnWidgetDestroying(this)); - if (non_client_view_) - non_client_view_->WindowClosing(); - widget_delegate_->WindowClosing(); -} - -void Widget::OnNativeWidgetDestroyed() { - FOR_EACH_OBSERVER(WidgetObserver, observers_, OnWidgetDestroyed(this)); - widget_delegate_->DeleteDelegate(); - widget_delegate_ = NULL; - native_widget_destroyed_ = true; -} - -gfx::Size Widget::GetMinimumSize() const { - return non_client_view_ ? non_client_view_->GetMinimumSize() : gfx::Size(); -} - -gfx::Size Widget::GetMaximumSize() const { - return non_client_view_ ? non_client_view_->GetMaximumSize() : gfx::Size(); -} - -void Widget::OnNativeWidgetMove() { - widget_delegate_->OnWidgetMove(); - View* root = GetRootView(); - if (root && root->GetFocusManager()) { - View* focused_view = root->GetFocusManager()->GetFocusedView(); - if (focused_view && focused_view->GetInputMethod()) - focused_view->GetInputMethod()->OnCaretBoundsChanged(focused_view); - } - FOR_EACH_OBSERVER(WidgetObserver, observers_, OnWidgetBoundsChanged( - this, - GetWindowBoundsInScreen())); -} - -void Widget::OnNativeWidgetSizeChanged(const gfx::Size& new_size) { - View* root = GetRootView(); - if (root) { - root->SetSize(new_size); - if (root->GetFocusManager()) { - View* focused_view = GetRootView()->GetFocusManager()->GetFocusedView(); - if (focused_view && focused_view->GetInputMethod()) - focused_view->GetInputMethod()->OnCaretBoundsChanged(focused_view); - } - } - SaveWindowPlacementIfInitialized(); - - FOR_EACH_OBSERVER(WidgetObserver, observers_, OnWidgetBoundsChanged( - this, - GetWindowBoundsInScreen())); -} - -void Widget::OnNativeWidgetWindowShowStateChanged() { - SaveWindowPlacementIfInitialized(); -} - -void Widget::OnNativeWidgetBeginUserBoundsChange() { - widget_delegate_->OnWindowBeginUserBoundsChange(); -} - -void Widget::OnNativeWidgetEndUserBoundsChange() { - widget_delegate_->OnWindowEndUserBoundsChange(); -} - -bool Widget::HasFocusManager() const { - return !!focus_manager_.get(); -} - -bool Widget::OnNativeWidgetPaintAccelerated(const gfx::Rect& dirty_region) { - ui::Compositor* compositor = GetCompositor(); - if (!compositor) - return false; - - compositor->ScheduleRedrawRect(dirty_region); - return true; -} - -void Widget::OnNativeWidgetPaint(gfx::Canvas* canvas) { - // On Linux Aura, we can get here during Init() because of the - // SetInitialBounds call. - if (native_widget_initialized_) - GetRootView()->Paint(canvas, CullSet()); -} - -int Widget::GetNonClientComponent(const gfx::Point& point) { - int component = non_client_view_ ? - non_client_view_->NonClientHitTest(point) : - HTNOWHERE; - - if (movement_disabled_ && (component == HTCAPTION || component == HTSYSMENU)) - return HTNOWHERE; - - return component; -} - -void Widget::OnKeyEvent(ui::KeyEvent* event) { - SendEventToProcessor(event); -} - -// TODO(tdanderson): We should not be calling the OnMouse*() functions on -// RootView from anywhere in Widget. Use -// SendEventToProcessor() instead. See crbug.com/348087. -void Widget::OnMouseEvent(ui::MouseEvent* event) { - if (event->type() != ui::ET_MOUSE_MOVED) - last_mouse_event_was_move_ = false; - - View* root_view = GetRootView(); - switch (event->type()) { - case ui::ET_MOUSE_PRESSED: { - // We may get deleted by the time we return from OnMousePressed. So we - // use an observer to make sure we are still alive. - WidgetDeletionObserver widget_deletion_observer(this); - - // Make sure we're still visible before we attempt capture as the mouse - // press processing may have made the window hide (as happens with menus). - - // It is possible for a View to show a context menu on mouse-press. Since - // the menu does a capture and starts a nested message-loop, the release - // would go to the menu. The next click (i.e. both mouse-press and release - // events) also go to the menu. The menu (and the nested message-loop) - // gets closed after this second release event. The code then resumes from - // here. So make sure that the mouse-button is still down before doing a - // capture. - if (root_view && root_view->OnMousePressed(*event) && - widget_deletion_observer.IsWidgetAlive() && IsVisible() && - internal::NativeWidgetPrivate::IsMouseButtonDown()) { - if (!native_widget_->HasCapture()) - native_widget_->SetCapture(); - event->SetHandled(); - } - return; - } - - case ui::ET_MOUSE_RELEASED: - // Release capture first, to avoid confusion if OnMouseReleased blocks. - if (auto_release_capture_ && native_widget_->HasCapture()) { - base::AutoReset<bool> resetter(&ignore_capture_loss_, true); - native_widget_->ReleaseCapture(); - } - if (root_view) - root_view->OnMouseReleased(*event); - if ((event->flags() & ui::EF_IS_NON_CLIENT) == 0) - event->SetHandled(); - return; - - case ui::ET_MOUSE_MOVED: - if (!last_mouse_event_was_move_ || - last_mouse_event_position_ != event->location()) { - last_mouse_event_position_ = event->location(); - last_mouse_event_was_move_ = true; - if (root_view) - root_view->OnMouseMoved(*event); - } - return; - - case ui::ET_MOUSE_DRAGGED: - if (root_view) - root_view->OnMouseDragged(*event); - return; - - case ui::ET_MOUSE_EXITED: - if (root_view) - root_view->OnMouseExited(*event); - return; - - case ui::ET_MOUSEWHEEL: - if (root_view && root_view->OnMouseWheel( - static_cast<const ui::MouseWheelEvent&>(*event))) - event->SetHandled(); - return; - - default: - return; - } -} - -void Widget::OnMouseCaptureLost() { - if (ignore_capture_loss_) - return; - - View* root_view = GetRootView(); - if (root_view) - root_view->OnMouseCaptureLost(); -} - -void Widget::OnScrollEvent(ui::ScrollEvent* event) { - ui::ScrollEvent event_copy(*event); - SendEventToProcessor(&event_copy); - - // Convert unhandled ui::ET_SCROLL events into ui::ET_MOUSEWHEEL events. - if (!event_copy.handled() && event_copy.type() == ui::ET_SCROLL) { - ui::MouseWheelEvent wheel(*event); - OnMouseEvent(&wheel); - } -} - -void Widget::OnGestureEvent(ui::GestureEvent* event) { - // We explicitly do not capture here. Not capturing enables multiple widgets - // to get tap events at the same time. Views (such as tab dragging) may - // explicitly capture. - SendEventToProcessor(event); -} - -bool Widget::ExecuteCommand(int command_id) { - return widget_delegate_->ExecuteWindowsCommand(command_id); -} - -InputMethod* Widget::GetInputMethodDirect() { - return input_method_.get(); -} - -const std::vector<ui::Layer*>& Widget::GetRootLayers() { - if (root_layers_dirty_) { - root_layers_dirty_ = false; - root_layers_.clear(); - BuildRootLayers(GetRootView(), &root_layers_); - } - return root_layers_; -} - -bool Widget::HasHitTestMask() const { - return widget_delegate_->WidgetHasHitTestMask(); -} - -void Widget::GetHitTestMask(gfx::Path* mask) const { - DCHECK(mask); - widget_delegate_->GetWidgetHitTestMask(mask); -} - -Widget* Widget::AsWidget() { - return this; -} - -const Widget* Widget::AsWidget() const { - return this; -} - -bool Widget::SetInitialFocus(ui::WindowShowState show_state) { - View* v = widget_delegate_->GetInitiallyFocusedView(); - if (!focus_on_creation_ || show_state == ui::SHOW_STATE_INACTIVE || - show_state == ui::SHOW_STATE_MINIMIZED) { - // If not focusing the window now, tell the focus manager which view to - // focus when the window is restored. - if (v) - focus_manager_->SetStoredFocusView(v); - return true; - } - if (v) - v->RequestFocus(); - return !!v; -} - -//////////////////////////////////////////////////////////////////////////////// -// Widget, ui::EventSource implementation: -ui::EventProcessor* Widget::GetEventProcessor() { - return root_view_.get(); -} - -//////////////////////////////////////////////////////////////////////////////// -// Widget, FocusTraversable implementation: - -FocusSearch* Widget::GetFocusSearch() { - return root_view_->GetFocusSearch(); -} - -FocusTraversable* Widget::GetFocusTraversableParent() { - // We are a proxy to the root view, so we should be bypassed when traversing - // up and as a result this should not be called. - NOTREACHED(); - return NULL; -} - -View* Widget::GetFocusTraversableParentView() { - // We are a proxy to the root view, so we should be bypassed when traversing - // up and as a result this should not be called. - NOTREACHED(); - return NULL; -} - -//////////////////////////////////////////////////////////////////////////////// -// Widget, ui::NativeThemeObserver implementation: - -void Widget::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) { - DCHECK(observer_manager_.IsObserving(observed_theme)); - - ui::NativeTheme* current_native_theme = GetNativeTheme(); - if (!observer_manager_.IsObserving(current_native_theme)) { - observer_manager_.RemoveAll(); - observer_manager_.Add(current_native_theme); - } - - root_view_->PropagateNativeThemeChanged(current_native_theme); -} - -//////////////////////////////////////////////////////////////////////////////// -// Widget, protected: - -internal::RootView* Widget::CreateRootView() { - return new internal::RootView(this); -} - -void Widget::DestroyRootView() { - non_client_view_ = NULL; - root_view_.reset(); - // Input method has to be destroyed before focus manager. - input_method_.reset(); -} - -void Widget::OnDragWillStart() { -} - -void Widget::OnDragComplete() { -} - -//////////////////////////////////////////////////////////////////////////////// -// Widget, private: - -void Widget::SetInactiveRenderingDisabled(bool value) { - if (value == disable_inactive_rendering_) - return; - - disable_inactive_rendering_ = value; - if (non_client_view_) - non_client_view_->SetInactiveRenderingDisabled(value); -} - -void Widget::SaveWindowPlacement() { - // The window delegate does the actual saving for us. It seems like (judging - // by go/crash) that in some circumstances we can end up here after - // WM_DESTROY, at which point the window delegate is likely gone. So just - // bail. - if (!widget_delegate_) - return; - - ui::WindowShowState show_state = ui::SHOW_STATE_NORMAL; - gfx::Rect bounds; - native_widget_->GetWindowPlacement(&bounds, &show_state); - widget_delegate_->SaveWindowPlacement(bounds, show_state); -} - -void Widget::SaveWindowPlacementIfInitialized() { - if (native_widget_initialized_) - SaveWindowPlacement(); -} - -void Widget::SetInitialBounds(const gfx::Rect& bounds) { - if (!non_client_view_) - return; - - gfx::Rect saved_bounds; - if (GetSavedWindowPlacement(&saved_bounds, &saved_show_state_)) { - if (saved_show_state_ == ui::SHOW_STATE_MAXIMIZED) { - // If we're going to maximize, wait until Show is invoked to set the - // bounds. That way we avoid a noticeable resize. - initial_restored_bounds_ = saved_bounds; - } else if (!saved_bounds.IsEmpty()) { - // If the saved bounds are valid, use them. - SetBounds(saved_bounds); - } - } else { - if (bounds.IsEmpty()) { - // No initial bounds supplied, so size the window to its content and - // center over its parent. - native_widget_->CenterWindow(non_client_view_->GetPreferredSize()); - } else { - // Use the supplied initial bounds. - SetBoundsConstrained(bounds); - } - } -} - -void Widget::SetInitialBoundsForFramelessWindow(const gfx::Rect& bounds) { - if (bounds.IsEmpty()) { - View* contents_view = GetContentsView(); - DCHECK(contents_view); - // No initial bounds supplied, so size the window to its content and - // center over its parent if preferred size is provided. - gfx::Size size = contents_view->GetPreferredSize(); - if (!size.IsEmpty()) - native_widget_->CenterWindow(size); - } else { - // Use the supplied initial bounds. - SetBoundsConstrained(bounds); - } -} - -bool Widget::GetSavedWindowPlacement(gfx::Rect* bounds, - ui::WindowShowState* show_state) { - // First we obtain the window's saved show-style and store it. We need to do - // this here, rather than in Show() because by the time Show() is called, - // the window's size will have been reset (below) and the saved maximized - // state will have been lost. Sadly there's no way to tell on Windows when - // a window is restored from maximized state, so we can't more accurately - // track maximized state independently of sizing information. - - // Restore the window's placement from the controller. - if (widget_delegate_->GetSavedWindowPlacement(this, bounds, show_state)) { - if (!widget_delegate_->ShouldRestoreWindowSize()) { - bounds->set_size(non_client_view_->GetPreferredSize()); - } else { - gfx::Size minimum_size = GetMinimumSize(); - // Make sure the bounds are at least the minimum size. - if (bounds->width() < minimum_size.width()) - bounds->set_width(minimum_size.width()); - - if (bounds->height() < minimum_size.height()) - bounds->set_height(minimum_size.height()); - } - return true; - } - return false; -} - -scoped_ptr<InputMethod> Widget::CreateInputMethod() { - scoped_ptr<InputMethod> input_method(native_widget_->CreateInputMethod()); - if (input_method.get()) - input_method->Init(this); - return input_method.Pass(); -} - -void Widget::ReplaceInputMethod(InputMethod* input_method) { - input_method_.reset(input_method); - input_method->SetDelegate(native_widget_->GetInputMethodDelegate()); - input_method->Init(this); -} - -namespace internal { - -//////////////////////////////////////////////////////////////////////////////// -// internal::NativeWidgetPrivate, NativeWidget implementation: - -internal::NativeWidgetPrivate* NativeWidgetPrivate::AsNativeWidgetPrivate() { - return this; -} - -} // namespace internal -} // namespace views
diff --git a/ui/views/widget/widget.h b/ui/views/widget/widget.h deleted file mode 100644 index 08ab939..0000000 --- a/ui/views/widget/widget.h +++ /dev/null
@@ -1,954 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_WIDGET_WIDGET_H_ -#define UI_VIEWS_WIDGET_WIDGET_H_ - -#include <set> -#include <stack> -#include <vector> - -#include "base/gtest_prod_util.h" -#include "base/memory/scoped_ptr.h" -#include "base/observer_list.h" -#include "base/scoped_observer.h" -#include "ui/aura/window_layer_type.h" -#include "ui/base/ui_base_types.h" -#include "ui/events/event_source.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/gfx/rect.h" -#include "ui/native_theme/native_theme_observer.h" -#include "ui/views/focus/focus_manager.h" -#include "ui/views/widget/native_widget_delegate.h" -#include "ui/views/window/client_view.h" -#include "ui/views/window/non_client_view.h" - -#if defined(OS_WIN) -// Windows headers define macros for these function names which screw with us. -#if defined(IsMaximized) -#undef IsMaximized -#endif -#if defined(IsMinimized) -#undef IsMinimized -#endif -#if defined(CreateWindow) -#undef CreateWindow -#endif -#endif - -namespace gfx { -class Canvas; -class Point; -class Rect; -} - -namespace ui { -class Accelerator; -class Compositor; -class DefaultThemeProvider; -class InputMethod; -class Layer; -class NativeTheme; -class OSExchangeData; -class ThemeProvider; -} - -namespace views { - -class DesktopWindowTreeHost; -class InputMethod; -class NativeWidget; -class NonClientFrameView; -class TooltipManager; -class View; -class WidgetDelegate; -class WidgetObserver; -class WidgetRemovalsObserver; - -namespace internal { -class NativeWidgetPrivate; -class RootView; -} - -//////////////////////////////////////////////////////////////////////////////// -// Widget class -// -// Encapsulates the platform-specific rendering, event receiving and widget -// management aspects of the UI framework. -// -// Owns a RootView and thus a View hierarchy. Can contain child Widgets. -// Widget is a platform-independent type that communicates with a platform or -// context specific NativeWidget implementation. -// -// A special note on ownership: -// -// Depending on the value of the InitParams' ownership field, the Widget -// either owns or is owned by its NativeWidget: -// -// ownership = NATIVE_WIDGET_OWNS_WIDGET (default) -// The Widget instance is owned by its NativeWidget. When the NativeWidget -// is destroyed (in response to a native destruction message), it deletes -// the Widget from its destructor. -// ownership = WIDGET_OWNS_NATIVE_WIDGET (non-default) -// The Widget instance owns its NativeWidget. This state implies someone -// else wants to control the lifetime of this object. When they destroy -// the Widget it is responsible for destroying the NativeWidget (from its -// destructor). -// -class VIEWS_EXPORT Widget : public internal::NativeWidgetDelegate, - public ui::EventSource, - public FocusTraversable, - public ui::NativeThemeObserver { - public: - typedef std::set<Widget*> Widgets; - - enum FrameType { - FRAME_TYPE_DEFAULT, // Use whatever the default would be. - FRAME_TYPE_FORCE_CUSTOM, // Force the custom frame. - FRAME_TYPE_FORCE_NATIVE // Force the native frame. - }; - - // Result from RunMoveLoop(). - enum MoveLoopResult { - // The move loop completed successfully. - MOVE_LOOP_SUCCESSFUL, - - // The user canceled the move loop. - MOVE_LOOP_CANCELED - }; - - // Source that initiated the move loop. - enum MoveLoopSource { - MOVE_LOOP_SOURCE_MOUSE, - MOVE_LOOP_SOURCE_TOUCH, - }; - - // Behavior when escape is pressed during a move loop. - enum MoveLoopEscapeBehavior { - // Indicates the window should be hidden. - MOVE_LOOP_ESCAPE_BEHAVIOR_HIDE, - - // Indicates the window should not be hidden. - MOVE_LOOP_ESCAPE_BEHAVIOR_DONT_HIDE, - }; - - struct VIEWS_EXPORT InitParams { - enum Type { - TYPE_WINDOW, // A decorated Window, like a frame window. - // Widgets of TYPE_WINDOW will have a NonClientView. - TYPE_PANEL, // Always on top window managed by PanelManager. - // Widgets of TYPE_PANEL will have a NonClientView. - TYPE_WINDOW_FRAMELESS, - // An undecorated Window. - TYPE_CONTROL, // A control, like a button. - TYPE_POPUP, // An undecorated Window, with transient properties. - TYPE_MENU, // An undecorated Window, with transient properties - // specialized to menus. - TYPE_TOOLTIP, - TYPE_BUBBLE, - TYPE_DRAG, // An undecorated Window, used during a drag-and-drop to - // show the drag image. - }; - - enum WindowOpacity { - // Infer fully opaque or not. For WinAura, top-level windows that are not - // of TYPE_WINDOW are translucent so that they can be made to fade in. In - // all other cases, windows are fully opaque. - INFER_OPACITY, - // Fully opaque. - OPAQUE_WINDOW, - // Possibly translucent/transparent. - TRANSLUCENT_WINDOW, - }; - - enum Activatable { - // Infer whether the window should be activatable from the window type. - ACTIVATABLE_DEFAULT, - - ACTIVATABLE_YES, - ACTIVATABLE_NO - }; - - enum Ownership { - // Default. Creator is not responsible for managing the lifetime of the - // Widget, it is destroyed when the corresponding NativeWidget is - // destroyed. - NATIVE_WIDGET_OWNS_WIDGET, - // Used when the Widget is owned by someone other than the NativeWidget, - // e.g. a scoped_ptr in tests. - WIDGET_OWNS_NATIVE_WIDGET - }; - - enum ShadowType { - SHADOW_TYPE_DEFAULT, // Use default shadow setting. It will be one of - // the settings below depending on InitParams::type - // and the native widget's type. - SHADOW_TYPE_NONE, // Don't draw any shadow. - SHADOW_TYPE_DROP, // Draw a drop shadow that emphasizes Z-order - // relationship to other windows. - }; - - InitParams(); - explicit InitParams(Type type); - ~InitParams(); - - Type type; - // If NULL, a default implementation will be constructed. - WidgetDelegate* delegate; - bool child; - // If TRANSLUCENT_WINDOW, the widget may be fully or partially transparent. - // Translucent windows may not always be supported. Use - // IsTranslucentWindowOpacitySupported to determine if translucent windows - // are supported. - // If OPAQUE_WINDOW, we can perform optimizations based on the widget being - // fully opaque. Defaults to TRANSLUCENT_WINDOW if - // ViewsDelegate::UseTransparentWindows(). Defaults to OPAQUE_WINDOW for - // non-window widgets. - WindowOpacity opacity; - bool accept_events; - Activatable activatable; - bool keep_on_top; - bool visible_on_all_workspaces; - Ownership ownership; - bool mirror_origin_in_rtl; - ShadowType shadow_type; - // Specifies that the system default caption and icon should not be - // rendered, and that the client area should be equivalent to the window - // area. Only used on some platforms (Windows and Linux). - bool remove_standard_frame; - // Only used by ShellWindow on Windows. Specifies that the default icon of - // packaged app should be the system default icon. - bool use_system_default_icon; - // Whether the widget should be maximized or minimized. - ui::WindowShowState show_state; - // Should the widget be double buffered? Default is false. - bool double_buffer; - gfx::NativeView parent; - // Specifies the initial bounds of the Widget. Default is empty, which means - // the NativeWidget may specify a default size. If the parent is specified, - // |bounds| is in the parent's coordinate system. If the parent is not - // specified, it's in screen's global coordinate system. - gfx::Rect bounds; - // When set, this value is used as the Widget's NativeWidget implementation. - // The Widget will not construct a default one. Default is NULL. - NativeWidget* native_widget; - // Aura-only. Provides a DesktopWindowTreeHost implementation to use instead - // of the default one. - // TODO(beng): Figure out if there's a better way to expose this, e.g. get - // rid of NW subclasses and do this all via message handling. - DesktopWindowTreeHost* desktop_window_tree_host; - // Only used by NativeWidgetAura. Specifies the type of layer for the - // aura::Window. Default is WINDOW_LAYER_TEXTURED. - aura::WindowLayerType layer_type; - // Only used by Aura. Provides a context window whose RootWindow is - // consulted during widget creation to determine where in the Window - // hierarchy this widget should be placed. (This is separate from |parent|; - // if you pass a RootWindow to |parent|, your window will be parented to - // |parent|. If you pass a RootWindow to |context|, we ask that RootWindow - // where it wants your window placed.) NULL is not allowed if you are using - // aura. - gfx::NativeWindow context; - // If true, forces the window to be shown in the taskbar, even for window - // types that do not appear in the taskbar by default (popup and bubble). - bool force_show_in_taskbar; - // Only used by X11, for root level windows. Specifies the res_name and - // res_class fields, respectively, of the WM_CLASS window property. Controls - // window grouping and desktop file matching in Linux window managers. - std::string wm_role_name; - std::string wm_class_name; - std::string wm_class_class; - }; - - Widget(); - virtual ~Widget(); - - // Creates a toplevel window with no context. These methods should only be - // used in cases where there is no contextual information because we're - // creating a toplevel window connected to no other event. - // - // If you have any parenting or context information, or can pass that - // information, prefer the WithParent or WithContext versions of these - // methods. - static Widget* CreateWindow(WidgetDelegate* delegate); - static Widget* CreateWindowWithBounds(WidgetDelegate* delegate, - const gfx::Rect& bounds); - - // Creates a decorated window Widget with the specified properties. - static Widget* CreateWindowWithParent(WidgetDelegate* delegate, - gfx::NativeView parent); - static Widget* CreateWindowWithParentAndBounds(WidgetDelegate* delegate, - gfx::NativeView parent, - const gfx::Rect& bounds); - - // Creates a decorated window Widget in the same desktop context as |context|. - static Widget* CreateWindowWithContext(WidgetDelegate* delegate, - gfx::NativeWindow context); - static Widget* CreateWindowWithContextAndBounds(WidgetDelegate* delegate, - gfx::NativeWindow context, - const gfx::Rect& bounds); - - // Closes all Widgets that aren't identified as "secondary widgets". Called - // during application shutdown when the last non-secondary widget is closed. - static void CloseAllSecondaryWidgets(); - - // Converts a rectangle from one Widget's coordinate system to another's. - // Returns false if the conversion couldn't be made, because either these two - // Widgets do not have a common ancestor or they are not on the screen yet. - // The value of |*rect| won't be changed when false is returned. - static bool ConvertRect(const Widget* source, - const Widget* target, - gfx::Rect* rect); - - // Retrieves the Widget implementation associated with the given - // NativeView or Window, or NULL if the supplied handle has no associated - // Widget. - static Widget* GetWidgetForNativeView(gfx::NativeView native_view); - static Widget* GetWidgetForNativeWindow(gfx::NativeWindow native_window); - - // Retrieves the top level widget in a native view hierarchy - // starting at |native_view|. Top level widget is a widget with TYPE_WINDOW, - // TYPE_PANEL, TYPE_WINDOW_FRAMELESS, POPUP or MENU and has its own - // focus manager. This may be itself if the |native_view| is top level, - // or NULL if there is no toplevel in a native view hierarchy. - static Widget* GetTopLevelWidgetForNativeView(gfx::NativeView native_view); - - // Returns all Widgets in |native_view|'s hierarchy, including itself if - // it is one. - static void GetAllChildWidgets(gfx::NativeView native_view, - Widgets* children); - - // Returns all non-child Widgets owned by |native_view|. - static void GetAllOwnedWidgets(gfx::NativeView native_view, - Widgets* owned); - - // Re-parent a NativeView and notify all Widgets in |native_view|'s hierarchy - // of the change. - static void ReparentNativeView(gfx::NativeView native_view, - gfx::NativeView new_parent); - - // Returns the preferred size of the contents view of this window based on - // its localized size data. The width in cols is held in a localized string - // resource identified by |col_resource_id|, the height in the same fashion. - // TODO(beng): This should eventually live somewhere else, probably closer to - // ClientView. - static int GetLocalizedContentsWidth(int col_resource_id); - static int GetLocalizedContentsHeight(int row_resource_id); - static gfx::Size GetLocalizedContentsSize(int col_resource_id, - int row_resource_id); - - // Returns true if the specified type requires a NonClientView. - static bool RequiresNonClientView(InitParams::Type type); - - void Init(const InitParams& params); - - // Returns the gfx::NativeView associated with this Widget. - gfx::NativeView GetNativeView() const; - - // Returns the gfx::NativeWindow associated with this Widget. This may return - // NULL on some platforms if the widget was created with a type other than - // TYPE_WINDOW or TYPE_PANEL. - gfx::NativeWindow GetNativeWindow() const; - - // Add/remove observer. - void AddObserver(WidgetObserver* observer); - void RemoveObserver(WidgetObserver* observer); - bool HasObserver(WidgetObserver* observer); - - // Add/remove removals observer. - void AddRemovalsObserver(WidgetRemovalsObserver* observer); - void RemoveRemovalsObserver(WidgetRemovalsObserver* observer); - bool HasRemovalsObserver(WidgetRemovalsObserver* observer); - - // Returns the accelerator given a command id. Returns false if there is - // no accelerator associated with a given id, which is a common condition. - virtual bool GetAccelerator(int cmd_id, ui::Accelerator* accelerator) const; - - // Forwarded from the RootView so that the widget can do any cleanup. - void ViewHierarchyChanged(const View::ViewHierarchyChangedDetails& details); - - // Called right before changing the widget's parent NativeView to do any - // cleanup. - void NotifyNativeViewHierarchyWillChange(); - - // Called after changing the widget's parent NativeView. Notifies the RootView - // about the change. - void NotifyNativeViewHierarchyChanged(); - - // Called immediately before removing |view| from this widget. - void NotifyWillRemoveView(View* view); - - // Returns the top level widget in a hierarchy (see is_top_level() for - // the definition of top level widget.) Will return NULL if called - // before the widget is attached to the top level widget's hierarchy. - Widget* GetTopLevelWidget(); - const Widget* GetTopLevelWidget() const; - - // Gets/Sets the WidgetDelegate. - WidgetDelegate* widget_delegate() const { return widget_delegate_; } - - // Sets the specified view as the contents of this Widget. There can only - // be one contents view child of this Widget's RootView. This view is sized to - // fit the entire size of the RootView. The RootView takes ownership of this - // View, unless it is set as not being parent-owned. - void SetContentsView(View* view); - View* GetContentsView(); - - // Returns the bounds of the Widget in screen coordinates. - gfx::Rect GetWindowBoundsInScreen() const; - - // Returns the bounds of the Widget's client area in screen coordinates. - gfx::Rect GetClientAreaBoundsInScreen() const; - - // Retrieves the restored bounds for the window. - gfx::Rect GetRestoredBounds() const; - - // Sizes and/or places the widget to the specified bounds, size or position. - void SetBounds(const gfx::Rect& bounds); - void SetSize(const gfx::Size& size); - - // Sizes the window to the specified size and centerizes it. - void CenterWindow(const gfx::Size& size); - - // Like SetBounds(), but ensures the Widget is fully visible on screen, - // resizing and/or repositioning as necessary. This is only useful for - // non-child widgets. - void SetBoundsConstrained(const gfx::Rect& bounds); - - // Sets whether animations that occur when visibility is changed are enabled. - // Default is true. - void SetVisibilityChangedAnimationsEnabled(bool value); - - // Starts a nested message loop that moves the window. This can be used to - // start a window move operation from a mouse or touch event. This returns - // when the move completes. |drag_offset| is the offset from the top left - // corner of the window to the point where the cursor is dragging, and is used - // to offset the bounds of the window from the cursor. - MoveLoopResult RunMoveLoop(const gfx::Vector2d& drag_offset, - MoveLoopSource source, - MoveLoopEscapeBehavior escape_behavior); - - // Stops a previously started move loop. This is not immediate. - void EndMoveLoop(); - - // Places the widget in front of the specified widget in z-order. - void StackAboveWidget(Widget* widget); - void StackAbove(gfx::NativeView native_view); - void StackAtTop(); - - // Places the widget below the specified NativeView. - void StackBelow(gfx::NativeView native_view); - - // Sets a shape on the widget. Passing a NULL |shape| reverts the widget to - // be rectangular. Takes ownership of |shape|. - void SetShape(gfx::NativeRegion shape); - - // Hides the widget then closes it after a return to the message loop. - virtual void Close(); - - // TODO(beng): Move off public API. - // Closes the widget immediately. Compare to |Close|. This will destroy the - // window handle associated with this Widget, so should not be called from - // any code that expects it to be valid beyond this call. - void CloseNow(); - - // Whether the widget has been asked to close itself. In particular this is - // set to true after Close() has been invoked on the NativeWidget. - bool IsClosed() const; - - // Shows the widget. The widget is activated if during initialization the - // can_activate flag in the InitParams structure is set to true. - virtual void Show(); - // Hides the widget. - void Hide(); - - // Like Show(), but does not activate the window. - void ShowInactive(); - - // Activates the widget, assuming it already exists and is visible. - void Activate(); - - // Deactivates the widget, making the next window in the Z order the active - // window. - void Deactivate(); - - // Returns whether the Widget is the currently active window. - virtual bool IsActive() const; - - // Prevents the window from being rendered as deactivated. This state is - // reset automatically as soon as the window becomes activated again. There is - // no ability to control the state through this API as this leads to sync - // problems. - void DisableInactiveRendering(); - - // Sets the widget to be on top of all other widgets in the windowing system. - void SetAlwaysOnTop(bool on_top); - - // Returns whether the widget has been set to be on top of most other widgets - // in the windowing system. - bool IsAlwaysOnTop() const; - - // Sets the widget to be visible on all work spaces. - void SetVisibleOnAllWorkspaces(bool always_visible); - - // Maximizes/minimizes/restores the window. - void Maximize(); - void Minimize(); - void Restore(); - - // Whether or not the window is maximized or minimized. - virtual bool IsMaximized() const; - bool IsMinimized() const; - - // Accessors for fullscreen state. - void SetFullscreen(bool fullscreen); - bool IsFullscreen() const; - - // Sets the opacity of the widget. This may allow widgets behind the widget - // in the Z-order to become visible, depending on the capabilities of the - // underlying windowing system. - void SetOpacity(unsigned char opacity); - - // Sets whether or not the window should show its frame as a "transient drag - // frame" - slightly transparent and without the standard window controls. - void SetUseDragFrame(bool use_drag_frame); - - // Flashes the frame of the window to draw attention to it. Currently only - // implemented on Windows for non-Aura. - void FlashFrame(bool flash); - - // Returns the View at the root of the View hierarchy contained by this - // Widget. - View* GetRootView(); - const View* GetRootView() const; - - // A secondary widget is one that is automatically closed (via Close()) when - // all non-secondary widgets are closed. - // Default is true. - // TODO(beng): This is an ugly API, should be handled implicitly via - // transience. - void set_is_secondary_widget(bool is_secondary_widget) { - is_secondary_widget_ = is_secondary_widget; - } - bool is_secondary_widget() const { return is_secondary_widget_; } - - // Returns whether the Widget is visible to the user. - virtual bool IsVisible() const; - - // Returns the ThemeProvider that provides theme resources for this Widget. - virtual ui::ThemeProvider* GetThemeProvider() const; - - ui::NativeTheme* GetNativeTheme() { - return const_cast<ui::NativeTheme*>( - const_cast<const Widget*>(this)->GetNativeTheme()); - } - const ui::NativeTheme* GetNativeTheme() const; - - // Returns the FocusManager for this widget. - // Note that all widgets in a widget hierarchy share the same focus manager. - FocusManager* GetFocusManager(); - const FocusManager* GetFocusManager() const; - - // Returns the InputMethod for this widget. - // Note that all widgets in a widget hierarchy share the same input method. - InputMethod* GetInputMethod(); - const InputMethod* GetInputMethod() const; - - // Returns the ui::InputMethod for this widget. - // TODO(yukishiino): Rename this method to GetInputMethod once we remove - // views::InputMethod. - ui::InputMethod* GetHostInputMethod(); - - // Starts a drag operation for the specified view. This blocks until the drag - // operation completes. |view| can be NULL. - // If the view is non-NULL it can be accessed during the drag by calling - // dragged_view(). If the view has not been deleted during the drag, - // OnDragDone() is called on it. |location| is in the widget's coordinate - // system. - void RunShellDrag(View* view, - const ui::OSExchangeData& data, - const gfx::Point& location, - int operation, - ui::DragDropTypes::DragEventSource source); - - // Returns the view that requested the current drag operation via - // RunShellDrag(), or NULL if there is no such view or drag operation. - View* dragged_view() { return dragged_view_; } - - // Adds the specified |rect| in client area coordinates to the rectangle to be - // redrawn. - virtual void SchedulePaintInRect(const gfx::Rect& rect); - - // Sets the currently visible cursor. If |cursor| is NULL, the cursor used - // before the current is restored. - void SetCursor(gfx::NativeCursor cursor); - - // Returns true if and only if mouse events are enabled. - bool IsMouseEventsEnabled() const; - - // Sets/Gets a native window property on the underlying native window object. - // Returns NULL if the property does not exist. Setting the property value to - // NULL removes the property. - void SetNativeWindowProperty(const char* name, void* value); - void* GetNativeWindowProperty(const char* name) const; - - // Tell the window to update its title from the delegate. - void UpdateWindowTitle(); - - // Tell the window to update its icon from the delegate. - void UpdateWindowIcon(); - - // Retrieves the focus traversable for this widget. - FocusTraversable* GetFocusTraversable(); - - // Notifies the view hierarchy contained in this widget that theme resources - // changed. - void ThemeChanged(); - - // Notifies the view hierarchy contained in this widget that locale resources - // changed. - void LocaleChanged(); - - void SetFocusTraversableParent(FocusTraversable* parent); - void SetFocusTraversableParentView(View* parent_view); - - // Clear native focus set to the Widget's NativeWidget. - void ClearNativeFocus(); - - void set_frame_type(FrameType frame_type) { frame_type_ = frame_type; } - FrameType frame_type() const { return frame_type_; } - - // Creates an appropriate NonClientFrameView for this widget. The - // WidgetDelegate is given the first opportunity to create one, followed by - // the NativeWidget implementation. If both return NULL, a default one is - // created. - virtual NonClientFrameView* CreateNonClientFrameView(); - - // Whether we should be using a native frame. - bool ShouldUseNativeFrame() const; - - // Determines whether the window contents should be rendered transparently - // (for example, so that they can overhang onto the window title bar). - bool ShouldWindowContentsBeTransparent() const; - - // Forces the frame into the alternate frame type (custom or native) depending - // on its current state. - void DebugToggleFrameType(); - - // Tell the window that something caused the frame type to change. - void FrameTypeChanged(); - - NonClientView* non_client_view() { - return const_cast<NonClientView*>( - const_cast<const Widget*>(this)->non_client_view()); - } - const NonClientView* non_client_view() const { - return non_client_view_; - } - - ClientView* client_view() { - return const_cast<ClientView*>( - const_cast<const Widget*>(this)->client_view()); - } - const ClientView* client_view() const { - // non_client_view_ may be NULL, especially during creation. - return non_client_view_ ? non_client_view_->client_view() : NULL; - } - - const ui::Compositor* GetCompositor() const; - ui::Compositor* GetCompositor(); - - // Returns the widget's layer, if any. - ui::Layer* GetLayer(); - - // Reorders the widget's child NativeViews which are associated to the view - // tree (eg via a NativeViewHost) to match the z-order of the views in the - // view tree. The z-order of views with layers relative to views with - // associated NativeViews is used to reorder the NativeView layers. This - // method assumes that the widget's child layers which are owned by a view are - // already in the correct z-order relative to each other and does no - // reordering if there are no views with an associated NativeView. - void ReorderNativeViews(); - - // Schedules an update to the root layers. The actual processing occurs when - // GetRootLayers() is invoked. - void UpdateRootLayers(); - - const NativeWidget* native_widget() const; - NativeWidget* native_widget(); - - internal::NativeWidgetPrivate* native_widget_private() { - return native_widget_; - } - const internal::NativeWidgetPrivate* native_widget_private() const { - return native_widget_; - } - - // Sets capture to the specified view. This makes it so that all mouse, touch - // and gesture events go to |view|. If |view| is NULL, the widget still - // obtains event capture, but the events will go to the view they'd normally - // go to. - void SetCapture(View* view); - - // Releases capture. - void ReleaseCapture(); - - // Returns true if the widget has capture. - bool HasCapture(); - - void set_auto_release_capture(bool auto_release_capture) { - auto_release_capture_ = auto_release_capture; - } - - // Returns the font used for tooltips. - TooltipManager* GetTooltipManager(); - const TooltipManager* GetTooltipManager() const; - - void set_focus_on_creation(bool focus_on_creation) { - focus_on_creation_ = focus_on_creation; - } - - // True if the widget is considered top level widget. Top level widget - // is a widget of TYPE_WINDOW, TYPE_PANEL, TYPE_WINDOW_FRAMELESS, BUBBLE, - // POPUP or MENU, and has a focus manager and input method object associated - // with it. TYPE_CONTROL and TYPE_TOOLTIP is not considered top level. - bool is_top_level() const { return is_top_level_; } - - // True when window movement via mouse interaction with the frame is disabled. - bool movement_disabled() const { return movement_disabled_; } - void set_movement_disabled(bool disabled) { movement_disabled_ = disabled; } - - // Returns the work area bounds of the screen the Widget belongs to. - gfx::Rect GetWorkAreaBoundsInScreen() const; - - // Creates and dispatches synthesized mouse move event using the current - // mouse location to refresh hovering status in the widget. - void SynthesizeMouseMoveEvent(); - - // Called by our RootView after it has performed a Layout. Used to forward - // window sizing information to the window server on some platforms. - void OnRootViewLayout(); - - // Whether the widget supports translucency. - bool IsTranslucentWindowOpacitySupported() const; - - // Called when the delegate's CanResize or CanMaximize changes. - void OnSizeConstraintsChanged(); - - // Notification that our owner is closing. - // NOTE: this is not invoked for aura as it's currently not needed there. - // Under aura menus close by way of activation getting reset when the owner - // closes. - virtual void OnOwnerClosing(); - - // Overridden from NativeWidgetDelegate: - virtual bool IsModal() const override; - virtual bool IsDialogBox() const override; - virtual bool CanActivate() const override; - virtual bool IsInactiveRenderingDisabled() const override; - virtual void EnableInactiveRendering() override; - virtual void OnNativeWidgetActivationChanged(bool active) override; - virtual void OnNativeFocus(gfx::NativeView old_focused_view) override; - virtual void OnNativeBlur(gfx::NativeView new_focused_view) override; - virtual void OnNativeWidgetVisibilityChanging(bool visible) override; - virtual void OnNativeWidgetVisibilityChanged(bool visible) override; - virtual void OnNativeWidgetCreated(bool desktop_widget) override; - virtual void OnNativeWidgetDestroying() override; - virtual void OnNativeWidgetDestroyed() override; - virtual gfx::Size GetMinimumSize() const override; - virtual gfx::Size GetMaximumSize() const override; - virtual void OnNativeWidgetMove() override; - virtual void OnNativeWidgetSizeChanged(const gfx::Size& new_size) override; - virtual void OnNativeWidgetWindowShowStateChanged() override; - virtual void OnNativeWidgetBeginUserBoundsChange() override; - virtual void OnNativeWidgetEndUserBoundsChange() override; - virtual bool HasFocusManager() const override; - virtual bool OnNativeWidgetPaintAccelerated( - const gfx::Rect& dirty_region) override; - virtual void OnNativeWidgetPaint(gfx::Canvas* canvas) override; - virtual int GetNonClientComponent(const gfx::Point& point) override; - virtual void OnKeyEvent(ui::KeyEvent* event) override; - virtual void OnMouseEvent(ui::MouseEvent* event) override; - virtual void OnMouseCaptureLost() override; - virtual void OnScrollEvent(ui::ScrollEvent* event) override; - virtual void OnGestureEvent(ui::GestureEvent* event) override; - virtual bool ExecuteCommand(int command_id) override; - virtual InputMethod* GetInputMethodDirect() override; - virtual const std::vector<ui::Layer*>& GetRootLayers() override; - virtual bool HasHitTestMask() const override; - virtual void GetHitTestMask(gfx::Path* mask) const override; - virtual Widget* AsWidget() override; - virtual const Widget* AsWidget() const override; - virtual bool SetInitialFocus(ui::WindowShowState show_state) override; - - // Overridden from ui::EventSource: - virtual ui::EventProcessor* GetEventProcessor() override; - - // Overridden from FocusTraversable: - virtual FocusSearch* GetFocusSearch() override; - virtual FocusTraversable* GetFocusTraversableParent() override; - virtual View* GetFocusTraversableParentView() override; - - // Overridden from ui::NativeThemeObserver: - virtual void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override; - - protected: - // Creates the RootView to be used within this Widget. Subclasses may override - // to create custom RootViews that do specialized event processing. - // TODO(beng): Investigate whether or not this is needed. - virtual internal::RootView* CreateRootView(); - - // Provided to allow the NativeWidget implementations to destroy the RootView - // _before_ the focus manager/tooltip manager. - // TODO(beng): remove once we fold those objects onto this one. - void DestroyRootView(); - - // Notification that a drag will start. Default implementation does nothing. - virtual void OnDragWillStart(); - - // Notification that the drag performed by RunShellDrag() has completed. - virtual void OnDragComplete(); - - private: - friend class ComboboxTest; - friend class TextfieldTest; - - // Sets the value of |disable_inactive_rendering_|. If the value changes, - // both the NonClientView and WidgetDelegate are notified. - void SetInactiveRenderingDisabled(bool value); - - // Persists the window's restored position and "show" state using the - // window delegate. - void SaveWindowPlacement(); - - // Invokes SaveWindowPlacement() if the native widget has been initialized. - // This is called at times when the native widget may not have been - // initialized. - void SaveWindowPlacementIfInitialized(); - - // Sizes and positions the window just after it is created. - void SetInitialBounds(const gfx::Rect& bounds); - - // Sizes and positions the frameless window just after it is created. - void SetInitialBoundsForFramelessWindow(const gfx::Rect& bounds); - - // Returns the bounds and "show" state from the delegate. Returns true if - // the delegate wants to use a specified bounds. - bool GetSavedWindowPlacement(gfx::Rect* bounds, - ui::WindowShowState* show_state); - - // Creates and initializes a new InputMethod and returns it, otherwise null. - scoped_ptr<InputMethod> CreateInputMethod(); - - // Sets a different InputMethod instance to this widget. The instance - // must not be initialized, the ownership will be assumed by the widget. - // It's only for testing purpose. - void ReplaceInputMethod(InputMethod* input_method); - - internal::NativeWidgetPrivate* native_widget_; - - ObserverList<WidgetObserver> observers_; - - ObserverList<WidgetRemovalsObserver> removals_observers_; - - // Non-owned pointer to the Widget's delegate. If a NULL delegate is supplied - // to Init() a default WidgetDelegate is created. - WidgetDelegate* widget_delegate_; - - // The root of the View hierarchy attached to this window. - // WARNING: see warning in tooltip_manager_ for ordering dependencies with - // this and tooltip_manager_. - scoped_ptr<internal::RootView> root_view_; - - // The View that provides the non-client area of the window (title bar, - // window controls, sizing borders etc). To use an implementation other than - // the default, this class must be sub-classed and this value set to the - // desired implementation before calling |InitWindow()|. - NonClientView* non_client_view_; - - // The focus manager keeping track of focus for this Widget and any of its - // children. NULL for non top-level widgets. - // WARNING: RootView's destructor calls into the FocusManager. As such, this - // must be destroyed AFTER root_view_. This is enforced in DestroyRootView(). - scoped_ptr<FocusManager> focus_manager_; - - // A theme provider to use when no other theme provider is specified. - scoped_ptr<ui::DefaultThemeProvider> default_theme_provider_; - - // Valid for the lifetime of RunShellDrag(), indicates the view the drag - // started from. - View* dragged_view_; - - // See class documentation for Widget above for a note about ownership. - InitParams::Ownership ownership_; - - // See set_is_secondary_widget(). - bool is_secondary_widget_; - - // The current frame type in use by this window. Defaults to - // FRAME_TYPE_DEFAULT. - FrameType frame_type_; - - // True when the window should be rendered as active, regardless of whether - // or not it actually is. - bool disable_inactive_rendering_; - - // Set to true if the widget is in the process of closing. - bool widget_closed_; - - // The saved "show" state for this window. See note in SetInitialBounds - // that explains why we save this. - ui::WindowShowState saved_show_state_; - - // The restored bounds used for the initial show. This is only used if - // |saved_show_state_| is maximized. - gfx::Rect initial_restored_bounds_; - - // Focus is automatically set to the view provided by the delegate - // when the widget is shown. Set this value to false to override - // initial focus for the widget. - bool focus_on_creation_; - - mutable scoped_ptr<InputMethod> input_method_; - - // See |is_top_level()| accessor. - bool is_top_level_; - - // Tracks whether native widget has been initialized. - bool native_widget_initialized_; - - // Whether native widget has been destroyed. - bool native_widget_destroyed_; - - // True if capture losses should be ignored. - bool ignore_capture_loss_; - - // The following are used to detect duplicate mouse move events and not - // deliver them. Displaying a window may result in the system generating - // duplicate move events even though the mouse hasn't moved. - // TODO(tdanderson): We may be able to remove these members. - bool last_mouse_event_was_move_; - gfx::Point last_mouse_event_position_; - - // True if event capture should be released on a mouse up event. Default is - // true. - bool auto_release_capture_; - - // See description in GetRootLayers(). - std::vector<ui::Layer*> root_layers_; - - // Is |root_layers_| out of date? - bool root_layers_dirty_; - - // True when window movement via mouse interaction with the frame should be - // disabled. - bool movement_disabled_; - - ScopedObserver<ui::NativeTheme, ui::NativeThemeObserver> observer_manager_; - - DISALLOW_COPY_AND_ASSIGN(Widget); -}; - -} // namespace views - -#endif // UI_VIEWS_WIDGET_WIDGET_H_
diff --git a/ui/views/widget/widget_aura_utils.cc b/ui/views/widget/widget_aura_utils.cc deleted file mode 100644 index be284a8..0000000 --- a/ui/views/widget/widget_aura_utils.cc +++ /dev/null
@@ -1,35 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/widget/widget_aura_utils.h" - -#include "base/logging.h" - -namespace views { - -ui::wm::WindowType GetAuraWindowTypeForWidgetType( - Widget::InitParams::Type type) { - switch (type) { - case Widget::InitParams::TYPE_WINDOW: - return ui::wm::WINDOW_TYPE_NORMAL; - case Widget::InitParams::TYPE_PANEL: - return ui::wm::WINDOW_TYPE_PANEL; - case Widget::InitParams::TYPE_CONTROL: - return ui::wm::WINDOW_TYPE_CONTROL; - case Widget::InitParams::TYPE_WINDOW_FRAMELESS: - case Widget::InitParams::TYPE_POPUP: - case Widget::InitParams::TYPE_BUBBLE: - case Widget::InitParams::TYPE_DRAG: - return ui::wm::WINDOW_TYPE_POPUP; - case Widget::InitParams::TYPE_MENU: - return ui::wm::WINDOW_TYPE_MENU; - case Widget::InitParams::TYPE_TOOLTIP: - return ui::wm::WINDOW_TYPE_TOOLTIP; - default: - NOTREACHED() << "Unhandled widget type " << type; - return ui::wm::WINDOW_TYPE_UNKNOWN; - } -} - -} // namespace views
diff --git a/ui/views/widget/widget_aura_utils.h b/ui/views/widget/widget_aura_utils.h deleted file mode 100644 index 4b16de4..0000000 --- a/ui/views/widget/widget_aura_utils.h +++ /dev/null
@@ -1,20 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_WIDGET_WIDGET_AURA_UTILS_H_ -#define UI_VIEWS_WIDGET_WIDGET_AURA_UTILS_H_ - -#include "ui/views/widget/widget.h" -#include "ui/wm/public/window_types.h" - -// Functions shared by native_widget_aura.cc and desktop_native_widget_aura.cc: - -namespace views { - -ui::wm::WindowType GetAuraWindowTypeForWidgetType( - Widget::InitParams::Type type); - -} // namespace views - -#endif // UI_VIEWS_WIDGET_WIDGET_AURA_UTILS_H_
diff --git a/ui/views/widget/widget_delegate.cc b/ui/views/widget/widget_delegate.cc deleted file mode 100644 index 18643b7..0000000 --- a/ui/views/widget/widget_delegate.cc +++ /dev/null
@@ -1,205 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/widget/widget_delegate.h" - -#include "base/strings/utf_string_conversions.h" -#include "ui/gfx/image/image_skia.h" -#include "ui/views/bubble/bubble_delegate.h" -#include "ui/views/view.h" -#include "ui/views/views_delegate.h" -#include "ui/views/widget/widget.h" -#include "ui/views/window/client_view.h" - -namespace views { - -//////////////////////////////////////////////////////////////////////////////// -// WidgetDelegate: - -WidgetDelegate::WidgetDelegate() - : default_contents_view_(NULL), - can_activate_(true) { -} - -void WidgetDelegate::OnWidgetMove() { -} - -void WidgetDelegate::OnDisplayChanged() { -} - -void WidgetDelegate::OnWorkAreaChanged() { -} - -View* WidgetDelegate::GetInitiallyFocusedView() { - return NULL; -} - -BubbleDelegateView* WidgetDelegate::AsBubbleDelegate() { - return NULL; -} - -DialogDelegate* WidgetDelegate::AsDialogDelegate() { - return NULL; -} - -bool WidgetDelegate::CanResize() const { - return false; -} - -bool WidgetDelegate::CanMaximize() const { - return false; -} - -bool WidgetDelegate::CanMinimize() const { - return false; -} - -bool WidgetDelegate::CanActivate() const { - return can_activate_; -} - -ui::ModalType WidgetDelegate::GetModalType() const { - return ui::MODAL_TYPE_NONE; -} - -ui::AXRole WidgetDelegate::GetAccessibleWindowRole() const { - return ui::AX_ROLE_WINDOW; -} - -base::string16 WidgetDelegate::GetAccessibleWindowTitle() const { - return GetWindowTitle(); -} - -base::string16 WidgetDelegate::GetWindowTitle() const { - return base::string16(); -} - -bool WidgetDelegate::ShouldShowWindowTitle() const { - return true; -} - -bool WidgetDelegate::ShouldShowCloseButton() const { - return true; -} - -bool WidgetDelegate::ShouldHandleSystemCommands() const { - const Widget* widget = GetWidget(); - if (!widget) - return false; - - return widget->non_client_view() != NULL; -} - -gfx::ImageSkia WidgetDelegate::GetWindowAppIcon() { - // Use the window icon as app icon by default. - return GetWindowIcon(); -} - -// Returns the icon to be displayed in the window. -gfx::ImageSkia WidgetDelegate::GetWindowIcon() { - return gfx::ImageSkia(); -} - -bool WidgetDelegate::ShouldShowWindowIcon() const { - return false; -} - -bool WidgetDelegate::ExecuteWindowsCommand(int command_id) { - return false; -} - -std::string WidgetDelegate::GetWindowName() const { - return std::string(); -} - -void WidgetDelegate::SaveWindowPlacement(const gfx::Rect& bounds, - ui::WindowShowState show_state) { - std::string window_name = GetWindowName(); - if (!ViewsDelegate::views_delegate || window_name.empty()) - return; - - ViewsDelegate::views_delegate->SaveWindowPlacement( - GetWidget(), window_name, bounds, show_state); -} - -bool WidgetDelegate::GetSavedWindowPlacement( - const Widget* widget, - gfx::Rect* bounds, - ui::WindowShowState* show_state) const { - std::string window_name = GetWindowName(); - if (!ViewsDelegate::views_delegate || window_name.empty()) - return false; - - return ViewsDelegate::views_delegate->GetSavedWindowPlacement( - widget, window_name, bounds, show_state); -} - -bool WidgetDelegate::ShouldRestoreWindowSize() const { - return true; -} - -View* WidgetDelegate::GetContentsView() { - if (!default_contents_view_) - default_contents_view_ = new View; - return default_contents_view_; -} - -ClientView* WidgetDelegate::CreateClientView(Widget* widget) { - return new ClientView(widget, GetContentsView()); -} - -NonClientFrameView* WidgetDelegate::CreateNonClientFrameView(Widget* widget) { - return NULL; -} - -View* WidgetDelegate::CreateOverlayView() { - return NULL; -} - -bool WidgetDelegate::WillProcessWorkAreaChange() const { - return false; -} - -bool WidgetDelegate::WidgetHasHitTestMask() const { - return false; -} - -void WidgetDelegate::GetWidgetHitTestMask(gfx::Path* mask) const { - DCHECK(mask); -} - -bool WidgetDelegate::ShouldAdvanceFocusToTopLevelWidget() const { - return false; -} - -bool WidgetDelegate::ShouldDescendIntoChildForEventHandling( - gfx::NativeView child, - const gfx::Point& location) { - return true; -} - -//////////////////////////////////////////////////////////////////////////////// -// WidgetDelegateView: - -WidgetDelegateView::WidgetDelegateView() { - // A WidgetDelegate should be deleted on DeleteDelegate. - set_owned_by_client(); -} - -WidgetDelegateView::~WidgetDelegateView() { -} - -void WidgetDelegateView::DeleteDelegate() { - delete this; -} - -Widget* WidgetDelegateView::GetWidget() { - return View::GetWidget(); -} - -const Widget* WidgetDelegateView::GetWidget() const { - return View::GetWidget(); -} - -} // namespace views
diff --git a/ui/views/widget/widget_delegate.h b/ui/views/widget/widget_delegate.h deleted file mode 100644 index 3f67cb4..0000000 --- a/ui/views/widget/widget_delegate.h +++ /dev/null
@@ -1,217 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_WIDGET_WIDGET_DELEGATE_H_ -#define UI_VIEWS_WIDGET_WIDGET_DELEGATE_H_ - -#include <string> -#include <vector> - -#include "ui/accessibility/ax_enums.h" -#include "ui/base/ui_base_types.h" -#include "ui/views/view.h" - -namespace gfx { -class ImageSkia; -class Rect; -} - -namespace views { -class BubbleDelegateView; -class ClientView; -class DialogDelegate; -class NonClientFrameView; -class View; -class Widget; - -// Handles events on Widgets in context-specific ways. -class VIEWS_EXPORT WidgetDelegate { - public: - WidgetDelegate(); - - // Sets the return value of CanActivate(). Default is true. - void set_can_activate(bool can_activate) { - can_activate_ = can_activate; - } - - // Called whenever the widget's position changes. - virtual void OnWidgetMove(); - - // Called with the display changes (color depth or resolution). - virtual void OnDisplayChanged(); - - // Called when the work area (the desktop area minus task bars, - // menu bars, etc.) changes in size. - virtual void OnWorkAreaChanged(); - - // Returns the view that should have the focus when the widget is shown. If - // NULL no view is focused. - virtual View* GetInitiallyFocusedView(); - - virtual BubbleDelegateView* AsBubbleDelegate(); - virtual DialogDelegate* AsDialogDelegate(); - - // Returns true if the window can be resized. - virtual bool CanResize() const; - - // Returns true if the window can be maximized. - virtual bool CanMaximize() const; - - // Returns true if the window can be minimized. - virtual bool CanMinimize() const; - - // Returns true if the window can be activated. - virtual bool CanActivate() const; - - // Returns the modal type that applies to the widget. Default is - // ui::MODAL_TYPE_NONE (not modal). - virtual ui::ModalType GetModalType() const; - - virtual ui::AXRole GetAccessibleWindowRole() const; - - // Returns the title to be read with screen readers. - virtual base::string16 GetAccessibleWindowTitle() const; - - // Returns the text to be displayed in the window title. - virtual base::string16 GetWindowTitle() const; - - // Returns true if the window should show a title in the title bar. - virtual bool ShouldShowWindowTitle() const; - - // Returns true if the window should show a close button in the title bar. - virtual bool ShouldShowCloseButton() const; - - // Returns true if the window should handle standard system commands, such as - // close, minimize, maximize. - virtual bool ShouldHandleSystemCommands() const; - - // Returns the app icon for the window. On Windows, this is the ICON_BIG used - // in Alt-Tab list and Win7's taskbar. - virtual gfx::ImageSkia GetWindowAppIcon(); - - // Returns the icon to be displayed in the window. - virtual gfx::ImageSkia GetWindowIcon(); - - // Returns true if a window icon should be shown. - virtual bool ShouldShowWindowIcon() const; - - // Execute a command in the window's controller. Returns true if the command - // was handled, false if it was not. - virtual bool ExecuteWindowsCommand(int command_id); - - // Returns the window's name identifier. Used to identify this window for - // state restoration. - virtual std::string GetWindowName() const; - - // Saves the window's bounds and "show" state. By default this uses the - // process' local state keyed by window name (See GetWindowName above). This - // behavior can be overridden to provide additional functionality. - virtual void SaveWindowPlacement(const gfx::Rect& bounds, - ui::WindowShowState show_state); - - // Retrieves the window's bounds and "show" states. - // This behavior can be overridden to provide additional functionality. - virtual bool GetSavedWindowPlacement(const Widget* widget, - gfx::Rect* bounds, - ui::WindowShowState* show_state) const; - - // Returns true if the window's size should be restored. If this is false, - // only the window's origin is restored and the window is given its - // preferred size. - // Default is true. - virtual bool ShouldRestoreWindowSize() const; - - // Called when the window closes. The delegate MUST NOT delete itself during - // this call, since it can be called afterwards. See DeleteDelegate(). - virtual void WindowClosing() {} - - // Called when the window is destroyed. No events must be sent or received - // after this point. The delegate can use this opportunity to delete itself at - // this time if necessary. - virtual void DeleteDelegate() {} - - // Called when the user begins/ends to change the bounds of the window. - virtual void OnWindowBeginUserBoundsChange() {} - virtual void OnWindowEndUserBoundsChange() {} - - // Returns the Widget associated with this delegate. - virtual Widget* GetWidget() = 0; - virtual const Widget* GetWidget() const = 0; - - // Returns the View that is contained within this Widget. - virtual View* GetContentsView(); - - // Called by the Widget to create the Client View used to host the contents - // of the widget. - virtual ClientView* CreateClientView(Widget* widget); - - // Called by the Widget to create the NonClient Frame View for this widget. - // Return NULL to use the default one. - virtual NonClientFrameView* CreateNonClientFrameView(Widget* widget); - - // Called by the Widget to create the overlay View for this widget. Return - // NULL for no overlay. The overlay View will fill the Widget and sit on top - // of the ClientView and NonClientFrameView (both visually and wrt click - // targeting). - virtual View* CreateOverlayView(); - - // Returns true if the window can be notified with the work area change. - // Otherwise, the work area change for the top window will be processed by - // the default window manager. In some cases, like panel, we would like to - // manage the positions by ourselves. - virtual bool WillProcessWorkAreaChange() const; - - // Returns true if window has a hit-test mask. - virtual bool WidgetHasHitTestMask() const; - - // Provides the hit-test mask if HasHitTestMask above returns true. - virtual void GetWidgetHitTestMask(gfx::Path* mask) const; - - // Returns true if focus should advance to the top level widget when - // tab/shift-tab is hit and on the last/first focusable view. Default returns - // false, which means tab/shift-tab never advance to the top level Widget. - virtual bool ShouldAdvanceFocusToTopLevelWidget() const; - - // Returns true if event handling should descend into |child|. - // |location| is in terms of the Window. - virtual bool ShouldDescendIntoChildForEventHandling( - gfx::NativeView child, - const gfx::Point& location); - - // Populates |panes| with accessible panes in this window that can - // be cycled through with keyboard focus. - virtual void GetAccessiblePanes(std::vector<View*>* panes) {} - - protected: - virtual ~WidgetDelegate() {} - - private: - View* default_contents_view_; - - bool can_activate_; - - DISALLOW_COPY_AND_ASSIGN(WidgetDelegate); -}; - -// A WidgetDelegate implementation that is-a View. Used to override GetWidget() -// to call View's GetWidget() for the common case where a WidgetDelegate -// implementation is-a View. Note that WidgetDelegateView is not owned by -// view's hierarchy and is expected to be deleted on DeleteDelegate call. -class VIEWS_EXPORT WidgetDelegateView : public WidgetDelegate, public View { - public: - WidgetDelegateView(); - virtual ~WidgetDelegateView(); - - // Overridden from WidgetDelegate: - virtual void DeleteDelegate() override; - virtual Widget* GetWidget() override; - virtual const Widget* GetWidget() const override; - - private: - DISALLOW_COPY_AND_ASSIGN(WidgetDelegateView); -}; - -} // namespace views - -#endif // UI_VIEWS_WIDGET_WIDGET_DELEGATE_H_
diff --git a/ui/views/widget/widget_deletion_observer.cc b/ui/views/widget/widget_deletion_observer.cc deleted file mode 100644 index db3a44e..0000000 --- a/ui/views/widget/widget_deletion_observer.cc +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/widget/widget_deletion_observer.h" - -#include "ui/views/widget/widget.h" - -namespace views { - -WidgetDeletionObserver::WidgetDeletionObserver(Widget* widget) - : widget_(widget) { - if (widget_) - widget_->AddObserver(this); -} - -WidgetDeletionObserver::~WidgetDeletionObserver() { - CleanupWidget(); -} - -void WidgetDeletionObserver::OnWidgetDestroying(Widget* widget) { - CleanupWidget(); -} - -void WidgetDeletionObserver::CleanupWidget() { - if (widget_) { - widget_->RemoveObserver(this); - widget_ = NULL; - } -} - -} // namespace views
diff --git a/ui/views/widget/widget_deletion_observer.h b/ui/views/widget/widget_deletion_observer.h deleted file mode 100644 index 785e132..0000000 --- a/ui/views/widget/widget_deletion_observer.h +++ /dev/null
@@ -1,38 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_WIDGET_WIDGET_DELETION_OBSERVER_H_ -#define UI_VIEWS_WIDGET_WIDGET_DELETION_OBSERVER_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "ui/views/views_export.h" -#include "ui/views/widget/widget_observer.h" - -namespace views { -class Widget; - -// A simple WidgetObserver that can be probed for the life of a widget. -class VIEWS_EXPORT WidgetDeletionObserver : public WidgetObserver { - public: - explicit WidgetDeletionObserver(Widget* widget); - virtual ~WidgetDeletionObserver(); - - // Returns true if the widget passed in the constructor is still alive. - bool IsWidgetAlive() { return widget_ != NULL; } - - // Overridden from WidgetObserver. - virtual void OnWidgetDestroying(Widget* widget) override; - - private: - void CleanupWidget(); - - Widget* widget_; - - DISALLOW_COPY_AND_ASSIGN(WidgetDeletionObserver); -}; - -} // namespace views - -#endif // UI_VIEWS_WIDGET_WIDGET_DELETION_OBSERVER_H_
diff --git a/ui/views/widget/widget_hwnd_utils.cc b/ui/views/widget/widget_hwnd_utils.cc deleted file mode 100644 index 29f6ce0..0000000 --- a/ui/views/widget/widget_hwnd_utils.cc +++ /dev/null
@@ -1,167 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/widget/widget_hwnd_utils.h" - -#include <dwmapi.h> - -#include "base/command_line.h" -#include "base/win/windows_version.h" -#include "ui/base/l10n/l10n_util_win.h" -#include "ui/base/ui_base_switches.h" -#include "ui/views/widget/widget_delegate.h" -#include "ui/views/win/hwnd_message_handler.h" - -#if defined(OS_WIN) -#include "ui/base/win/shell.h" -#endif - -namespace views { - -namespace { - -void CalculateWindowStylesFromInitParams( - const Widget::InitParams& params, - WidgetDelegate* widget_delegate, - internal::NativeWidgetDelegate* native_widget_delegate, - DWORD* style, - DWORD* ex_style, - DWORD* class_style) { - *style = WS_CLIPCHILDREN | WS_CLIPSIBLINGS; - *ex_style = 0; - *class_style = CS_DBLCLKS; - - // Set type-independent style attributes. - if (params.child) - *style |= WS_CHILD; - if (params.show_state == ui::SHOW_STATE_MAXIMIZED) - *style |= WS_MAXIMIZE; - if (params.show_state == ui::SHOW_STATE_MINIMIZED) - *style |= WS_MINIMIZE; - if (!params.accept_events) - *ex_style |= WS_EX_TRANSPARENT; - DCHECK_NE(Widget::InitParams::ACTIVATABLE_DEFAULT, params.activatable); - if (params.activatable == Widget::InitParams::ACTIVATABLE_NO) - *ex_style |= WS_EX_NOACTIVATE; - if (params.keep_on_top) - *ex_style |= WS_EX_TOPMOST; - if (params.mirror_origin_in_rtl) - *ex_style |= l10n_util::GetExtendedTooltipStyles(); - // Layered windows do not work with Aura. They are basically incompatible - // with Direct3D surfaces. Officially, it should be impossible to achieve - // per-pixel alpha compositing with the desktop and 3D acceleration but it - // has been discovered that since Vista There is a secret handshake between - // user32 and the DMW. If things are set up just right DMW gets out of the - // way; it does not create a backbuffer and simply blends our D3D surface - // and the desktop background. The handshake is as follows: - // 1- Use D3D9Ex to create device/swapchain, etc. You need D3DFMT_A8R8G8B8. - // 2- The window must have WS_EX_COMPOSITED in the extended style. - // 3- The window must have WS_POPUP in its style. - // 4- The windows must not have WM_SIZEBOX, WS_THICKFRAME or WS_CAPTION in its - // style. - // 5- When the window is created but before it is presented, call - // DwmExtendFrameIntoClientArea passing -1 as the margins. - if (params.opacity == Widget::InitParams::TRANSLUCENT_WINDOW) { - if (ui::win::IsAeroGlassEnabled()) - *ex_style |= WS_EX_COMPOSITED; - } - if (params.shadow_type == Widget::InitParams::SHADOW_TYPE_DROP) { - *class_style |= (base::win::GetVersion() < base::win::VERSION_XP) ? - 0 : CS_DROPSHADOW; - } - - // Set type-dependent style attributes. - switch (params.type) { - case Widget::InitParams::TYPE_PANEL: - *ex_style |= WS_EX_TOPMOST; - if (params.remove_standard_frame) { - *style |= WS_POPUP; - break; - } - // Else, no break. Fall through to TYPE_WINDOW. - case Widget::InitParams::TYPE_WINDOW: { - // WS_OVERLAPPEDWINDOW is equivalent to: - // WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | - // WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX - *style |= WS_OVERLAPPEDWINDOW; - if (!widget_delegate->CanMaximize()) - *style &= ~WS_MAXIMIZEBOX; - if (!widget_delegate->CanMinimize()) - *style &= ~WS_MINIMIZEBOX; - if (!widget_delegate->CanResize()) - *style &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX); - if (params.remove_standard_frame) - *style &= ~(WS_MINIMIZEBOX | WS_MAXIMIZEBOX); - - if (native_widget_delegate->IsDialogBox()) { - *style |= DS_MODALFRAME; - // NOTE: Turning this off means we lose the close button, which is bad. - // Turning it on though means the user can maximize or size the window - // from the system menu, which is worse. We may need to provide our own - // menu to get the close button to appear properly. - // style &= ~WS_SYSMENU; - - // Set the WS_POPUP style for modal dialogs. This ensures that the owner - // window is activated on destruction. This style should not be set for - // non-modal non-top-level dialogs like constrained windows. - *style |= native_widget_delegate->IsModal() ? WS_POPUP : 0; - } - *ex_style |= - native_widget_delegate->IsDialogBox() ? WS_EX_DLGMODALFRAME : 0; - - // See layered window comment above. - if (*ex_style & WS_EX_COMPOSITED) - *style &= ~(WS_THICKFRAME | WS_CAPTION); - break; - } - case Widget::InitParams::TYPE_CONTROL: - *style |= WS_VISIBLE; - break; - case Widget::InitParams::TYPE_WINDOW_FRAMELESS: - *style |= WS_POPUP; - break; - case Widget::InitParams::TYPE_BUBBLE: - *style |= WS_POPUP; - *style |= WS_CLIPCHILDREN; - if (!params.force_show_in_taskbar) - *ex_style |= WS_EX_TOOLWINDOW; - break; - case Widget::InitParams::TYPE_POPUP: - *style |= WS_POPUP; - if (!params.force_show_in_taskbar) - *ex_style |= WS_EX_TOOLWINDOW; - break; - case Widget::InitParams::TYPE_MENU: - *style |= WS_POPUP; - break; - default: - NOTREACHED(); - } -} - -} // namespace - -bool DidClientAreaSizeChange(const WINDOWPOS* window_pos) { - return !(window_pos->flags & SWP_NOSIZE) || - window_pos->flags & SWP_FRAMECHANGED; -} - -void ConfigureWindowStyles( - HWNDMessageHandler* handler, - const Widget::InitParams& params, - WidgetDelegate* widget_delegate, - internal::NativeWidgetDelegate* native_widget_delegate) { - // Configure the HWNDMessageHandler with the appropriate - DWORD style = 0; - DWORD ex_style = 0; - DWORD class_style = 0; - CalculateWindowStylesFromInitParams(params, widget_delegate, - native_widget_delegate, &style, &ex_style, - &class_style); - handler->set_initial_class_style(class_style); - handler->set_window_style(handler->window_style() | style); - handler->set_window_ex_style(handler->window_ex_style() | ex_style); -} - -} // namespace views
diff --git a/ui/views/widget/widget_hwnd_utils.h b/ui/views/widget/widget_hwnd_utils.h deleted file mode 100644 index 09ee0ab..0000000 --- a/ui/views/widget/widget_hwnd_utils.h +++ /dev/null
@@ -1,36 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_WIDGET_WIDGET_HWND_UTILS_H_ -#define UI_VIEWS_WIDGET_WIDGET_HWND_UTILS_H_ - -#include <windows.h> - -#include "ui/views/widget/widget.h" - -// Functions shared by hwnd_message_handler.cc and -// desktop_window_tree_host_win.cc: - -namespace views { -class HWNDMessageHandler; -class WidgetDelegate; -namespace internal { -class NativeWidgetDelegate; -} - -// Returns true if the WINDOWPOS data provided indicates the client area of -// the window may have changed size. This can be caused by the window being -// resized or its frame changing. -bool DidClientAreaSizeChange(const WINDOWPOS* window_pos); - -// Sets styles appropriate for |params| on |handler|. -void ConfigureWindowStyles( - HWNDMessageHandler* handler, - const Widget::InitParams& params, - WidgetDelegate* widget_delegate, - internal::NativeWidgetDelegate* native_widget_delegate); - -} // namespace views - -#endif // UI_VIEWS_WIDGET_WIDGET_HWND_UTILS_H_
diff --git a/ui/views/widget/widget_interactive_uitest.cc b/ui/views/widget/widget_interactive_uitest.cc deleted file mode 100644 index 681f1d1..0000000 --- a/ui/views/widget/widget_interactive_uitest.cc +++ /dev/null
@@ -1,1157 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/basictypes.h" -#include "base/bind.h" -#include "base/command_line.h" -#include "base/path_service.h" -#include "base/run_loop.h" -#include "base/strings/stringprintf.h" -#include "base/strings/utf_string_conversions.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/base/ui_base_paths.h" -#include "ui/base/ui_base_switches.h" -#include "ui/events/event_processor.h" -#include "ui/events/test/event_generator.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/gl/gl_surface.h" -#include "ui/views/controls/textfield/textfield.h" -#include "ui/views/controls/textfield/textfield_test_api.h" -#include "ui/views/focus/focus_manager.h" -#include "ui/views/test/focus_manager_test.h" -#include "ui/views/test/widget_test.h" -#include "ui/views/touchui/touch_selection_controller_impl.h" -#include "ui/views/widget/widget.h" -#include "ui/views/window/dialog_delegate.h" -#include "ui/wm/public/activation_client.h" - -#if defined(OS_WIN) -#include "ui/aura/window.h" -#include "ui/aura/window_tree_host.h" -#include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" -#include "ui/views/win/hwnd_util.h" -#endif - -namespace views { -namespace test { - -namespace { - -// A View that closes the Widget and exits the current message-loop when it -// receives a mouse-release event. -class ExitLoopOnRelease : public View { - public: - ExitLoopOnRelease() {} - virtual ~ExitLoopOnRelease() {} - - private: - // Overridden from View: - virtual void OnMouseReleased(const ui::MouseEvent& event) override { - GetWidget()->Close(); - base::MessageLoop::current()->QuitNow(); - } - - DISALLOW_COPY_AND_ASSIGN(ExitLoopOnRelease); -}; - -// A view that does a capture on ui::ET_GESTURE_TAP_DOWN events. -class GestureCaptureView : public View { - public: - GestureCaptureView() {} - virtual ~GestureCaptureView() {} - - private: - // Overridden from View: - virtual void OnGestureEvent(ui::GestureEvent* event) override { - if (event->type() == ui::ET_GESTURE_TAP_DOWN) { - GetWidget()->SetCapture(this); - event->StopPropagation(); - } - } - - DISALLOW_COPY_AND_ASSIGN(GestureCaptureView); -}; - -// A view that always processes all mouse events. -class MouseView : public View { - public: - MouseView() - : View(), - entered_(0), - exited_(0), - pressed_(0) { - } - virtual ~MouseView() {} - - virtual bool OnMousePressed(const ui::MouseEvent& event) override { - pressed_++; - return true; - } - - virtual void OnMouseEntered(const ui::MouseEvent& event) override { - entered_++; - } - - virtual void OnMouseExited(const ui::MouseEvent& event) override { - exited_++; - } - - // Return the number of OnMouseEntered calls and reset the counter. - int EnteredCalls() { - int i = entered_; - entered_ = 0; - return i; - } - - // Return the number of OnMouseExited calls and reset the counter. - int ExitedCalls() { - int i = exited_; - exited_ = 0; - return i; - } - - int pressed() const { return pressed_; } - - private: - int entered_; - int exited_; - - int pressed_; - - DISALLOW_COPY_AND_ASSIGN(MouseView); -}; - -// A View that shows a different widget, sets capture on that widget, and -// initiates a nested message-loop when it receives a mouse-press event. -class NestedLoopCaptureView : public View { - public: - explicit NestedLoopCaptureView(Widget* widget) : widget_(widget) {} - virtual ~NestedLoopCaptureView() {} - - private: - // Overridden from View: - virtual bool OnMousePressed(const ui::MouseEvent& event) override { - // Start a nested loop. - widget_->Show(); - widget_->SetCapture(widget_->GetContentsView()); - EXPECT_TRUE(widget_->HasCapture()); - - base::MessageLoopForUI* loop = base::MessageLoopForUI::current(); - base::MessageLoop::ScopedNestableTaskAllower allow(loop); - - base::RunLoop run_loop; - run_loop.Run(); - return true; - } - - Widget* widget_; - - DISALLOW_COPY_AND_ASSIGN(NestedLoopCaptureView); -}; - -} // namespace - -class WidgetTestInteractive : public WidgetTest { - public: - WidgetTestInteractive() {} - virtual ~WidgetTestInteractive() {} - - virtual void SetUp() override { - gfx::GLSurface::InitializeOneOffForTests(); - ui::RegisterPathProvider(); - base::FilePath ui_test_pak_path; - ASSERT_TRUE(PathService::Get(ui::UI_TEST_PAK, &ui_test_pak_path)); - ui::ResourceBundle::InitSharedInstanceWithPakPath(ui_test_pak_path); - WidgetTest::SetUp(); - } - - protected: - static void ShowQuickMenuImmediately( - TouchSelectionControllerImpl* controller) { - DCHECK(controller); - if (controller->context_menu_timer_.IsRunning()) { - controller->context_menu_timer_.Stop(); -// TODO(tapted): Enable this when porting ui/views/touchui to Mac. -#if !defined(OS_MACOSX) - controller->ContextMenuTimerFired(); -#endif - } - } - - static bool IsQuickMenuVisible(TouchSelectionControllerImpl* controller) { - DCHECK(controller); - return controller->context_menu_ && controller->context_menu_->visible(); - } -}; - -#if defined(OS_WIN) -// Tests whether activation and focus change works correctly in Windows. -// We test the following:- -// 1. If the active aura window is correctly set when a top level widget is -// created. -// 2. If the active aura window in widget 1 created above, is set to NULL when -// another top level widget is created and focused. -// 3. On focusing the native platform window for widget 1, the active aura -// window for widget 1 should be set and that for widget 2 should reset. -// TODO(ananta): Discuss with erg on how to write this test for linux x11 aura. -TEST_F(WidgetTestInteractive, DesktopNativeWidgetAuraActivationAndFocusTest) { - // Create widget 1 and expect the active window to be its window. - View* contents_view1 = new View; - contents_view1->SetFocusable(true); - Widget widget1; - Widget::InitParams init_params = - CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); - init_params.bounds = gfx::Rect(0, 0, 200, 200); - init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - init_params.native_widget = new DesktopNativeWidgetAura(&widget1); - widget1.Init(init_params); - widget1.SetContentsView(contents_view1); - widget1.Show(); - aura::Window* root_window1= widget1.GetNativeView()->GetRootWindow(); - contents_view1->RequestFocus(); - - EXPECT_TRUE(root_window1 != NULL); - aura::client::ActivationClient* activation_client1 = - aura::client::GetActivationClient(root_window1); - EXPECT_TRUE(activation_client1 != NULL); - EXPECT_EQ(activation_client1->GetActiveWindow(), widget1.GetNativeView()); - - // Create widget 2 and expect the active window to be its window. - View* contents_view2 = new View; - Widget widget2; - Widget::InitParams init_params2 = - CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); - init_params2.bounds = gfx::Rect(0, 0, 200, 200); - init_params2.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - init_params2.native_widget = new DesktopNativeWidgetAura(&widget2); - widget2.Init(init_params2); - widget2.SetContentsView(contents_view2); - widget2.Show(); - aura::Window* root_window2 = widget2.GetNativeView()->GetRootWindow(); - contents_view2->RequestFocus(); - ::SetActiveWindow( - root_window2->GetHost()->GetAcceleratedWidget()); - - aura::client::ActivationClient* activation_client2 = - aura::client::GetActivationClient(root_window2); - EXPECT_TRUE(activation_client2 != NULL); - EXPECT_EQ(activation_client2->GetActiveWindow(), widget2.GetNativeView()); - EXPECT_EQ(activation_client1->GetActiveWindow(), - reinterpret_cast<aura::Window*>(NULL)); - - // Now set focus back to widget 1 and expect the active window to be its - // window. - contents_view1->RequestFocus(); - ::SetActiveWindow( - root_window1->GetHost()->GetAcceleratedWidget()); - EXPECT_EQ(activation_client2->GetActiveWindow(), - reinterpret_cast<aura::Window*>(NULL)); - EXPECT_EQ(activation_client1->GetActiveWindow(), widget1.GetNativeView()); -} -#endif // defined(OS_WIN) - -TEST_F(WidgetTestInteractive, CaptureAutoReset) { - Widget* toplevel = CreateTopLevelFramelessPlatformWidget(); - View* container = new View; - toplevel->SetContentsView(container); - - EXPECT_FALSE(toplevel->HasCapture()); - toplevel->SetCapture(NULL); - EXPECT_TRUE(toplevel->HasCapture()); - - // By default, mouse release removes capture. - gfx::Point click_location(45, 15); - ui::MouseEvent release(ui::ET_MOUSE_RELEASED, click_location, click_location, - ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); - toplevel->OnMouseEvent(&release); - EXPECT_FALSE(toplevel->HasCapture()); - - // Now a mouse release shouldn't remove capture. - toplevel->set_auto_release_capture(false); - toplevel->SetCapture(NULL); - EXPECT_TRUE(toplevel->HasCapture()); - toplevel->OnMouseEvent(&release); - EXPECT_TRUE(toplevel->HasCapture()); - toplevel->ReleaseCapture(); - EXPECT_FALSE(toplevel->HasCapture()); - - toplevel->Close(); - RunPendingMessages(); -} - -TEST_F(WidgetTestInteractive, ResetCaptureOnGestureEnd) { - Widget* toplevel = CreateTopLevelFramelessPlatformWidget(); - View* container = new View; - toplevel->SetContentsView(container); - - View* gesture = new GestureCaptureView; - gesture->SetBounds(0, 0, 30, 30); - container->AddChildView(gesture); - - MouseView* mouse = new MouseView; - mouse->SetBounds(30, 0, 30, 30); - container->AddChildView(mouse); - - toplevel->SetSize(gfx::Size(100, 100)); - toplevel->Show(); - - // Start a gesture on |gesture|. - ui::GestureEvent tap_down(15, - 15, - 0, - base::TimeDelta(), - ui::GestureEventDetails(ui::ET_GESTURE_TAP_DOWN)); - ui::GestureEvent end(15, - 15, - 0, - base::TimeDelta(), - ui::GestureEventDetails(ui::ET_GESTURE_END)); - toplevel->OnGestureEvent(&tap_down); - - // Now try to click on |mouse|. Since |gesture| will have capture, |mouse| - // will not receive the event. - gfx::Point click_location(45, 15); - - ui::MouseEvent press(ui::ET_MOUSE_PRESSED, click_location, click_location, - ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); - ui::MouseEvent release(ui::ET_MOUSE_RELEASED, click_location, click_location, - ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); - - EXPECT_TRUE(toplevel->HasCapture()); - - toplevel->OnMouseEvent(&press); - toplevel->OnMouseEvent(&release); - EXPECT_EQ(0, mouse->pressed()); - - EXPECT_FALSE(toplevel->HasCapture()); - - // The end of the gesture should release the capture, and pressing on |mouse| - // should now reach |mouse|. - toplevel->OnGestureEvent(&end); - toplevel->OnMouseEvent(&press); - toplevel->OnMouseEvent(&release); - EXPECT_EQ(1, mouse->pressed()); - - toplevel->Close(); - RunPendingMessages(); -} - -// Checks that if a mouse-press triggers a capture on a different widget (which -// consumes the mouse-release event), then the target of the press does not have -// capture. -TEST_F(WidgetTestInteractive, DisableCaptureWidgetFromMousePress) { - // The test creates two widgets: |first| and |second|. - // The View in |first| makes |second| visible, sets capture on it, and starts - // a nested loop (like a menu does). The View in |second| terminates the - // nested loop and closes the widget. - // The test sends a mouse-press event to |first|, and posts a task to send a - // release event to |second|, to make sure that the release event is - // dispatched after the nested loop starts. - - Widget* first = CreateTopLevelFramelessPlatformWidget(); - Widget* second = CreateTopLevelFramelessPlatformWidget(); - - View* container = new NestedLoopCaptureView(second); - first->SetContentsView(container); - - second->SetContentsView(new ExitLoopOnRelease()); - - first->SetSize(gfx::Size(100, 100)); - first->Show(); - - gfx::Point location(20, 20); - base::MessageLoop::current()->PostTask(FROM_HERE, - base::Bind(&Widget::OnMouseEvent, - base::Unretained(second), - base::Owned(new ui::MouseEvent(ui::ET_MOUSE_RELEASED, - location, - location, - ui::EF_LEFT_MOUSE_BUTTON, - ui::EF_LEFT_MOUSE_BUTTON)))); - ui::MouseEvent press(ui::ET_MOUSE_PRESSED, location, location, - ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); - first->OnMouseEvent(&press); - EXPECT_FALSE(first->HasCapture()); - first->Close(); - RunPendingMessages(); -} - -// Tests some grab/ungrab events. -// TODO(estade): can this be enabled now that this is an interactive ui test? -TEST_F(WidgetTestInteractive, DISABLED_GrabUngrab) { - Widget* toplevel = CreateTopLevelPlatformWidget(); - Widget* child1 = CreateChildNativeWidgetWithParent(toplevel); - Widget* child2 = CreateChildNativeWidgetWithParent(toplevel); - - toplevel->SetBounds(gfx::Rect(0, 0, 500, 500)); - - child1->SetBounds(gfx::Rect(10, 10, 300, 300)); - View* view = new MouseView(); - view->SetBounds(0, 0, 300, 300); - child1->GetRootView()->AddChildView(view); - - child2->SetBounds(gfx::Rect(200, 10, 200, 200)); - view = new MouseView(); - view->SetBounds(0, 0, 200, 200); - child2->GetRootView()->AddChildView(view); - - toplevel->Show(); - RunPendingMessages(); - - // Click on child1 - gfx::Point p1(45, 45); - ui::MouseEvent pressed(ui::ET_MOUSE_PRESSED, p1, p1, - ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); - toplevel->OnMouseEvent(&pressed); - - EXPECT_TRUE(toplevel->HasCapture()); - EXPECT_TRUE(child1->HasCapture()); - EXPECT_FALSE(child2->HasCapture()); - - ui::MouseEvent released(ui::ET_MOUSE_RELEASED, p1, p1, - ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); - toplevel->OnMouseEvent(&released); - - EXPECT_FALSE(toplevel->HasCapture()); - EXPECT_FALSE(child1->HasCapture()); - EXPECT_FALSE(child2->HasCapture()); - - RunPendingMessages(); - - // Click on child2 - gfx::Point p2(315, 45); - ui::MouseEvent pressed2(ui::ET_MOUSE_PRESSED, p2, p2, - ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); - toplevel->OnMouseEvent(&pressed2); - EXPECT_TRUE(pressed2.handled()); - EXPECT_TRUE(toplevel->HasCapture()); - EXPECT_TRUE(child2->HasCapture()); - EXPECT_FALSE(child1->HasCapture()); - - ui::MouseEvent released2(ui::ET_MOUSE_RELEASED, p2, p2, - ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); - toplevel->OnMouseEvent(&released2); - EXPECT_FALSE(toplevel->HasCapture()); - EXPECT_FALSE(child1->HasCapture()); - EXPECT_FALSE(child2->HasCapture()); - - toplevel->CloseNow(); -} - -// Tests mouse move outside of the window into the "resize controller" and back -// will still generate an OnMouseEntered and OnMouseExited event.. -TEST_F(WidgetTestInteractive, CheckResizeControllerEvents) { - Widget* toplevel = CreateTopLevelPlatformWidget(); - - toplevel->SetBounds(gfx::Rect(0, 0, 100, 100)); - - MouseView* view = new MouseView(); - view->SetBounds(90, 90, 10, 10); - toplevel->GetRootView()->AddChildView(view); - - toplevel->Show(); - RunPendingMessages(); - - // Move to an outside position. - gfx::Point p1(200, 200); - ui::MouseEvent moved_out(ui::ET_MOUSE_MOVED, p1, p1, ui::EF_NONE, - ui::EF_NONE); - toplevel->OnMouseEvent(&moved_out); - EXPECT_EQ(0, view->EnteredCalls()); - EXPECT_EQ(0, view->ExitedCalls()); - - // Move onto the active view. - gfx::Point p2(95, 95); - ui::MouseEvent moved_over(ui::ET_MOUSE_MOVED, p2, p2, ui::EF_NONE, - ui::EF_NONE); - toplevel->OnMouseEvent(&moved_over); - EXPECT_EQ(1, view->EnteredCalls()); - EXPECT_EQ(0, view->ExitedCalls()); - - // Move onto the outer resizing border. - gfx::Point p3(102, 95); - ui::MouseEvent moved_resizer(ui::ET_MOUSE_MOVED, p3, p3, ui::EF_NONE, - ui::EF_NONE); - toplevel->OnMouseEvent(&moved_resizer); - EXPECT_EQ(0, view->EnteredCalls()); - EXPECT_EQ(1, view->ExitedCalls()); - - // Move onto the view again. - toplevel->OnMouseEvent(&moved_over); - EXPECT_EQ(1, view->EnteredCalls()); - EXPECT_EQ(0, view->ExitedCalls()); - - RunPendingMessages(); - - toplevel->CloseNow(); -} - -// Test view focus restoration when a widget is deactivated and re-activated. -TEST_F(WidgetTestInteractive, ViewFocusOnWidgetActivationChanges) { - Widget* widget1 = CreateTopLevelPlatformWidget(); - View* view1 = new View; - view1->SetFocusable(true); - widget1->GetContentsView()->AddChildView(view1); - - Widget* widget2 = CreateTopLevelPlatformWidget(); - View* view2a = new View; - View* view2b = new View; - view2a->SetFocusable(true); - view2b->SetFocusable(true); - widget2->GetContentsView()->AddChildView(view2a); - widget2->GetContentsView()->AddChildView(view2b); - - widget1->Show(); - EXPECT_TRUE(widget1->IsActive()); - view1->RequestFocus(); - EXPECT_EQ(view1, widget1->GetFocusManager()->GetFocusedView()); - - widget2->Show(); - EXPECT_TRUE(widget2->IsActive()); - EXPECT_FALSE(widget1->IsActive()); - EXPECT_EQ(NULL, widget1->GetFocusManager()->GetFocusedView()); - view2a->RequestFocus(); - EXPECT_EQ(view2a, widget2->GetFocusManager()->GetFocusedView()); - view2b->RequestFocus(); - EXPECT_EQ(view2b, widget2->GetFocusManager()->GetFocusedView()); - - widget1->Activate(); - EXPECT_TRUE(widget1->IsActive()); - EXPECT_EQ(view1, widget1->GetFocusManager()->GetFocusedView()); - EXPECT_FALSE(widget2->IsActive()); - EXPECT_EQ(NULL, widget2->GetFocusManager()->GetFocusedView()); - - widget2->Activate(); - EXPECT_TRUE(widget2->IsActive()); - EXPECT_EQ(view2b, widget2->GetFocusManager()->GetFocusedView()); - EXPECT_FALSE(widget1->IsActive()); - EXPECT_EQ(NULL, widget1->GetFocusManager()->GetFocusedView()); - - widget1->CloseNow(); - widget2->CloseNow(); -} - -#if defined(OS_WIN) - -// Test view focus retention when a widget's HWND is disabled and re-enabled. -TEST_F(WidgetTestInteractive, ViewFocusOnHWNDEnabledChanges) { - Widget* widget = CreateTopLevelFramelessPlatformWidget(); - widget->SetContentsView(new View); - for (size_t i = 0; i < 2; ++i) { - widget->GetContentsView()->AddChildView(new View); - widget->GetContentsView()->child_at(i)->SetFocusable(true); - } - - widget->Show(); - const HWND hwnd = HWNDForWidget(widget); - EXPECT_TRUE(::IsWindow(hwnd)); - EXPECT_TRUE(::IsWindowEnabled(hwnd)); - EXPECT_EQ(hwnd, ::GetActiveWindow()); - - for (int i = 0; i < widget->GetContentsView()->child_count(); ++i) { - SCOPED_TRACE(base::StringPrintf("Child view %d", i)); - View* view = widget->GetContentsView()->child_at(i); - - view->RequestFocus(); - EXPECT_EQ(view, widget->GetFocusManager()->GetFocusedView()); - EXPECT_FALSE(::EnableWindow(hwnd, FALSE)); - EXPECT_FALSE(::IsWindowEnabled(hwnd)); - - // Oddly, disabling the HWND leaves it active with the focus unchanged. - EXPECT_EQ(hwnd, ::GetActiveWindow()); - EXPECT_TRUE(widget->IsActive()); - EXPECT_EQ(view, widget->GetFocusManager()->GetFocusedView()); - - EXPECT_TRUE(::EnableWindow(hwnd, TRUE)); - EXPECT_TRUE(::IsWindowEnabled(hwnd)); - EXPECT_EQ(hwnd, ::GetActiveWindow()); - EXPECT_TRUE(widget->IsActive()); - EXPECT_EQ(view, widget->GetFocusManager()->GetFocusedView()); - } - - widget->CloseNow(); -} - -// This class subclasses the Widget class to listen for activation change -// notifications and provides accessors to return information as to whether -// the widget is active. We need this to ensure that users of the widget -// class activate the widget only when the underlying window becomes really -// active. Previously we would activate the widget in the WM_NCACTIVATE -// message which is incorrect because APIs like FlashWindowEx flash the -// window caption by sending fake WM_NCACTIVATE messages. -class WidgetActivationTest : public Widget { - public: - WidgetActivationTest() - : active_(false) {} - - virtual ~WidgetActivationTest() {} - - virtual void OnNativeWidgetActivationChanged(bool active) override { - active_ = active; - } - - bool active() const { return active_; } - - private: - bool active_; - - DISALLOW_COPY_AND_ASSIGN(WidgetActivationTest); -}; - -// Tests whether the widget only becomes active when the underlying window -// is really active. -TEST_F(WidgetTestInteractive, WidgetNotActivatedOnFakeActivationMessages) { - WidgetActivationTest widget1; - Widget::InitParams init_params = - CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); - init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - init_params.native_widget = new DesktopNativeWidgetAura(&widget1); - init_params.bounds = gfx::Rect(0, 0, 200, 200); - widget1.Init(init_params); - widget1.Show(); - EXPECT_EQ(true, widget1.active()); - - WidgetActivationTest widget2; - init_params.native_widget = new DesktopNativeWidgetAura(&widget2); - widget2.Init(init_params); - widget2.Show(); - EXPECT_EQ(true, widget2.active()); - EXPECT_EQ(false, widget1.active()); - - HWND win32_native_window1 = HWNDForWidget(&widget1); - EXPECT_TRUE(::IsWindow(win32_native_window1)); - - ::SendMessage(win32_native_window1, WM_NCACTIVATE, 1, 0); - EXPECT_EQ(false, widget1.active()); - EXPECT_EQ(true, widget2.active()); - - ::SetActiveWindow(win32_native_window1); - EXPECT_EQ(true, widget1.active()); - EXPECT_EQ(false, widget2.active()); -} -#endif // defined(OS_WIN) - -#if !defined(OS_CHROMEOS) -// Provides functionality to create a window modal dialog. -class ModalDialogDelegate : public DialogDelegateView { - public: - explicit ModalDialogDelegate(ui::ModalType type) : type_(type) {} - virtual ~ModalDialogDelegate() {} - - // WidgetDelegate overrides. - virtual ui::ModalType GetModalType() const override { - return type_; - } - - private: - ui::ModalType type_; - - DISALLOW_COPY_AND_ASSIGN(ModalDialogDelegate); -}; - -// Tests whether the focused window is set correctly when a modal window is -// created and destroyed. When it is destroyed it should focus the owner window. -TEST_F(WidgetTestInteractive, WindowModalWindowDestroyedActivationTest) { - TestWidgetFocusChangeListener focus_listener; - WidgetFocusManager::GetInstance()->AddFocusChangeListener(&focus_listener); - const std::vector<NativeViewPair>& focus_changes = - focus_listener.focus_changes(); - - // Create a top level widget. - Widget top_level_widget; - Widget::InitParams init_params = - CreateParams(Widget::InitParams::TYPE_WINDOW); - init_params.show_state = ui::SHOW_STATE_NORMAL; - gfx::Rect initial_bounds(0, 0, 500, 500); - init_params.bounds = initial_bounds; - init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - init_params.native_widget = - new PlatformDesktopNativeWidget(&top_level_widget); - top_level_widget.Init(init_params); - top_level_widget.Show(); - - gfx::NativeView top_level_native_view = top_level_widget.GetNativeView(); - EXPECT_EQ(1u, focus_changes.size()); - EXPECT_EQ(NativeViewPair(NULL, top_level_native_view), focus_changes[0]); - - // Create a modal dialog. - // This instance will be destroyed when the dialog is destroyed. - ModalDialogDelegate* dialog_delegate = - new ModalDialogDelegate(ui::MODAL_TYPE_WINDOW); - - Widget* modal_dialog_widget = views::DialogDelegate::CreateDialogWidget( - dialog_delegate, NULL, top_level_widget.GetNativeView()); - modal_dialog_widget->SetBounds(gfx::Rect(100, 100, 200, 200)); - modal_dialog_widget->Show(); - - gfx::NativeView modal_native_view = modal_dialog_widget->GetNativeView(); - EXPECT_EQ(3u, focus_changes.size()); - EXPECT_EQ(NativeViewPair(top_level_native_view, modal_native_view), - focus_changes[1]); - EXPECT_EQ(NativeViewPair(top_level_native_view, modal_native_view), - focus_changes[2]); - - modal_dialog_widget->CloseNow(); - - EXPECT_EQ(5u, focus_changes.size()); - EXPECT_EQ(NativeViewPair(modal_native_view, top_level_native_view), - focus_changes[3]); - EXPECT_EQ(NativeViewPair(modal_native_view, top_level_native_view), - focus_changes[4]); - - top_level_widget.CloseNow(); - WidgetFocusManager::GetInstance()->RemoveFocusChangeListener(&focus_listener); -} - -// Test that when opening a system-modal window, capture is released. -TEST_F(WidgetTestInteractive, SystemModalWindowReleasesCapture) { - TestWidgetFocusChangeListener focus_listener; - WidgetFocusManager::GetInstance()->AddFocusChangeListener(&focus_listener); - - // Create a top level widget. - Widget top_level_widget; - Widget::InitParams init_params = - CreateParams(Widget::InitParams::TYPE_WINDOW); - init_params.show_state = ui::SHOW_STATE_NORMAL; - gfx::Rect initial_bounds(0, 0, 500, 500); - init_params.bounds = initial_bounds; - init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - init_params.native_widget = - new PlatformDesktopNativeWidget(&top_level_widget); - top_level_widget.Init(init_params); - top_level_widget.Show(); - - EXPECT_EQ(top_level_widget.GetNativeView(), - focus_listener.focus_changes().back().second);; - - EXPECT_FALSE(top_level_widget.HasCapture()); - top_level_widget.SetCapture(NULL); - EXPECT_TRUE(top_level_widget.HasCapture()); - - // Create a modal dialog. - ModalDialogDelegate* dialog_delegate = - new ModalDialogDelegate(ui::MODAL_TYPE_SYSTEM); - - Widget* modal_dialog_widget = views::DialogDelegate::CreateDialogWidget( - dialog_delegate, NULL, top_level_widget.GetNativeView()); - modal_dialog_widget->SetBounds(gfx::Rect(100, 100, 200, 200)); - modal_dialog_widget->Show(); - - EXPECT_FALSE(top_level_widget.HasCapture()); - - modal_dialog_widget->CloseNow(); - top_level_widget.CloseNow(); - WidgetFocusManager::GetInstance()->RemoveFocusChangeListener(&focus_listener); -} - -#endif // !defined(OS_CHROMEOS) - -TEST_F(WidgetTestInteractive, CanActivateFlagIsHonored) { - Widget widget; - Widget::InitParams init_params = - CreateParams(Widget::InitParams::TYPE_WINDOW); - init_params.bounds = gfx::Rect(0, 0, 200, 200); - init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - init_params.activatable = Widget::InitParams::ACTIVATABLE_NO; -#if !defined(OS_CHROMEOS) - init_params.native_widget = new PlatformDesktopNativeWidget(&widget); -#endif // !defined(OS_CHROMEOS) - widget.Init(init_params); - - widget.Show(); - EXPECT_FALSE(widget.IsActive()); -} - -// Test that touch selection quick menu is not activated when opened. -TEST_F(WidgetTestInteractive, TouchSelectionQuickMenuIsNotActivated) { - CommandLine::ForCurrentProcess()->AppendSwitch(switches::kEnableTouchEditing); -#if defined(OS_WIN) - views_delegate().set_use_desktop_native_widgets(true); -#endif // !defined(OS_WIN) - - Widget widget; - Widget::InitParams init_params = - CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); - init_params.bounds = gfx::Rect(0, 0, 200, 200); - init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(init_params); - - Textfield* textfield = new Textfield; - textfield->SetBounds(0, 0, 200, 20); - textfield->SetText(base::ASCIIToUTF16("some text")); - widget.GetRootView()->AddChildView(textfield); - - widget.Show(); - textfield->RequestFocus(); - textfield->SelectAll(true); - TextfieldTestApi textfield_test_api(textfield); - - RunPendingMessages(); - - ui::test::EventGenerator generator(widget.GetNativeWindow()); - generator.GestureTapAt(gfx::Point(10, 10)); - ShowQuickMenuImmediately(static_cast<TouchSelectionControllerImpl*>( - textfield_test_api.touch_selection_controller())); - - EXPECT_TRUE(textfield->HasFocus()); - EXPECT_TRUE(widget.IsActive()); - EXPECT_TRUE(IsQuickMenuVisible(static_cast<TouchSelectionControllerImpl*>( - textfield_test_api.touch_selection_controller()))); -} - -TEST_F(WidgetTestInteractive, DisableViewDoesNotActivateWidget) { -#if defined(OS_WIN) - views_delegate().set_use_desktop_native_widgets(true); -#endif // !defined(OS_WIN) - - // Create first widget and view, activate the widget, and focus the view. - Widget widget1; - Widget::InitParams params1 = CreateParams(Widget::InitParams::TYPE_POPUP); - params1.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params1.activatable = Widget::InitParams::ACTIVATABLE_YES; - widget1.Init(params1); - - View* view1 = new View(); - view1->SetFocusable(true); - widget1.GetRootView()->AddChildView(view1); - - widget1.Activate(); - EXPECT_TRUE(widget1.IsActive()); - - FocusManager* focus_manager1 = widget1.GetFocusManager(); - ASSERT_TRUE(focus_manager1); - focus_manager1->SetFocusedView(view1); - EXPECT_EQ(view1, focus_manager1->GetFocusedView()); - - // Create second widget and view, activate the widget, and focus the view. - Widget widget2; - Widget::InitParams params2 = CreateParams(Widget::InitParams::TYPE_POPUP); - params2.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params2.activatable = Widget::InitParams::ACTIVATABLE_YES; - widget2.Init(params2); - - View* view2 = new View(); - view2->SetFocusable(true); - widget2.GetRootView()->AddChildView(view2); - - widget2.Activate(); - EXPECT_TRUE(widget2.IsActive()); - EXPECT_FALSE(widget1.IsActive()); - - FocusManager* focus_manager2 = widget2.GetFocusManager(); - ASSERT_TRUE(focus_manager2); - focus_manager2->SetFocusedView(view2); - EXPECT_EQ(view2, focus_manager2->GetFocusedView()); - - // Disable the first view and make sure it loses focus, but its widget is not - // activated. - view1->SetEnabled(false); - EXPECT_NE(view1, focus_manager1->GetFocusedView()); - EXPECT_FALSE(widget1.IsActive()); - EXPECT_TRUE(widget2.IsActive()); -} - -namespace { - -// Used to veirfy OnMouseCaptureLost() has been invoked. -class CaptureLostTrackingWidget : public Widget { - public: - CaptureLostTrackingWidget() : got_capture_lost_(false) {} - virtual ~CaptureLostTrackingWidget() {} - - bool GetAndClearGotCaptureLost() { - bool value = got_capture_lost_; - got_capture_lost_ = false; - return value; - } - - // Widget: - virtual void OnMouseCaptureLost() override { - got_capture_lost_ = true; - Widget::OnMouseCaptureLost(); - } - - private: - bool got_capture_lost_; - - DISALLOW_COPY_AND_ASSIGN(CaptureLostTrackingWidget); -}; - -} // namespace - -class WidgetCaptureTest : public ViewsTestBase { - public: - WidgetCaptureTest() { - } - - virtual ~WidgetCaptureTest() { - } - - virtual void SetUp() override { - gfx::GLSurface::InitializeOneOffForTests(); - ui::RegisterPathProvider(); - base::FilePath ui_test_pak_path; - ASSERT_TRUE(PathService::Get(ui::UI_TEST_PAK, &ui_test_pak_path)); - ui::ResourceBundle::InitSharedInstanceWithPakPath(ui_test_pak_path); - ViewsTestBase::SetUp(); - } - - // Verifies Widget::SetCapture() results in updating native capture along with - // invoking the right Widget function. - void TestCapture(bool use_desktop_native_widget) { - CaptureLostTrackingWidget widget1; - Widget::InitParams params1 = - CreateParams(views::Widget::InitParams::TYPE_WINDOW); - params1.native_widget = CreateNativeWidget(use_desktop_native_widget, - &widget1); - params1.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget1.Init(params1); - widget1.Show(); - - CaptureLostTrackingWidget widget2; - Widget::InitParams params2 = - CreateParams(views::Widget::InitParams::TYPE_WINDOW); - params2.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params2.native_widget = CreateNativeWidget(use_desktop_native_widget, - &widget2); - widget2.Init(params2); - widget2.Show(); - - // Set capture to widget2 and verity it gets it. - widget2.SetCapture(widget2.GetRootView()); - EXPECT_FALSE(widget1.HasCapture()); - EXPECT_TRUE(widget2.HasCapture()); - EXPECT_FALSE(widget1.GetAndClearGotCaptureLost()); - EXPECT_FALSE(widget2.GetAndClearGotCaptureLost()); - - // Set capture to widget1 and verify it gets it. - widget1.SetCapture(widget1.GetRootView()); - EXPECT_TRUE(widget1.HasCapture()); - EXPECT_FALSE(widget2.HasCapture()); - EXPECT_FALSE(widget1.GetAndClearGotCaptureLost()); - EXPECT_TRUE(widget2.GetAndClearGotCaptureLost()); - - // Release and verify no one has it. - widget1.ReleaseCapture(); - EXPECT_FALSE(widget1.HasCapture()); - EXPECT_FALSE(widget2.HasCapture()); - EXPECT_TRUE(widget1.GetAndClearGotCaptureLost()); - EXPECT_FALSE(widget2.GetAndClearGotCaptureLost()); - } - - NativeWidget* CreateNativeWidget(bool create_desktop_native_widget, - Widget* widget) { -#if !defined(OS_CHROMEOS) - if (create_desktop_native_widget) - return new PlatformDesktopNativeWidget(widget); -#endif - return NULL; - } - - private: - DISALLOW_COPY_AND_ASSIGN(WidgetCaptureTest); -}; - -// See description in TestCapture(). -TEST_F(WidgetCaptureTest, Capture) { - TestCapture(false); -} - -#if !defined(OS_CHROMEOS) -// See description in TestCapture(). Creates DesktopNativeWidget. -TEST_F(WidgetCaptureTest, CaptureDesktopNativeWidget) { - TestCapture(true); -} -#endif - -// Test that no state is set if capture fails. -TEST_F(WidgetCaptureTest, FailedCaptureRequestIsNoop) { - Widget widget; - Widget::InitParams params = - CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); - params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.bounds = gfx::Rect(400, 400); - widget.Init(params); - - MouseView* mouse_view1 = new MouseView; - MouseView* mouse_view2 = new MouseView; - View* contents_view = new View; - contents_view->AddChildView(mouse_view1); - contents_view->AddChildView(mouse_view2); - widget.SetContentsView(contents_view); - - mouse_view1->SetBounds(0, 0, 200, 400); - mouse_view2->SetBounds(200, 0, 200, 400); - - // Setting capture should fail because |widget| is not visible. - widget.SetCapture(mouse_view1); - EXPECT_FALSE(widget.HasCapture()); - - widget.Show(); - ui::test::EventGenerator generator(GetContext(), widget.GetNativeWindow()); - generator.set_current_location(gfx::Point(300, 10)); - generator.PressLeftButton(); - - EXPECT_FALSE(mouse_view1->pressed()); - EXPECT_TRUE(mouse_view2->pressed()); -} - -#if !defined(OS_CHROMEOS) && !defined(OS_WIN) -// Test that a synthetic mouse exit is sent to the widget which was handling -// mouse events when a different widget grabs capture. -// TODO(pkotwicz): Make test pass on CrOS and Windows. -TEST_F(WidgetCaptureTest, MouseExitOnCaptureGrab) { - Widget widget1; - Widget::InitParams params1 = - CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); - params1.native_widget = CreateNativeWidget(true, &widget1); - params1.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget1.Init(params1); - MouseView* mouse_view1 = new MouseView; - widget1.SetContentsView(mouse_view1); - widget1.Show(); - widget1.SetBounds(gfx::Rect(300, 300)); - - Widget widget2; - Widget::InitParams params2 = - CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); - params2.native_widget = CreateNativeWidget(true, &widget2); - params2.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget2.Init(params2); - widget2.Show(); - widget2.SetBounds(gfx::Rect(400, 0, 300, 300)); - - ui::test::EventGenerator generator(widget1.GetNativeWindow()); - generator.set_current_location(gfx::Point(100, 100)); - generator.MoveMouseBy(0, 0); - - EXPECT_EQ(1, mouse_view1->EnteredCalls()); - EXPECT_EQ(0, mouse_view1->ExitedCalls()); - - widget2.SetCapture(NULL); - EXPECT_EQ(0, mouse_view1->EnteredCalls()); - // Grabbing native capture on Windows generates a ui::ET_MOUSE_EXITED event - // in addition to the one generated by Chrome. - EXPECT_LT(0, mouse_view1->ExitedCalls()); -} -#endif // !defined(OS_CHROMEOS) - -namespace { - -// Widget observer which grabs capture when the widget is activated. -class CaptureOnActivationObserver : public WidgetObserver { - public: - CaptureOnActivationObserver() { - } - virtual ~CaptureOnActivationObserver() { - } - - // WidgetObserver: - virtual void OnWidgetActivationChanged(Widget* widget, bool active) override { - if (active) - widget->SetCapture(NULL); - } - - private: - DISALLOW_COPY_AND_ASSIGN(CaptureOnActivationObserver); -}; - -} // namespace - -// Test that setting capture on widget activation of a non-toplevel widget -// (e.g. a bubble on Linux) succeeds. -TEST_F(WidgetCaptureTest, SetCaptureToNonToplevel) { - Widget toplevel; - Widget::InitParams toplevel_params = - CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); - toplevel_params.native_widget = CreateNativeWidget(true, &toplevel); - toplevel_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - toplevel.Init(toplevel_params); - toplevel.Show(); - - Widget* child = new Widget; - Widget::InitParams child_params = - CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); - child_params.parent = toplevel.GetNativeView(); - child_params.context = toplevel.GetNativeWindow(); - child->Init(child_params); - - CaptureOnActivationObserver observer; - child->AddObserver(&observer); - child->Show(); - - EXPECT_TRUE(child->HasCapture()); -} - - -#if defined(OS_WIN) -namespace { - -// Used to verify OnMouseEvent() has been invoked. -class MouseEventTrackingWidget : public Widget { - public: - MouseEventTrackingWidget() : got_mouse_event_(false) {} - virtual ~MouseEventTrackingWidget() {} - - bool GetAndClearGotMouseEvent() { - bool value = got_mouse_event_; - got_mouse_event_ = false; - return value; - } - - // Widget: - virtual void OnMouseEvent(ui::MouseEvent* event) override { - got_mouse_event_ = true; - Widget::OnMouseEvent(event); - } - - private: - bool got_mouse_event_; - - DISALLOW_COPY_AND_ASSIGN(MouseEventTrackingWidget); -}; - -} // namespace - -// Verifies if a mouse event is received on a widget that doesn't have capture -// on Windows that it is correctly processed by the widget that doesn't have -// capture. This behavior is not desired on OSes other than Windows. -TEST_F(WidgetCaptureTest, MouseEventDispatchedToRightWindow) { - MouseEventTrackingWidget widget1; - Widget::InitParams params1 = - CreateParams(views::Widget::InitParams::TYPE_WINDOW); - params1.native_widget = new DesktopNativeWidgetAura(&widget1); - params1.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget1.Init(params1); - widget1.Show(); - - MouseEventTrackingWidget widget2; - Widget::InitParams params2 = - CreateParams(views::Widget::InitParams::TYPE_WINDOW); - params2.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params2.native_widget = new DesktopNativeWidgetAura(&widget2); - widget2.Init(params2); - widget2.Show(); - - // Set capture to widget2 and verity it gets it. - widget2.SetCapture(widget2.GetRootView()); - EXPECT_FALSE(widget1.HasCapture()); - EXPECT_TRUE(widget2.HasCapture()); - - widget1.GetAndClearGotMouseEvent(); - widget2.GetAndClearGotMouseEvent(); - // Send a mouse event to the RootWindow associated with |widget1|. Even though - // |widget2| has capture, |widget1| should still get the event. - ui::MouseEvent mouse_event(ui::ET_MOUSE_EXITED, gfx::Point(), gfx::Point(), - ui::EF_NONE, ui::EF_NONE); - ui::EventDispatchDetails details = widget1.GetNativeWindow()-> - GetHost()->event_processor()->OnEventFromSource(&mouse_event); - ASSERT_FALSE(details.dispatcher_destroyed); - EXPECT_TRUE(widget1.GetAndClearGotMouseEvent()); - EXPECT_FALSE(widget2.GetAndClearGotMouseEvent()); -} -#endif // defined(OS_WIN) - -} // namespace test -} // namespace views
diff --git a/ui/views/widget/widget_observer.h b/ui/views/widget/widget_observer.h deleted file mode 100644 index 2cad714..0000000 --- a/ui/views/widget/widget_observer.h +++ /dev/null
@@ -1,55 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_WIDGET_WIDGET_OBSERVER_H_ -#define UI_VIEWS_WIDGET_WIDGET_OBSERVER_H_ - -#include "ui/views/views_export.h" - -namespace gfx { -class Rect; -} - -namespace views { - -class Widget; -class View; - -// Observers can listen to various events on the Widgets. -class VIEWS_EXPORT WidgetObserver { - public: - // The closing notification is sent immediately in response to (i.e. in the - // same call stack as) a request to close the Widget (via Close() or - // CloseNow()). - virtual void OnWidgetClosing(Widget* widget) {} - - // Invoked after notification is received from the event loop that the native - // widget has been created. - virtual void OnWidgetCreated(Widget* widget) {} - - // The destroying event occurs immediately before the widget is destroyed. - // This typically occurs asynchronously with respect the the close request, as - // a result of a later invocation from the event loop. - virtual void OnWidgetDestroying(Widget* widget) {} - - // Invoked after notification is received from the event loop that the native - // widget has been destroyed. - virtual void OnWidgetDestroyed(Widget* widget) {} - - virtual void OnWidgetVisibilityChanging(Widget* widget, bool visible) {} - - virtual void OnWidgetVisibilityChanged(Widget* widget, bool visible) {} - - virtual void OnWidgetActivationChanged(Widget* widget, bool active) {} - - virtual void OnWidgetBoundsChanged(Widget* widget, - const gfx::Rect& new_bounds) {} - - protected: - virtual ~WidgetObserver() {} -}; - -} // namespace views - -#endif // UI_VIEWS_WIDGET_WIDGET_OBSERVER_H_
diff --git a/ui/views/widget/widget_removals_observer.h b/ui/views/widget/widget_removals_observer.h deleted file mode 100644 index e62acab..0000000 --- a/ui/views/widget/widget_removals_observer.h +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_WIDGET_WIDGET_REMOVALS_OBSERVER_H_ -#define UI_VIEWS_WIDGET_WIDGET_REMOVALS_OBSERVER_H_ - -#include "ui/views/views_export.h" - -namespace views { - -class Widget; -class View; - -// |WidgetRemovalsObserver| complements |WidgetObserver| with additional -// notifications. These include events occurring during tear down like view -// removal. For this reason, it is recommended that subclasses not also inherit -// from |View|. -class VIEWS_EXPORT WidgetRemovalsObserver { - public: - // Called immediately before a descendant view of |widget| is removed. - virtual void OnWillRemoveView(Widget* widget, View* view) {} - - protected: - virtual ~WidgetRemovalsObserver() {} -}; - -} // namespace views - -#endif // UI_VIEWS_WIDGET_WIDGET_REMOVALS_OBSERVER_H_
diff --git a/ui/views/widget/widget_unittest.cc b/ui/views/widget/widget_unittest.cc deleted file mode 100644 index 374435f..0000000 --- a/ui/views/widget/widget_unittest.cc +++ /dev/null
@@ -1,3379 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <algorithm> -#include <set> - -#include "base/basictypes.h" -#include "base/bind.h" -#include "base/memory/scoped_ptr.h" -#include "base/message_loop/message_loop.h" -#include "base/run_loop.h" -#include "base/strings/utf_string_conversions.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/base/hit_test.h" -#include "ui/compositor/layer_animation_observer.h" -#include "ui/compositor/scoped_animation_duration_scale_mode.h" -#include "ui/compositor/scoped_layer_animation_settings.h" -#include "ui/events/event_processor.h" -#include "ui/events/event_utils.h" -#include "ui/events/test/event_generator.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/gfx/point.h" -#include "ui/views/bubble/bubble_delegate.h" -#include "ui/views/controls/textfield/textfield.h" -#include "ui/views/test/test_views_delegate.h" -#include "ui/views/test/widget_test.h" -#include "ui/views/views_delegate.h" -#include "ui/views/widget/native_widget_delegate.h" -#include "ui/views/widget/root_view.h" -#include "ui/views/widget/widget_deletion_observer.h" -#include "ui/views/window/dialog_delegate.h" -#include "ui/views/window/native_frame_view.h" - -#if defined(OS_WIN) -#include "ui/views/win/hwnd_util.h" -#endif - -namespace views { -namespace test { - -namespace { - -// TODO(tdanderson): This utility function is used in different unittest -// files. Move to a common location to avoid -// repeated code. -gfx::Point ConvertPointFromWidgetToView(View* view, const gfx::Point& p) { - gfx::Point tmp(p); - View::ConvertPointToTarget(view->GetWidget()->GetRootView(), view, &tmp); - return tmp; -} - -} // namespace - -// A view that keeps track of the events it receives, optionally consuming them. -class EventCountView : public View { - public: - // Whether to call SetHandled() on events as they are received. For some event - // types, this will allow EventCountView to receives future events in the - // event sequence, such as a drag. - enum HandleMode { - PROPAGATE_EVENTS, - CONSUME_EVENTS - }; - - EventCountView() - : last_flags_(0), - handle_mode_(PROPAGATE_EVENTS) {} - - virtual ~EventCountView() {} - - int GetEventCount(ui::EventType type) { - return event_count_[type]; - } - - void ResetCounts() { - event_count_.clear(); - } - - int last_flags() const { - return last_flags_; - } - - void set_handle_mode(HandleMode handle_mode) { - handle_mode_ = handle_mode; - } - - protected: - // Overridden from View: - virtual void OnMouseMoved(const ui::MouseEvent& event) override { - // MouseMove events are not re-dispatched from the RootView. - ++event_count_[ui::ET_MOUSE_MOVED]; - last_flags_ = 0; - } - - // Overridden from ui::EventHandler: - virtual void OnKeyEvent(ui::KeyEvent* event) override { - RecordEvent(event); - } - virtual void OnMouseEvent(ui::MouseEvent* event) override { - RecordEvent(event); - } - virtual void OnScrollEvent(ui::ScrollEvent* event) override { - RecordEvent(event); - } - virtual void OnGestureEvent(ui::GestureEvent* event) override { - RecordEvent(event); - } - - private: - void RecordEvent(ui::Event* event) { - ++event_count_[event->type()]; - last_flags_ = event->flags(); - if (handle_mode_ == CONSUME_EVENTS) - event->SetHandled(); - } - - std::map<ui::EventType, int> event_count_; - int last_flags_; - HandleMode handle_mode_; - - DISALLOW_COPY_AND_ASSIGN(EventCountView); -}; - -// A view that keeps track of the events it receives, and consumes all scroll -// gesture events and ui::ET_SCROLL events. -class ScrollableEventCountView : public EventCountView { - public: - ScrollableEventCountView() {} - virtual ~ScrollableEventCountView() {} - - private: - // Overridden from ui::EventHandler: - virtual void OnGestureEvent(ui::GestureEvent* event) override { - EventCountView::OnGestureEvent(event); - switch (event->type()) { - case ui::ET_GESTURE_SCROLL_BEGIN: - case ui::ET_GESTURE_SCROLL_UPDATE: - case ui::ET_GESTURE_SCROLL_END: - case ui::ET_SCROLL_FLING_START: - event->SetHandled(); - break; - default: - break; - } - } - - virtual void OnScrollEvent(ui::ScrollEvent* event) override { - EventCountView::OnScrollEvent(event); - if (event->type() == ui::ET_SCROLL) - event->SetHandled(); - } - - DISALLOW_COPY_AND_ASSIGN(ScrollableEventCountView); -}; - -// A view that implements GetMinimumSize. -class MinimumSizeFrameView : public NativeFrameView { - public: - explicit MinimumSizeFrameView(Widget* frame): NativeFrameView(frame) {} - virtual ~MinimumSizeFrameView() {} - - private: - // Overridden from View: - virtual gfx::Size GetMinimumSize() const override { - return gfx::Size(300, 400); - } - - DISALLOW_COPY_AND_ASSIGN(MinimumSizeFrameView); -}; - -// An event handler that simply keeps a count of the different types of events -// it receives. -class EventCountHandler : public ui::EventHandler { - public: - EventCountHandler() {} - virtual ~EventCountHandler() {} - - int GetEventCount(ui::EventType type) { - return event_count_[type]; - } - - void ResetCounts() { - event_count_.clear(); - } - - protected: - // Overridden from ui::EventHandler: - virtual void OnEvent(ui::Event* event) override { - RecordEvent(*event); - ui::EventHandler::OnEvent(event); - } - - private: - void RecordEvent(const ui::Event& event) { - ++event_count_[event.type()]; - } - - std::map<ui::EventType, int> event_count_; - - DISALLOW_COPY_AND_ASSIGN(EventCountHandler); -}; - -// Class that closes the widget (which ends up deleting it immediately) when the -// appropriate event is received. -class CloseWidgetView : public View { - public: - explicit CloseWidgetView(ui::EventType event_type) - : event_type_(event_type) { - } - - // ui::EventHandler override: - virtual void OnEvent(ui::Event* event) override { - if (event->type() == event_type_) { - // Go through NativeWidgetPrivate to simulate what happens if the OS - // deletes the NativeWindow out from under us. - GetWidget()->native_widget_private()->CloseNow(); - } else { - View::OnEvent(event); - if (!event->IsTouchEvent()) - event->SetHandled(); - } - } - - private: - const ui::EventType event_type_; - - DISALLOW_COPY_AND_ASSIGN(CloseWidgetView); -}; - -ui::WindowShowState GetWidgetShowState(const Widget* widget) { - // Use IsMaximized/IsMinimized/IsFullScreen instead of GetWindowPlacement - // because the former is implemented on all platforms but the latter is not. - return widget->IsFullscreen() ? ui::SHOW_STATE_FULLSCREEN : - widget->IsMaximized() ? ui::SHOW_STATE_MAXIMIZED : - widget->IsMinimized() ? ui::SHOW_STATE_MINIMIZED : - widget->IsActive() ? ui::SHOW_STATE_NORMAL : - ui::SHOW_STATE_INACTIVE; -} - -TEST_F(WidgetTest, WidgetInitParams) { - // Widgets are not transparent by default. - Widget::InitParams init1; - EXPECT_EQ(Widget::InitParams::INFER_OPACITY, init1.opacity); -} - -//////////////////////////////////////////////////////////////////////////////// -// Widget::GetTopLevelWidget tests. - -TEST_F(WidgetTest, GetTopLevelWidget_Native) { - // Create a hierarchy of native widgets. - Widget* toplevel = CreateTopLevelPlatformWidget(); - gfx::NativeView parent = toplevel->GetNativeView(); - Widget* child = CreateChildPlatformWidget(parent); - - EXPECT_EQ(toplevel, toplevel->GetTopLevelWidget()); - EXPECT_EQ(toplevel, child->GetTopLevelWidget()); - - toplevel->CloseNow(); - // |child| should be automatically destroyed with |toplevel|. -} - -// Test if a focus manager and an inputmethod work without CHECK failure -// when window activation changes. -TEST_F(WidgetTest, ChangeActivation) { - Widget* top1 = CreateTopLevelPlatformWidget(); - // CreateInputMethod before activated - top1->GetInputMethod(); - top1->Show(); - RunPendingMessages(); - - Widget* top2 = CreateTopLevelPlatformWidget(); - top2->Show(); - RunPendingMessages(); - - top1->Activate(); - RunPendingMessages(); - - // Create InputMethod after deactivated. - top2->GetInputMethod(); - top2->Activate(); - RunPendingMessages(); - - top1->Activate(); - RunPendingMessages(); - - top1->CloseNow(); - top2->CloseNow(); -} - -// Tests visibility of child widgets. -TEST_F(WidgetTest, Visibility) { - Widget* toplevel = CreateTopLevelPlatformWidget(); - gfx::NativeView parent = toplevel->GetNativeView(); - Widget* child = CreateChildPlatformWidget(parent); - - EXPECT_FALSE(toplevel->IsVisible()); - EXPECT_FALSE(child->IsVisible()); - - child->Show(); - - EXPECT_FALSE(toplevel->IsVisible()); - EXPECT_FALSE(child->IsVisible()); - - toplevel->Show(); - - EXPECT_TRUE(toplevel->IsVisible()); - EXPECT_TRUE(child->IsVisible()); - - toplevel->CloseNow(); - // |child| should be automatically destroyed with |toplevel|. -} - -//////////////////////////////////////////////////////////////////////////////// -// Widget ownership tests. -// -// Tests various permutations of Widget ownership specified in the -// InitParams::Ownership param. - -// A WidgetTest that supplies a toplevel widget for NativeWidget to parent to. -class WidgetOwnershipTest : public WidgetTest { - public: - WidgetOwnershipTest() {} - virtual ~WidgetOwnershipTest() {} - - virtual void SetUp() { - WidgetTest::SetUp(); - desktop_widget_ = CreateTopLevelPlatformWidget(); - } - - virtual void TearDown() { - desktop_widget_->CloseNow(); - WidgetTest::TearDown(); - } - - private: - Widget* desktop_widget_; - - DISALLOW_COPY_AND_ASSIGN(WidgetOwnershipTest); -}; - -// A bag of state to monitor destructions. -struct OwnershipTestState { - OwnershipTestState() : widget_deleted(false), native_widget_deleted(false) {} - - bool widget_deleted; - bool native_widget_deleted; -}; - -// A platform NativeWidget subclass that updates a bag of state when it is -// destroyed. -class OwnershipTestNativeWidget : public PlatformNativeWidget { - public: - OwnershipTestNativeWidget(internal::NativeWidgetDelegate* delegate, - OwnershipTestState* state) - : PlatformNativeWidget(delegate), - state_(state) { - } - virtual ~OwnershipTestNativeWidget() { - state_->native_widget_deleted = true; - } - - private: - OwnershipTestState* state_; - - DISALLOW_COPY_AND_ASSIGN(OwnershipTestNativeWidget); -}; - -// A views NativeWidget subclass that updates a bag of state when it is -// destroyed. -class OwnershipTestNativeWidgetAura : public NativeWidgetCapture { - public: - OwnershipTestNativeWidgetAura(internal::NativeWidgetDelegate* delegate, - OwnershipTestState* state) - : NativeWidgetCapture(delegate), - state_(state) { - } - virtual ~OwnershipTestNativeWidgetAura() { - state_->native_widget_deleted = true; - } - - private: - OwnershipTestState* state_; - - DISALLOW_COPY_AND_ASSIGN(OwnershipTestNativeWidgetAura); -}; - -// A Widget subclass that updates a bag of state when it is destroyed. -class OwnershipTestWidget : public Widget { - public: - explicit OwnershipTestWidget(OwnershipTestState* state) : state_(state) {} - virtual ~OwnershipTestWidget() { - state_->widget_deleted = true; - } - - private: - OwnershipTestState* state_; - - DISALLOW_COPY_AND_ASSIGN(OwnershipTestWidget); -}; - -// Widget owns its NativeWidget, part 1: NativeWidget is a platform-native -// widget. -TEST_F(WidgetOwnershipTest, Ownership_WidgetOwnsPlatformNativeWidget) { - OwnershipTestState state; - - scoped_ptr<Widget> widget(new OwnershipTestWidget(&state)); - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.native_widget = - new OwnershipTestNativeWidgetAura(widget.get(), &state); - params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget->Init(params); - - // Now delete the Widget, which should delete the NativeWidget. - widget.reset(); - - EXPECT_TRUE(state.widget_deleted); - EXPECT_TRUE(state.native_widget_deleted); - - // TODO(beng): write test for this ownership scenario and the NativeWidget - // being deleted out from under the Widget. -} - -// Widget owns its NativeWidget, part 2: NativeWidget is a NativeWidget. -TEST_F(WidgetOwnershipTest, Ownership_WidgetOwnsViewsNativeWidget) { - OwnershipTestState state; - - scoped_ptr<Widget> widget(new OwnershipTestWidget(&state)); - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.native_widget = - new OwnershipTestNativeWidgetAura(widget.get(), &state); - params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget->Init(params); - - // Now delete the Widget, which should delete the NativeWidget. - widget.reset(); - - EXPECT_TRUE(state.widget_deleted); - EXPECT_TRUE(state.native_widget_deleted); - - // TODO(beng): write test for this ownership scenario and the NativeWidget - // being deleted out from under the Widget. -} - -// Widget owns its NativeWidget, part 3: NativeWidget is a NativeWidget, -// destroy the parent view. -TEST_F(WidgetOwnershipTest, - Ownership_WidgetOwnsViewsNativeWidget_DestroyParentView) { - OwnershipTestState state; - - Widget* toplevel = CreateTopLevelPlatformWidget(); - - scoped_ptr<Widget> widget(new OwnershipTestWidget(&state)); - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.native_widget = - new OwnershipTestNativeWidgetAura(widget.get(), &state); - params.parent = toplevel->GetNativeView(); - params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget->Init(params); - - // Now close the toplevel, which deletes the view hierarchy. - toplevel->CloseNow(); - - RunPendingMessages(); - - // This shouldn't delete the widget because it shouldn't be deleted - // from the native side. - EXPECT_FALSE(state.widget_deleted); - EXPECT_FALSE(state.native_widget_deleted); - - // Now delete it explicitly. - widget.reset(); - - EXPECT_TRUE(state.widget_deleted); - EXPECT_TRUE(state.native_widget_deleted); -} - -// NativeWidget owns its Widget, part 1: NativeWidget is a platform-native -// widget. -TEST_F(WidgetOwnershipTest, Ownership_PlatformNativeWidgetOwnsWidget) { - OwnershipTestState state; - - Widget* widget = new OwnershipTestWidget(&state); - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.native_widget = - new OwnershipTestNativeWidgetAura(widget, &state); - widget->Init(params); - - // Now destroy the native widget. - widget->CloseNow(); - - EXPECT_TRUE(state.widget_deleted); - EXPECT_TRUE(state.native_widget_deleted); -} - -// NativeWidget owns its Widget, part 2: NativeWidget is a NativeWidget. -TEST_F(WidgetOwnershipTest, Ownership_ViewsNativeWidgetOwnsWidget) { - OwnershipTestState state; - - Widget* toplevel = CreateTopLevelPlatformWidget(); - - Widget* widget = new OwnershipTestWidget(&state); - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.native_widget = - new OwnershipTestNativeWidgetAura(widget, &state); - params.parent = toplevel->GetNativeView(); - widget->Init(params); - - // Now destroy the native widget. This is achieved by closing the toplevel. - toplevel->CloseNow(); - - // The NativeWidget won't be deleted until after a return to the message loop - // so we have to run pending messages before testing the destruction status. - RunPendingMessages(); - - EXPECT_TRUE(state.widget_deleted); - EXPECT_TRUE(state.native_widget_deleted); -} - -// NativeWidget owns its Widget, part 3: NativeWidget is a platform-native -// widget, destroyed out from under it by the OS. -TEST_F(WidgetOwnershipTest, - Ownership_PlatformNativeWidgetOwnsWidget_NativeDestroy) { - OwnershipTestState state; - - Widget* widget = new OwnershipTestWidget(&state); - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.native_widget = - new OwnershipTestNativeWidgetAura(widget, &state); - widget->Init(params); - - // Now simulate a destroy of the platform native widget from the OS: - SimulateNativeDestroy(widget); - - EXPECT_TRUE(state.widget_deleted); - EXPECT_TRUE(state.native_widget_deleted); -} - -// NativeWidget owns its Widget, part 4: NativeWidget is a NativeWidget, -// destroyed by the view hierarchy that contains it. -TEST_F(WidgetOwnershipTest, - Ownership_ViewsNativeWidgetOwnsWidget_NativeDestroy) { - OwnershipTestState state; - - Widget* toplevel = CreateTopLevelPlatformWidget(); - - Widget* widget = new OwnershipTestWidget(&state); - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.native_widget = - new OwnershipTestNativeWidgetAura(widget, &state); - params.parent = toplevel->GetNativeView(); - widget->Init(params); - - // Destroy the widget (achieved by closing the toplevel). - toplevel->CloseNow(); - - // The NativeWidget won't be deleted until after a return to the message loop - // so we have to run pending messages before testing the destruction status. - RunPendingMessages(); - - EXPECT_TRUE(state.widget_deleted); - EXPECT_TRUE(state.native_widget_deleted); -} - -// NativeWidget owns its Widget, part 5: NativeWidget is a NativeWidget, -// we close it directly. -TEST_F(WidgetOwnershipTest, - Ownership_ViewsNativeWidgetOwnsWidget_Close) { - OwnershipTestState state; - - Widget* toplevel = CreateTopLevelPlatformWidget(); - - Widget* widget = new OwnershipTestWidget(&state); - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.native_widget = - new OwnershipTestNativeWidgetAura(widget, &state); - params.parent = toplevel->GetNativeView(); - widget->Init(params); - - // Destroy the widget. - widget->Close(); - toplevel->CloseNow(); - - // The NativeWidget won't be deleted until after a return to the message loop - // so we have to run pending messages before testing the destruction status. - RunPendingMessages(); - - EXPECT_TRUE(state.widget_deleted); - EXPECT_TRUE(state.native_widget_deleted); -} - -// Widget owns its NativeWidget and has a WidgetDelegateView as its contents. -TEST_F(WidgetOwnershipTest, - Ownership_WidgetOwnsNativeWidgetWithWithWidgetDelegateView) { - OwnershipTestState state; - - WidgetDelegateView* delegate_view = new WidgetDelegateView; - - scoped_ptr<Widget> widget(new OwnershipTestWidget(&state)); - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.native_widget = - new OwnershipTestNativeWidgetAura(widget.get(), &state); - params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.delegate = delegate_view; - widget->Init(params); - widget->SetContentsView(delegate_view); - - // Now delete the Widget. There should be no crash or use-after-free. - widget.reset(); - - EXPECT_TRUE(state.widget_deleted); - EXPECT_TRUE(state.native_widget_deleted); -} - -//////////////////////////////////////////////////////////////////////////////// -// Test to verify using various Widget methods doesn't crash when the underlying -// NativeView is destroyed. -// -class WidgetWithDestroyedNativeViewTest : public ViewsTestBase { - public: - WidgetWithDestroyedNativeViewTest() {} - virtual ~WidgetWithDestroyedNativeViewTest() {} - - void InvokeWidgetMethods(Widget* widget) { - widget->GetNativeView(); - widget->GetNativeWindow(); - ui::Accelerator accelerator; - widget->GetAccelerator(0, &accelerator); - widget->GetTopLevelWidget(); - widget->GetWindowBoundsInScreen(); - widget->GetClientAreaBoundsInScreen(); - widget->SetBounds(gfx::Rect(0, 0, 100, 80)); - widget->SetSize(gfx::Size(10, 11)); - widget->SetBoundsConstrained(gfx::Rect(0, 0, 120, 140)); - widget->SetVisibilityChangedAnimationsEnabled(false); - widget->StackAtTop(); - widget->IsClosed(); - widget->Close(); - widget->Hide(); - widget->Activate(); - widget->Deactivate(); - widget->IsActive(); - widget->DisableInactiveRendering(); - widget->SetAlwaysOnTop(true); - widget->IsAlwaysOnTop(); - widget->Maximize(); - widget->Minimize(); - widget->Restore(); - widget->IsMaximized(); - widget->IsFullscreen(); - widget->SetOpacity(0); - widget->SetUseDragFrame(true); - widget->FlashFrame(true); - widget->IsVisible(); - widget->GetThemeProvider(); - widget->GetNativeTheme(); - widget->GetFocusManager(); - widget->GetInputMethod(); - widget->SchedulePaintInRect(gfx::Rect(0, 0, 1, 2)); - widget->IsMouseEventsEnabled(); - widget->SetNativeWindowProperty("xx", widget); - widget->GetNativeWindowProperty("xx"); - widget->GetFocusTraversable(); - widget->GetLayer(); - widget->ReorderNativeViews(); - widget->SetCapture(widget->GetRootView()); - widget->ReleaseCapture(); - widget->HasCapture(); - widget->GetWorkAreaBoundsInScreen(); - widget->IsTranslucentWindowOpacitySupported(); - } - - private: - DISALLOW_COPY_AND_ASSIGN(WidgetWithDestroyedNativeViewTest); -}; - -TEST_F(WidgetWithDestroyedNativeViewTest, Test) { - { - Widget widget; - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(params); - widget.Show(); - - widget.native_widget_private()->CloseNow(); - InvokeWidgetMethods(&widget); - } -#if !defined(OS_CHROMEOS) - { - Widget widget; - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.native_widget = new PlatformDesktopNativeWidget(&widget); - params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget.Init(params); - widget.Show(); - - widget.native_widget_private()->CloseNow(); - InvokeWidgetMethods(&widget); - } -#endif -} - -//////////////////////////////////////////////////////////////////////////////// -// Widget observer tests. -// - -class WidgetObserverTest : public WidgetTest, public WidgetObserver { - public: - WidgetObserverTest() - : active_(NULL), - widget_closed_(NULL), - widget_activated_(NULL), - widget_shown_(NULL), - widget_hidden_(NULL), - widget_bounds_changed_(NULL) { - } - - virtual ~WidgetObserverTest() {} - - // Overridden from WidgetObserver: - virtual void OnWidgetDestroying(Widget* widget) override { - if (active_ == widget) - active_ = NULL; - widget_closed_ = widget; - } - - virtual void OnWidgetActivationChanged(Widget* widget, - bool active) override { - if (active) { - if (widget_activated_) - widget_activated_->Deactivate(); - widget_activated_ = widget; - active_ = widget; - } else { - if (widget_activated_ == widget) - widget_activated_ = NULL; - widget_deactivated_ = widget; - } - } - - virtual void OnWidgetVisibilityChanged(Widget* widget, - bool visible) override { - if (visible) - widget_shown_ = widget; - else - widget_hidden_ = widget; - } - - virtual void OnWidgetBoundsChanged(Widget* widget, - const gfx::Rect& new_bounds) override { - widget_bounds_changed_ = widget; - } - - void reset() { - active_ = NULL; - widget_closed_ = NULL; - widget_activated_ = NULL; - widget_deactivated_ = NULL; - widget_shown_ = NULL; - widget_hidden_ = NULL; - widget_bounds_changed_ = NULL; - } - - Widget* NewWidget() { - Widget* widget = CreateTopLevelNativeWidget(); - widget->AddObserver(this); - return widget; - } - - const Widget* active() const { return active_; } - const Widget* widget_closed() const { return widget_closed_; } - const Widget* widget_activated() const { return widget_activated_; } - const Widget* widget_deactivated() const { return widget_deactivated_; } - const Widget* widget_shown() const { return widget_shown_; } - const Widget* widget_hidden() const { return widget_hidden_; } - const Widget* widget_bounds_changed() const { return widget_bounds_changed_; } - - private: - Widget* active_; - - Widget* widget_closed_; - Widget* widget_activated_; - Widget* widget_deactivated_; - Widget* widget_shown_; - Widget* widget_hidden_; - Widget* widget_bounds_changed_; -}; - -TEST_F(WidgetObserverTest, DISABLED_ActivationChange) { - Widget* toplevel = CreateTopLevelPlatformWidget(); - - Widget* toplevel1 = NewWidget(); - Widget* toplevel2 = NewWidget(); - - toplevel1->Show(); - toplevel2->Show(); - - reset(); - - toplevel1->Activate(); - - RunPendingMessages(); - EXPECT_EQ(toplevel1, widget_activated()); - - toplevel2->Activate(); - RunPendingMessages(); - EXPECT_EQ(toplevel1, widget_deactivated()); - EXPECT_EQ(toplevel2, widget_activated()); - EXPECT_EQ(toplevel2, active()); - - toplevel->CloseNow(); -} - -TEST_F(WidgetObserverTest, DISABLED_VisibilityChange) { - Widget* toplevel = CreateTopLevelPlatformWidget(); - - Widget* child1 = NewWidget(); - Widget* child2 = NewWidget(); - - toplevel->Show(); - child1->Show(); - child2->Show(); - - reset(); - - child1->Hide(); - EXPECT_EQ(child1, widget_hidden()); - - child2->Hide(); - EXPECT_EQ(child2, widget_hidden()); - - child1->Show(); - EXPECT_EQ(child1, widget_shown()); - - child2->Show(); - EXPECT_EQ(child2, widget_shown()); - - toplevel->CloseNow(); -} - -TEST_F(WidgetObserverTest, DestroyBubble) { - Widget* anchor = CreateTopLevelPlatformWidget(); - anchor->Show(); - - BubbleDelegateView* bubble_delegate = - new BubbleDelegateView(anchor->client_view(), BubbleBorder::NONE); - Widget* bubble_widget(BubbleDelegateView::CreateBubble(bubble_delegate)); - bubble_widget->Show(); - bubble_widget->CloseNow(); - - anchor->Hide(); - anchor->CloseNow(); -} - -TEST_F(WidgetObserverTest, WidgetBoundsChanged) { - Widget* child1 = NewWidget(); - Widget* child2 = NewWidget(); - - child1->OnNativeWidgetMove(); - EXPECT_EQ(child1, widget_bounds_changed()); - - child2->OnNativeWidgetMove(); - EXPECT_EQ(child2, widget_bounds_changed()); - - child1->OnNativeWidgetSizeChanged(gfx::Size()); - EXPECT_EQ(child1, widget_bounds_changed()); - - child2->OnNativeWidgetSizeChanged(gfx::Size()); - EXPECT_EQ(child2, widget_bounds_changed()); -} - -// Tests that SetBounds() and GetWindowBoundsInScreen() is symmetric when the -// widget is visible and not maximized or fullscreen. -TEST_F(WidgetTest, GetWindowBoundsInScreen) { - // Choose test coordinates away from edges and dimensions that are "small" - // (but not too small) to ensure the OS doesn't try to adjust them. - const gfx::Rect kTestBounds(150, 150, 400, 300); - const gfx::Size kTestSize(200, 180); - - // First test a toplevel widget. - Widget* widget = CreateTopLevelPlatformWidget(); - widget->Show(); - - EXPECT_NE(kTestSize.ToString(), - widget->GetWindowBoundsInScreen().size().ToString()); - widget->SetSize(kTestSize); - EXPECT_EQ(kTestSize.ToString(), - widget->GetWindowBoundsInScreen().size().ToString()); - - EXPECT_NE(kTestBounds.ToString(), - widget->GetWindowBoundsInScreen().ToString()); - widget->SetBounds(kTestBounds); - EXPECT_EQ(kTestBounds.ToString(), - widget->GetWindowBoundsInScreen().ToString()); - - // Changing just the size should not change the origin. - widget->SetSize(kTestSize); - EXPECT_EQ(kTestBounds.origin().ToString(), - widget->GetWindowBoundsInScreen().origin().ToString()); - - widget->CloseNow(); - - // Same tests with a frameless window. - widget = CreateTopLevelFramelessPlatformWidget(); - widget->Show(); - - EXPECT_NE(kTestSize.ToString(), - widget->GetWindowBoundsInScreen().size().ToString()); - widget->SetSize(kTestSize); - EXPECT_EQ(kTestSize.ToString(), - widget->GetWindowBoundsInScreen().size().ToString()); - - EXPECT_NE(kTestBounds.ToString(), - widget->GetWindowBoundsInScreen().ToString()); - widget->SetBounds(kTestBounds); - EXPECT_EQ(kTestBounds.ToString(), - widget->GetWindowBoundsInScreen().ToString()); - - // For a frameless widget, the client bounds should also match. - EXPECT_EQ(kTestBounds.ToString(), - widget->GetClientAreaBoundsInScreen().ToString()); - - // Verify origin is stable for a frameless window as well. - widget->SetSize(kTestSize); - EXPECT_EQ(kTestBounds.origin().ToString(), - widget->GetWindowBoundsInScreen().origin().ToString()); - - widget->CloseNow(); -} - -// Before being enabled on Mac, this was #ifdef(false). -// TODO(tapted): Fix this for DesktopNativeWidgets on other platforms. -#if defined(OS_MACOSX) -// Aura needs shell to maximize/fullscreen window. -// NativeWidgetGtk doesn't implement GetRestoredBounds. -TEST_F(WidgetTest, GetRestoredBounds) { - Widget* toplevel = CreateTopLevelPlatformWidget(); - EXPECT_EQ(toplevel->GetWindowBoundsInScreen().ToString(), - toplevel->GetRestoredBounds().ToString()); - toplevel->Show(); - toplevel->Maximize(); - RunPendingMessages(); -#if defined(OS_MACOSX) - // Current expectation on Mac is to do nothing on Maximize. - EXPECT_EQ(toplevel->GetWindowBoundsInScreen().ToString(), - toplevel->GetRestoredBounds().ToString()); -#else - EXPECT_NE(toplevel->GetWindowBoundsInScreen().ToString(), - toplevel->GetRestoredBounds().ToString()); -#endif - EXPECT_GT(toplevel->GetRestoredBounds().width(), 0); - EXPECT_GT(toplevel->GetRestoredBounds().height(), 0); - - toplevel->Restore(); - RunPendingMessages(); - EXPECT_EQ(toplevel->GetWindowBoundsInScreen().ToString(), - toplevel->GetRestoredBounds().ToString()); - - toplevel->SetFullscreen(true); - RunPendingMessages(); - EXPECT_NE(toplevel->GetWindowBoundsInScreen().ToString(), - toplevel->GetRestoredBounds().ToString()); - EXPECT_GT(toplevel->GetRestoredBounds().width(), 0); - EXPECT_GT(toplevel->GetRestoredBounds().height(), 0); -} -#endif - -// Test that window state is not changed after getting out of full screen. -TEST_F(WidgetTest, ExitFullscreenRestoreState) { - Widget* toplevel = CreateTopLevelPlatformWidget(); - - toplevel->Show(); - RunPendingMessages(); - - // This should be a normal state window. - EXPECT_EQ(ui::SHOW_STATE_NORMAL, GetWidgetShowState(toplevel)); - - toplevel->SetFullscreen(true); - EXPECT_EQ(ui::SHOW_STATE_FULLSCREEN, GetWidgetShowState(toplevel)); - toplevel->SetFullscreen(false); - EXPECT_NE(ui::SHOW_STATE_FULLSCREEN, GetWidgetShowState(toplevel)); - - // And it should still be in normal state after getting out of full screen. - EXPECT_EQ(ui::SHOW_STATE_NORMAL, GetWidgetShowState(toplevel)); - -// On Mac, a "maximized" state is indistinguishable from a window that just -// fills the screen, so nothing to check there. -#if !defined(OS_MACOSX) - // Now, make it maximized. - toplevel->Maximize(); - EXPECT_EQ(ui::SHOW_STATE_MAXIMIZED, GetWidgetShowState(toplevel)); - - toplevel->SetFullscreen(true); - EXPECT_EQ(ui::SHOW_STATE_FULLSCREEN, GetWidgetShowState(toplevel)); - toplevel->SetFullscreen(false); - EXPECT_NE(ui::SHOW_STATE_FULLSCREEN, GetWidgetShowState(toplevel)); - - // And it stays maximized after getting out of full screen. - EXPECT_EQ(ui::SHOW_STATE_MAXIMIZED, GetWidgetShowState(toplevel)); -#endif - - // Clean up. - toplevel->Close(); - RunPendingMessages(); -} - -// The key-event propagation from Widget happens differently on aura and -// non-aura systems because of the difference in IME. So this test works only on -// aura. -TEST_F(WidgetTest, KeyboardInputEvent) { - Widget* toplevel = CreateTopLevelPlatformWidget(); - View* container = toplevel->client_view(); - - Textfield* textfield = new Textfield(); - textfield->SetText(base::ASCIIToUTF16("some text")); - container->AddChildView(textfield); - toplevel->Show(); - textfield->RequestFocus(); - - // The press gets handled. The release doesn't have an effect. - ui::KeyEvent backspace_p(ui::ET_KEY_PRESSED, ui::VKEY_DELETE, ui::EF_NONE); - toplevel->OnKeyEvent(&backspace_p); - EXPECT_TRUE(backspace_p.stopped_propagation()); - ui::KeyEvent backspace_r(ui::ET_KEY_RELEASED, ui::VKEY_DELETE, ui::EF_NONE); - toplevel->OnKeyEvent(&backspace_r); - EXPECT_FALSE(backspace_r.handled()); - - toplevel->Close(); -} - -// Verifies bubbles result in a focus lost when shown. -// TODO(msw): this tests relies on focus, it needs to be in -// interactive_ui_tests. -TEST_F(WidgetTest, DISABLED_FocusChangesOnBubble) { - // Create a widget, show and activate it and focus the contents view. - View* contents_view = new View; - contents_view->SetFocusable(true); - Widget widget; - Widget::InitParams init_params = - CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS); - init_params.bounds = gfx::Rect(0, 0, 200, 200); - init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; -#if !defined(OS_CHROMEOS) - init_params.native_widget = new PlatformDesktopNativeWidget(&widget); -#endif - widget.Init(init_params); - widget.SetContentsView(contents_view); - widget.Show(); - widget.Activate(); - contents_view->RequestFocus(); - EXPECT_TRUE(contents_view->HasFocus()); - - // Show a bubble. - BubbleDelegateView* bubble_delegate_view = - new BubbleDelegateView(contents_view, BubbleBorder::TOP_LEFT); - bubble_delegate_view->SetFocusable(true); - BubbleDelegateView::CreateBubble(bubble_delegate_view)->Show(); - bubble_delegate_view->RequestFocus(); - - // |contents_view_| should no longer have focus. - EXPECT_FALSE(contents_view->HasFocus()); - EXPECT_TRUE(bubble_delegate_view->HasFocus()); - - bubble_delegate_view->GetWidget()->CloseNow(); - - // Closing the bubble should result in focus going back to the contents view. - EXPECT_TRUE(contents_view->HasFocus()); -} - -class TestBubbleDelegateView : public BubbleDelegateView { - public: - TestBubbleDelegateView(View* anchor) - : BubbleDelegateView(anchor, BubbleBorder::NONE), - reset_controls_called_(false) {} - virtual ~TestBubbleDelegateView() {} - - virtual bool ShouldShowCloseButton() const override { - reset_controls_called_ = true; - return true; - } - - mutable bool reset_controls_called_; -}; - -TEST_F(WidgetTest, BubbleControlsResetOnInit) { - Widget* anchor = CreateTopLevelPlatformWidget(); - anchor->Show(); - - TestBubbleDelegateView* bubble_delegate = - new TestBubbleDelegateView(anchor->client_view()); - Widget* bubble_widget(BubbleDelegateView::CreateBubble(bubble_delegate)); - EXPECT_TRUE(bubble_delegate->reset_controls_called_); - bubble_widget->Show(); - bubble_widget->CloseNow(); - - anchor->Hide(); - anchor->CloseNow(); -} - -// Desktop native widget Aura tests are for non Chrome OS platforms. -#if !defined(OS_CHROMEOS) -// Test to ensure that after minimize, view width is set to zero. -TEST_F(WidgetTest, TestViewWidthAfterMinimizingWidget) { - // Create a widget. - Widget widget; - Widget::InitParams init_params = - CreateParams(Widget::InitParams::TYPE_WINDOW); - init_params.show_state = ui::SHOW_STATE_NORMAL; - gfx::Rect initial_bounds(0, 0, 300, 400); - init_params.bounds = initial_bounds; - init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - init_params.native_widget = new PlatformDesktopNativeWidget(&widget); - widget.Init(init_params); - NonClientView* non_client_view = widget.non_client_view(); - NonClientFrameView* frame_view = new MinimumSizeFrameView(&widget); - non_client_view->SetFrameView(frame_view); - widget.Show(); - widget.Minimize(); - EXPECT_EQ(0, frame_view->width()); -} - -// This class validates whether paints are received for a visible Widget. -// To achieve this it overrides the Show and Close methods on the Widget class -// and sets state whether subsequent paints are expected. -class DesktopAuraTestValidPaintWidget : public views::Widget { - public: - DesktopAuraTestValidPaintWidget() - : received_paint_(false), - expect_paint_(true), - received_paint_while_hidden_(false) {} - - virtual ~DesktopAuraTestValidPaintWidget() {} - - void InitForTest(Widget::InitParams create_params); - - virtual void Show() override { - expect_paint_ = true; - views::Widget::Show(); - } - - virtual void Close() override { - expect_paint_ = false; - views::Widget::Close(); - } - - void Hide() { - expect_paint_ = false; - views::Widget::Hide(); - } - - virtual void OnNativeWidgetPaint(gfx::Canvas* canvas) override { - received_paint_ = true; - EXPECT_TRUE(expect_paint_); - if (!expect_paint_) - received_paint_while_hidden_ = true; - views::Widget::OnNativeWidgetPaint(canvas); - } - - bool ReadReceivedPaintAndReset() { - bool result = received_paint_; - received_paint_ = false; - return result; - } - - bool received_paint_while_hidden() const { - return received_paint_while_hidden_; - } - - private: - bool received_paint_; - bool expect_paint_; - bool received_paint_while_hidden_; - - DISALLOW_COPY_AND_ASSIGN(DesktopAuraTestValidPaintWidget); -}; - -void DesktopAuraTestValidPaintWidget::InitForTest(InitParams init_params) { - init_params.bounds = gfx::Rect(0, 0, 200, 200); - init_params.ownership = InitParams::WIDGET_OWNS_NATIVE_WIDGET; - init_params.native_widget = new PlatformDesktopNativeWidget(this); - Init(init_params); - - View* contents_view = new View; - contents_view->SetFocusable(true); - SetContentsView(contents_view); - - Show(); - Activate(); -} - -TEST_F(WidgetTest, DesktopNativeWidgetNoPaintAfterCloseTest) { - DesktopAuraTestValidPaintWidget widget; - widget.InitForTest(CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS)); - RunPendingMessages(); - EXPECT_TRUE(widget.ReadReceivedPaintAndReset()); - widget.SchedulePaintInRect(widget.GetRestoredBounds()); - widget.Close(); - RunPendingMessages(); - EXPECT_FALSE(widget.ReadReceivedPaintAndReset()); - EXPECT_FALSE(widget.received_paint_while_hidden()); -} - -TEST_F(WidgetTest, DesktopNativeWidgetNoPaintAfterHideTest) { - DesktopAuraTestValidPaintWidget widget; - widget.InitForTest(CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS)); - RunPendingMessages(); - EXPECT_TRUE(widget.ReadReceivedPaintAndReset()); - widget.SchedulePaintInRect(widget.GetRestoredBounds()); - widget.Hide(); - RunPendingMessages(); - EXPECT_FALSE(widget.ReadReceivedPaintAndReset()); - EXPECT_FALSE(widget.received_paint_while_hidden()); - widget.Close(); -} - -// Test to ensure that the aura Window's visiblity state is set to visible if -// the underlying widget is hidden and then shown. -TEST_F(WidgetTest, TestWindowVisibilityAfterHide) { - // Create a widget. - Widget widget; - Widget::InitParams init_params = - CreateParams(Widget::InitParams::TYPE_WINDOW); - init_params.show_state = ui::SHOW_STATE_NORMAL; - gfx::Rect initial_bounds(0, 0, 300, 400); - init_params.bounds = initial_bounds; - init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - init_params.native_widget = new PlatformDesktopNativeWidget(&widget); - widget.Init(init_params); - NonClientView* non_client_view = widget.non_client_view(); - NonClientFrameView* frame_view = new MinimumSizeFrameView(&widget); - non_client_view->SetFrameView(frame_view); - - widget.Show(); - EXPECT_TRUE(IsNativeWindowVisible(widget.GetNativeWindow())); - widget.Hide(); - EXPECT_FALSE(IsNativeWindowVisible(widget.GetNativeWindow())); - widget.Show(); - EXPECT_TRUE(IsNativeWindowVisible(widget.GetNativeWindow())); -} - -// The following code verifies we can correctly destroy a Widget from a mouse -// enter/exit. We could test move/drag/enter/exit but in general we don't run -// nested message loops from such events, nor has the code ever really dealt -// with this situation. - -// Generates two moves (first generates enter, second real move), a press, drag -// and release stopping at |last_event_type|. -void GenerateMouseEvents(Widget* widget, ui::EventType last_event_type) { - const gfx::Rect screen_bounds(widget->GetWindowBoundsInScreen()); - ui::MouseEvent move_event(ui::ET_MOUSE_MOVED, screen_bounds.CenterPoint(), - screen_bounds.CenterPoint(), 0, 0); - ui::EventProcessor* dispatcher = WidgetTest::GetEventProcessor(widget); - ui::EventDispatchDetails details = dispatcher->OnEventFromSource(&move_event); - if (last_event_type == ui::ET_MOUSE_ENTERED || details.dispatcher_destroyed) - return; - details = dispatcher->OnEventFromSource(&move_event); - if (last_event_type == ui::ET_MOUSE_MOVED || details.dispatcher_destroyed) - return; - - ui::MouseEvent press_event(ui::ET_MOUSE_PRESSED, screen_bounds.CenterPoint(), - screen_bounds.CenterPoint(), 0, 0); - details = dispatcher->OnEventFromSource(&press_event); - if (last_event_type == ui::ET_MOUSE_PRESSED || details.dispatcher_destroyed) - return; - - gfx::Point end_point(screen_bounds.CenterPoint()); - end_point.Offset(1, 1); - ui::MouseEvent drag_event(ui::ET_MOUSE_DRAGGED, end_point, end_point, 0, 0); - details = dispatcher->OnEventFromSource(&drag_event); - if (last_event_type == ui::ET_MOUSE_DRAGGED || details.dispatcher_destroyed) - return; - - ui::MouseEvent release_event(ui::ET_MOUSE_RELEASED, end_point, end_point, 0, - 0); - details = dispatcher->OnEventFromSource(&release_event); - if (details.dispatcher_destroyed) - return; -} - -// Creates a widget and invokes GenerateMouseEvents() with |last_event_type|. -void RunCloseWidgetDuringDispatchTest(WidgetTest* test, - ui::EventType last_event_type) { - // |widget| is deleted by CloseWidgetView. - Widget* widget = new Widget; - Widget::InitParams params = - test->CreateParams(Widget::InitParams::TYPE_POPUP); - params.native_widget = new PlatformDesktopNativeWidget(widget); - params.bounds = gfx::Rect(0, 0, 50, 100); - widget->Init(params); - widget->SetContentsView(new CloseWidgetView(last_event_type)); - widget->Show(); - GenerateMouseEvents(widget, last_event_type); -} - -// Verifies deleting the widget from a mouse pressed event doesn't crash. -TEST_F(WidgetTest, CloseWidgetDuringMousePress) { - RunCloseWidgetDuringDispatchTest(this, ui::ET_MOUSE_PRESSED); -} - -// Verifies deleting the widget from a mouse released event doesn't crash. -TEST_F(WidgetTest, CloseWidgetDuringMouseReleased) { - RunCloseWidgetDuringDispatchTest(this, ui::ET_MOUSE_RELEASED); -} - -#endif // !defined(OS_CHROMEOS) - -// Tests that wheel events generated from scroll events are targetted to the -// views under the cursor when the focused view does not processed them. -TEST_F(WidgetTest, WheelEventsFromScrollEventTarget) { - EventCountView* cursor_view = new EventCountView; - cursor_view->SetBounds(60, 0, 50, 40); - - Widget* widget = CreateTopLevelPlatformWidget(); - widget->GetRootView()->AddChildView(cursor_view); - - // Generate a scroll event on the cursor view. - ui::ScrollEvent scroll(ui::ET_SCROLL, - gfx::Point(65, 5), - ui::EventTimeForNow(), - 0, - 0, 20, - 0, 20, - 2); - widget->OnScrollEvent(&scroll); - - EXPECT_EQ(1, cursor_view->GetEventCount(ui::ET_SCROLL)); - EXPECT_EQ(1, cursor_view->GetEventCount(ui::ET_MOUSEWHEEL)); - - cursor_view->ResetCounts(); - - ui::ScrollEvent scroll2(ui::ET_SCROLL, - gfx::Point(5, 5), - ui::EventTimeForNow(), - 0, - 0, 20, - 0, 20, - 2); - widget->OnScrollEvent(&scroll2); - - EXPECT_EQ(0, cursor_view->GetEventCount(ui::ET_SCROLL)); - EXPECT_EQ(0, cursor_view->GetEventCount(ui::ET_MOUSEWHEEL)); - - widget->CloseNow(); -} - -// Tests that if a scroll-begin gesture is not handled, then subsequent scroll -// events are not dispatched to any view. -TEST_F(WidgetTest, GestureScrollEventDispatching) { - EventCountView* noscroll_view = new EventCountView; - EventCountView* scroll_view = new ScrollableEventCountView; - - noscroll_view->SetBounds(0, 0, 50, 40); - scroll_view->SetBounds(60, 0, 40, 40); - - Widget* widget = CreateTopLevelPlatformWidget(); - widget->GetRootView()->AddChildView(noscroll_view); - widget->GetRootView()->AddChildView(scroll_view); - - { - ui::GestureEvent begin( - 5, - 5, - 0, - base::TimeDelta(), - ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_BEGIN)); - widget->OnGestureEvent(&begin); - ui::GestureEvent update( - 25, - 15, - 0, - base::TimeDelta(), - ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_UPDATE, 20, 10)); - widget->OnGestureEvent(&update); - ui::GestureEvent end(25, - 15, - 0, - base::TimeDelta(), - ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_END)); - widget->OnGestureEvent(&end); - - EXPECT_EQ(1, noscroll_view->GetEventCount(ui::ET_GESTURE_SCROLL_BEGIN)); - EXPECT_EQ(0, noscroll_view->GetEventCount(ui::ET_GESTURE_SCROLL_UPDATE)); - EXPECT_EQ(0, noscroll_view->GetEventCount(ui::ET_GESTURE_SCROLL_END)); - } - - { - ui::GestureEvent begin( - 65, - 5, - 0, - base::TimeDelta(), - ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_BEGIN)); - widget->OnGestureEvent(&begin); - ui::GestureEvent update( - 85, - 15, - 0, - base::TimeDelta(), - ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_UPDATE, 20, 10)); - widget->OnGestureEvent(&update); - ui::GestureEvent end(85, - 15, - 0, - base::TimeDelta(), - ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_END)); - widget->OnGestureEvent(&end); - - EXPECT_EQ(1, scroll_view->GetEventCount(ui::ET_GESTURE_SCROLL_BEGIN)); - EXPECT_EQ(1, scroll_view->GetEventCount(ui::ET_GESTURE_SCROLL_UPDATE)); - EXPECT_EQ(1, scroll_view->GetEventCount(ui::ET_GESTURE_SCROLL_END)); - } - - widget->CloseNow(); -} - -// Tests that event-handlers installed on the RootView get triggered correctly. -// TODO(tdanderson): Clean up this test as part of crbug.com/355680. -TEST_F(WidgetTest, EventHandlersOnRootView) { - Widget* widget = CreateTopLevelNativeWidget(); - View* root_view = widget->GetRootView(); - - scoped_ptr<EventCountView> view(new EventCountView()); - view->set_owned_by_client(); - view->SetBounds(0, 0, 20, 20); - root_view->AddChildView(view.get()); - - EventCountHandler h1; - root_view->AddPreTargetHandler(&h1); - - EventCountHandler h2; - root_view->AddPostTargetHandler(&h2); - - widget->SetBounds(gfx::Rect(0, 0, 100, 100)); - widget->Show(); - - // Dispatch a ui::ET_SCROLL event. The event remains unhandled and should - // bubble up the views hierarchy to be re-dispatched on the root view. - ui::ScrollEvent scroll(ui::ET_SCROLL, - gfx::Point(5, 5), - ui::EventTimeForNow(), - 0, - 0, 20, - 0, 20, - 2); - widget->OnScrollEvent(&scroll); - EXPECT_EQ(2, h1.GetEventCount(ui::ET_SCROLL)); - EXPECT_EQ(1, view->GetEventCount(ui::ET_SCROLL)); - EXPECT_EQ(2, h2.GetEventCount(ui::ET_SCROLL)); - - // Unhandled scroll events are turned into wheel events and re-dispatched. - EXPECT_EQ(1, h1.GetEventCount(ui::ET_MOUSEWHEEL)); - EXPECT_EQ(1, view->GetEventCount(ui::ET_MOUSEWHEEL)); - EXPECT_EQ(1, h2.GetEventCount(ui::ET_MOUSEWHEEL)); - - h1.ResetCounts(); - view->ResetCounts(); - h2.ResetCounts(); - - // Dispatch a ui::ET_SCROLL_FLING_START event. The event remains unhandled and - // should bubble up the views hierarchy to be re-dispatched on the root view. - ui::ScrollEvent fling(ui::ET_SCROLL_FLING_START, - gfx::Point(5, 5), - ui::EventTimeForNow(), - 0, - 0, 20, - 0, 20, - 2); - widget->OnScrollEvent(&fling); - EXPECT_EQ(2, h1.GetEventCount(ui::ET_SCROLL_FLING_START)); - EXPECT_EQ(1, view->GetEventCount(ui::ET_SCROLL_FLING_START)); - EXPECT_EQ(2, h2.GetEventCount(ui::ET_SCROLL_FLING_START)); - - // Unhandled scroll events which are not of type ui::ET_SCROLL should not - // be turned into wheel events and re-dispatched. - EXPECT_EQ(0, h1.GetEventCount(ui::ET_MOUSEWHEEL)); - EXPECT_EQ(0, view->GetEventCount(ui::ET_MOUSEWHEEL)); - EXPECT_EQ(0, h2.GetEventCount(ui::ET_MOUSEWHEEL)); - - h1.ResetCounts(); - view->ResetCounts(); - h2.ResetCounts(); - - // Change the handle mode of |view| so that events are marked as handled at - // the target phase. - view->set_handle_mode(EventCountView::CONSUME_EVENTS); - - // Dispatch a ui::ET_GESTURE_TAP_DOWN and a ui::ET_GESTURE_TAP_CANCEL event. - // The events are handled at the target phase and should not reach the - // post-target handler. - ui::GestureEvent tap_down(5, - 5, - 0, - ui::EventTimeForNow(), - ui::GestureEventDetails(ui::ET_GESTURE_TAP_DOWN)); - widget->OnGestureEvent(&tap_down); - EXPECT_EQ(1, h1.GetEventCount(ui::ET_GESTURE_TAP_DOWN)); - EXPECT_EQ(1, view->GetEventCount(ui::ET_GESTURE_TAP_DOWN)); - EXPECT_EQ(0, h2.GetEventCount(ui::ET_GESTURE_TAP_DOWN)); - - ui::GestureEvent tap_cancel( - 5, - 5, - 0, - ui::EventTimeForNow(), - ui::GestureEventDetails(ui::ET_GESTURE_TAP_CANCEL)); - widget->OnGestureEvent(&tap_cancel); - EXPECT_EQ(1, h1.GetEventCount(ui::ET_GESTURE_TAP_CANCEL)); - EXPECT_EQ(1, view->GetEventCount(ui::ET_GESTURE_TAP_CANCEL)); - EXPECT_EQ(0, h2.GetEventCount(ui::ET_GESTURE_TAP_CANCEL)); - - h1.ResetCounts(); - view->ResetCounts(); - h2.ResetCounts(); - - // Dispatch a ui::ET_SCROLL event. The event is handled at the target phase - // and should not reach the post-target handler. - ui::ScrollEvent consumed_scroll(ui::ET_SCROLL, - gfx::Point(5, 5), - ui::EventTimeForNow(), - 0, - 0, 20, - 0, 20, - 2); - widget->OnScrollEvent(&consumed_scroll); - EXPECT_EQ(1, h1.GetEventCount(ui::ET_SCROLL)); - EXPECT_EQ(1, view->GetEventCount(ui::ET_SCROLL)); - EXPECT_EQ(0, h2.GetEventCount(ui::ET_SCROLL)); - - // Handled scroll events are not turned into wheel events and re-dispatched. - EXPECT_EQ(0, h1.GetEventCount(ui::ET_MOUSEWHEEL)); - EXPECT_EQ(0, view->GetEventCount(ui::ET_MOUSEWHEEL)); - EXPECT_EQ(0, h2.GetEventCount(ui::ET_MOUSEWHEEL)); - - widget->CloseNow(); -} - -TEST_F(WidgetTest, SynthesizeMouseMoveEvent) { - Widget* widget = CreateTopLevelNativeWidget(); - View* root_view = widget->GetRootView(); - - EventCountView* v1 = new EventCountView(); - v1->SetBounds(0, 0, 10, 10); - root_view->AddChildView(v1); - EventCountView* v2 = new EventCountView(); - v2->SetBounds(0, 10, 10, 10); - root_view->AddChildView(v2); - - gfx::Point cursor_location(5, 5); - ui::MouseEvent move(ui::ET_MOUSE_MOVED, cursor_location, cursor_location, - ui::EF_NONE, ui::EF_NONE); - widget->OnMouseEvent(&move); - - EXPECT_EQ(1, v1->GetEventCount(ui::ET_MOUSE_ENTERED)); - EXPECT_EQ(0, v2->GetEventCount(ui::ET_MOUSE_ENTERED)); - - delete v1; - v2->SetBounds(0, 0, 10, 10); - EXPECT_EQ(0, v2->GetEventCount(ui::ET_MOUSE_ENTERED)); - - widget->SynthesizeMouseMoveEvent(); - EXPECT_EQ(1, v2->GetEventCount(ui::ET_MOUSE_ENTERED)); -} - -namespace { - -// ui::EventHandler which handles all mouse press events. -class MousePressEventConsumer : public ui::EventHandler { - public: - explicit MousePressEventConsumer() { - } - - virtual ~MousePressEventConsumer() { - } - - private: - // ui::EventHandler: - virtual void OnMouseEvent(ui::MouseEvent* event) override { - if (event->type() == ui::ET_MOUSE_PRESSED) - event->SetHandled(); - } - - DISALLOW_COPY_AND_ASSIGN(MousePressEventConsumer); -}; - -} // namespace - -// Test that mouse presses and mouse releases are dispatched normally when a -// touch is down. -TEST_F(WidgetTest, MouseEventDispatchWhileTouchIsDown) { - Widget* widget = CreateTopLevelNativeWidget(); - widget->Show(); - widget->SetSize(gfx::Size(300, 300)); - - EventCountView* event_count_view = new EventCountView(); - event_count_view->SetBounds(0, 0, 300, 300); - widget->GetRootView()->AddChildView(event_count_view); - - MousePressEventConsumer consumer; - event_count_view->AddPostTargetHandler(&consumer); - - ui::test::EventGenerator generator(GetContext(), widget->GetNativeWindow()); - generator.PressTouch(); - generator.ClickLeftButton(); - - EXPECT_EQ(1, event_count_view->GetEventCount(ui::ET_MOUSE_PRESSED)); - EXPECT_EQ(1, event_count_view->GetEventCount(ui::ET_MOUSE_RELEASED)); - - widget->CloseNow(); -} - -// Used by SingleWindowClosing to count number of times WindowClosing() has -// been invoked. -class ClosingDelegate : public WidgetDelegate { - public: - ClosingDelegate() : count_(0), widget_(NULL) {} - - int count() const { return count_; } - - void set_widget(views::Widget* widget) { widget_ = widget; } - - // WidgetDelegate overrides: - virtual Widget* GetWidget() override { return widget_; } - virtual const Widget* GetWidget() const override { return widget_; } - virtual void WindowClosing() override { - count_++; - } - - private: - int count_; - views::Widget* widget_; - - DISALLOW_COPY_AND_ASSIGN(ClosingDelegate); -}; - -// Verifies WindowClosing() is invoked correctly on the delegate when a Widget -// is closed. -TEST_F(WidgetTest, SingleWindowClosing) { - scoped_ptr<ClosingDelegate> delegate(new ClosingDelegate()); - Widget* widget = new Widget(); // Destroyed by CloseNow() below. - Widget::InitParams init_params = - CreateParams(Widget::InitParams::TYPE_WINDOW); - init_params.bounds = gfx::Rect(0, 0, 200, 200); - init_params.delegate = delegate.get(); -#if !defined(OS_CHROMEOS) - init_params.native_widget = new PlatformDesktopNativeWidget(widget); -#endif - widget->Init(init_params); - EXPECT_EQ(0, delegate->count()); - widget->CloseNow(); - EXPECT_EQ(1, delegate->count()); -} - -class WidgetWindowTitleTest : public WidgetTest { - protected: - void RunTest(bool desktop_native_widget) { - Widget* widget = new Widget(); // Destroyed by CloseNow() below. - Widget::InitParams init_params = - CreateParams(Widget::InitParams::TYPE_WINDOW); - widget->Init(init_params); - -#if !defined(OS_CHROMEOS) - if (desktop_native_widget) - init_params.native_widget = new PlatformDesktopNativeWidget(widget); -#else - DCHECK(!desktop_native_widget) - << "DesktopNativeWidget does not exist on non-Aura or on ChromeOS."; -#endif - - internal::NativeWidgetPrivate* native_widget = - widget->native_widget_private(); - - base::string16 empty; - base::string16 s1(base::UTF8ToUTF16("Title1")); - base::string16 s2(base::UTF8ToUTF16("Title2")); - base::string16 s3(base::UTF8ToUTF16("TitleLong")); - - // The widget starts with no title, setting empty should not change - // anything. - EXPECT_FALSE(native_widget->SetWindowTitle(empty)); - // Setting the title to something non-empty should cause a change. - EXPECT_TRUE(native_widget->SetWindowTitle(s1)); - // Setting the title to something else with the same length should cause a - // change. - EXPECT_TRUE(native_widget->SetWindowTitle(s2)); - // Setting the title to something else with a different length should cause - // a change. - EXPECT_TRUE(native_widget->SetWindowTitle(s3)); - // Setting the title to the same thing twice should not cause a change. - EXPECT_FALSE(native_widget->SetWindowTitle(s3)); - - widget->CloseNow(); - } -}; - -TEST_F(WidgetWindowTitleTest, SetWindowTitleChanged_NativeWidget) { - // Use the default NativeWidget. - bool desktop_native_widget = false; - RunTest(desktop_native_widget); -} - -// DesktopNativeWidget does not exist on non-Aura or on ChromeOS. -#if !defined(OS_CHROMEOS) -TEST_F(WidgetWindowTitleTest, SetWindowTitleChanged_DesktopNativeWidget) { - // Override to use a DesktopNativeWidget. - bool desktop_native_widget = true; - RunTest(desktop_native_widget); -} -#endif // !OS_CHROMEOS - -TEST_F(WidgetTest, WidgetDeleted_InOnMousePressed) { - Widget* widget = new Widget; - Widget::InitParams params = - CreateParams(views::Widget::InitParams::TYPE_POPUP); - widget->Init(params); - - widget->SetContentsView(new CloseWidgetView(ui::ET_MOUSE_PRESSED)); - - widget->SetSize(gfx::Size(100, 100)); - widget->Show(); - - ui::test::EventGenerator generator(GetContext(), widget->GetNativeWindow()); - - WidgetDeletionObserver deletion_observer(widget); - generator.ClickLeftButton(); - EXPECT_FALSE(deletion_observer.IsWidgetAlive()); - - // Yay we did not crash! -} - -TEST_F(WidgetTest, WidgetDeleted_InDispatchGestureEvent) { - Widget* widget = new Widget; - Widget::InitParams params = - CreateParams(views::Widget::InitParams::TYPE_POPUP); - widget->Init(params); - - widget->SetContentsView(new CloseWidgetView(ui::ET_GESTURE_TAP_DOWN)); - - widget->SetSize(gfx::Size(100, 100)); - widget->Show(); - - ui::test::EventGenerator generator(GetContext(), widget->GetNativeWindow()); - - WidgetDeletionObserver deletion_observer(widget); - generator.GestureTapAt(widget->GetWindowBoundsInScreen().CenterPoint()); - EXPECT_FALSE(deletion_observer.IsWidgetAlive()); - - // Yay we did not crash! -} - -// See description of RunGetNativeThemeFromDestructor() for details. -class GetNativeThemeFromDestructorView : public WidgetDelegateView { - public: - GetNativeThemeFromDestructorView() {} - virtual ~GetNativeThemeFromDestructorView() { - VerifyNativeTheme(); - } - - virtual View* GetContentsView() override { - return this; - } - - private: - void VerifyNativeTheme() { - ASSERT_TRUE(GetNativeTheme() != NULL); - } - - DISALLOW_COPY_AND_ASSIGN(GetNativeThemeFromDestructorView); -}; - -// Verifies GetNativeTheme() from the destructor of a WidgetDelegateView doesn't -// crash. |is_first_run| is true if this is the first call. A return value of -// true indicates this should be run again with a value of false. -// First run uses DesktopNativeWidgetAura (if possible). Second run doesn't. -bool RunGetNativeThemeFromDestructor(const Widget::InitParams& in_params, - bool is_first_run) { - bool needs_second_run = false; - // Destroyed by CloseNow() below. - Widget* widget = new Widget; - Widget::InitParams params(in_params); - // Deletes itself when the Widget is destroyed. - params.delegate = new GetNativeThemeFromDestructorView; -#if !defined(OS_CHROMEOS) - if (is_first_run) { - params.native_widget = new PlatformDesktopNativeWidget(widget); - needs_second_run = true; - } -#endif - widget->Init(params); - widget->CloseNow(); - return needs_second_run; -} - -// See description of RunGetNativeThemeFromDestructor() for details. -TEST_F(WidgetTest, GetNativeThemeFromDestructor) { - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - if (RunGetNativeThemeFromDestructor(params, true)) - RunGetNativeThemeFromDestructor(params, false); -} - -// Used by HideCloseDestroy. Allows setting a boolean when the widget is -// destroyed. -class CloseDestroysWidget : public Widget { - public: - explicit CloseDestroysWidget(bool* destroyed) - : destroyed_(destroyed) { - } - - virtual ~CloseDestroysWidget() { - if (destroyed_) { - *destroyed_ = true; - base::MessageLoop::current()->QuitNow(); - } - } - - void Detach() { destroyed_ = NULL; } - - private: - // If non-null set to true from destructor. - bool* destroyed_; - - DISALLOW_COPY_AND_ASSIGN(CloseDestroysWidget); -}; - -// An observer that registers that an animation has ended. -class AnimationEndObserver : public ui::ImplicitAnimationObserver { - public: - AnimationEndObserver() : animation_completed_(false) {} - virtual ~AnimationEndObserver() {} - - bool animation_completed() const { return animation_completed_; } - - // ui::ImplicitAnimationObserver: - virtual void OnImplicitAnimationsCompleted() override { - animation_completed_ = true; - } - - private: - bool animation_completed_; - - DISALLOW_COPY_AND_ASSIGN(AnimationEndObserver); -}; - -// An observer that registers the bounds of a widget on destruction. -class WidgetBoundsObserver : public WidgetObserver { - public: - WidgetBoundsObserver() {} - virtual ~WidgetBoundsObserver() {} - - gfx::Rect bounds() { return bounds_; } - - // WidgetObserver: - virtual void OnWidgetDestroying(Widget* widget) override { - bounds_ = widget->GetWindowBoundsInScreen(); - } - - private: - gfx::Rect bounds_; - - DISALLOW_COPY_AND_ASSIGN(WidgetBoundsObserver); -}; - -// Verifies Close() results in destroying. -TEST_F(WidgetTest, CloseDestroys) { - bool destroyed = false; - CloseDestroysWidget* widget = new CloseDestroysWidget(&destroyed); - Widget::InitParams params = - CreateParams(views::Widget::InitParams::TYPE_MENU); - params.opacity = Widget::InitParams::OPAQUE_WINDOW; -#if !defined(OS_CHROMEOS) - params.native_widget = new PlatformDesktopNativeWidget(widget); -#endif - widget->Init(params); - widget->Show(); - widget->Hide(); - widget->Close(); - EXPECT_FALSE(destroyed); - // Run the message loop as Close() asynchronously deletes. - base::RunLoop().Run(); - EXPECT_TRUE(destroyed); - // Close() should destroy the widget. If not we'll cleanup to avoid leaks. - if (!destroyed) { - widget->Detach(); - widget->CloseNow(); - } -} - -// Tests that killing a widget while animating it does not crash. -TEST_F(WidgetTest, CloseWidgetWhileAnimating) { - scoped_ptr<Widget> widget(new Widget); - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.bounds = gfx::Rect(50, 50, 250, 250); - widget->Init(params); - AnimationEndObserver animation_observer; - WidgetBoundsObserver widget_observer; - gfx::Rect bounds(0, 0, 50, 50); - { - // Normal animations for tests have ZERO_DURATION, make sure we are actually - // animating the movement. - ui::ScopedAnimationDurationScaleMode animation_scale_mode( - ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION); - ui::ScopedLayerAnimationSettings animation_settings( - widget->GetLayer()->GetAnimator()); - animation_settings.AddObserver(&animation_observer); - widget->AddObserver(&widget_observer); - widget->Show(); - - // Animate the bounds change. - widget->SetBounds(bounds); - widget.reset(); - EXPECT_FALSE(animation_observer.animation_completed()); - } - EXPECT_TRUE(animation_observer.animation_completed()); - EXPECT_EQ(widget_observer.bounds(), bounds); -} - -// A view that consumes mouse-pressed event and gesture-tap-down events. -class RootViewTestView : public View { - public: - RootViewTestView(): View() {} - - private: - virtual bool OnMousePressed(const ui::MouseEvent& event) override { - return true; - } - - virtual void OnGestureEvent(ui::GestureEvent* event) override { - if (event->type() == ui::ET_GESTURE_TAP_DOWN) - event->SetHandled(); - } -}; - -// Checks if RootView::*_handler_ fields are unset when widget is hidden. -// Fails on chromium.webkit Windows bot, see crbug.com/264872. -#if defined(OS_WIN) -#define MAYBE_DisableTestRootViewHandlersWhenHidden\ - DISABLED_TestRootViewHandlersWhenHidden -#else -#define MAYBE_DisableTestRootViewHandlersWhenHidden\ - TestRootViewHandlersWhenHidden -#endif -TEST_F(WidgetTest, MAYBE_DisableTestRootViewHandlersWhenHidden) { - Widget* widget = CreateTopLevelNativeWidget(); - widget->SetBounds(gfx::Rect(0, 0, 300, 300)); - View* view = new RootViewTestView(); - view->SetBounds(0, 0, 300, 300); - internal::RootView* root_view = - static_cast<internal::RootView*>(widget->GetRootView()); - root_view->AddChildView(view); - - // Check RootView::mouse_pressed_handler_. - widget->Show(); - EXPECT_EQ(NULL, GetMousePressedHandler(root_view)); - gfx::Point click_location(45, 15); - ui::MouseEvent press(ui::ET_MOUSE_PRESSED, click_location, click_location, - ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON); - widget->OnMouseEvent(&press); - EXPECT_EQ(view, GetMousePressedHandler(root_view)); - widget->Hide(); - EXPECT_EQ(NULL, GetMousePressedHandler(root_view)); - - // Check RootView::mouse_move_handler_. - widget->Show(); - EXPECT_EQ(NULL, GetMouseMoveHandler(root_view)); - gfx::Point move_location(45, 15); - ui::MouseEvent move(ui::ET_MOUSE_MOVED, move_location, move_location, 0, 0); - widget->OnMouseEvent(&move); - EXPECT_EQ(view, GetMouseMoveHandler(root_view)); - widget->Hide(); - EXPECT_EQ(NULL, GetMouseMoveHandler(root_view)); - - // Check RootView::gesture_handler_. - widget->Show(); - EXPECT_EQ(NULL, GetGestureHandler(root_view)); - ui::GestureEvent tap_down(15, - 15, - 0, - base::TimeDelta(), - ui::GestureEventDetails(ui::ET_GESTURE_TAP_DOWN)); - widget->OnGestureEvent(&tap_down); - EXPECT_EQ(view, GetGestureHandler(root_view)); - widget->Hide(); - EXPECT_EQ(NULL, GetGestureHandler(root_view)); - - widget->Close(); -} - -// Convenience to make constructing a GestureEvent simpler. -class GestureEventForTest : public ui::GestureEvent { - public: - GestureEventForTest(ui::EventType type, int x, int y) - : GestureEvent(x, - y, - 0, - base::TimeDelta(), - ui::GestureEventDetails(type)) {} - - GestureEventForTest(ui::GestureEventDetails details, int x, int y) - : GestureEvent(x, y, 0, base::TimeDelta(), details) {} -}; - -// Tests that the |gesture_handler_| member in RootView is always NULL -// after the dispatch of a ui::ET_GESTURE_END event corresponding to -// the release of the final touch point on the screen, but that -// ui::ET_GESTURE_END events corresponding to the removal of any other touch -// point do not modify |gesture_handler_|. -TEST_F(WidgetTest, GestureEndEvents) { - Widget* widget = CreateTopLevelNativeWidget(); - widget->SetBounds(gfx::Rect(0, 0, 300, 300)); - EventCountView* view = new EventCountView(); - view->SetBounds(0, 0, 300, 300); - internal::RootView* root_view = - static_cast<internal::RootView*>(widget->GetRootView()); - root_view->AddChildView(view); - widget->Show(); - - // If no gesture handler is set, a ui::ET_GESTURE_END event should not set - // the gesture handler. - EXPECT_EQ(NULL, GetGestureHandler(root_view)); - GestureEventForTest end(ui::ET_GESTURE_END, 15, 15); - widget->OnGestureEvent(&end); - EXPECT_EQ(NULL, GetGestureHandler(root_view)); - - // Change the handle mode of |view| to indicate that it would like - // to handle all events, then send a GESTURE_TAP to set the gesture handler. - view->set_handle_mode(EventCountView::CONSUME_EVENTS); - GestureEventForTest tap(ui::ET_GESTURE_TAP, 15, 15); - widget->OnGestureEvent(&tap); - EXPECT_TRUE(tap.handled()); - EXPECT_EQ(view, GetGestureHandler(root_view)); - - // The gesture handler should remain unchanged on a ui::ET_GESTURE_END - // corresponding to a second touch point, but should be reset to NULL by a - // ui::ET_GESTURE_END corresponding to the final touch point. - ui::GestureEventDetails details(ui::ET_GESTURE_END); - details.set_touch_points(2); - GestureEventForTest end_second_touch_point(details, 15, 15); - widget->OnGestureEvent(&end_second_touch_point); - EXPECT_EQ(view, GetGestureHandler(root_view)); - - end = GestureEventForTest(ui::ET_GESTURE_END, 15, 15); - widget->OnGestureEvent(&end); - EXPECT_TRUE(end.handled()); - EXPECT_EQ(NULL, GetGestureHandler(root_view)); - - // Send a GESTURE_TAP to set the gesture handler, then change the handle - // mode of |view| to indicate that it does not want to handle any - // further events. - tap = GestureEventForTest(ui::ET_GESTURE_TAP, 15, 15); - widget->OnGestureEvent(&tap); - EXPECT_TRUE(tap.handled()); - EXPECT_EQ(view, GetGestureHandler(root_view)); - view->set_handle_mode(EventCountView::PROPAGATE_EVENTS); - - // The gesture handler should remain unchanged on a ui::ET_GESTURE_END - // corresponding to a second touch point, but should be reset to NULL by a - // ui::ET_GESTURE_END corresponding to the final touch point. - end_second_touch_point = GestureEventForTest(details, 15, 15); - widget->OnGestureEvent(&end_second_touch_point); - EXPECT_EQ(view, GetGestureHandler(root_view)); - - end = GestureEventForTest(ui::ET_GESTURE_END, 15, 15); - widget->OnGestureEvent(&end); - EXPECT_FALSE(end.handled()); - EXPECT_EQ(NULL, GetGestureHandler(root_view)); - - widget->Close(); -} - -// Tests that gesture events which should not be processed (because -// RootView::OnEventProcessingStarted() has marked them as handled) are not -// dispatched to any views. -TEST_F(WidgetTest, GestureEventsNotProcessed) { - Widget* widget = CreateTopLevelNativeWidget(); - widget->SetBounds(gfx::Rect(0, 0, 300, 300)); - - // Define a hierarchy of four views (coordinates are in - // their parent coordinate space). - // v1 (0, 0, 300, 300) - // v2 (0, 0, 100, 100) - // v3 (0, 0, 50, 50) - // v4(0, 0, 10, 10) - EventCountView* v1 = new EventCountView(); - v1->SetBounds(0, 0, 300, 300); - EventCountView* v2 = new EventCountView(); - v2->SetBounds(0, 0, 100, 100); - EventCountView* v3 = new EventCountView(); - v3->SetBounds(0, 0, 50, 50); - EventCountView* v4 = new EventCountView(); - v4->SetBounds(0, 0, 10, 10); - internal::RootView* root_view = - static_cast<internal::RootView*>(widget->GetRootView()); - root_view->AddChildView(v1); - v1->AddChildView(v2); - v2->AddChildView(v3); - v3->AddChildView(v4); - - widget->Show(); - - // ui::ET_GESTURE_BEGIN events should never be seen by any view, but - // they should be marked as handled by OnEventProcessingStarted(). - GestureEventForTest begin(ui::ET_GESTURE_BEGIN, 5, 5); - widget->OnGestureEvent(&begin); - EXPECT_EQ(0, v1->GetEventCount(ui::ET_GESTURE_BEGIN)); - EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_BEGIN)); - EXPECT_EQ(0, v3->GetEventCount(ui::ET_GESTURE_BEGIN)); - EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_BEGIN)); - EXPECT_EQ(NULL, GetGestureHandler(root_view)); - EXPECT_TRUE(begin.handled()); - v1->ResetCounts(); - v2->ResetCounts(); - v3->ResetCounts(); - v4->ResetCounts(); - - // ui::ET_GESTURE_END events should not be seen by any view when there is - // no default gesture handler set, but they should be marked as handled by - // OnEventProcessingStarted(). - GestureEventForTest end(ui::ET_GESTURE_END, 5, 5); - widget->OnGestureEvent(&end); - EXPECT_EQ(0, v1->GetEventCount(ui::ET_GESTURE_END)); - EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_END)); - EXPECT_EQ(0, v3->GetEventCount(ui::ET_GESTURE_END)); - EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_END)); - EXPECT_EQ(NULL, GetGestureHandler(root_view)); - EXPECT_TRUE(end.handled()); - v1->ResetCounts(); - v2->ResetCounts(); - v3->ResetCounts(); - v4->ResetCounts(); - - // ui::ET_GESTURE_END events not corresponding to the release of the - // final touch point should never be seen by any view, but they should - // be marked as handled by OnEventProcessingStarted(). - ui::GestureEventDetails details(ui::ET_GESTURE_END); - details.set_touch_points(2); - GestureEventForTest end_second_touch_point(details, 5, 5); - widget->OnGestureEvent(&end_second_touch_point); - EXPECT_EQ(0, v1->GetEventCount(ui::ET_GESTURE_END)); - EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_END)); - EXPECT_EQ(0, v3->GetEventCount(ui::ET_GESTURE_END)); - EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_END)); - EXPECT_EQ(NULL, GetGestureHandler(root_view)); - EXPECT_TRUE(end_second_touch_point.handled()); - v1->ResetCounts(); - v2->ResetCounts(); - v3->ResetCounts(); - v4->ResetCounts(); - - // ui::ET_GESTURE_SCROLL_UPDATE events should never be seen by any view when - // there is no default gesture handler set, but they should be marked as - // handled by OnEventProcessingStarted(). - GestureEventForTest scroll_update(ui::ET_GESTURE_SCROLL_UPDATE, 5, 5); - widget->OnGestureEvent(&scroll_update); - EXPECT_EQ(0, v1->GetEventCount(ui::ET_GESTURE_SCROLL_UPDATE)); - EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_SCROLL_UPDATE)); - EXPECT_EQ(0, v3->GetEventCount(ui::ET_GESTURE_SCROLL_UPDATE)); - EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_SCROLL_UPDATE)); - EXPECT_EQ(NULL, GetGestureHandler(root_view)); - EXPECT_TRUE(scroll_update.handled()); - v1->ResetCounts(); - v2->ResetCounts(); - v3->ResetCounts(); - v4->ResetCounts(); - - // ui::ET_GESTURE_SCROLL_END events should never be seen by any view when - // there is no default gesture handler set, but they should be marked as - // handled by OnEventProcessingStarted(). - GestureEventForTest scroll_end(ui::ET_GESTURE_SCROLL_END, 5, 5); - widget->OnGestureEvent(&scroll_end); - EXPECT_EQ(0, v1->GetEventCount(ui::ET_GESTURE_SCROLL_END)); - EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_SCROLL_END)); - EXPECT_EQ(0, v3->GetEventCount(ui::ET_GESTURE_SCROLL_END)); - EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_SCROLL_END)); - EXPECT_EQ(NULL, GetGestureHandler(root_view)); - EXPECT_TRUE(scroll_end.handled()); - v1->ResetCounts(); - v2->ResetCounts(); - v3->ResetCounts(); - v4->ResetCounts(); - - // ui::ET_SCROLL_FLING_START events should never be seen by any view when - // there is no default gesture handler set, but they should be marked as - // handled by OnEventProcessingStarted(). - GestureEventForTest scroll_fling_start(ui::ET_SCROLL_FLING_START, 5, 5); - widget->OnGestureEvent(&scroll_fling_start); - EXPECT_EQ(0, v1->GetEventCount(ui::ET_SCROLL_FLING_START)); - EXPECT_EQ(0, v2->GetEventCount(ui::ET_SCROLL_FLING_START)); - EXPECT_EQ(0, v3->GetEventCount(ui::ET_SCROLL_FLING_START)); - EXPECT_EQ(0, v4->GetEventCount(ui::ET_SCROLL_FLING_START)); - EXPECT_EQ(NULL, GetGestureHandler(root_view)); - EXPECT_TRUE(scroll_fling_start.handled()); - v1->ResetCounts(); - v2->ResetCounts(); - v3->ResetCounts(); - v4->ResetCounts(); - - widget->Close(); -} - -// Tests that a (non-scroll) gesture event is dispatched to the correct views -// in a view hierarchy and that the default gesture handler in RootView is set -// correctly. -TEST_F(WidgetTest, GestureEventDispatch) { - Widget* widget = CreateTopLevelNativeWidget(); - widget->SetBounds(gfx::Rect(0, 0, 300, 300)); - - // Define a hierarchy of four views (coordinates are in - // their parent coordinate space). - // v1 (0, 0, 300, 300) - // v2 (0, 0, 100, 100) - // v3 (0, 0, 50, 50) - // v4(0, 0, 10, 10) - EventCountView* v1 = new EventCountView(); - v1->SetBounds(0, 0, 300, 300); - EventCountView* v2 = new EventCountView(); - v2->SetBounds(0, 0, 100, 100); - EventCountView* v3 = new EventCountView(); - v3->SetBounds(0, 0, 50, 50); - EventCountView* v4 = new EventCountView(); - v4->SetBounds(0, 0, 10, 10); - internal::RootView* root_view = - static_cast<internal::RootView*>(widget->GetRootView()); - root_view->AddChildView(v1); - v1->AddChildView(v2); - v2->AddChildView(v3); - v3->AddChildView(v4); - - widget->Show(); - - // No gesture handler is set in the root view and none of the views in the - // view hierarchy handle a ui::ET_GESTURE_TAP event. In this case the tap - // event should be dispatched to all views in the hierarchy, the gesture - // handler should remain unset, and the event should remain unhandled. - GestureEventForTest tap(ui::ET_GESTURE_TAP, 5, 5); - EXPECT_EQ(NULL, GetGestureHandler(root_view)); - widget->OnGestureEvent(&tap); - EXPECT_EQ(1, v1->GetEventCount(ui::ET_GESTURE_TAP)); - EXPECT_EQ(1, v2->GetEventCount(ui::ET_GESTURE_TAP)); - EXPECT_EQ(1, v3->GetEventCount(ui::ET_GESTURE_TAP)); - EXPECT_EQ(1, v4->GetEventCount(ui::ET_GESTURE_TAP)); - EXPECT_EQ(NULL, GetGestureHandler(root_view)); - EXPECT_FALSE(tap.handled()); - - // No gesture handler is set in the root view and |v1|, |v2|, and |v3| all - // handle a ui::ET_GESTURE_TAP event. In this case the tap event should be - // dispatched to |v4| and |v3|, the gesture handler should be set to |v3|, - // and the event should be marked as handled. - v1->ResetCounts(); - v2->ResetCounts(); - v3->ResetCounts(); - v4->ResetCounts(); - v1->set_handle_mode(EventCountView::CONSUME_EVENTS); - v2->set_handle_mode(EventCountView::CONSUME_EVENTS); - v3->set_handle_mode(EventCountView::CONSUME_EVENTS); - tap = GestureEventForTest(ui::ET_GESTURE_TAP, 5, 5); - widget->OnGestureEvent(&tap); - EXPECT_EQ(0, v1->GetEventCount(ui::ET_GESTURE_TAP)); - EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_TAP)); - EXPECT_EQ(1, v3->GetEventCount(ui::ET_GESTURE_TAP)); - EXPECT_EQ(1, v4->GetEventCount(ui::ET_GESTURE_TAP)); - EXPECT_EQ(v3, GetGestureHandler(root_view)); - EXPECT_TRUE(tap.handled()); - - // The gesture handler is set to |v3| and all views handle all gesture event - // types. In this case subsequent gesture events should only be dispatched to - // |v3| and marked as handled. The gesture handler should remain as |v3|. - v1->ResetCounts(); - v2->ResetCounts(); - v3->ResetCounts(); - v4->ResetCounts(); - v4->set_handle_mode(EventCountView::CONSUME_EVENTS); - tap = GestureEventForTest(ui::ET_GESTURE_TAP, 5, 5); - widget->OnGestureEvent(&tap); - EXPECT_TRUE(tap.handled()); - GestureEventForTest show_press(ui::ET_GESTURE_SHOW_PRESS, 5, 5); - widget->OnGestureEvent(&show_press); - tap = GestureEventForTest(ui::ET_GESTURE_TAP, 5, 5); - widget->OnGestureEvent(&tap); - EXPECT_EQ(0, v1->GetEventCount(ui::ET_GESTURE_TAP)); - EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_TAP)); - EXPECT_EQ(2, v3->GetEventCount(ui::ET_GESTURE_TAP)); - EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_TAP)); - EXPECT_EQ(0, v1->GetEventCount(ui::ET_GESTURE_SHOW_PRESS)); - EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_SHOW_PRESS)); - EXPECT_EQ(1, v3->GetEventCount(ui::ET_GESTURE_SHOW_PRESS)); - EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_SHOW_PRESS)); - EXPECT_TRUE(tap.handled()); - EXPECT_TRUE(show_press.handled()); - EXPECT_EQ(v3, GetGestureHandler(root_view)); - - // The gesture handler is set to |v3|, but |v3| does not handle - // ui::ET_GESTURE_TAP events. In this case a tap gesture should be dispatched - // only to |v3|, but the event should remain unhandled. The gesture handler - // should remain as |v3|. - v1->ResetCounts(); - v2->ResetCounts(); - v3->ResetCounts(); - v4->ResetCounts(); - v3->set_handle_mode(EventCountView::PROPAGATE_EVENTS); - tap = GestureEventForTest(ui::ET_GESTURE_TAP, 5, 5); - widget->OnGestureEvent(&tap); - EXPECT_EQ(0, v1->GetEventCount(ui::ET_GESTURE_TAP)); - EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_TAP)); - EXPECT_EQ(1, v3->GetEventCount(ui::ET_GESTURE_TAP)); - EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_TAP)); - EXPECT_FALSE(tap.handled()); - EXPECT_EQ(v3, GetGestureHandler(root_view)); - - widget->Close(); -} - -// Tests that gesture scroll events will change the default gesture handler in -// RootView if the current handler to which they are dispatched does not handle -// gesture scroll events. -TEST_F(WidgetTest, ScrollGestureEventDispatch) { - Widget* widget = CreateTopLevelNativeWidget(); - widget->SetBounds(gfx::Rect(0, 0, 300, 300)); - - // Define a hierarchy of four views (coordinates are in - // their parent coordinate space). - // v1 (0, 0, 300, 300) - // v2 (0, 0, 100, 100) - // v3 (0, 0, 50, 50) - // v4(0, 0, 10, 10) - EventCountView* v1 = new EventCountView(); - v1->SetBounds(0, 0, 300, 300); - EventCountView* v2 = new EventCountView(); - v2->SetBounds(0, 0, 100, 100); - EventCountView* v3 = new EventCountView(); - v3->SetBounds(0, 0, 50, 50); - EventCountView* v4 = new EventCountView(); - v4->SetBounds(0, 0, 10, 10); - internal::RootView* root_view = - static_cast<internal::RootView*>(widget->GetRootView()); - root_view->AddChildView(v1); - v1->AddChildView(v2); - v2->AddChildView(v3); - v3->AddChildView(v4); - - widget->Show(); - - // Change the handle mode of |v3| to indicate that it would like to handle - // gesture events. - v3->set_handle_mode(EventCountView::CONSUME_EVENTS); - - // When no gesture handler is set, dispatching a ui::ET_GESTURE_TAP_DOWN - // should bubble up the views hierarchy until it reaches the first view - // that will handle it (|v3|) and then sets the handler to |v3|. - EXPECT_EQ(NULL, GetGestureHandler(root_view)); - GestureEventForTest tap_down(ui::ET_GESTURE_TAP_DOWN, 5, 5); - widget->OnGestureEvent(&tap_down); - EXPECT_EQ(0, v1->GetEventCount(ui::ET_GESTURE_TAP_DOWN)); - EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_TAP_DOWN)); - EXPECT_EQ(1, v3->GetEventCount(ui::ET_GESTURE_TAP_DOWN)); - EXPECT_EQ(1, v4->GetEventCount(ui::ET_GESTURE_TAP_DOWN)); - EXPECT_EQ(v3, GetGestureHandler(root_view)); - EXPECT_TRUE(tap_down.handled()); - v1->ResetCounts(); - v2->ResetCounts(); - v3->ResetCounts(); - v4->ResetCounts(); - - // A ui::ET_GESTURE_TAP_CANCEL event should be dispatched to |v3| directly. - GestureEventForTest tap_cancel(ui::ET_GESTURE_TAP_CANCEL, 5, 5); - widget->OnGestureEvent(&tap_cancel); - EXPECT_EQ(0, v1->GetEventCount(ui::ET_GESTURE_TAP_CANCEL)); - EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_TAP_CANCEL)); - EXPECT_EQ(1, v3->GetEventCount(ui::ET_GESTURE_TAP_CANCEL)); - EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_TAP_CANCEL)); - EXPECT_EQ(v3, GetGestureHandler(root_view)); - EXPECT_TRUE(tap_cancel.handled()); - v1->ResetCounts(); - v2->ResetCounts(); - v3->ResetCounts(); - v4->ResetCounts(); - - // Change the handle mode of |v3| to indicate that it would no longer like - // to handle events, and change the mode of |v1| to indicate that it would - // like to handle events. - v3->set_handle_mode(EventCountView::PROPAGATE_EVENTS); - v1->set_handle_mode(EventCountView::CONSUME_EVENTS); - - // Dispatch a ui::ET_GESTURE_SCROLL_BEGIN event. Because the current gesture - // handler (|v3|) does not handle scroll events, the event should bubble up - // the views hierarchy until it reaches the first view that will handle - // it (|v1|) and then sets the handler to |v1|. - GestureEventForTest scroll_begin(ui::ET_GESTURE_SCROLL_BEGIN, 5, 5); - widget->OnGestureEvent(&scroll_begin); - EXPECT_EQ(1, v1->GetEventCount(ui::ET_GESTURE_SCROLL_BEGIN)); - EXPECT_EQ(1, v2->GetEventCount(ui::ET_GESTURE_SCROLL_BEGIN)); - EXPECT_EQ(1, v3->GetEventCount(ui::ET_GESTURE_SCROLL_BEGIN)); - EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_SCROLL_BEGIN)); - EXPECT_EQ(v1, GetGestureHandler(root_view)); - EXPECT_TRUE(scroll_begin.handled()); - v1->ResetCounts(); - v2->ResetCounts(); - v3->ResetCounts(); - v4->ResetCounts(); - - // A ui::ET_GESTURE_SCROLL_UPDATE event should be dispatched to |v1| - // directly. - GestureEventForTest scroll_update(ui::ET_GESTURE_SCROLL_UPDATE, 5, 5); - widget->OnGestureEvent(&scroll_update); - EXPECT_EQ(1, v1->GetEventCount(ui::ET_GESTURE_SCROLL_UPDATE)); - EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_SCROLL_UPDATE)); - EXPECT_EQ(0, v3->GetEventCount(ui::ET_GESTURE_SCROLL_UPDATE)); - EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_SCROLL_UPDATE)); - EXPECT_EQ(v1, GetGestureHandler(root_view)); - EXPECT_TRUE(scroll_update.handled()); - v1->ResetCounts(); - v2->ResetCounts(); - v3->ResetCounts(); - v4->ResetCounts(); - - // A ui::ET_GESTURE_SCROLL_END event should be dispatched to |v1| - // directly and should not reset the gesture handler. - GestureEventForTest scroll_end(ui::ET_GESTURE_SCROLL_END, 5, 5); - widget->OnGestureEvent(&scroll_end); - EXPECT_EQ(1, v1->GetEventCount(ui::ET_GESTURE_SCROLL_END)); - EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_SCROLL_END)); - EXPECT_EQ(0, v3->GetEventCount(ui::ET_GESTURE_SCROLL_END)); - EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_SCROLL_END)); - EXPECT_EQ(v1, GetGestureHandler(root_view)); - EXPECT_TRUE(scroll_end.handled()); - v1->ResetCounts(); - v2->ResetCounts(); - v3->ResetCounts(); - v4->ResetCounts(); - - // A ui::ET_GESTURE_PINCH_BEGIN event (which is a non-scroll event) should - // still be dispatched to |v1| directly. - GestureEventForTest pinch_begin(ui::ET_GESTURE_PINCH_BEGIN, 5, 5); - widget->OnGestureEvent(&pinch_begin); - EXPECT_EQ(1, v1->GetEventCount(ui::ET_GESTURE_PINCH_BEGIN)); - EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_PINCH_BEGIN)); - EXPECT_EQ(0, v3->GetEventCount(ui::ET_GESTURE_PINCH_BEGIN)); - EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_PINCH_BEGIN)); - EXPECT_EQ(v1, GetGestureHandler(root_view)); - EXPECT_TRUE(pinch_begin.handled()); - v1->ResetCounts(); - v2->ResetCounts(); - v3->ResetCounts(); - v4->ResetCounts(); - - // A ui::ET_GESTURE_END event should be dispatched to |v1| and should - // set the gesture handler to NULL. - GestureEventForTest end(ui::ET_GESTURE_END, 5, 5); - widget->OnGestureEvent(&end); - EXPECT_EQ(1, v1->GetEventCount(ui::ET_GESTURE_END)); - EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_END)); - EXPECT_EQ(0, v3->GetEventCount(ui::ET_GESTURE_END)); - EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_END)); - EXPECT_EQ(NULL, GetGestureHandler(root_view)); - EXPECT_TRUE(end.handled()); - - widget->Close(); -} - -// A class used in WidgetTest.GestureEventLocationWhileBubbling to verify -// that when a gesture event bubbles up a View hierarchy, the location -// of a gesture event seen by each View is in the local coordinate space -// of that View. -class GestureLocationView : public EventCountView { - public: - GestureLocationView() {} - virtual ~GestureLocationView() {} - - void set_expected_location(gfx::Point expected_location) { - expected_location_ = expected_location; - } - - // EventCountView: - virtual void OnGestureEvent(ui::GestureEvent* event) override { - EventCountView::OnGestureEvent(event); - - // Verify that the location of |event| is in the local coordinate - // space of |this|. - EXPECT_EQ(expected_location_, event->location()); - } - - private: - // The expected location of a gesture event dispatched to |this|. - gfx::Point expected_location_; - - DISALLOW_COPY_AND_ASSIGN(GestureLocationView); -}; - -// Verifies that the location of a gesture event is always in the local -// coordinate space of the View receiving the event while bubbling. -TEST_F(WidgetTest, GestureEventLocationWhileBubbling) { - Widget* widget = CreateTopLevelNativeWidget(); - widget->SetBounds(gfx::Rect(0, 0, 300, 300)); - - // Define a hierarchy of three views (coordinates shown below are in the - // coordinate space of the root view, but the coordinates used for - // SetBounds() are in their parent coordinate space). - // v1 (50, 50, 150, 150) - // v2 (100, 70, 50, 80) - // v3 (120, 100, 10, 10) - GestureLocationView* v1 = new GestureLocationView(); - v1->SetBounds(50, 50, 150, 150); - GestureLocationView* v2 = new GestureLocationView(); - v2->SetBounds(50, 20, 50, 80); - GestureLocationView* v3 = new GestureLocationView(); - v3->SetBounds(20, 30, 10, 10); - internal::RootView* root_view = - static_cast<internal::RootView*>(widget->GetRootView()); - root_view->AddChildView(v1); - v1->AddChildView(v2); - v2->AddChildView(v3); - - widget->Show(); - - // Define a GESTURE_TAP event located at (125, 105) in root view coordinates. - // This event is contained within all of |v1|, |v2|, and |v3|. - gfx::Point location_in_root(125, 105); - GestureEventForTest tap( - ui::ET_GESTURE_TAP, location_in_root.x(), location_in_root.y()); - - // Calculate the location of the event in the local coordinate spaces - // of each of the views. - gfx::Point location_in_v1(ConvertPointFromWidgetToView(v1, location_in_root)); - EXPECT_EQ(gfx::Point(75, 55), location_in_v1); - gfx::Point location_in_v2(ConvertPointFromWidgetToView(v2, location_in_root)); - EXPECT_EQ(gfx::Point(25, 35), location_in_v2); - gfx::Point location_in_v3(ConvertPointFromWidgetToView(v3, location_in_root)); - EXPECT_EQ(gfx::Point(5, 5), location_in_v3); - - // Dispatch the event. When each view receives the event, its location should - // be in the local coordinate space of that view (see the check made by - // GestureLocationView). After dispatch is complete the event's location - // should be in the root coordinate space. - v1->set_expected_location(location_in_v1); - v2->set_expected_location(location_in_v2); - v3->set_expected_location(location_in_v3); - widget->OnGestureEvent(&tap); - EXPECT_EQ(location_in_root, tap.location()); - - // Verify that each view did in fact see the event. - EventCountView* view1 = v1; - EventCountView* view2 = v2; - EventCountView* view3 = v3; - EXPECT_EQ(1, view1->GetEventCount(ui::ET_GESTURE_TAP)); - EXPECT_EQ(1, view2->GetEventCount(ui::ET_GESTURE_TAP)); - EXPECT_EQ(1, view3->GetEventCount(ui::ET_GESTURE_TAP)); - - widget->Close(); -} - -// Verifies that disabled views are permitted to be set as the default gesture -// handler in RootView. Also verifies that gesture events targeted to a disabled -// view are not actually dispatched to the view, but are still marked as -// handled. -TEST_F(WidgetTest, DisabledGestureEventTarget) { - Widget* widget = CreateTopLevelNativeWidget(); - widget->SetBounds(gfx::Rect(0, 0, 300, 300)); - - // Define a hierarchy of four views (coordinates are in - // their parent coordinate space). - // v1 (0, 0, 300, 300) - // v2 (0, 0, 100, 100) - // v3 (0, 0, 50, 50) - // v4(0, 0, 10, 10) - EventCountView* v1 = new EventCountView(); - v1->SetBounds(0, 0, 300, 300); - EventCountView* v2 = new EventCountView(); - v2->SetBounds(0, 0, 100, 100); - EventCountView* v3 = new EventCountView(); - v3->SetBounds(0, 0, 50, 50); - EventCountView* v4 = new EventCountView(); - v4->SetBounds(0, 0, 10, 10); - internal::RootView* root_view = - static_cast<internal::RootView*>(widget->GetRootView()); - root_view->AddChildView(v1); - v1->AddChildView(v2); - v2->AddChildView(v3); - v3->AddChildView(v4); - - widget->Show(); - - // |v1|, |v2|, and |v3| all handle gesture events but |v3| is marked as - // disabled. - v1->set_handle_mode(EventCountView::CONSUME_EVENTS); - v2->set_handle_mode(EventCountView::CONSUME_EVENTS); - v3->set_handle_mode(EventCountView::CONSUME_EVENTS); - v3->SetEnabled(false); - - // No gesture handler is set in the root view. In this case the tap event - // should be dispatched only to |v4|, the gesture handler should be set to - // |v3|, and the event should be marked as handled. - GestureEventForTest tap(ui::ET_GESTURE_TAP, 5, 5); - widget->OnGestureEvent(&tap); - EXPECT_EQ(0, v1->GetEventCount(ui::ET_GESTURE_TAP)); - EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_TAP)); - EXPECT_EQ(0, v3->GetEventCount(ui::ET_GESTURE_TAP)); - EXPECT_EQ(1, v4->GetEventCount(ui::ET_GESTURE_TAP)); - EXPECT_EQ(v3, GetGestureHandler(root_view)); - EXPECT_TRUE(tap.handled()); - v1->ResetCounts(); - v2->ResetCounts(); - v3->ResetCounts(); - v4->ResetCounts(); - - // A subsequent gesture event should be marked as handled but not dispatched. - tap = GestureEventForTest(ui::ET_GESTURE_TAP, 5, 5); - widget->OnGestureEvent(&tap); - EXPECT_EQ(0, v1->GetEventCount(ui::ET_GESTURE_TAP)); - EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_TAP)); - EXPECT_EQ(0, v3->GetEventCount(ui::ET_GESTURE_TAP)); - EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_TAP)); - EXPECT_EQ(v3, GetGestureHandler(root_view)); - EXPECT_TRUE(tap.handled()); - v1->ResetCounts(); - v2->ResetCounts(); - v3->ResetCounts(); - v4->ResetCounts(); - - // A GESTURE_END should reset the default gesture handler to NULL. It should - // also not be dispatched to |v3| but still marked as handled. - GestureEventForTest end(ui::ET_GESTURE_END, 5, 5); - widget->OnGestureEvent(&end); - EXPECT_EQ(0, v1->GetEventCount(ui::ET_GESTURE_END)); - EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_END)); - EXPECT_EQ(0, v3->GetEventCount(ui::ET_GESTURE_END)); - EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_END)); - EXPECT_EQ(NULL, GetGestureHandler(root_view)); - EXPECT_TRUE(end.handled()); - v1->ResetCounts(); - v2->ResetCounts(); - v3->ResetCounts(); - v4->ResetCounts(); - - // Change the handle mode of |v3| to indicate that it would no longer like - // to handle events which are dispatched to it. - v3->set_handle_mode(EventCountView::PROPAGATE_EVENTS); - - // No gesture handler is set in the root view. In this case the tap event - // should be dispatched only to |v4| and the event should be marked as - // handled. Furthermore, the gesture handler should be set to - // |v3|; even though |v3| does not explicitly handle events, it is a - // valid target for the tap event because it is disabled. - tap = GestureEventForTest(ui::ET_GESTURE_TAP, 5, 5); - widget->OnGestureEvent(&tap); - EXPECT_EQ(0, v1->GetEventCount(ui::ET_GESTURE_TAP)); - EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_TAP)); - EXPECT_EQ(0, v3->GetEventCount(ui::ET_GESTURE_TAP)); - EXPECT_EQ(1, v4->GetEventCount(ui::ET_GESTURE_TAP)); - EXPECT_EQ(v3, GetGestureHandler(root_view)); - EXPECT_TRUE(tap.handled()); - v1->ResetCounts(); - v2->ResetCounts(); - v3->ResetCounts(); - v4->ResetCounts(); - - // A GESTURE_END should reset the default gesture handler to NULL. It should - // also not be dispatched to |v3| but still marked as handled. - end = GestureEventForTest(ui::ET_GESTURE_END, 5, 5); - widget->OnGestureEvent(&end); - EXPECT_EQ(0, v1->GetEventCount(ui::ET_GESTURE_END)); - EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_END)); - EXPECT_EQ(0, v3->GetEventCount(ui::ET_GESTURE_END)); - EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_END)); - EXPECT_EQ(NULL, GetGestureHandler(root_view)); - EXPECT_TRUE(end.handled()); - - widget->Close(); -} - -// Test the result of Widget::GetAllChildWidgets(). -TEST_F(WidgetTest, GetAllChildWidgets) { - // Create the following widget hierarchy: - // - // toplevel - // +-- w1 - // +-- w11 - // +-- w2 - // +-- w21 - // +-- w22 - Widget* toplevel = CreateTopLevelPlatformWidget(); - Widget* w1 = CreateChildPlatformWidget(toplevel->GetNativeView()); - Widget* w11 = CreateChildPlatformWidget(w1->GetNativeView()); - Widget* w2 = CreateChildPlatformWidget(toplevel->GetNativeView()); - Widget* w21 = CreateChildPlatformWidget(w2->GetNativeView()); - Widget* w22 = CreateChildPlatformWidget(w2->GetNativeView()); - - std::set<Widget*> expected; - expected.insert(toplevel); - expected.insert(w1); - expected.insert(w11); - expected.insert(w2); - expected.insert(w21); - expected.insert(w22); - - std::set<Widget*> widgets; - Widget::GetAllChildWidgets(toplevel->GetNativeView(), &widgets); - - EXPECT_EQ(expected.size(), widgets.size()); - EXPECT_TRUE(std::equal(expected.begin(), expected.end(), widgets.begin())); -} - -// Used by DestroyChildWidgetsInOrder. On destruction adds the supplied name to -// a vector. -class DestroyedTrackingView : public View { - public: - DestroyedTrackingView(const std::string& name, - std::vector<std::string>* add_to) - : name_(name), - add_to_(add_to) { - } - - virtual ~DestroyedTrackingView() { - add_to_->push_back(name_); - } - - private: - const std::string name_; - std::vector<std::string>* add_to_; - - DISALLOW_COPY_AND_ASSIGN(DestroyedTrackingView); -}; - -class WidgetChildDestructionTest : public WidgetTest { - public: - WidgetChildDestructionTest() {} - - // Creates a top level and a child, destroys the child and verifies the views - // of the child are destroyed before the views of the parent. - void RunDestroyChildWidgetsTest(bool top_level_has_desktop_native_widget_aura, - bool child_has_desktop_native_widget_aura) { - // When a View is destroyed its name is added here. - std::vector<std::string> destroyed; - - Widget* top_level = new Widget; - Widget::InitParams params = - CreateParams(views::Widget::InitParams::TYPE_WINDOW); -#if !defined(OS_CHROMEOS) - if (top_level_has_desktop_native_widget_aura) - params.native_widget = new PlatformDesktopNativeWidget(top_level); -#endif - top_level->Init(params); - top_level->GetRootView()->AddChildView( - new DestroyedTrackingView("parent", &destroyed)); - top_level->Show(); - - Widget* child = new Widget; - Widget::InitParams child_params = - CreateParams(views::Widget::InitParams::TYPE_POPUP); - child_params.parent = top_level->GetNativeView(); -#if !defined(OS_CHROMEOS) - if (child_has_desktop_native_widget_aura) - child_params.native_widget = new PlatformDesktopNativeWidget(child); -#endif - child->Init(child_params); - child->GetRootView()->AddChildView( - new DestroyedTrackingView("child", &destroyed)); - child->Show(); - - // Should trigger destruction of the child too. - top_level->native_widget_private()->CloseNow(); - - // Child should be destroyed first. - ASSERT_EQ(2u, destroyed.size()); - EXPECT_EQ("child", destroyed[0]); - EXPECT_EQ("parent", destroyed[1]); - } - - private: - DISALLOW_COPY_AND_ASSIGN(WidgetChildDestructionTest); -}; - -#if !defined(OS_CHROMEOS) -// See description of RunDestroyChildWidgetsTest(). Parent uses -// DesktopNativeWidgetAura. -TEST_F(WidgetChildDestructionTest, - DestroyChildWidgetsInOrderWithDesktopNativeWidget) { - RunDestroyChildWidgetsTest(true, false); -} - -// See description of RunDestroyChildWidgetsTest(). Both parent and child use -// DesktopNativeWidgetAura. -TEST_F(WidgetChildDestructionTest, - DestroyChildWidgetsInOrderWithDesktopNativeWidgetForBoth) { - RunDestroyChildWidgetsTest(true, true); -} -#endif // !defined(OS_CHROMEOS) - -// See description of RunDestroyChildWidgetsTest(). -TEST_F(WidgetChildDestructionTest, DestroyChildWidgetsInOrder) { - RunDestroyChildWidgetsTest(false, false); -} - -#if !defined(OS_CHROMEOS) -// Provides functionality to create a window modal dialog. -class ModalDialogDelegate : public DialogDelegateView { - public: - ModalDialogDelegate() {} - virtual ~ModalDialogDelegate() {} - - // WidgetDelegate overrides. - virtual ui::ModalType GetModalType() const override { - return ui::MODAL_TYPE_WINDOW; - } - - private: - DISALLOW_COPY_AND_ASSIGN(ModalDialogDelegate); -}; - -// This test verifies that whether mouse events when a modal dialog is -// displayed are eaten or recieved by the dialog. -TEST_F(WidgetTest, WindowMouseModalityTest) { - // Create a top level widget. - Widget top_level_widget; - Widget::InitParams init_params = - CreateParams(Widget::InitParams::TYPE_WINDOW); - init_params.show_state = ui::SHOW_STATE_NORMAL; - gfx::Rect initial_bounds(0, 0, 500, 500); - init_params.bounds = initial_bounds; - init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - init_params.native_widget = - new PlatformDesktopNativeWidget(&top_level_widget); - top_level_widget.Init(init_params); - top_level_widget.Show(); - EXPECT_TRUE(top_level_widget.IsVisible()); - - // Create a view and validate that a mouse moves makes it to the view. - EventCountView* widget_view = new EventCountView(); - widget_view->SetBounds(0, 0, 10, 10); - top_level_widget.GetRootView()->AddChildView(widget_view); - - gfx::Point cursor_location_main(5, 5); - ui::MouseEvent move_main(ui::ET_MOUSE_MOVED, - cursor_location_main, - cursor_location_main, - ui::EF_NONE, - ui::EF_NONE); - ui::EventDispatchDetails details = - GetEventProcessor(&top_level_widget)->OnEventFromSource(&move_main); - ASSERT_FALSE(details.dispatcher_destroyed); - - EXPECT_EQ(1, widget_view->GetEventCount(ui::ET_MOUSE_ENTERED)); - widget_view->ResetCounts(); - - // Create a modal dialog and validate that a mouse down message makes it to - // the main view within the dialog. - - // This instance will be destroyed when the dialog is destroyed. - ModalDialogDelegate* dialog_delegate = new ModalDialogDelegate; - - Widget* modal_dialog_widget = views::DialogDelegate::CreateDialogWidget( - dialog_delegate, NULL, top_level_widget.GetNativeView()); - modal_dialog_widget->SetBounds(gfx::Rect(100, 100, 200, 200)); - EventCountView* dialog_widget_view = new EventCountView(); - dialog_widget_view->SetBounds(0, 0, 50, 50); - modal_dialog_widget->GetRootView()->AddChildView(dialog_widget_view); - modal_dialog_widget->Show(); - EXPECT_TRUE(modal_dialog_widget->IsVisible()); - - gfx::Point cursor_location_dialog(100, 100); - ui::MouseEvent mouse_down_dialog(ui::ET_MOUSE_PRESSED, - cursor_location_dialog, - cursor_location_dialog, - ui::EF_NONE, - ui::EF_NONE); - details = GetEventProcessor(&top_level_widget)->OnEventFromSource( - &mouse_down_dialog); - ASSERT_FALSE(details.dispatcher_destroyed); - EXPECT_EQ(1, dialog_widget_view->GetEventCount(ui::ET_MOUSE_PRESSED)); - - // Send a mouse move message to the main window. It should not be received by - // the main window as the modal dialog is still active. - gfx::Point cursor_location_main2(6, 6); - ui::MouseEvent mouse_down_main(ui::ET_MOUSE_MOVED, - cursor_location_main2, - cursor_location_main2, - ui::EF_NONE, - ui::EF_NONE); - details = GetEventProcessor(&top_level_widget)->OnEventFromSource( - &mouse_down_main); - ASSERT_FALSE(details.dispatcher_destroyed); - EXPECT_EQ(0, widget_view->GetEventCount(ui::ET_MOUSE_MOVED)); - - modal_dialog_widget->CloseNow(); - top_level_widget.CloseNow(); -} - -// Verifies nativeview visbility matches that of Widget visibility when -// SetFullscreen is invoked. -TEST_F(WidgetTest, FullscreenStatePropagated) { - Widget::InitParams init_params = - CreateParams(Widget::InitParams::TYPE_WINDOW); - init_params.show_state = ui::SHOW_STATE_NORMAL; - init_params.bounds = gfx::Rect(0, 0, 500, 500); - init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - - { - Widget top_level_widget; - top_level_widget.Init(init_params); - top_level_widget.SetFullscreen(true); - EXPECT_EQ(top_level_widget.IsVisible(), - IsNativeWindowVisible(top_level_widget.GetNativeWindow())); - top_level_widget.CloseNow(); - } -#if !defined(OS_CHROMEOS) - { - Widget top_level_widget; - init_params.native_widget = - new PlatformDesktopNativeWidget(&top_level_widget); - top_level_widget.Init(init_params); - top_level_widget.SetFullscreen(true); - EXPECT_EQ(top_level_widget.IsVisible(), - IsNativeWindowVisible(top_level_widget.GetNativeWindow())); - top_level_widget.CloseNow(); - } -#endif -} -#if defined(OS_WIN) - -// Provides functionality to test widget activation via an activation flag -// which can be set by an accessor. -class ModalWindowTestWidgetDelegate : public WidgetDelegate { - public: - ModalWindowTestWidgetDelegate() - : widget_(NULL), - can_activate_(true) {} - - virtual ~ModalWindowTestWidgetDelegate() {} - - // Overridden from WidgetDelegate: - virtual void DeleteDelegate() override { - delete this; - } - virtual Widget* GetWidget() override { - return widget_; - } - virtual const Widget* GetWidget() const override { - return widget_; - } - virtual bool CanActivate() const override { - return can_activate_; - } - virtual bool ShouldAdvanceFocusToTopLevelWidget() const override { - return true; - } - - void set_can_activate(bool can_activate) { - can_activate_ = can_activate; - } - - void set_widget(Widget* widget) { - widget_ = widget; - } - - private: - Widget* widget_; - bool can_activate_; - - DISALLOW_COPY_AND_ASSIGN(ModalWindowTestWidgetDelegate); -}; - -// Tests whether we can activate the top level widget when a modal dialog is -// active. -TEST_F(WidgetTest, WindowModalityActivationTest) { - // Destroyed when the top level widget created below is destroyed. - ModalWindowTestWidgetDelegate* widget_delegate = - new ModalWindowTestWidgetDelegate; - // Create a top level widget. - Widget top_level_widget; - Widget::InitParams init_params = - CreateParams(Widget::InitParams::TYPE_WINDOW); - init_params.show_state = ui::SHOW_STATE_NORMAL; - gfx::Rect initial_bounds(0, 0, 500, 500); - init_params.bounds = initial_bounds; - init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - init_params.native_widget = new DesktopNativeWidgetAura(&top_level_widget); - init_params.delegate = widget_delegate; - top_level_widget.Init(init_params); - widget_delegate->set_widget(&top_level_widget); - top_level_widget.Show(); - EXPECT_TRUE(top_level_widget.IsVisible()); - - HWND win32_window = views::HWNDForWidget(&top_level_widget); - EXPECT_TRUE(::IsWindow(win32_window)); - - // This instance will be destroyed when the dialog is destroyed. - ModalDialogDelegate* dialog_delegate = new ModalDialogDelegate; - - // We should be able to activate the window even if the WidgetDelegate - // says no, when a modal dialog is active. - widget_delegate->set_can_activate(false); - - Widget* modal_dialog_widget = views::DialogDelegate::CreateDialogWidget( - dialog_delegate, NULL, top_level_widget.GetNativeWindow()); - modal_dialog_widget->SetBounds(gfx::Rect(100, 100, 200, 200)); - modal_dialog_widget->Show(); - EXPECT_TRUE(modal_dialog_widget->IsVisible()); - - LRESULT activate_result = ::SendMessage( - win32_window, - WM_MOUSEACTIVATE, - reinterpret_cast<WPARAM>(win32_window), - MAKELPARAM(WM_LBUTTONDOWN, HTCLIENT)); - EXPECT_EQ(activate_result, MA_ACTIVATE); - - modal_dialog_widget->CloseNow(); - top_level_widget.CloseNow(); -} -#endif // defined(OS_WIN) -#endif // !defined(OS_CHROMEOS) - -TEST_F(WidgetTest, ShowCreatesActiveWindow) { - Widget* widget = CreateTopLevelPlatformWidget(); - - widget->Show(); - EXPECT_EQ(GetWidgetShowState(widget), ui::SHOW_STATE_NORMAL); - - widget->CloseNow(); -} - -// OSX does not have a per-application "active" window such as provided by -// ::GetActiveWindow() on Windows. There is only a system-wide "keyWindow" which -// is updated asynchronously. -#if defined(OS_MACOSX) -#define MAYBE_ShowInactive DISABLED_ShowInactive -#else -#define MAYBE_ShowInactive ShowInactive -#endif -TEST_F(WidgetTest, MAYBE_ShowInactive) { - Widget* widget = CreateTopLevelPlatformWidget(); - - widget->ShowInactive(); - EXPECT_EQ(GetWidgetShowState(widget), ui::SHOW_STATE_INACTIVE); - - widget->CloseNow(); -} - -TEST_F(WidgetTest, InactiveBeforeShow) { - Widget* widget = CreateTopLevelPlatformWidget(); - - EXPECT_FALSE(widget->IsActive()); - EXPECT_FALSE(widget->IsVisible()); - - widget->Show(); - - EXPECT_TRUE(widget->IsActive()); - EXPECT_TRUE(widget->IsVisible()); - - widget->CloseNow(); -} - -TEST_F(WidgetTest, ShowInactiveAfterShow) { - // Create 2 widgets to ensure window layering does not change. - Widget* widget = CreateTopLevelPlatformWidget(); - Widget* widget2 = CreateTopLevelPlatformWidget(); - - widget2->Show(); - EXPECT_FALSE(widget->IsActive()); - EXPECT_TRUE(widget2->IsVisible()); - EXPECT_TRUE(widget2->IsActive()); - - widget->Show(); - EXPECT_TRUE(widget->IsActive()); - EXPECT_FALSE(widget2->IsActive()); - widget->ShowInactive(); - EXPECT_TRUE(widget->IsActive()); - EXPECT_FALSE(widget2->IsActive()); - EXPECT_EQ(GetWidgetShowState(widget), ui::SHOW_STATE_NORMAL); - - widget2->CloseNow(); - widget->CloseNow(); -} - -TEST_F(WidgetTest, ShowAfterShowInactive) { - Widget* widget = CreateTopLevelPlatformWidget(); - - widget->ShowInactive(); - widget->Show(); - EXPECT_EQ(GetWidgetShowState(widget), ui::SHOW_STATE_NORMAL); - - widget->CloseNow(); -} - -#if !defined(OS_CHROMEOS) -TEST_F(WidgetTest, InactiveWidgetDoesNotGrabActivation) { - Widget* widget = CreateTopLevelPlatformWidget(); - widget->Show(); - EXPECT_EQ(GetWidgetShowState(widget), ui::SHOW_STATE_NORMAL); - - Widget widget2; - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP); - params.native_widget = new PlatformDesktopNativeWidget(&widget2); - params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - widget2.Init(params); - widget2.Show(); - - EXPECT_EQ(GetWidgetShowState(&widget2), ui::SHOW_STATE_INACTIVE); - EXPECT_EQ(GetWidgetShowState(widget), ui::SHOW_STATE_NORMAL); - - widget->CloseNow(); - widget2.CloseNow(); -} -#endif // !defined(OS_CHROMEOS) - -namespace { - -class FullscreenAwareFrame : public views::NonClientFrameView { - public: - explicit FullscreenAwareFrame(views::Widget* widget) - : widget_(widget), fullscreen_layout_called_(false) {} - virtual ~FullscreenAwareFrame() {} - - // views::NonClientFrameView overrides: - virtual gfx::Rect GetBoundsForClientView() const override { - return gfx::Rect(); - } - virtual gfx::Rect GetWindowBoundsForClientBounds( - const gfx::Rect& client_bounds) const override { - return gfx::Rect(); - } - virtual int NonClientHitTest(const gfx::Point& point) override { - return HTNOWHERE; - } - virtual void GetWindowMask(const gfx::Size& size, - gfx::Path* window_mask) override {} - virtual void ResetWindowControls() override {} - virtual void UpdateWindowIcon() override {} - virtual void UpdateWindowTitle() override {} - virtual void SizeConstraintsChanged() override {} - - // views::View overrides: - virtual void Layout() override { - if (widget_->IsFullscreen()) - fullscreen_layout_called_ = true; - } - - bool fullscreen_layout_called() const { return fullscreen_layout_called_; } - - private: - views::Widget* widget_; - bool fullscreen_layout_called_; - - DISALLOW_COPY_AND_ASSIGN(FullscreenAwareFrame); -}; - -} // namespace - -// Tests that frame Layout is called when a widget goes fullscreen without -// changing its size or title. -TEST_F(WidgetTest, FullscreenFrameLayout) { - Widget* widget = CreateTopLevelPlatformWidget(); - FullscreenAwareFrame* frame = new FullscreenAwareFrame(widget); - widget->non_client_view()->SetFrameView(frame); // Owns |frame|. - - widget->Maximize(); - RunPendingMessages(); - - EXPECT_FALSE(frame->fullscreen_layout_called()); - widget->SetFullscreen(true); - widget->Show(); - RunPendingMessages(); - EXPECT_TRUE(frame->fullscreen_layout_called()); - - widget->CloseNow(); -} - -#if !defined(OS_CHROMEOS) -namespace { - -// Trivial WidgetObserverTest that invokes Widget::IsActive() from -// OnWindowDestroying. -class IsActiveFromDestroyObserver : public WidgetObserver { - public: - IsActiveFromDestroyObserver() {} - virtual ~IsActiveFromDestroyObserver() {} - virtual void OnWidgetDestroying(Widget* widget) override { - widget->IsActive(); - } - - private: - DISALLOW_COPY_AND_ASSIGN(IsActiveFromDestroyObserver); -}; - -} // namespace - -// Verifies Widget::IsActive() invoked from -// WidgetObserver::OnWidgetDestroying() in a child widget doesn't crash. -TEST_F(WidgetTest, IsActiveFromDestroy) { - // Create two widgets, one a child of the other. - IsActiveFromDestroyObserver observer; - Widget parent_widget; - Widget::InitParams parent_params = - CreateParams(Widget::InitParams::TYPE_POPUP); - parent_params.native_widget = new PlatformDesktopNativeWidget(&parent_widget); - parent_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - parent_widget.Init(parent_params); - parent_widget.Show(); - - Widget child_widget; - Widget::InitParams child_params = - CreateParams(Widget::InitParams::TYPE_POPUP); - child_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - child_params.context = parent_widget.GetNativeWindow(); - child_widget.Init(child_params); - child_widget.AddObserver(&observer); - child_widget.Show(); - - parent_widget.CloseNow(); -} -#endif // !defined(OS_CHROMEOS) - -// Tests that events propagate through from the dispatcher with the correct -// event type, and that the different platforms behave the same. -TEST_F(WidgetTest, MouseEventTypesViaGenerator) { - EventCountView* view = new EventCountView; - view->set_handle_mode(EventCountView::CONSUME_EVENTS); - view->SetBounds(10, 10, 50, 40); - - Widget* widget = CreateTopLevelFramelessPlatformWidget(); - widget->GetRootView()->AddChildView(view); - - widget->SetBounds(gfx::Rect(0, 0, 100, 80)); - widget->Show(); - - ui::test::EventGenerator generator(GetContext(), widget->GetNativeWindow()); - generator.set_current_location(gfx::Point(20, 20)); - - generator.ClickLeftButton(); - EXPECT_EQ(1, view->GetEventCount(ui::ET_MOUSE_PRESSED)); - EXPECT_EQ(1, view->GetEventCount(ui::ET_MOUSE_RELEASED)); - EXPECT_EQ(ui::EF_LEFT_MOUSE_BUTTON, view->last_flags()); - - generator.PressRightButton(); - EXPECT_EQ(2, view->GetEventCount(ui::ET_MOUSE_PRESSED)); - EXPECT_EQ(1, view->GetEventCount(ui::ET_MOUSE_RELEASED)); - EXPECT_EQ(ui::EF_RIGHT_MOUSE_BUTTON, view->last_flags()); - - generator.ReleaseRightButton(); - EXPECT_EQ(2, view->GetEventCount(ui::ET_MOUSE_PRESSED)); - EXPECT_EQ(2, view->GetEventCount(ui::ET_MOUSE_RELEASED)); - EXPECT_EQ(ui::EF_RIGHT_MOUSE_BUTTON, view->last_flags()); - - // Test mouse move events. - EXPECT_EQ(0, view->GetEventCount(ui::ET_MOUSE_MOVED)); - EXPECT_EQ(0, view->GetEventCount(ui::ET_MOUSE_ENTERED)); - - // Move the mouse within the view (20, 20) -> (30, 30). - generator.MoveMouseTo(gfx::Point(30, 30)); - EXPECT_EQ(1, view->GetEventCount(ui::ET_MOUSE_MOVED)); - EXPECT_EQ(1, view->GetEventCount(ui::ET_MOUSE_ENTERED)); - EXPECT_EQ(ui::EF_NONE, view->last_flags()); - - // Move it again - entered count shouldn't change. - generator.MoveMouseTo(gfx::Point(31, 31)); - EXPECT_EQ(2, view->GetEventCount(ui::ET_MOUSE_MOVED)); - EXPECT_EQ(1, view->GetEventCount(ui::ET_MOUSE_ENTERED)); - EXPECT_EQ(0, view->GetEventCount(ui::ET_MOUSE_EXITED)); - - // Move it off the view. - generator.MoveMouseTo(gfx::Point(5, 5)); - EXPECT_EQ(2, view->GetEventCount(ui::ET_MOUSE_MOVED)); - EXPECT_EQ(1, view->GetEventCount(ui::ET_MOUSE_ENTERED)); - EXPECT_EQ(1, view->GetEventCount(ui::ET_MOUSE_EXITED)); - - // Move it back on. - generator.MoveMouseTo(gfx::Point(20, 20)); - EXPECT_EQ(3, view->GetEventCount(ui::ET_MOUSE_MOVED)); - EXPECT_EQ(2, view->GetEventCount(ui::ET_MOUSE_ENTERED)); - EXPECT_EQ(1, view->GetEventCount(ui::ET_MOUSE_EXITED)); - - // Drargging. Cover HasCapture() and NativeWidgetPrivate::IsMouseButtonDown(). - generator.DragMouseTo(gfx::Point(40, 40)); - EXPECT_EQ(3, view->GetEventCount(ui::ET_MOUSE_PRESSED)); - EXPECT_EQ(3, view->GetEventCount(ui::ET_MOUSE_RELEASED)); - EXPECT_EQ(1, view->GetEventCount(ui::ET_MOUSE_DRAGGED)); - EXPECT_EQ(ui::EF_LEFT_MOUSE_BUTTON, view->last_flags()); - - widget->CloseNow(); -} - -// Tests that a view does not receive entered, dragged, or moved events if -// a mouse cursor is moved into it while the left mouse button is pressed. -TEST_F(WidgetTest, DragIntoView) { - EventCountView* container = new EventCountView; - container->SetBounds(0, 0, 100, 80); - - EventCountView* consume_view = new EventCountView; - consume_view->set_handle_mode(EventCountView::CONSUME_EVENTS); - consume_view->SetBounds(10, 10, 50, 40); - - Widget* widget = CreateTopLevelFramelessPlatformWidget(); - widget->SetBounds(gfx::Rect(0, 0, 100, 80)); - widget->SetContentsView(container); - container->AddChildView(consume_view); - - widget->Show(); - - ui::test::EventGenerator generator(GetContext(), widget->GetNativeWindow()); - generator.set_current_location(gfx::Point(75, 15)); - - generator.PressLeftButton(); - generator.MoveMouseTo(gfx::Point(20, 20)); - EXPECT_EQ(0, consume_view->GetEventCount(ui::ET_MOUSE_ENTERED)); - EXPECT_EQ(0, consume_view->GetEventCount(ui::ET_MOUSE_DRAGGED)); - EXPECT_EQ(0, consume_view->GetEventCount(ui::ET_MOUSE_MOVED)); - - widget->CloseNow(); -} - -// Tests that a view receives the correct mouse events if a mouse cursor -// is moved out of its bounds while the left mouse button is pressed. -TEST_F(WidgetTest, DragOutOfView) { - EventCountView* container = new EventCountView; - container->SetBounds(0, 0, 100, 80); - - EventCountView* consume_view = new EventCountView; - consume_view->set_handle_mode(EventCountView::CONSUME_EVENTS); - consume_view->SetBounds(10, 10, 50, 40); - - Widget* widget = CreateTopLevelFramelessPlatformWidget(); - widget->SetBounds(gfx::Rect(0, 0, 100, 80)); - widget->SetContentsView(container); - container->AddChildView(consume_view); - - widget->Show(); - - ui::test::EventGenerator generator(GetContext(), widget->GetNativeWindow()); - generator.set_current_location(gfx::Point(20, 20)); - - generator.PressLeftButton(); - EXPECT_EQ(1, consume_view->GetEventCount(ui::ET_MOUSE_PRESSED)); - EXPECT_EQ(0, container->GetEventCount(ui::ET_MOUSE_PRESSED)); - consume_view->ResetCounts(); - - generator.MoveMouseTo(gfx::Point(70, 70)); - EXPECT_EQ(0, consume_view->GetEventCount(ui::ET_MOUSE_EXITED)); - EXPECT_EQ(1, consume_view->GetEventCount(ui::ET_MOUSE_DRAGGED)); - EXPECT_EQ(0, consume_view->GetEventCount(ui::ET_MOUSE_MOVED)); - EXPECT_EQ(0, container->GetEventCount(ui::ET_MOUSE_ENTERED)); - EXPECT_EQ(0, container->GetEventCount(ui::ET_MOUSE_DRAGGED)); - EXPECT_EQ(0, container->GetEventCount(ui::ET_MOUSE_MOVED)); - consume_view->ResetCounts(); - - generator.MoveMouseTo(gfx::Point(71, 71)); - EXPECT_EQ(1, consume_view->GetEventCount(ui::ET_MOUSE_DRAGGED)); - EXPECT_EQ(0, consume_view->GetEventCount(ui::ET_MOUSE_MOVED)); - EXPECT_EQ(0, container->GetEventCount(ui::ET_MOUSE_DRAGGED)); - EXPECT_EQ(0, container->GetEventCount(ui::ET_MOUSE_MOVED)); - consume_view->ResetCounts(); - - generator.ReleaseLeftButton(); - EXPECT_EQ(1, consume_view->GetEventCount(ui::ET_MOUSE_RELEASED)); - EXPECT_EQ(0, container->GetEventCount(ui::ET_MOUSE_RELEASED)); - consume_view->ResetCounts(); - - widget->CloseNow(); -} - -// Tests that the root view is correctly set up for Widget types that do not -// require a non-client view, before any other views are added to the widget. -// That is, before Widget::ReorderNativeViews() is called which, if called with -// a root view not set, could cause the root view to get resized to the widget. -TEST_F(WidgetTest, NonClientWindowValidAfterInit) { - Widget* widget = CreateTopLevelFramelessPlatformWidget(); - View* root_view = widget->GetRootView(); - - // Size the root view to exceed the widget bounds. - const gfx::Rect test_rect(0, 0, 500, 500); - root_view->SetBoundsRect(test_rect); - - EXPECT_NE(test_rect.size(), widget->GetWindowBoundsInScreen().size()); - - EXPECT_EQ(test_rect, root_view->bounds()); - widget->ReorderNativeViews(); - EXPECT_EQ(test_rect, root_view->bounds()); - - widget->CloseNow(); -} - -} // namespace test -} // namespace views
diff --git a/ui/views/widget/window_reorderer.cc b/ui/views/widget/window_reorderer.cc deleted file mode 100644 index 098796c..0000000 --- a/ui/views/widget/window_reorderer.cc +++ /dev/null
@@ -1,201 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/widget/window_reorderer.h" - -#include <map> -#include <vector> - -#include "ui/aura/window.h" -#include "ui/views/view.h" -#include "ui/views/view_constants_aura.h" - -namespace views { - -namespace { - -// Sets |hosted_windows| to a mapping of the views with an associated window to -// the window that they are associated to. Only views associated to a child of -// |parent_window| are returned. -void GetViewsWithAssociatedWindow( - const aura::Window& parent_window, - std::map<views::View*, aura::Window*>* hosted_windows) { - const std::vector<aura::Window*>& child_windows = parent_window.children(); - for (size_t i = 0; i < child_windows.size(); ++i) { - aura::Window* child = child_windows[i]; - View* host_view = child->GetProperty(kHostViewKey); - if (host_view) - (*hosted_windows)[host_view] = child; - } -} - -// Sets |order| to the list of views whose layer / associated window's layer -// is a child of |parent_layer|. |order| is sorted in ascending z-order of -// the views. -// |hosts| are the views with an associated window whose layer is a child of -// |parent_layer|. -void GetOrderOfViewsWithLayers( - views::View* view, - ui::Layer* parent_layer, - const std::map<views::View*, aura::Window*>& hosts, - std::vector<views::View*>* order) { - DCHECK(view); - DCHECK(parent_layer); - DCHECK(order); - if (view->layer() && view->layer()->parent() == parent_layer) { - order->push_back(view); - // |hosts| may contain a child of |view|. - } else if (hosts.find(view) != hosts.end()) { - order->push_back(view); - } - - for (int i = 0; i < view->child_count(); ++i) - GetOrderOfViewsWithLayers(view->child_at(i), parent_layer, hosts, order); -} - -} // namespace - -// Class which reorders windows as a result of the kHostViewKey property being -// set on the window. -class WindowReorderer::AssociationObserver : public aura::WindowObserver { - public: - explicit AssociationObserver(WindowReorderer* reorderer); - virtual ~AssociationObserver(); - - // Start/stop observing changes in the kHostViewKey property on |window|. - void StartObserving(aura::Window* window); - void StopObserving(aura::Window* window); - - private: - // aura::WindowObserver overrides: - virtual void OnWindowPropertyChanged(aura::Window* window, - const void* key, - intptr_t old) override; - virtual void OnWindowDestroying(aura::Window* window) override; - - // Not owned. - WindowReorderer* reorderer_; - - std::set<aura::Window*> windows_; - - DISALLOW_COPY_AND_ASSIGN(AssociationObserver); -}; - -WindowReorderer::AssociationObserver::AssociationObserver( - WindowReorderer* reorderer) - : reorderer_(reorderer) { -} - -WindowReorderer::AssociationObserver::~AssociationObserver() { - while (!windows_.empty()) - StopObserving(*windows_.begin()); -} - -void WindowReorderer::AssociationObserver::StartObserving( - aura::Window* window) { - windows_.insert(window); - window->AddObserver(this); -} - -void WindowReorderer::AssociationObserver::StopObserving( - aura::Window* window) { - windows_.erase(window); - window->RemoveObserver(this); -} - -void WindowReorderer::AssociationObserver::OnWindowPropertyChanged( - aura::Window* window, - const void* key, - intptr_t old) { - if (key == kHostViewKey) - reorderer_->ReorderChildWindows(); -} - -void WindowReorderer::AssociationObserver::OnWindowDestroying( - aura::Window* window) { - windows_.erase(window); - window->RemoveObserver(this); -} - -WindowReorderer::WindowReorderer(aura::Window* parent_window, - View* root_view) - : parent_window_(parent_window), - root_view_(root_view), - association_observer_(new AssociationObserver(this)) { - parent_window_->AddObserver(this); - const std::vector<aura::Window*>& windows = parent_window_->children(); - for (size_t i = 0; i < windows.size(); ++i) - association_observer_->StartObserving(windows[i]); - ReorderChildWindows(); -} - -WindowReorderer::~WindowReorderer() { - if (parent_window_) { - parent_window_->RemoveObserver(this); - // |association_observer_| stops observing any windows it is observing upon - // destruction. - } -} - -void WindowReorderer::ReorderChildWindows() { - if (!parent_window_) - return; - - std::map<View*, aura::Window*> hosted_windows; - GetViewsWithAssociatedWindow(*parent_window_, &hosted_windows); - - if (hosted_windows.empty()) { - // Exit early if there are no views with associated windows. - // View::ReorderLayers() should have already reordered the layers owned by - // views. - return; - } - - // Compute the desired z-order of the layers based on the order of the views - // with layers and views with associated windows in the view tree. - std::vector<View*> view_with_layer_order; - GetOrderOfViewsWithLayers(root_view_, parent_window_->layer(), hosted_windows, - &view_with_layer_order); - - // For the sake of simplicity, reorder both the layers owned by views and the - // layers of windows associated with a view. Iterate through - // |view_with_layer_order| backwards and stack windows at the bottom so that - // windows not associated to a view are stacked above windows with an - // associated view. - for (std::vector<View*>::reverse_iterator it = view_with_layer_order.rbegin(); - it != view_with_layer_order.rend(); ++it) { - View* view = *it; - ui::Layer* layer = view->layer(); - aura::Window* window = NULL; - - std::map<View*, aura::Window*>::iterator hosted_window_it = - hosted_windows.find(view); - if (hosted_window_it != hosted_windows.end()) { - window = hosted_window_it->second; - layer = window->layer(); - } - - DCHECK(layer); - if (window) - parent_window_->StackChildAtBottom(window); - parent_window_->layer()->StackAtBottom(layer); - } -} - -void WindowReorderer::OnWindowAdded(aura::Window* new_window) { - association_observer_->StartObserving(new_window); - ReorderChildWindows(); -} - -void WindowReorderer::OnWillRemoveWindow(aura::Window* window) { - association_observer_->StopObserving(window); -} - -void WindowReorderer::OnWindowDestroying(aura::Window* window) { - parent_window_->RemoveObserver(this); - parent_window_ = NULL; - association_observer_.reset(); -} - -} // namespace views
diff --git a/ui/views/widget/window_reorderer.h b/ui/views/widget/window_reorderer.h deleted file mode 100644 index 5091cf4..0000000 --- a/ui/views/widget/window_reorderer.h +++ /dev/null
@@ -1,59 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_WIDGET_WINDOW_REORDERER_H_ -#define UI_VIEWS_WIDGET_WINDOW_REORDERER_H_ - -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "ui/aura/window_observer.h" - -namespace aura { -class Window; -} - -namespace views { -class View; - -// Class which reorders the widget's child windows which have an associated view -// in the widget's view tree according the z-order of the views in the view -// tree. Windows not associated to a view are stacked above windows with an -// associated view. The child windows' layers are additionally reordered -// according to the z-order of the associated views relative to views with -// layers. -class WindowReorderer : public aura::WindowObserver { - public: - WindowReorderer(aura::Window* window, View* root_view); - virtual ~WindowReorderer(); - - // Explicitly reorder the children of |window_| (and their layers). This - // method should be called when the position of a view with an associated - // window changes in the view hierarchy. This method assumes that the - // child layers of |window_| which are owned by views are already in the - // correct z-order relative to each other and does no reordering if there - // are no views with an associated window. - void ReorderChildWindows(); - - private: - // aura::WindowObserver overrides: - virtual void OnWindowAdded(aura::Window* new_window) override; - virtual void OnWillRemoveWindow(aura::Window* window) override; - virtual void OnWindowDestroying(aura::Window* window) override; - - // The window and the root view of the native widget which owns the - // WindowReorderer. - aura::Window* parent_window_; - View* root_view_; - - // Reorders windows as a result of the kHostViewKey being set on a child of - // |parent_window_|. - class AssociationObserver; - scoped_ptr<AssociationObserver> association_observer_; - - DISALLOW_COPY_AND_ASSIGN(WindowReorderer); -}; - -} // namespace views - -#endif // UI_VIEWS_WIDGET_WINDOW_REORDERER_H_
diff --git a/ui/views/widget/window_reorderer_unittest.cc b/ui/views/widget/window_reorderer_unittest.cc deleted file mode 100644 index 67cf246..0000000 --- a/ui/views/widget/window_reorderer_unittest.cc +++ /dev/null
@@ -1,263 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/aura/test/aura_test_base.h" -#include "ui/aura/test/test_windows.h" -#include "ui/aura/window.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/compositor/layer.h" -#include "ui/compositor/test/test_layers.h" -#include "ui/views/view.h" -#include "ui/views/view_constants_aura.h" -#include "ui/views/widget/widget.h" - -namespace views { -namespace { - -// Creates a control widget with the passed in parameters. -// The caller takes ownership of the returned widget. -Widget* CreateControlWidget(aura::Window* parent, const gfx::Rect& bounds) { - Widget::InitParams params(Widget::InitParams::TYPE_CONTROL); - params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - params.parent = parent; - params.bounds = bounds; - Widget* widget = new Widget(); - widget->Init(params); - return widget; -} - -// Sets the name of |window| and |window|'s layer to |name|. -void SetWindowAndLayerName(aura::Window* window, const std::string& name) { - window->SetName(name); - window->layer()->set_name(name); -} - -// Returns a string containing the name of each of the child windows (bottommost -// first) of |parent|. The format of the string is "name1 name2 name3 ...". -std::string ChildWindowNamesAsString(const aura::Window& parent) { - std::string names; - typedef std::vector<aura::Window*> Windows; - for (Windows::const_iterator it = parent.children().begin(); - it != parent.children().end(); ++it) { - if (!names.empty()) - names += " "; - names += (*it)->name(); - } - return names; -} - -typedef aura::test::AuraTestBase WindowReordererTest; - -// Test that views with layers and views with associated windows are reordered -// according to the view hierarchy. -TEST_F(WindowReordererTest, Basic) { - scoped_ptr<Widget> parent(CreateControlWidget(root_window(), - gfx::Rect(0, 0, 100, 100))); - parent->Show(); - aura::Window* parent_window = parent->GetNativeWindow(); - - View* contents_view = new View(); - parent->SetContentsView(contents_view); - - // 1) Test that layers for views and layers for windows associated to a host - // view are stacked below the layers for any windows not associated to a host - // view. - View* v = new View(); - v->SetPaintToLayer(true); - v->layer()->set_name("v"); - contents_view->AddChildView(v); - - scoped_ptr<Widget> w1(CreateControlWidget(parent_window, - gfx::Rect(0, 1, 100, 101))); - SetWindowAndLayerName(w1->GetNativeView(), "w1"); - w1->Show(); - scoped_ptr<Widget> w2(CreateControlWidget(parent_window, - gfx::Rect(0, 2, 100, 102))); - SetWindowAndLayerName(w2->GetNativeView(), "w2"); - w2->Show(); - - EXPECT_EQ("w1 w2", ChildWindowNamesAsString(*parent_window)); - EXPECT_EQ("v w1 w2", - ui::test::ChildLayerNamesAsString(*parent_window->layer())); - - View* host_view2 = new View(); - contents_view->AddChildView(host_view2); - w2->GetNativeView()->SetProperty(kHostViewKey, host_view2); - EXPECT_EQ("w2 w1", ChildWindowNamesAsString(*parent_window)); - EXPECT_EQ("v w2 w1", - ui::test::ChildLayerNamesAsString(*parent_window->layer())); - - View* host_view1 = new View(); - w1->GetNativeView()->SetProperty(kHostViewKey, host_view1); - contents_view->AddChildViewAt(host_view1, 0); - EXPECT_EQ("w1 w2", ChildWindowNamesAsString(*parent_window)); - EXPECT_EQ("w1 v w2", - ui::test::ChildLayerNamesAsString(*parent_window->layer())); - - // 2) Test the z-order of the windows and layers as a result of reordering the - // views. - contents_view->ReorderChildView(host_view1, -1); - EXPECT_EQ("w2 w1", ChildWindowNamesAsString(*parent_window)); - EXPECT_EQ("v w2 w1", - ui::test::ChildLayerNamesAsString(*parent_window->layer())); - - contents_view->ReorderChildView(host_view2, -1); - EXPECT_EQ("w1 w2", ChildWindowNamesAsString(*parent_window)); - EXPECT_EQ("v w1 w2", - ui::test::ChildLayerNamesAsString(*parent_window->layer())); - - // 3) Test the z-order of the windows and layers as a result of reordering the - // views in situations where the window order remains unchanged. - contents_view->ReorderChildView(v, -1); - EXPECT_EQ("w1 w2", ChildWindowNamesAsString(*parent_window)); - EXPECT_EQ("w1 w2 v", - ui::test::ChildLayerNamesAsString(*parent_window->layer())); - - contents_view->ReorderChildView(host_view2, -1); - EXPECT_EQ("w1 w2", ChildWindowNamesAsString(*parent_window)); - EXPECT_EQ("w1 v w2", - ui::test::ChildLayerNamesAsString(*parent_window->layer())); - - // Work around for bug in NativeWidgetAura. - // TODO: fix bug and remove this. - parent->Close(); -} - -// Test that different orderings of: -// - adding a window to a parent widget -// - adding a "host" view to a parent widget -// - associating the "host" view and window -// all correctly reorder the child windows and layers. -TEST_F(WindowReordererTest, Association) { - scoped_ptr<Widget> parent(CreateControlWidget(root_window(), - gfx::Rect(0, 0, 100, 100))); - parent->Show(); - aura::Window* parent_window = parent->GetNativeWindow(); - - View* contents_view = new View(); - parent->SetContentsView(contents_view); - - aura::Window* w1 = aura::test::CreateTestWindowWithId(0, - parent->GetNativeWindow()); - SetWindowAndLayerName(w1, "w1"); - - aura::Window* w2 = aura::test::CreateTestWindowWithId(0, NULL); - SetWindowAndLayerName(w2, "w2"); - - View* host_view2 = new View(); - - // 1) Test that parenting the window to the parent widget last results in a - // correct ordering of child windows and layers. - contents_view->AddChildView(host_view2); - w2->SetProperty(views::kHostViewKey, host_view2); - EXPECT_EQ("w1", ChildWindowNamesAsString(*parent_window)); - EXPECT_EQ("w1", - ui::test::ChildLayerNamesAsString(*parent_window->layer())); - - parent_window->AddChild(w2); - EXPECT_EQ("w2 w1", ChildWindowNamesAsString(*parent_window)); - EXPECT_EQ("w2 w1", - ui::test::ChildLayerNamesAsString(*parent_window->layer())); - - // 2) Test that associating the window and "host" view last results in a - // correct ordering of child windows and layers. - View* host_view1 = new View(); - contents_view->AddChildViewAt(host_view1, 0); - EXPECT_EQ("w2 w1", ChildWindowNamesAsString(*parent_window)); - EXPECT_EQ("w2 w1", - ui::test::ChildLayerNamesAsString(*parent_window->layer())); - - w1->SetProperty(views::kHostViewKey, host_view1); - EXPECT_EQ("w1 w2", ChildWindowNamesAsString(*parent_window)); - EXPECT_EQ("w1 w2", - ui::test::ChildLayerNamesAsString(*parent_window->layer())); - - // 3) Test that parenting the "host" view to the parent widget last results - // in a correct ordering of child windows and layers. - contents_view->RemoveChildView(host_view2); - contents_view->AddChildViewAt(host_view2, 0); - EXPECT_EQ("w2 w1", ChildWindowNamesAsString(*parent_window)); - EXPECT_EQ("w2 w1", - ui::test::ChildLayerNamesAsString(*parent_window->layer())); - - // Work around for bug in NativeWidgetAura. - // TODO: fix bug and remove this. - parent->Close(); -} - -// It is possible to associate a window to a view which has a parent layer -// (other than the widget layer). In this case, the parent layer of the host -// view and the parent layer of the associated window are different. Test that -// the layers and windows are properly reordered in this case. -TEST_F(WindowReordererTest, HostViewParentHasLayer) { - scoped_ptr<Widget> parent(CreateControlWidget(root_window(), - gfx::Rect(0, 0, 100, 100))); - parent->Show(); - aura::Window* parent_window = parent->GetNativeWindow(); - - View* contents_view = new View(); - parent->SetContentsView(contents_view); - - // Create the following view hierarchy. (*) denotes views which paint to a - // layer. - // - // contents_view - // +-- v1 - // +-- v11* - // +-- v12 (attached window) - // +-- v13* - // +--v2* - - View* v1 = new View(); - contents_view->AddChildView(v1); - - View* v11 = new View(); - v11->SetPaintToLayer(true); - v11->layer()->set_name("v11"); - v1->AddChildView(v11); - - scoped_ptr<Widget> w(CreateControlWidget(parent_window, - gfx::Rect(0, 1, 100, 101))); - SetWindowAndLayerName(w->GetNativeView(), "w"); - w->Show(); - - View* v12 = new View(); - v1->AddChildView(v12); - w->GetNativeView()->SetProperty(kHostViewKey, v12); - - View* v13 = new View(); - v13->SetPaintToLayer(true); - v13->layer()->set_name("v13"); - v1->AddChildView(v13); - - View* v2 = new View(); - v2->SetPaintToLayer(true); - v2->layer()->set_name("v2"); - contents_view->AddChildView(v2); - - // Test intial state. - EXPECT_EQ("w", ChildWindowNamesAsString(*parent_window)); - EXPECT_EQ("v11 w v13 v2", - ui::test::ChildLayerNamesAsString(*parent_window->layer())); - - // |w|'s layer should be stacked above |v1|'s layer. - v1->SetPaintToLayer(true); - v1->layer()->set_name("v1"); - EXPECT_EQ("w", ChildWindowNamesAsString(*parent_window)); - EXPECT_EQ("v1 w v2", - ui::test::ChildLayerNamesAsString(*parent_window->layer())); - - // Test moving the host view from one view with a layer to another. - v2->AddChildView(v12); - EXPECT_EQ("w", ChildWindowNamesAsString(*parent_window)); - EXPECT_EQ("v1 v2 w", - ui::test::ChildLayerNamesAsString(*parent_window->layer())); - - // Work around for bug in NativeWidgetAura. - // TODO: fix bug and remove this. - parent->Close(); -} - -} // namespace -} // namespace views
diff --git a/ui/views/win/DEPS b/ui/views/win/DEPS deleted file mode 100644 index 8cab170..0000000 --- a/ui/views/win/DEPS +++ /dev/null
@@ -1,25 +0,0 @@ -# hwnd_util is allowed to include ui/views because it has separate -# implementations for win and aura. -specific_include_rules = { - "hwnd_util.*": [ - "+ui/views", - ], -} - -# The rest of the code here is intended to be distinct from the rest of -# views and not depend on the details of the win and aura implementations. -# Use HWNDMessageHandlerDelegate instead of #including views types. -include_rules = [ - "-ui/views", - - "+base", - "+ui/base", - "+ui/gfx", - "+ui/views/accessibility/native_view_accessibility_win.h", - "+ui/views/ime/input_method_delegate.h", - "+ui/views/views_delegate.h", - "+ui/views/views_export.h", - "+ui/views/widget/monitor_win.h", - "+ui/views/widget/widget_hwnd_utils.h", - "+ui/views/win", -]
diff --git a/ui/views/win/fullscreen_handler.cc b/ui/views/win/fullscreen_handler.cc deleted file mode 100644 index a6f5156..0000000 --- a/ui/views/win/fullscreen_handler.cc +++ /dev/null
@@ -1,105 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/win/fullscreen_handler.h" - -#include "base/logging.h" -#include "base/win/win_util.h" -#include "ui/gfx/rect.h" -#include "ui/views/win/scoped_fullscreen_visibility.h" - -namespace views { - -//////////////////////////////////////////////////////////////////////////////// -// FullscreenHandler, public: - -FullscreenHandler::FullscreenHandler() - : hwnd_(NULL), - fullscreen_(false), - metro_snap_(false) { -} - -FullscreenHandler::~FullscreenHandler() { -} - -void FullscreenHandler::SetFullscreen(bool fullscreen) { - if (fullscreen_ == fullscreen) - return; - - SetFullscreenImpl(fullscreen, false); -} - -void FullscreenHandler::SetMetroSnap(bool metro_snap) { - if (metro_snap_ == metro_snap) - return; - - SetFullscreenImpl(metro_snap, true); - metro_snap_ = metro_snap; -} - -gfx::Rect FullscreenHandler::GetRestoreBounds() const { - return gfx::Rect(saved_window_info_.window_rect); -} - -//////////////////////////////////////////////////////////////////////////////// -// FullscreenHandler, private: - -void FullscreenHandler::SetFullscreenImpl(bool fullscreen, bool for_metro) { - ScopedFullscreenVisibility visibility(hwnd_); - - // Save current window state if not already fullscreen. - if (!fullscreen_) { - // Save current window information. We force the window into restored mode - // before going fullscreen because Windows doesn't seem to hide the - // taskbar if the window is in the maximized state. - saved_window_info_.maximized = !!::IsZoomed(hwnd_); - if (saved_window_info_.maximized) - ::SendMessage(hwnd_, WM_SYSCOMMAND, SC_RESTORE, 0); - saved_window_info_.style = GetWindowLong(hwnd_, GWL_STYLE); - saved_window_info_.ex_style = GetWindowLong(hwnd_, GWL_EXSTYLE); - GetWindowRect(hwnd_, &saved_window_info_.window_rect); - } - - fullscreen_ = fullscreen; - - if (fullscreen_) { - // Set new window style and size. - SetWindowLong(hwnd_, GWL_STYLE, - saved_window_info_.style & ~(WS_CAPTION | WS_THICKFRAME)); - SetWindowLong(hwnd_, GWL_EXSTYLE, - saved_window_info_.ex_style & ~(WS_EX_DLGMODALFRAME | - WS_EX_WINDOWEDGE | WS_EX_CLIENTEDGE | WS_EX_STATICEDGE)); - - // On expand, if we're given a window_rect, grow to it, otherwise do - // not resize. - if (!for_metro) { - MONITORINFO monitor_info; - monitor_info.cbSize = sizeof(monitor_info); - GetMonitorInfo(MonitorFromWindow(hwnd_, MONITOR_DEFAULTTONEAREST), - &monitor_info); - gfx::Rect window_rect(monitor_info.rcMonitor); - SetWindowPos(hwnd_, NULL, window_rect.x(), window_rect.y(), - window_rect.width(), window_rect.height(), - SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED); - } - } else { - // Reset original window style and size. The multiple window size/moves - // here are ugly, but if SetWindowPos() doesn't redraw, the taskbar won't be - // repainted. Better-looking methods welcome. - SetWindowLong(hwnd_, GWL_STYLE, saved_window_info_.style); - SetWindowLong(hwnd_, GWL_EXSTYLE, saved_window_info_.ex_style); - - if (!for_metro) { - // On restore, resize to the previous saved rect size. - gfx::Rect new_rect(saved_window_info_.window_rect); - SetWindowPos(hwnd_, NULL, new_rect.x(), new_rect.y(), - new_rect.width(), new_rect.height(), - SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED); - } - if (saved_window_info_.maximized) - ::SendMessage(hwnd_, WM_SYSCOMMAND, SC_MAXIMIZE, 0); - } -} - -} // namespace views
diff --git a/ui/views/win/fullscreen_handler.h b/ui/views/win/fullscreen_handler.h deleted file mode 100644 index 4a620d5..0000000 --- a/ui/views/win/fullscreen_handler.h +++ /dev/null
@@ -1,60 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_WIN_FULLSCREEN_HANDLER_H_ -#define UI_VIEWS_WIN_FULLSCREEN_HANDLER_H_ - -#include <windows.h> - -#include <map> - -#include "base/basictypes.h" - -namespace gfx { -class Rect; -} - -namespace views { - -class FullscreenHandler { - public: - FullscreenHandler(); - ~FullscreenHandler(); - - void set_hwnd(HWND hwnd) { hwnd_ = hwnd; } - - void SetFullscreen(bool fullscreen); - void SetMetroSnap(bool metro_snap); - - gfx::Rect GetRestoreBounds() const; - - bool fullscreen() const { return fullscreen_; } - bool metro_snap() const { return metro_snap_; } - - private: - // Information saved before going into fullscreen mode, used to restore the - // window afterwards. - struct SavedWindowInfo { - bool maximized; - LONG style; - LONG ex_style; - RECT window_rect; - }; - - void SetFullscreenImpl(bool fullscreen, bool for_metro); - - HWND hwnd_; - bool fullscreen_; - bool metro_snap_; - - // Saved window information from before entering fullscreen mode. - // TODO(beng): move to private once GetRestoredBounds() moves onto Widget. - SavedWindowInfo saved_window_info_; - - DISALLOW_COPY_AND_ASSIGN(FullscreenHandler); -}; - -} // namespace views - -#endif // UI_VIEWS_WIN_FULLSCREEN_HANDLER_H_ \ No newline at end of file
diff --git a/ui/views/win/hwnd_message_handler.cc b/ui/views/win/hwnd_message_handler.cc deleted file mode 100644 index fca579d..0000000 --- a/ui/views/win/hwnd_message_handler.cc +++ /dev/null
@@ -1,2502 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/win/hwnd_message_handler.h" - -#include <dwmapi.h> -#include <oleacc.h> -#include <shellapi.h> -#include <wtsapi32.h> -#pragma comment(lib, "wtsapi32.lib") - -#include "base/bind.h" -#include "base/debug/trace_event.h" -#include "base/win/win_util.h" -#include "base/win/windows_version.h" -#include "ui/base/touch/touch_enabled.h" -#include "ui/base/view_prop.h" -#include "ui/base/win/internal_constants.h" -#include "ui/base/win/lock_state.h" -#include "ui/base/win/mouse_wheel_util.h" -#include "ui/base/win/shell.h" -#include "ui/base/win/touch_input.h" -#include "ui/events/event.h" -#include "ui/events/event_utils.h" -#include "ui/events/keycodes/keyboard_code_conversion_win.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/canvas_skia_paint.h" -#include "ui/gfx/icon_util.h" -#include "ui/gfx/insets.h" -#include "ui/gfx/path.h" -#include "ui/gfx/path_win.h" -#include "ui/gfx/screen.h" -#include "ui/gfx/win/dpi.h" -#include "ui/gfx/win/hwnd_util.h" -#include "ui/native_theme/native_theme_win.h" -#include "ui/views/views_delegate.h" -#include "ui/views/widget/monitor_win.h" -#include "ui/views/widget/widget_hwnd_utils.h" -#include "ui/views/win/fullscreen_handler.h" -#include "ui/views/win/hwnd_message_handler_delegate.h" -#include "ui/views/win/scoped_fullscreen_visibility.h" - -namespace views { -namespace { - -// MoveLoopMouseWatcher is used to determine if the user canceled or completed a -// move. win32 doesn't appear to offer a way to determine the result of a move, -// so we install hooks to determine if we got a mouse up and assume the move -// completed. -class MoveLoopMouseWatcher { - public: - MoveLoopMouseWatcher(HWNDMessageHandler* host, bool hide_on_escape); - ~MoveLoopMouseWatcher(); - - // Returns true if the mouse is up, or if we couldn't install the hook. - bool got_mouse_up() const { return got_mouse_up_; } - - private: - // Instance that owns the hook. We only allow one instance to hook the mouse - // at a time. - static MoveLoopMouseWatcher* instance_; - - // Key and mouse callbacks from the hook. - static LRESULT CALLBACK MouseHook(int n_code, WPARAM w_param, LPARAM l_param); - static LRESULT CALLBACK KeyHook(int n_code, WPARAM w_param, LPARAM l_param); - - void Unhook(); - - // HWNDMessageHandler that created us. - HWNDMessageHandler* host_; - - // Should the window be hidden when escape is pressed? - const bool hide_on_escape_; - - // Did we get a mouse up? - bool got_mouse_up_; - - // Hook identifiers. - HHOOK mouse_hook_; - HHOOK key_hook_; - - DISALLOW_COPY_AND_ASSIGN(MoveLoopMouseWatcher); -}; - -// static -MoveLoopMouseWatcher* MoveLoopMouseWatcher::instance_ = NULL; - -MoveLoopMouseWatcher::MoveLoopMouseWatcher(HWNDMessageHandler* host, - bool hide_on_escape) - : host_(host), - hide_on_escape_(hide_on_escape), - got_mouse_up_(false), - mouse_hook_(NULL), - key_hook_(NULL) { - // Only one instance can be active at a time. - if (instance_) - instance_->Unhook(); - - mouse_hook_ = SetWindowsHookEx( - WH_MOUSE, &MouseHook, NULL, GetCurrentThreadId()); - if (mouse_hook_) { - instance_ = this; - // We don't care if setting the key hook succeeded. - key_hook_ = SetWindowsHookEx( - WH_KEYBOARD, &KeyHook, NULL, GetCurrentThreadId()); - } - if (instance_ != this) { - // Failed installation. Assume we got a mouse up in this case, otherwise - // we'll think all drags were canceled. - got_mouse_up_ = true; - } -} - -MoveLoopMouseWatcher::~MoveLoopMouseWatcher() { - Unhook(); -} - -void MoveLoopMouseWatcher::Unhook() { - if (instance_ != this) - return; - - DCHECK(mouse_hook_); - UnhookWindowsHookEx(mouse_hook_); - if (key_hook_) - UnhookWindowsHookEx(key_hook_); - key_hook_ = NULL; - mouse_hook_ = NULL; - instance_ = NULL; -} - -// static -LRESULT CALLBACK MoveLoopMouseWatcher::MouseHook(int n_code, - WPARAM w_param, - LPARAM l_param) { - DCHECK(instance_); - if (n_code == HC_ACTION && w_param == WM_LBUTTONUP) - instance_->got_mouse_up_ = true; - return CallNextHookEx(instance_->mouse_hook_, n_code, w_param, l_param); -} - -// static -LRESULT CALLBACK MoveLoopMouseWatcher::KeyHook(int n_code, - WPARAM w_param, - LPARAM l_param) { - if (n_code == HC_ACTION && w_param == VK_ESCAPE) { - if (base::win::GetVersion() >= base::win::VERSION_VISTA) { - int value = TRUE; - DwmSetWindowAttribute( - instance_->host_->hwnd(), - DWMWA_TRANSITIONS_FORCEDISABLED, - &value, - sizeof(value)); - } - if (instance_->hide_on_escape_) - instance_->host_->Hide(); - } - return CallNextHookEx(instance_->key_hook_, n_code, w_param, l_param); -} - -// Called from OnNCActivate. -BOOL CALLBACK EnumChildWindowsForRedraw(HWND hwnd, LPARAM lparam) { - DWORD process_id; - GetWindowThreadProcessId(hwnd, &process_id); - int flags = RDW_INVALIDATE | RDW_NOCHILDREN | RDW_FRAME; - if (process_id == GetCurrentProcessId()) - flags |= RDW_UPDATENOW; - RedrawWindow(hwnd, NULL, NULL, flags); - return TRUE; -} - -bool GetMonitorAndRects(const RECT& rect, - HMONITOR* monitor, - gfx::Rect* monitor_rect, - gfx::Rect* work_area) { - DCHECK(monitor); - DCHECK(monitor_rect); - DCHECK(work_area); - *monitor = MonitorFromRect(&rect, MONITOR_DEFAULTTONULL); - if (!*monitor) - return false; - MONITORINFO monitor_info = { 0 }; - monitor_info.cbSize = sizeof(monitor_info); - GetMonitorInfo(*monitor, &monitor_info); - *monitor_rect = gfx::Rect(monitor_info.rcMonitor); - *work_area = gfx::Rect(monitor_info.rcWork); - return true; -} - -struct FindOwnedWindowsData { - HWND window; - std::vector<Widget*> owned_widgets; -}; - -// Enables or disables the menu item for the specified command and menu. -void EnableMenuItemByCommand(HMENU menu, UINT command, bool enabled) { - UINT flags = MF_BYCOMMAND | (enabled ? MF_ENABLED : MF_DISABLED | MF_GRAYED); - EnableMenuItem(menu, command, flags); -} - -// Callback used to notify child windows that the top level window received a -// DWMCompositionChanged message. -BOOL CALLBACK SendDwmCompositionChanged(HWND window, LPARAM param) { - SendMessage(window, WM_DWMCOMPOSITIONCHANGED, 0, 0); - return TRUE; -} - -// See comments in OnNCPaint() for details of this struct. -struct ClipState { - // The window being painted. - HWND parent; - - // DC painting to. - HDC dc; - - // Origin of the window in terms of the screen. - int x; - int y; -}; - -// See comments in OnNCPaint() for details of this function. -static BOOL CALLBACK ClipDCToChild(HWND window, LPARAM param) { - ClipState* clip_state = reinterpret_cast<ClipState*>(param); - if (GetParent(window) == clip_state->parent && IsWindowVisible(window)) { - RECT bounds; - GetWindowRect(window, &bounds); - ExcludeClipRect(clip_state->dc, - bounds.left - clip_state->x, - bounds.top - clip_state->y, - bounds.right - clip_state->x, - bounds.bottom - clip_state->y); - } - return TRUE; -} - -// The thickness of an auto-hide taskbar in pixels. -const int kAutoHideTaskbarThicknessPx = 2; - -bool IsTopLevelWindow(HWND window) { - long style = ::GetWindowLong(window, GWL_STYLE); - if (!(style & WS_CHILD)) - return true; - HWND parent = ::GetParent(window); - return !parent || (parent == ::GetDesktopWindow()); -} - -void AddScrollStylesToWindow(HWND window) { - if (::IsWindow(window)) { - long current_style = ::GetWindowLong(window, GWL_STYLE); - ::SetWindowLong(window, GWL_STYLE, - current_style | WS_VSCROLL | WS_HSCROLL); - } -} - -const int kTouchDownContextResetTimeout = 500; - -// Windows does not flag synthesized mouse messages from touch in all cases. -// This causes us grief as we don't want to process touch and mouse messages -// concurrently. Hack as per msdn is to check if the time difference between -// the touch message and the mouse move is within 500 ms and at the same -// location as the cursor. -const int kSynthesizedMouseTouchMessagesTimeDifference = 500; - -} // namespace - -// A scoping class that prevents a window from being able to redraw in response -// to invalidations that may occur within it for the lifetime of the object. -// -// Why would we want such a thing? Well, it turns out Windows has some -// "unorthodox" behavior when it comes to painting its non-client areas. -// Occasionally, Windows will paint portions of the default non-client area -// right over the top of the custom frame. This is not simply fixed by handling -// WM_NCPAINT/WM_PAINT, with some investigation it turns out that this -// rendering is being done *inside* the default implementation of some message -// handlers and functions: -// . WM_SETTEXT -// . WM_SETICON -// . WM_NCLBUTTONDOWN -// . EnableMenuItem, called from our WM_INITMENU handler -// The solution is to handle these messages and call DefWindowProc ourselves, -// but prevent the window from being able to update itself for the duration of -// the call. We do this with this class, which automatically calls its -// associated Window's lock and unlock functions as it is created and destroyed. -// See documentation in those methods for the technique used. -// -// The lock only has an effect if the window was visible upon lock creation, as -// it doesn't guard against direct visiblility changes, and multiple locks may -// exist simultaneously to handle certain nested Windows messages. -// -// IMPORTANT: Do not use this scoping object for large scopes or periods of -// time! IT WILL PREVENT THE WINDOW FROM BEING REDRAWN! (duh). -// -// I would love to hear Raymond Chen's explanation for all this. And maybe a -// list of other messages that this applies to ;-) -class HWNDMessageHandler::ScopedRedrawLock { - public: - explicit ScopedRedrawLock(HWNDMessageHandler* owner) - : owner_(owner), - hwnd_(owner_->hwnd()), - was_visible_(owner_->IsVisible()), - cancel_unlock_(false), - force_(!(GetWindowLong(hwnd_, GWL_STYLE) & WS_CAPTION)) { - if (was_visible_ && ::IsWindow(hwnd_)) - owner_->LockUpdates(force_); - } - - ~ScopedRedrawLock() { - if (!cancel_unlock_ && was_visible_ && ::IsWindow(hwnd_)) - owner_->UnlockUpdates(force_); - } - - // Cancel the unlock operation, call this if the Widget is being destroyed. - void CancelUnlockOperation() { cancel_unlock_ = true; } - - private: - // The owner having its style changed. - HWNDMessageHandler* owner_; - // The owner's HWND, cached to avoid action after window destruction. - HWND hwnd_; - // Records the HWND visibility at the time of creation. - bool was_visible_; - // A flag indicating that the unlock operation was canceled. - bool cancel_unlock_; - // If true, perform the redraw lock regardless of Aero state. - bool force_; - - DISALLOW_COPY_AND_ASSIGN(ScopedRedrawLock); -}; - -//////////////////////////////////////////////////////////////////////////////// -// HWNDMessageHandler, public: - -long HWNDMessageHandler::last_touch_message_time_ = 0; - -HWNDMessageHandler::HWNDMessageHandler(HWNDMessageHandlerDelegate* delegate) - : delegate_(delegate), - fullscreen_handler_(new FullscreenHandler), - weak_factory_(this), - waiting_for_close_now_(false), - remove_standard_frame_(false), - use_system_default_icon_(false), - restored_enabled_(false), - current_cursor_(NULL), - previous_cursor_(NULL), - active_mouse_tracking_flags_(0), - is_right_mouse_pressed_on_caption_(false), - lock_updates_count_(0), - ignore_window_pos_changes_(false), - last_monitor_(NULL), - use_layered_buffer_(false), - layered_alpha_(255), - waiting_for_redraw_layered_window_contents_(false), - is_first_nccalc_(true), - menu_depth_(0), - autohide_factory_(this), - id_generator_(0), - needs_scroll_styles_(false), - in_size_loop_(false), - touch_down_contexts_(0), - last_mouse_hwheel_time_(0), - msg_handled_(FALSE), - dwm_transition_desired_(false) { -} - -HWNDMessageHandler::~HWNDMessageHandler() { - delegate_ = NULL; - // Prevent calls back into this class via WNDPROC now that we've been - // destroyed. - ClearUserData(); -} - -void HWNDMessageHandler::Init(HWND parent, const gfx::Rect& bounds) { - TRACE_EVENT0("views", "HWNDMessageHandler::Init"); - GetMonitorAndRects(bounds.ToRECT(), &last_monitor_, &last_monitor_rect_, - &last_work_area_); - - // Create the window. - WindowImpl::Init(parent, bounds); - // TODO(ananta) - // Remove the scrolling hack code once we have scrolling working well. -#if defined(ENABLE_SCROLL_HACK) - // Certain trackpad drivers on Windows have bugs where in they don't generate - // WM_MOUSEWHEEL messages for the trackpoint and trackpad scrolling gestures - // unless there is an entry for Chrome with the class name of the Window. - // These drivers check if the window under the trackpoint has the WS_VSCROLL/ - // WS_HSCROLL style and if yes they generate the legacy WM_VSCROLL/WM_HSCROLL - // messages. We add these styles to ensure that trackpad/trackpoint scrolling - // work. - // TODO(ananta) - // Look into moving the WS_VSCROLL and WS_HSCROLL style setting logic to the - // CalculateWindowStylesFromInitParams function. Doing it there seems to - // cause some interactive tests to fail. Investigation needed. - if (IsTopLevelWindow(hwnd())) { - long current_style = ::GetWindowLong(hwnd(), GWL_STYLE); - if (!(current_style & WS_POPUP)) { - AddScrollStylesToWindow(hwnd()); - needs_scroll_styles_ = true; - } - } -#endif - - prop_window_target_.reset(new ui::ViewProp(hwnd(), - ui::WindowEventTarget::kWin32InputEventTarget, - static_cast<ui::WindowEventTarget*>(this))); -} - -void HWNDMessageHandler::InitModalType(ui::ModalType modal_type) { - if (modal_type == ui::MODAL_TYPE_NONE) - return; - // We implement modality by crawling up the hierarchy of windows starting - // at the owner, disabling all of them so that they don't receive input - // messages. - HWND start = ::GetWindow(hwnd(), GW_OWNER); - while (start) { - ::EnableWindow(start, FALSE); - start = ::GetParent(start); - } -} - -void HWNDMessageHandler::Close() { - if (!IsWindow(hwnd())) - return; // No need to do anything. - - // Let's hide ourselves right away. - Hide(); - - // Modal dialog windows disable their owner windows; re-enable them now so - // they can activate as foreground windows upon this window's destruction. - RestoreEnabledIfNecessary(); - - if (!waiting_for_close_now_) { - // And we delay the close so that if we are called from an ATL callback, - // we don't destroy the window before the callback returned (as the caller - // may delete ourselves on destroy and the ATL callback would still - // dereference us when the callback returns). - waiting_for_close_now_ = true; - base::MessageLoop::current()->PostTask( - FROM_HERE, - base::Bind(&HWNDMessageHandler::CloseNow, weak_factory_.GetWeakPtr())); - } -} - -void HWNDMessageHandler::CloseNow() { - // We may already have been destroyed if the selection resulted in a tab - // switch which will have reactivated the browser window and closed us, so - // we need to check to see if we're still a window before trying to destroy - // ourself. - waiting_for_close_now_ = false; - if (IsWindow(hwnd())) - DestroyWindow(hwnd()); -} - -gfx::Rect HWNDMessageHandler::GetWindowBoundsInScreen() const { - RECT r; - GetWindowRect(hwnd(), &r); - return gfx::Rect(r); -} - -gfx::Rect HWNDMessageHandler::GetClientAreaBoundsInScreen() const { - RECT r; - GetClientRect(hwnd(), &r); - POINT point = { r.left, r.top }; - ClientToScreen(hwnd(), &point); - return gfx::Rect(point.x, point.y, r.right - r.left, r.bottom - r.top); -} - -gfx::Rect HWNDMessageHandler::GetRestoredBounds() const { - // If we're in fullscreen mode, we've changed the normal bounds to the monitor - // rect, so return the saved bounds instead. - if (fullscreen_handler_->fullscreen()) - return fullscreen_handler_->GetRestoreBounds(); - - gfx::Rect bounds; - GetWindowPlacement(&bounds, NULL); - return bounds; -} - -gfx::Rect HWNDMessageHandler::GetClientAreaBounds() const { - if (IsMinimized()) - return gfx::Rect(); - if (delegate_->WidgetSizeIsClientSize()) - return GetClientAreaBoundsInScreen(); - return GetWindowBoundsInScreen(); -} - -void HWNDMessageHandler::GetWindowPlacement( - gfx::Rect* bounds, - ui::WindowShowState* show_state) const { - WINDOWPLACEMENT wp; - wp.length = sizeof(wp); - const bool succeeded = !!::GetWindowPlacement(hwnd(), &wp); - DCHECK(succeeded); - - if (bounds != NULL) { - if (wp.showCmd == SW_SHOWNORMAL) { - // GetWindowPlacement can return misleading position if a normalized - // window was resized using Aero Snap feature (see comment 9 in bug - // 36421). As a workaround, using GetWindowRect for normalized windows. - const bool succeeded = GetWindowRect(hwnd(), &wp.rcNormalPosition) != 0; - DCHECK(succeeded); - - *bounds = gfx::Rect(wp.rcNormalPosition); - } else { - MONITORINFO mi; - mi.cbSize = sizeof(mi); - const bool succeeded = GetMonitorInfo( - MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONEAREST), &mi) != 0; - DCHECK(succeeded); - - *bounds = gfx::Rect(wp.rcNormalPosition); - // Convert normal position from workarea coordinates to screen - // coordinates. - bounds->Offset(mi.rcWork.left - mi.rcMonitor.left, - mi.rcWork.top - mi.rcMonitor.top); - } - } - - if (show_state) { - if (wp.showCmd == SW_SHOWMAXIMIZED) - *show_state = ui::SHOW_STATE_MAXIMIZED; - else if (wp.showCmd == SW_SHOWMINIMIZED) - *show_state = ui::SHOW_STATE_MINIMIZED; - else - *show_state = ui::SHOW_STATE_NORMAL; - } -} - -void HWNDMessageHandler::SetBounds(const gfx::Rect& bounds_in_pixels, - bool force_size_changed) { - LONG style = GetWindowLong(hwnd(), GWL_STYLE); - if (style & WS_MAXIMIZE) - SetWindowLong(hwnd(), GWL_STYLE, style & ~WS_MAXIMIZE); - - gfx::Size old_size = GetClientAreaBounds().size(); - SetWindowPos(hwnd(), NULL, bounds_in_pixels.x(), bounds_in_pixels.y(), - bounds_in_pixels.width(), bounds_in_pixels.height(), - SWP_NOACTIVATE | SWP_NOZORDER); - - // If HWND size is not changed, we will not receive standard size change - // notifications. If |force_size_changed| is |true|, we should pretend size is - // changed. - if (old_size == bounds_in_pixels.size() && force_size_changed) { - delegate_->HandleClientSizeChanged(GetClientAreaBounds().size()); - ResetWindowRegion(false, true); - } -} - -void HWNDMessageHandler::SetSize(const gfx::Size& size) { - SetWindowPos(hwnd(), NULL, 0, 0, size.width(), size.height(), - SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOMOVE); -} - -void HWNDMessageHandler::CenterWindow(const gfx::Size& size) { - HWND parent = GetParent(hwnd()); - if (!IsWindow(hwnd())) - parent = ::GetWindow(hwnd(), GW_OWNER); - gfx::CenterAndSizeWindow(parent, hwnd(), size); -} - -void HWNDMessageHandler::SetRegion(HRGN region) { - custom_window_region_.Set(region); - ResetWindowRegion(false, true); - UpdateDwmNcRenderingPolicy(); -} - -void HWNDMessageHandler::StackAbove(HWND other_hwnd) { - SetWindowPos(hwnd(), other_hwnd, 0, 0, 0, 0, - SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE); -} - -void HWNDMessageHandler::StackAtTop() { - SetWindowPos(hwnd(), HWND_TOP, 0, 0, 0, 0, - SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE); -} - -void HWNDMessageHandler::Show() { - if (IsWindow(hwnd())) { - if (!(GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_TRANSPARENT) && - !(GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_NOACTIVATE)) { - ShowWindowWithState(ui::SHOW_STATE_NORMAL); - } else { - ShowWindowWithState(ui::SHOW_STATE_INACTIVE); - } - } -} - -void HWNDMessageHandler::ShowWindowWithState(ui::WindowShowState show_state) { - TRACE_EVENT0("views", "HWNDMessageHandler::ShowWindowWithState"); - DWORD native_show_state; - switch (show_state) { - case ui::SHOW_STATE_INACTIVE: - native_show_state = SW_SHOWNOACTIVATE; - break; - case ui::SHOW_STATE_MAXIMIZED: - native_show_state = SW_SHOWMAXIMIZED; - break; - case ui::SHOW_STATE_MINIMIZED: - native_show_state = SW_SHOWMINIMIZED; - break; - default: - native_show_state = delegate_->GetInitialShowState(); - break; - } - - ShowWindow(hwnd(), native_show_state); - // When launched from certain programs like bash and Windows Live Messenger, - // show_state is set to SW_HIDE, so we need to correct that condition. We - // don't just change show_state to SW_SHOWNORMAL because MSDN says we must - // always first call ShowWindow with the specified value from STARTUPINFO, - // otherwise all future ShowWindow calls will be ignored (!!#@@#!). Instead, - // we call ShowWindow again in this case. - if (native_show_state == SW_HIDE) { - native_show_state = SW_SHOWNORMAL; - ShowWindow(hwnd(), native_show_state); - } - - // We need to explicitly activate the window if we've been shown with a state - // that should activate, because if we're opened from a desktop shortcut while - // an existing window is already running it doesn't seem to be enough to use - // one of these flags to activate the window. - if (native_show_state == SW_SHOWNORMAL || - native_show_state == SW_SHOWMAXIMIZED) - Activate(); - - if (!delegate_->HandleInitialFocus(show_state)) - SetInitialFocus(); -} - -void HWNDMessageHandler::ShowMaximizedWithBounds(const gfx::Rect& bounds) { - WINDOWPLACEMENT placement = { 0 }; - placement.length = sizeof(WINDOWPLACEMENT); - placement.showCmd = SW_SHOWMAXIMIZED; - placement.rcNormalPosition = bounds.ToRECT(); - SetWindowPlacement(hwnd(), &placement); -} - -void HWNDMessageHandler::Hide() { - if (IsWindow(hwnd())) { - // NOTE: Be careful not to activate any windows here (for example, calling - // ShowWindow(SW_HIDE) will automatically activate another window). This - // code can be called while a window is being deactivated, and activating - // another window will screw up the activation that is already in progress. - SetWindowPos(hwnd(), NULL, 0, 0, 0, 0, - SWP_HIDEWINDOW | SWP_NOACTIVATE | SWP_NOMOVE | - SWP_NOREPOSITION | SWP_NOSIZE | SWP_NOZORDER); - } -} - -void HWNDMessageHandler::Maximize() { - ExecuteSystemMenuCommand(SC_MAXIMIZE); -} - -void HWNDMessageHandler::Minimize() { - ExecuteSystemMenuCommand(SC_MINIMIZE); - delegate_->HandleNativeBlur(NULL); -} - -void HWNDMessageHandler::Restore() { - ExecuteSystemMenuCommand(SC_RESTORE); -} - -void HWNDMessageHandler::Activate() { - if (IsMinimized()) - ::ShowWindow(hwnd(), SW_RESTORE); - ::SetWindowPos(hwnd(), HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE); - SetForegroundWindow(hwnd()); -} - -void HWNDMessageHandler::Deactivate() { - HWND next_hwnd = ::GetNextWindow(hwnd(), GW_HWNDNEXT); - while (next_hwnd) { - if (::IsWindowVisible(next_hwnd)) { - ::SetForegroundWindow(next_hwnd); - return; - } - next_hwnd = ::GetNextWindow(next_hwnd, GW_HWNDNEXT); - } -} - -void HWNDMessageHandler::SetAlwaysOnTop(bool on_top) { - ::SetWindowPos(hwnd(), on_top ? HWND_TOPMOST : HWND_NOTOPMOST, - 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); -} - -bool HWNDMessageHandler::IsVisible() const { - return !!::IsWindowVisible(hwnd()); -} - -bool HWNDMessageHandler::IsActive() const { - return GetActiveWindow() == hwnd(); -} - -bool HWNDMessageHandler::IsMinimized() const { - return !!::IsIconic(hwnd()); -} - -bool HWNDMessageHandler::IsMaximized() const { - return !!::IsZoomed(hwnd()); -} - -bool HWNDMessageHandler::IsAlwaysOnTop() const { - return (GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_TOPMOST) != 0; -} - -bool HWNDMessageHandler::RunMoveLoop(const gfx::Vector2d& drag_offset, - bool hide_on_escape) { - ReleaseCapture(); - MoveLoopMouseWatcher watcher(this, hide_on_escape); - // In Aura, we handle touch events asynchronously. So we need to allow nested - // tasks while in windows move loop. - base::MessageLoop::ScopedNestableTaskAllower allow_nested( - base::MessageLoop::current()); - - SendMessage(hwnd(), WM_SYSCOMMAND, SC_MOVE | 0x0002, GetMessagePos()); - // Windows doesn't appear to offer a way to determine whether the user - // canceled the move or not. We assume if the user released the mouse it was - // successful. - return watcher.got_mouse_up(); -} - -void HWNDMessageHandler::EndMoveLoop() { - SendMessage(hwnd(), WM_CANCELMODE, 0, 0); -} - -void HWNDMessageHandler::SendFrameChanged() { - SetWindowPos(hwnd(), NULL, 0, 0, 0, 0, - SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOCOPYBITS | - SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOREPOSITION | - SWP_NOSENDCHANGING | SWP_NOSIZE | SWP_NOZORDER); -} - -void HWNDMessageHandler::FlashFrame(bool flash) { - FLASHWINFO fwi; - fwi.cbSize = sizeof(fwi); - fwi.hwnd = hwnd(); - if (flash) { - fwi.dwFlags = FLASHW_ALL; - fwi.uCount = 4; - fwi.dwTimeout = 0; - } else { - fwi.dwFlags = FLASHW_STOP; - } - FlashWindowEx(&fwi); -} - -void HWNDMessageHandler::ClearNativeFocus() { - ::SetFocus(hwnd()); -} - -void HWNDMessageHandler::SetCapture() { - DCHECK(!HasCapture()); - ::SetCapture(hwnd()); -} - -void HWNDMessageHandler::ReleaseCapture() { - if (HasCapture()) - ::ReleaseCapture(); -} - -bool HWNDMessageHandler::HasCapture() const { - return ::GetCapture() == hwnd(); -} - -void HWNDMessageHandler::SetVisibilityChangedAnimationsEnabled(bool enabled) { - if (base::win::GetVersion() >= base::win::VERSION_VISTA) { - int dwm_value = enabled ? FALSE : TRUE; - DwmSetWindowAttribute( - hwnd(), DWMWA_TRANSITIONS_FORCEDISABLED, &dwm_value, sizeof(dwm_value)); - } -} - -bool HWNDMessageHandler::SetTitle(const base::string16& title) { - base::string16 current_title; - size_t len_with_null = GetWindowTextLength(hwnd()) + 1; - if (len_with_null == 1 && title.length() == 0) - return false; - if (len_with_null - 1 == title.length() && - GetWindowText( - hwnd(), WriteInto(¤t_title, len_with_null), len_with_null) && - current_title == title) - return false; - SetWindowText(hwnd(), title.c_str()); - return true; -} - -void HWNDMessageHandler::SetCursor(HCURSOR cursor) { - if (cursor) { - previous_cursor_ = ::SetCursor(cursor); - current_cursor_ = cursor; - } else if (previous_cursor_) { - ::SetCursor(previous_cursor_); - previous_cursor_ = NULL; - } -} - -void HWNDMessageHandler::FrameTypeChanged() { - if (base::win::GetVersion() < base::win::VERSION_VISTA) { - // Don't redraw the window here, because we invalidate the window later. - ResetWindowRegion(true, false); - // The non-client view needs to update too. - delegate_->HandleFrameChanged(); - InvalidateRect(hwnd(), NULL, FALSE); - } else { - if (!custom_window_region_ && !delegate_->IsUsingCustomFrame()) - dwm_transition_desired_ = true; - if (!dwm_transition_desired_ || !fullscreen_handler_->fullscreen()) - PerformDwmTransition(); - } -} - -void HWNDMessageHandler::SchedulePaintInRect(const gfx::Rect& rect) { - if (use_layered_buffer_) { - // We must update the back-buffer immediately, since Windows' handling of - // invalid rects is somewhat mysterious. - invalid_rect_.Union(rect); - - // In some situations, such as drag and drop, when Windows itself runs a - // nested message loop our message loop appears to be starved and we don't - // receive calls to DidProcessMessage(). This only seems to affect layered - // windows, so we schedule a redraw manually using a task, since those never - // seem to be starved. Also, wtf. - if (!waiting_for_redraw_layered_window_contents_) { - waiting_for_redraw_layered_window_contents_ = true; - base::MessageLoop::current()->PostTask( - FROM_HERE, - base::Bind(&HWNDMessageHandler::RedrawLayeredWindowContents, - weak_factory_.GetWeakPtr())); - } - } else { - // InvalidateRect() expects client coordinates. - RECT r = rect.ToRECT(); - InvalidateRect(hwnd(), &r, FALSE); - } -} - -void HWNDMessageHandler::SetOpacity(BYTE opacity) { - layered_alpha_ = opacity; -} - -void HWNDMessageHandler::SetWindowIcons(const gfx::ImageSkia& window_icon, - const gfx::ImageSkia& app_icon) { - if (!window_icon.isNull()) { - HICON windows_icon = IconUtil::CreateHICONFromSkBitmap( - *window_icon.bitmap()); - // We need to make sure to destroy the previous icon, otherwise we'll leak - // these GDI objects until we crash! - HICON old_icon = reinterpret_cast<HICON>( - SendMessage(hwnd(), WM_SETICON, ICON_SMALL, - reinterpret_cast<LPARAM>(windows_icon))); - if (old_icon) - DestroyIcon(old_icon); - } - if (!app_icon.isNull()) { - HICON windows_icon = IconUtil::CreateHICONFromSkBitmap(*app_icon.bitmap()); - HICON old_icon = reinterpret_cast<HICON>( - SendMessage(hwnd(), WM_SETICON, ICON_BIG, - reinterpret_cast<LPARAM>(windows_icon))); - if (old_icon) - DestroyIcon(old_icon); - } -} - -void HWNDMessageHandler::SetFullscreen(bool fullscreen) { - fullscreen_handler()->SetFullscreen(fullscreen); - // If we are out of fullscreen and there was a pending DWM transition for the - // window, then go ahead and do it now. - if (!fullscreen && dwm_transition_desired_) - PerformDwmTransition(); -} - -void HWNDMessageHandler::SizeConstraintsChanged() { - LONG style = GetWindowLong(hwnd(), GWL_STYLE); - // Ignore if this is not a standard window. - if (!(style & WS_OVERLAPPED)) - return; - - if (delegate_->CanResize()) { - style |= WS_THICKFRAME | WS_MAXIMIZEBOX; - if (!delegate_->CanMaximize()) - style &= ~WS_MAXIMIZEBOX; - } else { - style &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX); - } - if (delegate_->CanMinimize()) { - style |= WS_MINIMIZEBOX; - } else { - style &= ~WS_MINIMIZEBOX; - } - SetWindowLong(hwnd(), GWL_STYLE, style); -} - -//////////////////////////////////////////////////////////////////////////////// -// HWNDMessageHandler, InputMethodDelegate implementation: - -void HWNDMessageHandler::DispatchKeyEventPostIME(const ui::KeyEvent& key) { - SetMsgHandled(delegate_->HandleKeyEvent(key)); -} - -//////////////////////////////////////////////////////////////////////////////// -// HWNDMessageHandler, gfx::WindowImpl overrides: - -HICON HWNDMessageHandler::GetDefaultWindowIcon() const { - if (use_system_default_icon_) - return NULL; - return ViewsDelegate::views_delegate ? - ViewsDelegate::views_delegate->GetDefaultWindowIcon() : NULL; -} - -LRESULT HWNDMessageHandler::OnWndProc(UINT message, - WPARAM w_param, - LPARAM l_param) { - HWND window = hwnd(); - LRESULT result = 0; - - if (delegate_ && delegate_->PreHandleMSG(message, w_param, l_param, &result)) - return result; - - // Otherwise we handle everything else. - // NOTE: We inline ProcessWindowMessage() as 'this' may be destroyed during - // dispatch and ProcessWindowMessage() doesn't deal with that well. - const BOOL old_msg_handled = msg_handled_; - base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr()); - const BOOL processed = - _ProcessWindowMessage(window, message, w_param, l_param, result, 0); - if (!ref) - return 0; - msg_handled_ = old_msg_handled; - - if (!processed) { - result = DefWindowProc(window, message, w_param, l_param); - // DefWindowProc() may have destroyed the window and/or us in a nested - // message loop. - if (!ref || !::IsWindow(window)) - return result; - } - - if (delegate_) { - delegate_->PostHandleMSG(message, w_param, l_param); - if (message == WM_NCDESTROY) - delegate_->HandleDestroyed(); - } - - if (message == WM_ACTIVATE && IsTopLevelWindow(window)) - PostProcessActivateMessage(LOWORD(w_param), !!HIWORD(w_param)); - return result; -} - -LRESULT HWNDMessageHandler::HandleMouseMessage(unsigned int message, - WPARAM w_param, - LPARAM l_param, - bool* handled) { - // Don't track forwarded mouse messages. We expect the caller to track the - // mouse. - base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr()); - LRESULT ret = HandleMouseEventInternal(message, w_param, l_param, false); - *handled = IsMsgHandled(); - return ret; -} - -LRESULT HWNDMessageHandler::HandleKeyboardMessage(unsigned int message, - WPARAM w_param, - LPARAM l_param, - bool* handled) { - base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr()); - LRESULT ret = OnKeyEvent(message, w_param, l_param); - *handled = IsMsgHandled(); - return ret; -} - -LRESULT HWNDMessageHandler::HandleTouchMessage(unsigned int message, - WPARAM w_param, - LPARAM l_param, - bool* handled) { - base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr()); - LRESULT ret = OnTouchEvent(message, w_param, l_param); - *handled = IsMsgHandled(); - return ret; -} - -LRESULT HWNDMessageHandler::HandleScrollMessage(unsigned int message, - WPARAM w_param, - LPARAM l_param, - bool* handled) { - base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr()); - LRESULT ret = OnScrollMessage(message, w_param, l_param); - *handled = IsMsgHandled(); - return ret; -} - -LRESULT HWNDMessageHandler::HandleNcHitTestMessage(unsigned int message, - WPARAM w_param, - LPARAM l_param, - bool* handled) { - base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr()); - LRESULT ret = OnNCHitTest( - gfx::Point(CR_GET_X_LPARAM(l_param), CR_GET_Y_LPARAM(l_param))); - *handled = IsMsgHandled(); - return ret; -} - -//////////////////////////////////////////////////////////////////////////////// -// HWNDMessageHandler, private: - -int HWNDMessageHandler::GetAppbarAutohideEdges(HMONITOR monitor) { - autohide_factory_.InvalidateWeakPtrs(); - return ViewsDelegate::views_delegate ? - ViewsDelegate::views_delegate->GetAppbarAutohideEdges( - monitor, - base::Bind(&HWNDMessageHandler::OnAppbarAutohideEdgesChanged, - autohide_factory_.GetWeakPtr())) : - ViewsDelegate::EDGE_BOTTOM; -} - -void HWNDMessageHandler::OnAppbarAutohideEdgesChanged() { - // This triggers querying WM_NCCALCSIZE again. - RECT client; - GetWindowRect(hwnd(), &client); - SetWindowPos(hwnd(), NULL, client.left, client.top, - client.right - client.left, client.bottom - client.top, - SWP_FRAMECHANGED); -} - -void HWNDMessageHandler::SetInitialFocus() { - if (!(GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_TRANSPARENT) && - !(GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_NOACTIVATE)) { - // The window does not get keyboard messages unless we focus it. - SetFocus(hwnd()); - } -} - -void HWNDMessageHandler::PostProcessActivateMessage(int activation_state, - bool minimized) { - DCHECK(IsTopLevelWindow(hwnd())); - const bool active = activation_state != WA_INACTIVE && !minimized; - if (delegate_->CanActivate()) - delegate_->HandleActivationChanged(active); -} - -void HWNDMessageHandler::RestoreEnabledIfNecessary() { - if (delegate_->IsModal() && !restored_enabled_) { - restored_enabled_ = true; - // If we were run modally, we need to undo the disabled-ness we inflicted on - // the owner's parent hierarchy. - HWND start = ::GetWindow(hwnd(), GW_OWNER); - while (start) { - ::EnableWindow(start, TRUE); - start = ::GetParent(start); - } - } -} - -void HWNDMessageHandler::ExecuteSystemMenuCommand(int command) { - if (command) - SendMessage(hwnd(), WM_SYSCOMMAND, command, 0); -} - -void HWNDMessageHandler::TrackMouseEvents(DWORD mouse_tracking_flags) { - // Begin tracking mouse events for this HWND so that we get WM_MOUSELEAVE - // when the user moves the mouse outside this HWND's bounds. - if (active_mouse_tracking_flags_ == 0 || mouse_tracking_flags & TME_CANCEL) { - if (mouse_tracking_flags & TME_CANCEL) { - // We're about to cancel active mouse tracking, so empty out the stored - // state. - active_mouse_tracking_flags_ = 0; - } else { - active_mouse_tracking_flags_ = mouse_tracking_flags; - } - - TRACKMOUSEEVENT tme; - tme.cbSize = sizeof(tme); - tme.dwFlags = mouse_tracking_flags; - tme.hwndTrack = hwnd(); - tme.dwHoverTime = 0; - TrackMouseEvent(&tme); - } else if (mouse_tracking_flags != active_mouse_tracking_flags_) { - TrackMouseEvents(active_mouse_tracking_flags_ | TME_CANCEL); - TrackMouseEvents(mouse_tracking_flags); - } -} - -void HWNDMessageHandler::ClientAreaSizeChanged() { - gfx::Size s = GetClientAreaBounds().size(); - delegate_->HandleClientSizeChanged(s); - if (use_layered_buffer_) - layered_window_contents_.reset(new gfx::Canvas(s, 1.0f, false)); -} - -bool HWNDMessageHandler::GetClientAreaInsets(gfx::Insets* insets) const { - if (delegate_->GetClientAreaInsets(insets)) - return true; - DCHECK(insets->empty()); - - // Returning false causes the default handling in OnNCCalcSize() to - // be invoked. - if (!delegate_->IsWidgetWindow() || - (!delegate_->IsUsingCustomFrame() && !remove_standard_frame_)) { - return false; - } - - if (IsMaximized()) { - // Windows automatically adds a standard width border to all sides when a - // window is maximized. - int border_thickness = GetSystemMetrics(SM_CXSIZEFRAME); - if (remove_standard_frame_) - border_thickness -= 1; - *insets = gfx::Insets( - border_thickness, border_thickness, border_thickness, border_thickness); - return true; - } - - *insets = gfx::Insets(); - return true; -} - -void HWNDMessageHandler::ResetWindowRegion(bool force, bool redraw) { - // A native frame uses the native window region, and we don't want to mess - // with it. - // WS_EX_COMPOSITED is used instead of WS_EX_LAYERED under aura. WS_EX_LAYERED - // automatically makes clicks on transparent pixels fall through, that isn't - // the case with WS_EX_COMPOSITED. So, we route WS_EX_COMPOSITED through to - // the delegate to allow for a custom hit mask. - if ((window_ex_style() & WS_EX_COMPOSITED) == 0 && !custom_window_region_ && - (!delegate_->IsUsingCustomFrame() || !delegate_->IsWidgetWindow())) { - if (force) - SetWindowRgn(hwnd(), NULL, redraw); - return; - } - - // Changing the window region is going to force a paint. Only change the - // window region if the region really differs. - HRGN current_rgn = CreateRectRgn(0, 0, 0, 0); - int current_rgn_result = GetWindowRgn(hwnd(), current_rgn); - - RECT window_rect; - GetWindowRect(hwnd(), &window_rect); - HRGN new_region; - if (custom_window_region_) { - new_region = ::CreateRectRgn(0, 0, 0, 0); - ::CombineRgn(new_region, custom_window_region_.Get(), NULL, RGN_COPY); - } else if (IsMaximized()) { - HMONITOR monitor = MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONEAREST); - MONITORINFO mi; - mi.cbSize = sizeof mi; - GetMonitorInfo(monitor, &mi); - RECT work_rect = mi.rcWork; - OffsetRect(&work_rect, -window_rect.left, -window_rect.top); - new_region = CreateRectRgnIndirect(&work_rect); - } else { - gfx::Path window_mask; - delegate_->GetWindowMask(gfx::Size(window_rect.right - window_rect.left, - window_rect.bottom - window_rect.top), - &window_mask); - new_region = gfx::CreateHRGNFromSkPath(window_mask); - } - - if (current_rgn_result == ERROR || !EqualRgn(current_rgn, new_region)) { - // SetWindowRgn takes ownership of the HRGN created by CreateNativeRegion. - SetWindowRgn(hwnd(), new_region, redraw); - } else { - DeleteObject(new_region); - } - - DeleteObject(current_rgn); -} - -void HWNDMessageHandler::UpdateDwmNcRenderingPolicy() { - if (base::win::GetVersion() < base::win::VERSION_VISTA) - return; - - if (fullscreen_handler_->fullscreen()) - return; - - DWMNCRENDERINGPOLICY policy = - custom_window_region_ || delegate_->IsUsingCustomFrame() ? - DWMNCRP_DISABLED : DWMNCRP_ENABLED; - - DwmSetWindowAttribute(hwnd(), DWMWA_NCRENDERING_POLICY, - &policy, sizeof(DWMNCRENDERINGPOLICY)); -} - -LRESULT HWNDMessageHandler::DefWindowProcWithRedrawLock(UINT message, - WPARAM w_param, - LPARAM l_param) { - ScopedRedrawLock lock(this); - // The Widget and HWND can be destroyed in the call to DefWindowProc, so use - // the WeakPtrFactory to avoid unlocking (and crashing) after destruction. - base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr()); - LRESULT result = DefWindowProc(hwnd(), message, w_param, l_param); - if (!ref) - lock.CancelUnlockOperation(); - return result; -} - -void HWNDMessageHandler::LockUpdates(bool force) { - // We skip locked updates when Aero is on for two reasons: - // 1. Because it isn't necessary - // 2. Because toggling the WS_VISIBLE flag may occur while the GPU process is - // attempting to present a child window's backbuffer onscreen. When these - // two actions race with one another, the child window will either flicker - // or will simply stop updating entirely. - if ((force || !ui::win::IsAeroGlassEnabled()) && ++lock_updates_count_ == 1) { - SetWindowLong(hwnd(), GWL_STYLE, - GetWindowLong(hwnd(), GWL_STYLE) & ~WS_VISIBLE); - } -} - -void HWNDMessageHandler::UnlockUpdates(bool force) { - if ((force || !ui::win::IsAeroGlassEnabled()) && --lock_updates_count_ <= 0) { - SetWindowLong(hwnd(), GWL_STYLE, - GetWindowLong(hwnd(), GWL_STYLE) | WS_VISIBLE); - lock_updates_count_ = 0; - } -} - -void HWNDMessageHandler::RedrawLayeredWindowContents() { - waiting_for_redraw_layered_window_contents_ = false; - if (invalid_rect_.IsEmpty()) - return; - - // We need to clip to the dirty rect ourselves. - layered_window_contents_->sk_canvas()->save(); - double scale = gfx::win::GetDeviceScaleFactor(); - layered_window_contents_->sk_canvas()->scale( - SkScalar(scale),SkScalar(scale)); - layered_window_contents_->ClipRect(invalid_rect_); - delegate_->PaintLayeredWindow(layered_window_contents_.get()); - layered_window_contents_->sk_canvas()->scale( - SkScalar(1.0/scale),SkScalar(1.0/scale)); - layered_window_contents_->sk_canvas()->restore(); - - RECT wr; - GetWindowRect(hwnd(), &wr); - SIZE size = {wr.right - wr.left, wr.bottom - wr.top}; - POINT position = {wr.left, wr.top}; - HDC dib_dc = skia::BeginPlatformPaint(layered_window_contents_->sk_canvas()); - POINT zero = {0, 0}; - BLENDFUNCTION blend = {AC_SRC_OVER, 0, layered_alpha_, AC_SRC_ALPHA}; - UpdateLayeredWindow(hwnd(), NULL, &position, &size, dib_dc, &zero, - RGB(0xFF, 0xFF, 0xFF), &blend, ULW_ALPHA); - invalid_rect_.SetRect(0, 0, 0, 0); - skia::EndPlatformPaint(layered_window_contents_->sk_canvas()); -} - -void HWNDMessageHandler::ForceRedrawWindow(int attempts) { - if (ui::IsWorkstationLocked()) { - // Presents will continue to fail as long as the input desktop is - // unavailable. - if (--attempts <= 0) - return; - base::MessageLoop::current()->PostDelayedTask( - FROM_HERE, - base::Bind(&HWNDMessageHandler::ForceRedrawWindow, - weak_factory_.GetWeakPtr(), - attempts), - base::TimeDelta::FromMilliseconds(500)); - return; - } - InvalidateRect(hwnd(), NULL, FALSE); -} - -// Message handlers ------------------------------------------------------------ - -void HWNDMessageHandler::OnActivateApp(BOOL active, DWORD thread_id) { - if (delegate_->IsWidgetWindow() && !active && - thread_id != GetCurrentThreadId()) { - delegate_->HandleAppDeactivated(); - // Also update the native frame if it is rendering the non-client area. - if (!remove_standard_frame_ && !delegate_->IsUsingCustomFrame()) - DefWindowProcWithRedrawLock(WM_NCACTIVATE, FALSE, 0); - } -} - -BOOL HWNDMessageHandler::OnAppCommand(HWND window, - short command, - WORD device, - int keystate) { - BOOL handled = !!delegate_->HandleAppCommand(command); - SetMsgHandled(handled); - // Make sure to return TRUE if the event was handled or in some cases the - // system will execute the default handler which can cause bugs like going - // forward or back two pages instead of one. - return handled; -} - -void HWNDMessageHandler::OnCancelMode() { - delegate_->HandleCancelMode(); - // Need default handling, otherwise capture and other things aren't canceled. - SetMsgHandled(FALSE); -} - -void HWNDMessageHandler::OnCaptureChanged(HWND window) { - delegate_->HandleCaptureLost(); -} - -void HWNDMessageHandler::OnClose() { - delegate_->HandleClose(); -} - -void HWNDMessageHandler::OnCommand(UINT notification_code, - int command, - HWND window) { - // If the notification code is > 1 it means it is control specific and we - // should ignore it. - if (notification_code > 1 || delegate_->HandleAppCommand(command)) - SetMsgHandled(FALSE); -} - -LRESULT HWNDMessageHandler::OnCreate(CREATESTRUCT* create_struct) { - use_layered_buffer_ = !!(window_ex_style() & WS_EX_LAYERED); - - if (window_ex_style() & WS_EX_COMPOSITED) { - if (base::win::GetVersion() >= base::win::VERSION_VISTA) { - // This is part of the magic to emulate layered windows with Aura - // see the explanation elsewere when we set WS_EX_COMPOSITED style. - MARGINS margins = {-1,-1,-1,-1}; - DwmExtendFrameIntoClientArea(hwnd(), &margins); - } - } - - fullscreen_handler_->set_hwnd(hwnd()); - - // This message initializes the window so that focus border are shown for - // windows. - SendMessage(hwnd(), - WM_CHANGEUISTATE, - MAKELPARAM(UIS_CLEAR, UISF_HIDEFOCUS), - 0); - - if (remove_standard_frame_) { - SetWindowLong(hwnd(), GWL_STYLE, - GetWindowLong(hwnd(), GWL_STYLE) & ~WS_CAPTION); - SendFrameChanged(); - } - - // Get access to a modifiable copy of the system menu. - GetSystemMenu(hwnd(), false); - - if (base::win::GetVersion() >= base::win::VERSION_WIN7 && - ui::AreTouchEventsEnabled()) - RegisterTouchWindow(hwnd(), TWF_WANTPALM); - - // We need to allow the delegate to size its contents since the window may not - // receive a size notification when its initial bounds are specified at window - // creation time. - ClientAreaSizeChanged(); - - delegate_->HandleCreate(); - - WTSRegisterSessionNotification(hwnd(), NOTIFY_FOR_THIS_SESSION); - - // TODO(beng): move more of NWW::OnCreate here. - return 0; -} - -void HWNDMessageHandler::OnDestroy() { - WTSUnRegisterSessionNotification(hwnd()); - delegate_->HandleDestroying(); -} - -void HWNDMessageHandler::OnDisplayChange(UINT bits_per_pixel, - const gfx::Size& screen_size) { - delegate_->HandleDisplayChange(); -} - -LRESULT HWNDMessageHandler::OnDwmCompositionChanged(UINT msg, - WPARAM w_param, - LPARAM l_param) { - if (!delegate_->IsWidgetWindow()) { - SetMsgHandled(FALSE); - return 0; - } - - FrameTypeChanged(); - return 0; -} - -void HWNDMessageHandler::OnEnterMenuLoop(BOOL from_track_popup_menu) { - if (menu_depth_++ == 0) - delegate_->HandleMenuLoop(true); -} - -void HWNDMessageHandler::OnEnterSizeMove() { - // Please refer to the comments in the OnSize function about the scrollbar - // hack. - // Hide the Windows scrollbar if the scroll styles are present to ensure - // that a paint flicker does not occur while sizing. - if (in_size_loop_ && needs_scroll_styles_) - ShowScrollBar(hwnd(), SB_BOTH, FALSE); - - delegate_->HandleBeginWMSizeMove(); - SetMsgHandled(FALSE); -} - -LRESULT HWNDMessageHandler::OnEraseBkgnd(HDC dc) { - // Needed to prevent resize flicker. - return 1; -} - -void HWNDMessageHandler::OnExitMenuLoop(BOOL is_shortcut_menu) { - if (--menu_depth_ == 0) - delegate_->HandleMenuLoop(false); - DCHECK_GE(0, menu_depth_); -} - -void HWNDMessageHandler::OnExitSizeMove() { - delegate_->HandleEndWMSizeMove(); - SetMsgHandled(FALSE); - // Please refer to the notes in the OnSize function for information about - // the scrolling hack. - // We hide the Windows scrollbar in the OnEnterSizeMove function. We need - // to add the scroll styles back to ensure that scrolling works in legacy - // trackpoint drivers. - if (in_size_loop_ && needs_scroll_styles_) - AddScrollStylesToWindow(hwnd()); -} - -void HWNDMessageHandler::OnGetMinMaxInfo(MINMAXINFO* minmax_info) { - gfx::Size min_window_size; - gfx::Size max_window_size; - delegate_->GetMinMaxSize(&min_window_size, &max_window_size); - min_window_size = gfx::win::DIPToScreenSize(min_window_size); - max_window_size = gfx::win::DIPToScreenSize(max_window_size); - - - // Add the native frame border size to the minimum and maximum size if the - // view reports its size as the client size. - if (delegate_->WidgetSizeIsClientSize()) { - RECT client_rect, window_rect; - GetClientRect(hwnd(), &client_rect); - GetWindowRect(hwnd(), &window_rect); - CR_DEFLATE_RECT(&window_rect, &client_rect); - min_window_size.Enlarge(window_rect.right - window_rect.left, - window_rect.bottom - window_rect.top); - // Either axis may be zero, so enlarge them independently. - if (max_window_size.width()) - max_window_size.Enlarge(window_rect.right - window_rect.left, 0); - if (max_window_size.height()) - max_window_size.Enlarge(0, window_rect.bottom - window_rect.top); - } - minmax_info->ptMinTrackSize.x = min_window_size.width(); - minmax_info->ptMinTrackSize.y = min_window_size.height(); - if (max_window_size.width() || max_window_size.height()) { - if (!max_window_size.width()) - max_window_size.set_width(GetSystemMetrics(SM_CXMAXTRACK)); - if (!max_window_size.height()) - max_window_size.set_height(GetSystemMetrics(SM_CYMAXTRACK)); - minmax_info->ptMaxTrackSize.x = max_window_size.width(); - minmax_info->ptMaxTrackSize.y = max_window_size.height(); - } - SetMsgHandled(FALSE); -} - -LRESULT HWNDMessageHandler::OnGetObject(UINT message, - WPARAM w_param, - LPARAM l_param) { - LRESULT reference_result = static_cast<LRESULT>(0L); - - // Only the lower 32 bits of l_param are valid when checking the object id - // because it sometimes gets sign-extended incorrectly (but not always). - DWORD obj_id = static_cast<DWORD>(static_cast<DWORD_PTR>(l_param)); - - // Accessibility readers will send an OBJID_CLIENT message - if (OBJID_CLIENT == obj_id) { - // Retrieve MSAA dispatch object for the root view. - base::win::ScopedComPtr<IAccessible> root( - delegate_->GetNativeViewAccessible()); - - // Create a reference that MSAA will marshall to the client. - reference_result = LresultFromObject(IID_IAccessible, w_param, - static_cast<IAccessible*>(root.Detach())); - } - - return reference_result; -} - -LRESULT HWNDMessageHandler::OnImeMessages(UINT message, - WPARAM w_param, - LPARAM l_param) { - LRESULT result = 0; - base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr()); - const bool msg_handled = - delegate_->HandleIMEMessage(message, w_param, l_param, &result); - if (ref.get()) - SetMsgHandled(msg_handled); - return result; -} - -void HWNDMessageHandler::OnInitMenu(HMENU menu) { - bool is_fullscreen = fullscreen_handler_->fullscreen(); - bool is_minimized = IsMinimized(); - bool is_maximized = IsMaximized(); - bool is_restored = !is_fullscreen && !is_minimized && !is_maximized; - - ScopedRedrawLock lock(this); - EnableMenuItemByCommand(menu, SC_RESTORE, delegate_->CanResize() && - (is_minimized || is_maximized)); - EnableMenuItemByCommand(menu, SC_MOVE, is_restored); - EnableMenuItemByCommand(menu, SC_SIZE, delegate_->CanResize() && is_restored); - EnableMenuItemByCommand(menu, SC_MAXIMIZE, delegate_->CanMaximize() && - !is_fullscreen && !is_maximized); - EnableMenuItemByCommand(menu, SC_MINIMIZE, delegate_->CanMinimize() && - !is_minimized); - - if (is_maximized && delegate_->CanResize()) - ::SetMenuDefaultItem(menu, SC_RESTORE, FALSE); - else if (!is_maximized && delegate_->CanMaximize()) - ::SetMenuDefaultItem(menu, SC_MAXIMIZE, FALSE); -} - -void HWNDMessageHandler::OnInputLangChange(DWORD character_set, - HKL input_language_id) { - delegate_->HandleInputLanguageChange(character_set, input_language_id); -} - -LRESULT HWNDMessageHandler::OnKeyEvent(UINT message, - WPARAM w_param, - LPARAM l_param) { - MSG msg = { hwnd(), message, w_param, l_param, GetMessageTime() }; - ui::KeyEvent key(msg); - if (!delegate_->HandleUntranslatedKeyEvent(key)) - DispatchKeyEventPostIME(key); - return 0; -} - -void HWNDMessageHandler::OnKillFocus(HWND focused_window) { - delegate_->HandleNativeBlur(focused_window); - SetMsgHandled(FALSE); -} - -LRESULT HWNDMessageHandler::OnMouseActivate(UINT message, - WPARAM w_param, - LPARAM l_param) { - // Please refer to the comments in the header for the touch_down_contexts_ - // member for the if statement below. - if (touch_down_contexts_) - return MA_NOACTIVATE; - - // On Windows, if we select the menu item by touch and if the window at the - // location is another window on the same thread, that window gets a - // WM_MOUSEACTIVATE message and ends up activating itself, which is not - // correct. We workaround this by setting a property on the window at the - // current cursor location. We check for this property in our - // WM_MOUSEACTIVATE handler and don't activate the window if the property is - // set. - if (::GetProp(hwnd(), ui::kIgnoreTouchMouseActivateForWindow)) { - ::RemoveProp(hwnd(), ui::kIgnoreTouchMouseActivateForWindow); - return MA_NOACTIVATE; - } - // A child window activation should be treated as if we lost activation. - POINT cursor_pos = {0}; - ::GetCursorPos(&cursor_pos); - ::ScreenToClient(hwnd(), &cursor_pos); - // The code below exists for child windows like NPAPI plugins etc which need - // to be activated whenever we receive a WM_MOUSEACTIVATE message. Don't put - // transparent child windows in this bucket as they are not supposed to grab - // activation. - // TODO(ananta) - // Get rid of this code when we deprecate NPAPI plugins. - HWND child = ::RealChildWindowFromPoint(hwnd(), cursor_pos); - if (::IsWindow(child) && child != hwnd() && ::IsWindowVisible(child) && - !(::GetWindowLong(child, GWL_EXSTYLE) & WS_EX_TRANSPARENT)) - PostProcessActivateMessage(WA_INACTIVE, false); - - // TODO(beng): resolve this with the GetWindowLong() check on the subsequent - // line. - if (delegate_->IsWidgetWindow()) - return delegate_->CanActivate() ? MA_ACTIVATE : MA_NOACTIVATEANDEAT; - if (GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_NOACTIVATE) - return MA_NOACTIVATE; - SetMsgHandled(FALSE); - return MA_ACTIVATE; -} - -LRESULT HWNDMessageHandler::OnMouseRange(UINT message, - WPARAM w_param, - LPARAM l_param) { - return HandleMouseEventInternal(message, w_param, l_param, true); -} - -void HWNDMessageHandler::OnMove(const gfx::Point& point) { - delegate_->HandleMove(); - SetMsgHandled(FALSE); -} - -void HWNDMessageHandler::OnMoving(UINT param, const RECT* new_bounds) { - delegate_->HandleMove(); -} - -LRESULT HWNDMessageHandler::OnNCActivate(UINT message, - WPARAM w_param, - LPARAM l_param) { - // Per MSDN, w_param is either TRUE or FALSE. However, MSDN also hints that: - // "If the window is minimized when this message is received, the application - // should pass the message to the DefWindowProc function." - // It is found out that the high word of w_param might be set when the window - // is minimized or restored. To handle this, w_param's high word should be - // cleared before it is converted to BOOL. - BOOL active = static_cast<BOOL>(LOWORD(w_param)); - - bool inactive_rendering_disabled = delegate_->IsInactiveRenderingDisabled(); - - if (!delegate_->IsWidgetWindow()) { - SetMsgHandled(FALSE); - return 0; - } - - if (!delegate_->CanActivate()) - return TRUE; - - // On activation, lift any prior restriction against rendering as inactive. - if (active && inactive_rendering_disabled) - delegate_->EnableInactiveRendering(); - - if (delegate_->IsUsingCustomFrame()) { - // TODO(beng, et al): Hack to redraw this window and child windows - // synchronously upon activation. Not all child windows are redrawing - // themselves leading to issues like http://crbug.com/74604 - // We redraw out-of-process HWNDs asynchronously to avoid hanging the - // whole app if a child HWND belonging to a hung plugin is encountered. - RedrawWindow(hwnd(), NULL, NULL, - RDW_NOCHILDREN | RDW_INVALIDATE | RDW_UPDATENOW); - EnumChildWindows(hwnd(), EnumChildWindowsForRedraw, NULL); - } - - // The frame may need to redraw as a result of the activation change. - // We can get WM_NCACTIVATE before we're actually visible. If we're not - // visible, no need to paint. - if (IsVisible()) - delegate_->SchedulePaint(); - - // Avoid DefWindowProc non-client rendering over our custom frame on newer - // Windows versions only (breaks taskbar activation indication on XP/Vista). - if (delegate_->IsUsingCustomFrame() && - base::win::GetVersion() > base::win::VERSION_VISTA) { - SetMsgHandled(TRUE); - return TRUE; - } - - return DefWindowProcWithRedrawLock( - WM_NCACTIVATE, inactive_rendering_disabled || active, 0); -} - -LRESULT HWNDMessageHandler::OnNCCalcSize(BOOL mode, LPARAM l_param) { - // We only override the default handling if we need to specify a custom - // non-client edge width. Note that in most cases "no insets" means no - // custom width, but in fullscreen mode or when the NonClientFrameView - // requests it, we want a custom width of 0. - - // Let User32 handle the first nccalcsize for captioned windows - // so it updates its internal structures (specifically caption-present) - // Without this Tile & Cascade windows won't work. - // See http://code.google.com/p/chromium/issues/detail?id=900 - if (is_first_nccalc_) { - is_first_nccalc_ = false; - if (GetWindowLong(hwnd(), GWL_STYLE) & WS_CAPTION) { - SetMsgHandled(FALSE); - return 0; - } - } - - gfx::Insets insets; - bool got_insets = GetClientAreaInsets(&insets); - if (!got_insets && !fullscreen_handler_->fullscreen() && - !(mode && remove_standard_frame_)) { - SetMsgHandled(FALSE); - return 0; - } - - RECT* client_rect = mode ? - &(reinterpret_cast<NCCALCSIZE_PARAMS*>(l_param)->rgrc[0]) : - reinterpret_cast<RECT*>(l_param); - client_rect->left += insets.left(); - client_rect->top += insets.top(); - client_rect->bottom -= insets.bottom(); - client_rect->right -= insets.right(); - if (IsMaximized()) { - // Find all auto-hide taskbars along the screen edges and adjust in by the - // thickness of the auto-hide taskbar on each such edge, so the window isn't - // treated as a "fullscreen app", which would cause the taskbars to - // disappear. - HMONITOR monitor = MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONULL); - if (!monitor) { - // We might end up here if the window was previously minimized and the - // user clicks on the taskbar button to restore it in the previously - // maximized position. In that case WM_NCCALCSIZE is sent before the - // window coordinates are restored to their previous values, so our - // (left,top) would probably be (-32000,-32000) like all minimized - // windows. So the above MonitorFromWindow call fails, but if we check - // the window rect given with WM_NCCALCSIZE (which is our previous - // restored window position) we will get the correct monitor handle. - monitor = MonitorFromRect(client_rect, MONITOR_DEFAULTTONULL); - if (!monitor) { - // This is probably an extreme case that we won't hit, but if we don't - // intersect any monitor, let us not adjust the client rect since our - // window will not be visible anyway. - return 0; - } - } - const int autohide_edges = GetAppbarAutohideEdges(monitor); - if (autohide_edges & ViewsDelegate::EDGE_LEFT) - client_rect->left += kAutoHideTaskbarThicknessPx; - if (autohide_edges & ViewsDelegate::EDGE_TOP) { - if (!delegate_->IsUsingCustomFrame()) { - // Tricky bit. Due to a bug in DwmDefWindowProc()'s handling of - // WM_NCHITTEST, having any nonclient area atop the window causes the - // caption buttons to draw onscreen but not respond to mouse - // hover/clicks. - // So for a taskbar at the screen top, we can't push the - // client_rect->top down; instead, we move the bottom up by one pixel, - // which is the smallest change we can make and still get a client area - // less than the screen size. This is visibly ugly, but there seems to - // be no better solution. - --client_rect->bottom; - } else { - client_rect->top += kAutoHideTaskbarThicknessPx; - } - } - if (autohide_edges & ViewsDelegate::EDGE_RIGHT) - client_rect->right -= kAutoHideTaskbarThicknessPx; - if (autohide_edges & ViewsDelegate::EDGE_BOTTOM) - client_rect->bottom -= kAutoHideTaskbarThicknessPx; - - // We cannot return WVR_REDRAW when there is nonclient area, or Windows - // exhibits bugs where client pixels and child HWNDs are mispositioned by - // the width/height of the upper-left nonclient area. - return 0; - } - - // If the window bounds change, we're going to relayout and repaint anyway. - // Returning WVR_REDRAW avoids an extra paint before that of the old client - // pixels in the (now wrong) location, and thus makes actions like resizing a - // window from the left edge look slightly less broken. - // We special case when left or top insets are 0, since these conditions - // actually require another repaint to correct the layout after glass gets - // turned on and off. - if (insets.left() == 0 || insets.top() == 0) - return 0; - return mode ? WVR_REDRAW : 0; -} - -LRESULT HWNDMessageHandler::OnNCHitTest(const gfx::Point& point) { - if (!delegate_->IsWidgetWindow()) { - SetMsgHandled(FALSE); - return 0; - } - - // If the DWM is rendering the window controls, we need to give the DWM's - // default window procedure first chance to handle hit testing. - if (!remove_standard_frame_ && !delegate_->IsUsingCustomFrame()) { - LRESULT result; - if (DwmDefWindowProc(hwnd(), WM_NCHITTEST, 0, - MAKELPARAM(point.x(), point.y()), &result)) { - return result; - } - } - - // First, give the NonClientView a chance to test the point to see if it - // provides any of the non-client area. - POINT temp = { point.x(), point.y() }; - MapWindowPoints(HWND_DESKTOP, hwnd(), &temp, 1); - int component = delegate_->GetNonClientComponent(gfx::Point(temp)); - if (component != HTNOWHERE) - return component; - - // Otherwise, we let Windows do all the native frame non-client handling for - // us. - LRESULT hit_test_code = DefWindowProc(hwnd(), WM_NCHITTEST, 0, - MAKELPARAM(point.x(), point.y())); - if (needs_scroll_styles_) { - switch (hit_test_code) { - // If we faked the WS_VSCROLL and WS_HSCROLL styles for this window, then - // Windows returns the HTVSCROLL or HTHSCROLL hit test codes if we hover - // or click on the non client portions of the window where the OS - // scrollbars would be drawn. These hittest codes are returned even when - // the scrollbars are hidden, which is the case in Aura. We fake the - // hittest code as HTCLIENT in this case to ensure that we receive client - // mouse messages as opposed to non client mouse messages. - case HTVSCROLL: - case HTHSCROLL: - hit_test_code = HTCLIENT; - break; - - case HTBOTTOMRIGHT: { - // Normally the HTBOTTOMRIGHT hittest code is received when we hover - // near the bottom right of the window. However due to our fake scroll - // styles, we get this code even when we hover around the area where - // the vertical scrollar down arrow would be drawn. - // We check if the hittest coordinates lie in this region and if yes - // we return HTCLIENT. - int border_width = ::GetSystemMetrics(SM_CXSIZEFRAME); - int border_height = ::GetSystemMetrics(SM_CYSIZEFRAME); - int scroll_width = ::GetSystemMetrics(SM_CXVSCROLL); - int scroll_height = ::GetSystemMetrics(SM_CYVSCROLL); - RECT window_rect; - ::GetWindowRect(hwnd(), &window_rect); - window_rect.bottom -= border_height; - window_rect.right -= border_width; - window_rect.left = window_rect.right - scroll_width; - window_rect.top = window_rect.bottom - scroll_height; - POINT pt; - pt.x = point.x(); - pt.y = point.y(); - if (::PtInRect(&window_rect, pt)) - hit_test_code = HTCLIENT; - break; - } - - default: - break; - } - } - return hit_test_code; -} - -void HWNDMessageHandler::OnNCPaint(HRGN rgn) { - // We only do non-client painting if we're not using the native frame. - // It's required to avoid some native painting artifacts from appearing when - // the window is resized. - if (!delegate_->IsWidgetWindow() || !delegate_->IsUsingCustomFrame()) { - SetMsgHandled(FALSE); - return; - } - - // We have an NC region and need to paint it. We expand the NC region to - // include the dirty region of the root view. This is done to minimize - // paints. - RECT window_rect; - GetWindowRect(hwnd(), &window_rect); - - gfx::Size root_view_size = delegate_->GetRootViewSize(); - if (gfx::Size(window_rect.right - window_rect.left, - window_rect.bottom - window_rect.top) != root_view_size) { - // If the size of the window differs from the size of the root view it - // means we're being asked to paint before we've gotten a WM_SIZE. This can - // happen when the user is interactively resizing the window. To avoid - // mass flickering we don't do anything here. Once we get the WM_SIZE we'll - // reset the region of the window which triggers another WM_NCPAINT and - // all is well. - return; - } - - RECT dirty_region; - // A value of 1 indicates paint all. - if (!rgn || rgn == reinterpret_cast<HRGN>(1)) { - dirty_region.left = 0; - dirty_region.top = 0; - dirty_region.right = window_rect.right - window_rect.left; - dirty_region.bottom = window_rect.bottom - window_rect.top; - } else { - RECT rgn_bounding_box; - GetRgnBox(rgn, &rgn_bounding_box); - if (!IntersectRect(&dirty_region, &rgn_bounding_box, &window_rect)) - return; // Dirty region doesn't intersect window bounds, bale. - - // rgn_bounding_box is in screen coordinates. Map it to window coordinates. - OffsetRect(&dirty_region, -window_rect.left, -window_rect.top); - } - - // In theory GetDCEx should do what we want, but I couldn't get it to work. - // In particular the docs mentiond DCX_CLIPCHILDREN, but as far as I can tell - // it doesn't work at all. So, instead we get the DC for the window then - // manually clip out the children. - HDC dc = GetWindowDC(hwnd()); - ClipState clip_state; - clip_state.x = window_rect.left; - clip_state.y = window_rect.top; - clip_state.parent = hwnd(); - clip_state.dc = dc; - EnumChildWindows(hwnd(), &ClipDCToChild, - reinterpret_cast<LPARAM>(&clip_state)); - - gfx::Rect old_paint_region = invalid_rect_; - if (!old_paint_region.IsEmpty()) { - // The root view has a region that needs to be painted. Include it in the - // region we're going to paint. - - RECT old_paint_region_crect = old_paint_region.ToRECT(); - RECT tmp = dirty_region; - UnionRect(&dirty_region, &tmp, &old_paint_region_crect); - } - - SchedulePaintInRect(gfx::Rect(dirty_region)); - - // gfx::CanvasSkiaPaint's destructor does the actual painting. As such, wrap - // the following in a block to force paint to occur so that we can release - // the dc. - if (!delegate_->HandlePaintAccelerated(gfx::Rect(dirty_region))) { - gfx::CanvasSkiaPaint canvas(dc, - true, - dirty_region.left, - dirty_region.top, - dirty_region.right - dirty_region.left, - dirty_region.bottom - dirty_region.top); - delegate_->HandlePaint(&canvas); - } - - ReleaseDC(hwnd(), dc); - // When using a custom frame, we want to avoid calling DefWindowProc() since - // that may render artifacts. - SetMsgHandled(delegate_->IsUsingCustomFrame()); -} - -LRESULT HWNDMessageHandler::OnNCUAHDrawCaption(UINT message, - WPARAM w_param, - LPARAM l_param) { - // See comment in widget_win.h at the definition of WM_NCUAHDRAWCAPTION for - // an explanation about why we need to handle this message. - SetMsgHandled(delegate_->IsUsingCustomFrame()); - return 0; -} - -LRESULT HWNDMessageHandler::OnNCUAHDrawFrame(UINT message, - WPARAM w_param, - LPARAM l_param) { - // See comment in widget_win.h at the definition of WM_NCUAHDRAWCAPTION for - // an explanation about why we need to handle this message. - SetMsgHandled(delegate_->IsUsingCustomFrame()); - return 0; -} - -LRESULT HWNDMessageHandler::OnNotify(int w_param, NMHDR* l_param) { - LRESULT l_result = 0; - SetMsgHandled(delegate_->HandleTooltipNotify(w_param, l_param, &l_result)); - return l_result; -} - -void HWNDMessageHandler::OnPaint(HDC dc) { - // Call BeginPaint()/EndPaint() around the paint handling, as that seems - // to do more to actually validate the window's drawing region. This only - // appears to matter for Windows that have the WS_EX_COMPOSITED style set - // but will be valid in general too. - PAINTSTRUCT ps; - HDC display_dc = BeginPaint(hwnd(), &ps); - CHECK(display_dc); - - // Try to paint accelerated first. - if (!IsRectEmpty(&ps.rcPaint) && - !delegate_->HandlePaintAccelerated(gfx::Rect(ps.rcPaint))) { - delegate_->HandlePaint(NULL); - } - - EndPaint(hwnd(), &ps); -} - -LRESULT HWNDMessageHandler::OnReflectedMessage(UINT message, - WPARAM w_param, - LPARAM l_param) { - SetMsgHandled(FALSE); - return 0; -} - -LRESULT HWNDMessageHandler::OnScrollMessage(UINT message, - WPARAM w_param, - LPARAM l_param) { - MSG msg = { hwnd(), message, w_param, l_param, GetMessageTime() }; - ui::ScrollEvent event(msg); - delegate_->HandleScrollEvent(event); - return 0; -} - -void HWNDMessageHandler::OnSessionChange(WPARAM status_code, - PWTSSESSION_NOTIFICATION session_id) { - // Direct3D presents are ignored while the screen is locked, so force the - // window to be redrawn on unlock. - if (status_code == WTS_SESSION_UNLOCK) - ForceRedrawWindow(10); - - SetMsgHandled(FALSE); -} - -LRESULT HWNDMessageHandler::OnSetCursor(UINT message, - WPARAM w_param, - LPARAM l_param) { - // Reimplement the necessary default behavior here. Calling DefWindowProc can - // trigger weird non-client painting for non-glass windows with custom frames. - // Using a ScopedRedrawLock to prevent caption rendering artifacts may allow - // content behind this window to incorrectly paint in front of this window. - // Invalidating the window to paint over either set of artifacts is not ideal. - wchar_t* cursor = IDC_ARROW; - switch (LOWORD(l_param)) { - case HTSIZE: - cursor = IDC_SIZENWSE; - break; - case HTLEFT: - case HTRIGHT: - cursor = IDC_SIZEWE; - break; - case HTTOP: - case HTBOTTOM: - cursor = IDC_SIZENS; - break; - case HTTOPLEFT: - case HTBOTTOMRIGHT: - cursor = IDC_SIZENWSE; - break; - case HTTOPRIGHT: - case HTBOTTOMLEFT: - cursor = IDC_SIZENESW; - break; - case HTCLIENT: - SetCursor(current_cursor_); - return 1; - case LOWORD(HTERROR): // Use HTERROR's LOWORD value for valid comparison. - SetMsgHandled(FALSE); - break; - default: - // Use the default value, IDC_ARROW. - break; - } - ::SetCursor(LoadCursor(NULL, cursor)); - return 1; -} - -void HWNDMessageHandler::OnSetFocus(HWND last_focused_window) { - delegate_->HandleNativeFocus(last_focused_window); - SetMsgHandled(FALSE); -} - -LRESULT HWNDMessageHandler::OnSetIcon(UINT size_type, HICON new_icon) { - // Use a ScopedRedrawLock to avoid weird non-client painting. - return DefWindowProcWithRedrawLock(WM_SETICON, size_type, - reinterpret_cast<LPARAM>(new_icon)); -} - -LRESULT HWNDMessageHandler::OnSetText(const wchar_t* text) { - // Use a ScopedRedrawLock to avoid weird non-client painting. - return DefWindowProcWithRedrawLock(WM_SETTEXT, NULL, - reinterpret_cast<LPARAM>(text)); -} - -void HWNDMessageHandler::OnSettingChange(UINT flags, const wchar_t* section) { - if (!GetParent(hwnd()) && (flags == SPI_SETWORKAREA) && - !delegate_->WillProcessWorkAreaChange()) { - // Fire a dummy SetWindowPos() call, so we'll trip the code in - // OnWindowPosChanging() below that notices work area changes. - ::SetWindowPos(hwnd(), 0, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | - SWP_NOZORDER | SWP_NOREDRAW | SWP_NOACTIVATE | SWP_NOOWNERZORDER); - SetMsgHandled(TRUE); - } else { - if (flags == SPI_SETWORKAREA) - delegate_->HandleWorkAreaChanged(); - SetMsgHandled(FALSE); - } -} - -void HWNDMessageHandler::OnSize(UINT param, const gfx::Size& size) { - RedrawWindow(hwnd(), NULL, NULL, RDW_INVALIDATE | RDW_ALLCHILDREN); - // ResetWindowRegion is going to trigger WM_NCPAINT. By doing it after we've - // invoked OnSize we ensure the RootView has been laid out. - ResetWindowRegion(false, true); - - // We add the WS_VSCROLL and WS_HSCROLL styles to top level windows to ensure - // that legacy trackpad/trackpoint drivers generate the WM_VSCROLL and - // WM_HSCROLL messages and scrolling works. - // We want the scroll styles to be present on the window. However we don't - // want Windows to draw the scrollbars. To achieve this we hide the scroll - // bars and readd them to the window style in a posted task to ensure that we - // don't get nested WM_SIZE messages. - if (needs_scroll_styles_ && !in_size_loop_) { - ShowScrollBar(hwnd(), SB_BOTH, FALSE); - base::MessageLoop::current()->PostTask( - FROM_HERE, base::Bind(&AddScrollStylesToWindow, hwnd())); - } -} - -void HWNDMessageHandler::OnSysCommand(UINT notification_code, - const gfx::Point& point) { - if (!delegate_->ShouldHandleSystemCommands()) - return; - - // Windows uses the 4 lower order bits of |notification_code| for type- - // specific information so we must exclude this when comparing. - static const int sc_mask = 0xFFF0; - // Ignore size/move/maximize in fullscreen mode. - if (fullscreen_handler_->fullscreen() && - (((notification_code & sc_mask) == SC_SIZE) || - ((notification_code & sc_mask) == SC_MOVE) || - ((notification_code & sc_mask) == SC_MAXIMIZE))) - return; - if (delegate_->IsUsingCustomFrame()) { - if ((notification_code & sc_mask) == SC_MINIMIZE || - (notification_code & sc_mask) == SC_MAXIMIZE || - (notification_code & sc_mask) == SC_RESTORE) { - delegate_->ResetWindowControls(); - } else if ((notification_code & sc_mask) == SC_MOVE || - (notification_code & sc_mask) == SC_SIZE) { - if (!IsVisible()) { - // Circumvent ScopedRedrawLocks and force visibility before entering a - // resize or move modal loop to get continuous sizing/moving feedback. - SetWindowLong(hwnd(), GWL_STYLE, - GetWindowLong(hwnd(), GWL_STYLE) | WS_VISIBLE); - } - } - } - - // Handle SC_KEYMENU, which means that the user has pressed the ALT - // key and released it, so we should focus the menu bar. - if ((notification_code & sc_mask) == SC_KEYMENU && point.x() == 0) { - int modifiers = ui::EF_NONE; - if (base::win::IsShiftPressed()) - modifiers |= ui::EF_SHIFT_DOWN; - if (base::win::IsCtrlPressed()) - modifiers |= ui::EF_CONTROL_DOWN; - // Retrieve the status of shift and control keys to prevent consuming - // shift+alt keys, which are used by Windows to change input languages. - ui::Accelerator accelerator(ui::KeyboardCodeForWindowsKeyCode(VK_MENU), - modifiers); - delegate_->HandleAccelerator(accelerator); - return; - } - - // If the delegate can't handle it, the system implementation will be called. - if (!delegate_->HandleCommand(notification_code)) { - // If the window is being resized by dragging the borders of the window - // with the mouse/touch/keyboard, we flag as being in a size loop. - if ((notification_code & sc_mask) == SC_SIZE) - in_size_loop_ = true; - base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr()); - DefWindowProc(hwnd(), WM_SYSCOMMAND, notification_code, - MAKELPARAM(point.x(), point.y())); - if (!ref.get()) - return; - in_size_loop_ = false; - } -} - -void HWNDMessageHandler::OnThemeChanged() { - ui::NativeThemeWin::instance()->CloseHandles(); -} - -LRESULT HWNDMessageHandler::OnTouchEvent(UINT message, - WPARAM w_param, - LPARAM l_param) { - // Handle touch events only on Aura for now. - int num_points = LOWORD(w_param); - scoped_ptr<TOUCHINPUT[]> input(new TOUCHINPUT[num_points]); - if (ui::GetTouchInputInfoWrapper(reinterpret_cast<HTOUCHINPUT>(l_param), - num_points, input.get(), - sizeof(TOUCHINPUT))) { - int flags = ui::GetModifiersFromKeyState(); - TouchEvents touch_events; - for (int i = 0; i < num_points; ++i) { - POINT point; - point.x = TOUCH_COORD_TO_PIXEL(input[i].x); - point.y = TOUCH_COORD_TO_PIXEL(input[i].y); - - if (base::win::GetVersion() == base::win::VERSION_WIN7) { - // Windows 7 sends touch events for touches in the non-client area, - // whereas Windows 8 does not. In order to unify the behaviour, always - // ignore touch events in the non-client area. - LPARAM l_param_ht = MAKELPARAM(point.x, point.y); - LRESULT hittest = SendMessage(hwnd(), WM_NCHITTEST, 0, l_param_ht); - - if (hittest != HTCLIENT) - return 0; - } - - ScreenToClient(hwnd(), &point); - - last_touch_message_time_ = ::GetMessageTime(); - - ui::EventType touch_event_type = ui::ET_UNKNOWN; - - if (input[i].dwFlags & TOUCHEVENTF_DOWN) { - touch_ids_.insert(input[i].dwID); - touch_event_type = ui::ET_TOUCH_PRESSED; - touch_down_contexts_++; - base::MessageLoop::current()->PostDelayedTask( - FROM_HERE, - base::Bind(&HWNDMessageHandler::ResetTouchDownContext, - weak_factory_.GetWeakPtr()), - base::TimeDelta::FromMilliseconds(kTouchDownContextResetTimeout)); - } else if (input[i].dwFlags & TOUCHEVENTF_UP) { - touch_ids_.erase(input[i].dwID); - touch_event_type = ui::ET_TOUCH_RELEASED; - } else if (input[i].dwFlags & TOUCHEVENTF_MOVE) { - touch_event_type = ui::ET_TOUCH_MOVED; - } - if (touch_event_type != ui::ET_UNKNOWN) { - base::TimeTicks now; - // input[i].dwTime doesn't necessarily relate to the system time at all, - // so use base::TimeTicks::HighResNow() if possible, or - // base::TimeTicks::Now() otherwise. - if (base::TimeTicks::IsHighResNowFastAndReliable()) - now = base::TimeTicks::HighResNow(); - else - now = base::TimeTicks::Now(); - ui::TouchEvent event(touch_event_type, - gfx::Point(point.x, point.y), - id_generator_.GetGeneratedID(input[i].dwID), - now - base::TimeTicks()); - event.set_flags(flags); - event.latency()->AddLatencyNumberWithTimestamp( - ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT, - 0, - 0, - base::TimeTicks::FromInternalValue( - event.time_stamp().ToInternalValue()), - 1); - - touch_events.push_back(event); - if (touch_event_type == ui::ET_TOUCH_RELEASED) - id_generator_.ReleaseNumber(input[i].dwID); - } - } - // Handle the touch events asynchronously. We need this because touch - // events on windows don't fire if we enter a modal loop in the context of - // a touch event. - base::MessageLoop::current()->PostTask( - FROM_HERE, - base::Bind(&HWNDMessageHandler::HandleTouchEvents, - weak_factory_.GetWeakPtr(), touch_events)); - } - CloseTouchInputHandle(reinterpret_cast<HTOUCHINPUT>(l_param)); - SetMsgHandled(FALSE); - return 0; -} - -void HWNDMessageHandler::OnWindowPosChanging(WINDOWPOS* window_pos) { - if (ignore_window_pos_changes_) { - // If somebody's trying to toggle our visibility, change the nonclient area, - // change our Z-order, or activate us, we should probably let it go through. - if (!(window_pos->flags & ((IsVisible() ? SWP_HIDEWINDOW : SWP_SHOWWINDOW) | - SWP_FRAMECHANGED)) && - (window_pos->flags & (SWP_NOZORDER | SWP_NOACTIVATE))) { - // Just sizing/moving the window; ignore. - window_pos->flags |= SWP_NOSIZE | SWP_NOMOVE | SWP_NOREDRAW; - window_pos->flags &= ~(SWP_SHOWWINDOW | SWP_HIDEWINDOW); - } - } else if (!GetParent(hwnd())) { - RECT window_rect; - HMONITOR monitor; - gfx::Rect monitor_rect, work_area; - if (GetWindowRect(hwnd(), &window_rect) && - GetMonitorAndRects(window_rect, &monitor, &monitor_rect, &work_area)) { - bool work_area_changed = (monitor_rect == last_monitor_rect_) && - (work_area != last_work_area_); - if (monitor && (monitor == last_monitor_) && - ((fullscreen_handler_->fullscreen() && - !fullscreen_handler_->metro_snap()) || - work_area_changed)) { - // A rect for the monitor we're on changed. Normally Windows notifies - // us about this (and thus we're reaching here due to the SetWindowPos() - // call in OnSettingChange() above), but with some software (e.g. - // nVidia's nView desktop manager) the work area can change asynchronous - // to any notification, and we're just sent a SetWindowPos() call with a - // new (frequently incorrect) position/size. In either case, the best - // response is to throw away the existing position/size information in - // |window_pos| and recalculate it based on the new work rect. - gfx::Rect new_window_rect; - if (fullscreen_handler_->fullscreen()) { - new_window_rect = monitor_rect; - } else if (IsMaximized()) { - new_window_rect = work_area; - int border_thickness = GetSystemMetrics(SM_CXSIZEFRAME); - new_window_rect.Inset(-border_thickness, -border_thickness); - } else { - new_window_rect = gfx::Rect(window_rect); - new_window_rect.AdjustToFit(work_area); - } - window_pos->x = new_window_rect.x(); - window_pos->y = new_window_rect.y(); - window_pos->cx = new_window_rect.width(); - window_pos->cy = new_window_rect.height(); - // WARNING! Don't set SWP_FRAMECHANGED here, it breaks moving the child - // HWNDs for some reason. - window_pos->flags &= ~(SWP_NOSIZE | SWP_NOMOVE | SWP_NOREDRAW); - window_pos->flags |= SWP_NOCOPYBITS; - - // Now ignore all immediately-following SetWindowPos() changes. Windows - // likes to (incorrectly) recalculate what our position/size should be - // and send us further updates. - ignore_window_pos_changes_ = true; - base::MessageLoop::current()->PostTask( - FROM_HERE, - base::Bind(&HWNDMessageHandler::StopIgnoringPosChanges, - weak_factory_.GetWeakPtr())); - } - last_monitor_ = monitor; - last_monitor_rect_ = monitor_rect; - last_work_area_ = work_area; - } - } - - if (DidClientAreaSizeChange(window_pos)) - delegate_->HandleWindowSizeChanging(); - - if (ScopedFullscreenVisibility::IsHiddenForFullscreen(hwnd())) { - // Prevent the window from being made visible if we've been asked to do so. - // See comment in header as to why we might want this. - window_pos->flags &= ~SWP_SHOWWINDOW; - } - - if (window_pos->flags & SWP_SHOWWINDOW) - delegate_->HandleVisibilityChanging(true); - else if (window_pos->flags & SWP_HIDEWINDOW) - delegate_->HandleVisibilityChanging(false); - - SetMsgHandled(FALSE); -} - -void HWNDMessageHandler::OnWindowPosChanged(WINDOWPOS* window_pos) { - if (DidClientAreaSizeChange(window_pos)) - ClientAreaSizeChanged(); - if (remove_standard_frame_ && window_pos->flags & SWP_FRAMECHANGED && - ui::win::IsAeroGlassEnabled() && - (window_ex_style() & WS_EX_COMPOSITED) == 0) { - MARGINS m = {10, 10, 10, 10}; - DwmExtendFrameIntoClientArea(hwnd(), &m); - } - if (window_pos->flags & SWP_SHOWWINDOW) - delegate_->HandleVisibilityChanged(true); - else if (window_pos->flags & SWP_HIDEWINDOW) - delegate_->HandleVisibilityChanged(false); - SetMsgHandled(FALSE); -} - -void HWNDMessageHandler::HandleTouchEvents(const TouchEvents& touch_events) { - base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr()); - for (size_t i = 0; i < touch_events.size() && ref; ++i) - delegate_->HandleTouchEvent(touch_events[i]); -} - -void HWNDMessageHandler::ResetTouchDownContext() { - touch_down_contexts_--; -} - -LRESULT HWNDMessageHandler::HandleMouseEventInternal(UINT message, - WPARAM w_param, - LPARAM l_param, - bool track_mouse) { - if (!touch_ids_.empty()) - return 0; - // We handle touch events on Windows Aura. Windows generates synthesized - // mouse messages in response to touch which we should ignore. However touch - // messages are only received for the client area. We need to ignore the - // synthesized mouse messages for all points in the client area and places - // which return HTNOWHERE. - if (ui::IsMouseEventFromTouch(message)) { - LPARAM l_param_ht = l_param; - // For mouse events (except wheel events), location is in window coordinates - // and should be converted to screen coordinates for WM_NCHITTEST. - if (message != WM_MOUSEWHEEL && message != WM_MOUSEHWHEEL) { - POINT screen_point = CR_POINT_INITIALIZER_FROM_LPARAM(l_param_ht); - MapWindowPoints(hwnd(), HWND_DESKTOP, &screen_point, 1); - l_param_ht = MAKELPARAM(screen_point.x, screen_point.y); - } - LRESULT hittest = SendMessage(hwnd(), WM_NCHITTEST, 0, l_param_ht); - if (hittest == HTCLIENT || hittest == HTNOWHERE) - return 0; - } - - // Certain logitech drivers send the WM_MOUSEHWHEEL message to the parent - // followed by WM_MOUSEWHEEL messages to the child window causing a vertical - // scroll. We treat these WM_MOUSEWHEEL messages as WM_MOUSEHWHEEL - // messages. - if (message == WM_MOUSEHWHEEL) - last_mouse_hwheel_time_ = ::GetMessageTime(); - - if (message == WM_MOUSEWHEEL && - ::GetMessageTime() == last_mouse_hwheel_time_) { - message = WM_MOUSEHWHEEL; - } - - if (message == WM_RBUTTONUP && is_right_mouse_pressed_on_caption_) { - is_right_mouse_pressed_on_caption_ = false; - ReleaseCapture(); - // |point| is in window coordinates, but WM_NCHITTEST and TrackPopupMenu() - // expect screen coordinates. - POINT screen_point = CR_POINT_INITIALIZER_FROM_LPARAM(l_param); - MapWindowPoints(hwnd(), HWND_DESKTOP, &screen_point, 1); - w_param = SendMessage(hwnd(), WM_NCHITTEST, 0, - MAKELPARAM(screen_point.x, screen_point.y)); - if (w_param == HTCAPTION || w_param == HTSYSMENU) { - gfx::ShowSystemMenuAtPoint(hwnd(), gfx::Point(screen_point)); - return 0; - } - } else if (message == WM_NCLBUTTONDOWN && delegate_->IsUsingCustomFrame()) { - switch (w_param) { - case HTCLOSE: - case HTMINBUTTON: - case HTMAXBUTTON: { - // When the mouse is pressed down in these specific non-client areas, - // we need to tell the RootView to send the mouse pressed event (which - // sets capture, allowing subsequent WM_LBUTTONUP (note, _not_ - // WM_NCLBUTTONUP) to fire so that the appropriate WM_SYSCOMMAND can be - // sent by the applicable button's ButtonListener. We _have_ to do this - // way rather than letting Windows just send the syscommand itself (as - // would happen if we never did this dance) because for some insane - // reason DefWindowProc for WM_NCLBUTTONDOWN also renders the pressed - // window control button appearance, in the Windows classic style, over - // our view! Ick! By handling this message we prevent Windows from - // doing this undesirable thing, but that means we need to roll the - // sys-command handling ourselves. - // Combine |w_param| with common key state message flags. - w_param |= base::win::IsCtrlPressed() ? MK_CONTROL : 0; - w_param |= base::win::IsShiftPressed() ? MK_SHIFT : 0; - } - } - } else if (message == WM_NCRBUTTONDOWN && - (w_param == HTCAPTION || w_param == HTSYSMENU)) { - is_right_mouse_pressed_on_caption_ = true; - // We SetCapture() to ensure we only show the menu when the button - // down and up are both on the caption. Note: this causes the button up to - // be WM_RBUTTONUP instead of WM_NCRBUTTONUP. - SetCapture(); - } - long message_time = GetMessageTime(); - MSG msg = { hwnd(), message, w_param, l_param, message_time, - { CR_GET_X_LPARAM(l_param), CR_GET_Y_LPARAM(l_param) } }; - ui::MouseEvent event(msg); - if (IsSynthesizedMouseMessage(message, message_time, l_param)) - event.set_flags(event.flags() | ui::EF_FROM_TOUCH); - - if (event.type() == ui::ET_MOUSE_MOVED && !HasCapture() && track_mouse) { - // Windows only fires WM_MOUSELEAVE events if the application begins - // "tracking" mouse events for a given HWND during WM_MOUSEMOVE events. - // We need to call |TrackMouseEvents| to listen for WM_MOUSELEAVE. - TrackMouseEvents((message == WM_NCMOUSEMOVE) ? - TME_NONCLIENT | TME_LEAVE : TME_LEAVE); - } else if (event.type() == ui::ET_MOUSE_EXITED) { - // Reset our tracking flags so future mouse movement over this - // NativeWidget results in a new tracking session. Fall through for - // OnMouseEvent. - active_mouse_tracking_flags_ = 0; - } else if (event.type() == ui::ET_MOUSEWHEEL) { - // Reroute the mouse wheel to the window under the pointer if applicable. - return (ui::RerouteMouseWheel(hwnd(), w_param, l_param) || - delegate_->HandleMouseEvent(ui::MouseWheelEvent(msg))) ? 0 : 1; - } - - // There are cases where the code handling the message destroys the window, - // so use the weak ptr to check if destruction occured or not. - base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr()); - bool handled = delegate_->HandleMouseEvent(event); - if (!ref.get()) - return 0; - if (!handled && message == WM_NCLBUTTONDOWN && w_param != HTSYSMENU && - delegate_->IsUsingCustomFrame()) { - // TODO(msw): Eliminate undesired painting, or re-evaluate this workaround. - // DefWindowProc for WM_NCLBUTTONDOWN does weird non-client painting, so we - // need to call it inside a ScopedRedrawLock. This may cause other negative - // side-effects (ex/ stifling non-client mouse releases). - DefWindowProcWithRedrawLock(message, w_param, l_param); - handled = true; - } - - if (ref.get()) - SetMsgHandled(handled); - return 0; -} - -bool HWNDMessageHandler::IsSynthesizedMouseMessage(unsigned int message, - int message_time, - LPARAM l_param) { - if (ui::IsMouseEventFromTouch(message)) - return true; - // Ignore mouse messages which occur at the same location as the current - // cursor position and within a time difference of 500 ms from the last - // touch message. - if (last_touch_message_time_ && message_time >= last_touch_message_time_ && - ((message_time - last_touch_message_time_) <= - kSynthesizedMouseTouchMessagesTimeDifference)) { - POINT mouse_location = CR_POINT_INITIALIZER_FROM_LPARAM(l_param); - ::ClientToScreen(hwnd(), &mouse_location); - POINT cursor_pos = {0}; - ::GetCursorPos(&cursor_pos); - if (memcmp(&cursor_pos, &mouse_location, sizeof(POINT))) - return false; - return true; - } - return false; -} - -void HWNDMessageHandler::PerformDwmTransition() { - dwm_transition_desired_ = false; - - UpdateDwmNcRenderingPolicy(); - // Don't redraw the window here, because we need to hide and show the window - // which will also trigger a redraw. - ResetWindowRegion(true, false); - // The non-client view needs to update too. - delegate_->HandleFrameChanged(); - - if (IsVisible() && !delegate_->IsUsingCustomFrame()) { - // For some reason, we need to hide the window after we change from a custom - // frame to a native frame. If we don't, the client area will be filled - // with black. This seems to be related to an interaction between DWM and - // SetWindowRgn, but the details aren't clear. Additionally, we need to - // specify SWP_NOZORDER here, otherwise if you have multiple chrome windows - // open they will re-appear with a non-deterministic Z-order. - UINT flags = SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER; - SetWindowPos(hwnd(), NULL, 0, 0, 0, 0, flags | SWP_HIDEWINDOW); - SetWindowPos(hwnd(), NULL, 0, 0, 0, 0, flags | SWP_SHOWWINDOW); - } - // WM_DWMCOMPOSITIONCHANGED is only sent to top level windows, however we want - // to notify our children too, since we can have MDI child windows who need to - // update their appearance. - EnumChildWindows(hwnd(), &SendDwmCompositionChanged, NULL); -} - -} // namespace views
diff --git a/ui/views/win/hwnd_message_handler.h b/ui/views/win/hwnd_message_handler.h deleted file mode 100644 index 86d3d52..0000000 --- a/ui/views/win/hwnd_message_handler.h +++ /dev/null
@@ -1,636 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_WIN_HWND_MESSAGE_HANDLER_H_ -#define UI_VIEWS_WIN_HWND_MESSAGE_HANDLER_H_ - -#include <windows.h> - -#include <set> -#include <vector> - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "base/memory/weak_ptr.h" -#include "base/strings/string16.h" -#include "base/win/scoped_gdi_object.h" -#include "base/win/win_util.h" -#include "ui/accessibility/ax_enums.h" -#include "ui/base/ui_base_types.h" -#include "ui/base/win/window_event_target.h" -#include "ui/events/event.h" -#include "ui/gfx/rect.h" -#include "ui/gfx/sequential_id_generator.h" -#include "ui/gfx/win/window_impl.h" -#include "ui/views/ime/input_method_delegate.h" -#include "ui/views/views_export.h" - -namespace gfx { -class Canvas; -class ImageSkia; -class Insets; -} - -namespace ui { -class ViewProp; -} - -namespace views { - -class FullscreenHandler; -class HWNDMessageHandlerDelegate; -class InputMethod; - -// These two messages aren't defined in winuser.h, but they are sent to windows -// with captions. They appear to paint the window caption and frame. -// Unfortunately if you override the standard non-client rendering as we do -// with CustomFrameWindow, sometimes Windows (not deterministically -// reproducibly but definitely frequently) will send these messages to the -// window and paint the standard caption/title over the top of the custom one. -// So we need to handle these messages in CustomFrameWindow to prevent this -// from happening. -const int WM_NCUAHDRAWCAPTION = 0xAE; -const int WM_NCUAHDRAWFRAME = 0xAF; - -// IsMsgHandled() and BEGIN_SAFE_MSG_MAP_EX are a modified version of -// BEGIN_MSG_MAP_EX. The main difference is it adds a WeakPtrFactory member -// (|weak_factory_|) that is used in _ProcessWindowMessage() and changing -// IsMsgHandled() from a member function to a define that checks if the weak -// factory is still valid in addition to the member. Together these allow for -// |this| to be deleted during dispatch. -#define IsMsgHandled() !ref.get() || msg_handled_ - -#define BEGIN_SAFE_MSG_MAP_EX(the_class) \ - private: \ - base::WeakPtrFactory<the_class> weak_factory_; \ - BOOL msg_handled_; \ -\ - public: \ - /* "handled" management for cracked handlers */ \ - void SetMsgHandled(BOOL handled) { \ - msg_handled_ = handled; \ - } \ - BOOL ProcessWindowMessage(HWND hwnd, \ - UINT msg, \ - WPARAM w_param, \ - LPARAM l_param, \ - LRESULT& l_result, \ - DWORD msg_map_id = 0) { \ - base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr()); \ - BOOL old_msg_handled = msg_handled_; \ - BOOL ret = _ProcessWindowMessage(hwnd, msg, w_param, l_param, l_result, \ - msg_map_id); \ - if (ref.get()) \ - msg_handled_ = old_msg_handled; \ - return ret; \ - } \ - BOOL _ProcessWindowMessage(HWND hWnd, \ - UINT uMsg, \ - WPARAM wParam, \ - LPARAM lParam, \ - LRESULT& lResult, \ - DWORD dwMsgMapID) { \ - base::WeakPtr<HWNDMessageHandler> ref(weak_factory_.GetWeakPtr()); \ - BOOL bHandled = TRUE; \ - hWnd; \ - uMsg; \ - wParam; \ - lParam; \ - lResult; \ - bHandled; \ - switch(dwMsgMapID) { \ - case 0: - -// An object that handles messages for a HWND that implements the views -// "Custom Frame" look. The purpose of this class is to isolate the windows- -// specific message handling from the code that wraps it. It is intended to be -// used by both a views::NativeWidget and an aura::WindowTreeHost -// implementation. -// TODO(beng): This object should eventually *become* the WindowImpl. -class VIEWS_EXPORT HWNDMessageHandler : - public gfx::WindowImpl, - public internal::InputMethodDelegate, - public ui::WindowEventTarget { - public: - explicit HWNDMessageHandler(HWNDMessageHandlerDelegate* delegate); - ~HWNDMessageHandler(); - - void Init(HWND parent, const gfx::Rect& bounds); - void InitModalType(ui::ModalType modal_type); - - void Close(); - void CloseNow(); - - gfx::Rect GetWindowBoundsInScreen() const; - gfx::Rect GetClientAreaBoundsInScreen() const; - gfx::Rect GetRestoredBounds() const; - // This accounts for the case where the widget size is the client size. - gfx::Rect GetClientAreaBounds() const; - - void GetWindowPlacement(gfx::Rect* bounds, - ui::WindowShowState* show_state) const; - - // Sets the bounds of the HWND to |bounds_in_pixels|. If the HWND size is not - // changed, |force_size_changed| determines if we should pretend it is. - void SetBounds(const gfx::Rect& bounds_in_pixels, bool force_size_changed); - - void SetSize(const gfx::Size& size); - void CenterWindow(const gfx::Size& size); - - void SetRegion(HRGN rgn); - - void StackAbove(HWND other_hwnd); - void StackAtTop(); - - void Show(); - void ShowWindowWithState(ui::WindowShowState show_state); - void ShowMaximizedWithBounds(const gfx::Rect& bounds); - void Hide(); - - void Maximize(); - void Minimize(); - void Restore(); - - void Activate(); - void Deactivate(); - - void SetAlwaysOnTop(bool on_top); - - bool IsVisible() const; - bool IsActive() const; - bool IsMinimized() const; - bool IsMaximized() const; - bool IsAlwaysOnTop() const; - - bool RunMoveLoop(const gfx::Vector2d& drag_offset, bool hide_on_escape); - void EndMoveLoop(); - - // Tells the HWND its client area has changed. - void SendFrameChanged(); - - void FlashFrame(bool flash); - - void ClearNativeFocus(); - - void SetCapture(); - void ReleaseCapture(); - bool HasCapture() const; - - FullscreenHandler* fullscreen_handler() { return fullscreen_handler_.get(); } - - void SetVisibilityChangedAnimationsEnabled(bool enabled); - - // Returns true if the title changed. - bool SetTitle(const base::string16& title); - - void SetCursor(HCURSOR cursor); - - void FrameTypeChanged(); - - void SchedulePaintInRect(const gfx::Rect& rect); - void SetOpacity(BYTE opacity); - - void SetWindowIcons(const gfx::ImageSkia& window_icon, - const gfx::ImageSkia& app_icon); - - void set_remove_standard_frame(bool remove_standard_frame) { - remove_standard_frame_ = remove_standard_frame; - } - - void set_use_system_default_icon(bool use_system_default_icon) { - use_system_default_icon_ = use_system_default_icon; - } - - void SetFullscreen(bool fullscreen); - - // Updates the window style to reflect whether it can be resized or maximized. - void SizeConstraintsChanged(); - - private: - typedef std::set<DWORD> TouchIDs; - - // Overridden from internal::InputMethodDelegate: - virtual void DispatchKeyEventPostIME(const ui::KeyEvent& key) override; - - // Overridden from WindowImpl: - virtual HICON GetDefaultWindowIcon() const override; - virtual LRESULT OnWndProc(UINT message, - WPARAM w_param, - LPARAM l_param) override; - - // Overridden from WindowEventTarget - virtual LRESULT HandleMouseMessage(unsigned int message, - WPARAM w_param, - LPARAM l_param, - bool* handled) override; - virtual LRESULT HandleKeyboardMessage(unsigned int message, - WPARAM w_param, - LPARAM l_param, - bool* handled) override; - virtual LRESULT HandleTouchMessage(unsigned int message, - WPARAM w_param, - LPARAM l_param, - bool* handled) override; - - virtual LRESULT HandleScrollMessage(unsigned int message, - WPARAM w_param, - LPARAM l_param, - bool* handled) override; - - virtual LRESULT HandleNcHitTestMessage(unsigned int message, - WPARAM w_param, - LPARAM l_param, - bool* handled) override; - - // Returns the auto-hide edges of the appbar. See - // ViewsDelegate::GetAppbarAutohideEdges() for details. If the edges change, - // OnAppbarAutohideEdgesChanged() is called. - int GetAppbarAutohideEdges(HMONITOR monitor); - - // Callback if the autohide edges have changed. See - // ViewsDelegate::GetAppbarAutohideEdges() for details. - void OnAppbarAutohideEdgesChanged(); - - // Can be called after the delegate has had the opportunity to set focus and - // did not do so. - void SetInitialFocus(); - - // Called after the WM_ACTIVATE message has been processed by the default - // windows procedure. - void PostProcessActivateMessage(int activation_state, bool minimized); - - // Enables disabled owner windows that may have been disabled due to this - // window's modality. - void RestoreEnabledIfNecessary(); - - // Executes the specified SC_command. - void ExecuteSystemMenuCommand(int command); - - // Start tracking all mouse events so that this window gets sent mouse leave - // messages too. - void TrackMouseEvents(DWORD mouse_tracking_flags); - - // Responds to the client area changing size, either at window creation time - // or subsequently. - void ClientAreaSizeChanged(); - - // Returns the insets of the client area relative to the non-client area of - // the window. - bool GetClientAreaInsets(gfx::Insets* insets) const; - - // Resets the window region for the current widget bounds if necessary. - // If |force| is true, the window region is reset to NULL even for native - // frame windows. - void ResetWindowRegion(bool force, bool redraw); - - // Enables or disables rendering of the non-client (glass) area by DWM, - // under Vista and above, depending on whether the caller has requested a - // custom frame. - void UpdateDwmNcRenderingPolicy(); - - // Calls DefWindowProc, safely wrapping the call in a ScopedRedrawLock to - // prevent frame flicker. DefWindowProc handling can otherwise render the - // classic-look window title bar directly. - LRESULT DefWindowProcWithRedrawLock(UINT message, - WPARAM w_param, - LPARAM l_param); - - // Lock or unlock the window from being able to redraw itself in response to - // updates to its invalid region. - class ScopedRedrawLock; - void LockUpdates(bool force); - void UnlockUpdates(bool force); - - // Stops ignoring SetWindowPos() requests (see below). - void StopIgnoringPosChanges() { ignore_window_pos_changes_ = false; } - - // Synchronously updates the invalid contents of the Widget. Valid for - // layered windows only. - void RedrawLayeredWindowContents(); - - // Attempts to force the window to be redrawn, ensuring that it gets - // onscreen. - void ForceRedrawWindow(int attempts); - - // Message Handlers ---------------------------------------------------------- - - BEGIN_SAFE_MSG_MAP_EX(HWNDMessageHandler) - // Range handlers must go first! - CR_MESSAGE_RANGE_HANDLER_EX(WM_MOUSEFIRST, WM_MOUSELAST, OnMouseRange) - CR_MESSAGE_RANGE_HANDLER_EX(WM_NCMOUSEMOVE, - WM_NCXBUTTONDBLCLK, - OnMouseRange) - - // CustomFrameWindow hacks - CR_MESSAGE_HANDLER_EX(WM_NCUAHDRAWCAPTION, OnNCUAHDrawCaption) - CR_MESSAGE_HANDLER_EX(WM_NCUAHDRAWFRAME, OnNCUAHDrawFrame) - - // Vista and newer - CR_MESSAGE_HANDLER_EX(WM_DWMCOMPOSITIONCHANGED, OnDwmCompositionChanged) - - // Non-atlcrack.h handlers - CR_MESSAGE_HANDLER_EX(WM_GETOBJECT, OnGetObject) - - // Mouse events. - CR_MESSAGE_HANDLER_EX(WM_MOUSEACTIVATE, OnMouseActivate) - CR_MESSAGE_HANDLER_EX(WM_MOUSELEAVE, OnMouseRange) - CR_MESSAGE_HANDLER_EX(WM_NCMOUSELEAVE, OnMouseRange) - CR_MESSAGE_HANDLER_EX(WM_SETCURSOR, OnSetCursor); - - // Key events. - CR_MESSAGE_HANDLER_EX(WM_KEYDOWN, OnKeyEvent) - CR_MESSAGE_HANDLER_EX(WM_KEYUP, OnKeyEvent) - CR_MESSAGE_HANDLER_EX(WM_SYSKEYDOWN, OnKeyEvent) - CR_MESSAGE_HANDLER_EX(WM_SYSKEYUP, OnKeyEvent) - - // IME Events. - CR_MESSAGE_HANDLER_EX(WM_IME_SETCONTEXT, OnImeMessages) - CR_MESSAGE_HANDLER_EX(WM_IME_STARTCOMPOSITION, OnImeMessages) - CR_MESSAGE_HANDLER_EX(WM_IME_COMPOSITION, OnImeMessages) - CR_MESSAGE_HANDLER_EX(WM_IME_ENDCOMPOSITION, OnImeMessages) - CR_MESSAGE_HANDLER_EX(WM_IME_REQUEST, OnImeMessages) - CR_MESSAGE_HANDLER_EX(WM_IME_NOTIFY, OnImeMessages) - CR_MESSAGE_HANDLER_EX(WM_CHAR, OnImeMessages) - CR_MESSAGE_HANDLER_EX(WM_SYSCHAR, OnImeMessages) - - // Scroll events - CR_MESSAGE_HANDLER_EX(WM_VSCROLL, OnScrollMessage) - CR_MESSAGE_HANDLER_EX(WM_HSCROLL, OnScrollMessage) - - // Touch Events. - CR_MESSAGE_HANDLER_EX(WM_TOUCH, OnTouchEvent) - - // Uses the general handler macro since the specific handler macro - // MSG_WM_NCACTIVATE would convert WPARAM type to BOOL type. The high - // word of WPARAM could be set when the window is minimized or restored. - CR_MESSAGE_HANDLER_EX(WM_NCACTIVATE, OnNCActivate) - - // This list is in _ALPHABETICAL_ order! OR I WILL HURT YOU. - CR_MSG_WM_ACTIVATEAPP(OnActivateApp) - CR_MSG_WM_APPCOMMAND(OnAppCommand) - CR_MSG_WM_CANCELMODE(OnCancelMode) - CR_MSG_WM_CAPTURECHANGED(OnCaptureChanged) - CR_MSG_WM_CLOSE(OnClose) - CR_MSG_WM_COMMAND(OnCommand) - CR_MSG_WM_CREATE(OnCreate) - CR_MSG_WM_DESTROY(OnDestroy) - CR_MSG_WM_DISPLAYCHANGE(OnDisplayChange) - CR_MSG_WM_ENTERMENULOOP(OnEnterMenuLoop) - CR_MSG_WM_EXITMENULOOP(OnExitMenuLoop) - CR_MSG_WM_ENTERSIZEMOVE(OnEnterSizeMove) - CR_MSG_WM_ERASEBKGND(OnEraseBkgnd) - CR_MSG_WM_EXITSIZEMOVE(OnExitSizeMove) - CR_MSG_WM_GETMINMAXINFO(OnGetMinMaxInfo) - CR_MSG_WM_INITMENU(OnInitMenu) - CR_MSG_WM_INPUTLANGCHANGE(OnInputLangChange) - CR_MSG_WM_KILLFOCUS(OnKillFocus) - CR_MSG_WM_MOVE(OnMove) - CR_MSG_WM_MOVING(OnMoving) - CR_MSG_WM_NCCALCSIZE(OnNCCalcSize) - CR_MSG_WM_NCHITTEST(OnNCHitTest) - CR_MSG_WM_NCPAINT(OnNCPaint) - CR_MSG_WM_NOTIFY(OnNotify) - CR_MSG_WM_PAINT(OnPaint) - CR_MSG_WM_SETFOCUS(OnSetFocus) - CR_MSG_WM_SETICON(OnSetIcon) - CR_MSG_WM_SETTEXT(OnSetText) - CR_MSG_WM_SETTINGCHANGE(OnSettingChange) - CR_MSG_WM_SIZE(OnSize) - CR_MSG_WM_SYSCOMMAND(OnSysCommand) - CR_MSG_WM_THEMECHANGED(OnThemeChanged) - CR_MSG_WM_WINDOWPOSCHANGED(OnWindowPosChanged) - CR_MSG_WM_WINDOWPOSCHANGING(OnWindowPosChanging) - CR_MSG_WM_WTSSESSION_CHANGE(OnSessionChange) - CR_END_MSG_MAP() - - // Message Handlers. - // This list is in _ALPHABETICAL_ order! - // TODO(beng): Once this object becomes the WindowImpl, these methods can - // be made private. - void OnActivateApp(BOOL active, DWORD thread_id); - // TODO(beng): return BOOL is temporary until this object becomes a - // WindowImpl. - BOOL OnAppCommand(HWND window, short command, WORD device, int keystate); - void OnCancelMode(); - void OnCaptureChanged(HWND window); - void OnClose(); - void OnCommand(UINT notification_code, int command, HWND window); - LRESULT OnCreate(CREATESTRUCT* create_struct); - void OnDestroy(); - void OnDisplayChange(UINT bits_per_pixel, const gfx::Size& screen_size); - LRESULT OnDwmCompositionChanged(UINT msg, WPARAM w_param, LPARAM l_param); - void OnEnterMenuLoop(BOOL from_track_popup_menu); - void OnEnterSizeMove(); - LRESULT OnEraseBkgnd(HDC dc); - void OnExitMenuLoop(BOOL is_shortcut_menu); - void OnExitSizeMove(); - void OnGetMinMaxInfo(MINMAXINFO* minmax_info); - LRESULT OnGetObject(UINT message, WPARAM w_param, LPARAM l_param); - LRESULT OnImeMessages(UINT message, WPARAM w_param, LPARAM l_param); - void OnInitMenu(HMENU menu); - void OnInputLangChange(DWORD character_set, HKL input_language_id); - LRESULT OnKeyEvent(UINT message, WPARAM w_param, LPARAM l_param); - void OnKillFocus(HWND focused_window); - LRESULT OnMouseActivate(UINT message, WPARAM w_param, LPARAM l_param); - LRESULT OnMouseRange(UINT message, WPARAM w_param, LPARAM l_param); - void OnMove(const gfx::Point& point); - void OnMoving(UINT param, const RECT* new_bounds); - LRESULT OnNCActivate(UINT message, WPARAM w_param, LPARAM l_param); - LRESULT OnNCCalcSize(BOOL mode, LPARAM l_param); - LRESULT OnNCHitTest(const gfx::Point& point); - void OnNCPaint(HRGN rgn); - LRESULT OnNCUAHDrawCaption(UINT message, WPARAM w_param, LPARAM l_param); - LRESULT OnNCUAHDrawFrame(UINT message, WPARAM w_param, LPARAM l_param); - LRESULT OnNotify(int w_param, NMHDR* l_param); - void OnPaint(HDC dc); - LRESULT OnReflectedMessage(UINT message, WPARAM w_param, LPARAM l_param); - LRESULT OnScrollMessage(UINT message, WPARAM w_param, LPARAM l_param); - void OnSessionChange(WPARAM status_code, PWTSSESSION_NOTIFICATION session_id); - LRESULT OnSetCursor(UINT message, WPARAM w_param, LPARAM l_param); - void OnSetFocus(HWND last_focused_window); - LRESULT OnSetIcon(UINT size_type, HICON new_icon); - LRESULT OnSetText(const wchar_t* text); - void OnSettingChange(UINT flags, const wchar_t* section); - void OnSize(UINT param, const gfx::Size& size); - void OnSysCommand(UINT notification_code, const gfx::Point& point); - void OnThemeChanged(); - LRESULT OnTouchEvent(UINT message, WPARAM w_param, LPARAM l_param); - void OnWindowPosChanging(WINDOWPOS* window_pos); - void OnWindowPosChanged(WINDOWPOS* window_pos); - - typedef std::vector<ui::TouchEvent> TouchEvents; - // Helper to handle the list of touch events passed in. We need this because - // touch events on windows don't fire if we enter a modal loop in the context - // of a touch event. - void HandleTouchEvents(const TouchEvents& touch_events); - - // Resets the flag which indicates that we are in the context of a touch down - // event. - void ResetTouchDownContext(); - - // Helper to handle mouse events. - // The |message|, |w_param|, |l_param| parameters identify the Windows mouse - // message and its parameters respectively. - // The |track_mouse| parameter indicates if we should track the mouse. - LRESULT HandleMouseEventInternal(UINT message, - WPARAM w_param, - LPARAM l_param, - bool track_mouse); - - // Returns true if the mouse message passed in is an OS synthesized mouse - // message. - // |message| identifies the mouse message. - // |message_time| is the time when the message occurred. - // |l_param| indicates the location of the mouse message. - bool IsSynthesizedMouseMessage(unsigned int message, - int message_time, - LPARAM l_param); - - // Provides functionality to transition a frame to DWM. - void PerformDwmTransition(); - - HWNDMessageHandlerDelegate* delegate_; - - scoped_ptr<FullscreenHandler> fullscreen_handler_; - - // Set to true in Close() and false is CloseNow(). - bool waiting_for_close_now_; - - bool remove_standard_frame_; - - bool use_system_default_icon_; - - // Whether all ancestors have been enabled. This is only used if is_modal_ is - // true. - bool restored_enabled_; - - // The current cursor. - HCURSOR current_cursor_; - - // The last cursor that was active before the current one was selected. Saved - // so that we can restore it. - HCURSOR previous_cursor_; - - // Event handling ------------------------------------------------------------ - - // The flags currently being used with TrackMouseEvent to track mouse - // messages. 0 if there is no active tracking. The value of this member is - // used when tracking is canceled. - DWORD active_mouse_tracking_flags_; - - // Set to true when the user presses the right mouse button on the caption - // area. We need this so we can correctly show the context menu on mouse-up. - bool is_right_mouse_pressed_on_caption_; - - // The set of touch devices currently down. - TouchIDs touch_ids_; - - // ScopedRedrawLock ---------------------------------------------------------- - - // Represents the number of ScopedRedrawLocks active against this widget. - // If this is greater than zero, the widget should be locked against updates. - int lock_updates_count_; - - // Window resizing ----------------------------------------------------------- - - // When true, this flag makes us discard incoming SetWindowPos() requests that - // only change our position/size. (We still allow changes to Z-order, - // activation, etc.) - bool ignore_window_pos_changes_; - - // The last-seen monitor containing us, and its rect and work area. These are - // used to catch updates to the rect and work area and react accordingly. - HMONITOR last_monitor_; - gfx::Rect last_monitor_rect_, last_work_area_; - - // Layered windows ----------------------------------------------------------- - - // Should we keep an off-screen buffer? This is false by default, set to true - // when WS_EX_LAYERED is specified before the native window is created. - // - // NOTE: this is intended to be used with a layered window (a window with an - // extended window style of WS_EX_LAYERED). If you are using a layered window - // and NOT changing the layered alpha or anything else, then leave this value - // alone. OTOH if you are invoking SetLayeredWindowAttributes then you'll - // most likely want to set this to false, or after changing the alpha toggle - // the extended style bit to false than back to true. See MSDN for more - // details. - bool use_layered_buffer_; - - // The default alpha to be applied to the layered window. - BYTE layered_alpha_; - - // A canvas that contains the window contents in the case of a layered - // window. - scoped_ptr<gfx::Canvas> layered_window_contents_; - - // We must track the invalid rect ourselves, for two reasons: - // For layered windows, Windows will not do this properly with - // InvalidateRect()/GetUpdateRect(). (In fact, it'll return misleading - // information from GetUpdateRect()). - // We also need to keep track of the invalid rectangle for the RootView should - // we need to paint the non-client area. The data supplied to WM_NCPAINT seems - // to be insufficient. - gfx::Rect invalid_rect_; - - // Set to true when waiting for RedrawLayeredWindowContents(). - bool waiting_for_redraw_layered_window_contents_; - - // True the first time nccalc is called on a sizable widget - bool is_first_nccalc_; - - // Copy of custom window region specified via SetRegion(), if any. - base::win::ScopedRegion custom_window_region_; - - // If > 0 indicates a menu is running (we're showing a native menu). - int menu_depth_; - - // A factory used to lookup appbar autohide edges. - base::WeakPtrFactory<HWNDMessageHandler> autohide_factory_; - - // Generates touch-ids for touch-events. - ui::SequentialIDGenerator id_generator_; - - // Indicates if the window needs the WS_VSCROLL and WS_HSCROLL styles. - bool needs_scroll_styles_; - - // Set to true if we are in the context of a sizing operation. - bool in_size_loop_; - - // Stores a pointer to the WindowEventTarget interface implemented by this - // class. Allows callers to retrieve the interface pointer. - scoped_ptr<ui::ViewProp> prop_window_target_; - - // Number of active touch down contexts. This is incremented on touch down - // events and decremented later using a delayed task. - // We need this to ignore WM_MOUSEACTIVATE messages generated in response to - // touch input. This is fine because activation still works correctly via - // native SetFocus calls invoked in the views code. - int touch_down_contexts_; - - // Time the last touch message was received. Used to flag mouse messages - // synthesized by Windows for touch which are not flagged by the OS as - // synthesized mouse messages. For more information please refer to - // the IsMouseEventFromTouch function. - static long last_touch_message_time_; - - // Time the last WM_MOUSEHWHEEL message is received. Please refer to the - // HandleMouseEventInternal function as to why this is needed. - long last_mouse_hwheel_time_; - - // On Windows Vista and beyond, if we are transitioning from custom frame - // to Aero(glass) we delay setting the DWM related properties in full - // screen mode as DWM is not supported in full screen windows. We perform - // the DWM related operations when the window comes out of fullscreen mode. - // This member variable is set to true if the window is transitioning to - // glass. Defaults to false. - bool dwm_transition_desired_; - - DISALLOW_COPY_AND_ASSIGN(HWNDMessageHandler); -}; - -} // namespace views - -#endif // UI_VIEWS_WIN_HWND_MESSAGE_HANDLER_H_
diff --git a/ui/views/win/hwnd_message_handler_delegate.h b/ui/views/win/hwnd_message_handler_delegate.h deleted file mode 100644 index 9a2e688..0000000 --- a/ui/views/win/hwnd_message_handler_delegate.h +++ /dev/null
@@ -1,241 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_WIN_HWND_MESSAGE_HANDLER_DELEGATE_H_ -#define UI_VIEWS_WIN_HWND_MESSAGE_HANDLER_DELEGATE_H_ - -#include "ui/views/views_export.h" - -namespace gfx { -class Canvas; -class Insets; -class Path; -class Point; -class Size; -} - -namespace ui { -class Accelerator; -class KeyEvent; -class MouseEvent; -class TouchEvent; -} - -namespace views { - -class InputMethod; - -// Implemented by the object that uses the HWNDMessageHandler to handle -// notifications from the underlying HWND and service requests for data. -class VIEWS_EXPORT HWNDMessageHandlerDelegate { - public: - virtual bool IsWidgetWindow() const = 0; - - // TODO(beng): resolve this more satisfactorily vis-a-vis ShouldUseNativeFrame - // to avoid confusion. - virtual bool IsUsingCustomFrame() const = 0; - - virtual void SchedulePaint() = 0; - virtual void EnableInactiveRendering() = 0; - virtual bool IsInactiveRenderingDisabled() = 0; - - virtual bool CanResize() const = 0; - virtual bool CanMaximize() const = 0; - virtual bool CanMinimize() const = 0; - virtual bool CanActivate() const = 0; - - virtual bool WidgetSizeIsClientSize() const = 0; - - // Returns true if the delegate represents a modal window. - virtual bool IsModal() const = 0; - - // Returns the show state that should be used for the application's first - // window. - virtual int GetInitialShowState() const = 0; - - virtual bool WillProcessWorkAreaChange() const = 0; - - virtual int GetNonClientComponent(const gfx::Point& point) const = 0; - virtual void GetWindowMask(const gfx::Size& size, gfx::Path* mask) = 0; - - // Returns true if the delegate modifies |insets| to define a custom client - // area for the window, false if the default client area should be used. If - // false is returned, |insets| is not modified. - virtual bool GetClientAreaInsets(gfx::Insets* insets) const = 0; - - // Returns the minimum and maximum size the window can be resized to by the - // user. - virtual void GetMinMaxSize(gfx::Size* min_size, - gfx::Size* max_size) const = 0; - - // Returns the current size of the RootView. - virtual gfx::Size GetRootViewSize() const = 0; - - virtual void ResetWindowControls() = 0; - - virtual void PaintLayeredWindow(gfx::Canvas* canvas) = 0; - - virtual InputMethod* GetInputMethod() = 0; - - virtual gfx::NativeViewAccessible GetNativeViewAccessible() = 0; - - // Returns true if the window should handle standard system commands, such as - // close, minimize, maximize. - // TODO(benwells): Remove this once bubbles don't have two widgets - // implementing them on non-aura windows. http://crbug.com/189112. - virtual bool ShouldHandleSystemCommands() const = 0; - - // TODO(beng): Investigate migrating these methods to On* prefixes once - // HWNDMessageHandler is the WindowImpl. - - // Called when another app was activated. - virtual void HandleAppDeactivated() = 0; - - // Called when the window was activated or deactivated. |active| reflects the - // new state. - virtual void HandleActivationChanged(bool active) = 0; - - // Called when a well known "app command" from the system was performed. - // Returns true if the command was handled. - virtual bool HandleAppCommand(short command) = 0; - - // Called from WM_CANCELMODE. - virtual void HandleCancelMode() = 0; - - // Called when the window has lost mouse capture. - virtual void HandleCaptureLost() = 0; - - // Called when the user tried to close the window. - virtual void HandleClose() = 0; - - // Called when a command defined by the application was performed. Returns - // true if the command was handled. - virtual bool HandleCommand(int command) = 0; - - // Called when an accelerator is invoked. - virtual void HandleAccelerator(const ui::Accelerator& accelerator) = 0; - - // Called when the HWND is created. - virtual void HandleCreate() = 0; - - // Called when the HWND is being destroyed, before any child HWNDs are - // destroyed. - virtual void HandleDestroying() = 0; - - // Called after the HWND is destroyed, after all child HWNDs have been - // destroyed. - virtual void HandleDestroyed() = 0; - - // Called when the HWND is to be focused for the first time. This is called - // when the window is shown for the first time. Returns true if the delegate - // set focus and no default processing should be done by the message handler. - virtual bool HandleInitialFocus(ui::WindowShowState show_state) = 0; - - // Called when display settings are adjusted on the system. - virtual void HandleDisplayChange() = 0; - - // Called when the user begins or ends a size/move operation using the window - // manager. - virtual void HandleBeginWMSizeMove() = 0; - virtual void HandleEndWMSizeMove() = 0; - - // Called when the window's position changed. - virtual void HandleMove() = 0; - - // Called when the system's work area has changed. - virtual void HandleWorkAreaChanged() = 0; - - // Called when the window's visibility is changing. |visible| holds the new - // state. - virtual void HandleVisibilityChanging(bool visible) = 0; - - // Called when the window's visibility changed. |visible| holds the new state. - virtual void HandleVisibilityChanged(bool visible) = 0; - - // Called when the window's client size changed. |new_size| holds the new - // size. - virtual void HandleClientSizeChanged(const gfx::Size& new_size) = 0; - - // Called when the window's frame has changed. - virtual void HandleFrameChanged() = 0; - - // Called when focus shifted to this HWND from |last_focused_window|. - virtual void HandleNativeFocus(HWND last_focused_window) = 0; - - // Called when focus shifted from the HWND to a different window. - virtual void HandleNativeBlur(HWND focused_window) = 0; - - // Called when a mouse event is received. Returns true if the event was - // handled by the delegate. - virtual bool HandleMouseEvent(const ui::MouseEvent& event) = 0; - - // Called when a translated key event is received (i.e. post IME translation.) - // Returns true if the event was handled by the delegate. - virtual bool HandleKeyEvent(const ui::KeyEvent& event) = 0; - - // Called when an untranslated key event is received (i.e. pre-IME - // translation). Returns true if the event was sent to the input method. - virtual bool HandleUntranslatedKeyEvent(const ui::KeyEvent& event) = 0; - - // Called when a touch event is received. - virtual void HandleTouchEvent(const ui::TouchEvent& event) = 0; - - // Called when an IME message needs to be processed by the delegate. Returns - // true if the event was handled and no default processing should be - // performed. - virtual bool HandleIMEMessage(UINT message, - WPARAM w_param, - LPARAM l_param, - LRESULT* result) = 0; - - // Called when the system input language changes. - virtual void HandleInputLanguageChange(DWORD character_set, - HKL input_language_id) = 0; - - // Called to compel the delegate to paint |invalid_rect| accelerated. Returns - // true if accelerated painting was performed. - virtual bool HandlePaintAccelerated(const gfx::Rect& invalid_rect) = 0; - - // Called to compel the delegate to paint using the software path. - virtual void HandlePaint(gfx::Canvas* canvas) = 0; - - // Called to forward a WM_NOTIFY message to the tooltip manager. - virtual bool HandleTooltipNotify(int w_param, - NMHDR* l_param, - LRESULT* l_result) = 0; - - // Invoked on entering/exiting a menu loop. - virtual void HandleMenuLoop(bool in_menu_loop) = 0; - - // Catch-all message handling and filtering. Called before - // HWNDMessageHandler's built-in handling, which may pre-empt some - // expectations in Views/Aura if messages are consumed. Returns true if the - // message was consumed by the delegate and should not be processed further - // by the HWNDMessageHandler. In this case, |result| is returned. |result| is - // not modified otherwise. - virtual bool PreHandleMSG(UINT message, - WPARAM w_param, - LPARAM l_param, - LRESULT* result) = 0; - - // Like PreHandleMSG, but called after HWNDMessageHandler's built-in handling - // has run and after DefWindowProc. - virtual void PostHandleMSG(UINT message, - WPARAM w_param, - LPARAM l_param) = 0; - - // Called when a scroll event is received. Returns true if the event was - // handled by the delegate. - virtual bool HandleScrollEvent(const ui::ScrollEvent& event) = 0; - - // Called when the window size is about to change. - virtual void HandleWindowSizeChanging() = 0; - - protected: - virtual ~HWNDMessageHandlerDelegate() {} -}; - -} // namespace views - -#endif // UI_VIEWS_WIN_HWND_MESSAGE_HANDLER_DELEGATE_H_
diff --git a/ui/views/win/hwnd_util.h b/ui/views/win/hwnd_util.h deleted file mode 100644 index 7dfd9e3..0000000 --- a/ui/views/win/hwnd_util.h +++ /dev/null
@@ -1,33 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_WIN_HWND_UTIL_H_ -#define UI_VIEWS_WIN_HWND_UTIL_H_ - -#include "ui/gfx/native_widget_types.h" -#include "ui/gfx/rect.h" -#include "ui/views/views_export.h" - -namespace views { - -class View; -class Widget; - -// Returns the HWND for the specified View. -VIEWS_EXPORT HWND HWNDForView(const View* view); - -// Returns the HWND for the specified Widget. -VIEWS_EXPORT HWND HWNDForWidget(const Widget* widget); - -// Returns the HWND for the specified NativeView. -VIEWS_EXPORT HWND HWNDForNativeView(const gfx::NativeView view); - -// Returns the HWND for the specified NativeWindow. -VIEWS_EXPORT HWND HWNDForNativeWindow(const gfx::NativeWindow window); - -VIEWS_EXPORT gfx::Rect GetWindowBoundsForClientBounds( - View* view, const gfx::Rect& client_bounds); -} - -#endif // UI_VIEWS_WIN_HWND_UTIL_H_
diff --git a/ui/views/win/hwnd_util_aurawin.cc b/ui/views/win/hwnd_util_aurawin.cc deleted file mode 100644 index 37dca58..0000000 --- a/ui/views/win/hwnd_util_aurawin.cc +++ /dev/null
@@ -1,46 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/win/hwnd_util.h" - -#include "ui/aura/window.h" -#include "ui/aura/window_tree_host.h" -#include "ui/views/widget/widget.h" - -namespace views { - -HWND HWNDForView(const View* view) { - return view->GetWidget() ? HWNDForWidget(view->GetWidget()) : NULL; -} - -HWND HWNDForWidget(const Widget* widget) { - return HWNDForNativeWindow(widget->GetNativeWindow()); -} - -HWND HWNDForNativeView(const gfx::NativeView view) { - return view && view->GetRootWindow() ? - view->GetHost()->GetAcceleratedWidget() : NULL; -} - -HWND HWNDForNativeWindow(const gfx::NativeWindow window) { - return window && window->GetRootWindow() ? - window->GetHost()->GetAcceleratedWidget() : NULL; -} - -gfx::Rect GetWindowBoundsForClientBounds(View* view, - const gfx::Rect& client_bounds) { - DCHECK(view); - aura::WindowTreeHost* host = view->GetWidget()->GetNativeWindow()->GetHost(); - if (host) { - HWND hwnd = host->GetAcceleratedWidget(); - RECT rect = client_bounds.ToRECT(); - DWORD style = ::GetWindowLong(hwnd, GWL_STYLE); - DWORD ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); - AdjustWindowRectEx(&rect, style, FALSE, ex_style); - return gfx::Rect(rect); - } - return client_bounds; -} - -} // namespace views
diff --git a/ui/views/win/scoped_fullscreen_visibility.cc b/ui/views/win/scoped_fullscreen_visibility.cc deleted file mode 100644 index b6fd33f..0000000 --- a/ui/views/win/scoped_fullscreen_visibility.cc +++ /dev/null
@@ -1,53 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/win/scoped_fullscreen_visibility.h" - -#include "base/logging.h" - -namespace views { - -// static -std::map<HWND, int>* ScopedFullscreenVisibility::full_screen_windows_ = NULL; - -ScopedFullscreenVisibility::ScopedFullscreenVisibility(HWND hwnd) - : hwnd_(hwnd) { - if (!full_screen_windows_) - full_screen_windows_ = new FullscreenHWNDs; - FullscreenHWNDs::iterator it = full_screen_windows_->find(hwnd_); - if (it != full_screen_windows_->end()) { - it->second++; - } else { - full_screen_windows_->insert(std::make_pair(hwnd_, 1)); - // NOTE: Be careful not to activate any windows here (for example, calling - // ShowWindow(SW_HIDE) will automatically activate another window). This - // code can be called while a window is being deactivated, and activating - // another window will screw up the activation that is already in progress. - SetWindowPos(hwnd_, NULL, 0, 0, 0, 0, - SWP_HIDEWINDOW | SWP_NOACTIVATE | SWP_NOMOVE | - SWP_NOREPOSITION | SWP_NOSIZE | SWP_NOZORDER); - } -} - -ScopedFullscreenVisibility::~ScopedFullscreenVisibility() { - FullscreenHWNDs::iterator it = full_screen_windows_->find(hwnd_); - DCHECK(it != full_screen_windows_->end()); - if (--it->second == 0) { - full_screen_windows_->erase(it); - ShowWindow(hwnd_, SW_SHOW); - } - if (full_screen_windows_->empty()) { - delete full_screen_windows_; - full_screen_windows_ = NULL; - } -} - -// static -bool ScopedFullscreenVisibility::IsHiddenForFullscreen(HWND hwnd) { - if (!full_screen_windows_) - return false; - return full_screen_windows_->find(hwnd) != full_screen_windows_->end(); -} - -} // namespace views
diff --git a/ui/views/win/scoped_fullscreen_visibility.h b/ui/views/win/scoped_fullscreen_visibility.h deleted file mode 100644 index b78b800..0000000 --- a/ui/views/win/scoped_fullscreen_visibility.h +++ /dev/null
@@ -1,41 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_WIN_SCOPED_FULLSCREEN_VISIBILITY_H_ -#define UI_VIEWS_WIN_SCOPED_FULLSCREEN_VISIBILITY_H_ - -#include <windows.h> - -#include <map> - -#include "base/basictypes.h" -#include "ui/views/views_export.h" - -namespace views { - -// Scoping class that ensures a HWND remains hidden while it enters or leaves -// the fullscreen state. This reduces some flicker-jank that an application UI -// might suffer. -class VIEWS_EXPORT ScopedFullscreenVisibility { - public: - explicit ScopedFullscreenVisibility(HWND hwnd); - ~ScopedFullscreenVisibility(); - - // Returns true if |hwnd| is currently hidden due to instance(s) of this - // class. - static bool IsHiddenForFullscreen(HWND hwnd); - - private: - typedef std::map<HWND, int> FullscreenHWNDs; - - HWND hwnd_; - - static FullscreenHWNDs* full_screen_windows_; - - DISALLOW_COPY_AND_ASSIGN(ScopedFullscreenVisibility); -}; - -} // namespace views - -#endif // UI_VIEWS_WIN_SCOPED_FULLSCREEN_VISIBILITY_H_
diff --git a/ui/views/window/client_view.cc b/ui/views/window/client_view.cc deleted file mode 100644 index fb7d89f..0000000 --- a/ui/views/window/client_view.cc +++ /dev/null
@@ -1,98 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/window/client_view.h" - -#include "base/logging.h" -#include "ui/accessibility/ax_view_state.h" -#include "ui/base/hit_test.h" -#include "ui/views/widget/widget.h" -#include "ui/views/widget/widget_delegate.h" - -namespace views { - -// static -const char ClientView::kViewClassName[] = - "ui/views/window/ClientView"; - -/////////////////////////////////////////////////////////////////////////////// -// ClientView, public: - -ClientView::ClientView(Widget* widget, View* contents_view) - : contents_view_(contents_view) { -} - -int ClientView::NonClientHitTest(const gfx::Point& point) { - return bounds().Contains(point) ? HTCLIENT : HTNOWHERE; -} - -DialogClientView* ClientView::AsDialogClientView() { - return NULL; -} - -const DialogClientView* ClientView::AsDialogClientView() const { - return NULL; -} - -bool ClientView::CanClose() { - return true; -} - -void ClientView::WidgetClosing() { -} - -/////////////////////////////////////////////////////////////////////////////// -// ClientView, View overrides: - -gfx::Size ClientView::GetPreferredSize() const { - // |contents_view_| is allowed to be NULL up until the point where this view - // is attached to a Container. - return contents_view_ ? contents_view_->GetPreferredSize() : gfx::Size(); -} - -gfx::Size ClientView::GetMaximumSize() const { - // |contents_view_| is allowed to be NULL up until the point where this view - // is attached to a Container. - return contents_view_ ? contents_view_->GetMaximumSize() : gfx::Size(); -} - -gfx::Size ClientView::GetMinimumSize() const { - // |contents_view_| is allowed to be NULL up until the point where this view - // is attached to a Container. - return contents_view_ ? contents_view_->GetMinimumSize() : gfx::Size(); -} - -void ClientView::Layout() { - // |contents_view_| is allowed to be NULL up until the point where this view - // is attached to a Container. - if (contents_view_) - contents_view_->SetBounds(0, 0, width(), height()); -} - -const char* ClientView::GetClassName() const { - return kViewClassName; -} - -void ClientView::GetAccessibleState(ui::AXViewState* state) { - state->role = ui::AX_ROLE_CLIENT; -} - -void ClientView::OnBoundsChanged(const gfx::Rect& previous_bounds) { - // Overridden to do nothing. The NonClientView manually calls Layout on the - // ClientView when it is itself laid out, see comment in - // NonClientView::Layout. -} - -void ClientView::ViewHierarchyChanged( - const ViewHierarchyChangedDetails& details) { - if (details.is_add && details.child == this) { - DCHECK(GetWidget()); - DCHECK(contents_view_); // |contents_view_| must be valid now! - // Insert |contents_view_| at index 0 so it is first in the focus chain. - // (the OK/Cancel buttons are inserted before contents_view_) - AddChildViewAt(contents_view_, 0); - } -} - -} // namespace views
diff --git a/ui/views/window/client_view.h b/ui/views/window/client_view.h deleted file mode 100644 index 53d393b..0000000 --- a/ui/views/window/client_view.h +++ /dev/null
@@ -1,86 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_WINDOW_CLIENT_VIEW_H_ -#define UI_VIEWS_WINDOW_CLIENT_VIEW_H_ - -#include "ui/views/view.h" - -namespace views { - -class DialogClientView; -class Widget; - -/////////////////////////////////////////////////////////////////////////////// -// ClientView -// -// A ClientView is a View subclass that is used to occupy the "client area" -// of a widget. It provides basic information to the widget that contains it -// such as non-client hit testing information, sizing etc. Sub-classes of -// ClientView are used to create more elaborate contents, e.g. -// "DialogClientView". -class VIEWS_EXPORT ClientView : public View { - public: - // Internal class name - static const char kViewClassName[]; - - // Constructs a ClientView object for the specified widget with the specified - // contents. Since this object is created during the process of creating - // |widget|, |contents_view| must be valid if you want the initial size of - // the widget to be based on |contents_view|'s preferred size. - ClientView(Widget* widget, View* contents_view); - virtual ~ClientView() {} - - // Manual RTTI ftw. - virtual DialogClientView* AsDialogClientView(); - virtual const DialogClientView* AsDialogClientView() const; - - // Returns true to signal that the Widget can be closed. Specialized - // ClientView subclasses can override this default behavior to allow the - // close to be blocked until the user corrects mistakes, accepts a warning - // dialog, etc. - virtual bool CanClose(); - - // Notification that the widget is closing. - virtual void WidgetClosing(); - - // Tests to see if the specified point (in view coordinates) is within the - // bounds of this view. If so, it returns HTCLIENT in this default - // implementation. If it is outside the bounds of this view, this must return - // HTNOWHERE to tell the caller to do further processing to determine where - // in the non-client area it is (if it is). - // Subclasses of ClientView can extend this logic by overriding this method - // to detect if regions within the client area count as parts of the "non- - // client" area. A good example of this is the size box at the bottom right - // corner of resizable dialog boxes. - virtual int NonClientHitTest(const gfx::Point& point); - - // Overridden from View: - virtual gfx::Size GetPreferredSize() const override; - virtual gfx::Size GetMinimumSize() const override; - virtual gfx::Size GetMaximumSize() const override; - virtual void Layout() override; - virtual const char* GetClassName() const override; - - protected: - // Overridden from View: - virtual void GetAccessibleState(ui::AXViewState* state) override; - virtual void OnBoundsChanged(const gfx::Rect& previous_bounds) override; - virtual void ViewHierarchyChanged( - const ViewHierarchyChangedDetails& details) override; - - // Accessors for private data members. - View* contents_view() const { return contents_view_; } - void set_contents_view(View* contents_view) { - contents_view_ = contents_view; - } - - private: - // The View that this ClientView contains. - View* contents_view_; -}; - -} // namespace views - -#endif // UI_VIEWS_WINDOW_CLIENT_VIEW_H_
diff --git a/ui/views/window/custom_frame_view.cc b/ui/views/window/custom_frame_view.cc deleted file mode 100644 index dcc3e69..0000000 --- a/ui/views/window/custom_frame_view.cc +++ /dev/null
@@ -1,632 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/window/custom_frame_view.h" - -#include <algorithm> -#include <vector> - -#include "base/strings/utf_string_conversions.h" -#include "ui/base/hit_test.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/font.h" -#include "ui/gfx/image/image.h" -#include "ui/gfx/path.h" -#include "ui/gfx/rect.h" -#include "ui/resources/grit/ui_resources.h" -#include "ui/strings/grit/ui_strings.h" -#include "ui/views/color_constants.h" -#include "ui/views/controls/button/image_button.h" -#include "ui/views/views_delegate.h" -#include "ui/views/widget/native_widget_private.h" -#include "ui/views/widget/widget.h" -#include "ui/views/widget/widget_delegate.h" -#include "ui/views/window/client_view.h" -#include "ui/views/window/frame_background.h" -#include "ui/views/window/window_button_order_provider.h" -#include "ui/views/window/window_resources.h" -#include "ui/views/window/window_shape.h" - -namespace views { - -namespace { - -// The frame border is only visible in restored mode and is hardcoded to 4 px on -// each side regardless of the system window border size. -const int kFrameBorderThickness = 4; -// In the window corners, the resize areas don't actually expand bigger, but the -// 16 px at the end of each edge triggers diagonal resizing. -const int kResizeAreaCornerSize = 16; -// The titlebar never shrinks too short to show the caption button plus some -// padding below it. -const int kCaptionButtonHeightWithPadding = 19; -// The titlebar has a 2 px 3D edge along the top and bottom. -const int kTitlebarTopAndBottomEdgeThickness = 2; -// The icon is inset 2 px from the left frame border. -const int kIconLeftSpacing = 2; -// The icon never shrinks below 16 px on a side. -const int kIconMinimumSize = 16; -// The space between the window icon and the title text. -const int kTitleIconOffsetX = 4; -// The space between the title text and the caption buttons. -const int kTitleCaptionSpacing = 5; - -#if defined(OS_CHROMEOS) -// Chrome OS uses a dark gray. -const SkColor kDefaultColorFrame = SkColorSetRGB(109, 109, 109); -const SkColor kDefaultColorFrameInactive = SkColorSetRGB(176, 176, 176); -#else -// Windows and Linux use a blue. -const SkColor kDefaultColorFrame = SkColorSetRGB(66, 116, 201); -const SkColor kDefaultColorFrameInactive = SkColorSetRGB(161, 182, 228); -#endif - -const gfx::FontList& GetTitleFontList() { - static const gfx::FontList title_font_list = - internal::NativeWidgetPrivate::GetWindowTitleFontList(); - return title_font_list; -} - -void LayoutButton(ImageButton* button, const gfx::Rect& bounds) { - button->SetVisible(true); - button->SetImageAlignment(ImageButton::ALIGN_LEFT, - ImageButton::ALIGN_BOTTOM); - button->SetBoundsRect(bounds); -} - -} // namespace - -/////////////////////////////////////////////////////////////////////////////// -// CustomFrameView, public: - -CustomFrameView::CustomFrameView() - : frame_(NULL), - window_icon_(NULL), - minimize_button_(NULL), - maximize_button_(NULL), - restore_button_(NULL), - close_button_(NULL), - frame_background_(new FrameBackground()), - minimum_title_bar_x_(0), - maximum_title_bar_x_(-1) { -} - -CustomFrameView::~CustomFrameView() { -} - -void CustomFrameView::Init(Widget* frame) { - frame_ = frame; - - close_button_ = InitWindowCaptionButton(IDS_APP_ACCNAME_CLOSE, - IDR_CLOSE, IDR_CLOSE_H, IDR_CLOSE_P); - minimize_button_ = InitWindowCaptionButton(IDS_APP_ACCNAME_MINIMIZE, - IDR_MINIMIZE, IDR_MINIMIZE_H, IDR_MINIMIZE_P); - maximize_button_ = InitWindowCaptionButton(IDS_APP_ACCNAME_MAXIMIZE, - IDR_MAXIMIZE, IDR_MAXIMIZE_H, IDR_MAXIMIZE_P); - restore_button_ = InitWindowCaptionButton(IDS_APP_ACCNAME_RESTORE, - IDR_RESTORE, IDR_RESTORE_H, IDR_RESTORE_P); - - if (frame_->widget_delegate()->ShouldShowWindowIcon()) { - window_icon_ = new ImageButton(this); - AddChildView(window_icon_); - } -} - -/////////////////////////////////////////////////////////////////////////////// -// CustomFrameView, NonClientFrameView implementation: - -gfx::Rect CustomFrameView::GetBoundsForClientView() const { - return client_view_bounds_; -} - -gfx::Rect CustomFrameView::GetWindowBoundsForClientBounds( - const gfx::Rect& client_bounds) const { - int top_height = NonClientTopBorderHeight(); - int border_thickness = NonClientBorderThickness(); - return gfx::Rect(client_bounds.x() - border_thickness, - client_bounds.y() - top_height, - client_bounds.width() + (2 * border_thickness), - client_bounds.height() + top_height + border_thickness); -} - -int CustomFrameView::NonClientHitTest(const gfx::Point& point) { - // Sanity check. - if (!bounds().Contains(point)) - return HTNOWHERE; - - int frame_component = frame_->client_view()->NonClientHitTest(point); - - // See if we're in the sysmenu region. (We check the ClientView first to be - // consistent with OpaqueBrowserFrameView; it's not really necessary here.) - gfx::Rect sysmenu_rect(IconBounds()); - // In maximized mode we extend the rect to the screen corner to take advantage - // of Fitts' Law. - if (frame_->IsMaximized()) - sysmenu_rect.SetRect(0, 0, sysmenu_rect.right(), sysmenu_rect.bottom()); - sysmenu_rect.set_x(GetMirroredXForRect(sysmenu_rect)); - if (sysmenu_rect.Contains(point)) - return (frame_component == HTCLIENT) ? HTCLIENT : HTSYSMENU; - - if (frame_component != HTNOWHERE) - return frame_component; - - // Then see if the point is within any of the window controls. - if (close_button_->GetMirroredBounds().Contains(point)) - return HTCLOSE; - if (restore_button_->GetMirroredBounds().Contains(point)) - return HTMAXBUTTON; - if (maximize_button_->GetMirroredBounds().Contains(point)) - return HTMAXBUTTON; - if (minimize_button_->GetMirroredBounds().Contains(point)) - return HTMINBUTTON; - if (window_icon_ && window_icon_->GetMirroredBounds().Contains(point)) - return HTSYSMENU; - - int window_component = GetHTComponentForFrame(point, FrameBorderThickness(), - NonClientBorderThickness(), kResizeAreaCornerSize, kResizeAreaCornerSize, - frame_->widget_delegate()->CanResize()); - // Fall back to the caption if no other component matches. - return (window_component == HTNOWHERE) ? HTCAPTION : window_component; -} - -void CustomFrameView::GetWindowMask(const gfx::Size& size, - gfx::Path* window_mask) { - DCHECK(window_mask); - if (frame_->IsMaximized() || !ShouldShowTitleBarAndBorder()) - return; - - GetDefaultWindowMask(size, window_mask); -} - -void CustomFrameView::ResetWindowControls() { - restore_button_->SetState(CustomButton::STATE_NORMAL); - minimize_button_->SetState(CustomButton::STATE_NORMAL); - maximize_button_->SetState(CustomButton::STATE_NORMAL); - // The close button isn't affected by this constraint. -} - -void CustomFrameView::UpdateWindowIcon() { - if (window_icon_) - window_icon_->SchedulePaint(); -} - -void CustomFrameView::UpdateWindowTitle() { - if (frame_->widget_delegate()->ShouldShowWindowTitle()) - SchedulePaintInRect(title_bounds_); -} - -void CustomFrameView::SizeConstraintsChanged() { - ResetWindowControls(); - LayoutWindowControls(); -} - -/////////////////////////////////////////////////////////////////////////////// -// CustomFrameView, View overrides: - -void CustomFrameView::OnPaint(gfx::Canvas* canvas) { - if (!ShouldShowTitleBarAndBorder()) - return; - - if (frame_->IsMaximized()) - PaintMaximizedFrameBorder(canvas); - else - PaintRestoredFrameBorder(canvas); - PaintTitleBar(canvas); - if (ShouldShowClientEdge()) - PaintRestoredClientEdge(canvas); -} - -void CustomFrameView::Layout() { - if (ShouldShowTitleBarAndBorder()) { - LayoutWindowControls(); - LayoutTitleBar(); - } - - LayoutClientView(); -} - -gfx::Size CustomFrameView::GetPreferredSize() const { - return frame_->non_client_view()->GetWindowBoundsForClientBounds( - gfx::Rect(frame_->client_view()->GetPreferredSize())).size(); -} - -gfx::Size CustomFrameView::GetMinimumSize() const { - return frame_->non_client_view()->GetWindowBoundsForClientBounds( - gfx::Rect(frame_->client_view()->GetMinimumSize())).size(); -} - -gfx::Size CustomFrameView::GetMaximumSize() const { - gfx::Size max_size = frame_->client_view()->GetMaximumSize(); - gfx::Size converted_size = - frame_->non_client_view()->GetWindowBoundsForClientBounds( - gfx::Rect(max_size)).size(); - return gfx::Size(max_size.width() == 0 ? 0 : converted_size.width(), - max_size.height() == 0 ? 0 : converted_size.height()); -} - -/////////////////////////////////////////////////////////////////////////////// -// CustomFrameView, ButtonListener implementation: - -void CustomFrameView::ButtonPressed(Button* sender, const ui::Event& event) { - if (sender == close_button_) - frame_->Close(); - else if (sender == minimize_button_) - frame_->Minimize(); - else if (sender == maximize_button_) - frame_->Maximize(); - else if (sender == restore_button_) - frame_->Restore(); -} - -/////////////////////////////////////////////////////////////////////////////// -// CustomFrameView, private: - -int CustomFrameView::FrameBorderThickness() const { - return frame_->IsMaximized() ? 0 : kFrameBorderThickness; -} - -int CustomFrameView::NonClientBorderThickness() const { - // In maximized mode, we don't show a client edge. - return FrameBorderThickness() + - (ShouldShowClientEdge() ? kClientEdgeThickness : 0); -} - -int CustomFrameView::NonClientTopBorderHeight() const { - return std::max(FrameBorderThickness() + IconSize(), - CaptionButtonY() + kCaptionButtonHeightWithPadding) + - TitlebarBottomThickness(); -} - -int CustomFrameView::CaptionButtonY() const { - // Maximized buttons start at window top so that even if their images aren't - // drawn flush with the screen edge, they still obey Fitts' Law. -#if defined(OS_LINUX) && !defined(OS_CHROMEOS) - return FrameBorderThickness(); -#else - return frame_->IsMaximized() ? FrameBorderThickness() : kFrameShadowThickness; -#endif -} - -int CustomFrameView::TitlebarBottomThickness() const { - return kTitlebarTopAndBottomEdgeThickness + - (ShouldShowClientEdge() ? kClientEdgeThickness : 0); -} - -int CustomFrameView::IconSize() const { -#if defined(OS_WIN) - // This metric scales up if either the titlebar height or the titlebar font - // size are increased. - return GetSystemMetrics(SM_CYSMICON); -#else - return std::max(GetTitleFontList().GetHeight(), kIconMinimumSize); -#endif -} - -gfx::Rect CustomFrameView::IconBounds() const { - int size = IconSize(); - int frame_thickness = FrameBorderThickness(); - // Our frame border has a different "3D look" than Windows'. Theirs has a - // more complex gradient on the top that they push their icon/title below; - // then the maximized window cuts this off and the icon/title are centered - // in the remaining space. Because the apparent shape of our border is - // simpler, using the same positioning makes things look slightly uncentered - // with restored windows, so when the window is restored, instead of - // calculating the remaining space from below the frame border, we calculate - // from below the 3D edge. - int unavailable_px_at_top = frame_->IsMaximized() ? - frame_thickness : kTitlebarTopAndBottomEdgeThickness; - // When the icon is shorter than the minimum space we reserve for the caption - // button, we vertically center it. We want to bias rounding to put extra - // space above the icon, since the 3D edge (+ client edge, for restored - // windows) below looks (to the eye) more like additional space than does the - // 3D edge (or nothing at all, for maximized windows) above; hence the +1. - int y = unavailable_px_at_top + (NonClientTopBorderHeight() - - unavailable_px_at_top - size - TitlebarBottomThickness() + 1) / 2; - return gfx::Rect(frame_thickness + kIconLeftSpacing + minimum_title_bar_x_, - y, size, size); -} - -bool CustomFrameView::ShouldShowTitleBarAndBorder() const { - if (frame_->IsFullscreen()) - return false; - - if (ViewsDelegate::views_delegate) { - return !ViewsDelegate::views_delegate->WindowManagerProvidesTitleBar( - frame_->IsMaximized()); - } - - return true; -} - -bool CustomFrameView::ShouldShowClientEdge() const { - return !frame_->IsMaximized() && ShouldShowTitleBarAndBorder(); -} - -void CustomFrameView::PaintRestoredFrameBorder(gfx::Canvas* canvas) { - frame_background_->set_frame_color(GetFrameColor()); - const gfx::ImageSkia* frame_image = GetFrameImage(); - frame_background_->set_theme_image(frame_image); - frame_background_->set_top_area_height(frame_image->height()); - - ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); - - frame_background_->SetCornerImages( - rb.GetImageNamed(IDR_WINDOW_TOP_LEFT_CORNER).ToImageSkia(), - rb.GetImageNamed(IDR_WINDOW_TOP_RIGHT_CORNER).ToImageSkia(), - rb.GetImageNamed(IDR_WINDOW_BOTTOM_LEFT_CORNER).ToImageSkia(), - rb.GetImageNamed(IDR_WINDOW_BOTTOM_RIGHT_CORNER).ToImageSkia()); - frame_background_->SetSideImages( - rb.GetImageNamed(IDR_WINDOW_LEFT_SIDE).ToImageSkia(), - rb.GetImageNamed(IDR_WINDOW_TOP_CENTER).ToImageSkia(), - rb.GetImageNamed(IDR_WINDOW_RIGHT_SIDE).ToImageSkia(), - rb.GetImageNamed(IDR_WINDOW_BOTTOM_CENTER).ToImageSkia()); - - frame_background_->PaintRestored(canvas, this); -} - -void CustomFrameView::PaintMaximizedFrameBorder(gfx::Canvas* canvas) { - const gfx::ImageSkia* frame_image = GetFrameImage(); - frame_background_->set_theme_image(frame_image); - frame_background_->set_top_area_height(frame_image->height()); - frame_background_->PaintMaximized(canvas, this); - - ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); - - // TODO(jamescook): Migrate this into FrameBackground. - // The bottom of the titlebar actually comes from the top of the Client Edge - // graphic, with the actual client edge clipped off the bottom. - const gfx::ImageSkia* titlebar_bottom = rb.GetImageNamed( - IDR_APP_TOP_CENTER).ToImageSkia(); - int edge_height = titlebar_bottom->height() - - (ShouldShowClientEdge() ? kClientEdgeThickness : 0); - canvas->TileImageInt(*titlebar_bottom, 0, - frame_->client_view()->y() - edge_height, width(), edge_height); -} - -void CustomFrameView::PaintTitleBar(gfx::Canvas* canvas) { - WidgetDelegate* delegate = frame_->widget_delegate(); - - // It seems like in some conditions we can be asked to paint after the window - // that contains us is WM_DESTROYed. At this point, our delegate is NULL. The - // correct long term fix may be to shut down the RootView in WM_DESTROY. - if (!delegate || !delegate->ShouldShowWindowTitle()) - return; - - gfx::Rect rect = title_bounds_; - rect.set_x(GetMirroredXForRect(title_bounds_)); - canvas->DrawStringRect(delegate->GetWindowTitle(), GetTitleFontList(), - SK_ColorWHITE, rect); -} - -void CustomFrameView::PaintRestoredClientEdge(gfx::Canvas* canvas) { - gfx::Rect client_area_bounds = frame_->client_view()->bounds(); - // The shadows have a 1 pixel gap on the inside, so draw them 1 pixel inwards. - gfx::Rect shadowed_area_bounds = client_area_bounds; - shadowed_area_bounds.Inset(gfx::Insets(1, 1, 1, 1)); - int shadowed_area_top = shadowed_area_bounds.y(); - - ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); - - // Top: left, center, right sides. - const gfx::ImageSkia* top_left = rb.GetImageSkiaNamed(IDR_APP_TOP_LEFT); - const gfx::ImageSkia* top_center = rb.GetImageSkiaNamed(IDR_APP_TOP_CENTER); - const gfx::ImageSkia* top_right = rb.GetImageSkiaNamed(IDR_APP_TOP_RIGHT); - int top_edge_y = shadowed_area_top - top_center->height(); - canvas->DrawImageInt(*top_left, - shadowed_area_bounds.x() - top_left->width(), - top_edge_y); - canvas->TileImageInt(*top_center, - shadowed_area_bounds.x(), - top_edge_y, - shadowed_area_bounds.width(), - top_center->height()); - canvas->DrawImageInt(*top_right, shadowed_area_bounds.right(), top_edge_y); - - // Right side. - const gfx::ImageSkia* right = rb.GetImageSkiaNamed(IDR_CONTENT_RIGHT_SIDE); - int shadowed_area_bottom = - std::max(shadowed_area_top, shadowed_area_bounds.bottom()); - int shadowed_area_height = shadowed_area_bottom - shadowed_area_top; - canvas->TileImageInt(*right, - shadowed_area_bounds.right(), - shadowed_area_top, - right->width(), - shadowed_area_height); - - // Bottom: left, center, right sides. - const gfx::ImageSkia* bottom_left = - rb.GetImageSkiaNamed(IDR_CONTENT_BOTTOM_LEFT_CORNER); - const gfx::ImageSkia* bottom_center = - rb.GetImageSkiaNamed(IDR_CONTENT_BOTTOM_CENTER); - const gfx::ImageSkia* bottom_right = - rb.GetImageSkiaNamed(IDR_CONTENT_BOTTOM_RIGHT_CORNER); - - canvas->DrawImageInt(*bottom_left, - shadowed_area_bounds.x() - bottom_left->width(), - shadowed_area_bottom); - - canvas->TileImageInt(*bottom_center, - shadowed_area_bounds.x(), - shadowed_area_bottom, - shadowed_area_bounds.width(), - bottom_right->height()); - - canvas->DrawImageInt(*bottom_right, - shadowed_area_bounds.right(), - shadowed_area_bottom); - // Left side. - const gfx::ImageSkia* left = rb.GetImageSkiaNamed(IDR_CONTENT_LEFT_SIDE); - canvas->TileImageInt(*left, - shadowed_area_bounds.x() - left->width(), - shadowed_area_top, - left->width(), - shadowed_area_height); -} - -SkColor CustomFrameView::GetFrameColor() const { - return frame_->IsActive() ? kDefaultColorFrame : kDefaultColorFrameInactive; -} - -const gfx::ImageSkia* CustomFrameView::GetFrameImage() const { - return ui::ResourceBundle::GetSharedInstance().GetImageNamed( - frame_->IsActive() ? IDR_FRAME : IDR_FRAME_INACTIVE).ToImageSkia(); -} - -void CustomFrameView::LayoutWindowControls() { - minimum_title_bar_x_ = 0; - maximum_title_bar_x_ = width(); - - if (bounds().IsEmpty()) - return; - - int caption_y = CaptionButtonY(); - bool is_maximized = frame_->IsMaximized(); - // There should always be the same number of non-shadow pixels visible to the - // side of the caption buttons. In maximized mode we extend the edge button - // to the screen corner to obey Fitts' Law. - int extra_width = is_maximized ? - (kFrameBorderThickness - kFrameShadowThickness) : 0; - int next_button_x = FrameBorderThickness(); - - bool is_restored = !is_maximized && !frame_->IsMinimized(); - ImageButton* invisible_button = is_restored ? restore_button_ - : maximize_button_; - invisible_button->SetVisible(false); - - WindowButtonOrderProvider* button_order = - WindowButtonOrderProvider::GetInstance(); - const std::vector<views::FrameButton>& leading_buttons = - button_order->leading_buttons(); - const std::vector<views::FrameButton>& trailing_buttons = - button_order->trailing_buttons(); - - ImageButton* button = NULL; - for (std::vector<views::FrameButton>::const_iterator it = - leading_buttons.begin(); it != leading_buttons.end(); ++it) { - button = GetImageButton(*it); - if (!button) - continue; - gfx::Rect target_bounds(gfx::Point(next_button_x, caption_y), - button->GetPreferredSize()); - if (it == leading_buttons.begin()) - target_bounds.set_width(target_bounds.width() + extra_width); - LayoutButton(button, target_bounds); - next_button_x += button->width(); - minimum_title_bar_x_ = std::min(width(), next_button_x); - } - - // Trailing buttions are laid out in a RTL fashion - next_button_x = width() - FrameBorderThickness(); - for (std::vector<views::FrameButton>::const_reverse_iterator it = - trailing_buttons.rbegin(); it != trailing_buttons.rend(); ++it) { - button = GetImageButton(*it); - if (!button) - continue; - gfx::Rect target_bounds(gfx::Point(next_button_x, caption_y), - button->GetPreferredSize()); - if (it == trailing_buttons.rbegin()) - target_bounds.set_width(target_bounds.width() + extra_width); - target_bounds.Offset(-target_bounds.width(), 0); - LayoutButton(button, target_bounds); - next_button_x = button->x(); - maximum_title_bar_x_ = std::max(minimum_title_bar_x_, next_button_x); - } -} - -void CustomFrameView::LayoutTitleBar() { - DCHECK_GE(maximum_title_bar_x_, 0); - // The window title position is calculated based on the icon position, even - // when there is no icon. - gfx::Rect icon_bounds(IconBounds()); - bool show_window_icon = window_icon_ != NULL; - if (show_window_icon) - window_icon_->SetBoundsRect(icon_bounds); - - if (!frame_->widget_delegate()->ShouldShowWindowTitle()) - return; - - // The offset between the window left edge and the title text. - int title_x = show_window_icon ? icon_bounds.right() + kTitleIconOffsetX - : icon_bounds.x(); - int title_height = GetTitleFontList().GetHeight(); - // We bias the title position so that when the difference between the icon and - // title heights is odd, the extra pixel of the title is above the vertical - // midline rather than below. This compensates for how the icon is already - // biased downwards (see IconBounds()) and helps prevent descenders on the - // title from overlapping the 3D edge at the bottom of the titlebar. - title_bounds_.SetRect(title_x, - icon_bounds.y() + ((icon_bounds.height() - title_height - 1) / 2), - std::max(0, maximum_title_bar_x_ - kTitleCaptionSpacing - - title_x), title_height); -} - -void CustomFrameView::LayoutClientView() { - if (!ShouldShowTitleBarAndBorder()) { - client_view_bounds_ = bounds(); - return; - } - - int top_height = NonClientTopBorderHeight(); - int border_thickness = NonClientBorderThickness(); - client_view_bounds_.SetRect(border_thickness, top_height, - std::max(0, width() - (2 * border_thickness)), - std::max(0, height() - top_height - border_thickness)); -} - -ImageButton* CustomFrameView::InitWindowCaptionButton( - int accessibility_string_id, - int normal_image_id, - int hot_image_id, - int pushed_image_id) { - ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); - ImageButton* button = new ImageButton(this); - button->SetAccessibleName(l10n_util::GetStringUTF16(accessibility_string_id)); - button->SetImage(CustomButton::STATE_NORMAL, - rb.GetImageNamed(normal_image_id).ToImageSkia()); - button->SetImage(CustomButton::STATE_HOVERED, - rb.GetImageNamed(hot_image_id).ToImageSkia()); - button->SetImage(CustomButton::STATE_PRESSED, - rb.GetImageNamed(pushed_image_id).ToImageSkia()); - AddChildView(button); - return button; -} - -ImageButton* CustomFrameView::GetImageButton(views::FrameButton frame_button) { - ImageButton* button = NULL; - switch (frame_button) { - case views::FRAME_BUTTON_MINIMIZE: { - button = minimize_button_; - // If we should not show the minimize button, then we return NULL as we - // don't want this button to become visible and to be laid out. - bool should_show = frame_->widget_delegate()->CanMinimize(); - button->SetVisible(should_show); - if (!should_show) - return NULL; - - break; - } - case views::FRAME_BUTTON_MAXIMIZE: { - bool is_restored = !frame_->IsMaximized() && !frame_->IsMinimized(); - button = is_restored ? maximize_button_ : restore_button_; - // If we should not show the maximize/restore button, then we return - // NULL as we don't want this button to become visible and to be laid - // out. - bool should_show = frame_->widget_delegate()->CanMaximize(); - button->SetVisible(should_show); - if (!should_show) - return NULL; - - break; - } - case views::FRAME_BUTTON_CLOSE: { - button = close_button_; - break; - } - } - return button; -} - -} // namespace views
diff --git a/ui/views/window/custom_frame_view.h b/ui/views/window/custom_frame_view.h deleted file mode 100644 index a09dd33..0000000 --- a/ui/views/window/custom_frame_view.h +++ /dev/null
@@ -1,163 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_WINDOW_CUSTOM_FRAME_VIEW_H_ -#define UI_VIEWS_WINDOW_CUSTOM_FRAME_VIEW_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "ui/views/controls/button/button.h" -#include "ui/views/window/frame_buttons.h" -#include "ui/views/window/non_client_view.h" - -namespace gfx { -class ImageSkia; -} - -namespace views { - -class FrameBackground; -class ImageButton; -class Widget; - -/////////////////////////////////////////////////////////////////////////////// -// -// CustomFrameView -// -// A view that provides the non client frame for Windows. This means -// rendering the non-standard window caption, border, and controls. -// -//////////////////////////////////////////////////////////////////////////////// -class VIEWS_EXPORT CustomFrameView : public NonClientFrameView, - public ButtonListener { - public: - CustomFrameView(); - virtual ~CustomFrameView(); - - void Init(Widget* frame); - - // Overridden from NonClientFrameView: - virtual gfx::Rect GetBoundsForClientView() const override; - virtual gfx::Rect GetWindowBoundsForClientBounds( - const gfx::Rect& client_bounds) const override; - virtual int NonClientHitTest(const gfx::Point& point) override; - virtual void GetWindowMask(const gfx::Size& size, - gfx::Path* window_mask) override; - virtual void ResetWindowControls() override; - virtual void UpdateWindowIcon() override; - virtual void UpdateWindowTitle() override; - virtual void SizeConstraintsChanged() override; - - // Overridden from View: - virtual void OnPaint(gfx::Canvas* canvas) override; - virtual void Layout() override; - virtual gfx::Size GetPreferredSize() const override; - virtual gfx::Size GetMinimumSize() const override; - virtual gfx::Size GetMaximumSize() const override; - - // Overridden from ButtonListener: - virtual void ButtonPressed(Button* sender, const ui::Event& event) override; - - private: - friend class CustomFrameViewTest; - - // Returns the thickness of the border that makes up the window frame edges. - // This does not include any client edge. - int FrameBorderThickness() const; - - // Returns the thickness of the entire nonclient left, right, and bottom - // borders, including both the window frame and any client edge. - int NonClientBorderThickness() const; - - // Returns the height of the entire nonclient top border, including the window - // frame, any title area, and any connected client edge. - int NonClientTopBorderHeight() const; - - // Returns the y-coordinate of the caption buttons. - int CaptionButtonY() const; - - // Returns the thickness of the nonclient portion of the 3D edge along the - // bottom of the titlebar. - int TitlebarBottomThickness() const; - - // Returns the size of the titlebar icon. This is used even when the icon is - // not shown, e.g. to set the titlebar height. - int IconSize() const; - - // Returns the bounds of the titlebar icon (or where the icon would be if - // there was one). - gfx::Rect IconBounds() const; - - // Returns true if the title bar, caption buttons, and frame border should be - // drawn. If false, the client view occupies the full area of this view. - bool ShouldShowTitleBarAndBorder() const; - - // Returns true if the client edge should be drawn. This is true if - // the window is not maximized. - bool ShouldShowClientEdge() const; - - // Paint various sub-components of this view. - void PaintRestoredFrameBorder(gfx::Canvas* canvas); - void PaintMaximizedFrameBorder(gfx::Canvas* canvas); - void PaintTitleBar(gfx::Canvas* canvas); - void PaintRestoredClientEdge(gfx::Canvas* canvas); - - // Compute aspects of the frame needed to paint the frame background. - SkColor GetFrameColor() const; - const gfx::ImageSkia* GetFrameImage() const; - - // Performs the layout for the window control buttons based on the - // configuration specified in WindowButtonOrderProvider. The sizing and - // positions of the buttons affects LayoutTitleBar, call this beforehand. - void LayoutWindowControls(); - - // Calculations depend on the positions of the window controls. Always call - // LayoutWindowControls beforehand. - void LayoutTitleBar(); - void LayoutClientView(); - - // Creates, adds and returns a new window caption button (e.g, minimize, - // maximize, restore). - ImageButton* InitWindowCaptionButton(int accessibility_string_id, - int normal_image_id, - int hot_image_id, - int pushed_image_id); - - // Returns the window caption button for the given FrameButton type, if it - // should be visible. Otherwise NULL. - ImageButton* GetImageButton(views::FrameButton button); - - // The bounds of the client view, in this view's coordinates. - gfx::Rect client_view_bounds_; - - // The layout rect of the title, if visible. - gfx::Rect title_bounds_; - - // Not owned. - Widget* frame_; - - // The icon of this window. May be NULL. - ImageButton* window_icon_; - - // Window caption buttons. - ImageButton* minimize_button_; - ImageButton* maximize_button_; - ImageButton* restore_button_; - ImageButton* close_button_; - - // Background painter for the window frame. - scoped_ptr<FrameBackground> frame_background_; - - // The horizontal boundaries for the title bar to layout within. Restricted - // by the space used by the leading and trailing buttons. - int minimum_title_bar_x_; - int maximum_title_bar_x_; - - DISALLOW_COPY_AND_ASSIGN(CustomFrameView); -}; - -} // namespace views - -#endif // UI_VIEWS_WINDOW_CUSTOM_FRAME_VIEW_H_
diff --git a/ui/views/window/custom_frame_view_unittest.cc b/ui/views/window/custom_frame_view_unittest.cc deleted file mode 100644 index 68c79e8..0000000 --- a/ui/views/window/custom_frame_view_unittest.cc +++ /dev/null
@@ -1,280 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/window/custom_frame_view.h" - -#include <vector> - -#include "ui/views/controls/button/image_button.h" -#include "ui/views/test/views_test_base.h" -#include "ui/views/widget/widget.h" -#include "ui/views/widget/widget_delegate.h" -#include "ui/views/window/window_button_order_provider.h" - -namespace views { - -namespace { - -// Allows for the control of whether or not the widget can minimize/maximize or -// not. This can be set after initial setup in order to allow testing of both -// forms of delegates. By default this can minimize and maximize. -class MinimizeAndMaximizeStateControlDelegate : public WidgetDelegateView { - public: - MinimizeAndMaximizeStateControlDelegate() - : can_maximize_(true), - can_minimize_(true) {} - virtual ~MinimizeAndMaximizeStateControlDelegate() {} - - void set_can_maximize(bool can_maximize) { - can_maximize_ = can_maximize; - } - - void set_can_minimize(bool can_minimize) { - can_minimize_ = can_minimize; - } - - // WidgetDelegate: - virtual bool CanMaximize() const override { return can_maximize_; } - virtual bool CanMinimize() const override { return can_minimize_; } - - private: - bool can_maximize_; - bool can_minimize_; - - DISALLOW_COPY_AND_ASSIGN(MinimizeAndMaximizeStateControlDelegate); -}; - -} // namespace - -class CustomFrameViewTest : public ViewsTestBase { - public: - CustomFrameViewTest() {} - virtual ~CustomFrameViewTest() {} - - CustomFrameView* custom_frame_view() { - return custom_frame_view_; - } - - MinimizeAndMaximizeStateControlDelegate* - minimize_and_maximize_state_control_delegate() { - return minimize_and_maximize_state_control_delegate_; - } - - Widget* widget() { - return widget_; - } - - // ViewsTestBase: - virtual void SetUp() override; - virtual void TearDown() override; - - protected: - const std::vector<views::FrameButton>& leading_buttons() { - return WindowButtonOrderProvider::GetInstance()->leading_buttons(); - } - - const std::vector<views::FrameButton>& trailing_buttons() { - return WindowButtonOrderProvider::GetInstance()->trailing_buttons(); - } - - ImageButton* minimize_button() { - return custom_frame_view_->minimize_button_; - } - - ImageButton* maximize_button() { - return custom_frame_view_->maximize_button_; - } - - ImageButton* restore_button() { - return custom_frame_view_->restore_button_; - } - - ImageButton* close_button() { - return custom_frame_view_->close_button_; - } - - gfx::Rect title_bounds() { - return custom_frame_view_->title_bounds_; - } - - void SetWindowButtonOrder( - const std::vector<views::FrameButton> leading_buttons, - const std::vector<views::FrameButton> trailing_buttons); - - private: - // Parent container for |custom_frame_view_| - Widget* widget_; - - // Owned by |widget_| - CustomFrameView* custom_frame_view_; - - // Delegate of |widget_| which controls minimizing and maximizing - MinimizeAndMaximizeStateControlDelegate* - minimize_and_maximize_state_control_delegate_; - - DISALLOW_COPY_AND_ASSIGN(CustomFrameViewTest); -}; - -void CustomFrameViewTest::SetUp() { - ViewsTestBase::SetUp(); - - minimize_and_maximize_state_control_delegate_ = - new MinimizeAndMaximizeStateControlDelegate; - widget_ = new Widget; - Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW); - params.delegate = minimize_and_maximize_state_control_delegate_; - params.remove_standard_frame = true; - widget_->Init(params); - - custom_frame_view_ = new CustomFrameView; - widget_->non_client_view()->SetFrameView(custom_frame_view_); -} - -void CustomFrameViewTest::TearDown() { - widget_->CloseNow(); - - ViewsTestBase::TearDown(); -} - -void CustomFrameViewTest::SetWindowButtonOrder( - const std::vector<views::FrameButton> leading_buttons, - const std::vector<views::FrameButton> trailing_buttons) { - WindowButtonOrderProvider::GetInstance()-> - SetWindowButtonOrder(leading_buttons, trailing_buttons); -} - -// Tests that there is a default button ordering before initialization causes -// a configuration file check. -TEST_F(CustomFrameViewTest, DefaultButtons) { - const std::vector<views::FrameButton>& trailing = trailing_buttons(); - EXPECT_EQ(trailing.size(), 3u); - EXPECT_TRUE(leading_buttons().empty()); - EXPECT_EQ(trailing[0], FRAME_BUTTON_MINIMIZE); - EXPECT_EQ(trailing[1], FRAME_BUTTON_MAXIMIZE); - EXPECT_EQ(trailing[2], FRAME_BUTTON_CLOSE); -} - -// Tests that layout places the buttons in order, that the restore button is -// hidden and the buttons are placed after the title. -TEST_F(CustomFrameViewTest, DefaultButtonLayout) { - Widget* parent = widget(); - CustomFrameView* view = custom_frame_view(); - view->Init(parent); - parent->SetBounds(gfx::Rect(0, 0, 300, 100)); - parent->Show(); - - EXPECT_LT(minimize_button()->x(), maximize_button()->x()); - EXPECT_LT(maximize_button()->x(), close_button()->x()); - EXPECT_FALSE(restore_button()->visible()); - - EXPECT_GT(minimize_button()->x(), - title_bounds().x() + title_bounds().width()); -} - -// Tests that setting the buttons to leading places them before the title. -TEST_F(CustomFrameViewTest, LeadingButtonLayout) { - Widget* parent = widget(); - CustomFrameView* view = custom_frame_view(); - - std::vector<views::FrameButton> leading; - leading.push_back(views::FRAME_BUTTON_CLOSE); - leading.push_back(views::FRAME_BUTTON_MINIMIZE); - leading.push_back(views::FRAME_BUTTON_MAXIMIZE); - - std::vector<views::FrameButton> trailing; - - SetWindowButtonOrder(leading, trailing); - - view->Init(parent); - parent->SetBounds(gfx::Rect(0, 0, 300, 100)); - parent->Show(); - EXPECT_LT(close_button()->x(), minimize_button()->x()); - EXPECT_LT(minimize_button()->x(), maximize_button()->x()); - EXPECT_FALSE(restore_button()->visible()); - EXPECT_LT(maximize_button()->x() + maximize_button()->width(), - title_bounds().x()); -} - -// Tests that layouts occuring while maximized swap the maximize button for the -// restore button -TEST_F(CustomFrameViewTest, MaximizeRevealsRestoreButton) { - Widget* parent = widget(); - CustomFrameView* view = custom_frame_view(); - view->Init(parent); - parent->SetBounds(gfx::Rect(0, 0, 300, 100)); - parent->Show(); - - ASSERT_FALSE(restore_button()->visible()); - ASSERT_TRUE(maximize_button()->visible()); - - parent->Maximize(); - view->Layout(); - - EXPECT_TRUE(restore_button()->visible()); - EXPECT_FALSE(maximize_button()->visible()); -} - -// Tests that when the parent cannot maximize that the maximize button is not -// visible -TEST_F(CustomFrameViewTest, CannotMaximizeHidesButton) { - Widget* parent = widget(); - CustomFrameView* view = custom_frame_view(); - MinimizeAndMaximizeStateControlDelegate* delegate = - minimize_and_maximize_state_control_delegate(); - delegate->set_can_maximize(false); - - view->Init(parent); - parent->SetBounds(gfx::Rect(0, 0, 300, 100)); - parent->Show(); - - EXPECT_FALSE(restore_button()->visible()); - EXPECT_FALSE(maximize_button()->visible()); -} - -// Tests that when the parent cannot minimize that the minimize button is not -// visible -TEST_F(CustomFrameViewTest, CannotMinimizeHidesButton) { - Widget* parent = widget(); - CustomFrameView* view = custom_frame_view(); - MinimizeAndMaximizeStateControlDelegate* delegate = - minimize_and_maximize_state_control_delegate(); - delegate->set_can_minimize(false); - - view->Init(parent); - parent->SetBounds(gfx::Rect(0, 0, 300, 100)); - parent->Show(); - - EXPECT_FALSE(minimize_button()->visible()); -} - -// Tests that when maximized that the edge button has an increased width. -TEST_F(CustomFrameViewTest, LargerEdgeButtonsWhenMaximized) { - Widget* parent = widget(); - CustomFrameView* view = custom_frame_view(); - - // Custom ordering to have a button on each edge. - std::vector<views::FrameButton> leading; - leading.push_back(views::FRAME_BUTTON_CLOSE); - leading.push_back(views::FRAME_BUTTON_MAXIMIZE); - std::vector<views::FrameButton> trailing; - trailing.push_back(views::FRAME_BUTTON_MINIMIZE); - SetWindowButtonOrder(leading, trailing); - - view->Init(parent); - parent->SetBounds(gfx::Rect(0, 0, 300, 100)); - parent->Show(); - - gfx::Rect close_button_initial_bounds = close_button()->bounds(); - gfx::Rect minimize_button_initial_bounds = minimize_button()->bounds(); - - parent->Maximize(); - view->Layout(); - - EXPECT_GT(close_button()->bounds().width(), - close_button_initial_bounds.width()); - EXPECT_GT(minimize_button()->bounds().width(), - minimize_button_initial_bounds.width()); -} - -} // namespace views
diff --git a/ui/views/window/dialog_client_view.cc b/ui/views/window/dialog_client_view.cc deleted file mode 100644 index 17f7186..0000000 --- a/ui/views/window/dialog_client_view.cc +++ /dev/null
@@ -1,428 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/window/dialog_client_view.h" - -#include <algorithm> - -#include "ui/events/keycodes/keyboard_codes.h" -#include "ui/views/background.h" -#include "ui/views/controls/button/blue_button.h" -#include "ui/views/controls/button/label_button.h" -#include "ui/views/layout/layout_constants.h" -#include "ui/views/widget/widget.h" -#include "ui/views/window/dialog_delegate.h" - -namespace views { - -namespace { - -// The group used by the buttons. This name is chosen voluntarily big not to -// conflict with other groups that could be in the dialog content. -const int kButtonGroup = 6666; - -#if defined(OS_WIN) || defined(OS_CHROMEOS) -const bool kIsOkButtonOnLeftSide = true; -#else -const bool kIsOkButtonOnLeftSide = false; -#endif - -// Returns true if the given view should be shown (i.e. exists and is -// visible). -bool ShouldShow(View* view) { - return view && view->visible(); -} - -// Do the layout for a button. -void LayoutButton(LabelButton* button, gfx::Rect* row_bounds) { - if (!button) - return; - - const gfx::Size size = button->GetPreferredSize(); - row_bounds->set_width(row_bounds->width() - size.width()); - button->SetBounds(row_bounds->right(), row_bounds->y(), - size.width(), row_bounds->height()); - row_bounds->set_width(row_bounds->width() - kRelatedButtonHSpacing); -} - -} // namespace - -/////////////////////////////////////////////////////////////////////////////// -// DialogClientView, public: - -DialogClientView::DialogClientView(Widget* owner, View* contents_view) - : ClientView(owner, contents_view), - ok_button_(NULL), - cancel_button_(NULL), - default_button_(NULL), - focus_manager_(NULL), - extra_view_(NULL), - footnote_view_(NULL), - notified_delegate_(false) { -} - -DialogClientView::~DialogClientView() { -} - -void DialogClientView::AcceptWindow() { - // Only notify the delegate once. See |notified_delegate_|'s comment. - if (!notified_delegate_ && GetDialogDelegate()->Accept(false)) { - notified_delegate_ = true; - Close(); - } -} - -void DialogClientView::CancelWindow() { - // Only notify the delegate once. See |notified_delegate_|'s comment. - if (!notified_delegate_ && GetDialogDelegate()->Cancel()) { - notified_delegate_ = true; - Close(); - } -} - -void DialogClientView::UpdateDialogButtons() { - const int buttons = GetDialogDelegate()->GetDialogButtons(); - ui::Accelerator escape(ui::VKEY_ESCAPE, ui::EF_NONE); - if (default_button_) - default_button_->SetIsDefault(false); - default_button_ = NULL; - - if (buttons & ui::DIALOG_BUTTON_OK) { - if (!ok_button_) { - ok_button_ = CreateDialogButton(ui::DIALOG_BUTTON_OK); - if (!(buttons & ui::DIALOG_BUTTON_CANCEL)) - ok_button_->AddAccelerator(escape); - AddChildView(ok_button_); - } - - UpdateButton(ok_button_, ui::DIALOG_BUTTON_OK); - } else if (ok_button_) { - delete ok_button_; - ok_button_ = NULL; - } - - if (buttons & ui::DIALOG_BUTTON_CANCEL) { - if (!cancel_button_) { - cancel_button_ = CreateDialogButton(ui::DIALOG_BUTTON_CANCEL); - cancel_button_->AddAccelerator(escape); - AddChildView(cancel_button_); - } - - UpdateButton(cancel_button_, ui::DIALOG_BUTTON_CANCEL); - } else if (cancel_button_) { - delete cancel_button_; - cancel_button_ = NULL; - } - - // Use the escape key to close the window if there are no dialog buttons. - if (!has_dialog_buttons()) - AddAccelerator(escape); - else - ResetAccelerators(); -} - -/////////////////////////////////////////////////////////////////////////////// -// DialogClientView, ClientView overrides: - -bool DialogClientView::CanClose() { - if (notified_delegate_) - return true; - - // The dialog is closing but no Accept or Cancel action has been performed - // before: it's a Close action. - if (GetDialogDelegate()->Close()) { - notified_delegate_ = true; - GetDialogDelegate()->OnClosed(); - return true; - } - return false; -} - -DialogClientView* DialogClientView::AsDialogClientView() { - return this; -} - -const DialogClientView* DialogClientView::AsDialogClientView() const { - return this; -} - -void DialogClientView::OnWillChangeFocus(View* focused_before, - View* focused_now) { - // Make the newly focused button default or restore the dialog's default. - const int default_button = GetDialogDelegate()->GetDefaultDialogButton(); - LabelButton* new_default_button = NULL; - if (focused_now && - !strcmp(focused_now->GetClassName(), LabelButton::kViewClassName)) { - new_default_button = static_cast<LabelButton*>(focused_now); - } else if (default_button == ui::DIALOG_BUTTON_OK && ok_button_) { - new_default_button = ok_button_; - } else if (default_button == ui::DIALOG_BUTTON_CANCEL && cancel_button_) { - new_default_button = cancel_button_; - } - - if (default_button_ && default_button_ != new_default_button) - default_button_->SetIsDefault(false); - default_button_ = new_default_button; - if (default_button_ && !default_button_->is_default()) - default_button_->SetIsDefault(true); -} - -void DialogClientView::OnDidChangeFocus(View* focused_before, - View* focused_now) { -} - -//////////////////////////////////////////////////////////////////////////////// -// DialogClientView, View overrides: - -gfx::Size DialogClientView::GetPreferredSize() const { - // Initialize the size to fit the buttons and extra view row. - gfx::Size size( - (ok_button_ ? ok_button_->GetPreferredSize().width() : 0) + - (cancel_button_ ? cancel_button_->GetPreferredSize().width() : 0) + - (cancel_button_ && ok_button_ ? kRelatedButtonHSpacing : 0) + - (ShouldShow(extra_view_) ? extra_view_->GetPreferredSize().width() : 0) + - (ShouldShow(extra_view_) && has_dialog_buttons() ? - kRelatedButtonHSpacing : 0), - 0); - - int buttons_height = GetButtonsAndExtraViewRowHeight(); - if (buttons_height != 0) { - size.Enlarge(0, buttons_height + kRelatedControlVerticalSpacing); - // Inset the buttons and extra view. - const gfx::Insets insets = GetButtonRowInsets(); - size.Enlarge(insets.width(), insets.height()); - } - - // Increase the size as needed to fit the contents view. - // NOTE: The contents view is not inset on the top or side client view edges. - gfx::Size contents_size = contents_view()->GetPreferredSize(); - size.Enlarge(0, contents_size.height()); - size.set_width(std::max(size.width(), contents_size.width())); - - // Increase the size as needed to fit the footnote view. - if (ShouldShow(footnote_view_)) { - gfx::Size footnote_size = footnote_view_->GetPreferredSize(); - if (!footnote_size.IsEmpty()) - size.set_width(std::max(size.width(), footnote_size.width())); - - int footnote_height = footnote_view_->GetHeightForWidth(size.width()); - size.Enlarge(0, footnote_height); - } - - return size; -} - -void DialogClientView::Layout() { - gfx::Rect bounds = GetContentsBounds(); - - // Layout the footnote view. - if (ShouldShow(footnote_view_)) { - const int height = footnote_view_->GetHeightForWidth(bounds.width()); - footnote_view_->SetBounds(bounds.x(), bounds.bottom() - height, - bounds.width(), height); - if (height != 0) - bounds.Inset(0, 0, 0, height); - } - - // Layout the row containing the buttons and the extra view. - if (has_dialog_buttons() || ShouldShow(extra_view_)) { - bounds.Inset(GetButtonRowInsets()); - const int height = GetButtonsAndExtraViewRowHeight(); - gfx::Rect row_bounds(bounds.x(), bounds.bottom() - height, - bounds.width(), height); - if (kIsOkButtonOnLeftSide) { - LayoutButton(cancel_button_, &row_bounds); - LayoutButton(ok_button_, &row_bounds); - } else { - LayoutButton(ok_button_, &row_bounds); - LayoutButton(cancel_button_, &row_bounds); - } - if (extra_view_) { - row_bounds.set_width(std::min(row_bounds.width(), - extra_view_->GetPreferredSize().width())); - extra_view_->SetBoundsRect(row_bounds); - } - - if (height > 0) - bounds.Inset(0, 0, 0, height + kRelatedControlVerticalSpacing); - } - - // Layout the contents view to the top and side edges of the contents bounds. - // NOTE: The local insets do not apply to the contents view sides or top. - const gfx::Rect contents_bounds = GetContentsBounds(); - contents_view()->SetBounds(contents_bounds.x(), contents_bounds.y(), - contents_bounds.width(), bounds.bottom() - contents_bounds.y()); -} - -bool DialogClientView::AcceleratorPressed(const ui::Accelerator& accelerator) { - DCHECK_EQ(accelerator.key_code(), ui::VKEY_ESCAPE); - Close(); - return true; -} - -void DialogClientView::ViewHierarchyChanged( - const ViewHierarchyChangedDetails& details) { - ClientView::ViewHierarchyChanged(details); - if (details.is_add && details.child == this) { - focus_manager_ = GetFocusManager(); - if (focus_manager_) - GetFocusManager()->AddFocusChangeListener(this); - - UpdateDialogButtons(); - CreateExtraView(); - CreateFootnoteView(); - } else if (!details.is_add && details.child == this) { - if (focus_manager_) - focus_manager_->RemoveFocusChangeListener(this); - focus_manager_ = NULL; - } else if (!details.is_add) { - if (details.child == default_button_) - default_button_ = NULL; - if (details.child == ok_button_) - ok_button_ = NULL; - if (details.child == cancel_button_) - cancel_button_ = NULL; - } -} - -void DialogClientView::NativeViewHierarchyChanged() { - FocusManager* focus_manager = GetFocusManager(); - if (focus_manager_ != focus_manager) { - if (focus_manager_) - focus_manager_->RemoveFocusChangeListener(this); - focus_manager_ = focus_manager; - if (focus_manager_) - focus_manager_->AddFocusChangeListener(this); - } -} - -void DialogClientView::OnNativeThemeChanged(const ui::NativeTheme* theme) { - // The old dialog style needs an explicit background color, while the new - // dialog style simply inherits the bubble's frame view color. - const DialogDelegate* dialog = GetDialogDelegate(); - - if (dialog && !dialog->UseNewStyleForThisDialog()) { - set_background(views::Background::CreateSolidBackground(GetNativeTheme()-> - GetSystemColor(ui::NativeTheme::kColorId_DialogBackground))); - } -} - -//////////////////////////////////////////////////////////////////////////////// -// DialogClientView, ButtonListener implementation: - -void DialogClientView::ButtonPressed(Button* sender, const ui::Event& event) { - // Check for a valid delegate to avoid handling events after destruction. - if (!GetDialogDelegate()) - return; - - if (sender == ok_button_) - AcceptWindow(); - else if (sender == cancel_button_) - CancelWindow(); - else - NOTREACHED(); -} - -//////////////////////////////////////////////////////////////////////////////// -// DialogClientView, protected: - -DialogClientView::DialogClientView(View* contents_view) - : ClientView(NULL, contents_view), - ok_button_(NULL), - cancel_button_(NULL), - default_button_(NULL), - focus_manager_(NULL), - extra_view_(NULL), - footnote_view_(NULL), - notified_delegate_(false) {} - -DialogDelegate* DialogClientView::GetDialogDelegate() const { - return GetWidget()->widget_delegate()->AsDialogDelegate(); -} - -void DialogClientView::CreateExtraView() { - if (extra_view_) - return; - - extra_view_ = GetDialogDelegate()->CreateExtraView(); - if (extra_view_) { - extra_view_->SetGroup(kButtonGroup); - AddChildView(extra_view_); - } -} - -void DialogClientView::CreateFootnoteView() { - if (footnote_view_) - return; - - footnote_view_ = GetDialogDelegate()->CreateFootnoteView(); - if (footnote_view_) - AddChildView(footnote_view_); -} - -void DialogClientView::ChildPreferredSizeChanged(View* child) { - if (child == footnote_view_ || child == extra_view_) - Layout(); -} - -void DialogClientView::ChildVisibilityChanged(View* child) { - ChildPreferredSizeChanged(child); -} - -//////////////////////////////////////////////////////////////////////////////// -// DialogClientView, private: - -LabelButton* DialogClientView::CreateDialogButton(ui::DialogButton type) { - const base::string16 title = GetDialogDelegate()->GetDialogButtonLabel(type); - LabelButton* button = NULL; - if (GetDialogDelegate()->UseNewStyleForThisDialog() && - GetDialogDelegate()->GetDefaultDialogButton() == type && - GetDialogDelegate()->ShouldDefaultButtonBeBlue()) { - button = new BlueButton(this, title); - } else { - button = new LabelButton(this, title); - button->SetStyle(Button::STYLE_BUTTON); - } - button->SetFocusable(true); - - const int kDialogMinButtonWidth = 75; - button->SetMinSize(gfx::Size(kDialogMinButtonWidth, 0)); - button->SetGroup(kButtonGroup); - return button; -} - -void DialogClientView::UpdateButton(LabelButton* button, - ui::DialogButton type) { - DialogDelegate* dialog = GetDialogDelegate(); - button->SetText(dialog->GetDialogButtonLabel(type)); - button->SetEnabled(dialog->IsDialogButtonEnabled(type)); - - if (type == dialog->GetDefaultDialogButton()) { - default_button_ = button; - button->SetIsDefault(true); - } -} - -int DialogClientView::GetButtonsAndExtraViewRowHeight() const { - int extra_view_height = ShouldShow(extra_view_) ? - extra_view_->GetPreferredSize().height() : 0; - int buttons_height = std::max( - ok_button_ ? ok_button_->GetPreferredSize().height() : 0, - cancel_button_ ? cancel_button_->GetPreferredSize().height() : 0); - return std::max(extra_view_height, buttons_height); -} - -gfx::Insets DialogClientView::GetButtonRowInsets() const { - // NOTE: The insets only apply to the buttons, extra view, and footnote view. - return GetButtonsAndExtraViewRowHeight() == 0 ? gfx::Insets() : - gfx::Insets(0, kButtonHEdgeMarginNew, - kButtonVEdgeMarginNew, kButtonHEdgeMarginNew); -} - -void DialogClientView::Close() { - GetWidget()->Close(); - GetDialogDelegate()->OnClosed(); -} - -} // namespace views
diff --git a/ui/views/window/dialog_client_view.h b/ui/views/window/dialog_client_view.h deleted file mode 100644 index bf38f25..0000000 --- a/ui/views/window/dialog_client_view.h +++ /dev/null
@@ -1,135 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_WINDOW_DIALOG_CLIENT_VIEW_H_ -#define UI_VIEWS_WINDOW_DIALOG_CLIENT_VIEW_H_ - -#include "ui/base/ui_base_types.h" -#include "ui/views/controls/button/button.h" -#include "ui/views/focus/focus_manager.h" -#include "ui/views/window/client_view.h" - -namespace views { - -class DialogDelegate; -class LabelButton; -class Widget; - -// DialogClientView provides adornments for a dialog's content view, including -// custom-labeled [OK] and [Cancel] buttons with [Enter] and [Esc] accelerators. -// The view also displays the delegate's extra view alongside the buttons and -// the delegate's footnote view below the buttons. The view appears like below. -// NOTE: The contents view is not inset on the top or side client view edges. -// +------------------------------+ -// | Contents View | -// +------------------------------+ -// | [Extra View] [OK] [Cancel] | -// | [ Footnote View ] | -// +------------------------------+ -class VIEWS_EXPORT DialogClientView : public ClientView, - public ButtonListener, - public FocusChangeListener { - public: - DialogClientView(Widget* widget, View* contents_view); - virtual ~DialogClientView(); - - // Accept or Cancel the dialog. - void AcceptWindow(); - void CancelWindow(); - - // Accessors in case the user wishes to adjust these buttons. - LabelButton* ok_button() const { return ok_button_; } - LabelButton* cancel_button() const { return cancel_button_; } - - // Update the dialog buttons to match the dialog's delegate. - void UpdateDialogButtons(); - - // ClientView implementation: - virtual bool CanClose() override; - virtual DialogClientView* AsDialogClientView() override; - virtual const DialogClientView* AsDialogClientView() const override; - - // FocusChangeListener implementation: - virtual void OnWillChangeFocus(View* focused_before, - View* focused_now) override; - virtual void OnDidChangeFocus(View* focused_before, - View* focused_now) override; - - // View implementation: - virtual gfx::Size GetPreferredSize() const override; - virtual void Layout() override; - virtual bool AcceleratorPressed(const ui::Accelerator& accelerator) override; - virtual void ViewHierarchyChanged( - const ViewHierarchyChangedDetails& details) override; - virtual void NativeViewHierarchyChanged() override; - virtual void OnNativeThemeChanged(const ui::NativeTheme* theme) override; - - // ButtonListener implementation: - virtual void ButtonPressed(Button* sender, const ui::Event& event) override; - - protected: - // For testing. - DialogClientView(View* contents_view); - - // Returns the DialogDelegate for the window. Virtual for testing. - virtual DialogDelegate* GetDialogDelegate() const; - - // Create and add the extra view, if supplied by the delegate. - void CreateExtraView(); - - // Creates and adds the footnote view, if supplied by the delegate. - void CreateFootnoteView(); - - // View implementation. - virtual void ChildPreferredSizeChanged(View* child) override; - virtual void ChildVisibilityChanged(View* child) override; - - private: - FRIEND_TEST_ALL_PREFIXES(DialogClientViewTest, FocusManager); - - bool has_dialog_buttons() const { return ok_button_ || cancel_button_; } - - // Create a dialog button of the appropriate type. - LabelButton* CreateDialogButton(ui::DialogButton type); - - // Update |button|'s text and enabled state according to the delegate's state. - void UpdateButton(LabelButton* button, ui::DialogButton type); - - // Returns the height of the row containing the buttons and the extra view. - int GetButtonsAndExtraViewRowHeight() const; - - // Returns the insets for the buttons and extra view. - gfx::Insets GetButtonRowInsets() const; - - // Closes the widget. - void Close(); - - // The dialog buttons. - LabelButton* ok_button_; - LabelButton* cancel_button_; - - // The button that is currently default; may be NULL. - LabelButton* default_button_; - - // Observe |focus_manager_| to update the default button with focus changes. - FocusManager* focus_manager_; - - // The extra view shown in the row of buttons; may be NULL. - View* extra_view_; - - // The footnote view shown below the buttons; may be NULL. - View* footnote_view_; - - // True if we've notified the delegate the window is closing and the delegate - // allosed the close. In some situations it's possible to get two closes (see - // http://crbug.com/71940). This is used to avoid notifying the delegate - // twice, which can have bad consequences. - bool notified_delegate_; - - DISALLOW_COPY_AND_ASSIGN(DialogClientView); -}; - -} // namespace views - -#endif // UI_VIEWS_WINDOW_DIALOG_CLIENT_VIEW_H_
diff --git a/ui/views/window/dialog_client_view_unittest.cc b/ui/views/window/dialog_client_view_unittest.cc deleted file mode 100644 index 6f4812c..0000000 --- a/ui/views/window/dialog_client_view_unittest.cc +++ /dev/null
@@ -1,292 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/basictypes.h" -#include "base/strings/utf_string_conversions.h" -#include "ui/base/ui_base_types.h" -#include "ui/views/controls/button/label_button.h" -#include "ui/views/test/test_views.h" -#include "ui/views/test/views_test_base.h" -#include "ui/views/widget/widget.h" -#include "ui/views/window/dialog_client_view.h" -#include "ui/views/window/dialog_delegate.h" - -namespace views { - -class TestDialogClientView : public DialogClientView { - public: - TestDialogClientView(View* contents_view, - DialogDelegate* dialog_delegate) - : DialogClientView(contents_view), - dialog_(dialog_delegate) {} - virtual ~TestDialogClientView() {} - - // DialogClientView implementation. - virtual DialogDelegate* GetDialogDelegate() const override { return dialog_; } - - View* GetContentsView() { return contents_view(); } - - void CreateExtraViews() { - CreateExtraView(); - CreateFootnoteView(); - } - - private: - DialogDelegate* dialog_; - - DISALLOW_COPY_AND_ASSIGN(TestDialogClientView); -}; - -class DialogClientViewTest : public ViewsTestBase, - public DialogDelegateView { - public: - DialogClientViewTest() - : dialog_buttons_(ui::DIALOG_BUTTON_NONE), - extra_view_(NULL), - footnote_view_(NULL) {} - virtual ~DialogClientViewTest() {} - - // testing::Test implementation. - virtual void SetUp() override { - dialog_buttons_ = ui::DIALOG_BUTTON_NONE; - contents_.reset(new StaticSizedView(gfx::Size(100, 200))); - client_view_.reset(new TestDialogClientView(contents_.get(), this)); - - ViewsTestBase::SetUp(); - } - - // DialogDelegateView implementation. - virtual View* GetContentsView() override { return contents_.get(); } - virtual View* CreateExtraView() override { return extra_view_; } - virtual View* CreateFootnoteView() override { return footnote_view_; } - virtual int GetDialogButtons() const override { return dialog_buttons_; } - - protected: - gfx::Rect GetUpdatedClientBounds() { - client_view_->SizeToPreferredSize(); - client_view_->Layout(); - return client_view_->bounds(); - } - - // Makes sure that the content view is sized correctly. Width must be at least - // the requested amount, but height should always match exactly. - void CheckContentsIsSetToPreferredSize() { - const gfx::Rect client_bounds = GetUpdatedClientBounds(); - const gfx::Size preferred_size = contents_->GetPreferredSize(); - EXPECT_EQ(preferred_size.height(), contents_->bounds().height()); - EXPECT_LE(preferred_size.width(), contents_->bounds().width()); - EXPECT_EQ(contents_->bounds().origin(), client_bounds.origin()); - EXPECT_EQ(contents_->bounds().right(), client_bounds.right()); - } - - // Sets the buttons to show in the dialog and refreshes the dialog. - void SetDialogButtons(int dialog_buttons) { - dialog_buttons_ = dialog_buttons; - client_view_->UpdateDialogButtons(); - } - - // Sets the extra view. - void SetExtraView(View* view) { - DCHECK(!extra_view_); - extra_view_ = view; - client_view_->CreateExtraViews(); - } - - // Sets the footnote view. - void SetFootnoteView(View* view) { - DCHECK(!footnote_view_); - footnote_view_ = view; - client_view_->CreateExtraViews(); - } - - TestDialogClientView* client_view() { return client_view_.get(); } - - private: - // The contents of the dialog. - scoped_ptr<View> contents_; - // The DialogClientView that's being tested. - scoped_ptr<TestDialogClientView> client_view_; - // The bitmask of buttons to show in the dialog. - int dialog_buttons_; - View* extra_view_; // weak - View* footnote_view_; // weak - - DISALLOW_COPY_AND_ASSIGN(DialogClientViewTest); -}; - -TEST_F(DialogClientViewTest, UpdateButtons) { - // This dialog should start with no buttons. - EXPECT_EQ(GetDialogButtons(), ui::DIALOG_BUTTON_NONE); - EXPECT_EQ(NULL, client_view()->ok_button()); - EXPECT_EQ(NULL, client_view()->cancel_button()); - const int height_without_buttons = GetUpdatedClientBounds().height(); - - // Update to use both buttons. - SetDialogButtons(ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL); - EXPECT_TRUE(client_view()->ok_button()->is_default()); - EXPECT_FALSE(client_view()->cancel_button()->is_default()); - const int height_with_buttons = GetUpdatedClientBounds().height(); - EXPECT_GT(height_with_buttons, height_without_buttons); - - // Remove the dialog buttons. - SetDialogButtons(ui::DIALOG_BUTTON_NONE); - EXPECT_EQ(NULL, client_view()->ok_button()); - EXPECT_EQ(NULL, client_view()->cancel_button()); - EXPECT_EQ(GetUpdatedClientBounds().height(), height_without_buttons); - - // Reset with just an ok button. - SetDialogButtons(ui::DIALOG_BUTTON_OK); - EXPECT_TRUE(client_view()->ok_button()->is_default()); - EXPECT_EQ(NULL, client_view()->cancel_button()); - EXPECT_EQ(GetUpdatedClientBounds().height(), height_with_buttons); - - // Reset with just a cancel button. - SetDialogButtons(ui::DIALOG_BUTTON_CANCEL); - EXPECT_EQ(NULL, client_view()->ok_button()); - EXPECT_TRUE(client_view()->cancel_button()->is_default()); - EXPECT_EQ(GetUpdatedClientBounds().height(), height_with_buttons); -} - -TEST_F(DialogClientViewTest, RemoveAndUpdateButtons) { - // Removing buttons from another context should clear the local pointer. - SetDialogButtons(ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL); - delete client_view()->ok_button(); - EXPECT_EQ(NULL, client_view()->ok_button()); - delete client_view()->cancel_button(); - EXPECT_EQ(NULL, client_view()->cancel_button()); - - // Updating should restore the requested buttons properly. - SetDialogButtons(ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL); - EXPECT_TRUE(client_view()->ok_button()->is_default()); - EXPECT_FALSE(client_view()->cancel_button()->is_default()); -} - -// Test that the contents view gets its preferred size in the basic dialog -// configuration. -TEST_F(DialogClientViewTest, ContentsSize) { - CheckContentsIsSetToPreferredSize(); - EXPECT_EQ(GetContentsView()->bounds().bottom(), - client_view()->bounds().bottom()); -} - -// Test the effect of the button strip on layout. -TEST_F(DialogClientViewTest, LayoutWithButtons) { - SetDialogButtons(ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL); - CheckContentsIsSetToPreferredSize(); - EXPECT_LT(GetContentsView()->bounds().bottom(), - client_view()->bounds().bottom()); - gfx::Size no_extra_view_size = client_view()->bounds().size(); - - View* extra_view = new StaticSizedView(gfx::Size(200, 200)); - SetExtraView(extra_view); - CheckContentsIsSetToPreferredSize(); - EXPECT_GT(client_view()->bounds().height(), no_extra_view_size.height()); - int width_of_extra_view = extra_view->bounds().width(); - - // Visibility of extra view is respected. - extra_view->SetVisible(false); - CheckContentsIsSetToPreferredSize(); - EXPECT_EQ(no_extra_view_size.height(), client_view()->bounds().height()); - EXPECT_EQ(no_extra_view_size.width(), client_view()->bounds().width()); - - // Try with a reduced-size dialog. - extra_view->SetVisible(true); - client_view()->SetBoundsRect(gfx::Rect(gfx::Point(0, 0), no_extra_view_size)); - client_view()->Layout(); - DCHECK_GT(width_of_extra_view, extra_view->bounds().width()); -} - -// Test the effect of the footnote view on layout. -TEST_F(DialogClientViewTest, LayoutWithFootnote) { - CheckContentsIsSetToPreferredSize(); - gfx::Size no_footnote_size = client_view()->bounds().size(); - - View* footnote_view = new StaticSizedView(gfx::Size(200, 200)); - SetFootnoteView(footnote_view); - CheckContentsIsSetToPreferredSize(); - EXPECT_GT(client_view()->bounds().height(), no_footnote_size.height()); - EXPECT_EQ(200, footnote_view->bounds().height()); - gfx::Size with_footnote_size = client_view()->bounds().size(); - EXPECT_EQ(with_footnote_size.width(), footnote_view->bounds().width()); - - SetDialogButtons(ui::DIALOG_BUTTON_CANCEL); - CheckContentsIsSetToPreferredSize(); - EXPECT_LE(with_footnote_size.height(), client_view()->bounds().height()); - EXPECT_LE(with_footnote_size.width(), client_view()->bounds().width()); - gfx::Size with_footnote_and_button_size = client_view()->bounds().size(); - - SetDialogButtons(ui::DIALOG_BUTTON_NONE); - footnote_view->SetVisible(false); - CheckContentsIsSetToPreferredSize(); - EXPECT_EQ(no_footnote_size.height(), client_view()->bounds().height()); - EXPECT_EQ(no_footnote_size.width(), client_view()->bounds().width()); -} - -// Test that GetHeightForWidth is respected for the footnote view. -TEST_F(DialogClientViewTest, LayoutWithFootnoteHeightForWidth) { - CheckContentsIsSetToPreferredSize(); - gfx::Size no_footnote_size = client_view()->bounds().size(); - - View* footnote_view = new ProportionallySizedView(3); - SetFootnoteView(footnote_view); - CheckContentsIsSetToPreferredSize(); - EXPECT_GT(client_view()->bounds().height(), no_footnote_size.height()); - EXPECT_EQ(footnote_view->bounds().width() * 3, - footnote_view->bounds().height()); -} - -// Test that the DialogClientView's FocusManager is properly updated when the -// DialogClientView belongs to a non top level widget and the widget is -// reparented. The DialogClientView belongs to a non top level widget in the -// case of constrained windows. The constrained window's widget is reparented -// when a browser tab is dragged to a different browser window. -TEST_F(DialogClientViewTest, FocusManager) { - scoped_ptr<Widget> toplevel1(new Widget); - Widget::InitParams toplevel1_params = - CreateParams(Widget::InitParams::TYPE_WINDOW); - toplevel1_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - toplevel1->Init(toplevel1_params); - - scoped_ptr<Widget> toplevel2(new Widget); - Widget::InitParams toplevel2_params = - CreateParams(Widget::InitParams::TYPE_WINDOW); - toplevel2_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; - toplevel2->Init(toplevel2_params); - - Widget* dialog = new Widget; - Widget::InitParams dialog_params = - CreateParams(Widget::InitParams::TYPE_WINDOW); - dialog_params.child = true; - dialog_params.delegate = new DialogDelegateView(); - dialog_params.parent = toplevel1->GetNativeView(); - dialog->Init(dialog_params); - - // Test that the FocusManager has been properly set when the DialogClientView - // was parented to |dialog|. - DialogClientView* client_view = - static_cast<DialogClientView*>(dialog->client_view()); - EXPECT_EQ(toplevel1->GetFocusManager(), client_view->focus_manager_); - - // Test that the FocusManager is properly updated when the DialogClientView's - // top level widget is changed. - Widget::ReparentNativeView(dialog->GetNativeView(), NULL); - EXPECT_EQ(NULL, client_view->focus_manager_); - Widget::ReparentNativeView(dialog->GetNativeView(), - toplevel2->GetNativeView()); - EXPECT_EQ(toplevel2->GetFocusManager(), client_view->focus_manager_); - Widget::ReparentNativeView(dialog->GetNativeView(), - toplevel1->GetNativeView()); - EXPECT_NE(toplevel1->GetFocusManager(), toplevel2->GetFocusManager()); - EXPECT_EQ(toplevel1->GetFocusManager(), client_view->focus_manager_); - - // Test that the FocusManager is properly cleared when the DialogClientView is - // removed from |dialog| during the widget's destruction. - client_view->set_owned_by_client(); - scoped_ptr<DialogClientView> owned_client_view(client_view); - toplevel1->CloseNow(); - toplevel2->CloseNow(); - EXPECT_EQ(NULL, owned_client_view->focus_manager_); -} - -} // namespace views
diff --git a/ui/views/window/dialog_delegate.cc b/ui/views/window/dialog_delegate.cc deleted file mode 100644 index 1627a8f..0000000 --- a/ui/views/window/dialog_delegate.cc +++ /dev/null
@@ -1,241 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/window/dialog_delegate.h" - -#include "base/logging.h" -#include "ui/base/l10n/l10n_util.h" -#include "ui/strings/grit/ui_strings.h" -#include "ui/views/bubble/bubble_border.h" -#include "ui/views/bubble/bubble_frame_view.h" -#include "ui/views/controls/button/label_button.h" -#include "ui/views/widget/widget.h" -#include "ui/views/widget/widget_observer.h" -#include "ui/views/window/dialog_client_view.h" - -#if defined(OS_WIN) -#include "ui/base/win/shell.h" -#endif - -namespace views { - -//////////////////////////////////////////////////////////////////////////////// -// DialogDelegate: - -DialogDelegate::DialogDelegate() : supports_new_style_(true) { -} - -DialogDelegate::~DialogDelegate() { -} - -// static -Widget* DialogDelegate::CreateDialogWidget(WidgetDelegate* delegate, - gfx::NativeWindow context, - gfx::NativeView parent) { - return CreateDialogWidgetWithBounds(delegate, context, parent, gfx::Rect()); -} - -// static -Widget* DialogDelegate::CreateDialogWidgetWithBounds(WidgetDelegate* delegate, - gfx::NativeWindow context, - gfx::NativeView parent, - const gfx::Rect& bounds) { - views::Widget* widget = new views::Widget; - views::Widget::InitParams params; - params.delegate = delegate; - params.bounds = bounds; - DialogDelegate* dialog = delegate->AsDialogDelegate(); - -#if defined(OS_LINUX) && !defined(OS_CHROMEOS) - // The new style doesn't support unparented dialogs on Linux desktop. - if (dialog) - dialog->supports_new_style_ &= parent != NULL; -#elif defined(OS_WIN) - // The new style doesn't support unparented dialogs on Windows Classic themes. - if (dialog && !ui::win::IsAeroGlassEnabled()) - dialog->supports_new_style_ &= parent != NULL; -#endif - - if (!dialog || dialog->UseNewStyleForThisDialog()) { - params.opacity = Widget::InitParams::TRANSLUCENT_WINDOW; - params.remove_standard_frame = true; - // The bubble frame includes its own shadow; remove any native shadowing. - params.shadow_type = views::Widget::InitParams::SHADOW_TYPE_NONE; - } - params.context = context; - params.parent = parent; - // Web-modal (ui::MODAL_TYPE_CHILD) dialogs with parents are marked as child - // widgets to prevent top-level window behavior (independent movement, etc). - params.child = parent && (delegate->GetModalType() == ui::MODAL_TYPE_CHILD); - widget->Init(params); - return widget; -} - -View* DialogDelegate::CreateExtraView() { - return NULL; -} - -View* DialogDelegate::CreateTitlebarExtraView() { - return NULL; -} - -View* DialogDelegate::CreateFootnoteView() { - return NULL; -} - -bool DialogDelegate::Cancel() { - return true; -} - -bool DialogDelegate::Accept(bool window_closing) { - return Accept(); -} - -bool DialogDelegate::Accept() { - return true; -} - -bool DialogDelegate::Close() { - int buttons = GetDialogButtons(); - if ((buttons & ui::DIALOG_BUTTON_CANCEL) || - (buttons == ui::DIALOG_BUTTON_NONE)) { - return Cancel(); - } - return Accept(true); -} - -base::string16 DialogDelegate::GetDialogLabel() const { - return base::string16(); -} - -base::string16 DialogDelegate::GetDialogTitle() const { - return GetWindowTitle(); -} - -int DialogDelegate::GetDialogButtons() const { - return ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL; -} - -int DialogDelegate::GetDefaultDialogButton() const { - if (GetDialogButtons() & ui::DIALOG_BUTTON_OK) - return ui::DIALOG_BUTTON_OK; - if (GetDialogButtons() & ui::DIALOG_BUTTON_CANCEL) - return ui::DIALOG_BUTTON_CANCEL; - return ui::DIALOG_BUTTON_NONE; -} - -bool DialogDelegate::ShouldDefaultButtonBeBlue() const { - return false; -} - -base::string16 DialogDelegate::GetDialogButtonLabel( - ui::DialogButton button) const { - if (button == ui::DIALOG_BUTTON_OK) - return l10n_util::GetStringUTF16(IDS_APP_OK); - if (button == ui::DIALOG_BUTTON_CANCEL) { - if (GetDialogButtons() & ui::DIALOG_BUTTON_OK) - return l10n_util::GetStringUTF16(IDS_APP_CANCEL); - return l10n_util::GetStringUTF16(IDS_APP_CLOSE); - } - NOTREACHED(); - return base::string16(); -} - -bool DialogDelegate::IsDialogButtonEnabled(ui::DialogButton button) const { - return true; -} - -View* DialogDelegate::GetInitiallyFocusedView() { - // Focus the default button if any. - const DialogClientView* dcv = GetDialogClientView(); - int default_button = GetDefaultDialogButton(); - if (default_button == ui::DIALOG_BUTTON_NONE) - return NULL; - - if ((default_button & GetDialogButtons()) == 0) { - // The default button is a button we don't have. - NOTREACHED(); - return NULL; - } - - if (default_button & ui::DIALOG_BUTTON_OK) - return dcv->ok_button(); - if (default_button & ui::DIALOG_BUTTON_CANCEL) - return dcv->cancel_button(); - return NULL; -} - -DialogDelegate* DialogDelegate::AsDialogDelegate() { - return this; -} - -ClientView* DialogDelegate::CreateClientView(Widget* widget) { - return new DialogClientView(widget, GetContentsView()); -} - -NonClientFrameView* DialogDelegate::CreateNonClientFrameView(Widget* widget) { - if (UseNewStyleForThisDialog()) - return CreateDialogFrameView(widget); - return WidgetDelegate::CreateNonClientFrameView(widget); -} - -// static -NonClientFrameView* DialogDelegate::CreateDialogFrameView(Widget* widget) { - BubbleFrameView* frame = new BubbleFrameView(gfx::Insets()); - scoped_ptr<BubbleBorder> border(new BubbleBorder( - BubbleBorder::FLOAT, BubbleBorder::SMALL_SHADOW, SK_ColorRED)); - border->set_use_theme_background_color(true); - frame->SetBubbleBorder(border.Pass()); - DialogDelegate* delegate = widget->widget_delegate()->AsDialogDelegate(); - if (delegate) { - View* titlebar_view = delegate->CreateTitlebarExtraView(); - if (titlebar_view) - frame->SetTitlebarExtraView(titlebar_view); - } - return frame; -} - -bool DialogDelegate::UseNewStyleForThisDialog() const { - return supports_new_style_; -} - -const DialogClientView* DialogDelegate::GetDialogClientView() const { - return GetWidget()->client_view()->AsDialogClientView(); -} - -DialogClientView* DialogDelegate::GetDialogClientView() { - return GetWidget()->client_view()->AsDialogClientView(); -} - -ui::AXRole DialogDelegate::GetAccessibleWindowRole() const { - return ui::AX_ROLE_DIALOG; -} - -//////////////////////////////////////////////////////////////////////////////// -// DialogDelegateView: - -DialogDelegateView::DialogDelegateView() { - // A WidgetDelegate should be deleted on DeleteDelegate. - set_owned_by_client(); -} - -DialogDelegateView::~DialogDelegateView() {} - -void DialogDelegateView::DeleteDelegate() { - delete this; -} - -Widget* DialogDelegateView::GetWidget() { - return View::GetWidget(); -} - -const Widget* DialogDelegateView::GetWidget() const { - return View::GetWidget(); -} - -View* DialogDelegateView::GetContentsView() { - return this; -} - -} // namespace views
diff --git a/ui/views/window/dialog_delegate.h b/ui/views/window/dialog_delegate.h deleted file mode 100644 index d2294c2..0000000 --- a/ui/views/window/dialog_delegate.h +++ /dev/null
@@ -1,146 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_WINDOW_DIALOG_DELEGATE_H_ -#define UI_VIEWS_WINDOW_DIALOG_DELEGATE_H_ - -#include "base/compiler_specific.h" -#include "base/strings/string16.h" -#include "ui/accessibility/ax_enums.h" -#include "ui/base/models/dialog_model.h" -#include "ui/base/ui_base_types.h" -#include "ui/views/widget/widget_delegate.h" - -namespace views { - -class DialogClientView; - -/////////////////////////////////////////////////////////////////////////////// -// -// DialogDelegate -// -// DialogDelegate is an interface implemented by objects that wish to show a -// dialog box Window. The window that is displayed uses this interface to -// determine how it should be displayed and notify the delegate object of -// certain events. -// -/////////////////////////////////////////////////////////////////////////////// -class VIEWS_EXPORT DialogDelegate : public ui::DialogModel, - public WidgetDelegate { - public: - DialogDelegate(); - virtual ~DialogDelegate(); - - // Same as CreateDialogWidgetWithBounds() with an empty |bounds|. - static Widget* CreateDialogWidget(WidgetDelegate* delegate, - gfx::NativeWindow context, - gfx::NativeView parent); - - // Create a dialog widget with the specified |context| or |parent|. - // If |bounds| is not empty, used to initially place the dialog, otherwise - // a default location is used. - static Widget* CreateDialogWidgetWithBounds(WidgetDelegate* delegate, - gfx::NativeWindow context, - gfx::NativeView parent, - const gfx::Rect& bounds); - - // Override this function to display an extra view adjacent to the buttons. - // Overrides may construct the view; this will only be called once per dialog. - virtual View* CreateExtraView(); - - // Override this function to display an extra view in the titlebar. - // Overrides may construct the view; this will only be called once per dialog. - // Note: this only works for new style dialogs. - virtual View* CreateTitlebarExtraView(); - - // Override this function to display a footnote view below the buttons. - // Overrides may construct the view; this will only be called once per dialog. - virtual View* CreateFootnoteView(); - - // For Dialog boxes, if there is a "Cancel" button or no dialog button at all, - // this is called when the user presses the "Cancel" button or the Esc key. - // It can also be called on a close action if |Close| has not been - // overridden. This function should return true if the window can be closed - // after it returns, or false if it must remain open. - virtual bool Cancel(); - - // For Dialog boxes, this is called when the user presses the "OK" button, - // or the Enter key. It can also be called on a close action if |Close| - // has not been overridden. This function should return true if the window - // can be closed after it returns, or false if it must remain open. - // If |window_closing| is true, it means that this handler is - // being called because the window is being closed (e.g. by Window::Close) - // and there is no Cancel handler, so Accept is being called instead. - virtual bool Accept(bool window_closing); - virtual bool Accept(); - - // Called when the user closes the window without selecting an option, - // e.g. by pressing the close button on the window or using a window manager - // gesture. By default, this calls Accept() if the only button in the dialog - // is Accept, Cancel() otherwise. This function should return true if the - // window can be closed after it returns, or false if it must remain open. - virtual bool Close(); - - // Overridden from ui::DialogModel: - virtual base::string16 GetDialogLabel() const override; - virtual base::string16 GetDialogTitle() const override; - virtual int GetDialogButtons() const override; - virtual int GetDefaultDialogButton() const override; - virtual bool ShouldDefaultButtonBeBlue() const override; - virtual base::string16 GetDialogButtonLabel( - ui::DialogButton button) const override; - virtual bool IsDialogButtonEnabled(ui::DialogButton button) const override; - - // Overridden from WidgetDelegate: - virtual View* GetInitiallyFocusedView() override; - virtual DialogDelegate* AsDialogDelegate() override; - virtual ClientView* CreateClientView(Widget* widget) override; - virtual NonClientFrameView* CreateNonClientFrameView(Widget* widget) override; - - // Create a frame view using the new dialog style. - static NonClientFrameView* CreateDialogFrameView(Widget* widget); - - // Returns whether this particular dialog should use the new dialog style. - virtual bool UseNewStyleForThisDialog() const; - - // Called when the window has been closed. - virtual void OnClosed() {} - - // A helper for accessing the DialogClientView object contained by this - // delegate's Window. - const DialogClientView* GetDialogClientView() const; - DialogClientView* GetDialogClientView(); - - protected: - // Overridden from WidgetDelegate: - virtual ui::AXRole GetAccessibleWindowRole() const override; - - private: - // A flag indicating whether this dialog supports the new style. - bool supports_new_style_; -}; - -// A DialogDelegate implementation that is-a View. Used to override GetWidget() -// to call View's GetWidget() for the common case where a DialogDelegate -// implementation is-a View. Note that DialogDelegateView is not owned by -// view's hierarchy and is expected to be deleted on DeleteDelegate call. -class VIEWS_EXPORT DialogDelegateView : public DialogDelegate, - public View { - public: - DialogDelegateView(); - virtual ~DialogDelegateView(); - - // Overridden from DialogDelegate: - virtual void DeleteDelegate() override; - virtual Widget* GetWidget() override; - virtual const Widget* GetWidget() const override; - virtual View* GetContentsView() override; - - private: - DISALLOW_COPY_AND_ASSIGN(DialogDelegateView); -}; - -} // namespace views - -#endif // UI_VIEWS_WINDOW_DIALOG_DELEGATE_H_
diff --git a/ui/views/window/dialog_delegate_unittest.cc b/ui/views/window/dialog_delegate_unittest.cc deleted file mode 100644 index 7bbf191..0000000 --- a/ui/views/window/dialog_delegate_unittest.cc +++ /dev/null
@@ -1,231 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/strings/utf_string_conversions.h" -#include "ui/base/hit_test.h" -#include "ui/views/bubble/bubble_border.h" -#include "ui/views/bubble/bubble_frame_view.h" -#include "ui/views/controls/button/checkbox.h" -#include "ui/views/controls/button/label_button.h" -#include "ui/views/test/views_test_base.h" -#include "ui/views/widget/widget.h" -#include "ui/views/window/dialog_client_view.h" -#include "ui/views/window/dialog_delegate.h" - -namespace views { - -namespace { - -class TestDialog : public DialogDelegateView, public ButtonListener { - public: - TestDialog() - : canceled_(false), - accepted_(false), - closeable_(false), - last_pressed_button_(NULL) {} - virtual ~TestDialog() {} - - // DialogDelegateView overrides: - virtual bool Cancel() override { - canceled_ = true; - return closeable_; - } - virtual bool Accept() override { - accepted_ = true; - return closeable_; - } - - // DialogDelegateView overrides: - virtual gfx::Size GetPreferredSize() const override { - return gfx::Size(200, 200); - } - virtual base::string16 GetWindowTitle() const override { return title_; } - virtual bool UseNewStyleForThisDialog() const override { return true; } - - // ButtonListener override: - virtual void ButtonPressed(Button* sender, const ui::Event& event) override { - last_pressed_button_ = sender; - } - - Button* last_pressed_button() const { return last_pressed_button_; } - - void PressEnterAndCheckStates(Button* button) { - ui::KeyEvent key_event(ui::ET_KEY_PRESSED, ui::VKEY_RETURN, ui::EF_NONE); - GetFocusManager()->OnKeyEvent(key_event); - const DialogClientView* client_view = GetDialogClientView(); - EXPECT_EQ(canceled_, client_view->cancel_button()->is_default()); - EXPECT_EQ(accepted_, client_view->ok_button()->is_default()); - // This view does not listen for ok or cancel clicks, DialogClientView does. - CheckAndResetStates(button == client_view->cancel_button(), - button == client_view->ok_button(), - (canceled_ || accepted_ ) ? NULL : button); - } - - void CheckAndResetStates(bool canceled, bool accepted, Button* last_pressed) { - EXPECT_EQ(canceled, canceled_); - canceled_ = false; - EXPECT_EQ(accepted, accepted_); - accepted_ = false; - EXPECT_EQ(last_pressed, last_pressed_button_); - last_pressed_button_ = NULL; - } - - void TearDown() { - closeable_ = true; - GetWidget()->Close(); - } - - void set_title(const base::string16& title) { title_ = title; } - - private: - bool canceled_; - bool accepted_; - // Prevent the dialog from closing, for repeated ok and cancel button clicks. - bool closeable_; - Button* last_pressed_button_; - base::string16 title_; - - DISALLOW_COPY_AND_ASSIGN(TestDialog); -}; - -class DialogTest : public ViewsTestBase { - public: - DialogTest() : dialog_(NULL) {} - virtual ~DialogTest() {} - - virtual void SetUp() override { - ViewsTestBase::SetUp(); - dialog_ = new TestDialog(); - DialogDelegate::CreateDialogWidget(dialog_, GetContext(), NULL)->Show(); - } - - virtual void TearDown() override { - dialog_->TearDown(); - ViewsTestBase::TearDown(); - } - - TestDialog* dialog() const { return dialog_; } - - private: - TestDialog* dialog_; - - DISALLOW_COPY_AND_ASSIGN(DialogTest); -}; - -} // namespace - -TEST_F(DialogTest, DefaultButtons) { - DialogClientView* client_view = dialog()->GetDialogClientView(); - LabelButton* ok_button = client_view->ok_button(); - - // DialogDelegate's default button (ok) should be default (and handle enter). - EXPECT_EQ(ui::DIALOG_BUTTON_OK, dialog()->GetDefaultDialogButton()); - dialog()->PressEnterAndCheckStates(ok_button); - - // Focus another button in the dialog, it should become the default. - LabelButton* button_1 = new LabelButton(dialog(), base::string16()); - client_view->AddChildView(button_1); - client_view->OnWillChangeFocus(ok_button, button_1); - EXPECT_TRUE(button_1->is_default()); - dialog()->PressEnterAndCheckStates(button_1); - - // Focus a Checkbox (not a push button), OK should become the default again. - Checkbox* checkbox = new Checkbox(base::string16()); - client_view->AddChildView(checkbox); - client_view->OnWillChangeFocus(button_1, checkbox); - EXPECT_FALSE(button_1->is_default()); - dialog()->PressEnterAndCheckStates(ok_button); - - // Focus yet another button in the dialog, it should become the default. - LabelButton* button_2 = new LabelButton(dialog(), base::string16()); - client_view->AddChildView(button_2); - client_view->OnWillChangeFocus(checkbox, button_2); - EXPECT_FALSE(button_1->is_default()); - EXPECT_TRUE(button_2->is_default()); - dialog()->PressEnterAndCheckStates(button_2); - - // Focus nothing, OK should become the default again. - client_view->OnWillChangeFocus(button_2, NULL); - EXPECT_FALSE(button_1->is_default()); - EXPECT_FALSE(button_2->is_default()); - dialog()->PressEnterAndCheckStates(ok_button); -} - -TEST_F(DialogTest, AcceptAndCancel) { - DialogClientView* client_view = dialog()->GetDialogClientView(); - LabelButton* ok_button = client_view->ok_button(); - LabelButton* cancel_button = client_view->cancel_button(); - - // Check that return/escape accelerators accept/cancel dialogs. - const ui::KeyEvent return_key( - ui::ET_KEY_PRESSED, ui::VKEY_RETURN, ui::EF_NONE); - dialog()->GetFocusManager()->OnKeyEvent(return_key); - dialog()->CheckAndResetStates(false, true, NULL); - const ui::KeyEvent escape_key( - ui::ET_KEY_PRESSED, ui::VKEY_ESCAPE, ui::EF_NONE); - dialog()->GetFocusManager()->OnKeyEvent(escape_key); - dialog()->CheckAndResetStates(true, false, NULL); - - // Check ok and cancel button behavior on a directed return key events. - ok_button->OnKeyPressed(return_key); - dialog()->CheckAndResetStates(false, true, NULL); - cancel_button->OnKeyPressed(return_key); - dialog()->CheckAndResetStates(true, false, NULL); - - // Check that return accelerators cancel dialogs if cancel is focused. - cancel_button->RequestFocus(); - dialog()->GetFocusManager()->OnKeyEvent(return_key); - dialog()->CheckAndResetStates(true, false, NULL); -} - -TEST_F(DialogTest, RemoveDefaultButton) { - // Removing buttons from the dialog here should not cause a crash on close. - delete dialog()->GetDialogClientView()->ok_button(); - delete dialog()->GetDialogClientView()->cancel_button(); -} - -TEST_F(DialogTest, HitTest) { - // Ensure that the new style's BubbleFrameView hit-tests as expected. - const NonClientView* view = dialog()->GetWidget()->non_client_view(); - BubbleFrameView* frame = static_cast<BubbleFrameView*>(view->frame_view()); - const int border = frame->bubble_border()->GetBorderThickness(); - - struct { - const int point; - const int hit; - } cases[] = { - { border, HTSYSMENU }, - { border + 10, HTSYSMENU }, - { border + 20, HTCAPTION }, - { border + 40, HTCLIENT }, - { border + 50, HTCLIENT }, - { 1000, HTNOWHERE }, - }; - - for (size_t i = 0; i < arraysize(cases); ++i) { - gfx::Point point(cases[i].point, cases[i].point); - EXPECT_EQ(cases[i].hit, frame->NonClientHitTest(point)) - << " with border: " << border << ", at point " << cases[i].point; - } -} - -TEST_F(DialogTest, BoundsAccommodateTitle) { - TestDialog* dialog2(new TestDialog()); - dialog2->set_title(base::ASCIIToUTF16("Title")); - DialogDelegate::CreateDialogWidget(dialog2, GetContext(), NULL); - - // Titled dialogs have taller initial frame bounds than untitled dialogs. - View* frame1 = dialog()->GetWidget()->non_client_view()->frame_view(); - View* frame2 = dialog2->GetWidget()->non_client_view()->frame_view(); - EXPECT_LT(frame1->GetPreferredSize().height(), - frame2->GetPreferredSize().height()); - - // Giving the default test dialog a title will yield the same bounds. - dialog()->set_title(base::ASCIIToUTF16("Title")); - dialog()->GetWidget()->UpdateWindowTitle(); - EXPECT_EQ(frame1->GetPreferredSize().height(), - frame2->GetPreferredSize().height()); -} - -} // namespace views
diff --git a/ui/views/window/frame_background.cc b/ui/views/window/frame_background.cc deleted file mode 100644 index a325dbf..0000000 --- a/ui/views/window/frame_background.cc +++ /dev/null
@@ -1,174 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/window/frame_background.h" - -#include "third_party/skia/include/core/SkCanvas.h" -#include "third_party/skia/include/core/SkColor.h" -#include "ui/base/theme_provider.h" -#include "ui/gfx/canvas.h" -#include "ui/views/view.h" - -namespace views { - -FrameBackground::FrameBackground() - : frame_color_(0), - theme_image_(NULL), - theme_overlay_image_(NULL), - top_area_height_(0), - left_edge_(NULL), - top_edge_(NULL), - right_edge_(NULL), - bottom_edge_(NULL), - top_left_corner_(NULL), - top_right_corner_(NULL), - bottom_left_corner_(NULL), - bottom_right_corner_(NULL), - maximized_top_inset_(0) { -} - -FrameBackground::~FrameBackground() { -} - -void FrameBackground::SetSideImages(const gfx::ImageSkia* left, - const gfx::ImageSkia* top, - const gfx::ImageSkia* right, - const gfx::ImageSkia* bottom) { - left_edge_ = left; - top_edge_ = top; - right_edge_ = right; - bottom_edge_ = bottom; -} - -void FrameBackground::SetCornerImages(const gfx::ImageSkia* top_left, - const gfx::ImageSkia* top_right, - const gfx::ImageSkia* bottom_left, - const gfx::ImageSkia* bottom_right) { - top_left_corner_ = top_left; - top_right_corner_ = top_right; - bottom_left_corner_ = bottom_left; - bottom_right_corner_ = bottom_right; -} - -void FrameBackground::PaintRestored(gfx::Canvas* canvas, View* view) const { - // Fill with the frame color first so we have a constant background for - // areas not covered by the theme image. - PaintFrameColor(canvas, view); - - // Draw the theme frame. - canvas->TileImageInt(*theme_image_, - 0, 0, view->width(), theme_image_->height()); - - // Draw the theme frame overlay, if available. - if (theme_overlay_image_) - canvas->DrawImageInt(*theme_overlay_image_, 0, 0); - - // Draw the top corners and edge, scaling the corner images down if they - // are too big and relative to the vertical space available. - int top_left_height = - std::min(top_left_corner_->height(), - view->height() - bottom_left_corner_->height()); - canvas->DrawImageInt(*top_left_corner_, - 0, 0, top_left_corner_->width(), top_left_height, - 0, 0, top_left_corner_->width(), top_left_height, - false); - canvas->TileImageInt(*top_edge_, - top_left_corner_->width(), - 0, - view->width() - top_left_corner_->width() - top_right_corner_->width(), - top_edge_->height()); - int top_right_height = - std::min(top_right_corner_->height(), - view->height() - bottom_right_corner_->height()); - canvas->DrawImageInt(*top_right_corner_, - 0, 0, - top_right_corner_->width(), top_right_height, - view->width() - top_right_corner_->width(), 0, - top_right_corner_->width(), top_right_height, - false); - - // Right edge. - int right_edge_height = - view->height() - top_right_height - bottom_right_corner_->height(); - canvas->TileImageInt(*right_edge_, - view->width() - right_edge_->width(), - top_right_height, - right_edge_->width(), - right_edge_height); - - // Bottom corners and edge. - canvas->DrawImageInt(*bottom_right_corner_, - view->width() - bottom_right_corner_->width(), - view->height() - bottom_right_corner_->height()); - canvas->TileImageInt( - *bottom_edge_, - bottom_left_corner_->width(), - view->height() - bottom_edge_->height(), - view->width() - bottom_left_corner_->width() - - bottom_right_corner_->width(), - bottom_edge_->height()); - canvas->DrawImageInt(*bottom_left_corner_, 0, - view->height() - bottom_left_corner_->height()); - - // Left edge. - int left_edge_height = - view->height() - top_left_height - bottom_left_corner_->height(); - canvas->TileImageInt(*left_edge_, - 0, top_left_height, - left_edge_->width(), left_edge_height); -} - -void FrameBackground::PaintMaximized(gfx::Canvas* canvas, View* view) const { - // We will be painting from -|maximized_top_inset_| to - // -|maximized_top_inset_| + |theme_image_|->height(). If this is less than - // |top_area_height_|, we need to paint the frame color to fill in the area - // beneath the image. - int theme_frame_bottom = -maximized_top_inset_ + theme_image_->height(); - if (top_area_height_ > theme_frame_bottom) { - canvas->FillRect(gfx::Rect(0, 0, view->width(), top_area_height_), - frame_color_); - } - - // Draw the theme frame. - canvas->TileImageInt(*theme_image_, - 0, - -maximized_top_inset_, - view->width(), - theme_image_->height()); - // Draw the theme frame overlay, if available. - if (theme_overlay_image_) - canvas->DrawImageInt(*theme_overlay_image_, 0, -maximized_top_inset_); -} - -void FrameBackground::PaintFrameColor(gfx::Canvas* canvas, View* view) const { - // Fill the top area. - canvas->FillRect(gfx::Rect(0, 0, view->width(), top_area_height_), - frame_color_); - - // If the window is very short, we're done. - int remaining_height = view->height() - top_area_height_; - if (remaining_height <= 0) - return; - - // Fill down the sides. - canvas->FillRect(gfx::Rect(0, top_area_height_, left_edge_->width(), - remaining_height), frame_color_); - canvas->FillRect(gfx::Rect(view->width() - right_edge_->width(), - top_area_height_, right_edge_->width(), - remaining_height), frame_color_); - - // If the window is very narrow, we're done. - int center_width = - view->width() - left_edge_->width() - right_edge_->width(); - if (center_width <= 0) - return; - - // Fill the bottom area. - canvas->FillRect(gfx::Rect(left_edge_->width(), - view->height() - bottom_edge_->height(), - center_width, bottom_edge_->height()), - frame_color_); -} - -} // namespace views
diff --git a/ui/views/window/frame_background.h b/ui/views/window/frame_background.h deleted file mode 100644 index bdabf51..0000000 --- a/ui/views/window/frame_background.h +++ /dev/null
@@ -1,102 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_WINDOW_FRAME_BACKGROUND_H_ -#define UI_VIEWS_WINDOW_FRAME_BACKGROUND_H_ - -#include "base/basictypes.h" -#include "third_party/skia/include/core/SkColor.h" -#include "ui/views/views_export.h" - -namespace gfx { -class Canvas; -class ImageSkia; -} - -namespace views { - -class View; - -// FrameBackground handles painting for all the various window frames we -// support in Chrome. It intends to consolidate paint code that historically -// was copied. One frame to rule them all! -class VIEWS_EXPORT FrameBackground { - public: - FrameBackground(); - ~FrameBackground(); - - // Sets the color to draw under the frame images. - void set_frame_color(SkColor color) { frame_color_ = color; } - - // Sets the theme image for the top of the window. May be NULL. - // Memory is owned by the caller. - void set_theme_image(const gfx::ImageSkia* image) { theme_image_ = image; } - - // Sets an image that overlays the top window image. Usually used to add - // edge highlighting to provide the illusion of depth. May be NULL. - // Memory is owned by the caller. - void set_theme_overlay_image(gfx::ImageSkia* image) { - theme_overlay_image_ = image; - } - - // Sets the height of the top area to fill with the default frame color, - // which must extend behind the tab strip. - void set_top_area_height(int height) { top_area_height_ = height; } - - // Vertical inset for theme image when drawing maximized. - void set_maximized_top_inset(int inset) { maximized_top_inset_ = inset; } - - // Sets images used when drawing the sides of the frame. - // Caller owns the memory. - void SetSideImages(const gfx::ImageSkia* left, - const gfx::ImageSkia* top, - const gfx::ImageSkia* right, - const gfx::ImageSkia* bottom); - - // Sets images used when drawing the corners of the frame. - // Caller owns the memory. - void SetCornerImages(const gfx::ImageSkia* top_left, - const gfx::ImageSkia* top_right, - const gfx::ImageSkia* bottom_left, - const gfx::ImageSkia* bottom_right); - - // Paints the border for a standard, non-maximized window. Also paints the - // background of the title bar area, since the top frame border and the - // title bar background are a contiguous component. - void PaintRestored(gfx::Canvas* canvas, View* view) const; - - // Paints the border for a maximized window, which does not include the - // window edges. - void PaintMaximized(gfx::Canvas* canvas, View* view) const; - - private: - // Fills the frame area with the frame color. - void PaintFrameColor(gfx::Canvas* canvas, View* view) const; - - SkColor frame_color_; - const gfx::ImageSkia* theme_image_; - gfx::ImageSkia* theme_overlay_image_; - int top_area_height_; - - // Images for the sides of the frame. - const gfx::ImageSkia* left_edge_; - const gfx::ImageSkia* top_edge_; - const gfx::ImageSkia* right_edge_; - const gfx::ImageSkia* bottom_edge_; - - // Images for the corners of the frame. - const gfx::ImageSkia* top_left_corner_; - const gfx::ImageSkia* top_right_corner_; - const gfx::ImageSkia* bottom_left_corner_; - const gfx::ImageSkia* bottom_right_corner_; - - // Vertical inset for theme image when drawing maximized. - int maximized_top_inset_; - - DISALLOW_COPY_AND_ASSIGN(FrameBackground); -}; - -} // namespace views - -#endif // UI_VIEWS_WINDOW_FRAME_BACKGROUND_H_
diff --git a/ui/views/window/frame_buttons.h b/ui/views/window/frame_buttons.h deleted file mode 100644 index d534356..0000000 --- a/ui/views/window/frame_buttons.h +++ /dev/null
@@ -1,19 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_WINDOW_FRAME_BUTTONS_H_ -#define UI_VIEWS_WINDOW_FRAME_BUTTONS_H_ - -namespace views { - -// Identifies what a button in a window frame is. -enum FrameButton { - FRAME_BUTTON_MINIMIZE, - FRAME_BUTTON_MAXIMIZE, - FRAME_BUTTON_CLOSE -}; - -} // namespace views - -#endif // UI_VIEWS_WINDOW_FRAME_BUTTONS_H_
diff --git a/ui/views/window/native_frame_view.cc b/ui/views/window/native_frame_view.cc deleted file mode 100644 index fb37b6f..0000000 --- a/ui/views/window/native_frame_view.cc +++ /dev/null
@@ -1,103 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/window/native_frame_view.h" - -#include "ui/views/widget/native_widget.h" -#include "ui/views/widget/widget.h" - -#if defined(OS_WIN) -#include "ui/views/win/hwnd_util.h" -#endif - -namespace views { - -//////////////////////////////////////////////////////////////////////////////// -// NativeFrameView, public: - -// static -const char NativeFrameView::kViewClassName[] = "NativeFrameView"; - -NativeFrameView::NativeFrameView(Widget* frame) - : NonClientFrameView(), - frame_(frame) { -} - -NativeFrameView::~NativeFrameView() { -} - -//////////////////////////////////////////////////////////////////////////////// -// NativeFrameView, NonClientFrameView overrides: - -gfx::Rect NativeFrameView::GetBoundsForClientView() const { - return gfx::Rect(0, 0, width(), height()); -} - -gfx::Rect NativeFrameView::GetWindowBoundsForClientBounds( - const gfx::Rect& client_bounds) const { -#if defined(OS_WIN) - return views::GetWindowBoundsForClientBounds( - static_cast<View*>(const_cast<NativeFrameView*>(this)), client_bounds); -#else - // Enforce minimum size (1, 1) in case that |client_bounds| is passed with - // empty size. - gfx::Rect window_bounds = client_bounds; - if (window_bounds.IsEmpty()) - window_bounds.set_size(gfx::Size(1,1)); - return window_bounds; -#endif -} - -int NativeFrameView::NonClientHitTest(const gfx::Point& point) { - return frame_->client_view()->NonClientHitTest(point); -} - -void NativeFrameView::GetWindowMask(const gfx::Size& size, - gfx::Path* window_mask) { - // Nothing to do, we use the default window mask. -} - -void NativeFrameView::ResetWindowControls() { - // Nothing to do. -} - -void NativeFrameView::UpdateWindowIcon() { - // Nothing to do. -} - -void NativeFrameView::UpdateWindowTitle() { - // Nothing to do. -} - -void NativeFrameView::SizeConstraintsChanged() { - // Nothing to do. -} - -gfx::Size NativeFrameView::GetPreferredSize() const { - gfx::Size client_preferred_size = frame_->client_view()->GetPreferredSize(); -#if defined(OS_WIN) - // Returns the client size. On Windows, this is the expected behavior for - // native frames (see |NativeWidgetWin::WidgetSizeIsClientSize()|), while - // other platforms currently always return client bounds from - // |GetWindowBoundsForClientBounds()|. - return client_preferred_size; -#else - return frame_->non_client_view()->GetWindowBoundsForClientBounds( - gfx::Rect(client_preferred_size)).size(); -#endif -} - -gfx::Size NativeFrameView::GetMinimumSize() const { - return frame_->client_view()->GetMinimumSize(); -} - -gfx::Size NativeFrameView::GetMaximumSize() const { - return frame_->client_view()->GetMaximumSize(); -} - -const char* NativeFrameView::GetClassName() const { - return kViewClassName; -} - -} // namespace views
diff --git a/ui/views/window/native_frame_view.h b/ui/views/window/native_frame_view.h deleted file mode 100644 index 3f4d09a..0000000 --- a/ui/views/window/native_frame_view.h +++ /dev/null
@@ -1,48 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_WINDOW_NATIVE_FRAME_VIEW_H_ -#define UI_VIEWS_WINDOW_NATIVE_FRAME_VIEW_H_ - -#include "ui/views/window/non_client_view.h" - -namespace views { - -class Widget; - -class VIEWS_EXPORT NativeFrameView : public NonClientFrameView { - public: - static const char kViewClassName[]; - - explicit NativeFrameView(Widget* frame); - virtual ~NativeFrameView(); - - // NonClientFrameView overrides: - virtual gfx::Rect GetBoundsForClientView() const override; - virtual gfx::Rect GetWindowBoundsForClientBounds( - const gfx::Rect& client_bounds) const override; - virtual int NonClientHitTest(const gfx::Point& point) override; - virtual void GetWindowMask(const gfx::Size& size, - gfx::Path* window_mask) override; - virtual void ResetWindowControls() override; - virtual void UpdateWindowIcon() override; - virtual void UpdateWindowTitle() override; - virtual void SizeConstraintsChanged() override; - - // View overrides: - virtual gfx::Size GetPreferredSize() const override; - virtual gfx::Size GetMinimumSize() const override; - virtual gfx::Size GetMaximumSize() const override; - virtual const char* GetClassName() const override; - - private: - // Our containing frame. - Widget* frame_; - - DISALLOW_COPY_AND_ASSIGN(NativeFrameView); -}; - -} // namespace views - -#endif // UI_VIEWS_WINDOW_NATIVE_FRAME_VIEW_H_
diff --git a/ui/views/window/non_client_view.cc b/ui/views/window/non_client_view.cc deleted file mode 100644 index b8f1ce0..0000000 --- a/ui/views/window/non_client_view.cc +++ /dev/null
@@ -1,343 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/window/non_client_view.h" - -#include "ui/accessibility/ax_view_state.h" -#include "ui/base/hit_test.h" -#include "ui/gfx/rect_conversions.h" -#include "ui/views/rect_based_targeting_utils.h" -#include "ui/views/view_targeter.h" -#include "ui/views/widget/root_view.h" -#include "ui/views/widget/widget.h" -#include "ui/views/window/client_view.h" - -namespace views { - -// static -const char NonClientFrameView::kViewClassName[] = - "ui/views/window/NonClientFrameView"; - -const char NonClientView::kViewClassName[] = - "ui/views/window/NonClientView"; - -// The frame view and the client view are always at these specific indices, -// because the RootView message dispatch sends messages to items higher in the -// z-order first and we always want the client view to have first crack at -// handling mouse messages. -static const int kFrameViewIndex = 0; -static const int kClientViewIndex = 1; -// The overlay view is always on top (index == child_count() - 1). - -//////////////////////////////////////////////////////////////////////////////// -// NonClientView, public: - -NonClientView::NonClientView() - : client_view_(NULL), - overlay_view_(NULL) { - SetEventTargeter( - scoped_ptr<views::ViewTargeter>(new views::ViewTargeter(this))); -} - -NonClientView::~NonClientView() { - // This value may have been reset before the window hierarchy shuts down, - // so we need to manually remove it. - RemoveChildView(frame_view_.get()); -} - -void NonClientView::SetFrameView(NonClientFrameView* frame_view) { - // See comment in header about ownership. - frame_view->set_owned_by_client(); - if (frame_view_.get()) - RemoveChildView(frame_view_.get()); - frame_view_.reset(frame_view); - if (parent()) - AddChildViewAt(frame_view_.get(), kFrameViewIndex); -} - -void NonClientView::SetOverlayView(View* view) { - if (overlay_view_) - RemoveChildView(overlay_view_); - - if (!view) - return; - - overlay_view_ = view; - if (parent()) - AddChildView(overlay_view_); -} - -bool NonClientView::CanClose() { - return client_view_->CanClose(); -} - -void NonClientView::WindowClosing() { - client_view_->WidgetClosing(); -} - -void NonClientView::UpdateFrame() { - Widget* widget = GetWidget(); - SetFrameView(widget->CreateNonClientFrameView()); - widget->ThemeChanged(); - Layout(); - SchedulePaint(); -} - -void NonClientView::SetInactiveRenderingDisabled(bool disable) { - frame_view_->SetInactiveRenderingDisabled(disable); -} - -gfx::Rect NonClientView::GetWindowBoundsForClientBounds( - const gfx::Rect client_bounds) const { - return frame_view_->GetWindowBoundsForClientBounds(client_bounds); -} - -int NonClientView::NonClientHitTest(const gfx::Point& point) { - // The NonClientFrameView is responsible for also asking the ClientView. - return frame_view_->NonClientHitTest(point); -} - -void NonClientView::GetWindowMask(const gfx::Size& size, - gfx::Path* window_mask) { - frame_view_->GetWindowMask(size, window_mask); -} - -void NonClientView::ResetWindowControls() { - frame_view_->ResetWindowControls(); -} - -void NonClientView::UpdateWindowIcon() { - frame_view_->UpdateWindowIcon(); -} - -void NonClientView::UpdateWindowTitle() { - frame_view_->UpdateWindowTitle(); -} - -void NonClientView::SizeConstraintsChanged() { - frame_view_->SizeConstraintsChanged(); -} - -void NonClientView::LayoutFrameView() { - // First layout the NonClientFrameView, which determines the size of the - // ClientView... - frame_view_->SetBounds(0, 0, width(), height()); - - // We need to manually call Layout here because layout for the frame view can - // change independently of the bounds changing - e.g. after the initial - // display of the window the metrics of the native window controls can change, - // which does not change the bounds of the window but requires a re-layout to - // trigger a repaint. We override OnBoundsChanged() for the NonClientFrameView - // to do nothing so that SetBounds above doesn't cause Layout to be called - // twice. - frame_view_->Layout(); -} - -void NonClientView::SetAccessibleName(const base::string16& name) { - accessible_name_ = name; -} - -//////////////////////////////////////////////////////////////////////////////// -// NonClientView, View overrides: - -gfx::Size NonClientView::GetPreferredSize() const { - // TODO(pkasting): This should probably be made to look similar to - // GetMinimumSize() below. This will require implementing GetPreferredSize() - // better in the various frame views. - gfx::Rect client_bounds(gfx::Point(), client_view_->GetPreferredSize()); - return GetWindowBoundsForClientBounds(client_bounds).size(); -} - -gfx::Size NonClientView::GetMinimumSize() const { - return frame_view_->GetMinimumSize(); -} - -gfx::Size NonClientView::GetMaximumSize() const { - return frame_view_->GetMaximumSize(); -} - -void NonClientView::Layout() { - LayoutFrameView(); - - // Then layout the ClientView, using those bounds. - client_view_->SetBoundsRect(frame_view_->GetBoundsForClientView()); - - // We need to manually call Layout on the ClientView as well for the same - // reason as above. - client_view_->Layout(); - - if (overlay_view_ && overlay_view_->visible()) - overlay_view_->SetBoundsRect(GetLocalBounds()); -} - -void NonClientView::ViewHierarchyChanged( - const ViewHierarchyChangedDetails& details) { - // Add our two child views here as we are added to the Widget so that if we - // are subsequently resized all the parent-child relationships are - // established. - if (details.is_add && GetWidget() && details.child == this) { - AddChildViewAt(frame_view_.get(), kFrameViewIndex); - AddChildViewAt(client_view_, kClientViewIndex); - if (overlay_view_) - AddChildView(overlay_view_); - } -} - -void NonClientView::GetAccessibleState(ui::AXViewState* state) { - state->role = ui::AX_ROLE_CLIENT; - state->name = accessible_name_; -} - -const char* NonClientView::GetClassName() const { - return kViewClassName; -} - -View* NonClientView::GetTooltipHandlerForPoint(const gfx::Point& point) { - // The same logic as for |TargetForRect()| applies here. - if (frame_view_->parent() == this) { - // During the reset of the frame_view_ it's possible to be in this code - // after it's been removed from the view hierarchy but before it's been - // removed from the NonClientView. - gfx::Point point_in_child_coords(point); - View::ConvertPointToTarget(this, frame_view_.get(), &point_in_child_coords); - View* handler = - frame_view_->GetTooltipHandlerForPoint(point_in_child_coords); - if (handler) - return handler; - } - - return View::GetTooltipHandlerForPoint(point); -} - -View* NonClientView::TargetForRect(View* root, const gfx::Rect& rect) { - CHECK_EQ(root, this); - - if (!UsePointBasedTargeting(rect)) - return ViewTargeterDelegate::TargetForRect(root, rect); - - // Because of the z-ordering of our child views (the client view is positioned - // over the non-client frame view, if the client view ever overlaps the frame - // view visually (as it does for the browser window), then it will eat - // events for the window controls. We override this method here so that we can - // detect this condition and re-route the events to the non-client frame view. - // The assumption is that the frame view's implementation of HitTest will only - // return true for area not occupied by the client view. - if (frame_view_->parent() == this) { - // During the reset of the frame_view_ it's possible to be in this code - // after it's been removed from the view hierarchy but before it's been - // removed from the NonClientView. - gfx::RectF rect_in_child_coords_f(rect); - View::ConvertRectToTarget(this, frame_view_.get(), &rect_in_child_coords_f); - gfx::Rect rect_in_child_coords = gfx::ToEnclosingRect( - rect_in_child_coords_f); - if (frame_view_->HitTestRect(rect_in_child_coords)) - return frame_view_->GetEventHandlerForRect(rect_in_child_coords); - } - - return ViewTargeterDelegate::TargetForRect(root, rect); -} - -//////////////////////////////////////////////////////////////////////////////// -// NonClientFrameView, public: - -NonClientFrameView::~NonClientFrameView() { -} - -void NonClientFrameView::SetInactiveRenderingDisabled(bool disable) { - if (inactive_rendering_disabled_ == disable) - return; - - bool should_paint_as_active_old = ShouldPaintAsActive(); - inactive_rendering_disabled_ = disable; - - // The widget schedules a paint when the activation changes. - if (should_paint_as_active_old != ShouldPaintAsActive()) - SchedulePaint(); -} - -bool NonClientFrameView::ShouldPaintAsActive() const { - return inactive_rendering_disabled_ || GetWidget()->IsActive(); -} - -int NonClientFrameView::GetHTComponentForFrame(const gfx::Point& point, - int top_resize_border_height, - int resize_border_thickness, - int top_resize_corner_height, - int resize_corner_width, - bool can_resize) { - // Tricky: In XP, native behavior is to return HTTOPLEFT and HTTOPRIGHT for - // a |resize_corner_size|-length strip of both the side and top borders, but - // only to return HTBOTTOMLEFT/HTBOTTOMRIGHT along the bottom border + corner - // (not the side border). Vista goes further and doesn't return these on any - // of the side borders. We allow callers to match either behavior. - int component; - if (point.x() < resize_border_thickness) { - if (point.y() < top_resize_corner_height) - component = HTTOPLEFT; - else if (point.y() >= (height() - resize_border_thickness)) - component = HTBOTTOMLEFT; - else - component = HTLEFT; - } else if (point.x() >= (width() - resize_border_thickness)) { - if (point.y() < top_resize_corner_height) - component = HTTOPRIGHT; - else if (point.y() >= (height() - resize_border_thickness)) - component = HTBOTTOMRIGHT; - else - component = HTRIGHT; - } else if (point.y() < top_resize_border_height) { - if (point.x() < resize_corner_width) - component = HTTOPLEFT; - else if (point.x() >= (width() - resize_corner_width)) - component = HTTOPRIGHT; - else - component = HTTOP; - } else if (point.y() >= (height() - resize_border_thickness)) { - if (point.x() < resize_corner_width) - component = HTBOTTOMLEFT; - else if (point.x() >= (width() - resize_corner_width)) - component = HTBOTTOMRIGHT; - else - component = HTBOTTOM; - } else { - return HTNOWHERE; - } - - // If the window can't be resized, there are no resize boundaries, just - // window borders. - return can_resize ? component : HTBORDER; -} - -void NonClientFrameView::GetAccessibleState(ui::AXViewState* state) { - state->role = ui::AX_ROLE_CLIENT; -} - -const char* NonClientFrameView::GetClassName() const { - return kViewClassName; -} - -//////////////////////////////////////////////////////////////////////////////// -// NonClientFrameView, protected: - -NonClientFrameView::NonClientFrameView() : inactive_rendering_disabled_(false) { - SetEventTargeter( - scoped_ptr<views::ViewTargeter>(new views::ViewTargeter(this))); -} - -// ViewTargeterDelegate: -bool NonClientFrameView::DoesIntersectRect(const View* target, - const gfx::Rect& rect) const { - CHECK_EQ(target, this); - - // For the default case, we assume the non-client frame view never overlaps - // the client view. - return !GetWidget()->client_view()->bounds().Intersects(rect); -} - -void NonClientFrameView::OnBoundsChanged(const gfx::Rect& previous_bounds) { - // Overridden to do nothing. The NonClientView manually calls Layout on the - // FrameView when it is itself laid out, see comment in NonClientView::Layout. -} - -} // namespace views
diff --git a/ui/views/window/non_client_view.h b/ui/views/window/non_client_view.h deleted file mode 100644 index 99a6880..0000000 --- a/ui/views/window/non_client_view.h +++ /dev/null
@@ -1,259 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_WINDOW_NON_CLIENT_VIEW_H_ -#define UI_VIEWS_WINDOW_NON_CLIENT_VIEW_H_ - -#include "ui/views/view.h" -#include "ui/views/view_targeter_delegate.h" - -namespace gfx { -class Path; -} - -namespace views { - -class ClientView; - -//////////////////////////////////////////////////////////////////////////////// -// NonClientFrameView -// -// An object that subclasses NonClientFrameView is a View that renders and -// responds to events within the frame portions of the non-client area of a -// window. This view does _not_ contain the ClientView, but rather is a sibling -// of it. -class VIEWS_EXPORT NonClientFrameView : public View, - public ViewTargeterDelegate { - public: - // Internal class name. - static const char kViewClassName[]; - - enum { - // Various edges of the frame border have a 1 px shadow along their edges; - // in a few cases we shift elements based on this amount for visual appeal. - kFrameShadowThickness = 1, - - // In restored mode, we draw a 1 px edge around the content area inside the - // frame border. - kClientEdgeThickness = 1, - }; - - virtual ~NonClientFrameView(); - - // Sets whether the window should be rendered as active regardless of the - // actual active state. Used when bubbles become active to make their parent - // appear active. A value of true makes the window render as active always, - // false gives normal behavior. - void SetInactiveRenderingDisabled(bool disable); - - // Used to determine if the frame should be painted as active. Keyed off the - // window's actual active state and |inactive_rendering_disabled_|. - bool ShouldPaintAsActive() const; - - // Helper for non-client view implementations to determine which area of the - // window border the specified |point| falls within. The other parameters are - // the size of the sizing edges, and whether or not the window can be - // resized. - int GetHTComponentForFrame(const gfx::Point& point, - int top_resize_border_height, - int resize_border_thickness, - int top_resize_corner_height, - int resize_corner_width, - bool can_resize); - - // Returns the bounds (in this View's parent's coordinates) that the client - // view should be laid out within. - virtual gfx::Rect GetBoundsForClientView() const = 0; - - virtual gfx::Rect GetWindowBoundsForClientBounds( - const gfx::Rect& client_bounds) const = 0; - - // This function must ask the ClientView to do a hittest. We don't do this in - // the parent NonClientView because that makes it more difficult to calculate - // hittests for regions that are partially obscured by the ClientView, e.g. - // HTSYSMENU. - virtual int NonClientHitTest(const gfx::Point& point) = 0; - virtual void GetWindowMask(const gfx::Size& size, - gfx::Path* window_mask) = 0; - virtual void ResetWindowControls() = 0; - virtual void UpdateWindowIcon() = 0; - virtual void UpdateWindowTitle() = 0; - virtual void SizeConstraintsChanged() = 0; - - // View: - virtual void GetAccessibleState(ui::AXViewState* state) override; - virtual const char* GetClassName() const override; - - protected: - NonClientFrameView(); - - // ViewTargeterDelegate: - virtual bool DoesIntersectRect(const View* target, - const gfx::Rect& rect) const override; - - // View: - virtual void OnBoundsChanged(const gfx::Rect& previous_bounds) override; - - private: - // Prevents the non-client frame view from being rendered as inactive when - // true. - bool inactive_rendering_disabled_; -}; - -//////////////////////////////////////////////////////////////////////////////// -// NonClientView -// -// The NonClientView is the logical root of all Views contained within a -// Window, except for the RootView which is its parent and of which it is the -// sole child. The NonClientView has two children, the NonClientFrameView which -// is responsible for painting and responding to events from the non-client -// portions of the window, and the ClientView, which is responsible for the -// same for the client area of the window: -// -// +- views::Widget ------------------------------------+ -// | +- views::RootView ------------------------------+ | -// | | +- views::NonClientView ---------------------+ | | -// | | | +- views::NonClientFrameView subclass ---+ | | | -// | | | | | | | | -// | | | | << all painting and event receiving >> | | | | -// | | | | << of the non-client areas of a >> | | | | -// | | | | << views::Widget. >> | | | | -// | | | | | | | | -// | | | +----------------------------------------+ | | | -// | | | +- views::ClientView or subclass --------+ | | | -// | | | | | | | | -// | | | | << all painting and event receiving >> | | | | -// | | | | << of the client areas of a >> | | | | -// | | | | << views::Widget. >> | | | | -// | | | | | | | | -// | | | +----------------------------------------+ | | | -// | | +--------------------------------------------+ | | -// | +------------------------------------------------+ | -// +----------------------------------------------------+ -// -// The NonClientFrameView and ClientView are siblings because due to theme -// changes the NonClientFrameView may be replaced with different -// implementations (e.g. during the switch from DWM/Aero-Glass to Vista Basic/ -// Classic rendering). -// -class VIEWS_EXPORT NonClientView : public View, public ViewTargeterDelegate { - public: - // Internal class name. - static const char kViewClassName[]; - - NonClientView(); - virtual ~NonClientView(); - - // Returns the current NonClientFrameView instance, or NULL if - // it does not exist. - NonClientFrameView* frame_view() const { return frame_view_.get(); } - - // Replaces the current NonClientFrameView (if any) with the specified one. - void SetFrameView(NonClientFrameView* frame_view); - - // Replaces the current |overlay_view_| (if any) with the specified one. - void SetOverlayView(View* view); - - // Returns true if the ClientView determines that the containing window can be - // closed, false otherwise. - bool CanClose(); - - // Called by the containing Window when it is closed. - void WindowClosing(); - - // Replaces the frame view with a new one. Used when switching window theme - // or frame style. - void UpdateFrame(); - - // Prevents the window from being rendered as deactivated when |disable| is - // true, until called with |disable| false. Used when a sub-window is to be - // shown that shouldn't visually de-activate the window. - void SetInactiveRenderingDisabled(bool disable); - - // Returns the bounds of the window required to display the content area at - // the specified bounds. - gfx::Rect GetWindowBoundsForClientBounds(const gfx::Rect client_bounds) const; - - // Determines the windows HT* code when the mouse cursor is at the - // specified point, in window coordinates. - int NonClientHitTest(const gfx::Point& point); - - // Returns a mask to be used to clip the top level window for the given - // size. This is used to create the non-rectangular window shape. - void GetWindowMask(const gfx::Size& size, gfx::Path* window_mask); - - // Tells the window controls as rendered by the NonClientView to reset - // themselves to a normal state. This happens in situations where the - // containing window does not receive a normal sequences of messages that - // would lead to the controls returning to this normal state naturally, e.g. - // when the window is maximized, minimized or restored. - void ResetWindowControls(); - - // Tells the NonClientView to invalidate the NonClientFrameView's window icon. - void UpdateWindowIcon(); - - // Tells the NonClientView to invalidate the NonClientFrameView's window - // title. - void UpdateWindowTitle(); - - // Called when the size constraints of the window change. - void SizeConstraintsChanged(); - - // Get/Set client_view property. - ClientView* client_view() const { return client_view_; } - void set_client_view(ClientView* client_view) { - client_view_ = client_view; - } - - // Layout just the frame view. This is necessary on Windows when non-client - // metrics such as the position of the window controls changes independently - // of a window resize message. - void LayoutFrameView(); - - // Set the accessible name of this view. - void SetAccessibleName(const base::string16& name); - - // NonClientView, View overrides: - virtual gfx::Size GetPreferredSize() const override; - virtual gfx::Size GetMinimumSize() const override; - virtual gfx::Size GetMaximumSize() const override; - virtual void Layout() override; - virtual void GetAccessibleState(ui::AXViewState* state) override; - virtual const char* GetClassName() const override; - - virtual views::View* GetTooltipHandlerForPoint( - const gfx::Point& point) override; - - protected: - // NonClientView, View overrides: - virtual void ViewHierarchyChanged( - const ViewHierarchyChangedDetails& details) override; - - private: - // ViewTargeterDelegate: - virtual View* TargetForRect(View* root, const gfx::Rect& rect) override; - - // A ClientView object or subclass, responsible for sizing the contents view - // of the window, hit testing and perhaps other tasks depending on the - // implementation. - ClientView* client_view_; - - // The NonClientFrameView that renders the non-client portions of the window. - // This object is not owned by the view hierarchy because it can be replaced - // dynamically as the system settings change. - scoped_ptr<NonClientFrameView> frame_view_; - - // The overlay view, when non-NULL and visible, takes up the entire widget and - // is placed on top of the ClientView and NonClientFrameView. - View* overlay_view_; - - // The accessible name of this view. - base::string16 accessible_name_; - - DISALLOW_COPY_AND_ASSIGN(NonClientView); -}; - -} // namespace views - -#endif // UI_VIEWS_WINDOW_NON_CLIENT_VIEW_H_
diff --git a/ui/views/window/window_button_order_provider.cc b/ui/views/window/window_button_order_provider.cc deleted file mode 100644 index b1ac70e..0000000 --- a/ui/views/window/window_button_order_provider.cc +++ /dev/null
@@ -1,41 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/window/window_button_order_provider.h" - -namespace views { - -// static -WindowButtonOrderProvider* WindowButtonOrderProvider::instance_ = NULL; - -/////////////////////////////////////////////////////////////////////////////// -// WindowButtonOrderProvider, public: - -// static -WindowButtonOrderProvider* WindowButtonOrderProvider::GetInstance() { - if (!instance_) - instance_ = new WindowButtonOrderProvider; - return instance_; -} - -/////////////////////////////////////////////////////////////////////////////// -// WindowButtonOrderProvider, protected: - -WindowButtonOrderProvider::WindowButtonOrderProvider() { - trailing_buttons_.push_back(views::FRAME_BUTTON_MINIMIZE); - trailing_buttons_.push_back(views::FRAME_BUTTON_MAXIMIZE); - trailing_buttons_.push_back(views::FRAME_BUTTON_CLOSE); -} - -WindowButtonOrderProvider::~WindowButtonOrderProvider() { -} - -void WindowButtonOrderProvider::SetWindowButtonOrder( - const std::vector<views::FrameButton>& leading_buttons, - const std::vector<views::FrameButton>& trailing_buttons) { - leading_buttons_ = leading_buttons; - trailing_buttons_ = trailing_buttons; -} - -} // namespace views
diff --git a/ui/views/window/window_button_order_provider.h b/ui/views/window/window_button_order_provider.h deleted file mode 100644 index f50a49f..0000000 --- a/ui/views/window/window_button_order_provider.h +++ /dev/null
@@ -1,56 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_WINDOW_WINDOW_BUTTON_ORDER_PROVIDER_H_ -#define UI_VIEWS_WINDOW_WINDOW_BUTTON_ORDER_PROVIDER_H_ - -#include <vector> - -#include "base/macros.h" -#include "ui/views/views_export.h" -#include "ui/views/window/frame_buttons.h" - -namespace views { - -// Stores the ordering of window control buttons. Provides a default ordering -// of |FRAME_BUTTON_MINIMZE|, |FRAME_BUTTON_MAXIMIZE|, |FRAME_BUTTON_CLOSE|, -// where all controls are on the trailing end of a window. -// -// On Linux users can provide configuration files to control the ordering. This -// configuration is checked and overrides the defaults. -class VIEWS_EXPORT WindowButtonOrderProvider { - public: - static WindowButtonOrderProvider* GetInstance(); - - const std::vector<views::FrameButton>& leading_buttons() const { - return leading_buttons_; - } - - const std::vector<views::FrameButton>& trailing_buttons() const { - return trailing_buttons_; - } - - void SetWindowButtonOrder( - const std::vector<views::FrameButton>& leading_buttons, - const std::vector<views::FrameButton>& trailing_buttons); - - protected: - WindowButtonOrderProvider(); - virtual ~WindowButtonOrderProvider(); - - private: - static WindowButtonOrderProvider* instance_; - - // Layout arrangement of the window caption buttons. On linux these will be - // set via a WindowButtonOrderObserver. On other platforms a default - // arrangement of a trailing minimize, maximize, close, will be set. - std::vector<views::FrameButton> leading_buttons_; - std::vector<views::FrameButton> trailing_buttons_; - - DISALLOW_COPY_AND_ASSIGN(WindowButtonOrderProvider); -}; - -} // namespace views - -#endif // UI_VIEWS_WINDOW_WINDOW_BUTTON_ORDER_PROVIDER_H_
diff --git a/ui/views/window/window_resources.h b/ui/views/window/window_resources.h deleted file mode 100644 index 55a4a09..0000000 --- a/ui/views/window/window_resources.h +++ /dev/null
@@ -1,33 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_WINDOW_WINDOW_RESOURCES_H_ -#define UI_VIEWS_WINDOW_WINDOW_RESOURCES_H_ - -namespace gfx { -class ImageSkia; -} - -namespace views { - -typedef int FramePartImage; - -/////////////////////////////////////////////////////////////////////////////// -// WindowResources -// -// An interface implemented by an object providing images to render the -// contents of a window frame. The Window may swap in different -// implementations of this interface to render different modes. The definition -// of FramePartImage depends on the implementation. -// -class WindowResources { - public: - virtual ~WindowResources() {} - - virtual gfx::ImageSkia* GetPartImage(FramePartImage part) const = 0; -}; - -} // namespace views - -#endif // UI_VIEWS_WINDOW_WINDOW_RESOURCES_H_
diff --git a/ui/views/window/window_shape.cc b/ui/views/window/window_shape.cc deleted file mode 100644 index 1f6bc13..0000000 --- a/ui/views/window/window_shape.cc +++ /dev/null
@@ -1,46 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/views/window/window_shape.h" - -#include "ui/gfx/path.h" -#include "ui/gfx/size.h" - -namespace views { - -void GetDefaultWindowMask(const gfx::Size &size, gfx::Path *window_mask) { - // Redefine the window visible region for the new size. - window_mask->moveTo(0, 3); - window_mask->lineTo(1, 2); - window_mask->lineTo(1, 1); - window_mask->lineTo(2, 1); - window_mask->lineTo(3, 0); - - window_mask->lineTo(SkIntToScalar(size.width() - 3), 0); - window_mask->lineTo(SkIntToScalar(size.width() - 2), 1); - window_mask->lineTo(SkIntToScalar(size.width() - 1), 1); - window_mask->lineTo(SkIntToScalar(size.width() - 1), 2); - window_mask->lineTo(SkIntToScalar(size.width()), 3); - - window_mask->lineTo(SkIntToScalar(size.width()), - SkIntToScalar(size.height() - 3)); - window_mask->lineTo(SkIntToScalar(size.width() - 1), - SkIntToScalar(size.height() - 3)); - window_mask->lineTo(SkIntToScalar(size.width() - 1), - SkIntToScalar(size.height() - 1)); - window_mask->lineTo(SkIntToScalar(size.width() - 3), - SkIntToScalar(size.height() - 2)); - window_mask->lineTo(SkIntToScalar(size.width() - 3), - SkIntToScalar(size.height())); - - window_mask->lineTo(3, SkIntToScalar(size.height())); - window_mask->lineTo(2, SkIntToScalar(size.height() - 2)); - window_mask->lineTo(1, SkIntToScalar(size.height() - 1)); - window_mask->lineTo(1, SkIntToScalar(size.height() - 3)); - window_mask->lineTo(0, SkIntToScalar(size.height() - 3)); - - window_mask->close(); -} - -} // namespace views
diff --git a/ui/views/window/window_shape.h b/ui/views/window/window_shape.h deleted file mode 100644 index dde0f62..0000000 --- a/ui/views/window/window_shape.h +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_VIEWS_WINDOW_WINDOW_SHAPE_H_ -#define UI_VIEWS_WINDOW_WINDOW_SHAPE_H_ - -#include "ui/views/views_export.h" - -namespace gfx { -class Size; -class Path; -} - -namespace views { - -// Sets the window mask to a style that most likely matches -// ui/resources/window_* -VIEWS_EXPORT void GetDefaultWindowMask(const gfx::Size& size, - gfx::Path* window_mask); - -} // namespace views - -#endif // UI_VIEWS_WINDOW_WINDOW_SHAPE_H_
diff --git a/ui/wm/BUILD.gn b/ui/wm/BUILD.gn deleted file mode 100644 index 186fb11..0000000 --- a/ui/wm/BUILD.gn +++ /dev/null
@@ -1,144 +0,0 @@ -# Copyright 2014 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -component("wm") { - sources = [ - "core/accelerator_delegate.h", - "core/accelerator_filter.cc", - "core/accelerator_filter.h", - "core/base_focus_rules.cc", - "core/base_focus_rules.h", - "core/capture_controller.cc", - "core/capture_controller.h", - "core/compound_event_filter.cc", - "core/compound_event_filter.h", - "core/coordinate_conversion.cc", - "core/coordinate_conversion.h", - "core/cursor_manager.cc", - "core/cursor_manager.h", - "core/default_activation_client.cc", - "core/default_activation_client.h", - "core/easy_resize_window_targeter.cc", - "core/easy_resize_window_targeter.h", - "core/focus_controller.cc", - "core/focus_controller.h", - "core/focus_rules.h", - "core/image_grid.cc", - "core/image_grid.h", - "core/input_method_event_filter.cc", - "core/input_method_event_filter.h", - "core/masked_window_targeter.cc", - "core/masked_window_targeter.h", - "core/native_cursor_manager.h", - "core/native_cursor_manager_delegate.h", - "core/nested_accelerator_dispatcher_linux.cc", - "core/nested_accelerator_dispatcher_win.cc", - "core/nested_accelerator_dispatcher.cc", - "core/nested_accelerator_dispatcher.h", - "core/nested_accelerator_delegate.h", - "core/nested_accelerator_controller.cc", - "core/nested_accelerator_controller.h", - "core/shadow.cc", - "core/shadow.h", - "core/shadow_controller.cc", - "core/shadow_controller.h", - "core/shadow_types.cc", - "core/shadow_types.h", - "core/transient_window_controller.cc", - "core/transient_window_controller.h", - "core/transient_window_manager.cc", - "core/transient_window_manager.h", - "core/transient_window_observer.h", - "core/transient_window_stacking_client.cc", - "core/transient_window_stacking_client.h", - "core/user_activity_detector.cc", - "core/user_activity_detector.h", - "core/user_activity_observer.h", - "core/visibility_controller.cc", - "core/visibility_controller.h", - "core/window_animations.cc", - "core/window_animations.h", - "core/window_modality_controller.cc", - "core/window_modality_controller.h", - "core/window_util.cc", - "core/window_util.h", - "core/wm_core_switches.cc", - "core/wm_core_switches.h", - "core/wm_state.cc", - "core/wm_state.h", - "wm_export.h", - ] - - defines = [ "WM_IMPLEMENTATION" ] - - deps = [ - "//base", - "//skia", - "//ui/aura", - "//ui/base", - "//ui/compositor", - "//ui/events", - "//ui/events/platform", - "//ui/events:events_base", - "//ui/events/platform", - "//ui/gfx", - "//ui/gfx/geometry", - "//ui/resources", - ] -} - -if (false) { - static_library("test_support") { - testonly = true - sources = [ - "test/wm_test_helper.cc", - "test/wm_test_helper.h", - ] - - deps = [ - ":wm", - "//skia", - "//ui/aura", - "//ui/aura:test_support", - "//ui/base", - "//ui/events", - "//ui/events:events_base", - ] - } - - test("wm_unittests") { - sources = [ - "test/run_all_unittests.cc", - "core/compound_event_filter_unittest.cc", - "core/cursor_manager_unittest.cc", - "core/focus_controller_unittest.cc", - "core/input_method_event_filter_unittest.cc", - "core/image_grid_unittest.cc", - "core/nested_accelerator_controller_unittest.cc", - "core/shadow_controller_unittest.cc", - "core/transient_window_manager_unittest.cc", - "core/transient_window_stacking_client_unittest.cc", - "core/user_activity_detector_unittest.cc", - "core/visibility_controller_unittest.cc", - "core/window_animations_unittest.cc", - ] - - deps = [ - ":test_support", - ":wm", - "//base", - "//base/test:test_support", - "//skia", - "//testing/gtest", - "//ui/aura:test_support", - "//ui/base:test_support", - "//ui/compositor:test_support", - "//ui/events:test_support", - "//ui/events/platform", - "//ui/gfx", - "//ui/gfx/geometry", - "//ui/gl", - ] - } -} # if (false)
diff --git a/ui/wm/DEPS b/ui/wm/DEPS deleted file mode 100644 index 62fe7e2..0000000 --- a/ui/wm/DEPS +++ /dev/null
@@ -1,5 +0,0 @@ -include_rules = [ - "+ui/aura", - "+ui/events", - "+ui/gfx", -]
diff --git a/ui/wm/README.chromium b/ui/wm/README.chromium deleted file mode 100644 index e45b858..0000000 --- a/ui/wm/README.chromium +++ /dev/null
@@ -1,8 +0,0 @@ -Window Management functionality for apps built on Aura. - -public/ - Implementation-agnostic APIs. -core/ - Implementations of public/ -test/ - Test implementations of public/, and a minimal WM for use in testing.
diff --git a/ui/wm/core/DEPS b/ui/wm/core/DEPS deleted file mode 100644 index 4d98e61..0000000 --- a/ui/wm/core/DEPS +++ /dev/null
@@ -1,17 +0,0 @@ -include_rules = [ - "+third_party/skia", - "+ui/aura", - "+ui/base/accelerators", - "+ui/base/cursor", - "+ui/base/hit_test.h", - "+ui/base/ime", - "+ui/base/resource", - "+ui/base/ui_base_switches_util.h", - "+ui/base/ui_base_paths.h", - "+ui/base/ui_base_types.h", - "+ui/compositor", - "+ui/events", - "+ui/gfx", - "+ui/resources/grit/ui_resources.h", - "+ui/views/views_export.h", -]
diff --git a/ui/wm/core/accelerator_delegate.h b/ui/wm/core/accelerator_delegate.h deleted file mode 100644 index 886d7db..0000000 --- a/ui/wm/core/accelerator_delegate.h +++ /dev/null
@@ -1,33 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_CORE_ACCELERATOR_DELEGATE_H_ -#define UI_WM_CORE_ACCELERATOR_DELEGATE_H_ - -namespace ui { -class Accelerator; -class KeyEvent; -} - -namespace wm { - -class AcceleratorDelegate { - public: - virtual ~AcceleratorDelegate() {} - - // Type of keys that triggers accelerators. - enum KeyType { - KEY_TYPE_SYSTEM, - KEY_TYPE_OTHER, - }; - - // Return true if the |accelerator| has been processed. - virtual bool ProcessAccelerator(const ui::KeyEvent& event, - const ui::Accelerator& accelerator, - KeyType key_type) = 0; -}; - -} // namespace wm - -#endif // UI_WM_CORE_ACCELERATOR_DELEGATE_H_
diff --git a/ui/wm/core/accelerator_filter.cc b/ui/wm/core/accelerator_filter.cc deleted file mode 100644 index 51c6106..0000000 --- a/ui/wm/core/accelerator_filter.cc +++ /dev/null
@@ -1,80 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/accelerator_filter.h" - -#include "ui/base/accelerators/accelerator.h" -#include "ui/events/event.h" -#include "ui/wm/core/accelerator_delegate.h" - -namespace wm { -namespace { - -// Returns true if |key_code| is a key usually handled directly by the shell. -bool IsSystemKey(ui::KeyboardCode key_code) { -#if defined(OS_CHROMEOS) - switch (key_code) { - case ui::VKEY_MEDIA_LAUNCH_APP2: // Fullscreen button. - case ui::VKEY_MEDIA_LAUNCH_APP1: // Overview button. - case ui::VKEY_BRIGHTNESS_DOWN: - case ui::VKEY_BRIGHTNESS_UP: - case ui::VKEY_KBD_BRIGHTNESS_DOWN: - case ui::VKEY_KBD_BRIGHTNESS_UP: - case ui::VKEY_VOLUME_MUTE: - case ui::VKEY_VOLUME_DOWN: - case ui::VKEY_VOLUME_UP: - return true; - default: - return false; - } -#endif // defined(OS_CHROMEOS) - return false; -} - -} // namespace - -//////////////////////////////////////////////////////////////////////////////// -// AcceleratorFilter, public: - -AcceleratorFilter::AcceleratorFilter(scoped_ptr<AcceleratorDelegate> delegate) - : delegate_(delegate.Pass()) { -} - -AcceleratorFilter::~AcceleratorFilter() { -} - -//////////////////////////////////////////////////////////////////////////////// -// AcceleratorFilter, EventFilter implementation: - -void AcceleratorFilter::OnKeyEvent(ui::KeyEvent* event) { - const ui::EventType type = event->type(); - DCHECK(event->target()); - if ((type != ui::ET_KEY_PRESSED && type != ui::ET_KEY_RELEASED) || - event->is_char() || !event->target()) { - return; - } - - ui::Accelerator accelerator = CreateAcceleratorFromKeyEvent(*event); - - AcceleratorDelegate::KeyType key_type = - IsSystemKey(event->key_code()) ? AcceleratorDelegate::KEY_TYPE_SYSTEM - : AcceleratorDelegate::KEY_TYPE_OTHER; - - if (delegate_->ProcessAccelerator(*event, accelerator, key_type)) - event->StopPropagation(); -} - -ui::Accelerator CreateAcceleratorFromKeyEvent(const ui::KeyEvent& key_event) { - const int kModifierFlagMask = - (ui::EF_SHIFT_DOWN | ui::EF_CONTROL_DOWN | ui::EF_ALT_DOWN); - - ui::Accelerator accelerator(key_event.key_code(), - key_event.flags() & kModifierFlagMask); - if (key_event.type() == ui::ET_KEY_RELEASED) - accelerator.set_type(ui::ET_KEY_RELEASED); - accelerator.set_is_repeat(key_event.IsRepeat()); - return accelerator; -} - -} // namespace wm
diff --git a/ui/wm/core/accelerator_filter.h b/ui/wm/core/accelerator_filter.h deleted file mode 100644 index 0ac7605..0000000 --- a/ui/wm/core/accelerator_filter.h +++ /dev/null
@@ -1,40 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_CORE_ACCELERATOR_FILTER_H_ -#define UI_WM_CORE_ACCELERATOR_FILTER_H_ - -#include "base/macros.h" -#include "base/memory/scoped_ptr.h" -#include "ui/events/event_handler.h" -#include "ui/wm/wm_export.h" - -namespace ui { -class Accelerator; -} - -namespace wm { -class AcceleratorDelegate; - -// AcceleratorFilter filters key events for AcceleratorControler handling global -// keyboard accelerators. -class WM_EXPORT AcceleratorFilter : public ui::EventHandler { - public: - AcceleratorFilter(scoped_ptr<AcceleratorDelegate> delegate); - virtual ~AcceleratorFilter(); - - // Overridden from ui::EventHandler: - virtual void OnKeyEvent(ui::KeyEvent* event) override; - - private: - scoped_ptr<AcceleratorDelegate> delegate_; - - DISALLOW_COPY_AND_ASSIGN(AcceleratorFilter); -}; - -ui::Accelerator CreateAcceleratorFromKeyEvent(const ui::KeyEvent& key_event); - -} // namespace wm - -#endif // UI_WM_CORE_ACCELERATOR_FILTER_H_
diff --git a/ui/wm/core/base_focus_rules.cc b/ui/wm/core/base_focus_rules.cc deleted file mode 100644 index e38aa2e..0000000 --- a/ui/wm/core/base_focus_rules.cc +++ /dev/null
@@ -1,194 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/base_focus_rules.h" - -#include "ui/aura/client/focus_client.h" -#include "ui/aura/window.h" -#include "ui/wm/core/window_modality_controller.h" -#include "ui/wm/core/window_util.h" -#include "ui/wm/public/activation_delegate.h" - -namespace wm { -namespace { - -aura::Window* GetFocusedWindow(aura::Window* context) { - aura::client::FocusClient* focus_client = - aura::client::GetFocusClient(context); - return focus_client ? focus_client->GetFocusedWindow() : NULL; -} - -} // namespace - -//////////////////////////////////////////////////////////////////////////////// -// BaseFocusRules, protected: - -BaseFocusRules::BaseFocusRules() { -} - -BaseFocusRules::~BaseFocusRules() { -} - -bool BaseFocusRules::IsWindowConsideredVisibleForActivation( - aura::Window* window) const { - return window->IsVisible(); -} - -//////////////////////////////////////////////////////////////////////////////// -// BaseFocusRules, FocusRules implementation: - -bool BaseFocusRules::IsToplevelWindow(aura::Window* window) const { - // The window must in a valid hierarchy. - if (!window->GetRootWindow()) - return false; - - // The window must exist within a container that supports activation. - // The window cannot be blocked by a modal transient. - return SupportsChildActivation(window->parent()); -} - -bool BaseFocusRules::CanActivateWindow(aura::Window* window) const { - // It is possible to activate a NULL window, it is equivalent to clearing - // activation. - if (!window) - return true; - - // Only toplevel windows can be activated. - if (!IsToplevelWindow(window)) - return false; - - // The window must be visible. - if (!IsWindowConsideredVisibleForActivation(window)) - return false; - - // The window's activation delegate must allow this window to be activated. - if (aura::client::GetActivationDelegate(window) && - !aura::client::GetActivationDelegate(window)->ShouldActivate()) { - return false; - } - - // A window must be focusable to be activatable. We don't call - // CanFocusWindow() from here because it will call back to us via - // GetActivatableWindow(). - if (!window->CanFocus()) - return false; - - // The window cannot be blocked by a modal transient. - return !GetModalTransient(window); -} - -bool BaseFocusRules::CanFocusWindow(aura::Window* window) const { - // It is possible to focus a NULL window, it is equivalent to clearing focus. - if (!window) - return true; - - // The focused window is always inside the active window, so windows that - // aren't activatable can't contain the focused window. - aura::Window* activatable = GetActivatableWindow(window); - if (!activatable || !activatable->Contains(window)) - return false; - return window->CanFocus(); -} - -aura::Window* BaseFocusRules::GetToplevelWindow(aura::Window* window) const { - aura::Window* parent = window->parent(); - aura::Window* child = window; - while (parent) { - if (IsToplevelWindow(child)) - return child; - - parent = parent->parent(); - child = child->parent(); - } - return NULL; -} - -aura::Window* BaseFocusRules::GetActivatableWindow(aura::Window* window) const { - aura::Window* parent = window->parent(); - aura::Window* child = window; - while (parent) { - if (CanActivateWindow(child)) - return child; - - // CanActivateWindow() above will return false if |child| is blocked by a - // modal transient. In this case the modal is or contains the activatable - // window. We recurse because the modal may itself be blocked by a modal - // transient. - aura::Window* modal_transient = GetModalTransient(child); - if (modal_transient) - return GetActivatableWindow(modal_transient); - - if (wm::GetTransientParent(child)) { - // To avoid infinite recursion, if |child| has a transient parent - // whose own modal transient is |child| itself, just return |child|. - aura::Window* parent_modal_transient = - GetModalTransient(wm::GetTransientParent(child)); - if (parent_modal_transient == child) - return child; - - return GetActivatableWindow(wm::GetTransientParent(child)); - } - - parent = parent->parent(); - child = child->parent(); - } - return NULL; -} - -aura::Window* BaseFocusRules::GetFocusableWindow(aura::Window* window) const { - if (CanFocusWindow(window)) - return window; - - // |window| may be in a hierarchy that is non-activatable, in which case we - // need to cut over to the activatable hierarchy. - aura::Window* activatable = GetActivatableWindow(window); - if (!activatable) { - // There may not be a related activatable hierarchy to cut over to, in which - // case we try an unrelated one. - aura::Window* toplevel = GetToplevelWindow(window); - if (toplevel) - activatable = GetNextActivatableWindow(toplevel); - if (!activatable) - return NULL; - } - - if (!activatable->Contains(window)) { - // If there's already a child window focused in the activatable hierarchy, - // just use that (i.e. don't shift focus), otherwise we need to at least cut - // over to the activatable hierarchy. - aura::Window* focused = GetFocusedWindow(activatable); - return activatable->Contains(focused) ? focused : activatable; - } - - while (window && !CanFocusWindow(window)) - window = window->parent(); - return window; -} - -aura::Window* BaseFocusRules::GetNextActivatableWindow( - aura::Window* ignore) const { - DCHECK(ignore); - - // Can be called from the RootWindow's destruction, which has a NULL parent. - if (!ignore->parent()) - return NULL; - - // In the basic scenarios handled by BasicFocusRules, the pool of activatable - // windows is limited to the |ignore|'s siblings. - const aura::Window::Windows& siblings = ignore->parent()->children(); - DCHECK(!siblings.empty()); - - for (aura::Window::Windows::const_reverse_iterator rit = siblings.rbegin(); - rit != siblings.rend(); - ++rit) { - aura::Window* cur = *rit; - if (cur == ignore) - continue; - if (CanActivateWindow(cur)) - return cur; - } - return NULL; -} - -} // namespace wm
diff --git a/ui/wm/core/base_focus_rules.h b/ui/wm/core/base_focus_rules.h deleted file mode 100644 index 8073541..0000000 --- a/ui/wm/core/base_focus_rules.h +++ /dev/null
@@ -1,45 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_CORE_BASE_FOCUS_RULES_H_ -#define UI_WM_CORE_BASE_FOCUS_RULES_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "ui/wm/core/focus_rules.h" - -namespace wm { - -// A set of basic focus and activation rules. Specializations should most likely -// subclass this and call up to these methods rather than reimplementing them. -class WM_EXPORT BaseFocusRules : public FocusRules { - protected: - BaseFocusRules(); - virtual ~BaseFocusRules(); - - // Returns true if the children of |window| can be activated. - virtual bool SupportsChildActivation(aura::Window* window) const = 0; - - // Returns true if |window| is considered visible for activation purposes. - virtual bool IsWindowConsideredVisibleForActivation( - aura::Window* window) const; - - // Overridden from FocusRules: - virtual bool IsToplevelWindow(aura::Window* window) const override; - virtual bool CanActivateWindow(aura::Window* window) const override; - virtual bool CanFocusWindow(aura::Window* window) const override; - virtual aura::Window* GetToplevelWindow(aura::Window* window) const override; - virtual aura::Window* GetActivatableWindow( - aura::Window* window) const override; - virtual aura::Window* GetFocusableWindow(aura::Window* window) const override; - virtual aura::Window* GetNextActivatableWindow( - aura::Window* ignore) const override; - - private: - DISALLOW_COPY_AND_ASSIGN(BaseFocusRules); -}; - -} // namespace wm - -#endif // UI_WM_CORE_BASE_FOCUS_RULES_H_
diff --git a/ui/wm/core/capture_controller.cc b/ui/wm/core/capture_controller.cc deleted file mode 100644 index b3d8620..0000000 --- a/ui/wm/core/capture_controller.cc +++ /dev/null
@@ -1,145 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/capture_controller.h" - -#include "ui/aura/window.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/aura/window_tree_host.h" - -namespace wm { - -//////////////////////////////////////////////////////////////////////////////// -// CaptureController, public: - -void CaptureController::Attach(aura::Window* root) { - DCHECK_EQ(0u, root_windows_.count(root)); - root_windows_.insert(root); - aura::client::SetCaptureClient(root, this); -} - -void CaptureController::Detach(aura::Window* root) { - root_windows_.erase(root); - aura::client::SetCaptureClient(root, NULL); -} - -//////////////////////////////////////////////////////////////////////////////// -// CaptureController, aura::client::CaptureClient implementation: - -void CaptureController::SetCapture(aura::Window* new_capture_window) { - if (capture_window_ == new_capture_window) - return; - - // Make sure window has a root window. - DCHECK(!new_capture_window || new_capture_window->GetRootWindow()); - DCHECK(!capture_window_ || capture_window_->GetRootWindow()); - - aura::Window* old_capture_window = capture_window_; - aura::Window* old_capture_root = old_capture_window ? - old_capture_window->GetRootWindow() : NULL; - - // Copy the list in case it's modified out from under us. - RootWindows root_windows(root_windows_); - - // If we're actually starting capture, then cancel any touches/gestures - // that aren't already locked to the new window, and transfer any on the - // old capture window to the new one. When capture is released we have no - // distinction between the touches/gestures that were in the window all - // along (and so shouldn't be canceled) and those that got moved, so - // just leave them all where they are. - if (new_capture_window) { - ui::GestureRecognizer::Get()->TransferEventsTo(old_capture_window, - new_capture_window); - } - - capture_window_ = new_capture_window; - - for (RootWindows::const_iterator i = root_windows.begin(); - i != root_windows.end(); ++i) { - aura::client::CaptureDelegate* delegate = (*i)->GetHost()->dispatcher(); - delegate->UpdateCapture(old_capture_window, new_capture_window); - } - - aura::Window* capture_root = - capture_window_ ? capture_window_->GetRootWindow() : NULL; - if (capture_root != old_capture_root) { - if (old_capture_root) { - aura::client::CaptureDelegate* delegate = - old_capture_root->GetHost()->dispatcher(); - delegate->ReleaseNativeCapture(); - } - if (capture_root) { - aura::client::CaptureDelegate* delegate = - capture_root->GetHost()->dispatcher(); - delegate->SetNativeCapture(); - } - } -} - -void CaptureController::ReleaseCapture(aura::Window* window) { - if (capture_window_ != window) - return; - SetCapture(NULL); -} - -aura::Window* CaptureController::GetCaptureWindow() { - return capture_window_; -} - -aura::Window* CaptureController::GetGlobalCaptureWindow() { - return capture_window_; -} - -//////////////////////////////////////////////////////////////////////////////// -// CaptureController, private: - -CaptureController::CaptureController() - : capture_window_(NULL) { -} - -CaptureController::~CaptureController() { -} - -//////////////////////////////////////////////////////////////////////////////// -// ScopedCaptureClient: - -// static -CaptureController* ScopedCaptureClient::capture_controller_ = NULL; - -ScopedCaptureClient::ScopedCaptureClient(aura::Window* root) - : root_window_(root) { - root->AddObserver(this); - if (!capture_controller_) - capture_controller_ = new CaptureController; - capture_controller_->Attach(root); -} - -ScopedCaptureClient::~ScopedCaptureClient() { - Shutdown(); -} - -// static -bool ScopedCaptureClient::IsActive() { - return capture_controller_ && capture_controller_->is_active(); -} - -void ScopedCaptureClient::OnWindowDestroyed(aura::Window* window) { - DCHECK_EQ(window, root_window_); - Shutdown(); -} - -void ScopedCaptureClient::Shutdown() { - if (!root_window_) - return; - - root_window_->RemoveObserver(this); - capture_controller_->Detach(root_window_); - if (!capture_controller_->is_active()) { - delete capture_controller_; - capture_controller_ = NULL; - } - root_window_ = NULL; -} - -} // namespace wm
diff --git a/ui/wm/core/capture_controller.h b/ui/wm/core/capture_controller.h deleted file mode 100644 index 230ea50..0000000 --- a/ui/wm/core/capture_controller.h +++ /dev/null
@@ -1,86 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_CORE_CAPTURE_CONTROLLER_H_ -#define UI_WM_CORE_CAPTURE_CONTROLLER_H_ - -#include <set> - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "ui/aura/client/capture_client.h" -#include "ui/aura/window_observer.h" -#include "ui/wm/wm_export.h" - -namespace wm { - -// Internal CaptureClient implementation. See ScopedCaptureClient for details. -class WM_EXPORT CaptureController : public aura::client::CaptureClient { - public: - // Adds |root| to the list of RootWindows notified when capture changes. - void Attach(aura::Window* root); - - // Removes |root| from the list of RootWindows notified when capture changes. - void Detach(aura::Window* root); - - // Returns true if this CaptureController is installed on at least one - // RootWindow. - bool is_active() const { return !root_windows_.empty(); } - - // Overridden from aura::client::CaptureClient: - virtual void SetCapture(aura::Window* window) override; - virtual void ReleaseCapture(aura::Window* window) override; - virtual aura::Window* GetCaptureWindow() override; - virtual aura::Window* GetGlobalCaptureWindow() override; - - private: - friend class ScopedCaptureClient; - typedef std::set<aura::Window*> RootWindows; - - CaptureController(); - virtual ~CaptureController(); - - // The current capture window. NULL if there is no capture window. - aura::Window* capture_window_; - - // Set of RootWindows notified when capture changes. - RootWindows root_windows_; - - DISALLOW_COPY_AND_ASSIGN(CaptureController); -}; - -// ScopedCaptureClient is responsible for creating a CaptureClient for a -// RootWindow. Specifically it creates a single CaptureController that is shared -// among all ScopedCaptureClients and adds the RootWindow to it. -class WM_EXPORT ScopedCaptureClient : public aura::WindowObserver { - public: - explicit ScopedCaptureClient(aura::Window* root); - virtual ~ScopedCaptureClient(); - - // Returns true if there is a CaptureController with at least one RootWindow. - static bool IsActive(); - - aura::client::CaptureClient* capture_client() { - return capture_controller_; - } - - // Overridden from aura::WindowObserver: - virtual void OnWindowDestroyed(aura::Window* window) override; - - private: - // Invoked from destructor and OnWindowDestroyed() to cleanup. - void Shutdown(); - - // The single CaptureController instance. - static CaptureController* capture_controller_; - - // RootWindow this ScopedCaptureClient was create for. - aura::Window* root_window_; - - DISALLOW_COPY_AND_ASSIGN(ScopedCaptureClient); -}; - -} // namespace wm - -#endif // UI_WM_CORE_CAPTURE_CONTROLLER_H_
diff --git a/ui/wm/core/compound_event_filter.cc b/ui/wm/core/compound_event_filter.cc deleted file mode 100644 index d1f652c..0000000 --- a/ui/wm/core/compound_event_filter.cc +++ /dev/null
@@ -1,263 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/compound_event_filter.h" - -#include "base/containers/hash_tables.h" -#include "base/logging.h" -#include "ui/aura/client/cursor_client.h" -#include "ui/aura/env.h" -#include "ui/aura/window.h" -#include "ui/aura/window_delegate.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/aura/window_tracker.h" -#include "ui/base/hit_test.h" -#include "ui/events/event.h" -#include "ui/wm/public/activation_client.h" -#include "ui/wm/public/drag_drop_client.h" - -#if defined(OS_CHROMEOS) && defined(USE_X11) -#include "ui/events/x/touch_factory_x11.h" -#endif - -namespace wm { - -namespace { - -// Returns true if the cursor should be hidden on touch events. -// TODO(tdanderson|rsadam): Move this function into CursorClient. -bool ShouldHideCursorOnTouch(const ui::TouchEvent& event) { -#if defined(OS_WIN) - return true; -#elif defined(OS_CHROMEOS) -#if defined(USE_X11) - int device_id = event.source_device_id(); - if (device_id >= 0 && - !ui::TouchFactory::GetInstance()->IsMultiTouchDevice(device_id)) { - // If the touch event is coming from a mouse-device (i.e. not a real - // touch-device), then do not hide the cursor. - return false; - } -#endif // defined(USE_X11) - return true; -#else - // Linux Aura does not hide the cursor on touch by default. - // TODO(tdanderson): Change this if having consistency across - // all platforms which use Aura is desired. - return false; -#endif -} - -} // namespace - -//////////////////////////////////////////////////////////////////////////////// -// CompoundEventFilter, public: - -CompoundEventFilter::CompoundEventFilter() { -} - -CompoundEventFilter::~CompoundEventFilter() { - // Additional filters are not owned by CompoundEventFilter and they - // should all be removed when running here. |handlers_| has - // check_empty == true and will DCHECK failure if it is not empty. -} - -// static -gfx::NativeCursor CompoundEventFilter::CursorForWindowComponent( - int window_component) { - switch (window_component) { - case HTBOTTOM: - return ui::kCursorSouthResize; - case HTBOTTOMLEFT: - return ui::kCursorSouthWestResize; - case HTBOTTOMRIGHT: - return ui::kCursorSouthEastResize; - case HTLEFT: - return ui::kCursorWestResize; - case HTRIGHT: - return ui::kCursorEastResize; - case HTTOP: - return ui::kCursorNorthResize; - case HTTOPLEFT: - return ui::kCursorNorthWestResize; - case HTTOPRIGHT: - return ui::kCursorNorthEastResize; - default: - return ui::kCursorNull; - } -} - -void CompoundEventFilter::AddHandler(ui::EventHandler* handler) { - handlers_.AddObserver(handler); -} - -void CompoundEventFilter::RemoveHandler(ui::EventHandler* handler) { - handlers_.RemoveObserver(handler); -} - -//////////////////////////////////////////////////////////////////////////////// -// CompoundEventFilter, private: - -void CompoundEventFilter::UpdateCursor(aura::Window* target, - ui::MouseEvent* event) { - // If drag and drop is in progress, let the drag drop client set the cursor - // instead of setting the cursor here. - aura::Window* root_window = target->GetRootWindow(); - aura::client::DragDropClient* drag_drop_client = - aura::client::GetDragDropClient(root_window); - if (drag_drop_client && drag_drop_client->IsDragDropInProgress()) - return; - - aura::client::CursorClient* cursor_client = - aura::client::GetCursorClient(root_window); - if (cursor_client) { - gfx::NativeCursor cursor = target->GetCursor(event->location()); - if ((event->flags() & ui::EF_IS_NON_CLIENT)) { - if (target->delegate()) { - int window_component = - target->delegate()->GetNonClientComponent(event->location()); - cursor = CursorForWindowComponent(window_component); - } else { - // Allow the OS to handle non client cursors if we don't have a - // a delegate to handle the non client hittest. - return; - } - } - cursor_client->SetCursor(cursor); - } -} - -void CompoundEventFilter::FilterKeyEvent(ui::KeyEvent* event) { - if (handlers_.might_have_observers()) { - ObserverListBase<ui::EventHandler>::Iterator it(handlers_); - ui::EventHandler* handler; - while (!event->stopped_propagation() && (handler = it.GetNext()) != NULL) - handler->OnKeyEvent(event); - } -} - -void CompoundEventFilter::FilterMouseEvent(ui::MouseEvent* event) { - if (handlers_.might_have_observers()) { - ObserverListBase<ui::EventHandler>::Iterator it(handlers_); - ui::EventHandler* handler; - while (!event->stopped_propagation() && (handler = it.GetNext()) != NULL) - handler->OnMouseEvent(event); - } -} - -void CompoundEventFilter::FilterTouchEvent(ui::TouchEvent* event) { - if (handlers_.might_have_observers()) { - ObserverListBase<ui::EventHandler>::Iterator it(handlers_); - ui::EventHandler* handler; - while (!event->stopped_propagation() && (handler = it.GetNext()) != NULL) - handler->OnTouchEvent(event); - } -} - -void CompoundEventFilter::SetCursorVisibilityOnEvent(aura::Window* target, - ui::Event* event, - bool show) { - if (event->flags() & ui::EF_IS_SYNTHESIZED) - return; - - aura::client::CursorClient* client = - aura::client::GetCursorClient(target->GetRootWindow()); - if (!client) - return; - - if (show) - client->ShowCursor(); - else - client->HideCursor(); -} - -void CompoundEventFilter::SetMouseEventsEnableStateOnEvent(aura::Window* target, - ui::Event* event, - bool enable) { - if (event->flags() & ui::EF_IS_SYNTHESIZED) - return; - aura::client::CursorClient* client = - aura::client::GetCursorClient(target->GetRootWindow()); - if (!client) - return; - - if (enable) - client->EnableMouseEvents(); - else - client->DisableMouseEvents(); -} - -//////////////////////////////////////////////////////////////////////////////// -// CompoundEventFilter, ui::EventHandler implementation: - -void CompoundEventFilter::OnKeyEvent(ui::KeyEvent* event) { - aura::Window* target = static_cast<aura::Window*>(event->target()); - aura::client::CursorClient* client = - aura::client::GetCursorClient(target->GetRootWindow()); - if (client && client->ShouldHideCursorOnKeyEvent(*event)) - SetCursorVisibilityOnEvent(target, event, false); - - FilterKeyEvent(event); -} - -void CompoundEventFilter::OnMouseEvent(ui::MouseEvent* event) { - aura::Window* window = static_cast<aura::Window*>(event->target()); - aura::WindowTracker window_tracker; - window_tracker.Add(window); - - // We must always update the cursor, otherwise the cursor can get stuck if an - // event filter registered with us consumes the event. - // It should also update the cursor for clicking and wheels for ChromeOS boot. - // When ChromeOS is booted, it hides the mouse cursor but immediate mouse - // operation will show the cursor. - // We also update the cursor for mouse enter in case a mouse cursor is sent to - // outside of the root window and moved back for some reasons (e.g. running on - // on Desktop for testing, or a bug in pointer barrier). - if (!(event->flags() & ui::EF_FROM_TOUCH) && - (event->type() == ui::ET_MOUSE_ENTERED || - event->type() == ui::ET_MOUSE_MOVED || - event->type() == ui::ET_MOUSE_PRESSED || - event->type() == ui::ET_MOUSEWHEEL)) { - SetMouseEventsEnableStateOnEvent(window, event, true); - SetCursorVisibilityOnEvent(window, event, true); - UpdateCursor(window, event); - } - - FilterMouseEvent(event); -} - -void CompoundEventFilter::OnScrollEvent(ui::ScrollEvent* event) { -} - -void CompoundEventFilter::OnTouchEvent(ui::TouchEvent* event) { - FilterTouchEvent(event); - if (!event->handled() && event->type() == ui::ET_TOUCH_PRESSED && - ShouldHideCursorOnTouch(*event) && - !aura::Env::GetInstance()->IsMouseButtonDown()) { - SetMouseEventsEnableStateOnEvent( - static_cast<aura::Window*>(event->target()), event, false); - } -} - -void CompoundEventFilter::OnGestureEvent(ui::GestureEvent* event) { - if (handlers_.might_have_observers()) { - ObserverListBase<ui::EventHandler>::Iterator it(handlers_); - ui::EventHandler* handler; - while (!event->stopped_propagation() && (handler = it.GetNext()) != NULL) - handler->OnGestureEvent(event); - } - -#if defined(OS_WIN) - // A Win8 edge swipe event is a special event that does not have location - // information associated with it, and is not preceeded by an ET_TOUCH_PRESSED - // event. So we treat it specially here. - if (!event->handled() && event->type() == ui::ET_GESTURE_WIN8_EDGE_SWIPE && - !aura::Env::GetInstance()->IsMouseButtonDown()) { - SetMouseEventsEnableStateOnEvent( - static_cast<aura::Window*>(event->target()), event, false); - } -#endif -} - -} // namespace wm
diff --git a/ui/wm/core/compound_event_filter.h b/ui/wm/core/compound_event_filter.h deleted file mode 100644 index a7767f3..0000000 --- a/ui/wm/core/compound_event_filter.h +++ /dev/null
@@ -1,93 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_CORE_COMPOUND_EVENT_FILTER_H_ -#define UI_WM_CORE_COMPOUND_EVENT_FILTER_H_ - -#include "base/compiler_specific.h" -#include "base/observer_list.h" -#include "ui/events/event.h" -#include "ui/events/event_handler.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/wm/wm_export.h" - -namespace aura { -class CursorManager; -class RootWindow; -} - -namespace ui { -class GestureEvent; -class KeyEvent; -class LocatedEvent; -class MouseEvent; -class TouchEvent; -} - -namespace wm { - -// TODO(beng): This class should die. AddEventHandler() on the root Window -// should be used instead. -// CompoundEventFilter gets all events first and can provide actions to those -// events. It implements global features such as click to activate a window and -// cursor change when moving mouse. -// Additional event filters can be added to CompoundEventFilter. Events will -// pass through those additional filters in their addition order and could be -// consumed by any of those filters. If an event is consumed by a filter, the -// rest of the filter(s) and CompoundEventFilter will not see the consumed -// event. -class WM_EXPORT CompoundEventFilter : public ui::EventHandler { - public: - CompoundEventFilter(); - virtual ~CompoundEventFilter(); - - // Returns the cursor for the specified component. - static gfx::NativeCursor CursorForWindowComponent(int window_component); - - // Adds/removes additional event filters. This does not take ownership of - // the EventHandler. - // NOTE: These handlers are deprecated. Use env::AddPreTargetEventHandler etc. - // instead. - void AddHandler(ui::EventHandler* filter); - void RemoveHandler(ui::EventHandler* filter); - - private: - // Updates the cursor if the target provides a custom one, and provides - // default resize cursors for window edges. - void UpdateCursor(aura::Window* target, ui::MouseEvent* event); - - // Dispatches event to additional filters. - void FilterKeyEvent(ui::KeyEvent* event); - void FilterMouseEvent(ui::MouseEvent* event); - void FilterTouchEvent(ui::TouchEvent* event); - - // Sets the visibility of the cursor if the event is not synthesized. - void SetCursorVisibilityOnEvent(aura::Window* target, - ui::Event* event, - bool show); - - // Enables or disables mouse events if the event is not synthesized. - void SetMouseEventsEnableStateOnEvent(aura::Window* target, - ui::Event* event, - bool enable); - - // Overridden from ui::EventHandler: - virtual void OnKeyEvent(ui::KeyEvent* event) override; - virtual void OnMouseEvent(ui::MouseEvent* event) override; - virtual void OnScrollEvent(ui::ScrollEvent* event) override; - virtual void OnTouchEvent(ui::TouchEvent* event) override; - virtual void OnGestureEvent(ui::GestureEvent* event) override; - - // Additional pre-target event handlers. - ObserverList<ui::EventHandler, true> handlers_; - - // True if the cursur was hidden by the filter. - bool cursor_hidden_by_filter_; - - DISALLOW_COPY_AND_ASSIGN(CompoundEventFilter); -}; - -} // namespace wm - -#endif // UI_WM_CORE_COMPOUND_EVENT_FILTER_H_
diff --git a/ui/wm/core/compound_event_filter_unittest.cc b/ui/wm/core/compound_event_filter_unittest.cc deleted file mode 100644 index 05f75e9..0000000 --- a/ui/wm/core/compound_event_filter_unittest.cc +++ /dev/null
@@ -1,250 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/compound_event_filter.h" - -#include "ui/aura/client/cursor_client.h" -#include "ui/aura/env.h" -#include "ui/aura/test/aura_test_base.h" -#include "ui/aura/test/test_cursor_client.h" -#include "ui/aura/test/test_windows.h" -#include "ui/aura/window.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/events/event.h" -#include "ui/events/event_utils.h" -#include "ui/events/test/event_generator.h" -#include "ui/wm/core/default_activation_client.h" -#include "ui/wm/public/activation_client.h" - -namespace { - -#if defined(OS_CHROMEOS) || defined(OS_WIN) -base::TimeDelta GetTime() { - return ui::EventTimeForNow(); -} -#endif // defined(OS_CHROMEOS) || defined(OS_WIN) - -} - -namespace wm { - -namespace { - -// An event filter that consumes all gesture events. -class ConsumeGestureEventFilter : public ui::EventHandler { - public: - ConsumeGestureEventFilter() {} - virtual ~ConsumeGestureEventFilter() {} - - private: - // Overridden from ui::EventHandler: - virtual void OnGestureEvent(ui::GestureEvent* e) override { - e->StopPropagation(); - } - - DISALLOW_COPY_AND_ASSIGN(ConsumeGestureEventFilter); -}; - -} // namespace - -typedef aura::test::AuraTestBase CompoundEventFilterTest; - -#if defined(OS_CHROMEOS) -// A keypress only hides the cursor on ChromeOS (crbug.com/304296). -TEST_F(CompoundEventFilterTest, CursorVisibilityChange) { - scoped_ptr<CompoundEventFilter> compound_filter(new CompoundEventFilter); - aura::Env::GetInstance()->AddPreTargetHandler(compound_filter.get()); - aura::test::TestWindowDelegate delegate; - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(&delegate, 1234, - gfx::Rect(5, 5, 100, 100), root_window())); - window->Show(); - window->SetCapture(); - - aura::test::TestCursorClient cursor_client(root_window()); - - // Send key event to hide the cursor. - ui::KeyEvent key('a', ui::VKEY_A, ui::EF_NONE); - DispatchEventUsingWindowDispatcher(&key); - EXPECT_FALSE(cursor_client.IsCursorVisible()); - - // Synthesized mouse event should not show the cursor. - ui::MouseEvent enter(ui::ET_MOUSE_ENTERED, gfx::Point(10, 10), - gfx::Point(10, 10), 0, 0); - enter.set_flags(enter.flags() | ui::EF_IS_SYNTHESIZED); - DispatchEventUsingWindowDispatcher(&enter); - EXPECT_FALSE(cursor_client.IsCursorVisible()); - - ui::MouseEvent move(ui::ET_MOUSE_MOVED, gfx::Point(10, 10), - gfx::Point(10, 10), 0, 0); - move.set_flags(enter.flags() | ui::EF_IS_SYNTHESIZED); - DispatchEventUsingWindowDispatcher(&move); - EXPECT_FALSE(cursor_client.IsCursorVisible()); - - // A real mouse event should show the cursor. - ui::MouseEvent real_move(ui::ET_MOUSE_MOVED, gfx::Point(10, 10), - gfx::Point(10, 10), 0, 0); - DispatchEventUsingWindowDispatcher(&real_move); - EXPECT_TRUE(cursor_client.IsCursorVisible()); - - // Disallow hiding the cursor on keypress. - cursor_client.set_should_hide_cursor_on_key_event(false); - key = ui::KeyEvent('a', ui::VKEY_A, ui::EF_NONE); - DispatchEventUsingWindowDispatcher(&key); - EXPECT_TRUE(cursor_client.IsCursorVisible()); - - // Allow hiding the cursor on keypress. - cursor_client.set_should_hide_cursor_on_key_event(true); - key = ui::KeyEvent('a', ui::VKEY_A, ui::EF_NONE); - DispatchEventUsingWindowDispatcher(&key); - EXPECT_FALSE(cursor_client.IsCursorVisible()); - - // Mouse synthesized exit event should not show the cursor. - ui::MouseEvent exit(ui::ET_MOUSE_EXITED, gfx::Point(10, 10), - gfx::Point(10, 10), 0, 0); - exit.set_flags(enter.flags() | ui::EF_IS_SYNTHESIZED); - DispatchEventUsingWindowDispatcher(&exit); - EXPECT_FALSE(cursor_client.IsCursorVisible()); - - aura::Env::GetInstance()->RemovePreTargetHandler(compound_filter.get()); -} -#endif // defined(OS_CHROMEOS) - -#if defined(OS_CHROMEOS) || defined(OS_WIN) -// Touch visually hides the cursor on ChromeOS and Windows. -TEST_F(CompoundEventFilterTest, TouchHidesCursor) { - new wm::DefaultActivationClient(root_window()); - scoped_ptr<CompoundEventFilter> compound_filter(new CompoundEventFilter); - aura::Env::GetInstance()->AddPreTargetHandler(compound_filter.get()); - aura::test::TestWindowDelegate delegate; - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(&delegate, 1234, - gfx::Rect(5, 5, 100, 100), root_window())); - window->Show(); - window->SetCapture(); - - aura::test::TestCursorClient cursor_client(root_window()); - - ui::MouseEvent mouse0(ui::ET_MOUSE_MOVED, gfx::Point(10, 10), - gfx::Point(10, 10), 0, 0); - DispatchEventUsingWindowDispatcher(&mouse0); - EXPECT_TRUE(cursor_client.IsMouseEventsEnabled()); - - // This press is required for the GestureRecognizer to associate a target - // with kTouchId - ui::TouchEvent press0( - ui::ET_TOUCH_PRESSED, gfx::Point(90, 90), 1, GetTime()); - DispatchEventUsingWindowDispatcher(&press0); - EXPECT_FALSE(cursor_client.IsMouseEventsEnabled()); - - ui::TouchEvent move(ui::ET_TOUCH_MOVED, gfx::Point(10, 10), 1, GetTime()); - DispatchEventUsingWindowDispatcher(&move); - EXPECT_FALSE(cursor_client.IsMouseEventsEnabled()); - - ui::TouchEvent release( - ui::ET_TOUCH_RELEASED, gfx::Point(10, 10), 1, GetTime()); - DispatchEventUsingWindowDispatcher(&release); - EXPECT_FALSE(cursor_client.IsMouseEventsEnabled()); - - ui::MouseEvent mouse1(ui::ET_MOUSE_MOVED, gfx::Point(10, 10), - gfx::Point(10, 10), 0, 0); - // Move the cursor again. The cursor should be visible. - DispatchEventUsingWindowDispatcher(&mouse1); - EXPECT_TRUE(cursor_client.IsMouseEventsEnabled()); - - // Now activate the window and press on it again. - ui::TouchEvent press1( - ui::ET_TOUCH_PRESSED, gfx::Point(90, 90), 1, GetTime()); - aura::client::GetActivationClient( - root_window())->ActivateWindow(window.get()); - DispatchEventUsingWindowDispatcher(&press1); - EXPECT_FALSE(cursor_client.IsMouseEventsEnabled()); - aura::Env::GetInstance()->RemovePreTargetHandler(compound_filter.get()); -} -#endif // defined(OS_CHROMEOS) || defined(OS_WIN) - -// Tests that if an event filter consumes a gesture, then it doesn't focus the -// window. -TEST_F(CompoundEventFilterTest, FilterConsumedGesture) { - scoped_ptr<CompoundEventFilter> compound_filter(new CompoundEventFilter); - scoped_ptr<ui::EventHandler> gesure_handler(new ConsumeGestureEventFilter); - compound_filter->AddHandler(gesure_handler.get()); - aura::Env::GetInstance()->AddPreTargetHandler(compound_filter.get()); - aura::test::TestWindowDelegate delegate; - DCHECK(root_window()); - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(&delegate, 1234, - gfx::Rect(5, 5, 100, 100), root_window())); - window->Show(); - - EXPECT_TRUE(window->CanFocus()); - EXPECT_FALSE(window->HasFocus()); - - // Tap on the window should not focus it since the filter will be consuming - // the gestures. - ui::test::EventGenerator generator(root_window(), gfx::Point(50, 50)); - generator.PressTouch(); - EXPECT_FALSE(window->HasFocus()); - - compound_filter->RemoveHandler(gesure_handler.get()); - aura::Env::GetInstance()->RemovePreTargetHandler(compound_filter.get()); -} - -// Verifies we don't attempt to hide the mouse when the mouse is down and a -// touch event comes in. -TEST_F(CompoundEventFilterTest, DontHideWhenMouseDown) { - ui::test::EventGenerator event_generator(root_window()); - - scoped_ptr<CompoundEventFilter> compound_filter(new CompoundEventFilter); - aura::Env::GetInstance()->AddPreTargetHandler(compound_filter.get()); - aura::test::TestWindowDelegate delegate; - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(&delegate, 1234, - gfx::Rect(5, 5, 100, 100), root_window())); - window->Show(); - - aura::test::TestCursorClient cursor_client(root_window()); - - // Move and press the mouse over the window. - event_generator.MoveMouseTo(10, 10); - EXPECT_TRUE(cursor_client.IsMouseEventsEnabled()); - event_generator.PressLeftButton(); - EXPECT_TRUE(cursor_client.IsMouseEventsEnabled()); - EXPECT_TRUE(aura::Env::GetInstance()->IsMouseButtonDown()); - - // Do a touch event. As the mouse button is down this should not disable mouse - // events. - event_generator.PressTouch(); - EXPECT_TRUE(cursor_client.IsMouseEventsEnabled()); - aura::Env::GetInstance()->RemovePreTargetHandler(compound_filter.get()); -} - -#if defined(OS_WIN) -// Windows synthesizes mouse messages for touch events. We should not be -// showing the cursor when we receive such messages. -TEST_F(CompoundEventFilterTest, DontShowCursorOnMouseMovesFromTouch) { - scoped_ptr<CompoundEventFilter> compound_filter(new CompoundEventFilter); - aura::Env::GetInstance()->AddPreTargetHandler(compound_filter.get()); - aura::test::TestWindowDelegate delegate; - scoped_ptr<aura::Window> window(CreateTestWindowWithDelegate(&delegate, 1234, - gfx::Rect(5, 5, 100, 100), root_window())); - window->Show(); - window->SetCapture(); - - aura::test::TestCursorClient cursor_client(root_window()); - cursor_client.DisableMouseEvents(); - EXPECT_FALSE(cursor_client.IsMouseEventsEnabled()); - - ui::MouseEvent mouse0(ui::ET_MOUSE_MOVED, gfx::Point(10, 10), - gfx::Point(10, 10), 0, 0); - mouse0.set_flags(mouse0.flags() | ui::EF_FROM_TOUCH); - - DispatchEventUsingWindowDispatcher(&mouse0); - EXPECT_FALSE(cursor_client.IsMouseEventsEnabled()); - - mouse0.set_flags(mouse0.flags() & ~ui::EF_FROM_TOUCH); - DispatchEventUsingWindowDispatcher(&mouse0); - EXPECT_TRUE(cursor_client.IsMouseEventsEnabled()); - - aura::Env::GetInstance()->RemovePreTargetHandler(compound_filter.get()); -} -#endif - -} // namespace wm
diff --git a/ui/wm/core/coordinate_conversion.cc b/ui/wm/core/coordinate_conversion.cc deleted file mode 100644 index 6227b37..0000000 --- a/ui/wm/core/coordinate_conversion.cc +++ /dev/null
@@ -1,29 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/coordinate_conversion.h" - -#include "ui/aura/client/screen_position_client.h" -#include "ui/gfx/point.h" - -namespace wm { - -void ConvertPointToScreen(const aura::Window* window, gfx::Point* point) { - DCHECK(window); - DCHECK(window->GetRootWindow()); - DCHECK(aura::client::GetScreenPositionClient(window->GetRootWindow())); - aura::client::GetScreenPositionClient(window->GetRootWindow())-> - ConvertPointToScreen(window, point); -} - -void ConvertPointFromScreen(const aura::Window* window, - gfx::Point* point_in_screen) { - DCHECK(window); - DCHECK(window->GetRootWindow()); - DCHECK(aura::client::GetScreenPositionClient(window->GetRootWindow())); - aura::client::GetScreenPositionClient(window->GetRootWindow())-> - ConvertPointFromScreen(window, point_in_screen); -} - -} // namespace wm
diff --git a/ui/wm/core/coordinate_conversion.h b/ui/wm/core/coordinate_conversion.h deleted file mode 100644 index acc6a46..0000000 --- a/ui/wm/core/coordinate_conversion.h +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_CORE_COORDINATE_CONVERSION_H_ -#define UI_WM_CORE_COORDINATE_CONVERSION_H_ - -#include "ui/wm/wm_export.h" - -namespace aura { -class Window; -} // namespace aura - -namespace gfx { -class Point; -} // namespace gfx - -namespace wm { - -// Converts the |point| from a given |window|'s coordinates into the screen -// coordinates. -WM_EXPORT void ConvertPointToScreen(const aura::Window* window, - gfx::Point* point); - -// Converts the |point| from the screen coordinates to a given |window|'s -// coordinates. -WM_EXPORT void ConvertPointFromScreen(const aura::Window* window, - gfx::Point* point_in_screen); - -} // namespace wm - -#endif // UI_WM_CORE_COORDINATE_CONVERSION_H_
diff --git a/ui/wm/core/cursor_manager.cc b/ui/wm/core/cursor_manager.cc deleted file mode 100644 index e9f9885..0000000 --- a/ui/wm/core/cursor_manager.cc +++ /dev/null
@@ -1,217 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/cursor_manager.h" - -#include "base/logging.h" -#include "ui/aura/client/cursor_client_observer.h" -#include "ui/wm/core/native_cursor_manager.h" -#include "ui/wm/core/native_cursor_manager_delegate.h" - -namespace wm { - -namespace internal { - -// Represents the cursor state which is composed of cursor type, visibility, and -// mouse events enable state. When mouse events are disabled, the cursor is -// always invisible. -class CursorState { - public: - CursorState() - : cursor_(ui::kCursorNone), - visible_(true), - cursor_set_(ui::CURSOR_SET_NORMAL), - mouse_events_enabled_(true), - visible_on_mouse_events_enabled_(true) { - } - - gfx::NativeCursor cursor() const { return cursor_; } - void set_cursor(gfx::NativeCursor cursor) { cursor_ = cursor; } - - bool visible() const { return visible_; } - void SetVisible(bool visible) { - if (mouse_events_enabled_) - visible_ = visible; - // Ignores the call when mouse events disabled. - } - - ui::CursorSetType cursor_set() const { return cursor_set_; } - void set_cursor_set(ui::CursorSetType cursor_set) { - cursor_set_ = cursor_set; - } - - bool mouse_events_enabled() const { return mouse_events_enabled_; } - void SetMouseEventsEnabled(bool enabled) { - if (mouse_events_enabled_ == enabled) - return; - mouse_events_enabled_ = enabled; - - // Restores the visibility when mouse events are enabled. - if (enabled) { - visible_ = visible_on_mouse_events_enabled_; - } else { - visible_on_mouse_events_enabled_ = visible_; - visible_ = false; - } - } - - private: - gfx::NativeCursor cursor_; - bool visible_; - ui::CursorSetType cursor_set_; - bool mouse_events_enabled_; - - // The visibility to set when mouse events are enabled. - bool visible_on_mouse_events_enabled_; - - DISALLOW_COPY_AND_ASSIGN(CursorState); -}; - -} // namespace internal - -CursorManager::CursorManager(scoped_ptr<NativeCursorManager> delegate) - : delegate_(delegate.Pass()), - cursor_lock_count_(0), - current_state_(new internal::CursorState), - state_on_unlock_(new internal::CursorState) { -} - -CursorManager::~CursorManager() { -} - -void CursorManager::SetCursor(gfx::NativeCursor cursor) { - state_on_unlock_->set_cursor(cursor); - if (cursor_lock_count_ == 0 && - GetCursor() != state_on_unlock_->cursor()) { - delegate_->SetCursor(state_on_unlock_->cursor(), this); - } -} - -gfx::NativeCursor CursorManager::GetCursor() const { - return current_state_->cursor(); -} - -void CursorManager::ShowCursor() { - state_on_unlock_->SetVisible(true); - if (cursor_lock_count_ == 0 && - IsCursorVisible() != state_on_unlock_->visible()) { - delegate_->SetVisibility(state_on_unlock_->visible(), this); - FOR_EACH_OBSERVER(aura::client::CursorClientObserver, observers_, - OnCursorVisibilityChanged(true)); - } -} - -void CursorManager::HideCursor() { - state_on_unlock_->SetVisible(false); - if (cursor_lock_count_ == 0 && - IsCursorVisible() != state_on_unlock_->visible()) { - delegate_->SetVisibility(state_on_unlock_->visible(), this); - FOR_EACH_OBSERVER(aura::client::CursorClientObserver, observers_, - OnCursorVisibilityChanged(false)); - } -} - -bool CursorManager::IsCursorVisible() const { - return current_state_->visible(); -} - -void CursorManager::SetCursorSet(ui::CursorSetType cursor_set) { - state_on_unlock_->set_cursor_set(cursor_set); - if (GetCursorSet() != state_on_unlock_->cursor_set()) - delegate_->SetCursorSet(state_on_unlock_->cursor_set(), this); -} - -ui::CursorSetType CursorManager::GetCursorSet() const { - return current_state_->cursor_set(); -} - -void CursorManager::EnableMouseEvents() { - state_on_unlock_->SetMouseEventsEnabled(true); - if (cursor_lock_count_ == 0 && - IsMouseEventsEnabled() != state_on_unlock_->mouse_events_enabled()) { - delegate_->SetMouseEventsEnabled(state_on_unlock_->mouse_events_enabled(), - this); - } -} - -void CursorManager::DisableMouseEvents() { - state_on_unlock_->SetMouseEventsEnabled(false); - if (cursor_lock_count_ == 0 && - IsMouseEventsEnabled() != state_on_unlock_->mouse_events_enabled()) { - delegate_->SetMouseEventsEnabled(state_on_unlock_->mouse_events_enabled(), - this); - } -} - -bool CursorManager::IsMouseEventsEnabled() const { - return current_state_->mouse_events_enabled(); -} - -void CursorManager::SetDisplay(const gfx::Display& display) { - delegate_->SetDisplay(display, this); -} - -void CursorManager::LockCursor() { - cursor_lock_count_++; -} - -void CursorManager::UnlockCursor() { - cursor_lock_count_--; - DCHECK_GE(cursor_lock_count_, 0); - if (cursor_lock_count_ > 0) - return; - - if (GetCursor() != state_on_unlock_->cursor()) { - delegate_->SetCursor(state_on_unlock_->cursor(), this); - } - if (IsMouseEventsEnabled() != state_on_unlock_->mouse_events_enabled()) { - delegate_->SetMouseEventsEnabled(state_on_unlock_->mouse_events_enabled(), - this); - } - if (IsCursorVisible() != state_on_unlock_->visible()) { - delegate_->SetVisibility(state_on_unlock_->visible(), - this); - } -} - -bool CursorManager::IsCursorLocked() const { - return cursor_lock_count_ > 0; -} - -void CursorManager::AddObserver( - aura::client::CursorClientObserver* observer) { - observers_.AddObserver(observer); -} - -void CursorManager::RemoveObserver( - aura::client::CursorClientObserver* observer) { - observers_.RemoveObserver(observer); -} - -bool CursorManager::ShouldHideCursorOnKeyEvent( - const ui::KeyEvent& event) const { - return false; -} - -void CursorManager::CommitCursor(gfx::NativeCursor cursor) { - current_state_->set_cursor(cursor); -} - -void CursorManager::CommitVisibility(bool visible) { - // TODO(tdanderson): Find a better place for this so we don't - // notify the observers more than is necessary. - FOR_EACH_OBSERVER(aura::client::CursorClientObserver, observers_, - OnCursorVisibilityChanged(visible)); - current_state_->SetVisible(visible); -} - -void CursorManager::CommitCursorSet(ui::CursorSetType cursor_set) { - current_state_->set_cursor_set(cursor_set); -} - -void CursorManager::CommitMouseEventsEnabled(bool enabled) { - current_state_->SetMouseEventsEnabled(enabled); -} - -} // namespace wm
diff --git a/ui/wm/core/cursor_manager.h b/ui/wm/core/cursor_manager.h deleted file mode 100644 index a10b8ac..0000000 --- a/ui/wm/core/cursor_manager.h +++ /dev/null
@@ -1,90 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_CORE_CURSOR_MANAGER_H_ -#define UI_WM_CORE_CURSOR_MANAGER_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "base/observer_list.h" -#include "ui/aura/client/cursor_client.h" -#include "ui/base/cursor/cursor.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/gfx/point.h" -#include "ui/wm/core/native_cursor_manager_delegate.h" -#include "ui/wm/wm_export.h" - -namespace gfx { -class Display; -} - -namespace ui { -class KeyEvent; -} - -namespace wm { - -namespace internal { -class CursorState; -} - -class NativeCursorManager; - -// This class receives requests to change cursor properties, as well as -// requests to queue any further changes until a later time. It sends changes -// to the NativeCursorManager, which communicates back to us when these changes -// were made through the NativeCursorManagerDelegate interface. -class WM_EXPORT CursorManager : public aura::client::CursorClient, - public NativeCursorManagerDelegate { - public: - explicit CursorManager(scoped_ptr<NativeCursorManager> delegate); - ~CursorManager() override; - - // Overridden from aura::client::CursorClient: - void SetCursor(gfx::NativeCursor) override; - gfx::NativeCursor GetCursor() const override; - void ShowCursor() override; - void HideCursor() override; - bool IsCursorVisible() const override; - void SetCursorSet(ui::CursorSetType cursor_set) override; - ui::CursorSetType GetCursorSet() const override; - void EnableMouseEvents() override; - void DisableMouseEvents() override; - bool IsMouseEventsEnabled() const override; - void SetDisplay(const gfx::Display& display) override; - void LockCursor() override; - void UnlockCursor() override; - bool IsCursorLocked() const override; - void AddObserver(aura::client::CursorClientObserver* observer) override; - void RemoveObserver(aura::client::CursorClientObserver* observer) override; - bool ShouldHideCursorOnKeyEvent(const ui::KeyEvent& event) const override; - - private: - // Overridden from NativeCursorManagerDelegate: - void CommitCursor(gfx::NativeCursor cursor) override; - void CommitVisibility(bool visible) override; - void CommitCursorSet(ui::CursorSetType cursor_set) override; - void CommitMouseEventsEnabled(bool enabled) override; - - scoped_ptr<NativeCursorManager> delegate_; - - // Number of times LockCursor() has been invoked without a corresponding - // UnlockCursor(). - int cursor_lock_count_; - - // The current state of the cursor. - scoped_ptr<internal::CursorState> current_state_; - - // The cursor state to restore when the cursor is unlocked. - scoped_ptr<internal::CursorState> state_on_unlock_; - - ObserverList<aura::client::CursorClientObserver> observers_; - - DISALLOW_COPY_AND_ASSIGN(CursorManager); -}; - -} // namespace wm - -#endif // UI_WM_CORE_CURSOR_MANAGER_H_
diff --git a/ui/wm/core/cursor_manager_unittest.cc b/ui/wm/core/cursor_manager_unittest.cc deleted file mode 100644 index 8dd2aa8..0000000 --- a/ui/wm/core/cursor_manager_unittest.cc +++ /dev/null
@@ -1,330 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/cursor_manager.h" - -#include "ui/aura/client/cursor_client_observer.h" -#include "ui/aura/test/aura_test_base.h" -#include "ui/wm/core/native_cursor_manager.h" - -namespace { - -class TestingCursorManager : public wm::NativeCursorManager { - public: - // Overridden from wm::NativeCursorManager: - virtual void SetDisplay( - const gfx::Display& display, - wm::NativeCursorManagerDelegate* delegate) override {} - - virtual void SetCursor( - gfx::NativeCursor cursor, - wm::NativeCursorManagerDelegate* delegate) override { - delegate->CommitCursor(cursor); - } - - virtual void SetVisibility( - bool visible, - wm::NativeCursorManagerDelegate* delegate) override { - delegate->CommitVisibility(visible); - } - - virtual void SetMouseEventsEnabled( - bool enabled, - wm::NativeCursorManagerDelegate* delegate) override { - delegate->CommitMouseEventsEnabled(enabled); - } - - virtual void SetCursorSet( - ui::CursorSetType cursor_set, - wm::NativeCursorManagerDelegate* delegate) override { - delegate->CommitCursorSet(cursor_set); - } -}; - -} // namespace - -class CursorManagerTest : public aura::test::AuraTestBase { - protected: - CursorManagerTest() - : delegate_(new TestingCursorManager), - cursor_manager_(scoped_ptr<wm::NativeCursorManager>( - delegate_)) { - } - - TestingCursorManager* delegate_; - wm::CursorManager cursor_manager_; -}; - -class TestingCursorClientObserver : public aura::client::CursorClientObserver { - public: - TestingCursorClientObserver() - : cursor_visibility_(false), - did_visibility_change_(false) {} - void reset() { cursor_visibility_ = did_visibility_change_ = false; } - bool is_cursor_visible() const { return cursor_visibility_; } - bool did_visibility_change() const { return did_visibility_change_; } - - // Overridden from aura::client::CursorClientObserver: - virtual void OnCursorVisibilityChanged(bool is_visible) override { - cursor_visibility_ = is_visible; - did_visibility_change_ = true; - } - - private: - bool cursor_visibility_; - bool did_visibility_change_; - - DISALLOW_COPY_AND_ASSIGN(TestingCursorClientObserver); -}; - -TEST_F(CursorManagerTest, ShowHideCursor) { - cursor_manager_.SetCursor(ui::kCursorCopy); - EXPECT_EQ(ui::kCursorCopy, cursor_manager_.GetCursor().native_type()); - - cursor_manager_.ShowCursor(); - EXPECT_TRUE(cursor_manager_.IsCursorVisible()); - cursor_manager_.HideCursor(); - EXPECT_FALSE(cursor_manager_.IsCursorVisible()); - // The current cursor does not change even when the cursor is not shown. - EXPECT_EQ(ui::kCursorCopy, cursor_manager_.GetCursor().native_type()); - - // Check if cursor visibility is locked. - cursor_manager_.LockCursor(); - EXPECT_FALSE(cursor_manager_.IsCursorVisible()); - cursor_manager_.ShowCursor(); - EXPECT_FALSE(cursor_manager_.IsCursorVisible()); - cursor_manager_.UnlockCursor(); - EXPECT_TRUE(cursor_manager_.IsCursorVisible()); - - cursor_manager_.LockCursor(); - EXPECT_TRUE(cursor_manager_.IsCursorVisible()); - cursor_manager_.HideCursor(); - EXPECT_TRUE(cursor_manager_.IsCursorVisible()); - cursor_manager_.UnlockCursor(); - EXPECT_FALSE(cursor_manager_.IsCursorVisible()); - - // Checks setting visiblity while cursor is locked does not affect the - // subsequent uses of UnlockCursor. - cursor_manager_.LockCursor(); - cursor_manager_.HideCursor(); - cursor_manager_.UnlockCursor(); - EXPECT_FALSE(cursor_manager_.IsCursorVisible()); - - cursor_manager_.ShowCursor(); - cursor_manager_.LockCursor(); - cursor_manager_.UnlockCursor(); - EXPECT_TRUE(cursor_manager_.IsCursorVisible()); - - cursor_manager_.LockCursor(); - cursor_manager_.ShowCursor(); - cursor_manager_.UnlockCursor(); - EXPECT_TRUE(cursor_manager_.IsCursorVisible()); - - cursor_manager_.HideCursor(); - cursor_manager_.LockCursor(); - cursor_manager_.UnlockCursor(); - EXPECT_FALSE(cursor_manager_.IsCursorVisible()); -} - -// Verifies that LockCursor/UnlockCursor work correctly with -// EnableMouseEvents and DisableMouseEvents -TEST_F(CursorManagerTest, EnableDisableMouseEvents) { - cursor_manager_.SetCursor(ui::kCursorCopy); - EXPECT_EQ(ui::kCursorCopy, cursor_manager_.GetCursor().native_type()); - - cursor_manager_.EnableMouseEvents(); - EXPECT_TRUE(cursor_manager_.IsMouseEventsEnabled()); - cursor_manager_.DisableMouseEvents(); - EXPECT_FALSE(cursor_manager_.IsMouseEventsEnabled()); - // The current cursor does not change even when the cursor is not shown. - EXPECT_EQ(ui::kCursorCopy, cursor_manager_.GetCursor().native_type()); - - // Check if cursor enable state is locked. - cursor_manager_.LockCursor(); - EXPECT_FALSE(cursor_manager_.IsMouseEventsEnabled()); - cursor_manager_.EnableMouseEvents(); - EXPECT_FALSE(cursor_manager_.IsMouseEventsEnabled()); - cursor_manager_.UnlockCursor(); - EXPECT_TRUE(cursor_manager_.IsMouseEventsEnabled()); - - cursor_manager_.LockCursor(); - EXPECT_TRUE(cursor_manager_.IsMouseEventsEnabled()); - cursor_manager_.DisableMouseEvents(); - EXPECT_TRUE(cursor_manager_.IsMouseEventsEnabled()); - cursor_manager_.UnlockCursor(); - EXPECT_FALSE(cursor_manager_.IsMouseEventsEnabled()); - - // Checks enabling cursor while cursor is locked does not affect the - // subsequent uses of UnlockCursor. - cursor_manager_.LockCursor(); - cursor_manager_.DisableMouseEvents(); - cursor_manager_.UnlockCursor(); - EXPECT_FALSE(cursor_manager_.IsMouseEventsEnabled()); - - cursor_manager_.EnableMouseEvents(); - cursor_manager_.LockCursor(); - cursor_manager_.UnlockCursor(); - EXPECT_TRUE(cursor_manager_.IsMouseEventsEnabled()); - - cursor_manager_.LockCursor(); - cursor_manager_.EnableMouseEvents(); - cursor_manager_.UnlockCursor(); - EXPECT_TRUE(cursor_manager_.IsMouseEventsEnabled()); - - cursor_manager_.DisableMouseEvents(); - cursor_manager_.LockCursor(); - cursor_manager_.UnlockCursor(); - EXPECT_FALSE(cursor_manager_.IsMouseEventsEnabled()); -} - -TEST_F(CursorManagerTest, SetCursorSet) { - EXPECT_EQ(ui::CURSOR_SET_NORMAL, cursor_manager_.GetCursorSet()); - - cursor_manager_.SetCursorSet(ui::CURSOR_SET_NORMAL); - EXPECT_EQ(ui::CURSOR_SET_NORMAL, cursor_manager_.GetCursorSet()); - - cursor_manager_.SetCursorSet(ui::CURSOR_SET_LARGE); - EXPECT_EQ(ui::CURSOR_SET_LARGE, cursor_manager_.GetCursorSet()); - - cursor_manager_.SetCursorSet(ui::CURSOR_SET_NORMAL); - EXPECT_EQ(ui::CURSOR_SET_NORMAL, cursor_manager_.GetCursorSet()); -} - -TEST_F(CursorManagerTest, IsMouseEventsEnabled) { - cursor_manager_.EnableMouseEvents(); - EXPECT_TRUE(cursor_manager_.IsMouseEventsEnabled()); - cursor_manager_.DisableMouseEvents(); - EXPECT_FALSE(cursor_manager_.IsMouseEventsEnabled()); -} - -// Verifies that the mouse events enable state changes correctly when -// ShowCursor/HideCursor and EnableMouseEvents/DisableMouseEvents are used -// together. -TEST_F(CursorManagerTest, ShowAndEnable) { - // Changing the visibility of the cursor does not affect the enable state. - cursor_manager_.EnableMouseEvents(); - cursor_manager_.ShowCursor(); - EXPECT_TRUE(cursor_manager_.IsCursorVisible()); - EXPECT_TRUE(cursor_manager_.IsMouseEventsEnabled()); - cursor_manager_.HideCursor(); - EXPECT_FALSE(cursor_manager_.IsCursorVisible()); - EXPECT_TRUE(cursor_manager_.IsMouseEventsEnabled()); - cursor_manager_.ShowCursor(); - EXPECT_TRUE(cursor_manager_.IsCursorVisible()); - EXPECT_TRUE(cursor_manager_.IsMouseEventsEnabled()); - - // When mouse events are disabled, it also gets invisible. - EXPECT_TRUE(cursor_manager_.IsCursorVisible()); - cursor_manager_.DisableMouseEvents(); - EXPECT_FALSE(cursor_manager_.IsCursorVisible()); - EXPECT_FALSE(cursor_manager_.IsMouseEventsEnabled()); - - // When mouse events are enabled, it restores the visibility state. - cursor_manager_.EnableMouseEvents(); - EXPECT_TRUE(cursor_manager_.IsCursorVisible()); - EXPECT_TRUE(cursor_manager_.IsMouseEventsEnabled()); - - cursor_manager_.ShowCursor(); - cursor_manager_.DisableMouseEvents(); - EXPECT_FALSE(cursor_manager_.IsCursorVisible()); - EXPECT_FALSE(cursor_manager_.IsMouseEventsEnabled()); - cursor_manager_.EnableMouseEvents(); - EXPECT_TRUE(cursor_manager_.IsCursorVisible()); - EXPECT_TRUE(cursor_manager_.IsMouseEventsEnabled()); - - cursor_manager_.HideCursor(); - cursor_manager_.DisableMouseEvents(); - EXPECT_FALSE(cursor_manager_.IsCursorVisible()); - EXPECT_FALSE(cursor_manager_.IsMouseEventsEnabled()); - cursor_manager_.EnableMouseEvents(); - EXPECT_FALSE(cursor_manager_.IsCursorVisible()); - EXPECT_TRUE(cursor_manager_.IsMouseEventsEnabled()); - - // When mouse events are disabled, ShowCursor is ignored. - cursor_manager_.DisableMouseEvents(); - EXPECT_FALSE(cursor_manager_.IsCursorVisible()); - EXPECT_FALSE(cursor_manager_.IsMouseEventsEnabled()); - cursor_manager_.ShowCursor(); - EXPECT_FALSE(cursor_manager_.IsCursorVisible()); - EXPECT_FALSE(cursor_manager_.IsMouseEventsEnabled()); - cursor_manager_.DisableMouseEvents(); - EXPECT_FALSE(cursor_manager_.IsCursorVisible()); - EXPECT_FALSE(cursor_manager_.IsMouseEventsEnabled()); -} - -// Verifies that calling DisableMouseEvents multiple times in a row makes no -// difference compared with calling it once. -// This is a regression test for http://crbug.com/169404. -TEST_F(CursorManagerTest, MultipleDisableMouseEvents) { - cursor_manager_.DisableMouseEvents(); - cursor_manager_.DisableMouseEvents(); - cursor_manager_.EnableMouseEvents(); - cursor_manager_.LockCursor(); - cursor_manager_.UnlockCursor(); - EXPECT_TRUE(cursor_manager_.IsCursorVisible()); -} - -// Verifies that calling EnableMouseEvents multiple times in a row makes no -// difference compared with calling it once. -TEST_F(CursorManagerTest, MultipleEnableMouseEvents) { - cursor_manager_.DisableMouseEvents(); - cursor_manager_.EnableMouseEvents(); - cursor_manager_.EnableMouseEvents(); - cursor_manager_.LockCursor(); - cursor_manager_.UnlockCursor(); - EXPECT_TRUE(cursor_manager_.IsCursorVisible()); -} - -TEST_F(CursorManagerTest, TestCursorClientObserver) { - // Add two observers. Both should have OnCursorVisibilityChanged() - // invoked when the visibility of the cursor changes. - TestingCursorClientObserver observer_a; - TestingCursorClientObserver observer_b; - cursor_manager_.AddObserver(&observer_a); - cursor_manager_.AddObserver(&observer_b); - - // Initial state before any events have been sent. - observer_a.reset(); - observer_b.reset(); - EXPECT_FALSE(observer_a.did_visibility_change()); - EXPECT_FALSE(observer_b.did_visibility_change()); - EXPECT_FALSE(observer_a.is_cursor_visible()); - EXPECT_FALSE(observer_b.is_cursor_visible()); - - // Hide the cursor using HideCursor(). - cursor_manager_.HideCursor(); - EXPECT_TRUE(observer_a.did_visibility_change()); - EXPECT_TRUE(observer_b.did_visibility_change()); - EXPECT_FALSE(observer_a.is_cursor_visible()); - EXPECT_FALSE(observer_b.is_cursor_visible()); - - // Show the cursor using ShowCursor(). - observer_a.reset(); - observer_b.reset(); - cursor_manager_.ShowCursor(); - EXPECT_TRUE(observer_a.did_visibility_change()); - EXPECT_TRUE(observer_b.did_visibility_change()); - EXPECT_TRUE(observer_a.is_cursor_visible()); - EXPECT_TRUE(observer_b.is_cursor_visible()); - - // Remove observer_b. Its OnCursorVisibilityChanged() should - // not be invoked past this point. - cursor_manager_.RemoveObserver(&observer_b); - - // Hide the cursor using HideCursor(). - observer_a.reset(); - observer_b.reset(); - cursor_manager_.HideCursor(); - EXPECT_TRUE(observer_a.did_visibility_change()); - EXPECT_FALSE(observer_b.did_visibility_change()); - EXPECT_FALSE(observer_a.is_cursor_visible()); - - // Show the cursor using ShowCursor(). - observer_a.reset(); - observer_b.reset(); - cursor_manager_.ShowCursor(); - EXPECT_TRUE(observer_a.did_visibility_change()); - EXPECT_FALSE(observer_b.did_visibility_change()); - EXPECT_TRUE(observer_a.is_cursor_visible()); -}
diff --git a/ui/wm/core/default_activation_client.cc b/ui/wm/core/default_activation_client.cc deleted file mode 100644 index d6383d6..0000000 --- a/ui/wm/core/default_activation_client.cc +++ /dev/null
@@ -1,152 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/default_activation_client.h" - -#include "ui/aura/window.h" -#include "ui/wm/public/activation_change_observer.h" -#include "ui/wm/public/activation_delegate.h" - -namespace wm { - -// Takes care of observing root window destruction & destroying the client. -class DefaultActivationClient::Deleter : public aura::WindowObserver { - public: - Deleter(DefaultActivationClient* client, aura::Window* root_window) - : client_(client), - root_window_(root_window) { - root_window_->AddObserver(this); - } - - private: - virtual ~Deleter() {} - - // Overridden from WindowObserver: - virtual void OnWindowDestroyed(aura::Window* window) override { - DCHECK_EQ(window, root_window_); - root_window_->RemoveObserver(this); - delete client_; - delete this; - } - - DefaultActivationClient* client_; - aura::Window* root_window_; - - DISALLOW_COPY_AND_ASSIGN(Deleter); -}; - -//////////////////////////////////////////////////////////////////////////////// -// DefaultActivationClient, public: - -DefaultActivationClient::DefaultActivationClient(aura::Window* root_window) - : last_active_(NULL) { - aura::client::SetActivationClient(root_window, this); - new Deleter(this, root_window); -} - -//////////////////////////////////////////////////////////////////////////////// -// DefaultActivationClient, client::ActivationClient implementation: - -void DefaultActivationClient::AddObserver( - aura::client::ActivationChangeObserver* observer) { - observers_.AddObserver(observer); -} - -void DefaultActivationClient::RemoveObserver( - aura::client::ActivationChangeObserver* observer) { - observers_.RemoveObserver(observer); -} - -void DefaultActivationClient::ActivateWindow(aura::Window* window) { - aura::Window* last_active = GetActiveWindow(); - if (last_active == window) - return; - - last_active_ = last_active; - RemoveActiveWindow(window); - active_windows_.push_back(window); - window->parent()->StackChildAtTop(window); - window->AddObserver(this); - - FOR_EACH_OBSERVER(aura::client::ActivationChangeObserver, - observers_, - OnWindowActivated(window, last_active)); - - aura::client::ActivationChangeObserver* observer = - aura::client::GetActivationChangeObserver(last_active); - if (observer) - observer->OnWindowActivated(window, last_active); - observer = aura::client::GetActivationChangeObserver(window); - if (observer) - observer->OnWindowActivated(window, last_active); -} - -void DefaultActivationClient::DeactivateWindow(aura::Window* window) { - aura::client::ActivationChangeObserver* observer = - aura::client::GetActivationChangeObserver(window); - if (observer) - observer->OnWindowActivated(NULL, window); - if (last_active_) - ActivateWindow(last_active_); -} - -aura::Window* DefaultActivationClient::GetActiveWindow() { - if (active_windows_.empty()) - return NULL; - return active_windows_.back(); -} - -aura::Window* DefaultActivationClient::GetActivatableWindow( - aura::Window* window) { - return NULL; -} - -aura::Window* DefaultActivationClient::GetToplevelWindow(aura::Window* window) { - return NULL; -} - -bool DefaultActivationClient::CanActivateWindow(aura::Window* window) const { - return true; -} - -//////////////////////////////////////////////////////////////////////////////// -// DefaultActivationClient, aura::WindowObserver implementation: - -void DefaultActivationClient::OnWindowDestroyed(aura::Window* window) { - if (window == last_active_) - last_active_ = NULL; - - if (window == GetActiveWindow()) { - active_windows_.pop_back(); - aura::Window* next_active = GetActiveWindow(); - if (next_active && aura::client::GetActivationChangeObserver(next_active)) { - aura::client::GetActivationChangeObserver(next_active)->OnWindowActivated( - next_active, NULL); - } - return; - } - - RemoveActiveWindow(window); -} - -//////////////////////////////////////////////////////////////////////////////// -// DefaultActivationClient, private: - -DefaultActivationClient::~DefaultActivationClient() { - for (unsigned int i = 0; i < active_windows_.size(); ++i) { - active_windows_[i]->RemoveObserver(this); - } -} - -void DefaultActivationClient::RemoveActiveWindow(aura::Window* window) { - for (unsigned int i = 0; i < active_windows_.size(); ++i) { - if (active_windows_[i] == window) { - active_windows_.erase(active_windows_.begin() + i); - window->RemoveObserver(this); - return; - } - } -} - -} // namespace wm
diff --git a/ui/wm/core/default_activation_client.h b/ui/wm/core/default_activation_client.h deleted file mode 100644 index fb9f9e2..0000000 --- a/ui/wm/core/default_activation_client.h +++ /dev/null
@@ -1,71 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_CORE_DEFAULT_ACTIVATION_CLIENT_H_ -#define UI_WM_CORE_DEFAULT_ACTIVATION_CLIENT_H_ - -#include <vector> - -#include "base/compiler_specific.h" -#include "base/logging.h" -#include "base/observer_list.h" -#include "ui/aura/window_observer.h" -#include "ui/wm/public/activation_client.h" -#include "ui/wm/wm_export.h" - -namespace aura { -namespace client { -class ActivationChangeObserver; -} -} - -namespace wm { - -// Simple ActivationClient implementation for use by tests and other targets -// that just need basic behavior (e.g. activate windows whenever requested, -// restack windows at the top when they're activated, etc.). This object deletes -// itself when the root window it is associated with is destroyed. -class WM_EXPORT DefaultActivationClient : public aura::client::ActivationClient, - public aura::WindowObserver { - public: - explicit DefaultActivationClient(aura::Window* root_window); - - // Overridden from aura::client::ActivationClient: - virtual void AddObserver( - aura::client::ActivationChangeObserver* observer) override; - virtual void RemoveObserver( - aura::client::ActivationChangeObserver* observer) override; - virtual void ActivateWindow(aura::Window* window) override; - virtual void DeactivateWindow(aura::Window* window) override; - virtual aura::Window* GetActiveWindow() override; - virtual aura::Window* GetActivatableWindow(aura::Window* window) override; - virtual aura::Window* GetToplevelWindow(aura::Window* window) override; - virtual bool CanActivateWindow(aura::Window* window) const override; - - // Overridden from WindowObserver: - virtual void OnWindowDestroyed(aura::Window* window) override; - - private: - class Deleter; - - virtual ~DefaultActivationClient(); - void RemoveActiveWindow(aura::Window* window); - - // This class explicitly does NOT store the active window in a window property - // to make sure that ActivationChangeObserver is not treated as part of the - // aura API. Assumptions to that end will cause tests that use this client to - // fail. - std::vector<aura::Window*> active_windows_; - - // The window which was active before the currently active one. - aura::Window* last_active_; - - ObserverList<aura::client::ActivationChangeObserver> observers_; - - DISALLOW_COPY_AND_ASSIGN(DefaultActivationClient); -}; - -} // namespace wm - -#endif // UI_WM_CORE_DEFAULT_ACTIVATION_CLIENT_H_
diff --git a/ui/wm/core/easy_resize_window_targeter.cc b/ui/wm/core/easy_resize_window_targeter.cc deleted file mode 100644 index 445028c..0000000 --- a/ui/wm/core/easy_resize_window_targeter.cc +++ /dev/null
@@ -1,62 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/easy_resize_window_targeter.h" - -#include "ui/aura/window.h" -#include "ui/gfx/geometry/insets_f.h" -#include "ui/gfx/geometry/rect.h" -#include "ui/wm/public/transient_window_client.h" - -namespace wm { - -EasyResizeWindowTargeter::EasyResizeWindowTargeter( - aura::Window* container, - const gfx::Insets& mouse_extend, - const gfx::Insets& touch_extend) - : container_(container), - mouse_extend_(mouse_extend), - touch_extend_(touch_extend) { -} - -EasyResizeWindowTargeter::~EasyResizeWindowTargeter() { -} - -bool EasyResizeWindowTargeter::EventLocationInsideBounds( - ui::EventTarget* target, - const ui::LocatedEvent& event) const { - aura::Window* window = static_cast<aura::Window*>(target); - if (ShouldUseExtendedBounds(window)) { - // Note that |event|'s location is in |window|'s parent's coordinate system, - // so convert it to |window|'s coordinate system first. - gfx::Point point = event.location(); - if (window->parent()) - aura::Window::ConvertPointToTarget(window->parent(), window, &point); - - gfx::Rect bounds(window->bounds().size()); - if (event.IsTouchEvent() || event.IsGestureEvent()) - bounds.Inset(touch_extend_); - else - bounds.Inset(mouse_extend_); - - return bounds.Contains(point); - } - return WindowTargeter::EventLocationInsideBounds(window, event); -} - -bool EasyResizeWindowTargeter::ShouldUseExtendedBounds( - const aura::Window* window) const { - // Use the extended bounds only for immediate child windows of |container_|. - // Use the default targetter otherwise. - if (window->parent() != container_) - return false; - - aura::client::TransientWindowClient* transient_window_client = - aura::client::GetTransientWindowClient(); - return !transient_window_client || - !transient_window_client->GetTransientParent(window) || - transient_window_client->GetTransientParent(window) == container_; -} - -} // namespace wm
diff --git a/ui/wm/core/easy_resize_window_targeter.h b/ui/wm/core/easy_resize_window_targeter.h deleted file mode 100644 index 5693300..0000000 --- a/ui/wm/core/easy_resize_window_targeter.h +++ /dev/null
@@ -1,53 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_CORE_EASY_RESIZE_WINDOW_TARGETER_H_ -#define UI_WM_CORE_EASY_RESIZE_WINDOW_TARGETER_H_ - -#include "ui/aura/window_targeter.h" -#include "ui/gfx/geometry/insets.h" -#include "ui/wm/wm_export.h" - -namespace wm { - -// An EventTargeter for a container window that uses a slightly larger -// hit-target region for easier resize. -class WM_EXPORT EasyResizeWindowTargeter : public aura::WindowTargeter { - public: - // |container| window is the owner of this targeter. - EasyResizeWindowTargeter(aura::Window* container, - const gfx::Insets& mouse_extend, - const gfx::Insets& touch_extend); - - virtual ~EasyResizeWindowTargeter(); - - protected: - void set_mouse_extend(const gfx::Insets& mouse_extend) { - mouse_extend_ = mouse_extend; - } - - void set_touch_extend(const gfx::Insets& touch_extend) { - touch_extend_ = touch_extend; - } - - // ui::EventTargeter: - virtual bool EventLocationInsideBounds( - ui::EventTarget* target, - const ui::LocatedEvent& event) const override; - - private: - // Returns true if the hit testing (EventLocationInsideBounds()) should use - // the extended bounds. - bool ShouldUseExtendedBounds(const aura::Window* window) const; - - aura::Window* container_; - gfx::Insets mouse_extend_; - gfx::Insets touch_extend_; - - DISALLOW_COPY_AND_ASSIGN(EasyResizeWindowTargeter); -}; - -} // namespace wm - -#endif // UI_WM_CORE_EASY_RESIZE_WINDOW_TARGETER_H_
diff --git a/ui/wm/core/focus_controller.cc b/ui/wm/core/focus_controller.cc deleted file mode 100644 index 66c6deb..0000000 --- a/ui/wm/core/focus_controller.cc +++ /dev/null
@@ -1,362 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/focus_controller.h" - -#include "base/auto_reset.h" -#include "ui/aura/client/aura_constants.h" -#include "ui/aura/client/capture_client.h" -#include "ui/aura/client/focus_change_observer.h" -#include "ui/aura/env.h" -#include "ui/aura/window_tracker.h" -#include "ui/base/ime/text_input_focus_manager.h" -#include "ui/events/event.h" -#include "ui/wm/core/focus_rules.h" -#include "ui/wm/core/window_util.h" -#include "ui/wm/public/activation_change_observer.h" - -namespace wm { -namespace { - -// When a modal window is activated, we bring its entire transient parent chain -// to the front. This function must be called before the modal transient is -// stacked at the top to ensure correct stacking order. -void StackTransientParentsBelowModalWindow(aura::Window* window) { - if (window->GetProperty(aura::client::kModalKey) != ui::MODAL_TYPE_WINDOW) - return; - - aura::Window* transient_parent = wm::GetTransientParent(window); - while (transient_parent) { - transient_parent->parent()->StackChildAtTop(transient_parent); - transient_parent = wm::GetTransientParent(transient_parent); - } -} - -} // namespace - -//////////////////////////////////////////////////////////////////////////////// -// FocusController, public: - -FocusController::FocusController(FocusRules* rules) - : active_window_(NULL), - focused_window_(NULL), - updating_focus_(false), - updating_activation_(false), - rules_(rules), - observer_manager_(this) { - DCHECK(rules); -} - -FocusController::~FocusController() { -} - -//////////////////////////////////////////////////////////////////////////////// -// FocusController, aura::client::ActivationClient implementation: - -void FocusController::AddObserver( - aura::client::ActivationChangeObserver* observer) { - activation_observers_.AddObserver(observer); -} - -void FocusController::RemoveObserver( - aura::client::ActivationChangeObserver* observer) { - activation_observers_.RemoveObserver(observer); -} - -void FocusController::ActivateWindow(aura::Window* window) { - FocusWindow(window); -} - -void FocusController::DeactivateWindow(aura::Window* window) { - if (window) - FocusWindow(rules_->GetNextActivatableWindow(window)); -} - -aura::Window* FocusController::GetActiveWindow() { - return active_window_; -} - -aura::Window* FocusController::GetActivatableWindow(aura::Window* window) { - return rules_->GetActivatableWindow(window); -} - -aura::Window* FocusController::GetToplevelWindow(aura::Window* window) { - return rules_->GetToplevelWindow(window); -} - -bool FocusController::CanActivateWindow(aura::Window* window) const { - return rules_->CanActivateWindow(window); -} - -//////////////////////////////////////////////////////////////////////////////// -// FocusController, aura::client::FocusClient implementation: - -void FocusController::AddObserver( - aura::client::FocusChangeObserver* observer) { - focus_observers_.AddObserver(observer); -} - -void FocusController::RemoveObserver( - aura::client::FocusChangeObserver* observer) { - focus_observers_.RemoveObserver(observer); -} - -void FocusController::FocusWindow(aura::Window* window) { - if (window && - (window->Contains(focused_window_) || window->Contains(active_window_))) { - return; - } - - // We should not be messing with the focus if the window has capture, unless - // no has focus. - if (window && (aura::client::GetCaptureWindow(window) == window) && - focused_window_) { - return; - } - - // Focusing a window also activates its containing activatable window. Note - // that the rules could redirect activation activation and/or focus. - aura::Window* focusable = rules_->GetFocusableWindow(window); - aura::Window* activatable = - focusable ? rules_->GetActivatableWindow(focusable) : NULL; - - // We need valid focusable/activatable windows in the event we're not clearing - // focus. "Clearing focus" is inferred by whether or not |window| passed to - // this function is non-NULL. - if (window && (!focusable || !activatable)) - return; - DCHECK((focusable && activatable) || !window); - - // Activation change observers may change the focused window. If this happens - // we must not adjust the focus below since this will clobber that change. - aura::Window* last_focused_window = focused_window_; - if (!updating_activation_) - SetActiveWindow(window, activatable); - - // If the window's ActivationChangeObserver shifted focus to a valid window, - // we don't want to focus the window we thought would be focused by default. - bool activation_changed_focus = last_focused_window != focused_window_; - if (!updating_focus_ && (!activation_changed_focus || !focused_window_)) { - if (active_window_ && focusable) - DCHECK(active_window_->Contains(focusable)); - SetFocusedWindow(focusable); - } -} - -void FocusController::ResetFocusWithinActiveWindow(aura::Window* window) { - DCHECK(window); - if (!active_window_) - return; - if (!active_window_->Contains(window)) - return; - SetFocusedWindow(window); -} - -aura::Window* FocusController::GetFocusedWindow() { - return focused_window_; -} - -//////////////////////////////////////////////////////////////////////////////// -// FocusController, ui::EventHandler implementation: -void FocusController::OnKeyEvent(ui::KeyEvent* event) { -} - -void FocusController::OnMouseEvent(ui::MouseEvent* event) { - if (event->type() == ui::ET_MOUSE_PRESSED && !event->handled()) - WindowFocusedFromInputEvent(static_cast<aura::Window*>(event->target())); -} - -void FocusController::OnScrollEvent(ui::ScrollEvent* event) { -} - -void FocusController::OnTouchEvent(ui::TouchEvent* event) { -} - -void FocusController::OnGestureEvent(ui::GestureEvent* event) { - if (event->type() == ui::ET_GESTURE_BEGIN && - event->details().touch_points() == 1 && - !event->handled()) { - WindowFocusedFromInputEvent(static_cast<aura::Window*>(event->target())); - } -} - -//////////////////////////////////////////////////////////////////////////////// -// FocusController, aura::WindowObserver implementation: - -void FocusController::OnWindowVisibilityChanged(aura::Window* window, - bool visible) { - if (!visible) - WindowLostFocusFromDispositionChange(window, window->parent()); -} - -void FocusController::OnWindowDestroying(aura::Window* window) { - WindowLostFocusFromDispositionChange(window, window->parent()); -} - -void FocusController::OnWindowHierarchyChanging( - const HierarchyChangeParams& params) { - if (params.receiver == active_window_ && - params.target->Contains(params.receiver) && (!params.new_parent || - aura::client::GetFocusClient(params.new_parent) != - aura::client::GetFocusClient(params.receiver))) { - WindowLostFocusFromDispositionChange(params.receiver, params.old_parent); - } -} - -void FocusController::OnWindowHierarchyChanged( - const HierarchyChangeParams& params) { - if (params.receiver == focused_window_ && - params.target->Contains(params.receiver) && (!params.new_parent || - aura::client::GetFocusClient(params.new_parent) != - aura::client::GetFocusClient(params.receiver))) { - WindowLostFocusFromDispositionChange(params.receiver, params.old_parent); - } -} - -//////////////////////////////////////////////////////////////////////////////// -// FocusController, private: - -void FocusController::SetFocusedWindow(aura::Window* window) { - if (updating_focus_ || window == focused_window_) - return; - DCHECK(rules_->CanFocusWindow(window)); - if (window) - DCHECK_EQ(window, rules_->GetFocusableWindow(window)); - - base::AutoReset<bool> updating_focus(&updating_focus_, true); - aura::Window* lost_focus = focused_window_; - - // |window| is going to get the focus, so reset the text input client. - // OnWindowFocused() may set a proper text input client if the implementation - // supports text input. - ui::TextInputFocusManager* text_input_focus_manager = - ui::TextInputFocusManager::GetInstance(); - if (window) - text_input_focus_manager->FocusTextInputClient(NULL); - - // Allow for the window losing focus to be deleted during dispatch. If it is - // deleted pass NULL to observers instead of a deleted window. - aura::WindowTracker window_tracker; - if (lost_focus) - window_tracker.Add(lost_focus); - if (focused_window_ && observer_manager_.IsObserving(focused_window_) && - focused_window_ != active_window_) { - observer_manager_.Remove(focused_window_); - } - focused_window_ = window; - if (focused_window_ && !observer_manager_.IsObserving(focused_window_)) - observer_manager_.Add(focused_window_); - - FOR_EACH_OBSERVER(aura::client::FocusChangeObserver, - focus_observers_, - OnWindowFocused(focused_window_, - window_tracker.Contains(lost_focus) ? - lost_focus : NULL)); - if (window_tracker.Contains(lost_focus)) { - aura::client::FocusChangeObserver* observer = - aura::client::GetFocusChangeObserver(lost_focus); - if (observer) - observer->OnWindowFocused(focused_window_, lost_focus); - } - aura::client::FocusChangeObserver* observer = - aura::client::GetFocusChangeObserver(focused_window_); - if (observer) { - observer->OnWindowFocused( - focused_window_, - window_tracker.Contains(lost_focus) ? lost_focus : NULL); - } - - // Ensure that the text input client is reset when the window loses the focus. - if (!window) - text_input_focus_manager->FocusTextInputClient(NULL); -} - -void FocusController::SetActiveWindow(aura::Window* requested_window, - aura::Window* window) { - if (updating_activation_) - return; - - if (window == active_window_) { - if (requested_window) { - FOR_EACH_OBSERVER(aura::client::ActivationChangeObserver, - activation_observers_, - OnAttemptToReactivateWindow(requested_window, - active_window_)); - } - return; - } - - DCHECK(rules_->CanActivateWindow(window)); - if (window) - DCHECK_EQ(window, rules_->GetActivatableWindow(window)); - - base::AutoReset<bool> updating_activation(&updating_activation_, true); - aura::Window* lost_activation = active_window_; - // Allow for the window losing activation to be deleted during dispatch. If - // it is deleted pass NULL to observers instead of a deleted window. - aura::WindowTracker window_tracker; - if (lost_activation) - window_tracker.Add(lost_activation); - if (active_window_ && observer_manager_.IsObserving(active_window_) && - focused_window_ != active_window_) { - observer_manager_.Remove(active_window_); - } - active_window_ = window; - if (active_window_ && !observer_manager_.IsObserving(active_window_)) - observer_manager_.Add(active_window_); - if (active_window_) { - StackTransientParentsBelowModalWindow(active_window_); - active_window_->parent()->StackChildAtTop(active_window_); - } - - aura::client::ActivationChangeObserver* observer = NULL; - if (window_tracker.Contains(lost_activation)) { - observer = aura::client::GetActivationChangeObserver(lost_activation); - if (observer) - observer->OnWindowActivated(active_window_, lost_activation); - } - observer = aura::client::GetActivationChangeObserver(active_window_); - if (observer) { - observer->OnWindowActivated( - active_window_, - window_tracker.Contains(lost_activation) ? lost_activation : NULL); - } - FOR_EACH_OBSERVER(aura::client::ActivationChangeObserver, - activation_observers_, - OnWindowActivated(active_window_, - window_tracker.Contains(lost_activation) ? - lost_activation : NULL)); -} - -void FocusController::WindowLostFocusFromDispositionChange( - aura::Window* window, - aura::Window* next) { - // A window's modality state will interfere with focus restoration during its - // destruction. - window->ClearProperty(aura::client::kModalKey); - // TODO(beng): See if this function can be replaced by a call to - // FocusWindow(). - // Activation adjustments are handled first in the event of a disposition - // changed. If an activation change is necessary, focus is reset as part of - // that process so there's no point in updating focus independently. - if (window == active_window_) { - aura::Window* next_activatable = rules_->GetNextActivatableWindow(window); - SetActiveWindow(NULL, next_activatable); - if (!(active_window_ && active_window_->Contains(focused_window_))) - SetFocusedWindow(next_activatable); - } else if (window->Contains(focused_window_)) { - // Active window isn't changing, but focused window might be. - SetFocusedWindow(rules_->GetFocusableWindow(next)); - } -} - -void FocusController::WindowFocusedFromInputEvent(aura::Window* window) { - // Only focus |window| if it or any of its parents can be focused. Otherwise - // FocusWindow() will focus the topmost window, which may not be the - // currently focused one. - if (rules_->CanFocusWindow(GetToplevelWindow(window))) - FocusWindow(window); -} - -} // namespace wm
diff --git a/ui/wm/core/focus_controller.h b/ui/wm/core/focus_controller.h deleted file mode 100644 index 9e4149f..0000000 --- a/ui/wm/core/focus_controller.h +++ /dev/null
@@ -1,126 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_CORE_FOCUS_CONTROLLER_H_ -#define UI_WM_CORE_FOCUS_CONTROLLER_H_ - -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "base/observer_list.h" -#include "base/scoped_observer.h" -#include "ui/aura/client/focus_client.h" -#include "ui/aura/window_observer.h" -#include "ui/events/event_handler.h" -#include "ui/wm/public/activation_client.h" -#include "ui/wm/wm_export.h" - -namespace wm { - -class FocusRules; - -// FocusController handles focus and activation changes for an environment -// encompassing one or more RootWindows. Within an environment there can be -// only one focused and one active window at a time. When focus or activation -// changes notifications are sent using the -// aura::client::Focus/ActivationChangeObserver interfaces. -// Changes to focus and activation can be from three sources: -// . the Aura Client API (implemented here in aura::client::ActivationClient). -// (The FocusController must be set as the ActivationClient implementation -// for all RootWindows). -// . input events (implemented here in ui::EventHandler). -// (The FocusController must be registered as a pre-target handler for -// the applicable environment owner, either a RootWindow or another type). -// . Window disposition changes (implemented here in aura::WindowObserver). -// (The FocusController registers itself as an observer of the active and -// focused windows). -class WM_EXPORT FocusController : public aura::client::ActivationClient, - public aura::client::FocusClient, - public ui::EventHandler, - public aura::WindowObserver { - public: - // |rules| cannot be NULL. - explicit FocusController(FocusRules* rules); - virtual ~FocusController(); - - private: - // Overridden from aura::client::ActivationClient: - virtual void AddObserver( - aura::client::ActivationChangeObserver* observer) override; - virtual void RemoveObserver( - aura::client::ActivationChangeObserver* observer) override; - virtual void ActivateWindow(aura::Window* window) override; - virtual void DeactivateWindow(aura::Window* window) override; - virtual aura::Window* GetActiveWindow() override; - virtual aura::Window* GetActivatableWindow(aura::Window* window) override; - virtual aura::Window* GetToplevelWindow(aura::Window* window) override; - virtual bool CanActivateWindow(aura::Window* window) const override; - - // Overridden from aura::client::FocusClient: - virtual void AddObserver( - aura::client::FocusChangeObserver* observer) override; - virtual void RemoveObserver( - aura::client::FocusChangeObserver* observer) override; - virtual void FocusWindow(aura::Window* window) override; - virtual void ResetFocusWithinActiveWindow(aura::Window* window) override; - virtual aura::Window* GetFocusedWindow() override; - - // Overridden from ui::EventHandler: - virtual void OnKeyEvent(ui::KeyEvent* event) override; - virtual void OnMouseEvent(ui::MouseEvent* event) override; - virtual void OnScrollEvent(ui::ScrollEvent* event) override; - virtual void OnTouchEvent(ui::TouchEvent* event) override; - virtual void OnGestureEvent(ui::GestureEvent* event) override; - - // Overridden from aura::WindowObserver: - virtual void OnWindowVisibilityChanged(aura::Window* window, - bool visible) override; - virtual void OnWindowDestroying(aura::Window* window) override; - virtual void OnWindowHierarchyChanging( - const HierarchyChangeParams& params) override; - virtual void OnWindowHierarchyChanged( - const HierarchyChangeParams& params) override; - - // Internal implementation that sets the focused window, fires events etc. - // This function must be called with a valid focusable window. - void SetFocusedWindow(aura::Window* window); - - // Internal implementation that sets the active window, fires events etc. - // This function must be called with a valid |activatable_window|. - // |requested window| refers to the window that was passed in to an external - // request (e.g. FocusWindow or ActivateWindow). It may be NULL, e.g. if - // SetActiveWindow was not called by an external request. |activatable_window| - // refers to the actual window to be activated, which may be different. - void SetActiveWindow(aura::Window* requested_window, - aura::Window* activatable_window); - - // Called when a window's disposition changed such that it and its hierarchy - // are no longer focusable/activatable. |next| is a valid window that is used - // as a starting point for finding a window to focus next based on rules. - void WindowLostFocusFromDispositionChange(aura::Window* window, - aura::Window* next); - - // Called when an attempt is made to focus or activate a window via an input - // event targeted at that window. Rules determine the best focusable window - // for the input window. - void WindowFocusedFromInputEvent(aura::Window* window); - - aura::Window* active_window_; - aura::Window* focused_window_; - - bool updating_focus_; - bool updating_activation_; - - scoped_ptr<FocusRules> rules_; - - ObserverList<aura::client::ActivationChangeObserver> activation_observers_; - ObserverList<aura::client::FocusChangeObserver> focus_observers_; - - ScopedObserver<aura::Window, aura::WindowObserver> observer_manager_; - - DISALLOW_COPY_AND_ASSIGN(FocusController); -}; - -} // namespace wm - -#endif // UI_WM_CORE_FOCUS_CONTROLLER_H_
diff --git a/ui/wm/core/focus_controller_unittest.cc b/ui/wm/core/focus_controller_unittest.cc deleted file mode 100644 index 2508bcd..0000000 --- a/ui/wm/core/focus_controller_unittest.cc +++ /dev/null
@@ -1,1285 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/focus_controller.h" - -#include <map> - -#include "ui/aura/client/aura_constants.h" -#include "ui/aura/client/default_capture_client.h" -#include "ui/aura/client/focus_change_observer.h" -#include "ui/aura/test/aura_test_base.h" -#include "ui/aura/test/test_window_delegate.h" -#include "ui/aura/test/test_windows.h" -#include "ui/aura/window.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/aura/window_tracker.h" -#include "ui/base/ime/dummy_text_input_client.h" -#include "ui/base/ime/text_input_focus_manager.h" -#include "ui/events/event.h" -#include "ui/events/event_constants.h" -#include "ui/events/event_handler.h" -#include "ui/events/test/event_generator.h" -#include "ui/wm/core/base_focus_rules.h" -#include "ui/wm/core/wm_state.h" -#include "ui/wm/public/activation_change_observer.h" -#include "ui/wm/public/activation_client.h" - -namespace wm { - -class FocusNotificationObserver : public aura::client::ActivationChangeObserver, - public aura::client::FocusChangeObserver { - public: - FocusNotificationObserver() - : activation_changed_count_(0), - focus_changed_count_(0), - reactivation_count_(0), - reactivation_requested_window_(NULL), - reactivation_actual_window_(NULL) {} - virtual ~FocusNotificationObserver() {} - - void ExpectCounts(int activation_changed_count, int focus_changed_count) { - EXPECT_EQ(activation_changed_count, activation_changed_count_); - EXPECT_EQ(focus_changed_count, focus_changed_count_); - } - int reactivation_count() const { - return reactivation_count_; - } - aura::Window* reactivation_requested_window() const { - return reactivation_requested_window_; - } - aura::Window* reactivation_actual_window() const { - return reactivation_actual_window_; - } - - private: - // Overridden from aura::client::ActivationChangeObserver: - virtual void OnWindowActivated(aura::Window* gained_active, - aura::Window* lost_active) override { - ++activation_changed_count_; - } - virtual void OnAttemptToReactivateWindow( - aura::Window* request_active, - aura::Window* actual_active) override { - ++reactivation_count_; - reactivation_requested_window_ = request_active; - reactivation_actual_window_ = actual_active; - } - - // Overridden from aura::client::FocusChangeObserver: - virtual void OnWindowFocused(aura::Window* gained_focus, - aura::Window* lost_focus) override { - ++focus_changed_count_; - } - - int activation_changed_count_; - int focus_changed_count_; - int reactivation_count_; - aura::Window* reactivation_requested_window_; - aura::Window* reactivation_actual_window_; - - DISALLOW_COPY_AND_ASSIGN(FocusNotificationObserver); -}; - -class WindowDeleter { - public: - virtual aura::Window* GetDeletedWindow() = 0; - - protected: - virtual ~WindowDeleter() {} -}; - -// ActivationChangeObserver and FocusChangeObserver that keeps track of whether -// it was notified about activation changes or focus changes with a deleted -// window. -class RecordingActivationAndFocusChangeObserver - : public aura::client::ActivationChangeObserver, - public aura::client::FocusChangeObserver { - public: - RecordingActivationAndFocusChangeObserver(aura::Window* root, - WindowDeleter* deleter) - : root_(root), - deleter_(deleter), - was_notified_with_deleted_window_(false) { - aura::client::GetActivationClient(root_)->AddObserver(this); - aura::client::GetFocusClient(root_)->AddObserver(this); - } - virtual ~RecordingActivationAndFocusChangeObserver() { - aura::client::GetActivationClient(root_)->RemoveObserver(this); - aura::client::GetFocusClient(root_)->RemoveObserver(this); - } - - bool was_notified_with_deleted_window() const { - return was_notified_with_deleted_window_; - } - - // Overridden from aura::client::ActivationChangeObserver: - virtual void OnWindowActivated(aura::Window* gained_active, - aura::Window* lost_active) override { - if (lost_active && lost_active == deleter_->GetDeletedWindow()) - was_notified_with_deleted_window_ = true; - } - - // Overridden from aura::client::FocusChangeObserver: - virtual void OnWindowFocused(aura::Window* gained_focus, - aura::Window* lost_focus) override { - if (lost_focus && lost_focus == deleter_->GetDeletedWindow()) - was_notified_with_deleted_window_ = true; - } - - private: - aura::Window* root_; - - // Not owned. - WindowDeleter* deleter_; - - // Whether the observer was notified about the loss of activation or the - // loss of focus with a window already deleted by |deleter_| as the - // |lost_active| or |lost_focus| parameter. - bool was_notified_with_deleted_window_; - - DISALLOW_COPY_AND_ASSIGN(RecordingActivationAndFocusChangeObserver); -}; - -// ActivationChangeObserver that deletes the window losing activation. -class DeleteOnLoseActivationChangeObserver : - public aura::client::ActivationChangeObserver, - public WindowDeleter { - public: - explicit DeleteOnLoseActivationChangeObserver(aura::Window* window) - : root_(window->GetRootWindow()), - window_(window), - did_delete_(false) { - aura::client::GetActivationClient(root_)->AddObserver(this); - } - virtual ~DeleteOnLoseActivationChangeObserver() { - aura::client::GetActivationClient(root_)->RemoveObserver(this); - } - - // Overridden from aura::client::ActivationChangeObserver: - virtual void OnWindowActivated(aura::Window* gained_active, - aura::Window* lost_active) override { - if (window_ && lost_active == window_) { - delete lost_active; - did_delete_ = true; - } - } - - // Overridden from WindowDeleter: - virtual aura::Window* GetDeletedWindow() override { - return did_delete_ ? window_ : NULL; - } - - private: - aura::Window* root_; - aura::Window* window_; - bool did_delete_; - - DISALLOW_COPY_AND_ASSIGN(DeleteOnLoseActivationChangeObserver); -}; - -// FocusChangeObserver that deletes the window losing focus. -class DeleteOnLoseFocusChangeObserver - : public aura::client::FocusChangeObserver, - public WindowDeleter { - public: - explicit DeleteOnLoseFocusChangeObserver(aura::Window* window) - : root_(window->GetRootWindow()), - window_(window), - did_delete_(false) { - aura::client::GetFocusClient(root_)->AddObserver(this); - } - virtual ~DeleteOnLoseFocusChangeObserver() { - aura::client::GetFocusClient(root_)->RemoveObserver(this); - } - - // Overridden from aura::client::FocusChangeObserver: - virtual void OnWindowFocused(aura::Window* gained_focus, - aura::Window* lost_focus) override { - if (window_ && lost_focus == window_) { - delete lost_focus; - did_delete_ = true; - } - } - - // Overridden from WindowDeleter: - virtual aura::Window* GetDeletedWindow() override { - return did_delete_ ? window_ : NULL; - } - - private: - aura::Window* root_; - aura::Window* window_; - bool did_delete_; - - DISALLOW_COPY_AND_ASSIGN(DeleteOnLoseFocusChangeObserver); -}; - -class ScopedFocusNotificationObserver : public FocusNotificationObserver { - public: - ScopedFocusNotificationObserver(aura::Window* root_window) - : root_window_(root_window) { - aura::client::GetActivationClient(root_window_)->AddObserver(this); - aura::client::GetFocusClient(root_window_)->AddObserver(this); - } - virtual ~ScopedFocusNotificationObserver() { - aura::client::GetActivationClient(root_window_)->RemoveObserver(this); - aura::client::GetFocusClient(root_window_)->RemoveObserver(this); - } - - private: - aura::Window* root_window_; - - DISALLOW_COPY_AND_ASSIGN(ScopedFocusNotificationObserver); -}; - -class ScopedTargetFocusNotificationObserver : public FocusNotificationObserver { - public: - ScopedTargetFocusNotificationObserver(aura::Window* root_window, int id) - : target_(root_window->GetChildById(id)) { - aura::client::SetActivationChangeObserver(target_, this); - aura::client::SetFocusChangeObserver(target_, this); - tracker_.Add(target_); - } - virtual ~ScopedTargetFocusNotificationObserver() { - if (tracker_.Contains(target_)) { - aura::client::SetActivationChangeObserver(target_, NULL); - aura::client::SetFocusChangeObserver(target_, NULL); - } - } - - private: - aura::Window* target_; - aura::WindowTracker tracker_; - - DISALLOW_COPY_AND_ASSIGN(ScopedTargetFocusNotificationObserver); -}; - -class ScopedFocusedTextInputClientChanger - : public ScopedFocusNotificationObserver { - public: - ScopedFocusedTextInputClientChanger(aura::Window* root_window, - ui::TextInputClient* text_input_client) - : ScopedFocusNotificationObserver(root_window), - text_input_client_(text_input_client) {} - - private: - // Overridden from aura::client::FocusChangeObserver: - virtual void OnWindowFocused(aura::Window* gained_focus, - aura::Window* lost_focus) override { - ui::TextInputFocusManager::GetInstance()->FocusTextInputClient( - text_input_client_); - } - - ui::TextInputClient* text_input_client_; -}; - -// Used to fake the handling of events in the pre-target phase. -class SimpleEventHandler : public ui::EventHandler { - public: - SimpleEventHandler() {} - virtual ~SimpleEventHandler() {} - - // Overridden from ui::EventHandler: - virtual void OnMouseEvent(ui::MouseEvent* event) override { - event->SetHandled(); - } - virtual void OnGestureEvent(ui::GestureEvent* event) override { - event->SetHandled(); - } - - private: - DISALLOW_COPY_AND_ASSIGN(SimpleEventHandler); -}; - -class FocusShiftingActivationObserver - : public aura::client::ActivationChangeObserver { - public: - explicit FocusShiftingActivationObserver(aura::Window* activated_window) - : activated_window_(activated_window), - shift_focus_to_(NULL) {} - virtual ~FocusShiftingActivationObserver() {} - - void set_shift_focus_to(aura::Window* shift_focus_to) { - shift_focus_to_ = shift_focus_to; - } - - private: - // Overridden from aura::client::ActivationChangeObserver: - virtual void OnWindowActivated(aura::Window* gained_active, - aura::Window* lost_active) override { - // Shift focus to a child. This should prevent the default focusing from - // occurring in FocusController::FocusWindow(). - if (gained_active == activated_window_) { - aura::client::FocusClient* client = - aura::client::GetFocusClient(gained_active); - client->FocusWindow(shift_focus_to_); - } - } - - aura::Window* activated_window_; - aura::Window* shift_focus_to_; - - DISALLOW_COPY_AND_ASSIGN(FocusShiftingActivationObserver); -}; - -// BaseFocusRules subclass that allows basic overrides of focus/activation to -// be tested. This is intended more as a test that the override system works at -// all, rather than as an exhaustive set of use cases, those should be covered -// in tests for those FocusRules implementations. -class TestFocusRules : public BaseFocusRules { - public: - TestFocusRules() : focus_restriction_(NULL) {} - - // Restricts focus and activation to this window and its child hierarchy. - void set_focus_restriction(aura::Window* focus_restriction) { - focus_restriction_ = focus_restriction; - } - - // Overridden from BaseFocusRules: - virtual bool SupportsChildActivation(aura::Window* window) const override { - // In FocusControllerTests, only the RootWindow has activatable children. - return window->GetRootWindow() == window; - } - virtual bool CanActivateWindow(aura::Window* window) const override { - // Restricting focus to a non-activatable child window means the activatable - // parent outside the focus restriction is activatable. - bool can_activate = - CanFocusOrActivate(window) || window->Contains(focus_restriction_); - return can_activate ? BaseFocusRules::CanActivateWindow(window) : false; - } - virtual bool CanFocusWindow(aura::Window* window) const override { - return CanFocusOrActivate(window) ? - BaseFocusRules::CanFocusWindow(window) : false; - } - virtual aura::Window* GetActivatableWindow( - aura::Window* window) const override { - return BaseFocusRules::GetActivatableWindow( - CanFocusOrActivate(window) ? window : focus_restriction_); - } - virtual aura::Window* GetFocusableWindow( - aura::Window* window) const override { - return BaseFocusRules::GetFocusableWindow( - CanFocusOrActivate(window) ? window : focus_restriction_); - } - virtual aura::Window* GetNextActivatableWindow( - aura::Window* ignore) const override { - aura::Window* next_activatable = - BaseFocusRules::GetNextActivatableWindow(ignore); - return CanFocusOrActivate(next_activatable) ? - next_activatable : GetActivatableWindow(focus_restriction_); - } - - private: - bool CanFocusOrActivate(aura::Window* window) const { - return !focus_restriction_ || focus_restriction_->Contains(window); - } - - aura::Window* focus_restriction_; - - DISALLOW_COPY_AND_ASSIGN(TestFocusRules); -}; - -// Common infrastructure shared by all FocusController test types. -class FocusControllerTestBase : public aura::test::AuraTestBase { - protected: - FocusControllerTestBase() {} - - // Overridden from aura::test::AuraTestBase: - virtual void SetUp() override { - wm_state_.reset(new wm::WMState); - // FocusController registers itself as an Env observer so it can catch all - // window initializations, including the root_window()'s, so we create it - // before allowing the base setup. - test_focus_rules_ = new TestFocusRules; - focus_controller_.reset(new FocusController(test_focus_rules_)); - aura::test::AuraTestBase::SetUp(); - root_window()->AddPreTargetHandler(focus_controller_.get()); - aura::client::SetFocusClient(root_window(), focus_controller_.get()); - aura::client::SetActivationClient(root_window(), focus_controller_.get()); - - // Hierarchy used by all tests: - // root_window - // +-- w1 - // | +-- w11 - // | +-- w12 - // +-- w2 - // | +-- w21 - // | +-- w211 - // +-- w3 - aura::Window* w1 = aura::test::CreateTestWindowWithDelegate( - aura::test::TestWindowDelegate::CreateSelfDestroyingDelegate(), 1, - gfx::Rect(0, 0, 50, 50), root_window()); - aura::test::CreateTestWindowWithDelegate( - aura::test::TestWindowDelegate::CreateSelfDestroyingDelegate(), 11, - gfx::Rect(5, 5, 10, 10), w1); - aura::test::CreateTestWindowWithDelegate( - aura::test::TestWindowDelegate::CreateSelfDestroyingDelegate(), 12, - gfx::Rect(15, 15, 10, 10), w1); - aura::Window* w2 = aura::test::CreateTestWindowWithDelegate( - aura::test::TestWindowDelegate::CreateSelfDestroyingDelegate(), 2, - gfx::Rect(75, 75, 50, 50), root_window()); - aura::Window* w21 = aura::test::CreateTestWindowWithDelegate( - aura::test::TestWindowDelegate::CreateSelfDestroyingDelegate(), 21, - gfx::Rect(5, 5, 10, 10), w2); - aura::test::CreateTestWindowWithDelegate( - aura::test::TestWindowDelegate::CreateSelfDestroyingDelegate(), 211, - gfx::Rect(1, 1, 5, 5), w21); - aura::test::CreateTestWindowWithDelegate( - aura::test::TestWindowDelegate::CreateSelfDestroyingDelegate(), 3, - gfx::Rect(125, 125, 50, 50), root_window()); - } - virtual void TearDown() override { - root_window()->RemovePreTargetHandler(focus_controller_.get()); - aura::test::AuraTestBase::TearDown(); - test_focus_rules_ = NULL; // Owned by FocusController. - focus_controller_.reset(); - wm_state_.reset(); - } - - void FocusWindow(aura::Window* window) { - aura::client::GetFocusClient(root_window())->FocusWindow(window); - } - aura::Window* GetFocusedWindow() { - return aura::client::GetFocusClient(root_window())->GetFocusedWindow(); - } - int GetFocusedWindowId() { - aura::Window* focused_window = GetFocusedWindow(); - return focused_window ? focused_window->id() : -1; - } - void ActivateWindow(aura::Window* window) { - aura::client::GetActivationClient(root_window())->ActivateWindow(window); - } - void DeactivateWindow(aura::Window* window) { - aura::client::GetActivationClient(root_window())->DeactivateWindow(window); - } - aura::Window* GetActiveWindow() { - return aura::client::GetActivationClient(root_window())->GetActiveWindow(); - } - int GetActiveWindowId() { - aura::Window* active_window = GetActiveWindow(); - return active_window ? active_window->id() : -1; - } - - TestFocusRules* test_focus_rules() { return test_focus_rules_; } - - // Test functions. - virtual void BasicFocus() = 0; - virtual void BasicActivation() = 0; - virtual void FocusEvents() = 0; - virtual void DuplicateFocusEvents() {} - virtual void ActivationEvents() = 0; - virtual void ReactivationEvents() {} - virtual void DuplicateActivationEvents() {} - virtual void ShiftFocusWithinActiveWindow() {} - virtual void ShiftFocusToChildOfInactiveWindow() {} - virtual void ShiftFocusToParentOfFocusedWindow() {} - virtual void FocusRulesOverride() = 0; - virtual void ActivationRulesOverride() = 0; - virtual void ShiftFocusOnActivation() {} - virtual void ShiftFocusOnActivationDueToHide() {} - virtual void NoShiftActiveOnActivation() {} - virtual void NoFocusChangeOnClickOnCaptureWindow() {} - virtual void ChangeFocusWhenNothingFocusedAndCaptured() {} - virtual void DontPassDeletedWindow() {} - virtual void FocusedTextInputClient() {} - - private: - scoped_ptr<FocusController> focus_controller_; - TestFocusRules* test_focus_rules_; - scoped_ptr<wm::WMState> wm_state_; - - DISALLOW_COPY_AND_ASSIGN(FocusControllerTestBase); -}; - -// Test base for tests where focus is directly set to a target window. -class FocusControllerDirectTestBase : public FocusControllerTestBase { - protected: - FocusControllerDirectTestBase() {} - - // Different test types shift focus in different ways. - virtual void FocusWindowDirect(aura::Window* window) = 0; - virtual void ActivateWindowDirect(aura::Window* window) = 0; - virtual void DeactivateWindowDirect(aura::Window* window) = 0; - - // Input events do not change focus if the window can not be focused. - virtual bool IsInputEvent() = 0; - - void FocusWindowById(int id) { - aura::Window* window = root_window()->GetChildById(id); - DCHECK(window); - FocusWindowDirect(window); - } - void ActivateWindowById(int id) { - aura::Window* window = root_window()->GetChildById(id); - DCHECK(window); - ActivateWindowDirect(window); - } - - // Overridden from FocusControllerTestBase: - virtual void BasicFocus() override { - EXPECT_EQ(NULL, GetFocusedWindow()); - FocusWindowById(1); - EXPECT_EQ(1, GetFocusedWindowId()); - FocusWindowById(2); - EXPECT_EQ(2, GetFocusedWindowId()); - } - virtual void BasicActivation() override { - EXPECT_EQ(NULL, GetActiveWindow()); - ActivateWindowById(1); - EXPECT_EQ(1, GetActiveWindowId()); - ActivateWindowById(2); - EXPECT_EQ(2, GetActiveWindowId()); - // Verify that attempting to deactivate NULL does not crash and does not - // change activation. - DeactivateWindow(NULL); - EXPECT_EQ(2, GetActiveWindowId()); - DeactivateWindow(GetActiveWindow()); - EXPECT_EQ(1, GetActiveWindowId()); - } - virtual void FocusEvents() override { - ScopedFocusNotificationObserver root_observer(root_window()); - ScopedTargetFocusNotificationObserver observer1(root_window(), 1); - ScopedTargetFocusNotificationObserver observer2(root_window(), 2); - - root_observer.ExpectCounts(0, 0); - observer1.ExpectCounts(0, 0); - observer2.ExpectCounts(0, 0); - - FocusWindowById(1); - root_observer.ExpectCounts(1, 1); - observer1.ExpectCounts(1, 1); - observer2.ExpectCounts(0, 0); - - FocusWindowById(2); - root_observer.ExpectCounts(2, 2); - observer1.ExpectCounts(2, 2); - observer2.ExpectCounts(1, 1); - } - virtual void DuplicateFocusEvents() override { - // Focusing an existing focused window should not resend focus events. - ScopedFocusNotificationObserver root_observer(root_window()); - ScopedTargetFocusNotificationObserver observer1(root_window(), 1); - - root_observer.ExpectCounts(0, 0); - observer1.ExpectCounts(0, 0); - - FocusWindowById(1); - root_observer.ExpectCounts(1, 1); - observer1.ExpectCounts(1, 1); - - FocusWindowById(1); - root_observer.ExpectCounts(1, 1); - observer1.ExpectCounts(1, 1); - } - virtual void ActivationEvents() override { - ActivateWindowById(1); - - ScopedFocusNotificationObserver root_observer(root_window()); - ScopedTargetFocusNotificationObserver observer1(root_window(), 1); - ScopedTargetFocusNotificationObserver observer2(root_window(), 2); - - root_observer.ExpectCounts(0, 0); - observer1.ExpectCounts(0, 0); - observer2.ExpectCounts(0, 0); - - ActivateWindowById(2); - root_observer.ExpectCounts(1, 1); - observer1.ExpectCounts(1, 1); - observer2.ExpectCounts(1, 1); - } - virtual void ReactivationEvents() override { - ActivateWindowById(1); - ScopedFocusNotificationObserver root_observer(root_window()); - EXPECT_EQ(0, root_observer.reactivation_count()); - root_window()->GetChildById(2)->Hide(); - // When we attempt to activate "2", which cannot be activated because it - // is not visible, "1" will be reactivated. - ActivateWindowById(2); - EXPECT_EQ(1, root_observer.reactivation_count()); - EXPECT_EQ(root_window()->GetChildById(2), - root_observer.reactivation_requested_window()); - EXPECT_EQ(root_window()->GetChildById(1), - root_observer.reactivation_actual_window()); - } - virtual void DuplicateActivationEvents() override { - // Activating an existing active window should not resend activation events. - ActivateWindowById(1); - - ScopedFocusNotificationObserver root_observer(root_window()); - ScopedTargetFocusNotificationObserver observer1(root_window(), 1); - ScopedTargetFocusNotificationObserver observer2(root_window(), 2); - - root_observer.ExpectCounts(0, 0); - observer1.ExpectCounts(0, 0); - observer2.ExpectCounts(0, 0); - - ActivateWindowById(2); - root_observer.ExpectCounts(1, 1); - observer1.ExpectCounts(1, 1); - observer2.ExpectCounts(1, 1); - - ActivateWindowById(2); - root_observer.ExpectCounts(1, 1); - observer1.ExpectCounts(1, 1); - observer2.ExpectCounts(1, 1); - } - virtual void ShiftFocusWithinActiveWindow() override { - ActivateWindowById(1); - EXPECT_EQ(1, GetActiveWindowId()); - EXPECT_EQ(1, GetFocusedWindowId()); - FocusWindowById(11); - EXPECT_EQ(11, GetFocusedWindowId()); - FocusWindowById(12); - EXPECT_EQ(12, GetFocusedWindowId()); - } - virtual void ShiftFocusToChildOfInactiveWindow() override { - ActivateWindowById(2); - EXPECT_EQ(2, GetActiveWindowId()); - EXPECT_EQ(2, GetFocusedWindowId()); - FocusWindowById(11); - EXPECT_EQ(1, GetActiveWindowId()); - EXPECT_EQ(11, GetFocusedWindowId()); - } - virtual void ShiftFocusToParentOfFocusedWindow() override { - ActivateWindowById(1); - EXPECT_EQ(1, GetFocusedWindowId()); - FocusWindowById(11); - EXPECT_EQ(11, GetFocusedWindowId()); - FocusWindowById(1); - // Focus should _not_ shift to the parent of the already-focused window. - EXPECT_EQ(11, GetFocusedWindowId()); - } - virtual void FocusRulesOverride() override { - EXPECT_EQ(NULL, GetFocusedWindow()); - FocusWindowById(11); - EXPECT_EQ(11, GetFocusedWindowId()); - - test_focus_rules()->set_focus_restriction(root_window()->GetChildById(211)); - FocusWindowById(12); - // Input events leave focus unchanged; direct API calls will change focus - // to the restricted window. - int focused_window = IsInputEvent() ? 11 : 211; - EXPECT_EQ(focused_window, GetFocusedWindowId()); - - test_focus_rules()->set_focus_restriction(NULL); - FocusWindowById(12); - EXPECT_EQ(12, GetFocusedWindowId()); - } - virtual void ActivationRulesOverride() override { - ActivateWindowById(1); - EXPECT_EQ(1, GetActiveWindowId()); - EXPECT_EQ(1, GetFocusedWindowId()); - - aura::Window* w3 = root_window()->GetChildById(3); - test_focus_rules()->set_focus_restriction(w3); - - ActivateWindowById(2); - // Input events leave activation unchanged; direct API calls will activate - // the restricted window. - int active_window = IsInputEvent() ? 1 : 3; - EXPECT_EQ(active_window, GetActiveWindowId()); - EXPECT_EQ(active_window, GetFocusedWindowId()); - - test_focus_rules()->set_focus_restriction(NULL); - ActivateWindowById(2); - EXPECT_EQ(2, GetActiveWindowId()); - EXPECT_EQ(2, GetFocusedWindowId()); - } - virtual void ShiftFocusOnActivation() override { - // When a window is activated, by default that window is also focused. - // An ActivationChangeObserver may shift focus to another window within the - // same activatable window. - ActivateWindowById(2); - EXPECT_EQ(2, GetFocusedWindowId()); - ActivateWindowById(1); - EXPECT_EQ(1, GetFocusedWindowId()); - - ActivateWindowById(2); - - aura::Window* target = root_window()->GetChildById(1); - aura::client::ActivationClient* client = - aura::client::GetActivationClient(root_window()); - - scoped_ptr<FocusShiftingActivationObserver> observer( - new FocusShiftingActivationObserver(target)); - observer->set_shift_focus_to(target->GetChildById(11)); - client->AddObserver(observer.get()); - - ActivateWindowById(1); - - // w1's ActivationChangeObserver shifted focus to this child, pre-empting - // FocusController's default setting. - EXPECT_EQ(11, GetFocusedWindowId()); - - ActivateWindowById(2); - EXPECT_EQ(2, GetFocusedWindowId()); - - // Simulate a focus reset by the ActivationChangeObserver. This should - // trigger the default setting in FocusController. - observer->set_shift_focus_to(NULL); - ActivateWindowById(1); - EXPECT_EQ(1, GetFocusedWindowId()); - - client->RemoveObserver(observer.get()); - - ActivateWindowById(2); - EXPECT_EQ(2, GetFocusedWindowId()); - ActivateWindowById(1); - EXPECT_EQ(1, GetFocusedWindowId()); - } - virtual void ShiftFocusOnActivationDueToHide() override { - // Similar to ShiftFocusOnActivation except the activation change is - // triggered by hiding the active window. - ActivateWindowById(1); - EXPECT_EQ(1, GetFocusedWindowId()); - - // Removes window 3 as candidate for next activatable window. - root_window()->GetChildById(3)->Hide(); - EXPECT_EQ(1, GetFocusedWindowId()); - - aura::Window* target = root_window()->GetChildById(2); - aura::client::ActivationClient* client = - aura::client::GetActivationClient(root_window()); - - scoped_ptr<FocusShiftingActivationObserver> observer( - new FocusShiftingActivationObserver(target)); - observer->set_shift_focus_to(target->GetChildById(21)); - client->AddObserver(observer.get()); - - // Hide the active window. - root_window()->GetChildById(1)->Hide(); - - EXPECT_EQ(21, GetFocusedWindowId()); - - client->RemoveObserver(observer.get()); - } - virtual void NoShiftActiveOnActivation() override { - // When a window is activated, we need to prevent any change to activation - // from being made in response to an activation change notification. - } - - virtual void NoFocusChangeOnClickOnCaptureWindow() override { - scoped_ptr<aura::client::DefaultCaptureClient> capture_client( - new aura::client::DefaultCaptureClient(root_window())); - // Clicking on a window which has capture should not cause a focus change - // to the window. This test verifies whether that is indeed the case. - ActivateWindowById(1); - - EXPECT_EQ(1, GetActiveWindowId()); - EXPECT_EQ(1, GetFocusedWindowId()); - - aura::Window* w2 = root_window()->GetChildById(2); - aura::client::GetCaptureClient(root_window())->SetCapture(w2); - ui::test::EventGenerator generator(root_window(), w2); - generator.ClickLeftButton(); - - EXPECT_EQ(1, GetActiveWindowId()); - EXPECT_EQ(1, GetFocusedWindowId()); - aura::client::GetCaptureClient(root_window())->ReleaseCapture(w2); - } - - // Verifies focus change is honored while capture held. - virtual void ChangeFocusWhenNothingFocusedAndCaptured() override { - scoped_ptr<aura::client::DefaultCaptureClient> capture_client( - new aura::client::DefaultCaptureClient(root_window())); - aura::Window* w1 = root_window()->GetChildById(1); - aura::client::GetCaptureClient(root_window())->SetCapture(w1); - - EXPECT_EQ(-1, GetActiveWindowId()); - EXPECT_EQ(-1, GetFocusedWindowId()); - - FocusWindowById(1); - - EXPECT_EQ(1, GetActiveWindowId()); - EXPECT_EQ(1, GetFocusedWindowId()); - - aura::client::GetCaptureClient(root_window())->ReleaseCapture(w1); - } - - // Verifies if a window that loses activation or focus is deleted during - // observer notification we don't pass the deleted window to other observers. - virtual void DontPassDeletedWindow() override { - FocusWindowById(1); - - EXPECT_EQ(1, GetActiveWindowId()); - EXPECT_EQ(1, GetFocusedWindowId()); - - { - aura::Window* to_delete = root_window()->GetChildById(1); - DeleteOnLoseActivationChangeObserver observer1(to_delete); - RecordingActivationAndFocusChangeObserver observer2(root_window(), - &observer1); - - FocusWindowById(2); - - EXPECT_EQ(2, GetActiveWindowId()); - EXPECT_EQ(2, GetFocusedWindowId()); - - EXPECT_EQ(to_delete, observer1.GetDeletedWindow()); - EXPECT_FALSE(observer2.was_notified_with_deleted_window()); - } - - { - aura::Window* to_delete = root_window()->GetChildById(2); - DeleteOnLoseFocusChangeObserver observer1(to_delete); - RecordingActivationAndFocusChangeObserver observer2(root_window(), - &observer1); - - FocusWindowById(3); - - EXPECT_EQ(3, GetActiveWindowId()); - EXPECT_EQ(3, GetFocusedWindowId()); - - EXPECT_EQ(to_delete, observer1.GetDeletedWindow()); - EXPECT_FALSE(observer2.was_notified_with_deleted_window()); - } - } - - // Verifies if the focused text input client is cleared when a window gains - // or loses the focus. - virtual void FocusedTextInputClient() override { - ui::TextInputFocusManager* text_input_focus_manager = - ui::TextInputFocusManager::GetInstance(); - ui::DummyTextInputClient text_input_client; - ui::TextInputClient* null_text_input_client = NULL; - - EXPECT_EQ(null_text_input_client, - text_input_focus_manager->GetFocusedTextInputClient()); - - text_input_focus_manager->FocusTextInputClient(&text_input_client); - EXPECT_EQ(&text_input_client, - text_input_focus_manager->GetFocusedTextInputClient()); - FocusWindowById(1); - // The focused text input client gets cleared when a window gets focused - // unless any of observers sets the focused text input client. - EXPECT_EQ(null_text_input_client, - text_input_focus_manager->GetFocusedTextInputClient()); - - ScopedFocusedTextInputClientChanger text_input_focus_changer( - root_window(), &text_input_client); - EXPECT_EQ(null_text_input_client, - text_input_focus_manager->GetFocusedTextInputClient()); - FocusWindowById(2); - // |text_input_focus_changer| sets the focused text input client. - EXPECT_EQ(&text_input_client, - text_input_focus_manager->GetFocusedTextInputClient()); - - FocusWindow(NULL); - // The focused text input client gets cleared when a window loses the focus. - EXPECT_EQ(null_text_input_client, - text_input_focus_manager->GetFocusedTextInputClient()); - } - - private: - DISALLOW_COPY_AND_ASSIGN(FocusControllerDirectTestBase); -}; - -// Focus and Activation changes via aura::client::ActivationClient API. -class FocusControllerApiTest : public FocusControllerDirectTestBase { - public: - FocusControllerApiTest() {} - - private: - // Overridden from FocusControllerTestBase: - virtual void FocusWindowDirect(aura::Window* window) override { - FocusWindow(window); - } - virtual void ActivateWindowDirect(aura::Window* window) override { - ActivateWindow(window); - } - virtual void DeactivateWindowDirect(aura::Window* window) override { - DeactivateWindow(window); - } - virtual bool IsInputEvent() override { return false; } - - DISALLOW_COPY_AND_ASSIGN(FocusControllerApiTest); -}; - -// Focus and Activation changes via input events. -class FocusControllerMouseEventTest : public FocusControllerDirectTestBase { - public: - FocusControllerMouseEventTest() {} - - // Tests that a handled mouse or gesture event does not trigger a window - // activation. - void IgnoreHandledEvent() { - EXPECT_EQ(NULL, GetActiveWindow()); - aura::Window* w1 = root_window()->GetChildById(1); - SimpleEventHandler handler; - root_window()->PrependPreTargetHandler(&handler); - ui::test::EventGenerator generator(root_window(), w1); - generator.ClickLeftButton(); - EXPECT_EQ(NULL, GetActiveWindow()); - generator.GestureTapAt(w1->bounds().CenterPoint()); - EXPECT_EQ(NULL, GetActiveWindow()); - root_window()->RemovePreTargetHandler(&handler); - generator.ClickLeftButton(); - EXPECT_EQ(1, GetActiveWindowId()); - } - - private: - // Overridden from FocusControllerTestBase: - virtual void FocusWindowDirect(aura::Window* window) override { - ui::test::EventGenerator generator(root_window(), window); - generator.ClickLeftButton(); - } - virtual void ActivateWindowDirect(aura::Window* window) override { - ui::test::EventGenerator generator(root_window(), window); - generator.ClickLeftButton(); - } - virtual void DeactivateWindowDirect(aura::Window* window) override { - aura::Window* next_activatable = - test_focus_rules()->GetNextActivatableWindow(window); - ui::test::EventGenerator generator(root_window(), next_activatable); - generator.ClickLeftButton(); - } - virtual bool IsInputEvent() override { return true; } - - DISALLOW_COPY_AND_ASSIGN(FocusControllerMouseEventTest); -}; - -class FocusControllerGestureEventTest : public FocusControllerDirectTestBase { - public: - FocusControllerGestureEventTest() {} - - private: - // Overridden from FocusControllerTestBase: - virtual void FocusWindowDirect(aura::Window* window) override { - ui::test::EventGenerator generator(root_window(), window); - generator.GestureTapAt(window->bounds().CenterPoint()); - } - virtual void ActivateWindowDirect(aura::Window* window) override { - ui::test::EventGenerator generator(root_window(), window); - generator.GestureTapAt(window->bounds().CenterPoint()); - } - virtual void DeactivateWindowDirect(aura::Window* window) override { - aura::Window* next_activatable = - test_focus_rules()->GetNextActivatableWindow(window); - ui::test::EventGenerator generator(root_window(), next_activatable); - generator.GestureTapAt(window->bounds().CenterPoint()); - } - virtual bool IsInputEvent() override { return true; } - - DISALLOW_COPY_AND_ASSIGN(FocusControllerGestureEventTest); -}; - -// Test base for tests where focus is implicitly set to a window as the result -// of a disposition change to the focused window or the hierarchy that contains -// it. -class FocusControllerImplicitTestBase : public FocusControllerTestBase { - protected: - explicit FocusControllerImplicitTestBase(bool parent) : parent_(parent) {} - - aura::Window* GetDispositionWindow(aura::Window* window) { - return parent_ ? window->parent() : window; - } - - // Change the disposition of |window| in such a way as it will lose focus. - virtual void ChangeWindowDisposition(aura::Window* window) = 0; - - // Allow each disposition change test to add additional post-disposition - // change expectations. - virtual void PostDispostionChangeExpectations() {} - - // Overridden from FocusControllerTestBase: - virtual void BasicFocus() override { - EXPECT_EQ(NULL, GetFocusedWindow()); - - aura::Window* w211 = root_window()->GetChildById(211); - FocusWindow(w211); - EXPECT_EQ(211, GetFocusedWindowId()); - - ChangeWindowDisposition(w211); - // BasicFocusRules passes focus to the parent. - EXPECT_EQ(parent_ ? 2 : 21, GetFocusedWindowId()); - } - virtual void BasicActivation() override { - DCHECK(!parent_) << "Activation tests don't support parent changes."; - - EXPECT_EQ(NULL, GetActiveWindow()); - - aura::Window* w2 = root_window()->GetChildById(2); - ActivateWindow(w2); - EXPECT_EQ(2, GetActiveWindowId()); - - ChangeWindowDisposition(w2); - EXPECT_EQ(3, GetActiveWindowId()); - PostDispostionChangeExpectations(); - } - virtual void FocusEvents() override { - aura::Window* w211 = root_window()->GetChildById(211); - FocusWindow(w211); - - ScopedFocusNotificationObserver root_observer(root_window()); - ScopedTargetFocusNotificationObserver observer211(root_window(), 211); - root_observer.ExpectCounts(0, 0); - observer211.ExpectCounts(0, 0); - - ChangeWindowDisposition(w211); - root_observer.ExpectCounts(0, 1); - observer211.ExpectCounts(0, 1); - } - virtual void ActivationEvents() override { - DCHECK(!parent_) << "Activation tests don't support parent changes."; - - aura::Window* w2 = root_window()->GetChildById(2); - ActivateWindow(w2); - - ScopedFocusNotificationObserver root_observer(root_window()); - ScopedTargetFocusNotificationObserver observer2(root_window(), 2); - ScopedTargetFocusNotificationObserver observer3(root_window(), 3); - root_observer.ExpectCounts(0, 0); - observer2.ExpectCounts(0, 0); - observer3.ExpectCounts(0, 0); - - ChangeWindowDisposition(w2); - root_observer.ExpectCounts(1, 1); - observer2.ExpectCounts(1, 1); - observer3.ExpectCounts(1, 1); - } - virtual void FocusRulesOverride() override { - EXPECT_EQ(NULL, GetFocusedWindow()); - aura::Window* w211 = root_window()->GetChildById(211); - FocusWindow(w211); - EXPECT_EQ(211, GetFocusedWindowId()); - - test_focus_rules()->set_focus_restriction(root_window()->GetChildById(11)); - ChangeWindowDisposition(w211); - // Normally, focus would shift to the parent (w21) but the override shifts - // it to 11. - EXPECT_EQ(11, GetFocusedWindowId()); - - test_focus_rules()->set_focus_restriction(NULL); - } - virtual void ActivationRulesOverride() override { - DCHECK(!parent_) << "Activation tests don't support parent changes."; - - aura::Window* w1 = root_window()->GetChildById(1); - ActivateWindow(w1); - - EXPECT_EQ(1, GetActiveWindowId()); - EXPECT_EQ(1, GetFocusedWindowId()); - - aura::Window* w3 = root_window()->GetChildById(3); - test_focus_rules()->set_focus_restriction(w3); - - // Normally, activation/focus would move to w2, but since we have a focus - // restriction, it should move to w3 instead. - ChangeWindowDisposition(w1); - EXPECT_EQ(3, GetActiveWindowId()); - EXPECT_EQ(3, GetFocusedWindowId()); - - test_focus_rules()->set_focus_restriction(NULL); - ActivateWindow(root_window()->GetChildById(2)); - EXPECT_EQ(2, GetActiveWindowId()); - EXPECT_EQ(2, GetFocusedWindowId()); - } - - private: - // When true, the disposition change occurs to the parent of the window - // instead of to the window. This verifies that changes occurring in the - // hierarchy that contains the window affect the window's focus. - bool parent_; - - DISALLOW_COPY_AND_ASSIGN(FocusControllerImplicitTestBase); -}; - -// Focus and Activation changes in response to window visibility changes. -class FocusControllerHideTest : public FocusControllerImplicitTestBase { - public: - FocusControllerHideTest() : FocusControllerImplicitTestBase(false) {} - - protected: - FocusControllerHideTest(bool parent) - : FocusControllerImplicitTestBase(parent) {} - - // Overridden from FocusControllerImplicitTestBase: - virtual void ChangeWindowDisposition(aura::Window* window) override { - GetDispositionWindow(window)->Hide(); - } - - private: - DISALLOW_COPY_AND_ASSIGN(FocusControllerHideTest); -}; - -// Focus and Activation changes in response to window parent visibility -// changes. -class FocusControllerParentHideTest : public FocusControllerHideTest { - public: - FocusControllerParentHideTest() : FocusControllerHideTest(true) {} - - private: - DISALLOW_COPY_AND_ASSIGN(FocusControllerParentHideTest); -}; - -// Focus and Activation changes in response to window destruction. -class FocusControllerDestructionTest : public FocusControllerImplicitTestBase { - public: - FocusControllerDestructionTest() : FocusControllerImplicitTestBase(false) {} - - protected: - FocusControllerDestructionTest(bool parent) - : FocusControllerImplicitTestBase(parent) {} - - // Overridden from FocusControllerImplicitTestBase: - virtual void ChangeWindowDisposition(aura::Window* window) override { - delete GetDispositionWindow(window); - } - - private: - DISALLOW_COPY_AND_ASSIGN(FocusControllerDestructionTest); -}; - -// Focus and Activation changes in response to window parent destruction. -class FocusControllerParentDestructionTest - : public FocusControllerDestructionTest { - public: - FocusControllerParentDestructionTest() - : FocusControllerDestructionTest(true) {} - - private: - DISALLOW_COPY_AND_ASSIGN(FocusControllerParentDestructionTest); -}; - -// Focus and Activation changes in response to window removal. -class FocusControllerRemovalTest : public FocusControllerImplicitTestBase { - public: - FocusControllerRemovalTest() : FocusControllerImplicitTestBase(false) {} - - protected: - FocusControllerRemovalTest(bool parent) - : FocusControllerImplicitTestBase(parent) {} - - // Overridden from FocusControllerImplicitTestBase: - virtual void ChangeWindowDisposition(aura::Window* window) override { - aura::Window* disposition_window = GetDispositionWindow(window); - disposition_window->parent()->RemoveChild(disposition_window); - window_owner_.reset(disposition_window); - } - virtual void TearDown() override { - window_owner_.reset(); - FocusControllerImplicitTestBase::TearDown(); - } - - private: - scoped_ptr<aura::Window> window_owner_; - - DISALLOW_COPY_AND_ASSIGN(FocusControllerRemovalTest); -}; - -// Focus and Activation changes in response to window parent removal. -class FocusControllerParentRemovalTest : public FocusControllerRemovalTest { - public: - FocusControllerParentRemovalTest() : FocusControllerRemovalTest(true) {} - - private: - DISALLOW_COPY_AND_ASSIGN(FocusControllerParentRemovalTest); -}; - - -#define FOCUS_CONTROLLER_TEST(TESTCLASS, TESTNAME) \ - TEST_F(TESTCLASS, TESTNAME) { TESTNAME(); } - -// Runs direct focus change tests (input events and API calls). -#define DIRECT_FOCUS_CHANGE_TESTS(TESTNAME) \ - FOCUS_CONTROLLER_TEST(FocusControllerApiTest, TESTNAME) \ - FOCUS_CONTROLLER_TEST(FocusControllerMouseEventTest, TESTNAME) \ - FOCUS_CONTROLLER_TEST(FocusControllerGestureEventTest, TESTNAME) - -// Runs implicit focus change tests for disposition changes to target. -#define IMPLICIT_FOCUS_CHANGE_TARGET_TESTS(TESTNAME) \ - FOCUS_CONTROLLER_TEST(FocusControllerHideTest, TESTNAME) \ - FOCUS_CONTROLLER_TEST(FocusControllerDestructionTest, TESTNAME) \ - FOCUS_CONTROLLER_TEST(FocusControllerRemovalTest, TESTNAME) - -// Runs implicit focus change tests for disposition changes to target's parent -// hierarchy. -#define IMPLICIT_FOCUS_CHANGE_PARENT_TESTS(TESTNAME) \ - /* TODO(beng): parent destruction tests are not supported at - present due to workspace manager issues. \ - FOCUS_CONTROLLER_TEST(FocusControllerParentDestructionTest, TESTNAME) */ \ - FOCUS_CONTROLLER_TEST(FocusControllerParentHideTest, TESTNAME) \ - FOCUS_CONTROLLER_TEST(FocusControllerParentRemovalTest, TESTNAME) - -// Runs all implicit focus change tests (changes to the target and target's -// parent hierarchy) -#define IMPLICIT_FOCUS_CHANGE_TESTS(TESTNAME) \ - IMPLICIT_FOCUS_CHANGE_TARGET_TESTS(TESTNAME) \ - IMPLICIT_FOCUS_CHANGE_PARENT_TESTS(TESTNAME) - -// Runs all possible focus change tests. -#define ALL_FOCUS_TESTS(TESTNAME) \ - DIRECT_FOCUS_CHANGE_TESTS(TESTNAME) \ - IMPLICIT_FOCUS_CHANGE_TESTS(TESTNAME) - -// Runs focus change tests that apply only to the target. For example, -// implicit activation changes caused by window disposition changes do not -// occur when changes to the containing hierarchy happen. -#define TARGET_FOCUS_TESTS(TESTNAME) \ - DIRECT_FOCUS_CHANGE_TESTS(TESTNAME) \ - IMPLICIT_FOCUS_CHANGE_TARGET_TESTS(TESTNAME) - -// - Focuses a window, verifies that focus changed. -ALL_FOCUS_TESTS(BasicFocus); - -// - Activates a window, verifies that activation changed. -TARGET_FOCUS_TESTS(BasicActivation); - -// - Focuses a window, verifies that focus events were dispatched. -ALL_FOCUS_TESTS(FocusEvents); - -// - Focuses or activates a window multiple times, verifies that events are only -// dispatched when focus/activation actually changes. -DIRECT_FOCUS_CHANGE_TESTS(DuplicateFocusEvents); -DIRECT_FOCUS_CHANGE_TESTS(DuplicateActivationEvents); - -// - Activates a window, verifies that activation events were dispatched. -TARGET_FOCUS_TESTS(ActivationEvents); - -// - Attempts to active a hidden window, verifies that current window is -// attempted to be reactivated and the appropriate event dispatched. -FOCUS_CONTROLLER_TEST(FocusControllerApiTest, ReactivationEvents); - -// - Input events/API calls shift focus between focusable windows within the -// active window. -DIRECT_FOCUS_CHANGE_TESTS(ShiftFocusWithinActiveWindow); - -// - Input events/API calls to a child window of an inactive window shifts -// activation to the activatable parent and focuses the child. -DIRECT_FOCUS_CHANGE_TESTS(ShiftFocusToChildOfInactiveWindow); - -// - Input events/API calls to focus the parent of the focused window do not -// shift focus away from the child. -DIRECT_FOCUS_CHANGE_TESTS(ShiftFocusToParentOfFocusedWindow); - -// - Verifies that FocusRules determine what can be focused. -ALL_FOCUS_TESTS(FocusRulesOverride); - -// - Verifies that FocusRules determine what can be activated. -TARGET_FOCUS_TESTS(ActivationRulesOverride); - -// - Verifies that attempts to change focus or activation from a focus or -// activation change observer are ignored. -DIRECT_FOCUS_CHANGE_TESTS(ShiftFocusOnActivation); -DIRECT_FOCUS_CHANGE_TESTS(ShiftFocusOnActivationDueToHide); -DIRECT_FOCUS_CHANGE_TESTS(NoShiftActiveOnActivation); - -// Clicking on a window which has capture should not result in a focus change. -DIRECT_FOCUS_CHANGE_TESTS(NoFocusChangeOnClickOnCaptureWindow); - -FOCUS_CONTROLLER_TEST(FocusControllerApiTest, - ChangeFocusWhenNothingFocusedAndCaptured); - -// See description above DontPassDeletedWindow() for details. -FOCUS_CONTROLLER_TEST(FocusControllerApiTest, DontPassDeletedWindow); - -// - Verifies that the focused text input client is cleard when the window focus -// changes. -ALL_FOCUS_TESTS(FocusedTextInputClient); - -// If a mouse event was handled, it should not activate a window. -FOCUS_CONTROLLER_TEST(FocusControllerMouseEventTest, IgnoreHandledEvent); - -} // namespace wm
diff --git a/ui/wm/core/focus_rules.h b/ui/wm/core/focus_rules.h deleted file mode 100644 index cb9a4dd..0000000 --- a/ui/wm/core/focus_rules.h +++ /dev/null
@@ -1,66 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_CORE_FOCUS_RULES_H_ -#define UI_WM_CORE_FOCUS_RULES_H_ - -#include "ui/wm/wm_export.h" - -namespace aura { -class Window; -} - -namespace wm { - -// Implemented by an object that establishes the rules about what can be -// focused or activated. -class WM_EXPORT FocusRules { - public: - virtual ~FocusRules() {} - - // Returns true if |window| is a toplevel window. Whether or not a window - // is considered toplevel is determined by a similar set of rules that - // govern activation and focus. Not all toplevel windows are activatable, - // call CanActivateWindow() to determine if a window can be activated. - virtual bool IsToplevelWindow(aura::Window* window) const = 0; - // Returns true if |window| can be activated or focused. - virtual bool CanActivateWindow(aura::Window* window) const = 0; - // For CanFocusWindow(), NULL is supported, because NULL is a valid focusable - // window (in the case of clearing focus). - virtual bool CanFocusWindow(aura::Window* window) const = 0; - - // Returns the toplevel window containing |window|. Not all toplevel windows - // are activatable, call GetActivatableWindow() instead to return the - // activatable window, which might be in a different hierarchy. - // Will return NULL if |window| is not contained by a window considered to be - // a toplevel window. - virtual aura::Window* GetToplevelWindow(aura::Window* window) const = 0; - // Returns the activatable or focusable window given an attempt to activate or - // focus |window|. Some possible scenarios (not intended to be exhaustive): - // - |window| is a child of a non-focusable window and so focus must be set - // according to rules defined by the delegate, e.g. to a parent. - // - |window| is an activatable window that is the transient parent of a modal - // window, so attempts to activate |window| should result in the modal - // transient being activated instead. - // These methods may return NULL if they are unable to find an activatable - // or focusable window given |window|. - virtual aura::Window* GetActivatableWindow(aura::Window* window) const = 0; - virtual aura::Window* GetFocusableWindow(aura::Window* window) const = 0; - - // Returns the next window to activate in the event that |ignore| is no longer - // activatable. This function is called when something is happening to - // |ignore| that means it can no longer have focus or activation, including - // but not limited to: - // - it or its parent hierarchy is being hidden, or removed from the - // RootWindow. - // - it is being destroyed. - // - it is being explicitly deactivated. - // |ignore| cannot be NULL. - virtual aura::Window* GetNextActivatableWindow( - aura::Window* ignore) const = 0; -}; - -} // namespace wm - -#endif // UI_WM_CORE_FOCUS_RULES_H_
diff --git a/ui/wm/core/image_grid.cc b/ui/wm/core/image_grid.cc deleted file mode 100644 index 0b329f3..0000000 --- a/ui/wm/core/image_grid.cc +++ /dev/null
@@ -1,342 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/image_grid.h" - -#include <algorithm> - -#include "third_party/skia/include/core/SkColor.h" -#include "third_party/skia/include/core/SkXfermode.h" -#include "ui/compositor/dip_util.h" -#include "ui/gfx/canvas.h" -#include "ui/gfx/image/image.h" -#include "ui/gfx/image/image_skia_operations.h" -#include "ui/gfx/rect.h" -#include "ui/gfx/rect_conversions.h" -#include "ui/gfx/size.h" -#include "ui/gfx/size_conversions.h" -#include "ui/gfx/transform.h" - -using std::max; -using std::min; - -namespace wm { -namespace { - -// Sets the scaling for the transform applied to a layer. The left, top, -// right and bottom layers are stretched to the height or width of the -// center image. - -void ScaleWidth(gfx::Size center, ui::Layer* layer, gfx::Transform& transform) { - float layer_width = layer->bounds().width() * layer->device_scale_factor(); - float scale = static_cast<float>(center.width()) / layer_width; - transform.Scale(scale, 1.0); -} - -void ScaleHeight(gfx::Size center, - ui::Layer* layer, - gfx::Transform& transform) { - float layer_height = layer->bounds().height() * layer->device_scale_factor(); - float scale = static_cast<float>(center.height()) / layer_height; - transform.Scale(1.0, scale); -} - -// Returns the dimensions of |image| if non-NULL or gfx::Size(0, 0) otherwise. -gfx::Size GetImageSize(const gfx::Image* image) { - return image ? gfx::Size(image->ToImageSkia()->width(), - image->ToImageSkia()->height()) - : gfx::Size(); -} - -// Returns true if |layer|'s bounds don't fit within |size|. -bool LayerExceedsSize(const ui::Layer* layer, const gfx::Size& size) { - return layer->bounds().width() > size.width() || - layer->bounds().height() > size.height(); -} - -} // namespace - -gfx::RectF ImageGrid::TestAPI::GetTransformedLayerBounds( - const ui::Layer& layer) { - gfx::RectF bounds = layer.bounds(); - layer.transform().TransformRect(&bounds); - return bounds; -} - -ImageGrid::ImageGrid() - : layer_(new ui::Layer(ui::LAYER_NOT_DRAWN)), - top_image_height_(0), - bottom_image_height_(0), - left_image_width_(0), - right_image_width_(0), - base_top_row_height_(0), - base_bottom_row_height_(0), - base_left_column_width_(0), - base_right_column_width_(0) { -} - -ImageGrid::~ImageGrid() { -} - -void ImageGrid::SetImages(const gfx::Image* top_left_image, - const gfx::Image* top_image, - const gfx::Image* top_right_image, - const gfx::Image* left_image, - const gfx::Image* center_image, - const gfx::Image* right_image, - const gfx::Image* bottom_left_image, - const gfx::Image* bottom_image, - const gfx::Image* bottom_right_image) { - SetImage(top_left_image, &top_left_layer_, &top_left_painter_, NONE); - SetImage(top_image, &top_layer_, &top_painter_, HORIZONTAL); - SetImage(top_right_image, &top_right_layer_, &top_right_painter_, NONE); - SetImage(left_image, &left_layer_, &left_painter_, VERTICAL); - SetImage(center_image, ¢er_layer_, ¢er_painter_, NONE); - SetImage(right_image, &right_layer_, &right_painter_, VERTICAL); - SetImage(bottom_left_image, &bottom_left_layer_, &bottom_left_painter_, NONE); - SetImage(bottom_image, &bottom_layer_, &bottom_painter_, HORIZONTAL); - SetImage( - bottom_right_image, &bottom_right_layer_, &bottom_right_painter_, NONE); - - top_image_height_ = GetImageSize(top_image).height(); - bottom_image_height_ = GetImageSize(bottom_image).height(); - left_image_width_ = GetImageSize(left_image).width(); - right_image_width_ = GetImageSize(right_image).width(); - - base_top_row_height_ = max(GetImageSize(top_left_image).height(), - max(GetImageSize(top_image).height(), - GetImageSize(top_right_image).height())); - base_bottom_row_height_ = max(GetImageSize(bottom_left_image).height(), - max(GetImageSize(bottom_image).height(), - GetImageSize(bottom_right_image).height())); - base_left_column_width_ = max(GetImageSize(top_left_image).width(), - max(GetImageSize(left_image).width(), - GetImageSize(bottom_left_image).width())); - base_right_column_width_ = max(GetImageSize(top_right_image).width(), - max(GetImageSize(right_image).width(), - GetImageSize(bottom_right_image).width())); - - // Invalidate previous |size_| so calls to SetSize() will recompute it. - size_.SetSize(0, 0); -} - -void ImageGrid::SetSize(const gfx::Size& size) { - if (size_ == size) - return; - - size_ = size; - - gfx::Rect updated_bounds = layer_->bounds(); - updated_bounds.set_size(size); - layer_->SetBounds(updated_bounds); - - // Calculate the available amount of space for corner images on all sides of - // the grid. If the images don't fit, we need to clip them. - const int left = min(base_left_column_width_, size_.width() / 2); - const int right = min(base_right_column_width_, size_.width() - left); - const int top = min(base_top_row_height_, size_.height() / 2); - const int bottom = min(base_bottom_row_height_, size_.height() - top); - - // The remaining space goes to the center image. - int center_width = std::max(size.width() - left - right, 0); - int center_height = std::max(size.height() - top - bottom, 0); - - // At non-integer scale factors, the ratio of dimensions in DIP is not - // necessarily the same as the ratio in physical pixels due to rounding. Set - // the transform on each of the layers based on dimensions in pixels. - gfx::Size center_size_in_pixels = gfx::ToFlooredSize(gfx::ScaleSize( - gfx::Size(center_width, center_height), layer_->device_scale_factor())); - - if (top_layer_.get()) { - if (center_width > 0) { - gfx::Transform transform; - transform.Translate(left, 0); - ScaleWidth(center_size_in_pixels, top_layer_.get(), transform); - top_layer_->SetTransform(transform); - } - top_layer_->SetVisible(center_width > 0); - } - if (bottom_layer_.get()) { - if (center_width > 0) { - gfx::Transform transform; - transform.Translate( - left, size.height() - bottom_layer_->bounds().height()); - ScaleWidth(center_size_in_pixels, bottom_layer_.get(), transform); - bottom_layer_->SetTransform(transform); - } - bottom_layer_->SetVisible(center_width > 0); - } - if (left_layer_.get()) { - if (center_height > 0) { - gfx::Transform transform; - transform.Translate(0, top); - ScaleHeight(center_size_in_pixels, left_layer_.get(), transform); - left_layer_->SetTransform(transform); - } - left_layer_->SetVisible(center_height > 0); - } - if (right_layer_.get()) { - if (center_height > 0) { - gfx::Transform transform; - transform.Translate( - size.width() - right_layer_->bounds().width(), top); - ScaleHeight(center_size_in_pixels, right_layer_.get(), transform); - right_layer_->SetTransform(transform); - } - right_layer_->SetVisible(center_height > 0); - } - - if (top_left_layer_.get()) { - // No transformation needed; it should be at (0, 0) and unscaled. - top_left_painter_->SetClipRect( - LayerExceedsSize(top_left_layer_.get(), gfx::Size(left, top)) ? - gfx::Rect(gfx::Rect(0, 0, left, top)) : - gfx::Rect(), - top_left_layer_.get()); - } - if (top_right_layer_.get()) { - gfx::Transform transform; - transform.Translate(size.width() - top_right_layer_->bounds().width(), 0.0); - top_right_layer_->SetTransform(transform); - top_right_painter_->SetClipRect( - LayerExceedsSize(top_right_layer_.get(), gfx::Size(right, top)) ? - gfx::Rect(top_right_layer_->bounds().width() - right, 0, - right, top) : - gfx::Rect(), - top_right_layer_.get()); - } - if (bottom_left_layer_.get()) { - gfx::Transform transform; - transform.Translate( - 0.0, size.height() - bottom_left_layer_->bounds().height()); - bottom_left_layer_->SetTransform(transform); - bottom_left_painter_->SetClipRect( - LayerExceedsSize(bottom_left_layer_.get(), gfx::Size(left, bottom)) ? - gfx::Rect(0, bottom_left_layer_->bounds().height() - bottom, - left, bottom) : - gfx::Rect(), - bottom_left_layer_.get()); - } - if (bottom_right_layer_.get()) { - gfx::Transform transform; - transform.Translate( - size.width() - bottom_right_layer_->bounds().width(), - size.height() - bottom_right_layer_->bounds().height()); - bottom_right_layer_->SetTransform(transform); - bottom_right_painter_->SetClipRect( - LayerExceedsSize(bottom_right_layer_.get(), gfx::Size(right, bottom)) ? - gfx::Rect(bottom_right_layer_->bounds().width() - right, - bottom_right_layer_->bounds().height() - bottom, - right, bottom) : - gfx::Rect(), - bottom_right_layer_.get()); - } - - if (center_layer_.get()) { - if (center_width > 0 && center_height > 0) { - gfx::Transform transform; - transform.Translate(left, top); - transform.Scale(center_width / center_layer_->bounds().width(), - center_height / center_layer_->bounds().height()); - center_layer_->SetTransform(transform); - } - center_layer_->SetVisible(center_width > 0 && center_height > 0); - } -} - -void ImageGrid::SetContentBounds(const gfx::Rect& content_bounds) { - - SetSize(gfx::Size( - content_bounds.width() + left_image_width_ + right_image_width_, - content_bounds.height() + top_image_height_ + - bottom_image_height_)); - layer_->SetBounds( - gfx::Rect(content_bounds.x() - left_image_width_, - content_bounds.y() - top_image_height_, - layer_->bounds().width(), - layer_->bounds().height())); -} - -void ImageGrid::ImagePainter::SetClipRect(const gfx::Rect& clip_rect, - ui::Layer* layer) { - if (clip_rect != clip_rect_) { - clip_rect_ = clip_rect; - layer->SchedulePaint(layer->bounds()); - } -} - -void ImageGrid::ImagePainter::OnPaintLayer(gfx::Canvas* canvas) { - if (!clip_rect_.IsEmpty()) - canvas->ClipRect(clip_rect_); - canvas->DrawImageInt(image_, 0, 0); -} - -void ImageGrid::ImagePainter::OnDelegatedFrameDamage( - const gfx::Rect& damage_rect_in_dip) { -} - -void ImageGrid::ImagePainter::OnDeviceScaleFactorChanged( - float device_scale_factor) { - // Redrawing will take care of scale factor change. -} - -base::Closure ImageGrid::ImagePainter::PrepareForLayerBoundsChange() { - return base::Closure(); -} - -void ImageGrid::SetImage(const gfx::Image* image, - scoped_ptr<ui::Layer>* layer_ptr, - scoped_ptr<ImagePainter>* painter_ptr, - ImageType type) { - // Minimum width (for HORIZONTAL) or height (for VERTICAL) of the - // |image| so that layers are scaled property if the device scale - // factor is non integral. - const int kMinimumSize = 20; - - // Clean out old layers and painters. - if (layer_ptr->get()) - layer_->Remove(layer_ptr->get()); - layer_ptr->reset(); - painter_ptr->reset(); - - // If we're not using an image, we're done. - if (!image) - return; - - gfx::ImageSkia image_skia = image->AsImageSkia(); - switch (type) { - case HORIZONTAL: - if (image_skia.width() < kMinimumSize) { - image_skia = gfx::ImageSkiaOperations::CreateResizedImage( - image_skia, - skia::ImageOperations::RESIZE_GOOD, - gfx::Size(kMinimumSize, image_skia.height())); - } - break; - case VERTICAL: - if (image_skia.height() < kMinimumSize) { - image_skia = gfx::ImageSkiaOperations::CreateResizedImage( - image_skia, - skia::ImageOperations::RESIZE_GOOD, - gfx::Size(image_skia.width(), kMinimumSize)); - } - break; - case NONE: - break; - } - - // Set up the new layer and painter. - layer_ptr->reset(new ui::Layer(ui::LAYER_TEXTURED)); - - const gfx::Size size = image_skia.size(); - layer_ptr->get()->SetBounds(gfx::Rect(0, 0, size.width(), size.height())); - - painter_ptr->reset(new ImagePainter(image_skia)); - layer_ptr->get()->set_delegate(painter_ptr->get()); - layer_ptr->get()->SetFillsBoundsOpaquely(false); - layer_ptr->get()->SetVisible(true); - layer_->Add(layer_ptr->get()); -} - -} // namespace wm
diff --git a/ui/wm/core/image_grid.h b/ui/wm/core/image_grid.h deleted file mode 100644 index 6102f8b..0000000 --- a/ui/wm/core/image_grid.h +++ /dev/null
@@ -1,223 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_CORE_IMAGE_GRID_H_ -#define UI_WM_CORE_IMAGE_GRID_H_ - -#include "base/basictypes.h" -#include "base/gtest_prod_util.h" -#include "base/memory/scoped_ptr.h" -#include "ui/compositor/layer.h" -#include "ui/compositor/layer_delegate.h" -#include "ui/gfx/image/image_skia.h" -#include "ui/gfx/rect.h" -#include "ui/gfx/size.h" -#include "ui/wm/wm_export.h" - -namespace gfx { -class Image; -} // namespace gfx - -namespace wm { - -// An ImageGrid is a 3x3 array of ui::Layers, each containing an image. -// -// As the grid is resized, its images fill the requested space: -// - corner images are not scaled -// - top and bottom images are scaled horizontally -// - left and right images are scaled vertically -// - the center image is scaled in both directions -// -// If one of the non-center images is smaller than the largest images in its -// row or column, it will be aligned with the outside of the grid. For -// example, given 4x4 top-left and top-right images and a 1x2 top images: -// -// +--------+---------------------+--------+ -// | | top | | -// | top- +---------------------+ top- + -// | left | | right | -// +----+---+ +---+----+ -// | | | | -// ... -// -// This may seem odd at first, but it lets ImageGrid be used to draw shadows -// with curved corners that extend inwards beyond a window's borders. In the -// below example, the top-left corner image is overlaid on top of the window's -// top-left corner: -// -// +---------+----------------------- -// | ..xxx|XXXXXXXXXXXXXXXXXX -// | .xXXXXX|XXXXXXXXXXXXXXXXXX_____ -// | .xXX | ^ window's top edge -// | .xXX | -// +---------+ -// | xXX| -// | xXX|< window's left edge -// | xXX| -// ... -// -class WM_EXPORT ImageGrid { - public: - // Helper class for use by tests. - class WM_EXPORT TestAPI { - public: - TestAPI(ImageGrid* grid) : grid_(grid) {} - - gfx::Rect top_left_clip_rect() const { - return grid_->top_left_painter_->clip_rect_; - } - gfx::Rect top_right_clip_rect() const { - return grid_->top_right_painter_->clip_rect_; - } - gfx::Rect bottom_left_clip_rect() const { - return grid_->bottom_left_painter_->clip_rect_; - } - gfx::Rect bottom_right_clip_rect() const { - return grid_->bottom_right_painter_->clip_rect_; - } - - // Returns |layer|'s bounds after applying the layer's current transform. - gfx::RectF GetTransformedLayerBounds(const ui::Layer& layer); - - private: - ImageGrid* grid_; // not owned - - DISALLOW_COPY_AND_ASSIGN(TestAPI); - }; - - ImageGrid(); - ~ImageGrid(); - - ui::Layer* layer() { return layer_.get(); } - int top_image_height() const { return top_image_height_; } - int bottom_image_height() const { return bottom_image_height_; } - int left_image_width() const { return left_image_width_; } - int right_image_width() const { return right_image_width_; } - - // Visible to allow independent layer animations and for testing. - ui::Layer* top_left_layer() const { return top_left_layer_.get(); } - ui::Layer* top_layer() const { return top_layer_.get(); } - ui::Layer* top_right_layer() const { return top_right_layer_.get(); } - ui::Layer* left_layer() const { return left_layer_.get(); } - ui::Layer* center_layer() const { return center_layer_.get(); } - ui::Layer* right_layer() const { return right_layer_.get(); } - ui::Layer* bottom_left_layer() const { return bottom_left_layer_.get(); } - ui::Layer* bottom_layer() const { return bottom_layer_.get(); } - ui::Layer* bottom_right_layer() const { return bottom_right_layer_.get(); } - - // Sets the grid to display the passed-in images (any of which can be NULL). - // Ownership of the images remains with the caller. May be called more than - // once to switch images. - void SetImages(const gfx::Image* top_left_image, - const gfx::Image* top_image, - const gfx::Image* top_right_image, - const gfx::Image* left_image, - const gfx::Image* center_image, - const gfx::Image* right_image, - const gfx::Image* bottom_left_image, - const gfx::Image* bottom_image, - const gfx::Image* bottom_right_image); - - void SetSize(const gfx::Size& size); - - // Sets the grid to a position and size such that the inner edges of the top, - // bottom, left and right images will be flush with |content_bounds_in_dip|. - void SetContentBounds(const gfx::Rect& content_bounds_in_dip); - - private: - // Delegate responsible for painting a specific image on a layer. - class ImagePainter : public ui::LayerDelegate { - public: - ImagePainter(const gfx::ImageSkia& image) : image_(image) {} - virtual ~ImagePainter() {} - - // Clips |layer| to |clip_rect|. Triggers a repaint if the clipping - // rectangle has changed. An empty rectangle disables clipping. - void SetClipRect(const gfx::Rect& clip_rect, ui::Layer* layer); - - // ui::LayerDelegate implementation: - virtual void OnPaintLayer(gfx::Canvas* canvas) override; - virtual void OnDelegatedFrameDamage( - const gfx::Rect& damage_rect_in_dip) override; - virtual void OnDeviceScaleFactorChanged(float device_scale_factor) override; - virtual base::Closure PrepareForLayerBoundsChange() override; - - private: - friend class TestAPI; - - const gfx::ImageSkia image_; - - gfx::Rect clip_rect_; - - DISALLOW_COPY_AND_ASSIGN(ImagePainter); - }; - - enum ImageType { - HORIZONTAL, - VERTICAL, - NONE, - }; - - // Sets |layer_ptr| and |painter_ptr| to display |image| and adds the - // passed-in layer to |layer_|. If image is NULL resets |layer_ptr| and - // |painter_ptr| and removes any existing layer from |layer_|. - // If |type| is either HORIZONTAL or VERTICAL, it may resize the image to - // guarantee that it has minimum size in order for scaling work properly - // with fractional device scale factors. crbug.com/376519. - void SetImage(const gfx::Image* image, - scoped_ptr<ui::Layer>* layer_ptr, - scoped_ptr<ImagePainter>* painter_ptr, - ImageType type); - - // Layer that contains all of the image layers. - scoped_ptr<ui::Layer> layer_; - - // The grid's dimensions. - gfx::Size size_; - - // Heights and widths of the images displayed by |top_layer_|, - // |bottom_layer_|, |left_layer_|, and |right_layer_|. - int top_image_height_; - int bottom_image_height_; - int left_image_width_; - int right_image_width_; - - // Heights of the tallest images in the top and bottom rows and the widest - // images in the left and right columns. Note that we may have less actual - // space than this available if the images are large and |size_| is small. - int base_top_row_height_; - int base_bottom_row_height_; - int base_left_column_width_; - int base_right_column_width_; - - // Layers used to display the various images. Children of |layer_|. - // Positions for which no images were supplied are NULL. - scoped_ptr<ui::Layer> top_left_layer_; - scoped_ptr<ui::Layer> top_layer_; - scoped_ptr<ui::Layer> top_right_layer_; - scoped_ptr<ui::Layer> left_layer_; - scoped_ptr<ui::Layer> center_layer_; - scoped_ptr<ui::Layer> right_layer_; - scoped_ptr<ui::Layer> bottom_left_layer_; - scoped_ptr<ui::Layer> bottom_layer_; - scoped_ptr<ui::Layer> bottom_right_layer_; - - // Delegates responsible for painting the above layers. - // Positions for which no images were supplied are NULL. - scoped_ptr<ImagePainter> top_left_painter_; - scoped_ptr<ImagePainter> top_painter_; - scoped_ptr<ImagePainter> top_right_painter_; - scoped_ptr<ImagePainter> left_painter_; - scoped_ptr<ImagePainter> center_painter_; - scoped_ptr<ImagePainter> right_painter_; - scoped_ptr<ImagePainter> bottom_left_painter_; - scoped_ptr<ImagePainter> bottom_painter_; - scoped_ptr<ImagePainter> bottom_right_painter_; - - DISALLOW_COPY_AND_ASSIGN(ImageGrid); -}; - -} // namespace wm - -#endif // UI_WM_CORE_IMAGE_GRID_H_
diff --git a/ui/wm/core/image_grid_unittest.cc b/ui/wm/core/image_grid_unittest.cc deleted file mode 100644 index b10e14f..0000000 --- a/ui/wm/core/image_grid_unittest.cc +++ /dev/null
@@ -1,340 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/image_grid.h" - -#include "testing/gtest/include/gtest/gtest.h" -#include "third_party/skia/include/core/SkBitmap.h" -#include "ui/aura/test/aura_test_base.h" -#include "ui/gfx/image/image.h" -#include "ui/gfx/image/image_skia.h" - -namespace wm { - -namespace { - -// Creates a gfx::Image with the requested dimensions. -gfx::Image* CreateImage(const gfx::Size& size) { - SkBitmap bitmap; - bitmap.setInfo(SkImageInfo::MakeN32Premul(size.width(), size.height())); - return new gfx::Image(gfx::ImageSkia::CreateFrom1xBitmap(bitmap)); -} - -} // namespace - -typedef aura::test::AuraTestBase ImageGridTest; - -// Test that an ImageGrid's layers are transformed correctly when SetSize() is -// called. -TEST_F(ImageGridTest, Basic) { - // Size of the images around the grid's border. - const int kBorder = 2; - - scoped_ptr<gfx::Image> image_1x1(CreateImage(gfx::Size(1, 1))); - scoped_ptr<gfx::Image> image_1xB(CreateImage(gfx::Size(1, kBorder))); - scoped_ptr<gfx::Image> image_Bx1(CreateImage(gfx::Size(kBorder, 1))); - scoped_ptr<gfx::Image> image_BxB(CreateImage(gfx::Size(kBorder, kBorder))); - - ImageGrid grid; - grid.SetImages(image_BxB.get(), image_1xB.get(), image_BxB.get(), - image_Bx1.get(), image_1x1.get(), image_Bx1.get(), - image_BxB.get(), image_1xB.get(), image_BxB.get()); - - ImageGrid::TestAPI test_api(&grid); - ASSERT_TRUE(grid.top_left_layer() != NULL); - ASSERT_TRUE(grid.top_layer() != NULL); - ASSERT_TRUE(grid.top_right_layer() != NULL); - ASSERT_TRUE(grid.left_layer() != NULL); - ASSERT_TRUE(grid.center_layer() != NULL); - ASSERT_TRUE(grid.right_layer() != NULL); - ASSERT_TRUE(grid.bottom_left_layer() != NULL); - ASSERT_TRUE(grid.bottom_layer() != NULL); - ASSERT_TRUE(grid.bottom_right_layer() != NULL); - - const gfx::Size size(20, 30); - grid.SetSize(size); - - // The top-left layer should be flush with the top-left corner and unscaled. - EXPECT_EQ(gfx::RectF(0, 0, kBorder, kBorder).ToString(), - test_api.GetTransformedLayerBounds( - *grid.top_left_layer()).ToString()); - - // The top layer should be flush with the top edge and stretched horizontally - // between the two top corners. - EXPECT_EQ(gfx::RectF( - kBorder, 0, size.width() - 2 * kBorder, kBorder).ToString(), - test_api.GetTransformedLayerBounds( - *grid.top_layer()).ToString()); - - // The top-right layer should be flush with the top-right corner and unscaled. - EXPECT_EQ(gfx::RectF(size.width() - kBorder, 0, kBorder, kBorder).ToString(), - test_api.GetTransformedLayerBounds( - *grid.top_right_layer()).ToString()); - - // The left layer should be flush with the left edge and stretched vertically - // between the two left corners. - EXPECT_EQ(gfx::RectF( - 0, kBorder, kBorder, size.height() - 2 * kBorder).ToString(), - test_api.GetTransformedLayerBounds( - *grid.left_layer()).ToString()); - - // The center layer should fill the space in the middle of the grid. - EXPECT_EQ(gfx::RectF( - kBorder, kBorder, size.width() - 2 * kBorder, - size.height() - 2 * kBorder).ToString(), - test_api.GetTransformedLayerBounds( - *grid.center_layer()).ToString()); - - // The right layer should be flush with the right edge and stretched - // vertically between the two right corners. - EXPECT_EQ(gfx::RectF( - size.width() - kBorder, kBorder, - kBorder, size.height() - 2 * kBorder).ToString(), - test_api.GetTransformedLayerBounds( - *grid.right_layer()).ToString()); - - // The bottom-left layer should be flush with the bottom-left corner and - // unscaled. - EXPECT_EQ(gfx::RectF(0, size.height() - kBorder, kBorder, kBorder).ToString(), - test_api.GetTransformedLayerBounds( - *grid.bottom_left_layer()).ToString()); - - // The bottom layer should be flush with the bottom edge and stretched - // horizontally between the two bottom corners. - EXPECT_EQ(gfx::RectF( - kBorder, size.height() - kBorder, - size.width() - 2 * kBorder, kBorder).ToString(), - test_api.GetTransformedLayerBounds( - *grid.bottom_layer()).ToString()); - - // The bottom-right layer should be flush with the bottom-right corner and - // unscaled. - EXPECT_EQ(gfx::RectF( - size.width() - kBorder, size.height() - kBorder, - kBorder, kBorder).ToString(), - test_api.GetTransformedLayerBounds( - *grid.bottom_right_layer()).ToString()); -} - -// Test that an ImageGrid's layers are transformed correctly when -// SetContentBounds() is called. -TEST_F(ImageGridTest, SetContentBounds) { - // Size of the images around the grid's border. - const int kBorder = 2; - - scoped_ptr<gfx::Image> image_1x1(CreateImage(gfx::Size(1, 1))); - scoped_ptr<gfx::Image> image_1xB(CreateImage(gfx::Size(1, kBorder))); - scoped_ptr<gfx::Image> image_Bx1(CreateImage(gfx::Size(kBorder, 1))); - scoped_ptr<gfx::Image> image_BxB(CreateImage(gfx::Size(kBorder, kBorder))); - - ImageGrid grid; - grid.SetImages(image_BxB.get(), image_1xB.get(), image_BxB.get(), - image_Bx1.get(), image_1x1.get(), image_Bx1.get(), - image_BxB.get(), image_1xB.get(), image_BxB.get()); - - ImageGrid::TestAPI test_api(&grid); - - const gfx::Point origin(5, 10); - const gfx::Size size(20, 30); - grid.SetContentBounds(gfx::Rect(origin, size)); - - // The master layer is positioned above the top-left corner of the content - // bounds and has height/width that contain the grid and bounds. - EXPECT_EQ(gfx::RectF(origin.x() - kBorder, - origin.y() - kBorder, - size.width() + 2 * kBorder, - size.height() + 2 * kBorder).ToString(), - test_api.GetTransformedLayerBounds(*grid.layer()).ToString()); -} - -// Check that we don't crash if only a single image is supplied. -TEST_F(ImageGridTest, SingleImage) { - const int kBorder = 1; - scoped_ptr<gfx::Image> image(CreateImage(gfx::Size(kBorder, kBorder))); - - ImageGrid grid; - grid.SetImages(NULL, image.get(), NULL, - NULL, NULL, NULL, - NULL, NULL, NULL); - - ImageGrid::TestAPI test_api(&grid); - EXPECT_TRUE(grid.top_left_layer() == NULL); - ASSERT_TRUE(grid.top_layer() != NULL); - EXPECT_TRUE(grid.top_right_layer() == NULL); - EXPECT_TRUE(grid.left_layer() == NULL); - EXPECT_TRUE(grid.center_layer() == NULL); - EXPECT_TRUE(grid.right_layer() == NULL); - EXPECT_TRUE(grid.bottom_left_layer() == NULL); - EXPECT_TRUE(grid.bottom_layer() == NULL); - EXPECT_TRUE(grid.bottom_right_layer() == NULL); - - const gfx::Size kSize(10, 10); - grid.SetSize(kSize); - - // The top layer should be scaled horizontally across the entire width, but it - // shouldn't be scaled vertically. - EXPECT_EQ(gfx::RectF(0, 0, kSize.width(), kBorder).ToString(), - test_api.GetTransformedLayerBounds( - *grid.top_layer()).ToString()); -} - -// Check that we don't crash when we reset existing images to NULL and -// reset NULL images to new ones. -TEST_F(ImageGridTest, ResetImages) { - const int kBorder = 1; - scoped_ptr<gfx::Image> image(CreateImage(gfx::Size(kBorder, kBorder))); - - ImageGrid grid; - grid.SetImages(NULL, image.get(), NULL, - NULL, NULL, NULL, - NULL, NULL, NULL); - - // Only the top edge has a layer. - ImageGrid::TestAPI test_api(&grid); - ASSERT_TRUE(grid.top_left_layer() == NULL); - ASSERT_FALSE(grid.top_layer() == NULL); - ASSERT_TRUE(grid.top_right_layer() == NULL); - ASSERT_TRUE(grid.left_layer() == NULL); - ASSERT_TRUE(grid.center_layer() == NULL); - ASSERT_TRUE(grid.right_layer() == NULL); - ASSERT_TRUE(grid.bottom_left_layer() == NULL); - ASSERT_TRUE(grid.bottom_layer() == NULL); - ASSERT_TRUE(grid.bottom_right_layer() == NULL); - - grid.SetImages(NULL, NULL, NULL, - NULL, NULL, NULL, - NULL, image.get(), NULL); - - // Now only the bottom edge has a layer. - ASSERT_TRUE(grid.top_left_layer() == NULL); - ASSERT_TRUE(grid.top_layer() == NULL); - ASSERT_TRUE(grid.top_right_layer() == NULL); - ASSERT_TRUE(grid.left_layer() == NULL); - ASSERT_TRUE(grid.center_layer() == NULL); - ASSERT_TRUE(grid.right_layer() == NULL); - ASSERT_TRUE(grid.bottom_left_layer() == NULL); - ASSERT_FALSE(grid.bottom_layer() == NULL); - ASSERT_TRUE(grid.bottom_right_layer() == NULL); -} - -// Test that side (top, left, right, bottom) layers that are narrower than their -// adjacent corner layers stay pinned to the outside edges instead of getting -// moved inwards or scaled. This exercises the scenario used for shadows. -TEST_F(ImageGridTest, SmallerSides) { - const int kCorner = 2; - const int kEdge = 1; - - scoped_ptr<gfx::Image> top_left_image( - CreateImage(gfx::Size(kCorner, kCorner))); - scoped_ptr<gfx::Image> top_image(CreateImage(gfx::Size(kEdge, kEdge))); - scoped_ptr<gfx::Image> top_right_image( - CreateImage(gfx::Size(kCorner, kCorner))); - scoped_ptr<gfx::Image> left_image(CreateImage(gfx::Size(kEdge, kEdge))); - scoped_ptr<gfx::Image> right_image(CreateImage(gfx::Size(kEdge, kEdge))); - - ImageGrid grid; - grid.SetImages(top_left_image.get(), top_image.get(), top_right_image.get(), - left_image.get(), NULL, right_image.get(), - NULL, NULL, NULL); - ImageGrid::TestAPI test_api(&grid); - - const gfx::Size kSize(20, 30); - grid.SetSize(kSize); - - // The top layer should be flush with the top edge and stretched horizontally - // between the two top corners. - EXPECT_EQ(gfx::RectF( - kCorner, 0, kSize.width() - 2 * kCorner, kEdge).ToString(), - test_api.GetTransformedLayerBounds( - *grid.top_layer()).ToString()); - - // The left layer should be flush with the left edge and stretched vertically - // between the top left corner and the bottom. - EXPECT_EQ(gfx::RectF( - 0, kCorner, kEdge, kSize.height() - kCorner).ToString(), - test_api.GetTransformedLayerBounds( - *grid.left_layer()).ToString()); - - // The right layer should be flush with the right edge and stretched - // vertically between the top right corner and the bottom. - EXPECT_EQ(gfx::RectF( - kSize.width() - kEdge, kCorner, - kEdge, kSize.height() - kCorner).ToString(), - test_api.GetTransformedLayerBounds( - *grid.right_layer()).ToString()); -} - -// Test that we hide or clip layers as needed when the grid is assigned a small -// size. -TEST_F(ImageGridTest, TooSmall) { - const int kCorner = 5; - const int kCenter = 3; - const int kEdge = 3; - - scoped_ptr<gfx::Image> top_left_image( - CreateImage(gfx::Size(kCorner, kCorner))); - scoped_ptr<gfx::Image> top_image(CreateImage(gfx::Size(kEdge, kEdge))); - scoped_ptr<gfx::Image> top_right_image( - CreateImage(gfx::Size(kCorner, kCorner))); - scoped_ptr<gfx::Image> left_image(CreateImage(gfx::Size(kEdge, kEdge))); - scoped_ptr<gfx::Image> center_image(CreateImage(gfx::Size(kCenter, kCenter))); - scoped_ptr<gfx::Image> right_image(CreateImage(gfx::Size(kEdge, kEdge))); - scoped_ptr<gfx::Image> bottom_left_image( - CreateImage(gfx::Size(kCorner, kCorner))); - scoped_ptr<gfx::Image> bottom_image(CreateImage(gfx::Size(kEdge, kEdge))); - scoped_ptr<gfx::Image> bottom_right_image( - CreateImage(gfx::Size(kCorner, kCorner))); - - ImageGrid grid; - grid.SetImages( - top_left_image.get(), top_image.get(), top_right_image.get(), - left_image.get(), center_image.get(), right_image.get(), - bottom_left_image.get(), bottom_image.get(), bottom_right_image.get()); - ImageGrid::TestAPI test_api(&grid); - - // Set a size that's smaller than the combined (unscaled) corner images. - const gfx::Size kSmallSize(kCorner + kCorner - 3, kCorner + kCorner - 5); - grid.SetSize(kSmallSize); - - // The scalable images around the sides and in the center should be hidden. - EXPECT_FALSE(grid.top_layer()->visible()); - EXPECT_FALSE(grid.bottom_layer()->visible()); - EXPECT_FALSE(grid.left_layer()->visible()); - EXPECT_FALSE(grid.right_layer()->visible()); - EXPECT_FALSE(grid.center_layer()->visible()); - - // The corner images' clip rects should sum to the expected size. - EXPECT_EQ(kSmallSize.width(), - test_api.top_left_clip_rect().width() + - test_api.top_right_clip_rect().width()); - EXPECT_EQ(kSmallSize.width(), - test_api.bottom_left_clip_rect().width() + - test_api.bottom_right_clip_rect().width()); - EXPECT_EQ(kSmallSize.height(), - test_api.top_left_clip_rect().height() + - test_api.bottom_left_clip_rect().height()); - EXPECT_EQ(kSmallSize.height(), - test_api.top_right_clip_rect().height() + - test_api.bottom_right_clip_rect().height()); - - // Resize the grid to be large enough to show all images. - const gfx::Size kLargeSize(kCorner + kCorner + kCenter, - kCorner + kCorner + kCenter); - grid.SetSize(kLargeSize); - - // The scalable images should be visible now. - EXPECT_TRUE(grid.top_layer()->visible()); - EXPECT_TRUE(grid.bottom_layer()->visible()); - EXPECT_TRUE(grid.left_layer()->visible()); - EXPECT_TRUE(grid.right_layer()->visible()); - EXPECT_TRUE(grid.center_layer()->visible()); - - // We shouldn't be clipping the corner images anymore. - EXPECT_TRUE(test_api.top_left_clip_rect().IsEmpty()); - EXPECT_TRUE(test_api.top_right_clip_rect().IsEmpty()); - EXPECT_TRUE(test_api.bottom_left_clip_rect().IsEmpty()); - EXPECT_TRUE(test_api.bottom_right_clip_rect().IsEmpty()); -} - -} // namespace wm
diff --git a/ui/wm/core/input_method_event_filter.cc b/ui/wm/core/input_method_event_filter.cc deleted file mode 100644 index 3488e4a..0000000 --- a/ui/wm/core/input_method_event_filter.cc +++ /dev/null
@@ -1,105 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/input_method_event_filter.h" - -#include "ui/aura/client/aura_constants.h" -#include "ui/aura/window_tree_host.h" -#include "ui/base/ime/input_method.h" -#include "ui/base/ime/input_method_factory.h" -#include "ui/base/ime/text_input_client.h" -#include "ui/events/event.h" -#include "ui/events/event_processor.h" - -namespace wm { - -//////////////////////////////////////////////////////////////////////////////// -// InputMethodEventFilter, public: - -InputMethodEventFilter::InputMethodEventFilter(gfx::AcceleratedWidget widget) - : input_method_(ui::CreateInputMethod(this, widget)) { - // TODO(yusukes): Check if the root window is currently focused and pass the - // result to Init(). - input_method_->Init(true); -} - -InputMethodEventFilter::~InputMethodEventFilter() { -} - -void InputMethodEventFilter::SetInputMethodPropertyInRootWindow( - aura::Window* root_window) { - root_window->SetProperty(aura::client::kRootWindowInputMethodKey, - input_method_.get()); -} - -//////////////////////////////////////////////////////////////////////////////// -// InputMethodEventFilter, EventFilter implementation: - -void InputMethodEventFilter::OnKeyEvent(ui::KeyEvent* event) { - // We're processing key events as follows (details are simplified). - // - // At the beginning, key events have a ET_KEY_{PRESSED,RELEASED} event type, - // and they're passed from step 1 through step 3. - // 1. EventProcessor::OnEventFromSource() - // 2. InputMethodEventFilter::OnKeyEvent() - // 3. InputMethod::DispatchKeyEvent() - // where InputMethod may call DispatchKeyEventPostIME() if IME didn't consume - // the key event. Otherwise, step 4 through step 6 are skipped and we fall - // down to step 7 directly. - // 4. InputMethodEventFilter::DispatchKeyEventPostIME() - // where the key event is marked as TRANSLATED and the event type becomes - // ET_TRANSLATED_KEY_{PRESS,RELEASE}. Then, we dispatch the event again from - // the beginning. - // 5. EventProcessor::OnEventFromSource() [second time] - // 6. InputMethodEventFilter::OnKeyEvent() [second time] - // where we know that the event was already processed once by IME and - // re-dispatched, we don't pass the event to IME again. Instead we unmark the - // event as not translated (as same as the original state), and let the event - // dispatcher continue to dispatch the event to the rest event handlers. - // 7. EventHandler::OnKeyEvent() - if (event->IsTranslated()) { - // The |event| was already processed by IME, so we don't pass the event to - // IME again. Just let the event dispatcher continue to dispatch the event. - event->SetTranslated(false); - } else { - if (input_method_->DispatchKeyEvent(*event)) - event->StopPropagation(); - } -} - -//////////////////////////////////////////////////////////////////////////////// -// InputMethodEventFilter, ui::InputMethodDelegate implementation: - -bool InputMethodEventFilter::DispatchKeyEventPostIME( - const ui::KeyEvent& event) { -#if defined(OS_WIN) - DCHECK(!event.HasNativeEvent() || event.native_event().message != WM_CHAR); -#endif - // Since the underlying IME didn't consume the key event, we're going to - // dispatch the event again from the beginning of the tree of event targets. - // This time we have to skip dispatching the event to the IME, we mark the - // event as TRANSLATED so we can distinguish this event as a second time - // dispatched event. - // For the target where to dispatch the event, always tries the current - // focused text input client's attached window. And fallback to the target - // carried by event. - aura::Window* target_window = NULL; - ui::TextInputClient* input = input_method_->GetTextInputClient(); - if (input) - target_window = input->GetAttachedWindow(); - if (!target_window) - target_window = static_cast<aura::Window*>(event.target()); - if (!target_window) - return false; - ui::EventProcessor* target_dispatcher = - target_window->GetRootWindow()->GetHost()->event_processor(); - ui::KeyEvent aura_event(event); - aura_event.SetTranslated(true); - ui::EventDispatchDetails details = - target_dispatcher->OnEventFromSource(&aura_event); - CHECK(!details.dispatcher_destroyed); - return aura_event.handled(); -} - -} // namespace wm
diff --git a/ui/wm/core/input_method_event_filter.h b/ui/wm/core/input_method_event_filter.h deleted file mode 100644 index d658d77..0000000 --- a/ui/wm/core/input_method_event_filter.h +++ /dev/null
@@ -1,50 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_CORE_INPUT_METHOD_EVENT_FILTER_H_ -#define UI_WM_CORE_INPUT_METHOD_EVENT_FILTER_H_ - -#include "base/compiler_specific.h" -#include "base/macros.h" -#include "base/memory/scoped_ptr.h" -#include "ui/base/ime/input_method_delegate.h" -#include "ui/events/event_handler.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/wm/wm_export.h" - -namespace ui { -class EventProcessor; -class InputMethod; -} - -namespace wm { - -// An event filter that forwards a KeyEvent to a system IME, and dispatches a -// TranslatedKeyEvent to the root window as needed. -class WM_EXPORT InputMethodEventFilter - : public ui::EventHandler, - public ui::internal::InputMethodDelegate { - public: - explicit InputMethodEventFilter(gfx::AcceleratedWidget widget); - virtual ~InputMethodEventFilter(); - - void SetInputMethodPropertyInRootWindow(aura::Window* root_window); - - ui::InputMethod* input_method() const { return input_method_.get(); } - - private: - // Overridden from ui::EventHandler: - virtual void OnKeyEvent(ui::KeyEvent* event) override; - - // Overridden from ui::internal::InputMethodDelegate: - virtual bool DispatchKeyEventPostIME(const ui::KeyEvent& event) override; - - scoped_ptr<ui::InputMethod> input_method_; - - DISALLOW_COPY_AND_ASSIGN(InputMethodEventFilter); -}; - -} // namespace wm - -#endif // UI_WM_CORE_INPUT_METHOD_EVENT_FILTER_H_
diff --git a/ui/wm/core/input_method_event_filter_unittest.cc b/ui/wm/core/input_method_event_filter_unittest.cc deleted file mode 100644 index 9a2d31b..0000000 --- a/ui/wm/core/input_method_event_filter_unittest.cc +++ /dev/null
@@ -1,142 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/input_method_event_filter.h" - -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/aura/client/aura_constants.h" -#include "ui/aura/test/aura_test_base.h" -#include "ui/aura/test/test_windows.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/base/ime/dummy_text_input_client.h" -#include "ui/base/ime/input_method.h" -#include "ui/base/ime/text_input_focus_manager.h" -#include "ui/base/ui_base_switches_util.h" -#include "ui/events/test/event_generator.h" -#include "ui/events/test/test_event_handler.h" -#include "ui/wm/core/compound_event_filter.h" -#include "ui/wm/core/default_activation_client.h" -#include "ui/wm/public/activation_client.h" - -#if !defined(OS_WIN) && !defined(USE_X11) -// On platforms except Windows and X11, ui::test::EventGenerator::PressKey -// generates a key event without native_event(), which is not supported by -// ui::MockInputMethod. -#define TestInputMethodKeyEventPropagation \ -DISABLED_TestInputMethodKeyEventPropagation -#endif - -namespace wm { - -class TestTextInputClient : public ui::DummyTextInputClient { - public: - explicit TestTextInputClient(aura::Window* window) : window_(window) {} - - virtual aura::Window* GetAttachedWindow() const override { return window_; } - - private: - aura::Window* window_; - - DISALLOW_COPY_AND_ASSIGN(TestTextInputClient); -}; - -class InputMethodEventFilterTest : public aura::test::AuraTestBase { - public: - InputMethodEventFilterTest() {} - virtual ~InputMethodEventFilterTest() {} - - // testing::Test overrides: - virtual void SetUp() override { - aura::test::AuraTestBase::SetUp(); - - root_window()->AddPreTargetHandler(&root_filter_); - input_method_event_filter_.reset( - new InputMethodEventFilter(host()->GetAcceleratedWidget())); - input_method_event_filter_->SetInputMethodPropertyInRootWindow( - root_window()); - root_filter_.AddHandler(input_method_event_filter_.get()); - root_filter_.AddHandler(&test_filter_); - - test_window_.reset(aura::test::CreateTestWindowWithDelegate( - &test_window_delegate_, -1, gfx::Rect(), root_window())); - test_input_client_.reset(new TestTextInputClient(test_window_.get())); - - input_method_event_filter_->input_method()->SetFocusedTextInputClient( - test_input_client_.get()); - } - - virtual void TearDown() override { - test_window_.reset(); - root_filter_.RemoveHandler(&test_filter_); - root_filter_.RemoveHandler(input_method_event_filter_.get()); - root_window()->RemovePreTargetHandler(&root_filter_); - - input_method_event_filter_.reset(); - test_input_client_.reset(); - aura::test::AuraTestBase::TearDown(); - } - - protected: - CompoundEventFilter root_filter_; - ui::test::TestEventHandler test_filter_; - scoped_ptr<InputMethodEventFilter> input_method_event_filter_; - aura::test::TestWindowDelegate test_window_delegate_; - scoped_ptr<aura::Window> test_window_; - scoped_ptr<TestTextInputClient> test_input_client_; - - private: - DISALLOW_COPY_AND_ASSIGN(InputMethodEventFilterTest); -}; - -TEST_F(InputMethodEventFilterTest, TestInputMethodProperty) { - // Tests if InputMethodEventFilter adds a window property on its - // construction. - EXPECT_TRUE(root_window()->GetProperty( - aura::client::kRootWindowInputMethodKey)); -} - -// Tests if InputMethodEventFilter dispatches a ui::ET_TRANSLATED_KEY_* event to -// the root window. -TEST_F(InputMethodEventFilterTest, TestInputMethodKeyEventPropagation) { - // Send a fake key event to the root window. InputMethodEventFilter, which is - // automatically set up by AshTestBase, consumes it and sends a new - // ui::ET_TRANSLATED_KEY_* event to the root window, which will be consumed by - // the test event filter. - ui::test::EventGenerator generator(root_window()); - EXPECT_EQ(0, test_filter_.num_key_events()); - generator.PressKey(ui::VKEY_SPACE, 0); - EXPECT_EQ(1, test_filter_.num_key_events()); - generator.ReleaseKey(ui::VKEY_SPACE, 0); - EXPECT_EQ(2, test_filter_.num_key_events()); -} - -TEST_F(InputMethodEventFilterTest, TestEventDispatching) { - ui::KeyEvent evt(ui::ET_KEY_PRESSED, - ui::VKEY_PROCESSKEY, - ui::EF_IME_FABRICATED_KEY); - // Calls DispatchKeyEventPostIME() without a focused text input client. - if (switches::IsTextInputFocusManagerEnabled()) - ui::TextInputFocusManager::GetInstance()->FocusTextInputClient(NULL); - else - input_method_event_filter_->input_method()->SetFocusedTextInputClient(NULL); - input_method_event_filter_->input_method()->DispatchKeyEvent(evt); - // Verifies 0 key event happened because InputMethodEventFilter:: - // DispatchKeyEventPostIME() returns false. - EXPECT_EQ(0, test_filter_.num_key_events()); - - // Calls DispatchKeyEventPostIME() with a focused text input client. - if (switches::IsTextInputFocusManagerEnabled()) { - ui::TextInputFocusManager::GetInstance()->FocusTextInputClient( - test_input_client_.get()); - } else { - input_method_event_filter_->input_method()->SetFocusedTextInputClient( - test_input_client_.get()); - } - input_method_event_filter_->input_method()->DispatchKeyEvent(evt); - // Verifies 1 key event happened because InputMethodEventFilter:: - // DispatchKeyEventPostIME() returns true. - EXPECT_EQ(1, test_filter_.num_key_events()); -} - -} // namespace wm
diff --git a/ui/wm/core/masked_window_targeter.cc b/ui/wm/core/masked_window_targeter.cc deleted file mode 100644 index 5cbdb19..0000000 --- a/ui/wm/core/masked_window_targeter.cc +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/masked_window_targeter.h" - -#include "ui/aura/window.h" -#include "ui/gfx/path.h" - -namespace wm { - -MaskedWindowTargeter::MaskedWindowTargeter(aura::Window* masked_window) - : masked_window_(masked_window) { -} - -MaskedWindowTargeter::~MaskedWindowTargeter() {} - -bool MaskedWindowTargeter::EventLocationInsideBounds( - ui::EventTarget* target, - const ui::LocatedEvent& event) const { - aura::Window* window = static_cast<aura::Window*>(target); - if (window == masked_window_) { - gfx::Path mask; - if (!GetHitTestMask(window, &mask)) - return WindowTargeter::EventLocationInsideBounds(window, event); - - gfx::Size size = window->bounds().size(); - SkRegion clip_region; - clip_region.setRect(0, 0, size.width(), size.height()); - - gfx::Point point = event.location(); - if (window->parent()) - aura::Window::ConvertPointToTarget(window->parent(), window, &point); - - SkRegion mask_region; - return mask_region.setPath(mask, clip_region) && - mask_region.contains(point.x(), point.y()); - } - - return WindowTargeter::EventLocationInsideBounds(window, event); -} - -} // namespace wm
diff --git a/ui/wm/core/masked_window_targeter.h b/ui/wm/core/masked_window_targeter.h deleted file mode 100644 index e289329..0000000 --- a/ui/wm/core/masked_window_targeter.h +++ /dev/null
@@ -1,40 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_CORE_MASKED_WINDOW_TARGETER_H_ -#define UI_WM_CORE_MASKED_WINDOW_TARGETER_H_ - -#include "ui/aura/window_targeter.h" -#include "ui/wm/wm_export.h" - -namespace gfx { -class Path; -} - -namespace wm { - -class WM_EXPORT MaskedWindowTargeter : public aura::WindowTargeter { - public: - explicit MaskedWindowTargeter(aura::Window* masked_window); - virtual ~MaskedWindowTargeter(); - - protected: - // Sets the hit-test mask for |window| in |mask| (in |window|'s local - // coordinate system). Returns whether a valid mask has been set in |mask|. - virtual bool GetHitTestMask(aura::Window* window, gfx::Path* mask) const = 0; - - // ui::EventTargeter: - virtual bool EventLocationInsideBounds( - ui::EventTarget* target, - const ui::LocatedEvent& event) const override; - - private: - aura::Window* masked_window_; - - DISALLOW_COPY_AND_ASSIGN(MaskedWindowTargeter); -}; - -} // namespace wm - -#endif // UI_WM_CORE_MASKED_WINDOW_TARGETER_H_
diff --git a/ui/wm/core/native_cursor_manager.h b/ui/wm/core/native_cursor_manager.h deleted file mode 100644 index de16ef8..0000000 --- a/ui/wm/core/native_cursor_manager.h +++ /dev/null
@@ -1,61 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_CORE_NATIVE_CURSOR_MANAGER_H_ -#define UI_WM_CORE_NATIVE_CURSOR_MANAGER_H_ - -#include "base/strings/string16.h" -#include "ui/base/cursor/cursor.h" -#include "ui/wm/core/native_cursor_manager_delegate.h" -#include "ui/wm/wm_export.h" - -namespace gfx { -class Display; -} - -namespace wm { - -// Interface where platforms such as Ash or Desktop aura are notified of -// requested changes to cursor state. When requested, implementer should tell -// the CursorManager of any actual state changes performed through the -// delegate. -class WM_EXPORT NativeCursorManager { - public: - virtual ~NativeCursorManager() {} - - // A request to set the screen DPI. Can cause changes in the current cursor. - virtual void SetDisplay( - const gfx::Display& display, - NativeCursorManagerDelegate* delegate) = 0; - - // A request to set the cursor to |cursor|. At minimum, implementer should - // call NativeCursorManagerDelegate::CommitCursor() with whatever cursor is - // actually used. - virtual void SetCursor( - gfx::NativeCursor cursor, - NativeCursorManagerDelegate* delegate) = 0; - - // A request to set the visibility of the cursor. At minimum, implementer - // should call NativeCursorManagerDelegate::CommitVisibility() with whatever - // the visibility is. - virtual void SetVisibility( - bool visible, - NativeCursorManagerDelegate* delegate) = 0; - - // A request to set the cursor set. - virtual void SetCursorSet( - ui::CursorSetType cursor_set, - NativeCursorManagerDelegate* delegate) = 0; - - // A request to set whether mouse events are disabled. At minimum, - // implementer should call NativeCursorManagerDelegate:: - // CommitMouseEventsEnabled() with whether mouse events are actually enabled. - virtual void SetMouseEventsEnabled( - bool enabled, - NativeCursorManagerDelegate* delegate) = 0; -}; - -} // namespace wm - -#endif // UI_WM_CORE_NATIVE_CURSOR_MANAGER_H_
diff --git a/ui/wm/core/native_cursor_manager_delegate.h b/ui/wm/core/native_cursor_manager_delegate.h deleted file mode 100644 index 1393b2c..0000000 --- a/ui/wm/core/native_cursor_manager_delegate.h +++ /dev/null
@@ -1,33 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_CORE_NATIVE_CURSOR_MANAGER_DELEGATE_H_ -#define UI_WM_CORE_NATIVE_CURSOR_MANAGER_DELEGATE_H_ - -#include "ui/base/cursor/cursor.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/wm/wm_export.h" - -namespace wm { - -// The non-public interface that CursorManager exposes to its users. This -// gives accessors to all the current state, and mutators to all the current -// state. -class WM_EXPORT NativeCursorManagerDelegate { - public: - virtual ~NativeCursorManagerDelegate() {} - - // TODO(tdanderson): Possibly remove this interface. - virtual gfx::NativeCursor GetCursor() const = 0; - virtual bool IsCursorVisible() const = 0; - - virtual void CommitCursor(gfx::NativeCursor cursor) = 0; - virtual void CommitVisibility(bool visible) = 0; - virtual void CommitCursorSet(ui::CursorSetType cursor_set) = 0; - virtual void CommitMouseEventsEnabled(bool enabled) = 0; -}; - -} // namespace wm - -#endif // UI_WM_CORE_NATIVE_CURSOR_MANAGER_DELEGATE_H_
diff --git a/ui/wm/core/nested_accelerator_controller.cc b/ui/wm/core/nested_accelerator_controller.cc deleted file mode 100644 index e4ace4f..0000000 --- a/ui/wm/core/nested_accelerator_controller.cc +++ /dev/null
@@ -1,57 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/nested_accelerator_controller.h" - -#include "base/auto_reset.h" -#include "base/bind.h" -#include "base/run_loop.h" -#include "ui/wm/core/nested_accelerator_delegate.h" -#include "ui/wm/core/nested_accelerator_dispatcher.h" - -namespace wm { - -NestedAcceleratorController::NestedAcceleratorController( - NestedAcceleratorDelegate* delegate) - : dispatcher_delegate_(delegate) { - DCHECK(delegate); -} - -NestedAcceleratorController::~NestedAcceleratorController() { -} - -void NestedAcceleratorController::PrepareNestedLoopClosures( - base::MessagePumpDispatcher* nested_dispatcher, - base::Closure* run_closure, - base::Closure* quit_closure) { - scoped_ptr<NestedAcceleratorDispatcher> old_accelerator_dispatcher = - accelerator_dispatcher_.Pass(); - accelerator_dispatcher_ = NestedAcceleratorDispatcher::Create( - dispatcher_delegate_.get(), nested_dispatcher); - - scoped_ptr<base::RunLoop> run_loop = accelerator_dispatcher_->CreateRunLoop(); - *quit_closure = - base::Bind(&NestedAcceleratorController::QuitNestedMessageLoop, - base::Unretained(this), - run_loop->QuitClosure()); - *run_closure = base::Bind(&NestedAcceleratorController::RunNestedMessageLoop, - base::Unretained(this), - base::Passed(&run_loop), - base::Passed(&old_accelerator_dispatcher)); -} - -void NestedAcceleratorController::RunNestedMessageLoop( - scoped_ptr<base::RunLoop> run_loop, - scoped_ptr<NestedAcceleratorDispatcher> old_accelerator_dispatcher) { - run_loop->Run(); - accelerator_dispatcher_ = old_accelerator_dispatcher.Pass(); -} - -void NestedAcceleratorController::QuitNestedMessageLoop( - const base::Closure& quit_runloop) { - quit_runloop.Run(); - accelerator_dispatcher_.reset(); -} - -} // namespace wm
diff --git a/ui/wm/core/nested_accelerator_controller.h b/ui/wm/core/nested_accelerator_controller.h deleted file mode 100644 index 1eca937..0000000 --- a/ui/wm/core/nested_accelerator_controller.h +++ /dev/null
@@ -1,47 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_CORE_NESTED_ACCELERATOR_CONTROLLER_H_ -#define UI_WM_CORE_NESTED_ACCELERATOR_CONTROLLER_H_ - -#include "base/callback.h" -#include "base/message_loop/message_loop.h" -#include "ui/wm/public/dispatcher_client.h" -#include "ui/wm/wm_export.h" - -namespace wm { - -class NestedAcceleratorDelegate; -class NestedAcceleratorDispatcher; - -// Creates a dispatcher which wraps another dispatcher. -// The outer dispatcher runs first and performs ash specific handling. -// If it does not consume the event it forwards the event to the nested -// dispatcher. -class WM_EXPORT NestedAcceleratorController - : public aura::client::DispatcherClient { - public: - explicit NestedAcceleratorController(NestedAcceleratorDelegate* delegate); - virtual ~NestedAcceleratorController(); - - // aura::client::DispatcherClient: - virtual void PrepareNestedLoopClosures( - base::MessagePumpDispatcher* dispatcher, - base::Closure* run_closure, - base::Closure* quit_closure) override; - - private: - void RunNestedMessageLoop(scoped_ptr<base::RunLoop> run_loop, - scoped_ptr<NestedAcceleratorDispatcher> dispatcher); - void QuitNestedMessageLoop(const base::Closure& quit_runloop); - - scoped_ptr<NestedAcceleratorDispatcher> accelerator_dispatcher_; - scoped_ptr<NestedAcceleratorDelegate> dispatcher_delegate_; - - DISALLOW_COPY_AND_ASSIGN(NestedAcceleratorController); -}; - -} // namespace wm - -#endif // UI_WM_CORE_NESTED_ACCELERATOR_CONTROLLER_H_
diff --git a/ui/wm/core/nested_accelerator_controller_unittest.cc b/ui/wm/core/nested_accelerator_controller_unittest.cc deleted file mode 100644 index ce548d5..0000000 --- a/ui/wm/core/nested_accelerator_controller_unittest.cc +++ /dev/null
@@ -1,207 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/nested_accelerator_controller.h" - -#include "base/bind.h" -#include "base/event_types.h" -#include "base/message_loop/message_loop.h" -#include "ui/aura/test/aura_test_base.h" -#include "ui/aura/test/test_windows.h" -#include "ui/aura/window.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/base/accelerators/accelerator.h" -#include "ui/base/accelerators/accelerator.h" -#include "ui/base/accelerators/accelerator_manager.h" -#include "ui/events/event_constants.h" -#include "ui/events/event_utils.h" -#include "ui/events/platform/platform_event_dispatcher.h" -#include "ui/events/platform/platform_event_source.h" -#include "ui/events/platform/scoped_event_dispatcher.h" -#include "ui/wm/core/nested_accelerator_delegate.h" -#include "ui/wm/public/dispatcher_client.h" - -#if defined(USE_X11) -#include <X11/Xlib.h> -#include "ui/events/test/events_test_utils_x11.h" -#endif // USE_X11 - -namespace wm { -namespace test { - -namespace { - -class MockDispatcher : public ui::PlatformEventDispatcher { - public: - MockDispatcher() : num_key_events_dispatched_(0) {} - - int num_key_events_dispatched() { return num_key_events_dispatched_; } - - private: - // ui::PlatformEventDispatcher: - virtual bool CanDispatchEvent(const ui::PlatformEvent& event) override { - return true; - } - virtual uint32_t DispatchEvent(const ui::PlatformEvent& event) override { - if (ui::EventTypeFromNative(event) == ui::ET_KEY_RELEASED) - num_key_events_dispatched_++; - return ui::POST_DISPATCH_NONE; - } - - int num_key_events_dispatched_; - - DISALLOW_COPY_AND_ASSIGN(MockDispatcher); -}; - -class TestTarget : public ui::AcceleratorTarget { - public: - TestTarget() : accelerator_pressed_count_(0) {} - virtual ~TestTarget() {} - - int accelerator_pressed_count() const { return accelerator_pressed_count_; } - - // Overridden from ui::AcceleratorTarget: - virtual bool AcceleratorPressed(const ui::Accelerator& accelerator) override { - accelerator_pressed_count_++; - return true; - } - virtual bool CanHandleAccelerators() const override { return true; } - - private: - int accelerator_pressed_count_; - - DISALLOW_COPY_AND_ASSIGN(TestTarget); -}; - -void DispatchKeyReleaseA(aura::Window* root_window) { -// Sending both keydown and keyup is necessary here because the accelerator -// manager only checks a keyup event following a keydown event. See -// ShouldHandle() in ui/base/accelerators/accelerator_manager.cc for details. -#if defined(OS_WIN) - MSG native_event_down = {NULL, WM_KEYDOWN, ui::VKEY_A, 0}; - aura::WindowTreeHost* host = root_window->GetHost(); - host->PostNativeEvent(native_event_down); - MSG native_event_up = {NULL, WM_KEYUP, ui::VKEY_A, 0}; - host->PostNativeEvent(native_event_up); -#elif defined(USE_X11) - ui::ScopedXI2Event native_event; - native_event.InitKeyEvent(ui::ET_KEY_PRESSED, ui::VKEY_A, 0); - aura::WindowTreeHost* host = root_window->GetHost(); - host->PostNativeEvent(native_event); - native_event.InitKeyEvent(ui::ET_KEY_RELEASED, ui::VKEY_A, 0); - host->PostNativeEvent(native_event); -#endif - // Make sure the inner message-loop terminates after dispatching the events. - base::MessageLoop::current()->PostTask( - FROM_HERE, base::MessageLoop::current()->QuitClosure()); -} - -class MockNestedAcceleratorDelegate : public NestedAcceleratorDelegate { - public: - MockNestedAcceleratorDelegate() - : accelerator_manager_(new ui::AcceleratorManager) {} - virtual ~MockNestedAcceleratorDelegate() {} - - // NestedAcceleratorDelegate: - virtual Result ProcessAccelerator( - const ui::Accelerator& accelerator) override { - return accelerator_manager_->Process(accelerator) ? - RESULT_PROCESSED : RESULT_NOT_PROCESSED; - } - - void Register(const ui::Accelerator& accelerator, - ui::AcceleratorTarget* target) { - accelerator_manager_->Register( - accelerator, ui::AcceleratorManager::kNormalPriority, target); - } - - private: - scoped_ptr<ui::AcceleratorManager> accelerator_manager_; - - DISALLOW_COPY_AND_ASSIGN(MockNestedAcceleratorDelegate); -}; - -class NestedAcceleratorTest : public aura::test::AuraTestBase { - public: - NestedAcceleratorTest() {} - virtual ~NestedAcceleratorTest() {} - - virtual void SetUp() override { - AuraTestBase::SetUp(); - delegate_ = new MockNestedAcceleratorDelegate(); - nested_accelerator_controller_.reset( - new NestedAcceleratorController(delegate_)); - aura::client::SetDispatcherClient(root_window(), - nested_accelerator_controller_.get()); - } - - virtual void TearDown() override { - aura::client::SetDispatcherClient(root_window(), NULL); - AuraTestBase::TearDown(); - delegate_ = NULL; - nested_accelerator_controller_.reset(); - } - - MockNestedAcceleratorDelegate* delegate() { return delegate_; } - - private: - scoped_ptr<NestedAcceleratorController> nested_accelerator_controller_; - MockNestedAcceleratorDelegate* delegate_; - - DISALLOW_COPY_AND_ASSIGN(NestedAcceleratorTest); -}; - -} // namespace - -// Aura window above lock screen in z order. -// http://crbug.com/396494 -TEST_F(NestedAcceleratorTest, DISABLED_AssociatedWindowAboveLockScreen) { - // TODO(oshima|sadrul): remove when Win implements PES. - if (!ui::PlatformEventSource::GetInstance()) - return; - MockDispatcher inner_dispatcher; - scoped_ptr<aura::Window> mock_lock_container( - CreateNormalWindow(0, root_window(), NULL)); - aura::test::CreateTestWindowWithId(1, mock_lock_container.get()); - - scoped_ptr<aura::Window> associated_window( - CreateNormalWindow(2, root_window(), NULL)); - EXPECT_TRUE(aura::test::WindowIsAbove(associated_window.get(), - mock_lock_container.get())); - - DispatchKeyReleaseA(root_window()); - scoped_ptr<ui::ScopedEventDispatcher> override_dispatcher = - ui::PlatformEventSource::GetInstance()->OverrideDispatcher( - &inner_dispatcher); - aura::client::DispatcherRunLoop run_loop( - aura::client::GetDispatcherClient(root_window()), NULL); - run_loop.Run(); - EXPECT_EQ(1, inner_dispatcher.num_key_events_dispatched()); -} - -// Test that the nested dispatcher handles accelerators. -// http://crbug.com/396494 -TEST_F(NestedAcceleratorTest, DISABLED_AcceleratorsHandled) { - // TODO(oshima|sadrul): remove when Win implements PES. - if (!ui::PlatformEventSource::GetInstance()) - return; - MockDispatcher inner_dispatcher; - ui::Accelerator accelerator(ui::VKEY_A, ui::EF_NONE); - accelerator.set_type(ui::ET_KEY_RELEASED); - TestTarget target; - delegate()->Register(accelerator, &target); - - DispatchKeyReleaseA(root_window()); - scoped_ptr<ui::ScopedEventDispatcher> override_dispatcher = - ui::PlatformEventSource::GetInstance()->OverrideDispatcher( - &inner_dispatcher); - aura::client::DispatcherRunLoop run_loop( - aura::client::GetDispatcherClient(root_window()), NULL); - run_loop.Run(); - EXPECT_EQ(0, inner_dispatcher.num_key_events_dispatched()); - EXPECT_EQ(1, target.accelerator_pressed_count()); -} - -} // namespace test -} // namespace wm
diff --git a/ui/wm/core/nested_accelerator_delegate.h b/ui/wm/core/nested_accelerator_delegate.h deleted file mode 100644 index 4b13c0d..0000000 --- a/ui/wm/core/nested_accelerator_delegate.h +++ /dev/null
@@ -1,34 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_CORE_NESTED_ACCELERATOR_DELEGATE_H_ -#define UI_WM_CORE_NESTED_ACCELERATOR_DELEGATE_H_ - -namespace ui { -class Accelerator; -} - -namespace wm { - -// A delegate interface that implements the behavior of nested accelerator -// handling. -class NestedAcceleratorDelegate { - public: - enum Result { - RESULT_PROCESSED, - RESULT_NOT_PROCESSED, - // The key event should be ignored now and instead be reposted so that - // next event loop. - RESULT_PROCESS_LATER, - }; - - virtual ~NestedAcceleratorDelegate() {} - - // Attempts to process the |accelerator|. - virtual Result ProcessAccelerator(const ui::Accelerator& accelerator) = 0; -}; - -} // namespace wm - -#endif // UI_WM_CORE_NESTED_ACCELERATOR_DELEGATE_H_
diff --git a/ui/wm/core/nested_accelerator_dispatcher.cc b/ui/wm/core/nested_accelerator_dispatcher.cc deleted file mode 100644 index d37c93c..0000000 --- a/ui/wm/core/nested_accelerator_dispatcher.cc +++ /dev/null
@@ -1,21 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/nested_accelerator_dispatcher.h" - -#include "base/logging.h" -#include "ui/wm/core/nested_accelerator_delegate.h" - -namespace wm { - -NestedAcceleratorDispatcher::NestedAcceleratorDispatcher( - NestedAcceleratorDelegate* delegate) - : delegate_(delegate) { - DCHECK(delegate); -} - -NestedAcceleratorDispatcher::~NestedAcceleratorDispatcher() { -} - -} // namespace wm
diff --git a/ui/wm/core/nested_accelerator_dispatcher.h b/ui/wm/core/nested_accelerator_dispatcher.h deleted file mode 100644 index df5dd08..0000000 --- a/ui/wm/core/nested_accelerator_dispatcher.h +++ /dev/null
@@ -1,55 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_CORE_NESTED_ACCELERATOR_DISPATCHER_H_ -#define UI_WM_CORE_NESTED_ACCELERATOR_DISPATCHER_H_ - -#include "base/macros.h" -#include "base/memory/scoped_ptr.h" -#include "ui/wm/wm_export.h" - -namespace base { -class MessagePumpDispatcher; -class RunLoop; -} - -namespace ui { -class KeyEvent; -} - -namespace wm { - -class NestedAcceleratorDelegate; - -// Dispatcher for handling accelerators from menu. -// -// Wraps a nested dispatcher to which control is passed if no accelerator key -// has been pressed. If the nested dispatcher is NULL, then the control is -// passed back to the default dispatcher. -// TODO(pkotwicz): Add support for a |nested_dispatcher| which sends -// events to a system IME. -class WM_EXPORT NestedAcceleratorDispatcher { - public: - virtual ~NestedAcceleratorDispatcher(); - - static scoped_ptr<NestedAcceleratorDispatcher> Create( - NestedAcceleratorDelegate* dispatcher_delegate, - base::MessagePumpDispatcher* nested_dispatcher); - - // Creates a base::RunLoop object to run a nested message loop. - virtual scoped_ptr<base::RunLoop> CreateRunLoop() = 0; - - protected: - explicit NestedAcceleratorDispatcher(NestedAcceleratorDelegate* delegate); - - NestedAcceleratorDelegate* - delegate_; // Owned by NestedAcceleratorController. - - private: - DISALLOW_COPY_AND_ASSIGN(NestedAcceleratorDispatcher); -}; - -} // namespace wm - -#endif // UI_WM_CORE_NESTED_ACCELERATOR_DISPATCHER_H_
diff --git a/ui/wm/core/nested_accelerator_dispatcher_linux.cc b/ui/wm/core/nested_accelerator_dispatcher_linux.cc deleted file mode 100644 index 16a4efb..0000000 --- a/ui/wm/core/nested_accelerator_dispatcher_linux.cc +++ /dev/null
@@ -1,104 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/nested_accelerator_dispatcher.h" - -#include "base/memory/scoped_ptr.h" -#include "base/run_loop.h" -#include "ui/base/accelerators/accelerator.h" -#include "ui/events/event.h" -#include "ui/events/platform/platform_event_dispatcher.h" -#include "ui/events/platform/platform_event_source.h" -#include "ui/events/platform/scoped_event_dispatcher.h" -#include "ui/wm/core/accelerator_filter.h" -#include "ui/wm/core/nested_accelerator_delegate.h" - -#if defined(USE_X11) -#include <X11/Xlib.h> -#endif - -namespace wm { - -namespace { - -#if defined(USE_OZONE) -bool IsKeyEvent(const base::NativeEvent& native_event) { - const ui::KeyEvent* event = static_cast<const ui::KeyEvent*>(native_event); - return event->IsKeyEvent(); -} -#elif defined(USE_X11) -bool IsKeyEvent(const XEvent* xev) { - return xev->type == KeyPress || xev->type == KeyRelease; -} -#else -#error Unknown build platform: you should have either use_ozone or use_x11. -#endif - -scoped_ptr<ui::ScopedEventDispatcher> OverrideDispatcher( - ui::PlatformEventDispatcher* dispatcher) { - ui::PlatformEventSource* source = ui::PlatformEventSource::GetInstance(); - return source ? source->OverrideDispatcher(dispatcher) - : scoped_ptr<ui::ScopedEventDispatcher>(); -} - -} // namespace - -class NestedAcceleratorDispatcherLinux : public NestedAcceleratorDispatcher, - public ui::PlatformEventDispatcher { - public: - explicit NestedAcceleratorDispatcherLinux(NestedAcceleratorDelegate* delegate) - : NestedAcceleratorDispatcher(delegate), - restore_dispatcher_(OverrideDispatcher(this)) {} - - virtual ~NestedAcceleratorDispatcherLinux() {} - - private: - // AcceleratorDispatcher: - virtual scoped_ptr<base::RunLoop> CreateRunLoop() override { - return scoped_ptr<base::RunLoop>(new base::RunLoop()); - } - - // ui::PlatformEventDispatcher: - virtual bool CanDispatchEvent(const ui::PlatformEvent& event) override { - return true; - } - - virtual uint32_t DispatchEvent(const ui::PlatformEvent& event) override { - if (IsKeyEvent(event)) { - ui::KeyEvent key_event(event); - ui::Accelerator accelerator = CreateAcceleratorFromKeyEvent(key_event); - - switch (delegate_->ProcessAccelerator(accelerator)) { - case NestedAcceleratorDelegate::RESULT_PROCESS_LATER: -#if defined(USE_X11) - XPutBackEvent(event->xany.display, event); -#else - NOTIMPLEMENTED(); -#endif - return ui::POST_DISPATCH_NONE; - case NestedAcceleratorDelegate::RESULT_PROCESSED: - return ui::POST_DISPATCH_NONE; - case NestedAcceleratorDelegate::RESULT_NOT_PROCESSED: - break; - } - } - ui::PlatformEventDispatcher* prev = *restore_dispatcher_; - - uint32_t perform_default = ui::POST_DISPATCH_PERFORM_DEFAULT; - return prev ? prev->DispatchEvent(event) : perform_default; - } - - scoped_ptr<ui::ScopedEventDispatcher> restore_dispatcher_; - - DISALLOW_COPY_AND_ASSIGN(NestedAcceleratorDispatcherLinux); -}; - -scoped_ptr<NestedAcceleratorDispatcher> NestedAcceleratorDispatcher::Create( - NestedAcceleratorDelegate* delegate, - base::MessagePumpDispatcher* nested_dispatcher) { - return scoped_ptr<NestedAcceleratorDispatcher>( - new NestedAcceleratorDispatcherLinux(delegate)); -} - -} // namespace wm
diff --git a/ui/wm/core/nested_accelerator_dispatcher_win.cc b/ui/wm/core/nested_accelerator_dispatcher_win.cc deleted file mode 100644 index 5504d57..0000000 --- a/ui/wm/core/nested_accelerator_dispatcher_win.cc +++ /dev/null
@@ -1,74 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/nested_accelerator_dispatcher.h" - -#include "base/memory/scoped_ptr.h" -#include "base/message_loop/message_pump_dispatcher.h" -#include "base/run_loop.h" -#include "ui/base/accelerators/accelerator.h" -#include "ui/events/event.h" -#include "ui/wm/core/accelerator_filter.h" -#include "ui/wm/core/nested_accelerator_delegate.h" - -using base::MessagePumpDispatcher; - -namespace wm { - -namespace { - -bool IsKeyEvent(const MSG& msg) { - return msg.message == WM_KEYDOWN || msg.message == WM_SYSKEYDOWN || - msg.message == WM_KEYUP || msg.message == WM_SYSKEYUP; -} - -} // namespace - -class NestedAcceleratorDispatcherWin : public NestedAcceleratorDispatcher, - public MessagePumpDispatcher { - public: - NestedAcceleratorDispatcherWin(NestedAcceleratorDelegate* delegate, - MessagePumpDispatcher* nested) - : NestedAcceleratorDispatcher(delegate), nested_dispatcher_(nested) {} - virtual ~NestedAcceleratorDispatcherWin() {} - - private: - // NestedAcceleratorDispatcher: - virtual scoped_ptr<base::RunLoop> CreateRunLoop() override { - return scoped_ptr<base::RunLoop>(new base::RunLoop(this)); - } - - // MessagePumpDispatcher: - virtual uint32_t Dispatch(const MSG& event) override { - if (IsKeyEvent(event)) { - ui::KeyEvent key_event(event); - ui::Accelerator accelerator = CreateAcceleratorFromKeyEvent(key_event); - - switch (delegate_->ProcessAccelerator(accelerator)) { - case NestedAcceleratorDelegate::RESULT_PROCESS_LATER: - return POST_DISPATCH_QUIT_LOOP; - case NestedAcceleratorDelegate::RESULT_PROCESSED: - return POST_DISPATCH_NONE; - case NestedAcceleratorDelegate::RESULT_NOT_PROCESSED: - break; - } - } - - return nested_dispatcher_ ? nested_dispatcher_->Dispatch(event) - : POST_DISPATCH_PERFORM_DEFAULT; - } - - MessagePumpDispatcher* nested_dispatcher_; - - DISALLOW_COPY_AND_ASSIGN(NestedAcceleratorDispatcherWin); -}; - -scoped_ptr<NestedAcceleratorDispatcher> NestedAcceleratorDispatcher::Create( - NestedAcceleratorDelegate* delegate, - MessagePumpDispatcher* nested_dispatcher) { - return scoped_ptr<NestedAcceleratorDispatcher>( - new NestedAcceleratorDispatcherWin(delegate, nested_dispatcher)); -} - -} // namespace wm
diff --git a/ui/wm/core/shadow.cc b/ui/wm/core/shadow.cc deleted file mode 100644 index 4b62122..0000000 --- a/ui/wm/core/shadow.cc +++ /dev/null
@@ -1,203 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/shadow.h" - -#include "third_party/skia/include/core/SkBitmap.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/compositor/layer.h" -#include "ui/compositor/scoped_layer_animation_settings.h" -#include "ui/resources/grit/ui_resources.h" - -namespace { - -// Shadow opacity for different styles. -const float kActiveShadowOpacity = 1.0f; -const float kInactiveShadowOpacity = 0.2f; -const float kSmallShadowOpacity = 1.0f; - -// Shadow aperture for different styles. -// Note that this may be greater than interior inset to allow shadows with -// curved corners that extend inwards beyond a window's borders. -const int kActiveInteriorAperture = 134; -const int kInactiveInteriorAperture = 134; -const int kSmallInteriorAperture = 9; - -// Interior inset for different styles. -const int kActiveInteriorInset = 64; -const int kInactiveInteriorInset = 64; -const int kSmallInteriorInset = 4; - -// Duration for opacity animation in milliseconds. -const int kShadowAnimationDurationMs = 100; - -float GetOpacityForStyle(wm::Shadow::Style style) { - switch (style) { - case wm::Shadow::STYLE_ACTIVE: - return kActiveShadowOpacity; - case wm::Shadow::STYLE_INACTIVE: - return kInactiveShadowOpacity; - case wm::Shadow::STYLE_SMALL: - return kSmallShadowOpacity; - } - return 1.0f; -} - -int GetShadowApertureForStyle(wm::Shadow::Style style) { - switch (style) { - case wm::Shadow::STYLE_ACTIVE: - return kActiveInteriorAperture; - case wm::Shadow::STYLE_INACTIVE: - return kInactiveInteriorAperture; - case wm::Shadow::STYLE_SMALL: - return kSmallInteriorAperture; - } - return 0; -} - -int GetInteriorInsetForStyle(wm::Shadow::Style style) { - switch (style) { - case wm::Shadow::STYLE_ACTIVE: - return kActiveInteriorInset; - case wm::Shadow::STYLE_INACTIVE: - return kInactiveInteriorInset; - case wm::Shadow::STYLE_SMALL: - return kSmallInteriorInset; - } - return 0; -} - -} // namespace - -namespace wm { - -Shadow::Shadow() : style_(STYLE_ACTIVE), interior_inset_(0) { -} - -Shadow::~Shadow() { -} - -void Shadow::Init(Style style) { - style_ = style; - - layer_.reset(new ui::Layer(ui::LAYER_NOT_DRAWN)); - shadow_layer_.reset(new ui::Layer(ui::LAYER_NINE_PATCH)); - layer()->Add(shadow_layer_.get()); - - UpdateImagesForStyle(); - shadow_layer_->set_name("Shadow"); - shadow_layer_->SetVisible(true); - shadow_layer_->SetFillsBoundsOpaquely(false); - shadow_layer_->SetOpacity(GetOpacityForStyle(style_)); -} - -void Shadow::SetContentBounds(const gfx::Rect& content_bounds) { - content_bounds_ = content_bounds; - UpdateLayerBounds(); -} - -void Shadow::SetStyle(Style style) { - if (style_ == style) - return; - - Style old_style = style_; - style_ = style; - - // Stop waiting for any as yet unfinished implicit animations. - StopObservingImplicitAnimations(); - - // If we're switching to or from the small style, don't bother with - // animations. - if (style == STYLE_SMALL || old_style == STYLE_SMALL) { - UpdateImagesForStyle(); - shadow_layer_->SetOpacity(GetOpacityForStyle(style)); - return; - } - - // If we're becoming active, switch images now. Because the inactive image - // has a very low opacity the switch isn't noticeable and this approach - // allows us to use only a single set of shadow images at a time. - if (style == STYLE_ACTIVE) { - UpdateImagesForStyle(); - // Opacity was baked into inactive image, start opacity low to match. - shadow_layer_->SetOpacity(kInactiveShadowOpacity); - } - - { - // Property sets within this scope will be implicitly animated. - ui::ScopedLayerAnimationSettings settings(shadow_layer_->GetAnimator()); - settings.AddObserver(this); - settings.SetTransitionDuration( - base::TimeDelta::FromMilliseconds(kShadowAnimationDurationMs)); - switch (style_) { - case STYLE_ACTIVE: - shadow_layer_->SetOpacity(kActiveShadowOpacity); - break; - case STYLE_INACTIVE: - shadow_layer_->SetOpacity(kInactiveShadowOpacity); - break; - default: - NOTREACHED() << "Unhandled style " << style_; - break; - } - } -} - -void Shadow::OnImplicitAnimationsCompleted() { - // If we just finished going inactive, switch images. This doesn't cause - // a visual pop because the inactive image opacity is so low. - if (style_ == STYLE_INACTIVE) { - UpdateImagesForStyle(); - // Opacity is baked into inactive image, so set fully opaque. - shadow_layer_->SetOpacity(1.0f); - } -} - -void Shadow::UpdateImagesForStyle() { - ResourceBundle& res = ResourceBundle::GetSharedInstance(); - gfx::Image image; - switch (style_) { - case STYLE_ACTIVE: - image = res.GetImageNamed(IDR_AURA_SHADOW_ACTIVE); - break; - case STYLE_INACTIVE: - image = res.GetImageNamed(IDR_AURA_SHADOW_INACTIVE); - break; - case STYLE_SMALL: - image = res.GetImageNamed(IDR_WINDOW_BUBBLE_SHADOW_SMALL); - break; - default: - NOTREACHED() << "Unhandled style " << style_; - break; - } - - shadow_layer_->UpdateNinePatchLayerBitmap(image.AsBitmap()); - image_size_ = image.Size(); - interior_inset_ = GetInteriorInsetForStyle(style_); - - // Image sizes may have changed. - UpdateLayerBounds(); -} - -void Shadow::UpdateLayerBounds() { - // Update bounds based on content bounds and interior inset. - gfx::Rect layer_bounds = content_bounds_; - layer_bounds.Inset(-interior_inset_, -interior_inset_); - layer()->SetBounds(layer_bounds); - shadow_layer_->SetBounds(gfx::Rect(layer_bounds.size())); - - // Update the shadow aperture and border for style. Note that border is in - // layer space and it cannot exceed the bounds of the layer. - int aperture = GetShadowApertureForStyle(style_); - int aperture_x = std::min(aperture, layer_bounds.width() / 2); - int aperture_y = std::min(aperture, layer_bounds.height() / 2); - shadow_layer_->UpdateNinePatchLayerAperture( - gfx::Rect(aperture_x, aperture_y, - image_size_.width() - aperture_x * 2, - image_size_.height() - aperture_y * 2)); - shadow_layer_->UpdateNinePatchLayerBorder( - gfx::Rect(aperture_x, aperture_y, aperture_x * 2, aperture_y * 2)); -} - -} // namespace wm
diff --git a/ui/wm/core/shadow.h b/ui/wm/core/shadow.h deleted file mode 100644 index 19f5972..0000000 --- a/ui/wm/core/shadow.h +++ /dev/null
@@ -1,92 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_CORE_SHADOW_H_ -#define UI_WM_CORE_SHADOW_H_ - -#include "base/basictypes.h" -#include "base/memory/scoped_ptr.h" -#include "ui/compositor/layer_animation_observer.h" -#include "ui/gfx/rect.h" -#include "ui/wm/wm_export.h" - -namespace ui { -class Layer; -} // namespace ui - -namespace wm { - -// Simple class that draws a drop shadow around content at given bounds. -class WM_EXPORT Shadow : public ui::ImplicitAnimationObserver { - public: - enum Style { - // Active windows have more opaque shadows, shifted down to make the window - // appear "higher". - STYLE_ACTIVE, - - // Inactive windows have less opaque shadows. - STYLE_INACTIVE, - - // Small windows like tooltips and context menus have lighter, smaller - // shadows. - STYLE_SMALL, - }; - - Shadow(); - virtual ~Shadow(); - - void Init(Style style); - - // Returns |layer_.get()|. This is exposed so it can be added to the same - // layer as the content and stacked below it. SetContentBounds() should be - // used to adjust the shadow's size and position (rather than applying - // transformations to this layer). - ui::Layer* layer() const { return layer_.get(); } - - const gfx::Rect& content_bounds() const { return content_bounds_; } - Style style() const { return style_; } - - // Moves and resizes the shadow layer to frame |content_bounds|. - void SetContentBounds(const gfx::Rect& content_bounds); - - // Sets the shadow's style, animating opacity as necessary. - void SetStyle(Style style); - - // ui::ImplicitAnimationObserver overrides: - virtual void OnImplicitAnimationsCompleted() override; - - private: - // Updates the shadow images to the current |style_|. - void UpdateImagesForStyle(); - - // Updates the shadow layer bounds based on the inteior inset and the current - // |content_bounds_|. - void UpdateLayerBounds(); - - // The current style, set when the transition animation starts. - Style style_; - - // The parent layer of the shadow layer. It serves as a container accessible - // from the outside to control the visibility of the shadow. - scoped_ptr<ui::Layer> layer_; - - // The actual shadow layer corresponding to a cc::NinePatchLayer. - scoped_ptr<ui::Layer> shadow_layer_; - - // Size of the current shadow image. - gfx::Size image_size_; - - // Bounds of the content that the shadow encloses. - gfx::Rect content_bounds_; - - // The interior inset of the shadow images. The content bounds of the image - // grid should be set to |content_bounds_| inset by this amount. - int interior_inset_; - - DISALLOW_COPY_AND_ASSIGN(Shadow); -}; - -} // namespace wm - -#endif // UI_WM_CORE_SHADOW_H_
diff --git a/ui/wm/core/shadow_controller.cc b/ui/wm/core/shadow_controller.cc deleted file mode 100644 index abd33ad..0000000 --- a/ui/wm/core/shadow_controller.cc +++ /dev/null
@@ -1,285 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/shadow_controller.h" - -#include <utility> - -#include "base/command_line.h" -#include "base/logging.h" -#include "base/memory/linked_ptr.h" -#include "base/scoped_observer.h" -#include "ui/aura/env.h" -#include "ui/aura/env_observer.h" -#include "ui/aura/window.h" -#include "ui/aura/window_observer.h" -#include "ui/compositor/layer.h" -#include "ui/wm/core/shadow.h" -#include "ui/wm/core/shadow_types.h" -#include "ui/wm/core/window_util.h" -#include "ui/wm/public/activation_client.h" - -using std::make_pair; - -namespace wm { - -namespace { - -ShadowType GetShadowTypeFromWindow(aura::Window* window) { - switch (window->type()) { - case ui::wm::WINDOW_TYPE_NORMAL: - case ui::wm::WINDOW_TYPE_PANEL: - case ui::wm::WINDOW_TYPE_MENU: - case ui::wm::WINDOW_TYPE_TOOLTIP: - return SHADOW_TYPE_RECTANGULAR; - default: - break; - } - return SHADOW_TYPE_NONE; -} - -bool ShouldUseSmallShadowForWindow(aura::Window* window) { - switch (window->type()) { - case ui::wm::WINDOW_TYPE_MENU: - case ui::wm::WINDOW_TYPE_TOOLTIP: - return true; - default: - break; - } - return false; -} - -bool IsShadowAlwaysActive(aura::Window* window) { - return GetShadowType(window) == SHADOW_TYPE_RECTANGULAR_ALWAYS_ACTIVE; -} - -Shadow::Style GetShadowStyleForWindow(aura::Window* window) { - return ShouldUseSmallShadowForWindow(window) ? Shadow::STYLE_SMALL : - ((IsActiveWindow(window) || IsShadowAlwaysActive(window)) ? - Shadow::STYLE_ACTIVE : Shadow::STYLE_INACTIVE); -} - -// Returns the shadow style to be applied to |losing_active| when it is losing -// active to |gaining_active|. |gaining_active| may be of a type that hides when -// inactive, and as such we do not want to render |losing_active| as inactive. -Shadow::Style GetShadowStyleForWindowLosingActive( - aura::Window* losing_active, - aura::Window* gaining_active) { - if (IsShadowAlwaysActive(losing_active)) - return Shadow::STYLE_ACTIVE; - - if (gaining_active && aura::client::GetHideOnDeactivate(gaining_active)) { - aura::Window::Windows::const_iterator it = - std::find(GetTransientChildren(losing_active).begin(), - GetTransientChildren(losing_active).end(), - gaining_active); - if (it != GetTransientChildren(losing_active).end()) - return Shadow::STYLE_ACTIVE; - } - return Shadow::STYLE_INACTIVE; -} - -} // namespace - -// ShadowController::Impl ------------------------------------------------------ - -// Real implementation of the ShadowController. ShadowController observes -// ActivationChangeObserver, which are per ActivationClient, where as there is -// only a single Impl (as it observes all window creation by way of an -// EnvObserver). -class ShadowController::Impl : - public aura::EnvObserver, - public aura::WindowObserver, - public base::RefCounted<Impl> { - public: - // Returns the singleton instance, destroyed when there are no more refs. - static Impl* GetInstance(); - - // aura::EnvObserver override: - virtual void OnWindowInitialized(aura::Window* window) override; - - // aura::WindowObserver overrides: - virtual void OnWindowPropertyChanged( - aura::Window* window, const void* key, intptr_t old) override; - virtual void OnWindowBoundsChanged( - aura::Window* window, - const gfx::Rect& old_bounds, - const gfx::Rect& new_bounds) override; - virtual void OnWindowDestroyed(aura::Window* window) override; - - private: - friend class base::RefCounted<Impl>; - friend class ShadowController; - friend class ShadowController::TestApi; - - typedef std::map<aura::Window*, linked_ptr<Shadow> > WindowShadowMap; - - Impl(); - virtual ~Impl(); - - // Forwarded from ShadowController. - void OnWindowActivated(aura::Window* gained_active, - aura::Window* lost_active); - - // Checks if |window| is visible and contains a property requesting a shadow. - bool ShouldShowShadowForWindow(aura::Window* window) const; - - // Returns |window|'s shadow from |window_shadows_|, or NULL if no shadow - // exists. - Shadow* GetShadowForWindow(aura::Window* window); - - // Updates the shadow styles for windows when activation changes. - void HandleWindowActivationChange(aura::Window* gaining_active, - aura::Window* losing_active); - - // Shows or hides |window|'s shadow as needed (creating the shadow if - // necessary). - void HandlePossibleShadowVisibilityChange(aura::Window* window); - - // Creates a new shadow for |window| and stores it in |window_shadows_|. The - // shadow's bounds are initialized and it is added to the window's layer. - void CreateShadowForWindow(aura::Window* window); - - WindowShadowMap window_shadows_; - - ScopedObserver<aura::Window, aura::WindowObserver> observer_manager_; - - static Impl* instance_; - - DISALLOW_COPY_AND_ASSIGN(Impl); -}; - -// static -ShadowController::Impl* ShadowController::Impl::instance_ = NULL; - -// static -ShadowController::Impl* ShadowController::Impl::GetInstance() { - if (!instance_) - instance_ = new Impl(); - return instance_; -} - -void ShadowController::Impl::OnWindowInitialized(aura::Window* window) { - observer_manager_.Add(window); - SetShadowType(window, GetShadowTypeFromWindow(window)); - HandlePossibleShadowVisibilityChange(window); -} - -void ShadowController::Impl::OnWindowPropertyChanged(aura::Window* window, - const void* key, - intptr_t old) { - if (key == kShadowTypeKey) { - HandlePossibleShadowVisibilityChange(window); - return; - } -} - -void ShadowController::Impl::OnWindowBoundsChanged( - aura::Window* window, - const gfx::Rect& old_bounds, - const gfx::Rect& new_bounds) { - Shadow* shadow = GetShadowForWindow(window); - if (shadow) - shadow->SetContentBounds(gfx::Rect(new_bounds.size())); -} - -void ShadowController::Impl::OnWindowDestroyed(aura::Window* window) { - window_shadows_.erase(window); - observer_manager_.Remove(window); -} - -void ShadowController::Impl::OnWindowActivated(aura::Window* gained_active, - aura::Window* lost_active) { - if (gained_active) { - Shadow* shadow = GetShadowForWindow(gained_active); - if (shadow && !ShouldUseSmallShadowForWindow(gained_active)) - shadow->SetStyle(Shadow::STYLE_ACTIVE); - } - if (lost_active) { - Shadow* shadow = GetShadowForWindow(lost_active); - if (shadow && !ShouldUseSmallShadowForWindow(lost_active)) { - shadow->SetStyle(GetShadowStyleForWindowLosingActive(lost_active, - gained_active)); - } - } -} - -bool ShadowController::Impl::ShouldShowShadowForWindow( - aura::Window* window) const { - const ShadowType type = GetShadowType(window); - switch (type) { - case SHADOW_TYPE_NONE: - return false; - case SHADOW_TYPE_RECTANGULAR: - case SHADOW_TYPE_RECTANGULAR_ALWAYS_ACTIVE: - return true; - default: - NOTREACHED() << "Unknown shadow type " << type; - return false; - } -} - -Shadow* ShadowController::Impl::GetShadowForWindow(aura::Window* window) { - WindowShadowMap::const_iterator it = window_shadows_.find(window); - return it != window_shadows_.end() ? it->second.get() : NULL; -} - -void ShadowController::Impl::HandlePossibleShadowVisibilityChange( - aura::Window* window) { - const bool should_show = ShouldShowShadowForWindow(window); - Shadow* shadow = GetShadowForWindow(window); - if (shadow) { - shadow->SetStyle(GetShadowStyleForWindow(window)); - shadow->layer()->SetVisible(should_show); - } else if (should_show && !shadow) { - CreateShadowForWindow(window); - } -} - -void ShadowController::Impl::CreateShadowForWindow(aura::Window* window) { - linked_ptr<Shadow> shadow(new Shadow()); - window_shadows_.insert(make_pair(window, shadow)); - shadow->Init(GetShadowStyleForWindow(window)); - shadow->SetContentBounds(gfx::Rect(window->bounds().size())); - shadow->layer()->SetVisible(ShouldShowShadowForWindow(window)); - window->layer()->Add(shadow->layer()); -} - -ShadowController::Impl::Impl() - : observer_manager_(this) { - aura::Env::GetInstance()->AddObserver(this); -} - -ShadowController::Impl::~Impl() { - DCHECK_EQ(instance_, this); - aura::Env::GetInstance()->RemoveObserver(this); - instance_ = NULL; -} - -// ShadowController ------------------------------------------------------------ - -ShadowController::ShadowController( - aura::client::ActivationClient* activation_client) - : activation_client_(activation_client), - impl_(Impl::GetInstance()) { - // Watch for window activation changes. - activation_client_->AddObserver(this); -} - -ShadowController::~ShadowController() { - activation_client_->RemoveObserver(this); -} - -void ShadowController::OnWindowActivated(aura::Window* gained_active, - aura::Window* lost_active) { - impl_->OnWindowActivated(gained_active, lost_active); -} - -// ShadowController::TestApi --------------------------------------------------- - -Shadow* ShadowController::TestApi::GetShadowForWindow(aura::Window* window) { - return controller_->impl_->GetShadowForWindow(window); -} - -} // namespace wm
diff --git a/ui/wm/core/shadow_controller.h b/ui/wm/core/shadow_controller.h deleted file mode 100644 index 9deeda6..0000000 --- a/ui/wm/core/shadow_controller.h +++ /dev/null
@@ -1,69 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_CORE_SHADOW_CONTROLLER_H_ -#define UI_WM_CORE_SHADOW_CONTROLLER_H_ - -#include <map> - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/memory/ref_counted.h" -#include "ui/wm/public/activation_change_observer.h" -#include "ui/wm/wm_export.h" - -namespace aura { -class Window; -namespace client { -class ActivationClient; -} -} -namespace gfx { -class Rect; -} - -namespace wm { - -class Shadow; - -// ShadowController observes changes to windows and creates and updates drop -// shadows as needed. ShadowController itself is light weight and per -// ActivationClient. ShadowController delegates to its implementation class, -// which observes all window creation. -class WM_EXPORT ShadowController : - public aura::client::ActivationChangeObserver { - public: - class WM_EXPORT TestApi { - public: - explicit TestApi(ShadowController* controller) : controller_(controller) {} - ~TestApi() {} - - Shadow* GetShadowForWindow(aura::Window* window); - - private: - ShadowController* controller_; // not owned - - DISALLOW_COPY_AND_ASSIGN(TestApi); - }; - - explicit ShadowController(aura::client::ActivationClient* activation_client); - virtual ~ShadowController(); - - // aura::client::ActivationChangeObserver overrides: - virtual void OnWindowActivated(aura::Window* gained_active, - aura::Window* lost_active) override; - - private: - class Impl; - - aura::client::ActivationClient* activation_client_; - - scoped_refptr<Impl> impl_; - - DISALLOW_COPY_AND_ASSIGN(ShadowController); -}; - -} // namespace wm - -#endif // UI_WM_CORE_SHADOW_CONTROLLER_H_
diff --git a/ui/wm/core/shadow_controller_unittest.cc b/ui/wm/core/shadow_controller_unittest.cc deleted file mode 100644 index 1b1aa18..0000000 --- a/ui/wm/core/shadow_controller_unittest.cc +++ /dev/null
@@ -1,273 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/shadow_controller.h" - -#include <algorithm> -#include <vector> - -#include "base/memory/scoped_ptr.h" -#include "ui/aura/client/window_tree_client.h" -#include "ui/aura/test/aura_test_base.h" -#include "ui/aura/window.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/compositor/layer.h" -#include "ui/wm/core/default_activation_client.h" -#include "ui/wm/core/shadow.h" -#include "ui/wm/core/shadow_types.h" -#include "ui/wm/core/window_util.h" -#include "ui/wm/core/wm_state.h" -#include "ui/wm/public/activation_client.h" - -namespace wm { - -class ShadowControllerTest : public aura::test::AuraTestBase { - public: - ShadowControllerTest() {} - virtual ~ShadowControllerTest() {} - - virtual void SetUp() override { - wm_state_.reset(new wm::WMState); - AuraTestBase::SetUp(); - new wm::DefaultActivationClient(root_window()); - aura::client::ActivationClient* activation_client = - aura::client::GetActivationClient(root_window()); - shadow_controller_.reset(new ShadowController(activation_client)); - } - virtual void TearDown() override { - shadow_controller_.reset(); - AuraTestBase::TearDown(); - wm_state_.reset(); - } - - protected: - ShadowController* shadow_controller() { return shadow_controller_.get(); } - - void ActivateWindow(aura::Window* window) { - DCHECK(window); - DCHECK(window->GetRootWindow()); - aura::client::GetActivationClient(window->GetRootWindow())->ActivateWindow( - window); - } - - private: - scoped_ptr<ShadowController> shadow_controller_; - scoped_ptr<wm::WMState> wm_state_; - - DISALLOW_COPY_AND_ASSIGN(ShadowControllerTest); -}; - -// Tests that various methods in Window update the Shadow object as expected. -TEST_F(ShadowControllerTest, Shadow) { - scoped_ptr<aura::Window> window(new aura::Window(NULL)); - window->SetType(ui::wm::WINDOW_TYPE_NORMAL); - window->Init(aura::WINDOW_LAYER_TEXTURED); - ParentWindow(window.get()); - - // We should create the shadow before the window is visible (the shadow's - // layer won't get drawn yet since it's a child of the window's layer). - ShadowController::TestApi api(shadow_controller()); - const Shadow* shadow = api.GetShadowForWindow(window.get()); - ASSERT_TRUE(shadow != NULL); - EXPECT_TRUE(shadow->layer()->visible()); - - // The shadow should remain visible after window visibility changes. - window->Show(); - EXPECT_TRUE(shadow->layer()->visible()); - window->Hide(); - EXPECT_TRUE(shadow->layer()->visible()); - - // If the shadow is disabled, it should be hidden. - SetShadowType(window.get(), SHADOW_TYPE_NONE); - window->Show(); - EXPECT_FALSE(shadow->layer()->visible()); - SetShadowType(window.get(), SHADOW_TYPE_RECTANGULAR); - EXPECT_TRUE(shadow->layer()->visible()); - - // The shadow's layer should be a child of the window's layer. - EXPECT_EQ(window->layer(), shadow->layer()->parent()); - - window->parent()->RemoveChild(window.get()); - aura::Window* window_ptr = window.get(); - window.reset(); - EXPECT_TRUE(api.GetShadowForWindow(window_ptr) == NULL); -} - -// Tests that the window's shadow's bounds are updated correctly. -TEST_F(ShadowControllerTest, ShadowBounds) { - scoped_ptr<aura::Window> window(new aura::Window(NULL)); - window->SetType(ui::wm::WINDOW_TYPE_NORMAL); - window->Init(aura::WINDOW_LAYER_TEXTURED); - ParentWindow(window.get()); - window->Show(); - - const gfx::Rect kOldBounds(20, 30, 400, 300); - window->SetBounds(kOldBounds); - - // When the shadow is first created, it should use the window's size (but - // remain at the origin, since it's a child of the window's layer). - SetShadowType(window.get(), SHADOW_TYPE_RECTANGULAR); - ShadowController::TestApi api(shadow_controller()); - const Shadow* shadow = api.GetShadowForWindow(window.get()); - ASSERT_TRUE(shadow != NULL); - EXPECT_EQ(gfx::Rect(kOldBounds.size()).ToString(), - shadow->content_bounds().ToString()); - - // When we change the window's bounds, the shadow's should be updated too. - gfx::Rect kNewBounds(50, 60, 500, 400); - window->SetBounds(kNewBounds); - EXPECT_EQ(gfx::Rect(kNewBounds.size()).ToString(), - shadow->content_bounds().ToString()); -} - -// Tests that activating a window changes the shadow style. -TEST_F(ShadowControllerTest, ShadowStyle) { - ShadowController::TestApi api(shadow_controller()); - - scoped_ptr<aura::Window> window1(new aura::Window(NULL)); - window1->SetType(ui::wm::WINDOW_TYPE_NORMAL); - window1->Init(aura::WINDOW_LAYER_TEXTURED); - ParentWindow(window1.get()); - window1->SetBounds(gfx::Rect(10, 20, 300, 400)); - window1->Show(); - ActivateWindow(window1.get()); - - // window1 is active, so style should have active appearance. - Shadow* shadow1 = api.GetShadowForWindow(window1.get()); - ASSERT_TRUE(shadow1 != NULL); - EXPECT_EQ(Shadow::STYLE_ACTIVE, shadow1->style()); - - // Create another window and activate it. - scoped_ptr<aura::Window> window2(new aura::Window(NULL)); - window2->SetType(ui::wm::WINDOW_TYPE_NORMAL); - window2->Init(aura::WINDOW_LAYER_TEXTURED); - ParentWindow(window2.get()); - window2->SetBounds(gfx::Rect(11, 21, 301, 401)); - window2->Show(); - ActivateWindow(window2.get()); - - // window1 is now inactive, so shadow should go inactive. - Shadow* shadow2 = api.GetShadowForWindow(window2.get()); - ASSERT_TRUE(shadow2 != NULL); - EXPECT_EQ(Shadow::STYLE_INACTIVE, shadow1->style()); - EXPECT_EQ(Shadow::STYLE_ACTIVE, shadow2->style()); -} - -// Tests that we use smaller shadows for tooltips and menus. -TEST_F(ShadowControllerTest, SmallShadowsForTooltipsAndMenus) { - ShadowController::TestApi api(shadow_controller()); - - scoped_ptr<aura::Window> tooltip_window(new aura::Window(NULL)); - tooltip_window->SetType(ui::wm::WINDOW_TYPE_TOOLTIP); - tooltip_window->Init(aura::WINDOW_LAYER_TEXTURED); - ParentWindow(tooltip_window.get()); - tooltip_window->SetBounds(gfx::Rect(10, 20, 300, 400)); - tooltip_window->Show(); - - Shadow* tooltip_shadow = api.GetShadowForWindow(tooltip_window.get()); - ASSERT_TRUE(tooltip_shadow != NULL); - EXPECT_EQ(Shadow::STYLE_SMALL, tooltip_shadow->style()); - - scoped_ptr<aura::Window> menu_window(new aura::Window(NULL)); - menu_window->SetType(ui::wm::WINDOW_TYPE_MENU); - menu_window->Init(aura::WINDOW_LAYER_TEXTURED); - ParentWindow(menu_window.get()); - menu_window->SetBounds(gfx::Rect(10, 20, 300, 400)); - menu_window->Show(); - - Shadow* menu_shadow = api.GetShadowForWindow(tooltip_window.get()); - ASSERT_TRUE(menu_shadow != NULL); - EXPECT_EQ(Shadow::STYLE_SMALL, menu_shadow->style()); -} - -// http://crbug.com/120210 - transient parents of certain types of transients -// should not lose their shadow when they lose activation to the transient. -TEST_F(ShadowControllerTest, TransientParentKeepsActiveShadow) { - ShadowController::TestApi api(shadow_controller()); - - scoped_ptr<aura::Window> window1(new aura::Window(NULL)); - window1->SetType(ui::wm::WINDOW_TYPE_NORMAL); - window1->Init(aura::WINDOW_LAYER_TEXTURED); - ParentWindow(window1.get()); - window1->SetBounds(gfx::Rect(10, 20, 300, 400)); - window1->Show(); - ActivateWindow(window1.get()); - - // window1 is active, so style should have active appearance. - Shadow* shadow1 = api.GetShadowForWindow(window1.get()); - ASSERT_TRUE(shadow1 != NULL); - EXPECT_EQ(Shadow::STYLE_ACTIVE, shadow1->style()); - - // Create a window that is transient to window1, and that has the 'hide on - // deactivate' property set. Upon activation, window1 should still have an - // active shadow. - scoped_ptr<aura::Window> window2(new aura::Window(NULL)); - window2->SetType(ui::wm::WINDOW_TYPE_NORMAL); - window2->Init(aura::WINDOW_LAYER_TEXTURED); - ParentWindow(window2.get()); - window2->SetBounds(gfx::Rect(11, 21, 301, 401)); - AddTransientChild(window1.get(), window2.get()); - aura::client::SetHideOnDeactivate(window2.get(), true); - window2->Show(); - ActivateWindow(window2.get()); - - // window1 is now inactive, but its shadow should still appear active. - EXPECT_EQ(Shadow::STYLE_ACTIVE, shadow1->style()); -} - -TEST_F(ShadowControllerTest, AlwaysActive) { - ShadowController::TestApi api(shadow_controller()); - - scoped_ptr<aura::Window> window1(new aura::Window(NULL)); - window1->SetType(ui::wm::WINDOW_TYPE_NORMAL); - window1->Init(aura::WINDOW_LAYER_TEXTURED); - ParentWindow(window1.get()); - window1->SetBounds(gfx::Rect(10, 20, 300, 400)); - SetShadowType(window1.get(), SHADOW_TYPE_RECTANGULAR_ALWAYS_ACTIVE); - window1->Show(); - - // Showing the window with SHADOW_TYPE_RECTANGULAR_ALWAYS_ACTIVE should - // have active shadow. - EXPECT_EQ(Shadow::STYLE_ACTIVE, - api.GetShadowForWindow(window1.get())->style()); - - scoped_ptr<aura::Window> window2(new aura::Window(NULL)); - window2->SetType(ui::wm::WINDOW_TYPE_NORMAL); - window2->Init(aura::WINDOW_LAYER_TEXTURED); - ParentWindow(window2.get()); - window2->SetBounds(gfx::Rect(11, 21, 301, 401)); - window2->Show(); - - // Setting SHADOW_TYPE_RECTANGULAR_ALWAYS_ACTIVE to the visible window - // should set the active shadow. - EXPECT_EQ(Shadow::STYLE_INACTIVE, - api.GetShadowForWindow(window2.get())->style()); - SetShadowType(window2.get(), SHADOW_TYPE_RECTANGULAR_ALWAYS_ACTIVE); - EXPECT_EQ(Shadow::STYLE_ACTIVE, - api.GetShadowForWindow(window2.get())->style()); - - // Activation should not change the shadow style. - ActivateWindow(window2.get()); - EXPECT_EQ(Shadow::STYLE_ACTIVE, - api.GetShadowForWindow(window1.get())->style()); - EXPECT_EQ(Shadow::STYLE_ACTIVE, - api.GetShadowForWindow(window2.get())->style()); - - ActivateWindow(window1.get()); - EXPECT_EQ(Shadow::STYLE_ACTIVE, - api.GetShadowForWindow(window1.get())->style()); - EXPECT_EQ(Shadow::STYLE_ACTIVE, - api.GetShadowForWindow(window2.get())->style()); - - // Restore the style to plain RECTANGULAR and make sure the inactive window - // gets the inactive shadow. - SetShadowType(window1.get(), SHADOW_TYPE_RECTANGULAR); - SetShadowType(window2.get(), SHADOW_TYPE_RECTANGULAR); - EXPECT_EQ(Shadow::STYLE_ACTIVE, - api.GetShadowForWindow(window1.get())->style()); - EXPECT_EQ(Shadow::STYLE_INACTIVE, - api.GetShadowForWindow(window2.get())->style()); -} - -} // namespace wm
diff --git a/ui/wm/core/shadow_types.cc b/ui/wm/core/shadow_types.cc deleted file mode 100644 index a7afe89..0000000 --- a/ui/wm/core/shadow_types.cc +++ /dev/null
@@ -1,23 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/shadow_types.h" - -#include "ui/aura/window_property.h" - -DECLARE_WINDOW_PROPERTY_TYPE(wm::ShadowType); - -namespace wm { - -void SetShadowType(aura::Window* window, ShadowType shadow_type) { - window->SetProperty(kShadowTypeKey, shadow_type); -} - -ShadowType GetShadowType(aura::Window* window) { - return window->GetProperty(kShadowTypeKey); -} - -DEFINE_WINDOW_PROPERTY_KEY(ShadowType, kShadowTypeKey, SHADOW_TYPE_NONE); - -} // namespace wm
diff --git a/ui/wm/core/shadow_types.h b/ui/wm/core/shadow_types.h deleted file mode 100644 index ef6be1d..0000000 --- a/ui/wm/core/shadow_types.h +++ /dev/null
@@ -1,35 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_CORE_SHADOW_TYPES_H_ -#define UI_WM_CORE_SHADOW_TYPES_H_ - -#include "ui/aura/window.h" -#include "ui/wm/wm_export.h" - -namespace aura { -class Window; -} - -namespace wm { - -// Different types of drop shadows that can be drawn under a window by the -// shell. Used as a value for the kShadowTypeKey property. -enum ShadowType { - // Starts at 0 due to the cast in GetShadowType(). - SHADOW_TYPE_NONE = 0, - SHADOW_TYPE_RECTANGULAR, - SHADOW_TYPE_RECTANGULAR_ALWAYS_ACTIVE, -}; - -WM_EXPORT void SetShadowType(aura::Window* window, ShadowType shadow_type); -WM_EXPORT ShadowType GetShadowType(aura::Window* window); - -// A property key describing the drop shadow that should be displayed under the -// window. If unset, no shadow is displayed. -extern const aura::WindowProperty<ShadowType>* const kShadowTypeKey; - -} // namespace wm - -#endif // UI_WM_CORE_SHADOW_TYPES_H_
diff --git a/ui/wm/core/shadow_unittest.cc b/ui/wm/core/shadow_unittest.cc deleted file mode 100644 index 2ffdd4a..0000000 --- a/ui/wm/core/shadow_unittest.cc +++ /dev/null
@@ -1,153 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/shadow.h" - -#include "base/memory/scoped_ptr.h" -#include "base/path_service.h" -#include "third_party/skia/include/core/SkBitmap.h" -#include "ui/aura/test/aura_test_base.h" -#include "ui/aura/test/test_windows.h" -#include "ui/aura/window.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/base/ui_base_paths.h" -#include "ui/compositor/layer.h" -#include "ui/compositor/layer_tree_owner.h" -#include "ui/resources/grit/ui_resources.h" - -namespace wm { - -namespace { - -const int kSmallBitmapSize = 129; -const int kLargeBitmapSize = 269; - -// Mock for the ResourceBundle::Delegate class. -class MockResourceBundleDelegate : public ui::ResourceBundle::Delegate { - public: - MockResourceBundleDelegate() : last_resource_id_(0) { - SkBitmap bitmap_small, bitmap_large; - bitmap_small.allocPixels( - SkImageInfo::MakeN32Premul(kSmallBitmapSize, kSmallBitmapSize)); - bitmap_large.allocPixels( - SkImageInfo::MakeN32Premul(kLargeBitmapSize, kLargeBitmapSize)); - image_small_ = gfx::Image::CreateFrom1xBitmap(bitmap_small); - image_large_ = gfx::Image::CreateFrom1xBitmap(bitmap_large); - } - virtual ~MockResourceBundleDelegate() {} - - // ResourceBundle::Delegate: - virtual base::FilePath GetPathForResourcePack( - const base::FilePath& pack_path, - ui::ScaleFactor scale_factor) override { - return base::FilePath(); - } - virtual base::FilePath GetPathForLocalePack( - const base::FilePath& pack_path, - const std::string& locale) override { - return base::FilePath(); - } - virtual gfx::Image GetImageNamed(int resource_id) override { - last_resource_id_ = resource_id; - switch (resource_id) { - case IDR_WINDOW_BUBBLE_SHADOW_SMALL: - return image_small_; - case IDR_AURA_SHADOW_ACTIVE: - case IDR_AURA_SHADOW_INACTIVE: - return image_large_; - default: - NOTREACHED(); - return gfx::Image(); - } - } - virtual gfx::Image GetNativeImageNamed( - int resource_id, ui::ResourceBundle::ImageRTL rtl) override { - return gfx::Image(); - } - virtual base::RefCountedStaticMemory* LoadDataResourceBytes( - int resource_id, ui::ScaleFactor scale_factor) override { - return NULL; - } - virtual bool GetRawDataResource( - int resource_id, ui::ScaleFactor scale_factor, - base::StringPiece* value) override { - return false; - } - virtual bool GetLocalizedString( - int message_id, base::string16* value) override { - return false; - } - virtual scoped_ptr<gfx::Font> GetFont( - ui::ResourceBundle::FontStyle style) override { - return scoped_ptr<gfx::Font>(); - } - - int last_resource_id() const { return last_resource_id_; } - - private: - gfx::Image image_small_; - gfx::Image image_large_; - int last_resource_id_; - - DISALLOW_COPY_AND_ASSIGN(MockResourceBundleDelegate); -}; - -} // namespace - -class ShadowTest: public aura::test::AuraTestBase { - public: - ShadowTest() {} - virtual ~ShadowTest() {} - - MockResourceBundleDelegate* delegate() { return delegate_.get(); } - - // aura::testAuraBase: - virtual void SetUp() override { - aura::test::AuraTestBase::SetUp(); - delegate_.reset(new MockResourceBundleDelegate()); - if (ResourceBundle::HasSharedInstance()) - ui::ResourceBundle::CleanupSharedInstance(); - ui::ResourceBundle::InitSharedInstanceWithLocale( - "en-US", delegate(), ui::ResourceBundle::LOAD_COMMON_RESOURCES); - } - virtual void TearDown() override { - ui::ResourceBundle::CleanupSharedInstance(); - base::FilePath ui_test_pak_path; - ASSERT_TRUE(PathService::Get(ui::UI_TEST_PAK, &ui_test_pak_path)); - ui::ResourceBundle::InitSharedInstanceWithPakPath(ui_test_pak_path); - aura::test::AuraTestBase::TearDown(); - } - private: - scoped_ptr<MockResourceBundleDelegate> delegate_; - DISALLOW_COPY_AND_ASSIGN(ShadowTest); -}; - -// Test if the proper image is set for the specified style. -TEST_F(ShadowTest, UpdateImagesForStyle) { - Shadow shadow; - - shadow.Init(Shadow::STYLE_SMALL); - EXPECT_EQ(delegate()->last_resource_id(), IDR_WINDOW_BUBBLE_SHADOW_SMALL); - shadow.SetStyle(Shadow::STYLE_ACTIVE); - EXPECT_EQ(delegate()->last_resource_id(), IDR_AURA_SHADOW_ACTIVE); - shadow.SetStyle(Shadow::STYLE_INACTIVE); - EXPECT_EQ(delegate()->last_resource_id(), IDR_AURA_SHADOW_INACTIVE); -} - -// Test if the proper content bounds is calculated based on the current style. -TEST_F(ShadowTest, SetContentBounds) { - Shadow shadow; - - // Verify that layer bounds are inset from content bounds. - shadow.Init(Shadow::STYLE_ACTIVE); - gfx::Rect content_bounds(100, 100, 300, 300); - shadow.SetContentBounds(content_bounds); - EXPECT_EQ(shadow.content_bounds(), content_bounds); - EXPECT_EQ(shadow.layer()->bounds(), gfx::Rect(36, 36, 428, 428)); - - shadow.SetStyle(Shadow::STYLE_SMALL); - EXPECT_EQ(shadow.content_bounds(), content_bounds); - EXPECT_EQ(shadow.layer()->bounds(), gfx::Rect(96, 96, 308, 308)); -} -} // namespace wm
diff --git a/ui/wm/core/transient_window_controller.cc b/ui/wm/core/transient_window_controller.cc deleted file mode 100644 index bb1945c..0000000 --- a/ui/wm/core/transient_window_controller.cc +++ /dev/null
@@ -1,40 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/transient_window_controller.h" - -#include "ui/wm/core/transient_window_manager.h" - -namespace wm { - -TransientWindowController::TransientWindowController() { -} - -TransientWindowController::~TransientWindowController() { -} - -void TransientWindowController::AddTransientChild(aura::Window* parent, - aura::Window* child) { - TransientWindowManager::Get(parent)->AddTransientChild(child); -} - -void TransientWindowController::RemoveTransientChild(aura::Window* parent, - aura::Window* child) { - TransientWindowManager::Get(parent)->RemoveTransientChild(child); -} - -aura::Window* TransientWindowController::GetTransientParent( - aura::Window* window) { - return const_cast<aura::Window*>(GetTransientParent( - const_cast<const aura::Window*>(window))); -} - -const aura::Window* TransientWindowController::GetTransientParent( - const aura::Window* window) { - const TransientWindowManager* window_manager = - TransientWindowManager::Get(window); - return window_manager ? window_manager->transient_parent() : NULL; -} - -} // namespace wm
diff --git a/ui/wm/core/transient_window_controller.h b/ui/wm/core/transient_window_controller.h deleted file mode 100644 index 4322b41..0000000 --- a/ui/wm/core/transient_window_controller.h +++ /dev/null
@@ -1,36 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_CORE_TRANSIENT_WINDOW_CONTROLLER_H_ -#define UI_WM_CORE_TRANSIENT_WINDOW_CONTROLLER_H_ - -#include "ui/wm/public/transient_window_client.h" -#include "ui/wm/wm_export.h" - -namespace wm { - -// TransientWindowClient implementation. Uses TransientWindowManager to handle -// tracking transient per window. -class WM_EXPORT TransientWindowController - : public aura::client::TransientWindowClient { - public: - TransientWindowController(); - virtual ~TransientWindowController(); - - // TransientWindowClient: - virtual void AddTransientChild(aura::Window* parent, - aura::Window* child) override; - virtual void RemoveTransientChild(aura::Window* parent, - aura::Window* child) override; - virtual aura::Window* GetTransientParent(aura::Window* window) override; - virtual const aura::Window* GetTransientParent( - const aura::Window* window) override; - - private: - DISALLOW_COPY_AND_ASSIGN(TransientWindowController); -}; - -} // namespace wm - -#endif // UI_WM_CORE_TRANSIENT_WINDOW_CONTROLLER_H_
diff --git a/ui/wm/core/transient_window_manager.cc b/ui/wm/core/transient_window_manager.cc deleted file mode 100644 index 9a2ba38..0000000 --- a/ui/wm/core/transient_window_manager.cc +++ /dev/null
@@ -1,214 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/transient_window_manager.h" - -#include <algorithm> -#include <functional> - -#include "base/auto_reset.h" -#include "base/stl_util.h" -#include "ui/aura/window.h" -#include "ui/aura/window_property.h" -#include "ui/wm/core/transient_window_observer.h" -#include "ui/wm/core/transient_window_stacking_client.h" -#include "ui/wm/core/window_util.h" - -using aura::Window; - -namespace wm { -namespace { - -DEFINE_OWNED_WINDOW_PROPERTY_KEY(TransientWindowManager, kPropertyKey, NULL); - -} // namespace - -TransientWindowManager::~TransientWindowManager() { -} - -// static -TransientWindowManager* TransientWindowManager::Get(Window* window) { - TransientWindowManager* manager = window->GetProperty(kPropertyKey); - if (!manager) { - manager = new TransientWindowManager(window); - window->SetProperty(kPropertyKey, manager); - } - return manager; -} - -// static -const TransientWindowManager* TransientWindowManager::Get( - const Window* window) { - return window->GetProperty(kPropertyKey); -} - -void TransientWindowManager::AddObserver(TransientWindowObserver* observer) { - observers_.AddObserver(observer); -} - -void TransientWindowManager::RemoveObserver(TransientWindowObserver* observer) { - observers_.RemoveObserver(observer); -} - -void TransientWindowManager::AddTransientChild(Window* child) { - // TransientWindowStackingClient does the stacking of transient windows. If it - // isn't installed stacking is going to be wrong. - DCHECK(TransientWindowStackingClient::instance_); - - TransientWindowManager* child_manager = Get(child); - if (child_manager->transient_parent_) - Get(child_manager->transient_parent_)->RemoveTransientChild(child); - DCHECK(std::find(transient_children_.begin(), transient_children_.end(), - child) == transient_children_.end()); - transient_children_.push_back(child); - child_manager->transient_parent_ = window_; - - // Restack |child| properly above its transient parent, if they share the same - // parent. - if (child->parent() == window_->parent()) - RestackTransientDescendants(); - - FOR_EACH_OBSERVER(TransientWindowObserver, observers_, - OnTransientChildAdded(window_, child)); -} - -void TransientWindowManager::RemoveTransientChild(Window* child) { - Windows::iterator i = - std::find(transient_children_.begin(), transient_children_.end(), child); - DCHECK(i != transient_children_.end()); - transient_children_.erase(i); - TransientWindowManager* child_manager = Get(child); - DCHECK_EQ(window_, child_manager->transient_parent_); - child_manager->transient_parent_ = NULL; - - // If |child| and its former transient parent share the same parent, |child| - // should be restacked properly so it is not among transient children of its - // former parent, anymore. - if (window_->parent() == child->parent()) - RestackTransientDescendants(); - - FOR_EACH_OBSERVER(TransientWindowObserver, observers_, - OnTransientChildRemoved(window_, child)); -} - -bool TransientWindowManager::IsStackingTransient( - const aura::Window* target) const { - return stacking_target_ == target; -} - -TransientWindowManager::TransientWindowManager(Window* window) - : window_(window), - transient_parent_(NULL), - stacking_target_(NULL), - parent_controls_visibility_(false), - show_on_parent_visible_(false), - ignore_visibility_changed_event_(false) { - window_->AddObserver(this); -} - -void TransientWindowManager::RestackTransientDescendants() { - Window* parent = window_->parent(); - if (!parent) - return; - - // Stack any transient children that share the same parent to be in front of - // |window_|. The existing stacking order is preserved by iterating backwards - // and always stacking on top. - Window::Windows children(parent->children()); - for (Window::Windows::reverse_iterator it = children.rbegin(); - it != children.rend(); ++it) { - if ((*it) != window_ && HasTransientAncestor(*it, window_)) { - TransientWindowManager* descendant_manager = Get(*it); - base::AutoReset<Window*> resetter( - &descendant_manager->stacking_target_, - window_); - parent->StackChildAbove((*it), window_); - } - } -} - -void TransientWindowManager::OnWindowParentChanged(aura::Window* window, - aura::Window* parent) { - DCHECK_EQ(window_, window); - // Stack |window| properly if it is transient child of a sibling. - Window* transient_parent = wm::GetTransientParent(window); - if (transient_parent && transient_parent->parent() == parent) { - TransientWindowManager* transient_parent_manager = - Get(transient_parent); - transient_parent_manager->RestackTransientDescendants(); - } -} - -void TransientWindowManager::UpdateTransientChildVisibility( - bool parent_visible) { - base::AutoReset<bool> reset(&ignore_visibility_changed_event_, true); - if (!parent_visible) { - show_on_parent_visible_ = window_->TargetVisibility(); - window_->Hide(); - } else { - if (show_on_parent_visible_ && parent_controls_visibility_) - window_->Show(); - show_on_parent_visible_ = false; - } -} - -void TransientWindowManager::OnWindowVisibilityChanging(Window* window, - bool visible) { - DCHECK_EQ(window_, window); - - for (auto* child : transient_children_) - Get(child)->UpdateTransientChildVisibility(visible); -} - -void TransientWindowManager::OnWindowVisibilityChanged(Window* window, - bool visible) { - if (window_ != window || ignore_visibility_changed_event_ || - !transient_parent_ || !parent_controls_visibility_) { - return; - } - if (!transient_parent_->TargetVisibility() && visible) { - base::AutoReset<bool> reset(&ignore_visibility_changed_event_, true); - show_on_parent_visible_ = true; - window_->Hide(); - } else if (!visible) { - DCHECK(!show_on_parent_visible_); - } -} - -void TransientWindowManager::OnWindowStackingChanged(Window* window) { - DCHECK_EQ(window_, window); - // Do nothing if we initiated the stacking change. - const TransientWindowManager* transient_manager = - Get(static_cast<const Window*>(window)); - if (transient_manager && transient_manager->stacking_target_) { - Windows::const_iterator window_i = std::find( - window->parent()->children().begin(), - window->parent()->children().end(), - window); - DCHECK(window_i != window->parent()->children().end()); - if (window_i != window->parent()->children().begin() && - (*(window_i - 1) == transient_manager->stacking_target_)) - return; - } - - RestackTransientDescendants(); -} - -void TransientWindowManager::OnWindowDestroying(Window* window) { - // Removes ourselves from our transient parent (if it hasn't been done by the - // RootWindow). - if (transient_parent_) { - TransientWindowManager::Get(transient_parent_)->RemoveTransientChild( - window_); - } - - // Destroy transient children, only after we've removed ourselves from our - // parent, as destroying an active transient child may otherwise attempt to - // refocus us. - Windows transient_children(transient_children_); - STLDeleteElements(&transient_children); - DCHECK(transient_children_.empty()); -} - -} // namespace wm
diff --git a/ui/wm/core/transient_window_manager.h b/ui/wm/core/transient_window_manager.h deleted file mode 100644 index a6c5139..0000000 --- a/ui/wm/core/transient_window_manager.h +++ /dev/null
@@ -1,111 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_CORE_TRANSIENT_WINDOW_MANAGER_H_ -#define UI_WM_CORE_TRANSIENT_WINDOW_MANAGER_H_ - -#include <vector> - -#include "base/observer_list.h" -#include "ui/aura/window_observer.h" -#include "ui/wm/wm_export.h" - -namespace wm { - -class TransientWindowObserver; - -// TransientWindowManager manages the set of transient children for a window -// along with the transient parent. Transient children get the following -// behavior: -// . The transient parent destroys any transient children when it is -// destroyed. This means a transient child is destroyed if either its parent -// or transient parent is destroyed. -// . If a transient child and its transient parent share the same parent, then -// transient children are always ordered above the transient parent. -// . If a transient parent is hidden, it hides all transient children. -// For show operation, please refer to |set_parent_controls_visibility(bool)|. -// Transient windows are typically used for popups and menus. -// TODO(sky): when we nuke TransientWindowClient rename this to -// TransientWindowController. -class WM_EXPORT TransientWindowManager : public aura::WindowObserver { - public: - typedef std::vector<aura::Window*> Windows; - - virtual ~TransientWindowManager(); - - // Returns the TransientWindowManager for |window|. This never returns NULL. - static TransientWindowManager* Get(aura::Window* window); - - // Returns the TransientWindowManager for |window| only if it already exists. - // WARNING: this may return NULL. - static const TransientWindowManager* Get(const aura::Window* window); - - void AddObserver(TransientWindowObserver* observer); - void RemoveObserver(TransientWindowObserver* observer); - - // Adds or removes a transient child. - void AddTransientChild(aura::Window* child); - void RemoveTransientChild(aura::Window* child); - - // Setting true lets the transient parent show this transient - // child when the parent is shown. If this was shown when the - // transient parent is hidden, it remains hidden and gets shown - // when the transient parent is shown. This is false by default. - void set_parent_controls_visibility(bool parent_controls_visibility) { - parent_controls_visibility_ = parent_controls_visibility; - } - - const Windows& transient_children() const { return transient_children_; } - - aura::Window* transient_parent() { return transient_parent_; } - const aura::Window* transient_parent() const { return transient_parent_; } - - // Returns true if in the process of stacking |window_| on top of |target|. - // That is, when the stacking order of a window changes - // (OnWindowStackingChanged()) the transients may get restacked as well. This - // function can be used to detect if TransientWindowManager is in the process - // of stacking a transient as the result of window stacking changing. - bool IsStackingTransient(const aura::Window* target) const; - - private: - explicit TransientWindowManager(aura::Window* window); - - // Stacks transient descendants of this window that are its siblings just - // above it. - void RestackTransientDescendants(); - - // Update the window's visibility following the transient parent's - // visibility. See |set_parent_controls_visibility(bool)| for more details. - void UpdateTransientChildVisibility(bool visible); - - // WindowObserver: - virtual void OnWindowParentChanged(aura::Window* window, - aura::Window* parent) override; - virtual void OnWindowVisibilityChanging(aura::Window* window, - bool visible) override; - virtual void OnWindowVisibilityChanged(aura::Window* window, - bool visible) override; - virtual void OnWindowStackingChanged(aura::Window* window) override; - virtual void OnWindowDestroying(aura::Window* window) override; - - aura::Window* window_; - aura::Window* transient_parent_; - Windows transient_children_; - - // If non-null we're actively restacking transient as the result of a - // transient ancestor changing. - aura::Window* stacking_target_; - - bool parent_controls_visibility_; - bool show_on_parent_visible_; - bool ignore_visibility_changed_event_; - - ObserverList<TransientWindowObserver> observers_; - - DISALLOW_COPY_AND_ASSIGN(TransientWindowManager); -}; - -} // namespace wm - -#endif // UI_WM_CORE_TRANSIENT_WINDOW_MANAGER_H_
diff --git a/ui/wm/core/transient_window_manager_unittest.cc b/ui/wm/core/transient_window_manager_unittest.cc deleted file mode 100644 index 79d2559..0000000 --- a/ui/wm/core/transient_window_manager_unittest.cc +++ /dev/null
@@ -1,707 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/transient_window_manager.h" - -#include "ui/aura/client/visibility_client.h" -#include "ui/aura/client/window_tree_client.h" -#include "ui/aura/layout_manager.h" -#include "ui/aura/test/aura_test_base.h" -#include "ui/aura/test/test_windows.h" -#include "ui/aura/window.h" -#include "ui/wm/core/transient_window_observer.h" -#include "ui/wm/core/window_util.h" -#include "ui/wm/core/wm_state.h" - -using aura::Window; - -using aura::test::ChildWindowIDsAsString; -using aura::test::CreateTestWindowWithId; - -namespace wm { - -class TestTransientWindowObserver : public TransientWindowObserver { - public: - TestTransientWindowObserver() : add_count_(0), remove_count_(0) { - } - - virtual ~TestTransientWindowObserver() { - } - - int add_count() const { return add_count_; } - int remove_count() const { return remove_count_; } - - // TransientWindowObserver overrides: - virtual void OnTransientChildAdded(Window* window, - Window* transient) override { - add_count_++; - } - virtual void OnTransientChildRemoved(Window* window, - Window* transient) override { - remove_count_++; - } - - private: - int add_count_; - int remove_count_; - - DISALLOW_COPY_AND_ASSIGN(TestTransientWindowObserver); -}; - -class TransientWindowManagerTest : public aura::test::AuraTestBase { - public: - TransientWindowManagerTest() {} - virtual ~TransientWindowManagerTest() {} - - virtual void SetUp() override { - AuraTestBase::SetUp(); - wm_state_.reset(new wm::WMState); - } - - virtual void TearDown() override { - wm_state_.reset(); - AuraTestBase::TearDown(); - } - - protected: - // Creates a transient window that is transient to |parent|. - Window* CreateTransientChild(int id, Window* parent) { - Window* window = new Window(NULL); - window->set_id(id); - window->SetType(ui::wm::WINDOW_TYPE_NORMAL); - window->Init(aura::WINDOW_LAYER_TEXTURED); - AddTransientChild(parent, window); - aura::client::ParentWindowWithContext(window, root_window(), gfx::Rect()); - return window; - } - - private: - scoped_ptr<wm::WMState> wm_state_; - - DISALLOW_COPY_AND_ASSIGN(TransientWindowManagerTest); -}; - -// Various assertions for transient children. -TEST_F(TransientWindowManagerTest, TransientChildren) { - scoped_ptr<Window> parent(CreateTestWindowWithId(0, root_window())); - scoped_ptr<Window> w1(CreateTestWindowWithId(1, parent.get())); - scoped_ptr<Window> w3(CreateTestWindowWithId(3, parent.get())); - Window* w2 = CreateTestWindowWithId(2, parent.get()); - // w2 is now owned by w1. - AddTransientChild(w1.get(), w2); - // Stack w1 at the top (end), this should force w2 to be last (on top of w1). - parent->StackChildAtTop(w1.get()); - ASSERT_EQ(3u, parent->children().size()); - EXPECT_EQ(w2, parent->children().back()); - - // Destroy w1, which should also destroy w3 (since it's a transient child). - w1.reset(); - w2 = NULL; - ASSERT_EQ(1u, parent->children().size()); - EXPECT_EQ(w3.get(), parent->children()[0]); - - w1.reset(CreateTestWindowWithId(4, parent.get())); - w2 = CreateTestWindowWithId(5, w3.get()); - AddTransientChild(w1.get(), w2); - parent->StackChildAtTop(w3.get()); - // Stack w1 at the top (end), this shouldn't affect w2 since it has a - // different parent. - parent->StackChildAtTop(w1.get()); - ASSERT_EQ(2u, parent->children().size()); - EXPECT_EQ(w3.get(), parent->children()[0]); - EXPECT_EQ(w1.get(), parent->children()[1]); - - // Hiding parent should hide transient children. - EXPECT_TRUE(w2->IsVisible()); - w1->Hide(); - EXPECT_FALSE(w2->IsVisible()); - - // And they should stay hidden even after the parent became visible. - w1->Show(); - EXPECT_FALSE(w2->IsVisible()); - - // Hidden transient child should stay hidden regardless of - // parent's visibility. - w2->Hide(); - EXPECT_FALSE(w2->IsVisible()); - w1->Hide(); - EXPECT_FALSE(w2->IsVisible()); - w1->Show(); - EXPECT_FALSE(w2->IsVisible()); - - // Transient child can be shown even if the transient parent is hidden. - w1->Hide(); - EXPECT_FALSE(w2->IsVisible()); - w2->Show(); - EXPECT_TRUE(w2->IsVisible()); - w1->Show(); - EXPECT_TRUE(w2->IsVisible()); - - // When the parent_controls_visibility is true, TransientWindowManager - // controls the children's visibility. It stays invisible even if - // Window::Show() is called, and gets shown when the parent becomes visible. - wm::TransientWindowManager::Get(w2)->set_parent_controls_visibility(true); - w1->Hide(); - EXPECT_FALSE(w2->IsVisible()); - w2->Show(); - EXPECT_FALSE(w2->IsVisible()); - w1->Show(); - EXPECT_TRUE(w2->IsVisible()); - - // Hiding a transient child that is hidden by the transient parent - // is not currently handled and will be shown anyway. - w1->Hide(); - EXPECT_FALSE(w2->IsVisible()); - w2->Hide(); - EXPECT_FALSE(w2->IsVisible()); - w1->Show(); - EXPECT_TRUE(w2->IsVisible()); -} - -// Tests that transient children are stacked as a unit when using stack above. -TEST_F(TransientWindowManagerTest, TransientChildrenGroupAbove) { - scoped_ptr<Window> parent(CreateTestWindowWithId(0, root_window())); - scoped_ptr<Window> w1(CreateTestWindowWithId(1, parent.get())); - Window* w11 = CreateTestWindowWithId(11, parent.get()); - scoped_ptr<Window> w2(CreateTestWindowWithId(2, parent.get())); - Window* w21 = CreateTestWindowWithId(21, parent.get()); - Window* w211 = CreateTestWindowWithId(211, parent.get()); - Window* w212 = CreateTestWindowWithId(212, parent.get()); - Window* w213 = CreateTestWindowWithId(213, parent.get()); - Window* w22 = CreateTestWindowWithId(22, parent.get()); - ASSERT_EQ(8u, parent->children().size()); - - // w11 is now owned by w1. - AddTransientChild(w1.get(), w11); - // w21 is now owned by w2. - AddTransientChild(w2.get(), w21); - // w22 is now owned by w2. - AddTransientChild(w2.get(), w22); - // w211 is now owned by w21. - AddTransientChild(w21, w211); - // w212 is now owned by w21. - AddTransientChild(w21, w212); - // w213 is now owned by w21. - AddTransientChild(w21, w213); - EXPECT_EQ("1 11 2 21 211 212 213 22", ChildWindowIDsAsString(parent.get())); - - // Stack w1 at the top (end), this should force w11 to be last (on top of w1). - parent->StackChildAtTop(w1.get()); - EXPECT_EQ(w11, parent->children().back()); - EXPECT_EQ("2 21 211 212 213 22 1 11", ChildWindowIDsAsString(parent.get())); - - // This tests that the order in children_ array rather than in - // transient_children_ array is used when reinserting transient children. - // If transient_children_ array was used '22' would be following '21'. - parent->StackChildAtTop(w2.get()); - EXPECT_EQ(w22, parent->children().back()); - EXPECT_EQ("1 11 2 21 211 212 213 22", ChildWindowIDsAsString(parent.get())); - - parent->StackChildAbove(w11, w2.get()); - EXPECT_EQ(w11, parent->children().back()); - EXPECT_EQ("2 21 211 212 213 22 1 11", ChildWindowIDsAsString(parent.get())); - - parent->StackChildAbove(w21, w1.get()); - EXPECT_EQ(w22, parent->children().back()); - EXPECT_EQ("1 11 2 21 211 212 213 22", ChildWindowIDsAsString(parent.get())); - - parent->StackChildAbove(w21, w22); - EXPECT_EQ(w213, parent->children().back()); - EXPECT_EQ("1 11 2 22 21 211 212 213", ChildWindowIDsAsString(parent.get())); - - parent->StackChildAbove(w11, w21); - EXPECT_EQ(w11, parent->children().back()); - EXPECT_EQ("2 22 21 211 212 213 1 11", ChildWindowIDsAsString(parent.get())); - - parent->StackChildAbove(w213, w21); - EXPECT_EQ(w11, parent->children().back()); - EXPECT_EQ("2 22 21 213 211 212 1 11", ChildWindowIDsAsString(parent.get())); - - // No change when stacking a transient parent above its transient child. - parent->StackChildAbove(w21, w211); - EXPECT_EQ(w11, parent->children().back()); - EXPECT_EQ("2 22 21 213 211 212 1 11", ChildWindowIDsAsString(parent.get())); - - // This tests that the order in children_ array rather than in - // transient_children_ array is used when reinserting transient children. - // If transient_children_ array was used '22' would be following '21'. - parent->StackChildAbove(w2.get(), w1.get()); - EXPECT_EQ(w212, parent->children().back()); - EXPECT_EQ("1 11 2 22 21 213 211 212", ChildWindowIDsAsString(parent.get())); - - parent->StackChildAbove(w11, w213); - EXPECT_EQ(w11, parent->children().back()); - EXPECT_EQ("2 22 21 213 211 212 1 11", ChildWindowIDsAsString(parent.get())); -} - -// Tests that transient children are stacked as a unit when using stack below. -TEST_F(TransientWindowManagerTest, TransientChildrenGroupBelow) { - scoped_ptr<Window> parent(CreateTestWindowWithId(0, root_window())); - scoped_ptr<Window> w1(CreateTestWindowWithId(1, parent.get())); - Window* w11 = CreateTestWindowWithId(11, parent.get()); - scoped_ptr<Window> w2(CreateTestWindowWithId(2, parent.get())); - Window* w21 = CreateTestWindowWithId(21, parent.get()); - Window* w211 = CreateTestWindowWithId(211, parent.get()); - Window* w212 = CreateTestWindowWithId(212, parent.get()); - Window* w213 = CreateTestWindowWithId(213, parent.get()); - Window* w22 = CreateTestWindowWithId(22, parent.get()); - ASSERT_EQ(8u, parent->children().size()); - - // w11 is now owned by w1. - AddTransientChild(w1.get(), w11); - // w21 is now owned by w2. - AddTransientChild(w2.get(), w21); - // w22 is now owned by w2. - AddTransientChild(w2.get(), w22); - // w211 is now owned by w21. - AddTransientChild(w21, w211); - // w212 is now owned by w21. - AddTransientChild(w21, w212); - // w213 is now owned by w21. - AddTransientChild(w21, w213); - EXPECT_EQ("1 11 2 21 211 212 213 22", ChildWindowIDsAsString(parent.get())); - - // Stack w2 at the bottom, this should force w11 to be last (on top of w1). - // This also tests that the order in children_ array rather than in - // transient_children_ array is used when reinserting transient children. - // If transient_children_ array was used '22' would be following '21'. - parent->StackChildAtBottom(w2.get()); - EXPECT_EQ(w11, parent->children().back()); - EXPECT_EQ("2 21 211 212 213 22 1 11", ChildWindowIDsAsString(parent.get())); - - parent->StackChildAtBottom(w1.get()); - EXPECT_EQ(w22, parent->children().back()); - EXPECT_EQ("1 11 2 21 211 212 213 22", ChildWindowIDsAsString(parent.get())); - - parent->StackChildBelow(w21, w1.get()); - EXPECT_EQ(w11, parent->children().back()); - EXPECT_EQ("2 21 211 212 213 22 1 11", ChildWindowIDsAsString(parent.get())); - - parent->StackChildBelow(w11, w2.get()); - EXPECT_EQ(w22, parent->children().back()); - EXPECT_EQ("1 11 2 21 211 212 213 22", ChildWindowIDsAsString(parent.get())); - - parent->StackChildBelow(w22, w21); - EXPECT_EQ(w213, parent->children().back()); - EXPECT_EQ("1 11 2 22 21 211 212 213", ChildWindowIDsAsString(parent.get())); - - parent->StackChildBelow(w21, w11); - EXPECT_EQ(w11, parent->children().back()); - EXPECT_EQ("2 22 21 211 212 213 1 11", ChildWindowIDsAsString(parent.get())); - - parent->StackChildBelow(w213, w211); - EXPECT_EQ(w11, parent->children().back()); - EXPECT_EQ("2 22 21 213 211 212 1 11", ChildWindowIDsAsString(parent.get())); - - // No change when stacking a transient parent below its transient child. - parent->StackChildBelow(w21, w211); - EXPECT_EQ(w11, parent->children().back()); - EXPECT_EQ("2 22 21 213 211 212 1 11", ChildWindowIDsAsString(parent.get())); - - parent->StackChildBelow(w1.get(), w2.get()); - EXPECT_EQ(w212, parent->children().back()); - EXPECT_EQ("1 11 2 22 21 213 211 212", ChildWindowIDsAsString(parent.get())); - - parent->StackChildBelow(w213, w11); - EXPECT_EQ(w11, parent->children().back()); - EXPECT_EQ("2 22 21 213 211 212 1 11", ChildWindowIDsAsString(parent.get())); -} - -// Tests that transient windows are stacked properly when created. -TEST_F(TransientWindowManagerTest, StackUponCreation) { - scoped_ptr<Window> window0(CreateTestWindowWithId(0, root_window())); - scoped_ptr<Window> window1(CreateTestWindowWithId(1, root_window())); - - scoped_ptr<Window> window2(CreateTransientChild(2, window0.get())); - EXPECT_EQ("0 2 1", ChildWindowIDsAsString(root_window())); -} - -// Tests that windows are restacked properly after a call to AddTransientChild() -// or RemoveTransientChild(). -TEST_F(TransientWindowManagerTest, RestackUponAddOrRemoveTransientChild) { - scoped_ptr<Window> windows[4]; - for (int i = 0; i < 4; i++) - windows[i].reset(CreateTestWindowWithId(i, root_window())); - EXPECT_EQ("0 1 2 3", ChildWindowIDsAsString(root_window())); - - AddTransientChild(windows[0].get(), windows[2].get()); - EXPECT_EQ("0 2 1 3", ChildWindowIDsAsString(root_window())); - - AddTransientChild(windows[0].get(), windows[3].get()); - EXPECT_EQ("0 2 3 1", ChildWindowIDsAsString(root_window())); - - RemoveTransientChild(windows[0].get(), windows[2].get()); - EXPECT_EQ("0 3 2 1", ChildWindowIDsAsString(root_window())); - - RemoveTransientChild(windows[0].get(), windows[3].get()); - EXPECT_EQ("0 3 2 1", ChildWindowIDsAsString(root_window())); -} - -namespace { - -// Used by NotifyDelegateAfterDeletingTransients. Adds a string to a vector when -// OnWindowDestroyed() is invoked so that destruction order can be verified. -class DestroyedTrackingDelegate : public aura::test::TestWindowDelegate { - public: - explicit DestroyedTrackingDelegate(const std::string& name, - std::vector<std::string>* results) - : name_(name), - results_(results) {} - - virtual void OnWindowDestroyed(aura::Window* window) override { - results_->push_back(name_); - } - - private: - const std::string name_; - std::vector<std::string>* results_; - - DISALLOW_COPY_AND_ASSIGN(DestroyedTrackingDelegate); -}; - -} // namespace - -// Verifies the delegate is notified of destruction after transients are -// destroyed. -TEST_F(TransientWindowManagerTest, NotifyDelegateAfterDeletingTransients) { - std::vector<std::string> destruction_order; - - DestroyedTrackingDelegate parent_delegate("parent", &destruction_order); - scoped_ptr<Window> parent(new Window(&parent_delegate)); - parent->Init(aura::WINDOW_LAYER_NOT_DRAWN); - - DestroyedTrackingDelegate transient_delegate("transient", &destruction_order); - Window* transient = new Window(&transient_delegate); // Owned by |parent|. - transient->Init(aura::WINDOW_LAYER_NOT_DRAWN); - AddTransientChild(parent.get(), transient); - parent.reset(); - - ASSERT_EQ(2u, destruction_order.size()); - EXPECT_EQ("transient", destruction_order[0]); - EXPECT_EQ("parent", destruction_order[1]); -} - -TEST_F(TransientWindowManagerTest, StackTransientsWhoseLayersHaveNoDelegate) { - // Create a window with several transients, then a couple windows on top. - scoped_ptr<Window> window1(CreateTestWindowWithId(1, root_window())); - scoped_ptr<Window> window11(CreateTransientChild(11, window1.get())); - scoped_ptr<Window> window12(CreateTransientChild(12, window1.get())); - scoped_ptr<Window> window13(CreateTransientChild(13, window1.get())); - scoped_ptr<Window> window2(CreateTestWindowWithId(2, root_window())); - scoped_ptr<Window> window3(CreateTestWindowWithId(3, root_window())); - - EXPECT_EQ("1 11 12 13 2 3", ChildWindowIDsAsString(root_window())); - - // Remove the delegates of a couple of transients, as if they are closing - // and animating out. - window11->layer()->set_delegate(NULL); - window13->layer()->set_delegate(NULL); - - // Move window1 to the front. All transients should move with it, and their - // order should be preserved. - root_window()->StackChildAtTop(window1.get()); - - EXPECT_EQ("2 3 1 11 12 13", ChildWindowIDsAsString(root_window())); -} - -TEST_F(TransientWindowManagerTest, - StackTransientsLayersRelativeToOtherTransients) { - // Create a window with several transients, then a couple windows on top. - scoped_ptr<Window> window1(CreateTestWindowWithId(1, root_window())); - scoped_ptr<Window> window11(CreateTransientChild(11, window1.get())); - scoped_ptr<Window> window12(CreateTransientChild(12, window1.get())); - scoped_ptr<Window> window13(CreateTransientChild(13, window1.get())); - - EXPECT_EQ("1 11 12 13", ChildWindowIDsAsString(root_window())); - - // Stack 11 above 12. - root_window()->StackChildAbove(window11.get(), window12.get()); - EXPECT_EQ("1 12 11 13", ChildWindowIDsAsString(root_window())); - - // Stack 13 below 12. - root_window()->StackChildBelow(window13.get(), window12.get()); - EXPECT_EQ("1 13 12 11", ChildWindowIDsAsString(root_window())); - - // Stack 11 above 1. - root_window()->StackChildAbove(window11.get(), window1.get()); - EXPECT_EQ("1 11 13 12", ChildWindowIDsAsString(root_window())); - - // Stack 12 below 13. - root_window()->StackChildBelow(window12.get(), window13.get()); - EXPECT_EQ("1 11 12 13", ChildWindowIDsAsString(root_window())); -} - -TEST_F(TransientWindowManagerTest, - StackTransientsLayersRelativeToOtherTransientsNoLayerDelegate) { - // Create a window with several transients, then a couple windows on top. - scoped_ptr<Window> window1(CreateTestWindowWithId(1, root_window())); - scoped_ptr<Window> window11(CreateTransientChild(11, window1.get())); - scoped_ptr<Window> window12(CreateTransientChild(12, window1.get())); - scoped_ptr<Window> window13(CreateTransientChild(13, window1.get())); - scoped_ptr<Window> window2(CreateTestWindowWithId(2, root_window())); - scoped_ptr<Window> window3(CreateTestWindowWithId(3, root_window())); - - EXPECT_EQ("1 11 12 13 2 3", ChildWindowIDsAsString(root_window())); - - window1->layer()->set_delegate(NULL); - - // Stack 1 at top. - root_window()->StackChildAtTop(window1.get()); - EXPECT_EQ("2 3 1 11 12 13", ChildWindowIDsAsString(root_window())); -} - -class StackingMadrigalLayoutManager : public aura::LayoutManager { - public: - explicit StackingMadrigalLayoutManager(Window* root_window) - : root_window_(root_window) { - root_window_->SetLayoutManager(this); - } - virtual ~StackingMadrigalLayoutManager() { - } - - private: - // Overridden from LayoutManager: - virtual void OnWindowResized() override {} - virtual void OnWindowAddedToLayout(Window* child) override {} - virtual void OnWillRemoveWindowFromLayout(Window* child) override {} - virtual void OnWindowRemovedFromLayout(Window* child) override {} - virtual void OnChildWindowVisibilityChanged(Window* child, - bool visible) override { - Window::Windows::const_iterator it = root_window_->children().begin(); - Window* last_window = NULL; - for (; it != root_window_->children().end(); ++it) { - if (*it == child && last_window) { - if (!visible) - root_window_->StackChildAbove(last_window, *it); - else - root_window_->StackChildAbove(*it, last_window); - break; - } - last_window = *it; - } - } - virtual void SetChildBounds(Window* child, - const gfx::Rect& requested_bounds) override { - SetChildBoundsDirect(child, requested_bounds); - } - - Window* root_window_; - - DISALLOW_COPY_AND_ASSIGN(StackingMadrigalLayoutManager); -}; - -class StackingMadrigalVisibilityClient : public aura::client::VisibilityClient { - public: - explicit StackingMadrigalVisibilityClient(Window* root_window) - : ignored_window_(NULL) { - aura::client::SetVisibilityClient(root_window, this); - } - virtual ~StackingMadrigalVisibilityClient() { - } - - void set_ignored_window(Window* ignored_window) { - ignored_window_ = ignored_window; - } - - private: - // Overridden from client::VisibilityClient: - virtual void UpdateLayerVisibility(Window* window, bool visible) override { - if (!visible) { - if (window == ignored_window_) - window->layer()->set_delegate(NULL); - else - window->layer()->SetVisible(visible); - } else { - window->layer()->SetVisible(visible); - } - } - - Window* ignored_window_; - - DISALLOW_COPY_AND_ASSIGN(StackingMadrigalVisibilityClient); -}; - -// This test attempts to reconstruct a circumstance that can happen when the -// aura client attempts to manipulate the visibility and delegate of a layer -// independent of window visibility. -// A use case is where the client attempts to keep a window visible onscreen -// even after code has called Hide() on the window. The use case for this would -// be that window hides are animated (e.g. the window fades out). To prevent -// spurious updating the client code may also clear window's layer's delegate, -// so that the window cannot attempt to paint or update it further. The window -// uses the presence of a NULL layer delegate as a signal in stacking to note -// that the window is being manipulated by such a use case and its stacking -// should not be adjusted. -// One issue that can arise when a window opens two transient children, and the -// first is hidden. Subsequent attempts to activate the transient parent can -// result in the transient parent being stacked above the second transient -// child. A fix is made to Window::StackAbove to prevent this, and this test -// verifies this fix. -TEST_F(TransientWindowManagerTest, StackingMadrigal) { - new StackingMadrigalLayoutManager(root_window()); - StackingMadrigalVisibilityClient visibility_client(root_window()); - - scoped_ptr<Window> window1(CreateTestWindowWithId(1, root_window())); - scoped_ptr<Window> window11(CreateTransientChild(11, window1.get())); - - visibility_client.set_ignored_window(window11.get()); - - window11->Show(); - window11->Hide(); - - // As a transient, window11 should still be stacked above window1, even when - // hidden. - EXPECT_TRUE(aura::test::WindowIsAbove(window11.get(), window1.get())); - EXPECT_TRUE(aura::test::LayerIsAbove(window11.get(), window1.get())); - - // A new transient should still be above window1. It will appear behind - // window11 because we don't stack windows on top of targets with NULL - // delegates. - scoped_ptr<Window> window12(CreateTransientChild(12, window1.get())); - window12->Show(); - - EXPECT_TRUE(aura::test::WindowIsAbove(window12.get(), window1.get())); - EXPECT_TRUE(aura::test::LayerIsAbove(window12.get(), window1.get())); - - // In earlier versions of the StackChildAbove() method, attempting to stack - // window1 above window12 at this point would actually restack the layers - // resulting in window12's layer being below window1's layer (though the - // windows themselves would still be correctly stacked, so events would pass - // through.) - root_window()->StackChildAbove(window1.get(), window12.get()); - - // Both window12 and its layer should be stacked above window1. - EXPECT_TRUE(aura::test::WindowIsAbove(window12.get(), window1.get())); - EXPECT_TRUE(aura::test::LayerIsAbove(window12.get(), window1.get())); -} - -// Test for an issue where attempting to stack a primary window on top of a -// transient with a NULL layer delegate causes that primary window to be moved, -// but the layer order not changed to match. http://crbug.com/112562 -TEST_F(TransientWindowManagerTest, StackOverClosingTransient) { - scoped_ptr<Window> window1(CreateTestWindowWithId(1, root_window())); - scoped_ptr<Window> transient1(CreateTransientChild(11, window1.get())); - scoped_ptr<Window> window2(CreateTestWindowWithId(2, root_window())); - scoped_ptr<Window> transient2(CreateTransientChild(21, window2.get())); - - // Both windows and layers are stacked in creation order. - Window* root = root_window(); - ASSERT_EQ(4u, root->children().size()); - EXPECT_EQ(root->children()[0], window1.get()); - EXPECT_EQ(root->children()[1], transient1.get()); - EXPECT_EQ(root->children()[2], window2.get()); - EXPECT_EQ(root->children()[3], transient2.get()); - ASSERT_EQ(4u, root->layer()->children().size()); - EXPECT_EQ(root->layer()->children()[0], window1->layer()); - EXPECT_EQ(root->layer()->children()[1], transient1->layer()); - EXPECT_EQ(root->layer()->children()[2], window2->layer()); - EXPECT_EQ(root->layer()->children()[3], transient2->layer()); - EXPECT_EQ("1 11 2 21", ChildWindowIDsAsString(root_window())); - - // This brings window1 and its transient to the front. - root->StackChildAtTop(window1.get()); - EXPECT_EQ("2 21 1 11", ChildWindowIDsAsString(root_window())); - - EXPECT_EQ(root->children()[0], window2.get()); - EXPECT_EQ(root->children()[1], transient2.get()); - EXPECT_EQ(root->children()[2], window1.get()); - EXPECT_EQ(root->children()[3], transient1.get()); - EXPECT_EQ(root->layer()->children()[0], window2->layer()); - EXPECT_EQ(root->layer()->children()[1], transient2->layer()); - EXPECT_EQ(root->layer()->children()[2], window1->layer()); - EXPECT_EQ(root->layer()->children()[3], transient1->layer()); - - // Pretend we're closing the top-most transient, then bring window2 to the - // front. This mimics activating a browser window while the status bubble - // is fading out. The transient should stay topmost. - transient1->layer()->set_delegate(NULL); - root->StackChildAtTop(window2.get()); - - EXPECT_EQ(root->children()[0], window1.get()); - EXPECT_EQ(root->children()[1], window2.get()); - EXPECT_EQ(root->children()[2], transient2.get()); - EXPECT_EQ(root->children()[3], transient1.get()); - EXPECT_EQ(root->layer()->children()[0], window1->layer()); - EXPECT_EQ(root->layer()->children()[1], window2->layer()); - EXPECT_EQ(root->layer()->children()[2], transient2->layer()); - EXPECT_EQ(root->layer()->children()[3], transient1->layer()); - - // Close the transient. Remaining windows are stable. - transient1.reset(); - - ASSERT_EQ(3u, root->children().size()); - EXPECT_EQ(root->children()[0], window1.get()); - EXPECT_EQ(root->children()[1], window2.get()); - EXPECT_EQ(root->children()[2], transient2.get()); - ASSERT_EQ(3u, root->layer()->children().size()); - EXPECT_EQ(root->layer()->children()[0], window1->layer()); - EXPECT_EQ(root->layer()->children()[1], window2->layer()); - EXPECT_EQ(root->layer()->children()[2], transient2->layer()); - - // Open another window on top. - scoped_ptr<Window> window3(CreateTestWindowWithId(3, root_window())); - - ASSERT_EQ(4u, root->children().size()); - EXPECT_EQ(root->children()[0], window1.get()); - EXPECT_EQ(root->children()[1], window2.get()); - EXPECT_EQ(root->children()[2], transient2.get()); - EXPECT_EQ(root->children()[3], window3.get()); - ASSERT_EQ(4u, root->layer()->children().size()); - EXPECT_EQ(root->layer()->children()[0], window1->layer()); - EXPECT_EQ(root->layer()->children()[1], window2->layer()); - EXPECT_EQ(root->layer()->children()[2], transient2->layer()); - EXPECT_EQ(root->layer()->children()[3], window3->layer()); - - // Pretend we're closing the topmost non-transient window, then bring - // window2 to the top. It should not move. - window3->layer()->set_delegate(NULL); - root->StackChildAtTop(window2.get()); - - ASSERT_EQ(4u, root->children().size()); - EXPECT_EQ(root->children()[0], window1.get()); - EXPECT_EQ(root->children()[1], window2.get()); - EXPECT_EQ(root->children()[2], transient2.get()); - EXPECT_EQ(root->children()[3], window3.get()); - ASSERT_EQ(4u, root->layer()->children().size()); - EXPECT_EQ(root->layer()->children()[0], window1->layer()); - EXPECT_EQ(root->layer()->children()[1], window2->layer()); - EXPECT_EQ(root->layer()->children()[2], transient2->layer()); - EXPECT_EQ(root->layer()->children()[3], window3->layer()); - - // Bring window1 to the top. It should move ahead of window2, but not - // ahead of window3 (with NULL delegate). - root->StackChildAtTop(window1.get()); - - ASSERT_EQ(4u, root->children().size()); - EXPECT_EQ(root->children()[0], window2.get()); - EXPECT_EQ(root->children()[1], transient2.get()); - EXPECT_EQ(root->children()[2], window1.get()); - EXPECT_EQ(root->children()[3], window3.get()); - ASSERT_EQ(4u, root->layer()->children().size()); - EXPECT_EQ(root->layer()->children()[0], window2->layer()); - EXPECT_EQ(root->layer()->children()[1], transient2->layer()); - EXPECT_EQ(root->layer()->children()[2], window1->layer()); - EXPECT_EQ(root->layer()->children()[3], window3->layer()); -} - -// Verifies TransientWindowObserver is notified appropriately. -TEST_F(TransientWindowManagerTest, TransientWindowObserverNotified) { - scoped_ptr<Window> parent(CreateTestWindowWithId(0, root_window())); - scoped_ptr<Window> w1(CreateTestWindowWithId(1, parent.get())); - - TestTransientWindowObserver test_observer; - TransientWindowManager::Get(parent.get())->AddObserver(&test_observer); - - AddTransientChild(parent.get(), w1.get()); - EXPECT_EQ(1, test_observer.add_count()); - EXPECT_EQ(0, test_observer.remove_count()); - - RemoveTransientChild(parent.get(), w1.get()); - EXPECT_EQ(1, test_observer.add_count()); - EXPECT_EQ(1, test_observer.remove_count()); - - TransientWindowManager::Get(parent.get())->RemoveObserver(&test_observer); -} - -} // namespace wm
diff --git a/ui/wm/core/transient_window_observer.h b/ui/wm/core/transient_window_observer.h deleted file mode 100644 index aff5af5..0000000 --- a/ui/wm/core/transient_window_observer.h +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_CORE_TRANSIENT_WINDOW_OBSERVER_H_ -#define UI_WM_CORE_TRANSIENT_WINDOW_OBSERVER_H_ - -#include "ui/wm/wm_export.h" - -namespace aura { -class Window; -} - -namespace wm { - -class WM_EXPORT TransientWindowObserver { - public: - // Called when a transient child is added to |window|. - virtual void OnTransientChildAdded(aura::Window* window, - aura::Window* transient) = 0; - - // Called when a transient child is removed from |window|. - virtual void OnTransientChildRemoved(aura::Window* window, - aura::Window* transient) = 0; - - protected: - virtual ~TransientWindowObserver() {} -}; - -} // namespace wm - -#endif // UI_WM_CORE_TRANSIENT_WINDOW_OBSERVER_H_
diff --git a/ui/wm/core/transient_window_stacking_client.cc b/ui/wm/core/transient_window_stacking_client.cc deleted file mode 100644 index f8dc42c..0000000 --- a/ui/wm/core/transient_window_stacking_client.cc +++ /dev/null
@@ -1,131 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/transient_window_stacking_client.h" - -#include <algorithm> - -#include "ui/wm/core/transient_window_manager.h" -#include "ui/wm/core/window_util.h" - -using aura::Window; - -namespace wm { - -namespace { - -// Populates |ancestors| with all transient ancestors of |window| that are -// siblings of |window|. Returns true if any ancestors were found, false if not. -bool GetAllTransientAncestors(Window* window, Window::Windows* ancestors) { - Window* parent = window->parent(); - for (; window; window = GetTransientParent(window)) { - if (window->parent() == parent) - ancestors->push_back(window); - } - return (!ancestors->empty()); -} - -// Replaces |window1| and |window2| with their possible transient ancestors that -// are still siblings (have a common transient parent). |window1| and |window2| -// are not modified if such ancestors cannot be found. -void FindCommonTransientAncestor(Window** window1, Window** window2) { - DCHECK(window1); - DCHECK(window2); - DCHECK(*window1); - DCHECK(*window2); - // Assemble chains of ancestors of both windows. - Window::Windows ancestors1; - Window::Windows ancestors2; - if (!GetAllTransientAncestors(*window1, &ancestors1) || - !GetAllTransientAncestors(*window2, &ancestors2)) { - return; - } - // Walk the two chains backwards and look for the first difference. - Window::Windows::reverse_iterator it1 = ancestors1.rbegin(); - Window::Windows::reverse_iterator it2 = ancestors2.rbegin(); - for (; it1 != ancestors1.rend() && it2 != ancestors2.rend(); ++it1, ++it2) { - if (*it1 != *it2) { - *window1 = *it1; - *window2 = *it2; - break; - } - } -} - -// Adjusts |target| so that we don't attempt to stack on top of a window with a -// NULL delegate. -void SkipNullDelegates(Window::StackDirection direction, Window** target) { - const Window::Windows& children((*target)->parent()->children()); - size_t target_i = - std::find(children.begin(), children.end(), *target) - - children.begin(); - - // By convention we don't stack on top of windows with layers with NULL - // delegates. Walk backward to find a valid target window. See tests - // TransientWindowManagerTest.StackingMadrigal and StackOverClosingTransient - // for an explanation of this. - while (target_i > 0) { - const size_t index = direction == Window::STACK_ABOVE ? - target_i : target_i - 1; - if (!children[index]->layer() || - children[index]->layer()->delegate() != NULL) - break; - --target_i; - } - *target = children[target_i]; -} - -} // namespace - -// static -TransientWindowStackingClient* TransientWindowStackingClient::instance_ = NULL; - -TransientWindowStackingClient::TransientWindowStackingClient() { - instance_ = this; -} - -TransientWindowStackingClient::~TransientWindowStackingClient() { - if (instance_ == this) - instance_ = NULL; -} - -bool TransientWindowStackingClient::AdjustStacking( - Window** child, - Window** target, - Window::StackDirection* direction) { - const TransientWindowManager* transient_manager = - TransientWindowManager::Get(static_cast<const Window*>(*child)); - if (transient_manager && transient_manager->IsStackingTransient(*target)) - return true; - - // For windows that have transient children stack the transient ancestors that - // are siblings. This prevents one transient group from being inserted in the - // middle of another. - FindCommonTransientAncestor(child, target); - - // When stacking above skip to the topmost transient descendant of the target. - if (*direction == Window::STACK_ABOVE && - !HasTransientAncestor(*child, *target)) { - const Window::Windows& siblings((*child)->parent()->children()); - size_t target_i = - std::find(siblings.begin(), siblings.end(), *target) - siblings.begin(); - while (target_i + 1 < siblings.size() && - HasTransientAncestor(siblings[target_i + 1], *target)) { - ++target_i; - } - *target = siblings[target_i]; - } - - SkipNullDelegates(*direction, target); - - // If we couldn't find a valid target position, don't move anything. - if (*direction == Window::STACK_ABOVE && - ((*target)->layer() && (*target)->layer()->delegate() == NULL)) { - return false; - } - - return *child != *target; -} - -} // namespace wm
diff --git a/ui/wm/core/transient_window_stacking_client.h b/ui/wm/core/transient_window_stacking_client.h deleted file mode 100644 index ce9d55c..0000000 --- a/ui/wm/core/transient_window_stacking_client.h +++ /dev/null
@@ -1,37 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_CORE_TRANSIENT_WINDOW_STACKING_CLIENT_H_ -#define UI_WM_CORE_TRANSIENT_WINDOW_STACKING_CLIENT_H_ - -#include "ui/aura/client/window_stacking_client.h" -#include "ui/wm/wm_export.h" - -namespace wm { - -class TransientWindowManager; - -class WM_EXPORT TransientWindowStackingClient - : public aura::client::WindowStackingClient { - public: - TransientWindowStackingClient(); - virtual ~TransientWindowStackingClient(); - - // WindowStackingClient: - virtual bool AdjustStacking(aura::Window** child, - aura::Window** target, - aura::Window::StackDirection* direction) override; - - private: - // Purely for DCHECKs. - friend class TransientWindowManager; - - static TransientWindowStackingClient* instance_; - - DISALLOW_COPY_AND_ASSIGN(TransientWindowStackingClient); -}; - -} // namespace wm - -#endif // UI_WM_CORE_TRANSIENT_WINDOW_STACKING_CLIENT_H_
diff --git a/ui/wm/core/transient_window_stacking_client_unittest.cc b/ui/wm/core/transient_window_stacking_client_unittest.cc deleted file mode 100644 index c067496..0000000 --- a/ui/wm/core/transient_window_stacking_client_unittest.cc +++ /dev/null
@@ -1,215 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/transient_window_stacking_client.h" - -#include "base/memory/scoped_ptr.h" -#include "ui/aura/test/aura_test_base.h" -#include "ui/aura/test/test_windows.h" -#include "ui/compositor/test/test_layers.h" -#include "ui/wm/core/window_util.h" - -using aura::test::ChildWindowIDsAsString; -using aura::test::CreateTestWindowWithId; -using aura::Window; - -namespace wm { - -class TransientWindowStackingClientTest : public aura::test::AuraTestBase { - public: - TransientWindowStackingClientTest() {} - virtual ~TransientWindowStackingClientTest() {} - - virtual void SetUp() override { - AuraTestBase::SetUp(); - client_.reset(new TransientWindowStackingClient); - aura::client::SetWindowStackingClient(client_.get()); - } - - virtual void TearDown() override { - aura::client::SetWindowStackingClient(NULL); - AuraTestBase::TearDown(); - } - - private: - scoped_ptr<TransientWindowStackingClient> client_; - DISALLOW_COPY_AND_ASSIGN(TransientWindowStackingClientTest); -}; - -// Tests that transient children are stacked as a unit when using stack above. -TEST_F(TransientWindowStackingClientTest, TransientChildrenGroupAbove) { - scoped_ptr<Window> parent(CreateTestWindowWithId(0, root_window())); - scoped_ptr<Window> w1(CreateTestWindowWithId(1, parent.get())); - Window* w11 = CreateTestWindowWithId(11, parent.get()); - scoped_ptr<Window> w2(CreateTestWindowWithId(2, parent.get())); - Window* w21 = CreateTestWindowWithId(21, parent.get()); - Window* w211 = CreateTestWindowWithId(211, parent.get()); - Window* w212 = CreateTestWindowWithId(212, parent.get()); - Window* w213 = CreateTestWindowWithId(213, parent.get()); - Window* w22 = CreateTestWindowWithId(22, parent.get()); - ASSERT_EQ(8u, parent->children().size()); - - AddTransientChild(w1.get(), w11); // w11 is now owned by w1. - AddTransientChild(w2.get(), w21); // w21 is now owned by w2. - AddTransientChild(w2.get(), w22); // w22 is now owned by w2. - AddTransientChild(w21, w211); // w211 is now owned by w21. - AddTransientChild(w21, w212); // w212 is now owned by w21. - AddTransientChild(w21, w213); // w213 is now owned by w21. - EXPECT_EQ("1 11 2 21 211 212 213 22", ChildWindowIDsAsString(parent.get())); - - // Stack w1 at the top (end), this should force w11 to be last (on top of w1). - parent->StackChildAtTop(w1.get()); - EXPECT_EQ(w11, parent->children().back()); - EXPECT_EQ("2 21 211 212 213 22 1 11", ChildWindowIDsAsString(parent.get())); - - // This tests that the order in children_ array rather than in - // transient_children_ array is used when reinserting transient children. - // If transient_children_ array was used '22' would be following '21'. - parent->StackChildAtTop(w2.get()); - EXPECT_EQ(w22, parent->children().back()); - EXPECT_EQ("1 11 2 21 211 212 213 22", ChildWindowIDsAsString(parent.get())); - - parent->StackChildAbove(w11, w2.get()); - EXPECT_EQ(w11, parent->children().back()); - EXPECT_EQ("2 21 211 212 213 22 1 11", ChildWindowIDsAsString(parent.get())); - - parent->StackChildAbove(w21, w1.get()); - EXPECT_EQ(w22, parent->children().back()); - EXPECT_EQ("1 11 2 21 211 212 213 22", ChildWindowIDsAsString(parent.get())); - - parent->StackChildAbove(w21, w22); - EXPECT_EQ(w213, parent->children().back()); - EXPECT_EQ("1 11 2 22 21 211 212 213", ChildWindowIDsAsString(parent.get())); - - parent->StackChildAbove(w11, w21); - EXPECT_EQ(w11, parent->children().back()); - EXPECT_EQ("2 22 21 211 212 213 1 11", ChildWindowIDsAsString(parent.get())); - - parent->StackChildAbove(w213, w21); - EXPECT_EQ(w11, parent->children().back()); - EXPECT_EQ("2 22 21 213 211 212 1 11", ChildWindowIDsAsString(parent.get())); - - // No change when stacking a transient parent above its transient child. - parent->StackChildAbove(w21, w211); - EXPECT_EQ(w11, parent->children().back()); - EXPECT_EQ("2 22 21 213 211 212 1 11", ChildWindowIDsAsString(parent.get())); - - // This tests that the order in children_ array rather than in - // transient_children_ array is used when reinserting transient children. - // If transient_children_ array was used '22' would be following '21'. - parent->StackChildAbove(w2.get(), w1.get()); - EXPECT_EQ(w212, parent->children().back()); - EXPECT_EQ("1 11 2 22 21 213 211 212", ChildWindowIDsAsString(parent.get())); - - parent->StackChildAbove(w11, w213); - EXPECT_EQ(w11, parent->children().back()); - EXPECT_EQ("2 22 21 213 211 212 1 11", ChildWindowIDsAsString(parent.get())); -} - -// Tests that transient children are stacked as a unit when using stack below. -TEST_F(TransientWindowStackingClientTest, TransientChildrenGroupBelow) { - scoped_ptr<Window> parent(CreateTestWindowWithId(0, root_window())); - scoped_ptr<Window> w1(CreateTestWindowWithId(1, parent.get())); - Window* w11 = CreateTestWindowWithId(11, parent.get()); - scoped_ptr<Window> w2(CreateTestWindowWithId(2, parent.get())); - Window* w21 = CreateTestWindowWithId(21, parent.get()); - Window* w211 = CreateTestWindowWithId(211, parent.get()); - Window* w212 = CreateTestWindowWithId(212, parent.get()); - Window* w213 = CreateTestWindowWithId(213, parent.get()); - Window* w22 = CreateTestWindowWithId(22, parent.get()); - ASSERT_EQ(8u, parent->children().size()); - - AddTransientChild(w1.get(), w11); // w11 is now owned by w1. - AddTransientChild(w2.get(), w21); // w21 is now owned by w2. - AddTransientChild(w2.get(), w22); // w22 is now owned by w2. - AddTransientChild(w21, w211); // w211 is now owned by w21. - AddTransientChild(w21, w212); // w212 is now owned by w21. - AddTransientChild(w21, w213); // w213 is now owned by w21. - EXPECT_EQ("1 11 2 21 211 212 213 22", ChildWindowIDsAsString(parent.get())); - - // Stack w2 at the bottom, this should force w11 to be last (on top of w1). - // This also tests that the order in children_ array rather than in - // transient_children_ array is used when reinserting transient children. - // If transient_children_ array was used '22' would be following '21'. - parent->StackChildAtBottom(w2.get()); - EXPECT_EQ(w11, parent->children().back()); - EXPECT_EQ("2 21 211 212 213 22 1 11", ChildWindowIDsAsString(parent.get())); - - parent->StackChildAtBottom(w1.get()); - EXPECT_EQ(w22, parent->children().back()); - EXPECT_EQ("1 11 2 21 211 212 213 22", ChildWindowIDsAsString(parent.get())); - - parent->StackChildBelow(w21, w1.get()); - EXPECT_EQ(w11, parent->children().back()); - EXPECT_EQ("2 21 211 212 213 22 1 11", ChildWindowIDsAsString(parent.get())); - - parent->StackChildBelow(w11, w2.get()); - EXPECT_EQ(w22, parent->children().back()); - EXPECT_EQ("1 11 2 21 211 212 213 22", ChildWindowIDsAsString(parent.get())); - - parent->StackChildBelow(w22, w21); - EXPECT_EQ(w213, parent->children().back()); - EXPECT_EQ("1 11 2 22 21 211 212 213", ChildWindowIDsAsString(parent.get())); - - parent->StackChildBelow(w21, w11); - EXPECT_EQ(w11, parent->children().back()); - EXPECT_EQ("2 22 21 211 212 213 1 11", ChildWindowIDsAsString(parent.get())); - - parent->StackChildBelow(w213, w211); - EXPECT_EQ(w11, parent->children().back()); - EXPECT_EQ("2 22 21 213 211 212 1 11", ChildWindowIDsAsString(parent.get())); - - // No change when stacking a transient parent below its transient child. - parent->StackChildBelow(w21, w211); - EXPECT_EQ(w11, parent->children().back()); - EXPECT_EQ("2 22 21 213 211 212 1 11", ChildWindowIDsAsString(parent.get())); - - parent->StackChildBelow(w1.get(), w2.get()); - EXPECT_EQ(w212, parent->children().back()); - EXPECT_EQ("1 11 2 22 21 213 211 212", ChildWindowIDsAsString(parent.get())); - - parent->StackChildBelow(w213, w11); - EXPECT_EQ(w11, parent->children().back()); - EXPECT_EQ("2 22 21 213 211 212 1 11", ChildWindowIDsAsString(parent.get())); -} - -TEST_F(TransientWindowStackingClientTest, - StackWindowsWhoseLayersHaveNoDelegate) { - scoped_ptr<Window> window1(CreateTestWindowWithId(1, root_window())); - window1->layer()->set_name("1"); - scoped_ptr<Window> window2(CreateTestWindowWithId(2, root_window())); - window2->layer()->set_name("2"); - scoped_ptr<Window> window3(CreateTestWindowWithId(3, root_window())); - window3->layer()->set_name("3"); - - // This brings |window1| (and its layer) to the front. - root_window()->StackChildAbove(window1.get(), window3.get()); - EXPECT_EQ("2 3 1", ChildWindowIDsAsString(root_window())); - EXPECT_EQ("2 3 1", - ui::test::ChildLayerNamesAsString(*root_window()->layer())); - - // Since |window1| does not have a delegate, |window2| should not move in - // front of it, nor should its layer. - window1->layer()->set_delegate(NULL); - root_window()->StackChildAbove(window2.get(), window1.get()); - EXPECT_EQ("3 2 1", ChildWindowIDsAsString(root_window())); - EXPECT_EQ("3 2 1", - ui::test::ChildLayerNamesAsString(*root_window()->layer())); - - // It should still be possible to stack |window3| immediately below |window1|. - root_window()->StackChildBelow(window3.get(), window1.get()); - EXPECT_EQ("2 3 1", ChildWindowIDsAsString(root_window())); - EXPECT_EQ("2 3 1", - ui::test::ChildLayerNamesAsString(*root_window()->layer())); - - // Since neither |window3| nor |window1| have a delegate, |window2| should - // not move in front of either. - window3->layer()->set_delegate(NULL); - root_window()->StackChildBelow(window2.get(), window1.get()); - EXPECT_EQ("2 3 1", ChildWindowIDsAsString(root_window())); - EXPECT_EQ("2 3 1", - ui::test::ChildLayerNamesAsString(*root_window()->layer())); -} - -} // namespace wm
diff --git a/ui/wm/core/user_activity_detector.cc b/ui/wm/core/user_activity_detector.cc deleted file mode 100644 index 56bf563..0000000 --- a/ui/wm/core/user_activity_detector.cc +++ /dev/null
@@ -1,112 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/user_activity_detector.h" - -#include "base/format_macros.h" -#include "base/logging.h" -#include "base/strings/stringprintf.h" -#include "ui/events/event.h" -#include "ui/wm/core/user_activity_observer.h" - -namespace wm { - -namespace { - -// Returns a string describing |event|. -std::string GetEventDebugString(const ui::Event* event) { - std::string details = base::StringPrintf( - "type=%d name=%s flags=%d time=%" PRId64, - event->type(), event->name().c_str(), event->flags(), - event->time_stamp().InMilliseconds()); - - if (event->IsKeyEvent()) { - details += base::StringPrintf(" key_code=%d", - static_cast<const ui::KeyEvent*>(event)->key_code()); - } else if (event->IsMouseEvent() || event->IsTouchEvent() || - event->IsGestureEvent()) { - details += base::StringPrintf(" location=%s", - static_cast<const ui::LocatedEvent*>( - event)->location().ToString().c_str()); - } - - return details; -} - -} // namespace - -const int UserActivityDetector::kNotifyIntervalMs = 200; - -// Too low and mouse events generated at the tail end of reconfiguration -// will be reported as user activity and turn the screen back on; too high -// and we'll ignore legitimate activity. -const int UserActivityDetector::kDisplayPowerChangeIgnoreMouseMs = 1000; - -UserActivityDetector::UserActivityDetector() { -} - -UserActivityDetector::~UserActivityDetector() { -} - -bool UserActivityDetector::HasObserver(UserActivityObserver* observer) const { - return observers_.HasObserver(observer); -} - -void UserActivityDetector::AddObserver(UserActivityObserver* observer) { - observers_.AddObserver(observer); -} - -void UserActivityDetector::RemoveObserver(UserActivityObserver* observer) { - observers_.RemoveObserver(observer); -} - -void UserActivityDetector::OnDisplayPowerChanging() { - honor_mouse_events_time_ = GetCurrentTime() + - base::TimeDelta::FromMilliseconds(kDisplayPowerChangeIgnoreMouseMs); -} - -void UserActivityDetector::OnKeyEvent(ui::KeyEvent* event) { - HandleActivity(event); -} - -void UserActivityDetector::OnMouseEvent(ui::MouseEvent* event) { - if (event->flags() & ui::EF_IS_SYNTHESIZED) - return; - if (!honor_mouse_events_time_.is_null() && - GetCurrentTime() < honor_mouse_events_time_) - return; - - HandleActivity(event); -} - -void UserActivityDetector::OnScrollEvent(ui::ScrollEvent* event) { - HandleActivity(event); -} - -void UserActivityDetector::OnTouchEvent(ui::TouchEvent* event) { - HandleActivity(event); -} - -void UserActivityDetector::OnGestureEvent(ui::GestureEvent* event) { - HandleActivity(event); -} - -base::TimeTicks UserActivityDetector::GetCurrentTime() const { - return !now_for_test_.is_null() ? now_for_test_ : base::TimeTicks::Now(); -} - -void UserActivityDetector::HandleActivity(const ui::Event* event) { - base::TimeTicks now = GetCurrentTime(); - last_activity_time_ = now; - if (last_observer_notification_time_.is_null() || - (now - last_observer_notification_time_).InMillisecondsF() >= - kNotifyIntervalMs) { - if (VLOG_IS_ON(1)) - VLOG(1) << "Reporting user activity: " << GetEventDebugString(event); - FOR_EACH_OBSERVER(UserActivityObserver, observers_, OnUserActivity(event)); - last_observer_notification_time_ = now; - } -} - -} // namespace wm
diff --git a/ui/wm/core/user_activity_detector.h b/ui/wm/core/user_activity_detector.h deleted file mode 100644 index 7e5db9f..0000000 --- a/ui/wm/core/user_activity_detector.h +++ /dev/null
@@ -1,81 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_CORE_USER_ACTIVITY_DETECTOR_H_ -#define UI_WM_CORE_USER_ACTIVITY_DETECTOR_H_ - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/observer_list.h" -#include "base/time/time.h" -#include "ui/events/event_handler.h" -#include "ui/wm/wm_export.h" - -namespace wm { - -class UserActivityObserver; - -// Watches for input events and notifies observers that the user is active. -class WM_EXPORT UserActivityDetector : public ui::EventHandler { - public: - // Minimum amount of time between notifications to observers. - static const int kNotifyIntervalMs; - - // Amount of time that mouse events should be ignored after notification - // is received that displays' power states are being changed. - static const int kDisplayPowerChangeIgnoreMouseMs; - - UserActivityDetector(); - virtual ~UserActivityDetector(); - - base::TimeTicks last_activity_time() const { return last_activity_time_; } - - void set_now_for_test(base::TimeTicks now) { now_for_test_ = now; } - - bool HasObserver(UserActivityObserver* observer) const; - void AddObserver(UserActivityObserver* observer); - void RemoveObserver(UserActivityObserver* observer); - - // Called when displays are about to be turned on or off. - void OnDisplayPowerChanging(); - - // ui::EventHandler implementation. - virtual void OnKeyEvent(ui::KeyEvent* event) override; - virtual void OnMouseEvent(ui::MouseEvent* event) override; - virtual void OnScrollEvent(ui::ScrollEvent* event) override; - virtual void OnTouchEvent(ui::TouchEvent* event) override; - virtual void OnGestureEvent(ui::GestureEvent* event) override; - - private: - // Returns |now_for_test_| if set or base::TimeTicks::Now() otherwise. - base::TimeTicks GetCurrentTime() const; - - // Updates |last_activity_time_|. Additionally notifies observers and - // updates |last_observer_notification_time_| if enough time has passed - // since the last notification. - void HandleActivity(const ui::Event* event); - - ObserverList<UserActivityObserver> observers_; - - // Last time at which user activity was observed. - base::TimeTicks last_activity_time_; - - // Last time at which we notified observers that the user was active. - base::TimeTicks last_observer_notification_time_; - - // If set, used when the current time is needed. This can be set by tests to - // simulate the passage of time. - base::TimeTicks now_for_test_; - - // If set, mouse events will be ignored until this time is reached. This - // is to avoid reporting mouse events that occur when displays are turned - // on or off as user activity. - base::TimeTicks honor_mouse_events_time_; - - DISALLOW_COPY_AND_ASSIGN(UserActivityDetector); -}; - -} // namespace wm - -#endif // UI_WM_CORE_USER_ACTIVITY_DETECTOR_H_
diff --git a/ui/wm/core/user_activity_detector_unittest.cc b/ui/wm/core/user_activity_detector_unittest.cc deleted file mode 100644 index 0273093..0000000 --- a/ui/wm/core/user_activity_detector_unittest.cc +++ /dev/null
@@ -1,202 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/user_activity_detector.h" - -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "base/time/time.h" -#include "ui/aura/test/aura_test_base.h" -#include "ui/events/event.h" -#include "ui/events/event_constants.h" -#include "ui/events/keycodes/keyboard_codes.h" -#include "ui/gfx/point.h" -#include "ui/wm/core/user_activity_observer.h" - -namespace wm { - -// Implementation that just counts the number of times we've been told that the -// user is active. -class TestUserActivityObserver : public UserActivityObserver { - public: - TestUserActivityObserver() : num_invocations_(0) {} - - int num_invocations() const { return num_invocations_; } - void reset_stats() { num_invocations_ = 0; } - - // UserActivityObserver implementation. - virtual void OnUserActivity(const ui::Event* event) override { - num_invocations_++; - } - - private: - // Number of times that OnUserActivity() has been called. - int num_invocations_; - - DISALLOW_COPY_AND_ASSIGN(TestUserActivityObserver); -}; - -class UserActivityDetectorTest : public aura::test::AuraTestBase { - public: - UserActivityDetectorTest() {} - virtual ~UserActivityDetectorTest() {} - - virtual void SetUp() override { - AuraTestBase::SetUp(); - observer_.reset(new TestUserActivityObserver); - detector_.reset(new UserActivityDetector); - detector_->AddObserver(observer_.get()); - - now_ = base::TimeTicks::Now(); - detector_->set_now_for_test(now_); - } - - virtual void TearDown() override { - detector_->RemoveObserver(observer_.get()); - AuraTestBase::TearDown(); - } - - protected: - // Move |detector_|'s idea of the current time forward by |delta|. - void AdvanceTime(base::TimeDelta delta) { - now_ += delta; - detector_->set_now_for_test(now_); - } - - scoped_ptr<UserActivityDetector> detector_; - scoped_ptr<TestUserActivityObserver> observer_; - - base::TimeTicks now_; - - private: - DISALLOW_COPY_AND_ASSIGN(UserActivityDetectorTest); -}; - -// Checks that the observer is notified in response to different types of input -// events. -TEST_F(UserActivityDetectorTest, Basic) { - ui::KeyEvent key_event(ui::ET_KEY_PRESSED, ui::VKEY_A, ui::EF_NONE); - detector_->OnKeyEvent(&key_event); - EXPECT_FALSE(key_event.handled()); - EXPECT_EQ(now_.ToInternalValue(), - detector_->last_activity_time().ToInternalValue()); - EXPECT_EQ(1, observer_->num_invocations()); - observer_->reset_stats(); - - base::TimeDelta advance_delta = base::TimeDelta::FromMilliseconds( - UserActivityDetector::kNotifyIntervalMs); - AdvanceTime(advance_delta); - ui::MouseEvent mouse_event( - ui::ET_MOUSE_MOVED, gfx::Point(), gfx::Point(), ui::EF_NONE, ui::EF_NONE); - detector_->OnMouseEvent(&mouse_event); - EXPECT_FALSE(mouse_event.handled()); - EXPECT_EQ(now_.ToInternalValue(), - detector_->last_activity_time().ToInternalValue()); - EXPECT_EQ(1, observer_->num_invocations()); - observer_->reset_stats(); - - base::TimeTicks time_before_ignore = now_; - - // Temporarily ignore mouse events when displays are turned on or off. - detector_->OnDisplayPowerChanging(); - detector_->OnMouseEvent(&mouse_event); - EXPECT_FALSE(mouse_event.handled()); - EXPECT_EQ(time_before_ignore.ToInternalValue(), - detector_->last_activity_time().ToInternalValue()); - EXPECT_EQ(0, observer_->num_invocations()); - observer_->reset_stats(); - - const base::TimeDelta kIgnoreMouseTime = - base::TimeDelta::FromMilliseconds( - UserActivityDetector::kDisplayPowerChangeIgnoreMouseMs); - AdvanceTime(kIgnoreMouseTime / 2); - detector_->OnMouseEvent(&mouse_event); - EXPECT_FALSE(mouse_event.handled()); - EXPECT_EQ(time_before_ignore.ToInternalValue(), - detector_->last_activity_time().ToInternalValue()); - EXPECT_EQ(0, observer_->num_invocations()); - observer_->reset_stats(); - - // After enough time has passed, mouse events should be reported again. - AdvanceTime(std::max(kIgnoreMouseTime, advance_delta)); - detector_->OnMouseEvent(&mouse_event); - EXPECT_FALSE(mouse_event.handled()); - EXPECT_EQ(now_.ToInternalValue(), - detector_->last_activity_time().ToInternalValue()); - EXPECT_EQ(1, observer_->num_invocations()); - observer_->reset_stats(); - - AdvanceTime(advance_delta); - ui::TouchEvent touch_event( - ui::ET_TOUCH_PRESSED, gfx::Point(), 0, base::TimeDelta()); - detector_->OnTouchEvent(&touch_event); - EXPECT_FALSE(touch_event.handled()); - EXPECT_EQ(now_.ToInternalValue(), - detector_->last_activity_time().ToInternalValue()); - EXPECT_EQ(1, observer_->num_invocations()); - observer_->reset_stats(); - - AdvanceTime(advance_delta); - ui::GestureEvent gesture_event( - 0, - 0, - ui::EF_NONE, - base::TimeDelta::FromMilliseconds(base::Time::Now().ToDoubleT() * 1000), - ui::GestureEventDetails(ui::ET_GESTURE_TAP)); - detector_->OnGestureEvent(&gesture_event); - EXPECT_FALSE(gesture_event.handled()); - EXPECT_EQ(now_.ToInternalValue(), - detector_->last_activity_time().ToInternalValue()); - EXPECT_EQ(1, observer_->num_invocations()); - observer_->reset_stats(); -} - -// Checks that observers aren't notified too frequently. -TEST_F(UserActivityDetectorTest, RateLimitNotifications) { - // The observer should be notified about a key event. - ui::KeyEvent event(ui::ET_KEY_PRESSED, ui::VKEY_A, ui::EF_NONE); - detector_->OnKeyEvent(&event); - EXPECT_FALSE(event.handled()); - EXPECT_EQ(1, observer_->num_invocations()); - observer_->reset_stats(); - - // It shouldn't be notified if a second event occurs in the same instant in - // time. - detector_->OnKeyEvent(&event); - EXPECT_FALSE(event.handled()); - EXPECT_EQ(0, observer_->num_invocations()); - observer_->reset_stats(); - - // Advance the time, but not quite enough for another notification to be sent. - AdvanceTime( - base::TimeDelta::FromMilliseconds( - UserActivityDetector::kNotifyIntervalMs - 100)); - detector_->OnKeyEvent(&event); - EXPECT_FALSE(event.handled()); - EXPECT_EQ(0, observer_->num_invocations()); - observer_->reset_stats(); - - // Advance time by the notification interval, definitely moving out of the - // rate limit. This should let us trigger another notification. - AdvanceTime(base::TimeDelta::FromMilliseconds( - UserActivityDetector::kNotifyIntervalMs)); - - detector_->OnKeyEvent(&event); - EXPECT_FALSE(event.handled()); - EXPECT_EQ(1, observer_->num_invocations()); -} - -// Checks that the detector ignores synthetic mouse events. -TEST_F(UserActivityDetectorTest, IgnoreSyntheticMouseEvents) { - ui::MouseEvent mouse_event( - ui::ET_MOUSE_MOVED, gfx::Point(), gfx::Point(), ui::EF_IS_SYNTHESIZED, - ui::EF_NONE); - detector_->OnMouseEvent(&mouse_event); - EXPECT_FALSE(mouse_event.handled()); - EXPECT_EQ(base::TimeTicks().ToInternalValue(), - detector_->last_activity_time().ToInternalValue()); - EXPECT_EQ(0, observer_->num_invocations()); -} - -} // namespace wm
diff --git a/ui/wm/core/user_activity_observer.h b/ui/wm/core/user_activity_observer.h deleted file mode 100644 index 0fb35a6..0000000 --- a/ui/wm/core/user_activity_observer.h +++ /dev/null
@@ -1,35 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_CORE_USER_ACTIVITY_OBSERVER_H_ -#define UI_WM_CORE_USER_ACTIVITY_OBSERVER_H_ - -#include "base/basictypes.h" -#include "ui/wm/wm_export.h" - -namespace ui { -class Event; -} - -namespace wm { - -// Interface for classes that want to be notified about user activity. -// Implementations should register themselves with UserActivityDetector. -class WM_EXPORT UserActivityObserver { - public: - // Invoked periodically while the user is active (i.e. generating input - // events). |event| is the event that triggered the notification; it may - // be NULL in some cases (e.g. testing or synthetic invocations). - virtual void OnUserActivity(const ui::Event* event) = 0; - - protected: - UserActivityObserver() {} - virtual ~UserActivityObserver() {} - - DISALLOW_COPY_AND_ASSIGN(UserActivityObserver); -}; - -} // namespace wm - -#endif // UI_WM_CORE_USER_ACTIVITY_OBSERVER_H_
diff --git a/ui/wm/core/visibility_controller.cc b/ui/wm/core/visibility_controller.cc deleted file mode 100644 index fc187a9..0000000 --- a/ui/wm/core/visibility_controller.cc +++ /dev/null
@@ -1,89 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/visibility_controller.h" - -#include "ui/aura/window.h" -#include "ui/aura/window_property.h" -#include "ui/compositor/layer.h" -#include "ui/wm/core/window_animations.h" - -namespace wm { - -namespace { - -// Property set on all windows whose child windows' visibility changes are -// animated. -DEFINE_WINDOW_PROPERTY_KEY( - bool, kChildWindowVisibilityChangesAnimatedKey, false); - -bool ShouldAnimateWindow(aura::Window* window) { - return window->parent() && window->parent()->GetProperty( - kChildWindowVisibilityChangesAnimatedKey); -} - -} // namespace - -VisibilityController::VisibilityController() { -} - -VisibilityController::~VisibilityController() { -} - -bool VisibilityController::CallAnimateOnChildWindowVisibilityChanged( - aura::Window* window, - bool visible) { - return AnimateOnChildWindowVisibilityChanged(window, visible); -} - -void VisibilityController::UpdateLayerVisibility(aura::Window* window, - bool visible) { - bool animated = window->type() != ui::wm::WINDOW_TYPE_CONTROL && - window->type() != ui::wm::WINDOW_TYPE_UNKNOWN && - ShouldAnimateWindow(window); - animated = animated && - CallAnimateOnChildWindowVisibilityChanged(window, visible); - - // If we're already in the process of hiding don't do anything. Otherwise we - // may end up prematurely canceling the animation. - // This does not check opacity as when fading out a visibility change should - // also be scheduled (to do otherwise would mean the window can not be seen, - // opacity is 0, yet the window is marked as visible) (see CL 132903003). - // TODO(vollick): remove this. - if (!visible && - window->layer()->GetAnimator()->IsAnimatingProperty( - ui::LayerAnimationElement::VISIBILITY) && - !window->layer()->GetTargetVisibility()) { - return; - } - - // When a window is made visible, we always make its layer visible - // immediately. When a window is hidden, the layer must be left visible and - // only made not visible once the animation is complete. - if (!animated || visible) - window->layer()->SetVisible(visible); -} - -SuspendChildWindowVisibilityAnimations::SuspendChildWindowVisibilityAnimations( - aura::Window* window) - : window_(window), - original_enabled_(window->GetProperty( - kChildWindowVisibilityChangesAnimatedKey)) { - window_->ClearProperty(kChildWindowVisibilityChangesAnimatedKey); -} - -SuspendChildWindowVisibilityAnimations:: - ~SuspendChildWindowVisibilityAnimations() { - if (original_enabled_) - window_->SetProperty(kChildWindowVisibilityChangesAnimatedKey, true); - else - window_->ClearProperty(kChildWindowVisibilityChangesAnimatedKey); -} - -void SetChildWindowVisibilityChangesAnimated(aura::Window* window) { - window->SetProperty(kChildWindowVisibilityChangesAnimatedKey, true); -} - -} // namespace wm -
diff --git a/ui/wm/core/visibility_controller.h b/ui/wm/core/visibility_controller.h deleted file mode 100644 index d29a6da..0000000 --- a/ui/wm/core/visibility_controller.h +++ /dev/null
@@ -1,74 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_CORE_VISIBILITY_CONTROLLER_H_ -#define UI_WM_CORE_VISIBILITY_CONTROLLER_H_ - -#include "base/compiler_specific.h" -#include "base/logging.h" -#include "ui/aura/client/visibility_client.h" -#include "ui/wm/wm_export.h" - -namespace wm { - -class WM_EXPORT VisibilityController - : public aura::client::VisibilityClient { - public: - VisibilityController(); - virtual ~VisibilityController(); - - protected: - // Subclasses override if they want to call a different implementation of - // this function. - // TODO(beng): potentially replace by an actual window animator class in - // window_animations.h. - virtual bool CallAnimateOnChildWindowVisibilityChanged(aura::Window* window, - bool visible); - - private: - // Overridden from aura::client::VisibilityClient: - virtual void UpdateLayerVisibility(aura::Window* window, - bool visible) override; - - DISALLOW_COPY_AND_ASSIGN(VisibilityController); -}; - -// Suspends the animations for visibility changes during the lifetime of an -// instance of this class. -// -// Example: -// -// void ViewName::UnanimatedAction() { -// SuspendChildWindowVisibilityAnimations suspend(parent); -// // Perform unanimated action here. -// // ... -// // When the method finishes, visibility animations will return to their -// // previous state. -// } -// -class WM_EXPORT SuspendChildWindowVisibilityAnimations { - public: - // Suspend visibility animations of child windows. - explicit SuspendChildWindowVisibilityAnimations(aura::Window* window); - - // Restore visibility animations to their original state. - ~SuspendChildWindowVisibilityAnimations(); - - private: - // The window to manage. - aura::Window* window_; - - // Whether the visibility animations on child windows were originally enabled. - const bool original_enabled_; - - DISALLOW_COPY_AND_ASSIGN(SuspendChildWindowVisibilityAnimations); -}; - -// Tells |window| to animate visibility changes to its children. -void WM_EXPORT SetChildWindowVisibilityChangesAnimated( - aura::Window* window); - -} // namespace wm - -#endif // UI_WM_CORE_VISIBILITY_CONTROLLER_H_
diff --git a/ui/wm/core/visibility_controller_unittest.cc b/ui/wm/core/visibility_controller_unittest.cc deleted file mode 100644 index 01731ef..0000000 --- a/ui/wm/core/visibility_controller_unittest.cc +++ /dev/null
@@ -1,56 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/visibility_controller.h" - -#include "ui/aura/test/aura_test_base.h" -#include "ui/aura/test/test_window_delegate.h" -#include "ui/aura/test/test_windows.h" -#include "ui/aura/window.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/compositor/layer.h" -#include "ui/compositor/layer_animator.h" -#include "ui/compositor/scoped_animation_duration_scale_mode.h" -#include "ui/compositor/scoped_layer_animation_settings.h" - -namespace wm { - -typedef aura::test::AuraTestBase VisibilityControllerTest; - -// Check that a transparency change to 0 will not cause a hide call to be -// ignored. -TEST_F(VisibilityControllerTest, AnimateTransparencyToZeroAndHideHides) { - // We cannot disable animations for this test. - ui::ScopedAnimationDurationScaleMode test_duration_mode( - ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION); - - VisibilityController controller; - aura::client::SetVisibilityClient(root_window(), &controller); - - SetChildWindowVisibilityChangesAnimated(root_window()); - - aura::test::TestWindowDelegate d; - scoped_ptr<aura::Window> window(aura::test::CreateTestWindowWithDelegate( - &d, -2, gfx::Rect(0, 0, 50, 50), root_window())); - ui::ScopedLayerAnimationSettings settings(window->layer()->GetAnimator()); - settings.SetTransitionDuration(base::TimeDelta::FromMilliseconds(5)); - - EXPECT_TRUE(window->layer()->visible()); - EXPECT_TRUE(window->IsVisible()); - - window->layer()->SetOpacity(0.0); - EXPECT_TRUE(window->layer()->visible()); - EXPECT_TRUE(window->IsVisible()); - EXPECT_TRUE(window->layer()->GetAnimator()-> - IsAnimatingProperty(ui::LayerAnimationElement::OPACITY)); - EXPECT_EQ(0.0f, window->layer()->GetTargetOpacity()); - - // Check that the visibility is correct after the hide animation has finished. - window->Hide(); - window->layer()->GetAnimator()->StopAnimating(); - EXPECT_FALSE(window->layer()->visible()); - EXPECT_FALSE(window->IsVisible()); -} - -} // namespace wm
diff --git a/ui/wm/core/window_animations.cc b/ui/wm/core/window_animations.cc deleted file mode 100644 index fa5e6da..0000000 --- a/ui/wm/core/window_animations.cc +++ /dev/null
@@ -1,672 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/window_animations.h" - -#include <math.h> - -#include <algorithm> -#include <vector> - -#include "base/command_line.h" -#include "base/compiler_specific.h" -#include "base/logging.h" -#include "base/message_loop/message_loop.h" -#include "base/stl_util.h" -#include "base/time/time.h" -#include "ui/aura/client/aura_constants.h" -#include "ui/aura/window.h" -#include "ui/aura/window_delegate.h" -#include "ui/aura/window_observer.h" -#include "ui/aura/window_property.h" -#include "ui/compositor/compositor_observer.h" -#include "ui/compositor/layer.h" -#include "ui/compositor/layer_animation_observer.h" -#include "ui/compositor/layer_animation_sequence.h" -#include "ui/compositor/layer_animator.h" -#include "ui/compositor/layer_tree_owner.h" -#include "ui/compositor/scoped_animation_duration_scale_mode.h" -#include "ui/compositor/scoped_layer_animation_settings.h" -#include "ui/gfx/animation/animation.h" -#include "ui/gfx/interpolated_transform.h" -#include "ui/gfx/rect_conversions.h" -#include "ui/gfx/screen.h" -#include "ui/gfx/vector2d.h" -#include "ui/gfx/vector3d_f.h" -#include "ui/wm/core/window_util.h" -#include "ui/wm/core/wm_core_switches.h" -#include "ui/wm/public/animation_host.h" - -DECLARE_WINDOW_PROPERTY_TYPE(int) -DECLARE_WINDOW_PROPERTY_TYPE(wm::WindowVisibilityAnimationType) -DECLARE_WINDOW_PROPERTY_TYPE(wm::WindowVisibilityAnimationTransition) -DECLARE_WINDOW_PROPERTY_TYPE(float) -DECLARE_EXPORTED_WINDOW_PROPERTY_TYPE(WM_EXPORT, bool) - -namespace wm { -namespace { -const float kWindowAnimation_Vertical_TranslateY = 15.f; - -// A base class for hiding animation observer which has two roles: -// 1) Notifies AnimationHost at the end of hiding animation. -// 2) Detaches the window's layers for hiding animation and deletes -// them upon completion of the animation. This is necessary to a) -// ensure that the animation continues in the event of the window being -// deleted, and b) to ensure that the animation is visible even if the -// window gets restacked below other windows when focus or activation -// changes. -// The subclass will determine when the animation is completed. -class HidingWindowAnimationObserverBase : public aura::WindowObserver { - public: - explicit HidingWindowAnimationObserverBase(aura::Window* window) - : window_(window) { - window_->AddObserver(this); - } - virtual ~HidingWindowAnimationObserverBase() { - if (window_) - window_->RemoveObserver(this); - } - - // aura::WindowObserver: - virtual void OnWindowDestroying(aura::Window* window) override { - DCHECK_EQ(window, window_); - WindowInvalid(); - } - - virtual void OnWindowDestroyed(aura::Window* window) override { - DCHECK_EQ(window, window_); - WindowInvalid(); - } - - // Detach the current layers and create new layers for |window_|. - // Stack the original layers above |window_| and its transient - // children. If the window has transient children, the original - // layers will be moved above the top most transient child so that - // activation change does not put the window above the animating - // layer. - void DetachAndRecreateLayers() { - layer_owner_ = RecreateLayers(window_); - if (window_->parent()) { - const aura::Window::Windows& transient_children = - GetTransientChildren(window_); - aura::Window::Windows::const_iterator iter = - std::find(window_->parent()->children().begin(), - window_->parent()->children().end(), - window_); - DCHECK(iter != window_->parent()->children().end()); - aura::Window* topmost_transient_child = NULL; - for (++iter; iter != window_->parent()->children().end(); ++iter) { - if (std::find(transient_children.begin(), - transient_children.end(), - *iter) != transient_children.end()) { - topmost_transient_child = *iter; - } - } - if (topmost_transient_child) { - window_->parent()->layer()->StackAbove( - layer_owner_->root(), topmost_transient_child->layer()); - } - } - } - - protected: - // Invoked when the hiding animation is completed. It will delete - // 'this', and no operation should be made on this object after this - // point. - void OnAnimationCompleted() { - // Window may have been destroyed by this point. - if (window_) { - aura::client::AnimationHost* animation_host = - aura::client::GetAnimationHost(window_); - if (animation_host) - animation_host->OnWindowHidingAnimationCompleted(); - window_->RemoveObserver(this); - } - delete this; - } - - private: - // Invoked when the window is destroyed (or destroying). - void WindowInvalid() { - layer_owner_->root()->SuppressPaint(); - - window_->RemoveObserver(this); - window_ = NULL; - } - - aura::Window* window_; - - // The owner of detached layers. - scoped_ptr<ui::LayerTreeOwner> layer_owner_; - - DISALLOW_COPY_AND_ASSIGN(HidingWindowAnimationObserverBase); -}; - -} // namespace - -DEFINE_WINDOW_PROPERTY_KEY(int, - kWindowVisibilityAnimationTypeKey, - WINDOW_VISIBILITY_ANIMATION_TYPE_DEFAULT); -DEFINE_WINDOW_PROPERTY_KEY(int, kWindowVisibilityAnimationDurationKey, 0); -DEFINE_WINDOW_PROPERTY_KEY(WindowVisibilityAnimationTransition, - kWindowVisibilityAnimationTransitionKey, - ANIMATE_BOTH); -DEFINE_WINDOW_PROPERTY_KEY(float, - kWindowVisibilityAnimationVerticalPositionKey, - kWindowAnimation_Vertical_TranslateY); - -// A HidingWindowAnimationObserver that deletes observer and detached -// layers upon the completion of the implicit animation. -class ImplicitHidingWindowAnimationObserver - : public HidingWindowAnimationObserverBase, - public ui::ImplicitAnimationObserver { - public: - ImplicitHidingWindowAnimationObserver( - aura::Window* window, - ui::ScopedLayerAnimationSettings* settings); - virtual ~ImplicitHidingWindowAnimationObserver() {} - - // ui::ImplicitAnimationObserver: - virtual void OnImplicitAnimationsCompleted() override; - - private: - DISALLOW_COPY_AND_ASSIGN(ImplicitHidingWindowAnimationObserver); -}; - -namespace { - -const int kDefaultAnimationDurationForMenuMS = 150; - -const float kWindowAnimation_HideOpacity = 0.f; -const float kWindowAnimation_ShowOpacity = 1.f; -const float kWindowAnimation_TranslateFactor = 0.5f; -const float kWindowAnimation_ScaleFactor = .95f; - -const int kWindowAnimation_Rotate_DurationMS = 180; -const int kWindowAnimation_Rotate_OpacityDurationPercent = 90; -const float kWindowAnimation_Rotate_TranslateY = -20.f; -const float kWindowAnimation_Rotate_PerspectiveDepth = 500.f; -const float kWindowAnimation_Rotate_DegreesX = 5.f; -const float kWindowAnimation_Rotate_ScaleFactor = .99f; - -const float kWindowAnimation_Bounce_Scale = 1.02f; -const int kWindowAnimation_Bounce_DurationMS = 180; -const int kWindowAnimation_Bounce_GrowShrinkDurationPercent = 40; - -base::TimeDelta GetWindowVisibilityAnimationDuration( - const aura::Window& window) { - int duration = - window.GetProperty(kWindowVisibilityAnimationDurationKey); - if (duration == 0 && window.type() == ui::wm::WINDOW_TYPE_MENU) { - return base::TimeDelta::FromMilliseconds( - kDefaultAnimationDurationForMenuMS); - } - return base::TimeDelta::FromInternalValue(duration); -} - -// Gets/sets the WindowVisibilityAnimationType associated with a window. -// TODO(beng): redundant/fold into method on public api? -int GetWindowVisibilityAnimationType(aura::Window* window) { - int type = window->GetProperty(kWindowVisibilityAnimationTypeKey); - if (type == WINDOW_VISIBILITY_ANIMATION_TYPE_DEFAULT) { - return (window->type() == ui::wm::WINDOW_TYPE_MENU || - window->type() == ui::wm::WINDOW_TYPE_TOOLTIP) - ? WINDOW_VISIBILITY_ANIMATION_TYPE_FADE - : WINDOW_VISIBILITY_ANIMATION_TYPE_DROP; - } - return type; -} - -void GetTransformRelativeToRoot(ui::Layer* layer, gfx::Transform* transform) { - const ui::Layer* root = layer; - while (root->parent()) - root = root->parent(); - layer->GetTargetTransformRelativeTo(root, transform); -} - -gfx::Rect GetLayerWorldBoundsAfterTransform(ui::Layer* layer, - const gfx::Transform& transform) { - gfx::Transform in_world = transform; - GetTransformRelativeToRoot(layer, &in_world); - - gfx::RectF transformed = layer->bounds(); - in_world.TransformRect(&transformed); - - return gfx::ToEnclosingRect(transformed); -} - -// Augment the host window so that the enclosing bounds of the full -// animation will fit inside of it. -void AugmentWindowSize(aura::Window* window, - const gfx::Transform& end_transform) { - aura::client::AnimationHost* animation_host = - aura::client::GetAnimationHost(window); - if (!animation_host) - return; - - const gfx::Rect& world_at_start = window->bounds(); - gfx::Rect world_at_end = - GetLayerWorldBoundsAfterTransform(window->layer(), end_transform); - gfx::Rect union_in_window_space = - gfx::UnionRects(world_at_start, world_at_end); - - // Calculate the top left and bottom right deltas to be added to the window - // bounds. - gfx::Vector2d top_left_delta(world_at_start.x() - union_in_window_space.x(), - world_at_start.y() - union_in_window_space.y()); - - gfx::Vector2d bottom_right_delta( - union_in_window_space.x() + union_in_window_space.width() - - (world_at_start.x() + world_at_start.width()), - union_in_window_space.y() + union_in_window_space.height() - - (world_at_start.y() + world_at_start.height())); - - DCHECK(top_left_delta.x() >= 0 && top_left_delta.y() >= 0 && - bottom_right_delta.x() >= 0 && bottom_right_delta.y() >= 0); - - animation_host->SetHostTransitionOffsets(top_left_delta, bottom_right_delta); -} - -// Shows a window using an animation, animating its opacity from 0.f to 1.f, -// its visibility to true, and its transform from |start_transform| to -// |end_transform|. -void AnimateShowWindowCommon(aura::Window* window, - const gfx::Transform& start_transform, - const gfx::Transform& end_transform) { - AugmentWindowSize(window, end_transform); - - window->layer()->SetOpacity(kWindowAnimation_HideOpacity); - window->layer()->SetTransform(start_transform); - window->layer()->SetVisible(true); - - { - // Property sets within this scope will be implicitly animated. - ui::ScopedLayerAnimationSettings settings(window->layer()->GetAnimator()); - base::TimeDelta duration = GetWindowVisibilityAnimationDuration(*window); - if (duration.ToInternalValue() > 0) - settings.SetTransitionDuration(duration); - - window->layer()->SetTransform(end_transform); - window->layer()->SetOpacity(kWindowAnimation_ShowOpacity); - } -} - -// Hides a window using an animation, animating its opacity from 1.f to 0.f, -// its visibility to false, and its transform to |end_transform|. -void AnimateHideWindowCommon(aura::Window* window, - const gfx::Transform& end_transform) { - AugmentWindowSize(window, end_transform); - - // Property sets within this scope will be implicitly animated. - ScopedHidingAnimationSettings hiding_settings(window); - base::TimeDelta duration = GetWindowVisibilityAnimationDuration(*window); - if (duration.ToInternalValue() > 0) - hiding_settings.layer_animation_settings()->SetTransitionDuration(duration); - - window->layer()->SetOpacity(kWindowAnimation_HideOpacity); - window->layer()->SetTransform(end_transform); - window->layer()->SetVisible(false); -} - -static gfx::Transform GetScaleForWindow(aura::Window* window) { - gfx::Rect bounds = window->bounds(); - gfx::Transform scale = gfx::GetScaleTransform( - gfx::Point(kWindowAnimation_TranslateFactor * bounds.width(), - kWindowAnimation_TranslateFactor * bounds.height()), - kWindowAnimation_ScaleFactor); - return scale; -} - -// Show/Hide windows using a shrink animation. -void AnimateShowWindow_Drop(aura::Window* window) { - AnimateShowWindowCommon(window, GetScaleForWindow(window), gfx::Transform()); -} - -void AnimateHideWindow_Drop(aura::Window* window) { - AnimateHideWindowCommon(window, GetScaleForWindow(window)); -} - -// Show/Hide windows using a vertical Glenimation. -void AnimateShowWindow_Vertical(aura::Window* window) { - gfx::Transform transform; - transform.Translate(0, window->GetProperty( - kWindowVisibilityAnimationVerticalPositionKey)); - AnimateShowWindowCommon(window, transform, gfx::Transform()); -} - -void AnimateHideWindow_Vertical(aura::Window* window) { - gfx::Transform transform; - transform.Translate(0, window->GetProperty( - kWindowVisibilityAnimationVerticalPositionKey)); - AnimateHideWindowCommon(window, transform); -} - -// Show/Hide windows using a fade. -void AnimateShowWindow_Fade(aura::Window* window) { - AnimateShowWindowCommon(window, gfx::Transform(), gfx::Transform()); -} - -void AnimateHideWindow_Fade(aura::Window* window) { - AnimateHideWindowCommon(window, gfx::Transform()); -} - -ui::LayerAnimationElement* CreateGrowShrinkElement( - aura::Window* window, bool grow) { - scoped_ptr<ui::InterpolatedTransform> scale(new ui::InterpolatedScale( - gfx::Point3F(kWindowAnimation_Bounce_Scale, - kWindowAnimation_Bounce_Scale, - 1), - gfx::Point3F(1, 1, 1))); - scoped_ptr<ui::InterpolatedTransform> scale_about_pivot( - new ui::InterpolatedTransformAboutPivot( - gfx::Point(window->bounds().width() * 0.5, - window->bounds().height() * 0.5), - scale.release())); - scale_about_pivot->SetReversed(grow); - scoped_ptr<ui::LayerAnimationElement> transition( - ui::LayerAnimationElement::CreateInterpolatedTransformElement( - scale_about_pivot.release(), - base::TimeDelta::FromMilliseconds( - kWindowAnimation_Bounce_DurationMS * - kWindowAnimation_Bounce_GrowShrinkDurationPercent / 100))); - transition->set_tween_type(grow ? gfx::Tween::EASE_OUT : gfx::Tween::EASE_IN); - return transition.release(); -} - -void AnimateBounce(aura::Window* window) { - ui::ScopedLayerAnimationSettings scoped_settings( - window->layer()->GetAnimator()); - scoped_settings.SetPreemptionStrategy( - ui::LayerAnimator::REPLACE_QUEUED_ANIMATIONS); - scoped_ptr<ui::LayerAnimationSequence> sequence( - new ui::LayerAnimationSequence); - sequence->AddElement(CreateGrowShrinkElement(window, true)); - sequence->AddElement(ui::LayerAnimationElement::CreatePauseElement( - ui::LayerAnimationElement::BOUNDS, - base::TimeDelta::FromMilliseconds( - kWindowAnimation_Bounce_DurationMS * - (100 - 2 * kWindowAnimation_Bounce_GrowShrinkDurationPercent) / - 100))); - sequence->AddElement(CreateGrowShrinkElement(window, false)); - window->layer()->GetAnimator()->StartAnimation(sequence.release()); -} - -// A HidingWindowAnimationObserver that deletes observer and detached -// layers when the last_sequence has been completed or aborted. -class RotateHidingWindowAnimationObserver - : public HidingWindowAnimationObserverBase, - public ui::LayerAnimationObserver { - public: - explicit RotateHidingWindowAnimationObserver(aura::Window* window) - : HidingWindowAnimationObserverBase(window) {} - virtual ~RotateHidingWindowAnimationObserver() {} - - // Destroys itself after |last_sequence| ends or is aborted. Does not take - // ownership of |last_sequence|, which should not be NULL. - void SetLastSequence(ui::LayerAnimationSequence* last_sequence) { - last_sequence->AddObserver(this); - } - - // ui::LayerAnimationObserver: - virtual void OnLayerAnimationEnded( - ui::LayerAnimationSequence* sequence) override { - OnAnimationCompleted(); - } - virtual void OnLayerAnimationAborted( - ui::LayerAnimationSequence* sequence) override { - OnAnimationCompleted(); - } - virtual void OnLayerAnimationScheduled( - ui::LayerAnimationSequence* sequence) override {} - - private: - DISALLOW_COPY_AND_ASSIGN(RotateHidingWindowAnimationObserver); -}; - -void AddLayerAnimationsForRotate(aura::Window* window, bool show) { - if (show) - window->layer()->SetOpacity(kWindowAnimation_HideOpacity); - - base::TimeDelta duration = base::TimeDelta::FromMilliseconds( - kWindowAnimation_Rotate_DurationMS); - - RotateHidingWindowAnimationObserver* observer = NULL; - - if (!show) { - observer = new RotateHidingWindowAnimationObserver(window); - window->layer()->GetAnimator()->SchedulePauseForProperties( - duration * (100 - kWindowAnimation_Rotate_OpacityDurationPercent) / 100, - ui::LayerAnimationElement::OPACITY); - } - scoped_ptr<ui::LayerAnimationElement> opacity( - ui::LayerAnimationElement::CreateOpacityElement( - show ? kWindowAnimation_ShowOpacity : kWindowAnimation_HideOpacity, - duration * kWindowAnimation_Rotate_OpacityDurationPercent / 100)); - opacity->set_tween_type(gfx::Tween::EASE_IN_OUT); - window->layer()->GetAnimator()->ScheduleAnimation( - new ui::LayerAnimationSequence(opacity.release())); - - float xcenter = window->bounds().width() * 0.5; - - gfx::Transform transform; - transform.Translate(xcenter, 0); - transform.ApplyPerspectiveDepth(kWindowAnimation_Rotate_PerspectiveDepth); - transform.Translate(-xcenter, 0); - scoped_ptr<ui::InterpolatedTransform> perspective( - new ui::InterpolatedConstantTransform(transform)); - - scoped_ptr<ui::InterpolatedTransform> scale( - new ui::InterpolatedScale(1, kWindowAnimation_Rotate_ScaleFactor)); - scoped_ptr<ui::InterpolatedTransform> scale_about_pivot( - new ui::InterpolatedTransformAboutPivot( - gfx::Point(xcenter, kWindowAnimation_Rotate_TranslateY), - scale.release())); - - scoped_ptr<ui::InterpolatedTransform> translation( - new ui::InterpolatedTranslation(gfx::Point(), gfx::Point( - 0, kWindowAnimation_Rotate_TranslateY))); - - scoped_ptr<ui::InterpolatedTransform> rotation( - new ui::InterpolatedAxisAngleRotation( - gfx::Vector3dF(1, 0, 0), 0, kWindowAnimation_Rotate_DegreesX)); - - scale_about_pivot->SetChild(perspective.release()); - translation->SetChild(scale_about_pivot.release()); - rotation->SetChild(translation.release()); - rotation->SetReversed(show); - - scoped_ptr<ui::LayerAnimationElement> transition( - ui::LayerAnimationElement::CreateInterpolatedTransformElement( - rotation.release(), duration)); - ui::LayerAnimationSequence* last_sequence = - new ui::LayerAnimationSequence(transition.release()); - window->layer()->GetAnimator()->ScheduleAnimation(last_sequence); - - if (observer) { - observer->SetLastSequence(last_sequence); - observer->DetachAndRecreateLayers(); - } -} - -void AnimateShowWindow_Rotate(aura::Window* window) { - AddLayerAnimationsForRotate(window, true); -} - -void AnimateHideWindow_Rotate(aura::Window* window) { - AddLayerAnimationsForRotate(window, false); -} - -bool AnimateShowWindow(aura::Window* window) { - if (!HasWindowVisibilityAnimationTransition(window, ANIMATE_SHOW)) { - if (HasWindowVisibilityAnimationTransition(window, ANIMATE_HIDE)) { - // Since hide animation may have changed opacity and transform, - // reset them to show the window. - window->layer()->SetOpacity(kWindowAnimation_ShowOpacity); - window->layer()->SetTransform(gfx::Transform()); - } - return false; - } - - switch (GetWindowVisibilityAnimationType(window)) { - case WINDOW_VISIBILITY_ANIMATION_TYPE_DROP: - AnimateShowWindow_Drop(window); - return true; - case WINDOW_VISIBILITY_ANIMATION_TYPE_VERTICAL: - AnimateShowWindow_Vertical(window); - return true; - case WINDOW_VISIBILITY_ANIMATION_TYPE_FADE: - AnimateShowWindow_Fade(window); - return true; - case WINDOW_VISIBILITY_ANIMATION_TYPE_ROTATE: - AnimateShowWindow_Rotate(window); - return true; - default: - return false; - } -} - -bool AnimateHideWindow(aura::Window* window) { - if (!HasWindowVisibilityAnimationTransition(window, ANIMATE_HIDE)) { - if (HasWindowVisibilityAnimationTransition(window, ANIMATE_SHOW)) { - // Since show animation may have changed opacity and transform, - // reset them, though the change should be hidden. - window->layer()->SetOpacity(kWindowAnimation_HideOpacity); - window->layer()->SetTransform(gfx::Transform()); - } - return false; - } - - switch (GetWindowVisibilityAnimationType(window)) { - case WINDOW_VISIBILITY_ANIMATION_TYPE_DROP: - AnimateHideWindow_Drop(window); - return true; - case WINDOW_VISIBILITY_ANIMATION_TYPE_VERTICAL: - AnimateHideWindow_Vertical(window); - return true; - case WINDOW_VISIBILITY_ANIMATION_TYPE_FADE: - AnimateHideWindow_Fade(window); - return true; - case WINDOW_VISIBILITY_ANIMATION_TYPE_ROTATE: - AnimateHideWindow_Rotate(window); - return true; - default: - return false; - } -} - -} // namespace - -//////////////////////////////////////////////////////////////////////////////// -// ImplicitHidingWindowAnimationObserver - -ImplicitHidingWindowAnimationObserver::ImplicitHidingWindowAnimationObserver( - aura::Window* window, - ui::ScopedLayerAnimationSettings* settings) - : HidingWindowAnimationObserverBase(window) { - settings->AddObserver(this); -} - -void ImplicitHidingWindowAnimationObserver::OnImplicitAnimationsCompleted() { - OnAnimationCompleted(); -} - -//////////////////////////////////////////////////////////////////////////////// -// ScopedHidingAnimationSettings - -ScopedHidingAnimationSettings::ScopedHidingAnimationSettings( - aura::Window* window) - : layer_animation_settings_(window->layer()->GetAnimator()), - observer_(new ImplicitHidingWindowAnimationObserver( - window, - &layer_animation_settings_)) { -} - -ScopedHidingAnimationSettings::~ScopedHidingAnimationSettings() { - observer_->DetachAndRecreateLayers(); -} - -//////////////////////////////////////////////////////////////////////////////// -// External interface - -void SetWindowVisibilityAnimationType(aura::Window* window, int type) { - window->SetProperty(kWindowVisibilityAnimationTypeKey, type); -} - -int GetWindowVisibilityAnimationType(aura::Window* window) { - return window->GetProperty(kWindowVisibilityAnimationTypeKey); -} - -void SetWindowVisibilityAnimationTransition( - aura::Window* window, - WindowVisibilityAnimationTransition transition) { - window->SetProperty(kWindowVisibilityAnimationTransitionKey, transition); -} - -bool HasWindowVisibilityAnimationTransition( - aura::Window* window, - WindowVisibilityAnimationTransition transition) { - WindowVisibilityAnimationTransition prop = window->GetProperty( - kWindowVisibilityAnimationTransitionKey); - return (prop & transition) != 0; -} - -void SetWindowVisibilityAnimationDuration(aura::Window* window, - const base::TimeDelta& duration) { - window->SetProperty(kWindowVisibilityAnimationDurationKey, - static_cast<int>(duration.ToInternalValue())); -} - -base::TimeDelta GetWindowVisibilityAnimationDuration( - const aura::Window& window) { - return base::TimeDelta::FromInternalValue( - window.GetProperty(kWindowVisibilityAnimationDurationKey)); -} - -void SetWindowVisibilityAnimationVerticalPosition(aura::Window* window, - float position) { - window->SetProperty(kWindowVisibilityAnimationVerticalPositionKey, position); -} - -bool AnimateOnChildWindowVisibilityChanged(aura::Window* window, bool visible) { - if (WindowAnimationsDisabled(window)) - return false; - if (visible) - return AnimateShowWindow(window); - // Don't start hiding the window again if it's already being hidden. - return window->layer()->GetTargetOpacity() != 0.0f && - AnimateHideWindow(window); -} - -bool AnimateWindow(aura::Window* window, WindowAnimationType type) { - switch (type) { - case WINDOW_ANIMATION_TYPE_BOUNCE: - AnimateBounce(window); - return true; - default: - NOTREACHED(); - return false; - } -} - -bool WindowAnimationsDisabled(aura::Window* window) { - // Individual windows can choose to skip animations. - if (window && window->GetProperty(aura::client::kAnimationsDisabledKey)) - return true; - - // Animations can be disabled globally for testing. - if (base::CommandLine::ForCurrentProcess()->HasSwitch( - switches::kWindowAnimationsDisabled)) - return true; - - // Tests of animations themselves should still run even if the machine is - // being accessed via Remote Desktop. - if (ui::ScopedAnimationDurationScaleMode::duration_scale_mode() == - ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION) - return false; - - // Let the user decide whether or not to play the animation. - return !gfx::Animation::ShouldRenderRichAnimation(); -} - -} // namespace wm
diff --git a/ui/wm/core/window_animations.h b/ui/wm/core/window_animations.h deleted file mode 100644 index 422167e..0000000 --- a/ui/wm/core/window_animations.h +++ /dev/null
@@ -1,117 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_CORE_WINDOW_ANIMATIONS_H_ -#define UI_WM_CORE_WINDOW_ANIMATIONS_H_ - -#include <vector> - -#include "ui/compositor/scoped_layer_animation_settings.h" -#include "ui/wm/wm_export.h" - -namespace aura { -class Window; -} -namespace base { -class TimeDelta; -} -namespace gfx { -class Rect; -} -namespace ui { -class ImplicitAnimationObserver; -class Layer; -class LayerAnimationSequence; -} - -namespace wm { - -// A variety of canned animations for window transitions. -enum WindowVisibilityAnimationType { - WINDOW_VISIBILITY_ANIMATION_TYPE_DEFAULT = 0, // Default. Lets the system - // decide based on window - // type. - WINDOW_VISIBILITY_ANIMATION_TYPE_DROP, // Window shrinks in. - WINDOW_VISIBILITY_ANIMATION_TYPE_VERTICAL, // Vertical Glenimation. - WINDOW_VISIBILITY_ANIMATION_TYPE_FADE, // Fades in/out. - WINDOW_VISIBILITY_ANIMATION_TYPE_ROTATE, // Window rotates in. - - // Downstream library animations start above this point. - WINDOW_VISIBILITY_ANIMATION_MAX -}; - -// Canned animations that take effect once but don't have a symmetric pair as -// visibility animations do. -enum WindowAnimationType { - WINDOW_ANIMATION_TYPE_BOUNCE = 0, // Window scales up and down. -}; - -// Type of visibility change transition that a window should animate. -// Default behavior is to animate both show and hide. -enum WindowVisibilityAnimationTransition { - ANIMATE_SHOW = 0x1, - ANIMATE_HIDE = 0x2, - ANIMATE_BOTH = ANIMATE_SHOW | ANIMATE_HIDE, - ANIMATE_NONE = 0x4, -}; - -// These two methods use int for type rather than WindowVisibilityAnimationType -// since downstream libraries can extend the set of animations. -WM_EXPORT void SetWindowVisibilityAnimationType(aura::Window* window, int type); -WM_EXPORT int GetWindowVisibilityAnimationType(aura::Window* window); - -WM_EXPORT void SetWindowVisibilityAnimationTransition( - aura::Window* window, - WindowVisibilityAnimationTransition transition); - -WM_EXPORT bool HasWindowVisibilityAnimationTransition( - aura::Window* window, - WindowVisibilityAnimationTransition transition); - -WM_EXPORT void SetWindowVisibilityAnimationDuration( - aura::Window* window, - const base::TimeDelta& duration); - -WM_EXPORT base::TimeDelta GetWindowVisibilityAnimationDuration( - const aura::Window& window); - -WM_EXPORT void SetWindowVisibilityAnimationVerticalPosition( - aura::Window* window, - float position); - -class ImplicitHidingWindowAnimationObserver; -// A wrapper of ui::ScopedLayerAnimationSettings for implicit hiding animations. -// Use this to ensure that the hiding animation is visible even after -// the window is deleted or deactivated, instead of using -// ui::ScopedLayerAnimationSettings directly. -class WM_EXPORT ScopedHidingAnimationSettings { - public: - explicit ScopedHidingAnimationSettings(aura::Window* window); - ~ScopedHidingAnimationSettings(); - - // Returns the wrapped ScopedLayeAnimationSettings instance. - ui::ScopedLayerAnimationSettings* layer_animation_settings() { - return &layer_animation_settings_; - } - - private: - ui::ScopedLayerAnimationSettings layer_animation_settings_; - ImplicitHidingWindowAnimationObserver* observer_; - - DISALLOW_COPY_AND_ASSIGN(ScopedHidingAnimationSettings); -}; - -// Returns false if the |window| didn't animate. -WM_EXPORT bool AnimateOnChildWindowVisibilityChanged(aura::Window* window, - bool visible); -WM_EXPORT bool AnimateWindow(aura::Window* window, WindowAnimationType type); - -// Returns true if window animations are disabled for |window|. Window -// animations are enabled by default. If |window| is NULL, this just checks -// if the global flag disabling window animations is present. -WM_EXPORT bool WindowAnimationsDisabled(aura::Window* window); - -} // namespace wm - -#endif // UI_WM_CORE_WINDOW_ANIMATIONS_H_
diff --git a/ui/wm/core/window_animations_unittest.cc b/ui/wm/core/window_animations_unittest.cc deleted file mode 100644 index b1db736..0000000 --- a/ui/wm/core/window_animations_unittest.cc +++ /dev/null
@@ -1,308 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/window_animations.h" - -#include "base/time/time.h" -#include "ui/aura/test/aura_test_base.h" -#include "ui/aura/test/test_windows.h" -#include "ui/aura/window.h" -#include "ui/compositor/layer.h" -#include "ui/compositor/layer_animator.h" -#include "ui/compositor/scoped_animation_duration_scale_mode.h" -#include "ui/gfx/animation/animation_container_element.h" -#include "ui/gfx/vector2d.h" -#include "ui/wm/core/transient_window_manager.h" -#include "ui/wm/core/transient_window_stacking_client.h" -#include "ui/wm/core/window_util.h" -#include "ui/wm/public/animation_host.h" - -using aura::Window; -using ui::Layer; - -namespace wm { -namespace { - -template<typename T>int GetZPosition(const T* child) { - const T* parent = child->parent(); - const std::vector<T*> children = parent->children(); - typename std::vector<T*>::const_iterator iter = - std::find(children.begin(), children.end(), child); - DCHECK(iter != children.end()); - return iter - children.begin(); -} - -int GetWindowZPosition(const aura::Window* child) { - return GetZPosition<aura::Window>(child); -} - -int GetLayerZPosition(const ui::Layer* child) { - return GetZPosition<ui::Layer>(child); -} - -} // namespace - -class WindowAnimationsTest : public aura::test::AuraTestBase { - public: - WindowAnimationsTest() {} - - virtual void TearDown() override { - AuraTestBase::TearDown(); - } - - private: - DISALLOW_COPY_AND_ASSIGN(WindowAnimationsTest); -}; - -TEST_F(WindowAnimationsTest, LayerTargetVisibility) { - scoped_ptr<aura::Window> window( - aura::test::CreateTestWindowWithId(0, NULL)); - - // Layer target visibility changes according to Show/Hide. - window->Show(); - EXPECT_TRUE(window->layer()->GetTargetVisibility()); - window->Hide(); - EXPECT_FALSE(window->layer()->GetTargetVisibility()); - window->Show(); - EXPECT_TRUE(window->layer()->GetTargetVisibility()); -} - -TEST_F(WindowAnimationsTest, LayerTargetVisibility_AnimateShow) { - // Tests if opacity and transform are reset when only show animation is - // enabled. See also LayerTargetVisibility_AnimateHide. - // Since the window is not visible after Hide() is called, opacity and - // transform shouldn't matter in case of ANIMATE_SHOW, but we reset them - // to keep consistency. - - scoped_ptr<aura::Window> window(aura::test::CreateTestWindowWithId(0, NULL)); - SetWindowVisibilityAnimationTransition(window.get(), ANIMATE_SHOW); - - // Layer target visibility and opacity change according to Show/Hide. - window->Show(); - AnimateOnChildWindowVisibilityChanged(window.get(), true); - EXPECT_TRUE(window->layer()->GetTargetVisibility()); - EXPECT_EQ(1, window->layer()->opacity()); - - window->Hide(); - AnimateOnChildWindowVisibilityChanged(window.get(), false); - EXPECT_FALSE(window->layer()->GetTargetVisibility()); - EXPECT_EQ(0, window->layer()->opacity()); - EXPECT_EQ(gfx::Transform(), window->layer()->transform()); - - window->Show(); - AnimateOnChildWindowVisibilityChanged(window.get(), true); - EXPECT_TRUE(window->layer()->GetTargetVisibility()); - EXPECT_EQ(1, window->layer()->opacity()); -} - -TEST_F(WindowAnimationsTest, LayerTargetVisibility_AnimateHide) { - // Tests if opacity and transform are reset when only hide animation is - // enabled. Hide animation changes opacity and transform in addition to - // visibility, so we need to reset not only visibility but also opacity - // and transform to show the window. - - scoped_ptr<aura::Window> window(aura::test::CreateTestWindowWithId(0, NULL)); - SetWindowVisibilityAnimationTransition(window.get(), ANIMATE_HIDE); - - // Layer target visibility and opacity change according to Show/Hide. - window->Show(); - AnimateOnChildWindowVisibilityChanged(window.get(), true); - EXPECT_TRUE(window->layer()->GetTargetVisibility()); - EXPECT_EQ(1, window->layer()->opacity()); - EXPECT_EQ(gfx::Transform(), window->layer()->transform()); - - window->Hide(); - AnimateOnChildWindowVisibilityChanged(window.get(), false); - EXPECT_FALSE(window->layer()->GetTargetVisibility()); - EXPECT_EQ(0, window->layer()->opacity()); - - window->Show(); - AnimateOnChildWindowVisibilityChanged(window.get(), true); - EXPECT_TRUE(window->layer()->GetTargetVisibility()); - EXPECT_EQ(1, window->layer()->opacity()); - EXPECT_EQ(gfx::Transform(), window->layer()->transform()); -} - -TEST_F(WindowAnimationsTest, HideAnimationDetachLayers) { - scoped_ptr<aura::Window> parent(aura::test::CreateTestWindowWithId(0, NULL)); - - scoped_ptr<aura::Window> other( - aura::test::CreateTestWindowWithId(1, parent.get())); - - scoped_ptr<aura::Window> animating_window( - aura::test::CreateTestWindowWithId(2, parent.get())); - SetWindowVisibilityAnimationTransition(animating_window.get(), ANIMATE_HIDE); - - EXPECT_EQ(0, GetWindowZPosition(other.get())); - EXPECT_EQ(1, GetWindowZPosition(animating_window.get())); - EXPECT_EQ(0, GetLayerZPosition(other->layer())); - EXPECT_EQ(1, GetLayerZPosition(animating_window->layer())); - - { - ui::ScopedAnimationDurationScaleMode scale_mode( - ui::ScopedAnimationDurationScaleMode::FAST_DURATION); - ui::Layer* animating_layer = animating_window->layer(); - - animating_window->Hide(); - EXPECT_TRUE(AnimateOnChildWindowVisibilityChanged( - animating_window.get(), false)); - EXPECT_TRUE(animating_layer->GetAnimator()->is_animating()); - EXPECT_FALSE(animating_layer->delegate()); - - // Make sure the Hide animation create another layer, and both are in - // the parent layer. - EXPECT_NE(animating_window->layer(), animating_layer); - EXPECT_TRUE( - std::find(parent->layer()->children().begin(), - parent->layer()->children().end(), - animating_layer) != - parent->layer()->children().end()); - EXPECT_TRUE( - std::find(parent->layer()->children().begin(), - parent->layer()->children().end(), - animating_window->layer()) != - parent->layer()->children().end()); - // Current layer must be already hidden. - EXPECT_FALSE(animating_window->layer()->visible()); - - EXPECT_EQ(1, GetWindowZPosition(animating_window.get())); - EXPECT_EQ(1, GetLayerZPosition(animating_window->layer())); - EXPECT_EQ(2, GetLayerZPosition(animating_layer)); - - parent->StackChildAtTop(other.get()); - EXPECT_EQ(0, GetWindowZPosition(animating_window.get())); - EXPECT_EQ(1, GetWindowZPosition(other.get())); - - EXPECT_EQ(0, GetLayerZPosition(animating_window->layer())); - EXPECT_EQ(1, GetLayerZPosition(other->layer())); - // Make sure the animating layer is on top. - EXPECT_EQ(2, GetLayerZPosition(animating_layer)); - - // Animating layer must be gone - animating_layer->GetAnimator()->StopAnimating(); - EXPECT_TRUE( - std::find(parent->layer()->children().begin(), - parent->layer()->children().end(), - animating_layer) == - parent->layer()->children().end()); - } -} - -TEST_F(WindowAnimationsTest, HideAnimationDetachLayersWithTransientChildren) { - TransientWindowStackingClient transient_stacking_client; - - scoped_ptr<aura::Window> parent(aura::test::CreateTestWindowWithId(0, NULL)); - - scoped_ptr<aura::Window> other( - aura::test::CreateTestWindowWithId(1, parent.get())); - - scoped_ptr<aura::Window> animating_window( - aura::test::CreateTestWindowWithId(2, parent.get())); - SetWindowVisibilityAnimationTransition(animating_window.get(), ANIMATE_HIDE); - - scoped_ptr<aura::Window> transient1( - aura::test::CreateTestWindowWithId(3, parent.get())); - scoped_ptr<aura::Window> transient2( - aura::test::CreateTestWindowWithId(4, parent.get())); - - TransientWindowManager::Get(animating_window.get()); - AddTransientChild(animating_window.get(), transient1.get()); - AddTransientChild(animating_window.get(), transient2.get()); - - EXPECT_EQ(0, GetWindowZPosition(other.get())); - EXPECT_EQ(1, GetWindowZPosition(animating_window.get())); - EXPECT_EQ(2, GetWindowZPosition(transient1.get())); - EXPECT_EQ(3, GetWindowZPosition(transient2.get())); - - { - ui::ScopedAnimationDurationScaleMode scale_mode( - ui::ScopedAnimationDurationScaleMode::FAST_DURATION); - ui::Layer* animating_layer = animating_window->layer(); - - animating_window->Hide(); - EXPECT_TRUE(AnimateOnChildWindowVisibilityChanged( - animating_window.get(), false)); - EXPECT_TRUE(animating_layer->GetAnimator()->is_animating()); - EXPECT_FALSE(animating_layer->delegate()); - - EXPECT_EQ(1, GetWindowZPosition(animating_window.get())); - EXPECT_EQ(2, GetWindowZPosition(transient1.get())); - EXPECT_EQ(3, GetWindowZPosition(transient2.get())); - - EXPECT_EQ(1, GetLayerZPosition(animating_window->layer())); - EXPECT_EQ(2, GetLayerZPosition(transient1->layer())); - EXPECT_EQ(3, GetLayerZPosition(transient2->layer())); - EXPECT_EQ(4, GetLayerZPosition(animating_layer)); - - parent->StackChildAtTop(other.get()); - - EXPECT_EQ(0, GetWindowZPosition(animating_window.get())); - EXPECT_EQ(1, GetWindowZPosition(transient1.get())); - EXPECT_EQ(2, GetWindowZPosition(transient2.get())); - EXPECT_EQ(3, GetWindowZPosition(other.get())); - - EXPECT_EQ(0, GetLayerZPosition(animating_window->layer())); - EXPECT_EQ(1, GetLayerZPosition(transient1->layer())); - EXPECT_EQ(2, GetLayerZPosition(transient2->layer())); - EXPECT_EQ(3, GetLayerZPosition(other->layer())); - // Make sure the animating layer is on top of all windows. - EXPECT_EQ(4, GetLayerZPosition(animating_layer)); - } -} - -// A simple AnimationHost implementation for the NotifyHideCompleted test. -class NotifyHideCompletedAnimationHost : public aura::client::AnimationHost { - public: - NotifyHideCompletedAnimationHost() : hide_completed_(false) {} - virtual ~NotifyHideCompletedAnimationHost() {} - - // Overridden from TestWindowDelegate: - virtual void OnWindowHidingAnimationCompleted() override { - hide_completed_ = true; - } - - virtual void SetHostTransitionOffsets( - const gfx::Vector2d& top_left, - const gfx::Vector2d& bottom_right) override {} - - bool hide_completed() const { return hide_completed_; } - - private: - bool hide_completed_; - - DISALLOW_COPY_AND_ASSIGN(NotifyHideCompletedAnimationHost); -}; - -TEST_F(WindowAnimationsTest, NotifyHideCompleted) { - NotifyHideCompletedAnimationHost animation_host; - scoped_ptr<aura::Window> window(aura::test::CreateTestWindowWithId(0, NULL)); - aura::client::SetAnimationHost(window.get(), &animation_host); - wm::SetWindowVisibilityAnimationType( - window.get(), WINDOW_VISIBILITY_ANIMATION_TYPE_FADE); - AnimateOnChildWindowVisibilityChanged(window.get(), true); - EXPECT_TRUE(window->layer()->visible()); - - EXPECT_FALSE(animation_host.hide_completed()); - AnimateOnChildWindowVisibilityChanged(window.get(), false); - EXPECT_TRUE(animation_host.hide_completed()); -} - -// The rotation animation for hiding a window should not leak the animation -// observer. -TEST_F(WindowAnimationsTest, RotateHideNoLeak) { - ui::ScopedAnimationDurationScaleMode scale_mode( - ui::ScopedAnimationDurationScaleMode::FAST_DURATION); - - scoped_ptr<aura::Window> window(aura::test::CreateTestWindowWithId(0, NULL)); - ui::Layer* animating_layer = window->layer(); - wm::SetWindowVisibilityAnimationType(window.get(), - WINDOW_VISIBILITY_ANIMATION_TYPE_ROTATE); - - AnimateOnChildWindowVisibilityChanged(window.get(), true); - AnimateOnChildWindowVisibilityChanged(window.get(), false); - - animating_layer->GetAnimator()->StopAnimating(); -} - -} // namespace wm
diff --git a/ui/wm/core/window_modality_controller.cc b/ui/wm/core/window_modality_controller.cc deleted file mode 100644 index 1df375b..0000000 --- a/ui/wm/core/window_modality_controller.cc +++ /dev/null
@@ -1,201 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/window_modality_controller.h" - -#include <algorithm> - -#include "ui/aura/client/aura_constants.h" -#include "ui/aura/client/capture_client.h" -#include "ui/aura/env.h" -#include "ui/aura/window.h" -#include "ui/aura/window_event_dispatcher.h" -#include "ui/aura/window_property.h" -#include "ui/base/ui_base_types.h" -#include "ui/events/event.h" -#include "ui/events/event_target.h" -#include "ui/events/gestures/gesture_recognizer.h" -#include "ui/wm/core/window_animations.h" -#include "ui/wm/core/window_util.h" - -namespace wm { - -// Transient child's modal parent. -extern const aura::WindowProperty<aura::Window*>* const kModalParentKey; -DEFINE_WINDOW_PROPERTY_KEY(aura::Window*, kModalParentKey, NULL); - -namespace { - -bool HasAncestor(aura::Window* window, aura::Window* ancestor) { - if (!window) - return false; - if (window == ancestor) - return true; - return HasAncestor(window->parent(), ancestor); -} - -bool TransientChildIsWindowModal(aura::Window* window) { - return window->GetProperty(aura::client::kModalKey) == ui::MODAL_TYPE_WINDOW; -} - -bool TransientChildIsSystemModal(aura::Window* window) { - return window->GetProperty(aura::client::kModalKey) == ui::MODAL_TYPE_SYSTEM; -} - -bool TransientChildIsChildModal(aura::Window* window) { - return window->GetProperty(aura::client::kModalKey) == ui::MODAL_TYPE_CHILD; -} - -aura::Window* GetModalParent(aura::Window* window) { - return window->GetProperty(kModalParentKey); -} - -bool IsModalTransientChild(aura::Window* transient, aura::Window* original) { - return transient->IsVisible() && - (TransientChildIsWindowModal(transient) || - TransientChildIsSystemModal(transient) || - (TransientChildIsChildModal(transient) && - (HasAncestor(original, GetModalParent(transient))))); -} - -aura::Window* GetModalTransientChild( - aura::Window* activatable, - aura::Window* original) { - for (aura::Window::Windows::const_iterator it = - GetTransientChildren(activatable).begin(); - it != GetTransientChildren(activatable).end(); - ++it) { - aura::Window* transient = *it; - if (IsModalTransientChild(transient, original)) { - return GetTransientChildren(transient).empty() ? - transient : GetModalTransientChild(transient, original); - } - } - return NULL; -} - -} // namespace - -void SetModalParent(aura::Window* child, aura::Window* parent) { - child->SetProperty(kModalParentKey, parent); -} - -aura::Window* GetModalTransient(aura::Window* window) { - if (!window) - return NULL; - - // We always want to check the for the transient child of the toplevel window. - aura::Window* toplevel = GetToplevelWindow(window); - if (!toplevel) - return NULL; - - return GetModalTransientChild(toplevel, window); -} - -//////////////////////////////////////////////////////////////////////////////// -// WindowModalityController, public: - -WindowModalityController::WindowModalityController( - ui::EventTarget* event_target) - : event_target_(event_target) { - aura::Env::GetInstance()->AddObserver(this); - DCHECK(event_target->IsPreTargetListEmpty()); - event_target_->AddPreTargetHandler(this); -} - -WindowModalityController::~WindowModalityController() { - event_target_->RemovePreTargetHandler(this); - aura::Env::GetInstance()->RemoveObserver(this); - for (size_t i = 0; i < windows_.size(); ++i) - windows_[i]->RemoveObserver(this); -} - -//////////////////////////////////////////////////////////////////////////////// -// WindowModalityController, aura::EventFilter implementation: - -void WindowModalityController::OnKeyEvent(ui::KeyEvent* event) { - aura::Window* target = static_cast<aura::Window*>(event->target()); - if (GetModalTransient(target)) - event->SetHandled(); -} - -void WindowModalityController::OnMouseEvent(ui::MouseEvent* event) { - aura::Window* target = static_cast<aura::Window*>(event->target()); - if (ProcessLocatedEvent(target, event)) - event->SetHandled(); -} - -void WindowModalityController::OnTouchEvent(ui::TouchEvent* event) { - aura::Window* target = static_cast<aura::Window*>(event->target()); - if (ProcessLocatedEvent(target, event)) - event->SetHandled(); -} - -//////////////////////////////////////////////////////////////////////////////// -// WindowModalityController, aura::EnvObserver implementation: - -void WindowModalityController::OnWindowInitialized(aura::Window* window) { - windows_.push_back(window); - window->AddObserver(this); -} - -//////////////////////////////////////////////////////////////////////////////// -// WindowModalityController, aura::WindowObserver implementation: - -void WindowModalityController::OnWindowPropertyChanged(aura::Window* window, - const void* key, - intptr_t old) { - // In tests, we sometimes create the modality relationship after a window is - // visible. - if (key == aura::client::kModalKey && - window->GetProperty(aura::client::kModalKey) != ui::MODAL_TYPE_NONE && - window->IsVisible()) { - ActivateWindow(window); - ui::GestureRecognizer::Get()->TransferEventsTo(GetTransientParent(window), - NULL); - } -} - -void WindowModalityController::OnWindowVisibilityChanged( - aura::Window* window, - bool visible) { - if (visible && window->GetProperty(aura::client::kModalKey) != - ui::MODAL_TYPE_NONE) { - ui::GestureRecognizer::Get()->TransferEventsTo(GetTransientParent(window), - NULL); - // Make sure no other window has capture, otherwise |window| won't get mouse - // events. - aura::Window* capture_window = aura::client::GetCaptureWindow(window); - if (capture_window) - capture_window->ReleaseCapture(); - } -} - -void WindowModalityController::OnWindowDestroyed(aura::Window* window) { - windows_.erase(std::find(windows_.begin(), windows_.end(), window)); - window->RemoveObserver(this); -} - -bool WindowModalityController::ProcessLocatedEvent(aura::Window* target, - ui::LocatedEvent* event) { - if (event->handled()) - return false; - aura::Window* modal_transient_child = GetModalTransient(target); - if (modal_transient_child && (event->type() == ui::ET_MOUSE_PRESSED || - event->type() == ui::ET_TOUCH_PRESSED)) { - // Activate top window if transient child window is window modal. - if (TransientChildIsWindowModal(modal_transient_child)) { - aura::Window* toplevel = GetToplevelWindow(target); - DCHECK(toplevel); - ActivateWindow(toplevel); - } - - AnimateWindow(modal_transient_child, WINDOW_ANIMATION_TYPE_BOUNCE); - } - if (event->type() == ui::ET_TOUCH_CANCELLED) - return false; - return !!modal_transient_child; -} - -} // namespace wm
diff --git a/ui/wm/core/window_modality_controller.h b/ui/wm/core/window_modality_controller.h deleted file mode 100644 index 33386ce..0000000 --- a/ui/wm/core/window_modality_controller.h +++ /dev/null
@@ -1,71 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_CORE_WINDOW_MODALITY_CONTROLLER_H_ -#define UI_WM_CORE_WINDOW_MODALITY_CONTROLLER_H_ - -#include <vector> - -#include "base/compiler_specific.h" -#include "ui/aura/env_observer.h" -#include "ui/aura/window_observer.h" -#include "ui/events/event_handler.h" -#include "ui/wm/wm_export.h" - -namespace ui { -class EventTarget; -class LocatedEvent; -} - -namespace wm { - -// Sets the modal parent for the child. -WM_EXPORT void SetModalParent(aura::Window* child, aura::Window* parent); - -// Returns the modal transient child of |window|, or NULL if |window| does not -// have any modal transient children. -WM_EXPORT aura::Window* GetModalTransient(aura::Window* window); - -// WindowModalityController is an event filter that consumes events sent to -// windows that are the transient parents of window-modal windows. This filter -// must be added to the CompoundEventFilter so that activation works properly. -class WM_EXPORT WindowModalityController : public ui::EventHandler, - public aura::EnvObserver, - public aura::WindowObserver { - public: - explicit WindowModalityController(ui::EventTarget* event_target); - virtual ~WindowModalityController(); - - // Overridden from ui::EventHandler: - virtual void OnKeyEvent(ui::KeyEvent* event) override; - virtual void OnMouseEvent(ui::MouseEvent* event) override; - virtual void OnTouchEvent(ui::TouchEvent* event) override; - - // Overridden from aura::EnvObserver: - virtual void OnWindowInitialized(aura::Window* window) override; - - // Overridden from aura::WindowObserver: - virtual void OnWindowPropertyChanged(aura::Window* window, - const void* key, - intptr_t old) override; - virtual void OnWindowVisibilityChanged(aura::Window* window, - bool visible) override; - virtual void OnWindowDestroyed(aura::Window* window) override; - - private: - // Processes a mouse/touch event, and returns true if the event should be - // consumed. - bool ProcessLocatedEvent(aura::Window* target, - ui::LocatedEvent* event); - - std::vector<aura::Window*> windows_; - - ui::EventTarget* event_target_; - - DISALLOW_COPY_AND_ASSIGN(WindowModalityController); -}; - -} // namespace wm - -#endif // UI_WM_CORE_WINDOW_MODALITY_CONTROLLER_H_
diff --git a/ui/wm/core/window_util.cc b/ui/wm/core/window_util.cc deleted file mode 100644 index 4004a46..0000000 --- a/ui/wm/core/window_util.cc +++ /dev/null
@@ -1,128 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/window_util.h" - -#include "ui/aura/window.h" -#include "ui/compositor/layer.h" -#include "ui/compositor/layer_tree_owner.h" -#include "ui/wm/core/transient_window_manager.h" -#include "ui/wm/public/activation_client.h" - -namespace { - -// Invokes RecreateLayer() on all the children of |to_clone|, adding the newly -// cloned children to |parent|. -// -// WARNING: It is assumed that |parent| is ultimately owned by a LayerTreeOwner. -void CloneChildren(ui::Layer* to_clone, ui::Layer* parent) { - typedef std::vector<ui::Layer*> Layers; - // Make a copy of the children since RecreateLayer() mutates it. - Layers children(to_clone->children()); - for (Layers::const_iterator i = children.begin(); i != children.end(); ++i) { - ui::LayerOwner* owner = (*i)->owner(); - ui::Layer* old_layer = owner ? owner->RecreateLayer().release() : NULL; - if (old_layer) { - parent->Add(old_layer); - // RecreateLayer() moves the existing children to the new layer. Create a - // copy of those. - CloneChildren(owner->layer(), old_layer); - } - } -} - -} // namespace - -namespace wm { - -void ActivateWindow(aura::Window* window) { - DCHECK(window); - DCHECK(window->GetRootWindow()); - aura::client::GetActivationClient(window->GetRootWindow())->ActivateWindow( - window); -} - -void DeactivateWindow(aura::Window* window) { - DCHECK(window); - DCHECK(window->GetRootWindow()); - aura::client::GetActivationClient(window->GetRootWindow())->DeactivateWindow( - window); -} - -bool IsActiveWindow(aura::Window* window) { - DCHECK(window); - if (!window->GetRootWindow()) - return false; - aura::client::ActivationClient* client = - aura::client::GetActivationClient(window->GetRootWindow()); - return client && client->GetActiveWindow() == window; -} - -bool CanActivateWindow(aura::Window* window) { - DCHECK(window); - if (!window->GetRootWindow()) - return false; - aura::client::ActivationClient* client = - aura::client::GetActivationClient(window->GetRootWindow()); - return client && client->CanActivateWindow(window); -} - -aura::Window* GetActivatableWindow(aura::Window* window) { - aura::client::ActivationClient* client = - aura::client::GetActivationClient(window->GetRootWindow()); - return client ? client->GetActivatableWindow(window) : NULL; -} - -aura::Window* GetToplevelWindow(aura::Window* window) { - aura::client::ActivationClient* client = - aura::client::GetActivationClient(window->GetRootWindow()); - return client ? client->GetToplevelWindow(window) : NULL; -} - -scoped_ptr<ui::LayerTreeOwner> RecreateLayers(ui::LayerOwner* root) { - scoped_ptr<ui::LayerTreeOwner> old_layer( - new ui::LayerTreeOwner(root->RecreateLayer().release())); - if (old_layer->root()) - CloneChildren(root->layer(), old_layer->root()); - return old_layer.Pass(); -} - -aura::Window* GetTransientParent(aura::Window* window) { - return const_cast<aura::Window*>(GetTransientParent( - const_cast<const aura::Window*>(window))); -} - -const aura::Window* GetTransientParent(const aura::Window* window) { - const TransientWindowManager* manager = TransientWindowManager::Get(window); - return manager ? manager->transient_parent() : NULL; -} - -const std::vector<aura::Window*>& GetTransientChildren( - const aura::Window* window) { - const TransientWindowManager* manager = TransientWindowManager::Get(window); - if (manager) - return manager->transient_children(); - - static std::vector<aura::Window*>* shared = new std::vector<aura::Window*>; - return *shared; -} - -void AddTransientChild(aura::Window* parent, aura::Window* child) { - TransientWindowManager::Get(parent)->AddTransientChild(child); -} - -void RemoveTransientChild(aura::Window* parent, aura::Window* child) { - TransientWindowManager::Get(parent)->RemoveTransientChild(child); -} - -bool HasTransientAncestor(const aura::Window* window, - const aura::Window* ancestor) { - const aura::Window* transient_parent = GetTransientParent(window); - if (transient_parent == ancestor) - return true; - return transient_parent ? - HasTransientAncestor(transient_parent, ancestor) : false; -} - -} // namespace wm
diff --git a/ui/wm/core/window_util.h b/ui/wm/core/window_util.h deleted file mode 100644 index 78f2ffb..0000000 --- a/ui/wm/core/window_util.h +++ /dev/null
@@ -1,67 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_CORE_WINDOW_UTIL_H_ -#define UI_WM_CORE_WINDOW_UTIL_H_ - -#include <vector> - -#include "base/basictypes.h" -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "ui/wm/wm_export.h" - -namespace aura { -class Window; -} - -namespace ui { -class Layer; -class LayerOwner; -class LayerTreeOwner; -} - -namespace wm { - -WM_EXPORT void ActivateWindow(aura::Window* window); -WM_EXPORT void DeactivateWindow(aura::Window* window); -WM_EXPORT bool IsActiveWindow(aura::Window* window); -WM_EXPORT bool CanActivateWindow(aura::Window* window); - -// Retrieves the activatable window for |window|. The ActivationClient makes -// this determination. -WM_EXPORT aura::Window* GetActivatableWindow(aura::Window* window); - -// Retrieves the toplevel window for |window|. The ActivationClient makes this -// determination. -WM_EXPORT aura::Window* GetToplevelWindow(aura::Window* window); - -// Returns the existing Layer for |root| (and all its descendants) and creates -// a new layer for |root| and all its descendants. This is intended for -// animations that want to animate between the existing visuals and a new state. -// -// As a result of this |root| has freshly created layers, meaning the layers -// have not yet been painted to. -WM_EXPORT scoped_ptr<ui::LayerTreeOwner> RecreateLayers( - ui::LayerOwner* root); - -// Convenience functions that get the TransientWindowManager for the window and -// redirect appropriately. These are preferable to calling functions on -// TransientWindowManager as they handle the appropriate NULL checks. -WM_EXPORT aura::Window* GetTransientParent(aura::Window* window); -WM_EXPORT const aura::Window* GetTransientParent( - const aura::Window* window); -WM_EXPORT const std::vector<aura::Window*>& GetTransientChildren( - const aura::Window* window); -WM_EXPORT void AddTransientChild(aura::Window* parent, aura::Window* child); -WM_EXPORT void RemoveTransientChild(aura::Window* parent, aura::Window* child); - -// Returns true if |window| has |ancestor| as a transient ancestor. A transient -// ancestor is found by following the transient parent chain of the window. -WM_EXPORT bool HasTransientAncestor(const aura::Window* window, - const aura::Window* ancestor); - -} // namespace wm - -#endif // UI_WM_CORE_WINDOW_UTIL_H_
diff --git a/ui/wm/core/window_util_unittest.cc b/ui/wm/core/window_util_unittest.cc deleted file mode 100644 index 35be225..0000000 --- a/ui/wm/core/window_util_unittest.cc +++ /dev/null
@@ -1,52 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/window_util.h" - -#include "base/memory/scoped_ptr.h" -#include "ui/aura/test/aura_test_base.h" -#include "ui/aura/test/test_windows.h" -#include "ui/aura/window.h" -#include "ui/compositor/layer.h" -#include "ui/compositor/layer_tree_owner.h" - -namespace wm { - -typedef aura::test::AuraTestBase WindowUtilTest; - -// Test if the recreate layers does not recreate layers that have -// already been acquired. -TEST_F(WindowUtilTest, RecreateLayers) { - scoped_ptr<aura::Window> window1( - aura::test::CreateTestWindowWithId(0, NULL)); - scoped_ptr<aura::Window> window11( - aura::test::CreateTestWindowWithId(1, window1.get())); - scoped_ptr<aura::Window> window12( - aura::test::CreateTestWindowWithId(2, window1.get())); - - ASSERT_EQ(2u, window1->layer()->children().size()); - - scoped_ptr<ui::Layer> acquired(window11->AcquireLayer()); - EXPECT_TRUE(acquired.get()); - EXPECT_EQ(acquired.get(), window11->layer()); - - scoped_ptr<ui::LayerTreeOwner> tree = - wm::RecreateLayers(window1.get()); - - // The detached layer should not have the layer that has - // already been detached. - ASSERT_EQ(1u, tree->root()->children().size()); - // Child layer is new instance. - EXPECT_NE(window11->layer(), tree->root()->children()[0]); - EXPECT_NE(window12->layer(), tree->root()->children()[0]); - - // The original window should have both. - ASSERT_EQ(2u, window1->layer()->children().size()); - EXPECT_EQ(window11->layer(), window1->layer()->children()[0]); - EXPECT_EQ(window12->layer(), window1->layer()->children()[1]); - - // Delete the window before the acquired layer is deleted. - window11.reset(); -} -} // namespace wm
diff --git a/ui/wm/core/wm_core_switches.cc b/ui/wm/core/wm_core_switches.cc deleted file mode 100644 index 12fbfcc..0000000 --- a/ui/wm/core/wm_core_switches.cc +++ /dev/null
@@ -1,16 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/wm_core_switches.h" - -#include "base/command_line.h" - -namespace wm { -namespace switches { - -// If present animations are disabled. -const char kWindowAnimationsDisabled[] = "wm-window-animations-disabled"; - -} // namespace switches -} // namespace wm
diff --git a/ui/wm/core/wm_core_switches.h b/ui/wm/core/wm_core_switches.h deleted file mode 100644 index 05658d6..0000000 --- a/ui/wm/core/wm_core_switches.h +++ /dev/null
@@ -1,24 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_CORE_WM_CORE_SWITCHES_H_ -#define UI_WM_CORE_WM_CORE_SWITCHES_H_ - -#include "build/build_config.h" -#include "ui/wm/wm_export.h" - -namespace wm { -namespace switches { - -// Note: If you add a switch, consider if it needs to be copied to a subsequent -// command line if the process executes a new copy of itself. (For example, -// see chromeos::LoginUtil::GetOffTheRecordCommandLine().) - -// Please keep alphabetized. -WM_EXPORT extern const char kWindowAnimationsDisabled[]; - -} // namespace switches -} // namespace wm - -#endif // UI_WM_CORE_WM_CORE_SWITCHES_H_
diff --git a/ui/wm/core/wm_state.cc b/ui/wm/core/wm_state.cc deleted file mode 100644 index 6d58086..0000000 --- a/ui/wm/core/wm_state.cc +++ /dev/null
@@ -1,30 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/core/wm_state.h" - -#include "ui/events/platform/platform_event_source.h" -#include "ui/wm/core/transient_window_controller.h" -#include "ui/wm/core/transient_window_stacking_client.h" - -namespace wm { - -WMState::WMState() - : window_stacking_client_(new TransientWindowStackingClient), - transient_window_client_(new TransientWindowController) { - aura::client::SetWindowStackingClient(window_stacking_client_.get()); - aura::client::SetTransientWindowClient(transient_window_client_.get()); -} - -WMState::~WMState() { - if (aura::client::GetWindowStackingClient() == window_stacking_client_.get()) - aura::client::SetWindowStackingClient(NULL); - - if (aura::client::GetTransientWindowClient() == - transient_window_client_.get()) { - aura::client::SetTransientWindowClient(NULL); - } -} - -} // namespace wm
diff --git a/ui/wm/core/wm_state.h b/ui/wm/core/wm_state.h deleted file mode 100644 index 289c9da..0000000 --- a/ui/wm/core/wm_state.h +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright (c) 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_CORE_WM_STATE_H_ -#define UI_WM_CORE_WM_STATE_H_ - -#include "base/memory/scoped_ptr.h" -#include "ui/wm/wm_export.h" - -namespace wm { - -class TransientWindowController; -class TransientWindowStackingClient; - -// Installs state needed by the window manager. -class WM_EXPORT WMState { - public: - WMState(); - ~WMState(); - - // WindowStackingClient: - private: - scoped_ptr<TransientWindowStackingClient> window_stacking_client_; - scoped_ptr<TransientWindowController> transient_window_client_; - - DISALLOW_COPY_AND_ASSIGN(WMState); -}; - -} // namespace wm - -#endif // UI_WM_CORE_WM_STATE_H_
diff --git a/ui/wm/public/DEPS b/ui/wm/public/DEPS deleted file mode 100644 index 1e9f248..0000000 --- a/ui/wm/public/DEPS +++ /dev/null
@@ -1,9 +0,0 @@ -include_rules = [ - "+ui/base/dragdrop/drag_drop_types.h", -] - -specific_include_rules = { - "drag_drop_client.h": [ - "+ui/base/dragdrop/drag_drop_types.h", - ], -}
diff --git a/ui/wm/public/activation_change_observer.cc b/ui/wm/public/activation_change_observer.cc deleted file mode 100644 index 7fcbb7a..0000000 --- a/ui/wm/public/activation_change_observer.cc +++ /dev/null
@@ -1,29 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/public/activation_change_observer.h" - -#include "ui/aura/window.h" -#include "ui/aura/window_property.h" - -DECLARE_WINDOW_PROPERTY_TYPE(aura::client::ActivationChangeObserver*) - -namespace aura { -namespace client { - -DEFINE_LOCAL_WINDOW_PROPERTY_KEY( - ActivationChangeObserver*, kActivationChangeObserverKey, NULL); - -void SetActivationChangeObserver( - Window* window, - ActivationChangeObserver* observer) { - window->SetProperty(kActivationChangeObserverKey, observer); -} - -ActivationChangeObserver* GetActivationChangeObserver(Window* window) { - return window ? window->GetProperty(kActivationChangeObserverKey) : NULL; -} - -} // namespace client -} // namespace aura
diff --git a/ui/wm/public/activation_change_observer.h b/ui/wm/public/activation_change_observer.h deleted file mode 100644 index 68d5b8a..0000000 --- a/ui/wm/public/activation_change_observer.h +++ /dev/null
@@ -1,45 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_PUBLIC_ACTIVATION_CHANGE_OBSERVER_H_ -#define UI_WM_PUBLIC_ACTIVATION_CHANGE_OBSERVER_H_ - -#include "ui/aura/aura_export.h" - -namespace aura { -class Window; - -namespace client { - -class AURA_EXPORT ActivationChangeObserver { - public: - // Called when |active| gains focus, or there is no active window - // (|active| is NULL in this case.) |old_active| refers to the - // previous active window or NULL if there was no previously active - // window. - virtual void OnWindowActivated(Window* gained_active, - Window* lost_active) = 0; - - // Called when during window activation the currently active window is - // selected for activation. This can happen when a window requested for - // activation cannot be activated because a system modal window is active. - virtual void OnAttemptToReactivateWindow(aura::Window* request_active, - aura::Window* actual_active) {} - - protected: - virtual ~ActivationChangeObserver() {} -}; - -// Gets/Sets the ActivationChangeObserver for a specific window. This observer -// is notified after the ActivationClient notifies all registered observers. -AURA_EXPORT void SetActivationChangeObserver( - Window* window, - ActivationChangeObserver* observer); -AURA_EXPORT ActivationChangeObserver* GetActivationChangeObserver( - Window* window); - -} // namespace client -} // namespace aura - -#endif // UI_WM_PUBLIC_ACTIVATION_CHANGE_OBSERVER_H_
diff --git a/ui/wm/public/activation_client.cc b/ui/wm/public/activation_client.cc deleted file mode 100644 index 6a47554..0000000 --- a/ui/wm/public/activation_client.cc +++ /dev/null
@@ -1,38 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/public/activation_client.h" - -#include "ui/aura/window.h" -#include "ui/aura/window_property.h" - -DECLARE_EXPORTED_WINDOW_PROPERTY_TYPE(AURA_EXPORT, aura::Window*) -DECLARE_WINDOW_PROPERTY_TYPE(aura::client::ActivationClient*) - -namespace aura { -namespace client { - -DEFINE_WINDOW_PROPERTY_KEY( - ActivationClient*, kRootWindowActivationClientKey, NULL); -DEFINE_WINDOW_PROPERTY_KEY(bool, kHideOnDeactivate, false); - -void SetActivationClient(Window* root_window, ActivationClient* client) { - root_window->SetProperty(kRootWindowActivationClientKey, client); -} - -ActivationClient* GetActivationClient(Window* root_window) { - return root_window ? - root_window->GetProperty(kRootWindowActivationClientKey) : NULL; -} - -void SetHideOnDeactivate(Window* window, bool hide_on_deactivate) { - window->SetProperty(kHideOnDeactivate, hide_on_deactivate); -} - -bool GetHideOnDeactivate(Window* window) { - return window->GetProperty(kHideOnDeactivate); -} - -} // namespace client -} // namespace aura
diff --git a/ui/wm/public/activation_client.h b/ui/wm/public/activation_client.h deleted file mode 100644 index 4e01778..0000000 --- a/ui/wm/public/activation_client.h +++ /dev/null
@@ -1,73 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_PUBLIC_ACTIVATION_CLIENT_H_ -#define UI_WM_PUBLIC_ACTIVATION_CLIENT_H_ - -#include "ui/aura/aura_export.h" - -namespace ui { -class Event; -} - -namespace aura { -class Window; - -namespace client { -class ActivationChangeObserver; - -// An interface implemented by an object that manages window activation. -class AURA_EXPORT ActivationClient { - public: - // Adds/Removes ActivationChangeObservers. - virtual void AddObserver(ActivationChangeObserver* observer) = 0; - virtual void RemoveObserver(ActivationChangeObserver* observer) = 0; - - // Activates |window|. If |window| is NULL, nothing happens. - virtual void ActivateWindow(Window* window) = 0; - - // Deactivates |window|. What (if anything) is activated next is up to the - // client. If |window| is NULL, nothing happens. - virtual void DeactivateWindow(Window* window) = 0; - - // Retrieves the active window, or NULL if there is none. - virtual Window* GetActiveWindow() = 0; - - // Retrieves the activatable window for |window|, or NULL if there is none. - // Note that this is often but not always the toplevel window (see - // GetToplevelWindow() below), as the toplevel window may not be activatable - // (for example it may be blocked by a modal transient, or some other - // condition). - virtual Window* GetActivatableWindow(Window* window) = 0; - - // Retrieves the toplevel window for |window|, or NULL if there is none. - virtual Window* GetToplevelWindow(Window* window) = 0; - - // Returns true if |window| can be activated, false otherwise. If |window| has - // a modal child it can not be activated. - virtual bool CanActivateWindow(Window* window) const = 0; - - protected: - virtual ~ActivationClient() {} -}; - -// Sets/Gets the activation client on the root Window. -AURA_EXPORT void SetActivationClient(Window* root_window, - ActivationClient* client); -AURA_EXPORT ActivationClient* GetActivationClient(Window* root_window); - -// Some types of transient window are only visible when active. -// The transient parents of these windows may have visual appearance properties -// that differ from transient parents that can be deactivated. -// The presence of this property implies these traits. -// TODO(beng): currently the UI framework (views) implements the actual -// close-on-deactivate component of this feature but it should be -// possible to implement in the aura client. -AURA_EXPORT void SetHideOnDeactivate(Window* window, bool hide_on_deactivate); -AURA_EXPORT bool GetHideOnDeactivate(Window* window); - -} // namespace clients -} // namespace aura - -#endif // UI_WM_PUBLIC_ACTIVATION_CLIENT_H_
diff --git a/ui/wm/public/activation_delegate.cc b/ui/wm/public/activation_delegate.cc deleted file mode 100644 index 2a9bbc9..0000000 --- a/ui/wm/public/activation_delegate.cc +++ /dev/null
@@ -1,27 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/public/activation_delegate.h" - -#include "ui/aura/window.h" -#include "ui/aura/window_property.h" - -DECLARE_WINDOW_PROPERTY_TYPE(aura::client::ActivationDelegate*) - -namespace aura { -namespace client { - -DEFINE_LOCAL_WINDOW_PROPERTY_KEY( - ActivationDelegate*, kActivationDelegateKey, NULL); - -void SetActivationDelegate(Window* window, ActivationDelegate* delegate) { - window->SetProperty(kActivationDelegateKey, delegate); -} - -ActivationDelegate* GetActivationDelegate(Window* window) { - return window->GetProperty(kActivationDelegateKey); -} - -} // namespace client -} // namespace aura
diff --git a/ui/wm/public/activation_delegate.h b/ui/wm/public/activation_delegate.h deleted file mode 100644 index 3c5b3ae..0000000 --- a/ui/wm/public/activation_delegate.h +++ /dev/null
@@ -1,37 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_PUBLIC_ACTIVATION_DELEGATE_H_ -#define UI_WM_PUBLIC_ACTIVATION_DELEGATE_H_ - -#include "ui/aura/aura_export.h" - -namespace ui { -class Event; -} - -namespace aura { -class Window; -namespace client { - -// An interface implemented by an object that configures and responds to changes -// to a window's activation state. -class AURA_EXPORT ActivationDelegate { - public: - // Returns true if the window should be activated. - virtual bool ShouldActivate() const = 0; - - protected: - virtual ~ActivationDelegate() {} -}; - -// Sets/Gets the ActivationDelegate on the Window. No ownership changes. -AURA_EXPORT void SetActivationDelegate(Window* window, - ActivationDelegate* delegate); -AURA_EXPORT ActivationDelegate* GetActivationDelegate(Window* window); - -} // namespace client -} // namespace aura - -#endif // UI_WM_PUBLIC_ACTIVATION_DELEGATE_H_
diff --git a/ui/wm/public/animation_host.cc b/ui/wm/public/animation_host.cc deleted file mode 100644 index 0d90f9c..0000000 --- a/ui/wm/public/animation_host.cc +++ /dev/null
@@ -1,28 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/public/animation_host.h" - -#include "ui/aura/window.h" -#include "ui/aura/window_property.h" - -DECLARE_WINDOW_PROPERTY_TYPE(aura::client::AnimationHost*) - -namespace aura { -namespace client { - -DEFINE_WINDOW_PROPERTY_KEY(AnimationHost*, kRootWindowAnimationHostKey, NULL); - -void SetAnimationHost(Window* window, AnimationHost* animation_host) { - DCHECK(window); - window->SetProperty(kRootWindowAnimationHostKey, animation_host); -} - -AnimationHost* GetAnimationHost(Window* window) { - DCHECK(window); - return window->GetProperty(kRootWindowAnimationHostKey); -} - -} // namespace client -} // namespace aura
diff --git a/ui/wm/public/animation_host.h b/ui/wm/public/animation_host.h deleted file mode 100644 index 71f9f4d..0000000 --- a/ui/wm/public/animation_host.h +++ /dev/null
@@ -1,48 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_PUBLIC_ANIMATION_HOST_H_ -#define UI_WM_PUBLIC_ANIMATION_HOST_H_ - -#include "base/compiler_specific.h" -#include "ui/aura/aura_export.h" - -namespace gfx { -class Vector2d; -} - -namespace aura { -class Window; -namespace client { - -// Interface for top level window host of animation. Communicates additional -// bounds required for animation as well as animation completion for deferring -// window closes on hide. -class AURA_EXPORT AnimationHost { - public: - // Ensure the host window is at least this large so that transitions have - // sufficient space. - // The |top_left_delta| parameter contains the offset to be subtracted from - // the window bounds for the top left corner. - // The |bottom_right_delta| parameter contains the offset to be added to the - // window bounds for the bottom right. - virtual void SetHostTransitionOffsets( - const gfx::Vector2d& top_left_delta, - const gfx::Vector2d& bottom_right_delta) = 0; - - // Called after the window has faded out on a hide. - virtual void OnWindowHidingAnimationCompleted() = 0; - - protected: - virtual ~AnimationHost() {} -}; - -AURA_EXPORT void SetAnimationHost(Window* window, - AnimationHost* animation_host); -AURA_EXPORT AnimationHost* GetAnimationHost(Window* window); - -} // namespace client -} // namespace aura - -#endif // UI_WM_PUBLIC_ANIMATION_HOST_H_
diff --git a/ui/wm/public/dispatcher_client.cc b/ui/wm/public/dispatcher_client.cc deleted file mode 100644 index e3be7ca..0000000 --- a/ui/wm/public/dispatcher_client.cc +++ /dev/null
@@ -1,52 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/public/dispatcher_client.h" - -#include "base/callback.h" -#include "ui/aura/window.h" -#include "ui/aura/window_property.h" - -DECLARE_WINDOW_PROPERTY_TYPE(aura::client::DispatcherClient*); - -namespace aura { -namespace client { - -DispatcherRunLoop::DispatcherRunLoop(DispatcherClient* client, - base::MessagePumpDispatcher* dispatcher) { - client->PrepareNestedLoopClosures(dispatcher, &run_closure_, &quit_closure_); -} - -DispatcherRunLoop::~DispatcherRunLoop() { -} - -void DispatcherRunLoop::Run() { - base::MessageLoopForUI* loop = base::MessageLoopForUI::current(); - base::MessageLoopForUI::ScopedNestableTaskAllower allow_nested(loop); - run_closure_.Run(); -} - -base::Closure DispatcherRunLoop::QuitClosure() { - return quit_closure_; -} - -void DispatcherRunLoop::Quit() { - quit_closure_.Run(); -} - -DEFINE_LOCAL_WINDOW_PROPERTY_KEY(DispatcherClient*, kDispatcherClientKey, NULL); - -void SetDispatcherClient(Window* root_window, DispatcherClient* client) { - DCHECK_EQ(root_window->GetRootWindow(), root_window); - root_window->SetProperty(kDispatcherClientKey, client); -} - -DispatcherClient* GetDispatcherClient(Window* root_window) { - if (root_window) - DCHECK_EQ(root_window->GetRootWindow(), root_window); - return root_window ? root_window->GetProperty(kDispatcherClientKey) : NULL; -} - -} // namespace client -} // namespace aura
diff --git a/ui/wm/public/dispatcher_client.h b/ui/wm/public/dispatcher_client.h deleted file mode 100644 index a301e92..0000000 --- a/ui/wm/public/dispatcher_client.h +++ /dev/null
@@ -1,59 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_PUBLIC_DISPATCHER_CLIENT_H_ -#define UI_WM_PUBLIC_DISPATCHER_CLIENT_H_ - -#include "base/callback.h" -#include "base/macros.h" -#include "base/message_loop/message_pump_dispatcher.h" -#include "ui/aura/aura_export.h" - -namespace aura { -class Window; -namespace client { - -class DispatcherClient; - -// A base::RunLoop like object for running a nested message-loop with a -// specified DispatcherClient and a MessagePumpDispatcher. -class AURA_EXPORT DispatcherRunLoop { - public: - DispatcherRunLoop(DispatcherClient* client, - base::MessagePumpDispatcher* dispatcher); - ~DispatcherRunLoop(); - - void Run(); - base::Closure QuitClosure(); - void Quit(); - - private: - base::Closure run_closure_; - base::Closure quit_closure_; - - DISALLOW_COPY_AND_ASSIGN(DispatcherRunLoop); -}; - -// An interface implemented by an object which handles nested dispatchers. -class AURA_EXPORT DispatcherClient { - public: - virtual ~DispatcherClient() {} - - protected: - friend class DispatcherRunLoop; - - virtual void PrepareNestedLoopClosures( - base::MessagePumpDispatcher* dispatcher, - base::Closure* run_closure, - base::Closure* quit_closure) = 0; -}; - -AURA_EXPORT void SetDispatcherClient(Window* root_window, - DispatcherClient* client); -AURA_EXPORT DispatcherClient* GetDispatcherClient(Window* root_window); - -} // namespace client -} // namespace aura - -#endif // UI_WM_PUBLIC_DISPATCHER_CLIENT_H_
diff --git a/ui/wm/public/drag_drop_client.cc b/ui/wm/public/drag_drop_client.cc deleted file mode 100644 index c452f9e..0000000 --- a/ui/wm/public/drag_drop_client.cc +++ /dev/null
@@ -1,31 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/public/drag_drop_client.h" - -#include "ui/aura/window.h" -#include "ui/aura/window_property.h" - -DECLARE_WINDOW_PROPERTY_TYPE(aura::client::DragDropClient*) - -namespace aura { -namespace client { - -DEFINE_LOCAL_WINDOW_PROPERTY_KEY( - DragDropClient*, kRootWindowDragDropClientKey, NULL); - -void SetDragDropClient(Window* root_window, DragDropClient* client) { - DCHECK_EQ(root_window->GetRootWindow(), root_window); - root_window->SetProperty(kRootWindowDragDropClientKey, client); -} - -DragDropClient* GetDragDropClient(Window* root_window) { - if (root_window) - DCHECK_EQ(root_window->GetRootWindow(), root_window); - return root_window ? - root_window->GetProperty(kRootWindowDragDropClientKey) : NULL; -} - -} // namespace client -} // namespace aura
diff --git a/ui/wm/public/drag_drop_client.h b/ui/wm/public/drag_drop_client.h deleted file mode 100644 index 62a2355..0000000 --- a/ui/wm/public/drag_drop_client.h +++ /dev/null
@@ -1,62 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_PUBLIC_DRAG_DROP_CLIENT_H_ -#define UI_WM_PUBLIC_DRAG_DROP_CLIENT_H_ - -#include "ui/aura/aura_export.h" -#include "ui/base/dragdrop/drag_drop_types.h" -#include "ui/gfx/native_widget_types.h" - -namespace gfx { -class Point; -} - -namespace ui { -class LocatedEvent; -class OSExchangeData; -} - -namespace aura { -class Window; -namespace client { - -// An interface implemented by an object that controls a drag and drop session. -class AURA_EXPORT DragDropClient { - public: - virtual ~DragDropClient() {} - - // Initiates a drag and drop session. Returns the drag operation that was - // applied at the end of the drag drop session. |root_location| is in the - // root Window's coordinate system. - virtual int StartDragAndDrop(const ui::OSExchangeData& data, - aura::Window* root_window, - aura::Window* source_window, - const gfx::Point& root_location, - int operation, - ui::DragDropTypes::DragEventSource source) = 0; - - // Called when mouse is dragged during a drag and drop. - virtual void DragUpdate(aura::Window* target, - const ui::LocatedEvent& event) = 0; - - // Called when mouse is released during a drag and drop. - virtual void Drop(aura::Window* target, - const ui::LocatedEvent& event) = 0; - - // Called when a drag and drop session is cancelled. - virtual void DragCancel() = 0; - - // Returns true if a drag and drop session is in progress. - virtual bool IsDragDropInProgress() = 0; -}; - -AURA_EXPORT void SetDragDropClient(Window* root_window, - DragDropClient* client); -AURA_EXPORT DragDropClient* GetDragDropClient(Window* root_window); - -} // namespace client -} // namespace aura - -#endif // UI_WM_PUBLIC_DRAG_DROP_CLIENT_H_
diff --git a/ui/wm/public/drag_drop_delegate.cc b/ui/wm/public/drag_drop_delegate.cc deleted file mode 100644 index 6380f96..0000000 --- a/ui/wm/public/drag_drop_delegate.cc +++ /dev/null
@@ -1,27 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/public/drag_drop_delegate.h" - -#include "ui/aura/window.h" -#include "ui/aura/window_property.h" - -DECLARE_WINDOW_PROPERTY_TYPE(aura::client::DragDropDelegate*) - -namespace aura { -namespace client { - -DEFINE_LOCAL_WINDOW_PROPERTY_KEY( - DragDropDelegate*, kDragDropDelegateKey, NULL); - -void SetDragDropDelegate(Window* window, DragDropDelegate* delegate) { - window->SetProperty(kDragDropDelegateKey, delegate); -} - -DragDropDelegate* GetDragDropDelegate(Window* window) { - return window->GetProperty(kDragDropDelegateKey); -} - -} // namespace client -} // namespace aura
diff --git a/ui/wm/public/drag_drop_delegate.h b/ui/wm/public/drag_drop_delegate.h deleted file mode 100644 index 50f6c26..0000000 --- a/ui/wm/public/drag_drop_delegate.h +++ /dev/null
@@ -1,51 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_PUBLIC_DRAG_DROP_DELEGATE_H_ -#define UI_WM_PUBLIC_DRAG_DROP_DELEGATE_H_ - -#include "ui/aura/aura_export.h" - -namespace ui { -class DropTargetEvent; -} - -namespace aura { -class Window; -namespace client { - -// Delegate interface for drag and drop actions on aura::Window. -class AURA_EXPORT DragDropDelegate { - public: - // OnDragEntered is invoked when the mouse enters this window during a drag & - // drop session. This is immediately followed by an invocation of - // OnDragUpdated, and eventually one of OnDragExited or OnPerformDrop. - virtual void OnDragEntered(const ui::DropTargetEvent& event) = 0; - - // Invoked during a drag and drop session while the mouse is over the window. - // This should return a bitmask of the DragDropTypes::DragOperation supported - // based on the location of the event. Return 0 to indicate the drop should - // not be accepted. - virtual int OnDragUpdated(const ui::DropTargetEvent& event) = 0; - - // Invoked during a drag and drop session when the mouse exits the window, or - // when the drag session was canceled and the mouse was over the window. - virtual void OnDragExited() = 0; - - // Invoked during a drag and drop session when OnDragUpdated returns a valid - // operation and the user release the mouse. - virtual int OnPerformDrop(const ui::DropTargetEvent& event) = 0; - - protected: - virtual ~DragDropDelegate() {} -}; - -AURA_EXPORT void SetDragDropDelegate(Window* window, - DragDropDelegate* delegate); -AURA_EXPORT DragDropDelegate* GetDragDropDelegate(Window* window); - -} // namespace client -} // namespace aura - -#endif // UI_WM_PUBLIC_DRAG_DROP_DELEGATE_H_
diff --git a/ui/wm/public/scoped_tooltip_disabler.cc b/ui/wm/public/scoped_tooltip_disabler.cc deleted file mode 100644 index 45a39ca..0000000 --- a/ui/wm/public/scoped_tooltip_disabler.cc +++ /dev/null
@@ -1,43 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/public/scoped_tooltip_disabler.h" - -#include "ui/aura/window.h" -#include "ui/wm/public/tooltip_client.h" - -namespace aura { -namespace client { - -ScopedTooltipDisabler::ScopedTooltipDisabler(aura::Window* window) - : root_(window ? window->GetRootWindow() : NULL) { - if (root_) { - root_->AddObserver(this); - TooltipClient* client = GetTooltipClient(root_); - if (client) - client->SetTooltipsEnabled(false); - } -} - -ScopedTooltipDisabler::~ScopedTooltipDisabler() { - EnableTooltips(); -} - -void ScopedTooltipDisabler::EnableTooltips() { - if (!root_) - return; - TooltipClient* client = GetTooltipClient(root_); - if (client) - client->SetTooltipsEnabled(true); - root_->RemoveObserver(this); - root_ = NULL; -} - -void ScopedTooltipDisabler::OnWindowDestroying(aura::Window* window) { - EnableTooltips(); -} - - -} // namespace client -} // namespace aura
diff --git a/ui/wm/public/scoped_tooltip_disabler.h b/ui/wm/public/scoped_tooltip_disabler.h deleted file mode 100644 index 1022788..0000000 --- a/ui/wm/public/scoped_tooltip_disabler.h +++ /dev/null
@@ -1,39 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_PUBLIC_SCOPED_TOOLTIP_DISABLER_H_ -#define UI_WM_PUBLIC_SCOPED_TOOLTIP_DISABLER_H_ - -#include "ui/aura/window_observer.h" - -namespace aura { -namespace client { - -// Use to temporarily disable tooltips. -class AURA_EXPORT ScopedTooltipDisabler : aura::WindowObserver { - public: - // Disables tooltips on |window| (does nothing if |window| is NULL). Tooltips - // are reenabled from the destructor when there are no most outstanding - // ScopedTooltipDisablers for |window|. - explicit ScopedTooltipDisabler(aura::Window* window); - virtual ~ScopedTooltipDisabler(); - - private: - // Reenables the tooltips on the TooltipClient. - void EnableTooltips(); - - // aura::WindowObserver: - virtual void OnWindowDestroying(aura::Window* window) override; - - // The RootWindow to disable Tooltips on; NULL if the Window passed to the - // constructor was not in a root or the root has been destroyed. - aura::Window* root_; - - DISALLOW_COPY_AND_ASSIGN(ScopedTooltipDisabler); -}; - -} // namespace client -} // namespace aura - -#endif // UI_WM_PUBLIC_SCOPED_TOOLTIP_DISABLER_H_
diff --git a/ui/wm/public/tooltip_client.cc b/ui/wm/public/tooltip_client.cc deleted file mode 100644 index 844cca5..0000000 --- a/ui/wm/public/tooltip_client.cc +++ /dev/null
@@ -1,52 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/public/tooltip_client.h" - -#include "ui/aura/window.h" -#include "ui/aura/window_property.h" - -DECLARE_WINDOW_PROPERTY_TYPE(aura::client::TooltipClient*) -DECLARE_WINDOW_PROPERTY_TYPE(base::string16*) -DECLARE_WINDOW_PROPERTY_TYPE(void**) - -namespace aura { -namespace client { - -DEFINE_LOCAL_WINDOW_PROPERTY_KEY( - TooltipClient*, kRootWindowTooltipClientKey, NULL); -DEFINE_LOCAL_WINDOW_PROPERTY_KEY(base::string16*, kTooltipTextKey, NULL); -DEFINE_LOCAL_WINDOW_PROPERTY_KEY(void*, kTooltipIdKey, NULL); - -void SetTooltipClient(Window* root_window, TooltipClient* client) { - DCHECK_EQ(root_window->GetRootWindow(), root_window); - root_window->SetProperty(kRootWindowTooltipClientKey, client); -} - -TooltipClient* GetTooltipClient(Window* root_window) { - if (root_window) - DCHECK_EQ(root_window->GetRootWindow(), root_window); - return root_window ? - root_window->GetProperty(kRootWindowTooltipClientKey) : NULL; -} - -void SetTooltipText(Window* window, base::string16* tooltip_text) { - window->SetProperty(kTooltipTextKey, tooltip_text); -} - -void SetTooltipId(Window* window, void* id) { - window->SetProperty(kTooltipIdKey, id); -} - -const base::string16 GetTooltipText(Window* window) { - base::string16* string_ptr = window->GetProperty(kTooltipTextKey); - return string_ptr ? *string_ptr : base::string16(); -} - -const void* GetTooltipId(Window* window) { - return window->GetProperty(kTooltipIdKey); -} - -} // namespace client -} // namespace aura
diff --git a/ui/wm/public/tooltip_client.h b/ui/wm/public/tooltip_client.h deleted file mode 100644 index f2b97cd..0000000 --- a/ui/wm/public/tooltip_client.h +++ /dev/null
@@ -1,51 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_PUBLIC_TOOLTIP_CLIENT_H_ -#define UI_WM_PUBLIC_TOOLTIP_CLIENT_H_ - -#include "ui/aura/aura_export.h" -#include "ui/gfx/font.h" - -namespace aura { -class Window; -namespace client { - -class ScopedTooltipDisabler; - -class AURA_EXPORT TooltipClient { - public: - // Informs the shell tooltip manager of change in tooltip for window |target|. - virtual void UpdateTooltip(Window* target) = 0; - - // Sets the time after which the tooltip is hidden for Window |target|. If - // |timeout_in_ms| is <= 0, the tooltip is shown indefinitely. - virtual void SetTooltipShownTimeout(Window* target, int timeout_in_ms) = 0; - - protected: - // Enables/Disables tooltips. This is treated as a reference count. Consumers - // must use ScopedTooltipDisabler to enable/disabled tooltips. - virtual void SetTooltipsEnabled(bool enable) = 0; - - private: - friend class ScopedTooltipDisabler; -}; - -AURA_EXPORT void SetTooltipClient(Window* root_window, - TooltipClient* client); -AURA_EXPORT TooltipClient* GetTooltipClient(Window* root_window); - -// Sets the text for the tooltip. The id is used to determine uniqueness when -// the text does not change. For example, if the tooltip text does not change, -// but the id does then the position of the tooltip is updated. -AURA_EXPORT void SetTooltipText(Window* window, - base::string16* tooltip_text); -AURA_EXPORT void SetTooltipId(Window* window, void* id); -AURA_EXPORT const base::string16 GetTooltipText(Window* window); -AURA_EXPORT const void* GetTooltipId(Window* window); - -} // namespace client -} // namespace aura - -#endif // UI_WM_PUBLIC_TOOLTIP_CLIENT_H_
diff --git a/ui/wm/public/transient_window_client.cc b/ui/wm/public/transient_window_client.cc deleted file mode 100644 index aab8e51..0000000 --- a/ui/wm/public/transient_window_client.cc +++ /dev/null
@@ -1,25 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/public/transient_window_client.h" - -namespace aura { -namespace client { - -namespace { - -TransientWindowClient* instance = NULL; - -} // namespace - -void SetTransientWindowClient(TransientWindowClient* client) { - instance = client; -} - -TransientWindowClient* GetTransientWindowClient() { - return instance; -} - -} // namespace client -} // namespace aura
diff --git a/ui/wm/public/transient_window_client.h b/ui/wm/public/transient_window_client.h deleted file mode 100644 index 2086100..0000000 --- a/ui/wm/public/transient_window_client.h +++ /dev/null
@@ -1,47 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_PUBLIC_TRANSIENT_WINDOW_CLIENT_H_ -#define UI_WM_PUBLIC_TRANSIENT_WINDOW_CLIENT_H_ - -#include "base/basictypes.h" -#include "ui/aura/aura_export.h" - -namespace aura { - -class Window; - -namespace client { - -// TransientWindowClient is used to add or remove transient windows. Transient -// children get the following behavior: -// . The transient parent destroys any transient children when it is -// destroyed. This means a transient child is destroyed if either its parent -// or transient parent is destroyed. -// . If a transient child and its transient parent share the same parent, then -// transient children are always ordered above the transient parent. -// Transient windows are typically used for popups and menus. -// TODO(sky): nuke this class and replace with calls to TransientWindowManager. -// This is temporary until we start moving to ui/wm. -class AURA_EXPORT TransientWindowClient { - public: - virtual void AddTransientChild(Window* parent, Window* child) = 0; - virtual void RemoveTransientChild(Window* parent, Window* child) = 0; - virtual Window* GetTransientParent(Window* window) = 0; - virtual const Window* GetTransientParent(const Window* window) = 0; - - protected: - virtual ~TransientWindowClient() {} -}; - -// Sets/gets the TransientWindowClient. This does *not* take ownership of -// |client|. It is assumed the caller will invoke SetTransientWindowClient(NULL) -// before deleting |client|. -AURA_EXPORT void SetTransientWindowClient(TransientWindowClient* client); -AURA_EXPORT TransientWindowClient* GetTransientWindowClient(); - -} // namespace client -} // namespace aura - -#endif // UI_WM_PUBLIC_TRANSIENT_WINDOW_CLIENT_H_
diff --git a/ui/wm/public/window_move_client.cc b/ui/wm/public/window_move_client.cc deleted file mode 100644 index 44ccca9..0000000 --- a/ui/wm/public/window_move_client.cc +++ /dev/null
@@ -1,28 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/public/window_move_client.h" - -#include "ui/aura/window.h" -#include "ui/aura/window_property.h" - -DECLARE_WINDOW_PROPERTY_TYPE(aura::client::WindowMoveClient*) - -namespace aura { -namespace client { - -// A property key to store a client that handles window moves. -DEFINE_LOCAL_WINDOW_PROPERTY_KEY( - WindowMoveClient*, kWindowMoveClientKey, NULL); - -void SetWindowMoveClient(Window* window, WindowMoveClient* client) { - window->SetProperty(kWindowMoveClientKey, client); -} - -WindowMoveClient* GetWindowMoveClient(Window* window) { - return window->GetProperty(kWindowMoveClientKey); -} - -} // namespace client -} // namespace aura
diff --git a/ui/wm/public/window_move_client.h b/ui/wm/public/window_move_client.h deleted file mode 100644 index b8943d3..0000000 --- a/ui/wm/public/window_move_client.h +++ /dev/null
@@ -1,56 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_PUBLIC_WINDOW_MOVE_CLIENT_H_ -#define UI_WM_PUBLIC_WINDOW_MOVE_CLIENT_H_ - -#include "ui/aura/aura_export.h" -#include "ui/gfx/vector2d.h" - -namespace gfx { -class Point; -} - -namespace aura { -class Window; -namespace client { - -enum WindowMoveResult { - MOVE_SUCCESSFUL, // Moving window was successful. - MOVE_CANCELED // Moving window was canceled. -}; - -enum WindowMoveSource { - WINDOW_MOVE_SOURCE_MOUSE, - WINDOW_MOVE_SOURCE_TOUCH, -}; - -// An interface implemented by an object that manages programatically keyed -// window moving. -class AURA_EXPORT WindowMoveClient { - public: - // Starts a nested message loop for moving the window. |drag_offset| is the - // offset from the window origin to the cursor when the drag was started. - // Returns MOVE_SUCCESSFUL if the move has completed successfully, or - // MOVE_CANCELED otherwise. - virtual WindowMoveResult RunMoveLoop(Window* window, - const gfx::Vector2d& drag_offset, - WindowMoveSource source) = 0; - - // Ends a previously started move loop. - virtual void EndMoveLoop() = 0; - - protected: - virtual ~WindowMoveClient() {} -}; - -// Sets/Gets the activation client for the specified window. -AURA_EXPORT void SetWindowMoveClient(Window* window, - WindowMoveClient* client); -AURA_EXPORT WindowMoveClient* GetWindowMoveClient(Window* window); - -} // namespace client -} // namespace aura - -#endif // UI_WM_PUBLIC_WINDOW_MOVE_CLIENT_H_
diff --git a/ui/wm/public/window_types.h b/ui/wm/public/window_types.h deleted file mode 100644 index 8a9f8b9..0000000 --- a/ui/wm/public/window_types.h +++ /dev/null
@@ -1,36 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_PUBLIC_WINDOW_TYPES_H_ -#define UI_WM_PUBLIC_WINDOW_TYPES_H_ - -namespace ui { -namespace wm { - -// This isn't a property because it can't change after the window has been -// initialized. -enum WindowType { - WINDOW_TYPE_UNKNOWN = 0, - - // Regular windows that should be laid out by the client. - WINDOW_TYPE_NORMAL, - - // Miscellaneous windows that should not be laid out by the shell. - WINDOW_TYPE_POPUP, - - // A window intended as a control. Not laid out by the shell. - WINDOW_TYPE_CONTROL, - - // Always on top windows aligned to bottom right of screen. - WINDOW_TYPE_PANEL, - - WINDOW_TYPE_MENU, - - WINDOW_TYPE_TOOLTIP, -}; - -} // namespace wm -} // namespace ui - -#endif // UI_WM_PUBLIC_WINDOW_TYPES_H_
diff --git a/ui/wm/test/DEPS b/ui/wm/test/DEPS deleted file mode 100644 index 412f2e6..0000000 --- a/ui/wm/test/DEPS +++ /dev/null
@@ -1,7 +0,0 @@ -include_rules = [ - "+ui/aura", - "+ui/base/resource/resource_bundle.h", - "+ui/base/ui_base_paths.h", - "+ui/gl", - "+ui/views", -]
diff --git a/ui/wm/test/run_all_unittests.cc b/ui/wm/test/run_all_unittests.cc deleted file mode 100644 index a0ac59d..0000000 --- a/ui/wm/test/run_all_unittests.cc +++ /dev/null
@@ -1,45 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/basictypes.h" -#include "base/bind.h" -#include "base/compiler_specific.h" -#include "base/path_service.h" -#include "base/test/launcher/unit_test_launcher.h" -#include "base/test/test_suite.h" -#include "testing/gtest/include/gtest/gtest.h" -#include "ui/base/resource/resource_bundle.h" -#include "ui/base/ui_base_paths.h" -#include "ui/gl/gl_surface.h" - -class WMTestSuite : public base::TestSuite { - public: - WMTestSuite(int argc, char** argv) : base::TestSuite(argc, argv) {} - - protected: - virtual void Initialize() override { - base::TestSuite::Initialize(); - gfx::GLSurface::InitializeOneOffForTests(); - ui::RegisterPathProvider(); - - base::FilePath ui_test_pak_path; - ASSERT_TRUE(PathService::Get(ui::UI_TEST_PAK, &ui_test_pak_path)); - ui::ResourceBundle::InitSharedInstanceWithPakPath(ui_test_pak_path); - } - - virtual void Shutdown() override { - ui::ResourceBundle::CleanupSharedInstance(); - base::TestSuite::Shutdown(); - } - - private: - DISALLOW_COPY_AND_ASSIGN(WMTestSuite); -}; - -int main(int argc, char** argv) { - WMTestSuite test_suite(argc, argv); - - return base::LaunchUnitTests( - argc, argv, base::Bind(&WMTestSuite::Run, base::Unretained(&test_suite))); -}
diff --git a/ui/wm/test/wm_test_helper.cc b/ui/wm/test/wm_test_helper.cc deleted file mode 100644 index c74ddfe..0000000 --- a/ui/wm/test/wm_test_helper.cc +++ /dev/null
@@ -1,52 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "ui/wm/test/wm_test_helper.h" - -#include "ui/aura/client/default_capture_client.h" -#include "ui/aura/env.h" -#include "ui/aura/test/test_focus_client.h" -#include "ui/aura/window.h" -#include "ui/wm/core/compound_event_filter.h" -#include "ui/wm/core/default_activation_client.h" -#include "ui/wm/core/input_method_event_filter.h" - -namespace wm { - -WMTestHelper::WMTestHelper(const gfx::Size& default_window_size, - ui::ContextFactory* context_factory) { - aura::Env::CreateInstance(true); - aura::Env::GetInstance()->set_context_factory(context_factory); - host_.reset(aura::WindowTreeHost::Create(gfx::Rect(default_window_size))); - host_->InitHost(); - aura::client::SetWindowTreeClient(host_->window(), this); - - focus_client_.reset(new aura::test::TestFocusClient); - aura::client::SetFocusClient(host_->window(), focus_client_.get()); - - root_window_event_filter_.reset(new wm::CompoundEventFilter); - host_->window()->AddPreTargetHandler(root_window_event_filter_.get()); - - input_method_filter_.reset(new wm::InputMethodEventFilter( - host_->GetAcceleratedWidget())); - input_method_filter_->SetInputMethodPropertyInRootWindow(host_->window()); - root_window_event_filter_->AddHandler(input_method_filter_.get()); - - new wm::DefaultActivationClient(host_->window()); - - capture_client_.reset( - new aura::client::DefaultCaptureClient(host_->window())); -} - -WMTestHelper::~WMTestHelper() { - root_window_event_filter_->RemoveHandler(input_method_filter_.get()); -} - -aura::Window* WMTestHelper::GetDefaultParent(aura::Window* context, - aura::Window* window, - const gfx::Rect& bounds) { - return host_->window(); -} - -} // namespace wm
diff --git a/ui/wm/test/wm_test_helper.h b/ui/wm/test/wm_test_helper.h deleted file mode 100644 index 990b478..0000000 --- a/ui/wm/test/wm_test_helper.h +++ /dev/null
@@ -1,65 +0,0 @@ -// Copyright 2013 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_TEST_WM_TEST_HELPER_H_ -#define UI_WM_TEST_WM_TEST_HELPER_H_ - -#include "base/compiler_specific.h" -#include "base/memory/scoped_ptr.h" -#include "ui/aura/client/window_tree_client.h" -#include "ui/aura/window_tree_host.h" - -namespace aura { -class Window; -class WindowTreeHost; -namespace client { -class DefaultCaptureClient; -class FocusClient; -} -} - -namespace gfx { -class Rect; -class Size; -} - -namespace ui { -class ContextFactory; -} - -namespace wm { - -class CompoundEventFilter; -class InputMethodEventFilter; - -// Creates a minimal environment for running the shell. We can't pull in all of -// ash here, but we can create attach several of the same things we'd find in -// the ash parts of the code. -class WMTestHelper : public aura::client::WindowTreeClient { - public: - WMTestHelper(const gfx::Size& default_window_size, - ui::ContextFactory* context_factory); - virtual ~WMTestHelper(); - - aura::WindowTreeHost* host() { return host_.get(); } - - // Overridden from client::WindowTreeClient: - virtual aura::Window* GetDefaultParent(aura::Window* context, - aura::Window* window, - const gfx::Rect& bounds) override; - - private: - scoped_ptr<aura::WindowTreeHost> host_; - - scoped_ptr<wm::CompoundEventFilter> root_window_event_filter_; - scoped_ptr<aura::client::DefaultCaptureClient> capture_client_; - scoped_ptr<wm::InputMethodEventFilter> input_method_filter_; - scoped_ptr<aura::client::FocusClient> focus_client_; - - DISALLOW_COPY_AND_ASSIGN(WMTestHelper); -}; - -} // namespace wm - -#endif // UI_WM_TEST_WM_TEST_HELPER_H_
diff --git a/ui/wm/wm.gyp b/ui/wm/wm.gyp deleted file mode 100644 index 45f346e..0000000 --- a/ui/wm/wm.gyp +++ /dev/null
@@ -1,154 +0,0 @@ -# Copyright 2013 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -{ - 'variables': { - 'chromium_code': 1, - }, - 'targets': [ - { - # GN version: //ui/wm - 'target_name': 'wm', - 'type': '<(component)', - 'dependencies': [ - '../../base/base.gyp:base', - '../../skia/skia.gyp:skia', - '../aura/aura.gyp:aura', - '../compositor/compositor.gyp:compositor', - '../events/events.gyp:events', - '../events/events.gyp:events_base', - '../events/platform/events_platform.gyp:events_platform', - '../gfx/gfx.gyp:gfx_geometry', - '../gfx/gfx.gyp:gfx', - '../resources/ui_resources.gyp:ui_resources', - '../base/ui_base.gyp:ui_base', - ], - 'defines': [ - 'WM_IMPLEMENTATION', - ], - 'sources': [ - # Note: sources list duplicated in GN build. - 'core/accelerator_delegate.h', - 'core/accelerator_filter.cc', - 'core/accelerator_filter.h', - 'core/base_focus_rules.h', - 'core/base_focus_rules.cc', - 'core/base_focus_rules.h', - 'core/capture_controller.cc', - 'core/capture_controller.h', - 'core/compound_event_filter.cc', - 'core/compound_event_filter.h', - 'core/coordinate_conversion.cc', - 'core/coordinate_conversion.h', - 'core/cursor_manager.cc', - 'core/cursor_manager.h', - 'core/default_activation_client.cc', - 'core/default_activation_client.h', - 'core/easy_resize_window_targeter.cc', - 'core/easy_resize_window_targeter.h', - 'core/focus_controller.cc', - 'core/focus_controller.h', - 'core/focus_rules.h', - 'core/image_grid.cc', - 'core/image_grid.h', - 'core/input_method_event_filter.cc', - 'core/input_method_event_filter.h', - 'core/masked_window_targeter.cc', - 'core/masked_window_targeter.h', - 'core/native_cursor_manager.h', - 'core/native_cursor_manager_delegate.h', - 'core/nested_accelerator_dispatcher_linux.cc', - 'core/nested_accelerator_dispatcher_win.cc', - 'core/nested_accelerator_dispatcher.cc', - 'core/nested_accelerator_dispatcher.h', - 'core/nested_accelerator_delegate.h', - 'core/nested_accelerator_controller.cc', - 'core/nested_accelerator_controller.h', - 'core/shadow.cc', - 'core/shadow.h', - 'core/shadow_controller.cc', - 'core/shadow_controller.h', - 'core/shadow_types.cc', - 'core/shadow_types.h', - 'core/transient_window_controller.cc', - 'core/transient_window_controller.h', - 'core/transient_window_manager.cc', - 'core/transient_window_manager.h', - 'core/transient_window_observer.h', - 'core/transient_window_stacking_client.cc', - 'core/transient_window_stacking_client.h', - 'core/user_activity_detector.cc', - 'core/user_activity_detector.h', - 'core/user_activity_observer.h', - 'core/visibility_controller.cc', - 'core/visibility_controller.h', - 'core/window_animations.cc', - 'core/window_animations.h', - 'core/window_modality_controller.cc', - 'core/window_modality_controller.h', - 'core/window_util.cc', - 'core/window_util.h', - 'core/wm_core_switches.cc', - 'core/wm_core_switches.h', - 'core/wm_state.cc', - 'core/wm_state.h', - 'wm_export.h', - ], - }, - { - # GN version: //ui/wm:test_support - 'target_name': 'wm_test_support', - 'type': 'static_library', - 'dependencies': [ - '../../skia/skia.gyp:skia', - '../aura/aura.gyp:aura', - '../events/events.gyp:events', - '../events/events.gyp:events_base', - ], - 'sources': [ - 'test/wm_test_helper.cc', - 'test/wm_test_helper.h', - ], - }, - { - # GN version: //ui/wm:wm_unittests - 'target_name': 'wm_unittests', - 'type': 'executable', - 'dependencies': [ - '../../base/base.gyp:base', - '../../base/base.gyp:test_support_base', - '../../skia/skia.gyp:skia', - '../../testing/gtest.gyp:gtest', - '../aura/aura.gyp:aura', - '../aura/aura.gyp:aura_test_support', - '../base/ui_base.gyp:ui_base', - '../compositor/compositor.gyp:compositor', - '../events/events.gyp:events', - '../events/events.gyp:events_base', - '../events/platform/events_platform.gyp:events_platform', - '../gfx/gfx.gyp:gfx', - '../gfx/gfx.gyp:gfx_geometry', - 'wm', - 'wm_test_support', - ], - 'sources': [ - 'test/run_all_unittests.cc', - 'core/compound_event_filter_unittest.cc', - 'core/cursor_manager_unittest.cc', - 'core/focus_controller_unittest.cc', - 'core/input_method_event_filter_unittest.cc', - 'core/image_grid_unittest.cc', - 'core/nested_accelerator_controller_unittest.cc', - 'core/shadow_controller_unittest.cc', - 'core/shadow_unittest.cc', - 'core/transient_window_manager_unittest.cc', - 'core/transient_window_stacking_client_unittest.cc', - 'core/user_activity_detector_unittest.cc', - 'core/visibility_controller_unittest.cc', - 'core/window_animations_unittest.cc', - 'core/window_util_unittest.cc', - ], - }, - ], -}
diff --git a/ui/wm/wm_export.h b/ui/wm/wm_export.h deleted file mode 100644 index 461d693..0000000 --- a/ui/wm/wm_export.h +++ /dev/null
@@ -1,32 +0,0 @@ -// Copyright 2014 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef UI_WM_WM_EXPORT_H_ -#define UI_WM_WM_EXPORT_H_ - -// Defines WM_EXPORT so that functionality implemented by the WM module -// can be exported to consumers. - -#if defined(COMPONENT_BUILD) -#if defined(WIN32) - -#if defined(WM_IMPLEMENTATION) -#define WM_EXPORT __declspec(dllexport) -#else -#define WM_EXPORT __declspec(dllimport) -#endif // defined(WM_IMPLEMENTATION) - -#else // defined(WIN32) -#if defined(WM_IMPLEMENTATION) -#define WM_EXPORT __attribute__((visibility("default"))) -#else -#define WM_EXPORT -#endif -#endif - -#else // defined(COMPONENT_BUILD) -#define WM_EXPORT -#endif - -#endif // UI_WM_WM_EXPORT_H_