code stringlengths 1 1.05M | repo_name stringlengths 6 83 | path stringlengths 3 242 | language stringclasses 222
values | license stringclasses 20
values | size int64 1 1.05M |
|---|---|---|---|---|---|
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/shell_dialogs/shell_dialog_linux.h"
#include "base/environment.h"
#include "base/no_destructor.h"
#include "base/notreached.h"
#include "build/chromeos_buildflags.h"
#include "ui/linux/linux_ui.h"
#include "ui/shell_dialogs/select_file_dialog_linux.h"
#include "ui/shell_dialogs/select_file_dialog_linux_kde.h"
#include "ui/shell_dialogs/select_file_policy.h"
#if defined(USE_DBUS)
#include "ui/shell_dialogs/select_file_dialog_linux_portal.h"
#endif
namespace shell_dialog_linux {
void Initialize() {
#if defined(USE_DBUS)
ui::SelectFileDialogLinuxPortal::StartAvailabilityTestInBackground();
#endif
}
void Finalize() {
#if defined(USE_DBUS)
ui::SelectFileDialogLinuxPortal::DestroyPortalConnection();
#endif
}
} // namespace shell_dialog_linux
namespace ui {
namespace {
enum FileDialogChoice {
kUnknown,
kToolkit,
kKde,
#if defined(USE_DBUS)
kPortal,
#endif
};
FileDialogChoice dialog_choice_ = kUnknown;
std::string& KDialogVersion() {
static base::NoDestructor<std::string> version;
return *version;
}
FileDialogChoice GetFileDialogChoice() {
#if defined(USE_DBUS)
// Check to see if the portal is available.
if (SelectFileDialogLinuxPortal::IsPortalAvailable())
return kPortal;
// Make sure to kill the portal connection.
SelectFileDialogLinuxPortal::DestroyPortalConnection();
#endif
// Check to see if KDE is the desktop environment.
std::unique_ptr<base::Environment> env(base::Environment::Create());
base::nix::DesktopEnvironment desktop =
base::nix::GetDesktopEnvironment(env.get());
if (desktop == base::nix::DESKTOP_ENVIRONMENT_KDE3 ||
desktop == base::nix::DESKTOP_ENVIRONMENT_KDE4 ||
desktop == base::nix::DESKTOP_ENVIRONMENT_KDE5 ||
desktop == base::nix::DESKTOP_ENVIRONMENT_KDE6) {
// Check to see if the user dislikes the KDE file dialog.
if (!env->HasVar("NO_CHROME_KDE_FILE_DIALOG")) {
// Check to see if the KDE dialog works.
if (SelectFileDialogLinux::CheckKDEDialogWorksOnUIThread(
KDialogVersion())) {
return kKde;
}
}
}
return kToolkit;
}
} // namespace
SelectFileDialog* CreateSelectFileDialog(
SelectFileDialog::Listener* listener,
std::unique_ptr<SelectFilePolicy> policy) {
if (dialog_choice_ == kUnknown)
dialog_choice_ = GetFileDialogChoice();
const LinuxUi* linux_ui = LinuxUi::instance();
switch (dialog_choice_) {
case kToolkit:
if (!linux_ui)
break;
return linux_ui->CreateSelectFileDialog(listener, std::move(policy));
#if defined(USE_DBUS)
case kPortal:
return new SelectFileDialogLinuxPortal(listener, std::move(policy));
#endif
case kKde: {
std::unique_ptr<base::Environment> env(base::Environment::Create());
base::nix::DesktopEnvironment desktop =
base::nix::GetDesktopEnvironment(env.get());
return NewSelectFileDialogLinuxKde(listener, std::move(policy), desktop,
KDialogVersion());
}
case kUnknown:
NOTREACHED();
}
return nullptr;
}
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/shell_dialogs/shell_dialog_linux.cc | C++ | unknown | 3,233 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_SHELL_DIALOGS_SHELL_DIALOG_LINUX_H_
#define UI_SHELL_DIALOGS_SHELL_DIALOG_LINUX_H_
#include "ui/shell_dialogs/shell_dialogs_export.h"
namespace shell_dialog_linux {
// TODO(thomasanderson): Remove Initialize() and Finalize().
// Should be called before the first call to CreateSelectFileDialog.
SHELL_DIALOGS_EXPORT void Initialize();
SHELL_DIALOGS_EXPORT void Finalize();
} // namespace shell_dialog_linux
#endif // UI_SHELL_DIALOGS_SHELL_DIALOG_LINUX_H_
| Zhao-PengFei35/chromium_src_4 | ui/shell_dialogs/shell_dialog_linux.h | C++ | unknown | 620 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/notreached.h"
#include "ui/shell_dialogs/select_file_dialog.h"
#include "ui/shell_dialogs/select_file_policy.h"
namespace ui {
SelectFileDialog* CreateSelectFileDialog(
SelectFileDialog::Listener* listener,
std::unique_ptr<SelectFilePolicy> policy) {
NOTIMPLEMENTED();
return nullptr;
}
} // namespace ui | Zhao-PengFei35/chromium_src_4 | ui/shell_dialogs/shell_dialog_stub.cc | C++ | unknown | 479 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_SHELL_DIALOGS_SHELL_DIALOGS_EXPORT_H_
#define UI_SHELL_DIALOGS_SHELL_DIALOGS_EXPORT_H_
// Defines SHELL_DIALOGS_EXPORT so that functionality implemented by the Shell
// Dialogs module can be exported to consumers.
#if defined(COMPONENT_BUILD)
#if defined(WIN32)
#if defined(SHELL_DIALOGS_IMPLEMENTATION)
#define SHELL_DIALOGS_EXPORT __declspec(dllexport)
#else
#define SHELL_DIALOGS_EXPORT __declspec(dllimport)
#endif // defined(SHELL_DIALOGS_IMPLEMENTATION)
#else // defined(WIN32)
#if defined(SHELL_DIALOGS_IMPLEMENTATION)
#define SHELL_DIALOGS_EXPORT __attribute__((visibility("default")))
#else
#define SHELL_DIALOGS_EXPORT
#endif
#endif
#else // defined(COMPONENT_BUILD)
#define SHELL_DIALOGS_EXPORT
#endif
#endif // UI_SHELL_DIALOGS_SHELL_DIALOGS_EXPORT_H_
| Zhao-PengFei35/chromium_src_4 | ui/shell_dialogs/shell_dialogs_export.h | C | unknown | 930 |
include_rules = [
"+cc",
"+components/viz/common/frame_sinks",
"-components/viz/service/surfaces",
"+skia/ext",
"+third_party/skia",
"+ui/aura",
"+ui/android/view_android.h",
"+ui/android/window_android.h",
"+ui/android/window_android_compositor.h",
"+ui/base/layout.h",
"+ui/compositor",
"+ui/display",
"+ui/gfx",
"+ui/gl",
"+ui/wm",
]
| Zhao-PengFei35/chromium_src_4 | ui/snapshot/DEPS | Python | unknown | 367 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/snapshot/screenshot_grabber.h"
#include <stddef.h>
#include <climits>
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "base/task/current_thread.h"
#include "base/task/single_thread_task_runner.h"
#include "base/task/task_runner.h"
#include "base/time/time.h"
#include "ui/snapshot/snapshot.h"
#if defined(USE_AURA)
#include "ui/aura/client/cursor_client.h"
#include "ui/aura/window.h"
#endif
namespace ui {
namespace {
// The minimum interval between two screenshot commands. It has to be
// more than 1000 to prevent the conflict of filenames.
const int kScreenshotMinimumIntervalInMS = 1000;
} // namespace
#if defined(USE_AURA)
class ScreenshotGrabber::ScopedCursorHider {
public:
// The nullptr might be returned when GetCursorClient is nullptr.
static std::unique_ptr<ScopedCursorHider> Create(aura::Window* window) {
DCHECK(window->IsRootWindow());
aura::client::CursorClient* cursor_client =
aura::client::GetCursorClient(window);
if (!cursor_client)
return nullptr;
cursor_client->HideCursor();
return std::unique_ptr<ScopedCursorHider>(
base::WrapUnique(new ScopedCursorHider(window)));
}
ScopedCursorHider(const ScopedCursorHider&) = delete;
ScopedCursorHider& operator=(const ScopedCursorHider&) = delete;
~ScopedCursorHider() {
aura::client::CursorClient* cursor_client =
aura::client::GetCursorClient(window_);
cursor_client->ShowCursor();
}
private:
explicit ScopedCursorHider(aura::Window* window) : window_(window) {}
raw_ptr<aura::Window> window_;
};
#endif
ScreenshotGrabber::ScreenshotGrabber() {}
ScreenshotGrabber::~ScreenshotGrabber() {
}
void ScreenshotGrabber::TakeScreenshot(gfx::NativeWindow window,
const gfx::Rect& rect,
ScreenshotCallback callback) {
DCHECK(base::CurrentUIThread::IsSet());
last_screenshot_timestamp_ = base::TimeTicks::Now();
bool is_partial = true;
// Window identifier is used to log a message on failure to capture a full
// screen (i.e. non partial) screenshot. The only time is_partial can be
// false, we will also have an identification string for the window.
std::string window_identifier;
#if defined(USE_AURA)
aura::Window* aura_window = static_cast<aura::Window*>(window);
is_partial = rect.size() != aura_window->bounds().size();
window_identifier = aura_window->GetBoundsInScreen().ToString();
cursor_hider_ = ScopedCursorHider::Create(aura_window->GetRootWindow());
#endif
ui::GrabWindowSnapshotAsyncPNG(
window, rect,
base::BindOnce(&ScreenshotGrabber::GrabWindowSnapshotAsyncCallback,
factory_.GetWeakPtr(), window_identifier, is_partial,
std::move(callback)));
}
bool ScreenshotGrabber::CanTakeScreenshot() {
return last_screenshot_timestamp_.is_null() ||
base::TimeTicks::Now() - last_screenshot_timestamp_ >
base::Milliseconds(kScreenshotMinimumIntervalInMS);
}
void ScreenshotGrabber::GrabWindowSnapshotAsyncCallback(
const std::string& window_identifier,
bool is_partial,
ScreenshotCallback callback,
scoped_refptr<base::RefCountedMemory> png_data) {
DCHECK(base::CurrentUIThread::IsSet());
#if defined(USE_AURA)
cursor_hider_.reset();
#endif
if (!png_data.get()) {
if (is_partial) {
LOG(ERROR) << "Failed to grab the window screenshot";
std::move(callback).Run(ScreenshotResult::GRABWINDOW_PARTIAL_FAILED,
nullptr);
} else {
LOG(ERROR) << "Failed to grab the window screenshot for "
<< window_identifier;
std::move(callback).Run(ScreenshotResult::GRABWINDOW_FULL_FAILED,
nullptr);
}
return;
}
std::move(callback).Run(ScreenshotResult::SUCCESS, std::move(png_data));
}
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/snapshot/screenshot_grabber.cc | C++ | unknown | 4,237 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_SNAPSHOT_SCREENSHOT_GRABBER_H_
#define UI_SNAPSHOT_SCREENSHOT_GRABBER_H_
#include <memory>
#include <string>
#include "base/functional/callback.h"
#include "base/memory/ref_counted_memory.h"
#include "base/memory/weak_ptr.h"
#include "base/time/time.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/snapshot/snapshot_export.h"
namespace ui {
// Result of the entire screenshotting attempt. This enum is fat for various
// file operations which could happen in the chrome layer.
enum class ScreenshotResult {
SUCCESS,
GRABWINDOW_PARTIAL_FAILED,
GRABWINDOW_FULL_FAILED,
CREATE_DIR_FAILED,
GET_DIR_FAILED,
CHECK_DIR_FAILED,
CREATE_FILE_FAILED,
WRITE_FILE_FAILED,
// Disabled by an enterprise policy or special modes.
DISABLED,
// Disabled by Data Leak Prevention feature.
DISABLED_BY_DLP
};
class SNAPSHOT_EXPORT ScreenshotGrabber {
public:
ScreenshotGrabber();
ScreenshotGrabber(const ScreenshotGrabber&) = delete;
ScreenshotGrabber& operator=(const ScreenshotGrabber&) = delete;
~ScreenshotGrabber();
// Callback for the new system, which ignores the observer crud.
using ScreenshotCallback =
base::OnceCallback<void(ui::ScreenshotResult screenshot_result,
scoped_refptr<base::RefCountedMemory> png_data)>;
// Takes a screenshot of |rect| in |window| in that window's coordinate space
// and return it to |callback|.
void TakeScreenshot(gfx::NativeWindow window,
const gfx::Rect& rect,
ScreenshotCallback callback);
bool CanTakeScreenshot();
private:
#if defined(USE_AURA)
class ScopedCursorHider;
#endif
void GrabWindowSnapshotAsyncCallback(
const std::string& window_identifier,
bool is_partial,
ScreenshotCallback callback,
scoped_refptr<base::RefCountedMemory> png_data);
// The timestamp when the screenshot task was issued last time.
base::TimeTicks last_screenshot_timestamp_;
#if defined(USE_AURA)
// The object to hide cursor when taking screenshot.
std::unique_ptr<ScopedCursorHider> cursor_hider_;
#endif
base::WeakPtrFactory<ScreenshotGrabber> factory_{this};
};
} // namespace ui
#endif // UI_SNAPSHOT_SCREENSHOT_GRABBER_H_
| Zhao-PengFei35/chromium_src_4 | ui/snapshot/screenshot_grabber.h | C++ | unknown | 2,415 |
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/snapshot/snapshot.h"
#include <utility>
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/task/thread_pool.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/codec/png_codec.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/gfx/image/image_skia_rep.h"
#include "ui/gfx/image/image_util.h"
namespace ui {
namespace {
scoped_refptr<base::RefCountedMemory> EncodeImageAsPNG(
const gfx::Image& image) {
if (image.IsEmpty())
return nullptr;
DCHECK(!image.AsImageSkia().GetRepresentation(1.0f).is_null());
return image.As1xPNGBytes();
}
scoped_refptr<base::RefCountedMemory> EncodeImageAsJPEG(
const gfx::Image& image) {
std::vector<uint8_t> result;
DCHECK(!image.AsImageSkia().GetRepresentation(1.0f).is_null());
gfx::JPEG1xEncodedDataFromImage(image, 100, &result);
return base::RefCountedBytes::TakeVector(&result);
}
void EncodeImageAndScheduleCallback(
scoped_refptr<base::RefCountedMemory> (*encode_func)(const gfx::Image&),
base::OnceCallback<void(scoped_refptr<base::RefCountedMemory> data)>
callback,
gfx::Image image) {
base::ThreadPool::PostTaskAndReplyWithResult(
FROM_HERE, {base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
base::BindOnce(encode_func, std::move(image)), std::move(callback));
}
} // namespace
void GrabWindowSnapshotAsyncPNG(gfx::NativeWindow window,
const gfx::Rect& source_rect,
GrabWindowSnapshotAsyncPNGCallback callback) {
GrabWindowSnapshotAsync(
window, source_rect,
base::BindOnce(&EncodeImageAndScheduleCallback, &EncodeImageAsPNG,
std::move(callback)));
}
void GrabWindowSnapshotAsyncJPEG(gfx::NativeWindow window,
const gfx::Rect& source_rect,
GrabWindowSnapshotAsyncJPEGCallback callback) {
GrabWindowSnapshotAsync(
window, source_rect,
base::BindOnce(&EncodeImageAndScheduleCallback, &EncodeImageAsJPEG,
std::move(callback)));
}
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/snapshot/snapshot.cc | C++ | unknown | 2,309 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_SNAPSHOT_SNAPSHOT_H_
#define UI_SNAPSHOT_SNAPSHOT_H_
#include "base/functional/callback_forward.h"
#include "base/memory/ref_counted.h"
#include "base/memory/ref_counted_memory.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/snapshot/snapshot_export.h"
namespace gfx {
class Rect;
class Image;
class Size;
}
namespace ui {
// Grabs a snapshot of the window/view. No security checks are done. This is
// intended to be used for debugging purposes where no BrowserProcess instance
// is available (ie. tests). This function is synchronous, so it should NOT be
// used in a result of user action. Support for async vs synchronous
// GrabWindowSnapshot differs by platform. To be most general, use the
// synchronous function first and if it returns false call the async one.
SNAPSHOT_EXPORT bool GrabWindowSnapshot(gfx::NativeWindow window,
const gfx::Rect& snapshot_bounds,
gfx::Image* image);
SNAPSHOT_EXPORT bool GrabViewSnapshot(gfx::NativeView view,
const gfx::Rect& snapshot_bounds,
gfx::Image* image);
// These functions take a snapshot of |source_rect|, specified in layer space
// coordinates (DIP for desktop, physical pixels for Android), and scale the
// snapshot to |target_size| (in physical pixels), asynchronously.
using GrabWindowSnapshotAsyncCallback =
base::OnceCallback<void(gfx::Image snapshot)>;
SNAPSHOT_EXPORT void GrabWindowSnapshotAndScaleAsync(
gfx::NativeWindow window,
const gfx::Rect& source_rect,
const gfx::Size& target_size,
GrabWindowSnapshotAsyncCallback callback);
SNAPSHOT_EXPORT void GrabWindowSnapshotAsync(
gfx::NativeWindow window,
const gfx::Rect& source_rect,
GrabWindowSnapshotAsyncCallback callback);
SNAPSHOT_EXPORT void GrabViewSnapshotAsync(
gfx::NativeView view,
const gfx::Rect& source_rect,
GrabWindowSnapshotAsyncCallback callback);
using GrabWindowSnapshotAsyncPNGCallback =
base::OnceCallback<void(scoped_refptr<base::RefCountedMemory> data)>;
SNAPSHOT_EXPORT void GrabWindowSnapshotAsyncPNG(
gfx::NativeWindow window,
const gfx::Rect& source_rect,
GrabWindowSnapshotAsyncPNGCallback callback);
using GrabWindowSnapshotAsyncJPEGCallback =
base::OnceCallback<void(scoped_refptr<base::RefCountedMemory> data)>;
SNAPSHOT_EXPORT void GrabWindowSnapshotAsyncJPEG(
gfx::NativeWindow window,
const gfx::Rect& source_rect,
GrabWindowSnapshotAsyncJPEGCallback callback);
} // namespace ui
#endif // UI_SNAPSHOT_SNAPSHOT_H_
| Zhao-PengFei35/chromium_src_4 | ui/snapshot/snapshot.h | C++ | unknown | 2,778 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/snapshot/snapshot.h"
#include <memory>
#include <utility>
#include "base/functional/bind.h"
#include "components/viz/common/frame_sinks/copy_output_request.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/android/view_android.h"
#include "ui/android/window_android.h"
#include "ui/android/window_android_compositor.h"
#include "ui/base/layout.h"
#include "ui/gfx/geometry/point_conversions.h"
#include "ui/gfx/geometry/rect_conversions.h"
#include "ui/snapshot/snapshot_async.h"
namespace ui {
// Sync versions are not supported in Android. Callers should fall back
// to the async version.
bool GrabViewSnapshot(gfx::NativeView view,
const gfx::Rect& snapshot_bounds,
gfx::Image* image) {
return GrabWindowSnapshot(view->GetWindowAndroid(), snapshot_bounds, image);
}
bool GrabWindowSnapshot(gfx::NativeWindow window,
const gfx::Rect& snapshot_bounds,
gfx::Image* image) {
return false;
}
static std::unique_ptr<viz::CopyOutputRequest> CreateCopyRequest(
gfx::NativeView view,
const gfx::Rect& source_rect,
viz::CopyOutputRequest::CopyOutputRequestCallback callback) {
std::unique_ptr<viz::CopyOutputRequest> request =
std::make_unique<viz::CopyOutputRequest>(
viz::CopyOutputRequest::ResultFormat::RGBA,
viz::CopyOutputRequest::ResultDestination::kSystemMemory,
std::move(callback));
float scale = ui::GetScaleFactorForNativeView(view);
request->set_area(gfx::ScaleToEnclosingRect(source_rect, scale));
return request;
}
static void MakeAsyncCopyRequest(
gfx::NativeWindow window,
const gfx::Rect& source_rect,
std::unique_ptr<viz::CopyOutputRequest> copy_request) {
if (!window->GetCompositor())
return;
window->GetCompositor()->RequestCopyOfOutputOnRootLayer(
std::move(copy_request));
}
void GrabWindowSnapshotAndScaleAsync(gfx::NativeWindow window,
const gfx::Rect& source_rect,
const gfx::Size& target_size,
GrabWindowSnapshotAsyncCallback callback) {
MakeAsyncCopyRequest(
window, source_rect,
CreateCopyRequest(window, source_rect,
base::BindOnce(&SnapshotAsync::ScaleCopyOutputResult,
std::move(callback), target_size)));
}
void GrabWindowSnapshotAsync(gfx::NativeWindow window,
const gfx::Rect& source_rect,
GrabWindowSnapshotAsyncCallback callback) {
MakeAsyncCopyRequest(
window, source_rect,
CreateCopyRequest(
window, source_rect,
base::BindOnce(&SnapshotAsync::RunCallbackWithCopyOutputResult,
std::move(callback))));
}
void GrabViewSnapshotAsync(gfx::NativeView view,
const gfx::Rect& source_rect,
GrabWindowSnapshotAsyncCallback callback) {
std::unique_ptr<viz::CopyOutputRequest> copy_request =
view->MaybeRequestCopyOfView(CreateCopyRequest(
view, source_rect,
base::BindOnce(&SnapshotAsync::RunCallbackWithCopyOutputResult,
std::move(callback))));
if (!copy_request)
return;
MakeAsyncCopyRequest(view->GetWindowAndroid(), source_rect,
std::move(copy_request));
}
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/snapshot/snapshot_android.cc | C++ | unknown | 3,613 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/snapshot/snapshot_async.h"
#include "base/functional/bind.h"
#include "base/location.h"
#include "base/numerics/safe_conversions.h"
#include "base/task/thread_pool.h"
#include "skia/ext/image_operations.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/gfx/image/image.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/gfx/skbitmap_operations.h"
namespace ui {
namespace {
void OnFrameScalingFinished(GrabWindowSnapshotAsyncCallback callback,
const SkBitmap& scaled_bitmap) {
std::move(callback).Run(gfx::Image::CreateFrom1xBitmap(scaled_bitmap));
}
SkBitmap ScaleBitmap(const SkBitmap& input_bitmap,
const gfx::Size& target_size) {
return skia::ImageOperations::Resize(input_bitmap,
skia::ImageOperations::RESIZE_GOOD,
target_size.width(),
target_size.height(),
static_cast<SkBitmap::Allocator*>(NULL));
}
} // namespace
void SnapshotAsync::ScaleCopyOutputResult(
GrabWindowSnapshotAsyncCallback callback,
const gfx::Size& target_size,
std::unique_ptr<viz::CopyOutputResult> result) {
auto scoped_bitmap = result->ScopedAccessSkBitmap();
auto bitmap = scoped_bitmap.GetOutScopedBitmap();
if (!bitmap.readyToDraw()) {
std::move(callback).Run(gfx::Image());
return;
}
// TODO(sergeyu): Potentially images can be scaled on GPU before reading it
// from GPU. Image scaling is implemented in content::GlHelper, but it's can't
// be used here because it's not in content/public. Move the scaling code
// somewhere so that it can be reused here.
base::ThreadPool::PostTaskAndReplyWithResult(
FROM_HERE, {base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN},
base::BindOnce(ScaleBitmap, bitmap, target_size),
base::BindOnce(&OnFrameScalingFinished, std::move(callback)));
}
void SnapshotAsync::RunCallbackWithCopyOutputResult(
GrabWindowSnapshotAsyncCallback callback,
std::unique_ptr<viz::CopyOutputResult> result) {
auto scoped_bitmap = result->ScopedAccessSkBitmap();
auto bitmap = scoped_bitmap.GetOutScopedBitmap();
if (!bitmap.readyToDraw()) {
std::move(callback).Run(gfx::Image());
return;
}
std::move(callback).Run(gfx::Image::CreateFrom1xBitmap(bitmap));
}
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/snapshot/snapshot_async.cc | C++ | unknown | 2,555 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_SNAPSHOT_SNAPSHOT_ASYNC_H_
#define UI_SNAPSHOT_SNAPSHOT_ASYNC_H_
#include <memory>
#include "components/viz/common/frame_sinks/copy_output_result.h"
#include "ui/snapshot/snapshot.h"
namespace gfx {
class Size;
}
namespace ui {
// Helper methods for async snapshots to convert a viz::CopyOutputResult into a
// ui::GrabWindowSnapshot callback.
class SnapshotAsync {
public:
SnapshotAsync() = delete;
SnapshotAsync(const SnapshotAsync&) = delete;
SnapshotAsync& operator=(const SnapshotAsync&) = delete;
static void ScaleCopyOutputResult(
GrabWindowSnapshotAsyncCallback callback,
const gfx::Size& target_size,
std::unique_ptr<viz::CopyOutputResult> result);
static void RunCallbackWithCopyOutputResult(
GrabWindowSnapshotAsyncCallback callback,
std::unique_ptr<viz::CopyOutputResult> result);
};
} // namespace ui
#endif // UI_SNAPSHOT_SNAPSHOT_ASYNC_H_
| Zhao-PengFei35/chromium_src_4 | ui/snapshot/snapshot_async.h | C++ | unknown | 1,061 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/snapshot/snapshot_aura.h"
#include <memory>
#include <utility>
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/task/sequenced_task_runner.h"
#include "build/build_config.h"
#include "components/viz/common/frame_sinks/copy_output_request.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "ui/aura/window.h"
#include "ui/aura/window_tracker.h"
#include "ui/compositor/compositor.h"
#include "ui/compositor/layer.h"
#include "ui/snapshot/snapshot_async.h"
namespace ui {
bool GrabWindowSnapshotAura(aura::Window* window,
const gfx::Rect& snapshot_bounds,
gfx::Image* image) {
// Not supported in Aura. Callers should fall back to the async version.
return false;
}
static void MakeAsyncCopyRequest(
Layer* layer,
const gfx::Rect& source_rect,
viz::CopyOutputRequest::CopyOutputRequestCallback callback) {
std::unique_ptr<viz::CopyOutputRequest> request =
std::make_unique<viz::CopyOutputRequest>(
viz::CopyOutputRequest::ResultFormat::RGBA,
viz::CopyOutputRequest::ResultDestination::kSystemMemory,
std::move(callback));
request->set_area(source_rect);
request->set_result_task_runner(
base::SequencedTaskRunner::GetCurrentDefault());
layer->RequestCopyOfOutput(std::move(request));
}
static void FinishedAsyncCopyRequest(
std::unique_ptr<aura::WindowTracker> tracker,
const gfx::Rect& source_rect,
viz::CopyOutputRequest::CopyOutputRequestCallback callback,
int retry_count,
std::unique_ptr<viz::CopyOutputResult> result) {
static const int kMaxRetries = 5;
// Retry the copy request if the previous one failed for some reason.
if (!tracker->windows().empty() && (retry_count < kMaxRetries) &&
result->IsEmpty()) {
// Look up window before calling MakeAsyncRequest. Otherwise, due
// to undefined (favorably right to left) argument evaluation
// order, the tracker might have been passed and set to NULL
// before the window is looked up which results in a NULL pointer
// dereference.
aura::Window* window = tracker->windows()[0];
MakeAsyncCopyRequest(
window->layer(), source_rect,
base::BindOnce(&FinishedAsyncCopyRequest, std::move(tracker),
source_rect, std::move(callback), retry_count + 1));
return;
}
std::move(callback).Run(std::move(result));
}
static void MakeInitialAsyncCopyRequest(
aura::Window* window,
const gfx::Rect& source_rect,
viz::CopyOutputRequest::CopyOutputRequestCallback callback) {
auto tracker = std::make_unique<aura::WindowTracker>();
tracker->Add(window);
MakeAsyncCopyRequest(
window->layer(), source_rect,
base::BindOnce(&FinishedAsyncCopyRequest, std::move(tracker), source_rect,
std::move(callback), 0));
}
void GrabWindowSnapshotAndScaleAsyncAura(
aura::Window* window,
const gfx::Rect& source_rect,
const gfx::Size& target_size,
GrabWindowSnapshotAsyncCallback callback) {
MakeInitialAsyncCopyRequest(
window, source_rect,
base::BindOnce(&SnapshotAsync::ScaleCopyOutputResult, std::move(callback),
target_size));
}
void GrabWindowSnapshotAsyncAura(aura::Window* window,
const gfx::Rect& source_rect,
GrabWindowSnapshotAsyncCallback callback) {
MakeInitialAsyncCopyRequest(
window, source_rect,
base::BindOnce(&SnapshotAsync::RunCallbackWithCopyOutputResult,
std::move(callback)));
}
#if !BUILDFLAG(IS_WIN)
bool GrabWindowSnapshot(gfx::NativeWindow window,
const gfx::Rect& snapshot_bounds,
gfx::Image* image) {
// Not supported in Aura. Callers should fall back to the async version.
return false;
}
bool GrabViewSnapshot(gfx::NativeView view,
const gfx::Rect& snapshot_bounds,
gfx::Image* image) {
return GrabWindowSnapshot(view, snapshot_bounds, image);
}
void GrabWindowSnapshotAndScaleAsync(gfx::NativeWindow window,
const gfx::Rect& source_rect,
const gfx::Size& target_size,
GrabWindowSnapshotAsyncCallback callback) {
GrabWindowSnapshotAndScaleAsyncAura(window, source_rect, target_size,
std::move(callback));
}
void GrabWindowSnapshotAsync(gfx::NativeWindow window,
const gfx::Rect& source_rect,
GrabWindowSnapshotAsyncCallback callback) {
GrabWindowSnapshotAsyncAura(window, source_rect, std::move(callback));
}
void GrabViewSnapshotAsync(gfx::NativeView view,
const gfx::Rect& source_rect,
GrabWindowSnapshotAsyncCallback callback) {
GrabWindowSnapshotAsyncAura(view, source_rect, std::move(callback));
}
void GrabLayerSnapshotAsync(ui::Layer* layer,
const gfx::Rect& source_rect,
GrabWindowSnapshotAsyncCallback callback) {
MakeAsyncCopyRequest(
layer, source_rect,
base::BindOnce(&SnapshotAsync::RunCallbackWithCopyOutputResult,
std::move(callback)));
}
#endif
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/snapshot/snapshot_aura.cc | C++ | unknown | 5,546 |
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_SNAPSHOT_SNAPSHOT_AURA_H_
#define UI_SNAPSHOT_SNAPSHOT_AURA_H_
#include "ui/snapshot/snapshot.h"
namespace ui {
class Layer;
// These functions are identical to those in snapshot.h, except they're
// guaranteed to read the frame using an Aura CopyOutputRequest and not the
// native windowing system. source_rect and target_size are in DIP.
SNAPSHOT_EXPORT void GrabWindowSnapshotAndScaleAsyncAura(
aura::Window* window,
const gfx::Rect& source_rect,
const gfx::Size& target_size,
GrabWindowSnapshotAsyncCallback callback);
SNAPSHOT_EXPORT void GrabWindowSnapshotAsyncAura(
aura::Window* window,
const gfx::Rect& source_rect,
GrabWindowSnapshotAsyncCallback callback);
// Grabs a snapshot of a |layer| and all its descendants.
// |source_rect| is the bounds of the snapshot content relative to |layer|.
SNAPSHOT_EXPORT void GrabLayerSnapshotAsync(
Layer* layer,
const gfx::Rect& source_rect,
GrabWindowSnapshotAsyncCallback callback);
} // namespace ui
#endif // UI_SNAPSHOT_SNAPSHOT_AURA_H_
| Zhao-PengFei35/chromium_src_4 | ui/snapshot/snapshot_aura.h | C++ | unknown | 1,198 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/snapshot/snapshot.h"
#include <stddef.h>
#include <stdint.h>
#include "base/functional/bind.h"
#include "base/run_loop.h"
#include "base/test/task_environment.h"
#include "base/test/test_simple_task_runner.h"
#include "base/test/test_timeouts.h"
#include "base/win/windows_version.h"
#include "build/build_config.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkPixelRef.h"
#include "ui/aura/test/aura_test_helper.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_event_dispatcher.h"
#include "ui/compositor/compositor.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/paint_recorder.h"
#include "ui/compositor/test/draw_waiter_for_test.h"
#include "ui/compositor/test/test_context_factories.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size_conversions.h"
#include "ui/gfx/geometry/transform.h"
#include "ui/gfx/image/image.h"
#include "ui/gl/gl_implementation.h"
namespace ui {
namespace {
SkColor GetExpectedColorForPoint(int x, int y) {
return SkColorSetRGB(std::min(x, 255), std::min(y, 255), 0);
}
// Paint simple rectangle on the specified aura window.
class TestPaintingWindowDelegate : public aura::test::TestWindowDelegate {
public:
explicit TestPaintingWindowDelegate(const gfx::Size& window_size)
: window_size_(window_size) {
}
TestPaintingWindowDelegate(const TestPaintingWindowDelegate&) = delete;
TestPaintingWindowDelegate& operator=(const TestPaintingWindowDelegate&) =
delete;
~TestPaintingWindowDelegate() override {}
void OnPaint(const ui::PaintContext& context) override {
ui::PaintRecorder recorder(context, window_size_);
for (int y = 0; y < window_size_.height(); ++y) {
for (int x = 0; x < window_size_.width(); ++x) {
recorder.canvas()->FillRect(gfx::Rect(x, y, 1, 1),
GetExpectedColorForPoint(x, y));
}
}
}
private:
gfx::Size window_size_;
};
size_t GetFailedPixelsCountWithScaleFactor(const gfx::Image& image,
int scale_factor) {
const SkBitmap* bitmap = image.ToSkBitmap();
uint32_t* bitmap_data =
reinterpret_cast<uint32_t*>(bitmap->pixelRef()->pixels());
size_t result = 0;
for (int y = 0; y < bitmap->height(); y += scale_factor) {
for (int x = 0; x < bitmap->width(); x += scale_factor) {
if (static_cast<SkColor>(bitmap_data[x + y * bitmap->width()]) !=
GetExpectedColorForPoint(x / scale_factor, y / scale_factor)) {
++result;
}
}
}
return result;
}
size_t GetFailedPixelsCount(const gfx::Image& image) {
return GetFailedPixelsCountWithScaleFactor(image, 1);
}
} // namespace
class SnapshotAuraTest : public testing::Test {
public:
SnapshotAuraTest() = default;
SnapshotAuraTest(const SnapshotAuraTest&) = delete;
SnapshotAuraTest& operator=(const SnapshotAuraTest&) = delete;
~SnapshotAuraTest() override = default;
void SetUp() override {
testing::Test::SetUp();
task_environment_ = std::make_unique<base::test::TaskEnvironment>(
base::test::TaskEnvironment::MainThreadType::UI);
// The ContextFactory must exist before any Compositors are created.
// Snapshot test tests real drawing and readback, so needs pixel output.
const bool enable_pixel_output = true;
context_factories_ =
std::make_unique<ui::TestContextFactories>(enable_pixel_output);
helper_ = std::make_unique<aura::test::AuraTestHelper>(
context_factories_->GetContextFactory());
helper_->SetUp();
}
void TearDown() override {
test_window_.reset();
delegate_.reset();
helper_->RunAllPendingInMessageLoop();
helper_.reset();
context_factories_.reset();
task_environment_.reset();
testing::Test::TearDown();
}
protected:
aura::Window* test_window() { return test_window_.get(); }
aura::Window* root_window() { return helper_->GetContext(); }
aura::TestScreen* test_screen() { return helper_->GetTestScreen(); }
void WaitForDraw() {
helper_->GetHost()->compositor()->ScheduleDraw();
ui::DrawWaiterForTest::WaitForCompositingEnded(
helper_->GetHost()->compositor());
}
void SetupTestWindow(const gfx::Rect& window_bounds) {
delegate_ =
std::make_unique<TestPaintingWindowDelegate>(window_bounds.size());
test_window_.reset(aura::test::CreateTestWindowWithDelegate(
delegate_.get(), 0, window_bounds, root_window()));
}
gfx::Image GrabSnapshotForTestWindow() {
gfx::Rect source_rect(test_window_->bounds().size());
aura::Window::ConvertRectToTarget(
test_window(), root_window(), &source_rect);
scoped_refptr<SnapshotHolder> holder(new SnapshotHolder);
ui::GrabWindowSnapshotAsync(
root_window(), source_rect,
base::BindOnce(&SnapshotHolder::SnapshotCallback, holder));
holder->WaitForSnapshot();
DCHECK(holder->completed());
return holder->image();
}
private:
class SnapshotHolder : public base::RefCountedThreadSafe<SnapshotHolder> {
public:
SnapshotHolder() : completed_(false) {}
void SnapshotCallback(gfx::Image image) {
DCHECK(!completed_);
image_ = image;
completed_ = true;
run_loop_.Quit();
}
void WaitForSnapshot() { run_loop_.Run(); }
bool completed() const { return completed_; }
const gfx::Image& image() const { return image_; }
private:
friend class base::RefCountedThreadSafe<SnapshotHolder>;
virtual ~SnapshotHolder() {}
base::RunLoop run_loop_;
gfx::Image image_;
bool completed_;
};
std::unique_ptr<base::test::TaskEnvironment> task_environment_;
std::unique_ptr<ui::TestContextFactories> context_factories_;
std::unique_ptr<aura::test::AuraTestHelper> helper_;
std::unique_ptr<aura::Window> test_window_;
std::unique_ptr<TestPaintingWindowDelegate> delegate_;
std::vector<unsigned char> png_representation_;
};
#if BUILDFLAG(IS_WIN) && !defined(NDEBUG)
// https://crbug.com/852512
#define MAYBE_FullScreenWindow DISABLED_FullScreenWindow
#elif BUILDFLAG(IS_LINUX)
// https://crbug.com/1143031
#define MAYBE_FullScreenWindow DISABLED_FullScreenWindow
#else
#define MAYBE_FullScreenWindow FullScreenWindow
#endif
TEST_F(SnapshotAuraTest, MAYBE_FullScreenWindow) {
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_FUCHSIA)
// TODO(https://crbug.com/1143031): Fix this test to run in < action_timeout()
// on the Linux Debug & TSAN bots.
const base::test::ScopedRunLoopTimeout increased_run_timeout(
FROM_HERE, TestTimeouts::action_max_timeout());
#endif // BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) ||
// BUILDFLAG(IS_FUCHSIA)
#if BUILDFLAG(IS_WIN)
// TODO(https://crbug.com/850556): Make work on Windows.
if (::testing::internal::AlwaysTrue()) {
GTEST_SKIP();
}
#endif
SetupTestWindow(root_window()->bounds());
WaitForDraw();
gfx::Image snapshot = GrabSnapshotForTestWindow();
EXPECT_EQ(test_window()->bounds().size().ToString(),
snapshot.Size().ToString());
EXPECT_EQ(0u, GetFailedPixelsCount(snapshot));
}
TEST_F(SnapshotAuraTest, PartialBounds) {
#if BUILDFLAG(IS_WIN)
// TODO(https://crbug.com/850556): Make work on Windows.
if (::testing::internal::AlwaysTrue()) {
GTEST_SKIP();
}
#endif
gfx::Rect test_bounds(100, 100, 300, 200);
SetupTestWindow(test_bounds);
WaitForDraw();
gfx::Image snapshot = GrabSnapshotForTestWindow();
EXPECT_EQ(test_bounds.size().ToString(), snapshot.Size().ToString());
EXPECT_EQ(0u, GetFailedPixelsCount(snapshot));
}
TEST_F(SnapshotAuraTest, Rotated) {
#if BUILDFLAG(IS_WIN)
// TODO(https://crbug.com/850556): Make work on Windows.
if (::testing::internal::AlwaysTrue()) {
GTEST_SKIP();
}
#endif
test_screen()->SetDisplayRotation(display::Display::ROTATE_90);
gfx::Rect test_bounds(100, 100, 300, 200);
SetupTestWindow(test_bounds);
WaitForDraw();
gfx::Image snapshot = GrabSnapshotForTestWindow();
EXPECT_EQ(test_bounds.size().ToString(), snapshot.Size().ToString());
EXPECT_EQ(0u, GetFailedPixelsCount(snapshot));
}
TEST_F(SnapshotAuraTest, UIScale) {
#if BUILDFLAG(IS_WIN)
// TODO(https://crbug.com/850556): Make work on Windows.
if (::testing::internal::AlwaysTrue()) {
GTEST_SKIP();
}
#endif
const float kUIScale = 0.5f;
test_screen()->SetUIScale(kUIScale);
gfx::Rect test_bounds(100, 100, 300, 200);
SetupTestWindow(test_bounds);
WaitForDraw();
// Snapshot always captures the physical pixels.
gfx::SizeF snapshot_size(test_bounds.size());
snapshot_size.InvScale(kUIScale);
gfx::Image snapshot = GrabSnapshotForTestWindow();
EXPECT_EQ(gfx::ToRoundedSize(snapshot_size).ToString(),
snapshot.Size().ToString());
EXPECT_EQ(0u, GetFailedPixelsCountWithScaleFactor(snapshot, 1 / kUIScale));
}
TEST_F(SnapshotAuraTest, DeviceScaleFactor) {
#if BUILDFLAG(IS_WIN)
// TODO(https://crbug.com/850556): Make work on Windows.
if (::testing::internal::AlwaysTrue()) {
GTEST_SKIP();
}
#endif
test_screen()->SetDeviceScaleFactor(2.0f);
gfx::Rect test_bounds(100, 100, 150, 100);
SetupTestWindow(test_bounds);
WaitForDraw();
// Snapshot always captures the physical pixels.
gfx::SizeF snapshot_size(test_bounds.size());
snapshot_size.Scale(2.0f);
gfx::Image snapshot = GrabSnapshotForTestWindow();
EXPECT_EQ(gfx::ToRoundedSize(snapshot_size).ToString(),
snapshot.Size().ToString());
EXPECT_EQ(0u, GetFailedPixelsCountWithScaleFactor(snapshot, 2));
}
TEST_F(SnapshotAuraTest, RotateAndUIScale) {
#if BUILDFLAG(IS_WIN)
// TODO(https://crbug.com/850556): Make work on Windows.
if (::testing::internal::AlwaysTrue()) {
GTEST_SKIP();
}
#endif
const float kUIScale = 0.5f;
test_screen()->SetUIScale(kUIScale);
test_screen()->SetDisplayRotation(display::Display::ROTATE_90);
gfx::Rect test_bounds(100, 100, 200, 300);
SetupTestWindow(test_bounds);
WaitForDraw();
// Snapshot always captures the physical pixels.
gfx::SizeF snapshot_size(test_bounds.size());
snapshot_size.InvScale(kUIScale);
gfx::Image snapshot = GrabSnapshotForTestWindow();
EXPECT_EQ(gfx::ToRoundedSize(snapshot_size).ToString(),
snapshot.Size().ToString());
EXPECT_EQ(0u, GetFailedPixelsCountWithScaleFactor(snapshot, 1 / kUIScale));
}
TEST_F(SnapshotAuraTest, RotateAndUIScaleAndScaleFactor) {
#if BUILDFLAG(IS_WIN)
// TODO(https://crbug.com/850556): Make work on Windows.
if (::testing::internal::AlwaysTrue()) {
GTEST_SKIP();
}
#endif
test_screen()->SetDeviceScaleFactor(2.0f);
const float kUIScale = 0.5f;
test_screen()->SetUIScale(kUIScale);
test_screen()->SetDisplayRotation(display::Display::ROTATE_90);
gfx::Rect test_bounds(20, 30, 100, 150);
SetupTestWindow(test_bounds);
WaitForDraw();
// Snapshot always captures the physical pixels.
gfx::SizeF snapshot_size(test_bounds.size());
snapshot_size.Scale(2.0f / kUIScale);
gfx::Image snapshot = GrabSnapshotForTestWindow();
EXPECT_EQ(gfx::ToRoundedSize(snapshot_size).ToString(),
snapshot.Size().ToString());
EXPECT_EQ(0u, GetFailedPixelsCountWithScaleFactor(snapshot, 2 / kUIScale));
}
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/snapshot/snapshot_aura_unittest.cc | C++ | unknown | 11,512 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_SNAPSHOT_SNAPSHOT_EXPORT_H_
#define UI_SNAPSHOT_SNAPSHOT_EXPORT_H_
// Defines SNAPSHOT_EXPORT so that functionality implemented by the snapshot
// module can be exported to consumers.
#if defined(COMPONENT_BUILD)
#if defined(WIN32)
#if defined(SNAPSHOT_IMPLEMENTATION)
#define SNAPSHOT_EXPORT __declspec(dllexport)
#else
#define SNAPSHOT_EXPORT __declspec(dllimport)
#endif // defined(SNAPSHOT_IMPLEMENTATION)
#else // defined(WIN32)
#if defined(SNAPSHOT_IMPLEMENTATION)
#define SNAPSHOT_EXPORT __attribute__((visibility("default")))
#else
#define SNAPSHOT_EXPORT
#endif
#endif
#else // defined(COMPONENT_BUILD)
#define SNAPSHOT_EXPORT
#endif
#endif // UI_SNAPSHOT_SNAPSHOT_EXPORT_H_
| Zhao-PengFei35/chromium_src_4 | ui/snapshot/snapshot_export.h | C | unknown | 849 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/snapshot/snapshot.h"
#include "base/functional/callback.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/image/image.h"
namespace ui {
bool GrabViewSnapshot(gfx::NativeView view,
const gfx::Rect& snapshot_bounds,
gfx::Image* image) {
// TODO(bajones): Implement iOS snapshot functionality
return false;
}
bool GrabWindowSnapshot(gfx::NativeWindow window,
const gfx::Rect& snapshot_bounds,
gfx::Image* image) {
// TODO(bajones): Implement iOS snapshot functionality
return false;
}
void GrabWindowSnapshotAndScaleAsync(
gfx::NativeWindow window,
const gfx::Rect& snapshot_bounds,
const gfx::Size& target_size,
GrabWindowSnapshotAsyncCallback callback) {
std::move(callback).Run(gfx::Image());
}
void GrabViewSnapshotAsync(gfx::NativeView view,
const gfx::Rect& source_rect,
GrabWindowSnapshotAsyncCallback callback) {
std::move(callback).Run(gfx::Image());
}
void GrabWindowSnapshotAsync(gfx::NativeWindow window,
const gfx::Rect& source_rect,
GrabWindowSnapshotAsyncCallback callback) {
std::move(callback).Run(gfx::Image());
}
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/snapshot/snapshot_ios.mm | Objective-C++ | unknown | 1,451 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/snapshot/snapshot.h"
#import <Cocoa/Cocoa.h>
#include "base/check_op.h"
#include "base/functional/callback.h"
#include "base/mac/scoped_cftyperef.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/image/image.h"
namespace ui {
bool GrabViewSnapshot(gfx::NativeView native_view,
const gfx::Rect& snapshot_bounds,
gfx::Image* image) {
NSView* view = native_view.GetNativeNSView();
NSWindow* window = [view window];
NSScreen* screen = [[NSScreen screens] firstObject];
gfx::Rect screen_bounds = gfx::Rect(NSRectToCGRect([screen frame]));
// Get the view bounds relative to the screen
NSRect frame = [view convertRect:[view bounds] toView:nil];
frame = [window convertRectToScreen:frame];
gfx::Rect view_bounds = gfx::Rect(NSRectToCGRect(frame));
// Flip window coordinates based on the primary screen.
view_bounds.set_y(
screen_bounds.height() - view_bounds.y() - view_bounds.height());
// Convert snapshot bounds relative to window into bounds relative to
// screen.
gfx::Rect screen_snapshot_bounds = snapshot_bounds;
screen_snapshot_bounds.Offset(view_bounds.OffsetFromOrigin());
DCHECK_LE(screen_snapshot_bounds.right(), view_bounds.right());
DCHECK_LE(screen_snapshot_bounds.bottom(), view_bounds.bottom());
base::ScopedCFTypeRef<CGImageRef> windowSnapshot(
CGWindowListCreateImage(screen_snapshot_bounds.ToCGRect(),
kCGWindowListOptionIncludingWindow,
[window windowNumber],
kCGWindowImageBoundsIgnoreFraming));
if (CGImageGetWidth(windowSnapshot) <= 0)
return false;
*image =
gfx::Image([[[NSImage alloc] initWithCGImage:windowSnapshot
size:NSZeroSize] autorelease]);
return true;
}
bool GrabWindowSnapshot(gfx::NativeWindow native_window,
const gfx::Rect& snapshot_bounds,
gfx::Image* image) {
// Make sure to grab the "window frame" view so we get current tab +
// tabstrip.
NSWindow* window = native_window.GetNativeNSWindow();
return GrabViewSnapshot([[window contentView] superview], snapshot_bounds,
image);
}
void GrabWindowSnapshotAndScaleAsync(
gfx::NativeWindow window,
const gfx::Rect& snapshot_bounds,
const gfx::Size& target_size,
GrabWindowSnapshotAsyncCallback callback) {
std::move(callback).Run(gfx::Image());
}
void GrabViewSnapshotAsync(gfx::NativeView view,
const gfx::Rect& source_rect,
GrabWindowSnapshotAsyncCallback callback) {
std::move(callback).Run(gfx::Image());
}
void GrabWindowSnapshotAsync(gfx::NativeWindow native_window,
const gfx::Rect& source_rect,
GrabWindowSnapshotAsyncCallback callback) {
NSWindow* window = native_window.GetNativeNSWindow();
return GrabViewSnapshotAsync([[window contentView] superview], source_rect,
std::move(callback));
}
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/snapshot/snapshot_mac.mm | Objective-C++ | unknown | 3,274 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/snapshot/snapshot.h"
#import <Cocoa/Cocoa.h>
#include <memory>
#include "base/mac/mac_util.h"
#include "base/mac/scoped_nsobject.h"
#include "base/test/task_environment.h"
#include "testing/platform_test.h"
#import "ui/base/test/cocoa_helper.h"
#import "ui/base/test/windowed_nsnotification_observer.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/image/image.h"
namespace ui {
namespace {
class GrabWindowSnapshotTest : public CocoaTest {
private:
base::test::TaskEnvironment task_environment_{
base::test::TaskEnvironment::MainThreadType::UI};
};
TEST_F(GrabWindowSnapshotTest, TestGrabWindowSnapshot) {
// Flaky only on the 10.13 bot yet not on any subsequent macOS bot.
// https://crbug.com/1359153
if (base::mac::IsOS10_13())
GTEST_SKIP() << "flaky on macOS 10.13 bot";
// The window snapshot code uses `CGWindowListCreateImage` which requires
// going to the windowserver. By default, unittests are run with the
// `NSApplicationActivationPolicyProhibited` policy which prohibits
// windowserver connections, which would cause this test to fail for reasons
// other than the code not actually working.
NSApp.activationPolicy = NSApplicationActivationPolicyAccessory;
// Launch a test window so we can take a snapshot.
const NSUInteger window_size = 400;
NSRect frame = NSMakeRect(0, 0, window_size, window_size);
NSWindow* window = test_window();
base::scoped_nsobject<WindowedNSNotificationObserver> waiter(
[[WindowedNSNotificationObserver alloc]
initForNotification:NSWindowDidUpdateNotification
object:window]);
[window setFrame:frame display:false];
[window setBackgroundColor:NSColor.blueColor];
[window makeKeyAndOrderFront:nil];
[window display];
EXPECT_TRUE([waiter wait]);
// Take the snapshot.
gfx::Image image;
gfx::Rect bounds = gfx::Rect(0, 0, window_size, window_size);
EXPECT_TRUE(ui::GrabWindowSnapshot(window, bounds, &image));
// The call to `CGWindowListCreateImage` returned a `CGImageRef` that is
// wrapped in an `NSImage` (inside the returned `gfx::Image`). The image rep
// that results (e.g. an `NSCGImageSnapshotRep` in macOS 12) isn't anything
// that pixel values can be retrieved from, so do a quick-and-dirty conversion
// to an `NSBitmapImageRep`.
NSBitmapImageRep* image_rep =
[NSBitmapImageRep imageRepWithData:image.ToNSImage().TIFFRepresentation];
// Test the size.
EXPECT_EQ(window_size * window.backingScaleFactor, image_rep.pixelsWide);
EXPECT_EQ(window_size * window.backingScaleFactor, image_rep.pixelsHigh);
// Pick a pixel in the middle of the screenshot and expect it to be some
// version of blue.
NSColor* color = [image_rep colorAtX:image_rep.pixelsWide / 2
y:image_rep.pixelsHigh / 2];
CGFloat red = 0, green = 0, blue = 0, alpha = 0;
[color getRed:&red green:&green blue:&blue alpha:&alpha];
EXPECT_LE(red, 0.2);
EXPECT_LE(green, 0.2);
EXPECT_GE(blue, 0.9);
EXPECT_EQ(alpha, 1);
}
} // namespace
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/snapshot/snapshot_mac_unittest.mm | Objective-C++ | unknown | 3,224 |
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/snapshot/snapshot_win.h"
#include <memory>
#include <utility>
#include "base/functional/callback.h"
#include "base/win/windows_version.h"
#include "skia/ext/platform_canvas.h"
#include "skia/ext/skia_utils_win.h"
#include "ui/aura/window.h"
#include "ui/aura/window_tree_host.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/geometry/skia_conversions.h"
#include "ui/gfx/geometry/transform.h"
#include "ui/gfx/image/image.h"
#include "ui/snapshot/snapshot.h"
#include "ui/snapshot/snapshot_aura.h"
namespace ui {
namespace internal {
bool GrabHwndSnapshot(HWND window_handle,
const gfx::Rect& snapshot_bounds_in_pixels,
const gfx::Rect& clip_rect_in_pixels,
gfx::Image* image) {
gfx::Rect snapshot_bounds_in_window =
snapshot_bounds_in_pixels + clip_rect_in_pixels.OffsetFromOrigin();
gfx::Size bitmap_size(snapshot_bounds_in_window.right(),
snapshot_bounds_in_window.bottom());
std::unique_ptr<SkCanvas> canvas = skia::CreatePlatformCanvas(
bitmap_size.width(), bitmap_size.height(), false);
HDC mem_hdc = skia::GetNativeDrawingContext(canvas.get());
// Grab a copy of the window. Use PrintWindow because it works even when the
// window's partially occluded. The PW_RENDERFULLCONTENT flag is undocumented,
// but works starting in Windows 8.1. It allows for capturing the contents of
// the window that are drawn using DirectComposition.
UINT flags = PW_CLIENTONLY | PW_RENDERFULLCONTENT;
BOOL result = PrintWindow(window_handle, mem_hdc, flags);
if (!result) {
PLOG(ERROR) << "Failed to print window";
return false;
}
SkBitmap bitmap;
bitmap.allocN32Pixels(snapshot_bounds_in_window.width(),
snapshot_bounds_in_window.height());
canvas->readPixels(bitmap, snapshot_bounds_in_window.x(),
snapshot_bounds_in_window.y());
// Clear the region of the bitmap outside the clip rect to white.
SkCanvas image_canvas(bitmap, SkSurfaceProps{});
SkPaint paint;
paint.setColor(SK_ColorWHITE);
SkRegion region;
gfx::Rect clip_in_bitmap(clip_rect_in_pixels.size());
clip_in_bitmap.Offset(-snapshot_bounds_in_pixels.OffsetFromOrigin());
region.setRect(
gfx::RectToSkIRect(gfx::Rect(snapshot_bounds_in_pixels.size())));
region.op(gfx::RectToSkIRect(clip_in_bitmap), SkRegion::kDifference_Op);
image_canvas.drawRegion(region, paint);
*image = gfx::Image::CreateFrom1xBitmap(bitmap);
return true;
}
} // namespace internal
bool GrabViewSnapshot(gfx::NativeView view_handle,
const gfx::Rect& snapshot_bounds,
gfx::Image* image) {
return GrabWindowSnapshot(view_handle, snapshot_bounds, image);
}
bool GrabWindowSnapshot(gfx::NativeWindow window_handle,
const gfx::Rect& snapshot_bounds,
gfx::Image* image) {
DCHECK(window_handle);
gfx::Rect window_bounds = window_handle->GetBoundsInRootWindow();
aura::WindowTreeHost* host = window_handle->GetHost();
DCHECK(host);
HWND hwnd = host->GetAcceleratedWidget();
gfx::Rect snapshot_bounds_in_pixels =
host->GetRootTransform().MapRect(snapshot_bounds);
gfx::Rect expanded_window_bounds_in_pixels =
host->GetRootTransform().MapRect(window_bounds);
RECT client_area;
::GetClientRect(hwnd, &client_area);
gfx::Rect client_area_rect(client_area);
client_area_rect.set_origin(gfx::Point());
expanded_window_bounds_in_pixels.Intersect(client_area_rect);
return internal::GrabHwndSnapshot(hwnd, snapshot_bounds_in_pixels,
expanded_window_bounds_in_pixels, image);
}
void GrabWindowSnapshotAsync(gfx::NativeWindow window,
const gfx::Rect& source_rect,
GrabWindowSnapshotAsyncCallback callback) {
gfx::Image image;
GrabWindowSnapshot(window, source_rect, &image);
std::move(callback).Run(image);
}
void GrabViewSnapshotAsync(gfx::NativeView view,
const gfx::Rect& source_rect,
GrabWindowSnapshotAsyncCallback callback) {
NOTIMPLEMENTED();
std::move(callback).Run(gfx::Image());
}
void GrabWindowSnapshotAndScaleAsync(gfx::NativeWindow window,
const gfx::Rect& source_rect,
const gfx::Size& target_size,
GrabWindowSnapshotAsyncCallback callback) {
NOTIMPLEMENTED();
std::move(callback).Run(gfx::Image());
}
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/snapshot/snapshot_win.cc | C++ | unknown | 4,783 |
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_SNAPSHOT_SNAPSHOT_WIN_H_
#define UI_SNAPSHOT_SNAPSHOT_WIN_H_
#include <windows.h>
#include "ui/snapshot/snapshot_export.h"
namespace gfx {
class Image;
class Rect;
}
namespace ui {
namespace internal {
// Grabs a snapshot of the desktop. No security checks are done. This is
// intended to be used for debugging purposes where no BrowserProcess instance
// is available (ie. tests). DO NOT use in a result of user action.
//
// snapshot_bounds_in_pixels is the area relative to clip_rect_in_pixels that
// should be captured. Areas outside clip_rect_in_pixels are filled white.
// clip_rect_in_pixels is relative to the client area of the window.
SNAPSHOT_EXPORT bool GrabHwndSnapshot(
HWND window_handle,
const gfx::Rect& snapshot_bounds_in_pixels,
const gfx::Rect& clip_rect_in_pixels,
gfx::Image* image);
} // namespace internal
} // namespace ui
#endif // UI_SNAPSHOT_SNAPSHOT_WIN_H_
| Zhao-PengFei35/chromium_src_4 | ui/snapshot/snapshot_win.h | C++ | unknown | 1,071 |
specific_include_rules = {
"run_all_unittests\.cc": [
"+mojo/core/embedder",
]
}
| Zhao-PengFei35/chromium_src_4 | ui/snapshot/test/DEPS | Python | unknown | 89 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/functional/bind.h"
#include "base/test/launcher/unit_test_launcher.h"
#include "base/test/test_suite.h"
#include "mojo/core/embedder/embedder.h"
#include "ui/compositor/test/test_suite.h"
int main(int argc, char** argv) {
mojo::core::Init();
#if defined(USE_AURA)
ui::test::CompositorTestSuite test_suite(argc, argv);
return base::LaunchUnitTests(
argc, argv,
base::BindOnce(&ui::test::CompositorTestSuite::Run,
base::Unretained(&test_suite)));
#else
base::TestSuite test_suite(argc, argv);
return base::LaunchUnitTests(
argc, argv,
base::BindOnce(&base::TestSuite::Run, base::Unretained(&test_suite)));
#endif
}
| Zhao-PengFei35/chromium_src_4 | ui/snapshot/test/run_all_unittests.cc | C++ | unknown | 830 |
include_rules = [
"+skia/ext",
"+third_party/skia",
"+ui/base",
"+ui/latency/latency_info.h",
"+ui/gfx",
"+ui/gl",
]
| Zhao-PengFei35/chromium_src_4 | ui/surface/DEPS | Python | unknown | 129 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_SURFACE_SURFACE_EXPORT_H_
#define UI_SURFACE_SURFACE_EXPORT_H_
#if defined(COMPONENT_BUILD)
#if defined(WIN32)
#if defined(SURFACE_IMPLEMENTATION)
#define SURFACE_EXPORT __declspec(dllexport)
#else
#define SURFACE_EXPORT __declspec(dllimport)
#endif // defined(SURFACE_IMPLEMENTATION)
#else // defined(WIN32)
#if defined(SURFACE_IMPLEMENTATION)
#define SURFACE_EXPORT __attribute__((visibility("default")))
#else
#define SURFACE_EXPORT
#endif
#endif
#else // defined(COMPONENT_BUILD)
#define SURFACE_EXPORT
#endif
#endif // UI_SURFACE_SURFACE_EXPORT_H_
| Zhao-PengFei35/chromium_src_4 | ui/surface/surface_export.h | C | unknown | 717 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/surface/transport_dib.h"
#include <stddef.h>
#include <memory>
#include "base/logging.h"
#include "base/memory/ptr_util.h"
#include "base/memory/shared_memory_mapping.h"
#include "base/memory/unsafe_shared_memory_region.h"
#include "base/numerics/checked_math.h"
#include "build/build_config.h"
#include "skia/ext/platform_canvas.h"
TransportDIB::TransportDIB(base::UnsafeSharedMemoryRegion region)
: shm_region_(std::move(region)) {}
TransportDIB::~TransportDIB() = default;
// static
std::unique_ptr<TransportDIB> TransportDIB::Map(
base::UnsafeSharedMemoryRegion region) {
std::unique_ptr<TransportDIB> dib = CreateWithHandle(std::move(region));
if (!dib->Map())
return nullptr;
return dib;
}
// static
std::unique_ptr<TransportDIB> TransportDIB::CreateWithHandle(
base::UnsafeSharedMemoryRegion region) {
return base::WrapUnique(new TransportDIB(std::move(region)));
}
std::unique_ptr<SkCanvas> TransportDIB::GetPlatformCanvas(int w,
int h,
bool opaque) {
if (!shm_region_.IsValid())
return nullptr;
// Calculate the size for the memory region backing the canvas. If not valid
// then fail gracefully.
size_t canvas_size;
// 32-bit RGB data. A size_t causes a type change from int when multiplying.
const size_t bpp = 4;
if (!base::CheckMul(h, base::CheckMul(w, bpp)).AssignIfValid(&canvas_size))
return nullptr;
#if BUILDFLAG(IS_WIN)
// This DIB already mapped the file into this process, but PlatformCanvas
// will map it again.
DCHECK(!memory()) << "Mapped file twice in the same process.";
// We can't check the canvas size before mapping, but it's safe because
// Windows will fail to map the section if the dimensions of the canvas
// are too large.
std::unique_ptr<SkCanvas> canvas =
skia::CreatePlatformCanvasWithSharedSection(
w, h, opaque, shm_region_.GetPlatformHandle(),
skia::RETURN_NULL_ON_FAILURE);
if (canvas)
size_ = canvas_size;
return canvas;
#else
if ((!memory() && !Map()) || !VerifyCanvasSize(w, h))
return nullptr;
return skia::CreatePlatformCanvasWithPixels(w, h, opaque,
static_cast<uint8_t*>(memory()),
skia::RETURN_NULL_ON_FAILURE);
#endif
}
bool TransportDIB::Map() {
if (!shm_region_.IsValid())
return false;
if (memory())
return true;
shm_mapping_ = shm_region_.Map();
if (!shm_mapping_.IsValid()) {
PLOG(ERROR) << "Failed to map transport DIB";
return false;
}
size_ = shm_mapping_.size();
return true;
}
void* TransportDIB::memory() const {
return shm_mapping_.IsValid() ? shm_mapping_.memory() : nullptr;
}
base::UnsafeSharedMemoryRegion* TransportDIB::shared_memory_region() {
return &shm_region_;
}
// static
bool TransportDIB::VerifyCanvasSize(int w, int h) {
if (w <= 0 || h <= 0)
return false;
size_t canvas_size;
// 32-bit RGB data. A size_t causes a type change from int when multiplying.
const size_t bpp = 4;
if (!base::CheckMul(h, base::CheckMul(w, bpp)).AssignIfValid(&canvas_size))
return false;
return canvas_size <= size_;
}
| Zhao-PengFei35/chromium_src_4 | ui/surface/transport_dib.cc | C++ | unknown | 3,419 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_SURFACE_TRANSPORT_DIB_H_
#define UI_SURFACE_TRANSPORT_DIB_H_
#include <stddef.h>
#include <memory>
#include "base/memory/shared_memory_mapping.h"
#include "base/memory/unsafe_shared_memory_region.h"
#include "build/build_config.h"
#include "ui/surface/surface_export.h"
class SkCanvas;
// -----------------------------------------------------------------------------
// A TransportDIB is a block of memory that is used to transport pixels
// between processes: from the renderer process to the browser, and
// between renderer and plugin processes.
// -----------------------------------------------------------------------------
class SURFACE_EXPORT TransportDIB {
public:
TransportDIB(const TransportDIB&) = delete;
TransportDIB& operator=(const TransportDIB&) = delete;
~TransportDIB();
// Creates and maps a new TransportDIB with a shared memory region.
// Returns nullptr on failure.
static std::unique_ptr<TransportDIB> Map(
base::UnsafeSharedMemoryRegion region);
// Creates a new TransportDIB with a shared memory region. This always returns
// a valid pointer. The DIB is not mapped.
static std::unique_ptr<TransportDIB> CreateWithHandle(
base::UnsafeSharedMemoryRegion region);
// Returns a canvas using the memory of this TransportDIB. The returned
// pointer will be owned by the caller. The bitmap will be of the given size,
// which should fit inside this memory. Bitmaps returned will be either
// opaque or have premultiplied alpha.
//
// On POSIX, this |TransportDIB| will be mapped if not already. On Windows,
// this |TransportDIB| will NOT be mapped and should not be mapped prior,
// because PlatformCanvas will map the file internally.
//
// Will return NULL on allocation failure. This could be because the image
// is too large to map into the current process' address space.
std::unique_ptr<SkCanvas> GetPlatformCanvas(int w, int h, bool opaque);
// Map the DIB into the current process if it is not already. This is used to
// map a DIB that has already been created. Returns true if the DIB is mapped.
bool Map();
// Return a pointer to the shared memory.
void* memory() const;
// Return the maximum size of the shared memory. This is not the amount of
// data which is valid, you have to know that via other means, this is simply
// the maximum amount that /could/ be valid.
size_t size() const { return size_; }
// Returns a pointer to the UnsafeSharedMemoryRegion object that backs the
// transport dib.
base::UnsafeSharedMemoryRegion* shared_memory_region();
private:
// Verifies that the dib can hold a canvas of the requested dimensions.
bool VerifyCanvasSize(int w, int h);
explicit TransportDIB(base::UnsafeSharedMemoryRegion region);
base::UnsafeSharedMemoryRegion shm_region_;
base::WritableSharedMemoryMapping shm_mapping_;
size_t size_ = 0;
};
#endif // UI_SURFACE_TRANSPORT_DIB_H_
| Zhao-PengFei35/chromium_src_4 | ui/surface/transport_dib.h | C++ | unknown | 3,085 |
include_rules = [
"+ui/aura",
"+ui/aura_extra",
"+ui/base",
"+ui/compositor",
"+ui/events",
"+ui/gfx",
"+ui/resources"
]
| Zhao-PengFei35/chromium_src_4 | ui/touch_selection/DEPS | Python | unknown | 135 |
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/touch_selection/longpress_drag_selector.h"
#include "base/auto_reset.h"
#include "ui/events/gesture_detection/motion_event.h"
namespace ui {
namespace {
gfx::Vector2dF SafeNormalize(const gfx::Vector2dF& v) {
return v.IsZero() ? v : ScaleVector2d(v, 1.f / v.Length());
}
} // namespace
LongPressDragSelector::LongPressDragSelector(
LongPressDragSelectorClient* client)
: client_(client),
state_(INACTIVE),
has_longpress_drag_start_anchor_(false) {
}
LongPressDragSelector::~LongPressDragSelector() {
}
bool LongPressDragSelector::WillHandleTouchEvent(const MotionEvent& event) {
switch (event.GetAction()) {
case MotionEvent::Action::DOWN:
touch_down_position_.SetPoint(event.GetX(), event.GetY());
touch_down_time_ = event.GetEventTime();
has_longpress_drag_start_anchor_ = false;
SetState(LONGPRESS_PENDING);
return false;
case MotionEvent::Action::UP:
case MotionEvent::Action::CANCEL:
SetState(INACTIVE);
#ifdef OHOS_CLIPBOARD
client_->UpdateSelectionChanged(*this);
#endif
return false;
case MotionEvent::Action::MOVE:
break;
default:
return false;
}
if (state_ != DRAG_PENDING && state_ != DRAGGING)
return false;
gfx::PointF position(event.GetX(), event.GetY());
if (state_ == DRAGGING) {
gfx::PointF drag_position = position + longpress_drag_selection_offset_;
client_->OnDragUpdate(*this, drag_position);
return true;
}
// We can't use |touch_down_position_| as the offset anchor, as
// showing the selection UI may have shifted the motion coordinates.
if (!has_longpress_drag_start_anchor_) {
has_longpress_drag_start_anchor_ = true;
longpress_drag_start_anchor_ = position;
return true;
}
// Allow an additional slop affordance after the longpress occurs.
gfx::Vector2dF delta = position - longpress_drag_start_anchor_;
if (client_->IsWithinTapSlop(delta))
return true;
gfx::PointF selection_start = client_->GetSelectionStart();
gfx::PointF selection_end = client_->GetSelectionEnd();
bool extend_selection_start = false;
if (std::abs(delta.y()) > std::abs(delta.x())) {
// If initial motion is up/down, extend the start/end selection bound.
extend_selection_start = delta.y() < 0;
} else {
// Otherwise extend the selection bound toward which we're moving, or
// the closest bound if motion is already away from both bounds.
// Note that, for mixed RTL text, or for multiline selections triggered
// by longpress, this may not pick the most suitable drag target
gfx::Vector2dF start_delta = selection_start - longpress_drag_start_anchor_;
gfx::Vector2dF end_delta = selection_end - longpress_drag_start_anchor_;
// The vectors must be normalized to make dot product comparison meaningful.
gfx::Vector2dF normalized_start_delta = SafeNormalize(start_delta);
gfx::Vector2dF normalized_end_delta = SafeNormalize(end_delta);
double start_dot_product = gfx::DotProduct(normalized_start_delta, delta);
double end_dot_product = gfx::DotProduct(normalized_end_delta, delta);
if (start_dot_product >= 0 || end_dot_product >= 0) {
// The greater the dot product the more similar the direction.
extend_selection_start = start_dot_product > end_dot_product;
} else {
// If we're already moving away from both endpoints, pick the closest.
extend_selection_start =
start_delta.LengthSquared() < end_delta.LengthSquared();
}
}
gfx::PointF extent = extend_selection_start ? selection_start : selection_end;
longpress_drag_selection_offset_ = extent - position;
client_->OnDragBegin(*this, extent);
SetState(DRAGGING);
return true;
}
bool LongPressDragSelector::IsActive() const {
return state_ == DRAG_PENDING || state_ == DRAGGING;
}
void LongPressDragSelector::OnLongPressEvent(base::TimeTicks event_time,
const gfx::PointF& position) {
// We have no guarantees that the current gesture stream is aligned with the
// observed touch stream. We only know that the gesture sequence is downstream
// from the touch sequence. Using a time/distance heuristic helps ensure that
// the observed longpress corresponds to the active touch sequence.
if (state_ == LONGPRESS_PENDING &&
// Ensure the down event occurs *before* the longpress event. Use a
// small time epsilon to account for floating point time conversion.
(touch_down_time_ < event_time + base::Microseconds(10)) &&
client_->IsWithinTapSlop(touch_down_position_ - position)) {
SetState(SELECTION_PENDING);
}
}
void LongPressDragSelector::OnScrollBeginEvent() {
SetState(INACTIVE);
}
void LongPressDragSelector::OnSelectionActivated() {
if (state_ == SELECTION_PENDING)
SetState(DRAG_PENDING);
}
void LongPressDragSelector::OnSelectionDeactivated() {
SetState(INACTIVE);
}
void LongPressDragSelector::SetState(SelectionState state) {
if (state_ == state)
return;
const bool was_dragging = state_ == DRAGGING;
const bool was_active = IsActive();
state_ = state;
// TODO(jdduke): Add UMA for tracking relative longpress drag frequency.
if (was_dragging)
client_->OnDragEnd(*this);
if (was_active != IsActive())
client_->OnLongPressDragActiveStateChanged();
}
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/touch_selection/longpress_drag_selector.cc | C++ | unknown | 5,518 |
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_TOUCH_SELECTION_LONGPRESS_DRAG_SELECTOR_H_
#define UI_TOUCH_SELECTION_LONGPRESS_DRAG_SELECTOR_H_
#include "base/memory/raw_ptr.h"
#include "base/time/time.h"
#include "ui/gfx/geometry/point_f.h"
#include "ui/gfx/geometry/vector2d_f.h"
#include "ui/touch_selection/touch_selection_draggable.h"
#include "ui/touch_selection/ui_touch_selection_export.h"
namespace ui {
class MotionEvent;
class UI_TOUCH_SELECTION_EXPORT LongPressDragSelectorClient
: public TouchSelectionDraggableClient {
public:
~LongPressDragSelectorClient() override {}
virtual void OnLongPressDragActiveStateChanged() = 0;
virtual gfx::PointF GetSelectionStart() const = 0;
virtual gfx::PointF GetSelectionEnd() const = 0;
};
// Supports text selection via touch dragging after a longpress-initiated
// selection.
class UI_TOUCH_SELECTION_EXPORT LongPressDragSelector
: public TouchSelectionDraggable {
public:
explicit LongPressDragSelector(LongPressDragSelectorClient* client);
~LongPressDragSelector() override;
// TouchSelectionDraggable implementation.
bool WillHandleTouchEvent(const MotionEvent& event) override;
bool IsActive() const override;
// Called just prior to a longpress event being handled.
void OnLongPressEvent(base::TimeTicks event_time,
const gfx::PointF& position);
// Called when a scroll is going to happen to cancel longpress-drag gesture.
void OnScrollBeginEvent();
// Called when the active selection changes.
void OnSelectionActivated();
void OnSelectionDeactivated();
private:
enum SelectionState {
INACTIVE,
LONGPRESS_PENDING,
SELECTION_PENDING,
DRAG_PENDING,
DRAGGING
};
void SetState(SelectionState state);
const raw_ptr<LongPressDragSelectorClient> client_;
SelectionState state_;
base::TimeTicks touch_down_time_;
gfx::PointF touch_down_position_;
gfx::Vector2dF longpress_drag_selection_offset_;
gfx::PointF longpress_drag_start_anchor_;
bool has_longpress_drag_start_anchor_;
};
} // namespace ui
#endif // UI_TOUCH_SELECTION_LONGPRESS_DRAG_SELECTOR_H_
| Zhao-PengFei35/chromium_src_4 | ui/touch_selection/longpress_drag_selector.h | C++ | unknown | 2,239 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/touch_selection/longpress_drag_selector.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/events/test/motion_event_test_utils.h"
using ui::test::MockMotionEvent;
namespace ui {
namespace {
const double kSlop = 10.;
} // namespace
class LongPressDragSelectorTest : public testing::Test,
public LongPressDragSelectorClient {
public:
LongPressDragSelectorTest()
: dragging_(false), active_state_changed_(false) {}
~LongPressDragSelectorTest() override {}
void SetSelection(const gfx::PointF& start, const gfx::PointF& end) {
selection_start_ = start;
selection_end_ = end;
}
bool GetAndResetActiveStateChanged() {
bool active_state_changed = active_state_changed_;
active_state_changed_ = false;
return active_state_changed;
}
bool IsDragging() const { return dragging_; }
const gfx::PointF& DragPosition() const { return drag_position_; }
// LongPressDragSelectorClient implementation.
void OnDragBegin(const TouchSelectionDraggable& handler,
const gfx::PointF& drag_position) override {
dragging_ = true;
drag_position_ = drag_position;
}
void OnDragUpdate(const TouchSelectionDraggable& handler,
const gfx::PointF& drag_position) override {
drag_position_ = drag_position;
}
void OnDragEnd(const TouchSelectionDraggable& handler) override {
dragging_ = false;
}
bool IsWithinTapSlop(const gfx::Vector2dF& delta) const override {
return delta.LengthSquared() < (kSlop * kSlop);
}
void OnLongPressDragActiveStateChanged() override {
active_state_changed_ = true;
}
gfx::PointF GetSelectionStart() const override { return selection_start_; }
gfx::PointF GetSelectionEnd() const override { return selection_end_; }
#if defined(OHOS_UNITTESTS)
void UpdateSelectionChanged(const TouchSelectionDraggable& draggable) override {}
#endif // OHOS_UNITTESTS
private:
bool dragging_;
bool active_state_changed_;
gfx::PointF drag_position_;
gfx::PointF selection_start_;
gfx::PointF selection_end_;
};
TEST_F(LongPressDragSelectorTest, BasicDrag) {
LongPressDragSelector selector(this);
MockMotionEvent event;
// Start a touch sequence.
EXPECT_FALSE(selector.WillHandleTouchEvent(event.PressPoint(0, 0)));
EXPECT_FALSE(GetAndResetActiveStateChanged());
// Activate a longpress-triggered selection.
gfx::PointF selection_start(0, 10);
gfx::PointF selection_end(10, 10);
selector.OnLongPressEvent(event.GetEventTime(), gfx::PointF());
EXPECT_FALSE(GetAndResetActiveStateChanged());
// Motion should not be consumed until a selection is detected.
EXPECT_FALSE(selector.WillHandleTouchEvent(event.MovePoint(0, 0, 0)));
SetSelection(selection_start, selection_end);
selector.OnSelectionActivated();
EXPECT_TRUE(GetAndResetActiveStateChanged());
EXPECT_FALSE(IsDragging());
// Initiate drag motion. Note that the first move event after activation is
// used to initialize the drag start anchor.
EXPECT_TRUE(selector.WillHandleTouchEvent(event.MovePoint(0, 0, 0)));
EXPECT_FALSE(IsDragging());
// The first slop exceeding motion will start the drag. As the motion is
// downward, the end selection point should be moved.
EXPECT_TRUE(selector.WillHandleTouchEvent(event.MovePoint(0, 0, kSlop)));
EXPECT_TRUE(IsDragging());
EXPECT_EQ(selection_end, DragPosition());
// Subsequent motion will extend the selection.
EXPECT_TRUE(selector.WillHandleTouchEvent(event.MovePoint(0, 0, kSlop * 2)));
EXPECT_TRUE(IsDragging());
EXPECT_EQ(selection_end + gfx::Vector2dF(0, kSlop), DragPosition());
EXPECT_TRUE(selector.WillHandleTouchEvent(event.MovePoint(0, 0, kSlop * 3)));
EXPECT_TRUE(IsDragging());
EXPECT_EQ(selection_end + gfx::Vector2dF(0, kSlop * 2), DragPosition());
// Release the touch sequence, ending the drag. The selector will never
// consume the start/end events, only move events after a longpress.
EXPECT_FALSE(selector.WillHandleTouchEvent(event.ReleasePoint()));
EXPECT_FALSE(IsDragging());
EXPECT_TRUE(GetAndResetActiveStateChanged());
}
TEST_F(LongPressDragSelectorTest, BasicReverseDrag) {
LongPressDragSelector selector(this);
MockMotionEvent event;
// Start a touch sequence.
EXPECT_FALSE(selector.WillHandleTouchEvent(event.PressPoint(0, 0)));
EXPECT_FALSE(GetAndResetActiveStateChanged());
// Activate a longpress-triggered selection.
gfx::PointF selection_start(0, 10);
gfx::PointF selection_end(10, 10);
selector.OnLongPressEvent(event.GetEventTime(), gfx::PointF());
EXPECT_FALSE(GetAndResetActiveStateChanged());
SetSelection(selection_start, selection_end);
selector.OnSelectionActivated();
EXPECT_TRUE(GetAndResetActiveStateChanged());
EXPECT_FALSE(IsDragging());
// Initiate drag motion.
EXPECT_TRUE(selector.WillHandleTouchEvent(event.MovePoint(0, 5, 0)));
EXPECT_FALSE(IsDragging());
// As the initial motion is leftward, toward the selection start, the
// selection start should be the drag point.
EXPECT_TRUE(selector.WillHandleTouchEvent(event.MovePoint(0, -kSlop, 0)));
EXPECT_TRUE(IsDragging());
EXPECT_EQ(selection_start, DragPosition());
EXPECT_TRUE(selector.WillHandleTouchEvent(event.MovePoint(0, 0, -kSlop)));
EXPECT_TRUE(IsDragging());
EXPECT_EQ(selection_start + gfx::Vector2dF(kSlop, -kSlop), DragPosition());
// Release the touch sequence, ending the drag.
EXPECT_FALSE(selector.WillHandleTouchEvent(event.ReleasePoint()));
EXPECT_FALSE(IsDragging());
EXPECT_TRUE(GetAndResetActiveStateChanged());
}
TEST_F(LongPressDragSelectorTest, NoActiveTouch) {
LongPressDragSelector selector(this);
MockMotionEvent event;
// Activate a longpress-triggered selection.
gfx::PointF selection_start(0, 10);
gfx::PointF selection_end(10, 10);
selector.OnLongPressEvent(event.GetEventTime(), gfx::PointF());
SetSelection(selection_start, selection_end);
selector.OnSelectionActivated();
EXPECT_FALSE(GetAndResetActiveStateChanged());
EXPECT_FALSE(IsDragging());
// Start a new touch sequence; it shouldn't initiate selection drag as there
// was no active touch sequence when the longpress selection started.
EXPECT_FALSE(selector.WillHandleTouchEvent(event.PressPoint(0, 0)));
EXPECT_FALSE(selector.WillHandleTouchEvent(event.MovePoint(0, 0, 0)));
EXPECT_FALSE(selector.WillHandleTouchEvent(event.MovePoint(0, 0, kSlop)));
EXPECT_FALSE(selector.WillHandleTouchEvent(event.MovePoint(0, 0, kSlop * 2)));
EXPECT_FALSE(IsDragging());
EXPECT_EQ(gfx::PointF(), DragPosition());
}
TEST_F(LongPressDragSelectorTest, NoLongPress) {
LongPressDragSelector selector(this);
MockMotionEvent event;
// Start a touch sequence.
EXPECT_FALSE(selector.WillHandleTouchEvent(event.PressPoint(0, 0)));
EXPECT_FALSE(GetAndResetActiveStateChanged());
// Activate a selection without a preceding longpress.
gfx::PointF selection_start(0, 10);
gfx::PointF selection_end(10, 10);
SetSelection(selection_start, selection_end);
selector.OnSelectionActivated();
EXPECT_FALSE(GetAndResetActiveStateChanged());
EXPECT_FALSE(IsDragging());
// Touch movement should not initiate selection drag.
EXPECT_FALSE(selector.WillHandleTouchEvent(event.MovePoint(0, 0, 0)));
EXPECT_FALSE(selector.WillHandleTouchEvent(event.MovePoint(0, 0, kSlop)));
EXPECT_FALSE(selector.WillHandleTouchEvent(event.MovePoint(0, 0, kSlop * 2)));
EXPECT_FALSE(IsDragging());
EXPECT_EQ(gfx::PointF(), DragPosition());
}
TEST_F(LongPressDragSelectorTest, NoValidLongPress) {
LongPressDragSelector selector(this);
MockMotionEvent event;
// Start a touch sequence.
EXPECT_FALSE(selector.WillHandleTouchEvent(event.PressPoint(0, 0)));
EXPECT_FALSE(GetAndResetActiveStateChanged());
gfx::PointF selection_start(0, 10);
gfx::PointF selection_end(10, 10);
SetSelection(selection_start, selection_end);
// Activate a longpress-triggered selection, but at a time before the current
// touch down event.
selector.OnLongPressEvent(event.GetEventTime() - base::Seconds(1),
gfx::PointF());
selector.OnSelectionActivated();
EXPECT_FALSE(GetAndResetActiveStateChanged());
EXPECT_FALSE(IsDragging());
// Activate a longpress-triggered selection, but at a place different than the
// current touch down event.
selector.OnLongPressEvent(event.GetEventTime(), gfx::PointF(kSlop, 0));
selector.OnSelectionActivated();
EXPECT_FALSE(GetAndResetActiveStateChanged());
EXPECT_FALSE(IsDragging());
// Touch movement should not initiate selection drag.
EXPECT_FALSE(selector.WillHandleTouchEvent(event.MovePoint(0, 0, 0)));
EXPECT_FALSE(selector.WillHandleTouchEvent(event.MovePoint(0, 0, kSlop)));
EXPECT_FALSE(selector.WillHandleTouchEvent(event.MovePoint(0, 0, kSlop * 2)));
EXPECT_FALSE(IsDragging());
EXPECT_EQ(gfx::PointF(), DragPosition());
}
TEST_F(LongPressDragSelectorTest, NoSelection) {
LongPressDragSelector selector(this);
MockMotionEvent event;
// Start a touch sequence.
EXPECT_FALSE(selector.WillHandleTouchEvent(event.PressPoint(0, 0)));
EXPECT_FALSE(GetAndResetActiveStateChanged());
// Trigger a longpress.
selector.OnLongPressEvent(event.GetEventTime(), gfx::PointF());
EXPECT_FALSE(GetAndResetActiveStateChanged());
EXPECT_FALSE(IsDragging());
// Touch movement should not initiate selection drag, as there is no active
// selection.
EXPECT_FALSE(selector.WillHandleTouchEvent(event.MovePoint(0, 0, 0)));
EXPECT_FALSE(selector.WillHandleTouchEvent(event.MovePoint(0, 0, kSlop)));
EXPECT_FALSE(selector.WillHandleTouchEvent(event.MovePoint(0, 0, kSlop * 2)));
EXPECT_FALSE(IsDragging());
EXPECT_EQ(gfx::PointF(), DragPosition());
EXPECT_FALSE(selector.WillHandleTouchEvent(event.ReleasePoint()));
}
TEST_F(LongPressDragSelectorTest, NoDragMotion) {
LongPressDragSelector selector(this);
MockMotionEvent event;
// Start a touch sequence.
EXPECT_FALSE(selector.WillHandleTouchEvent(event.PressPoint(0, 0)));
EXPECT_FALSE(GetAndResetActiveStateChanged());
// Activate a longpress-triggered selection.
selector.OnLongPressEvent(event.GetEventTime(), gfx::PointF());
EXPECT_FALSE(GetAndResetActiveStateChanged());
gfx::PointF selection_start(0, 10);
gfx::PointF selection_end(10, 10);
SetSelection(selection_start, selection_end);
selector.OnSelectionActivated();
EXPECT_TRUE(GetAndResetActiveStateChanged());
EXPECT_FALSE(IsDragging());
// Touch movement within the slop region should not initiate selection drag.
EXPECT_TRUE(selector.WillHandleTouchEvent(event.MovePoint(0, 0, 0)));
EXPECT_TRUE(selector.WillHandleTouchEvent(event.MovePoint(0, 0, kSlop / 2)));
EXPECT_TRUE(selector.WillHandleTouchEvent(event.MovePoint(0, 0, -kSlop / 2)));
EXPECT_FALSE(IsDragging());
EXPECT_EQ(gfx::PointF(), DragPosition());
EXPECT_FALSE(selector.WillHandleTouchEvent(event.ReleasePoint()));
EXPECT_TRUE(GetAndResetActiveStateChanged());
}
TEST_F(LongPressDragSelectorTest, SelectionDeactivated) {
LongPressDragSelector selector(this);
MockMotionEvent event;
// Start a touch sequence.
EXPECT_FALSE(selector.WillHandleTouchEvent(event.PressPoint(0, 0)));
EXPECT_FALSE(GetAndResetActiveStateChanged());
// Activate a longpress-triggered selection.
selector.OnLongPressEvent(event.GetEventTime(), gfx::PointF());
EXPECT_FALSE(GetAndResetActiveStateChanged());
gfx::PointF selection_start(0, 10);
gfx::PointF selection_end(10, 10);
SetSelection(selection_start, selection_end);
selector.OnSelectionActivated();
EXPECT_TRUE(GetAndResetActiveStateChanged());
EXPECT_FALSE(IsDragging());
// Start a drag selection.
EXPECT_TRUE(selector.WillHandleTouchEvent(event.MovePoint(0, 0, 0)));
EXPECT_TRUE(selector.WillHandleTouchEvent(event.MovePoint(0, 0, kSlop)));
EXPECT_TRUE(selector.WillHandleTouchEvent(event.MovePoint(0, 0, kSlop * 2)));
EXPECT_TRUE(IsDragging());
// Clearing the selection should force an end to the drag.
selector.OnSelectionDeactivated();
EXPECT_TRUE(GetAndResetActiveStateChanged());
EXPECT_FALSE(IsDragging());
// Subsequent motion should not be consumed.
EXPECT_FALSE(selector.WillHandleTouchEvent(event.MovePoint(0, 0, 0)));
EXPECT_FALSE(selector.WillHandleTouchEvent(event.MovePoint(0, 0, kSlop)));
EXPECT_FALSE(selector.WillHandleTouchEvent(event.MovePoint(0, 0, kSlop * 2)));
EXPECT_FALSE(IsDragging());
EXPECT_FALSE(selector.WillHandleTouchEvent(event.ReleasePoint()));
}
TEST_F(LongPressDragSelectorTest, DragFast) {
LongPressDragSelector selector(this);
MockMotionEvent event;
// Start a touch sequence.
EXPECT_FALSE(selector.WillHandleTouchEvent(event.PressPoint(0, 0)));
EXPECT_FALSE(GetAndResetActiveStateChanged());
// Activate a longpress-triggered selection.
gfx::PointF selection_start(0, 10);
gfx::PointF selection_end(10, 10);
selector.OnLongPressEvent(event.GetEventTime(), gfx::PointF());
EXPECT_FALSE(GetAndResetActiveStateChanged());
SetSelection(selection_start, selection_end);
selector.OnSelectionActivated();
EXPECT_TRUE(GetAndResetActiveStateChanged());
EXPECT_FALSE(IsDragging());
// Initiate drag motion.
EXPECT_TRUE(selector.WillHandleTouchEvent(event.MovePoint(0, 15, 5)));
EXPECT_FALSE(IsDragging());
// As the initial motion exceeds both endpoints, the closer bound should
// be used for dragging, in this case the selection end.
EXPECT_TRUE(selector.WillHandleTouchEvent(
event.MovePoint(0, 15.f + kSlop * 2.f, 5.f + kSlop)));
EXPECT_TRUE(IsDragging());
EXPECT_EQ(selection_end, DragPosition());
// Release the touch sequence, ending the drag.
EXPECT_FALSE(selector.WillHandleTouchEvent(event.ReleasePoint()));
EXPECT_FALSE(IsDragging());
EXPECT_TRUE(GetAndResetActiveStateChanged());
}
TEST_F(LongPressDragSelectorTest, ScrollAfterLongPress) {
LongPressDragSelector selector(this);
MockMotionEvent event;
gfx::PointF touch_point(0, 0);
// Start a touch sequence.
EXPECT_FALSE(selector.WillHandleTouchEvent(
event.PressPoint(touch_point.x(), touch_point.y())));
// Long-press and hold down.
selector.OnLongPressEvent(event.GetEventTime(), touch_point);
// Scroll the page. This should cancel long-press drag gesture.
touch_point.Offset(0, 2 * kSlop);
EXPECT_FALSE(selector.WillHandleTouchEvent(
event.MovePoint(0, touch_point.x(), touch_point.y())));
selector.OnScrollBeginEvent();
// Now if the selection is activated, because long-press drag gesture was
// canceled, active state of the long-press selector should not change.
selector.OnSelectionActivated();
EXPECT_FALSE(GetAndResetActiveStateChanged());
// Release the touch sequence.
selector.WillHandleTouchEvent(event.ReleasePoint());
}
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/touch_selection/longpress_drag_selector_unittest.cc | C++ | unknown | 14,929 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_TOUCH_SELECTION_SELECTION_EVENT_TYPE_H_
#define UI_TOUCH_SELECTION_SELECTION_EVENT_TYPE_H_
namespace ui {
// This file contains a list of events relating to selection and insertion, used
// for notifying Java when the renderer selection has changed.
// A Java counterpart will be generated for this enum.
// GENERATED_JAVA_ENUM_PACKAGE: org.chromium.ui.touch_selection
enum SelectionEventType {
SELECTION_HANDLES_SHOWN,
SELECTION_HANDLES_MOVED,
SELECTION_HANDLES_CLEARED,
SELECTION_HANDLE_DRAG_STARTED,
SELECTION_HANDLE_DRAG_STOPPED,
INSERTION_HANDLE_SHOWN,
INSERTION_HANDLE_MOVED,
INSERTION_HANDLE_TAPPED,
INSERTION_HANDLE_CLEARED,
INSERTION_HANDLE_DRAG_STARTED,
INSERTION_HANDLE_DRAG_STOPPED,
#ifdef OHOS_CLIPBOARD
SELECTION_HANDLES_UPDATEMENU,
#endif
};
} // namespace ui
#endif // UI_TOUCH_SELECTION_SELECTION_EVENT_TYPE_H_
| Zhao-PengFei35/chromium_src_4 | ui/touch_selection/selection_event_type.h | C++ | unknown | 1,014 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/touch_selection/touch_handle.h"
#include <algorithm>
#include <cmath>
#include <ostream>
#include "base/check_op.h"
#include "base/notreached.h"
namespace ui {
namespace {
// Maximum duration of a fade sequence.
constexpr auto kFadeDuration = base::Milliseconds(200);
// Maximum amount of travel for a fade sequence. This avoids handle "ghosting"
// when the handle is moving rapidly while the fade is active.
constexpr double kFadeDistanceSquared = 20.0f * 20.0f;
// Avoid using an empty touch rect, as it may fail the intersection test event
// if it lies within the other rect's bounds.
constexpr float kMinTouchMajorForHitTesting = 1.0f;
// The maximum touch size to use when computing whether a touch point is
// targetting a touch handle. This is necessary for devices that misreport
// touch radii, preventing inappropriately largely touch sizes from completely
// breaking handle dragging behavior.
constexpr float kMaxTouchMajorForHitTesting = 36.0f;
// Note that the intersection region is boundary *exclusive*.
bool RectIntersectsCircle(const gfx::RectF& rect,
const gfx::PointF& circle_center,
float circle_radius) {
DCHECK_GT(circle_radius, 0.f);
// An intersection occurs if the closest point between the rect and the
// circle's center is less than the circle's radius.
#if BUILDFLAG(IS_OHOS)
return rect.Contains(circle_center);
#else
gfx::PointF closest_point_in_rect(circle_center);
closest_point_in_rect.SetToMax(rect.origin());
closest_point_in_rect.SetToMin(rect.bottom_right());
gfx::Vector2dF distance = circle_center - closest_point_in_rect;
return distance.LengthSquared() < (circle_radius * circle_radius);
#endif
}
} // namespace
// TODO(AviD): Remove this once logging(DCHECK) supports enum class.
static std::ostream& operator<<(std::ostream& os,
const TouchHandleOrientation& orientation) {
switch (orientation) {
case TouchHandleOrientation::LEFT:
return os << "LEFT";
case TouchHandleOrientation::RIGHT:
return os << "RIGHT";
case TouchHandleOrientation::CENTER:
return os << "CENTER";
case TouchHandleOrientation::UNDEFINED:
return os << "UNDEFINED";
default:
return os << "INVALID: " << static_cast<int>(orientation);
}
}
// Responsible for rendering a selection or insertion handle for text editing.
TouchHandle::TouchHandle(TouchHandleClient* client,
TouchHandleOrientation orientation,
const gfx::RectF& viewport_rect)
: drawable_(client->CreateDrawable()),
client_(client),
viewport_rect_(viewport_rect),
orientation_(orientation),
deferred_orientation_(TouchHandleOrientation::UNDEFINED),
alpha_(0.f),
animate_deferred_fade_(false),
enabled_(true),
is_visible_(false),
is_dragging_(false),
is_drag_within_tap_region_(false),
is_handle_layout_update_required_(false),
mirror_vertical_(false),
mirror_horizontal_(false) {
DCHECK_NE(orientation, TouchHandleOrientation::UNDEFINED);
drawable_->SetEnabled(enabled_);
drawable_->SetOrientation(orientation_, false, false);
drawable_->SetOrigin(focus_bottom_);
drawable_->SetAlpha(alpha_);
handle_horizontal_padding_ = drawable_->GetDrawableHorizontalPaddingRatio();
}
TouchHandle::~TouchHandle() {}
void TouchHandle::SetEnabled(bool enabled) {
if (enabled_ == enabled)
return;
if (!enabled) {
SetVisible(false, ANIMATION_NONE);
EndDrag();
EndFade();
}
enabled_ = enabled;
drawable_->SetEnabled(enabled);
}
void TouchHandle::SetVisible(bool visible, AnimationStyle animation_style) {
DCHECK(enabled_);
if (is_visible_ == visible)
return;
is_visible_ = visible;
// Handle repositioning may have been deferred while previously invisible.
if (visible)
SetUpdateLayoutRequired();
bool animate = animation_style != ANIMATION_NONE;
if (is_dragging_) {
animate_deferred_fade_ = animate;
return;
}
if (animate)
BeginFade();
else
EndFade();
}
void TouchHandle::SetFocus(const gfx::PointF& top, const gfx::PointF& bottom) {
DCHECK(enabled_);
if (focus_top_ == top && focus_bottom_ == bottom)
return;
focus_top_ = top;
focus_bottom_ = bottom;
SetUpdateLayoutRequired();
}
void TouchHandle::SetViewportRect(const gfx::RectF& viewport_rect) {
DCHECK(enabled_);
if (viewport_rect_ == viewport_rect)
return;
viewport_rect_ = viewport_rect;
SetUpdateLayoutRequired();
}
void TouchHandle::SetOrientation(TouchHandleOrientation orientation) {
DCHECK(enabled_);
DCHECK_NE(orientation, TouchHandleOrientation::UNDEFINED);
if (is_dragging_) {
deferred_orientation_ = orientation;
return;
}
DCHECK_EQ(deferred_orientation_, TouchHandleOrientation::UNDEFINED);
if (orientation_ == orientation)
return;
orientation_ = orientation;
SetUpdateLayoutRequired();
}
bool TouchHandle::WillHandleTouchEvent(const MotionEvent& event) {
if (!enabled_)
return false;
if (!is_dragging_ && event.GetAction() != MotionEvent::Action::DOWN)
return false;
switch (event.GetAction()) {
case MotionEvent::Action::DOWN: {
if (!is_visible_)
return false;
const gfx::PointF touch_point(event.GetX(), event.GetY());
const float touch_radius =
std::clamp(event.GetTouchMajor(), kMinTouchMajorForHitTesting,
kMaxTouchMajorForHitTesting) *
0.5f;
const gfx::RectF drawable_bounds = drawable_->GetVisibleBounds();
// Only use the touch radius for targetting if the touch is at or below
// the drawable area. This makes it easier to interact with the line of
// text above the drawable.
if (touch_point.y() < drawable_bounds.y() ||
#ifdef OHOS_CLIPBOARD
!RectIntersectsCircle(drawable_bounds, touch_point, touch_radius) ||
!event.FromOverlay()) {
#else
!RectIntersectsCircle(drawable_bounds, touch_point, touch_radius)) {
#endif // #ifdef OHOS_CLIPBOARD
EndDrag();
return false;
}
touch_down_position_ = touch_point;
touch_drag_offset_ = focus_bottom_ - touch_down_position_;
touch_down_time_ = event.GetEventTime();
#ifdef OHOS_CLIPBOARD
if (orientation_ == TouchHandleOrientation::LEFT) {
touch_drag_offset_ = focus_bottom_ - touch_down_position_;
}
#endif
BeginDrag();
} break;
case MotionEvent::Action::MOVE: {
gfx::PointF touch_move_position(event.GetX(), event.GetY());
is_drag_within_tap_region_ &=
client_->IsWithinTapSlop(touch_down_position_ - touch_move_position);
// Note that we signal drag update even if we're inside the tap region,
// as there are cases where characters are narrower than the slop length.
client_->OnDragUpdate(*this, touch_move_position + touch_drag_offset_);
} break;
case MotionEvent::Action::UP: {
if (is_drag_within_tap_region_ &&
(event.GetEventTime() - touch_down_time_) <
client_->GetMaxTapDuration()) {
client_->OnHandleTapped(*this);
}
EndDrag();
} break;
case MotionEvent::Action::CANCEL:
EndDrag();
break;
default:
break;
};
return true;
}
bool TouchHandle::IsActive() const {
return is_dragging_;
}
bool TouchHandle::Animate(base::TimeTicks frame_time) {
if (fade_end_time_ == base::TimeTicks())
return false;
DCHECK(enabled_);
const float time_u = 1.0f - (fade_end_time_ - frame_time) / kFadeDuration;
const float position_u =
(focus_bottom_ - fade_start_position_).LengthSquared() /
kFadeDistanceSquared;
const float u = std::max(time_u, position_u);
SetAlpha(is_visible_ ? u : 1.0f - u);
if (u >= 1)
EndFade();
return u < 1;
}
gfx::RectF TouchHandle::GetVisibleBounds() const {
if (!is_visible_ || !enabled_)
return gfx::RectF();
return drawable_->GetVisibleBounds();
}
#if BUILDFLAG(IS_OHOS)
void TouchHandle::SetEdge(const gfx::PointF& top, const gfx::PointF& bottom) {
drawable_->SetEdge(top, bottom);
}
#endif
void TouchHandle::UpdateHandleLayout() {
// Suppress repositioning a handle while invisible or fading out to prevent it
// from "ghosting" outside the visible bounds. The position will be pushed to
// the drawable when the handle regains visibility (see |SetVisible()|).
if (!is_visible_ || !is_handle_layout_update_required_)
return;
is_handle_layout_update_required_ = false;
// Update mirror values only when dragging has stopped to prevent unwanted
// inversion while dragging of handles.
if (!is_dragging_) {
gfx::RectF handle_bounds = drawable_->GetVisibleBounds();
bool mirror_horizontal = false;
bool mirror_vertical = false;
const float handle_width =
handle_bounds.width() * (1.0 - handle_horizontal_padding_);
const float handle_height = handle_bounds.height();
const float bottom_y_unmirrored =
focus_bottom_.y() + handle_height + viewport_rect_.y();
const float top_y_mirrored =
focus_top_.y() - handle_height + viewport_rect_.y();
const float bottom_y_clipped =
std::max(bottom_y_unmirrored - viewport_rect_.bottom(), 0.f);
const float top_y_clipped =
std::max(viewport_rect_.y() - top_y_mirrored, 0.f);
mirror_vertical = top_y_clipped < bottom_y_clipped;
if (orientation_ == TouchHandleOrientation::LEFT) {
const float left_x_clipped = std::max(
viewport_rect_.x() - (focus_bottom_.x() - handle_width), 0.f);
if (left_x_clipped > 0)
mirror_horizontal = true;
} else if (orientation_ == TouchHandleOrientation::RIGHT) {
const float right_x_clipped = std::max(
(focus_bottom_.x() + handle_width) - viewport_rect_.right(), 0.f);
if (right_x_clipped > 0)
mirror_horizontal = true;
}
if (client_->IsAdaptiveHandleOrientationEnabled()) {
mirror_horizontal_ = mirror_horizontal;
mirror_vertical_ = mirror_vertical;
}
}
drawable_->SetOrientation(orientation_, mirror_vertical_, mirror_horizontal_);
#if BUILDFLAG(IS_OHOS)
drawable_->SetEdge(focus_top_, focus_bottom_);
#endif
drawable_->SetOrigin(ComputeHandleOrigin());
}
#ifdef OHOS_CLIPBOARD
void TouchHandle::ResetPositionAfterDragEnd() {
if (!is_visible_ || !drawable_) {
return;
}
drawable_->SetOrigin(ComputeHandleOrigin());
}
#endif
void TouchHandle::SetTransparent() {
SetAlpha(0.f);
}
gfx::PointF TouchHandle::ComputeHandleOrigin() const {
gfx::PointF focus = mirror_vertical_ ? focus_top_ : focus_bottom_;
gfx::RectF drawable_bounds = drawable_->GetVisibleBounds();
float drawable_width = drawable_->GetVisibleBounds().width();
// Calculate the focal offsets from origin for the handle drawable
// based on the orientation.
int focal_offset_x = 0;
int focal_offset_y = mirror_vertical_ ? drawable_bounds.height() : 0;
switch (orientation_) {
case ui::TouchHandleOrientation::LEFT:
#if BUILDFLAG(IS_OHOS)
focal_offset_x =
mirror_horizontal_
? drawable_width * (1.0f - handle_horizontal_padding_)
: drawable_width * handle_horizontal_padding_;
#else
focal_offset_x =
mirror_horizontal_
? drawable_width * handle_horizontal_padding_
: drawable_width * (1.0f - handle_horizontal_padding_);
#endif
break;
case ui::TouchHandleOrientation::RIGHT:
focal_offset_x =
mirror_horizontal_
? drawable_width * (1.0f - handle_horizontal_padding_)
: drawable_width * handle_horizontal_padding_;
break;
case ui::TouchHandleOrientation::CENTER:
#if BUILDFLAG(IS_OHOS)
focal_offset_x =
mirror_horizontal_
? drawable_width * (1.0f - handle_horizontal_padding_)
: drawable_width * handle_horizontal_padding_;
#else
focal_offset_x = drawable_width * 0.5f;
#endif
break;
case ui::TouchHandleOrientation::UNDEFINED:
NOTREACHED() << "Invalid touch handle orientation.";
break;
};
return focus - gfx::Vector2dF(focal_offset_x, focal_offset_y);
}
void TouchHandle::BeginDrag() {
DCHECK(enabled_);
if (is_dragging_)
return;
EndFade();
is_dragging_ = true;
is_drag_within_tap_region_ = true;
client_->OnDragBegin(*this, focus_bottom());
}
void TouchHandle::EndDrag() {
DCHECK(enabled_);
if (!is_dragging_)
return;
is_dragging_ = false;
is_drag_within_tap_region_ = false;
client_->OnDragEnd(*this);
if (deferred_orientation_ != TouchHandleOrientation::UNDEFINED) {
TouchHandleOrientation deferred_orientation = deferred_orientation_;
deferred_orientation_ = TouchHandleOrientation::UNDEFINED;
SetOrientation(deferred_orientation);
// Handle layout may be deferred while the handle is dragged.
SetUpdateLayoutRequired();
UpdateHandleLayout();
}
if (animate_deferred_fade_) {
BeginFade();
} else {
// As drawable visibility assignment is deferred while dragging, push the
// change by forcing fade completion.
EndFade();
}
}
void TouchHandle::BeginFade() {
DCHECK(enabled_);
DCHECK(!is_dragging_);
animate_deferred_fade_ = false;
const float target_alpha = is_visible_ ? 1.f : 0.f;
if (target_alpha == alpha_) {
EndFade();
return;
}
fade_end_time_ =
base::TimeTicks::Now() + kFadeDuration * std::abs(target_alpha - alpha_);
fade_start_position_ = focus_bottom_;
client_->SetNeedsAnimate();
}
void TouchHandle::EndFade() {
DCHECK(enabled_);
animate_deferred_fade_ = false;
fade_end_time_ = base::TimeTicks();
SetAlpha(is_visible_ ? 1.f : 0.f);
}
void TouchHandle::SetAlpha(float alpha) {
alpha = std::clamp(alpha, 0.0f, 1.0f);
if (alpha_ == alpha)
return;
alpha_ = alpha;
drawable_->SetAlpha(alpha);
}
void TouchHandle::SetUpdateLayoutRequired() {
// TODO(AviD): Make the layout call explicit to the caller by adding this in
// TouchHandleClient.
is_handle_layout_update_required_ = true;
}
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/touch_selection/touch_handle.cc | C++ | unknown | 14,288 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_TOUCH_SELECTION_TOUCH_HANDLE_H_
#define UI_TOUCH_SELECTION_TOUCH_HANDLE_H_
#include <memory>
#include "base/memory/raw_ptr.h"
#include "base/time/time.h"
#include "ui/events/gesture_detection/motion_event.h"
#include "ui/gfx/geometry/point_f.h"
#include "ui/gfx/geometry/rect_f.h"
#include "ui/gfx/geometry/vector2d_f.h"
#include "ui/touch_selection/touch_handle_orientation.h"
#include "ui/touch_selection/touch_selection_draggable.h"
#include "ui/touch_selection/ui_touch_selection_export.h"
namespace ui {
class TouchHandle;
// Interface through which |TouchHandle| delegates rendering-specific duties.
class UI_TOUCH_SELECTION_EXPORT TouchHandleDrawable {
public:
virtual ~TouchHandleDrawable() {}
// Sets whether the handle is active, allowing resource cleanup if necessary.
virtual void SetEnabled(bool enabled) = 0;
// Update the handle visuals to |orientation|.
// |mirror_vertical| and |mirror_horizontal| are used to invert the drawables
// if required for adaptive handle orientation.
virtual void SetOrientation(ui::TouchHandleOrientation orientation,
bool mirror_vertical,
bool mirror_horizontal) = 0;
// Sets the origin position of the touch handle.
// |origin| takes care of positioning the handle drawable based on
// its visible bounds.
virtual void SetOrigin(const gfx::PointF& origin) = 0;
// Sets the transparency |alpha| for the handle drawable.
virtual void SetAlpha(float alpha) = 0;
// Returns the visible bounds of the handle drawable.
// The bounds includes the transparent horizontal padding.
virtual gfx::RectF GetVisibleBounds() const = 0;
// Returns the transparent horizontal padding ratio of the handle drawable.
virtual float GetDrawableHorizontalPaddingRatio() const = 0;
#if BUILDFLAG(IS_OHOS)
// Sets the Selection left-handle-start or right-handle-end's edge.
virtual void SetEdge(const gfx::PointF& top, const gfx::PointF& bottom) = 0;
#endif
};
// Interface through which |TouchHandle| communicates handle manipulation and
// requests concrete drawable instances.
class UI_TOUCH_SELECTION_EXPORT TouchHandleClient
: public TouchSelectionDraggableClient {
public:
~TouchHandleClient() override {}
virtual void OnHandleTapped(const TouchHandle& handle) = 0;
virtual void SetNeedsAnimate() = 0;
virtual std::unique_ptr<TouchHandleDrawable> CreateDrawable() = 0;
virtual base::TimeDelta GetMaxTapDuration() const = 0;
virtual bool IsAdaptiveHandleOrientationEnabled() const = 0;
};
// Responsible for displaying a selection or insertion handle for text
// interaction.
class UI_TOUCH_SELECTION_EXPORT TouchHandle : public TouchSelectionDraggable {
public:
// The drawable will be enabled but invisible until otherwise specified.
TouchHandle(TouchHandleClient* client,
TouchHandleOrientation orientation,
const gfx::RectF& viewport_rect);
TouchHandle(const TouchHandle&) = delete;
TouchHandle& operator=(const TouchHandle&) = delete;
~TouchHandle() override;
// TouchSelectionDraggable implementation.
bool WillHandleTouchEvent(const MotionEvent& event) override;
bool IsActive() const override;
// Sets whether the handle is active, allowing resource cleanup if necessary.
// If false, active animations or touch drag sequences will be cancelled.
// While disabled, manipulation is *explicitly not supported*, and may lead to
// undesirable and/or unstable side-effects. The handle can be safely
// re-enabled to allow continued operation.
void SetEnabled(bool enabled);
enum AnimationStyle { ANIMATION_NONE, ANIMATION_SMOOTH };
// Update the handle visibility, fading in/out according to |animation_style|.
// If an animation is in-progress, it will be overriden appropriately.
void SetVisible(bool visible, AnimationStyle animation_style);
// Update the focus points for the handles. The handle will be positioned
// either |top| or |bottom| based on the mirror parameters.
// Note: If a fade out animation is active or the handle is invisible, the
// handle position will not be updated until the handle regains visibility.
void SetFocus(const gfx::PointF& top, const gfx::PointF& bottom);
// Update the viewport rect, based on which the handle decide its inversion.
void SetViewportRect(const gfx::RectF& viewport_rect);
// Update the handle visuals to |orientation|.
// Note: If the handle is being dragged, the orientation change will be
// deferred until the drag has ceased.
void SetOrientation(TouchHandleOrientation orientation);
// Ticks an active animation, as requested to the client by |SetNeedsAnimate|.
// Returns true if an animation is active and requires further ticking.
bool Animate(base::TimeTicks frame_time);
// Get the visible bounds of the handle, based on the current position and
// the drawable's size/orientation. If the handle is invisible or disabled,
// the bounds will be empty.
gfx::RectF GetVisibleBounds() const;
// Updates the handle layout if the is_handle_layout_update_required_ flag is
// set. Will be called once per frame update, avoids multiple updates for
// for the same frame update due to more than one parameter updates.
void UpdateHandleLayout();
// Set the handle to transparent. Handle will be set to opaque again in
// EndDrag() call.
void SetTransparent();
const gfx::PointF& focus_bottom() const { return focus_bottom_; }
TouchHandleOrientation orientation() const { return orientation_; }
float alpha() const { return alpha_; }
#if BUILDFLAG(IS_OHOS)
void SetEdge(const gfx::PointF& top, const gfx::PointF& bottom);
const gfx::PointF& focus_top() const { return focus_top_; }
bool GetEnabled() const { return enabled_; }
#endif
#ifdef OHOS_CLIPBOARD
void ResetPositionAfterDragEnd();
#endif
#ifdef OHOS_EX_TOPCONTROLS
const gfx::RectF& viewport() const { return viewport_rect_; }
#endif
private:
gfx::PointF ComputeHandleOrigin() const;
void BeginDrag();
void EndDrag();
void BeginFade();
void EndFade();
void SetAlpha(float alpha);
void SetUpdateLayoutRequired();
std::unique_ptr<TouchHandleDrawable> drawable_;
const raw_ptr<TouchHandleClient> client_;
gfx::PointF focus_bottom_;
gfx::PointF focus_top_;
gfx::RectF viewport_rect_;
TouchHandleOrientation orientation_;
TouchHandleOrientation deferred_orientation_;
gfx::PointF touch_down_position_;
gfx::Vector2dF touch_drag_offset_;
base::TimeTicks touch_down_time_;
// Note that when a fade animation is active, |is_visible_| and |position_|
// may not reflect the actual visibility and position of the drawable. This
// discrepancy is resolved either upon fade completion or cancellation.
base::TimeTicks fade_end_time_;
gfx::PointF fade_start_position_;
float alpha_;
bool animate_deferred_fade_;
bool enabled_;
bool is_visible_;
bool is_dragging_;
bool is_drag_within_tap_region_;
bool is_handle_layout_update_required_;
// Mirror variables determine if the handles should be inverted or not.
bool mirror_vertical_;
bool mirror_horizontal_;
float handle_horizontal_padding_;
};
} // namespace ui
#endif // UI_TOUCH_SELECTION_TOUCH_HANDLE_H_
| Zhao-PengFei35/chromium_src_4 | ui/touch_selection/touch_handle.h | C++ | unknown | 7,402 |
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/touch_selection/touch_handle_drawable_aura.h"
#include "ui/aura/window.h"
#include "ui/aura/window_targeter.h"
#include "ui/aura_extra/image_window_delegate.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/hit_test.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/compositor/layer.h"
#include "ui/events/event.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/geometry/rect_conversions.h"
#include "ui/resources/grit/ui_resources.h"
namespace ui {
namespace {
// The distance by which a handle image is offset from the focal point (i.e.
// text baseline) downwards.
const int kSelectionHandleVerticalVisualOffset = 2;
// The padding around the selection handle image can be used to extend the
// handle window so that touch events near the selection handle image are
// targeted to the selection handle window.
const int kSelectionHandlePadding = 0;
// Epsilon value used to compare float values to zero.
const float kEpsilon = 1e-8f;
// Returns the appropriate handle image based on the handle orientation.
gfx::Image* GetHandleImage(TouchHandleOrientation orientation) {
int resource_id = 0;
switch (orientation) {
case TouchHandleOrientation::LEFT:
resource_id = IDR_TEXT_SELECTION_HANDLE_LEFT;
break;
case TouchHandleOrientation::CENTER:
resource_id = IDR_TEXT_SELECTION_HANDLE_CENTER;
break;
case TouchHandleOrientation::RIGHT:
resource_id = IDR_TEXT_SELECTION_HANDLE_RIGHT;
break;
case TouchHandleOrientation::UNDEFINED:
NOTREACHED() << "Invalid touch handle bound type.";
return nullptr;
};
return &ResourceBundle::GetSharedInstance().GetImageNamed(resource_id);
}
bool IsNearlyZero(float value) {
return std::abs(value) < kEpsilon;
}
} // namespace
TouchHandleDrawableAura::TouchHandleDrawableAura(aura::Window* parent)
: window_(
std::make_unique<aura::Window>(new aura_extra::ImageWindowDelegate)),
window_delegate_(
static_cast<aura_extra::ImageWindowDelegate*>(window_->delegate())),
enabled_(false),
alpha_(0),
orientation_(TouchHandleOrientation::UNDEFINED) {
window_delegate_->set_image_offset(gfx::Vector2d(kSelectionHandlePadding,
kSelectionHandlePadding));
window_->SetTransparent(true);
window_->Init(LAYER_TEXTURED);
window_->set_owned_by_parent(false);
window_->SetEventTargetingPolicy(aura::EventTargetingPolicy::kNone);
parent->AddChild(window_.get());
}
TouchHandleDrawableAura::~TouchHandleDrawableAura() {
}
void TouchHandleDrawableAura::UpdateBounds() {
gfx::RectF new_bounds = relative_bounds_;
new_bounds.Offset(origin_position_.x(), origin_position_.y());
window_->SetBounds(gfx::ToEnclosingRect(new_bounds));
}
bool TouchHandleDrawableAura::IsVisible() const {
return enabled_ && !IsNearlyZero(alpha_);
}
void TouchHandleDrawableAura::SetEnabled(bool enabled) {
if (enabled == enabled_)
return;
enabled_ = enabled;
if (IsVisible())
window_->Show();
else
window_->Hide();
}
void TouchHandleDrawableAura::SetOrientation(TouchHandleOrientation orientation,
bool mirror_vertical,
bool mirror_horizontal) {
// TODO(AviD): Implement adaptive handle orientation logic for Aura
DCHECK(window_delegate_);
DCHECK(!mirror_vertical);
DCHECK(!mirror_horizontal);
if (orientation_ == orientation)
return;
orientation_ = orientation;
gfx::Image* image = GetHandleImage(orientation);
window_delegate_->SetImage(*image);
// Calculate the relative bounds.
gfx::Size image_size = image->Size();
int window_width = image_size.width() + 2 * kSelectionHandlePadding;
int window_height = image_size.height() + 2 * kSelectionHandlePadding;
relative_bounds_ =
gfx::RectF(-kSelectionHandlePadding,
kSelectionHandleVerticalVisualOffset - kSelectionHandlePadding,
window_width, window_height);
gfx::Rect paint_bounds(relative_bounds_.x(), relative_bounds_.y(),
relative_bounds_.width(), relative_bounds_.height());
window_->SchedulePaintInRect(paint_bounds);
UpdateBounds();
}
void TouchHandleDrawableAura::SetOrigin(const gfx::PointF& position) {
origin_position_ = position;
UpdateBounds();
}
void TouchHandleDrawableAura::SetAlpha(float alpha) {
if (alpha == alpha_)
return;
alpha_ = alpha;
window_->layer()->SetOpacity(alpha_);
if (IsVisible())
window_->Show();
else
window_->Hide();
}
gfx::RectF TouchHandleDrawableAura::GetVisibleBounds() const {
gfx::RectF bounds(window_->bounds());
bounds.Inset(gfx::InsetsF::TLBR(
kSelectionHandlePadding + kSelectionHandleVerticalVisualOffset,
kSelectionHandlePadding, kSelectionHandlePadding,
kSelectionHandlePadding));
return bounds;
}
float TouchHandleDrawableAura::GetDrawableHorizontalPaddingRatio() const {
// Aura does not have any transparent padding for its handle drawable.
return 0.0f;
}
#if BUILDFLAG(IS_OHOS)
void TouchHandleDrawableAura::SetEdge(const gfx::PointF& top,
const gfx::PointF& bottom) {}
#endif
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/touch_selection/touch_handle_drawable_aura.cc | C++ | unknown | 5,382 |
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_TOUCH_SELECTION_TOUCH_HANDLE_DRAWABLE_AURA_H_
#define UI_TOUCH_SELECTION_TOUCH_HANDLE_DRAWABLE_AURA_H_
#include "base/memory/raw_ptr.h"
#include "ui/touch_selection/touch_handle.h"
#include "ui/touch_selection/touch_handle_orientation.h"
#include "ui/touch_selection/ui_touch_selection_export.h"
namespace aura {
class Window;
}
namespace aura_extra {
class ImageWindowDelegate;
}
namespace ui {
class UI_TOUCH_SELECTION_EXPORT TouchHandleDrawableAura
: public TouchHandleDrawable {
public:
explicit TouchHandleDrawableAura(aura::Window* parent);
TouchHandleDrawableAura(const TouchHandleDrawableAura&) = delete;
TouchHandleDrawableAura& operator=(const TouchHandleDrawableAura&) = delete;
~TouchHandleDrawableAura() override;
private:
void UpdateBounds();
bool IsVisible() const;
// TouchHandleDrawable:
void SetEnabled(bool enabled) override;
void SetOrientation(TouchHandleOrientation orientation,
bool mirror_vertical,
bool mirror_horizontal) override;
void SetOrigin(const gfx::PointF& position) override;
void SetAlpha(float alpha) override;
gfx::RectF GetVisibleBounds() const override;
float GetDrawableHorizontalPaddingRatio() const override;
#if BUILDFLAG(IS_OHOS)
void SetEdge(const gfx::PointF& top, const gfx::PointF& bottom) override;
#endif
std::unique_ptr<aura::Window> window_;
// `window_delegate_` self destroys when`OnWindowDestroyed()` is invoked
// during the destruction of `window_`. It must be declared last and cleared
// first to avoid holding a ptr to freed memory.
raw_ptr<aura_extra::ImageWindowDelegate> window_delegate_;
bool enabled_;
float alpha_;
ui::TouchHandleOrientation orientation_;
// Origin position of the handle set via SetOrigin, in coordinate space of
// selection controller client (i.e. handle's parent).
gfx::PointF origin_position_;
// Window bounds relative to the focal position.
gfx::RectF relative_bounds_;
};
} // namespace ui
#endif // UI_TOUCH_SELECTION_TOUCH_HANDLE_DRAWABLE_AURA_H_
| Zhao-PengFei35/chromium_src_4 | ui/touch_selection/touch_handle_drawable_aura.h | C++ | unknown | 2,217 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_TOUCH_SELECTION_TOUCH_HANDLE_ORIENTATION_H_
#define UI_TOUCH_SELECTION_TOUCH_HANDLE_ORIENTATION_H_
namespace ui {
// Orientation types for Touch handles, used for setting the type of
// handle orientation on java and native side.
// A Java counterpart will be generated for this enum.
// GENERATED_JAVA_ENUM_PACKAGE: org.chromium.ui.touch_selection
enum class TouchHandleOrientation {
LEFT,
CENTER,
RIGHT,
UNDEFINED,
};
} // namespace ui
#endif // UI_TOUCH_SELECTION_TOUCH_HANDLE_ORIENTATION_H_
| Zhao-PengFei35/chromium_src_4 | ui/touch_selection/touch_handle_orientation.h | C++ | unknown | 665 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/touch_selection/touch_handle.h"
#include "base/memory/raw_ptr.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/events/test/motion_event_test_utils.h"
#include "ui/gfx/geometry/rect_f.h"
#include "ui/touch_selection/touch_handle_orientation.h"
using ui::test::MockMotionEvent;
namespace ui {
namespace {
const int kDefaultTapDurationMs = 200;
const double kDefaultTapSlop = 10.;
const float kDefaultDrawableSize = 10.f;
const gfx::RectF kDefaultViewportRect(0, 0, 560, 1200);
struct MockDrawableData {
TouchHandleOrientation orientation = TouchHandleOrientation::UNDEFINED;
float alpha = 0.f;
bool mirror_horizontal = false;
bool mirror_vertical = false;
bool enabled = false;
bool visible = false;
gfx::RectF rect{0, 0, kDefaultDrawableSize, kDefaultDrawableSize};
};
class MockTouchHandleDrawable : public TouchHandleDrawable {
public:
explicit MockTouchHandleDrawable(MockDrawableData* data) : data_(data) {}
~MockTouchHandleDrawable() override {}
void SetEnabled(bool enabled) override { data_->enabled = enabled; }
void SetOrientation(TouchHandleOrientation orientation,
bool mirror_vertical,
bool mirror_horizontal) override {
data_->orientation = orientation;
data_->mirror_horizontal = mirror_horizontal;
data_->mirror_vertical = mirror_vertical;
}
void SetOrigin(const gfx::PointF& origin) override {
data_->rect.set_origin(origin);
}
void SetAlpha(float alpha) override {
data_->alpha = alpha;
data_->visible = alpha > 0;
}
// TODO(AviD): Add unittests for non-zero values of padding ratio once the
// code refactoring is completed.
float GetDrawableHorizontalPaddingRatio() const override { return 0; }
gfx::RectF GetVisibleBounds() const override { return data_->rect; }
#if defined(OHOS_UNITTESTS)
void SetEdge(const gfx::PointF& top, const gfx::PointF& bottom) override {}
#endif
private:
raw_ptr<MockDrawableData> data_;
};
} // namespace
class TouchHandleTest : public testing::Test, public TouchHandleClient {
public:
TouchHandleTest()
: dragging_(false),
dragged_(false),
tapped_(false),
needs_animate_(false) {}
~TouchHandleTest() override {}
// TouchHandleClient implementation.
void OnDragBegin(const TouchSelectionDraggable& handler,
const gfx::PointF& drag_position) override {
dragging_ = true;
}
void OnDragUpdate(const TouchSelectionDraggable& handler,
const gfx::PointF& drag_position) override {
dragged_ = true;
drag_position_ = drag_position;
}
void OnDragEnd(const TouchSelectionDraggable& handler) override {
dragging_ = false;
}
bool IsWithinTapSlop(const gfx::Vector2dF& delta) const override {
return delta.LengthSquared() < (kDefaultTapSlop * kDefaultTapSlop);
}
void OnHandleTapped(const TouchHandle& handle) override { tapped_ = true; }
void SetNeedsAnimate() override { needs_animate_ = true; }
std::unique_ptr<TouchHandleDrawable> CreateDrawable() override {
return std::make_unique<MockTouchHandleDrawable>(&drawable_data_);
}
base::TimeDelta GetMaxTapDuration() const override {
return base::Milliseconds(kDefaultTapDurationMs);
}
bool IsAdaptiveHandleOrientationEnabled() const override {
// Enable adaptive handle orientation by default for unittests
return true;
}
void Animate(TouchHandle& handle) {
needs_animate_ = false;
base::TimeTicks now = base::TimeTicks::Now();
while (handle.Animate(now))
now += base::Milliseconds(16);
}
bool GetAndResetHandleDragged() {
bool dragged = dragged_;
dragged_ = false;
return dragged;
}
bool GetAndResetHandleTapped() {
bool tapped = tapped_;
tapped_ = false;
return tapped;
}
bool GetAndResetNeedsAnimate() {
bool needs_animate = needs_animate_;
needs_animate_ = false;
return needs_animate;
}
void UpdateHandleFocus(TouchHandle& handle,
gfx::PointF& top,
gfx::PointF& bottom) {
handle.SetFocus(top, bottom);
handle.UpdateHandleLayout();
}
void UpdateHandleOrientation(TouchHandle& handle,
TouchHandleOrientation orientation) {
handle.SetOrientation(orientation);
handle.UpdateHandleLayout();
}
void UpdateHandleVisibility(TouchHandle& handle,
bool visible,
TouchHandle::AnimationStyle animation_style) {
handle.SetVisible(visible, animation_style);
handle.UpdateHandleLayout();
}
void UpdateViewportRect(TouchHandle& handle, gfx::RectF viewport_rect) {
handle.SetViewportRect(viewport_rect);
handle.UpdateHandleLayout();
}
bool IsDragging() const { return dragging_; }
const gfx::PointF& DragPosition() const { return drag_position_; }
bool NeedsAnimate() const { return needs_animate_; }
const MockDrawableData& drawable() { return drawable_data_; }
#if defined(OHOS_UNITTESTS)
void UpdateSelectionChanged(const TouchSelectionDraggable& draggable) override {}
#endif // OHOS_UNITTESTS
private:
gfx::PointF drag_position_;
bool dragging_;
bool dragged_;
bool tapped_;
bool needs_animate_;
MockDrawableData drawable_data_;
};
TEST_F(TouchHandleTest, Visibility) {
TouchHandle handle(this, TouchHandleOrientation::CENTER,
kDefaultViewportRect);
EXPECT_FALSE(drawable().visible);
UpdateHandleVisibility(handle, true, TouchHandle::ANIMATION_NONE);
EXPECT_TRUE(drawable().visible);
EXPECT_EQ(1.f, drawable().alpha);
UpdateHandleVisibility(handle, false, TouchHandle::ANIMATION_NONE);
EXPECT_FALSE(drawable().visible);
UpdateHandleVisibility(handle, true, TouchHandle::ANIMATION_NONE);
EXPECT_TRUE(drawable().visible);
EXPECT_EQ(1.f, drawable().alpha);
}
TEST_F(TouchHandleTest, VisibilityAnimation) {
TouchHandle handle(this, TouchHandleOrientation::CENTER,
kDefaultViewportRect);
ASSERT_FALSE(NeedsAnimate());
ASSERT_FALSE(drawable().visible);
ASSERT_EQ(0.f, drawable().alpha);
UpdateHandleVisibility(handle, true, TouchHandle::ANIMATION_SMOOTH);
EXPECT_TRUE(NeedsAnimate());
EXPECT_FALSE(drawable().visible);
EXPECT_EQ(0.f, drawable().alpha);
Animate(handle);
EXPECT_TRUE(drawable().visible);
EXPECT_EQ(1.f, drawable().alpha);
ASSERT_FALSE(NeedsAnimate());
UpdateHandleVisibility(handle, false, TouchHandle::ANIMATION_SMOOTH);
EXPECT_TRUE(NeedsAnimate());
EXPECT_TRUE(drawable().visible);
EXPECT_EQ(1.f, drawable().alpha);
Animate(handle);
EXPECT_FALSE(drawable().visible);
EXPECT_EQ(0.f, drawable().alpha);
UpdateHandleVisibility(handle, true, TouchHandle::ANIMATION_NONE);
EXPECT_EQ(1.f, drawable().alpha);
EXPECT_FALSE(GetAndResetNeedsAnimate());
UpdateHandleVisibility(handle, false, TouchHandle::ANIMATION_SMOOTH);
EXPECT_EQ(1.f, drawable().alpha);
EXPECT_TRUE(GetAndResetNeedsAnimate());
UpdateHandleVisibility(handle, true, TouchHandle::ANIMATION_SMOOTH);
EXPECT_EQ(1.f, drawable().alpha);
EXPECT_FALSE(GetAndResetNeedsAnimate());
}
TEST_F(TouchHandleTest, Orientation) {
TouchHandle handle(this, TouchHandleOrientation::CENTER,
kDefaultViewportRect);
EXPECT_EQ(TouchHandleOrientation::CENTER, drawable().orientation);
UpdateHandleVisibility(handle, true, TouchHandle::ANIMATION_NONE);
UpdateHandleOrientation(handle, TouchHandleOrientation::LEFT);
EXPECT_EQ(TouchHandleOrientation::LEFT, drawable().orientation);
UpdateHandleOrientation(handle, TouchHandleOrientation::RIGHT);
EXPECT_EQ(TouchHandleOrientation::RIGHT, drawable().orientation);
UpdateHandleOrientation(handle, TouchHandleOrientation::CENTER);
EXPECT_EQ(TouchHandleOrientation::CENTER, drawable().orientation);
}
TEST_F(TouchHandleTest, Position) {
TouchHandle handle(this, TouchHandleOrientation::CENTER,
kDefaultViewportRect);
UpdateHandleVisibility(handle, true, TouchHandle::ANIMATION_NONE);
const gfx::Vector2dF koffset_vector(kDefaultDrawableSize / 2.f, 0);
gfx::PointF focus_top;
gfx::PointF focus_bottom;
EXPECT_EQ(gfx::PointF() - koffset_vector, drawable().rect.origin());
focus_top = gfx::PointF(7.3f, -3.7f);
focus_bottom = gfx::PointF(7.3f, -2.7f);
UpdateHandleFocus(handle, focus_top, focus_bottom);
EXPECT_EQ(focus_bottom - koffset_vector, drawable().rect.origin());
focus_top = gfx::PointF(-7.3f, 3.7f);
focus_bottom = gfx::PointF(-7.3f, 4.7f);
UpdateHandleFocus(handle, focus_top, focus_bottom);
EXPECT_EQ(focus_bottom - koffset_vector, drawable().rect.origin());
}
TEST_F(TouchHandleTest, PositionNotUpdatedWhileFadingOrInvisible) {
TouchHandle handle(this, TouchHandleOrientation::CENTER,
kDefaultViewportRect);
UpdateHandleVisibility(handle, true, TouchHandle::ANIMATION_NONE);
ASSERT_TRUE(drawable().visible);
ASSERT_FALSE(NeedsAnimate());
const gfx::Vector2dF koffset_vector(kDefaultDrawableSize / 2.f, 0);
gfx::PointF old_focus_top(7.3f, -3.7f);
gfx::PointF old_focus_bottom(7.3f, -2.7f);
UpdateHandleFocus(handle, old_focus_top, old_focus_bottom);
ASSERT_EQ(old_focus_bottom - koffset_vector, drawable().rect.origin());
UpdateHandleVisibility(handle, false, TouchHandle::ANIMATION_SMOOTH);
ASSERT_TRUE(NeedsAnimate());
gfx::PointF new_position_top(3.7f, -3.7f);
gfx::PointF new_position_bottom(3.7f, -2.7f);
UpdateHandleFocus(handle, new_position_top, new_position_bottom);
EXPECT_EQ(old_focus_bottom - koffset_vector, drawable().rect.origin());
EXPECT_TRUE(NeedsAnimate());
// While the handle is fading, the new position should not take affect.
base::TimeTicks now = base::TimeTicks::Now();
while (handle.Animate(now)) {
EXPECT_EQ(old_focus_bottom - koffset_vector, drawable().rect.origin());
now += base::Milliseconds(16);
}
// Even after the animation terminates, the new position will not be pushed.
EXPECT_EQ(old_focus_bottom - koffset_vector, drawable().rect.origin());
// As soon as the handle becomes visible, the new position will be pushed.
UpdateHandleVisibility(handle, true, TouchHandle::ANIMATION_SMOOTH);
EXPECT_EQ(new_position_bottom - koffset_vector, drawable().rect.origin());
}
TEST_F(TouchHandleTest, Enabled) {
// A newly created handle defaults to enabled.
TouchHandle handle(this, TouchHandleOrientation::CENTER,
kDefaultViewportRect);
EXPECT_TRUE(drawable().enabled);
UpdateHandleVisibility(handle, true, TouchHandle::ANIMATION_SMOOTH);
EXPECT_TRUE(GetAndResetNeedsAnimate());
EXPECT_EQ(0.f, drawable().alpha);
handle.SetEnabled(false);
EXPECT_FALSE(drawable().enabled);
// Dragging should not be allowed while the handle is disabled.
base::TimeTicks event_time = base::TimeTicks::Now();
const float kOffset = kDefaultDrawableSize / 2.f;
MockMotionEvent event(MockMotionEvent::Action::DOWN, event_time, kOffset,
kOffset);
EXPECT_FALSE(handle.WillHandleTouchEvent(event));
// Disabling mid-animation should cancel the animation.
handle.SetEnabled(true);
UpdateHandleVisibility(handle, true, TouchHandle::ANIMATION_SMOOTH);
EXPECT_TRUE(drawable().enabled);
EXPECT_EQ(0.f, drawable().alpha);
// Since alpha value is 0, visibility of drawable will be false.
EXPECT_FALSE(drawable().visible);
EXPECT_TRUE(GetAndResetNeedsAnimate());
handle.SetEnabled(false);
EXPECT_FALSE(drawable().enabled);
EXPECT_FALSE(drawable().visible);
EXPECT_FALSE(handle.Animate(base::TimeTicks::Now()));
// Disabling mid-drag should cancel the drag.
handle.SetEnabled(true);
UpdateHandleVisibility(handle, true, TouchHandle::ANIMATION_NONE);
EXPECT_TRUE(handle.WillHandleTouchEvent(event));
EXPECT_TRUE(IsDragging());
handle.SetEnabled(false);
EXPECT_FALSE(IsDragging());
EXPECT_FALSE(handle.WillHandleTouchEvent(event));
}
TEST_F(TouchHandleTest, Drag) {
TouchHandle handle(this, TouchHandleOrientation::CENTER,
kDefaultViewportRect);
base::TimeTicks event_time = base::TimeTicks::Now();
const float kOffset = kDefaultDrawableSize / 2.f;
// The handle must be visible to trigger drag.
MockMotionEvent event(MockMotionEvent::Action::DOWN, event_time, kOffset,
kOffset);
EXPECT_FALSE(handle.WillHandleTouchEvent(event));
EXPECT_FALSE(IsDragging());
UpdateHandleVisibility(handle, true, TouchHandle::ANIMATION_NONE);
// Action::DOWN must fall within the drawable region to trigger drag.
event = MockMotionEvent(MockMotionEvent::Action::DOWN, event_time, 50, 50);
EXPECT_FALSE(handle.WillHandleTouchEvent(event));
EXPECT_FALSE(IsDragging());
// Only Action::DOWN will trigger drag.
event = MockMotionEvent(MockMotionEvent::Action::MOVE, event_time, kOffset,
kOffset);
EXPECT_FALSE(handle.WillHandleTouchEvent(event));
EXPECT_FALSE(IsDragging());
// Start the drag.
event = MockMotionEvent(MockMotionEvent::Action::DOWN, event_time, kOffset,
kOffset);
EXPECT_TRUE(handle.WillHandleTouchEvent(event));
EXPECT_TRUE(IsDragging());
event = MockMotionEvent(MockMotionEvent::Action::MOVE, event_time,
kOffset + 10, kOffset + 15);
EXPECT_TRUE(handle.WillHandleTouchEvent(event));
EXPECT_TRUE(GetAndResetHandleDragged());
EXPECT_TRUE(IsDragging());
EXPECT_EQ(gfx::PointF(10, 15), DragPosition());
event = MockMotionEvent(MockMotionEvent::Action::MOVE, event_time,
kOffset - 10, kOffset - 15);
EXPECT_TRUE(handle.WillHandleTouchEvent(event));
EXPECT_TRUE(GetAndResetHandleDragged());
EXPECT_TRUE(IsDragging());
EXPECT_EQ(gfx::PointF(-10, -15), DragPosition());
event = MockMotionEvent(MockMotionEvent::Action::UP);
EXPECT_TRUE(handle.WillHandleTouchEvent(event));
EXPECT_FALSE(GetAndResetHandleDragged());
EXPECT_FALSE(IsDragging());
// Non-Action::DOWN events after the drag has terminated should not be
// handled.
event = MockMotionEvent(MockMotionEvent::Action::CANCEL);
EXPECT_FALSE(handle.WillHandleTouchEvent(event));
}
TEST_F(TouchHandleTest, DragDefersOrientationChange) {
TouchHandle handle(this, TouchHandleOrientation::RIGHT, kDefaultViewportRect);
ASSERT_EQ(drawable().orientation, TouchHandleOrientation::RIGHT);
UpdateHandleVisibility(handle, true, TouchHandle::ANIMATION_NONE);
MockMotionEvent event(MockMotionEvent::Action::DOWN);
EXPECT_TRUE(handle.WillHandleTouchEvent(event));
EXPECT_TRUE(IsDragging());
// Orientation changes will be deferred until the drag ends.
UpdateHandleOrientation(handle, TouchHandleOrientation::LEFT);
EXPECT_EQ(TouchHandleOrientation::RIGHT, drawable().orientation);
event = MockMotionEvent(MockMotionEvent::Action::MOVE);
EXPECT_TRUE(handle.WillHandleTouchEvent(event));
EXPECT_TRUE(GetAndResetHandleDragged());
EXPECT_TRUE(IsDragging());
EXPECT_EQ(TouchHandleOrientation::RIGHT, drawable().orientation);
event = MockMotionEvent(MockMotionEvent::Action::UP);
EXPECT_TRUE(handle.WillHandleTouchEvent(event));
EXPECT_FALSE(GetAndResetHandleDragged());
EXPECT_FALSE(IsDragging());
EXPECT_EQ(TouchHandleOrientation::LEFT, drawable().orientation);
}
TEST_F(TouchHandleTest, DragDefersFade) {
TouchHandle handle(this, TouchHandleOrientation::CENTER,
kDefaultViewportRect);
UpdateHandleVisibility(handle, true, TouchHandle::ANIMATION_NONE);
MockMotionEvent event(MockMotionEvent::Action::DOWN);
EXPECT_TRUE(handle.WillHandleTouchEvent(event));
EXPECT_TRUE(IsDragging());
// Fade will be deferred until the drag ends.
UpdateHandleVisibility(handle, false, TouchHandle::ANIMATION_SMOOTH);
EXPECT_FALSE(NeedsAnimate());
EXPECT_TRUE(drawable().visible);
EXPECT_EQ(1.f, drawable().alpha);
event = MockMotionEvent(MockMotionEvent::Action::MOVE);
EXPECT_TRUE(handle.WillHandleTouchEvent(event));
EXPECT_FALSE(NeedsAnimate());
EXPECT_TRUE(drawable().visible);
event = MockMotionEvent(MockMotionEvent::Action::UP);
EXPECT_TRUE(handle.WillHandleTouchEvent(event));
EXPECT_FALSE(IsDragging());
EXPECT_TRUE(NeedsAnimate());
Animate(handle);
EXPECT_FALSE(drawable().visible);
EXPECT_EQ(0.f, drawable().alpha);
}
TEST_F(TouchHandleTest, DragTargettingUsesTouchSize) {
TouchHandle handle(this, TouchHandleOrientation::CENTER,
kDefaultViewportRect);
gfx::PointF focus_top(kDefaultDrawableSize / 2, 0);
gfx::PointF focus_bottom(kDefaultDrawableSize / 2, 0);
UpdateHandleFocus(handle, focus_top, focus_bottom);
UpdateHandleVisibility(handle, true, TouchHandle::ANIMATION_NONE);
base::TimeTicks event_time = base::TimeTicks::Now();
const float kTouchSize = 24.f;
const float kOffset = kDefaultDrawableSize + kTouchSize / 2.001f;
MockMotionEvent event(MockMotionEvent::Action::DOWN, event_time, kOffset, 0);
event.SetTouchMajor(0.f);
EXPECT_FALSE(handle.WillHandleTouchEvent(event));
EXPECT_FALSE(IsDragging());
event.SetTouchMajor(kTouchSize / 2.f);
EXPECT_FALSE(handle.WillHandleTouchEvent(event));
EXPECT_FALSE(IsDragging());
event.SetTouchMajor(kTouchSize);
EXPECT_TRUE(handle.WillHandleTouchEvent(event));
EXPECT_TRUE(IsDragging());
event.SetTouchMajor(kTouchSize * 2.f);
EXPECT_TRUE(handle.WillHandleTouchEvent(event));
EXPECT_TRUE(IsDragging());
// The touch hit test region should be circular.
event = MockMotionEvent(MockMotionEvent::Action::DOWN, event_time, kOffset,
kOffset);
event.SetTouchMajor(kTouchSize);
EXPECT_FALSE(handle.WillHandleTouchEvent(event));
EXPECT_FALSE(IsDragging());
event.SetTouchMajor(kTouchSize * std::sqrt(2.f) - 0.1f);
EXPECT_FALSE(handle.WillHandleTouchEvent(event));
EXPECT_FALSE(IsDragging());
event.SetTouchMajor(kTouchSize * std::sqrt(2.f) + 0.1f);
EXPECT_TRUE(handle.WillHandleTouchEvent(event));
EXPECT_TRUE(IsDragging());
// Ensure a touch size of 0 can still register a hit.
event =
MockMotionEvent(MockMotionEvent::Action::DOWN, event_time,
kDefaultDrawableSize / 2.f, kDefaultDrawableSize / 2.f);
event.SetTouchMajor(0);
EXPECT_TRUE(handle.WillHandleTouchEvent(event));
EXPECT_TRUE(IsDragging());
// Touches centered above the handle region should never register a hit, even
// if the touch region intersects the handle region.
event = MockMotionEvent(MockMotionEvent::Action::DOWN, event_time,
kDefaultDrawableSize / 2.f, -kTouchSize / 3.f);
event.SetTouchMajor(kTouchSize);
EXPECT_FALSE(handle.WillHandleTouchEvent(event));
EXPECT_FALSE(IsDragging());
}
TEST_F(TouchHandleTest, Tap) {
TouchHandle handle(this, TouchHandleOrientation::CENTER,
kDefaultViewportRect);
UpdateHandleVisibility(handle, true, TouchHandle::ANIMATION_NONE);
base::TimeTicks event_time = base::TimeTicks::Now();
// Action::CANCEL shouldn't trigger a tap.
MockMotionEvent event(MockMotionEvent::Action::DOWN, event_time, 0, 0);
EXPECT_TRUE(handle.WillHandleTouchEvent(event));
event_time += base::Milliseconds(50);
event = MockMotionEvent(MockMotionEvent::Action::CANCEL, event_time, 0, 0);
EXPECT_TRUE(handle.WillHandleTouchEvent(event));
EXPECT_FALSE(GetAndResetHandleTapped());
// Long press shouldn't trigger a tap.
event = MockMotionEvent(MockMotionEvent::Action::DOWN, event_time, 0, 0);
EXPECT_TRUE(handle.WillHandleTouchEvent(event));
event_time += 2 * GetMaxTapDuration();
event = MockMotionEvent(MockMotionEvent::Action::UP, event_time, 0, 0);
EXPECT_TRUE(handle.WillHandleTouchEvent(event));
EXPECT_FALSE(GetAndResetHandleTapped());
// Only a brief tap within the slop region should trigger a tap.
event = MockMotionEvent(MockMotionEvent::Action::DOWN, event_time, 0, 0);
EXPECT_TRUE(handle.WillHandleTouchEvent(event));
event_time += GetMaxTapDuration() / 2;
event = MockMotionEvent(MockMotionEvent::Action::MOVE, event_time,
kDefaultTapSlop / 2.f, 0);
EXPECT_TRUE(handle.WillHandleTouchEvent(event));
event = MockMotionEvent(MockMotionEvent::Action::UP, event_time,
kDefaultTapSlop / 2.f, 0);
EXPECT_TRUE(handle.WillHandleTouchEvent(event));
EXPECT_TRUE(GetAndResetHandleTapped());
// Moving beyond the slop region shouldn't trigger a tap.
event = MockMotionEvent(MockMotionEvent::Action::DOWN, event_time, 0, 0);
EXPECT_TRUE(handle.WillHandleTouchEvent(event));
event_time += GetMaxTapDuration() / 2;
event = MockMotionEvent(MockMotionEvent::Action::MOVE, event_time,
kDefaultTapSlop * 2.f, 0);
EXPECT_TRUE(handle.WillHandleTouchEvent(event));
event = MockMotionEvent(MockMotionEvent::Action::UP, event_time,
kDefaultTapSlop * 2.f, 0);
EXPECT_TRUE(handle.WillHandleTouchEvent(event));
EXPECT_FALSE(GetAndResetHandleTapped());
}
TEST_F(TouchHandleTest, MirrorFocusChange) {
TouchHandle handle(this, TouchHandleOrientation::LEFT, kDefaultViewportRect);
UpdateHandleVisibility(handle, true, TouchHandle::ANIMATION_NONE);
gfx::PointF focus_top;
gfx::PointF focus_bottom;
EXPECT_EQ(gfx::PointF(), drawable().rect.origin());
// Moving the selection to the bottom of the screen
// should mirror the handle vertically.
focus_top = gfx::PointF(17.3f, 1199.0f);
focus_bottom = gfx::PointF(17.3f, 1200.0f);
UpdateHandleFocus(handle, focus_top, focus_bottom);
EXPECT_TRUE(drawable().mirror_vertical);
EXPECT_FALSE(drawable().mirror_horizontal);
// Moving the left handle to the left edge of the viewport
// should mirror the handle horizontally as well.
focus_top = gfx::PointF(2.3f, 1199.0f);
focus_bottom = gfx::PointF(2.3f, 1200.0f);
UpdateHandleFocus(handle, focus_top, focus_bottom);
EXPECT_TRUE(drawable().mirror_vertical);
EXPECT_TRUE(drawable().mirror_horizontal);
// When the selection is not at the bottom, only the
// horizontal mirror flag should be true.
focus_top = gfx::PointF(2.3f, 7.3f);
focus_bottom = gfx::PointF(2.3f, 8.3f);
UpdateHandleFocus(handle, focus_top, focus_bottom);
EXPECT_FALSE(drawable().mirror_vertical);
EXPECT_TRUE(drawable().mirror_horizontal);
// When selection handles intersects the viewport fully,
// both mirror values should be false.
focus_top = gfx::PointF(23.3f, 7.3f);
focus_bottom = gfx::PointF(23.3f, 8.3f);
UpdateHandleFocus(handle, focus_top, focus_bottom);
EXPECT_FALSE(drawable().mirror_vertical);
EXPECT_FALSE(drawable().mirror_horizontal);
// Horizontal mirror should be true for Right handle when
// the handle is at theright edge of the viewport.
UpdateHandleOrientation(handle, TouchHandleOrientation::RIGHT);
focus_top = gfx::PointF(560.0f, 7.3f);
focus_bottom = gfx::PointF(560.0f, 8.3f);
UpdateHandleFocus(handle, focus_top, focus_bottom);
EXPECT_FALSE(drawable().mirror_vertical);
EXPECT_TRUE(drawable().mirror_horizontal);
}
TEST_F(TouchHandleTest, DragDefersMirrorChange) {
TouchHandle handle(this, TouchHandleOrientation::RIGHT, kDefaultViewportRect);
ASSERT_EQ(drawable().orientation, TouchHandleOrientation::RIGHT);
UpdateHandleVisibility(handle, true, TouchHandle::ANIMATION_NONE);
base::TimeTicks event_time = base::TimeTicks::Now();
const float kOffset = kDefaultDrawableSize / 2.f;
// Start the drag.
MockMotionEvent event(MockMotionEvent::Action::DOWN, event_time, kOffset,
kOffset);
EXPECT_TRUE(handle.WillHandleTouchEvent(event));
EXPECT_TRUE(IsDragging());
UpdateHandleOrientation(handle, TouchHandleOrientation::LEFT);
gfx::PointF focus_top(17.3f, 1199.0f);
gfx::PointF focus_bottom(17.3f, 1200.0f);
UpdateHandleFocus(handle, focus_top, focus_bottom);
EXPECT_FALSE(drawable().mirror_vertical);
EXPECT_FALSE(drawable().mirror_horizontal);
// Mirror flag changes will be deferred until the drag ends.
event = MockMotionEvent(MockMotionEvent::Action::UP);
EXPECT_TRUE(handle.WillHandleTouchEvent(event));
EXPECT_FALSE(GetAndResetHandleDragged());
EXPECT_FALSE(IsDragging());
EXPECT_TRUE(drawable().mirror_vertical);
EXPECT_FALSE(drawable().mirror_horizontal);
}
TEST_F(TouchHandleTest, ViewportSizeChange) {
TouchHandle handle(this, TouchHandleOrientation::RIGHT, kDefaultViewportRect);
ASSERT_EQ(drawable().orientation, TouchHandleOrientation::RIGHT);
UpdateHandleVisibility(handle, true, TouchHandle::ANIMATION_NONE);
gfx::PointF focus_top;
gfx::PointF focus_bottom;
EXPECT_EQ(gfx::PointF(), drawable().rect.origin());
focus_top = gfx::PointF(230.0f, 599.0f);
focus_bottom = gfx::PointF(230.0f, 600.0f);
UpdateHandleFocus(handle, focus_top, focus_bottom);
EXPECT_FALSE(drawable().mirror_vertical);
EXPECT_FALSE(drawable().mirror_horizontal);
UpdateViewportRect(handle, gfx::RectF(0, 0, 560, 600));
EXPECT_TRUE(drawable().mirror_vertical);
EXPECT_FALSE(drawable().mirror_horizontal);
UpdateViewportRect(handle, gfx::RectF(0, 0, 230, 600));
EXPECT_TRUE(drawable().mirror_vertical);
EXPECT_TRUE(drawable().mirror_horizontal);
UpdateViewportRect(handle, kDefaultViewportRect);
EXPECT_FALSE(drawable().mirror_vertical);
EXPECT_FALSE(drawable().mirror_horizontal);
}
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/touch_selection/touch_handle_unittest.cc | C++ | unknown | 25,393 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/touch_selection/touch_selection_controller.h"
#include <memory>
#include "base/auto_reset.h"
#include "base/check_op.h"
#include "base/metrics/histogram_macros.h"
#include "base/metrics/user_metrics.h"
#include "base/notreached.h"
namespace ui {
namespace {
gfx::Vector2dF ComputeLineOffsetFromBottom(const gfx::SelectionBound& bound) {
gfx::Vector2dF line_offset =
gfx::ScaleVector2d(bound.edge_start() - bound.edge_end(), 0.5f);
// An offset of 8 DIPs is sufficient for most line sizes. For small lines,
// using half the line height avoids synthesizing a point on a line above
// (or below) the intended line.
const gfx::Vector2dF kMaxLineOffset(8.f, 8.f);
line_offset.SetToMin(kMaxLineOffset);
line_offset.SetToMax(-kMaxLineOffset);
return line_offset;
}
TouchHandleOrientation ToTouchHandleOrientation(
gfx::SelectionBound::Type type) {
switch (type) {
case gfx::SelectionBound::LEFT:
return TouchHandleOrientation::LEFT;
case gfx::SelectionBound::RIGHT:
return TouchHandleOrientation::RIGHT;
case gfx::SelectionBound::CENTER:
return TouchHandleOrientation::CENTER;
case gfx::SelectionBound::EMPTY:
return TouchHandleOrientation::UNDEFINED;
}
NOTREACHED() << "Invalid selection bound type: " << type;
return TouchHandleOrientation::UNDEFINED;
}
} // namespace
TouchSelectionController::TouchSelectionController(
TouchSelectionControllerClient* client,
const Config& config)
: client_(client),
config_(config),
response_pending_input_event_(INPUT_EVENT_TYPE_NONE),
start_orientation_(TouchHandleOrientation::UNDEFINED),
end_orientation_(TouchHandleOrientation::UNDEFINED),
active_status_(INACTIVE),
temporarily_hidden_(false),
anchor_drag_to_selection_start_(false),
longpress_drag_selector_(this),
selection_handle_dragged_(false),
consume_touch_sequence_(false),
show_touch_handles_(false) {
DCHECK(client_);
}
TouchSelectionController::~TouchSelectionController() {
}
void TouchSelectionController::OnSelectionBoundsChanged(
const gfx::SelectionBound& start,
const gfx::SelectionBound& end) {
if (start == start_ && end_ == end)
return;
if (start.type() == gfx::SelectionBound::EMPTY ||
end.type() == gfx::SelectionBound::EMPTY ||
!show_touch_handles_) {
HideHandles();
return;
}
// Swap the Handles when the start and end selection points cross each other.
if (active_status_ == SELECTION_ACTIVE) {
// Bounds have the same orientation.
bool need_swap = (start_selection_handle_->IsActive() &&
end_.edge_end() == start.edge_end()) ||
(end_selection_handle_->IsActive() &&
end.edge_end() == start_.edge_end());
// Bounds have different orientation.
// Specifically, for writing-mode: vertical-*, selection bounds are
// horizontal.
// When vertical-lr:
// - start bound is from right to left,
// - end bound is from left to right.
// When vertical-rl:
// - start bound is from left to right,
// - end bound is from right to left.
// So when previous start/end bound become current end/start bound,
// edge_start() and edge_end() are swapped. Therefore, we are comparing
// edge_end() with edge_start() here.
need_swap |= (start_selection_handle_->IsActive() &&
end_.edge_end() == start.edge_start()) ||
(end_selection_handle_->IsActive() &&
end.edge_end() == start_.edge_start());
#ifdef OHOS_CLIPBOARD
if (!need_swap) {
need_swap = (end_ == end && end_selection_handle_->IsActive()) ||
(start_ == start && start_selection_handle_->IsActive());
}
#endif
if (need_swap)
start_selection_handle_.swap(end_selection_handle_);
}
// Update |anchor_drag_to_selection_start_| for long press drag selector.
// Since selection can be updated with only one end at a time, if one end is
// equal to the previous value, the updated end is the other.
if (start_ == start)
anchor_drag_to_selection_start_ = false;
else if (end_ == end)
anchor_drag_to_selection_start_ = true;
start_ = start;
end_ = end;
start_orientation_ = ToTouchHandleOrientation(start_.type());
end_orientation_ = ToTouchHandleOrientation(end_.type());
// Ensure that |response_pending_input_event_| is cleared after the method
// completes, while also making its current value available for the duration
// of the call.
InputEventType causal_input_event = response_pending_input_event_;
response_pending_input_event_ = INPUT_EVENT_TYPE_NONE;
base::AutoReset<InputEventType> auto_reset_response_pending_input_event(
&response_pending_input_event_, causal_input_event);
if ((start_orientation_ == TouchHandleOrientation::LEFT ||
start_orientation_ == TouchHandleOrientation::RIGHT) &&
(end_orientation_ == TouchHandleOrientation::RIGHT ||
end_orientation_ == TouchHandleOrientation::LEFT)) {
OnSelectionChanged();
return;
}
if (start_orientation_ == TouchHandleOrientation::CENTER) {
OnInsertionChanged();
return;
}
HideHandles();
}
void TouchSelectionController::OnViewportChanged(
const gfx::RectF viewport_rect) {
// Trigger a force update if the viewport is changed, so that
// it triggers a call to change the mirror values if required.
if (viewport_rect_ == viewport_rect)
return;
viewport_rect_ = viewport_rect;
if (active_status_ == INACTIVE)
return;
if (active_status_ == INSERTION_ACTIVE) {
DCHECK(insertion_handle_);
insertion_handle_->SetViewportRect(viewport_rect);
} else if (active_status_ == SELECTION_ACTIVE) {
DCHECK(start_selection_handle_);
DCHECK(end_selection_handle_);
start_selection_handle_->SetViewportRect(viewport_rect);
end_selection_handle_->SetViewportRect(viewport_rect);
}
// Update handle layout after setting the new Viewport size.
UpdateHandleLayoutIfNecessary();
#ifdef OHOS_EX_TOPCONTROLS
if (client_) {
client_->OnSelectionEvent(SELECTION_HANDLES_MOVED);
}
#endif
}
bool TouchSelectionController::WillHandleTouchEvent(const MotionEvent& event) {
bool handled = WillHandleTouchEventImpl(event);
// If Action::DOWN is consumed, the rest of touch sequence should be consumed,
// too, regardless of value of |handled|.
// TODO(mohsen): This will consume touch events until the next Action::DOWN.
// Ideally we should consume until the final Action::UP/Action::CANCEL.
// But, apparently, we can't reliably determine the final Action::CANCEL in a
// multi-touch scenario. See https://crbug.com/653212.
if (event.GetAction() == MotionEvent::Action::DOWN)
consume_touch_sequence_ = handled;
return handled || consume_touch_sequence_;
}
void TouchSelectionController::HandleTapEvent(const gfx::PointF& location,
int tap_count) {
if (tap_count > 1) {
response_pending_input_event_ = REPEATED_TAP;
} else {
response_pending_input_event_ = TAP;
}
}
void TouchSelectionController::HandleLongPressEvent(
base::TimeTicks event_time,
const gfx::PointF& location) {
#ifdef OHOS_CLIPBOARD
is_long_press_ = true;
#endif
longpress_drag_selector_.OnLongPressEvent(event_time, location);
response_pending_input_event_ = LONG_PRESS;
}
void TouchSelectionController::OnScrollBeginEvent() {
// When there is an active selection, if the user performs a long-press that
// does not trigger a new selection (e.g. a long-press on an empty area) and
// then scrolls, the scroll will move the selection. In this case we will
// think incorrectly that the selection change was due to the long-press and
// will activate touch selection and start long-press drag gesture (see
// ActivateInsertionIfNecessary()). To prevent this, we need to reset the
// state of touch selection controller and long-press drag selector.
// TODO(mohsen): Remove this workaround when we have enough information about
// the cause of a selection change (see https://crbug.com/571897).
longpress_drag_selector_.OnScrollBeginEvent();
response_pending_input_event_ = INPUT_EVENT_TYPE_NONE;
}
void TouchSelectionController::HideHandles() {
response_pending_input_event_ = INPUT_EVENT_TYPE_NONE;
DeactivateInsertion();
DeactivateSelection();
start_ = gfx::SelectionBound();
end_ = gfx::SelectionBound();
start_orientation_ = ToTouchHandleOrientation(start_.type());
end_orientation_ = ToTouchHandleOrientation(end_.type());
}
void TouchSelectionController::HideAndDisallowShowingAutomatically() {
HideHandles();
show_touch_handles_ = false;
}
void TouchSelectionController::SetTemporarilyHidden(bool hidden) {
if (temporarily_hidden_ == hidden)
return;
temporarily_hidden_ = hidden;
RefreshHandleVisibility();
}
bool TouchSelectionController::Animate(base::TimeTicks frame_time) {
if (active_status_ == INSERTION_ACTIVE)
return insertion_handle_->Animate(frame_time);
if (active_status_ == SELECTION_ACTIVE) {
bool needs_animate = start_selection_handle_->Animate(frame_time);
needs_animate |= end_selection_handle_->Animate(frame_time);
return needs_animate;
}
return false;
}
gfx::RectF TouchSelectionController::GetRectBetweenBounds() const {
// Short-circuit for efficiency.
if (active_status_ == INACTIVE)
return gfx::RectF();
if (start_.visible() && !end_.visible()) {
// This BoundingRect is actually a line unless the selection is rotated.
return gfx::BoundingRect(start_.edge_start(), start_.edge_end());
}
if (end_.visible() && !start_.visible()) {
// This BoundingRect is actually a line unless the selection is rotated.
return gfx::BoundingRect(end_.edge_start(), end_.edge_end());
}
// If both handles are visible, or both are invisible, use the entire rect.
// Specifically, if both handles are on the same horizontal line for
// writing-mode: vertical-*, or both are on the same vertical line for
// writing-mode: horizontal, the entire rect is actually a line unless the
// selection is rotated.
return RectFBetweenSelectionBounds(start_, end_);
}
gfx::RectF TouchSelectionController::GetVisibleRectBetweenBounds() const {
// Short-circuit for efficiency.
if (active_status_ == INACTIVE)
return gfx::RectF();
// Returns the rect of the entire visible selection rect.
return RectFBetweenVisibleSelectionBounds(start_, end_);
}
gfx::RectF TouchSelectionController::GetStartHandleRect() const {
if (active_status_ == INSERTION_ACTIVE)
return insertion_handle_->GetVisibleBounds();
if (active_status_ == SELECTION_ACTIVE)
return start_selection_handle_->GetVisibleBounds();
return gfx::RectF();
}
gfx::RectF TouchSelectionController::GetEndHandleRect() const {
if (active_status_ == INSERTION_ACTIVE)
return insertion_handle_->GetVisibleBounds();
if (active_status_ == SELECTION_ACTIVE)
return end_selection_handle_->GetVisibleBounds();
return gfx::RectF();
}
float TouchSelectionController::GetTouchHandleHeight() const {
if (active_status_ == INSERTION_ACTIVE)
return insertion_handle_->GetVisibleBounds().height();
if (active_status_ == SELECTION_ACTIVE) {
if (GetStartVisible())
return start_selection_handle_->GetVisibleBounds().height();
if (GetEndVisible())
return end_selection_handle_->GetVisibleBounds().height();
}
return 0.f;
}
float TouchSelectionController::GetActiveHandleMiddleY() const {
const gfx::SelectionBound* bound = nullptr;
if (active_status_ == INSERTION_ACTIVE && insertion_handle_->IsActive())
bound = &start_;
if (active_status_ == SELECTION_ACTIVE) {
if (start_selection_handle_->IsActive())
bound = &start_;
else if (end_selection_handle_->IsActive())
bound = &end_;
}
if (!bound)
return 0.f;
return (bound->edge_start().y() + bound->edge_end().y()) / 2.f;
}
const gfx::PointF& TouchSelectionController::GetStartPosition() const {
return start_.edge_end();
}
const gfx::PointF& TouchSelectionController::GetEndPosition() const {
return end_.edge_end();
}
bool TouchSelectionController::WillHandleTouchEventImpl(
const MotionEvent& event) {
show_touch_handles_ = true;
if (config_.enable_longpress_drag_selection &&
longpress_drag_selector_.WillHandleTouchEvent(event)) {
return true;
}
if (active_status_ == INSERTION_ACTIVE) {
DCHECK(insertion_handle_);
return insertion_handle_->WillHandleTouchEvent(event);
}
if (active_status_ == SELECTION_ACTIVE) {
DCHECK(start_selection_handle_);
DCHECK(end_selection_handle_);
if (start_selection_handle_->IsActive())
return start_selection_handle_->WillHandleTouchEvent(event);
if (end_selection_handle_->IsActive())
return end_selection_handle_->WillHandleTouchEvent(event);
const gfx::PointF event_pos(event.GetX(), event.GetY());
if ((event_pos - GetStartPosition()).LengthSquared() <=
(event_pos - GetEndPosition()).LengthSquared()) {
return start_selection_handle_->WillHandleTouchEvent(event);
}
return end_selection_handle_->WillHandleTouchEvent(event);
}
return false;
}
void TouchSelectionController::OnSwipeToMoveCursorBegin() {
if (config_.hide_active_handle) {
// Hide the handle when magnifier is showing since it can confuse the user.
SetTemporarilyHidden(true);
// If the user has typed something, the insertion handle might be hidden.
// Prepare to show touch handles on end.
show_touch_handles_ = true;
}
}
void TouchSelectionController::OnSwipeToMoveCursorEnd() {
// Show the handle at the end if magnifier was showing.
if (config_.hide_active_handle)
SetTemporarilyHidden(false);
}
#ifdef OHOS_DRAG_DROP
void TouchSelectionController::ResetResponsePendingInputEvent() {
response_pending_input_event_ = INPUT_EVENT_TYPE_NONE;
}
#endif
#ifdef OHOS_CLIPBOARD
void TouchSelectionController::UpdateSelectionChanged(
const TouchSelectionDraggable& draggable) {
if (&draggable != insertion_handle_.get()) {
client_->OnSelectionEvent(SELECTION_HANDLES_UPDATEMENU);
}
}
bool TouchSelectionController::IsLongPressDragSelectionActive() {
return longpress_drag_selector_.IsActive();
}
bool TouchSelectionController::IsLongPressEvent() {
return is_long_press_;
}
void TouchSelectionController::ResetLongPressEvent() {
is_long_press_ = false;
}
#endif
void TouchSelectionController::OnDragBegin(
const TouchSelectionDraggable& draggable,
const gfx::PointF& drag_position) {
if (&draggable == insertion_handle_.get()) {
DCHECK_EQ(active_status_, INSERTION_ACTIVE);
if (config_.hide_active_handle)
insertion_handle_->SetTransparent();
client_->OnSelectionEvent(INSERTION_HANDLE_DRAG_STARTED);
anchor_drag_to_selection_start_ = true;
return;
}
DCHECK_EQ(active_status_, SELECTION_ACTIVE);
if (&draggable == start_selection_handle_.get()) {
anchor_drag_to_selection_start_ = true;
} else if (&draggable == end_selection_handle_.get()) {
anchor_drag_to_selection_start_ = false;
} else {
DCHECK_EQ(&draggable, &longpress_drag_selector_);
anchor_drag_to_selection_start_ =
(drag_position - GetStartPosition()).LengthSquared() <
(drag_position - GetEndPosition()).LengthSquared();
}
if (config_.hide_active_handle) {
if (&draggable == start_selection_handle_.get()) {
start_selection_handle_->SetTransparent();
} else if (&draggable == end_selection_handle_.get()) {
end_selection_handle_->SetTransparent();
}
}
gfx::PointF base = GetStartPosition() + GetStartLineOffset();
gfx::PointF extent = GetEndPosition() + GetEndLineOffset();
if (anchor_drag_to_selection_start_)
std::swap(base, extent);
// If this is the first drag, log an action to allow user action sequencing.
if (!selection_handle_dragged_)
base::RecordAction(base::UserMetricsAction("SelectionChanged"));
selection_handle_dragged_ = true;
#ifdef OHOS_CLIPBOARD
selection_handle_orientation_dragging_ =
anchor_drag_to_selection_start_ ? TouchHandleOrientation::LEFT : TouchHandleOrientation::RIGHT;
#endif
// When moving the handle we want to move only the extent point. Before doing
// so we must make sure that the base point is set correctly.
client_->SelectBetweenCoordinates(base, extent);
client_->OnSelectionEvent(SELECTION_HANDLE_DRAG_STARTED);
}
void TouchSelectionController::OnDragUpdate(
const TouchSelectionDraggable& draggable,
const gfx::PointF& drag_position) {
// As the position corresponds to the bottom left point of the selection
// bound, offset it to some reasonable point on the current line of text.
gfx::Vector2dF line_offset = anchor_drag_to_selection_start_
? GetStartLineOffset()
: GetEndLineOffset();
#ifdef OHOS_CLIPBOARD
gfx::PointF line_position;
if (selection_handle_orientation_dragging_ == TouchHandleOrientation::LEFT) {
line_position = drag_position - line_offset;
} else {
line_position = drag_position + line_offset;
}
#else
gfx::PointF line_position = drag_position + line_offset;
#endif
if (&draggable == insertion_handle_.get())
client_->MoveCaret(line_position);
else
client_->MoveRangeSelectionExtent(line_position);
// We use the bound middle point to restrict the ability to move up and
// down, but let user move it more freely in horizontal direction.
if (&draggable == &longpress_drag_selector_) {
// Show magnifier at the selection edge.
const gfx::SelectionBound* bound =
anchor_drag_to_selection_start_ ? &start_ : &end_;
const float x = bound->edge_start().x();
const float y = (bound->edge_start().y() + bound->edge_end().y()) / 2.f;
client_->OnDragUpdate(TouchSelectionDraggable::Type::kLongpress,
gfx::PointF(x, y));
} else {
const float y = GetActiveHandleMiddleY();
client_->OnDragUpdate(TouchSelectionDraggable::Type::kTouchHandle,
gfx::PointF(drag_position.x(), y));
}
}
void TouchSelectionController::OnDragEnd(
const TouchSelectionDraggable& draggable) {
#ifdef OHOS_CLIPBOARD
selection_handle_orientation_dragging_ = TouchHandleOrientation::UNDEFINED;
#endif
if (&draggable == insertion_handle_.get())
client_->OnSelectionEvent(INSERTION_HANDLE_DRAG_STOPPED);
else {
#ifdef OHOS_CLIPBOARD
if (&draggable == start_selection_handle_.get()) {
start_selection_handle_->ResetPositionAfterDragEnd();
}
if (&draggable == end_selection_handle_.get()) {
end_selection_handle_->ResetPositionAfterDragEnd();
}
#endif
client_->OnSelectionEvent(SELECTION_HANDLE_DRAG_STOPPED);
}
}
bool TouchSelectionController::IsWithinTapSlop(
const gfx::Vector2dF& delta) const {
return delta.LengthSquared() <
(static_cast<double>(config_.tap_slop) * config_.tap_slop);
}
void TouchSelectionController::OnHandleTapped(const TouchHandle& handle) {
if (insertion_handle_ && &handle == insertion_handle_.get())
client_->OnSelectionEvent(INSERTION_HANDLE_TAPPED);
}
void TouchSelectionController::SetNeedsAnimate() {
client_->SetNeedsAnimate();
}
std::unique_ptr<TouchHandleDrawable>
TouchSelectionController::CreateDrawable() {
return client_->CreateDrawable();
}
base::TimeDelta TouchSelectionController::GetMaxTapDuration() const {
return config_.max_tap_duration;
}
bool TouchSelectionController::IsAdaptiveHandleOrientationEnabled() const {
return config_.enable_adaptive_handle_orientation;
}
void TouchSelectionController::OnLongPressDragActiveStateChanged() {
// The handles should remain hidden for the duration of a longpress drag,
// including the time between a longpress and the start of drag motion.
RefreshHandleVisibility();
}
gfx::PointF TouchSelectionController::GetSelectionStart() const {
return GetStartPosition();
}
gfx::PointF TouchSelectionController::GetSelectionEnd() const {
return GetEndPosition();
}
void TouchSelectionController::OnInsertionChanged() {
DeactivateSelection();
const bool activated = ActivateInsertionIfNecessary();
const TouchHandle::AnimationStyle animation = GetAnimationStyle(!activated);
#if BUILDFLAG(IS_OHOS)
insertion_handle_->SetEdge(start_.edge_start(), start_.edge_end());
#endif
insertion_handle_->SetFocus(start_.edge_start(), start_.edge_end());
insertion_handle_->SetVisible(GetStartVisible(), animation);
UpdateHandleLayoutIfNecessary();
client_->OnSelectionEvent(activated ? INSERTION_HANDLE_SHOWN
: INSERTION_HANDLE_MOVED);
}
void TouchSelectionController::OnSelectionChanged() {
DeactivateInsertion();
const bool activated = ActivateSelectionIfNecessary();
const TouchHandle::AnimationStyle animation = GetAnimationStyle(!activated);
#if BUILDFLAG(IS_OHOS)
start_selection_handle_->SetEdge(start_.edge_start(), start_.edge_end());
end_selection_handle_->SetEdge(end_.edge_start(), end_.edge_end());
#endif
start_selection_handle_->SetFocus(start_.edge_start(), start_.edge_end());
end_selection_handle_->SetFocus(end_.edge_start(), end_.edge_end());
start_selection_handle_->SetOrientation(start_orientation_);
end_selection_handle_->SetOrientation(end_orientation_);
start_selection_handle_->SetVisible(GetStartVisible(), animation);
end_selection_handle_->SetVisible(GetEndVisible(), animation);
UpdateHandleLayoutIfNecessary();
client_->OnSelectionEvent(activated ? SELECTION_HANDLES_SHOWN
: SELECTION_HANDLES_MOVED);
}
bool TouchSelectionController::ActivateInsertionIfNecessary() {
DCHECK_NE(SELECTION_ACTIVE, active_status_);
if (!insertion_handle_) {
insertion_handle_ = std::make_unique<TouchHandle>(
this, TouchHandleOrientation::CENTER, viewport_rect_);
}
if (active_status_ == INACTIVE || response_pending_input_event_ == TAP ||
response_pending_input_event_ == LONG_PRESS) {
active_status_ = INSERTION_ACTIVE;
insertion_handle_->SetEnabled(true);
insertion_handle_->SetViewportRect(viewport_rect_);
response_pending_input_event_ = INPUT_EVENT_TYPE_NONE;
return true;
}
return false;
}
void TouchSelectionController::DeactivateInsertion() {
if (active_status_ != INSERTION_ACTIVE)
return;
DCHECK(insertion_handle_);
active_status_ = INACTIVE;
insertion_handle_->SetEnabled(false);
client_->OnSelectionEvent(INSERTION_HANDLE_CLEARED);
}
bool TouchSelectionController::ActivateSelectionIfNecessary() {
DCHECK_NE(INSERTION_ACTIVE, active_status_);
if (!start_selection_handle_) {
start_selection_handle_ =
std::make_unique<TouchHandle>(this, start_orientation_, viewport_rect_);
} else {
start_selection_handle_->SetEnabled(true);
start_selection_handle_->SetViewportRect(viewport_rect_);
}
if (!end_selection_handle_) {
end_selection_handle_ =
std::make_unique<TouchHandle>(this, end_orientation_, viewport_rect_);
} else {
end_selection_handle_->SetEnabled(true);
end_selection_handle_->SetViewportRect(viewport_rect_);
}
// As a long press received while a selection is already active may trigger
// an entirely new selection, notify the client but avoid sending an
// intervening SELECTION_HANDLES_CLEARED update to avoid unnecessary state
// changes.
if (active_status_ == INACTIVE ||
response_pending_input_event_ == LONG_PRESS ||
response_pending_input_event_ == REPEATED_TAP) {
if (active_status_ == SELECTION_ACTIVE) {
// The active selection session finishes with the start of the new one.
LogSelectionEnd();
}
active_status_ = SELECTION_ACTIVE;
selection_handle_dragged_ = false;
selection_start_time_ = base::TimeTicks::Now();
response_pending_input_event_ = INPUT_EVENT_TYPE_NONE;
longpress_drag_selector_.OnSelectionActivated();
return true;
}
return false;
}
void TouchSelectionController::DeactivateSelection() {
if (active_status_ != SELECTION_ACTIVE)
return;
DCHECK(start_selection_handle_);
DCHECK(end_selection_handle_);
LogSelectionEnd();
longpress_drag_selector_.OnSelectionDeactivated();
start_selection_handle_->SetEnabled(false);
end_selection_handle_->SetEnabled(false);
active_status_ = INACTIVE;
client_->OnSelectionEvent(SELECTION_HANDLES_CLEARED);
}
void TouchSelectionController::UpdateHandleLayoutIfNecessary() {
if (active_status_ == INSERTION_ACTIVE) {
DCHECK(insertion_handle_);
insertion_handle_->UpdateHandleLayout();
} else if (active_status_ == SELECTION_ACTIVE) {
DCHECK(start_selection_handle_);
DCHECK(end_selection_handle_);
start_selection_handle_->UpdateHandleLayout();
end_selection_handle_->UpdateHandleLayout();
}
}
void TouchSelectionController::RefreshHandleVisibility() {
TouchHandle::AnimationStyle animation_style = GetAnimationStyle(true);
if (active_status_ == SELECTION_ACTIVE) {
start_selection_handle_->SetVisible(GetStartVisible(), animation_style);
end_selection_handle_->SetVisible(GetEndVisible(), animation_style);
}
if (active_status_ == INSERTION_ACTIVE)
insertion_handle_->SetVisible(GetStartVisible(), animation_style);
// Update handle layout if handle visibility is explicitly changed.
UpdateHandleLayoutIfNecessary();
}
gfx::Vector2dF TouchSelectionController::GetStartLineOffset() const {
return ComputeLineOffsetFromBottom(start_);
}
gfx::Vector2dF TouchSelectionController::GetEndLineOffset() const {
return ComputeLineOffsetFromBottom(end_);
}
bool TouchSelectionController::GetStartVisible() const {
if (!start_.visible())
return false;
return !temporarily_hidden_ && !longpress_drag_selector_.IsActive();
}
bool TouchSelectionController::GetEndVisible() const {
if (!end_.visible())
return false;
return !temporarily_hidden_ && !longpress_drag_selector_.IsActive();
}
TouchHandle::AnimationStyle TouchSelectionController::GetAnimationStyle(
bool was_active) const {
return was_active && client_->SupportsAnimation()
? TouchHandle::ANIMATION_SMOOTH
: TouchHandle::ANIMATION_NONE;
}
void TouchSelectionController::LogSelectionEnd() {
// TODO(mfomitchev): Once we are able to tell the difference between
// 'successful' and 'unsuccessful' selections - log
// Event.TouchSelection.Duration instead and get rid of
// Event.TouchSelectionD.WasDraggeduration.
if (selection_handle_dragged_) {
base::TimeDelta duration = base::TimeTicks::Now() - selection_start_time_;
UMA_HISTOGRAM_CUSTOM_TIMES("Event.TouchSelection.WasDraggedDuration",
duration, base::Milliseconds(500),
base::Seconds(60), 60);
}
}
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/touch_selection/touch_selection_controller.cc | C++ | unknown | 27,076 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_TOUCH_SELECTION_TOUCH_SELECTION_CONTROLLER_H_
#define UI_TOUCH_SELECTION_TOUCH_SELECTION_CONTROLLER_H_
#include "base/memory/raw_ptr.h"
#include "base/time/time.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/point_f.h"
#include "ui/gfx/geometry/rect_f.h"
#include "ui/gfx/geometry/vector2d_f.h"
#include "ui/gfx/selection_bound.h"
#include "ui/touch_selection/longpress_drag_selector.h"
#include "ui/touch_selection/selection_event_type.h"
#include "ui/touch_selection/touch_handle.h"
#include "ui/touch_selection/touch_handle_orientation.h"
#include "ui/touch_selection/ui_touch_selection_export.h"
namespace ui {
class MotionEvent;
// Interface through which |TouchSelectionController| issues selection-related
// commands, notifications and requests.
class UI_TOUCH_SELECTION_EXPORT TouchSelectionControllerClient {
public:
virtual ~TouchSelectionControllerClient() {}
virtual bool SupportsAnimation() const = 0;
virtual void SetNeedsAnimate() = 0;
virtual void MoveCaret(const gfx::PointF& position) = 0;
virtual void MoveRangeSelectionExtent(const gfx::PointF& extent) = 0;
virtual void SelectBetweenCoordinates(const gfx::PointF& base,
const gfx::PointF& extent) = 0;
virtual void OnSelectionEvent(SelectionEventType event) = 0;
virtual void OnDragUpdate(const TouchSelectionDraggable::Type type,
const gfx::PointF& position) = 0;
virtual std::unique_ptr<TouchHandleDrawable> CreateDrawable() = 0;
virtual void DidScroll() = 0;
virtual void ShowTouchSelectionContextMenu(const gfx::Point& location) {}
};
// Controller for manipulating text selection via touch input.
class UI_TOUCH_SELECTION_EXPORT TouchSelectionController
: public TouchHandleClient,
public LongPressDragSelectorClient {
public:
enum ActiveStatus {
INACTIVE,
INSERTION_ACTIVE,
SELECTION_ACTIVE,
};
struct UI_TOUCH_SELECTION_EXPORT Config {
// Maximum allowed time for handle tap detection. Defaults to 300 ms.
base::TimeDelta max_tap_duration = base::Milliseconds(300);
// Defaults to 8 DIPs.
float tap_slop = 8;
// Controls whether adaptive orientation for selection handles is enabled.
// Defaults to false.
bool enable_adaptive_handle_orientation = false;
// Controls whether drag selection after a longpress is enabled.
// Defaults to false.
bool enable_longpress_drag_selection = false;
// Should we hide the active handle.
bool hide_active_handle = false;
};
TouchSelectionController(TouchSelectionControllerClient* client,
const Config& config);
TouchSelectionController(const TouchSelectionController&) = delete;
TouchSelectionController& operator=(const TouchSelectionController&) = delete;
~TouchSelectionController() override;
// To be called when the selection bounds have changed.
// Note that such updates will trigger handle updates only if preceded
// by an appropriate call to allow automatic showing.
void OnSelectionBoundsChanged(const gfx::SelectionBound& start,
const gfx::SelectionBound& end);
// To be called when the viewport rect has been changed. This is used for
// setting the state of the handles.
void OnViewportChanged(const gfx::RectF viewport_rect);
// Allows touch-dragging of the handle.
// Returns true iff the event was consumed, in which case the caller should
// cease further handling of the event.
bool WillHandleTouchEvent(const MotionEvent& event);
// To be called before forwarding a tap event.
// |tap_count| is tap index in a repeated sequence, i.e., 1 for the first
// tap, 2 for the second tap, etc...
void HandleTapEvent(const gfx::PointF& location, int tap_count);
// To be called before forwarding a longpress event.
void HandleLongPressEvent(base::TimeTicks event_time,
const gfx::PointF& location);
// To be called before forwarding a gesture scroll begin event to prevent
// long-press drag.
void OnScrollBeginEvent();
// Hide the handles and suppress bounds updates until the next explicit
// showing allowance.
void HideAndDisallowShowingAutomatically();
// Override the handle visibility according to |hidden|.
void SetTemporarilyHidden(bool hidden);
// Ticks an active animation, as requested to the client by |SetNeedsAnimate|.
// Returns true if an animation is active and requires further ticking.
bool Animate(base::TimeTicks animate_time);
// Returns the rect between the two active selection bounds. If just one of
// the bounds is visible, or both bounds are visible and on the same line,
// the rect is simply a one-dimensional rect of that bound. If no selection
// is active, an empty rect will be returned.
gfx::RectF GetRectBetweenBounds() const;
// Returns the rect between the selection bounds (as above) but clipped by
// occluding layers.
gfx::RectF GetVisibleRectBetweenBounds() const;
// Returns the visible rect of specified touch handle. For an active insertion
// these values will be identical.
gfx::RectF GetStartHandleRect() const;
gfx::RectF GetEndHandleRect() const;
// Return the handle height of visible touch handle. This value will be zero
// when no handle is visible.
float GetTouchHandleHeight() const;
// Returns the focal point of the start and end bounds, as defined by
// their bottom coordinate.
const gfx::PointF& GetStartPosition() const;
const gfx::PointF& GetEndPosition() const;
// To be called when swipe-to-move-cursor motion begins.
void OnSwipeToMoveCursorBegin();
// To be called when swipe-to-move-cursor motion ends.
void OnSwipeToMoveCursorEnd();
const gfx::SelectionBound& start() const { return start_; }
const gfx::SelectionBound& end() const { return end_; }
#if BUILDFLAG(IS_OHOS)
const std::unique_ptr<TouchHandle>& GetInsertHandle() {
return insertion_handle_;
}
const std::unique_ptr<TouchHandle>& GetStartSelectionHandle() {
return start_selection_handle_;
}
const std::unique_ptr<TouchHandle>& GetEndSelectionHandle() {
return end_selection_handle_;
}
#endif
#ifdef OHOS_DRAG_DROP
void ResetResponsePendingInputEvent();
#endif
#ifdef OHOS_CLIPBOARD
void UpdateSelectionChanged(const TouchSelectionDraggable& draggable) override;
bool IsLongPressDragSelectionActive();
bool IsLongPressEvent();
void ResetLongPressEvent();
#endif
ActiveStatus active_status() const { return active_status_; }
private:
friend class TouchSelectionControllerTestApi;
enum InputEventType { TAP, REPEATED_TAP, LONG_PRESS, INPUT_EVENT_TYPE_NONE };
bool WillHandleTouchEventImpl(const MotionEvent& event);
// TouchHandleClient implementation.
void OnDragBegin(const TouchSelectionDraggable& draggable,
const gfx::PointF& drag_position) override;
void OnDragUpdate(const TouchSelectionDraggable& draggable,
const gfx::PointF& drag_position) override;
void OnDragEnd(const TouchSelectionDraggable& draggable) override;
bool IsWithinTapSlop(const gfx::Vector2dF& delta) const override;
void OnHandleTapped(const TouchHandle& handle) override;
void SetNeedsAnimate() override;
std::unique_ptr<TouchHandleDrawable> CreateDrawable() override;
base::TimeDelta GetMaxTapDuration() const override;
bool IsAdaptiveHandleOrientationEnabled() const override;
// LongPressDragSelectorClient implementation.
void OnLongPressDragActiveStateChanged() override;
gfx::PointF GetSelectionStart() const override;
gfx::PointF GetSelectionEnd() const override;
void OnInsertionChanged();
void OnSelectionChanged();
// Returns true if insertion mode was newly (re)activated.
bool ActivateInsertionIfNecessary();
void DeactivateInsertion();
// Returns true if selection mode was newly (re)activated.
bool ActivateSelectionIfNecessary();
void DeactivateSelection();
void UpdateHandleLayoutIfNecessary();
bool WillHandleTouchEventForLongPressDrag(const MotionEvent& event);
void SetTemporarilyHiddenForLongPressDrag(bool hidden);
void RefreshHandleVisibility();
// Returns the y-coordinate of middle point of selection bound corresponding
// to the active selection or insertion handle. If there is no active handle,
// returns 0.0.
float GetActiveHandleMiddleY() const;
void HideHandles();
gfx::Vector2dF GetStartLineOffset() const;
gfx::Vector2dF GetEndLineOffset() const;
bool GetStartVisible() const;
bool GetEndVisible() const;
TouchHandle::AnimationStyle GetAnimationStyle(bool was_active) const;
void LogSelectionEnd();
const raw_ptr<TouchSelectionControllerClient> client_;
const Config config_;
InputEventType response_pending_input_event_;
// The bounds at the begin and end of the selection, which might be vertical
// or horizontal line and represents the position of the touch handles or
// caret.
gfx::SelectionBound start_;
gfx::SelectionBound end_;
TouchHandleOrientation start_orientation_;
TouchHandleOrientation end_orientation_;
ActiveStatus active_status_;
std::unique_ptr<TouchHandle> insertion_handle_;
std::unique_ptr<TouchHandle> start_selection_handle_;
std::unique_ptr<TouchHandle> end_selection_handle_;
bool temporarily_hidden_;
// Whether to use the start bound (if false, the end bound) for computing the
// appropriate text line offset when performing a selection drag. This helps
// ensure that the initial selection induced by the drag doesn't "jump"
// between lines.
bool anchor_drag_to_selection_start_;
#ifdef OHOS_CLIPBOARD
TouchHandleOrientation selection_handle_orientation_dragging_ = TouchHandleOrientation::UNDEFINED;
#endif
// Longpress drag allows direct manipulation of longpress-initiated selection.
LongPressDragSelector longpress_drag_selector_;
gfx::RectF viewport_rect_;
base::TimeTicks selection_start_time_;
// Whether a selection handle was dragged during the current 'selection
// session' - i.e. since the current selection has been activated.
bool selection_handle_dragged_;
// Determines whether the entire touch sequence should be consumed or not.
bool consume_touch_sequence_;
bool show_touch_handles_;
#ifdef OHOS_CLIPBOARD
bool is_long_press_ = false;
#endif
};
} // namespace ui
#endif // UI_TOUCH_SELECTION_TOUCH_SELECTION_CONTROLLER_H_
| Zhao-PengFei35/chromium_src_4 | ui/touch_selection/touch_selection_controller.h | C++ | unknown | 10,575 |
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/touch_selection/touch_selection_controller_test_api.h"
namespace ui {
TouchSelectionControllerTestApi::TouchSelectionControllerTestApi(
TouchSelectionController* controller)
: controller_(controller) {}
TouchSelectionControllerTestApi::~TouchSelectionControllerTestApi() {}
bool TouchSelectionControllerTestApi::GetStartVisible() const {
return controller_->GetStartVisible();
}
bool TouchSelectionControllerTestApi::GetEndVisible() const {
return controller_->GetEndVisible();
}
float TouchSelectionControllerTestApi::GetStartAlpha() const {
if (controller_->active_status_ == TouchSelectionController::SELECTION_ACTIVE)
return controller_->start_selection_handle_->alpha();
return 0.f;
}
float TouchSelectionControllerTestApi::GetEndAlpha() const {
if (controller_->active_status_ == TouchSelectionController::SELECTION_ACTIVE)
return controller_->end_selection_handle_->alpha();
return 0.f;
}
float TouchSelectionControllerTestApi::GetInsertionHandleAlpha() const {
if (controller_->active_status_ == TouchSelectionController::INSERTION_ACTIVE)
return controller_->insertion_handle_->alpha();
return 0.f;
}
TouchHandleOrientation
TouchSelectionControllerTestApi::GetStartHandleOrientation() const {
if (controller_->active_status_ != TouchSelectionController::SELECTION_ACTIVE)
return TouchHandleOrientation::UNDEFINED;
return controller_->start_selection_handle_->orientation();
}
TouchHandleOrientation
TouchSelectionControllerTestApi::GetEndHandleOrientation() const {
if (controller_->active_status_ != TouchSelectionController::SELECTION_ACTIVE)
return TouchHandleOrientation::UNDEFINED;
return controller_->end_selection_handle_->orientation();
}
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/touch_selection/touch_selection_controller_test_api.cc | C++ | unknown | 1,898 |
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_TOUCH_SELECTION_TOUCH_SELECTION_CONTROLLER_TEST_API_H_
#define UI_TOUCH_SELECTION_TOUCH_SELECTION_CONTROLLER_TEST_API_H_
#include "base/memory/raw_ptr.h"
#include "ui/touch_selection/touch_selection_controller.h"
namespace ui {
// Test api class to access internals of |ui::TouchSelectionController| in
// tests.
class TouchSelectionControllerTestApi {
public:
explicit TouchSelectionControllerTestApi(
TouchSelectionController* controller);
TouchSelectionControllerTestApi(const TouchSelectionControllerTestApi&) =
delete;
TouchSelectionControllerTestApi& operator=(
const TouchSelectionControllerTestApi&) = delete;
~TouchSelectionControllerTestApi();
bool GetStartVisible() const;
bool GetEndVisible() const;
float GetStartAlpha() const;
float GetEndAlpha() const;
float GetInsertionHandleAlpha() const;
TouchHandleOrientation GetStartHandleOrientation() const;
TouchHandleOrientation GetEndHandleOrientation() const;
bool temporarily_hidden() const { return controller_->temporarily_hidden_; }
private:
const raw_ptr<TouchSelectionController> controller_;
};
} // namespace ui
#endif // UI_TOUCH_SELECTION_TOUCH_SELECTION_CONTROLLER_TEST_API_H_
| Zhao-PengFei35/chromium_src_4 | ui/touch_selection/touch_selection_controller_test_api.h | C++ | unknown | 1,362 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/touch_selection/touch_selection_controller.h"
#include <vector>
#include "base/memory/raw_ptr.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/events/test/motion_event_test_utils.h"
#include "ui/touch_selection/touch_selection_controller_test_api.h"
using testing::ElementsAre;
using testing::IsEmpty;
using ui::test::MockMotionEvent;
namespace ui {
namespace {
constexpr int kDefaultTapTimeoutMs = 200;
constexpr float kDefaultTapSlop = 10.f;
constexpr gfx::PointF kIgnoredPoint(0, 0);
constexpr TouchSelectionController::Config kDefaultConfig = {
.max_tap_duration = base::Milliseconds(kDefaultTapTimeoutMs),
.tap_slop = kDefaultTapSlop,
};
class MockTouchHandleDrawable : public TouchHandleDrawable {
public:
explicit MockTouchHandleDrawable(bool* contains_point)
: intersects_rect_(contains_point) {}
MockTouchHandleDrawable(const MockTouchHandleDrawable&) = delete;
MockTouchHandleDrawable& operator=(const MockTouchHandleDrawable&) = delete;
~MockTouchHandleDrawable() override {}
void SetEnabled(bool enabled) override {}
void SetOrientation(ui::TouchHandleOrientation orientation,
bool mirror_vertical,
bool mirror_horizontal) override {}
void SetOrigin(const gfx::PointF& origin) override {}
void SetAlpha(float alpha) override {}
gfx::RectF GetVisibleBounds() const override {
return *intersects_rect_ ? gfx::RectF(-1000, -1000, 2000, 2000)
: gfx::RectF(-1000, -1000, 0, 0);
}
float GetDrawableHorizontalPaddingRatio() const override { return 0; }
#if defined(OHOS_UNITTESTS)
void SetEdge(const gfx::PointF& top, const gfx::PointF& bottom) override {}
#endif
private:
raw_ptr<bool> intersects_rect_;
};
class TouchSelectionControllerTest : public testing::Test,
public TouchSelectionControllerClient {
public:
TouchSelectionControllerTest() = default;
TouchSelectionControllerTest(const TouchSelectionControllerTest&) = delete;
TouchSelectionControllerTest& operator=(const TouchSelectionControllerTest&) =
delete;
~TouchSelectionControllerTest() override {}
// testing::Test implementation.
void SetUp() override {
InitializeControllerWithConfig(kDefaultConfig);
StartTouchEventSequence();
}
void TearDown() override { controller_.reset(); }
// TouchSelectionControllerClient implementation.
bool SupportsAnimation() const override { return animation_enabled_; }
void SetNeedsAnimate() override { needs_animate_ = true; }
void MoveCaret(const gfx::PointF& position) override {
caret_moved_ = true;
caret_position_ = position;
}
void SelectBetweenCoordinates(const gfx::PointF& base,
const gfx::PointF& extent) override {
if (base == selection_end_ && extent == selection_start_)
selection_points_swapped_ = true;
selection_start_ = base;
selection_end_ = extent;
}
void MoveRangeSelectionExtent(const gfx::PointF& extent) override {
selection_moved_ = true;
selection_end_ = extent;
}
void OnSelectionEvent(SelectionEventType event) override {
events_.push_back(event);
last_event_start_ = controller_->GetStartPosition();
last_event_end_ = controller_->GetEndPosition();
last_event_bounds_rect_ = controller_->GetRectBetweenBounds();
}
void OnDragUpdate(const TouchSelectionDraggable::Type type,
const gfx::PointF& position) override {
last_drag_update_position_ = position;
}
std::unique_ptr<TouchHandleDrawable> CreateDrawable() override {
return std::make_unique<MockTouchHandleDrawable>(&dragging_enabled_);
}
void DidScroll() override {}
void InitializeControllerWithConfig(TouchSelectionController::Config config) {
controller_ = std::make_unique<TouchSelectionController>(this, config);
}
void StartTouchEventSequence() {
controller_->WillHandleTouchEvent(
MockMotionEvent(MotionEvent::Action::DOWN));
}
void SetAnimationEnabled(bool enabled) { animation_enabled_ = enabled; }
void SetDraggingEnabled(bool enabled) { dragging_enabled_ = enabled; }
void ClearSelection() {
controller_->OnSelectionBoundsChanged(gfx::SelectionBound(),
gfx::SelectionBound());
}
void ClearInsertion() { ClearSelection(); }
void ChangeInsertion(const gfx::RectF& rect, bool visible) {
gfx::SelectionBound bound;
bound.set_type(gfx::SelectionBound::CENTER);
bound.SetEdge(rect.origin(), rect.bottom_left());
bound.set_visible(visible);
controller_->OnSelectionBoundsChanged(bound, bound);
}
void ChangeSelection(const gfx::RectF& start_rect,
bool start_visible,
const gfx::RectF& end_rect,
bool end_visible) {
gfx::SelectionBound start_bound, end_bound;
start_bound.set_type(gfx::SelectionBound::LEFT);
end_bound.set_type(gfx::SelectionBound::RIGHT);
start_bound.SetEdge(start_rect.origin(), start_rect.bottom_left());
end_bound.SetEdge(end_rect.origin(), end_rect.bottom_left());
start_bound.set_visible(start_visible);
end_bound.set_visible(end_visible);
controller_->OnSelectionBoundsChanged(start_bound, end_bound);
}
void ChangeVerticalSelection(const gfx::RectF& start_rect,
bool start_visible,
const gfx::RectF& end_rect,
bool end_visible) {
gfx::SelectionBound start_bound, end_bound;
start_bound.set_type(gfx::SelectionBound::RIGHT);
end_bound.set_type(gfx::SelectionBound::LEFT);
start_bound.SetEdge(start_rect.origin(), start_rect.bottom_right());
end_bound.SetEdge(end_rect.bottom_right(), end_rect.origin());
start_bound.set_visible(start_visible);
end_bound.set_visible(end_visible);
controller_->OnSelectionBoundsChanged(start_bound, end_bound);
}
void OnLongPressEvent() {
controller().HandleLongPressEvent(base::TimeTicks(),
kIgnoredPoint);
}
void OnTapEvent() {
controller().HandleTapEvent(kIgnoredPoint, 1);
}
void OnDoubleTapEvent() {
controller().HandleTapEvent(kIgnoredPoint, 2);
}
void OnTripleTapEvent() { controller().HandleTapEvent(kIgnoredPoint, 3); }
void Animate() {
base::TimeTicks now = base::TimeTicks::Now();
while (needs_animate_) {
needs_animate_ = controller_->Animate(now);
now += base::Milliseconds(16);
}
}
bool GetAndResetNeedsAnimate() {
bool needs_animate = needs_animate_;
Animate();
return needs_animate;
}
bool GetAndResetCaretMoved() {
bool moved = caret_moved_;
caret_moved_ = false;
return moved;
}
bool GetAndResetSelectionMoved() {
bool moved = selection_moved_;
selection_moved_ = false;
return moved;
}
bool GetAndResetSelectionPointsSwapped() {
bool swapped = selection_points_swapped_;
selection_points_swapped_ = false;
return swapped;
}
const gfx::PointF& GetLastCaretPosition() const { return caret_position_; }
const gfx::PointF& GetLastSelectionStart() const { return selection_start_; }
const gfx::PointF& GetLastSelectionEnd() const { return selection_end_; }
const gfx::PointF& GetLastEventStart() const { return last_event_start_; }
const gfx::PointF& GetLastEventEnd() const { return last_event_end_; }
const gfx::RectF& GetLastEventBoundsRect() const {
return last_event_bounds_rect_;
}
const gfx::PointF& GetLastDragUpdatePosition() const {
return last_drag_update_position_;
}
std::vector<SelectionEventType> GetAndResetEvents() {
std::vector<SelectionEventType> events;
events.swap(events_);
return events;
}
TouchSelectionController& controller() { return *controller_; }
private:
gfx::PointF last_event_start_;
gfx::PointF last_event_end_;
gfx::PointF caret_position_;
gfx::PointF selection_start_;
gfx::PointF selection_end_;
gfx::RectF last_event_bounds_rect_;
gfx::PointF last_drag_update_position_;
std::vector<SelectionEventType> events_;
bool caret_moved_ = false;
bool selection_moved_ = false;
bool selection_points_swapped_ = false;
bool needs_animate_ = false;
bool animation_enabled_ = true;
bool dragging_enabled_ = false;
std::unique_ptr<TouchSelectionController> controller_;
};
TEST_F(TouchSelectionControllerTest, InsertionBasic) {
gfx::RectF insertion_rect(5, 5, 0, 10);
bool visible = true;
OnTapEvent();
ChangeInsertion(insertion_rect, visible);
EXPECT_THAT(GetAndResetEvents(), ElementsAre(INSERTION_HANDLE_SHOWN));
EXPECT_EQ(insertion_rect.bottom_left(), GetLastEventStart());
insertion_rect.Offset(1, 0);
ChangeInsertion(insertion_rect, visible);
EXPECT_THAT(GetAndResetEvents(), ElementsAre(INSERTION_HANDLE_MOVED));
EXPECT_EQ(insertion_rect.bottom_left(), GetLastEventStart());
insertion_rect.Offset(0, 1);
ChangeInsertion(insertion_rect, visible);
EXPECT_THAT(GetAndResetEvents(), ElementsAre(INSERTION_HANDLE_MOVED));
EXPECT_EQ(insertion_rect.bottom_left(), GetLastEventStart());
OnTapEvent();
insertion_rect.Offset(1, 0);
ChangeInsertion(insertion_rect, visible);
EXPECT_THAT(GetAndResetEvents(), ElementsAre(INSERTION_HANDLE_SHOWN));
EXPECT_EQ(insertion_rect.bottom_left(), GetLastEventStart());
ClearInsertion();
EXPECT_THAT(GetAndResetEvents(),
ElementsAre(INSERTION_HANDLE_CLEARED));
}
TEST_F(TouchSelectionControllerTest, InsertionToSelectionTransition) {
OnLongPressEvent();
gfx::RectF start_rect(5, 5, 0, 10);
gfx::RectF end_rect(50, 5, 0, 10);
bool visible = true;
ChangeInsertion(start_rect, visible);
EXPECT_THAT(GetAndResetEvents(),
ElementsAre(INSERTION_HANDLE_SHOWN));
EXPECT_EQ(start_rect.bottom_left(), GetLastEventStart());
ChangeSelection(start_rect, visible, end_rect, visible);
EXPECT_THAT(GetAndResetEvents(),
ElementsAre(INSERTION_HANDLE_CLEARED, SELECTION_HANDLES_SHOWN));
EXPECT_EQ(start_rect.bottom_left(), GetLastEventStart());
ChangeInsertion(end_rect, visible);
EXPECT_THAT(GetAndResetEvents(),
ElementsAre(SELECTION_HANDLES_CLEARED, INSERTION_HANDLE_SHOWN));
EXPECT_EQ(end_rect.bottom_left(), GetLastEventStart());
ClearInsertion();
EXPECT_THAT(GetAndResetEvents(), ElementsAre(INSERTION_HANDLE_CLEARED));
OnTapEvent();
ChangeInsertion(end_rect, visible);
EXPECT_THAT(GetAndResetEvents(), ElementsAre(INSERTION_HANDLE_SHOWN));
EXPECT_EQ(end_rect.bottom_left(), GetLastEventStart());
}
TEST_F(TouchSelectionControllerTest, InsertionDragged) {
base::TimeTicks event_time = base::TimeTicks::Now();
OnTapEvent();
// The touch sequence should not be handled if insertion is not active.
MockMotionEvent event(MockMotionEvent::Action::DOWN, event_time, 0, 0);
EXPECT_FALSE(controller().WillHandleTouchEvent(event));
float line_height = 10.f;
gfx::RectF start_rect(10, 0, 0, line_height);
bool visible = true;
ChangeInsertion(start_rect, visible);
EXPECT_THAT(GetAndResetEvents(),
ElementsAre(INSERTION_HANDLE_SHOWN));
EXPECT_EQ(start_rect.bottom_left(), GetLastEventStart());
// The touch sequence should be handled only if the drawable reports a hit.
EXPECT_FALSE(controller().WillHandleTouchEvent(event));
SetDraggingEnabled(true);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_FALSE(GetAndResetCaretMoved());
EXPECT_THAT(GetAndResetEvents(), ElementsAre(INSERTION_HANDLE_DRAG_STARTED));
// The MoveCaret() result should reflect the movement.
// The reported position is offset from the center of |start_rect|.
gfx::PointF start_offset = start_rect.CenterPoint();
event = MockMotionEvent(MockMotionEvent::Action::MOVE, event_time, 0, 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_TRUE(GetAndResetCaretMoved());
EXPECT_EQ(start_offset + gfx::Vector2dF(0, 5), GetLastCaretPosition());
event = MockMotionEvent(MockMotionEvent::Action::MOVE, event_time, 5, 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_TRUE(GetAndResetCaretMoved());
EXPECT_EQ(start_offset + gfx::Vector2dF(5, 5), GetLastCaretPosition());
event = MockMotionEvent(MockMotionEvent::Action::MOVE, event_time, 10, 10);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_TRUE(GetAndResetCaretMoved());
EXPECT_EQ(start_offset + gfx::Vector2dF(10, 10), GetLastCaretPosition());
event = MockMotionEvent(MockMotionEvent::Action::UP, event_time, 10, 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_FALSE(GetAndResetCaretMoved());
EXPECT_THAT(GetAndResetEvents(), ElementsAre(INSERTION_HANDLE_DRAG_STOPPED));
// Following Action::DOWN should not be consumed if it does not start handle
// dragging.
SetDraggingEnabled(false);
event = MockMotionEvent(MotionEvent::Action::DOWN, event_time, 0, 0);
EXPECT_FALSE(controller().WillHandleTouchEvent(event));
}
TEST_F(TouchSelectionControllerTest, InsertionDeactivatedWhileDragging) {
base::TimeTicks event_time = base::TimeTicks::Now();
OnTapEvent();
float line_height = 10.f;
gfx::RectF start_rect(10, 0, 0, line_height);
bool visible = true;
ChangeInsertion(start_rect, visible);
EXPECT_THAT(GetAndResetEvents(),
ElementsAre(INSERTION_HANDLE_SHOWN));
EXPECT_EQ(start_rect.bottom_left(), GetLastEventStart());
// Enable dragging so that the following Action::DOWN starts handle dragging.
SetDraggingEnabled(true);
// Touch down to start dragging.
MockMotionEvent event(MockMotionEvent::Action::DOWN, event_time, 0, 0);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_FALSE(GetAndResetCaretMoved());
EXPECT_THAT(GetAndResetEvents(), ElementsAre(INSERTION_HANDLE_DRAG_STARTED));
// Move the handle.
gfx::PointF start_offset = start_rect.CenterPoint();
event = MockMotionEvent(MockMotionEvent::Action::MOVE, event_time, 0, 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_TRUE(GetAndResetCaretMoved());
EXPECT_EQ(start_offset + gfx::Vector2dF(0, 5), GetLastCaretPosition());
// Deactivate touch selection to end dragging.
controller().HideAndDisallowShowingAutomatically();
EXPECT_THAT(GetAndResetEvents(), ElementsAre(INSERTION_HANDLE_DRAG_STOPPED,
INSERTION_HANDLE_CLEARED));
// Move the finger. There is no handle to move, so the cursor is not moved;
// but, the event is still consumed because the touch down that started the
// touch sequence was consumed.
event = MockMotionEvent(MockMotionEvent::Action::MOVE, event_time, 5, 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_FALSE(GetAndResetCaretMoved());
EXPECT_EQ(start_offset + gfx::Vector2dF(0, 5), GetLastCaretPosition());
// Lift the finger to end the touch sequence.
event = MockMotionEvent(MockMotionEvent::Action::UP, event_time, 5, 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_FALSE(GetAndResetCaretMoved());
EXPECT_THAT(GetAndResetEvents(), IsEmpty());
// Following Action::DOWN should not be consumed if it does not start handle
// dragging.
SetDraggingEnabled(false);
event = MockMotionEvent(MotionEvent::Action::DOWN, event_time, 0, 0);
EXPECT_FALSE(controller().WillHandleTouchEvent(event));
}
TEST_F(TouchSelectionControllerTest, InsertionTapped) {
base::TimeTicks event_time = base::TimeTicks::Now();
OnTapEvent();
SetDraggingEnabled(true);
gfx::RectF start_rect(10, 0, 0, 10);
bool visible = true;
ChangeInsertion(start_rect, visible);
EXPECT_THAT(GetAndResetEvents(),
ElementsAre(INSERTION_HANDLE_SHOWN));
MockMotionEvent event(MockMotionEvent::Action::DOWN, event_time, 0, 0);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(INSERTION_HANDLE_DRAG_STARTED));
event = MockMotionEvent(MockMotionEvent::Action::UP, event_time, 0, 0);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(INSERTION_HANDLE_TAPPED,
INSERTION_HANDLE_DRAG_STOPPED));
// Reset the insertion.
ClearInsertion();
OnTapEvent();
ChangeInsertion(start_rect, visible);
EXPECT_THAT(GetAndResetEvents(),
ElementsAre(INSERTION_HANDLE_CLEARED, INSERTION_HANDLE_SHOWN));
// No tap should be signalled if the time between DOWN and UP was too long.
event = MockMotionEvent(MockMotionEvent::Action::DOWN, event_time, 0, 0);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
event = MockMotionEvent(MockMotionEvent::Action::UP,
event_time + base::Seconds(1), 0, 0);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(INSERTION_HANDLE_DRAG_STARTED,
INSERTION_HANDLE_DRAG_STOPPED));
// Reset the insertion.
ClearInsertion();
OnTapEvent();
ChangeInsertion(start_rect, visible);
EXPECT_THAT(GetAndResetEvents(),
ElementsAre(INSERTION_HANDLE_CLEARED, INSERTION_HANDLE_SHOWN));
// No tap should be signalled if the drag was too long.
event = MockMotionEvent(MockMotionEvent::Action::DOWN, event_time, 0, 0);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
event = MockMotionEvent(MockMotionEvent::Action::MOVE, event_time, 100, 0);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
event = MockMotionEvent(MockMotionEvent::Action::UP, event_time, 100, 0);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(INSERTION_HANDLE_DRAG_STARTED,
INSERTION_HANDLE_DRAG_STOPPED));
// Reset the insertion.
ClearInsertion();
OnTapEvent();
ChangeInsertion(start_rect, visible);
EXPECT_THAT(GetAndResetEvents(),
ElementsAre(INSERTION_HANDLE_CLEARED, INSERTION_HANDLE_SHOWN));
// No tap should be signalled if the touch sequence is cancelled.
event = MockMotionEvent(MockMotionEvent::Action::DOWN, event_time, 0, 0);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
event = MockMotionEvent(MockMotionEvent::Action::CANCEL, event_time, 0, 0);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(INSERTION_HANDLE_DRAG_STARTED,
INSERTION_HANDLE_DRAG_STOPPED));
}
TEST_F(TouchSelectionControllerTest, SelectionBasic) {
gfx::RectF start_rect(5, 5, 0, 10);
gfx::RectF end_rect(50, 5, 0, 10);
bool visible = true;
OnLongPressEvent();
ChangeSelection(start_rect, visible, end_rect, visible);
EXPECT_THAT(GetAndResetEvents(),
ElementsAre(SELECTION_HANDLES_SHOWN));
EXPECT_EQ(start_rect.bottom_left(), GetLastEventStart());
start_rect.Offset(1, 0);
ChangeSelection(start_rect, visible, end_rect, visible);
// Selection movement does not currently trigger a separate event.
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLES_MOVED));
EXPECT_EQ(start_rect.bottom_left(), GetLastEventStart());
EXPECT_EQ(end_rect.bottom_left(), GetLastEventEnd());
ClearSelection();
EXPECT_THAT(GetAndResetEvents(),
ElementsAre(SELECTION_HANDLES_CLEARED));
}
TEST_F(TouchSelectionControllerTest, SelectionAllowedByDoubleTap) {
gfx::RectF start_rect(5, 5, 0, 10);
gfx::RectF end_rect(50, 5, 0, 10);
bool visible = true;
OnDoubleTapEvent();
ChangeSelection(start_rect, visible, end_rect, visible);
EXPECT_THAT(GetAndResetEvents(),
ElementsAre(SELECTION_HANDLES_SHOWN));
EXPECT_EQ(start_rect.bottom_left(), GetLastEventStart());
}
TEST_F(TouchSelectionControllerTest, SelectionAllowedByDoubleTapOnEditable) {
gfx::RectF start_rect(5, 5, 0, 10);
gfx::RectF end_rect(50, 5, 0, 10);
bool visible = true;
// If the user double tap selects text in an editable region, the first tap
// will register insertion and the second tap selection.
OnTapEvent();
ChangeInsertion(start_rect, visible);
EXPECT_THAT(GetAndResetEvents(),
ElementsAre(INSERTION_HANDLE_SHOWN));
OnDoubleTapEvent();
ChangeSelection(start_rect, visible, end_rect, visible);
EXPECT_THAT(GetAndResetEvents(),
ElementsAre(INSERTION_HANDLE_CLEARED, SELECTION_HANDLES_SHOWN));
}
TEST_F(TouchSelectionControllerTest,
SelectionAllowedByTripleTapOnEditableArabicVowel) {
gfx::RectF start_rect(5, 5, 0, 10);
gfx::RectF end_rect(5, 5, 0, 10);
bool visible = true;
// If the user triple tap selects text in an editable region, the first tap
// will register insertion.
OnTapEvent();
ChangeInsertion(start_rect, visible);
EXPECT_THAT(GetAndResetEvents(), ElementsAre(INSERTION_HANDLE_SHOWN));
// The second tap will also not select since the charcter (Arabic/Urdu vowel)
// has zero width, the second tap will maintain insertion.
OnDoubleTapEvent();
ChangeInsertion(start_rect, visible);
EXPECT_THAT(GetAndResetEvents(), ElementsAre());
// The third tap selects everything in the editable text box. Since the only
// text in the editable box is a zero length character the selection has the
// same start and end rect.
OnTripleTapEvent();
ChangeSelection(start_rect, visible, end_rect, visible);
EXPECT_THAT(GetAndResetEvents(),
ElementsAre(INSERTION_HANDLE_CLEARED, SELECTION_HANDLES_SHOWN));
}
TEST_F(TouchSelectionControllerTest, SelectionAllowsEmptyUpdateAfterLongPress) {
gfx::RectF start_rect(5, 5, 0, 10);
gfx::RectF end_rect(50, 5, 0, 10);
bool visible = true;
OnLongPressEvent();
EXPECT_THAT(GetAndResetEvents(), IsEmpty());
// There may be several empty updates after a longpress due to the
// asynchronous response. These empty updates should not prevent the selection
// handles from (eventually) activating.
ClearSelection();
EXPECT_THAT(GetAndResetEvents(), IsEmpty());
ClearSelection();
EXPECT_THAT(GetAndResetEvents(), IsEmpty());
ChangeSelection(start_rect, visible, end_rect, visible);
EXPECT_THAT(GetAndResetEvents(),
ElementsAre(SELECTION_HANDLES_SHOWN));
}
TEST_F(TouchSelectionControllerTest, SelectionRepeatedLongPress) {
gfx::RectF start_rect(5, 5, 0, 10);
gfx::RectF end_rect(50, 5, 0, 10);
bool visible = true;
OnLongPressEvent();
ChangeSelection(start_rect, visible, end_rect, visible);
EXPECT_THAT(GetAndResetEvents(),
ElementsAre(SELECTION_HANDLES_SHOWN));
EXPECT_EQ(start_rect.bottom_left(), GetLastEventStart());
EXPECT_EQ(end_rect.bottom_left(), GetLastEventEnd());
// A long press triggering a new selection should re-send the
// SELECTION_HANDLES_SHOWN
// event notification.
start_rect.Offset(10, 10);
OnLongPressEvent();
ChangeSelection(start_rect, visible, end_rect, visible);
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLES_SHOWN));
EXPECT_EQ(start_rect.bottom_left(), GetLastEventStart());
EXPECT_EQ(end_rect.bottom_left(), GetLastEventEnd());
}
TEST_F(TouchSelectionControllerTest, SelectionDragged) {
base::TimeTicks event_time = base::TimeTicks::Now();
OnLongPressEvent();
// The touch sequence should not be handled if selection is not active.
MockMotionEvent event(MockMotionEvent::Action::DOWN, event_time, 0, 0);
EXPECT_FALSE(controller().WillHandleTouchEvent(event));
float line_height = 10.f;
gfx::RectF start_rect(0, 0, 0, line_height);
gfx::RectF end_rect(50, 0, 0, line_height);
bool visible = true;
ChangeSelection(start_rect, visible, end_rect, visible);
EXPECT_THAT(GetAndResetEvents(),
ElementsAre(SELECTION_HANDLES_SHOWN));
EXPECT_EQ(start_rect.bottom_left(), GetLastEventStart());
// The touch sequence should be handled only if the drawable reports a hit.
EXPECT_FALSE(controller().WillHandleTouchEvent(event));
SetDraggingEnabled(true);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_FALSE(GetAndResetSelectionMoved());
// The SelectBetweenCoordinates() result should reflect the movement. Note
// that the start coordinate will always reflect the "fixed" handle's
// position, in this case the position from |end_rect|.
// Note that the reported position is offset from the center of the
// input rects (i.e., the middle of the corresponding text line).
gfx::PointF fixed_offset = end_rect.CenterPoint();
gfx::PointF start_offset = start_rect.CenterPoint();
event = MockMotionEvent(MockMotionEvent::Action::MOVE, event_time, 0, 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLE_DRAG_STARTED));
EXPECT_TRUE(GetAndResetSelectionMoved());
EXPECT_EQ(fixed_offset, GetLastSelectionStart());
EXPECT_EQ(start_offset + gfx::Vector2dF(0, 5), GetLastSelectionEnd());
event = MockMotionEvent(MockMotionEvent::Action::MOVE, event_time, 5, 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_TRUE(GetAndResetSelectionMoved());
EXPECT_EQ(fixed_offset, GetLastSelectionStart());
EXPECT_EQ(start_offset + gfx::Vector2dF(5, 5), GetLastSelectionEnd());
event = MockMotionEvent(MockMotionEvent::Action::MOVE, event_time, 10, 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_TRUE(GetAndResetSelectionMoved());
EXPECT_EQ(fixed_offset, GetLastSelectionStart());
EXPECT_EQ(start_offset + gfx::Vector2dF(10, 5), GetLastSelectionEnd());
event = MockMotionEvent(MockMotionEvent::Action::UP, event_time, 10, 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLE_DRAG_STOPPED));
EXPECT_FALSE(GetAndResetSelectionMoved());
// Following Action::DOWN should not be consumed if it does not start handle
// dragging.
SetDraggingEnabled(false);
event = MockMotionEvent(MotionEvent::Action::DOWN, event_time, 0, 0);
EXPECT_FALSE(controller().WillHandleTouchEvent(event));
}
TEST_F(TouchSelectionControllerTest, SelectionDraggedWithOverlap) {
base::TimeTicks event_time = base::TimeTicks::Now();
OnLongPressEvent();
float line_height = 10.f;
gfx::RectF start_rect(0, 0, 0, line_height);
gfx::RectF end_rect(50, 0, 0, line_height);
bool visible = true;
ChangeSelection(start_rect, visible, end_rect, visible);
EXPECT_THAT(GetAndResetEvents(),
ElementsAre(SELECTION_HANDLES_SHOWN));
EXPECT_EQ(start_rect.bottom_left(), GetLastEventStart());
// The Action::DOWN should lock to the closest handle.
gfx::PointF end_offset = end_rect.CenterPoint();
gfx::PointF fixed_offset = start_rect.CenterPoint();
float touch_down_x = (end_offset.x() + fixed_offset.x()) / 2 + 1.f;
MockMotionEvent event(MockMotionEvent::Action::DOWN, event_time, touch_down_x,
0);
SetDraggingEnabled(true);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLE_DRAG_STARTED));
EXPECT_FALSE(GetAndResetSelectionMoved());
// Even though the Action::MOVE is over the start handle, it should continue
// targetting the end handle that consumed the Action::DOWN.
event = MockMotionEvent(MockMotionEvent::Action::MOVE, event_time, 0, 0);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_TRUE(GetAndResetSelectionMoved());
EXPECT_EQ(fixed_offset, GetLastSelectionStart());
EXPECT_EQ(end_offset - gfx::Vector2dF(touch_down_x, 0),
GetLastSelectionEnd());
event = MockMotionEvent(MockMotionEvent::Action::UP, event_time, 0, 0);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLE_DRAG_STOPPED));
EXPECT_FALSE(GetAndResetSelectionMoved());
}
TEST_F(TouchSelectionControllerTest, SelectionDraggedToSwitchBaseAndExtent) {
base::TimeTicks event_time = base::TimeTicks::Now();
OnLongPressEvent();
float line_height = 10.f;
gfx::RectF start_rect(50, line_height, 0, line_height);
gfx::RectF end_rect(100, line_height, 0, line_height);
bool visible = true;
ChangeSelection(start_rect, visible, end_rect, visible);
EXPECT_THAT(GetAndResetEvents(),
ElementsAre(SELECTION_HANDLES_SHOWN));
EXPECT_EQ(start_rect.bottom_left(), GetLastEventStart());
SetDraggingEnabled(true);
// Move the extent, not triggering a swap of points.
MockMotionEvent event(MockMotionEvent::Action::DOWN, event_time, end_rect.x(),
end_rect.bottom());
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_FALSE(GetAndResetSelectionMoved());
EXPECT_FALSE(GetAndResetSelectionPointsSwapped());
gfx::PointF base_offset = start_rect.CenterPoint();
gfx::PointF extent_offset = end_rect.CenterPoint();
event = MockMotionEvent(MockMotionEvent::Action::MOVE, event_time,
end_rect.x(), end_rect.bottom() + 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLE_DRAG_STARTED));
EXPECT_TRUE(GetAndResetSelectionMoved());
EXPECT_FALSE(GetAndResetSelectionPointsSwapped());
EXPECT_EQ(base_offset, GetLastSelectionStart());
EXPECT_EQ(extent_offset + gfx::Vector2dF(0, 5), GetLastSelectionEnd());
event = MockMotionEvent(MockMotionEvent::Action::UP, event_time, 10, 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLE_DRAG_STOPPED));
EXPECT_FALSE(GetAndResetSelectionMoved());
end_rect += gfx::Vector2dF(0, 5);
ChangeSelection(start_rect, visible, end_rect, visible);
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLES_MOVED));
// Move the base, triggering a swap of points.
event = MockMotionEvent(MockMotionEvent::Action::DOWN, event_time,
start_rect.x(), start_rect.bottom());
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_FALSE(GetAndResetSelectionMoved());
EXPECT_TRUE(GetAndResetSelectionPointsSwapped());
base_offset = end_rect.CenterPoint();
extent_offset = start_rect.CenterPoint();
event = MockMotionEvent(MockMotionEvent::Action::MOVE, event_time,
start_rect.x(), start_rect.bottom() + 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLE_DRAG_STARTED));
EXPECT_TRUE(GetAndResetSelectionMoved());
EXPECT_FALSE(GetAndResetSelectionPointsSwapped());
EXPECT_EQ(base_offset, GetLastSelectionStart());
EXPECT_EQ(extent_offset + gfx::Vector2dF(0, 5), GetLastSelectionEnd());
event = MockMotionEvent(MockMotionEvent::Action::UP, event_time, 10, 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLE_DRAG_STOPPED));
EXPECT_FALSE(GetAndResetSelectionMoved());
start_rect += gfx::Vector2dF(0, 5);
ChangeSelection(start_rect, visible, end_rect, visible);
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLES_MOVED));
// Move the same point again, not triggering a swap of points.
event = MockMotionEvent(MockMotionEvent::Action::DOWN, event_time,
start_rect.x(), start_rect.bottom());
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_FALSE(GetAndResetSelectionMoved());
EXPECT_FALSE(GetAndResetSelectionPointsSwapped());
base_offset = end_rect.CenterPoint();
extent_offset = start_rect.CenterPoint();
event = MockMotionEvent(MockMotionEvent::Action::MOVE, event_time,
start_rect.x(), start_rect.bottom() + 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLE_DRAG_STARTED));
EXPECT_TRUE(GetAndResetSelectionMoved());
EXPECT_FALSE(GetAndResetSelectionPointsSwapped());
EXPECT_EQ(base_offset, GetLastSelectionStart());
EXPECT_EQ(extent_offset + gfx::Vector2dF(0, 5), GetLastSelectionEnd());
event = MockMotionEvent(MockMotionEvent::Action::UP, event_time, 10, 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLE_DRAG_STOPPED));
EXPECT_FALSE(GetAndResetSelectionMoved());
start_rect += gfx::Vector2dF(0, 5);
ChangeSelection(start_rect, visible, end_rect, visible);
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLES_MOVED));
// Move the base, triggering a swap of points.
event = MockMotionEvent(MockMotionEvent::Action::DOWN, event_time,
end_rect.x(), end_rect.bottom());
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_FALSE(GetAndResetSelectionMoved());
EXPECT_TRUE(GetAndResetSelectionPointsSwapped());
base_offset = start_rect.CenterPoint();
extent_offset = end_rect.CenterPoint();
event = MockMotionEvent(MockMotionEvent::Action::MOVE, event_time,
end_rect.x(), end_rect.bottom() + 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLE_DRAG_STARTED));
EXPECT_TRUE(GetAndResetSelectionMoved());
EXPECT_FALSE(GetAndResetSelectionPointsSwapped());
EXPECT_EQ(base_offset, GetLastSelectionStart());
EXPECT_EQ(extent_offset + gfx::Vector2dF(0, 5), GetLastSelectionEnd());
event = MockMotionEvent(MockMotionEvent::Action::UP, event_time, 10, 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLE_DRAG_STOPPED));
EXPECT_FALSE(GetAndResetSelectionMoved());
}
TEST_F(TouchSelectionControllerTest, SelectionDragExtremeLineSize) {
base::TimeTicks event_time = base::TimeTicks::Now();
OnLongPressEvent();
float small_line_height = 1.f;
float large_line_height = 50.f;
gfx::RectF small_line_rect(0, 0, 0, small_line_height);
gfx::RectF large_line_rect(50, 50, 0, large_line_height);
bool visible = true;
ChangeSelection(small_line_rect, visible, large_line_rect, visible);
EXPECT_THAT(GetAndResetEvents(),
ElementsAre(SELECTION_HANDLES_SHOWN));
EXPECT_EQ(small_line_rect.bottom_left(), GetLastEventStart());
// Start dragging the handle on the small line.
MockMotionEvent event(MockMotionEvent::Action::DOWN, event_time,
small_line_rect.x(), small_line_rect.y());
SetDraggingEnabled(true);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLE_DRAG_STARTED));
// The drag coordinate for large lines should be capped to a reasonable
// offset, allowing seamless transition to neighboring lines with different
// sizes. The drag coordinate for small lines should have an offset
// commensurate with the small line size.
EXPECT_EQ(large_line_rect.bottom_left() - gfx::Vector2dF(0, 8.f),
GetLastSelectionStart());
EXPECT_EQ(small_line_rect.CenterPoint(), GetLastSelectionEnd());
small_line_rect += gfx::Vector2dF(25.f, 0);
event = MockMotionEvent(MockMotionEvent::Action::MOVE, event_time,
small_line_rect.x(), small_line_rect.y());
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_TRUE(GetAndResetSelectionMoved());
EXPECT_EQ(small_line_rect.CenterPoint(), GetLastSelectionEnd());
}
TEST_F(TouchSelectionControllerTest, Animation) {
OnTapEvent();
gfx::RectF insertion_rect(5, 5, 0, 10);
bool visible = true;
ChangeInsertion(insertion_rect, visible);
EXPECT_FALSE(GetAndResetNeedsAnimate());
visible = false;
ChangeInsertion(insertion_rect, visible);
EXPECT_TRUE(GetAndResetNeedsAnimate());
visible = true;
ChangeInsertion(insertion_rect, visible);
EXPECT_TRUE(GetAndResetNeedsAnimate());
// If the handles are explicity hidden, no animation should be triggered.
controller().HideAndDisallowShowingAutomatically();
EXPECT_FALSE(GetAndResetNeedsAnimate());
// If the client doesn't support animation, no animation should be triggered.
SetAnimationEnabled(false);
OnTapEvent();
visible = true;
ChangeInsertion(insertion_rect, visible);
EXPECT_FALSE(GetAndResetNeedsAnimate());
}
TEST_F(TouchSelectionControllerTest, TemporarilyHidden) {
TouchSelectionControllerTestApi test_controller(&controller());
OnTapEvent();
gfx::RectF insertion_rect(5, 5, 0, 10);
bool visible = true;
ChangeInsertion(insertion_rect, visible);
EXPECT_FALSE(GetAndResetNeedsAnimate());
EXPECT_TRUE(test_controller.GetStartVisible());
EXPECT_TRUE(test_controller.GetEndVisible());
controller().SetTemporarilyHidden(true);
EXPECT_TRUE(GetAndResetNeedsAnimate());
EXPECT_FALSE(test_controller.GetStartVisible());
EXPECT_FALSE(test_controller.GetEndVisible());
EXPECT_EQ(0.f, test_controller.GetStartAlpha());
EXPECT_EQ(0.f, test_controller.GetEndAlpha());
visible = false;
ChangeInsertion(insertion_rect, visible);
EXPECT_FALSE(GetAndResetNeedsAnimate());
EXPECT_FALSE(test_controller.GetStartVisible());
EXPECT_EQ(0.f, test_controller.GetStartAlpha());
visible = true;
ChangeInsertion(insertion_rect, visible);
EXPECT_FALSE(GetAndResetNeedsAnimate());
EXPECT_FALSE(test_controller.GetStartVisible());
EXPECT_EQ(0.f, test_controller.GetStartAlpha());
controller().SetTemporarilyHidden(false);
EXPECT_TRUE(GetAndResetNeedsAnimate());
EXPECT_TRUE(test_controller.GetStartVisible());
}
TEST_F(TouchSelectionControllerTest, SelectionClearOnTap) {
gfx::RectF start_rect(5, 5, 0, 10);
gfx::RectF end_rect(50, 5, 0, 10);
bool visible = true;
OnLongPressEvent();
ChangeSelection(start_rect, visible, end_rect, visible);
EXPECT_THAT(GetAndResetEvents(),
ElementsAre(SELECTION_HANDLES_SHOWN));
// Selection should not be cleared if the selection bounds have not changed.
OnTapEvent();
EXPECT_THAT(GetAndResetEvents(), IsEmpty());
EXPECT_EQ(start_rect.bottom_left(), GetLastEventStart());
OnTapEvent();
ClearSelection();
EXPECT_THAT(GetAndResetEvents(),
ElementsAre(SELECTION_HANDLES_CLEARED));
}
TEST_F(TouchSelectionControllerTest, LongPressDrag) {
TouchSelectionController::Config config = kDefaultConfig;
config.enable_longpress_drag_selection = true;
InitializeControllerWithConfig(config);
TouchSelectionControllerTestApi test_controller(&controller());
gfx::RectF start_rect(-50, 0, 0, 10);
gfx::RectF end_rect(50, 0, 0, 10);
bool visible = true;
// Start a touch sequence.
MockMotionEvent event;
EXPECT_FALSE(controller().WillHandleTouchEvent(event.PressPoint(0, 0)));
// Activate a longpress-triggered selection.
OnLongPressEvent();
ChangeSelection(start_rect, visible, end_rect, visible);
EXPECT_THAT(GetAndResetEvents(),
ElementsAre(SELECTION_HANDLES_SHOWN));
EXPECT_EQ(start_rect.bottom_left(), GetLastEventStart());
// The handles should remain invisible while the touch release and longpress
// drag gesture are pending.
EXPECT_FALSE(test_controller.GetStartVisible());
EXPECT_FALSE(test_controller.GetEndVisible());
EXPECT_EQ(0.f, test_controller.GetStartAlpha());
EXPECT_EQ(0.f, test_controller.GetEndAlpha());
// The selection coordinates should reflect the drag movement.
gfx::PointF fixed_offset = start_rect.CenterPoint();
gfx::PointF end_offset = end_rect.CenterPoint();
EXPECT_TRUE(controller().WillHandleTouchEvent(event.MovePoint(0, 0, 0)));
EXPECT_THAT(GetAndResetEvents(), IsEmpty());
EXPECT_TRUE(controller().WillHandleTouchEvent(
event.MovePoint(0, 0, kDefaultTapSlop)));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLE_DRAG_STARTED));
EXPECT_EQ(fixed_offset, GetLastSelectionStart());
EXPECT_EQ(end_offset, GetLastSelectionEnd());
// Movement after the start of drag will be relative to the moved endpoint.
EXPECT_TRUE(controller().WillHandleTouchEvent(
event.MovePoint(0, 0, 2 * kDefaultTapSlop)));
EXPECT_TRUE(GetAndResetSelectionMoved());
EXPECT_EQ(end_offset + gfx::Vector2dF(0, kDefaultTapSlop),
GetLastSelectionEnd());
EXPECT_TRUE(controller().WillHandleTouchEvent(
event.MovePoint(0, kDefaultTapSlop, 2 * kDefaultTapSlop)));
EXPECT_TRUE(GetAndResetSelectionMoved());
EXPECT_EQ(end_offset + gfx::Vector2dF(kDefaultTapSlop, kDefaultTapSlop),
GetLastSelectionEnd());
EXPECT_TRUE(controller().WillHandleTouchEvent(
event.MovePoint(0, 2 * kDefaultTapSlop, 2 * kDefaultTapSlop)));
EXPECT_TRUE(GetAndResetSelectionMoved());
EXPECT_EQ(end_offset + gfx::Vector2dF(2 * kDefaultTapSlop, kDefaultTapSlop),
GetLastSelectionEnd());
// The handles should still be hidden.
EXPECT_FALSE(test_controller.GetStartVisible());
EXPECT_FALSE(test_controller.GetEndVisible());
EXPECT_EQ(0.f, test_controller.GetStartAlpha());
EXPECT_EQ(0.f, test_controller.GetEndAlpha());
// Releasing the touch sequence should end the drag and show the handles.
EXPECT_FALSE(controller().WillHandleTouchEvent(event.ReleasePoint()));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLE_DRAG_STOPPED));
EXPECT_TRUE(test_controller.GetStartVisible());
EXPECT_TRUE(test_controller.GetEndVisible());
}
TEST_F(TouchSelectionControllerTest, LongPressNoDrag) {
TouchSelectionController::Config config = kDefaultConfig;
config.enable_longpress_drag_selection = true;
InitializeControllerWithConfig(config);
TouchSelectionControllerTestApi test_controller(&controller());
gfx::RectF start_rect(-50, 0, 0, 10);
gfx::RectF end_rect(50, 0, 0, 10);
bool visible = true;
// Start a touch sequence.
MockMotionEvent event;
EXPECT_FALSE(controller().WillHandleTouchEvent(event.PressPoint(0, 0)));
// Activate a longpress-triggered selection.
OnLongPressEvent();
ChangeSelection(start_rect, visible, end_rect, visible);
EXPECT_THAT(GetAndResetEvents(),
ElementsAre(SELECTION_HANDLES_SHOWN));
EXPECT_EQ(start_rect.bottom_left(), GetLastEventStart());
// The handles should remain invisible while the touch release and longpress
// drag gesture are pending.
EXPECT_FALSE(test_controller.GetStartVisible());
EXPECT_FALSE(test_controller.GetEndVisible());
EXPECT_EQ(0.f, test_controller.GetStartAlpha());
EXPECT_EQ(0.f, test_controller.GetEndAlpha());
// If no drag movement occurs, the handles should reappear after the touch
// is released.
EXPECT_FALSE(controller().WillHandleTouchEvent(event.ReleasePoint()));
EXPECT_THAT(GetAndResetEvents(), IsEmpty());
EXPECT_TRUE(test_controller.GetStartVisible());
EXPECT_TRUE(test_controller.GetEndVisible());
}
TEST_F(TouchSelectionControllerTest, NoLongPressDragIfDisabled) {
// The TouchSelectionController disables longpress drag selection by default.
InitializeControllerWithConfig(kDefaultConfig);
TouchSelectionControllerTestApi test_controller(&controller());
gfx::RectF start_rect(-50, 0, 0, 10);
gfx::RectF end_rect(50, 0, 0, 10);
bool visible = true;
// Start a touch sequence.
MockMotionEvent event;
EXPECT_FALSE(controller().WillHandleTouchEvent(event.PressPoint(0, 0)));
// Activate a longpress-triggered selection.
OnLongPressEvent();
ChangeSelection(start_rect, visible, end_rect, visible);
EXPECT_THAT(GetAndResetEvents(),
ElementsAre(SELECTION_HANDLES_SHOWN));
EXPECT_EQ(start_rect.bottom_left(), GetLastEventStart());
EXPECT_TRUE(test_controller.GetStartVisible());
EXPECT_TRUE(test_controller.GetEndVisible());
EXPECT_EQ(1.f, test_controller.GetStartAlpha());
EXPECT_EQ(1.f, test_controller.GetEndAlpha());
// Subsequent motion of the same touch sequence after longpress shouldn't
// trigger drag selection.
EXPECT_FALSE(controller().WillHandleTouchEvent(event.MovePoint(0, 0, 0)));
EXPECT_THAT(GetAndResetEvents(), IsEmpty());
EXPECT_FALSE(controller().WillHandleTouchEvent(
event.MovePoint(0, 0, kDefaultTapSlop * 10)));
EXPECT_THAT(GetAndResetEvents(), IsEmpty());
// Releasing the touch sequence should have no effect.
EXPECT_FALSE(controller().WillHandleTouchEvent(event.ReleasePoint()));
EXPECT_THAT(GetAndResetEvents(), IsEmpty());
EXPECT_TRUE(test_controller.GetStartVisible());
EXPECT_TRUE(test_controller.GetEndVisible());
EXPECT_EQ(1.f, test_controller.GetStartAlpha());
EXPECT_EQ(1.f, test_controller.GetEndAlpha());
}
TEST_F(TouchSelectionControllerTest, RectBetweenBounds) {
gfx::RectF start_rect(5, 5, 0, 10);
gfx::RectF end_rect(50, 5, 0, 10);
bool visible = true;
EXPECT_EQ(gfx::RectF(), controller().GetRectBetweenBounds());
OnLongPressEvent();
ChangeSelection(start_rect, visible, end_rect, visible);
ASSERT_THAT(GetAndResetEvents(),
ElementsAre(SELECTION_HANDLES_SHOWN));
EXPECT_EQ(gfx::RectF(5, 5, 45, 10), controller().GetRectBetweenBounds());
// The result of |GetRectBetweenBounds| should be available within the
// |OnSelectionEvent| callback, as stored by |GetLastEventBoundsRect()|.
EXPECT_EQ(GetLastEventBoundsRect(), controller().GetRectBetweenBounds());
start_rect.Offset(1, 0);
ChangeSelection(start_rect, visible, end_rect, visible);
ASSERT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLES_MOVED));
EXPECT_EQ(gfx::RectF(6, 5, 44, 10), controller().GetRectBetweenBounds());
EXPECT_EQ(GetLastEventBoundsRect(), controller().GetRectBetweenBounds());
// If only one bound is visible, the selection bounding rect should reflect
// only the visible bound.
ChangeSelection(start_rect, visible, end_rect, false);
ASSERT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLES_MOVED));
EXPECT_EQ(start_rect, controller().GetRectBetweenBounds());
EXPECT_EQ(GetLastEventBoundsRect(), controller().GetRectBetweenBounds());
ChangeSelection(start_rect, false, end_rect, visible);
ASSERT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLES_MOVED));
EXPECT_EQ(end_rect, controller().GetRectBetweenBounds());
EXPECT_EQ(GetLastEventBoundsRect(), controller().GetRectBetweenBounds());
// If both bounds are visible, the full bounding rect should be returned.
ChangeSelection(start_rect, false, end_rect, false);
ASSERT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLES_MOVED));
EXPECT_EQ(gfx::RectF(6, 5, 44, 10), controller().GetRectBetweenBounds());
EXPECT_EQ(GetLastEventBoundsRect(), controller().GetRectBetweenBounds());
ClearSelection();
ASSERT_THAT(GetAndResetEvents(),
ElementsAre(SELECTION_HANDLES_CLEARED));
EXPECT_EQ(gfx::RectF(), controller().GetRectBetweenBounds());
}
TEST_F(TouchSelectionControllerTest, TouchHandleHeight) {
OnLongPressEvent();
SetDraggingEnabled(true);
gfx::RectF start_rect(5, 5, 0, 10);
gfx::RectF end_rect(50, 5, 0, 10);
// Handle height should be zero when there is no selection/ insertion.
EXPECT_EQ(0.f, controller().GetTouchHandleHeight());
// Insertion case - Handle shown.
ChangeInsertion(start_rect, true);
EXPECT_THAT(GetAndResetEvents(), ElementsAre(INSERTION_HANDLE_SHOWN));
EXPECT_NE(0.f, controller().GetTouchHandleHeight());
// Insertion case - Handle moved.
start_rect.Offset(1, 0);
ChangeInsertion(start_rect, true);
EXPECT_THAT(GetAndResetEvents(), ElementsAre(INSERTION_HANDLE_MOVED));
EXPECT_NE(0.f, controller().GetTouchHandleHeight());
ClearInsertion();
EXPECT_THAT(GetAndResetEvents(), ElementsAre(INSERTION_HANDLE_CLEARED));
EXPECT_EQ(0.f, controller().GetTouchHandleHeight());
// Selection case - Start and End are visible.
ChangeSelection(start_rect, true, end_rect, true);
ASSERT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLES_SHOWN));
EXPECT_NE(0.f, controller().GetTouchHandleHeight());
// Selection case - Only Start is visible.
ChangeSelection(start_rect, true, end_rect, false);
ASSERT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLES_MOVED));
EXPECT_NE(0.f, controller().GetTouchHandleHeight());
// Selection case - Only End is visible.
ChangeSelection(start_rect, false, end_rect, true);
ASSERT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLES_MOVED));
EXPECT_NE(0.f, controller().GetTouchHandleHeight());
ClearSelection();
ASSERT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLES_CLEARED));
EXPECT_EQ(0.f, controller().GetTouchHandleHeight());
}
TEST_F(TouchSelectionControllerTest, SelectionNoOrientationChangeWhenSwapped) {
TouchSelectionControllerTestApi test_controller(&controller());
base::TimeTicks event_time = base::TimeTicks::Now();
OnLongPressEvent();
float line_height = 10.f;
gfx::RectF start_rect(50, line_height, 0, line_height);
gfx::RectF end_rect(100, line_height, 0, line_height);
bool visible = true;
ChangeSelection(start_rect, visible, end_rect, visible);
EXPECT_THAT(GetAndResetEvents(),
ElementsAre(SELECTION_HANDLES_SHOWN));
EXPECT_EQ(start_rect.bottom_left(), GetLastEventStart());
EXPECT_EQ(test_controller.GetStartHandleOrientation(),
TouchHandleOrientation::LEFT);
EXPECT_EQ(test_controller.GetEndHandleOrientation(),
TouchHandleOrientation::RIGHT);
SetDraggingEnabled(true);
// Simulate moving the base, not triggering a swap of points.
MockMotionEvent event(MockMotionEvent::Action::DOWN, event_time,
start_rect.x(), start_rect.bottom());
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLE_DRAG_STARTED));
gfx::RectF offset_rect = end_rect;
offset_rect.Offset(gfx::Vector2dF(-10, 0));
ChangeSelection(offset_rect, visible, end_rect, visible);
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLES_MOVED));
EXPECT_EQ(test_controller.GetStartHandleOrientation(),
TouchHandleOrientation::LEFT);
EXPECT_EQ(test_controller.GetEndHandleOrientation(),
TouchHandleOrientation::RIGHT);
event_time += base::Milliseconds(2 * kDefaultTapTimeoutMs);
event = MockMotionEvent(MockMotionEvent::Action::UP, event_time,
offset_rect.x(), offset_rect.bottom());
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLE_DRAG_STOPPED));
EXPECT_EQ(test_controller.GetStartHandleOrientation(),
TouchHandleOrientation::LEFT);
EXPECT_EQ(test_controller.GetEndHandleOrientation(),
TouchHandleOrientation::RIGHT);
// Simulate moving the base, triggering a swap of points.
event = MockMotionEvent(MockMotionEvent::Action::DOWN, event_time,
offset_rect.x(), offset_rect.bottom());
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLE_DRAG_STARTED));
offset_rect.Offset(gfx::Vector2dF(20, 0));
ChangeSelection(end_rect, visible, offset_rect, visible);
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLES_MOVED));
EXPECT_EQ(test_controller.GetStartHandleOrientation(),
TouchHandleOrientation::LEFT);
EXPECT_EQ(test_controller.GetEndHandleOrientation(),
TouchHandleOrientation::LEFT);
event_time += base::Milliseconds(2 * kDefaultTapTimeoutMs);
event = MockMotionEvent(MockMotionEvent::Action::UP, event_time,
offset_rect.x(), offset_rect.bottom());
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLE_DRAG_STOPPED));
EXPECT_EQ(test_controller.GetStartHandleOrientation(),
TouchHandleOrientation::LEFT);
EXPECT_EQ(test_controller.GetEndHandleOrientation(),
TouchHandleOrientation::RIGHT);
// Simulate moving the anchor, not triggering a swap of points.
event = MockMotionEvent(MockMotionEvent::Action::DOWN, event_time,
offset_rect.x(), offset_rect.bottom());
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLE_DRAG_STARTED));
offset_rect.Offset(gfx::Vector2dF(-5, 0));
ChangeSelection(end_rect, visible, offset_rect, visible);
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLES_MOVED));
EXPECT_EQ(test_controller.GetStartHandleOrientation(),
TouchHandleOrientation::LEFT);
EXPECT_EQ(test_controller.GetEndHandleOrientation(),
TouchHandleOrientation::RIGHT);
event_time += base::Milliseconds(2 * kDefaultTapTimeoutMs);
event = MockMotionEvent(MockMotionEvent::Action::UP, event_time,
offset_rect.x(), offset_rect.bottom());
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLE_DRAG_STOPPED));
EXPECT_EQ(test_controller.GetStartHandleOrientation(),
TouchHandleOrientation::LEFT);
EXPECT_EQ(test_controller.GetEndHandleOrientation(),
TouchHandleOrientation::RIGHT);
// Simulate moving the anchor, triggering a swap of points.
event = MockMotionEvent(MockMotionEvent::Action::DOWN, event_time,
offset_rect.x(), offset_rect.bottom());
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLE_DRAG_STARTED));
offset_rect.Offset(gfx::Vector2dF(-15, 0));
ChangeSelection(offset_rect, visible, end_rect, visible);
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLES_MOVED));
EXPECT_EQ(test_controller.GetStartHandleOrientation(),
TouchHandleOrientation::RIGHT);
EXPECT_EQ(test_controller.GetEndHandleOrientation(),
TouchHandleOrientation::RIGHT);
event_time += base::Milliseconds(2 * kDefaultTapTimeoutMs);
event = MockMotionEvent(MockMotionEvent::Action::UP, event_time,
offset_rect.x(), offset_rect.bottom());
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLE_DRAG_STOPPED));
EXPECT_EQ(test_controller.GetStartHandleOrientation(),
TouchHandleOrientation::LEFT);
EXPECT_EQ(test_controller.GetEndHandleOrientation(),
TouchHandleOrientation::RIGHT);
}
TEST_F(TouchSelectionControllerTest, VerticalTextSelectionHandleSwap) {
TouchSelectionControllerTestApi test_controller(&controller());
base::TimeTicks event_time = base::TimeTicks::Now();
OnLongPressEvent();
// Horizontal bounds.
gfx::RectF start_rect(0, 50, 16, 0);
gfx::RectF end_rect(0, 100, 16, 0);
bool visible = true;
ChangeVerticalSelection(start_rect, visible, end_rect, visible);
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLES_SHOWN));
EXPECT_EQ(start_rect.bottom_right(), GetLastEventStart());
EXPECT_EQ(test_controller.GetStartHandleOrientation(),
TouchHandleOrientation::RIGHT);
EXPECT_EQ(test_controller.GetEndHandleOrientation(),
TouchHandleOrientation::LEFT);
SetDraggingEnabled(true);
// Simulate moving the base, triggering a swap of points.
// Start to drag start handle.
MockMotionEvent event(MockMotionEvent::Action::DOWN, event_time,
start_rect.right(), start_rect.bottom());
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLE_DRAG_STARTED));
// Move start handle down below end handle.
gfx::RectF offset_rect = end_rect;
offset_rect.Offset(gfx::Vector2dF(0, 20));
ChangeVerticalSelection(end_rect, visible, offset_rect, visible);
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLES_MOVED));
EXPECT_EQ(test_controller.GetStartHandleOrientation(),
TouchHandleOrientation::RIGHT);
EXPECT_EQ(test_controller.GetEndHandleOrientation(),
TouchHandleOrientation::RIGHT);
// Release.
event_time += base::Milliseconds(2 * kDefaultTapTimeoutMs);
event = MockMotionEvent(MockMotionEvent::Action::UP, event_time,
offset_rect.x(), offset_rect.bottom());
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLE_DRAG_STOPPED));
EXPECT_EQ(test_controller.GetStartHandleOrientation(),
TouchHandleOrientation::RIGHT);
EXPECT_EQ(test_controller.GetEndHandleOrientation(),
TouchHandleOrientation::LEFT);
// Move end handle up.
// Start to drag end handle.
event = MockMotionEvent(MockMotionEvent::Action::DOWN, event_time,
offset_rect.x(), offset_rect.bottom());
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLE_DRAG_STARTED));
// Move up end handle up above the start handle.
offset_rect = start_rect;
ChangeVerticalSelection(offset_rect, visible, end_rect, visible);
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLES_MOVED));
EXPECT_EQ(test_controller.GetStartHandleOrientation(),
TouchHandleOrientation::LEFT);
EXPECT_EQ(test_controller.GetEndHandleOrientation(),
TouchHandleOrientation::LEFT);
// Release.
event_time += base::Milliseconds(2 * kDefaultTapTimeoutMs);
event = MockMotionEvent(MockMotionEvent::Action::UP, event_time,
offset_rect.x(), offset_rect.bottom());
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLE_DRAG_STOPPED));
EXPECT_EQ(test_controller.GetStartHandleOrientation(),
TouchHandleOrientation::RIGHT);
EXPECT_EQ(test_controller.GetEndHandleOrientation(),
TouchHandleOrientation::LEFT);
}
TEST_F(TouchSelectionControllerTest, InsertionUpdateDragPosition) {
base::TimeTicks event_time = base::TimeTicks::Now();
float line_height = 10.f;
gfx::RectF insertion_rect(10, 0, 0, line_height);
bool visible = true;
OnTapEvent();
ChangeInsertion(insertion_rect, visible);
EXPECT_THAT(GetAndResetEvents(), ElementsAre(INSERTION_HANDLE_SHOWN));
EXPECT_EQ(gfx::PointF(0.f, 0.f), GetLastDragUpdatePosition());
SetDraggingEnabled(true);
MockMotionEvent event(MockMotionEvent::Action::DOWN, event_time, 10, 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
event = MockMotionEvent(MockMotionEvent::Action::MOVE, event_time, 10, 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(INSERTION_HANDLE_DRAG_STARTED));
EXPECT_EQ(gfx::PointF(10.f, 5.f), GetLastDragUpdatePosition());
insertion_rect.Offset(1, 0);
ChangeInsertion(insertion_rect, visible);
event = MockMotionEvent(MockMotionEvent::Action::MOVE, event_time, 12, 6);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(INSERTION_HANDLE_MOVED));
// Don't follow the y-coordinate change but only x-coordinate change.
EXPECT_EQ(gfx::PointF(12.f, 5.f), GetLastDragUpdatePosition());
insertion_rect.Offset(0, 1);
event = MockMotionEvent(MockMotionEvent::Action::MOVE, event_time, 11, 6);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
ChangeInsertion(insertion_rect, visible);
event = MockMotionEvent(MockMotionEvent::Action::MOVE, event_time, 11, 7);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(INSERTION_HANDLE_MOVED));
// Don't follow the y-coordinate change.
EXPECT_EQ(gfx::PointF(11.f, 6.f), GetLastDragUpdatePosition());
event_time += base::Milliseconds(2 * kDefaultTapTimeoutMs);
event = MockMotionEvent(MockMotionEvent::Action::UP, event_time, 0, 0);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(INSERTION_HANDLE_DRAG_STOPPED));
SetDraggingEnabled(false);
}
TEST_F(TouchSelectionControllerTest, SelectionUpdateDragPosition) {
base::TimeTicks event_time = base::TimeTicks::Now();
float line_height = 10.f;
gfx::RectF start_rect(10, 0, 0, line_height);
gfx::RectF end_rect(50, 0, 0, line_height);
bool visible = true;
OnLongPressEvent();
ChangeSelection(start_rect, visible, end_rect, visible);
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLES_SHOWN));
EXPECT_EQ(gfx::PointF(0.f, 0.f), GetLastDragUpdatePosition());
// Left handle.
SetDraggingEnabled(true);
MockMotionEvent event(MockMotionEvent::Action::DOWN, event_time, 10, 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
event = MockMotionEvent(MockMotionEvent::Action::MOVE, event_time, 10, 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLE_DRAG_STARTED));
EXPECT_EQ(gfx::PointF(10.f, 5.f), GetLastDragUpdatePosition());
event = MockMotionEvent(MockMotionEvent::Action::MOVE, event_time, 16, 6);
start_rect.Offset(5, 0);
ChangeSelection(start_rect, visible, end_rect, visible);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLES_MOVED));
// Don't follow the y-coordinate change but only x-coordinate change.
EXPECT_EQ(gfx::PointF(16.f, 5.f), GetLastDragUpdatePosition());
event_time += base::Milliseconds(2 * kDefaultTapTimeoutMs);
event = MockMotionEvent(MockMotionEvent::Action::UP, event_time, 15, 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLE_DRAG_STOPPED));
// Right handle.
event = MockMotionEvent(MockMotionEvent::Action::DOWN, event_time, 50, 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
event = MockMotionEvent(MockMotionEvent::Action::MOVE, event_time, 50, 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLE_DRAG_STARTED));
EXPECT_EQ(gfx::PointF(50.f, 5.f), GetLastDragUpdatePosition());
event = MockMotionEvent(MockMotionEvent::Action::MOVE, event_time, 45, 5);
end_rect.Offset(-5, 0);
ChangeSelection(start_rect, visible, end_rect, visible);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLES_MOVED));
EXPECT_EQ(gfx::PointF(45.f, 5.f), GetLastDragUpdatePosition());
event_time += base::Milliseconds(2 * kDefaultTapTimeoutMs);
event = MockMotionEvent(MockMotionEvent::Action::UP, event_time, 45, 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLE_DRAG_STOPPED));
}
TEST_F(TouchSelectionControllerTest, LongpressDragSelectorUpdateDragPosition) {
TouchSelectionController::Config config = kDefaultConfig;
config.enable_longpress_drag_selection = true;
InitializeControllerWithConfig(config);
float line_height = 10.f;
gfx::RectF start_rect(-40, 0, 0, line_height);
gfx::RectF end_rect(50, 0, 0, line_height);
bool visible = true;
// Start a touch sequence.
MockMotionEvent event;
EXPECT_FALSE(controller().WillHandleTouchEvent(event.PressPoint(0, 0)));
// Activate a longpress-triggered selection
OnLongPressEvent();
ChangeSelection(start_rect, visible, end_rect, visible);
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLES_SHOWN));
EXPECT_EQ(start_rect.bottom_left(), GetLastEventStart());
EXPECT_TRUE(controller().WillHandleTouchEvent(event.MovePoint(0, 0, 0)));
EXPECT_THAT(GetAndResetEvents(), IsEmpty());
// Move within tap slop, move haven't started yet.
EXPECT_TRUE(controller().WillHandleTouchEvent(
event.MovePoint(0, 0, kDefaultTapSlop)));
EXPECT_THAT(GetAndResetEvents(), ElementsAre(SELECTION_HANDLE_DRAG_STARTED));
EXPECT_EQ(gfx::PointF(0.f, 0.f), GetLastDragUpdatePosition());
// Movement after the start of drag will be relative to the moved endpoint,
// the actual selection change offset is not necessary equal to the event
// moving distance.
end_rect.Offset(6, 0);
ChangeSelection(start_rect, visible, end_rect, visible);
EXPECT_TRUE(controller().WillHandleTouchEvent(event.MovePoint(0, 5, 0)));
EXPECT_TRUE(GetAndResetSelectionMoved());
EXPECT_EQ(gfx::PointF(56.f, 5.f), GetLastDragUpdatePosition());
// Vertical move
end_rect.Offset(0, 10);
ChangeSelection(start_rect, visible, end_rect, visible);
EXPECT_TRUE(controller().WillHandleTouchEvent(event.MovePoint(0, 5, 10)));
EXPECT_TRUE(GetAndResetSelectionMoved());
EXPECT_EQ(gfx::PointF(56.f, 15.f), GetLastDragUpdatePosition());
// Move start
start_rect.Offset(30, 0);
ChangeSelection(start_rect, visible, end_rect, visible);
EXPECT_TRUE(controller().WillHandleTouchEvent(event.MovePoint(0, 35, 10)));
EXPECT_TRUE(GetAndResetSelectionMoved());
EXPECT_EQ(gfx::PointF(-10.f, 5.f), GetLastDragUpdatePosition());
}
TEST_F(TouchSelectionControllerTest, NoHideActiveInsertionHandle) {
TouchSelectionController::Config config = kDefaultConfig;
config.hide_active_handle = false;
InitializeControllerWithConfig(config);
TouchSelectionControllerTestApi test_controller(&controller());
base::TimeTicks event_time = base::TimeTicks::Now();
float line_height = 10.f;
gfx::RectF insertion_rect(10, 0, 0, line_height);
bool visible = true;
StartTouchEventSequence();
OnTapEvent();
ChangeInsertion(insertion_rect, visible);
EXPECT_THAT(GetAndResetEvents(), ElementsAre(INSERTION_HANDLE_SHOWN));
SetDraggingEnabled(true);
EXPECT_EQ(1.f, test_controller.GetInsertionHandleAlpha());
MockMotionEvent event(MockMotionEvent::Action::DOWN, event_time, 10, 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_EQ(1.f, test_controller.GetInsertionHandleAlpha());
}
TEST_F(TouchSelectionControllerTest, HideActiveInsertionHandle) {
TouchSelectionController::Config config = kDefaultConfig;
config.hide_active_handle = true;
InitializeControllerWithConfig(config);
TouchSelectionControllerTestApi test_controller(&controller());
base::TimeTicks event_time = base::TimeTicks::Now();
float line_height = 10.f;
gfx::RectF insertion_rect(10, 0, 0, line_height);
bool visible = true;
StartTouchEventSequence();
OnTapEvent();
ChangeInsertion(insertion_rect, visible);
EXPECT_THAT(GetAndResetEvents(), ElementsAre(INSERTION_HANDLE_SHOWN));
SetDraggingEnabled(true);
EXPECT_EQ(1.f, test_controller.GetInsertionHandleAlpha());
MockMotionEvent event(MockMotionEvent::Action::DOWN, event_time, 10, 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_EQ(0.f, test_controller.GetInsertionHandleAlpha());
event = MockMotionEvent(MockMotionEvent::Action::MOVE, event_time, 10, 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_EQ(0.f, test_controller.GetInsertionHandleAlpha());
event_time += base::Milliseconds(2 * kDefaultTapTimeoutMs);
// UP will reset the alpha to visible.
event = MockMotionEvent(MockMotionEvent::Action::UP, event_time, 0, 0);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_EQ(1.f, test_controller.GetInsertionHandleAlpha());
}
TEST_F(TouchSelectionControllerTest, NoHideActiveSelectionHandle) {
TouchSelectionController::Config config = kDefaultConfig;
config.hide_active_handle = false;
InitializeControllerWithConfig(config);
TouchSelectionControllerTestApi test_controller(&controller());
base::TimeTicks event_time = base::TimeTicks::Now();
float line_height = 10.f;
gfx::RectF start_rect(10, 0, 0, line_height);
gfx::RectF end_rect(50, 0, 0, line_height);
bool visible = true;
StartTouchEventSequence();
OnLongPressEvent();
ChangeSelection(start_rect, visible, end_rect, visible);
// Start handle.
SetDraggingEnabled(true);
EXPECT_EQ(1.f, test_controller.GetStartAlpha());
EXPECT_EQ(1.f, test_controller.GetEndAlpha());
MockMotionEvent event(MockMotionEvent::Action::DOWN, event_time, 10, 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_EQ(1.f, test_controller.GetStartAlpha());
EXPECT_EQ(1.f, test_controller.GetEndAlpha());
event = MockMotionEvent(MockMotionEvent::Action::UP, event_time, 10, 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_EQ(1.f, test_controller.GetStartAlpha());
EXPECT_EQ(1.f, test_controller.GetEndAlpha());
// End handle.
event = MockMotionEvent(MockMotionEvent::Action::DOWN, event_time, 50, 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_EQ(1.f, test_controller.GetStartAlpha());
EXPECT_EQ(1.f, test_controller.GetEndAlpha());
event_time += base::Milliseconds(2 * kDefaultTapTimeoutMs);
event = MockMotionEvent(MockMotionEvent::Action::UP, event_time, 50, 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_EQ(1.f, test_controller.GetStartAlpha());
EXPECT_EQ(1.f, test_controller.GetEndAlpha());
}
TEST_F(TouchSelectionControllerTest, HideActiveSelectionHandle) {
TouchSelectionController::Config config = kDefaultConfig;
config.hide_active_handle = true;
InitializeControllerWithConfig(config);
TouchSelectionControllerTestApi test_controller(&controller());
base::TimeTicks event_time = base::TimeTicks::Now();
float line_height = 10.f;
gfx::RectF start_rect(10, 0, 0, line_height);
gfx::RectF end_rect(50, 0, 0, line_height);
bool visible = true;
StartTouchEventSequence();
OnLongPressEvent();
ChangeSelection(start_rect, visible, end_rect, visible);
// Start handle.
SetDraggingEnabled(true);
EXPECT_EQ(1.f, test_controller.GetStartAlpha());
EXPECT_EQ(1.f, test_controller.GetEndAlpha());
MockMotionEvent event(MockMotionEvent::Action::DOWN, event_time, 10, 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_EQ(0.f, test_controller.GetStartAlpha());
EXPECT_EQ(1.f, test_controller.GetEndAlpha());
event = MockMotionEvent(MockMotionEvent::Action::MOVE, event_time, 10, 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_EQ(0.f, test_controller.GetStartAlpha());
EXPECT_EQ(1.f, test_controller.GetEndAlpha());
event_time += base::Milliseconds(2 * kDefaultTapTimeoutMs);
// UP will reset alpha to be visible.
event = MockMotionEvent(MockMotionEvent::Action::UP, event_time, 10, 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_EQ(1.f, test_controller.GetStartAlpha());
EXPECT_EQ(1.f, test_controller.GetEndAlpha());
// End handle.
event = MockMotionEvent(MockMotionEvent::Action::DOWN, event_time, 50, 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_EQ(1.f, test_controller.GetStartAlpha());
EXPECT_EQ(0.f, test_controller.GetEndAlpha());
event = MockMotionEvent(MockMotionEvent::Action::MOVE, event_time, 50, 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_EQ(1.f, test_controller.GetStartAlpha());
EXPECT_EQ(0.f, test_controller.GetEndAlpha());
event_time += base::Milliseconds(2 * kDefaultTapTimeoutMs);
// UP will reset alpha to be visible.
event = MockMotionEvent(MockMotionEvent::Action::UP, event_time, 50, 5);
EXPECT_TRUE(controller().WillHandleTouchEvent(event));
EXPECT_EQ(1.f, test_controller.GetStartAlpha());
EXPECT_EQ(1.f, test_controller.GetEndAlpha());
}
TEST_F(TouchSelectionControllerTest, SwipeToMoveCursor_HideHandlesIfShown) {
// Step 1: Extra set-up.
// For Android P+, we need to hide handles while showing magnifier.
TouchSelectionController::Config config = kDefaultConfig;
config.hide_active_handle = true;
InitializeControllerWithConfig(config);
TouchSelectionControllerTestApi test_controller(&controller());
gfx::RectF insertion_rect(5, 5, 0, 10);
bool visible = true;
StartTouchEventSequence();
OnTapEvent();
ChangeInsertion(insertion_rect, visible);
EXPECT_THAT(GetAndResetEvents(), ElementsAre(INSERTION_HANDLE_SHOWN));
EXPECT_EQ(insertion_rect.bottom_left(), GetLastEventStart());
EXPECT_TRUE(test_controller.GetStartVisible());
// Step 2: Swipe-to-move-cursor begins: hide handles.
controller().OnSwipeToMoveCursorBegin();
EXPECT_FALSE(test_controller.GetStartVisible());
// Step 3: Move insertion: still hidden.
gfx::RectF new_insertion_rect(10, 5, 0, 10);
ChangeInsertion(new_insertion_rect, visible);
EXPECT_FALSE(test_controller.GetStartVisible());
// Step 4: Swipe-to-move-cursor ends: show handles.
controller().OnSwipeToMoveCursorEnd();
EXPECT_TRUE(test_controller.GetStartVisible());
}
TEST_F(TouchSelectionControllerTest, SwipeToMoveCursor_HandleWasNotShown) {
// Step 1: Extra set-up.
// For Android P+, we need to hide handles while showing magnifier.
TouchSelectionController::Config config = kDefaultConfig;
config.hide_active_handle = true;
InitializeControllerWithConfig(config);
TouchSelectionControllerTestApi test_controller(&controller());
gfx::RectF insertion_rect(5, 5, 0, 10);
bool visible = true;
StartTouchEventSequence();
OnTapEvent();
ChangeInsertion(insertion_rect, visible);
EXPECT_THAT(GetAndResetEvents(), ElementsAre(INSERTION_HANDLE_SHOWN));
EXPECT_EQ(insertion_rect.bottom_left(), GetLastEventStart());
EXPECT_TRUE(test_controller.GetStartVisible());
// Step 2: Handle is initially hidden, i.e., due to user typing.
controller().HideAndDisallowShowingAutomatically();
EXPECT_FALSE(test_controller.GetStartVisible());
// Step 3: Swipe-to-move-cursor begins: hide handles.
controller().OnSwipeToMoveCursorBegin();
EXPECT_FALSE(test_controller.GetStartVisible());
// Step 4: Move insertion.
// Note that this step is needed to show handle at the end since
// OnInsertionChanged() should activate start_ again, although it will stay
// temporarily hidden.
gfx::RectF new_insertion_rect(10, 5, 0, 10);
ChangeInsertion(new_insertion_rect, visible);
EXPECT_FALSE(test_controller.GetStartVisible());
// Step 5: Swipe-to-move-cursor ends: show handles.
controller().OnSwipeToMoveCursorEnd();
EXPECT_TRUE(test_controller.GetStartVisible());
}
} // namespace
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/touch_selection/touch_selection_controller_unittest.cc | C++ | unknown | 73,982 |
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_TOUCH_SELECTION_TOUCH_SELECTION_DRAGGABLE_H_
#define UI_TOUCH_SELECTION_TOUCH_SELECTION_DRAGGABLE_H_
#include "ui/gfx/geometry/point_f.h"
#include "ui/touch_selection/ui_touch_selection_export.h"
namespace ui {
class MotionEvent;
class TouchSelectionDraggable;
// Interface through which TouchSelectionDraggable manipulates the selection.
class UI_TOUCH_SELECTION_EXPORT TouchSelectionDraggableClient {
public:
virtual ~TouchSelectionDraggableClient() {}
virtual void OnDragBegin(const TouchSelectionDraggable& draggable,
const gfx::PointF& start_position) = 0;
virtual void OnDragUpdate(const TouchSelectionDraggable& draggable,
const gfx::PointF& new_position) = 0;
virtual void OnDragEnd(const TouchSelectionDraggable& draggable) = 0;
virtual bool IsWithinTapSlop(const gfx::Vector2dF& delta) const = 0;
#ifdef OHOS_CLIPBOARD
virtual void UpdateSelectionChanged(const TouchSelectionDraggable& draggable) = 0;
#endif
};
// Generic interface for entities that manipulate the selection via dragging.
class UI_TOUCH_SELECTION_EXPORT TouchSelectionDraggable {
public:
// GENERATED_JAVA_ENUM_PACKAGE: org.chromium.ui.touch_selection
// GENERATED_JAVA_CLASS_NAME_OVERRIDE: TouchSelectionDraggableType
enum class Type {
kNone,
kTouchHandle,
kLongpress,
};
protected:
virtual ~TouchSelectionDraggable() {}
// Offers a touch sequence to the draggable target. Returns true if the event
// was consumed, in which case the caller should cease further handling.
virtual bool WillHandleTouchEvent(const ui::MotionEvent& event) = 0;
// Whether a drag is active OR being detected for the current touch sequence.
virtual bool IsActive() const = 0;
};
} // namespace ui
#endif // UI_TOUCH_SELECTION_TOUCH_SELECTION_DRAGGABLE_H_
| Zhao-PengFei35/chromium_src_4 | ui/touch_selection/touch_selection_draggable.h | C++ | unknown | 1,981 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/touch_selection/touch_selection_magnifier_runner.h"
#include "base/check_op.h"
namespace ui {
namespace {
TouchSelectionMagnifierRunner* g_touch_selection_magnifier_runner = nullptr;
} // namespace
TouchSelectionMagnifierRunner::~TouchSelectionMagnifierRunner() {
DCHECK_EQ(this, g_touch_selection_magnifier_runner);
g_touch_selection_magnifier_runner = nullptr;
}
TouchSelectionMagnifierRunner* TouchSelectionMagnifierRunner::GetInstance() {
return g_touch_selection_magnifier_runner;
}
TouchSelectionMagnifierRunner::TouchSelectionMagnifierRunner() {
DCHECK(!g_touch_selection_magnifier_runner);
g_touch_selection_magnifier_runner = this;
}
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/touch_selection/touch_selection_magnifier_runner.cc | C++ | unknown | 839 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_TOUCH_SELECTION_TOUCH_SELECTION_MAGNIFIER_RUNNER_H_
#define UI_TOUCH_SELECTION_TOUCH_SELECTION_MAGNIFIER_RUNNER_H_
#include "ui/touch_selection/ui_touch_selection_export.h"
namespace aura {
class Window;
} // namespace aura
namespace gfx {
class PointF;
} // namespace gfx
namespace ui {
// An interface for the singleton object responsible for running the touch
// selection magnifier.
class UI_TOUCH_SELECTION_EXPORT TouchSelectionMagnifierRunner {
public:
TouchSelectionMagnifierRunner(const TouchSelectionMagnifierRunner&) = delete;
TouchSelectionMagnifierRunner& operator=(
const TouchSelectionMagnifierRunner&) = delete;
virtual ~TouchSelectionMagnifierRunner();
static TouchSelectionMagnifierRunner* GetInstance();
// Creates and shows a magnifier, or updates the running magnifier's position
// if the runner is already showing a magnifier. `position` specifies
// coordinates in the context window.
virtual void ShowMagnifier(aura::Window* context,
const gfx::PointF& position) = 0;
// Closes and stops showing the running magnifier.
virtual void CloseMagnifier() = 0;
// Returns true if the runner is currently showing a magnifier.
virtual bool IsRunning() const = 0;
protected:
TouchSelectionMagnifierRunner();
};
} // namespace ui
#endif // UI_TOUCH_SELECTION_TOUCH_SELECTION_MAGNIFIER_RUNNER_H_
| Zhao-PengFei35/chromium_src_4 | ui/touch_selection/touch_selection_magnifier_runner.h | C++ | unknown | 1,543 |
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/touch_selection/touch_selection_menu_runner.h"
#include "base/check_op.h"
namespace ui {
namespace {
TouchSelectionMenuRunner* g_touch_selection_menu_runner = nullptr;
} // namespace
TouchSelectionMenuClient::TouchSelectionMenuClient() = default;
TouchSelectionMenuClient::~TouchSelectionMenuClient() = default;
base::WeakPtr<TouchSelectionMenuClient> TouchSelectionMenuClient::GetWeakPtr() {
return weak_factory_.GetWeakPtr();
}
TouchSelectionMenuRunner::~TouchSelectionMenuRunner() {
DCHECK_EQ(this, g_touch_selection_menu_runner);
g_touch_selection_menu_runner = nullptr;
}
TouchSelectionMenuRunner* TouchSelectionMenuRunner::GetInstance() {
return g_touch_selection_menu_runner;
}
TouchSelectionMenuRunner::TouchSelectionMenuRunner() {
DCHECK(!g_touch_selection_menu_runner);
g_touch_selection_menu_runner = this;
}
} // namespace ui
| Zhao-PengFei35/chromium_src_4 | ui/touch_selection/touch_selection_menu_runner.cc | C++ | unknown | 1,020 |
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_TOUCH_SELECTION_TOUCH_SELECTION_MENU_RUNNER_H_
#define UI_TOUCH_SELECTION_TOUCH_SELECTION_MENU_RUNNER_H_
#include "base/memory/weak_ptr.h"
#include "base/strings/string_util.h"
#include "ui/touch_selection/ui_touch_selection_export.h"
namespace aura {
class Window;
}
namespace gfx {
class Rect;
class Size;
}
namespace ui {
// Client interface for TouchSelectionMenuRunner.
class UI_TOUCH_SELECTION_EXPORT TouchSelectionMenuClient {
public:
TouchSelectionMenuClient();
virtual ~TouchSelectionMenuClient();
virtual bool IsCommandIdEnabled(int command_id) const = 0;
virtual void ExecuteCommand(int command_id, int event_flags) = 0;
// Called when the quick menu needs to run a context menu. Depending on the
// implementation, this may run the context menu synchronously, or request the
// menu to show up in which case the menu will run asynchronously at a later
// time.
virtual void RunContextMenu() = 0;
// Whether the Quick Menu should be opened.
virtual bool ShouldShowQuickMenu() = 0;
// Returns the current text selection.
virtual std::u16string GetSelectedText() = 0;
// Returns a WeakPtr to this client. `TouchSelectionMenuRunnerChromeOS`
// performs asynchronous work before showing the menu. The client can be
// deleted during that time window. See https://crbug.com/1146270
base::WeakPtr<TouchSelectionMenuClient> GetWeakPtr();
private:
base::WeakPtrFactory<TouchSelectionMenuClient> weak_factory_{this};
};
// An interface for the singleton object responsible for running touch selection
// quick menu.
class UI_TOUCH_SELECTION_EXPORT TouchSelectionMenuRunner {
public:
TouchSelectionMenuRunner(const TouchSelectionMenuRunner&) = delete;
TouchSelectionMenuRunner& operator=(const TouchSelectionMenuRunner&) = delete;
virtual ~TouchSelectionMenuRunner();
static TouchSelectionMenuRunner* GetInstance();
// Checks whether there is any command available to show in the menu.
virtual bool IsMenuAvailable(
const TouchSelectionMenuClient* client) const = 0;
// Creates and displays the quick menu, if there is any command available.
// |anchor_rect| is in screen coordinates.
virtual void OpenMenu(base::WeakPtr<TouchSelectionMenuClient> client,
const gfx::Rect& anchor_rect,
const gfx::Size& handle_image_size,
aura::Window* context) = 0;
virtual void CloseMenu() = 0;
virtual bool IsRunning() const = 0;
protected:
TouchSelectionMenuRunner();
};
} // namespace ui
#endif // UI_TOUCH_SELECTION_TOUCH_SELECTION_MENU_RUNNER_H_
| Zhao-PengFei35/chromium_src_4 | ui/touch_selection/touch_selection_menu_runner.h | C++ | unknown | 2,756 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_TOUCH_SELECTION_UI_TOUCH_SELECTION_EXPORT_H_
#define UI_TOUCH_SELECTION_UI_TOUCH_SELECTION_EXPORT_H_
// Defines UI_TOUCH_SELECTION_EXPORT so that functionality implemented by the UI
// touch selection module can be exported to consumers.
#include "build/build_config.h"
#if defined(COMPONENT_BUILD)
#if defined(WIN32)
#if defined(UI_TOUCH_SELECTION_IMPLEMENTATION)
#define UI_TOUCH_SELECTION_EXPORT __declspec(dllexport)
#else
#define UI_TOUCH_SELECTION_EXPORT __declspec(dllimport)
#endif
#else // !defined(WIN32)
#if defined(UI_TOUCH_SELECTION_IMPLEMENTATION)
#define UI_TOUCH_SELECTION_EXPORT __attribute__((visibility("default")))
#else
#define UI_TOUCH_SELECTION_EXPORT
#endif
#endif
#else // !defined(COMPONENT_BUILD)
#define UI_TOUCH_SELECTION_EXPORT
#endif
#endif // UI_TOUCH_SELECTION_UI_TOUCH_SELECTION_EXPORT_H_
| Zhao-PengFei35/chromium_src_4 | ui/touch_selection/ui_touch_selection_export.h | C | unknown | 993 |
include_rules = [
"+ash/constants",
"+cc/paint",
"+chromeos/constants",
"+components/crash/core/common/crash_key.h",
"+components/remote_cocoa",
"+components/url_formatter",
"+components/vector_icons",
"+mojo/public/cpp/bindings",
"+skia/ext",
"+third_party/iaccessible2",
"+third_party/skia",
"+ui/accessibility",
"+ui/aura",
"+ui/base",
"+ui/color",
"+ui/compositor",
"+ui/display",
"+ui/events",
"+ui/gfx",
"+ui/gl/test/gl_surface_test_support.h", # To initialize GL for tests.
"+ui/linux",
"+ui/lottie",
"+ui/native_theme",
"+ui/ozone/buildflags.h",
"+ui/ozone/public",
"+ui/platform_window",
"+ui/resources/grit/ui_resources.h",
"+ui/strings/grit/ui_strings.h",
"+ui/touch_selection",
"+ui/wm/core",
"+ui/wm/public",
]
specific_include_rules = {
"examples_browser_main_parts\.cc": [
"+ui/wm/test"
],
"highlight_border\.cc": [
"+ui/chromeos/styles/cros_tokens_color_mappings.h"
],
"run_all_unittests_main\.cc": [
"+mojo/core/embedder",
],
"views_perftests\.cc": [
"+mojo/core/embedder",
],
"view_unittest\.cc": [
"+cc/playback",
"+components/viz/common",
],
"views_test_suite\.cc": [
"+gpu/ipc/service",
"+ui/gl",
],
".*test\.cc": [
"+cc/base",
"+cc/test",
]
}
| Zhao-PengFei35/chromium_src_4 | ui/views/DEPS | Python | unknown | 1,297 |
# Copyright 2019 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Presubmit script for changes affecting //ui/views.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details about the presubmit API built into depot_tools.
"""
USE_PYTHON3 = True
PRESUBMIT_VERSION = '2.0.0'
INCLUDE_CPP_FILES_ONLY = (
r'.*\.(cc|h)$',
)
def CheckChangeLintsClean(input_api, output_api):
"""Makes sure that the change is cpplint clean."""
sources = lambda x: input_api.FilterSourceFile(
x, files_to_check=INCLUDE_CPP_FILES_ONLY,
files_to_skip=input_api.DEFAULT_FILES_TO_SKIP)
return input_api.canned_checks.CheckChangeLintsClean(
input_api, output_api, sources, lint_filters=[], verbose_level=1)
| Zhao-PengFei35/chromium_src_4 | ui/views/PRESUBMIT.py | Python | unknown | 817 |
include_rules = [
"+third_party/iaccessible2",
]
specific_include_rules = {
"ax_system_caret_win_interactive_uitest\.cc": [
"+mojo/core/embedder",
]
}
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/DEPS | Python | unknown | 162 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/accessibility/accessibility_alert_window.h"
#include "base/strings/utf_string_conversions.h"
#include "ui/accessibility/aura/aura_window_properties.h"
#include "ui/aura/window.h"
#include "ui/compositor/layer_type.h"
#include "ui/views/accessibility/ax_aura_obj_cache.h"
#include "ui/views/accessibility/view_accessibility.h"
namespace views {
AccessibilityAlertWindow::AccessibilityAlertWindow(aura::Window* parent,
views::AXAuraObjCache* cache)
: cache_(cache) {
CHECK(parent);
alert_window_ = std::make_unique<aura::Window>(
nullptr, aura::client::WINDOW_TYPE_UNKNOWN);
alert_window_->set_owned_by_parent(false);
alert_window_->Init(ui::LayerType::LAYER_NOT_DRAWN);
alert_window_->SetProperty(ui::kAXRoleOverride, ax::mojom::Role::kAlert);
parent->AddChild(alert_window_.get());
observation_.Observe(aura::Env::GetInstance());
}
AccessibilityAlertWindow::~AccessibilityAlertWindow() = default;
void AccessibilityAlertWindow::HandleAlert(const std::string& alert_string) {
if (!alert_window_ || !alert_window_->parent())
return;
alert_window_->SetTitle(base::UTF8ToUTF16(alert_string));
cache_->FireEvent(cache_->GetOrCreate(alert_window_.get()),
ax::mojom::Event::kAlert);
}
void AccessibilityAlertWindow::OnWillDestroyEnv() {
observation_.Reset();
alert_window_.reset();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/accessibility_alert_window.cc | C++ | unknown | 1,579 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_ACCESSIBILITY_ACCESSIBILITY_ALERT_WINDOW_H_
#define UI_VIEWS_ACCESSIBILITY_ACCESSIBILITY_ALERT_WINDOW_H_
#include <memory>
#include <string>
#include "base/gtest_prod_util.h"
#include "base/memory/raw_ptr.h"
#include "base/scoped_observation.h"
#include "ui/aura/env.h"
#include "ui/aura/env_observer.h"
#include "ui/views/views_export.h"
namespace aura {
class Window;
}
namespace views {
class AXAuraObjCache;
// This class provides a caller a way to alert an accessibility client such as
// ChromeVox with a text string without a backing visible window or view.
class VIEWS_EXPORT AccessibilityAlertWindow : public aura::EnvObserver {
public:
// |parent| is the window where a child alert window will be added.
AccessibilityAlertWindow(aura::Window* parent, views::AXAuraObjCache* cache);
AccessibilityAlertWindow(const AccessibilityAlertWindow&) = delete;
AccessibilityAlertWindow& operator=(const AccessibilityAlertWindow&) = delete;
~AccessibilityAlertWindow() override;
// Triggers an alert with the text |alert_string| to be sent to an
// accessibility client.
void HandleAlert(const std::string& alert_string);
private:
FRIEND_TEST_ALL_PREFIXES(AccessibilityAlertWindowTest, HandleAlert);
FRIEND_TEST_ALL_PREFIXES(AccessibilityAlertWindowTest, OnWillDestroyEnv);
// aura::EnvObserver:
void OnWillDestroyEnv() override;
// The child alert window.
std::unique_ptr<aura::Window> alert_window_;
// The accessibility cache associated with |alert_window_|.
raw_ptr<views::AXAuraObjCache, DanglingUntriaged> cache_;
base::ScopedObservation<aura::Env, aura::EnvObserver> observation_{this};
};
} // namespace views
#endif // UI_VIEWS_ACCESSIBILITY_ACCESSIBILITY_ALERT_WINDOW_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/accessibility_alert_window.h | C++ | unknown | 1,891 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/accessibility/accessibility_alert_window.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/aura/window.h"
#include "ui/compositor/layer_type.h"
#include "ui/views/accessibility/ax_aura_obj_cache.h"
#include "ui/views/accessibility/ax_aura_obj_wrapper.h"
#include "ui/views/test/views_test_base.h"
namespace views {
class FakeAXAuraObjCacheDelegate : public AXAuraObjCache::Delegate {
public:
FakeAXAuraObjCacheDelegate() = default;
FakeAXAuraObjCacheDelegate(const FakeAXAuraObjCacheDelegate&) = delete;
FakeAXAuraObjCacheDelegate& operator=(const FakeAXAuraObjCacheDelegate&) =
delete;
~FakeAXAuraObjCacheDelegate() override = default;
void OnChildWindowRemoved(AXAuraObjWrapper* parent) override {}
void OnEvent(AXAuraObjWrapper* aura_obj,
ax::mojom::Event event_type) override {
if (event_type == ax::mojom::Event::kAlert)
count_++;
}
int count() { return count_; }
void set_count(int count) { count_ = count; }
private:
int count_ = 0;
};
class AccessibilityAlertWindowTest : public ViewsTestBase {
public:
AccessibilityAlertWindowTest() = default;
AccessibilityAlertWindowTest(const AccessibilityAlertWindowTest&) = delete;
AccessibilityAlertWindowTest& operator=(const AccessibilityAlertWindowTest&) =
delete;
~AccessibilityAlertWindowTest() override = default;
protected:
void SetUp() override {
ViewsTestBase::SetUp();
parent_ = std::make_unique<aura::Window>(nullptr);
parent_->Init(ui::LAYER_SOLID_COLOR);
}
std::unique_ptr<aura::Window> parent_;
AXAuraObjCache cache;
};
TEST_F(AccessibilityAlertWindowTest, HandleAlert) {
FakeAXAuraObjCacheDelegate delegate;
cache.SetDelegate(&delegate);
AccessibilityAlertWindow window(parent_.get(), &cache);
window.HandleAlert("test");
EXPECT_EQ(1, delegate.count());
delegate.set_count(0);
window.OnWillDestroyEnv();
window.HandleAlert("test");
EXPECT_EQ(0, delegate.count());
}
TEST_F(AccessibilityAlertWindowTest, OnWillDestroyEnv) {
AccessibilityAlertWindow window(parent_.get(), &cache);
window.OnWillDestroyEnv();
EXPECT_FALSE(window.observation_.IsObserving());
EXPECT_FALSE(window.alert_window_);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/accessibility_alert_window_unittest.cc | C++ | unknown | 2,432 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/accessibility/accessibility_paint_checks.h"
#include <string>
#include "build/chromeos_buildflags.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/base/class_property.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/view.h"
#include "ui/views/view_utils.h"
#include "ui/views/widget/widget.h"
namespace views {
DEFINE_UI_CLASS_PROPERTY_KEY(bool, kSkipAccessibilityPaintChecks, false)
void RunAccessibilityPaintChecks(View* view) {
// Note that none of these checks run if DCHECKs are off. Dead-code
// elimination should remove the following. This is done instead of #ifs to
// make sure that the code compiles regardless of DCHECK availability.
if (!DCHECK_IS_ON())
return;
if (view->GetProperty(kSkipAccessibilityPaintChecks))
return;
// Get accessible node data from ViewAccessibility instead of View, because
// some additional fields are processed and set there.
ui::AXNodeData node_data;
view->GetViewAccessibility().GetAccessibleNodeData(&node_data);
// No checks for unfocusable items yet.
if (!node_data.HasState(ax::mojom::State::kFocusable))
return;
// TODO(crbug.com/1218186): Enable these DCHECKs on ash. One of the current
// failures seem to be SearchResultPageView marking itself as ignored
// (temporarily), which marks focusable children as ignored. One way of enabling
// these here would be to turn `kSkipAccessibilityPaintChecks` into a cascading
// property or introduce a cascading property specifically for the current
// misbehavior in SearchResultPageView to be able to suppress that and enable
// the DCHECK elsewhere.
#if !BUILDFLAG(IS_CHROMEOS_ASH)
DCHECK(!node_data.HasState(ax::mojom::State::kIgnored))
<< "View is focusable and should not be ignored.\n"
<< GetViewDebugInfo(view);
DCHECK(!node_data.IsInvisible())
<< "View is focusable and should not be invisible.\n"
<< GetViewDebugInfo(view);
#endif // !BUILDFLAG(IS_CHROMEOS_ASH)
// ViewAccessibility::GetAccessibleNodeData currently returns early, after
// setting the role to kUnknown, the NameFrom to kAttributeExplicitlyEmpty,
// and adding the kDisabled restriction, if the Widget is closed.
if (node_data.GetRestriction() != ax::mojom::Restriction::kDisabled) {
// Focusable views should have a valid role.
DCHECK(node_data.role != ax::mojom::Role::kNone &&
node_data.role != ax::mojom::Role::kUnknown)
<< "View is focusable but lacks a valid role.\n"
<< GetViewDebugInfo(view);
}
// Focusable nodes must have an accessible name, otherwise screen reader users
// will not know what they landed on. For example, the reload button should
// have an accessible name of "Reload".
// Exceptions:
// 1) Textfields can set the placeholder string attribute.
// 2) Explicitly setting the name to "" is allowed if the view uses
// AXNodedata.SetNameExplicitlyEmpty().
// It has a name, we're done.
if (!node_data.GetStringAttribute(ax::mojom::StringAttribute::kName).empty())
return;
// Text fields are allowed to have a placeholder instead.
if (node_data.role == ax::mojom::Role::kTextField &&
!node_data.GetStringAttribute(ax::mojom::StringAttribute::kPlaceholder)
.empty()) {
return;
}
// Finally, a view is allowed to explicitly state that it has no name.
DCHECK_EQ(node_data.GetNameFrom(),
ax::mojom::NameFrom::kAttributeExplicitlyEmpty)
<< "View is focusable but has no accessible name or placeholder, and is "
"not explicitly marked as empty. The accessible name is spoken by "
"screen readers to end users. Thus if this is production code, the "
"accessible name should be localized.\n"
<< GetViewDebugInfo(view);
}
void RunAccessibilityPaintChecksRecursive(View* view) {
RunAccessibilityPaintChecks(view);
for (auto* v : view->children())
RunAccessibilityPaintChecksRecursive(v);
}
void RunAccessibilityPaintChecks(Widget* widget) {
RunAccessibilityPaintChecksRecursive(widget->GetRootView());
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/accessibility_paint_checks.cc | C++ | unknown | 4,294 |
// Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_ACCESSIBILITY_ACCESSIBILITY_PAINT_CHECKS_H_
#define UI_VIEWS_ACCESSIBILITY_ACCESSIBILITY_PAINT_CHECKS_H_
#include "ui/base/class_property.h"
#include "ui/views/views_export.h"
namespace views {
class View;
class Widget;
// This runs DCHECKs related to the view's state when painting. Generally, when
// a View is ready to be displayed to the user it should also be accessible.
VIEWS_EXPORT void RunAccessibilityPaintChecks(View* view);
// Runs the paint checks recursively starting from the Widget's RootView.
VIEWS_EXPORT void RunAccessibilityPaintChecks(Widget* widget);
// Skip accessibility paint checks on a specific View.
// TODO(pbos): Remove this key. Do not add new uses to it, instead make sure
// that the offending View is fixed.
VIEWS_EXPORT extern const ui::ClassProperty<bool>* const
kSkipAccessibilityPaintChecks;
} // namespace views
#endif // UI_VIEWS_ACCESSIBILITY_ACCESSIBILITY_PAINT_CHECKS_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/accessibility_paint_checks.h | C++ | unknown | 1,089 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/accessibility/accessibility_paint_checks.h"
#include <memory>
#include <utility>
#include "base/strings/utf_string_conversions.h"
#include "base/test/gtest_util.h"
#include "ui/views/controls/button/image_button.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
namespace views {
using AccessibilityPaintChecksTest = ViewsTestBase;
// Test that a view that is not accessible will fail the accessibility audit.
TEST_F(AccessibilityPaintChecksTest, VerifyAccessibilityCheckerFailAndPass) {
// Create containing widget.
Widget widget;
Widget::InitParams params =
Widget::InitParams(Widget::InitParams::TYPE_WINDOW);
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.bounds = gfx::Rect(0, 0, 650, 650);
params.context = GetContext();
widget.Init(std::move(params));
widget.Show();
// Add the button.
auto* button =
widget.GetContentsView()->AddChildView(std::make_unique<ImageButton>());
// Accessibility test should pass as it is focusable but has a name.
button->SetFocusBehavior(View::FocusBehavior::ALWAYS);
button->SetAccessibleName(u"Some name");
RunAccessibilityPaintChecks(&widget);
// Accessibility test should pass as it has no name but is not focusable.
button->SetFocusBehavior(View::FocusBehavior::NEVER);
button->SetAccessibleName(u"");
RunAccessibilityPaintChecks(&widget);
// Accessibility test should fail as it has no name and is focusable.
button->SetFocusBehavior(View::FocusBehavior::ALWAYS);
EXPECT_DCHECK_DEATH_WITH(RunAccessibilityPaintChecks(&widget), "name");
// Restore the name of the button so that it is not the source of failure.
button->SetAccessibleName(u"Some name");
// Accessibility test should fail if the focusable view lacks a valid role.
auto* generic_view =
widget.GetContentsView()->AddChildView(std::make_unique<View>());
generic_view->SetFocusBehavior(View::FocusBehavior::ALWAYS);
EXPECT_DCHECK_DEATH_WITH(RunAccessibilityPaintChecks(&widget), "role");
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/accessibility_paint_checks_unittest.cc | C++ | unknown | 2,247 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/accessibility/ax_aura_obj_cache.h"
#include <utility>
#include "base/containers/contains.h"
#include "base/memory/raw_ptr.h"
#include "base/strings/string_util.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_node.h"
#include "ui/aura/client/aura_constants.h"
#include "ui/aura/client/focus_client.h"
#include "ui/aura/window.h"
#include "ui/aura/window_observer.h"
#include "ui/views/accessibility/ax_aura_obj_wrapper.h"
#include "ui/views/accessibility/ax_view_obj_wrapper.h"
#include "ui/views/accessibility/ax_virtual_view.h"
#include "ui/views/accessibility/ax_virtual_view_wrapper.h"
#include "ui/views/accessibility/ax_widget_obj_wrapper.h"
#include "ui/views/accessibility/ax_window_obj_wrapper.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
namespace views {
namespace {
aura::client::FocusClient* GetFocusClient(aura::Window* root_window) {
if (!root_window)
return nullptr;
return aura::client::GetFocusClient(root_window);
}
} // namespace
// A class which observes the destruction of the a11y override window. Done here
// since adding Window and WindowObserver includes are not allowed in the
// header.
class AXAuraObjCache::A11yOverrideWindowObserver : public aura::WindowObserver {
public:
explicit A11yOverrideWindowObserver(AXAuraObjCache* cache) : cache_(cache) {}
A11yOverrideWindowObserver(const A11yOverrideWindowObserver&) = delete;
A11yOverrideWindowObserver& operator=(const A11yOverrideWindowObserver&) =
delete;
~A11yOverrideWindowObserver() override = default;
void Observe() {
observer_.Reset();
aura::Window* a11y_override_window = cache_->a11y_override_window_;
if (a11y_override_window)
observer_.Observe(a11y_override_window);
}
private:
// aura::WindowObserver:
void OnWindowDestroying(aura::Window* window) override {
DCHECK(window);
DCHECK_EQ(cache_->a11y_override_window_, window);
cache_->a11y_override_window_ = nullptr;
observer_.Reset();
}
// Pointer to the AXAuraObjCache object that owns |this|. Guaranteed not to be
// null for the lifetime of this.
const raw_ptr<AXAuraObjCache> cache_;
base::ScopedObservation<aura::Window, aura::WindowObserver> observer_{this};
};
AXAuraObjWrapper* AXAuraObjCache::GetOrCreate(View* view) {
// Avoid problems with transient focus events. https://crbug.com/729449
if (!view->GetWidget())
return nullptr;
DCHECK(view_to_id_map_.find(view) != view_to_id_map_.end() ||
// This is either a new view or we're erroneously here during ~View.
view->life_cycle_state() == View::LifeCycleState::kAlive);
return CreateInternal<AXViewObjWrapper>(view, &view_to_id_map_);
}
AXAuraObjWrapper* AXAuraObjCache::GetOrCreate(AXVirtualView* virtual_view) {
if (!virtual_view->GetOwnerView() ||
!virtual_view->GetOwnerView()->GetWidget())
return nullptr;
return CreateInternal<AXVirtualViewWrapper>(virtual_view,
&virtual_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_);
}
void AXAuraObjCache::CreateOrReplace(std::unique_ptr<AXAuraObjWrapper> obj) {
cache_[obj->GetUniqueId()] = std::move(obj);
}
int32_t AXAuraObjCache::GetID(View* view) const {
return GetIDInternal(view, view_to_id_map_);
}
int32_t AXAuraObjCache::GetID(AXVirtualView* virtual_view) const {
return GetIDInternal(virtual_view, virtual_view_to_id_map_);
}
int32_t AXAuraObjCache::GetID(Widget* widget) const {
return GetIDInternal(widget, widget_to_id_map_);
}
int32_t AXAuraObjCache::GetID(aura::Window* window) const {
return GetIDInternal(window, window_to_id_map_);
}
void AXAuraObjCache::Remove(View* view) {
RemoveInternal(view, &view_to_id_map_);
}
void AXAuraObjCache::Remove(AXVirtualView* virtual_view) {
RemoveInternal(virtual_view, &virtual_view_to_id_map_);
}
void AXAuraObjCache::RemoveViewSubtree(View* view) {
Remove(view);
for (View* child : view->children())
RemoveViewSubtree(child);
}
void AXAuraObjCache::Remove(Widget* widget) {
RemoveInternal(widget, &widget_to_id_map_);
// When an entire widget is deleted, it doesn't always send a notification
// on each of its views, so we need to explore them recursively.
auto* view = widget->GetRootView();
if (view)
RemoveViewSubtree(view);
}
void AXAuraObjCache::Remove(aura::Window* window, aura::Window* parent) {
int id = GetIDInternal(parent, window_to_id_map_);
AXAuraObjWrapper* parent_window_obj = Get(id);
RemoveInternal(window, &window_to_id_map_);
if (parent && delegate_)
delegate_->OnChildWindowRemoved(parent_window_obj);
if (focused_window_ == window)
focused_window_ = nullptr;
}
AXAuraObjWrapper* AXAuraObjCache::Get(int32_t id) {
auto it = cache_.find(id);
return it != cache_.end() ? it->second.get() : nullptr;
}
void AXAuraObjCache::GetTopLevelWindows(
std::vector<AXAuraObjWrapper*>* children) {
for (aura::Window* root : root_windows_)
children->push_back(GetOrCreate(root));
}
AXAuraObjWrapper* AXAuraObjCache::GetFocus() {
View* focused_view = GetFocusedView();
while (focused_view &&
(focused_view->GetViewAccessibility().IsIgnored() ||
focused_view->GetViewAccessibility().propagate_focus_to_ancestor())) {
focused_view = focused_view->parent();
}
if (!focused_view)
return nullptr;
if (focused_view->GetViewAccessibility().FocusedVirtualChild()) {
return focused_view->GetViewAccessibility()
.FocusedVirtualChild()
->GetOrCreateWrapper(this);
}
return GetOrCreate(focused_view);
}
void AXAuraObjCache::OnFocusedViewChanged() {
View* view = GetFocusedView();
if (view)
view->NotifyAccessibilityEvent(ax::mojom::Event::kFocus, true);
}
void AXAuraObjCache::FireEvent(AXAuraObjWrapper* aura_obj,
ax::mojom::Event event_type) {
if (delegate_)
delegate_->OnEvent(aura_obj, event_type);
}
AXAuraObjCache::AXAuraObjCache()
: a11y_override_window_observer_(
std::make_unique<A11yOverrideWindowObserver>(this)) {}
AXAuraObjCache::~AXAuraObjCache() {
// Remove all focus observers from |root_windows_|.
for (aura::Window* window : root_windows_) {
aura::client::FocusClient* focus_client = GetFocusClient(window);
if (focus_client)
focus_client->RemoveObserver(this);
}
root_windows_.clear();
for (auto& entry : virtual_view_to_id_map_)
entry.first->set_cache(nullptr);
}
View* AXAuraObjCache::GetFocusedView() {
Widget* focused_widget = focused_widget_for_testing_;
aura::Window* focused_window =
focused_widget ? focused_widget->GetNativeWindow() : nullptr;
if (!focused_widget) {
// Uses the a11y override window for focus if it exists, otherwise gets the
// last focused window.
focused_window = a11y_override_window_ ? a11y_override_window_.get()
: focused_window_.get();
// Finally, fallback to searching for the focus.
if (!focused_window) {
for (aura::Window* window : root_windows_) {
auto* focus_client = GetFocusClient(window);
if (focus_client &&
(focused_window = GetFocusClient(window)->GetFocusedWindow())) {
break;
}
}
}
if (!focused_window)
return nullptr;
focused_widget = Widget::GetWidgetForNativeView(focused_window);
while (!focused_widget) {
focused_window = focused_window->parent();
if (!focused_window)
break;
focused_widget = Widget::GetWidgetForNativeView(focused_window);
}
}
if (!focused_widget)
return nullptr;
FocusManager* focus_manager = focused_widget->GetFocusManager();
if (!focus_manager)
return nullptr;
View* focused_view = focus_manager->GetFocusedView();
if (focused_view)
return focused_view;
// No view has focus, but a child tree might have focus.
if (focused_window) {
auto* non_client = focused_widget->non_client_view();
auto* client = non_client ? non_client->client_view() : nullptr;
if (client && !client->children().empty()) {
const ViewAccessibility& host_accessibility =
client->children().front()->GetViewAccessibility();
ui::AXNodeData host_data;
host_accessibility.GetAccessibleNodeData(&host_data);
if (host_accessibility.GetChildTreeID() != ui::AXTreeIDUnknown() ||
!host_data
.GetStringAttribute(
ax::mojom::StringAttribute::kChildTreeNodeAppId)
.empty()) {
return client->children().front();
}
}
}
return focused_widget->GetRootView();
}
void AXAuraObjCache::OnWindowFocused(aura::Window* gained_focus,
aura::Window* lost_focus) {
focused_window_ = gained_focus;
OnFocusedViewChanged();
}
void AXAuraObjCache::OnRootWindowObjCreated(aura::Window* window) {
if (root_windows_.empty() && GetFocusClient(window))
GetFocusClient(window)->AddObserver(this);
// Do not allow duplicate entries.
if (!base::Contains(root_windows_, window)) {
root_windows_.push_back(window);
}
}
void AXAuraObjCache::OnRootWindowObjDestroyed(aura::Window* window) {
base::EraseIf(root_windows_, [window](aura::Window* current_window) {
return current_window == window;
});
if (root_windows_.empty() && GetFocusClient(window))
GetFocusClient(window)->RemoveObserver(this);
if (focused_window_ == window)
focused_window_ = nullptr;
}
void AXAuraObjCache::SetA11yOverrideWindow(aura::Window* a11y_override_window) {
a11y_override_window_ = a11y_override_window;
a11y_override_window_observer_->Observe();
}
template <typename AuraViewWrapper, typename AuraView>
AXAuraObjWrapper* AXAuraObjCache::CreateInternal(
AuraView* aura_view,
std::map<AuraView*, int32_t>* aura_view_to_id_map) {
if (!aura_view)
return nullptr;
auto it = aura_view_to_id_map->find(aura_view);
if (it != aura_view_to_id_map->end())
return Get(it->second);
auto wrapper = std::make_unique<AuraViewWrapper>(this, aura_view);
ui::AXNodeID id = wrapper->GetUniqueId();
// Ensure this |AuraView| is not already in the cache. This must happen after
// |GetUniqueId|, as that can alter the cache such that the |find| call above
// may have missed.
DCHECK(aura_view_to_id_map->find(aura_view) == aura_view_to_id_map->end());
(*aura_view_to_id_map)[aura_view] = id;
cache_[id] = std::move(wrapper);
return cache_[id].get();
}
template <typename AuraView>
int32_t AXAuraObjCache::GetIDInternal(
AuraView* aura_view,
const std::map<AuraView*, int32_t>& aura_view_to_id_map) const {
if (!aura_view)
return ui::kInvalidAXNodeID;
auto it = aura_view_to_id_map.find(aura_view);
return it != aura_view_to_id_map.end() ? it->second : ui::kInvalidAXNodeID;
}
template <typename AuraView>
void AXAuraObjCache::RemoveInternal(
AuraView* aura_view,
std::map<AuraView*, int32_t>* aura_view_to_id_map) {
int32_t id = GetID(aura_view);
if (id == ui::kInvalidAXNodeID)
return;
aura_view_to_id_map->erase(aura_view);
cache_.erase(id);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/ax_aura_obj_cache.cc | C++ | unknown | 11,662 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_ACCESSIBILITY_AX_AURA_OBJ_CACHE_H_
#define UI_VIEWS_ACCESSIBILITY_AX_AURA_OBJ_CACHE_H_
#include <stdint.h>
#include <map>
#include <memory>
#include <set>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "base/no_destructor.h"
#include "ui/accessibility/ax_enums.mojom-forward.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/aura/client/focus_change_observer.h"
#include "ui/views/views_export.h"
namespace aura {
class Window;
} // namespace aura
namespace views {
class AXAuraObjWrapper;
class AXVirtualView;
class View;
class Widget;
// A cache responsible for assigning id's to a set of interesting Aura views.
class VIEWS_EXPORT AXAuraObjCache : public aura::client::FocusChangeObserver {
public:
AXAuraObjCache();
AXAuraObjCache(const AXAuraObjCache&) = delete;
AXAuraObjCache& operator=(const AXAuraObjCache&) = delete;
~AXAuraObjCache() override;
class Delegate {
public:
virtual ~Delegate() = default;
virtual void OnChildWindowRemoved(AXAuraObjWrapper* parent) = 0;
virtual void OnEvent(AXAuraObjWrapper* aura_obj,
ax::mojom::Event event_type) = 0;
};
// Get or create an entry in the cache. May return null if the View is not
// associated with a Widget.
AXAuraObjWrapper* GetOrCreate(View* view);
AXAuraObjWrapper* GetOrCreate(AXVirtualView* virtual_view);
// Get or create an entry in the cache.
AXAuraObjWrapper* GetOrCreate(Widget* widget);
AXAuraObjWrapper* GetOrCreate(aura::Window* window);
// Creates an entry in this cache given a wrapper object. Use this method when
// creating a wrapper not backed by any of the supported views above. This
// cache will take ownership. Will replace an existing entry with the same id.
void CreateOrReplace(std::unique_ptr<AXAuraObjWrapper> obj);
// Gets an id given an Aura view.
ui::AXNodeID GetID(View* view) const;
ui::AXNodeID GetID(AXVirtualView* view) const;
ui::AXNodeID GetID(Widget* widget) const;
ui::AXNodeID GetID(aura::Window* window) const;
// Removes an entry from this cache based on an Aura view.
void Remove(View* view);
void Remove(AXVirtualView* view);
void Remove(Widget* widget);
// Removes |window| and optionally notifies delegate by sending an event on
// the |parent| if provided.
void Remove(aura::Window* window, aura::Window* parent);
// Removes a view and all of its descendants from the cache.
void RemoveViewSubtree(View* view);
// Lookup a cached entry based on an id.
AXAuraObjWrapper* Get(ui::AXNodeID id);
// Get all top level windows this cache knows about. Under classic ash and
// SingleProcessMash this is a list of per-display root windows.
void GetTopLevelWindows(std::vector<AXAuraObjWrapper*>* children);
// Get the object that has focus.
AXAuraObjWrapper* GetFocus();
// Tell our delegate to fire an event on a given object.
void FireEvent(AXAuraObjWrapper* aura_obj, ax::mojom::Event event_type);
// Notifies this cache of a change in root window.
void OnRootWindowObjCreated(aura::Window* window);
// Notifies this cache of a change in root window.
void OnRootWindowObjDestroyed(aura::Window* window);
// Sets a window to take a11y focus. This is for windows that need to work
// with accessibility clients that consume accessibility APIs, but cannot take
// real focus themselves. |a11y_override_window_| will be set to null when
// destroyed, or can be set back to null using this function.
// TODO(sammiequon): Merge this with set_focused_widget_for_testing().
void SetA11yOverrideWindow(aura::Window* a11y_override_window);
void SetDelegate(Delegate* delegate) { delegate_ = delegate; }
// Changes the behavior of GetFocusedView() so that it only considers
// views within the given Widget, this enables making tests
// involving focus reliable.
void set_focused_widget_for_testing(views::Widget* widget) {
focused_widget_for_testing_ = widget;
}
private:
friend class base::NoDestructor<AXAuraObjCache>;
class A11yOverrideWindowObserver;
View* GetFocusedView();
// Send a notification that the focused view may have changed.
void OnFocusedViewChanged();
// aura::client::FocusChangeObserver override.
void OnWindowFocused(aura::Window* gained_focus,
aura::Window* lost_focus) override;
template <typename AuraViewWrapper, typename AuraView>
AXAuraObjWrapper* CreateInternal(
AuraView* aura_view,
std::map<AuraView*, ui::AXNodeID>* aura_view_to_id_map);
template <typename AuraView>
ui::AXNodeID GetIDInternal(
AuraView* aura_view,
const std::map<AuraView*, ui::AXNodeID>& aura_view_to_id_map) const;
template <typename AuraView>
void RemoveInternal(AuraView* aura_view,
std::map<AuraView*, ui::AXNodeID>* aura_view_to_id_map);
// The window that should take a11y focus. This is for a window that needs to
// work with accessiblity features, but cannot take real focus. Gets set to
// null if the window is destroyed.
raw_ptr<aura::Window> a11y_override_window_ = nullptr;
// Observes |a11y_override_window_| for destruction and sets it to null in
// that case.
std::unique_ptr<A11yOverrideWindowObserver> a11y_override_window_observer_;
std::map<views::View*, ui::AXNodeID> view_to_id_map_;
std::map<views::AXVirtualView*, ui::AXNodeID> virtual_view_to_id_map_;
std::map<views::Widget*, ui::AXNodeID> widget_to_id_map_;
std::map<aura::Window*, ui::AXNodeID> window_to_id_map_;
std::map<ui::AXNodeID, std::unique_ptr<AXAuraObjWrapper>> cache_;
raw_ptr<Delegate> delegate_ = nullptr;
std::vector<aura::Window*> root_windows_;
raw_ptr<aura::Window> focused_window_ = nullptr;
raw_ptr<views::Widget> focused_widget_for_testing_ = nullptr;
};
} // namespace views
#endif // UI_VIEWS_ACCESSIBILITY_AX_AURA_OBJ_CACHE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/ax_aura_obj_cache.h | C++ | unknown | 6,034 |
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/accessibility/ax_aura_obj_cache.h"
#include <string>
#include <utility>
#include "base/memory/raw_ptr.h"
#include "base/strings/utf_string_conversions.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_node.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/accessibility/ax_tree.h"
#include "ui/accessibility/ax_tree_serializer.h"
#include "ui/accessibility/ax_tree_source_checker.h"
#include "ui/aura/window.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
#include "ui/views/accessibility/ax_aura_obj_wrapper.h"
#include "ui/views/accessibility/ax_event_manager.h"
#include "ui/views/accessibility/ax_event_observer.h"
#include "ui/views/accessibility/ax_tree_source_views.h"
#include "ui/views/accessibility/ax_virtual_view.h"
#include "ui/views/accessibility/ax_virtual_view_wrapper.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/widget/unique_widget_ptr.h"
#include "ui/views/widget/widget_delegate.h"
namespace views::test {
namespace {
// This class can be used as a deleter for std::unique_ptr<Widget>
// to call function Widget::CloseNow automatically.
struct WidgetCloser {
inline void operator()(Widget* widget) const { widget->CloseNow(); }
};
using WidgetAutoclosePtr = std::unique_ptr<Widget, WidgetCloser>;
bool HasNodeWithName(ui::AXNode* node, const std::string& name) {
if (node->GetStringAttribute(ax::mojom::StringAttribute::kName) == name)
return true;
for (ui::AXNode* child : node->children()) {
if (HasNodeWithName(child, name))
return true;
}
return false;
}
bool HasNodeWithName(const ui::AXTree& tree, const std::string& name) {
return HasNodeWithName(tree.root(), name);
}
class AXAuraObjCacheTest : public WidgetTest {
public:
AXAuraObjCacheTest() = default;
~AXAuraObjCacheTest() override = default;
ui::AXNodeData GetData(AXAuraObjWrapper* wrapper) {
ui::AXNodeData data;
wrapper->Serialize(&data);
return data;
}
};
TEST_F(AXAuraObjCacheTest, TestViewRemoval) {
AXAuraObjCache cache;
WidgetAutoclosePtr widget(CreateTopLevelPlatformWidget());
auto* parent = widget->GetRootView()->AddChildView(std::make_unique<View>());
auto* child = parent->AddChildView(std::make_unique<View>());
AXAuraObjWrapper* ax_widget = cache.GetOrCreate(widget.get());
ASSERT_NE(nullptr, ax_widget);
AXAuraObjWrapper* ax_parent = cache.GetOrCreate(parent);
ASSERT_NE(nullptr, ax_parent);
AXAuraObjWrapper* ax_child = cache.GetOrCreate(child);
ASSERT_NE(nullptr, ax_child);
// Everything should have an ID, indicating it's in the cache.
ASSERT_NE(cache.GetID(widget.get()), ui::kInvalidAXNodeID);
ASSERT_NE(cache.GetID(parent), ui::kInvalidAXNodeID);
ASSERT_NE(cache.GetID(child), ui::kInvalidAXNodeID);
// Removing the parent view should remove both the parent and child
// from the cache, but leave the widget.
widget->GetRootView()->RemoveChildViewT(parent);
ASSERT_NE(cache.GetID(widget.get()), ui::kInvalidAXNodeID);
ASSERT_EQ(ui::kInvalidAXNodeID, cache.GetID(parent));
ASSERT_EQ(ui::kInvalidAXNodeID, cache.GetID(child));
}
// Helper for the ViewDestruction test.
class ViewBlurObserver : public ViewObserver {
public:
ViewBlurObserver(AXAuraObjCache* cache, View* view) : cache_(cache) {
observation_.Observe(view);
}
void OnViewBlurred(View* view) override {
ASSERT_FALSE(was_called());
observation_.Reset();
// The cache entry gets deleted in
// AXViewObjWrapper::OnViewIsDeleting which occurs later in ~View.
}
bool was_called() { return !observation_.IsObserving(); }
private:
raw_ptr<AXAuraObjCache> cache_;
base::ScopedObservation<View, ViewObserver> observation_{this};
};
// Test that stale cache entries are not left behind if a cache entry is
// re-created during View destruction.
TEST_F(AXAuraObjCacheTest, ViewDestruction) {
AXAuraObjCache cache;
WidgetAutoclosePtr widget(CreateTopLevelPlatformWidget());
LabelButton* button = new LabelButton(Button::PressedCallback(), u"button");
widget->GetRootView()->AddChildView(button);
widget->Activate();
button->RequestFocus();
base::RunLoop().RunUntilIdle();
ASSERT_TRUE(button->HasFocus());
cache.GetOrCreate(widget.get());
cache.GetOrCreate(button);
// Everything should have an ID, indicating it's in the cache.
EXPECT_NE(cache.GetID(widget.get()), ui::kInvalidAXNodeID);
EXPECT_NE(cache.GetID(button), ui::kInvalidAXNodeID);
ViewBlurObserver observer(&cache, button);
delete button;
// The button object is destroyed, so there should be no stale cache entries.
EXPECT_NE(button, nullptr);
EXPECT_EQ(ui::kInvalidAXNodeID, cache.GetID(button));
EXPECT_TRUE(observer.was_called());
}
TEST_F(AXAuraObjCacheTest, CacheDestructionUAF) {
// This test ensures that a UAF is not possible during cache destruction.
// Two top-level widgets need to be created and inserted into |root_windows_|.
// This test uses manual memory management, rather than managed helpers
// that other tests are using. Ensure there is not a UAF crash when deleting
// the cache.
AXAuraObjCache* cache = new AXAuraObjCache();
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.bounds = gfx::Rect(0, 0, 200, 200);
widget->Init(std::move(params));
cache->OnRootWindowObjCreated(widget->GetNativeWindow());
widget->Activate();
base::RunLoop().RunUntilIdle();
cache->GetOrCreate(widget.get());
// Everything should have an ID, indicating it's in the cache.
EXPECT_NE(cache->GetID(widget.get()), ui::kInvalidAXNodeID);
// Create a second top-level widget to ensure |root_windows_| isn't empty.
UniqueWidgetPtr widget2 = std::make_unique<Widget>();
Widget::InitParams params2 = CreateParams(Widget::InitParams::TYPE_WINDOW);
params2.bounds = gfx::Rect(0, 0, 200, 200);
widget2->Init(std::move(params2));
cache->OnRootWindowObjCreated(widget2->GetNativeWindow());
cache->GetOrCreate(widget2.get());
widget2->Activate();
base::RunLoop().RunUntilIdle();
// Everything should have an ID, indicating it's in the cache.
EXPECT_NE(cache->GetID(widget2.get()), ui::kInvalidAXNodeID);
// Delete the first widget, then delete the cache.
cache->OnRootWindowObjDestroyed(widget->GetNativeWindow());
widget.reset();
delete cache;
}
TEST_F(AXAuraObjCacheTest, ValidTree) {
// Create a parent window.
UniqueWidgetPtr parent_widget = std::make_unique<Widget>();
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.bounds = gfx::Rect(0, 0, 200, 200);
parent_widget->Init(std::move(params));
parent_widget->GetNativeWindow()->SetTitle(u"ParentWindow");
parent_widget->Show();
// Create a child window.
Widget* child_widget = new Widget(); // Owned by parent_widget.
params = CreateParams(Widget::InitParams::TYPE_BUBBLE);
params.parent = parent_widget->GetNativeWindow();
params.child = true;
params.bounds = gfx::Rect(100, 100, 200, 200);
params.ownership = views::Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET;
child_widget->Init(std::move(params));
child_widget->GetNativeWindow()->SetTitle(u"ChildWindow");
child_widget->Show();
// Create a child view.
LabelButton* button =
new LabelButton(Button::PressedCallback(), u"ChildButton");
button->SetSize(gfx::Size(20, 20));
child_widget->GetContentsView()->AddChildView(button);
// Use AXAuraObjCache to serialize the node tree.
AXAuraObjCache cache;
ui::AXTreeID tree_id = ui::AXTreeID::CreateNewAXTreeID();
AXTreeSourceViews tree_source(
cache.GetOrCreate(parent_widget->GetNativeWindow()), tree_id, &cache);
ui::AXTreeSerializer<AXAuraObjWrapper*> serializer(&tree_source);
ui::AXTreeUpdate serialized_tree;
serializer.SerializeChanges(tree_source.GetRoot(), &serialized_tree);
// Verify tree is valid.
ui::AXTreeSourceChecker<AXAuraObjWrapper*> checker(&tree_source);
std::string error_string;
EXPECT_TRUE(checker.CheckAndGetErrorString(&error_string)) << error_string;
ui::AXTree ax_tree(serialized_tree);
EXPECT_TRUE(HasNodeWithName(ax_tree, "ParentWindow"));
EXPECT_TRUE(HasNodeWithName(ax_tree, "ChildWindow"));
EXPECT_TRUE(HasNodeWithName(ax_tree, "ChildButton"));
}
TEST_F(AXAuraObjCacheTest, GetFocusIsUnignoredAncestor) {
AXAuraObjCache cache;
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.bounds = gfx::Rect(0, 0, 200, 200);
params.activatable = views::Widget::InitParams::Activatable::kYes;
widget->Init(std::move(params));
widget->Show();
// Note that AXAuraObjCache::GetFocusedView has some logic to force focus on
// the first child of the client view when one cannot be found from the
// FocusManager if it has a child tree id.
ClientView* client = widget->non_client_view()->client_view();
ASSERT_NE(nullptr, client);
View* client_child = client->children().front();
ASSERT_NE(nullptr, client_child);
client_child->GetViewAccessibility().OverrideRole(ax::mojom::Role::kDialog);
client_child->GetViewAccessibility().OverrideChildTreeID(
ui::AXTreeID::CreateNewAXTreeID());
auto* parent = widget->GetRootView()->AddChildView(std::make_unique<View>());
parent->GetViewAccessibility().OverrideRole(ax::mojom::Role::kTextField);
parent->SetFocusBehavior(View::FocusBehavior::ALWAYS);
auto* child = parent->AddChildView(std::make_unique<View>());
child->GetViewAccessibility().OverrideRole(ax::mojom::Role::kGroup);
child->SetFocusBehavior(View::FocusBehavior::ALWAYS);
AXAuraObjWrapper* ax_widget = cache.GetOrCreate(widget.get());
ASSERT_NE(nullptr, ax_widget);
AXAuraObjWrapper* ax_client_child = cache.GetOrCreate(client_child);
ASSERT_NE(nullptr, ax_client_child);
AXAuraObjWrapper* ax_parent = cache.GetOrCreate(parent);
ASSERT_NE(nullptr, ax_parent);
AXAuraObjWrapper* ax_child = cache.GetOrCreate(child);
ASSERT_NE(nullptr, ax_child);
ASSERT_EQ(nullptr, cache.GetFocus());
cache.OnRootWindowObjCreated(widget->GetNativeWindow());
ASSERT_EQ(ax::mojom::Role::kDialog, GetData(cache.GetFocus()).role);
ASSERT_EQ(ax_client_child, cache.GetFocus());
parent->RequestFocus();
ASSERT_EQ(ax::mojom::Role::kTextField, GetData(cache.GetFocus()).role);
ASSERT_EQ(ax_parent, cache.GetFocus());
child->RequestFocus();
ASSERT_EQ(ax::mojom::Role::kGroup, GetData(cache.GetFocus()).role);
ASSERT_EQ(ax_child, cache.GetFocus());
// Ignore should cause focus to move upwards.
child->GetViewAccessibility().OverrideIsIgnored(true);
ASSERT_EQ(ax::mojom::Role::kTextField, GetData(cache.GetFocus()).role);
ASSERT_EQ(ax_parent, cache.GetFocus());
// Propagate focus to ancestor should also cause focus to move upward.
parent->GetViewAccessibility().set_propagate_focus_to_ancestor(true);
ASSERT_EQ(ax::mojom::Role::kWindow, GetData(cache.GetFocus()).role);
ASSERT_EQ(cache.GetOrCreate(widget->GetRootView()), cache.GetFocus());
cache.OnRootWindowObjDestroyed(widget->GetNativeWindow());
}
class TestingWidgetDelegateView : public WidgetDelegateView {
public:
explicit TestingWidgetDelegateView(base::RunLoop* run_loop)
: run_loop_(run_loop) {}
~TestingWidgetDelegateView() override {
NotifyAccessibilityEvent(ax::mojom::Event::kChildrenChanged, false);
run_loop_->QuitWhenIdle();
}
TestingWidgetDelegateView(const TestingWidgetDelegateView&) = delete;
TestingWidgetDelegateView& operator=(const TestingWidgetDelegateView&) =
delete;
private:
raw_ptr<base::RunLoop> run_loop_;
};
class TestingAXEventObserver : public AXEventObserver {
public:
explicit TestingAXEventObserver(AXAuraObjCache* cache) : cache_(cache) {
observation_.Observe(AXEventManager::Get());
}
~TestingAXEventObserver() override = default;
TestingAXEventObserver(const TestingAXEventObserver&) = delete;
TestingAXEventObserver& operator=(const TestingAXEventObserver&) = delete;
private:
void OnViewEvent(View* view, ax::mojom::Event event_type) override {
AXAuraObjWrapper* ax_view = cache_->GetOrCreate(view);
while (ax_view != nullptr) {
ax_view = ax_view->GetParent();
}
}
raw_ptr<AXAuraObjCache> cache_;
base::ScopedObservation<AXEventManager, AXEventObserver> observation_{this};
};
TEST_F(AXAuraObjCacheTest, DoNotCreateWidgetWrapperOnDestroyed) {
AXAuraObjCache cache;
TestingAXEventObserver observer(&cache);
Widget* widget = new Widget;
base::RunLoop run_loop;
TestingWidgetDelegateView* delegate =
new TestingWidgetDelegateView(&run_loop);
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.bounds = gfx::Rect(0, 0, 200, 200);
params.activatable = views::Widget::InitParams::Activatable::kYes;
params.delegate = delegate;
widget->Init(std::move(params));
widget->Show();
EXPECT_NE(ui::kInvalidAXNodeID, cache.GetID(widget));
// Widget is closed asynchronously.
widget->Close();
run_loop.Run();
EXPECT_EQ(ui::kInvalidAXNodeID, cache.GetID(widget));
}
TEST_F(AXAuraObjCacheTest, VirtualViews) {
AXAuraObjCache cache;
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.bounds = gfx::Rect(0, 0, 200, 200);
params.activatable = views::Widget::InitParams::Activatable::kYes;
widget->Init(std::move(params));
widget->Show();
auto* parent = widget->GetRootView()->AddChildView(std::make_unique<View>());
AXVirtualView* virtual_label = new AXVirtualView;
virtual_label->GetCustomData().role = ax::mojom::Role::kStaticText;
virtual_label->GetCustomData().SetNameChecked("Label");
parent->GetViewAccessibility().AddVirtualChildView(
base::WrapUnique(virtual_label));
AXVirtualViewWrapper* wrapper = virtual_label->GetOrCreateWrapper(&cache);
ui::AXNodeID id = wrapper->GetUniqueId();
AXAuraObjWrapper* wrapper2 = cache.Get(id);
EXPECT_EQ(wrapper, wrapper2);
parent->GetViewAccessibility().RemoveVirtualChildView(virtual_label);
EXPECT_EQ(nullptr, cache.Get(id));
}
} // namespace
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/ax_aura_obj_cache_unittest.cc | C++ | unknown | 14,439 |
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/accessibility/ax_aura_obj_wrapper.h"
namespace views {
AXAuraObjWrapper::AXAuraObjWrapper(AXAuraObjCache* cache)
: aura_obj_cache_(cache) {}
AXAuraObjWrapper::~AXAuraObjWrapper() = default;
bool AXAuraObjWrapper::HandleAccessibleAction(const ui::AXActionData& action) {
return false;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/ax_aura_obj_wrapper.cc | C++ | unknown | 482 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_ACCESSIBILITY_AX_AURA_OBJ_WRAPPER_H_
#define UI_VIEWS_ACCESSIBILITY_AX_AURA_OBJ_WRAPPER_H_
#include <stdint.h>
#include <string>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/gfx/geometry/point.h"
#include "ui/views/views_export.h"
namespace ui {
struct AXActionData;
} // namespace ui
namespace views {
class AXAuraObjCache;
// An interface abstraction for Aura views that exposes the view-tree formed
// by the implementing view types.
class VIEWS_EXPORT AXAuraObjWrapper {
public:
explicit AXAuraObjWrapper(AXAuraObjCache* cache);
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 ui::AXNodeID GetUniqueId() const = 0;
virtual std::string ToString() const = 0;
// Actions.
virtual bool HandleAccessibleAction(const ui::AXActionData& action);
const AXAuraObjCache* cache() const { return aura_obj_cache_; }
protected:
absl::optional<std::vector<AXAuraObjWrapper*>> cached_children_;
// The cache associated with this wrapper. Subclasses should initialize this
// cache on construction.
raw_ptr<AXAuraObjCache> aura_obj_cache_ = nullptr;
friend class AXTreeSourceViews;
};
} // namespace views
#endif // UI_VIEWS_ACCESSIBILITY_AX_AURA_OBJ_WRAPPER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/ax_aura_obj_wrapper.h | C++ | unknown | 1,680 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/accessibility/ax_event_manager.h"
#include "base/no_destructor.h"
#include "base/observer_list.h"
#include "ui/views/accessibility/ax_event_observer.h"
namespace views {
AXEventManager::AXEventManager() = default;
AXEventManager::~AXEventManager() = default;
// static
AXEventManager* AXEventManager::Get() {
static base::NoDestructor<AXEventManager> instance;
return instance.get();
}
void AXEventManager::AddObserver(AXEventObserver* observer) {
observers_.AddObserver(observer);
}
void AXEventManager::RemoveObserver(AXEventObserver* observer) {
observers_.RemoveObserver(observer);
}
void AXEventManager::NotifyViewEvent(views::View* view,
ax::mojom::Event event_type) {
for (AXEventObserver& observer : observers_)
observer.OnViewEvent(view, event_type);
}
void AXEventManager::NotifyVirtualViewEvent(views::AXVirtualView* virtual_view,
ax::mojom::Event event_type) {
for (AXEventObserver& observer : observers_)
observer.OnVirtualViewEvent(virtual_view, event_type);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/ax_event_manager.cc | C++ | unknown | 1,271 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_ACCESSIBILITY_AX_EVENT_MANAGER_H_
#define UI_VIEWS_ACCESSIBILITY_AX_EVENT_MANAGER_H_
#include "base/observer_list.h"
#include "ui/accessibility/ax_enums.mojom-forward.h"
#include "ui/views/views_export.h"
namespace views {
class AXEventObserver;
class AXVirtualView;
class View;
// AXEventManager allows observation of accessibility events for all views.
class VIEWS_EXPORT AXEventManager {
public:
AXEventManager();
AXEventManager(const AXEventManager&) = delete;
AXEventManager& operator=(const AXEventManager&) = delete;
~AXEventManager();
// Returns the singleton instance.
static AXEventManager* Get();
void AddObserver(AXEventObserver* observer);
void RemoveObserver(AXEventObserver* observer);
// Notifies observers of an accessibility event. |view| must not be null.
void NotifyViewEvent(views::View* view, ax::mojom::Event event_type);
void NotifyVirtualViewEvent(views::AXVirtualView* virtual_view,
ax::mojom::Event event_type);
private:
base::ObserverList<AXEventObserver> observers_;
};
} // namespace views
#endif // UI_VIEWS_ACCESSIBILITY_AX_EVENT_MANAGER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/ax_event_manager.h | C++ | unknown | 1,302 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/accessibility/ax_event_observer.h"
namespace views {
AXEventObserver::AXEventObserver() = default;
AXEventObserver::~AXEventObserver() = default;
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/ax_event_observer.cc | C++ | unknown | 335 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_ACCESSIBILITY_AX_EVENT_OBSERVER_H_
#define UI_VIEWS_ACCESSIBILITY_AX_EVENT_OBSERVER_H_
#include "base/observer_list_types.h"
#include "ui/accessibility/ax_enums.mojom-forward.h"
#include "ui/views/views_export.h"
namespace views {
class AXVirtualView;
class View;
// AXEventObserver is notified for accessibility events on all views.
class VIEWS_EXPORT AXEventObserver : public base::CheckedObserver {
public:
virtual void OnViewEvent(views::View* view, ax::mojom::Event event_type) = 0;
virtual void OnVirtualViewEvent(views::AXVirtualView* virtual_view,
ax::mojom::Event event_type) {}
protected:
AXEventObserver();
~AXEventObserver() override;
};
} // namespace views
#endif // UI_VIEWS_ACCESSIBILITY_AX_EVENT_OBSERVER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/ax_event_observer.h | C++ | unknown | 939 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/accessibility/ax_root_obj_wrapper.h"
#include <utility>
#include "base/containers/contains.h"
#include "base/strings/utf_string_conversions.h"
#include "build/chromeos_buildflags.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/accessibility/platform/ax_unique_id.h"
#include "ui/aura/window.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/views/accessibility/ax_aura_obj_cache.h"
#include "ui/views/accessibility/ax_window_obj_wrapper.h"
AXRootObjWrapper::AXRootObjWrapper(views::AXAuraObjCache::Delegate* delegate,
views::AXAuraObjCache* cache)
: views::AXAuraObjWrapper(cache), delegate_(delegate) {}
AXRootObjWrapper::~AXRootObjWrapper() = default;
bool AXRootObjWrapper::HasChild(views::AXAuraObjWrapper* child) {
std::vector<views::AXAuraObjWrapper*> children;
GetChildren(&children);
return base::Contains(children, child);
}
views::AXAuraObjWrapper* AXRootObjWrapper::GetParent() {
return nullptr;
}
void AXRootObjWrapper::GetChildren(
std::vector<views::AXAuraObjWrapper*>* out_children) {
aura_obj_cache_->GetTopLevelWindows(out_children);
}
void AXRootObjWrapper::Serialize(ui::AXNodeData* out_node_data) {
out_node_data->id = unique_id_.Get();
#if BUILDFLAG(IS_CHROMEOS_LACROS)
out_node_data->role = ax::mojom::Role::kClient;
#else
out_node_data->role = ax::mojom::Role::kDesktop;
#endif
display::Screen* screen = display::Screen::GetScreen();
if (!screen)
return;
const display::Display& display = screen->GetPrimaryDisplay();
out_node_data->relative_bounds.bounds =
gfx::RectF(display.bounds().width(), display.bounds().height());
// Utilize the display bounds to figure out if this screen is in landscape or
// portrait. We use this rather than |rotation| because some devices default
// to landscape, some in portrait. Encode landscape as horizontal state,
// portrait as vertical state.
if (display.bounds().width() > display.bounds().height())
out_node_data->AddState(ax::mojom::State::kHorizontal);
else
out_node_data->AddState(ax::mojom::State::kVertical);
}
ui::AXNodeID AXRootObjWrapper::GetUniqueId() const {
return unique_id_.Get();
}
std::string AXRootObjWrapper::ToString() const {
return "root";
}
void AXRootObjWrapper::OnDisplayMetricsChanged(const display::Display& display,
uint32_t changed_metrics) {
delegate_->OnEvent(this, ax::mojom::Event::kLoadComplete);
}
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/ax_root_obj_wrapper.cc | C++ | unknown | 2,708 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_ACCESSIBILITY_AX_ROOT_OBJ_WRAPPER_H_
#define UI_VIEWS_ACCESSIBILITY_AX_ROOT_OBJ_WRAPPER_H_
#include <stdint.h>
#include <memory>
#include <string>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "ui/accessibility/platform/ax_unique_id.h"
#include "ui/display/display_observer.h"
#include "ui/views/accessibility/ax_aura_obj_cache.h"
#include "ui/views/accessibility/ax_aura_obj_wrapper.h"
class VIEWS_EXPORT AXRootObjWrapper : public views::AXAuraObjWrapper,
display::DisplayObserver {
public:
AXRootObjWrapper(views::AXAuraObjCache::Delegate* delegate,
views::AXAuraObjCache* cache);
AXRootObjWrapper(const AXRootObjWrapper&) = delete;
AXRootObjWrapper& operator=(const AXRootObjWrapper&) = delete;
~AXRootObjWrapper() override;
// Convenience method to check for existence of a child.
bool HasChild(views::AXAuraObjWrapper* child);
// views::AXAuraObjWrapper overrides.
views::AXAuraObjWrapper* GetParent() override;
void GetChildren(
std::vector<views::AXAuraObjWrapper*>* out_children) override;
void Serialize(ui::AXNodeData* out_node_data) override;
ui::AXNodeID GetUniqueId() const final;
std::string ToString() const override;
private:
// display::DisplayObserver:
void OnDisplayMetricsChanged(const display::Display& display,
uint32_t changed_metrics) override;
display::ScopedOptionalDisplayObserver display_observer_{this};
ui::AXUniqueId unique_id_;
raw_ptr<views::AXAuraObjCache::Delegate> delegate_;
};
#endif // UI_VIEWS_ACCESSIBILITY_AX_ROOT_OBJ_WRAPPER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/ax_root_obj_wrapper.h | C++ | unknown | 1,787 |
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <windows.h> // Must come before other Windows system headers.
#include <oleacc.h>
#include <wrl/client.h>
#include "base/memory/raw_ptr.h"
#include "base/strings/utf_string_conversions.h"
#include "base/win/scoped_variant.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/aura/window.h"
#include "ui/aura/window_tree_host.h"
#include "ui/base/ime/input_method.h"
#include "ui/base/ime/text_edit_commands.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/controls/textfield/textfield_test_api.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/widget/widget.h"
namespace views {
namespace {
class AXSystemCaretWinTest : public test::DesktopWidgetTest {
public:
AXSystemCaretWinTest() : self_(CHILDID_SELF) {}
AXSystemCaretWinTest(const AXSystemCaretWinTest&) = delete;
AXSystemCaretWinTest& operator=(const AXSystemCaretWinTest&) = delete;
~AXSystemCaretWinTest() override = default;
void SetUp() override {
SetUpForInteractiveTests();
test::DesktopWidgetTest::SetUp();
widget_ = CreateTopLevelNativeWidget();
widget_->SetBounds(gfx::Rect(0, 0, 200, 200));
textfield_ = new Textfield();
textfield_->SetBounds(0, 0, 200, 20);
textfield_->SetText(u"Some text.");
widget_->GetRootView()->AddChildView(textfield_.get());
test::WidgetActivationWaiter waiter(widget_, true);
widget_->Show();
waiter.Wait();
textfield_->RequestFocus();
ASSERT_TRUE(widget_->IsActive());
ASSERT_TRUE(textfield_->HasFocus());
ASSERT_EQ(ui::TEXT_INPUT_TYPE_TEXT,
widget_->GetInputMethod()->GetTextInputType());
}
void TearDown() override {
widget_->CloseNow();
test::DesktopWidgetTest::TearDown();
ui::ResourceBundle::CleanupSharedInstance();
}
protected:
raw_ptr<Widget> widget_;
raw_ptr<Textfield> textfield_;
base::win::ScopedVariant self_;
};
class WinAccessibilityCaretEventMonitor {
public:
WinAccessibilityCaretEventMonitor(UINT event_min, UINT event_max);
WinAccessibilityCaretEventMonitor(const WinAccessibilityCaretEventMonitor&) =
delete;
WinAccessibilityCaretEventMonitor& operator=(
const WinAccessibilityCaretEventMonitor&) = delete;
~WinAccessibilityCaretEventMonitor();
// Blocks until the next event is received. When it's received, it
// queries accessibility information about the object that fired the
// event and populates the event, hwnd, role, state, and name in the
// passed arguments.
void WaitForNextEvent(DWORD* out_event, UINT* out_role, UINT* out_state);
private:
void OnWinEventHook(HWINEVENTHOOK handle,
DWORD event,
HWND hwnd,
LONG obj_id,
LONG child_id,
DWORD event_thread,
DWORD event_time);
static void CALLBACK WinEventHookThunk(HWINEVENTHOOK handle,
DWORD event,
HWND hwnd,
LONG obj_id,
LONG child_id,
DWORD event_thread,
DWORD event_time);
struct EventInfo {
DWORD event;
HWND hwnd;
LONG obj_id;
LONG child_id;
};
base::circular_deque<EventInfo> event_queue_;
base::RunLoop loop_runner_;
HWINEVENTHOOK win_event_hook_handle_;
static WinAccessibilityCaretEventMonitor* instance_;
};
// static
WinAccessibilityCaretEventMonitor*
WinAccessibilityCaretEventMonitor::instance_ = nullptr;
WinAccessibilityCaretEventMonitor::WinAccessibilityCaretEventMonitor(
UINT event_min,
UINT event_max) {
CHECK(!instance_) << "There can be only one instance of"
<< " WinAccessibilityCaretEventMonitor at a time.";
instance_ = this;
win_event_hook_handle_ =
SetWinEventHook(event_min, event_max, nullptr,
&WinAccessibilityCaretEventMonitor::WinEventHookThunk,
GetCurrentProcessId(),
0, // Hook all threads
WINEVENT_OUTOFCONTEXT);
}
WinAccessibilityCaretEventMonitor::~WinAccessibilityCaretEventMonitor() {
UnhookWinEvent(win_event_hook_handle_);
instance_ = nullptr;
}
void WinAccessibilityCaretEventMonitor::WaitForNextEvent(DWORD* out_event,
UINT* out_role,
UINT* out_state) {
if (event_queue_.empty())
loop_runner_.Run();
EventInfo event_info = event_queue_.front();
event_queue_.pop_front();
*out_event = event_info.event;
Microsoft::WRL::ComPtr<IAccessible> acc_obj;
base::win::ScopedVariant child_variant;
CHECK(S_OK == AccessibleObjectFromEvent(event_info.hwnd, event_info.obj_id,
event_info.child_id, &acc_obj,
child_variant.Receive()));
base::win::ScopedVariant role_variant;
if (S_OK == acc_obj->get_accRole(child_variant, role_variant.Receive()))
*out_role = V_I4(role_variant.ptr());
else
*out_role = 0;
base::win::ScopedVariant state_variant;
if (S_OK == acc_obj->get_accState(child_variant, state_variant.Receive()))
*out_state = V_I4(state_variant.ptr());
else
*out_state = 0;
}
void WinAccessibilityCaretEventMonitor::OnWinEventHook(HWINEVENTHOOK handle,
DWORD event,
HWND hwnd,
LONG obj_id,
LONG child_id,
DWORD event_thread,
DWORD event_time) {
EventInfo event_info;
event_info.event = event;
event_info.hwnd = hwnd;
event_info.obj_id = obj_id;
event_info.child_id = child_id;
event_queue_.push_back(event_info);
loop_runner_.Quit();
}
// static
void CALLBACK
WinAccessibilityCaretEventMonitor::WinEventHookThunk(HWINEVENTHOOK handle,
DWORD event,
HWND hwnd,
LONG obj_id,
LONG child_id,
DWORD event_thread,
DWORD event_time) {
if (instance_ && obj_id == OBJID_CARET) {
instance_->OnWinEventHook(handle, event, hwnd, obj_id, child_id,
event_thread, event_time);
}
}
} // namespace
TEST_F(AXSystemCaretWinTest, TestOnCaretBoundsChangeInTextField) {
TextfieldTestApi textfield_test_api(textfield_);
Microsoft::WRL::ComPtr<IAccessible> caret_accessible;
gfx::NativeWindow native_window = widget_->GetNativeWindow();
ASSERT_NE(nullptr, native_window);
HWND hwnd = native_window->GetHost()->GetAcceleratedWidget();
EXPECT_HRESULT_SUCCEEDED(AccessibleObjectFromWindow(
hwnd, static_cast<DWORD>(OBJID_CARET), IID_PPV_ARGS(&caret_accessible)));
gfx::Rect window_bounds = native_window->GetBoundsInScreen();
textfield_test_api.ExecuteTextEditCommand(
ui::TextEditCommand::MOVE_TO_BEGINNING_OF_DOCUMENT);
gfx::Point caret_position = textfield_test_api.GetCursorViewRect().origin() +
window_bounds.OffsetFromOrigin();
LONG x, y, width, height;
EXPECT_EQ(S_OK,
caret_accessible->accLocation(&x, &y, &width, &height, self_));
EXPECT_EQ(caret_position.x(), x);
EXPECT_EQ(caret_position.y(), y);
EXPECT_EQ(1, width);
textfield_test_api.ExecuteTextEditCommand(
ui::TextEditCommand::MOVE_TO_END_OF_DOCUMENT);
gfx::Point caret_position2 = textfield_test_api.GetCursorViewRect().origin() +
window_bounds.OffsetFromOrigin();
EXPECT_NE(caret_position, caret_position2);
EXPECT_EQ(S_OK,
caret_accessible->accLocation(&x, &y, &width, &height, self_));
EXPECT_EQ(caret_position2.x(), x);
EXPECT_EQ(caret_position2.y(), y);
EXPECT_EQ(1, width);
}
TEST_F(AXSystemCaretWinTest, TestOnInputTypeChangeInTextField) {
Microsoft::WRL::ComPtr<IAccessible> caret_accessible;
gfx::NativeWindow native_window = widget_->GetNativeWindow();
ASSERT_NE(nullptr, native_window);
HWND hwnd = native_window->GetHost()->GetAcceleratedWidget();
EXPECT_HRESULT_SUCCEEDED(AccessibleObjectFromWindow(
hwnd, static_cast<DWORD>(OBJID_CARET), IID_PPV_ARGS(&caret_accessible)));
LONG x, y, width, height;
EXPECT_EQ(S_OK,
caret_accessible->accLocation(&x, &y, &width, &height, self_));
textfield_->SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD);
// Caret object should still be valid.
EXPECT_EQ(S_OK,
caret_accessible->accLocation(&x, &y, &width, &height, self_));
// Retrieving the caret again should also work.
caret_accessible.Reset();
EXPECT_HRESULT_SUCCEEDED(AccessibleObjectFromWindow(
hwnd, static_cast<DWORD>(OBJID_CARET), IID_PPV_ARGS(&caret_accessible)));
LONG x2, y2, width2, height2;
EXPECT_EQ(S_OK,
caret_accessible->accLocation(&x2, &y2, &width2, &height2, self_));
EXPECT_EQ(x, x2);
EXPECT_EQ(y, y2);
EXPECT_EQ(width, width2);
EXPECT_EQ(height, height2);
}
TEST_F(AXSystemCaretWinTest, TestMovingWindow) {
Microsoft::WRL::ComPtr<IAccessible> caret_accessible;
gfx::NativeWindow native_window = widget_->GetNativeWindow();
ASSERT_NE(nullptr, native_window);
HWND hwnd = native_window->GetHost()->GetAcceleratedWidget();
EXPECT_HRESULT_SUCCEEDED(AccessibleObjectFromWindow(
hwnd, static_cast<DWORD>(OBJID_CARET), IID_PPV_ARGS(&caret_accessible)));
LONG x, y, width, height;
EXPECT_EQ(S_OK,
caret_accessible->accLocation(&x, &y, &width, &height, self_));
widget_->SetBounds(gfx::Rect(100, 100, 500, 500));
LONG x2, y2, width2, height2;
EXPECT_EQ(S_OK,
caret_accessible->accLocation(&x2, &y2, &width2, &height2, self_));
EXPECT_NE(x, x2);
EXPECT_NE(y, y2);
// The width and height of the caret shouldn't change.
EXPECT_EQ(width, width2);
EXPECT_EQ(height, height2);
// Try maximizing the window.
SendMessage(hwnd, WM_SYSCOMMAND, SC_MAXIMIZE, 0);
// On Win7, maximizing the window causes our caret object to get destroyed and
// re-created, so re-acquire it.
caret_accessible.Reset();
EXPECT_HRESULT_SUCCEEDED(AccessibleObjectFromWindow(
hwnd, static_cast<DWORD>(OBJID_CARET), IID_PPV_ARGS(&caret_accessible)));
LONG x3, y3, width3, height3;
EXPECT_EQ(S_OK,
caret_accessible->accLocation(&x3, &y3, &width3, &height3, self_));
EXPECT_NE(x2, x3);
EXPECT_NE(y2, y3);
// The width and height of the caret shouldn't change.
EXPECT_EQ(width, width3);
EXPECT_EQ(height, height3);
}
// TODO(https://crbug.com/1294822): This test is flaky.
TEST_F(AXSystemCaretWinTest, DISABLED_TestCaretMSAAEvents) {
TextfieldTestApi textfield_test_api(textfield_);
Microsoft::WRL::ComPtr<IAccessible> caret_accessible;
gfx::NativeWindow native_window = widget_->GetNativeWindow();
ASSERT_NE(nullptr, native_window);
HWND hwnd = native_window->GetHost()->GetAcceleratedWidget();
EXPECT_HRESULT_SUCCEEDED(AccessibleObjectFromWindow(
hwnd, static_cast<DWORD>(OBJID_CARET), IID_PPV_ARGS(&caret_accessible)));
DWORD event;
UINT role;
UINT state;
{
// Set caret to start of textfield.
WinAccessibilityCaretEventMonitor monitor(EVENT_OBJECT_SHOW,
EVENT_OBJECT_LOCATIONCHANGE);
textfield_test_api.ExecuteTextEditCommand(
ui::TextEditCommand::MOVE_TO_BEGINNING_OF_DOCUMENT);
monitor.WaitForNextEvent(&event, &role, &state);
ASSERT_EQ(event, static_cast<DWORD>(EVENT_OBJECT_LOCATIONCHANGE))
<< "Event should be EVENT_OBJECT_LOCATIONCHANGE";
ASSERT_EQ(role, static_cast<UINT>(ROLE_SYSTEM_CARET))
<< "Role should be ROLE_SYSTEM_CARET";
ASSERT_EQ(state, static_cast<UINT>(0)) << "State should be 0";
}
{
// Set caret to end of textfield.
WinAccessibilityCaretEventMonitor monitor(EVENT_OBJECT_SHOW,
EVENT_OBJECT_LOCATIONCHANGE);
textfield_test_api.ExecuteTextEditCommand(
ui::TextEditCommand::MOVE_TO_END_OF_DOCUMENT);
monitor.WaitForNextEvent(&event, &role, &state);
ASSERT_EQ(event, static_cast<DWORD>(EVENT_OBJECT_LOCATIONCHANGE))
<< "Event should be EVENT_OBJECT_LOCATIONCHANGE";
ASSERT_EQ(role, static_cast<UINT>(ROLE_SYSTEM_CARET))
<< "Role should be ROLE_SYSTEM_CARET";
ASSERT_EQ(state, static_cast<UINT>(0)) << "State should be 0";
}
{
// Move focus to a button.
LabelButton button{Button::PressedCallback(), std::u16string()};
button.SetBounds(500, 0, 200, 20);
widget_->GetRootView()->AddChildView(&button);
test::WidgetActivationWaiter waiter(widget_, true);
WinAccessibilityCaretEventMonitor monitor(EVENT_OBJECT_SHOW,
EVENT_OBJECT_LOCATIONCHANGE);
widget_->Show();
waiter.Wait();
button.SetFocusBehavior(View::FocusBehavior::ALWAYS);
button.RequestFocus();
monitor.WaitForNextEvent(&event, &role, &state);
ASSERT_EQ(event, static_cast<DWORD>(EVENT_OBJECT_HIDE))
<< "Event should be EVENT_OBJECT_HIDE";
ASSERT_EQ(role, static_cast<UINT>(ROLE_SYSTEM_CARET))
<< "Role should be ROLE_SYSTEM_CARET";
ASSERT_EQ(state, static_cast<UINT>(STATE_SYSTEM_INVISIBLE))
<< "State should be STATE_SYSTEM_INVISIBLE";
}
{
// Move focus back to the text field.
WinAccessibilityCaretEventMonitor monitor(EVENT_OBJECT_SHOW,
EVENT_OBJECT_LOCATIONCHANGE);
textfield_->RequestFocus();
monitor.WaitForNextEvent(&event, &role, &state);
ASSERT_EQ(event, static_cast<DWORD>(EVENT_OBJECT_SHOW))
<< "Event should be EVENT_OBJECT_SHOW";
ASSERT_EQ(role, static_cast<UINT>(ROLE_SYSTEM_CARET))
<< "Role should be ROLE_SYSTEM_CARET";
ASSERT_EQ(state, static_cast<UINT>(0)) << "State should be 0";
}
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/ax_system_caret_win_interactive_uitest.cc | C++ | unknown | 14,668 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/accessibility/ax_tree_source_views.h"
#include <string>
#include <vector>
#include "ui/accessibility/ax_action_data.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/accessibility/ax_tree_data.h"
#include "ui/accessibility/platform/ax_unique_id.h"
#include "ui/gfx/geometry/point_f.h"
#include "ui/gfx/geometry/transform.h"
#include "ui/views/accessibility/ax_aura_obj_cache.h"
#include "ui/views/accessibility/ax_aura_obj_wrapper.h"
#include "ui/views/accessibility/ax_virtual_view.h"
namespace views {
AXTreeSourceViews::AXTreeSourceViews(AXAuraObjWrapper* root,
const ui::AXTreeID& tree_id,
views::AXAuraObjCache* cache)
: root_(root), tree_id_(tree_id), cache_(cache) {
DCHECK(root_);
DCHECK_NE(tree_id_, ui::AXTreeIDUnknown());
}
AXTreeSourceViews::~AXTreeSourceViews() = default;
void AXTreeSourceViews::HandleAccessibleAction(const ui::AXActionData& action) {
int id = action.target_node_id;
// In Views, we only support setting the selection within a single node,
// not across multiple nodes like on the web.
if (action.action == ax::mojom::Action::kSetSelection) {
CHECK_EQ(action.anchor_node_id, action.focus_node_id);
id = action.anchor_node_id;
}
AXAuraObjWrapper* obj = GetFromId(id);
if (obj)
obj->HandleAccessibleAction(action);
}
bool AXTreeSourceViews::GetTreeData(ui::AXTreeData* tree_data) const {
tree_data->tree_id = tree_id_;
tree_data->loaded = true;
tree_data->loading_progress = 1.0;
AXAuraObjWrapper* focus = cache_->GetFocus();
if (focus)
tree_data->focus_id = focus->GetUniqueId();
return true;
}
AXAuraObjWrapper* AXTreeSourceViews::GetRoot() const {
return root_;
}
AXAuraObjWrapper* AXTreeSourceViews::GetFromId(int32_t id) const {
AXAuraObjWrapper* root = GetRoot();
// Root might not be in the cache.
if (id == root->GetUniqueId())
return root;
AXAuraObjWrapper* wrapper = cache_->Get(id);
// We must do a lookup in AXVirtualView as well if the main cache doesn't hold
// this node.
if (!wrapper && AXVirtualView::GetFromId(id)) {
AXVirtualView* virtual_view = AXVirtualView::GetFromId(id);
return virtual_view->GetOrCreateWrapper(cache_);
}
return wrapper;
}
int32_t AXTreeSourceViews::GetId(AXAuraObjWrapper* node) const {
return node->GetUniqueId();
}
void AXTreeSourceViews::CacheChildrenIfNeeded(AXAuraObjWrapper* node) {
if (node->cached_children_) {
return;
}
node->cached_children_.emplace();
node->GetChildren(&(*node->cached_children_));
}
size_t AXTreeSourceViews::GetChildCount(AXAuraObjWrapper* node) const {
std::vector<AXAuraObjWrapper*> children;
node->GetChildren(&children);
return children.size();
}
AXAuraObjWrapper* AXTreeSourceViews::ChildAt(AXAuraObjWrapper* node,
size_t index) const {
std::vector<AXAuraObjWrapper*> children;
node->GetChildren(&children);
return children[index];
}
void AXTreeSourceViews::ClearChildCache(AXAuraObjWrapper* node) {
node->cached_children_.reset();
}
AXAuraObjWrapper* AXTreeSourceViews::GetParent(AXAuraObjWrapper* node) const {
AXAuraObjWrapper* root = GetRoot();
// The root has no parent by definition.
if (node->GetUniqueId() == root->GetUniqueId())
return nullptr;
AXAuraObjWrapper* parent = node->GetParent();
// A top-level widget doesn't have a parent, so return the root.
if (!parent)
return root;
return parent;
}
bool AXTreeSourceViews::IsIgnored(AXAuraObjWrapper* node) const {
if (!node)
return false;
ui::AXNodeData out_data;
node->Serialize(&out_data);
return out_data.IsIgnored();
}
bool AXTreeSourceViews::IsEqual(AXAuraObjWrapper* node1,
AXAuraObjWrapper* node2) const {
return node1 && node2 && node1->GetUniqueId() == node2->GetUniqueId();
}
AXAuraObjWrapper* AXTreeSourceViews::GetNull() const {
return nullptr;
}
std::string AXTreeSourceViews::GetDebugString(AXAuraObjWrapper* node) const {
return node ? node->ToString() : "(null)";
}
void AXTreeSourceViews::SerializeNode(AXAuraObjWrapper* node,
ui::AXNodeData* out_data) const {
node->Serialize(out_data);
if (out_data->role == ax::mojom::Role::kWindow ||
out_data->role == ax::mojom::Role::kDialog) {
// Add clips children flag by default to these roles.
out_data->AddBoolAttribute(ax::mojom::BoolAttribute::kClipsChildren, true);
}
// Converts the global coordinates reported by each AXAuraObjWrapper
// into parent-relative coordinates to be used in the accessibility
// tree. That way when any Window, Widget, or View moves (and fires
// a location changed event), its descendants all move relative to
// it by default.
AXAuraObjWrapper* parent = node->GetParent();
if (!parent)
return;
ui::AXNodeData parent_data;
parent->Serialize(&parent_data);
out_data->relative_bounds.bounds.Offset(
-parent_data.relative_bounds.bounds.OffsetFromOrigin());
out_data->relative_bounds.offset_container_id = parent->GetUniqueId();
}
std::string AXTreeSourceViews::ToString(AXAuraObjWrapper* root,
std::string prefix) {
ui::AXNodeData data;
root->Serialize(&data);
std::string output = prefix + data.ToString() + '\n';
std::vector<AXAuraObjWrapper*> children;
root->GetChildren(&children);
prefix += prefix[0];
for (AXAuraObjWrapper* child : children)
output += ToString(child, prefix);
return output;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/ax_tree_source_views.cc | C++ | unknown | 5,737 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_ACCESSIBILITY_AX_TREE_SOURCE_VIEWS_H_
#define UI_VIEWS_ACCESSIBILITY_AX_TREE_SOURCE_VIEWS_H_
#include <string>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "ui/accessibility/ax_tree_id.h"
#include "ui/accessibility/ax_tree_source.h"
#include "ui/views/views_export.h"
namespace ui {
struct AXActionData;
struct AXNodeData;
struct AXTreeData;
} // namespace ui
namespace views {
class AXAuraObjCache;
class AXAuraObjWrapper;
// This class exposes the views hierarchy as an accessibility tree permitting
// use with other accessibility classes. Subclasses must implement GetRoot().
// The root can be an existing object in the Widget/View hierarchy or a new node
// (for example to create the "desktop" node for the extension API call
// chrome.automation.getDesktop()).
class VIEWS_EXPORT AXTreeSourceViews
: public ui::AXTreeSource<AXAuraObjWrapper*> {
public:
AXTreeSourceViews(AXAuraObjWrapper* root,
const ui::AXTreeID& tree_id,
AXAuraObjCache* cache);
AXTreeSourceViews(const AXTreeSourceViews&) = delete;
AXTreeSourceViews& operator=(const AXTreeSourceViews&) = delete;
~AXTreeSourceViews() override;
// Invokes an action on an Aura object.
void HandleAccessibleAction(const ui::AXActionData& action);
// AXTreeSource:
bool GetTreeData(ui::AXTreeData* data) const override;
AXAuraObjWrapper* GetRoot() const override;
AXAuraObjWrapper* GetFromId(int32_t id) const override;
int32_t GetId(AXAuraObjWrapper* node) const override;
void CacheChildrenIfNeeded(AXAuraObjWrapper*) override;
size_t GetChildCount(AXAuraObjWrapper* node) const override;
void ClearChildCache(AXAuraObjWrapper*) override;
AXAuraObjWrapper* ChildAt(AXAuraObjWrapper* node, size_t) const override;
AXAuraObjWrapper* GetParent(AXAuraObjWrapper* node) const override;
bool IsIgnored(AXAuraObjWrapper* node) const override;
bool IsEqual(AXAuraObjWrapper* node1, AXAuraObjWrapper* node2) const override;
AXAuraObjWrapper* GetNull() const override;
std::string GetDebugString(AXAuraObjWrapper* node) const override;
void SerializeNode(AXAuraObjWrapper* node,
ui::AXNodeData* out_data) const override;
// Useful for debugging.
std::string ToString(views::AXAuraObjWrapper* root, std::string prefix);
const ui::AXTreeID tree_id() const { return tree_id_; }
private:
// The top-level object to use for the AX tree. See class comment.
const raw_ptr<AXAuraObjWrapper, DanglingUntriaged> root_ = nullptr;
// ID to use for the AX tree.
const ui::AXTreeID tree_id_;
raw_ptr<views::AXAuraObjCache, DanglingUntriaged> cache_;
};
} // namespace views
#endif // UI_VIEWS_ACCESSIBILITY_AX_TREE_SOURCE_VIEWS_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/ax_tree_source_views.h | C++ | unknown | 2,887 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/accessibility/ax_tree_source_views.h"
#include <memory>
#include <utility>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "base/strings/utf_string_conversions.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/accessibility/ax_tree_data.h"
#include "ui/accessibility/platform/ax_unique_id.h"
#include "ui/aura/client/focus_client.h"
#include "ui/aura/test/test_window_delegate.h"
#include "ui/gfx/geometry/rect_f.h"
#include "ui/views/accessibility/ax_aura_obj_cache.h"
#include "ui/views/accessibility/ax_aura_obj_wrapper.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/widget/unique_widget_ptr.h"
#include "ui/views/widget/widget.h"
namespace views {
namespace {
// TestAXTreeSourceViews provides a root with a default tree ID.
class TestAXTreeSourceViews : public AXTreeSourceViews {
public:
TestAXTreeSourceViews(AXAuraObjWrapper* root, AXAuraObjCache* cache)
: AXTreeSourceViews(root, ui::AXTreeID::CreateNewAXTreeID(), cache) {}
TestAXTreeSourceViews(const TestAXTreeSourceViews&) = delete;
TestAXTreeSourceViews& operator=(const TestAXTreeSourceViews&) = delete;
~TestAXTreeSourceViews() override = default;
};
class AXTreeSourceViewsTest : public ViewsTestBase {
public:
AXTreeSourceViewsTest() = default;
AXTreeSourceViewsTest(const AXTreeSourceViewsTest&) = delete;
AXTreeSourceViewsTest& operator=(const AXTreeSourceViewsTest&) = delete;
~AXTreeSourceViewsTest() override = default;
// testing::Test:
void SetUp() override {
ViewsTestBase::SetUp();
widget_ = std::make_unique<Widget>();
Widget::InitParams params(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
params.bounds = gfx::Rect(11, 22, 333, 444);
params.context = GetContext();
widget_->Init(std::move(params));
widget_->SetContentsView(std::make_unique<View>());
label1_ = new Label(u"Label 1");
label1_->SetBounds(1, 1, 111, 111);
widget_->GetContentsView()->AddChildView(label1_.get());
label2_ = new Label(u"Label 2");
label2_->SetBounds(2, 2, 222, 222);
widget_->GetContentsView()->AddChildView(label2_.get());
textfield_ = new Textfield();
textfield_->SetBounds(222, 2, 20, 200);
widget_->GetContentsView()->AddChildView(textfield_.get());
}
void TearDown() override {
widget_.reset();
ViewsTestBase::TearDown();
}
UniqueWidgetPtr widget_;
raw_ptr<Label> label1_ = nullptr; // Owned by views hierarchy.
raw_ptr<Label> label2_ = nullptr; // Owned by views hierarchy.
raw_ptr<Textfield> textfield_ = nullptr; // Owned by views hierarchy.
};
TEST_F(AXTreeSourceViewsTest, Basics) {
AXAuraObjCache cache;
// Start the tree at the Widget's contents view.
AXAuraObjWrapper* root = cache.GetOrCreate(widget_->GetContentsView());
TestAXTreeSourceViews tree(root, &cache);
EXPECT_EQ(root, tree.GetRoot());
// The root has no parent.
EXPECT_FALSE(tree.GetParent(root));
// The root has the right children.
tree.CacheChildrenIfNeeded(root);
ASSERT_EQ(3u, tree.GetChildCount(root));
// The labels are the children.
AXAuraObjWrapper* label1 = tree.ChildAt(root, 0);
AXAuraObjWrapper* label2 = tree.ChildAt(root, 1);
AXAuraObjWrapper* textfield = tree.ChildAt(root, 2);
EXPECT_EQ(label1, cache.GetOrCreate(label1_));
EXPECT_EQ(label2, cache.GetOrCreate(label2_));
EXPECT_EQ(textfield, cache.GetOrCreate(textfield_));
// The parents is correct.
EXPECT_EQ(root, tree.GetParent(label1));
EXPECT_EQ(root, tree.GetParent(label2));
EXPECT_EQ(root, tree.GetParent(textfield));
// IDs match the ones in the cache.
EXPECT_EQ(root->GetUniqueId(), tree.GetId(root));
EXPECT_EQ(label1->GetUniqueId(), tree.GetId(label1));
EXPECT_EQ(label2->GetUniqueId(), tree.GetId(label2));
EXPECT_EQ(textfield->GetUniqueId(), tree.GetId(textfield));
// Reverse ID lookups work.
EXPECT_EQ(root, tree.GetFromId(root->GetUniqueId()));
EXPECT_EQ(label1, tree.GetFromId(label1->GetUniqueId()));
EXPECT_EQ(label2, tree.GetFromId(label2->GetUniqueId()));
EXPECT_EQ(textfield, tree.GetFromId(textfield->GetUniqueId()));
// Validity.
EXPECT_TRUE(root != nullptr);
// Comparisons.
EXPECT_TRUE(tree.IsEqual(label1, label1));
EXPECT_FALSE(tree.IsEqual(label1, label2));
EXPECT_FALSE(tree.IsEqual(label1, nullptr));
EXPECT_FALSE(tree.IsEqual(nullptr, label1));
// Null pointers is the null value.
EXPECT_EQ(nullptr, tree.GetNull());
}
TEST_F(AXTreeSourceViewsTest, GetTreeDataWithFocus) {
AXAuraObjCache cache;
TestAXTreeSourceViews tree(cache.GetOrCreate(widget_.get()), &cache);
textfield_->RequestFocus();
ui::AXTreeData tree_data;
tree.GetTreeData(&tree_data);
EXPECT_TRUE(tree_data.loaded);
EXPECT_EQ(cache.GetID(textfield_), tree_data.focus_id);
}
TEST_F(AXTreeSourceViewsTest, IgnoredView) {
View* ignored_view = new View();
ignored_view->GetViewAccessibility().OverrideIsIgnored(true);
widget_->GetContentsView()->AddChildView(ignored_view);
AXAuraObjCache cache;
TestAXTreeSourceViews tree(cache.GetOrCreate(widget_.get()), &cache);
EXPECT_TRUE(cache.GetOrCreate(ignored_view) != nullptr);
}
TEST_F(AXTreeSourceViewsTest, ViewWithChildTreeHasNoChildren) {
View* contents_view = widget_->GetContentsView();
contents_view->GetViewAccessibility().OverrideChildTreeID(
ui::AXTreeID::CreateNewAXTreeID());
AXAuraObjCache cache;
TestAXTreeSourceViews tree(cache.GetOrCreate(widget_.get()), &cache);
auto* ax_obj = cache.GetOrCreate(contents_view);
EXPECT_TRUE(ax_obj != nullptr);
tree.CacheChildrenIfNeeded(ax_obj);
EXPECT_EQ(0u, tree.GetChildCount(ax_obj));
EXPECT_EQ(nullptr, cache.GetOrCreate(textfield_)->GetParent());
}
#if BUILDFLAG(ENABLE_DESKTOP_AURA)
class AXTreeSourceViewsDesktopWidgetTest : public AXTreeSourceViewsTest {
public:
AXTreeSourceViewsDesktopWidgetTest() {
set_native_widget_type(ViewsTestBase::NativeWidgetType::kDesktop);
}
};
// Tests that no use-after-free when a focused child window is destroyed in
// desktop aura widget.
TEST_F(AXTreeSourceViewsDesktopWidgetTest, FocusedChildWindowDestroyed) {
AXAuraObjCache cache;
AXAuraObjWrapper* root_wrapper =
cache.GetOrCreate(widget_->GetNativeWindow()->GetRootWindow());
EXPECT_NE(nullptr, root_wrapper);
aura::test::TestWindowDelegate child_delegate;
aura::Window* child = new aura::Window(&child_delegate);
child->Init(ui::LAYER_NOT_DRAWN);
widget_->GetNativeView()->AddChild(child);
aura::client::GetFocusClient(widget_->GetNativeView())->FocusWindow(child);
AXAuraObjWrapper* child_wrapper = cache.GetOrCreate(child);
EXPECT_NE(nullptr, child_wrapper);
// GetFocus() reflects the focused child window.
EXPECT_NE(nullptr, cache.GetFocus());
test::WidgetDestroyedWaiter waiter(widget_.get());
// Close the widget to destroy the child.
widget_.reset();
// Wait for the async widget close.
waiter.Wait();
// GetFocus() should return null and no use-after-free to call it.
EXPECT_EQ(nullptr, cache.GetFocus());
}
#endif // defined(USE_AURA)
} // namespace
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/ax_tree_source_views_unittest.cc | C++ | unknown | 7,415 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/accessibility/ax_view_obj_wrapper.h"
#include <string>
#include <vector>
#include "ui/accessibility/ax_action_data.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/accessibility/platform/ax_unique_id.h"
#include "ui/views/accessibility/ax_aura_obj_cache.h"
#include "ui/views/accessibility/ax_virtual_view.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/widget/widget.h"
namespace views {
AXViewObjWrapper::AXViewObjWrapper(AXAuraObjCache* aura_obj_cache, View* view)
: AXAuraObjWrapper(aura_obj_cache), view_(view) {
if (view->GetWidget())
aura_obj_cache_->GetOrCreate(view->GetWidget());
observation_.Observe(view);
}
AXViewObjWrapper::~AXViewObjWrapper() = default;
AXAuraObjWrapper* AXViewObjWrapper::GetParent() {
if (view_->parent()) {
if (view_->parent()->GetViewAccessibility().GetChildTreeID() !=
ui::AXTreeIDUnknown())
return nullptr;
return aura_obj_cache_->GetOrCreate(view_->parent());
}
if (view_->GetWidget())
return aura_obj_cache_->GetOrCreate(view_->GetWidget());
return nullptr;
}
void AXViewObjWrapper::GetChildren(
std::vector<AXAuraObjWrapper*>* out_children) {
const ViewAccessibility& view_accessibility = view_->GetViewAccessibility();
// Ignore this view's descendants if it has a child tree.
if (view_accessibility.GetChildTreeID() != ui::AXTreeIDUnknown())
return;
if (view_accessibility.IsLeaf())
return;
// TODO(dtseng): Need to handle |Widget| child of |View|.
for (View* child : view_->children()) {
if (child->GetVisible())
out_children->push_back(aura_obj_cache_->GetOrCreate(child));
}
for (const auto& child : view_accessibility.virtual_children())
out_children->push_back(child->GetOrCreateWrapper(aura_obj_cache_));
}
void AXViewObjWrapper::Serialize(ui::AXNodeData* out_node_data) {
ViewAccessibility& view_accessibility = view_->GetViewAccessibility();
view_accessibility.GetAccessibleNodeData(out_node_data);
if (view_accessibility.GetNextWindowFocus()) {
out_node_data->AddIntAttribute(
ax::mojom::IntAttribute::kNextWindowFocusId,
aura_obj_cache_->GetOrCreate(view_accessibility.GetNextWindowFocus())
->GetUniqueId());
}
if (view_accessibility.GetPreviousWindowFocus()) {
out_node_data->AddIntAttribute(
ax::mojom::IntAttribute::kPreviousWindowFocusId,
aura_obj_cache_
->GetOrCreate(view_accessibility.GetPreviousWindowFocus())
->GetUniqueId());
}
}
ui::AXNodeID AXViewObjWrapper::GetUniqueId() const {
return view_->GetViewAccessibility().GetUniqueId();
}
bool AXViewObjWrapper::HandleAccessibleAction(const ui::AXActionData& action) {
return view_->HandleAccessibleAction(action);
}
std::string AXViewObjWrapper::ToString() const {
return std::string(view_->GetClassName());
}
void AXViewObjWrapper::OnViewIsDeleting(View* observed_view) {
DCHECK_EQ(view_, observed_view);
observation_.Reset();
// Remove() deletes |this|, so this should be the last line in the function.
aura_obj_cache_->Remove(observed_view);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/ax_view_obj_wrapper.cc | C++ | unknown | 3,295 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_ACCESSIBILITY_AX_VIEW_OBJ_WRAPPER_H_
#define UI_VIEWS_ACCESSIBILITY_AX_VIEW_OBJ_WRAPPER_H_
#include <stdint.h>
#include <string>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "base/scoped_observation.h"
#include "ui/views/accessibility/ax_aura_obj_wrapper.h"
#include "ui/views/view.h"
#include "ui/views/view_observer.h"
namespace views {
class AXAuraObjCache;
// Describes a |View| for use with other AX classes.
class AXViewObjWrapper : public AXAuraObjWrapper, public ViewObserver {
public:
// |aura_obj_cache| must outlive this object.
AXViewObjWrapper(AXAuraObjCache* aura_obj_cache, View* view);
AXViewObjWrapper(const AXViewObjWrapper&) = delete;
AXViewObjWrapper& operator=(const AXViewObjWrapper&) = delete;
~AXViewObjWrapper() override;
View* view() { return view_; }
// AXAuraObjWrapper overrides.
AXAuraObjWrapper* GetParent() override;
void GetChildren(std::vector<AXAuraObjWrapper*>* out_children) override;
void Serialize(ui::AXNodeData* out_node_data) override;
ui::AXNodeID GetUniqueId() const final;
bool HandleAccessibleAction(const ui::AXActionData& action) override;
std::string ToString() const override;
// ViewObserver overrides.
void OnViewIsDeleting(View* observed_view) override;
private:
// This is never null, as we destroy ourselves when the view is deleted.
const raw_ptr<View> view_;
base::ScopedObservation<View, ViewObserver> observation_{this};
};
} // namespace views
#endif // UI_VIEWS_ACCESSIBILITY_AX_VIEW_OBJ_WRAPPER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/ax_view_obj_wrapper.h | C++ | unknown | 1,688 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/accessibility/ax_virtual_view.h"
#include <stdint.h>
#include <algorithm>
#include <map>
#include <utility>
#include "base/containers/adapters.h"
#include "base/functional/callback.h"
#include "base/no_destructor.h"
#include "base/ranges/algorithm.h"
#include "build/build_config.h"
#include "ui/accessibility/ax_action_data.h"
#include "ui/accessibility/ax_tree_data.h"
#include "ui/accessibility/platform/ax_platform_node.h"
#include "ui/base/layout.h"
#include "ui/base/ui_base_types.h"
#include "ui/gfx/geometry/rect_conversions.h"
#include "ui/views/accessibility/ax_event_manager.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/accessibility/view_ax_platform_node_delegate.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
#if BUILDFLAG(IS_WIN)
#include "ui/views/win/hwnd_util.h"
#endif
namespace views {
// Tracks all virtual ax views.
std::map<int32_t, AXVirtualView*>& GetIdMap() {
static base::NoDestructor<std::map<int32_t, AXVirtualView*>> id_to_obj_map;
return *id_to_obj_map;
}
// static
const char AXVirtualView::kViewClassName[] = "AXVirtualView";
// static
AXVirtualView* AXVirtualView::GetFromId(int32_t id) {
auto& id_map = GetIdMap();
const auto& it = id_map.find(id);
return it != id_map.end() ? it->second : nullptr;
}
AXVirtualView::AXVirtualView() {
GetIdMap()[unique_id_.Get()] = this;
ax_platform_node_ = ui::AXPlatformNode::Create(this);
DCHECK(ax_platform_node_);
custom_data_.AddStringAttribute(ax::mojom::StringAttribute::kClassName,
GetViewClassName());
}
AXVirtualView::~AXVirtualView() {
GetIdMap().erase(unique_id_.Get());
DCHECK(!parent_view_ || !virtual_parent_view_)
<< "Either |parent_view_| or |virtual_parent_view_| could be set but "
"not both.";
if (ax_platform_node_) {
// Clear ax_platform_node_ and return another raw_ptr instance that is
// allowed to dangle.
ax_platform_node_.ExtractAsDangling()->Destroy();
}
#if defined(USE_AURA)
if (ax_aura_obj_cache_)
ax_aura_obj_cache_->Remove(this);
#endif
}
void AXVirtualView::AddChildView(std::unique_ptr<AXVirtualView> view) {
DCHECK(view);
if (view->virtual_parent_view_ == this)
return; // Already a child of this virtual view.
AddChildViewAt(std::move(view), children_.size());
}
void AXVirtualView::AddChildViewAt(std::unique_ptr<AXVirtualView> view,
size_t index) {
DCHECK(view);
CHECK_NE(view.get(), this)
<< "You cannot add an AXVirtualView as its own child.";
DCHECK(!view->parent_view_) << "This |view| already has a View "
"parent. Call RemoveVirtualChildView first.";
DCHECK(!view->virtual_parent_view_) << "This |view| already has an "
"AXVirtualView parent. Call "
"RemoveChildView first.";
DCHECK_LE(index, children_.size());
view->virtual_parent_view_ = this;
children_.insert(children_.begin() + static_cast<ptrdiff_t>(index),
std::move(view));
if (GetOwnerView()) {
GetOwnerView()->NotifyAccessibilityEvent(ax::mojom::Event::kChildrenChanged,
true);
}
}
void AXVirtualView::ReorderChildView(AXVirtualView* view, size_t index) {
DCHECK(view);
index = std::min(index, children_.size() - 1);
DCHECK_EQ(view->virtual_parent_view_, this);
if (children_[index].get() == view)
return;
auto cur_index = GetIndexOf(view);
if (!cur_index.has_value())
return;
std::unique_ptr<AXVirtualView> child =
std::move(children_[cur_index.value()]);
children_.erase(children_.begin() +
static_cast<ptrdiff_t>(cur_index.value()));
children_.insert(children_.begin() + static_cast<ptrdiff_t>(index),
std::move(child));
GetOwnerView()->NotifyAccessibilityEvent(ax::mojom::Event::kChildrenChanged,
true);
}
std::unique_ptr<AXVirtualView> AXVirtualView::RemoveFromParentView() {
if (parent_view_)
return parent_view_->RemoveVirtualChildView(this);
// This virtual view hasn't been added to a parent view yet.
CHECK(virtual_parent_view_)
<< "Cannot remove from parent view if there is no parent.";
return virtual_parent_view_->RemoveChildView(this);
}
std::unique_ptr<AXVirtualView> AXVirtualView::RemoveChildView(
AXVirtualView* view) {
DCHECK(view);
auto cur_index = GetIndexOf(view);
if (!cur_index.has_value())
return {};
bool focus_changed = false;
if (GetOwnerView()) {
ViewAccessibility& view_accessibility =
GetOwnerView()->GetViewAccessibility();
if (view_accessibility.FocusedVirtualChild() &&
Contains(view_accessibility.FocusedVirtualChild())) {
focus_changed = true;
}
}
std::unique_ptr<AXVirtualView> child =
std::move(children_[cur_index.value()]);
children_.erase(children_.begin() +
static_cast<ptrdiff_t>(cur_index.value()));
child->virtual_parent_view_ = nullptr;
child->populate_data_callback_.Reset();
if (GetOwnerView()) {
if (focus_changed)
GetOwnerView()->GetViewAccessibility().OverrideFocus(nullptr);
GetOwnerView()->NotifyAccessibilityEvent(ax::mojom::Event::kChildrenChanged,
true);
}
return child;
}
void AXVirtualView::RemoveAllChildViews() {
while (!children_.empty())
RemoveChildView(children_.back().get());
}
bool AXVirtualView::Contains(const AXVirtualView* view) const {
DCHECK(view);
for (const AXVirtualView* v = view; v; v = v->virtual_parent_view_) {
if (v == this)
return true;
}
return false;
}
absl::optional<size_t> AXVirtualView::GetIndexOf(
const AXVirtualView* view) const {
DCHECK(view);
const auto iter =
base::ranges::find(children_, view, &std::unique_ptr<AXVirtualView>::get);
return iter != children_.end() ? absl::make_optional(static_cast<size_t>(
iter - children_.begin()))
: absl::nullopt;
}
const char* AXVirtualView::GetViewClassName() const {
return kViewClassName;
}
gfx::NativeViewAccessible AXVirtualView::GetNativeObject() const {
DCHECK(ax_platform_node_);
return ax_platform_node_->GetNativeViewAccessible();
}
void AXVirtualView::NotifyAccessibilityEvent(ax::mojom::Event event_type) {
DCHECK(ax_platform_node_);
if (GetOwnerView()) {
const ViewAccessibility::AccessibilityEventsCallback& events_callback =
GetOwnerView()->GetViewAccessibility().accessibility_events_callback();
if (events_callback)
events_callback.Run(this, event_type);
}
// This is used on platforms that have a native accessibility API.
ax_platform_node_->NotifyAccessibilityEvent(event_type);
// This is used on platforms that don't have a native accessibility API.
AXEventManager::Get()->NotifyVirtualViewEvent(this, event_type);
}
ui::AXNodeData& AXVirtualView::GetCustomData() {
return custom_data_;
}
void AXVirtualView::SetPopulateDataCallback(
base::RepeatingCallback<void(ui::AXNodeData*)> callback) {
populate_data_callback_ = std::move(callback);
}
void AXVirtualView::UnsetPopulateDataCallback() {
populate_data_callback_.Reset();
}
// ui::AXPlatformNodeDelegate
const ui::AXNodeData& AXVirtualView::GetData() const {
// Make a copy of our |custom_data_| so that any modifications will not be
// made to the data that users of this class will be manipulating.
static ui::AXNodeData node_data;
node_data = custom_data_;
node_data.id = GetUniqueId().Get();
if (!GetOwnerView() || !GetOwnerView()->GetEnabled())
node_data.SetRestriction(ax::mojom::Restriction::kDisabled);
if (!GetOwnerView() || !GetOwnerView()->IsDrawn())
node_data.AddState(ax::mojom::State::kInvisible);
if (GetOwnerView() && GetOwnerView()->context_menu_controller())
node_data.AddAction(ax::mojom::Action::kShowContextMenu);
if (populate_data_callback_ && GetOwnerView())
populate_data_callback_.Run(&node_data);
// According to the ARIA spec, the node should not be ignored if it is
// focusable. This is to ensure that the focusable node is both understandable
// and operable.
if (node_data.HasState(ax::mojom::State::kIgnored) &&
node_data.HasState(ax::mojom::State::kFocusable)) {
node_data.RemoveState(ax::mojom::State::kIgnored);
}
return node_data;
}
size_t AXVirtualView::GetChildCount() const {
size_t count = 0;
for (const std::unique_ptr<AXVirtualView>& child : children_) {
if (child->IsIgnored()) {
count += child->GetChildCount();
} else {
++count;
}
}
return count;
}
gfx::NativeViewAccessible AXVirtualView::ChildAtIndex(size_t index) const {
DCHECK_LT(index, GetChildCount())
<< "|index| should be less than the child count.";
for (const std::unique_ptr<AXVirtualView>& child : children_) {
if (child->IsIgnored()) {
size_t child_count = child->GetChildCount();
if (index < child_count)
return child->ChildAtIndex(index);
index -= child_count;
} else {
if (index == 0)
return child->GetNativeObject();
--index;
}
}
NOTREACHED_NORETURN() << "|index| should be less than the child count.";
}
#if !BUILDFLAG(IS_MAC)
gfx::NativeViewAccessible AXVirtualView::GetNSWindow() {
NOTREACHED_NORETURN();
}
#endif
gfx::NativeViewAccessible AXVirtualView::GetNativeViewAccessible() {
return GetNativeObject();
}
gfx::NativeViewAccessible AXVirtualView::GetParent() const {
if (parent_view_) {
if (!parent_view_->IsIgnored())
return parent_view_->GetNativeObject();
return GetDelegate()->GetParent();
}
if (virtual_parent_view_) {
if (virtual_parent_view_->IsIgnored())
return virtual_parent_view_->GetParent();
return virtual_parent_view_->GetNativeObject();
}
// This virtual view hasn't been added to a parent view yet.
return nullptr;
}
gfx::Rect AXVirtualView::GetBoundsRect(
const ui::AXCoordinateSystem coordinate_system,
const ui::AXClippingBehavior clipping_behavior,
ui::AXOffscreenResult* offscreen_result) const {
// We could optionally add clipping here if ever needed.
// TODO(nektar): Implement bounds that are relative to the parent.
gfx::Rect bounds = gfx::ToEnclosingRect(GetData().relative_bounds.bounds);
View* owner_view = GetOwnerView();
if (owner_view && owner_view->GetWidget())
View::ConvertRectToScreen(owner_view, &bounds);
switch (coordinate_system) {
case ui::AXCoordinateSystem::kScreenDIPs:
return bounds;
case ui::AXCoordinateSystem::kScreenPhysicalPixels: {
float scale_factor = 1.0;
if (owner_view && owner_view->GetWidget()) {
gfx::NativeView native_view = owner_view->GetWidget()->GetNativeView();
if (native_view)
scale_factor = ui::GetScaleFactorForNativeView(native_view);
}
return gfx::ScaleToEnclosingRect(bounds, scale_factor);
}
case ui::AXCoordinateSystem::kRootFrame:
case ui::AXCoordinateSystem::kFrame:
NOTIMPLEMENTED();
return gfx::Rect();
}
}
gfx::NativeViewAccessible AXVirtualView::HitTestSync(
int screen_physical_pixel_x,
int screen_physical_pixel_y) const {
if (GetData().IsInvisible())
return nullptr;
// Check if the point is within any of the virtual children of this view.
// AXVirtualView's HitTestSync is a recursive function that will return the
// deepest child, since it does not support relative bounds.
// Search the greater indices first, since they're on top in the z-order.
for (const std::unique_ptr<AXVirtualView>& child :
base::Reversed(children_)) {
gfx::NativeViewAccessible result =
child->HitTestSync(screen_physical_pixel_x, screen_physical_pixel_y);
if (result)
return result;
}
// If it's not inside any of our virtual children, and it's inside the bounds
// of this virtual view, then it's inside this virtual view.
gfx::Rect bounds_in_screen_physical_pixels =
GetBoundsRect(ui::AXCoordinateSystem::kScreenPhysicalPixels,
ui::AXClippingBehavior::kUnclipped);
if (bounds_in_screen_physical_pixels.Contains(
static_cast<float>(screen_physical_pixel_x),
static_cast<float>(screen_physical_pixel_y)) &&
!IsIgnored()) {
return GetNativeObject();
}
return nullptr;
}
gfx::NativeViewAccessible AXVirtualView::GetFocus() const {
View* owner_view = GetOwnerView();
if (owner_view) {
if (!(owner_view->HasFocus())) {
return nullptr;
}
return owner_view->GetViewAccessibility().GetFocusedDescendant();
}
// This virtual view hasn't been added to a parent view yet.
return nullptr;
}
ui::AXPlatformNode* AXVirtualView::GetFromNodeID(int32_t id) {
AXVirtualView* virtual_view = GetFromId(id);
if (virtual_view) {
return virtual_view->ax_platform_node();
}
return nullptr;
}
bool AXVirtualView::AccessibilityPerformAction(const ui::AXActionData& data) {
bool result = false;
if (custom_data_.HasAction(data.action))
result = HandleAccessibleAction(data);
if (!result && GetOwnerView())
return HandleAccessibleActionInOwnerView(data);
return result;
}
bool AXVirtualView::ShouldIgnoreHoveredStateForTesting() {
// TODO(nektar): Implement.
return false;
}
bool AXVirtualView::IsOffscreen() const {
// TODO(nektar): Implement.
return false;
}
const ui::AXUniqueId& AXVirtualView::GetUniqueId() const {
return unique_id_;
}
// Virtual views need to implement this function in order for accessibility
// events to be routed correctly.
gfx::AcceleratedWidget AXVirtualView::GetTargetForNativeAccessibilityEvent() {
#if BUILDFLAG(IS_WIN)
if (GetOwnerView())
return HWNDForView(GetOwnerView());
#endif
return gfx::kNullAcceleratedWidget;
}
std::vector<int32_t> AXVirtualView::GetColHeaderNodeIds() const {
return GetDelegate()->GetColHeaderNodeIds();
}
std::vector<int32_t> AXVirtualView::GetColHeaderNodeIds(int col_index) const {
return GetDelegate()->GetColHeaderNodeIds(col_index);
}
absl::optional<int32_t> AXVirtualView::GetCellId(int row_index,
int col_index) const {
return GetDelegate()->GetCellId(row_index, col_index);
}
bool AXVirtualView::HandleAccessibleAction(
const ui::AXActionData& action_data) {
if (!GetOwnerView())
return false;
switch (action_data.action) {
case ax::mojom::Action::kShowContextMenu: {
const gfx::Rect screen_bounds = GetBoundsRect(
ui::AXCoordinateSystem::kScreenDIPs, ui::AXClippingBehavior::kClipped,
nullptr /* offscreen_result */);
if (!screen_bounds.IsEmpty()) {
GetOwnerView()->ShowContextMenu(screen_bounds.CenterPoint(),
ui::MENU_SOURCE_KEYBOARD);
return true;
}
break;
}
default:
break;
}
return HandleAccessibleActionInOwnerView(action_data);
}
bool AXVirtualView::HandleAccessibleActionInOwnerView(
const ui::AXActionData& action_data) {
DCHECK(GetOwnerView());
// Save the node id so that the owner view can determine which virtual view
// is being targeted for action.
ui::AXActionData forwarded_action_data = action_data;
forwarded_action_data.target_node_id = GetData().id;
return GetOwnerView()->HandleAccessibleAction(forwarded_action_data);
}
void AXVirtualView::set_cache(AXAuraObjCache* cache) {
#if defined(USE_AURA)
if (ax_aura_obj_cache_ && cache)
ax_aura_obj_cache_->Remove(this);
#endif
ax_aura_obj_cache_ = cache;
}
View* AXVirtualView::GetOwnerView() const {
if (parent_view_)
return parent_view_->view();
if (virtual_parent_view_)
return virtual_parent_view_->GetOwnerView();
// This virtual view hasn't been added to a parent view yet.
return nullptr;
}
ViewAXPlatformNodeDelegate* AXVirtualView::GetDelegate() const {
DCHECK(GetOwnerView());
return static_cast<ViewAXPlatformNodeDelegate*>(
&GetOwnerView()->GetViewAccessibility());
}
AXVirtualViewWrapper* AXVirtualView::GetOrCreateWrapper(
views::AXAuraObjCache* cache) {
#if defined(USE_AURA)
return static_cast<AXVirtualViewWrapper*>(cache->GetOrCreate(this));
#else
return nullptr;
#endif
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/ax_virtual_view.cc | C++ | unknown | 16,551 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_ACCESSIBILITY_AX_VIRTUAL_VIEW_H_
#define UI_VIEWS_ACCESSIBILITY_AX_VIRTUAL_VIEW_H_
#include <stdint.h>
#include <memory>
#include <vector>
#include "base/functional/callback_forward.h"
#include "base/memory/raw_ptr.h"
#include "build/build_config.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/accessibility/ax_enums.mojom-forward.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/accessibility/platform/ax_platform_node_delegate.h"
#include "ui/accessibility/platform/ax_unique_id.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/rect_f.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/views_export.h"
#if defined(USE_AURA)
#include "ui/views/accessibility/ax_virtual_view_wrapper.h"
#endif
namespace ui {
struct AXActionData;
class AXUniqueId;
} // namespace ui
namespace views {
class AXAuraObjCache;
class AXVirtualViewWrapper;
class View;
class ViewAccessibility;
class ViewAXPlatformNodeDelegate;
namespace test {
class AXVirtualViewTest;
} // namespace test
// Implements a virtual view that is used only for accessibility.
//
// Some composite widgets such as tree and table views may utilize lightweight
// UI objects instead of actual views for displaying and managing their
// contents. We need a corresponding virtual accessibility view to expose
// information about these lightweight Ui objects to accessibility. An
// AXVirtualView is owned by its parent, which could either be a
// ViewAccessibility or an AXVirtualView.
class VIEWS_EXPORT AXVirtualView : public ui::AXPlatformNodeDelegate {
public:
using AXVirtualViews = std::vector<std::unique_ptr<AXVirtualView>>;
static AXVirtualView* GetFromId(int32_t id);
AXVirtualView();
AXVirtualView(const AXVirtualView&) = delete;
AXVirtualView& operator=(const AXVirtualView&) = delete;
~AXVirtualView() override;
//
// Methods for managing parent - child relationships.
//
// Adds |view| as a child of this virtual view, optionally at |index|.
// We take ownership of our children.
void AddChildView(std::unique_ptr<AXVirtualView> view);
void AddChildViewAt(std::unique_ptr<AXVirtualView> view, size_t index);
// Moves |view| to the specified |index|. A too-large value for |index| moves
// |view| to the end.
void ReorderChildView(AXVirtualView* view, size_t index);
// Removes this virtual view from its parent, which could either be a virtual
// or a real view. Hands ownership of this view back to the caller.
std::unique_ptr<AXVirtualView> RemoveFromParentView();
// Removes |view| from this virtual view. The view's parent will change to
// nullptr. Hands ownership back to the caller.
std::unique_ptr<AXVirtualView> RemoveChildView(AXVirtualView* view);
// Removes all the children from this virtual view.
// The virtual views are deleted.
void RemoveAllChildViews();
const AXVirtualViews& children() const { return children_; }
// Returns the parent ViewAccessibility if the parent is a real View and not
// an AXVirtualView. Returns nullptr otherwise.
const ViewAccessibility* parent_view() const { return parent_view_; }
ViewAccessibility* parent_view() { return parent_view_; }
// Returns the parent view if the parent is an AXVirtualView and not a real
// View. Returns nullptr otherwise.
const AXVirtualView* virtual_parent_view() const {
return virtual_parent_view_;
}
AXVirtualView* virtual_parent_view() { return virtual_parent_view_; }
ui::AXPlatformNode* ax_platform_node() { return ax_platform_node_; }
// Returns true if |view| is contained within the hierarchy of this
// AXVirtualView, even as an indirect descendant. Will return true if |view|
// is also this AXVirtualView.
bool Contains(const AXVirtualView* view) const;
// Returns the index of |view|, or nullopt if |view| is not a child of this
// virtual view.
absl::optional<size_t> GetIndexOf(const AXVirtualView* view) const;
//
// Other methods.
//
const char* GetViewClassName() const;
gfx::NativeViewAccessible GetNativeObject() const;
void NotifyAccessibilityEvent(ax::mojom::Event event_type);
// Allows clients to modify the AXNodeData for this virtual view. This should
// be used for attributes that are relatively stable and do not change
// dynamically.
ui::AXNodeData& GetCustomData();
// Allows clients to modify the AXNodeData for this virtual view dynamically
// via a callback. This should be used for attributes that change often and
// would be queried every time a client accesses this view's AXNodeData.
void SetPopulateDataCallback(
base::RepeatingCallback<void(ui::AXNodeData*)> callback);
void UnsetPopulateDataCallback();
// ui::AXPlatformNodeDelegate. Note that
// - Some of these functions have Mac-specific implementations in
// ax_virtual_view_mac.mm.
// - GetChildCount(), ChildAtIndex(), and GetParent() are used by assistive
// technologies to access the unignored accessibility tree, which doesn't
// necessarily reflect the internal descendant tree. (An ignored node means
// that the node should not be exposed to the platform.)
const ui::AXNodeData& GetData() const override;
size_t GetChildCount() const override;
gfx::NativeViewAccessible ChildAtIndex(size_t index) const override;
gfx::NativeViewAccessible GetNSWindow() override;
gfx::NativeViewAccessible GetNativeViewAccessible() override;
gfx::NativeViewAccessible GetParent() const override;
gfx::Rect GetBoundsRect(
const ui::AXCoordinateSystem coordinate_system,
const ui::AXClippingBehavior clipping_behavior,
ui::AXOffscreenResult* offscreen_result = nullptr) const override;
gfx::NativeViewAccessible HitTestSync(
int screen_physical_pixel_x,
int screen_physical_pixel_y) const override;
gfx::NativeViewAccessible GetFocus() const override;
ui::AXPlatformNode* GetFromNodeID(int32_t id) override;
bool AccessibilityPerformAction(const ui::AXActionData& data) override;
bool ShouldIgnoreHoveredStateForTesting() override;
bool IsOffscreen() const override;
const ui::AXUniqueId& GetUniqueId() const override;
gfx::AcceleratedWidget GetTargetForNativeAccessibilityEvent() override;
std::vector<int32_t> GetColHeaderNodeIds() const override;
std::vector<int32_t> GetColHeaderNodeIds(int col_index) const override;
absl::optional<int32_t> GetCellId(int row_index,
int col_index) const override;
// Gets the real View that owns our shallowest virtual ancestor,, if any.
View* GetOwnerView() const;
// Gets the delegate for our owning View; if we are on a platform that exposes
// Views directly to platform APIs instead of serializing them into an AXTree.
// Otherwise, returns nullptr.
ViewAXPlatformNodeDelegate* GetDelegate() const;
// Gets or creates a wrapper suitable for use with tree sources.
AXVirtualViewWrapper* GetOrCreateWrapper(views::AXAuraObjCache* cache);
// Handle a request from assistive technology to perform an action on this
// virtual view. Returns true on success, but note that the success/failure is
// not propagated to the client that requested the action, since the
// request is sometimes asynchronous. The right way to send a response is
// via NotifyAccessibilityEvent().
virtual bool HandleAccessibleAction(const ui::AXActionData& action_data);
protected:
// Forwards a request from assistive technology to perform an action on this
// virtual view to the owner view's accessible action handler.
bool HandleAccessibleActionInOwnerView(const ui::AXActionData& action_data);
private:
// Needed in order to access set_cache(), so that AXAuraObjCache can
// track when an AXVirtualViewWrapper is deleted.
friend class AXAuraObjCache;
friend class AXVirtualViewWrapper;
friend class views::test::AXVirtualViewTest;
// Internal class name.
static const char kViewClassName[];
// The AXAuraObjCache associated with our wrapper, if any. This is
// called by friend classes AXAuraObjCache and AXVirtualViewWrapper.
void set_cache(AXAuraObjCache* cache);
// Sets the parent ViewAccessibility if the parent is a real View and not an
// AXVirtualView. It is invalid to set both |parent_view_| and
// |virtual_parent_view_|.
void set_parent_view(ViewAccessibility* view_accessibility) {
DCHECK(!virtual_parent_view_);
parent_view_ = view_accessibility;
}
// We own this, but it is reference-counted on some platforms so we can't use
// a unique_ptr. It is destroyed in the destructor.
raw_ptr<ui::AXPlatformNode> ax_platform_node_;
// Weak. Owns us if not nullptr.
// Either |parent_view_| or |virtual_parent_view_| should be set but not both.
raw_ptr<ViewAccessibility> parent_view_ = nullptr;
// Weak. Owns us if not nullptr.
// Either |parent_view_| or |virtual_parent_view_| should be set but not both.
raw_ptr<AXVirtualView> virtual_parent_view_ = nullptr;
// We own our children.
AXVirtualViews children_;
// The AXAuraObjCache that owns the AXVirtualViewWrapper associated with
// this object, if any.
raw_ptr<AXAuraObjCache> ax_aura_obj_cache_ = nullptr;
ui::AXUniqueId unique_id_;
ui::AXNodeData custom_data_;
base::RepeatingCallback<void(ui::AXNodeData*)> populate_data_callback_;
friend class ViewAccessibility;
};
} // namespace views
#endif // UI_VIEWS_ACCESSIBILITY_AX_VIRTUAL_VIEW_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/ax_virtual_view.h | C++ | unknown | 9,589 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/accessibility/ax_virtual_view.h"
#include "ui/views/cocoa/native_widget_mac_ns_window_host.h"
#include "ui/views/widget/widget.h"
namespace views {
gfx::NativeViewAccessible AXVirtualView::GetNSWindow() {
View* owner = GetOwnerView();
if (!owner)
return nil;
Widget* widget = owner->GetWidget();
if (!widget)
return nil;
auto* window_host = NativeWidgetMacNSWindowHost::GetFromNativeWindow(
widget->GetNativeWindow());
if (!window_host)
return nil;
return window_host->GetNativeViewAccessibleForNSWindow();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/ax_virtual_view_mac.mm | Objective-C++ | unknown | 733 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/accessibility/ax_virtual_view.h"
#include <utility>
#include <vector>
#include "base/functional/callback.h"
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "build/build_config.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/accessibility/ax_enums.mojom.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/geometry/rect.h"
#include "ui/gfx/geometry/size.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/accessibility/view_ax_platform_node_delegate.h"
#include "ui/views/controls/button/button.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
#if BUILDFLAG(IS_WIN)
#include "ui/views/win/hwnd_util.h"
#endif
namespace views::test {
namespace {
class TestButton : public Button {
public:
TestButton() : Button(Button::PressedCallback()) {}
TestButton(const TestButton&) = delete;
TestButton& operator=(const TestButton&) = delete;
~TestButton() override = default;
};
} // namespace
class AXVirtualViewTest : public ViewsTestBase {
public:
AXVirtualViewTest() : ax_mode_setter_(ui::kAXModeComplete) {}
AXVirtualViewTest(const AXVirtualViewTest&) = delete;
AXVirtualViewTest& operator=(const AXVirtualViewTest&) = delete;
~AXVirtualViewTest() override = default;
void SetUp() override {
ViewsTestBase::SetUp();
widget_ = new Widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.bounds = gfx::Rect(0, 0, 200, 200);
widget_->Init(std::move(params));
button_ = new TestButton;
button_->SetSize(gfx::Size(20, 20));
button_->SetAccessibleName(u"Button");
widget_->GetContentsView()->AddChildView(button_.get());
virtual_label_ = new AXVirtualView;
virtual_label_->GetCustomData().role = ax::mojom::Role::kStaticText;
virtual_label_->GetCustomData().SetNameChecked("Label");
button_->GetViewAccessibility().AddVirtualChildView(
base::WrapUnique(virtual_label_.get()));
widget_->Show();
ViewAccessibility::AccessibilityEventsCallback
accessibility_events_callback = base::BindRepeating(
[](std::vector<std::pair<const ui::AXPlatformNodeDelegate*,
const ax::mojom::Event>>*
accessibility_events,
const ui::AXPlatformNodeDelegate* delegate,
const ax::mojom::Event event_type) {
DCHECK(accessibility_events);
accessibility_events->push_back({delegate, event_type});
},
&accessibility_events_);
button_->GetViewAccessibility().set_accessibility_events_callback(
std::move(accessibility_events_callback));
}
void TearDown() override {
if (!widget_->IsClosed())
widget_->Close();
ViewsTestBase::TearDown();
}
protected:
ViewAXPlatformNodeDelegate* GetButtonAccessibility() const {
return static_cast<ViewAXPlatformNodeDelegate*>(
&button_->GetViewAccessibility());
}
#if defined(USE_AURA)
void SetCache(AXVirtualView& virtual_view, AXAuraObjCache& cache) const {
virtual_view.set_cache(&cache);
}
#endif // defined(USE_AURA)
void ExpectReceivedAccessibilityEvents(
const std::vector<std::pair<const ui::AXPlatformNodeDelegate*,
const ax::mojom::Event>>& expected_events) {
EXPECT_THAT(accessibility_events_, testing::ContainerEq(expected_events));
accessibility_events_.clear();
}
raw_ptr<Widget> widget_;
raw_ptr<Button> button_;
// Weak, |button_| owns this.
raw_ptr<AXVirtualView> virtual_label_;
private:
std::vector<
std::pair<const ui::AXPlatformNodeDelegate*, const ax::mojom::Event>>
accessibility_events_;
ScopedAXModeSetter ax_mode_setter_;
};
TEST_F(AXVirtualViewTest, AccessibilityRoleAndName) {
EXPECT_EQ(ax::mojom::Role::kButton, GetButtonAccessibility()->GetRole());
EXPECT_EQ(ax::mojom::Role::kStaticText, virtual_label_->GetRole());
EXPECT_EQ("Label", virtual_label_->GetStringAttribute(
ax::mojom::StringAttribute::kName));
}
// The focusable state of a virtual view should not depend on the focusable
// state of the real view ancestor, however the enabled state should.
TEST_F(AXVirtualViewTest, FocusableAndEnabledState) {
virtual_label_->GetCustomData().AddState(ax::mojom::State::kFocusable);
EXPECT_TRUE(GetButtonAccessibility()->HasState(ax::mojom::State::kFocusable));
EXPECT_TRUE(virtual_label_->HasState(ax::mojom::State::kFocusable));
EXPECT_EQ(ax::mojom::Restriction::kNone,
GetButtonAccessibility()->GetData().GetRestriction());
EXPECT_EQ(ax::mojom::Restriction::kNone,
virtual_label_->GetData().GetRestriction());
button_->SetFocusBehavior(View::FocusBehavior::NEVER);
EXPECT_FALSE(
GetButtonAccessibility()->HasState(ax::mojom::State::kFocusable));
EXPECT_TRUE(virtual_label_->HasState(ax::mojom::State::kFocusable));
EXPECT_EQ(ax::mojom::Restriction::kNone,
GetButtonAccessibility()->GetData().GetRestriction());
EXPECT_EQ(ax::mojom::Restriction::kNone,
virtual_label_->GetData().GetRestriction());
button_->SetEnabled(false);
EXPECT_FALSE(
GetButtonAccessibility()->HasState(ax::mojom::State::kFocusable));
EXPECT_TRUE(virtual_label_->HasState(ax::mojom::State::kFocusable));
EXPECT_EQ(ax::mojom::Restriction::kDisabled,
GetButtonAccessibility()->GetData().GetRestriction());
EXPECT_EQ(ax::mojom::Restriction::kDisabled,
virtual_label_->GetData().GetRestriction());
button_->SetEnabled(true);
button_->SetFocusBehavior(View::FocusBehavior::ALWAYS);
virtual_label_->GetCustomData().RemoveState(ax::mojom::State::kFocusable);
EXPECT_TRUE(GetButtonAccessibility()->HasState(ax::mojom::State::kFocusable));
EXPECT_FALSE(virtual_label_->HasState(ax::mojom::State::kFocusable));
EXPECT_EQ(ax::mojom::Restriction::kNone,
GetButtonAccessibility()->GetData().GetRestriction());
EXPECT_EQ(ax::mojom::Restriction::kNone,
virtual_label_->GetData().GetRestriction());
}
TEST_F(AXVirtualViewTest, VirtualLabelIsChildOfButton) {
EXPECT_EQ(1u, GetButtonAccessibility()->GetChildCount());
EXPECT_EQ(0u, virtual_label_->GetChildCount());
ASSERT_NE(nullptr, virtual_label_->GetParent());
EXPECT_EQ(button_->GetNativeViewAccessible(), virtual_label_->GetParent());
ASSERT_NE(nullptr, GetButtonAccessibility()->ChildAtIndex(0));
EXPECT_EQ(virtual_label_->GetNativeObject(),
GetButtonAccessibility()->ChildAtIndex(0));
}
TEST_F(AXVirtualViewTest, RemoveFromParentView) {
ASSERT_EQ(1u, GetButtonAccessibility()->GetChildCount());
std::unique_ptr<AXVirtualView> removed_label =
virtual_label_->RemoveFromParentView();
EXPECT_EQ(nullptr, removed_label->GetParent());
EXPECT_TRUE(GetButtonAccessibility()->virtual_children().empty());
AXVirtualView* virtual_child_1 = new AXVirtualView;
removed_label->AddChildView(base::WrapUnique(virtual_child_1));
ASSERT_EQ(1u, removed_label->GetChildCount());
ASSERT_NE(nullptr, virtual_child_1->GetParent());
std::unique_ptr<AXVirtualView> removed_child_1 =
virtual_child_1->RemoveFromParentView();
EXPECT_EQ(nullptr, removed_child_1->GetParent());
EXPECT_EQ(0u, removed_label->GetChildCount());
}
#if defined(USE_AURA)
TEST_F(AXVirtualViewTest, MultipleCaches) {
// This test ensures that AXVirtualView objects remove themselves from an
// existing cache (if present) when |set_cache| is called.
std::unique_ptr<AXAuraObjCache> cache = std::make_unique<AXAuraObjCache>();
std::unique_ptr<AXAuraObjCache> second_cache =
std::make_unique<AXAuraObjCache>();
// Store |virtual_label_| in |cache|.
SetCache(*virtual_label_, *cache);
AXVirtualViewWrapper* wrapper =
virtual_label_->GetOrCreateWrapper(cache.get());
EXPECT_NE(wrapper, nullptr);
EXPECT_NE(wrapper->GetUniqueId(), ui::kInvalidAXNodeID);
EXPECT_NE(wrapper->GetParent(), nullptr);
EXPECT_NE(cache->GetID(virtual_label_.get()), ui::kInvalidAXNodeID);
// Store |virtual_label_| in |second_cache|.
SetCache(*virtual_label_, *second_cache);
AXVirtualViewWrapper* second_wrapper =
virtual_label_->GetOrCreateWrapper(second_cache.get());
EXPECT_NE(second_wrapper, nullptr);
EXPECT_NE(second_wrapper->GetUniqueId(), ui::kInvalidAXNodeID);
// |virtual_label_| should only exist in |second_cache|.
EXPECT_NE(second_cache->GetID(virtual_label_.get()), ui::kInvalidAXNodeID);
EXPECT_EQ(cache->GetID(virtual_label_.get()), ui::kInvalidAXNodeID);
}
#endif // defined(USE_AURA)
TEST_F(AXVirtualViewTest, AddingAndRemovingVirtualChildren) {
ASSERT_EQ(0u, virtual_label_->GetChildCount());
ExpectReceivedAccessibilityEvents({});
AXVirtualView* virtual_child_1 = new AXVirtualView;
virtual_label_->AddChildView(base::WrapUnique(virtual_child_1));
EXPECT_EQ(1u, virtual_label_->GetChildCount());
ASSERT_NE(nullptr, virtual_child_1->GetParent());
EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_1->GetParent());
ASSERT_NE(nullptr, virtual_label_->ChildAtIndex(0));
EXPECT_EQ(virtual_child_1->GetNativeObject(),
virtual_label_->ChildAtIndex(0));
ExpectReceivedAccessibilityEvents({std::make_pair(
GetButtonAccessibility(), ax::mojom::Event::kChildrenChanged)});
AXVirtualView* virtual_child_2 = new AXVirtualView;
virtual_label_->AddChildView(base::WrapUnique(virtual_child_2));
EXPECT_EQ(2u, virtual_label_->GetChildCount());
ASSERT_NE(nullptr, virtual_child_2->GetParent());
EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_2->GetParent());
ASSERT_NE(nullptr, virtual_label_->ChildAtIndex(1));
EXPECT_EQ(virtual_child_2->GetNativeObject(),
virtual_label_->ChildAtIndex(1));
ExpectReceivedAccessibilityEvents({std::make_pair(
GetButtonAccessibility(), ax::mojom::Event::kChildrenChanged)});
AXVirtualView* virtual_child_3 = new AXVirtualView;
virtual_child_2->AddChildView(base::WrapUnique(virtual_child_3));
EXPECT_EQ(2u, virtual_label_->GetChildCount());
EXPECT_EQ(0u, virtual_child_1->GetChildCount());
EXPECT_EQ(1u, virtual_child_2->GetChildCount());
ASSERT_NE(nullptr, virtual_child_3->GetParent());
EXPECT_EQ(virtual_child_2->GetNativeObject(), virtual_child_3->GetParent());
ASSERT_NE(nullptr, virtual_child_2->ChildAtIndex(0));
EXPECT_EQ(virtual_child_3->GetNativeObject(),
virtual_child_2->ChildAtIndex(0));
ExpectReceivedAccessibilityEvents({std::make_pair(
GetButtonAccessibility(), ax::mojom::Event::kChildrenChanged)});
virtual_child_2->RemoveChildView(virtual_child_3);
EXPECT_EQ(0u, virtual_child_2->GetChildCount());
EXPECT_EQ(2u, virtual_label_->GetChildCount());
ExpectReceivedAccessibilityEvents({std::make_pair(
GetButtonAccessibility(), ax::mojom::Event::kChildrenChanged)});
virtual_label_->RemoveAllChildViews();
EXPECT_EQ(0u, virtual_label_->GetChildCount());
// There should be two "kChildrenChanged" events because Two virtual child
// views are removed in total.
ExpectReceivedAccessibilityEvents(
{std::make_pair(GetButtonAccessibility(),
ax::mojom::Event::kChildrenChanged),
std::make_pair(GetButtonAccessibility(),
ax::mojom::Event::kChildrenChanged)});
}
TEST_F(AXVirtualViewTest, ReorderingVirtualChildren) {
ASSERT_EQ(0u, virtual_label_->GetChildCount());
AXVirtualView* virtual_child_1 = new AXVirtualView;
virtual_label_->AddChildView(base::WrapUnique(virtual_child_1));
ASSERT_EQ(1u, virtual_label_->GetChildCount());
AXVirtualView* virtual_child_2 = new AXVirtualView;
virtual_label_->AddChildView(base::WrapUnique(virtual_child_2));
ASSERT_EQ(2u, virtual_label_->GetChildCount());
virtual_label_->ReorderChildView(virtual_child_1, 100);
ASSERT_EQ(2u, virtual_label_->GetChildCount());
EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_2->GetParent());
ASSERT_NE(nullptr, virtual_label_->ChildAtIndex(0));
EXPECT_EQ(virtual_child_2->GetNativeObject(),
virtual_label_->ChildAtIndex(0));
ASSERT_NE(nullptr, virtual_label_->ChildAtIndex(1));
EXPECT_EQ(virtual_child_1->GetNativeObject(),
virtual_label_->ChildAtIndex(1));
virtual_label_->ReorderChildView(virtual_child_1, 0);
ASSERT_EQ(2u, virtual_label_->GetChildCount());
EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_1->GetParent());
ASSERT_NE(nullptr, virtual_label_->ChildAtIndex(0));
EXPECT_EQ(virtual_child_1->GetNativeObject(),
virtual_label_->ChildAtIndex(0));
ASSERT_NE(nullptr, virtual_label_->ChildAtIndex(1));
EXPECT_EQ(virtual_child_2->GetNativeObject(),
virtual_label_->ChildAtIndex(1));
virtual_label_->RemoveAllChildViews();
ASSERT_EQ(0u, virtual_label_->GetChildCount());
}
TEST_F(AXVirtualViewTest, ContainsVirtualChild) {
ASSERT_EQ(0u, virtual_label_->GetChildCount());
AXVirtualView* virtual_child_1 = new AXVirtualView;
virtual_label_->AddChildView(base::WrapUnique(virtual_child_1));
ASSERT_EQ(1u, virtual_label_->GetChildCount());
AXVirtualView* virtual_child_2 = new AXVirtualView;
virtual_label_->AddChildView(base::WrapUnique(virtual_child_2));
ASSERT_EQ(2u, virtual_label_->GetChildCount());
AXVirtualView* virtual_child_3 = new AXVirtualView;
virtual_child_2->AddChildView(base::WrapUnique(virtual_child_3));
ASSERT_EQ(1u, virtual_child_2->GetChildCount());
EXPECT_TRUE(button_->GetViewAccessibility().Contains(virtual_label_));
EXPECT_TRUE(virtual_label_->Contains(virtual_label_));
EXPECT_TRUE(virtual_label_->Contains(virtual_child_1));
EXPECT_TRUE(virtual_label_->Contains(virtual_child_2));
EXPECT_TRUE(virtual_label_->Contains(virtual_child_3));
EXPECT_TRUE(virtual_child_2->Contains(virtual_child_2));
EXPECT_TRUE(virtual_child_2->Contains(virtual_child_3));
EXPECT_FALSE(virtual_child_1->Contains(virtual_label_));
EXPECT_FALSE(virtual_child_2->Contains(virtual_label_));
EXPECT_FALSE(virtual_child_3->Contains(virtual_child_2));
virtual_label_->RemoveAllChildViews();
ASSERT_EQ(0u, virtual_label_->GetChildCount());
}
TEST_F(AXVirtualViewTest, GetIndexOfVirtualChild) {
ASSERT_EQ(0u, virtual_label_->GetChildCount());
AXVirtualView* virtual_child_1 = new AXVirtualView;
virtual_label_->AddChildView(base::WrapUnique(virtual_child_1));
ASSERT_EQ(1u, virtual_label_->GetChildCount());
AXVirtualView* virtual_child_2 = new AXVirtualView;
virtual_label_->AddChildView(base::WrapUnique(virtual_child_2));
ASSERT_EQ(2u, virtual_label_->GetChildCount());
AXVirtualView* virtual_child_3 = new AXVirtualView;
virtual_child_2->AddChildView(base::WrapUnique(virtual_child_3));
ASSERT_EQ(1u, virtual_child_2->GetChildCount());
EXPECT_FALSE(virtual_label_->GetIndexOf(virtual_label_).has_value());
EXPECT_EQ(0u, virtual_label_->GetIndexOf(virtual_child_1).value());
EXPECT_EQ(1u, virtual_label_->GetIndexOf(virtual_child_2).value());
EXPECT_FALSE(virtual_label_->GetIndexOf(virtual_child_3).has_value());
EXPECT_EQ(0u, virtual_child_2->GetIndexOf(virtual_child_3).value());
virtual_label_->RemoveAllChildViews();
ASSERT_EQ(0u, virtual_label_->GetChildCount());
}
// Verify that virtual views with invisible ancestors inherit the
// ax::mojom::State::kInvisible state.
TEST_F(AXVirtualViewTest, InvisibleVirtualViews) {
EXPECT_TRUE(widget_->IsVisible());
EXPECT_FALSE(
GetButtonAccessibility()->HasState(ax::mojom::State::kInvisible));
EXPECT_FALSE(virtual_label_->HasState(ax::mojom::State::kInvisible));
button_->SetVisible(false);
EXPECT_TRUE(GetButtonAccessibility()->HasState(ax::mojom::State::kInvisible));
EXPECT_TRUE(virtual_label_->HasState(ax::mojom::State::kInvisible));
button_->SetVisible(true);
}
TEST_F(AXVirtualViewTest, OverrideFocus) {
ViewAccessibility& button_accessibility = button_->GetViewAccessibility();
ASSERT_NE(nullptr, button_accessibility.GetNativeObject());
ASSERT_NE(nullptr, virtual_label_->GetNativeObject());
ExpectReceivedAccessibilityEvents({});
button_->SetFocusBehavior(View::FocusBehavior::ALWAYS);
button_->RequestFocus();
ExpectReceivedAccessibilityEvents(
{std::make_pair(GetButtonAccessibility(), ax::mojom::Event::kFocus)});
EXPECT_EQ(button_accessibility.GetNativeObject(),
button_accessibility.GetFocusedDescendant());
button_accessibility.OverrideFocus(virtual_label_);
EXPECT_EQ(virtual_label_->GetNativeObject(),
button_accessibility.GetFocusedDescendant());
ExpectReceivedAccessibilityEvents(
{std::make_pair(virtual_label_, ax::mojom::Event::kFocus)});
button_accessibility.OverrideFocus(nullptr);
EXPECT_EQ(button_accessibility.GetNativeObject(),
button_accessibility.GetFocusedDescendant());
ExpectReceivedAccessibilityEvents(
{std::make_pair(GetButtonAccessibility(), ax::mojom::Event::kFocus)});
ASSERT_EQ(0u, virtual_label_->GetChildCount());
AXVirtualView* virtual_child_1 = new AXVirtualView;
virtual_label_->AddChildView(base::WrapUnique(virtual_child_1));
ASSERT_EQ(1u, virtual_label_->GetChildCount());
ExpectReceivedAccessibilityEvents({std::make_pair(
GetButtonAccessibility(), ax::mojom::Event::kChildrenChanged)});
AXVirtualView* virtual_child_2 = new AXVirtualView;
virtual_label_->AddChildView(base::WrapUnique(virtual_child_2));
ASSERT_EQ(2u, virtual_label_->GetChildCount());
ExpectReceivedAccessibilityEvents({std::make_pair(
GetButtonAccessibility(), ax::mojom::Event::kChildrenChanged)});
button_accessibility.OverrideFocus(virtual_child_1);
EXPECT_EQ(virtual_child_1->GetNativeObject(),
button_accessibility.GetFocusedDescendant());
ExpectReceivedAccessibilityEvents(
{std::make_pair(virtual_child_1, ax::mojom::Event::kFocus)});
AXVirtualView* virtual_child_3 = new AXVirtualView;
virtual_child_2->AddChildView(base::WrapUnique(virtual_child_3));
ASSERT_EQ(1u, virtual_child_2->GetChildCount());
ExpectReceivedAccessibilityEvents({std::make_pair(
GetButtonAccessibility(), ax::mojom::Event::kChildrenChanged)});
EXPECT_EQ(virtual_child_1->GetNativeObject(),
button_accessibility.GetFocusedDescendant());
button_accessibility.OverrideFocus(virtual_child_3);
EXPECT_EQ(virtual_child_3->GetNativeObject(),
button_accessibility.GetFocusedDescendant());
ExpectReceivedAccessibilityEvents(
{std::make_pair(virtual_child_3, ax::mojom::Event::kFocus)});
// Test that calling GetFocus() while the owner view is not focused will
// return nullptr.
button_->SetFocusBehavior(View::FocusBehavior::NEVER);
button_->RequestFocus();
ExpectReceivedAccessibilityEvents({});
EXPECT_EQ(nullptr, virtual_label_->GetFocus());
EXPECT_EQ(nullptr, virtual_child_1->GetFocus());
EXPECT_EQ(nullptr, virtual_child_2->GetFocus());
EXPECT_EQ(nullptr, virtual_child_3->GetFocus());
button_->SetFocusBehavior(View::FocusBehavior::ALWAYS);
button_->RequestFocus();
ExpectReceivedAccessibilityEvents(
{std::make_pair(virtual_child_3, ax::mojom::Event::kFocus)});
// Test that calling GetFocus() from any object in the tree will return the
// same result.
EXPECT_EQ(virtual_child_3->GetNativeObject(), virtual_label_->GetFocus());
EXPECT_EQ(virtual_child_3->GetNativeObject(), virtual_child_1->GetFocus());
EXPECT_EQ(virtual_child_3->GetNativeObject(), virtual_child_2->GetFocus());
EXPECT_EQ(virtual_child_3->GetNativeObject(), virtual_child_3->GetFocus());
virtual_label_->RemoveChildView(virtual_child_2);
ASSERT_EQ(1u, virtual_label_->GetChildCount());
ExpectReceivedAccessibilityEvents(
{std::make_pair(GetButtonAccessibility(), ax::mojom::Event::kFocus),
std::make_pair(GetButtonAccessibility(),
ax::mojom::Event::kChildrenChanged)});
EXPECT_EQ(button_accessibility.GetNativeObject(),
button_accessibility.GetFocusedDescendant());
EXPECT_EQ(button_accessibility.GetNativeObject(), virtual_label_->GetFocus());
EXPECT_EQ(button_accessibility.GetNativeObject(),
virtual_child_1->GetFocus());
button_accessibility.OverrideFocus(virtual_child_1);
EXPECT_EQ(virtual_child_1->GetNativeObject(),
button_accessibility.GetFocusedDescendant());
ExpectReceivedAccessibilityEvents(
{std::make_pair(virtual_child_1, ax::mojom::Event::kFocus)});
virtual_label_->RemoveAllChildViews();
ASSERT_EQ(0u, virtual_label_->GetChildCount());
EXPECT_EQ(button_accessibility.GetNativeObject(),
button_accessibility.GetFocusedDescendant());
ExpectReceivedAccessibilityEvents(
{std::make_pair(GetButtonAccessibility(), ax::mojom::Event::kFocus),
std::make_pair(GetButtonAccessibility(),
ax::mojom::Event::kChildrenChanged)});
}
TEST_F(AXVirtualViewTest, TreeNavigation) {
ASSERT_EQ(0u, virtual_label_->GetChildCount());
AXVirtualView* virtual_child_1 = new AXVirtualView;
virtual_label_->AddChildView(base::WrapUnique(virtual_child_1));
AXVirtualView* virtual_child_2 = new AXVirtualView;
virtual_label_->AddChildView(base::WrapUnique(virtual_child_2));
AXVirtualView* virtual_child_3 = new AXVirtualView;
virtual_label_->AddChildView(base::WrapUnique(virtual_child_3));
AXVirtualView* virtual_child_4 = new AXVirtualView;
virtual_child_2->AddChildView(base::WrapUnique(virtual_child_4));
EXPECT_EQ(button_->GetNativeViewAccessible(), virtual_label_->GetParent());
EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_1->GetParent());
EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_2->GetParent());
EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_3->GetParent());
EXPECT_EQ(virtual_child_2->GetNativeObject(), virtual_child_4->GetParent());
EXPECT_EQ(0u, virtual_label_->GetIndexInParent());
EXPECT_EQ(0u, virtual_child_1->GetIndexInParent());
EXPECT_EQ(1u, virtual_child_2->GetIndexInParent());
EXPECT_EQ(2u, virtual_child_3->GetIndexInParent());
EXPECT_EQ(0u, virtual_child_4->GetIndexInParent());
EXPECT_EQ(3u, virtual_label_->GetChildCount());
EXPECT_EQ(0u, virtual_child_1->GetChildCount());
EXPECT_EQ(1u, virtual_child_2->GetChildCount());
EXPECT_EQ(0u, virtual_child_3->GetChildCount());
EXPECT_EQ(0u, virtual_child_4->GetChildCount());
EXPECT_EQ(virtual_child_1->GetNativeObject(),
virtual_label_->ChildAtIndex(0));
EXPECT_EQ(virtual_child_2->GetNativeObject(),
virtual_label_->ChildAtIndex(1));
EXPECT_EQ(virtual_child_3->GetNativeObject(),
virtual_label_->ChildAtIndex(2));
EXPECT_EQ(virtual_child_4->GetNativeObject(),
virtual_child_2->ChildAtIndex(0));
EXPECT_EQ(virtual_child_1->GetNativeObject(),
virtual_label_->GetFirstChild());
EXPECT_EQ(virtual_child_3->GetNativeObject(), virtual_label_->GetLastChild());
EXPECT_EQ(nullptr, virtual_child_1->GetFirstChild());
EXPECT_EQ(nullptr, virtual_child_1->GetLastChild());
EXPECT_EQ(virtual_child_4->GetNativeObject(),
virtual_child_2->GetFirstChild());
EXPECT_EQ(virtual_child_4->GetNativeObject(),
virtual_child_2->GetLastChild());
EXPECT_EQ(nullptr, virtual_child_4->GetFirstChild());
EXPECT_EQ(nullptr, virtual_child_4->GetLastChild());
EXPECT_EQ(nullptr, virtual_label_->GetNextSibling());
EXPECT_EQ(nullptr, virtual_label_->GetPreviousSibling());
EXPECT_EQ(virtual_child_2->GetNativeObject(),
virtual_child_1->GetNextSibling());
EXPECT_EQ(nullptr, virtual_child_1->GetPreviousSibling());
EXPECT_EQ(virtual_child_3->GetNativeObject(),
virtual_child_2->GetNextSibling());
EXPECT_EQ(virtual_child_1->GetNativeObject(),
virtual_child_2->GetPreviousSibling());
EXPECT_EQ(nullptr, virtual_child_3->GetNextSibling());
EXPECT_EQ(virtual_child_2->GetNativeObject(),
virtual_child_3->GetPreviousSibling());
EXPECT_EQ(nullptr, virtual_child_4->GetNextSibling());
EXPECT_EQ(nullptr, virtual_child_4->GetPreviousSibling());
}
TEST_F(AXVirtualViewTest, TreeNavigationWithIgnoredVirtualViews) {
ASSERT_EQ(0u, virtual_label_->GetChildCount());
AXVirtualView* virtual_child_1 = new AXVirtualView;
virtual_label_->AddChildView(base::WrapUnique(virtual_child_1));
virtual_child_1->GetCustomData().AddState(ax::mojom::State::kIgnored);
EXPECT_EQ(0u, virtual_label_->GetChildCount());
EXPECT_EQ(0u, virtual_child_1->GetChildCount());
AXVirtualView* virtual_child_2 = new AXVirtualView;
virtual_child_1->AddChildView(base::WrapUnique(virtual_child_2));
AXVirtualView* virtual_child_3 = new AXVirtualView;
virtual_child_2->AddChildView(base::WrapUnique(virtual_child_3));
AXVirtualView* virtual_child_4 = new AXVirtualView;
virtual_child_2->AddChildView(base::WrapUnique(virtual_child_4));
// While ignored nodes should not be accessible via any of the tree navigation
// methods, their descendants should be.
EXPECT_EQ(button_->GetNativeViewAccessible(), virtual_label_->GetParent());
EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_1->GetParent());
EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_2->GetParent());
EXPECT_EQ(virtual_child_2->GetNativeObject(), virtual_child_3->GetParent());
EXPECT_EQ(virtual_child_2->GetNativeObject(), virtual_child_4->GetParent());
EXPECT_EQ(0u, virtual_label_->GetIndexInParent());
EXPECT_FALSE(virtual_child_1->GetIndexInParent().has_value());
EXPECT_EQ(0u, virtual_child_2->GetIndexInParent());
EXPECT_EQ(0u, virtual_child_3->GetIndexInParent());
EXPECT_EQ(1u, virtual_child_4->GetIndexInParent());
EXPECT_EQ(1u, virtual_label_->GetChildCount());
EXPECT_EQ(1u, virtual_child_1->GetChildCount());
EXPECT_EQ(2u, virtual_child_2->GetChildCount());
EXPECT_EQ(0u, virtual_child_3->GetChildCount());
EXPECT_EQ(0u, virtual_child_4->GetChildCount());
EXPECT_EQ(virtual_child_2->GetNativeObject(),
virtual_label_->ChildAtIndex(0));
EXPECT_EQ(virtual_child_2->GetNativeObject(),
virtual_child_1->ChildAtIndex(0));
EXPECT_EQ(virtual_child_3->GetNativeObject(),
virtual_child_2->ChildAtIndex(0));
EXPECT_EQ(virtual_child_4->GetNativeObject(),
virtual_child_2->ChildAtIndex(1));
// Try ignoring a node by changing its role, instead of its state.
virtual_child_2->GetCustomData().role = ax::mojom::Role::kNone;
EXPECT_EQ(button_->GetNativeViewAccessible(), virtual_label_->GetParent());
EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_1->GetParent());
EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_2->GetParent());
EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_3->GetParent());
EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_4->GetParent());
EXPECT_EQ(2u, virtual_label_->GetChildCount());
EXPECT_EQ(2u, virtual_child_1->GetChildCount());
EXPECT_EQ(2u, virtual_child_2->GetChildCount());
EXPECT_EQ(0u, virtual_child_3->GetChildCount());
EXPECT_EQ(0u, virtual_child_4->GetChildCount());
EXPECT_EQ(0u, virtual_label_->GetIndexInParent());
EXPECT_FALSE(virtual_child_1->GetIndexInParent().has_value());
EXPECT_FALSE(virtual_child_2->GetIndexInParent().has_value());
EXPECT_EQ(0u, virtual_child_3->GetIndexInParent());
EXPECT_EQ(1u, virtual_child_4->GetIndexInParent());
EXPECT_EQ(virtual_child_3->GetNativeObject(),
virtual_label_->ChildAtIndex(0));
EXPECT_EQ(virtual_child_4->GetNativeObject(),
virtual_label_->ChildAtIndex(1));
EXPECT_EQ(virtual_child_3->GetNativeObject(),
virtual_child_1->ChildAtIndex(0));
EXPECT_EQ(virtual_child_4->GetNativeObject(),
virtual_child_1->ChildAtIndex(1));
EXPECT_EQ(virtual_child_3->GetNativeObject(),
virtual_child_2->ChildAtIndex(0));
EXPECT_EQ(virtual_child_4->GetNativeObject(),
virtual_child_2->ChildAtIndex(1));
// Test for mixed ignored and unignored virtual children.
AXVirtualView* virtual_child_5 = new AXVirtualView;
virtual_child_1->AddChildView(base::WrapUnique(virtual_child_5));
EXPECT_EQ(button_->GetNativeViewAccessible(), virtual_label_->GetParent());
EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_1->GetParent());
EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_2->GetParent());
EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_3->GetParent());
EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_4->GetParent());
EXPECT_EQ(virtual_label_->GetNativeObject(), virtual_child_5->GetParent());
EXPECT_EQ(3u, virtual_label_->GetChildCount());
EXPECT_EQ(3u, virtual_child_1->GetChildCount());
EXPECT_EQ(2u, virtual_child_2->GetChildCount());
EXPECT_EQ(0u, virtual_child_3->GetChildCount());
EXPECT_EQ(0u, virtual_child_4->GetChildCount());
EXPECT_EQ(0u, virtual_child_5->GetChildCount());
EXPECT_EQ(0u, virtual_label_->GetIndexInParent());
EXPECT_FALSE(virtual_child_1->GetIndexInParent().has_value());
EXPECT_FALSE(virtual_child_2->GetIndexInParent().has_value());
EXPECT_EQ(0u, virtual_child_3->GetIndexInParent());
EXPECT_EQ(1u, virtual_child_4->GetIndexInParent());
EXPECT_EQ(2u, virtual_child_5->GetIndexInParent());
EXPECT_EQ(virtual_child_3->GetNativeObject(),
virtual_label_->ChildAtIndex(0));
EXPECT_EQ(virtual_child_4->GetNativeObject(),
virtual_label_->ChildAtIndex(1));
EXPECT_EQ(virtual_child_5->GetNativeObject(),
virtual_label_->ChildAtIndex(2));
// An ignored root node should not be exposed.
virtual_label_->GetCustomData().AddState(ax::mojom::State::kIgnored);
EXPECT_EQ(button_->GetNativeViewAccessible(), virtual_label_->GetParent());
EXPECT_EQ(button_->GetNativeViewAccessible(), virtual_child_1->GetParent());
EXPECT_EQ(button_->GetNativeViewAccessible(), virtual_child_2->GetParent());
EXPECT_EQ(button_->GetNativeViewAccessible(), virtual_child_3->GetParent());
EXPECT_EQ(button_->GetNativeViewAccessible(), virtual_child_4->GetParent());
EXPECT_EQ(button_->GetNativeViewAccessible(), virtual_child_5->GetParent());
EXPECT_EQ(3u, GetButtonAccessibility()->GetChildCount());
EXPECT_EQ(0u, virtual_child_3->GetIndexInParent());
EXPECT_EQ(1u, virtual_child_4->GetIndexInParent());
EXPECT_EQ(2u, virtual_child_5->GetIndexInParent());
EXPECT_EQ(virtual_child_3->GetNativeObject(),
GetButtonAccessibility()->ChildAtIndex(0));
EXPECT_EQ(virtual_child_4->GetNativeObject(),
GetButtonAccessibility()->ChildAtIndex(1));
EXPECT_EQ(virtual_child_5->GetNativeObject(),
GetButtonAccessibility()->ChildAtIndex(2));
// Test for mixed ignored and unignored root nodes.
AXVirtualView* virtual_label_2 = new AXVirtualView;
virtual_label_2->GetCustomData().role = ax::mojom::Role::kStaticText;
virtual_label_2->GetCustomData().SetNameChecked("Label");
button_->GetViewAccessibility().AddVirtualChildView(
base::WrapUnique(virtual_label_2));
EXPECT_EQ(button_->GetNativeViewAccessible(), virtual_label_2->GetParent());
EXPECT_EQ(4u, GetButtonAccessibility()->GetChildCount());
EXPECT_EQ(0u, virtual_label_2->GetChildCount());
EXPECT_EQ(virtual_label_2->GetNativeObject(),
GetButtonAccessibility()->ChildAtIndex(3));
// A focusable node should not be ignored.
virtual_child_1->GetCustomData().AddState(ax::mojom::State::kFocusable);
EXPECT_EQ(2u, GetButtonAccessibility()->GetChildCount());
EXPECT_EQ(1u, virtual_label_->GetChildCount());
EXPECT_EQ(virtual_child_1->GetNativeObject(),
GetButtonAccessibility()->ChildAtIndex(0));
EXPECT_EQ(virtual_label_2->GetNativeObject(),
GetButtonAccessibility()->ChildAtIndex(1));
}
TEST_F(AXVirtualViewTest, HitTesting) {
ASSERT_EQ(0u, virtual_label_->GetChildCount());
const gfx::Vector2d offset_from_origin =
button_->GetBoundsInScreen().OffsetFromOrigin();
// Test that hit testing is recursive.
AXVirtualView* virtual_child_1 = new AXVirtualView;
virtual_child_1->GetCustomData().relative_bounds.bounds =
gfx::RectF(0, 0, 10, 10);
virtual_label_->AddChildView(base::WrapUnique(virtual_child_1));
AXVirtualView* virtual_child_2 = new AXVirtualView;
virtual_child_2->GetCustomData().relative_bounds.bounds =
gfx::RectF(5, 5, 5, 5);
virtual_child_1->AddChildView(base::WrapUnique(virtual_child_2));
gfx::Point point_1 = gfx::Point(2, 2) + offset_from_origin;
EXPECT_EQ(virtual_child_1->GetNativeObject(),
virtual_child_1->HitTestSync(point_1.x(), point_1.y()));
gfx::Point point_2 = gfx::Point(7, 7) + offset_from_origin;
EXPECT_EQ(virtual_child_2->GetNativeObject(),
virtual_label_->HitTestSync(point_2.x(), point_2.y()));
// Test that hit testing follows the z-order.
AXVirtualView* virtual_child_3 = new AXVirtualView;
virtual_child_3->GetCustomData().relative_bounds.bounds =
gfx::RectF(5, 5, 10, 10);
virtual_label_->AddChildView(base::WrapUnique(virtual_child_3));
AXVirtualView* virtual_child_4 = new AXVirtualView;
virtual_child_4->GetCustomData().relative_bounds.bounds =
gfx::RectF(10, 10, 10, 10);
virtual_child_3->AddChildView(base::WrapUnique(virtual_child_4));
EXPECT_EQ(virtual_child_3->GetNativeObject(),
virtual_label_->HitTestSync(point_2.x(), point_2.y()));
gfx::Point point_3 = gfx::Point(12, 12) + offset_from_origin;
EXPECT_EQ(virtual_child_4->GetNativeObject(),
virtual_label_->HitTestSync(point_3.x(), point_3.y()));
// Test that hit testing skips ignored nodes but not their descendants.
virtual_child_3->GetCustomData().AddState(ax::mojom::State::kIgnored);
EXPECT_EQ(virtual_child_2->GetNativeObject(),
virtual_label_->HitTestSync(point_2.x(), point_2.y()));
EXPECT_EQ(virtual_child_4->GetNativeObject(),
virtual_label_->HitTestSync(point_3.x(), point_3.y()));
}
// Test for GetTargetForNativeAccessibilityEvent().
#if BUILDFLAG(IS_WIN)
TEST_F(AXVirtualViewTest, GetTargetForEvents) {
EXPECT_EQ(button_, virtual_label_->GetOwnerView());
EXPECT_NE(nullptr, HWNDForView(virtual_label_->GetOwnerView()));
EXPECT_EQ(HWNDForView(button_),
virtual_label_->GetTargetForNativeAccessibilityEvent());
}
#endif // BUILDFLAG(IS_WIN)
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/ax_virtual_view_unittest.cc | C++ | unknown | 34,643 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/accessibility/ax_virtual_view_wrapper.h"
#include <string>
#include "ui/views/accessibility/ax_view_obj_wrapper.h"
#include "ui/views/accessibility/ax_virtual_view.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/view.h"
namespace views {
AXVirtualViewWrapper::AXVirtualViewWrapper(AXAuraObjCache* cache,
AXVirtualView* virtual_view)
: AXAuraObjWrapper(cache), virtual_view_(virtual_view) {
virtual_view->set_cache(cache);
}
AXVirtualViewWrapper::~AXVirtualViewWrapper() = default;
AXAuraObjWrapper* AXVirtualViewWrapper::GetParent() {
if (virtual_view_->virtual_parent_view()) {
return const_cast<AXVirtualView*>(virtual_view_->virtual_parent_view())
->GetOrCreateWrapper(aura_obj_cache_);
}
if (virtual_view_->GetOwnerView())
return aura_obj_cache_->GetOrCreate(virtual_view_->GetOwnerView());
return nullptr;
}
void AXVirtualViewWrapper::GetChildren(
std::vector<AXAuraObjWrapper*>* out_children) {
for (const auto& child : virtual_view_->children())
out_children->push_back(child->GetOrCreateWrapper(aura_obj_cache_));
}
void AXVirtualViewWrapper::Serialize(ui::AXNodeData* out_node_data) {
*out_node_data = virtual_view_->GetData();
View* owner_view = virtual_view_->GetOwnerView();
if (owner_view && owner_view->GetWidget()) {
gfx::Point offset;
View::ConvertPointToScreen(owner_view, &offset);
out_node_data->relative_bounds.bounds.Offset(offset.x(), offset.y());
}
}
ui::AXNodeID AXVirtualViewWrapper::GetUniqueId() const {
return virtual_view_->GetUniqueId().Get();
}
bool AXVirtualViewWrapper::HandleAccessibleAction(
const ui::AXActionData& action) {
return virtual_view_->HandleAccessibleAction(action);
}
std::string AXVirtualViewWrapper::ToString() const {
std::string description = "Virtual view child of ";
return description + virtual_view_->GetOwnerView()->GetClassName();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/ax_virtual_view_wrapper.cc | C++ | unknown | 2,134 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_ACCESSIBILITY_AX_VIRTUAL_VIEW_WRAPPER_H_
#define UI_VIEWS_ACCESSIBILITY_AX_VIRTUAL_VIEW_WRAPPER_H_
#include <string>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "ui/views/accessibility/ax_aura_obj_cache.h"
#include "ui/views/accessibility/ax_aura_obj_wrapper.h"
#include "ui/views/views_export.h"
namespace views {
class AXAuraObjWrapper;
class AXVirtualView;
// Wraps (and adapts) an AXVirtualView for use with AXTreeSourceViews.
class AXVirtualViewWrapper : public AXAuraObjWrapper {
public:
AXVirtualViewWrapper(AXAuraObjCache* cache, AXVirtualView* virtual_view);
AXVirtualViewWrapper(const AXVirtualViewWrapper&) = delete;
AXVirtualViewWrapper& operator=(const AXVirtualViewWrapper&) = delete;
~AXVirtualViewWrapper() override;
// AXAuraObjWrapper:
AXAuraObjWrapper* GetParent() override;
void GetChildren(std::vector<AXAuraObjWrapper*>* out_children) override;
void Serialize(ui::AXNodeData* out_node_data) override;
ui::AXNodeID GetUniqueId() const override;
bool HandleAccessibleAction(const ui::AXActionData& action) override;
std::string ToString() const override;
private:
// Weak.
raw_ptr<AXVirtualView> virtual_view_;
};
} // namespace views
#endif // UI_VIEWS_ACCESSIBILITY_AX_VIRTUAL_VIEW_WRAPPER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/ax_virtual_view_wrapper.h | C++ | unknown | 1,431 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/accessibility/ax_widget_obj_wrapper.h"
#include <vector>
#include "base/strings/utf_string_conversions.h"
#include "ui/accessibility/ax_enums.mojom.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_delegate.h"
namespace views {
AXWidgetObjWrapper::AXWidgetObjWrapper(AXAuraObjCache* aura_obj_cache,
Widget* widget)
: AXAuraObjWrapper(aura_obj_cache), widget_(widget) {
DCHECK(widget->GetNativeView());
widget_observation_.Observe(widget);
}
AXWidgetObjWrapper::~AXWidgetObjWrapper() = default;
AXAuraObjWrapper* AXWidgetObjWrapper::GetParent() {
return aura_obj_cache_->GetOrCreate(widget_->GetNativeView());
}
void AXWidgetObjWrapper::GetChildren(
std::vector<AXAuraObjWrapper*>* out_children) {
if (!widget_->IsVisible() || !widget_->GetRootView() ||
!widget_->GetRootView()->GetVisible()) {
return;
}
out_children->push_back(aura_obj_cache_->GetOrCreate(widget_->GetRootView()));
}
void AXWidgetObjWrapper::Serialize(ui::AXNodeData* out_node_data) {
out_node_data->id = GetUniqueId();
out_node_data->role = widget_->widget_delegate()->GetAccessibleWindowRole();
out_node_data->AddStringAttribute(
ax::mojom::StringAttribute::kName,
base::UTF16ToUTF8(
widget_->widget_delegate()->GetAccessibleWindowTitle()));
out_node_data->AddStringAttribute(ax::mojom::StringAttribute::kClassName,
"Widget");
out_node_data->relative_bounds.bounds =
gfx::RectF(widget_->GetWindowBoundsInScreen());
out_node_data->state = 0;
}
ui::AXNodeID AXWidgetObjWrapper::GetUniqueId() const {
return unique_id_.Get();
}
std::string AXWidgetObjWrapper::ToString() const {
return "Widget";
}
void AXWidgetObjWrapper::OnWidgetDestroying(Widget* widget) {
aura_obj_cache_->Remove(widget);
}
void AXWidgetObjWrapper::OnWidgetDestroyed(Widget* widget) {
// Normally this does not run because of OnWidgetDestroying should have
// removed |this| from cache. However, some code could trigger a destroying
// widget to be created after OnWidgetDestroying. This guards against such
// situation and ensures the destroyed widget is removed from cache.
// See https://crbug.com/1091545
aura_obj_cache_->Remove(widget);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/ax_widget_obj_wrapper.cc | C++ | unknown | 2,584 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_ACCESSIBILITY_AX_WIDGET_OBJ_WRAPPER_H_
#define UI_VIEWS_ACCESSIBILITY_AX_WIDGET_OBJ_WRAPPER_H_
#include <stdint.h>
#include <string>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "base/scoped_observation.h"
#include "ui/accessibility/platform/ax_unique_id.h"
#include "ui/views/accessibility/ax_aura_obj_wrapper.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_observer.h"
namespace views {
class AXAuraObjCache;
// Describes a |Widget| for use with other AX classes.
class AXWidgetObjWrapper : public AXAuraObjWrapper, public WidgetObserver {
public:
// |aura_obj_cache| must outlive this object.
AXWidgetObjWrapper(AXAuraObjCache* aura_obj_cache, Widget* widget);
AXWidgetObjWrapper(const AXWidgetObjWrapper&) = delete;
AXWidgetObjWrapper& operator=(const AXWidgetObjWrapper&) = delete;
~AXWidgetObjWrapper() override;
// AXAuraObjWrapper overrides.
AXAuraObjWrapper* GetParent() override;
void GetChildren(std::vector<AXAuraObjWrapper*>* out_children) override;
void Serialize(ui::AXNodeData* out_node_data) override;
ui::AXNodeID GetUniqueId() const final;
std::string ToString() const override;
// WidgetObserver overrides.
void OnWidgetDestroying(Widget* widget) override;
void OnWidgetDestroyed(Widget* widget) override;
private:
raw_ptr<Widget> widget_;
const ui::AXUniqueId unique_id_;
base::ScopedObservation<Widget, WidgetObserver> widget_observation_{this};
};
} // namespace views
#endif // UI_VIEWS_ACCESSIBILITY_AX_WIDGET_OBJ_WRAPPER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/ax_widget_obj_wrapper.h | C++ | unknown | 1,700 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/accessibility/ax_window_obj_wrapper.h"
#include <stddef.h>
#include <string>
#include <vector>
#include "base/strings/utf_string_conversions.h"
#include "build/chromeos_buildflags.h"
#include "ui/accessibility/aura/aura_window_properties.h"
#include "ui/accessibility/ax_action_data.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/accessibility/ax_tree_id.h"
#include "ui/aura/client/focus_client.h"
#include "ui/aura/window_tree_host.h"
#include "ui/aura/window_tree_host_platform.h"
#include "ui/base/ime/text_input_client.h"
#include "ui/compositor/layer.h"
#include "ui/views/accessibility/ax_aura_obj_cache.h"
#include "ui/views/widget/widget.h"
#if BUILDFLAG(IS_CHROMEOS_LACROS)
#include "ui/views/widget/desktop_aura/desktop_window_tree_host_platform.h"
#endif
namespace views {
namespace {
Widget* GetWidgetForWindow(aura::Window* window) {
Widget* widget = Widget::GetWidgetForNativeView(window);
if (!widget)
return nullptr;
// Under mus/mash both the WindowTreeHost's root aura::Window and the content
// aura::Window will return the same Widget for GetWidgetForNativeView(). Only
// return the Widget for the content window, not the root, since otherwise
// we'll end up with two children in the AX node tree that have the same
// parent.
if (widget->GetNativeWindow() != window) {
DCHECK(window->IsRootWindow());
return nullptr;
}
return widget;
}
// Fires |event| on the |window|, and the Widget and RootView associated with
// |window|.
void FireEventOnWindowChildWidgetAndRootView(aura::Window* window,
ax::mojom::Event event,
AXAuraObjCache* cache) {
cache->FireEvent(cache->GetOrCreate(window), event);
Widget* widget = GetWidgetForWindow(window);
if (widget) {
cache->FireEvent(cache->GetOrCreate(widget), event);
views::View* root_view = widget->GetRootView();
if (root_view)
root_view->NotifyAccessibilityEvent(event, true);
}
}
// Fires location change events on a window, taking into account its
// associated widget, that widget's root view, and descendant windows.
void FireLocationChangesRecursively(aura::Window* window,
AXAuraObjCache* cache) {
FireEventOnWindowChildWidgetAndRootView(
window, ax::mojom::Event::kLocationChanged, cache);
for (auto* child : window->children())
FireLocationChangesRecursively(child, cache);
}
std::string GetWindowName(aura::Window* window) {
std::string class_name = window->GetName();
if (class_name.empty())
class_name = "aura::Window";
return class_name;
}
#if BUILDFLAG(IS_CHROMEOS_LACROS)
std::string GetPlatformWindowId(aura::Window* window) {
// Ignore non-top level windows.
if (!window->IsRootWindow() || window->parent())
return std::string();
// On desktop aura there is one WindowTreeHost per top-level window.
aura::WindowTreeHost* window_tree_host = window->GetHost();
if (!window_tree_host)
return std::string();
// Prefer the DesktopWindowTreeHostPlatform if it exists.
DesktopWindowTreeHostPlatform* desktop_window_tree_host_platform =
DesktopWindowTreeHostPlatform::GetHostForWidget(
window_tree_host->GetAcceleratedWidget());
if (!desktop_window_tree_host_platform)
return window_tree_host->GetUniqueId();
while (desktop_window_tree_host_platform->window_parent()) {
desktop_window_tree_host_platform =
desktop_window_tree_host_platform->window_parent();
}
return desktop_window_tree_host_platform->GetUniqueId();
}
#endif // BUILDFLAG(IS_CHROMEOS_LACROS)
} // namespace
AXWindowObjWrapper::AXWindowObjWrapper(AXAuraObjCache* aura_obj_cache,
aura::Window* window)
: AXAuraObjWrapper(aura_obj_cache),
window_(window),
is_root_window_(window->IsRootWindow()) {
observation_.Observe(window);
if (is_root_window_)
aura_obj_cache_->OnRootWindowObjCreated(window);
// This is a top level root window.
if (window->IsRootWindow() && !window->parent()) {
// On desktop aura there is one WindowTreeHost per top-level window.
aura::WindowTreeHost* window_tree_host = window->GetHost();
if (window_tree_host)
ime_observation_.Observe(window_tree_host->GetInputMethod());
}
}
AXWindowObjWrapper::~AXWindowObjWrapper() = default;
bool AXWindowObjWrapper::HandleAccessibleAction(
const ui::AXActionData& action) {
if (action.action == ax::mojom::Action::kFocus) {
window_->Focus();
return true;
}
return false;
}
AXAuraObjWrapper* AXWindowObjWrapper::GetParent() {
#if BUILDFLAG(IS_CHROMEOS_LACROS)
const std::string& window_id = GetPlatformWindowId(window_);
// In Lacros, the presence of a platform window id means it is parented to the
// Ash tree via the app id.
if (!window_id.empty())
return nullptr;
#endif // BUILDFLAG(IS_CHROMEOS_LACROS)
aura::Window* parent = window_->parent();
if (!parent)
return nullptr;
if (parent->GetProperty(ui::kChildAXTreeID) &&
ui::AXTreeID::FromString(*(parent->GetProperty(ui::kChildAXTreeID))) !=
ui::AXTreeIDUnknown()) {
return nullptr;
}
return aura_obj_cache_->GetOrCreate(parent);
}
void AXWindowObjWrapper::GetChildren(
std::vector<AXAuraObjWrapper*>* out_children) {
// Ignore this window's descendants if it has a child tree.
if (window_->GetProperty(ui::kChildAXTreeID) &&
ui::AXTreeID::FromString(*(window_->GetProperty(ui::kChildAXTreeID))) !=
ui::AXTreeIDUnknown()) {
return;
}
// Ignore this window's children if it is forced to be invisible.
if (window_->GetProperty(ui::kAXConsiderInvisibleAndIgnoreChildren))
return;
for (auto* child : window_->children())
out_children->push_back(aura_obj_cache_->GetOrCreate(child));
// Also consider any associated widgets as children.
Widget* widget = GetWidgetForWindow(window_);
if (widget && widget->IsVisible())
out_children->push_back(aura_obj_cache_->GetOrCreate(widget));
}
void AXWindowObjWrapper::Serialize(ui::AXNodeData* out_node_data) {
#if BUILDFLAG(IS_CHROMEOS_LACROS)
// This app id connects this node with a node in the Ash tree (an
// components/exo shell surface).
const std::string& window_id = GetPlatformWindowId(window_);
if (!window_id.empty())
out_node_data->AddStringAttribute(ax::mojom::StringAttribute::kAppId,
window_id);
#endif // BUILDFLAG(IS_CHROMEOS_LACROS)
if (window_->IsRootWindow() && !window_->parent() && window_->GetHost()) {
ui::TextInputClient* client =
window_->GetHost()->GetInputMethod()->GetTextInputClient();
// Only set caret bounds if input caret is in an editable node.
if (client && client->GetTextInputType() != ui::TEXT_INPUT_TYPE_NONE) {
gfx::Rect caret_bounds_in_screen = client->GetCaretBounds();
out_node_data->AddIntListAttribute(
ax::mojom::IntListAttribute::kCaretBounds,
{caret_bounds_in_screen.x(), caret_bounds_in_screen.y(),
caret_bounds_in_screen.width(), caret_bounds_in_screen.height()});
}
}
out_node_data->id = GetUniqueId();
ax::mojom::Role role = window_->GetProperty(ui::kAXRoleOverride);
if (role != ax::mojom::Role::kNone)
out_node_data->role = role;
else
out_node_data->role = ax::mojom::Role::kWindow;
out_node_data->AddStringAttribute(ax::mojom::StringAttribute::kName,
base::UTF16ToUTF8(window_->GetTitle()));
if (!window_->IsVisible() ||
window_->GetProperty(ui::kAXConsiderInvisibleAndIgnoreChildren)) {
out_node_data->AddState(ax::mojom::State::kInvisible);
}
out_node_data->relative_bounds.bounds =
gfx::RectF(window_->GetBoundsInScreen());
out_node_data->AddStringAttribute(ax::mojom::StringAttribute::kClassName,
GetWindowName(window_));
std::string* child_ax_tree_id_ptr = window_->GetProperty(ui::kChildAXTreeID);
if (child_ax_tree_id_ptr) {
ui::AXTreeID child_ax_tree_id =
ui::AXTreeID::FromString(*child_ax_tree_id_ptr);
if (child_ax_tree_id != ui::AXTreeIDUnknown()) {
// Most often, child AX trees are parented to Views. We need to handle
// the case where they're not here, but we don't want the same AX tree
// to be a child of two different parents.
//
// To avoid this double-parenting, only add the child tree ID of this
// window if the top-level window doesn't have an associated Widget.
//
// Also, if this window is not visible, its child tree should also be
// non-visible so prune it.
if (!window_->GetToplevelWindow() ||
GetWidgetForWindow(window_->GetToplevelWindow()) ||
!window_->IsVisible() ||
window_->GetProperty(ui::kAXConsiderInvisibleAndIgnoreChildren)) {
return;
}
out_node_data->AddChildTreeId(child_ax_tree_id);
const float scale_factor =
window_->GetToplevelWindow()->layer()->device_scale_factor();
out_node_data->AddFloatAttribute(
ax::mojom::FloatAttribute::kChildTreeScale, scale_factor);
}
}
}
ui::AXNodeID AXWindowObjWrapper::GetUniqueId() const {
return unique_id_.Get();
}
std::string AXWindowObjWrapper::ToString() const {
return GetWindowName(window_);
}
void AXWindowObjWrapper::OnCaretBoundsChanged(
const ui::TextInputClient* client) {
FireEvent(ax::mojom::Event::kTreeChanged);
}
void AXWindowObjWrapper::OnWindowDestroyed(aura::Window* window) {
if (is_root_window_)
aura_obj_cache_->OnRootWindowObjDestroyed(window_);
aura_obj_cache_->Remove(window, nullptr);
}
void AXWindowObjWrapper::OnWindowDestroying(aura::Window* window) {
DCHECK_EQ(window, window_);
window_destroying_ = true;
}
void AXWindowObjWrapper::OnWindowHierarchyChanged(
const HierarchyChangeParams& params) {
if (params.phase == WindowObserver::HierarchyChangeParams::HIERARCHY_CHANGED)
aura_obj_cache_->Remove(params.target, params.old_parent);
}
void AXWindowObjWrapper::OnWindowBoundsChanged(
aura::Window* window,
const gfx::Rect& old_bounds,
const gfx::Rect& new_bounds,
ui::PropertyChangeReason reason) {
if (window_destroying_)
return;
if (window == window_)
FireLocationChangesRecursively(window_, aura_obj_cache_);
}
void AXWindowObjWrapper::OnWindowPropertyChanged(aura::Window* window,
const void* key,
intptr_t old) {
if (window_destroying_ || window != window_)
return;
if (key == ui::kChildAXTreeID ||
key == ui::kAXConsiderInvisibleAndIgnoreChildren) {
FireEvent(ax::mojom::Event::kChildrenChanged);
}
}
void AXWindowObjWrapper::OnWindowVisibilityChanged(aura::Window* window,
bool visible) {
if (window_destroying_)
return;
FireEvent(ax::mojom::Event::kStateChanged);
}
void AXWindowObjWrapper::OnWindowTransformed(aura::Window* window,
ui::PropertyChangeReason reason) {
if (window_destroying_)
return;
if (window == window_)
FireLocationChangesRecursively(window_, aura_obj_cache_);
}
void AXWindowObjWrapper::OnWindowTitleChanged(aura::Window* window) {
if (window_destroying_)
return;
FireEventOnWindowChildWidgetAndRootView(
window_, ax::mojom::Event::kTreeChanged, aura_obj_cache_);
}
void AXWindowObjWrapper::FireEvent(ax::mojom::Event event_type) {
aura_obj_cache_->FireEvent(aura_obj_cache_->GetOrCreate(window_), event_type);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/ax_window_obj_wrapper.cc | C++ | unknown | 11,902 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_ACCESSIBILITY_AX_WINDOW_OBJ_WRAPPER_H_
#define UI_VIEWS_ACCESSIBILITY_AX_WINDOW_OBJ_WRAPPER_H_
#include <stdint.h>
#include <string>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "base/scoped_observation.h"
#include "ui/accessibility/ax_enums.mojom-forward.h"
#include "ui/accessibility/platform/ax_unique_id.h"
#include "ui/aura/window.h"
#include "ui/aura/window_observer.h"
#include "ui/base/ime/input_method.h"
#include "ui/base/ime/input_method_observer.h"
#include "ui/views/accessibility/ax_aura_obj_wrapper.h"
namespace ui {
class InputMethod;
}
namespace views {
class AXAuraObjCache;
// Describes a |Window| for use with other AX classes.
class AXWindowObjWrapper : public AXAuraObjWrapper,
public ui::InputMethodObserver,
public aura::WindowObserver {
public:
// |aura_obj_cache| and |window| must outlive this object.
AXWindowObjWrapper(AXAuraObjCache* aura_obj_cache, aura::Window* window);
AXWindowObjWrapper(const AXWindowObjWrapper&) = delete;
AXWindowObjWrapper& operator=(const AXWindowObjWrapper&) = delete;
~AXWindowObjWrapper() override;
// AXAuraObjWrapper overrides.
bool HandleAccessibleAction(const ui::AXActionData& action) override;
AXAuraObjWrapper* GetParent() override;
void GetChildren(std::vector<AXAuraObjWrapper*>* out_children) override;
void Serialize(ui::AXNodeData* out_node_data) override;
ui::AXNodeID GetUniqueId() const final;
std::string ToString() const override;
// InputMethodObserver overrides.
void OnFocus() override {}
void OnBlur() override {}
void OnInputMethodDestroyed(const ui::InputMethod* input_method) override {}
void OnTextInputStateChanged(const ui::TextInputClient* client) override {}
void OnCaretBoundsChanged(const ui::TextInputClient* client) override;
// WindowObserver overrides.
void OnWindowDestroyed(aura::Window* window) override;
void OnWindowDestroying(aura::Window* window) override;
void OnWindowHierarchyChanged(const HierarchyChangeParams& params) override;
void OnWindowBoundsChanged(aura::Window* window,
const gfx::Rect& old_bounds,
const gfx::Rect& new_bounds,
ui::PropertyChangeReason reason) override;
void OnWindowPropertyChanged(aura::Window* window,
const void* key,
intptr_t old) override;
void OnWindowVisibilityChanged(aura::Window* window, bool visible) override;
void OnWindowTransformed(aura::Window* window,
ui::PropertyChangeReason reason) override;
void OnWindowTitleChanged(aura::Window* window) override;
private:
// Fires an accessibility event.
void FireEvent(ax::mojom::Event event_type);
gfx::Rect GetCaretBounds(const ui::TextInputClient* client);
const raw_ptr<aura::Window> window_;
const bool is_root_window_;
const ui::AXUniqueId unique_id_;
// Whether OnWindowDestroying has happened for |window_|. Used to suppress
// further events from |window| after OnWindowDestroying. Otherwise, dangling
// pointer could be left in |aura_obj_cache_|. See https://crbug.com/1091545
bool window_destroying_ = false;
base::ScopedObservation<aura::Window, aura::WindowObserver> observation_{
this};
base::ScopedObservation<ui::InputMethod, ui::InputMethodObserver>
ime_observation_{this};
};
} // namespace views
#endif // UI_VIEWS_ACCESSIBILITY_AX_WINDOW_OBJ_WRAPPER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/ax_window_obj_wrapper.h | C++ | unknown | 3,683 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/accessibility/test_list_grid_view.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_node_data.h"
namespace views {
namespace test {
TestListGridView::TestListGridView() = default;
TestListGridView::~TestListGridView() = default;
void TestListGridView::GetAccessibleNodeData(ui::AXNodeData* node_data) {
node_data->role = ax::mojom::Role::kListGrid;
if (aria_row_count) {
node_data->AddIntAttribute(ax::mojom::IntAttribute::kAriaRowCount,
*aria_row_count);
}
if (aria_column_count) {
node_data->AddIntAttribute(ax::mojom::IntAttribute::kAriaColumnCount,
*aria_column_count);
}
if (table_row_count) {
node_data->AddIntAttribute(ax::mojom::IntAttribute::kTableRowCount,
*table_row_count);
}
if (table_column_count) {
node_data->AddIntAttribute(ax::mojom::IntAttribute::kTableColumnCount,
*table_column_count);
}
}
void TestListGridView::SetAriaTableSize(int row_count, int column_count) {
aria_row_count = absl::make_optional(row_count);
aria_column_count = absl::make_optional(column_count);
}
void TestListGridView::SetTableSize(int row_count, int column_count) {
table_row_count = absl::make_optional(row_count);
table_column_count = absl::make_optional(column_count);
}
void TestListGridView::UnsetAriaTableSize() {
aria_row_count = absl::nullopt;
aria_column_count = absl::nullopt;
}
void TestListGridView::UnsetTableSize() {
table_row_count = absl::nullopt;
table_column_count = absl::nullopt;
}
} // namespace test
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/test_list_grid_view.cc | C++ | unknown | 1,816 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_ACCESSIBILITY_TEST_LIST_GRID_VIEW_H_
#define UI_VIEWS_ACCESSIBILITY_TEST_LIST_GRID_VIEW_H_
#include "ui/views/view.h"
namespace ui {
struct AXNodeData;
} // namespace ui
namespace views {
namespace test {
// Class used for testing row and column count accessibility APIs.
class TestListGridView : public View {
public:
TestListGridView();
~TestListGridView() override;
void GetAccessibleNodeData(ui::AXNodeData* node_data) override;
void SetAriaTableSize(int row_count, int column_count);
void SetTableSize(int row_count, int column_count);
void UnsetAriaTableSize();
void UnsetTableSize();
private:
absl::optional<int> aria_row_count = absl::nullopt;
absl::optional<int> aria_column_count = absl::nullopt;
absl::optional<int> table_row_count = absl::nullopt;
absl::optional<int> table_column_count = absl::nullopt;
};
} // namespace test
} // namespace views
#endif // UI_VIEWS_ACCESSIBILITY_TEST_LIST_GRID_VIEW_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/test_list_grid_view.h | C++ | unknown | 1,114 |
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/accessibility/view_accessibility.h"
#include <utility>
#include "base/functional/callback.h"
#include "base/memory/ptr_util.h"
#include "base/ranges/algorithm.h"
#include "base/strings/utf_string_conversions.h"
#include "build/chromeos_buildflags.h"
#include "ui/accessibility/accessibility_features.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/platform/ax_platform_node.h"
#include "ui/accessibility/platform/ax_platform_node_delegate.h"
#include "ui/base/buildflags.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/views/accessibility/views_ax_tree_manager.h"
#include "ui/views/accessibility/widget_ax_tree_id_map.h"
#include "ui/views/view.h"
#include "ui/views/widget/root_view.h"
#include "ui/views/widget/widget.h"
namespace views {
namespace {
bool IsValidRoleForViews(ax::mojom::Role role) {
switch (role) {
// These roles all have special meaning and shouldn't ever be
// set on a View.
case ax::mojom::Role::kDesktop:
case ax::mojom::Role::kDocument: // Used for ARIA role="document".
case ax::mojom::Role::kIframe:
case ax::mojom::Role::kIframePresentational:
case ax::mojom::Role::kPdfRoot:
case ax::mojom::Role::kPortal:
case ax::mojom::Role::kRootWebArea:
case ax::mojom::Role::kSvgRoot:
case ax::mojom::Role::kUnknown:
return false;
default:
return true;
}
}
} // namespace
#if !BUILDFLAG_INTERNAL_HAS_NATIVE_ACCESSIBILITY()
// static
std::unique_ptr<ViewAccessibility> ViewAccessibility::Create(View* view) {
// Cannot use std::make_unique because constructor is protected.
return base::WrapUnique(new ViewAccessibility(view));
}
#endif
ViewAccessibility::ViewAccessibility(View* view)
: view_(view), focused_virtual_child_(nullptr) {
#if defined(USE_AURA) && !BUILDFLAG(IS_CHROMEOS_ASH)
if (features::IsAccessibilityTreeForViewsEnabled()) {
Widget* widget = view_->GetWidget();
if (widget && widget->is_top_level() &&
!WidgetAXTreeIDMap::GetInstance().HasWidget(widget)) {
View* root_view = static_cast<View*>(widget->GetRootView());
if (root_view && root_view == view) {
ax_tree_manager_ = std::make_unique<views::ViewsAXTreeManager>(widget);
}
}
}
#endif
}
ViewAccessibility::~ViewAccessibility() = default;
void ViewAccessibility::AddVirtualChildView(
std::unique_ptr<AXVirtualView> virtual_view) {
AddVirtualChildViewAt(std::move(virtual_view), virtual_children_.size());
}
void ViewAccessibility::AddVirtualChildViewAt(
std::unique_ptr<AXVirtualView> virtual_view,
size_t index) {
DCHECK(virtual_view);
DCHECK_LE(index, virtual_children_.size());
if (virtual_view->parent_view() == this)
return;
DCHECK(!virtual_view->parent_view()) << "This |view| already has a View "
"parent. Call RemoveVirtualChildView "
"first.";
DCHECK(!virtual_view->virtual_parent_view()) << "This |view| already has an "
"AXVirtualView parent. Call "
"RemoveChildView first.";
virtual_view->set_parent_view(this);
auto insert_iterator =
virtual_children_.begin() + static_cast<ptrdiff_t>(index);
virtual_children_.insert(insert_iterator, std::move(virtual_view));
}
std::unique_ptr<AXVirtualView> ViewAccessibility::RemoveVirtualChildView(
AXVirtualView* virtual_view) {
DCHECK(virtual_view);
auto cur_index = GetIndexOf(virtual_view);
if (!cur_index.has_value())
return {};
std::unique_ptr<AXVirtualView> child =
std::move(virtual_children_[cur_index.value()]);
virtual_children_.erase(virtual_children_.begin() +
static_cast<ptrdiff_t>(cur_index.value()));
child->set_parent_view(nullptr);
child->UnsetPopulateDataCallback();
if (focused_virtual_child_ && child->Contains(focused_virtual_child_))
OverrideFocus(nullptr);
return child;
}
void ViewAccessibility::RemoveAllVirtualChildViews() {
while (!virtual_children_.empty())
RemoveVirtualChildView(virtual_children_.back().get());
}
bool ViewAccessibility::Contains(const AXVirtualView* virtual_view) const {
DCHECK(virtual_view);
for (const auto& virtual_child : virtual_children_) {
// AXVirtualView::Contains() also checks if the provided virtual view is the
// same as |this|.
if (virtual_child->Contains(virtual_view))
return true;
}
return false;
}
absl::optional<size_t> ViewAccessibility::GetIndexOf(
const AXVirtualView* virtual_view) const {
DCHECK(virtual_view);
const auto iter = base::ranges::find(virtual_children_, virtual_view,
&std::unique_ptr<AXVirtualView>::get);
return iter != virtual_children_.end()
? absl::make_optional(
static_cast<size_t>(iter - virtual_children_.begin()))
: absl::nullopt;
}
void ViewAccessibility::GetAccessibleNodeData(ui::AXNodeData* data) const {
data->id = GetUniqueId().Get();
data->AddStringAttribute(ax::mojom::StringAttribute::kClassName,
view_->GetClassName());
// Views may misbehave if their widget is closed; return an unknown role
// rather than possibly crashing.
const views::Widget* widget = view_->GetWidget();
if (!widget || !widget->widget_delegate() || widget->IsClosed()) {
data->role = ax::mojom::Role::kUnknown;
data->SetRestriction(ax::mojom::Restriction::kDisabled);
// TODO(accessibility): Returning early means that any custom data which
// had been set via the Override functions is not included. Preserving
// and exposing these properties might be worth doing, even in the case
// of object destruction.
// Ordinarily, a view cannot be focusable if its widget has already closed.
// So, it would have been appropriate to set the focusable state to false in
// this particular case. However, the `FocusManager` may sometimes try to
// retrieve the focusable state of this view via
// `View::IsAccessibilityFocusable()`, even after this view's widget has
// been closed. Returning the wrong result might cause a crash, because the
// focus manager might be expecting the result to be the same regardless of
// the state of the view's widget.
if (ViewAccessibility::IsAccessibilityFocusable()) {
data->AddState(ax::mojom::State::kFocusable);
// Set this node as intentionally nameless to avoid DCHECKs for a missing
// name of a focusable.
data->SetNameExplicitlyEmpty();
}
return;
}
view_->GetAccessibleNodeData(data);
if (custom_data_.role != ax::mojom::Role::kUnknown)
data->role = custom_data_.role;
if (data->role == ax::mojom::Role::kAlertDialog) {
// When an alert dialog is used, indicate this with xml-roles. This helps
// JAWS understand that it's a dialog and not just an ordinary alert, even
// though xml-roles is normally used to expose ARIA roles in web content.
// Specifically, this enables the JAWS Insert+T read window title command.
// Note: if an alert has focusable descendants such as buttons, it should
// use kAlertDialog, not kAlert.
data->AddStringAttribute(ax::mojom::StringAttribute::kRole, "alertdialog");
}
std::string name;
if (custom_data_.GetStringAttribute(ax::mojom::StringAttribute::kName,
&name)) {
if (!name.empty())
data->SetNameChecked(name);
else
data->SetNameExplicitlyEmpty();
}
std::string description;
if (custom_data_.GetStringAttribute(ax::mojom::StringAttribute::kDescription,
&description)) {
if (!description.empty())
data->SetDescription(description);
else
data->SetDescriptionExplicitlyEmpty();
}
if (custom_data_.GetHasPopup() != ax::mojom::HasPopup::kFalse)
data->SetHasPopup(custom_data_.GetHasPopup());
static constexpr ax::mojom::IntAttribute kOverridableIntAttributes[]{
ax::mojom::IntAttribute::kDescriptionFrom,
ax::mojom::IntAttribute::kNameFrom,
ax::mojom::IntAttribute::kPosInSet,
ax::mojom::IntAttribute::kSetSize,
};
for (auto attribute : kOverridableIntAttributes) {
if (custom_data_.HasIntAttribute(attribute))
data->AddIntAttribute(attribute, custom_data_.GetIntAttribute(attribute));
}
static constexpr ax::mojom::IntListAttribute kOverridableIntListAttributes[]{
ax::mojom::IntListAttribute::kLabelledbyIds,
ax::mojom::IntListAttribute::kDescribedbyIds,
};
for (auto attribute : kOverridableIntListAttributes) {
if (custom_data_.HasIntListAttribute(attribute))
data->AddIntListAttribute(attribute,
custom_data_.GetIntListAttribute(attribute));
}
if (!data->HasStringAttribute(ax::mojom::StringAttribute::kDescription)) {
std::u16string tooltip = view_->GetTooltipText(gfx::Point());
// Some screen readers announce the accessible description right after the
// accessible name. Only use the tooltip as the accessible description if
// it's different from the name, otherwise users might be puzzled as to why
// their screen reader is announcing the same thing twice.
if (!tooltip.empty() && tooltip != data->GetString16Attribute(
ax::mojom::StringAttribute::kName)) {
data->SetDescription(base::UTF16ToUTF8(tooltip));
}
}
data->relative_bounds.bounds = gfx::RectF(view_->GetBoundsInScreen());
if (!custom_data_.relative_bounds.bounds.IsEmpty())
data->relative_bounds.bounds = custom_data_.relative_bounds.bounds;
// We need to add the ignored state to all ignored Views, similar to how Blink
// exposes ignored DOM nodes. Calling AXNodeData::IsIgnored() would also check
// if the role is in the list of roles that are inherently ignored.
// Furthermore, we add the ignored state if this View is a descendant of a
// leaf View. We call this class's "IsChildOfLeaf" method instead of the one
// in our platform specific subclass because subclasses determine if a node is
// a leaf by (among other things) counting the number of unignored children,
// which would create a circular definition of the ignored state.
if (is_ignored_ || data->IsIgnored() || ViewAccessibility::IsChildOfLeaf())
data->AddState(ax::mojom::State::kIgnored);
if (ViewAccessibility::IsAccessibilityFocusable())
data->AddState(ax::mojom::State::kFocusable);
if (is_enabled_) {
if (*is_enabled_) {
// Take into account the possibility that the View is marked as readonly
// but enabled. In other words, we can't just remove all restrictions,
// unless the View is explicitly marked as disabled. Note that readonly is
// another restriction state in addition to enabled and disabled, (see
// ax::mojom::Restriction).
if (data->GetRestriction() == ax::mojom::Restriction::kDisabled)
data->SetRestriction(ax::mojom::Restriction::kNone);
} else {
data->SetRestriction(ax::mojom::Restriction::kDisabled);
}
} else if (!view_->GetEnabled()) {
data->SetRestriction(ax::mojom::Restriction::kDisabled);
}
if (!view_->GetVisible() && data->role != ax::mojom::Role::kAlert)
data->AddState(ax::mojom::State::kInvisible);
if (view_->context_menu_controller())
data->AddAction(ax::mojom::Action::kShowContextMenu);
DCHECK(!data->HasStringAttribute(ax::mojom::StringAttribute::kChildTreeId))
<< "Please annotate child tree ids using "
"ViewAccessibility::OverrideChildTreeID.";
if (child_tree_id_) {
data->AddChildTreeId(child_tree_id_.value());
if (widget && widget->GetNativeView() && display::Screen::GetScreen()) {
const float scale_factor =
display::Screen::GetScreen()
->GetDisplayNearestView(view_->GetWidget()->GetNativeView())
.device_scale_factor();
data->AddFloatAttribute(ax::mojom::FloatAttribute::kChildTreeScale,
scale_factor);
}
}
}
void ViewAccessibility::OverrideFocus(AXVirtualView* virtual_view) {
DCHECK(!virtual_view || Contains(virtual_view))
<< "|virtual_view| must be nullptr or a descendant of this view.";
focused_virtual_child_ = virtual_view;
if (view_->HasFocus()) {
if (focused_virtual_child_) {
focused_virtual_child_->NotifyAccessibilityEvent(
ax::mojom::Event::kFocus);
} else {
view_->NotifyAccessibilityEvent(ax::mojom::Event::kFocus, true);
}
}
}
bool ViewAccessibility::IsAccessibilityFocusable() const {
// Descendants of leaf nodes should not be reported as focusable, because all
// such descendants are not exposed to the accessibility APIs of any platform.
// (See `AXNode::IsLeaf()` for more information.) We avoid calling
// `IsChildOfLeaf()` for performance reasons, because `FocusManager` makes use
// of this method, which means that it would be called frequently. However,
// since all descendants of leaf nodes are ignored by default, and since our
// testing framework enforces the condition that all ignored nodes should not
// be focusable, if there is test coverage, such a situation will cause a test
// failure.
return view_->GetFocusBehavior() != View::FocusBehavior::NEVER &&
ViewAccessibility::IsAccessibilityEnabled() && view_->IsDrawn() &&
!is_ignored_;
}
bool ViewAccessibility::IsFocusedForTesting() const {
return view_->HasFocus() && !focused_virtual_child_;
}
void ViewAccessibility::SetPopupFocusOverride() {
NOTIMPLEMENTED();
}
void ViewAccessibility::EndPopupFocusOverride() {
NOTIMPLEMENTED();
}
void ViewAccessibility::FireFocusAfterMenuClose() {
view_->NotifyAccessibilityEvent(ax::mojom::Event::kFocusAfterMenuClose, true);
}
void ViewAccessibility::OverrideRole(const ax::mojom::Role role) {
DCHECK(IsValidRoleForViews(role)) << "Invalid role for Views.";
custom_data_.role = role;
}
void ViewAccessibility::OverrideName(const std::string& name,
const ax::mojom::NameFrom name_from) {
DCHECK_EQ(name.empty(),
name_from == ax::mojom::NameFrom::kAttributeExplicitlyEmpty)
<< "If the name is being removed to improve the user experience, "
"|name_from| should be set to |kAttributeExplicitlyEmpty|.";
// |AXNodeData::SetName| expects a valid role. Some Views call |OverrideRole|
// prior to overriding the name. For those that don't, see if we can get the
// default role from the View.
if (custom_data_.role == ax::mojom::Role::kUnknown) {
ui::AXNodeData data;
view_->GetAccessibleNodeData(&data);
custom_data_.role = data.role;
}
custom_data_.SetNameFrom(name_from);
custom_data_.SetNameChecked(name);
}
void ViewAccessibility::OverrideName(const std::u16string& name,
const ax::mojom::NameFrom name_from) {
OverrideName(base::UTF16ToUTF8(name), name_from);
}
void ViewAccessibility::OverrideLabelledBy(
const View* labelled_by_view,
const ax::mojom::NameFrom name_from) {
DCHECK_NE(labelled_by_view, view_);
// |OverrideName| might have been used before |OverrideLabelledBy|.
// We don't want to keep an old/incorrect name. In addition, some ATs might
// expect the name to be provided by us from the label. So try to get the
// name from the labelling View and use the result.
//
// |ViewAccessibility::GetAccessibleNodeData| gets properties from: 1) The
// View's implementation of |View::GetAccessibleNodeData| and 2) the
// custom_data_ set via ViewAccessibility's various Override functions.
// HOWEVER, it returns early prior to checking either of those sources if the
// Widget does not exist or is closed. Thus given a View whose Widget is about
// to be created, we cannot use |ViewAccessibility::GetAccessibleNodeData| to
// obtain the name. If |OverrideLabelledBy| is being called, presumably the
// labelling View is not in the process of being destroyed. So manually check
// the two sources.
ui::AXNodeData label_data;
const_cast<View*>(labelled_by_view)->GetAccessibleNodeData(&label_data);
const std::string& label =
label_data.GetStringAttribute(ax::mojom::StringAttribute::kName).empty()
? labelled_by_view->GetViewAccessibility()
.custom_data_.GetStringAttribute(
ax::mojom::StringAttribute::kName)
: label_data.GetStringAttribute(ax::mojom::StringAttribute::kName);
// |OverrideName| includes logic to populate custom_data_.role with the
// View's default role in cases where |OverrideRole| was not called (yet).
// This ensures |AXNodeData::SetName| is not called with |Role::kUnknown|.
OverrideName(label, name_from);
int32_t labelled_by_id =
labelled_by_view->GetViewAccessibility().GetUniqueId().Get();
custom_data_.AddIntListAttribute(ax::mojom::IntListAttribute::kLabelledbyIds,
{labelled_by_id});
}
void ViewAccessibility::OverrideDescription(
const std::string& description,
const ax::mojom::DescriptionFrom description_from) {
DCHECK_EQ(
description.empty(),
description_from == ax::mojom::DescriptionFrom::kAttributeExplicitlyEmpty)
<< "If the description is being removed to improve the user experience, "
"|description_from| should be set to |kAttributeExplicitlyEmpty|.";
custom_data_.SetDescriptionFrom(description_from);
custom_data_.SetDescription(description);
}
void ViewAccessibility::OverrideDescription(
const std::u16string& description,
const ax::mojom::DescriptionFrom description_from) {
OverrideDescription(base::UTF16ToUTF8(description), description_from);
}
void ViewAccessibility::OverrideNativeWindowTitle(const std::string& title) {
NOTIMPLEMENTED() << "Only implemented on Mac for now.";
}
void ViewAccessibility::OverrideNativeWindowTitle(const std::u16string& title) {
OverrideNativeWindowTitle(base::UTF16ToUTF8(title));
}
void ViewAccessibility::OverrideIsLeaf(bool value) {
is_leaf_ = value;
}
bool ViewAccessibility::IsLeaf() const {
return is_leaf_;
}
bool ViewAccessibility::IsChildOfLeaf() const {
// Note to future developers: This method is called from
// "GetAccessibleNodeData". We should avoid calling any methods in any of our
// subclasses that might try and retrieve our AXNodeData, because this will
// cause an infinite loop.
// TODO(crbug.com/1100047): Make this method non-virtual and delete it from
// all subclasses.
if (const View* parent_view = view_->parent()) {
const ViewAccessibility& view_accessibility =
parent_view->GetViewAccessibility();
if (view_accessibility.ViewAccessibility::IsLeaf())
return true;
return view_accessibility.ViewAccessibility::IsChildOfLeaf();
}
return false;
}
void ViewAccessibility::OverrideIsIgnored(bool value) {
is_ignored_ = value;
}
bool ViewAccessibility::IsIgnored() const {
// TODO(nektar): Make this method non-virtual and implement as follows:
// ui::AXNodeData out_data;
// GetAccessibleNodeData(&out_data);
// return out_data.IsIgnored();
return is_ignored_;
}
void ViewAccessibility::OverrideIsEnabled(bool enabled) {
// Cannot store this value in `custom_data_` because
// `AXNodeData::AddIntAttribute` will DCHECK if you add an IntAttribute that
// is equal to kNone. Adding an IntAttribute that is equal to kNone is
// ambiguous, since it is unclear what would be the difference between doing
// this and not adding the attribute at all.
is_enabled_ = enabled;
}
bool ViewAccessibility::IsAccessibilityEnabled() const {
if (is_enabled_)
return *is_enabled_;
return view_->GetEnabled();
}
void ViewAccessibility::OverrideBounds(const gfx::RectF& bounds) {
custom_data_.relative_bounds.bounds = bounds;
}
void ViewAccessibility::OverrideHasPopup(const ax::mojom::HasPopup has_popup) {
custom_data_.SetHasPopup(has_popup);
}
void ViewAccessibility::OverridePosInSet(int pos_in_set, int set_size) {
custom_data_.AddIntAttribute(ax::mojom::IntAttribute::kPosInSet, pos_in_set);
custom_data_.AddIntAttribute(ax::mojom::IntAttribute::kSetSize, set_size);
}
void ViewAccessibility::ClearPosInSetOverride() {
custom_data_.RemoveIntAttribute(ax::mojom::IntAttribute::kPosInSet);
custom_data_.RemoveIntAttribute(ax::mojom::IntAttribute::kSetSize);
}
void ViewAccessibility::OverrideNextFocus(Widget* widget) {
if (widget)
next_focus_ = widget->GetWeakPtr();
else
next_focus_ = nullptr;
}
void ViewAccessibility::OverridePreviousFocus(Widget* widget) {
if (widget)
previous_focus_ = widget->GetWeakPtr();
else
previous_focus_ = nullptr;
}
Widget* ViewAccessibility::GetNextWindowFocus() const {
return next_focus_.get();
}
Widget* ViewAccessibility::GetPreviousWindowFocus() const {
return previous_focus_.get();
}
void ViewAccessibility::OverrideChildTreeID(ui::AXTreeID tree_id) {
if (tree_id == ui::AXTreeIDUnknown())
child_tree_id_ = absl::nullopt;
else
child_tree_id_ = tree_id;
}
ui::AXTreeID ViewAccessibility::GetChildTreeID() const {
return child_tree_id_ ? *child_tree_id_ : ui::AXTreeIDUnknown();
}
gfx::NativeViewAccessible ViewAccessibility::GetNativeObject() const {
return nullptr;
}
void ViewAccessibility::NotifyAccessibilityEvent(ax::mojom::Event event_type) {
// Used for unit testing.
if (accessibility_events_callback_)
accessibility_events_callback_.Run(nullptr, event_type);
}
void ViewAccessibility::AnnounceText(const std::u16string& text) {
Widget* const widget = view_->GetWidget();
if (!widget)
return;
auto* const root_view =
static_cast<internal::RootView*>(widget->GetRootView());
if (!root_view)
return;
root_view->AnnounceText(text);
}
const ui::AXUniqueId& ViewAccessibility::GetUniqueId() const {
return unique_id_;
}
ViewsAXTreeManager* ViewAccessibility::AXTreeManager() const {
ViewsAXTreeManager* manager = nullptr;
#if defined(USE_AURA) && !BUILDFLAG(IS_CHROMEOS_ASH)
Widget* widget = view_->GetWidget();
// Don't return managers for closing Widgets.
if (!widget || !widget->widget_delegate() || widget->IsClosed())
return nullptr;
manager = ax_tree_manager_.get();
// ViewsAXTreeManagers are only created for top-level windows (Widgets). For
// non top-level Views, look up the Widget's tree ID to retrieve the manager.
if (!manager) {
ui::AXTreeID tree_id =
WidgetAXTreeIDMap::GetInstance().GetWidgetTreeID(widget);
DCHECK_NE(tree_id, ui::AXTreeIDUnknown());
manager = static_cast<views::ViewsAXTreeManager*>(
ui::AXTreeManager::FromID(tree_id));
}
#endif
return manager;
}
gfx::NativeViewAccessible ViewAccessibility::GetFocusedDescendant() {
if (focused_virtual_child_)
return focused_virtual_child_->GetNativeObject();
return view_->GetNativeViewAccessible();
}
const ViewAccessibility::AccessibilityEventsCallback&
ViewAccessibility::accessibility_events_callback() const {
return accessibility_events_callback_;
}
void ViewAccessibility::set_accessibility_events_callback(
ViewAccessibility::AccessibilityEventsCallback callback) {
accessibility_events_callback_ = std::move(callback);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/view_accessibility.cc | C++ | unknown | 23,547 |
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_ACCESSIBILITY_VIEW_ACCESSIBILITY_H_
#define UI_VIEWS_ACCESSIBILITY_VIEW_ACCESSIBILITY_H_
#include <memory>
#include <string>
#include <vector>
#include "base/functional/callback_forward.h"
#include "base/memory/raw_ptr.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/accessibility/ax_enums.mojom-forward.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/accessibility/platform/ax_unique_id.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/accessibility/ax_virtual_view.h"
#include "ui/views/views_export.h"
namespace ui {
class AXPlatformNodeDelegate;
} // namespace ui
namespace views {
class View;
class ViewsAXTreeManager;
class Widget;
// An object that manages the accessibility interface for a View.
//
// The default accessibility properties of a View is determined by calling
// |View::GetAccessibleNodeData()|, which is overridden by many |View|
// subclasses. |ViewAccessibility| lets you override these for a particular
// view.
//
// In most cases, subclasses of |ViewAccessibility| own the |AXPlatformNode|
// that implements the native accessibility APIs on a specific platform.
class VIEWS_EXPORT ViewAccessibility {
public:
using AccessibilityEventsCallback =
base::RepeatingCallback<void(const ui::AXPlatformNodeDelegate*,
const ax::mojom::Event)>;
using AXVirtualViews = AXVirtualView::AXVirtualViews;
static std::unique_ptr<ViewAccessibility> Create(View* view);
ViewAccessibility(const ViewAccessibility&) = delete;
ViewAccessibility& operator=(const ViewAccessibility&) = delete;
virtual ~ViewAccessibility();
// Modifies |node_data| to reflect the current accessible state of the
// associated View, taking any custom overrides into account
// (see OverrideFocus, OverrideRole, etc. below).
virtual void GetAccessibleNodeData(ui::AXNodeData* node_data) const;
//
// The following methods get or set accessibility attributes (in the owning
// View's AXNodeData), overrideing any identical attributes which might have
// been set by the owning View in its View::GetAccessibleNodeData() method.
//
// Note that accessibility string attributes are only used if non-empty, so
// you can't override a string with the empty string.
//
// Sets one of our virtual descendants as having the accessibility focus. This
// means that if this view has the system focus, it will set the accessibility
// focus to the provided descendant virtual view instead. Set this to nullptr
// if none of our virtual descendants should have the accessibility focus. It
// is illegal to set this to any virtual view that is currently not one of our
// descendants and this is enforced by a DCHECK.
void OverrideFocus(AXVirtualView* virtual_view);
// Returns whether this view is focusable when the user uses an accessibility
// aid or the keyboard, even though it may not be normally focusable. Note
// that if using the keyboard, on macOS the preference "Full Keyboard Access"
// needs to be turned on.
virtual bool IsAccessibilityFocusable() const;
// Used for testing. Returns true if this view is considered focused.
virtual bool IsFocusedForTesting() const;
// Call when this is the active descendant of a popup view that temporarily
// takes over focus. It is only necessary to use this for menus like autofill,
// where the actual focus is in content.
// When the popup closes, call EndPopupFocusOverride().
virtual void SetPopupFocusOverride();
// Call when popup closes, if it used SetPopupFocusOverride().
virtual void EndPopupFocusOverride();
// Call when a menu closes, to restore focus to where it was previously.
virtual void FireFocusAfterMenuClose();
void OverrideRole(const ax::mojom::Role role);
// Sets the accessible name to the specified string value.
// By default the source type of the name is attribute. This source is
// appropriate for most use cases where a View is providing a non-empty flat
// string as the accessible name. If a View has a need to remove the
// accessible name, the string should be empty and the source of the name
// should instead be kAttributeExplicitlyEmpty. Note that the name source
// types were created based on needs associated with web content
// accessibility, and assistive technologies may make decisions based on that
// supposition. For instance, kTitle implies that the source of the name will
// be presented as a tooltip, such as would result from the HTML 'title'
// attribute or the SVG <title> element.
void OverrideName(
const std::string& name,
const ax::mojom::NameFrom name_from = ax::mojom::NameFrom::kAttribute);
void OverrideName(
const std::u16string& name,
const ax::mojom::NameFrom name_from = ax::mojom::NameFrom::kAttribute);
// Sets the accessible label source by establishing a relationship between
// this View and another view, such as a Label. By default the source type of
// the name is "related element." This default should cover most, if not all,
// of the use cases for Views. Note that the name source types were created
// based on needs associated with web content accessibility, and assistive
// technologies may make decisions based on that supposition. For instance,
// kTitle implies that the source of the name will be presented as a tooltip,
// such as would result from the HTML 'title' attribute or the SVG <title>
// element.
void OverrideLabelledBy(const View* labelled_by_view,
const ax::mojom::NameFrom name_from =
ax::mojom::NameFrom::kRelatedElement);
// Sets the accessible description to the specified string value.
// By default the source type of the description is aria-description. While
// Views technically don't support ARIA, aria-description is the closest
// existing DescriptionFrom source for Views providing a flat string
// description. And assistive technologies already know how to recognize this
// source type. Therefore, Views are encouraged to go with this default unless
// they have a specific reason not to. If a View has a need to remove the
// accessible description, the string should be empty and the source of the
// description should instead be kAttributeExplicitlyEmpty. If a View never
// had an accessible description, there is no need to override it with an
// empty string.
void OverrideDescription(const std::string& description,
const ax::mojom::DescriptionFrom description_from =
ax::mojom::DescriptionFrom::kAriaDescription);
void OverrideDescription(const std::u16string& description,
const ax::mojom::DescriptionFrom description_from =
ax::mojom::DescriptionFrom::kAriaDescription);
// Sets the platform-specific accessible name/title property of the
// NativeViewAccessible window. This is needed on platforms where the name
// of the NativeViewAccessible window is automatically calculated by the
// platform's accessibility API. For instance on the Mac, the label of the
// NativeWidgetMacNSWindow of a JavaScript alert is taken from the name of
// the child RootView. Note: the first function does the string conversion
// and calls the second, thus only the latter needs to be implemented by
// interested platforms.
void OverrideNativeWindowTitle(const std::u16string& title);
virtual void OverrideNativeWindowTitle(const std::string& title);
// Sets whether this View hides all its descendants from the accessibility
// tree that is exposed to platform APIs. This is similar, but not exactly
// identical to aria-hidden="true".
//
// Note that this attribute does not cross widget boundaries, i.e. if a sub
// widget is a descendant of this View, it will not be marked hidden. This
// should not happen in practice as widgets are not children of Views.
void OverrideIsLeaf(bool value);
virtual bool IsLeaf() const;
// Returns true if an ancestor of this node (not including itself) is a
// leaf node, meaning that this node is not actually exposed to any
// platform's accessibility layer.
virtual bool IsChildOfLeaf() const;
// Hides this View from the accessibility tree that is exposed to platform
// APIs.
void OverrideIsIgnored(bool value);
virtual bool IsIgnored() const;
// Marks this View either as enabled or disabled (grayed out) in the
// accessibility tree and ignores the View's real enabled state. Does not
// affect the View's focusable state (see "IsAccessibilityFocusable()").
// Screen readers make a special announcement when an item is disabled.
//
// It might not be advisable to mark a View as enabled in the accessibility
// tree, whilst the real View is actually disabled, because such a View will
// not respond to user actions.
void OverrideIsEnabled(bool enabled);
virtual bool IsAccessibilityEnabled() const;
void OverrideBounds(const gfx::RectF& bounds);
void OverrideHasPopup(const ax::mojom::HasPopup has_popup);
// Override information provided to users by screen readers when describing
// elements in a menu, listbox, or another set-like item. For example, "New
// tab, menu item 1 of 5". If not specified, a view's index in its parent and
// its parent's number of children provide the values for |pos_in_set| and
// |set_size| respectively.
//
// Note that |pos_in_set| is one-based, i.e. it starts from 1 not 0.
void OverridePosInSet(int pos_in_set, int set_size);
void ClearPosInSetOverride();
// Override the next or previous focused widget. Some assistive technologies,
// such as screen readers, may utilize this information to transition focus
// from the beginning or end of one widget to another when navigating by its
// default navigation method.
void OverrideNextFocus(Widget* widget);
void OverridePreviousFocus(Widget* widget);
Widget* GetNextWindowFocus() const;
Widget* GetPreviousWindowFocus() const;
// Override the child tree id.
void OverrideChildTreeID(ui::AXTreeID tree_id);
ui::AXTreeID GetChildTreeID() const;
// Returns the accessibility object that represents the View whose
// accessibility is managed by this instance. This may be an AXPlatformNode or
// it may be a native accessible object implemented by another class.
virtual gfx::NativeViewAccessible GetNativeObject() const;
// Causes the screen reader to announce |text|. If the current user is not
// using a screen reader, has no effect.
virtual void AnnounceText(const std::u16string& text);
virtual const ui::AXUniqueId& GetUniqueId() const;
View* view() const { return view_; }
AXVirtualView* FocusedVirtualChild() const { return focused_virtual_child_; }
ViewsAXTreeManager* AXTreeManager() const;
//
// Methods for managing virtual views.
//
// Adds |virtual_view| as a child of this View. We take ownership of our
// virtual children.
void AddVirtualChildView(std::unique_ptr<AXVirtualView> virtual_view);
// Adds |virtual_view| as a child of this View at an index.
// We take ownership of our virtual children.
void AddVirtualChildViewAt(std::unique_ptr<AXVirtualView> virtual_view,
size_t index);
// Removes |virtual_view| from this View. The virtual view's parent will
// change to nullptr. Hands ownership back to the caller.
std::unique_ptr<AXVirtualView> RemoveVirtualChildView(
AXVirtualView* virtual_view);
// Removes all the virtual children from this View.
// The virtual views are deleted.
void RemoveAllVirtualChildViews();
const AXVirtualViews& virtual_children() const { return virtual_children_; }
// Returns true if |virtual_view| is contained within the hierarchy of this
// View, even as an indirect descendant.
bool Contains(const AXVirtualView* virtual_view) const;
// Returns the index of |virtual_view|, or nullopt if |virtual_view| is not a
// child of this View.
absl::optional<size_t> GetIndexOf(const AXVirtualView* virtual_view) const;
// Returns the native accessibility object associated with the AXVirtualView
// descendant that is currently focused. If no virtual descendants are
// present, or no virtual descendant has been marked as focused, returns the
// native accessibility object associated with this view.
gfx::NativeViewAccessible GetFocusedDescendant();
// If true, moves accessibility focus to an ancestor.
void set_propagate_focus_to_ancestor(bool value) {
propagate_focus_to_ancestor_ = value;
}
bool propagate_focus_to_ancestor() { return propagate_focus_to_ancestor_; }
// Used for testing. Allows a test to watch accessibility events.
const AccessibilityEventsCallback& accessibility_events_callback() const;
void set_accessibility_events_callback(AccessibilityEventsCallback callback);
protected:
explicit ViewAccessibility(View* view);
// Used internally and by View.
virtual void NotifyAccessibilityEvent(ax::mojom::Event event_type);
// Used for testing. Called every time an accessibility event is fired.
AccessibilityEventsCallback accessibility_events_callback_;
private:
friend class View;
// Weak. Owns this.
const raw_ptr<View> view_;
// If there are any virtual children, they override any real children.
// We own our virtual children.
AXVirtualViews virtual_children_;
// The virtual child that is currently focused.
// This is nullptr if no virtual child is focused.
// See also OverrideFocus() and GetFocusedDescendant().
raw_ptr<AXVirtualView> focused_virtual_child_;
const ui::AXUniqueId unique_id_;
// Contains data set explicitly via OverrideRole, OverrideName, etc. that
// overrides anything provided by GetAccessibleNodeData().
ui::AXNodeData custom_data_;
// If set to true, anything that is a descendant of this view will be hidden
// from accessibility.
bool is_leaf_ = false;
// When true the view is ignored when generating the AX node hierarchy, but
// its children are included. For example, if you created a custom table with
// the digits 1 - 9 arranged in a 3 x 3 grid, marking the table and rows
// "ignored" would mean that the digits 1 - 9 would appear as if they were
// immediate children of the root. Likewise "internal" container views can be
// ignored, like a Widget's RootView, ClientView, etc.
// Similar to setting the role of an ARIA widget to "none" or
// "presentational".
bool is_ignored_ = false;
// Used to override the View's enabled state in case we need to mark the View
// as enabled or disabled only in the accessibility tree.
absl::optional<bool> is_enabled_ = absl::nullopt;
// Used by the Views system to help some assistive technologies, such as
// screen readers, transition focus from one widget to another.
base::WeakPtr<Widget> next_focus_ = nullptr;
base::WeakPtr<Widget> previous_focus_ = nullptr;
// This view's child tree id.
absl::optional<ui::AXTreeID> child_tree_id_;
// Whether to move accessibility focus to an ancestor.
bool propagate_focus_to_ancestor_ = false;
#if defined(USE_AURA) && !BUILDFLAG(IS_CHROMEOS_ASH)
// Each instance of ViewAccessibility that's associated with a root View
// owns an ViewsAXTreeManager. For other Views, this should be nullptr.
std::unique_ptr<views::ViewsAXTreeManager> ax_tree_manager_;
#endif
};
} // namespace views
#endif // UI_VIEWS_ACCESSIBILITY_VIEW_ACCESSIBILITY_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/view_accessibility.h | C++ | unknown | 15,789 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/accessibility/view_accessibility_utils.h"
#include <set>
#include "base/ranges/algorithm.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
namespace views {
// static
Widget* ViewAccessibilityUtils::GetFocusedChildWidgetForAccessibility(
const View* view) {
const FocusManager* focus_manager = view->GetFocusManager();
if (!focus_manager)
return nullptr;
const View* focused_view = view->GetFocusManager()->GetFocusedView();
if (!focused_view)
return nullptr;
std::set<Widget*> child_widgets;
Widget::GetAllOwnedWidgets(view->GetWidget()->GetNativeView(),
&child_widgets);
const auto i =
base::ranges::find_if(child_widgets, [focused_view](auto* child_widget) {
return IsFocusedChildWidget(child_widget, focused_view);
});
return (i == child_widgets.cend()) ? nullptr : *i;
}
// static
bool ViewAccessibilityUtils::IsFocusedChildWidget(Widget* widget,
const View* focused_view) {
return widget->IsVisible() &&
widget->GetContentsView()->Contains(focused_view);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/view_accessibility_utils.cc | C++ | unknown | 1,354 |
// Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_ACCESSIBILITY_VIEW_ACCESSIBILITY_UTILS_H_
#define UI_VIEWS_ACCESSIBILITY_VIEW_ACCESSIBILITY_UTILS_H_
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
namespace views {
class VIEWS_EXPORT ViewAccessibilityUtils {
public:
// Returns a focused child widget if the view has a child that should be
// treated as a special case. For example, if a tab modal dialog is visible
// and focused, this will return the dialog when called on the BrowserView.
// This helper function is used to treat such widgets as separate windows for
// accessibility. Returns nullptr if no such widget is present.
static Widget* GetFocusedChildWidgetForAccessibility(const View* view);
// Used by GetFocusedChildWidgetForAccessibility to determine if a Widget
// should be handled separately.
static bool IsFocusedChildWidget(Widget* widget, const View* focused_view);
};
} // namespace views
#endif // UI_VIEWS_ACCESSIBILITY_VIEW_ACCESSIBILITY_UTILS_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/view_accessibility_utils.h | C++ | unknown | 1,129 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/accessibility/view_ax_platform_node_delegate.h"
#include <map>
#include <memory>
#include <set>
#include <utility>
#include <vector>
#include "base/containers/adapters.h"
#include "base/functional/bind.h"
#include "base/lazy_instance.h"
#include "base/ranges/algorithm.h"
#include "base/task/single_thread_task_runner.h"
#include "build/build_config.h"
#include "ui/accessibility/ax_action_data.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_role_properties.h"
#include "ui/accessibility/ax_tree.h"
#include "ui/accessibility/ax_tree_data.h"
#include "ui/accessibility/ax_tree_id.h"
#include "ui/accessibility/ax_tree_update.h"
#include "ui/accessibility/platform/ax_platform_node.h"
#include "ui/accessibility/platform/ax_platform_node_base.h"
#include "ui/accessibility/platform/ax_unique_id.h"
#include "ui/accessibility/single_ax_tree_manager.h"
#include "ui/base/layout.h"
#include "ui/events/event_utils.h"
#include "ui/views/accessibility/view_accessibility_utils.h"
#include "ui/views/controls/native/native_view_host.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
namespace views {
namespace {
// Information required to fire a delayed accessibility event.
struct QueuedEvent {
QueuedEvent(ax::mojom::Event type, int32_t node_id)
: type(type), node_id(node_id) {}
ax::mojom::Event type;
int32_t node_id;
};
base::LazyInstance<std::vector<QueuedEvent>>::Leaky g_event_queue =
LAZY_INSTANCE_INITIALIZER;
bool g_is_queueing_events = false;
bool IsAccessibilityFocusableWhenEnabled(View* view) {
return view->GetFocusBehavior() != View::FocusBehavior::NEVER &&
view->IsDrawn();
}
// Used to determine if a View should be ignored by accessibility clients by
// being a non-keyboard-focusable child of a keyboard-focusable ancestor. E.g.,
// LabelButtons contain Labels, but a11y should just show that there's a button.
bool IsViewUnfocusableDescendantOfFocusableAncestor(View* view) {
if (IsAccessibilityFocusableWhenEnabled(view))
return false;
while (view->parent()) {
view = view->parent();
if (IsAccessibilityFocusableWhenEnabled(view))
return true;
}
return false;
}
ui::AXPlatformNode* FromNativeWindow(gfx::NativeWindow native_window) {
Widget* widget = Widget::GetWidgetForNativeWindow(native_window);
if (!widget)
return nullptr;
View* view = widget->GetRootView();
if (!view)
return nullptr;
gfx::NativeViewAccessible native_view_accessible =
view->GetNativeViewAccessible();
if (!native_view_accessible)
return nullptr;
return ui::AXPlatformNode::FromNativeViewAccessible(native_view_accessible);
}
ui::AXPlatformNode* PlatformNodeFromNodeID(int32_t id) {
// Note: For Views, node IDs and unique IDs are the same - but that isn't
// necessarily true for all AXPlatformNodes.
return ui::AXPlatformNodeBase::GetFromUniqueId(id);
}
void FireEvent(QueuedEvent event) {
ui::AXPlatformNode* node = PlatformNodeFromNodeID(event.node_id);
if (node)
node->NotifyAccessibilityEvent(event.type);
}
void FlushQueue() {
DCHECK(g_is_queueing_events);
for (QueuedEvent event : g_event_queue.Get())
FireEvent(event);
g_is_queueing_events = false;
g_event_queue.Get().clear();
}
void PostFlushEventQueueTaskIfNecessary() {
if (!g_is_queueing_events) {
g_is_queueing_events = true;
base::OnceCallback<void()> cb = base::BindOnce(&FlushQueue);
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(FROM_HERE,
std::move(cb));
}
}
} // namespace
ViewAXPlatformNodeDelegate::ChildWidgetsResult::ChildWidgetsResult() = default;
ViewAXPlatformNodeDelegate::ChildWidgetsResult::ChildWidgetsResult(
std::vector<Widget*> child_widgets,
bool is_tab_modal_showing)
: child_widgets(child_widgets),
is_tab_modal_showing(is_tab_modal_showing) {}
ViewAXPlatformNodeDelegate::ChildWidgetsResult::ChildWidgetsResult(
const ViewAXPlatformNodeDelegate::ChildWidgetsResult& other) = default;
ViewAXPlatformNodeDelegate::ChildWidgetsResult::~ChildWidgetsResult() = default;
ViewAXPlatformNodeDelegate::ChildWidgetsResult&
ViewAXPlatformNodeDelegate::ChildWidgetsResult::operator=(
const ViewAXPlatformNodeDelegate::ChildWidgetsResult& other) = default;
ViewAXPlatformNodeDelegate::ViewAXPlatformNodeDelegate(View* view)
: ViewAccessibility(view) {}
void ViewAXPlatformNodeDelegate::Init() {
ax_platform_node_ = ui::AXPlatformNode::Create(this);
DCHECK(ax_platform_node_);
static bool first_time = true;
if (first_time) {
ui::AXPlatformNode::RegisterNativeWindowHandler(
base::BindRepeating(&FromNativeWindow));
first_time = false;
}
}
ViewAXPlatformNodeDelegate::~ViewAXPlatformNodeDelegate() {
if (ui::AXPlatformNode::GetPopupFocusOverride() ==
ax_platform_node_->GetNativeViewAccessible()) {
ui::AXPlatformNode::SetPopupFocusOverride(nullptr);
}
// Call ExtractAsDangling() first to clear the underlying pointer and return
// another raw_ptr instance that is allowed to dangle.
ax_platform_node_.ExtractAsDangling()->Destroy();
}
bool ViewAXPlatformNodeDelegate::IsAccessibilityFocusable() const {
return GetData().HasState(ax::mojom::State::kFocusable);
}
bool ViewAXPlatformNodeDelegate::IsFocusedForTesting() const {
if (ui::AXPlatformNode::GetPopupFocusOverride()) {
return ui::AXPlatformNode::GetPopupFocusOverride() ==
GetNativeViewAccessible();
}
return ViewAccessibility::IsFocusedForTesting();
}
void ViewAXPlatformNodeDelegate::SetPopupFocusOverride() {
ui::AXPlatformNode::SetPopupFocusOverride(GetNativeViewAccessible());
}
void ViewAXPlatformNodeDelegate::EndPopupFocusOverride() {
ui::AXPlatformNode::SetPopupFocusOverride(nullptr);
}
void ViewAXPlatformNodeDelegate::FireFocusAfterMenuClose() {
ui::AXPlatformNodeBase* focused_node =
static_cast<ui::AXPlatformNodeBase*>(ax_platform_node_);
// Continue to drill down focused nodes to get to the "deepest" node that is
// focused. This is not necessarily a view. It could be web content.
while (focused_node) {
ui::AXPlatformNodeBase* deeper_focus = static_cast<ui::AXPlatformNodeBase*>(
ui::AXPlatformNode::FromNativeViewAccessible(focused_node->GetFocus()));
if (!deeper_focus || deeper_focus == focused_node)
break;
focused_node = deeper_focus;
}
if (focused_node) {
// Callback used for testing.
if (accessibility_events_callback_) {
accessibility_events_callback_.Run(
this, ax::mojom::Event::kFocusAfterMenuClose);
}
focused_node->NotifyAccessibilityEvent(
ax::mojom::Event::kFocusAfterMenuClose);
}
}
bool ViewAXPlatformNodeDelegate::IsIgnored() const {
// TODO(nektar): Make `ViewAccessibility::IsIgnored()` non-virtual and delete
// this method. For this to happen
// `IsViewUnfocusableDescendantOfFocusableAncestor()` needs to be moved to
// `ViewAccessibility`.
return GetData().IsIgnored();
}
gfx::NativeViewAccessible ViewAXPlatformNodeDelegate::GetNativeObject() const {
DCHECK(ax_platform_node_);
return ax_platform_node_->GetNativeViewAccessible();
}
void ViewAXPlatformNodeDelegate::NotifyAccessibilityEvent(
ax::mojom::Event event_type) {
DCHECK(ax_platform_node_);
if (accessibility_events_callback_)
accessibility_events_callback_.Run(this, event_type);
if (g_is_queueing_events) {
g_event_queue.Get().emplace_back(event_type, GetUniqueId());
return;
}
// Some events have special handling.
switch (event_type) {
case ax::mojom::Event::kFocusAfterMenuClose: {
DCHECK(!ui::AXPlatformNode::GetPopupFocusOverride())
<< "Must call ViewAccessibility::EndPopupFocusOverride() as menu "
"closes.";
break;
}
case ax::mojom::Event::kFocus: {
if (ui::AXPlatformNode::GetPopupFocusOverride()) {
DCHECK_EQ(ui::AXPlatformNode::GetPopupFocusOverride(),
GetNativeViewAccessible())
<< "If the popup focus override is on, then the kFocus event must "
"match it. Most likely the popup has closed, but did not call "
"ViewAccessibility::EndPopupFocusOverride(), and focus has "
"now moved on.";
}
break;
}
case ax::mojom::Event::kFocusContext: {
// A focus context event is intended to send a focus event and a delay
// before the next focus event. It makes sense to delay the entire next
// synchronous batch of next events so that ordering remains the same.
// Begin queueing subsequent events and flush queue asynchronously.
PostFlushEventQueueTaskIfNecessary();
break;
}
case ax::mojom::Event::kLiveRegionChanged: {
// Fire after a delay so that screen readers don't wipe it out when
// another user-generated event fires simultaneously.
PostFlushEventQueueTaskIfNecessary();
g_event_queue.Get().emplace_back(event_type, GetUniqueId());
return;
}
default:
break;
}
// Fire events here now that our internal state is up-to-date.
ax_platform_node_->NotifyAccessibilityEvent(event_type);
}
#if BUILDFLAG(IS_MAC)
void ViewAXPlatformNodeDelegate::AnnounceText(const std::u16string& text) {
ax_platform_node_->AnnounceText(text);
}
#endif // BUILDFLAG(IS_MAC)
const ui::AXNodeData& ViewAXPlatformNodeDelegate::GetData() const {
// Clear the data, then populate it.
data_ = ui::AXNodeData();
GetAccessibleNodeData(&data_);
// View::IsDrawn is true if a View is visible and all of its ancestors are
// visible too, since invisibility inherits.
//
// (We could try to move this logic to ViewAccessibility, but
// that would require ensuring that Chrome OS invalidates the whole
// subtree when a View changes its visibility state.)
if (!view()->IsDrawn())
data_.AddState(ax::mojom::State::kInvisible);
// Make sure this element is excluded from the a11y tree if there's a
// focusable parent. All keyboard focusable elements should be leaf nodes.
// Exceptions to this rule will themselves be accessibility focusable.
//
// Note: this code was added to support MacViews accessibility,
// because we needed a way to mark a View as a leaf node in the
// accessibility tree. We need to replace this with a cross-platform
// solution that works for ChromeVox, too, and move it to ViewAccessibility.
if (IsViewUnfocusableDescendantOfFocusableAncestor(view()))
data_.AddState(ax::mojom::State::kIgnored);
return data_;
}
size_t ViewAXPlatformNodeDelegate::GetChildCount() const {
// We call `ViewAccessibility::IsLeaf` here instead of our own override
// because our class has an expanded definition of what a leaf node is, which
// includes all nodes with zero unignored children. Calling our own override
// would create a circular definition of what a "leaf node" is.
if (ViewAccessibility::IsLeaf())
return 0;
// If present, virtual view children override any real children.
if (!virtual_children().empty()) {
// Ignored virtual views are not exposed in any accessibility platform APIs.
// Remove all ignored virtual view children and recursively replace them
// with their unignored children count.
size_t virtual_child_count = 0;
for (const std::unique_ptr<AXVirtualView>& virtual_child :
virtual_children()) {
if (virtual_child->IsIgnored()) {
virtual_child_count += virtual_child->GetChildCount();
} else {
++virtual_child_count;
}
}
// A virtual views subtree hides any real view children.
return virtual_child_count;
}
const ChildWidgetsResult child_widgets_result = GetChildWidgets();
if (child_widgets_result.is_tab_modal_showing) {
// In order to support the "read title (NVDAKey+T)" and "read window
// (NVDAKey+B)" commands in the NVDA screen reader, hide the rest of the UI
// from the accessibility tree when a modal dialog is showing.
DCHECK_EQ(child_widgets_result.child_widgets.size(), 1U);
return 1;
}
// Ignored views are not exposed in any accessibility platform APIs. Remove
// all ignored view children and recursively replace them with their unignored
// children count. This matches how AXPlatformNodeDelegate::GetChildCount()
// behaves for Web content.
size_t view_child_count = 0;
for (View* child : view()->children()) {
const ViewAccessibility& view_accessibility = child->GetViewAccessibility();
if (view_accessibility.IsIgnored()) {
const auto* child_view_delegate =
static_cast<const ViewAXPlatformNodeDelegate*>(&view_accessibility);
DCHECK(child_view_delegate);
view_child_count += child_view_delegate->GetChildCount();
} else {
++view_child_count;
}
}
return view_child_count + child_widgets_result.child_widgets.size();
}
gfx::NativeViewAccessible ViewAXPlatformNodeDelegate::ChildAtIndex(
size_t index) const {
DCHECK_LT(index, GetChildCount())
<< "|index| should be less than the unignored child count.";
if (IsLeaf())
return nullptr;
if (!virtual_children().empty()) {
// A virtual views subtree hides all the real view children.
for (const std::unique_ptr<AXVirtualView>& virtual_child :
virtual_children()) {
if (virtual_child->IsIgnored()) {
size_t virtual_child_count = virtual_child->GetChildCount();
if (index < virtual_child_count)
return virtual_child->ChildAtIndex(index);
index -= virtual_child_count;
} else {
if (index == 0)
return virtual_child->GetNativeObject();
--index;
}
}
NOTREACHED_NORETURN()
<< "|index| should be less than the unignored child count.";
}
// Our widget might have child widgets. If this is a root view, include those
// widgets in the list of the root view's children because this is the most
// opportune location in the accessibility tree to expose them.
const ChildWidgetsResult child_widgets_result = GetChildWidgets();
const std::vector<Widget*>& child_widgets =
child_widgets_result.child_widgets;
// If a visible tab modal dialog is present, return the dialog's root view.
//
// This is in order to support the "read title (NVDAKey+T)" and "read window
// (NVDAKey+B)" commands in the NVDA screen reader. We need to hide the rest
// of the UI, other than the dialog, from the screen reader.
if (child_widgets_result.is_tab_modal_showing) {
DCHECK_EQ(index, 0u);
DCHECK_EQ(child_widgets.size(), 1U);
return child_widgets[0]->GetRootView()->GetNativeViewAccessible();
}
for (View* child : view()->children()) {
ViewAccessibility& view_accessibility = child->GetViewAccessibility();
if (view_accessibility.IsIgnored()) {
auto* child_view_delegate =
static_cast<ViewAXPlatformNodeDelegate*>(&view_accessibility);
DCHECK(child_view_delegate);
size_t child_count = child_view_delegate->GetChildCount();
if (index < child_count)
return child_view_delegate->ChildAtIndex(index);
index -= child_count;
} else {
if (index == 0)
return view_accessibility.view()->GetNativeViewAccessible();
--index;
}
}
CHECK_LT(index, child_widgets_result.child_widgets.size())
<< "|index| should be less than the unignored child count.";
return child_widgets[index]->GetRootView()->GetNativeViewAccessible();
}
bool ViewAXPlatformNodeDelegate::HasModalDialog() const {
return GetChildWidgets().is_tab_modal_showing;
}
bool ViewAXPlatformNodeDelegate::IsChildOfLeaf() const {
return AXPlatformNodeDelegate::IsChildOfLeaf();
}
ui::AXNodePosition::AXPositionInstance
ViewAXPlatformNodeDelegate::CreateTextPositionAt(
int offset,
ax::mojom::TextAffinity affinity) const {
// Support text navigation only on text fields for now. Primarily this is to
// support navigating the address bar.
if (!IsDescendantOfAtomicTextField())
return ui::AXNodePosition::CreateNullPosition();
if (!single_tree_manager_) {
ui::AXTreeUpdate initial_state;
initial_state.root_id = GetData().id;
initial_state.nodes = {GetData()};
initial_state.has_tree_data = true;
initial_state.tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID();
auto tree = std::make_unique<ui::AXTree>(initial_state);
single_tree_manager_ =
std::make_unique<ui::SingleAXTreeManager>(std::move(tree));
} else {
DCHECK(single_tree_manager_->ax_tree());
ui::AXTreeUpdate update;
update.nodes = {GetData()};
const_cast<ui::AXTree*>(single_tree_manager_->ax_tree())
->Unserialize(update);
}
return ui::AXNodePosition::CreatePosition(*single_tree_manager_->GetRoot(),
offset, affinity);
}
gfx::NativeViewAccessible ViewAXPlatformNodeDelegate::GetNSWindow() {
NOTIMPLEMENTED() << "Should only be called on Mac.";
return nullptr;
}
gfx::NativeViewAccessible ViewAXPlatformNodeDelegate::GetNativeViewAccessible()
const {
// TODO(nektar): Make "GetNativeViewAccessible" const throughout the codebase.
return const_cast<ViewAXPlatformNodeDelegate*>(this)
->GetNativeViewAccessible();
}
gfx::NativeViewAccessible
ViewAXPlatformNodeDelegate::GetNativeViewAccessible() {
// The WebView class returns the BrowserAccessibility instance exposed by its
// WebContents child, not its own AXPlatformNode. This is done by overriding
// "GetNativeViewAccessible", so we can't simply call "GetNativeObject" here.
return view()->GetNativeViewAccessible();
}
gfx::NativeViewAccessible ViewAXPlatformNodeDelegate::GetParent() const {
if (View* parent_view = view()->parent()) {
ViewAccessibility& view_accessibility = parent_view->GetViewAccessibility();
if (!view_accessibility.IsIgnored())
return parent_view->GetNativeViewAccessible();
auto* parent_view_delegate =
static_cast<ViewAXPlatformNodeDelegate*>(&view_accessibility);
DCHECK(parent_view_delegate);
return parent_view_delegate->GetParent();
}
if (Widget* widget = view()->GetWidget()) {
Widget* top_widget = widget->GetTopLevelWidget();
if (top_widget && widget != top_widget && top_widget->GetRootView())
return top_widget->GetRootView()->GetNativeViewAccessible();
}
return nullptr;
}
bool ViewAXPlatformNodeDelegate::IsLeaf() const {
return ViewAccessibility::IsLeaf() || AXPlatformNodeDelegate::IsLeaf();
}
bool ViewAXPlatformNodeDelegate::IsInvisibleOrIgnored() const {
return IsIgnored() || !view()->GetVisible();
}
bool ViewAXPlatformNodeDelegate::IsAccessibilityEnabled() const {
return GetData().GetRestriction() != ax::mojom::Restriction::kDisabled;
}
bool ViewAXPlatformNodeDelegate::IsFocused() const {
return GetFocus() == GetNativeObject();
}
bool ViewAXPlatformNodeDelegate::IsToplevelBrowserWindow() {
// Note: only used on Desktop Linux. Other platforms don't have an application
// node so this would never return true.
ui::AXNodeData data = GetData();
if (data.role != ax::mojom::Role::kWindow)
return false;
AXPlatformNodeDelegate* parent = GetParentDelegate();
return parent && parent->GetData().role == ax::mojom::Role::kApplication;
}
gfx::Rect ViewAXPlatformNodeDelegate::GetBoundsRect(
const ui::AXCoordinateSystem coordinate_system,
const ui::AXClippingBehavior clipping_behavior,
ui::AXOffscreenResult* offscreen_result) const {
switch (coordinate_system) {
case ui::AXCoordinateSystem::kScreenDIPs:
// We could optionally add clipping here if ever needed.
return view()->GetBoundsInScreen();
case ui::AXCoordinateSystem::kScreenPhysicalPixels:
case ui::AXCoordinateSystem::kRootFrame:
case ui::AXCoordinateSystem::kFrame:
NOTIMPLEMENTED();
return gfx::Rect();
}
}
gfx::NativeViewAccessible ViewAXPlatformNodeDelegate::HitTestSync(
int screen_physical_pixel_x,
int screen_physical_pixel_y) const {
if (!view() || !view()->GetWidget())
return nullptr;
if (IsLeaf())
return GetNativeViewAccessible();
gfx::NativeView native_view = view()->GetWidget()->GetNativeView();
float scale_factor = 1.0;
if (native_view) {
scale_factor = ui::GetScaleFactorForNativeView(native_view);
scale_factor = scale_factor <= 0 ? 1.0 : scale_factor;
}
int screen_dips_x = screen_physical_pixel_x / scale_factor;
int screen_dips_y = screen_physical_pixel_y / scale_factor;
// Search child widgets first, since they're on top in the z-order.
for (Widget* child_widget : GetChildWidgets().child_widgets) {
View* child_root_view = child_widget->GetRootView();
gfx::Point point(screen_dips_x, screen_dips_y);
View::ConvertPointFromScreen(child_root_view, &point);
if (child_root_view->HitTestPoint(point))
return child_root_view->GetNativeViewAccessible();
}
gfx::Point point(screen_dips_x, screen_dips_y);
View::ConvertPointFromScreen(view(), &point);
if (!view()->HitTestPoint(point))
return nullptr;
// Check if the point is within any of the virtual children of this view.
// AXVirtualView's HitTestSync is a recursive function that will return the
// deepest child, since it does not support relative bounds.
if (!virtual_children().empty()) {
// Search the greater indices first, since they're on top in the z-order.
for (const std::unique_ptr<AXVirtualView>& child :
base::Reversed(virtual_children())) {
gfx::NativeViewAccessible result =
child->HitTestSync(screen_physical_pixel_x, screen_physical_pixel_y);
if (result)
return result;
}
// If it's not inside any of our virtual children, it's inside this view.
return GetNativeViewAccessible();
}
// Check if the point is within any of the immediate children of this
// view. We don't have to search further because AXPlatformNode will
// do a recursive hit test if we return anything other than |this| or NULL.
View* v = view();
const auto is_point_in_child = [point, v](View* child) {
if (!child->GetVisible())
return false;
ui::AXNodeData child_data;
child->GetViewAccessibility().GetAccessibleNodeData(&child_data);
if (child_data.IsInvisible())
return false;
gfx::Point point_in_child_coords = point;
v->ConvertPointToTarget(v, child, &point_in_child_coords);
return child->HitTestPoint(point_in_child_coords);
};
const auto i =
base::ranges::find_if(base::Reversed(v->children()), is_point_in_child);
// If it's not inside any of our children, it's inside this view.
return (i == v->children().rend()) ? GetNativeViewAccessible()
: (*i)->GetNativeViewAccessible();
}
gfx::NativeViewAccessible ViewAXPlatformNodeDelegate::GetFocus() const {
gfx::NativeViewAccessible focus_override =
ui::AXPlatformNode::GetPopupFocusOverride();
if (focus_override)
return focus_override;
FocusManager* focus_manager = view()->GetFocusManager();
View* focused_view =
focus_manager ? focus_manager->GetFocusedView() : nullptr;
if (!focused_view)
return nullptr;
// The accessibility focus will be either on the |focused_view| or on one of
// its virtual children.
return focused_view->GetViewAccessibility().GetFocusedDescendant();
}
ui::AXPlatformNode* ViewAXPlatformNodeDelegate::GetFromNodeID(int32_t id) {
return PlatformNodeFromNodeID(id);
}
ui::AXPlatformNode* ViewAXPlatformNodeDelegate::GetFromTreeIDAndNodeID(
const ui::AXTreeID& ax_tree_id,
int32_t id) {
return nullptr;
}
bool ViewAXPlatformNodeDelegate::AccessibilityPerformAction(
const ui::AXActionData& data) {
return view()->HandleAccessibleAction(data);
}
bool ViewAXPlatformNodeDelegate::ShouldIgnoreHoveredStateForTesting() {
return false;
}
bool ViewAXPlatformNodeDelegate::IsOffscreen() const {
// TODO(katydek): need to implement.
return false;
}
std::u16string ViewAXPlatformNodeDelegate::GetAuthorUniqueId() const {
const View* v = view();
if (v) {
const int view_id = v->GetID();
if (view_id)
return u"view_" + base::NumberToString16(view_id);
}
return std::u16string();
}
bool ViewAXPlatformNodeDelegate::IsMinimized() const {
Widget* widget = view()->GetWidget();
return widget && widget->IsMinimized();
}
// TODO(accessibility): This function should call AXNode::IsReadOnlySupported
// instead, just like in BrowserAccessibility, but ViewAccessibility objects
// don't have a corresponding AXNode yet.
bool ViewAXPlatformNodeDelegate::IsReadOnlySupported() const {
return ui::IsReadOnlySupported(GetData().role);
}
// TODO(accessibility): This function should call AXNode::IsReadOnlyOrDisabled
// instead, just like in BrowserAccessibility, but ViewAccessibility objects
// don't have a corresponding AXNode yet.
bool ViewAXPlatformNodeDelegate::IsReadOnlyOrDisabled() const {
switch (GetData().GetRestriction()) {
case ax::mojom::Restriction::kReadOnly:
case ax::mojom::Restriction::kDisabled:
return true;
case ax::mojom::Restriction::kNone: {
if (HasState(ax::mojom::State::kEditable) ||
HasState(ax::mojom::State::kRichlyEditable)) {
return false;
}
if (ui::ShouldHaveReadonlyStateByDefault(GetData().role))
return true;
// When readonly is not supported, we assume that the node is always
// read-only and mark it as such since this is the default behavior.
return !IsReadOnlySupported();
}
}
}
const ui::AXUniqueId& ViewAXPlatformNodeDelegate::GetUniqueId() const {
return ViewAccessibility::GetUniqueId();
}
std::vector<int32_t> ViewAXPlatformNodeDelegate::GetColHeaderNodeIds() const {
std::vector<int32_t> col_header_ids;
if (!virtual_children().empty()) {
for (const std::unique_ptr<AXVirtualView>& header_cell :
virtual_children().front()->children()) {
const ui::AXNodeData& header_data = header_cell->GetData();
if (header_data.role == ax::mojom::Role::kColumnHeader) {
col_header_ids.push_back(header_data.id);
}
}
}
return col_header_ids;
}
std::vector<int32_t> ViewAXPlatformNodeDelegate::GetColHeaderNodeIds(
int col_index) const {
std::vector<int32_t> columns = GetColHeaderNodeIds();
if (static_cast<size_t>(col_index) >= columns.size()) {
return {};
}
return {columns[static_cast<size_t>(col_index)]};
}
absl::optional<int32_t> ViewAXPlatformNodeDelegate::GetCellId(
int row_index,
int col_index) const {
if (virtual_children().empty() || !GetAncestorTableView())
return absl::nullopt;
AXVirtualView* ax_cell = GetAncestorTableView()->GetVirtualAccessibilityCell(
static_cast<size_t>(row_index), static_cast<size_t>(col_index));
if (!ax_cell)
return absl::nullopt;
const ui::AXNodeData& cell_data = ax_cell->GetData();
if (cell_data.role == ax::mojom::Role::kCell)
return cell_data.id;
return absl::nullopt;
}
TableView* ViewAXPlatformNodeDelegate::GetAncestorTableView() const {
ui::AXNodeData data;
view()->GetViewAccessibility().GetAccessibleNodeData(&data);
if (!ui::IsTableLike(data.role))
return nullptr;
return static_cast<TableView*>(view());
}
bool ViewAXPlatformNodeDelegate::IsOrderedSetItem() const {
const ui::AXNodeData& data = GetData();
return (view()->GetGroup() >= 0) ||
(data.HasIntAttribute(ax::mojom::IntAttribute::kPosInSet) &&
data.HasIntAttribute(ax::mojom::IntAttribute::kSetSize));
}
bool ViewAXPlatformNodeDelegate::IsOrderedSet() const {
return (view()->GetGroup() >= 0) ||
GetData().HasIntAttribute(ax::mojom::IntAttribute::kSetSize);
}
absl::optional<int> ViewAXPlatformNodeDelegate::GetPosInSet() const {
// Consider overridable attributes first.
const ui::AXNodeData& data = GetData();
if (data.HasIntAttribute(ax::mojom::IntAttribute::kPosInSet))
return data.GetIntAttribute(ax::mojom::IntAttribute::kPosInSet);
std::vector<View*> views_in_group;
GetViewsInGroupForSet(&views_in_group);
if (views_in_group.empty())
return absl::nullopt;
// Check this is in views_in_group; it may be removed if it is ignored.
auto found_view = base::ranges::find(views_in_group, view());
if (found_view == views_in_group.end())
return absl::nullopt;
int pos_in_set = base::checked_cast<int>(
std::distance(views_in_group.begin(), found_view));
// pos_in_set is zero-based; users expect one-based, so increment.
return ++pos_in_set;
}
absl::optional<int> ViewAXPlatformNodeDelegate::GetSetSize() const {
// Consider overridable attributes first.
const ui::AXNodeData& data = GetData();
if (data.HasIntAttribute(ax::mojom::IntAttribute::kSetSize))
return data.GetIntAttribute(ax::mojom::IntAttribute::kSetSize);
std::vector<View*> views_in_group;
GetViewsInGroupForSet(&views_in_group);
if (views_in_group.empty())
return absl::nullopt;
// Check this is in views_in_group; it may be removed if it is ignored.
auto found_view = base::ranges::find(views_in_group, view());
if (found_view == views_in_group.end())
return absl::nullopt;
return base::checked_cast<int>(views_in_group.size());
}
void ViewAXPlatformNodeDelegate::GetViewsInGroupForSet(
std::vector<View*>* views_in_group) const {
const int group_id = view()->GetGroup();
if (group_id < 0)
return;
View* view_to_check = view();
// If this view has a parent, check from the parent, to make sure we catch any
// siblings.
if (view()->parent())
view_to_check = view()->parent();
view_to_check->GetViewsInGroup(group_id, views_in_group);
// Remove any views that are ignored in the accessibility tree.
views_in_group->erase(
std::remove_if(
views_in_group->begin(), views_in_group->end(),
[](View* view) {
ViewAccessibility& view_accessibility =
view->GetViewAccessibility();
return view_accessibility.IsIgnored();
}),
views_in_group->end());
}
bool ViewAXPlatformNodeDelegate::TableHasColumnOrRowHeaderNodeForTesting()
const {
if (!GetAncestorTableView()) {
return false;
}
return !GetAncestorTableView()->visible_columns().empty();
}
ViewAXPlatformNodeDelegate::ChildWidgetsResult
ViewAXPlatformNodeDelegate::GetChildWidgets() const {
// This method is used to create a parent / child relationship between the
// root view and any child widgets. Child widgets should only be exposed as
// the direct children of the root view. A root view should appear as the only
// child of a widget.
Widget* widget = view()->GetWidget();
// Note that during window close, a Widget may exist in a state where it has
// no NativeView, but hasn't yet torn down its view hierarchy.
if (!widget || !widget->GetNativeView() || widget->GetRootView() != view())
return ChildWidgetsResult();
std::set<Widget*> owned_widgets;
Widget::GetAllOwnedWidgets(widget->GetNativeView(), &owned_widgets);
std::vector<Widget*> visible_widgets;
base::ranges::copy_if(owned_widgets, std::back_inserter(visible_widgets),
&Widget::IsVisible);
// Focused child widgets should take the place of the web page they cover in
// the accessibility tree.
const FocusManager* focus_manager = view()->GetFocusManager();
const View* focused_view =
focus_manager ? focus_manager->GetFocusedView() : nullptr;
const auto is_focused_child = [focused_view](Widget* child_widget) {
return ViewAccessibilityUtils::IsFocusedChildWidget(child_widget,
focused_view);
};
const auto i = base::ranges::find_if(visible_widgets, is_focused_child);
// In order to support the "read title (NVDAKey+T)" and "read window
// (NVDAKey+B)" commands in the NVDA screen reader, hide the rest of the UI
// from the accessibility tree when a modal dialog is showing.
if (i != visible_widgets.cend())
return ChildWidgetsResult({*i}, true /* is_tab_modal_showing */);
return ChildWidgetsResult(visible_widgets, false /* is_tab_modal_showing */);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/view_ax_platform_node_delegate.cc | C++ | unknown | 32,382 |
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_ACCESSIBILITY_VIEW_AX_PLATFORM_NODE_DELEGATE_H_
#define UI_VIEWS_ACCESSIBILITY_VIEW_AX_PLATFORM_NODE_DELEGATE_H_
#include <stdint.h>
#include <memory>
#include <string>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "build/build_config.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/accessibility/ax_enums.mojom-forward.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/accessibility/ax_node_position.h"
#include "ui/accessibility/platform/ax_platform_node_delegate.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/controls/table/table_view.h"
#include "ui/views/views_export.h"
#include "ui/views/widget/widget_observer.h"
namespace ui {
struct AXActionData;
class AXUniqueId;
class SingleAXTreeManager;
} // namespace ui
namespace views {
class View;
// Shared base class for platforms that require an implementation of
// |ViewAXPlatformNodeDelegate| to interface with the native accessibility
// toolkit. This class owns the |AXPlatformNode|, which implements those native
// APIs.
class VIEWS_EXPORT ViewAXPlatformNodeDelegate
: public ViewAccessibility,
public ui::AXPlatformNodeDelegate {
public:
ViewAXPlatformNodeDelegate(const ViewAXPlatformNodeDelegate&) = delete;
ViewAXPlatformNodeDelegate& operator=(const ViewAXPlatformNodeDelegate&) =
delete;
~ViewAXPlatformNodeDelegate() override;
// ViewAccessibility:
bool IsAccessibilityFocusable() const override;
bool IsFocusedForTesting() const override;
void SetPopupFocusOverride() override;
void EndPopupFocusOverride() override;
void FireFocusAfterMenuClose() override;
bool IsIgnored() const override;
bool IsAccessibilityEnabled() const override;
gfx::NativeViewAccessible GetNativeObject() const override;
void NotifyAccessibilityEvent(ax::mojom::Event event_type) override;
#if BUILDFLAG(IS_MAC)
void AnnounceText(const std::u16string& text) override;
#endif
// ui::AXPlatformNodeDelegate.
const ui::AXNodeData& GetData() const override;
size_t GetChildCount() const override;
gfx::NativeViewAccessible ChildAtIndex(size_t index) const override;
bool HasModalDialog() const override;
// Also in |ViewAccessibility|.
bool IsChildOfLeaf() const override;
ui::AXNodePosition::AXPositionInstance CreateTextPositionAt(
int offset,
ax::mojom::TextAffinity affinity) const override;
gfx::NativeViewAccessible GetNSWindow() override;
// TODO(nektar): Make "GetNativeViewAccessible" a const method throughout the
// codebase.
gfx::NativeViewAccessible GetNativeViewAccessible() const;
gfx::NativeViewAccessible GetNativeViewAccessible() override;
gfx::NativeViewAccessible GetParent() const override;
bool IsLeaf() const override;
bool IsInvisibleOrIgnored() const override;
bool IsFocused() const override;
bool IsToplevelBrowserWindow() override;
gfx::Rect GetBoundsRect(
const ui::AXCoordinateSystem coordinate_system,
const ui::AXClippingBehavior clipping_behavior,
ui::AXOffscreenResult* offscreen_result) const override;
gfx::NativeViewAccessible HitTestSync(
int screen_physical_pixel_x,
int screen_physical_pixel_y) const override;
gfx::NativeViewAccessible GetFocus() const override;
ui::AXPlatformNode* GetFromNodeID(int32_t id) override;
ui::AXPlatformNode* GetFromTreeIDAndNodeID(const ui::AXTreeID& ax_tree_id,
int32_t id) override;
bool AccessibilityPerformAction(const ui::AXActionData& data) override;
bool ShouldIgnoreHoveredStateForTesting() override;
bool IsOffscreen() const override;
std::u16string GetAuthorUniqueId() const override;
bool IsMinimized() const override;
bool IsReadOnlySupported() const override;
bool IsReadOnlyOrDisabled() const override;
// Also in |ViewAccessibility|.
const ui::AXUniqueId& GetUniqueId() const override;
std::vector<int32_t> GetColHeaderNodeIds() const override;
std::vector<int32_t> GetColHeaderNodeIds(int col_index) const override;
absl::optional<int32_t> GetCellId(int row_index,
int col_index) const override;
bool IsOrderedSetItem() const override;
bool IsOrderedSet() const override;
absl::optional<int> GetPosInSet() const override;
absl::optional<int> GetSetSize() const override;
bool TableHasColumnOrRowHeaderNodeForTesting() const;
protected:
explicit ViewAXPlatformNodeDelegate(View* view);
friend class ViewAccessibility;
// Called by ViewAccessibility::Create immediately after
// construction. Used to avoid issues with calling virtual functions
// during the constructor.
virtual void Init();
ui::AXPlatformNode* ax_platform_node() { return ax_platform_node_; }
private:
struct ChildWidgetsResult final {
ChildWidgetsResult();
ChildWidgetsResult(std::vector<Widget*> child_widgets,
bool is_tab_modal_showing);
ChildWidgetsResult(const ChildWidgetsResult& other);
virtual ~ChildWidgetsResult();
ChildWidgetsResult& operator=(const ChildWidgetsResult& other);
std::vector<Widget*> child_widgets;
// When the focus is within a child widget, |child_widgets| contains only
// that widget. Otherwise, |child_widgets| contains all child widgets.
//
// The former arises when a modal dialog is showing. In order to support the
// "read title (NVDAKey+T)" and "read window (NVDAKey+B)" commands in the
// NVDA screen reader, we need to hide the rest of the UI from the
// accessibility tree for these commands to work properly.
bool is_tab_modal_showing = false;
};
// Uses Views::GetViewsInGroup to find nearby Views in the same group.
// Searches from the View's parent to include siblings within that group.
void GetViewsInGroupForSet(std::vector<View*>* views_in_group) const;
// If this delegate is attached to the root view, returns all the child
// widgets of this view's owning widget.
ChildWidgetsResult GetChildWidgets() const;
// Gets the real (non-virtual) TableView, otherwise nullptr.
TableView* GetAncestorTableView() const;
// A tree manager that is used to hook up `AXPosition` to text fields in
// Views.
mutable std::unique_ptr<ui::SingleAXTreeManager> single_tree_manager_;
// We own this, but it is reference-counted on some platforms so we can't use
// a unique_ptr. It is destroyed in the destructor.
raw_ptr<ui::AXPlatformNode> ax_platform_node_ = nullptr;
mutable ui::AXNodeData data_;
};
} // namespace views
#endif // UI_VIEWS_ACCESSIBILITY_VIEW_AX_PLATFORM_NODE_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/view_ax_platform_node_delegate.h | C++ | unknown | 6,841 |
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/accessibility/view_ax_platform_node_delegate_auralinux.h"
#include <memory>
#include <vector>
#include "base/containers/contains.h"
#include "base/memory/raw_ptr.h"
#include "base/no_destructor.h"
#include "base/ranges/algorithm.h"
#include "base/scoped_multi_source_observation.h"
#include "ui/accessibility/ax_action_data.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/accessibility/platform/ax_platform_node_auralinux.h"
#include "ui/accessibility/platform/ax_platform_node_delegate.h"
#include "ui/aura/window.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/accessibility/views_utilities_aura.h"
#include "ui/views/view.h"
#include "ui/views/views_delegate.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_observer.h"
#include "ui/wm/core/window_util.h"
namespace views {
namespace {
// Return the widget of any parent window of |widget|, first checking for
// transient parent windows.
Widget* GetWidgetOfParentWindowIncludingTransient(Widget* widget) {
if (!widget)
return nullptr;
aura::Window* window = widget->GetNativeWindow();
if (!window)
return nullptr;
// Look for an ancestor window with a Widget, and if found, return
// the NativeViewAccessible for its RootView.
aura::Window* ancestor_window = GetWindowParentIncludingTransient(window);
if (!ancestor_window)
return nullptr;
return Widget::GetWidgetForNativeView(ancestor_window);
}
// Return the toplevel widget ancestor of |widget|, including widgets of
// parents of transient windows.
Widget* GetToplevelWidgetIncludingTransientWindows(Widget* widget) {
widget = widget->GetTopLevelWidget();
if (Widget* parent_widget = GetWidgetOfParentWindowIncludingTransient(widget))
return GetToplevelWidgetIncludingTransientWindows(parent_widget);
return widget;
}
// ATK requires that we have a single root "application" object that's the
// owner of all other windows. This is a simple class that implements the
// AXPlatformNodeDelegate interface so we can create such an application
// object. Every time we create an accessibility object for a View, we add its
// top-level widget to a vector so we can return the list of all top-level
// windows as children of this application object.
class AuraLinuxApplication : public ui::AXPlatformNodeDelegate,
public WidgetObserver,
public aura::WindowObserver {
public:
AuraLinuxApplication(const AuraLinuxApplication&) = delete;
AuraLinuxApplication& operator=(const AuraLinuxApplication&) = delete;
// Get the single instance of this class.
static AuraLinuxApplication& GetInstance() {
static base::NoDestructor<AuraLinuxApplication> instance;
return *instance;
}
// Called every time we create a new accessibility on a View.
// Add the top-level widget to our registry so that we can enumerate all
// top-level widgets.
void RegisterWidget(Widget* widget) {
if (!widget)
return;
widget = GetToplevelWidgetIncludingTransientWindows(widget);
if (!widget || base::Contains(widgets_, widget))
return;
widgets_.push_back(widget);
widget_observations_.AddObservation(widget);
aura::Window* window = widget->GetNativeWindow();
if (window)
window_observations_.AddObservation(window);
}
gfx::NativeViewAccessible GetNativeViewAccessible() override {
return ax_platform_node_->GetNativeViewAccessible();
}
const ui::AXUniqueId& GetUniqueId() const override { return unique_id_; }
// WidgetObserver:
void OnWidgetDestroying(Widget* widget) override {
widget_observations_.RemoveObservation(widget);
aura::Window* window = widget->GetNativeWindow();
if (window && window_observations_.IsObservingSource(window))
window_observations_.RemoveObservation(window);
auto iter = base::ranges::find(widgets_, widget);
if (iter != widgets_.end())
widgets_.erase(iter);
}
void OnWindowVisibilityChanged(aura::Window* window, bool visible) override {
for (Widget* widget : widgets_) {
if (widget->GetNativeWindow() != window)
continue;
View* root_view = widget->GetRootView();
if (!root_view)
continue;
root_view->NotifyAccessibilityEvent(
ax::mojom::Event::kWindowVisibilityChanged, true);
}
}
// ui::AXPlatformNodeDelegate:
const ui::AXNodeData& GetData() const override {
// Despite the fact that the comment above
// `views::ViewsDelegate::GetInstance()` says that a nullptr check is not
// needed, we discovered that the delegate instance may be nullptr during
// test setup. Since the application name does not change, we can set it
// only once and avoid setting it every time our accessibility data is
// retrieved.
if (data_.GetStringAttribute(ax::mojom::StringAttribute::kName).empty() &&
ViewsDelegate::GetInstance()) {
data_.SetNameChecked(ViewsDelegate::GetInstance()->GetApplicationName());
}
return data_;
}
size_t GetChildCount() const override { return widgets_.size(); }
gfx::NativeViewAccessible ChildAtIndex(size_t index) const override {
if (index >= GetChildCount())
return nullptr;
Widget* widget = widgets_[index];
CHECK(widget);
return widget->GetRootView()->GetNativeViewAccessible();
}
bool IsChildOfLeaf() const override {
// TODO(crbug.com/1100047): Needed to prevent endless loops only on Linux
// ATK.
return false;
}
private:
friend class base::NoDestructor<AuraLinuxApplication>;
AuraLinuxApplication() {
data_.id = unique_id_.Get();
data_.role = ax::mojom::Role::kApplication;
data_.AddState(ax::mojom::State::kFocusable);
ax_platform_node_ = ui::AXPlatformNode::Create(this);
DCHECK(ax_platform_node_);
ui::AXPlatformNodeAuraLinux::SetApplication(ax_platform_node_);
ui::AXPlatformNodeAuraLinux::StaticInitialize();
}
~AuraLinuxApplication() override {
ax_platform_node_->Destroy();
ax_platform_node_ = nullptr;
}
// TODO(nektar): Make this into a const pointer so that it can't be set
// outside the class's constructor.
raw_ptr<ui::AXPlatformNode> ax_platform_node_;
ui::AXUniqueId unique_id_;
mutable ui::AXNodeData data_;
std::vector<Widget*> widgets_;
base::ScopedMultiSourceObservation<Widget, WidgetObserver>
widget_observations_{this};
base::ScopedMultiSourceObservation<aura::Window, aura::WindowObserver>
window_observations_{this};
};
} // namespace
// static
std::unique_ptr<ViewAccessibility> ViewAccessibility::Create(View* view) {
AuraLinuxApplication::GetInstance().RegisterWidget(view->GetWidget());
auto result = std::make_unique<ViewAXPlatformNodeDelegateAuraLinux>(view);
result->Init();
return result;
}
ViewAXPlatformNodeDelegateAuraLinux::ViewAXPlatformNodeDelegateAuraLinux(
View* view)
: ViewAXPlatformNodeDelegate(view) {}
void ViewAXPlatformNodeDelegateAuraLinux::Init() {
ViewAXPlatformNodeDelegate::Init();
view_observation_.Observe(view());
}
ViewAXPlatformNodeDelegateAuraLinux::~ViewAXPlatformNodeDelegateAuraLinux() {
view_observation_.Reset();
}
gfx::NativeViewAccessible ViewAXPlatformNodeDelegateAuraLinux::GetParent()
const {
if (gfx::NativeViewAccessible parent =
ViewAXPlatformNodeDelegate::GetParent()) {
return parent;
}
Widget* parent_widget =
GetWidgetOfParentWindowIncludingTransient(view()->GetWidget());
if (parent_widget)
return parent_widget->GetRootView()->GetNativeViewAccessible();
return AuraLinuxApplication::GetInstance().GetNativeViewAccessible();
}
bool ViewAXPlatformNodeDelegateAuraLinux::IsChildOfLeaf() const {
// TODO(crbug.com/1100047): Needed to prevent endless loops only on Linux ATK.
return false;
}
void ViewAXPlatformNodeDelegateAuraLinux::OnViewHierarchyChanged(
View* observed_view,
const ViewHierarchyChangedDetails& details) {
if (view() != details.child || !details.is_add)
return;
static_cast<ui::AXPlatformNodeAuraLinux*>(ax_platform_node())
->OnParentChanged();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/view_ax_platform_node_delegate_auralinux.cc | C++ | unknown | 8,334 |
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_ACCESSIBILITY_VIEW_AX_PLATFORM_NODE_DELEGATE_AURALINUX_H_
#define UI_VIEWS_ACCESSIBILITY_VIEW_AX_PLATFORM_NODE_DELEGATE_AURALINUX_H_
#include "base/scoped_observation.h"
#include "ui/views/accessibility/view_ax_platform_node_delegate.h"
#include "ui/views/view_observer.h"
namespace views {
class View;
class ViewAXPlatformNodeDelegateAuraLinux : public ViewAXPlatformNodeDelegate,
public ViewObserver {
public:
explicit ViewAXPlatformNodeDelegateAuraLinux(View* view);
ViewAXPlatformNodeDelegateAuraLinux(
const ViewAXPlatformNodeDelegateAuraLinux&) = delete;
ViewAXPlatformNodeDelegateAuraLinux& operator=(
const ViewAXPlatformNodeDelegateAuraLinux&) = delete;
~ViewAXPlatformNodeDelegateAuraLinux() override;
void Init() override;
// |ViewAXPlatformNodeDelegate| overrides:
gfx::NativeViewAccessible GetParent() const override;
bool IsChildOfLeaf() const override;
private:
void OnViewHierarchyChanged(
View* observed_view,
const ViewHierarchyChangedDetails& details) override;
base::ScopedObservation<View, ViewObserver> view_observation_{this};
};
} // namespace views
#endif // UI_VIEWS_ACCESSIBILITY_VIEW_AX_PLATFORM_NODE_DELEGATE_AURALINUX_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/view_ax_platform_node_delegate_auralinux.h | C++ | unknown | 1,414 |
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/accessibility/view_ax_platform_node_delegate.h"
#include <atk/atk.h>
#include <memory>
#include "base/test/gtest_util.h"
#include "ui/accessibility/platform/ax_platform_node.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/widget/unique_widget_ptr.h"
namespace views::test {
class ViewAXPlatformNodeDelegateAuraLinuxTest : public ViewsTestBase {
public:
ViewAXPlatformNodeDelegateAuraLinuxTest()
: ax_mode_setter_(ui::kAXModeComplete) {}
~ViewAXPlatformNodeDelegateAuraLinuxTest() override = default;
private:
ScopedAXModeSetter ax_mode_setter_;
};
TEST_F(ViewAXPlatformNodeDelegateAuraLinuxTest, TextfieldAccessibility) {
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP);
widget->Init(std::move(init_params));
View* content = widget->SetContentsView(std::make_unique<View>());
Textfield* textfield = new Textfield;
textfield->SetAccessibleName(u"Name");
content->AddChildView(textfield);
ASSERT_EQ(0, atk_object_get_n_accessible_children(
textfield->GetNativeViewAccessible()))
<< "Text fields should be leaf nodes on this platform, otherwise no "
"descendants will be recognized by assistive software.";
AtkText* atk_text = ATK_TEXT(textfield->GetNativeViewAccessible());
ASSERT_NE(nullptr, atk_text);
struct TextChangeData {
int position;
int length;
std::string text;
};
std::vector<TextChangeData> text_remove_events;
std::vector<TextChangeData> text_insert_events;
GCallback callback = G_CALLBACK(
+[](AtkText*, int position, int length, char* text, gpointer data) {
auto* events = static_cast<std::vector<TextChangeData>*>(data);
events->push_back(TextChangeData{position, length, text});
});
g_signal_connect(atk_text, "text-insert", callback, &text_insert_events);
g_signal_connect(atk_text, "text-remove", callback, &text_remove_events);
textfield->SetText(u"Value");
ASSERT_EQ(text_remove_events.size(), 0ul);
ASSERT_EQ(text_insert_events.size(), 1ul);
EXPECT_EQ(text_insert_events[0].position, 0);
EXPECT_EQ(text_insert_events[0].length, 5);
EXPECT_EQ(text_insert_events[0].text, "Value");
text_insert_events.clear();
textfield->SetText(u"Value A");
ASSERT_EQ(text_remove_events.size(), 0ul);
ASSERT_EQ(text_insert_events.size(), 1ul);
EXPECT_EQ(text_insert_events[0].position, 5);
EXPECT_EQ(text_insert_events[0].length, 2);
EXPECT_EQ(text_insert_events[0].text, " A");
text_insert_events.clear();
textfield->SetText(u"Value");
ASSERT_EQ(text_remove_events.size(), 1ul);
ASSERT_EQ(text_insert_events.size(), 0ul);
EXPECT_EQ(text_remove_events[0].position, 5);
EXPECT_EQ(text_remove_events[0].length, 2);
EXPECT_EQ(text_remove_events[0].text, " A");
text_remove_events.clear();
textfield->SetText(u"Prefix Value");
ASSERT_EQ(text_remove_events.size(), 0ul);
ASSERT_EQ(text_insert_events.size(), 1ul);
EXPECT_EQ(text_insert_events[0].position, 0);
EXPECT_EQ(text_insert_events[0].length, 7);
EXPECT_EQ(text_insert_events[0].text, "Prefix ");
text_insert_events.clear();
textfield->SetText(u"Value");
ASSERT_EQ(text_remove_events.size(), 1ul);
ASSERT_EQ(text_insert_events.size(), 0ul);
EXPECT_EQ(text_remove_events[0].position, 0);
EXPECT_EQ(text_remove_events[0].length, 7);
EXPECT_EQ(text_remove_events[0].text, "Prefix ");
text_insert_events.clear();
}
TEST_F(ViewAXPlatformNodeDelegateAuraLinuxTest,
ExpandedChangedNotFiredOnNonExpandableViews) {
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP);
widget->Init(std::move(init_params));
View* content = widget->SetContentsView(std::make_unique<View>());
EXPECT_DCHECK_DEATH(content->NotifyAccessibilityEvent(
ax::mojom::Event::kExpandedChanged, true));
}
TEST_F(ViewAXPlatformNodeDelegateAuraLinuxTest, AuraChildWidgets) {
// Create the parent widget->
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams init_params =
CreateParams(Widget::InitParams::TYPE_WINDOW);
init_params.bounds = gfx::Rect(0, 0, 400, 200);
widget->Init(std::move(init_params));
widget->Show();
// Initially it has 1 child.
AtkObject* root_view_accessible =
widget->GetRootView()->GetNativeViewAccessible();
ASSERT_EQ(1, atk_object_get_n_accessible_children(root_view_accessible));
// Create the child widget, one of two ways (see below).
UniqueWidgetPtr child_widget = std::make_unique<Widget>();
Widget::InitParams child_init_params =
CreateParams(Widget::InitParams::TYPE_BUBBLE);
child_init_params.parent = widget->GetNativeView();
child_init_params.bounds = gfx::Rect(30, 40, 100, 50);
child_init_params.child = false;
child_widget->Init(std::move(child_init_params));
child_widget->Show();
// Now the AtkObject for the parent widget should have 2 children.
ASSERT_EQ(2, atk_object_get_n_accessible_children(root_view_accessible));
// Make sure that querying the parent of the child gets us back to
// the original parent.
AtkObject* child_widget_accessible =
child_widget->GetRootView()->GetNativeViewAccessible();
ASSERT_EQ(atk_object_get_parent(child_widget_accessible),
root_view_accessible);
// Make sure that querying the second child of the parent is the child widget
// accessible as well.
AtkObject* second_child =
atk_object_ref_accessible_child(root_view_accessible, 1);
ASSERT_EQ(second_child, child_widget_accessible);
g_object_unref(second_child);
}
// Tests if atk_object_get_index_in_parent doesn't DCHECK after the
// corresponding View is removed from a widget->
TEST_F(ViewAXPlatformNodeDelegateAuraLinuxTest, IndexInParent) {
// Create the Widget that will represent the application
UniqueWidgetPtr parent_widget = std::make_unique<Widget>();
Widget::InitParams init_params =
CreateParams(Widget::InitParams::TYPE_WINDOW);
parent_widget->Init(std::move(init_params));
parent_widget->Show();
// |widget| will be destroyed later.
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams child_init_params =
CreateParams(Widget::InitParams::TYPE_POPUP);
child_init_params.parent = parent_widget->GetNativeView();
widget->Init(std::move(child_init_params));
widget->Show();
View* const contents = widget->SetContentsView(std::make_unique<View>());
AtkObject* atk_object = contents->GetNativeViewAccessible();
EXPECT_EQ(0, atk_object_get_index_in_parent(atk_object));
std::unique_ptr<View> contents_unique =
widget->GetRootView()->RemoveChildViewT(contents);
EXPECT_EQ(-1, atk_object_get_index_in_parent(atk_object));
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/view_ax_platform_node_delegate_auralinux_unittest.cc | C++ | unknown | 7,026 |
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_ACCESSIBILITY_VIEW_AX_PLATFORM_NODE_DELEGATE_MAC_H_
#define UI_VIEWS_ACCESSIBILITY_VIEW_AX_PLATFORM_NODE_DELEGATE_MAC_H_
#include "ui/views/accessibility/view_ax_platform_node_delegate.h"
#include <string>
namespace views {
// Mac-specific accessibility class for |ViewAXPlatformNodeDelegate|.
class ViewAXPlatformNodeDelegateMac : public ViewAXPlatformNodeDelegate {
public:
explicit ViewAXPlatformNodeDelegateMac(View* view);
ViewAXPlatformNodeDelegateMac(const ViewAXPlatformNodeDelegateMac&) = delete;
ViewAXPlatformNodeDelegateMac& operator=(
const ViewAXPlatformNodeDelegateMac&) = delete;
~ViewAXPlatformNodeDelegateMac() override;
// |ViewAXPlatformNodeDelegate| overrides:
gfx::NativeViewAccessible GetNSWindow() override;
gfx::NativeViewAccessible GetParent() const override;
// |ViewAccessibility| overrides:
void OverrideNativeWindowTitle(const std::string& title) override;
};
} // namespace views
#endif // UI_VIEWS_ACCESSIBILITY_VIEW_AX_PLATFORM_NODE_DELEGATE_MAC_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/view_ax_platform_node_delegate_mac.h | C++ | unknown | 1,178 |
// Copyright 2017 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/accessibility/view_ax_platform_node_delegate_mac.h"
#include <memory>
#include "ui/accessibility/platform/ax_platform_node_mac.h"
#include "ui/views/cocoa/native_widget_mac_ns_window_host.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
namespace views {
// static
std::unique_ptr<ViewAccessibility> ViewAccessibility::Create(View* view) {
auto result = std::make_unique<ViewAXPlatformNodeDelegateMac>(view);
result->Init();
return result;
}
ViewAXPlatformNodeDelegateMac::ViewAXPlatformNodeDelegateMac(View* view)
: ViewAXPlatformNodeDelegate(view) {}
ViewAXPlatformNodeDelegateMac::~ViewAXPlatformNodeDelegateMac() = default;
gfx::NativeViewAccessible ViewAXPlatformNodeDelegateMac::GetNSWindow() {
auto* widget = view()->GetWidget();
if (!widget)
return nil;
auto* window_host = NativeWidgetMacNSWindowHost::GetFromNativeWindow(
widget->GetNativeWindow());
if (!window_host)
return nil;
return window_host->GetNativeViewAccessibleForNSWindow();
}
gfx::NativeViewAccessible ViewAXPlatformNodeDelegateMac::GetParent() const {
if (view()->parent())
return ViewAXPlatformNodeDelegate::GetParent();
auto* widget = view()->GetWidget();
if (!widget)
return nil;
auto* window_host = NativeWidgetMacNSWindowHost::GetFromNativeWindow(
view()->GetWidget()->GetNativeWindow());
if (!window_host)
return nil;
return window_host->GetNativeViewAccessibleForNSView();
}
void ViewAXPlatformNodeDelegateMac::OverrideNativeWindowTitle(
const std::string& title) {
if (gfx::NativeViewAccessible ax_window = GetNSWindow()) {
[ax_window setAccessibilityLabel:base::SysUTF8ToNSString(title)];
}
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/view_ax_platform_node_delegate_mac.mm | Objective-C++ | unknown | 1,915 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/accessibility/view_ax_platform_node_delegate.h"
#include <memory>
#include <string>
#include "base/memory/raw_ptr.h"
#include "base/strings/utf_string_conversions.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/widget/widget_delegate.h"
namespace views::test {
namespace {
static const char* kDialogName = "DialogName";
static const char* kDifferentNodeName = "DifferentNodeName";
static const char* kDescription = "SomeDescription";
class AccessibleView : public View {
public:
void GetAccessibleNodeData(ui::AXNodeData* node_data) override {
node_data->role = role_;
node_data->SetNameChecked(name_);
if (description_) {
if (description_->empty())
node_data->SetDescriptionExplicitlyEmpty();
else
node_data->SetDescription(*description_);
}
}
ViewAXPlatformNodeDelegate* GetPlatformNodeDelegate() {
return static_cast<ViewAXPlatformNodeDelegate*>(&GetViewAccessibility());
}
void SetDescription(const absl::optional<std::string>& descritpion) {
description_ = descritpion;
}
const absl::optional<std::string>& GetDescription() const {
return description_;
}
void SetNameChecked(const std::string& name) { name_ = name; }
const std::string& GetName() const { return name_; }
void SetRole(ax::mojom::Role role) { role_ = role; }
ax::mojom::Role GetRole() const { return role_; }
private:
absl::optional<std::string> description_ = kDescription;
std::string name_ = kDialogName;
ax::mojom::Role role_ = ax::mojom::Role::kDialog;
};
} // namespace
class ViewAXPlatformNodeDelegateMacTest : public ViewsTestBase {
public:
ViewAXPlatformNodeDelegateMacTest() = default;
~ViewAXPlatformNodeDelegateMacTest() override = default;
void SetUp() override {
ViewsTestBase::SetUp();
widget_ = CreateTestWidget();
widget_->widget_delegate()->SetTitle(base::ASCIIToUTF16(kDialogName));
view_ = widget_->SetContentsView(std::make_unique<AccessibleView>());
}
void TearDown() override {
widget_.reset();
ViewsTestBase::TearDown();
}
protected:
std::unique_ptr<Widget> widget_;
raw_ptr<AccessibleView> view_;
};
TEST_F(ViewAXPlatformNodeDelegateMacTest,
GetNameReturnsNodeNameWhenNameAndTitleAreEqual) {
EXPECT_NE(view_->GetPlatformNodeDelegate()->GetName(),
*view_->GetDescription());
}
TEST_F(ViewAXPlatformNodeDelegateMacTest,
GetNameReturnsNodeNameWhenNameAndTitleAreDifferent) {
EXPECT_NE(view_->GetPlatformNodeDelegate()->GetName(),
*view_->GetDescription());
view_->SetNameChecked(kDifferentNodeName);
EXPECT_EQ(view_->GetPlatformNodeDelegate()->GetName(), kDifferentNodeName);
}
TEST_F(ViewAXPlatformNodeDelegateMacTest, GetNameReturnsNodeNameForNonDialog) {
EXPECT_NE(view_->GetPlatformNodeDelegate()->GetName(),
*view_->GetDescription());
view_->SetRole(ax::mojom::Role::kDesktop);
EXPECT_EQ(view_->GetPlatformNodeDelegate()->GetName(), kDialogName);
}
TEST_F(ViewAXPlatformNodeDelegateMacTest,
GetNameReturnsNodeNameWhenDescriptionIsNotSet) {
EXPECT_NE(view_->GetPlatformNodeDelegate()->GetName(),
*view_->GetDescription());
view_->SetDescription(absl::nullopt);
EXPECT_EQ(view_->GetPlatformNodeDelegate()->GetName(), kDialogName);
}
TEST_F(ViewAXPlatformNodeDelegateMacTest,
GetNameReturnsNodeNameWhenDescriptionIsAnEmptyString) {
EXPECT_NE(view_->GetPlatformNodeDelegate()->GetName(),
*view_->GetDescription());
view_->SetDescription("");
EXPECT_EQ(view_->GetPlatformNodeDelegate()->GetName(), kDialogName);
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/view_ax_platform_node_delegate_mac_unittest.cc | C++ | unknown | 3,888 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/accessibility/view_ax_platform_node_delegate.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/gtest_util.h"
#include "build/build_config.h"
#include "ui/accessibility/ax_action_data.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/accessibility/platform/ax_platform_node.h"
#include "ui/accessibility/platform/ax_platform_node_base.h"
#include "ui/base/models/table_model.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/rect_conversions.h"
#include "ui/gfx/geometry/size.h"
#include "ui/views/accessibility/ax_aura_obj_cache.h"
#include "ui/views/accessibility/ax_aura_obj_wrapper.h"
#include "ui/views/accessibility/ax_event_manager.h"
#include "ui/views/accessibility/ax_event_observer.h"
#include "ui/views/accessibility/ax_widget_obj_wrapper.h"
#include "ui/views/controls/button/button.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/menu/submenu_view.h"
#include "ui/views/controls/menu/test_menu_item_view.h"
#include "ui/views/controls/scroll_view.h"
#include "ui/views/controls/table/table_view.h"
#include "ui/views/test/menu_test_utils.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/widget/unique_widget_ptr.h"
#include "ui/views/widget/widget.h"
namespace views::test {
namespace {
class TestButton : public Button {
public:
TestButton() : Button(Button::PressedCallback()) {}
TestButton(const TestButton&) = delete;
TestButton& operator=(const TestButton&) = delete;
~TestButton() override = default;
};
class TestAXEventObserver : public AXEventObserver {
public:
explicit TestAXEventObserver(AXAuraObjCache* cache) : cache_(cache) {
AXEventManager::Get()->AddObserver(this);
}
TestAXEventObserver(const TestAXEventObserver&) = delete;
TestAXEventObserver& operator=(const TestAXEventObserver&) = delete;
~TestAXEventObserver() override {
AXEventManager::Get()->RemoveObserver(this);
}
// AXEventObserver:
void OnViewEvent(View* view, ax::mojom::Event event_type) override {
std::vector<AXAuraObjWrapper*> out_children;
AXAuraObjWrapper* ax_obj = cache_->GetOrCreate(view->GetWidget());
ax_obj->GetChildren(&out_children);
}
private:
raw_ptr<AXAuraObjCache> cache_;
};
} // namespace
class TestTableModel : public ui::TableModel {
public:
TestTableModel() = default;
TestTableModel(const TestTableModel&) = delete;
TestTableModel& operator=(const TestTableModel&) = delete;
// ui::TableModel:
size_t RowCount() override { return 10; }
std::u16string GetText(size_t row, int column_id) override {
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 base::ASCIIToUTF16(cells[row % 5][column_id]);
}
void SetObserver(ui::TableModelObserver* observer) override {}
};
class ViewAXPlatformNodeDelegateTest : public ViewsTestBase {
public:
ViewAXPlatformNodeDelegateTest() : ax_mode_setter_(ui::kAXModeComplete) {}
ViewAXPlatformNodeDelegateTest(const ViewAXPlatformNodeDelegateTest&) =
delete;
ViewAXPlatformNodeDelegateTest& operator=(
const ViewAXPlatformNodeDelegateTest&) = delete;
~ViewAXPlatformNodeDelegateTest() override = default;
void SetUp() override {
ViewsTestBase::SetUp();
widget_ = new Widget;
Widget::InitParams params =
CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
params.bounds = gfx::Rect(0, 0, 200, 200);
widget_->Init(std::move(params));
button_ = new TestButton();
button_->SetID(NON_DEFAULT_VIEW_ID);
button_->SetSize(gfx::Size(20, 20));
label_ = new Label();
label_->SetID(DEFAULT_VIEW_ID);
button_->AddChildView(label_.get());
widget_->GetRootView()->AddChildView(button_.get());
widget_->Show();
}
void TearDown() override {
if (!widget_->IsClosed())
widget_->Close();
ViewsTestBase::TearDown();
}
ViewAXPlatformNodeDelegate* button_accessibility() {
return static_cast<ViewAXPlatformNodeDelegate*>(
&button_->GetViewAccessibility());
}
ViewAXPlatformNodeDelegate* label_accessibility() {
return static_cast<ViewAXPlatformNodeDelegate*>(
&label_->GetViewAccessibility());
}
ViewAXPlatformNodeDelegate* view_accessibility(View* view) {
return static_cast<ViewAXPlatformNodeDelegate*>(
&view->GetViewAccessibility());
}
bool SetFocused(ViewAXPlatformNodeDelegate* ax_delegate, bool focused) {
ui::AXActionData data;
data.action =
focused ? ax::mojom::Action::kFocus : ax::mojom::Action::kBlur;
return ax_delegate->AccessibilityPerformAction(data);
}
// Sets up a more complicated structure of Views - one parent View with four
// child Views.
View::Views SetUpExtraViews() {
View* parent_view =
widget_->GetRootView()->AddChildView(std::make_unique<View>());
View::Views views{parent_view};
for (int i = 0; i < 4; i++)
views.push_back(parent_view->AddChildView(std::make_unique<View>()));
return views;
}
// Adds group id information to the first 5 values in |views|.
void SetUpExtraViewsGroups(const View::Views& views) {
// v[0] g1
// | | | |
// v[1] g1 v[2] g1 v[3] g2 v[4]
ASSERT_GE(views.size(), 5u);
views[0]->SetGroup(1);
views[1]->SetGroup(1);
views[2]->SetGroup(1);
views[3]->SetGroup(2);
// Skip views[4] - no group id.
}
// Adds posInSet and setSize overrides to the first 5 values in |views|.
void SetUpExtraViewsSetOverrides(const View::Views& views) {
// v[0] p4 s4
// | | | |
// v[1] p3 s4 v[2] p2 s4 v[3] p- s- v[4] p1 s4
ASSERT_GE(views.size(), 5u);
views[0]->GetViewAccessibility().OverridePosInSet(4, 4);
views[1]->GetViewAccessibility().OverridePosInSet(3, 4);
views[2]->GetViewAccessibility().OverridePosInSet(2, 4);
// Skip views[3] - no override.
views[4]->GetViewAccessibility().OverridePosInSet(1, 4);
}
protected:
const int DEFAULT_VIEW_ID = 0;
const int NON_DEFAULT_VIEW_ID = 1;
raw_ptr<Widget> widget_ = nullptr;
raw_ptr<Button> button_ = nullptr;
raw_ptr<Label> label_ = nullptr;
ScopedAXModeSetter ax_mode_setter_;
};
class ViewAXPlatformNodeDelegateTableTest
: public ViewAXPlatformNodeDelegateTest {
public:
void SetUp() override {
ViewAXPlatformNodeDelegateTest::SetUp();
std::vector<ui::TableColumn> columns;
columns.push_back(TestTableColumn(0, "Fruit"));
columns.push_back(TestTableColumn(1, "Color"));
columns.push_back(TestTableColumn(2, "Origin"));
columns.push_back(TestTableColumn(3, "Price"));
model_ = std::make_unique<TestTableModel>();
auto table =
std::make_unique<TableView>(model_.get(), columns, TEXT_ONLY, true);
table_ = table.get();
widget_->GetRootView()->AddChildView(
TableView::CreateScrollViewWithTable(std::move(table)));
}
ui::TableColumn TestTableColumn(int id, const std::string& title) {
ui::TableColumn column;
column.id = id;
column.title = base::ASCIIToUTF16(title.c_str());
column.sortable = true;
return column;
}
ViewAXPlatformNodeDelegate* table_accessibility() {
return view_accessibility(table_);
}
private:
std::unique_ptr<TestTableModel> model_;
raw_ptr<TableView> table_ = nullptr; // Owned by parent.
};
class ViewAXPlatformNodeDelegateMenuTest
: public ViewAXPlatformNodeDelegateTest {
public:
void SetUp() override {
ViewAXPlatformNodeDelegateTest::SetUp();
owner_ = std::make_unique<Widget>();
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
owner_->Init(std::move(params));
owner_->Show();
menu_delegate_ = std::make_unique<TestMenuDelegate>();
menu_ = new views::TestMenuItemView(menu_delegate_.get());
runner_ = std::make_unique<MenuRunner>(menu_, 0);
menu_->AppendMenuItemImpl(0, u"normal", ui::ImageModel(),
MenuItemView::Type::kNormal);
menu_->AppendMenuItemImpl(1, u"submenu", ui::ImageModel(),
MenuItemView::Type::kSubMenu);
menu_->AppendMenuItemImpl(2, u"actionable", ui::ImageModel(),
MenuItemView::Type::kActionableSubMenu);
menu_->AppendMenuItemImpl(3, u"checkbox", ui::ImageModel(),
MenuItemView::Type::kCheckbox);
menu_->AppendMenuItemImpl(4, u"radio", ui::ImageModel(),
MenuItemView::Type::kRadio);
menu_->AppendMenuItemImpl(5, u"separator", ui::ImageModel(),
MenuItemView::Type::kSeparator);
menu_->AppendMenuItemImpl(6, u"highlighted", ui::ImageModel(),
MenuItemView::Type::kHighlighted);
menu_->AppendMenuItemImpl(7, u"title", ui::ImageModel(),
MenuItemView::Type::kTitle);
submenu_ = menu_->GetSubmenu();
submenu_->GetMenuItemAt(3)->SetSelected(true);
}
void TearDown() override {
if (owner_)
owner_->CloseNow();
ViewAXPlatformNodeDelegateTest::TearDown();
}
void RunMenu() {
runner_.get()->RunMenuAt(owner_.get(), nullptr, gfx::Rect(),
MenuAnchorPosition::kTopLeft,
ui::MENU_SOURCE_NONE);
}
ViewAXPlatformNodeDelegate* submenu_accessibility() {
return view_accessibility(submenu_);
}
private:
// Owned by runner_.
raw_ptr<views::TestMenuItemView> menu_ = nullptr;
raw_ptr<SubmenuView> submenu_ = nullptr;
std::unique_ptr<TestMenuDelegate> menu_delegate_;
std::unique_ptr<MenuRunner> runner_;
UniqueWidgetPtr owner_;
};
TEST_F(ViewAXPlatformNodeDelegateTest, FocusBehaviorShouldAffectIgnoredState) {
EXPECT_EQ(ax::mojom::Role::kButton, button_accessibility()->GetRole());
EXPECT_FALSE(button_accessibility()->HasState(ax::mojom::State::kIgnored));
// Since the label is a subview of |button_|, and the button is keyboard
// focusable, the label is assumed to form part of the button and should be
// ignored.
EXPECT_EQ(ax::mojom::Role::kStaticText, label_accessibility()->GetRole());
EXPECT_TRUE(label_accessibility()->HasState(ax::mojom::State::kIgnored));
// This will happen for all potentially keyboard-focusable Views with
// non-keyboard-focusable children, so if we make the button unfocusable, the
// label will not be ignored any more.
button_->SetFocusBehavior(View::FocusBehavior::NEVER);
EXPECT_EQ(ax::mojom::Role::kButton, button_accessibility()->GetRole());
EXPECT_FALSE(button_accessibility()->HasState(ax::mojom::State::kIgnored));
EXPECT_EQ(ax::mojom::Role::kStaticText, label_accessibility()->GetRole());
EXPECT_FALSE(label_accessibility()->HasState(ax::mojom::State::kIgnored));
}
TEST_F(ViewAXPlatformNodeDelegateTest, BoundsShouldMatch) {
gfx::Rect bounds = gfx::ToEnclosingRect(
button_accessibility()->GetData().relative_bounds.bounds);
gfx::Rect screen_bounds =
button_accessibility()->GetUnclippedScreenBoundsRect();
EXPECT_EQ(button_->GetBoundsInScreen(), bounds);
EXPECT_EQ(screen_bounds, bounds);
}
TEST_F(ViewAXPlatformNodeDelegateTest, LabelIsChildOfButton) {
// Disable focus rings for this test: they introduce extra children that can
// be either before or after the label, which complicates correctness testing.
button_->SetInstallFocusRingOnFocus(false);
// Since the label is a subview of |button_|, and the button is keyboard
// focusable, the label is assumed to form part of the button and should be
// ignored, i.e. not visible in the accessibility tree that is available to
// platform APIs.
EXPECT_NE(View::FocusBehavior::NEVER, button_->GetFocusBehavior());
EXPECT_EQ(0u, button_accessibility()->GetChildCount());
EXPECT_EQ(ax::mojom::Role::kStaticText, label_accessibility()->GetRole());
// Modify the focus behavior to make the button unfocusable, and verify that
// the label is now a child of the button.
button_->SetFocusBehavior(View::FocusBehavior::NEVER);
EXPECT_EQ(1u, button_accessibility()->GetChildCount());
EXPECT_EQ(label_->GetNativeViewAccessible(),
button_accessibility()->ChildAtIndex(0));
EXPECT_EQ(button_->GetNativeViewAccessible(),
label_accessibility()->GetParent());
EXPECT_EQ(ax::mojom::Role::kStaticText, label_accessibility()->GetRole());
}
// Verify Views with invisible ancestors have ax::mojom::State::kInvisible.
TEST_F(ViewAXPlatformNodeDelegateTest, InvisibleViews) {
EXPECT_TRUE(widget_->IsVisible());
EXPECT_FALSE(button_accessibility()->HasState(ax::mojom::State::kInvisible));
EXPECT_FALSE(label_accessibility()->HasState(ax::mojom::State::kInvisible));
button_->SetVisible(false);
EXPECT_TRUE(button_accessibility()->HasState(ax::mojom::State::kInvisible));
EXPECT_TRUE(label_accessibility()->HasState(ax::mojom::State::kInvisible));
}
TEST_F(ViewAXPlatformNodeDelegateTest, SetFocus) {
// Make |button_| focusable, and focus/unfocus it via
// ViewAXPlatformNodeDelegate.
button_->SetFocusBehavior(View::FocusBehavior::ALWAYS);
EXPECT_EQ(nullptr, button_->GetFocusManager()->GetFocusedView());
EXPECT_EQ(nullptr, button_accessibility()->GetFocus());
EXPECT_TRUE(SetFocused(button_accessibility(), true));
EXPECT_EQ(button_, button_->GetFocusManager()->GetFocusedView());
EXPECT_EQ(button_->GetNativeViewAccessible(),
button_accessibility()->GetFocus());
EXPECT_TRUE(SetFocused(button_accessibility(), false));
EXPECT_EQ(nullptr, button_->GetFocusManager()->GetFocusedView());
EXPECT_EQ(nullptr, button_accessibility()->GetFocus());
// If the button is not focusable at all, or if it is disabled for
// accessibility, SetFocused() should return false.
button_->SetEnabled(false);
EXPECT_FALSE(SetFocused(button_accessibility(), true));
button_->SetEnabled(true);
button_accessibility()->OverrideIsEnabled(false);
EXPECT_FALSE(SetFocused(button_accessibility(), true));
EXPECT_FALSE(button_accessibility()->IsAccessibilityFocusable());
button_accessibility()->OverrideIsEnabled(true);
EXPECT_TRUE(button_accessibility()->IsAccessibilityFocusable());
}
TEST_F(ViewAXPlatformNodeDelegateTest, GetAuthorUniqueIdDefault) {
ASSERT_EQ(u"", label_accessibility()->GetAuthorUniqueId());
}
TEST_F(ViewAXPlatformNodeDelegateTest, GetAuthorUniqueIdNonDefault) {
ASSERT_EQ(u"view_1", button_accessibility()->GetAuthorUniqueId());
}
TEST_F(ViewAXPlatformNodeDelegateTest, OverrideNameAndDescription) {
// Initially the button has no name and no description.
EXPECT_EQ(button_accessibility()->GetName(), "");
EXPECT_EQ(button_accessibility()->GetNameFrom(), ax::mojom::NameFrom::kNone);
EXPECT_EQ(button_accessibility()->GetDescription(), "");
EXPECT_EQ(button_accessibility()->GetDescriptionFrom(),
ax::mojom::DescriptionFrom::kNone);
// Setting the name to the empty string without explicitly setting the
// source to reflect that should trigger a DCHECK in OverrideName.
EXPECT_DCHECK_DEATH_WITH(button_accessibility()->OverrideName(""),
"Check failed: name.empty\\(\\) == name_from == "
"ax::mojom::NameFrom::kAttributeExplicitlyEmpty");
// Setting the name to a non-empty string with a NameFrom of
// kAttributeExplicitlyEmpty should trigger a DCHECK in OverrideName.
EXPECT_DCHECK_DEATH_WITH(
button_accessibility()->OverrideName(
"foo", ax::mojom::NameFrom::kAttributeExplicitlyEmpty),
"Check failed: name.empty\\(\\) == name_from == "
"ax::mojom::NameFrom::kAttributeExplicitlyEmpty");
button_accessibility()->OverrideName(
"", ax::mojom::NameFrom::kAttributeExplicitlyEmpty);
EXPECT_EQ(button_accessibility()->GetName(), "");
EXPECT_EQ(button_accessibility()->GetNameFrom(),
ax::mojom::NameFrom::kAttributeExplicitlyEmpty);
// Setting the description to the empty string without explicitly setting
// the source to reflect that should trigger a DCHECK in OverrideDescription.
EXPECT_DCHECK_DEATH_WITH(
button_accessibility()->OverrideDescription(""),
"Check failed: description.empty\\(\\) == description_from == "
"ax::mojom::DescriptionFrom::kAttributeExplicitlyEmpty");
// Setting the description to a non-empty string with a DescriptionFrom of
// kAttributeExplicitlyEmpty should trigger a DCHECK in OverrideDescription.
EXPECT_DCHECK_DEATH_WITH(
button_accessibility()->OverrideDescription(
"foo", ax::mojom::DescriptionFrom::kAttributeExplicitlyEmpty),
"Check failed: description.empty\\(\\) == description_from == "
"ax::mojom::DescriptionFrom::kAttributeExplicitlyEmpty");
button_accessibility()->OverrideDescription(
"", ax::mojom::DescriptionFrom::kAttributeExplicitlyEmpty);
EXPECT_EQ(button_accessibility()->GetDescription(), "");
EXPECT_EQ(button_accessibility()->GetDescriptionFrom(),
ax::mojom::DescriptionFrom::kAttributeExplicitlyEmpty);
// Overriding the name and description without specifying the sources
// should set the sources to kAttribute and kAriaDescription respectively.
button_accessibility()->OverrideName("Button's Name");
EXPECT_EQ(button_accessibility()->GetName(), "Button's Name");
EXPECT_EQ(button_accessibility()->GetNameFrom(),
ax::mojom::NameFrom::kAttribute);
button_accessibility()->OverrideDescription("Button's description");
EXPECT_EQ(button_accessibility()->GetDescription(), "Button's description");
EXPECT_EQ(button_accessibility()->GetDescriptionFrom(),
ax::mojom::DescriptionFrom::kAriaDescription);
// Initially the label has no name and no description.
EXPECT_EQ(label_accessibility()->GetName(), "");
EXPECT_EQ(label_accessibility()->GetDescription(), "");
// Set the name and description of the label using other source types
// for greater test coverage (i.e. rather than those types being the
// most appropriate choice.)
label_accessibility()->OverrideName("Label's Name",
ax::mojom::NameFrom::kContents);
EXPECT_EQ(label_accessibility()->GetName(), "Label's Name");
EXPECT_EQ(label_accessibility()->GetNameFrom(),
ax::mojom::NameFrom::kContents);
label_accessibility()->OverrideDescription(
"Label's description", ax::mojom::DescriptionFrom::kTitle);
EXPECT_EQ(label_accessibility()->GetDescription(), "Label's description");
EXPECT_EQ(label_accessibility()->GetDescriptionFrom(),
ax::mojom::DescriptionFrom::kTitle);
// Set the label's View as the name source of the accessible button.
// This should cause the previously-set name to be replaced with the
// accessible name of the label.
button_accessibility()->OverrideLabelledBy(label_);
EXPECT_EQ(button_accessibility()->GetName(), "Label's Name");
EXPECT_EQ(button_accessibility()->GetNameFrom(),
ax::mojom::NameFrom::kRelatedElement);
// Setting the labelledby View to itself should trigger a DCHECK.
EXPECT_DCHECK_DEATH_WITH(button_accessibility()->OverrideLabelledBy(button_),
"Check failed: labelled_by_view != view_");
}
TEST_F(ViewAXPlatformNodeDelegateTest, IsOrderedSet) {
View::Views group_ids = SetUpExtraViews();
SetUpExtraViewsGroups(group_ids);
// Only last element has no group id.
EXPECT_TRUE(view_accessibility(group_ids[0])->IsOrderedSet());
EXPECT_TRUE(view_accessibility(group_ids[1])->IsOrderedSet());
EXPECT_TRUE(view_accessibility(group_ids[2])->IsOrderedSet());
EXPECT_TRUE(view_accessibility(group_ids[3])->IsOrderedSet());
EXPECT_FALSE(view_accessibility(group_ids[4])->IsOrderedSet());
EXPECT_TRUE(view_accessibility(group_ids[0])->IsOrderedSetItem());
EXPECT_TRUE(view_accessibility(group_ids[1])->IsOrderedSetItem());
EXPECT_TRUE(view_accessibility(group_ids[2])->IsOrderedSetItem());
EXPECT_TRUE(view_accessibility(group_ids[3])->IsOrderedSetItem());
EXPECT_FALSE(view_accessibility(group_ids[4])->IsOrderedSetItem());
View::Views overrides = SetUpExtraViews();
SetUpExtraViewsSetOverrides(overrides);
// Only overrides[3] has no override values for setSize/ posInSet.
EXPECT_TRUE(view_accessibility(overrides[0])->IsOrderedSet());
EXPECT_TRUE(view_accessibility(overrides[1])->IsOrderedSet());
EXPECT_TRUE(view_accessibility(overrides[2])->IsOrderedSet());
EXPECT_FALSE(view_accessibility(overrides[3])->IsOrderedSet());
EXPECT_TRUE(view_accessibility(overrides[4])->IsOrderedSet());
EXPECT_TRUE(view_accessibility(overrides[0])->IsOrderedSetItem());
EXPECT_TRUE(view_accessibility(overrides[1])->IsOrderedSetItem());
EXPECT_TRUE(view_accessibility(overrides[2])->IsOrderedSetItem());
EXPECT_FALSE(view_accessibility(overrides[3])->IsOrderedSetItem());
EXPECT_TRUE(view_accessibility(overrides[4])->IsOrderedSetItem());
}
TEST_F(ViewAXPlatformNodeDelegateTest, SetSizeAndPosition) {
// Test Views with group ids.
View::Views group_ids = SetUpExtraViews();
SetUpExtraViewsGroups(group_ids);
EXPECT_EQ(view_accessibility(group_ids[0])->GetSetSize(), 3);
EXPECT_EQ(view_accessibility(group_ids[0])->GetPosInSet(), 1);
EXPECT_EQ(view_accessibility(group_ids[1])->GetSetSize(), 3);
EXPECT_EQ(view_accessibility(group_ids[1])->GetPosInSet(), 2);
EXPECT_EQ(view_accessibility(group_ids[2])->GetSetSize(), 3);
EXPECT_EQ(view_accessibility(group_ids[2])->GetPosInSet(), 3);
EXPECT_EQ(view_accessibility(group_ids[3])->GetSetSize(), 1);
EXPECT_EQ(view_accessibility(group_ids[3])->GetPosInSet(), 1);
EXPECT_FALSE(view_accessibility(group_ids[4])->GetSetSize().has_value());
EXPECT_FALSE(view_accessibility(group_ids[4])->GetPosInSet().has_value());
// Check if a View is ignored, it is not counted in SetSize or PosInSet
group_ids[1]->GetViewAccessibility().OverrideIsIgnored(true);
group_ids[2]->GetViewAccessibility().OverrideIsIgnored(true);
EXPECT_EQ(view_accessibility(group_ids[0])->GetSetSize(), 1);
EXPECT_EQ(view_accessibility(group_ids[0])->GetPosInSet(), 1);
EXPECT_FALSE(view_accessibility(group_ids[1])->GetSetSize().has_value());
EXPECT_FALSE(view_accessibility(group_ids[1])->GetPosInSet().has_value());
EXPECT_FALSE(view_accessibility(group_ids[2])->GetSetSize().has_value());
EXPECT_FALSE(view_accessibility(group_ids[2])->GetPosInSet().has_value());
group_ids[1]->GetViewAccessibility().OverrideIsIgnored(false);
group_ids[2]->GetViewAccessibility().OverrideIsIgnored(false);
// Test Views with setSize/ posInSet override values set.
View::Views overrides = SetUpExtraViews();
SetUpExtraViewsSetOverrides(overrides);
EXPECT_EQ(view_accessibility(overrides[0])->GetSetSize(), 4);
EXPECT_EQ(view_accessibility(overrides[0])->GetPosInSet(), 4);
EXPECT_EQ(view_accessibility(overrides[1])->GetSetSize(), 4);
EXPECT_EQ(view_accessibility(overrides[1])->GetPosInSet(), 3);
EXPECT_EQ(view_accessibility(overrides[2])->GetSetSize(), 4);
EXPECT_EQ(view_accessibility(overrides[2])->GetPosInSet(), 2);
EXPECT_FALSE(view_accessibility(overrides[3])->GetSetSize().has_value());
EXPECT_FALSE(view_accessibility(overrides[3])->GetPosInSet().has_value());
EXPECT_EQ(view_accessibility(overrides[4])->GetSetSize(), 4);
EXPECT_EQ(view_accessibility(overrides[4])->GetPosInSet(), 1);
// Test Views with both group ids and setSize/ posInSet override values set.
// Make sure the override values take precedence when both are set.
// Add setSize/ posInSet overrides to the Views with group ids.
SetUpExtraViewsSetOverrides(group_ids);
EXPECT_EQ(view_accessibility(group_ids[0])->GetSetSize(), 4);
EXPECT_EQ(view_accessibility(group_ids[0])->GetPosInSet(), 4);
EXPECT_EQ(view_accessibility(group_ids[1])->GetSetSize(), 4);
EXPECT_EQ(view_accessibility(group_ids[1])->GetPosInSet(), 3);
EXPECT_EQ(view_accessibility(group_ids[2])->GetSetSize(), 4);
EXPECT_EQ(view_accessibility(group_ids[2])->GetPosInSet(), 2);
EXPECT_EQ(view_accessibility(group_ids[3])->GetSetSize(), 1);
EXPECT_EQ(view_accessibility(group_ids[3])->GetPosInSet(), 1);
EXPECT_EQ(view_accessibility(group_ids[4])->GetSetSize(), 4);
EXPECT_EQ(view_accessibility(group_ids[4])->GetPosInSet(), 1);
}
TEST_F(ViewAXPlatformNodeDelegateTest, TreeNavigation) {
// Adds one extra parent view with four child views to our widget. The parent
// view is added as the next sibling of the already present button view.
//
// Widget
// ++NonClientView
// ++NonClientFrameView
// ++Button
// ++++Label
// 0 = ++ParentView
// 1 = ++++ChildView1
// 2 = ++++ChildView2
// 3 = ++++ChildView3
// 4 = ++++ChildView4
View::Views extra_views = SetUpExtraViews();
ViewAXPlatformNodeDelegate* parent_view = view_accessibility(extra_views[0]);
ViewAXPlatformNodeDelegate* child_view_1 = view_accessibility(extra_views[1]);
ViewAXPlatformNodeDelegate* child_view_2 = view_accessibility(extra_views[2]);
ViewAXPlatformNodeDelegate* child_view_3 = view_accessibility(extra_views[3]);
ViewAXPlatformNodeDelegate* child_view_4 = view_accessibility(extra_views[4]);
EXPECT_EQ(view_accessibility(widget_->GetRootView())->GetNativeObject(),
parent_view->GetParent());
EXPECT_EQ(4u, parent_view->GetChildCount());
EXPECT_EQ(0u, button_accessibility()->GetIndexInParent());
EXPECT_EQ(1u, parent_view->GetIndexInParent());
EXPECT_EQ(child_view_1->GetNativeObject(), parent_view->ChildAtIndex(0));
EXPECT_EQ(child_view_2->GetNativeObject(), parent_view->ChildAtIndex(1));
EXPECT_EQ(child_view_3->GetNativeObject(), parent_view->ChildAtIndex(2));
EXPECT_EQ(child_view_4->GetNativeObject(), parent_view->ChildAtIndex(3));
EXPECT_EQ(nullptr, parent_view->GetNextSibling());
EXPECT_EQ(button_accessibility()->GetNativeObject(),
parent_view->GetPreviousSibling());
EXPECT_EQ(parent_view->GetNativeObject(), child_view_1->GetParent());
EXPECT_EQ(0u, child_view_1->GetChildCount());
EXPECT_EQ(0u, child_view_1->GetIndexInParent());
EXPECT_EQ(child_view_2->GetNativeObject(), child_view_1->GetNextSibling());
EXPECT_EQ(nullptr, child_view_1->GetPreviousSibling());
EXPECT_EQ(parent_view->GetNativeObject(), child_view_2->GetParent());
EXPECT_EQ(0u, child_view_2->GetChildCount());
EXPECT_EQ(1u, child_view_2->GetIndexInParent());
EXPECT_EQ(child_view_3->GetNativeObject(), child_view_2->GetNextSibling());
EXPECT_EQ(child_view_1->GetNativeObject(),
child_view_2->GetPreviousSibling());
EXPECT_EQ(parent_view->GetNativeObject(), child_view_3->GetParent());
EXPECT_EQ(0u, child_view_3->GetChildCount());
EXPECT_EQ(2u, child_view_3->GetIndexInParent());
EXPECT_EQ(child_view_4->GetNativeObject(), child_view_3->GetNextSibling());
EXPECT_EQ(child_view_2->GetNativeObject(),
child_view_3->GetPreviousSibling());
EXPECT_EQ(parent_view->GetNativeObject(), child_view_4->GetParent());
EXPECT_EQ(0u, child_view_4->GetChildCount());
EXPECT_EQ(3u, child_view_4->GetIndexInParent());
EXPECT_EQ(nullptr, child_view_4->GetNextSibling());
EXPECT_EQ(child_view_3->GetNativeObject(),
child_view_4->GetPreviousSibling());
}
TEST_F(ViewAXPlatformNodeDelegateTest, TreeNavigationWithLeafViews) {
// Adds one extra parent view with four child views to our widget. The parent
// view is added as the next sibling of the already present button view.
//
// Widget
// ++Button
// ++++Label
// 0 = ++ParentView
// 1 = ++++ChildView1
// 2 = ++++ChildView2
// 3 = ++++ChildView3
// 4 = ++++ChildView4
View::Views extra_views = SetUpExtraViews();
ViewAXPlatformNodeDelegate* contents_view =
view_accessibility(widget_->GetRootView());
ViewAXPlatformNodeDelegate* parent_view = view_accessibility(extra_views[0]);
ViewAXPlatformNodeDelegate* child_view_1 = view_accessibility(extra_views[1]);
ViewAXPlatformNodeDelegate* child_view_2 = view_accessibility(extra_views[2]);
ViewAXPlatformNodeDelegate* child_view_3 = view_accessibility(extra_views[3]);
ViewAXPlatformNodeDelegate* child_view_4 = view_accessibility(extra_views[4]);
// Mark the parent view and the second child view as leafs. This should hide
// all four children, not only the second child. It should not hide the parent
// view. In this context, "hide" means that these views will be ignored (be
// invisible) by platform accessibility APIs.
parent_view->OverrideIsLeaf(true);
child_view_2->OverrideIsLeaf(true);
EXPECT_EQ(2u, contents_view->GetChildCount());
EXPECT_EQ(contents_view->GetNativeObject(), parent_view->GetParent());
EXPECT_EQ(0u, parent_view->GetChildCount());
EXPECT_EQ(0u, button_accessibility()->GetIndexInParent());
EXPECT_EQ(1u, parent_view->GetIndexInParent());
EXPECT_FALSE(contents_view->IsIgnored());
EXPECT_FALSE(parent_view->IsIgnored());
EXPECT_TRUE(child_view_1->IsIgnored());
EXPECT_TRUE(child_view_2->IsIgnored());
EXPECT_TRUE(child_view_3->IsIgnored());
EXPECT_TRUE(child_view_4->IsIgnored());
EXPECT_FALSE(contents_view->IsLeaf());
EXPECT_TRUE(parent_view->IsLeaf());
EXPECT_FALSE(contents_view->IsChildOfLeaf());
EXPECT_FALSE(parent_view->IsChildOfLeaf());
#if !BUILDFLAG(USE_ATK)
// TODO(crbug.com/1100047): IsChildOfLeaf always returns false on Linux.
EXPECT_TRUE(child_view_1->IsChildOfLeaf());
EXPECT_TRUE(child_view_2->IsChildOfLeaf());
EXPECT_TRUE(child_view_3->IsChildOfLeaf());
EXPECT_TRUE(child_view_4->IsChildOfLeaf());
#endif // !BUILDFLAG(USE_ATK)
EXPECT_EQ(parent_view->GetNativeObject(), child_view_1->GetParent());
EXPECT_EQ(parent_view->GetNativeObject(), child_view_2->GetParent());
EXPECT_EQ(parent_view->GetNativeObject(), child_view_3->GetParent());
EXPECT_EQ(parent_view->GetNativeObject(), child_view_4->GetParent());
// Try unhiding the parent view's descendants. Nothing should be hidden any
// more. The second child has no descendants so marking it as a leaf should
// have no effect.
parent_view->OverrideIsLeaf(false);
EXPECT_EQ(2u, contents_view->GetChildCount());
EXPECT_EQ(contents_view->GetNativeObject(), parent_view->GetParent());
EXPECT_EQ(4u, parent_view->GetChildCount());
EXPECT_EQ(0u, button_accessibility()->GetIndexInParent());
EXPECT_EQ(1u, parent_view->GetIndexInParent());
EXPECT_FALSE(contents_view->IsIgnored());
EXPECT_FALSE(parent_view->IsIgnored());
EXPECT_FALSE(child_view_1->IsIgnored());
EXPECT_FALSE(child_view_2->IsIgnored());
EXPECT_FALSE(child_view_3->IsIgnored());
EXPECT_FALSE(child_view_4->IsIgnored());
EXPECT_FALSE(contents_view->IsLeaf());
EXPECT_FALSE(parent_view->IsLeaf());
EXPECT_TRUE(child_view_1->IsLeaf());
EXPECT_TRUE(child_view_2->IsLeaf());
EXPECT_TRUE(child_view_3->IsLeaf());
EXPECT_TRUE(child_view_4->IsLeaf());
EXPECT_FALSE(contents_view->IsChildOfLeaf());
EXPECT_FALSE(parent_view->IsChildOfLeaf());
EXPECT_FALSE(child_view_1->IsChildOfLeaf());
EXPECT_FALSE(child_view_2->IsChildOfLeaf());
EXPECT_FALSE(child_view_3->IsChildOfLeaf());
EXPECT_FALSE(child_view_4->IsChildOfLeaf());
EXPECT_EQ(parent_view->GetNativeObject(), child_view_1->GetParent());
EXPECT_EQ(parent_view->GetNativeObject(), child_view_2->GetParent());
EXPECT_EQ(parent_view->GetNativeObject(), child_view_3->GetParent());
EXPECT_EQ(parent_view->GetNativeObject(), child_view_4->GetParent());
EXPECT_EQ(child_view_1->GetNativeObject(), parent_view->ChildAtIndex(0));
EXPECT_EQ(child_view_2->GetNativeObject(), parent_view->ChildAtIndex(1));
EXPECT_EQ(child_view_3->GetNativeObject(), parent_view->ChildAtIndex(2));
EXPECT_EQ(child_view_4->GetNativeObject(), parent_view->ChildAtIndex(3));
}
TEST_F(ViewAXPlatformNodeDelegateTest, TreeNavigationWithIgnoredViews) {
// Adds one extra parent view with four child views to our widget. The parent
// view is added as the next sibling of the already present button view.
//
// Widget
// ++Button
// ++++Label
// 0 = ++ParentView
// 1 = ++++ChildView1
// 2 = ++++ChildView2
// 3 = ++++ChildView3
// 4 = ++++ChildView4
View::Views extra_views = SetUpExtraViews();
ViewAXPlatformNodeDelegate* contents_view =
view_accessibility(widget_->GetRootView());
ViewAXPlatformNodeDelegate* parent_view = view_accessibility(extra_views[0]);
ViewAXPlatformNodeDelegate* child_view_1 = view_accessibility(extra_views[1]);
ViewAXPlatformNodeDelegate* child_view_2 = view_accessibility(extra_views[2]);
ViewAXPlatformNodeDelegate* child_view_3 = view_accessibility(extra_views[3]);
ViewAXPlatformNodeDelegate* child_view_4 = view_accessibility(extra_views[4]);
// Mark the parent view and the second child view as ignored.
parent_view->OverrideIsIgnored(true);
child_view_2->OverrideIsIgnored(true);
EXPECT_EQ(contents_view->GetNativeObject(), parent_view->GetParent());
EXPECT_EQ(3u, parent_view->GetChildCount());
EXPECT_EQ(0u, button_accessibility()->GetIndexInParent());
EXPECT_FALSE(parent_view->GetIndexInParent().has_value());
EXPECT_EQ(child_view_1->GetNativeObject(), parent_view->ChildAtIndex(0));
EXPECT_EQ(child_view_3->GetNativeObject(), parent_view->ChildAtIndex(1));
EXPECT_EQ(child_view_4->GetNativeObject(), parent_view->ChildAtIndex(2));
EXPECT_EQ(button_accessibility()->GetNativeObject(),
contents_view->ChildAtIndex(0));
EXPECT_EQ(child_view_1->GetNativeObject(), contents_view->ChildAtIndex(1));
EXPECT_EQ(child_view_3->GetNativeObject(), contents_view->ChildAtIndex(2));
EXPECT_EQ(child_view_4->GetNativeObject(), contents_view->ChildAtIndex(3));
EXPECT_EQ(nullptr, parent_view->GetNextSibling());
EXPECT_EQ(nullptr, parent_view->GetPreviousSibling());
EXPECT_EQ(contents_view->GetNativeObject(), child_view_1->GetParent());
EXPECT_EQ(0u, child_view_1->GetChildCount());
EXPECT_EQ(1u, child_view_1->GetIndexInParent());
EXPECT_EQ(child_view_3->GetNativeObject(), child_view_1->GetNextSibling());
EXPECT_EQ(button_accessibility()->GetNativeObject(),
child_view_1->GetPreviousSibling());
EXPECT_EQ(contents_view->GetNativeObject(), child_view_2->GetParent());
EXPECT_EQ(0u, child_view_2->GetChildCount());
EXPECT_FALSE(child_view_2->GetIndexInParent().has_value());
EXPECT_EQ(nullptr, child_view_2->GetNextSibling());
EXPECT_EQ(nullptr, child_view_2->GetPreviousSibling());
EXPECT_EQ(contents_view->GetNativeObject(), child_view_3->GetParent());
EXPECT_EQ(0u, child_view_3->GetChildCount());
EXPECT_EQ(2u, child_view_3->GetIndexInParent());
EXPECT_EQ(child_view_4->GetNativeObject(), child_view_3->GetNextSibling());
EXPECT_EQ(child_view_1->GetNativeObject(),
child_view_3->GetPreviousSibling());
EXPECT_EQ(contents_view->GetNativeObject(), child_view_4->GetParent());
EXPECT_EQ(0u, child_view_4->GetChildCount());
EXPECT_EQ(3u, child_view_4->GetIndexInParent());
EXPECT_EQ(nullptr, child_view_4->GetNextSibling());
EXPECT_EQ(child_view_3->GetNativeObject(),
child_view_4->GetPreviousSibling());
}
TEST_F(ViewAXPlatformNodeDelegateTest, OverrideIsEnabled) {
// Initially, the button should be enabled.
EXPECT_TRUE(button_accessibility()->IsAccessibilityEnabled());
EXPECT_TRUE(button_accessibility()->IsAccessibilityFocusable());
button_->SetEnabled(false);
EXPECT_FALSE(button_accessibility()->IsAccessibilityEnabled());
EXPECT_FALSE(button_accessibility()->IsAccessibilityFocusable());
button_->SetEnabled(true);
EXPECT_TRUE(button_accessibility()->IsAccessibilityEnabled());
EXPECT_TRUE(button_accessibility()->IsAccessibilityFocusable());
// `ViewAccessibility::OverrideIsEnabled` should have priority over
// `View::SetEnabled`.
button_accessibility()->OverrideIsEnabled(false);
EXPECT_FALSE(button_accessibility()->IsAccessibilityEnabled());
EXPECT_FALSE(button_accessibility()->IsAccessibilityFocusable());
button_->SetEnabled(false);
EXPECT_FALSE(button_accessibility()->IsAccessibilityEnabled());
EXPECT_FALSE(button_accessibility()->IsAccessibilityFocusable());
button_accessibility()->OverrideIsEnabled(true);
EXPECT_TRUE(button_accessibility()->IsAccessibilityEnabled());
EXPECT_TRUE(button_accessibility()->IsAccessibilityFocusable());
// Initially, the label should be enabled. It should never be focusable
// because it is not an interactive control like the button.
EXPECT_TRUE(label_accessibility()->IsAccessibilityEnabled());
EXPECT_FALSE(label_accessibility()->IsAccessibilityFocusable());
label_->SetEnabled(false);
EXPECT_FALSE(label_accessibility()->IsAccessibilityEnabled());
EXPECT_FALSE(label_accessibility()->IsAccessibilityFocusable());
label_accessibility()->OverrideIsEnabled(true);
EXPECT_TRUE(label_accessibility()->IsAccessibilityEnabled());
EXPECT_FALSE(label_accessibility()->IsAccessibilityFocusable());
label_accessibility()->OverrideIsEnabled(false);
EXPECT_FALSE(label_accessibility()->IsAccessibilityEnabled());
EXPECT_FALSE(label_accessibility()->IsAccessibilityFocusable());
}
TEST_F(ViewAXPlatformNodeDelegateTest, OverrideHasPopup) {
View::Views view_ids = SetUpExtraViews();
view_ids[1]->GetViewAccessibility().OverrideHasPopup(
ax::mojom::HasPopup::kTrue);
view_ids[2]->GetViewAccessibility().OverrideHasPopup(
ax::mojom::HasPopup::kMenu);
ui::AXNodeData node_data_0;
view_ids[0]->GetViewAccessibility().GetAccessibleNodeData(&node_data_0);
EXPECT_EQ(node_data_0.GetHasPopup(), ax::mojom::HasPopup::kFalse);
ui::AXNodeData node_data_1;
view_ids[1]->GetViewAccessibility().GetAccessibleNodeData(&node_data_1);
EXPECT_EQ(node_data_1.GetHasPopup(), ax::mojom::HasPopup::kTrue);
ui::AXNodeData node_data_2;
view_ids[2]->GetViewAccessibility().GetAccessibleNodeData(&node_data_2);
EXPECT_EQ(node_data_2.GetHasPopup(), ax::mojom::HasPopup::kMenu);
}
TEST_F(ViewAXPlatformNodeDelegateTest, FocusOnMenuClose) {
// Set Focus on the button
button_->SetFocusBehavior(View::FocusBehavior::ALWAYS);
EXPECT_EQ(nullptr, button_->GetFocusManager()->GetFocusedView());
EXPECT_EQ(nullptr, button_accessibility()->GetFocus());
EXPECT_TRUE(SetFocused(button_accessibility(), true));
EXPECT_EQ(button_->GetNativeViewAccessible(),
button_accessibility()->GetFocus());
// Fire FocusAfterMenuClose event on the button.
base::RunLoop run_loop;
ui::AXPlatformNodeBase::SetOnNotifyEventCallbackForTesting(
ax::mojom::Event::kFocusAfterMenuClose, run_loop.QuitClosure());
button_accessibility()->FireFocusAfterMenuClose();
run_loop.Run();
EXPECT_EQ(button_->GetNativeViewAccessible(),
button_accessibility()->GetFocus());
}
TEST_F(ViewAXPlatformNodeDelegateTableTest, TableHasHeader) {
EXPECT_TRUE(table_accessibility()->TableHasColumnOrRowHeaderNodeForTesting());
EXPECT_EQ(size_t{4}, table_accessibility()->GetColHeaderNodeIds().size());
EXPECT_TRUE(table_accessibility()->GetColHeaderNodeIds(5).empty());
}
TEST_F(ViewAXPlatformNodeDelegateTableTest, TableHasCell) {
EXPECT_NE(absl::nullopt, table_accessibility()->GetCellId(0, 0));
EXPECT_NE(absl::nullopt, table_accessibility()->GetCellId(0, 3));
EXPECT_NE(absl::nullopt, table_accessibility()->GetCellId(9, 3));
EXPECT_DCHECK_DEATH(table_accessibility()->GetCellId(-1, 0));
EXPECT_DCHECK_DEATH(table_accessibility()->GetCellId(0, -1));
EXPECT_DCHECK_DEATH(table_accessibility()->GetCellId(10, 0));
EXPECT_DCHECK_DEATH(table_accessibility()->GetCellId(0, 4));
}
TEST_F(ViewAXPlatformNodeDelegateMenuTest, MenuTest) {
RunMenu();
ViewAXPlatformNodeDelegate* submenu = submenu_accessibility();
EXPECT_FALSE(submenu->HasState(ax::mojom::State::kFocusable));
EXPECT_EQ(submenu->GetChildCount(), 8u);
EXPECT_EQ(submenu->GetRole(), ax::mojom::Role::kMenu);
EXPECT_EQ(submenu->GetData().GetHasPopup(), ax::mojom::HasPopup::kMenu);
auto items = submenu->view()->children();
// MenuItemView::Type::kNormal
ViewAXPlatformNodeDelegate* normal_item = view_accessibility(items[0]);
EXPECT_TRUE(normal_item->HasState(ax::mojom::State::kFocusable));
EXPECT_TRUE(normal_item->GetData().IsSelectable());
EXPECT_FALSE(
normal_item->GetBoolAttribute(ax::mojom::BoolAttribute::kSelected));
EXPECT_FALSE(normal_item->IsInvisibleOrIgnored());
EXPECT_FALSE(normal_item->GetData().IsInvisibleOrIgnored());
EXPECT_EQ(normal_item->GetRole(), ax::mojom::Role::kMenuItem);
EXPECT_EQ(normal_item->GetData().GetHasPopup(), ax::mojom::HasPopup::kFalse);
EXPECT_EQ(normal_item->GetPosInSet(), 1);
EXPECT_EQ(normal_item->GetSetSize(), 7);
EXPECT_EQ(normal_item->GetChildCount(), 0u);
EXPECT_EQ(normal_item->GetIndexInParent(), 0u);
// MenuItemView::Type::kSubMenu
ViewAXPlatformNodeDelegate* submenu_item = view_accessibility(items[1]);
EXPECT_TRUE(submenu_item->HasState(ax::mojom::State::kFocusable));
EXPECT_TRUE(submenu_item->GetData().IsSelectable());
EXPECT_FALSE(
submenu_item->GetBoolAttribute(ax::mojom::BoolAttribute::kSelected));
EXPECT_FALSE(submenu_item->IsInvisibleOrIgnored());
EXPECT_FALSE(submenu_item->GetData().IsInvisibleOrIgnored());
EXPECT_EQ(submenu_item->GetRole(), ax::mojom::Role::kMenuItem);
EXPECT_EQ(submenu_item->GetData().GetHasPopup(), ax::mojom::HasPopup::kMenu);
EXPECT_EQ(submenu_item->GetPosInSet(), 2);
EXPECT_EQ(submenu_item->GetSetSize(), 7);
#if BUILDFLAG(IS_MAC)
// A virtual child with role menu is exposed so that VoiceOver treats a
// MenuItemView of type kSubMenu as a submenu rather than an item.
EXPECT_EQ(submenu_item->GetChildCount(), 1u);
#else
EXPECT_EQ(submenu_item->GetChildCount(), 0u);
#endif // BUILDFLAG(IS_MAC)
EXPECT_EQ(submenu_item->GetIndexInParent(), 1u);
// MenuItemView::Type::kActionableSubMenu
ViewAXPlatformNodeDelegate* actionable_submenu_item =
view_accessibility(items[2]);
EXPECT_TRUE(actionable_submenu_item->HasState(ax::mojom::State::kFocusable));
EXPECT_TRUE(actionable_submenu_item->GetData().IsSelectable());
EXPECT_FALSE(actionable_submenu_item->GetBoolAttribute(
ax::mojom::BoolAttribute::kSelected));
EXPECT_FALSE(actionable_submenu_item->IsInvisibleOrIgnored());
EXPECT_FALSE(actionable_submenu_item->GetData().IsInvisibleOrIgnored());
EXPECT_EQ(actionable_submenu_item->GetRole(), ax::mojom::Role::kMenuItem);
EXPECT_EQ(actionable_submenu_item->GetData().GetHasPopup(),
ax::mojom::HasPopup::kMenu);
EXPECT_EQ(actionable_submenu_item->GetPosInSet(), 3);
EXPECT_EQ(actionable_submenu_item->GetSetSize(), 7);
#if BUILDFLAG(IS_MAC)
// A virtual child with role menu is exposed so that VoiceOver treats a
// MenuItemView of type kActionableSubMenu as a submenu rather than an item.
EXPECT_EQ(actionable_submenu_item->GetChildCount(), 1u);
#else
EXPECT_EQ(actionable_submenu_item->GetChildCount(), 0u);
#endif // BUILDFLAG(IS_MAC)
EXPECT_EQ(actionable_submenu_item->GetIndexInParent(), 2u);
// MenuItemView::Type::kCheckbox
ViewAXPlatformNodeDelegate* checkbox_item = view_accessibility(items[3]);
EXPECT_TRUE(checkbox_item->HasState(ax::mojom::State::kFocusable));
EXPECT_TRUE(checkbox_item->GetData().IsSelectable());
EXPECT_TRUE(
checkbox_item->GetBoolAttribute(ax::mojom::BoolAttribute::kSelected));
EXPECT_FALSE(checkbox_item->IsInvisibleOrIgnored());
EXPECT_FALSE(checkbox_item->GetData().IsInvisibleOrIgnored());
EXPECT_EQ(checkbox_item->GetRole(), ax::mojom::Role::kMenuItemCheckBox);
EXPECT_EQ(checkbox_item->GetData().GetHasPopup(),
ax::mojom::HasPopup::kFalse);
EXPECT_EQ(checkbox_item->GetPosInSet(), 4);
EXPECT_EQ(checkbox_item->GetSetSize(), 7);
EXPECT_EQ(checkbox_item->GetChildCount(), 0u);
EXPECT_EQ(checkbox_item->GetIndexInParent(), 3u);
// MenuItemView::Type::kRadio
ViewAXPlatformNodeDelegate* radio_item = view_accessibility(items[4]);
EXPECT_TRUE(radio_item->HasState(ax::mojom::State::kFocusable));
EXPECT_TRUE(radio_item->GetData().IsSelectable());
EXPECT_FALSE(
radio_item->GetBoolAttribute(ax::mojom::BoolAttribute::kSelected));
EXPECT_FALSE(radio_item->IsInvisibleOrIgnored());
EXPECT_FALSE(radio_item->GetData().IsInvisibleOrIgnored());
EXPECT_EQ(radio_item->GetRole(), ax::mojom::Role::kMenuItemRadio);
EXPECT_EQ(radio_item->GetData().GetHasPopup(), ax::mojom::HasPopup::kFalse);
EXPECT_EQ(radio_item->GetPosInSet(), 5);
EXPECT_EQ(radio_item->GetSetSize(), 7);
EXPECT_EQ(radio_item->GetChildCount(), 0u);
EXPECT_EQ(radio_item->GetIndexInParent(), 4u);
// MenuItemView::Type::kSeparator
ViewAXPlatformNodeDelegate* separator_item = view_accessibility(items[5]);
EXPECT_FALSE(separator_item->HasState(ax::mojom::State::kFocusable));
EXPECT_FALSE(separator_item->GetData().IsSelectable());
EXPECT_FALSE(
separator_item->GetBoolAttribute(ax::mojom::BoolAttribute::kSelected));
EXPECT_FALSE(separator_item->IsInvisibleOrIgnored());
EXPECT_FALSE(separator_item->GetData().IsInvisibleOrIgnored());
EXPECT_EQ(separator_item->GetRole(), ax::mojom::Role::kSplitter);
EXPECT_EQ(separator_item->GetData().GetHasPopup(),
ax::mojom::HasPopup::kFalse);
EXPECT_FALSE(
separator_item->HasIntAttribute(ax::mojom::IntAttribute::kPosInSet));
EXPECT_FALSE(
separator_item->HasIntAttribute(ax::mojom::IntAttribute::kSetSize));
EXPECT_EQ(separator_item->GetChildCount(), 0u);
EXPECT_EQ(separator_item->GetIndexInParent(), 5u);
// MenuItemView::Type::kHighlighted
ViewAXPlatformNodeDelegate* highlighted_item = view_accessibility(items[6]);
EXPECT_TRUE(highlighted_item->HasState(ax::mojom::State::kFocusable));
EXPECT_TRUE(highlighted_item->GetData().IsSelectable());
EXPECT_FALSE(
highlighted_item->GetBoolAttribute(ax::mojom::BoolAttribute::kSelected));
EXPECT_FALSE(highlighted_item->IsInvisibleOrIgnored());
EXPECT_FALSE(highlighted_item->GetData().IsInvisibleOrIgnored());
EXPECT_EQ(highlighted_item->GetRole(), ax::mojom::Role::kMenuItem);
EXPECT_EQ(highlighted_item->GetData().GetHasPopup(),
ax::mojom::HasPopup::kFalse);
EXPECT_EQ(highlighted_item->GetPosInSet(), 6);
EXPECT_EQ(highlighted_item->GetSetSize(), 7);
EXPECT_EQ(highlighted_item->GetChildCount(), 0u);
EXPECT_EQ(highlighted_item->GetIndexInParent(), 6u);
// MenuItemView::Type::kTitle
ViewAXPlatformNodeDelegate* title_item = view_accessibility(items[7]);
EXPECT_TRUE(title_item->HasState(ax::mojom::State::kFocusable));
EXPECT_TRUE(title_item->GetData().IsSelectable());
EXPECT_FALSE(
title_item->GetBoolAttribute(ax::mojom::BoolAttribute::kSelected));
EXPECT_FALSE(title_item->IsInvisibleOrIgnored());
EXPECT_FALSE(title_item->GetData().IsInvisibleOrIgnored());
EXPECT_EQ(title_item->GetRole(), ax::mojom::Role::kMenuItem);
EXPECT_EQ(title_item->GetData().GetHasPopup(), ax::mojom::HasPopup::kFalse);
EXPECT_EQ(title_item->GetPosInSet(), 7);
EXPECT_EQ(title_item->GetSetSize(), 7);
EXPECT_EQ(title_item->GetChildCount(), 0u);
EXPECT_EQ(title_item->GetIndexInParent(), 7u);
}
#if defined(USE_AURA)
class DerivedTestView : public View {
public:
DerivedTestView() = default;
~DerivedTestView() override = default;
void OnBlur() override { SetVisible(false); }
};
using AXViewTest = ViewsTestBase;
// Check if the destruction of the widget ends successfully if |view|'s
// visibility changed during destruction.
TEST_F(AXViewTest, LayoutCalledInvalidateRootView) {
// TODO(jamescook): Construct a real AutomationManagerAura rather than using
// this observer to simulate it.
AXAuraObjCache cache;
TestAXEventObserver observer(&cache);
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
widget->Init(std::move(params));
widget->Show();
View* root = widget->GetRootView();
DerivedTestView* parent = new DerivedTestView();
DerivedTestView* child = new DerivedTestView();
root->AddChildView(parent);
parent->AddChildView(child);
child->SetFocusBehavior(DerivedTestView::FocusBehavior::ALWAYS);
parent->SetFocusBehavior(DerivedTestView::FocusBehavior::ALWAYS);
root->SetFocusBehavior(DerivedTestView::FocusBehavior::ALWAYS);
parent->RequestFocus();
// During the destruction of parent, OnBlur will be called and change the
// visibility to false.
parent->SetVisible(true);
cache.GetOrCreate(widget.get());
}
#endif
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/accessibility/view_ax_platform_node_delegate_unittest.cc | C++ | unknown | 48,807 |