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 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/widget/desktop_aura/desktop_drag_drop_client_ozone.h"
#include <memory>
#include <utility>
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/memory/scoped_refptr.h"
#include "base/notreached.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/single_thread_task_runner.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "ui/aura/client/drag_drop_delegate.h"
#include "ui/aura/window.h"
#include "ui/aura/window_tree_host.h"
#include "ui/base/cursor/platform_cursor.h"
#include "ui/base/data_transfer_policy/data_transfer_endpoint.h"
#include "ui/base/data_transfer_policy/data_transfer_policy_controller.h"
#include "ui/base/dragdrop/drag_drop_types.h"
#include "ui/base/dragdrop/mojom/drag_drop_types.mojom.h"
#include "ui/base/dragdrop/os_exchange_data.h"
#include "ui/platform_window/platform_window.h"
#include "ui/platform_window/wm/wm_drag_handler.h"
#include "ui/platform_window/wm/wm_drop_handler.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/views_delegate.h"
#include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h"
#include "ui/views/widget/desktop_aura/desktop_window_tree_host_platform.h"
namespace views {
namespace {
using ::ui::mojom::DragEventSource;
using ::ui::mojom::DragOperation;
// Platforms have different approaches to handling window coordinates. For
// instance, Wayland doesn't use window origin (it is always zero) and treats
// coordinates of pointer events as local ones (always within the window), but
// X11 1) uses the origin and may adjust it so that a window gets non-zero
// origin, see X11Window::OnConfigureEvent(), and 2) treats mouse coordinates as
// global ones, so that the event may be considered being 'outside the window'
// and discarded, which will make some tests in this suite failing.
//
// To ensure the drag to be always started within the drag widget, we choose
// size of the drag widget and location so that the location stays within the
// widget, even if the platform adjusts its position.
//
// See crbug.com/1119787
constexpr gfx::Rect kDragWidgetBounds{200, 200};
constexpr gfx::PointF kStartDragLocation{100, 100};
class FakePlatformWindow : public ui::PlatformWindow, public ui::WmDragHandler {
public:
FakePlatformWindow() { SetWmDragHandler(this, this); }
FakePlatformWindow(const FakePlatformWindow&) = delete;
FakePlatformWindow& operator=(const FakePlatformWindow&) = delete;
~FakePlatformWindow() override = default;
void set_modifiers(int modifiers) { modifiers_ = modifiers; }
// ui::PlatformWindow
void Show(bool inactive) override {}
void Hide() override {}
void Close() override {}
bool IsVisible() const override { return true; }
void PrepareForShutdown() override {}
void SetBoundsInPixels(const gfx::Rect& bounds) override {}
gfx::Rect GetBoundsInPixels() const override { return gfx::Rect(); }
void SetBoundsInDIP(const gfx::Rect& bounds) override {}
gfx::Rect GetBoundsInDIP() const override { return gfx::Rect(); }
void SetTitle(const std::u16string& title) override {}
void SetCapture() override {}
void ReleaseCapture() override {}
bool HasCapture() const override { return false; }
void SetFullscreen(bool fullscreen, int64_t target_display_id) override {}
void Maximize() override {}
void Minimize() override {}
void Restore() override {}
ui::PlatformWindowState GetPlatformWindowState() const override {
return ui::PlatformWindowState::kNormal;
}
void Activate() override {}
void Deactivate() override {}
void SetCursor(scoped_refptr<ui::PlatformCursor> cursor) override {}
void MoveCursorTo(const gfx::Point& location) override {}
void ConfineCursorToBounds(const gfx::Rect& bounds) override {}
void SetRestoredBoundsInDIP(const gfx::Rect& bounds) override {}
gfx::Rect GetRestoredBoundsInDIP() const override { return gfx::Rect(); }
void SetUseNativeFrame(bool use_native_frame) override {}
bool ShouldUseNativeFrame() const override { return false; }
void SetWindowIcons(const gfx::ImageSkia& window_icon,
const gfx::ImageSkia& app_icon) override {}
void SizeConstraintsChanged() override {}
// ui::WmDragHandler
bool StartDrag(const OSExchangeData& data,
int operation,
DragEventSource source,
gfx::NativeCursor cursor,
bool can_grab_pointer,
WmDragHandler::DragFinishedCallback callback,
WmDragHandler::LocationDelegate* delegate) override {
drag_finished_callback_ = std::move(callback);
source_data_ = std::make_unique<OSExchangeData>(data.provider().Clone());
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(&FakePlatformWindow::ProcessDrag, base::Unretained(this),
std::move(source_data_), operation));
base::RunLoop run_loop;
drag_loop_quit_closure_ = run_loop.QuitClosure();
run_loop.Run();
return true;
}
void CancelDrag() override { drag_loop_quit_closure_.Run(); }
void UpdateDragImage(const gfx::ImageSkia& image,
const gfx::Vector2d& offset) override {}
void OnDragEnter(const gfx::PointF& point,
std::unique_ptr<OSExchangeData> data,
int operation) {
ui::WmDropHandler* drop_handler = ui::GetWmDropHandler(*this);
if (!drop_handler)
return;
drop_handler->OnDragEnter(point, std::move(data), operation, modifiers_);
}
int OnDragMotion(const gfx::PointF& point, int operation) {
ui::WmDropHandler* drop_handler = ui::GetWmDropHandler(*this);
if (!drop_handler)
return 0;
return drop_handler->OnDragMotion(point, operation, modifiers_);
}
void OnDragDrop(std::unique_ptr<OSExchangeData> data) {
ui::WmDropHandler* drop_handler = ui::GetWmDropHandler(*this);
if (!drop_handler)
return;
drop_handler->OnDragDrop(std::move(data), modifiers_);
}
void OnDragLeave() {
ui::WmDropHandler* drop_handler = ui::GetWmDropHandler(*this);
if (!drop_handler)
return;
drop_handler->OnDragLeave();
}
void CloseDrag(DragOperation operation) {
std::move(drag_finished_callback_).Run(operation);
drag_loop_quit_closure_.Run();
}
void ProcessDrag(std::unique_ptr<OSExchangeData> data, int operation) {
OnDragEnter(kStartDragLocation, std::move(data), operation);
int updated_operation = OnDragMotion(kStartDragLocation, operation);
OnDragDrop(nullptr);
OnDragLeave();
CloseDrag(ui::PreferredDragOperation(updated_operation));
}
private:
WmDragHandler::DragFinishedCallback drag_finished_callback_;
std::unique_ptr<ui::OSExchangeData> source_data_;
base::RepeatingClosure drag_loop_quit_closure_;
int modifiers_ = 0;
};
// DragDropDelegate which counts the number of each type of drag-drop event.
class FakeDragDropDelegate : public aura::client::DragDropDelegate {
public:
FakeDragDropDelegate() = default;
FakeDragDropDelegate(const FakeDragDropDelegate&) = delete;
FakeDragDropDelegate& operator=(const FakeDragDropDelegate&) = delete;
~FakeDragDropDelegate() override = default;
int num_enters() const { return num_enters_; }
int num_updates() const { return num_updates_; }
int num_exits() const { return num_exits_; }
int num_drops() const { return num_drops_; }
int last_event_flags() const { return last_event_flags_; }
ui::OSExchangeData* received_data() const { return received_data_.get(); }
void SetOperation(DragOperation operation) {
destination_operation_ = operation;
}
private:
// aura::client::DragDropDelegate:
void OnDragEntered(const ui::DropTargetEvent& event) override {
++num_enters_;
last_event_flags_ = event.flags();
}
aura::client::DragUpdateInfo OnDragUpdated(
const ui::DropTargetEvent& event) override {
++num_updates_;
last_event_flags_ = event.flags();
return aura::client::DragUpdateInfo(
static_cast<int>(destination_operation_),
ui::DataTransferEndpoint(ui::EndpointType::kDefault));
}
void OnDragExited() override { ++num_exits_; }
DropCallback GetDropCallback(const ui::DropTargetEvent& event) override {
last_event_flags_ = event.flags();
return base::BindOnce(&FakeDragDropDelegate::PerformDrop,
base::Unretained(this));
}
void PerformDrop(std::unique_ptr<ui::OSExchangeData> data,
ui::mojom::DragOperation& output_drag_op,
std::unique_ptr<ui::LayerTreeOwner> drag_image_layer_owner) {
++num_drops_;
received_data_ = std::move(data);
output_drag_op = destination_operation_;
}
int num_enters_ = 0;
int num_updates_ = 0;
int num_exits_ = 0;
int num_drops_ = 0;
std::unique_ptr<ui::OSExchangeData> received_data_;
DragOperation destination_operation_;
int last_event_flags_ = ui::EF_NONE;
};
} // namespace
class DesktopDragDropClientOzoneTest : public ViewsTestBase {
public:
DesktopDragDropClientOzoneTest() = default;
DesktopDragDropClientOzoneTest(const DesktopDragDropClientOzoneTest&) =
delete;
DesktopDragDropClientOzoneTest& operator=(
const DesktopDragDropClientOzoneTest&) = delete;
~DesktopDragDropClientOzoneTest() override = default;
void SetModifiers(int modifiers) {
DCHECK(platform_window_);
platform_window_->set_modifiers(modifiers);
}
DragOperation StartDragAndDrop(int allowed_operations) {
auto data = std::make_unique<ui::OSExchangeData>();
data->SetString(u"Test");
SkBitmap drag_bitmap;
drag_bitmap.allocN32Pixels(10, 10);
drag_bitmap.eraseARGB(0xFF, 0, 0, 0);
gfx::ImageSkia drag_image(gfx::ImageSkia::CreateFrom1xBitmap(drag_bitmap));
data->provider().SetDragImage(drag_image, gfx::Vector2d());
return client_->StartDragAndDrop(
std::move(data), widget_->GetNativeWindow()->GetRootWindow(),
widget_->GetNativeWindow(), gfx::Point(), allowed_operations,
ui::mojom::DragEventSource::kMouse);
}
// ViewsTestBase:
void SetUp() override {
set_native_widget_type(NativeWidgetType::kDesktop);
ViewsTestBase::SetUp();
// Create widget to initiate the drags.
widget_ = std::make_unique<Widget>();
Widget::InitParams params(Widget::InitParams::TYPE_WINDOW);
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.bounds = kDragWidgetBounds;
widget_->Init(std::move(params));
widget_->Show();
// Creates FakeDragDropDelegate and set it for |window|.
aura::Window* window = widget_->GetNativeWindow();
dragdrop_delegate_ = std::make_unique<FakeDragDropDelegate>();
aura::client::SetDragDropDelegate(window, dragdrop_delegate_.get());
platform_window_ = std::make_unique<FakePlatformWindow>();
ui::WmDragHandler* drag_handler = ui::GetWmDragHandler(*(platform_window_));
// Creates DesktopDragDropClientOzone with |window| and |drag_handler|.
client_ =
std::make_unique<DesktopDragDropClientOzone>(window, drag_handler);
SetWmDropHandler(platform_window_.get(), client_.get());
}
void TearDown() override {
client_.reset();
platform_window_.reset();
widget_.reset();
ViewsTestBase::TearDown();
}
protected:
std::unique_ptr<FakeDragDropDelegate> dragdrop_delegate_;
std::unique_ptr<FakePlatformWindow> platform_window_;
private:
std::unique_ptr<DesktopDragDropClientOzone> client_;
// The widget used to initiate drags.
std::unique_ptr<Widget> widget_;
};
TEST_F(DesktopDragDropClientOzoneTest, StartDrag) {
// Set the operation which the destination can accept.
dragdrop_delegate_->SetOperation(DragOperation::kCopy);
// Start Drag and Drop with the operations suggested.
DragOperation operation = StartDragAndDrop(ui::DragDropTypes::DRAG_COPY |
ui::DragDropTypes::DRAG_MOVE);
// The |operation| decided through negotiation should be 'DRAG_COPY'.
EXPECT_EQ(DragOperation::kCopy, operation);
EXPECT_EQ(1, dragdrop_delegate_->num_enters());
EXPECT_EQ(1, dragdrop_delegate_->num_updates());
EXPECT_EQ(1, dragdrop_delegate_->num_drops());
EXPECT_EQ(0, dragdrop_delegate_->num_exits());
EXPECT_EQ(ui::EF_NONE, dragdrop_delegate_->last_event_flags());
}
TEST_F(DesktopDragDropClientOzoneTest, StartDragCtrlPressed) {
SetModifiers(ui::EF_CONTROL_DOWN);
// Set the operation which the destination can accept.
dragdrop_delegate_->SetOperation(DragOperation::kCopy);
// Start Drag and Drop with the operations suggested.
DragOperation operation = StartDragAndDrop(ui::DragDropTypes::DRAG_COPY |
ui::DragDropTypes::DRAG_MOVE);
// The |operation| decided through negotiation should be 'DRAG_COPY'.
EXPECT_EQ(DragOperation::kCopy, operation);
EXPECT_EQ(1, dragdrop_delegate_->num_enters());
EXPECT_EQ(1, dragdrop_delegate_->num_updates());
EXPECT_EQ(1, dragdrop_delegate_->num_drops());
EXPECT_EQ(0, dragdrop_delegate_->num_exits());
EXPECT_EQ(ui::EF_CONTROL_DOWN, dragdrop_delegate_->last_event_flags());
}
TEST_F(DesktopDragDropClientOzoneTest, ReceiveDrag) {
// Set the operation which the destination can accept.
auto operation = DragOperation::kMove;
dragdrop_delegate_->SetOperation(operation);
// Set the data which will be delivered.
const std::u16string sample_data = u"ReceiveDrag";
std::unique_ptr<ui::OSExchangeData> data =
std::make_unique<ui::OSExchangeData>();
data->SetString(sample_data);
// Simulate that the drag enter/motion/drop/leave events happen with the
// |suggested_operation|.
int suggested_operation =
ui::DragDropTypes::DRAG_COPY | ui::DragDropTypes::DRAG_MOVE;
platform_window_->OnDragEnter(kStartDragLocation, std::move(data),
suggested_operation);
int updated_operation =
platform_window_->OnDragMotion(kStartDragLocation, suggested_operation);
platform_window_->OnDragDrop(nullptr);
platform_window_->OnDragLeave();
// The |updated_operation| decided through negotiation should be
// 'ui::DragDropTypes::DRAG_MOVE'.
EXPECT_EQ(static_cast<int>(operation), updated_operation);
std::u16string string_data;
dragdrop_delegate_->received_data()->GetString(&string_data);
EXPECT_EQ(sample_data, string_data);
EXPECT_EQ(1, dragdrop_delegate_->num_enters());
EXPECT_EQ(1, dragdrop_delegate_->num_updates());
EXPECT_EQ(1, dragdrop_delegate_->num_drops());
EXPECT_EQ(0, dragdrop_delegate_->num_exits());
}
TEST_F(DesktopDragDropClientOzoneTest, TargetDestroyedDuringDrag) {
const int suggested_operation =
ui::DragDropTypes::DRAG_COPY | ui::DragDropTypes::DRAG_MOVE;
// Set the operation which the destination can accept.
dragdrop_delegate_->SetOperation(DragOperation::kMove);
// Set the data which will be delivered.
const std::u16string sample_data = u"ReceiveDrag";
std::unique_ptr<ui::OSExchangeData> data =
std::make_unique<ui::OSExchangeData>();
data->SetString(sample_data);
// Simulate that the drag enter/motion/leave events happen with the
// |suggested_operation| in the main window.
platform_window_->OnDragEnter(kStartDragLocation, std::move(data),
suggested_operation);
platform_window_->OnDragMotion(kStartDragLocation, suggested_operation);
platform_window_->OnDragLeave();
// Create another window with its own DnD facility and simulate that the drag
// enters it and then the window is destroyed.
auto another_widget = std::make_unique<Widget>();
Widget::InitParams params(Widget::InitParams::TYPE_WINDOW);
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.bounds = gfx::Rect(100, 100);
another_widget->Init(std::move(params));
another_widget->Show();
aura::Window* another_window = another_widget->GetNativeWindow();
auto another_dragdrop_delegate = std::make_unique<FakeDragDropDelegate>();
aura::client::SetDragDropDelegate(another_window,
another_dragdrop_delegate.get());
another_dragdrop_delegate->SetOperation(DragOperation::kCopy);
auto another_platform_window = std::make_unique<FakePlatformWindow>();
ui::WmDragHandler* drag_handler =
ui::GetWmDragHandler(*(another_platform_window));
auto another_client = std::make_unique<DesktopDragDropClientOzone>(
another_window, drag_handler);
SetWmDropHandler(another_platform_window.get(), another_client.get());
std::unique_ptr<ui::OSExchangeData> another_data =
std::make_unique<ui::OSExchangeData>();
another_data->SetString(sample_data);
another_platform_window->OnDragEnter(gfx::PointF(), std::move(another_data),
suggested_operation);
another_platform_window->OnDragMotion(gfx::PointF(), suggested_operation);
another_widget->CloseWithReason(Widget::ClosedReason::kUnspecified);
another_widget.reset();
// The main window should have the typical record of a drag started and left.
EXPECT_EQ(1, dragdrop_delegate_->num_enters());
EXPECT_EQ(1, dragdrop_delegate_->num_updates());
EXPECT_EQ(0, dragdrop_delegate_->num_drops());
EXPECT_EQ(1, dragdrop_delegate_->num_exits());
// As the target window has closed and we have never provided another one,
// the number of exits should be zero despite that the platform window has
// notified the client about leaving the drag.
EXPECT_EQ(1, another_dragdrop_delegate->num_enters());
EXPECT_EQ(1, another_dragdrop_delegate->num_updates());
EXPECT_EQ(0, another_dragdrop_delegate->num_drops());
EXPECT_EQ(0, another_dragdrop_delegate->num_exits());
}
// crbug.com/1151836 was null dereference during drag and drop.
//
// A possible reason was invalid sequence of events, so here we just drop data
// without any notifications that should come before (like drag enter or drag
// motion). Before this change, that would hit some DCHECKS in the debug build
// or cause crash in the release one, now it is handled properly. Methods of
// FakeDragDropDelegate ensure that data in the event is always valid.
//
// The error message rendered in the console when this test is running is the
// expected and valid side effect.
//
// See more information in the bug.
TEST_F(DesktopDragDropClientOzoneTest, Bug1151836) {
platform_window_->OnDragDrop(nullptr);
}
namespace {
class MockDataTransferPolicyController
: public ui::DataTransferPolicyController {
public:
MOCK_METHOD3(IsClipboardReadAllowed,
bool(const ui::DataTransferEndpoint* const data_src,
const ui::DataTransferEndpoint* const data_dst,
const absl::optional<size_t> size));
MOCK_METHOD5(PasteIfAllowed,
void(const ui::DataTransferEndpoint* const data_src,
const ui::DataTransferEndpoint* const data_dst,
const absl::optional<size_t> size,
content::RenderFrameHost* rfh,
base::OnceCallback<void(bool)> callback));
MOCK_METHOD3(DropIfAllowed,
void(const ui::OSExchangeData* drag_data,
const ui::DataTransferEndpoint* data_dst,
base::OnceClosure drop_cb));
};
} // namespace
TEST_F(DesktopDragDropClientOzoneTest, DataLeakPreventionAllowDrop) {
MockDataTransferPolicyController dtp_controller;
// Data Leak Prevention stack allows the drop.
EXPECT_CALL(dtp_controller, DropIfAllowed(testing::_, testing::_, testing::_))
.WillOnce([&](const ui::OSExchangeData* drag_data,
const ui::DataTransferEndpoint* data_dst,
base::OnceClosure drop_cb) { std::move(drop_cb).Run(); });
// Set the operation which the destination can accept.
dragdrop_delegate_->SetOperation(DragOperation::kCopy);
// Start Drag and Drop with the operations suggested.
DragOperation operation = StartDragAndDrop(ui::DragDropTypes::DRAG_COPY |
ui::DragDropTypes::DRAG_MOVE);
// The |operation| decided through negotiation should be 'DRAG_COPY'.
EXPECT_EQ(DragOperation::kCopy, operation);
std::u16string string_data;
dragdrop_delegate_->received_data()->GetString(&string_data);
EXPECT_EQ(u"Test", string_data);
EXPECT_EQ(1, dragdrop_delegate_->num_enters());
EXPECT_EQ(1, dragdrop_delegate_->num_updates());
EXPECT_EQ(1, dragdrop_delegate_->num_drops());
EXPECT_EQ(0, dragdrop_delegate_->num_exits());
}
TEST_F(DesktopDragDropClientOzoneTest, DataLeakPreventionBlockDrop) {
MockDataTransferPolicyController dtp_controller;
// Data Leak Prevention stack blocks the drop.
EXPECT_CALL(dtp_controller,
DropIfAllowed(testing::_, testing::_, testing::_));
// Set the operation which the destination can accept.
dragdrop_delegate_->SetOperation(DragOperation::kCopy);
// Start Drag and Drop with the operations suggested.
DragOperation operation = StartDragAndDrop(ui::DragDropTypes::DRAG_COPY |
ui::DragDropTypes::DRAG_MOVE);
// The |operation| decided through negotiation should be 'DRAG_COPY'.
EXPECT_EQ(DragOperation::kCopy, operation);
EXPECT_EQ(nullptr, dragdrop_delegate_->received_data());
EXPECT_EQ(1, dragdrop_delegate_->num_enters());
EXPECT_EQ(1, dragdrop_delegate_->num_updates());
EXPECT_EQ(0, dragdrop_delegate_->num_drops());
EXPECT_EQ(1, dragdrop_delegate_->num_exits());
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_drag_drop_client_ozone_unittest.cc | C++ | unknown | 21,686 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/widget/desktop_aura/desktop_drag_drop_client_win.h"
#include <memory>
#include "base/metrics/histogram_macros.h"
#include "base/threading/hang_watcher.h"
#include "ui/base/dragdrop/drag_drop_types.h"
#include "ui/base/dragdrop/drag_source_win.h"
#include "ui/base/dragdrop/drop_target_event.h"
#include "ui/base/dragdrop/mojom/drag_drop_types.mojom-shared.h"
#include "ui/base/dragdrop/os_exchange_data_provider_win.h"
#include "ui/base/win/event_creation_utils.h"
#include "ui/display/win/screen_win.h"
#include "ui/views/widget/desktop_aura/desktop_drop_target_win.h"
#include "ui/views/widget/desktop_aura/desktop_window_tree_host_win.h"
namespace views {
DesktopDragDropClientWin::DesktopDragDropClientWin(
aura::Window* root_window,
HWND window,
DesktopWindowTreeHostWin* desktop_host)
: drag_drop_in_progress_(false),
desktop_host_(desktop_host) {
drop_target_ = new DesktopDropTargetWin(root_window);
drop_target_->Init(window);
}
DesktopDragDropClientWin::~DesktopDragDropClientWin() {
if (drag_drop_in_progress_)
DragCancel();
}
ui::mojom::DragOperation DesktopDragDropClientWin::StartDragAndDrop(
std::unique_ptr<ui::OSExchangeData> data,
aura::Window* root_window,
aura::Window* source_window,
const gfx::Point& screen_location,
int allowed_operations,
ui::mojom::DragEventSource source) {
drag_drop_in_progress_ = true;
gfx::Point touch_screen_point;
if (source == ui::mojom::DragEventSource::kTouch) {
touch_screen_point =
screen_location + source_window->GetBoundsInScreen().OffsetFromOrigin();
source_window->GetHost()->ConvertDIPToPixels(&touch_screen_point);
desktop_host_->StartTouchDrag(touch_screen_point);
// Gesture state gets left in a state where you can't start
// another drag, unless it's cleaned up. Cleaning it up before starting
// drag drop also fixes an issue with getting two kGestureScrollBegin events
// in a row. See crbug.com/1120809.
source_window->CleanupGestureState();
}
base::WeakPtr<DesktopDragDropClientWin> alive(weak_factory_.GetWeakPtr());
drag_source_ = ui::DragSourceWin::Create();
Microsoft::WRL::ComPtr<ui::DragSourceWin> drag_source_copy = drag_source_;
drag_source_copy->set_data(data.get());
ui::OSExchangeDataProviderWin::GetDataObjectImpl(*data)->set_in_drag_loop(
true);
DWORD effect;
// Never consider the current scope as hung. The hang watching deadline (if
// any) is not valid since the user can take unbounded time to complete the
// drag. (http://crbug.com/806174)
base::HangWatcher::InvalidateActiveExpectations();
HRESULT result = ::DoDragDrop(
ui::OSExchangeDataProviderWin::GetIDataObject(*data.get()),
drag_source_.Get(),
ui::DragDropTypes::DragOperationToDropEffect(allowed_operations),
&effect);
if (alive && source == ui::mojom::DragEventSource::kTouch) {
desktop_host_->FinishTouchDrag(touch_screen_point);
// Move the mouse cursor to where the drag drop started, to avoid issues
// when the drop is outside of the Chrome window.
::SetCursorPos(touch_screen_point.x(), touch_screen_point.y());
}
drag_source_copy->set_data(nullptr);
if (alive)
drag_drop_in_progress_ = false;
if (result != DRAGDROP_S_DROP)
effect = DROPEFFECT_NONE;
return ui::PreferredDragOperation(
ui::DragDropTypes::DropEffectToDragOperation(effect));
}
void DesktopDragDropClientWin::DragCancel() {
drag_source_->CancelDrag();
}
bool DesktopDragDropClientWin::IsDragDropInProgress() {
return drag_drop_in_progress_;
}
void DesktopDragDropClientWin::AddObserver(
aura::client::DragDropClientObserver* observer) {
NOTIMPLEMENTED();
}
void DesktopDragDropClientWin::RemoveObserver(
aura::client::DragDropClientObserver* observer) {
NOTIMPLEMENTED();
}
void DesktopDragDropClientWin::OnNativeWidgetDestroying(HWND window) {
if (drop_target_.get()) {
RevokeDragDrop(window);
drop_target_ = nullptr;
}
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_drag_drop_client_win.cc | C++ | unknown | 4,173 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_DRAG_DROP_CLIENT_WIN_H_
#define UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_DRAG_DROP_CLIENT_WIN_H_
#include <wrl/client.h>
#include <memory>
#include "base/memory/raw_ptr.h"
#include "base/memory/scoped_refptr.h"
#include "base/memory/weak_ptr.h"
#include "ui/aura/client/drag_drop_client.h"
#include "ui/views/views_export.h"
namespace aura {
namespace client {
class DragDropClientObserver;
}
} // namespace aura
namespace ui {
class DragSourceWin;
}
namespace views {
class DesktopDropTargetWin;
class DesktopWindowTreeHostWin;
class VIEWS_EXPORT DesktopDragDropClientWin
: public aura::client::DragDropClient {
public:
DesktopDragDropClientWin(aura::Window* root_window,
HWND window,
DesktopWindowTreeHostWin* desktop_host);
DesktopDragDropClientWin(const DesktopDragDropClientWin&) = delete;
DesktopDragDropClientWin& operator=(const DesktopDragDropClientWin&) = delete;
~DesktopDragDropClientWin() override;
// Overridden from aura::client::DragDropClient:
ui::mojom::DragOperation StartDragAndDrop(
std::unique_ptr<ui::OSExchangeData> data,
aura::Window* root_window,
aura::Window* source_window,
const gfx::Point& screen_location,
int allowed_operations,
ui::mojom::DragEventSource source) override;
void DragCancel() override;
bool IsDragDropInProgress() override;
void AddObserver(aura::client::DragDropClientObserver* observer) override;
void RemoveObserver(aura::client::DragDropClientObserver* observer) override;
void OnNativeWidgetDestroying(HWND window);
base::WeakPtr<DesktopDragDropClientWin> GetWeakPtr() {
return weak_factory_.GetWeakPtr();
}
private:
bool drag_drop_in_progress_;
Microsoft::WRL::ComPtr<ui::DragSourceWin> drag_source_;
scoped_refptr<DesktopDropTargetWin> drop_target_;
// |this| will get deleted when DesktopNativeWidgetAura is notified that the
// DesktopWindowTreeHost is being destroyed. So desktop_host_ should outlive
// |this|.
raw_ptr<DesktopWindowTreeHostWin> desktop_host_ = nullptr;
base::WeakPtrFactory<DesktopDragDropClientWin> weak_factory_{this};
};
} // namespace views
#endif // UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_DRAG_DROP_CLIENT_WIN_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_drag_drop_client_win.h | C++ | unknown | 2,441 |
// Copyright 2011 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/widget/desktop_aura/desktop_drop_target_win.h"
#include <utility>
#include "base/win/win_util.h"
#include "ui/aura/client/drag_drop_client.h"
#include "ui/aura/client/drag_drop_delegate.h"
#include "ui/aura/window.h"
#include "ui/aura/window_tree_host.h"
#include "ui/base/dragdrop/drag_drop_types.h"
#include "ui/base/dragdrop/drop_target_event.h"
#include "ui/base/dragdrop/mojom/drag_drop_types.mojom.h"
#include "ui/base/dragdrop/os_exchange_data_provider_win.h"
#include "ui/events/event_constants.h"
using aura::client::DragDropClient;
using aura::client::DragDropDelegate;
using ui::OSExchangeData;
using ui::OSExchangeDataProviderWin;
namespace {
int ConvertKeyStateToAuraEventFlags(DWORD key_state) {
int flags = 0;
if (key_state & MK_CONTROL)
flags |= ui::EF_CONTROL_DOWN;
if (key_state & MK_ALT)
flags |= ui::EF_ALT_DOWN;
if (key_state & MK_SHIFT)
flags |= ui::EF_SHIFT_DOWN;
if (key_state & MK_LBUTTON)
flags |= ui::EF_LEFT_MOUSE_BUTTON;
if (key_state & MK_MBUTTON)
flags |= ui::EF_MIDDLE_MOUSE_BUTTON;
if (key_state & MK_RBUTTON)
flags |= ui::EF_RIGHT_MOUSE_BUTTON;
return flags;
}
} // namespace
namespace views {
DesktopDropTargetWin::DesktopDropTargetWin(aura::Window* root_window)
: root_window_(root_window), target_window_(nullptr) {}
DesktopDropTargetWin::~DesktopDropTargetWin() {
if (target_window_)
target_window_->RemoveObserver(this);
}
DWORD DesktopDropTargetWin::OnDragEnter(IDataObject* data_object,
DWORD key_state,
POINT position,
DWORD effect) {
std::unique_ptr<OSExchangeData> data;
std::unique_ptr<ui::DropTargetEvent> event;
DragDropDelegate* delegate;
// Translate will call OnDragEntered.
Translate(data_object, key_state, position, effect, &data, &event, &delegate);
return ui::DragDropTypes::DragOperationToDropEffect(
ui::DragDropTypes::DRAG_NONE);
}
DWORD DesktopDropTargetWin::OnDragOver(IDataObject* data_object,
DWORD key_state,
POINT position,
DWORD effect) {
int drag_operation = ui::DragDropTypes::DRAG_NONE;
std::unique_ptr<OSExchangeData> data;
std::unique_ptr<ui::DropTargetEvent> event;
DragDropDelegate* delegate;
Translate(data_object, key_state, position, effect, &data, &event, &delegate);
if (delegate)
drag_operation = delegate->OnDragUpdated(*event).drag_operation;
return ui::DragDropTypes::DragOperationToDropEffect(drag_operation);
}
void DesktopDropTargetWin::OnDragLeave(IDataObject* data_object) {
NotifyDragLeave();
}
DWORD DesktopDropTargetWin::OnDrop(IDataObject* data_object,
DWORD key_state,
POINT position,
DWORD effect) {
auto drag_operation = ui::mojom::DragOperation::kNone;
std::unique_ptr<OSExchangeData> data;
std::unique_ptr<ui::DropTargetEvent> event;
DragDropDelegate* delegate;
Translate(data_object, key_state, position, effect, &data, &event, &delegate);
if (delegate) {
auto drop_cb = delegate->GetDropCallback(*event);
if (drop_cb)
std::move(drop_cb).Run(std::move(data), drag_operation,
/*drag_image_layer_owner=*/nullptr);
}
if (target_window_) {
target_window_->RemoveObserver(this);
target_window_ = nullptr;
}
return ui::DragDropTypes::DragOperationToDropEffect(
static_cast<int>(drag_operation));
}
void DesktopDropTargetWin::OnWindowDestroyed(aura::Window* window) {
DCHECK(window == target_window_);
target_window_ = nullptr;
}
void DesktopDropTargetWin::Translate(
IDataObject* data_object,
DWORD key_state,
POINT position,
DWORD effect,
std::unique_ptr<OSExchangeData>* data,
std::unique_ptr<ui::DropTargetEvent>* event,
DragDropDelegate** delegate) {
gfx::Point location(position.x, position.y);
gfx::Point root_location = location;
root_window_->GetHost()->ConvertScreenInPixelsToDIP(&root_location);
aura::Window* target_window =
root_window_->GetEventHandlerForPoint(root_location);
bool target_window_changed = false;
if (target_window != target_window_) {
if (target_window_)
NotifyDragLeave();
target_window_ = target_window;
if (target_window_)
target_window_->AddObserver(this);
target_window_changed = true;
}
*delegate = nullptr;
if (!target_window_)
return;
*delegate = aura::client::GetDragDropDelegate(target_window_);
if (!*delegate)
return;
*data = std::make_unique<OSExchangeData>(
std::make_unique<OSExchangeDataProviderWin>(data_object));
location = root_location;
aura::Window::ConvertPointToTarget(root_window_, target_window_, &location);
*event = std::make_unique<ui::DropTargetEvent>(
*(data->get()), gfx::PointF(location), gfx::PointF(root_location),
ui::DragDropTypes::DropEffectToDragOperation(effect));
(*event)->set_flags(ConvertKeyStateToAuraEventFlags(key_state));
if (target_window_changed)
(*delegate)->OnDragEntered(*event->get());
}
void DesktopDropTargetWin::NotifyDragLeave() {
if (!target_window_)
return;
DragDropDelegate* delegate =
aura::client::GetDragDropDelegate(target_window_);
if (delegate)
delegate->OnDragExited();
target_window_->RemoveObserver(this);
target_window_ = nullptr;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_drop_target_win.cc | C++ | unknown | 5,691 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_DROP_TARGET_WIN_H_
#define UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_DROP_TARGET_WIN_H_
#include <memory>
#include "base/memory/raw_ptr.h"
#include "ui/aura/window_observer.h"
#include "ui/base/dragdrop/drop_target_win.h"
namespace aura {
namespace client {
class DragDropDelegate;
}
} // namespace aura
namespace ui {
class DropTargetEvent;
class OSExchangeData;
} // namespace ui
namespace views {
// DesktopDropTargetWin takes care of managing drag and drop for
// DesktopWindowTreeHostWin. It converts Windows OLE drop messages into
// aura::client::DragDropDelegate calls.
class DesktopDropTargetWin : public ui::DropTargetWin,
public aura::WindowObserver {
public:
explicit DesktopDropTargetWin(aura::Window* root_window);
DesktopDropTargetWin(const DesktopDropTargetWin&) = delete;
DesktopDropTargetWin& operator=(const DesktopDropTargetWin&) = delete;
~DesktopDropTargetWin() override;
private:
// ui::DropTargetWin implementation:
DWORD OnDragEnter(IDataObject* data_object,
DWORD key_state,
POINT position,
DWORD effect) override;
DWORD OnDragOver(IDataObject* data_object,
DWORD key_state,
POINT position,
DWORD effect) override;
void OnDragLeave(IDataObject* data_object) override;
DWORD OnDrop(IDataObject* data_object,
DWORD key_state,
POINT position,
DWORD effect) override;
// aura::WindowObserver implementation:
void OnWindowDestroyed(aura::Window* window) override;
// Common functionality for the ui::DropTargetWin methods to translate from
// COM data types to Aura ones.
void Translate(IDataObject* data_object,
DWORD key_state,
POINT cursor_position,
DWORD effect,
std::unique_ptr<ui::OSExchangeData>* data,
std::unique_ptr<ui::DropTargetEvent>* event,
aura::client::DragDropDelegate** delegate);
void NotifyDragLeave();
// The root window associated with this drop target.
raw_ptr<aura::Window> root_window_;
// The Aura window that is currently under the cursor. We need to manually
// keep track of this because Windows will only call our drag enter method
// once when the user enters the associated HWND. But inside that HWND there
// could be multiple aura windows, so we need to generate drag enter events
// for them.
raw_ptr<aura::Window> target_window_;
};
} // namespace views
#endif // UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_DROP_TARGET_WIN_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_drop_target_win.h | C++ | unknown | 2,822 |
// 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/widget/desktop_aura/desktop_event_client.h"
#include "ui/aura/env.h"
namespace views {
DesktopEventClient::DesktopEventClient() = default;
DesktopEventClient::~DesktopEventClient() = default;
bool DesktopEventClient::GetCanProcessEventsWithinSubtree(
const aura::Window* window) const {
return true;
}
ui::EventTarget* DesktopEventClient::GetToplevelEventTarget() {
return aura::Env::GetInstance();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_event_client.cc | C++ | unknown | 601 |
// 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_WIDGET_DESKTOP_AURA_DESKTOP_EVENT_CLIENT_H_
#define UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_EVENT_CLIENT_H_
#include "ui/aura/client/event_client.h"
#include "ui/views/views_export.h"
namespace views {
class VIEWS_EXPORT DesktopEventClient : public aura::client::EventClient {
public:
DesktopEventClient();
DesktopEventClient(const DesktopEventClient&) = delete;
DesktopEventClient& operator=(const DesktopEventClient&) = delete;
~DesktopEventClient() override;
// Overridden from aura::client::EventClient:
bool GetCanProcessEventsWithinSubtree(
const aura::Window* window) const override;
ui::EventTarget* GetToplevelEventTarget() override;
};
} // namespace views
#endif // UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_EVENT_CLIENT_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_event_client.h | C++ | unknown | 919 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/widget/desktop_aura/desktop_focus_rules.h"
#include "ui/aura/client/aura_constants.h"
#include "ui/aura/window.h"
#include "ui/aura/window_event_dispatcher.h"
#include "ui/wm/core/window_util.h"
namespace views {
DesktopFocusRules::DesktopFocusRules(aura::Window* content_window)
: content_window_(content_window) {}
DesktopFocusRules::~DesktopFocusRules() = default;
bool DesktopFocusRules::CanActivateWindow(const aura::Window* window) const {
// The RootWindow is not activatable, only |content_window_| and children of
// the RootWindow are considered activatable.
if (window && window->IsRootWindow())
return false;
if (window && IsToplevelWindow(window) &&
content_window_->GetRootWindow()->Contains(window) &&
wm::WindowStateIs(window->GetRootWindow(), ui::SHOW_STATE_MINIMIZED)) {
return true;
}
if (!BaseFocusRules::CanActivateWindow(window))
return false;
// Never activate a window that is not a child of the root window. Transients
// spanning different DesktopNativeWidgetAuras may trigger this.
return !window || content_window_->GetRootWindow()->Contains(window);
}
bool DesktopFocusRules::CanFocusWindow(const aura::Window* window,
const ui::Event* event) const {
return BaseFocusRules::CanFocusWindow(window, event) ||
wm::WindowStateIs(window->GetRootWindow(), ui::SHOW_STATE_MINIMIZED);
}
bool DesktopFocusRules::SupportsChildActivation(
const aura::Window* window) const {
// In Desktop-Aura, only the content_window or children of the RootWindow are
// activatable.
return window->IsRootWindow();
}
bool DesktopFocusRules::IsWindowConsideredVisibleForActivation(
const aura::Window* window) const {
// |content_window_| is initially hidden and made visible from Show(). Even in
// this state we still want it to be activatable.
return BaseFocusRules::IsWindowConsideredVisibleForActivation(window) ||
(window == content_window_);
}
const aura::Window* DesktopFocusRules::GetToplevelWindow(
const aura::Window* window) const {
const aura::Window* top_level_window =
wm::BaseFocusRules::GetToplevelWindow(window);
// In Desktop-Aura, only the content_window or children of the RootWindow are
// considered as top level windows.
if (top_level_window == content_window_->parent())
return content_window_;
return top_level_window;
}
aura::Window* DesktopFocusRules::GetNextActivatableWindow(
aura::Window* window) const {
aura::Window* next_activatable_window =
wm::BaseFocusRules::GetNextActivatableWindow(window);
// In Desktop-Aura the content_window_'s parent is a dummy window and thus
// should never be activated. We should return the content_window_ if it
// can be activated in this case.
if (next_activatable_window == content_window_->parent() &&
CanActivateWindow(content_window_))
return content_window_;
return next_activatable_window;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_focus_rules.cc | C++ | unknown | 3,145 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_FOCUS_RULES_H_
#define UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_FOCUS_RULES_H_
#include "base/memory/raw_ptr.h"
#include "ui/wm/core/base_focus_rules.h"
namespace views {
class DesktopFocusRules : public wm::BaseFocusRules {
public:
explicit DesktopFocusRules(aura::Window* content_window);
DesktopFocusRules(const DesktopFocusRules&) = delete;
DesktopFocusRules& operator=(const DesktopFocusRules&) = delete;
~DesktopFocusRules() override;
private:
// Overridden from wm::BaseFocusRules:
bool CanActivateWindow(const aura::Window* window) const override;
bool CanFocusWindow(const aura::Window* window,
const ui::Event* event) const override;
bool SupportsChildActivation(const aura::Window* window) const override;
bool IsWindowConsideredVisibleForActivation(
const aura::Window* window) const override;
const aura::Window* GetToplevelWindow(
const aura::Window* window) const override;
aura::Window* GetNextActivatableWindow(aura::Window* window) const override;
// The content window. This is an activatable window even though it is a
// child.
raw_ptr<aura::Window> content_window_;
};
} // namespace views
#endif // UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_FOCUS_RULES_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_focus_rules.h | C++ | unknown | 1,434 |
// 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/widget/desktop_aura/desktop_focus_rules.h"
#include "ui/aura/client/focus_client.h"
#include "ui/aura/test/test_window_delegate.h"
#include "ui/aura/window.h"
#include "ui/aura/window_event_dispatcher.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h"
#include "ui/views/widget/widget.h"
#include "ui/wm/core/window_util.h"
namespace views {
using DesktopFocusRulesTest = test::DesktopWidgetTest;
// Verifies we don't attempt to activate a window in another widget.
TEST_F(DesktopFocusRulesTest, DontFocusWindowsInOtherHierarchies) {
// Two widgets (each with a DesktopNativeWidgetAura). |w2| has a child Window
// |w2_child| that is not focusable. |w2_child|'s has a transient parent in
// |w1|.
Widget* w1 = CreateTopLevelNativeWidget();
Widget* w2 = CreateTopLevelNativeWidget();
aura::test::TestWindowDelegate w2_child_delegate;
w2_child_delegate.set_can_focus(false);
aura::Window* w2_child = new aura::Window(&w2_child_delegate);
w2_child->Init(ui::LAYER_SOLID_COLOR);
w2->GetNativeView()->AddChild(w2_child);
wm::AddTransientChild(w1->GetNativeView(), w2_child);
aura::client::GetFocusClient(w2->GetNativeView())->FocusWindow(w2_child);
aura::Window* focused =
aura::client::GetFocusClient(w2->GetNativeView())->GetFocusedWindow();
EXPECT_TRUE((focused == nullptr) || w2->GetNativeView()->Contains(focused));
wm::RemoveTransientChild(w1->GetNativeView(), w2_child);
w1->CloseNow();
w2->CloseNow();
}
// Verifies root windows are not activatable.
TEST_F(DesktopFocusRulesTest, CanActivateWindowForRootWindow) {
Widget* w1 = CreateTopLevelNativeWidget();
aura::Window* content_window = w1->GetNativeWindow();
aura::Window* root_window = content_window->GetRootWindow();
EXPECT_TRUE(wm::CanActivateWindow(content_window));
EXPECT_FALSE(wm::CanActivateWindow(root_window));
w1->CloseNow();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_focus_rules_unittest.cc | C++ | unknown | 2,099 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/widget/desktop_aura/desktop_native_cursor_manager.h"
#include "base/trace_event/trace_event.h"
#include "ui/aura/client/cursor_shape_client.h"
#include "ui/aura/window_event_dispatcher.h"
#include "ui/aura/window_tree_host.h"
#include "ui/base/cursor/mojom/cursor_type.mojom-shared.h"
#include "ui/wm/core/cursor_loader.h"
namespace views {
DesktopNativeCursorManager::DesktopNativeCursorManager() {
aura::client::SetCursorShapeClient(&cursor_loader_);
}
DesktopNativeCursorManager::~DesktopNativeCursorManager() {
aura::client::SetCursorShapeClient(nullptr);
}
void DesktopNativeCursorManager::AddHost(aura::WindowTreeHost* host) {
hosts_.insert(host);
}
void DesktopNativeCursorManager::RemoveHost(aura::WindowTreeHost* host) {
hosts_.erase(host);
}
void DesktopNativeCursorManager::SetDisplay(
const display::Display& display,
wm::NativeCursorManagerDelegate* delegate) {
if (cursor_loader_.SetDisplay(display)) {
SetCursor(delegate->GetCursor(), delegate);
}
}
void DesktopNativeCursorManager::SetCursor(
gfx::NativeCursor cursor,
wm::NativeCursorManagerDelegate* delegate) {
gfx::NativeCursor new_cursor = cursor;
cursor_loader_.SetPlatformCursor(&new_cursor);
delegate->CommitCursor(new_cursor);
if (delegate->IsCursorVisible()) {
for (auto* host : hosts_)
host->SetCursor(new_cursor);
}
}
void DesktopNativeCursorManager::SetVisibility(
bool visible,
wm::NativeCursorManagerDelegate* delegate) {
TRACE_EVENT1("ui,input", "DesktopNativeCursorManager::SetVisibility",
"visible", visible);
delegate->CommitVisibility(visible);
if (visible) {
SetCursor(delegate->GetCursor(), delegate);
} else {
gfx::NativeCursor invisible_cursor(ui::mojom::CursorType::kNone);
cursor_loader_.SetPlatformCursor(&invisible_cursor);
for (auto* host : hosts_)
host->SetCursor(invisible_cursor);
}
for (auto* host : hosts_)
host->OnCursorVisibilityChanged(visible);
}
void DesktopNativeCursorManager::SetCursorSize(
ui::CursorSize cursor_size,
wm::NativeCursorManagerDelegate* delegate) {
NOTIMPLEMENTED();
}
void DesktopNativeCursorManager::SetMouseEventsEnabled(
bool enabled,
wm::NativeCursorManagerDelegate* delegate) {
TRACE_EVENT0("ui,input", "DesktopNativeCursorManager::SetMouseEventsEnabled");
delegate->CommitMouseEventsEnabled(enabled);
// TODO(erg): In the ash version, we set the last mouse location on Env. I'm
// not sure this concept makes sense on the desktop.
SetVisibility(delegate->IsCursorVisible(), delegate);
for (auto* host : hosts_)
host->dispatcher()->OnMouseEventsEnableStateChanged(enabled);
}
void DesktopNativeCursorManager::InitCursorSizeObserver(
wm::NativeCursorManagerDelegate* delegate) {
NOTREACHED_NORETURN();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_native_cursor_manager.cc | C++ | unknown | 2,989 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_NATIVE_CURSOR_MANAGER_H_
#define UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_NATIVE_CURSOR_MANAGER_H_
#include <memory>
#include <set>
#include "ui/views/views_export.h"
#include "ui/wm/core/cursor_loader.h"
#include "ui/wm/core/native_cursor_manager.h"
namespace aura {
class WindowTreeHost;
}
namespace wm {
class NativeCursorManagerDelegate;
}
namespace views {
// A NativeCursorManager that performs the desktop-specific setting of cursor
// state. Similar to NativeCursorManagerAsh, it also communicates these changes
// to all root windows.
class VIEWS_EXPORT DesktopNativeCursorManager : public wm::NativeCursorManager {
public:
DesktopNativeCursorManager();
DesktopNativeCursorManager(const DesktopNativeCursorManager&) = delete;
DesktopNativeCursorManager& operator=(const DesktopNativeCursorManager&) =
delete;
~DesktopNativeCursorManager() override;
// Adds |host| to the set |hosts_|.
void AddHost(aura::WindowTreeHost* host);
// Removes |host| from the set |hosts_|.
void RemoveHost(aura::WindowTreeHost* host);
// Initialize the observer that will report system cursor size.
virtual void InitCursorSizeObserver(
wm::NativeCursorManagerDelegate* delegate);
private:
// Overridden from wm::NativeCursorManager:
void SetDisplay(const display::Display& display,
wm::NativeCursorManagerDelegate* delegate) override;
void SetCursor(gfx::NativeCursor cursor,
wm::NativeCursorManagerDelegate* delegate) override;
void SetVisibility(bool visible,
wm::NativeCursorManagerDelegate* delegate) override;
void SetCursorSize(ui::CursorSize cursor_size,
wm::NativeCursorManagerDelegate* delegate) override;
void SetMouseEventsEnabled(
bool enabled,
wm::NativeCursorManagerDelegate* delegate) override;
// The set of hosts to notify of changes in cursor state.
using Hosts = std::set<aura::WindowTreeHost*>;
Hosts hosts_;
wm::CursorLoader cursor_loader_;
};
} // namespace views
#endif // UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_NATIVE_CURSOR_MANAGER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_native_cursor_manager.h | C++ | unknown | 2,291 |
// 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/widget/desktop_aura/desktop_native_cursor_manager_win.h"
#include <utility>
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/numerics/safe_conversions.h"
#include "base/win/windows_types.h"
#include "ui/wm/core/native_cursor_manager_delegate.h"
namespace views {
namespace {
constexpr int kDefaultCursorSize = 32;
} // namespace
DesktopNativeCursorManagerWin::DesktopNativeCursorManagerWin() = default;
DesktopNativeCursorManagerWin::~DesktopNativeCursorManagerWin() = default;
void DesktopNativeCursorManagerWin::SetSystemCursorSize(
wm::NativeCursorManagerDelegate* delegate) {
DWORD cursor_base_size = 0;
if (hkcu_cursor_regkey_.Valid() &&
hkcu_cursor_regkey_.ReadValueDW(L"CursorBaseSize", &cursor_base_size) ==
ERROR_SUCCESS) {
int size = base::checked_cast<int>(cursor_base_size);
system_cursor_size_ = gfx::Size(size, size);
}
// Report cursor size.
delegate->CommitSystemCursorSize(system_cursor_size_);
}
void DesktopNativeCursorManagerWin::RegisterCursorRegkeyObserver(
wm::NativeCursorManagerDelegate* delegate) {
if (!hkcu_cursor_regkey_.Valid())
return;
hkcu_cursor_regkey_.StartWatching(base::BindOnce(
[](DesktopNativeCursorManagerWin* manager,
wm::NativeCursorManagerDelegate* delegate) {
manager->SetSystemCursorSize(delegate);
// RegKey::StartWatching only provides one notification.
// Reregistration is required to get future notifications.
manager->RegisterCursorRegkeyObserver(delegate);
},
// It's safe to use |base::Unretained(this)| here, because |this| owns
// the |hkcu_cursor_regkey_|, and the callback will be cancelled if
// |hkcu_cursor_regkey_| is destroyed.
base::Unretained(this), delegate));
}
void DesktopNativeCursorManagerWin::InitCursorSizeObserver(
wm::NativeCursorManagerDelegate* delegate) {
hkcu_cursor_regkey_.Open(HKEY_CURRENT_USER, L"Control Panel\\Cursors",
KEY_READ | KEY_NOTIFY);
system_cursor_size_ = gfx::Size(kDefaultCursorSize, kDefaultCursorSize);
RegisterCursorRegkeyObserver(delegate);
SetSystemCursorSize(delegate);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_native_cursor_manager_win.cc | C++ | unknown | 2,379 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_NATIVE_CURSOR_MANAGER_WIN_H_
#define UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_NATIVE_CURSOR_MANAGER_WIN_H_
#include "base/win/registry.h"
#include "ui/gfx/geometry/size.h"
#include "ui/views/views_export.h"
#include "ui/views/widget/desktop_aura/desktop_native_cursor_manager.h"
namespace wm {
class NativeCursorManagerDelegate;
}
namespace views {
// A NativeCursorManager that performs the desktop-specific setting of cursor
// state. Similar to NativeCursorManagerAsh, it also communicates these changes
// to all root windows.
class VIEWS_EXPORT DesktopNativeCursorManagerWin
: public DesktopNativeCursorManager {
public:
DesktopNativeCursorManagerWin();
DesktopNativeCursorManagerWin(const DesktopNativeCursorManagerWin&) = delete;
DesktopNativeCursorManagerWin& operator=(
const DesktopNativeCursorManagerWin&) = delete;
~DesktopNativeCursorManagerWin() override;
void InitCursorSizeObserver(
wm::NativeCursorManagerDelegate* delegate) override;
private:
// Retrieve and report the cursor size to cursor manager.
void SetSystemCursorSize(wm::NativeCursorManagerDelegate* delegate);
void RegisterCursorRegkeyObserver(wm::NativeCursorManagerDelegate* delegate);
base::win::RegKey hkcu_cursor_regkey_;
gfx::Size system_cursor_size_;
};
} // namespace views
#endif // UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_NATIVE_CURSOR_MANAGER_WIN_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_native_cursor_manager_win.h | C++ | unknown | 1,572 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h"
#include <memory>
#include <utility>
#include "base/auto_reset.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/memory/raw_ptr.h"
#include "base/trace_event/trace_event.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/aura/client/aura_constants.h"
#include "ui/aura/client/cursor_client.h"
#include "ui/aura/client/drag_drop_client.h"
#include "ui/aura/client/drag_drop_delegate.h"
#include "ui/aura/client/focus_client.h"
#include "ui/aura/client/window_parenting_client.h"
#include "ui/aura/env.h"
#include "ui/aura/window.h"
#include "ui/aura/window_observer.h"
#include "ui/aura/window_occlusion_tracker.h"
#include "ui/aura/window_tree_host.h"
#include "ui/base/class_property.h"
#include "ui/base/data_transfer_policy/data_transfer_endpoint.h"
#include "ui/base/dragdrop/drag_drop_types.h"
#include "ui/base/hit_test.h"
#include "ui/base/ime/input_method.h"
#include "ui/base/owned_window_anchor.h"
#include "ui/base/ui_base_features.h"
#include "ui/base/ui_base_types.h"
#include "ui/compositor/compositor.h"
#include "ui/compositor/layer.h"
#include "ui/display/screen.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/geometry/point_conversions.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/geometry/size_conversions.h"
#include "ui/views/corewm/tooltip.h"
#include "ui/views/corewm/tooltip_controller.h"
#include "ui/views/drag_utils.h"
#include "ui/views/view_constants_aura.h"
#include "ui/views/views_delegate.h"
#include "ui/views/widget/desktop_aura/desktop_capture_client.h"
#include "ui/views/widget/desktop_aura/desktop_event_client.h"
#include "ui/views/widget/desktop_aura/desktop_focus_rules.h"
#include "ui/views/widget/desktop_aura/desktop_native_cursor_manager.h"
#include "ui/views/widget/desktop_aura/desktop_screen_position_client.h"
#include "ui/views/widget/desktop_aura/desktop_window_tree_host.h"
#include "ui/views/widget/desktop_aura/desktop_window_tree_host_platform.h"
#include "ui/views/widget/focus_manager_event_handler.h"
#include "ui/views/widget/native_widget_aura.h"
#include "ui/views/widget/root_view.h"
#include "ui/views/widget/tooltip_manager_aura.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_aura_utils.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/widget/window_reorderer.h"
#include "ui/wm/core/compound_event_filter.h"
#include "ui/wm/core/cursor_manager.h"
#include "ui/wm/core/focus_controller.h"
#include "ui/wm/core/native_cursor_manager.h"
#include "ui/wm/core/shadow_controller.h"
#include "ui/wm/core/shadow_controller_delegate.h"
#include "ui/wm/core/shadow_types.h"
#include "ui/wm/core/visibility_controller.h"
#include "ui/wm/core/window_animations.h"
#include "ui/wm/core/window_modality_controller.h"
#include "ui/wm/core/window_util.h"
#include "ui/wm/public/activation_client.h"
#if BUILDFLAG(IS_WIN)
#include "ui/base/win/shell.h"
#include "ui/views/widget/desktop_aura/desktop_native_cursor_manager_win.h"
#endif
DEFINE_EXPORTED_UI_CLASS_PROPERTY_TYPE(VIEWS_EXPORT,
views::DesktopNativeWidgetAura*)
namespace views {
DEFINE_UI_CLASS_PROPERTY_KEY(DesktopNativeWidgetAura*,
kDesktopNativeWidgetAuraKey,
NULL)
namespace {
// This class provides functionality to create a top level widget to host a
// child window.
class DesktopNativeWidgetTopLevelHandler : public aura::WindowObserver {
public:
// This function creates a widget with the bounds passed in which eventually
// becomes the parent of the child window passed in.
static aura::Window* CreateParentWindow(aura::Window* child_window,
aura::Window* context,
const gfx::Rect& bounds,
bool full_screen,
bool is_menu,
ui::ZOrderLevel root_z_order) {
// This instance will get deleted when the widget is destroyed.
DesktopNativeWidgetTopLevelHandler* top_level_handler =
new DesktopNativeWidgetTopLevelHandler;
child_window->SetBounds(gfx::Rect(bounds.size()));
Widget::InitParams init_params;
init_params.type = full_screen ? Widget::InitParams::TYPE_WINDOW
: is_menu ? Widget::InitParams::TYPE_MENU
: Widget::InitParams::TYPE_POPUP;
#if BUILDFLAG(IS_CHROMEOS_LACROS)
// Evaluate if the window needs shadow.
init_params.shadow_type =
(wm::GetShadowElevationConvertDefault(child_window) > 0)
? Widget::InitParams::ShadowType::kDrop
: Widget::InitParams::ShadowType::kNone;
#endif
#if BUILDFLAG(IS_WIN)
// For menus, on Windows versions that support drop shadow remove
// the standard frame in order to keep just the shadow.
if (init_params.type == Widget::InitParams::TYPE_MENU)
init_params.remove_standard_frame = true;
#endif
init_params.bounds = bounds;
init_params.ownership = Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET;
init_params.layer_type = ui::LAYER_NOT_DRAWN;
init_params.activatable = full_screen
? Widget::InitParams::Activatable::kYes
: Widget::InitParams::Activatable::kNo;
init_params.z_order = root_z_order;
// Also provide the context, which Ozone (in particular - Wayland) will use
// to parent this newly created toplevel native widget to. Please refer to
// https://crrev.com/c/2831291 for more details.
init_params.context = context;
auto* anchor = child_window->GetProperty(aura::client::kOwnedWindowAnchor);
if (anchor) {
init_params.init_properties_container.SetProperty(
aura::client::kOwnedWindowAnchor, *anchor);
child_window->ClearProperty(aura::client::kOwnedWindowAnchor);
}
// This widget instance will get deleted when the window is
// destroyed.
top_level_handler->top_level_widget_ = new Widget();
// Ensure that we always use the DesktopNativeWidgetAura instance as the
// native widget here. If we enter this code path in tests then it is
// possible that we may end up with a NativeWidgetAura instance as the
// native widget which breaks this code path.
init_params.native_widget =
new DesktopNativeWidgetAura(top_level_handler->top_level_widget_);
top_level_handler->top_level_widget_->Init(std::move(init_params));
top_level_handler->top_level_widget_->SetFullscreen(full_screen);
top_level_handler->top_level_widget_->Show();
aura::Window* native_window =
top_level_handler->top_level_widget_->GetNativeView();
child_window->AddObserver(top_level_handler);
native_window->AddObserver(top_level_handler);
top_level_handler->child_window_ = child_window;
return native_window;
}
DesktopNativeWidgetTopLevelHandler(
const DesktopNativeWidgetTopLevelHandler&) = delete;
DesktopNativeWidgetTopLevelHandler& operator=(
const DesktopNativeWidgetTopLevelHandler&) = delete;
// aura::WindowObserver overrides
void OnWindowDestroying(aura::Window* window) override {
window->RemoveObserver(this);
// If the widget is being destroyed by the OS then we should not try and
// destroy it again.
if (top_level_widget_ && window == top_level_widget_->GetNativeView()) {
top_level_widget_ = nullptr;
return;
}
if (top_level_widget_) {
DCHECK(top_level_widget_->GetNativeView());
top_level_widget_->GetNativeView()->RemoveObserver(this);
// When we receive a notification that the child of the window created
// above is being destroyed we go ahead and initiate the destruction of
// the corresponding widget.
top_level_widget_->Close();
top_level_widget_ = nullptr;
}
delete this;
}
void OnWindowBoundsChanged(aura::Window* window,
const gfx::Rect& old_bounds,
const gfx::Rect& new_bounds,
ui::PropertyChangeReason reason) override {
// The position of the window may have changed. Hence we use SetBounds in
// place of SetSize. We need to pass the bounds in screen coordinates to
// the Widget::SetBounds function.
if (top_level_widget_ && window == child_window_)
top_level_widget_->SetBounds(window->GetBoundsInScreen());
}
private:
DesktopNativeWidgetTopLevelHandler() = default;
~DesktopNativeWidgetTopLevelHandler() override = default;
raw_ptr<Widget> top_level_widget_ = nullptr;
raw_ptr<aura::Window> child_window_ = nullptr;
};
class DesktopNativeWidgetAuraWindowParentingClient
: public aura::client::WindowParentingClient {
public:
explicit DesktopNativeWidgetAuraWindowParentingClient(
aura::Window* root_window)
: root_window_(root_window) {
aura::client::SetWindowParentingClient(root_window_, this);
}
DesktopNativeWidgetAuraWindowParentingClient(
const DesktopNativeWidgetAuraWindowParentingClient&) = delete;
DesktopNativeWidgetAuraWindowParentingClient& operator=(
const DesktopNativeWidgetAuraWindowParentingClient&) = delete;
~DesktopNativeWidgetAuraWindowParentingClient() override {
aura::client::SetWindowParentingClient(root_window_, nullptr);
}
// Overridden from client::WindowParentingClient:
aura::Window* GetDefaultParent(aura::Window* window,
const gfx::Rect& bounds) override {
// TODO(crbug.com/1236997): Re-enable this logic once Fuchsia's windowing
// APIs provide the required functionality.
#if !BUILDFLAG(IS_FUCHSIA)
bool is_fullscreen = window->GetProperty(aura::client::kShowStateKey) ==
ui::SHOW_STATE_FULLSCREEN;
bool is_menu = window->GetType() == aura::client::WINDOW_TYPE_MENU;
if (is_fullscreen || is_menu) {
ui::ZOrderLevel root_z_order = ui::ZOrderLevel::kNormal;
internal::NativeWidgetPrivate* native_widget =
DesktopNativeWidgetAura::ForWindow(root_window_);
if (native_widget)
root_z_order = native_widget->GetZOrderLevel();
return DesktopNativeWidgetTopLevelHandler::CreateParentWindow(
window, root_window_ /* context */, bounds, is_fullscreen, is_menu,
root_z_order);
}
#endif // !BUILDFLAG(IS_FUCHSIA)
return root_window_;
}
private:
raw_ptr<aura::Window> root_window_;
};
} // namespace
class RootWindowDestructionObserver : public aura::WindowObserver {
public:
explicit RootWindowDestructionObserver(DesktopNativeWidgetAura* parent)
: parent_(parent) {}
RootWindowDestructionObserver(const RootWindowDestructionObserver&) = delete;
RootWindowDestructionObserver& operator=(
const RootWindowDestructionObserver&) = delete;
~RootWindowDestructionObserver() override = default;
private:
// Overridden from aura::WindowObserver:
void OnWindowDestroyed(aura::Window* window) override {
parent_->RootWindowDestroyed();
window->RemoveObserver(this);
delete this;
}
raw_ptr<DesktopNativeWidgetAura> parent_;
};
////////////////////////////////////////////////////////////////////////////////
// DesktopNativeWidgetAura, public:
int DesktopNativeWidgetAura::cursor_reference_count_ = 0;
DesktopNativeCursorManager* DesktopNativeWidgetAura::native_cursor_manager_ =
nullptr;
wm::CursorManager* DesktopNativeWidgetAura::cursor_manager_ = nullptr;
DesktopNativeWidgetAura::DesktopNativeWidgetAura(
internal::NativeWidgetDelegate* delegate)
: desktop_window_tree_host_(nullptr),
content_window_(new aura::Window(this)),
native_widget_delegate_(delegate->AsWidget()->GetWeakPtr()),
cursor_(gfx::kNullCursor) {
aura::client::SetFocusChangeObserver(content_window_, this);
wm::SetActivationChangeObserver(content_window_, this);
}
DesktopNativeWidgetAura::~DesktopNativeWidgetAura() {
if (ownership_ == Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET) {
// `drop_helper_` and `window_reorderer_` hold a pointer to
// `native_widget_delegate_`'s root view. Reset them before deleting
// `native_widget_delegate_` to avoid holding a briefly dangling ptr.
drop_helper_.reset();
window_reorderer_.reset();
owned_native_widget_delegate.reset();
} else {
CloseNow();
}
}
// static
DesktopNativeWidgetAura* DesktopNativeWidgetAura::ForWindow(
aura::Window* window) {
return window->GetProperty(kDesktopNativeWidgetAuraKey);
}
void DesktopNativeWidgetAura::OnHostClosed() {
// Don't invoke Widget::OnNativeWidgetDestroying(), its done by
// DesktopWindowTreeHost.
// The WindowModalityController is at the front of the event pretarget
// handler list. We destroy it first to preserve order symantics.
if (window_modality_controller_)
window_modality_controller_.reset();
// Make sure we don't have capture. Otherwise CaptureController and
// WindowEventDispatcher are left referencing a deleted Window.
{
aura::Window* capture_window = capture_client_->GetCaptureWindow();
if (capture_window && host_->window()->Contains(capture_window))
capture_window->ReleaseCapture();
}
// DesktopWindowTreeHost owns the ActivationController which ShadowController
// references. Make sure we destroy ShadowController early on.
shadow_controller_.reset();
tooltip_manager_.reset();
if (tooltip_controller_.get()) {
host_->window()->RemovePreTargetHandler(tooltip_controller_.get());
wm::SetTooltipClient(host_->window(), nullptr);
tooltip_controller_.reset();
}
window_parenting_client_.reset(); // Uses host_->dispatcher() at destruction.
capture_client_.reset(); // Uses host_->dispatcher() at destruction.
focus_manager_event_handler_.reset();
// FocusController uses |content_window_|. Destroy it now so that we don't
// have to worry about the possibility of FocusController attempting to use
// |content_window_| after it's been destroyed but before all child windows
// have been destroyed.
host_->window()->RemovePreTargetHandler(focus_client_.get());
aura::client::SetFocusClient(host_->window(), nullptr);
wm::SetActivationClient(host_->window(), nullptr);
focus_client_.reset();
host_->window()->RemovePreTargetHandler(root_window_event_filter_.get());
host_->RemoveObserver(this);
// |drag_drop_client_| holds a raw_ptr on |desktop_window_tree_host_|, so we
// need to destroy it first.
drag_drop_client_.reset();
// WindowEventDispatcher owns |desktop_window_tree_host_|.
desktop_window_tree_host_ = nullptr;
// Delete host after resetting `desktop_window_tree_host_` and
// `content_window_` to avoid accessing the stale instance during deletion.
host_.reset();
content_window_ = nullptr;
// |OnNativeWidgetDestroyed| may delete |this| if the object does not own
// itself.
bool should_delete_this =
(ownership_ == Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET) ||
(ownership_ == Widget::InitParams::CLIENT_OWNS_WIDGET);
if (native_widget_delegate_)
native_widget_delegate_->OnNativeWidgetDestroyed();
if (should_delete_this)
delete this;
}
void DesktopNativeWidgetAura::OnDesktopWindowTreeHostDestroyed(
aura::WindowTreeHost* host) {
if (use_desktop_native_cursor_manager_) {
// We explicitly do NOT clear the cursor client property. Since the cursor
// manager is a singleton, it can outlive any window hierarchy, and it's
// important that objects attached to this destroying window hierarchy have
// an opportunity to deregister their observers from the cursor manager.
// They may want to do this when they are notified that they're being
// removed from the window hierarchy, which happens soon after this
// function when DesktopWindowTreeHost* calls DestroyDispatcher().
native_cursor_manager_->RemoveHost(host);
}
aura::client::SetScreenPositionClient(host->window(), nullptr);
position_client_.reset();
aura::client::SetEventClient(host->window(), nullptr);
event_client_.reset();
}
base::WeakPtr<internal::NativeWidgetPrivate>
DesktopNativeWidgetAura::GetWeakPtr() {
return weak_ptr_factory_.GetWeakPtr();
}
void DesktopNativeWidgetAura::NotifyAccessibilityEvent(
ax::mojom::Event event_type) {
if (!GetWidget() || !GetWidget()->GetRootView())
return;
GetWidget()->GetRootView()->NotifyAccessibilityEvent(event_type, true);
}
views::corewm::TooltipController*
DesktopNativeWidgetAura::tooltip_controller() {
return tooltip_controller_.get();
}
void DesktopNativeWidgetAura::HandleActivationChanged(bool active) {
DCHECK(native_widget_delegate_);
if (!native_widget_delegate_->ShouldHandleNativeWidgetActivationChanged(
active)) {
return;
}
wm::ActivationClient* activation_client =
wm::GetActivationClient(host_->window());
if (!activation_client)
return;
// Update `should_activate_` with the new activation state of this widget
// while handling this change. We do this to ensure that the activation client
// sees the correct activation state for this widget when handling the
// activation change event. This is needed since the activation client may
// check whether this widget can receive activation when deciding which window
// should receive activation next.
base::AutoReset<absl::optional<bool>> resetter(&should_activate_, active);
if (active) {
// TODO(nektar): We need to harmonize the firing of accessibility
// events between platforms.
// https://crbug.com/897177
NotifyAccessibilityEvent(ax::mojom::Event::kWindowActivated);
if (GetWidget()->HasFocusManager()) {
// This function can be called before the focus manager has had a
// chance to set the focused view. In which case we should get the
// last focused view.
views::FocusManager* focus_manager = GetWidget()->GetFocusManager();
View* view_for_activation = focus_manager->GetFocusedView()
? focus_manager->GetFocusedView()
: focus_manager->GetStoredFocusView();
if (!view_for_activation || !view_for_activation->GetWidget()) {
view_for_activation = GetWidget()->GetRootView();
activation_client->ActivateWindow(content_window_);
} else if (view_for_activation == focus_manager->GetStoredFocusView()) {
// Update activation before restoring focus to prevent race condition.
// RestoreFocusedView() will activate the widget if Widget::IsActive()
// is false. Note that IsActive() checks ActivationClient for active
// widget, if ActivationClient is updated after focus, we risk running
// into an infinite loop.
// In practice, infinite loop does not happen because the window tree
// host avoids re-entrance to Activate() when the OS's window is active.
// But this is still a risk when two DNWAs both try to activate itself.
activation_client->ActivateWindow(
view_for_activation->GetWidget()->GetNativeView());
// When desktop native widget has modal transient child, we don't
// restore focused view here, as the modal transient child window will
// get activated and focused. Thus, we are not left with multiple
// focuses. For aura child widgets, since their views are managed by
// |focus_manager|, we then allow restoring focused view.
if (!wm::GetModalTransient(GetWidget()->GetNativeView())) {
focus_manager->RestoreFocusedView();
// Set to false if desktop native widget has activated activation
// change, so that aura window activation change focus restore
// operation can be ignored.
restore_focus_on_activate_ = false;
}
}
// Refreshes the focus info to IMF in case that IMF cached the old info
// about focused text input client when it was "inactive".
GetInputMethod()->OnFocus();
}
} else {
// TODO(nektar): We need to harmonize the firing of accessibility
// events between platforms.
// https://crbug.com/897177
NotifyAccessibilityEvent(ax::mojom::Event::kWindowDeactivated);
// If we're not active we need to deactivate the corresponding
// aura::Window. This way if a child widget is active it gets correctly
// deactivated (child widgets don't get native desktop activation changes,
// only aura activation changes).
aura::Window* active_window = activation_client->GetActiveWindow();
if (active_window) {
activation_client->DeactivateWindow(active_window);
GetInputMethod()->OnBlur();
}
}
// At this point the FocusController's state should have been appropriately
// updated, propagate the NativeWidget activation notification.
native_widget_delegate_->OnNativeWidgetActivationChanged(active);
}
void DesktopNativeWidgetAura::OnHostWillClose() {
// The host is going to close, but our DnD client may use it, so we need to
// detach the DnD client and destroy it to avoid uses after free.
aura::client::SetDragDropClient(host_->window(), nullptr);
drag_drop_client_.reset();
}
gfx::NativeWindow DesktopNativeWidgetAura::GetNativeWindow() const {
return content_window_;
}
void DesktopNativeWidgetAura::UpdateWindowTransparency() {
if (!desktop_window_tree_host_->ShouldUpdateWindowTransparency())
return;
const bool transparent =
desktop_window_tree_host_->ShouldWindowContentsBeTransparent();
auto* window_tree_host = desktop_window_tree_host_->AsWindowTreeHost();
window_tree_host->compositor()->SetBackgroundColor(
transparent ? SK_ColorTRANSPARENT : SK_ColorWHITE);
window_tree_host->window()->SetTransparent(transparent);
content_window_->SetTransparent(transparent);
// Regardless of transparency or not, this root content window will always
// fill its bounds completely, so set this flag to true to avoid an
// unecessary clear before update.
content_window_->SetFillsBoundsCompletely(true);
}
////////////////////////////////////////////////////////////////////////////////
// DesktopNativeWidgetAura, internal::NativeWidgetPrivate implementation:
void DesktopNativeWidgetAura::InitNativeWidget(Widget::InitParams params) {
ownership_ = params.ownership;
widget_type_ = params.type;
name_ = params.name;
if (ownership_ == Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET)
owned_native_widget_delegate =
base::WrapUnique(native_widget_delegate_.get());
content_window_->AcquireAllPropertiesFrom(
std::move(params.init_properties_container));
NativeWidgetAura::RegisterNativeWidgetForWindow(this, content_window_);
content_window_->SetType(GetAuraWindowTypeForWidgetType(params.type));
content_window_->Init(params.layer_type);
wm::SetShadowElevation(content_window_, wm::kShadowElevationNone);
if (!desktop_window_tree_host_) {
if (params.desktop_window_tree_host) {
desktop_window_tree_host_ = params.desktop_window_tree_host;
} else {
desktop_window_tree_host_ =
DesktopWindowTreeHost::Create(native_widget_delegate_.get(), this);
}
host_.reset(desktop_window_tree_host_->AsWindowTreeHost());
}
desktop_window_tree_host_->Init(params);
host_->window()->AddChild(content_window_);
host_->window()->SetProperty(kDesktopNativeWidgetAuraKey, this);
host_->window()->AddObserver(new RootWindowDestructionObserver(this));
// The WindowsModalityController event filter should be at the head of the
// pre target handlers list. This ensures that it handles input events first
// when modal windows are at the top of the Zorder.
if (widget_type_ == Widget::InitParams::TYPE_WINDOW)
window_modality_controller_ =
std::make_unique<wm::WindowModalityController>(host_->window());
// |root_window_event_filter_| must be created before
// OnWindowTreeHostCreated() is invoked.
// CEF sets focus to the window the user clicks down on.
// TODO(beng): see if we can't do this some other way. CEF seems a heavy-
// handed way of accomplishing focus.
// No event filter for aura::Env. Create CompoundEventFilter per
// WindowEventDispatcher.
root_window_event_filter_ = std::make_unique<wm::CompoundEventFilter>();
host_->window()->AddPreTargetHandler(root_window_event_filter_.get());
use_desktop_native_cursor_manager_ =
desktop_window_tree_host_->ShouldUseDesktopNativeCursorManager();
if (use_desktop_native_cursor_manager_) {
// The host's dispatcher must be added to |native_cursor_manager_| before
// OnNativeWidgetCreated() is called.
cursor_reference_count_++;
if (!native_cursor_manager_) {
native_cursor_manager_ =
desktop_window_tree_host_->GetSingletonDesktopNativeCursorManager();
}
native_cursor_manager_->AddHost(host());
if (!cursor_manager_) {
cursor_manager_ = new wm::CursorManager(
std::unique_ptr<wm::NativeCursorManager>(native_cursor_manager_));
cursor_manager_->SetDisplay(
display::Screen::GetScreen()->GetDisplayNearestWindow(
host_->window()));
if (features::IsSystemCursorSizeSupported()) {
native_cursor_manager_->InitCursorSizeObserver(cursor_manager_);
}
}
aura::client::SetCursorClient(host_->window(), cursor_manager_);
}
host_->window()->SetName(params.name);
content_window_->SetName("DesktopNativeWidgetAura - content window");
desktop_window_tree_host_->OnNativeWidgetCreated(params);
UpdateWindowTransparency();
capture_client_ = std::make_unique<DesktopCaptureClient>(host_->window());
wm::FocusController* focus_controller =
new wm::FocusController(new DesktopFocusRules(content_window_));
focus_client_.reset(focus_controller);
aura::client::SetFocusClient(host_->window(), focus_controller);
wm::SetActivationClient(host_->window(), focus_controller);
host_->window()->AddPreTargetHandler(focus_controller);
position_client_ = desktop_window_tree_host_->CreateScreenPositionClient();
drag_drop_client_ = desktop_window_tree_host_->CreateDragDropClient();
// Mus returns null from CreateDragDropClient().
if (drag_drop_client_)
aura::client::SetDragDropClient(host_->window(), drag_drop_client_.get());
wm::SetActivationDelegate(content_window_, this);
OnHostResized(host());
host_->AddObserver(this);
window_parenting_client_ =
std::make_unique<DesktopNativeWidgetAuraWindowParentingClient>(
host_->window());
drop_helper_ = std::make_unique<DropHelper>(GetWidget()->GetRootView());
aura::client::SetDragDropDelegate(content_window_, this);
if (params.type != Widget::InitParams::TYPE_TOOLTIP) {
tooltip_manager_ = std::make_unique<TooltipManagerAura>(this);
tooltip_controller_ = std::make_unique<corewm::TooltipController>(
desktop_window_tree_host_->CreateTooltip(),
wm::GetActivationClient(host_->window()));
wm::SetTooltipClient(host_->window(), tooltip_controller_.get());
host_->window()->AddPreTargetHandler(tooltip_controller_.get());
}
if (params.opacity == Widget::InitParams::WindowOpacity::kTranslucent &&
desktop_window_tree_host_->ShouldCreateVisibilityController()) {
visibility_controller_ = std::make_unique<wm::VisibilityController>();
aura::client::SetVisibilityClient(host_->window(),
visibility_controller_.get());
wm::SetChildWindowVisibilityChangesAnimated(host_->window());
}
if (params.type == Widget::InitParams::TYPE_WINDOW) {
focus_manager_event_handler_ = std::make_unique<FocusManagerEventHandler>(
GetWidget(), host_->window());
}
event_client_ = std::make_unique<DesktopEventClient>();
aura::client::SetEventClient(host_->window(), event_client_.get());
shadow_controller_ = std::make_unique<wm::ShadowController>(
wm::GetActivationClient(host_->window()), nullptr);
OnSizeConstraintsChanged();
window_reorderer_ = std::make_unique<WindowReorderer>(
content_window_, GetWidget()->GetRootView());
}
void DesktopNativeWidgetAura::OnWidgetInitDone() {
desktop_window_tree_host_->OnWidgetInitDone();
}
std::unique_ptr<NonClientFrameView>
DesktopNativeWidgetAura::CreateNonClientFrameView() {
return desktop_window_tree_host_->CreateNonClientFrameView();
}
bool DesktopNativeWidgetAura::ShouldUseNativeFrame() const {
return desktop_window_tree_host_->ShouldUseNativeFrame();
}
bool DesktopNativeWidgetAura::ShouldWindowContentsBeTransparent() const {
return desktop_window_tree_host_->ShouldWindowContentsBeTransparent();
}
void DesktopNativeWidgetAura::FrameTypeChanged() {
desktop_window_tree_host_->FrameTypeChanged();
UpdateWindowTransparency();
}
Widget* DesktopNativeWidgetAura::GetWidget() {
return native_widget_delegate_ ? native_widget_delegate_->AsWidget()
: nullptr;
}
const Widget* DesktopNativeWidgetAura::GetWidget() const {
return native_widget_delegate_ ? native_widget_delegate_->AsWidget()
: nullptr;
}
gfx::NativeView DesktopNativeWidgetAura::GetNativeView() const {
return content_window_;
}
Widget* DesktopNativeWidgetAura::GetTopLevelWidget() {
return GetWidget();
}
const ui::Compositor* DesktopNativeWidgetAura::GetCompositor() const {
return content_window_ ? content_window_->layer()->GetCompositor() : nullptr;
}
const ui::Layer* DesktopNativeWidgetAura::GetLayer() const {
return content_window_ ? content_window_->layer() : nullptr;
}
void DesktopNativeWidgetAura::ReorderNativeViews() {
if (!content_window_)
return;
// Reordering native views causes multiple changes to the window tree.
// Instantiate a ScopedPause to recompute occlusion once at the end of this
// scope rather than after each individual change.
// https://crbug.com/829918
aura::WindowOcclusionTracker::ScopedPause pause_occlusion;
window_reorderer_->ReorderChildWindows();
}
void DesktopNativeWidgetAura::ViewRemoved(View* view) {
DCHECK(drop_helper_.get() != nullptr);
drop_helper_->ResetTargetViewIfEquals(view);
}
void DesktopNativeWidgetAura::SetNativeWindowProperty(const char* name,
void* value) {
if (content_window_)
content_window_->SetNativeWindowProperty(name, value);
}
void* DesktopNativeWidgetAura::GetNativeWindowProperty(const char* name) const {
return content_window_ ? content_window_->GetNativeWindowProperty(name)
: nullptr;
}
TooltipManager* DesktopNativeWidgetAura::GetTooltipManager() const {
return tooltip_manager_.get();
}
void DesktopNativeWidgetAura::SetCapture() {
if (!content_window_)
return;
content_window_->SetCapture();
}
void DesktopNativeWidgetAura::ReleaseCapture() {
if (!content_window_)
return;
content_window_->ReleaseCapture();
}
bool DesktopNativeWidgetAura::HasCapture() const {
return content_window_ && content_window_->HasCapture() &&
desktop_window_tree_host_ && desktop_window_tree_host_->HasCapture();
}
ui::InputMethod* DesktopNativeWidgetAura::GetInputMethod() {
return host() ? host()->GetInputMethod() : nullptr;
}
void DesktopNativeWidgetAura::CenterWindow(const gfx::Size& size) {
if (desktop_window_tree_host_)
desktop_window_tree_host_->CenterWindow(size);
}
void DesktopNativeWidgetAura::GetWindowPlacement(
gfx::Rect* bounds,
ui::WindowShowState* maximized) const {
if (desktop_window_tree_host_)
desktop_window_tree_host_->GetWindowPlacement(bounds, maximized);
}
bool DesktopNativeWidgetAura::SetWindowTitle(const std::u16string& title) {
if (!desktop_window_tree_host_)
return false;
return desktop_window_tree_host_->SetWindowTitle(title);
}
void DesktopNativeWidgetAura::SetWindowIcons(const gfx::ImageSkia& window_icon,
const gfx::ImageSkia& app_icon) {
if (desktop_window_tree_host_)
desktop_window_tree_host_->SetWindowIcons(window_icon, app_icon);
if (content_window_)
NativeWidgetAura::AssignIconToAuraWindow(content_window_, window_icon,
app_icon);
}
const gfx::ImageSkia* DesktopNativeWidgetAura::GetWindowIcon() {
return nullptr;
}
const gfx::ImageSkia* DesktopNativeWidgetAura::GetWindowAppIcon() {
return nullptr;
}
void DesktopNativeWidgetAura::InitModalType(ui::ModalType modal_type) {
// 99% of the time, we should not be asked to create a
// DesktopNativeWidgetAura that is modal. We only support window modal
// dialogs on the same lines as non AURA.
desktop_window_tree_host_->InitModalType(modal_type);
}
gfx::Rect DesktopNativeWidgetAura::GetWindowBoundsInScreen() const {
return desktop_window_tree_host_
? desktop_window_tree_host_->GetWindowBoundsInScreen()
: gfx::Rect();
}
gfx::Rect DesktopNativeWidgetAura::GetClientAreaBoundsInScreen() const {
return desktop_window_tree_host_
? desktop_window_tree_host_->GetClientAreaBoundsInScreen()
: gfx::Rect();
}
gfx::Rect DesktopNativeWidgetAura::GetRestoredBounds() const {
return desktop_window_tree_host_
? desktop_window_tree_host_->GetRestoredBounds()
: gfx::Rect();
}
std::string DesktopNativeWidgetAura::GetWorkspace() const {
return desktop_window_tree_host_ ? desktop_window_tree_host_->GetWorkspace()
: std::string();
}
void DesktopNativeWidgetAura::SetBounds(const gfx::Rect& bounds) {
if (!desktop_window_tree_host_)
return;
desktop_window_tree_host_->SetBoundsInDIP(bounds);
}
void DesktopNativeWidgetAura::SetBoundsConstrained(const gfx::Rect& bounds) {
if (!content_window_)
return;
SetBounds(NativeWidgetPrivate::ConstrainBoundsToDisplayWorkArea(bounds));
}
void DesktopNativeWidgetAura::SetSize(const gfx::Size& size) {
if (desktop_window_tree_host_)
desktop_window_tree_host_->SetSize(size);
}
void DesktopNativeWidgetAura::StackAbove(gfx::NativeView native_view) {
if (desktop_window_tree_host_)
desktop_window_tree_host_->StackAbove(native_view);
}
void DesktopNativeWidgetAura::StackAtTop() {
if (desktop_window_tree_host_)
desktop_window_tree_host_->StackAtTop();
}
bool DesktopNativeWidgetAura::IsStackedAbove(gfx::NativeView native_view) {
return desktop_window_tree_host_ &&
desktop_window_tree_host_->IsStackedAbove(native_view);
}
void DesktopNativeWidgetAura::SetShape(
std::unique_ptr<Widget::ShapeRects> shape) {
if (desktop_window_tree_host_)
desktop_window_tree_host_->SetShape(std::move(shape));
}
void DesktopNativeWidgetAura::Close() {
if (desktop_window_tree_host_)
desktop_window_tree_host_->Close();
}
void DesktopNativeWidgetAura::CloseNow() {
if (desktop_window_tree_host_)
desktop_window_tree_host_->CloseNow();
}
void DesktopNativeWidgetAura::Show(ui::WindowShowState show_state,
const gfx::Rect& restore_bounds) {
if (!desktop_window_tree_host_)
return;
desktop_window_tree_host_->Show(show_state, restore_bounds);
}
void DesktopNativeWidgetAura::Hide() {
if (desktop_window_tree_host_)
desktop_window_tree_host_->AsWindowTreeHost()->Hide();
if (content_window_)
content_window_->Hide();
}
bool DesktopNativeWidgetAura::IsVisible() const {
// The objects checked here should be the same objects changed in
// ShowWithWindowState and ShowMaximizedWithBounds. For example, MS Windows
// platform code might show the desktop window tree host early, meaning we
// aren't fully visible as we haven't shown the content window. Callers may
// short-circuit a call to show this widget if they think its already visible.
return content_window_ && content_window_->TargetVisibility() &&
desktop_window_tree_host_ && desktop_window_tree_host_->IsVisible();
}
void DesktopNativeWidgetAura::Activate() {
if (desktop_window_tree_host_ && content_window_) {
bool was_tree_active = desktop_window_tree_host_->IsActive();
desktop_window_tree_host_->Activate();
// If the whole window tree host was already active,
// treat this as a request to focus |content_window_|.
//
// Note: it might make sense to always focus |content_window_|,
// since if client code is calling Widget::Activate() they probably
// want that particular widget to be activated, not just something
// within that widget hierarchy.
if (was_tree_active && focus_client_->GetFocusedWindow() != content_window_)
focus_client_->FocusWindow(content_window_);
}
}
void DesktopNativeWidgetAura::Deactivate() {
if (desktop_window_tree_host_)
desktop_window_tree_host_->Deactivate();
}
bool DesktopNativeWidgetAura::IsActive() const {
return content_window_ && desktop_window_tree_host_ &&
desktop_window_tree_host_->IsActive() &&
wm::IsActiveWindow(content_window_);
}
void DesktopNativeWidgetAura::PaintAsActiveChanged() {
desktop_window_tree_host_->PaintAsActiveChanged();
}
void DesktopNativeWidgetAura::SetZOrderLevel(ui::ZOrderLevel order) {
if (content_window_)
desktop_window_tree_host_->SetZOrderLevel(order);
}
ui::ZOrderLevel DesktopNativeWidgetAura::GetZOrderLevel() const {
if (desktop_window_tree_host_)
return desktop_window_tree_host_->GetZOrderLevel();
return ui::ZOrderLevel::kNormal;
}
void DesktopNativeWidgetAura::SetVisibleOnAllWorkspaces(bool always_visible) {
if (desktop_window_tree_host_)
desktop_window_tree_host_->SetVisibleOnAllWorkspaces(always_visible);
}
bool DesktopNativeWidgetAura::IsVisibleOnAllWorkspaces() const {
return desktop_window_tree_host_ &&
desktop_window_tree_host_->IsVisibleOnAllWorkspaces();
}
void DesktopNativeWidgetAura::Maximize() {
if (desktop_window_tree_host_)
desktop_window_tree_host_->Maximize();
}
void DesktopNativeWidgetAura::Minimize() {
if (desktop_window_tree_host_)
desktop_window_tree_host_->Minimize();
internal::RootView* root_view =
static_cast<internal::RootView*>(GetWidget()->GetRootView());
root_view->ResetEventHandlers();
}
bool DesktopNativeWidgetAura::IsMaximized() const {
return desktop_window_tree_host_ && desktop_window_tree_host_->IsMaximized();
}
bool DesktopNativeWidgetAura::IsMinimized() const {
return desktop_window_tree_host_ && desktop_window_tree_host_->IsMinimized();
}
void DesktopNativeWidgetAura::Restore() {
if (desktop_window_tree_host_)
desktop_window_tree_host_->Restore();
}
void DesktopNativeWidgetAura::SetFullscreen(bool fullscreen,
int64_t target_display_id) {
if (desktop_window_tree_host_)
desktop_window_tree_host_->SetFullscreen(fullscreen, target_display_id);
}
bool DesktopNativeWidgetAura::IsFullscreen() const {
return content_window_ && desktop_window_tree_host_->IsFullscreen();
}
void DesktopNativeWidgetAura::SetCanAppearInExistingFullscreenSpaces(
bool can_appear_in_existing_fullscreen_spaces) {}
void DesktopNativeWidgetAura::SetOpacity(float opacity) {
if (desktop_window_tree_host_)
desktop_window_tree_host_->SetOpacity(opacity);
}
void DesktopNativeWidgetAura::SetAspectRatio(const gfx::SizeF& aspect_ratio,
const gfx::Size& excluded_margin) {
if (desktop_window_tree_host_)
desktop_window_tree_host_->SetAspectRatio(aspect_ratio, excluded_margin);
}
void DesktopNativeWidgetAura::FlashFrame(bool flash_frame) {
if (desktop_window_tree_host_)
desktop_window_tree_host_->FlashFrame(flash_frame);
}
void DesktopNativeWidgetAura::RunShellDrag(
View* view,
std::unique_ptr<ui::OSExchangeData> data,
const gfx::Point& location,
int operation,
ui::mojom::DragEventSource source) {
if (!content_window_)
return;
views::RunShellDrag(content_window_, std::move(data), location, operation,
source);
}
void DesktopNativeWidgetAura::SchedulePaintInRect(const gfx::Rect& rect) {
if (content_window_)
content_window_->SchedulePaintInRect(rect);
}
void DesktopNativeWidgetAura::ScheduleLayout() {
// ScheduleDraw() triggers a callback to
// WindowDelegate::UpdateVisualState().
if (content_window_)
content_window_->ScheduleDraw();
}
void DesktopNativeWidgetAura::SetCursor(const ui::Cursor& cursor) {
cursor_ = cursor;
aura::client::CursorClient* cursor_client =
aura::client::GetCursorClient(host_->window());
if (cursor_client)
cursor_client->SetCursor(cursor);
}
bool DesktopNativeWidgetAura::IsMouseEventsEnabled() const {
// We explicitly check |host_| here because it can be null during the process
// of widget shutdown (even if |content_window_| is not), and must be valid to
// determine if mouse events are enabled.
if (!content_window_ || !host_)
return false;
aura::client::CursorClient* cursor_client =
aura::client::GetCursorClient(host_->window());
return cursor_client ? cursor_client->IsMouseEventsEnabled() : true;
}
bool DesktopNativeWidgetAura::IsMouseButtonDown() const {
return aura::Env::GetInstance()->IsMouseButtonDown();
}
void DesktopNativeWidgetAura::ClearNativeFocus() {
desktop_window_tree_host_->ClearNativeFocus();
if (ShouldActivate()) {
aura::client::GetFocusClient(content_window_)
->ResetFocusWithinActiveWindow(content_window_);
}
}
gfx::Rect DesktopNativeWidgetAura::GetWorkAreaBoundsInScreen() const {
return desktop_window_tree_host_
? desktop_window_tree_host_->GetWorkAreaBoundsInScreen()
: gfx::Rect();
}
bool DesktopNativeWidgetAura::IsMoveLoopSupported() const {
return desktop_window_tree_host_
? desktop_window_tree_host_->IsMoveLoopSupported()
: true;
}
Widget::MoveLoopResult DesktopNativeWidgetAura::RunMoveLoop(
const gfx::Vector2d& drag_offset,
Widget::MoveLoopSource source,
Widget::MoveLoopEscapeBehavior escape_behavior) {
if (!desktop_window_tree_host_)
return Widget::MoveLoopResult::kCanceled;
return desktop_window_tree_host_->RunMoveLoop(drag_offset, source,
escape_behavior);
}
void DesktopNativeWidgetAura::EndMoveLoop() {
if (desktop_window_tree_host_)
desktop_window_tree_host_->EndMoveLoop();
}
void DesktopNativeWidgetAura::SetVisibilityChangedAnimationsEnabled(
bool value) {
if (desktop_window_tree_host_)
desktop_window_tree_host_->SetVisibilityChangedAnimationsEnabled(value);
}
void DesktopNativeWidgetAura::SetVisibilityAnimationDuration(
const base::TimeDelta& duration) {
wm::SetWindowVisibilityAnimationDuration(content_window_, duration);
}
void DesktopNativeWidgetAura::SetVisibilityAnimationTransition(
Widget::VisibilityTransition transition) {
wm::WindowVisibilityAnimationTransition wm_transition = wm::ANIMATE_NONE;
switch (transition) {
case Widget::ANIMATE_SHOW:
wm_transition = wm::ANIMATE_SHOW;
break;
case Widget::ANIMATE_HIDE:
wm_transition = wm::ANIMATE_HIDE;
break;
case Widget::ANIMATE_BOTH:
wm_transition = wm::ANIMATE_BOTH;
break;
case Widget::ANIMATE_NONE:
wm_transition = wm::ANIMATE_NONE;
break;
}
wm::SetWindowVisibilityAnimationTransition(content_window_, wm_transition);
}
bool DesktopNativeWidgetAura::IsTranslucentWindowOpacitySupported() const {
return desktop_window_tree_host_ &&
desktop_window_tree_host_->IsTranslucentWindowOpacitySupported();
}
ui::GestureRecognizer* DesktopNativeWidgetAura::GetGestureRecognizer() {
return aura::Env::GetInstance()->gesture_recognizer();
}
ui::GestureConsumer* DesktopNativeWidgetAura::GetGestureConsumer() {
return content_window_;
}
void DesktopNativeWidgetAura::OnSizeConstraintsChanged() {
if (!desktop_window_tree_host_)
return;
NativeWidgetAura::SetResizeBehaviorFromDelegate(
GetWidget()->widget_delegate(), content_window_);
desktop_window_tree_host_->SizeConstraintsChanged();
}
void DesktopNativeWidgetAura::OnNativeViewHierarchyWillChange() {}
void DesktopNativeWidgetAura::OnNativeViewHierarchyChanged() {}
std::string DesktopNativeWidgetAura::GetName() const {
return name_;
}
////////////////////////////////////////////////////////////////////////////////
// DesktopNativeWidgetAura, aura::WindowDelegate implementation:
gfx::Size DesktopNativeWidgetAura::GetMinimumSize() const {
return native_widget_delegate_ ? native_widget_delegate_->GetMinimumSize()
: gfx::Size();
}
gfx::Size DesktopNativeWidgetAura::GetMaximumSize() const {
return native_widget_delegate_ ? native_widget_delegate_->GetMaximumSize()
: gfx::Size();
}
gfx::NativeCursor DesktopNativeWidgetAura::GetCursor(const gfx::Point& point) {
return cursor_;
}
int DesktopNativeWidgetAura::GetNonClientComponent(
const gfx::Point& point) const {
return native_widget_delegate_
? native_widget_delegate_->GetNonClientComponent(point)
: 0;
}
bool DesktopNativeWidgetAura::ShouldDescendIntoChildForEventHandling(
aura::Window* child,
const gfx::Point& location) {
return native_widget_delegate_
? native_widget_delegate_->ShouldDescendIntoChildForEventHandling(
content_window_->layer(), child, child->layer(), location)
: false;
}
bool DesktopNativeWidgetAura::CanFocus() {
return true;
}
void DesktopNativeWidgetAura::OnCaptureLost() {
if (native_widget_delegate_)
native_widget_delegate_->OnMouseCaptureLost();
}
void DesktopNativeWidgetAura::OnPaint(const ui::PaintContext& context) {
if (native_widget_delegate_) {
desktop_window_tree_host_->UpdateWindowShapeIfNeeded(context);
native_widget_delegate_->OnNativeWidgetPaint(context);
}
}
void DesktopNativeWidgetAura::OnDeviceScaleFactorChanged(
float old_device_scale_factor,
float new_device_scale_factor) {
GetWidget()->DeviceScaleFactorChanged(old_device_scale_factor,
new_device_scale_factor);
}
void DesktopNativeWidgetAura::OnWindowDestroying(aura::Window* window) {
// Cleanup happens in OnHostClosed().
}
void DesktopNativeWidgetAura::OnWindowDestroyed(aura::Window* window) {
// Cleanup happens in OnHostClosed(). We own |content_window_| (indirectly by
// way of |dispatcher_|) so there should be no need to do any processing
// here.
}
void DesktopNativeWidgetAura::OnWindowTargetVisibilityChanged(bool visible) {}
bool DesktopNativeWidgetAura::HasHitTestMask() const {
return native_widget_delegate_ ? native_widget_delegate_->HasHitTestMask()
: false;
}
void DesktopNativeWidgetAura::GetHitTestMask(SkPath* mask) const {
if (native_widget_delegate_)
native_widget_delegate_->GetHitTestMask(mask);
}
void DesktopNativeWidgetAura::UpdateVisualState() {
if (native_widget_delegate_)
native_widget_delegate_->LayoutRootViewIfNecessary();
}
////////////////////////////////////////////////////////////////////////////////
// DesktopNativeWidgetAura, ui::EventHandler implementation:
void DesktopNativeWidgetAura::OnKeyEvent(ui::KeyEvent* event) {
if (event->is_char()) {
// If a ui::InputMethod object is attached to the root window, character
// events are handled inside the object and are not passed to this function.
// If such object is not attached, character events might be sent (e.g. on
// Windows). In this case, we just skip these.
return;
}
// Renderer may send a key event back to us if the key event wasn't handled,
// and the window may be invisible by that time.
if (!content_window_->IsVisible())
return;
if (native_widget_delegate_)
native_widget_delegate_->OnKeyEvent(event);
}
void DesktopNativeWidgetAura::OnMouseEvent(ui::MouseEvent* event) {
DCHECK(content_window_->IsVisible());
if (tooltip_manager_.get())
tooltip_manager_->UpdateTooltip();
TooltipManagerAura::UpdateTooltipManagerForCapture(this);
if (native_widget_delegate_)
native_widget_delegate_->OnMouseEvent(event);
// WARNING: we may have been deleted.
}
void DesktopNativeWidgetAura::OnScrollEvent(ui::ScrollEvent* event) {
if (!native_widget_delegate_)
return;
if (event->type() == ui::ET_SCROLL) {
native_widget_delegate_->OnScrollEvent(event);
if (event->handled())
return;
// Convert unprocessed scroll events into wheel events.
ui::MouseWheelEvent mwe(*event->AsScrollEvent());
native_widget_delegate_->OnMouseEvent(&mwe);
if (mwe.handled())
event->SetHandled();
} else {
native_widget_delegate_->OnScrollEvent(event);
}
}
void DesktopNativeWidgetAura::OnGestureEvent(ui::GestureEvent* event) {
if (native_widget_delegate_)
native_widget_delegate_->OnGestureEvent(event);
}
base::StringPiece DesktopNativeWidgetAura::GetLogContext() const {
return "DesktopNativeWidgetAura";
}
////////////////////////////////////////////////////////////////////////////////
// DesktopNativeWidgetAura, wm::ActivationDelegate implementation:
bool DesktopNativeWidgetAura::ShouldActivate() const {
return (!should_activate_.has_value() || should_activate_.value()) &&
(native_widget_delegate_ && native_widget_delegate_->CanActivate());
}
////////////////////////////////////////////////////////////////////////////////
// DesktopNativeWidgetAura, wm::ActivationChangeObserver implementation:
void DesktopNativeWidgetAura::OnWindowActivated(
wm::ActivationChangeObserver::ActivationReason reason,
aura::Window* gained_active,
aura::Window* lost_active) {
DCHECK(content_window_ == gained_active || content_window_ == lost_active);
if (gained_active == content_window_ && restore_focus_on_activate_) {
restore_focus_on_activate_ = false;
// For OS_LINUX, desktop native widget may not be activated when child
// widgets gets aura activation changes. Only when desktop native widget is
// active, we can rely on aura activation to restore focused view.
if (GetWidget() && GetWidget()->IsActive())
GetWidget()->GetFocusManager()->RestoreFocusedView();
} else if (lost_active == content_window_ && GetWidget()->HasFocusManager()) {
DCHECK(!restore_focus_on_activate_);
restore_focus_on_activate_ = true;
// Pass in false so that ClearNativeFocus() isn't invoked.
if (GetWidget())
GetWidget()->GetFocusManager()->StoreFocusedView(false);
}
// This widget is considered active when both its window tree host and its
// content window are active. When the window tree host gains and looses
// activation, the window tree host calls into HandleActivationChanged() which
// notifies delegates of the activation change.
// However the widget's content window can still be deactivated and activated
// while the window tree host remains active. For e.g. if a child widget is
// spawned (e.g. a bubble) the child's content window is activated and the
// root content window is deactivated. This is a valid state since the window
// tree host should remain active while the child is active. The child bubble
// can then be closed and activation returns to the root content window - all
// without the window tree host's activation state changing.
// As the activation state of the content window changes we must ensure that
// we notify this widget's delegate. Do this here for cases where we are not
// handling an activation change in HandleActivationChanged() since delegates
// will be notified of the change there directly.
const bool content_window_activated = content_window_ == gained_active;
const bool tree_host_active = desktop_window_tree_host_->IsActive();
// TODO(crbug.com/1300567): Update focus rules to avoid focusing the desktop
// widget's content window if its window tree host is not active.
if (native_widget_delegate_ && !should_activate_.has_value() &&
(tree_host_active || !content_window_activated)) {
native_widget_delegate_->OnNativeWidgetActivationChanged(
content_window_activated);
}
// Give the native widget a chance to handle any specific changes it needs.
desktop_window_tree_host_->OnActiveWindowChanged(content_window_activated);
}
////////////////////////////////////////////////////////////////////////////////
// DesktopNativeWidgetAura, aura::client::FocusChangeObserver implementation:
void DesktopNativeWidgetAura::OnWindowFocused(aura::Window* gained_focus,
aura::Window* lost_focus) {
if (!native_widget_delegate_)
return;
if (content_window_ == gained_focus) {
native_widget_delegate_->OnNativeFocus();
} else if (content_window_ == lost_focus) {
native_widget_delegate_->OnNativeBlur();
}
}
////////////////////////////////////////////////////////////////////////////////
// DesktopNativeWidgetAura, aura::WindowDragDropDelegate implementation:
void DesktopNativeWidgetAura::OnDragEntered(const ui::DropTargetEvent& event) {
DCHECK(drop_helper_.get() != nullptr);
last_drop_operation_ = drop_helper_->OnDragOver(
event.data(), event.location(), event.source_operations());
}
aura::client::DragUpdateInfo DesktopNativeWidgetAura::OnDragUpdated(
const ui::DropTargetEvent& event) {
DCHECK(drop_helper_.get() != nullptr);
last_drop_operation_ = drop_helper_->OnDragOver(
event.data(), event.location(), event.source_operations());
return aura::client::DragUpdateInfo(
last_drop_operation_,
ui::DataTransferEndpoint(ui::EndpointType::kDefault));
}
void DesktopNativeWidgetAura::OnDragExited() {
DCHECK(drop_helper_.get() != nullptr);
drop_helper_->OnDragExit();
}
aura::client::DragDropDelegate::DropCallback
DesktopNativeWidgetAura::GetDropCallback(const ui::DropTargetEvent& event) {
DCHECK(drop_helper_);
auto drop_helper_cb = drop_helper_->GetDropCallback(
event.data(), event.location(), last_drop_operation_);
return base::BindOnce(&DesktopNativeWidgetAura::PerformDrop,
weak_ptr_factory_.GetWeakPtr(),
std::move(drop_helper_cb));
}
////////////////////////////////////////////////////////////////////////////////
// DesktopNativeWidgetAura, aura::WindowTreeHostObserver implementation:
void DesktopNativeWidgetAura::OnHostCloseRequested(aura::WindowTreeHost* host) {
GetWidget()->Close();
}
void DesktopNativeWidgetAura::OnHostResized(aura::WindowTreeHost* host) {
// Don't update the bounds of the child layers when animating closed. If we
// did it would force a paint, which we don't want. We don't want the paint
// as we can't assume any of the children are valid.
if (desktop_window_tree_host_->IsAnimatingClosed())
return;
if (!native_widget_delegate_)
return;
gfx::Rect new_bounds = gfx::Rect(host->window()->bounds().size());
content_window_->SetBounds(new_bounds);
native_widget_delegate_->OnNativeWidgetSizeChanged(new_bounds.size());
}
void DesktopNativeWidgetAura::OnHostWorkspaceChanged(
aura::WindowTreeHost* host) {
if (native_widget_delegate_)
native_widget_delegate_->OnNativeWidgetWorkspaceChanged();
}
void DesktopNativeWidgetAura::OnHostMovedInPixels(aura::WindowTreeHost* host) {
TRACE_EVENT0("views", "DesktopNativeWidgetAura::OnHostMovedInPixels");
if (native_widget_delegate_)
native_widget_delegate_->OnNativeWidgetMove();
}
////////////////////////////////////////////////////////////////////////////////
// DesktopNativeWidgetAura, private:
void DesktopNativeWidgetAura::RootWindowDestroyed() {
cursor_reference_count_--;
if (cursor_reference_count_ == 0) {
// We are the last DesktopNativeWidgetAura instance, and we are responsible
// for cleaning up |cursor_manager_|.
delete cursor_manager_;
native_cursor_manager_ = nullptr;
cursor_manager_ = nullptr;
}
}
void DesktopNativeWidgetAura::PerformDrop(
views::DropHelper::DropCallback drop_cb,
std::unique_ptr<ui::OSExchangeData> data,
ui::mojom::DragOperation& output_drag_op,
std::unique_ptr<ui::LayerTreeOwner> drag_image_layer_owner) {
if (ShouldActivate())
Activate();
if (drop_cb)
std::move(drop_cb).Run(std::move(data), output_drag_op,
std::move(drag_image_layer_owner));
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_native_widget_aura.cc | C++ | unknown | 56,799 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_NATIVE_WIDGET_AURA_H_
#define UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_NATIVE_WIDGET_AURA_H_
#include <memory>
#include <string>
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/strings/string_piece.h"
#include "ui/aura/client/drag_drop_delegate.h"
#include "ui/aura/client/focus_change_observer.h"
#include "ui/aura/window_delegate.h"
#include "ui/aura/window_tree_host_observer.h"
#include "ui/base/cursor/cursor.h"
#include "ui/views/widget/drop_helper.h"
#include "ui/views/widget/native_widget_private.h"
#include "ui/wm/core/compound_event_filter.h"
#include "ui/wm/public/activation_change_observer.h"
#include "ui/wm/public/activation_delegate.h"
namespace aura {
class WindowEventDispatcher;
class WindowTreeHost;
namespace client {
class DragDropClient;
class ScreenPositionClient;
class WindowParentingClient;
} // namespace client
} // namespace aura
namespace wm {
class CompoundEventFilter;
class CursorManager;
class FocusController;
class ShadowController;
class VisibilityController;
class WindowModalityController;
} // namespace wm
namespace views {
namespace corewm {
class TooltipController;
}
class DesktopCaptureClient;
class DesktopEventClient;
class DesktopNativeCursorManager;
class DesktopWindowTreeHost;
class FocusManagerEventHandler;
class TooltipManagerAura;
class WindowReorderer;
// DesktopNativeWidgetAura handles top-level widgets on Windows, Linux, and
// Chrome OS with mash.
class VIEWS_EXPORT DesktopNativeWidgetAura
: public internal::NativeWidgetPrivate,
public aura::WindowDelegate,
public wm::ActivationDelegate,
public wm::ActivationChangeObserver,
public aura::client::FocusChangeObserver,
public aura::client::DragDropDelegate,
public aura::WindowTreeHostObserver {
public:
explicit DesktopNativeWidgetAura(internal::NativeWidgetDelegate* delegate);
DesktopNativeWidgetAura(const DesktopNativeWidgetAura&) = delete;
DesktopNativeWidgetAura& operator=(const DesktopNativeWidgetAura&) = delete;
~DesktopNativeWidgetAura() override;
// Maps from window to DesktopNativeWidgetAura. |window| must be a root
// window.
static DesktopNativeWidgetAura* ForWindow(aura::Window* window);
// Called by our DesktopWindowTreeHost after it has deleted native resources;
// this is the signal that we should start our shutdown.
virtual void OnHostClosed();
// TODO(beng): remove this method and replace with an implementation of
// WindowDestroying() that takes the window being destroyed.
// Called from ~DesktopWindowTreeHost. This takes the WindowEventDispatcher
// as by the time we get here |dispatcher_| is NULL.
virtual void OnDesktopWindowTreeHostDestroyed(aura::WindowTreeHost* host);
wm::CompoundEventFilter* root_window_event_filter() {
return root_window_event_filter_.get();
}
aura::WindowTreeHost* host() { return host_.get(); }
DesktopWindowTreeHost* desktop_window_tree_host_for_testing() {
return desktop_window_tree_host_.get();
}
aura::Window* content_window() { return content_window_; }
views::corewm::TooltipController* tooltip_controller();
Widget::InitParams::Type widget_type() const { return widget_type_; }
// Ensures that the correct window is activated/deactivated based on whether
// we are being activated/deactivated.
void HandleActivationChanged(bool active);
// Called before the window tree host will close.
void OnHostWillClose();
// Overridden from internal::NativeWidgetPrivate:
gfx::NativeWindow GetNativeWindow() const override;
// Configures the appropriate aura::Windows based on the
// DesktopWindowTreeHost's transparency.
void UpdateWindowTransparency();
base::WeakPtr<internal::NativeWidgetPrivate> GetWeakPtr() override;
protected:
// internal::NativeWidgetPrivate:
void InitNativeWidget(Widget::InitParams params) override;
void OnWidgetInitDone() override;
std::unique_ptr<NonClientFrameView> CreateNonClientFrameView() override;
bool ShouldUseNativeFrame() const override;
bool ShouldWindowContentsBeTransparent() const override;
void FrameTypeChanged() override;
Widget* GetWidget() override;
const Widget* GetWidget() const override;
gfx::NativeView GetNativeView() const override;
Widget* GetTopLevelWidget() override;
const ui::Compositor* GetCompositor() const override;
const ui::Layer* GetLayer() const override;
void ReorderNativeViews() override;
void ViewRemoved(View* view) override;
void SetNativeWindowProperty(const char* name, void* value) override;
void* GetNativeWindowProperty(const char* name) const override;
TooltipManager* GetTooltipManager() const override;
void SetCapture() override;
void ReleaseCapture() override;
bool HasCapture() const override;
ui::InputMethod* GetInputMethod() override;
void CenterWindow(const gfx::Size& size) override;
void GetWindowPlacement(gfx::Rect* bounds,
ui::WindowShowState* maximized) const override;
bool SetWindowTitle(const std::u16string& title) override;
void SetWindowIcons(const gfx::ImageSkia& window_icon,
const gfx::ImageSkia& app_icon) override;
const gfx::ImageSkia* GetWindowIcon() override;
const gfx::ImageSkia* GetWindowAppIcon() override;
void InitModalType(ui::ModalType modal_type) override;
gfx::Rect GetWindowBoundsInScreen() const override;
gfx::Rect GetClientAreaBoundsInScreen() const override;
gfx::Rect GetRestoredBounds() const override;
std::string GetWorkspace() const override;
void SetBounds(const gfx::Rect& bounds) override;
void SetBoundsConstrained(const gfx::Rect& bounds) override;
void SetSize(const gfx::Size& size) override;
void StackAbove(gfx::NativeView native_view) override;
void StackAtTop() override;
bool IsStackedAbove(gfx::NativeView native_view) override;
void SetShape(std::unique_ptr<Widget::ShapeRects> shape) override;
void Close() override;
void CloseNow() override;
void Show(ui::WindowShowState show_state,
const gfx::Rect& restore_bounds) override;
void Hide() override;
bool IsVisible() const override;
void Activate() override;
void Deactivate() override;
bool IsActive() const override;
void PaintAsActiveChanged() override;
void SetZOrderLevel(ui::ZOrderLevel order) override;
ui::ZOrderLevel GetZOrderLevel() const override;
void SetVisibleOnAllWorkspaces(bool always_visible) override;
bool IsVisibleOnAllWorkspaces() const override;
void Maximize() override;
void Minimize() override;
bool IsMaximized() const override;
bool IsMinimized() const override;
void Restore() override;
void SetFullscreen(bool fullscreen, int64_t target_display_id) override;
bool IsFullscreen() const override;
void SetCanAppearInExistingFullscreenSpaces(
bool can_appear_in_existing_fullscreen_spaces) override;
void SetOpacity(float opacity) override;
// See NativeWidgetPrivate::SetAspectRatio for more information.
void SetAspectRatio(const gfx::SizeF& aspect_ratio,
const gfx::Size& excluded_margin) override;
void FlashFrame(bool flash_frame) override;
void RunShellDrag(View* view,
std::unique_ptr<ui::OSExchangeData> data,
const gfx::Point& location,
int operation,
ui::mojom::DragEventSource source) override;
void SchedulePaintInRect(const gfx::Rect& rect) override;
void ScheduleLayout() override;
void SetCursor(const ui::Cursor& cursor) override;
bool IsMouseEventsEnabled() const override;
bool IsMouseButtonDown() const override;
void ClearNativeFocus() override;
gfx::Rect GetWorkAreaBoundsInScreen() const override;
bool IsMoveLoopSupported() const override;
Widget::MoveLoopResult RunMoveLoop(
const gfx::Vector2d& drag_offset,
Widget::MoveLoopSource source,
Widget::MoveLoopEscapeBehavior escape_behavior) override;
void EndMoveLoop() override;
void SetVisibilityChangedAnimationsEnabled(bool value) override;
void SetVisibilityAnimationDuration(const base::TimeDelta& duration) override;
void SetVisibilityAnimationTransition(
Widget::VisibilityTransition transition) override;
bool IsTranslucentWindowOpacitySupported() const override;
ui::GestureRecognizer* GetGestureRecognizer() override;
ui::GestureConsumer* GetGestureConsumer() override;
void OnSizeConstraintsChanged() override;
void OnNativeViewHierarchyWillChange() override;
void OnNativeViewHierarchyChanged() override;
std::string GetName() const override;
// aura::WindowDelegate:
gfx::Size GetMinimumSize() const override;
gfx::Size GetMaximumSize() const override;
void OnBoundsChanged(const gfx::Rect& old_bounds,
const gfx::Rect& new_bounds) override {}
gfx::NativeCursor GetCursor(const gfx::Point& point) override;
int GetNonClientComponent(const gfx::Point& point) const override;
bool ShouldDescendIntoChildForEventHandling(
aura::Window* child,
const gfx::Point& location) override;
bool CanFocus() override;
void OnCaptureLost() override;
void OnPaint(const ui::PaintContext& context) override;
void OnDeviceScaleFactorChanged(float old_device_scale_factor,
float new_device_scale_factor) override;
void OnWindowDestroying(aura::Window* window) override;
void OnWindowDestroyed(aura::Window* window) override;
void OnWindowTargetVisibilityChanged(bool visible) override;
bool HasHitTestMask() const override;
void GetHitTestMask(SkPath* mask) const override;
void UpdateVisualState() override;
// ui::EventHandler:
void OnKeyEvent(ui::KeyEvent* event) override;
void OnMouseEvent(ui::MouseEvent* event) override;
void OnScrollEvent(ui::ScrollEvent* event) override;
void OnGestureEvent(ui::GestureEvent* event) override;
base::StringPiece GetLogContext() const override;
// wm::ActivationDelegate:
bool ShouldActivate() const override;
// wm::ActivationChangeObserver:
void OnWindowActivated(wm::ActivationChangeObserver::ActivationReason reason,
aura::Window* gained_active,
aura::Window* lost_active) override;
// aura::client::FocusChangeObserver:
void OnWindowFocused(aura::Window* gained_focus,
aura::Window* lost_focus) override;
// ura::client::DragDropDelegate:
void OnDragEntered(const ui::DropTargetEvent& event) override;
aura::client::DragUpdateInfo OnDragUpdated(
const ui::DropTargetEvent& event) override;
void OnDragExited() override;
aura::client::DragDropDelegate::DropCallback GetDropCallback(
const ui::DropTargetEvent& event) override;
// aura::WindowTreeHostObserver:
void OnHostCloseRequested(aura::WindowTreeHost* host) override;
void OnHostResized(aura::WindowTreeHost* host) override;
void OnHostWorkspaceChanged(aura::WindowTreeHost* host) override;
void OnHostMovedInPixels(aura::WindowTreeHost* host) override;
private:
friend class RootWindowDestructionObserver;
void RootWindowDestroyed();
// Notify the root view of our widget of a native accessibility event.
void NotifyAccessibilityEvent(ax::mojom::Event event_type);
void PerformDrop(views::DropHelper::DropCallback drop_cb,
std::unique_ptr<ui::OSExchangeData> data,
ui::mojom::DragOperation& output_drag_op,
std::unique_ptr<ui::LayerTreeOwner> drag_image_layer_owner);
std::unique_ptr<aura::WindowTreeHost> host_;
// DanglingUntriaged because it is assigned a DanglingUntriaged pointer.
raw_ptr<DesktopWindowTreeHost, DanglingUntriaged> desktop_window_tree_host_;
// See class documentation for Widget in widget.h for a note about ownership.
Widget::InitParams::Ownership ownership_ =
Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET;
// Internal name.
std::string name_;
std::unique_ptr<DesktopCaptureClient> capture_client_;
// This is the return value from GetNativeView().
// WARNING: this may be NULL, in particular during shutdown it becomes NULL.
raw_ptr<aura::Window, DanglingUntriaged> content_window_;
base::WeakPtr<internal::NativeWidgetDelegate> native_widget_delegate_;
// This is a unique ptr to enforce scenarios where NativeWidget
// will own the NativeWidgetDelegate.
// Used for ownership model: NativeWidgetOwnsWidget.
std::unique_ptr<internal::NativeWidgetDelegate> owned_native_widget_delegate;
std::unique_ptr<wm::FocusController> focus_client_;
std::unique_ptr<aura::client::ScreenPositionClient> position_client_;
std::unique_ptr<aura::client::DragDropClient> drag_drop_client_;
std::unique_ptr<aura::client::WindowParentingClient> window_parenting_client_;
std::unique_ptr<DesktopEventClient> event_client_;
std::unique_ptr<FocusManagerEventHandler> focus_manager_event_handler_;
// Toplevel event filter which dispatches to other event filters.
std::unique_ptr<wm::CompoundEventFilter> root_window_event_filter_;
std::unique_ptr<DropHelper> drop_helper_;
int last_drop_operation_ = ui::DragDropTypes::DRAG_NONE;
std::unique_ptr<corewm::TooltipController> tooltip_controller_;
std::unique_ptr<TooltipManagerAura> tooltip_manager_;
std::unique_ptr<wm::VisibilityController> visibility_controller_;
std::unique_ptr<wm::WindowModalityController> window_modality_controller_;
bool restore_focus_on_activate_ = false;
// This flag is used to ensure that the activation client correctly sees
// whether this widget should receive activation when handling an activation
// change event in `HandleActivationChanged()`.This is needed as the widget
// may not have propagated its new activation state to its delegate before the
// activation client decides which window to activate next.
absl::optional<bool> should_activate_;
gfx::NativeCursor cursor_;
// We must manually reference count the number of users of |cursor_manager_|
// because the cursors created by |cursor_manager_| are shared among the
// DNWAs. We can't just stuff this in a LazyInstance because we need to
// destroy this as the last DNWA happens; we can't put it off until
// (potentially) after we tear down the X11 connection because that's a
// crash.
static int cursor_reference_count_;
static wm::CursorManager* cursor_manager_;
static DesktopNativeCursorManager* native_cursor_manager_;
std::unique_ptr<wm::ShadowController> shadow_controller_;
// Reorders child windows of |window_| associated with a view based on the
// order of the associated views in the widget's view hierarchy.
std::unique_ptr<WindowReorderer> window_reorderer_;
// See class documentation for Widget in widget.h for a note about type.
Widget::InitParams::Type widget_type_ = Widget::InitParams::TYPE_WINDOW;
// See DesktopWindowTreeHost::ShouldUseDesktopNativeCursorManager().
bool use_desktop_native_cursor_manager_ = false;
// The following factory is used to provide references to the
// DesktopNativeWidgetAura instance and used for calls to close to run drop
// callback.
base::WeakPtrFactory<DesktopNativeWidgetAura> weak_ptr_factory_{this};
};
} // namespace views
#endif // UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_NATIVE_WIDGET_AURA_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_native_widget_aura.h | C++ | unknown | 15,468 |
// 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/widget/desktop_aura/desktop_native_widget_aura.h"
#include "ui/views/test/native_widget_factory.h"
#include "ui/views/test/widget_test.h"
#include "ui/wm/public/activation_client.h"
namespace views::test {
using DesktopNativeWidgetAuraTest = DesktopWidgetTestInteractive;
// This tests ensures that when a widget with an active child widget are
// showing, and a new widget is shown, the widget and its child are both
// deactivated. This covers a regression where deactivating the child widget
// would activate the parent widget at the same time the new widget receives
// activation, causing windows to lock when minimizing / maximizing (see
// crbug.com/1284537).
TEST_F(DesktopNativeWidgetAuraTest, WidgetsWithChildrenDeactivateCorrectly) {
auto widget1 = std::make_unique<Widget>();
Widget::InitParams params1(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
params1.context = GetContext();
params1.native_widget = new DesktopNativeWidgetAura(widget1.get());
params1.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget1->Init(std::move(params1));
auto widget1_child = std::make_unique<Widget>();
Widget::InitParams params_child(Widget::InitParams::TYPE_BUBBLE);
params_child.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params_child.parent = widget1->GetNativeView();
params_child.native_widget =
CreatePlatformNativeWidgetImpl(widget1_child.get(), kDefault, nullptr);
widget1_child->Init(std::move(params_child));
widget1_child->widget_delegate()->SetCanActivate(true);
auto widget2 = std::make_unique<Widget>();
Widget::InitParams params2(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
params2.context = GetContext();
params2.native_widget = new DesktopNativeWidgetAura(widget2.get());
params2.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget2->Init(std::move(params2));
auto* activation_client1 =
wm::GetActivationClient(widget1->GetNativeView()->GetRootWindow());
auto* activation_client1_child =
wm::GetActivationClient(widget1_child->GetNativeView()->GetRootWindow());
auto* activation_client2 =
wm::GetActivationClient(widget2->GetNativeView()->GetRootWindow());
// All widgets belonging to the same tree host should share an activation
// client. Widgets belonging to different tree hosts should have different
// activation clients.
ASSERT_EQ(activation_client1, activation_client1_child);
ASSERT_NE(activation_client1, activation_client2);
const auto show_widget = [&](Widget* target) {
target->Show();
views::test::WidgetActivationWaiter(widget1.get(), target == widget1.get())
.Wait();
views::test::WidgetActivationWaiter(widget1_child.get(),
target == widget1_child.get())
.Wait();
views::test::WidgetActivationWaiter(widget2.get(), target == widget2.get())
.Wait();
};
show_widget(widget1.get());
EXPECT_TRUE(widget1->IsActive());
EXPECT_FALSE(widget1_child->IsActive());
EXPECT_FALSE(widget2->IsActive());
EXPECT_EQ(activation_client1->GetActiveWindow(), widget1->GetNativeView());
EXPECT_EQ(activation_client2->GetActiveWindow(), nullptr);
// The child widget should become activate and its parent should deactivate.
show_widget(widget1_child.get());
EXPECT_FALSE(widget1->IsActive());
EXPECT_TRUE(widget1_child->IsActive());
EXPECT_FALSE(widget2->IsActive());
EXPECT_EQ(activation_client1->GetActiveWindow(),
widget1_child->GetNativeView());
EXPECT_EQ(activation_client2->GetActiveWindow(), nullptr);
// Showing the second widget should deactivate both the first widget and its
// child.
show_widget(widget2.get());
EXPECT_FALSE(widget1->IsActive());
EXPECT_FALSE(widget1_child->IsActive());
EXPECT_TRUE(widget2->IsActive());
EXPECT_EQ(activation_client1->GetActiveWindow(), nullptr);
EXPECT_EQ(activation_client2->GetActiveWindow(), widget2->GetNativeView());
widget1_child->CloseNow();
widget1->CloseNow();
widget2->CloseNow();
}
// Tests to make sure that a widget that shows an active child has activation
// correctly propagate to the child's content window. This also tests to make
// sure that when this child window is closed, and the desktop widget's window
// tree host remains active, the widget's content window has its activation
// state restored. This tests against a regression where the desktop widget
// would not receive activation when it's child bubbles were closed (see
// crbug.com/1294404).
TEST_F(DesktopNativeWidgetAuraTest,
DesktopWidgetsRegainFocusWhenChildWidgetClosed) {
auto widget = std::make_unique<Widget>();
Widget::InitParams params(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
params.context = GetContext();
params.native_widget = new DesktopNativeWidgetAura(widget.get());
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget->Init(std::move(params));
auto widget_child = std::make_unique<Widget>();
Widget::InitParams params_child(Widget::InitParams::TYPE_BUBBLE);
params_child.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params_child.parent = widget->GetNativeView();
params_child.native_widget =
CreatePlatformNativeWidgetImpl(widget_child.get(), kDefault, nullptr);
widget_child->Init(std::move(params_child));
widget_child->widget_delegate()->SetCanActivate(true);
auto* activation_client =
wm::GetActivationClient(widget->GetNativeView()->GetRootWindow());
auto* activation_client_child =
wm::GetActivationClient(widget_child->GetNativeView()->GetRootWindow());
// All widgets belonging to the same tree host should share an activation
// client.
ASSERT_EQ(activation_client, activation_client_child);
widget->Show();
views::test::WidgetActivationWaiter(widget.get(), true).Wait();
views::test::WidgetActivationWaiter(widget_child.get(), false).Wait();
EXPECT_TRUE(widget->IsActive());
EXPECT_FALSE(widget_child->IsActive());
EXPECT_EQ(activation_client->GetActiveWindow(), widget->GetNativeView());
widget_child->Show();
views::test::WidgetActivationWaiter(widget.get(), false).Wait();
views::test::WidgetActivationWaiter(widget_child.get(), true).Wait();
EXPECT_FALSE(widget->IsActive());
EXPECT_TRUE(widget_child->IsActive());
EXPECT_EQ(activation_client->GetActiveWindow(),
widget_child->GetNativeView());
widget_child->Close();
views::test::WidgetActivationWaiter(widget.get(), true).Wait();
views::test::WidgetActivationWaiter(widget_child.get(), false).Wait();
EXPECT_TRUE(widget->IsActive());
EXPECT_FALSE(widget_child->IsActive());
EXPECT_EQ(activation_client->GetActiveWindow(), widget->GetNativeView());
widget_child->CloseNow();
widget->CloseNow();
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_native_widget_aura_interactive_uitest.cc | C++ | unknown | 6,963 |
// 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/widget/desktop_aura/desktop_native_widget_aura.h"
#include <memory>
#include <utility>
#include "base/functional/bind.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/task/single_thread_task_runner.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "ui/aura/client/aura_constants.h"
#include "ui/aura/client/cursor_client.h"
#include "ui/aura/client/focus_client.h"
#include "ui/aura/client/window_parenting_client.h"
#include "ui/aura/env.h"
#include "ui/aura/test/test_window_delegate.h"
#include "ui/aura/test/window_occlusion_tracker_test_api.h"
#include "ui/aura/window.h"
#include "ui/aura/window_tree_host.h"
#include "ui/base/cursor/mojom/cursor_type.mojom-shared.h"
#include "ui/display/screen.h"
#include "ui/events/event_processor.h"
#include "ui/events/event_utils.h"
#include "ui/events/test/event_generator.h"
#include "ui/views/test/native_widget_factory.h"
#include "ui/views/test/test_views.h"
#include "ui/views/test/test_views_delegate.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/view_constants_aura.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/dialog_delegate.h"
#if BUILDFLAG(IS_WIN)
#include <windows.h>
#include "ui/base/view_prop.h"
#include "ui/base/win/window_event_target.h"
#include "ui/views/win/hwnd_util.h"
#endif
namespace views::test {
using DesktopNativeWidgetAuraTest = DesktopWidgetTest;
// Verifies creating a Widget with a parent that is not in a RootWindow doesn't
// crash.
TEST_F(DesktopNativeWidgetAuraTest, CreateWithParentNotInRootWindow) {
std::unique_ptr<aura::Window> window(new aura::Window(nullptr));
window->Init(ui::LAYER_NOT_DRAWN);
Widget widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.bounds = gfx::Rect(0, 0, 200, 200);
params.parent = window.get();
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget.Init(std::move(params));
}
// Verifies that the Aura windows making up a widget instance have the correct
// bounds after the widget is resized.
TEST_F(DesktopNativeWidgetAuraTest, DesktopAuraWindowSizeTest) {
Widget widget;
// On Linux we test this with popup windows because the WM may ignore the size
// suggestion for normal windows.
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP);
#else
Widget::InitParams init_params =
CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
#endif
init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget.Init(std::move(init_params));
gfx::Rect bounds(0, 0, 100, 100);
widget.SetBounds(bounds);
widget.Show();
EXPECT_EQ(bounds.ToString(),
widget.GetNativeView()->GetRootWindow()->bounds().ToString());
EXPECT_EQ(bounds.ToString(), widget.GetNativeView()->bounds().ToString());
EXPECT_EQ(bounds.ToString(),
widget.GetNativeView()->parent()->bounds().ToString());
gfx::Rect new_bounds(0, 0, 200, 200);
widget.SetBounds(new_bounds);
EXPECT_EQ(new_bounds.ToString(),
widget.GetNativeView()->GetRootWindow()->bounds().ToString());
EXPECT_EQ(new_bounds.ToString(), widget.GetNativeView()->bounds().ToString());
EXPECT_EQ(new_bounds.ToString(),
widget.GetNativeView()->parent()->bounds().ToString());
}
// Verifies GetNativeView() is initially hidden. If the native view is initially
// shown then animations can not be disabled.
TEST_F(DesktopNativeWidgetAuraTest, NativeViewInitiallyHidden) {
Widget widget;
Widget::InitParams init_params =
CreateParams(Widget::InitParams::TYPE_WINDOW);
init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget.Init(std::move(init_params));
EXPECT_FALSE(widget.GetNativeView()->IsVisible());
}
// Verifies that the native view isn't activated if Widget requires that.
TEST_F(DesktopNativeWidgetAuraTest, NativeViewNoActivate) {
// Widget of TYPE_POPUP can't be activated.
Widget widget;
Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP);
init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget.Init(std::move(init_params));
EXPECT_FALSE(widget.CanActivate());
EXPECT_EQ(nullptr, aura::client::GetFocusClient(widget.GetNativeWindow())
->GetFocusedWindow());
}
#if BUILDFLAG(IS_WIN)
// Verifies that if the DesktopWindowTreeHost is already shown, the native view
// still reports not visible as we haven't shown the content window.
TEST_F(DesktopNativeWidgetAuraTest, WidgetNotVisibleOnlyWindowTreeHostShown) {
Widget widget;
Widget::InitParams init_params =
CreateParams(Widget::InitParams::TYPE_WINDOW);
init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget.Init(std::move(init_params));
ShowWindow(widget.GetNativeView()->GetHost()->GetAcceleratedWidget(),
SW_SHOWNORMAL);
EXPECT_FALSE(widget.IsVisible());
}
#endif
TEST_F(DesktopNativeWidgetAuraTest, DesktopAuraWindowShowFrameless) {
Widget widget;
Widget::InitParams init_params =
CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget.Init(std::move(init_params));
// Make sure that changing frame type doesn't crash when there's no non-client
// view.
ASSERT_EQ(nullptr, widget.non_client_view());
widget.DebugToggleFrameType();
widget.Show();
#if BUILDFLAG(IS_WIN)
// On Windows also make sure that handling WM_SYSCOMMAND doesn't crash with
// custom frame. Frame type needs to be toggled again if Aero Glass is
// disabled.
if (widget.ShouldUseNativeFrame())
widget.DebugToggleFrameType();
SendMessage(widget.GetNativeWindow()->GetHost()->GetAcceleratedWidget(),
WM_SYSCOMMAND, SC_RESTORE, 0);
#endif // BUILDFLAG(IS_WIN)
}
#if BUILDFLAG(IS_CHROMEOS_ASH)
// TODO(crbug.com/916272): investigate fixing and enabling on Chrome OS.
#define MAYBE_GlobalCursorState DISABLED_GlobalCursorState
#else
#define MAYBE_GlobalCursorState GlobalCursorState
#endif
// Verify that the cursor state is shared between two native widgets.
TEST_F(DesktopNativeWidgetAuraTest, MAYBE_GlobalCursorState) {
// Create two native widgets, each owning different root windows.
Widget widget_a;
Widget::InitParams init_params_a =
CreateParams(Widget::InitParams::TYPE_WINDOW);
init_params_a.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget_a.Init(std::move(init_params_a));
Widget widget_b;
Widget::InitParams init_params_b =
CreateParams(Widget::InitParams::TYPE_WINDOW);
init_params_b.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget_b.Init(std::move(init_params_b));
aura::client::CursorClient* cursor_client_a = aura::client::GetCursorClient(
widget_a.GetNativeView()->GetHost()->window());
aura::client::CursorClient* cursor_client_b = aura::client::GetCursorClient(
widget_b.GetNativeView()->GetHost()->window());
// Verify the cursor can be locked using one client and unlocked using
// another.
EXPECT_FALSE(cursor_client_a->IsCursorLocked());
EXPECT_FALSE(cursor_client_b->IsCursorLocked());
cursor_client_a->LockCursor();
EXPECT_TRUE(cursor_client_a->IsCursorLocked());
EXPECT_TRUE(cursor_client_b->IsCursorLocked());
cursor_client_b->UnlockCursor();
EXPECT_FALSE(cursor_client_a->IsCursorLocked());
EXPECT_FALSE(cursor_client_b->IsCursorLocked());
// Verify that mouse events can be disabled using one client and then
// re-enabled using another. Note that disabling mouse events should also
// have the side effect of making the cursor invisible.
EXPECT_TRUE(cursor_client_a->IsCursorVisible());
EXPECT_TRUE(cursor_client_b->IsCursorVisible());
EXPECT_TRUE(cursor_client_a->IsMouseEventsEnabled());
EXPECT_TRUE(cursor_client_b->IsMouseEventsEnabled());
cursor_client_b->DisableMouseEvents();
EXPECT_FALSE(cursor_client_a->IsCursorVisible());
EXPECT_FALSE(cursor_client_b->IsCursorVisible());
EXPECT_FALSE(cursor_client_a->IsMouseEventsEnabled());
EXPECT_FALSE(cursor_client_b->IsMouseEventsEnabled());
cursor_client_a->EnableMouseEvents();
EXPECT_TRUE(cursor_client_a->IsCursorVisible());
EXPECT_TRUE(cursor_client_b->IsCursorVisible());
EXPECT_TRUE(cursor_client_a->IsMouseEventsEnabled());
EXPECT_TRUE(cursor_client_b->IsMouseEventsEnabled());
// Verify that setting the cursor using one cursor client
// will set it for all root windows.
EXPECT_EQ(ui::mojom::CursorType::kNull, cursor_client_a->GetCursor().type());
EXPECT_EQ(ui::mojom::CursorType::kNull, cursor_client_b->GetCursor().type());
cursor_client_b->SetCursor(ui::mojom::CursorType::kPointer);
EXPECT_EQ(ui::mojom::CursorType::kPointer,
cursor_client_a->GetCursor().type());
EXPECT_EQ(ui::mojom::CursorType::kPointer,
cursor_client_b->GetCursor().type());
// Verify that hiding the cursor using one cursor client will
// hide it for all root windows. Note that hiding the cursor
// should not disable mouse events.
cursor_client_a->HideCursor();
EXPECT_FALSE(cursor_client_a->IsCursorVisible());
EXPECT_FALSE(cursor_client_b->IsCursorVisible());
EXPECT_TRUE(cursor_client_a->IsMouseEventsEnabled());
EXPECT_TRUE(cursor_client_b->IsMouseEventsEnabled());
// Verify that the visibility state cannot be changed using one
// cursor client when the cursor was locked using another.
cursor_client_b->LockCursor();
cursor_client_a->ShowCursor();
EXPECT_FALSE(cursor_client_a->IsCursorVisible());
EXPECT_FALSE(cursor_client_b->IsCursorVisible());
// Verify the cursor becomes visible on unlock (since a request
// to make it visible was queued up while the cursor was locked).
cursor_client_b->UnlockCursor();
EXPECT_TRUE(cursor_client_a->IsCursorVisible());
EXPECT_TRUE(cursor_client_b->IsCursorVisible());
}
// Verifies FocusController doesn't attempt to access |content_window_| during
// destruction. Previously the FocusController was destroyed after the window.
// This could be problematic as FocusController references |content_window_| and
// could attempt to use it after |content_window_| was destroyed. This test
// verifies this doesn't happen. Note that this test only failed under ASAN.
TEST_F(DesktopNativeWidgetAuraTest, DontAccessContentWindowDuringDestruction) {
aura::test::TestWindowDelegate delegate;
{
Widget widget;
Widget::InitParams init_params =
CreateParams(Widget::InitParams::TYPE_WINDOW);
init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget.Init(std::move(init_params));
// Owned by |widget|.
aura::Window* window = new aura::Window(&delegate);
window->Init(ui::LAYER_NOT_DRAWN);
window->Show();
widget.GetNativeWindow()->parent()->AddChild(window);
widget.Show();
}
}
namespace {
std::unique_ptr<Widget> CreateAndShowControlWidget(aura::Window* parent) {
auto widget = std::make_unique<Widget>();
Widget::InitParams params(Widget::InitParams::TYPE_CONTROL);
params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.parent = parent;
params.native_widget =
CreatePlatformNativeWidgetImpl(widget.get(), kStubCapture, nullptr);
widget->Init(std::move(params));
widget->Show();
return widget;
}
} // namespace
#if BUILDFLAG(IS_CHROMEOS_ASH)
// TODO(crbug.com/916272): investigate fixing and enabling on Chrome OS.
#define MAYBE_ReorderDoesntRecomputeOcclusion \
DISABLED_ReorderDoesntRecomputeOcclusion
#else
#define MAYBE_ReorderDoesntRecomputeOcclusion ReorderDoesntRecomputeOcclusion
#endif
TEST_F(DesktopNativeWidgetAuraTest, MAYBE_ReorderDoesntRecomputeOcclusion) {
// Create the parent widget.
Widget parent;
Widget::InitParams init_params =
CreateParams(Widget::InitParams::TYPE_WINDOW);
init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
parent.Init(std::move(init_params));
parent.Show();
aura::Window* parent_window = parent.GetNativeWindow();
parent_window->TrackOcclusionState();
View* contents_view = parent.GetContentsView();
// Create child widgets.
std::unique_ptr<Widget> w1(CreateAndShowControlWidget(parent_window));
std::unique_ptr<Widget> w2(CreateAndShowControlWidget(parent_window));
std::unique_ptr<Widget> w3(CreateAndShowControlWidget(parent_window));
// Create child views.
View* host_view1 = new View();
w1->GetNativeView()->SetProperty(kHostViewKey, host_view1);
contents_view->AddChildView(host_view1);
View* host_view2 = new View();
w2->GetNativeView()->SetProperty(kHostViewKey, host_view2);
contents_view->AddChildView(host_view2);
View* host_view3 = new View();
w3->GetNativeView()->SetProperty(kHostViewKey, host_view3);
contents_view->AddChildView(host_view3);
// Reorder child views. Expect occlusion to only be recomputed once.
aura::test::WindowOcclusionTrackerTestApi window_occlusion_tracker_test_api(
aura::Env::GetInstance()->GetWindowOcclusionTracker());
const int num_times_occlusion_recomputed =
window_occlusion_tracker_test_api.GetNumTimesOcclusionRecomputed();
contents_view->ReorderChildView(host_view3, 0);
EXPECT_EQ(num_times_occlusion_recomputed + 1,
window_occlusion_tracker_test_api.GetNumTimesOcclusionRecomputed());
}
void QuitNestedLoopAndCloseWidget(std::unique_ptr<Widget> widget,
base::OnceClosure quit_runloop) {
std::move(quit_runloop).Run();
}
// Verifies that a widget can be destroyed when running a nested message-loop.
TEST_F(DesktopNativeWidgetAuraTest, WidgetCanBeDestroyedFromNestedLoop) {
std::unique_ptr<Widget> widget(new Widget);
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.bounds = gfx::Rect(0, 0, 200, 200);
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget->Init(std::move(params));
widget->Show();
// Post a task that terminates the nested loop and destroyes the widget. This
// task will be executed from the nested loop initiated with the call to
// |RunWithDispatcher()| below.
base::RunLoop run_loop;
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(&QuitNestedLoopAndCloseWidget,
std::move(widget), run_loop.QuitClosure()));
run_loop.Run();
}
// DesktopNativeWidgetAura::CloseNow is protected.
// Create a new object to override CloseNow so we can test deleting
// the native widget.
class TestDesktopNativeWidgetAura : public DesktopNativeWidgetAura {
public:
explicit TestDesktopNativeWidgetAura(internal::NativeWidgetDelegate* delegate)
: DesktopNativeWidgetAura(delegate) {}
TestDesktopNativeWidgetAura(const TestDesktopNativeWidgetAura&) = delete;
TestDesktopNativeWidgetAura& operator=(const TestDesktopNativeWidgetAura&) =
delete;
~TestDesktopNativeWidgetAura() override = default;
void CloseNow() override { DesktopNativeWidgetAura::CloseNow(); }
};
// Series of tests that verifies a null NativeWidgetDelegate does not cause
// a crash.
class DesktopNativeWidgetAuraWithNoDelegateTest
: public DesktopNativeWidgetAuraTest {
public:
DesktopNativeWidgetAuraWithNoDelegateTest() = default;
DesktopNativeWidgetAuraWithNoDelegateTest(
const DesktopNativeWidgetAuraWithNoDelegateTest&) = delete;
DesktopNativeWidgetAuraWithNoDelegateTest& operator=(
const DesktopNativeWidgetAuraWithNoDelegateTest&) = delete;
~DesktopNativeWidgetAuraWithNoDelegateTest() override = default;
// testing::Test overrides:
void SetUp() override {
DesktopNativeWidgetAuraTest::SetUp();
Widget widget;
desktop_native_widget_ = new TestDesktopNativeWidgetAura(&widget);
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.ownership = views::Widget::InitParams::CLIENT_OWNS_WIDGET;
params.native_widget = desktop_native_widget_;
widget.Init(std::move(params));
widget.Show();
// Notify all widget observers that the widget is destroying so they can
// unregister properly and clear the pointer to the widget.
widget.OnNativeWidgetDestroying();
// Widget will create a DefaultWidgetDelegate if no delegates are provided.
// Call Widget::OnNativeWidgetDestroyed() to destroy
// the WidgetDelegate properly.
widget.OnNativeWidgetDestroyed();
}
void TearDown() override {
desktop_native_widget_->CloseNow();
ViewsTestBase::TearDown();
}
raw_ptr<TestDesktopNativeWidgetAura> desktop_native_widget_;
};
TEST_F(DesktopNativeWidgetAuraWithNoDelegateTest, GetHitTestMaskTest) {
SkPath mask;
static_cast<aura::WindowDelegate*>(desktop_native_widget_)
->GetHitTestMask(&mask);
}
TEST_F(DesktopNativeWidgetAuraWithNoDelegateTest, GetMaximumSizeTest) {
static_cast<aura::WindowDelegate*>(desktop_native_widget_)->GetMaximumSize();
}
TEST_F(DesktopNativeWidgetAuraWithNoDelegateTest, GetMinimumSizeTest) {
static_cast<aura::WindowDelegate*>(desktop_native_widget_)->GetMinimumSize();
}
TEST_F(DesktopNativeWidgetAuraWithNoDelegateTest, GetNonClientComponentTest) {
static_cast<aura::WindowDelegate*>(desktop_native_widget_)
->GetNonClientComponent(gfx::Point());
}
TEST_F(DesktopNativeWidgetAuraWithNoDelegateTest, GetWidgetTest) {
static_cast<internal::NativeWidgetPrivate*>(desktop_native_widget_)
->GetWidget();
}
TEST_F(DesktopNativeWidgetAuraWithNoDelegateTest, HasHitTestMaskTest) {
static_cast<aura::WindowDelegate*>(desktop_native_widget_)->HasHitTestMask();
}
TEST_F(DesktopNativeWidgetAuraWithNoDelegateTest, OnCaptureLostTest) {
static_cast<aura::WindowDelegate*>(desktop_native_widget_)->OnCaptureLost();
}
TEST_F(DesktopNativeWidgetAuraWithNoDelegateTest, OnGestureEventTest) {
ui::GestureEvent gesture(0, 0, 0, ui::EventTimeForNow(),
ui::GestureEventDetails(ui::ET_GESTURE_TAP_DOWN));
static_cast<ui::EventHandler*>(desktop_native_widget_)
->OnGestureEvent(&gesture);
}
TEST_F(DesktopNativeWidgetAuraWithNoDelegateTest, OnHostMovedInPixelsTest) {
static_cast<aura::WindowTreeHostObserver*>(desktop_native_widget_)
->OnHostMovedInPixels(nullptr);
}
TEST_F(DesktopNativeWidgetAuraWithNoDelegateTest, OnHostResizedTest) {
static_cast<aura::WindowTreeHostObserver*>(desktop_native_widget_)
->OnHostResized(nullptr);
}
TEST_F(DesktopNativeWidgetAuraWithNoDelegateTest, OnHostWorkspaceChangedTest) {
static_cast<aura::WindowTreeHostObserver*>(desktop_native_widget_)
->OnHostWorkspaceChanged(nullptr);
}
TEST_F(DesktopNativeWidgetAuraWithNoDelegateTest, OnKeyEventTest) {
ui::KeyEvent key(ui::ET_KEY_PRESSED, ui::VKEY_0, ui::EF_NONE);
static_cast<ui::EventHandler*>(desktop_native_widget_)->OnKeyEvent(&key);
}
TEST_F(DesktopNativeWidgetAuraWithNoDelegateTest, OnMouseEventTest) {
ui::MouseEvent move(ui::ET_MOUSE_MOVED, gfx::Point(), gfx::Point(),
ui::EventTimeForNow(), ui::EF_NONE, ui::EF_NONE);
static_cast<ui::EventHandler*>(desktop_native_widget_)->OnMouseEvent(&move);
}
TEST_F(DesktopNativeWidgetAuraWithNoDelegateTest, OnPaintTest) {
static_cast<aura::WindowDelegate*>(desktop_native_widget_)
->OnPaint(ui::PaintContext(nullptr, 0, gfx::Rect(), false));
}
TEST_F(DesktopNativeWidgetAuraWithNoDelegateTest, OnScrollEventTest) {
ui::ScrollEvent scroll(ui::ET_SCROLL, gfx::Point(), ui::EventTimeForNow(), 0,
0, 0, 0, 0, 0);
static_cast<ui::EventHandler*>(desktop_native_widget_)
->OnScrollEvent(&scroll);
}
TEST_F(DesktopNativeWidgetAuraWithNoDelegateTest, OnWindowActivatedTest) {
static_cast<wm::ActivationChangeObserver*>(desktop_native_widget_)
->OnWindowActivated(
wm::ActivationChangeObserver::ActivationReason::ACTIVATION_CLIENT,
static_cast<internal::NativeWidgetPrivate*>(desktop_native_widget_)
->GetNativeView(),
nullptr);
}
TEST_F(DesktopNativeWidgetAuraWithNoDelegateTest, OnWindowFocusedTest) {
static_cast<aura::client::FocusChangeObserver*>(desktop_native_widget_)
->OnWindowFocused(nullptr, nullptr);
}
TEST_F(DesktopNativeWidgetAuraWithNoDelegateTest, ShouldActivateTest) {
static_cast<wm::ActivationDelegate*>(desktop_native_widget_)
->ShouldActivate();
}
TEST_F(DesktopNativeWidgetAuraWithNoDelegateTest,
ShouldDescendIntoChildForEventHandlingTest) {
static_cast<aura::WindowDelegate*>(desktop_native_widget_)
->ShouldDescendIntoChildForEventHandling(nullptr, gfx::Point());
}
TEST_F(DesktopNativeWidgetAuraWithNoDelegateTest, UpdateVisualStateTest) {
static_cast<aura::WindowDelegate*>(desktop_native_widget_)
->UpdateVisualState();
}
using DesktopAuraWidgetTest = DesktopWidgetTest;
#if !BUILDFLAG(IS_FUCHSIA)
// TODO(crbug.com/1236997): Under Fuchsia pop-up and fullscreen windows are not
// reparented to be top-level, so the following tests are not valid.
// This class provides functionality to create fullscreen and top level popup
// windows. It additionally tests whether the destruction of these windows
// occurs correctly in desktop AURA without crashing.
// It provides facilities to test the following cases:-
// 1. Child window destroyed which should lead to the destruction of the
// parent.
// 2. Parent window destroyed which should lead to the child being destroyed.
class DesktopAuraTopLevelWindowTest : public aura::WindowObserver {
public:
DesktopAuraTopLevelWindowTest() = default;
DesktopAuraTopLevelWindowTest(const DesktopAuraTopLevelWindowTest&) = delete;
DesktopAuraTopLevelWindowTest& operator=(
const DesktopAuraTopLevelWindowTest&) = delete;
~DesktopAuraTopLevelWindowTest() override {
EXPECT_TRUE(owner_destroyed_);
EXPECT_TRUE(owned_window_destroyed_);
top_level_widget_ = nullptr;
owned_window_ = nullptr;
}
void CreateTopLevelWindow(const gfx::Rect& bounds, bool fullscreen) {
Widget::InitParams init_params;
init_params.type = Widget::InitParams::TYPE_WINDOW;
init_params.bounds = bounds;
init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
init_params.layer_type = ui::LAYER_NOT_DRAWN;
init_params.accept_events = fullscreen;
widget_.Init(std::move(init_params));
owned_window_ = new aura::Window(&child_window_delegate_);
owned_window_->SetType(aura::client::WINDOW_TYPE_NORMAL);
owned_window_->SetName("TestTopLevelWindow");
if (fullscreen) {
owned_window_->SetProperty(aura::client::kShowStateKey,
ui::SHOW_STATE_FULLSCREEN);
} else {
owned_window_->SetType(aura::client::WINDOW_TYPE_MENU);
}
owned_window_->Init(ui::LAYER_TEXTURED);
aura::client::ParentWindowWithContext(
owned_window_, widget_.GetNativeView()->GetRootWindow(),
gfx::Rect(0, 0, 1900, 1600));
owned_window_->Show();
owned_window_->AddObserver(this);
ASSERT_TRUE(owned_window_->parent() != nullptr);
owned_window_->parent()->AddObserver(this);
top_level_widget_ =
views::Widget::GetWidgetForNativeView(owned_window_->parent());
ASSERT_TRUE(top_level_widget_ != nullptr);
}
void DestroyOwnedWindow() {
ASSERT_TRUE(owned_window_ != nullptr);
// If async mode is off then clean up state here.
if (!use_async_mode_) {
owned_window_->RemoveObserver(this);
owned_window_->parent()->RemoveObserver(this);
owner_destroyed_ = true;
owned_window_destroyed_ = true;
}
delete owned_window_;
}
void DestroyOwnerWindow() {
ASSERT_TRUE(top_level_widget_ != nullptr);
top_level_widget_->CloseNow();
}
void OnWindowDestroying(aura::Window* window) override {
window->RemoveObserver(this);
if (window == owned_window_) {
owned_window_destroyed_ = true;
} else if (window == top_level_widget_->GetNativeView()) {
owner_destroyed_ = true;
} else {
ADD_FAILURE() << "Unexpected window destroyed callback: " << window;
}
}
aura::Window* owned_window() { return owned_window_; }
views::Widget* top_level_widget() { return top_level_widget_; }
void set_use_async_mode(bool async_mode) { use_async_mode_ = async_mode; }
private:
views::Widget widget_;
raw_ptr<views::Widget> top_level_widget_ = nullptr;
raw_ptr<aura::Window> owned_window_ = nullptr;
bool owner_destroyed_ = false;
bool owned_window_destroyed_ = false;
aura::test::TestWindowDelegate child_window_delegate_;
// This flag controls whether we need to wait for the destruction to complete
// before finishing the test. Defaults to true.
bool use_async_mode_ = true;
};
TEST_F(DesktopAuraWidgetTest, FullscreenWindowDestroyedBeforeOwnerTest) {
DesktopAuraTopLevelWindowTest fullscreen_window;
ASSERT_NO_FATAL_FAILURE(
fullscreen_window.CreateTopLevelWindow(gfx::Rect(0, 0, 200, 200), true));
RunPendingMessages();
ASSERT_NO_FATAL_FAILURE(fullscreen_window.DestroyOwnedWindow());
RunPendingMessages();
}
TEST_F(DesktopAuraWidgetTest, FullscreenWindowOwnerDestroyed) {
DesktopAuraTopLevelWindowTest fullscreen_window;
ASSERT_NO_FATAL_FAILURE(
fullscreen_window.CreateTopLevelWindow(gfx::Rect(0, 0, 200, 200), true));
RunPendingMessages();
ASSERT_NO_FATAL_FAILURE(fullscreen_window.DestroyOwnerWindow());
RunPendingMessages();
}
TEST_F(DesktopAuraWidgetTest, TopLevelOwnedPopupTest) {
DesktopAuraTopLevelWindowTest popup_window;
ASSERT_NO_FATAL_FAILURE(
popup_window.CreateTopLevelWindow(gfx::Rect(0, 0, 200, 200), false));
RunPendingMessages();
ASSERT_NO_FATAL_FAILURE(popup_window.DestroyOwnedWindow());
RunPendingMessages();
}
// This test validates that when a top level owned popup Aura window is
// resized, the widget is resized as well.
TEST_F(DesktopAuraWidgetTest, TopLevelOwnedPopupResizeTest) {
DesktopAuraTopLevelWindowTest popup_window;
popup_window.set_use_async_mode(false);
ASSERT_NO_FATAL_FAILURE(
popup_window.CreateTopLevelWindow(gfx::Rect(0, 0, 200, 200), false));
gfx::Rect new_size(0, 0, 400, 400);
popup_window.owned_window()->SetBounds(new_size);
EXPECT_EQ(popup_window.top_level_widget()->GetNativeView()->bounds().size(),
new_size.size());
ASSERT_NO_FATAL_FAILURE(popup_window.DestroyOwnedWindow());
}
// This test validates that when a top level owned popup Aura window is
// repositioned, the widget is repositioned as well.
TEST_F(DesktopAuraWidgetTest, TopLevelOwnedPopupRepositionTest) {
DesktopAuraTopLevelWindowTest popup_window;
popup_window.set_use_async_mode(false);
ASSERT_NO_FATAL_FAILURE(
popup_window.CreateTopLevelWindow(gfx::Rect(0, 0, 200, 200), false));
gfx::Rect new_pos(10, 10, 400, 400);
popup_window.owned_window()->SetBoundsInScreen(
new_pos,
display::Screen::GetScreen()->GetDisplayNearestPoint(gfx::Point()));
EXPECT_EQ(new_pos,
popup_window.top_level_widget()->GetWindowBoundsInScreen());
ASSERT_NO_FATAL_FAILURE(popup_window.DestroyOwnedWindow());
}
#endif // !BUILDFLAG(IS_FUCHSIA)
// The following code verifies we can correctly destroy a Widget from a mouse
// enter/exit. We could test move/drag/enter/exit but in general we don't run
// nested run loops from such events, nor has the code ever really dealt
// with this situation.
// Generates two moves (first generates enter, second real move), a press, drag
// and release stopping at |last_event_type|.
void GenerateMouseEvents(Widget* widget, ui::EventType last_event_type) {
const gfx::Rect screen_bounds(widget->GetWindowBoundsInScreen());
ui::MouseEvent move_event(ui::ET_MOUSE_MOVED, screen_bounds.CenterPoint(),
screen_bounds.CenterPoint(), ui::EventTimeForNow(),
0, 0);
ui::EventSink* sink = WidgetTest::GetEventSink(widget);
ui::EventDispatchDetails details = sink->OnEventFromSource(&move_event);
if (last_event_type == ui::ET_MOUSE_ENTERED || details.dispatcher_destroyed)
return;
details = sink->OnEventFromSource(&move_event);
if (last_event_type == ui::ET_MOUSE_MOVED || details.dispatcher_destroyed)
return;
ui::MouseEvent press_event(ui::ET_MOUSE_PRESSED, screen_bounds.CenterPoint(),
screen_bounds.CenterPoint(), ui::EventTimeForNow(),
0, 0);
details = sink->OnEventFromSource(&press_event);
if (last_event_type == ui::ET_MOUSE_PRESSED || details.dispatcher_destroyed)
return;
gfx::Point end_point(screen_bounds.CenterPoint());
end_point.Offset(1, 1);
ui::MouseEvent drag_event(ui::ET_MOUSE_DRAGGED, end_point, end_point,
ui::EventTimeForNow(), 0, 0);
details = sink->OnEventFromSource(&drag_event);
if (last_event_type == ui::ET_MOUSE_DRAGGED || details.dispatcher_destroyed)
return;
ui::MouseEvent release_event(ui::ET_MOUSE_RELEASED, end_point, end_point,
ui::EventTimeForNow(), 0, 0);
details = sink->OnEventFromSource(&release_event);
if (details.dispatcher_destroyed)
return;
}
// Creates a widget and invokes GenerateMouseEvents() with |last_event_type|.
void RunCloseWidgetDuringDispatchTest(WidgetTest* test,
ui::EventType last_event_type) {
// |widget| is deleted by CloseWidgetView.
Widget* widget = new Widget;
Widget::InitParams params =
test->CreateParams(Widget::InitParams::TYPE_POPUP);
params.bounds = gfx::Rect(0, 0, 50, 100);
widget->Init(std::move(params));
widget->SetContentsView(std::make_unique<CloseWidgetView>(last_event_type));
widget->Show();
GenerateMouseEvents(widget, last_event_type);
}
// Verifies deleting the widget from a mouse pressed event doesn't crash.
TEST_F(DesktopAuraWidgetTest, CloseWidgetDuringMousePress) {
RunCloseWidgetDuringDispatchTest(this, ui::ET_MOUSE_PRESSED);
}
// Verifies deleting the widget from a mouse released event doesn't crash.
TEST_F(DesktopAuraWidgetTest, CloseWidgetDuringMouseReleased) {
RunCloseWidgetDuringDispatchTest(this, ui::ET_MOUSE_RELEASED);
}
#if BUILDFLAG(IS_CHROMEOS_ASH)
// TODO(crbug.com/916272): investigate fixing and enabling on Chrome OS.
#define MAYBE_WindowMouseModalityTest DISABLED_WindowMouseModalityTest
#else
#define MAYBE_WindowMouseModalityTest WindowMouseModalityTest
#endif
// This test verifies that whether mouse events when a modal dialog is
// displayed are eaten or recieved by the dialog.
TEST_F(DesktopWidgetTest, MAYBE_WindowMouseModalityTest) {
// Create a top level widget.
Widget top_level_widget;
Widget::InitParams init_params =
CreateParams(Widget::InitParams::TYPE_WINDOW);
init_params.show_state = ui::SHOW_STATE_NORMAL;
gfx::Rect initial_bounds(0, 0, 500, 500);
init_params.bounds = initial_bounds;
init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
top_level_widget.Init(std::move(init_params));
top_level_widget.Show();
EXPECT_TRUE(top_level_widget.IsVisible());
// Create a view and validate that a mouse moves makes it to the view.
EventCountView* widget_view = new EventCountView();
widget_view->SetBounds(0, 0, 10, 10);
top_level_widget.GetRootView()->AddChildView(widget_view);
gfx::Point cursor_location_main(5, 5);
ui::MouseEvent move_main(ui::ET_MOUSE_MOVED, cursor_location_main,
cursor_location_main, ui::EventTimeForNow(),
ui::EF_NONE, ui::EF_NONE);
ui::EventDispatchDetails details =
GetEventSink(&top_level_widget)->OnEventFromSource(&move_main);
ASSERT_FALSE(details.dispatcher_destroyed);
EXPECT_EQ(1, widget_view->GetEventCount(ui::ET_MOUSE_ENTERED));
widget_view->ResetCounts();
// Create a modal dialog and validate that a mouse down message makes it to
// the main view within the dialog.
// This instance will be destroyed when the dialog is destroyed.
auto dialog_delegate = std::make_unique<DialogDelegateView>();
dialog_delegate->SetModalType(ui::MODAL_TYPE_WINDOW);
Widget* modal_dialog_widget = views::DialogDelegate::CreateDialogWidget(
dialog_delegate.release(), nullptr, top_level_widget.GetNativeView());
modal_dialog_widget->SetBounds(gfx::Rect(100, 100, 200, 200));
EventCountView* dialog_widget_view = new EventCountView();
dialog_widget_view->SetBounds(0, 0, 50, 50);
modal_dialog_widget->GetRootView()->AddChildView(dialog_widget_view);
modal_dialog_widget->Show();
EXPECT_TRUE(modal_dialog_widget->IsVisible());
gfx::Point cursor_location_dialog(100, 100);
ui::MouseEvent mouse_down_dialog(
ui::ET_MOUSE_PRESSED, cursor_location_dialog, cursor_location_dialog,
ui::EventTimeForNow(), ui::EF_NONE, ui::EF_NONE);
details =
GetEventSink(&top_level_widget)->OnEventFromSource(&mouse_down_dialog);
ASSERT_FALSE(details.dispatcher_destroyed);
EXPECT_EQ(1, dialog_widget_view->GetEventCount(ui::ET_MOUSE_PRESSED));
// Send a mouse move message to the main window. It should not be received by
// the main window as the modal dialog is still active.
gfx::Point cursor_location_main2(6, 6);
ui::MouseEvent mouse_down_main(ui::ET_MOUSE_MOVED, cursor_location_main2,
cursor_location_main2, ui::EventTimeForNow(),
ui::EF_NONE, ui::EF_NONE);
details =
GetEventSink(&top_level_widget)->OnEventFromSource(&mouse_down_main);
ASSERT_FALSE(details.dispatcher_destroyed);
EXPECT_EQ(0, widget_view->GetEventCount(ui::ET_MOUSE_MOVED));
modal_dialog_widget->CloseNow();
top_level_widget.CloseNow();
}
#if BUILDFLAG(IS_WIN)
// Tests whether we can activate the top level widget when a modal dialog is
// active.
TEST_F(DesktopWidgetTest, WindowModalityActivationTest) {
TestDesktopWidgetDelegate widget_delegate;
widget_delegate.InitWidget(CreateParams(Widget::InitParams::TYPE_WINDOW));
Widget* top_level_widget = widget_delegate.GetWidget();
top_level_widget->Show();
EXPECT_TRUE(top_level_widget->IsVisible());
HWND win32_window = views::HWNDForWidget(top_level_widget);
EXPECT_TRUE(::IsWindow(win32_window));
// We should be able to activate the window even if the WidgetDelegate
// says no, when a modal dialog is active.
widget_delegate.SetCanActivate(false);
auto dialog_delegate = std::make_unique<DialogDelegateView>();
dialog_delegate->SetModalType(ui::MODAL_TYPE_WINDOW);
Widget* modal_dialog_widget = views::DialogDelegate::CreateDialogWidget(
dialog_delegate.release(), nullptr, top_level_widget->GetNativeView());
modal_dialog_widget->SetBounds(gfx::Rect(100, 100, 200, 200));
modal_dialog_widget->Show();
EXPECT_TRUE(modal_dialog_widget->IsVisible());
LRESULT activate_result = ::SendMessage(
win32_window, WM_MOUSEACTIVATE, reinterpret_cast<WPARAM>(win32_window),
MAKELPARAM(WM_LBUTTONDOWN, HTCLIENT));
EXPECT_EQ(activate_result, MA_ACTIVATE);
modal_dialog_widget->CloseNow();
}
// This test validates that sending WM_CHAR/WM_SYSCHAR/WM_SYSDEADCHAR
// messages via the WindowEventTarget interface implemented by the
// HWNDMessageHandler class does not cause a crash due to an unprocessed
// event
TEST_F(DesktopWidgetTest, CharMessagesAsKeyboardMessagesDoesNotCrash) {
Widget widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget.Init(std::move(params));
widget.Show();
ui::WindowEventTarget* target =
reinterpret_cast<ui::WindowEventTarget*>(ui::ViewProp::GetValue(
widget.GetNativeWindow()->GetHost()->GetAcceleratedWidget(),
ui::WindowEventTarget::kWin32InputEventTarget));
ASSERT_NE(nullptr, target);
bool handled = false;
target->HandleKeyboardMessage(WM_CHAR, 0, 0, &handled);
target->HandleKeyboardMessage(WM_SYSCHAR, 0, 0, &handled);
target->HandleKeyboardMessage(WM_SYSDEADCHAR, 0, 0, &handled);
widget.CloseNow();
}
#endif // BUILDFLAG(IS_WIN)
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_native_widget_aura_unittest.cc | C++ | unknown | 36,270 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_SCREEN_H_
#define UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_SCREEN_H_
#include <memory>
#include "ui/views/views_export.h"
namespace display {
class Screen;
}
namespace views {
// Creates a Screen that represents the screen of the environment that hosts
// a WindowTreeHost.
VIEWS_EXPORT std::unique_ptr<display::Screen> CreateDesktopScreen();
} // namespace views
#endif // UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_SCREEN_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_screen.h | C++ | unknown | 615 |
// 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/widget/desktop_aura/desktop_screen_ozone.h"
#include <memory>
#include "build/build_config.h"
#include "ui/aura/screen_ozone.h"
#include "ui/views/widget/desktop_aura/desktop_screen.h"
#include "ui/views/widget/desktop_aura/desktop_window_tree_host_platform.h"
namespace views {
DesktopScreenOzone::DesktopScreenOzone() = default;
DesktopScreenOzone::~DesktopScreenOzone() = default;
gfx::NativeWindow DesktopScreenOzone::GetNativeWindowFromAcceleratedWidget(
gfx::AcceleratedWidget widget) const {
if (!widget)
return nullptr;
return views::DesktopWindowTreeHostPlatform::GetContentWindowForWidget(
widget);
}
#if !BUILDFLAG(IS_LINUX)
std::unique_ptr<display::Screen> CreateDesktopScreen() {
auto screen = std::make_unique<DesktopScreenOzone>();
screen->Initialize();
return screen;
}
#endif
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_screen_ozone.cc | C++ | unknown | 1,010 |
// 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_WIDGET_DESKTOP_AURA_DESKTOP_SCREEN_OZONE_H_
#define UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_SCREEN_OZONE_H_
#include "ui/aura/screen_ozone.h"
#include "ui/views/views_export.h"
namespace views {
class VIEWS_EXPORT DesktopScreenOzone : public aura::ScreenOzone {
public:
DesktopScreenOzone();
DesktopScreenOzone(const DesktopScreenOzone&) = delete;
DesktopScreenOzone& operator=(const DesktopScreenOzone&) = delete;
~DesktopScreenOzone() override;
private:
// ui::aura::ScreenOzone:
gfx::NativeWindow GetNativeWindowFromAcceleratedWidget(
gfx::AcceleratedWidget widget) const override;
};
} // namespace views
#endif // UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_SCREEN_OZONE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_screen_ozone.h | C++ | unknown | 858 |
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/scoped_observation.h"
#include "ui/linux/device_scale_factor_observer.h"
#include "ui/linux/linux_ui.h"
#include "ui/ozone/public/platform_screen.h"
#include "ui/views/widget/desktop_aura/desktop_screen.h"
#include "ui/views/widget/desktop_aura/desktop_screen_ozone.h"
namespace views {
// Listens to device scale factor changes that can be provided via "external" to
// Ozone sources such as toolkits, etc, and provides Ozone with new values.
class DesktopScreenOzoneLinux : public DesktopScreenOzone,
public ui::DeviceScaleFactorObserver {
public:
DesktopScreenOzoneLinux() = default;
~DesktopScreenOzoneLinux() override = default;
private:
// DeviceScaleFactorObserver:
void OnDeviceScaleFactorChanged() override {
SetDeviceScaleFactorToPlatformScreen(
ui::LinuxUi::instance()->GetDeviceScaleFactor());
}
void SetDeviceScaleFactorToPlatformScreen(float scale_factor) {
platform_screen()->SetDeviceScaleFactor(scale_factor);
}
// ScreenOzone:
//
// Linux/Ozone/X11 must get scale factor from LinuxUI before displays are
// fetched. X11ScreenOzone fetches lists of displays synchronously only on the
// first initialization. Later, when it gets a notification about scale factor
// changes, displays are updated via a task, which results in a first
// PlatformWindow created with wrong bounds translated from DIP to px. Thus,
// set the display scale factor as early as possible so that list of displays
// have correct scale factor from the beginning.
void OnBeforePlatformScreenInit() override {
auto* linux_ui = ui::LinuxUi::instance();
if (linux_ui) {
display_scale_factor_observer_.Observe(linux_ui);
// Send current scale factor as starting to observe doesn't actually
// result in getting a OnDeviceScaleFactorChanged call.
SetDeviceScaleFactorToPlatformScreen(linux_ui->GetDeviceScaleFactor());
}
}
base::ScopedObservation<ui::LinuxUi, DeviceScaleFactorObserver>
display_scale_factor_observer_{this};
};
std::unique_ptr<display::Screen> CreateDesktopScreen() {
auto screen = std::make_unique<DesktopScreenOzoneLinux>();
screen->Initialize();
return screen;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_screen_ozone_linux.cc | C++ | unknown | 2,393 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/widget/desktop_aura/desktop_screen_position_client.h"
#include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h"
namespace views {
namespace {
// Returns true if bounds passed to window in SetBounds should be treated as
// though they are in screen coordinates.
bool PositionWindowInScreenCoordinates(aura::Window* window) {
if (window->GetType() == aura::client::WINDOW_TYPE_POPUP)
return true;
Widget* widget = Widget::GetWidgetForNativeView(window);
return widget && widget->is_top_level();
}
} // namespace
DesktopScreenPositionClient::~DesktopScreenPositionClient() = default;
void DesktopScreenPositionClient::SetBounds(aura::Window* window,
const gfx::Rect& bounds,
const display::Display& display) {
// TODO(jam): Use the 3rd parameter, |display|.
aura::Window* root = window->GetRootWindow();
internal::NativeWidgetPrivate* desktop_native_widget =
DesktopNativeWidgetAura::ForWindow(root);
if (desktop_native_widget &&
desktop_native_widget->GetNativeView() == window) {
desktop_native_widget->SetBounds(bounds);
return;
}
if (PositionWindowInScreenCoordinates(window)) {
// The caller expects windows we consider "embedded" to be placed in the
// screen coordinate system. So we need to offset the root window's
// position (which is in screen coordinates) from these bounds.
gfx::Point origin = bounds.origin();
aura::Window::ConvertPointToTarget(window->parent(), root, &origin);
gfx::Point host_origin = GetRootWindowOriginInScreen(root);
origin.Offset(-host_origin.x(), -host_origin.y());
window->SetBounds(gfx::Rect(origin, bounds.size()));
return;
}
window->SetBounds(bounds);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_screen_position_client.cc | C++ | unknown | 1,975 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_SCREEN_POSITION_CLIENT_H_
#define UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_SCREEN_POSITION_CLIENT_H_
#include "ui/views/views_export.h"
#include "ui/wm/core/default_screen_position_client.h"
namespace views {
// Client that always offsets by the toplevel RootWindow of the passed
// in child NativeWidgetAura.
class VIEWS_EXPORT DesktopScreenPositionClient
: public wm::DefaultScreenPositionClient {
public:
using DefaultScreenPositionClient::DefaultScreenPositionClient;
DesktopScreenPositionClient(const DesktopScreenPositionClient&) = delete;
DesktopScreenPositionClient& operator=(const DesktopScreenPositionClient&) =
delete;
~DesktopScreenPositionClient() override;
// aura::client::DefaultScreenPositionClient:
void SetBounds(aura::Window* window,
const gfx::Rect& bounds,
const display::Display& display) override;
};
} // namespace views
#endif // UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_SCREEN_POSITION_CLIENT_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_screen_position_client.h | C++ | unknown | 1,172 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/widget/desktop_aura/desktop_screen_win.h"
#include <memory>
#include "ui/aura/window.h"
#include "ui/aura/window_tree_host.h"
#include "ui/views/widget/desktop_aura/desktop_screen.h"
#include "ui/views/widget/desktop_aura/desktop_window_tree_host_win.h"
namespace views {
DesktopScreenWin::DesktopScreenWin() {
DCHECK(!display::Screen::HasScreen());
display::Screen::SetScreenInstance(this);
}
DesktopScreenWin::~DesktopScreenWin() {
display::Screen::SetScreenInstance(nullptr);
}
HWND DesktopScreenWin::GetHWNDFromNativeWindow(gfx::NativeWindow window) const {
if (!window)
return nullptr;
aura::WindowTreeHost* host = window->GetHost();
return host ? host->GetAcceleratedWidget() : nullptr;
}
gfx::NativeWindow DesktopScreenWin::GetNativeWindowFromHWND(HWND hwnd) const {
return ::IsWindow(hwnd)
? DesktopWindowTreeHostWin::GetContentWindowForHWND(hwnd)
: gfx::kNullNativeWindow;
}
bool DesktopScreenWin::IsNativeWindowOccluded(gfx::NativeWindow window) const {
return window->GetHost()->GetNativeWindowOcclusionState() ==
aura::Window::OcclusionState::OCCLUDED;
}
absl::optional<bool> DesktopScreenWin::IsWindowOnCurrentVirtualDesktop(
gfx::NativeWindow window) const {
DCHECK(window);
return window->GetHost()->on_current_workspace();
}
////////////////////////////////////////////////////////////////////////////////
std::unique_ptr<display::Screen> CreateDesktopScreen() {
return std::make_unique<DesktopScreenWin>();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_screen_win.cc | C++ | unknown | 1,688 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_SCREEN_WIN_H_
#define UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_SCREEN_WIN_H_
#include "base/memory/raw_ptr.h"
#include "ui/display/win/screen_win.h"
#include "ui/views/views_export.h"
namespace views {
class VIEWS_EXPORT DesktopScreenWin : public display::win::ScreenWin {
public:
DesktopScreenWin();
DesktopScreenWin(const DesktopScreenWin&) = delete;
DesktopScreenWin& operator=(const DesktopScreenWin&) = delete;
~DesktopScreenWin() override;
private:
// display::win::ScreenWin:
HWND GetHWNDFromNativeWindow(gfx::NativeWindow window) const override;
gfx::NativeWindow GetNativeWindowFromHWND(HWND hwnd) const override;
bool IsNativeWindowOccluded(gfx::NativeWindow window) const override;
absl::optional<bool> IsWindowOnCurrentVirtualDesktop(
gfx::NativeWindow window) const override;
};
} // namespace views
#endif // UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_SCREEN_WIN_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_screen_win.h | C++ | unknown | 1,093 |
// 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/widget/desktop_aura/desktop_window_tree_host.h"
#include "build/build_config.h"
#include "ui/aura/window.h"
#include "ui/aura/window_tree_host.h"
#include "ui/display/screen.h"
#include "ui/views/widget/desktop_aura/desktop_native_cursor_manager.h"
#include "ui/views/widget/desktop_aura/desktop_screen_position_client.h"
namespace views {
bool DesktopWindowTreeHost::IsMoveLoopSupported() const {
return true;
}
void DesktopWindowTreeHost::UpdateWindowShapeIfNeeded(
const ui::PaintContext& context) {}
void DesktopWindowTreeHost::PaintAsActiveChanged() {}
std::unique_ptr<aura::client::ScreenPositionClient>
DesktopWindowTreeHost::CreateScreenPositionClient() {
return std::make_unique<DesktopScreenPositionClient>(
AsWindowTreeHost()->window());
}
DesktopNativeCursorManager*
DesktopWindowTreeHost::GetSingletonDesktopNativeCursorManager() {
return new DesktopNativeCursorManager();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_window_tree_host.cc | C++ | unknown | 1,097 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_WINDOW_TREE_HOST_H_
#define UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_WINDOW_TREE_HOST_H_
#include <memory>
#include <string>
#include "ui/aura/window_event_dispatcher.h"
#include "ui/base/ui_base_types.h"
#include "ui/views/views_export.h"
#include "ui/views/widget/widget.h"
namespace aura {
class WindowTreeHost;
class Window;
namespace client {
class DragDropClient;
class ScreenPositionClient;
} // namespace client
} // namespace aura
namespace gfx {
class ImageSkia;
class Rect;
} // namespace gfx
namespace ui {
class PaintContext;
} // namespace ui
namespace views {
namespace corewm {
class Tooltip;
}
namespace internal {
class NativeWidgetDelegate;
}
class DesktopNativeCursorManager;
class DesktopNativeWidgetAura;
class VIEWS_EXPORT DesktopWindowTreeHost {
public:
virtual ~DesktopWindowTreeHost() = default;
static DesktopWindowTreeHost* Create(
internal::NativeWidgetDelegate* native_widget_delegate,
DesktopNativeWidgetAura* desktop_native_widget_aura);
// Sets up resources needed before the WindowEventDispatcher has been created.
// It is expected this calls InitHost() on the WindowTreeHost.
virtual void Init(const Widget::InitParams& params) = 0;
// Invoked once the DesktopNativeWidgetAura has been created.
virtual void OnNativeWidgetCreated(const Widget::InitParams& params) = 0;
// Called from DesktopNativeWidgetAura::OnWidgetInitDone().
virtual void OnWidgetInitDone() = 0;
// Called from DesktopNativeWidgetAura::OnWindowActivated().
virtual void OnActiveWindowChanged(bool active) = 0;
// Creates and returns the Tooltip implementation to use. Return value is
// owned by DesktopNativeWidgetAura and lives as long as
// DesktopWindowTreeHost.
virtual std::unique_ptr<corewm::Tooltip> CreateTooltip() = 0;
// Creates and returns the DragDropClient implementation to use. Return value
// is owned by DesktopNativeWidgetAura and lives as long as
// DesktopWindowTreeHost.
virtual std::unique_ptr<aura::client::DragDropClient>
CreateDragDropClient() = 0;
// Creates the ScreenPositionClient to use for the WindowTreeHost. Default
// implementation creates DesktopScreenPositionClient.
virtual std::unique_ptr<aura::client::ScreenPositionClient>
CreateScreenPositionClient();
virtual void Close() = 0;
virtual void CloseNow() = 0;
virtual aura::WindowTreeHost* AsWindowTreeHost() = 0;
// There are two distinct ways for DesktopWindowTreeHosts's to be shown:
// 1. This function is called. As this function is specific to
// DesktopWindowTreeHost, it is only called from DesktopNativeWidgetAura.
// 2. Calling Show() directly on the WindowTreeHost associated with this
// DesktopWindowTreeHost. This is very rare. In general, calls go through
// Widget, which ends up in (1).
//
// Implementations must deal with these two code paths. In general, this is
// done by having the WindowTreeHost subclass override ShowImpl() to call this
// function: Show(ui::SHOW_STATE_NORMAL, gfx::Rect()). A subtle
// ramification is the implementation of this function can *not* call
// WindowTreeHost::Show(), and the implementation of this must perform the
// same work as WindowTreeHost::Show(). This means setting the visibility of
// the compositor, window() and DesktopNativeWidgetAura::content_window()
// appropriately. Some subclasses set the visibility of window() in the
// constructor and assume it's always true.
virtual void Show(ui::WindowShowState show_state,
const gfx::Rect& restore_bounds) = 0;
virtual bool IsVisible() const = 0;
virtual void SetSize(const gfx::Size& size) = 0;
virtual void StackAbove(aura::Window* window) = 0;
virtual void StackAtTop() = 0;
virtual bool IsStackedAbove(aura::Window* window) = 0;
virtual void CenterWindow(const gfx::Size& size) = 0;
virtual void GetWindowPlacement(gfx::Rect* bounds,
ui::WindowShowState* show_state) const = 0;
virtual gfx::Rect GetWindowBoundsInScreen() const = 0;
virtual gfx::Rect GetClientAreaBoundsInScreen() const = 0;
virtual gfx::Rect GetRestoredBounds() const = 0;
virtual std::string GetWorkspace() const = 0;
virtual gfx::Rect GetWorkAreaBoundsInScreen() const = 0;
// Sets the shape of the root window. If |native_shape| is nullptr then the
// window reverts to rectangular.
virtual void SetShape(std::unique_ptr<Widget::ShapeRects> native_shape) = 0;
virtual void Activate() = 0;
virtual void Deactivate() = 0;
virtual bool IsActive() const = 0;
virtual void PaintAsActiveChanged();
virtual void Maximize() = 0;
virtual void Minimize() = 0;
virtual void Restore() = 0;
virtual bool IsMaximized() const = 0;
virtual bool IsMinimized() const = 0;
virtual bool HasCapture() const = 0;
virtual void SetZOrderLevel(ui::ZOrderLevel order) = 0;
virtual ui::ZOrderLevel GetZOrderLevel() const = 0;
virtual void SetVisibleOnAllWorkspaces(bool always_visible) = 0;
virtual bool IsVisibleOnAllWorkspaces() const = 0;
// Returns true if the title changed.
virtual bool SetWindowTitle(const std::u16string& title) = 0;
virtual void ClearNativeFocus() = 0;
virtual bool IsMoveLoopSupported() const;
virtual Widget::MoveLoopResult RunMoveLoop(
const gfx::Vector2d& drag_offset,
Widget::MoveLoopSource source,
Widget::MoveLoopEscapeBehavior escape_behavior) = 0;
virtual void EndMoveLoop() = 0;
virtual void SetVisibilityChangedAnimationsEnabled(bool value) = 0;
virtual std::unique_ptr<NonClientFrameView> CreateNonClientFrameView() = 0;
// Determines whether the window should use native title bar and borders.
virtual bool ShouldUseNativeFrame() const = 0;
// Determines whether the window contents should be rendered transparently
// (for example, so that they can overhang onto the window title bar).
virtual bool ShouldWindowContentsBeTransparent() const = 0;
virtual void FrameTypeChanged() = 0;
// Set the fullscreen state. `target_display_id` indicates the display where
// the window should be shown fullscreen; display::kInvalidDisplayId indicates
// that no display was specified, so the current display may be used.
virtual void SetFullscreen(bool fullscreen, int64_t target_display_id) = 0;
// Returns true if the window is in fullscreen on any display.
virtual bool IsFullscreen() const = 0;
virtual void SetOpacity(float opacity) = 0;
// See NativeWidgetPrivate::SetAspectRatio for more information about what
// `excluded_margin` does.
virtual void SetAspectRatio(const gfx::SizeF& aspect_ratio,
const gfx::Size& excluded_margin) = 0;
virtual void SetWindowIcons(const gfx::ImageSkia& window_icon,
const gfx::ImageSkia& app_icon) = 0;
virtual void InitModalType(ui::ModalType modal_type) = 0;
virtual void FlashFrame(bool flash_frame) = 0;
// Returns true if the Widget was closed but is still showing because of
// animations.
virtual bool IsAnimatingClosed() const = 0;
// Returns true if the Widget supports translucency.
virtual bool IsTranslucentWindowOpacitySupported() const = 0;
// Called when the window's size constraints change.
virtual void SizeConstraintsChanged() = 0;
// Returns true if the transparency of the DesktopNativeWidgetAura's
// |content_window_| should change.
virtual bool ShouldUpdateWindowTransparency() const = 0;
// A return value of true indicates DesktopNativeCursorManager should be
// used, a return value of false indicates the DesktopWindowTreeHost manages
// cursors itself.
virtual bool ShouldUseDesktopNativeCursorManager() const = 0;
// Returns whether a VisibilityController should be created.
virtual bool ShouldCreateVisibilityController() const = 0;
// Sets the bounds in screen coordinate DIPs (WindowTreeHost generally
// operates in pixels). This function is implemented in terms of Screen.
virtual void SetBoundsInDIP(const gfx::Rect& bounds) = 0;
// Updates window shape by clipping the canvas before paint starts.
virtual void UpdateWindowShapeIfNeeded(const ui::PaintContext& context);
virtual DesktopNativeCursorManager* GetSingletonDesktopNativeCursorManager();
};
} // namespace views
#endif // UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_WINDOW_TREE_HOST_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_window_tree_host.h | C++ | unknown | 8,545 |
// 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/widget/desktop_aura/desktop_window_tree_host_lacros.h"
#include <memory>
#include <string>
#include "chromeos/ui/base/window_properties.h"
#include "ui/aura/window.h"
#include "ui/aura/window_delegate.h"
#include "ui/events/event.h"
#include "ui/ozone/public/ozone_platform.h"
#include "ui/platform_window/extensions/desk_extension.h"
#include "ui/platform_window/extensions/pinned_mode_extension.h"
#include "ui/platform_window/extensions/system_modal_extension.h"
#include "ui/platform_window/extensions/wayland_extension.h"
#include "ui/platform_window/platform_window.h"
#include "ui/platform_window/platform_window_init_properties.h"
#include "ui/platform_window/wm/wm_move_resize_handler.h"
#include "ui/views/corewm/tooltip_aura.h"
#include "ui/views/corewm/tooltip_controller.h"
#include "ui/views/corewm/tooltip_lacros.h"
#include "ui/views/views_delegate.h"
#include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h"
#include "ui/views/widget/desktop_aura/window_event_filter_lacros.h"
#include "ui/views/widget/widget.h"
namespace {
chromeos::WindowStateType ToChromeosWindowStateType(
ui::PlatformWindowState state) {
switch (state) {
case ui::PlatformWindowState::kUnknown:
return chromeos::WindowStateType::kDefault;
case ui::PlatformWindowState::kMaximized:
return chromeos::WindowStateType::kMaximized;
case ui::PlatformWindowState::kMinimized:
return chromeos::WindowStateType::kMinimized;
case ui::PlatformWindowState::kNormal:
return chromeos::WindowStateType::kNormal;
case ui::PlatformWindowState::kFullScreen:
return chromeos::WindowStateType::kFullscreen;
case ui::PlatformWindowState::kSnappedPrimary:
return chromeos::WindowStateType::kPrimarySnapped;
case ui::PlatformWindowState::kSnappedSecondary:
return chromeos::WindowStateType::kSecondarySnapped;
case ui::PlatformWindowState::kFloated:
return chromeos::WindowStateType::kFloated;
}
}
} // namespace
namespace views {
DesktopWindowTreeHostLacros::DesktopWindowTreeHostLacros(
internal::NativeWidgetDelegate* native_widget_delegate,
DesktopNativeWidgetAura* desktop_native_widget_aura)
: DesktopWindowTreeHostPlatform(native_widget_delegate,
desktop_native_widget_aura) {}
DesktopWindowTreeHostLacros::~DesktopWindowTreeHostLacros() = default;
ui::WaylandExtension* DesktopWindowTreeHostLacros::GetWaylandExtension() {
return platform_window() ? ui::GetWaylandExtension(*(platform_window()))
: nullptr;
}
const ui::WaylandExtension* DesktopWindowTreeHostLacros::GetWaylandExtension()
const {
return platform_window() ? ui::GetWaylandExtension(*(platform_window()))
: nullptr;
}
void DesktopWindowTreeHostLacros::OnNativeWidgetCreated(
const Widget::InitParams& params) {
CreateNonClientEventFilter();
DesktopWindowTreeHostPlatform::OnNativeWidgetCreated(params);
platform_window()->SetUseNativeFrame(false);
}
void DesktopWindowTreeHostLacros::InitModalType(ui::ModalType modal_type) {
if (ui::GetSystemModalExtension(*(platform_window()))) {
ui::GetSystemModalExtension(*(platform_window()))
->SetSystemModal(modal_type == ui::MODAL_TYPE_SYSTEM);
}
switch (modal_type) {
case ui::MODAL_TYPE_NONE:
case ui::MODAL_TYPE_SYSTEM:
break;
default:
// TODO(erg): Figure out under what situations |modal_type| isn't
// none. The comment in desktop_native_widget_aura.cc suggests that this
// is rare.
NOTIMPLEMENTED();
}
}
void DesktopWindowTreeHostLacros::OnClosed() {
DestroyNonClientEventFilter();
DesktopWindowTreeHostPlatform::OnClosed();
}
void DesktopWindowTreeHostLacros::OnWindowStateChanged(
ui::PlatformWindowState old_window_show_state,
ui::PlatformWindowState new_window_show_state) {
DesktopWindowTreeHostPlatform::OnWindowStateChanged(old_window_show_state,
new_window_show_state);
GetContentWindow()->SetProperty(
chromeos::kWindowStateTypeKey,
ToChromeosWindowStateType(new_window_show_state));
}
void DesktopWindowTreeHostLacros::OnImmersiveModeChanged(bool enabled) {
// Keep in sync with ImmersiveFullscreenController::Enable for widget. See
// comment there for details.
GetContentWindow()->SetProperty(chromeos::kImmersiveIsActive, enabled);
}
void DesktopWindowTreeHostLacros::OnTooltipShownOnServer(
const std::u16string& text,
const gfx::Rect& bounds) {
if (tooltip_controller()) {
tooltip_controller()->OnTooltipShownOnServer(GetContentWindow(), text,
bounds);
}
}
void DesktopWindowTreeHostLacros::OnTooltipHiddenOnServer() {
if (tooltip_controller()) {
tooltip_controller()->OnTooltipHiddenOnServer();
}
}
void DesktopWindowTreeHostLacros::AddAdditionalInitProperties(
const Widget::InitParams& params,
ui::PlatformWindowInitProperties* properties) {
properties->icon = ViewsDelegate::GetInstance()->GetDefaultWindowIcon();
properties->wayland_app_id = params.wayland_app_id;
}
std::unique_ptr<corewm::Tooltip> DesktopWindowTreeHostLacros::CreateTooltip() {
// TODO(crbug.com/1338597): Remove TooltipAura from Lacros when Ash is new
// enough.
if (ui::OzonePlatform::GetInstance()
->GetPlatformRuntimeProperties()
.supports_tooltip) {
return std::make_unique<views::corewm::TooltipLacros>();
}
// Fallback to TooltipAura if wayland version is not new enough.
return std::make_unique<views::corewm::TooltipAura>();
}
void DesktopWindowTreeHostLacros::CreateNonClientEventFilter() {
DCHECK(!non_client_window_event_filter_);
non_client_window_event_filter_ = std::make_unique<WindowEventFilterLacros>(
this, GetWmMoveResizeHandler(*platform_window()));
}
void DesktopWindowTreeHostLacros::DestroyNonClientEventFilter() {
non_client_window_event_filter_.reset();
}
// static
DesktopWindowTreeHostLacros* DesktopWindowTreeHostLacros::From(
WindowTreeHost* wth) {
DCHECK(has_open_windows()) << "Calling this method from non-Platform based "
"platform.";
for (auto widget : open_windows()) {
DesktopWindowTreeHostPlatform* wth_platform =
DesktopWindowTreeHostPlatform::GetHostForWidget(widget);
if (wth_platform != wth)
continue;
return static_cast<views::DesktopWindowTreeHostLacros*>(wth_platform);
}
return nullptr;
}
ui::DeskExtension* DesktopWindowTreeHostLacros::GetDeskExtension() {
return ui::GetDeskExtension(*(platform_window()));
}
const ui::DeskExtension* DesktopWindowTreeHostLacros::GetDeskExtension() const {
return ui::GetDeskExtension(*(platform_window()));
}
ui::PinnedModeExtension* DesktopWindowTreeHostLacros::GetPinnedModeExtension() {
return ui::GetPinnedModeExtension(*(platform_window()));
}
const ui::PinnedModeExtension*
DesktopWindowTreeHostLacros::GetPinnedModeExtension() const {
return ui::GetPinnedModeExtension(*(platform_window()));
}
// static
DesktopWindowTreeHost* DesktopWindowTreeHost::Create(
internal::NativeWidgetDelegate* native_widget_delegate,
DesktopNativeWidgetAura* desktop_native_widget_aura) {
return new DesktopWindowTreeHostLacros(native_widget_delegate,
desktop_native_widget_aura);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_window_tree_host_lacros.cc | C++ | unknown | 7,577 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_WINDOW_TREE_HOST_LACROS_H_
#define UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_WINDOW_TREE_HOST_LACROS_H_
#include <memory>
#include "base/gtest_prod_util.h"
#include "base/memory/weak_ptr.h"
#include "chromeos/ui/base/window_state_type.h"
#include "ui/aura/scoped_window_targeter.h"
#include "ui/base/buildflags.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/views/views_export.h"
#include "ui/views/widget/desktop_aura/desktop_window_tree_host_platform.h"
namespace ui {
class WaylandExtension;
class DeskExtension;
class PinnedModeExtension;
} // namespace ui
namespace views {
class WindowEventFilterLacros;
// Contains Lacros specific implementation.
class VIEWS_EXPORT DesktopWindowTreeHostLacros
: public DesktopWindowTreeHostPlatform {
public:
// Casts from a base WindowTreeHost instance.
static DesktopWindowTreeHostLacros* From(WindowTreeHost* wth);
DesktopWindowTreeHostLacros(
internal::NativeWidgetDelegate* native_widget_delegate,
DesktopNativeWidgetAura* desktop_native_widget_aura);
DesktopWindowTreeHostLacros(const DesktopWindowTreeHostLacros&) = delete;
DesktopWindowTreeHostLacros& operator=(const DesktopWindowTreeHostLacros&) =
delete;
~DesktopWindowTreeHostLacros() override;
ui::WaylandExtension* GetWaylandExtension();
const ui::WaylandExtension* GetWaylandExtension() const;
ui::DeskExtension* GetDeskExtension();
const ui::DeskExtension* GetDeskExtension() const;
ui::PinnedModeExtension* GetPinnedModeExtension();
const ui::PinnedModeExtension* GetPinnedModeExtension() const;
protected:
// Overridden from DesktopWindowTreeHost:
void OnNativeWidgetCreated(const Widget::InitParams& params) override;
void InitModalType(ui::ModalType modal_type) override;
// PlatformWindowDelegate:
void OnClosed() override;
void OnWindowStateChanged(
ui::PlatformWindowState old_window_show_state,
ui::PlatformWindowState new_window_show_state) override;
void OnImmersiveModeChanged(bool enabled) override;
void OnTooltipShownOnServer(const std::u16string& text,
const gfx::Rect& bounds) override;
void OnTooltipHiddenOnServer() override;
// DesktopWindowTreeHostPlatform overrides:
void AddAdditionalInitProperties(
const Widget::InitParams& params,
ui::PlatformWindowInitProperties* properties) override;
std::unique_ptr<corewm::Tooltip> CreateTooltip() override;
private:
FRIEND_TEST_ALL_PREFIXES(DesktopWindowTreeHostPlatformImplTestWithTouch,
HitTest);
void CreateNonClientEventFilter();
void DestroyNonClientEventFilter();
// A handler for events intended for non client area.
// A posthandler for events intended for non client area. Handles events if no
// other consumer handled them.
std::unique_ptr<WindowEventFilterLacros> non_client_window_event_filter_;
// The display and the native X window hosting the root window.
base::WeakPtrFactory<DesktopWindowTreeHostLacros> weak_factory_{this};
};
} // namespace views
#endif // UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_WINDOW_TREE_HOST_LACROS_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_window_tree_host_lacros.h | C++ | unknown | 3,296 |
// 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/widget/desktop_aura/desktop_window_tree_host_linux.h"
#include <list>
#include <memory>
#include <string>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/aura/null_window_targeter.h"
#include "ui/aura/scoped_window_targeter.h"
#include "ui/aura/window.h"
#include "ui/aura/window_delegate.h"
#include "ui/color/color_id.h"
#include "ui/color/color_provider.h"
#include "ui/compositor/compositor.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/events/event.h"
#include "ui/linux/linux_ui.h"
#include "ui/platform_window/extensions/desk_extension.h"
#include "ui/platform_window/extensions/pinned_mode_extension.h"
#include "ui/platform_window/extensions/wayland_extension.h"
#include "ui/platform_window/extensions/x11_extension.h"
#include "ui/platform_window/platform_window_init_properties.h"
#include "ui/platform_window/wm/wm_move_resize_handler.h"
#include "ui/views/views_delegate.h"
#include "ui/views/widget/widget.h"
#if BUILDFLAG(USE_ATK)
#include "ui/accessibility/platform/atk_util_auralinux.h"
#endif
#include "ui/views/widget/desktop_aura/window_event_filter_linux.h"
namespace views {
namespace {
class SwapWithNewSizeObserverHelper : public ui::CompositorObserver {
public:
using HelperCallback = base::RepeatingCallback<void(const gfx::Size&)>;
SwapWithNewSizeObserverHelper(ui::Compositor* compositor,
const HelperCallback& callback)
: compositor_(compositor), callback_(callback) {
compositor_->AddObserver(this);
}
SwapWithNewSizeObserverHelper(const SwapWithNewSizeObserverHelper&) = delete;
SwapWithNewSizeObserverHelper& operator=(
const SwapWithNewSizeObserverHelper&) = delete;
~SwapWithNewSizeObserverHelper() override {
if (compositor_)
compositor_->RemoveObserver(this);
}
private:
// ui::CompositorObserver:
void OnCompositingCompleteSwapWithNewSize(ui::Compositor* compositor,
const gfx::Size& size) override {
DCHECK_EQ(compositor, compositor_);
callback_.Run(size);
}
void OnCompositingShuttingDown(ui::Compositor* compositor) override {
DCHECK_EQ(compositor, compositor_);
compositor_->RemoveObserver(this);
compositor_ = nullptr;
}
raw_ptr<ui::Compositor> compositor_;
const HelperCallback callback_;
};
} // namespace
DesktopWindowTreeHostLinux::DesktopWindowTreeHostLinux(
internal::NativeWidgetDelegate* native_widget_delegate,
DesktopNativeWidgetAura* desktop_native_widget_aura)
: DesktopWindowTreeHostPlatform(native_widget_delegate,
desktop_native_widget_aura) {}
DesktopWindowTreeHostLinux::~DesktopWindowTreeHostLinux() = default;
gfx::Rect DesktopWindowTreeHostLinux::GetXRootWindowOuterBounds() const {
// TODO(msisov): must be removed as soon as all X11 low-level bits are moved
// to Ozone.
DCHECK(GetX11Extension());
return GetX11Extension()->GetXRootWindowOuterBounds();
}
void DesktopWindowTreeHostLinux::LowerWindow() {
if (GetX11Extension())
GetX11Extension()->LowerXWindow();
else
NOTIMPLEMENTED_LOG_ONCE();
}
base::OnceClosure DesktopWindowTreeHostLinux::DisableEventListening() {
// Allows to open multiple file-pickers. See https://crbug.com/678982
modal_dialog_counter_++;
if (modal_dialog_counter_ == 1) {
// ScopedWindowTargeter is used to temporarily replace the event-targeter
// with NullWindowEventTargeter to make |dialog| modal.
targeter_for_modal_ = std::make_unique<aura::ScopedWindowTargeter>(
window(), std::make_unique<aura::NullWindowTargeter>());
}
return base::BindOnce(&DesktopWindowTreeHostLinux::EnableEventListening,
weak_factory_.GetWeakPtr());
}
void DesktopWindowTreeHostLinux::Init(const Widget::InitParams& params) {
DesktopWindowTreeHostPlatform::Init(params);
if (GetX11Extension() && GetX11Extension()->IsSyncExtensionAvailable()) {
compositor_observer_ = std::make_unique<SwapWithNewSizeObserverHelper>(
compositor(),
base::BindRepeating(
&DesktopWindowTreeHostLinux::OnCompleteSwapWithNewSize,
base::Unretained(this)));
}
}
void DesktopWindowTreeHostLinux::OnNativeWidgetCreated(
const Widget::InitParams& params) {
CreateNonClientEventFilter();
DesktopWindowTreeHostPlatform::OnNativeWidgetCreated(params);
}
void DesktopWindowTreeHostLinux::InitModalType(ui::ModalType modal_type) {
switch (modal_type) {
case ui::MODAL_TYPE_NONE:
break;
default:
// TODO(erg): Figure out under what situations |modal_type| isn't
// none. The comment in desktop_native_widget_aura.cc suggests that this
// is rare.
NOTIMPLEMENTED();
}
}
Widget::MoveLoopResult DesktopWindowTreeHostLinux::RunMoveLoop(
const gfx::Vector2d& drag_offset,
Widget::MoveLoopSource source,
Widget::MoveLoopEscapeBehavior escape_behavior) {
GetContentWindow()->SetCapture();
// DesktopWindowTreeHostLinux::RunMoveLoop() may result in |this| being
// deleted. As an extra safity guard, keep track of |this| with a weak
// pointer, and only call ReleaseCapture() if it still exists.
//
// TODO(https://crbug.com/1289682): Consider removing capture set/unset
// during window drag 'n drop (detached).
auto weak_this = weak_factory_.GetWeakPtr();
Widget::MoveLoopResult result = DesktopWindowTreeHostPlatform::RunMoveLoop(
drag_offset, source, escape_behavior);
if (weak_this.get())
GetContentWindow()->ReleaseCapture();
return result;
}
gfx::Rect DesktopWindowTreeHostLinux::GetWindowBoundsInScreen() const {
if (!screen_bounds_.IsEmpty())
return screen_bounds_;
return DesktopWindowTreeHostPlatform::GetWindowBoundsInScreen();
}
gfx::Point DesktopWindowTreeHostLinux::GetLocationOnScreenInPixels() const {
if (!screen_bounds_.IsEmpty())
return screen_bounds_.origin();
return DesktopWindowTreeHostPlatform::GetLocationOnScreenInPixels();
}
void DesktopWindowTreeHostLinux::DispatchEvent(ui::Event* event) {
// In Windows, the native events sent to chrome are separated into client
// and non-client versions of events, which we record on our LocatedEvent
// structures. On X11/Wayland, we emulate the concept of non-client. Before we
// pass this event to the cross platform event handling framework, we need to
// make sure it is appropriately marked as non-client if it's in the non
// client area, or otherwise, we can get into a state where the a window is
// set as the |mouse_pressed_handler_| in window_event_dispatcher.cc
// despite the mouse button being released.
//
// We can't do this later in the dispatch process because we share that
// with ash, and ash gets confused about event IS_NON_CLIENT-ness on
// events, since ash doesn't expect this bit to be set, because it's never
// been set before. (This works on ash on Windows because none of the mouse
// events on the ash desktop are clicking in what Windows considers to be a
// non client area.) Likewise, we won't want to do the following in any
// WindowTreeHost that hosts ash.
int hit_test_code = HTNOWHERE;
if (event->IsMouseEvent() || event->IsTouchEvent()) {
ui::LocatedEvent* located_event = event->AsLocatedEvent();
if (GetContentWindow() && GetContentWindow()->delegate()) {
int flags = located_event->flags();
gfx::PointF location = located_event->location_f();
gfx::PointF location_in_dip =
GetRootTransform().InverseMapPoint(location).value_or(location);
hit_test_code = GetContentWindow()->delegate()->GetNonClientComponent(
gfx::ToRoundedPoint(location_in_dip));
if (hit_test_code != HTCLIENT && hit_test_code != HTNOWHERE)
flags |= ui::EF_IS_NON_CLIENT;
located_event->set_flags(flags);
}
// While we unset the urgency hint when we gain focus, we also must remove
// it on mouse clicks because we can call FlashFrame() on an active window.
if (located_event->IsMouseEvent() &&
(located_event->AsMouseEvent()->IsAnyButton() ||
located_event->IsMouseWheelEvent()))
FlashFrame(false);
}
// Prehandle the event as long as as we are not able to track if it is handled
// or not as SendEventToSink results in copying the event and our copy of the
// event will not set to handled unless a dispatcher or a target are
// destroyed.
if ((event->IsMouseEvent() || event->IsTouchEvent()) &&
non_client_window_event_filter_) {
non_client_window_event_filter_->HandleLocatedEventWithHitTest(
hit_test_code, event->AsLocatedEvent());
}
if (!event->handled())
WindowTreeHostPlatform::DispatchEvent(event);
}
void DesktopWindowTreeHostLinux::OnClosed() {
DestroyNonClientEventFilter();
DesktopWindowTreeHostPlatform::OnClosed();
}
ui::X11Extension* DesktopWindowTreeHostLinux::GetX11Extension() {
return platform_window() ? ui::GetX11Extension(*(platform_window()))
: nullptr;
}
const ui::X11Extension* DesktopWindowTreeHostLinux::GetX11Extension() const {
return platform_window() ? ui::GetX11Extension(*(platform_window()))
: nullptr;
}
#if BUILDFLAG(USE_ATK)
bool DesktopWindowTreeHostLinux::OnAtkKeyEvent(AtkKeyEventStruct* atk_event,
bool transient) {
if (!transient && !IsActive() && !HasCapture())
return false;
return ui::AtkUtilAuraLinux::HandleAtkKeyEvent(atk_event) ==
ui::DiscardAtkKeyEvent::Discard;
}
#endif
bool DesktopWindowTreeHostLinux::IsOverrideRedirect() const {
// BrowserDesktopWindowTreeHostLinux implements this for browser windows.
return false;
}
gfx::Rect DesktopWindowTreeHostLinux::GetGuessedFullScreenSizeInPx() const {
display::Screen* screen = display::Screen::GetScreen();
const display::Display display =
screen->GetDisplayMatching(GetWindowBoundsInScreen());
return gfx::Rect(gfx::ScaleToFlooredPoint(display.bounds().origin(),
display.device_scale_factor()),
display.GetSizeInPixel());
}
void DesktopWindowTreeHostLinux::AddAdditionalInitProperties(
const Widget::InitParams& params,
ui::PlatformWindowInitProperties* properties) {
// Set the background color on startup to make the initial flickering
// happening between the XWindow is mapped and the first expose event
// is completely handled less annoying. If possible, we use the content
// window's background color, otherwise we fallback to white.
ui::ColorId target_color;
switch (properties->type) {
case ui::PlatformWindowType::kBubble:
target_color = ui::kColorBubbleBackground;
break;
case ui::PlatformWindowType::kTooltip:
target_color = ui::kColorTooltipBackground;
break;
default:
target_color = ui::kColorWindowBackground;
break;
}
properties->background_color =
GetWidget()->GetColorProvider()->GetColor(target_color);
properties->icon = ViewsDelegate::GetInstance()->GetDefaultWindowIcon();
properties->wm_class_name = params.wm_class_name;
properties->wm_class_class = params.wm_class_class;
properties->wm_role_name = params.wm_role_name;
properties->wayland_app_id = params.wayland_app_id;
properties->parent_widget = params.parent_widget;
DCHECK(!properties->x11_extension_delegate);
properties->x11_extension_delegate = this;
}
base::flat_map<std::string, std::string>
DesktopWindowTreeHostLinux::GetKeyboardLayoutMap() {
if (auto* linux_ui = ui::LinuxUi::instance())
return linux_ui->GetKeyboardLayoutMap();
return WindowTreeHostPlatform::GetKeyboardLayoutMap();
}
void DesktopWindowTreeHostLinux::OnCompleteSwapWithNewSize(
const gfx::Size& size) {
if (GetX11Extension())
GetX11Extension()->OnCompleteSwapAfterResize();
}
void DesktopWindowTreeHostLinux::CreateNonClientEventFilter() {
DCHECK(!non_client_window_event_filter_);
non_client_window_event_filter_ = std::make_unique<WindowEventFilterClass>(
this, GetWmMoveResizeHandler(*platform_window()));
}
void DesktopWindowTreeHostLinux::DestroyNonClientEventFilter() {
non_client_window_event_filter_.reset();
}
void DesktopWindowTreeHostLinux::OnLostMouseGrab() {
dispatcher()->OnHostLostMouseGrab();
}
void DesktopWindowTreeHostLinux::EnableEventListening() {
DCHECK_GT(modal_dialog_counter_, 0UL);
if (!--modal_dialog_counter_)
targeter_for_modal_.reset();
}
// static
DesktopWindowTreeHost* DesktopWindowTreeHost::Create(
internal::NativeWidgetDelegate* native_widget_delegate,
DesktopNativeWidgetAura* desktop_native_widget_aura) {
return new DesktopWindowTreeHostLinux(native_widget_delegate,
desktop_native_widget_aura);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_window_tree_host_linux.cc | C++ | unknown | 13,059 |
// 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_WIDGET_DESKTOP_AURA_DESKTOP_WINDOW_TREE_HOST_LINUX_H_
#define UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_WINDOW_TREE_HOST_LINUX_H_
#include <memory>
#include <string>
#include <vector>
#include "base/gtest_prod_util.h"
#include "base/memory/weak_ptr.h"
#include "ui/aura/scoped_window_targeter.h"
#include "ui/base/buildflags.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/ozone/buildflags.h"
#include "ui/platform_window/extensions/x11_extension_delegate.h"
#include "ui/views/views_export.h"
#include "ui/views/widget/desktop_aura/desktop_window_tree_host_platform.h"
namespace aura {
class ScopedWindowTargeter;
} // namespace aura
namespace ui {
class X11Extension;
} // namespace ui
namespace views {
class WindowEventFilterLinux;
using WindowEventFilterClass = WindowEventFilterLinux;
// Contains Linux specific implementation, which supports both X11 and Wayland
// backend.
class VIEWS_EXPORT DesktopWindowTreeHostLinux
: public DesktopWindowTreeHostPlatform,
public ui::X11ExtensionDelegate {
public:
DesktopWindowTreeHostLinux(
internal::NativeWidgetDelegate* native_widget_delegate,
DesktopNativeWidgetAura* desktop_native_widget_aura);
DesktopWindowTreeHostLinux(const DesktopWindowTreeHostLinux&) = delete;
DesktopWindowTreeHostLinux& operator=(const DesktopWindowTreeHostLinux&) =
delete;
~DesktopWindowTreeHostLinux() override;
// Returns the current bounds in terms of the X11 Root Window including the
// borders provided by the window manager (if any). Not in use for Wayland.
gfx::Rect GetXRootWindowOuterBounds() const;
// DesktopWindowTreeHostPlatform:
void LowerWindow() override;
// Disables event listening to make |dialog| modal.
base::OnceClosure DisableEventListening();
void set_screen_bounds(const gfx::Rect& bounds) { screen_bounds_ = bounds; }
protected:
// Overridden from DesktopWindowTreeHost:
void Init(const Widget::InitParams& params) override;
void OnNativeWidgetCreated(const Widget::InitParams& params) override;
void InitModalType(ui::ModalType modal_type) override;
Widget::MoveLoopResult RunMoveLoop(
const gfx::Vector2d& drag_offset,
Widget::MoveLoopSource source,
Widget::MoveLoopEscapeBehavior escape_behavior) override;
gfx::Rect GetWindowBoundsInScreen() const override;
gfx::Point GetLocationOnScreenInPixels() const override;
// PlatformWindowDelegate:
void DispatchEvent(ui::Event* event) override;
void OnClosed() override;
ui::X11Extension* GetX11Extension();
const ui::X11Extension* GetX11Extension() const;
// DesktopWindowTreeHostPlatform:
void AddAdditionalInitProperties(
const Widget::InitParams& params,
ui::PlatformWindowInitProperties* properties) override;
private:
FRIEND_TEST_ALL_PREFIXES(DesktopWindowTreeHostPlatformImplTestWithTouch,
HitTest);
// DesktopWindowTreeHostPlatform:
base::flat_map<std::string, std::string> GetKeyboardLayoutMap() override;
// Called back by compositor_observer_ if the latter is set.
virtual void OnCompleteSwapWithNewSize(const gfx::Size& size);
void CreateNonClientEventFilter();
void DestroyNonClientEventFilter();
// X11ExtensionDelegate overrides:
void OnLostMouseGrab() override;
#if BUILDFLAG(USE_ATK)
bool OnAtkKeyEvent(AtkKeyEventStruct* atk_key_event, bool transient) override;
#endif // BUILDFLAG(USE_ATK)
bool IsOverrideRedirect() const override;
gfx::Rect GetGuessedFullScreenSizeInPx() const override;
// Enables event listening after closing |dialog|.
void EnableEventListening();
// A handler for events intended for non client area.
// A posthandler for events intended for non client area. Handles events if no
// other consumer handled them.
std::unique_ptr<WindowEventFilterClass> non_client_window_event_filter_;
std::unique_ptr<CompositorObserver> compositor_observer_;
std::unique_ptr<aura::ScopedWindowTargeter> targeter_for_modal_;
uint32_t modal_dialog_counter_ = 0;
// Override the screen bounds when the host is a child window.
gfx::Rect screen_bounds_;
// The display and the native X window hosting the root window.
base::WeakPtrFactory<DesktopWindowTreeHostLinux> weak_factory_{this};
};
} // namespace views
#endif // UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_WINDOW_TREE_HOST_LINUX_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_window_tree_host_linux.h | C++ | unknown | 4,494 |
// 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/widget/desktop_aura/desktop_window_tree_host_platform.h"
#include <memory>
#include <string>
#include <utility>
#include "base/containers/contains.h"
#include "base/functional/bind.h"
#include "base/notreached.h"
#include "base/ranges/algorithm.h"
#include "base/task/single_thread_task_runner.h"
#include "build/build_config.h"
#include "third_party/skia/include/core/SkPath.h"
#include "ui/aura/client/aura_constants.h"
#include "ui/aura/client/drag_drop_client.h"
#include "ui/aura/client/focus_client.h"
#include "ui/aura/client/transient_window_client.h"
#include "ui/base/hit_test.h"
#include "ui/base/owned_window_anchor.h"
#include "ui/base/ui_base_types.h"
#include "ui/compositor/compositor.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/paint_recorder.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/display/types/display_constants.h"
#include "ui/gfx/geometry/dip_util.h"
#include "ui/ozone/public/ozone_platform.h"
#include "ui/platform_window/extensions/workspace_extension.h"
#include "ui/platform_window/platform_window.h"
#include "ui/platform_window/platform_window_init_properties.h"
#include "ui/platform_window/wm/wm_move_loop_handler.h"
#include "ui/views/corewm/tooltip_aura.h"
#include "ui/views/corewm/tooltip_controller.h"
#include "ui/views/widget/desktop_aura/desktop_drag_drop_client_ozone.h"
#include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h"
#include "ui/views/widget/widget_aura_utils.h"
#include "ui/views/window/native_frame_view.h"
#include "ui/wm/core/window_util.h"
#include "ui/wm/public/window_move_client.h"
#if BUILDFLAG(IS_LINUX)
#include "ui/views/widget/desktop_aura/desktop_drag_drop_client_ozone_linux.h"
#endif
DEFINE_UI_CLASS_PROPERTY_TYPE(views::DesktopWindowTreeHostPlatform*)
namespace views {
DEFINE_UI_CLASS_PROPERTY_KEY(DesktopWindowTreeHostPlatform*,
kHostForRootWindow,
nullptr)
namespace {
// A list of all (top-level) windows that have been created but not yet
// destroyed.
std::list<gfx::AcceleratedWidget>* open_windows_ = nullptr;
bool DetermineInactivity(ui::WindowShowState show_state) {
if (show_state != ui::SHOW_STATE_DEFAULT &&
show_state != ui::SHOW_STATE_NORMAL &&
show_state != ui::SHOW_STATE_INACTIVE &&
show_state != ui::SHOW_STATE_MAXIMIZED) {
// It will behave like SHOW_STATE_NORMAL.
NOTIMPLEMENTED_LOG_ONCE();
}
// See comment in PlatformWindow::Show().
return show_state == ui::SHOW_STATE_INACTIVE;
}
ui::PlatformWindowOpacity GetPlatformWindowOpacity(
Widget::InitParams::WindowOpacity opacity) {
switch (opacity) {
case Widget::InitParams::WindowOpacity::kInferred:
return ui::PlatformWindowOpacity::kInferOpacity;
case Widget::InitParams::WindowOpacity::kOpaque:
return ui::PlatformWindowOpacity::kOpaqueWindow;
case Widget::InitParams::WindowOpacity::kTranslucent:
return ui::PlatformWindowOpacity::kTranslucentWindow;
}
return ui::PlatformWindowOpacity::kOpaqueWindow;
}
ui::PlatformWindowType GetPlatformWindowType(
Widget::InitParams::Type window_type,
bool requires_accelerated_widget) {
switch (window_type) {
case Widget::InitParams::TYPE_WINDOW:
return ui::PlatformWindowType::kWindow;
case Widget::InitParams::TYPE_MENU:
return ui::PlatformWindowType::kMenu;
case Widget::InitParams::TYPE_TOOLTIP:
return ui::PlatformWindowType::kTooltip;
case Widget::InitParams::TYPE_DRAG:
return ui::PlatformWindowType::kDrag;
case Widget::InitParams::TYPE_BUBBLE:
return requires_accelerated_widget ? ui::PlatformWindowType::kTooltip
: ui::PlatformWindowType::kBubble;
default:
return ui::PlatformWindowType::kPopup;
}
NOTREACHED_NORETURN();
}
ui::PlatformWindowShadowType GetPlatformWindowShadowType(
Widget::InitParams::ShadowType shadow_type) {
switch (shadow_type) {
case Widget::InitParams::ShadowType::kDefault:
return ui::PlatformWindowShadowType::kDefault;
case Widget::InitParams::ShadowType::kNone:
return ui::PlatformWindowShadowType::kNone;
case Widget::InitParams::ShadowType::kDrop:
return ui::PlatformWindowShadowType::kDrop;
}
NOTREACHED_NORETURN();
}
ui::PlatformWindowInitProperties ConvertWidgetInitParamsToInitProperties(
const Widget::InitParams& params,
bool requires_accelerated_widget) {
ui::PlatformWindowInitProperties properties;
properties.type =
GetPlatformWindowType(params.type, requires_accelerated_widget);
properties.activatable =
params.activatable == Widget::InitParams::Activatable::kYes;
properties.force_show_in_taskbar = params.force_show_in_taskbar;
properties.z_order = params.EffectiveZOrderLevel();
properties.keep_on_top = properties.z_order != ui::ZOrderLevel::kNormal;
properties.is_security_surface =
properties.z_order == ui::ZOrderLevel::kSecuritySurface;
properties.visible_on_all_workspaces = params.visible_on_all_workspaces;
properties.remove_standard_frame = params.remove_standard_frame;
properties.workspace = params.workspace;
properties.opacity = GetPlatformWindowOpacity(params.opacity);
properties.shadow_type = GetPlatformWindowShadowType(params.shadow_type);
if (params.parent && params.parent->GetHost())
properties.parent_widget = params.parent->GetHost()->GetAcceleratedWidget();
#if BUILDFLAG(IS_OZONE)
if (ui::OzonePlatform::GetInstance()
->GetPlatformProperties()
.set_parent_for_non_top_level_windows) {
// If context has been set, use that as the parent_widget so that Wayland
// creates a correct hierarchy of windows.
if (params.context) {
auto* host = params.context->GetHost();
// Use this context as a parent widget iff the host for a root window is
// set (this happens during OnNativeWidgetCreated). Otherwise, the context
// can be a native window of a WindowTreeHost created by
// WindowTreeHost::Create, which we don't want to have as a context (this
// happens in tests - called by TestScreen, AuraTestHelper,
// aura::DemoMain, and SitePerProcessBrowserTest).
if (host && host->window()->GetProperty(kHostForRootWindow))
properties.parent_widget = host->GetAcceleratedWidget();
}
}
properties.inhibit_keyboard_shortcuts = params.inhibit_keyboard_shortcuts;
#endif
#if BUILDFLAG(IS_CHROMEOS)
// Set restore members for windows to know ids upon creation. See the
// corresponding comment in Widget::InitParams.
properties.restore_session_id = params.restore_session_id;
properties.restore_window_id = params.restore_window_id;
properties.restore_window_id_source = params.restore_window_id_source;
#endif
#if BUILDFLAG(IS_FUCHSIA)
properties.enable_keyboard = true;
#endif
return properties;
}
SkPath GetWindowMask(const Widget* widget) {
if (!widget->non_client_view())
return SkPath();
SkPath window_mask;
// Some frame views define a custom (non-rectanguar) window mask.
// If so, use it to define the window shape. If not, fall through.
const_cast<NonClientView*>(widget->non_client_view())
->GetWindowMask(widget->GetWindowBoundsInScreen().size(), &window_mask);
return window_mask;
}
} // namespace
////////////////////////////////////////////////////////////////////////////////
// DesktopWindowTreeHostPlatform:
DesktopWindowTreeHostPlatform::DesktopWindowTreeHostPlatform(
internal::NativeWidgetDelegate* native_widget_delegate,
DesktopNativeWidgetAura* desktop_native_widget_aura)
: native_widget_delegate_(native_widget_delegate->AsWidget()->GetWeakPtr()),
desktop_native_widget_aura_(desktop_native_widget_aura),
window_move_client_(this) {}
DesktopWindowTreeHostPlatform::~DesktopWindowTreeHostPlatform() {
window()->ClearProperty(kHostForRootWindow);
DCHECK(!platform_window()) << "The host must be closed before destroying it.";
desktop_native_widget_aura_->OnDesktopWindowTreeHostDestroyed(this);
DestroyDispatcher();
}
// static
aura::Window* DesktopWindowTreeHostPlatform::GetContentWindowForWidget(
gfx::AcceleratedWidget widget) {
auto* host = DesktopWindowTreeHostPlatform::GetHostForWidget(widget);
return host ? host->GetContentWindow() : nullptr;
}
// static
DesktopWindowTreeHostPlatform* DesktopWindowTreeHostPlatform::GetHostForWidget(
gfx::AcceleratedWidget widget) {
aura::WindowTreeHost* host =
aura::WindowTreeHost::GetForAcceleratedWidget(widget);
return host ? host->window()->GetProperty(kHostForRootWindow) : nullptr;
}
// static
std::vector<aura::Window*> DesktopWindowTreeHostPlatform::GetAllOpenWindows() {
std::vector<aura::Window*> windows(open_windows().size());
base::ranges::transform(
open_windows(), windows.begin(),
DesktopWindowTreeHostPlatform::GetContentWindowForWidget);
return windows;
}
// static
void DesktopWindowTreeHostPlatform::CleanUpWindowList(
void (*func)(aura::Window* window)) {
if (!open_windows_)
return;
while (!open_windows_->empty()) {
gfx::AcceleratedWidget widget = open_windows_->front();
func(DesktopWindowTreeHostPlatform::GetContentWindowForWidget(widget));
if (!open_windows_->empty() && open_windows_->front() == widget)
open_windows_->erase(open_windows_->begin());
}
delete open_windows_;
open_windows_ = nullptr;
}
aura::Window* DesktopWindowTreeHostPlatform::GetContentWindow() {
return desktop_native_widget_aura_->content_window();
}
void DesktopWindowTreeHostPlatform::Init(const Widget::InitParams& params) {
if (params.type == Widget::InitParams::TYPE_WINDOW)
GetContentWindow()->SetProperty(aura::client::kAnimationsDisabledKey, true);
#if defined(USE_AURA) && (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS))
const bool requires_accelerated_widget = params.requires_accelerated_widget;
#else
const bool requires_accelerated_widget = false;
#endif
ui::PlatformWindowInitProperties properties =
ConvertWidgetInitParamsToInitProperties(params,
requires_accelerated_widget);
AddAdditionalInitProperties(params, &properties);
// If we have a parent, record the parent/child relationship. We use this
// data during destruction to make sure that when we try to close a parent
// window, we also destroy all child windows.
if (properties.parent_widget) {
window_parent_ = DesktopWindowTreeHostPlatform::GetHostForWidget(
properties.parent_widget);
if (window_parent_)
window_parent_->window_children_.insert(this);
}
// Calculate initial bounds.
properties.bounds = params.bounds;
// Set extensions delegate.
DCHECK(!properties.workspace_extension_delegate);
properties.workspace_extension_delegate = this;
CreateAndSetPlatformWindow(std::move(properties));
// Disable compositing on tooltips as a workaround for
// https://crbug.com/442111.
CreateCompositor(params.force_software_compositing ||
params.type == Widget::InitParams::TYPE_TOOLTIP);
WindowTreeHost::OnAcceleratedWidgetAvailable();
InitHost();
window()->Show();
}
void DesktopWindowTreeHostPlatform::OnNativeWidgetCreated(
const Widget::InitParams& params) {
window()->SetProperty(kHostForRootWindow, this);
// This reroutes RunMoveLoop requests to the DesktopWindowTreeHostPlatform.
// The availability of this feature depends on a platform (PlatformWindow)
// that implements RunMoveLoop.
wm::SetWindowMoveClient(window(), &window_move_client_);
platform_window()->SetUseNativeFrame(params.type ==
Widget::InitParams::TYPE_WINDOW &&
!params.remove_standard_frame);
native_widget_delegate_->OnNativeWidgetCreated();
}
void DesktopWindowTreeHostPlatform::OnWidgetInitDone() {
// Once we can guarantee |NonClientView| is created OnWidgetInitDone,
// UpdateWindowTransparency and FillsBoundsCompletely accordingly.
desktop_native_widget_aura_->UpdateWindowTransparency();
GetContentWindow()->SetFillsBoundsCompletely(
GetWindowMaskForClipping().isEmpty());
}
void DesktopWindowTreeHostPlatform::OnActiveWindowChanged(bool active) {}
std::unique_ptr<corewm::Tooltip>
DesktopWindowTreeHostPlatform::CreateTooltip() {
return std::make_unique<corewm::TooltipAura>();
}
std::unique_ptr<aura::client::DragDropClient>
DesktopWindowTreeHostPlatform::CreateDragDropClient() {
ui::WmDragHandler* drag_handler = ui::GetWmDragHandler(*(platform_window()));
std::unique_ptr<DesktopDragDropClientOzone> drag_drop_client =
#if BUILDFLAG(IS_LINUX)
std::make_unique<DesktopDragDropClientOzoneLinux>(window(), drag_handler);
#else
std::make_unique<DesktopDragDropClientOzone>(window(), drag_handler);
#endif // BUILDFLAG(IS_LINUX)
// Set a class property key, which allows |drag_drop_client| to be used for
// drop action.
SetWmDropHandler(platform_window(), drag_drop_client.get());
return std::move(drag_drop_client);
}
void DesktopWindowTreeHostPlatform::Close() {
// If we are in process of closing or the PlatformWindow has already been
// closed, do nothing.
if (close_widget_factory_.HasWeakPtrs() || !platform_window())
return;
GetContentWindow()->Hide();
// Hide while waiting for the close.
// Please note that it's better to call WindowTreeHost::Hide, which also calls
// PlatformWindow::Hide and Compositor::SetVisible(false).
Hide();
// And we delay the close so that if we are called from an ATL callback,
// we don't destroy the window before the callback returned (as the caller
// may delete ourselves on destroy and the ATL callback would still
// dereference us when the callback returns).
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(&DesktopWindowTreeHostPlatform::CloseNow,
close_widget_factory_.GetWeakPtr()));
}
void DesktopWindowTreeHostPlatform::CloseNow() {
if (!platform_window())
return;
#if BUILDFLAG(IS_OZONE)
SetWmDropHandler(platform_window(), nullptr);
#endif
platform_window()->PrepareForShutdown();
ReleaseCapture();
if (native_widget_delegate_)
native_widget_delegate_->OnNativeWidgetDestroying();
// If we have children, close them. Use a copy for iteration because they'll
// remove themselves.
std::set<DesktopWindowTreeHostPlatform*> window_children_copy =
window_children_;
for (auto* child : window_children_copy)
child->CloseNow();
DCHECK(window_children_.empty());
// If we have a parent, remove ourselves from its children list.
if (window_parent_) {
window_parent_->window_children_.erase(this);
window_parent_ = nullptr;
}
// Destroy the compositor before destroying the |platform_window()| since
// shutdown may try to swap, and the swap without a window may cause an error
// in X Server or Wayland, which causes a crash with in-process renderer, for
// example.
DestroyCompositor();
platform_window()->Close();
}
aura::WindowTreeHost* DesktopWindowTreeHostPlatform::AsWindowTreeHost() {
return this;
}
void DesktopWindowTreeHostPlatform::Show(ui::WindowShowState show_state,
const gfx::Rect& restore_bounds) {
if (compositor())
SetVisible(true);
platform_window()->Show(DetermineInactivity(show_state));
switch (show_state) {
case ui::SHOW_STATE_MAXIMIZED:
platform_window()->Maximize();
if (!restore_bounds.IsEmpty()) {
// Enforce |restored_bounds_in_pixels_| since calling Maximize() could
// have reset it.
platform_window()->SetRestoredBoundsInDIP(restore_bounds);
}
break;
case ui::SHOW_STATE_MINIMIZED:
platform_window()->Minimize();
break;
case ui::SHOW_STATE_FULLSCREEN:
SetFullscreen(true, display::kInvalidDisplayId);
break;
default:
break;
}
if (native_widget_delegate_->CanActivate()) {
if (show_state != ui::SHOW_STATE_INACTIVE)
Activate();
// SetInitialFocus() should be always be called, even for
// SHOW_STATE_INACTIVE. If the window has to stay inactive, the method will
// do the right thing.
// Activate() might fail if the window is non-activatable. In this case, we
// should pass SHOW_STATE_INACTIVE to SetInitialFocus() to stop the initial
// focused view from getting focused. See https://crbug.com/515594 for
// example.
native_widget_delegate_->SetInitialFocus(
IsActive() ? show_state : ui::SHOW_STATE_INACTIVE);
}
GetContentWindow()->Show();
}
bool DesktopWindowTreeHostPlatform::IsVisible() const {
return platform_window()->IsVisible();
}
void DesktopWindowTreeHostPlatform::SetSize(const gfx::Size& size) {
auto bounds_in_dip = platform_window()->GetBoundsInDIP();
bounds_in_dip.set_size(size);
platform_window()->SetBoundsInDIP(bounds_in_dip);
}
void DesktopWindowTreeHostPlatform::StackAbove(aura::Window* window) {
if (!window || !window->GetRootWindow())
return;
platform_window()->StackAbove(window->GetHost()->GetAcceleratedWidget());
}
void DesktopWindowTreeHostPlatform::StackAtTop() {
platform_window()->StackAtTop();
}
bool DesktopWindowTreeHostPlatform::IsStackedAbove(aura::Window* window) {
// TODO(https://crbug.com/1363218) Implement Window layer check
NOTREACHED_NORETURN();
}
void DesktopWindowTreeHostPlatform::CenterWindow(const gfx::Size& size) {
gfx::Rect parent_bounds = GetWorkAreaBoundsInScreen();
// If |window_|'s transient parent bounds are big enough to contain |size|,
// use them instead.
if (wm::GetTransientParent(GetContentWindow())) {
gfx::Rect transient_parent_rect =
wm::GetTransientParent(GetContentWindow())->GetBoundsInScreen();
// Consider using the intersect of the work area.
if (transient_parent_rect.height() >= size.height() &&
transient_parent_rect.width() >= size.width()) {
parent_bounds = transient_parent_rect;
}
}
gfx::Rect window_bounds_in_screen = parent_bounds;
window_bounds_in_screen.ClampToCenteredSize(size);
SetBoundsInDIP(window_bounds_in_screen);
}
void DesktopWindowTreeHostPlatform::GetWindowPlacement(
gfx::Rect* bounds,
ui::WindowShowState* show_state) const {
*bounds = GetRestoredBounds();
if (IsFullscreen())
*show_state = ui::SHOW_STATE_FULLSCREEN;
else if (IsMinimized())
*show_state = ui::SHOW_STATE_MINIMIZED;
else if (IsMaximized())
*show_state = ui::SHOW_STATE_MAXIMIZED;
else if (!IsActive())
*show_state = ui::SHOW_STATE_INACTIVE;
else
*show_state = ui::SHOW_STATE_NORMAL;
}
gfx::Rect DesktopWindowTreeHostPlatform::GetWindowBoundsInScreen() const {
return platform_window()->GetBoundsInDIP();
}
gfx::Rect DesktopWindowTreeHostPlatform::GetClientAreaBoundsInScreen() const {
// Attempts to calculate the rect by asking the NonClientFrameView what it
// thought its GetBoundsForClientView() were broke combobox drop down
// placement.
return GetWindowBoundsInScreen();
}
gfx::Rect DesktopWindowTreeHostPlatform::GetRestoredBounds() const {
// We can't reliably track the restored bounds of a window, but we can get
// the 90% case down. When *chrome* is the process that requests maximizing
// or restoring bounds, we can record the current bounds before we request
// maximization, and clear it when we detect a state change.
gfx::Rect restored_bounds = platform_window()->GetRestoredBoundsInDIP();
// When window is resized, |restored bounds| is not set and empty.
// If |restored bounds| is empty, it returns the current window size.
if (!restored_bounds.IsEmpty())
return restored_bounds;
return GetWindowBoundsInScreen();
}
std::string DesktopWindowTreeHostPlatform::GetWorkspace() const {
auto* workspace_extension = ui::GetWorkspaceExtension(*platform_window());
return workspace_extension ? workspace_extension->GetWorkspace()
: std::string();
}
gfx::Rect DesktopWindowTreeHostPlatform::GetWorkAreaBoundsInScreen() const {
return GetDisplayNearestRootWindow().work_area();
}
void DesktopWindowTreeHostPlatform::SetShape(
std::unique_ptr<Widget::ShapeRects> native_shape) {
// TODO(crbug.com/1158733) : When supporting PlatformWindow::SetShape,
// Calls ui::Layer::SetAlphaShape and sets |is_shape_explicitly_set_| to true.
platform_window()->SetShape(std::move(native_shape), GetRootTransform());
}
void DesktopWindowTreeHostPlatform::Activate() {
platform_window()->Activate();
}
void DesktopWindowTreeHostPlatform::Deactivate() {
ReleaseCapture();
platform_window()->Deactivate();
}
bool DesktopWindowTreeHostPlatform::IsActive() const {
return is_active_;
}
void DesktopWindowTreeHostPlatform::Maximize() {
platform_window()->Maximize();
if (IsMinimized())
Show(ui::SHOW_STATE_NORMAL, gfx::Rect());
}
void DesktopWindowTreeHostPlatform::Minimize() {
ReleaseCapture();
platform_window()->Minimize();
}
void DesktopWindowTreeHostPlatform::Restore() {
platform_window()->Restore();
Show(ui::SHOW_STATE_NORMAL, gfx::Rect());
}
bool DesktopWindowTreeHostPlatform::IsMaximized() const {
return platform_window()->GetPlatformWindowState() ==
ui::PlatformWindowState::kMaximized;
}
bool DesktopWindowTreeHostPlatform::IsMinimized() const {
return platform_window()->GetPlatformWindowState() ==
ui::PlatformWindowState::kMinimized;
}
bool DesktopWindowTreeHostPlatform::HasCapture() const {
return platform_window()->HasCapture();
}
void DesktopWindowTreeHostPlatform::SetZOrderLevel(ui::ZOrderLevel order) {
platform_window()->SetZOrderLevel(order);
}
ui::ZOrderLevel DesktopWindowTreeHostPlatform::GetZOrderLevel() const {
return platform_window()->GetZOrderLevel();
}
void DesktopWindowTreeHostPlatform::SetVisibleOnAllWorkspaces(
bool always_visible) {
auto* workspace_extension = ui::GetWorkspaceExtension(*platform_window());
if (workspace_extension)
workspace_extension->SetVisibleOnAllWorkspaces(always_visible);
}
bool DesktopWindowTreeHostPlatform::IsVisibleOnAllWorkspaces() const {
auto* workspace_extension = ui::GetWorkspaceExtension(*platform_window());
return workspace_extension ? workspace_extension->IsVisibleOnAllWorkspaces()
: false;
}
bool DesktopWindowTreeHostPlatform::SetWindowTitle(
const std::u16string& title) {
if (window_title_ == title)
return false;
window_title_ = title;
platform_window()->SetTitle(window_title_);
return true;
}
void DesktopWindowTreeHostPlatform::ClearNativeFocus() {
// This method is weird and misnamed. Instead of clearing the native focus,
// it sets the focus to our content_window, which will trigger a cascade
// of focus changes into views.
if (GetContentWindow() && aura::client::GetFocusClient(GetContentWindow()) &&
GetContentWindow()->Contains(
aura::client::GetFocusClient(GetContentWindow())
->GetFocusedWindow())) {
aura::client::GetFocusClient(GetContentWindow())
->FocusWindow(GetContentWindow());
}
}
bool DesktopWindowTreeHostPlatform::IsMoveLoopSupported() const {
return platform_window()->IsClientControlledWindowMovementSupported();
}
Widget::MoveLoopResult DesktopWindowTreeHostPlatform::RunMoveLoop(
const gfx::Vector2d& drag_offset,
Widget::MoveLoopSource source,
Widget::MoveLoopEscapeBehavior escape_behavior) {
auto* move_loop_handler = ui::GetWmMoveLoopHandler(*platform_window());
if (move_loop_handler && move_loop_handler->RunMoveLoop(drag_offset))
return Widget::MoveLoopResult::kSuccessful;
return Widget::MoveLoopResult::kCanceled;
}
void DesktopWindowTreeHostPlatform::EndMoveLoop() {
auto* move_loop_handler = ui::GetWmMoveLoopHandler(*platform_window());
if (move_loop_handler)
move_loop_handler->EndMoveLoop();
}
void DesktopWindowTreeHostPlatform::SetVisibilityChangedAnimationsEnabled(
bool value) {
platform_window()->SetVisibilityChangedAnimationsEnabled(value);
}
std::unique_ptr<NonClientFrameView>
DesktopWindowTreeHostPlatform::CreateNonClientFrameView() {
return ShouldUseNativeFrame() ? std::make_unique<NativeFrameView>(GetWidget())
: nullptr;
}
bool DesktopWindowTreeHostPlatform::ShouldUseNativeFrame() const {
return platform_window()->ShouldUseNativeFrame();
}
bool DesktopWindowTreeHostPlatform::ShouldWindowContentsBeTransparent() const {
return platform_window()->ShouldWindowContentsBeTransparent() ||
!(GetWindowMaskForClipping().isEmpty());
}
void DesktopWindowTreeHostPlatform::FrameTypeChanged() {
if (!native_widget_delegate_) {
return;
}
Widget::FrameType new_type =
native_widget_delegate_->AsWidget()->frame_type();
if (new_type == Widget::FrameType::kDefault) {
// The default is determined by Widget::InitParams::remove_standard_frame
// and does not change.
return;
}
platform_window()->SetUseNativeFrame(new_type ==
Widget::FrameType::kForceNative);
// Replace the frame and layout the contents. Even though we don't have a
// swappable glass frame like on Windows, we still replace the frame because
// the button assets don't update otherwise.
if (GetWidget()->non_client_view())
GetWidget()->non_client_view()->UpdateFrame();
}
void DesktopWindowTreeHostPlatform::SetFullscreen(bool fullscreen,
int64_t target_display_id) {
auto weak_ptr = GetWeakPtr();
platform_window()->SetFullscreen(fullscreen, target_display_id);
if (!weak_ptr)
return;
// The state must change synchronously to let media react on fullscreen
// changes.
DCHECK_EQ(fullscreen, IsFullscreen());
if (IsFullscreen() == fullscreen)
ScheduleRelayout();
// Else: the widget will be relaid out either when the window bounds change
// or when |platform_window|'s fullscreen state changes.
}
bool DesktopWindowTreeHostPlatform::IsFullscreen() const {
return platform_window()->GetPlatformWindowState() ==
ui::PlatformWindowState::kFullScreen;
}
void DesktopWindowTreeHostPlatform::SetOpacity(float opacity) {
GetContentWindow()->layer()->SetOpacity(opacity);
platform_window()->SetOpacity(opacity);
}
void DesktopWindowTreeHostPlatform::SetAspectRatio(
const gfx::SizeF& aspect_ratio,
const gfx::Size& excluded_margin) {
// TODO(crbug.com/1407629): send `excluded_margin`.
if (excluded_margin.width() > 0 || excluded_margin.height() > 0) {
NOTIMPLEMENTED_LOG_ONCE();
}
platform_window()->SetAspectRatio(aspect_ratio);
}
void DesktopWindowTreeHostPlatform::SetWindowIcons(
const gfx::ImageSkia& window_icon,
const gfx::ImageSkia& app_icon) {
platform_window()->SetWindowIcons(window_icon, app_icon);
}
void DesktopWindowTreeHostPlatform::InitModalType(ui::ModalType modal_type) {
NOTIMPLEMENTED_LOG_ONCE();
}
void DesktopWindowTreeHostPlatform::FlashFrame(bool flash_frame) {
platform_window()->FlashFrame(flash_frame);
}
bool DesktopWindowTreeHostPlatform::IsAnimatingClosed() const {
return platform_window()->IsAnimatingClosed();
}
bool DesktopWindowTreeHostPlatform::IsTranslucentWindowOpacitySupported()
const {
return platform_window()->IsTranslucentWindowOpacitySupported();
}
void DesktopWindowTreeHostPlatform::SizeConstraintsChanged() {
platform_window()->SizeConstraintsChanged();
}
bool DesktopWindowTreeHostPlatform::ShouldUpdateWindowTransparency() const {
return true;
}
bool DesktopWindowTreeHostPlatform::ShouldUseDesktopNativeCursorManager()
const {
return true;
}
bool DesktopWindowTreeHostPlatform::ShouldCreateVisibilityController() const {
return true;
}
void DesktopWindowTreeHostPlatform::UpdateWindowShapeIfNeeded(
const ui::PaintContext& context) {
if (is_shape_explicitly_set_)
return;
SkPath clip_path = GetWindowMaskForClipping();
if (clip_path.isEmpty())
return;
ui::PaintRecorder recorder(context, GetWindowBoundsInScreen().size());
recorder.canvas()->ClipPath(clip_path, true);
}
void DesktopWindowTreeHostPlatform::SetBoundsInDIP(const gfx::Rect& bounds) {
platform_window()->SetBoundsInDIP(bounds);
}
gfx::Transform DesktopWindowTreeHostPlatform::GetRootTransform() const {
// TODO(crbug.com/1306688): This can use wrong scale during initialization.
// Revisit this as a part of 'use dip' work.
display::Display display = display::Screen::GetScreen()->GetPrimaryDisplay();
// This might be called before the |platform_window| is created. Thus,
// explicitly check if that exists before trying to access its visibility and
// the display where it is shown.
if (platform_window())
display = GetDisplayNearestRootWindow();
else if (window_parent_)
display = window_parent_->GetDisplayNearestRootWindow();
gfx::Transform transform;
float scale = display.device_scale_factor();
transform.Scale(scale, scale);
return transform;
}
void DesktopWindowTreeHostPlatform::ShowImpl() {
Show(ui::SHOW_STATE_NORMAL, gfx::Rect());
}
void DesktopWindowTreeHostPlatform::HideImpl() {
WindowTreeHostPlatform::HideImpl();
native_widget_delegate_->OnNativeWidgetVisibilityChanged(false);
}
gfx::Rect DesktopWindowTreeHostPlatform::CalculateRootWindowBounds() const {
return gfx::Rect(platform_window()->GetBoundsInDIP().size());
}
gfx::Rect DesktopWindowTreeHostPlatform::GetBoundsInDIP() const {
return platform_window()->GetBoundsInDIP();
}
void DesktopWindowTreeHostPlatform::OnClosed() {
open_windows().remove(GetAcceleratedWidget());
wm::SetWindowMoveClient(window(), nullptr);
SetWmDropHandler(platform_window(), nullptr);
desktop_native_widget_aura_->OnHostWillClose();
SetPlatformWindow(nullptr);
desktop_native_widget_aura_->OnHostClosed();
}
void DesktopWindowTreeHostPlatform::OnWindowStateChanged(
ui::PlatformWindowState old_state,
ui::PlatformWindowState new_state) {
bool was_minimized = old_state == ui::PlatformWindowState::kMinimized;
bool is_minimized = new_state == ui::PlatformWindowState::kMinimized;
// Propagate minimization/restore to compositor to avoid drawing 'blank'
// frames that could be treated as previews, which show content even if a
// window is minimized.
if (is_minimized != was_minimized) {
if (is_minimized) {
SetVisible(false);
GetContentWindow()->Hide();
} else {
GetContentWindow()->Show();
SetVisible(true);
}
}
// Now that we have different window properties, we may need to relayout the
// window. (The windows code doesn't need this because their window change is
// synchronous.)
ScheduleRelayout();
}
void DesktopWindowTreeHostPlatform::OnCloseRequest() {
GetWidget()->Close();
}
void DesktopWindowTreeHostPlatform::OnAcceleratedWidgetAvailable(
gfx::AcceleratedWidget widget) {
DCHECK(!base::Contains(open_windows(), widget));
open_windows().push_front(widget);
aura::WindowTreeHostPlatform::OnAcceleratedWidgetAvailable(widget);
}
void DesktopWindowTreeHostPlatform::OnWillDestroyAcceleratedWidget() {
desktop_native_widget_aura_->OnHostWillClose();
}
void DesktopWindowTreeHostPlatform::OnActivationChanged(bool active) {
if (active) {
auto widget = GetAcceleratedWidget();
open_windows().remove(widget);
open_windows().insert(open_windows().begin(), widget);
}
if (is_active_ == active)
return;
is_active_ = active;
aura::WindowTreeHostPlatform::OnActivationChanged(active);
desktop_native_widget_aura_->HandleActivationChanged(active);
ScheduleRelayout();
}
absl::optional<gfx::Size>
DesktopWindowTreeHostPlatform::GetMinimumSizeForWindow() {
return native_widget_delegate_->GetMinimumSize();
}
absl::optional<gfx::Size>
DesktopWindowTreeHostPlatform::GetMaximumSizeForWindow() {
return native_widget_delegate_->GetMaximumSize();
}
SkPath DesktopWindowTreeHostPlatform::GetWindowMaskForWindowShapeInPixels() {
SkPath window_mask = GetWindowMask(GetWidget());
// Convert SkPath in DIPs to pixels.
if (!window_mask.isEmpty()) {
window_mask.transform(
gfx::TransformToFlattenedSkMatrix(GetRootTransform()));
}
return window_mask;
}
absl::optional<ui::MenuType> DesktopWindowTreeHostPlatform::GetMenuType() {
return GetContentWindow()->GetProperty(aura::client::kMenuType);
}
absl::optional<ui::OwnedWindowAnchor>
DesktopWindowTreeHostPlatform::GetOwnedWindowAnchorAndRectInDIP() {
const auto* anchor =
GetContentWindow()->GetProperty(aura::client::kOwnedWindowAnchor);
return anchor ? absl::make_optional(*anchor) : absl::nullopt;
}
gfx::Rect DesktopWindowTreeHostPlatform::ConvertRectToPixels(
const gfx::Rect& rect_in_dip) const {
return ToPixelRect(rect_in_dip);
}
gfx::Rect DesktopWindowTreeHostPlatform::ConvertRectToDIP(
const gfx::Rect& rect_in_pixels) const {
return ToDIPRect(rect_in_pixels);
}
gfx::PointF DesktopWindowTreeHostPlatform::ConvertScreenPointToLocalDIP(
const gfx::Point& screen_in_pixels) const {
#if BUILDFLAG(IS_CHROMEOS_LACROS)
// lacros should not use this.
NOTREACHED_NORETURN();
#else
// TODO(crbug.com/1318279): DIP should use gfx::PointF. Fix this as
// a part of cleanup work(crbug.com/1318279).
gfx::Point local_dip(screen_in_pixels);
ConvertScreenInPixelsToDIP(&local_dip);
return gfx::PointF(local_dip);
#endif
}
void DesktopWindowTreeHostPlatform::OnWorkspaceChanged() {
OnHostWorkspaceChanged();
}
gfx::Rect DesktopWindowTreeHostPlatform::ToDIPRect(
const gfx::Rect& rect_in_pixels) const {
return GetRootTransform()
.InverseMapRect(rect_in_pixels)
.value_or(rect_in_pixels);
}
gfx::Rect DesktopWindowTreeHostPlatform::ToPixelRect(
const gfx::Rect& rect_in_dip) const {
gfx::RectF rect_in_pixels_f =
GetRootTransform().MapRect(gfx::RectF(rect_in_dip));
// Due to the limitation of IEEE floating point representation and rounding
// error, the converted result may become slightly larger than expected value,
// such as 3000.0005. Allow 0.001 eplisin to round down in such case. This is
// also used in cc/viz. See crbug.com/1418606.
constexpr float kEpsilon = 0.001f;
return gfx::ToEnclosingRectIgnoringError(rect_in_pixels_f, kEpsilon);
}
Widget* DesktopWindowTreeHostPlatform::GetWidget() {
return native_widget_delegate_->AsWidget();
}
const Widget* DesktopWindowTreeHostPlatform::GetWidget() const {
return native_widget_delegate_->AsWidget();
}
views::corewm::TooltipController*
DesktopWindowTreeHostPlatform::tooltip_controller() {
return desktop_native_widget_aura_->tooltip_controller();
}
void DesktopWindowTreeHostPlatform::ScheduleRelayout() {
Widget* widget = native_widget_delegate_->AsWidget();
NonClientView* non_client_view = widget->non_client_view();
// non_client_view may be NULL, especially during creation.
if (non_client_view) {
if (non_client_view->frame_view())
non_client_view->frame_view()->InvalidateLayout();
non_client_view->client_view()->InvalidateLayout();
non_client_view->InvalidateLayout();
// Once |NonClientView| is invalidateLayout,
// UpdateWindowTransparency and FillsBoundsCompletely accordingly.
desktop_native_widget_aura_->UpdateWindowTransparency();
GetContentWindow()->SetFillsBoundsCompletely(
GetWindowMaskForClipping().isEmpty());
}
}
void DesktopWindowTreeHostPlatform::SetVisible(bool visible) {
if (compositor())
compositor()->SetVisible(visible);
native_widget_delegate_->OnNativeWidgetVisibilityChanged(visible);
}
void DesktopWindowTreeHostPlatform::AddAdditionalInitProperties(
const Widget::InitParams& params,
ui::PlatformWindowInitProperties* properties) {}
SkPath DesktopWindowTreeHostPlatform::GetWindowMaskForClipping() const {
if (!platform_window()->ShouldUpdateWindowShape())
return SkPath();
return GetWindowMask(GetWidget());
}
display::Display DesktopWindowTreeHostPlatform::GetDisplayNearestRootWindow()
const {
DCHECK(window());
DCHECK(window()->IsRootWindow());
// TODO(sky): GetDisplayNearestWindow() should take a const aura::Window*.
return display::Screen::GetScreen()->GetDisplayNearestWindow(
const_cast<aura::Window*>(window()));
}
////////////////////////////////////////////////////////////////////////////////
// DesktopWindowTreeHost:
// Linux subclasses this host and adds some Linux specific bits.
#if !BUILDFLAG(IS_LINUX) && !BUILDFLAG(IS_CHROMEOS)
// static
DesktopWindowTreeHost* DesktopWindowTreeHost::Create(
internal::NativeWidgetDelegate* native_widget_delegate,
DesktopNativeWidgetAura* desktop_native_widget_aura) {
return new DesktopWindowTreeHostPlatform(native_widget_delegate,
desktop_native_widget_aura);
}
#endif
// static
std::list<gfx::AcceleratedWidget>&
DesktopWindowTreeHostPlatform::open_windows() {
if (!open_windows_)
open_windows_ = new std::list<gfx::AcceleratedWidget>();
return *open_windows_;
}
// static
bool DesktopWindowTreeHostPlatform::has_open_windows() {
return !!open_windows_;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_window_tree_host_platform.cc | C++ | unknown | 37,336 |
// 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_WIDGET_DESKTOP_AURA_DESKTOP_WINDOW_TREE_HOST_PLATFORM_H_
#define UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_WINDOW_TREE_HOST_PLATFORM_H_
#include <list>
#include <memory>
#include <set>
#include <string>
#include <vector>
#include "base/gtest_prod_util.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "build/build_config.h"
#include "ui/aura/window_tree_host_platform.h"
#include "ui/base/ui_base_types.h"
#include "ui/platform_window/extensions/workspace_extension_delegate.h"
#include "ui/views/views_export.h"
#include "ui/views/widget/desktop_aura/desktop_window_tree_host.h"
#include "ui/views/widget/desktop_aura/window_move_client_platform.h"
namespace ui {
class PaintContext;
} // namespace ui
namespace views {
namespace corewm {
class TooltipController;
}
class VIEWS_EXPORT DesktopWindowTreeHostPlatform
: public aura::WindowTreeHostPlatform,
public DesktopWindowTreeHost,
public ui::WorkspaceExtensionDelegate {
public:
DesktopWindowTreeHostPlatform(
internal::NativeWidgetDelegate* native_widget_delegate,
DesktopNativeWidgetAura* desktop_native_widget_aura);
DesktopWindowTreeHostPlatform(const DesktopWindowTreeHostPlatform&) = delete;
DesktopWindowTreeHostPlatform& operator=(
const DesktopWindowTreeHostPlatform&) = delete;
~DesktopWindowTreeHostPlatform() override;
// A way of converting a |widget| into the content_window()
// of the associated DesktopNativeWidgetAura.
static aura::Window* GetContentWindowForWidget(gfx::AcceleratedWidget widget);
// A way of converting a |widget| into this object.
static DesktopWindowTreeHostPlatform* GetHostForWidget(
gfx::AcceleratedWidget widget);
// Get all open top-level windows. This includes windows that may not be
// visible. This list is sorted in their stacking order, i.e. the first window
// is the topmost window.
static std::vector<aura::Window*> GetAllOpenWindows();
// Runs the |func| callback for each content-window, and deallocates the
// internal list of open windows.
static void CleanUpWindowList(void (*func)(aura::Window* window));
// Accessor for DesktopNativeWidgetAura::content_window().
aura::Window* GetContentWindow();
const aura::Window* GetContentWindow() const;
// DesktopWindowTreeHost:
void Init(const Widget::InitParams& params) override;
void OnNativeWidgetCreated(const Widget::InitParams& params) override;
void OnWidgetInitDone() override;
void OnActiveWindowChanged(bool active) override;
std::unique_ptr<corewm::Tooltip> CreateTooltip() override;
std::unique_ptr<aura::client::DragDropClient> CreateDragDropClient() override;
void Close() override;
void CloseNow() override;
aura::WindowTreeHost* AsWindowTreeHost() override;
void Show(ui::WindowShowState show_state,
const gfx::Rect& restore_bounds) override;
bool IsVisible() const override;
void SetSize(const gfx::Size& size) override;
void StackAbove(aura::Window* window) override;
void StackAtTop() override;
bool IsStackedAbove(aura::Window* window) override;
void CenterWindow(const gfx::Size& size) override;
void GetWindowPlacement(gfx::Rect* bounds,
ui::WindowShowState* show_state) const override;
gfx::Rect GetWindowBoundsInScreen() const override;
gfx::Rect GetClientAreaBoundsInScreen() const override;
gfx::Rect GetRestoredBounds() const override;
std::string GetWorkspace() const override;
gfx::Rect GetWorkAreaBoundsInScreen() const override;
void SetShape(std::unique_ptr<Widget::ShapeRects> native_shape) override;
void Activate() override;
void Deactivate() override;
bool IsActive() const override;
void Maximize() override;
void Minimize() override;
void Restore() override;
bool IsMaximized() const override;
bool IsMinimized() const override;
bool HasCapture() const override;
void SetZOrderLevel(ui::ZOrderLevel order) override;
ui::ZOrderLevel GetZOrderLevel() const override;
void SetVisibleOnAllWorkspaces(bool always_visible) override;
bool IsVisibleOnAllWorkspaces() const override;
bool SetWindowTitle(const std::u16string& title) override;
void ClearNativeFocus() override;
bool IsMoveLoopSupported() const override;
Widget::MoveLoopResult RunMoveLoop(
const gfx::Vector2d& drag_offset,
Widget::MoveLoopSource source,
Widget::MoveLoopEscapeBehavior escape_behavior) override;
void EndMoveLoop() override;
void SetVisibilityChangedAnimationsEnabled(bool value) override;
std::unique_ptr<NonClientFrameView> CreateNonClientFrameView() override;
bool ShouldUseNativeFrame() const override;
bool ShouldWindowContentsBeTransparent() const override;
void FrameTypeChanged() override;
void SetFullscreen(bool fullscreen, int64_t display_id) override;
bool IsFullscreen() const override;
void SetOpacity(float opacity) override;
void SetAspectRatio(const gfx::SizeF& aspect_ratio,
const gfx::Size& excluded_margin) override;
void SetWindowIcons(const gfx::ImageSkia& window_icon,
const gfx::ImageSkia& app_icon) override;
void InitModalType(ui::ModalType modal_type) override;
void FlashFrame(bool flash_frame) override;
bool IsAnimatingClosed() const override;
bool IsTranslucentWindowOpacitySupported() const override;
void SizeConstraintsChanged() override;
bool ShouldUpdateWindowTransparency() const override;
bool ShouldUseDesktopNativeCursorManager() const override;
bool ShouldCreateVisibilityController() const override;
void UpdateWindowShapeIfNeeded(const ui::PaintContext& context) override;
void SetBoundsInDIP(const gfx::Rect& bounds) override;
// WindowTreeHost:
gfx::Transform GetRootTransform() const override;
void ShowImpl() override;
void HideImpl() override;
gfx::Rect CalculateRootWindowBounds() const override;
gfx::Rect GetBoundsInDIP() const override;
// PlatformWindowDelegate:
void OnClosed() override;
void OnWindowStateChanged(ui::PlatformWindowState old_state,
ui::PlatformWindowState new_state) override;
void OnCloseRequest() override;
void OnAcceleratedWidgetAvailable(gfx::AcceleratedWidget widget) override;
void OnWillDestroyAcceleratedWidget() override;
void OnActivationChanged(bool active) override;
absl::optional<gfx::Size> GetMinimumSizeForWindow() override;
absl::optional<gfx::Size> GetMaximumSizeForWindow() override;
SkPath GetWindowMaskForWindowShapeInPixels() override;
absl::optional<ui::MenuType> GetMenuType() override;
absl::optional<ui::OwnedWindowAnchor> GetOwnedWindowAnchorAndRectInDIP()
override;
gfx::Rect ConvertRectToPixels(const gfx::Rect& rect_in_dip) const override;
gfx::Rect ConvertRectToDIP(const gfx::Rect& rect_in_pixels) const override;
gfx::PointF ConvertScreenPointToLocalDIP(
const gfx::Point& screen_in_pixels) const override;
// ui::WorkspaceExtensionDelegate:
void OnWorkspaceChanged() override;
DesktopWindowTreeHostPlatform* window_parent() const {
return window_parent_;
}
// Tells the window manager to lower the |platform_window()| owned by this
// host down the stack so that it does not obscure any sibling windows.
// This is supported when running on x11
virtual void LowerWindow() {}
protected:
FRIEND_TEST_ALL_PREFIXES(DesktopWindowTreeHostPlatformImplTest,
MouseNCEvents);
FRIEND_TEST_ALL_PREFIXES(DesktopWindowTreeHostPlatformImplHighDPITest,
MouseNCEvents);
// See comment for variable open_windows_.
static std::list<gfx::AcceleratedWidget>& open_windows();
static bool has_open_windows();
// These are not general purpose methods and must be used with care. Please
// make sure you understand the rounding direction before using.
gfx::Rect ToDIPRect(const gfx::Rect& rect_in_pixels) const;
gfx::Rect ToPixelRect(const gfx::Rect& rect_in_dip) const;
Widget* GetWidget();
const Widget* GetWidget() const;
views::corewm::TooltipController* tooltip_controller();
private:
FRIEND_TEST_ALL_PREFIXES(DesktopWindowTreeHostPlatformTest,
UpdateWindowShapeFromWindowMask);
FRIEND_TEST_ALL_PREFIXES(DesktopWindowTreeHostPlatformTest,
MakesParentChildRelationship);
void ScheduleRelayout();
// Set visibility and fire OnNativeWidgetVisibilityChanged() if it changed.
void SetVisible(bool visible);
// There are platform specific properties that Linux may want to add.
virtual void AddAdditionalInitProperties(
const Widget::InitParams& params,
ui::PlatformWindowInitProperties* properties);
// Returns window mask to clip canvas to update window shape of
// the content window.
virtual SkPath GetWindowMaskForClipping() const;
// Helper method that returns the display for the |window()|.
display::Display GetDisplayNearestRootWindow() const;
const base::WeakPtr<internal::NativeWidgetDelegate> native_widget_delegate_;
const raw_ptr<DesktopNativeWidgetAura> desktop_native_widget_aura_;
bool is_active_ = false;
std::u16string window_title_;
// We can optionally have a parent which can order us to close, or own
// children who we're responsible for closing when we CloseNow().
raw_ptr<DesktopWindowTreeHostPlatform> window_parent_ = nullptr;
std::set<DesktopWindowTreeHostPlatform*> window_children_;
// Used for tab dragging in move loop requests.
WindowMoveClientPlatform window_move_client_;
// The content window shape can be set from either SetShape or default window
// mask. When explicitly setting from SetShape, |explicitly_set_shape_:true|
// to prevent clipping the canvas before painting for default window mask.
bool is_shape_explicitly_set_ = false;
base::WeakPtrFactory<DesktopWindowTreeHostPlatform> close_widget_factory_{
this};
};
} // namespace views
#endif // UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_WINDOW_TREE_HOST_PLATFORM_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_window_tree_host_platform.h | C++ | unknown | 10,146 |
// 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 "base/memory/raw_ptr.h"
#include "ui/views/widget/desktop_aura/desktop_window_tree_host_platform.h"
#include "base/run_loop.h"
#include "build/build_config.h"
#include "ui/aura/client/aura_constants.h"
#include "ui/aura/env.h"
#include "ui/aura/window_tree_host_platform.h"
#include "ui/base/hit_test.h"
#include "ui/base/ime/input_method.h"
#include "ui/base/test/ui_controls.h"
#include "ui/platform_window/platform_window.h"
#include "ui/platform_window/wm/wm_move_resize_handler.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/window/native_frame_view.h"
#if BUILDFLAG(IS_LINUX)
#include "ui/views/widget/desktop_aura/desktop_window_tree_host_linux.h"
#include "ui/views/widget/desktop_aura/window_event_filter_linux.h"
using DesktopWindowTreeHostPlatformImpl = views::DesktopWindowTreeHostLinux;
#else
#include "ui/views/widget/desktop_aura/desktop_window_tree_host_lacros.h"
#include "ui/views/widget/desktop_aura/window_event_filter_lacros.h"
using DesktopWindowTreeHostPlatformImpl = views::DesktopWindowTreeHostLacros;
#endif
namespace views {
namespace {
bool IsNonClientComponent(int hittest) {
switch (hittest) {
case HTBOTTOM:
case HTBOTTOMLEFT:
case HTBOTTOMRIGHT:
case HTCAPTION:
case HTLEFT:
case HTRIGHT:
case HTTOP:
case HTTOPLEFT:
case HTTOPRIGHT:
return true;
default:
return false;
}
}
std::unique_ptr<Widget> CreateWidget(const gfx::Rect& bounds) {
std::unique_ptr<Widget> widget(new Widget);
Widget::InitParams params(Widget::InitParams::TYPE_WINDOW);
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.remove_standard_frame = true;
params.native_widget = new DesktopNativeWidgetAura(widget.get());
params.bounds = bounds;
widget->Init(std::move(params));
return widget;
}
// Dispatches a motion event targeted to |point_in_screen|.
void DispatchMouseMotionEventSync(const gfx::Point& point_in_screen) {
base::RunLoop run_loop;
ui_controls::SendMouseMoveNotifyWhenDone(
point_in_screen.x(), point_in_screen.y(), run_loop.QuitClosure());
run_loop.Run();
}
// An event handler which counts the number of mouse moves it has seen.
class MouseMoveCounterHandler : public ui::EventHandler {
public:
MouseMoveCounterHandler() = default;
MouseMoveCounterHandler(const MouseMoveCounterHandler&) = delete;
MouseMoveCounterHandler& operator=(const MouseMoveCounterHandler&) = delete;
~MouseMoveCounterHandler() override = default;
// ui::EventHandler:
void OnMouseEvent(ui::MouseEvent* event) override {
// ui_controls::SendMouseMoveNotifyWhenDone calls
// aura::Window::MoveCursorTo, which internally results in calling both
// aura::WindowEventDispatcher::PostSynthesizeMouseMove and
// aura::WindowTreeHostPlatform::MoveCursorToScreenLocationInPixels. Thus,
// two events will come - one is synthetic and another one is our real one.
// Ignore the synthetic events as we are not interested in them.
if (event->type() == ui::ET_MOUSE_MOVED && !event->IsSynthesized())
++count_;
}
int num_mouse_moves() const { return count_; }
private:
int count_ = 0;
};
// A fake handler, which just stores the hittest and pointer location values.
class FakeWmMoveResizeHandler : public ui::WmMoveResizeHandler {
public:
using SetBoundsCallback = base::RepeatingCallback<void(gfx::Rect)>;
explicit FakeWmMoveResizeHandler(ui::PlatformWindow* window)
: platform_window_(window) {}
FakeWmMoveResizeHandler(const FakeWmMoveResizeHandler&) = delete;
FakeWmMoveResizeHandler& operator=(const FakeWmMoveResizeHandler&) = delete;
~FakeWmMoveResizeHandler() override = default;
void Reset() {
hittest_ = -1;
pointer_location_in_px_ = gfx::Point();
}
int hittest() const { return hittest_; }
gfx::Point pointer_location_in_px() const { return pointer_location_in_px_; }
void set_bounds(const gfx::Rect& bounds) { bounds_ = bounds; }
// ui::WmMoveResizeHandler
void DispatchHostWindowDragMovement(
int hittest,
const gfx::Point& pointer_location_in_px) override {
hittest_ = hittest;
pointer_location_in_px_ = pointer_location_in_px;
platform_window_->SetBoundsInPixels(bounds_);
}
private:
raw_ptr<ui::PlatformWindow> platform_window_;
gfx::Rect bounds_;
int hittest_ = -1;
gfx::Point pointer_location_in_px_;
};
void SetExpectationBasedOnHittestValue(
int hittest,
const FakeWmMoveResizeHandler& handler,
const gfx::Point& pointer_location_in_px) {
if (IsNonClientComponent(hittest)) {
// Ensure both the pointer location and the hit test value are passed to the
// fake move/resize handler.
EXPECT_EQ(handler.pointer_location_in_px().ToString(),
pointer_location_in_px.ToString());
EXPECT_EQ(handler.hittest(), hittest);
return;
}
// Ensure the handler does not receive the hittest value or the pointer
// location.
EXPECT_TRUE(handler.pointer_location_in_px().IsOrigin());
EXPECT_NE(handler.hittest(), hittest);
}
// This is used to return a customized result to NonClientHitTest.
class HitTestNonClientFrameView : public NativeFrameView {
public:
explicit HitTestNonClientFrameView(Widget* widget)
: NativeFrameView(widget) {}
HitTestNonClientFrameView(const HitTestNonClientFrameView&) = delete;
HitTestNonClientFrameView& operator=(const HitTestNonClientFrameView&) =
delete;
~HitTestNonClientFrameView() override = default;
void set_hit_test_result(int component) { hit_test_result_ = component; }
// NonClientFrameView overrides:
int NonClientHitTest(const gfx::Point& point) override {
return hit_test_result_;
}
private:
int hit_test_result_ = HTNOWHERE;
};
// This is used to return HitTestNonClientFrameView on create call.
class HitTestWidgetDelegate : public WidgetDelegate {
public:
HitTestWidgetDelegate() {
SetCanResize(true);
SetOwnedByWidget(true);
}
HitTestWidgetDelegate(const HitTestWidgetDelegate&) = delete;
HitTestWidgetDelegate& operator=(const HitTestWidgetDelegate&) = delete;
~HitTestWidgetDelegate() override = default;
HitTestNonClientFrameView* frame_view() { return frame_view_; }
// WidgetDelegate:
std::unique_ptr<NonClientFrameView> CreateNonClientFrameView(
Widget* widget) override {
DCHECK(!frame_view_);
auto frame_view = std::make_unique<HitTestNonClientFrameView>(widget);
frame_view_ = frame_view.get();
return frame_view;
}
private:
raw_ptr<HitTestNonClientFrameView> frame_view_ = nullptr;
};
// Test host that can intercept calls to the real host.
class TestDesktopWindowTreeHostPlatformImpl
: public DesktopWindowTreeHostPlatformImpl {
public:
TestDesktopWindowTreeHostPlatformImpl(
internal::NativeWidgetDelegate* native_widget_delegate,
DesktopNativeWidgetAura* desktop_native_widget_aura)
: DesktopWindowTreeHostPlatformImpl(native_widget_delegate,
desktop_native_widget_aura) {}
TestDesktopWindowTreeHostPlatformImpl(
const TestDesktopWindowTreeHostPlatformImpl&) = delete;
TestDesktopWindowTreeHostPlatformImpl& operator=(
const TestDesktopWindowTreeHostPlatformImpl&) = delete;
~TestDesktopWindowTreeHostPlatformImpl() override = default;
// PlatformWindowDelegate:
// Instead of making these tests friends of the host, override the dispatch
// method to make it public and nothing else.
void DispatchEvent(ui::Event* event) override {
DesktopWindowTreeHostPlatformImpl::DispatchEvent(event);
}
void ResetCalledMaximize() { called_maximize_ = false; }
bool called_maximize() const { return called_maximize_; }
// DesktopWindowTreeHost
void Maximize() override {
called_maximize_ = true;
DesktopWindowTreeHostPlatformImpl::Maximize();
}
private:
bool called_maximize_ = false;
};
} // namespace
class DesktopWindowTreeHostPlatformImplTest
: public test::DesktopWidgetTestInteractive {
public:
DesktopWindowTreeHostPlatformImplTest() = default;
DesktopWindowTreeHostPlatformImplTest(
const DesktopWindowTreeHostPlatformImplTest&) = delete;
DesktopWindowTreeHostPlatformImplTest& operator=(
const DesktopWindowTreeHostPlatformImplTest&) = delete;
~DesktopWindowTreeHostPlatformImplTest() override = default;
protected:
Widget* BuildTopLevelDesktopWidget(const gfx::Rect& bounds) {
Widget* toplevel = new Widget;
delegate_ = new HitTestWidgetDelegate();
Widget::InitParams toplevel_params =
CreateParams(Widget::InitParams::TYPE_WINDOW);
auto* native_widget = new DesktopNativeWidgetAura(toplevel);
toplevel_params.native_widget = native_widget;
host_ = new TestDesktopWindowTreeHostPlatformImpl(toplevel, native_widget);
toplevel_params.desktop_window_tree_host = host_.get();
toplevel_params.delegate = delegate_.get();
toplevel_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
toplevel_params.bounds = bounds;
toplevel_params.remove_standard_frame = true;
toplevel->Init(std::move(toplevel_params));
return toplevel;
}
void DispatchEvent(ui::Event* event) {
DCHECK(host_);
std::unique_ptr<ui::Event> owned_event(event);
host_->DispatchEvent(owned_event.get());
}
void GenerateAndDispatchClickMouseEvent(const gfx::Point& click_location,
int flags) {
DCHECK(host_);
DispatchEvent(
GenerateMouseEvent(ui::ET_MOUSE_PRESSED, click_location, flags));
DispatchEvent(
GenerateMouseEvent(ui::ET_MOUSE_RELEASED, click_location, flags));
}
ui::MouseEvent* GenerateMouseEvent(ui::EventType event_type,
const gfx::Point& click_location,
int flags) {
int flag = 0;
if (flags & ui::EF_LEFT_MOUSE_BUTTON) {
flag = ui::EF_LEFT_MOUSE_BUTTON;
} else {
CHECK(flags & ui::EF_RIGHT_MOUSE_BUTTON)
<< "Other mouse clicks are not supported yet. Add the new one.";
flag = ui::EF_RIGHT_MOUSE_BUTTON;
}
return new ui::MouseEvent(event_type, click_location, click_location,
base::TimeTicks::Now(), flags, flag);
}
ui::GestureEvent* GenerateGestureEvent(
const gfx::Point& gesture_location,
const ui::GestureEventDetails& gesture_details) {
return new ui::GestureEvent(gesture_location.x(), gesture_location.y(), 0,
base::TimeTicks::Now(), gesture_details);
}
raw_ptr<HitTestWidgetDelegate> delegate_ = nullptr;
raw_ptr<TestDesktopWindowTreeHostPlatformImpl> host_ = nullptr;
};
// These tests are run using either click or touch events.
class DesktopWindowTreeHostPlatformImplTestWithTouch
: public DesktopWindowTreeHostPlatformImplTest,
public testing::WithParamInterface<bool> {
public:
bool use_touch_event() const { return GetParam(); }
};
// On Lacros, the resize and drag operations are handled by compositor,
// so this test does not make much sense.
#if BUILDFLAG(IS_CHROMEOS_LACROS)
#define MAYBE_HitTest DISABLED_HitTest
#else
#define MAYBE_HitTest HitTest
#endif
TEST_P(DesktopWindowTreeHostPlatformImplTestWithTouch, MAYBE_HitTest) {
gfx::Rect widget_bounds(0, 0, 100, 100);
std::unique_ptr<Widget> widget(BuildTopLevelDesktopWidget(widget_bounds));
widget->Show();
// Install a fake move/resize handler to intercept the move/resize call.
auto handler =
std::make_unique<FakeWmMoveResizeHandler>(host_->platform_window());
host_->DestroyNonClientEventFilter();
#if BUILDFLAG(IS_CHROMEOS_LACROS)
host_->non_client_window_event_filter_ =
std::make_unique<WindowEventFilterLacros>(host_, handler.get());
#else
host_->non_client_window_event_filter_ =
std::make_unique<WindowEventFilterLinux>(host_, handler.get());
#endif
// It is not important to use pointer locations corresponding to the hittests
// values used in the browser itself, because we fake the hit test results,
// which non client frame view sends back. Thus, just make sure the content
// window is able to receive these events.
gfx::Point pointer_location_in_px(10, 10);
constexpr int hittest_values[] = {
HTBOTTOM, HTBOTTOMLEFT, HTBOTTOMRIGHT, HTCAPTION, HTLEFT,
HTRIGHT, HTTOP, HTTOPLEFT, HTTOPRIGHT, HTNOWHERE,
HTBORDER, HTCLIENT, HTCLOSE, HTERROR, HTGROWBOX,
HTHELP, HTHSCROLL, HTMENU, HTMAXBUTTON, HTMINBUTTON,
HTREDUCE, HTSIZE, HTSYSMENU, HTTRANSPARENT, HTVSCROLL,
HTZOOM,
};
aura::Window* window = widget->GetNativeWindow();
auto* frame_view = delegate_->frame_view();
for (int hittest : hittest_values) {
handler->Reset();
// Set the desired hit test result value, which will be returned, when
// WindowEventFilter starts to perform hit testing.
frame_view->set_hit_test_result(hittest);
gfx::Rect bounds = window->GetBoundsInScreen();
// The wm move/resize handler receives pointer location in the global
// screen coordinate, whereas event dispatcher receives event locations on
// a local system coordinate. Thus, add an offset of a new possible origin
// value of a window to the expected pointer location.
gfx::Point expected_pointer_location_in_px(pointer_location_in_px);
expected_pointer_location_in_px.Offset(bounds.x(), bounds.y());
if (hittest == HTCAPTION) {
// Move the window on HTCAPTION hit test value.
bounds =
gfx::Rect(gfx::Point(bounds.x() + 2, bounds.y() + 4), bounds.size());
handler->set_bounds(bounds);
} else if (IsNonClientComponent(hittest)) {
// Resize the window on other than HTCAPTION non client hit test values.
bounds = gfx::Rect(
gfx::Point(bounds.origin()),
gfx::Size(bounds.size().width() + 5, bounds.size().height() + 10));
handler->set_bounds(bounds);
}
// Send mouse/touch down event and make sure the WindowEventFilter calls
// the move/resize handler to start interactive move/resize with the
// |hittest| value we specified.
if (use_touch_event()) {
ui::GestureEventDetails gesture_details(ui::ET_GESTURE_SCROLL_BEGIN);
DispatchEvent(
GenerateGestureEvent(pointer_location_in_px, gesture_details));
} else {
DispatchEvent(GenerateMouseEvent(ui::ET_MOUSE_PRESSED,
pointer_location_in_px,
ui::EF_LEFT_MOUSE_BUTTON));
}
// The test expectation is based on the hit test component. If it is a
// non-client component, which results in a call to move/resize, the
// handler must receive the hittest value and the pointer location in
// global screen coordinate system. In other cases, it must not.
SetExpectationBasedOnHittestValue(hittest, *handler.get(),
expected_pointer_location_in_px);
// Make sure the bounds of the content window are correct.
EXPECT_EQ(window->GetBoundsInScreen().ToString(), bounds.ToString());
// Dispatch mouse/touch release event to release a mouse/touch pressed
// handler and be able to consume future events.
if (use_touch_event()) {
ui::GestureEventDetails gesture_details(ui::ET_GESTURE_SCROLL_END);
DispatchEvent(
GenerateGestureEvent(pointer_location_in_px, gesture_details));
} else {
DispatchEvent(GenerateMouseEvent(ui::ET_MOUSE_RELEASED,
pointer_location_in_px,
ui::EF_LEFT_MOUSE_BUTTON));
}
}
}
// Tests that the window is maximized in response to a double click event.
TEST_P(DesktopWindowTreeHostPlatformImplTestWithTouch,
DoubleClickHeaderMaximizes) {
gfx::Rect bounds(0, 0, 100, 100);
std::unique_ptr<Widget> widget(BuildTopLevelDesktopWidget(bounds));
widget->Show();
aura::Window* window = widget->GetNativeWindow();
window->SetProperty(aura::client::kResizeBehaviorKey,
aura::client::kResizeBehaviorCanMaximize);
RunPendingMessages();
host_->ResetCalledMaximize();
auto* frame_view = delegate_->frame_view();
// Set the desired hit test result value, which will be returned, when
// WindowEventFilter starts to perform hit testing.
frame_view->set_hit_test_result(HTCAPTION);
host_->ResetCalledMaximize();
if (use_touch_event()) {
ui::GestureEventDetails details(ui::ET_GESTURE_TAP);
details.set_tap_count(1);
DispatchEvent(GenerateGestureEvent(gfx::Point(), details));
details.set_tap_count(2);
DispatchEvent(GenerateGestureEvent(gfx::Point(), details));
} else {
int flags = ui::EF_LEFT_MOUSE_BUTTON;
GenerateAndDispatchClickMouseEvent(gfx::Point(), flags);
flags |= ui::EF_IS_DOUBLE_CLICK;
GenerateAndDispatchClickMouseEvent(gfx::Point(), flags);
}
EXPECT_TRUE(host_->called_maximize());
widget->CloseNow();
}
// Tests that the window does not maximize in response to a double click event,
// if the first click was to a different target component than that of the
// second click.
TEST_P(DesktopWindowTreeHostPlatformImplTestWithTouch,
DoubleClickTwoDifferentTargetsDoesntMaximizes) {
gfx::Rect bounds(0, 0, 100, 100);
std::unique_ptr<Widget> widget(BuildTopLevelDesktopWidget(bounds));
widget->Show();
aura::Window* window = widget->GetNativeWindow();
window->SetProperty(aura::client::kResizeBehaviorKey,
aura::client::kResizeBehaviorCanMaximize);
RunPendingMessages();
host_->ResetCalledMaximize();
auto* frame_view = delegate_->frame_view();
if (use_touch_event()) {
frame_view->set_hit_test_result(HTCLIENT);
ui::GestureEventDetails details(ui::ET_GESTURE_TAP);
details.set_tap_count(1);
DispatchEvent(GenerateGestureEvent(gfx::Point(), details));
frame_view->set_hit_test_result(HTCLIENT);
details.set_tap_count(2);
DispatchEvent(GenerateGestureEvent(gfx::Point(), details));
} else {
frame_view->set_hit_test_result(HTCLIENT);
int flags = ui::EF_LEFT_MOUSE_BUTTON;
GenerateAndDispatchClickMouseEvent(gfx::Point(), flags);
frame_view->set_hit_test_result(HTCLIENT);
flags |= ui::EF_IS_DOUBLE_CLICK;
GenerateAndDispatchClickMouseEvent(gfx::Point(), flags);
}
EXPECT_FALSE(host_->called_maximize());
widget->CloseNow();
}
// Tests that the window does not maximize in response to a double click event,
// if the double click was interrupted by a right click.
TEST_F(DesktopWindowTreeHostPlatformImplTest,
RightClickDuringDoubleClickDoesntMaximize) {
gfx::Rect bounds(0, 0, 100, 100);
std::unique_ptr<Widget> widget(BuildTopLevelDesktopWidget(bounds));
widget->Show();
aura::Window* window = widget->GetNativeWindow();
window->SetProperty(aura::client::kResizeBehaviorKey,
aura::client::kResizeBehaviorCanMaximize);
RunPendingMessages();
host_->ResetCalledMaximize();
auto* frame_view = delegate_->frame_view();
frame_view->set_hit_test_result(HTCLIENT);
int flags_left_button = ui::EF_LEFT_MOUSE_BUTTON;
GenerateAndDispatchClickMouseEvent(gfx::Point(), flags_left_button);
frame_view->set_hit_test_result(HTCAPTION);
GenerateAndDispatchClickMouseEvent(gfx::Point(), ui::EF_RIGHT_MOUSE_BUTTON);
EXPECT_FALSE(host_->called_maximize());
flags_left_button |= ui::EF_IS_DOUBLE_CLICK;
GenerateAndDispatchClickMouseEvent(gfx::Point(), flags_left_button);
EXPECT_FALSE(host_->called_maximize());
widget->CloseNow();
}
// Test that calling Widget::Deactivate() sets the widget as inactive wrt to
// Chrome even if it not possible to deactivate the window wrt to the x server.
// This behavior is required by several interactive_ui_tests.
TEST_F(DesktopWindowTreeHostPlatformImplTest, Deactivate) {
std::unique_ptr<Widget> widget(CreateWidget(gfx::Rect(100, 100, 100, 100)));
{
views::test::WidgetActivationWaiter waiter(widget.get(), true);
widget->Show();
widget->Activate();
waiter.Wait();
}
{
// Regardless of whether |widget|'s X11 window eventually gets deactivated,
// |widget|'s "active" state should change.
views::test::WidgetActivationWaiter waiter(widget.get(), false);
widget->Deactivate();
waiter.Wait();
EXPECT_FALSE(widget->IsActive());
}
{
// |widget|'s X11 window should still be active. Reactivating |widget|
// should update the widget's "active" state. Note: Activating a widget
// whose X11 window is not active does not synchronously update the widget's
// "active" state.
views::test::WidgetActivationWaiter waiter(widget.get(), true);
widget->Activate();
waiter.Wait();
EXPECT_TRUE(widget->IsActive());
}
}
// Chrome attempts to make mouse capture look synchronous on Linux. Test that
// Chrome synchronously switches the window that mouse events are forwarded to
// when capture is changed.
TEST_F(DesktopWindowTreeHostPlatformImplTest, CaptureEventForwarding) {
ui_controls::EnableUIControls();
std::unique_ptr<Widget> widget1(CreateWidget(gfx::Rect(100, 100, 100, 100)));
aura::Window* window1 = widget1->GetNativeWindow();
views::test::WidgetActivationWaiter waiter1(widget1.get(), true);
widget1->Show();
waiter1.Wait();
std::unique_ptr<Widget> widget2(CreateWidget(gfx::Rect(200, 100, 100, 100)));
aura::Window* window2 = widget2->GetNativeWindow();
views::test::WidgetActivationWaiter waiter2(widget2.get(), true);
widget2->Show();
waiter2.Wait();
MouseMoveCounterHandler recorder1;
window1->AddPreTargetHandler(&recorder1);
MouseMoveCounterHandler recorder2;
window2->AddPreTargetHandler(&recorder2);
// Move the mouse to the center of |widget2|.
gfx::Point point_in_screen = widget2->GetWindowBoundsInScreen().CenterPoint();
DispatchMouseMotionEventSync(point_in_screen);
EXPECT_EQ(0, recorder1.num_mouse_moves());
EXPECT_EQ(1, recorder2.num_mouse_moves());
EXPECT_EQ(point_in_screen.ToString(),
aura::Env::GetInstance()->last_mouse_location().ToString());
// Set capture to |widget1|. Because DesktopWindowTreeHostX11 calls
// XGrabPointer() with owner == False, the X server sends events to |widget2|
// as long as the mouse is hovered over |widget2|. Verify that Chrome
// redirects mouse events to |widget1|.
widget1->SetCapture(nullptr);
point_in_screen += gfx::Vector2d(1, 0);
DispatchMouseMotionEventSync(point_in_screen);
EXPECT_EQ(1, recorder1.num_mouse_moves());
EXPECT_EQ(1, recorder2.num_mouse_moves());
// If the event's location was correctly changed to be relative to |widget1|,
// Env's last mouse position will be correct.
EXPECT_EQ(point_in_screen.ToString(),
aura::Env::GetInstance()->last_mouse_location().ToString());
// Set capture to |widget2|. Subsequent events sent to |widget2| should not be
// forwarded.
widget2->SetCapture(nullptr);
point_in_screen += gfx::Vector2d(1, 0);
DispatchMouseMotionEventSync(point_in_screen);
EXPECT_EQ(1, recorder1.num_mouse_moves());
EXPECT_EQ(2, recorder2.num_mouse_moves());
EXPECT_EQ(point_in_screen.ToString(),
aura::Env::GetInstance()->last_mouse_location().ToString());
// If the mouse is not hovered over |widget1| or |widget2|, the X server will
// send events to the window which has capture. Test the mouse events sent to
// |widget2| are not forwarded.
DispatchMouseMotionEventSync(point_in_screen);
EXPECT_EQ(1, recorder1.num_mouse_moves());
EXPECT_EQ(3, recorder2.num_mouse_moves());
EXPECT_EQ(point_in_screen.ToString(),
aura::Env::GetInstance()->last_mouse_location().ToString());
// Release capture. Test that when capture is released, mouse events are no
// longer forwarded to other widgets.
widget2->ReleaseCapture();
point_in_screen = widget1->GetWindowBoundsInScreen().CenterPoint();
DispatchMouseMotionEventSync(point_in_screen);
EXPECT_EQ(2, recorder1.num_mouse_moves());
EXPECT_EQ(3, recorder2.num_mouse_moves());
EXPECT_EQ(point_in_screen.ToString(),
aura::Env::GetInstance()->last_mouse_location().ToString());
// Cleanup
window1->RemovePreTargetHandler(&recorder1);
window2->RemovePreTargetHandler(&recorder2);
}
TEST_F(DesktopWindowTreeHostPlatformImplTest, InputMethodFocus) {
std::unique_ptr<Widget> widget(CreateWidget(gfx::Rect(100, 100, 100, 100)));
std::unique_ptr<Textfield> textfield(new Textfield);
// Provide an accessible name so that accessibility paint checks pass.
textfield->SetAccessibleName(u"test");
textfield->SetBounds(0, 0, 200, 20);
widget->GetRootView()->AddChildView(textfield.get());
widget->ShowInactive();
textfield->RequestFocus();
EXPECT_FALSE(widget->IsActive());
// TODO(shuchen): uncomment the below check once the
// "default-focused-input-method" logic is removed in aura::WindowTreeHost.
// EXPECT_EQ(ui::TEXT_INPUT_TYPE_NONE,
// widget->GetInputMethod()->GetTextInputType());
views::test::WidgetActivationWaiter waiter(widget.get(), true);
widget->Activate();
waiter.Wait();
EXPECT_TRUE(widget->IsActive());
EXPECT_EQ(ui::TEXT_INPUT_TYPE_TEXT,
widget->GetInputMethod()->GetTextInputType());
widget->Deactivate();
EXPECT_FALSE(widget->IsActive());
EXPECT_EQ(ui::TEXT_INPUT_TYPE_NONE,
widget->GetInputMethod()->GetTextInputType());
}
INSTANTIATE_TEST_SUITE_P(,
DesktopWindowTreeHostPlatformImplTestWithTouch,
testing::Bool());
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_window_tree_host_platform_impl_interactive_uitest.cc | C++ | unknown | 25,910 |
// 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/widget/desktop_aura/desktop_window_tree_host_platform.h"
#include <utility>
#include "base/command_line.h"
#include "ui/base/hit_test.h"
#include "ui/base/ui_base_types.h"
#include "ui/display/display_switches.h"
#include "ui/platform_window/platform_window.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h"
#include "ui/views/widget/widget_delegate.h"
namespace views {
// This tests the wayland and linux(x11) implementation of the
// DesktopWindowTreeHostPlatform.
namespace {
// A NonClientFrameView with a window mask with the bottom right corner cut out.
class ShapedNonClientFrameView : public NonClientFrameView {
public:
ShapedNonClientFrameView() = default;
ShapedNonClientFrameView(const ShapedNonClientFrameView&) = delete;
ShapedNonClientFrameView& operator=(const ShapedNonClientFrameView&) = delete;
~ShapedNonClientFrameView() override = default;
// NonClientFrameView:
gfx::Rect GetBoundsForClientView() const override { return bounds(); }
gfx::Rect GetWindowBoundsForClientBounds(
const gfx::Rect& client_bounds) const override {
return client_bounds;
}
int NonClientHitTest(const gfx::Point& point) override {
// Fake bottom for non client event test.
if (point == gfx::Point(500, 500))
return HTBOTTOM;
return HTNOWHERE;
}
void GetWindowMask(const gfx::Size& size, SkPath* window_mask) override {
int right = size.width();
int bottom = size.height();
window_mask->moveTo(0, 0);
window_mask->lineTo(0, bottom);
window_mask->lineTo(right, bottom);
window_mask->lineTo(right, 10);
window_mask->lineTo(right - 10, 10);
window_mask->lineTo(right - 10, 0);
window_mask->close();
}
void ResetWindowControls() override {}
void UpdateWindowIcon() override {}
void UpdateWindowTitle() override {}
void SizeConstraintsChanged() override {}
bool GetAndResetLayoutRequest() {
bool layout_requested = layout_requested_;
layout_requested_ = false;
return layout_requested;
}
private:
void Layout() override { layout_requested_ = true; }
bool layout_requested_ = false;
};
class ShapedWidgetDelegate : public WidgetDelegateView {
public:
ShapedWidgetDelegate() = default;
ShapedWidgetDelegate(const ShapedWidgetDelegate&) = delete;
ShapedWidgetDelegate& operator=(const ShapedWidgetDelegate&) = delete;
~ShapedWidgetDelegate() override = default;
// WidgetDelegateView:
std::unique_ptr<NonClientFrameView> CreateNonClientFrameView(
Widget* widget) override {
return std::make_unique<ShapedNonClientFrameView>();
}
};
class MouseEventRecorder : public ui::EventHandler {
public:
MouseEventRecorder() = default;
MouseEventRecorder(const MouseEventRecorder&) = delete;
MouseEventRecorder& operator=(const MouseEventRecorder&) = delete;
~MouseEventRecorder() override = default;
void Reset() { mouse_events_.clear(); }
const std::vector<ui::MouseEvent>& mouse_events() const {
return mouse_events_;
}
private:
// ui::EventHandler:
void OnMouseEvent(ui::MouseEvent* mouse) override {
mouse_events_.push_back(*mouse);
}
std::vector<ui::MouseEvent> mouse_events_;
};
} // namespace
class DesktopWindowTreeHostPlatformImplTest : public ViewsTestBase {
public:
DesktopWindowTreeHostPlatformImplTest() = default;
DesktopWindowTreeHostPlatformImplTest(
const DesktopWindowTreeHostPlatformImplTest&) = delete;
DesktopWindowTreeHostPlatformImplTest& operator=(
const DesktopWindowTreeHostPlatformImplTest&) = delete;
~DesktopWindowTreeHostPlatformImplTest() override = default;
void SetUp() override {
set_native_widget_type(NativeWidgetType::kDesktop);
ViewsTestBase::SetUp();
}
protected:
// Creates a widget of size 100x100.
std::unique_ptr<Widget> CreateWidget(WidgetDelegate* delegate) {
std::unique_ptr<Widget> widget(new Widget);
Widget::InitParams params(Widget::InitParams::TYPE_WINDOW);
params.delegate = delegate;
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.remove_standard_frame = true;
params.bounds = gfx::Rect(100, 100, 100, 100);
widget->Init(std::move(params));
return widget;
}
};
TEST_F(DesktopWindowTreeHostPlatformImplTest,
ChildWindowDestructionDuringTearDown) {
Widget parent_widget;
Widget::InitParams parent_params =
CreateParams(Widget::InitParams::TYPE_WINDOW);
parent_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
parent_widget.Init(std::move(parent_params));
parent_widget.Show();
Widget child_widget;
Widget::InitParams child_params =
CreateParams(Widget::InitParams::TYPE_WINDOW);
child_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
child_params.parent = parent_widget.GetNativeWindow();
child_widget.Init(std::move(child_params));
child_widget.Show();
// Sanity check that the two widgets each have their own XID.
ASSERT_NE(parent_widget.GetNativeWindow()->GetHost()->GetAcceleratedWidget(),
child_widget.GetNativeWindow()->GetHost()->GetAcceleratedWidget());
Widget::CloseAllSecondaryWidgets();
EXPECT_TRUE(DesktopWindowTreeHostPlatform::GetAllOpenWindows().empty());
}
TEST_F(DesktopWindowTreeHostPlatformImplTest, MouseNCEvents) {
std::unique_ptr<Widget> widget = CreateWidget(new ShapedWidgetDelegate());
widget->Show();
base::RunLoop().RunUntilIdle();
widget->SetBounds(gfx::Rect(100, 100, 501, 501));
base::RunLoop().RunUntilIdle();
MouseEventRecorder recorder;
widget->GetNativeWindow()->AddPreTargetHandler(&recorder);
auto* host_platform = static_cast<DesktopWindowTreeHostPlatform*>(
widget->GetNativeWindow()->GetHost());
ASSERT_TRUE(host_platform);
ui::MouseEvent event(ui::ET_MOUSE_PRESSED, gfx::PointF(500, 500),
gfx::PointF(500, 500), base::TimeTicks::Now(), 0, 0, {});
host_platform->DispatchEvent(&event);
ASSERT_EQ(1u, recorder.mouse_events().size());
EXPECT_EQ(ui::ET_MOUSE_PRESSED, recorder.mouse_events()[0].type());
EXPECT_TRUE(recorder.mouse_events()[0].flags() & ui::EF_IS_NON_CLIENT);
widget->GetNativeWindow()->RemovePreTargetHandler(&recorder);
}
// Checks that a call to `SetZOrderLevel` on a `PlatformWindow` sets the z order
// on the associated `Widget`.
TEST_F(DesktopWindowTreeHostPlatformImplTest,
SetZOrderCorrectlySetsZOrderOnPlatformWindows) {
// We want the widget to be initialized with a non-default z order to check
// that it gets initialized with the correct z order.
Widget widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.z_order = ui::ZOrderLevel::kFloatingWindow;
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget.Init(std::move(params));
widget.Show();
auto* host_platform = static_cast<DesktopWindowTreeHostPlatform*>(
widget.GetNativeWindow()->GetHost());
ASSERT_TRUE(host_platform);
auto* platform_window = host_platform->platform_window();
ASSERT_EQ(ui::ZOrderLevel::kFloatingWindow,
platform_window->GetZOrderLevel());
ASSERT_EQ(ui::ZOrderLevel::kFloatingWindow, widget.GetZOrderLevel());
platform_window->SetZOrderLevel(ui::ZOrderLevel::kNormal);
EXPECT_EQ(ui::ZOrderLevel::kNormal, platform_window->GetZOrderLevel());
EXPECT_EQ(ui::ZOrderLevel::kNormal, widget.GetZOrderLevel());
}
class DesktopWindowTreeHostPlatformImplHighDPITest
: public DesktopWindowTreeHostPlatformImplTest {
public:
DesktopWindowTreeHostPlatformImplHighDPITest() = default;
~DesktopWindowTreeHostPlatformImplHighDPITest() override = default;
private:
void SetUp() override {
base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
command_line->AppendSwitchASCII(switches::kForceDeviceScaleFactor, "2");
DesktopWindowTreeHostPlatformImplTest::SetUp();
}
};
TEST_F(DesktopWindowTreeHostPlatformImplHighDPITest, MouseNCEvents) {
std::unique_ptr<Widget> widget = CreateWidget(new ShapedWidgetDelegate());
widget->Show();
widget->SetBounds(gfx::Rect(100, 100, 1000, 1000));
base::RunLoop().RunUntilIdle();
MouseEventRecorder recorder;
widget->GetNativeWindow()->AddPreTargetHandler(&recorder);
auto* host_platform = static_cast<DesktopWindowTreeHostPlatform*>(
widget->GetNativeWindow()->GetHost());
ASSERT_TRUE(host_platform);
ui::MouseEvent event(ui::ET_MOUSE_PRESSED, gfx::PointF(1001, 1001),
gfx::PointF(1001, 1001), base::TimeTicks::Now(), 0, 0,
{});
host_platform->DispatchEvent(&event);
EXPECT_EQ(1u, recorder.mouse_events().size());
EXPECT_EQ(gfx::Point(500, 500), recorder.mouse_events()[0].location());
EXPECT_EQ(ui::ET_MOUSE_PRESSED, recorder.mouse_events()[0].type());
EXPECT_TRUE(recorder.mouse_events()[0].flags() & ui::EF_IS_NON_CLIENT);
widget->GetNativeWindow()->RemovePreTargetHandler(&recorder);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_window_tree_host_platform_impl_unittest.cc | C++ | unknown | 9,154 |
// 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/widget/desktop_aura/desktop_window_tree_host_platform.h"
#include <memory>
#include <utility>
#include "base/command_line.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "build/build_config.h"
#include "ui/aura/window_tree_host.h"
#include "ui/aura/window_tree_host_observer.h"
#include "ui/base/ui_base_features.h"
#include "ui/compositor/layer.h"
#include "ui/display/display_switches.h"
#include "ui/display/types/display_constants.h"
#include "ui/platform_window/platform_window.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h"
#include "ui/views/widget/widget_observer.h"
#if BUILDFLAG(IS_OZONE)
#include "ui/ozone/public/ozone_platform.h"
#endif
namespace views {
namespace {
class TestWidgetObserver : public WidgetObserver {
public:
enum class Change {
kVisibility,
kDestroying,
};
explicit TestWidgetObserver(Widget* widget) : widget_(widget) {
DCHECK(widget_);
widget_->AddObserver(this);
}
TestWidgetObserver(const TestWidgetObserver&) = delete;
TestWidgetObserver& operator=(const TestWidgetObserver&) = delete;
~TestWidgetObserver() override {
// This might have been destroyed by the widget destroying delegate call.
if (widget_)
widget_->RemoveObserver(this);
}
// Waits for notification changes for the |change|. |old_value| must be
// provided to be sure that this is not called after the change has already
// happened - e.g. synchronous change.
void WaitForChange(Change change, bool old_value) {
switch (change) {
case Change::kVisibility:
if (old_value == visible_)
Wait();
break;
case Change::kDestroying:
if (old_value == on_widget_destroying_)
Wait();
break;
default:
NOTREACHED_NORETURN() << "unknown value";
}
}
bool widget_destroying() const { return on_widget_destroying_; }
bool visible() const { return visible_; }
private:
// views::WidgetObserver overrides:
void OnWidgetDestroying(Widget* widget) override {
DCHECK_EQ(widget_, widget);
widget_->RemoveObserver(this);
widget_ = nullptr;
on_widget_destroying_ = true;
StopWaiting();
}
void OnWidgetVisibilityChanged(Widget* widget, bool visible) override {
DCHECK_EQ(widget_, widget);
visible_ = visible;
StopWaiting();
}
void Wait() {
ASSERT_FALSE(run_loop_);
run_loop_ = std::make_unique<base::RunLoop>();
run_loop_->Run();
run_loop_.reset();
}
void StopWaiting() {
if (!run_loop_)
return;
ASSERT_TRUE(run_loop_->running());
run_loop_->Quit();
}
raw_ptr<Widget> widget_;
std::unique_ptr<base::RunLoop> run_loop_;
bool on_widget_destroying_ = false;
bool visible_ = false;
};
std::unique_ptr<Widget> CreateWidgetWithNativeWidgetWithParams(
Widget::InitParams params) {
std::unique_ptr<Widget> widget(new Widget);
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.native_widget = new DesktopNativeWidgetAura(widget.get());
widget->Init(std::move(params));
return widget;
}
std::unique_ptr<Widget> CreateWidgetWithNativeWidget() {
Widget::InitParams params(Widget::InitParams::TYPE_WINDOW);
params.delegate = nullptr;
params.remove_standard_frame = true;
params.bounds = gfx::Rect(100, 100, 100, 100);
return CreateWidgetWithNativeWidgetWithParams(std::move(params));
}
} // namespace
class DesktopWindowTreeHostPlatformTest : public ViewsTestBase {
public:
DesktopWindowTreeHostPlatformTest() = default;
DesktopWindowTreeHostPlatformTest(const DesktopWindowTreeHostPlatformTest&) =
delete;
DesktopWindowTreeHostPlatformTest& operator=(
const DesktopWindowTreeHostPlatformTest&) = delete;
~DesktopWindowTreeHostPlatformTest() override = default;
};
TEST_F(DesktopWindowTreeHostPlatformTest, CallOnNativeWidgetDestroying) {
std::unique_ptr<Widget> widget = CreateWidgetWithNativeWidget();
TestWidgetObserver observer(widget->native_widget_private()->GetWidget());
widget->CloseNow();
observer.WaitForChange(TestWidgetObserver::Change::kDestroying,
false /* old_value */);
EXPECT_TRUE(observer.widget_destroying());
}
// Calling show/hide/show triggers changing visibility of the native widget.
TEST_F(DesktopWindowTreeHostPlatformTest, CallOnNativeWidgetVisibilityChanged) {
std::unique_ptr<Widget> widget = CreateWidgetWithNativeWidget();
TestWidgetObserver observer(widget->native_widget_private()->GetWidget());
EXPECT_FALSE(observer.visible());
widget->Show();
EXPECT_TRUE(observer.visible());
widget->Hide();
EXPECT_FALSE(observer.visible());
widget->Show();
EXPECT_TRUE(observer.visible());
}
// Tests that the minimization information is propagated to the content window.
TEST_F(DesktopWindowTreeHostPlatformTest,
ToggleMinimizePropogateToContentWindow) {
std::unique_ptr<Widget> widget = CreateWidgetWithNativeWidget();
widget->Show();
auto* host_platform = DesktopWindowTreeHostPlatform::GetHostForWidget(
widget->GetNativeWindow()->GetHost()->GetAcceleratedWidget());
ASSERT_TRUE(host_platform);
EXPECT_TRUE(widget->GetNativeWindow()->IsVisible());
// Pretend a PlatformWindow enters the minimized state.
host_platform->OnWindowStateChanged(ui::PlatformWindowState::kUnknown,
ui::PlatformWindowState::kMinimized);
EXPECT_FALSE(widget->GetNativeWindow()->IsVisible());
// Pretend a PlatformWindow exits the minimized state.
host_platform->OnWindowStateChanged(ui::PlatformWindowState::kMinimized,
ui::PlatformWindowState::kNormal);
EXPECT_TRUE(widget->GetNativeWindow()->IsVisible());
}
// Tests that the window shape is updated from the
// |NonClientView::GetWindowMask|.
TEST_F(DesktopWindowTreeHostPlatformTest, UpdateWindowShapeFromWindowMask) {
std::unique_ptr<Widget> widget = CreateWidgetWithNativeWidget();
widget->Show();
auto* host_platform = DesktopWindowTreeHostPlatform::GetHostForWidget(
widget->GetNativeWindow()->GetHost()->GetAcceleratedWidget());
ASSERT_TRUE(host_platform);
if (!host_platform->platform_window()->ShouldUpdateWindowShape())
return;
auto* content_window =
DesktopWindowTreeHostPlatform::GetContentWindowForWidget(
widget->GetNativeWindow()->GetHost()->GetAcceleratedWidget());
ASSERT_TRUE(content_window);
EXPECT_FALSE(host_platform->GetWindowMaskForWindowShapeInPixels().isEmpty());
// SetClipPath for the layer of the content window is updated from it.
EXPECT_FALSE(host_platform->GetWindowMaskForClipping().isEmpty());
EXPECT_FALSE(widget->GetLayer()->FillsBoundsCompletely());
// When fullscreen mode, clip_path_ is set to empty since there is no
// |NonClientView::GetWindowMask|.
host_platform->SetFullscreen(true, display::kInvalidDisplayId);
widget->SetBounds(gfx::Rect(800, 800));
EXPECT_TRUE(host_platform->GetWindowMaskForWindowShapeInPixels().isEmpty());
EXPECT_TRUE(host_platform->GetWindowMaskForClipping().isEmpty());
EXPECT_TRUE(widget->GetLayer()->FillsBoundsCompletely());
}
// A Widget that allows setting the min/max size for the widget.
class CustomSizeWidget : public Widget {
public:
CustomSizeWidget() = default;
CustomSizeWidget(const CustomSizeWidget&) = delete;
CustomSizeWidget& operator=(const CustomSizeWidget&) = delete;
~CustomSizeWidget() override = default;
void set_min_size(const gfx::Size& size) { min_size_ = size; }
void set_max_size(const gfx::Size& size) { max_size_ = size; }
// Widget:
gfx::Size GetMinimumSize() const override { return min_size_; }
gfx::Size GetMaximumSize() const override { return max_size_; }
private:
gfx::Size min_size_;
gfx::Size max_size_;
};
TEST_F(DesktopWindowTreeHostPlatformTest, SetBoundsWithMinMax) {
CustomSizeWidget widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.bounds = gfx::Rect(200, 100);
widget.Init(std::move(params));
widget.Show();
base::RunLoop().RunUntilIdle();
EXPECT_EQ(gfx::Size(200, 100).ToString(),
widget.GetWindowBoundsInScreen().size().ToString());
widget.SetBounds(gfx::Rect(300, 200));
EXPECT_EQ(gfx::Size(300, 200).ToString(),
widget.GetWindowBoundsInScreen().size().ToString());
widget.set_min_size(gfx::Size(100, 100));
widget.SetBounds(gfx::Rect(50, 500));
EXPECT_EQ(gfx::Size(100, 500).ToString(),
widget.GetWindowBoundsInScreen().size().ToString());
}
class ResizeObserver : public aura::WindowTreeHostObserver {
public:
explicit ResizeObserver(aura::WindowTreeHost* host) : host_(host) {
host_->AddObserver(this);
}
ResizeObserver(const ResizeObserver&) = delete;
ResizeObserver& operator=(const ResizeObserver&) = delete;
~ResizeObserver() override { host_->RemoveObserver(this); }
int bounds_change_count() const { return bounds_change_count_; }
int resize_count() const { return resize_count_; }
// aura::WindowTreeHostObserver:
void OnHostResized(aura::WindowTreeHost* host) override { resize_count_++; }
void OnHostWillProcessBoundsChange(aura::WindowTreeHost* host) override {
bounds_change_count_++;
}
private:
const raw_ptr<aura::WindowTreeHost> host_;
int resize_count_ = 0;
int bounds_change_count_ = 0;
};
// Verifies that setting widget bounds, just after creating it, with the same
// size passed in InitParams does not lead to a "bounds change" event. Prevents
// regressions, such as https://crbug.com/1151092.
TEST_F(DesktopWindowTreeHostPlatformTest, SetBoundsWithUnchangedSize) {
auto widget = CreateWidgetWithNativeWidget();
widget->Show();
EXPECT_EQ(gfx::Size(100, 100), widget->GetWindowBoundsInScreen().size());
auto* host = widget->GetNativeWindow()->GetHost();
ResizeObserver observer(host);
auto* dwth_platform = DesktopWindowTreeHostPlatform::GetHostForWidget(
widget->GetNativeWindow()->GetHost()->GetAcceleratedWidget());
ASSERT_TRUE(dwth_platform);
// Check with different origin.
dwth_platform->SetBoundsInPixels(gfx::Rect(2, 2, 100, 100));
EXPECT_EQ(1, observer.bounds_change_count());
EXPECT_EQ(0, observer.resize_count());
}
TEST_F(DesktopWindowTreeHostPlatformTest, MakesParentChildRelationship) {
bool context_is_also_parent = false;
#if BUILDFLAG(IS_OZONE)
if (ui::OzonePlatform::GetInstance()
->GetPlatformProperties()
.set_parent_for_non_top_level_windows) {
context_is_also_parent = true;
}
#endif
auto widget = CreateWidgetWithNativeWidget();
widget->Show();
Widget::InitParams widget_2_params(Widget::InitParams::TYPE_MENU);
widget_2_params.bounds = gfx::Rect(110, 110, 100, 100);
widget_2_params.parent = widget->GetNativeWindow();
auto widget2 =
CreateWidgetWithNativeWidgetWithParams(std::move(widget_2_params));
widget2->Show();
auto* host_platform = DesktopWindowTreeHostPlatform::GetHostForWidget(
widget->GetNativeWindow()->GetHost()->GetAcceleratedWidget());
EXPECT_EQ(host_platform->window_parent_, nullptr);
EXPECT_EQ(host_platform->window_children_.size(), 1u);
auto* host_platform2 = DesktopWindowTreeHostPlatform::GetHostForWidget(
widget2->GetNativeWindow()->GetHost()->GetAcceleratedWidget());
EXPECT_EQ(host_platform2->window_parent_, host_platform);
EXPECT_EQ(*host_platform->window_children_.begin(), host_platform2);
Widget::InitParams widget_3_params(Widget::InitParams::TYPE_MENU);
widget_3_params.bounds = gfx::Rect(120, 120, 50, 80);
widget_3_params.parent = widget->GetNativeWindow();
auto widget3 =
CreateWidgetWithNativeWidgetWithParams(std::move(widget_3_params));
widget3->Show();
EXPECT_EQ(host_platform->window_parent_, nullptr);
EXPECT_EQ(host_platform->window_children_.size(), 2u);
auto* host_platform3 = DesktopWindowTreeHostPlatform::GetHostForWidget(
widget3->GetNativeWindow()->GetHost()->GetAcceleratedWidget());
EXPECT_EQ(host_platform3->window_parent_, host_platform);
EXPECT_NE(host_platform->window_children_.find(host_platform3),
host_platform->window_children_.end());
Widget::InitParams widget_4_params(Widget::InitParams::TYPE_TOOLTIP);
widget_4_params.bounds = gfx::Rect(105, 105, 10, 10);
widget_4_params.context = widget->GetNativeWindow();
auto widget4 =
CreateWidgetWithNativeWidgetWithParams(std::move(widget_4_params));
widget4->Show();
EXPECT_EQ(host_platform->window_parent_, nullptr);
auto* host_platform4 = DesktopWindowTreeHostPlatform::GetHostForWidget(
widget4->GetNativeWindow()->GetHost()->GetAcceleratedWidget());
if (context_is_also_parent) {
EXPECT_EQ(host_platform->window_children_.size(), 3u);
EXPECT_EQ(host_platform4->window_parent_, host_platform);
EXPECT_NE(host_platform->window_children_.find(host_platform4),
host_platform->window_children_.end());
} else {
EXPECT_EQ(host_platform4->window_parent_, nullptr);
EXPECT_EQ(host_platform->window_children_.size(), 2u);
EXPECT_NE(host_platform->window_children_.find(host_platform3),
host_platform->window_children_.end());
}
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_window_tree_host_platform_unittest.cc | C++ | unknown | 13,455 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/widget/desktop_aura/desktop_window_tree_host_win.h"
#include <algorithm>
#include <utility>
#include <vector>
#include "base/containers/flat_set.h"
#include "base/feature_list.h"
#include "base/functional/bind.h"
#include "base/memory/ptr_util.h"
#include "base/memory/scoped_refptr.h"
#include "base/ranges/algorithm.h"
#include "base/trace_event/trace_event.h"
#include "base/win/win_util.h"
#include "third_party/skia/include/core/SkPath.h"
#include "third_party/skia/include/core/SkRegion.h"
#include "ui/aura/client/aura_constants.h"
#include "ui/aura/client/cursor_client.h"
#include "ui/aura/client/focus_client.h"
#include "ui/aura/window_event_dispatcher.h"
#include "ui/base/class_property.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/cursor/platform_cursor.h"
#include "ui/base/ime/input_method.h"
#include "ui/base/ui_base_features.h"
#include "ui/base/win/event_creation_utils.h"
#include "ui/base/win/win_cursor.h"
#include "ui/compositor/compositor.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/paint_context.h"
#include "ui/display/win/dpi.h"
#include "ui/display/win/screen_win.h"
#include "ui/events/keyboard_hook.h"
#include "ui/events/keycodes/dom/dom_code.h"
#include "ui/events/keycodes/dom/dom_keyboard_layout_map.h"
#include "ui/events/platform/platform_event_source.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/gfx/geometry/vector2d.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/gfx/path_win.h"
#include "ui/views/corewm/tooltip_aura.h"
#include "ui/views/views_features.h"
#include "ui/views/views_switches.h"
#include "ui/views/widget/desktop_aura/desktop_drag_drop_client_win.h"
#include "ui/views/widget/desktop_aura/desktop_native_cursor_manager.h"
#include "ui/views/widget/desktop_aura/desktop_native_cursor_manager_win.h"
#include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h"
#include "ui/views/widget/root_view.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/widget/widget_hwnd_utils.h"
#include "ui/views/win/fullscreen_handler.h"
#include "ui/views/win/hwnd_message_handler.h"
#include "ui/views/win/hwnd_util.h"
#include "ui/views/window/native_frame_view.h"
#include "ui/wm/core/compound_event_filter.h"
#include "ui/wm/core/window_animations.h"
#include "ui/wm/public/scoped_tooltip_disabler.h"
DEFINE_UI_CLASS_PROPERTY_TYPE(views::DesktopWindowTreeHostWin*)
namespace views {
namespace {
// While the mouse is locked we want the invisible mouse to stay within the
// confines of the screen so we keep it in a capture region the size of the
// screen. However, on windows when the mouse hits the edge of the screen some
// events trigger and cause strange issues to occur. To stop those events from
// occurring we add a small border around the edge of the capture region.
// This constant controls how many pixels wide that border is.
const int kMouseCaptureRegionBorder = 5;
gfx::Size GetExpandedWindowSize(bool is_translucent, gfx::Size size) {
if (!is_translucent) {
return size;
}
// Some AMD drivers can't display windows that are less than 64x64 pixels,
// so expand them to be at least that size. http://crbug.com/286609
gfx::Size expanded(std::max(size.width(), 64), std::max(size.height(), 64));
return expanded;
}
void InsetBottomRight(gfx::Rect* rect, const gfx::Vector2d& vector) {
rect->Inset(gfx::Insets::TLBR(0, 0, vector.y(), vector.x()));
}
// Updates the cursor clip region. Used for mouse locking.
void UpdateMouseLockRegion(aura::Window* window, bool locked) {
if (!locked) {
::ClipCursor(nullptr);
return;
}
RECT window_rect =
display::Screen::GetScreen()
->DIPToScreenRectInWindow(window, window->GetBoundsInScreen())
.ToRECT();
window_rect.left += kMouseCaptureRegionBorder;
window_rect.right -= kMouseCaptureRegionBorder;
window_rect.top += kMouseCaptureRegionBorder;
window_rect.bottom -= kMouseCaptureRegionBorder;
::ClipCursor(&window_rect);
}
} // namespace
DEFINE_UI_CLASS_PROPERTY_KEY(aura::Window*, kContentWindowForRootWindow, NULL)
// Identifies the DesktopWindowTreeHostWin associated with the
// WindowEventDispatcher.
DEFINE_UI_CLASS_PROPERTY_KEY(DesktopWindowTreeHostWin*,
kDesktopWindowTreeHostKey,
NULL)
////////////////////////////////////////////////////////////////////////////////
// DesktopWindowTreeHostWin, public:
bool DesktopWindowTreeHostWin::is_cursor_visible_ = true;
DesktopWindowTreeHostWin::DesktopWindowTreeHostWin(
internal::NativeWidgetDelegate* native_widget_delegate,
DesktopNativeWidgetAura* desktop_native_widget_aura)
: message_handler_(new HWNDMessageHandler(
this,
native_widget_delegate->AsWidget()->GetName())),
native_widget_delegate_(native_widget_delegate->AsWidget()->GetWeakPtr()),
desktop_native_widget_aura_(desktop_native_widget_aura),
drag_drop_client_(nullptr),
should_animate_window_close_(false),
pending_close_(false),
has_non_client_view_(false) {}
DesktopWindowTreeHostWin::~DesktopWindowTreeHostWin() {
desktop_native_widget_aura_->OnDesktopWindowTreeHostDestroyed(this);
DestroyDispatcher();
}
// static
aura::Window* DesktopWindowTreeHostWin::GetContentWindowForHWND(HWND hwnd) {
// All HWND's we create should have WindowTreeHost instances associated with
// them. There are exceptions like the content layer creating HWND's which
// are not associated with WindowTreeHost instances.
aura::WindowTreeHost* host =
aura::WindowTreeHost::GetForAcceleratedWidget(hwnd);
return host ? host->window()->GetProperty(kContentWindowForRootWindow) : NULL;
}
void DesktopWindowTreeHostWin::StartTouchDrag(gfx::Point screen_point) {
// Send a mouse down and mouse move before do drag drop runs its own event
// loop. This is required for ::DoDragDrop to start the drag.
ui::SendMouseEvent(screen_point, MOUSEEVENTF_LEFTDOWN | MOUSEEVENTF_ABSOLUTE);
ui::SendMouseEvent(screen_point, MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE);
in_touch_drag_ = true;
}
void DesktopWindowTreeHostWin::FinishTouchDrag(gfx::Point screen_point) {
if (in_touch_drag_) {
in_touch_drag_ = false;
ui::SendMouseEvent(screen_point, MOUSEEVENTF_LEFTUP | MOUSEEVENTF_ABSOLUTE);
}
}
////////////////////////////////////////////////////////////////////////////////
// DesktopWindowTreeHostWin, DesktopWindowTreeHost implementation:
void DesktopWindowTreeHostWin::Init(const Widget::InitParams& params) {
wants_mouse_events_when_inactive_ = params.wants_mouse_events_when_inactive;
wm::SetAnimationHost(content_window(), this);
if (params.type == Widget::InitParams::TYPE_WINDOW &&
!params.remove_standard_frame)
content_window()->SetProperty(aura::client::kAnimationsDisabledKey, true);
ConfigureWindowStyles(message_handler_.get(), params,
GetWidget()->widget_delegate(),
native_widget_delegate_.get());
HWND parent_hwnd = nullptr;
if (params.parent_widget) {
parent_hwnd = params.parent_widget;
has_external_parent_ = true;
} else if (params.parent && params.parent->GetHost()) {
parent_hwnd = params.parent->GetHost()->GetAcceleratedWidget();
}
remove_standard_frame_ = params.remove_standard_frame;
has_non_client_view_ = Widget::RequiresNonClientView(params.type);
z_order_ = params.EffectiveZOrderLevel();
gfx::Rect pixel_bounds;
if (has_external_parent_ && params.type != Widget::InitParams::TYPE_MENU) {
// Scale relative to the screen that contains the parent window.
// Child windows always have origin (0,0).
pixel_bounds.set_size(display::win::ScreenWin::DIPToScreenSize(
parent_hwnd, params.bounds.size()));
} else {
// We don't have an HWND yet, so scale relative to the nearest screen.
pixel_bounds =
display::win::ScreenWin::DIPToScreenRect(nullptr, params.bounds);
}
message_handler_->Init(parent_hwnd, pixel_bounds, params.headless_mode);
CreateCompositor(params.force_software_compositing);
OnAcceleratedWidgetAvailable();
InitHost();
window()->Show();
if (base::FeatureList::IsEnabled(views::features::kWidgetLayering)) {
// Stack immedately above its parent so that it does not cover other
// root-level windows.
if (params.parent)
StackAbove(params.parent);
}
}
void DesktopWindowTreeHostWin::OnNativeWidgetCreated(
const Widget::InitParams& params) {
// The cursor is not necessarily visible when the root window is created.
aura::client::CursorClient* cursor_client =
aura::client::GetCursorClient(window());
if (cursor_client)
is_cursor_visible_ = cursor_client->IsCursorVisible();
window()->SetProperty(kContentWindowForRootWindow, content_window());
window()->SetProperty(kDesktopWindowTreeHostKey, this);
should_animate_window_close_ =
content_window()->GetType() != aura::client::WINDOW_TYPE_NORMAL &&
!wm::WindowAnimationsDisabled(content_window());
}
void DesktopWindowTreeHostWin::OnActiveWindowChanged(bool active) {}
void DesktopWindowTreeHostWin::OnWidgetInitDone() {}
std::unique_ptr<corewm::Tooltip> DesktopWindowTreeHostWin::CreateTooltip() {
return std::make_unique<corewm::TooltipAura>();
}
std::unique_ptr<aura::client::DragDropClient>
DesktopWindowTreeHostWin::CreateDragDropClient() {
auto res =
std::make_unique<DesktopDragDropClientWin>(window(), GetHWND(), this);
drag_drop_client_ = res->GetWeakPtr();
return std::move(res);
}
void DesktopWindowTreeHostWin::Close() {
// Calling Hide() can detach the content window's layer, so store it
// beforehand so we can access it below.
auto* window_layer = content_window()->layer();
content_window()->Hide();
// TODO(beng): Move this entire branch to DNWA so it can be shared with X11.
if (should_animate_window_close_) {
pending_close_ = true;
// Animation may not start for a number of reasons.
if (!window_layer->GetAnimator()->is_animating())
message_handler_->Close();
// else case, OnWindowHidingAnimationCompleted does the actual Close.
} else {
message_handler_->Close();
}
}
void DesktopWindowTreeHostWin::CloseNow() {
message_handler_->CloseNow();
}
aura::WindowTreeHost* DesktopWindowTreeHostWin::AsWindowTreeHost() {
return this;
}
void DesktopWindowTreeHostWin::Show(ui::WindowShowState show_state,
const gfx::Rect& restore_bounds) {
OnAcceleratedWidgetMadeVisible(true);
gfx::Rect pixel_restore_bounds;
if (show_state == ui::SHOW_STATE_MAXIMIZED) {
// The window parameter is intentionally passed as nullptr because a
// non-null window parameter causes errors when restoring windows to saved
// positions in variable-DPI situations. See https://crbug.com/1252564 for
// details.
pixel_restore_bounds =
display::win::ScreenWin::DIPToScreenRect(nullptr, restore_bounds);
}
message_handler_->Show(show_state, pixel_restore_bounds);
content_window()->Show();
}
bool DesktopWindowTreeHostWin::IsVisible() const {
return message_handler_->IsVisible();
}
void DesktopWindowTreeHostWin::SetSize(const gfx::Size& size) {
gfx::Size size_in_pixels =
display::win::ScreenWin::DIPToScreenSize(GetHWND(), size);
gfx::Size expanded =
GetExpandedWindowSize(message_handler_->is_translucent(), size_in_pixels);
window_enlargement_ =
gfx::Vector2d(expanded.width() - size_in_pixels.width(),
expanded.height() - size_in_pixels.height());
message_handler_->SetSize(expanded);
}
void DesktopWindowTreeHostWin::StackAbove(aura::Window* window) {
HWND hwnd = HWNDForNativeView(window);
if (hwnd)
message_handler_->StackAbove(hwnd);
}
void DesktopWindowTreeHostWin::StackAtTop() {
message_handler_->StackAtTop();
}
void DesktopWindowTreeHostWin::CenterWindow(const gfx::Size& size) {
gfx::Size size_in_pixels =
display::win::ScreenWin::DIPToScreenSize(GetHWND(), size);
gfx::Size expanded_size;
expanded_size =
GetExpandedWindowSize(message_handler_->is_translucent(), size_in_pixels);
window_enlargement_ =
gfx::Vector2d(expanded_size.width() - size_in_pixels.width(),
expanded_size.height() - size_in_pixels.height());
message_handler_->CenterWindow(expanded_size);
}
void DesktopWindowTreeHostWin::GetWindowPlacement(
gfx::Rect* bounds,
ui::WindowShowState* show_state) const {
message_handler_->GetWindowPlacement(bounds, show_state);
InsetBottomRight(bounds, window_enlargement_);
*bounds = display::win::ScreenWin::ScreenToDIPRect(GetHWND(), *bounds);
}
gfx::Rect DesktopWindowTreeHostWin::GetWindowBoundsInScreen() const {
gfx::Rect pixel_bounds = message_handler_->GetWindowBoundsInScreen();
InsetBottomRight(&pixel_bounds, window_enlargement_);
return display::win::ScreenWin::ScreenToDIPRect(GetHWND(), pixel_bounds);
}
gfx::Rect DesktopWindowTreeHostWin::GetClientAreaBoundsInScreen() const {
gfx::Rect pixel_bounds = message_handler_->GetClientAreaBoundsInScreen();
InsetBottomRight(&pixel_bounds, window_enlargement_);
return display::win::ScreenWin::ScreenToDIPRect(GetHWND(), pixel_bounds);
}
gfx::Rect DesktopWindowTreeHostWin::GetRestoredBounds() const {
gfx::Rect pixel_bounds = message_handler_->GetRestoredBounds();
InsetBottomRight(&pixel_bounds, window_enlargement_);
return display::win::ScreenWin::ScreenToDIPRect(GetHWND(), pixel_bounds);
}
std::string DesktopWindowTreeHostWin::GetWorkspace() const {
return std::string();
}
gfx::Rect DesktopWindowTreeHostWin::GetWorkAreaBoundsInScreen() const {
MONITORINFO monitor_info;
monitor_info.cbSize = sizeof(monitor_info);
GetMonitorInfo(
MonitorFromWindow(message_handler_->hwnd(), MONITOR_DEFAULTTONEAREST),
&monitor_info);
gfx::Rect pixel_bounds = gfx::Rect(monitor_info.rcWork);
return display::win::ScreenWin::ScreenToDIPRect(GetHWND(), pixel_bounds);
}
void DesktopWindowTreeHostWin::SetShape(
std::unique_ptr<Widget::ShapeRects> native_shape) {
if (!native_shape || native_shape->empty()) {
message_handler_->SetRegion(nullptr);
return;
}
// TODO(wez): This would be a lot simpler if we were passed an SkPath.
// See crbug.com/410593.
SkRegion shape;
const float scale = display::win::ScreenWin::GetScaleFactorForHWND(GetHWND());
if (scale > 1.0) {
std::vector<SkIRect> sk_rects;
for (const gfx::Rect& rect : *native_shape) {
const SkIRect sk_rect = gfx::RectToSkIRect(rect);
SkRect scaled_rect =
SkRect::MakeLTRB(sk_rect.left() * scale, sk_rect.top() * scale,
sk_rect.right() * scale, sk_rect.bottom() * scale);
SkIRect rounded_scaled_rect;
scaled_rect.roundOut(&rounded_scaled_rect);
sk_rects.push_back(rounded_scaled_rect);
}
shape.setRects(&sk_rects[0], static_cast<int>(sk_rects.size()));
} else {
for (const gfx::Rect& rect : *native_shape)
shape.op(gfx::RectToSkIRect(rect), SkRegion::kUnion_Op);
}
message_handler_->SetRegion(gfx::CreateHRGNFromSkRegion(shape));
}
void DesktopWindowTreeHostWin::Activate() {
message_handler_->Activate();
}
void DesktopWindowTreeHostWin::Deactivate() {
message_handler_->Deactivate();
}
bool DesktopWindowTreeHostWin::IsActive() const {
return message_handler_->IsActive();
}
void DesktopWindowTreeHostWin::PaintAsActiveChanged() {
message_handler_->PaintAsActiveChanged();
}
void DesktopWindowTreeHostWin::Maximize() {
message_handler_->Maximize();
}
void DesktopWindowTreeHostWin::Minimize() {
message_handler_->Minimize();
}
void DesktopWindowTreeHostWin::Restore() {
message_handler_->Restore();
}
bool DesktopWindowTreeHostWin::IsMaximized() const {
return message_handler_->IsMaximized();
}
bool DesktopWindowTreeHostWin::IsMinimized() const {
return message_handler_->IsMinimized();
}
bool DesktopWindowTreeHostWin::HasCapture() const {
return message_handler_->HasCapture();
}
void DesktopWindowTreeHostWin::SetZOrderLevel(ui::ZOrderLevel order) {
z_order_ = order;
// Emulate the multiple window levels provided by other platforms by
// collapsing the z-order enum into kNormal = normal, everything else = always
// on top.
message_handler_->SetAlwaysOnTop(order != ui::ZOrderLevel::kNormal);
}
ui::ZOrderLevel DesktopWindowTreeHostWin::GetZOrderLevel() const {
bool window_always_on_top = message_handler_->IsAlwaysOnTop();
bool level_always_on_top = z_order_ != ui::ZOrderLevel::kNormal;
if (window_always_on_top == level_always_on_top)
return z_order_;
// If something external has forced a window to be always-on-top, map it to
// kFloatingWindow as a reasonable equivalent.
return window_always_on_top ? ui::ZOrderLevel::kFloatingWindow
: ui::ZOrderLevel::kNormal;
}
bool DesktopWindowTreeHostWin::IsStackedAbove(aura::Window* window) {
HWND above = GetHWND();
HWND below = window->GetHost()->GetAcceleratedWidget();
// Child windows are always above their parent windows.
// Check to see if HWNDs have a Parent-Child relationship.
if (IsChild(below, above))
return true;
if (IsChild(above, below))
return false;
// Check all HWNDs with lower z order than current HWND
// to see if it matches or is a parent to the "below" HWND.
bool result = false;
HWND parent = above;
while (parent && parent != GetDesktopWindow()) {
HWND next = parent;
while (next) {
// GW_HWNDNEXT retrieves the next HWND below z order level.
next = GetWindow(next, GW_HWNDNEXT);
if (next == below || IsChild(next, below)) {
result = true;
break;
}
}
parent = GetAncestor(parent, GA_PARENT);
}
return result;
}
void DesktopWindowTreeHostWin::SetVisibleOnAllWorkspaces(bool always_visible) {
// Chrome does not yet support Windows 10 desktops.
}
bool DesktopWindowTreeHostWin::IsVisibleOnAllWorkspaces() const {
return false;
}
bool DesktopWindowTreeHostWin::SetWindowTitle(const std::u16string& title) {
return message_handler_->SetTitle(title);
}
void DesktopWindowTreeHostWin::ClearNativeFocus() {
message_handler_->ClearNativeFocus();
}
Widget::MoveLoopResult DesktopWindowTreeHostWin::RunMoveLoop(
const gfx::Vector2d& drag_offset,
Widget::MoveLoopSource source,
Widget::MoveLoopEscapeBehavior escape_behavior) {
const bool hide_on_escape =
escape_behavior == Widget::MoveLoopEscapeBehavior::kHide;
return message_handler_->RunMoveLoop(drag_offset, hide_on_escape)
? Widget::MoveLoopResult::kSuccessful
: Widget::MoveLoopResult::kCanceled;
}
void DesktopWindowTreeHostWin::EndMoveLoop() {
message_handler_->EndMoveLoop();
}
void DesktopWindowTreeHostWin::SetVisibilityChangedAnimationsEnabled(
bool value) {
message_handler_->SetVisibilityChangedAnimationsEnabled(value);
content_window()->SetProperty(aura::client::kAnimationsDisabledKey, !value);
}
std::unique_ptr<NonClientFrameView>
DesktopWindowTreeHostWin::CreateNonClientFrameView() {
return ShouldUseNativeFrame() ? std::make_unique<NativeFrameView>(
native_widget_delegate_->AsWidget())
: nullptr;
}
bool DesktopWindowTreeHostWin::ShouldUseNativeFrame() const {
return IsTranslucentWindowOpacitySupported();
}
bool DesktopWindowTreeHostWin::ShouldWindowContentsBeTransparent() const {
// The window contents need to be transparent when the titlebar area is drawn
// by the DWM rather than Chrome, so that area can show through. This
// function does not describe the transparency of the whole window appearance,
// but merely of the content Chrome draws, so even when the system titlebars
// appear opaque (Win 8+), the content above them needs to be transparent, or
// they'll be covered by a black (undrawn) region.
return ShouldUseNativeFrame() && !IsFullscreen();
}
void DesktopWindowTreeHostWin::FrameTypeChanged() {
message_handler_->FrameTypeChanged();
}
void DesktopWindowTreeHostWin::SetFullscreen(bool fullscreen,
int64_t target_display_id) {
auto weak_ptr = GetWeakPtr();
message_handler_->SetFullscreen(fullscreen, target_display_id);
if (!weak_ptr)
return;
// TODO(sky): workaround for ScopedFullscreenVisibility showing window
// directly. Instead of this should listen for visibility changes and then
// update window.
if (message_handler_->IsVisible() && !content_window()->TargetVisibility()) {
OnAcceleratedWidgetMadeVisible(true);
content_window()->Show();
}
desktop_native_widget_aura_->UpdateWindowTransparency();
}
bool DesktopWindowTreeHostWin::IsFullscreen() const {
return message_handler_->IsFullscreen();
}
void DesktopWindowTreeHostWin::SetOpacity(float opacity) {
content_window()->layer()->SetOpacity(opacity);
}
void DesktopWindowTreeHostWin::SetAspectRatio(
const gfx::SizeF& aspect_ratio,
const gfx::Size& excluded_margin) {
DCHECK(!aspect_ratio.IsEmpty());
message_handler_->SetAspectRatio(aspect_ratio.width() / aspect_ratio.height(),
excluded_margin);
}
void DesktopWindowTreeHostWin::SetWindowIcons(const gfx::ImageSkia& window_icon,
const gfx::ImageSkia& app_icon) {
message_handler_->SetWindowIcons(window_icon, app_icon);
}
void DesktopWindowTreeHostWin::InitModalType(ui::ModalType modal_type) {
message_handler_->InitModalType(modal_type);
}
void DesktopWindowTreeHostWin::FlashFrame(bool flash_frame) {
message_handler_->FlashFrame(flash_frame);
}
bool DesktopWindowTreeHostWin::IsAnimatingClosed() const {
return pending_close_;
}
bool DesktopWindowTreeHostWin::IsTranslucentWindowOpacitySupported() const {
return true;
}
void DesktopWindowTreeHostWin::SizeConstraintsChanged() {
message_handler_->SizeConstraintsChanged();
}
bool DesktopWindowTreeHostWin::ShouldUpdateWindowTransparency() const {
return true;
}
bool DesktopWindowTreeHostWin::ShouldUseDesktopNativeCursorManager() const {
return true;
}
bool DesktopWindowTreeHostWin::ShouldCreateVisibilityController() const {
return true;
}
////////////////////////////////////////////////////////////////////////////////
// DesktopWindowTreeHostWin, WindowTreeHost implementation:
ui::EventSource* DesktopWindowTreeHostWin::GetEventSource() {
return this;
}
gfx::AcceleratedWidget DesktopWindowTreeHostWin::GetAcceleratedWidget() {
return message_handler_->hwnd();
}
void DesktopWindowTreeHostWin::ShowImpl() {
Show(ui::SHOW_STATE_NORMAL, gfx::Rect());
}
void DesktopWindowTreeHostWin::HideImpl() {
if (!pending_close_)
message_handler_->Hide();
}
// GetBoundsInPixels and SetBoundsInPixels work in pixel coordinates, whereas
// other get/set methods work in DIP.
gfx::Rect DesktopWindowTreeHostWin::GetBoundsInPixels() const {
gfx::Rect bounds(message_handler_->GetClientAreaBounds());
// If the window bounds were expanded we need to return the original bounds
// To achieve this we do the reverse of the expansion, i.e. add the
// window_expansion_top_left_delta_ to the origin and subtract the
// window_expansion_bottom_right_delta_ from the width and height.
gfx::Rect without_expansion(
bounds.x() + window_expansion_top_left_delta_.x(),
bounds.y() + window_expansion_top_left_delta_.y(),
bounds.width() - window_expansion_bottom_right_delta_.x() -
window_enlargement_.x(),
bounds.height() - window_expansion_bottom_right_delta_.y() -
window_enlargement_.y());
return without_expansion;
}
void DesktopWindowTreeHostWin::SetBoundsInPixels(const gfx::Rect& bounds) {
// If the window bounds have to be expanded we need to subtract the
// window_expansion_top_left_delta_ from the origin and add the
// window_expansion_bottom_right_delta_ to the width and height
gfx::Size old_content_size = GetBoundsInPixels().size();
gfx::Rect expanded(
bounds.x() - window_expansion_top_left_delta_.x(),
bounds.y() - window_expansion_top_left_delta_.y(),
bounds.width() + window_expansion_bottom_right_delta_.x(),
bounds.height() + window_expansion_bottom_right_delta_.y());
gfx::Rect new_expanded(
expanded.origin(),
GetExpandedWindowSize(message_handler_->is_translucent(),
expanded.size()));
window_enlargement_ =
gfx::Vector2d(new_expanded.width() - expanded.width(),
new_expanded.height() - expanded.height());
// When |new_expanded| causes the window to be moved to a display with a
// different DSF, HWNDMessageHandler::OnDpiChanged() will be called and the
// window size will be scaled automatically.
message_handler_->SetBounds(new_expanded, old_content_size != bounds.size());
}
gfx::Rect
DesktopWindowTreeHostWin::GetBoundsInAcceleratedWidgetPixelCoordinates() {
if (message_handler_->IsMinimized())
return gfx::Rect();
const gfx::Rect client_bounds =
message_handler_->GetClientAreaBoundsInScreen();
const gfx::Rect window_bounds = message_handler_->GetWindowBoundsInScreen();
if (window_bounds == client_bounds)
return gfx::Rect(window_bounds.size());
const gfx::Vector2d offset = client_bounds.origin() - window_bounds.origin();
DCHECK(offset.x() >= 0 && offset.y() >= 0);
return gfx::Rect(gfx::Point() + offset, client_bounds.size());
}
gfx::Point DesktopWindowTreeHostWin::GetLocationOnScreenInPixels() const {
return GetBoundsInPixels().origin();
}
void DesktopWindowTreeHostWin::SetCapture() {
message_handler_->SetCapture();
}
void DesktopWindowTreeHostWin::ReleaseCapture() {
message_handler_->ReleaseCapture();
}
bool DesktopWindowTreeHostWin::CaptureSystemKeyEventsImpl(
absl::optional<base::flat_set<ui::DomCode>> dom_codes) {
// Only one KeyboardHook should be active at a time, otherwise there will be
// problems with event routing (i.e. which Hook takes precedence) and
// destruction ordering.
DCHECK(!keyboard_hook_);
keyboard_hook_ = ui::KeyboardHook::CreateModifierKeyboardHook(
std::move(dom_codes), GetAcceleratedWidget(),
base::BindRepeating(&DesktopWindowTreeHostWin::HandleKeyEvent,
base::Unretained(this)));
return keyboard_hook_ != nullptr;
}
void DesktopWindowTreeHostWin::ReleaseSystemKeyEventCapture() {
keyboard_hook_.reset();
}
bool DesktopWindowTreeHostWin::IsKeyLocked(ui::DomCode dom_code) {
return keyboard_hook_ && keyboard_hook_->IsKeyLocked(dom_code);
}
base::flat_map<std::string, std::string>
DesktopWindowTreeHostWin::GetKeyboardLayoutMap() {
return ui::GenerateDomKeyboardLayoutMap();
}
void DesktopWindowTreeHostWin::SetCursorNative(gfx::NativeCursor cursor) {
TRACE_EVENT1("ui,input", "DesktopWindowTreeHostWin::SetCursorNative",
"cursor", cursor.type());
message_handler_->SetCursor(
ui::WinCursor::FromPlatformCursor(cursor.platform()));
}
void DesktopWindowTreeHostWin::OnCursorVisibilityChangedNative(bool show) {
if (is_cursor_visible_ == show)
return;
is_cursor_visible_ = show;
::ShowCursor(!!show);
}
void DesktopWindowTreeHostWin::MoveCursorToScreenLocationInPixels(
const gfx::Point& location_in_pixels) {
POINT cursor_location = location_in_pixels.ToPOINT();
::ClientToScreen(GetHWND(), &cursor_location);
::SetCursorPos(cursor_location.x, cursor_location.y);
}
std::unique_ptr<aura::ScopedEnableUnadjustedMouseEvents>
DesktopWindowTreeHostWin::RequestUnadjustedMovement() {
return message_handler_->RegisterUnadjustedMouseEvent();
}
void DesktopWindowTreeHostWin::LockMouse(aura::Window* window) {
UpdateMouseLockRegion(window, true /*locked*/);
WindowTreeHost::LockMouse(window);
}
void DesktopWindowTreeHostWin::UnlockMouse(aura::Window* window) {
UpdateMouseLockRegion(window, false /*locked*/);
WindowTreeHost::UnlockMouse(window);
}
////////////////////////////////////////////////////////////////////////////////
// DesktopWindowTreeHostWin, wm::AnimationHost implementation:
void DesktopWindowTreeHostWin::SetHostTransitionOffsets(
const gfx::Vector2d& top_left_delta,
const gfx::Vector2d& bottom_right_delta) {
gfx::Rect bounds_without_expansion = GetBoundsInPixels();
window_expansion_top_left_delta_ = top_left_delta;
window_expansion_bottom_right_delta_ = bottom_right_delta;
SetBoundsInPixels(bounds_without_expansion);
}
void DesktopWindowTreeHostWin::OnWindowHidingAnimationCompleted() {
if (pending_close_)
message_handler_->Close();
}
////////////////////////////////////////////////////////////////////////////////
// DesktopWindowTreeHostWin, HWNDMessageHandlerDelegate implementation:
ui::InputMethod* DesktopWindowTreeHostWin::GetHWNDMessageDelegateInputMethod() {
return GetInputMethod();
}
bool DesktopWindowTreeHostWin::HasNonClientView() const {
return has_non_client_view_;
}
FrameMode DesktopWindowTreeHostWin::GetFrameMode() const {
if (!GetWidget())
return FrameMode::SYSTEM_DRAWN;
return GetWidget()->ShouldUseNativeFrame() ? FrameMode::SYSTEM_DRAWN
: FrameMode::CUSTOM_DRAWN;
}
bool DesktopWindowTreeHostWin::HasFrame() const {
return !remove_standard_frame_;
}
void DesktopWindowTreeHostWin::SchedulePaint() {
if (GetWidget())
GetWidget()->GetRootView()->SchedulePaint();
}
bool DesktopWindowTreeHostWin::ShouldPaintAsActive() const {
return GetWidget() ? GetWidget()->ShouldPaintAsActive() : false;
}
bool DesktopWindowTreeHostWin::CanResize() const {
return GetWidget()->widget_delegate()->CanResize();
}
bool DesktopWindowTreeHostWin::CanMaximize() const {
return GetWidget()->widget_delegate()->CanMaximize();
}
bool DesktopWindowTreeHostWin::CanMinimize() const {
return GetWidget()->widget_delegate()->CanMinimize();
}
bool DesktopWindowTreeHostWin::CanActivate() const {
if (IsModalWindowActive())
return true;
return native_widget_delegate_ ? native_widget_delegate_->CanActivate()
: false;
}
bool DesktopWindowTreeHostWin::WantsMouseEventsWhenInactive() const {
return wants_mouse_events_when_inactive_;
}
bool DesktopWindowTreeHostWin::WidgetSizeIsClientSize() const {
const Widget* widget =
GetWidget() ? GetWidget()->GetTopLevelWidget() : nullptr;
return IsMaximized() || (widget && widget->ShouldUseNativeFrame());
}
bool DesktopWindowTreeHostWin::IsModal() const {
return native_widget_delegate_ ? native_widget_delegate_->IsModal() : false;
}
int DesktopWindowTreeHostWin::GetInitialShowState() const {
return CanActivate() ? SW_SHOWNORMAL : SW_SHOWNOACTIVATE;
}
int DesktopWindowTreeHostWin::GetNonClientComponent(
const gfx::Point& point) const {
gfx::Point dip_position =
display::win::ScreenWin::ClientToDIPPoint(GetHWND(), point);
return native_widget_delegate_->GetNonClientComponent(dip_position);
}
void DesktopWindowTreeHostWin::GetWindowMask(const gfx::Size& size,
SkPath* path) {
if (GetWidget()->non_client_view()) {
GetWidget()->non_client_view()->GetWindowMask(
display::win::ScreenWin::ScreenToDIPSize(GetHWND(), size), path);
// Convert path in DIPs to pixels.
if (!path->isEmpty()) {
const float scale =
display::win::ScreenWin::GetScaleFactorForHWND(GetHWND());
SkScalar sk_scale = SkFloatToScalar(scale);
SkMatrix matrix;
matrix.setScale(sk_scale, sk_scale);
path->transform(matrix);
}
} else if (!window_enlargement_.IsZero()) {
gfx::Rect bounds(WidgetSizeIsClientSize()
? message_handler_->GetClientAreaBoundsInScreen()
: message_handler_->GetWindowBoundsInScreen());
InsetBottomRight(&bounds, window_enlargement_);
path->addRect(SkRect::MakeXYWH(0, 0, bounds.width(), bounds.height()));
}
}
bool DesktopWindowTreeHostWin::GetClientAreaInsets(gfx::Insets* insets,
HMONITOR monitor) const {
return false;
}
bool DesktopWindowTreeHostWin::GetDwmFrameInsetsInPixels(
gfx::Insets* insets) const {
return false;
}
void DesktopWindowTreeHostWin::GetMinMaxSize(gfx::Size* min_size,
gfx::Size* max_size) const {
*min_size = native_widget_delegate_->GetMinimumSize();
*max_size = native_widget_delegate_->GetMaximumSize();
}
gfx::Size DesktopWindowTreeHostWin::GetRootViewSize() const {
return GetWidget()->GetRootView()->size();
}
gfx::Size DesktopWindowTreeHostWin::DIPToScreenSize(
const gfx::Size& dip_size) const {
return display::win::ScreenWin::DIPToScreenSize(GetHWND(), dip_size);
}
void DesktopWindowTreeHostWin::ResetWindowControls() {
if (GetWidget()->non_client_view())
GetWidget()->non_client_view()->ResetWindowControls();
}
gfx::NativeViewAccessible DesktopWindowTreeHostWin::GetNativeViewAccessible() {
// This function may be called during shutdown when the |RootView| is nullptr.
return GetWidget()->GetRootView()
? GetWidget()->GetRootView()->GetNativeViewAccessible()
: nullptr;
}
void DesktopWindowTreeHostWin::HandleActivationChanged(bool active) {
// This can be invoked from HWNDMessageHandler::Init(), at which point we're
// not in a good state and need to ignore it.
// TODO(beng): Do we need this still now the host owns the dispatcher?
if (!dispatcher())
return;
desktop_native_widget_aura_->HandleActivationChanged(active);
}
bool DesktopWindowTreeHostWin::HandleAppCommand(int command) {
// We treat APPCOMMAND ids as an extension of our command namespace, and just
// let the delegate figure out what to do...
return GetWidget()->widget_delegate() &&
GetWidget()->widget_delegate()->ExecuteWindowsCommand(command);
}
void DesktopWindowTreeHostWin::HandleCancelMode() {
dispatcher()->DispatchCancelModeEvent();
}
void DesktopWindowTreeHostWin::HandleCaptureLost() {
OnHostLostWindowCapture();
}
void DesktopWindowTreeHostWin::HandleClose() {
GetWidget()->Close();
}
bool DesktopWindowTreeHostWin::HandleCommand(int command) {
return GetWidget()->widget_delegate()->ExecuteWindowsCommand(command);
}
void DesktopWindowTreeHostWin::HandleAccelerator(
const ui::Accelerator& accelerator) {
GetWidget()->GetFocusManager()->ProcessAccelerator(accelerator);
}
void DesktopWindowTreeHostWin::HandleCreate() {
native_widget_delegate_->OnNativeWidgetCreated();
}
void DesktopWindowTreeHostWin::HandleDestroying() {
drag_drop_client_->OnNativeWidgetDestroying(GetHWND());
if (native_widget_delegate_)
native_widget_delegate_->OnNativeWidgetDestroying();
// Destroy the compositor before destroying the HWND since shutdown
// may try to swap to the window.
DestroyCompositor();
}
void DesktopWindowTreeHostWin::HandleDestroyed() {
desktop_native_widget_aura_->OnHostClosed();
}
bool DesktopWindowTreeHostWin::HandleInitialFocus(
ui::WindowShowState show_state) {
return GetWidget()->SetInitialFocus(show_state);
}
void DesktopWindowTreeHostWin::HandleDisplayChange() {
GetWidget()->widget_delegate()->OnDisplayChanged();
}
void DesktopWindowTreeHostWin::HandleBeginWMSizeMove() {
native_widget_delegate_->OnNativeWidgetBeginUserBoundsChange();
}
void DesktopWindowTreeHostWin::HandleEndWMSizeMove() {
native_widget_delegate_->OnNativeWidgetEndUserBoundsChange();
}
void DesktopWindowTreeHostWin::HandleMove() {
CheckForMonitorChange();
OnHostMovedInPixels();
}
void DesktopWindowTreeHostWin::HandleWorkAreaChanged() {
CheckForMonitorChange();
GetWidget()->widget_delegate()->OnWorkAreaChanged();
}
void DesktopWindowTreeHostWin::HandleVisibilityChanged(bool visible) {
if (native_widget_delegate_)
native_widget_delegate_->OnNativeWidgetVisibilityChanged(visible);
}
void DesktopWindowTreeHostWin::HandleWindowMinimizedOrRestored(bool restored) {
// Ignore minimize/restore events that happen before widget initialization is
// done. If a window is created minimized, and then activated, restoring
// focus will fail because the root window is not visible, which is exposed by
// ExtensionWindowCreateTest.AcceptState.
if (!native_widget_delegate_->IsNativeWidgetInitialized())
return;
if (restored)
window()->Show();
else
window()->Hide();
}
void DesktopWindowTreeHostWin::HandleClientSizeChanged(
const gfx::Size& new_size) {
CheckForMonitorChange();
if (dispatcher())
OnHostResizedInPixels(new_size);
}
void DesktopWindowTreeHostWin::HandleFrameChanged() {
CheckForMonitorChange();
desktop_native_widget_aura_->UpdateWindowTransparency();
// Replace the frame and layout the contents.
if (GetWidget()->non_client_view())
GetWidget()->non_client_view()->UpdateFrame();
}
void DesktopWindowTreeHostWin::HandleNativeFocus(HWND last_focused_window) {
// See comments in CefBrowserPlatformDelegateNativeWin::SetFocus.
if (has_external_parent_ && CanActivate())
HandleActivationChanged(true);
}
void DesktopWindowTreeHostWin::HandleNativeBlur(HWND focused_window) {
// See comments in CefBrowserPlatformDelegateNativeWin::SetFocus.
if (has_external_parent_ && CanActivate())
HandleActivationChanged(false);
}
bool DesktopWindowTreeHostWin::HandleMouseEvent(ui::MouseEvent* event) {
// Ignore native platform events for test purposes
if (ui::PlatformEventSource::ShouldIgnoreNativePlatformEvents())
return true;
// See comments in CefBrowserPlatformDelegateNativeWin::SetFocus.
if (has_external_parent_ && CanActivate() && event->IsAnyButton() &&
::GetFocus() != GetHWND()) {
::SetFocus(GetHWND());
}
SendEventToSink(event);
return event->handled();
}
void DesktopWindowTreeHostWin::HandleKeyEvent(ui::KeyEvent* event) {
// Bypass normal handling of alt-space, which would otherwise consume the
// corresponding WM_SYSCHAR. This allows HandleIMEMessage() to show the
// system menu in this case. If we instead showed the system menu here, the
// WM_SYSCHAR would trigger a beep when processed by the native event handler.
if ((event->type() == ui::ET_KEY_PRESSED) &&
(event->key_code() == ui::VKEY_SPACE) &&
(event->flags() & ui::EF_ALT_DOWN) &&
!(event->flags() & ui::EF_CONTROL_DOWN) &&
GetWidget()->non_client_view()) {
return;
}
SendEventToSink(event);
}
void DesktopWindowTreeHostWin::HandleTouchEvent(ui::TouchEvent* event) {
// HWNDMessageHandler asynchronously processes touch events. Because of this
// it's possible for the aura::WindowEventDispatcher to have been destroyed
// by the time we attempt to process them.
if (!GetWidget()->GetNativeView())
return;
if (in_touch_drag_) {
POINT event_point;
event_point.x = event->location().x();
event_point.y = event->location().y();
::ClientToScreen(GetHWND(), &event_point);
gfx::Point screen_point(event_point);
// Send equivalent mouse events, because Ole32 drag drop doesn't seem to
// handle pointer events.
if (event->type() == ui::ET_TOUCH_MOVED) {
ui::SendMouseEvent(screen_point, MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE);
} else if (event->type() == ui::ET_TOUCH_RELEASED) {
FinishTouchDrag(screen_point);
}
}
// TODO(crbug.com/229301) Calling ::SetCursorPos for ui::ET_TOUCH_PRESSED
// events here would fix web ui tab strip drags when the cursor is not over
// the Chrome window - The TODO is to figure out if that's reasonable, since
// it would change the cursor pos on every touch event. Or figure out if there
// is a less intrusive way of fixing the cursor position. If we can do that,
// we can remove the call to ::SetCursorPos in
// DesktopDragDropClientWin::StartDragAndDrop. Note that calling SetCursorPos
// at the start of StartDragAndDrop breaks touch drag and drop, so it has to
// be called some time before we get to StartDragAndDrop.
// Currently we assume the window that has capture gets touch events too.
aura::WindowTreeHost* host =
aura::WindowTreeHost::GetForAcceleratedWidget(GetCapture());
if (host) {
DesktopWindowTreeHostWin* target =
host->window()->GetProperty(kDesktopWindowTreeHostKey);
if (target && target->HasCapture() && target != this) {
POINT target_location(event->location().ToPOINT());
ClientToScreen(GetHWND(), &target_location);
ScreenToClient(target->GetHWND(), &target_location);
ui::TouchEvent target_event(*event, static_cast<View*>(nullptr),
static_cast<View*>(nullptr));
target_event.set_location(gfx::Point(target_location));
target_event.set_root_location(target_event.location());
target->SendEventToSink(&target_event);
return;
}
}
SendEventToSink(event);
}
bool DesktopWindowTreeHostWin::HandleIMEMessage(UINT message,
WPARAM w_param,
LPARAM l_param,
LRESULT* result) {
// Show the system menu at an appropriate location on alt-space.
if ((message == WM_SYSCHAR) && (w_param == VK_SPACE) &&
GetWidget()->non_client_view()) {
const auto* frame = GetWidget()->non_client_view()->frame_view();
ShowSystemMenuAtScreenPixelLocation(
GetHWND(), frame->GetSystemMenuScreenPixelLocation());
return true;
}
CHROME_MSG msg = {};
msg.hwnd = GetHWND();
msg.message = message;
msg.wParam = w_param;
msg.lParam = l_param;
return GetInputMethod()->OnUntranslatedIMEMessage(msg, result);
}
void DesktopWindowTreeHostWin::HandleInputLanguageChange(
DWORD character_set,
HKL input_language_id) {
GetInputMethod()->OnInputLocaleChanged();
}
void DesktopWindowTreeHostWin::HandlePaintAccelerated(
const gfx::Rect& invalid_rect) {
if (compositor())
compositor()->ScheduleRedrawRect(invalid_rect);
}
void DesktopWindowTreeHostWin::HandleMenuLoop(bool in_menu_loop) {
if (in_menu_loop) {
tooltip_disabler_ = std::make_unique<wm::ScopedTooltipDisabler>(window());
} else {
tooltip_disabler_.reset();
}
}
bool DesktopWindowTreeHostWin::PreHandleMSG(UINT message,
WPARAM w_param,
LPARAM l_param,
LRESULT* result) {
return false;
}
void DesktopWindowTreeHostWin::PostHandleMSG(UINT message,
WPARAM w_param,
LPARAM l_param) {}
bool DesktopWindowTreeHostWin::HandleScrollEvent(ui::ScrollEvent* event) {
SendEventToSink(event);
return event->handled();
}
bool DesktopWindowTreeHostWin::HandleGestureEvent(ui::GestureEvent* event) {
SendEventToSink(event);
return event->handled();
}
void DesktopWindowTreeHostWin::HandleWindowSizeChanging() {
if (compositor())
compositor()->DisableSwapUntilResize();
}
void DesktopWindowTreeHostWin::HandleWindowSizeUnchanged() {
// A resize may not have occurred if the window size happened not to have
// changed (can occur on Windows 10 when snapping a window to the side of
// the screen). In that case do a resize to the current size to reenable
// swaps.
if (compositor())
compositor()->ReenableSwap();
}
void DesktopWindowTreeHostWin::HandleWindowScaleFactorChanged(
float window_scale_factor) {
// TODO(ccameron): This will violate surface invariants, and is insane.
// Shouldn't the scale factor and window pixel size changes be sent
// atomically? And how does this interact with updates to display::Display?
// Should we expect the display::Display to be updated before this? If so,
// why can't we use the DisplayObserver that the base WindowTreeHost is
// using?
if (compositor()) {
compositor()->SetScaleAndSize(
window_scale_factor, message_handler_->GetClientAreaBounds().size(),
window()->GetLocalSurfaceId());
}
}
void DesktopWindowTreeHostWin::HandleHeadlessWindowBoundsChanged(
const gfx::Rect& bounds) {
window()->SetProperty(aura::client::kHeadlessBoundsKey, bounds);
}
DesktopNativeCursorManager*
DesktopWindowTreeHostWin::GetSingletonDesktopNativeCursorManager() {
return new DesktopNativeCursorManagerWin();
}
void DesktopWindowTreeHostWin::SetBoundsInDIP(const gfx::Rect& bounds) {
// The window parameter is intentionally passed as nullptr on Windows because
// a non-null window parameter causes errors when restoring windows to saved
// positions in variable-DPI situations. See https://crbug.com/1224715 for
// details.
aura::Window* root = nullptr;
if (has_external_parent_) {
// Scale relative to the screen that contains the parent window.
root = AsWindowTreeHost()->window();
}
gfx::Rect bounds_in_pixels =
display::Screen::GetScreen()->DIPToScreenRectInWindow(root, bounds);
if (has_external_parent_) {
// Child windows always have origin (0,0).
bounds_in_pixels.set_origin(gfx::Point(0, 0));
}
AsWindowTreeHost()->SetBoundsInPixels(bounds_in_pixels);
}
////////////////////////////////////////////////////////////////////////////////
// DesktopWindowTreeHostWin, private:
Widget* DesktopWindowTreeHostWin::GetWidget() {
return native_widget_delegate_ ? native_widget_delegate_->AsWidget()
: nullptr;
}
const Widget* DesktopWindowTreeHostWin::GetWidget() const {
return native_widget_delegate_ ? native_widget_delegate_->AsWidget()
: nullptr;
}
HWND DesktopWindowTreeHostWin::GetHWND() const {
return message_handler_->hwnd();
}
bool DesktopWindowTreeHostWin::IsModalWindowActive() const {
// This function can get called during window creation which occurs before
// dispatcher() has been created.
if (!dispatcher())
return false;
const auto is_active = [](const auto* child) {
return child->GetProperty(aura::client::kModalKey) != ui::MODAL_TYPE_NONE &&
child->TargetVisibility();
};
return base::ranges::any_of(window()->children(), is_active);
}
void DesktopWindowTreeHostWin::CheckForMonitorChange() {
HMONITOR monitor_from_window =
::MonitorFromWindow(GetHWND(), MONITOR_DEFAULTTOPRIMARY);
if (monitor_from_window == last_monitor_from_window_)
return;
last_monitor_from_window_ = monitor_from_window;
OnHostDisplayChanged();
}
aura::Window* DesktopWindowTreeHostWin::content_window() {
return desktop_native_widget_aura_->content_window();
}
////////////////////////////////////////////////////////////////////////////////
// DesktopWindowTreeHost, public:
// static
DesktopWindowTreeHost* DesktopWindowTreeHost::Create(
internal::NativeWidgetDelegate* native_widget_delegate,
DesktopNativeWidgetAura* desktop_native_widget_aura) {
return new DesktopWindowTreeHostWin(native_widget_delegate,
desktop_native_widget_aura);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_window_tree_host_win.cc | C++ | unknown | 47,194 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_WINDOW_TREE_HOST_WIN_H_
#define UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_WINDOW_TREE_HOST_WIN_H_
#include <memory>
#include <string>
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "ui/aura/window_tree_host.h"
#include "ui/views/views_export.h"
#include "ui/views/widget/desktop_aura/desktop_window_tree_host.h"
#include "ui/views/win/hwnd_message_handler_delegate.h"
#include "ui/wm/public/animation_host.h"
namespace aura {
namespace client {
class DragDropClient;
class FocusClient;
} // namespace client
} // namespace aura
namespace ui {
enum class DomCode;
class InputMethod;
class KeyboardHook;
} // namespace ui
namespace wm {
class ScopedTooltipDisabler;
} // namespace wm
namespace views {
class DesktopDragDropClientWin;
class HWNDMessageHandler;
class NonClientFrameView;
namespace test {
class DesktopWindowTreeHostWinTestApi;
}
class VIEWS_EXPORT DesktopWindowTreeHostWin
: public DesktopWindowTreeHost,
public wm::AnimationHost,
public aura::WindowTreeHost,
public HWNDMessageHandlerDelegate {
public:
DesktopWindowTreeHostWin(
internal::NativeWidgetDelegate* native_widget_delegate,
DesktopNativeWidgetAura* desktop_native_widget_aura);
DesktopWindowTreeHostWin(const DesktopWindowTreeHostWin&) = delete;
DesktopWindowTreeHostWin& operator=(const DesktopWindowTreeHostWin&) = delete;
~DesktopWindowTreeHostWin() override;
// A way of converting an HWND into a content window.
static aura::Window* GetContentWindowForHWND(HWND hwnd);
// When DesktopDragDropClientWin starts a touch-initiated drag, it calls
// this method to record that we're in touch drag mode, and synthesizes
// right mouse button down and move events to get ::DoDragDrop started.
void StartTouchDrag(gfx::Point screen_point);
// If in touch drag mode, this method synthesizes a left mouse button up
// event to match the left mouse button down event in StartTouchDrag. It
// also restores the cursor pos to where the drag started, to avoid leaving
// the cursor outside the Chrome window doing the drag drop. This allows
// subsequent touch drag drops to succeed. Touch drag drop requires that
// the cursor be over the same window as the touch drag point.
// This needs to be called in two cases:
// 1. The normal case is that ::DoDragDrop starts, we get touch move events,
// which we turn into mouse move events, and then we get a touch release
// event. Calling FinishTouchDragIfInDrag generates a mouse up, which stops
// the drag drop.
// 2. ::DoDragDrop exits immediately, w/o us handling any touch events. In
// this case, FinishTouchDragIfInDrag makes sure we have a mouse button up to
// match the mouse button down, because we won't get a touch release event. We
// don't know for sure if ::DoDragDrop exited immediately, other than by
// checking if `in_touch_drag_` has been set to false.
//
// So, we always call FinishTouchDragIfInDrag after ::DoDragDrop exits, to
// make sure it gets called, and we make it handle getting called multiple
// times. Most of the time, FinishTouchDrag will have already been called when
// we get a touch release event, in which case the second call needs to be a
// noop, which is accomplished by checking if `in_touch_drag_` is already
// false.
void FinishTouchDrag(gfx::Point screen_point);
protected:
// Overridden from DesktopWindowTreeHost:
void Init(const Widget::InitParams& params) override;
void OnNativeWidgetCreated(const Widget::InitParams& params) override;
void OnActiveWindowChanged(bool active) override;
void OnWidgetInitDone() override;
std::unique_ptr<corewm::Tooltip> CreateTooltip() override;
std::unique_ptr<aura::client::DragDropClient> CreateDragDropClient() override;
void Close() override;
void CloseNow() override;
aura::WindowTreeHost* AsWindowTreeHost() override;
void Show(ui::WindowShowState show_state,
const gfx::Rect& restore_bounds) override;
bool IsVisible() const override;
void SetSize(const gfx::Size& size) override;
void StackAbove(aura::Window* window) override;
void StackAtTop() override;
bool IsStackedAbove(aura::Window* window) override;
void CenterWindow(const gfx::Size& size) override;
void GetWindowPlacement(gfx::Rect* bounds,
ui::WindowShowState* show_state) const override;
gfx::Rect GetWindowBoundsInScreen() const override;
gfx::Rect GetClientAreaBoundsInScreen() const override;
gfx::Rect GetRestoredBounds() const override;
std::string GetWorkspace() const override;
gfx::Rect GetWorkAreaBoundsInScreen() const override;
void SetShape(std::unique_ptr<Widget::ShapeRects> native_shape) override;
void Activate() override;
void Deactivate() override;
bool IsActive() const override;
void PaintAsActiveChanged() override;
void Maximize() override;
void Minimize() override;
void Restore() override;
bool IsMaximized() const override;
bool IsMinimized() const override;
bool HasCapture() const override;
void SetZOrderLevel(ui::ZOrderLevel order) override;
ui::ZOrderLevel GetZOrderLevel() const override;
void SetVisibleOnAllWorkspaces(bool always_visible) override;
bool IsVisibleOnAllWorkspaces() const override;
bool SetWindowTitle(const std::u16string& title) override;
void ClearNativeFocus() override;
Widget::MoveLoopResult RunMoveLoop(
const gfx::Vector2d& drag_offset,
Widget::MoveLoopSource source,
Widget::MoveLoopEscapeBehavior escape_behavior) override;
void EndMoveLoop() override;
void SetVisibilityChangedAnimationsEnabled(bool value) override;
std::unique_ptr<NonClientFrameView> CreateNonClientFrameView() override;
bool ShouldUseNativeFrame() const override;
bool ShouldWindowContentsBeTransparent() const override;
void FrameTypeChanged() override;
void SetFullscreen(bool fullscreen, int64_t target_display_id) override;
bool IsFullscreen() const override;
void SetOpacity(float opacity) override;
void SetAspectRatio(const gfx::SizeF& aspect_ratio,
const gfx::Size& excluded_margin) override;
void SetWindowIcons(const gfx::ImageSkia& window_icon,
const gfx::ImageSkia& app_icon) override;
void InitModalType(ui::ModalType modal_type) override;
void FlashFrame(bool flash_frame) override;
bool IsAnimatingClosed() const override;
bool IsTranslucentWindowOpacitySupported() const override;
void SizeConstraintsChanged() override;
bool ShouldUpdateWindowTransparency() const override;
bool ShouldUseDesktopNativeCursorManager() const override;
bool ShouldCreateVisibilityController() const override;
DesktopNativeCursorManager* GetSingletonDesktopNativeCursorManager() override;
void SetBoundsInDIP(const gfx::Rect& bounds) override;
// Overridden from aura::WindowTreeHost:
ui::EventSource* GetEventSource() override;
gfx::AcceleratedWidget GetAcceleratedWidget() override;
void ShowImpl() override;
void HideImpl() override;
gfx::Rect GetBoundsInPixels() const override;
void SetBoundsInPixels(const gfx::Rect& bounds) override;
gfx::Rect GetBoundsInAcceleratedWidgetPixelCoordinates() override;
gfx::Point GetLocationOnScreenInPixels() const override;
void SetCapture() override;
void ReleaseCapture() override;
bool CaptureSystemKeyEventsImpl(
absl::optional<base::flat_set<ui::DomCode>> dom_codes) override;
void ReleaseSystemKeyEventCapture() override;
bool IsKeyLocked(ui::DomCode dom_code) override;
base::flat_map<std::string, std::string> GetKeyboardLayoutMap() override;
void SetCursorNative(gfx::NativeCursor cursor) override;
void OnCursorVisibilityChangedNative(bool show) override;
void MoveCursorToScreenLocationInPixels(
const gfx::Point& location_in_pixels) override;
std::unique_ptr<aura::ScopedEnableUnadjustedMouseEvents>
RequestUnadjustedMovement() override;
void LockMouse(aura::Window* window) override;
void UnlockMouse(aura::Window* window) override;
// Overridden from aura::client::AnimationHost
void SetHostTransitionOffsets(
const gfx::Vector2d& top_left_delta,
const gfx::Vector2d& bottom_right_delta) override;
void OnWindowHidingAnimationCompleted() override;
// Overridden from HWNDMessageHandlerDelegate:
ui::InputMethod* GetHWNDMessageDelegateInputMethod() override;
bool HasNonClientView() const override;
FrameMode GetFrameMode() const override;
bool HasFrame() const override;
void SchedulePaint() override;
bool ShouldPaintAsActive() const override;
bool CanResize() const override;
bool CanMaximize() const override;
bool CanMinimize() const override;
bool CanActivate() const override;
bool WantsMouseEventsWhenInactive() const override;
bool WidgetSizeIsClientSize() const override;
bool IsModal() const override;
int GetInitialShowState() const override;
int GetNonClientComponent(const gfx::Point& point) const override;
void GetWindowMask(const gfx::Size& size, SkPath* path) override;
bool GetClientAreaInsets(gfx::Insets* insets,
HMONITOR monitor) const override;
bool GetDwmFrameInsetsInPixels(gfx::Insets* insets) const override;
void GetMinMaxSize(gfx::Size* min_size, gfx::Size* max_size) const override;
gfx::Size GetRootViewSize() const override;
gfx::Size DIPToScreenSize(const gfx::Size& dip_size) const override;
void ResetWindowControls() override;
gfx::NativeViewAccessible GetNativeViewAccessible() override;
void HandleActivationChanged(bool active) override;
bool HandleAppCommand(int command) override;
void HandleCancelMode() override;
void HandleCaptureLost() override;
void HandleClose() override;
bool HandleCommand(int command) override;
void HandleAccelerator(const ui::Accelerator& accelerator) override;
void HandleCreate() override;
void HandleDestroying() override;
void HandleDestroyed() override;
bool HandleInitialFocus(ui::WindowShowState show_state) override;
void HandleDisplayChange() override;
void HandleBeginWMSizeMove() override;
void HandleEndWMSizeMove() override;
void HandleMove() override;
void HandleWorkAreaChanged() override;
void HandleVisibilityChanged(bool visible) override;
void HandleWindowMinimizedOrRestored(bool restored) override;
void HandleClientSizeChanged(const gfx::Size& new_size) override;
void HandleFrameChanged() override;
void HandleNativeFocus(HWND last_focused_window) override;
void HandleNativeBlur(HWND focused_window) override;
bool HandleMouseEvent(ui::MouseEvent* event) override;
void HandleKeyEvent(ui::KeyEvent* event) override;
void HandleTouchEvent(ui::TouchEvent* event) override;
bool HandleIMEMessage(UINT message,
WPARAM w_param,
LPARAM l_param,
LRESULT* result) override;
void HandleInputLanguageChange(DWORD character_set,
HKL input_language_id) override;
void HandlePaintAccelerated(const gfx::Rect& invalid_rect) override;
void HandleMenuLoop(bool in_menu_loop) override;
bool PreHandleMSG(UINT message,
WPARAM w_param,
LPARAM l_param,
LRESULT* result) override;
void PostHandleMSG(UINT message, WPARAM w_param, LPARAM l_param) override;
bool HandleScrollEvent(ui::ScrollEvent* event) override;
bool HandleGestureEvent(ui::GestureEvent* event) override;
void HandleWindowSizeChanging() override;
void HandleWindowSizeUnchanged() override;
void HandleWindowScaleFactorChanged(float window_scale_factor) override;
void HandleHeadlessWindowBoundsChanged(const gfx::Rect& bounds) override;
Widget* GetWidget();
const Widget* GetWidget() const;
HWND GetHWND() const;
private:
friend class ::views::test::DesktopWindowTreeHostWinTestApi;
// Returns true if a modal window is active in the current root window chain.
bool IsModalWindowActive() const;
// Called whenever the HWND resizes or moves, to see if the nearest HMONITOR
// has changed, and, if so, inform the aura::WindowTreeHost.
void CheckForMonitorChange();
// Accessor for DesktopNativeWidgetAura::content_window().
aura::Window* content_window();
HMONITOR last_monitor_from_window_ = nullptr;
std::unique_ptr<HWNDMessageHandler> message_handler_;
std::unique_ptr<aura::client::FocusClient> focus_client_;
// TODO(beng): Consider providing an interface to DesktopNativeWidgetAura
// instead of providing this route back to Widget.
base::WeakPtr<internal::NativeWidgetDelegate> native_widget_delegate_;
raw_ptr<DesktopNativeWidgetAura> desktop_native_widget_aura_;
// Owned by DesktopNativeWidgetAura.
base::WeakPtr<DesktopDragDropClientWin> drag_drop_client_;
// When certain windows are being shown, we augment the window size
// temporarily for animation. The following two members contain the top left
// and bottom right offsets which are used to enlarge the window.
gfx::Vector2d window_expansion_top_left_delta_;
gfx::Vector2d window_expansion_bottom_right_delta_;
// Windows are enlarged to be at least 64x64 pixels, so keep track of the
// extra added here.
gfx::Vector2d window_enlargement_;
// Whether the window close should be converted to a hide, and then actually
// closed on the completion of the hide animation. This is cached because
// the property is set on the contained window which has a shorter lifetime.
bool should_animate_window_close_;
// When Close()d and animations are being applied to this window, the close
// of the window needs to be deferred to when the close animation is
// completed. This variable indicates that a Close was converted to a Hide,
// so that when the Hide is completed the host window should be closed.
bool pending_close_;
// True if the widget is going to have a non_client_view. We cache this value
// rather than asking the Widget for the non_client_view so that we know at
// Init time, before the Widget has created the NonClientView.
bool has_non_client_view_;
// True if the window should have the frame removed.
bool remove_standard_frame_;
// True if the widget has a external parent view/window outside of the
// Chromium-controlled view/window hierarchy.
bool has_external_parent_ = false;
// Visibility of the cursor. On Windows we can have multiple root windows and
// the implementation of ::ShowCursor() is based on a counter, so making this
// member static ensures that ::ShowCursor() is always called exactly once
// whenever the cursor visibility state changes.
static bool is_cursor_visible_;
// Captures system key events when keyboard lock is requested.
std::unique_ptr<ui::KeyboardHook> keyboard_hook_;
std::unique_ptr<wm::ScopedTooltipDisabler> tooltip_disabler_;
// Indicates if current window will receive mouse events when should not
// become activated.
bool wants_mouse_events_when_inactive_ = false;
// Set to true when DesktopDragDropClientWin starts a touch-initiated drag
// drop and false when it finishes. While in touch drag, if touch move events
// are received, the equivalent mouse events are generated, because ole32
// ::DoDragDrop does not seem to handle touch events. WinRT drag drop does
// support touch, but we've been unable to use it in Chrome. See
// https://crbug.com/1236783 for more info.
bool in_touch_drag_ = false;
// The z-order level of the window; the window exhibits "always on top"
// behavior if > 0.
ui::ZOrderLevel z_order_ = ui::ZOrderLevel::kNormal;
};
} // namespace views
#endif // UI_VIEWS_WIDGET_DESKTOP_AURA_DESKTOP_WINDOW_TREE_HOST_WIN_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_window_tree_host_win.h | C++ | unknown | 15,888 |
// 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/widget/desktop_aura/desktop_window_tree_host_win.h"
#include <oleacc.h>
#include <windows.h>
#include <utility>
#include "base/command_line.h"
#include "ui/accessibility/accessibility_switches.h"
#include "ui/accessibility/platform/ax_platform_node_win.h"
#include "ui/accessibility/platform/ax_system_caret_win.h"
#include "ui/views/test/desktop_window_tree_host_win_test_api.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/win/hwnd_message_handler.h"
namespace views {
namespace test {
using DesktopWindowTreeHostWinTest = DesktopWidgetTest;
TEST_F(DesktopWindowTreeHostWinTest, DebuggingId) {
Widget widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
constexpr char kDebuggingName[] = "test-debugging-id";
params.name = kDebuggingName;
widget.Init(std::move(params));
DesktopWindowTreeHostWin* desktop_window_tree_host =
static_cast<DesktopWindowTreeHostWin*>(
widget.GetNativeWindow()->GetHost());
EXPECT_EQ(std::string(kDebuggingName),
DesktopWindowTreeHostWinTestApi(desktop_window_tree_host)
.GetHwndMessageHandler()
->debugging_id());
}
class DesktopWindowTreeHostWinAccessibilityObjectTest
: public DesktopWidgetTest {
public:
DesktopWindowTreeHostWinAccessibilityObjectTest() = default;
DesktopWindowTreeHostWinAccessibilityObjectTest(
const DesktopWindowTreeHostWinAccessibilityObjectTest&) = delete;
DesktopWindowTreeHostWinAccessibilityObjectTest& operator=(
const DesktopWindowTreeHostWinAccessibilityObjectTest&) = delete;
~DesktopWindowTreeHostWinAccessibilityObjectTest() override = default;
protected:
void CacheRootNode(const Widget& widget) {
DesktopWindowTreeHostWinTestApi host(static_cast<DesktopWindowTreeHostWin*>(
widget.GetNativeWindow()->GetHost()));
host.GetNativeViewAccessible()->QueryInterface(IID_PPV_ARGS(&test_node_));
}
void CacheCaretNode(const Widget& widget) {
DesktopWindowTreeHostWinTestApi host(static_cast<DesktopWindowTreeHostWin*>(
widget.GetNativeWindow()->GetHost()));
host.EnsureAXSystemCaretCreated();
host.GetAXSystemCaret()->GetCaret()->QueryInterface(
IID_PPV_ARGS(&test_node_));
}
Microsoft::WRL::ComPtr<ui::AXPlatformNodeWin> test_node_;
};
// This test validates that we do not leak the root accessibility object when
// handing it out.
TEST_F(DesktopWindowTreeHostWinAccessibilityObjectTest, RootDoesNotLeak) {
{
Widget widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget.Init(std::move(params));
widget.Show();
// Cache a pointer to the object we return to Windows.
CacheRootNode(widget);
// Repeatedly call the public API to obtain an accessibility object. If our
// code is leaking references, this will drive up the reference count.
HWND hwnd = widget.GetNativeWindow()->GetHost()->GetAcceleratedWidget();
for (int i = 0; i < 10; i++) {
Microsoft::WRL::ComPtr<IAccessible> root_accessible;
EXPECT_HRESULT_SUCCEEDED(::AccessibleObjectFromWindow(
hwnd, OBJID_CLIENT, IID_PPV_ARGS(&root_accessible)));
EXPECT_NE(root_accessible.Get(), nullptr);
}
// Close the widget and destroy it by letting it go out of scope.
widget.CloseNow();
}
// At this point our test reference should be the only one remaining.
EXPECT_EQ(test_node_->m_dwRef, 1);
}
// This test validates that we do not leak the caret accessibility object when
// handing it out.
TEST_F(DesktopWindowTreeHostWinAccessibilityObjectTest, CaretDoesNotLeak) {
{
Widget widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget.Init(std::move(params));
widget.Show();
// Cache a pointer to the object we return to Windows.
CacheCaretNode(widget);
// Repeatedly call the public API to obtain an accessibility object. If our
// code is leaking references, this will drive up the reference count.
HWND hwnd = widget.GetNativeWindow()->GetHost()->GetAcceleratedWidget();
for (int i = 0; i < 10; i++) {
Microsoft::WRL::ComPtr<IAccessible> caret_accessible;
EXPECT_HRESULT_SUCCEEDED(::AccessibleObjectFromWindow(
hwnd, OBJID_CARET, IID_PPV_ARGS(&caret_accessible)));
EXPECT_NE(caret_accessible.Get(), nullptr);
}
// Close the widget and destroy it by letting it go out of scope.
widget.CloseNow();
}
// At this point our test reference should be the only one remaining.
EXPECT_EQ(test_node_->m_dwRef, 1);
}
// This test validates that we do not leak the root accessibility object when
// handing it out (UIA mode).
TEST_F(DesktopWindowTreeHostWinAccessibilityObjectTest, UiaRootDoesNotLeak) {
base::CommandLine::ForCurrentProcess()->AppendSwitch(
::switches::kEnableExperimentalUIAutomation);
{
Widget widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget.Init(std::move(params));
widget.Show();
// Cache a pointer to the object we return to Windows.
CacheRootNode(widget);
// Repeatedly call the public API to obtain an accessibility object. If our
// code is leaking references, this will drive up the reference count.
Microsoft::WRL::ComPtr<IUIAutomation> uia;
ASSERT_HRESULT_SUCCEEDED(CoCreateInstance(CLSID_CUIAutomation, nullptr,
CLSCTX_INPROC_SERVER,
IID_IUIAutomation, &uia));
HWND hwnd = widget.GetNativeWindow()->GetHost()->GetAcceleratedWidget();
for (int i = 0; i < 10; i++) {
Microsoft::WRL::ComPtr<IUIAutomationElement> root_element;
EXPECT_HRESULT_SUCCEEDED(uia->ElementFromHandle(hwnd, &root_element));
EXPECT_NE(root_element.Get(), nullptr);
// Raise an event on the root node. This will cause UIA to cache a pointer
// to it.
::UiaRaiseStructureChangedEvent(test_node_.Get(),
StructureChangeType_ChildrenInvalidated,
nullptr, 0);
}
// Close the widget and destroy it by letting it go out of scope.
widget.CloseNow();
}
// At this point our test reference should be the only one remaining.
EXPECT_EQ(test_node_->m_dwRef, 1);
}
} // namespace test
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/desktop_window_tree_host_win_unittest.cc | C++ | unknown | 6,826 |
// 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/widget/desktop_aura/window_event_filter_lacros.h"
#include "ui/aura/client/aura_constants.h"
#include "ui/aura/window.h"
#include "ui/aura/window_delegate.h"
#include "ui/aura/window_tree_host.h"
#include "ui/base/hit_test.h"
#include "ui/events/event.h"
#include "ui/events/event_utils.h"
#include "ui/platform_window/wm/wm_move_resize_handler.h"
#include "ui/views/widget/desktop_aura/desktop_window_tree_host_platform.h"
#include "ui/views/widget/widget.h"
namespace views {
WindowEventFilterLacros::WindowEventFilterLacros(
DesktopWindowTreeHostPlatform* desktop_window_tree_host,
ui::WmMoveResizeHandler* handler)
: desktop_window_tree_host_(desktop_window_tree_host), handler_(handler) {
desktop_window_tree_host_->window()->AddPreTargetHandler(this);
}
WindowEventFilterLacros::~WindowEventFilterLacros() {
desktop_window_tree_host_->window()->RemovePreTargetHandler(this);
}
void WindowEventFilterLacros::OnMouseEvent(ui::MouseEvent* event) {
if (event->type() != ui::ET_MOUSE_PRESSED ||
!event->IsOnlyLeftMouseButton()) {
return;
}
auto* window = static_cast<aura::Window*>(event->target());
int component =
window->delegate()
? window->delegate()->GetNonClientComponent(event->location())
: HTNOWHERE;
if (event->flags() & ui::EF_IS_DOUBLE_CLICK) {
if (previous_pressed_component_ == HTCAPTION && component == HTCAPTION) {
MaybeToggleMaximizedState(window);
previous_pressed_component_ = HTNOWHERE;
event->SetHandled();
}
return;
}
previous_pressed_component_ = component;
MaybeDispatchHostWindowDragMovement(component, event);
}
void WindowEventFilterLacros::OnGestureEvent(ui::GestureEvent* event) {
auto* window = static_cast<aura::Window*>(event->target());
int component =
window->delegate()
? window->delegate()->GetNonClientComponent(event->location())
: HTNOWHERE;
// Double tap to maximize.
if (event->type() == ui::ET_GESTURE_TAP) {
int previous_pressed_component = previous_pressed_component_;
previous_pressed_component_ = component;
if (previous_pressed_component_ == HTCAPTION &&
previous_pressed_component == HTCAPTION &&
event->details().tap_count() == 2) {
MaybeToggleMaximizedState(window);
previous_pressed_component_ = HTNOWHERE;
event->SetHandled();
}
return;
}
// Interactive window move.
if (event->type() == ui::ET_GESTURE_SCROLL_BEGIN)
MaybeDispatchHostWindowDragMovement(component, event);
}
void WindowEventFilterLacros::MaybeToggleMaximizedState(aura::Window* window) {
if (!(window->GetProperty(aura::client::kResizeBehaviorKey) &
aura::client::kResizeBehaviorCanMaximize)) {
return;
}
// TODO(crbug.com/1299310): send toggle event to ash-chrome.
if (desktop_window_tree_host_->IsMaximized())
desktop_window_tree_host_->Restore();
else
desktop_window_tree_host_->Maximize();
}
void WindowEventFilterLacros::MaybeDispatchHostWindowDragMovement(
int component,
ui::LocatedEvent* event) {
if (!handler_ || !ui::CanPerformDragOrResize(component))
return;
// The location argument is not used in lacros as the drag and resize
// are handled by the compositor (ash-chrome).
handler_->DispatchHostWindowDragMovement(component, gfx::Point());
// Stop the event propagation for mouse events only (not touch), given that
// it'd prevent the Gesture{Provider,Detector} machirery to get triggered,
// breaking gestures including tapping, double tapping, show press and
// long press.
if (event->IsMouseEvent())
event->StopPropagation();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/window_event_filter_lacros.cc | C++ | unknown | 3,828 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_WIDGET_DESKTOP_AURA_WINDOW_EVENT_FILTER_LACROS_H_
#define UI_VIEWS_WIDGET_DESKTOP_AURA_WINDOW_EVENT_FILTER_LACROS_H_
#include "base/memory/raw_ptr.h"
#include "ui/base/hit_test.h"
#include "ui/events/event_handler.h"
#include "ui/views/views_export.h"
namespace aura {
class Window;
} // namespace aura
namespace ui {
class GestureEvent;
class MouseEvent;
class LocatedEvent;
class WmMoveResizeHandler;
} // namespace ui
namespace views {
class DesktopWindowTreeHostPlatform;
// An EventFilter that sets properties on native windows. Uses
// WmMoveResizeHandler to dispatch move/resize requests.
class VIEWS_EXPORT WindowEventFilterLacros : public ui::EventHandler {
public:
WindowEventFilterLacros(
DesktopWindowTreeHostPlatform* desktop_window_tree_host,
ui::WmMoveResizeHandler* handler);
WindowEventFilterLacros(const WindowEventFilterLacros&) = delete;
WindowEventFilterLacros& operator=(const WindowEventFilterLacros&) = delete;
~WindowEventFilterLacros() override;
void OnGestureEvent(ui::GestureEvent* event) override;
void OnMouseEvent(ui::MouseEvent* event) override;
private:
void MaybeToggleMaximizedState(aura::Window* window);
// Dispatches a message to the window manager to tell it to act as if a border
// or titlebar drag occurred with left mouse click. In case of X11, a
// _NET_WM_MOVERESIZE message is sent.
void MaybeDispatchHostWindowDragMovement(int hittest,
ui::LocatedEvent* event);
const raw_ptr<DesktopWindowTreeHostPlatform> desktop_window_tree_host_;
int previous_pressed_component_ = HTNOWHERE;
// A handler, which is used for interactive move/resize events if set and
// unless MaybeDispatchHostWindowDragMovement is overridden by a derived
// class.
const raw_ptr<ui::WmMoveResizeHandler> handler_;
};
} // namespace views
#endif // UI_VIEWS_WIDGET_DESKTOP_AURA_WINDOW_EVENT_FILTER_LACROS_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/window_event_filter_lacros.h | C++ | unknown | 2,097 |
// 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/widget/desktop_aura/window_event_filter_linux.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/aura/client/aura_constants.h"
#include "ui/aura/env.h"
#include "ui/aura/window.h"
#include "ui/aura/window_delegate.h"
#include "ui/aura/window_tree_host.h"
#include "ui/base/hit_test.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/events/event.h"
#include "ui/events/event_utils.h"
#include "ui/linux/linux_ui.h"
#include "ui/platform_window/wm/wm_move_resize_handler.h"
#include "ui/views/widget/desktop_aura/desktop_window_tree_host_platform.h"
#include "ui/views/widget/native_widget_aura.h"
#include "ui/views/widget/widget.h"
namespace views {
WindowEventFilterLinux::WindowEventFilterLinux(
DesktopWindowTreeHostPlatform* desktop_window_tree_host,
ui::WmMoveResizeHandler* handler)
: desktop_window_tree_host_(desktop_window_tree_host), handler_(handler) {
desktop_window_tree_host_->window()->AddPreTargetHandler(this);
}
WindowEventFilterLinux::~WindowEventFilterLinux() {
desktop_window_tree_host_->window()->RemovePreTargetHandler(this);
}
void WindowEventFilterLinux::HandleLocatedEventWithHitTest(
int hit_test,
ui::LocatedEvent* event) {
if (event->type() != ui::ET_MOUSE_PRESSED)
return;
if (event->IsMouseEvent() &&
HandleMouseEventWithHitTest(hit_test, event->AsMouseEvent())) {
return;
}
if (desktop_window_tree_host_->GetContentWindow()->GetProperty(
aura::client::kResizeBehaviorKey) &
aura::client::kResizeBehaviorCanResize) {
MaybeDispatchHostWindowDragMovement(hit_test, event);
}
}
bool WindowEventFilterLinux::HandleMouseEventWithHitTest(
int hit_test,
ui::MouseEvent* event) {
int previous_click_component = HTNOWHERE;
if (event->IsLeftMouseButton()) {
previous_click_component = click_component_;
click_component_ = hit_test;
}
if (hit_test == HTCAPTION) {
OnClickedCaption(event, previous_click_component);
return true;
}
if (hit_test == HTMAXBUTTON) {
OnClickedMaximizeButton(event);
return true;
}
return false;
}
void WindowEventFilterLinux::OnClickedCaption(ui::MouseEvent* event,
int previous_click_component) {
ui::LinuxUi::WindowFrameActionSource action_type;
ui::LinuxUi::WindowFrameAction default_action;
if (event->IsRightMouseButton()) {
action_type = ui::LinuxUi::WindowFrameActionSource::kRightClick;
default_action = ui::LinuxUi::WindowFrameAction::kMenu;
} else if (event->IsMiddleMouseButton()) {
action_type = ui::LinuxUi::WindowFrameActionSource::kMiddleClick;
default_action = ui::LinuxUi::WindowFrameAction::kNone;
} else if (event->IsLeftMouseButton() &&
event->flags() & ui::EF_IS_DOUBLE_CLICK) {
click_component_ = HTNOWHERE;
if (previous_click_component == HTCAPTION) {
action_type = ui::LinuxUi::WindowFrameActionSource::kDoubleClick;
default_action = ui::LinuxUi::WindowFrameAction::kToggleMaximize;
} else {
return;
}
} else {
MaybeDispatchHostWindowDragMovement(HTCAPTION, event);
return;
}
auto* content_window = desktop_window_tree_host_->GetContentWindow();
auto* linux_ui_theme = ui::LinuxUi::instance();
ui::LinuxUi::WindowFrameAction action =
linux_ui_theme ? linux_ui_theme->GetWindowFrameAction(action_type)
: default_action;
switch (action) {
case ui::LinuxUi::WindowFrameAction::kNone:
break;
case ui::LinuxUi::WindowFrameAction::kLower:
LowerWindow();
event->SetHandled();
break;
case ui::LinuxUi::WindowFrameAction::kMinimize:
desktop_window_tree_host_->Minimize();
event->SetHandled();
break;
case ui::LinuxUi::WindowFrameAction::kToggleMaximize:
MaybeToggleMaximizedState(content_window);
event->SetHandled();
break;
case ui::LinuxUi::WindowFrameAction::kMenu:
views::Widget* widget =
views::Widget::GetWidgetForNativeView(content_window);
if (!widget)
break;
views::View* view = widget->GetContentsView();
if (!view || !view->context_menu_controller())
break;
// Controller requires locations to be in DIP, while |this| receives the
// location in px.
gfx::PointF location = desktop_window_tree_host_->GetRootTransform()
.InverseMapPoint(event->location_f())
.value_or(event->location_f());
gfx::Point location_in_screen = gfx::ToRoundedPoint(location);
views::View::ConvertPointToScreen(view, &location_in_screen);
view->ShowContextMenu(location_in_screen, ui::MENU_SOURCE_MOUSE);
event->SetHandled();
break;
}
}
void WindowEventFilterLinux::OnClickedMaximizeButton(ui::MouseEvent* event) {
auto* content_window = desktop_window_tree_host_->GetContentWindow();
views::Widget* widget = views::Widget::GetWidgetForNativeView(content_window);
if (!widget)
return;
gfx::Rect display_work_area = display::Screen::GetScreen()
->GetDisplayNearestWindow(content_window)
.work_area();
gfx::Rect bounds = widget->GetWindowBoundsInScreen();
if (event->IsMiddleMouseButton()) {
bounds.set_y(display_work_area.y());
bounds.set_height(display_work_area.height());
widget->SetBounds(bounds);
event->StopPropagation();
} else if (event->IsRightMouseButton()) {
bounds.set_x(display_work_area.x());
bounds.set_width(display_work_area.width());
widget->SetBounds(bounds);
event->StopPropagation();
}
}
void WindowEventFilterLinux::MaybeToggleMaximizedState(aura::Window* window) {
if (!(window->GetProperty(aura::client::kResizeBehaviorKey) &
aura::client::kResizeBehaviorCanMaximize)) {
return;
}
if (desktop_window_tree_host_->IsMaximized())
desktop_window_tree_host_->Restore();
else
desktop_window_tree_host_->Maximize();
}
void WindowEventFilterLinux::LowerWindow() {
#if BUILDFLAG(OZONE_PLATFORM_X11)
desktop_window_tree_host_->LowerWindow();
#endif
}
void WindowEventFilterLinux::MaybeDispatchHostWindowDragMovement(
int hittest,
ui::LocatedEvent* event) {
if (!event->IsMouseEvent() && !event->IsGestureEvent())
return;
if (event->IsMouseEvent() && !event->AsMouseEvent()->IsLeftMouseButton())
return;
if (!handler_ || !ui::CanPerformDragOrResize(hittest))
return;
// Some platforms (eg X11) may require last pointer location not in the
// local surface coordinates, but rather in the screen coordinates for
// interactive move/resize.
auto bounds_in_px =
desktop_window_tree_host_->AsWindowTreeHost()->GetBoundsInPixels();
auto screen_point_in_px = event->location();
screen_point_in_px.Offset(bounds_in_px.x(), bounds_in_px.y());
handler_->DispatchHostWindowDragMovement(hittest, screen_point_in_px);
// Stop the event propagation for mouse events only (not touch), given that
// it'd prevent the Gesture{Provider,Detector} machirery to get triggered,
// breaking gestures including tapping, double tapping, show press and
// long press.
if (event->IsMouseEvent())
event->StopPropagation();
}
void WindowEventFilterLinux::OnGestureEvent(ui::GestureEvent* event) {
auto* window = static_cast<aura::Window*>(event->target());
int hit_test_code =
window->delegate()
? window->delegate()->GetNonClientComponent(event->location())
: HTNOWHERE;
// Double tap to maximize.
if (event->type() == ui::ET_GESTURE_TAP) {
int previous_click_component = click_component_;
click_component_ = hit_test_code;
if (click_component_ == HTCAPTION &&
click_component_ == previous_click_component &&
event->details().tap_count() == 2) {
MaybeToggleMaximizedState(window);
click_component_ = HTNOWHERE;
event->StopPropagation();
}
return;
}
// Interactive window move.
if (event->type() == ui::ET_GESTURE_SCROLL_BEGIN)
MaybeDispatchHostWindowDragMovement(hit_test_code, event);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/window_event_filter_linux.cc | C++ | unknown | 8,324 |
// 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_WIDGET_DESKTOP_AURA_WINDOW_EVENT_FILTER_LINUX_H_
#define UI_VIEWS_WIDGET_DESKTOP_AURA_WINDOW_EVENT_FILTER_LINUX_H_
#include "base/memory/raw_ptr.h"
#include "ui/base/hit_test.h"
#include "ui/events/event_handler.h"
#include "ui/views/views_export.h"
namespace aura {
class Window;
} // namespace aura
namespace ui {
class LocatedEvent;
class MouseEvent;
class WmMoveResizeHandler;
} // namespace ui
namespace views {
class DesktopWindowTreeHostPlatform;
// An EventFilter that sets properties on native windows. Uses
// WmMoveResizeHandler to dispatch move/resize requests.
class VIEWS_EXPORT WindowEventFilterLinux : public ui::EventHandler {
public:
WindowEventFilterLinux(
DesktopWindowTreeHostPlatform* desktop_window_tree_host,
ui::WmMoveResizeHandler* handler);
WindowEventFilterLinux(const WindowEventFilterLinux&) = delete;
WindowEventFilterLinux& operator=(const WindowEventFilterLinux&) = delete;
~WindowEventFilterLinux() override;
void HandleLocatedEventWithHitTest(int hit_test, ui::LocatedEvent* event);
private:
bool HandleMouseEventWithHitTest(int hit_test, ui::MouseEvent* event);
// Called when the user clicked the caption area.
void OnClickedCaption(ui::MouseEvent* event, int previous_click_component);
// Called when the user clicked the maximize button.
void OnClickedMaximizeButton(ui::MouseEvent* event);
void MaybeToggleMaximizedState(aura::Window* window);
// Dispatches a message to the window manager to tell it to act as if a border
// or titlebar drag occurred with left mouse click. In case of X11, a
// _NET_WM_MOVERESIZE message is sent.
void MaybeDispatchHostWindowDragMovement(int hittest,
ui::LocatedEvent* event);
// A signal to lower an attached to this filter window to the bottom of the
// stack.
void LowerWindow();
// ui::EventHandler overrides:
void OnGestureEvent(ui::GestureEvent* event) override;
const raw_ptr<DesktopWindowTreeHostPlatform> desktop_window_tree_host_;
// A handler, which is used for interactive move/resize events if set and
// unless MaybeDispatchHostWindowDragMovement is overridden by a derived
// class.
const raw_ptr<ui::WmMoveResizeHandler> handler_;
// The non-client component for the target of a MouseEvent. Mouse events can
// be destructive to the window tree, which can cause the component of a
// ui::EF_IS_DOUBLE_CLICK event to no longer be the same as that of the
// initial click. Acting on a double click should only occur for matching
// components.
int click_component_ = HTNOWHERE;
};
} // namespace views
#endif // UI_VIEWS_WIDGET_DESKTOP_AURA_WINDOW_EVENT_FILTER_LINUX_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/window_event_filter_linux.h | C++ | unknown | 2,864 |
// 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/widget/desktop_aura/window_move_client_platform.h"
#include "ui/views/widget/desktop_aura/desktop_window_tree_host_platform.h"
namespace views {
WindowMoveClientPlatform::WindowMoveClientPlatform(
DesktopWindowTreeHostPlatform* host)
: host_(host) {}
WindowMoveClientPlatform::~WindowMoveClientPlatform() = default;
wm::WindowMoveResult WindowMoveClientPlatform::RunMoveLoop(
aura::Window* source,
const gfx::Vector2d& drag_offset,
wm::WindowMoveSource move_source) {
DCHECK(host_->GetContentWindow()->Contains(source));
auto move_loop_result = host_->RunMoveLoop(
drag_offset,
move_source == wm::WindowMoveSource::WINDOW_MOVE_SOURCE_MOUSE
? Widget::MoveLoopSource::kMouse
: Widget::MoveLoopSource::kTouch,
Widget::MoveLoopEscapeBehavior::kHide);
return move_loop_result == Widget::MoveLoopResult::kSuccessful
? wm::MOVE_SUCCESSFUL
: wm::MOVE_CANCELED;
}
void WindowMoveClientPlatform::EndMoveLoop() {
host_->EndMoveLoop();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/window_move_client_platform.cc | C++ | unknown | 1,211 |
// 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_WIDGET_DESKTOP_AURA_WINDOW_MOVE_CLIENT_PLATFORM_H_
#define UI_VIEWS_WIDGET_DESKTOP_AURA_WINDOW_MOVE_CLIENT_PLATFORM_H_
#include "base/memory/raw_ptr.h"
#include "ui/views/views_export.h"
#include "ui/wm/public/window_move_client.h"
namespace views {
class DesktopWindowTreeHostPlatform;
// Reroutes move loop requests to DesktopWindowTreeHostPlatform.
class VIEWS_EXPORT WindowMoveClientPlatform : public wm::WindowMoveClient {
public:
explicit WindowMoveClientPlatform(DesktopWindowTreeHostPlatform* host);
WindowMoveClientPlatform(const WindowMoveClientPlatform& host) = delete;
WindowMoveClientPlatform& operator=(const WindowMoveClientPlatform& host) =
delete;
~WindowMoveClientPlatform() override;
// Overridden from wm::WindowMoveClient:
wm::WindowMoveResult RunMoveLoop(aura::Window* window,
const gfx::Vector2d& drag_offset,
wm::WindowMoveSource move_source) override;
void EndMoveLoop() override;
private:
// The RunMoveLoop request is forwarded to this host.
raw_ptr<DesktopWindowTreeHostPlatform> host_ = nullptr;
};
} // namespace views
#endif // UI_VIEWS_WIDGET_DESKTOP_AURA_WINDOW_MOVE_CLIENT_PLATFORM_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_aura/window_move_client_platform.h | C++ | unknown | 1,386 |
// 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/display/display.h"
#include "ui/display/screen.h"
#include "ui/views/test/native_widget_factory.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/dialog_delegate.h"
namespace views {
using DesktopScreenPositionClientTest = test::DesktopWidgetTest;
// Verifies setting the bounds of a dialog parented to a Widget with a
// PlatformDesktopNativeWidget is positioned correctly.
TEST_F(DesktopScreenPositionClientTest, PositionDialog) {
Widget parent_widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.bounds = gfx::Rect(10, 11, 200, 200);
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
parent_widget.Init(std::move(params));
// Owned by |dialog|.
DialogDelegateView* dialog_delegate_view = new DialogDelegateView;
// Owned by |parent_widget|.
Widget* dialog = DialogDelegate::CreateDialogWidget(
dialog_delegate_view, nullptr, parent_widget.GetNativeView());
dialog->SetBounds(gfx::Rect(11, 12, 200, 200));
EXPECT_EQ(gfx::Point(11, 12), dialog->GetWindowBoundsInScreen().origin());
}
// Verifies that setting the bounds of a control parented to something other
// than the root window is positioned correctly.
TEST_F(DesktopScreenPositionClientTest, PositionControlWithNonRootParent) {
Widget widget1;
Widget widget2;
Widget widget3;
gfx::Point origin = gfx::Point(16, 16);
gfx::Rect work_area =
display::Screen::GetScreen()->GetDisplayNearestPoint(origin).work_area();
// Use a custom frame type. By default we will choose a native frame when
// aero glass is enabled, and this complicates the logic surrounding origin
// computation, making it difficult to compute the expected origin location.
widget1.set_frame_type(Widget::FrameType::kForceCustom);
widget2.set_frame_type(Widget::FrameType::kForceCustom);
widget3.set_frame_type(Widget::FrameType::kForceCustom);
// Create 3 windows. A root window, an arbitrary window parented to the root
// but NOT positioned at (0,0) relative to the root, and then a third window
// parented to the second, also not positioned at (0,0).
Widget::InitParams params1 = CreateParams(Widget::InitParams::TYPE_WINDOW);
params1.bounds = gfx::Rect(
origin + work_area.OffsetFromOrigin(),
gfx::Size(700, work_area.height() - origin.y() - work_area.y()));
params1.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget1.Init(std::move(params1));
Widget::InitParams params2 = CreateParams(Widget::InitParams::TYPE_WINDOW);
params2.bounds = gfx::Rect(origin, gfx::Size(600, work_area.height() - 100));
params2.parent = widget1.GetNativeView();
params2.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params2.child = true;
params2.native_widget = test::CreatePlatformNativeWidgetImpl(
&widget2, test::kStubCapture, nullptr);
widget2.Init(std::move(params2));
Widget::InitParams params3 = CreateParams(Widget::InitParams::TYPE_CONTROL);
params3.parent = widget2.GetNativeView();
params3.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params3.child = true;
params3.bounds = gfx::Rect(origin, gfx::Size(500, work_area.height() - 200));
params3.native_widget = test::CreatePlatformNativeWidgetImpl(
&widget3, test::kStubCapture, nullptr);
widget3.Init(std::move(params3));
// The origin of the 3rd window should be the sum of all parent origins.
gfx::Point expected_origin(origin.x() * 3 + work_area.x(),
origin.y() * 3 + work_area.y());
gfx::Rect expected_bounds(expected_origin,
gfx::Size(500, work_area.height() - 200));
gfx::Rect actual_bounds(widget3.GetWindowBoundsInScreen());
EXPECT_EQ(expected_bounds, actual_bounds);
}
// Verifies that the initial bounds of the widget is fully on the screen.
TEST_F(DesktopScreenPositionClientTest, InitialBoundsConstrainedToDesktop) {
Widget widget;
// Use the primary display for this test.
gfx::Rect work_area =
display::Screen::GetScreen()->GetPrimaryDisplay().work_area();
// Make the origin start at 75% of the width and height.
gfx::Point origin =
gfx::Point(work_area.width() * 3 / 4, work_area.height() * 3 / 4);
// Use a custom frame type. See above for further explanation.
widget.set_frame_type(Widget::FrameType::kForceCustom);
// Create a window that is intentionally positioned so that it is off screen.
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.bounds = gfx::Rect(
origin, gfx::Size(work_area.width() / 2, work_area.height() / 2));
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget.Init(std::move(params));
// The bounds of the window should be fully on the primary display.
gfx::Point expected_origin(work_area.right() - work_area.width() / 2,
work_area.bottom() - work_area.height() / 2);
gfx::Rect expected_bounds(expected_origin, gfx::Size(work_area.width() / 2,
work_area.height() / 2));
gfx::Rect actual_bounds(widget.GetWindowBoundsInScreen());
EXPECT_EQ(expected_bounds, actual_bounds);
}
// Verifies that the initial bounds of the widget is fully within the bounds of
// the parent.
TEST_F(DesktopScreenPositionClientTest, InitialBoundsConstrainedToParent) {
Widget widget1;
Widget widget2;
// Use the primary display for this test.
gfx::Rect work_area =
display::Screen::GetScreen()->GetPrimaryDisplay().work_area();
gfx::Point origin = gfx::Point(work_area.x() + work_area.width() / 4,
work_area.y() + work_area.height() / 4);
// Use a custom frame type. See above for further explanation
widget1.set_frame_type(Widget::FrameType::kForceCustom);
widget2.set_frame_type(Widget::FrameType::kForceCustom);
// Create 2 windows. A root window, and an arbitrary window parented to the
// root and positioned such that it extends beyond the bounds of the root.
Widget::InitParams params1 = CreateParams(Widget::InitParams::TYPE_WINDOW);
params1.bounds = gfx::Rect(
origin, gfx::Size(work_area.width() / 2, work_area.height() / 2));
params1.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget1.Init(std::move(params1));
gfx::Rect widget_bounds(widget1.GetWindowBoundsInScreen());
Widget::InitParams params2 = CreateParams(Widget::InitParams::TYPE_WINDOW);
params2.bounds =
gfx::Rect(widget_bounds.width() * 3 / 4, widget_bounds.height() * 3 / 4,
widget_bounds.width() / 2, widget_bounds.height() / 2);
params2.parent = widget1.GetNativeView();
params2.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params2.child = true;
params2.native_widget = test::CreatePlatformNativeWidgetImpl(
&widget2, test::kStubCapture, nullptr);
widget2.Init(std::move(params2));
// The bounds of the child window should be fully in the parent.
gfx::Point expected_origin(
widget_bounds.right() - widget_bounds.width() / 2,
widget_bounds.bottom() - widget_bounds.height() / 2);
gfx::Rect expected_bounds(
expected_origin,
gfx::Size(widget_bounds.width() / 2, widget_bounds.height() / 2));
gfx::Rect actual_bounds(widget2.GetWindowBoundsInScreen());
EXPECT_EQ(expected_bounds, actual_bounds);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/desktop_widget_unittest.cc | C++ | unknown | 7,571 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/widget/drop_helper.h"
#include <memory>
#include <set>
#include <utility>
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/functional/callback_helpers.h"
#include "base/no_destructor.h"
#include "build/build_config.h"
#include "ui/base/dragdrop/drag_drop_types.h"
#include "ui/base/dragdrop/mojom/drag_drop_types.mojom.h"
#include "ui/compositor/layer_tree_owner.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
namespace views {
namespace {
using ::ui::mojom::DragOperation;
const View* g_drag_entered_callback_view = nullptr;
base::RepeatingClosure* GetDragEnteredCallback() {
static base::NoDestructor<base::RepeatingClosure> callback;
return callback.get();
}
} // namespace
DropHelper::DropHelper(View* root_view)
: root_view_(root_view), target_view_(nullptr) {}
DropHelper::~DropHelper() = default;
// static
void DropHelper::SetDragEnteredCallbackForTesting(
const View* view,
base::RepeatingClosure callback) {
g_drag_entered_callback_view = view;
*GetDragEnteredCallback() = std::move(callback);
}
void DropHelper::ResetTargetViewIfEquals(View* view) {
if (target_view_ == view)
target_view_ = nullptr;
if (deepest_view_ == view)
deepest_view_ = nullptr;
}
int DropHelper::OnDragOver(const OSExchangeData& data,
const gfx::Point& root_view_location,
int drag_operation) {
const View* old_deepest_view = deepest_view_;
View* view =
CalculateTargetViewImpl(root_view_location, data, true, &deepest_view_);
if (view != target_view_) {
// Target changed. Notify old drag exited, then new drag entered.
NotifyDragExit();
target_view_ = view;
NotifyDragEntered(data, root_view_location, drag_operation);
}
// Notify testing callback if the drag newly moved over the target view.
if (g_drag_entered_callback_view &&
g_drag_entered_callback_view->Contains(deepest_view_) &&
!g_drag_entered_callback_view->Contains(old_deepest_view)) {
auto* callback = GetDragEnteredCallback();
if (!callback->is_null())
callback->Run();
}
return NotifyDragOver(data, root_view_location, drag_operation);
}
void DropHelper::OnDragExit() {
NotifyDragExit();
deepest_view_ = target_view_ = nullptr;
}
DragOperation DropHelper::OnDrop(const OSExchangeData& data,
const gfx::Point& root_view_location,
int drag_operation) {
View* drop_view = target_view_;
deepest_view_ = target_view_ = nullptr;
if (!drop_view)
return DragOperation::kNone;
if (drag_operation == ui::DragDropTypes::DRAG_NONE) {
drop_view->OnDragExited();
return DragOperation::kNone;
}
gfx::Point view_location(root_view_location);
View* root_view = drop_view->GetWidget()->GetRootView();
View::ConvertPointToTarget(root_view, drop_view, &view_location);
ui::DropTargetEvent drop_event(data, gfx::PointF(view_location),
gfx::PointF(view_location), drag_operation);
auto output_drag_op = ui::mojom::DragOperation::kNone;
auto drop_cb = drop_view->GetDropCallback(drop_event);
std::move(drop_cb).Run(drop_event, output_drag_op,
/*drag_image_layer_owner=*/nullptr);
return output_drag_op;
}
DropHelper::DropCallback DropHelper::GetDropCallback(
const OSExchangeData& data,
const gfx::Point& root_view_location,
int drag_operation) {
View* drop_view = target_view_;
deepest_view_ = target_view_ = nullptr;
if (!drop_view)
return base::NullCallback();
if (drag_operation == ui::DragDropTypes::DRAG_NONE) {
drop_view->OnDragExited();
return base::NullCallback();
}
gfx::Point view_location(root_view_location);
View* root_view = drop_view->GetWidget()->GetRootView();
View::ConvertPointToTarget(root_view, drop_view, &view_location);
ui::DropTargetEvent drop_event(data, gfx::PointF(view_location),
gfx::PointF(view_location), drag_operation);
auto drop_view_cb = drop_view->GetDropCallback(drop_event);
if (!drop_view_cb)
return base::NullCallback();
return base::BindOnce(
[](const ui::DropTargetEvent& drop_event, View::DropCallback drop_cb,
std::unique_ptr<ui::OSExchangeData> data,
ui::mojom::DragOperation& output_drag_op,
std::unique_ptr<ui::LayerTreeOwner> drag_image_layer_owner) {
// Bind the drop_event here instead of using the one that the callback
// is invoked with as that event is in window coordinates and callbacks
// expect View coordinates.
std::move(drop_cb).Run(drop_event, output_drag_op,
std::move(drag_image_layer_owner));
},
drop_event, std::move(drop_view_cb));
}
View* DropHelper::CalculateTargetView(const gfx::Point& root_view_location,
const OSExchangeData& data,
bool check_can_drop) {
return CalculateTargetViewImpl(root_view_location, data, check_can_drop,
nullptr);
}
View* DropHelper::CalculateTargetViewImpl(const gfx::Point& root_view_location,
const OSExchangeData& data,
bool check_can_drop,
View** deepest_view) {
View* view = root_view_->GetEventHandlerForPoint(root_view_location);
if (view == deepest_view_) {
// The view the mouse is over hasn't changed; reuse the target.
return target_view_;
}
if (deepest_view)
*deepest_view = view;
// TODO(sky): for the time being these are separate. Once I port chrome menu
// I can switch to the #else implementation and nuke the OS_WIN
// implementation.
#if BUILDFLAG(IS_WIN)
// View under mouse changed, which means a new view may want the drop.
// Walk the tree, stopping at target_view_ as we know it'll accept the
// drop.
while (view && view != target_view_ &&
(!view->GetEnabled() || !view->CanDrop(data))) {
view = view->parent();
}
#else
int formats = 0;
std::set<ui::ClipboardFormatType> format_types;
while (view && view != target_view_) {
if (view->GetEnabled() && view->GetDropFormats(&formats, &format_types) &&
data.HasAnyFormat(formats, format_types) &&
(!check_can_drop || view->CanDrop(data))) {
// Found the view.
return view;
}
formats = 0;
format_types.clear();
view = view->parent();
}
#endif
return view;
}
void DropHelper::NotifyDragEntered(const OSExchangeData& data,
const gfx::Point& root_view_location,
int drag_operation) {
if (!target_view_)
return;
gfx::Point target_view_location(root_view_location);
View::ConvertPointToTarget(root_view_, target_view_, &target_view_location);
ui::DropTargetEvent enter_event(data, gfx::PointF(target_view_location),
gfx::PointF(target_view_location),
drag_operation);
target_view_->OnDragEntered(enter_event);
}
int DropHelper::NotifyDragOver(const OSExchangeData& data,
const gfx::Point& root_view_location,
int drag_operation) {
if (!target_view_)
return ui::DragDropTypes::DRAG_NONE;
gfx::Point target_view_location(root_view_location);
View::ConvertPointToTarget(root_view_, target_view_, &target_view_location);
ui::DropTargetEvent enter_event(data, gfx::PointF(target_view_location),
gfx::PointF(target_view_location),
drag_operation);
return target_view_->OnDragUpdated(enter_event);
}
void DropHelper::NotifyDragExit() {
if (target_view_)
target_view_->OnDragExited();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/drop_helper.cc | C++ | unknown | 8,109 |
// Copyright 2011 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_WIDGET_DROP_HELPER_H_
#define UI_VIEWS_WIDGET_DROP_HELPER_H_
#include <memory>
#include "base/functional/callback_forward.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/raw_ptr_exclusion.h"
#include "ui/base/dragdrop/mojom/drag_drop_types.mojom-forward.h"
#include "ui/compositor/layer_tree_owner.h"
#include "ui/views/view.h"
#include "ui/views/views_export.h"
namespace gfx {
class Point;
} // namespace gfx
namespace ui {
class OSExchangeData;
} // namespace ui
using ui::OSExchangeData;
namespace views {
class RootView;
// DropHelper provides support for managing the view a drop is going to occur
// at during dnd as well as sending the view the appropriate dnd methods.
// DropHelper is intended to be used by a class that interacts with the system
// drag and drop. The system class invokes OnDragOver as the mouse moves,
// then either OnDragExit or OnDrop when the drop is done.
class VIEWS_EXPORT DropHelper {
public:
// This is expected to match the signature of
// aura::client::DragDropDelegate::DropCallback.
using DropCallback = base::OnceCallback<void(
std::unique_ptr<ui::OSExchangeData> data,
ui::mojom::DragOperation& output_drag_op,
std::unique_ptr<ui::LayerTreeOwner> drag_image_layer_owner)>;
explicit DropHelper(View* root_view);
DropHelper(const DropHelper&) = delete;
DropHelper& operator=(const DropHelper&) = delete;
~DropHelper();
// Sets a callback that is run any time a drag enters |view|. Only exposed
// for testing.
static void SetDragEnteredCallbackForTesting(const View* view,
base::RepeatingClosure callback);
// Current view drop events are targeted at, may be NULL.
View* target_view() const { return target_view_; }
// Returns the RootView the DropHelper was created with.
View* root_view() const { return root_view_; }
// Resets the target_view_ to NULL if it equals view.
//
// This is invoked when a View is removed from the RootView to make sure
// we don't target a view that was removed during dnd.
void ResetTargetViewIfEquals(View* view);
// Invoked when a the mouse is dragged over the root view during a drag and
// drop operation. This method returns a bitmask of the types in DragDropTypes
// for the target view. If no view wants the drop, DRAG_NONE is returned.
int OnDragOver(const OSExchangeData& data,
const gfx::Point& root_view_location,
int drag_operation);
// Invoked when a the mouse is dragged out of the root view during a drag and
// drop operation.
void OnDragExit();
// Invoked when the user drops data on the root view during a drag and drop
// operation. See OnDragOver for details on return type.
//
// NOTE: implementations must invoke OnDragOver before invoking this,
// supplying the return value from OnDragOver as the drag_operation.
ui::mojom::DragOperation OnDrop(const OSExchangeData& data,
const gfx::Point& root_view_location,
int drag_operation);
// Invoked when the user drops data on the root view during a drag and drop
// operation, but the drop is held because of DataTransferPolicController.
// To fetch the correct callback, callers should invoke
DropCallback GetDropCallback(const OSExchangeData& data,
const gfx::Point& root_view_location,
int drag_operation);
bool WillAnimateDragImageForDrop();
// Calculates the target view for a drop given the specified location in
// the coordinate system of the rootview. This tries to avoid continually
// querying CanDrop by returning target_view_ if the mouse is still over
// target_view_.
View* CalculateTargetView(const gfx::Point& root_view_location,
const OSExchangeData& data,
bool check_can_drop);
private:
// Implementation of CalculateTargetView. If |deepest_view| is non-NULL it is
// set to the deepest descendant of the RootView that contains the point
// |root_view_location|
View* CalculateTargetViewImpl(const gfx::Point& root_view_location,
const OSExchangeData& data,
bool check_can_drop,
View** deepest_view);
// Methods to send the appropriate drop notification to the targeted view.
// These do nothing if the target view is NULL.
void NotifyDragEntered(const OSExchangeData& data,
const gfx::Point& root_view_location,
int drag_operation);
int NotifyDragOver(const OSExchangeData& data,
const gfx::Point& root_view_location,
int drag_operation);
void NotifyDragExit();
// RootView we were created for.
raw_ptr<View, DanglingUntriaged> root_view_;
// View we're targeting events at.
raw_ptr<View, DanglingUntriaged> target_view_;
// The deepest view under the current drop coordinate.
// This field is not a raw_ptr<> because it was filtered by the rewriter for:
// #addr-of
RAW_PTR_EXCLUSION View* deepest_view_ = nullptr;
};
} // namespace views
#endif // UI_VIEWS_WIDGET_DROP_HELPER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/drop_helper.h | C++ | unknown | 5,440 |
// 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/widget/drop_helper.h"
#include <memory>
#include <set>
#include <utility>
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/dragdrop/drop_target_event.h"
#include "ui/base/dragdrop/mojom/drag_drop_types.mojom.h"
#include "ui/base/dragdrop/os_exchange_data.h"
#include "ui/compositor/layer_tree_owner.h"
#include "ui/gfx/geometry/point.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
namespace views {
namespace {
// A view implementation for validating drop location.
class TestDropTargetView : public views::View {
public:
TestDropTargetView() : drop_location_(-1, -1) {}
bool GetDropFormats(
int* formats,
std::set<ui::ClipboardFormatType>* format_types) override {
*formats = ui::OSExchangeData::STRING;
return true;
}
bool CanDrop(const OSExchangeData& data) override { return true; }
int OnDragUpdated(const ui::DropTargetEvent& event) override {
return static_cast<int>(ui::mojom::DragOperation::kCopy);
}
gfx::Point drop_location() { return drop_location_; }
DropCallback GetDropCallback(const ui::DropTargetEvent& event) override {
return base::BindOnce(&TestDropTargetView::PerformDrop,
base::Unretained(this));
}
private:
gfx::Point drop_location_;
void PerformDrop(const ui::DropTargetEvent& event,
ui::mojom::DragOperation& output_drag_op,
std::unique_ptr<ui::LayerTreeOwner> drag_image_layer_owner) {
drop_location_ = event.location();
output_drag_op = ui::mojom::DragOperation::kCopy;
}
};
class DropHelperTest : public ViewsTestBase {
public:
DropHelperTest() = default;
~DropHelperTest() override = default;
};
// Verifies that drop coordinates are dispatched in View coordinates.
TEST_F(DropHelperTest, DropCoordinates) {
// Create widget
Widget widget;
Widget::InitParams init_params(
CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS));
init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget.Init(std::move(init_params));
// Setup a widget with a view that isn't aligned with the corner. In screen
// coordinates, the target view starts at (120, 80) and ends at (220, 130).
gfx::Rect bounds(100, 50, 200, 100);
widget.SetBounds(bounds);
views::View* container =
widget.SetContentsView(std::make_unique<views::View>());
TestDropTargetView* drop_target =
container->AddChildView(std::make_unique<TestDropTargetView>());
drop_target->SetBounds(20, 30, 100, 50);
widget.Show();
auto drop_helper = std::make_unique<DropHelper>(widget.GetRootView());
// Construct drag data
auto data = std::make_unique<ui::OSExchangeData>();
data->SetString(u"Drag and drop is cool");
int drag_operation = static_cast<int>(ui::mojom::DragOperation::kCopy);
gfx::Point enter_location = {10, 0};
// Enter parent view
drop_helper->OnDragOver(*data, enter_location, drag_operation);
// Location of center of target view in root.
gfx::Point target = {70, 55};
// Enter target view
drop_helper->OnDragOver(*data, target, drag_operation);
// Start drop.
DropHelper::DropCallback callback =
drop_helper->GetDropCallback(*data, target, drag_operation);
ASSERT_TRUE(callback);
// Perform the drop.
ui::mojom::DragOperation output_op = ui::mojom::DragOperation::kNone;
std::move(callback).Run(std::move(data), output_op,
/*drag_image_layer_owner=*/nullptr);
// The test view always executes a copy operation.
EXPECT_EQ(output_op, ui::mojom::DragOperation::kCopy);
// Verify the location of the drop is centered in the target view.
EXPECT_EQ(drop_target->drop_location(), gfx::Point(50, 25));
}
} // namespace
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/drop_helper_unittest.cc | C++ | unknown | 4,005 |
// 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/widget/focus_manager_event_handler.h"
#include "ui/aura/window.h"
#include "ui/views/focus/focus_manager.h"
#include "ui/views/widget/widget.h"
namespace views {
FocusManagerEventHandler::FocusManagerEventHandler(Widget* widget,
aura::Window* window)
: widget_(widget), window_(window) {
DCHECK(window_);
window_->AddPreTargetHandler(this);
}
FocusManagerEventHandler::~FocusManagerEventHandler() {
window_->RemovePreTargetHandler(this);
}
void FocusManagerEventHandler::OnKeyEvent(ui::KeyEvent* event) {
if (widget_ && widget_->GetFocusManager()->GetFocusedView() &&
!widget_->GetFocusManager()->OnKeyEvent(*event)) {
event->StopPropagation();
}
}
base::StringPiece FocusManagerEventHandler::GetLogContext() const {
return "FocusManagerEventHandler";
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/focus_manager_event_handler.cc | C++ | unknown | 1,023 |
// Copyright 2016 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_WIDGET_FOCUS_MANAGER_EVENT_HANDLER_H_
#define UI_VIEWS_WIDGET_FOCUS_MANAGER_EVENT_HANDLER_H_
#include "base/memory/raw_ptr.h"
#include "base/strings/string_piece.h"
#include "ui/events/event_handler.h"
namespace aura {
class Window;
}
namespace views {
class Widget;
// This class forwards KeyEvents to the FocusManager associated with a widget.
// This allows KeyEvents to be processed before other targets.
class FocusManagerEventHandler : public ui::EventHandler {
public:
FocusManagerEventHandler(Widget* widget, aura::Window* window);
FocusManagerEventHandler(const FocusManagerEventHandler&) = delete;
FocusManagerEventHandler& operator=(const FocusManagerEventHandler&) = delete;
~FocusManagerEventHandler() override;
// Implementation of ui::EventHandler:
void OnKeyEvent(ui::KeyEvent* event) override;
base::StringPiece GetLogContext() const override;
private:
raw_ptr<Widget> widget_;
// |window_| is the event target that is associated with this class.
raw_ptr<aura::Window> window_;
};
} // namespace views
#endif // UI_VIEWS_WIDGET_FOCUS_MANAGER_EVENT_HANDLER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/focus_manager_event_handler.h | C++ | unknown | 1,273 |
// Copyright 2011 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_WIDGET_NATIVE_WIDGET_H_
#define UI_VIEWS_WIDGET_NATIVE_WIDGET_H_
#include "ui/views/views_export.h"
namespace views {
class Widget;
namespace internal {
class NativeWidgetPrivate;
}
////////////////////////////////////////////////////////////////////////////////
// NativeWidget interface
//
// An interface that serves as the public API base for the
// internal::NativeWidget interface that Widget uses to communicate with a
// backend-specific native widget implementation. This is the only component of
// this interface that is publicly visible, and exists solely for exposure via
// Widget's native_widget() accessor, which code occasionally static_casts to
// a known implementation in platform-specific code.
//
class VIEWS_EXPORT NativeWidget {
public:
virtual ~NativeWidget() = default;
private:
friend class Widget;
virtual internal::NativeWidgetPrivate* AsNativeWidgetPrivate() = 0;
};
} // namespace views
#endif // UI_VIEWS_WIDGET_NATIVE_WIDGET_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/native_widget.h | C++ | unknown | 1,147 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/widget/native_widget_aura.h"
#include <memory>
#include <utility>
#include <vector>
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/task/single_thread_task_runner.h"
#include "build/build_config.h"
#include "ui/aura/client/aura_constants.h"
#include "ui/aura/client/capture_client.h"
#include "ui/aura/client/cursor_client.h"
#include "ui/aura/client/drag_drop_client.h"
#include "ui/aura/client/drag_drop_delegate.h"
#include "ui/aura/client/focus_client.h"
#include "ui/aura/client/screen_position_client.h"
#include "ui/aura/client/window_parenting_client.h"
#include "ui/aura/client/window_types.h"
#include "ui/aura/env.h"
#include "ui/aura/window.h"
#include "ui/aura/window_event_dispatcher.h"
#include "ui/aura/window_observer.h"
#include "ui/aura/window_tree_host.h"
#include "ui/base/class_property.h"
#include "ui/base/data_transfer_policy/data_transfer_endpoint.h"
#include "ui/base/dragdrop/os_exchange_data.h"
#include "ui/base/ui_base_types.h"
#include "ui/compositor/layer.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/events/event.h"
#include "ui/gfx/canvas.h"
#include "ui/native_theme/native_theme_aura.h"
#include "ui/views/buildflags.h"
#include "ui/views/drag_utils.h"
#include "ui/views/views_delegate.h"
#include "ui/views/widget/drop_helper.h"
#include "ui/views/widget/focus_manager_event_handler.h"
#include "ui/views/widget/native_widget_delegate.h"
#include "ui/views/widget/root_view.h"
#include "ui/views/widget/tooltip_manager_aura.h"
#include "ui/views/widget/widget_aura_utils.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/widget/window_reorderer.h"
#include "ui/wm/core/coordinate_conversion.h"
#include "ui/wm/core/shadow_types.h"
#include "ui/wm/core/transient_window_manager.h"
#include "ui/wm/core/window_animations.h"
#include "ui/wm/core/window_properties.h"
#include "ui/wm/core/window_util.h"
#include "ui/wm/public/activation_client.h"
#include "ui/wm/public/window_move_client.h"
#if BUILDFLAG(ENABLE_DESKTOP_AURA)
#include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h"
#include "ui/views/widget/desktop_aura/desktop_window_tree_host.h"
#endif
#if BUILDFLAG(ENABLE_DESKTOP_AURA) && BUILDFLAG(IS_OZONE)
#include "ui/views/widget/desktop_aura/desktop_window_tree_host_platform.h"
#endif
#if BUILDFLAG(IS_WIN)
#include "ui/views/widget/desktop_aura/desktop_window_tree_host_win.h"
#endif
DEFINE_UI_CLASS_PROPERTY_TYPE(views::internal::NativeWidgetPrivate*)
namespace views {
namespace {
DEFINE_UI_CLASS_PROPERTY_KEY(internal::NativeWidgetPrivate*,
kNativeWidgetPrivateKey,
nullptr)
void SetRestoreBounds(aura::Window* window, const gfx::Rect& bounds) {
window->SetProperty(aura::client::kRestoreBoundsKey, bounds);
}
void SetIcon(aura::Window* window,
const aura::WindowProperty<gfx::ImageSkia*>* key,
const gfx::ImageSkia& value) {
if (value.isNull())
window->ClearProperty(key);
else
window->SetProperty(key, value);
}
bool FindLayersInOrder(const std::vector<ui::Layer*>& children,
const ui::Layer** first,
const ui::Layer** second) {
for (const ui::Layer* child : children) {
if (child == *second) {
*second = nullptr;
return *first == nullptr;
}
if (child == *first)
*first = nullptr;
if (FindLayersInOrder(child->children(), first, second))
return true;
// If second is cleared without success, exit early with failure.
if (!*second)
return false;
}
return false;
}
} // namespace
////////////////////////////////////////////////////////////////////////////////
// NativeWidgetAura, public:
NativeWidgetAura::NativeWidgetAura(internal::NativeWidgetDelegate* delegate)
: delegate_(delegate->AsWidget()->GetWeakPtr()),
window_(new aura::Window(this, aura::client::WINDOW_TYPE_UNKNOWN)) {
aura::client::SetFocusChangeObserver(window_, this);
wm::SetActivationChangeObserver(window_, this);
}
// static
void NativeWidgetAura::RegisterNativeWidgetForWindow(
internal::NativeWidgetPrivate* native_widget,
aura::Window* window) {
window->SetProperty(kNativeWidgetPrivateKey, native_widget);
}
// static
void NativeWidgetAura::AssignIconToAuraWindow(aura::Window* window,
const gfx::ImageSkia& window_icon,
const gfx::ImageSkia& app_icon) {
if (window) {
SetIcon(window, aura::client::kWindowIconKey, window_icon);
SetIcon(window, aura::client::kAppIconKey, app_icon);
}
}
// static
void NativeWidgetAura::SetShadowElevationFromInitParams(
aura::Window* window,
const Widget::InitParams& params) {
if (params.shadow_type == Widget::InitParams::ShadowType::kNone) {
wm::SetShadowElevation(window, wm::kShadowElevationNone);
} else if (params.shadow_type == Widget::InitParams::ShadowType::kDrop &&
params.shadow_elevation) {
wm::SetShadowElevation(window, *params.shadow_elevation);
}
}
// static
void NativeWidgetAura::SetResizeBehaviorFromDelegate(WidgetDelegate* delegate,
aura::Window* window) {
if (!window)
return;
int behavior = aura::client::kResizeBehaviorNone;
if (delegate) {
if (delegate->CanResize())
behavior |= aura::client::kResizeBehaviorCanResize;
if (delegate->CanMaximize())
behavior |= aura::client::kResizeBehaviorCanMaximize;
if (delegate->CanMinimize())
behavior |= aura::client::kResizeBehaviorCanMinimize;
}
window->SetProperty(aura::client::kResizeBehaviorKey, behavior);
}
////////////////////////////////////////////////////////////////////////////////
// NativeWidgetAura, internal::NativeWidgetPrivate implementation:
void NativeWidgetAura::InitNativeWidget(Widget::InitParams params) {
// See Widget::InitParams::context for details.
DCHECK(params.parent || params.context);
ownership_ = params.ownership;
if (ownership_ == Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET)
owned_delegate_ = base::WrapUnique(delegate_.get());
window_->AcquireAllPropertiesFrom(
std::move(params.init_properties_container));
RegisterNativeWidgetForWindow(this, window_);
window_->SetType(GetAuraWindowTypeForWidgetType(params.type));
if (params.corner_radius) {
window_->SetProperty(aura::client::kWindowCornerRadiusKey,
*params.corner_radius);
}
window_->SetProperty(aura::client::kShowStateKey, params.show_state);
int desk_index;
// Set workspace property of this window created with a specified workspace
// in InitParams. The desk index can be kActiveWorkspace=-1, representing
// an active desk. If the window is visible on all workspaces, it belongs on
// the active desk.
if (params.visible_on_all_workspaces) {
window_->SetProperty(aura::client::kWindowWorkspaceKey,
aura::client::kWindowWorkspaceVisibleOnAllWorkspaces);
} else if (base::StringToInt(params.workspace, &desk_index)) {
window_->SetProperty(aura::client::kWindowWorkspaceKey, desk_index);
}
if (params.type == Widget::InitParams::TYPE_BUBBLE)
wm::SetHideOnDeactivate(window_, true);
window_->SetTransparent(params.opacity ==
Widget::InitParams::WindowOpacity::kTranslucent);
// Check for ShadowType::kNone before aura::Window::Init() to ensure observers
// do not add useless shadow layers by deriving one from the window type.
SetShadowElevationFromInitParams(window_, params);
window_->Init(params.layer_type);
// Set name after layer init so it propagates to layer.
window_->SetName(params.name.empty() ? "NativeWidgetAura" : params.name);
if (params.type == Widget::InitParams::TYPE_CONTROL)
window_->Show();
delegate_->OnNativeWidgetCreated();
gfx::Rect window_bounds = params.bounds;
gfx::NativeView parent = params.parent;
gfx::NativeView context = params.context;
if (!params.child) {
wm::TransientWindowManager::GetOrCreate(window_)->AddObserver(this);
// Set up the transient child before the window is added. This way the
// LayoutManager knows the window has a transient parent.
if (parent && parent->GetType() != aura::client::WINDOW_TYPE_UNKNOWN) {
wm::AddTransientChild(parent, window_);
if (!context)
context = parent;
parent = nullptr;
// Generally transient bubbles are showing state associated to the parent
// window. Make sure the transient bubble is only visible if the parent is
// visible, otherwise the bubble may not make sense by itself.
if (params.type == Widget::InitParams::TYPE_BUBBLE) {
wm::TransientWindowManager::GetOrCreate(window_)
->set_parent_controls_visibility(true);
}
}
// SetZOrderLevel before SetParent so that always-on-top container is used.
SetZOrderLevel(params.EffectiveZOrderLevel());
// Make sure we have a real |window_bounds|.
aura::Window* parent_or_context = parent ? parent : context;
if (parent_or_context && window_bounds == gfx::Rect()) {
// If a parent or context is specified but no bounds are given, use the
// origin of the display so that the widget will be added to the same
// display as the parent or context.
gfx::Rect bounds = display::Screen::GetScreen()
->GetDisplayNearestWindow(parent_or_context)
.bounds();
window_bounds.set_origin(bounds.origin());
}
}
// Set properties before adding to the parent so that its layout manager sees
// the correct values.
OnSizeConstraintsChanged();
if (parent) {
parent->AddChild(window_);
} else {
aura::client::ParentWindowWithContext(window_, context->GetRootWindow(),
window_bounds);
}
window_->AddObserver(this);
// Wait to set the bounds until we have a parent. That way we can know our
// true state/bounds (the LayoutManager may enforce a particular
// state/bounds).
if (IsMaximized() || IsMinimized())
SetRestoreBounds(window_, window_bounds);
else
SetBounds(window_bounds);
window_->SetEventTargetingPolicy(
params.accept_events ? aura::EventTargetingPolicy::kTargetAndDescendants
: aura::EventTargetingPolicy::kNone);
DCHECK(GetWidget()->GetRootView());
if (params.type != Widget::InitParams::TYPE_TOOLTIP)
tooltip_manager_ = std::make_unique<views::TooltipManagerAura>(this);
drop_helper_ = std::make_unique<DropHelper>(GetWidget()->GetRootView());
if (params.type != Widget::InitParams::TYPE_TOOLTIP &&
params.type != Widget::InitParams::TYPE_POPUP) {
aura::client::SetDragDropDelegate(window_, this);
}
if (params.type == Widget::InitParams::TYPE_WINDOW) {
focus_manager_event_handler_ =
std::make_unique<FocusManagerEventHandler>(GetWidget(), window_);
}
wm::SetActivationDelegate(window_, this);
window_reorderer_ =
std::make_unique<WindowReorderer>(window_, GetWidget()->GetRootView());
}
void NativeWidgetAura::OnWidgetInitDone() {}
std::unique_ptr<NonClientFrameView>
NativeWidgetAura::CreateNonClientFrameView() {
return nullptr;
}
bool NativeWidgetAura::ShouldUseNativeFrame() const {
// There is only one frame type for aura.
return false;
}
bool NativeWidgetAura::ShouldWindowContentsBeTransparent() const {
return false;
}
void NativeWidgetAura::FrameTypeChanged() {
// This is called when the Theme has changed; forward the event to the root
// widget.
GetWidget()->ThemeChanged();
GetWidget()->GetRootView()->SchedulePaint();
}
Widget* NativeWidgetAura::GetWidget() {
return delegate_ ? delegate_->AsWidget() : nullptr;
}
const Widget* NativeWidgetAura::GetWidget() const {
return delegate_ ? delegate_->AsWidget() : nullptr;
}
gfx::NativeView NativeWidgetAura::GetNativeView() const {
return window_;
}
gfx::NativeWindow NativeWidgetAura::GetNativeWindow() const {
return window_;
}
Widget* NativeWidgetAura::GetTopLevelWidget() {
NativeWidgetPrivate* native_widget = GetTopLevelNativeWidget(GetNativeView());
return native_widget ? native_widget->GetWidget() : nullptr;
}
const ui::Compositor* NativeWidgetAura::GetCompositor() const {
return window_ ? window_->layer()->GetCompositor() : nullptr;
}
const ui::Layer* NativeWidgetAura::GetLayer() const {
return window_ ? window_->layer() : nullptr;
}
void NativeWidgetAura::ReorderNativeViews() {
window_reorderer_->ReorderChildWindows();
}
void NativeWidgetAura::ViewRemoved(View* view) {
DCHECK(drop_helper_.get() != nullptr);
drop_helper_->ResetTargetViewIfEquals(view);
}
void NativeWidgetAura::SetNativeWindowProperty(const char* name, void* value) {
if (window_)
window_->SetNativeWindowProperty(name, value);
}
void* NativeWidgetAura::GetNativeWindowProperty(const char* name) const {
return window_ ? window_->GetNativeWindowProperty(name) : nullptr;
}
TooltipManager* NativeWidgetAura::GetTooltipManager() const {
return tooltip_manager_.get();
}
void NativeWidgetAura::SetCapture() {
if (window_)
window_->SetCapture();
}
void NativeWidgetAura::ReleaseCapture() {
if (window_)
window_->ReleaseCapture();
}
bool NativeWidgetAura::HasCapture() const {
return window_ && window_->HasCapture();
}
ui::InputMethod* NativeWidgetAura::GetInputMethod() {
if (!window_)
return nullptr;
aura::Window* root_window = window_->GetRootWindow();
return root_window ? root_window->GetHost()->GetInputMethod() : nullptr;
}
void NativeWidgetAura::CenterWindow(const gfx::Size& size) {
if (!window_)
return;
window_->SetProperty(aura::client::kPreferredSize, size);
gfx::Rect parent_bounds(window_->parent()->GetBoundsInRootWindow());
// When centering window, we take the intersection of the host and
// the parent. We assume the root window represents the visible
// rect of a single screen.
gfx::Rect work_area = display::Screen::GetScreen()
->GetDisplayNearestWindow(window_)
.work_area();
aura::client::ScreenPositionClient* screen_position_client =
aura::client::GetScreenPositionClient(window_->GetRootWindow());
if (screen_position_client) {
gfx::Point origin = work_area.origin();
screen_position_client->ConvertPointFromScreen(window_->GetRootWindow(),
&origin);
work_area.set_origin(origin);
}
parent_bounds.Intersect(work_area);
// If |window_|'s transient parent's bounds are big enough to fit it, then we
// center it with respect to the transient parent.
if (wm::GetTransientParent(window_)) {
gfx::Rect transient_parent_rect =
wm::GetTransientParent(window_)->GetBoundsInRootWindow();
transient_parent_rect.Intersect(work_area);
if (transient_parent_rect.height() >= size.height() &&
transient_parent_rect.width() >= size.width())
parent_bounds = transient_parent_rect;
}
gfx::Rect window_bounds(
parent_bounds.x() + (parent_bounds.width() - size.width()) / 2,
parent_bounds.y() + (parent_bounds.height() - size.height()) / 2,
size.width(), size.height());
// Don't size the window bigger than the parent, otherwise the user may not be
// able to close or move it.
window_bounds.AdjustToFit(parent_bounds);
// Convert the bounds back relative to the parent.
gfx::Point origin = window_bounds.origin();
aura::Window::ConvertPointToTarget(window_->GetRootWindow(),
window_->parent(), &origin);
window_bounds.set_origin(origin);
window_->SetBounds(window_bounds);
}
void NativeWidgetAura::GetWindowPlacement(
gfx::Rect* bounds,
ui::WindowShowState* show_state) const {
// The interface specifies returning restored bounds, not current bounds.
*bounds = GetRestoredBounds();
*show_state = window_ ? window_->GetProperty(aura::client::kShowStateKey)
: ui::SHOW_STATE_DEFAULT;
}
bool NativeWidgetAura::SetWindowTitle(const std::u16string& title) {
if (!window_)
return false;
if (window_->GetTitle() == title)
return false;
window_->SetTitle(title);
return true;
}
void NativeWidgetAura::SetWindowIcons(const gfx::ImageSkia& window_icon,
const gfx::ImageSkia& app_icon) {
AssignIconToAuraWindow(window_, window_icon, app_icon);
}
const gfx::ImageSkia* NativeWidgetAura::GetWindowIcon() {
return window_->GetProperty(aura::client::kWindowIconKey);
}
const gfx::ImageSkia* NativeWidgetAura::GetWindowAppIcon() {
return window_->GetProperty(aura::client::kAppIconKey);
}
void NativeWidgetAura::InitModalType(ui::ModalType modal_type) {
if (modal_type != ui::MODAL_TYPE_NONE)
window_->SetProperty(aura::client::kModalKey, modal_type);
if (modal_type == ui::MODAL_TYPE_WINDOW) {
wm::TransientWindowManager::GetOrCreate(window_)
->set_parent_controls_visibility(true);
}
}
gfx::Rect NativeWidgetAura::GetWindowBoundsInScreen() const {
return window_ ? window_->GetBoundsInScreen() : gfx::Rect();
}
gfx::Rect NativeWidgetAura::GetClientAreaBoundsInScreen() const {
// View-to-screen coordinate system transformations depend on this returning
// the full window bounds, for example View::ConvertPointToScreen().
return window_ ? window_->GetBoundsInScreen() : gfx::Rect();
}
gfx::Rect NativeWidgetAura::GetRestoredBounds() const {
if (!window_)
return gfx::Rect();
// Restored bounds should only be relevant if the window is minimized,
// maximized, or fullscreen. However, in some places the code expects
// GetRestoredBounds() to return the current window bounds if the window is
// not in either state.
if (IsMinimized() || IsMaximized() || IsFullscreen()) {
// Restore bounds are in screen coordinates, no need to convert.
gfx::Rect* restore_bounds =
window_->GetProperty(aura::client::kRestoreBoundsKey);
if (restore_bounds)
return *restore_bounds;
}
// Prefer getting the window bounds and converting them to screen bounds since
// Window::GetBoundsInScreen takes into the account the window transform.
auto* screen_position_client =
aura::client::GetScreenPositionClient(window_->GetRootWindow());
if (screen_position_client) {
// |window_|'s bounds are in parent's coordinate system so use that when
// converting.
gfx::Rect bounds = window_->bounds();
gfx::Point origin = bounds.origin();
screen_position_client->ConvertPointToScreenIgnoringTransforms(
window_->parent(), &origin);
return gfx::Rect(origin, bounds.size());
}
return window_->GetBoundsInScreen();
}
std::string NativeWidgetAura::GetWorkspace() const {
int desk_index = window_->GetProperty(aura::client::kWindowWorkspaceKey);
if (desk_index == aura::client::kWindowWorkspaceUnassignedWorkspace ||
desk_index == aura::client::kWindowWorkspaceVisibleOnAllWorkspaces) {
return std::string();
}
return base::NumberToString(desk_index);
}
void NativeWidgetAura::SetBounds(const gfx::Rect& bounds) {
if (!window_)
return;
aura::Window* root = window_->GetRootWindow();
if (root) {
aura::client::ScreenPositionClient* screen_position_client =
aura::client::GetScreenPositionClient(root);
if (screen_position_client) {
display::Display dst_display =
display::Screen::GetScreen()->GetDisplayMatching(bounds);
screen_position_client->SetBounds(window_, bounds, dst_display);
return;
}
}
window_->SetBounds(bounds);
}
void NativeWidgetAura::SetBoundsConstrained(const gfx::Rect& bounds) {
if (!window_)
return;
gfx::Rect new_bounds(bounds);
if (window_->parent()) {
if (window_->parent()->GetProperty(wm::kUsesScreenCoordinatesKey)) {
new_bounds =
NativeWidgetPrivate::ConstrainBoundsToDisplayWorkArea(new_bounds);
} else {
new_bounds.AdjustToFit(gfx::Rect(window_->parent()->bounds().size()));
}
}
SetBounds(new_bounds);
}
void NativeWidgetAura::SetSize(const gfx::Size& size) {
if (window_)
window_->SetBounds(gfx::Rect(window_->bounds().origin(), size));
}
void NativeWidgetAura::StackAbove(gfx::NativeView native_view) {
if (window_ && window_->parent() &&
window_->parent() == native_view->parent())
window_->parent()->StackChildAbove(window_, native_view);
}
void NativeWidgetAura::StackAtTop() {
if (window_)
window_->parent()->StackChildAtTop(window_);
}
bool NativeWidgetAura::IsStackedAbove(gfx::NativeView native_view) {
if (!window_)
return false;
// If the root windows are not shared between two native views
// it is likely that they are child windows of different top level windows.
// In that scenario, just check the top level windows.
if (GetNativeWindow()->GetRootWindow() != native_view->GetRootWindow()) {
return GetTopLevelWidget()->IsStackedAbove(
native_view->GetToplevelWindow());
}
const ui::Layer* first = native_view->layer(); // below
const ui::Layer* second = GetWidget()->GetLayer(); // above
return FindLayersInOrder(
GetNativeWindow()->GetRootWindow()->layer()->children(), &first, &second);
}
void NativeWidgetAura::SetShape(std::unique_ptr<Widget::ShapeRects> shape) {
if (window_)
window_->layer()->SetAlphaShape(std::move(shape));
}
void NativeWidgetAura::Close() {
// |window_| may already be deleted by parent window. This can happen
// when this widget is child widget or has transient parent
// and ownership is WIDGET_OWNS_NATIVE_WIDGET.
DCHECK(window_ ||
ownership_ == Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET);
if (window_) {
Hide();
window_->SetProperty(aura::client::kModalKey, ui::MODAL_TYPE_NONE);
}
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(&NativeWidgetAura::CloseNow, weak_factory.GetWeakPtr()));
}
void NativeWidgetAura::CloseNow() {
// We cannot use `raw_ptr::ClearAndDelete` here:
// In `window_` destructor, `OnWindowDestroying` will be called on this
// instance and `OnWindowDestroying` contains logic that still needs reference
// in `window_`. `ClearAndDelete` would have cleared the value in `window_`
// first before deleting `window_` causing problem in `OnWindowDestroying`.
if (window_)
delete window_;
// `window_` destructor may delete this `NativeWidgetAura` instance. Therefore
// we must NOT access anything through `this` after `delete window_`.
// Therefore, we should NOT attempt to set `window_` to `nullptr`.
}
void NativeWidgetAura::Show(ui::WindowShowState show_state,
const gfx::Rect& restore_bounds) {
if (!window_)
return;
if ((show_state == ui::SHOW_STATE_MAXIMIZED ||
show_state == ui::SHOW_STATE_MINIMIZED) &&
!restore_bounds.IsEmpty()) {
SetRestoreBounds(window_, restore_bounds);
}
if (show_state == ui::SHOW_STATE_MAXIMIZED ||
show_state == ui::SHOW_STATE_FULLSCREEN) {
window_->SetProperty(aura::client::kShowStateKey, show_state);
}
window_->Show();
if (delegate_->CanActivate()) {
if (show_state != ui::SHOW_STATE_INACTIVE)
Activate();
// SetInitialFocus() should be always be called, even for
// SHOW_STATE_INACTIVE. If the window has to stay inactive, the method will
// do the right thing.
// Activate() might fail if the window is non-activatable. In this case, we
// should pass SHOW_STATE_INACTIVE to SetInitialFocus() to stop the initial
// focused view from getting focused. See crbug.com/515594 for example.
SetInitialFocus(IsActive() ? show_state : ui::SHOW_STATE_INACTIVE);
}
// On desktop aura, a window is activated first even when it is shown as
// minimized. Do the same for consistency.
if (show_state == ui::SHOW_STATE_MINIMIZED)
Minimize();
}
void NativeWidgetAura::Hide() {
if (window_)
window_->Hide();
}
bool NativeWidgetAura::IsVisible() const {
return window_ && window_->IsVisible();
}
void NativeWidgetAura::Activate() {
if (!window_)
return;
// We don't necessarily have a root window yet. This can happen with
// constrained windows.
if (window_->GetRootWindow())
wm::GetActivationClient(window_->GetRootWindow())->ActivateWindow(window_);
if (window_->GetProperty(aura::client::kDrawAttentionKey))
window_->SetProperty(aura::client::kDrawAttentionKey, false);
}
void NativeWidgetAura::Deactivate() {
if (!window_)
return;
wm::GetActivationClient(window_->GetRootWindow())->DeactivateWindow(window_);
}
bool NativeWidgetAura::IsActive() const {
return window_ && wm::IsActiveWindow(window_);
}
void NativeWidgetAura::SetZOrderLevel(ui::ZOrderLevel order) {
if (window_)
window_->SetProperty(aura::client::kZOrderingKey, order);
}
ui::ZOrderLevel NativeWidgetAura::GetZOrderLevel() const {
if (window_)
return window_->GetProperty(aura::client::kZOrderingKey);
return ui::ZOrderLevel::kNormal;
}
void NativeWidgetAura::SetVisibleOnAllWorkspaces(bool always_visible) {
window_->SetProperty(
aura::client::kWindowWorkspaceKey,
always_visible ? aura::client::kWindowWorkspaceVisibleOnAllWorkspaces
: aura::client::kWindowWorkspaceUnassignedWorkspace);
}
bool NativeWidgetAura::IsVisibleOnAllWorkspaces() const {
return window_ && window_->GetProperty(aura::client::kWindowWorkspaceKey) ==
aura::client::kWindowWorkspaceVisibleOnAllWorkspaces;
}
void NativeWidgetAura::Maximize() {
if (window_)
window_->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MAXIMIZED);
}
void NativeWidgetAura::Minimize() {
if (window_)
window_->SetProperty(aura::client::kShowStateKey, ui::SHOW_STATE_MINIMIZED);
}
bool NativeWidgetAura::IsMaximized() const {
return window_ && window_->GetProperty(aura::client::kShowStateKey) ==
ui::SHOW_STATE_MAXIMIZED;
}
bool NativeWidgetAura::IsMinimized() const {
return window_ && window_->GetProperty(aura::client::kShowStateKey) ==
ui::SHOW_STATE_MINIMIZED;
}
void NativeWidgetAura::Restore() {
if (window_)
wm::Restore(window_);
}
void NativeWidgetAura::SetFullscreen(bool fullscreen,
int64_t target_display_id) {
if (!window_) {
return;
}
wm::SetWindowFullscreen(window_, fullscreen, target_display_id);
}
bool NativeWidgetAura::IsFullscreen() const {
return window_ && window_->GetProperty(aura::client::kShowStateKey) ==
ui::SHOW_STATE_FULLSCREEN;
}
void NativeWidgetAura::SetCanAppearInExistingFullscreenSpaces(
bool can_appear_in_existing_fullscreen_spaces) {}
void NativeWidgetAura::SetOpacity(float opacity) {
if (window_)
window_->layer()->SetOpacity(opacity);
}
void NativeWidgetAura::SetAspectRatio(const gfx::SizeF& aspect_ratio,
const gfx::Size& excluded_margin) {
DCHECK(!aspect_ratio.IsEmpty());
if (excluded_margin.width() > 0 || excluded_margin.height() > 0) {
NOTIMPLEMENTED_LOG_ONCE();
}
if (window_) {
// aura::client::kAspectRatio is owned, which allows for passing by value.
window_->SetProperty(aura::client::kAspectRatio, aspect_ratio);
// TODO(crbug.com/1407629): send `excluded_margin`.
}
}
void NativeWidgetAura::FlashFrame(bool flash) {
if (window_)
window_->SetProperty(aura::client::kDrawAttentionKey, flash);
}
void NativeWidgetAura::RunShellDrag(View* view,
std::unique_ptr<ui::OSExchangeData> data,
const gfx::Point& location,
int operation,
ui::mojom::DragEventSource source) {
if (window_)
views::RunShellDrag(window_, std::move(data), location, operation, source);
}
void NativeWidgetAura::SchedulePaintInRect(const gfx::Rect& rect) {
if (window_)
window_->SchedulePaintInRect(rect);
}
void NativeWidgetAura::ScheduleLayout() {
// ScheduleDraw() triggers a callback to WindowDelegate::UpdateVisualState().
if (window_)
window_->ScheduleDraw();
}
void NativeWidgetAura::SetCursor(const ui::Cursor& cursor) {
cursor_ = cursor;
aura::client::CursorClient* cursor_client =
aura::client::GetCursorClient(window_->GetRootWindow());
if (cursor_client)
cursor_client->SetCursor(cursor);
}
bool NativeWidgetAura::IsMouseEventsEnabled() const {
if (!window_)
return false;
aura::client::CursorClient* cursor_client =
aura::client::GetCursorClient(window_->GetRootWindow());
return cursor_client ? cursor_client->IsMouseEventsEnabled() : true;
}
bool NativeWidgetAura::IsMouseButtonDown() const {
return aura::Env::GetInstance()->IsMouseButtonDown();
}
void NativeWidgetAura::ClearNativeFocus() {
aura::client::FocusClient* client = aura::client::GetFocusClient(window_);
if (window_ && client && window_->Contains(client->GetFocusedWindow()))
client->ResetFocusWithinActiveWindow(window_);
}
gfx::Rect NativeWidgetAura::GetWorkAreaBoundsInScreen() const {
if (!window_)
return gfx::Rect();
return display::Screen::GetScreen()
->GetDisplayNearestWindow(window_)
.work_area();
}
Widget::MoveLoopResult NativeWidgetAura::RunMoveLoop(
const gfx::Vector2d& drag_offset,
Widget::MoveLoopSource source,
Widget::MoveLoopEscapeBehavior escape_behavior) {
// |escape_behavior| is only needed on windows when running the native message
// loop.
if (!window_ || !window_->GetRootWindow())
return Widget::MoveLoopResult::kCanceled;
wm::WindowMoveClient* move_client =
wm::GetWindowMoveClient(window_->GetRootWindow());
if (!move_client)
return Widget::MoveLoopResult::kCanceled;
SetCapture();
wm::WindowMoveSource window_move_source =
source == Widget::MoveLoopSource::kMouse ? wm::WINDOW_MOVE_SOURCE_MOUSE
: wm::WINDOW_MOVE_SOURCE_TOUCH;
if (move_client->RunMoveLoop(window_, drag_offset, window_move_source) ==
wm::MOVE_SUCCESSFUL) {
return Widget::MoveLoopResult::kSuccessful;
}
return Widget::MoveLoopResult::kCanceled;
}
void NativeWidgetAura::EndMoveLoop() {
if (!window_ || !window_->GetRootWindow())
return;
wm::WindowMoveClient* move_client =
wm::GetWindowMoveClient(window_->GetRootWindow());
if (move_client)
move_client->EndMoveLoop();
}
void NativeWidgetAura::SetVisibilityChangedAnimationsEnabled(bool value) {
if (window_)
window_->SetProperty(aura::client::kAnimationsDisabledKey, !value);
}
void NativeWidgetAura::SetVisibilityAnimationDuration(
const base::TimeDelta& duration) {
wm::SetWindowVisibilityAnimationDuration(window_, duration);
}
void NativeWidgetAura::SetVisibilityAnimationTransition(
Widget::VisibilityTransition transition) {
wm::WindowVisibilityAnimationTransition wm_transition = wm::ANIMATE_NONE;
switch (transition) {
case Widget::ANIMATE_SHOW:
wm_transition = wm::ANIMATE_SHOW;
break;
case Widget::ANIMATE_HIDE:
wm_transition = wm::ANIMATE_HIDE;
break;
case Widget::ANIMATE_BOTH:
wm_transition = wm::ANIMATE_BOTH;
break;
case Widget::ANIMATE_NONE:
wm_transition = wm::ANIMATE_NONE;
break;
}
wm::SetWindowVisibilityAnimationTransition(window_, wm_transition);
}
bool NativeWidgetAura::IsTranslucentWindowOpacitySupported() const {
return true;
}
ui::GestureRecognizer* NativeWidgetAura::GetGestureRecognizer() {
return aura::Env::GetInstance()->gesture_recognizer();
}
ui::GestureConsumer* NativeWidgetAura::GetGestureConsumer() {
return window_;
}
void NativeWidgetAura::OnSizeConstraintsChanged() {
SetResizeBehaviorFromDelegate(GetWidget()->widget_delegate(), window_);
}
void NativeWidgetAura::OnNativeViewHierarchyWillChange() {}
void NativeWidgetAura::OnNativeViewHierarchyChanged() {}
std::string NativeWidgetAura::GetName() const {
return window_ ? window_->GetName() : std::string();
}
base::WeakPtr<internal::NativeWidgetPrivate> NativeWidgetAura::GetWeakPtr() {
return weak_factory.GetWeakPtr();
}
////////////////////////////////////////////////////////////////////////////////
// NativeWidgetAura, aura::WindowDelegate implementation:
gfx::Size NativeWidgetAura::GetMinimumSize() const {
return delegate_ ? delegate_->GetMinimumSize() : gfx::Size();
}
gfx::Size NativeWidgetAura::GetMaximumSize() const {
// Do no check maximizability as EXO clients can have maximum size and be
// maximizable at the same time.
return delegate_ ? delegate_->GetMaximumSize() : gfx::Size();
}
void NativeWidgetAura::OnBoundsChanged(const gfx::Rect& old_bounds,
const gfx::Rect& new_bounds) {
// Assume that if the old bounds was completely empty a move happened. This
// handles the case of a maximize animation acquiring the layer (acquiring a
// layer results in clearing the bounds).
if (delegate_ &&
(old_bounds.origin() != new_bounds.origin() ||
(old_bounds == gfx::Rect(0, 0, 0, 0) && !new_bounds.IsEmpty()))) {
delegate_->OnNativeWidgetMove();
}
if (delegate_ && (old_bounds.size() != new_bounds.size()))
delegate_->OnNativeWidgetSizeChanged(new_bounds.size());
}
gfx::NativeCursor NativeWidgetAura::GetCursor(const gfx::Point& point) {
return cursor_;
}
int NativeWidgetAura::GetNonClientComponent(const gfx::Point& point) const {
return delegate_ ? delegate_->GetNonClientComponent(point) : 0;
}
bool NativeWidgetAura::ShouldDescendIntoChildForEventHandling(
aura::Window* child,
const gfx::Point& location) {
return delegate_ ? delegate_->ShouldDescendIntoChildForEventHandling(
window_->layer(), child, child->layer(), location)
: false;
}
bool NativeWidgetAura::CanFocus() {
return ShouldActivate();
}
void NativeWidgetAura::OnCaptureLost() {
if (delegate_)
delegate_->OnMouseCaptureLost();
}
void NativeWidgetAura::OnPaint(const ui::PaintContext& context) {
if (delegate_)
delegate_->OnNativeWidgetPaint(context);
}
void NativeWidgetAura::OnDeviceScaleFactorChanged(
float old_device_scale_factor,
float new_device_scale_factor) {
GetWidget()->DeviceScaleFactorChanged(old_device_scale_factor,
new_device_scale_factor);
}
void NativeWidgetAura::OnWindowDestroying(aura::Window* window) {
window_->RemoveObserver(this);
if (wm::TransientWindowManager::GetIfExists(window_)) {
wm::TransientWindowManager::GetOrCreate(window_)->RemoveObserver(this);
}
if (delegate_)
delegate_->OnNativeWidgetDestroying();
// If the aura::Window is destroyed, we can no longer show tooltips.
tooltip_manager_.reset();
focus_manager_event_handler_.reset();
}
void NativeWidgetAura::OnWindowDestroyed(aura::Window* window) {
window_ = nullptr;
// |OnNativeWidgetDestroyed| may delete |this| if the object does not own
// itself.
bool should_delete_this =
(ownership_ == Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET) ||
(ownership_ == Widget::InitParams::CLIENT_OWNS_WIDGET);
if (delegate_)
delegate_->OnNativeWidgetDestroyed();
if (should_delete_this)
delete this;
}
void NativeWidgetAura::OnWindowTargetVisibilityChanged(bool visible) {
if (delegate_)
delegate_->OnNativeWidgetVisibilityChanged(visible);
}
bool NativeWidgetAura::HasHitTestMask() const {
return delegate_ ? delegate_->HasHitTestMask() : false;
}
void NativeWidgetAura::GetHitTestMask(SkPath* mask) const {
DCHECK(mask);
if (delegate_)
delegate_->GetHitTestMask(mask);
}
void NativeWidgetAura::UpdateVisualState() {
if (delegate_)
delegate_->LayoutRootViewIfNecessary();
}
////////////////////////////////////////////////////////////////////////////////
// NativeWidgetAura, aura::WindowObserver implementation:
void NativeWidgetAura::OnWindowPropertyChanged(aura::Window* window,
const void* key,
intptr_t old) {
if (delegate_ && key == aura::client::kShowStateKey)
delegate_->OnNativeWidgetWindowShowStateChanged();
if (delegate_ && key == aura::client::kWindowWorkspaceKey)
delegate_->OnNativeWidgetWorkspaceChanged();
}
void NativeWidgetAura::OnResizeLoopStarted(aura::Window* window) {
if (delegate_)
delegate_->OnNativeWidgetBeginUserBoundsChange();
}
void NativeWidgetAura::OnResizeLoopEnded(aura::Window* window) {
if (delegate_)
delegate_->OnNativeWidgetEndUserBoundsChange();
}
void NativeWidgetAura::OnWindowAddedToRootWindow(aura::Window* window) {
if (delegate_)
delegate_->OnNativeWidgetAddedToCompositor();
}
void NativeWidgetAura::OnWindowRemovingFromRootWindow(aura::Window* window,
aura::Window* new_root) {
if (delegate_)
delegate_->OnNativeWidgetRemovingFromCompositor();
}
////////////////////////////////////////////////////////////////////////////////
// NativeWidgetAura, ui::EventHandler implementation:
void NativeWidgetAura::OnKeyEvent(ui::KeyEvent* event) {
DCHECK(window_);
// Renderer may send a key event back to us if the key event wasn't handled,
// and the window may be invisible by that time.
if (!window_->IsVisible())
return;
if (delegate_)
delegate_->OnKeyEvent(event);
}
void NativeWidgetAura::OnMouseEvent(ui::MouseEvent* event) {
DCHECK(window_);
DCHECK(window_->IsVisible());
if (delegate_ && event->type() == ui::ET_MOUSEWHEEL) {
delegate_->OnMouseEvent(event);
return;
}
if (tooltip_manager_.get())
tooltip_manager_->UpdateTooltip();
TooltipManagerAura::UpdateTooltipManagerForCapture(this);
if (delegate_)
delegate_->OnMouseEvent(event);
}
void NativeWidgetAura::OnScrollEvent(ui::ScrollEvent* event) {
if (delegate_)
delegate_->OnScrollEvent(event);
}
void NativeWidgetAura::OnGestureEvent(ui::GestureEvent* event) {
DCHECK(window_);
DCHECK(window_->IsVisible() || event->IsEndingEvent());
if (delegate_)
delegate_->OnGestureEvent(event);
}
////////////////////////////////////////////////////////////////////////////////
// NativeWidgetAura, wm::ActivationDelegate implementation:
bool NativeWidgetAura::ShouldActivate() const {
return delegate_ ? delegate_->CanActivate() : false;
}
////////////////////////////////////////////////////////////////////////////////
// NativeWidgetAura, wm::ActivationChangeObserver implementation:
void NativeWidgetAura::OnWindowActivated(
wm::ActivationChangeObserver::ActivationReason,
aura::Window* gained_active,
aura::Window* lost_active) {
DCHECK(window_ == gained_active || window_ == lost_active);
if (GetWidget() && GetWidget()->GetFocusManager()) {
if (window_ == gained_active)
GetWidget()->GetFocusManager()->RestoreFocusedView();
else if (window_ == lost_active)
GetWidget()->GetFocusManager()->StoreFocusedView(true);
}
if (delegate_)
delegate_->OnNativeWidgetActivationChanged(window_ == gained_active);
}
////////////////////////////////////////////////////////////////////////////////
// NativeWidgetAura, aura::client::FocusChangeObserver:
void NativeWidgetAura::OnWindowFocused(aura::Window* gained_focus,
aura::Window* lost_focus) {
if (delegate_ && window_ == gained_focus)
delegate_->OnNativeFocus();
else if (delegate_ && window_ == lost_focus)
delegate_->OnNativeBlur();
}
////////////////////////////////////////////////////////////////////////////////
// NativeWidgetAura, aura::WindowDragDropDelegate implementation:
void NativeWidgetAura::OnDragEntered(const ui::DropTargetEvent& event) {
DCHECK(drop_helper_.get() != nullptr);
last_drop_operation_ = drop_helper_->OnDragOver(
event.data(), event.location(), event.source_operations());
}
aura::client::DragUpdateInfo NativeWidgetAura::OnDragUpdated(
const ui::DropTargetEvent& event) {
DCHECK(drop_helper_.get() != nullptr);
last_drop_operation_ = drop_helper_->OnDragOver(
event.data(), event.location(), event.source_operations());
return aura::client::DragUpdateInfo(
last_drop_operation_,
ui::DataTransferEndpoint(ui::EndpointType::kDefault));
}
void NativeWidgetAura::OnDragExited() {
DCHECK(drop_helper_.get() != nullptr);
drop_helper_->OnDragExit();
}
aura::client::DragDropDelegate::DropCallback NativeWidgetAura::GetDropCallback(
const ui::DropTargetEvent& event) {
DCHECK(drop_helper_);
return drop_helper_->GetDropCallback(event.data(), event.location(),
last_drop_operation_);
}
////////////////////////////////////////////////////////////////////////////////
// NativeWidgetAura, wm::TransientWindowObserver implementation:
void NativeWidgetAura::OnTransientParentChanged(aura::Window* new_parent) {
if (delegate_)
delegate_->OnNativeWidgetParentChanged(new_parent);
}
////////////////////////////////////////////////////////////////////////////////
// NativeWidgetAura, protected:
NativeWidgetAura::~NativeWidgetAura() {
if (ownership_ == Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET) {
// `drop_helper_` and `window_reorderer_` hold a pointer to `delegate_`'s
// root view. Reset them before deleting `delegate_` to avoid holding a
// briefly dangling ptr.
drop_helper_.reset();
window_reorderer_.reset();
owned_delegate_.reset();
} else {
CloseNow();
}
}
////////////////////////////////////////////////////////////////////////////////
// NativeWidgetAura, private:
void NativeWidgetAura::SetInitialFocus(ui::WindowShowState show_state) {
// The window does not get keyboard messages unless we focus it.
if (!GetWidget()->SetInitialFocus(show_state))
window_->Focus();
}
////////////////////////////////////////////////////////////////////////////////
// Widget, public:
namespace {
#if BUILDFLAG(ENABLE_DESKTOP_AURA) && (BUILDFLAG(IS_WIN) || BUILDFLAG(IS_OZONE))
void CloseWindow(aura::Window* window) {
if (window) {
Widget* widget = Widget::GetWidgetForNativeView(window);
if (widget && widget->is_secondary_widget())
// To avoid the delay in shutdown caused by using Close which may wait
// for animations, use CloseNow. Because this is only used on secondary
// widgets it seems relatively safe to skip the extra processing of
// Close.
widget->CloseNow();
}
}
#endif
#if BUILDFLAG(IS_WIN)
BOOL CALLBACK WindowCallbackProc(HWND hwnd, LPARAM lParam) {
aura::Window* root_window =
DesktopWindowTreeHostWin::GetContentWindowForHWND(hwnd);
CloseWindow(root_window);
return TRUE;
}
#endif
} // namespace
// static
void Widget::CloseAllSecondaryWidgets() {
#if BUILDFLAG(IS_WIN)
EnumThreadWindows(GetCurrentThreadId(), WindowCallbackProc, 0);
#endif
#if BUILDFLAG(ENABLE_DESKTOP_AURA) && BUILDFLAG(IS_OZONE)
DesktopWindowTreeHostPlatform::CleanUpWindowList(CloseWindow);
#endif
}
namespace internal {
////////////////////////////////////////////////////////////////////////////////
// internal::NativeWidgetPrivate, public:
// static
NativeWidgetPrivate* NativeWidgetPrivate::CreateNativeWidget(
internal::NativeWidgetDelegate* delegate) {
return new NativeWidgetAura(delegate);
}
// static
NativeWidgetPrivate* NativeWidgetPrivate::GetNativeWidgetForNativeView(
gfx::NativeView native_view) {
return native_view->GetProperty(kNativeWidgetPrivateKey);
}
// static
NativeWidgetPrivate* NativeWidgetPrivate::GetNativeWidgetForNativeWindow(
gfx::NativeWindow native_window) {
return native_window->GetProperty(kNativeWidgetPrivateKey);
}
// static
NativeWidgetPrivate* NativeWidgetPrivate::GetTopLevelNativeWidget(
gfx::NativeView native_view) {
aura::Window* window = native_view;
NativeWidgetPrivate* top_level_native_widget = nullptr;
while (window) {
NativeWidgetPrivate* native_widget = GetNativeWidgetForNativeView(window);
if (native_widget)
top_level_native_widget = native_widget;
window = window->parent();
}
return top_level_native_widget;
}
// static
void NativeWidgetPrivate::GetAllChildWidgets(gfx::NativeView native_view,
Widget::Widgets* children) {
{
// Code expects widget for |native_view| to be added to |children|.
NativeWidgetPrivate* native_widget = static_cast<NativeWidgetPrivate*>(
GetNativeWidgetForNativeView(native_view));
if (native_widget && native_widget->GetWidget())
children->insert(native_widget->GetWidget());
}
for (auto* child_window : native_view->children())
GetAllChildWidgets(child_window, children);
}
// static
void NativeWidgetPrivate::GetAllOwnedWidgets(gfx::NativeView native_view,
Widget::Widgets* owned) {
// Add all owned widgets.
for (aura::Window* transient_child : wm::GetTransientChildren(native_view)) {
NativeWidgetPrivate* native_widget = static_cast<NativeWidgetPrivate*>(
GetNativeWidgetForNativeView(transient_child));
if (native_widget && native_widget->GetWidget())
owned->insert(native_widget->GetWidget());
GetAllOwnedWidgets(transient_child, owned);
}
// Add all child windows.
for (aura::Window* child : native_view->children())
GetAllChildWidgets(child, owned);
}
// static
void NativeWidgetPrivate::ReparentNativeView(gfx::NativeView native_view,
gfx::NativeView new_parent) {
DCHECK(native_view != new_parent);
gfx::NativeView previous_parent = native_view->parent();
if (previous_parent == new_parent)
return;
Widget::Widgets widgets;
GetAllChildWidgets(native_view, &widgets);
// First notify all the widgets that they are being disassociated
// from their previous parent.
for (auto* widget : widgets)
widget->NotifyNativeViewHierarchyWillChange();
if (new_parent) {
new_parent->AddChild(native_view);
} else {
// The following looks weird, but it's the equivalent of what aura has
// always done. (The previous behaviour of aura::Window::SetParent() used
// NULL as a special value that meant ask the WindowParentingClient where
// things should go.)
//
// This probably isn't strictly correct, but its an invariant that a Window
// in use will be attached to a RootWindow, so we can't just call
// RemoveChild here. The only possible thing that could assign a RootWindow
// in this case is the stacking client of the current RootWindow. This
// matches our previous behaviour; the global stacking client would almost
// always reattach the window to the same RootWindow.
aura::Window* root_window = native_view->GetRootWindow();
aura::client::ParentWindowWithContext(native_view, root_window,
root_window->GetBoundsInScreen());
}
// And now, notify them that they have a brand new parent.
for (auto* widget : widgets)
widget->NotifyNativeViewHierarchyChanged();
}
// static
gfx::NativeView NativeWidgetPrivate::GetGlobalCapture(
gfx::NativeView native_view) {
aura::client::CaptureClient* capture_client =
aura::client::GetCaptureClient(native_view->GetRootWindow());
if (!capture_client)
return nullptr;
return capture_client->GetGlobalCaptureWindow();
}
} // namespace internal
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/native_widget_aura.cc | C++ | unknown | 47,930 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_WIDGET_NATIVE_WIDGET_AURA_H_
#define UI_VIEWS_WIDGET_NATIVE_WIDGET_AURA_H_
#include <memory>
#include <string>
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "build/build_config.h"
#include "ui/aura/client/drag_drop_delegate.h"
#include "ui/aura/client/focus_change_observer.h"
#include "ui/aura/window_delegate.h"
#include "ui/aura/window_observer.h"
#include "ui/base/cursor/cursor.h"
#include "ui/events/event_constants.h"
#include "ui/views/views_export.h"
#include "ui/views/widget/native_widget_private.h"
#include "ui/wm/core/transient_window_observer.h"
#include "ui/wm/public/activation_change_observer.h"
#include "ui/wm/public/activation_delegate.h"
#if BUILDFLAG(IS_MAC)
#error "This file must not be included on macOS; Chromium Mac doesn't use Aura."
#endif
namespace aura {
class Window;
}
namespace views {
class DropHelper;
class FocusManagerEventHandler;
class TooltipManagerAura;
class WindowReorderer;
class VIEWS_EXPORT NativeWidgetAura : public internal::NativeWidgetPrivate,
public aura::WindowDelegate,
public aura::WindowObserver,
public wm::ActivationDelegate,
public wm::ActivationChangeObserver,
public wm::TransientWindowObserver,
public aura::client::FocusChangeObserver,
public aura::client::DragDropDelegate {
public:
explicit NativeWidgetAura(internal::NativeWidgetDelegate* delegate);
NativeWidgetAura(const NativeWidgetAura&) = delete;
NativeWidgetAura& operator=(const NativeWidgetAura&) = delete;
// Called internally by NativeWidgetAura and DesktopNativeWidgetAura to
// associate |native_widget| with |window|.
static void RegisterNativeWidgetForWindow(
internal::NativeWidgetPrivate* native_widget,
aura::Window* window);
// Assign an icon to aura window.
static void AssignIconToAuraWindow(aura::Window* window,
const gfx::ImageSkia& window_icon,
const gfx::ImageSkia& app_icon);
// If necessary, sets the ShadowElevation of |window| from |params|.
static void SetShadowElevationFromInitParams(
aura::Window* window,
const Widget::InitParams& params);
// Sets the window property aura::client::kResizeBehaviorKey based on the
// values from the delegate.
static void SetResizeBehaviorFromDelegate(WidgetDelegate* delegate,
aura::Window* window);
// internal::NativeWidgetPrivate:
void InitNativeWidget(Widget::InitParams params) override;
void OnWidgetInitDone() override;
std::unique_ptr<NonClientFrameView> CreateNonClientFrameView() override;
bool ShouldUseNativeFrame() const override;
bool ShouldWindowContentsBeTransparent() const override;
void FrameTypeChanged() override;
Widget* GetWidget() override;
const Widget* GetWidget() const override;
gfx::NativeView GetNativeView() const override;
gfx::NativeWindow GetNativeWindow() const override;
Widget* GetTopLevelWidget() override;
const ui::Compositor* GetCompositor() const override;
const ui::Layer* GetLayer() const override;
void ReorderNativeViews() override;
void ViewRemoved(View* view) override;
void SetNativeWindowProperty(const char* name, void* value) override;
void* GetNativeWindowProperty(const char* name) const override;
TooltipManager* GetTooltipManager() const override;
void SetCapture() override;
void ReleaseCapture() override;
bool HasCapture() const override;
ui::InputMethod* GetInputMethod() override;
void CenterWindow(const gfx::Size& size) override;
void GetWindowPlacement(gfx::Rect* bounds,
ui::WindowShowState* maximized) const override;
bool SetWindowTitle(const std::u16string& title) override;
void SetWindowIcons(const gfx::ImageSkia& window_icon,
const gfx::ImageSkia& app_icon) override;
const gfx::ImageSkia* GetWindowIcon() override;
const gfx::ImageSkia* GetWindowAppIcon() override;
void InitModalType(ui::ModalType modal_type) override;
gfx::Rect GetWindowBoundsInScreen() const override;
gfx::Rect GetClientAreaBoundsInScreen() const override;
gfx::Rect GetRestoredBounds() const override;
std::string GetWorkspace() const override;
void SetBounds(const gfx::Rect& bounds) override;
void SetBoundsConstrained(const gfx::Rect& bounds) override;
void SetSize(const gfx::Size& size) override;
void StackAbove(gfx::NativeView native_view) override;
void StackAtTop() override;
bool IsStackedAbove(gfx::NativeView widget) override;
void SetShape(std::unique_ptr<Widget::ShapeRects> shape) override;
void Close() override;
void CloseNow() override;
void Show(ui::WindowShowState show_state,
const gfx::Rect& restore_bounds) override;
void Hide() override;
bool IsVisible() const override;
void Activate() override;
void Deactivate() override;
bool IsActive() const override;
void SetZOrderLevel(ui::ZOrderLevel order) override;
ui::ZOrderLevel GetZOrderLevel() const override;
void SetVisibleOnAllWorkspaces(bool always_visible) override;
bool IsVisibleOnAllWorkspaces() const override;
void Maximize() override;
void Minimize() override;
bool IsMaximized() const override;
bool IsMinimized() const override;
void Restore() override;
void SetFullscreen(bool fullscreen, int64_t target_display_id) override;
bool IsFullscreen() const override;
void SetCanAppearInExistingFullscreenSpaces(
bool can_appear_in_existing_fullscreen_spaces) override;
void SetOpacity(float opacity) override;
void SetAspectRatio(const gfx::SizeF& aspect_ratio,
const gfx::Size& excluded_margin) override;
void FlashFrame(bool flash_frame) override;
void RunShellDrag(View* view,
std::unique_ptr<ui::OSExchangeData> data,
const gfx::Point& location,
int operation,
ui::mojom::DragEventSource source) override;
void SchedulePaintInRect(const gfx::Rect& rect) override;
void ScheduleLayout() override;
void SetCursor(const ui::Cursor& cursor) override;
bool IsMouseEventsEnabled() const override;
bool IsMouseButtonDown() const override;
void ClearNativeFocus() override;
gfx::Rect GetWorkAreaBoundsInScreen() const override;
Widget::MoveLoopResult RunMoveLoop(
const gfx::Vector2d& drag_offset,
Widget::MoveLoopSource source,
Widget::MoveLoopEscapeBehavior escape_behavior) override;
void EndMoveLoop() override;
void SetVisibilityChangedAnimationsEnabled(bool value) override;
void SetVisibilityAnimationDuration(const base::TimeDelta& duration) override;
void SetVisibilityAnimationTransition(
Widget::VisibilityTransition transition) override;
bool IsTranslucentWindowOpacitySupported() const override;
ui::GestureRecognizer* GetGestureRecognizer() override;
ui::GestureConsumer* GetGestureConsumer() override;
void OnSizeConstraintsChanged() override;
void OnNativeViewHierarchyWillChange() override;
void OnNativeViewHierarchyChanged() override;
std::string GetName() const override;
base::WeakPtr<internal::NativeWidgetPrivate> GetWeakPtr() override;
// aura::WindowDelegate:
gfx::Size GetMinimumSize() const override;
gfx::Size GetMaximumSize() const override;
void OnBoundsChanged(const gfx::Rect& old_bounds,
const gfx::Rect& new_bounds) override;
gfx::NativeCursor GetCursor(const gfx::Point& point) override;
int GetNonClientComponent(const gfx::Point& point) const override;
bool ShouldDescendIntoChildForEventHandling(
aura::Window* child,
const gfx::Point& location) override;
bool CanFocus() override;
void OnCaptureLost() override;
void OnPaint(const ui::PaintContext& context) override;
void OnDeviceScaleFactorChanged(float old_device_scale_factor,
float new_device_scale_factor) override;
void OnWindowDestroying(aura::Window* window) override;
void OnWindowDestroyed(aura::Window* window) override;
void OnWindowTargetVisibilityChanged(bool visible) override;
bool HasHitTestMask() const override;
void GetHitTestMask(SkPath* mask) const override;
void UpdateVisualState() override;
// aura::WindowObserver:
void OnWindowPropertyChanged(aura::Window* window,
const void* key,
intptr_t old) override;
void OnResizeLoopStarted(aura::Window* window) override;
void OnResizeLoopEnded(aura::Window* window) override;
void OnWindowAddedToRootWindow(aura::Window* window) override;
void OnWindowRemovingFromRootWindow(aura::Window* window,
aura::Window* new_root) override;
// ui::EventHandler:
void OnKeyEvent(ui::KeyEvent* event) override;
void OnMouseEvent(ui::MouseEvent* event) override;
void OnScrollEvent(ui::ScrollEvent* event) override;
void OnGestureEvent(ui::GestureEvent* event) override;
// wm::ActivationDelegate:
bool ShouldActivate() const override;
// wm::ActivationChangeObserver:
void OnWindowActivated(wm::ActivationChangeObserver::ActivationReason reason,
aura::Window* gained_active,
aura::Window* lost_active) override;
// aura::client::FocusChangeObserver:
void OnWindowFocused(aura::Window* gained_focus,
aura::Window* lost_focus) override;
// aura::client::DragDropDelegate:
void OnDragEntered(const ui::DropTargetEvent& event) override;
aura::client::DragUpdateInfo OnDragUpdated(
const ui::DropTargetEvent& event) override;
void OnDragExited() override;
aura::client::DragDropDelegate::DropCallback GetDropCallback(
const ui::DropTargetEvent& event) override;
// aura::TransientWindowObserver:
void OnTransientParentChanged(aura::Window* new_parent) override;
protected:
~NativeWidgetAura() override;
internal::NativeWidgetDelegate* delegate() { return delegate_.get(); }
private:
void SetInitialFocus(ui::WindowShowState show_state);
base::WeakPtr<internal::NativeWidgetDelegate> delegate_;
std::unique_ptr<internal::NativeWidgetDelegate> owned_delegate_;
// WARNING: set to NULL when destroyed. As the Widget is not necessarily
// destroyed along with |window_| all usage of |window_| should first verify
// non-NULL.
raw_ptr<aura::Window> window_;
// See class documentation for Widget in widget.h for a note about ownership.
Widget::InitParams::Ownership ownership_ =
Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET;
ui::Cursor cursor_;
std::unique_ptr<TooltipManagerAura> tooltip_manager_;
// Reorders child windows of |window_| associated with a view based on the
// order of the associated views in the widget's view hierarchy.
std::unique_ptr<WindowReorderer> window_reorderer_;
std::unique_ptr<DropHelper> drop_helper_;
int last_drop_operation_;
// Native widget's handler to receive events before the event target.
std::unique_ptr<FocusManagerEventHandler> focus_manager_event_handler_;
// The following factory is used to provide references to the NativeWidgetAura
// instance. We need a separate factory from the |close_widget_factory_|
// because the close widget factory is currently used to ensure that the
// CloseNow task is only posted once. We check whether there are any weak
// pointers from close_widget_factory_| before posting
// the CloseNow task, so we can't have any other weak pointers for this to
// work properly. CloseNow can destroy the aura::Window
// which will not destroy the NativeWidget if WIDGET_OWNS_NATIVE_WIDGET, and
// we need to make sure we do not attempt to destroy the aura::Window twice.
// TODO(1346381): The two factories can be combined if the
// WIDGET_OWNS_NATIVE_WIDGET is removed.
base::WeakPtrFactory<NativeWidgetAura> weak_factory{this};
};
} // namespace views
#endif // UI_VIEWS_WIDGET_NATIVE_WIDGET_AURA_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/native_widget_aura.h | C++ | unknown | 12,351 |
// 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/widget/native_widget_aura.h"
#include "ui/aura/window.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/test/native_widget_factory.h"
#include "ui/views/test/widget_test.h"
#include "ui/wm/core/base_focus_rules.h"
#include "ui/wm/core/focus_controller.h"
namespace views::test {
namespace {
class TestFocusRules : public wm::BaseFocusRules {
public:
TestFocusRules() = default;
TestFocusRules(const TestFocusRules&) = delete;
TestFocusRules& operator=(const TestFocusRules&) = delete;
~TestFocusRules() override = default;
void set_can_activate(bool can_activate) { can_activate_ = can_activate; }
// wm::BaseFocusRules overrides:
bool SupportsChildActivation(const aura::Window* window) const override {
return true;
}
bool CanActivateWindow(const aura::Window* window) const override {
return can_activate_;
}
private:
bool can_activate_ = true;
};
} // namespace
using NativeWidgetAuraTest = DesktopWidgetTestInteractive;
// When requesting view focus from a non-active top level widget, focus is not
// instantly given. Instead, the view is firstly stored and then it is attempted
// to activate the widget. If widget is currently not activatable, focus should
// not be grabbed. And focus will be given/restored the next time the widget is
// made active. (crbug.com/621791)
TEST_F(NativeWidgetAuraTest, NonActiveWindowRequestImeFocus) {
TestFocusRules* test_focus_rules = new TestFocusRules;
std::unique_ptr<wm::FocusController> focus_controller =
std::make_unique<wm::FocusController>(test_focus_rules);
wm::SetActivationClient(GetContext(), focus_controller.get());
Widget* widget1 = new Widget;
Widget::InitParams params1(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
params1.context = GetContext();
params1.native_widget =
CreatePlatformNativeWidgetImpl(widget1, kDefault, nullptr);
params1.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget1->Init(std::move(params1));
Textfield* textfield1 = new Textfield;
widget1->GetRootView()->AddChildView(textfield1);
Widget* widget2 = new Widget;
Widget::InitParams params2(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
params2.context = GetContext();
params2.native_widget =
CreatePlatformNativeWidgetImpl(widget2, kDefault, nullptr);
params2.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget2->Init(std::move(params2));
Textfield* textfield2a = new Textfield;
widget2->GetRootView()->AddChildView(textfield2a);
Textfield* textfield2b = new Textfield;
widget2->GetRootView()->AddChildView(textfield2b);
views::test::WidgetActivationWaiter waiter1(widget1, true);
widget1->Show();
waiter1.Wait();
textfield1->RequestFocus();
EXPECT_TRUE(textfield1->HasFocus());
EXPECT_FALSE(textfield2a->HasFocus());
EXPECT_FALSE(textfield2b->HasFocus());
// Don't allow window activation at this step.
test_focus_rules->set_can_activate(false);
textfield2a->RequestFocus();
EXPECT_TRUE(textfield1->HasFocus());
EXPECT_FALSE(textfield2a->HasFocus());
EXPECT_FALSE(textfield2b->HasFocus());
// Allow window activation and |widget2| gets activated at this step, focus
// should be properly restored.
test_focus_rules->set_can_activate(true);
views::test::WidgetActivationWaiter waiter2(widget2, true);
widget2->Activate();
waiter2.Wait();
EXPECT_TRUE(textfield2a->HasFocus());
EXPECT_FALSE(textfield2b->HasFocus());
EXPECT_FALSE(textfield1->HasFocus());
widget1->CloseNow();
widget2->CloseNow();
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/native_widget_aura_interactive_uitest.cc | C++ | unknown | 3,734 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/widget/native_widget_aura.h"
#include <memory>
#include <set>
#include <utility>
#include "base/command_line.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/aura/client/aura_constants.h"
#include "ui/aura/env.h"
#include "ui/aura/layout_manager.h"
#include "ui/aura/window.h"
#include "ui/aura/window_observer.h"
#include "ui/aura/window_tree_host.h"
#include "ui/compositor/layer.h"
#include "ui/events/event.h"
#include "ui/events/event_utils.h"
#include "ui/events/test/event_generator.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/widget/root_view.h"
#include "ui/views/widget/unique_widget_ptr.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/wm/core/base_focus_rules.h"
#include "ui/wm/core/default_activation_client.h"
#include "ui/wm/core/focus_controller.h"
#include "ui/wm/core/transient_window_manager.h"
namespace views {
namespace {
NativeWidgetAura* Init(aura::Window* parent, Widget* widget) {
Widget::InitParams params(Widget::InitParams::TYPE_POPUP);
params.parent = parent;
widget->Init(std::move(params));
return static_cast<NativeWidgetAura*>(widget->native_widget());
}
// TestFocusRules is intended to provide a way to manually set a window's
// activatability so that the focus rules can be tested.
class TestFocusRules : public wm::BaseFocusRules {
public:
TestFocusRules() = default;
TestFocusRules(const TestFocusRules&) = delete;
TestFocusRules& operator=(const TestFocusRules&) = delete;
~TestFocusRules() override = default;
void set_can_activate(bool can_activate) { can_activate_ = can_activate; }
// wm::BaseFocusRules overrides:
bool SupportsChildActivation(const aura::Window* window) const override {
return true;
}
bool CanActivateWindow(const aura::Window* window) const override {
return can_activate_;
}
private:
bool can_activate_ = true;
};
class NativeWidgetAuraTest : public ViewsTestBase {
public:
NativeWidgetAuraTest() = default;
NativeWidgetAuraTest(const NativeWidgetAuraTest&) = delete;
NativeWidgetAuraTest& operator=(const NativeWidgetAuraTest&) = delete;
~NativeWidgetAuraTest() override = default;
TestFocusRules* test_focus_rules() { return test_focus_rules_; }
// testing::Test overrides:
void SetUp() override {
ViewsTestBase::SetUp();
test_focus_rules_ = new TestFocusRules;
focus_controller_ =
std::make_unique<wm::FocusController>(test_focus_rules_);
wm::SetActivationClient(root_window(), focus_controller_.get());
host()->SetBoundsInPixels(gfx::Rect(640, 480));
}
private:
std::unique_ptr<wm::FocusController> focus_controller_;
raw_ptr<TestFocusRules> test_focus_rules_;
};
TEST_F(NativeWidgetAuraTest, CenterWindowLargeParent) {
// Make a parent window larger than the host represented by
// WindowEventDispatcher.
auto parent = std::make_unique<aura::Window>(nullptr);
parent->Init(ui::LAYER_NOT_DRAWN);
parent->SetBounds(gfx::Rect(0, 0, 1024, 800));
UniqueWidgetPtr widget = std::make_unique<Widget>();
NativeWidgetAura* window = Init(parent.get(), widget.get());
window->CenterWindow(gfx::Size(100, 100));
EXPECT_EQ(gfx::Rect((640 - 100) / 2, (480 - 100) / 2, 100, 100),
window->GetNativeWindow()->bounds());
}
TEST_F(NativeWidgetAuraTest, CenterWindowSmallParent) {
// Make a parent window smaller than the host represented by
// WindowEventDispatcher.
auto parent = std::make_unique<aura::Window>(nullptr);
parent->Init(ui::LAYER_NOT_DRAWN);
parent->SetBounds(gfx::Rect(0, 0, 480, 320));
UniqueWidgetPtr widget = std::make_unique<Widget>();
NativeWidgetAura* window = Init(parent.get(), widget.get());
window->CenterWindow(gfx::Size(100, 100));
EXPECT_EQ(gfx::Rect((480 - 100) / 2, (320 - 100) / 2, 100, 100),
window->GetNativeWindow()->bounds());
}
// Verifies CenterWindow() constrains to parent size.
TEST_F(NativeWidgetAuraTest, CenterWindowSmallParentNotAtOrigin) {
// Make a parent window smaller than the host represented by
// WindowEventDispatcher and offset it slightly from the origin.
auto parent = std::make_unique<aura::Window>(nullptr);
parent->Init(ui::LAYER_NOT_DRAWN);
parent->SetBounds(gfx::Rect(20, 40, 480, 320));
UniqueWidgetPtr widget = std::make_unique<Widget>();
NativeWidgetAura* window = Init(parent.get(), widget.get());
window->CenterWindow(gfx::Size(500, 600));
// |window| should be no bigger than |parent|.
EXPECT_EQ("20,40 480x320", window->GetNativeWindow()->bounds().ToString());
}
// View which handles both mouse and gesture events.
class EventHandlingView : public View {
public:
EventHandlingView() = default;
EventHandlingView(const EventHandlingView&) = delete;
EventHandlingView& operator=(const EventHandlingView&) = delete;
~EventHandlingView() override = default;
// Returns whether an event specified by `type_to_query` has been handled.
bool HandledEventBefore(ui::EventType type_to_query) const {
return handled_gestures_set_.find(type_to_query) !=
handled_gestures_set_.cend();
}
// View:
const char* GetClassName() const override { return "EventHandlingView"; }
void OnMouseEvent(ui::MouseEvent* event) override { event->SetHandled(); }
void OnGestureEvent(ui::GestureEvent* event) override {
// Record the handled gesture event.
const ui::EventType event_type = event->type();
if (handled_gestures_set_.find(event_type) ==
handled_gestures_set_.cend()) {
EXPECT_TRUE(handled_gestures_set_.insert(event->type()).second);
} else {
// Only ET_GESTURE_SCROLL_UPDATE events can be received more than once.
EXPECT_EQ(ui::ET_GESTURE_SCROLL_UPDATE, event->type());
}
event->SetHandled();
}
private:
std::set<ui::EventType> handled_gestures_set_;
};
// Verifies that when the mouse click interrupts the gesture scroll, the view
// where the gesture scroll starts should receive the scroll end event.
TEST_F(NativeWidgetAuraTest, MouseClickInterruptsGestureScroll) {
Widget::InitParams init_params =
CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
init_params.bounds = gfx::Rect(100, 100);
UniqueWidgetPtr widget = std::make_unique<Widget>();
widget->Init(std::move(init_params));
widget->Show();
auto* contents_view = widget->SetContentsView(std::make_unique<View>());
auto* child_view =
contents_view->AddChildView(std::make_unique<EventHandlingView>());
child_view->SetBoundsRect(gfx::Rect(gfx::Size{50, 50}));
auto scroll_callback = [](ui::test::EventGenerator* event_generator,
int* step_count, ui::EventType event_type,
const gfx::Vector2dF& offset) {
if (event_type != ui::ET_GESTURE_SCROLL_UPDATE)
return;
*step_count -= 1;
if (*step_count)
return;
// Do not interrupt the gesture scroll until the last gesture update event
// is handled.
DCHECK_EQ(0, *step_count);
event_generator->MoveMouseTo(event_generator->current_screen_location());
event_generator->ClickLeftButton();
};
const gfx::Point center_point = child_view->GetBoundsInScreen().CenterPoint();
gfx::Point target_point = center_point;
target_point.Offset(0, 20);
int step_count = 10;
ui::test::EventGenerator generator(widget->GetNativeView()->GetRootWindow());
generator.GestureScrollSequenceWithCallback(
center_point, target_point,
/*duration=*/base::Milliseconds(100), step_count,
base::BindRepeating(scroll_callback, &generator, &step_count));
// Verify that `child_view` receives gesture end events.
EXPECT_TRUE(child_view->HandledEventBefore(ui::ET_GESTURE_SCROLL_END));
EXPECT_TRUE(child_view->HandledEventBefore(ui::ET_GESTURE_END));
}
TEST_F(NativeWidgetAuraTest, CreateMinimized) {
Widget::InitParams params(Widget::InitParams::TYPE_WINDOW);
params.parent = nullptr;
params.context = root_window();
params.show_state = ui::SHOW_STATE_MINIMIZED;
params.bounds.SetRect(0, 0, 1024, 800);
UniqueWidgetPtr widget = std::make_unique<Widget>();
widget->Init(std::move(params));
widget->Show();
EXPECT_TRUE(widget->IsMinimized());
}
// Tests that GetRestoreBounds returns the window bounds even if the window is
// transformed.
TEST_F(NativeWidgetAuraTest, RestoreBounds) {
Widget::InitParams params(Widget::InitParams::TYPE_WINDOW);
params.parent = nullptr;
params.context = root_window();
params.bounds.SetRect(0, 0, 400, 400);
UniqueWidgetPtr widget = std::make_unique<Widget>();
widget->Init(std::move(params));
widget->Show();
EXPECT_EQ(gfx::Rect(400, 400), widget->GetRestoredBounds());
gfx::Transform transform;
transform.Translate(100.f, 100.f);
widget->GetNativeWindow()->SetTransform(transform);
EXPECT_EQ(gfx::Rect(400, 400), widget->GetRestoredBounds());
}
TEST_F(NativeWidgetAuraTest, GetWorkspace) {
Widget::InitParams params(Widget::InitParams::TYPE_WINDOW);
params.parent = nullptr;
params.context = root_window();
params.show_state = ui::SHOW_STATE_MINIMIZED;
params.bounds.SetRect(0, 0, 1024, 800);
UniqueWidgetPtr widget = std::make_unique<Widget>();
widget->Init(std::move(params));
widget->Show();
widget->GetNativeWindow()->SetProperty(
aura::client::kWindowWorkspaceKey,
aura::client::kWindowWorkspaceUnassignedWorkspace);
EXPECT_EQ("", widget->GetWorkspace());
widget->GetNativeWindow()->SetProperty(
aura::client::kWindowWorkspaceKey,
aura::client::kWindowWorkspaceVisibleOnAllWorkspaces);
EXPECT_EQ("", widget->GetWorkspace());
const int desk_index = 1;
widget->GetNativeWindow()->SetProperty(aura::client::kWindowWorkspaceKey,
desk_index);
EXPECT_EQ(base::NumberToString(desk_index), widget->GetWorkspace());
}
// A WindowObserver that counts kShowStateKey property changes.
class TestWindowObserver : public aura::WindowObserver {
public:
explicit TestWindowObserver(gfx::NativeWindow window) : window_(window) {
window_->AddObserver(this);
}
TestWindowObserver(const TestWindowObserver&) = delete;
TestWindowObserver& operator=(const TestWindowObserver&) = delete;
~TestWindowObserver() override { window_->RemoveObserver(this); }
// aura::WindowObserver:
void OnWindowPropertyChanged(aura::Window* window,
const void* key,
intptr_t old) override {
if (key != aura::client::kShowStateKey)
return;
count_++;
state_ = window_->GetProperty(aura::client::kShowStateKey);
}
int count() const { return count_; }
ui::WindowShowState state() const { return state_; }
void Reset() { count_ = 0; }
private:
gfx::NativeWindow window_;
int count_ = 0;
ui::WindowShowState state_ = ui::WindowShowState::SHOW_STATE_DEFAULT;
};
// Tests that window transitions from normal to minimized and back do not
// involve extra show state transitions.
TEST_F(NativeWidgetAuraTest, ToggleState) {
Widget::InitParams params(Widget::InitParams::TYPE_WINDOW);
params.parent = nullptr;
params.context = root_window();
params.show_state = ui::SHOW_STATE_NORMAL;
params.bounds.SetRect(0, 0, 1024, 800);
UniqueWidgetPtr widget = std::make_unique<Widget>();
widget->Init(std::move(params));
auto observer =
std::make_unique<TestWindowObserver>(widget->GetNativeWindow());
widget->Show();
EXPECT_FALSE(widget->IsMinimized());
EXPECT_EQ(0, observer->count());
EXPECT_EQ(ui::WindowShowState::SHOW_STATE_DEFAULT, observer->state());
widget->Minimize();
EXPECT_TRUE(widget->IsMinimized());
EXPECT_EQ(1, observer->count());
EXPECT_EQ(ui::WindowShowState::SHOW_STATE_MINIMIZED, observer->state());
observer->Reset();
widget->Show();
widget->Restore();
EXPECT_EQ(1, observer->count());
EXPECT_EQ(ui::WindowShowState::SHOW_STATE_NORMAL, observer->state());
observer.reset();
EXPECT_FALSE(widget->IsMinimized());
}
class TestLayoutManagerBase : public aura::LayoutManager {
public:
TestLayoutManagerBase() = default;
TestLayoutManagerBase(const TestLayoutManagerBase&) = delete;
TestLayoutManagerBase& operator=(const TestLayoutManagerBase&) = delete;
~TestLayoutManagerBase() override = default;
// aura::LayoutManager:
void OnWindowResized() override {}
void OnWindowAddedToLayout(aura::Window* child) override {}
void OnWillRemoveWindowFromLayout(aura::Window* child) override {}
void OnWindowRemovedFromLayout(aura::Window* child) override {}
void OnChildWindowVisibilityChanged(aura::Window* child,
bool visible) override {}
void SetChildBounds(aura::Window* child,
const gfx::Rect& requested_bounds) override {}
};
// Used by ShowMaximizedDoesntBounceAround. See it for details.
class MaximizeLayoutManager : public TestLayoutManagerBase {
public:
MaximizeLayoutManager() = default;
MaximizeLayoutManager(const MaximizeLayoutManager&) = delete;
MaximizeLayoutManager& operator=(const MaximizeLayoutManager&) = delete;
~MaximizeLayoutManager() override = default;
private:
// aura::LayoutManager:
void OnWindowAddedToLayout(aura::Window* child) override {
// This simulates what happens when adding a maximized window.
SetChildBoundsDirect(child, gfx::Rect(0, 0, 300, 300));
}
};
// This simulates BrowserView, which creates a custom RootView so that
// OnNativeWidgetSizeChanged that is invoked during Init matters.
class TestWidget : public Widget {
public:
TestWidget() = default;
TestWidget(const TestWidget&) = delete;
TestWidget& operator=(const TestWidget&) = delete;
// Returns true if the size changes to a non-empty size, and then to another
// size.
bool did_size_change_more_than_once() const {
return did_size_change_more_than_once_;
}
void OnNativeWidgetSizeChanged(const gfx::Size& new_size) override {
if (last_size_.IsEmpty())
last_size_ = new_size;
else if (!did_size_change_more_than_once_ && new_size != last_size_)
did_size_change_more_than_once_ = true;
Widget::OnNativeWidgetSizeChanged(new_size);
}
private:
bool did_size_change_more_than_once_ = false;
gfx::Size last_size_;
};
// Verifies the size of the widget doesn't change more than once during Init if
// the window ends up maximized. This is important as otherwise
// RenderWidgetHostViewAura ends up getting resized during construction, which
// leads to noticable flashes.
TEST_F(NativeWidgetAuraTest, ShowMaximizedDoesntBounceAround) {
root_window()->SetBounds(gfx::Rect(0, 0, 640, 480));
root_window()->SetLayoutManager(std::make_unique<MaximizeLayoutManager>());
UniqueWidgetPtr widget = std::make_unique<TestWidget>();
Widget::InitParams params(Widget::InitParams::TYPE_WINDOW);
params.parent = nullptr;
params.context = root_window();
params.show_state = ui::SHOW_STATE_MAXIMIZED;
params.bounds = gfx::Rect(10, 10, 100, 200);
widget->Init(std::move(params));
EXPECT_FALSE(
static_cast<TestWidget*>(widget.get())->did_size_change_more_than_once());
}
class PropertyTestLayoutManager : public TestLayoutManagerBase {
public:
PropertyTestLayoutManager() = default;
PropertyTestLayoutManager(const PropertyTestLayoutManager&) = delete;
PropertyTestLayoutManager& operator=(const PropertyTestLayoutManager&) =
delete;
~PropertyTestLayoutManager() override = default;
bool added() const { return added_; }
private:
// aura::LayoutManager:
void OnWindowAddedToLayout(aura::Window* child) override {
EXPECT_EQ(aura::client::kResizeBehaviorCanResize |
aura::client::kResizeBehaviorCanMaximize |
aura::client::kResizeBehaviorCanMinimize,
child->GetProperty(aura::client::kResizeBehaviorKey));
added_ = true;
}
bool added_ = false;
};
// Verifies the resize behavior when added to the layout manager.
TEST_F(NativeWidgetAuraTest, TestPropertiesWhenAddedToLayout) {
root_window()->SetBounds(gfx::Rect(0, 0, 640, 480));
PropertyTestLayoutManager* layout_manager = root_window()->SetLayoutManager(
std::make_unique<PropertyTestLayoutManager>());
UniqueWidgetPtr widget = std::make_unique<TestWidget>();
Widget::InitParams params(Widget::InitParams::TYPE_WINDOW);
params.delegate = new WidgetDelegate();
params.delegate->SetOwnedByWidget(true);
params.delegate->SetHasWindowSizeControls(true);
params.parent = nullptr;
params.context = root_window();
widget->Init(std::move(params));
EXPECT_TRUE(layout_manager->added());
}
TEST_F(NativeWidgetAuraTest, GetClientAreaScreenBounds) {
// Create a widget.
Widget::InitParams params(Widget::InitParams::TYPE_WINDOW);
params.context = root_window();
params.bounds.SetRect(10, 20, 300, 400);
UniqueWidgetPtr widget = std::make_unique<Widget>();
widget->Init(std::move(params));
// For Aura, client area bounds match window bounds.
gfx::Rect client_bounds = widget->GetClientAreaBoundsInScreen();
EXPECT_EQ(10, client_bounds.x());
EXPECT_EQ(20, client_bounds.y());
EXPECT_EQ(300, client_bounds.width());
EXPECT_EQ(400, client_bounds.height());
}
// View subclass that tracks whether it has gotten a gesture event.
class GestureTrackingView : public View {
public:
GestureTrackingView() = default;
GestureTrackingView(const GestureTrackingView&) = delete;
GestureTrackingView& operator=(const GestureTrackingView&) = delete;
void set_consume_gesture_event(bool value) { consume_gesture_event_ = value; }
void clear_got_gesture_event() { got_gesture_event_ = false; }
bool got_gesture_event() const { return got_gesture_event_; }
// View overrides:
void OnGestureEvent(ui::GestureEvent* event) override {
got_gesture_event_ = true;
if (consume_gesture_event_)
event->StopPropagation();
}
private:
// Was OnGestureEvent() invoked?
bool got_gesture_event_ = false;
// Dictates what OnGestureEvent() returns.
bool consume_gesture_event_ = true;
};
// Verifies a capture isn't set on touch press and that the view that gets
// the press gets the release.
TEST_F(NativeWidgetAuraTest, DontCaptureOnGesture) {
// Create two views (both sized the same). |child| is configured not to
// consume the gesture event.
auto content_view = std::make_unique<GestureTrackingView>();
GestureTrackingView* child = new GestureTrackingView();
child->set_consume_gesture_event(false);
content_view->SetLayoutManager(std::make_unique<FillLayout>());
content_view->AddChildView(child);
UniqueWidgetPtr widget = std::make_unique<TestWidget>();
Widget::InitParams params(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
params.context = root_window();
params.bounds = gfx::Rect(0, 0, 100, 200);
widget->Init(std::move(params));
GestureTrackingView* view = widget->SetContentsView(std::move(content_view));
widget->Show();
ui::TouchEvent press(ui::ET_TOUCH_PRESSED, gfx::Point(41, 51),
ui::EventTimeForNow(),
ui::PointerDetails(ui::EventPointerType::kTouch, 1));
ui::EventDispatchDetails details = GetEventSink()->OnEventFromSource(&press);
ASSERT_FALSE(details.dispatcher_destroyed);
// Both views should get the press.
EXPECT_TRUE(view->got_gesture_event());
EXPECT_TRUE(child->got_gesture_event());
view->clear_got_gesture_event();
child->clear_got_gesture_event();
// Touch events should not automatically grab capture.
EXPECT_FALSE(widget->HasCapture());
// Release touch. Only |view| should get the release since that it consumed
// the press.
ui::TouchEvent release(ui::ET_TOUCH_RELEASED, gfx::Point(250, 251),
ui::EventTimeForNow(),
ui::PointerDetails(ui::EventPointerType::kTouch, 1));
details = GetEventSink()->OnEventFromSource(&release);
ASSERT_FALSE(details.dispatcher_destroyed);
EXPECT_TRUE(view->got_gesture_event());
EXPECT_FALSE(child->got_gesture_event());
view->clear_got_gesture_event();
}
// Verifies views with layers are targeted for events properly.
TEST_F(NativeWidgetAuraTest, PreferViewLayersToChildWindows) {
// Create two widgets: |parent| and |child|. |child| is a child of |parent|.
UniqueWidgetPtr parent = std::make_unique<Widget>();
Widget::InitParams parent_params(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
parent_params.context = root_window();
parent->Init(std::move(parent_params));
View* parent_root = parent->SetContentsView(std::make_unique<View>());
parent->SetBounds(gfx::Rect(0, 0, 400, 400));
parent->Show();
UniqueWidgetPtr child = std::make_unique<Widget>();
Widget::InitParams child_params(Widget::InitParams::TYPE_CONTROL);
child_params.parent = parent->GetNativeWindow();
child->Init(std::move(child_params));
child->SetBounds(gfx::Rect(0, 0, 200, 200));
child->Show();
// Point is over |child|.
EXPECT_EQ(
child->GetNativeWindow(),
parent->GetNativeWindow()->GetEventHandlerForPoint(gfx::Point(50, 50)));
// Create a view with a layer and stack it at the bottom (below |child|).
View* view_with_layer = new View;
parent_root->AddChildView(view_with_layer);
view_with_layer->SetBounds(0, 0, 50, 50);
view_with_layer->SetPaintToLayer();
// Make sure that |child| still gets the event.
EXPECT_EQ(
child->GetNativeWindow(),
parent->GetNativeWindow()->GetEventHandlerForPoint(gfx::Point(20, 20)));
// Move |view_with_layer| to the top and make sure it gets the
// event when the point is within |view_with_layer|'s bounds.
view_with_layer->layer()->parent()->StackAtTop(view_with_layer->layer());
EXPECT_EQ(
parent->GetNativeWindow(),
parent->GetNativeWindow()->GetEventHandlerForPoint(gfx::Point(20, 20)));
// Point is over |child|, it should get the event.
EXPECT_EQ(
child->GetNativeWindow(),
parent->GetNativeWindow()->GetEventHandlerForPoint(gfx::Point(70, 70)));
delete view_with_layer;
view_with_layer = nullptr;
EXPECT_EQ(
child->GetNativeWindow(),
parent->GetNativeWindow()->GetEventHandlerForPoint(gfx::Point(20, 20)));
}
// Verifies views with layers are targeted for events properly.
TEST_F(NativeWidgetAuraTest,
ShouldDescendIntoChildForEventHandlingChecksVisibleBounds) {
// Create two widgets: |parent| and |child|. |child| is a child of |parent|.
UniqueWidgetPtr parent = std::make_unique<Widget>();
Widget::InitParams parent_params(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
parent_params.context = root_window();
parent->Init(std::move(parent_params));
View* parent_root_view = parent->SetContentsView(std::make_unique<View>());
parent->SetBounds(gfx::Rect(0, 0, 400, 400));
parent->Show();
UniqueWidgetPtr child = std::make_unique<Widget>();
Widget::InitParams child_params(Widget::InitParams::TYPE_CONTROL);
child_params.parent = parent->GetNativeWindow();
child->Init(std::move(child_params));
child->SetBounds(gfx::Rect(0, 0, 200, 200));
child->Show();
// Point is over |child|.
EXPECT_EQ(
child->GetNativeWindow(),
parent->GetNativeWindow()->GetEventHandlerForPoint(gfx::Point(50, 50)));
View* parent_root_view_child =
parent_root_view->AddChildView(std::make_unique<View>());
parent_root_view_child->SetBounds(0, 0, 10, 10);
// Create a View whose layer extends outside the bounds of its parent. Event
// targeting should only consider the visible bounds.
View* parent_root_view_child_child =
parent_root_view_child->AddChildView(std::make_unique<View>());
parent_root_view_child_child->SetBounds(0, 0, 100, 100);
parent_root_view_child_child->SetPaintToLayer();
parent_root_view_child_child->layer()->parent()->StackAtTop(
parent_root_view_child_child->layer());
// 20,20 is over |parent_root_view_child_child|'s layer, but not the visible
// bounds of |parent_root_view_child_child|, so |child| should be the event
// target.
EXPECT_EQ(
child->GetNativeWindow(),
parent->GetNativeWindow()->GetEventHandlerForPoint(gfx::Point(20, 20)));
}
// Verifies views with layers that have SetCanProcessEventWithinSubtree(false)
// set are ignored for event targeting (i.e. the underlying child window can
// still be the target of those events).
TEST_F(
NativeWidgetAuraTest,
ShouldDescendIntoChildForEventHandlingIgnoresViewsThatDoNotProcessEvents) {
// Create two widgets: `parent` and `child`. `child` is a child of `parent`.
UniqueWidgetPtr parent = std::make_unique<Widget>();
Widget::InitParams parent_params(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
parent_params.context = root_window();
parent->Init(std::move(parent_params));
View* const parent_root_view =
parent->SetContentsView(std::make_unique<View>());
parent->SetBounds(gfx::Rect(0, 0, 400, 400));
parent->Show();
UniqueWidgetPtr child = std::make_unique<Widget>();
Widget::InitParams child_params(Widget::InitParams::TYPE_CONTROL);
child_params.parent = parent->GetNativeWindow();
child->Init(std::move(child_params));
child->SetBounds(gfx::Rect(0, 0, 200, 200));
child->Show();
// Point is over `child`.
EXPECT_EQ(
child->GetNativeWindow(),
parent->GetNativeWindow()->GetEventHandlerForPoint(gfx::Point(50, 50)));
View* const view_overlapping_child =
parent_root_view->AddChildView(std::make_unique<View>());
view_overlapping_child->SetBoundsRect(gfx::Rect(0, 0, 200, 200));
view_overlapping_child->SetPaintToLayer();
view_overlapping_child->layer()->parent()->StackAtTop(
view_overlapping_child->layer());
// While `view_overlapping_child` receives events, parent should be the event
// handler as the view is on top of the child widget. This basically is used
// to verify that the test setup is working (view with layer overlapping child
// window receives events).
EXPECT_EQ(
parent->GetNativeWindow(),
parent->GetNativeWindow()->GetEventHandlerForPoint(gfx::Point(50, 50)));
// Events should not be routed to `parent` if the view overlapping `child`
// does not process events.
view_overlapping_child->SetCanProcessEventsWithinSubtree(false);
EXPECT_EQ(
child->GetNativeWindow(),
parent->GetNativeWindow()->GetEventHandlerForPoint(gfx::Point(50, 50)));
}
// Verifies that widget->FlashFrame() sets aura::client::kDrawAttentionKey,
// and activating the window clears it.
TEST_F(NativeWidgetAuraTest, FlashFrame) {
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams params(Widget::InitParams::TYPE_WINDOW);
params.context = root_window();
widget->Init(std::move(params));
aura::Window* window = widget->GetNativeWindow();
EXPECT_FALSE(window->GetProperty(aura::client::kDrawAttentionKey));
widget->FlashFrame(true);
EXPECT_TRUE(window->GetProperty(aura::client::kDrawAttentionKey));
widget->FlashFrame(false);
EXPECT_FALSE(window->GetProperty(aura::client::kDrawAttentionKey));
widget->FlashFrame(true);
EXPECT_TRUE(window->GetProperty(aura::client::kDrawAttentionKey));
widget->Activate();
EXPECT_FALSE(window->GetProperty(aura::client::kDrawAttentionKey));
}
// Used to track calls to WidgetDelegate::OnWidgetMove().
class MoveTestWidgetDelegate : public WidgetDelegateView {
public:
MoveTestWidgetDelegate() = default;
MoveTestWidgetDelegate(const MoveTestWidgetDelegate&) = delete;
MoveTestWidgetDelegate& operator=(const MoveTestWidgetDelegate&) = delete;
~MoveTestWidgetDelegate() override = default;
void ClearGotMove() { got_move_ = false; }
bool got_move() const { return got_move_; }
// WidgetDelegate overrides:
void OnWidgetMove() override { got_move_ = true; }
private:
bool got_move_ = false;
};
// This test simulates what happens when a window is normally maximized. That
// is, it's layer is acquired for animation then the window is maximized.
// Acquiring the layer resets the bounds of the window. This test verifies the
// Widget is still notified correctly of a move in this case.
TEST_F(NativeWidgetAuraTest, OnWidgetMovedInvokedAfterAcquireLayer) {
// |delegate| is owned by the Widget by default and is deleted when the widget
// is destroyed.
// See WidgetDelegateView::WidgetDelegateView();
auto delegate = std::make_unique<MoveTestWidgetDelegate>();
auto* delegate_ptr = delegate.get();
UniqueWidgetPtr widget = base::WrapUnique(Widget::CreateWindowWithContext(
std::move(delegate), root_window(), gfx::Rect(10, 10, 100, 200)));
widget->Show();
delegate_ptr->ClearGotMove();
// Simulate a maximize with animation.
widget->GetNativeView()->RecreateLayer();
widget->SetBounds(gfx::Rect(0, 0, 500, 500));
EXPECT_TRUE(delegate_ptr->got_move());
}
// Tests that if a widget has a view which should be initially focused when the
// widget is shown, this view should not get focused if the associated window
// can not be activated.
TEST_F(NativeWidgetAuraTest, PreventFocusOnNonActivableWindow) {
test_focus_rules()->set_can_activate(false);
test::TestInitialFocusWidgetDelegate delegate(root_window());
delegate.GetWidget()->Show();
EXPECT_FALSE(delegate.view()->HasFocus());
test_focus_rules()->set_can_activate(true);
test::TestInitialFocusWidgetDelegate delegate2(root_window());
delegate2.GetWidget()->Show();
EXPECT_TRUE(delegate2.view()->HasFocus());
}
// Tests that the transient child bubble window is only visible if the parent is
// visible.
TEST_F(NativeWidgetAuraTest, VisibilityOfChildBubbleWindow) {
// Create a parent window.
UniqueWidgetPtr parent = std::make_unique<Widget>();
Widget::InitParams parent_params(Widget::InitParams::TYPE_WINDOW);
parent_params.context = root_window();
parent->Init(std::move(parent_params));
parent->SetBounds(gfx::Rect(0, 0, 480, 320));
// Add a child bubble window to the above parent window and show it.
UniqueWidgetPtr child = std::make_unique<Widget>();
Widget::InitParams child_params(Widget::InitParams::TYPE_BUBBLE);
child_params.parent = parent->GetNativeWindow();
child->Init(std::move(child_params));
child->SetBounds(gfx::Rect(0, 0, 200, 200));
child->Show();
// Check that the bubble window is added as the transient child and it is
// hidden because parent window is hidden.
wm::TransientWindowManager* manager =
wm::TransientWindowManager::GetOrCreate(child->GetNativeWindow());
EXPECT_EQ(parent->GetNativeWindow(), manager->transient_parent());
EXPECT_FALSE(parent->IsVisible());
EXPECT_FALSE(child->IsVisible());
// Show the parent window should make the transient child bubble visible.
parent->Show();
EXPECT_TRUE(parent->IsVisible());
EXPECT_TRUE(child->IsVisible());
}
// Tests that for a child transient window, if its modal type is
// ui::MODAL_TYPE_WINDOW, then its visibility is controlled by its transient
// parent's visibility.
TEST_F(NativeWidgetAuraTest, TransientChildModalWindowVisibility) {
// Create a parent window.
UniqueWidgetPtr parent = std::make_unique<Widget>();
Widget::InitParams parent_params(Widget::InitParams::TYPE_WINDOW);
parent_params.context = root_window();
parent->Init(std::move(parent_params));
parent->SetBounds(gfx::Rect(0, 0, 400, 400));
parent->Show();
EXPECT_TRUE(parent->IsVisible());
// Create a ui::MODAL_TYPE_WINDOW modal type transient child window.
UniqueWidgetPtr child = std::make_unique<Widget>();
Widget::InitParams child_params(Widget::InitParams::TYPE_WINDOW);
child_params.parent = parent->GetNativeWindow();
child_params.delegate = new WidgetDelegate;
child_params.delegate->SetOwnedByWidget(true);
child_params.delegate->SetModalType(ui::MODAL_TYPE_WINDOW);
child->Init(std::move(child_params));
child->SetBounds(gfx::Rect(0, 0, 200, 200));
child->Show();
EXPECT_TRUE(parent->IsVisible());
EXPECT_TRUE(child->IsVisible());
// Hide the parent window should also hide the child window.
parent->Hide();
EXPECT_FALSE(parent->IsVisible());
EXPECT_FALSE(child->IsVisible());
// The child window can't be shown if the parent window is hidden.
child->Show();
EXPECT_FALSE(parent->IsVisible());
EXPECT_FALSE(child->IsVisible());
parent->Show();
EXPECT_TRUE(parent->IsVisible());
EXPECT_TRUE(child->IsVisible());
}
// Tests that widgets that are created minimized have the correct restore
// bounds.
TEST_F(NativeWidgetAuraTest, MinimizedWidgetRestoreBounds) {
const gfx::Rect restore_bounds(300, 300);
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams params(Widget::InitParams::TYPE_WINDOW);
params.context = root_window();
params.show_state = ui::SHOW_STATE_MINIMIZED;
params.bounds = restore_bounds;
widget->Init(std::move(params));
widget->Show();
aura::Window* window = widget->GetNativeWindow();
EXPECT_EQ(ui::SHOW_STATE_MINIMIZED,
window->GetProperty(aura::client::kShowStateKey));
EXPECT_EQ(restore_bounds,
*window->GetProperty(aura::client::kRestoreBoundsKey));
widget->Restore();
EXPECT_EQ(restore_bounds, window->bounds());
}
// NativeWidgetAura has a protected destructor.
// Use a test object that overrides the destructor for unit tests.
class TestNativeWidgetAura : public NativeWidgetAura {
public:
explicit TestNativeWidgetAura(internal::NativeWidgetDelegate* delegate)
: NativeWidgetAura(delegate) {}
TestNativeWidgetAura(const TestNativeWidgetAura&) = delete;
TestNativeWidgetAura& operator=(const TestNativeWidgetAura&) = delete;
~TestNativeWidgetAura() override = default;
};
// Series of tests that verifies having a null NativeWidgetDelegate doesn't
// crash.
class NativeWidgetAuraWithNoDelegateTest : public NativeWidgetAuraTest {
public:
NativeWidgetAuraWithNoDelegateTest() = default;
NativeWidgetAuraWithNoDelegateTest(
const NativeWidgetAuraWithNoDelegateTest&) = delete;
NativeWidgetAuraWithNoDelegateTest& operator=(
const NativeWidgetAuraWithNoDelegateTest&) = delete;
~NativeWidgetAuraWithNoDelegateTest() override = default;
// testing::Test overrides:
void SetUp() override {
NativeWidgetAuraTest::SetUp();
Widget widget;
native_widget_ = new TestNativeWidgetAura(&widget);
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.ownership = views::Widget::InitParams::CLIENT_OWNS_WIDGET;
params.native_widget = native_widget_;
widget.Init(std::move(params));
widget.Show();
// Notify all widget observers that the widget is destroying so they can
// unregister properly and clear the pointer to the widget.
widget.OnNativeWidgetDestroying();
// Widget will create a DefaultWidgetDelegate if no delegates are provided.
// Call Widget::OnNativeWidgetDestroyed() to destroy
// the WidgetDelegate properly.
widget.OnNativeWidgetDestroyed();
}
void TearDown() override {
native_widget_->CloseNow();
ViewsTestBase::TearDown();
}
raw_ptr<TestNativeWidgetAura> native_widget_;
};
TEST_F(NativeWidgetAuraWithNoDelegateTest, GetHitTestMaskTest) {
SkPath mask;
native_widget_->GetHitTestMask(&mask);
}
TEST_F(NativeWidgetAuraWithNoDelegateTest, GetMaximumSizeTest) {
native_widget_->GetMaximumSize();
}
TEST_F(NativeWidgetAuraWithNoDelegateTest, GetMinimumSizeTest) {
native_widget_->GetMinimumSize();
}
TEST_F(NativeWidgetAuraWithNoDelegateTest, GetNonClientComponentTest) {
native_widget_->GetNonClientComponent(gfx::Point());
}
TEST_F(NativeWidgetAuraWithNoDelegateTest, GetWidgetTest) {
native_widget_->GetWidget();
}
TEST_F(NativeWidgetAuraWithNoDelegateTest, HasHitTestMaskTest) {
native_widget_->HasHitTestMask();
}
TEST_F(NativeWidgetAuraWithNoDelegateTest, OnBoundsChangedTest) {
native_widget_->OnCaptureLost();
}
TEST_F(NativeWidgetAuraWithNoDelegateTest, OnCaptureLostTest) {
native_widget_->OnBoundsChanged(gfx::Rect(), gfx::Rect());
}
TEST_F(NativeWidgetAuraWithNoDelegateTest, OnGestureEventTest) {
ui::GestureEvent gesture(0, 0, 0, ui::EventTimeForNow(),
ui::GestureEventDetails(ui::ET_GESTURE_TAP_DOWN));
native_widget_->OnGestureEvent(&gesture);
}
TEST_F(NativeWidgetAuraWithNoDelegateTest, OnKeyEventTest) {
ui::KeyEvent key(ui::ET_KEY_PRESSED, ui::VKEY_0, ui::EF_NONE);
native_widget_->OnKeyEvent(&key);
}
TEST_F(NativeWidgetAuraWithNoDelegateTest, OnMouseEventTest) {
ui::MouseEvent move(ui::ET_MOUSE_MOVED, gfx::Point(), gfx::Point(),
ui::EventTimeForNow(), ui::EF_NONE, ui::EF_NONE);
native_widget_->OnMouseEvent(&move);
}
TEST_F(NativeWidgetAuraWithNoDelegateTest, OnPaintTest) {
native_widget_->OnPaint(ui::PaintContext(nullptr, 0, gfx::Rect(), false));
}
TEST_F(NativeWidgetAuraWithNoDelegateTest, OnResizeLoopEndedTest) {
native_widget_->OnResizeLoopEnded(nullptr);
}
TEST_F(NativeWidgetAuraWithNoDelegateTest, OnResizeLoopStartedTest) {
native_widget_->OnResizeLoopStarted(nullptr);
}
TEST_F(NativeWidgetAuraWithNoDelegateTest, OnScrollEventTest) {
ui::ScrollEvent scroll(ui::ET_SCROLL, gfx::Point(), ui::EventTimeForNow(), 0,
0, 0, 0, 0, 0);
native_widget_->OnScrollEvent(&scroll);
}
TEST_F(NativeWidgetAuraWithNoDelegateTest, OnTransientParentChangedTest) {
native_widget_->OnTransientParentChanged(nullptr);
}
TEST_F(NativeWidgetAuraWithNoDelegateTest, OnWindowAddedToRootWindowTest) {
native_widget_->OnWindowAddedToRootWindow(nullptr);
}
TEST_F(NativeWidgetAuraWithNoDelegateTest, OnWindowPropertyChangedTest) {
native_widget_->OnWindowPropertyChanged(nullptr, nullptr, 0);
}
TEST_F(NativeWidgetAuraWithNoDelegateTest, OnWindowRemovingFromRootWindowTest) {
native_widget_->OnWindowRemovingFromRootWindow(nullptr, nullptr);
}
TEST_F(NativeWidgetAuraWithNoDelegateTest,
OnWindowTargetVisibilityChangedTest) {
native_widget_->OnWindowTargetVisibilityChanged(false);
}
TEST_F(NativeWidgetAuraWithNoDelegateTest, OnWindowActivatedTest) {
native_widget_->OnWindowActivated(
wm::ActivationChangeObserver::ActivationReason::ACTIVATION_CLIENT,
native_widget_->GetNativeView(), nullptr);
}
TEST_F(NativeWidgetAuraWithNoDelegateTest, OnWindowFocusedTest) {
native_widget_->OnWindowFocused(nullptr, nullptr);
}
TEST_F(NativeWidgetAuraWithNoDelegateTest, ShouldActivateTest) {
native_widget_->ShouldActivate();
}
TEST_F(NativeWidgetAuraWithNoDelegateTest,
ShouldDescendIntoChildForEventHandlingTest) {
native_widget_->ShouldDescendIntoChildForEventHandling(nullptr, gfx::Point());
}
TEST_F(NativeWidgetAuraWithNoDelegateTest, UpdateVisualStateTest) {
native_widget_->UpdateVisualState();
}
} // namespace
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/native_widget_aura_unittest.cc | C++ | unknown | 38,839 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_WIDGET_NATIVE_WIDGET_DELEGATE_H_
#define UI_VIEWS_WIDGET_NATIVE_WIDGET_DELEGATE_H_
#include "ui/events/event_constants.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/views_export.h"
class SkPath;
namespace gfx {
class Point;
class Size;
} // namespace gfx
namespace ui {
class GestureEvent;
class KeyEvent;
class Layer;
class MouseEvent;
class PaintContext;
class ScrollEvent;
} // namespace ui
namespace views {
class Widget;
namespace internal {
////////////////////////////////////////////////////////////////////////////////
// NativeWidgetDelegate
//
// An interface implemented by the object that handles events sent by a
// NativeWidget implementation.
//
class VIEWS_EXPORT NativeWidgetDelegate {
public:
virtual ~NativeWidgetDelegate() = default;
// Returns true if the window is modal.
virtual bool IsModal() const = 0;
// Returns true if the window is a dialog box.
virtual bool IsDialogBox() const = 0;
// Returns true if the window can be activated.
virtual bool CanActivate() const = 0;
// Returns true if the native widget has been initialized.
virtual bool IsNativeWidgetInitialized() const = 0;
// Called when the activation state of a window has changed.
// Returns true if this event was handled.
virtual bool OnNativeWidgetActivationChanged(bool active) = 0;
// Returns true if the window's activation change event should be handled.
virtual bool ShouldHandleNativeWidgetActivationChanged(bool active) = 0;
// Called when native focus moves from one native view to another.
virtual void OnNativeFocus() = 0;
virtual void OnNativeBlur() = 0;
// Called when the window is shown/hidden.
virtual void OnNativeWidgetVisibilityChanged(bool visible) = 0;
// Called when the native widget is created.
virtual void OnNativeWidgetCreated() = 0;
// Called just before the native widget is destroyed. This is the delegate's
// last chance to do anything with the native widget handle.
virtual void OnNativeWidgetDestroying() = 0;
// Called just after the native widget is destroyed.
virtual void OnNativeWidgetDestroyed() = 0;
// Called after the native widget's parent has changed.
virtual void OnNativeWidgetParentChanged(gfx::NativeView parent) = 0;
// Returns the smallest size the window can be resized to by the user.
virtual gfx::Size GetMinimumSize() const = 0;
// Returns the largest size the window can be resized to by the user.
virtual gfx::Size GetMaximumSize() const = 0;
// Called when the NativeWidget changed position.
virtual void OnNativeWidgetMove() = 0;
// Called when the NativeWidget changed size to |new_size|.
// This may happen at the same time as OnNativeWidgetWindowShowStateChanged,
// e.g. maximize.
virtual void OnNativeWidgetSizeChanged(const gfx::Size& new_size) = 0;
// Called when NativeWidget changed workspaces or its visible on all
// workspaces state changes.
virtual void OnNativeWidgetWorkspaceChanged() = 0;
// Called when the NativeWidget changes its window state.
// This may happen at the same time as OnNativeWidgetSizeChanged, e.g.
// maximize.
virtual void OnNativeWidgetWindowShowStateChanged() = 0;
// Called when the user begins/ends to change the bounds of the window.
virtual void OnNativeWidgetBeginUserBoundsChange() = 0;
virtual void OnNativeWidgetEndUserBoundsChange() = 0;
// Called when the NativeWidget is added and/or being removed from a
// Compositor. On some platforms the Compositor never changes, and these
// functions are never called.
virtual void OnNativeWidgetAddedToCompositor() = 0;
virtual void OnNativeWidgetRemovingFromCompositor() = 0;
// Returns true if the delegate has a FocusManager.
virtual bool HasFocusManager() const = 0;
// Paints the rootview in the context. This will also refresh the compositor
// tree if necessary.
virtual void OnNativeWidgetPaint(const ui::PaintContext& context) = 0;
// Returns the non-client component (see ui/base/hit_test.h) containing
// |point|, in client coordinates.
virtual int GetNonClientComponent(const gfx::Point& point) = 0;
// Event handlers.
virtual void OnKeyEvent(ui::KeyEvent* event) = 0;
virtual void OnMouseEvent(ui::MouseEvent* event) = 0;
virtual void OnMouseCaptureLost() = 0;
virtual void OnScrollEvent(ui::ScrollEvent* event) = 0;
virtual void OnGestureEvent(ui::GestureEvent* event) = 0;
// Runs the specified native command. Returns true if the command is handled.
virtual bool ExecuteCommand(int command_id) = 0;
// Returns true if window has a hit-test mask.
virtual bool HasHitTestMask() const = 0;
// Provides the hit-test mask if HasHitTestMask above returns true.
virtual void GetHitTestMask(SkPath* mask) const = 0;
virtual Widget* AsWidget() = 0;
virtual const Widget* AsWidget() const = 0;
// Sets-up the focus manager with the view that should have focus when the
// window is shown the first time. It takes the intended |show_state| of the
// window in order to decide whether the window should be focused now or
// later. Returns true if the initial focus has been set or the window should
// not set the initial focus, or false if the caller should set the initial
// focus (if any).
virtual bool SetInitialFocus(ui::WindowShowState show_state) = 0;
// Returns true if event handling should descend into |child|. |root_layer| is
// the layer associated with the root Window and |child_layer| the layer
// associated with |child|. |location| is in terms of the Window.
virtual bool ShouldDescendIntoChildForEventHandling(
ui::Layer* root_layer,
gfx::NativeView child,
ui::Layer* child_layer,
const gfx::Point& location) = 0;
// Called to process a previous call to ScheduleLayout().
virtual void LayoutRootViewIfNecessary() = 0;
};
} // namespace internal
} // namespace views
#endif // UI_VIEWS_WIDGET_NATIVE_WIDGET_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/native_widget_delegate.h | C++ | unknown | 6,112 |
// 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_WIDGET_NATIVE_WIDGET_MAC_H_
#define UI_VIEWS_WIDGET_NATIVE_WIDGET_MAC_H_
#include <memory>
#include <string>
#include "base/memory/raw_ptr.h"
#include "ui/base/ime/ime_key_event_dispatcher.h"
#include "ui/base/window_open_disposition.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/widget/native_widget_private.h"
#if defined(__OBJC__)
@class NativeWidgetMacNSWindow;
#else
class NativeWidgetMacNSWindow;
#endif
namespace remote_cocoa {
namespace mojom {
class CreateWindowParams;
class NativeWidgetNSWindow;
class ValidateUserInterfaceItemResult;
} // namespace mojom
class ApplicationHost;
class NativeWidgetNSWindowBridge;
} // namespace remote_cocoa
namespace views {
namespace test {
class MockNativeWidgetMac;
class NativeWidgetMacTest;
} // namespace test
class NativeWidgetMacNSWindowHost;
class VIEWS_EXPORT NativeWidgetMac : public internal::NativeWidgetPrivate,
public FocusChangeListener,
public ui::ImeKeyEventDispatcher {
public:
explicit NativeWidgetMac(internal::NativeWidgetDelegate* delegate);
NativeWidgetMac(const NativeWidgetMac&) = delete;
NativeWidgetMac& operator=(const NativeWidgetMac&) = delete;
~NativeWidgetMac() override;
// Informs |delegate_| that the native widget is about to be destroyed.
// NativeWidgetNSWindowBridge::OnWindowWillClose() invokes this early when the
// NSWindowDelegate informs the bridge that the window is being closed (later,
// invoking OnWindowDestroyed()).
void WindowDestroying();
// Deletes |bridge_| and informs |delegate_| that the native widget is
// destroyed.
void WindowDestroyed();
// Called when the backing NSWindow gains or loses key status.
void OnWindowKeyStatusChanged(bool is_key, bool is_content_first_responder);
// The vertical position from which sheets should be anchored, from the top
// of the content view.
virtual int32_t SheetOffsetY();
// Returns in |override_titlebar_height| whether or not to override the
// titlebar height and in |titlebar_height| the height of the titlebar.
virtual void GetWindowFrameTitlebarHeight(bool* override_titlebar_height,
float* titlebar_height);
// Called when the window begins transitioning to or from being fullscreen.
virtual void OnWindowFullscreenTransitionStart() {}
// Called when the window has completed its transition to or from being
// fullscreen. Note that if there are multiple consecutive transitions
// (because a new transition was initiated before the previous one completed)
// then this will only be called when all transitions have competed.
virtual void OnWindowFullscreenTransitionComplete() {}
// Handle "Move focus to the window toolbar" shortcut.
virtual void OnFocusWindowToolbar() {}
// Allows subclasses to override the behavior for
// -[NSUserInterfaceValidations validateUserInterfaceItem].
virtual void ValidateUserInterfaceItem(
int32_t command,
remote_cocoa::mojom::ValidateUserInterfaceItemResult* result) {}
// Returns in |will_execute| whether or not ExecuteCommand() will execute
// the chrome command |command| with |window_open_disposition| and
// |is_before_first_responder|.
virtual bool WillExecuteCommand(int32_t command,
WindowOpenDisposition window_open_disposition,
bool is_before_first_responder);
// Execute the chrome command |command| with |window_open_disposition|. If
// |is_before_first_responder| then only call ExecuteCommand if the command
// is reserved and extension shortcut handling is not suspended. Returns in
// |was_executed| whether or not ExecuteCommand was called (regardless of what
// the return value for ExecuteCommand was).
virtual bool ExecuteCommand(int32_t command,
WindowOpenDisposition window_open_disposition,
bool is_before_first_responder);
ui::Compositor* GetCompositor() {
return const_cast<ui::Compositor*>(
const_cast<const NativeWidgetMac*>(this)->GetCompositor());
}
// internal::NativeWidgetPrivate:
void InitNativeWidget(Widget::InitParams params) override;
void OnWidgetInitDone() override;
std::unique_ptr<NonClientFrameView> CreateNonClientFrameView() override;
bool ShouldUseNativeFrame() const override;
bool ShouldWindowContentsBeTransparent() const override;
void FrameTypeChanged() override;
Widget* GetWidget() override;
const Widget* GetWidget() const override;
gfx::NativeView GetNativeView() const override;
gfx::NativeWindow GetNativeWindow() const override;
Widget* GetTopLevelWidget() override;
const ui::Compositor* GetCompositor() const override;
const ui::Layer* GetLayer() const override;
void ReorderNativeViews() override;
void ViewRemoved(View* view) override;
void SetNativeWindowProperty(const char* name, void* value) override;
void* GetNativeWindowProperty(const char* name) const override;
TooltipManager* GetTooltipManager() const override;
void SetCapture() override;
void ReleaseCapture() override;
bool HasCapture() const override;
ui::InputMethod* GetInputMethod() override;
void CenterWindow(const gfx::Size& size) override;
void GetWindowPlacement(gfx::Rect* bounds,
ui::WindowShowState* show_state) const override;
bool SetWindowTitle(const std::u16string& title) override;
void SetWindowIcons(const gfx::ImageSkia& window_icon,
const gfx::ImageSkia& app_icon) override;
const gfx::ImageSkia* GetWindowIcon() override;
const gfx::ImageSkia* GetWindowAppIcon() override;
void InitModalType(ui::ModalType modal_type) override;
gfx::Rect GetWindowBoundsInScreen() const override;
gfx::Rect GetClientAreaBoundsInScreen() const override;
gfx::Rect GetRestoredBounds() const override;
std::string GetWorkspace() const override;
void SetBounds(const gfx::Rect& bounds) override;
void SetBoundsConstrained(const gfx::Rect& bounds) override;
void SetSize(const gfx::Size& size) override;
void StackAbove(gfx::NativeView native_view) override;
void StackAtTop() override;
bool IsStackedAbove(gfx::NativeView native_view) override;
void SetShape(std::unique_ptr<Widget::ShapeRects> shape) override;
void Close() override;
void CloseNow() override;
void Show(ui::WindowShowState show_state,
const gfx::Rect& restore_bounds) override;
void Hide() override;
bool IsVisible() const override;
void Activate() override;
void Deactivate() override;
bool IsActive() const override;
void SetZOrderLevel(ui::ZOrderLevel order) override;
ui::ZOrderLevel GetZOrderLevel() const override;
void SetVisibleOnAllWorkspaces(bool always_visible) override;
bool IsVisibleOnAllWorkspaces() const override;
void Maximize() override;
void Minimize() override;
bool IsMaximized() const override;
bool IsMinimized() const override;
void Restore() override;
void SetFullscreen(bool fullscreen, int64_t target_display_id) override;
bool IsFullscreen() const override;
void SetCanAppearInExistingFullscreenSpaces(
bool can_appear_in_existing_fullscreen_spaces) override;
void SetOpacity(float opacity) override;
void SetAspectRatio(const gfx::SizeF& aspect_ratio,
const gfx::Size& excluded_margin) override;
void FlashFrame(bool flash_frame) override;
void RunShellDrag(View* view,
std::unique_ptr<ui::OSExchangeData> data,
const gfx::Point& location,
int operation,
ui::mojom::DragEventSource source) override;
void SchedulePaintInRect(const gfx::Rect& rect) override;
void ScheduleLayout() override;
void SetCursor(const ui::Cursor& cursor) override;
void ShowEmojiPanel() override;
bool IsMouseEventsEnabled() const override;
bool IsMouseButtonDown() const override;
void ClearNativeFocus() override;
gfx::Rect GetWorkAreaBoundsInScreen() const override;
Widget::MoveLoopResult RunMoveLoop(
const gfx::Vector2d& drag_offset,
Widget::MoveLoopSource source,
Widget::MoveLoopEscapeBehavior escape_behavior) override;
void EndMoveLoop() override;
void SetVisibilityChangedAnimationsEnabled(bool value) override;
void SetVisibilityAnimationDuration(const base::TimeDelta& duration) override;
void SetVisibilityAnimationTransition(
Widget::VisibilityTransition transition) override;
bool IsTranslucentWindowOpacitySupported() const override;
ui::GestureRecognizer* GetGestureRecognizer() override;
ui::GestureConsumer* GetGestureConsumer() override;
void OnSizeConstraintsChanged() override;
void OnNativeViewHierarchyWillChange() override;
void OnNativeViewHierarchyChanged() override;
std::string GetName() const override;
base::WeakPtr<internal::NativeWidgetPrivate> GetWeakPtr() override;
// Calls |callback| with the newly created NativeWidget whenever a
// NativeWidget is created.
static void SetInitNativeWidgetCallback(
base::RepeatingCallback<void(NativeWidgetMac*)> callback);
protected:
// The argument to SetBounds is sometimes in screen coordinates and sometimes
// in parent window coordinates. This function will take that bounds argument
// and convert it to screen coordinates if needed.
gfx::Rect ConvertBoundsToScreenIfNeeded(const gfx::Rect& bounds) const;
virtual void PopulateCreateWindowParams(
const Widget::InitParams& widget_params,
remote_cocoa::mojom::CreateWindowParams* params) {}
// Creates the NSWindow that will be passed to the NativeWidgetNSWindowBridge.
// Called by InitNativeWidget. The return value will be autoreleased.
// Note that some tests (in particular, views_unittests that interact
// with ScopedFakeNSWindowFullscreen, on 10.10) assume that these windows
// are autoreleased, and will crash if the window has a more precise
// lifetime.
virtual NativeWidgetMacNSWindow* CreateNSWindow(
const remote_cocoa::mojom::CreateWindowParams* params);
// Return the BridgeFactoryHost that is to be used for creating this window
// and all of its child windows. This will return nullptr if the native
// windows are to be created in the current process.
virtual remote_cocoa::ApplicationHost* GetRemoteCocoaApplicationHost();
// Called after the window has been initialized. Allows subclasses to perform
// additional initialization.
virtual void OnWindowInitialized() {}
// Optional hook for subclasses invoked by WindowDestroying().
virtual void OnWindowDestroying(gfx::NativeWindow window) {}
internal::NativeWidgetDelegate* delegate() { return delegate_; }
// Return the mojo interface for the NSWindow. The interface may be
// implemented in-process or out-of-process.
remote_cocoa::mojom::NativeWidgetNSWindow* GetNSWindowMojo() const;
// Return the bridge structure only if this widget is in-process.
remote_cocoa::NativeWidgetNSWindowBridge* GetInProcessNSWindowBridge() const;
NativeWidgetMacNSWindowHost* GetNSWindowHost() const {
return ns_window_host_.get();
}
// Unregister focus listeners from previous focus manager, and register them
// with the |new_focus_manager|. Updates |focus_manager_|.
void SetFocusManager(FocusManager* new_focus_manager);
// FocusChangeListener:
void OnWillChangeFocus(View* focused_before, View* focused_now) override;
void OnDidChangeFocus(View* focused_before, View* focused_now) override;
// ui::ImeKeyEventDispatcher:
ui::EventDispatchDetails DispatchKeyEventPostIME(ui::KeyEvent* key) override;
private:
friend class test::MockNativeWidgetMac;
friend class views::test::NativeWidgetMacTest;
class ZoomFocusMonitor;
raw_ptr<internal::NativeWidgetDelegate, DanglingUntriaged> delegate_;
std::unique_ptr<NativeWidgetMacNSWindowHost> ns_window_host_;
Widget::InitParams::Ownership ownership_ =
Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET;
// Internal name.
std::string name_;
ui::ZOrderLevel z_order_level_ = ui::ZOrderLevel::kNormal;
Widget::InitParams::Type type_;
// Weak pointer to the FocusManager with with |zoom_focus_monitor_| and
// |ns_window_host_| are registered.
raw_ptr<FocusManager> focus_manager_ = nullptr;
std::unique_ptr<ui::InputMethod> input_method_;
std::unique_ptr<ZoomFocusMonitor> zoom_focus_monitor_;
// Held while this widget is active if it's a child.
std::unique_ptr<Widget::PaintAsActiveLock> parent_key_lock_;
// The following factory is used to provide references to the NativeWidgetMac
// instance.
base::WeakPtrFactory<NativeWidgetMac> weak_factory{this};
};
} // namespace views
#endif // UI_VIEWS_WIDGET_NATIVE_WIDGET_MAC_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/native_widget_mac.h | Objective-C | unknown | 12,952 |
// 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/widget/native_widget_mac.h"
#include <ApplicationServices/ApplicationServices.h>
#import <Cocoa/Cocoa.h>
#include <CoreFoundation/CoreFoundation.h>
#include <utility>
#include "base/base64.h"
#include "base/functional/callback.h"
#include "base/mac/scoped_nsobject.h"
#include "base/no_destructor.h"
#include "base/strings/sys_string_conversions.h"
#include "components/crash/core/common/crash_key.h"
#import "components/remote_cocoa/app_shim/bridged_content_view.h"
#import "components/remote_cocoa/app_shim/immersive_mode_controller.h"
#import "components/remote_cocoa/app_shim/native_widget_mac_nswindow.h"
#import "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h"
#import "components/remote_cocoa/app_shim/views_nswindow_delegate.h"
#import "ui/base/cocoa/window_size_constants.h"
#include "ui/base/ime/init/input_method_factory.h"
#include "ui/base/ime/input_method.h"
#include "ui/compositor/compositor.h"
#include "ui/compositor/layer.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/events/gestures/gesture_recognizer.h"
#include "ui/events/gestures/gesture_recognizer_impl_mac.h"
#include "ui/events/gestures/gesture_types.h"
#include "ui/gfx/font_list.h"
#import "ui/gfx/mac/coordinate_conversion.h"
#include "ui/native_theme/native_theme.h"
#include "ui/native_theme/native_theme_mac.h"
#import "ui/views/cocoa/drag_drop_client_mac.h"
#import "ui/views/cocoa/native_widget_mac_ns_window_host.h"
#include "ui/views/cocoa/text_input_host.h"
#include "ui/views/views_features.h"
#include "ui/views/widget/drop_helper.h"
#include "ui/views/widget/native_widget_delegate.h"
#include "ui/views/widget/widget_aura_utils.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/window/native_frame_view_mac.h"
using remote_cocoa::mojom::WindowVisibilityState;
namespace views {
namespace {
static base::RepeatingCallback<void(NativeWidgetMac*)>*
g_init_native_widget_callback = nullptr;
uint64_t StyleMaskForParams(const Widget::InitParams& params) {
// If the Widget is modal, it will be displayed as a sheet. This works best if
// it has NSWindowStyleMaskTitled. For example, with
// NSWindowStyleMaskBorderless, the parent window still accepts input.
// NSWindowStyleMaskFullSizeContentView ensures that calculating the modal's
// content rect doesn't account for a nonexistent title bar.
if (params.delegate &&
params.delegate->GetModalType() == ui::MODAL_TYPE_WINDOW)
return NSWindowStyleMaskTitled | NSWindowStyleMaskFullSizeContentView;
// TODO(tapted): Determine better masks when there are use cases for it.
if (params.remove_standard_frame)
return NSWindowStyleMaskBorderless;
if (params.type == Widget::InitParams::TYPE_WINDOW) {
return NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable;
}
return NSWindowStyleMaskBorderless;
}
CGWindowLevel CGWindowLevelForZOrderLevel(ui::ZOrderLevel level,
Widget::InitParams::Type type) {
switch (level) {
case ui::ZOrderLevel::kNormal:
return kCGNormalWindowLevel;
case ui::ZOrderLevel::kFloatingWindow:
if (type == Widget::InitParams::TYPE_MENU)
return kCGPopUpMenuWindowLevel;
else
return kCGFloatingWindowLevel;
case ui::ZOrderLevel::kFloatingUIElement:
if (type == Widget::InitParams::TYPE_DRAG)
return kCGDraggingWindowLevel;
else
return kCGStatusWindowLevel;
case ui::ZOrderLevel::kSecuritySurface:
return kCGScreenSaverWindowLevel - 1;
}
}
} // namespace
// Implements zoom following focus for macOS accessibility zoom.
class NativeWidgetMac::ZoomFocusMonitor : public FocusChangeListener {
public:
ZoomFocusMonitor() = default;
~ZoomFocusMonitor() override = default;
void OnWillChangeFocus(View* focused_before, View* focused_now) override {}
void OnDidChangeFocus(View* focused_before, View* focused_now) override {
if (!focused_now || !UAZoomEnabled())
return;
// Web content handles its own zooming.
if (strcmp("WebView", focused_now->GetClassName()) == 0)
return;
NSRect rect = NSRectFromCGRect(focused_now->GetBoundsInScreen().ToCGRect());
UAZoomChangeFocus(&rect, nullptr, kUAZoomFocusTypeOther);
}
};
////////////////////////////////////////////////////////////////////////////////
// NativeWidgetMac:
NativeWidgetMac::NativeWidgetMac(internal::NativeWidgetDelegate* delegate)
: delegate_(delegate),
ns_window_host_(new NativeWidgetMacNSWindowHost(this)) {}
NativeWidgetMac::~NativeWidgetMac() {
if (ownership_ == Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET)
delete delegate_;
else
CloseNow();
}
void NativeWidgetMac::WindowDestroying() {
OnWindowDestroying(GetNativeWindow());
delegate_->OnNativeWidgetDestroying();
}
void NativeWidgetMac::WindowDestroyed() {
DCHECK(GetNSWindowMojo());
SetFocusManager(nullptr);
ns_window_host_.reset();
// |OnNativeWidgetDestroyed| may delete |this| if the object does not own
// itself.
bool should_delete_this =
(ownership_ == Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET) ||
(ownership_ == Widget::InitParams::CLIENT_OWNS_WIDGET);
delegate_->OnNativeWidgetDestroyed();
if (should_delete_this)
delete this;
}
void NativeWidgetMac::OnWindowKeyStatusChanged(
bool is_key,
bool is_content_first_responder) {
Widget* widget = GetWidget();
if (!widget->OnNativeWidgetActivationChanged(is_key))
return;
// The contentView is the BridgedContentView hosting the views::RootView. The
// focus manager will already know if a native subview has focus.
if (!is_content_first_responder)
return;
if (is_key) {
widget->OnNativeFocus();
widget->GetFocusManager()->RestoreFocusedView();
} else {
widget->OnNativeBlur();
widget->GetFocusManager()->StoreFocusedView(true);
parent_key_lock_.reset();
}
}
int32_t NativeWidgetMac::SheetOffsetY() {
return 0;
}
void NativeWidgetMac::GetWindowFrameTitlebarHeight(
bool* override_titlebar_height,
float* titlebar_height) {
*override_titlebar_height = false;
*titlebar_height = 0;
}
bool NativeWidgetMac::WillExecuteCommand(
int32_t command,
WindowOpenDisposition window_open_disposition,
bool is_before_first_responder) {
// This is supported only by subclasses in chrome/browser/ui.
NOTIMPLEMENTED();
return false;
}
bool NativeWidgetMac::ExecuteCommand(
int32_t command,
WindowOpenDisposition window_open_disposition,
bool is_before_first_responder) {
// This is supported only by subclasses in chrome/browser/ui.
NOTIMPLEMENTED();
return false;
}
void NativeWidgetMac::InitNativeWidget(Widget::InitParams params) {
ownership_ = params.ownership;
name_ = params.name;
type_ = params.type;
NativeWidgetMacNSWindowHost* parent_host =
NativeWidgetMacNSWindowHost::GetFromNativeView(params.parent);
// Determine the factory through which to create the bridge
remote_cocoa::ApplicationHost* application_host =
parent_host ? parent_host->application_host()
: GetRemoteCocoaApplicationHost();
// Compute the parameters to describe the NSWindow.
auto create_window_params = remote_cocoa::mojom::CreateWindowParams::New();
create_window_params->window_class =
remote_cocoa::mojom::WindowClass::kDefault;
create_window_params->style_mask = StyleMaskForParams(params);
create_window_params->titlebar_appears_transparent = false;
create_window_params->window_title_hidden = false;
PopulateCreateWindowParams(params, create_window_params.get());
if (application_host) {
ns_window_host_->CreateRemoteNSWindow(application_host,
std::move(create_window_params));
} else {
base::scoped_nsobject<NativeWidgetMacNSWindow> window(
[CreateNSWindow(create_window_params.get()) retain]);
ns_window_host_->CreateInProcessNSWindowBridge(std::move(window));
}
// If the z-order wasn't specifically set to something other than `kNormal`,
// then override it if it would leave the widget z-ordered incorrectly in some
// platform-specific corner cases.
if (params.parent &&
(!params.z_order || params.z_order == ui::ZOrderLevel::kNormal)) {
if (auto* parent_widget = Widget::GetWidgetForNativeView(params.parent)) {
// If our parent is z-ordered above us, then float a bit higher.
params.z_order =
std::max(params.z_order.value_or(ui::ZOrderLevel::kNormal),
parent_widget->GetZOrderLevel());
}
}
ns_window_host_->SetParent(parent_host);
ns_window_host_->InitWindow(params,
ConvertBoundsToScreenIfNeeded(params.bounds));
OnWindowInitialized();
// Only set the z-order here if it is non-default since setting it may affect
// how the window is treated by Expose.
if (params.EffectiveZOrderLevel() != ui::ZOrderLevel::kNormal)
SetZOrderLevel(params.EffectiveZOrderLevel());
GetNSWindowMojo()->SetIgnoresMouseEvents(!params.accept_events);
GetNSWindowMojo()->SetVisibleOnAllSpaces(params.visible_on_all_workspaces);
delegate_->OnNativeWidgetCreated();
DCHECK(GetWidget()->GetRootView());
ns_window_host_->SetRootView(GetWidget()->GetRootView());
GetNSWindowMojo()->CreateContentView(ns_window_host_->GetRootViewNSViewId(),
GetWidget()->GetRootView()->bounds());
if (auto* focus_manager = GetWidget()->GetFocusManager()) {
GetNSWindowMojo()->MakeFirstResponder();
// Only one ZoomFocusMonitor is needed per FocusManager, so create one only
// for top-level widgets.
if (GetWidget()->is_top_level())
zoom_focus_monitor_ = std::make_unique<ZoomFocusMonitor>();
SetFocusManager(focus_manager);
}
ns_window_host_->CreateCompositor(params);
if (g_init_native_widget_callback)
g_init_native_widget_callback->Run(this);
}
void NativeWidgetMac::OnWidgetInitDone() {
OnSizeConstraintsChanged();
ns_window_host_->OnWidgetInitDone();
}
std::unique_ptr<NonClientFrameView>
NativeWidgetMac::CreateNonClientFrameView() {
return std::make_unique<NativeFrameViewMac>(GetWidget());
}
bool NativeWidgetMac::ShouldUseNativeFrame() const {
return true;
}
bool NativeWidgetMac::ShouldWindowContentsBeTransparent() const {
// On Windows, this returns true when Aero is enabled which draws the titlebar
// with translucency.
return false;
}
void NativeWidgetMac::FrameTypeChanged() {
// This is called when the Theme has changed; forward the event to the root
// widget.
GetWidget()->ThemeChanged();
GetWidget()->GetRootView()->SchedulePaint();
}
Widget* NativeWidgetMac::GetWidget() {
return delegate_->AsWidget();
}
const Widget* NativeWidgetMac::GetWidget() const {
return delegate_->AsWidget();
}
gfx::NativeView NativeWidgetMac::GetNativeView() const {
// The immersive mode's overlay widget content view is moved to an another
// NSWindow when entering fullscreen. When the view is moved, the current
// content view will be nil. Return the cached original content view instead.
NSView* contentView = (NSView*)GetNativeWindowProperty(
views::NativeWidgetMacNSWindowHost::kImmersiveContentNSView);
if (contentView) {
return gfx::NativeView(contentView);
}
// Returns a BridgedContentView, unless there is no views::RootView set.
return [GetNativeWindow().GetNativeNSWindow() contentView];
}
gfx::NativeWindow NativeWidgetMac::GetNativeWindow() const {
return ns_window_host_ ? ns_window_host_->GetInProcessNSWindow() : nil;
}
Widget* NativeWidgetMac::GetTopLevelWidget() {
NativeWidgetPrivate* native_widget = GetTopLevelNativeWidget(GetNativeView());
return native_widget ? native_widget->GetWidget() : nullptr;
}
const ui::Compositor* NativeWidgetMac::GetCompositor() const {
return ns_window_host_ && ns_window_host_->layer()
? ns_window_host_->layer()->GetCompositor()
: nullptr;
}
const ui::Layer* NativeWidgetMac::GetLayer() const {
return ns_window_host_ ? ns_window_host_->layer() : nullptr;
}
void NativeWidgetMac::ReorderNativeViews() {
if (ns_window_host_)
ns_window_host_->ReorderChildViews();
}
void NativeWidgetMac::ViewRemoved(View* view) {
DragDropClientMac* client =
ns_window_host_ ? ns_window_host_->drag_drop_client() : nullptr;
if (client)
client->drop_helper()->ResetTargetViewIfEquals(view);
}
void NativeWidgetMac::SetNativeWindowProperty(const char* name, void* value) {
if (ns_window_host_)
ns_window_host_->SetNativeWindowProperty(name, value);
}
void* NativeWidgetMac::GetNativeWindowProperty(const char* name) const {
if (ns_window_host_)
return ns_window_host_->GetNativeWindowProperty(name);
return nullptr;
}
TooltipManager* NativeWidgetMac::GetTooltipManager() const {
if (ns_window_host_)
return ns_window_host_->tooltip_manager();
return nullptr;
}
void NativeWidgetMac::SetCapture() {
if (GetNSWindowMojo())
GetNSWindowMojo()->AcquireCapture();
}
void NativeWidgetMac::ReleaseCapture() {
if (GetNSWindowMojo())
GetNSWindowMojo()->ReleaseCapture();
}
bool NativeWidgetMac::HasCapture() const {
return ns_window_host_ && ns_window_host_->IsMouseCaptureActive();
}
ui::InputMethod* NativeWidgetMac::GetInputMethod() {
if (!input_method_) {
input_method_ = ui::CreateInputMethod(this, gfx::kNullAcceleratedWidget);
// For now, use always-focused mode on Mac for the input method.
// TODO(tapted): Move this to OnWindowKeyStatusChangedTo() and balance.
input_method_->OnFocus();
}
return input_method_.get();
}
void NativeWidgetMac::CenterWindow(const gfx::Size& size) {
GetNSWindowMojo()->SetSizeAndCenter(size, GetWidget()->GetMinimumSize());
}
void NativeWidgetMac::GetWindowPlacement(
gfx::Rect* bounds,
ui::WindowShowState* show_state) const {
*bounds = GetRestoredBounds();
if (IsFullscreen())
*show_state = ui::SHOW_STATE_FULLSCREEN;
else if (IsMinimized())
*show_state = ui::SHOW_STATE_MINIMIZED;
else
*show_state = ui::SHOW_STATE_NORMAL;
}
bool NativeWidgetMac::SetWindowTitle(const std::u16string& title) {
if (!ns_window_host_)
return false;
return ns_window_host_->SetWindowTitle(title);
}
void NativeWidgetMac::SetWindowIcons(const gfx::ImageSkia& window_icon,
const gfx::ImageSkia& app_icon) {
// Per-window icons are not really a thing on Mac, so do nothing.
// TODO(tapted): Investigate whether to use NSWindowDocumentIconButton to set
// an icon next to the window title. See http://crbug.com/766897.
}
void NativeWidgetMac::InitModalType(ui::ModalType modal_type) {
if (modal_type == ui::MODAL_TYPE_NONE)
return;
// System modal windows not implemented (or used) on Mac.
DCHECK_NE(ui::MODAL_TYPE_SYSTEM, modal_type);
// A peculiarity of the constrained window framework is that it permits a
// dialog of MODAL_TYPE_WINDOW to have a null parent window; falling back to
// a non-modal window in this case.
DCHECK(ns_window_host_->parent() || modal_type == ui::MODAL_TYPE_WINDOW);
// Everything happens upon show.
}
const gfx::ImageSkia* NativeWidgetMac::GetWindowIcon() {
return nullptr;
}
const gfx::ImageSkia* NativeWidgetMac::GetWindowAppIcon() {
return nullptr;
}
gfx::Rect NativeWidgetMac::GetWindowBoundsInScreen() const {
return ns_window_host_ ? ns_window_host_->GetWindowBoundsInScreen()
: gfx::Rect();
}
gfx::Rect NativeWidgetMac::GetClientAreaBoundsInScreen() const {
return ns_window_host_ ? ns_window_host_->GetContentBoundsInScreen()
: gfx::Rect();
}
gfx::Rect NativeWidgetMac::GetRestoredBounds() const {
return ns_window_host_ ? ns_window_host_->GetRestoredBounds() : gfx::Rect();
}
std::string NativeWidgetMac::GetWorkspace() const {
return ns_window_host_ ? base::Base64Encode(
ns_window_host_->GetWindowStateRestorationData())
: std::string();
}
gfx::Rect NativeWidgetMac::ConvertBoundsToScreenIfNeeded(
const gfx::Rect& bounds) const {
// If there isn't a parent widget, then bounds cannot be relative to the
// parent.
if (!ns_window_host_ || !ns_window_host_->parent() || !GetWidget())
return bounds;
// Replicate the logic in desktop_aura/desktop_screen_position_client.cc.
if (GetAuraWindowTypeForWidgetType(type_) ==
aura::client::WINDOW_TYPE_POPUP ||
GetWidget()->is_top_level()) {
return bounds;
}
// Empty bounds are only allowed to be specified at initialization and are
// expected not to be translated.
if (bounds.IsEmpty())
return bounds;
gfx::Rect bounds_in_screen = bounds;
bounds_in_screen.Offset(
ns_window_host_->parent()->GetWindowBoundsInScreen().OffsetFromOrigin());
return bounds_in_screen;
}
void NativeWidgetMac::SetBounds(const gfx::Rect& bounds) {
if (!ns_window_host_)
return;
ns_window_host_->SetBoundsInScreen(ConvertBoundsToScreenIfNeeded(bounds));
}
void NativeWidgetMac::SetBoundsConstrained(const gfx::Rect& bounds) {
if (!ns_window_host_)
return;
gfx::Rect new_bounds(bounds);
if (ns_window_host_->parent()) {
new_bounds.AdjustToFit(
gfx::Rect(ns_window_host_->parent()->GetWindowBoundsInScreen().size()));
} else {
new_bounds = ConstrainBoundsToDisplayWorkArea(new_bounds);
}
SetBounds(new_bounds);
}
void NativeWidgetMac::SetSize(const gfx::Size& size) {
if (!ns_window_host_)
return;
// Ensure the top-left corner stays in-place (rather than the bottom-left,
// which -[NSWindow setContentSize:] would do).
ns_window_host_->SetBoundsInScreen(
gfx::Rect(GetWindowBoundsInScreen().origin(), size));
}
void NativeWidgetMac::StackAbove(gfx::NativeView native_view) {
if (!GetNSWindowMojo())
return;
auto* sibling_host =
NativeWidgetMacNSWindowHost::GetFromNativeView(native_view);
if (!sibling_host) {
// This will only work if |this| is in-process.
DCHECK(!ns_window_host_->application_host());
NSInteger view_parent = native_view.GetNativeNSView().window.windowNumber;
[GetNativeWindow().GetNativeNSWindow() orderWindow:NSWindowAbove
relativeTo:view_parent];
return;
}
CHECK_EQ(ns_window_host_->application_host(),
sibling_host->application_host())
<< "|native_view|'s NativeWidgetMacNSWindowHost isn't same "
"process |this|";
// Check if |native_view|'s NativeWidgetMacNSWindowHost corresponds to the
// same process as |this|.
GetNSWindowMojo()->StackAbove(sibling_host->bridged_native_widget_id());
return;
}
void NativeWidgetMac::StackAtTop() {
if (GetNSWindowMojo())
GetNSWindowMojo()->StackAtTop();
}
bool NativeWidgetMac::IsStackedAbove(gfx::NativeView native_view) {
if (!GetNSWindowMojo())
return false;
// -[NSApplication orderedWindows] are ordered front-to-back.
NSWindow* first = GetNativeWindow().GetNativeNSWindow();
NSWindow* second = [native_view.GetNativeNSView() window];
for (NSWindow* window in [NSApp orderedWindows]) {
if (window == second)
return !first;
if (window == first)
first = nil;
}
return false;
}
void NativeWidgetMac::SetShape(std::unique_ptr<Widget::ShapeRects> shape) {
NOTIMPLEMENTED();
}
void NativeWidgetMac::Close() {
if (GetNSWindowMojo())
GetNSWindowMojo()->CloseWindow();
}
void NativeWidgetMac::CloseNow() {
if (ns_window_host_)
ns_window_host_->CloseWindowNow();
// Note: |ns_window_host_| will be deleted here, and |this| will be deleted
// here when ownership_ == NATIVE_WIDGET_OWNS_WIDGET,
}
void NativeWidgetMac::Show(ui::WindowShowState show_state,
const gfx::Rect& restore_bounds) {
if (!GetNSWindowMojo())
return;
switch (show_state) {
case ui::SHOW_STATE_DEFAULT:
case ui::SHOW_STATE_NORMAL:
case ui::SHOW_STATE_INACTIVE:
case ui::SHOW_STATE_MINIMIZED:
break;
case ui::SHOW_STATE_MAXIMIZED:
case ui::SHOW_STATE_FULLSCREEN:
NOTIMPLEMENTED();
break;
case ui::SHOW_STATE_END:
NOTREACHED_NORETURN();
}
auto window_state = WindowVisibilityState::kShowAndActivateWindow;
if (show_state == ui::SHOW_STATE_INACTIVE) {
window_state = WindowVisibilityState::kShowInactive;
} else if (show_state == ui::SHOW_STATE_MINIMIZED) {
window_state = WindowVisibilityState::kHideWindow;
} else if (show_state == ui::SHOW_STATE_DEFAULT) {
window_state = delegate_->CanActivate()
? window_state
: WindowVisibilityState::kShowInactive;
}
GetNSWindowMojo()->SetVisibilityState(window_state);
// Ignore the SetInitialFocus() result. BridgedContentView should get
// firstResponder status regardless.
delegate_->SetInitialFocus(show_state);
}
void NativeWidgetMac::Hide() {
if (!GetNSWindowMojo())
return;
GetNSWindowMojo()->SetVisibilityState(WindowVisibilityState::kHideWindow);
}
bool NativeWidgetMac::IsVisible() const {
return ns_window_host_ && ns_window_host_->IsVisible();
}
void NativeWidgetMac::Activate() {
if (!GetNSWindowMojo())
return;
GetNSWindowMojo()->SetVisibilityState(
WindowVisibilityState::kShowAndActivateWindow);
}
void NativeWidgetMac::Deactivate() {
NOTIMPLEMENTED();
}
bool NativeWidgetMac::IsActive() const {
return ns_window_host_ ? ns_window_host_->IsWindowKey() : false;
}
void NativeWidgetMac::SetZOrderLevel(ui::ZOrderLevel order) {
if (!GetNSWindowMojo())
return;
z_order_level_ = order;
GetNSWindowMojo()->SetWindowLevel(CGWindowLevelForZOrderLevel(order, type_));
}
ui::ZOrderLevel NativeWidgetMac::GetZOrderLevel() const {
return z_order_level_;
}
void NativeWidgetMac::SetVisibleOnAllWorkspaces(bool always_visible) {
if (!GetNSWindowMojo())
return;
GetNSWindowMojo()->SetVisibleOnAllSpaces(always_visible);
}
bool NativeWidgetMac::IsVisibleOnAllWorkspaces() const {
return false;
}
void NativeWidgetMac::Maximize() {
if (!GetNSWindowMojo())
return;
GetNSWindowMojo()->SetZoomed(true);
}
void NativeWidgetMac::Minimize() {
if (!GetNSWindowMojo())
return;
GetNSWindowMojo()->SetMiniaturized(true);
}
bool NativeWidgetMac::IsMaximized() const {
if (!ns_window_host_)
return false;
return ns_window_host_->IsZoomed();
}
bool NativeWidgetMac::IsMinimized() const {
if (!ns_window_host_)
return false;
return ns_window_host_->IsMiniaturized();
}
void NativeWidgetMac::Restore() {
if (!GetNSWindowMojo())
return;
GetNSWindowMojo()->ExitFullscreen();
GetNSWindowMojo()->SetMiniaturized(false);
GetNSWindowMojo()->SetZoomed(false);
}
void NativeWidgetMac::SetFullscreen(bool fullscreen,
int64_t target_display_id) {
if (!ns_window_host_)
return;
ns_window_host_->SetFullscreen(fullscreen, target_display_id);
}
bool NativeWidgetMac::IsFullscreen() const {
return ns_window_host_ && ns_window_host_->target_fullscreen_state();
}
void NativeWidgetMac::SetCanAppearInExistingFullscreenSpaces(
bool can_appear_in_existing_fullscreen_spaces) {
if (!GetNSWindowMojo())
return;
GetNSWindowMojo()->SetCanAppearInExistingFullscreenSpaces(
can_appear_in_existing_fullscreen_spaces);
}
void NativeWidgetMac::SetOpacity(float opacity) {
if (!GetNSWindowMojo())
return;
GetNSWindowMojo()->SetOpacity(opacity);
}
void NativeWidgetMac::SetAspectRatio(const gfx::SizeF& aspect_ratio,
const gfx::Size& excluded_margin) {
if (!GetNSWindowMojo())
return;
GetNSWindowMojo()->SetAspectRatio(aspect_ratio, excluded_margin);
}
void NativeWidgetMac::FlashFrame(bool flash_frame) {
NOTIMPLEMENTED();
}
void NativeWidgetMac::RunShellDrag(View* view,
std::unique_ptr<ui::OSExchangeData> data,
const gfx::Point& location,
int operation,
ui::mojom::DragEventSource source) {
if (!ns_window_host_)
return;
ns_window_host_->drag_drop_client()->StartDragAndDrop(view, std::move(data),
operation, source);
}
void NativeWidgetMac::SchedulePaintInRect(const gfx::Rect& rect) {
// |rect| is relative to client area of the window.
NSWindow* window = GetNativeWindow().GetNativeNSWindow();
NSRect client_rect = [window contentRectForFrameRect:[window frame]];
NSRect target_rect = rect.ToCGRect();
// Convert to Appkit coordinate system (origin at bottom left).
target_rect.origin.y =
NSHeight(client_rect) - target_rect.origin.y - NSHeight(target_rect);
[GetNativeView().GetNativeNSView() setNeedsDisplayInRect:target_rect];
if (ns_window_host_ && ns_window_host_->layer())
ns_window_host_->layer()->SchedulePaint(rect);
}
void NativeWidgetMac::ScheduleLayout() {
ui::Compositor* compositor = GetCompositor();
if (compositor)
compositor->ScheduleDraw();
}
void NativeWidgetMac::SetCursor(const ui::Cursor& cursor) {
if (GetNSWindowMojo())
GetNSWindowMojo()->SetCursor(cursor);
}
void NativeWidgetMac::ShowEmojiPanel() {
// We must plumb the call to ui::ShowEmojiPanel() over the bridge so that it
// is called from the correct process.
if (GetNSWindowMojo())
GetNSWindowMojo()->ShowEmojiPanel();
}
bool NativeWidgetMac::IsMouseEventsEnabled() const {
// On platforms with touch, mouse events get disabled and calls to this method
// can affect hover states. Since there is no touch on desktop Mac, this is
// always true. Touch on Mac is tracked in http://crbug.com/445520.
return true;
}
bool NativeWidgetMac::IsMouseButtonDown() const {
return [NSEvent pressedMouseButtons] != 0;
}
void NativeWidgetMac::ClearNativeFocus() {
// To quote DesktopWindowTreeHostX11, "This method is weird and misnamed."
// The goal is to set focus to the content window, thereby removing focus from
// any NSView in the window that doesn't belong to toolkit-views.
if (!GetNSWindowMojo())
return;
GetNSWindowMojo()->MakeFirstResponder();
}
gfx::Rect NativeWidgetMac::GetWorkAreaBoundsInScreen() const {
return ns_window_host_ ? ns_window_host_->GetCurrentDisplay().work_area()
: gfx::Rect();
}
Widget::MoveLoopResult NativeWidgetMac::RunMoveLoop(
const gfx::Vector2d& drag_offset,
Widget::MoveLoopSource source,
Widget::MoveLoopEscapeBehavior escape_behavior) {
if (!GetInProcessNSWindowBridge())
return Widget::MoveLoopResult::kCanceled;
ReleaseCapture();
return GetInProcessNSWindowBridge()->RunMoveLoop(drag_offset)
? Widget::MoveLoopResult::kSuccessful
: Widget::MoveLoopResult::kCanceled;
}
void NativeWidgetMac::EndMoveLoop() {
if (GetInProcessNSWindowBridge())
GetInProcessNSWindowBridge()->EndMoveLoop();
}
void NativeWidgetMac::SetVisibilityChangedAnimationsEnabled(bool value) {
if (GetNSWindowMojo())
GetNSWindowMojo()->SetAnimationEnabled(value);
}
void NativeWidgetMac::SetVisibilityAnimationDuration(
const base::TimeDelta& duration) {
NOTIMPLEMENTED();
}
void NativeWidgetMac::SetVisibilityAnimationTransition(
Widget::VisibilityTransition widget_transitions) {
remote_cocoa::mojom::VisibilityTransition transitions =
remote_cocoa::mojom::VisibilityTransition::kNone;
switch (widget_transitions) {
case Widget::ANIMATE_NONE:
transitions = remote_cocoa::mojom::VisibilityTransition::kNone;
break;
case Widget::ANIMATE_SHOW:
transitions = remote_cocoa::mojom::VisibilityTransition::kShow;
break;
case Widget::ANIMATE_HIDE:
transitions = remote_cocoa::mojom::VisibilityTransition::kHide;
break;
case Widget::ANIMATE_BOTH:
transitions = remote_cocoa::mojom::VisibilityTransition::kBoth;
break;
}
if (GetNSWindowMojo())
GetNSWindowMojo()->SetTransitionsToAnimate(transitions);
}
bool NativeWidgetMac::IsTranslucentWindowOpacitySupported() const {
return false;
}
ui::GestureRecognizer* NativeWidgetMac::GetGestureRecognizer() {
static base::NoDestructor<ui::GestureRecognizerImplMac> recognizer;
return recognizer.get();
}
ui::GestureConsumer* NativeWidgetMac::GetGestureConsumer() {
NOTIMPLEMENTED();
return nullptr;
}
void NativeWidgetMac::OnSizeConstraintsChanged() {
if (!GetNSWindowMojo())
return;
Widget* widget = GetWidget();
GetNSWindowMojo()->SetSizeConstraints(
widget->GetMinimumSize(), widget->GetMaximumSize(),
widget->widget_delegate()->CanResize(),
widget->widget_delegate()->CanMaximize());
}
void NativeWidgetMac::OnNativeViewHierarchyWillChange() {
// If this is not top-level, then the FocusManager may change, so remove our
// listeners.
if (!GetWidget()->is_top_level())
SetFocusManager(nullptr);
parent_key_lock_.reset();
}
void NativeWidgetMac::OnNativeViewHierarchyChanged() {
if (!GetWidget()->is_top_level())
SetFocusManager(GetWidget()->GetFocusManager());
}
std::string NativeWidgetMac::GetName() const {
return name_;
}
base::WeakPtr<internal::NativeWidgetPrivate> NativeWidgetMac::GetWeakPtr() {
return weak_factory.GetWeakPtr();
}
// static
void NativeWidgetMac::SetInitNativeWidgetCallback(
base::RepeatingCallback<void(NativeWidgetMac*)> callback) {
DCHECK(!g_init_native_widget_callback || callback.is_null());
if (callback.is_null()) {
if (g_init_native_widget_callback) {
delete g_init_native_widget_callback;
g_init_native_widget_callback = nullptr;
}
return;
}
g_init_native_widget_callback =
new base::RepeatingCallback<void(NativeWidgetMac*)>(std::move(callback));
}
NativeWidgetMacNSWindow* NativeWidgetMac::CreateNSWindow(
const remote_cocoa::mojom::CreateWindowParams* params) {
return remote_cocoa::NativeWidgetNSWindowBridge::CreateNSWindow(params)
.autorelease();
}
remote_cocoa::ApplicationHost*
NativeWidgetMac::GetRemoteCocoaApplicationHost() {
return nullptr;
}
remote_cocoa::mojom::NativeWidgetNSWindow* NativeWidgetMac::GetNSWindowMojo()
const {
return ns_window_host_ ? ns_window_host_->GetNSWindowMojo() : nullptr;
}
remote_cocoa::NativeWidgetNSWindowBridge*
NativeWidgetMac::GetInProcessNSWindowBridge() const {
return ns_window_host_ ? ns_window_host_->GetInProcessNSWindowBridge()
: nullptr;
}
void NativeWidgetMac::SetFocusManager(FocusManager* new_focus_manager) {
if (focus_manager_) {
if (View* old_focus = focus_manager_->GetFocusedView())
OnDidChangeFocus(old_focus, nullptr);
focus_manager_->RemoveFocusChangeListener(this);
if (zoom_focus_monitor_)
focus_manager_->RemoveFocusChangeListener(zoom_focus_monitor_.get());
}
focus_manager_ = new_focus_manager;
if (focus_manager_) {
if (View* new_focus = focus_manager_->GetFocusedView())
OnDidChangeFocus(nullptr, new_focus);
focus_manager_->AddFocusChangeListener(this);
if (zoom_focus_monitor_)
focus_manager_->AddFocusChangeListener(zoom_focus_monitor_.get());
}
}
void NativeWidgetMac::OnWillChangeFocus(View* focused_before,
View* focused_now) {}
void NativeWidgetMac::OnDidChangeFocus(View* focused_before,
View* focused_now) {
ui::InputMethod* input_method = GetWidget()->GetInputMethod();
if (!input_method)
return;
ui::TextInputClient* new_text_input_client =
input_method->GetTextInputClient();
// Sanity check: For a top level widget, when focus moves away from the widget
// (i.e. |focused_now| is nil), then the textInputClient will be cleared.
DCHECK(!!focused_now || !new_text_input_client ||
!GetWidget()->is_top_level());
if (ns_window_host_) {
ns_window_host_->text_input_host()->SetTextInputClient(
new_text_input_client);
}
}
ui::EventDispatchDetails NativeWidgetMac::DispatchKeyEventPostIME(
ui::KeyEvent* key) {
DCHECK(focus_manager_);
if (!focus_manager_->OnKeyEvent(*key))
key->StopPropagation();
else
GetWidget()->OnKeyEvent(key);
return ui::EventDispatchDetails();
}
////////////////////////////////////////////////////////////////////////////////
// Widget:
// static
void Widget::CloseAllSecondaryWidgets() {
NSArray* starting_windows = [NSApp windows]; // Creates an autoreleased copy.
for (NSWindow* window in starting_windows) {
// Ignore any windows that couldn't have been created by NativeWidgetMac or
// a subclass. GetNativeWidgetForNativeWindow() will later interrogate the
// NSWindow delegate, but we can't trust that delegate to be a valid object.
if (![window isKindOfClass:[NativeWidgetMacNSWindow class]])
continue;
// Record a crash key to detect when client code may destroy a
// WidgetObserver without removing it (possibly leaking the Widget).
// A crash can occur in generic Widget teardown paths when trying to notify.
// See http://crbug.com/808318.
static crash_reporter::CrashKeyString<256> window_info_key("windowInfo");
std::string value = base::SysNSStringToUTF8(
[NSString stringWithFormat:@"Closing %@ (%@)", [window title],
[window className]]);
crash_reporter::ScopedCrashKeyString scopedWindowKey(&window_info_key,
value);
Widget* widget = GetWidgetForNativeWindow(window);
if (widget && widget->is_secondary_widget())
[window close];
}
}
namespace internal {
////////////////////////////////////////////////////////////////////////////////
// internal::NativeWidgetPrivate:
// static
NativeWidgetPrivate* NativeWidgetPrivate::CreateNativeWidget(
internal::NativeWidgetDelegate* delegate) {
return new NativeWidgetMac(delegate);
}
// static
NativeWidgetPrivate* NativeWidgetPrivate::GetNativeWidgetForNativeView(
gfx::NativeView native_view) {
return GetNativeWidgetForNativeWindow([native_view.GetNativeNSView() window]);
}
// static
NativeWidgetPrivate* NativeWidgetPrivate::GetNativeWidgetForNativeWindow(
gfx::NativeWindow window) {
if (NativeWidgetMacNSWindowHost* ns_window_host_impl =
NativeWidgetMacNSWindowHost::GetFromNativeWindow(window)) {
return ns_window_host_impl->native_widget_mac();
}
return nullptr; // Not created by NativeWidgetMac.
}
// static
NativeWidgetPrivate* NativeWidgetPrivate::GetTopLevelNativeWidget(
gfx::NativeView native_view) {
NativeWidgetMacNSWindowHost* window_host =
NativeWidgetMacNSWindowHost::GetFromNativeView(native_view);
if (!window_host)
return nullptr;
while (window_host->parent()) {
if (window_host->native_widget_mac()->GetWidget()->is_top_level())
break;
window_host = window_host->parent();
}
return window_host->native_widget_mac();
}
// static
void NativeWidgetPrivate::GetAllChildWidgets(gfx::NativeView native_view,
Widget::Widgets* children) {
NativeWidgetMacNSWindowHost* window_host =
NativeWidgetMacNSWindowHost::GetFromNativeView(native_view);
if (!window_host) {
NSView* ns_view = native_view.GetNativeNSView();
// The NSWindow is not itself a views::Widget, but it may have children that
// are. Support returning Widgets that are parented to the NSWindow, except:
// - Ignore requests for children of an NSView that is not a contentView.
// - We do not add a Widget for |native_view| to |children| (there is none).
if ([[ns_view window] contentView] != ns_view)
return;
// Collect -sheets and -childWindows. A window should never appear in both,
// since that causes AppKit to glitch.
NSArray* sheet_children = [[ns_view window] sheets];
for (NSWindow* native_child in sheet_children)
GetAllChildWidgets([native_child contentView], children);
for (NSWindow* native_child in [[ns_view window] childWindows]) {
DCHECK(![sheet_children containsObject:native_child]);
GetAllChildWidgets([native_child contentView], children);
}
return;
}
// If |native_view| is a subview of the contentView, it will share an
// NSWindow, but will itself be a native child of the Widget. That is, adding
// window_host->..->GetWidget() to |children| would be adding the _parent_ of
// |native_view|, not the Widget for |native_view|. |native_view| doesn't have
// a corresponding Widget of its own in this case (and so can't have Widget
// children of its own on Mac).
if (window_host->native_widget_mac()->GetNativeView() != native_view)
return;
// Code expects widget for |native_view| to be added to |children|.
if (window_host->native_widget_mac()->GetWidget())
children->insert(window_host->native_widget_mac()->GetWidget());
// When the NSWindow *is* a Widget, only consider children(). I.e. do not
// look through -[NSWindow childWindows] as done for the (!window_host) case
// above. -childWindows does not support hidden windows, and anything in there
// which is not in children() would have been added by AppKit.
for (NativeWidgetMacNSWindowHost* child : window_host->children())
GetAllChildWidgets(child->native_widget_mac()->GetNativeView(), children);
}
// static
void NativeWidgetPrivate::GetAllOwnedWidgets(gfx::NativeView native_view,
Widget::Widgets* owned) {
NativeWidgetMacNSWindowHost* window_host =
NativeWidgetMacNSWindowHost::GetFromNativeView(native_view);
if (!window_host) {
GetAllChildWidgets(native_view, owned);
return;
}
if (window_host->native_widget_mac()->GetNativeView() != native_view)
return;
for (NativeWidgetMacNSWindowHost* child : window_host->children())
GetAllChildWidgets(child->native_widget_mac()->GetNativeView(), owned);
}
// static
void NativeWidgetPrivate::ReparentNativeView(gfx::NativeView child,
gfx::NativeView new_parent) {
DCHECK_NE(child, new_parent);
DCHECK([new_parent.GetNativeNSView() window]);
CHECK(new_parent);
CHECK_NE([child.GetNativeNSView() superview], new_parent.GetNativeNSView());
NativeWidgetMacNSWindowHost* child_window_host =
NativeWidgetMacNSWindowHost::GetFromNativeView(child);
DCHECK(child_window_host);
gfx::NativeView widget_view =
child_window_host->native_widget_mac()->GetNativeView();
DCHECK_EQ(child, widget_view);
gfx::NativeWindow widget_window =
child_window_host->native_widget_mac()->GetNativeWindow();
DCHECK(
[child.GetNativeNSView() isDescendantOf:widget_view.GetNativeNSView()]);
DCHECK(widget_window && ![widget_window.GetNativeNSWindow() isSheet]);
NativeWidgetMacNSWindowHost* parent_window_host =
NativeWidgetMacNSWindowHost::GetFromNativeView(new_parent);
// Early out for no-op changes.
if (child == widget_view &&
child_window_host->parent() == parent_window_host) {
return;
}
// First notify all the widgets that they are being disassociated from their
// previous parent.
Widget::Widgets widgets;
GetAllChildWidgets(child, &widgets);
for (auto* widget : widgets)
widget->NotifyNativeViewHierarchyWillChange();
child_window_host->SetParent(parent_window_host);
// And now, notify them that they have a brand new parent.
for (auto* widget : widgets)
widget->NotifyNativeViewHierarchyChanged();
}
// static
gfx::NativeView NativeWidgetPrivate::GetGlobalCapture(
gfx::NativeView native_view) {
return NativeWidgetMacNSWindowHost::GetGlobalCaptureView();
}
} // namespace internal
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/native_widget_mac.mm | Objective-C++ | unknown | 39,914 |
// 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/widget/native_widget_mac.h"
#include "base/memory/raw_ptr.h"
#import <Cocoa/Cocoa.h>
#import "base/mac/mac_util.h"
#import "base/mac/scoped_nsobject.h"
#include "ui/base/test/ui_controls.h"
#import "ui/base/test/windowed_nsnotification_observer.h"
#import "ui/events/test/cocoa_test_event_utils.h"
#include "ui/views/bubble/bubble_dialog_delegate_view.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/test/native_widget_factory.h"
#include "ui/views/test/test_widget_observer.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/widget/widget_interactive_uitest_utils.h"
namespace views::test {
// Tests for NativeWidgetMac that rely on global window manager state, and can
// not be parallelized.
class NativeWidgetMacInteractiveUITest
: public WidgetTest,
public ::testing::WithParamInterface<bool> {
public:
class Observer;
NativeWidgetMacInteractiveUITest() = default;
NativeWidgetMacInteractiveUITest(const NativeWidgetMacInteractiveUITest&) =
delete;
NativeWidgetMacInteractiveUITest& operator=(
const NativeWidgetMacInteractiveUITest&) = delete;
// WidgetTest:
void SetUp() override {
SetUpForInteractiveTests();
WidgetTest::SetUp();
}
Widget* MakeWidget() {
return GetParam() ? CreateTopLevelFramelessPlatformWidget()
: CreateTopLevelPlatformWidget();
}
protected:
std::unique_ptr<Observer> observer_;
int activation_count_ = 0;
int deactivation_count_ = 0;
};
class NativeWidgetMacInteractiveUITest::Observer : public TestWidgetObserver {
public:
Observer(NativeWidgetMacInteractiveUITest* parent, Widget* widget)
: TestWidgetObserver(widget), parent_(parent) {}
Observer(const Observer&) = delete;
Observer& operator=(const Observer&) = delete;
void OnWidgetActivationChanged(Widget* widget, bool active) override {
if (active)
parent_->activation_count_++;
else
parent_->deactivation_count_++;
}
private:
raw_ptr<NativeWidgetMacInteractiveUITest> parent_;
};
// Test that showing a window causes it to attain global keyWindow status.
TEST_P(NativeWidgetMacInteractiveUITest, ShowAttainsKeyStatus) {
Widget* widget = MakeWidget();
observer_ = std::make_unique<Observer>(this, widget);
EXPECT_FALSE(widget->IsActive());
EXPECT_EQ(0, activation_count_);
{
WidgetActivationWaiter wait_for_first_active(widget, true);
widget->Show();
wait_for_first_active.Wait();
}
EXPECT_TRUE(widget->IsActive());
EXPECT_TRUE([widget->GetNativeWindow().GetNativeNSWindow() isKeyWindow]);
EXPECT_EQ(1, activation_count_);
EXPECT_EQ(0, deactivation_count_);
// Now check that losing and gaining key status due events outside of Widget
// works correctly.
Widget* widget2 = MakeWidget(); // Note: not observed.
EXPECT_EQ(0, deactivation_count_);
{
WidgetActivationWaiter wait_for_deactivate(widget, false);
widget2->Show();
wait_for_deactivate.Wait();
}
EXPECT_EQ(1, deactivation_count_);
EXPECT_FALSE(widget->IsActive());
EXPECT_EQ(1, activation_count_);
{
WidgetActivationWaiter wait_for_external_activate(widget, true);
[widget->GetNativeWindow().GetNativeNSWindow() makeKeyAndOrderFront:nil];
wait_for_external_activate.Wait();
}
EXPECT_TRUE(widget->IsActive());
EXPECT_EQ(1, deactivation_count_);
EXPECT_EQ(2, activation_count_);
widget2->CloseNow();
widget->CloseNow();
EXPECT_EQ(1, deactivation_count_);
EXPECT_EQ(2, activation_count_);
}
// Test that ShowInactive does not take keyWindow status.
TEST_P(NativeWidgetMacInteractiveUITest, ShowInactiveIgnoresKeyStatus) {
WidgetTest::WaitForSystemAppActivation();
Widget* widget = MakeWidget();
NSWindow* widget_window = widget->GetNativeWindow().GetNativeNSWindow();
base::scoped_nsobject<WindowedNSNotificationObserver> waiter(
[[WindowedNSNotificationObserver alloc]
initForNotification:NSWindowDidBecomeKeyNotification
object:widget_window]);
EXPECT_FALSE(widget->IsVisible());
EXPECT_FALSE([widget_window isVisible]);
EXPECT_FALSE(widget->IsActive());
EXPECT_FALSE([widget_window isKeyWindow]);
widget->ShowInactive();
EXPECT_TRUE(widget->IsVisible());
EXPECT_TRUE([widget_window isVisible]);
EXPECT_FALSE(widget->IsActive());
EXPECT_FALSE([widget_window isKeyWindow]);
// If the window were to become active, this would activate it.
RunPendingMessages();
EXPECT_FALSE(widget->IsActive());
EXPECT_FALSE([widget_window isKeyWindow]);
EXPECT_EQ(0, [waiter notificationCount]);
// Activating the inactive widget should make it key, asynchronously.
widget->Activate();
[waiter wait];
EXPECT_EQ(1, [waiter notificationCount]);
EXPECT_TRUE(widget->IsActive());
EXPECT_TRUE([widget_window isKeyWindow]);
widget->CloseNow();
}
namespace {
// Show |widget| and wait for it to become the key window.
void ShowKeyWindow(Widget* widget) {
NSWindow* widget_window = widget->GetNativeWindow().GetNativeNSWindow();
base::scoped_nsobject<WindowedNSNotificationObserver> waiter(
[[WindowedNSNotificationObserver alloc]
initForNotification:NSWindowDidBecomeKeyNotification
object:widget_window]);
widget->Show();
EXPECT_TRUE([waiter wait]);
EXPECT_TRUE([widget_window isKeyWindow]);
}
NSData* ViewAsTIFF(NSView* view) {
NSBitmapImageRep* bitmap =
[view bitmapImageRepForCachingDisplayInRect:[view bounds]];
[view cacheDisplayInRect:[view bounds] toBitmapImageRep:bitmap];
return [bitmap TIFFRepresentation];
}
class TestBubbleView : public BubbleDialogDelegateView {
public:
explicit TestBubbleView(Widget* parent) {
SetAnchorView(parent->GetContentsView());
}
TestBubbleView(const TestBubbleView&) = delete;
TestBubbleView& operator=(const TestBubbleView&) = delete;
};
} // namespace
// Test that parent windows keep their traffic lights enabled when showing
// dialogs.
TEST_F(NativeWidgetMacInteractiveUITest, ParentWindowTrafficLights) {
Widget* parent_widget = CreateTopLevelPlatformWidget();
parent_widget->SetBounds(gfx::Rect(100, 100, 100, 100));
ShowKeyWindow(parent_widget);
NSWindow* parent = parent_widget->GetNativeWindow().GetNativeNSWindow();
EXPECT_TRUE([parent isMainWindow]);
NSButton* button = [parent standardWindowButton:NSWindowCloseButton];
EXPECT_TRUE(button);
NSData* active_button_image = ViewAsTIFF(button);
EXPECT_TRUE(active_button_image);
EXPECT_TRUE(parent_widget->ShouldPaintAsActive());
// If a child widget is key, the parent should paint as active.
Widget* child_widget = new Widget;
Widget::InitParams params =
CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
params.parent = parent_widget->GetNativeView();
child_widget->Init(std::move(params));
child_widget->SetContentsView(new View);
child_widget->Show();
NSWindow* child = child_widget->GetNativeWindow().GetNativeNSWindow();
// Ensure the button instance is still valid.
EXPECT_EQ(button, [parent standardWindowButton:NSWindowCloseButton]);
EXPECT_TRUE(parent_widget->ShouldPaintAsActive());
// Parent window should still be main, and have its traffic lights active.
EXPECT_TRUE([parent isMainWindow]);
EXPECT_FALSE([parent isKeyWindow]);
// Enabled status doesn't actually change, but check anyway.
EXPECT_TRUE([button isEnabled]);
NSData* button_image_with_child = ViewAsTIFF(button);
EXPECT_TRUE([active_button_image isEqualToData:button_image_with_child]);
// Verify that activating some other random window does change the button.
// When the bubble loses activation, it will dismiss itself and update
// Widget::ShouldPaintAsActive().
Widget* other_widget = CreateTopLevelPlatformWidget();
other_widget->SetBounds(gfx::Rect(200, 200, 100, 100));
ShowKeyWindow(other_widget);
EXPECT_FALSE([parent isMainWindow]);
EXPECT_FALSE([parent isKeyWindow]);
EXPECT_FALSE(parent_widget->ShouldPaintAsActive());
EXPECT_TRUE([button isEnabled]);
NSData* inactive_button_image = ViewAsTIFF(button);
EXPECT_FALSE([active_button_image isEqualToData:inactive_button_image]);
// Focus the child again and assert the parent once again paints as active.
[child makeKeyWindow];
EXPECT_TRUE(parent_widget->ShouldPaintAsActive());
EXPECT_TRUE([child isKeyWindow]);
EXPECT_FALSE([parent isKeyWindow]);
child_widget->CloseNow();
other_widget->CloseNow();
parent_widget->CloseNow();
}
// Test activation of a window that has restoration data that was restored to
// the dock. See crbug.com/1205683 .
TEST_F(NativeWidgetMacInteractiveUITest,
DeminiaturizeWindowWithRestorationData) {
Widget* widget = new Widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.native_widget =
CreatePlatformNativeWidgetImpl(widget, kStubCapture, nullptr);
// Start the window off in the dock.
params.show_state = ui::SHOW_STATE_MINIMIZED;
// "{}" in base64encode, to create some dummy restoration data.
const std::string kDummyWindowRestorationData = "e30=";
params.workspace = kDummyWindowRestorationData;
widget->Init(std::move(params));
// Wait for the window to minimize. Ultimately we're going to check the
// NSWindow minimization state, so it would make sense to wait on the
// notification as we do below. However,
// widget->GetNativeWindow().GetNativeNSWindow() returns nil before the call
// to widget->Init(), and we'd need to set up the notification observer at
// that point. So instead, wait on the Widget state change.
{
views::test::PropertyWaiter minimize_waiter(
base::BindRepeating(&Widget::IsMinimized, base::Unretained(widget)),
true);
EXPECT_TRUE(minimize_waiter.Wait());
}
NSWindow* window = widget->GetNativeWindow().GetNativeNSWindow();
EXPECT_TRUE([window isMiniaturized]);
// As part of the window restoration process,
// SessionRestoreImpl::ShowBrowser() -> BrowserView::Show() ->
// views::Widget::Show() -> views::NativeWidgetMac::Show() which calls
// SetVisibilityState(), the code path we want to test. Even though the method
// name is Show(), it "shows" the saved_show_state_ which in this case is
// WindowVisibilityState::kHideWindow.
widget->Show();
EXPECT_TRUE([window isMiniaturized]);
// Activate the window from the dock (i.e.
// SetVisibilityState(WindowVisibilityState::kShowAndActivateWindow)).
base::scoped_nsobject<WindowedNSNotificationObserver>
deminiaturizationObserver([[WindowedNSNotificationObserver alloc]
initForNotification:NSWindowDidDeminiaturizeNotification
object:window]);
widget->Activate();
[deminiaturizationObserver wait];
EXPECT_FALSE([window isMiniaturized]);
widget->CloseNow();
}
// Test that bubble widgets are dismissed on right mouse down.
TEST_F(NativeWidgetMacInteractiveUITest, BubbleDismiss) {
Widget* parent_widget = CreateTopLevelPlatformWidget();
parent_widget->SetBounds(gfx::Rect(100, 100, 100, 100));
ShowKeyWindow(parent_widget);
Widget* bubble_widget =
BubbleDialogDelegateView::CreateBubble(new TestBubbleView(parent_widget));
ShowKeyWindow(bubble_widget);
// First, test with LeftMouseDown in the parent window.
NSEvent* mouse_down = cocoa_test_event_utils::LeftMouseDownAtPointInWindow(
NSMakePoint(50, 50),
parent_widget->GetNativeWindow().GetNativeNSWindow());
[NSApp sendEvent:mouse_down];
EXPECT_TRUE(bubble_widget->IsClosed());
bubble_widget =
BubbleDialogDelegateView::CreateBubble(new TestBubbleView(parent_widget));
ShowKeyWindow(bubble_widget);
// Test with RightMouseDown in the parent window.
mouse_down = cocoa_test_event_utils::RightMouseDownAtPointInWindow(
NSMakePoint(50, 50),
parent_widget->GetNativeWindow().GetNativeNSWindow());
[NSApp sendEvent:mouse_down];
EXPECT_TRUE(bubble_widget->IsClosed());
bubble_widget =
BubbleDialogDelegateView::CreateBubble(new TestBubbleView(parent_widget));
ShowKeyWindow(bubble_widget);
// Test with RightMouseDown in the bubble (bubble should stay open).
mouse_down = cocoa_test_event_utils::RightMouseDownAtPointInWindow(
NSMakePoint(50, 50),
bubble_widget->GetNativeWindow().GetNativeNSWindow());
[NSApp sendEvent:mouse_down];
EXPECT_FALSE(bubble_widget->IsClosed());
bubble_widget->CloseNow();
// Test with RightMouseDown when set_close_on_deactivate(false).
TestBubbleView* bubble_view = new TestBubbleView(parent_widget);
bubble_view->set_close_on_deactivate(false);
bubble_widget = BubbleDialogDelegateView::CreateBubble(bubble_view);
ShowKeyWindow(bubble_widget);
mouse_down = cocoa_test_event_utils::RightMouseDownAtPointInWindow(
NSMakePoint(50, 50),
parent_widget->GetNativeWindow().GetNativeNSWindow());
[NSApp sendEvent:mouse_down];
EXPECT_FALSE(bubble_widget->IsClosed());
parent_widget->CloseNow();
}
// Ensure BridgedContentView's inputContext can handle its window being torn
// away mid-way through event processing. Toolkit-views guarantees to move focus
// away from any Widget when the window is torn down. This test ensures that
// global references AppKit may have held on to are also updated.
TEST_F(NativeWidgetMacInteractiveUITest, GlobalNSTextInputContextUpdates) {
Widget* widget = CreateTopLevelNativeWidget();
Textfield* textfield = new Textfield;
textfield->SetBounds(0, 0, 100, 100);
widget->GetContentsView()->AddChildView(textfield);
textfield->RequestFocus();
{
WidgetActivationWaiter wait_for_first_active(widget, true);
widget->Show();
wait_for_first_active.Wait();
}
EXPECT_TRUE([widget->GetNativeView().GetNativeNSView() inputContext]);
EXPECT_EQ([widget->GetNativeView().GetNativeNSView() inputContext],
[NSTextInputContext currentInputContext]);
widget->GetContentsView()->RemoveChildView(textfield);
// NSTextInputContext usually only updates at the end of an AppKit event loop
// iteration. We just tore out the inputContext, so ensure the raw, weak
// global pointer that AppKit likes to keep around has been updated manually.
EXPECT_EQ(nil, [NSTextInputContext currentInputContext]);
EXPECT_FALSE([widget->GetNativeView().GetNativeNSView() inputContext]);
// RemoveChildView() doesn't delete the view.
delete textfield;
widget->Close();
base::RunLoop().RunUntilIdle();
}
INSTANTIATE_TEST_SUITE_P(NativeWidgetMacInteractiveUITestInstance,
NativeWidgetMacInteractiveUITest,
::testing::Bool());
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/native_widget_mac_interactive_uitest.mm | Objective-C++ | unknown | 14,759 |
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/memory/raw_ptr.h"
#import "base/task/single_thread_task_runner.h"
#include "base/task/single_thread_task_runner.h"
#import "ui/views/widget/native_widget_mac.h"
#import <Cocoa/Cocoa.h>
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#import "base/mac/foundation_util.h"
#include "base/mac/mac_util.h"
#import "base/mac/scoped_nsobject.h"
#import "base/mac/scoped_objc_class_swizzler.h"
#include "base/run_loop.h"
#include "base/strings/sys_string_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/test_timeouts.h"
#include "build/build_config.h"
#import "components/remote_cocoa/app_shim/bridged_content_view.h"
#import "components/remote_cocoa/app_shim/native_widget_mac_nswindow.h"
#import "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h"
#import "testing/gtest_mac.h"
#include "third_party/skia/include/core/SkBitmap.h"
#include "third_party/skia/include/core/SkCanvas.h"
#import "ui/base/cocoa/constrained_window/constrained_window_animation.h"
#import "ui/base/cocoa/window_size_constants.h"
#import "ui/base/test/scoped_fake_full_keyboard_access.h"
#import "ui/base/test/windowed_nsnotification_observer.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/recyclable_compositor_mac.h"
#import "ui/events/test/cocoa_test_event_utils.h"
#include "ui/events/test/event_generator.h"
#import "ui/gfx/mac/coordinate_conversion.h"
#include "ui/views/bubble/bubble_dialog_delegate_view.h"
#include "ui/views/cocoa/native_widget_mac_ns_window_host.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/native/native_view_host.h"
#include "ui/views/test/native_widget_factory.h"
#include "ui/views/test/test_widget_observer.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/widget/native_widget_mac.h"
#include "ui/views/widget/native_widget_private.h"
#include "ui/views/widget/widget_interactive_uitest_utils.h"
#include "ui/views/window/dialog_delegate.h"
namespace {
// "{}" in base64encode, to create some dummy restoration data.
const std::string kDummyWindowRestorationData = "e30=";
} // namespace
// Donates an implementation of -[NSAnimation stopAnimation] which calls the
// original implementation, then quits a nested run loop.
@interface TestStopAnimationWaiter : NSObject
@end
@interface ConstrainedWindowAnimationBase (TestingAPI)
- (void)setWindowStateForEnd;
@end
// Test NSWindow that provides hooks via method overrides to verify behavior.
@interface NativeWidgetMacTestWindow : NativeWidgetMacNSWindow
@property(readonly, nonatomic) int invalidateShadowCount;
@property(assign, nonatomic) BOOL fakeOnInactiveSpace;
@property(assign, nonatomic) bool* deallocFlag;
+ (void)waitForDealloc;
@end
// Used to mock BridgedContentView so that calls to drawRect: can be
// intercepted.
@interface MockBridgedView : NSView {
@private
// Number of times -[NSView drawRect:] has been called.
NSUInteger _drawRectCount;
// The dirtyRect parameter passed to last invocation of drawRect:.
NSRect _lastDirtyRect;
}
@property(assign, nonatomic) NSUInteger drawRectCount;
@property(assign, nonatomic) NSRect lastDirtyRect;
@end
@interface FocusableTestNSView : NSView
@end
namespace views::test {
// NativeWidgetNSWindowBridge friend to access private members.
class BridgedNativeWidgetTestApi {
public:
explicit BridgedNativeWidgetTestApi(NSWindow* window) {
bridge_ = NativeWidgetMacNSWindowHost::GetFromNativeWindow(window)
->GetInProcessNSWindowBridge();
}
BridgedNativeWidgetTestApi(const BridgedNativeWidgetTestApi&) = delete;
BridgedNativeWidgetTestApi& operator=(const BridgedNativeWidgetTestApi&) =
delete;
// Simulate a frame swap from the compositor.
void SimulateFrameSwap(const gfx::Size& size) {
const float kScaleFactor = 1.0f;
gfx::CALayerParams ca_layer_params;
ca_layer_params.is_empty = false;
ca_layer_params.pixel_size = size;
ca_layer_params.scale_factor = kScaleFactor;
bridge_->SetCALayerParams(ca_layer_params);
}
NSAnimation* show_animation() {
return base::mac::ObjCCastStrict<NSAnimation>(
bridge_->show_animation_.get());
}
bool HasWindowRestorationData() {
return bridge_->HasWindowRestorationData();
}
private:
raw_ptr<remote_cocoa::NativeWidgetNSWindowBridge> bridge_;
};
// Custom native_widget to create a NativeWidgetMacTestWindow.
class TestWindowNativeWidgetMac : public NativeWidgetMac {
public:
explicit TestWindowNativeWidgetMac(Widget* delegate)
: NativeWidgetMac(delegate) {}
TestWindowNativeWidgetMac(const TestWindowNativeWidgetMac&) = delete;
TestWindowNativeWidgetMac& operator=(const TestWindowNativeWidgetMac&) =
delete;
protected:
// NativeWidgetMac:
void PopulateCreateWindowParams(
const views::Widget::InitParams& widget_params,
remote_cocoa::mojom::CreateWindowParams* params) override {
params->style_mask = NSWindowStyleMaskBorderless;
if (widget_params.type == Widget::InitParams::TYPE_WINDOW) {
params->style_mask = NSWindowStyleMaskTitled | NSWindowStyleMaskClosable |
NSWindowStyleMaskMiniaturizable |
NSWindowStyleMaskResizable;
}
}
NativeWidgetMacNSWindow* CreateNSWindow(
const remote_cocoa::mojom::CreateWindowParams* params) override {
return [[[NativeWidgetMacTestWindow alloc]
initWithContentRect:ui::kWindowSizeDeterminedLater
styleMask:params->style_mask
backing:NSBackingStoreBuffered
defer:NO] autorelease];
}
};
// Tests for parts of NativeWidgetMac not covered by NativeWidgetNSWindowBridge,
// which need access to Cocoa APIs.
class NativeWidgetMacTest : public WidgetTest {
public:
NativeWidgetMacTest() = default;
NativeWidgetMacTest(const NativeWidgetMacTest&) = delete;
NativeWidgetMacTest& operator=(const NativeWidgetMacTest&) = delete;
// Make an NSWindow with a close button and a title bar to use as a parent.
// This NSWindow is backed by a widget that is not exposed to the caller.
// To destroy the Widget, the native NSWindow must be closed.
NativeWidgetMacTestWindow* MakeClosableTitledNativeParent() {
NativeWidgetMacTestWindow* native_parent = nil;
Widget::InitParams parent_init_params =
CreateParams(Widget::InitParams::TYPE_WINDOW);
parent_init_params.bounds = gfx::Rect(100, 100, 200, 200);
CreateWidgetWithTestWindow(std::move(parent_init_params), &native_parent);
return native_parent;
}
// Same as the above, but creates a borderless NSWindow.
NativeWidgetMacTestWindow* MakeBorderlessNativeParent() {
NativeWidgetMacTestWindow* native_parent = nil;
Widget::InitParams parent_init_params =
CreateParams(Widget::InitParams::TYPE_WINDOW);
parent_init_params.remove_standard_frame = true;
parent_init_params.bounds = gfx::Rect(100, 100, 200, 200);
CreateWidgetWithTestWindow(std::move(parent_init_params), &native_parent);
return native_parent;
}
// Create a Widget backed by the NativeWidgetMacTestWindow NSWindow subclass.
Widget* CreateWidgetWithTestWindow(Widget::InitParams params,
NativeWidgetMacTestWindow** window) {
Widget* widget = new Widget;
params.native_widget = new TestWindowNativeWidgetMac(widget);
widget->Init(std::move(params));
widget->Show();
*window = base::mac::ObjCCastStrict<NativeWidgetMacTestWindow>(
widget->GetNativeWindow().GetNativeNSWindow());
EXPECT_TRUE(*window);
return widget;
}
FocusManager* GetFocusManager(NativeWidgetMac* native_widget) const {
return native_widget->focus_manager_;
}
};
class WidgetChangeObserver : public TestWidgetObserver {
public:
explicit WidgetChangeObserver(Widget* widget) : TestWidgetObserver(widget) {}
WidgetChangeObserver(const WidgetChangeObserver&) = delete;
WidgetChangeObserver& operator=(const WidgetChangeObserver&) = delete;
void WaitForVisibleCounts(int gained, int lost) {
if (gained_visible_count_ >= gained && lost_visible_count_ >= lost)
return;
target_gained_visible_count_ = gained;
target_lost_visible_count_ = lost;
base::RunLoop run_loop;
run_loop_ = &run_loop;
base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE, run_loop.QuitClosure(), TestTimeouts::action_timeout());
run_loop.Run();
run_loop_ = nullptr;
}
int gained_visible_count() const { return gained_visible_count_; }
int lost_visible_count() const { return lost_visible_count_; }
private:
// WidgetObserver:
void OnWidgetVisibilityChanged(Widget* widget,
bool visible) override {
++(visible ? gained_visible_count_ : lost_visible_count_);
if (run_loop_ && gained_visible_count_ >= target_gained_visible_count_ &&
lost_visible_count_ >= target_lost_visible_count_)
run_loop_->Quit();
}
int gained_visible_count_ = 0;
int lost_visible_count_ = 0;
int target_gained_visible_count_ = 0;
int target_lost_visible_count_ = 0;
raw_ptr<base::RunLoop> run_loop_ = nullptr;
};
// This class gives public access to the protected ctor of
// BubbleDialogDelegateView.
class SimpleBubbleView : public BubbleDialogDelegateView {
public:
SimpleBubbleView() = default;
SimpleBubbleView(const SimpleBubbleView&) = delete;
SimpleBubbleView& operator=(const SimpleBubbleView&) = delete;
~SimpleBubbleView() override = default;
};
class CustomTooltipView : public View {
public:
CustomTooltipView(const std::u16string& tooltip, View* tooltip_handler)
: tooltip_(tooltip), tooltip_handler_(tooltip_handler) {}
CustomTooltipView(const CustomTooltipView&) = delete;
CustomTooltipView& operator=(const CustomTooltipView&) = delete;
// View:
std::u16string GetTooltipText(const gfx::Point& p) const override {
return tooltip_;
}
View* GetTooltipHandlerForPoint(const gfx::Point& point) override {
return tooltip_handler_ ? tooltip_handler_.get() : this;
}
private:
std::u16string tooltip_;
raw_ptr<View> tooltip_handler_; // Weak
};
// A Widget subclass that exposes counts to calls made to OnMouseEvent().
class MouseTrackingWidget : public Widget {
public:
int GetMouseEventCount(ui::EventType type) { return counts_[type]; }
void OnMouseEvent(ui::MouseEvent* event) override {
++counts_[event->type()];
Widget::OnMouseEvent(event);
}
private:
std::map<int, int> counts_;
};
// Test visibility states triggered externally.
TEST_F(NativeWidgetMacTest, HideAndShowExternally) {
Widget* widget = CreateTopLevelPlatformWidget();
NSWindow* ns_window = widget->GetNativeWindow().GetNativeNSWindow();
WidgetChangeObserver observer(widget);
// Should initially be hidden.
EXPECT_FALSE(widget->IsVisible());
EXPECT_FALSE([ns_window isVisible]);
EXPECT_EQ(0, observer.gained_visible_count());
EXPECT_EQ(0, observer.lost_visible_count());
widget->Show();
EXPECT_TRUE(widget->IsVisible());
EXPECT_TRUE([ns_window isVisible]);
EXPECT_EQ(1, observer.gained_visible_count());
EXPECT_EQ(0, observer.lost_visible_count());
widget->Hide();
EXPECT_FALSE(widget->IsVisible());
EXPECT_FALSE([ns_window isVisible]);
EXPECT_EQ(1, observer.gained_visible_count());
EXPECT_EQ(1, observer.lost_visible_count());
widget->Show();
EXPECT_TRUE(widget->IsVisible());
EXPECT_TRUE([ns_window isVisible]);
EXPECT_EQ(2, observer.gained_visible_count());
EXPECT_EQ(1, observer.lost_visible_count());
// Test when hiding individual windows.
[ns_window orderOut:nil];
EXPECT_FALSE(widget->IsVisible());
EXPECT_FALSE([ns_window isVisible]);
EXPECT_EQ(2, observer.gained_visible_count());
EXPECT_EQ(2, observer.lost_visible_count());
[ns_window orderFront:nil];
EXPECT_TRUE(widget->IsVisible());
EXPECT_TRUE([ns_window isVisible]);
EXPECT_EQ(3, observer.gained_visible_count());
EXPECT_EQ(2, observer.lost_visible_count());
// Test when hiding the entire application. This doesn't send an orderOut:
// to the NSWindow.
[NSApp hide:nil];
// When the activation policy is NSApplicationActivationPolicyRegular, the
// calls via NSApp are asynchronous, and the run loop needs to be flushed.
// With NSApplicationActivationPolicyProhibited, the following
// WaitForVisibleCounts calls are superfluous, but don't hurt.
observer.WaitForVisibleCounts(3, 3);
EXPECT_FALSE(widget->IsVisible());
EXPECT_FALSE([ns_window isVisible]);
EXPECT_EQ(3, observer.gained_visible_count());
EXPECT_EQ(3, observer.lost_visible_count());
[NSApp unhideWithoutActivation];
observer.WaitForVisibleCounts(4, 3);
EXPECT_TRUE(widget->IsVisible());
EXPECT_TRUE([ns_window isVisible]);
EXPECT_EQ(4, observer.gained_visible_count());
EXPECT_EQ(3, observer.lost_visible_count());
// Hide again to test unhiding with an activation.
[NSApp hide:nil];
observer.WaitForVisibleCounts(4, 4);
EXPECT_EQ(4, observer.lost_visible_count());
[NSApp unhide:nil];
observer.WaitForVisibleCounts(5, 4);
EXPECT_EQ(5, observer.gained_visible_count());
// Hide again to test makeKeyAndOrderFront:.
[ns_window orderOut:nil];
EXPECT_FALSE(widget->IsVisible());
EXPECT_FALSE([ns_window isVisible]);
EXPECT_EQ(5, observer.gained_visible_count());
EXPECT_EQ(5, observer.lost_visible_count());
[ns_window makeKeyAndOrderFront:nil];
EXPECT_TRUE(widget->IsVisible());
EXPECT_TRUE([ns_window isVisible]);
EXPECT_EQ(6, observer.gained_visible_count());
EXPECT_EQ(5, observer.lost_visible_count());
// No change when closing.
widget->CloseNow();
EXPECT_EQ(5, observer.lost_visible_count());
EXPECT_EQ(6, observer.gained_visible_count());
}
// Check methods that should not be implemented by NativeWidgetMac.
TEST_F(NativeWidgetMacTest, NotImplemented) {
NSWindow* native_parent = MakeBorderlessNativeParent();
NativeWidgetMacNSWindowHost* window_host =
NativeWidgetMacNSWindowHost::GetFromNativeWindow(native_parent);
EXPECT_FALSE(window_host->native_widget_mac()->WillExecuteCommand(
5001, WindowOpenDisposition::CURRENT_TAB, true));
EXPECT_FALSE(window_host->native_widget_mac()->ExecuteCommand(
5001, WindowOpenDisposition::CURRENT_TAB, true));
[native_parent close];
}
// Tests the WindowFrameTitlebarHeight method.
TEST_F(NativeWidgetMacTest, WindowFrameTitlebarHeight) {
NSWindow* native_parent = MakeBorderlessNativeParent();
NativeWidgetMacNSWindowHost* window_host =
NativeWidgetMacNSWindowHost::GetFromNativeWindow(native_parent);
bool override_titlebar_height = true;
float titlebar_height = 100.0;
window_host->native_widget_mac()->GetWindowFrameTitlebarHeight(
&override_titlebar_height, &titlebar_height);
EXPECT_EQ(false, override_titlebar_height);
EXPECT_EQ(0.0, titlebar_height);
[native_parent close];
}
// A view that counts calls to OnPaint().
class PaintCountView : public View {
public:
PaintCountView() { SetBounds(0, 0, 100, 100); }
PaintCountView(const PaintCountView&) = delete;
PaintCountView& operator=(const PaintCountView&) = delete;
// View:
void OnPaint(gfx::Canvas* canvas) override {
EXPECT_TRUE(GetWidget()->IsVisible());
++paint_count_;
if (run_loop_ && paint_count_ == target_paint_count_)
run_loop_->Quit();
}
void WaitForPaintCount(int target) {
if (paint_count_ == target)
return;
target_paint_count_ = target;
base::RunLoop run_loop;
run_loop_ = &run_loop;
run_loop.Run();
run_loop_ = nullptr;
}
int paint_count() { return paint_count_; }
private:
int paint_count_ = 0;
int target_paint_count_ = 0;
raw_ptr<base::RunLoop> run_loop_ = nullptr;
};
// Test that a child widget is only added to its parent NSWindow when the
// parent is on the active space. Otherwise, it may cause a space transition.
// See https://crbug.com/866760.
TEST_F(NativeWidgetMacTest, ChildWidgetOnInactiveSpace) {
NativeWidgetMacTestWindow* parent_window;
NativeWidgetMacTestWindow* child_window;
Widget::InitParams init_params =
CreateParams(Widget::InitParams::TYPE_WINDOW);
init_params.bounds = gfx::Rect(100, 100, 200, 200);
Widget* parent =
CreateWidgetWithTestWindow(std::move(init_params), &parent_window);
parent_window.fakeOnInactiveSpace = YES;
init_params.parent = parent->GetNativeView();
CreateWidgetWithTestWindow(std::move(init_params), &child_window);
EXPECT_EQ(nil, child_window.parentWindow);
parent_window.fakeOnInactiveSpace = NO;
parent->Show();
EXPECT_EQ(parent_window, child_window.parentWindow);
parent->CloseNow();
}
// Test minimized states triggered externally, implied visibility and restored
// bounds whilst minimized.
TEST_F(NativeWidgetMacTest, MiniaturizeExternally) {
Widget* widget = new Widget;
Widget::InitParams init_params(Widget::InitParams::TYPE_WINDOW);
widget->Init(std::move(init_params));
PaintCountView* view = new PaintCountView();
widget->GetContentsView()->AddChildView(view);
NSWindow* ns_window = widget->GetNativeWindow().GetNativeNSWindow();
WidgetChangeObserver observer(widget);
widget->SetBounds(gfx::Rect(100, 100, 300, 300));
EXPECT_TRUE(view->IsDrawn());
EXPECT_EQ(0, view->paint_count());
{
views::test::PropertyWaiter visibility_waiter(
base::BindRepeating(&Widget::IsVisible, base::Unretained(widget)),
true);
widget->Show();
EXPECT_TRUE(visibility_waiter.Wait());
}
EXPECT_EQ(1, observer.gained_visible_count());
EXPECT_EQ(0, observer.lost_visible_count());
const gfx::Rect restored_bounds = widget->GetRestoredBounds();
EXPECT_FALSE(restored_bounds.IsEmpty());
EXPECT_FALSE(widget->IsMinimized());
EXPECT_TRUE(widget->IsVisible());
// Showing should paint.
view->WaitForPaintCount(1);
// First try performMiniaturize:, which requires a minimize button. Note that
// Cocoa just blocks the UI thread during the animation, so no need to do
// anything fancy to wait for it finish.
{
views::test::PropertyWaiter minimize_waiter(
base::BindRepeating(&Widget::IsMinimized, base::Unretained(widget)),
true);
[ns_window performMiniaturize:nil];
EXPECT_TRUE(minimize_waiter.Wait());
}
EXPECT_TRUE(widget->IsMinimized());
EXPECT_FALSE(widget->IsVisible()); // Minimizing also makes things invisible.
EXPECT_EQ(1, observer.gained_visible_count());
EXPECT_EQ(1, observer.lost_visible_count());
EXPECT_EQ(restored_bounds, widget->GetRestoredBounds());
// No repaint when minimizing. But note that this is partly due to not calling
// [NSView setNeedsDisplay:YES] on the content view. The superview, which is
// an NSThemeFrame, would repaint |view| if we had, because the miniaturize
// button is highlighted for performMiniaturize.
EXPECT_EQ(1, view->paint_count());
{
views::test::PropertyWaiter deminimize_waiter(
base::BindRepeating(&Widget::IsMinimized, base::Unretained(widget)),
false);
[ns_window deminiaturize:nil];
EXPECT_TRUE(deminimize_waiter.Wait());
}
EXPECT_FALSE(widget->IsMinimized());
EXPECT_TRUE(widget->IsVisible());
EXPECT_EQ(2, observer.gained_visible_count());
EXPECT_EQ(1, observer.lost_visible_count());
EXPECT_EQ(restored_bounds, widget->GetRestoredBounds());
view->WaitForPaintCount(2); // A single paint when deminiaturizing.
EXPECT_FALSE([ns_window isMiniaturized]);
{
views::test::PropertyWaiter minimize_waiter(
base::BindRepeating(&Widget::IsMinimized, base::Unretained(widget)),
true);
widget->Minimize();
EXPECT_TRUE(minimize_waiter.Wait());
}
EXPECT_TRUE(widget->IsMinimized());
EXPECT_TRUE([ns_window isMiniaturized]);
EXPECT_EQ(2, observer.gained_visible_count());
EXPECT_EQ(2, observer.lost_visible_count());
EXPECT_EQ(restored_bounds, widget->GetRestoredBounds());
EXPECT_EQ(2, view->paint_count()); // No paint when miniaturizing.
{
views::test::PropertyWaiter deminimize_waiter(
base::BindRepeating(&Widget::IsMinimized, base::Unretained(widget)),
false);
widget->Restore(); // If miniaturized, should deminiaturize.
EXPECT_TRUE(deminimize_waiter.Wait());
}
EXPECT_FALSE(widget->IsMinimized());
EXPECT_FALSE([ns_window isMiniaturized]);
EXPECT_EQ(3, observer.gained_visible_count());
EXPECT_EQ(2, observer.lost_visible_count());
EXPECT_EQ(restored_bounds, widget->GetRestoredBounds());
view->WaitForPaintCount(3);
{
views::test::PropertyWaiter deminimize_waiter(
base::BindRepeating(&Widget::IsMinimized, base::Unretained(widget)),
false);
widget->Restore(); // If not miniaturized, does nothing.
EXPECT_TRUE(deminimize_waiter.Wait());
}
EXPECT_FALSE(widget->IsMinimized());
EXPECT_FALSE([ns_window isMiniaturized]);
EXPECT_EQ(3, observer.gained_visible_count());
EXPECT_EQ(2, observer.lost_visible_count());
EXPECT_EQ(restored_bounds, widget->GetRestoredBounds());
EXPECT_EQ(3, view->paint_count());
widget->CloseNow();
}
TEST_F(NativeWidgetMacTest, MiniaturizeFramelessWindow) {
// Create a widget without a minimize button.
Widget* widget = CreateTopLevelFramelessPlatformWidget();
NSWindow* ns_window = widget->GetNativeWindow().GetNativeNSWindow();
widget->SetBounds(gfx::Rect(100, 100, 300, 300));
widget->Show();
EXPECT_FALSE(widget->IsMinimized());
// This should fail, since performMiniaturize: requires a minimize button.
[ns_window performMiniaturize:nil];
EXPECT_FALSE(widget->IsMinimized());
// But this should work.
widget->Minimize();
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(widget->IsMinimized());
// Test closing while minimized.
widget->CloseNow();
}
// Simple view for the SetCursor test that overrides View::GetCursor().
class CursorView : public View {
public:
CursorView(int x, const ui::Cursor& cursor) : cursor_(cursor) {
SetBounds(x, 0, 100, 300);
}
CursorView(const CursorView&) = delete;
CursorView& operator=(const CursorView&) = delete;
// View:
ui::Cursor GetCursor(const ui::MouseEvent& event) override { return cursor_; }
private:
ui::Cursor cursor_;
};
// Test for Widget::SetCursor(). There is no Widget::GetCursor(), so this uses
// -[NSCursor currentCursor] to validate expectations. Note that currentCursor
// is just "the top cursor on the application's cursor stack.", which is why it
// is safe to use this in a non-interactive UI test with the EventGenerator.
TEST_F(NativeWidgetMacTest, SetCursor) {
NSCursor* arrow = [NSCursor arrowCursor];
NSCursor* hand = [NSCursor pointingHandCursor];
NSCursor* ibeam = [NSCursor IBeamCursor];
Widget* widget = CreateTopLevelPlatformWidget();
widget->SetBounds(gfx::Rect(0, 0, 300, 300));
auto* view_hand = widget->non_client_view()->frame_view()->AddChildView(
std::make_unique<CursorView>(0, ui::mojom::CursorType::kHand));
auto* view_ibeam = widget->non_client_view()->frame_view()->AddChildView(
std::make_unique<CursorView>(100, ui::mojom::CursorType::kIBeam));
widget->Show();
NSWindow* widget_window = widget->GetNativeWindow().GetNativeNSWindow();
// Events used to simulate tracking rectangle updates. These are not passed to
// toolkit-views, so it only matters whether they are inside or outside the
// content area.
const gfx::Rect bounds = widget->GetWindowBoundsInScreen();
NSEvent* event_in_content = cocoa_test_event_utils::MouseEventAtPoint(
NSMakePoint(bounds.x(), bounds.y()), NSEventTypeMouseMoved, 0);
NSEvent* event_out_of_content = cocoa_test_event_utils::MouseEventAtPoint(
NSMakePoint(-50, -50), NSEventTypeMouseMoved, 0);
EXPECT_NE(arrow, hand);
EXPECT_NE(arrow, ibeam);
// Make arrow the current cursor.
[arrow set];
EXPECT_EQ(arrow, [NSCursor currentCursor]);
// Use an event generator to ask views code to set the cursor. However, note
// that this does not cause Cocoa to generate tracking rectangle updates.
ui::test::EventGenerator event_generator(GetContext(), widget_window);
// Move the mouse over the first view, then simulate a tracking rectangle
// update. Verify that the cursor changed from arrow to hand type.
event_generator.MoveMouseTo(view_hand->GetBoundsInScreen().CenterPoint());
[widget_window cursorUpdate:event_in_content];
EXPECT_EQ(hand, [NSCursor currentCursor]);
// A tracking rectangle update not in the content area should forward to
// the native NSWindow implementation, which sets the arrow cursor.
[widget_window cursorUpdate:event_out_of_content];
EXPECT_EQ(arrow, [NSCursor currentCursor]);
// Now move to the second view.
event_generator.MoveMouseTo(view_ibeam->GetBoundsInScreen().CenterPoint());
[widget_window cursorUpdate:event_in_content];
EXPECT_EQ(ibeam, [NSCursor currentCursor]);
// Moving to the third view (but remaining in the content area) should also
// forward to the native NSWindow implementation.
event_generator.MoveMouseTo(widget->non_client_view()
->frame_view()
->GetBoundsInScreen()
.bottom_right());
[widget_window cursorUpdate:event_in_content];
EXPECT_EQ(arrow, [NSCursor currentCursor]);
widget->CloseNow();
}
// Tests that an accessibility request from the system makes its way through to
// a views::Label filling the window.
TEST_F(NativeWidgetMacTest, AccessibilityIntegration) {
Widget* widget = CreateTopLevelPlatformWidget();
gfx::Rect screen_rect(50, 50, 100, 100);
widget->SetBounds(screen_rect);
const std::u16string test_string = u"Green";
views::Label* label = new views::Label(test_string);
label->SetBounds(0, 0, 100, 100);
widget->GetContentsView()->AddChildView(label);
widget->Show();
// Accessibility hit tests come in Cocoa screen coordinates.
NSRect nsrect = gfx::ScreenRectToNSRect(screen_rect);
NSPoint midpoint = NSMakePoint(NSMidX(nsrect), NSMidY(nsrect));
id hit = [widget->GetNativeWindow().GetNativeNSWindow()
accessibilityHitTest:midpoint];
ASSERT_TRUE([hit conformsToProtocol:@protocol(NSAccessibility)]);
id<NSAccessibility> ax_hit = hit;
id title = ax_hit.accessibilityValue;
EXPECT_NSEQ(title, @"Green");
widget->CloseNow();
}
namespace {
Widget* AttachPopupToNativeParent(NSWindow* native_parent) {
base::scoped_nsobject<NSView> anchor_view(
[[NSView alloc] initWithFrame:[[native_parent contentView] bounds]]);
[[native_parent contentView] addSubview:anchor_view];
// Note: Don't use WidgetTest::CreateChildPlatformWidget because that makes
// windows of TYPE_CONTROL which need a parent Widget to obtain the focus
// manager.
Widget* child = new Widget;
Widget::InitParams init_params;
init_params.parent = anchor_view.get();
init_params.child = true;
init_params.type = Widget::InitParams::TYPE_POPUP;
child->Init(std::move(init_params));
return child;
}
} // namespace
// Tests creating a views::Widget parented off a native NSWindow.
TEST_F(NativeWidgetMacTest, NonWidgetParent) {
NSWindow* native_parent = MakeBorderlessNativeParent();
Widget::Widgets children;
Widget::GetAllChildWidgets([native_parent contentView], &children);
EXPECT_EQ(1u, children.size());
Widget* child = AttachPopupToNativeParent(native_parent);
EXPECT_FALSE(child->is_top_level());
TestWidgetObserver child_observer(child);
// GetTopLevelNativeWidget() will go up through |native_parent|'s Widget.
internal::NativeWidgetPrivate* top_level_widget =
internal::NativeWidgetPrivate::GetTopLevelNativeWidget(
child->GetNativeView());
EXPECT_EQ(Widget::GetWidgetForNativeWindow(native_parent),
top_level_widget->GetWidget());
EXPECT_NE(child, top_level_widget->GetWidget());
// To verify the parent, we need to use NativeWidgetMac APIs.
NativeWidgetMacNSWindowHost* bridged_native_widget_host =
NativeWidgetMacNSWindowHost::GetFromNativeWindow(
child->GetNativeWindow());
EXPECT_EQ(bridged_native_widget_host->parent()
->native_widget_mac()
->GetNativeWindow(),
native_parent);
const gfx::Rect child_bounds(50, 50, 200, 100);
child->SetBounds(child_bounds);
EXPECT_FALSE(child->IsVisible());
EXPECT_EQ(0u, [[native_parent childWindows] count]);
child->Show();
EXPECT_TRUE(child->IsVisible());
EXPECT_EQ(1u, [[native_parent childWindows] count]);
EXPECT_EQ(child->GetNativeWindow(), [native_parent childWindows][0]);
EXPECT_EQ(native_parent,
[child->GetNativeWindow().GetNativeNSWindow() parentWindow]);
Widget::GetAllChildWidgets([native_parent contentView], &children);
ASSERT_EQ(2u, children.size());
EXPECT_EQ(1u, children.count(child));
// Only non-toplevel Widgets are positioned relative to the parent, so the
// bounds set above should be in screen coordinates.
EXPECT_EQ(child_bounds, child->GetWindowBoundsInScreen());
// Removing the anchor view from its view hierarchy is permitted. This should
// not break the relationship between the two windows.
NSView* anchor_view = [[native_parent contentView] subviews][0];
EXPECT_TRUE(anchor_view);
[anchor_view removeFromSuperview];
EXPECT_EQ(bridged_native_widget_host->parent()
->native_widget_mac()
->GetNativeWindow(),
native_parent);
// Closing the parent should close and destroy the child.
EXPECT_FALSE(child_observer.widget_closed());
[native_parent close];
EXPECT_TRUE(child_observer.widget_closed());
EXPECT_EQ(0u, [[native_parent childWindows] count]);
[native_parent close];
}
// Tests that CloseAllSecondaryWidgets behaves in various configurations.
TEST_F(NativeWidgetMacTest, CloseAllSecondaryWidgetsValidState) {
NativeWidgetMacTestWindow* last_window = nil;
bool window_deallocated = false;
@autoreleasepool {
// First verify the behavior of CloseAllSecondaryWidgets in the normal case,
// and how [NSApp windows] changes in response to Widget closure.
Widget* widget = CreateWidgetWithTestWindow(
Widget::InitParams(Widget::InitParams::TYPE_WINDOW), &last_window);
last_window.deallocFlag = &window_deallocated;
TestWidgetObserver observer(widget);
EXPECT_TRUE([[NSApp windows] containsObject:last_window]);
Widget::CloseAllSecondaryWidgets();
EXPECT_TRUE(observer.widget_closed());
}
EXPECT_TRUE(window_deallocated);
window_deallocated = false;
@autoreleasepool {
// Repeat, but now retain a reference and close the window before
// CloseAllSecondaryWidgets().
Widget* widget = CreateWidgetWithTestWindow(
Widget::InitParams(Widget::InitParams::TYPE_WINDOW), &last_window);
last_window.deallocFlag = &window_deallocated;
TestWidgetObserver observer(widget);
[last_window retain];
widget->CloseNow();
EXPECT_TRUE(observer.widget_closed());
}
EXPECT_FALSE(window_deallocated);
@autoreleasepool {
Widget::CloseAllSecondaryWidgets();
[last_window release];
}
EXPECT_TRUE(window_deallocated);
// Repeat, with two Widgets. We can't control the order of window closure.
// If the parent is closed first, it should tear down the child while
// iterating over the windows. -[NSWindow close] will be sent to the child
// twice, but that should be fine.
Widget* parent = CreateTopLevelPlatformWidget();
Widget* child = CreateChildPlatformWidget(parent->GetNativeView());
parent->Show();
child->Show();
TestWidgetObserver parent_observer(parent);
TestWidgetObserver child_observer(child);
EXPECT_TRUE([[NSApp windows]
containsObject:parent->GetNativeWindow().GetNativeNSWindow()]);
EXPECT_TRUE([[NSApp windows]
containsObject:child->GetNativeWindow().GetNativeNSWindow()]);
Widget::CloseAllSecondaryWidgets();
EXPECT_TRUE(parent_observer.widget_closed());
EXPECT_TRUE(child_observer.widget_closed());
}
// Tests closing the last remaining NSWindow reference via -windowWillClose:.
// This is a regression test for http://crbug.com/616701.
TEST_F(NativeWidgetMacTest, NonWidgetParentLastReference) {
bool child_dealloced = false;
bool native_parent_dealloced = false;
NativeWidgetMacTestWindow* native_parent = nil;
@autoreleasepool {
native_parent = MakeBorderlessNativeParent();
[native_parent setDeallocFlag:&native_parent_dealloced];
NativeWidgetMacTestWindow* window;
Widget::InitParams init_params =
CreateParams(Widget::InitParams::TYPE_POPUP);
init_params.parent = [native_parent contentView];
init_params.bounds = gfx::Rect(0, 0, 100, 200);
CreateWidgetWithTestWindow(std::move(init_params), &window);
[window setDeallocFlag:&child_dealloced];
}
@autoreleasepool {
// On 10.11, closing a weak reference on the parent window works, but older
// versions of AppKit get upset if things are released inside -[NSWindow
// close]. This test tries to establish a situation where the last reference
// to the child window is released inside WidgetOwnerNSWindowAdapter::
// OnWindowWillClose().
[native_parent close];
}
// As of macOS 13 (Ventura), it seems that exiting the autoreleasepool
// block does not immediately trigger a release of its contents. Wait
// here for the deallocations to occur before proceeding.
while (!child_dealloced || !native_parent_dealloced) {
[NativeWidgetMacTestWindow waitForDealloc];
}
EXPECT_TRUE(child_dealloced);
EXPECT_TRUE(native_parent_dealloced);
}
// Tests visibility for a child of a native NSWindow, reshowing after a
// deminiaturize on the parent window (after attempting to show the child while
// the parent was miniaturized).
TEST_F(NativeWidgetMacTest, VisibleAfterNativeParentDeminiaturize) {
NSWindow* native_parent = MakeBorderlessNativeParent();
[native_parent makeKeyAndOrderFront:nil];
base::scoped_nsobject<WindowedNSNotificationObserver> miniaturizationObserver(
[[WindowedNSNotificationObserver alloc]
initForNotification:NSWindowDidMiniaturizeNotification
object:native_parent]);
[native_parent miniaturize:nil];
[miniaturizationObserver wait];
Widget* child = AttachPopupToNativeParent(native_parent);
child->Show();
EXPECT_FALSE([native_parent isVisible]);
EXPECT_FALSE(child->IsVisible()); // Parent is hidden so child is also.
base::scoped_nsobject<WindowedNSNotificationObserver>
deminiaturizationObserver([[WindowedNSNotificationObserver alloc]
initForNotification:NSWindowDidDeminiaturizeNotification
object:native_parent]);
[native_parent deminiaturize:nil];
[deminiaturizationObserver wait];
EXPECT_TRUE([native_parent isVisible]);
// Don't WaitForVisibleCounts() here: deminiaturize is synchronous, so any
// spurious _occlusion_ state change would have already occurred. Further
// occlusion changes are not guaranteed to be triggered by the deminiaturize.
EXPECT_TRUE(child->IsVisible());
[native_parent close];
}
// Use Native APIs to query the tooltip text that would be shown once the
// tooltip delay had elapsed.
std::u16string TooltipTextForWidget(Widget* widget) {
// For Mac, the actual location doesn't matter, since there is only one native
// view and it fills the window. This just assumes the window is at least big
// big enough for a constant coordinate to be within it.
NSPoint point = NSMakePoint(30, 30);
NSView* view = [widget->GetNativeView().GetNativeNSView() hitTest:point];
NSString* text =
[view view:view stringForToolTip:0 point:point userData:nullptr];
return base::SysNSStringToUTF16(text);
}
// Tests tooltips. The test doesn't wait for tooltips to appear. That is, the
// test assumes Cocoa calls stringForToolTip: at appropriate times and that,
// when a tooltip is already visible, changing it causes an update. These were
// tested manually by inserting a base::RunLoop.Run().
TEST_F(NativeWidgetMacTest, Tooltips) {
Widget* widget = CreateTopLevelPlatformWidget();
gfx::Rect screen_rect(50, 50, 100, 100);
widget->SetBounds(screen_rect);
const std::u16string tooltip_back = u"Back";
const std::u16string tooltip_front = u"Front";
const std::u16string long_tooltip(2000, 'W');
// Create a nested layout to test corner cases.
LabelButton* back = widget->non_client_view()->frame_view()->AddChildView(
std::make_unique<LabelButton>());
back->SetBounds(10, 10, 80, 80);
widget->Show();
ui::test::EventGenerator event_generator(GetContext(),
widget->GetNativeWindow());
// Initially, there should be no tooltip.
const gfx::Rect widget_bounds = widget->GetClientAreaBoundsInScreen();
event_generator.MoveMouseTo(widget_bounds.CenterPoint());
EXPECT_TRUE(TooltipTextForWidget(widget).empty());
// Create a new button for the "front", and set the tooltip, but don't add it
// to the view hierarchy yet.
auto front_managed = std::make_unique<LabelButton>();
front_managed->SetBounds(20, 20, 40, 40);
front_managed->SetTooltipText(tooltip_front);
// Changing the tooltip text shouldn't require an additional mousemove to take
// effect.
EXPECT_TRUE(TooltipTextForWidget(widget).empty());
back->SetTooltipText(tooltip_back);
EXPECT_EQ(tooltip_back, TooltipTextForWidget(widget));
// Adding a new view under the mouse should also take immediate effect.
LabelButton* front = back->AddChildView(std::move(front_managed));
EXPECT_EQ(tooltip_front, TooltipTextForWidget(widget));
// A long tooltip will be wrapped by Cocoa, but the full string should appear.
// Note that render widget hosts clip at 1024 to prevent DOS, but in toolkit-
// views the UI is more trusted.
front->SetTooltipText(long_tooltip);
EXPECT_EQ(long_tooltip, TooltipTextForWidget(widget));
// Move the mouse to a different view - tooltip should change.
event_generator.MoveMouseTo(back->GetBoundsInScreen().origin());
EXPECT_EQ(tooltip_back, TooltipTextForWidget(widget));
// Move the mouse off of any view, tooltip should clear.
event_generator.MoveMouseTo(widget_bounds.origin());
EXPECT_TRUE(TooltipTextForWidget(widget).empty());
widget->CloseNow();
}
// Tests case when mouse events are handled in one Widget,
// but tooltip belongs to another.
// It happens in menus when a submenu is shown and the parent gets the
// MouseExit event.
TEST_F(NativeWidgetMacTest, TwoWidgetTooltips) {
// Init two widgets, one above another.
Widget* widget_below = CreateTopLevelPlatformWidget();
widget_below->SetBounds(gfx::Rect(50, 50, 200, 200));
Widget* widget_above =
CreateChildPlatformWidget(widget_below->GetNativeView());
widget_above->SetBounds(gfx::Rect(100, 0, 100, 200));
const std::u16string tooltip_above = u"Front";
CustomTooltipView* view_above = widget_above->GetContentsView()->AddChildView(
std::make_unique<CustomTooltipView>(tooltip_above, nullptr));
view_above->SetBoundsRect(widget_above->GetContentsView()->bounds());
CustomTooltipView* view_below =
widget_below->non_client_view()->frame_view()->AddChildView(
std::make_unique<CustomTooltipView>(u"Back", view_above));
view_below->SetBoundsRect(widget_below->GetContentsView()->bounds());
widget_below->Show();
widget_above->Show();
// Move mouse above second widget and check that it returns tooltip
// for second. Despite that event was handled in the first one.
ui::test::EventGenerator event_generator(GetContext(),
widget_below->GetNativeWindow());
event_generator.MoveMouseTo(
widget_above->GetWindowBoundsInScreen().CenterPoint());
EXPECT_EQ(tooltip_above, TooltipTextForWidget(widget_below));
widget_above->CloseNow();
widget_below->CloseNow();
}
// Ensure captured mouse events correctly update dragging state in BaseView.
// Regression test for https://crbug.com/942452.
TEST_F(NativeWidgetMacTest, CapturedMouseUpClearsDrag) {
MouseTrackingWidget* widget = new MouseTrackingWidget;
Widget::InitParams init_params(Widget::InitParams::TYPE_WINDOW);
widget->Init(std::move(init_params));
NSWindow* window = widget->GetNativeWindow().GetNativeNSWindow();
BridgedContentView* native_view = [window contentView];
// Note: using native coordinates for consistency.
[window setFrame:NSMakeRect(50, 50, 100, 100) display:YES animate:NO];
NSEvent* enter_event = cocoa_test_event_utils::EnterEvent({50, 50}, window);
NSEvent* exit_event = cocoa_test_event_utils::ExitEvent({200, 200}, window);
widget->Show();
EXPECT_EQ(0, widget->GetMouseEventCount(ui::ET_MOUSE_ENTERED));
EXPECT_EQ(0, widget->GetMouseEventCount(ui::ET_MOUSE_EXITED));
[native_view mouseEntered:enter_event];
EXPECT_EQ(1, widget->GetMouseEventCount(ui::ET_MOUSE_ENTERED));
EXPECT_EQ(0, widget->GetMouseEventCount(ui::ET_MOUSE_EXITED));
[native_view mouseExited:exit_event];
EXPECT_EQ(1, widget->GetMouseEventCount(ui::ET_MOUSE_ENTERED));
EXPECT_EQ(1, widget->GetMouseEventCount(ui::ET_MOUSE_EXITED));
// Send a click. Note a click may initiate a drag, so the mouse-up is sent as
// a captured event.
std::pair<NSEvent*, NSEvent*> click =
cocoa_test_event_utils::MouseClickInView(native_view, 1);
[native_view mouseDown:click.first];
[native_view processCapturedMouseEvent:click.second];
// After a click, Enter/Exit should still work.
[native_view mouseEntered:enter_event];
EXPECT_EQ(2, widget->GetMouseEventCount(ui::ET_MOUSE_ENTERED));
EXPECT_EQ(1, widget->GetMouseEventCount(ui::ET_MOUSE_EXITED));
[native_view mouseExited:exit_event];
EXPECT_EQ(2, widget->GetMouseEventCount(ui::ET_MOUSE_ENTERED));
EXPECT_EQ(2, widget->GetMouseEventCount(ui::ET_MOUSE_EXITED));
widget->CloseNow();
}
namespace {
// TODO(ellyjones): Once DialogDelegate::CreateDialogWidget can accept a
// unique_ptr, return unique_ptr here.
DialogDelegateView* MakeModalDialog(ui::ModalType modal_type) {
auto dialog = std::make_unique<DialogDelegateView>();
dialog->SetModalType(modal_type);
return dialog.release();
}
// While in scope, waits for a call to a swizzled objective C method, then quits
// a nested run loop.
class ScopedSwizzleWaiter {
public:
explicit ScopedSwizzleWaiter(Class target)
: swizzler_(target,
[TestStopAnimationWaiter class],
@selector(setWindowStateForEnd)) {
DCHECK(!instance_);
instance_ = this;
}
ScopedSwizzleWaiter(const ScopedSwizzleWaiter&) = delete;
ScopedSwizzleWaiter& operator=(const ScopedSwizzleWaiter&) = delete;
~ScopedSwizzleWaiter() { instance_ = nullptr; }
static void OriginalSetWindowStateForEnd(id receiver, SEL method) {
return instance_->CallMethodInternal(receiver, method);
}
void WaitForMethod() {
if (method_called_)
return;
base::RunLoop run_loop;
base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE, run_loop.QuitClosure(), TestTimeouts::action_timeout());
run_loop_ = &run_loop;
run_loop.Run();
run_loop_ = nullptr;
}
bool method_called() const { return method_called_; }
private:
void CallMethodInternal(id receiver, SEL selector) {
DCHECK(!method_called_);
method_called_ = true;
if (run_loop_)
run_loop_->Quit();
swizzler_.InvokeOriginal<void>(receiver, selector);
}
static ScopedSwizzleWaiter* instance_;
base::mac::ScopedObjCClassSwizzler swizzler_;
raw_ptr<base::RunLoop> run_loop_ = nullptr;
bool method_called_ = false;
};
ScopedSwizzleWaiter* ScopedSwizzleWaiter::instance_ = nullptr;
// Shows a modal widget and waits for the show animation to complete. Waiting is
// not compulsory (calling Close() while animating the show will cancel the show
// animation). However, testing with overlapping swizzlers is tricky.
Widget* ShowChildModalWidgetAndWait(NSWindow* native_parent) {
Widget* modal_dialog_widget = views::DialogDelegate::CreateDialogWidget(
MakeModalDialog(ui::MODAL_TYPE_CHILD), nullptr,
[native_parent contentView]);
modal_dialog_widget->SetBounds(gfx::Rect(50, 50, 200, 150));
EXPECT_FALSE(modal_dialog_widget->IsVisible());
ScopedSwizzleWaiter show_waiter([ConstrainedWindowAnimationShow class]);
BridgedNativeWidgetTestApi test_api(
modal_dialog_widget->GetNativeWindow().GetNativeNSWindow());
EXPECT_FALSE(test_api.show_animation());
modal_dialog_widget->Show();
// Visible immediately (although it animates from transparent).
EXPECT_TRUE(modal_dialog_widget->IsVisible());
base::scoped_nsobject<NSAnimation> retained_animation(
test_api.show_animation(), base::scoped_policy::RETAIN);
EXPECT_TRUE(retained_animation);
EXPECT_TRUE([retained_animation isAnimating]);
// Run the animation.
show_waiter.WaitForMethod();
EXPECT_TRUE(modal_dialog_widget->IsVisible());
EXPECT_TRUE(show_waiter.method_called());
EXPECT_FALSE([retained_animation isAnimating]);
EXPECT_FALSE(test_api.show_animation());
return modal_dialog_widget;
}
// Shows a window-modal Widget (as a sheet). No need to wait since the native
// sheet animation is blocking.
Widget* ShowWindowModalWidget(NSWindow* native_parent) {
Widget* sheet_widget = views::DialogDelegate::CreateDialogWidget(
MakeModalDialog(ui::MODAL_TYPE_WINDOW), nullptr,
[native_parent contentView]);
sheet_widget->Show();
return sheet_widget;
}
} // namespace
// Tests object lifetime for the show/hide animations used for child-modal
// windows.
TEST_F(NativeWidgetMacTest, NativeWindowChildModalShowHide) {
NSWindow* native_parent = MakeBorderlessNativeParent();
{
Widget* modal_dialog_widget = ShowChildModalWidgetAndWait(native_parent);
TestWidgetObserver widget_observer(modal_dialog_widget);
ScopedSwizzleWaiter hide_waiter([ConstrainedWindowAnimationHide class]);
EXPECT_TRUE(modal_dialog_widget->IsVisible());
EXPECT_FALSE(widget_observer.widget_closed());
// Widget::Close() is always asynchronous, so we can check that the widget
// is initially visible, but then it's destroyed.
modal_dialog_widget->Close();
EXPECT_TRUE(modal_dialog_widget->IsVisible());
EXPECT_FALSE(hide_waiter.method_called());
EXPECT_FALSE(widget_observer.widget_closed());
// Wait for a hide to finish.
hide_waiter.WaitForMethod();
EXPECT_TRUE(hide_waiter.method_called());
// The animation finishing should also mean it has closed the window.
EXPECT_TRUE(widget_observer.widget_closed());
}
{
// Make a new dialog to test another lifetime flow.
Widget* modal_dialog_widget = ShowChildModalWidgetAndWait(native_parent);
TestWidgetObserver widget_observer(modal_dialog_widget);
// Start an asynchronous close as above.
ScopedSwizzleWaiter hide_waiter([ConstrainedWindowAnimationHide class]);
modal_dialog_widget->Close();
EXPECT_FALSE(widget_observer.widget_closed());
EXPECT_FALSE(hide_waiter.method_called());
// Now close the _parent_ window to force a synchronous close of the child.
[native_parent close];
// Widget is destroyed immediately. No longer paints, but the animation is
// still running.
EXPECT_TRUE(widget_observer.widget_closed());
EXPECT_FALSE(hide_waiter.method_called());
// Wait for the hide again. It will call close on its retained copy of the
// child NSWindow, but that's fine since all the C++ objects are detached.
hide_waiter.WaitForMethod();
EXPECT_TRUE(hide_waiter.method_called());
}
}
// Tests that the first call into SetVisibilityState() restores the window state
// for windows that start off miniaturized in the dock.
TEST_F(NativeWidgetMacTest, ConfirmMinimizedWindowRestoration) {
Widget* widget = new Widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.native_widget =
CreatePlatformNativeWidgetImpl(widget, kStubCapture, nullptr);
// Start the window off in the dock.
params.show_state = ui::SHOW_STATE_MINIMIZED;
params.workspace = kDummyWindowRestorationData;
widget->Init(std::move(params));
BridgedNativeWidgetTestApi test_api(
widget->GetNativeWindow().GetNativeNSWindow());
EXPECT_TRUE(test_api.HasWindowRestorationData());
// Show() ultimately invokes SetVisibilityState().
widget->Show();
EXPECT_FALSE(test_api.HasWindowRestorationData());
widget->CloseNow();
}
// Tests that the first call into SetVisibilityState() restores the window state
// for windows that start off visible.
TEST_F(NativeWidgetMacTest, ConfirmVisibleWindowRestoration) {
Widget* widget = new Widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.native_widget =
CreatePlatformNativeWidgetImpl(widget, kStubCapture, nullptr);
params.show_state = ui::SHOW_STATE_NORMAL;
params.workspace = kDummyWindowRestorationData;
widget->Init(std::move(params));
BridgedNativeWidgetTestApi test_api(
widget->GetNativeWindow().GetNativeNSWindow());
EXPECT_TRUE(test_api.HasWindowRestorationData());
// Show() ultimately invokes SetVisibilityState().
widget->Show();
EXPECT_FALSE(test_api.HasWindowRestorationData());
widget->CloseNow();
}
// Tests that calls to Hide() a Widget cancel any in-progress show animation,
// and that clients can control the triggering of the animation.
TEST_F(NativeWidgetMacTest, ShowAnimationControl) {
NSWindow* native_parent = MakeBorderlessNativeParent();
Widget* modal_dialog_widget = views::DialogDelegate::CreateDialogWidget(
MakeModalDialog(ui::MODAL_TYPE_CHILD), nullptr,
[native_parent contentView]);
modal_dialog_widget->SetBounds(gfx::Rect(50, 50, 200, 150));
EXPECT_FALSE(modal_dialog_widget->IsVisible());
BridgedNativeWidgetTestApi test_api(
modal_dialog_widget->GetNativeWindow().GetNativeNSWindow());
EXPECT_FALSE(test_api.show_animation());
modal_dialog_widget->Show();
EXPECT_TRUE(modal_dialog_widget->IsVisible());
base::scoped_nsobject<NSAnimation> retained_animation(
test_api.show_animation(), base::scoped_policy::RETAIN);
EXPECT_TRUE(retained_animation);
EXPECT_TRUE([retained_animation isAnimating]);
// Hide without waiting for the animation to complete. Animation should cancel
// and clear references from NativeWidgetNSWindowBridge.
modal_dialog_widget->Hide();
EXPECT_FALSE([retained_animation isAnimating]);
EXPECT_FALSE(test_api.show_animation());
retained_animation.reset();
// Disable animations and show again.
modal_dialog_widget->SetVisibilityAnimationTransition(Widget::ANIMATE_NONE);
modal_dialog_widget->Show();
EXPECT_FALSE(test_api.show_animation()); // No animation this time.
modal_dialog_widget->Hide();
// Test after re-enabling.
modal_dialog_widget->SetVisibilityAnimationTransition(Widget::ANIMATE_BOTH);
modal_dialog_widget->Show();
EXPECT_TRUE(test_api.show_animation());
retained_animation.reset(test_api.show_animation(),
base::scoped_policy::RETAIN);
// Test whether disabling native animations also disables custom modal ones.
modal_dialog_widget->SetVisibilityChangedAnimationsEnabled(false);
modal_dialog_widget->Show();
EXPECT_FALSE(test_api.show_animation()); // No animation this time.
modal_dialog_widget->Hide();
// Renable.
modal_dialog_widget->SetVisibilityChangedAnimationsEnabled(true);
modal_dialog_widget->Show();
EXPECT_TRUE(test_api.show_animation());
retained_animation.reset(test_api.show_animation(),
base::scoped_policy::RETAIN);
// Closing should also cancel the animation.
EXPECT_TRUE([retained_animation isAnimating]);
[native_parent close];
EXPECT_FALSE([retained_animation isAnimating]);
}
// Tests behavior of window-modal dialogs, displayed as sheets.
#if defined(ARCH_CPU_ARM64)
// Bulk-disabled as part of arm64 bot stabilization: https://crbug.com/1154345
#define MAYBE_WindowModalSheet DISABLED_WindowModalSheet
#else
#define MAYBE_WindowModalSheet WindowModalSheet
#endif
TEST_F(NativeWidgetMacTest, MAYBE_WindowModalSheet) {
NSWindow* native_parent = MakeClosableTitledNativeParent();
Widget* sheet_widget = views::DialogDelegate::CreateDialogWidget(
MakeModalDialog(ui::MODAL_TYPE_WINDOW), nullptr,
[native_parent contentView]);
WidgetChangeObserver widget_observer(sheet_widget);
// Retain, to run checks after the Widget is torn down.
base::scoped_nsobject<NSWindow> sheet_window(
[sheet_widget->GetNativeWindow().GetNativeNSWindow() retain]);
// Although there is no titlebar displayed, sheets need
// NSWindowStyleMaskTitled in order to properly engage window-modal behavior
// in AppKit.
EXPECT_TRUE(NSWindowStyleMaskTitled & [sheet_window styleMask]);
// But to properly size, sheets also need
// NSWindowStyleMaskFullSizeContentView.
EXPECT_TRUE(NSWindowStyleMaskFullSizeContentView & [sheet_window styleMask]);
sheet_widget->SetBounds(gfx::Rect(50, 50, 200, 150));
EXPECT_FALSE(sheet_widget->IsVisible());
EXPECT_FALSE(sheet_widget->GetLayer()->IsVisible());
NSButton* parent_close_button =
[native_parent standardWindowButton:NSWindowCloseButton];
EXPECT_TRUE(parent_close_button);
EXPECT_TRUE([parent_close_button isEnabled]);
bool did_observe = false;
bool* did_observe_ptr = &did_observe;
id observer = [[NSNotificationCenter defaultCenter]
addObserverForName:NSWindowWillBeginSheetNotification
object:native_parent
queue:nil
usingBlock:^(NSNotification* note) {
// Ensure that before the sheet runs, the window contents would
// be drawn.
EXPECT_TRUE(sheet_widget->IsVisible());
EXPECT_TRUE(sheet_widget->GetLayer()->IsVisible());
*did_observe_ptr = true;
}];
Widget::Widgets children;
Widget::GetAllChildWidgets([native_parent contentView], &children);
ASSERT_EQ(2u, children.size());
sheet_widget->Show(); // Should run the above block, then animate the sheet.
EXPECT_TRUE(did_observe);
[[NSNotificationCenter defaultCenter] removeObserver:observer];
// Ensure sheets are included as a child.
Widget::GetAllChildWidgets([native_parent contentView], &children);
ASSERT_EQ(2u, children.size());
EXPECT_TRUE(children.count(sheet_widget));
ASSERT_EQ(0U, native_parent.childWindows.count);
// Modal, so the close button in the parent window should get disabled.
EXPECT_FALSE([parent_close_button isEnabled]);
// The sheet should be hidden and shown in step with the parent.
widget_observer.WaitForVisibleCounts(1, 0);
EXPECT_TRUE(sheet_widget->IsVisible());
// TODO(tapted): Ideally [native_parent orderOut:nil] would also work here.
// But it does not. AppKit's childWindow management breaks down after an
// -orderOut: (see NativeWidgetNSWindowBridge::OnVisibilityChanged()). For
// regular child windows, NativeWidgetNSWindowBridge fixes the behavior with
// its own management. However, it can't do that for sheets without
// encountering http://crbug.com/605098 and http://crbug.com/667602. -[NSApp
// hide:] makes the NSWindow hidden in a different way, which does not break
// like -orderOut: does. Which is good, because a user can always do -[NSApp
// hide:], e.g., with Cmd+h, and that needs to work correctly.
[NSApp hide:nil];
widget_observer.WaitForVisibleCounts(1, 1);
EXPECT_FALSE(sheet_widget->IsVisible());
[native_parent makeKeyAndOrderFront:nil];
ASSERT_EQ(0u, native_parent.childWindows.count);
widget_observer.WaitForVisibleCounts(2, 1);
EXPECT_TRUE(sheet_widget->IsVisible());
// Trigger the close. Don't use CloseNow, since that tears down the UI before
// the close sheet animation gets a chance to run (so it's banned).
sheet_widget->Close();
EXPECT_TRUE(sheet_widget->IsVisible());
// Pump in order to trigger -[NSWindow endSheet:..], which will block while
// the animation runs, then delete |sheet_widget|.
EXPECT_TRUE([sheet_window delegate]);
base::RunLoop().RunUntilIdle();
EXPECT_FALSE([sheet_window delegate]);
[[NSNotificationCenter defaultCenter] removeObserver:observer];
EXPECT_TRUE(widget_observer.widget_closed());
EXPECT_TRUE([parent_close_button isEnabled]);
[native_parent close];
}
// Tests behavior when closing a window that is a sheet, or that hosts a sheet,
// and reshowing a sheet on a window after the sheet was closed with -[NSWindow
// close].
TEST_F(NativeWidgetMacTest, CloseWithWindowModalSheet) {
NSWindow* native_parent = MakeClosableTitledNativeParent();
{
Widget* sheet_widget = ShowWindowModalWidget(native_parent);
EXPECT_TRUE(
[sheet_widget->GetNativeWindow().GetNativeNSWindow() isVisible]);
WidgetChangeObserver widget_observer(sheet_widget);
// Test synchronous close (asynchronous close is tested above).
sheet_widget->CloseNow();
EXPECT_TRUE(widget_observer.widget_closed());
// Spin the RunLoop to ensure the task that ends the modal session on
// |native_parent| is executed. Otherwise |native_parent| will refuse to
// show another sheet.
base::RunLoop().RunUntilIdle();
}
{
Widget* sheet_widget = ShowWindowModalWidget(native_parent);
// Ensure the sheet wasn't blocked by a previous modal session.
EXPECT_TRUE(
[sheet_widget->GetNativeWindow().GetNativeNSWindow() isVisible]);
WidgetChangeObserver widget_observer(sheet_widget);
// Test native -[NSWindow close] on the sheet. Does not animate.
[sheet_widget->GetNativeWindow().GetNativeNSWindow() close];
EXPECT_TRUE(widget_observer.widget_closed());
base::RunLoop().RunUntilIdle();
}
// Similar, but invoke -[NSWindow close] immediately after an asynchronous
// Close(). This exercises a scenario where two tasks to end the sheet may be
// posted. Experimentally (on 10.13) both tasks run, but the second will never
// attempt to invoke -didEndSheet: on the |modalDelegate| arg of -beginSheet:.
// (If it did, it would be fine.)
{
Widget* sheet_widget = ShowWindowModalWidget(native_parent);
base::scoped_nsobject<NSWindow> sheet_window(
sheet_widget->GetNativeWindow().GetNativeNSWindow(),
base::scoped_policy::RETAIN);
EXPECT_TRUE([sheet_window isVisible]);
WidgetChangeObserver widget_observer(sheet_widget);
sheet_widget->Close(); // Asynchronous. Can't be called after -close.
EXPECT_FALSE(widget_observer.widget_closed());
[sheet_window close];
EXPECT_TRUE(widget_observer.widget_closed());
base::RunLoop().RunUntilIdle();
// Pretend both tasks ran fully. Note that |sheet_window| serves as its own
// |modalDelegate|.
[base::mac::ObjCCastStrict<NativeWidgetMacNSWindow>(sheet_window)
sheetDidEnd:sheet_window
returnCode:NSModalResponseStop
contextInfo:nullptr];
}
// Test another hypothetical: What if -sheetDidEnd: was invoked somehow
// without going through [NSApp endSheet:] or -[NSWindow endSheet:].
@autoreleasepool {
Widget* sheet_widget = ShowWindowModalWidget(native_parent);
NSWindow* sheet_window =
sheet_widget->GetNativeWindow().GetNativeNSWindow();
EXPECT_TRUE([sheet_window isVisible]);
WidgetChangeObserver widget_observer(sheet_widget);
sheet_widget->Close();
[base::mac::ObjCCastStrict<NativeWidgetMacNSWindow>(sheet_window)
sheetDidEnd:sheet_window
returnCode:NSModalResponseStop
contextInfo:nullptr];
EXPECT_TRUE(widget_observer.widget_closed());
// Here, the ViewsNSWindowDelegate should be dealloc'd.
}
base::RunLoop().RunUntilIdle(); // Run the task posted in Close().
// Test -[NSWindow close] on the parent window.
{
Widget* sheet_widget = ShowWindowModalWidget(native_parent);
EXPECT_TRUE(
[sheet_widget->GetNativeWindow().GetNativeNSWindow() isVisible]);
WidgetChangeObserver widget_observer(sheet_widget);
[native_parent close];
EXPECT_TRUE(widget_observer.widget_closed());
}
}
// Exercise a scenario where the task posted in the asynchronous Close() could
// eventually complete on a destroyed NSWindowDelegate. Regression test for
// https://crbug.com/851376.
TEST_F(NativeWidgetMacTest, CloseWindowModalSheetWithoutSheetParent) {
NSWindow* native_parent = MakeClosableTitledNativeParent();
@autoreleasepool {
Widget* sheet_widget = ShowWindowModalWidget(native_parent);
NSWindow* sheet_window =
sheet_widget->GetNativeWindow().GetNativeNSWindow();
EXPECT_TRUE([sheet_window isVisible]);
sheet_widget->Close(); // Asynchronous. Can't be called after -close.
// Now there's a task to end the sheet in the message queue. But destroying
// the NSWindowDelegate without _also_ posting a task that will _retain_ it
// is hard. It _is_ possible for a -performSelector:afterDelay: already in
// the queue to happen _after_ a PostTask posted now, but it's a very rare
// occurrence. So to simulate it, we pretend the sheet isn't actually a
// sheet by hiding its sheetParent. This avoids a task being posted that
// would retain the delegate, but also puts |native_parent| into a weird
// state.
//
// In fact, the "real" suspected trigger for this bug requires the PostTask
// to still be posted, then run to completion, and to dealloc the delegate
// it retains all before the -performSelector:afterDelay runs. That's the
// theory anyway.
//
// In reality, it didn't seem possible for -sheetDidEnd: to be invoked twice
// (AppKit would suppress it on subsequent calls to -[NSApp endSheet:] or
// -[NSWindow endSheet:]), so if the PostTask were to run to completion, the
// waiting -performSelector would always no- op. So this is actually testing
// a hypothetical where the sheetParent may be somehow nil during teardown
// (perhaps due to the parent window being further along in its teardown).
EXPECT_TRUE([sheet_window sheetParent]);
[sheet_window setValue:nil forKey:@"sheetParent"];
EXPECT_FALSE([sheet_window sheetParent]);
[sheet_window close];
// To repro the crash, we need a dealloc to occur here on |sheet_widget|'s
// NSWindowDelegate.
}
// Now there is still a task to end the sheet in the message queue, which
// should not crash.
base::RunLoop().RunUntilIdle();
[native_parent close];
}
// Test calls to Widget::ReparentNativeView() that result in a no-op on Mac.
TEST_F(NativeWidgetMacTest, NoopReparentNativeView) {
NSWindow* parent = MakeBorderlessNativeParent();
Widget* dialog = views::DialogDelegate::CreateDialogWidget(
new DialogDelegateView, nullptr, [parent contentView]);
NativeWidgetMacNSWindowHost* window_host =
NativeWidgetMacNSWindowHost::GetFromNativeWindow(
dialog->GetNativeWindow());
EXPECT_EQ(window_host->parent()->native_widget_mac()->GetNativeWindow(),
parent);
Widget::ReparentNativeView(dialog->GetNativeView(), [parent contentView]);
EXPECT_EQ(window_host->parent()->native_widget_mac()->GetNativeWindow(),
parent);
[parent close];
Widget* parent_widget = CreateTopLevelNativeWidget();
parent = parent_widget->GetNativeWindow().GetNativeNSWindow();
dialog = views::DialogDelegate::CreateDialogWidget(
new DialogDelegateView, nullptr, [parent contentView]);
window_host = NativeWidgetMacNSWindowHost::GetFromNativeWindow(
dialog->GetNativeWindow());
EXPECT_EQ(window_host->parent()->native_widget_mac()->GetNativeWindow(),
parent);
Widget::ReparentNativeView(dialog->GetNativeView(), [parent contentView]);
EXPECT_EQ(window_host->parent()->native_widget_mac()->GetNativeWindow(),
parent);
parent_widget->CloseNow();
}
// Attaches a child window to |parent| that checks its parent's delegate is
// cleared when the child is destroyed. This assumes the child is destroyed via
// destruction of its parent.
class ParentCloseMonitor : public WidgetObserver {
public:
explicit ParentCloseMonitor(Widget* parent) {
Widget* child = new Widget();
child->AddObserver(this);
Widget::InitParams init_params(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
init_params.parent = parent->GetNativeView();
init_params.bounds = gfx::Rect(100, 100, 100, 100);
init_params.native_widget =
CreatePlatformNativeWidgetImpl(child, kStubCapture, nullptr);
child->Init(std::move(init_params));
child->Show();
// NSWindow parent/child relationship should be established on Show() and
// the parent should have a delegate. Retain the parent since it can't be
// retrieved from the child while it is being destroyed.
parent_nswindow_.reset(
[[child->GetNativeWindow().GetNativeNSWindow() parentWindow] retain]);
EXPECT_TRUE(parent_nswindow_);
EXPECT_TRUE([parent_nswindow_ delegate]);
}
ParentCloseMonitor(const ParentCloseMonitor&) = delete;
ParentCloseMonitor& operator=(const ParentCloseMonitor&) = delete;
~ParentCloseMonitor() override {
EXPECT_TRUE(child_closed_); // Otherwise the observer wasn't removed.
}
void OnWidgetDestroying(Widget* child) override {
// Upon a parent-triggered close, the NSWindow relationship will still exist
// (it's removed just after OnWidgetDestroying() returns). The parent should
// still be open (children are always closed first), but not have a delegate
// (since it is being torn down).
EXPECT_TRUE([child->GetNativeWindow().GetNativeNSWindow() parentWindow]);
EXPECT_TRUE([parent_nswindow_ isVisible]);
EXPECT_FALSE([parent_nswindow_ delegate]);
EXPECT_FALSE(child_closed_);
}
void OnWidgetDestroyed(Widget* child) override {
EXPECT_FALSE([child->GetNativeWindow().GetNativeNSWindow() parentWindow]);
EXPECT_TRUE([parent_nswindow_ isVisible]);
EXPECT_FALSE([parent_nswindow_ delegate]);
EXPECT_FALSE(child_closed_);
child->RemoveObserver(this);
child_closed_ = true;
}
bool child_closed() const { return child_closed_; }
private:
base::scoped_nsobject<NSWindow> parent_nswindow_;
bool child_closed_ = false;
};
// Ensures when a parent window is destroyed, and triggers its child windows to
// be closed, that the child windows (via AppKit) do not attempt to call back
// into the parent, whilst it's in the process of being destroyed.
TEST_F(NativeWidgetMacTest, NoParentDelegateDuringTeardown) {
// First test "normal" windows and AppKit close.
{
Widget* parent = CreateTopLevelPlatformWidget();
parent->SetBounds(gfx::Rect(100, 100, 300, 200));
parent->Show();
ParentCloseMonitor monitor(parent);
[parent->GetNativeWindow().GetNativeNSWindow() close];
EXPECT_TRUE(monitor.child_closed());
}
// Test the Widget::CloseNow() flow.
{
Widget* parent = CreateTopLevelPlatformWidget();
parent->SetBounds(gfx::Rect(100, 100, 300, 200));
parent->Show();
ParentCloseMonitor monitor(parent);
parent->CloseNow();
EXPECT_TRUE(monitor.child_closed());
}
// Test the WIDGET_OWNS_NATIVE_WIDGET flow.
{
std::unique_ptr<Widget> parent(new Widget);
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.bounds = gfx::Rect(100, 100, 300, 200);
parent->Init(std::move(params));
parent->Show();
ParentCloseMonitor monitor(parent.get());
parent.reset();
EXPECT_TRUE(monitor.child_closed());
}
}
// Tests Cocoa properties that should be given to particular widget types.
TEST_F(NativeWidgetMacTest, NativeProperties) {
// Create a regular widget (TYPE_WINDOW).
Widget* regular_widget = CreateTopLevelNativeWidget();
EXPECT_TRUE([regular_widget->GetNativeWindow().GetNativeNSWindow()
canBecomeKeyWindow]);
EXPECT_TRUE([regular_widget->GetNativeWindow().GetNativeNSWindow()
canBecomeMainWindow]);
// Disabling activation should prevent key and main status.
regular_widget->widget_delegate()->SetCanActivate(false);
EXPECT_FALSE([regular_widget->GetNativeWindow().GetNativeNSWindow()
canBecomeKeyWindow]);
EXPECT_FALSE([regular_widget->GetNativeWindow().GetNativeNSWindow()
canBecomeMainWindow]);
// Create a dialog widget (also TYPE_WINDOW), but with a DialogDelegate.
Widget* dialog_widget = views::DialogDelegate::CreateDialogWidget(
MakeModalDialog(ui::MODAL_TYPE_CHILD), nullptr,
regular_widget->GetNativeView());
EXPECT_TRUE([dialog_widget->GetNativeWindow().GetNativeNSWindow()
canBecomeKeyWindow]);
// Dialogs shouldn't take main status away from their parent.
EXPECT_FALSE([dialog_widget->GetNativeWindow().GetNativeNSWindow()
canBecomeMainWindow]);
// Create a bubble widget (with a parent): also shouldn't get main.
BubbleDialogDelegateView* bubble_view = new SimpleBubbleView();
bubble_view->set_parent_window(regular_widget->GetNativeView());
Widget* bubble_widget = BubbleDialogDelegateView::CreateBubble(bubble_view);
EXPECT_TRUE([bubble_widget->GetNativeWindow().GetNativeNSWindow()
canBecomeKeyWindow]);
EXPECT_FALSE([bubble_widget->GetNativeWindow().GetNativeNSWindow()
canBecomeMainWindow]);
EXPECT_EQ(NSWindowCollectionBehaviorTransient,
[bubble_widget->GetNativeWindow().GetNativeNSWindow()
collectionBehavior] &
NSWindowCollectionBehaviorTransient);
regular_widget->CloseNow();
}
class CustomTitleWidgetDelegate : public WidgetDelegate {
public:
explicit CustomTitleWidgetDelegate(Widget* widget) : widget_(widget) {}
CustomTitleWidgetDelegate(const CustomTitleWidgetDelegate&) = delete;
CustomTitleWidgetDelegate& operator=(const CustomTitleWidgetDelegate&) =
delete;
void set_title(const std::u16string& title) { title_ = title; }
void set_should_show_title(bool show) { should_show_title_ = show; }
// WidgetDelegate:
std::u16string GetWindowTitle() const override { return title_; }
bool ShouldShowWindowTitle() const override { return should_show_title_; }
Widget* GetWidget() override { return widget_; }
const Widget* GetWidget() const override { return widget_; }
private:
raw_ptr<Widget> widget_;
std::u16string title_;
bool should_show_title_ = true;
};
// Test calls to invalidate the shadow when composited frames arrive.
TEST_F(NativeWidgetMacTest, InvalidateShadow) {
NativeWidgetMacTestWindow* window;
const gfx::Rect rect(0, 0, 100, 200);
Widget::InitParams init_params =
CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
init_params.bounds = rect;
Widget* widget = CreateWidgetWithTestWindow(std::move(init_params), &window);
// Simulate the initial paint.
BridgedNativeWidgetTestApi(window).SimulateFrameSwap(rect.size());
// Default is an opaque window, so shadow doesn't need to be invalidated.
EXPECT_EQ(0, [window invalidateShadowCount]);
widget->CloseNow();
init_params.opacity = Widget::InitParams::WindowOpacity::kTranslucent;
widget = CreateWidgetWithTestWindow(std::move(init_params), &window);
BridgedNativeWidgetTestApi test_api(window);
// First paint on a translucent window needs to invalidate the shadow. Once.
EXPECT_EQ(0, [window invalidateShadowCount]);
test_api.SimulateFrameSwap(rect.size());
EXPECT_EQ(1, [window invalidateShadowCount]);
test_api.SimulateFrameSwap(rect.size());
EXPECT_EQ(1, [window invalidateShadowCount]);
// Resizing the window also needs to trigger a shadow invalidation.
[window setContentSize:NSMakeSize(123, 456)];
// A "late" frame swap at the old size should do nothing.
test_api.SimulateFrameSwap(rect.size());
EXPECT_EQ(1, [window invalidateShadowCount]);
test_api.SimulateFrameSwap(gfx::Size(123, 456));
EXPECT_EQ(2, [window invalidateShadowCount]);
test_api.SimulateFrameSwap(gfx::Size(123, 456));
EXPECT_EQ(2, [window invalidateShadowCount]);
// Hiding the window does not require shadow invalidation.
widget->Hide();
test_api.SimulateFrameSwap(gfx::Size(123, 456));
EXPECT_EQ(2, [window invalidateShadowCount]);
// Showing a translucent window after hiding it, should trigger shadow
// invalidation.
widget->Show();
test_api.SimulateFrameSwap(gfx::Size(123, 456));
EXPECT_EQ(3, [window invalidateShadowCount]);
widget->CloseNow();
}
// Test that the contentView opacity corresponds to the window type.
TEST_F(NativeWidgetMacTest, ContentOpacity) {
NativeWidgetMacTestWindow* window;
Widget::InitParams init_params =
CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
EXPECT_EQ(init_params.opacity, Widget::InitParams::WindowOpacity::kInferred);
Widget* widget = CreateWidgetWithTestWindow(std::move(init_params), &window);
// Infer should default to opaque on Mac.
EXPECT_TRUE([[window contentView] isOpaque]);
widget->CloseNow();
init_params.opacity = Widget::InitParams::WindowOpacity::kTranslucent;
widget = CreateWidgetWithTestWindow(std::move(init_params), &window);
EXPECT_FALSE([[window contentView] isOpaque]);
widget->CloseNow();
// Test opaque explicitly.
init_params.opacity = Widget::InitParams::WindowOpacity::kOpaque;
widget = CreateWidgetWithTestWindow(std::move(init_params), &window);
EXPECT_TRUE([[window contentView] isOpaque]);
widget->CloseNow();
}
// Test the expected result of GetWorkAreaBoundsInScreen().
TEST_F(NativeWidgetMacTest, GetWorkAreaBoundsInScreen) {
Widget widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
// This is relative to the top-left of the primary screen, so unless the bot's
// display is smaller than 400x300, the window will be wholly contained there.
params.bounds = gfx::Rect(100, 100, 300, 200);
widget.Init(std::move(params));
widget.Show();
NSRect expected = [[[NSScreen screens] firstObject] visibleFrame];
NSRect actual = gfx::ScreenRectToNSRect(widget.GetWorkAreaBoundsInScreen());
EXPECT_FALSE(NSIsEmptyRect(actual));
EXPECT_NSEQ(expected, actual);
[widget.GetNativeWindow().GetNativeNSWindow() close];
actual = gfx::ScreenRectToNSRect(widget.GetWorkAreaBoundsInScreen());
EXPECT_TRUE(NSIsEmptyRect(actual));
}
// Test that Widget opacity can be changed.
TEST_F(NativeWidgetMacTest, ChangeOpacity) {
Widget* widget = CreateTopLevelPlatformWidget();
NSWindow* ns_window = widget->GetNativeWindow().GetNativeNSWindow();
CGFloat old_opacity = [ns_window alphaValue];
widget->SetOpacity(.7f);
EXPECT_NE(old_opacity, [ns_window alphaValue]);
EXPECT_DOUBLE_EQ(.7f, [ns_window alphaValue]);
widget->CloseNow();
}
// Ensure traversing NSView focus correctly updates the views::FocusManager.
TEST_F(NativeWidgetMacTest, ChangeFocusOnChangeFirstResponder) {
Widget* widget = CreateTopLevelPlatformWidget();
widget->GetRootView()->SetFocusBehavior(View::FocusBehavior::ALWAYS);
widget->Show();
base::scoped_nsobject<NSView> child_view([[FocusableTestNSView alloc]
initWithFrame:[widget->GetNativeView().GetNativeNSView() bounds]]);
[widget->GetNativeView().GetNativeNSView() addSubview:child_view];
EXPECT_TRUE([child_view acceptsFirstResponder]);
EXPECT_TRUE(widget->GetRootView()->IsFocusable());
FocusManager* manager = widget->GetFocusManager();
manager->SetFocusedView(widget->GetRootView());
EXPECT_EQ(manager->GetFocusedView(), widget->GetRootView());
[widget->GetNativeWindow().GetNativeNSWindow() makeFirstResponder:child_view];
EXPECT_FALSE(manager->GetFocusedView());
[widget->GetNativeWindow().GetNativeNSWindow()
makeFirstResponder:widget->GetNativeView().GetNativeNSView()];
EXPECT_EQ(manager->GetFocusedView(), widget->GetRootView());
widget->CloseNow();
}
// Test two kinds of widgets to re-parent.
TEST_F(NativeWidgetMacTest, ReparentNativeViewTypes) {
std::unique_ptr<Widget> toplevel1(new Widget);
Widget::InitParams toplevel_params =
CreateParams(Widget::InitParams::TYPE_POPUP);
toplevel_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
toplevel1->Init(std::move(toplevel_params));
toplevel1->Show();
std::unique_ptr<Widget> toplevel2(new Widget);
toplevel2->Init(std::move(toplevel_params));
toplevel2->Show();
Widget* child = new Widget;
Widget::InitParams child_params(Widget::InitParams::TYPE_CONTROL);
child->Init(std::move(child_params));
child->Show();
Widget::ReparentNativeView(child->GetNativeView(),
toplevel1->GetNativeView());
EXPECT_EQ([child->GetNativeWindow().GetNativeNSWindow() parentWindow],
[toplevel1->GetNativeView().GetNativeNSView() window]);
Widget::ReparentNativeView(child->GetNativeView(),
toplevel2->GetNativeView());
EXPECT_EQ([child->GetNativeWindow().GetNativeNSWindow() parentWindow],
[toplevel2->GetNativeView().GetNativeNSView() window]);
Widget::ReparentNativeView(toplevel2->GetNativeView(),
toplevel1->GetNativeView());
EXPECT_EQ([toplevel2->GetNativeWindow().GetNativeNSWindow() parentWindow],
[toplevel1->GetNativeView().GetNativeNSView() window]);
}
// Test class for Full Keyboard Access related tests.
class NativeWidgetMacFullKeyboardAccessTest : public NativeWidgetMacTest {
public:
NativeWidgetMacFullKeyboardAccessTest() = default;
protected:
// testing::Test:
void SetUp() override {
NativeWidgetMacTest::SetUp();
widget_ = CreateTopLevelPlatformWidget();
bridge_ = NativeWidgetMacNSWindowHost::GetFromNativeWindow(
widget_->GetNativeWindow())
->GetInProcessNSWindowBridge();
fake_full_keyboard_access_ =
ui::test::ScopedFakeFullKeyboardAccess::GetInstance();
DCHECK(fake_full_keyboard_access_);
widget_->Show();
}
void TearDown() override {
widget_->CloseNow();
NativeWidgetMacTest::TearDown();
}
raw_ptr<Widget> widget_ = nullptr;
raw_ptr<remote_cocoa::NativeWidgetNSWindowBridge> bridge_ = nullptr;
raw_ptr<ui::test::ScopedFakeFullKeyboardAccess> fake_full_keyboard_access_ =
nullptr;
};
// Ensure that calling SetSize doesn't change the origin.
TEST_F(NativeWidgetMacTest, SetSizeDoesntChangeOrigin) {
Widget* parent = CreateTopLevelFramelessPlatformWidget();
gfx::Rect parent_rect(100, 100, 400, 200);
parent->SetBounds(parent_rect);
// Popup children specify their bounds relative to their parent window.
Widget* child_control = new Widget;
gfx::Rect child_control_rect(50, 70, 300, 100);
{
Widget::InitParams params(Widget::InitParams::TYPE_CONTROL);
params.parent = parent->GetNativeView();
params.bounds = child_control_rect;
child_control->Init(std::move(params));
child_control->SetContentsView(new View);
}
// Window children specify their bounds in screen coords.
Widget* child_window = new Widget;
gfx::Rect child_window_rect(110, 90, 200, 50);
{
Widget::InitParams params(Widget::InitParams::TYPE_WINDOW);
params.parent = parent->GetNativeView();
params.bounds = child_window_rect;
child_window->Init(std::move(params));
}
// Sanity-check the initial bounds. Note that the CONTROL should be offset by
// the parent's origin.
EXPECT_EQ(parent->GetWindowBoundsInScreen(), parent_rect);
EXPECT_EQ(
child_control->GetWindowBoundsInScreen(),
gfx::Rect(child_control_rect.origin() + parent_rect.OffsetFromOrigin(),
child_control_rect.size()));
EXPECT_EQ(child_window->GetWindowBoundsInScreen(), child_window_rect);
// Update the size, but not the origin.
parent_rect.set_size(gfx::Size(505, 310));
parent->SetSize(parent_rect.size());
child_control_rect.set_size(gfx::Size(256, 102));
child_control->SetSize(child_control_rect.size());
child_window_rect.set_size(gfx::Size(172, 96));
child_window->SetSize(child_window_rect.size());
// Ensure that the origin didn't change.
EXPECT_EQ(parent->GetWindowBoundsInScreen(), parent_rect);
EXPECT_EQ(
child_control->GetWindowBoundsInScreen(),
gfx::Rect(child_control_rect.origin() + parent_rect.OffsetFromOrigin(),
child_control_rect.size()));
EXPECT_EQ(child_window->GetWindowBoundsInScreen(), child_window_rect);
parent->CloseNow();
}
// Tests that tooltip widgets get the correct accessibilty role so that they're
// not announced as windows by VoiceOver.
TEST_F(NativeWidgetMacTest, AccessibilityRole) {
{
NativeWidgetMacTestWindow* window;
Widget::InitParams init_params =
CreateParams(Widget::InitParams::TYPE_WINDOW);
Widget* widget =
CreateWidgetWithTestWindow(std::move(init_params), &window);
ASSERT_EQ([window accessibilityRole], NSAccessibilityWindowRole);
widget->CloseNow();
}
{
NativeWidgetMacTestWindow* window;
Widget::InitParams init_params =
CreateParams(Widget::InitParams::TYPE_TOOLTIP);
Widget* widget =
CreateWidgetWithTestWindow(std::move(init_params), &window);
ASSERT_EQ([window accessibilityRole], NSAccessibilityHelpTagRole);
widget->CloseNow();
}
}
// Test that updateFullKeyboardAccess method on BridgedContentView correctly
// sets the keyboard accessibility mode on the associated focus manager.
TEST_F(NativeWidgetMacFullKeyboardAccessTest, FullKeyboardToggle) {
EXPECT_TRUE(widget_->GetFocusManager()->keyboard_accessible());
fake_full_keyboard_access_->set_full_keyboard_access_state(false);
[bridge_->ns_view() updateFullKeyboardAccess];
EXPECT_FALSE(widget_->GetFocusManager()->keyboard_accessible());
fake_full_keyboard_access_->set_full_keyboard_access_state(true);
[bridge_->ns_view() updateFullKeyboardAccess];
EXPECT_TRUE(widget_->GetFocusManager()->keyboard_accessible());
}
// Test that a Widget's associated FocusManager is initialized with the correct
// keyboard accessibility value.
TEST_F(NativeWidgetMacFullKeyboardAccessTest, Initialization) {
EXPECT_TRUE(widget_->GetFocusManager()->keyboard_accessible());
fake_full_keyboard_access_->set_full_keyboard_access_state(false);
Widget* widget2 = CreateTopLevelPlatformWidget();
EXPECT_FALSE(widget2->GetFocusManager()->keyboard_accessible());
widget2->CloseNow();
}
// Test that the correct keyboard accessibility mode is set when the window
// becomes active.
TEST_F(NativeWidgetMacFullKeyboardAccessTest, Activation) {
EXPECT_TRUE(widget_->GetFocusManager()->keyboard_accessible());
widget_->Hide();
fake_full_keyboard_access_->set_full_keyboard_access_state(false);
// [bridge_->ns_view() updateFullKeyboardAccess] is not explicitly called
// since we may not receive full keyboard access toggle notifications when our
// application is inactive.
widget_->Show();
EXPECT_FALSE(widget_->GetFocusManager()->keyboard_accessible());
widget_->Hide();
fake_full_keyboard_access_->set_full_keyboard_access_state(true);
widget_->Show();
EXPECT_TRUE(widget_->GetFocusManager()->keyboard_accessible());
}
class NativeWidgetMacViewsOrderTest : public WidgetTest {
public:
NativeWidgetMacViewsOrderTest() = default;
NativeWidgetMacViewsOrderTest(const NativeWidgetMacViewsOrderTest&) = delete;
NativeWidgetMacViewsOrderTest& operator=(
const NativeWidgetMacViewsOrderTest&) = delete;
protected:
class NativeHostHolder {
public:
static std::unique_ptr<NativeHostHolder> CreateAndAddToParent(
View* parent) {
std::unique_ptr<NativeHostHolder> holder(new NativeHostHolder(
parent->AddChildView(std::make_unique<NativeViewHost>())));
holder->host()->Attach(holder->view());
return holder;
}
NativeHostHolder(const NativeHostHolder&) = delete;
NativeHostHolder& operator=(const NativeHostHolder&) = delete;
NSView* view() const { return view_.get(); }
NativeViewHost* host() const { return host_; }
private:
explicit NativeHostHolder(NativeViewHost* host)
: host_(host), view_([[NSView alloc] init]) {}
const raw_ptr<NativeViewHost> host_;
base::scoped_nsobject<NSView> view_;
};
// testing::Test:
void SetUp() override {
WidgetTest::SetUp();
widget_ = CreateTopLevelPlatformWidget();
starting_subviews_.reset(
[[widget_->GetNativeView().GetNativeNSView() subviews] copy]);
native_host_parent_ = new View();
widget_->GetContentsView()->AddChildView(native_host_parent_.get());
const size_t kNativeViewCount = 3;
for (size_t i = 0; i < kNativeViewCount; ++i) {
hosts_.push_back(
NativeHostHolder::CreateAndAddToParent(native_host_parent_));
}
EXPECT_EQ(kNativeViewCount, native_host_parent_->children().size());
EXPECT_NSEQ([widget_->GetNativeView().GetNativeNSView() subviews],
([GetStartingSubviews() arrayByAddingObjectsFromArray:@[
hosts_[0]->view(), hosts_[1]->view(), hosts_[2]->view()
]]));
}
void TearDown() override {
widget_->CloseNow();
hosts_.clear();
WidgetTest::TearDown();
}
NSView* GetContentNativeView() {
return widget_->GetNativeView().GetNativeNSView();
}
NSArray<NSView*>* GetStartingSubviews() { return starting_subviews_; }
raw_ptr<Widget> widget_ = nullptr;
raw_ptr<View> native_host_parent_ = nullptr;
std::vector<std::unique_ptr<NativeHostHolder>> hosts_;
base::scoped_nsobject<NSArray<NSView*>> starting_subviews_;
};
// Test that NativeViewHost::Attach()/Detach() method saves the NativeView
// z-order.
TEST_F(NativeWidgetMacViewsOrderTest, NativeViewAttached) {
NativeHostHolder* second_host = hosts_[1].get();
second_host->host()->Detach();
EXPECT_NSEQ([GetContentNativeView() subviews],
([GetStartingSubviews() arrayByAddingObjectsFromArray:@[
hosts_[0]->view(), hosts_[2]->view()
]]));
second_host->host()->Attach(second_host->view());
EXPECT_NSEQ([GetContentNativeView() subviews],
([GetStartingSubviews() arrayByAddingObjectsFromArray:@[
hosts_[0]->view(), hosts_[1]->view(), hosts_[2]->view()
]]));
}
// Tests that NativeViews order changes according to views::View hierarchy.
TEST_F(NativeWidgetMacViewsOrderTest, ReorderViews) {
native_host_parent_->ReorderChildView(hosts_[2]->host(), 1);
EXPECT_NSEQ([GetContentNativeView() subviews],
([GetStartingSubviews() arrayByAddingObjectsFromArray:@[
hosts_[0]->view(), hosts_[2]->view(), hosts_[1]->view()
]]));
native_host_parent_->RemoveChildView(hosts_[2]->host());
EXPECT_NSEQ([GetContentNativeView() subviews],
([GetStartingSubviews() arrayByAddingObjectsFromArray:@[
hosts_[0]->view(), hosts_[1]->view()
]]));
View* new_parent = new View();
native_host_parent_->RemoveChildView(hosts_[1]->host());
native_host_parent_->AddChildView(new_parent);
new_parent->AddChildView(hosts_[1]->host());
new_parent->AddChildView(hosts_[2]->host());
EXPECT_NSEQ([GetContentNativeView() subviews],
([GetStartingSubviews() arrayByAddingObjectsFromArray:@[
hosts_[0]->view(), hosts_[1]->view(), hosts_[2]->view()
]]));
native_host_parent_->ReorderChildView(new_parent, 0);
EXPECT_NSEQ([GetContentNativeView() subviews],
([GetStartingSubviews() arrayByAddingObjectsFromArray:@[
hosts_[1]->view(), hosts_[2]->view(), hosts_[0]->view()
]]));
}
// Test that unassociated native views stay on top after reordering.
TEST_F(NativeWidgetMacViewsOrderTest, UnassociatedViewsIsAbove) {
base::scoped_nsobject<NSView> child_view([[NSView alloc] init]);
[GetContentNativeView() addSubview:child_view];
EXPECT_NSEQ(
[GetContentNativeView() subviews],
([GetStartingSubviews() arrayByAddingObjectsFromArray:@[
hosts_[0]->view(), hosts_[1]->view(), hosts_[2]->view(), child_view
]]));
native_host_parent_->ReorderChildView(hosts_[2]->host(), 1);
EXPECT_NSEQ(
[GetContentNativeView() subviews],
([GetStartingSubviews() arrayByAddingObjectsFromArray:@[
hosts_[0]->view(), hosts_[2]->view(), hosts_[1]->view(), child_view
]]));
}
namespace {
// Returns an array of NSTouchBarItemIdentifier (i.e. NSString), extracted from
// the principal of |view|'s touch bar, which must be a NSGroupTouchBarItem.
// Also verifies that the touch bar's delegate returns non-nil for all items.
NSArray* ExtractTouchBarGroupIdentifiers(NSView* view) {
NSArray* result = nil;
NSTouchBar* touch_bar = [view touchBar];
NSTouchBarItemIdentifier principal = [touch_bar principalItemIdentifier];
EXPECT_TRUE(principal);
NSGroupTouchBarItem* group = base::mac::ObjCCastStrict<NSGroupTouchBarItem>(
[[touch_bar delegate] touchBar:touch_bar
makeItemForIdentifier:principal]);
EXPECT_TRUE(group);
NSTouchBar* nested_touch_bar = [group groupTouchBar];
result = [nested_touch_bar itemIdentifiers];
for (NSTouchBarItemIdentifier item in result) {
EXPECT_TRUE([[touch_bar delegate] touchBar:nested_touch_bar
makeItemForIdentifier:item]);
}
return result;
}
} // namespace
// Test TouchBar integration.
TEST_F(NativeWidgetMacTest, TouchBar) {
DialogDelegate* delegate = MakeModalDialog(ui::MODAL_TYPE_NONE);
views::DialogDelegate::CreateDialogWidget(delegate, nullptr, nullptr);
NSView* content =
[delegate->GetWidget()->GetNativeWindow().GetNativeNSWindow()
contentView];
// Constants from bridged_content_view_touch_bar.mm.
NSString* const kTouchBarOKId = @"com.google.chrome-OK";
NSString* const kTouchBarCancelId = @"com.google.chrome-CANCEL";
EXPECT_TRUE(content);
EXPECT_TRUE(delegate->GetOkButton());
EXPECT_TRUE(delegate->GetCancelButton());
NSTouchBar* touch_bar = [content touchBar];
EXPECT_TRUE([touch_bar delegate]);
EXPECT_TRUE([[touch_bar delegate] touchBar:touch_bar
makeItemForIdentifier:kTouchBarOKId]);
EXPECT_TRUE([[touch_bar delegate] touchBar:touch_bar
makeItemForIdentifier:kTouchBarCancelId]);
NSString* principal = [touch_bar principalItemIdentifier];
EXPECT_NSEQ(@"com.google.chrome-DIALOG-BUTTONS-GROUP", principal);
EXPECT_NSEQ((@[ kTouchBarCancelId, kTouchBarOKId ]),
ExtractTouchBarGroupIdentifiers(content));
// Ensure the touchBar is recreated by comparing pointers.
// Remove the cancel button.
delegate->SetButtons(ui::DIALOG_BUTTON_OK);
delegate->DialogModelChanged();
EXPECT_TRUE(delegate->GetOkButton());
EXPECT_FALSE(delegate->GetCancelButton());
NSTouchBar* new_touch_bar = [content touchBar];
EXPECT_NSNE(touch_bar, new_touch_bar);
EXPECT_NSEQ((@[ kTouchBarOKId ]), ExtractTouchBarGroupIdentifiers(content));
delegate->GetWidget()->CloseNow();
}
TEST_F(NativeWidgetMacTest, InitCallback) {
NativeWidget* observed_native_widget = nullptr;
const auto callback = base::BindRepeating(
[](NativeWidget** observed, NativeWidgetMac* native_widget) {
*observed = native_widget;
},
&observed_native_widget);
NativeWidgetMac::SetInitNativeWidgetCallback(callback);
Widget* widget_a = CreateTopLevelPlatformWidget();
EXPECT_EQ(observed_native_widget, widget_a->native_widget());
Widget* widget_b = CreateTopLevelPlatformWidget();
EXPECT_EQ(observed_native_widget, widget_b->native_widget());
auto empty = base::RepeatingCallback<void(NativeWidgetMac*)>();
DCHECK(empty.is_null());
NativeWidgetMac::SetInitNativeWidgetCallback(empty);
observed_native_widget = nullptr;
Widget* widget_c = CreateTopLevelPlatformWidget();
// The original callback from above should no longer be firing.
EXPECT_EQ(observed_native_widget, nullptr);
widget_a->CloseNow();
widget_b->CloseNow();
widget_c->CloseNow();
}
TEST_F(NativeWidgetMacTest, FocusManagerChangeOnReparentNativeView) {
WidgetAutoclosePtr toplevel(CreateTopLevelPlatformWidget());
Widget* child = CreateChildPlatformWidget(toplevel->GetNativeView());
WidgetAutoclosePtr target_toplevel(CreateTopLevelPlatformWidget());
EXPECT_EQ(child->GetFocusManager(), toplevel->GetFocusManager());
EXPECT_NE(child->GetFocusManager(), target_toplevel->GetFocusManager());
NativeWidgetMac* child_native_widget =
static_cast<NativeWidgetMac*>(child->native_widget());
EXPECT_EQ(GetFocusManager(child_native_widget), child->GetFocusManager());
Widget::ReparentNativeView(child->GetNativeView(),
target_toplevel->GetNativeView());
EXPECT_EQ(child->GetFocusManager(), target_toplevel->GetFocusManager());
EXPECT_NE(child->GetFocusManager(), toplevel->GetFocusManager());
EXPECT_EQ(GetFocusManager(child_native_widget), child->GetFocusManager());
}
} // namespace views::test
@implementation TestStopAnimationWaiter
- (void)setWindowStateForEnd {
views::test::ScopedSwizzleWaiter::OriginalSetWindowStateForEnd(self, _cmd);
}
@end
@implementation NativeWidgetMacTestWindow
@synthesize invalidateShadowCount = _invalidateShadowCount;
@synthesize fakeOnInactiveSpace = _fakeOnInactiveSpace;
@synthesize deallocFlag = _deallocFlag;
+ (base::RunLoop**)runLoop {
static base::RunLoop* runLoop = nullptr;
return &runLoop;
}
// Returns once the NativeWidgetMacTestWindow's -dealloc method has been
// called.
+ (void)waitForDealloc {
base::RunLoop runLoop;
base::SingleThreadTaskRunner::GetCurrentDefault()->PostDelayedTask(
FROM_HERE, runLoop.QuitClosure(), TestTimeouts::action_timeout());
(*[NativeWidgetMacTestWindow runLoop]) = &runLoop;
runLoop.Run();
(*[NativeWidgetMacTestWindow runLoop]) = nullptr;
}
- (void)dealloc {
if (_deallocFlag) {
DCHECK(!*_deallocFlag);
*_deallocFlag = true;
if (*[NativeWidgetMacTestWindow runLoop]) {
(*[NativeWidgetMacTestWindow runLoop])->Quit();
}
}
[super dealloc];
}
- (void)invalidateShadow {
++_invalidateShadowCount;
[super invalidateShadow];
}
- (BOOL)isOnActiveSpace {
return !_fakeOnInactiveSpace;
}
@end
@implementation MockBridgedView
@synthesize drawRectCount = _drawRectCount;
@synthesize lastDirtyRect = _lastDirtyRect;
- (void)drawRect:(NSRect)dirtyRect {
++_drawRectCount;
_lastDirtyRect = dirtyRect;
}
@end
@implementation FocusableTestNSView
- (BOOL)acceptsFirstResponder {
return YES;
}
@end
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/native_widget_mac_unittest.mm | Objective-C++ | unknown | 94,780 |
// 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/widget/native_widget_private.h"
#include "ui/base/emoji/emoji_panel_helper.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
namespace views::internal {
// static
gfx::Rect NativeWidgetPrivate::ConstrainBoundsToDisplayWorkArea(
const gfx::Rect& bounds) {
gfx::Rect new_bounds(bounds);
gfx::Rect work_area =
display::Screen::GetScreen()->GetDisplayMatching(bounds).work_area();
if (!work_area.IsEmpty())
new_bounds.AdjustToFit(work_area);
return new_bounds;
}
void NativeWidgetPrivate::PaintAsActiveChanged() {}
void NativeWidgetPrivate::ShowEmojiPanel() {
ui::ShowEmojiPanel();
}
bool NativeWidgetPrivate::IsMoveLoopSupported() const {
return true;
}
} // namespace views::internal
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/native_widget_private.cc | C++ | unknown | 895 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_WIDGET_NATIVE_WIDGET_PRIVATE_H_
#define UI_VIEWS_WIDGET_NATIVE_WIDGET_PRIVATE_H_
#include <memory>
#include <string>
#include "ui/base/dragdrop/mojom/drag_drop_types.mojom-forward.h"
#include "ui/base/ui_base_types.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/widget/native_widget.h"
#include "ui/views/widget/widget.h"
namespace gfx {
class ImageSkia;
class Rect;
} // namespace gfx
namespace ui {
class InputMethod;
class GestureRecognizer;
class OSExchangeData;
} // namespace ui
namespace views {
class TooltipManager;
namespace internal {
////////////////////////////////////////////////////////////////////////////////
// NativeWidgetPrivate interface
//
// A NativeWidget subclass internal to views that provides Widget a conduit for
// communication with a backend-specific native widget implementation.
//
// Many of the methods here are pass-thrus for Widget, and as such there is no
// documentation for them here. In that case, see methods of the same name in
// widget.h.
//
// IMPORTANT: This type is intended for use only by the views system and for
// NativeWidget implementations. This file should not be included
// in code that does not fall into one of these use cases.
//
class VIEWS_EXPORT NativeWidgetPrivate : public NativeWidget {
public:
~NativeWidgetPrivate() override = default;
// Creates an appropriate default NativeWidgetPrivate implementation for the
// current OS/circumstance.
static NativeWidgetPrivate* CreateNativeWidget(
internal::NativeWidgetDelegate* delegate);
static NativeWidgetPrivate* GetNativeWidgetForNativeView(
gfx::NativeView native_view);
static NativeWidgetPrivate* GetNativeWidgetForNativeWindow(
gfx::NativeWindow native_window);
// Retrieves the top NativeWidgetPrivate in the hierarchy containing the given
// NativeView, or NULL if there is no NativeWidgetPrivate that contains it.
static NativeWidgetPrivate* GetTopLevelNativeWidget(
gfx::NativeView native_view);
static void GetAllChildWidgets(gfx::NativeView native_view,
Widget::Widgets* children);
static void GetAllOwnedWidgets(gfx::NativeView native_view,
Widget::Widgets* owned);
static void ReparentNativeView(gfx::NativeView native_view,
gfx::NativeView new_parent);
// Returns the NativeView with capture, otherwise NULL if there is no current
// capture set, or if |native_view| has no root.
static gfx::NativeView GetGlobalCapture(gfx::NativeView native_view);
// Adjusts the given bounds to fit onto the display implied by the position
// of the given bounds.
static gfx::Rect ConstrainBoundsToDisplayWorkArea(const gfx::Rect& bounds);
// Initializes the NativeWidget.
virtual void InitNativeWidget(Widget::InitParams params) = 0;
// Called at the end of Widget::Init(), after Widget has completed
// initialization.
virtual void OnWidgetInitDone() = 0;
// Returns a NonClientFrameView for the widget's NonClientView, or NULL if
// the NativeWidget wants no special NonClientFrameView.
virtual std::unique_ptr<NonClientFrameView> CreateNonClientFrameView() = 0;
virtual bool ShouldUseNativeFrame() const = 0;
virtual bool ShouldWindowContentsBeTransparent() const = 0;
virtual void FrameTypeChanged() = 0;
// Returns the Widget associated with this NativeWidget. This function is
// guaranteed to return non-NULL for the lifetime of the NativeWidget.
virtual Widget* GetWidget() = 0;
virtual const Widget* GetWidget() const = 0;
// Returns the NativeView/Window associated with this NativeWidget.
virtual gfx::NativeView GetNativeView() const = 0;
virtual gfx::NativeWindow GetNativeWindow() const = 0;
// Returns the topmost Widget in a hierarchy.
virtual Widget* GetTopLevelWidget() = 0;
// Returns the Compositor, or NULL if there isn't one associated with this
// NativeWidget.
virtual const ui::Compositor* GetCompositor() const = 0;
// Returns the NativeWidget's layer, if any.
virtual const ui::Layer* GetLayer() const = 0;
// Reorders the widget's child NativeViews which are associated to the view
// tree (eg via a NativeViewHost) to match the z-order of the views in the
// view tree. The z-order of views with layers relative to views with
// associated NativeViews is used to reorder the NativeView layers. This
// method assumes that the widget's child layers which are owned by a view are
// already in the correct z-order relative to each other and does no
// reordering if there are no views with an associated NativeView.
virtual void ReorderNativeViews() = 0;
// Notifies the NativeWidget that a view was removed from the Widget's view
// hierarchy.
virtual void ViewRemoved(View* view) = 0;
// Sets/Gets a native window property on the underlying native window object.
// Returns NULL if the property does not exist. Setting the property value to
// NULL removes the property.
virtual void SetNativeWindowProperty(const char* name, void* value) = 0;
virtual void* GetNativeWindowProperty(const char* name) const = 0;
// Returns the native widget's tooltip manager. Called from the View hierarchy
// to update tooltips.
virtual TooltipManager* GetTooltipManager() const = 0;
// Sets or releases event capturing for this native widget.
virtual void SetCapture() = 0;
virtual void ReleaseCapture() = 0;
// Returns true if this native widget is capturing events.
virtual bool HasCapture() const = 0;
// Returns the ui::InputMethod for this native widget.
virtual ui::InputMethod* GetInputMethod() = 0;
// Centers the window and sizes it to the specified size.
virtual void CenterWindow(const gfx::Size& size) = 0;
// Retrieves the window's current restored bounds and "show" state, for
// persisting.
virtual void GetWindowPlacement(gfx::Rect* bounds,
ui::WindowShowState* show_state) const = 0;
// Sets the NativeWindow title. Returns true if the title changed.
virtual bool SetWindowTitle(const std::u16string& title) = 0;
// Sets the Window icons. |window_icon| is a 16x16 icon suitable for use in
// a title bar. |app_icon| is a larger size for use in the host environment
// app switching UI.
virtual void SetWindowIcons(const gfx::ImageSkia& window_icon,
const gfx::ImageSkia& app_icon) = 0;
virtual const gfx::ImageSkia* GetWindowIcon() = 0;
virtual const gfx::ImageSkia* GetWindowAppIcon() = 0;
// Initializes the modal type of the window to |modal_type|. Called from
// NativeWidgetDelegate::OnNativeWidgetCreated() before the widget is
// initially parented.
virtual void InitModalType(ui::ModalType modal_type) = 0;
// See method documentation in Widget.
virtual gfx::Rect GetWindowBoundsInScreen() const = 0;
virtual gfx::Rect GetClientAreaBoundsInScreen() const = 0;
virtual gfx::Rect GetRestoredBounds() const = 0;
virtual std::string GetWorkspace() const = 0;
virtual void SetBounds(const gfx::Rect& bounds) = 0;
virtual void SetBoundsConstrained(const gfx::Rect& bounds) = 0;
virtual void SetSize(const gfx::Size& size) = 0;
virtual void StackAbove(gfx::NativeView native_view) = 0;
virtual void StackAtTop() = 0;
virtual bool IsStackedAbove(gfx::NativeView native_view) = 0;
virtual void SetShape(std::unique_ptr<Widget::ShapeRects> shape) = 0;
virtual void Close() = 0;
virtual void CloseNow() = 0;
virtual void Show(ui::WindowShowState show_state,
const gfx::Rect& restore_bounds) = 0;
virtual void Hide() = 0;
virtual bool IsVisible() const = 0;
virtual void Activate() = 0;
virtual void Deactivate() = 0;
virtual bool IsActive() const = 0;
virtual void PaintAsActiveChanged();
virtual void SetZOrderLevel(ui::ZOrderLevel order) = 0;
virtual ui::ZOrderLevel GetZOrderLevel() const = 0;
virtual void SetVisibleOnAllWorkspaces(bool always_visible) = 0;
virtual bool IsVisibleOnAllWorkspaces() const = 0;
virtual void Maximize() = 0;
virtual void Minimize() = 0;
virtual bool IsMaximized() const = 0;
virtual bool IsMinimized() const = 0;
virtual void Restore() = 0;
virtual void SetFullscreen(bool fullscreen, int64_t target_display_id) = 0;
virtual bool IsFullscreen() const = 0;
virtual void SetCanAppearInExistingFullscreenSpaces(
bool can_appear_in_existing_fullscreen_spaces) = 0;
virtual void SetOpacity(float opacity) = 0;
// The size of the widget will be set such that it is in the same proportion
// as `aspect_ratio` after subtracting `excluded_margin` from the widget size.
//
// This allows the aspect ratio to refer to just a subrectangle of the widget,
// to leave room for, e.g., a client-drawn title bar or window decorations.
// System-drawn decorations are excluded automatically, but the system has no
// idea if we decide to draw our own. By setting `excluded_margin` to our
// custom-drawn decorations, we can maintain the same behavior.
virtual void SetAspectRatio(const gfx::SizeF& aspect_ratio,
const gfx::Size& excluded_margin) = 0;
virtual void FlashFrame(bool flash) = 0;
virtual void RunShellDrag(View* view,
std::unique_ptr<ui::OSExchangeData> data,
const gfx::Point& location,
int operation,
ui::mojom::DragEventSource source) = 0;
virtual void SchedulePaintInRect(const gfx::Rect& rect) = 0;
virtual void ScheduleLayout() = 0;
virtual void SetCursor(const ui::Cursor& cursor) = 0;
virtual void ShowEmojiPanel();
virtual bool IsMouseEventsEnabled() const = 0;
// Returns true if any mouse button is currently down.
virtual bool IsMouseButtonDown() const = 0;
virtual void ClearNativeFocus() = 0;
virtual gfx::Rect GetWorkAreaBoundsInScreen() const = 0;
virtual bool IsMoveLoopSupported() const;
virtual Widget::MoveLoopResult RunMoveLoop(
const gfx::Vector2d& drag_offset,
Widget::MoveLoopSource source,
Widget::MoveLoopEscapeBehavior escape_behavior) = 0;
virtual void EndMoveLoop() = 0;
virtual void SetVisibilityChangedAnimationsEnabled(bool value) = 0;
virtual void SetVisibilityAnimationDuration(
const base::TimeDelta& duration) = 0;
virtual void SetVisibilityAnimationTransition(
Widget::VisibilityTransition transition) = 0;
virtual bool IsTranslucentWindowOpacitySupported() const = 0;
virtual ui::GestureRecognizer* GetGestureRecognizer() = 0;
virtual ui::GestureConsumer* GetGestureConsumer() = 0;
virtual void OnSizeConstraintsChanged() = 0;
// Called before and after re-parenting of this or an ancestor widget.
virtual void OnNativeViewHierarchyWillChange() = 0;
virtual void OnNativeViewHierarchyChanged() = 0;
// Returns an internal name that matches the name of the associated Widget.
virtual std::string GetName() const = 0;
virtual base::WeakPtr<NativeWidgetPrivate> GetWeakPtr() = 0;
// Overridden from NativeWidget:
internal::NativeWidgetPrivate* AsNativeWidgetPrivate() override;
};
} // namespace internal
} // namespace views
#endif // UI_VIEWS_WIDGET_NATIVE_WIDGET_PRIVATE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/native_widget_private.h | C++ | unknown | 11,443 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/memory/raw_ptr.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/views/controls/native/native_view_host.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/view.h"
#include "ui/views/widget/native_widget_private.h"
#include "ui/views/widget/widget.h"
namespace views {
class ScopedTestWidget {
public:
explicit ScopedTestWidget(internal::NativeWidgetPrivate* native_widget)
: native_widget_(native_widget) {}
ScopedTestWidget(const ScopedTestWidget&) = delete;
ScopedTestWidget& operator=(const ScopedTestWidget&) = delete;
~ScopedTestWidget() {
// |CloseNow| deletes both |native_widget_| and its associated
// |Widget|.
native_widget_->GetWidget()->CloseNow();
}
internal::NativeWidgetPrivate* operator->() const { return native_widget_; }
internal::NativeWidgetPrivate* get() const { return native_widget_; }
private:
raw_ptr<internal::NativeWidgetPrivate> native_widget_;
};
class NativeWidgetTest : public ViewsTestBase {
public:
NativeWidgetTest() = default;
NativeWidgetTest(const NativeWidgetTest&) = delete;
NativeWidgetTest& operator=(const NativeWidgetTest&) = delete;
~NativeWidgetTest() override = default;
internal::NativeWidgetPrivate* CreateNativeWidgetOfType(
Widget::InitParams::Type type) {
Widget* widget = new Widget;
Widget::InitParams params = CreateParams(type);
params.ownership = views::Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET;
params.bounds = gfx::Rect(10, 10, 200, 200);
widget->Init(std::move(params));
return widget->native_widget_private();
}
internal::NativeWidgetPrivate* CreateNativeWidget() {
return CreateNativeWidgetOfType(Widget::InitParams::TYPE_POPUP);
}
internal::NativeWidgetPrivate* CreateNativeSubWidget() {
return CreateNativeWidgetOfType(Widget::InitParams::TYPE_CONTROL);
}
};
TEST_F(NativeWidgetTest, CreateNativeWidget) {
ScopedTestWidget widget(CreateNativeWidget());
EXPECT_TRUE(widget->GetWidget()->GetNativeView());
}
TEST_F(NativeWidgetTest, GetNativeWidgetForNativeView) {
ScopedTestWidget widget(CreateNativeWidget());
EXPECT_EQ(widget.get(),
internal::NativeWidgetPrivate::GetNativeWidgetForNativeView(
widget->GetWidget()->GetNativeView()));
}
// |widget| has the toplevel NativeWidget.
TEST_F(NativeWidgetTest, GetTopLevelNativeWidget1) {
ScopedTestWidget widget(CreateNativeWidget());
EXPECT_EQ(widget.get(),
internal::NativeWidgetPrivate::GetTopLevelNativeWidget(
widget->GetWidget()->GetNativeView()));
}
// |toplevel_widget| has the toplevel NativeWidget.
TEST_F(NativeWidgetTest, GetTopLevelNativeWidget2) {
internal::NativeWidgetPrivate* child_widget = CreateNativeSubWidget();
{
ScopedTestWidget toplevel_widget(CreateNativeWidget());
// |toplevel_widget| owns |child_host|.
NativeViewHost* child_host = toplevel_widget->GetWidget()->SetContentsView(
std::make_unique<NativeViewHost>());
// |child_host| hosts |child_widget|'s NativeView.
child_host->Attach(child_widget->GetWidget()->GetNativeView());
EXPECT_EQ(toplevel_widget.get(),
internal::NativeWidgetPrivate::GetTopLevelNativeWidget(
child_widget->GetWidget()->GetNativeView()));
}
// NativeViewHost only had a weak reference to the |child_widget|'s
// NativeView. Delete it and the associated Widget.
child_widget->CloseNow();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/native_widget_unittest.cc | C++ | unknown | 3,626 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/widget/root_view.h"
#include <algorithm>
#include <memory>
#include "base/logging.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/raw_ptr_exclusion.h"
#include "base/memory/raw_ref.h"
#include "base/scoped_observation.h"
#include "base/strings/string_piece.h"
#include "build/build_config.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/base/cursor/cursor.h"
#include "ui/base/dragdrop/mojom/drag_drop_types.mojom-shared.h"
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/base/ui_base_switches_util.h"
#include "ui/compositor/layer.h"
#include "ui/events/event.h"
#include "ui/events/event_utils.h"
#include "ui/events/gestures/gesture_recognizer.h"
#include "ui/events/keycodes/keyboard_codes.h"
#include "ui/gfx/canvas.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/drag_controller.h"
#include "ui/views/view_class_properties.h"
#include "ui/views/view_targeter.h"
#include "ui/views/widget/root_view_targeter.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_delegate.h"
using DispatchDetails = ui::EventDispatchDetails;
namespace views::internal {
namespace {
class MouseEnterExitEvent : public ui::MouseEvent {
public:
MouseEnterExitEvent(const ui::MouseEvent& event, ui::EventType type)
: ui::MouseEvent(event,
static_cast<View*>(nullptr),
static_cast<View*>(nullptr)) {
DCHECK(type == ui::ET_MOUSE_ENTERED || type == ui::ET_MOUSE_EXITED);
SetType(type);
}
~MouseEnterExitEvent() override = default;
// Event:
std::unique_ptr<ui::Event> Clone() const override {
return std::make_unique<MouseEnterExitEvent>(*this);
}
};
// TODO(crbug.com/1295290): This class is for debug purpose only.
// Remove it after resolving the issue.
class DanglingMouseMoveHandlerOnViewDestroyingChecker
: public views::ViewObserver {
public:
explicit DanglingMouseMoveHandlerOnViewDestroyingChecker(
const raw_ptr<views::View, DanglingUntriaged>& mouse_move_handler)
: mouse_move_handler_(mouse_move_handler) {
scoped_observation.Observe(mouse_move_handler_);
}
// views::ViewObserver:
void OnViewIsDeleting(views::View* view) override {
// `mouse_move_handler_` should be nulled before `view` dies. Otherwise
// `mouse_move_handler_` will become a dangling pointer.
CHECK(!mouse_move_handler_);
scoped_observation.Reset();
}
private:
base::ScopedObservation<views::View, views::ViewObserver> scoped_observation{
this};
// Excluded from `raw_ref` rewriter which would otherwise turn this
// into a `raw_ref<raw_ptr<>>`. The current `raw_ptr&` setup is
// intentional and used to observe the pointer without counting as a
// live reference to the underlying memory.
RAW_PTR_EXCLUSION const raw_ptr<views::View, DanglingUntriaged>&
mouse_move_handler_;
};
} // namespace
// Used by RootView to create a hidden child that can be used to make screen
// reader announcements on platforms that don't have a reliable system API call
// to do that.
//
// We use a separate view because the RootView itself supplies the widget's
// accessible name and cannot serve double-duty (the inability for views to make
// their own announcements without changing their accessible name or description
// is the reason this system exists at all).
class AnnounceTextView : public View {
public:
METADATA_HEADER(AnnounceTextView);
~AnnounceTextView() override = default;
void Announce(const std::u16string& text) {
// TODO(crbug.com/1024898): Use kLiveRegionChanged when supported across
// screen readers and platforms. See bug for details.
announce_text_ = text;
NotifyAccessibilityEvent(ax::mojom::Event::kAlert, true);
}
// View:
void GetAccessibleNodeData(ui::AXNodeData* node_data) override {
#if BUILDFLAG(IS_CHROMEOS)
// On ChromeOS, kAlert role can invoke an unnecessary event on reparenting.
node_data->role = ax::mojom::Role::kStaticText;
#else
// TODO(crbug.com/1024898): Use live regions (do not use alerts).
// May require setting kLiveStatus, kContainerLiveStatus to "polite".
node_data->role = ax::mojom::Role::kAlert;
#endif
node_data->SetNameChecked(announce_text_);
node_data->AddState(ax::mojom::State::kInvisible);
}
private:
std::u16string announce_text_;
};
BEGIN_METADATA(AnnounceTextView, View)
END_METADATA
// This event handler receives events in the pre-target phase and takes care of
// the following:
// - Shows keyboard-triggered context menus.
class PreEventDispatchHandler : public ui::EventHandler {
public:
explicit PreEventDispatchHandler(View* owner) : owner_(owner) {
owner_->AddPreTargetHandler(this);
}
PreEventDispatchHandler(const PreEventDispatchHandler&) = delete;
PreEventDispatchHandler& operator=(const PreEventDispatchHandler&) = delete;
~PreEventDispatchHandler() override { owner_->RemovePreTargetHandler(this); }
private:
// ui::EventHandler:
void OnKeyEvent(ui::KeyEvent* event) override {
CHECK_EQ(ui::EP_PRETARGET, event->phase());
// macOS doesn't have keyboard-triggered context menus.
#if !BUILDFLAG(IS_MAC)
if (event->handled())
return;
View* v = nullptr;
if (owner_->GetFocusManager()) // Can be NULL in unittests.
v = owner_->GetFocusManager()->GetFocusedView();
// Special case to handle keyboard-triggered context menus.
if (v && v->GetEnabled() &&
((event->key_code() == ui::VKEY_APPS) ||
(event->key_code() == ui::VKEY_F10 && event->IsShiftDown()))) {
// Clamp the menu location within the visible bounds of each ancestor view
// to avoid showing the menu over a completely different view or window.
gfx::Point location = v->GetKeyboardContextMenuLocation();
for (View* parent = v->parent(); parent; parent = parent->parent()) {
const gfx::Rect& parent_bounds = parent->GetBoundsInScreen();
location.SetToMax(parent_bounds.origin());
location.SetToMin(parent_bounds.bottom_right());
}
v->ShowContextMenu(location, ui::MENU_SOURCE_KEYBOARD);
event->StopPropagation();
}
#endif
}
base::StringPiece GetLogContext() const override {
return "PreEventDispatchHandler";
}
raw_ptr<View> owner_;
};
// This event handler receives events in the post-target phase and takes care of
// the following:
// - Generates context menu, or initiates drag-and-drop, from gesture events.
class PostEventDispatchHandler : public ui::EventHandler {
public:
PostEventDispatchHandler()
: touch_dnd_enabled_(::switches::IsTouchDragDropEnabled()) {}
PostEventDispatchHandler(const PostEventDispatchHandler&) = delete;
PostEventDispatchHandler& operator=(const PostEventDispatchHandler&) = delete;
~PostEventDispatchHandler() override = default;
private:
// Overridden from ui::EventHandler:
void OnGestureEvent(ui::GestureEvent* event) override {
DCHECK_EQ(ui::EP_POSTTARGET, event->phase());
if (event->handled())
return;
View* target = static_cast<View*>(event->target());
gfx::Point location = event->location();
if (touch_dnd_enabled_ && event->type() == ui::ET_GESTURE_LONG_PRESS &&
(!target->drag_controller() ||
target->drag_controller()->CanStartDragForView(target, location,
location))) {
if (target->DoDrag(*event, location,
ui::mojom::DragEventSource::kTouch)) {
event->StopPropagation();
return;
}
}
if (target->context_menu_controller() &&
(event->type() == ui::ET_GESTURE_LONG_PRESS ||
event->type() == ui::ET_GESTURE_LONG_TAP ||
event->type() == ui::ET_GESTURE_TWO_FINGER_TAP)) {
gfx::Point screen_location(location);
View::ConvertPointToScreen(target, &screen_location);
target->ShowContextMenu(screen_location, ui::MENU_SOURCE_TOUCH);
event->StopPropagation();
}
}
base::StringPiece GetLogContext() const override {
return "PostEventDispatchHandler";
}
bool touch_dnd_enabled_;
};
////////////////////////////////////////////////////////////////////////////////
// RootView, public:
// Creation and lifetime -------------------------------------------------------
RootView::RootView(Widget* widget)
: widget_(widget),
pre_dispatch_handler_(
std::make_unique<internal::PreEventDispatchHandler>(this)),
post_dispatch_handler_(
std::make_unique<internal::PostEventDispatchHandler>()) {
AddPostTargetHandler(post_dispatch_handler_.get());
SetEventTargeter(
std::unique_ptr<ViewTargeter>(new RootViewTargeter(this, this)));
}
RootView::~RootView() {
// If we have children remove them explicitly so to make sure a remove
// notification is sent for each one of them.
RemoveAllChildViews();
}
// Tree operations -------------------------------------------------------------
void RootView::SetContentsView(View* contents_view) {
DCHECK(contents_view && GetWidget()->native_widget())
<< "Can't be called because the widget is not initialized or is "
"destroyed";
// The ContentsView must be set up _after_ the window is created so that its
// Widget pointer is valid.
SetUseDefaultFillLayout(true);
if (!children().empty())
RemoveAllChildViews();
AddChildView(contents_view);
}
View* RootView::GetContentsView() {
return children().empty() ? nullptr : children().front();
}
void RootView::NotifyNativeViewHierarchyChanged() {
PropagateNativeViewHierarchyChanged();
}
// Focus -----------------------------------------------------------------------
void RootView::SetFocusTraversableParent(FocusTraversable* focus_traversable) {
DCHECK(focus_traversable != this);
focus_traversable_parent_ = focus_traversable;
}
void RootView::SetFocusTraversableParentView(View* view) {
focus_traversable_parent_view_ = view;
}
// System events ---------------------------------------------------------------
void RootView::ThemeChanged() {
View::PropagateThemeChanged();
}
void RootView::ResetEventHandlers() {
explicit_mouse_handler_ = false;
mouse_pressed_handler_ = nullptr;
mouse_move_handler_ = nullptr;
gesture_handler_ = nullptr;
event_dispatch_target_ = nullptr;
old_dispatch_target_ = nullptr;
}
void RootView::DeviceScaleFactorChanged(float old_device_scale_factor,
float new_device_scale_factor) {
View::PropagateDeviceScaleFactorChanged(old_device_scale_factor,
new_device_scale_factor);
}
// Accessibility ---------------------------------------------------------------
AnnounceTextView* RootView::GetOrCreateAnnounceView() {
if (!announce_view_) {
announce_view_ = AddChildView(std::make_unique<AnnounceTextView>());
announce_view_->SetProperty(kViewIgnoredByLayoutKey, true);
}
return announce_view_.get();
}
void RootView::AnnounceText(const std::u16string& text) {
#if BUILDFLAG(IS_MAC)
gfx::NativeViewAccessible native = GetViewAccessibility().GetNativeObject();
auto* ax_node = ui::AXPlatformNode::FromNativeViewAccessible(native);
if (ax_node)
ax_node->AnnounceText(text);
#else
DCHECK(GetWidget());
DCHECK(GetContentsView());
GetOrCreateAnnounceView()->Announce(text);
#endif
}
View* RootView::GetAnnounceViewForTesting() {
return GetOrCreateAnnounceView();
}
////////////////////////////////////////////////////////////////////////////////
// RootView, FocusTraversable implementation:
FocusSearch* RootView::GetFocusSearch() {
return &focus_search_;
}
FocusTraversable* RootView::GetFocusTraversableParent() {
return focus_traversable_parent_;
}
View* RootView::GetFocusTraversableParentView() {
return focus_traversable_parent_view_;
}
////////////////////////////////////////////////////////////////////////////////
// RootView, ui::EventProcessor overrides:
ui::EventTarget* RootView::GetRootForEvent(ui::Event* event) {
return this;
}
ui::EventTargeter* RootView::GetDefaultEventTargeter() {
return this->GetEventTargeter();
}
void RootView::OnEventProcessingStarted(ui::Event* event) {
VLOG(5) << "RootView::OnEventProcessingStarted(" << event->ToString() << ")";
if (!event->IsGestureEvent())
return;
ui::GestureEvent* gesture_event = event->AsGestureEvent();
// Do not process ui::ET_GESTURE_BEGIN events.
if (gesture_event->type() == ui::ET_GESTURE_BEGIN) {
event->SetHandled();
return;
}
// Do not process ui::ET_GESTURE_END events if they do not correspond to the
// removal of the final touch point or if no gesture handler has already
// been set.
if (gesture_event->type() == ui::ET_GESTURE_END &&
(gesture_event->details().touch_points() > 1 || !gesture_handler_)) {
event->SetHandled();
return;
}
// Do not process subsequent gesture scroll events if no handler was set for
// a ui::ET_GESTURE_SCROLL_BEGIN event.
if (!gesture_handler_ &&
(gesture_event->type() == ui::ET_GESTURE_SCROLL_UPDATE ||
gesture_event->type() == ui::ET_GESTURE_SCROLL_END ||
gesture_event->type() == ui::ET_SCROLL_FLING_START)) {
event->SetHandled();
return;
}
gesture_handler_set_before_processing_ = !!gesture_handler_;
}
void RootView::OnEventProcessingFinished(ui::Event* event) {
VLOG(5) << "RootView::OnEventProcessingFinished(" << event->ToString() << ")";
// If |event| was not handled and |gesture_handler_| was not set by the
// dispatch of a previous gesture event, then no default gesture handler
// should be set prior to the next gesture event being received.
if (event->IsGestureEvent() && !event->handled() &&
!gesture_handler_set_before_processing_) {
gesture_handler_ = nullptr;
}
}
////////////////////////////////////////////////////////////////////////////////
// RootView, View overrides:
const Widget* RootView::GetWidget() const {
return widget_;
}
Widget* RootView::GetWidget() {
return const_cast<Widget*>(const_cast<const RootView*>(this)->GetWidget());
}
bool RootView::IsDrawn() const {
return GetVisible();
}
bool RootView::OnMousePressed(const ui::MouseEvent& event) {
UpdateCursor(event);
SetMouseLocationAndFlags(event);
// If mouse_pressed_handler_ is non null, we are currently processing
// a pressed -> drag -> released session. In that case we send the
// event to mouse_pressed_handler_
if (mouse_pressed_handler_) {
ui::MouseEvent mouse_pressed_event(event, static_cast<View*>(this),
mouse_pressed_handler_.get());
drag_info_.Reset();
ui::EventDispatchDetails dispatch_details =
DispatchEvent(mouse_pressed_handler_, &mouse_pressed_event);
if (dispatch_details.dispatcher_destroyed)
return true;
return true;
}
DCHECK(!explicit_mouse_handler_);
// Walk up the tree from the target until we find a view that wants
// the mouse event.
for (mouse_pressed_handler_ = GetEventHandlerForPoint(event.location());
mouse_pressed_handler_ && (mouse_pressed_handler_ != this);
mouse_pressed_handler_ = mouse_pressed_handler_->parent()) {
DVLOG(1) << "OnMousePressed testing "
<< mouse_pressed_handler_->GetClassName();
DCHECK(mouse_pressed_handler_->GetEnabled());
// See if this view wants to handle the mouse press.
ui::MouseEvent mouse_pressed_event(event, static_cast<View*>(this),
mouse_pressed_handler_.get());
// Remove the double-click flag if the handler is different than the
// one which got the first click part of the double-click.
if (mouse_pressed_handler_ != last_click_handler_)
mouse_pressed_event.set_flags(event.flags() & ~ui::EF_IS_DOUBLE_CLICK);
drag_info_.Reset();
ui::EventDispatchDetails dispatch_details =
DispatchEvent(mouse_pressed_handler_, &mouse_pressed_event);
if (dispatch_details.dispatcher_destroyed)
return mouse_pressed_event.handled();
// The view could have removed itself from the tree when handling
// OnMousePressed(). In this case, the removal notification will have
// reset mouse_pressed_handler_ to NULL out from under us. Detect this
// case and stop. (See comments in view.h.)
//
// NOTE: Don't return true here, because we don't want the frame to
// forward future events to us when there's no handler.
if (!mouse_pressed_handler_)
break;
// If the view handled the event, leave mouse_pressed_handler_ set and
// return true, which will cause subsequent drag/release events to get
// forwarded to that view.
if (mouse_pressed_event.handled()) {
last_click_handler_ = mouse_pressed_handler_;
DVLOG(1) << "OnMousePressed handled by "
<< mouse_pressed_handler_->GetClassName();
return true;
}
}
// Reset mouse_pressed_handler_ to indicate that no processing is occurring.
mouse_pressed_handler_ = nullptr;
const bool last_click_was_handled = (last_click_handler_ != nullptr);
last_click_handler_ = nullptr;
// In the event that a double-click is not handled after traversing the
// entire hierarchy (even as a single-click when sent to a different view),
// it must be marked as handled to avoid anything happening from default
// processing if it the first click-part was handled by us.
return last_click_was_handled && (event.flags() & ui::EF_IS_DOUBLE_CLICK);
}
bool RootView::OnMouseDragged(const ui::MouseEvent& event) {
if (mouse_pressed_handler_) {
SetMouseLocationAndFlags(event);
ui::MouseEvent mouse_event(event, static_cast<View*>(this),
mouse_pressed_handler_.get());
ui::EventDispatchDetails dispatch_details =
DispatchEvent(mouse_pressed_handler_, &mouse_event);
if (dispatch_details.dispatcher_destroyed)
return false;
return true;
}
return false;
}
void RootView::OnMouseReleased(const ui::MouseEvent& event) {
UpdateCursor(event);
if (mouse_pressed_handler_) {
ui::MouseEvent mouse_released(event, static_cast<View*>(this),
mouse_pressed_handler_.get());
// We allow the view to delete us from the event dispatch callback. As such,
// configure state such that we're done first, then call View.
View* mouse_pressed_handler = mouse_pressed_handler_;
// During mouse event handling, `SetMouseAndGestureHandler()` may be called
// to set the gesture handler. Therefore we should reset the gesture handler
// when mouse is released.
SetMouseAndGestureHandler(nullptr);
ui::EventDispatchDetails dispatch_details =
DispatchEvent(mouse_pressed_handler, &mouse_released);
if (dispatch_details.dispatcher_destroyed)
return;
}
}
void RootView::OnMouseCaptureLost() {
if (mouse_pressed_handler_ || gesture_handler_) {
// Synthesize a release event for UpdateCursor.
if (mouse_pressed_handler_) {
gfx::Point last_point(last_mouse_event_x_, last_mouse_event_y_);
ui::MouseEvent release_event(ui::ET_MOUSE_RELEASED, last_point,
last_point, ui::EventTimeForNow(),
last_mouse_event_flags_, 0);
UpdateCursor(release_event);
}
// We allow the view to delete us from OnMouseCaptureLost. As such,
// configure state such that we're done first, then call View.
View* mouse_pressed_handler = mouse_pressed_handler_;
View* gesture_handler = gesture_handler_;
SetMouseAndGestureHandler(nullptr);
if (mouse_pressed_handler)
mouse_pressed_handler->OnMouseCaptureLost();
else
gesture_handler->OnMouseCaptureLost();
// WARNING: we may have been deleted.
}
}
void RootView::OnMouseMoved(const ui::MouseEvent& event) {
View* v = GetEventHandlerForPoint(event.location());
// Check for a disabled move handler. If the move handler became
// disabled while handling moves, it's wrong to suddenly send
// ET_MOUSE_EXITED and ET_MOUSE_ENTERED events, because the mouse
// hasn't actually exited yet.
if (mouse_move_handler_ && !mouse_move_handler_->GetEnabled() &&
v->Contains(mouse_move_handler_))
v = mouse_move_handler_;
if (v && v != this) {
if (v != mouse_move_handler_) {
if (mouse_move_handler_ != nullptr &&
(!mouse_move_handler_->GetNotifyEnterExitOnChild() ||
!mouse_move_handler_->Contains(v))) {
MouseEnterExitEvent exit(event, ui::ET_MOUSE_EXITED);
exit.ConvertLocationToTarget(static_cast<View*>(this),
mouse_move_handler_.get());
ui::EventDispatchDetails dispatch_details =
DispatchEvent(mouse_move_handler_, &exit);
if (dispatch_details.dispatcher_destroyed)
return;
// The mouse_move_handler_ could have been destroyed in the context of
// the mouse exit event.
if (!dispatch_details.target_destroyed) {
// View was removed by ET_MOUSE_EXITED, or |mouse_move_handler_| was
// cleared, perhaps by a nested event handler, so return and wait for
// the next mouse move event.
if (!mouse_move_handler_)
return;
dispatch_details = NotifyEnterExitOfDescendant(
event, ui::ET_MOUSE_EXITED, mouse_move_handler_, v);
if (dispatch_details.dispatcher_destroyed)
return;
}
}
View* old_handler = mouse_move_handler_;
mouse_move_handler_ = v;
// TODO(crbug.com/1295290): This is for debug purpose only.
// Remove it after resolving the issue.
DanglingMouseMoveHandlerOnViewDestroyingChecker
mouse_move_handler_dangling_checker(mouse_move_handler_);
if (!mouse_move_handler_->GetNotifyEnterExitOnChild() ||
!mouse_move_handler_->Contains(old_handler)) {
MouseEnterExitEvent entered(event, ui::ET_MOUSE_ENTERED);
entered.ConvertLocationToTarget(static_cast<View*>(this),
mouse_move_handler_.get());
ui::EventDispatchDetails dispatch_details =
DispatchEvent(mouse_move_handler_, &entered);
if (dispatch_details.dispatcher_destroyed ||
dispatch_details.target_destroyed) {
return;
}
// View was removed by ET_MOUSE_ENTERED, or |mouse_move_handler_| was
// cleared, perhaps by a nested event handler, so return and wait for
// the next mouse move event.
if (!mouse_move_handler_)
return;
dispatch_details = NotifyEnterExitOfDescendant(
event, ui::ET_MOUSE_ENTERED, mouse_move_handler_, old_handler);
if (dispatch_details.dispatcher_destroyed ||
dispatch_details.target_destroyed) {
return;
}
}
}
ui::MouseEvent moved_event(event, static_cast<View*>(this),
mouse_move_handler_.get());
mouse_move_handler_->OnMouseMoved(moved_event);
// TODO(tdanderson): It may be possible to avoid setting the cursor twice
// (once here and once from CompoundEventFilter) on a
// mousemove. See crbug.com/351469.
if (!(moved_event.flags() & ui::EF_IS_NON_CLIENT))
widget_->SetCursor(mouse_move_handler_->GetCursor(moved_event));
} else if (mouse_move_handler_ != nullptr) {
MouseEnterExitEvent exited(event, ui::ET_MOUSE_EXITED);
ui::EventDispatchDetails dispatch_details =
DispatchEvent(mouse_move_handler_, &exited);
if (dispatch_details.dispatcher_destroyed)
return;
// The mouse_move_handler_ could have been destroyed in the context of the
// mouse exit event.
if (!dispatch_details.target_destroyed) {
// View was removed by ET_MOUSE_EXITED, or |mouse_move_handler_| was
// cleared, perhaps by a nested event handler, so return and wait for
// the next mouse move event.
if (!mouse_move_handler_)
return;
dispatch_details = NotifyEnterExitOfDescendant(event, ui::ET_MOUSE_EXITED,
mouse_move_handler_, v);
if (dispatch_details.dispatcher_destroyed)
return;
}
// On Aura the non-client area extends slightly outside the root view for
// some windows. Let the non-client cursor handling code set the cursor
// as we do above.
if (!(event.flags() & ui::EF_IS_NON_CLIENT))
widget_->SetCursor(ui::Cursor());
mouse_move_handler_ = nullptr;
}
}
void RootView::OnMouseExited(const ui::MouseEvent& event) {
if (mouse_move_handler_ != nullptr) {
MouseEnterExitEvent exited(event, ui::ET_MOUSE_EXITED);
ui::EventDispatchDetails dispatch_details =
DispatchEvent(mouse_move_handler_, &exited);
if (dispatch_details.dispatcher_destroyed)
return;
// The mouse_move_handler_ could have been destroyed in the context of the
// mouse exit event.
if (!dispatch_details.target_destroyed) {
CHECK(mouse_move_handler_);
dispatch_details = NotifyEnterExitOfDescendant(
event, ui::ET_MOUSE_EXITED, mouse_move_handler_, nullptr);
if (dispatch_details.dispatcher_destroyed)
return;
}
mouse_move_handler_ = nullptr;
}
}
bool RootView::OnMouseWheel(const ui::MouseWheelEvent& event) {
for (View* v = GetEventHandlerForPoint(event.location());
v && v != this && !event.handled(); v = v->parent()) {
ui::EventDispatchDetails dispatch_details =
DispatchEvent(v, const_cast<ui::MouseWheelEvent*>(&event));
if (dispatch_details.dispatcher_destroyed ||
dispatch_details.target_destroyed) {
return event.handled();
}
}
return event.handled();
}
void RootView::MaybeNotifyGestureHandlerBeforeReplacement() {
#if defined(USE_AURA)
ui::GestureRecognizer* gesture_recognizer =
(gesture_handler_ && widget_ ? widget_->GetGestureRecognizer() : nullptr);
if (!gesture_recognizer)
return;
ui::GestureConsumer* gesture_consumer = widget_->GetGestureConsumer();
if (!gesture_recognizer->DoesConsumerHaveActiveTouch(gesture_consumer))
return;
gesture_recognizer->SendSynthesizedEndEvents(gesture_consumer);
#endif
}
void RootView::SetMouseAndGestureHandler(View* new_handler) {
SetMouseHandler(new_handler);
if (new_handler == gesture_handler_)
return;
MaybeNotifyGestureHandlerBeforeReplacement();
gesture_handler_ = new_handler;
}
void RootView::SetMouseHandler(View* new_mouse_handler) {
// If we're clearing the mouse handler, clear explicit_mouse_handler_ as well.
explicit_mouse_handler_ = (new_mouse_handler != nullptr);
mouse_pressed_handler_ = new_mouse_handler;
drag_info_.Reset();
}
void RootView::GetAccessibleNodeData(ui::AXNodeData* node_data) {
View::GetAccessibleNodeData(node_data);
DCHECK(GetWidget());
auto* widget_delegate = GetWidget()->widget_delegate();
if (!widget_delegate) {
return;
}
if (node_data->role == ax::mojom::Role::kUnknown) {
node_data->role = widget_delegate->GetAccessibleWindowRole();
}
if (node_data->GetStringAttribute(ax::mojom::StringAttribute::kName)
.empty() &&
static_cast<ax::mojom::NameFrom>(
node_data->GetIntAttribute(ax::mojom::IntAttribute::kNameFrom)) !=
ax::mojom::NameFrom::kAttributeExplicitlyEmpty) {
node_data->SetName(widget_delegate->GetAccessibleWindowTitle());
}
}
void RootView::UpdateParentLayer() {
if (layer())
ReparentLayer(widget_->GetLayer());
}
////////////////////////////////////////////////////////////////////////////////
// RootView, protected:
void RootView::ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) {
widget_->ViewHierarchyChanged(details);
if (!details.is_add && !details.move_view) {
if (!explicit_mouse_handler_ && mouse_pressed_handler_ == details.child)
mouse_pressed_handler_ = nullptr;
if (mouse_move_handler_ == details.child)
mouse_move_handler_ = nullptr;
if (gesture_handler_ == details.child)
gesture_handler_ = nullptr;
if (event_dispatch_target_ == details.child)
event_dispatch_target_ = nullptr;
if (old_dispatch_target_ == details.child)
old_dispatch_target_ = nullptr;
}
}
void RootView::VisibilityChanged(View* /*starting_from*/, bool is_visible) {
if (!is_visible) {
// When the root view is being hidden (e.g. when widget is minimized)
// handlers are reset, so that after it is reshown, events are not captured
// by old handlers.
ResetEventHandlers();
}
}
void RootView::OnDidSchedulePaint(const gfx::Rect& rect) {
if (!layer()) {
gfx::Rect xrect = ConvertRectToParent(rect);
gfx::Rect invalid_rect = gfx::IntersectRects(GetLocalBounds(), xrect);
if (!invalid_rect.IsEmpty())
widget_->SchedulePaintInRect(invalid_rect);
}
}
void RootView::OnPaint(gfx::Canvas* canvas) {
if (!layer() || !layer()->fills_bounds_opaquely())
canvas->DrawColor(SK_ColorTRANSPARENT, SkBlendMode::kClear);
View::OnPaint(canvas);
}
View::LayerOffsetData RootView::CalculateOffsetToAncestorWithLayer(
ui::Layer** layer_parent) {
if (layer() || !widget_->GetLayer())
return View::CalculateOffsetToAncestorWithLayer(layer_parent);
if (layer_parent)
*layer_parent = widget_->GetLayer();
return LayerOffsetData(widget_->GetLayer()->device_scale_factor());
}
View::DragInfo* RootView::GetDragInfo() {
return &drag_info_;
}
////////////////////////////////////////////////////////////////////////////////
// RootView, private:
void RootView::UpdateCursor(const ui::MouseEvent& event) {
if (!(event.flags() & ui::EF_IS_NON_CLIENT)) {
View* v = GetEventHandlerForPoint(event.location());
ui::MouseEvent me(event, static_cast<View*>(this), v);
widget_->SetCursor(v->GetCursor(me));
}
}
void RootView::SetMouseLocationAndFlags(const ui::MouseEvent& event) {
last_mouse_event_flags_ = event.flags();
last_mouse_event_x_ = event.x();
last_mouse_event_y_ = event.y();
}
ui::EventDispatchDetails RootView::NotifyEnterExitOfDescendant(
const ui::MouseEvent& event,
ui::EventType type,
View* view,
View* sibling) {
for (View* p = view->parent(); p; p = p->parent()) {
if (!p->GetNotifyEnterExitOnChild())
continue;
if (sibling && p->Contains(sibling))
break;
// It is necessary to recreate the notify-event for each dispatch, since one
// of the callbacks can mark the event as handled, and that would cause
// incorrect event dispatch.
MouseEnterExitEvent notify_event(event, type);
ui::EventDispatchDetails dispatch_details = DispatchEvent(p, ¬ify_event);
if (dispatch_details.dispatcher_destroyed ||
dispatch_details.target_destroyed) {
return dispatch_details;
}
}
return ui::EventDispatchDetails();
}
bool RootView::CanDispatchToTarget(ui::EventTarget* target) {
return event_dispatch_target_ == target;
}
ui::EventDispatchDetails RootView::PreDispatchEvent(ui::EventTarget* target,
ui::Event* event) {
View* view = static_cast<View*>(target);
if (event->IsGestureEvent()) {
// Update |gesture_handler_| to indicate which View is currently handling
// gesture events.
// TODO(tdanderson): Look into moving this to PostDispatchEvent() and
// using |event_dispatch_target_| instead of
// |gesture_handler_| to detect if the view has been
// removed from the tree.
gesture_handler_ = view;
}
old_dispatch_target_ = event_dispatch_target_;
event_dispatch_target_ = view;
return DispatchDetails();
}
ui::EventDispatchDetails RootView::PostDispatchEvent(ui::EventTarget* target,
const ui::Event& event) {
// The GESTURE_END event corresponding to the removal of the final touch
// point marks the end of a gesture sequence, so reset |gesture_handler_|
// to NULL.
if (event.type() == ui::ET_GESTURE_END) {
// In case a drag was in progress, reset all the handlers. Otherwise, just
// reset the gesture handler.
if (gesture_handler_ && gesture_handler_ == mouse_pressed_handler_)
SetMouseAndGestureHandler(nullptr);
else
gesture_handler_ = nullptr;
}
DispatchDetails details;
if (target != event_dispatch_target_)
details.target_destroyed = true;
event_dispatch_target_ = old_dispatch_target_;
old_dispatch_target_ = nullptr;
#ifndef NDEBUG
DCHECK(!event_dispatch_target_ || Contains(event_dispatch_target_));
#endif
return details;
}
BEGIN_METADATA(RootView, View)
END_METADATA
} // namespace views::internal
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/root_view.cc | C++ | unknown | 33,117 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_WIDGET_ROOT_VIEW_H_
#define UI_VIEWS_WIDGET_ROOT_VIEW_H_
#include <memory>
#include <string>
#include "base/memory/raw_ptr.h"
#include "ui/events/event_processor.h"
#include "ui/views/focus/focus_manager.h"
#include "ui/views/focus/focus_search.h"
#include "ui/views/view.h"
#include "ui/views/view_targeter_delegate.h"
namespace views {
namespace test {
class ViewTargeterTest;
class WidgetTest;
} // namespace test
class RootViewTargeter;
class Widget;
// This is a views-internal API and should not be used externally.
// Widget exposes this object as a View*.
namespace internal {
class AnnounceTextView;
class PreEventDispatchHandler;
////////////////////////////////////////////////////////////////////////////////
// RootView class
//
// The RootView is the root of a View hierarchy. A RootView is attached to a
// Widget. The Widget is responsible for receiving events from the host
// environment, converting them to views-compatible events and then forwarding
// them to the RootView for propagation into the View hierarchy.
//
// A RootView can have only one child, called its "Contents View" which is
// sized to fill the bounds of the RootView (and hence the client area of the
// Widget). Call SetContentsView() after the associated Widget has been
// initialized to attach the contents view to the RootView.
// TODO(beng): Enforce no other callers to AddChildView/tree functions by
// overriding those methods as private here.
// TODO(beng): Clean up API further, make Widget a friend.
// TODO(sky): We don't really want to export this class.
//
class VIEWS_EXPORT RootView : public View,
public ViewTargeterDelegate,
public FocusTraversable,
public ui::EventProcessor {
public:
METADATA_HEADER(RootView);
// Creation and lifetime -----------------------------------------------------
explicit RootView(Widget* widget);
RootView(const RootView&) = delete;
RootView& operator=(const RootView&) = delete;
~RootView() override;
// Tree operations -----------------------------------------------------------
// Sets the "contents view" of the RootView. This is the single child view
// that is responsible for laying out the contents of the widget.
void SetContentsView(View* contents_view);
View* GetContentsView();
// Called when parent of the host changed.
void NotifyNativeViewHierarchyChanged();
// Focus ---------------------------------------------------------------------
// Used to set the FocusTraversable parent after the view has been created
// (typically when the hierarchy changes and this RootView is added/removed).
virtual void SetFocusTraversableParent(FocusTraversable* focus_traversable);
// Used to set the View parent after the view has been created.
virtual void SetFocusTraversableParentView(View* view);
// System events -------------------------------------------------------------
// Public API for broadcasting theme change notifications to this View
// hierarchy.
void ThemeChanged();
// Used to clear event handlers so events aren't captured by old event
// handlers, e.g., when the widget is minimized.
void ResetEventHandlers();
// Public API for broadcasting device scale factor change notifications to
// this View hierarchy.
void DeviceScaleFactorChanged(float old_device_scale_factor,
float new_device_scale_factor);
// Accessibility -------------------------------------------------------------
// Make an announcement through the screen reader, if present.
void AnnounceText(const std::u16string& text);
View* GetAnnounceViewForTesting();
// FocusTraversable:
FocusSearch* GetFocusSearch() override;
FocusTraversable* GetFocusTraversableParent() override;
View* GetFocusTraversableParentView() override;
// ui::EventProcessor:
ui::EventTarget* GetRootForEvent(ui::Event* event) override;
ui::EventTargeter* GetDefaultEventTargeter() override;
void OnEventProcessingStarted(ui::Event* event) override;
void OnEventProcessingFinished(ui::Event* event) override;
// View:
const Widget* GetWidget() const override;
Widget* GetWidget() override;
bool IsDrawn() const override;
bool OnMousePressed(const ui::MouseEvent& event) override;
bool OnMouseDragged(const ui::MouseEvent& event) override;
void OnMouseReleased(const ui::MouseEvent& event) override;
void OnMouseCaptureLost() override;
void OnMouseMoved(const ui::MouseEvent& event) override;
void OnMouseExited(const ui::MouseEvent& event) override;
bool OnMouseWheel(const ui::MouseWheelEvent& event) override;
void SetMouseAndGestureHandler(View* new_handler) override;
void SetMouseHandler(View* new_mouse_handler) override;
void GetAccessibleNodeData(ui::AXNodeData* node_data) override;
void UpdateParentLayer() override;
const views::View* gesture_handler_for_testing() const {
return gesture_handler_;
}
protected:
// View:
void ViewHierarchyChanged(
const ViewHierarchyChangedDetails& details) override;
void VisibilityChanged(View* starting_from, bool is_visible) override;
void OnDidSchedulePaint(const gfx::Rect& rect) override;
void OnPaint(gfx::Canvas* canvas) override;
View::LayerOffsetData CalculateOffsetToAncestorWithLayer(
ui::Layer** layer_parent) override;
View::DragInfo* GetDragInfo() override;
private:
friend class ::views::RootViewTargeter;
friend class ::views::View;
friend class ::views::Widget;
friend class ::views::test::ViewTargeterTest;
friend class ::views::test::WidgetTest;
// Input ---------------------------------------------------------------------
// Update the cursor given a mouse event. This is called by non mouse_move
// event handlers to honor the cursor desired by views located under the
// cursor during drag operations. The location of the mouse should be in the
// current coordinate system (i.e. any necessary transformation should be
// applied to the point prior to calling this).
void UpdateCursor(const ui::MouseEvent& event);
// Updates the last_mouse_* fields from e. The location of the mouse should be
// in the current coordinate system (i.e. any necessary transformation should
// be applied to the point prior to calling this).
void SetMouseLocationAndFlags(const ui::MouseEvent& event);
// Returns announce_view_, a hidden view used to make announcements to the
// screen reader via an alert or live region update.
AnnounceTextView* GetOrCreateAnnounceView();
// |view| is the view receiving |event|. This function sends the event to all
// the Views up the hierarchy that has |notify_enter_exit_on_child_| flag
// turned on, but does not contain |sibling|.
[[nodiscard]] ui::EventDispatchDetails NotifyEnterExitOfDescendant(
const ui::MouseEvent& event,
ui::EventType type,
View* view,
View* sibling);
// Send synthesized gesture end events to `gesture_handler` before replacement
// if `gesture_handler` is in progress of gesture handling.
void MaybeNotifyGestureHandlerBeforeReplacement();
// ui::EventDispatcherDelegate:
bool CanDispatchToTarget(ui::EventTarget* target) override;
ui::EventDispatchDetails PreDispatchEvent(ui::EventTarget* target,
ui::Event* event) override;
ui::EventDispatchDetails PostDispatchEvent(ui::EventTarget* target,
const ui::Event& event) override;
//////////////////////////////////////////////////////////////////////////////
// Tree operations -----------------------------------------------------------
// The host Widget
raw_ptr<Widget, DanglingUntriaged> widget_;
// Input ---------------------------------------------------------------------
// TODO(tdanderson): Consider moving the input-related members into
// ViewTargeter / RootViewTargeter.
// The view currently handing down - drag - up
raw_ptr<View, DanglingUntriaged> mouse_pressed_handler_ = nullptr;
// The view currently handling enter / exit
raw_ptr<View, DanglingUntriaged> mouse_move_handler_ = nullptr;
// The last view to handle a mouse click, so that we can determine if
// a double-click lands on the same view as its single-click part.
raw_ptr<View, DanglingUntriaged> last_click_handler_ = nullptr;
// true if mouse_pressed_handler_ has been explicitly set
bool explicit_mouse_handler_ = false;
// Last position/flag of a mouse press/drag. Used if capture stops and we need
// to synthesize a release.
int last_mouse_event_flags_ = 0;
int last_mouse_event_x_ = -1;
int last_mouse_event_y_ = -1;
// The View currently handling gesture events.
raw_ptr<View, DanglingUntriaged> gesture_handler_ = nullptr;
// Used to indicate if the |gesture_handler_| member was set prior to the
// processing of the current event (i.e., if |gesture_handler_| was set
// by the dispatch of a previous gesture event).
// TODO(tdanderson): It may be possible to eliminate the need for this
// member if |event_dispatch_target_| can be used in
// its place.
bool gesture_handler_set_before_processing_ = false;
std::unique_ptr<internal::PreEventDispatchHandler> pre_dispatch_handler_;
std::unique_ptr<internal::PostEventDispatchHandler> post_dispatch_handler_;
// Focus ---------------------------------------------------------------------
// The focus search algorithm.
FocusSearch focus_search_{this, false, false};
// Whether this root view belongs to the current active window.
// bool activated_;
// The parent FocusTraversable, used for focus traversal.
raw_ptr<FocusTraversable, DanglingUntriaged> focus_traversable_parent_ =
nullptr;
// The View that contains this RootView. This is used when we have RootView
// wrapped inside native components, and is used for the focus traversal.
raw_ptr<View, DanglingUntriaged> focus_traversable_parent_view_ = nullptr;
raw_ptr<View, DanglingUntriaged> event_dispatch_target_ = nullptr;
raw_ptr<View, DanglingUntriaged> old_dispatch_target_ = nullptr;
// Drag and drop -------------------------------------------------------------
// Tracks drag state for a view.
View::DragInfo drag_info_;
// Accessibility -------------------------------------------------------------
// Hidden view used to make announcements to the screen reader via an alert or
// live region update.
raw_ptr<AnnounceTextView, DanglingUntriaged> announce_view_ = nullptr;
};
} // namespace internal
} // namespace views
#endif // UI_VIEWS_WIDGET_ROOT_VIEW_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/root_view.h | C++ | unknown | 10,874 |
// 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/widget/root_view_targeter.h"
#include "ui/views/view.h"
#include "ui/views/view_targeter_delegate.h"
#include "ui/views/views_switches.h"
#include "ui/views/widget/root_view.h"
#include "ui/views/widget/widget.h"
namespace views {
RootViewTargeter::RootViewTargeter(ViewTargeterDelegate* delegate,
internal::RootView* root_view)
: ViewTargeter(delegate), root_view_(root_view) {}
RootViewTargeter::~RootViewTargeter() = default;
View* RootViewTargeter::FindTargetForGestureEvent(
View* root,
const ui::GestureEvent& gesture) {
CHECK_EQ(root, root_view_);
// Return the default gesture handler if one is already set.
if (root_view_->gesture_handler_) {
CHECK(root_view_->gesture_handler_set_before_processing_);
return root_view_->gesture_handler_;
}
// If non-empty, use the gesture's bounding box to determine the target.
// Otherwise use the center point of the gesture's bounding box.
gfx::Rect rect(gesture.location(), gfx::Size(1, 1));
if (!gesture.details().bounding_box().IsEmpty()) {
// TODO(tdanderson): Pass in the bounding box to GetEventHandlerForRect()
// once crbug.com/313392 is resolved.
rect.set_size(gesture.details().bounding_box().size());
rect.Offset(-rect.width() / 2, -rect.height() / 2);
}
return root->GetEffectiveViewTargeter()->TargetForRect(root, rect);
}
ui::EventTarget* RootViewTargeter::FindNextBestTargetForGestureEvent(
ui::EventTarget* previous_target,
const ui::GestureEvent& gesture) {
// ET_GESTURE_END events should only ever be targeted to the default
// gesture handler set by a previous gesture, if one exists. Thus we do not
// permit any re-targeting of ET_GESTURE_END events.
if (gesture.type() == ui::ET_GESTURE_END)
return nullptr;
// Prohibit re-targeting of gesture events (except for GESTURE_SCROLL_BEGIN
// events) if the default gesture handler was set by the dispatch of a
// previous gesture event.
if (root_view_->gesture_handler_set_before_processing_ &&
gesture.type() != ui::ET_GESTURE_SCROLL_BEGIN) {
return nullptr;
}
// If |gesture_handler_| is NULL, it is either because the view was removed
// from the tree by the previous dispatch of |gesture| or because |gesture| is
// the GESTURE_END event corresponding to the removal of the last touch
// point. In either case, no further re-targeting of |gesture| should be
// permitted.
if (!root_view_->gesture_handler_)
return nullptr;
return previous_target->GetParentTarget();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/root_view_targeter.cc | C++ | unknown | 2,735 |
// 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_WIDGET_ROOT_VIEW_TARGETER_H_
#define UI_VIEWS_WIDGET_ROOT_VIEW_TARGETER_H_
#include "base/memory/raw_ptr.h"
#include "ui/views/view_targeter.h"
#include "ui/views/views_export.h"
namespace views {
namespace internal {
class RootView;
} // namespace internal
class View;
class ViewTargeterDelegate;
// A derived class of ViewTargeter that defines targeting logic for cases
// needing to access the members of RootView. For example, when determining the
// target of a gesture event, we need to know if a previous gesture has already
// established the View to which all subsequent gestures should be targeted.
class VIEWS_EXPORT RootViewTargeter : public ViewTargeter {
public:
RootViewTargeter(ViewTargeterDelegate* delegate,
internal::RootView* root_view);
RootViewTargeter(const RootViewTargeter&) = delete;
RootViewTargeter& operator=(const RootViewTargeter&) = delete;
~RootViewTargeter() override;
private:
// ViewTargeter:
View* FindTargetForGestureEvent(View* root,
const ui::GestureEvent& gesture) override;
ui::EventTarget* FindNextBestTargetForGestureEvent(
ui::EventTarget* previous_target,
const ui::GestureEvent& gesture) override;
// A pointer to the RootView on which |this| is installed.
raw_ptr<internal::RootView> root_view_;
};
} // namespace views
#endif // UI_VIEWS_WIDGET_ROOT_VIEW_TARGETER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/root_view_targeter.h | C++ | unknown | 1,576 |
// 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/widget/root_view.h"
#include <memory>
#include <utility>
#include "base/memory/ptr_util.h"
#include "base/memory/raw_ptr.h"
#include "build/build_config.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/events/event_utils.h"
#include "ui/events/keycodes/dom/dom_code.h"
#include "ui/views/context_menu_controller.h"
#include "ui/views/test/test_views.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/test/views_test_utils.h"
#include "ui/views/view_targeter.h"
#include "ui/views/widget/widget_deletion_observer.h"
#include "ui/views/window/dialog_delegate.h"
#if BUILDFLAG(IS_MAC)
#include "base/mac/mac_util.h"
#endif
namespace views::test {
namespace {
struct RootViewTestStateInit {
gfx::Rect bounds;
Widget::InitParams::Type type = Widget::InitParams::TYPE_WINDOW_FRAMELESS;
};
class RootViewTestState {
public:
explicit RootViewTestState(ViewsTestBase* delegate,
RootViewTestStateInit init = {}) {
Widget::InitParams init_params = delegate->CreateParams(init.type);
init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
if (init.bounds != gfx::Rect())
init_params.bounds = init.bounds;
widget_.Init(std::move(init_params));
widget_.Show();
widget_.SetContentsView(std::make_unique<View>());
}
Widget* widget() { return &widget_; }
internal::RootView* GetRootView() {
return static_cast<internal::RootView*>(widget_.GetRootView());
}
template <typename T>
T* AddChildView(std::unique_ptr<T> view) {
return widget_.GetContentsView()->AddChildView(std::move(view));
}
private:
Widget widget_;
};
class DeleteOnKeyEventView : public View {
public:
explicit DeleteOnKeyEventView(bool* set_on_key) : set_on_key_(set_on_key) {}
DeleteOnKeyEventView(const DeleteOnKeyEventView&) = delete;
DeleteOnKeyEventView& operator=(const DeleteOnKeyEventView&) = delete;
~DeleteOnKeyEventView() override = default;
bool OnKeyPressed(const ui::KeyEvent& event) override {
*set_on_key_ = true;
delete this;
return true;
}
private:
// Set to true in OnKeyPressed().
raw_ptr<bool> set_on_key_;
};
} // namespace
using RootViewTest = ViewsTestBase;
// Verifies deleting a View in OnKeyPressed() doesn't crash and that the
// target is marked as destroyed in the returned EventDispatchDetails.
TEST_F(RootViewTest, DeleteViewDuringKeyEventDispatch) {
RootViewTestState state(this);
internal::RootView* root_view = state.GetRootView();
bool got_key_event = false;
View* child = state.AddChildView(
std::make_unique<DeleteOnKeyEventView>(&got_key_event));
// Give focus to |child| so that it will be the target of the key event.
child->SetFocusBehavior(View::FocusBehavior::ALWAYS);
child->RequestFocus();
ViewTargeter* view_targeter = new ViewTargeter(root_view);
root_view->SetEventTargeter(base::WrapUnique(view_targeter));
ui::KeyEvent key_event(ui::ET_KEY_PRESSED, ui::VKEY_ESCAPE, ui::EF_NONE);
ui::EventDispatchDetails details = root_view->OnEventFromSource(&key_event);
EXPECT_TRUE(details.target_destroyed);
EXPECT_FALSE(details.dispatcher_destroyed);
EXPECT_TRUE(got_key_event);
}
// Tracks whether a context menu is shown.
class TestContextMenuController : public ContextMenuController {
public:
TestContextMenuController() = default;
TestContextMenuController(const TestContextMenuController&) = delete;
TestContextMenuController& operator=(const TestContextMenuController&) =
delete;
~TestContextMenuController() override = default;
int show_context_menu_calls() const { return show_context_menu_calls_; }
View* menu_source_view() const { return menu_source_view_; }
ui::MenuSourceType menu_source_type() const { return menu_source_type_; }
void Reset() {
show_context_menu_calls_ = 0;
menu_source_view_ = nullptr;
menu_source_type_ = ui::MENU_SOURCE_NONE;
}
// ContextMenuController:
void ShowContextMenuForViewImpl(View* source,
const gfx::Point& point,
ui::MenuSourceType source_type) override {
show_context_menu_calls_++;
menu_source_view_ = source;
menu_source_type_ = source_type;
}
private:
int show_context_menu_calls_ = 0;
raw_ptr<View> menu_source_view_ = nullptr;
ui::MenuSourceType menu_source_type_ = ui::MENU_SOURCE_NONE;
};
// Tests that context menus are shown for certain key events (Shift+F10
// and VKEY_APPS) by the pre-target handler installed on RootView.
TEST_F(RootViewTest, ContextMenuFromKeyEvent) {
// This behavior is intentionally unsupported on macOS.
#if !BUILDFLAG(IS_MAC)
RootViewTestState state(this);
internal::RootView* root_view = state.GetRootView();
TestContextMenuController controller;
View* focused_view = root_view->GetContentsView();
focused_view->set_context_menu_controller(&controller);
focused_view->SetFocusBehavior(View::FocusBehavior::ALWAYS);
focused_view->RequestFocus();
// No context menu should be shown for a keypress of 'A'.
ui::KeyEvent nomenu_key_event('a', ui::VKEY_A, ui::DomCode::NONE,
ui::EF_NONE);
ui::EventDispatchDetails details =
root_view->OnEventFromSource(&nomenu_key_event);
EXPECT_FALSE(details.target_destroyed);
EXPECT_FALSE(details.dispatcher_destroyed);
EXPECT_EQ(0, controller.show_context_menu_calls());
EXPECT_EQ(nullptr, controller.menu_source_view());
EXPECT_EQ(ui::MENU_SOURCE_NONE, controller.menu_source_type());
controller.Reset();
// A context menu should be shown for a keypress of Shift+F10.
ui::KeyEvent menu_key_event(ui::ET_KEY_PRESSED, ui::VKEY_F10,
ui::EF_SHIFT_DOWN);
details = root_view->OnEventFromSource(&menu_key_event);
EXPECT_FALSE(details.target_destroyed);
EXPECT_FALSE(details.dispatcher_destroyed);
EXPECT_EQ(1, controller.show_context_menu_calls());
EXPECT_EQ(focused_view, controller.menu_source_view());
EXPECT_EQ(ui::MENU_SOURCE_KEYBOARD, controller.menu_source_type());
controller.Reset();
// A context menu should be shown for a keypress of VKEY_APPS.
ui::KeyEvent menu_key_event2(ui::ET_KEY_PRESSED, ui::VKEY_APPS, ui::EF_NONE);
details = root_view->OnEventFromSource(&menu_key_event2);
EXPECT_FALSE(details.target_destroyed);
EXPECT_FALSE(details.dispatcher_destroyed);
EXPECT_EQ(1, controller.show_context_menu_calls());
EXPECT_EQ(focused_view, controller.menu_source_view());
EXPECT_EQ(ui::MENU_SOURCE_KEYBOARD, controller.menu_source_type());
controller.Reset();
#endif
}
// View which handles all gesture events.
class GestureHandlingView : public View {
public:
GestureHandlingView() = default;
GestureHandlingView(const GestureHandlingView&) = delete;
GestureHandlingView& operator=(const GestureHandlingView&) = delete;
~GestureHandlingView() override = default;
void OnGestureEvent(ui::GestureEvent* event) override { event->SetHandled(); }
};
// View which handles all mouse events.
class MouseHandlingView : public View {
public:
MouseHandlingView() = default;
MouseHandlingView(const MouseHandlingView&) = delete;
MouseHandlingView& operator=(const MouseHandlingView&) = delete;
~MouseHandlingView() override = default;
// View:
void OnMouseEvent(ui::MouseEvent* event) override { event->SetHandled(); }
};
TEST_F(RootViewTest, EventHandlersResetWhenDeleted) {
RootViewTestState state(this, {.bounds = {100, 100}});
internal::RootView* root_view = state.GetRootView();
// Set up a child view to handle events.
View* event_handler = state.AddChildView(std::make_unique<View>());
root_view->SetMouseAndGestureHandler(event_handler);
ASSERT_EQ(event_handler, root_view->gesture_handler_for_testing());
// Delete the child and expect that there is no longer a mouse handler.
root_view->GetContentsView()->RemoveChildViewT(event_handler);
EXPECT_EQ(nullptr, root_view->gesture_handler_for_testing());
}
TEST_F(RootViewTest, EventHandlersNotResetWhenReparented) {
RootViewTestState state(this, {.bounds = {100, 100}});
internal::RootView* root_view = state.GetRootView();
// Set up a child view to handle events
View* event_handler = state.AddChildView(std::make_unique<View>());
root_view->SetMouseAndGestureHandler(event_handler);
ASSERT_EQ(event_handler, root_view->gesture_handler_for_testing());
// Reparent the child within the hierarchy and expect that it's still the
// mouse handler.
View* other_parent = state.AddChildView(std::make_unique<View>());
other_parent->AddChildView(event_handler);
EXPECT_EQ(event_handler, root_view->gesture_handler_for_testing());
}
// Verifies that the gesture handler stored in the root view is reset after
// mouse is released. Note that during mouse event handling,
// `RootView::SetMouseAndGestureHandler()` may be called to set the gesture
// handler. Therefore we should reset the gesture handler when mouse is
// released. We may remove this test in the future if the implementation of the
// product code changes.
TEST_F(RootViewTest, GestureHandlerResetAfterMouseReleased) {
RootViewTestState state(this, {.bounds = {100, 100}});
internal::RootView* root_view = state.GetRootView();
// Create a child view to handle gestures.
View* gesture_handler =
state.AddChildView(std::make_unique<GestureHandlingView>());
gesture_handler->SetBoundsRect(gfx::Rect(gfx::Size{50, 50}));
// Create a child view to handle mouse events.
View* mouse_handler =
state.AddChildView(std::make_unique<MouseHandlingView>());
mouse_handler->SetBoundsRect(
gfx::Rect(gesture_handler->bounds().bottom_right(), gfx::Size{50, 50}));
// Emulate to start gesture scroll on `child_view`.
const gfx::Point gesture_handler_center_point =
gesture_handler->GetBoundsInScreen().CenterPoint();
ui::GestureEvent scroll_begin(
gesture_handler_center_point.x(), gesture_handler_center_point.y(),
ui::EF_NONE, base::TimeTicks(),
ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_BEGIN));
root_view->OnEventFromSource(&scroll_begin);
ui::GestureEvent scroll_update(
gesture_handler_center_point.x(), gesture_handler_center_point.y(),
ui::EF_NONE, base::TimeTicks(),
ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_UPDATE, /*delta_x=*/20,
/*delta_y=*/10));
root_view->OnEventFromSource(&scroll_update);
// Emulate the mouse click on `mouse_handler` before gesture scroll ends.
const gfx::Point mouse_handler_center_point =
mouse_handler->GetBoundsInScreen().CenterPoint();
ui::MouseEvent pressed_event(ui::ET_MOUSE_PRESSED, mouse_handler_center_point,
mouse_handler_center_point,
ui::EventTimeForNow(), ui::EF_NONE,
/*changed_button_flags=*/0);
ui::MouseEvent released_event(
ui::ET_MOUSE_RELEASED, mouse_handler_center_point,
mouse_handler_center_point, ui::EventTimeForNow(), ui::EF_NONE,
/*changed_button_flags=*/0);
root_view->OnMousePressed(pressed_event);
root_view->OnMouseReleased(released_event);
// Check that the gesture handler is reset.
EXPECT_EQ(nullptr, root_view->gesture_handler_for_testing());
}
// Tests that context menus are shown for long press by the post-target handler
// installed on the RootView only if the event is targetted at a view which can
// show a context menu.
TEST_F(RootViewTest, ContextMenuFromLongPress) {
RootViewTestState state(
this, {.bounds = {100, 100}, .type = Widget::InitParams::TYPE_POPUP});
internal::RootView* root_view = state.GetRootView();
View* parent_view = root_view->GetContentsView();
// Create a view capable of showing the context menu with two children one of
// which handles all gesture events (e.g. a button).
TestContextMenuController controller;
parent_view->set_context_menu_controller(&controller);
View* gesture_handling_child_view = new GestureHandlingView;
gesture_handling_child_view->SetBoundsRect(gfx::Rect(10, 10));
parent_view->AddChildView(gesture_handling_child_view);
View* other_child_view = new View;
other_child_view->SetBoundsRect(gfx::Rect(20, 0, 10, 10));
parent_view->AddChildView(other_child_view);
// |parent_view| should not show a context menu as a result of a long press on
// |gesture_handling_child_view|.
ui::GestureEvent long_press1(
5, 5, 0, base::TimeTicks(),
ui::GestureEventDetails(ui::ET_GESTURE_LONG_PRESS));
ui::EventDispatchDetails details = root_view->OnEventFromSource(&long_press1);
ui::GestureEvent end1(5, 5, 0, base::TimeTicks(),
ui::GestureEventDetails(ui::ET_GESTURE_END));
details = root_view->OnEventFromSource(&end1);
EXPECT_FALSE(details.target_destroyed);
EXPECT_FALSE(details.dispatcher_destroyed);
EXPECT_EQ(0, controller.show_context_menu_calls());
controller.Reset();
// |parent_view| should show a context menu as a result of a long press on
// |other_child_view|.
ui::GestureEvent long_press2(
25, 5, 0, base::TimeTicks(),
ui::GestureEventDetails(ui::ET_GESTURE_LONG_PRESS));
details = root_view->OnEventFromSource(&long_press2);
ui::GestureEvent end2(25, 5, 0, base::TimeTicks(),
ui::GestureEventDetails(ui::ET_GESTURE_END));
details = root_view->OnEventFromSource(&end2);
EXPECT_FALSE(details.target_destroyed);
EXPECT_FALSE(details.dispatcher_destroyed);
EXPECT_EQ(1, controller.show_context_menu_calls());
controller.Reset();
// |parent_view| should show a context menu as a result of a long press on
// itself.
ui::GestureEvent long_press3(
50, 50, 0, base::TimeTicks(),
ui::GestureEventDetails(ui::ET_GESTURE_LONG_PRESS));
details = root_view->OnEventFromSource(&long_press3);
ui::GestureEvent end3(25, 5, 0, base::TimeTicks(),
ui::GestureEventDetails(ui::ET_GESTURE_END));
details = root_view->OnEventFromSource(&end3);
EXPECT_FALSE(details.target_destroyed);
EXPECT_FALSE(details.dispatcher_destroyed);
EXPECT_EQ(1, controller.show_context_menu_calls());
}
// Tests that context menus are not shown for disabled views on a long press.
TEST_F(RootViewTest, ContextMenuFromLongPressOnDisabledView) {
RootViewTestState state(
this, {.bounds = {100, 100}, .type = Widget::InitParams::TYPE_POPUP});
internal::RootView* root_view = state.GetRootView();
View* parent_view = root_view->GetContentsView();
// Create a view capable of showing the context menu with two children one of
// which handles all gesture events (e.g. a button). Also mark this view
// as disabled.
TestContextMenuController controller;
parent_view->set_context_menu_controller(&controller);
parent_view->SetEnabled(false);
View* gesture_handling_child_view = new GestureHandlingView;
gesture_handling_child_view->SetBoundsRect(gfx::Rect(10, 10));
parent_view->AddChildView(gesture_handling_child_view);
View* other_child_view = new View;
other_child_view->SetBoundsRect(gfx::Rect(20, 0, 10, 10));
parent_view->AddChildView(other_child_view);
// |parent_view| should not show a context menu as a result of a long press on
// |gesture_handling_child_view|.
ui::GestureEvent long_press1(
5, 5, 0, base::TimeTicks(),
ui::GestureEventDetails(ui::ET_GESTURE_LONG_PRESS));
ui::EventDispatchDetails details = root_view->OnEventFromSource(&long_press1);
ui::GestureEvent end1(5, 5, 0, base::TimeTicks(),
ui::GestureEventDetails(ui::ET_GESTURE_END));
details = root_view->OnEventFromSource(&end1);
EXPECT_FALSE(details.target_destroyed);
EXPECT_FALSE(details.dispatcher_destroyed);
EXPECT_EQ(0, controller.show_context_menu_calls());
controller.Reset();
// |parent_view| should not show a context menu as a result of a long press on
// |other_child_view|.
ui::GestureEvent long_press2(
25, 5, 0, base::TimeTicks(),
ui::GestureEventDetails(ui::ET_GESTURE_LONG_PRESS));
details = root_view->OnEventFromSource(&long_press2);
ui::GestureEvent end2(25, 5, 0, base::TimeTicks(),
ui::GestureEventDetails(ui::ET_GESTURE_END));
details = root_view->OnEventFromSource(&end2);
EXPECT_FALSE(details.target_destroyed);
EXPECT_FALSE(details.dispatcher_destroyed);
EXPECT_EQ(0, controller.show_context_menu_calls());
controller.Reset();
// |parent_view| should not show a context menu as a result of a long press on
// itself.
ui::GestureEvent long_press3(
50, 50, 0, base::TimeTicks(),
ui::GestureEventDetails(ui::ET_GESTURE_LONG_PRESS));
details = root_view->OnEventFromSource(&long_press3);
ui::GestureEvent end3(25, 5, 0, base::TimeTicks(),
ui::GestureEventDetails(ui::ET_GESTURE_END));
details = root_view->OnEventFromSource(&end3);
EXPECT_FALSE(details.target_destroyed);
EXPECT_FALSE(details.dispatcher_destroyed);
EXPECT_EQ(0, controller.show_context_menu_calls());
}
namespace {
// View class which destroys itself when it gets an event of type
// |delete_event_type|.
class DeleteViewOnEvent : public View {
public:
DeleteViewOnEvent(ui::EventType delete_event_type, bool* was_destroyed)
: delete_event_type_(delete_event_type), was_destroyed_(was_destroyed) {}
DeleteViewOnEvent(const DeleteViewOnEvent&) = delete;
DeleteViewOnEvent& operator=(const DeleteViewOnEvent&) = delete;
~DeleteViewOnEvent() override { *was_destroyed_ = true; }
void OnEvent(ui::Event* event) override {
if (event->type() == delete_event_type_)
delete this;
}
private:
// The event type which causes the view to destroy itself.
ui::EventType delete_event_type_;
// Tracks whether the view was destroyed.
raw_ptr<bool> was_destroyed_;
};
// View class which remove itself when it gets an event of type
// |remove_event_type|.
class RemoveViewOnEvent : public View {
public:
explicit RemoveViewOnEvent(ui::EventType remove_event_type)
: remove_event_type_(remove_event_type) {}
RemoveViewOnEvent(const RemoveViewOnEvent&) = delete;
RemoveViewOnEvent& operator=(const RemoveViewOnEvent&) = delete;
void OnEvent(ui::Event* event) override {
if (event->type() == remove_event_type_)
parent()->RemoveChildView(this);
}
private:
// The event type which causes the view to remove itself.
ui::EventType remove_event_type_;
};
// View class which generates a nested event the first time it gets an event of
// type |nested_event_type|. This is used to simulate nested event loops which
// can cause |RootView::mouse_event_handler_| to get reset.
class NestedEventOnEvent : public View {
public:
NestedEventOnEvent(ui::EventType nested_event_type, View* root_view)
: nested_event_type_(nested_event_type), root_view_(root_view) {}
NestedEventOnEvent(const NestedEventOnEvent&) = delete;
NestedEventOnEvent& operator=(const NestedEventOnEvent&) = delete;
void OnEvent(ui::Event* event) override {
if (event->type() == nested_event_type_) {
ui::MouseEvent exit_event(ui::ET_MOUSE_EXITED, gfx::Point(), gfx::Point(),
ui::EventTimeForNow(), ui::EF_NONE,
ui::EF_NONE);
// Avoid infinite recursion if |nested_event_type_| == ET_MOUSE_EXITED.
nested_event_type_ = ui::ET_UNKNOWN;
root_view_->OnMouseExited(exit_event);
}
}
private:
// The event type which causes the view to generate a nested event.
ui::EventType nested_event_type_;
// root view of this view; owned by widget.
raw_ptr<View> root_view_;
};
} // namespace
// Verifies deleting a View in OnMouseExited() doesn't crash.
TEST_F(RootViewTest, DeleteViewOnMouseExitDispatch) {
RootViewTestState state(this, {.bounds = {10, 10, 500, 500},
.type = Widget::InitParams::TYPE_POPUP});
internal::RootView* root_view = state.GetRootView();
bool view_destroyed = false;
View* child = state.AddChildView(std::make_unique<DeleteViewOnEvent>(
ui::ET_MOUSE_EXITED, &view_destroyed));
child->SetBounds(10, 10, 500, 500);
// Generate a mouse move event which ensures that |mouse_moved_handler_|
// is set in the RootView class.
ui::MouseEvent moved_event(ui::ET_MOUSE_MOVED, gfx::Point(15, 15),
gfx::Point(15, 15), ui::EventTimeForNow(), 0, 0);
root_view->OnMouseMoved(moved_event);
ASSERT_FALSE(view_destroyed);
// Generate a mouse exit event which in turn will delete the child view which
// was the target of the mouse move event above. This should not crash when
// the mouse exit handler returns from the child.
ui::MouseEvent exit_event(ui::ET_MOUSE_EXITED, gfx::Point(), gfx::Point(),
ui::EventTimeForNow(), 0, 0);
root_view->OnMouseExited(exit_event);
EXPECT_TRUE(view_destroyed);
EXPECT_TRUE(root_view->GetContentsView()->children().empty());
}
// Verifies deleting a View in OnMouseEntered() doesn't crash.
TEST_F(RootViewTest, DeleteViewOnMouseEnterDispatch) {
RootViewTestState state(this, {.bounds = {10, 10, 500, 500},
.type = Widget::InitParams::TYPE_POPUP});
internal::RootView* root_view = state.GetRootView();
bool view_destroyed = false;
View* child = state.AddChildView(std::make_unique<DeleteViewOnEvent>(
ui::ET_MOUSE_ENTERED, &view_destroyed));
// Make |child| smaller than the containing Widget and RootView.
child->SetBounds(100, 100, 100, 100);
// Move the mouse within |widget| but outside of |child|.
ui::MouseEvent moved_event(ui::ET_MOUSE_MOVED, gfx::Point(15, 15),
gfx::Point(15, 15), ui::EventTimeForNow(), 0, 0);
root_view->OnMouseMoved(moved_event);
ASSERT_FALSE(view_destroyed);
// Move the mouse within |child|, which should dispatch a mouse enter event to
// |child| and destroy the view. This should not crash when the mouse enter
// handler returns from the child.
ui::MouseEvent moved_event2(ui::ET_MOUSE_MOVED, gfx::Point(115, 115),
gfx::Point(115, 115), ui::EventTimeForNow(), 0,
0);
root_view->OnMouseMoved(moved_event2);
EXPECT_TRUE(view_destroyed);
EXPECT_TRUE(root_view->GetContentsView()->children().empty());
}
// Verifies removing a View in OnMouseEntered() doesn't crash.
TEST_F(RootViewTest, RemoveViewOnMouseEnterDispatch) {
RootViewTestState state(this, {.bounds = {10, 10, 500, 500},
.type = Widget::InitParams::TYPE_POPUP});
internal::RootView* root_view = state.GetRootView();
View* content = root_view->GetContentsView();
// |child| gets removed without being deleted, so make it a local
// to prevent test memory leak.
RemoveViewOnEvent child(ui::ET_MOUSE_ENTERED);
content->AddChildView(&child);
// Make |child| smaller than the containing Widget and RootView.
child.SetBounds(100, 100, 100, 100);
// Move the mouse within |widget| but outside of |child|.
ui::MouseEvent moved_event(ui::ET_MOUSE_MOVED, gfx::Point(15, 15),
gfx::Point(15, 15), ui::EventTimeForNow(), 0, 0);
root_view->OnMouseMoved(moved_event);
// Move the mouse within |child|, which should dispatch a mouse enter event to
// |child| and remove the view. This should not crash when the mouse enter
// handler returns.
ui::MouseEvent moved_event2(ui::ET_MOUSE_MOVED, gfx::Point(115, 115),
gfx::Point(115, 115), ui::EventTimeForNow(), 0,
0);
root_view->OnMouseMoved(moved_event2);
EXPECT_TRUE(content->children().empty());
}
// Verifies clearing the root view's |mouse_move_handler_| in OnMouseExited()
// doesn't crash.
TEST_F(RootViewTest, ClearMouseMoveHandlerOnMouseExitDispatch) {
RootViewTestState state(this, {.bounds = {10, 10, 500, 500},
.type = Widget::InitParams::TYPE_POPUP});
internal::RootView* root_view = state.GetRootView();
View* child = state.AddChildView(
std::make_unique<NestedEventOnEvent>(ui::ET_MOUSE_EXITED, root_view));
// Make |child| smaller than the containing Widget and RootView.
child->SetBounds(100, 100, 100, 100);
// Generate a mouse move event which ensures that |mouse_moved_handler_|
// is set to the child view in the RootView class.
ui::MouseEvent moved_event(ui::ET_MOUSE_MOVED, gfx::Point(110, 110),
gfx::Point(110, 110), ui::EventTimeForNow(), 0, 0);
root_view->OnMouseMoved(moved_event);
// Move the mouse outside of |child| which causes a mouse exit event to be
// dispatched to |child|, which will in turn generate a nested event that
// clears |mouse_move_handler_|. This should not crash
// RootView::OnMouseMoved.
ui::MouseEvent move_event2(ui::ET_MOUSE_MOVED, gfx::Point(15, 15),
gfx::Point(15, 15), ui::EventTimeForNow(), 0, 0);
root_view->OnMouseMoved(move_event2);
}
// Verifies clearing the root view's |mouse_move_handler_| in OnMouseExited()
// doesn't crash, in the case where the root view is targeted, because
// it's the first enabled view encountered walking up the target tree.
TEST_F(RootViewTest,
ClearMouseMoveHandlerOnMouseExitDispatchWithContentViewDisabled) {
RootViewTestState state(this, {.bounds = {10, 10, 500, 500},
.type = Widget::InitParams::TYPE_POPUP});
internal::RootView* root_view = state.GetRootView();
View* child = state.AddChildView(
std::make_unique<NestedEventOnEvent>(ui::ET_MOUSE_EXITED, root_view));
// Make |child| smaller than the containing Widget and RootView.
child->SetBounds(100, 100, 100, 100);
// Generate a mouse move event which ensures that the |mouse_moved_handler_|
// member is set to the child view in the RootView class.
ui::MouseEvent moved_event(ui::ET_MOUSE_MOVED, gfx::Point(110, 110),
gfx::Point(110, 110), ui::EventTimeForNow(), 0, 0);
root_view->OnMouseMoved(moved_event);
// This will make RootView::OnMouseMoved skip the content view when looking
// for a handler for the mouse event, and instead use the root view.
root_view->GetContentsView()->SetEnabled(false);
// Move the mouse outside of |child| which should dispatch a mouse exit event
// to |mouse_move_handler_| (currently |child|), which will in turn generate a
// nested event that clears |mouse_move_handler_|. This should not crash
// RootView::OnMouseMoved.
ui::MouseEvent move_event2(ui::ET_MOUSE_MOVED, gfx::Point(200, 200),
gfx::Point(200, 200), ui::EventTimeForNow(), 0, 0);
root_view->OnMouseMoved(move_event2);
}
// Verifies clearing the root view's |mouse_move_handler_| in OnMouseEntered()
// doesn't crash.
TEST_F(RootViewTest, ClearMouseMoveHandlerOnMouseEnterDispatch) {
RootViewTestState state(this, {.bounds = {10, 10, 500, 500},
.type = Widget::InitParams::TYPE_POPUP});
internal::RootView* root_view = state.GetRootView();
View* child = state.AddChildView(
std::make_unique<NestedEventOnEvent>(ui::ET_MOUSE_ENTERED, root_view));
// Make |child| smaller than the containing Widget and RootView.
child->SetBounds(100, 100, 100, 100);
// Move the mouse within |widget| but outside of |child|.
ui::MouseEvent moved_event(ui::ET_MOUSE_MOVED, gfx::Point(15, 15),
gfx::Point(15, 15), ui::EventTimeForNow(), 0, 0);
root_view->OnMouseMoved(moved_event);
// Move the mouse within |child|, which dispatches a mouse enter event to
// |child| and resets the root view's |mouse_move_handler_|. This should not
// crash when the mouse enter handler generates an ET_MOUSE_ENTERED event.
ui::MouseEvent moved_event2(ui::ET_MOUSE_MOVED, gfx::Point(115, 115),
gfx::Point(115, 115), ui::EventTimeForNow(), 0,
0);
root_view->OnMouseMoved(moved_event2);
}
namespace {
// View class which deletes its owning Widget when it gets a mouse exit event.
class DeleteWidgetOnMouseExit : public View {
public:
explicit DeleteWidgetOnMouseExit(Widget* widget) : widget_(widget) {}
DeleteWidgetOnMouseExit(const DeleteWidgetOnMouseExit&) = delete;
DeleteWidgetOnMouseExit& operator=(const DeleteWidgetOnMouseExit&) = delete;
~DeleteWidgetOnMouseExit() override = default;
void OnMouseExited(const ui::MouseEvent& event) override { delete widget_; }
private:
raw_ptr<Widget> widget_;
};
} // namespace
// Test that there is no crash if a View deletes its parent Widget in
// View::OnMouseExited().
TEST_F(RootViewTest, DeleteWidgetOnMouseExitDispatch) {
Widget* widget = new Widget;
Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP);
init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget->Init(std::move(init_params));
widget->SetBounds(gfx::Rect(10, 10, 500, 500));
WidgetDeletionObserver widget_deletion_observer(widget);
auto content = std::make_unique<View>();
View* child = new DeleteWidgetOnMouseExit(widget);
content->AddChildView(child);
widget->SetContentsView(std::move(content));
// Make |child| smaller than the containing Widget and RootView.
child->SetBounds(100, 100, 100, 100);
internal::RootView* root_view =
static_cast<internal::RootView*>(widget->GetRootView());
// Move the mouse within |child|.
ui::MouseEvent moved_event(ui::ET_MOUSE_MOVED, gfx::Point(115, 115),
gfx::Point(115, 115), ui::EventTimeForNow(), 0, 0);
root_view->OnMouseMoved(moved_event);
ASSERT_TRUE(widget_deletion_observer.IsWidgetAlive());
// Move the mouse outside of |child| which should dispatch a mouse exit event
// to |child| and destroy the widget. This should not crash when the mouse
// exit handler returns from the child.
ui::MouseEvent move_event2(ui::ET_MOUSE_MOVED, gfx::Point(15, 15),
gfx::Point(15, 15), ui::EventTimeForNow(), 0, 0);
root_view->OnMouseMoved(move_event2);
EXPECT_FALSE(widget_deletion_observer.IsWidgetAlive());
}
// Test that there is no crash if a View deletes its parent widget as a result
// of a mouse exited event which was propagated from one of its children.
TEST_F(RootViewTest, DeleteWidgetOnMouseExitDispatchFromChild) {
Widget* widget = new Widget;
Widget::InitParams init_params = CreateParams(Widget::InitParams::TYPE_POPUP);
init_params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget->Init(std::move(init_params));
widget->SetBounds(gfx::Rect(10, 10, 500, 500));
WidgetDeletionObserver widget_deletion_observer(widget);
View* child = new DeleteWidgetOnMouseExit(widget);
View* subchild = new View();
View* content = widget->SetContentsView(std::make_unique<View>());
content->AddChildView(child);
child->AddChildView(subchild);
// Make |child| and |subchild| smaller than the containing Widget and
// RootView.
child->SetBounds(100, 100, 100, 100);
subchild->SetBounds(0, 0, 100, 100);
// Make mouse enter and exit events get propagated from |subchild| to |child|.
child->SetNotifyEnterExitOnChild(true);
internal::RootView* root_view =
static_cast<internal::RootView*>(widget->GetRootView());
// Move the mouse within |subchild| and |child|.
ui::MouseEvent moved_event(ui::ET_MOUSE_MOVED, gfx::Point(115, 115),
gfx::Point(115, 115), ui::EventTimeForNow(), 0, 0);
root_view->OnMouseMoved(moved_event);
ASSERT_TRUE(widget_deletion_observer.IsWidgetAlive());
// Move the mouse outside of |subchild| and |child| which should dispatch a
// mouse exit event to |subchild| and destroy the widget. This should not
// crash when the mouse exit handler returns from |subchild|.
ui::MouseEvent move_event2(ui::ET_MOUSE_MOVED, gfx::Point(15, 15),
gfx::Point(15, 15), ui::EventTimeForNow(), 0, 0);
root_view->OnMouseMoved(move_event2);
EXPECT_FALSE(widget_deletion_observer.IsWidgetAlive());
}
namespace {
class RootViewTestDialogDelegate : public DialogDelegateView {
public:
RootViewTestDialogDelegate() {
// Ensure that buttons don't influence the layout.
DialogDelegate::SetButtons(ui::DIALOG_BUTTON_NONE);
}
RootViewTestDialogDelegate(const RootViewTestDialogDelegate&) = delete;
RootViewTestDialogDelegate& operator=(const RootViewTestDialogDelegate&) =
delete;
~RootViewTestDialogDelegate() override = default;
int layout_count() const { return layout_count_; }
// DialogDelegateView:
gfx::Size CalculatePreferredSize() const override { return preferred_size_; }
void Layout() override {
EXPECT_EQ(size(), preferred_size_);
++layout_count_;
}
private:
const gfx::Size preferred_size_ = gfx::Size(111, 111);
int layout_count_ = 0;
};
} // namespace
// Ensure only one call to Layout() happens during Widget initialization, and
// ensure it happens at the ContentView's preferred size.
TEST_F(RootViewTest, SingleLayoutDuringInit) {
RootViewTestDialogDelegate* delegate = new RootViewTestDialogDelegate();
Widget* widget =
DialogDelegate::CreateDialogWidget(delegate, GetContext(), nullptr);
EXPECT_EQ(1, delegate->layout_count());
widget->CloseNow();
}
using RootViewDesktopNativeWidgetTest = ViewsTestWithDesktopNativeWidget;
// Also test Aura desktop Widget codepaths.
TEST_F(RootViewDesktopNativeWidgetTest, SingleLayoutDuringInit) {
RootViewTestDialogDelegate* delegate = new RootViewTestDialogDelegate();
Widget* widget =
DialogDelegate::CreateDialogWidget(delegate, GetContext(), nullptr);
EXPECT_EQ(1, delegate->layout_count());
widget->CloseNow();
}
#if !BUILDFLAG(IS_MAC)
// Tests that AnnounceText sets up the correct text value on the hidden view,
// and that the resulting hidden view actually stays hidden.
TEST_F(RootViewTest, AnnounceTextTest) {
RootViewTestState state(this, {.bounds = {100, 100, 100, 100}});
internal::RootView* root_view = state.GetRootView();
EXPECT_EQ(1U, root_view->children().size());
const std::u16string kText = u"Text";
root_view->AnnounceText(kText);
EXPECT_EQ(2U, root_view->children().size());
views::test::RunScheduledLayout(root_view);
EXPECT_FALSE(root_view->children()[0]->size().IsEmpty());
EXPECT_TRUE(root_view->children()[1]->size().IsEmpty());
View* const hidden_view = root_view->children()[1];
ui::AXNodeData node_data;
hidden_view->GetAccessibleNodeData(&node_data);
EXPECT_EQ(kText,
node_data.GetString16Attribute(ax::mojom::StringAttribute::kName));
}
#endif // !BUILDFLAG(IS_MAC)
TEST_F(RootViewTest, MouseEventDispatchedToClosestEnabledView) {
RootViewTestState state(this, {.bounds = {100, 100, 100, 100}});
internal::RootView* root_view = state.GetRootView();
View* const contents_view = root_view->GetContentsView();
EventCountView* const v1 =
contents_view->AddChildView(std::make_unique<EventCountView>());
EventCountView* const v2 =
v1->AddChildView(std::make_unique<EventCountView>());
EventCountView* const v3 =
v2->AddChildView(std::make_unique<EventCountView>());
contents_view->SetBoundsRect(gfx::Rect(0, 0, 10, 10));
v1->SetBoundsRect(gfx::Rect(0, 0, 10, 10));
v2->SetBoundsRect(gfx::Rect(0, 0, 10, 10));
v3->SetBoundsRect(gfx::Rect(0, 0, 10, 10));
v1->set_handle_mode(EventCountView::CONSUME_EVENTS);
v2->set_handle_mode(EventCountView::CONSUME_EVENTS);
v3->set_handle_mode(EventCountView::CONSUME_EVENTS);
ui::MouseEvent pressed_event(ui::ET_MOUSE_PRESSED, gfx::Point(5, 5),
gfx::Point(5, 5), ui::EventTimeForNow(), 0, 0);
ui::MouseEvent released_event(ui::ET_MOUSE_RELEASED, gfx::Point(5, 5),
gfx::Point(5, 5), ui::EventTimeForNow(), 0, 0);
root_view->OnMousePressed(pressed_event);
root_view->OnMouseReleased(released_event);
EXPECT_EQ(0, v1->GetEventCount(ui::ET_MOUSE_PRESSED));
EXPECT_EQ(0, v2->GetEventCount(ui::ET_MOUSE_PRESSED));
EXPECT_EQ(1, v3->GetEventCount(ui::ET_MOUSE_PRESSED));
v3->SetEnabled(false);
root_view->OnMousePressed(pressed_event);
root_view->OnMouseReleased(released_event);
EXPECT_EQ(0, v1->GetEventCount(ui::ET_MOUSE_PRESSED));
EXPECT_EQ(1, v2->GetEventCount(ui::ET_MOUSE_PRESSED));
EXPECT_EQ(1, v3->GetEventCount(ui::ET_MOUSE_PRESSED));
v3->SetEnabled(true);
v2->SetEnabled(false);
root_view->OnMousePressed(pressed_event);
root_view->OnMouseReleased(released_event);
EXPECT_EQ(1, v1->GetEventCount(ui::ET_MOUSE_PRESSED));
EXPECT_EQ(1, v2->GetEventCount(ui::ET_MOUSE_PRESSED));
EXPECT_EQ(1, v3->GetEventCount(ui::ET_MOUSE_PRESSED));
}
// If RootView::OnMousePressed() receives a double-click event that isn't
// handled by any views, it should still report it as handled if the first click
// was handled. However, it should *not* if the first click was unhandled.
// Regression test for https://crbug.com/1055674.
TEST_F(RootViewTest, DoubleClickHandledIffFirstClickHandled) {
RootViewTestState state(this, {.bounds = {100, 100, 100, 100}});
internal::RootView* root_view = state.GetRootView();
View* const contents_view = root_view->GetContentsView();
EventCountView* const v1 =
contents_view->AddChildView(std::make_unique<EventCountView>());
contents_view->SetBoundsRect(gfx::Rect(0, 0, 10, 10));
v1->SetBoundsRect(gfx::Rect(0, 0, 10, 10));
ui::MouseEvent pressed_event(ui::ET_MOUSE_PRESSED, gfx::Point(5, 5),
gfx::Point(5, 5), ui::EventTimeForNow(), 0, 0);
ui::MouseEvent released_event(ui::ET_MOUSE_RELEASED, gfx::Point(5, 5),
gfx::Point(5, 5), ui::EventTimeForNow(), 0, 0);
// First click handled, second click unhandled.
v1->set_handle_mode(EventCountView::CONSUME_EVENTS);
pressed_event.SetClickCount(1);
released_event.SetClickCount(1);
EXPECT_TRUE(root_view->OnMousePressed(pressed_event));
root_view->OnMouseReleased(released_event);
v1->set_handle_mode(EventCountView::PROPAGATE_EVENTS);
pressed_event.SetClickCount(2);
released_event.SetClickCount(2);
EXPECT_TRUE(root_view->OnMousePressed(pressed_event));
root_view->OnMouseReleased(released_event);
// Both clicks unhandled.
v1->set_handle_mode(EventCountView::PROPAGATE_EVENTS);
pressed_event.SetClickCount(1);
released_event.SetClickCount(1);
EXPECT_FALSE(root_view->OnMousePressed(pressed_event));
root_view->OnMouseReleased(released_event);
pressed_event.SetClickCount(2);
released_event.SetClickCount(2);
EXPECT_FALSE(root_view->OnMousePressed(pressed_event));
root_view->OnMouseReleased(released_event);
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/root_view_unittest.cc | C++ | unknown | 38,963 |
// 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/widget/sublevel_manager.h"
#include "base/containers/cxx20_erase_vector.h"
#include "base/ranges/algorithm.h"
#include "ui/views/widget/native_widget_private.h"
#include "ui/views/widget/widget.h"
namespace views {
SublevelManager::SublevelManager(Widget* owner, int sublevel)
: owner_(owner), sublevel_(sublevel) {
owner_observation_.Observe(owner);
}
SublevelManager::~SublevelManager() = default;
void SublevelManager::TrackChildWidget(Widget* child) {
DCHECK_EQ(0, base::ranges::count(children_, child));
DCHECK(child->parent() == owner_);
children_.push_back(child);
}
void SublevelManager::UntrackChildWidget(Widget* child) {
// During shutdown a child might get untracked more than once by the same
// parent. We don't want to DCHECK on that.
children_.erase(base::ranges::remove(children_, child), std::end(children_));
}
void SublevelManager::SetSublevel(int sublevel) {
sublevel_ = sublevel;
EnsureOwnerSublevel();
}
int SublevelManager::GetSublevel() const {
return sublevel_;
}
void SublevelManager::EnsureOwnerSublevel() {
// Walk through the path to the root and ensure sublevel on every widget
// on the path. This is to work around the behavior on some platforms
// where showing an activatable widget brings its ancestors to the front.
Widget* parent = owner_->parent();
Widget* child = owner_;
while (parent && parent->GetSublevelManager()->IsTrackingChildWidget(child)) {
parent->GetSublevelManager()->OrderChildWidget(child);
child = parent;
parent = parent->parent();
}
}
void SublevelManager::OrderChildWidget(Widget* child) {
DCHECK_EQ(1, base::ranges::count(children_, child));
children_.erase(base::ranges::remove(children_, child), std::end(children_));
ui::ZOrderLevel child_level = child->GetZOrderLevel();
auto insert_it = FindInsertPosition(child);
// Stacking above an invisible widget is a no-op on Mac. Therefore, find only
// visible ones.
auto find_visible_widget_of_same_level = [child_level](Widget* widget) {
return widget->IsVisible() && widget->GetZOrderLevel() == child_level;
};
auto prev_it = base::ranges::find_if(std::make_reverse_iterator(insert_it),
std::crend(children_),
find_visible_widget_of_same_level);
if (prev_it == children_.rend()) {
// x11 bug: stacking above the base `owner_` will cause `child` to become
// unresponsive after the base widget is minimized. As a workaround, we
// position `child` relative to the next child widget.
// Find the closest next widget at the same level.
auto next_it = base::ranges::find_if(insert_it, std::cend(children_),
find_visible_widget_of_same_level);
// Put `child` below `next_it`.
if (next_it != std::end(children_)) {
child->StackAboveWidget(*next_it);
(*next_it)->StackAboveWidget(child);
}
} else {
child->StackAboveWidget(*prev_it);
}
children_.insert(insert_it, child);
}
void SublevelManager::OnWidgetDestroying(Widget* owner) {
DCHECK(owner == owner_);
if (owner->parent())
owner->parent()->GetSublevelManager()->UntrackChildWidget(owner);
}
bool SublevelManager::IsTrackingChildWidget(Widget* child) {
return base::ranges::find(children_, child) != children_.end();
}
SublevelManager::ChildIterator SublevelManager::FindInsertPosition(
Widget* child) const {
ui::ZOrderLevel child_level = child->GetZOrderLevel();
int child_sublevel = child->GetZOrderSublevel();
return base::ranges::find_if(children_, [&](Widget* widget) {
return widget->GetZOrderLevel() == child_level &&
widget->GetZOrderSublevel() > child_sublevel;
});
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/sublevel_manager.cc | C++ | unknown | 3,925 |
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_WIDGET_SUBLEVEL_MANAGER_H_
#define UI_VIEWS_WIDGET_SUBLEVEL_MANAGER_H_
#include <vector>
#include "base/memory/raw_ptr.h"
#include "base/scoped_observation.h"
#include "ui/views/views_export.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_observer.h"
namespace views {
// The SublevelManager ensures a widget is shown at the correct sublevel.
// It tracks the sublevel of the owner widget and the stacking state of
// the owner's children widgets.
class VIEWS_EXPORT SublevelManager : public WidgetObserver {
public:
SublevelManager(Widget* owner, int sublevel);
~SublevelManager() override;
// Tracks a child widget.
void TrackChildWidget(Widget* child);
// Untracks a child widget.
// This is intended for internal use and to work around platform-specific
// compatibility issues.
// You should not use this.
void UntrackChildWidget(Widget* child);
// Sets the sublevel of `owner_` and triggers `EnsureOwnerSublevel()`.
void SetSublevel(int sublevel);
// Gets the sublevel of `owner_`.
int GetSublevel() const;
// Repositions `owner_` among its siblings of the same z-order level
// to ensure that its sublevel is respected.
void EnsureOwnerSublevel();
private:
// WidgetObserver:
void OnWidgetDestroying(Widget* owner) override;
// Repositions `child_` among its siblings of the same z-order level
// to ensure that its sublevel is respected.
void OrderChildWidget(Widget* child);
// Check if a child widget is being tracked.
bool IsTrackingChildWidget(Widget* child);
// Returns the position in `children_` before which `child` should be inserted
// to maintain the sublevel ordering. This methods assumes that `child` is not
// in `children_`.
using ChildIterator = std::vector<Widget*>::const_iterator;
ChildIterator FindInsertPosition(Widget* child) const;
// The owner widget.
raw_ptr<Widget> owner_;
// The sublevel of `owner_`.
int sublevel_;
// The observation of `owner_`.
base::ScopedObservation<Widget, WidgetObserver> owner_observation_{this};
// The tracked children widgets in the actual, back-to-front stacking order.
// After ensuring sublevel, children should be ordered by their sublevel
// within each level subsequence, but subsequences may interleave with each
// other. For example, "[(1,0), (2,0), (2,1), (1,1), (1,2)]" is a possible
// sequence of (level, sublevel).
std::vector<Widget*> children_;
};
} // namespace views
#endif // UI_VIEWS_WIDGET_SUBLEVEL_MANAGER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/sublevel_manager.h | C++ | unknown | 2,685 |
// 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/widget/sublevel_manager.h"
#include <AppKit/AppKit.h>
#include <algorithm>
#include <memory>
#include <string>
#include <tuple>
#include <utility>
#include "base/mac/mac_util.h"
#include "base/test/scoped_feature_list.h"
#include "build/buildflag.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/views_features.h"
namespace views {
enum WidgetShowType { kShowActive, kShowInactive };
class SublevelManagerMacTest
: public ViewsTestBase,
public testing::WithParamInterface<
std::tuple<WidgetShowType, Widget::InitParams::Activatable>> {
public:
SublevelManagerMacTest() {
scoped_feature_list_.InitAndEnableFeature(features::kWidgetLayering);
}
std::unique_ptr<Widget> CreateChildWidget(
Widget* parent,
ui::ZOrderLevel level,
int sublevel,
Widget::InitParams::Activatable activatable) {
Widget::InitParams params = CreateParamsForTestWidget();
params.z_order = level;
params.sublevel = sublevel;
params.activatable = activatable;
params.parent = parent->GetNativeView();
return CreateTestWidget(std::move(params));
}
// Call Show() or ShowInactive() depending on WidgetShowType.
void ShowWidget(const std::unique_ptr<Widget>& widget) {
WidgetShowType show_type = std::get<WidgetShowType>(GetParam());
if (show_type == WidgetShowType::kShowActive)
widget->Show();
else
widget->ShowInactive();
test::WidgetVisibleWaiter(widget.get()).Wait();
}
static std::string PrintTestName(
const ::testing::TestParamInfo<SublevelManagerMacTest::ParamType>& info) {
std::string test_name;
switch (std::get<WidgetShowType>(info.param)) {
case WidgetShowType::kShowActive:
test_name += "ShowActive";
break;
case WidgetShowType::kShowInactive:
test_name += "ShowInactive";
break;
}
test_name += "_";
switch (std::get<Widget::InitParams::Activatable>(info.param)) {
case Widget::InitParams::Activatable::kNo:
test_name += "NotActivatable";
break;
case Widget::InitParams::Activatable::kYes:
test_name += "Activatable";
break;
default:
NOTREACHED_NORETURN();
}
return test_name;
}
protected:
base::test::ScopedFeatureList scoped_feature_list_;
};
// Disabled widgets are ignored when its siblings are re-ordered.
TEST_P(SublevelManagerMacTest, ExplicitUntrack) {
std::unique_ptr<Widget> root = CreateTestWidget();
std::unique_ptr<Widget> root2 = CreateTestWidget();
std::unique_ptr<Widget> children[3];
ShowWidget(root);
ShowWidget(root2);
for (int i = 0; i < 3; i++) {
children[i] = CreateChildWidget(
root.get(), ui::ZOrderLevel::kNormal, i,
std::get<Widget::InitParams::Activatable>(GetParam()));
ShowWidget(children[i]);
// Disable the second widget.
if (i == 1) {
children[i]->parent()->GetSublevelManager()->UntrackChildWidget(
children[i].get());
}
}
NSWindow* root_nswindow = root->GetNativeWindow().GetNativeNSWindow();
NSWindow* root2_nswindow = root2->GetNativeWindow().GetNativeNSWindow();
NSWindow* child2_nswindow =
children[1]->GetNativeWindow().GetNativeNSWindow();
// Reparent `child2` to root2 at the NSWindow level but not at the Widget
// level.
[root_nswindow removeChildWindow:child2_nswindow];
[root2_nswindow addChildWindow:child2_nswindow ordered:NSWindowAbove];
children[1]->GetSublevelManager()->EnsureOwnerSublevel();
// The parent of child2 does not change.
EXPECT_EQ([child2_nswindow parentWindow], root2_nswindow);
}
INSTANTIATE_TEST_SUITE_P(
,
SublevelManagerMacTest,
::testing::Combine(
::testing::Values(WidgetShowType::kShowActive,
WidgetShowType::kShowInactive),
::testing::Values(Widget::InitParams::Activatable::kNo,
Widget::InitParams::Activatable::kYes)),
SublevelManagerMacTest::PrintTestName);
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/sublevel_manager_mac_unittest.mm | Objective-C++ | unknown | 4,208 |
// 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/widget/sublevel_manager.h"
#include <algorithm>
#include <memory>
#include <string>
#include <tuple>
#include <utility>
#include "base/test/scoped_feature_list.h"
#include "build/buildflag.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/views_features.h"
#if BUILDFLAG(IS_MAC)
#include "base/mac/mac_util.h"
#endif
namespace views {
enum WidgetShowType { kShowActive, kShowInactive };
class SublevelManagerTest : public ViewsTestBase,
public testing::WithParamInterface<
std::tuple<ViewsTestBase::NativeWidgetType,
WidgetShowType,
Widget::InitParams::Activatable>> {
public:
SublevelManagerTest() {
scoped_feature_list_.InitAndEnableFeature(features::kWidgetLayering);
}
void SetUp() override {
set_native_widget_type(
std::get<ViewsTestBase::NativeWidgetType>(GetParam()));
ViewsTestBase::SetUp();
#if BUILDFLAG(IS_MAC)
// MacOS 10.13 does not report window z-ordering reliably.
if (base::mac::IsAtMostOS10_13())
GTEST_SKIP();
#endif
}
std::unique_ptr<Widget> CreateChildWidget(
Widget* parent,
ui::ZOrderLevel level,
int sublevel,
Widget::InitParams::Activatable activatable) {
Widget::InitParams params = CreateParamsForTestWidget();
params.z_order = level;
params.sublevel = sublevel;
params.activatable = activatable;
params.parent = parent->GetNativeView();
return CreateTestWidget(std::move(params));
}
// Call Show() or ShowInactive() depending on WidgetShowType.
void ShowWidget(const std::unique_ptr<Widget>& widget) {
WidgetShowType show_type = std::get<WidgetShowType>(GetParam());
if (show_type == WidgetShowType::kShowActive)
widget->Show();
else
widget->ShowInactive();
test::WidgetVisibleWaiter(widget.get()).Wait();
}
static std::string PrintTestName(
const ::testing::TestParamInfo<SublevelManagerTest::ParamType>& info) {
std::string test_name;
switch (std::get<ViewsTestBase::NativeWidgetType>(info.param)) {
case ViewsTestBase::NativeWidgetType::kDefault:
test_name += "DefaultWidget";
break;
case ViewsTestBase::NativeWidgetType::kDesktop:
test_name += "DesktopWidget";
break;
}
test_name += "_";
switch (std::get<WidgetShowType>(info.param)) {
case WidgetShowType::kShowActive:
test_name += "ShowActive";
break;
case WidgetShowType::kShowInactive:
test_name += "ShowInactive";
break;
}
test_name += "_";
switch (std::get<Widget::InitParams::Activatable>(info.param)) {
case Widget::InitParams::Activatable::kNo:
test_name += "NotActivatable";
break;
case Widget::InitParams::Activatable::kYes:
test_name += "Activatable";
break;
default:
NOTREACHED_NORETURN();
}
return test_name;
}
protected:
base::test::ScopedFeatureList scoped_feature_list_;
};
// Widgets should be stacked according to their sublevel regardless
// the order of showing.
TEST_P(SublevelManagerTest, EnsureSublevel) {
std::unique_ptr<Widget> root = CreateTestWidget();
std::unique_ptr<Widget> children[3];
for (int sublevel = 0; sublevel < 3; sublevel++) {
children[sublevel] = CreateChildWidget(
root.get(), ui::ZOrderLevel::kNormal, sublevel,
std::get<Widget::InitParams::Activatable>(GetParam()));
}
ShowWidget(root);
int order[] = {0, 1, 2};
do {
for (int i : order)
ShowWidget(children[i]);
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++) {
if (i < j) {
EXPECT_FALSE(test::WidgetTest::IsWindowStackedAbove(
children[i].get(), children[j].get()));
} else if (i > j) {
EXPECT_TRUE(test::WidgetTest::IsWindowStackedAbove(
children[i].get(), children[j].get()));
}
}
} while (std::next_permutation(order, order + 3));
}
// Level should takes precedence over sublevel.
// TODO(crbug.com/1358586): disabled because currently non-desktop widgets
// ignore z-order level (except on ash) and we don't have a reliable way to
// test desktop widgets.
TEST_P(SublevelManagerTest, DISABLED_LevelSupersedeSublevel) {
std::unique_ptr<Widget> root = CreateTestWidget();
std::unique_ptr<Widget> low_level_widget, high_level_widget;
// `high_level_widget` should be above `low_level_widget` that has a lower
// level and a higher sublevel.
low_level_widget =
CreateChildWidget(root.get(), ui::ZOrderLevel::kNormal, 1,
std::get<Widget::InitParams::Activatable>(GetParam()));
high_level_widget =
CreateChildWidget(root.get(), ui::ZOrderLevel::kFloatingWindow, 0,
std::get<Widget::InitParams::Activatable>(GetParam()));
ShowWidget(root);
ShowWidget(high_level_widget);
ShowWidget(low_level_widget);
EXPECT_TRUE(test::WidgetTest::IsWindowStackedAbove(high_level_widget.get(),
low_level_widget.get()));
}
// Widgets are re-ordered only within the same level.
TEST_P(SublevelManagerTest, SublevelOnlyEnsuredWithinSameLevel) {
std::unique_ptr<Widget> root = CreateTestWidget();
std::unique_ptr<Widget> low_level_widget1, low_level_widget2,
high_level_widget;
low_level_widget1 =
CreateChildWidget(root.get(), ui::ZOrderLevel::kNormal, 1,
std::get<Widget::InitParams::Activatable>(GetParam()));
low_level_widget2 =
CreateChildWidget(root.get(), ui::ZOrderLevel::kNormal, 2,
std::get<Widget::InitParams::Activatable>(GetParam()));
high_level_widget =
CreateChildWidget(root.get(), ui::ZOrderLevel::kFloatingWindow, 0,
std::get<Widget::InitParams::Activatable>(GetParam()));
ShowWidget(root);
ShowWidget(low_level_widget2);
ShowWidget(low_level_widget1);
ShowWidget(high_level_widget);
EXPECT_TRUE(test::WidgetTest::IsWindowStackedAbove(high_level_widget.get(),
low_level_widget1.get()));
EXPECT_TRUE(test::WidgetTest::IsWindowStackedAbove(high_level_widget.get(),
low_level_widget2.get()));
EXPECT_TRUE(test::WidgetTest::IsWindowStackedAbove(low_level_widget2.get(),
low_level_widget1.get()));
}
// SetSublevel() should trigger re-ordering.
TEST_P(SublevelManagerTest, SetSublevel) {
std::unique_ptr<Widget> root = CreateTestWidget();
std::unique_ptr<Widget> child1, child2;
child1 =
CreateChildWidget(root.get(), ui::ZOrderLevel::kNormal, 1,
std::get<Widget::InitParams::Activatable>(GetParam()));
child2 =
CreateChildWidget(root.get(), ui::ZOrderLevel::kNormal, 2,
std::get<Widget::InitParams::Activatable>(GetParam()));
ShowWidget(root);
ShowWidget(child2);
ShowWidget(child1);
EXPECT_TRUE(
test::WidgetTest::IsWindowStackedAbove(child2.get(), child1.get()));
child1->SetZOrderSublevel(3);
EXPECT_TRUE(
test::WidgetTest::IsWindowStackedAbove(child1.get(), child2.get()));
}
TEST_P(SublevelManagerTest, GetSublevel) {
std::unique_ptr<Widget> root = CreateTestWidget();
std::unique_ptr<Widget> child1, child2;
child1 =
CreateChildWidget(root.get(), ui::ZOrderLevel::kNormal, 1,
std::get<Widget::InitParams::Activatable>(GetParam()));
child2 =
CreateChildWidget(root.get(), ui::ZOrderLevel::kNormal, 2,
std::get<Widget::InitParams::Activatable>(GetParam()));
EXPECT_EQ(child1->GetZOrderSublevel(), 1);
EXPECT_EQ(child2->GetZOrderSublevel(), 2);
}
// The stacking order between non-sibling widgets depend on the sublevels
// of the children of their most recent common ancestor.
TEST_P(SublevelManagerTest, GrandChildren) {
std::unique_ptr<Widget> root = CreateTestWidget();
std::unique_ptr<Widget> children[2];
std::unique_ptr<Widget> grand_children[2][2];
for (int i = 0; i < 2; i++) {
children[i] = CreateChildWidget(
root.get(), ui::ZOrderLevel::kNormal, i,
std::get<Widget::InitParams::Activatable>(GetParam()));
for (int j = 0; j < 2; j++) {
grand_children[i][j] = CreateChildWidget(
children[i].get(), ui::ZOrderLevel::kNormal, j,
std::get<Widget::InitParams::Activatable>(GetParam()));
}
}
ShowWidget(root);
ShowWidget(children[1]);
ShowWidget(children[0]);
ShowWidget(grand_children[1][0]);
ShowWidget(grand_children[0][1]);
EXPECT_TRUE(test::WidgetTest::IsWindowStackedAbove(children[1].get(),
children[0].get()));
// Even though grand_children[0][1] is shown later, because its parent has a
// lower sublevel than grand_children[1][0]'s parent, it should be behind.
EXPECT_TRUE(test::WidgetTest::IsWindowStackedAbove(
grand_children[1][0].get(), grand_children[0][1].get()));
}
// The sublevel manager should be able to handle the Widget re-parenting.
TEST_P(SublevelManagerTest, WidgetReparent) {
std::unique_ptr<Widget> root1 = CreateTestWidget();
std::unique_ptr<Widget> root2 = CreateTestWidget();
std::unique_ptr<Widget> child;
child =
CreateChildWidget(root1.get(), ui::ZOrderLevel::kNormal, 1,
std::get<Widget::InitParams::Activatable>(GetParam()));
ShowWidget(root1);
ShowWidget(child);
ShowWidget(root2);
Widget::ReparentNativeView(child->GetNativeView(), root2->GetNativeView());
ShowWidget(child);
#if !BUILDFLAG(IS_MAC)
// Mac does not allow re-parenting child widgets to nullptr.
Widget::ReparentNativeView(child->GetNativeView(), nullptr);
ShowWidget(child);
#endif
}
// Invisible widgets should be skipped to work around MacOS where
// stacking above them is no-op (crbug.com/1369180).
// When they become invisible, sublevels should be respected.
TEST_P(SublevelManagerTest, SkipInvisibleWidget) {
std::unique_ptr<Widget> root = CreateTestWidget();
std::unique_ptr<Widget> children[3];
ShowWidget(root);
for (int i = 0; i < 3; i++) {
children[i] = CreateChildWidget(
root.get(), ui::ZOrderLevel::kNormal, i,
std::get<Widget::InitParams::Activatable>(GetParam()));
ShowWidget(children[i]);
// Hide the second widget.
if (i == 1)
children[i]->Hide();
}
EXPECT_TRUE(test::WidgetTest::IsWindowStackedAbove(children[2].get(),
children[0].get()));
ShowWidget(children[1]);
EXPECT_TRUE(test::WidgetTest::IsWindowStackedAbove(children[1].get(),
children[0].get()));
EXPECT_TRUE(test::WidgetTest::IsWindowStackedAbove(children[2].get(),
children[1].get()));
}
// TODO(crbug.com/1333445): We should also test NativeWidgetType::kDesktop,
// but currently IsWindowStackedAbove() does not work for desktop widgets.
INSTANTIATE_TEST_SUITE_P(
,
SublevelManagerTest,
::testing::Combine(
::testing::Values(ViewsTestBase::NativeWidgetType::kDefault),
::testing::Values(WidgetShowType::kShowActive,
WidgetShowType::kShowInactive),
::testing::Values(Widget::InitParams::Activatable::kNo,
Widget::InitParams::Activatable::kYes)),
SublevelManagerTest::PrintTestName);
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/sublevel_manager_unittest.cc | C++ | unknown | 11,829 |
// Copyright 2011 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/widget/tooltip_manager.h"
namespace views {
// static
const char TooltipManager::kGroupingPropertyKey[] = "GroupingPropertyKey";
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/tooltip_manager.cc | C++ | unknown | 317 |
// Copyright 2011 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_WIDGET_TOOLTIP_MANAGER_H_
#define UI_VIEWS_WIDGET_TOOLTIP_MANAGER_H_
#include "ui/views/views_export.h"
namespace gfx {
class FontList;
class Point;
} // namespace gfx
namespace views {
class View;
// TooltipManager takes care of the wiring to support tooltips for Views. You
// almost never need to interact directly with TooltipManager, rather look to
// the various tooltip methods on View.
class VIEWS_EXPORT TooltipManager {
public:
// When a NativeView has capture all events are delivered to it. In some
// situations, such as menus, we want the tooltip to be shown for the
// NativeView the mouse is over, even if it differs from the NativeView that
// has capture (with menus the first menu shown has capture). To enable this
// if the NativeView that has capture has the same value for the property
// |kGroupingPropertyKey| as the NativeView the mouse is over the tooltip is
// shown.
static const char kGroupingPropertyKey[];
TooltipManager() = default;
virtual ~TooltipManager() = default;
// Returns the maximum width of the tooltip. |point| gives the location
// the tooltip is to be displayed on in screen coordinates.
virtual int GetMaxWidth(const gfx::Point& location) const = 0;
// Returns the font list used for tooltips.
virtual const gfx::FontList& GetFontList() const = 0;
// Notification that the view hierarchy has changed in some way.
virtual void UpdateTooltip() = 0;
// Invoked when the tooltip text changes for the specified views.
virtual void TooltipTextChanged(View* view) = 0;
};
} // namespace views
#endif // UI_VIEWS_WIDGET_TOOLTIP_MANAGER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/tooltip_manager.h | C++ | unknown | 1,795 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/widget/tooltip_manager_aura.h"
#include "ui/aura/client/screen_position_client.h"
#include "ui/aura/window_event_dispatcher.h"
#include "ui/aura/window_tree_host.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/display/screen.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/views/widget/native_widget_aura.h"
#include "ui/views/widget/widget.h"
#include "ui/wm/public/tooltip_client.h"
namespace views {
////////////////////////////////////////////////////////////////////////////////
// TooltipManagerAura public:
TooltipManagerAura::TooltipManagerAura(
internal::NativeWidgetPrivate* native_widget)
: native_widget_(native_widget) {
wm::SetTooltipText(GetWindow(), &tooltip_text_);
}
TooltipManagerAura::~TooltipManagerAura() {
wm::SetTooltipText(GetWindow(), nullptr);
}
// static
const gfx::FontList& TooltipManagerAura::GetDefaultFontList() {
return ui::ResourceBundle::GetSharedInstance().GetFontList(
ui::ResourceBundle::BaseFont);
}
// static
void TooltipManagerAura::UpdateTooltipManagerForCapture(
internal::NativeWidgetPrivate* source) {
if (!source->HasCapture())
return;
aura::Window* root_window = source->GetNativeView()->GetRootWindow();
if (!root_window)
return;
gfx::Point screen_loc(
root_window->GetHost()->dispatcher()->GetLastMouseLocationInRoot());
aura::client::ScreenPositionClient* screen_position_client =
aura::client::GetScreenPositionClient(root_window);
if (!screen_position_client)
return;
screen_position_client->ConvertPointToScreen(root_window, &screen_loc);
display::Screen* screen = display::Screen::GetScreen();
aura::Window* target = screen->GetWindowAtScreenPoint(screen_loc);
if (!target)
return;
gfx::Point target_loc(screen_loc);
screen_position_client =
aura::client::GetScreenPositionClient(target->GetRootWindow());
if (!screen_position_client)
return;
screen_position_client->ConvertPointFromScreen(target, &target_loc);
target = target->GetEventHandlerForPoint(target_loc);
while (target) {
internal::NativeWidgetPrivate* target_native_widget =
internal::NativeWidgetPrivate::GetNativeWidgetForNativeView(target);
if (target_native_widget == source)
return;
if (target_native_widget) {
if (target_native_widget->GetTooltipManager())
target_native_widget->GetTooltipManager()->UpdateTooltip();
return;
}
target = target->parent();
}
}
////////////////////////////////////////////////////////////////////////////////
// TooltipManagerAura, TooltipManager implementation:
const gfx::FontList& TooltipManagerAura::GetFontList() const {
return GetDefaultFontList();
}
int TooltipManagerAura::GetMaxWidth(const gfx::Point& point) const {
return wm::GetTooltipClient(native_widget_->GetNativeView()->GetRootWindow())
->GetMaxWidth(point);
}
void TooltipManagerAura::UpdateTooltip() {
aura::Window* root_window = GetWindow()->GetRootWindow();
if (wm::GetTooltipClient(root_window)) {
if (!native_widget_->IsVisible()) {
UpdateTooltipForTarget(nullptr, gfx::Point(), root_window);
return;
}
gfx::Point view_point =
root_window->GetHost()->dispatcher()->GetLastMouseLocationInRoot();
aura::Window::ConvertPointToTarget(root_window, GetWindow(), &view_point);
View* view = GetViewUnderPoint(view_point);
UpdateTooltipForTarget(view, view_point, root_window);
}
}
void TooltipManagerAura::TooltipTextChanged(View* view) {
aura::Window* root_window = GetWindow()->GetRootWindow();
if (wm::GetTooltipClient(root_window)) {
gfx::Point view_point =
root_window->GetHost()->dispatcher()->GetLastMouseLocationInRoot();
aura::Window::ConvertPointToTarget(root_window, GetWindow(), &view_point);
View* target = GetViewUnderPoint(view_point);
if (target != view)
return;
UpdateTooltipForTarget(view, view_point, root_window);
}
}
View* TooltipManagerAura::GetViewUnderPoint(const gfx::Point& point) {
View* root_view = native_widget_->GetWidget()
? native_widget_->GetWidget()->GetRootView()
: nullptr;
if (root_view)
return root_view->GetTooltipHandlerForPoint(point);
return nullptr;
}
void TooltipManagerAura::UpdateTooltipForTarget(View* target,
const gfx::Point& point,
aura::Window* root_window) {
if (target) {
gfx::Point view_point = point;
View::ConvertPointFromWidget(target, &view_point);
tooltip_text_ = target->GetTooltipText(view_point);
} else {
tooltip_text_.clear();
}
wm::SetTooltipId(GetWindow(), target);
wm::GetTooltipClient(root_window)->UpdateTooltip(GetWindow());
}
aura::Window* TooltipManagerAura::GetWindow() {
return native_widget_->GetNativeView();
}
} // namespace views.
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/tooltip_manager_aura.cc | C++ | unknown | 5,062 |
// Copyright 2011 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_WIDGET_TOOLTIP_MANAGER_AURA_H_
#define UI_VIEWS_WIDGET_TOOLTIP_MANAGER_AURA_H_
#include <string>
#include "base/memory/raw_ptr.h"
#include "ui/gfx/geometry/point.h"
#include "ui/views/views_export.h"
#include "ui/views/widget/tooltip_manager.h"
namespace aura {
class Window;
}
namespace gfx {
class FontList;
}
namespace views {
namespace internal {
class NativeWidgetPrivate;
}
// TooltipManager implementation for Aura.
class VIEWS_EXPORT TooltipManagerAura : public TooltipManager {
public:
explicit TooltipManagerAura(internal::NativeWidgetPrivate* native_widget);
TooltipManagerAura(const TooltipManagerAura&) = delete;
TooltipManagerAura& operator=(const TooltipManagerAura&) = delete;
~TooltipManagerAura() override;
// If |source| has capture this finds the Widget under the mouse and invokes
// UpdateTooltip() on it's TooltipManager. This is necessary as when capture
// is held mouse events are only delivered to the Window that has capture even
// though we may show tooltips for the Window under the mouse.
static void UpdateTooltipManagerForCapture(
internal::NativeWidgetPrivate* source);
// Returns the FontList used by all TooltipManagerAuras.
static const gfx::FontList& GetDefaultFontList();
// TooltipManager:
int GetMaxWidth(const gfx::Point& location) const override;
const gfx::FontList& GetFontList() const override;
void UpdateTooltip() override;
void TooltipTextChanged(View* view) override;
private:
View* GetViewUnderPoint(const gfx::Point& point);
void UpdateTooltipForTarget(View* target,
const gfx::Point& point,
aura::Window* root_window);
// Returns the Window the tooltip text is installed on.
aura::Window* GetWindow();
base::raw_ptr<internal::NativeWidgetPrivate> native_widget_;
std::u16string tooltip_text_;
};
} // namespace views
#endif // UI_VIEWS_WIDGET_TOOLTIP_MANAGER_AURA_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/tooltip_manager_aura.h | C++ | unknown | 2,111 |
// 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/widget/unique_widget_ptr.h"
#include <utility>
namespace views {
UniqueWidgetPtr::UniqueWidgetPtr() = default;
UniqueWidgetPtr::UniqueWidgetPtr(std::unique_ptr<Widget> widget) {
Init(std::move(widget));
}
UniqueWidgetPtr::UniqueWidgetPtr(UniqueWidgetPtr&& other) = default;
UniqueWidgetPtr& UniqueWidgetPtr::operator=(UniqueWidgetPtr&& other) = default;
UniqueWidgetPtr::~UniqueWidgetPtr() = default;
UniqueWidgetPtr::operator bool() const {
return !!get();
}
Widget& UniqueWidgetPtr::operator*() const {
return *get();
}
Widget* UniqueWidgetPtr::operator->() const {
return get();
}
void UniqueWidgetPtr::reset() {
unique_widget_ptr_impl_.reset();
}
Widget* UniqueWidgetPtr::get() const {
return unique_widget_ptr_impl_ ? unique_widget_ptr_impl_->Get() : nullptr;
}
void UniqueWidgetPtr::Init(std::unique_ptr<Widget> widget) {
unique_widget_ptr_impl_ = std::make_unique<Impl>(std::move(widget));
}
void UniqueWidgetPtr::Impl::WidgetAutoCloser::operator()(Widget* widget) {
widget->CloseWithReason(Widget::ClosedReason::kUnspecified);
}
UniqueWidgetPtr::Impl::Impl() = default;
UniqueWidgetPtr::Impl::Impl(std::unique_ptr<Widget> widget)
: widget_closer_(widget.release()) {
widget_observation_.Observe(widget_closer_.get());
}
UniqueWidgetPtr::Impl::~Impl() = default;
Widget* UniqueWidgetPtr::Impl::Get() const {
return widget_closer_.get();
}
void UniqueWidgetPtr::Impl::Reset() {
if (!widget_closer_)
return;
widget_observation_.Reset();
widget_closer_.reset();
}
void UniqueWidgetPtr::Impl::OnWidgetDestroying(Widget* widget) {
DCHECK_EQ(widget, widget_closer_.get());
widget_observation_.Reset();
widget_closer_.release();
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/unique_widget_ptr.cc | C++ | unknown | 1,877 |
// 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_WIDGET_UNIQUE_WIDGET_PTR_H_
#define UI_VIEWS_WIDGET_UNIQUE_WIDGET_PTR_H_
#include <memory>
#include "base/scoped_observation.h"
#include "ui/views/views_export.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_observer.h"
namespace views {
// A weak owning pointer to a Widget.
// This smart pointer acts like a unique_ptr: it ensures the Widget is
// properly closed when it goes out of scope.
// It also acts like a WeakPtr: the Widget may be deleted by its native
// widget and `get()` becomes nullptr when this happens.
// Caller may check the validity of this pointer before dereferencing it if
// the widget lifetime is in doubt.
class VIEWS_EXPORT UniqueWidgetPtr {
public:
UniqueWidgetPtr();
// This class acts like a std::unique_ptr<Widget>, so this constructor is
// deliberately implicit.
UniqueWidgetPtr(std::unique_ptr<Widget> widget); // NOLINT
// Construct from a subclass instance of Widget. Note that ~Widget() is
// virtual, so the downcasting is safe. This constructor is deliberately
// implicit.
template <class U>
UniqueWidgetPtr(std::unique_ptr<U> widget) { // NOLINT
Init(std::unique_ptr<Widget>(widget.release()));
}
UniqueWidgetPtr(UniqueWidgetPtr&&);
UniqueWidgetPtr& operator=(UniqueWidgetPtr&&);
~UniqueWidgetPtr();
explicit operator bool() const;
Widget& operator*() const;
Widget* operator->() const;
void reset();
Widget* get() const;
private:
class Impl : public WidgetObserver {
public:
Impl();
explicit Impl(std::unique_ptr<Widget> widget);
Impl(const Impl&) = delete;
Impl& operator=(const Impl&) = delete;
~Impl() override;
Widget* Get() const;
void Reset();
// WidgetObserver overrides.
void OnWidgetDestroying(Widget* widget) override;
private:
struct WidgetAutoCloser {
void operator()(Widget* widget);
};
base::ScopedObservation<Widget, WidgetObserver> widget_observation_{this};
std::unique_ptr<Widget, WidgetAutoCloser> widget_closer_;
};
void Init(std::unique_ptr<Widget> widget);
std::unique_ptr<Impl> unique_widget_ptr_impl_;
};
} // namespace views
#endif // UI_VIEWS_WIDGET_UNIQUE_WIDGET_PTR_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/unique_widget_ptr.h | C++ | unknown | 2,359 |
// 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/widget/unique_widget_ptr.h"
#include <memory>
#include <utility>
#include "base/memory/raw_ptr.h"
#include "base/scoped_observation.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_observer.h"
namespace views {
class UniqueWidgetPtrTest : public ViewsTestBase, public WidgetObserver {
public:
UniqueWidgetPtrTest() = default;
~UniqueWidgetPtrTest() override = default;
// ViewsTestBase overrides.
void TearDown() override {
ViewsTestBase::TearDown();
ASSERT_EQ(widget_, nullptr);
}
protected:
std::unique_ptr<Widget> AllocateTestWidget() override {
auto widget = ViewsTestBase::AllocateTestWidget();
widget->Init(CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS));
widget_observation_.Observe(widget.get());
return widget;
}
UniqueWidgetPtr CreateUniqueWidgetPtr() {
auto widget = UniqueWidgetPtr(AllocateTestWidget());
widget->SetContentsView(std::make_unique<View>());
widget_ = widget.get();
return widget;
}
Widget* widget() { return widget_; }
// WidgetObserver overrides.
void OnWidgetDestroying(Widget* widget) override {
ASSERT_NE(widget_, nullptr);
ASSERT_EQ(widget_, widget);
ASSERT_TRUE(widget_observation_.IsObservingSource(widget_.get()));
widget_observation_.Reset();
widget_ = nullptr;
}
private:
raw_ptr<Widget> widget_ = nullptr;
base::ScopedObservation<Widget, WidgetObserver> widget_observation_{this};
};
// Make sure explicitly resetting the |unique_widget_ptr| variable properly
// closes the widget. TearDown() will ensure |widget_| has been cleared.
TEST_F(UniqueWidgetPtrTest, TestCloseContent) {
UniqueWidgetPtr unique_widget_ptr = CreateUniqueWidgetPtr();
EXPECT_EQ(unique_widget_ptr->GetContentsView(), widget()->GetContentsView());
unique_widget_ptr.reset();
}
// Same as above, only testing that going out of scope will accomplish the same
// thing.
TEST_F(UniqueWidgetPtrTest, TestScopeDestruct) {
UniqueWidgetPtr unique_widget_ptr = CreateUniqueWidgetPtr();
EXPECT_EQ(unique_widget_ptr->GetContentsView(), widget()->GetContentsView());
// Just go out of scope to close the view;
}
// Check that proper move semantics for assignments work.
TEST_F(UniqueWidgetPtrTest, TestMoveAssign) {
UniqueWidgetPtr unique_widget_ptr2 = CreateUniqueWidgetPtr();
{
UniqueWidgetPtr unique_widget_ptr;
EXPECT_EQ(unique_widget_ptr2->GetContentsView(),
widget()->GetContentsView());
unique_widget_ptr = std::move(unique_widget_ptr2);
EXPECT_EQ(unique_widget_ptr->GetContentsView(),
widget()->GetContentsView());
EXPECT_FALSE(unique_widget_ptr2); // NOLINT
unique_widget_ptr.reset();
EXPECT_FALSE(unique_widget_ptr);
}
RunPendingMessages();
EXPECT_EQ(widget(), nullptr);
}
// Check that move construction functions correctly.
TEST_F(UniqueWidgetPtrTest, TestMoveConstruct) {
UniqueWidgetPtr unique_widget_ptr2 = CreateUniqueWidgetPtr();
{
EXPECT_EQ(unique_widget_ptr2->GetContentsView(),
widget()->GetContentsView());
UniqueWidgetPtr unique_widget_ptr = std::move(unique_widget_ptr2);
EXPECT_EQ(unique_widget_ptr->GetContentsView(),
widget()->GetContentsView());
EXPECT_FALSE(unique_widget_ptr2); // NOLINT
unique_widget_ptr.reset();
EXPECT_FALSE(unique_widget_ptr);
}
RunPendingMessages();
EXPECT_EQ(widget(), nullptr);
}
// Make sure that any external closing of the widget is properly tracked in the
// |unique_widget_ptr|.
TEST_F(UniqueWidgetPtrTest, TestCloseWidget) {
UniqueWidgetPtr unique_widget_ptr = CreateUniqueWidgetPtr();
EXPECT_EQ(unique_widget_ptr->GetContentsView(), widget()->GetContentsView());
// Initiate widget destruction.
widget()->CloseWithReason(Widget::ClosedReason::kUnspecified);
// Cycle the run loop to allow the deferred destruction to happen.
RunPendingMessages();
// The UniqueWidgetPtr should have dropped its reference to the content view.
EXPECT_FALSE(unique_widget_ptr);
}
// When the NativeWidget is destroyed, ensure that the Widget is also destroyed
// which in turn clears the |unique_widget_ptr|.
TEST_F(UniqueWidgetPtrTest, TestCloseNativeWidget) {
UniqueWidgetPtr unique_widget_ptr = CreateUniqueWidgetPtr();
EXPECT_EQ(unique_widget_ptr->GetContentsView(), widget()->GetContentsView());
// Initiate an OS level native widget destruction.
SimulateNativeDestroy(widget());
// The UniqueWidgetPtr should have dropped its reference to the content view.
EXPECT_FALSE(unique_widget_ptr);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/unique_widget_ptr_unittest.cc | C++ | unknown | 4,803 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/widget/widget.h"
#include <algorithm>
#include <set>
#include <utility>
#include "base/auto_reset.h"
#include "base/check_op.h"
#include "base/containers/adapters.h"
#include "base/functional/bind.h"
#include "base/i18n/rtl.h"
#include "base/notreached.h"
#include "base/observer_list.h"
#include "base/ranges/algorithm.h"
#include "base/strings/utf_string_conversions.h"
#include "base/trace_event/trace_event.h"
#include "build/build_config.h"
#include "ui/base/cursor/cursor.h"
#include "ui/base/default_style.h"
#include "ui/base/hit_test.h"
#include "ui/base/ime/input_method.h"
#include "ui/base/l10n/l10n_font_util.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/base/models/image_model.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/compositor/compositor.h"
#include "ui/compositor/layer.h"
#include "ui/display/screen.h"
#include "ui/events/event.h"
#include "ui/events/event_utils.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/views/controls/menu/menu_controller.h"
#include "ui/views/drag_controller.h"
#include "ui/views/event_monitor.h"
#include "ui/views/focus/focus_manager.h"
#include "ui/views/focus/focus_manager_factory.h"
#include "ui/views/focus/widget_focus_manager.h"
#include "ui/views/views_delegate.h"
#include "ui/views/views_features.h"
#include "ui/views/widget/any_widget_observer_singleton.h"
#include "ui/views/widget/native_widget_private.h"
#include "ui/views/widget/root_view.h"
#include "ui/views/widget/sublevel_manager.h"
#include "ui/views/widget/tooltip_manager.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/widget/widget_deletion_observer.h"
#include "ui/views/widget/widget_observer.h"
#include "ui/views/widget/widget_removals_observer.h"
#include "ui/views/window/custom_frame_view.h"
#include "ui/views/window/dialog_delegate.h"
#if BUILDFLAG(IS_LINUX)
#include "ui/linux/linux_ui.h"
#endif
namespace views {
namespace {
// If |view| has a layer the layer is added to |layers|. Else this recurses
// through the children. This is used to build a list of the layers created by
// views that are direct children of the Widgets layer.
void BuildViewsWithLayers(View* view, View::Views* views) {
if (view->layer()) {
views->push_back(view);
} else {
for (View* child : view->children())
BuildViewsWithLayers(child, views);
}
}
// Create a native widget implementation.
// First, use the supplied one if non-NULL.
// Finally, make a default one.
NativeWidget* CreateNativeWidget(const Widget::InitParams& params,
internal::NativeWidgetDelegate* delegate) {
if (params.native_widget)
return params.native_widget;
const auto& factory = ViewsDelegate::GetInstance()->native_widget_factory();
if (!factory.is_null()) {
NativeWidget* native_widget = factory.Run(params, delegate);
if (native_widget)
return native_widget;
}
return internal::NativeWidgetPrivate::CreateNativeWidget(delegate);
}
void NotifyCaretBoundsChanged(ui::InputMethod* input_method) {
if (!input_method)
return;
ui::TextInputClient* client = input_method->GetTextInputClient();
if (client)
input_method->OnCaretBoundsChanged(client);
}
} // namespace
// static
Widget::DisableActivationChangeHandlingType
Widget::g_disable_activation_change_handling_ =
Widget::DisableActivationChangeHandlingType::kNone;
// A default implementation of WidgetDelegate, used by Widget when no
// WidgetDelegate is supplied.
class DefaultWidgetDelegate : public WidgetDelegate {
public:
DefaultWidgetDelegate() {
// In most situations where a Widget is used without a delegate the Widget
// is used as a container, so that we want focus to advance to the top-level
// widget. A good example of this is the find bar.
SetOwnedByWidget(true);
SetFocusTraversesOut(true);
}
DefaultWidgetDelegate(const DefaultWidgetDelegate&) = delete;
DefaultWidgetDelegate& operator=(const DefaultWidgetDelegate&) = delete;
~DefaultWidgetDelegate() override = default;
};
////////////////////////////////////////////////////////////////////////////////
// Widget, PaintAsActiveLock:
Widget::PaintAsActiveLock::PaintAsActiveLock() = default;
Widget::PaintAsActiveLock::~PaintAsActiveLock() = default;
////////////////////////////////////////////////////////////////////////////////
// Widget, PaintAsActiveLockImpl:
class Widget::PaintAsActiveLockImpl : public Widget::PaintAsActiveLock {
public:
explicit PaintAsActiveLockImpl(base::WeakPtr<Widget>&& widget)
: widget_(widget) {}
~PaintAsActiveLockImpl() override {
Widget* const widget = widget_.get();
if (widget)
widget->UnlockPaintAsActive();
}
private:
base::WeakPtr<Widget> widget_;
};
////////////////////////////////////////////////////////////////////////////////
// Widget, InitParams:
Widget::InitParams::InitParams() = default;
Widget::InitParams::InitParams(Type type) : type(type) {}
Widget::InitParams::InitParams(InitParams&& other) = default;
Widget::InitParams::~InitParams() = default;
bool Widget::InitParams::CanActivate() const {
if (activatable != InitParams::Activatable::kDefault)
return activatable == InitParams::Activatable::kYes;
return type != InitParams::TYPE_CONTROL && type != InitParams::TYPE_POPUP &&
type != InitParams::TYPE_MENU && type != InitParams::TYPE_TOOLTIP &&
type != InitParams::TYPE_DRAG;
}
ui::ZOrderLevel Widget::InitParams::EffectiveZOrderLevel() const {
if (z_order.has_value())
return z_order.value();
switch (type) {
case TYPE_MENU:
return ui::ZOrderLevel::kFloatingWindow;
case TYPE_DRAG:
return ui::ZOrderLevel::kFloatingUIElement;
default:
return ui::ZOrderLevel::kNormal;
}
}
////////////////////////////////////////////////////////////////////////////////
// Widget, public:
Widget::Widget() = default;
Widget::Widget(InitParams params) {
Init(std::move(params));
}
Widget::~Widget() {
if (widget_delegate_)
widget_delegate_->WidgetDestroying();
if (ownership_ == InitParams::WIDGET_OWNS_NATIVE_WIDGET) {
owned_native_widget_.reset();
DCHECK(!native_widget_);
} else if (ownership_ == InitParams::NATIVE_WIDGET_OWNS_WIDGET) {
// TODO(crbug.com/937381): Revert to DCHECK once we figure out the reason.
CHECK(!native_widget_)
<< "Destroying a widget with a live native widget. "
<< "Widget probably should use WIDGET_OWNS_NATIVE_WIDGET ownership.";
} else {
DCHECK_EQ(ownership_, InitParams::CLIENT_OWNS_WIDGET);
if (native_widget_)
native_widget_->Close();
}
// Destroy RootView after the native widget, so in case the WidgetDelegate is
// a View in the RootView hierarchy it gets destroyed as a WidgetDelegate
// first.
// This makes destruction order for WidgetDelegate consistent between
// different Widget/NativeWidget ownership models (WidgetDelegate is always
// deleted before here, which may have removed it as a View from the
// View hierarchy).
DestroyRootView();
}
// static
Widget* Widget::CreateWindowWithParent(WidgetDelegate* delegate,
gfx::NativeView parent,
const gfx::Rect& bounds) {
Widget::InitParams params;
params.delegate = delegate;
params.parent = parent;
params.bounds = bounds;
return new Widget(std::move(params));
}
Widget* Widget::CreateWindowWithParent(std::unique_ptr<WidgetDelegate> delegate,
gfx::NativeView parent,
const gfx::Rect& bounds) {
DCHECK(delegate->owned_by_widget());
return CreateWindowWithParent(delegate.release(), parent, bounds);
}
// static
Widget* Widget::CreateWindowWithContext(WidgetDelegate* delegate,
gfx::NativeWindow context,
const gfx::Rect& bounds) {
Widget::InitParams params;
params.delegate = delegate;
params.context = context;
params.bounds = bounds;
return new Widget(std::move(params));
}
// static
Widget* Widget::CreateWindowWithContext(
std::unique_ptr<WidgetDelegate> delegate,
gfx::NativeWindow context,
const gfx::Rect& bounds) {
DCHECK(delegate->owned_by_widget());
return CreateWindowWithContext(delegate.release(), context, bounds);
}
// static
Widget* Widget::GetWidgetForNativeView(gfx::NativeView native_view) {
if (!native_view)
return nullptr;
internal::NativeWidgetPrivate* native_widget =
internal::NativeWidgetPrivate::GetNativeWidgetForNativeView(native_view);
return native_widget ? native_widget->GetWidget() : nullptr;
}
// static
Widget* Widget::GetWidgetForNativeWindow(gfx::NativeWindow native_window) {
if (!native_window)
return nullptr;
internal::NativeWidgetPrivate* native_widget =
internal::NativeWidgetPrivate::GetNativeWidgetForNativeWindow(
native_window);
return native_widget ? native_widget->GetWidget() : nullptr;
}
// static
Widget* Widget::GetTopLevelWidgetForNativeView(gfx::NativeView native_view) {
if (!native_view)
return nullptr;
internal::NativeWidgetPrivate* native_widget =
internal::NativeWidgetPrivate::GetTopLevelNativeWidget(native_view);
return native_widget ? native_widget->GetWidget() : nullptr;
}
// static
void Widget::GetAllChildWidgets(gfx::NativeView native_view,
Widgets* children) {
if (!native_view)
return;
internal::NativeWidgetPrivate::GetAllChildWidgets(native_view, children);
}
// static
void Widget::GetAllOwnedWidgets(gfx::NativeView native_view, Widgets* owned) {
if (!native_view)
return;
internal::NativeWidgetPrivate::GetAllOwnedWidgets(native_view, owned);
}
// static
void Widget::ReparentNativeView(gfx::NativeView native_view,
gfx::NativeView new_parent) {
DCHECK(native_view);
internal::NativeWidgetPrivate::ReparentNativeView(native_view, new_parent);
Widget* child_widget = GetWidgetForNativeView(native_view);
Widget* parent_widget =
new_parent ? GetWidgetForNativeView(new_parent) : nullptr;
if (child_widget)
child_widget->SetParent(parent_widget);
}
// static
int Widget::GetLocalizedContentsWidth(int col_resource_id) {
return ui::GetLocalizedContentsWidthForFontList(
col_resource_id,
ui::ResourceBundle::GetSharedInstance().GetFontListWithDelta(
ui::kMessageFontSizeDelta));
}
// static
int Widget::GetLocalizedContentsHeight(int row_resource_id) {
return ui::GetLocalizedContentsHeightForFontList(
row_resource_id,
ui::ResourceBundle::GetSharedInstance().GetFontListWithDelta(
ui::kMessageFontSizeDelta));
}
// static
gfx::Size Widget::GetLocalizedContentsSize(int col_resource_id,
int row_resource_id) {
return gfx::Size(GetLocalizedContentsWidth(col_resource_id),
GetLocalizedContentsHeight(row_resource_id));
}
// static
bool Widget::RequiresNonClientView(InitParams::Type type) {
return type == InitParams::TYPE_WINDOW || type == InitParams::TYPE_BUBBLE;
}
void Widget::Init(InitParams params) {
TRACE_EVENT0("views", "Widget::Init");
DCHECK(!native_widget_initialized_)
<< "This widget has already been initialized";
if (params.name.empty() && params.delegate) {
params.name = params.delegate->internal_name();
// If an internal name was not provided the class name of the contents view
// is a reasonable default.
if (params.name.empty() && params.delegate->GetContentsView())
params.name = params.delegate->GetContentsView()->GetClassName();
}
if (params.parent && GetWidgetForNativeView(params.parent))
parent_ = GetWidgetForNativeView(params.parent)->GetWeakPtr();
// Subscripbe to parent's paint-as-active change.
if (parent_) {
parent_paint_as_active_subscription_ =
parent_->RegisterPaintAsActiveChangedCallback(
base::BindRepeating(&Widget::OnParentShouldPaintAsActiveChanged,
base::Unretained(this)));
}
params.child |= (params.type == InitParams::TYPE_CONTROL);
is_top_level_ = !params.child ||
params.parent_widget != gfx::kNullAcceleratedWidget;
if (params.opacity == views::Widget::InitParams::WindowOpacity::kInferred &&
params.type != views::Widget::InitParams::TYPE_WINDOW) {
params.opacity = views::Widget::InitParams::WindowOpacity::kOpaque;
}
{
// ViewsDelegate::OnBeforeWidgetInit() may change `params.delegate` either
// by setting it to null or assigning a different value to it, so handle
// both cases.
// TODO(kylixrd): Rework this to avoid always creating the default delegate
// once the widget never owns a provided delegate.
owned_widget_delegate_ = std::make_unique<DefaultWidgetDelegate>();
widget_delegate_ = params.delegate ? params.delegate->AsWeakPtr()
: owned_widget_delegate_->AsWeakPtr();
ViewsDelegate::GetInstance()->OnBeforeWidgetInit(¶ms, this);
widget_delegate_ = params.delegate ? params.delegate->AsWeakPtr()
: owned_widget_delegate_->AsWeakPtr();
if (widget_delegate_.get() != owned_widget_delegate_.get()) {
// TODO(kylixrd): This will be unnecessary once the Widget can no longer
// "own" the delegate.
if (widget_delegate_->owned_by_widget())
owned_widget_delegate_ = base::WrapUnique(widget_delegate_.get());
else
owned_widget_delegate_.reset();
}
}
DCHECK(widget_delegate_);
if (params.opacity == views::Widget::InitParams::WindowOpacity::kInferred)
params.opacity = views::Widget::InitParams::WindowOpacity::kOpaque;
bool can_activate = params.CanActivate();
params.activatable = can_activate ? InitParams::Activatable::kYes
: InitParams::Activatable::kNo;
widget_delegate_->SetCanActivate(can_activate);
// Henceforth, ensure the delegate outlives the Widget.
widget_delegate_->can_delete_this_ = false;
widget_delegate_->WidgetInitializing(this);
ownership_ = params.ownership;
#if BUILDFLAG(IS_CHROMEOS_ASH)
background_elevation_ = params.background_elevation;
#endif
if (base::FeatureList::IsEnabled(features::kWidgetLayering)) {
sublevel_manager_ =
std::make_unique<SublevelManager>(this, params.sublevel);
}
internal::NativeWidgetPrivate* native_widget_raw_ptr =
CreateNativeWidget(params, this)->AsNativeWidgetPrivate();
native_widget_ = native_widget_raw_ptr->GetWeakPtr();
if (params.ownership == InitParams::WIDGET_OWNS_NATIVE_WIDGET) {
owned_native_widget_ = base::WrapUnique(native_widget_raw_ptr);
}
root_view_.reset(CreateRootView());
// Copy the elements of params that will be used after it is moved.
const InitParams::Type type = params.type;
const gfx::Rect bounds = params.bounds;
const ui::WindowShowState show_state = params.show_state;
WidgetDelegate* delegate = params.delegate;
native_widget_->InitNativeWidget(std::move(params));
if (type == InitParams::TYPE_MENU)
is_mouse_button_pressed_ = native_widget_->IsMouseButtonDown();
if (RequiresNonClientView(type)) {
non_client_view_ =
new NonClientView(widget_delegate_->CreateClientView(this));
non_client_view_->SetFrameView(CreateNonClientFrameView());
non_client_view_->SetOverlayView(widget_delegate_->CreateOverlayView());
// Bypass the Layout() that happens in Widget::SetContentsView(). Layout()
// will occur after setting the initial bounds below. The RootView's size is
// not valid until that happens.
root_view_->SetContentsView(non_client_view_);
// Initialize the window's icon and title before setting the window's
// initial bounds; the frame view's preferred height may depend on the
// presence of an icon or a title.
UpdateWindowIcon();
UpdateWindowTitle();
non_client_view_->ResetWindowControls();
SetInitialBounds(bounds);
// Perform the initial layout. This handles the case where the size might
// not actually change when setting the initial bounds. If it did, child
// views won't have a dirty Layout state, so won't do any work.
root_view_->Layout();
if (show_state == ui::SHOW_STATE_MAXIMIZED) {
Maximize();
saved_show_state_ = ui::SHOW_STATE_MAXIMIZED;
} else if (show_state == ui::SHOW_STATE_MINIMIZED) {
Minimize();
saved_show_state_ = ui::SHOW_STATE_MINIMIZED;
} else if (show_state == ui::SHOW_STATE_FULLSCREEN) {
SetFullscreen(true);
}
} else if (delegate) {
SetContentsView(delegate->TransferOwnershipOfContentsView());
if (params.parent_widget != gfx::kNullAcceleratedWidget) {
// Set the bounds directly instead of applying an inset.
SetBounds(bounds);
} else {
SetInitialBoundsForFramelessWindow(bounds);
}
}
if (base::FeatureList::IsEnabled(features::kWidgetLayering)) {
if (parent_)
parent_->GetSublevelManager()->TrackChildWidget(this);
}
native_theme_observation_.Observe(GetNativeTheme());
native_widget_initialized_ = true;
native_widget_->OnWidgetInitDone();
if (delegate)
delegate->WidgetInitialized();
internal::AnyWidgetObserverSingleton::GetInstance()->OnAnyWidgetInitialized(
this);
}
void Widget::ShowEmojiPanel() {
if (native_widget_)
native_widget_->ShowEmojiPanel();
}
// Unconverted methods (see header) --------------------------------------------
gfx::NativeView Widget::GetNativeView() const {
return native_widget_ ? native_widget_->GetNativeView()
: gfx::kNullNativeView;
}
gfx::NativeWindow Widget::GetNativeWindow() const {
return native_widget_ ? native_widget_->GetNativeWindow()
: gfx::kNullNativeWindow;
}
void Widget::AddObserver(WidgetObserver* observer) {
// Make sure that there is no nullptr in observer list. crbug.com/471649.
CHECK(observer);
observers_.AddObserver(observer);
}
void Widget::RemoveObserver(WidgetObserver* observer) {
observers_.RemoveObserver(observer);
}
bool Widget::HasObserver(const WidgetObserver* observer) const {
return observers_.HasObserver(observer);
}
void Widget::AddRemovalsObserver(WidgetRemovalsObserver* observer) {
removals_observers_.AddObserver(observer);
}
void Widget::RemoveRemovalsObserver(WidgetRemovalsObserver* observer) {
removals_observers_.RemoveObserver(observer);
}
bool Widget::HasRemovalsObserver(const WidgetRemovalsObserver* observer) const {
return removals_observers_.HasObserver(observer);
}
bool Widget::GetAccelerator(int cmd_id, ui::Accelerator* accelerator) const {
return false;
}
void Widget::ViewHierarchyChanged(const ViewHierarchyChangedDetails& details) {
if (!details.is_add) {
if (details.child == dragged_view_)
dragged_view_ = nullptr;
FocusManager* focus_manager = GetFocusManager();
if (focus_manager)
focus_manager->ViewRemoved(details.child);
if (native_widget_)
native_widget_->ViewRemoved(details.child);
}
}
void Widget::NotifyNativeViewHierarchyWillChange() {
if (!native_widget_)
return;
// During tear-down the top-level focus manager becomes unavailable to
// GTK tabbed panes and their children, so normal deregistration via
// |FocusManager::ViewRemoved()| calls are fouled. We clear focus here
// to avoid these redundant steps and to avoid accessing deleted views
// that may have been in focus.
ClearFocusFromWidget();
native_widget_->OnNativeViewHierarchyWillChange();
}
void Widget::NotifyNativeViewHierarchyChanged() {
if (!native_widget_)
return;
native_widget_->OnNativeViewHierarchyChanged();
root_view_->NotifyNativeViewHierarchyChanged();
}
void Widget::NotifyWillRemoveView(View* view) {
for (WidgetRemovalsObserver& observer : removals_observers_)
observer.OnWillRemoveView(this, view);
}
// Converted methods (see header) ----------------------------------------------
Widget* Widget::GetTopLevelWidget() {
return const_cast<Widget*>(
static_cast<const Widget*>(this)->GetTopLevelWidget());
}
const Widget* Widget::GetTopLevelWidget() const {
// GetTopLevelNativeWidget doesn't work during destruction because
// property is gone after gobject gets deleted. Short circuit here
// for toplevel so that InputMethod can remove itself from
// focus manager.
if (is_top_level())
return this;
return native_widget_ ? native_widget_->GetTopLevelWidget() : nullptr;
}
Widget* Widget::GetPrimaryWindowWidget() {
return GetTopLevelWidget();
}
const Widget* Widget::GetPrimaryWindowWidget() const {
return const_cast<Widget*>(this)->GetPrimaryWindowWidget();
}
void Widget::SetContentsView(View* view) {
// Do not SetContentsView() again if it is already set to the same view.
if (view == GetContentsView())
return;
// |non_client_view_| can only be non-null here if RequiresNonClientView() was
// true when the widget was initialized. Creating widgets with non-client
// views and then setting the contents view can cause subtle problems on
// Windows, where the native widget thinks there is still a
// |non_client_view_|. If you get this error, either use a different type when
// initializing the widget, or don't call SetContentsView().
DCHECK(!non_client_view_);
root_view_->SetContentsView(view);
// Force a layout now, since the attached hierarchy won't be ready for the
// containing window's bounds. Note that we call Layout directly rather than
// calling the widget's size changed handler, since the RootView's bounds may
// not have changed, which will cause the Layout not to be done otherwise.
root_view_->Layout();
}
View* Widget::GetContentsView() {
return root_view_->GetContentsView();
}
gfx::Rect Widget::GetWindowBoundsInScreen() const {
return native_widget_ ? native_widget_->GetWindowBoundsInScreen()
: gfx::Rect();
}
gfx::Rect Widget::GetClientAreaBoundsInScreen() const {
return native_widget_ ? native_widget_->GetClientAreaBoundsInScreen()
: gfx::Rect();
}
gfx::Rect Widget::GetRestoredBounds() const {
return native_widget_ ? native_widget_->GetRestoredBounds() : gfx::Rect();
}
std::string Widget::GetWorkspace() const {
return native_widget_ ? native_widget_->GetWorkspace() : "";
}
void Widget::SetBounds(const gfx::Rect& bounds) {
if (native_widget_)
native_widget_->SetBounds(bounds);
}
void Widget::SetSize(const gfx::Size& size) {
if (native_widget_)
native_widget_->SetSize(size);
}
void Widget::CenterWindow(const gfx::Size& size) {
if (native_widget_)
native_widget_->CenterWindow(size);
}
void Widget::SetBoundsConstrained(const gfx::Rect& bounds) {
if (native_widget_)
native_widget_->SetBoundsConstrained(bounds);
}
void Widget::SetVisibilityChangedAnimationsEnabled(bool value) {
if (native_widget_)
native_widget_->SetVisibilityChangedAnimationsEnabled(value);
}
void Widget::SetVisibilityAnimationDuration(const base::TimeDelta& duration) {
if (native_widget_)
native_widget_->SetVisibilityAnimationDuration(duration);
}
void Widget::SetVisibilityAnimationTransition(VisibilityTransition transition) {
if (native_widget_)
native_widget_->SetVisibilityAnimationTransition(transition);
}
bool Widget::IsMoveLoopSupported() const {
return native_widget_ ? native_widget_->IsMoveLoopSupported() : false;
}
Widget::MoveLoopResult Widget::RunMoveLoop(
const gfx::Vector2d& drag_offset,
MoveLoopSource source,
MoveLoopEscapeBehavior escape_behavior) {
if (!native_widget_)
return MoveLoopResult::kCanceled;
return native_widget_->RunMoveLoop(drag_offset, source, escape_behavior);
}
void Widget::EndMoveLoop() {
if (native_widget_)
native_widget_->EndMoveLoop();
}
void Widget::StackAboveWidget(Widget* widget) {
if (native_widget_)
native_widget_->StackAbove(widget->GetNativeView());
}
void Widget::StackAbove(gfx::NativeView native_view) {
if (native_widget_)
native_widget_->StackAbove(native_view);
}
void Widget::StackAtTop() {
if (native_widget_)
native_widget_->StackAtTop();
}
bool Widget::IsStackedAbove(gfx::NativeView native_view) {
return native_widget_ ? native_widget_->IsStackedAbove(native_view) : false;
}
void Widget::SetShape(std::unique_ptr<ShapeRects> shape) {
if (native_widget_)
native_widget_->SetShape(std::move(shape));
}
void Widget::CloseWithReason(ClosedReason closed_reason) {
if (widget_closed_) {
// It appears we can hit this code path if you close a modal dialog then
// close the last browser before the destructor is hit, which triggers
// invoking Close again.
return;
}
if (block_close_) {
return;
}
if (non_client_view_ && non_client_view_->OnWindowCloseRequested() ==
CloseRequestResult::kCannotClose) {
return;
}
// This is the last chance to cancel closing.
if (widget_delegate_ && !widget_delegate_->OnCloseRequested(closed_reason))
return;
// Cancel widget close on focus lost. This is used in UI Devtools to lock
// bubbles and in some tests where we want to ignore spurious deactivation.
if (closed_reason == ClosedReason::kLostFocus &&
(g_disable_activation_change_handling_ ==
DisableActivationChangeHandlingType::kIgnore ||
g_disable_activation_change_handling_ ==
DisableActivationChangeHandlingType::kIgnoreDeactivationOnly)) {
return;
}
// The actions below can cause this function to be called again, so mark
// |this| as closed early. See crbug.com/714334
widget_closed_ = true;
closed_reason_ = closed_reason;
SaveWindowPlacement();
ClearFocusFromWidget();
for (WidgetObserver& observer : observers_)
observer.OnWidgetClosing(this);
internal::AnyWidgetObserverSingleton::GetInstance()->OnAnyWidgetClosing(this);
if (widget_delegate_)
widget_delegate_->WindowWillClose();
if (native_widget_)
native_widget_->Close();
}
void Widget::Close() {
CloseWithReason(ClosedReason::kUnspecified);
}
void Widget::CloseNow() {
// Set this so that Widget::Close() early outs. In general this operation is
// a one-way and can't be undone.
widget_closed_ = true;
for (WidgetObserver& observer : observers_)
observer.OnWidgetClosing(this);
internal::AnyWidgetObserverSingleton::GetInstance()->OnAnyWidgetClosing(this);
DCHECK(native_widget_initialized_) << "Native widget is never initialized.";
if (native_widget_)
native_widget_->CloseNow();
}
bool Widget::IsClosed() const {
return widget_closed_;
}
void Widget::Show() {
if (!native_widget_)
return;
const ui::Layer* layer = GetLayer();
TRACE_EVENT1("views", "Widget::Show", "layer",
layer ? layer->name() : "none");
ui::WindowShowState preferred_show_state =
CanActivate() ? ui::SHOW_STATE_NORMAL : ui::SHOW_STATE_INACTIVE;
if (non_client_view_) {
// While initializing, the kiosk mode will go to full screen before the
// widget gets shown. In that case we stay in full screen mode, regardless
// of the |saved_show_state_| member.
if (saved_show_state_ == ui::SHOW_STATE_MAXIMIZED &&
!initial_restored_bounds_.IsEmpty() && !IsFullscreen()) {
native_widget_->Show(ui::SHOW_STATE_MAXIMIZED, initial_restored_bounds_);
} else {
native_widget_->Show(
IsFullscreen() ? ui::SHOW_STATE_FULLSCREEN : saved_show_state_,
gfx::Rect());
}
// |saved_show_state_| only applies the first time the window is shown.
// If we don't reset the value the window may be shown maximized every time
// it is subsequently shown after being hidden.
saved_show_state_ = preferred_show_state;
} else {
native_widget_->Show(preferred_show_state, gfx::Rect());
}
HandleShowRequested();
}
void Widget::Hide() {
if (!native_widget_)
return;
native_widget_->Hide();
internal::AnyWidgetObserverSingleton::GetInstance()->OnAnyWidgetHidden(this);
}
void Widget::ShowInactive() {
if (!native_widget_)
return;
// If this gets called with saved_show_state_ == ui::SHOW_STATE_MAXIMIZED,
// call SetBounds()with the restored bounds to set the correct size. This
// normally should not happen, but if it does we should avoid showing unsized
// windows.
if (saved_show_state_ == ui::SHOW_STATE_MAXIMIZED &&
!initial_restored_bounds_.IsEmpty()) {
SetBounds(initial_restored_bounds_);
saved_show_state_ = ui::SHOW_STATE_NORMAL;
}
native_widget_->Show(ui::SHOW_STATE_INACTIVE, gfx::Rect());
HandleShowRequested();
}
void Widget::Activate() {
if (CanActivate() && native_widget_)
native_widget_->Activate();
}
void Widget::Deactivate() {
if (native_widget_)
native_widget_->Deactivate();
}
bool Widget::IsActive() const {
return native_widget_ ? native_widget_->IsActive() : false;
}
void Widget::SetZOrderLevel(ui::ZOrderLevel order) {
if (native_widget_)
native_widget_->SetZOrderLevel(order);
}
ui::ZOrderLevel Widget::GetZOrderLevel() const {
return native_widget_ ? native_widget_->GetZOrderLevel()
: ui::ZOrderLevel::kNormal;
}
void Widget::SetZOrderSublevel(int sublevel) {
sublevel_manager_->SetSublevel(sublevel);
}
int Widget::GetZOrderSublevel() const {
if (!sublevel_manager_)
return 0;
return sublevel_manager_->GetSublevel();
}
void Widget::SetVisibleOnAllWorkspaces(bool always_visible) {
if (native_widget_)
native_widget_->SetVisibleOnAllWorkspaces(always_visible);
}
bool Widget::IsVisibleOnAllWorkspaces() const {
return native_widget_ ? native_widget_->IsVisibleOnAllWorkspaces() : false;
}
void Widget::Maximize() {
if (native_widget_)
native_widget_->Maximize();
}
void Widget::Minimize() {
if (native_widget_)
native_widget_->Minimize();
}
void Widget::Restore() {
if (native_widget_)
native_widget_->Restore();
}
bool Widget::IsMaximized() const {
return native_widget_ ? native_widget_->IsMaximized() : false;
}
bool Widget::IsMinimized() const {
return native_widget_ ? native_widget_->IsMinimized() : false;
}
void Widget::SetFullscreen(bool fullscreen, int64_t target_display_id) {
if (!native_widget_)
return;
// It isn't valid to specify `target_display_id` when exiting fullscreen.
if (!fullscreen)
DCHECK(target_display_id == display::kInvalidDisplayId);
if (IsFullscreen() == fullscreen &&
target_display_id == display::kInvalidDisplayId) {
return;
}
auto weak_ptr = GetWeakPtr();
native_widget_->SetFullscreen(fullscreen, target_display_id);
if (!weak_ptr)
return;
if (non_client_view_)
non_client_view_->InvalidateLayout();
}
bool Widget::IsFullscreen() const {
return native_widget_ ? native_widget_->IsFullscreen() : false;
}
void Widget::SetCanAppearInExistingFullscreenSpaces(
bool can_appear_in_existing_fullscreen_spaces) {
if (native_widget_) {
native_widget_->SetCanAppearInExistingFullscreenSpaces(
can_appear_in_existing_fullscreen_spaces);
}
}
void Widget::SetOpacity(float opacity) {
DCHECK(opacity >= 0.0f);
DCHECK(opacity <= 1.0f);
if (native_widget_)
native_widget_->SetOpacity(opacity);
}
void Widget::SetAspectRatio(const gfx::SizeF& aspect_ratio) {
if (!native_widget_) {
return;
}
// The aspect ratio affects the client view only, so figure out how much of
// the widget isn't taken up by the client view.
gfx::Size excluded_margin;
if (non_client_view() && non_client_view()->frame_view()) {
excluded_margin =
non_client_view()->bounds().size() -
non_client_view()->frame_view()->GetBoundsForClientView().size();
}
native_widget_->SetAspectRatio(aspect_ratio, excluded_margin);
}
void Widget::FlashFrame(bool flash) {
if (native_widget_)
native_widget_->FlashFrame(flash);
}
View* Widget::GetRootView() {
return root_view_.get();
}
const View* Widget::GetRootView() const {
return root_view_.get();
}
bool Widget::IsVisible() const {
return native_widget_ ? native_widget_->IsVisible() : false;
}
const ui::ThemeProvider* Widget::GetThemeProvider() const {
// The theme provider is provided by the very top widget in the ownership
// chain, which may include parenting, anchoring, etc. Use
// GetPrimaryWindowWidget() rather than GetTopLevelWidget() for this purpose
// (see description of those methods to learn more).
const Widget* const root_widget = GetPrimaryWindowWidget();
return (root_widget && root_widget != this) ? root_widget->GetThemeProvider()
: nullptr;
}
ui::ColorProviderManager::ThemeInitializerSupplier* Widget::GetCustomTheme()
const {
return nullptr;
}
FocusManager* Widget::GetFocusManager() {
Widget* toplevel_widget = GetTopLevelWidget();
return toplevel_widget ? toplevel_widget->focus_manager_.get() : nullptr;
}
const FocusManager* Widget::GetFocusManager() const {
const Widget* toplevel_widget = GetTopLevelWidget();
return toplevel_widget ? toplevel_widget->focus_manager_.get() : nullptr;
}
ui::InputMethod* Widget::GetInputMethod() {
if (is_top_level() && native_widget_) {
// Only creates the shared the input method instance on top level widget.
return native_widget_private()->GetInputMethod();
} else {
Widget* toplevel = GetTopLevelWidget();
// If GetTopLevelWidget() returns itself which is not toplevel,
// the widget is detached from toplevel widget.
// TODO(oshima): Fix GetTopLevelWidget() to return NULL
// if there is no toplevel. We probably need to add GetTopMostWidget()
// to replace some use cases.
return (toplevel && toplevel != this) ? toplevel->GetInputMethod()
: nullptr;
}
}
SublevelManager* Widget::GetSublevelManager() {
return sublevel_manager_.get();
}
void Widget::RunShellDrag(View* view,
std::unique_ptr<ui::OSExchangeData> data,
const gfx::Point& location,
int operation,
ui::mojom::DragEventSource source) {
if (!native_widget_)
return;
dragged_view_ = view;
OnDragWillStart();
for (WidgetObserver& observer : observers_)
observer.OnWidgetDragWillStart(this);
if (view && view->drag_controller()) {
view->drag_controller()->OnWillStartDragForView(view);
}
WidgetDeletionObserver widget_deletion_observer(this);
native_widget_->RunShellDrag(view, std::move(data), location, operation,
source);
// The widget may be destroyed during the drag operation.
if (!widget_deletion_observer.IsWidgetAlive())
return;
// If the view is removed during the drag operation, dragged_view_ is set to
// NULL.
if (view && dragged_view_ == view) {
dragged_view_ = nullptr;
view->OnDragDone();
}
OnDragComplete();
for (WidgetObserver& observer : observers_)
observer.OnWidgetDragComplete(this);
}
void Widget::SchedulePaintInRect(const gfx::Rect& rect) {
// This happens when DestroyRootView removes all children from the
// RootView which triggers a SchedulePaint that ends up here. This happens
// after in ~Widget after native_widget_ is destroyed.
if (native_widget_)
native_widget_->SchedulePaintInRect(rect);
}
void Widget::ScheduleLayout() {
if (native_widget_)
native_widget_->ScheduleLayout();
}
void Widget::SetCursor(const ui::Cursor& cursor) {
if (native_widget_)
native_widget_->SetCursor(cursor);
}
bool Widget::IsMouseEventsEnabled() const {
return native_widget_ ? native_widget_->IsMouseEventsEnabled() : false;
}
void Widget::SetNativeWindowProperty(const char* name, void* value) {
if (native_widget_)
native_widget_->SetNativeWindowProperty(name, value);
}
void* Widget::GetNativeWindowProperty(const char* name) const {
return native_widget_ ? native_widget_->GetNativeWindowProperty(name)
: nullptr;
}
void Widget::UpdateWindowTitle() {
if (!native_widget_)
return;
if (!non_client_view_)
return;
// Update the native frame's text. We do this regardless of whether or not
// the native frame is being used, since this also updates the taskbar, etc.
std::u16string window_title = widget_delegate_->GetWindowTitle();
base::i18n::AdjustStringForLocaleDirection(&window_title);
if (!native_widget_->SetWindowTitle(window_title))
return;
non_client_view_->UpdateWindowTitle();
}
void Widget::UpdateWindowIcon() {
if (!native_widget_)
return;
if (non_client_view_)
non_client_view_->UpdateWindowIcon();
gfx::ImageSkia window_icon =
widget_delegate_->GetWindowIcon().Rasterize(GetColorProvider());
// In general, icon information is read from a |widget_delegate_| and then
// passed to |native_widget_|. On ChromeOS, for lacros-chrome to support the
// initial window state as minimized state, a valid icon is added to
// |native_widget_| earlier stage of widget initialization. See
// https://crbug.com/1189981. As only lacros-chrome on ChromeOS supports this
// behavior other overrides of |native_widget_| will always have no icon
// information. This is also true for |app_icon| referred below.
if (window_icon.isNull()) {
const gfx::ImageSkia* icon = native_widget_->GetWindowIcon();
if (icon && !icon->isNull())
window_icon = *icon;
}
gfx::ImageSkia app_icon =
widget_delegate_->GetWindowAppIcon().Rasterize(GetColorProvider());
if (app_icon.isNull()) {
const gfx::ImageSkia* icon = native_widget_->GetWindowAppIcon();
if (icon && !icon->isNull())
app_icon = *icon;
}
native_widget_->SetWindowIcons(window_icon, app_icon);
}
FocusTraversable* Widget::GetFocusTraversable() {
return static_cast<internal::RootView*>(root_view_.get());
}
void Widget::ThemeChanged() {
root_view_->ThemeChanged();
for (WidgetObserver& observer : observers_)
observer.OnWidgetThemeChanged(this);
NotifyColorProviderChanged();
}
void Widget::DeviceScaleFactorChanged(float old_device_scale_factor,
float new_device_scale_factor) {
root_view_->DeviceScaleFactorChanged(old_device_scale_factor,
new_device_scale_factor);
}
void Widget::SetFocusTraversableParent(FocusTraversable* parent) {
root_view_->SetFocusTraversableParent(parent);
}
void Widget::SetFocusTraversableParentView(View* parent_view) {
root_view_->SetFocusTraversableParentView(parent_view);
}
void Widget::ClearNativeFocus() {
if (native_widget_)
native_widget_->ClearNativeFocus();
}
std::unique_ptr<NonClientFrameView> Widget::CreateNonClientFrameView() {
if (!native_widget_)
return nullptr;
auto frame_view = widget_delegate_->CreateNonClientFrameView(this);
if (!frame_view)
frame_view = native_widget_->CreateNonClientFrameView();
if (!frame_view) {
frame_view =
ViewsDelegate::GetInstance()->CreateDefaultNonClientFrameView(this);
}
if (frame_view)
return frame_view;
return std::make_unique<CustomFrameView>(this);
}
bool Widget::ShouldUseNativeFrame() const {
if (frame_type_ != FrameType::kDefault)
return frame_type_ == FrameType::kForceNative;
return native_widget_ ? native_widget_->ShouldUseNativeFrame() : false;
}
bool Widget::ShouldWindowContentsBeTransparent() const {
return native_widget_ ? native_widget_->ShouldWindowContentsBeTransparent()
: false;
}
void Widget::DebugToggleFrameType() {
if (!native_widget_)
return;
if (frame_type_ == FrameType::kDefault) {
frame_type_ = ShouldUseNativeFrame() ? FrameType::kForceCustom
: FrameType::kForceNative;
} else {
frame_type_ = frame_type_ == FrameType::kForceCustom
? FrameType::kForceNative
: FrameType::kForceCustom;
}
FrameTypeChanged();
}
void Widget::FrameTypeChanged() {
if (native_widget_)
native_widget_->FrameTypeChanged();
}
const ui::Compositor* Widget::GetCompositor() const {
return native_widget_ ? native_widget_->GetCompositor() : nullptr;
}
const ui::Layer* Widget::GetLayer() const {
return native_widget_ ? native_widget_->GetLayer() : nullptr;
}
void Widget::ReorderNativeViews() {
if (native_widget_)
native_widget_->ReorderNativeViews();
}
void Widget::LayerTreeChanged() {
// Calculate the layers requires traversing the tree, and since nearly any
// mutation of the tree can trigger this call we delay until absolutely
// necessary.
views_with_layers_dirty_ = true;
}
const NativeWidget* Widget::native_widget() const {
return native_widget_.get();
}
NativeWidget* Widget::native_widget() {
return native_widget_.get();
}
void Widget::SetCapture(View* view) {
if (!native_widget_)
return;
if (!native_widget_->HasCapture()) {
native_widget_->SetCapture();
// Early return if setting capture was unsuccessful.
if (!native_widget_->HasCapture())
return;
}
if (native_widget_->IsMouseButtonDown())
is_mouse_button_pressed_ = true;
root_view_->SetMouseAndGestureHandler(view);
}
void Widget::ReleaseCapture() {
if (native_widget_ && native_widget_->HasCapture())
native_widget_->ReleaseCapture();
}
bool Widget::HasCapture() {
return native_widget_ ? native_widget_->HasCapture() : false;
}
TooltipManager* Widget::GetTooltipManager() {
return native_widget_ ? native_widget_->GetTooltipManager() : nullptr;
}
const TooltipManager* Widget::GetTooltipManager() const {
return native_widget_ ? native_widget_->GetTooltipManager() : nullptr;
}
gfx::Rect Widget::GetWorkAreaBoundsInScreen() const {
return native_widget_ ? native_widget_->GetWorkAreaBoundsInScreen()
: gfx::Rect();
}
void Widget::SynthesizeMouseMoveEvent() {
// In screen coordinate.
gfx::Point mouse_location =
display::Screen::GetScreen()->GetCursorScreenPoint();
if (!GetWindowBoundsInScreen().Contains(mouse_location))
return;
// Convert: screen coordinate -> widget coordinate.
View::ConvertPointFromScreen(root_view_.get(), &mouse_location);
last_mouse_event_was_move_ = false;
ui::MouseEvent mouse_event(ui::ET_MOUSE_MOVED, mouse_location, mouse_location,
ui::EventTimeForNow(), ui::EF_IS_SYNTHESIZED, 0);
root_view_->OnMouseMoved(mouse_event);
}
bool Widget::IsTranslucentWindowOpacitySupported() const {
return native_widget_ ? native_widget_->IsTranslucentWindowOpacitySupported()
: false;
}
ui::GestureRecognizer* Widget::GetGestureRecognizer() {
return native_widget_ ? native_widget_->GetGestureRecognizer() : nullptr;
}
ui::GestureConsumer* Widget::GetGestureConsumer() {
return native_widget_ ? native_widget_->GetGestureConsumer() : nullptr;
}
void Widget::OnSizeConstraintsChanged() {
if (native_widget_)
native_widget_->OnSizeConstraintsChanged();
if (non_client_view_)
non_client_view_->SizeConstraintsChanged();
}
void Widget::OnOwnerClosing() {}
std::string Widget::GetName() const {
return native_widget_ ? native_widget_->GetName() : "";
}
base::CallbackListSubscription Widget::RegisterPaintAsActiveChangedCallback(
PaintAsActiveCallbackList::CallbackType callback) {
return paint_as_active_callbacks_.Add(std::move(callback));
}
std::unique_ptr<Widget::PaintAsActiveLock> Widget::LockPaintAsActive() {
const bool was_paint_as_active = ShouldPaintAsActive();
++paint_as_active_refcount_;
if (ShouldPaintAsActive() != was_paint_as_active) {
NotifyPaintAsActiveChanged();
if (parent() && !parent_paint_as_active_lock_)
parent_paint_as_active_lock_ = parent()->LockPaintAsActive();
}
return std::make_unique<PaintAsActiveLockImpl>(
weak_ptr_factory_.GetWeakPtr());
}
base::WeakPtr<Widget> Widget::GetWeakPtr() {
return weak_ptr_factory_.GetWeakPtr();
}
bool Widget::ShouldPaintAsActive() const {
// A transient bubble hits this code path when it loses focus.
// Return false after Close() is called.
if (widget_closed_)
return false;
return native_widget_active_ || paint_as_active_refcount_ ||
(parent() && parent()->ShouldPaintAsActive());
}
void Widget::OnParentShouldPaintAsActiveChanged() {
// |native_widget_| has already been deleted and |this| is being deleted so
// that we don't have to handle the event and also it's unsafe to reference
// |native_widget_| in this case.
if (!native_widget_)
return;
// |native_widget_active| is being updated in
// OnNativeWidgetActivationChanged(). Notification will be handled there.
if (native_widget_active_ != native_widget_->IsActive())
return;
// this->ShouldPaintAsActive() changes iff the native widget is
// inactive and there's no lock on this widget.
if (!(native_widget_active_ || paint_as_active_refcount_))
NotifyPaintAsActiveChanged();
}
void Widget::NotifyPaintAsActiveChanged() {
paint_as_active_callbacks_.Notify();
if (native_widget_) {
native_widget_->PaintAsActiveChanged();
}
}
void Widget::SetNativeTheme(ui::NativeTheme* native_theme) {
native_theme_ = native_theme;
native_theme_observation_.Reset();
if (native_theme)
native_theme_observation_.Observe(native_theme);
ThemeChanged();
}
int Widget::GetX() const {
return GetRestoredBounds().x();
}
int Widget::GetY() const {
return GetRestoredBounds().y();
}
int Widget::GetWidth() const {
return GetRestoredBounds().width();
}
int Widget::GetHeight() const {
return GetRestoredBounds().height();
}
bool Widget::GetVisible() const {
return IsVisible();
}
void Widget::SetX(int x) {
gfx::Rect bounds = GetRestoredBounds();
if (x == bounds.x())
return;
bounds.set_x(x);
SetBounds(bounds);
}
void Widget::SetY(int y) {
gfx::Rect bounds = GetRestoredBounds();
if (y == bounds.y())
return;
bounds.set_y(y);
SetBounds(bounds);
}
void Widget::SetWidth(int width) {
gfx::Rect bounds = GetRestoredBounds();
if (width == bounds.width())
return;
bounds.set_width(width);
SetBounds(bounds);
}
void Widget::SetHeight(int height) {
gfx::Rect bounds = GetRestoredBounds();
if (height == bounds.height())
return;
bounds.set_height(height);
SetBounds(bounds);
}
void Widget::SetVisible(bool visible) {
if (visible == IsVisible())
return;
if (visible)
Show();
else
Hide();
}
////////////////////////////////////////////////////////////////////////////////
// Widget, NativeWidgetDelegate implementation:
bool Widget::IsModal() const {
if (!widget_delegate_)
return false;
return widget_delegate_->GetModalType() != ui::MODAL_TYPE_NONE;
}
bool Widget::IsDialogBox() const {
if (!widget_delegate_)
return false;
return !!widget_delegate_->AsDialogDelegate();
}
bool Widget::CanActivate() const {
// This may be called after OnNativeWidgetDestroyed(), which sets
// |widget_delegate_| to null.
return widget_delegate_ && widget_delegate_->CanActivate();
}
bool Widget::IsNativeWidgetInitialized() const {
return native_widget_initialized_;
}
bool Widget::OnNativeWidgetActivationChanged(bool active) {
if (!ShouldHandleNativeWidgetActivationChanged(active))
return false;
// On windows we may end up here before we've completed initialization (from
// an WM_NCACTIVATE). If that happens the WidgetDelegate likely doesn't know
// the Widget and will crash attempting to access it.
if (!active && native_widget_initialized_)
SaveWindowPlacement();
for (WidgetObserver& observer : observers_)
observer.OnWidgetActivationChanged(this, active);
const bool was_paint_as_active = ShouldPaintAsActive();
// Widgets in a widget tree should share the same ShouldPaintAsActive().
// Lock the parent as paint-as-active when this widget becomes active.
// If we're in the process of closing the widget, delay resetting the
// `parent_paint_as_active_lock_` until the owning native widget destroys this
// widget (i.e. wait until widget destruction). Do this as closing a widget
// may result in synchronously calling into this method, which can cause the
// parent to immediately paint as inactive. This is an issue if, after this
// widget has been closed, the parent widget is the next widget to receive
// activation. If using a desktop native widget, the next widget to receive
// activation may be determined by the system's window manager and this may
// not happen synchronously with closing the Widget. By waiting for the owning
// native widget to destroy this widget we ensure that resetting the paint
// lock happens synchronously with the activation the next widget (see
// crbug/1303549).
if (!active && !paint_as_active_refcount_ && !widget_closed_)
parent_paint_as_active_lock_.reset();
else if (parent())
parent_paint_as_active_lock_ = parent()->LockPaintAsActive();
native_widget_active_ = active;
// Notify controls (e.g. LabelButton) and children widgets about the
// paint-as-active change.
if (ShouldPaintAsActive() != was_paint_as_active)
NotifyPaintAsActiveChanged();
return true;
}
bool Widget::ShouldHandleNativeWidgetActivationChanged(bool active) {
return (g_disable_activation_change_handling_ !=
DisableActivationChangeHandlingType::kIgnore) &&
(g_disable_activation_change_handling_ !=
DisableActivationChangeHandlingType::kIgnoreDeactivationOnly ||
active);
}
void Widget::OnNativeFocus() {
WidgetFocusManager::GetInstance()->OnNativeFocusChanged(GetNativeView());
}
void Widget::OnNativeBlur() {
WidgetFocusManager::GetInstance()->OnNativeFocusChanged(nullptr);
}
void Widget::OnNativeWidgetVisibilityChanged(bool visible) {
View* root = GetRootView();
if (root)
root->PropagateVisibilityNotifications(root, visible);
for (WidgetObserver& observer : observers_)
observer.OnWidgetVisibilityChanged(this, visible);
if (GetCompositor() && root && root->layer())
root->layer()->SetVisible(visible);
}
void Widget::OnNativeWidgetCreated() {
if (is_top_level())
focus_manager_ = FocusManagerFactory::Create(this);
DCHECK(native_widget_);
DCHECK(widget_delegate_);
native_widget_->InitModalType(widget_delegate_->GetModalType());
for (WidgetObserver& observer : observers_)
observer.OnWidgetCreated(this);
}
void Widget::OnNativeWidgetDestroying() {
// Tell the focus manager (if any) that root_view is being removed
// in case that the focused view is under this root view.
DCHECK(native_widget_);
if (GetFocusManager() && root_view_)
GetFocusManager()->ViewRemoved(root_view_.get());
for (WidgetObserver& observer : observers_)
observer.OnWidgetDestroying(this);
if (non_client_view_)
non_client_view_->WindowClosing();
widget_delegate_->WindowClosing();
}
void Widget::OnNativeWidgetDestroyed() {
for (WidgetObserver& observer : observers_)
observer.OnWidgetDestroyed(this);
// TODO(kylixrd): Remove the references to owned_by_widget once widgets cease
// being able to "own" the delegate.
if (widget_delegate_) {
if (widget_delegate_->owned_by_widget()) {
widget_delegate_->DeleteDelegate();
widget_delegate_->can_delete_this_ = true;
owned_widget_delegate_.reset();
} else {
widget_delegate_->can_delete_this_ = true;
widget_delegate_->DeleteDelegate();
}
}
// Immediately reset the weak ptr. If NATIVE_WIDGET_OWNS_WIDGET destruction of
// the NativeWidget can destroy the Widget. We don't want to touch the
// NativeWidget during the destruction of the Widget either since some member
// variables on the NativeWidget may already be destroyed. In
// WIDGET_OWNS_NATIVE_WIDGET the NativeWidget will be cleaned up through
// |owned_native_widget_|
native_widget_.reset();
}
void Widget::OnNativeWidgetParentChanged(gfx::NativeView parent) {
Widget* parent_widget = parent ? GetWidgetForNativeView(parent) : nullptr;
SetParent(parent_widget);
}
gfx::Size Widget::GetMinimumSize() const {
gfx::Size size;
if (widget_delegate_->MaybeGetMinimumSize(&size))
return size;
return non_client_view_ ? non_client_view_->GetMinimumSize() : gfx::Size();
}
gfx::Size Widget::GetMaximumSize() const {
gfx::Size size;
if (widget_delegate_->MaybeGetMaximumSize(&size))
return size;
return non_client_view_ ? non_client_view_->GetMaximumSize() : gfx::Size();
}
void Widget::OnNativeWidgetMove() {
TRACE_EVENT0("ui", "Widget::OnNativeWidgetMove");
if (widget_delegate_)
widget_delegate_->OnWidgetMove();
NotifyCaretBoundsChanged(GetInputMethod());
for (WidgetObserver& observer : observers_)
observer.OnWidgetBoundsChanged(this, GetWindowBoundsInScreen());
}
void Widget::OnNativeWidgetSizeChanged(const gfx::Size& new_size) {
TRACE_EVENT0("ui", "Widget::OnNativeWidgetSizeChanged");
View* root = GetRootView();
if (root)
root->SetSize(new_size);
NotifyCaretBoundsChanged(GetInputMethod());
SaveWindowPlacementIfInitialized();
for (WidgetObserver& observer : observers_)
observer.OnWidgetBoundsChanged(this, GetWindowBoundsInScreen());
}
void Widget::OnNativeWidgetWorkspaceChanged() {}
void Widget::OnNativeWidgetWindowShowStateChanged() {
SaveWindowPlacementIfInitialized();
}
void Widget::OnNativeWidgetBeginUserBoundsChange() {
if (widget_delegate_)
widget_delegate_->OnWindowBeginUserBoundsChange();
}
void Widget::OnNativeWidgetEndUserBoundsChange() {
if (widget_delegate_)
widget_delegate_->OnWindowEndUserBoundsChange();
}
void Widget::OnNativeWidgetAddedToCompositor() {}
void Widget::OnNativeWidgetRemovingFromCompositor() {}
bool Widget::HasFocusManager() const {
return !!focus_manager_.get();
}
void Widget::OnNativeWidgetPaint(const ui::PaintContext& context) {
// On Linux Aura, we can get here during Init() because of the
// SetInitialBounds call.
if (!native_widget_initialized_)
return;
GetRootView()->PaintFromPaintRoot(context);
}
int Widget::GetNonClientComponent(const gfx::Point& point) {
int component =
non_client_view_ ? non_client_view_->NonClientHitTest(point) : HTNOWHERE;
if (movement_disabled_ && (component == HTCAPTION || component == HTSYSMENU))
return HTNOWHERE;
return component;
}
void Widget::OnKeyEvent(ui::KeyEvent* event) {
SendEventToSink(event);
if (!event->handled() && GetFocusManager() &&
!GetFocusManager()->OnKeyEvent(*event)) {
event->StopPropagation();
}
}
// TODO(tdanderson): We should not be calling the OnMouse*() functions on
// RootView from anywhere in Widget. Use
// SendEventToSink() instead. See crbug.com/348087.
void Widget::OnMouseEvent(ui::MouseEvent* event) {
if (!native_widget_)
return;
TRACE_EVENT0("ui", "Widget::OnMouseEvent");
View* root_view = GetRootView();
switch (event->type()) {
case ui::ET_MOUSE_PRESSED: {
last_mouse_event_was_move_ = false;
// We may get deleted by the time we return from OnMousePressed. So we
// use an observer to make sure we are still alive.
WidgetDeletionObserver widget_deletion_observer(this);
gfx::NativeView current_capture =
internal::NativeWidgetPrivate::GetGlobalCapture(
native_widget_->GetNativeView());
// Make sure we're still visible before we attempt capture as the mouse
// press processing may have made the window hide (as happens with menus).
//
// It is possible that capture has changed as a result of a mouse-press.
// In these cases do not update internal state.
//
// A mouse-press may trigger a nested message-loop, and absorb the paired
// release. If so the code returns here. So make sure that that
// mouse-button is still down before attempting to do a capture.
if (root_view && root_view->OnMousePressed(*event) &&
widget_deletion_observer.IsWidgetAlive() && IsVisible() &&
native_widget_->IsMouseButtonDown() &&
current_capture == internal::NativeWidgetPrivate::GetGlobalCapture(
native_widget_->GetNativeView())) {
is_mouse_button_pressed_ = true;
if (!native_widget_->HasCapture())
native_widget_->SetCapture();
event->SetHandled();
}
return;
}
case ui::ET_MOUSE_RELEASED:
last_mouse_event_was_move_ = false;
is_mouse_button_pressed_ = false;
// Release capture first, to avoid confusion if OnMouseReleased blocks.
if (auto_release_capture_ && native_widget_->HasCapture()) {
base::AutoReset<bool> resetter(&ignore_capture_loss_, true);
native_widget_->ReleaseCapture();
}
if (root_view)
root_view->OnMouseReleased(*event);
if ((event->flags() & ui::EF_IS_NON_CLIENT) == 0 &&
// If none of the "normal" buttons are pressed, this event may be from
// one of the newer mice that have buttons bound to browser forward
// back actions. Don't squelch the event and let the default handler
// process it.
(event->flags() &
(ui::EF_LEFT_MOUSE_BUTTON | ui::EF_MIDDLE_MOUSE_BUTTON |
ui::EF_RIGHT_MOUSE_BUTTON)) != 0)
event->SetHandled();
return;
case ui::ET_MOUSE_MOVED:
case ui::ET_MOUSE_DRAGGED:
if (native_widget_->HasCapture() && is_mouse_button_pressed_) {
last_mouse_event_was_move_ = false;
if (root_view)
root_view->OnMouseDragged(*event);
} else if (!last_mouse_event_was_move_ ||
last_mouse_event_position_ != event->location()) {
last_mouse_event_position_ = event->location();
last_mouse_event_was_move_ = true;
if (root_view)
root_view->OnMouseMoved(*event);
}
return;
case ui::ET_MOUSE_EXITED:
last_mouse_event_was_move_ = false;
if (root_view)
root_view->OnMouseExited(*event);
return;
case ui::ET_MOUSEWHEEL:
if (root_view && root_view->OnMouseWheel(
static_cast<const ui::MouseWheelEvent&>(*event)))
event->SetHandled();
return;
default:
return;
}
}
void Widget::OnMouseCaptureLost() {
if (ignore_capture_loss_)
return;
View* root_view = GetRootView();
if (root_view)
root_view->OnMouseCaptureLost();
is_mouse_button_pressed_ = false;
}
void Widget::OnScrollEvent(ui::ScrollEvent* event) {
ui::ScrollEvent event_copy(*event);
SendEventToSink(&event_copy);
// Convert unhandled ui::ET_SCROLL events into ui::ET_MOUSEWHEEL events.
if (!event_copy.handled() && event_copy.type() == ui::ET_SCROLL) {
ui::MouseWheelEvent wheel(*event);
OnMouseEvent(&wheel);
}
}
void Widget::OnGestureEvent(ui::GestureEvent* event) {
// We explicitly do not capture here. Not capturing enables multiple widgets
// to get tap events at the same time. Views (such as tab dragging) may
// explicitly capture.
SendEventToSink(event);
}
bool Widget::ExecuteCommand(int command_id) {
if (!widget_delegate_)
return false;
return widget_delegate_->ExecuteWindowsCommand(command_id);
}
bool Widget::HasHitTestMask() const {
if (!widget_delegate_)
return false;
return widget_delegate_->WidgetHasHitTestMask();
}
void Widget::GetHitTestMask(SkPath* mask) const {
if (!widget_delegate_)
return;
DCHECK(mask);
widget_delegate_->GetWidgetHitTestMask(mask);
}
Widget* Widget::AsWidget() {
return this;
}
const Widget* Widget::AsWidget() const {
return this;
}
bool Widget::SetInitialFocus(ui::WindowShowState show_state) {
FocusManager* focus_manager = GetFocusManager();
if (!focus_manager || !widget_delegate_)
return false;
View* v = widget_delegate_->GetInitiallyFocusedView();
if (!focus_on_creation_ || show_state == ui::SHOW_STATE_INACTIVE ||
show_state == ui::SHOW_STATE_MINIMIZED) {
// If not focusing the window now, tell the focus manager which view to
// focus when the window is restored.
if (v)
focus_manager->SetStoredFocusView(v);
return true;
}
if (v) {
v->RequestFocus();
// If the Widget is active (thus allowing its child Views to receive focus),
// but the request for focus was unsuccessful, fall back to using the first
// focusable View instead.
if (focus_manager->GetFocusedView() == nullptr && IsActive())
focus_manager->AdvanceFocus(false);
}
return !!focus_manager->GetFocusedView();
}
bool Widget::ShouldDescendIntoChildForEventHandling(
ui::Layer* root_layer,
gfx::NativeView child,
ui::Layer* child_layer,
const gfx::Point& location) {
if (widget_delegate_ &&
!widget_delegate_->ShouldDescendIntoChildForEventHandling(child,
location)) {
return false;
}
const View::Views& views_with_layers = GetViewsWithLayers();
if (views_with_layers.empty())
return true;
// Don't descend into |child| if there is a view with a Layer that contains
// the point and is stacked above |child_layer|.
auto child_layer_iter =
base::ranges::find(root_layer->children(), child_layer);
if (child_layer_iter == root_layer->children().end())
return true;
for (View* view : base::Reversed(views_with_layers)) {
// Skip views that don't process events.
if (!view->GetCanProcessEventsWithinSubtree())
continue;
ui::Layer* layer = view->layer();
DCHECK(layer);
if (layer->visible() && layer->bounds().Contains(location)) {
auto root_layer_iter = base::ranges::find(root_layer->children(), layer);
if (child_layer_iter > root_layer_iter) {
// |child| is on top of the remaining layers, no need to continue.
return true;
}
// TODO(pbos): Does this need to be made more robust through hit testing
// or using ViewTargeter? This for instance does not take into account
// whether the view is enabled/drawn/etc.
//
// Event targeting uses the visible bounds of the View, which may differ
// from the bounds of the layer. Verify the view hosting the layer
// actually contains |location|. Use GetVisibleBounds(), which is
// effectively what event targetting uses.
gfx::Rect vis_bounds = view->GetVisibleBounds();
gfx::Point point_in_view = location;
View::ConvertPointToTarget(GetRootView(), view, &point_in_view);
if (vis_bounds.Contains(point_in_view))
return false;
}
}
return true;
}
void Widget::LayoutRootViewIfNecessary() {
if (root_view_ && root_view_->needs_layout())
root_view_->Layout();
}
////////////////////////////////////////////////////////////////////////////////
// Widget, ui::EventSource implementation:
ui::EventSink* Widget::GetEventSink() {
return root_view_.get();
}
////////////////////////////////////////////////////////////////////////////////
// Widget, FocusTraversable implementation:
FocusSearch* Widget::GetFocusSearch() {
return root_view_->GetFocusSearch();
}
FocusTraversable* Widget::GetFocusTraversableParent() {
// We are a proxy to the root view, so we should be bypassed when traversing
// up and as a result this should not be called.
NOTREACHED_NORETURN();
}
View* Widget::GetFocusTraversableParentView() {
// We are a proxy to the root view, so we should be bypassed when traversing
// up and as a result this should not be called.
NOTREACHED_NORETURN();
}
////////////////////////////////////////////////////////////////////////////////
// Widget, ui::NativeThemeObserver implementation:
void Widget::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) {
TRACE_EVENT0("ui", "Widget::OnNativeThemeUpdated");
ThemeChanged();
}
void Widget::SetColorModeOverride(
absl::optional<ui::ColorProviderManager::ColorMode> color_mode) {
color_mode_override_ = color_mode;
}
////////////////////////////////////////////////////////////////////////////////
// Widget, ui::ColorProviderSource:
ui::ColorProviderManager::Key Widget::GetColorProviderKey() const {
ui::ColorProviderManager::Key key =
GetNativeTheme()->GetColorProviderKey(GetCustomTheme());
#if BUILDFLAG(IS_CHROMEOS_ASH)
key.elevation_mode = background_elevation_;
#endif
key.user_color = GetUserColor();
if (color_mode_override_) {
key.color_mode = color_mode_override_.value();
}
return key;
}
absl::optional<SkColor> Widget::GetUserColor() const {
// Fall back to the user color defined in the NativeTheme if a user color is
// not provided by any widgets in this UI hierarchy.
return parent_ ? parent_->GetUserColor() : GetNativeTheme()->user_color();
}
const ui::ColorProvider* Widget::GetColorProvider() const {
return ui::ColorProviderManager::Get().GetColorProviderFor(
GetColorProviderKey());
}
////////////////////////////////////////////////////////////////////////////////
// Widget, protected:
internal::RootView* Widget::CreateRootView() {
return new internal::RootView(this);
}
void Widget::DestroyRootView() {
ClearFocusFromWidget();
NotifyWillRemoveView(root_view_.get());
non_client_view_ = nullptr;
// Remove all children before the unique_ptr reset so that
// GetWidget()->GetRootView() doesn't return nullptr while the views hierarchy
// is being torn down.
root_view_->RemoveAllChildViews();
root_view_.reset();
}
void Widget::OnDragWillStart() {}
void Widget::OnDragComplete() {}
const ui::NativeTheme* Widget::GetNativeTheme() const {
if (native_theme_)
return native_theme_;
if (parent_)
return parent_->GetNativeTheme();
#if BUILDFLAG(IS_LINUX)
if (auto* linux_ui_theme = ui::LinuxUiTheme::GetForWindow(GetNativeWindow()))
return linux_ui_theme->GetNativeTheme();
#endif
return ui::NativeTheme::GetInstanceForNativeUi();
}
////////////////////////////////////////////////////////////////////////////////
// Widget, private:
void Widget::SaveWindowPlacement() {
// The window delegate does the actual saving for us. It seems like (judging
// by go/crash) that in some circumstances we can end up here after
// WM_DESTROY, at which point the window delegate is likely gone. So just
// bail.
if (!widget_delegate_ || !widget_delegate_->ShouldSaveWindowPlacement() ||
!native_widget_)
return;
ui::WindowShowState show_state = ui::SHOW_STATE_NORMAL;
gfx::Rect bounds;
native_widget_->GetWindowPlacement(&bounds, &show_state);
widget_delegate_->SaveWindowPlacement(bounds, show_state);
}
void Widget::SaveWindowPlacementIfInitialized() {
if (native_widget_initialized_)
SaveWindowPlacement();
}
void Widget::SetInitialBounds(const gfx::Rect& bounds) {
if (!non_client_view_)
return;
gfx::Rect saved_bounds;
if (GetSavedWindowPlacement(&saved_bounds, &saved_show_state_)) {
if (saved_show_state_ == ui::SHOW_STATE_MAXIMIZED) {
// If we're going to maximize, wait until Show is invoked to set the
// bounds. That way we avoid a noticeable resize.
initial_restored_bounds_ = saved_bounds;
} else if (!saved_bounds.IsEmpty()) {
// If the saved bounds are valid, use them.
SetBounds(saved_bounds);
}
} else {
if (bounds.IsEmpty()) {
if (bounds.origin().IsOrigin()) {
// No initial bounds supplied, so size the window to its content and
// center over its parent.
CenterWindow(non_client_view_->GetPreferredSize());
} else {
// Use the preferred size and the supplied origin.
gfx::Rect preferred_bounds(bounds);
preferred_bounds.set_size(non_client_view_->GetPreferredSize());
SetBoundsConstrained(preferred_bounds);
}
} else {
// Use the supplied initial bounds.
SetBoundsConstrained(bounds);
}
}
}
void Widget::SetInitialBoundsForFramelessWindow(const gfx::Rect& bounds) {
if (bounds.IsEmpty()) {
View* contents_view = GetContentsView();
DCHECK(contents_view);
// No initial bounds supplied, so size the window to its content and
// center over its parent if preferred size is provided.
gfx::Size size = contents_view->GetPreferredSize();
if (!size.IsEmpty() && native_widget_)
native_widget_->CenterWindow(size);
} else {
// Use the supplied initial bounds.
SetBounds(bounds);
}
}
void Widget::SetParent(Widget* parent) {
if (parent == parent_.get())
return;
Widget* old_parent = parent_.get();
parent_ = parent ? parent->GetWeakPtr() : nullptr;
// Release the paint-as-active lock on the old parent.
bool has_lock_on_parent = !!parent_paint_as_active_lock_;
parent_paint_as_active_lock_.reset();
parent_paint_as_active_subscription_ = base::CallbackListSubscription();
// Lock and subscribe to parent's paint-as-active.
if (parent) {
if (has_lock_on_parent || native_widget_active_)
parent_paint_as_active_lock_ = parent->LockPaintAsActive();
parent_paint_as_active_subscription_ =
parent->RegisterPaintAsActiveChangedCallback(
base::BindRepeating(&Widget::OnParentShouldPaintAsActiveChanged,
base::Unretained(this)));
}
if (base::FeatureList::IsEnabled(features::kWidgetLayering)) {
if (old_parent)
old_parent->GetSublevelManager()->UntrackChildWidget(this);
if (parent)
parent->GetSublevelManager()->TrackChildWidget(this);
}
}
bool Widget::GetSavedWindowPlacement(gfx::Rect* bounds,
ui::WindowShowState* show_state) {
// First we obtain the window's saved show-style and store it. We need to do
// this here, rather than in Show() because by the time Show() is called,
// the window's size will have been reset (below) and the saved maximized
// state will have been lost. Sadly there's no way to tell on Windows when
// a window is restored from maximized state, so we can't more accurately
// track maximized state independently of sizing information.
if (!widget_delegate_->GetSavedWindowPlacement(this, bounds, show_state))
return false;
gfx::Size minimum_size = GetMinimumSize();
// Make sure the bounds are at least the minimum size.
if (bounds->width() < minimum_size.width())
bounds->set_width(minimum_size.width());
if (bounds->height() < minimum_size.height())
bounds->set_height(minimum_size.height());
return true;
}
const View::Views& Widget::GetViewsWithLayers() {
if (views_with_layers_dirty_) {
views_with_layers_dirty_ = false;
views_with_layers_.clear();
BuildViewsWithLayers(GetRootView(), &views_with_layers_);
}
return views_with_layers_;
}
void Widget::UnlockPaintAsActive() {
const bool was_paint_as_active = ShouldPaintAsActive();
DCHECK_GT(paint_as_active_refcount_, 0U);
--paint_as_active_refcount_;
if (!paint_as_active_refcount_ && !native_widget_active_)
parent_paint_as_active_lock_.reset();
if (ShouldPaintAsActive() != was_paint_as_active)
NotifyPaintAsActiveChanged();
}
void Widget::ClearFocusFromWidget() {
FocusManager* focus_manager = GetFocusManager();
// We are being removed from a window hierarchy. Treat this as
// the root_view_ being removed.
if (focus_manager)
focus_manager->ViewRemoved(root_view_.get());
}
void Widget::HandleShowRequested() {
if (base::FeatureList::IsEnabled(features::kWidgetLayering))
sublevel_manager_->EnsureOwnerSublevel();
internal::AnyWidgetObserverSingleton::GetInstance()->OnAnyWidgetShown(this);
}
BEGIN_METADATA_BASE(Widget)
ADD_READONLY_PROPERTY_METADATA(const char*, ClassName)
ADD_READONLY_PROPERTY_METADATA(gfx::Rect, ClientAreaBoundsInScreen)
ADD_READONLY_PROPERTY_METADATA(std::string, Name)
ADD_READONLY_PROPERTY_METADATA(gfx::Rect, RestoredBounds)
ADD_READONLY_PROPERTY_METADATA(gfx::Rect, WindowBoundsInScreen)
ADD_PROPERTY_METADATA(int, X)
ADD_PROPERTY_METADATA(int, Y)
ADD_PROPERTY_METADATA(int, Width)
ADD_PROPERTY_METADATA(int, Height)
ADD_PROPERTY_METADATA(bool, Visible)
ADD_PROPERTY_METADATA(ui::ZOrderLevel, ZOrderLevel)
END_METADATA
namespace internal {
////////////////////////////////////////////////////////////////////////////////
// internal::NativeWidgetPrivate, NativeWidget implementation:
internal::NativeWidgetPrivate* NativeWidgetPrivate::AsNativeWidgetPrivate() {
return this;
}
} // namespace internal
} // namespace views
DEFINE_ENUM_CONVERTERS(ui::ZOrderLevel,
{ui::ZOrderLevel::kNormal, u"kNormal"},
{ui::ZOrderLevel::kFloatingWindow, u"kFloatingWindow"},
{ui::ZOrderLevel::kFloatingUIElement,
u"kFloatingUIElement"},
{ui::ZOrderLevel::kSecuritySurface, u"kSecuritySurface"})
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/widget.cc | C++ | unknown | 73,037 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_WIDGET_WIDGET_H_
#define UI_VIEWS_WIDGET_WIDGET_H_
#include <memory>
#include <set>
#include <string>
#include <vector>
#include "base/callback_list.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/observer_list.h"
#include "base/scoped_observation.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "ui/base/dragdrop/mojom/drag_drop_types.mojom-forward.h"
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/base/metadata/metadata_types.h"
#include "ui/base/ui_base_types.h"
#include "ui/color/color_provider_manager.h"
#include "ui/color/color_provider_source.h"
#include "ui/display/types/display_constants.h"
#include "ui/events/event_source.h"
#include "ui/gfx/geometry/rect.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/native_theme/native_theme.h"
#include "ui/native_theme/native_theme_observer.h"
#include "ui/views/focus/focus_manager.h"
#include "ui/views/widget/native_widget_delegate.h"
#include "ui/views/window/client_view.h"
#include "ui/views/window/non_client_view.h"
namespace base {
class TimeDelta;
}
namespace gfx {
class Point;
class Rect;
} // namespace gfx
namespace ui {
class Accelerator;
class ColorProvider;
class Compositor;
class GestureRecognizer;
class InputMethod;
class Layer;
class OSExchangeData;
class ThemeProvider;
} // namespace ui
namespace ui_devtools {
class PageAgentViews;
}
namespace views {
class DesktopWindowTreeHost;
class NativeWidget;
class NonClientFrameView;
class SublevelManager;
class TooltipManager;
class View;
class WidgetDelegate;
class WidgetObserver;
class WidgetRemovalsObserver;
namespace internal {
class NativeWidgetPrivate;
class RootView;
} // namespace internal
enum class CloseRequestResult { kCanClose, kCannotClose };
////////////////////////////////////////////////////////////////////////////////
// Widget class
//
// Encapsulates the platform-specific rendering, event receiving and widget
// management aspects of the UI framework.
//
// Owns a RootView and thus a View hierarchy. Can contain child Widgets.
// Widget is a platform-independent type that communicates with a platform or
// context specific NativeWidget implementation.
//
// A special note on ownership:
//
// Depending on the value of the InitParams' ownership field, the Widget
// either owns or is owned by its NativeWidget:
//
// ownership = NATIVE_WIDGET_OWNS_WIDGET (default)
// The Widget instance is owned by its NativeWidget. When the NativeWidget
// is destroyed (in response to a native destruction message), it deletes
// the Widget from its destructor.
// ownership = WIDGET_OWNS_NATIVE_WIDGET (non-default)
// The Widget instance owns its NativeWidget. This state implies someone
// else wants to control the lifetime of this object. When they destroy
// the Widget it is responsible for destroying the NativeWidget (from its
// destructor). This is often used to place a Widget in a std::unique_ptr<>
// or on the stack in a test.
class VIEWS_EXPORT Widget : public internal::NativeWidgetDelegate,
public ui::EventSource,
public FocusTraversable,
public ui::NativeThemeObserver,
public ui::ColorProviderSource,
public ui::metadata::MetaDataProvider {
public:
METADATA_HEADER_BASE(Widget);
using Widgets = std::set<Widget*>;
using ShapeRects = std::vector<gfx::Rect>;
using PaintAsActiveCallbackList = base::RepeatingClosureList;
enum class FrameType {
kDefault, // Use whatever the default would be.
kForceCustom, // Force the custom frame.
kForceNative // Force the native frame.
};
// Result from RunMoveLoop().
enum class MoveLoopResult {
// The move loop completed successfully.
kSuccessful,
// The user canceled the move loop.
kCanceled
};
// Source that initiated the move loop.
enum class MoveLoopSource {
kMouse,
kTouch,
};
// Behavior when escape is pressed during a move loop.
enum class MoveLoopEscapeBehavior {
// Indicates the window should be hidden.
kHide,
// Indicates the window should not be hidden.
kDontHide,
};
// Type of visibility change transition that should animate.
enum VisibilityTransition {
ANIMATE_SHOW = 0x1,
ANIMATE_HIDE = 0x2,
ANIMATE_BOTH = ANIMATE_SHOW | ANIMATE_HIDE,
ANIMATE_NONE = 0x4,
};
// Represents the reason a Widget was closed, if it is known.
//
// For backwards compatibility, we default to kUnspecified when
// Widget::Close() is called. Note that we do not currently handle close
// reason for menu or for the main Chrome browser, as we have no reason to
// specifically differentiate those yet.
//
// Add additional values as needed. Do not change any existing values, as this
// enum is logged to UMA.
enum class ClosedReason {
kUnspecified = 0, // No reason was given for the widget closing.
kEscKeyPressed = 1, // The ESC key was pressed to cancel the widget.
kCloseButtonClicked = 2, // The [X] button was explicitly clicked.
kLostFocus = 3, // The widget destroyed itself when it lost focus.
kCancelButtonClicked = 4, // The widget's cancel button was clicked.
kAcceptButtonClicked = 5, // The widget's done/accept button was clicked.
kMaxValue = kAcceptButtonClicked
};
struct VIEWS_EXPORT InitParams {
enum Type {
TYPE_WINDOW, // A decorated Window, like a frame window.
// Widgets of TYPE_WINDOW will have a NonClientView.
TYPE_WINDOW_FRAMELESS, // An undecorated Window.
TYPE_CONTROL, // A control, like a button.
TYPE_POPUP, // An undecorated Window, with transient properties.
TYPE_MENU, // An undecorated Window, with transient properties
// specialized to menus.
TYPE_TOOLTIP,
TYPE_BUBBLE,
TYPE_DRAG, // An undecorated Window, used during a drag-and-drop to
// show the drag image.
};
enum class WindowOpacity {
// Infer fully opaque or not. For WinAura, top-level windows that are not
// of TYPE_WINDOW are translucent so that they can be made to fade in.
// For LinuxAura, only windows that are TYPE_DRAG are translucent. In all
// other cases, windows are fully opaque.
kInferred,
// Fully opaque.
kOpaque,
// Possibly translucent/transparent. Widgets that fade in or out using
// SetOpacity() but do not make use of an alpha channel should use
// kInferred.
kTranslucent,
};
enum class Activatable {
// Infer whether the window should be activatable from the window type.
kDefault,
kYes,
kNo
};
enum Ownership {
// Default. Creator is not responsible for managing the lifetime of the
// Widget, it is destroyed when the corresponding NativeWidget is
// destroyed.
NATIVE_WIDGET_OWNS_WIDGET,
// Used when the Widget is owned by someone other than the NativeWidget,
// e.g. a scoped_ptr in tests. Production use is discouraged because the
// Widget API might become unsafe after the platform window is closed.
WIDGET_OWNS_NATIVE_WIDGET,
// NOT READY FOR PRODUCTION USE.
// This is intended to be a safe replacement for
// WIDGET_OWNS_NATIVE_WIDGET.
// The NativeWidget will be closed along with the platform window.
CLIENT_OWNS_WIDGET
};
enum class ShadowType {
kDefault, // Use default shadow setting. It will be one of
// the settings below depending on InitParams::type
// and the native widget's type.
kNone, // Don't draw any shadow.
kDrop, // Draw a drop shadow that emphasizes Z-order
// relationship to other windows.
};
// Default initialization with |type| set to TYPE_WINDOW.
InitParams();
// Initialization for other |type| types.
explicit InitParams(Type type);
InitParams(InitParams&& other);
~InitParams();
InitParams& operator=(InitParams&& rhs) = default;
// Returns the activatablity based on |activatable|, but also handles the
// case where |activatable| is |kDefault|.
bool CanActivate() const;
// Returns the z-order level, based on the overriding |z_order| but also
// taking into account special levels due to |type|.
ui::ZOrderLevel EffectiveZOrderLevel() const;
Type type = TYPE_WINDOW;
// If null, a default implementation will be constructed. The default
// implementation deletes itself when the Widget closes.
raw_ptr<WidgetDelegate> delegate = nullptr;
// Internal name. Propagated to the NativeWidget. Useful for debugging.
std::string name;
// False if this widget behaves like a top-level widget, true otherwise. A
// top-level widget has its own focus and IME state, independent of any
// other widget. A widget for which child is true should have a parent; if
// it doesn't, it will not handle keyboard events or IME input at all.
// TODO(https://crbug.com/1057758): DCHECK(parent || !child)
bool child = false;
// If kTranslucent, the widget may be fully or partially transparent.
// If kOpaque, we can perform optimizations based on the widget being fully
// opaque. Default is based on ViewsDelegate::GetOpacityForInitParams().
// Defaults to kOpaque for non-window widgets. Translucent windows may not
// always be supported. Use IsTranslucentWindowOpacitySupported() to
// determine whether they are.
WindowOpacity opacity = WindowOpacity::kInferred;
bool accept_events = true;
Activatable activatable = Activatable::kDefault;
// The class of window and its overall z-order level. This level is visible
// to other applications in the system. A value other than `kNormal` will
// create an "always on top" widget.
absl::optional<ui::ZOrderLevel> z_order;
// The z-order sublevel that is invisible to other applications in the
// system. Widgets of the same `z_order` are stacked in the order specified
// by their sub-levels.
int sublevel = 0;
bool visible_on_all_workspaces = false;
// See Widget class comment above.
Ownership ownership = NATIVE_WIDGET_OWNS_WIDGET;
bool mirror_origin_in_rtl = false;
ShadowType shadow_type = ShadowType::kDefault;
// A hint about the size of the shadow if the type is ShadowType::kDrop. May
// be ignored on some platforms. No value indicates no preference.
absl::optional<int> shadow_elevation;
#if BUILDFLAG(IS_CHROMEOS_ASH)
ui::ColorProviderManager::ElevationMode background_elevation =
ui::ColorProviderManager::ElevationMode::kLow;
#endif
// The window corner radius. May be ignored on some platforms.
absl::optional<int> corner_radius;
// Specifies that the system default caption and icon should not be
// rendered, and that the client area should be equivalent to the window
// area. Only used on some platforms (Windows and Linux).
bool remove_standard_frame = false;
// Only used by ShellWindow on Windows. Specifies that the default icon of
// packaged app should be the system default icon.
bool use_system_default_icon = false;
// Whether the widget should be maximized or minimized.
ui::WindowShowState show_state = ui::SHOW_STATE_DEFAULT;
// The native *view* (not native *window*) to which this widget should be
// parented. If this widget has a parent, then:
// * If that parent closes, this widget is closed too
// * If that parent is hidden, this widget is hidden too
// * This widget is stacked above the parent widget (always on Mac, usually
// elsewhere)
// * This widget's initial bounds are constrained to the parent widget's
// bounds, which prevents window restoration from placing windows
// offscreen
// Note: on some platforms (Mac) this directly implies a parent-child
// relationship in the backing native windows, but on Aura platforms it does
// not necessarily.
//
// Windows with no parent window are permitted, although in Aura these
// windows instead need a "context". On Aura systems, if a widget has no
// parent set, its backing aura::Window is parented to the Aura root window.
//
// TODO(https://crbug.com/1057758): It makes no sense that this is a
// NativeView instead of a NativeWindow. On Aura, NativeView and
// NativeWindow are synonyms, and NativeWidgetAura immediately treats the
// provided NativeView as an aura::Window; on Mac, the NativeView is
// immediately converted to an NSWindow (ie a gfx::NativeWindow) and used
// that way throughout. This should simply be a NativeWindow - windows are
// parented to other windows, not to views, and it being a view confuses
// the concept with bubble anchoring a la BubbleDialogDelegateView.
gfx::NativeView parent = nullptr;
gfx::AcceleratedWidget parent_widget = gfx::kNullAcceleratedWidget;
// Specifies the initial bounds of the Widget. Default is empty, which means
// the NativeWidget may specify a default size. If the parent is specified,
// |bounds| is in the parent's coordinate system. If the parent is not
// specified, it's in screen's global coordinate system.
gfx::Rect bounds;
// The initial workspace of the Widget. Default is "", which means the
// current workspace.
std::string workspace;
// If set, this value is used as the Widget's NativeWidget implementation.
// The Widget will not construct a default one.
raw_ptr<NativeWidget> native_widget = nullptr;
// Aura-only. Provides a DesktopWindowTreeHost implementation to use instead
// of the default one.
// TODO(beng): Figure out if there's a better way to expose this, e.g. get
// rid of NW subclasses and do this all via message handling.
// DanglingUntriaged because it is assigned a DanglingUntriaged pointer.
raw_ptr<DesktopWindowTreeHost, DanglingUntriaged> desktop_window_tree_host =
nullptr;
// Only used by NativeWidgetAura. Specifies the type of layer for the
// aura::Window.
ui::LayerType layer_type = ui::LAYER_TEXTURED;
// Only used by Aura. Provides a context window whose RootWindow is
// consulted during widget creation to determine where in the Window
// hierarchy this widget should be placed. (This is separate from |parent|;
// if you pass a RootWindow to |parent|, your window will be parented to
// |parent|. If you pass a RootWindow to |context|, we ask that RootWindow
// where it wants your window placed.) Nullptr is not allowed on Windows and
// Linux. Nullptr is allowed on Chrome OS, which will place the window on
// the default desktop for new windows.
gfx::NativeWindow context = nullptr;
// If true, forces the window to be shown in the taskbar, even for window
// types that do not appear in the taskbar by default (popup and bubble).
bool force_show_in_taskbar = false;
// Only used by X11, for root level windows. Specifies the res_name and
// res_class fields, respectively, of the WM_CLASS window property. Controls
// window grouping and desktop file matching in Linux window managers.
std::string wm_role_name;
std::string wm_class_name;
std::string wm_class_class;
// Only used by Wayland, for root level windows.
std::string wayland_app_id;
// If true then the widget uses software compositing.
bool force_software_compositing = false;
// If set, mouse events will be sent to the widget even if inactive.
bool wants_mouse_events_when_inactive = false;
// If set, the widget was created in headless mode.
bool headless_mode = false;
#if defined(USE_AURA) && (BUILDFLAG(IS_LINUX) || \
BUILDFLAG(IS_CHROMEOS_LACROS) || BUILDFLAG(IS_OHOS))
// Indicates whether the desktop native widget is required for the widget.
// This may enforce changing the type of the underlying platform window.
// See crbug.com/1280332
bool requires_accelerated_widget = false;
#endif
#if BUILDFLAG(IS_CHROMEOS_LACROS)
// TODO(crbug.com/1327490): Rename restore info variables.
// Only used by Wayland. Specifies the session id window key, the restore
// window id, and the app id, respectively, respectively, used by the
// compositor to restore window state upon creation. Only one of
// `restore_window_id` and `restore_window_id_source` should be set, as
// `restore_window_id_source` is used for widgets without inherent restore
// window ids, e.g. Chrome apps.
int32_t restore_session_id = 0;
absl::optional<int32_t> restore_window_id;
absl::optional<std::string> restore_window_id_source;
#endif
// Contains any properties with which the native widget should be
// initialized prior to adding it to the window hierarchy. All the
// properties in |init_properties_container| will be moved to the native
// widget.
ui::PropertyHandler init_properties_container;
#if BUILDFLAG(IS_OZONE)
// Only used by Wayland for root level windows. Specifies whether this
// window should request the wayland compositor to send key events,
// even if it matches with the compositor's keyboard shortcuts.
bool inhibit_keyboard_shortcuts = false;
#endif
};
// Represents a lock held on the widget's ShouldPaintAsActive() state. As
// long as at least one lock is held, the widget will paint as active.
// Multiple locks can exist for the same widget, and a lock can outlive its
// associated widget. See Widget::LockPaintAsActive().
class PaintAsActiveLock {
public:
PaintAsActiveLock(const PaintAsActiveLock&) = delete;
PaintAsActiveLock& operator=(const PaintAsActiveLock&) = delete;
virtual ~PaintAsActiveLock();
protected:
PaintAsActiveLock();
};
Widget();
explicit Widget(InitParams params);
Widget(const Widget&) = delete;
Widget& operator=(const Widget&) = delete;
~Widget() override;
// Creates a decorated window Widget with the specified properties. The
// returned Widget is owned by its NativeWidget; see Widget class comment for
// details.
// The std::unique_ptr variant requires that delegate->owned_by_widget().
static Widget* CreateWindowWithParent(WidgetDelegate* delegate,
gfx::NativeView parent,
const gfx::Rect& bounds = gfx::Rect());
static Widget* CreateWindowWithParent(
std::unique_ptr<WidgetDelegate> delegate,
gfx::NativeView parent,
const gfx::Rect& bounds = gfx::Rect());
// Creates a decorated window Widget in the same desktop context as |context|.
// The returned Widget is owned by its NativeWidget; see Widget class comment
// for details.
// The std::unique_ptr variant requires that delegate->owned_by_widget().
static Widget* CreateWindowWithContext(WidgetDelegate* delegate,
gfx::NativeWindow context,
const gfx::Rect& bounds = gfx::Rect());
static Widget* CreateWindowWithContext(
std::unique_ptr<WidgetDelegate> delegate,
gfx::NativeWindow context,
const gfx::Rect& bounds = gfx::Rect());
// Closes all Widgets that aren't identified as "secondary widgets". Called
// during application shutdown when the last non-secondary widget is closed.
static void CloseAllSecondaryWidgets();
// Retrieves the Widget implementation associated with the given
// NativeView or Window, or NULL if the supplied handle has no associated
// Widget.
static Widget* GetWidgetForNativeView(gfx::NativeView native_view);
static Widget* GetWidgetForNativeWindow(gfx::NativeWindow native_window);
// Retrieves the top level widget in a native view hierarchy
// starting at |native_view|. Top level widget is a widget with TYPE_WINDOW,
// TYPE_PANEL, TYPE_WINDOW_FRAMELESS, POPUP or MENU and has its own
// focus manager. This may be itself if the |native_view| is top level,
// or NULL if there is no toplevel in a native view hierarchy.
static Widget* GetTopLevelWidgetForNativeView(gfx::NativeView native_view);
// Returns all Widgets in |native_view|'s hierarchy, including itself if
// it is one.
static void GetAllChildWidgets(gfx::NativeView native_view,
Widgets* children);
// Returns all Widgets owned by |native_view| (including child widgets, but
// not including itself).
static void GetAllOwnedWidgets(gfx::NativeView native_view, Widgets* owned);
// Re-parent a NativeView and notify all Widgets in |native_view|'s hierarchy
// of the change.
static void ReparentNativeView(gfx::NativeView native_view,
gfx::NativeView new_parent);
// Returns the preferred size of the contents view of this window based on
// its localized size data. The width in cols is held in a localized string
// resource identified by |col_resource_id|, the height in the same fashion.
// TODO(beng): This should eventually live somewhere else, probably closer to
// ClientView.
static int GetLocalizedContentsWidth(int col_resource_id);
static int GetLocalizedContentsHeight(int row_resource_id);
static gfx::Size GetLocalizedContentsSize(int col_resource_id,
int row_resource_id);
// Returns true if the specified type requires a NonClientView.
static bool RequiresNonClientView(InitParams::Type type);
// Initializes the widget, and in turn, the native widget. |params| should be
// moved to Init() by the caller.
void Init(InitParams params);
// Returns the gfx::NativeView associated with this Widget.
gfx::NativeView GetNativeView() const;
// Returns the gfx::NativeWindow associated with this Widget. This may return
// NULL on some platforms if the widget was created with a type other than
// TYPE_WINDOW or TYPE_PANEL.
gfx::NativeWindow GetNativeWindow() const;
// Add/remove observer.
void AddObserver(WidgetObserver* observer);
void RemoveObserver(WidgetObserver* observer);
bool HasObserver(const WidgetObserver* observer) const;
// Add/remove removals observer.
void AddRemovalsObserver(WidgetRemovalsObserver* observer);
void RemoveRemovalsObserver(WidgetRemovalsObserver* observer);
bool HasRemovalsObserver(const WidgetRemovalsObserver* observer) const;
// Returns the accelerator given a command id. Returns false if there is
// no accelerator associated with a given id, which is a common condition.
virtual bool GetAccelerator(int cmd_id, ui::Accelerator* accelerator) const;
// Forwarded from the RootView so that the widget can do any cleanup.
void ViewHierarchyChanged(const ViewHierarchyChangedDetails& details);
// Called right before changing the widget's parent NativeView to do any
// cleanup.
void NotifyNativeViewHierarchyWillChange();
// Called after changing the widget's parent NativeView. Notifies the RootView
// about the change.
void NotifyNativeViewHierarchyChanged();
// Called immediately before removing |view| from this widget.
void NotifyWillRemoveView(View* view);
// Returns the top level widget in a hierarchy (see is_top_level() for
// the definition of top level widget.) Will return NULL if called
// before the widget is attached to the top level widget's hierarchy.
//
// If you want to get the absolute primary application window, accounting for
// e.g. bubble and menu anchoring, use GetPrimaryWindowWidget() instead.
Widget* GetTopLevelWidget();
const Widget* GetTopLevelWidget() const;
// Returns the widget of the primary window this widget is associated with,
// such as an application window, accounting for anchoring and other
// relationships not accounted for in GetTopLevelWidget().
//
// Equivalent to GetTopLevelWidget() by default; override in derived classes
// that require additional logic.
virtual Widget* GetPrimaryWindowWidget();
const Widget* GetPrimaryWindowWidget() const;
// Gets/Sets the WidgetDelegate.
WidgetDelegate* widget_delegate() const { return widget_delegate_.get(); }
// Sets the specified view as the contents of this Widget. There can only
// be one contents view child of this Widget's RootView. This view is sized to
// fit the entire size of the RootView. The RootView takes ownership of this
// View, unless it is passed in as a raw pointer and set as not being
// parent-owned. Prefer using SetContentsView(std::unique_ptr) over passing a
// raw pointer for new code.
template <typename T>
T* SetContentsView(std::unique_ptr<T> view) {
DCHECK(!view->owned_by_client())
<< "This should only be called if the client is passing over the "
"ownership of |view|.";
T* raw_pointer = view.get();
SetContentsView(view.release());
return raw_pointer;
}
void SetContentsView(View* view);
// NOTE: This may not be the same view as WidgetDelegate::GetContentsView().
// See RootView::GetContentsView().
View* GetContentsView();
// Returns the bounds of the Widget in screen coordinates.
gfx::Rect GetWindowBoundsInScreen() const;
// Returns the bounds of the Widget's client area in screen coordinates.
gfx::Rect GetClientAreaBoundsInScreen() const;
// Retrieves the restored bounds for the window.
gfx::Rect GetRestoredBounds() const;
// Retrieves the current workspace for the window. (On macOS: an opaque
// binary blob that encodes the workspace and other window state. On ChromeOS,
// this returns empty string if this widget is a window that appears on all
// desks.)
std::string GetWorkspace() const;
// Sizes and/or places the widget to the specified bounds, size or position.
void SetBounds(const gfx::Rect& bounds);
void SetSize(const gfx::Size& size);
// Sizes the window to the specified size and centers it.
void CenterWindow(const gfx::Size& size);
// Like SetBounds(), but ensures the Widget is fully visible on screen or
// parent widget, resizing and/or repositioning as necessary.
void SetBoundsConstrained(const gfx::Rect& bounds);
// Sets whether animations that occur when visibility is changed are enabled.
// Default is true.
void SetVisibilityChangedAnimationsEnabled(bool value);
// Sets the duration of visibility change animations.
void SetVisibilityAnimationDuration(const base::TimeDelta& duration);
// Sets the visibility transitions that should animate.
// Default behavior is to animate both show and hide.
void SetVisibilityAnimationTransition(VisibilityTransition transition);
// Whether calling RunMoveLoop() is supported for the widget.
bool IsMoveLoopSupported() const;
// Starts a nested run loop that moves the window. This can be used to
// start a window move operation from a mouse or touch event. This returns
// when the move completes. |drag_offset| is the offset from the top left
// corner of the window to the point where the cursor is dragging, and is used
// to offset the bounds of the window from the cursor.
MoveLoopResult RunMoveLoop(const gfx::Vector2d& drag_offset,
MoveLoopSource source,
MoveLoopEscapeBehavior escape_behavior);
// Stops a previously started move loop. This is not immediate.
void EndMoveLoop();
// Places the widget in front of the specified widget in z-order.
void StackAboveWidget(Widget* widget);
void StackAbove(gfx::NativeView native_view);
void StackAtTop();
// Returns true if widget is above the specified window in z-order.
bool IsStackedAbove(gfx::NativeView native_view);
// Sets a shape on the widget. Passing a NULL |shape| reverts the widget to
// be rectangular.
void SetShape(std::unique_ptr<ShapeRects> shape);
// Equivalent to CloseWithReason(ClosedReason::kUnspecified).
// DEPRECATED: Please use CloseWithReason() instead.
void Close();
// Hides the widget, then closes it after a return to the message loop,
// specifying the reason for it having been closed.
// Note that while you can pass ClosedReason::kUnspecified, it is highly
// discouraged and only supported for backwards-compatibility with Close().
void CloseWithReason(ClosedReason closed_reason);
// A UI test which tries to asynchronously examine a widget (e.g. the pixel
// tests) will fail if the widget is closed before that. This can happen
// easily with widgets that close on focus loss coupled with tests being run
// in parallel, since one test's widget can be closed by the appearance of
// another test's. This method can be used to temporarily disable
// Widget::Close() for such asynchronous cases.
void SetBlockCloseForTesting(bool block_close) { block_close_ = block_close; }
// TODO(beng): Move off public API.
// Closes the widget immediately. Compare to |Close|. This will destroy the
// window handle associated with this Widget, so should not be called from
// any code that expects it to be valid beyond this call.
void CloseNow();
// Whether the widget has been asked to close itself. In particular this is
// set to true after Close() has been invoked on the NativeWidget.
bool IsClosed() const;
// Returns the reason the widget was closed, if it was specified.
ClosedReason closed_reason() const { return closed_reason_; }
// Shows the widget. The widget is activated if during initialization the
// can_activate flag in the InitParams structure is set to true.
void Show();
// Hides the widget.
void Hide();
// Like Show(), but does not activate the window. Tests may be flaky on Mac:
// Mac browsertests do not have an activation policy so the widget may be
// activated.
void ShowInactive();
// Activates the widget, assuming it already exists and is visible.
void Activate();
// Deactivates the widget, making the next window in the Z order the active
// window.
void Deactivate();
// Returns whether the Widget is the currently active window.
virtual bool IsActive() const;
// Sets the z-order of the widget. This only applies to top-level widgets.
void SetZOrderLevel(ui::ZOrderLevel order);
// Gets the z-order of the widget. This only applies to top-level widgets.
ui::ZOrderLevel GetZOrderLevel() const;
// Sets the z-order sublevel of the widget. This applies to both top-level
// and non top-level widgets.
void SetZOrderSublevel(int sublevel);
// Gets the z-order sublevel of the widget. This applies to both top-level
// and non top-level widgets.
int GetZOrderSublevel() const;
// Sets the widget to be visible on all work spaces.
void SetVisibleOnAllWorkspaces(bool always_visible);
// Is this widget currently visible on all workspaces?
// A call to SetVisibleOnAllWorkspaces(true) won't necessarily mean
// IsVisbleOnAllWorkspaces() == true (for example, when the platform doesn't
// support workspaces).
bool IsVisibleOnAllWorkspaces() const;
// Maximizes/minimizes/restores the window.
void Maximize();
void Minimize();
void Restore();
// Whether or not the window is maximized or minimized.
virtual bool IsMaximized() const;
bool IsMinimized() const;
// Accessors for fullscreen state.
// The `target_display_id` may only be specified if `fullscreen` is true, and
// indicates a specific display to become fullscreen on (note that this may
// move a fullscreen widget from one display to another).
void SetFullscreen(bool fullscreen,
int64_t target_display_id = display::kInvalidDisplayId);
bool IsFullscreen() const;
// macOS: Sets whether the window can share fullscreen windows' spaces.
void SetCanAppearInExistingFullscreenSpaces(
bool can_appear_in_existing_fullscreen_spaces);
// Sets the opacity of the widget. This may allow widgets behind the widget
// in the Z-order to become visible, depending on the capabilities of the
// underlying windowing system.
void SetOpacity(float opacity);
// Sets the aspect ratio of the widget's client view, which will be maintained
// during interactive resizing. Note that for widgets that have a client view
// that is framed by custom-drawn borders / window frame / etc, the widget
// size will be chosen so that the aspect ratio of client view, not the entire
// widget, will be `aspect_ratio`.
//
// Once set, some platforms ensure the content will only size to integer
// multiples of |aspect_ratio|.
void SetAspectRatio(const gfx::SizeF& aspect_ratio);
// Flashes the frame of the window to draw attention to it. Currently only
// implemented on Windows for non-Aura.
void FlashFrame(bool flash);
// Returns the View at the root of the View hierarchy contained by this
// Widget.
View* GetRootView();
const View* GetRootView() const;
// A secondary widget is one that is automatically closed (via Close()) when
// all non-secondary widgets are closed.
// Default is true.
// TODO(beng): This is an ugly API, should be handled implicitly via
// transience.
void set_is_secondary_widget(bool is_secondary_widget) {
is_secondary_widget_ = is_secondary_widget;
}
bool is_secondary_widget() const { return is_secondary_widget_; }
// Returns whether the Widget is visible to the user.
virtual bool IsVisible() const;
// Returns the ThemeProvider that provides theme resources for this Widget.
virtual const ui::ThemeProvider* GetThemeProvider() const;
// Returns a custom theme object suitable for use in a
// ColorProviderManager::Key. If this is null, the window has no custom theme.
virtual ui::ColorProviderManager::ThemeInitializerSupplier* GetCustomTheme()
const;
ui::NativeTheme* GetNativeTheme() {
return const_cast<ui::NativeTheme*>(
static_cast<const Widget*>(this)->GetNativeTheme());
}
virtual const ui::NativeTheme* GetNativeTheme() const;
// Returns the FocusManager for this widget.
// Note that all widgets in a widget hierarchy share the same focus manager.
FocusManager* GetFocusManager();
const FocusManager* GetFocusManager() const;
// Returns the ui::InputMethod for this widget.
ui::InputMethod* GetInputMethod();
// Returns the SublevelManager for this widget.
SublevelManager* GetSublevelManager();
// Starts a drag operation for the specified view. This blocks until the drag
// operation completes. |view| can be NULL.
// If the view is non-NULL it can be accessed during the drag by calling
// dragged_view(). If the view has not been deleted during the drag,
// OnDragDone() is called on it. |location| is in the widget's coordinate
// system.
void RunShellDrag(View* view,
std::unique_ptr<ui::OSExchangeData> data,
const gfx::Point& location,
int operation,
ui::mojom::DragEventSource source);
// Returns the view that requested the current drag operation via
// RunShellDrag(), or NULL if there is no such view or drag operation.
View* dragged_view() {
return const_cast<View*>(const_cast<const Widget*>(this)->dragged_view());
}
const View* dragged_view() const { return dragged_view_; }
// Adds the specified |rect| in client area coordinates to the rectangle to be
// redrawn.
virtual void SchedulePaintInRect(const gfx::Rect& rect);
// Schedule a layout to occur. This is called by RootView, client code should
// not need to call this.
void ScheduleLayout();
// Sets the currently visible cursor.
void SetCursor(const ui::Cursor& cursor);
// Returns true if and only if mouse events are enabled.
bool IsMouseEventsEnabled() const;
// Sets/Gets a native window property on the underlying native window object.
// Returns NULL if the property does not exist. Setting the property value to
// NULL removes the property.
void SetNativeWindowProperty(const char* name, void* value);
void* GetNativeWindowProperty(const char* name) const;
// Tell the window to update its title from the delegate.
void UpdateWindowTitle();
// Tell the window to update its icon from the delegate.
void UpdateWindowIcon();
// Shows the platform specific emoji picker for this widget.
void ShowEmojiPanel();
// Retrieves the focus traversable for this widget.
FocusTraversable* GetFocusTraversable();
// Notifies the view hierarchy contained in this widget that theme resources
// changed.
void ThemeChanged();
// Notifies the view hierarchy contained in this widget that the device scale
// factor changed.
void DeviceScaleFactorChanged(float old_device_scale_factor,
float new_device_scale_factor);
void SetFocusTraversableParent(FocusTraversable* parent);
void SetFocusTraversableParentView(View* parent_view);
// Clear native focus set to the Widget's NativeWidget.
void ClearNativeFocus();
void set_frame_type(FrameType frame_type) { frame_type_ = frame_type; }
FrameType frame_type() const { return frame_type_; }
// Creates an appropriate NonClientFrameView for this widget. The
// WidgetDelegate is given the first opportunity to create one, followed by
// the NativeWidget implementation. If both return NULL, a default one is
// created.
virtual std::unique_ptr<NonClientFrameView> CreateNonClientFrameView();
// Whether we should be using a native frame.
bool ShouldUseNativeFrame() const;
// Determines whether the window contents should be rendered transparently
// (for example, so that they can overhang onto the window title bar).
bool ShouldWindowContentsBeTransparent() const;
// Forces the frame into the alternate frame type (custom or native) depending
// on its current state.
void DebugToggleFrameType();
// Tell the window that something caused the frame type to change.
void FrameTypeChanged();
NonClientView* non_client_view() {
return const_cast<NonClientView*>(
const_cast<const Widget*>(this)->non_client_view());
}
const NonClientView* non_client_view() const { return non_client_view_; }
ClientView* client_view() {
return const_cast<ClientView*>(
const_cast<const Widget*>(this)->client_view());
}
const ClientView* client_view() const {
// non_client_view_ may be NULL, especially during creation.
return non_client_view_ ? non_client_view_->client_view() : nullptr;
}
// Returns the compositor for this Widget, note that this may change during
// the Widget's lifetime (e.g. when switching monitors on Chrome OS).
ui::Compositor* GetCompositor() {
return const_cast<ui::Compositor*>(
const_cast<const Widget*>(this)->GetCompositor());
}
const ui::Compositor* GetCompositor() const;
// Returns the widget's layer, if any.
ui::Layer* GetLayer() {
return const_cast<ui::Layer*>(const_cast<const Widget*>(this)->GetLayer());
}
const ui::Layer* GetLayer() const;
// Reorders the widget's child NativeViews which are associated to the view
// tree (eg via a NativeViewHost) to match the z-order of the views in the
// view tree. The z-order of views with layers relative to views with
// associated NativeViews is used to reorder the NativeView layers. This
// method assumes that the widget's child layers which are owned by a view are
// already in the correct z-order relative to each other and does no
// reordering if there are no views with an associated NativeView.
void ReorderNativeViews();
// Called by a View when the status of it's layer or one of the views
// descendants layer status changes.
void LayerTreeChanged();
const NativeWidget* native_widget() const;
NativeWidget* native_widget();
internal::NativeWidgetPrivate* native_widget_private() {
return native_widget_.get();
}
const internal::NativeWidgetPrivate* native_widget_private() const {
return native_widget_.get();
}
// Sets capture to the specified view. This makes it so that all mouse, touch
// and gesture events go to |view|. If |view| is NULL, the widget still
// obtains event capture, but the events will go to the view they'd normally
// go to.
void SetCapture(View* view);
// Releases capture.
void ReleaseCapture();
// Returns true if the widget has capture.
bool HasCapture();
void set_auto_release_capture(bool auto_release_capture) {
auto_release_capture_ = auto_release_capture;
}
// Returns the font used for tooltips.
TooltipManager* GetTooltipManager();
const TooltipManager* GetTooltipManager() const;
void set_focus_on_creation(bool focus_on_creation) {
focus_on_creation_ = focus_on_creation;
}
// Returns the parent of this widget. Note that
// * A top-level widget is not necessarily the root and may have a parent.
// * A child widget shares the same visual style, e.g. the dark/light theme,
// with its parent.
// * The native widget may change a widget's parent.
// * The native view's parent might or might not be the parent's native view.
// * For a desktop widget with a non-desktop parent, this value might be
// nullptr during shutdown.
Widget* parent() { return parent_.get(); }
const Widget* parent() const { return parent_.get(); }
// True if the widget is considered top level widget. Top level widget
// is a widget of TYPE_WINDOW, TYPE_PANEL, TYPE_WINDOW_FRAMELESS, BUBBLE,
// POPUP or MENU, and has a focus manager and input method object associated
// with it. TYPE_CONTROL and TYPE_TOOLTIP is not considered top level.
bool is_top_level() const { return is_top_level_; }
// True when window movement via mouse interaction with the frame is disabled.
bool movement_disabled() const { return movement_disabled_; }
void set_movement_disabled(bool disabled) { movement_disabled_ = disabled; }
// Returns the work area bounds of the screen the Widget belongs to.
gfx::Rect GetWorkAreaBoundsInScreen() const;
// Creates and dispatches synthesized mouse move event using the current
// mouse location to refresh hovering status in the widget.
void SynthesizeMouseMoveEvent();
// Whether the widget supports translucency.
bool IsTranslucentWindowOpacitySupported() const;
// Returns the gesture recognizer which can handle touch/gesture events on
// this.
ui::GestureRecognizer* GetGestureRecognizer();
// Returns the associated gesture consumer.
ui::GestureConsumer* GetGestureConsumer();
// Called when the delegate's CanResize or CanMaximize changes.
void OnSizeConstraintsChanged();
// Notification that our owner is closing.
// NOTE: this is not invoked for aura as it's currently not needed there.
// Under aura menus close by way of activation getting reset when the owner
// closes.
virtual void OnOwnerClosing();
// Returns the internal name for this Widget and NativeWidget.
std::string GetName() const;
// Registers |callback| to be called whenever the "paint as active" state
// changes.
base::CallbackListSubscription RegisterPaintAsActiveChangedCallback(
PaintAsActiveCallbackList::CallbackType callback);
// Prevents the widget from being rendered as inactive during the lifetime of
// the returned lock. Multiple locks can exist with disjoint lifetimes. The
// returned lock can safely outlive the associated widget.
std::unique_ptr<PaintAsActiveLock> LockPaintAsActive();
// Undoes LockPaintAsActive(). This should never be called outside of
// PaintAsActiveLock destructor.
void UnlockPaintAsActive();
// Returns true if the window should paint as active.
bool ShouldPaintAsActive() const;
// Called when the ShouldPaintAsActive() of parent changes.
void OnParentShouldPaintAsActiveChanged();
// Notifies registered callbacks and the native widget of changes to
// the ShouldPaintAsActive() state.
void NotifyPaintAsActiveChanged();
base::WeakPtr<Widget> GetWeakPtr();
// Overridden from NativeWidgetDelegate:
bool IsModal() const override;
bool IsDialogBox() const override;
bool CanActivate() const override;
bool IsNativeWidgetInitialized() const override;
bool OnNativeWidgetActivationChanged(bool active) override;
bool ShouldHandleNativeWidgetActivationChanged(bool active) override;
void OnNativeFocus() override;
void OnNativeBlur() override;
void OnNativeWidgetVisibilityChanged(bool visible) override;
void OnNativeWidgetCreated() override;
void OnNativeWidgetDestroying() override;
void OnNativeWidgetDestroyed() override;
void OnNativeWidgetParentChanged(gfx::NativeView parent) override;
gfx::Size GetMinimumSize() const override;
gfx::Size GetMaximumSize() const override;
void OnNativeWidgetMove() override;
void OnNativeWidgetSizeChanged(const gfx::Size& new_size) override;
void OnNativeWidgetWorkspaceChanged() override;
void OnNativeWidgetWindowShowStateChanged() override;
void OnNativeWidgetBeginUserBoundsChange() override;
void OnNativeWidgetEndUserBoundsChange() override;
void OnNativeWidgetAddedToCompositor() override;
void OnNativeWidgetRemovingFromCompositor() override;
bool HasFocusManager() const override;
void OnNativeWidgetPaint(const ui::PaintContext& context) override;
int GetNonClientComponent(const gfx::Point& point) override;
void OnKeyEvent(ui::KeyEvent* event) override;
void OnMouseEvent(ui::MouseEvent* event) override;
void OnMouseCaptureLost() override;
void OnScrollEvent(ui::ScrollEvent* event) override;
void OnGestureEvent(ui::GestureEvent* event) override;
bool ExecuteCommand(int command_id) override;
bool HasHitTestMask() const override;
void GetHitTestMask(SkPath* mask) const override;
Widget* AsWidget() override;
const Widget* AsWidget() const override;
bool SetInitialFocus(ui::WindowShowState show_state) override;
bool ShouldDescendIntoChildForEventHandling(
ui::Layer* root_layer,
gfx::NativeView child,
ui::Layer* child_layer,
const gfx::Point& location) override;
void LayoutRootViewIfNecessary() override;
// Overridden from ui::EventSource:
ui::EventSink* GetEventSink() override;
// Overridden from FocusTraversable:
FocusSearch* GetFocusSearch() override;
FocusTraversable* GetFocusTraversableParent() override;
View* GetFocusTraversableParentView() override;
// Overridden from ui::NativeThemeObserver:
void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override;
// Sets an override for `color_mode` when `GetColorProvider()` is requested.
// e.g. if set to kDark, colors will always be for the dark theme.
void SetColorModeOverride(
absl::optional<ui::ColorProviderManager::ColorMode> color_mode);
// ui::ColorProviderSource:
const ui::ColorProvider* GetColorProvider() const override;
// Set the native theme from which this widget gets color from.
void SetNativeThemeForTest(ui::NativeTheme* native_theme) {
SetNativeTheme(native_theme);
}
protected:
// Creates the RootView to be used within this Widget. Subclasses may override
// to create custom RootViews that do specialized event processing.
// TODO(beng): Investigate whether or not this is needed.
virtual internal::RootView* CreateRootView();
// Provided to allow the NativeWidget implementations to destroy the RootView
// _before_ the focus manager/tooltip manager.
// TODO(beng): remove once we fold those objects onto this one.
void DestroyRootView();
// Notification that a drag will start. Default implementation does nothing.
virtual void OnDragWillStart();
// Notification that the drag performed by RunShellDrag() has completed.
virtual void OnDragComplete();
// Set the native theme from which this widget gets color from.
void SetNativeTheme(ui::NativeTheme* native_theme);
// The following methods are used by the property access system described in
// the comments on views::View. They follow the required naming convention in
// order to allow them to be visible via the metadata.
// TODO(kylixrd): Refactor code to use these methods directly.
int GetX() const;
int GetY() const;
int GetWidth() const;
int GetHeight() const;
bool GetVisible() const;
void SetX(int x);
void SetY(int y);
void SetWidth(int width);
void SetHeight(int height);
void SetVisible(bool visible);
// ui::ColorProviderSource:
ui::ColorProviderManager::Key GetColorProviderKey() const override;
absl::optional<SkColor> GetUserColor() const override;
private:
// Type of ways to ignore activation changes.
enum class DisableActivationChangeHandlingType {
kNone = 0, // Don't ignore any activation changes.
kIgnore, // Ignore both activation and deactivation changes.
kIgnoreDeactivationOnly, // Ignore only deactivation changes.
};
class PaintAsActiveLockImpl;
friend class ButtonTest;
friend class ComboboxTest;
friend class PaintAsActiveLockImpl;
friend class TextfieldTest;
friend class ViewAuraTest;
friend class ui_devtools::PageAgentViews;
// TODO (kylixrd): Remove this after Widget no longer can "own" the
// WidgetDelegate.
friend class WidgetDelegate;
friend void DisableActivationChangeHandlingForTests();
// Sets/gets the type of disabling widget activation change handling.
static void SetDisableActivationChangeHandling(
DisableActivationChangeHandlingType new_type) {
g_disable_activation_change_handling_ = new_type;
}
static DisableActivationChangeHandlingType
GetDisableActivationChangeHandling() {
return g_disable_activation_change_handling_;
}
// Persists the window's restored position and "show" state using the
// window delegate.
void SaveWindowPlacement();
// Invokes SaveWindowPlacement() if the native widget has been initialized.
// This is called at times when the native widget may not have been
// initialized.
void SaveWindowPlacementIfInitialized();
// Sizes and positions the window just after it is created.
void SetInitialBounds(const gfx::Rect& bounds);
// Sizes and positions the frameless window just after it is created.
void SetInitialBoundsForFramelessWindow(const gfx::Rect& bounds);
// Set the parent of this widget.
void SetParent(Widget* parent);
// Returns the bounds and "show" state from the delegate. Returns true if
// the delegate wants to use a specified bounds.
bool GetSavedWindowPlacement(gfx::Rect* bounds,
ui::WindowShowState* show_state);
// Returns the Views whose layers are parented directly to the Widget's
// layer.
const View::Views& GetViewsWithLayers();
// If a descendent of |root_view_| is focused, then clear the focus.
void ClearFocusFromWidget();
// This holds logic that needs to called synchronously after showing, before
// the native widget asynchronously invokes OnNativeWidgetVisibilityChanged().
void HandleShowRequested();
static DisableActivationChangeHandlingType
g_disable_activation_change_handling_;
base::WeakPtr<internal::NativeWidgetPrivate> native_widget_ = nullptr;
// This unique pointer is only set when WIDGET_OWNS_NATIVE_WIDGET so that we
// can destroy the NativeWidget. Except for managing lifetime for
// WIDGET_OWNS_NATIVE_WIDGET, the NativeWidget should always be referenced
// through the |native_widget_| weak ptr.
std::unique_ptr<internal::NativeWidgetPrivate> owned_native_widget_;
base::ObserverList<WidgetObserver> observers_;
base::ObserverList<WidgetRemovalsObserver>::Unchecked removals_observers_;
// Weak pointer to the Widget's delegate. If a NULL delegate is supplied
// to Init() a default WidgetDelegate is created.
base::WeakPtr<WidgetDelegate> widget_delegate_;
// TODO(kylixrd): Rename this once the transition requiring the client to own
// the delegate is finished.
// [Owned Widget delegate if the DefaultWidgetDelegate is used. This
// ties the lifetime of the default delegate to the Widget.]
//
// This will "own" the delegate when WidgetDelegate::owned_by_widget() is
// true.
std::unique_ptr<WidgetDelegate> owned_widget_delegate_;
// The parent of this widget. This is the widget that associates with
// the |params.parent| supplied to Init(). If no parent is given or the native
// view parent has no associating Widget, this value will be nullptr.
// For a desktop widget with a non-desktop parent, this value might be nullptr
// during shutdown.
base::WeakPtr<Widget> parent_ = nullptr;
// The root of the View hierarchy attached to this window.
// WARNING: see warning in tooltip_manager_ for ordering dependencies with
// this and tooltip_manager_.
std::unique_ptr<internal::RootView> root_view_;
// The View that provides the non-client area of the window (title bar,
// window controls, sizing borders etc). To use an implementation other than
// the default, this class must be sub-classed and this value set to the
// desired implementation before calling |InitWindow()|.
raw_ptr<NonClientView> non_client_view_ = nullptr;
// The focus manager keeping track of focus for this Widget and any of its
// children. NULL for non top-level widgets.
// WARNING: RootView's destructor calls into the FocusManager. As such, this
// must be destroyed AFTER root_view_. This is enforced in DestroyRootView().
std::unique_ptr<FocusManager> focus_manager_;
// The sublevel manager that ensures that the children are stacked in the
// order specified by their InitParams::sublevel.
std::unique_ptr<SublevelManager> sublevel_manager_;
// Valid for the lifetime of RunShellDrag(), indicates the view the drag
// started from.
raw_ptr<View> dragged_view_ = nullptr;
// See class documentation for Widget above for a note about ownership.
InitParams::Ownership ownership_ = InitParams::NATIVE_WIDGET_OWNS_WIDGET;
// See set_is_secondary_widget().
bool is_secondary_widget_ = true;
#if BUILDFLAG(IS_CHROMEOS_ASH)
ui::ColorProviderManager::ElevationMode background_elevation_ =
ui::ColorProviderManager::ElevationMode::kLow;
#endif
// If set, overrides this value is used instead of the one from NativeTheme
// when constructing a ColorProvider.
absl::optional<ui::ColorProviderManager::ColorMode> color_mode_override_;
// The current frame type in use by this window. Defaults to
// FrameType::kDefault.
FrameType frame_type_ = FrameType::kDefault;
// Tracks whether the native widget is active.
bool native_widget_active_ = false;
// Count of paint-as-active locks on this widget. See LockPaintAsActive().
size_t paint_as_active_refcount_ = 0;
// Callbacks to notify when the ShouldPaintAsActive() changes.
PaintAsActiveCallbackList paint_as_active_callbacks_;
// Lock on the parent widget when this widget is active.
// When this widget is destroyed, the lock is automatically released.
std::unique_ptr<PaintAsActiveLock> parent_paint_as_active_lock_;
// Subscription to parent's ShouldPaintAsActive() change.
base::CallbackListSubscription parent_paint_as_active_subscription_;
// Set to true if the widget is in the process of closing.
bool widget_closed_ = false;
// The reason the widget was closed.
// Note that this may be ClosedReason::kUnspecified if the deprecated Close()
// method was called rather than CloseWithReason().
ClosedReason closed_reason_ = ClosedReason::kUnspecified;
// The saved "show" state for this window. See note in SetInitialBounds
// that explains why we save this.
ui::WindowShowState saved_show_state_ = ui::SHOW_STATE_DEFAULT;
// The restored bounds used for the initial show. This is only used if
// |saved_show_state_| is maximized. initial_restored_bounds_ is in DIP units
// and is converted to pixels in DesktopWindowTreeHostWin::Show.
gfx::Rect initial_restored_bounds_;
// Focus is automatically set to the view provided by the delegate
// when the widget is shown. Set this value to false to override
// initial focus for the widget.
bool focus_on_creation_ = true;
// See |is_top_level()| accessor.
bool is_top_level_ = false;
// Tracks whether native widget has been initialized.
bool native_widget_initialized_ = false;
// TODO(beng): Remove NativeWidgetGtk's dependence on these:
// If true, the mouse is currently down.
bool is_mouse_button_pressed_ = false;
// True if capture losses should be ignored.
bool ignore_capture_loss_ = false;
// TODO(beng): Remove NativeWidgetGtk's dependence on these:
// The following are used to detect duplicate mouse move events and not
// deliver them. Displaying a window may result in the system generating
// duplicate move events even though the mouse hasn't moved.
bool last_mouse_event_was_move_ = false;
gfx::Point last_mouse_event_position_;
// True if event capture should be released on a mouse up event. Default is
// true.
bool auto_release_capture_ = true;
// See description in GetViewsWithLayers().
View::Views views_with_layers_;
// Does |views_with_layers_| need updating?
bool views_with_layers_dirty_ = false;
// True when window movement via mouse interaction with the frame should be
// disabled.
bool movement_disabled_ = false;
// Block the widget from closing.
bool block_close_ = false;
// The native theme this widget is using.
// If nullptr, defaults to use the regular native theme.
raw_ptr<ui::NativeTheme> native_theme_ = nullptr;
base::ScopedObservation<ui::NativeTheme, ui::NativeThemeObserver>
native_theme_observation_{this};
base::WeakPtrFactory<Widget> weak_ptr_factory_{this};
};
} // namespace views
#endif // UI_VIEWS_WIDGET_WIDGET_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/widget.h | C++ | unknown | 58,154 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/widget/widget_aura_utils.h"
#include "base/notreached.h"
namespace views {
aura::client::WindowType GetAuraWindowTypeForWidgetType(
Widget::InitParams::Type type) {
switch (type) {
case Widget::InitParams::TYPE_WINDOW:
return aura::client::WINDOW_TYPE_NORMAL;
case Widget::InitParams::TYPE_CONTROL:
return aura::client::WINDOW_TYPE_CONTROL;
case Widget::InitParams::TYPE_WINDOW_FRAMELESS:
case Widget::InitParams::TYPE_POPUP:
case Widget::InitParams::TYPE_BUBBLE:
case Widget::InitParams::TYPE_DRAG:
return aura::client::WINDOW_TYPE_POPUP;
case Widget::InitParams::TYPE_MENU:
return aura::client::WINDOW_TYPE_MENU;
case Widget::InitParams::TYPE_TOOLTIP:
return aura::client::WINDOW_TYPE_TOOLTIP;
default:
NOTREACHED_NORETURN() << "Unhandled widget type " << type;
}
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/widget_aura_utils.cc | C++ | unknown | 1,037 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_WIDGET_WIDGET_AURA_UTILS_H_
#define UI_VIEWS_WIDGET_WIDGET_AURA_UTILS_H_
#include "ui/aura/client/window_types.h"
#include "ui/views/widget/widget.h"
// Functions shared by native_widget_aura.cc and desktop_native_widget_aura.cc:
namespace views {
aura::client::WindowType GetAuraWindowTypeForWidgetType(
Widget::InitParams::Type type);
} // namespace views
#endif // UI_VIEWS_WIDGET_WIDGET_AURA_UTILS_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/widget_aura_utils.h | C++ | unknown | 578 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/widget/widget_delegate.h"
#include <memory>
#include <utility>
#include "base/check.h"
#include "base/strings/utf_string_conversions.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/base/models/image_model.h"
#include "ui/display/display.h"
#include "ui/display/screen.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/views/view.h"
#include "ui/views/views_delegate.h"
#include "ui/views/widget/widget.h"
#include "ui/views/window/client_view.h"
namespace views {
namespace {
std::unique_ptr<ClientView> CreateDefaultClientView(WidgetDelegate* delegate,
Widget* widget) {
return std::make_unique<ClientView>(
widget, delegate->TransferOwnershipOfContentsView());
}
std::unique_ptr<View> CreateDefaultOverlayView() {
return nullptr;
}
} // namespace
////////////////////////////////////////////////////////////////////////////////
// WidgetDelegate:
WidgetDelegate::Params::Params() = default;
WidgetDelegate::Params::~Params() = default;
WidgetDelegate::WidgetDelegate()
: widget_initialized_callbacks_(std::make_unique<ClosureVector>()),
client_view_factory_(
base::BindOnce(&CreateDefaultClientView, base::Unretained(this))),
overlay_view_factory_(base::BindOnce(&CreateDefaultOverlayView)) {}
WidgetDelegate::~WidgetDelegate() {
CHECK(can_delete_this_) << "A WidgetDelegate must outlive its Widget";
if (!contents_view_taken_ && default_contents_view_ &&
!default_contents_view_->parent()) {
delete default_contents_view_;
default_contents_view_ = nullptr;
}
if (destructor_ran_) {
DCHECK(!*destructor_ran_);
*destructor_ran_ = true;
}
}
void WidgetDelegate::SetCanActivate(bool can_activate) {
can_activate_ = can_activate;
}
void WidgetDelegate::OnWidgetMove() {}
void WidgetDelegate::OnDisplayChanged() {}
void WidgetDelegate::OnWorkAreaChanged() {}
bool WidgetDelegate::OnCloseRequested(Widget::ClosedReason close_reason) {
return true;
}
View* WidgetDelegate::GetInitiallyFocusedView() {
return params_.initially_focused_view.value_or(nullptr);
}
bool WidgetDelegate::HasConfiguredInitiallyFocusedView() const {
return params_.initially_focused_view.has_value();
}
BubbleDialogDelegate* WidgetDelegate::AsBubbleDialogDelegate() {
return nullptr;
}
DialogDelegate* WidgetDelegate::AsDialogDelegate() {
return nullptr;
}
bool WidgetDelegate::CanResize() const {
return params_.can_resize;
}
bool WidgetDelegate::CanMaximize() const {
return params_.can_maximize;
}
bool WidgetDelegate::CanMinimize() const {
return params_.can_minimize;
}
bool WidgetDelegate::CanActivate() const {
return can_activate_;
}
ui::ModalType WidgetDelegate::GetModalType() const {
return params_.modal_type;
}
ax::mojom::Role WidgetDelegate::GetAccessibleWindowRole() {
return params_.accessible_role;
}
std::u16string WidgetDelegate::GetAccessibleWindowTitle() const {
return params_.accessible_title.empty() ? GetWindowTitle()
: params_.accessible_title;
}
std::u16string WidgetDelegate::GetWindowTitle() const {
return params_.title;
}
bool WidgetDelegate::ShouldShowWindowTitle() const {
return params_.show_title;
}
bool WidgetDelegate::ShouldCenterWindowTitleText() const {
#if defined(USE_AURA)
return params_.center_title;
#else
return false;
#endif
}
bool WidgetDelegate::ShouldShowCloseButton() const {
return params_.show_close_button;
}
ui::ImageModel WidgetDelegate::GetWindowAppIcon() {
// Prefer app icon if available.
if (!params_.app_icon.IsEmpty())
return params_.app_icon;
// Fall back to the window icon.
return GetWindowIcon();
}
// Returns the icon to be displayed in the window.
ui::ImageModel WidgetDelegate::GetWindowIcon() {
return params_.icon;
}
bool WidgetDelegate::ShouldShowWindowIcon() const {
return params_.show_icon;
}
bool WidgetDelegate::ExecuteWindowsCommand(int command_id) {
return false;
}
std::string WidgetDelegate::GetWindowName() const {
return std::string();
}
void WidgetDelegate::SaveWindowPlacement(const gfx::Rect& bounds,
ui::WindowShowState show_state) {
std::string window_name = GetWindowName();
if (!window_name.empty()) {
ViewsDelegate::GetInstance()->SaveWindowPlacement(GetWidget(), window_name,
bounds, show_state);
}
}
bool WidgetDelegate::ShouldSaveWindowPlacement() const {
return !GetWindowName().empty();
}
bool WidgetDelegate::GetSavedWindowPlacement(
const Widget* widget,
gfx::Rect* bounds,
ui::WindowShowState* show_state) const {
std::string window_name = GetWindowName();
if (window_name.empty() ||
!ViewsDelegate::GetInstance()->GetSavedWindowPlacement(
widget, window_name, bounds, show_state))
return false;
// Try to find a display intersecting the saved bounds.
const auto& display =
display::Screen::GetScreen()->GetDisplayMatching(*bounds);
return display.bounds().Intersects(*bounds);
}
void WidgetDelegate::WidgetInitializing(Widget* widget) {
widget_ = widget;
}
void WidgetDelegate::WidgetInitialized() {
for (auto&& callback : *widget_initialized_callbacks_)
std::move(callback).Run();
widget_initialized_callbacks_.reset();
OnWidgetInitialized();
}
void WidgetDelegate::WidgetDestroying() {
widget_ = nullptr;
}
void WidgetDelegate::WindowWillClose() {
// TODO(ellyjones): For this and the other callback methods, establish whether
// any other code calls these methods. If not, DCHECK here and below that
// these methods are only called once.
for (auto&& callback : window_will_close_callbacks_)
std::move(callback).Run();
}
void WidgetDelegate::WindowClosing() {
for (auto&& callback : window_closing_callbacks_)
std::move(callback).Run();
}
void WidgetDelegate::DeleteDelegate() {
bool owned_by_widget = params_.owned_by_widget;
ClosureVector delete_callbacks;
delete_callbacks.swap(delete_delegate_callbacks_);
bool destructor_ran = false;
destructor_ran_ = &destructor_ran;
for (auto&& callback : delete_callbacks)
std::move(callback).Run();
// TODO(kylixrd): Eventually the widget will never own the delegate, so much
// of this code will need to be reworked.
//
// If the WidgetDelegate is owned by the Widget, it is illegal for the
// DeleteDelegate callbacks to destruct it; if it is not owned by the Widget,
// the DeleteDelete callbacks are allowed but not required to destroy it.
if (owned_by_widget) {
DCHECK(!destructor_ran);
// TODO(kylxird): Rework this once the Widget stops being able to "own" the
// delegate.
// Only delete this if this delegate was never actually initialized wth a
// Widget or the delegate isn't "owned" by the Widget.
if (can_delete_this_) {
delete this;
return;
}
destructor_ran_ = nullptr;
} else {
// If the destructor didn't get run, reset destructor_ran_ so that when it
// does run it doesn't try to scribble over where our stack was.
if (!destructor_ran)
destructor_ran_ = nullptr;
}
}
Widget* WidgetDelegate::GetWidget() {
return widget_;
}
const Widget* WidgetDelegate::GetWidget() const {
return widget_;
}
View* WidgetDelegate::GetContentsView() {
if (unowned_contents_view_)
return unowned_contents_view_;
if (!default_contents_view_)
default_contents_view_ = new View;
return default_contents_view_;
}
View* WidgetDelegate::TransferOwnershipOfContentsView() {
DCHECK(!contents_view_taken_);
contents_view_taken_ = true;
if (owned_contents_view_)
owned_contents_view_.release();
return GetContentsView();
}
ClientView* WidgetDelegate::CreateClientView(Widget* widget) {
DCHECK(client_view_factory_);
return std::move(client_view_factory_).Run(widget).release();
}
std::unique_ptr<NonClientFrameView> WidgetDelegate::CreateNonClientFrameView(
Widget* widget) {
return nullptr;
}
View* WidgetDelegate::CreateOverlayView() {
DCHECK(overlay_view_factory_);
return std::move(overlay_view_factory_).Run().release();
}
bool WidgetDelegate::WidgetHasHitTestMask() const {
return false;
}
void WidgetDelegate::GetWidgetHitTestMask(SkPath* mask) const {
DCHECK(mask);
}
bool WidgetDelegate::ShouldDescendIntoChildForEventHandling(
gfx::NativeView child,
const gfx::Point& location) {
return true;
}
void WidgetDelegate::SetAccessibleWindowRole(ax::mojom::Role role) {
params_.accessible_role = role;
}
void WidgetDelegate::SetAccessibleTitle(std::u16string title) {
params_.accessible_title = std::move(title);
}
void WidgetDelegate::SetCanMaximize(bool can_maximize) {
bool old_can_maximize = std::exchange(params_.can_maximize, can_maximize);
if (GetWidget() && params_.can_maximize != old_can_maximize)
GetWidget()->OnSizeConstraintsChanged();
}
void WidgetDelegate::SetCanMinimize(bool can_minimize) {
bool old_can_minimize = std::exchange(params_.can_minimize, can_minimize);
if (GetWidget() && params_.can_minimize != old_can_minimize)
GetWidget()->OnSizeConstraintsChanged();
}
void WidgetDelegate::SetCanResize(bool can_resize) {
bool old_can_resize = std::exchange(params_.can_resize, can_resize);
if (GetWidget() && params_.can_resize != old_can_resize)
GetWidget()->OnSizeConstraintsChanged();
}
// TODO (kylixrd): This will be removed once Widget no longer "owns" the
// WidgetDelegate.
void WidgetDelegate::SetOwnedByWidget(bool owned) {
if (params_.owned_by_widget == owned)
return;
params_.owned_by_widget = owned;
if (widget_ && widget_->widget_delegate_.get() == this) {
if (params_.owned_by_widget)
widget_->owned_widget_delegate_ = base::WrapUnique(this);
else
widget_->owned_widget_delegate_.release();
}
}
void WidgetDelegate::SetFocusTraversesOut(bool focus_traverses_out) {
params_.focus_traverses_out = focus_traverses_out;
}
void WidgetDelegate::SetEnableArrowKeyTraversal(
bool enable_arrow_key_traversal) {
params_.enable_arrow_key_traversal = enable_arrow_key_traversal;
}
void WidgetDelegate::SetIcon(ui::ImageModel icon) {
params_.icon = std::move(icon);
if (GetWidget())
GetWidget()->UpdateWindowIcon();
}
void WidgetDelegate::SetAppIcon(ui::ImageModel icon) {
params_.app_icon = std::move(icon);
if (GetWidget())
GetWidget()->UpdateWindowIcon();
}
void WidgetDelegate::SetInitiallyFocusedView(View* initially_focused_view) {
DCHECK(!GetWidget());
params_.initially_focused_view = initially_focused_view;
}
void WidgetDelegate::SetModalType(ui::ModalType modal_type) {
DCHECK(!GetWidget());
params_.modal_type = modal_type;
}
void WidgetDelegate::SetShowCloseButton(bool show_close_button) {
params_.show_close_button = show_close_button;
}
void WidgetDelegate::SetShowIcon(bool show_icon) {
params_.show_icon = show_icon;
if (GetWidget())
GetWidget()->UpdateWindowIcon();
}
void WidgetDelegate::SetShowTitle(bool show_title) {
params_.show_title = show_title;
}
void WidgetDelegate::SetTitle(const std::u16string& title) {
if (params_.title == title)
return;
params_.title = title;
if (GetWidget())
GetWidget()->UpdateWindowTitle();
}
void WidgetDelegate::SetTitle(int title_message_id) {
SetTitle(l10n_util::GetStringUTF16(title_message_id));
}
#if defined(USE_AURA)
void WidgetDelegate::SetCenterTitle(bool center_title) {
params_.center_title = center_title;
}
#endif
void WidgetDelegate::SetHasWindowSizeControls(bool has_controls) {
SetCanMaximize(has_controls);
SetCanMinimize(has_controls);
SetCanResize(has_controls);
}
void WidgetDelegate::RegisterWidgetInitializedCallback(
base::OnceClosure callback) {
DCHECK(widget_initialized_callbacks_);
widget_initialized_callbacks_->emplace_back(std::move(callback));
}
void WidgetDelegate::RegisterWindowWillCloseCallback(
base::OnceClosure callback) {
window_will_close_callbacks_.emplace_back(std::move(callback));
}
void WidgetDelegate::RegisterWindowClosingCallback(base::OnceClosure callback) {
window_closing_callbacks_.emplace_back(std::move(callback));
}
void WidgetDelegate::RegisterDeleteDelegateCallback(
base::OnceClosure callback) {
delete_delegate_callbacks_.emplace_back(std::move(callback));
}
void WidgetDelegate::SetClientViewFactory(ClientViewFactory factory) {
DCHECK(!GetWidget());
client_view_factory_ = std::move(factory);
}
void WidgetDelegate::SetOverlayViewFactory(OverlayViewFactory factory) {
DCHECK(!GetWidget());
overlay_view_factory_ = std::move(factory);
}
void WidgetDelegate::SetContentsViewImpl(std::unique_ptr<View> contents) {
DCHECK(!contents->owned_by_client());
DCHECK(!unowned_contents_view_);
owned_contents_view_ = std::move(contents);
unowned_contents_view_ = owned_contents_view_.get();
}
////////////////////////////////////////////////////////////////////////////////
// WidgetDelegateView:
WidgetDelegateView::WidgetDelegateView() {
// TODO (kylixrd): Remove once the Widget ceases to "own" the WidgetDelegate.
// A WidgetDelegate should be deleted on DeleteDelegate.
SetOwnedByWidget(true);
}
WidgetDelegateView::~WidgetDelegateView() = default;
Widget* WidgetDelegateView::GetWidget() {
return View::GetWidget();
}
const Widget* WidgetDelegateView::GetWidget() const {
return View::GetWidget();
}
views::View* WidgetDelegateView::GetContentsView() {
return this;
}
BEGIN_METADATA(WidgetDelegateView, View)
END_METADATA
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/widget_delegate.cc | C++ | unknown | 13,780 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_WIDGET_WIDGET_DELEGATE_H_
#define UI_VIEWS_WIDGET_WIDGET_DELEGATE_H_
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "ui/accessibility/ax_enums.mojom.h"
#include "ui/base/metadata/metadata_header_macros.h"
#include "ui/base/models/image_model.h"
#include "ui/base/ui_base_types.h"
#include "ui/views/metadata/view_factory.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"
namespace gfx {
class Rect;
} // namespace gfx
namespace views {
class BubbleDialogDelegate;
class ClientView;
class DialogDelegate;
class NonClientFrameView;
class View;
// Handles events on Widgets in context-specific ways.
class VIEWS_EXPORT WidgetDelegate
: public base::SupportsWeakPtr<WidgetDelegate> {
public:
using ClientViewFactory =
base::OnceCallback<std::unique_ptr<ClientView>(Widget*)>;
using OverlayViewFactory = base::OnceCallback<std::unique_ptr<View>()>;
struct Params {
Params();
~Params();
// The window's role. Useful values include kWindow (a plain window),
// kDialog (a dialog), and kAlertDialog (a high-priority dialog whose body
// is read when it appears). Using a role outside this set is not likely to
// work across platforms.
ax::mojom::Role accessible_role = ax::mojom::Role::kWindow;
// The accessible title for the window, often more descriptive than the
// plain title. If no accessible title is present the result of
// GetWindowTitle() will be used.
std::u16string accessible_title;
// Whether the window should display controls for the user to minimize,
// maximize, or resize it.
bool can_maximize = false;
bool can_minimize = false;
bool can_resize = false;
#if defined(USE_AURA)
// Whether to center the widget's title within the frame.
bool center_title = false;
#endif
// Controls focus traversal past the first/last focusable view.
// If true, focus moves out of this Widget and to this Widget's toplevel
// Widget; if false, focus cycles within this Widget.
bool focus_traverses_out = false;
// Controls whether the user can traverse a Widget's views using up/down
// and left/right arrow keys in addition to TAB. Applies only to the
// current widget so can be set independently even on widgets that share a
// focus manager.
bool enable_arrow_key_traversal = false;
// The widget's icon, if any.
ui::ImageModel icon;
// The widget's app icon, a larger icon used for task bar and Alt-Tab.
ui::ImageModel app_icon;
// The widget's initially focused view, if any. This can only be set before
// this WidgetDelegate is used to initialize a Widget.
absl::optional<View*> initially_focused_view;
// The widget's internal name, used to identify it in window-state
// restoration (if this widget participates in that) and in debugging
// contexts. Never displayed to the user, and not translated.
std::string internal_name;
// The widget's modality type. Note that MODAL_TYPE_SYSTEM does not work at
// all on Mac.
ui::ModalType modal_type = ui::MODAL_TYPE_NONE;
// Whether this WidgetDelegate should delete itself when the Widget for
// which it is the delegate is about to be destroyed.
// See https://crbug.com/1119898 for more details.
bool owned_by_widget = false;
// Whether to show a close button in the widget frame.
bool show_close_button = true;
// Whether to show the widget's icon.
// TODO(ellyjones): What if this was implied by !icon.isNull()?
bool show_icon = false;
// Whether to display the widget's title in the frame.
bool show_title = true;
// The widget's title, if any.
// TODO(ellyjones): Should it be illegal to have show_title && !title?
std::u16string title;
};
WidgetDelegate();
WidgetDelegate(const WidgetDelegate&) = delete;
WidgetDelegate& operator=(const WidgetDelegate&) = delete;
virtual ~WidgetDelegate();
// Sets the return value of CanActivate(). Default is true.
void SetCanActivate(bool can_activate);
// Called whenever the widget's position changes.
virtual void OnWidgetMove();
// Called with the display changes (color depth or resolution).
virtual void OnDisplayChanged();
// Called when the work area (the desktop area minus task bars,
// menu bars, etc.) changes in size.
virtual void OnWorkAreaChanged();
// Called when the widget's initialization is complete.
virtual void OnWidgetInitialized() {}
// Called when the window has been requested to close, after all other checks
// have run. Returns whether the window should be allowed to close (default is
// true).
//
// Can be used as an alternative to specifying a custom ClientView with
// the CanClose() method, or in widget types which do not support a
// ClientView.
virtual bool OnCloseRequested(Widget::ClosedReason close_reason);
// Returns the view that should have the focus when the widget is shown. If
// nullptr no view is focused.
virtual View* GetInitiallyFocusedView();
bool HasConfiguredInitiallyFocusedView() const;
virtual BubbleDialogDelegate* AsBubbleDialogDelegate();
virtual DialogDelegate* AsDialogDelegate();
// Returns true if the window can be resized.
bool CanResize() const;
// Returns true if the window can be maximized.
virtual bool CanMaximize() const;
// Returns true if the window can be minimized.
virtual bool CanMinimize() const;
// Returns true if the window can be activated.
virtual bool CanActivate() const;
// Returns the modal type that applies to the widget. Default is
// ui::MODAL_TYPE_NONE (not modal).
virtual ui::ModalType GetModalType() const;
virtual ax::mojom::Role GetAccessibleWindowRole();
// Returns the title to be read with screen readers.
virtual std::u16string GetAccessibleWindowTitle() const;
// Returns the text to be displayed in the window title.
virtual std::u16string GetWindowTitle() const;
// Returns true if the window should show a title in the title bar.
virtual bool ShouldShowWindowTitle() const;
// Returns true if the window should show a close button in the title bar.
virtual bool ShouldShowCloseButton() const;
// Returns the app icon for the window. On Windows, this is the ICON_BIG used
// in Alt-Tab list and Win7's taskbar.
virtual ui::ImageModel GetWindowAppIcon();
// Returns the icon to be displayed in the window.
virtual ui::ImageModel GetWindowIcon();
// Returns true if a window icon should be shown.
bool ShouldShowWindowIcon() const;
// Execute a command in the window's controller. Returns true if the command
// was handled, false if it was not.
virtual bool ExecuteWindowsCommand(int command_id);
// Returns the window's name identifier. Used to identify this window for
// state restoration.
virtual std::string GetWindowName() const;
// Returns true if the widget should save its placement and state.
virtual bool ShouldSaveWindowPlacement() const;
// Saves the window's bounds and "show" state. By default this uses the
// process' local state keyed by window name (See GetWindowName above). This
// behavior can be overridden to provide additional functionality.
virtual void SaveWindowPlacement(const gfx::Rect& bounds,
ui::WindowShowState show_state);
// Retrieves the window's bounds and "show" states.
// This behavior can be overridden to provide additional functionality.
virtual bool GetSavedWindowPlacement(const Widget* widget,
gfx::Rect* bounds,
ui::WindowShowState* show_state) const;
// Hooks for the end of the Widget/Window lifecycle. As of this writing, these
// callbacks happen like so:
// 1. Client code calls Widget::CloseWithReason()
// 2. WidgetDelegate::WindowWillClose() is called
// 3. NativeWidget teardown (maybe async) starts OR the operating system
// abruptly closes the backing native window
// 4. WidgetDelegate::WindowClosing() is called
// 5. NativeWidget teardown completes, Widget teardown starts
// 6. WidgetDelegate::DeleteDelegate() is called
// 7. Widget teardown finishes, Widget is deleted
// At step 3, the "maybe async" is controlled by whether the close is done via
// Close() or CloseNow().
// Important note: for OS-initiated window closes, steps 1 and 2 don't happen
// - i.e, WindowWillClose() is never invoked.
//
// The default implementations of both of these call the callbacks described
// below. It is better to use those callback mechanisms than to override one
// of these methods.
virtual void WindowClosing();
// TODO (kylixrd): Rename this API once Widget ceases to "own" WidgetDelegate.
// Update the comment below to match the new state of things.
// Called when removed from a Widget. This first runs callbacks registered
// through RegisterDeleteDelegateCallback() and then either deletes `this` or
// not depending on SetOwnedByWidget(). If `this` is owned by Widget then the
// delegate is destructed at the end.
//
// WARNING: Use SetOwnedByWidget(true) and use delete-delegate callbacks to do
// pre-destruction cleanup instead of using self-deleting callbacks. The
// latter may become a DCHECK in the future.
void DeleteDelegate();
// Called when the user begins/ends to change the bounds of the window.
virtual void OnWindowBeginUserBoundsChange() {}
virtual void OnWindowEndUserBoundsChange() {}
// Returns the Widget associated with this delegate.
virtual Widget* GetWidget();
virtual const Widget* GetWidget() const;
// Get the view that is contained within this widget.
//
// WARNING: This method has unusual ownership behavior:
// * If the returned view is owned_by_client(), then the returned pointer is
// never an owning pointer;
// * If the returned view is !owned_by_client() (the default & the
// recommendation), then the returned pointer is *sometimes* an owning
// pointer and sometimes not. Specifically, it is an owning pointer exactly
// once, when this method is being used to construct the ClientView, which
// takes ownership of the ContentsView() when !owned_by_client().
//
// Apart from being difficult to reason about this introduces a problem: a
// WidgetDelegate can't know whether it owns its contents view or not, so
// constructing a WidgetDelegate which one does not then use to construct a
// Widget (often done in tests) leaks memory in a way that can't be locally
// fixed.
//
// TODO(ellyjones): This is not tenable - figure out how this should work and
// replace it.
virtual View* GetContentsView();
// Returns ownership of the contents view, which means something similar to
// but not the same as C++ ownership in the unique_ptr sense. The caller
// takes on responsibility for either destroying the returned View (if it
// is !owned_by_client()) or not (if it is owned_by_client()). Since this
// returns a raw pointer, this method serves only as a declaration of intent
// by the caller.
//
// It is only legal to call this method one time on a given WidgetDelegate
// instance.
//
// In future, this method will begin returning a unique_ptr<View> instead,
// and will eventually be renamed to TakeContentsView() once WidgetDelegate
// no longer retains any reference to the contents view internally.
View* TransferOwnershipOfContentsView();
// Called by the Widget to create the Client View used to host the contents
// of the widget.
virtual ClientView* CreateClientView(Widget* widget);
// Called by the Widget to create the NonClient Frame View for this widget.
// Return NULL to use the default one.
virtual std::unique_ptr<NonClientFrameView> CreateNonClientFrameView(
Widget* widget);
// Called by the Widget to create the overlay View for this widget. Return
// NULL for no overlay. The overlay View will fill the Widget and sit on top
// of the ClientView and NonClientFrameView (both visually and wrt click
// targeting).
virtual View* CreateOverlayView();
// Returns true if window has a hit-test mask.
virtual bool WidgetHasHitTestMask() const;
// Provides the hit-test mask if HasHitTestMask above returns true.
virtual void GetWidgetHitTestMask(SkPath* mask) const;
// Returns true if event handling should descend into |child|.
// |location| is in terms of the Window.
virtual bool ShouldDescendIntoChildForEventHandling(
gfx::NativeView child,
const gfx::Point& location);
// Populates |panes| with accessible panes in this window that can
// be cycled through with keyboard focus.
virtual void GetAccessiblePanes(std::vector<View*>* panes) {}
// Setters for data parameters of the WidgetDelegate. If you use these
// setters, there is no need to override the corresponding virtual getters.
void SetAccessibleWindowRole(ax::mojom::Role role);
void SetAccessibleTitle(std::u16string title);
void SetCanMaximize(bool can_maximize);
void SetCanMinimize(bool can_minimize);
void SetCanResize(bool can_resize);
void SetFocusTraversesOut(bool focus_traverses_out);
void SetEnableArrowKeyTraversal(bool enable_arrow_key_traversal);
void SetIcon(ui::ImageModel icon);
void SetAppIcon(ui::ImageModel icon);
void SetInitiallyFocusedView(View* initially_focused_view);
void SetModalType(ui::ModalType modal_type);
void SetOwnedByWidget(bool delete_self);
void SetShowCloseButton(bool show_close_button);
void SetShowIcon(bool show_icon);
void SetShowTitle(bool show_title);
void SetTitle(const std::u16string& title);
void SetTitle(int title_message_id);
#if defined(USE_AURA)
void SetCenterTitle(bool center_title);
#endif
template <typename T>
T* SetContentsView(std::unique_ptr<T> contents) {
T* raw_contents = contents.get();
SetContentsViewImpl(std::move(contents));
return raw_contents;
}
// A convenience wrapper that does all three of SetCanMaximize,
// SetCanMinimize, and SetCanResize.
void SetHasWindowSizeControls(bool has_controls);
void RegisterWidgetInitializedCallback(base::OnceClosure callback);
void RegisterWindowWillCloseCallback(base::OnceClosure callback);
void RegisterWindowClosingCallback(base::OnceClosure callback);
void RegisterDeleteDelegateCallback(base::OnceClosure callback);
void SetClientViewFactory(ClientViewFactory factory);
void SetOverlayViewFactory(OverlayViewFactory factory);
// Called to notify the WidgetDelegate of changes to the state of its Widget.
// It is not usually necessary to call these from client code.
void WidgetInitializing(Widget* widget);
void WidgetInitialized();
void WidgetDestroying();
void WindowWillClose();
// Returns true if the title text should be centered.
bool ShouldCenterWindowTitleText() const;
// CEF supports override of min/max size values.
virtual bool MaybeGetMinimumSize(gfx::Size* size) const { return false; }
virtual bool MaybeGetMaximumSize(gfx::Size* size) const { return false; }
bool focus_traverses_out() const { return params_.focus_traverses_out; }
bool enable_arrow_key_traversal() const {
return params_.enable_arrow_key_traversal;
}
bool owned_by_widget() const { return params_.owned_by_widget; }
void set_internal_name(std::string name) { params_.internal_name = name; }
std::string internal_name() const { return params_.internal_name; }
private:
// We're using a vector of OnceClosures instead of a OnceCallbackList because
// most of the clients of WidgetDelegate don't have a convenient place to
// store the CallbackLists' subscription objects.
using ClosureVector = std::vector<base::OnceClosure>;
friend class Widget;
void SetContentsViewImpl(std::unique_ptr<View> contents);
// The Widget that was initialized with this instance as its WidgetDelegate,
// if any.
raw_ptr<Widget, DanglingUntriaged> widget_ = nullptr;
Params params_;
raw_ptr<View, DanglingUntriaged> default_contents_view_ = nullptr;
bool contents_view_taken_ = false;
bool can_activate_ = true;
raw_ptr<View, DanglingUntriaged> unowned_contents_view_ = nullptr;
std::unique_ptr<View> owned_contents_view_;
// Managed by Widget. Ensures |this| outlives its Widget.
bool can_delete_this_ = true;
// Used to ensure that a client Delete callback doesn't actually destruct the
// WidgetDelegate if the client has given ownership to the Widget.
raw_ptr<bool> destructor_ran_ = nullptr;
// This is stored as a unique_ptr to make it easier to check in the
// registration methods whether a callback is being registered too late in the
// WidgetDelegate's lifecycle.
std::unique_ptr<ClosureVector> widget_initialized_callbacks_;
ClosureVector window_will_close_callbacks_;
ClosureVector window_closing_callbacks_;
ClosureVector delete_delegate_callbacks_;
ClientViewFactory client_view_factory_;
OverlayViewFactory overlay_view_factory_;
};
// A WidgetDelegate implementation that is-a View. Used to override GetWidget()
// to call View's GetWidget() for the common case where a WidgetDelegate
// implementation is-a View. Note that WidgetDelegateView is not owned by
// view's hierarchy and is expected to be deleted on DeleteDelegate call.
class VIEWS_EXPORT WidgetDelegateView : public WidgetDelegate, public View {
public:
METADATA_HEADER(WidgetDelegateView);
WidgetDelegateView();
WidgetDelegateView(const WidgetDelegateView&) = delete;
WidgetDelegateView& operator=(const WidgetDelegateView&) = delete;
~WidgetDelegateView() override;
// WidgetDelegate:
Widget* GetWidget() override;
const Widget* GetWidget() const override;
View* GetContentsView() override;
};
BEGIN_VIEW_BUILDER(VIEWS_EXPORT, WidgetDelegateView, View)
END_VIEW_BUILDER
} // namespace views
DEFINE_VIEW_BUILDER(VIEWS_EXPORT, WidgetDelegateView)
#endif // UI_VIEWS_WIDGET_WIDGET_DELEGATE_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/widget_delegate.h | C++ | unknown | 18,255 |
// 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/widget/widget_delegate.h"
#include <utility>
#include "base/test/bind.h"
#include "ui/base/models/image_model.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/gfx/image/image_unittest_util.h"
#include "ui/views/test/views_test_base.h"
#include "ui/views/view.h"
#include "ui/views/view_tracker.h"
namespace views {
namespace {
using WidgetDelegateTest = views::ViewsTestBase;
TEST_F(WidgetDelegateTest, ContentsViewOwnershipHeld) {
std::unique_ptr<View> view = std::make_unique<View>();
ViewTracker tracker(view.get());
auto delegate = std::make_unique<WidgetDelegate>();
delegate->SetContentsView(std::move(view));
delegate.reset();
EXPECT_FALSE(tracker.view());
}
TEST_F(WidgetDelegateTest, ContentsViewOwnershipTransferredToCaller) {
std::unique_ptr<View> view = std::make_unique<View>();
ViewTracker tracker(view.get());
std::unique_ptr<View> same_view;
auto delegate = std::make_unique<WidgetDelegate>();
delegate->SetContentsView(std::move(view));
same_view = base::WrapUnique(delegate->TransferOwnershipOfContentsView());
EXPECT_EQ(tracker.view(), same_view.get());
delegate.reset();
EXPECT_TRUE(tracker.view());
}
TEST_F(WidgetDelegateTest, GetContentsViewDoesNotTransferOwnership) {
std::unique_ptr<View> view = std::make_unique<View>();
ViewTracker tracker(view.get());
auto delegate = std::make_unique<WidgetDelegate>();
delegate->SetContentsView(std::move(view));
EXPECT_EQ(delegate->GetContentsView(), tracker.view());
delegate.reset();
EXPECT_FALSE(tracker.view());
}
TEST_F(WidgetDelegateTest, ClientViewFactoryCanReplaceClientView) {
ViewTracker tracker;
auto delegate = std::make_unique<WidgetDelegate>();
delegate->SetClientViewFactory(
base::BindLambdaForTesting([&tracker](Widget* widget) {
auto view = std::make_unique<ClientView>(widget, nullptr);
tracker.SetView(view.get());
return view;
}));
auto client =
base::WrapUnique<ClientView>(delegate->CreateClientView(nullptr));
EXPECT_EQ(tracker.view(), client.get());
}
TEST_F(WidgetDelegateTest, OverlayViewFactoryCanReplaceOverlayView) {
ViewTracker tracker;
auto delegate = std::make_unique<WidgetDelegate>();
delegate->SetOverlayViewFactory(base::BindLambdaForTesting([&tracker]() {
auto view = std::make_unique<View>();
tracker.SetView(view.get());
return view;
}));
auto overlay = base::WrapUnique<View>(delegate->CreateOverlayView());
EXPECT_EQ(tracker.view(), overlay.get());
}
TEST_F(WidgetDelegateTest, AppIconCanDifferFromWindowIcon) {
auto delegate = std::make_unique<WidgetDelegate>();
gfx::ImageSkia window_icon = gfx::test::CreateImageSkia(16, 16);
delegate->SetIcon(ui::ImageModel::FromImageSkia(window_icon));
gfx::ImageSkia app_icon = gfx::test::CreateImageSkia(48, 48);
delegate->SetAppIcon(ui::ImageModel::FromImageSkia(app_icon));
EXPECT_TRUE(delegate->GetWindowIcon().Rasterize(nullptr).BackedBySameObjectAs(
window_icon));
EXPECT_TRUE(
delegate->GetWindowAppIcon().Rasterize(nullptr).BackedBySameObjectAs(
app_icon));
}
TEST_F(WidgetDelegateTest, AppIconFallsBackToWindowIcon) {
auto delegate = std::make_unique<WidgetDelegate>();
gfx::ImageSkia window_icon = gfx::test::CreateImageSkia(16, 16);
delegate->SetIcon(ui::ImageModel::FromImageSkia(window_icon));
// Don't set an independent app icon.
EXPECT_TRUE(
delegate->GetWindowAppIcon().Rasterize(nullptr).BackedBySameObjectAs(
window_icon));
}
} // namespace
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/widget_delegate_unittest.cc | C++ | unknown | 3,702 |
// 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/widget/widget_deletion_observer.h"
#include "ui/views/widget/widget.h"
namespace views {
WidgetDeletionObserver::WidgetDeletionObserver(Widget* widget)
: widget_(widget) {
if (widget_)
widget_->AddObserver(this);
}
WidgetDeletionObserver::~WidgetDeletionObserver() {
CleanupWidget();
CHECK(!IsInObserverList());
}
void WidgetDeletionObserver::OnWidgetDestroying(Widget* widget) {
CleanupWidget();
}
void WidgetDeletionObserver::CleanupWidget() {
if (widget_) {
widget_->RemoveObserver(this);
widget_ = nullptr;
}
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/widget_deletion_observer.cc | C++ | unknown | 735 |
// 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_WIDGET_WIDGET_DELETION_OBSERVER_H_
#define UI_VIEWS_WIDGET_WIDGET_DELETION_OBSERVER_H_
#include "base/memory/raw_ptr.h"
#include "ui/views/views_export.h"
#include "ui/views/widget/widget_observer.h"
namespace views {
class Widget;
// A simple WidgetObserver that can be probed for the life of a widget.
class VIEWS_EXPORT WidgetDeletionObserver : public WidgetObserver {
public:
explicit WidgetDeletionObserver(Widget* widget);
WidgetDeletionObserver(const WidgetDeletionObserver&) = delete;
WidgetDeletionObserver& operator=(const WidgetDeletionObserver&) = delete;
~WidgetDeletionObserver() override;
// Returns true if the widget passed in the constructor is still alive.
bool IsWidgetAlive() { return widget_ != nullptr; }
// Overridden from WidgetObserver.
void OnWidgetDestroying(Widget* widget) override;
private:
void CleanupWidget();
raw_ptr<Widget> widget_;
};
} // namespace views
#endif // UI_VIEWS_WIDGET_WIDGET_DELETION_OBSERVER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/widget_deletion_observer.h | C++ | unknown | 1,143 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/views/widget/widget_hwnd_utils.h"
#include <dwmapi.h>
#include "base/command_line.h"
#include "build/build_config.h"
#include "ui/base/l10n/l10n_util_win.h"
#include "ui/base/ui_base_features.h"
#include "ui/base/ui_base_switches.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/win/hwnd_message_handler.h"
namespace views {
namespace {
void CalculateWindowStylesFromInitParams(
const Widget::InitParams& params,
WidgetDelegate* widget_delegate,
internal::NativeWidgetDelegate* native_widget_delegate,
bool is_translucent,
DWORD* style,
DWORD* ex_style,
DWORD* class_style) {
*style = WS_CLIPCHILDREN | WS_CLIPSIBLINGS;
*ex_style = 0;
*class_style = CS_DBLCLKS;
// Set type-independent style attributes.
if (params.child)
*style |= WS_CHILD;
if (params.show_state == ui::SHOW_STATE_MAXIMIZED)
*style |= WS_MAXIMIZE;
if (params.show_state == ui::SHOW_STATE_MINIMIZED)
*style |= WS_MINIMIZE;
if (!params.accept_events)
*ex_style |= WS_EX_TRANSPARENT;
DCHECK_NE(Widget::InitParams::Activatable::kDefault, params.activatable);
if (params.activatable == Widget::InitParams::Activatable::kNo)
*ex_style |= WS_EX_NOACTIVATE;
if (params.EffectiveZOrderLevel() != ui::ZOrderLevel::kNormal)
*ex_style |= WS_EX_TOPMOST;
if (params.mirror_origin_in_rtl)
*ex_style |= l10n_util::GetExtendedTooltipStyles();
if (params.shadow_type == Widget::InitParams::ShadowType::kDrop)
*class_style |= CS_DROPSHADOW;
// Set type-dependent style attributes.
switch (params.type) {
case Widget::InitParams::TYPE_WINDOW: {
// WS_OVERLAPPEDWINDOW is equivalent to:
// WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU |
// WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX
*style |= WS_OVERLAPPEDWINDOW;
if (!widget_delegate->CanMaximize())
*style &= static_cast<DWORD>(~WS_MAXIMIZEBOX);
if (!widget_delegate->CanMinimize())
*style &= static_cast<DWORD>(~WS_MINIMIZEBOX);
if (!widget_delegate->CanResize())
*style &= static_cast<DWORD>(~(WS_THICKFRAME | WS_MAXIMIZEBOX));
if (params.remove_standard_frame)
*style &= static_cast<DWORD>(~(WS_MINIMIZEBOX | WS_MAXIMIZEBOX |
WS_CAPTION | WS_SYSMENU));
if (native_widget_delegate->IsDialogBox()) {
*style |= DS_MODALFRAME;
// NOTE: Turning this off means we lose the close button, which is bad.
// Turning it on though means the user can maximize or size the window
// from the system menu, which is worse. We may need to provide our own
// menu to get the close button to appear properly.
// style &= ~WS_SYSMENU;
// Set the WS_POPUP style for modal dialogs. This ensures that the owner
// window is activated on destruction. This style should not be set for
// non-modal non-top-level dialogs like constrained windows.
*style |= native_widget_delegate->IsModal() ? WS_POPUP : 0;
}
*ex_style |=
native_widget_delegate->IsDialogBox() ? WS_EX_DLGMODALFRAME : 0;
// See layered window comment below.
if (is_translucent)
*style &= static_cast<DWORD>(~(WS_THICKFRAME | WS_CAPTION));
break;
}
case Widget::InitParams::TYPE_CONTROL:
*style |= WS_VISIBLE;
break;
case Widget::InitParams::TYPE_BUBBLE:
*style |= WS_POPUP;
*style |= WS_CLIPCHILDREN;
if (!params.force_show_in_taskbar)
*ex_style |= WS_EX_TOOLWINDOW;
break;
case Widget::InitParams::TYPE_POPUP:
*style |= WS_POPUP;
if (!params.force_show_in_taskbar)
*ex_style |= WS_EX_TOOLWINDOW;
break;
case Widget::InitParams::TYPE_MENU:
*style |= WS_POPUP;
if (params.remove_standard_frame) {
*style |= WS_THICKFRAME;
}
if (!params.force_show_in_taskbar)
*ex_style |= WS_EX_TOOLWINDOW;
break;
case Widget::InitParams::TYPE_DRAG:
case Widget::InitParams::TYPE_TOOLTIP:
case Widget::InitParams::TYPE_WINDOW_FRAMELESS:
*style |= WS_POPUP;
break;
default:
NOTREACHED_NORETURN();
}
}
} // namespace
bool DidClientAreaSizeChange(const WINDOWPOS* window_pos) {
return !(window_pos->flags & SWP_NOSIZE) ||
window_pos->flags & SWP_FRAMECHANGED;
}
bool DidMinimizedChange(UINT old_size_param, UINT new_size_param) {
return (
(old_size_param == SIZE_MINIMIZED && new_size_param != SIZE_MINIMIZED) ||
(old_size_param != SIZE_MINIMIZED && new_size_param == SIZE_MINIMIZED));
}
void ConfigureWindowStyles(
HWNDMessageHandler* handler,
const Widget::InitParams& params,
WidgetDelegate* widget_delegate,
internal::NativeWidgetDelegate* native_widget_delegate) {
// Configure the HWNDMessageHandler with the appropriate
DWORD style = 0;
DWORD ex_style = 0;
DWORD class_style = 0;
// Layered windows do not work with Direct3D, so a different mechanism needs
// to be used to allow for transparent borderless windows.
//
// 1- To allow the contents of the swapchain to blend with the contents
// behind it, it must must be created with D3DFMT_A8R8G8B8 in D3D9Ex, or
// with DXGI_ALPHA_MODE_PREMULTIPLIED with DirectComposition.
// 2- When the window is created but before it is presented, call
// DwmExtendFrameIntoClientArea passing -1 as the margins so that
// it's blended with the content below the window and not just black.
// 3- To avoid having a window frame and to avoid blurring the contents
// behind the window, the window must have WS_POPUP in its style and must
// not have not have WM_SIZEBOX, WS_THICKFRAME or WS_CAPTION in its
// style.
//
// Software composited windows can continue to use WS_EX_LAYERED.
bool is_translucent =
(params.opacity == Widget::InitParams::WindowOpacity::kTranslucent);
CalculateWindowStylesFromInitParams(params, widget_delegate,
native_widget_delegate, is_translucent,
&style, &ex_style, &class_style);
handler->set_is_translucent(is_translucent);
handler->set_initial_class_style(class_style);
handler->set_window_style(handler->window_style() | style);
handler->set_window_ex_style(handler->window_ex_style() | ex_style);
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/widget_hwnd_utils.cc | C++ | unknown | 6,529 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_WIDGET_WIDGET_HWND_UTILS_H_
#define UI_VIEWS_WIDGET_WIDGET_HWND_UTILS_H_
#include <windows.h>
#include "ui/views/widget/widget.h"
// Functions shared by hwnd_message_handler.cc and
// desktop_window_tree_host_win.cc:
namespace views {
class HWNDMessageHandler;
class WidgetDelegate;
namespace internal {
class NativeWidgetDelegate;
}
// Returns true if the WINDOWPOS data provided indicates the client area of
// the window may have changed size. This can be caused by the window being
// resized or its frame changing.
bool DidClientAreaSizeChange(const WINDOWPOS* window_pos);
// Returns true if the size data provided indicates that the window
// transitioned from a minimized state to something else or vice versa.
bool DidMinimizedChange(UINT old_size_param, UINT new_size_param);
// Sets styles appropriate for |params| on |handler|.
void ConfigureWindowStyles(
HWNDMessageHandler* handler,
const Widget::InitParams& params,
WidgetDelegate* widget_delegate,
internal::NativeWidgetDelegate* native_widget_delegate);
} // namespace views
#endif // UI_VIEWS_WIDGET_WIDGET_HWND_UTILS_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/widget_hwnd_utils.h | C++ | unknown | 1,277 |
// 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 <stddef.h>
#include <memory>
#include <utility>
#include "base/command_line.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/location.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/task/single_thread_task_runner.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "ui/base/ime/input_method.h"
#include "ui/base/ime/text_input_client.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/test/ui_controls.h"
#include "ui/base/ui_base_features.h"
#include "ui/base/ui_base_switches.h"
#include "ui/events/event_processor.h"
#include "ui/events/event_utils.h"
#include "ui/events/test/event_generator.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/bubble/bubble_dialog_delegate_view.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/controls/textfield/textfield_test_api.h"
#include "ui/views/focus/focus_manager.h"
#include "ui/views/test/focus_manager_test.h"
#include "ui/views/test/native_widget_factory.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/touchui/touch_selection_controller_impl.h"
#include "ui/views/widget/root_view.h"
#include "ui/views/widget/unique_widget_ptr.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_interactive_uitest_utils.h"
#include "ui/views/widget/widget_utils.h"
#include "ui/views/window/dialog_delegate.h"
#include "ui/wm/public/activation_client.h"
#if BUILDFLAG(IS_WIN)
#include "ui/aura/window.h"
#include "ui/aura/window_tree_host.h"
#include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h"
#include "ui/views/win/hwnd_util.h"
#endif
#if BUILDFLAG(IS_MAC)
#include "base/mac/mac_util.h"
#endif
namespace views::test {
namespace {
template <class T>
class UniqueWidgetPtrT : public views::UniqueWidgetPtr {
public:
UniqueWidgetPtrT() = default;
UniqueWidgetPtrT(std::unique_ptr<T> widget) // NOLINT
: views::UniqueWidgetPtr(std::move(widget)) {}
UniqueWidgetPtrT(UniqueWidgetPtrT&&) = default;
UniqueWidgetPtrT& operator=(UniqueWidgetPtrT&&) = default;
~UniqueWidgetPtrT() = default;
T& operator*() const {
return static_cast<T&>(views::UniqueWidgetPtr::operator*());
}
T* operator->() const {
return static_cast<T*>(views::UniqueWidgetPtr::operator->());
}
T* get() const { return static_cast<T*>(views::UniqueWidgetPtr::get()); }
};
// A View that closes the Widget and exits the current message-loop when it
// receives a mouse-release event.
class ExitLoopOnRelease : public View {
public:
explicit ExitLoopOnRelease(base::OnceClosure quit_closure)
: quit_closure_(std::move(quit_closure)) {
DCHECK(quit_closure_);
}
ExitLoopOnRelease(const ExitLoopOnRelease&) = delete;
ExitLoopOnRelease& operator=(const ExitLoopOnRelease&) = delete;
~ExitLoopOnRelease() override = default;
private:
// View:
void OnMouseReleased(const ui::MouseEvent& event) override {
GetWidget()->Close();
std::move(quit_closure_).Run();
}
base::OnceClosure quit_closure_;
};
// A view that does a capture on ui::ET_GESTURE_TAP_DOWN events.
class GestureCaptureView : public View {
public:
GestureCaptureView() = default;
GestureCaptureView(const GestureCaptureView&) = delete;
GestureCaptureView& operator=(const GestureCaptureView&) = delete;
~GestureCaptureView() override = default;
private:
// View:
void OnGestureEvent(ui::GestureEvent* event) override {
if (event->type() == ui::ET_GESTURE_TAP_DOWN) {
GetWidget()->SetCapture(this);
event->StopPropagation();
}
}
};
// A view that always processes all mouse events.
class MouseView : public View {
public:
MouseView() = default;
MouseView(const MouseView&) = delete;
MouseView& operator=(const MouseView&) = delete;
~MouseView() override = default;
bool OnMousePressed(const ui::MouseEvent& event) override {
pressed_++;
return true;
}
void OnMouseEntered(const ui::MouseEvent& event) override { entered_++; }
void OnMouseExited(const ui::MouseEvent& event) override { exited_++; }
// Return the number of OnMouseEntered calls and reset the counter.
int EnteredCalls() {
int i = entered_;
entered_ = 0;
return i;
}
// Return the number of OnMouseExited calls and reset the counter.
int ExitedCalls() {
int i = exited_;
exited_ = 0;
return i;
}
int pressed() const { return pressed_; }
private:
int entered_ = 0;
int exited_ = 0;
int pressed_ = 0;
};
// A View that shows a different widget, sets capture on that widget, and
// initiates a nested message-loop when it receives a mouse-press event.
class NestedLoopCaptureView : public View {
public:
explicit NestedLoopCaptureView(Widget* widget)
: run_loop_(base::RunLoop::Type::kNestableTasksAllowed),
widget_(widget) {}
NestedLoopCaptureView(const NestedLoopCaptureView&) = delete;
NestedLoopCaptureView& operator=(const NestedLoopCaptureView&) = delete;
~NestedLoopCaptureView() override = default;
base::OnceClosure GetQuitClosure() { return run_loop_.QuitClosure(); }
private:
// View:
bool OnMousePressed(const ui::MouseEvent& event) override {
// Start a nested loop.
widget_->Show();
widget_->SetCapture(widget_->GetContentsView());
EXPECT_TRUE(widget_->HasCapture());
run_loop_.Run();
return true;
}
base::RunLoop run_loop_;
raw_ptr<Widget> widget_;
};
ui::WindowShowState GetWidgetShowState(const Widget* widget) {
// Use IsMaximized/IsMinimized/IsFullScreen instead of GetWindowPlacement
// because the former is implemented on all platforms but the latter is not.
if (widget->IsFullscreen())
return ui::SHOW_STATE_FULLSCREEN;
if (widget->IsMaximized())
return ui::SHOW_STATE_MAXIMIZED;
if (widget->IsMinimized())
return ui::SHOW_STATE_MINIMIZED;
return widget->IsActive() ? ui::SHOW_STATE_NORMAL : ui::SHOW_STATE_INACTIVE;
}
// Give the OS an opportunity to process messages for an activation change, when
// there is actually no change expected (e.g. ShowInactive()).
void RunPendingMessagesForActiveStatusChange() {
#if BUILDFLAG(IS_MAC)
// On Mac, a single spin is *usually* enough. It isn't when a widget is shown
// and made active in two steps, so tests should follow up with a ShowSync()
// or ActivateSync to ensure a consistent state.
base::RunLoop().RunUntilIdle();
#endif
// TODO(tapted): Check for desktop aura widgets.
}
// Activate a widget, and wait for it to become active. On non-desktop Aura
// this is just an activation. For other widgets, it means activating and then
// spinning the run loop until the OS has activated the window.
void ActivateSync(Widget* widget) {
views::test::WidgetActivationWaiter waiter(widget, true);
widget->Activate();
waiter.Wait();
}
// Like for ActivateSync(), wait for a widget to become active, but Show() the
// widget rather than calling Activate().
void ShowSync(Widget* widget) {
views::test::WidgetActivationWaiter waiter(widget, true);
widget->Show();
waiter.Wait();
}
void DeactivateSync(Widget* widget) {
#if BUILDFLAG(IS_MAC)
// Deactivation of a window isn't a concept on Mac: If an application is
// active and it has any activatable windows, then one of them is always
// active. But we can simulate deactivation (e.g. as if another application
// became active) by temporarily making |widget| non-activatable, then
// activating (and closing) a temporary widget.
widget->widget_delegate()->SetCanActivate(false);
Widget* stealer = new Widget;
stealer->Init(Widget::InitParams(Widget::InitParams::TYPE_WINDOW));
ShowSync(stealer);
stealer->CloseNow();
widget->widget_delegate()->SetCanActivate(true);
#else
views::test::WidgetActivationWaiter waiter(widget, false);
widget->Deactivate();
waiter.Wait();
#endif
}
#if BUILDFLAG(IS_WIN)
void ActivatePlatformWindow(Widget* widget) {
::SetActiveWindow(
widget->GetNativeWindow()->GetHost()->GetAcceleratedWidget());
}
#endif
// Calls ShowInactive() on a Widget, and spins a run loop. The goal is to give
// the OS a chance to activate a widget. However, for this case, the test
// doesn't expect that to happen, so there is nothing to wait for.
void ShowInactiveSync(Widget* widget) {
widget->ShowInactive();
RunPendingMessagesForActiveStatusChange();
}
std::unique_ptr<Textfield> CreateTextfield() {
auto textfield = std::make_unique<Textfield>();
// Focusable views must have an accessible name in order to pass the
// accessibility paint checks. The name can be literal text, placeholder
// text or an associated label.
textfield->SetAccessibleName(u"Foo");
return textfield;
}
} // namespace
class WidgetTestInteractive : public WidgetTest {
public:
WidgetTestInteractive() = default;
~WidgetTestInteractive() override = default;
void SetUp() override {
SetUpForInteractiveTests();
WidgetTest::SetUp();
}
};
#if BUILDFLAG(IS_WIN)
// Tests whether activation and focus change works correctly in Windows.
// We test the following:-
// 1. If the active aura window is correctly set when a top level widget is
// created.
// 2. If the active aura window in widget 1 created above, is set to NULL when
// another top level widget is created and focused.
// 3. On focusing the native platform window for widget 1, the active aura
// window for widget 1 should be set and that for widget 2 should reset.
// TODO(ananta): Discuss with erg on how to write this test for linux x11 aura.
TEST_F(DesktopWidgetTestInteractive,
DesktopNativeWidgetAuraActivationAndFocusTest) {
// Create widget 1 and expect the active window to be its window.
View* focusable_view1 = new View;
focusable_view1->SetFocusBehavior(View::FocusBehavior::ALWAYS);
WidgetAutoclosePtr widget1(CreateTopLevelNativeWidget());
widget1->GetContentsView()->AddChildView(focusable_view1);
widget1->Show();
aura::Window* root_window1 = GetRootWindow(widget1.get());
focusable_view1->RequestFocus();
EXPECT_TRUE(root_window1 != nullptr);
wm::ActivationClient* activation_client1 =
wm::GetActivationClient(root_window1);
EXPECT_TRUE(activation_client1 != nullptr);
EXPECT_EQ(activation_client1->GetActiveWindow(), widget1->GetNativeView());
// Create widget 2 and expect the active window to be its window.
View* focusable_view2 = new View;
WidgetAutoclosePtr widget2(CreateTopLevelNativeWidget());
widget1->GetContentsView()->AddChildView(focusable_view2);
widget2->Show();
aura::Window* root_window2 = GetRootWindow(widget2.get());
focusable_view2->RequestFocus();
ActivatePlatformWindow(widget2.get());
wm::ActivationClient* activation_client2 =
wm::GetActivationClient(root_window2);
EXPECT_TRUE(activation_client2 != nullptr);
EXPECT_EQ(activation_client2->GetActiveWindow(), widget2->GetNativeView());
EXPECT_EQ(activation_client1->GetActiveWindow(),
reinterpret_cast<aura::Window*>(NULL));
// Now set focus back to widget 1 and expect the active window to be its
// window.
focusable_view1->RequestFocus();
ActivatePlatformWindow(widget1.get());
EXPECT_EQ(activation_client2->GetActiveWindow(),
reinterpret_cast<aura::Window*>(NULL));
EXPECT_EQ(activation_client1->GetActiveWindow(), widget1->GetNativeView());
}
// Verifies bubbles result in a focus lost when shown.
TEST_F(DesktopWidgetTestInteractive, FocusChangesOnBubble) {
WidgetAutoclosePtr widget(CreateTopLevelNativeWidget());
View* focusable_view =
widget->GetContentsView()->AddChildView(std::make_unique<View>());
focusable_view->SetFocusBehavior(View::FocusBehavior::ALWAYS);
widget->Show();
focusable_view->RequestFocus();
EXPECT_TRUE(focusable_view->HasFocus());
// Show a bubble.
auto owned_bubble_delegate_view =
std::make_unique<views::BubbleDialogDelegateView>(focusable_view,
BubbleBorder::NONE);
owned_bubble_delegate_view->SetFocusBehavior(View::FocusBehavior::ALWAYS);
BubbleDialogDelegateView* bubble_delegate_view =
owned_bubble_delegate_view.get();
BubbleDialogDelegateView::CreateBubble(std::move(owned_bubble_delegate_view))
->Show();
bubble_delegate_view->RequestFocus();
// |focusable_view| should no longer have focus.
EXPECT_FALSE(focusable_view->HasFocus());
EXPECT_TRUE(bubble_delegate_view->HasFocus());
bubble_delegate_view->GetWidget()->CloseNow();
// Closing the bubble should result in focus going back to the contents view.
EXPECT_TRUE(focusable_view->HasFocus());
}
class TouchEventHandler : public ui::EventHandler {
public:
explicit TouchEventHandler(Widget* widget) : widget_(widget) {
widget_->GetNativeWindow()->GetHost()->window()->AddPreTargetHandler(this);
}
TouchEventHandler(const TouchEventHandler&) = delete;
TouchEventHandler& operator=(const TouchEventHandler&) = delete;
~TouchEventHandler() override {
widget_->GetNativeWindow()->GetHost()->window()->RemovePreTargetHandler(
this);
}
void WaitForEvents() {
base::RunLoop run_loop(base::RunLoop::Type::kNestableTasksAllowed);
quit_closure_ = run_loop.QuitClosure();
run_loop.Run();
}
static void __stdcall AsyncActivateMouse(HWND hwnd,
UINT msg,
ULONG_PTR data,
LRESULT result) {
EXPECT_EQ(MA_NOACTIVATE, result);
std::move(reinterpret_cast<TouchEventHandler*>(data)->quit_closure_).Run();
}
void ActivateViaMouse() {
SendMessageCallback(
widget_->GetNativeWindow()->GetHost()->GetAcceleratedWidget(),
WM_MOUSEACTIVATE, 0, 0, AsyncActivateMouse,
reinterpret_cast<ULONG_PTR>(this));
}
private:
// ui::EventHandler:
void OnTouchEvent(ui::TouchEvent* event) override {
if (event->type() == ui::ET_TOUCH_PRESSED)
ActivateViaMouse();
}
raw_ptr<Widget> widget_;
base::OnceClosure quit_closure_;
};
// TODO(dtapuska): Disabled due to it being flaky crbug.com/817531
TEST_F(DesktopWidgetTestInteractive, DISABLED_TouchNoActivateWindow) {
View* focusable_view = new View;
focusable_view->SetFocusBehavior(View::FocusBehavior::ALWAYS);
WidgetAutoclosePtr widget(CreateTopLevelNativeWidget());
widget->GetContentsView()->AddChildView(focusable_view);
widget->Show();
{
TouchEventHandler touch_event_handler(widget.get());
ASSERT_TRUE(
ui_controls::SendTouchEvents(ui_controls::kTouchPress, 1, 100, 100));
touch_event_handler.WaitForEvents();
}
}
#endif // BUILDFLAG(IS_WIN)
// Tests mouse move outside of the window into the "resize controller" and back
// will still generate an OnMouseEntered and OnMouseExited event..
TEST_F(WidgetTestInteractive, CheckResizeControllerEvents) {
WidgetAutoclosePtr toplevel(CreateTopLevelFramelessPlatformWidget());
toplevel->SetBounds(gfx::Rect(0, 0, 100, 100));
MouseView* view = new MouseView();
view->SetBounds(90, 90, 10, 10);
// |view| needs to be a particular size. Reset the LayoutManager so that
// it doesn't get resized.
toplevel->GetRootView()->SetLayoutManager(nullptr);
toplevel->GetRootView()->AddChildView(view);
toplevel->Show();
RunPendingMessages();
// Move to an outside position.
gfx::Point p1(200, 200);
ui::MouseEvent moved_out(ui::ET_MOUSE_MOVED, p1, p1, ui::EventTimeForNow(),
ui::EF_NONE, ui::EF_NONE);
toplevel->OnMouseEvent(&moved_out);
EXPECT_EQ(0, view->EnteredCalls());
EXPECT_EQ(0, view->ExitedCalls());
// Move onto the active view.
gfx::Point p2(95, 95);
ui::MouseEvent moved_over(ui::ET_MOUSE_MOVED, p2, p2, ui::EventTimeForNow(),
ui::EF_NONE, ui::EF_NONE);
toplevel->OnMouseEvent(&moved_over);
EXPECT_EQ(1, view->EnteredCalls());
EXPECT_EQ(0, view->ExitedCalls());
// Move onto the outer resizing border.
gfx::Point p3(102, 95);
ui::MouseEvent moved_resizer(ui::ET_MOUSE_MOVED, p3, p3,
ui::EventTimeForNow(), ui::EF_NONE, ui::EF_NONE);
toplevel->OnMouseEvent(&moved_resizer);
EXPECT_EQ(0, view->EnteredCalls());
EXPECT_EQ(1, view->ExitedCalls());
// Move onto the view again.
toplevel->OnMouseEvent(&moved_over);
EXPECT_EQ(1, view->EnteredCalls());
EXPECT_EQ(0, view->ExitedCalls());
}
// Test view focus restoration when a widget is deactivated and re-activated.
TEST_F(WidgetTestInteractive, ViewFocusOnWidgetActivationChanges) {
WidgetAutoclosePtr widget1(CreateTopLevelPlatformWidget());
View* view1 =
widget1->GetContentsView()->AddChildView(std::make_unique<View>());
view1->SetFocusBehavior(View::FocusBehavior::ALWAYS);
WidgetAutoclosePtr widget2(CreateTopLevelPlatformWidget());
View* view2a = new View;
View* view2b = new View;
view2a->SetFocusBehavior(View::FocusBehavior::ALWAYS);
view2b->SetFocusBehavior(View::FocusBehavior::ALWAYS);
widget2->GetContentsView()->AddChildView(view2a);
widget2->GetContentsView()->AddChildView(view2b);
ShowSync(widget1.get());
EXPECT_TRUE(widget1->IsActive());
view1->RequestFocus();
EXPECT_EQ(view1, widget1->GetFocusManager()->GetFocusedView());
ShowSync(widget2.get());
EXPECT_TRUE(widget2->IsActive());
EXPECT_FALSE(widget1->IsActive());
EXPECT_EQ(nullptr, widget1->GetFocusManager()->GetFocusedView());
view2a->RequestFocus();
EXPECT_EQ(view2a, widget2->GetFocusManager()->GetFocusedView());
view2b->RequestFocus();
EXPECT_EQ(view2b, widget2->GetFocusManager()->GetFocusedView());
ActivateSync(widget1.get());
EXPECT_TRUE(widget1->IsActive());
EXPECT_EQ(view1, widget1->GetFocusManager()->GetFocusedView());
EXPECT_FALSE(widget2->IsActive());
EXPECT_EQ(nullptr, widget2->GetFocusManager()->GetFocusedView());
ActivateSync(widget2.get());
EXPECT_TRUE(widget2->IsActive());
EXPECT_EQ(view2b, widget2->GetFocusManager()->GetFocusedView());
EXPECT_FALSE(widget1->IsActive());
EXPECT_EQ(nullptr, widget1->GetFocusManager()->GetFocusedView());
}
TEST_F(WidgetTestInteractive, ZOrderCheckBetweenTopWindows) {
WidgetAutoclosePtr w1(CreateTopLevelPlatformWidget());
WidgetAutoclosePtr w2(CreateTopLevelPlatformWidget());
WidgetAutoclosePtr w3(CreateTopLevelPlatformWidget());
ShowSync(w1.get());
ShowSync(w2.get());
ShowSync(w3.get());
EXPECT_FALSE(w1->AsWidget()->IsStackedAbove(w2->AsWidget()->GetNativeView()));
EXPECT_FALSE(w2->AsWidget()->IsStackedAbove(w3->AsWidget()->GetNativeView()));
EXPECT_FALSE(w1->AsWidget()->IsStackedAbove(w3->AsWidget()->GetNativeView()));
EXPECT_TRUE(w2->AsWidget()->IsStackedAbove(w1->AsWidget()->GetNativeView()));
EXPECT_TRUE(w3->AsWidget()->IsStackedAbove(w2->AsWidget()->GetNativeView()));
EXPECT_TRUE(w3->AsWidget()->IsStackedAbove(w1->AsWidget()->GetNativeView()));
w2->AsWidget()->StackAboveWidget(w1->AsWidget());
EXPECT_TRUE(w2->AsWidget()->IsStackedAbove(w1->AsWidget()->GetNativeView()));
w1->AsWidget()->StackAboveWidget(w2->AsWidget());
EXPECT_FALSE(w2->AsWidget()->IsStackedAbove(w1->AsWidget()->GetNativeView()));
}
// Test z-order of child widgets relative to their parent.
// TODO(crbug.com/1227009): Disabled on Mac due to flake
#if BUILDFLAG(IS_MAC)
#define MAYBE_ChildStackedRelativeToParent DISABLED_ChildStackedRelativeToParent
#else
#define MAYBE_ChildStackedRelativeToParent ChildStackedRelativeToParent
#endif
TEST_F(WidgetTestInteractive, MAYBE_ChildStackedRelativeToParent) {
WidgetAutoclosePtr parent(CreateTopLevelPlatformWidget());
Widget* child = CreateChildPlatformWidget(parent->GetNativeView());
parent->SetBounds(gfx::Rect(160, 100, 320, 200));
child->SetBounds(gfx::Rect(50, 50, 30, 20));
// Child shown first. Initially not visible, but on top of parent when shown.
// Use ShowInactive whenever showing the child, otherwise the usual activation
// logic will just put it on top anyway. Here, we want to ensure it is on top
// of its parent regardless.
child->ShowInactive();
EXPECT_FALSE(child->IsVisible());
ShowSync(parent.get());
EXPECT_TRUE(child->IsVisible());
EXPECT_TRUE(IsWindowStackedAbove(child, parent.get()));
EXPECT_FALSE(IsWindowStackedAbove(parent.get(), child)); // Sanity check.
WidgetAutoclosePtr popover(CreateTopLevelPlatformWidget());
popover->SetBounds(gfx::Rect(150, 90, 340, 240));
ShowSync(popover.get());
// NOTE: for aura-mus-client stacking of top-levels is not maintained in the
// client, so z-order of top-levels can't be determined.
EXPECT_TRUE(IsWindowStackedAbove(popover.get(), child));
EXPECT_TRUE(IsWindowStackedAbove(child, parent.get()));
// Showing the parent again should raise it and its child above the popover.
ShowSync(parent.get());
EXPECT_TRUE(IsWindowStackedAbove(child, parent.get()));
EXPECT_TRUE(IsWindowStackedAbove(parent.get(), popover.get()));
// Test grandchildren.
Widget* grandchild = CreateChildPlatformWidget(child->GetNativeView());
grandchild->SetBounds(gfx::Rect(5, 5, 15, 10));
grandchild->ShowInactive();
EXPECT_TRUE(IsWindowStackedAbove(grandchild, child));
EXPECT_TRUE(IsWindowStackedAbove(child, parent.get()));
EXPECT_TRUE(IsWindowStackedAbove(parent.get(), popover.get()));
ShowSync(popover.get());
EXPECT_TRUE(IsWindowStackedAbove(popover.get(), grandchild));
EXPECT_TRUE(IsWindowStackedAbove(grandchild, child));
ShowSync(parent.get());
EXPECT_TRUE(IsWindowStackedAbove(grandchild, child));
EXPECT_TRUE(IsWindowStackedAbove(child, popover.get()));
// Test hiding and reshowing.
parent->Hide();
EXPECT_FALSE(grandchild->IsVisible());
ShowSync(parent.get());
EXPECT_TRUE(IsWindowStackedAbove(grandchild, child));
EXPECT_TRUE(IsWindowStackedAbove(child, parent.get()));
EXPECT_TRUE(IsWindowStackedAbove(parent.get(), popover.get()));
grandchild->Hide();
EXPECT_FALSE(grandchild->IsVisible());
grandchild->ShowInactive();
EXPECT_TRUE(IsWindowStackedAbove(grandchild, child));
EXPECT_TRUE(IsWindowStackedAbove(child, parent.get()));
EXPECT_TRUE(IsWindowStackedAbove(parent.get(), popover.get()));
}
TEST_F(WidgetTestInteractive, ChildWidgetStackAbove) {
#if BUILDFLAG(IS_MAC)
// MacOS 10.13 and before don't report window z-ordering reliably.
if (base::mac::IsAtMostOS10_13())
GTEST_SKIP();
#endif
WidgetAutoclosePtr toplevel(CreateTopLevelPlatformWidget());
Widget* children[] = {CreateChildPlatformWidget(toplevel->GetNativeView()),
CreateChildPlatformWidget(toplevel->GetNativeView()),
CreateChildPlatformWidget(toplevel->GetNativeView())};
int order[] = {0, 1, 2};
children[0]->ShowInactive();
children[1]->ShowInactive();
children[2]->ShowInactive();
ShowSync(toplevel.get());
do {
children[order[1]]->StackAboveWidget(children[order[0]]);
children[order[2]]->StackAboveWidget(children[order[1]]);
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
if (i < j)
EXPECT_FALSE(
IsWindowStackedAbove(children[order[i]], children[order[j]]));
else if (i > j)
EXPECT_TRUE(
IsWindowStackedAbove(children[order[i]], children[order[j]]));
} while (std::next_permutation(order, order + 3));
}
TEST_F(WidgetTestInteractive, ChildWidgetStackAtTop) {
#if BUILDFLAG(IS_MAC)
// MacOS 10.13 and before don't report window z-ordering reliably.
if (base::mac::IsAtMostOS10_13())
GTEST_SKIP();
#endif
WidgetAutoclosePtr toplevel(CreateTopLevelPlatformWidget());
Widget* children[] = {CreateChildPlatformWidget(toplevel->GetNativeView()),
CreateChildPlatformWidget(toplevel->GetNativeView()),
CreateChildPlatformWidget(toplevel->GetNativeView())};
int order[] = {0, 1, 2};
children[0]->ShowInactive();
children[1]->ShowInactive();
children[2]->ShowInactive();
ShowSync(toplevel.get());
do {
children[order[1]]->StackAtTop();
children[order[2]]->StackAtTop();
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
if (i < j)
EXPECT_FALSE(
IsWindowStackedAbove(children[order[i]], children[order[j]]));
else if (i > j)
EXPECT_TRUE(
IsWindowStackedAbove(children[order[i]], children[order[j]]));
} while (std::next_permutation(order, order + 3));
}
#if BUILDFLAG(IS_WIN)
// Test view focus retention when a widget's HWND is disabled and re-enabled.
TEST_F(WidgetTestInteractive, ViewFocusOnHWNDEnabledChanges) {
WidgetAutoclosePtr widget(CreateTopLevelFramelessPlatformWidget());
widget->SetContentsView(std::make_unique<View>());
for (size_t i = 0; i < 2; ++i) {
auto child = std::make_unique<View>();
child->SetFocusBehavior(View::FocusBehavior::ALWAYS);
widget->GetContentsView()->AddChildView(std::move(child));
}
widget->Show();
widget->GetNativeWindow()->GetHost()->Show();
const HWND hwnd = HWNDForWidget(widget.get());
EXPECT_TRUE(::IsWindow(hwnd));
EXPECT_TRUE(::IsWindowEnabled(hwnd));
EXPECT_EQ(hwnd, ::GetActiveWindow());
for (View* view : widget->GetContentsView()->children()) {
SCOPED_TRACE("Child view " +
base::NumberToString(
widget->GetContentsView()->GetIndexOf(view).value()));
view->RequestFocus();
EXPECT_EQ(view, widget->GetFocusManager()->GetFocusedView());
EXPECT_FALSE(::EnableWindow(hwnd, FALSE));
EXPECT_FALSE(::IsWindowEnabled(hwnd));
// Oddly, disabling the HWND leaves it active with the focus unchanged.
EXPECT_EQ(hwnd, ::GetActiveWindow());
EXPECT_TRUE(widget->IsActive());
EXPECT_EQ(view, widget->GetFocusManager()->GetFocusedView());
EXPECT_TRUE(::EnableWindow(hwnd, TRUE));
EXPECT_TRUE(::IsWindowEnabled(hwnd));
EXPECT_EQ(hwnd, ::GetActiveWindow());
EXPECT_TRUE(widget->IsActive());
EXPECT_EQ(view, widget->GetFocusManager()->GetFocusedView());
}
}
// This class subclasses the Widget class to listen for activation change
// notifications and provides accessors to return information as to whether
// the widget is active. We need this to ensure that users of the widget
// class activate the widget only when the underlying window becomes really
// active. Previously we would activate the widget in the WM_NCACTIVATE
// message which is incorrect because APIs like FlashWindowEx flash the
// window caption by sending fake WM_NCACTIVATE messages.
class WidgetActivationTest : public Widget {
public:
WidgetActivationTest() = default;
WidgetActivationTest(const WidgetActivationTest&) = delete;
WidgetActivationTest& operator=(const WidgetActivationTest&) = delete;
~WidgetActivationTest() override = default;
bool OnNativeWidgetActivationChanged(bool active) override {
active_ = active;
return true;
}
bool active() const { return active_; }
private:
bool active_ = false;
};
// Tests whether the widget only becomes active when the underlying window
// is really active.
TEST_F(WidgetTestInteractive, WidgetNotActivatedOnFakeActivationMessages) {
UniqueWidgetPtrT widget1 = std::make_unique<WidgetActivationTest>();
Widget::InitParams init_params =
CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
init_params.native_widget = new DesktopNativeWidgetAura(widget1.get());
init_params.bounds = gfx::Rect(0, 0, 200, 200);
widget1->Init(std::move(init_params));
widget1->Show();
EXPECT_EQ(true, widget1->active());
UniqueWidgetPtrT widget2 = std::make_unique<WidgetActivationTest>();
init_params = CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
init_params.native_widget = new DesktopNativeWidgetAura(widget2.get());
widget2->Init(std::move(init_params));
widget2->Show();
EXPECT_EQ(true, widget2->active());
EXPECT_EQ(false, widget1->active());
HWND win32_native_window1 = HWNDForWidget(widget1.get());
EXPECT_TRUE(::IsWindow(win32_native_window1));
::SendMessage(win32_native_window1, WM_NCACTIVATE, 1, 0);
EXPECT_EQ(false, widget1->active());
EXPECT_EQ(true, widget2->active());
::SetActiveWindow(win32_native_window1);
EXPECT_EQ(true, widget1->active());
EXPECT_EQ(false, widget2->active());
}
// On Windows if we create a fullscreen window on a thread, then it affects the
// way other windows on the thread interact with the taskbar. To workaround
// this we reduce the bounds of a fullscreen window by 1px when it loses
// activation. This test verifies the same.
TEST_F(WidgetTestInteractive, FullscreenBoundsReducedOnActivationLoss) {
UniqueWidgetPtr widget1 = std::make_unique<Widget>();
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.native_widget = new DesktopNativeWidgetAura(widget1.get());
widget1->Init(std::move(params));
widget1->SetBounds(gfx::Rect(0, 0, 200, 200));
widget1->Show();
widget1->Activate();
RunPendingMessages();
EXPECT_EQ(::GetActiveWindow(),
widget1->GetNativeWindow()->GetHost()->GetAcceleratedWidget());
widget1->SetFullscreen(true);
EXPECT_TRUE(widget1->IsFullscreen());
// Ensure that the StopIgnoringPosChanges task in HWNDMessageHandler runs.
// This task is queued when a widget becomes fullscreen.
RunPendingMessages();
EXPECT_EQ(::GetActiveWindow(),
widget1->GetNativeWindow()->GetHost()->GetAcceleratedWidget());
gfx::Rect fullscreen_bounds = widget1->GetWindowBoundsInScreen();
UniqueWidgetPtr widget2 = std::make_unique<Widget>();
params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.native_widget = new DesktopNativeWidgetAura(widget2.get());
widget2->Init(std::move(params));
widget2->SetBounds(gfx::Rect(0, 0, 200, 200));
widget2->Show();
widget2->Activate();
RunPendingMessages();
EXPECT_EQ(::GetActiveWindow(),
widget2->GetNativeWindow()->GetHost()->GetAcceleratedWidget());
gfx::Rect fullscreen_bounds_after_activation_loss =
widget1->GetWindowBoundsInScreen();
// After deactivation loss the bounds of the fullscreen widget should be
// reduced by 1px.
EXPECT_EQ(fullscreen_bounds.height() -
fullscreen_bounds_after_activation_loss.height(),
1);
widget1->Activate();
RunPendingMessages();
EXPECT_EQ(::GetActiveWindow(),
widget1->GetNativeWindow()->GetHost()->GetAcceleratedWidget());
gfx::Rect fullscreen_bounds_after_activate =
widget1->GetWindowBoundsInScreen();
// After activation the bounds of the fullscreen widget should be restored.
EXPECT_EQ(fullscreen_bounds, fullscreen_bounds_after_activate);
}
// Ensure the window rect and client rects are correct with a window that was
// maximized.
TEST_F(WidgetTestInteractive, FullscreenMaximizedWindowBounds) {
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.native_widget = new DesktopNativeWidgetAura(widget.get());
widget->set_frame_type(Widget::FrameType::kForceCustom);
widget->Init(std::move(params));
widget->SetBounds(gfx::Rect(0, 0, 200, 200));
widget->Show();
widget->Maximize();
EXPECT_TRUE(widget->IsMaximized());
widget->SetFullscreen(true);
EXPECT_TRUE(widget->IsFullscreen());
EXPECT_FALSE(widget->IsMaximized());
// Ensure that the StopIgnoringPosChanges task in HWNDMessageHandler runs.
// This task is queued when a widget becomes fullscreen.
RunPendingMessages();
aura::WindowTreeHost* host = widget->GetNativeWindow()->GetHost();
HWND hwnd = host->GetAcceleratedWidget();
HMONITOR monitor = ::MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
ASSERT_TRUE(!!monitor);
MONITORINFO monitor_info;
monitor_info.cbSize = sizeof(monitor_info);
ASSERT_TRUE(::GetMonitorInfo(monitor, &monitor_info));
gfx::Rect monitor_bounds(monitor_info.rcMonitor);
gfx::Rect window_bounds = widget->GetWindowBoundsInScreen();
gfx::Rect client_area_bounds = host->GetBoundsInPixels();
EXPECT_EQ(window_bounds, monitor_bounds);
EXPECT_EQ(monitor_bounds, client_area_bounds);
// Setting not fullscreen should return it to maximized.
widget->SetFullscreen(false);
EXPECT_FALSE(widget->IsFullscreen());
EXPECT_TRUE(widget->IsMaximized());
client_area_bounds = host->GetBoundsInPixels();
EXPECT_TRUE(monitor_bounds.Contains(client_area_bounds));
EXPECT_NE(monitor_bounds, client_area_bounds);
}
#endif // BUILDFLAG(IS_WIN)
#if BUILDFLAG(ENABLE_DESKTOP_AURA) || BUILDFLAG(IS_MAC)
// Tests whether the focused window is set correctly when a modal window is
// created and destroyed. When it is destroyed it should focus the owner window.
TEST_F(DesktopWidgetTestInteractive, WindowModalWindowDestroyedActivationTest) {
TestWidgetFocusChangeListener focus_listener;
WidgetFocusManager::GetInstance()->AddFocusChangeListener(&focus_listener);
const std::vector<gfx::NativeView>& focus_changes =
focus_listener.focus_changes();
// Create a top level widget.
UniqueWidgetPtr top_level_widget = std::make_unique<Widget>();
Widget::InitParams init_params =
CreateParams(Widget::InitParams::TYPE_WINDOW);
init_params.show_state = ui::SHOW_STATE_NORMAL;
gfx::Rect initial_bounds(0, 0, 500, 500);
init_params.bounds = initial_bounds;
top_level_widget->Init(std::move(init_params));
ShowSync(top_level_widget.get());
gfx::NativeView top_level_native_view = top_level_widget->GetNativeView();
ASSERT_FALSE(focus_listener.focus_changes().empty());
EXPECT_EQ(1u, focus_changes.size());
EXPECT_EQ(top_level_native_view, focus_changes[0]);
// Create a modal dialog.
auto dialog_delegate = std::make_unique<DialogDelegateView>();
dialog_delegate->SetModalType(ui::MODAL_TYPE_WINDOW);
Widget* modal_dialog_widget = views::DialogDelegate::CreateDialogWidget(
dialog_delegate.release(), nullptr, top_level_widget->GetNativeView());
modal_dialog_widget->SetBounds(gfx::Rect(100, 100, 200, 200));
// Note the dialog widget doesn't need a ShowSync. Since it is modal, it gains
// active status synchronously, even on Mac.
modal_dialog_widget->Show();
gfx::NativeView modal_native_view = modal_dialog_widget->GetNativeView();
ASSERT_EQ(3u, focus_changes.size());
EXPECT_EQ(gfx::kNullNativeView, focus_changes[1]);
EXPECT_EQ(modal_native_view, focus_changes[2]);
#if BUILDFLAG(IS_MAC)
// Window modal dialogs on Mac are "sheets", which animate to close before
// activating their parent widget.
views::test::WidgetActivationWaiter waiter(top_level_widget.get(), true);
modal_dialog_widget->Close();
waiter.Wait();
#else
views::test::WidgetDestroyedWaiter waiter(modal_dialog_widget);
modal_dialog_widget->Close();
waiter.Wait();
#endif
ASSERT_EQ(5u, focus_changes.size());
EXPECT_EQ(gfx::kNullNativeView, focus_changes[3]);
EXPECT_EQ(top_level_native_view, focus_changes[4]);
top_level_widget->Close();
WidgetFocusManager::GetInstance()->RemoveFocusChangeListener(&focus_listener);
}
#endif
TEST_F(DesktopWidgetTestInteractive, CanActivateFlagIsHonored) {
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams init_params =
CreateParams(Widget::InitParams::TYPE_WINDOW);
init_params.bounds = gfx::Rect(0, 0, 200, 200);
init_params.activatable = Widget::InitParams::Activatable::kNo;
widget->Init(std::move(init_params));
widget->Show();
EXPECT_FALSE(widget->IsActive());
}
#if defined(USE_AURA)
// Test that touch selection quick menu is not activated when opened.
TEST_F(DesktopWidgetTestInteractive, TouchSelectionQuickMenuIsNotActivated) {
WidgetAutoclosePtr widget(CreateTopLevelNativeWidget());
widget->SetBounds(gfx::Rect(0, 0, 200, 200));
std::unique_ptr<Textfield> textfield = CreateTextfield();
auto* const textfield_ptr = textfield.get();
textfield_ptr->SetBounds(0, 0, 200, 20);
textfield_ptr->SetText(u"some text");
widget->GetRootView()->AddChildView(std::move(textfield));
ShowSync(widget.get());
textfield_ptr->RequestFocus();
textfield_ptr->SelectAll(true);
TextfieldTestApi textfield_test_api(textfield_ptr);
ui::test::EventGenerator generator(GetRootWindow(widget.get()));
generator.GestureTapAt(textfield_ptr->GetBoundsInScreen().origin() +
gfx::Vector2d(10, 10));
// The touch selection controller must be created in response to tapping.
ASSERT_TRUE(textfield_test_api.touch_selection_controller());
static_cast<TouchSelectionControllerImpl*>(
textfield_test_api.touch_selection_controller())
->ShowQuickMenuImmediatelyForTesting();
EXPECT_TRUE(textfield_ptr->HasFocus());
EXPECT_TRUE(widget->IsActive());
EXPECT_TRUE(ui::TouchSelectionMenuRunner::GetInstance()->IsRunning());
}
#endif // defined(USE_AURA)
#if BUILDFLAG(IS_WIN)
TEST_F(DesktopWidgetTestInteractive, DisableViewDoesNotActivateWidget) {
#else
TEST_F(WidgetTestInteractive, DisableViewDoesNotActivateWidget) {
#endif // !BUILDFLAG(IS_WIN)
// Create first widget and view, activate the widget, and focus the view.
UniqueWidgetPtr widget1 = std::make_unique<Widget>();
Widget::InitParams params1 = CreateParams(Widget::InitParams::TYPE_POPUP);
params1.activatable = Widget::InitParams::Activatable::kYes;
widget1->Init(std::move(params1));
View* view1 = widget1->GetRootView()->AddChildView(std::make_unique<View>());
view1->SetFocusBehavior(View::FocusBehavior::ALWAYS);
widget1->Show();
ActivateSync(widget1.get());
FocusManager* focus_manager1 = widget1->GetFocusManager();
ASSERT_TRUE(focus_manager1);
focus_manager1->SetFocusedView(view1);
EXPECT_EQ(view1, focus_manager1->GetFocusedView());
// Create second widget and view, activate the widget, and focus the view.
UniqueWidgetPtr widget2 = std::make_unique<Widget>();
Widget::InitParams params2 = CreateParams(Widget::InitParams::TYPE_POPUP);
params2.activatable = Widget::InitParams::Activatable::kYes;
widget2->Init(std::move(params2));
View* view2 = widget2->GetRootView()->AddChildView(std::make_unique<View>());
view2->SetFocusBehavior(View::FocusBehavior::ALWAYS);
widget2->Show();
ActivateSync(widget2.get());
EXPECT_TRUE(widget2->IsActive());
EXPECT_FALSE(widget1->IsActive());
FocusManager* focus_manager2 = widget2->GetFocusManager();
ASSERT_TRUE(focus_manager2);
focus_manager2->SetFocusedView(view2);
EXPECT_EQ(view2, focus_manager2->GetFocusedView());
// Disable the first view and make sure it loses focus, but its widget is not
// activated.
view1->SetEnabled(false);
EXPECT_NE(view1, focus_manager1->GetFocusedView());
EXPECT_FALSE(widget1->IsActive());
EXPECT_TRUE(widget2->IsActive());
}
TEST_F(WidgetTestInteractive, ShowCreatesActiveWindow) {
WidgetAutoclosePtr widget(CreateTopLevelPlatformWidget());
ShowSync(widget.get());
EXPECT_EQ(GetWidgetShowState(widget.get()), ui::SHOW_STATE_NORMAL);
}
TEST_F(WidgetTestInteractive, ShowInactive) {
WidgetTest::WaitForSystemAppActivation();
WidgetAutoclosePtr widget(CreateTopLevelPlatformWidget());
ShowInactiveSync(widget.get());
EXPECT_EQ(GetWidgetShowState(widget.get()), ui::SHOW_STATE_INACTIVE);
}
TEST_F(WidgetTestInteractive, InactiveBeforeShow) {
WidgetAutoclosePtr widget(CreateTopLevelPlatformWidget());
EXPECT_FALSE(widget->IsActive());
EXPECT_FALSE(widget->IsVisible());
ShowSync(widget.get());
EXPECT_TRUE(widget->IsActive());
EXPECT_TRUE(widget->IsVisible());
}
TEST_F(WidgetTestInteractive, ShowInactiveAfterShow) {
// Create 2 widgets to ensure window layering does not change.
WidgetAutoclosePtr widget(CreateTopLevelPlatformWidget());
WidgetAutoclosePtr widget2(CreateTopLevelPlatformWidget());
ShowSync(widget2.get());
EXPECT_FALSE(widget->IsActive());
EXPECT_TRUE(widget2->IsVisible());
EXPECT_TRUE(widget2->IsActive());
ShowSync(widget.get());
EXPECT_TRUE(widget->IsActive());
EXPECT_FALSE(widget2->IsActive());
ShowInactiveSync(widget.get());
EXPECT_TRUE(widget->IsActive());
EXPECT_FALSE(widget2->IsActive());
EXPECT_EQ(GetWidgetShowState(widget.get()), ui::SHOW_STATE_NORMAL);
}
TEST_F(WidgetTestInteractive, ShowAfterShowInactive) {
WidgetAutoclosePtr widget(CreateTopLevelPlatformWidget());
widget->SetBounds(gfx::Rect(100, 100, 100, 100));
ShowInactiveSync(widget.get());
ShowSync(widget.get());
EXPECT_EQ(GetWidgetShowState(widget.get()), ui::SHOW_STATE_NORMAL);
}
TEST_F(WidgetTestInteractive, WidgetShouldBeActiveWhenShow) {
// TODO(crbug/1217331): This test fails if put under NativeWidgetAuraTest.
WidgetAutoclosePtr anchor_widget(CreateTopLevelNativeWidget());
test::WidgetActivationWaiter waiter(anchor_widget.get(), true);
anchor_widget->Show();
waiter.Wait();
EXPECT_TRUE(anchor_widget->IsActive());
#if !BUILDFLAG(IS_MAC)
EXPECT_TRUE(anchor_widget->GetNativeWindow()->HasFocus());
#endif
}
#if BUILDFLAG(ENABLE_DESKTOP_AURA) || BUILDFLAG(IS_MAC)
// TODO(crbug.com/1438286): Re-enable this test
TEST_F(WidgetTestInteractive, DISABLED_InactiveWidgetDoesNotGrabActivation) {
UniqueWidgetPtr widget = base::WrapUnique(CreateTopLevelPlatformWidget());
ShowSync(widget.get());
EXPECT_EQ(GetWidgetShowState(widget.get()), ui::SHOW_STATE_NORMAL);
UniqueWidgetPtr widget2 = std::make_unique<Widget>();
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
widget2->Init(std::move(params));
widget2->Show();
RunPendingMessagesForActiveStatusChange();
EXPECT_EQ(GetWidgetShowState(widget2.get()), ui::SHOW_STATE_INACTIVE);
EXPECT_EQ(GetWidgetShowState(widget.get()), ui::SHOW_STATE_NORMAL);
}
#endif // BUILDFLAG(ENABLE_DESKTOP_AURA) || BUILDFLAG(IS_MAC)
// ExitFullscreenRestoreState doesn't use DesktopAura widgets. On Mac, there are
// currently only Desktop widgets and fullscreen changes have to coordinate with
// the OS. See BridgedNativeWidgetUITest for native Mac fullscreen tests.
// Maximize on mac is also (intentionally) a no-op.
#if BUILDFLAG(IS_MAC)
#define MAYBE_ExitFullscreenRestoreState DISABLED_ExitFullscreenRestoreState
#else
#define MAYBE_ExitFullscreenRestoreState ExitFullscreenRestoreState
#endif
// Test that window state is not changed after getting out of full screen.
TEST_F(WidgetTestInteractive, MAYBE_ExitFullscreenRestoreState) {
WidgetAutoclosePtr toplevel(CreateTopLevelPlatformWidget());
toplevel->Show();
RunPendingMessages();
// This should be a normal state window.
EXPECT_EQ(ui::SHOW_STATE_NORMAL, GetWidgetShowState(toplevel.get()));
toplevel->SetFullscreen(true);
EXPECT_EQ(ui::SHOW_STATE_FULLSCREEN, GetWidgetShowState(toplevel.get()));
toplevel->SetFullscreen(false);
EXPECT_NE(ui::SHOW_STATE_FULLSCREEN, GetWidgetShowState(toplevel.get()));
// And it should still be in normal state after getting out of full screen.
EXPECT_EQ(ui::SHOW_STATE_NORMAL, GetWidgetShowState(toplevel.get()));
// Now, make it maximized.
toplevel->Maximize();
EXPECT_EQ(ui::SHOW_STATE_MAXIMIZED, GetWidgetShowState(toplevel.get()));
toplevel->SetFullscreen(true);
EXPECT_EQ(ui::SHOW_STATE_FULLSCREEN, GetWidgetShowState(toplevel.get()));
toplevel->SetFullscreen(false);
EXPECT_NE(ui::SHOW_STATE_FULLSCREEN, GetWidgetShowState(toplevel.get()));
// And it stays maximized after getting out of full screen.
EXPECT_EQ(ui::SHOW_STATE_MAXIMIZED, GetWidgetShowState(toplevel.get()));
}
// Testing initial focus is assigned properly for normal top-level widgets,
// and subclasses that specify a initially focused child view.
TEST_F(WidgetTestInteractive, InitialFocus) {
// By default, there is no initially focused view (even if there is a
// focusable subview).
Widget* toplevel(CreateTopLevelPlatformWidget());
View* view = new View;
view->SetFocusBehavior(View::FocusBehavior::ALWAYS);
toplevel->GetContentsView()->AddChildView(view);
ShowSync(toplevel);
toplevel->Show();
EXPECT_FALSE(view->HasFocus());
EXPECT_FALSE(toplevel->GetFocusManager()->GetStoredFocusView());
toplevel->CloseNow();
// Testing a widget which specifies a initially focused view.
TestInitialFocusWidgetDelegate delegate(GetContext());
Widget* widget = delegate.GetWidget();
ShowSync(widget);
widget->Show();
EXPECT_TRUE(delegate.view()->HasFocus());
EXPECT_EQ(delegate.view(), widget->GetFocusManager()->GetStoredFocusView());
}
TEST_F(DesktopWidgetTestInteractive, RestoreAfterMinimize) {
WidgetAutoclosePtr widget(CreateTopLevelNativeWidget());
ShowSync(widget.get());
ASSERT_FALSE(widget->IsMinimized());
PropertyWaiter minimize_waiter(
base::BindRepeating(&Widget::IsMinimized, base::Unretained(widget.get())),
true);
widget->Minimize();
EXPECT_TRUE(minimize_waiter.Wait());
PropertyWaiter restore_waiter(
base::BindRepeating(&Widget::IsMinimized, base::Unretained(widget.get())),
false);
widget->Restore();
EXPECT_TRUE(restore_waiter.Wait());
}
// Maximize is not implemented on macOS, see crbug.com/868599
#if !BUILDFLAG(IS_MAC)
// Widget::Show/ShowInactive should not restore a maximized window
TEST_F(DesktopWidgetTestInteractive, ShowAfterMaximize) {
WidgetAutoclosePtr widget(CreateTopLevelNativeWidget());
ShowSync(widget.get());
ASSERT_FALSE(widget->IsMaximized());
PropertyWaiter maximize_waiter(
base::BindRepeating(&Widget::IsMaximized, base::Unretained(widget.get())),
true);
widget->Maximize();
EXPECT_TRUE(maximize_waiter.Wait());
ShowSync(widget.get());
EXPECT_TRUE(widget->IsMaximized());
ShowInactiveSync(widget.get());
EXPECT_TRUE(widget->IsMaximized());
}
#endif
#if BUILDFLAG(IS_WIN)
// TODO(davidbienvenu): Get this test to pass on Linux and ChromeOS by hiding
// the root window when desktop widget is minimized.
// Tests that root window visibility toggles correctly when the desktop widget
// is minimized and maximized on Windows, and the Widget remains visible.
TEST_F(DesktopWidgetTestInteractive, RestoreAndMinimizeVisibility) {
WidgetAutoclosePtr widget(CreateTopLevelNativeWidget());
aura::Window* root_window = GetRootWindow(widget.get());
ShowSync(widget.get());
ASSERT_FALSE(widget->IsMinimized());
EXPECT_TRUE(root_window->IsVisible());
PropertyWaiter minimize_widget_waiter(
base::BindRepeating(&Widget::IsMinimized, base::Unretained(widget.get())),
true);
widget->Minimize();
EXPECT_TRUE(minimize_widget_waiter.Wait());
EXPECT_TRUE(widget->IsVisible());
EXPECT_FALSE(root_window->IsVisible());
PropertyWaiter restore_widget_waiter(
base::BindRepeating(&Widget::IsMinimized, base::Unretained(widget.get())),
false);
widget->Restore();
EXPECT_TRUE(restore_widget_waiter.Wait());
EXPECT_TRUE(widget->IsVisible());
EXPECT_TRUE(root_window->IsVisible());
}
// Test that focus is restored to the widget after a minimized window
// is activated.
TEST_F(DesktopWidgetTestInteractive, MinimizeAndActivateFocus) {
WidgetAutoclosePtr widget(CreateTopLevelNativeWidget());
aura::Window* root_window = GetRootWindow(widget.get());
auto* widget_window = widget->GetNativeWindow();
ShowSync(widget.get());
ASSERT_FALSE(widget->IsMinimized());
EXPECT_TRUE(root_window->IsVisible());
widget_window->Focus();
EXPECT_TRUE(widget_window->HasFocus());
widget->GetContentsView()->SetFocusBehavior(View::FocusBehavior::ALWAYS);
widget->GetContentsView()->RequestFocus();
EXPECT_TRUE(widget->GetContentsView()->HasFocus());
PropertyWaiter minimize_widget_waiter(
base::BindRepeating(&Widget::IsMinimized, base::Unretained(widget.get())),
true);
widget->Minimize();
EXPECT_TRUE(minimize_widget_waiter.Wait());
EXPECT_TRUE(widget->IsVisible());
EXPECT_FALSE(root_window->IsVisible());
PropertyWaiter restore_widget_waiter(
base::BindRepeating(&Widget::IsMinimized, base::Unretained(widget.get())),
false);
widget->Activate();
EXPECT_TRUE(widget->GetContentsView()->HasFocus());
EXPECT_TRUE(restore_widget_waiter.Wait());
EXPECT_TRUE(widget->IsVisible());
EXPECT_TRUE(root_window->IsVisible());
EXPECT_TRUE(widget_window->CanFocus());
}
#endif // BUILDFLAG(IS_WIN)
#if BUILDFLAG(ENABLE_DESKTOP_AURA) || BUILDFLAG(IS_MAC)
// Tests that minimizing a widget causes the gesture_handler
// to be cleared when the widget is minimized.
TEST_F(DesktopWidgetTestInteractive, EventHandlersClearedOnWidgetMinimize) {
WidgetAutoclosePtr widget(CreateTopLevelNativeWidget());
ShowSync(widget.get());
ASSERT_FALSE(widget->IsMinimized());
View mouse_handler_view;
internal::RootView* root_view =
static_cast<internal::RootView*>(widget->GetRootView());
// This also sets the gesture_handler, and we'll verify that it
// gets cleared when the widget is minimized.
root_view->SetMouseAndGestureHandler(&mouse_handler_view);
EXPECT_TRUE(GetGestureHandler(root_view));
widget->Minimize();
{
views::test::PropertyWaiter minimize_waiter(
base::BindRepeating(&Widget::IsMinimized,
base::Unretained(widget.get())),
true);
EXPECT_TRUE(minimize_waiter.Wait());
}
EXPECT_FALSE(GetGestureHandler(root_view));
}
#endif
#if (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)) && \
BUILDFLAG(ENABLE_DESKTOP_AURA)
// Tests that when a desktop native widget has modal transient child, it should
// avoid restore focused view itself as the modal transient child window will do
// that, thus avoids having multiple focused view visually (crbug.com/727641).
TEST_F(DesktopWidgetTestInteractive,
DesktopNativeWidgetWithModalTransientChild) {
// Create a desktop native Widget for Widget::Deactivate().
WidgetAutoclosePtr deactivate_widget(CreateTopLevelNativeWidget());
ShowSync(deactivate_widget.get());
// Create a top level desktop native widget.
WidgetAutoclosePtr top_level(CreateTopLevelNativeWidget());
std::unique_ptr<Textfield> textfield = CreateTextfield();
auto* const textfield_ptr = textfield.get();
textfield_ptr->SetBounds(0, 0, 200, 20);
top_level->GetRootView()->AddChildView(std::move(textfield));
ShowSync(top_level.get());
textfield_ptr->RequestFocus();
EXPECT_TRUE(textfield_ptr->HasFocus());
// Create a modal dialog.
// This instance will be destroyed when the dialog is destroyed.
auto dialog_delegate = std::make_unique<DialogDelegateView>();
dialog_delegate->SetModalType(ui::MODAL_TYPE_WINDOW);
Widget* modal_dialog_widget = DialogDelegate::CreateDialogWidget(
dialog_delegate.release(), nullptr, top_level->GetNativeView());
modal_dialog_widget->SetBounds(gfx::Rect(0, 0, 100, 10));
std::unique_ptr<Textfield> dialog_textfield = CreateTextfield();
auto* const dialog_textfield_ptr = dialog_textfield.get();
dialog_textfield_ptr->SetBounds(0, 0, 50, 5);
modal_dialog_widget->GetRootView()->AddChildView(std::move(dialog_textfield));
// Dialog widget doesn't need a ShowSync as it gains active status
// synchronously.
modal_dialog_widget->Show();
dialog_textfield_ptr->RequestFocus();
EXPECT_TRUE(dialog_textfield_ptr->HasFocus());
EXPECT_FALSE(textfield_ptr->HasFocus());
DeactivateSync(top_level.get());
EXPECT_FALSE(dialog_textfield_ptr->HasFocus());
EXPECT_FALSE(textfield_ptr->HasFocus());
// After deactivation and activation of top level widget, only modal dialog
// should restore focused view.
ActivateSync(top_level.get());
EXPECT_TRUE(dialog_textfield_ptr->HasFocus());
EXPECT_FALSE(textfield_ptr->HasFocus());
}
#endif // (BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)) &&
// BUILDFLAG(ENABLE_DESKTOP_AURA)
namespace {
// Helper class for CaptureLostTrackingWidget to store whether
// OnMouseCaptureLost has been invoked for a widget.
class CaptureLostState {
public:
CaptureLostState() = default;
CaptureLostState(const CaptureLostState&) = delete;
CaptureLostState& operator=(const CaptureLostState&) = delete;
bool GetAndClearGotCaptureLost() {
bool value = got_capture_lost_;
got_capture_lost_ = false;
return value;
}
void OnMouseCaptureLost() { got_capture_lost_ = true; }
private:
bool got_capture_lost_ = false;
};
// Used to verify OnMouseCaptureLost() has been invoked.
class CaptureLostTrackingWidget : public Widget {
public:
explicit CaptureLostTrackingWidget(CaptureLostState* capture_lost_state)
: capture_lost_state_(capture_lost_state) {}
CaptureLostTrackingWidget(const CaptureLostTrackingWidget&) = delete;
CaptureLostTrackingWidget& operator=(const CaptureLostTrackingWidget&) =
delete;
// Widget:
void OnMouseCaptureLost() override {
capture_lost_state_->OnMouseCaptureLost();
Widget::OnMouseCaptureLost();
}
private:
// Weak. Stores whether OnMouseCaptureLost has been invoked for this widget.
raw_ptr<CaptureLostState> capture_lost_state_;
};
} // namespace
class WidgetCaptureTest : public DesktopWidgetTestInteractive {
public:
WidgetCaptureTest() = default;
WidgetCaptureTest(const WidgetCaptureTest&) = delete;
WidgetCaptureTest& operator=(const WidgetCaptureTest&) = delete;
~WidgetCaptureTest() override = default;
// Verifies Widget::SetCapture() results in updating native capture along with
// invoking the right Widget function.
void TestCapture(bool use_desktop_native_widget) {
UniqueWidgetPtrT widget1 =
std::make_unique<CaptureLostTrackingWidget>(capture_state1_.get());
InitPlatformWidget(widget1.get(), use_desktop_native_widget);
widget1->Show();
UniqueWidgetPtrT widget2 =
std::make_unique<CaptureLostTrackingWidget>(capture_state2_.get());
InitPlatformWidget(widget2.get(), use_desktop_native_widget);
widget2->Show();
// Set capture to widget2 and verity it gets it.
widget2->SetCapture(widget2->GetRootView());
EXPECT_FALSE(widget1->HasCapture());
EXPECT_TRUE(widget2->HasCapture());
EXPECT_FALSE(capture_state1_->GetAndClearGotCaptureLost());
EXPECT_FALSE(capture_state2_->GetAndClearGotCaptureLost());
// Set capture to widget1 and verify it gets it.
widget1->SetCapture(widget1->GetRootView());
EXPECT_TRUE(widget1->HasCapture());
EXPECT_FALSE(widget2->HasCapture());
EXPECT_FALSE(capture_state1_->GetAndClearGotCaptureLost());
EXPECT_TRUE(capture_state2_->GetAndClearGotCaptureLost());
// Release and verify no one has it.
widget1->ReleaseCapture();
EXPECT_FALSE(widget1->HasCapture());
EXPECT_FALSE(widget2->HasCapture());
EXPECT_TRUE(capture_state1_->GetAndClearGotCaptureLost());
EXPECT_FALSE(capture_state2_->GetAndClearGotCaptureLost());
}
void InitPlatformWidget(Widget* widget, bool use_desktop_native_widget) {
Widget::InitParams params =
CreateParams(views::Widget::InitParams::TYPE_WINDOW);
// The test class by default returns DesktopNativeWidgetAura.
params.native_widget =
use_desktop_native_widget
? nullptr
: CreatePlatformNativeWidgetImpl(widget, kDefault, nullptr);
widget->Init(std::move(params));
}
protected:
void SetUp() override {
DesktopWidgetTestInteractive::SetUp();
capture_state1_ = std::make_unique<CaptureLostState>();
capture_state2_ = std::make_unique<CaptureLostState>();
}
void TearDown() override {
capture_state1_.reset();
capture_state2_.reset();
DesktopWidgetTestInteractive::TearDown();
}
private:
std::unique_ptr<CaptureLostState> capture_state1_;
std::unique_ptr<CaptureLostState> capture_state2_;
};
// See description in TestCapture().
TEST_F(WidgetCaptureTest, Capture) {
TestCapture(false);
}
#if BUILDFLAG(ENABLE_DESKTOP_AURA) || BUILDFLAG(IS_MAC)
// See description in TestCapture(). Creates DesktopNativeWidget.
TEST_F(WidgetCaptureTest, CaptureDesktopNativeWidget) {
TestCapture(true);
}
#endif
// Tests to ensure capture is correctly released from a Widget with capture when
// it is destroyed. Test for crbug.com/622201.
TEST_F(WidgetCaptureTest, DestroyWithCapture_CloseNow) {
CaptureLostState capture_state;
CaptureLostTrackingWidget* widget =
new CaptureLostTrackingWidget(&capture_state);
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
widget->Init(std::move(params));
widget->Show();
widget->SetCapture(widget->GetRootView());
EXPECT_TRUE(widget->HasCapture());
EXPECT_FALSE(capture_state.GetAndClearGotCaptureLost());
widget->CloseNow();
EXPECT_TRUE(capture_state.GetAndClearGotCaptureLost());
}
TEST_F(WidgetCaptureTest, DestroyWithCapture_Close) {
CaptureLostState capture_state;
CaptureLostTrackingWidget* widget =
new CaptureLostTrackingWidget(&capture_state);
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
widget->Init(std::move(params));
widget->Show();
widget->SetCapture(widget->GetRootView());
EXPECT_TRUE(widget->HasCapture());
EXPECT_FALSE(capture_state.GetAndClearGotCaptureLost());
widget->Close();
EXPECT_TRUE(capture_state.GetAndClearGotCaptureLost());
}
// TODO(kylixrd): Remove this test once Widget ownership is normalized.
TEST_F(WidgetCaptureTest, DestroyWithCapture_WidgetOwnsNativeWidget) {
Widget widget;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget.Init(std::move(params));
widget.Show();
widget.SetCapture(widget.GetRootView());
EXPECT_TRUE(widget.HasCapture());
}
// Test that no state is set if capture fails.
TEST_F(WidgetCaptureTest, FailedCaptureRequestIsNoop) {
UniqueWidgetPtr widget = std::make_unique<Widget>();
Widget::InitParams params =
CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
params.bounds = gfx::Rect(400, 400);
widget->Init(std::move(params));
auto contents_view = std::make_unique<View>();
MouseView* mouse_view1 =
contents_view->AddChildView(std::make_unique<MouseView>());
MouseView* mouse_view2 =
contents_view->AddChildView(std::make_unique<MouseView>());
widget->SetContentsView(std::move(contents_view));
mouse_view1->SetBounds(0, 0, 200, 400);
mouse_view2->SetBounds(200, 0, 200, 400);
// Setting capture should fail because |widget| is not visible.
widget->SetCapture(mouse_view1);
EXPECT_FALSE(widget->HasCapture());
widget->Show();
ui::test::EventGenerator generator(GetRootWindow(widget.get()),
widget->GetNativeWindow());
generator.set_current_screen_location(
widget->GetClientAreaBoundsInScreen().CenterPoint());
generator.PressLeftButton();
EXPECT_FALSE(mouse_view1->pressed());
EXPECT_TRUE(mouse_view2->pressed());
}
TEST_F(WidgetCaptureTest, CaptureAutoReset) {
WidgetAutoclosePtr toplevel(CreateTopLevelFramelessPlatformWidget());
toplevel->SetContentsView(std::make_unique<View>());
EXPECT_FALSE(toplevel->HasCapture());
toplevel->SetCapture(nullptr);
EXPECT_TRUE(toplevel->HasCapture());
// By default, mouse release removes capture.
gfx::Point click_location(45, 15);
ui::MouseEvent release(ui::ET_MOUSE_RELEASED, click_location, click_location,
ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON,
ui::EF_LEFT_MOUSE_BUTTON);
toplevel->OnMouseEvent(&release);
EXPECT_FALSE(toplevel->HasCapture());
// Now a mouse release shouldn't remove capture.
toplevel->set_auto_release_capture(false);
toplevel->SetCapture(nullptr);
EXPECT_TRUE(toplevel->HasCapture());
toplevel->OnMouseEvent(&release);
EXPECT_TRUE(toplevel->HasCapture());
toplevel->ReleaseCapture();
EXPECT_FALSE(toplevel->HasCapture());
}
TEST_F(WidgetCaptureTest, ResetCaptureOnGestureEnd) {
WidgetAutoclosePtr toplevel(CreateTopLevelFramelessPlatformWidget());
View* container = toplevel->SetContentsView(std::make_unique<View>());
View* gesture = new GestureCaptureView;
gesture->SetBounds(0, 0, 30, 30);
container->AddChildView(gesture);
MouseView* mouse = new MouseView;
mouse->SetBounds(30, 0, 30, 30);
container->AddChildView(mouse);
toplevel->SetSize(gfx::Size(100, 100));
toplevel->Show();
// Start a gesture on |gesture|.
ui::GestureEvent tap_down(15, 15, 0, base::TimeTicks(),
ui::GestureEventDetails(ui::ET_GESTURE_TAP_DOWN));
ui::GestureEvent end(15, 15, 0, base::TimeTicks(),
ui::GestureEventDetails(ui::ET_GESTURE_END));
toplevel->OnGestureEvent(&tap_down);
// Now try to click on |mouse|. Since |gesture| will have capture, |mouse|
// will not receive the event.
gfx::Point click_location(45, 15);
ui::MouseEvent press(ui::ET_MOUSE_PRESSED, click_location, click_location,
ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON,
ui::EF_LEFT_MOUSE_BUTTON);
ui::MouseEvent release(ui::ET_MOUSE_RELEASED, click_location, click_location,
ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON,
ui::EF_LEFT_MOUSE_BUTTON);
EXPECT_TRUE(toplevel->HasCapture());
toplevel->OnMouseEvent(&press);
toplevel->OnMouseEvent(&release);
EXPECT_EQ(0, mouse->pressed());
EXPECT_FALSE(toplevel->HasCapture());
// The end of the gesture should release the capture, and pressing on |mouse|
// should now reach |mouse|.
toplevel->OnGestureEvent(&end);
toplevel->OnMouseEvent(&press);
toplevel->OnMouseEvent(&release);
EXPECT_EQ(1, mouse->pressed());
}
// Checks that if a mouse-press triggers a capture on a different widget (which
// consumes the mouse-release event), then the target of the press does not have
// capture.
TEST_F(WidgetCaptureTest, DisableCaptureWidgetFromMousePress) {
// The test creates two widgets: |first| and |second|.
// The View in |first| makes |second| visible, sets capture on it, and starts
// a nested loop (like a menu does). The View in |second| terminates the
// nested loop and closes the widget.
// The test sends a mouse-press event to |first|, and posts a task to send a
// release event to |second|, to make sure that the release event is
// dispatched after the nested loop starts.
WidgetAutoclosePtr first(CreateTopLevelFramelessPlatformWidget());
Widget* second = CreateTopLevelFramelessPlatformWidget();
NestedLoopCaptureView* container =
first->SetContentsView(std::make_unique<NestedLoopCaptureView>(second));
second->SetContentsView(
std::make_unique<ExitLoopOnRelease>(container->GetQuitClosure()));
first->SetSize(gfx::Size(100, 100));
first->Show();
gfx::Point location(20, 20);
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(
&Widget::OnMouseEvent, base::Unretained(second),
base::Owned(new ui::MouseEvent(
ui::ET_MOUSE_RELEASED, location, location, ui::EventTimeForNow(),
ui::EF_LEFT_MOUSE_BUTTON, ui::EF_LEFT_MOUSE_BUTTON))));
ui::MouseEvent press(ui::ET_MOUSE_PRESSED, location, location,
ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON,
ui::EF_LEFT_MOUSE_BUTTON);
first->OnMouseEvent(&press);
EXPECT_FALSE(first->HasCapture());
}
// Tests some grab/ungrab events. Only one Widget can have capture at any given
// time.
TEST_F(WidgetCaptureTest, GrabUngrab) {
auto top_level = CreateTestWidget();
top_level->SetContentsView(std::make_unique<MouseView>());
Widget* child1 = new Widget;
Widget::InitParams params1 = CreateParams(Widget::InitParams::TYPE_CONTROL);
params1.parent = top_level->GetNativeView();
params1.bounds = gfx::Rect(10, 10, 100, 100);
child1->Init(std::move(params1));
child1->SetContentsView(std::make_unique<MouseView>());
Widget* child2 = new Widget;
Widget::InitParams params2 = CreateParams(Widget::InitParams::TYPE_CONTROL);
params2.parent = top_level->GetNativeView();
params2.bounds = gfx::Rect(110, 10, 100, 100);
child2->Init(std::move(params2));
child2->SetContentsView(std::make_unique<MouseView>());
top_level->Show();
RunPendingMessages();
// Click on child1.
ui::test::EventGenerator generator(GetRootWindow(top_level.get()),
child1->GetNativeWindow());
generator.set_current_screen_location(
child1->GetClientAreaBoundsInScreen().CenterPoint());
generator.PressLeftButton();
EXPECT_FALSE(top_level->HasCapture());
EXPECT_TRUE(child1->HasCapture());
EXPECT_FALSE(child2->HasCapture());
generator.ReleaseLeftButton();
EXPECT_FALSE(top_level->HasCapture());
EXPECT_FALSE(child1->HasCapture());
EXPECT_FALSE(child2->HasCapture());
// Click on child2.
generator.SetTargetWindow(child2->GetNativeWindow());
generator.set_current_screen_location(
child2->GetClientAreaBoundsInScreen().CenterPoint());
generator.PressLeftButton();
EXPECT_FALSE(top_level->HasCapture());
EXPECT_FALSE(child1->HasCapture());
EXPECT_TRUE(child2->HasCapture());
generator.ReleaseLeftButton();
EXPECT_FALSE(top_level->HasCapture());
EXPECT_FALSE(child1->HasCapture());
EXPECT_FALSE(child2->HasCapture());
// Click on top_level.
generator.SetTargetWindow(top_level->GetNativeWindow());
generator.set_current_screen_location(
top_level->GetClientAreaBoundsInScreen().origin());
generator.PressLeftButton();
EXPECT_TRUE(top_level->HasCapture());
EXPECT_FALSE(child1->HasCapture());
EXPECT_FALSE(child2->HasCapture());
generator.ReleaseLeftButton();
EXPECT_FALSE(top_level->HasCapture());
EXPECT_FALSE(child1->HasCapture());
EXPECT_FALSE(child2->HasCapture());
}
// Disabled on Mac. Desktop Mac doesn't have system modal windows since Carbon
// was deprecated. It does have application modal windows, but only Ash requests
// those.
#if BUILDFLAG(IS_MAC)
#define MAYBE_SystemModalWindowReleasesCapture \
DISABLED_SystemModalWindowReleasesCapture
#elif BUILDFLAG(IS_CHROMEOS_ASH)
// Investigate enabling for Chrome OS. It probably requires help from the window
// service.
#define MAYBE_SystemModalWindowReleasesCapture \
DISABLED_SystemModalWindowReleasesCapture
#else
#define MAYBE_SystemModalWindowReleasesCapture SystemModalWindowReleasesCapture
#endif
// Test that when opening a system-modal window, capture is released.
TEST_F(WidgetCaptureTest, MAYBE_SystemModalWindowReleasesCapture) {
TestWidgetFocusChangeListener focus_listener;
WidgetFocusManager::GetInstance()->AddFocusChangeListener(&focus_listener);
// Create a top level widget.
UniqueWidgetPtr top_level_widget = std::make_unique<Widget>();
Widget::InitParams init_params =
CreateParams(Widget::InitParams::TYPE_WINDOW);
init_params.show_state = ui::SHOW_STATE_NORMAL;
gfx::Rect initial_bounds(0, 0, 500, 500);
init_params.bounds = initial_bounds;
top_level_widget->Init(std::move(init_params));
ShowSync(top_level_widget.get());
ASSERT_FALSE(focus_listener.focus_changes().empty());
EXPECT_EQ(top_level_widget->GetNativeView(),
focus_listener.focus_changes().back());
EXPECT_FALSE(top_level_widget->HasCapture());
top_level_widget->SetCapture(nullptr);
EXPECT_TRUE(top_level_widget->HasCapture());
// Create a modal dialog.
auto dialog_delegate = std::make_unique<DialogDelegateView>();
dialog_delegate->SetModalType(ui::MODAL_TYPE_SYSTEM);
Widget* modal_dialog_widget = views::DialogDelegate::CreateDialogWidget(
dialog_delegate.release(), nullptr, top_level_widget->GetNativeView());
modal_dialog_widget->SetBounds(gfx::Rect(100, 100, 200, 200));
ShowSync(modal_dialog_widget);
EXPECT_FALSE(top_level_widget->HasCapture());
WidgetFocusManager::GetInstance()->RemoveFocusChangeListener(&focus_listener);
}
// Regression test for http://crbug.com/382421 (Linux-Aura issue).
// TODO(pkotwicz): Make test pass on CrOS and Windows.
// TODO(tapted): Investigate for toolkit-views on Mac http;//crbug.com/441064.
#if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_MAC)
#define MAYBE_MouseExitOnCaptureGrab DISABLED_MouseExitOnCaptureGrab
#else
#define MAYBE_MouseExitOnCaptureGrab MouseExitOnCaptureGrab
#endif
// Test that a synthetic mouse exit is sent to the widget which was handling
// mouse events when a different widget grabs capture. Except for Windows,
// which does not send a synthetic mouse exit.
TEST_F(WidgetCaptureTest, MAYBE_MouseExitOnCaptureGrab) {
UniqueWidgetPtr widget1 = std::make_unique<Widget>();
Widget::InitParams params1 =
CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
widget1->Init(std::move(params1));
MouseView* mouse_view1 =
widget1->SetContentsView(std::make_unique<MouseView>());
widget1->Show();
widget1->SetBounds(gfx::Rect(300, 300));
UniqueWidgetPtr widget2 = std::make_unique<Widget>();
Widget::InitParams params2 =
CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
widget2->Init(std::move(params2));
widget2->Show();
widget2->SetBounds(gfx::Rect(400, 0, 300, 300));
ui::test::EventGenerator generator(GetRootWindow(widget1.get()));
generator.set_current_screen_location(gfx::Point(100, 100));
generator.MoveMouseBy(0, 0);
EXPECT_EQ(1, mouse_view1->EnteredCalls());
EXPECT_EQ(0, mouse_view1->ExitedCalls());
widget2->SetCapture(nullptr);
EXPECT_EQ(0, mouse_view1->EnteredCalls());
// On Windows, Chrome doesn't synthesize a separate mouse exited event.
// Instead, it uses ::TrackMouseEvent to get notified of the mouse leaving.
// Calling SetCapture does not cause Windows to generate a WM_MOUSELEAVE
// event. See WindowEventDispatcher::OnOtherRootGotCapture() for more info.
#if BUILDFLAG(IS_WIN)
EXPECT_EQ(0, mouse_view1->ExitedCalls());
#else
EXPECT_EQ(1, mouse_view1->ExitedCalls());
#endif // BUILDFLAG(IS_WIN)
}
namespace {
// Widget observer which grabs capture when the widget is activated.
class CaptureOnActivationObserver : public WidgetObserver {
public:
CaptureOnActivationObserver() = default;
CaptureOnActivationObserver(const CaptureOnActivationObserver&) = delete;
CaptureOnActivationObserver& operator=(const CaptureOnActivationObserver&) =
delete;
~CaptureOnActivationObserver() override = default;
// WidgetObserver:
void OnWidgetActivationChanged(Widget* widget, bool active) override {
if (active) {
widget->SetCapture(nullptr);
activation_observed_ = true;
}
}
bool activation_observed() const { return activation_observed_; }
private:
bool activation_observed_ = false;
};
} // namespace
// Test that setting capture on widget activation of a non-toplevel widget
// (e.g. a bubble on Linux) succeeds.
TEST_F(WidgetCaptureTest, SetCaptureToNonToplevel) {
UniqueWidgetPtr toplevel = std::make_unique<Widget>();
Widget::InitParams toplevel_params =
CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
toplevel->Init(std::move(toplevel_params));
toplevel->Show();
UniqueWidgetPtr child = std::make_unique<Widget>();
Widget::InitParams child_params =
CreateParams(Widget::InitParams::TYPE_WINDOW_FRAMELESS);
child_params.parent = toplevel->GetNativeView();
child_params.context = toplevel->GetNativeWindow();
child->Init(std::move(child_params));
CaptureOnActivationObserver observer;
child->AddObserver(&observer);
child->Show();
#if BUILDFLAG(IS_MAC)
// On Mac, activation is asynchronous. A single trip to the runloop should be
// sufficient. On Aura platforms, note that since the child widget isn't top-
// level, the aura window manager gets asked whether the widget is active, not
// the OS.
base::RunLoop().RunUntilIdle();
#endif
EXPECT_TRUE(observer.activation_observed());
EXPECT_TRUE(child->HasCapture());
child->RemoveObserver(&observer);
}
#if BUILDFLAG(IS_WIN)
namespace {
// Used to verify OnMouseEvent() has been invoked.
class MouseEventTrackingWidget : public Widget {
public:
MouseEventTrackingWidget() = default;
MouseEventTrackingWidget(const MouseEventTrackingWidget&) = delete;
MouseEventTrackingWidget& operator=(const MouseEventTrackingWidget&) = delete;
~MouseEventTrackingWidget() override = default;
bool GetAndClearGotMouseEvent() {
bool value = got_mouse_event_;
got_mouse_event_ = false;
return value;
}
// Widget:
void OnMouseEvent(ui::MouseEvent* event) override {
got_mouse_event_ = true;
Widget::OnMouseEvent(event);
}
private:
bool got_mouse_event_ = false;
};
} // namespace
// Verifies if a mouse event is received on a widget that doesn't have capture
// on Windows that it is correctly processed by the widget that doesn't have
// capture. This behavior is not desired on OSes other than Windows.
TEST_F(WidgetCaptureTest, MouseEventDispatchedToRightWindow) {
UniqueWidgetPtrT widget1 = std::make_unique<MouseEventTrackingWidget>();
Widget::InitParams params1 =
CreateParams(views::Widget::InitParams::TYPE_WINDOW);
params1.native_widget = new DesktopNativeWidgetAura(widget1.get());
widget1->Init(std::move(params1));
widget1->Show();
UniqueWidgetPtrT widget2 = std::make_unique<MouseEventTrackingWidget>();
Widget::InitParams params2 =
CreateParams(views::Widget::InitParams::TYPE_WINDOW);
params2.native_widget = new DesktopNativeWidgetAura(widget2.get());
widget2->Init(std::move(params2));
widget2->Show();
// Set capture to widget2 and verity it gets it.
widget2->SetCapture(widget2->GetRootView());
EXPECT_FALSE(widget1->HasCapture());
EXPECT_TRUE(widget2->HasCapture());
widget1->GetAndClearGotMouseEvent();
widget2->GetAndClearGotMouseEvent();
// Send a mouse event to the RootWindow associated with |widget1|. Even though
// |widget2| has capture, |widget1| should still get the event.
ui::MouseEvent mouse_event(ui::ET_MOUSE_EXITED, gfx::Point(), gfx::Point(),
ui::EventTimeForNow(), ui::EF_NONE, ui::EF_NONE);
ui::EventDispatchDetails details =
widget1->GetNativeWindow()->GetHost()->GetEventSink()->OnEventFromSource(
&mouse_event);
ASSERT_FALSE(details.dispatcher_destroyed);
EXPECT_TRUE(widget1->GetAndClearGotMouseEvent());
EXPECT_FALSE(widget2->GetAndClearGotMouseEvent());
}
#endif // BUILDFLAG(IS_WIN)
class WidgetInputMethodInteractiveTest : public DesktopWidgetTestInteractive {
public:
WidgetInputMethodInteractiveTest() = default;
WidgetInputMethodInteractiveTest(const WidgetInputMethodInteractiveTest&) =
delete;
WidgetInputMethodInteractiveTest& operator=(
const WidgetInputMethodInteractiveTest&) = delete;
// testing::Test:
void SetUp() override {
DesktopWidgetTestInteractive::SetUp();
#if BUILDFLAG(IS_WIN)
// On Windows, Widget::Deactivate() works by activating the next topmost
// window on the z-order stack. This only works if there is at least one
// other window, so make sure that is the case.
deactivate_widget_ = CreateTopLevelNativeWidget();
deactivate_widget_->Show();
#endif
}
void TearDown() override {
if (deactivate_widget_)
deactivate_widget_->CloseNow();
DesktopWidgetTestInteractive::TearDown();
}
private:
raw_ptr<Widget> deactivate_widget_ = nullptr;
};
#if BUILDFLAG(IS_MAC)
#define MAYBE_Activation DISABLED_Activation
#else
#define MAYBE_Activation Activation
#endif
// Test input method focus changes affected by top window activaction.
TEST_F(WidgetInputMethodInteractiveTest, MAYBE_Activation) {
WidgetAutoclosePtr widget(CreateTopLevelNativeWidget());
std::unique_ptr<Textfield> textfield = CreateTextfield();
auto* const textfield_ptr = textfield.get();
widget->GetRootView()->AddChildView(std::move(textfield));
textfield_ptr->RequestFocus();
ShowSync(widget.get());
EXPECT_EQ(ui::TEXT_INPUT_TYPE_TEXT,
widget->GetInputMethod()->GetTextInputType());
DeactivateSync(widget.get());
EXPECT_EQ(ui::TEXT_INPUT_TYPE_NONE,
widget->GetInputMethod()->GetTextInputType());
}
// Test input method focus changes affected by focus changes within 1 window.
TEST_F(WidgetInputMethodInteractiveTest, OneWindow) {
WidgetAutoclosePtr widget(CreateTopLevelNativeWidget());
std::unique_ptr<Textfield> textfield1 = CreateTextfield();
auto* const textfield1_ptr = textfield1.get();
std::unique_ptr<Textfield> textfield2 = CreateTextfield();
auto* const textfield2_ptr = textfield2.get();
textfield2_ptr->SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD);
widget->GetRootView()->AddChildView(std::move(textfield1));
widget->GetRootView()->AddChildView(std::move(textfield2));
ShowSync(widget.get());
textfield1_ptr->RequestFocus();
EXPECT_EQ(ui::TEXT_INPUT_TYPE_TEXT,
widget->GetInputMethod()->GetTextInputType());
textfield2_ptr->RequestFocus();
EXPECT_EQ(ui::TEXT_INPUT_TYPE_PASSWORD,
widget->GetInputMethod()->GetTextInputType());
// Widget::Deactivate() doesn't work for CrOS, because it uses NWA instead of
// DNWA (which just activates the last active window) and involves the
// AuraTestHelper which sets the input method as DummyInputMethod.
#if BUILDFLAG(ENABLE_DESKTOP_AURA) || BUILDFLAG(IS_MAC)
DeactivateSync(widget.get());
EXPECT_EQ(ui::TEXT_INPUT_TYPE_NONE,
widget->GetInputMethod()->GetTextInputType());
ActivateSync(widget.get());
EXPECT_EQ(ui::TEXT_INPUT_TYPE_PASSWORD,
widget->GetInputMethod()->GetTextInputType());
DeactivateSync(widget.get());
textfield1_ptr->RequestFocus();
ActivateSync(widget.get());
EXPECT_TRUE(widget->IsActive());
EXPECT_EQ(ui::TEXT_INPUT_TYPE_TEXT,
widget->GetInputMethod()->GetTextInputType());
#endif
}
// Test input method focus changes affected by focus changes cross 2 windows
// which shares the same top window.
TEST_F(WidgetInputMethodInteractiveTest, TwoWindows) {
WidgetAutoclosePtr parent(CreateTopLevelNativeWidget());
parent->SetBounds(gfx::Rect(100, 100, 100, 100));
Widget* child = CreateChildNativeWidgetWithParent(parent.get());
child->SetBounds(gfx::Rect(0, 0, 50, 50));
child->Show();
std::unique_ptr<Textfield> textfield_parent = CreateTextfield();
auto* const textfield_parent_ptr = textfield_parent.get();
std::unique_ptr<Textfield> textfield_child = CreateTextfield();
auto* const textfield_child_ptr = textfield_child.get();
textfield_parent->SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD);
parent->GetRootView()->AddChildView(std::move(textfield_parent));
child->GetRootView()->AddChildView(std::move(textfield_child));
ShowSync(parent.get());
EXPECT_EQ(parent->GetInputMethod(), child->GetInputMethod());
textfield_parent_ptr->RequestFocus();
EXPECT_EQ(ui::TEXT_INPUT_TYPE_PASSWORD,
parent->GetInputMethod()->GetTextInputType());
textfield_child_ptr->RequestFocus();
EXPECT_EQ(ui::TEXT_INPUT_TYPE_TEXT,
parent->GetInputMethod()->GetTextInputType());
// Widget::Deactivate() doesn't work for CrOS, because it uses NWA instead of
// DNWA (which just activates the last active window) and involves the
// AuraTestHelper which sets the input method as DummyInputMethod.
#if BUILDFLAG(ENABLE_DESKTOP_AURA) || BUILDFLAG(IS_MAC)
DeactivateSync(parent.get());
EXPECT_EQ(ui::TEXT_INPUT_TYPE_NONE,
parent->GetInputMethod()->GetTextInputType());
ActivateSync(parent.get());
EXPECT_EQ(ui::TEXT_INPUT_TYPE_TEXT,
parent->GetInputMethod()->GetTextInputType());
textfield_parent_ptr->RequestFocus();
DeactivateSync(parent.get());
EXPECT_EQ(ui::TEXT_INPUT_TYPE_NONE,
parent->GetInputMethod()->GetTextInputType());
ActivateSync(parent.get());
EXPECT_EQ(ui::TEXT_INPUT_TYPE_PASSWORD,
parent->GetInputMethod()->GetTextInputType());
#endif
}
// Test input method focus changes affected by textfield's state changes.
TEST_F(WidgetInputMethodInteractiveTest, TextField) {
WidgetAutoclosePtr widget(CreateTopLevelNativeWidget());
std::unique_ptr<Textfield> textfield = CreateTextfield();
auto* const textfield_ptr = textfield.get();
widget->GetRootView()->AddChildView(std::move(textfield));
ShowSync(widget.get());
EXPECT_EQ(ui::TEXT_INPUT_TYPE_NONE,
widget->GetInputMethod()->GetTextInputType());
textfield_ptr->SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD);
EXPECT_EQ(ui::TEXT_INPUT_TYPE_NONE,
widget->GetInputMethod()->GetTextInputType());
textfield_ptr->RequestFocus();
EXPECT_EQ(ui::TEXT_INPUT_TYPE_PASSWORD,
widget->GetInputMethod()->GetTextInputType());
textfield_ptr->SetTextInputType(ui::TEXT_INPUT_TYPE_TEXT);
EXPECT_EQ(ui::TEXT_INPUT_TYPE_TEXT,
widget->GetInputMethod()->GetTextInputType());
textfield_ptr->SetReadOnly(true);
EXPECT_EQ(ui::TEXT_INPUT_TYPE_NONE,
widget->GetInputMethod()->GetTextInputType());
}
// Test input method should not work for accelerator.
TEST_F(WidgetInputMethodInteractiveTest, AcceleratorInTextfield) {
WidgetAutoclosePtr widget(CreateTopLevelNativeWidget());
std::unique_ptr<Textfield> textfield = CreateTextfield();
auto* const textfield_ptr = textfield.get();
widget->GetRootView()->AddChildView(std::move(textfield));
ShowSync(widget.get());
textfield_ptr->SetTextInputType(ui::TEXT_INPUT_TYPE_TEXT);
textfield_ptr->RequestFocus();
ui::KeyEvent key_event(ui::ET_KEY_PRESSED, ui::VKEY_F, ui::EF_ALT_DOWN);
ui::Accelerator accelerator(key_event);
widget->GetFocusManager()->RegisterAccelerator(
accelerator, ui::AcceleratorManager::kNormalPriority, textfield_ptr);
widget->OnKeyEvent(&key_event);
EXPECT_TRUE(key_event.stopped_propagation());
widget->GetFocusManager()->UnregisterAccelerators(textfield_ptr);
ui::KeyEvent key_event2(key_event);
widget->OnKeyEvent(&key_event2);
EXPECT_FALSE(key_event2.stopped_propagation());
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/widget_interactive_uitest.cc | C++ | unknown | 81,846 |
// Copyright 2023 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/widget/widget_interactive_uitest_utils.h"
#include <utility>
#include "base/functional/callback_forward.h"
#include "base/run_loop.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
namespace views::test {
PropertyWaiter::PropertyWaiter(base::RepeatingCallback<bool(void)> callback,
bool expected_value)
: callback_(std::move(callback)), expected_value_(expected_value) {}
PropertyWaiter::~PropertyWaiter() = default;
bool PropertyWaiter::Wait() {
if (callback_.Run() == expected_value_) {
success_ = true;
return success_;
}
start_time_ = base::TimeTicks::Now();
timer_.Start(FROM_HERE, base::TimeDelta(), this, &PropertyWaiter::Check);
run_loop_.Run();
return success_;
}
void PropertyWaiter::Check() {
DCHECK(!success_);
success_ = callback_.Run() == expected_value_;
if (success_ || base::TimeTicks::Now() - start_time_ > kTimeout) {
timer_.Stop();
run_loop_.Quit();
}
}
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/widget_interactive_uitest_utils.cc | C++ | unknown | 1,154 |
// Copyright 2023 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_WIDGET_WIDGET_INTERACTIVE_UITEST_UTILS_H_
#define UI_VIEWS_WIDGET_WIDGET_INTERACTIVE_UITEST_UTILS_H_
#include "base/functional/callback_forward.h"
#include "base/run_loop.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
namespace views::test {
// Wait until `callback` returns `expected_value`, but no longer than 1 second.
//
// Example Usage :
// WidgetAutoclosePtr widget(CreateTopLevelNativeWidget());
// PropertyWaiter minimize_waiter(
// base::BindRepeating(
// &Widget::IsMinimized, base::Unretained(widget.get())), true);
// widget->Minimize();
// EXPECT_TRUE(minimize_waiter.Wait());
class PropertyWaiter {
public:
PropertyWaiter(base::RepeatingCallback<bool(void)> callback,
bool expected_value);
~PropertyWaiter();
bool Wait();
private:
void Check();
const base::TimeDelta kTimeout = base::Seconds(1);
base::RepeatingCallback<bool(void)> callback_;
const bool expected_value_;
bool success_ = false;
base::TimeTicks start_time_;
base::RunLoop run_loop_;
base::RepeatingTimer timer_;
};
} // namespace views::test
#endif // UI_VIEWS_WIDGET_WIDGET_INTERACTIVE_UITEST_UTILS_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/widget_interactive_uitest_utils.h | C++ | unknown | 1,327 |
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_VIEWS_WIDGET_WIDGET_OBSERVER_H_
#define UI_VIEWS_WIDGET_WIDGET_OBSERVER_H_
#include "base/observer_list_types.h"
#include "ui/views/views_export.h"
namespace gfx {
class Rect;
}
namespace views {
class Widget;
// Observers can listen to various events on the Widgets.
class VIEWS_EXPORT WidgetObserver : public base::CheckedObserver {
public:
// The closing notification is sent immediately in response to (i.e. in the
// same call stack as) a request to close the Widget (via Close() or
// CloseNow()).
// TODO(crbug.com/1240365): Remove this, this API is too scary. Users of this
// API can expect it to always be called, but it's only called on the same
// stack as a close request. If the Widget closes due to OS native-widget
// destruction this is never called. Replace existing uses with
// OnWidgetDestroying() or by using ViewTrackers to track View lifetimes.
virtual void OnWidgetClosing(Widget* widget) {}
// Invoked after notification is received from the event loop that the native
// widget has been created.
virtual void OnWidgetCreated(Widget* widget) {}
// The destroying event occurs immediately before the widget is destroyed.
// This typically occurs asynchronously with respect the the close request, as
// a result of a later invocation from the event loop.
virtual void OnWidgetDestroying(Widget* widget) {}
// Invoked after notification is received from the event loop that the native
// widget has been destroyed.
virtual void OnWidgetDestroyed(Widget* widget) {}
// Called before RunShellDrag() is called and after it returns.
virtual void OnWidgetDragWillStart(Widget* widget) {}
virtual void OnWidgetDragComplete(Widget* widget) {}
virtual void OnWidgetVisibilityChanged(Widget* widget, bool visible) {}
virtual void OnWidgetActivationChanged(Widget* widget, bool active) {}
virtual void OnWidgetBoundsChanged(Widget* widget,
const gfx::Rect& new_bounds) {}
virtual void OnWidgetThemeChanged(Widget* widget) {}
protected:
~WidgetObserver() override = default;
};
} // namespace views
#endif // UI_VIEWS_WIDGET_WIDGET_OBSERVER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/widget_observer.h | C++ | unknown | 2,323 |
// 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_WIDGET_WIDGET_REMOVALS_OBSERVER_H_
#define UI_VIEWS_WIDGET_WIDGET_REMOVALS_OBSERVER_H_
#include "ui/views/views_export.h"
namespace views {
class Widget;
class View;
// |WidgetRemovalsObserver| complements |WidgetObserver| with additional
// notifications. These include events occurring during tear down like view
// removal. For this reason, it is recommended that subclasses not also inherit
// from |View|.
class VIEWS_EXPORT WidgetRemovalsObserver {
public:
// Called immediately before a descendant view of |widget| is removed
// from this widget. Won't be called if the view is moved within the
// same widget, but will be called if it's moved to a different widget.
// Only called on the root of a view tree; it implies that all of the
// descendants of |view| will be removed.
virtual void OnWillRemoveView(Widget* widget, View* view) {}
protected:
virtual ~WidgetRemovalsObserver() = default;
};
} // namespace views
#endif // UI_VIEWS_WIDGET_WIDGET_REMOVALS_OBSERVER_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/widget_removals_observer.h | C++ | unknown | 1,167 |
// 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 <memory>
#include <set>
#include <utility>
#include <vector>
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/memory/raw_ptr.h"
#include "base/ranges/algorithm.h"
#include "base/run_loop.h"
#include "base/test/gtest_util.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/base/dragdrop/mojom/drag_drop_types.mojom.h"
#include "ui/base/hit_test.h"
#include "ui/color/color_id.h"
#include "ui/color/color_provider.h"
#include "ui/color/color_provider_manager.h"
#include "ui/color/color_recipe.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_animation_observer.h"
#include "ui/compositor/scoped_animation_duration_scale_mode.h"
#include "ui/compositor/scoped_layer_animation_settings.h"
#include "ui/compositor/test/draw_waiter_for_test.h"
#include "ui/events/event_observer.h"
#include "ui/events/event_utils.h"
#include "ui/events/test/event_generator.h"
#include "ui/gfx/color_palette.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/native_theme/native_theme.h"
#include "ui/native_theme/test_native_theme.h"
#include "ui/views/bubble/bubble_dialog_delegate_view.h"
#include "ui/views/buildflags.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/event_monitor.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/style/platform_style.h"
#include "ui/views/test/mock_drag_controller.h"
#include "ui/views/test/mock_native_widget.h"
#include "ui/views/test/native_widget_factory.h"
#include "ui/views/test/test_views.h"
#include "ui/views/test/test_widget_observer.h"
#include "ui/views/test/views_test_utils.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/view_test_api.h"
#include "ui/views/views_test_suite.h"
#include "ui/views/widget/native_widget_delegate.h"
#include "ui/views/widget/native_widget_private.h"
#include "ui/views/widget/root_view.h"
#include "ui/views/widget/unique_widget_ptr.h"
#include "ui/views/widget/widget_delegate.h"
#include "ui/views/widget/widget_deletion_observer.h"
#include "ui/views/widget/widget_interactive_uitest_utils.h"
#include "ui/views/widget/widget_removals_observer.h"
#include "ui/views/widget/widget_utils.h"
#include "ui/views/window/dialog_delegate.h"
#include "ui/views/window/native_frame_view.h"
#if defined(USE_AURA)
#include "ui/aura/window.h"
#include "ui/aura/window_tree_host.h"
#include "ui/base/view_prop.h"
#include "ui/views/test/test_platform_native_widget.h"
#include "ui/views/widget/native_widget_aura.h"
#include "ui/wm/core/base_focus_rules.h"
#include "ui/wm/core/focus_controller.h"
#include "ui/wm/core/shadow_controller.h"
#include "ui/wm/core/shadow_controller_delegate.h"
#endif
#if BUILDFLAG(IS_WIN)
#include "ui/base/win/window_event_target.h"
#include "ui/views/win/hwnd_util.h"
#endif
#if BUILDFLAG(IS_MAC)
#include "base/mac/mac_util.h"
#endif
#if BUILDFLAG(ENABLE_DESKTOP_AURA)
#include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h"
#endif
#if BUILDFLAG(IS_OZONE)
#include "ui/ozone/public/ozone_platform.h"
#include "ui/ozone/public/platform_gl_egl_utility.h"
#endif
namespace views::test {
namespace {
// TODO(tdanderson): This utility function is used in different unittest
// files. Move to a common location to avoid
// repeated code.
gfx::Point ConvertPointFromWidgetToView(View* view, const gfx::Point& p) {
gfx::Point tmp(p);
View::ConvertPointToTarget(view->GetWidget()->GetRootView(), view, &tmp);
return tmp;
}
std::unique_ptr<ui::test::EventGenerator> CreateEventGenerator(
gfx::NativeWindow root_window,
gfx::NativeWindow target_window) {
auto generator =
std::make_unique<ui::test::EventGenerator>(root_window, target_window);
return generator;
}
class TestBubbleDialogDelegateView : public BubbleDialogDelegateView {
public:
explicit TestBubbleDialogDelegateView(View* anchor)
: BubbleDialogDelegateView(anchor, BubbleBorder::NONE) {}
~TestBubbleDialogDelegateView() override = default;
bool ShouldShowCloseButton() const override {
reset_controls_called_ = true;
return true;
}
mutable bool reset_controls_called_ = false;
};
// Convenience to make constructing a GestureEvent simpler.
ui::GestureEvent CreateTestGestureEvent(ui::EventType type, int x, int y) {
return ui::GestureEvent(x, y, 0, base::TimeTicks(),
ui::GestureEventDetails(type));
}
ui::GestureEvent CreateTestGestureEvent(const ui::GestureEventDetails& details,
int x,
int y) {
return ui::GestureEvent(x, y, 0, base::TimeTicks(), details);
}
class TestWidgetRemovalsObserver : public WidgetRemovalsObserver {
public:
TestWidgetRemovalsObserver() = default;
TestWidgetRemovalsObserver(const TestWidgetRemovalsObserver&) = delete;
TestWidgetRemovalsObserver& operator=(const TestWidgetRemovalsObserver&) =
delete;
~TestWidgetRemovalsObserver() override = default;
void OnWillRemoveView(Widget* widget, View* view) override {
removed_views_.insert(view);
}
bool DidRemoveView(View* view) {
return removed_views_.find(view) != removed_views_.end();
}
private:
std::set<View*> removed_views_;
};
} // namespace
// A view that keeps track of the events it receives, and consumes all scroll
// gesture events and ui::ET_SCROLL events.
class ScrollableEventCountView : public EventCountView {
public:
ScrollableEventCountView() = default;
ScrollableEventCountView(const ScrollableEventCountView&) = delete;
ScrollableEventCountView& operator=(const ScrollableEventCountView&) = delete;
~ScrollableEventCountView() override = default;
private:
// Overridden from ui::EventHandler:
void OnGestureEvent(ui::GestureEvent* event) override {
EventCountView::OnGestureEvent(event);
switch (event->type()) {
case ui::ET_GESTURE_SCROLL_BEGIN:
case ui::ET_GESTURE_SCROLL_UPDATE:
case ui::ET_GESTURE_SCROLL_END:
case ui::ET_SCROLL_FLING_START:
event->SetHandled();
break;
default:
break;
}
}
void OnScrollEvent(ui::ScrollEvent* event) override {
EventCountView::OnScrollEvent(event);
if (event->type() == ui::ET_SCROLL)
event->SetHandled();
}
};
// A view that implements GetMinimumSize.
class MinimumSizeFrameView : public NativeFrameView {
public:
explicit MinimumSizeFrameView(Widget* frame) : NativeFrameView(frame) {}
MinimumSizeFrameView(const MinimumSizeFrameView&) = delete;
MinimumSizeFrameView& operator=(const MinimumSizeFrameView&) = delete;
~MinimumSizeFrameView() override = default;
private:
// Overridden from View:
gfx::Size GetMinimumSize() const override { return gfx::Size(300, 400); }
};
// An event handler that simply keeps a count of the different types of events
// it receives.
class EventCountHandler : public ui::EventHandler {
public:
EventCountHandler() = default;
EventCountHandler(const EventCountHandler&) = delete;
EventCountHandler& operator=(const EventCountHandler&) = delete;
~EventCountHandler() override = default;
int GetEventCount(ui::EventType type) { return event_count_[type]; }
void ResetCounts() { event_count_.clear(); }
protected:
// Overridden from ui::EventHandler:
void OnEvent(ui::Event* event) override {
RecordEvent(*event);
ui::EventHandler::OnEvent(event);
}
private:
void RecordEvent(const ui::Event& event) { ++event_count_[event.type()]; }
std::map<ui::EventType, int> event_count_;
};
TEST_F(WidgetTest, WidgetInitParams) {
// Widgets are not transparent by default.
Widget::InitParams init1;
EXPECT_EQ(Widget::InitParams::WindowOpacity::kInferred, init1.opacity);
}
// Tests that the internal name is propagated through widget initialization to
// the native widget and back.
class WidgetWithCustomParamsTest : public WidgetTest {
public:
using InitFunction = base::RepeatingCallback<void(Widget::InitParams*)>;
void SetInitFunction(const InitFunction& init) { init_ = std::move(init); }
Widget::InitParams CreateParams(Widget::InitParams::Type type) override {
Widget::InitParams params = WidgetTest::CreateParams(type);
DCHECK(init_) << "If you don't need an init function, use WidgetTest";
init_.Run(¶ms);
return params;
}
private:
InitFunction init_;
};
TEST_F(WidgetWithCustomParamsTest, NamePropagatedFromParams) {
SetInitFunction(base::BindLambdaForTesting(
[](Widget::InitParams* params) { params->name = "MyWidget"; }));
std::unique_ptr<Widget> widget = CreateTestWidget();
EXPECT_EQ("MyWidget", widget->native_widget_private()->GetName());
EXPECT_EQ("MyWidget", widget->GetName());
}
TEST_F(WidgetWithCustomParamsTest, NamePropagatedFromDelegate) {
WidgetDelegate delegate;
delegate.set_internal_name("Foobar");
SetInitFunction(base::BindLambdaForTesting(
[&](Widget::InitParams* params) { params->delegate = &delegate; }));
std::unique_ptr<Widget> widget = CreateTestWidget();
EXPECT_EQ(delegate.internal_name(),
widget->native_widget_private()->GetName());
EXPECT_EQ(delegate.internal_name(), widget->GetName());
}
TEST_F(WidgetWithCustomParamsTest, NamePropagatedFromContentsViewClassName) {
class ViewWithClassName : public View {
public:
const char* GetClassName() const override { return "ViewWithClassName"; }
};
WidgetDelegate delegate;
auto view = std::make_unique<ViewWithClassName>();
auto* contents = delegate.SetContentsView(std::move(view));
SetInitFunction(base::BindLambdaForTesting(
[&](Widget::InitParams* params) { params->delegate = &delegate; }));
std::unique_ptr<Widget> widget = CreateTestWidget();
EXPECT_EQ(contents->GetClassName(),
widget->native_widget_private()->GetName());
EXPECT_EQ(contents->GetClassName(), widget->GetName());
}
#if BUILDFLAG(IS_CHROMEOS_ASH)
TEST_F(WidgetWithCustomParamsTest, SkottieColorsTest) {
struct SkottieColors {
bool operator==(const SkottieColors& other) const {
return color1 == other.color1 && color1_shade1 == other.color1_shade1 &&
color1_shade2 == other.color1_shade2 && color2 == other.color2 &&
color3 == other.color3 && color4 == other.color4 &&
color5 == other.color5 && color6 == other.color6 &&
base_color == other.base_color &&
secondary_color == other.secondary_color;
}
bool operator!=(const SkottieColors& other) const {
return !operator==(other);
}
SkColor color1, color1_shade1, color1_shade2, color2, color3, color4,
color5, color6, base_color, secondary_color;
};
class ViewObservingSkottieColors : public View {
public:
void OnThemeChanged() override {
View::OnThemeChanged();
const ui::ColorProvider* provider = GetColorProvider();
history.push_back({provider->GetColor(ui::kColorNativeColor1),
provider->GetColor(ui::kColorNativeColor1Shade1),
provider->GetColor(ui::kColorNativeColor1Shade2),
provider->GetColor(ui::kColorNativeColor2),
provider->GetColor(ui::kColorNativeColor3),
provider->GetColor(ui::kColorNativeColor4),
provider->GetColor(ui::kColorNativeColor5),
provider->GetColor(ui::kColorNativeColor6),
provider->GetColor(ui::kColorNativeBaseColor),
provider->GetColor(ui::kColorNativeSecondaryColor)});
}
std::vector<SkottieColors> history;
};
// |widget1| has low background elevation and is created in light mode.
ui::NativeTheme* theme = ui::NativeTheme::GetInstanceForNativeUi();
theme->set_use_dark_colors(false);
WidgetDelegate delegate1;
ViewObservingSkottieColors* contents1 =
delegate1.SetContentsView(std::make_unique<ViewObservingSkottieColors>());
SetInitFunction(base::BindLambdaForTesting([&](Widget::InitParams* params) {
params->delegate = &delegate1;
params->background_elevation =
ui::ColorProviderManager::ElevationMode::kLow;
}));
std::unique_ptr<Widget> widget1 = CreateTestWidget();
ASSERT_EQ(1u, contents1->history.size());
// |widget2| has high background elevation and is created in light mode.
WidgetDelegate delegate2;
ViewObservingSkottieColors* contents2 =
delegate2.SetContentsView(std::make_unique<ViewObservingSkottieColors>());
SetInitFunction(base::BindLambdaForTesting([&](Widget::InitParams* params) {
params->delegate = &delegate2;
params->background_elevation =
ui::ColorProviderManager::ElevationMode::kHigh;
}));
std::unique_ptr<Widget> widget2 = CreateTestWidget();
ASSERT_EQ(1u, contents2->history.size());
// Check that |contents1| and |contents2| have the same Skottie colors.
// Background elevation should not affect Skottie colors in light mode.
EXPECT_EQ(contents1->history[0u], contents2->history[0u]);
// Switch to dark mode.
theme->set_use_dark_colors(true);
theme->NotifyOnNativeThemeUpdated();
// Check that |contents1| and |contents2| were notified of the theme update.
ASSERT_EQ(2u, contents1->history.size());
ASSERT_EQ(2u, contents2->history.size());
// Check that the Skottie colors were actually changed with the notification.
EXPECT_NE(contents1->history[0u], contents1->history[1u]);
EXPECT_NE(contents2->history[0u], contents2->history[1u]);
// Check that |contents1| and |contents2| have different Skottie colors.
// Background elevation should affect Skottie colors in dark mode.
EXPECT_NE(contents1->history[1u], contents2->history[1u]);
// |widget3| has low background elevation and is created in dark mode.
WidgetDelegate delegate3;
ViewObservingSkottieColors* contents3 =
delegate3.SetContentsView(std::make_unique<ViewObservingSkottieColors>());
SetInitFunction(base::BindLambdaForTesting([&](Widget::InitParams* params) {
params->delegate = &delegate3;
params->background_elevation =
ui::ColorProviderManager::ElevationMode::kLow;
}));
std::unique_ptr<Widget> widget3 = CreateTestWidget();
ASSERT_EQ(1u, contents3->history.size());
// Check that |contents3| has the same Skottie colors as |contents1|. It
// should not matter whether a widget was created before or after dark mode
// was toggled.
EXPECT_EQ(contents1->history[1u], contents3->history[0u]);
// |widget4| has high background elevation and is created in dark mode.
WidgetDelegate delegate4;
ViewObservingSkottieColors* contents4 =
delegate4.SetContentsView(std::make_unique<ViewObservingSkottieColors>());
SetInitFunction(base::BindLambdaForTesting([&](Widget::InitParams* params) {
params->delegate = &delegate4;
params->background_elevation =
ui::ColorProviderManager::ElevationMode::kHigh;
}));
std::unique_ptr<Widget> widget4 = CreateTestWidget();
ASSERT_EQ(1u, contents4->history.size());
// Check that |contents4| has the same Skottie colors as |contents2|. It
// should not matter whether a widget was created before or after dark mode
// was toggled.
EXPECT_EQ(contents2->history[1u], contents4->history[0u]);
// Switch to light mode.
theme->set_use_dark_colors(false);
theme->NotifyOnNativeThemeUpdated();
// Check that all four contents views were notified of the theme update.
ASSERT_EQ(3u, contents1->history.size());
ASSERT_EQ(3u, contents2->history.size());
ASSERT_EQ(2u, contents3->history.size());
ASSERT_EQ(2u, contents4->history.size());
// Check that |contents1| and |contents2| are back to the Skottie colors they
// started with. It should not matter if dark mode is toggled on and back off.
EXPECT_EQ(contents1->history[0u], contents1->history[2u]);
EXPECT_EQ(contents2->history[0u], contents2->history[2u]);
// Check that |contents3| and |contents4| still have the same Skottie colors
// as |contents1| and |contents2|, respectively. It should not matter when a
// widget was created.
EXPECT_EQ(contents1->history[2u], contents3->history[1u]);
EXPECT_EQ(contents2->history[2u], contents4->history[1u]);
}
#endif
class WidgetColorModeTest : public WidgetTest {
public:
static constexpr SkColor kLightColor = SK_ColorWHITE;
static constexpr SkColor kDarkColor = SK_ColorBLACK;
WidgetColorModeTest() = default;
~WidgetColorModeTest() override = default;
void SetUp() override {
WidgetTest::SetUp();
// Setup color provider for the ui::kColorSysPrimary color.
ui::ColorProviderManager& manager =
ui::ColorProviderManager::GetForTesting();
manager.AppendColorProviderInitializer(base::BindRepeating(&AddColor));
}
void TearDown() override {
ui::ColorProviderManager::ResetForTesting();
WidgetTest::TearDown();
}
private:
static void AddColor(ui::ColorProvider* provider,
const ui::ColorProviderManager::Key& key) {
ui::ColorMixer& mixer = provider->AddMixer();
mixer[ui::kColorSysPrimary] = {
key.color_mode == ui::ColorProviderManager::ColorMode::kDark
? kDarkColor
: kLightColor};
}
};
TEST_F(WidgetColorModeTest, ColorModeOverride_NoOverride) {
ui::TestNativeTheme test_theme;
WidgetAutoclosePtr widget(CreateTopLevelPlatformWidget());
test_theme.SetDarkMode(true);
widget->SetNativeThemeForTest(&test_theme);
widget->SetColorModeOverride({});
// Verify that we resolve the dark color when we don't override color mode.
EXPECT_EQ(kDarkColor,
widget->GetColorProvider()->GetColor(ui::kColorSysPrimary));
}
TEST_F(WidgetColorModeTest, ColorModeOverride_DarkOverride) {
ui::TestNativeTheme test_theme;
WidgetAutoclosePtr widget(CreateTopLevelPlatformWidget());
test_theme.SetDarkMode(false);
widget->SetNativeThemeForTest(&test_theme);
widget->SetColorModeOverride(ui::ColorProviderManager::ColorMode::kDark);
// Verify that we resolve the light color even though the theme is dark.
EXPECT_EQ(kDarkColor,
widget->GetColorProvider()->GetColor(ui::kColorSysPrimary));
}
TEST_F(WidgetColorModeTest, ColorModeOverride_LightOverride) {
ui::TestNativeTheme test_theme;
WidgetAutoclosePtr widget(CreateTopLevelPlatformWidget());
test_theme.SetDarkMode(true);
widget->SetNativeThemeForTest(&test_theme);
widget->SetColorModeOverride(ui::ColorProviderManager::ColorMode::kLight);
// Verify that we resolve the light color even though the theme is dark.
EXPECT_EQ(kLightColor,
widget->GetColorProvider()->GetColor(ui::kColorSysPrimary));
}
TEST_F(WidgetTest, NativeWindowProperty) {
const char* key = "foo";
int value = 3;
WidgetAutoclosePtr widget(CreateTopLevelPlatformWidget());
EXPECT_EQ(nullptr, widget->GetNativeWindowProperty(key));
widget->SetNativeWindowProperty(key, &value);
EXPECT_EQ(&value, widget->GetNativeWindowProperty(key));
widget->SetNativeWindowProperty(key, nullptr);
EXPECT_EQ(nullptr, widget->GetNativeWindowProperty(key));
}
TEST_F(WidgetTest, GetParent) {
// Create a hierarchy of native widgets.
WidgetAutoclosePtr toplevel(CreateTopLevelPlatformWidget());
Widget* child = CreateChildPlatformWidget(toplevel->GetNativeView());
Widget* grandchild = CreateChildPlatformWidget(child->GetNativeView());
EXPECT_EQ(nullptr, toplevel->parent());
EXPECT_EQ(child, grandchild->parent());
EXPECT_EQ(toplevel.get(), child->parent());
// children should be automatically destroyed with |toplevel|.
}
// Verify that there is no change in focus if |enable_arrow_key_traversal| is
// false (the default).
TEST_F(WidgetTest, ArrowKeyFocusTraversalOffByDefault) {
WidgetAutoclosePtr toplevel(CreateTopLevelPlatformWidget());
// Establish default value.
DCHECK(!toplevel->widget_delegate()->enable_arrow_key_traversal());
View* container = toplevel->client_view();
container->SetLayoutManager(std::make_unique<FillLayout>());
auto* const button1 =
container->AddChildView(std::make_unique<LabelButton>());
auto* const button2 =
container->AddChildView(std::make_unique<LabelButton>());
toplevel->Show();
button1->RequestFocus();
ui::KeyEvent right_arrow(ui::ET_KEY_PRESSED, ui::VKEY_RIGHT, ui::EF_NONE);
toplevel->OnKeyEvent(&right_arrow);
EXPECT_TRUE(button1->HasFocus());
EXPECT_FALSE(button2->HasFocus());
ui::KeyEvent left_arrow(ui::ET_KEY_PRESSED, ui::VKEY_LEFT, ui::EF_NONE);
toplevel->OnKeyEvent(&left_arrow);
EXPECT_TRUE(button1->HasFocus());
EXPECT_FALSE(button2->HasFocus());
ui::KeyEvent up_arrow(ui::ET_KEY_PRESSED, ui::VKEY_UP, ui::EF_NONE);
toplevel->OnKeyEvent(&up_arrow);
EXPECT_TRUE(button1->HasFocus());
EXPECT_FALSE(button2->HasFocus());
ui::KeyEvent down_arrow(ui::ET_KEY_PRESSED, ui::VKEY_DOWN, ui::EF_NONE);
toplevel->OnKeyEvent(&down_arrow);
EXPECT_TRUE(button1->HasFocus());
EXPECT_FALSE(button2->HasFocus());
}
// Verify that arrow keys can change focus if |enable_arrow_key_traversal| is
// set to true.
TEST_F(WidgetTest, ArrowKeyTraversalMovesFocusBetweenViews) {
WidgetAutoclosePtr toplevel(CreateTopLevelPlatformWidget());
toplevel->widget_delegate()->SetEnableArrowKeyTraversal(true);
View* container = toplevel->client_view();
container->SetLayoutManager(std::make_unique<FillLayout>());
auto* const button1 =
container->AddChildView(std::make_unique<LabelButton>());
auto* const button2 =
container->AddChildView(std::make_unique<LabelButton>());
auto* const button3 =
container->AddChildView(std::make_unique<LabelButton>());
toplevel->Show();
button1->RequestFocus();
// Right should advance focus (similar to TAB).
ui::KeyEvent right_arrow(ui::ET_KEY_PRESSED, ui::VKEY_RIGHT, ui::EF_NONE);
toplevel->OnKeyEvent(&right_arrow);
EXPECT_FALSE(button1->HasFocus());
EXPECT_TRUE(button2->HasFocus());
EXPECT_FALSE(button3->HasFocus());
// Down should also advance focus.
ui::KeyEvent down_arrow(ui::ET_KEY_PRESSED, ui::VKEY_DOWN, ui::EF_NONE);
toplevel->OnKeyEvent(&down_arrow);
EXPECT_FALSE(button1->HasFocus());
EXPECT_FALSE(button2->HasFocus());
EXPECT_TRUE(button3->HasFocus());
// Left should reverse focus (similar to SHIFT+TAB).
ui::KeyEvent left_arrow(ui::ET_KEY_PRESSED, ui::VKEY_LEFT, ui::EF_NONE);
toplevel->OnKeyEvent(&left_arrow);
EXPECT_FALSE(button1->HasFocus());
EXPECT_TRUE(button2->HasFocus());
EXPECT_FALSE(button3->HasFocus());
// Up should also reverse focus.
ui::KeyEvent up_arrow(ui::ET_KEY_PRESSED, ui::VKEY_UP, ui::EF_NONE);
toplevel->OnKeyEvent(&up_arrow);
EXPECT_TRUE(button1->HasFocus());
EXPECT_FALSE(button2->HasFocus());
EXPECT_FALSE(button3->HasFocus());
// Test backwards wrap-around.
ui::KeyEvent up_arrow2(ui::ET_KEY_PRESSED, ui::VKEY_UP, ui::EF_NONE);
toplevel->OnKeyEvent(&up_arrow2);
EXPECT_FALSE(button1->HasFocus());
EXPECT_FALSE(button2->HasFocus());
EXPECT_TRUE(button3->HasFocus());
// Test forward wrap-around.
ui::KeyEvent down_arrow2(ui::ET_KEY_PRESSED, ui::VKEY_DOWN, ui::EF_NONE);
toplevel->OnKeyEvent(&down_arrow2);
EXPECT_TRUE(button1->HasFocus());
EXPECT_FALSE(button2->HasFocus());
EXPECT_FALSE(button3->HasFocus());
}
TEST_F(WidgetTest, ArrowKeyTraversalNotInheritedByChildWidgets) {
WidgetAutoclosePtr parent(CreateTopLevelPlatformWidget());
Widget* child = CreateChildPlatformWidget(parent->GetNativeView());
parent->widget_delegate()->SetEnableArrowKeyTraversal(true);
View* container = child->GetContentsView();
DCHECK(container);
container->SetLayoutManager(std::make_unique<FillLayout>());
auto* const button1 =
container->AddChildView(std::make_unique<LabelButton>());
auto* const button2 =
container->AddChildView(std::make_unique<LabelButton>());
parent->Show();
child->Show();
button1->RequestFocus();
// Arrow key should not cause focus change on child since only the parent
// Widget has |enable_arrow_key_traversal| set.
ui::KeyEvent right_arrow(ui::ET_KEY_PRESSED, ui::VKEY_RIGHT, ui::EF_NONE);
child->OnKeyEvent(&right_arrow);
EXPECT_TRUE(button1->HasFocus());
EXPECT_FALSE(button2->HasFocus());
}
TEST_F(WidgetTest, ArrowKeyTraversalMayBeExplicitlyEnabledByChildWidgets) {
WidgetAutoclosePtr parent(CreateTopLevelPlatformWidget());
Widget* child = CreateChildPlatformWidget(parent->GetNativeView());
child->widget_delegate()->SetEnableArrowKeyTraversal(true);
View* container = child->GetContentsView();
container->SetLayoutManager(std::make_unique<FillLayout>());
auto* const button1 =
container->AddChildView(std::make_unique<LabelButton>());
auto* const button2 =
container->AddChildView(std::make_unique<LabelButton>());
parent->Show();
child->Show();
button1->RequestFocus();
// Arrow key should cause focus key on child since child has flag set, even
// if the parent Widget does not.
ui::KeyEvent right_arrow(ui::ET_KEY_PRESSED, ui::VKEY_RIGHT, ui::EF_NONE);
child->OnKeyEvent(&right_arrow);
EXPECT_FALSE(button1->HasFocus());
EXPECT_TRUE(button2->HasFocus());
}
////////////////////////////////////////////////////////////////////////////////
// Widget::GetTopLevelWidget tests.
TEST_F(WidgetTest, GetTopLevelWidget_Native) {
// Create a hierarchy of native widgets.
WidgetAutoclosePtr toplevel(CreateTopLevelPlatformWidget());
gfx::NativeView parent = toplevel->GetNativeView();
Widget* child = CreateChildPlatformWidget(parent);
EXPECT_EQ(toplevel.get(), toplevel->GetTopLevelWidget());
EXPECT_EQ(toplevel.get(), child->GetTopLevelWidget());
// |child| should be automatically destroyed with |toplevel|.
}
// Test if a focus manager and an inputmethod work without CHECK failure
// when window activation changes.
TEST_F(WidgetTest, ChangeActivation) {
WidgetAutoclosePtr top1(CreateTopLevelPlatformWidget());
top1->Show();
RunPendingMessages();
WidgetAutoclosePtr top2(CreateTopLevelPlatformWidget());
top2->Show();
RunPendingMessages();
top1->Activate();
RunPendingMessages();
top2->Activate();
RunPendingMessages();
top1->Activate();
RunPendingMessages();
}
// Tests visibility of child widgets.
TEST_F(WidgetTest, Visibility) {
WidgetAutoclosePtr toplevel(CreateTopLevelPlatformWidget());
gfx::NativeView parent = toplevel->GetNativeView();
Widget* child = CreateChildPlatformWidget(parent);
EXPECT_FALSE(toplevel->IsVisible());
EXPECT_FALSE(child->IsVisible());
// Showing a child with a hidden parent keeps the child hidden.
child->Show();
EXPECT_FALSE(toplevel->IsVisible());
EXPECT_FALSE(child->IsVisible());
// Showing a hidden parent with a visible child shows both.
toplevel->Show();
EXPECT_TRUE(toplevel->IsVisible());
EXPECT_TRUE(child->IsVisible());
// Hiding a parent hides both parent and child.
toplevel->Hide();
EXPECT_FALSE(toplevel->IsVisible());
EXPECT_FALSE(child->IsVisible());
// Hiding a child while the parent is hidden keeps the child hidden when the
// parent is shown.
child->Hide();
toplevel->Show();
EXPECT_TRUE(toplevel->IsVisible());
EXPECT_FALSE(child->IsVisible());
// |child| should be automatically destroyed with |toplevel|.
}
// Test that child widgets are positioned relative to their parent.
TEST_F(WidgetTest, ChildBoundsRelativeToParent) {
WidgetAutoclosePtr toplevel(CreateTopLevelPlatformWidget());
Widget* child = CreateChildPlatformWidget(toplevel->GetNativeView());
toplevel->SetBounds(gfx::Rect(160, 100, 320, 200));
child->SetBounds(gfx::Rect(0, 0, 320, 200));
child->Show();
toplevel->Show();
gfx::Rect toplevel_bounds = toplevel->GetWindowBoundsInScreen();
// Check the parent origin. If it was (0, 0) the test wouldn't be interesting.
EXPECT_NE(gfx::Vector2d(0, 0), toplevel_bounds.OffsetFromOrigin());
// The child's origin is at (0, 0), but the same size, so bounds should match.
EXPECT_EQ(toplevel_bounds, child->GetWindowBoundsInScreen());
}
////////////////////////////////////////////////////////////////////////////////
// Widget ownership tests.
//
// Tests various permutations of Widget ownership specified in the
// InitParams::Ownership param. Make sure that they are properly destructed
// during shutdown.
// A bag of state to monitor destructions.
struct OwnershipTestState {
OwnershipTestState() = default;
bool widget_deleted = false;
bool native_widget_deleted = false;
};
class WidgetOwnershipTest : public WidgetTest {
public:
WidgetOwnershipTest() = default;
WidgetOwnershipTest(const WidgetOwnershipTest&) = delete;
WidgetOwnershipTest& operator=(const WidgetOwnershipTest&) = delete;
~WidgetOwnershipTest() override = default;
void TearDown() override {
EXPECT_TRUE(state()->widget_deleted);
EXPECT_TRUE(state()->native_widget_deleted);
WidgetTest::TearDown();
}
OwnershipTestState* state() { return &state_; }
private:
OwnershipTestState state_;
};
// A Widget subclass that updates a bag of state when it is destroyed.
class OwnershipTestWidget : public Widget {
public:
explicit OwnershipTestWidget(OwnershipTestState* state) : state_(state) {}
OwnershipTestWidget(const OwnershipTestWidget&) = delete;
OwnershipTestWidget& operator=(const OwnershipTestWidget&) = delete;
~OwnershipTestWidget() override { state_->widget_deleted = true; }
private:
raw_ptr<OwnershipTestState> state_;
};
class NativeWidgetDestroyedWaiter {
public:
explicit NativeWidgetDestroyedWaiter(OwnershipTestState* state)
: state_(state) {}
base::OnceClosure GetNativeWidgetDestroyedCallback() {
return base::BindOnce(
[](OwnershipTestState* state, base::RunLoop* run_loop) {
state->native_widget_deleted = true;
run_loop->Quit();
},
state_.get(), &run_loop_);
}
void Wait() {
if (!state_->native_widget_deleted)
run_loop_.Run();
}
private:
base::RunLoop run_loop_;
raw_ptr<OwnershipTestState> state_;
};
using NativeWidgetOwnsWidgetTest = WidgetOwnershipTest;
// NativeWidget owns its Widget, part 1.1: NativeWidget is a non-desktop
// widget, CloseNow() destroys Widget and NativeWidget synchronously.
TEST_F(NativeWidgetOwnsWidgetTest, NonDesktopWidget_CloseNow) {
Widget* widget = new OwnershipTestWidget(state());
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.native_widget = CreatePlatformNativeWidgetImpl(
widget, kStubCapture, &state()->native_widget_deleted);
widget->Init(std::move(params));
widget->CloseNow();
// Both widget and native widget should be deleted synchronously.
EXPECT_TRUE(state()->widget_deleted);
EXPECT_TRUE(state()->native_widget_deleted);
}
// NativeWidget owns its Widget, part 1.2: NativeWidget is a non-desktop
// widget, Close() destroys Widget and NativeWidget asynchronously.
TEST_F(NativeWidgetOwnsWidgetTest, NonDesktopWidget_Close) {
NativeWidgetDestroyedWaiter waiter(state());
Widget* widget = new OwnershipTestWidget(state());
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.native_widget = CreatePlatformNativeWidgetImpl(
widget, kStubCapture, waiter.GetNativeWidgetDestroyedCallback());
widget->Init(std::move(params));
widget->Close();
waiter.Wait();
EXPECT_TRUE(state()->widget_deleted);
EXPECT_TRUE(state()->native_widget_deleted);
}
// NativeWidget owns its Widget, part 1.3: NativeWidget is a desktop
// widget, Close() destroys Widget and NativeWidget asynchronously.
#if BUILDFLAG(ENABLE_DESKTOP_AURA)
TEST_F(NativeWidgetOwnsWidgetTest, DesktopWidget_Close) {
NativeWidgetDestroyedWaiter waiter(state());
Widget* widget = new OwnershipTestWidget(state());
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.native_widget = CreatePlatformDesktopNativeWidgetImpl(
widget, kStubCapture, waiter.GetNativeWidgetDestroyedCallback());
widget->Init(std::move(params));
widget->Close();
waiter.Wait();
EXPECT_TRUE(state()->widget_deleted);
EXPECT_TRUE(state()->native_widget_deleted);
}
#endif
// NativeWidget owns its Widget, part 1.4: NativeWidget is a desktop
// widget. Unlike desktop widget, CloseNow() might destroy Widget and
// NativeWidget asynchronously.
#if BUILDFLAG(ENABLE_DESKTOP_AURA)
TEST_F(NativeWidgetOwnsWidgetTest, DesktopWidget_CloseNow) {
NativeWidgetDestroyedWaiter waiter(state());
Widget* widget = new OwnershipTestWidget(state());
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.native_widget = CreatePlatformDesktopNativeWidgetImpl(
widget, kStubCapture, waiter.GetNativeWidgetDestroyedCallback());
widget->Init(std::move(params));
widget->CloseNow();
waiter.Wait();
EXPECT_TRUE(state()->widget_deleted);
EXPECT_TRUE(state()->native_widget_deleted);
}
#endif
// NativeWidget owns its Widget, part 2.1: NativeWidget is a non-desktop
// widget. CloseNow() the parent should destroy the child.
TEST_F(NativeWidgetOwnsWidgetTest, NonDestkopWidget_CloseNowParent) {
NativeWidgetDestroyedWaiter waiter(state());
Widget* toplevel = CreateTopLevelPlatformWidget();
Widget* widget = new OwnershipTestWidget(state());
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.parent = toplevel->GetNativeView();
params.native_widget = CreatePlatformNativeWidgetImpl(
widget, kStubCapture, waiter.GetNativeWidgetDestroyedCallback());
widget->Init(std::move(params));
// Now destroy the native widget. This is achieved by closing the toplevel.
toplevel->CloseNow();
// The NativeWidget won't be deleted until after a return to the message loop
// so we have to run pending messages before testing the destruction status.
waiter.Wait();
EXPECT_TRUE(state()->widget_deleted);
EXPECT_TRUE(state()->native_widget_deleted);
}
// NativeWidget owns its Widget, part 2.2: NativeWidget is a desktop
// widget. CloseNow() the parent should destroy the child.
#if BUILDFLAG(ENABLE_DESKTOP_AURA)
TEST_F(NativeWidgetOwnsWidgetTest, DestkopWidget_CloseNowParent) {
NativeWidgetDestroyedWaiter waiter(state());
Widget* toplevel = CreateTopLevelPlatformDesktopWidget();
Widget* widget = new OwnershipTestWidget(state());
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.parent = toplevel->GetNativeView();
params.native_widget = CreatePlatformDesktopNativeWidgetImpl(
widget, kStubCapture, waiter.GetNativeWidgetDestroyedCallback());
widget->Init(std::move(params));
// Now destroy the native widget. This is achieved by closing the toplevel.
toplevel->CloseNow();
// The NativeWidget won't be deleted until after a return to the message loop
// so we have to run pending messages before testing the destruction status.
waiter.Wait();
EXPECT_TRUE(state()->widget_deleted);
EXPECT_TRUE(state()->native_widget_deleted);
}
#endif
// NativeWidget owns its Widget, part 3.1: NativeWidget is a non-desktop
// widget, destroyed out from under it by the OS.
TEST_F(NativeWidgetOwnsWidgetTest, NonDesktopWidget_NativeDestroy) {
Widget* widget = new OwnershipTestWidget(state());
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.native_widget = CreatePlatformNativeWidgetImpl(
widget, kStubCapture, &state()->native_widget_deleted);
widget->Init(std::move(params));
// Now simulate a destroy of the platform native widget from the OS:
SimulateNativeDestroy(widget);
EXPECT_TRUE(state()->widget_deleted);
EXPECT_TRUE(state()->native_widget_deleted);
}
#if BUILDFLAG(ENABLE_DESKTOP_AURA)
// NativeWidget owns its Widget, part 3.2: NativeWidget is a desktop
// widget, destroyed out from under it by the OS.
TEST_F(NativeWidgetOwnsWidgetTest, DesktopWidget_NativeDestroy) {
NativeWidgetDestroyedWaiter waiter(state());
Widget* widget = new OwnershipTestWidget(state());
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.native_widget = CreatePlatformDesktopNativeWidgetImpl(
widget, kStubCapture, waiter.GetNativeWidgetDestroyedCallback());
widget->Init(std::move(params));
// Now simulate a destroy of the platform native widget from the OS:
SimulateDesktopNativeDestroy(widget);
waiter.Wait();
EXPECT_TRUE(state()->widget_deleted);
EXPECT_TRUE(state()->native_widget_deleted);
}
#endif
using WidgetOwnsNativeWidgetTest = WidgetOwnershipTest;
// Widget owns its NativeWidget, part 1.
TEST_F(WidgetOwnsNativeWidgetTest, Ownership) {
auto widget = std::make_unique<OwnershipTestWidget>(state());
Widget::InitParams params = CreateParamsForTestWidget();
params.native_widget = CreatePlatformNativeWidgetImpl(
widget.get(), kStubCapture, &state()->native_widget_deleted);
widget->Init(std::move(params));
// Now delete the Widget, which should delete the NativeWidget.
widget.reset();
// TODO(beng): write test for this ownership scenario and the NativeWidget
// being deleted out from under the Widget.
}
// Widget owns its NativeWidget, part 2: destroy the parent view.
TEST_F(WidgetOwnsNativeWidgetTest, DestroyParentView) {
Widget* toplevel = CreateTopLevelPlatformWidget();
auto widget = std::make_unique<OwnershipTestWidget>(state());
Widget::InitParams params = CreateParamsForTestWidget();
params.parent = toplevel->GetNativeView();
params.native_widget = CreatePlatformNativeWidgetImpl(
widget.get(), kStubCapture, &state()->native_widget_deleted);
widget->Init(std::move(params));
// Now close the toplevel, which deletes the view hierarchy.
toplevel->CloseNow();
RunPendingMessages();
// This shouldn't delete the widget because it shouldn't be deleted
// from the native side.
EXPECT_FALSE(state()->widget_deleted);
EXPECT_FALSE(state()->native_widget_deleted);
}
// Widget owns its NativeWidget, part 3: has a WidgetDelegateView as contents.
TEST_F(WidgetOwnsNativeWidgetTest, WidgetDelegateView) {
auto widget = std::make_unique<OwnershipTestWidget>(state());
Widget::InitParams params = CreateParamsForTestWidget();
params.native_widget = CreatePlatformNativeWidgetImpl(
widget.get(), kStubCapture, &state()->native_widget_deleted);
params.delegate = new WidgetDelegateView();
widget->Init(std::move(params));
// Allow the Widget to go out of scope. There should be no crash or
// use-after-free.
}
// Widget owns its NativeWidget, part 4: Widget::CloseNow should be idempotent.
TEST_F(WidgetOwnsNativeWidgetTest, IdempotentCloseNow) {
auto widget = std::make_unique<OwnershipTestWidget>(state());
Widget::InitParams params = CreateParamsForTestWidget();
params.native_widget = CreatePlatformNativeWidgetImpl(
widget.get(), kStubCapture, &state()->native_widget_deleted);
widget->Init(std::move(params));
// Now close the Widget, which should delete the NativeWidget.
widget->CloseNow();
RunPendingMessages();
// Close the widget again should not crash.
widget->CloseNow();
RunPendingMessages();
}
// Widget owns its NativeWidget, part 5: Widget::Close should be idempotent.
TEST_F(WidgetOwnsNativeWidgetTest, IdempotentClose) {
auto widget = std::make_unique<OwnershipTestWidget>(state());
Widget::InitParams params = CreateParamsForTestWidget();
params.native_widget = CreatePlatformNativeWidgetImpl(
widget.get(), kStubCapture, &state()->native_widget_deleted);
widget->Init(std::move(params));
// Now close the Widget, which should delete the NativeWidget.
widget->Close();
RunPendingMessages();
// Close the widget again should not crash.
widget->Close();
RunPendingMessages();
}
// Test for CLIENT_OWNS_WIDGET. The client holds a unique_ptr<Widget>.
// The NativeWidget will be destroyed when the platform window is closed.
using ClientOwnsWidgetTest = WidgetOwnershipTest;
TEST_F(ClientOwnsWidgetTest, Ownership) {
auto widget = std::make_unique<OwnershipTestWidget>(state());
Widget::InitParams params = CreateParamsForTestWidget();
params.native_widget = CreatePlatformNativeWidgetImpl(
widget.get(), kStubCapture, &state()->native_widget_deleted);
params.ownership = Widget::InitParams::CLIENT_OWNS_WIDGET;
widget->Init(std::move(params));
widget->CloseNow();
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(state()->native_widget_deleted);
}
////////////////////////////////////////////////////////////////////////////////
// Test to verify using various Widget methods doesn't crash when the underlying
// NativeView and NativeWidget is destroyed. Currently, for
// the WIDGET_OWNS_NATIVE_WIDGET ownership pattern, the NativeWidget will not be
// destroyed, but |native_widget_| will still be set to nullptr.
class WidgetWithDestroyedNativeViewOrNativeWidgetTest
: public ViewsTestBase,
public testing::WithParamInterface<
std::tuple<ViewsTestBase::NativeWidgetType,
Widget::InitParams::Ownership>> {
public:
WidgetWithDestroyedNativeViewOrNativeWidgetTest() = default;
WidgetWithDestroyedNativeViewOrNativeWidgetTest(
const WidgetWithDestroyedNativeViewOrNativeWidgetTest&) = delete;
WidgetWithDestroyedNativeViewOrNativeWidgetTest& operator=(
const WidgetWithDestroyedNativeViewOrNativeWidgetTest&) = delete;
~WidgetWithDestroyedNativeViewOrNativeWidgetTest() override = default;
// ViewsTestBase:
void SetUp() override {
set_native_widget_type(
std::get<ViewsTestBase::NativeWidgetType>(GetParam()));
ViewsTestBase::SetUp();
if (std::get<Widget::InitParams::Ownership>(GetParam()) ==
Widget::InitParams::CLIENT_OWNS_WIDGET) {
widget_ = std::make_unique<Widget>();
Widget::InitParams params = CreateParamsForTestWidget();
params.ownership = Widget::InitParams::CLIENT_OWNS_WIDGET;
widget_->Init(std::move(params));
} else {
widget_ = CreateTestWidget();
}
widget()->Show();
widget()->native_widget_private()->CloseNow();
task_environment()->RunUntilIdle();
}
Widget* widget() { return widget_.get(); }
static std::string PrintTestName(
const ::testing::TestParamInfo<
WidgetWithDestroyedNativeViewOrNativeWidgetTest::ParamType>& info) {
std::string test_name;
switch (std::get<ViewsTestBase::NativeWidgetType>(info.param)) {
case ViewsTestBase::NativeWidgetType::kDefault:
test_name += "DefaultNativeWidget";
break;
case ViewsTestBase::NativeWidgetType::kDesktop:
test_name += "DesktopNativeWidget";
break;
}
test_name += "_";
switch (std::get<Widget::InitParams::Ownership>(info.param)) {
case Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET:
test_name += "WidgetOwnsNativeWidget";
break;
case Widget::InitParams::CLIENT_OWNS_WIDGET:
test_name += "ClientOwnsNativeWidget";
break;
case Widget::InitParams::NATIVE_WIDGET_OWNS_WIDGET:
// Note: We don't test for this case in
// WidgetWithDestroyedNativeViewOrNativeWidgetTest.
test_name += "NativeWidgetOwnsWidget";
break;
}
return test_name;
}
private:
std::unique_ptr<Widget> widget_;
};
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, Activate) {
widget()->Activate();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, AddAndRemoveObserver) {
// Constructor calls |AddObserver()|
TestWidgetObserver observer(widget());
widget()->RemoveObserver(&observer);
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
AddAndRemoveRemovalsObserver) {
TestWidgetRemovalsObserver removals_observer;
widget()->AddRemovalsObserver(&removals_observer);
widget()->RemoveRemovalsObserver(&removals_observer);
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, AsWidget) {
widget()->AsWidget();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, CanActivate) {
widget()->CanActivate();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, CenterWindow) {
widget()->CenterWindow(gfx::Size());
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, ClearNativeFocus) {
widget()->ClearNativeFocus();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, ClientView) {
widget()->client_view();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, Close) {
widget()->Close();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
CloseAllSecondaryWidgets) {
widget()->CloseAllSecondaryWidgets();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, CloseNow) {
widget()->CloseNow();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, ClosedReason) {
widget()->closed_reason();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, CloseWithReason) {
widget()->CloseWithReason(views::Widget::ClosedReason::kUnspecified);
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
CreateNonClientFrameView) {
widget()->CreateNonClientFrameView();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, Deactivate) {
widget()->Deactivate();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, DebugToggleFrameType) {
widget()->DebugToggleFrameType();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, DraggedView) {
widget()->dragged_view();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, EndMoveLoop) {
widget()->EndMoveLoop();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, ExecuteCommand) {
widget()->ExecuteCommand(0);
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, FlashFrame) {
widget()->FlashFrame(true);
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, FrameType) {
widget()->frame_type();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, FrameTypeChanged) {
widget()->FrameTypeChanged();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, GetAccelerator) {
ui::Accelerator accelerator;
widget()->GetAccelerator(0, &accelerator);
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, GetAllChildWidgets) {
views::Widget::Widgets widgets;
Widget::GetAllChildWidgets(widget()->GetNativeView(), &widgets);
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, GetAllOwnedWidgets) {
views::Widget::Widgets widgets;
Widget::GetAllOwnedWidgets(widget()->GetNativeView(), &widgets);
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, GetAndSetZOrderLevel) {
widget()->SetZOrderLevel(ui::ZOrderLevel::kNormal);
widget()->GetZOrderLevel();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
GetClientAreaBoundsInScreen) {
widget()->GetClientAreaBoundsInScreen();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, GetColorProvider) {
widget()->GetColorProvider();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, GetCompositor) {
widget()->GetCompositor();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, GetContentsView) {
widget()->GetContentsView();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, GetCustomTheme) {
widget()->GetCustomTheme();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, GetEventSink) {
widget()->GetEventSink();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, GetFocusSearch) {
widget()->GetFocusSearch();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, GetFocusManager) {
widget()->GetFocusManager();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, GetFocusTraversable) {
widget()->GetFocusTraversable();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, GetGestureConsumer) {
widget()->GetGestureConsumer();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, GetGestureRecognizer) {
widget()->GetGestureRecognizer();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, GetHitTestMask) {
SkPath mask;
widget()->GetHitTestMask(&mask);
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, GetInputMethod) {
widget()->GetInputMethod();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, GetLayer) {
widget()->GetLayer();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, GetMinimumSize) {
widget()->GetMinimumSize();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, GetMaximumSize) {
widget()->GetMaximumSize();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, GetName) {
widget()->GetName();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, GetNativeTheme) {
widget()->GetNativeTheme();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, GetNativeView) {
widget()->GetNativeView();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, GetNativeWindow) {
widget()->GetNativeWindow();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
GetNativeWindowProperty) {
widget()->GetNativeWindowProperty("xx");
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, GetNonClientComponent) {
gfx::Point point;
widget()->GetNonClientComponent(point);
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
GetPrimaryWindowWidget) {
widget()->GetPrimaryWindowWidget();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, GetRestoredBounds) {
widget()->GetRestoredBounds();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, GetRootView) {
widget()->GetRootView();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, GetSublevelManager) {
widget()->GetSublevelManager();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, GetThemeProvider) {
widget()->GetThemeProvider();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, GetTooltipManager) {
widget()->GetTooltipManager();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, GetTopLevelWidget) {
widget()->GetTopLevelWidget();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
GetTopLevelWidgetForNativeView) {
Widget::GetTopLevelWidgetForNativeView(widget()->GetNativeView());
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, GetWeakPtr) {
widget()->GetWeakPtr();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
GetWidgetForNativeView) {
Widget::GetWidgetForNativeView(widget()->GetNativeView());
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
GetWidgetForNativeWindow) {
Widget::GetWidgetForNativeWindow(widget()->GetNativeWindow());
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
GetWindowBoundsInScreen) {
widget()->GetWindowBoundsInScreen();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
GetWorkAreaBoundsInScreen) {
widget()->GetWorkAreaBoundsInScreen();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, GetWorkspace) {
widget()->GetWorkspace();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, GetZOrderSublevel) {
widget()->GetZOrderSublevel();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, HasCapture) {
widget()->HasCapture();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, HasFocusManager) {
widget()->HasFocusManager();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, HasHitTestMask) {
widget()->HasHitTestMask();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, HasObserver) {
TestWidgetObserver observer(widget());
widget()->HasObserver(&observer);
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, HasRemovalsObserver) {
TestWidgetRemovalsObserver observer;
widget()->HasRemovalsObserver(&observer);
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, Hide) {
widget()->Hide();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, Init) {
Widget::InitParams params;
EXPECT_DCHECK_DEATH(widget()->Init(std::move(params)));
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, is_secondary_widget) {
widget()->is_secondary_widget();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, IsActive) {
widget()->IsActive();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, IsClosed) {
widget()->IsClosed();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, IsDialogBox) {
widget()->IsDialogBox();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, IsFullscreen) {
widget()->IsFullscreen();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, IsMaximized) {
widget()->IsMaximized();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, IsMinimized) {
widget()->IsMinimized();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, IsModal) {
widget()->IsModal();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, IsMouseEventsEnabled) {
widget()->IsMouseEventsEnabled();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, IsMoveLoopSupported) {
widget()->IsMoveLoopSupported();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
IsNativeWidgetInitialized) {
widget()->IsNativeWidgetInitialized();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, IsStackedAbove) {
std::unique_ptr<Widget> other_widget = CreateTestWidget();
widget()->IsStackedAbove(other_widget->GetNativeView());
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
IsTranslucentWindowOpacitySupported) {
widget()->IsTranslucentWindowOpacitySupported();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, IsVisible) {
widget()->IsVisible();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
IsVisibleOnAllWorkspaces) {
widget()->IsVisibleOnAllWorkspaces();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, OnGestureEvent) {
ui::GestureEvent event =
CreateTestGestureEvent(ui::ET_GESTURE_SCROLL_BEGIN, 5, 5);
widget()->OnGestureEvent(&event);
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, OnKeyEvent) {
ui::KeyEvent event(ui::ET_KEY_PRESSED, ui::VKEY_RIGHT, ui::EF_NONE);
widget()->OnKeyEvent(&event);
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, OnMouseCaptureLost) {
widget()->OnMouseCaptureLost();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, OnMouseEvent) {
gfx::Point p(200, 200);
ui::MouseEvent event(ui::ET_MOUSE_MOVED, p, p, ui::EventTimeForNow(),
ui::EF_NONE, ui::EF_NONE);
widget()->OnMouseEvent(&event);
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, OnNativeBlur) {
widget()->OnNativeBlur();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, OnNativeFocus) {
widget()->OnNativeFocus();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, OnNativeThemeUpdated) {
ui::TestNativeTheme theme;
widget()->OnNativeThemeUpdated(&theme);
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
OnNativeWidgetActivationChanged) {
widget()->OnNativeWidgetActivationChanged(false);
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
OnNativeWidgetAddedToCompositor) {
widget()->OnNativeWidgetAddedToCompositor();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
OnNativeWidgetBeginUserBoundsChange) {
widget()->OnNativeWidgetBeginUserBoundsChange();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, OnNativeWidgetCreated) {
EXPECT_DCHECK_DEATH(widget()->OnNativeWidgetCreated());
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
OnNativeWidgetDestroyed) {
widget()->OnNativeWidgetDestroyed();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
OnNativeWidgetDestroying) {
EXPECT_DCHECK_DEATH(widget()->OnNativeWidgetDestroying());
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
OnNativeWidgetEndUserBoundsChange) {
widget()->OnNativeWidgetEndUserBoundsChange();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, OnNativeWidgetMove) {
widget()->OnNativeWidgetMove();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, OnNativeWidgetPaint) {
auto display_list = base::MakeRefCounted<cc::DisplayItemList>();
widget()->OnNativeWidgetPaint(
ui::PaintContext(display_list.get(), 1, gfx::Rect(), false));
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
OnNativeWidgetParentChanged) {
widget()->OnNativeWidgetParentChanged(nullptr);
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
OnNativeWidgetRemovingFromCompositor) {
widget()->OnNativeWidgetRemovingFromCompositor();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
OnNativeWidgetSizeChanged) {
widget()->OnNativeWidgetSizeChanged(gfx::Size());
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
OnNativeWidgetVisibilityChanged) {
widget()->OnNativeWidgetVisibilityChanged(false);
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
OnNativeWidgetWindowShowStateChanged) {
widget()->OnNativeWidgetWindowShowStateChanged();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
OnNativeWidgetWorkspaceChanged) {
widget()->OnNativeWidgetWorkspaceChanged();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, OnOwnerClosing) {
widget()->OnOwnerClosing();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
OnParentShouldPaintAsActiveChanged) {
widget()->OnParentShouldPaintAsActiveChanged();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, OnScrollEvent) {
ui::ScrollEvent scroll(ui::ET_SCROLL, gfx::Point(65, 5),
ui::EventTimeForNow(), 0, 0, 20, 0, 20, 2);
widget()->OnScrollEvent(&scroll);
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
OnSizeConstraintsChanged) {
widget()->OnSizeConstraintsChanged();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, LayerTreeChanged) {
widget()->LayerTreeChanged();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
LayoutRootViewIfNecessary) {
widget()->LayoutRootViewIfNecessary();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, LockPaintAsActive) {
widget()->LockPaintAsActive();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, Maximize) {
widget()->Maximize();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, Minimize) {
widget()->Minimize();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, movement_disabled) {
widget()->movement_disabled();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, native_widget_private) {
widget()->native_widget_private();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, native_widget) {
widget()->native_widget();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, non_client_view) {
widget()->non_client_view();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
NotifyNativeViewHierarchyChanged) {
widget()->NotifyNativeViewHierarchyChanged();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
NotifyNativeViewHierarchyWillChange) {
widget()->NotifyNativeViewHierarchyWillChange();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, NotifyWillRemoveView) {
widget()->NotifyWillRemoveView(widget()->non_client_view());
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, parent) {
widget()->parent();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
RegisterPaintAsActiveChangedCallback) {
auto subscription =
widget()->RegisterPaintAsActiveChangedCallback(base::DoNothing());
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, ReleaseCapture) {
widget()->ReleaseCapture();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, ReorderNativeViews) {
widget()->ReorderNativeViews();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, ReparentNativeView) {
EXPECT_DCHECK_DEATH(
Widget::ReparentNativeView(widget()->GetNativeView(), nullptr));
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, Restore) {
widget()->Restore();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, RunMoveLoop) {
widget()->RunMoveLoop(gfx::Vector2d(), views::Widget::MoveLoopSource::kMouse,
views::Widget::MoveLoopEscapeBehavior::kHide);
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, RunShellDrag) {
std::unique_ptr<OSExchangeData> data(std::make_unique<OSExchangeData>());
widget()->RunShellDrag(nullptr, std::move(data), gfx::Point(), 0,
ui::mojom::DragEventSource::kMouse);
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, ScheduleLayout) {
widget()->ScheduleLayout();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, SchedulePaintInRect) {
widget()->SchedulePaintInRect(gfx::Rect(0, 0, 1, 2));
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, SetAspectRatio) {
widget()->SetAspectRatio(gfx::SizeF(1.0, 1.0));
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, SetBounds) {
widget()->SetBounds(gfx::Rect(0, 0, 100, 80));
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, SetBoundsConstrained) {
widget()->SetBoundsConstrained(gfx::Rect(0, 0, 120, 140));
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
SetCanAppearInExistingFullscreenSpaces) {
widget()->SetCanAppearInExistingFullscreenSpaces(false);
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, SetCapture) {
widget()->SetCapture(widget()->GetRootView());
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, SetContentsView) {
View view;
EXPECT_DCHECK_DEATH(widget()->SetContentsView(std::make_unique<View>()));
EXPECT_DCHECK_DEATH(widget()->SetContentsView(&view));
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, SetCursor) {
widget()->SetCursor(ui::Cursor());
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
SetFocusTraversableParent) {
std::unique_ptr<Widget> another_widget = CreateTestWidget();
widget()->SetFocusTraversableParent(another_widget->GetFocusTraversable());
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
SetFocusTraversableParentView) {
std::unique_ptr<Widget> another_widget = CreateTestWidget();
widget()->SetFocusTraversableParentView(another_widget->GetContentsView());
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, SetFullscreen) {
widget()->SetFullscreen(true);
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, SetInitialFocus) {
widget()->SetInitialFocus(ui::SHOW_STATE_INACTIVE);
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
SetNativeWindowProperty) {
widget()->SetNativeWindowProperty("xx", widget());
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, SetOpacity) {
widget()->SetOpacity(0.f);
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, SetShape) {
auto rects = std::make_unique<Widget::ShapeRects>();
rects->emplace_back(40, 0, 20, 100);
rects->emplace_back(0, 40, 100, 20);
widget()->SetShape(std::move(rects));
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, SetSize) {
widget()->SetSize(gfx::Size(10, 11));
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
SetVisibilityChangedAnimationsEnabled) {
widget()->SetVisibilityChangedAnimationsEnabled(false);
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
SetVisibilityAnimationDuration) {
widget()->SetVisibilityAnimationDuration(base::Seconds(1));
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
SetVisibilityAnimationTransition) {
widget()->SetVisibilityAnimationTransition(Widget::ANIMATE_BOTH);
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, SetVisible) {
widget()->SetVisibilityAnimationTransition(Widget::ANIMATE_BOTH);
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
SetVisibleOnAllWorkspaces) {
widget()->SetVisibleOnAllWorkspaces(true);
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
ShouldDescendIntoChildForEventHandling) {
widget()->ShouldDescendIntoChildForEventHandling(nullptr, gfx::NativeView(),
nullptr, gfx::Point(0, 0));
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
ShouldHandleNativeWidgetActivationChanged) {
widget()->ShouldHandleNativeWidgetActivationChanged(true);
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, ShouldPaintAsActive) {
widget()->ShouldPaintAsActive();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, ShouldUseNativeFrame) {
widget()->ShouldUseNativeFrame();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
ShouldWindowContentsBeTransparent) {
widget()->ShouldWindowContentsBeTransparent();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, Show) {
widget()->Show();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, ShowEmojiPanel) {
widget()->ShowEmojiPanel();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, ShowInactive) {
widget()->ShowInactive();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, StackAbove) {
std::unique_ptr<Widget> another_widget = CreateTestWidget();
widget()->StackAbove(another_widget->GetNativeView());
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, StackAboveWidget) {
std::unique_ptr<Widget> another_widget = CreateTestWidget();
widget()->StackAboveWidget(another_widget.get());
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, StackAtTop) {
widget()->StackAtTop();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest,
SynthesizeMouseMoveEvent) {
widget()->SynthesizeMouseMoveEvent();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, ThemeChanged) {
widget()->ThemeChanged();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, UnlockPaintAsActive) {
// UnlockPaintAsActive() is called in the destructor of PaintAsActiveLock.
// External invocation is not allowed.
EXPECT_DCHECK_DEATH(widget()->UnlockPaintAsActive());
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, UpdateWindowIcon) {
widget()->UpdateWindowIcon();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, UpdateWindowTitle) {
widget()->UpdateWindowTitle();
}
TEST_P(WidgetWithDestroyedNativeViewOrNativeWidgetTest, ViewHierarchyChanged) {
widget()->ViewHierarchyChanged(
ViewHierarchyChangedDetails(true, nullptr, nullptr, nullptr));
}
INSTANTIATE_TEST_SUITE_P(
PlatformWidgetWithDestroyedNativeViewOrNativeWidgetTest,
WidgetWithDestroyedNativeViewOrNativeWidgetTest,
::testing::Combine(
::testing::Values(ViewsTestBase::NativeWidgetType::kDefault,
ViewsTestBase::NativeWidgetType::kDesktop),
::testing::Values(Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET,
Widget::InitParams::CLIENT_OWNS_WIDGET)),
WidgetWithDestroyedNativeViewOrNativeWidgetTest::PrintTestName);
////////////////////////////////////////////////////////////////////////////////
// Widget observer tests.
//
class WidgetObserverTest : public WidgetTest, public WidgetObserver {
public:
WidgetObserverTest() = default;
~WidgetObserverTest() override = default;
// Set a widget to Close() the next time the Widget being observed is hidden.
void CloseOnNextHide(Widget* widget) { widget_to_close_on_hide_ = widget; }
// Overridden from WidgetObserver:
void OnWidgetDestroying(Widget* widget) override {
if (active_ == widget)
active_ = nullptr;
if (widget_activated_ == widget)
widget_activated_ = nullptr;
widget_closed_ = widget;
}
void OnWidgetActivationChanged(Widget* widget, bool active) override {
if (active) {
if (widget_activated_)
widget_activated_->Deactivate();
widget_activated_ = widget;
active_ = widget;
} else {
if (widget_activated_ == widget)
widget_activated_ = nullptr;
widget_deactivated_ = widget;
}
}
void OnWidgetVisibilityChanged(Widget* widget, bool visible) override {
if (visible) {
widget_shown_ = widget;
return;
}
widget_hidden_ = widget;
if (widget_to_close_on_hide_) {
widget_to_close_on_hide_->Close();
widget_to_close_on_hide_ = nullptr;
}
}
void OnWidgetBoundsChanged(Widget* widget,
const gfx::Rect& new_bounds) override {
widget_bounds_changed_ = widget;
}
void reset() {
active_ = nullptr;
widget_closed_ = nullptr;
widget_activated_ = nullptr;
widget_deactivated_ = nullptr;
widget_shown_ = nullptr;
widget_hidden_ = nullptr;
widget_bounds_changed_ = nullptr;
}
Widget* NewWidget() {
Widget* widget = CreateTopLevelNativeWidget();
widget->AddObserver(this);
return widget;
}
const Widget* active() const { return active_; }
const Widget* widget_closed() const { return widget_closed_; }
const Widget* widget_activated() const { return widget_activated_; }
const Widget* widget_deactivated() const { return widget_deactivated_; }
const Widget* widget_shown() const { return widget_shown_; }
const Widget* widget_hidden() const { return widget_hidden_; }
const Widget* widget_bounds_changed() const { return widget_bounds_changed_; }
private:
raw_ptr<Widget> active_ = nullptr;
raw_ptr<Widget> widget_closed_ = nullptr;
raw_ptr<Widget> widget_activated_ = nullptr;
raw_ptr<Widget> widget_deactivated_ = nullptr;
raw_ptr<Widget> widget_shown_ = nullptr;
raw_ptr<Widget> widget_hidden_ = nullptr;
raw_ptr<Widget> widget_bounds_changed_ = nullptr;
raw_ptr<Widget> widget_to_close_on_hide_ = nullptr;
};
// This test appears to be flaky on Mac.
#if BUILDFLAG(IS_MAC)
#define MAYBE_ActivationChange DISABLED_ActivationChange
#else
#define MAYBE_ActivationChange ActivationChange
#endif
TEST_F(WidgetObserverTest, MAYBE_ActivationChange) {
WidgetAutoclosePtr toplevel1(NewWidget());
WidgetAutoclosePtr toplevel2(NewWidget());
toplevel1->Show();
toplevel2->Show();
reset();
toplevel1->Activate();
RunPendingMessages();
EXPECT_EQ(toplevel1.get(), widget_activated());
toplevel2->Activate();
RunPendingMessages();
EXPECT_EQ(toplevel1.get(), widget_deactivated());
EXPECT_EQ(toplevel2.get(), widget_activated());
EXPECT_EQ(toplevel2.get(), active());
}
namespace {
// This class simulates a focus manager that moves focus to a second widget when
// the first one is closed. It simulates a situation where a sequence of widget
// observers might try to call Widget::Close in response to a OnWidgetClosing().
class WidgetActivationForwarder : public TestWidgetObserver {
public:
WidgetActivationForwarder(Widget* current_active_widget,
Widget* widget_to_activate)
: TestWidgetObserver(current_active_widget),
widget_to_activate_(widget_to_activate) {}
WidgetActivationForwarder(const WidgetActivationForwarder&) = delete;
WidgetActivationForwarder& operator=(const WidgetActivationForwarder&) =
delete;
~WidgetActivationForwarder() override = default;
private:
// WidgetObserver overrides:
void OnWidgetClosing(Widget* widget) override {
widget->OnNativeWidgetActivationChanged(false);
widget_to_activate_->Activate();
}
void OnWidgetActivationChanged(Widget* widget, bool active) override {
if (!active)
widget->Close();
}
raw_ptr<Widget> widget_to_activate_;
};
// This class observes a widget and counts the number of times OnWidgetClosing
// is called.
class WidgetCloseCounter : public TestWidgetObserver {
public:
explicit WidgetCloseCounter(Widget* widget) : TestWidgetObserver(widget) {}
WidgetCloseCounter(const WidgetCloseCounter&) = delete;
WidgetCloseCounter& operator=(const WidgetCloseCounter&) = delete;
~WidgetCloseCounter() override = default;
int close_count() const { return close_count_; }
private:
// WidgetObserver overrides:
void OnWidgetClosing(Widget* widget) override { close_count_++; }
int close_count_ = 0;
};
} // namespace
// Makes sure close notifications aren't sent more than once when a Widget is
// shutting down. Test for crbug.com/714334
TEST_F(WidgetObserverTest, CloseReentrancy) {
Widget* widget1 = CreateTopLevelPlatformWidget();
Widget* widget2 = CreateTopLevelPlatformWidget();
WidgetCloseCounter counter(widget1);
WidgetActivationForwarder focus_manager(widget1, widget2);
widget1->Close();
EXPECT_EQ(1, counter.close_count());
widget2->Close();
}
TEST_F(WidgetObserverTest, VisibilityChange) {
WidgetAutoclosePtr toplevel(CreateTopLevelPlatformWidget());
WidgetAutoclosePtr child1(NewWidget());
WidgetAutoclosePtr child2(NewWidget());
toplevel->Show();
child1->Show();
child2->Show();
reset();
child1->Hide();
EXPECT_EQ(child1.get(), widget_hidden());
child2->Hide();
EXPECT_EQ(child2.get(), widget_hidden());
child1->Show();
EXPECT_EQ(child1.get(), widget_shown());
child2->Show();
EXPECT_EQ(child2.get(), widget_shown());
}
TEST_F(WidgetObserverTest, DestroyBubble) {
// This test expect NativeWidgetAura, force its creation.
ViewsDelegate::GetInstance()->set_native_widget_factory(
ViewsDelegate::NativeWidgetFactory());
WidgetAutoclosePtr anchor(CreateTopLevelPlatformWidget());
anchor->Show();
BubbleDialogDelegateView* bubble_delegate =
new TestBubbleDialogDelegateView(anchor->client_view());
{
WidgetAutoclosePtr bubble_widget(
BubbleDialogDelegateView::CreateBubble(bubble_delegate));
bubble_widget->Show();
}
anchor->Hide();
}
TEST_F(WidgetObserverTest, WidgetBoundsChanged) {
WidgetAutoclosePtr child1(NewWidget());
WidgetAutoclosePtr child2(NewWidget());
child1->OnNativeWidgetMove();
EXPECT_EQ(child1.get(), widget_bounds_changed());
child2->OnNativeWidgetMove();
EXPECT_EQ(child2.get(), widget_bounds_changed());
child1->OnNativeWidgetSizeChanged(gfx::Size());
EXPECT_EQ(child1.get(), widget_bounds_changed());
child2->OnNativeWidgetSizeChanged(gfx::Size());
EXPECT_EQ(child2.get(), widget_bounds_changed());
}
// An extension to WidgetBoundsChanged to ensure notifications are forwarded
// by the NativeWidget implementation.
TEST_F(WidgetObserverTest, WidgetBoundsChangedNative) {
// Don't use NewWidget(), so that the Init() flow can be observed to ensure
// consistency across platforms.
Widget* widget = new Widget(); // Note: owned by NativeWidget.
widget->AddObserver(this);
EXPECT_FALSE(widget_bounds_changed());
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
// Use an origin within the work area since platforms (e.g. Mac) may move a
// window into the work area when showing, triggering a bounds change.
params.bounds = gfx::Rect(50, 50, 100, 100);
// Init causes a bounds change, even while not showing. Note some platforms
// cause a bounds change even when the bounds are empty. Mac does not.
widget->Init(std::move(params));
EXPECT_TRUE(widget_bounds_changed());
reset();
// Resizing while hidden, triggers a change.
widget->SetSize(gfx::Size(160, 100));
EXPECT_FALSE(widget->IsVisible());
EXPECT_TRUE(widget_bounds_changed());
reset();
// Setting the same size does nothing.
widget->SetSize(gfx::Size(160, 100));
EXPECT_FALSE(widget_bounds_changed());
reset();
// Showing does nothing to the bounds.
widget->Show();
EXPECT_TRUE(widget->IsVisible());
EXPECT_FALSE(widget_bounds_changed());
reset();
// Resizing while shown.
widget->SetSize(gfx::Size(170, 100));
EXPECT_TRUE(widget_bounds_changed());
reset();
// Resize to the same thing while shown does nothing.
widget->SetSize(gfx::Size(170, 100));
EXPECT_FALSE(widget_bounds_changed());
reset();
// Move, but don't change the size.
widget->SetBounds(gfx::Rect(110, 110, 170, 100));
EXPECT_TRUE(widget_bounds_changed());
reset();
// Moving to the same place does nothing.
widget->SetBounds(gfx::Rect(110, 110, 170, 100));
EXPECT_FALSE(widget_bounds_changed());
reset();
// No bounds change when closing.
widget->CloseNow();
EXPECT_FALSE(widget_bounds_changed());
}
namespace {
class MoveTrackingTestDesktopWidgetDelegate : public TestDesktopWidgetDelegate {
public:
int move_count() const { return move_count_; }
// WidgetDelegate:
void OnWidgetMove() override { ++move_count_; }
private:
int move_count_ = 0;
};
} // namespace
class DesktopWidgetObserverTest : public WidgetObserverTest {
public:
DesktopWidgetObserverTest() = default;
DesktopWidgetObserverTest(const DesktopWidgetObserverTest&) = delete;
DesktopWidgetObserverTest& operator=(const DesktopWidgetObserverTest&) =
delete;
~DesktopWidgetObserverTest() override = default;
// WidgetObserverTest:
void SetUp() override {
set_native_widget_type(NativeWidgetType::kDesktop);
WidgetObserverTest::SetUp();
}
};
// An extension to the WidgetBoundsChangedNative test above to ensure move
// notifications propagate to the WidgetDelegate.
TEST_F(DesktopWidgetObserverTest, OnWidgetMovedWhenOriginChangesNative) {
MoveTrackingTestDesktopWidgetDelegate delegate;
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
delegate.InitWidget(std::move(params));
Widget* widget = delegate.GetWidget();
widget->Show();
widget->SetBounds(gfx::Rect(100, 100, 300, 200));
const int moves_during_init = delegate.move_count();
// Resize without changing origin. No move.
widget->SetBounds(gfx::Rect(100, 100, 310, 210));
EXPECT_EQ(moves_during_init, delegate.move_count());
// Move without changing size. Moves.
widget->SetBounds(gfx::Rect(110, 110, 310, 210));
EXPECT_EQ(moves_during_init + 1, delegate.move_count());
// Changing both moves.
widget->SetBounds(gfx::Rect(90, 90, 330, 230));
EXPECT_EQ(moves_during_init + 2, delegate.move_count());
// Just grow vertically. On Mac, this changes the AppKit origin since it is
// from the bottom left of the screen, but there is no move as far as views is
// concerned.
widget->SetBounds(gfx::Rect(90, 90, 330, 240));
// No change.
EXPECT_EQ(moves_during_init + 2, delegate.move_count());
// For a similar reason, move the widget down by the same amount that it grows
// vertically. The AppKit origin does not change, but it is a move.
widget->SetBounds(gfx::Rect(90, 100, 330, 250));
EXPECT_EQ(moves_during_init + 3, delegate.move_count());
}
// Test correct behavior when widgets close themselves in response to visibility
// changes.
TEST_F(WidgetObserverTest, ClosingOnHiddenParent) {
WidgetAutoclosePtr parent(NewWidget());
Widget* child = CreateChildPlatformWidget(parent->GetNativeView());
TestWidgetObserver child_observer(child);
EXPECT_FALSE(parent->IsVisible());
EXPECT_FALSE(child->IsVisible());
// Note |child| is TYPE_CONTROL, which start shown. So no need to show the
// child separately.
parent->Show();
EXPECT_TRUE(parent->IsVisible());
EXPECT_TRUE(child->IsVisible());
// Simulate a child widget that closes itself when the parent is hidden.
CloseOnNextHide(child);
EXPECT_FALSE(child_observer.widget_closed());
parent->Hide();
RunPendingMessages();
EXPECT_TRUE(child_observer.widget_closed());
}
// Test behavior of NativeWidget*::GetWindowPlacement on the native desktop.
#if BUILDFLAG(IS_LINUX)
// On desktop-Linux cheat and use non-desktop widgets. On X11, minimize is
// asynchronous. Also (harder) showing a window doesn't activate it without
// user interaction (or extra steps only done for interactive ui tests).
// Without that, show_state remains in ui::SHOW_STATE_INACTIVE throughout.
// TODO(tapted): Find a nice way to run this with desktop widgets on Linux.
TEST_F(WidgetTest, GetWindowPlacement) {
#else
TEST_F(DesktopWidgetTest, GetWindowPlacement) {
#endif
WidgetAutoclosePtr widget;
widget.reset(CreateTopLevelNativeWidget());
gfx::Rect expected_bounds(100, 110, 200, 220);
widget->SetBounds(expected_bounds);
widget->Show();
// Start with something invalid to ensure it changes.
ui::WindowShowState show_state = ui::SHOW_STATE_END;
gfx::Rect restored_bounds;
internal::NativeWidgetPrivate* native_widget =
widget->native_widget_private();
native_widget->GetWindowPlacement(&restored_bounds, &show_state);
EXPECT_EQ(expected_bounds, restored_bounds);
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
// Non-desktop/Ash widgets start off in "default" until a Restore().
EXPECT_EQ(ui::SHOW_STATE_DEFAULT, show_state);
widget->Restore();
native_widget->GetWindowPlacement(&restored_bounds, &show_state);
#endif
EXPECT_EQ(ui::SHOW_STATE_NORMAL, show_state);
views::test::PropertyWaiter minimize_waiter(
base::BindRepeating(&Widget::IsMinimized, base::Unretained(widget.get())),
true);
widget->Minimize();
EXPECT_TRUE(minimize_waiter.Wait());
native_widget->GetWindowPlacement(&restored_bounds, &show_state);
EXPECT_EQ(ui::SHOW_STATE_MINIMIZED, show_state);
EXPECT_EQ(expected_bounds, restored_bounds);
views::test::PropertyWaiter restore_waiter(
base::BindRepeating(&Widget::IsMinimized, base::Unretained(widget.get())),
false);
widget->Restore();
EXPECT_TRUE(restore_waiter.Wait());
native_widget->GetWindowPlacement(&restored_bounds, &show_state);
EXPECT_EQ(ui::SHOW_STATE_NORMAL, show_state);
EXPECT_EQ(expected_bounds, restored_bounds);
expected_bounds = gfx::Rect(130, 140, 230, 250);
widget->SetBounds(expected_bounds);
native_widget->GetWindowPlacement(&restored_bounds, &show_state);
EXPECT_EQ(ui::SHOW_STATE_NORMAL, show_state);
EXPECT_EQ(expected_bounds, restored_bounds);
widget->SetFullscreen(true);
native_widget->GetWindowPlacement(&restored_bounds, &show_state);
#if BUILDFLAG(IS_WIN)
// Desktop Aura widgets on Windows currently don't update show_state when
// going fullscreen, and report restored_bounds as the full screen size.
// See http://crbug.com/475813.
EXPECT_EQ(ui::SHOW_STATE_NORMAL, show_state);
#else
EXPECT_EQ(ui::SHOW_STATE_FULLSCREEN, show_state);
EXPECT_EQ(expected_bounds, restored_bounds);
#endif
widget->SetFullscreen(false);
native_widget->GetWindowPlacement(&restored_bounds, &show_state);
EXPECT_EQ(ui::SHOW_STATE_NORMAL, show_state);
EXPECT_EQ(expected_bounds, restored_bounds);
}
// Test that widget size constraints are properly applied immediately after
// Init(), and that SetBounds() calls are appropriately clamped.
TEST_F(DesktopWidgetTest, MinimumSizeConstraints) {
TestDesktopWidgetDelegate delegate;
gfx::Size minimum_size(100, 100);
const gfx::Size smaller_size(90, 90);
delegate.set_contents_view(new StaticSizedView(minimum_size));
delegate.InitWidget(CreateParams(Widget::InitParams::TYPE_WINDOW));
Widget* widget = delegate.GetWidget();
// On desktop Linux, the Widget must be shown to ensure the window is mapped.
// On other platforms this line is optional.
widget->Show();
// Sanity checks.
EXPECT_GT(delegate.initial_bounds().width(), minimum_size.width());
EXPECT_GT(delegate.initial_bounds().height(), minimum_size.height());
EXPECT_EQ(delegate.initial_bounds().size(),
widget->GetWindowBoundsInScreen().size());
// Note: StaticSizedView doesn't currently provide a maximum size.
EXPECT_EQ(gfx::Size(), widget->GetMaximumSize());
if (!widget->ShouldUseNativeFrame()) {
// The test environment may have dwm disabled on Windows. In this case,
// CustomFrameView is used instead of the NativeFrameView, which will
// provide a minimum size that includes frame decorations.
minimum_size = widget->non_client_view()
->GetWindowBoundsForClientBounds(gfx::Rect(minimum_size))
.size();
}
EXPECT_EQ(minimum_size, widget->GetMinimumSize());
EXPECT_EQ(minimum_size, GetNativeWidgetMinimumContentSize(widget));
// Trying to resize smaller than the minimum size should restrict the content
// size to the minimum size.
widget->SetBounds(gfx::Rect(smaller_size));
EXPECT_EQ(minimum_size, widget->GetClientAreaBoundsInScreen().size());
widget->SetSize(smaller_size);
EXPECT_EQ(minimum_size, widget->GetClientAreaBoundsInScreen().size());
}
// When a non-desktop widget has a desktop child widget, due to the
// async nature of desktop widget shutdown, the parent can be destroyed before
// its child. Make sure that parent() returns nullptr at this time.
#if BUILDFLAG(ENABLE_DESKTOP_AURA)
TEST_F(DesktopWidgetTest, GetPossiblyDestroyedParent) {
WidgetAutoclosePtr root(CreateTopLevelNativeWidget());
const auto create_widget = [](Widget* parent, bool is_desktop) {
Widget* widget = new Widget;
Widget::InitParams init_params(Widget::InitParams::TYPE_WINDOW);
init_params.parent = parent->GetNativeView();
init_params.context = parent->GetNativeView();
if (is_desktop) {
init_params.native_widget =
new test::TestPlatformNativeWidget<DesktopNativeWidgetAura>(
widget, false, nullptr);
} else {
init_params.native_widget =
new test::TestPlatformNativeWidget<NativeWidgetAura>(widget, false,
nullptr);
}
widget->Init(std::move(init_params));
return widget;
};
WidgetAutoclosePtr child(create_widget(root.get(), /* non-desktop */ false));
WidgetAutoclosePtr grandchild(create_widget(child.get(), /* desktop */ true));
child.reset();
EXPECT_EQ(grandchild->parent(), nullptr);
}
#endif // BUILDFLAG(ENABLE_DESKTOP_AURA)
// Tests that SetBounds() and GetWindowBoundsInScreen() is symmetric when the
// widget is visible and not maximized or fullscreen.
TEST_F(WidgetTest, GetWindowBoundsInScreen) {
// Choose test coordinates away from edges and dimensions that are "small"
// (but not too small) to ensure the OS doesn't try to adjust them.
const gfx::Rect kTestBounds(150, 150, 400, 300);
const gfx::Size kTestSize(200, 180);
{
// First test a toplevel widget.
WidgetAutoclosePtr widget(CreateTopLevelPlatformWidget());
widget->Show();
EXPECT_NE(kTestSize.ToString(),
widget->GetWindowBoundsInScreen().size().ToString());
widget->SetSize(kTestSize);
EXPECT_EQ(kTestSize.ToString(),
widget->GetWindowBoundsInScreen().size().ToString());
EXPECT_NE(kTestBounds.ToString(),
widget->GetWindowBoundsInScreen().ToString());
widget->SetBounds(kTestBounds);
EXPECT_EQ(kTestBounds.ToString(),
widget->GetWindowBoundsInScreen().ToString());
// Changing just the size should not change the origin.
widget->SetSize(kTestSize);
EXPECT_EQ(kTestBounds.origin().ToString(),
widget->GetWindowBoundsInScreen().origin().ToString());
}
// Same tests with a frameless window.
WidgetAutoclosePtr widget(CreateTopLevelFramelessPlatformWidget());
widget->Show();
EXPECT_NE(kTestSize.ToString(),
widget->GetWindowBoundsInScreen().size().ToString());
widget->SetSize(kTestSize);
EXPECT_EQ(kTestSize.ToString(),
widget->GetWindowBoundsInScreen().size().ToString());
EXPECT_NE(kTestBounds.ToString(),
widget->GetWindowBoundsInScreen().ToString());
widget->SetBounds(kTestBounds);
EXPECT_EQ(kTestBounds.ToString(),
widget->GetWindowBoundsInScreen().ToString());
// For a frameless widget, the client bounds should also match.
EXPECT_EQ(kTestBounds.ToString(),
widget->GetClientAreaBoundsInScreen().ToString());
// Verify origin is stable for a frameless window as well.
widget->SetSize(kTestSize);
EXPECT_EQ(kTestBounds.origin().ToString(),
widget->GetWindowBoundsInScreen().origin().ToString());
}
// Chrome OS widgets need the shell to maximize/fullscreen window.
// Disable on desktop Linux because windows restore to the wrong bounds.
// See http://crbug.com/515369.
#if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_LINUX)
#define MAYBE_GetRestoredBounds DISABLED_GetRestoredBounds
#else
#define MAYBE_GetRestoredBounds GetRestoredBounds
#endif
// Test that GetRestoredBounds() returns the original bounds of the window.
TEST_F(DesktopWidgetTest, MAYBE_GetRestoredBounds) {
WidgetAutoclosePtr toplevel(CreateTopLevelNativeWidget());
toplevel->Show();
// Initial restored bounds have non-zero size.
EXPECT_FALSE(toplevel->GetRestoredBounds().IsEmpty());
const gfx::Rect bounds(100, 100, 200, 200);
toplevel->SetBounds(bounds);
EXPECT_EQ(bounds, toplevel->GetWindowBoundsInScreen());
EXPECT_EQ(bounds, toplevel->GetRestoredBounds());
toplevel->Maximize();
RunPendingMessages();
#if BUILDFLAG(IS_MAC)
// Current expectation on Mac is to do nothing on Maximize.
EXPECT_EQ(toplevel->GetWindowBoundsInScreen(), toplevel->GetRestoredBounds());
#else
EXPECT_NE(toplevel->GetWindowBoundsInScreen(), toplevel->GetRestoredBounds());
#endif
EXPECT_EQ(bounds, toplevel->GetRestoredBounds());
toplevel->Restore();
RunPendingMessages();
EXPECT_EQ(bounds, toplevel->GetWindowBoundsInScreen());
EXPECT_EQ(bounds, toplevel->GetRestoredBounds());
toplevel->SetFullscreen(true);
RunPendingMessages();
EXPECT_NE(toplevel->GetWindowBoundsInScreen(), toplevel->GetRestoredBounds());
EXPECT_EQ(bounds, toplevel->GetRestoredBounds());
toplevel->SetFullscreen(false);
RunPendingMessages();
EXPECT_EQ(bounds, toplevel->GetWindowBoundsInScreen());
EXPECT_EQ(bounds, toplevel->GetRestoredBounds());
}
// The key-event propagation from Widget happens differently on aura and
// non-aura systems because of the difference in IME. So this test works only on
// aura.
TEST_F(WidgetTest, KeyboardInputEvent) {
WidgetAutoclosePtr toplevel(CreateTopLevelPlatformWidget());
View* container = toplevel->client_view();
Textfield* textfield = new Textfield();
textfield->SetText(u"some text");
container->AddChildView(textfield);
toplevel->Show();
textfield->RequestFocus();
// The press gets handled. The release doesn't have an effect.
ui::KeyEvent backspace_p(ui::ET_KEY_PRESSED, ui::VKEY_DELETE, ui::EF_NONE);
toplevel->OnKeyEvent(&backspace_p);
EXPECT_TRUE(backspace_p.stopped_propagation());
ui::KeyEvent backspace_r(ui::ET_KEY_RELEASED, ui::VKEY_DELETE, ui::EF_NONE);
toplevel->OnKeyEvent(&backspace_r);
EXPECT_FALSE(backspace_r.handled());
}
TEST_F(WidgetTest, BubbleControlsResetOnInit) {
WidgetAutoclosePtr anchor(CreateTopLevelPlatformWidget());
anchor->Show();
{
TestBubbleDialogDelegateView* bubble_delegate =
new TestBubbleDialogDelegateView(anchor->client_view());
WidgetAutoclosePtr bubble_widget(
BubbleDialogDelegateView::CreateBubble(bubble_delegate));
EXPECT_TRUE(bubble_delegate->reset_controls_called_);
bubble_widget->Show();
}
anchor->Hide();
}
#if BUILDFLAG(IS_WIN)
// Test to ensure that after minimize, view width is set to zero. This is only
// the case for desktop widgets on Windows. Other platforms retain the window
// size while minimized.
TEST_F(DesktopWidgetTest, TestViewWidthAfterMinimizingWidget) {
// Create a widget.
std::unique_ptr<Widget> widget =
CreateTestWidget(Widget::InitParams::TYPE_WINDOW);
NonClientView* non_client_view = widget->non_client_view();
non_client_view->SetFrameView(
std::make_unique<MinimumSizeFrameView>(widget.get()));
// Setting the frame view doesn't do a layout, so force one.
non_client_view->InvalidateLayout();
views::test::RunScheduledLayout(non_client_view);
widget->Show();
EXPECT_NE(0, non_client_view->frame_view()->width());
widget->Minimize();
EXPECT_EQ(0, non_client_view->frame_view()->width());
}
#endif
// Desktop native widget Aura tests are for non Chrome OS platforms.
// This class validates whether paints are received for a visible Widget.
// It observes Widget visibility and Close() and tracks whether subsequent
// paints are expected.
class DesktopAuraTestValidPaintWidget : public Widget, public WidgetObserver {
public:
explicit DesktopAuraTestValidPaintWidget(Widget::InitParams init_params)
: Widget(std::move(init_params)) {
observation_.Observe(this);
}
DesktopAuraTestValidPaintWidget(const DesktopAuraTestValidPaintWidget&) =
delete;
DesktopAuraTestValidPaintWidget& operator=(
const DesktopAuraTestValidPaintWidget&) = delete;
~DesktopAuraTestValidPaintWidget() override = default;
bool ReadReceivedPaintAndReset() {
return std::exchange(received_paint_, false);
}
bool received_paint_while_hidden() const {
return received_paint_while_hidden_;
}
void WaitUntilPaint() {
if (received_paint_)
return;
base::RunLoop runloop;
quit_closure_ = runloop.QuitClosure();
runloop.Run();
quit_closure_.Reset();
}
// WidgetObserver:
void OnWidgetDestroying(Widget* widget) override { expect_paint_ = false; }
void OnNativeWidgetPaint(const ui::PaintContext& context) override {
received_paint_ = true;
EXPECT_TRUE(expect_paint_);
if (!expect_paint_)
received_paint_while_hidden_ = true;
views::Widget::OnNativeWidgetPaint(context);
if (!quit_closure_.is_null())
std::move(quit_closure_).Run();
}
void OnWidgetVisibilityChanged(Widget* widget, bool visible) override {
expect_paint_ = visible;
}
private:
bool received_paint_ = false;
bool expect_paint_ = true;
bool received_paint_while_hidden_ = false;
base::OnceClosure quit_closure_;
base::ScopedObservation<Widget, WidgetObserver> observation_{this};
};
class DesktopAuraPaintWidgetTest : public DesktopWidgetTest {
public:
std::unique_ptr<views::Widget> CreateTestWidget(
views::Widget::InitParams::Type type =
views::Widget::InitParams::TYPE_WINDOW_FRAMELESS) override {
auto widget = std::make_unique<DesktopAuraTestValidPaintWidget>(
CreateParamsForTestWidget(type));
paint_widget_ = widget.get();
View* contents_view =
widget->SetContentsView(std::make_unique<ContentsView>());
contents_view->SetFocusBehavior(View::FocusBehavior::ALWAYS);
widget->Show();
widget->Activate();
return widget;
}
DesktopAuraTestValidPaintWidget* paint_widget() { return paint_widget_; }
private:
class ContentsView : public View {
void GetAccessibleNodeData(ui::AXNodeData* node_data) override {
node_data->SetNameExplicitlyEmpty();
// Focusable Views need a valid role.
node_data->role = ax::mojom::Role::kDialog;
}
};
raw_ptr<DesktopAuraTestValidPaintWidget> paint_widget_ = nullptr;
};
TEST_F(DesktopAuraPaintWidgetTest, DesktopNativeWidgetNoPaintAfterCloseTest) {
std::unique_ptr<Widget> widget = CreateTestWidget();
paint_widget()->WaitUntilPaint();
EXPECT_TRUE(paint_widget()->ReadReceivedPaintAndReset());
widget->SchedulePaintInRect(widget->GetRestoredBounds());
widget->Close();
RunPendingMessages();
EXPECT_FALSE(paint_widget()->ReadReceivedPaintAndReset());
EXPECT_FALSE(paint_widget()->received_paint_while_hidden());
}
TEST_F(DesktopAuraPaintWidgetTest, DesktopNativeWidgetNoPaintAfterHideTest) {
std::unique_ptr<Widget> widget = CreateTestWidget();
paint_widget()->WaitUntilPaint();
EXPECT_TRUE(paint_widget()->ReadReceivedPaintAndReset());
widget->SchedulePaintInRect(widget->GetRestoredBounds());
widget->Hide();
RunPendingMessages();
EXPECT_FALSE(paint_widget()->ReadReceivedPaintAndReset());
EXPECT_FALSE(paint_widget()->received_paint_while_hidden());
widget->Close();
}
// Test to ensure that the aura Window's visibility state is set to visible if
// the underlying widget is hidden and then shown.
TEST_F(DesktopWidgetTest, TestWindowVisibilityAfterHide) {
// Create a widget.
std::unique_ptr<Widget> widget =
CreateTestWidget(Widget::InitParams::TYPE_WINDOW);
NonClientView* non_client_view = widget->non_client_view();
non_client_view->SetFrameView(
std::make_unique<MinimumSizeFrameView>(widget.get()));
widget->Show();
EXPECT_TRUE(IsNativeWindowVisible(widget->GetNativeWindow()));
widget->Hide();
EXPECT_FALSE(IsNativeWindowVisible(widget->GetNativeWindow()));
widget->Show();
EXPECT_TRUE(IsNativeWindowVisible(widget->GetNativeWindow()));
}
// Tests that wheel events generated from scroll events are targeted to the
// views under the cursor when the focused view does not processed them.
TEST_F(WidgetTest, WheelEventsFromScrollEventTarget) {
EventCountView* cursor_view = new EventCountView;
cursor_view->SetBounds(60, 0, 50, 40);
WidgetAutoclosePtr widget(CreateTopLevelPlatformWidget());
widget->GetRootView()->AddChildView(cursor_view);
// Generate a scroll event on the cursor view.
ui::ScrollEvent scroll(ui::ET_SCROLL, gfx::Point(65, 5),
ui::EventTimeForNow(), 0, 0, 20, 0, 20, 2);
widget->OnScrollEvent(&scroll);
EXPECT_EQ(1, cursor_view->GetEventCount(ui::ET_SCROLL));
EXPECT_EQ(1, cursor_view->GetEventCount(ui::ET_MOUSEWHEEL));
cursor_view->ResetCounts();
ui::ScrollEvent scroll2(ui::ET_SCROLL, gfx::Point(5, 5),
ui::EventTimeForNow(), 0, 0, 20, 0, 20, 2);
widget->OnScrollEvent(&scroll2);
EXPECT_EQ(0, cursor_view->GetEventCount(ui::ET_SCROLL));
EXPECT_EQ(0, cursor_view->GetEventCount(ui::ET_MOUSEWHEEL));
}
// Tests that if a scroll-begin gesture is not handled, then subsequent scroll
// events are not dispatched to any view.
TEST_F(WidgetTest, GestureScrollEventDispatching) {
EventCountView* noscroll_view = new EventCountView;
EventCountView* scroll_view = new ScrollableEventCountView;
noscroll_view->SetBounds(0, 0, 50, 40);
scroll_view->SetBounds(60, 0, 40, 40);
WidgetAutoclosePtr widget(CreateTopLevelPlatformWidget());
widget->GetRootView()->AddChildView(noscroll_view);
widget->GetRootView()->AddChildView(scroll_view);
{
ui::GestureEvent begin =
CreateTestGestureEvent(ui::ET_GESTURE_SCROLL_BEGIN, 5, 5);
widget->OnGestureEvent(&begin);
ui::GestureEvent update = CreateTestGestureEvent(
ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_UPDATE, 20, 10), 25, 15);
widget->OnGestureEvent(&update);
ui::GestureEvent end =
CreateTestGestureEvent(ui::ET_GESTURE_SCROLL_END, 25, 15);
widget->OnGestureEvent(&end);
EXPECT_EQ(1, noscroll_view->GetEventCount(ui::ET_GESTURE_SCROLL_BEGIN));
EXPECT_EQ(0, noscroll_view->GetEventCount(ui::ET_GESTURE_SCROLL_UPDATE));
EXPECT_EQ(0, noscroll_view->GetEventCount(ui::ET_GESTURE_SCROLL_END));
}
{
ui::GestureEvent begin =
CreateTestGestureEvent(ui::ET_GESTURE_SCROLL_BEGIN, 65, 5);
widget->OnGestureEvent(&begin);
ui::GestureEvent update = CreateTestGestureEvent(
ui::GestureEventDetails(ui::ET_GESTURE_SCROLL_UPDATE, 20, 10), 85, 15);
widget->OnGestureEvent(&update);
ui::GestureEvent end =
CreateTestGestureEvent(ui::ET_GESTURE_SCROLL_END, 85, 15);
widget->OnGestureEvent(&end);
EXPECT_EQ(1, scroll_view->GetEventCount(ui::ET_GESTURE_SCROLL_BEGIN));
EXPECT_EQ(1, scroll_view->GetEventCount(ui::ET_GESTURE_SCROLL_UPDATE));
EXPECT_EQ(1, scroll_view->GetEventCount(ui::ET_GESTURE_SCROLL_END));
}
}
// Tests that event-handlers installed on the RootView get triggered correctly.
// TODO(tdanderson): Clean up this test as part of crbug.com/355680.
TEST_F(WidgetTest, EventHandlersOnRootView) {
WidgetAutoclosePtr widget(CreateTopLevelNativeWidget());
View* root_view = widget->GetRootView();
EventCountView* view =
root_view->AddChildView(std::make_unique<EventCountView>());
view->SetBounds(0, 0, 20, 20);
EventCountHandler h1;
root_view->AddPreTargetHandler(&h1);
EventCountHandler h2;
root_view->AddPostTargetHandler(&h2);
widget->SetBounds(gfx::Rect(0, 0, 100, 100));
widget->Show();
// Dispatch a ui::ET_SCROLL event. The event remains unhandled and should
// bubble up the views hierarchy to be re-dispatched on the root view.
ui::ScrollEvent scroll(ui::ET_SCROLL, gfx::Point(5, 5), ui::EventTimeForNow(),
0, 0, 20, 0, 20, 2);
widget->OnScrollEvent(&scroll);
EXPECT_EQ(2, h1.GetEventCount(ui::ET_SCROLL));
EXPECT_EQ(1, view->GetEventCount(ui::ET_SCROLL));
EXPECT_EQ(2, h2.GetEventCount(ui::ET_SCROLL));
// Unhandled scroll events are turned into wheel events and re-dispatched.
EXPECT_EQ(1, h1.GetEventCount(ui::ET_MOUSEWHEEL));
EXPECT_EQ(1, view->GetEventCount(ui::ET_MOUSEWHEEL));
EXPECT_EQ(1, h2.GetEventCount(ui::ET_MOUSEWHEEL));
h1.ResetCounts();
view->ResetCounts();
h2.ResetCounts();
// Dispatch a ui::ET_SCROLL_FLING_START event. The event remains unhandled and
// should bubble up the views hierarchy to be re-dispatched on the root view.
ui::ScrollEvent fling(ui::ET_SCROLL_FLING_START, gfx::Point(5, 5),
ui::EventTimeForNow(), 0, 0, 20, 0, 20, 2);
widget->OnScrollEvent(&fling);
EXPECT_EQ(2, h1.GetEventCount(ui::ET_SCROLL_FLING_START));
EXPECT_EQ(1, view->GetEventCount(ui::ET_SCROLL_FLING_START));
EXPECT_EQ(2, h2.GetEventCount(ui::ET_SCROLL_FLING_START));
// Unhandled scroll events which are not of type ui::ET_SCROLL should not
// be turned into wheel events and re-dispatched.
EXPECT_EQ(0, h1.GetEventCount(ui::ET_MOUSEWHEEL));
EXPECT_EQ(0, view->GetEventCount(ui::ET_MOUSEWHEEL));
EXPECT_EQ(0, h2.GetEventCount(ui::ET_MOUSEWHEEL));
h1.ResetCounts();
view->ResetCounts();
h2.ResetCounts();
// Change the handle mode of |view| so that events are marked as handled at
// the target phase.
view->set_handle_mode(EventCountView::CONSUME_EVENTS);
// Dispatch a ui::ET_GESTURE_TAP_DOWN and a ui::ET_GESTURE_TAP_CANCEL event.
// The events are handled at the target phase and should not reach the
// post-target handler.
ui::GestureEvent tap_down =
CreateTestGestureEvent(ui::ET_GESTURE_TAP_DOWN, 5, 5);
widget->OnGestureEvent(&tap_down);
EXPECT_EQ(1, h1.GetEventCount(ui::ET_GESTURE_TAP_DOWN));
EXPECT_EQ(1, view->GetEventCount(ui::ET_GESTURE_TAP_DOWN));
EXPECT_EQ(0, h2.GetEventCount(ui::ET_GESTURE_TAP_DOWN));
ui::GestureEvent tap_cancel =
CreateTestGestureEvent(ui::ET_GESTURE_TAP_CANCEL, 5, 5);
widget->OnGestureEvent(&tap_cancel);
EXPECT_EQ(1, h1.GetEventCount(ui::ET_GESTURE_TAP_CANCEL));
EXPECT_EQ(1, view->GetEventCount(ui::ET_GESTURE_TAP_CANCEL));
EXPECT_EQ(0, h2.GetEventCount(ui::ET_GESTURE_TAP_CANCEL));
h1.ResetCounts();
view->ResetCounts();
h2.ResetCounts();
// Dispatch a ui::ET_SCROLL event. The event is handled at the target phase
// and should not reach the post-target handler.
ui::ScrollEvent consumed_scroll(ui::ET_SCROLL, gfx::Point(5, 5),
ui::EventTimeForNow(), 0, 0, 20, 0, 20, 2);
widget->OnScrollEvent(&consumed_scroll);
EXPECT_EQ(1, h1.GetEventCount(ui::ET_SCROLL));
EXPECT_EQ(1, view->GetEventCount(ui::ET_SCROLL));
EXPECT_EQ(0, h2.GetEventCount(ui::ET_SCROLL));
// Handled scroll events are not turned into wheel events and re-dispatched.
EXPECT_EQ(0, h1.GetEventCount(ui::ET_MOUSEWHEEL));
EXPECT_EQ(0, view->GetEventCount(ui::ET_MOUSEWHEEL));
EXPECT_EQ(0, h2.GetEventCount(ui::ET_MOUSEWHEEL));
root_view->RemovePreTargetHandler(&h1);
}
TEST_F(WidgetTest, SynthesizeMouseMoveEvent) {
WidgetAutoclosePtr widget(CreateTopLevelNativeWidget());
View* root_view = widget->GetRootView();
widget->SetBounds(gfx::Rect(0, 0, 100, 100));
EventCountView* v1 =
root_view->AddChildView(std::make_unique<EventCountView>());
v1->SetBounds(5, 5, 10, 10);
EventCountView* v2 =
root_view->AddChildView(std::make_unique<EventCountView>());
v2->SetBounds(5, 15, 10, 10);
widget->Show();
// SynthesizeMouseMoveEvent does nothing until the mouse is entered.
widget->SynthesizeMouseMoveEvent();
EXPECT_EQ(0, v1->GetEventCount(ui::ET_MOUSE_MOVED));
EXPECT_EQ(0, v2->GetEventCount(ui::ET_MOUSE_MOVED));
gfx::Point cursor_location(v1->GetBoundsInScreen().CenterPoint());
auto generator =
CreateEventGenerator(GetContext(), widget->GetNativeWindow());
generator->MoveMouseTo(cursor_location);
EXPECT_EQ(1, v1->GetEventCount(ui::ET_MOUSE_MOVED));
EXPECT_EQ(0, v2->GetEventCount(ui::ET_MOUSE_MOVED));
// SynthesizeMouseMoveEvent dispatches an mousemove event.
widget->SynthesizeMouseMoveEvent();
EXPECT_EQ(2, v1->GetEventCount(ui::ET_MOUSE_MOVED));
root_view->RemoveChildViewT(v1);
EXPECT_EQ(0, v2->GetEventCount(ui::ET_MOUSE_MOVED));
v2->SetBounds(5, 5, 10, 10);
EXPECT_EQ(0, v2->GetEventCount(ui::ET_MOUSE_MOVED));
widget->SynthesizeMouseMoveEvent();
EXPECT_EQ(1, v2->GetEventCount(ui::ET_MOUSE_MOVED));
}
namespace {
// ui::EventHandler which handles all mouse press events.
class MousePressEventConsumer : public ui::EventHandler {
public:
MousePressEventConsumer() = default;
MousePressEventConsumer(const MousePressEventConsumer&) = delete;
MousePressEventConsumer& operator=(const MousePressEventConsumer&) = delete;
private:
// ui::EventHandler:
void OnMouseEvent(ui::MouseEvent* event) override {
if (event->type() == ui::ET_MOUSE_PRESSED)
event->SetHandled();
}
};
} // namespace
// No touch on desktop Mac. Tracked in http://crbug.com/445520.
#if !BUILDFLAG(IS_MAC) || defined(USE_AURA)
// Test that mouse presses and mouse releases are dispatched normally when a
// touch is down.
TEST_F(WidgetTest, MouseEventDispatchWhileTouchIsDown) {
Widget* widget = CreateTopLevelNativeWidget();
widget->Show();
widget->SetSize(gfx::Size(300, 300));
EventCountView* event_count_view =
widget->GetRootView()->AddChildView(std::make_unique<EventCountView>());
event_count_view->SetBounds(0, 0, 300, 300);
MousePressEventConsumer consumer;
event_count_view->AddPostTargetHandler(&consumer);
auto generator =
CreateEventGenerator(GetContext(), widget->GetNativeWindow());
generator->PressTouch();
generator->ClickLeftButton();
EXPECT_EQ(1, event_count_view->GetEventCount(ui::ET_MOUSE_PRESSED));
EXPECT_EQ(1, event_count_view->GetEventCount(ui::ET_MOUSE_RELEASED));
// For mus it's important we destroy the widget before the EventGenerator.
widget->CloseNow();
}
#endif // !BUILDFLAG(IS_MAC) || defined(USE_AURA)
// Tests that when there is no active capture, that a mouse press causes capture
// to be set.
TEST_F(WidgetTest, MousePressCausesCapture) {
Widget* widget = CreateTopLevelNativeWidget();
widget->Show();
widget->SetSize(gfx::Size(300, 300));
EventCountView* event_count_view =
widget->GetRootView()->AddChildView(std::make_unique<EventCountView>());
event_count_view->SetBounds(0, 0, 300, 300);
// No capture has been set.
EXPECT_EQ(
gfx::kNullNativeView,
internal::NativeWidgetPrivate::GetGlobalCapture(widget->GetNativeView()));
MousePressEventConsumer consumer;
event_count_view->AddPostTargetHandler(&consumer);
auto generator =
CreateEventGenerator(GetContext(), widget->GetNativeWindow());
generator->MoveMouseTo(widget->GetClientAreaBoundsInScreen().CenterPoint());
generator->PressLeftButton();
EXPECT_EQ(1, event_count_view->GetEventCount(ui::ET_MOUSE_PRESSED));
EXPECT_EQ(
widget->GetNativeView(),
internal::NativeWidgetPrivate::GetGlobalCapture(widget->GetNativeView()));
// For mus it's important we destroy the widget before the EventGenerator.
widget->CloseNow();
}
namespace {
// An EventHandler which shows a Wiget upon receiving a mouse event. The Widget
// proceeds to take capture.
class CaptureEventConsumer : public ui::EventHandler {
public:
explicit CaptureEventConsumer(Widget* widget)
: event_count_view_(new EventCountView()), widget_(widget) {}
CaptureEventConsumer(const CaptureEventConsumer&) = delete;
CaptureEventConsumer& operator=(const CaptureEventConsumer&) = delete;
~CaptureEventConsumer() override { widget_->CloseNow(); }
private:
// ui::EventHandler:
void OnMouseEvent(ui::MouseEvent* event) override {
if (event->type() == ui::ET_MOUSE_PRESSED) {
event->SetHandled();
widget_->Show();
widget_->SetSize(gfx::Size(200, 200));
event_count_view_->SetBounds(0, 0, 200, 200);
widget_->GetRootView()->AddChildView(event_count_view_.get());
widget_->SetCapture(event_count_view_);
}
}
raw_ptr<EventCountView> event_count_view_;
raw_ptr<Widget> widget_;
};
} // namespace
// Tests that if explicit capture occurs during a mouse press, that implicit
// capture is not applied.
TEST_F(WidgetTest, CaptureDuringMousePressNotOverridden) {
Widget* widget = CreateTopLevelNativeWidget();
widget->Show();
widget->SetSize(gfx::Size(300, 300));
EventCountView* event_count_view =
widget->GetRootView()->AddChildView(std::make_unique<EventCountView>());
event_count_view->SetBounds(0, 0, 300, 300);
EXPECT_EQ(
gfx::kNullNativeView,
internal::NativeWidgetPrivate::GetGlobalCapture(widget->GetNativeView()));
Widget* widget2 = CreateTopLevelNativeWidget();
// Gives explicit capture to |widget2|
CaptureEventConsumer consumer(widget2);
event_count_view->AddPostTargetHandler(&consumer);
auto generator =
CreateEventGenerator(GetRootWindow(widget), widget->GetNativeWindow());
generator->MoveMouseTo(widget->GetClientAreaBoundsInScreen().CenterPoint());
// This event should implicitly give capture to |widget|, except that
// |consumer| will explicitly set capture on |widget2|.
generator->PressLeftButton();
EXPECT_EQ(1, event_count_view->GetEventCount(ui::ET_MOUSE_PRESSED));
EXPECT_NE(
widget->GetNativeView(),
internal::NativeWidgetPrivate::GetGlobalCapture(widget->GetNativeView()));
EXPECT_EQ(
widget2->GetNativeView(),
internal::NativeWidgetPrivate::GetGlobalCapture(widget->GetNativeView()));
// For mus it's important we destroy the widget before the EventGenerator.
widget->CloseNow();
}
class ClosingEventObserver : public ui::EventObserver {
public:
explicit ClosingEventObserver(Widget* widget) : widget_(widget) {}
ClosingEventObserver(const ClosingEventObserver&) = delete;
ClosingEventObserver& operator=(const ClosingEventObserver&) = delete;
// ui::EventObserver:
void OnEvent(const ui::Event& event) override {
// Guard against attempting to close the widget twice.
if (widget_)
widget_->CloseNow();
widget_ = nullptr;
}
private:
raw_ptr<Widget> widget_;
};
class ClosingView : public View {
public:
explicit ClosingView(Widget* widget) : widget_(widget) {}
ClosingView(const ClosingView&) = delete;
ClosingView& operator=(const ClosingView&) = delete;
// View:
void OnEvent(ui::Event* event) override {
// Guard against closing twice and writing to freed memory.
if (widget_ && event->type() == ui::ET_MOUSE_PRESSED) {
Widget* widget = widget_;
widget_ = nullptr;
widget->CloseNow();
}
}
private:
raw_ptr<Widget> widget_;
};
// Ensures that when multiple objects are intercepting OS-level events, that one
// can safely close a Widget that has capture.
TEST_F(WidgetTest, DestroyedWithCaptureViaEventMonitor) {
Widget* widget = CreateTopLevelNativeWidget();
TestWidgetObserver observer(widget);
widget->Show();
widget->SetSize(gfx::Size(300, 300));
// ClosingView and ClosingEventObserver both try to close the Widget. On Mac
// the order that EventMonitors receive OS events is not deterministic. If the
// one installed via SetCapture() sees it first, the event is swallowed (so
// both need to try). Note the regression test would only fail when the
// SetCapture() handler did _not_ swallow the event, but it still needs to try
// to close the Widget otherwise it will be left open, which fails elsewhere.
ClosingView* closing_view = widget->GetContentsView()->AddChildView(
std::make_unique<ClosingView>(widget));
widget->SetCapture(closing_view);
ClosingEventObserver closing_event_observer(widget);
auto monitor = EventMonitor::CreateApplicationMonitor(
&closing_event_observer, widget->GetNativeWindow(),
{ui::ET_MOUSE_PRESSED});
auto generator =
CreateEventGenerator(GetContext(), widget->GetNativeWindow());
generator->set_target(ui::test::EventGenerator::Target::APPLICATION);
EXPECT_FALSE(observer.widget_closed());
generator->PressLeftButton();
EXPECT_TRUE(observer.widget_closed());
}
TEST_F(WidgetTest, LockPaintAsActive) {
WidgetAutoclosePtr widget(CreateTopLevelPlatformWidget());
widget->ShowInactive();
EXPECT_FALSE(widget->ShouldPaintAsActive());
// First lock causes widget to paint as active.
auto lock = widget->LockPaintAsActive();
EXPECT_TRUE(widget->ShouldPaintAsActive());
// Second lock has no effect.
auto lock2 = widget->LockPaintAsActive();
EXPECT_TRUE(widget->ShouldPaintAsActive());
// Have to release twice to get back to inactive state.
lock2.reset();
EXPECT_TRUE(widget->ShouldPaintAsActive());
lock.reset();
EXPECT_FALSE(widget->ShouldPaintAsActive());
}
TEST_F(WidgetTest, LockPaintAsActive_AlreadyActive) {
WidgetAutoclosePtr widget(CreateTopLevelPlatformWidget());
widget->Show();
EXPECT_TRUE(widget->ShouldPaintAsActive());
// Lock has no effect.
auto lock = widget->LockPaintAsActive();
EXPECT_TRUE(widget->ShouldPaintAsActive());
// Remove lock has no effect.
lock.reset();
EXPECT_TRUE(widget->ShouldPaintAsActive());
}
TEST_F(WidgetTest, LockPaintAsActive_BecomesActive) {
WidgetAutoclosePtr widget(CreateTopLevelPlatformWidget());
widget->ShowInactive();
EXPECT_FALSE(widget->ShouldPaintAsActive());
// Lock toggles render mode.
auto lock = widget->LockPaintAsActive();
EXPECT_TRUE(widget->ShouldPaintAsActive());
widget->Activate();
// Remove lock has no effect.
lock.reset();
EXPECT_TRUE(widget->ShouldPaintAsActive());
}
class PaintAsActiveCallbackCounter {
public:
explicit PaintAsActiveCallbackCounter(Widget* widget) {
// Subscribe to |widget|'s paint-as-active change.
paint_as_active_subscription_ =
widget->RegisterPaintAsActiveChangedCallback(base::BindRepeating(
&PaintAsActiveCallbackCounter::Call, base::Unretained(this)));
}
void Call() { count_++; }
int CallCount() { return count_; }
private:
int count_ = 0;
base::CallbackListSubscription paint_as_active_subscription_;
};
TEST_F(WidgetTest, LockParentPaintAsActive) {
if (!PlatformStyle::kInactiveWidgetControlsAppearDisabled)
return;
WidgetAutoclosePtr parent(CreateTopLevelPlatformWidget());
WidgetAutoclosePtr child(CreateChildPlatformWidget(parent->GetNativeView()));
WidgetAutoclosePtr grandchild(
CreateChildPlatformWidget(child->GetNativeView()));
WidgetAutoclosePtr other(CreateTopLevelPlatformWidget());
child->widget_delegate()->SetCanActivate(true);
grandchild->widget_delegate()->SetCanActivate(true);
PaintAsActiveCallbackCounter parent_control(parent.get());
PaintAsActiveCallbackCounter child_control(child.get());
PaintAsActiveCallbackCounter grandchild_control(grandchild.get());
PaintAsActiveCallbackCounter other_control(other.get());
parent->Show();
EXPECT_TRUE(parent->ShouldPaintAsActive());
EXPECT_TRUE(child->ShouldPaintAsActive());
EXPECT_TRUE(grandchild->ShouldPaintAsActive());
EXPECT_FALSE(other->ShouldPaintAsActive());
EXPECT_EQ(parent_control.CallCount(), 1);
EXPECT_EQ(child_control.CallCount(), 1);
EXPECT_EQ(grandchild_control.CallCount(), 1);
EXPECT_EQ(other_control.CallCount(), 0);
other->Show();
EXPECT_FALSE(parent->ShouldPaintAsActive());
EXPECT_FALSE(child->ShouldPaintAsActive());
EXPECT_FALSE(grandchild->ShouldPaintAsActive());
EXPECT_TRUE(other->ShouldPaintAsActive());
EXPECT_EQ(parent_control.CallCount(), 2);
EXPECT_EQ(child_control.CallCount(), 2);
EXPECT_EQ(grandchild_control.CallCount(), 2);
EXPECT_EQ(other_control.CallCount(), 1);
child->Show();
EXPECT_TRUE(parent->ShouldPaintAsActive());
EXPECT_TRUE(child->ShouldPaintAsActive());
EXPECT_TRUE(grandchild->ShouldPaintAsActive());
EXPECT_FALSE(other->ShouldPaintAsActive());
EXPECT_EQ(parent_control.CallCount(), 3);
EXPECT_EQ(child_control.CallCount(), 3);
EXPECT_EQ(grandchild_control.CallCount(), 3);
EXPECT_EQ(other_control.CallCount(), 2);
other->Show();
EXPECT_FALSE(parent->ShouldPaintAsActive());
EXPECT_FALSE(child->ShouldPaintAsActive());
EXPECT_FALSE(grandchild->ShouldPaintAsActive());
EXPECT_TRUE(other->ShouldPaintAsActive());
EXPECT_EQ(parent_control.CallCount(), 4);
EXPECT_EQ(child_control.CallCount(), 4);
EXPECT_EQ(grandchild_control.CallCount(), 4);
EXPECT_EQ(other_control.CallCount(), 3);
grandchild->Show();
EXPECT_TRUE(parent->ShouldPaintAsActive());
EXPECT_TRUE(child->ShouldPaintAsActive());
EXPECT_TRUE(grandchild->ShouldPaintAsActive());
EXPECT_FALSE(other->ShouldPaintAsActive());
EXPECT_EQ(parent_control.CallCount(), 5);
EXPECT_EQ(child_control.CallCount(), 5);
EXPECT_EQ(grandchild_control.CallCount(), 5);
EXPECT_EQ(other_control.CallCount(), 4);
}
// Tests to make sure that child widgets do not cause their parent widget to
// paint inactive immediately when they are closed. This avoids having the
// parent paint as inactive in the time between when the bubble is closed and
// when it's eventually destroyed by its native widget (see crbug.com/1303549).
TEST_F(DesktopWidgetTest,
ClosingActiveChildDoesNotPrematurelyPaintParentInactive) {
// top_level_widget that owns the bubble widget.
auto top_level_widget = CreateTestWidget();
top_level_widget->Show();
// Create the child bubble widget.
auto bubble_widget = std::make_unique<Widget>();
Widget::InitParams init_params =
CreateParamsForTestWidget(Widget::InitParams::TYPE_BUBBLE);
init_params.parent = top_level_widget->GetNativeView();
bubble_widget->Init(std::move(init_params));
bubble_widget->Show();
EXPECT_TRUE(bubble_widget->ShouldPaintAsActive());
EXPECT_TRUE(top_level_widget->ShouldPaintAsActive());
// Closing the bubble wiget should not immediately cause the top level widget
// to paint inactive.
PaintAsActiveCallbackCounter top_level_counter(top_level_widget.get());
PaintAsActiveCallbackCounter bubble_counter(bubble_widget.get());
bubble_widget->Close();
EXPECT_FALSE(bubble_widget->ShouldPaintAsActive());
EXPECT_TRUE(top_level_widget->ShouldPaintAsActive());
EXPECT_EQ(top_level_counter.CallCount(), 0);
EXPECT_EQ(bubble_counter.CallCount(), 0);
}
// Widget used to destroy itself when OnNativeWidgetDestroyed is called.
class TestNativeWidgetDestroyedWidget : public Widget {
public:
// Overridden from NativeWidgetDelegate:
void OnNativeWidgetDestroyed() override;
};
void TestNativeWidgetDestroyedWidget::OnNativeWidgetDestroyed() {
Widget::OnNativeWidgetDestroyed();
delete this;
}
// Verifies that widget destroyed itself in OnNativeWidgetDestroyed does not
// crash in ASan.
TEST_F(DesktopWidgetTest, WidgetDestroyedItselfDoesNotCrash) {
TestDesktopWidgetDelegate delegate(new TestNativeWidgetDestroyedWidget);
delegate.InitWidget(CreateParamsForTestWidget());
delegate.GetWidget()->Show();
delegate.GetWidget()->CloseNow();
}
// Verifies WindowClosing() is invoked correctly on the delegate when a Widget
// is closed.
TEST_F(DesktopWidgetTest, SingleWindowClosing) {
TestDesktopWidgetDelegate delegate;
delegate.InitWidget(CreateParams(Widget::InitParams::TYPE_WINDOW));
EXPECT_EQ(0, delegate.window_closing_count());
delegate.GetWidget()->CloseNow();
EXPECT_EQ(1, delegate.window_closing_count());
}
TEST_F(DesktopWidgetTest, CloseRequested_AllowsClose) {
constexpr Widget::ClosedReason kReason = Widget::ClosedReason::kLostFocus;
TestDesktopWidgetDelegate delegate;
delegate.set_can_close(true);
delegate.InitWidget(CreateParams(Widget::InitParams::TYPE_WINDOW));
WidgetDestroyedWaiter waiter(delegate.GetWidget());
delegate.GetWidget()->CloseWithReason(kReason);
EXPECT_TRUE(delegate.GetWidget()->IsClosed());
EXPECT_EQ(kReason, delegate.GetWidget()->closed_reason());
EXPECT_EQ(kReason, delegate.last_closed_reason());
waiter.Wait();
}
TEST_F(DesktopWidgetTest, CloseRequested_DisallowClose) {
constexpr Widget::ClosedReason kReason = Widget::ClosedReason::kLostFocus;
TestDesktopWidgetDelegate delegate;
delegate.set_can_close(false);
delegate.InitWidget(CreateParams(Widget::InitParams::TYPE_WINDOW));
delegate.GetWidget()->CloseWithReason(kReason);
EXPECT_FALSE(delegate.GetWidget()->IsClosed());
EXPECT_EQ(Widget::ClosedReason::kUnspecified,
delegate.GetWidget()->closed_reason());
EXPECT_EQ(kReason, delegate.last_closed_reason());
delegate.GetWidget()->CloseNow();
}
TEST_F(DesktopWidgetTest, CloseRequested_SecondCloseIgnored) {
constexpr Widget::ClosedReason kReason1 = Widget::ClosedReason::kLostFocus;
constexpr Widget::ClosedReason kReason2 = Widget::ClosedReason::kUnspecified;
TestDesktopWidgetDelegate delegate;
delegate.set_can_close(true);
delegate.InitWidget(CreateParams(Widget::InitParams::TYPE_WINDOW));
WidgetDestroyedWaiter waiter(delegate.GetWidget());
// Close for the first time.
delegate.GetWidget()->CloseWithReason(kReason1);
EXPECT_TRUE(delegate.GetWidget()->IsClosed());
EXPECT_EQ(kReason1, delegate.last_closed_reason());
// Calling close again should have no effect.
delegate.GetWidget()->CloseWithReason(kReason2);
EXPECT_TRUE(delegate.GetWidget()->IsClosed());
EXPECT_EQ(kReason1, delegate.last_closed_reason());
waiter.Wait();
}
class WidgetWindowTitleTest : public DesktopWidgetTest {
protected:
void RunTest(bool desktop_native_widget) {
WidgetAutoclosePtr widget(new Widget()); // Destroyed by CloseNow().
Widget::InitParams init_params =
CreateParams(Widget::InitParams::TYPE_WINDOW);
if (!desktop_native_widget) {
init_params.native_widget =
CreatePlatformNativeWidgetImpl(widget.get(), kStubCapture, nullptr);
}
widget->Init(std::move(init_params));
internal::NativeWidgetPrivate* native_widget =
widget->native_widget_private();
std::u16string empty;
std::u16string s1(u"Title1");
std::u16string s2(u"Title2");
std::u16string s3(u"TitleLong");
// The widget starts with no title, setting empty should not change
// anything.
EXPECT_FALSE(native_widget->SetWindowTitle(empty));
// Setting the title to something non-empty should cause a change.
EXPECT_TRUE(native_widget->SetWindowTitle(s1));
// Setting the title to something else with the same length should cause a
// change.
EXPECT_TRUE(native_widget->SetWindowTitle(s2));
// Setting the title to something else with a different length should cause
// a change.
EXPECT_TRUE(native_widget->SetWindowTitle(s3));
// Setting the title to the same thing twice should not cause a change.
EXPECT_FALSE(native_widget->SetWindowTitle(s3));
}
};
TEST_F(WidgetWindowTitleTest, SetWindowTitleChanged_NativeWidget) {
// Use the default NativeWidget.
bool desktop_native_widget = false;
RunTest(desktop_native_widget);
}
TEST_F(WidgetWindowTitleTest, SetWindowTitleChanged_DesktopNativeWidget) {
// Override to use a DesktopNativeWidget.
bool desktop_native_widget = true;
RunTest(desktop_native_widget);
}
TEST_F(WidgetTest, WidgetDeleted_InOnMousePressed) {
Widget* widget = new Widget;
Widget::InitParams params =
CreateParams(views::Widget::InitParams::TYPE_POPUP);
widget->Init(std::move(params));
widget->SetContentsView(
std::make_unique<CloseWidgetView>(ui::ET_MOUSE_PRESSED));
widget->SetSize(gfx::Size(100, 100));
widget->Show();
auto generator =
CreateEventGenerator(GetContext(), widget->GetNativeWindow());
WidgetDeletionObserver deletion_observer(widget);
generator->PressLeftButton();
if (deletion_observer.IsWidgetAlive())
generator->ReleaseLeftButton();
EXPECT_FALSE(deletion_observer.IsWidgetAlive());
// Yay we did not crash!
}
// No touch on desktop Mac. Tracked in http://crbug.com/445520.
#if !BUILDFLAG(IS_MAC) || defined(USE_AURA)
TEST_F(WidgetTest, WidgetDeleted_InDispatchGestureEvent) {
Widget* widget = new Widget;
Widget::InitParams params =
CreateParams(views::Widget::InitParams::TYPE_POPUP);
widget->Init(std::move(params));
widget->SetContentsView(
std::make_unique<CloseWidgetView>(ui::ET_GESTURE_TAP_DOWN));
widget->SetSize(gfx::Size(100, 100));
widget->Show();
auto generator =
CreateEventGenerator(GetContext(), widget->GetNativeWindow());
WidgetDeletionObserver deletion_observer(widget);
generator->GestureTapAt(widget->GetWindowBoundsInScreen().CenterPoint());
EXPECT_FALSE(deletion_observer.IsWidgetAlive());
// Yay we did not crash!
}
#endif // !BUILDFLAG(IS_MAC) || defined(USE_AURA)
// See description of RunGetNativeThemeFromDestructor() for details.
class GetNativeThemeFromDestructorView : public WidgetDelegateView {
public:
GetNativeThemeFromDestructorView() = default;
GetNativeThemeFromDestructorView(const GetNativeThemeFromDestructorView&) =
delete;
GetNativeThemeFromDestructorView& operator=(
const GetNativeThemeFromDestructorView&) = delete;
~GetNativeThemeFromDestructorView() override { VerifyNativeTheme(); }
private:
void VerifyNativeTheme() { ASSERT_TRUE(GetNativeTheme() != nullptr); }
};
// Verifies GetNativeTheme() from the destructor of a WidgetDelegateView doesn't
// crash. |is_first_run| is true if this is the first call. A return value of
// true indicates this should be run again with a value of false.
// First run uses DesktopNativeWidgetAura (if possible). Second run doesn't.
bool RunGetNativeThemeFromDestructor(Widget::InitParams params,
bool is_first_run) {
bool needs_second_run = false;
// Destroyed by CloseNow() below.
WidgetTest::WidgetAutoclosePtr widget(new Widget);
// Deletes itself when the Widget is destroyed.
params.delegate = new GetNativeThemeFromDestructorView;
if (!is_first_run) {
params.native_widget =
CreatePlatformNativeWidgetImpl(widget.get(), kStubCapture, nullptr);
needs_second_run = true;
}
widget->Init(std::move(params));
return needs_second_run;
}
// See description of RunGetNativeThemeFromDestructor() for details.
TEST_F(DesktopWidgetTest, GetNativeThemeFromDestructor) {
if (RunGetNativeThemeFromDestructor(
CreateParams(Widget::InitParams::TYPE_POPUP), true)) {
RunGetNativeThemeFromDestructor(
CreateParams(Widget::InitParams::TYPE_POPUP), false);
}
}
// Used by HideCloseDestroy. Allows setting a boolean when the widget is
// destroyed.
class CloseDestroysWidget : public Widget {
public:
CloseDestroysWidget(bool* destroyed, base::OnceClosure quit_closure)
: destroyed_(destroyed), quit_closure_(std::move(quit_closure)) {
DCHECK(destroyed_);
DCHECK(quit_closure_);
}
CloseDestroysWidget(const CloseDestroysWidget&) = delete;
CloseDestroysWidget& operator=(const CloseDestroysWidget&) = delete;
~CloseDestroysWidget() override {
*destroyed_ = true;
std::move(quit_closure_).Run();
}
void Detach() { destroyed_ = nullptr; }
private:
raw_ptr<bool> destroyed_;
base::OnceClosure quit_closure_;
};
// An observer that registers that an animation has ended.
class AnimationEndObserver : public ui::ImplicitAnimationObserver {
public:
AnimationEndObserver() = default;
AnimationEndObserver(const AnimationEndObserver&) = delete;
AnimationEndObserver& operator=(const AnimationEndObserver&) = delete;
~AnimationEndObserver() override = default;
bool animation_completed() const { return animation_completed_; }
// ui::ImplicitAnimationObserver:
void OnImplicitAnimationsCompleted() override { animation_completed_ = true; }
private:
bool animation_completed_ = false;
};
// An observer that registers the bounds of a widget on destruction.
class WidgetBoundsObserver : public WidgetObserver {
public:
WidgetBoundsObserver() = default;
WidgetBoundsObserver(const WidgetBoundsObserver&) = delete;
WidgetBoundsObserver& operator=(const WidgetBoundsObserver&) = delete;
~WidgetBoundsObserver() override = default;
gfx::Rect bounds() { return bounds_; }
// WidgetObserver:
void OnWidgetDestroying(Widget* widget) override {
EXPECT_TRUE(widget->GetNativeWindow());
EXPECT_TRUE(Widget::GetWidgetForNativeWindow(widget->GetNativeWindow()));
bounds_ = widget->GetWindowBoundsInScreen();
}
private:
gfx::Rect bounds_;
};
// Verifies Close() results in destroying.
TEST_F(DesktopWidgetTest, CloseDestroys) {
bool destroyed = false;
base::RunLoop run_loop;
CloseDestroysWidget* widget =
new CloseDestroysWidget(&destroyed, run_loop.QuitClosure());
Widget::InitParams params =
CreateParams(views::Widget::InitParams::TYPE_MENU);
params.opacity = Widget::InitParams::WindowOpacity::kOpaque;
params.bounds = gfx::Rect(50, 50, 250, 250);
widget->Init(std::move(params));
widget->Show();
widget->Hide();
widget->Close();
EXPECT_FALSE(destroyed);
// Run the message loop as Close() asynchronously deletes.
run_loop.Run();
EXPECT_TRUE(destroyed);
// Close() should destroy the widget. If not we'll cleanup to avoid leaks.
if (!destroyed) {
widget->Detach();
widget->CloseNow();
}
}
// Tests that killing a widget while animating it does not crash.
TEST_F(WidgetTest, CloseWidgetWhileAnimating) {
std::unique_ptr<Widget> widget = CreateTestWidget();
AnimationEndObserver animation_observer;
WidgetBoundsObserver widget_observer;
gfx::Rect bounds(100, 100, 50, 50);
{
// Normal animations for tests have ZERO_DURATION, make sure we are actually
// animating the movement.
ui::ScopedAnimationDurationScaleMode animation_scale_mode(
ui::ScopedAnimationDurationScaleMode::NON_ZERO_DURATION);
ui::ScopedLayerAnimationSettings animation_settings(
widget->GetLayer()->GetAnimator());
animation_settings.AddObserver(&animation_observer);
widget->AddObserver(&widget_observer);
widget->Show();
// Animate the bounds change.
widget->SetBounds(bounds);
widget.reset();
EXPECT_FALSE(animation_observer.animation_completed());
}
EXPECT_TRUE(animation_observer.animation_completed());
EXPECT_EQ(widget_observer.bounds(), bounds);
}
// Test Widget::CloseAllSecondaryWidgets works as expected across platforms.
// ChromeOS doesn't implement or need CloseAllSecondaryWidgets() since
// everything is under a single root window.
#if BUILDFLAG(ENABLE_DESKTOP_AURA) || BUILDFLAG(IS_MAC)
TEST_F(DesktopWidgetTest, CloseAllSecondaryWidgets) {
Widget* widget1 = CreateTopLevelNativeWidget();
Widget* widget2 = CreateTopLevelNativeWidget();
TestWidgetObserver observer1(widget1);
TestWidgetObserver observer2(widget2);
widget1->Show(); // Just show the first one.
Widget::CloseAllSecondaryWidgets();
EXPECT_TRUE(observer1.widget_closed());
EXPECT_TRUE(observer2.widget_closed());
}
#endif
// Test that the NativeWidget is still valid during OnNativeWidgetDestroying(),
// and properties that depend on it are valid, when closed via CloseNow().
TEST_F(DesktopWidgetTest, ValidDuringOnNativeWidgetDestroyingFromCloseNow) {
Widget* widget = CreateTopLevelNativeWidget();
widget->Show();
gfx::Rect screen_rect(50, 50, 100, 100);
widget->SetBounds(screen_rect);
WidgetBoundsObserver observer;
widget->AddObserver(&observer);
widget->CloseNow();
EXPECT_EQ(screen_rect, observer.bounds());
}
// Test that the NativeWidget is still valid during OnNativeWidgetDestroying(),
// and properties that depend on it are valid, when closed via Close().
TEST_F(DesktopWidgetTest, ValidDuringOnNativeWidgetDestroyingFromClose) {
Widget* widget = CreateTopLevelNativeWidget();
widget->Show();
gfx::Rect screen_rect(50, 50, 100, 100);
widget->SetBounds(screen_rect);
WidgetBoundsObserver observer;
widget->AddObserver(&observer);
widget->Close();
EXPECT_EQ(gfx::Rect(), observer.bounds());
base::RunLoop().RunUntilIdle();
// Broken on Linux. See http://crbug.com/515379.
// TODO(crbug.com/1052397): Revisit the macro expression once build flag switch
// of lacros-chrome is complete.
#if !(BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS))
EXPECT_EQ(screen_rect, observer.bounds());
#endif
}
// Tests that we do not crash when a Widget is destroyed by going out of
// scope (as opposed to being explicitly deleted by its NativeWidget).
TEST_F(WidgetTest, NoCrashOnWidgetDelete) {
CreateTestWidget();
}
TEST_F(WidgetTest, NoCrashOnResizeConstraintsWindowTitleOnPopup) {
CreateTestWidget(Widget::InitParams::TYPE_POPUP)->OnSizeConstraintsChanged();
}
// Tests that we do not crash when a Widget is destroyed before it finishes
// processing of pending input events in the message loop.
TEST_F(WidgetTest, NoCrashOnWidgetDeleteWithPendingEvents) {
std::unique_ptr<Widget> widget = CreateTestWidget();
widget->Show();
auto generator =
CreateEventGenerator(GetContext(), widget->GetNativeWindow());
generator->MoveMouseTo(10, 10);
// No touch on desktop Mac. Tracked in http://crbug.com/445520.
#if BUILDFLAG(IS_MAC)
generator->ClickLeftButton();
#else
generator->PressTouch();
#endif
widget.reset();
}
// A view that consumes mouse-pressed event and gesture-tap-down events.
class RootViewTestView : public View {
public:
RootViewTestView() = default;
private:
bool OnMousePressed(const ui::MouseEvent& event) override { return true; }
void OnGestureEvent(ui::GestureEvent* event) override {
if (event->type() == ui::ET_GESTURE_TAP_DOWN)
event->SetHandled();
}
};
// Checks if RootView::*_handler_ fields are unset when widget is hidden.
// Fails on chromium.webkit Windows bot, see crbug.com/264872.
#if BUILDFLAG(IS_WIN)
#define MAYBE_DisableTestRootViewHandlersWhenHidden \
DISABLED_TestRootViewHandlersWhenHidden
#else
#define MAYBE_DisableTestRootViewHandlersWhenHidden \
TestRootViewHandlersWhenHidden
#endif
TEST_F(WidgetTest, MAYBE_DisableTestRootViewHandlersWhenHidden) {
Widget* widget = CreateTopLevelNativeWidget();
widget->SetBounds(gfx::Rect(0, 0, 300, 300));
View* view = new RootViewTestView();
view->SetBounds(0, 0, 300, 300);
internal::RootView* root_view =
static_cast<internal::RootView*>(widget->GetRootView());
root_view->AddChildView(view);
// Check RootView::mouse_pressed_handler_.
widget->Show();
EXPECT_EQ(nullptr, GetMousePressedHandler(root_view));
gfx::Point click_location(45, 15);
ui::MouseEvent press(ui::ET_MOUSE_PRESSED, click_location, click_location,
ui::EventTimeForNow(), ui::EF_LEFT_MOUSE_BUTTON,
ui::EF_LEFT_MOUSE_BUTTON);
widget->OnMouseEvent(&press);
EXPECT_EQ(view, GetMousePressedHandler(root_view));
widget->Hide();
EXPECT_EQ(nullptr, GetMousePressedHandler(root_view));
// Check RootView::mouse_move_handler_.
widget->Show();
EXPECT_EQ(nullptr, GetMouseMoveHandler(root_view));
gfx::Point move_location(45, 15);
ui::MouseEvent move(ui::ET_MOUSE_MOVED, move_location, move_location,
ui::EventTimeForNow(), 0, 0);
widget->OnMouseEvent(&move);
EXPECT_EQ(view, GetMouseMoveHandler(root_view));
widget->Hide();
EXPECT_EQ(nullptr, GetMouseMoveHandler(root_view));
// Check RootView::gesture_handler_.
widget->Show();
EXPECT_EQ(nullptr, GetGestureHandler(root_view));
ui::GestureEvent tap_down =
CreateTestGestureEvent(ui::ET_GESTURE_TAP_DOWN, 15, 15);
widget->OnGestureEvent(&tap_down);
EXPECT_EQ(view, GetGestureHandler(root_view));
widget->Hide();
EXPECT_EQ(nullptr, GetGestureHandler(root_view));
widget->Close();
}
// Tests that the |gesture_handler_| member in RootView is always NULL
// after the dispatch of a ui::ET_GESTURE_END event corresponding to
// the release of the final touch point on the screen, but that
// ui::ET_GESTURE_END events corresponding to the removal of any other touch
// point do not modify |gesture_handler_|.
TEST_F(WidgetTest, GestureEndEvents) {
Widget* widget = CreateTopLevelNativeWidget();
widget->SetBounds(gfx::Rect(0, 0, 300, 300));
EventCountView* view = new EventCountView();
view->SetBounds(0, 0, 300, 300);
internal::RootView* root_view =
static_cast<internal::RootView*>(widget->GetRootView());
root_view->AddChildView(view);
widget->Show();
// If no gesture handler is set, a ui::ET_GESTURE_END event should not set
// the gesture handler.
EXPECT_EQ(nullptr, GetGestureHandler(root_view));
ui::GestureEvent end = CreateTestGestureEvent(ui::ET_GESTURE_END, 15, 15);
widget->OnGestureEvent(&end);
EXPECT_EQ(nullptr, GetGestureHandler(root_view));
// Change the handle mode of |view| to indicate that it would like
// to handle all events, then send a GESTURE_TAP to set the gesture handler.
view->set_handle_mode(EventCountView::CONSUME_EVENTS);
ui::GestureEvent tap = CreateTestGestureEvent(ui::ET_GESTURE_TAP, 15, 15);
widget->OnGestureEvent(&tap);
EXPECT_TRUE(tap.handled());
EXPECT_EQ(view, GetGestureHandler(root_view));
// The gesture handler should remain unchanged on a ui::ET_GESTURE_END
// corresponding to a second touch point, but should be reset to NULL by a
// ui::ET_GESTURE_END corresponding to the final touch point.
ui::GestureEventDetails details(ui::ET_GESTURE_END);
details.set_touch_points(2);
ui::GestureEvent end_second_touch_point =
CreateTestGestureEvent(details, 15, 15);
widget->OnGestureEvent(&end_second_touch_point);
EXPECT_EQ(view, GetGestureHandler(root_view));
end = CreateTestGestureEvent(ui::ET_GESTURE_END, 15, 15);
widget->OnGestureEvent(&end);
EXPECT_TRUE(end.handled());
EXPECT_EQ(nullptr, GetGestureHandler(root_view));
// Send a GESTURE_TAP to set the gesture handler, then change the handle
// mode of |view| to indicate that it does not want to handle any
// further events.
tap = CreateTestGestureEvent(ui::ET_GESTURE_TAP, 15, 15);
widget->OnGestureEvent(&tap);
EXPECT_TRUE(tap.handled());
EXPECT_EQ(view, GetGestureHandler(root_view));
view->set_handle_mode(EventCountView::PROPAGATE_EVENTS);
// The gesture handler should remain unchanged on a ui::ET_GESTURE_END
// corresponding to a second touch point, but should be reset to NULL by a
// ui::ET_GESTURE_END corresponding to the final touch point.
end_second_touch_point = CreateTestGestureEvent(details, 15, 15);
widget->OnGestureEvent(&end_second_touch_point);
EXPECT_EQ(view, GetGestureHandler(root_view));
end = CreateTestGestureEvent(ui::ET_GESTURE_END, 15, 15);
widget->OnGestureEvent(&end);
EXPECT_FALSE(end.handled());
EXPECT_EQ(nullptr, GetGestureHandler(root_view));
widget->Close();
}
// Tests that gesture events which should not be processed (because
// RootView::OnEventProcessingStarted() has marked them as handled) are not
// dispatched to any views.
TEST_F(WidgetTest, GestureEventsNotProcessed) {
Widget* widget = CreateTopLevelNativeWidget();
widget->SetBounds(gfx::Rect(0, 0, 300, 300));
// Define a hierarchy of four views (coordinates are in
// their parent coordinate space).
// v1 (0, 0, 300, 300)
// v2 (0, 0, 100, 100)
// v3 (0, 0, 50, 50)
// v4(0, 0, 10, 10)
EventCountView* v1 = new EventCountView();
v1->SetBounds(0, 0, 300, 300);
EventCountView* v2 = new EventCountView();
v2->SetBounds(0, 0, 100, 100);
EventCountView* v3 = new EventCountView();
v3->SetBounds(0, 0, 50, 50);
EventCountView* v4 = new EventCountView();
v4->SetBounds(0, 0, 10, 10);
internal::RootView* root_view =
static_cast<internal::RootView*>(widget->GetRootView());
root_view->AddChildView(v1);
v1->AddChildView(v2);
v2->AddChildView(v3);
v3->AddChildView(v4);
widget->Show();
// ui::ET_GESTURE_BEGIN events should never be seen by any view, but
// they should be marked as handled by OnEventProcessingStarted().
ui::GestureEvent begin = CreateTestGestureEvent(ui::ET_GESTURE_BEGIN, 5, 5);
widget->OnGestureEvent(&begin);
EXPECT_EQ(0, v1->GetEventCount(ui::ET_GESTURE_BEGIN));
EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_BEGIN));
EXPECT_EQ(0, v3->GetEventCount(ui::ET_GESTURE_BEGIN));
EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_BEGIN));
EXPECT_EQ(nullptr, GetGestureHandler(root_view));
EXPECT_TRUE(begin.handled());
v1->ResetCounts();
v2->ResetCounts();
v3->ResetCounts();
v4->ResetCounts();
// ui::ET_GESTURE_END events should not be seen by any view when there is
// no default gesture handler set, but they should be marked as handled by
// OnEventProcessingStarted().
ui::GestureEvent end = CreateTestGestureEvent(ui::ET_GESTURE_END, 5, 5);
widget->OnGestureEvent(&end);
EXPECT_EQ(0, v1->GetEventCount(ui::ET_GESTURE_END));
EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_END));
EXPECT_EQ(0, v3->GetEventCount(ui::ET_GESTURE_END));
EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_END));
EXPECT_EQ(nullptr, GetGestureHandler(root_view));
EXPECT_TRUE(end.handled());
v1->ResetCounts();
v2->ResetCounts();
v3->ResetCounts();
v4->ResetCounts();
// ui::ET_GESTURE_END events not corresponding to the release of the
// final touch point should never be seen by any view, but they should
// be marked as handled by OnEventProcessingStarted().
ui::GestureEventDetails details(ui::ET_GESTURE_END);
details.set_touch_points(2);
ui::GestureEvent end_second_touch_point =
CreateTestGestureEvent(details, 5, 5);
widget->OnGestureEvent(&end_second_touch_point);
EXPECT_EQ(0, v1->GetEventCount(ui::ET_GESTURE_END));
EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_END));
EXPECT_EQ(0, v3->GetEventCount(ui::ET_GESTURE_END));
EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_END));
EXPECT_EQ(nullptr, GetGestureHandler(root_view));
EXPECT_TRUE(end_second_touch_point.handled());
v1->ResetCounts();
v2->ResetCounts();
v3->ResetCounts();
v4->ResetCounts();
// ui::ET_GESTURE_SCROLL_UPDATE events should never be seen by any view when
// there is no default gesture handler set, but they should be marked as
// handled by OnEventProcessingStarted().
ui::GestureEvent scroll_update =
CreateTestGestureEvent(ui::ET_GESTURE_SCROLL_UPDATE, 5, 5);
widget->OnGestureEvent(&scroll_update);
EXPECT_EQ(0, v1->GetEventCount(ui::ET_GESTURE_SCROLL_UPDATE));
EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_SCROLL_UPDATE));
EXPECT_EQ(0, v3->GetEventCount(ui::ET_GESTURE_SCROLL_UPDATE));
EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_SCROLL_UPDATE));
EXPECT_EQ(nullptr, GetGestureHandler(root_view));
EXPECT_TRUE(scroll_update.handled());
v1->ResetCounts();
v2->ResetCounts();
v3->ResetCounts();
v4->ResetCounts();
// ui::ET_GESTURE_SCROLL_END events should never be seen by any view when
// there is no default gesture handler set, but they should be marked as
// handled by OnEventProcessingStarted().
ui::GestureEvent scroll_end =
CreateTestGestureEvent(ui::ET_GESTURE_SCROLL_END, 5, 5);
widget->OnGestureEvent(&scroll_end);
EXPECT_EQ(0, v1->GetEventCount(ui::ET_GESTURE_SCROLL_END));
EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_SCROLL_END));
EXPECT_EQ(0, v3->GetEventCount(ui::ET_GESTURE_SCROLL_END));
EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_SCROLL_END));
EXPECT_EQ(nullptr, GetGestureHandler(root_view));
EXPECT_TRUE(scroll_end.handled());
v1->ResetCounts();
v2->ResetCounts();
v3->ResetCounts();
v4->ResetCounts();
// ui::ET_SCROLL_FLING_START events should never be seen by any view when
// there is no default gesture handler set, but they should be marked as
// handled by OnEventProcessingStarted().
ui::GestureEvent scroll_fling_start =
CreateTestGestureEvent(ui::ET_SCROLL_FLING_START, 5, 5);
widget->OnGestureEvent(&scroll_fling_start);
EXPECT_EQ(0, v1->GetEventCount(ui::ET_SCROLL_FLING_START));
EXPECT_EQ(0, v2->GetEventCount(ui::ET_SCROLL_FLING_START));
EXPECT_EQ(0, v3->GetEventCount(ui::ET_SCROLL_FLING_START));
EXPECT_EQ(0, v4->GetEventCount(ui::ET_SCROLL_FLING_START));
EXPECT_EQ(nullptr, GetGestureHandler(root_view));
EXPECT_TRUE(scroll_fling_start.handled());
v1->ResetCounts();
v2->ResetCounts();
v3->ResetCounts();
v4->ResetCounts();
widget->Close();
}
// Tests that a (non-scroll) gesture event is dispatched to the correct views
// in a view hierarchy and that the default gesture handler in RootView is set
// correctly.
TEST_F(WidgetTest, GestureEventDispatch) {
Widget* widget = CreateTopLevelNativeWidget();
widget->SetBounds(gfx::Rect(0, 0, 300, 300));
// Define a hierarchy of four views (coordinates are in
// their parent coordinate space).
// v1 (0, 0, 300, 300)
// v2 (0, 0, 100, 100)
// v3 (0, 0, 50, 50)
// v4(0, 0, 10, 10)
EventCountView* v1 = new EventCountView();
v1->SetBounds(0, 0, 300, 300);
EventCountView* v2 = new EventCountView();
v2->SetBounds(0, 0, 100, 100);
EventCountView* v3 = new EventCountView();
v3->SetBounds(0, 0, 50, 50);
EventCountView* v4 = new EventCountView();
v4->SetBounds(0, 0, 10, 10);
internal::RootView* root_view =
static_cast<internal::RootView*>(widget->GetRootView());
root_view->AddChildView(v1);
v1->AddChildView(v2);
v2->AddChildView(v3);
v3->AddChildView(v4);
widget->Show();
// No gesture handler is set in the root view and none of the views in the
// view hierarchy handle a ui::ET_GESTURE_TAP event. In this case the tap
// event should be dispatched to all views in the hierarchy, the gesture
// handler should remain unset, and the event should remain unhandled.
ui::GestureEvent tap = CreateTestGestureEvent(ui::ET_GESTURE_TAP, 5, 5);
EXPECT_EQ(nullptr, GetGestureHandler(root_view));
widget->OnGestureEvent(&tap);
EXPECT_EQ(1, v1->GetEventCount(ui::ET_GESTURE_TAP));
EXPECT_EQ(1, v2->GetEventCount(ui::ET_GESTURE_TAP));
EXPECT_EQ(1, v3->GetEventCount(ui::ET_GESTURE_TAP));
EXPECT_EQ(1, v4->GetEventCount(ui::ET_GESTURE_TAP));
EXPECT_EQ(nullptr, GetGestureHandler(root_view));
EXPECT_FALSE(tap.handled());
// No gesture handler is set in the root view and |v1|, |v2|, and |v3| all
// handle a ui::ET_GESTURE_TAP event. In this case the tap event should be
// dispatched to |v4| and |v3|, the gesture handler should be set to |v3|,
// and the event should be marked as handled.
v1->ResetCounts();
v2->ResetCounts();
v3->ResetCounts();
v4->ResetCounts();
v1->set_handle_mode(EventCountView::CONSUME_EVENTS);
v2->set_handle_mode(EventCountView::CONSUME_EVENTS);
v3->set_handle_mode(EventCountView::CONSUME_EVENTS);
tap = CreateTestGestureEvent(ui::ET_GESTURE_TAP, 5, 5);
widget->OnGestureEvent(&tap);
EXPECT_EQ(0, v1->GetEventCount(ui::ET_GESTURE_TAP));
EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_TAP));
EXPECT_EQ(1, v3->GetEventCount(ui::ET_GESTURE_TAP));
EXPECT_EQ(1, v4->GetEventCount(ui::ET_GESTURE_TAP));
EXPECT_EQ(v3, GetGestureHandler(root_view));
EXPECT_TRUE(tap.handled());
// The gesture handler is set to |v3| and all views handle all gesture event
// types. In this case subsequent gesture events should only be dispatched to
// |v3| and marked as handled. The gesture handler should remain as |v3|.
v1->ResetCounts();
v2->ResetCounts();
v3->ResetCounts();
v4->ResetCounts();
v4->set_handle_mode(EventCountView::CONSUME_EVENTS);
tap = CreateTestGestureEvent(ui::ET_GESTURE_TAP, 5, 5);
widget->OnGestureEvent(&tap);
EXPECT_TRUE(tap.handled());
ui::GestureEvent show_press =
CreateTestGestureEvent(ui::ET_GESTURE_SHOW_PRESS, 5, 5);
widget->OnGestureEvent(&show_press);
tap = CreateTestGestureEvent(ui::ET_GESTURE_TAP, 5, 5);
widget->OnGestureEvent(&tap);
EXPECT_EQ(0, v1->GetEventCount(ui::ET_GESTURE_TAP));
EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_TAP));
EXPECT_EQ(2, v3->GetEventCount(ui::ET_GESTURE_TAP));
EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_TAP));
EXPECT_EQ(0, v1->GetEventCount(ui::ET_GESTURE_SHOW_PRESS));
EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_SHOW_PRESS));
EXPECT_EQ(1, v3->GetEventCount(ui::ET_GESTURE_SHOW_PRESS));
EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_SHOW_PRESS));
EXPECT_TRUE(tap.handled());
EXPECT_TRUE(show_press.handled());
EXPECT_EQ(v3, GetGestureHandler(root_view));
// The gesture handler is set to |v3|, but |v3| does not handle
// ui::ET_GESTURE_TAP events. In this case a tap gesture should be dispatched
// only to |v3|, but the event should remain unhandled. The gesture handler
// should remain as |v3|.
v1->ResetCounts();
v2->ResetCounts();
v3->ResetCounts();
v4->ResetCounts();
v3->set_handle_mode(EventCountView::PROPAGATE_EVENTS);
tap = CreateTestGestureEvent(ui::ET_GESTURE_TAP, 5, 5);
widget->OnGestureEvent(&tap);
EXPECT_EQ(0, v1->GetEventCount(ui::ET_GESTURE_TAP));
EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_TAP));
EXPECT_EQ(1, v3->GetEventCount(ui::ET_GESTURE_TAP));
EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_TAP));
EXPECT_FALSE(tap.handled());
EXPECT_EQ(v3, GetGestureHandler(root_view));
widget->Close();
}
// Tests that gesture scroll events will change the default gesture handler in
// RootView if the current handler to which they are dispatched does not handle
// gesture scroll events.
TEST_F(WidgetTest, ScrollGestureEventDispatch) {
Widget* widget = CreateTopLevelNativeWidget();
widget->SetBounds(gfx::Rect(0, 0, 300, 300));
// Define a hierarchy of four views (coordinates are in
// their parent coordinate space).
// v1 (0, 0, 300, 300)
// v2 (0, 0, 100, 100)
// v3 (0, 0, 50, 50)
// v4(0, 0, 10, 10)
EventCountView* v1 = new EventCountView();
v1->SetBounds(0, 0, 300, 300);
EventCountView* v2 = new EventCountView();
v2->SetBounds(0, 0, 100, 100);
EventCountView* v3 = new EventCountView();
v3->SetBounds(0, 0, 50, 50);
EventCountView* v4 = new EventCountView();
v4->SetBounds(0, 0, 10, 10);
internal::RootView* root_view =
static_cast<internal::RootView*>(widget->GetRootView());
root_view->AddChildView(v1);
v1->AddChildView(v2);
v2->AddChildView(v3);
v3->AddChildView(v4);
widget->Show();
// Change the handle mode of |v3| to indicate that it would like to handle
// gesture events.
v3->set_handle_mode(EventCountView::CONSUME_EVENTS);
// When no gesture handler is set, dispatching a ui::ET_GESTURE_TAP_DOWN
// should bubble up the views hierarchy until it reaches the first view
// that will handle it (|v3|) and then sets the handler to |v3|.
EXPECT_EQ(nullptr, GetGestureHandler(root_view));
ui::GestureEvent tap_down =
CreateTestGestureEvent(ui::ET_GESTURE_TAP_DOWN, 5, 5);
widget->OnGestureEvent(&tap_down);
EXPECT_EQ(0, v1->GetEventCount(ui::ET_GESTURE_TAP_DOWN));
EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_TAP_DOWN));
EXPECT_EQ(1, v3->GetEventCount(ui::ET_GESTURE_TAP_DOWN));
EXPECT_EQ(1, v4->GetEventCount(ui::ET_GESTURE_TAP_DOWN));
EXPECT_EQ(v3, GetGestureHandler(root_view));
EXPECT_TRUE(tap_down.handled());
v1->ResetCounts();
v2->ResetCounts();
v3->ResetCounts();
v4->ResetCounts();
// A ui::ET_GESTURE_TAP_CANCEL event should be dispatched to |v3| directly.
ui::GestureEvent tap_cancel =
CreateTestGestureEvent(ui::ET_GESTURE_TAP_CANCEL, 5, 5);
widget->OnGestureEvent(&tap_cancel);
EXPECT_EQ(0, v1->GetEventCount(ui::ET_GESTURE_TAP_CANCEL));
EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_TAP_CANCEL));
EXPECT_EQ(1, v3->GetEventCount(ui::ET_GESTURE_TAP_CANCEL));
EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_TAP_CANCEL));
EXPECT_EQ(v3, GetGestureHandler(root_view));
EXPECT_TRUE(tap_cancel.handled());
v1->ResetCounts();
v2->ResetCounts();
v3->ResetCounts();
v4->ResetCounts();
// Change the handle mode of |v3| to indicate that it would no longer like
// to handle events, and change the mode of |v1| to indicate that it would
// like to handle events.
v3->set_handle_mode(EventCountView::PROPAGATE_EVENTS);
v1->set_handle_mode(EventCountView::CONSUME_EVENTS);
// Dispatch a ui::ET_GESTURE_SCROLL_BEGIN event. Because the current gesture
// handler (|v3|) does not handle scroll events, the event should bubble up
// the views hierarchy until it reaches the first view that will handle
// it (|v1|) and then sets the handler to |v1|.
ui::GestureEvent scroll_begin =
CreateTestGestureEvent(ui::ET_GESTURE_SCROLL_BEGIN, 5, 5);
widget->OnGestureEvent(&scroll_begin);
EXPECT_EQ(1, v1->GetEventCount(ui::ET_GESTURE_SCROLL_BEGIN));
EXPECT_EQ(1, v2->GetEventCount(ui::ET_GESTURE_SCROLL_BEGIN));
EXPECT_EQ(1, v3->GetEventCount(ui::ET_GESTURE_SCROLL_BEGIN));
EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_SCROLL_BEGIN));
EXPECT_EQ(v1, GetGestureHandler(root_view));
EXPECT_TRUE(scroll_begin.handled());
v1->ResetCounts();
v2->ResetCounts();
v3->ResetCounts();
v4->ResetCounts();
// A ui::ET_GESTURE_SCROLL_UPDATE event should be dispatched to |v1|
// directly.
ui::GestureEvent scroll_update =
CreateTestGestureEvent(ui::ET_GESTURE_SCROLL_UPDATE, 5, 5);
widget->OnGestureEvent(&scroll_update);
EXPECT_EQ(1, v1->GetEventCount(ui::ET_GESTURE_SCROLL_UPDATE));
EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_SCROLL_UPDATE));
EXPECT_EQ(0, v3->GetEventCount(ui::ET_GESTURE_SCROLL_UPDATE));
EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_SCROLL_UPDATE));
EXPECT_EQ(v1, GetGestureHandler(root_view));
EXPECT_TRUE(scroll_update.handled());
v1->ResetCounts();
v2->ResetCounts();
v3->ResetCounts();
v4->ResetCounts();
// A ui::ET_GESTURE_SCROLL_END event should be dispatched to |v1|
// directly and should not reset the gesture handler.
ui::GestureEvent scroll_end =
CreateTestGestureEvent(ui::ET_GESTURE_SCROLL_END, 5, 5);
widget->OnGestureEvent(&scroll_end);
EXPECT_EQ(1, v1->GetEventCount(ui::ET_GESTURE_SCROLL_END));
EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_SCROLL_END));
EXPECT_EQ(0, v3->GetEventCount(ui::ET_GESTURE_SCROLL_END));
EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_SCROLL_END));
EXPECT_EQ(v1, GetGestureHandler(root_view));
EXPECT_TRUE(scroll_end.handled());
v1->ResetCounts();
v2->ResetCounts();
v3->ResetCounts();
v4->ResetCounts();
// A ui::ET_GESTURE_PINCH_BEGIN event (which is a non-scroll event) should
// still be dispatched to |v1| directly.
ui::GestureEvent pinch_begin =
CreateTestGestureEvent(ui::ET_GESTURE_PINCH_BEGIN, 5, 5);
widget->OnGestureEvent(&pinch_begin);
EXPECT_EQ(1, v1->GetEventCount(ui::ET_GESTURE_PINCH_BEGIN));
EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_PINCH_BEGIN));
EXPECT_EQ(0, v3->GetEventCount(ui::ET_GESTURE_PINCH_BEGIN));
EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_PINCH_BEGIN));
EXPECT_EQ(v1, GetGestureHandler(root_view));
EXPECT_TRUE(pinch_begin.handled());
v1->ResetCounts();
v2->ResetCounts();
v3->ResetCounts();
v4->ResetCounts();
// A ui::ET_GESTURE_END event should be dispatched to |v1| and should
// set the gesture handler to NULL.
ui::GestureEvent end = CreateTestGestureEvent(ui::ET_GESTURE_END, 5, 5);
widget->OnGestureEvent(&end);
EXPECT_EQ(1, v1->GetEventCount(ui::ET_GESTURE_END));
EXPECT_EQ(0, v2->GetEventCount(ui::ET_GESTURE_END));
EXPECT_EQ(0, v3->GetEventCount(ui::ET_GESTURE_END));
EXPECT_EQ(0, v4->GetEventCount(ui::ET_GESTURE_END));
EXPECT_EQ(nullptr, GetGestureHandler(root_view));
EXPECT_TRUE(end.handled());
widget->Close();
}
// TODO(b/271490637): on Mac a drag controller should still be notified when
// drag will start. Figure out how to write a unit test for Mac. Then remove
// this build flag check.
#if !BUILDFLAG(IS_MAC)
// Verifies that the drag controller is notified when the view drag will start.
TEST_F(WidgetTest, NotifyDragControllerWhenDragWillStart) {
// Create a widget whose contents view is draggable.
UniqueWidgetPtr widget(std::make_unique<Widget>());
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_POPUP);
params.bounds = gfx::Rect(/*width=*/650, /*height=*/650);
widget->Init(std::move(params));
widget->Show();
MockDragController mock_drag_controller;
views::View contents_view;
contents_view.set_drag_controller(&mock_drag_controller);
widget->SetContentsView(&contents_view);
// Expect the drag controller is notified of the drag start.
EXPECT_CALL(mock_drag_controller, OnWillStartDragForView(&contents_view));
// Drag-and-drop `contents_view` by mouse.
ui::test::EventGenerator generator(GetContext(), widget->GetNativeWindow());
generator.MoveMouseTo(contents_view.GetBoundsInScreen().CenterPoint());
generator.PressLeftButton();
generator.MoveMouseBy(/*x=*/200, /*y=*/0);
generator.ReleaseLeftButton();
}
#endif // !BUILDFLAG(IS_MAC)
// A class used in WidgetTest.GestureEventLocationWhileBubbling to verify
// that when a gesture event bubbles up a View hierarchy, the location
// of a gesture event seen by each View is in the local coordinate space
// of that View.
class GestureLocationView : public EventCountView {
public:
GestureLocationView() = default;
GestureLocationView(const GestureLocationView&) = delete;
GestureLocationView& operator=(const GestureLocationView&) = delete;
~GestureLocationView() override = default;
void set_expected_location(gfx::Point expected_location) {
expected_location_ = expected_location;
}
// EventCountView:
void OnGestureEvent(ui::GestureEvent* event) override {
EventCountView::OnGestureEvent(event);
// Verify that the location of |event| is in the local coordinate
// space of |this|.
EXPECT_EQ(expected_location_, event->location());
}
private:
// The expected location of a gesture event dispatched to |this|.
gfx::Point expected_location_;
};
// Verifies that the location of a gesture event is always in the local
// coordinate space of the View receiving the event while bubbling.
TEST_F(WidgetTest, GestureEventLocationWhileBubbling) {
Widget* widget = CreateTopLevelNativeWidget();
widget->SetBounds(gfx::Rect(0, 0, 300, 300));
// Define a hierarchy of three views (coordinates shown below are in the
// coordinate space of the root view, but the coordinates used for
// SetBounds() are in their parent coordinate space).
// v1 (50, 50, 150, 150)
// v2 (100, 70, 50, 80)
// v3 (120, 100, 10, 10)
GestureLocationView* v1 = new GestureLocationView();
v1->SetBounds(50, 50, 150, 150);
GestureLocationView* v2 = new GestureLocationView();
v2->SetBounds(50, 20, 50, 80);
GestureLocationView* v3 = new GestureLocationView();
v3->SetBounds(20, 30, 10, 10);
internal::RootView* root_view =
static_cast<internal::RootView*>(widget->GetRootView());
root_view->AddChildView(v1);
v1->AddChildView(v2);
v2->AddChildView(v3);
widget->Show();
// Define a GESTURE_TAP event located at (125, 105) in root view coordinates.
// This event is contained within all of |v1|, |v2|, and |v3|.
gfx::Point location_in_root(125, 105);
ui::GestureEvent tap = CreateTestGestureEvent(
ui::ET_GESTURE_TAP, location_in_root.x(), location_in_root.y());
// Calculate the location of the event in the local coordinate spaces
// of each of the views.
gfx::Point location_in_v1(ConvertPointFromWidgetToView(v1, location_in_root));
EXPECT_EQ(gfx::Point(75, 55), location_in_v1);
gfx::Point location_in_v2(ConvertPointFromWidgetToView(v2, location_in_root));
EXPECT_EQ(gfx::Point(25, 35), location_in_v2);
gfx::Point location_in_v3(ConvertPointFromWidgetToView(v3, location_in_root));
EXPECT_EQ(gfx::Point(5, 5), location_in_v3);
// Dispatch the event. When each view receives the event, its location should
// be in the local coordinate space of that view (see the check made by
// GestureLocationView). After dispatch is complete the event's location
// should be in the root coordinate space.
v1->set_expected_location(location_in_v1);
v2->set_expected_location(location_in_v2);
v3->set_expected_location(location_in_v3);
widget->OnGestureEvent(&tap);
EXPECT_EQ(location_in_root, tap.location());
// Verify that each view did in fact see the event.
EventCountView* view1 = v1;
EventCountView* view2 = v2;
EventCountView* view3 = v3;
EXPECT_EQ(1, view1->GetEventCount(ui::ET_GESTURE_TAP));
EXPECT_EQ(1, view2->GetEventCount(ui::ET_GESTURE_TAP));
EXPECT_EQ(1, view3->GetEventCount(ui::ET_GESTURE_TAP));
widget->Close();
}
// Test the result of Widget::GetAllChildWidgets().
TEST_F(WidgetTest, GetAllChildWidgets) {
// Create the following widget hierarchy:
//
// toplevel
// +-- w1
// +-- w11
// +-- w2
// +-- w21
// +-- w22
WidgetAutoclosePtr toplevel(CreateTopLevelPlatformWidget());
Widget* w1 = CreateChildPlatformWidget(toplevel->GetNativeView());
Widget* w11 = CreateChildPlatformWidget(w1->GetNativeView());
Widget* w2 = CreateChildPlatformWidget(toplevel->GetNativeView());
Widget* w21 = CreateChildPlatformWidget(w2->GetNativeView());
Widget* w22 = CreateChildPlatformWidget(w2->GetNativeView());
std::set<Widget*> expected;
expected.insert(toplevel.get());
expected.insert(w1);
expected.insert(w11);
expected.insert(w2);
expected.insert(w21);
expected.insert(w22);
std::set<Widget*> child_widgets;
Widget::GetAllChildWidgets(toplevel->GetNativeView(), &child_widgets);
EXPECT_TRUE(base::ranges::equal(expected, child_widgets));
// Check GetAllOwnedWidgets(). On Aura, this includes "transient" children.
// Otherwise (on all platforms), it should be the same as GetAllChildWidgets()
// except the root Widget is not included.
EXPECT_EQ(1u, expected.erase(toplevel.get()));
std::set<Widget*> owned_widgets;
Widget::GetAllOwnedWidgets(toplevel->GetNativeView(), &owned_widgets);
EXPECT_TRUE(base::ranges::equal(expected, owned_widgets));
}
// Used by DestroyChildWidgetsInOrder. On destruction adds the supplied name to
// a vector.
class DestroyedTrackingView : public View {
public:
DestroyedTrackingView(const std::string& name,
std::vector<std::string>* add_to)
: name_(name), add_to_(add_to) {}
DestroyedTrackingView(const DestroyedTrackingView&) = delete;
DestroyedTrackingView& operator=(const DestroyedTrackingView&) = delete;
~DestroyedTrackingView() override { add_to_->push_back(name_); }
private:
const std::string name_;
raw_ptr<std::vector<std::string>> add_to_;
};
class WidgetChildDestructionTest : public DesktopWidgetTest {
public:
WidgetChildDestructionTest() = default;
WidgetChildDestructionTest(const WidgetChildDestructionTest&) = delete;
WidgetChildDestructionTest& operator=(const WidgetChildDestructionTest&) =
delete;
// Creates a top level and a child, destroys the child and verifies the views
// of the child are destroyed before the views of the parent.
void RunDestroyChildWidgetsTest(bool top_level_has_desktop_native_widget_aura,
bool child_has_desktop_native_widget_aura) {
// When a View is destroyed its name is added here.
std::vector<std::string> destroyed;
Widget* top_level = new Widget;
Widget::InitParams params =
CreateParams(views::Widget::InitParams::TYPE_WINDOW);
if (!top_level_has_desktop_native_widget_aura) {
params.native_widget =
CreatePlatformNativeWidgetImpl(top_level, kStubCapture, nullptr);
}
top_level->Init(std::move(params));
top_level->GetRootView()->AddChildView(
new DestroyedTrackingView("parent", &destroyed));
top_level->Show();
Widget* child = new Widget;
Widget::InitParams child_params =
CreateParams(views::Widget::InitParams::TYPE_POPUP);
child_params.parent = top_level->GetNativeView();
if (!child_has_desktop_native_widget_aura) {
child_params.native_widget =
CreatePlatformNativeWidgetImpl(child, kStubCapture, nullptr);
}
child->Init(std::move(child_params));
child->GetRootView()->AddChildView(
new DestroyedTrackingView("child", &destroyed));
child->Show();
// Should trigger destruction of the child too.
top_level->native_widget_private()->CloseNow();
// Child should be destroyed first.
ASSERT_EQ(2u, destroyed.size());
EXPECT_EQ("child", destroyed[0]);
EXPECT_EQ("parent", destroyed[1]);
}
};
// See description of RunDestroyChildWidgetsTest(). Parent uses
// DesktopNativeWidgetAura.
TEST_F(WidgetChildDestructionTest,
DestroyChildWidgetsInOrderWithDesktopNativeWidget) {
RunDestroyChildWidgetsTest(true, false);
}
// See description of RunDestroyChildWidgetsTest(). Both parent and child use
// DesktopNativeWidgetAura.
TEST_F(WidgetChildDestructionTest,
DestroyChildWidgetsInOrderWithDesktopNativeWidgetForBoth) {
RunDestroyChildWidgetsTest(true, true);
}
// See description of RunDestroyChildWidgetsTest().
TEST_F(WidgetChildDestructionTest, DestroyChildWidgetsInOrder) {
RunDestroyChildWidgetsTest(false, false);
}
// Verifies nativeview visbility matches that of Widget visibility when
// SetFullscreen is invoked.
TEST_F(WidgetTest, FullscreenStatePropagated) {
std::unique_ptr<Widget> top_level_widget = CreateTestWidget();
top_level_widget->SetFullscreen(true);
EXPECT_EQ(top_level_widget->IsVisible(),
IsNativeWindowVisible(top_level_widget->GetNativeWindow()));
}
// Verifies nativeview visbility matches that of Widget visibility when
// SetFullscreen is invoked, for a widget provided with a desktop widget.
TEST_F(DesktopWidgetTest, FullscreenStatePropagated_DesktopWidget) {
std::unique_ptr<Widget> top_level_widget = CreateTestWidget();
top_level_widget->SetFullscreen(true);
EXPECT_EQ(top_level_widget->IsVisible(),
IsNativeWindowVisible(top_level_widget->GetNativeWindow()));
}
// Used to delete the widget when the supplied bounds changes.
class DestroyingWidgetBoundsObserver : public WidgetObserver {
public:
explicit DestroyingWidgetBoundsObserver(std::unique_ptr<Widget> widget)
: widget_(std::move(widget)) {
widget_->AddObserver(this);
}
// There are no assertions here as not all platforms call
// OnWidgetBoundsChanged() when going fullscreen.
~DestroyingWidgetBoundsObserver() override = default;
// WidgetObserver:
void OnWidgetBoundsChanged(Widget* widget,
const gfx::Rect& new_bounds) override {
widget_->RemoveObserver(this);
widget_.reset();
}
private:
std::unique_ptr<Widget> widget_;
};
// Deletes a Widget when the bounds change as part of toggling fullscreen.
// This is a regression test for https://crbug.com/1197436.
// Disabled on Mac: This test has historically deleted the Widget not during
// SetFullscreen, but at the end of the test. When the Widget is deleted inside
// SetFullscreen, the test crashes.
// https://crbug.com/1307486
#if BUILDFLAG(IS_MAC)
#define MAYBE_DeleteInSetFullscreen DISABLED_DeleteInSetFullscreen
#else
#define MAYBE_DeleteInSetFullscreen DeleteInSetFullscreen
#endif
TEST_F(DesktopWidgetTest, MAYBE_DeleteInSetFullscreen) {
std::unique_ptr<Widget> widget = std::make_unique<Widget>();
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget->Init(std::move(params));
Widget* w = widget.get();
DestroyingWidgetBoundsObserver destroyer(std::move(widget));
w->SetFullscreen(true);
}
namespace {
class FullscreenAwareFrame : public views::NonClientFrameView {
public:
explicit FullscreenAwareFrame(views::Widget* widget) : widget_(widget) {}
FullscreenAwareFrame(const FullscreenAwareFrame&) = delete;
FullscreenAwareFrame& operator=(const FullscreenAwareFrame&) = delete;
~FullscreenAwareFrame() override = default;
// views::NonClientFrameView overrides:
gfx::Rect GetBoundsForClientView() const override { return gfx::Rect(); }
gfx::Rect GetWindowBoundsForClientBounds(
const gfx::Rect& client_bounds) const override {
return gfx::Rect();
}
int NonClientHitTest(const gfx::Point& point) override { return HTNOWHERE; }
void GetWindowMask(const gfx::Size& size, SkPath* window_mask) override {}
void ResetWindowControls() override {}
void UpdateWindowIcon() override {}
void UpdateWindowTitle() override {}
void SizeConstraintsChanged() override {}
// views::View overrides:
void Layout() override {
if (widget_->IsFullscreen())
fullscreen_layout_called_ = true;
}
bool fullscreen_layout_called() const { return fullscreen_layout_called_; }
private:
raw_ptr<views::Widget> widget_;
bool fullscreen_layout_called_ = false;
};
} // namespace
// Tests that frame Layout is called when a widget goes fullscreen without
// changing its size or title.
TEST_F(WidgetTest, FullscreenFrameLayout) {
WidgetAutoclosePtr widget(CreateTopLevelPlatformWidget());
auto frame_view = std::make_unique<FullscreenAwareFrame>(widget.get());
FullscreenAwareFrame* frame = frame_view.get();
widget->non_client_view()->SetFrameView(std::move(frame_view));
widget->Maximize();
RunPendingMessages();
EXPECT_FALSE(frame->fullscreen_layout_called());
widget->SetFullscreen(true);
widget->Show();
#if BUILDFLAG(IS_MAC)
// On macOS, a fullscreen layout is triggered from within SetFullscreen.
// https://crbug.com/1307496
EXPECT_TRUE(frame->fullscreen_layout_called());
#else
EXPECT_TRUE(ViewTestApi(frame).needs_layout());
#endif
widget->LayoutRootViewIfNecessary();
RunPendingMessages();
EXPECT_TRUE(frame->fullscreen_layout_called());
}
namespace {
// Trivial WidgetObserverTest that invokes Widget::IsActive() from
// OnWindowDestroying.
class IsActiveFromDestroyObserver : public WidgetObserver {
public:
IsActiveFromDestroyObserver() = default;
IsActiveFromDestroyObserver(const IsActiveFromDestroyObserver&) = delete;
IsActiveFromDestroyObserver& operator=(const IsActiveFromDestroyObserver&) =
delete;
~IsActiveFromDestroyObserver() override = default;
void OnWidgetDestroying(Widget* widget) override { widget->IsActive(); }
};
} // namespace
class ChildDesktopWidgetTest : public DesktopWidgetTest {
public:
Widget::InitParams CreateParams(Widget::InitParams::Type type) override {
Widget::InitParams params = DesktopWidgetTest::CreateParams(type);
if (context_)
params.context = context_;
return params;
}
std::unique_ptr<Widget> CreateChildWidget(gfx::NativeWindow context) {
context_ = context;
return CreateTestWidget();
}
private:
gfx::NativeWindow context_ = nullptr;
};
// Verifies Widget::IsActive() invoked from
// WidgetObserver::OnWidgetDestroying() in a child widget doesn't crash.
TEST_F(ChildDesktopWidgetTest, IsActiveFromDestroy) {
// Create two widgets, one a child of the other.
IsActiveFromDestroyObserver observer;
std::unique_ptr<Widget> parent_widget = CreateTestWidget();
parent_widget->Show();
std::unique_ptr<Widget> child_widget =
CreateChildWidget(parent_widget->GetNativeWindow());
child_widget->AddObserver(&observer);
child_widget->Show();
parent_widget->CloseNow();
}
// Tests that events propagate through from the dispatcher with the correct
// event type, and that the different platforms behave the same.
TEST_F(WidgetTest, MouseEventTypesViaGenerator) {
WidgetAutoclosePtr widget(CreateTopLevelFramelessPlatformWidget());
EventCountView* view =
widget->GetRootView()->AddChildView(std::make_unique<EventCountView>());
view->set_handle_mode(EventCountView::CONSUME_EVENTS);
view->SetBounds(10, 10, 50, 40);
widget->SetBounds(gfx::Rect(0, 0, 100, 80));
widget->Show();
auto generator =
CreateEventGenerator(GetContext(), widget->GetNativeWindow());
const gfx::Point view_center_point = view->GetBoundsInScreen().CenterPoint();
generator->set_current_screen_location(view_center_point);
generator->ClickLeftButton();
EXPECT_EQ(1, view->GetEventCount(ui::ET_MOUSE_PRESSED));
EXPECT_EQ(1, view->GetEventCount(ui::ET_MOUSE_RELEASED));
EXPECT_EQ(ui::EF_LEFT_MOUSE_BUTTON, view->last_flags());
generator->PressRightButton();
EXPECT_EQ(2, view->GetEventCount(ui::ET_MOUSE_PRESSED));
EXPECT_EQ(1, view->GetEventCount(ui::ET_MOUSE_RELEASED));
EXPECT_EQ(ui::EF_RIGHT_MOUSE_BUTTON, view->last_flags());
generator->ReleaseRightButton();
EXPECT_EQ(2, view->GetEventCount(ui::ET_MOUSE_PRESSED));
EXPECT_EQ(2, view->GetEventCount(ui::ET_MOUSE_RELEASED));
EXPECT_EQ(ui::EF_RIGHT_MOUSE_BUTTON, view->last_flags());
// Test mouse move events.
EXPECT_EQ(0, view->GetEventCount(ui::ET_MOUSE_MOVED));
EXPECT_EQ(0, view->GetEventCount(ui::ET_MOUSE_ENTERED));
// Move the mouse a displacement of (10, 10).
generator->MoveMouseTo(view_center_point + gfx::Vector2d(10, 10));
EXPECT_EQ(1, view->GetEventCount(ui::ET_MOUSE_MOVED));
EXPECT_EQ(1, view->GetEventCount(ui::ET_MOUSE_ENTERED));
EXPECT_EQ(ui::EF_NONE, view->last_flags());
// Move it again - entered count shouldn't change.
generator->MoveMouseTo(view_center_point + gfx::Vector2d(11, 11));
EXPECT_EQ(2, view->GetEventCount(ui::ET_MOUSE_MOVED));
EXPECT_EQ(1, view->GetEventCount(ui::ET_MOUSE_ENTERED));
EXPECT_EQ(0, view->GetEventCount(ui::ET_MOUSE_EXITED));
// Move it off the view.
const gfx::Point out_of_bounds_point =
view->GetBoundsInScreen().bottom_right() + gfx::Vector2d(10, 10);
generator->MoveMouseTo(out_of_bounds_point);
EXPECT_EQ(2, view->GetEventCount(ui::ET_MOUSE_MOVED));
EXPECT_EQ(1, view->GetEventCount(ui::ET_MOUSE_ENTERED));
EXPECT_EQ(1, view->GetEventCount(ui::ET_MOUSE_EXITED));
// Move it back on.
generator->MoveMouseTo(view_center_point);
EXPECT_EQ(3, view->GetEventCount(ui::ET_MOUSE_MOVED));
EXPECT_EQ(2, view->GetEventCount(ui::ET_MOUSE_ENTERED));
EXPECT_EQ(1, view->GetEventCount(ui::ET_MOUSE_EXITED));
// Drargging. Cover HasCapture() and NativeWidgetPrivate::IsMouseButtonDown().
generator->DragMouseTo(out_of_bounds_point);
EXPECT_EQ(3, view->GetEventCount(ui::ET_MOUSE_PRESSED));
EXPECT_EQ(3, view->GetEventCount(ui::ET_MOUSE_RELEASED));
EXPECT_EQ(1, view->GetEventCount(ui::ET_MOUSE_DRAGGED));
EXPECT_EQ(ui::EF_LEFT_MOUSE_BUTTON, view->last_flags());
}
// Tests that the root view is correctly set up for Widget types that do not
// require a non-client view, before any other views are added to the widget.
// That is, before Widget::ReorderNativeViews() is called which, if called with
// a root view not set, could cause the root view to get resized to the widget.
TEST_F(WidgetTest, NonClientWindowValidAfterInit) {
WidgetAutoclosePtr widget(CreateTopLevelFramelessPlatformWidget());
View* root_view = widget->GetRootView();
// Size the root view to exceed the widget bounds.
const gfx::Rect test_rect(0, 0, 500, 500);
root_view->SetBoundsRect(test_rect);
EXPECT_NE(test_rect.size(), widget->GetWindowBoundsInScreen().size());
EXPECT_EQ(test_rect, root_view->bounds());
widget->ReorderNativeViews();
EXPECT_EQ(test_rect, root_view->bounds());
}
#if BUILDFLAG(IS_WIN)
// Provides functionality to subclass a window and keep track of messages
// received.
class SubclassWindowHelper {
public:
explicit SubclassWindowHelper(HWND window)
: window_(window), message_to_destroy_on_(0) {
EXPECT_EQ(instance_, nullptr);
instance_ = this;
EXPECT_TRUE(Subclass());
}
SubclassWindowHelper(const SubclassWindowHelper&) = delete;
SubclassWindowHelper& operator=(const SubclassWindowHelper&) = delete;
~SubclassWindowHelper() {
Unsubclass();
instance_ = nullptr;
}
// Returns true if the |message| passed in was received.
bool received_message(unsigned int message) {
return (messages_.find(message) != messages_.end());
}
void Clear() { messages_.clear(); }
void set_message_to_destroy_on(unsigned int message) {
message_to_destroy_on_ = message;
}
private:
bool Subclass() {
old_proc_ = reinterpret_cast<WNDPROC>(::SetWindowLongPtr(
window_, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(WndProc)));
return old_proc_ != nullptr;
}
void Unsubclass() {
::SetWindowLongPtr(window_, GWLP_WNDPROC,
reinterpret_cast<LONG_PTR>(old_proc_));
}
static LRESULT CALLBACK WndProc(HWND window,
unsigned int message,
WPARAM w_param,
LPARAM l_param) {
EXPECT_NE(instance_, nullptr);
EXPECT_EQ(window, instance_->window_);
// Keep track of messags received for this window.
instance_->messages_.insert(message);
LRESULT ret = ::CallWindowProc(instance_->old_proc_, window, message,
w_param, l_param);
if (message == instance_->message_to_destroy_on_) {
instance_->Unsubclass();
::DestroyWindow(window);
}
return ret;
}
WNDPROC old_proc_;
HWND window_;
static SubclassWindowHelper* instance_;
std::set<unsigned int> messages_;
unsigned int message_to_destroy_on_;
};
SubclassWindowHelper* SubclassWindowHelper::instance_ = nullptr;
// This test validates whether the WM_SYSCOMMAND message for SC_MOVE is
// received when we post a WM_NCLBUTTONDOWN message for the caption in the
// following scenarios:-
// 1. Posting a WM_NCMOUSEMOVE message for a different location.
// 2. Posting a WM_NCMOUSEMOVE message with a different hittest code.
// 3. Posting a WM_MOUSEMOVE message.
// Disabled because of flaky timeouts: http://crbug.com/592742
TEST_F(DesktopWidgetTest,
DISABLED_SysCommandMoveOnNCLButtonDownOnCaptionAndMoveTest) {
std::unique_ptr<Widget> widget =
CreateTestWidget(Widget::InitParams::TYPE_WINDOW);
widget->Show();
::SetCursorPos(500, 500);
HWND window = widget->GetNativeWindow()->GetHost()->GetAcceleratedWidget();
SubclassWindowHelper subclass_helper(window);
// Posting just a WM_NCLBUTTONDOWN message should not result in a
// WM_SYSCOMMAND
::PostMessage(window, WM_NCLBUTTONDOWN, HTCAPTION, MAKELPARAM(100, 100));
RunPendingMessages();
EXPECT_TRUE(subclass_helper.received_message(WM_NCLBUTTONDOWN));
EXPECT_FALSE(subclass_helper.received_message(WM_SYSCOMMAND));
subclass_helper.Clear();
// Posting a WM_NCLBUTTONDOWN message followed by a WM_NCMOUSEMOVE at the
// same location should not result in a WM_SYSCOMMAND message.
::PostMessage(window, WM_NCLBUTTONDOWN, HTCAPTION, MAKELPARAM(100, 100));
::PostMessage(window, WM_NCMOUSEMOVE, HTCAPTION, MAKELPARAM(100, 100));
RunPendingMessages();
EXPECT_TRUE(subclass_helper.received_message(WM_NCLBUTTONDOWN));
EXPECT_TRUE(subclass_helper.received_message(WM_NCMOUSEMOVE));
EXPECT_FALSE(subclass_helper.received_message(WM_SYSCOMMAND));
subclass_helper.Clear();
// Posting a WM_NCLBUTTONDOWN message followed by a WM_NCMOUSEMOVE at a
// different location should result in a WM_SYSCOMMAND message.
::PostMessage(window, WM_NCLBUTTONDOWN, HTCAPTION, MAKELPARAM(100, 100));
::PostMessage(window, WM_NCMOUSEMOVE, HTCAPTION, MAKELPARAM(110, 110));
RunPendingMessages();
EXPECT_TRUE(subclass_helper.received_message(WM_NCLBUTTONDOWN));
EXPECT_TRUE(subclass_helper.received_message(WM_NCMOUSEMOVE));
EXPECT_TRUE(subclass_helper.received_message(WM_SYSCOMMAND));
subclass_helper.Clear();
// Posting a WM_NCLBUTTONDOWN message followed by a WM_NCMOUSEMOVE at a
// different location with a different hittest code should result in a
// WM_SYSCOMMAND message.
::PostMessage(window, WM_NCLBUTTONDOWN, HTCAPTION, MAKELPARAM(100, 100));
::PostMessage(window, WM_NCMOUSEMOVE, HTTOP, MAKELPARAM(110, 102));
RunPendingMessages();
EXPECT_TRUE(subclass_helper.received_message(WM_NCLBUTTONDOWN));
EXPECT_TRUE(subclass_helper.received_message(WM_NCMOUSEMOVE));
EXPECT_TRUE(subclass_helper.received_message(WM_SYSCOMMAND));
subclass_helper.Clear();
// Posting a WM_NCLBUTTONDOWN message followed by a WM_MOUSEMOVE should
// result in a WM_SYSCOMMAND message.
::PostMessage(window, WM_NCLBUTTONDOWN, HTCAPTION, MAKELPARAM(100, 100));
::PostMessage(window, WM_MOUSEMOVE, HTCLIENT, MAKELPARAM(110, 110));
RunPendingMessages();
EXPECT_TRUE(subclass_helper.received_message(WM_NCLBUTTONDOWN));
EXPECT_TRUE(subclass_helper.received_message(WM_MOUSEMOVE));
EXPECT_TRUE(subclass_helper.received_message(WM_SYSCOMMAND));
}
// This test validates that destroying the window in the context of the
// WM_SYSCOMMAND message with SC_MOVE does not crash.
// Disabled because of flaky timeouts: http://crbug.com/592742
TEST_F(DesktopWidgetTest, DISABLED_DestroyInSysCommandNCLButtonDownOnCaption) {
std::unique_ptr<Widget> widget =
CreateTestWidget(Widget::InitParams::TYPE_WINDOW);
widget->Show();
::SetCursorPos(500, 500);
HWND window = widget->GetNativeWindow()->GetHost()->GetAcceleratedWidget();
SubclassWindowHelper subclass_helper(window);
// Destroying the window in the context of the WM_SYSCOMMAND message
// should not crash.
subclass_helper.set_message_to_destroy_on(WM_SYSCOMMAND);
::PostMessage(window, WM_NCLBUTTONDOWN, HTCAPTION, MAKELPARAM(100, 100));
::PostMessage(window, WM_NCMOUSEMOVE, HTCAPTION, MAKELPARAM(110, 110));
RunPendingMessages();
EXPECT_TRUE(subclass_helper.received_message(WM_NCLBUTTONDOWN));
EXPECT_TRUE(subclass_helper.received_message(WM_SYSCOMMAND));
}
#endif
// Test that the z-order levels round-trip.
TEST_F(WidgetTest, ZOrderLevel) {
WidgetAutoclosePtr widget(CreateTopLevelNativeWidget());
EXPECT_EQ(ui::ZOrderLevel::kNormal, widget->GetZOrderLevel());
widget->SetZOrderLevel(ui::ZOrderLevel::kFloatingWindow);
EXPECT_EQ(ui::ZOrderLevel::kFloatingWindow, widget->GetZOrderLevel());
widget->SetZOrderLevel(ui::ZOrderLevel::kNormal);
EXPECT_EQ(ui::ZOrderLevel::kNormal, widget->GetZOrderLevel());
}
namespace {
class ScaleFactorView : public View {
public:
ScaleFactorView() = default;
ScaleFactorView(const ScaleFactorView&) = delete;
ScaleFactorView& operator=(const ScaleFactorView&) = delete;
// Overridden from ui::LayerDelegate:
void OnDeviceScaleFactorChanged(float old_device_scale_factor,
float new_device_scale_factor) override {
last_scale_factor_ = new_device_scale_factor;
View::OnDeviceScaleFactorChanged(old_device_scale_factor,
new_device_scale_factor);
}
float last_scale_factor() const { return last_scale_factor_; }
private:
float last_scale_factor_ = 0.f;
};
} // namespace
// Ensure scale factor changes are propagated from the native Widget.
TEST_F(WidgetTest, OnDeviceScaleFactorChanged) {
// Automatically close the widget, but not delete it.
WidgetAutoclosePtr widget(CreateTopLevelPlatformWidget());
ScaleFactorView* view = new ScaleFactorView;
widget->GetRootView()->AddChildView(view);
float scale_factor = widget->GetLayer()->device_scale_factor();
EXPECT_NE(scale_factor, 0.f);
// For views that are not layer-backed, adding the view won't notify the view
// about the initial scale factor. Fake it.
view->OnDeviceScaleFactorChanged(0.f, scale_factor);
EXPECT_EQ(scale_factor, view->last_scale_factor());
// Changes should be propagated.
scale_factor *= 2.0f;
widget->GetLayer()->OnDeviceScaleFactorChanged(scale_factor);
EXPECT_EQ(scale_factor, view->last_scale_factor());
}
// Test that WidgetRemovalsObserver::OnWillRemoveView is called when deleting
// a view.
TEST_F(WidgetTest, WidgetRemovalsObserverCalled) {
WidgetAutoclosePtr widget(CreateTopLevelPlatformWidget());
TestWidgetRemovalsObserver removals_observer;
widget->AddRemovalsObserver(&removals_observer);
View* parent = new View();
widget->client_view()->AddChildView(parent);
View* child = new View();
parent->AddChildView(child);
widget->client_view()->RemoveChildView(parent);
EXPECT_TRUE(removals_observer.DidRemoveView(parent));
EXPECT_FALSE(removals_observer.DidRemoveView(child));
// Calling RemoveChildView() doesn't delete the view, but deleting
// |parent| will automatically delete |child|.
delete parent;
widget->RemoveRemovalsObserver(&removals_observer);
}
// Test that WidgetRemovalsObserver::OnWillRemoveView is called when deleting
// the root view.
TEST_F(WidgetTest, WidgetRemovalsObserverCalledWhenRemovingRootView) {
WidgetAutoclosePtr widget(CreateTopLevelPlatformWidget());
TestWidgetRemovalsObserver removals_observer;
widget->AddRemovalsObserver(&removals_observer);
views::View* root_view = widget->GetRootView();
widget.reset();
EXPECT_TRUE(removals_observer.DidRemoveView(root_view));
}
// Test that WidgetRemovalsObserver::OnWillRemoveView is called when moving
// a view from one widget to another, but not when moving a view within
// the same widget.
TEST_F(WidgetTest, WidgetRemovalsObserverCalledWhenMovingBetweenWidgets) {
WidgetAutoclosePtr widget(CreateTopLevelPlatformWidget());
TestWidgetRemovalsObserver removals_observer;
widget->AddRemovalsObserver(&removals_observer);
View* parent = new View();
widget->client_view()->AddChildView(parent);
View* child = new View();
widget->client_view()->AddChildView(child);
// Reparenting the child shouldn't call the removals observer.
parent->AddChildView(child);
EXPECT_FALSE(removals_observer.DidRemoveView(child));
// Moving the child to a different widget should call the removals observer.
WidgetAutoclosePtr widget2(CreateTopLevelPlatformWidget());
widget2->client_view()->AddChildView(child);
EXPECT_TRUE(removals_observer.DidRemoveView(child));
widget->RemoveRemovalsObserver(&removals_observer);
}
// Test dispatch of ui::ET_MOUSEWHEEL.
TEST_F(WidgetTest, MouseWheelEvent) {
WidgetAutoclosePtr widget(CreateTopLevelPlatformWidget());
widget->SetBounds(gfx::Rect(0, 0, 600, 600));
EventCountView* event_count_view =
widget->client_view()->AddChildView(std::make_unique<EventCountView>());
event_count_view->SetBounds(0, 0, 600, 600);
widget->Show();
auto event_generator =
CreateEventGenerator(GetContext(), widget->GetNativeWindow());
event_generator->MoveMouseWheel(1, 1);
EXPECT_EQ(1, event_count_view->GetEventCount(ui::ET_MOUSEWHEEL));
}
class CloseFromClosingObserver : public WidgetObserver {
public:
~CloseFromClosingObserver() override {
EXPECT_TRUE(was_on_widget_closing_called_);
}
// WidgetObserver:
void OnWidgetClosing(Widget* widget) override {
// OnWidgetClosing() should only be called once, even if Close() is called
// after CloseNow().
ASSERT_FALSE(was_on_widget_closing_called_);
was_on_widget_closing_called_ = true;
widget->Close();
}
private:
bool was_on_widget_closing_called_ = false;
};
TEST_F(WidgetTest, CloseNowFollowedByCloseDoesntCallOnWidgetClosingTwice) {
CloseFromClosingObserver observer;
std::unique_ptr<Widget> widget = std::make_unique<Widget>();
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
widget->Init(std::move(params));
widget->AddObserver(&observer);
widget->CloseNow();
widget->RemoveObserver(&observer);
widget.reset();
// Assertions are in CloseFromClosingObserver.
}
namespace {
class TestSaveWindowPlacementWidgetDelegate : public TestDesktopWidgetDelegate {
public:
TestSaveWindowPlacementWidgetDelegate() = default;
TestSaveWindowPlacementWidgetDelegate(
const TestSaveWindowPlacementWidgetDelegate&) = delete;
TestSaveWindowPlacementWidgetDelegate operator=(
const TestSaveWindowPlacementWidgetDelegate&) = delete;
~TestSaveWindowPlacementWidgetDelegate() override = default;
void set_should_save_window_placement(bool should_save) {
should_save_window_placement_ = should_save;
}
int save_window_placement_count() const {
return save_window_placement_count_;
}
// ViewsDelegate:
std::string GetWindowName() const final { return GetWidget()->GetName(); }
bool ShouldSaveWindowPlacement() const final {
return should_save_window_placement_;
}
void SaveWindowPlacement(const gfx::Rect& bounds,
ui::WindowShowState show_state) override {
save_window_placement_count_++;
}
private:
bool should_save_window_placement_ = true;
int save_window_placement_count_ = 0;
};
} // namespace
TEST_F(WidgetTest, ShouldSaveWindowPlacement) {
for (bool save : {false, true}) {
SCOPED_TRACE(save ? "ShouldSave" : "ShouldNotSave");
TestSaveWindowPlacementWidgetDelegate widget_delegate;
widget_delegate.set_should_save_window_placement(save);
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
params.ownership = Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
params.name = "TestWidget";
widget_delegate.InitWidget(std::move(params));
auto* widget = widget_delegate.GetWidget();
widget->Close();
EXPECT_EQ(save ? 1 : 0, widget_delegate.save_window_placement_count());
}
}
// Parameterized test that verifies the behavior of SetAspectRatio with respect
// to the excluded margin.
class WidgetSetAspectRatioTest
: public ViewsTestBase,
public testing::WithParamInterface<gfx::Size /* margin */> {
public:
WidgetSetAspectRatioTest() : margin_(GetParam()) {}
WidgetSetAspectRatioTest(const WidgetSetAspectRatioTest&) = delete;
WidgetSetAspectRatioTest& operator=(const WidgetSetAspectRatioTest&) = delete;
~WidgetSetAspectRatioTest() override = default;
// ViewsTestBase:
void SetUp() override {
ViewsTestBase::SetUp();
widget_ = std::make_unique<Widget>();
Widget::InitParams params = CreateParams(Widget::InitParams::TYPE_WINDOW);
native_widget_ = std::make_unique<MockNativeWidget>(widget());
ON_CALL(*native_widget(), CreateNonClientFrameView).WillByDefault([this]() {
return std::make_unique<NonClientFrameViewWithFixedMargin>(margin());
});
params.native_widget = native_widget();
widget()->Init(std::move(params));
task_environment()->RunUntilIdle();
}
void TearDown() override {
native_widget_.reset();
widget()->Close();
widget_.reset();
ViewsTestBase::TearDown();
}
const gfx::Size& margin() const { return margin_; }
Widget* widget() { return widget_.get(); }
MockNativeWidget* native_widget() { return native_widget_.get(); }
private:
// Margin around the client view that should be excluded.
const gfx::Size margin_;
std::unique_ptr<Widget> widget_;
std::unique_ptr<MockNativeWidget> native_widget_;
// `NonClientFrameView` that pads the client view with a fixed-size margin,
// to leave room for drawing that's not included in the aspect ratio.
class NonClientFrameViewWithFixedMargin : public NonClientFrameView {
public:
// `margin` is the margin that we'll provide to our client view.
explicit NonClientFrameViewWithFixedMargin(const gfx::Size& margin)
: margin_(margin) {}
// NonClientFrameView
gfx::Rect GetBoundsForClientView() const override {
gfx::Rect r = bounds();
return gfx::Rect(r.x(), r.y(), r.width() - margin_.width(),
r.height() - margin_.height());
}
const gfx::Size margin_;
};
};
TEST_P(WidgetSetAspectRatioTest, SetAspectRatioIncludesMargin) {
// Provide a nonzero size. It doesn't particularly matter what, as long as
// it's larger than our margin.
const gfx::Rect root_view_bounds(0, 0, 100, 200);
ASSERT_GT(root_view_bounds.width(), margin().width());
ASSERT_GT(root_view_bounds.height(), margin().height());
widget()->non_client_view()->SetBoundsRect(root_view_bounds);
// Verify that the excluded margin matches the margin that our custom
// non-client frame provides.
const gfx::SizeF aspect_ratio(1.5f, 1.0f);
EXPECT_CALL(*native_widget(), SetAspectRatio(aspect_ratio, margin()));
widget()->SetAspectRatio(aspect_ratio);
}
INSTANTIATE_TEST_SUITE_P(WidgetSetAspectRatioTestInstantiation,
WidgetSetAspectRatioTest,
::testing::Values(gfx::Size(15, 20), gfx::Size(0, 0)));
class WidgetShadowTest : public WidgetTest {
public:
WidgetShadowTest() = default;
WidgetShadowTest(const WidgetShadowTest&) = delete;
WidgetShadowTest& operator=(const WidgetShadowTest&) = delete;
~WidgetShadowTest() override = default;
// WidgetTest:
void SetUp() override {
set_native_widget_type(NativeWidgetType::kDesktop);
WidgetTest::SetUp();
InitControllers();
}
void TearDown() override {
#if defined(USE_AURA) && !BUILDFLAG(ENABLE_DESKTOP_AURA)
shadow_controller_.reset();
focus_controller_.reset();
#endif
WidgetTest::TearDown();
}
Widget::InitParams CreateParams(Widget::InitParams::Type type) override {
Widget::InitParams params =
WidgetTest::CreateParams(override_type_.value_or(type));
params.shadow_type = Widget::InitParams::ShadowType::kDrop;
params.shadow_elevation = 10;
params.name = name_;
params.child = force_child_;
return params;
}
protected:
absl::optional<Widget::InitParams::Type> override_type_;
std::string name_;
bool force_child_ = false;
private:
#if BUILDFLAG(ENABLE_DESKTOP_AURA) || BUILDFLAG(IS_MAC)
void InitControllers() {}
#else
class TestFocusRules : public wm::BaseFocusRules {
public:
TestFocusRules() = default;
TestFocusRules(const TestFocusRules&) = delete;
TestFocusRules& operator=(const TestFocusRules&) = delete;
bool SupportsChildActivation(const aura::Window* window) const override {
return true;
}
};
void InitControllers() {
focus_controller_ =
std::make_unique<wm::FocusController>(new TestFocusRules);
shadow_controller_ = std::make_unique<wm::ShadowController>(
focus_controller_.get(), nullptr);
}
std::unique_ptr<wm::FocusController> focus_controller_;
std::unique_ptr<wm::ShadowController> shadow_controller_;
#endif // !BUILDFLAG(ENABLE_DESKTOP_AURA) && !BUILDFLAG(IS_MAC)
};
// Disabled on Mac: All drop shadows are managed out of process for now.
#if BUILDFLAG(IS_MAC)
#define MAYBE_ShadowsInRootWindow DISABLED_ShadowsInRootWindow
#else
#define MAYBE_ShadowsInRootWindow ShadowsInRootWindow
#endif
// Test that shadows are not added to root windows when created or upon
// activation. Test that shadows are added to non-root windows even if not
// activated.
TEST_F(WidgetShadowTest, MAYBE_ShadowsInRootWindow) {
#if defined(USE_AURA) && !BUILDFLAG(ENABLE_DESKTOP_AURA)
// On ChromeOS, top-levels have shadows.
bool top_level_window_should_have_shadow = true;
#else
// On non-chromeos platforms, the hosting OS is responsible for the shadow.
bool top_level_window_should_have_shadow = false;
#endif
// To start, just create a Widget. This constructs the first ShadowController
// which will start observing the environment for additional aura::Window
// initialization. The very first ShadowController in DesktopNativeWidgetAura
// is created after the call to aura::Window::Init(), so the ShadowController
// Impl class won't ever see this first Window being initialized.
name_ = "other_top_level";
Widget* other_top_level = CreateTopLevelNativeWidget();
name_ = "top_level";
Widget* top_level = CreateTopLevelNativeWidget();
top_level->SetBounds(gfx::Rect(100, 100, 320, 200));
EXPECT_FALSE(WidgetHasInProcessShadow(top_level));
EXPECT_FALSE(top_level->IsVisible());
top_level->ShowInactive();
EXPECT_EQ(top_level_window_should_have_shadow,
WidgetHasInProcessShadow(top_level));
top_level->Show();
EXPECT_EQ(top_level_window_should_have_shadow,
WidgetHasInProcessShadow(top_level));
name_ = "control";
Widget* control = CreateChildNativeWidgetWithParent(top_level);
control->SetBounds(gfx::Rect(20, 20, 160, 100));
// Widgets of TYPE_CONTROL become visible during Init, so start with a shadow.
EXPECT_TRUE(WidgetHasInProcessShadow(control));
control->ShowInactive();
EXPECT_TRUE(WidgetHasInProcessShadow(control));
control->Show();
EXPECT_TRUE(WidgetHasInProcessShadow(control));
name_ = "child";
override_type_ = Widget::InitParams::TYPE_POPUP;
force_child_ = true;
Widget* child = CreateChildNativeWidgetWithParent(top_level);
child->SetBounds(gfx::Rect(20, 20, 160, 100));
// Now false: the Widget hasn't been shown yet.
EXPECT_FALSE(WidgetHasInProcessShadow(child));
child->ShowInactive();
EXPECT_TRUE(WidgetHasInProcessShadow(child));
child->Show();
EXPECT_TRUE(WidgetHasInProcessShadow(child));
other_top_level->Show();
// Re-activate the top level window. This handles a hypothetical case where
// a shadow is added via the ActivationChangeObserver rather than by the
// aura::WindowObserver. Activation changes only modify an existing shadow
// (if there is one), but should never install a Shadow, even if the Window
// properties otherwise say it should have one.
top_level->Show();
EXPECT_EQ(top_level_window_should_have_shadow,
WidgetHasInProcessShadow(top_level));
top_level->Close();
other_top_level->Close();
}
#if BUILDFLAG(IS_WIN)
// Tests the case where an intervening owner popup window is destroyed out from
// under the currently active modal top-level window. In this instance, the
// remaining top-level windows should be re-enabled.
TEST_F(DesktopWidgetTest, WindowModalOwnerDestroyedEnabledTest) {
// top_level_widget owns owner_dialog_widget which owns owned_dialog_widget.
std::unique_ptr<Widget> top_level_widget = CreateTestWidget();
top_level_widget->Show();
// Create the owner modal dialog.
const auto create_params = [this](Widget* widget, gfx::NativeView parent) {
Widget::InitParams init_params =
CreateParamsForTestWidget(Widget::InitParams::TYPE_WINDOW);
init_params.delegate = new WidgetDelegate();
init_params.delegate->SetModalType(ui::MODAL_TYPE_WINDOW);
init_params.parent = parent;
init_params.native_widget =
new test::TestPlatformNativeWidget<DesktopNativeWidgetAura>(
widget, false, nullptr);
return init_params;
};
Widget owner_dialog_widget;
owner_dialog_widget.Init(
create_params(&owner_dialog_widget, top_level_widget->GetNativeView()));
owner_dialog_widget.Show();
HWND owner_hwnd = HWNDForWidget(&owner_dialog_widget);
// Create the owned modal dialog.
Widget owned_dialog_widget;
owned_dialog_widget.Init(
create_params(&owned_dialog_widget, owner_dialog_widget.GetNativeView()));
owned_dialog_widget.Show();
HWND owned_hwnd = HWNDForWidget(&owned_dialog_widget);
RunPendingMessages();
HWND top_hwnd = HWNDForWidget(top_level_widget.get());
EXPECT_FALSE(!!IsWindowEnabled(owner_hwnd));
EXPECT_FALSE(!!IsWindowEnabled(top_hwnd));
EXPECT_TRUE(!!IsWindowEnabled(owned_hwnd));
owner_dialog_widget.CloseNow();
RunPendingMessages();
EXPECT_FALSE(!!IsWindow(owner_hwnd));
EXPECT_FALSE(!!IsWindow(owned_hwnd));
EXPECT_TRUE(!!IsWindowEnabled(top_hwnd));
top_level_widget->CloseNow();
}
TEST_F(DesktopWidgetTest, StackAboveTest) {
WidgetAutoclosePtr root_one(CreateTopLevelNativeWidget());
WidgetAutoclosePtr root_two(CreateTopLevelNativeWidget());
Widget* child_one = CreateChildNativeWidgetWithParent(root_one->AsWidget());
Widget* child_one_b = CreateChildNativeWidgetWithParent(root_one->AsWidget());
Widget* child_two = CreateChildNativeWidgetWithParent(root_two->AsWidget());
Widget* grandchild_one =
CreateChildNativeWidgetWithParent(child_one->AsWidget());
Widget* grandchild_two =
CreateChildNativeWidgetWithParent(child_two->AsWidget());
root_one->ShowInactive();
child_one->ShowInactive();
child_one_b->ShowInactive();
grandchild_one->ShowInactive();
root_two->ShowInactive();
child_two->ShowInactive();
grandchild_two->ShowInactive();
// Creates the following where Z-Order is from Left to Right.
// root_one root_two
// / \ /
// child_one_b child_one child_two
// / /
// grandchild_one grandchild_two
//
// Note: child_one and grandchild_one were brought to front
// when grandchild_one was shown.
// Child elements are stacked above parent.
EXPECT_TRUE(child_one->IsStackedAbove(root_one->GetNativeView()));
EXPECT_TRUE(child_one_b->IsStackedAbove(root_one->GetNativeView()));
EXPECT_TRUE(grandchild_one->IsStackedAbove(child_one->GetNativeView()));
EXPECT_TRUE(grandchild_two->IsStackedAbove(root_two->GetNativeView()));
// Siblings with higher z-order are stacked correctly.
EXPECT_TRUE(child_one->IsStackedAbove(child_one_b->GetNativeView()));
EXPECT_TRUE(grandchild_one->IsStackedAbove(child_one_b->GetNativeView()));
// Root elements are stacked above child of a root with lower z-order.
EXPECT_TRUE(root_two->IsStackedAbove(root_one->GetNativeView()));
EXPECT_TRUE(root_two->IsStackedAbove(child_one_b->GetNativeView()));
// Child elements are stacked above child of root with lower z-order.
EXPECT_TRUE(child_two->IsStackedAbove(child_one_b->GetNativeView()));
EXPECT_TRUE(child_two->IsStackedAbove(grandchild_one->GetNativeView()));
EXPECT_TRUE(grandchild_two->IsStackedAbove(child_one->GetNativeView()));
EXPECT_TRUE(grandchild_two->IsStackedAbove(root_one->GetNativeView()));
// False cases to verify function is not just returning true for all cases.
EXPECT_FALSE(root_one->IsStackedAbove(grandchild_two->GetNativeView()));
EXPECT_FALSE(root_one->IsStackedAbove(grandchild_one->GetNativeView()));
EXPECT_FALSE(child_two->IsStackedAbove(grandchild_two->GetNativeView()));
EXPECT_FALSE(child_one->IsStackedAbove(grandchild_two->GetNativeView()));
EXPECT_FALSE(child_one_b->IsStackedAbove(child_two->GetNativeView()));
EXPECT_FALSE(grandchild_one->IsStackedAbove(grandchild_two->GetNativeView()));
EXPECT_FALSE(grandchild_one->IsStackedAbove(root_two->GetNativeView()));
EXPECT_FALSE(child_one_b->IsStackedAbove(grandchild_one->GetNativeView()));
}
#endif // BUILDFLAG(IS_WIN)
#if BUILDFLAG(ENABLE_DESKTOP_AURA) || BUILDFLAG(IS_MAC)
namespace {
bool CanHaveCompositingManager() {
#if BUILDFLAG(IS_OZONE)
auto* const egl_utility =
ui::OzonePlatform::GetInstance()->GetPlatformGLEGLUtility();
return (egl_utility != nullptr) && egl_utility->HasVisualManager();
#else
return false;
#endif
}
bool ExpectWidgetTransparency(Widget::InitParams::WindowOpacity opacity) {
switch (opacity) {
case Widget::InitParams::WindowOpacity::kOpaque:
return false;
case Widget::InitParams::WindowOpacity::kTranslucent:
return true;
case Widget::InitParams::WindowOpacity::kInferred:
ADD_FAILURE() << "WidgetOpacity must be explicitly set";
return false;
}
}
class CompositingWidgetTest : public DesktopWidgetTest {
public:
CompositingWidgetTest()
: widget_types_{Widget::InitParams::TYPE_WINDOW,
Widget::InitParams::TYPE_WINDOW_FRAMELESS,
Widget::InitParams::TYPE_CONTROL,
Widget::InitParams::TYPE_POPUP,
Widget::InitParams::TYPE_MENU,
Widget::InitParams::TYPE_TOOLTIP,
Widget::InitParams::TYPE_BUBBLE,
Widget::InitParams::TYPE_DRAG} {}
CompositingWidgetTest(const CompositingWidgetTest&) = delete;
CompositingWidgetTest& operator=(const CompositingWidgetTest&) = delete;
~CompositingWidgetTest() override = default;
Widget::InitParams CreateParams(Widget::InitParams::Type type) override {
Widget::InitParams params = DesktopWidgetTest::CreateParams(type);
params.opacity = opacity_;
return params;
}
void CheckAllWidgetsForOpacity(
const Widget::InitParams::WindowOpacity opacity) {
opacity_ = opacity;
for (const auto& widget_type : widget_types_) {
#if BUILDFLAG(IS_MAC)
// Tooltips are native on Mac. See NativeWidgetNSWindowBridge::Init.
if (widget_type == Widget::InitParams::TYPE_TOOLTIP)
continue;
#elif BUILDFLAG(IS_WIN)
// Other widget types would require to create a parent window and the
// the purpose of this test is mainly X11 in the first place.
if (widget_type != Widget::InitParams::TYPE_WINDOW)
continue;
#endif
std::unique_ptr<Widget> widget = CreateTestWidget(widget_type);
// Use NativeWidgetAura directly.
if (widget_type == Widget::InitParams::TYPE_WINDOW_FRAMELESS ||
widget_type == Widget::InitParams::TYPE_CONTROL)
continue;
#if BUILDFLAG(IS_MAC)
// Mac always always has a compositing window manager, but doesn't have
// transparent titlebars which is what ShouldWindowContentsBeTransparent()
// is currently used for. Asking for transparency should get it. Note that
// TestViewsDelegate::use_transparent_windows_ determines the result of
// kInferOpacity: assume it is false.
bool should_be_transparent =
opacity_ == Widget::InitParams::WindowOpacity::kTranslucent;
#else
bool should_be_transparent = widget->ShouldWindowContentsBeTransparent();
#endif
EXPECT_EQ(IsNativeWindowTransparent(widget->GetNativeWindow()),
should_be_transparent);
if (CanHaveCompositingManager()) {
if (HasCompositingManager() && ExpectWidgetTransparency(opacity))
EXPECT_TRUE(widget->IsTranslucentWindowOpacitySupported());
else
EXPECT_FALSE(widget->IsTranslucentWindowOpacitySupported());
}
}
}
protected:
const std::vector<Widget::InitParams::Type> widget_types_;
Widget::InitParams::WindowOpacity opacity_ =
Widget::InitParams::WindowOpacity::kInferred;
};
} // namespace
// Only test manually set opacity via kOpaque or kTranslucent. kInferred is
// unpredictable and depends on the platform and window type.
TEST_F(CompositingWidgetTest, Transparency_DesktopWidgetOpaque) {
CheckAllWidgetsForOpacity(Widget::InitParams::WindowOpacity::kOpaque);
}
TEST_F(CompositingWidgetTest, Transparency_DesktopWidgetTranslucent) {
CheckAllWidgetsForOpacity(Widget::InitParams::WindowOpacity::kTranslucent);
}
#endif // BUILDFLAG(ENABLE_DESKTOP_AURA) || BUILDFLAG(IS_MAC)
} // namespace views::test
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/widget_unittest.cc | C++ | unknown | 206,338 |
// 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/widget/widget_utils.h"
#include <utility>
#include "ui/views/widget/widget.h"
#if defined(USE_AURA)
#include "ui/aura/window.h"
#endif
namespace views {
WidgetOpenTimer::WidgetOpenTimer(Callback callback)
: callback_(std::move(callback)) {}
WidgetOpenTimer::~WidgetOpenTimer() = default;
void WidgetOpenTimer::OnWidgetDestroying(Widget* widget) {
DCHECK(open_timer_.has_value());
DCHECK(observed_widget_.IsObservingSource(widget));
callback_.Run(open_timer_->Elapsed());
open_timer_.reset();
observed_widget_.Reset();
}
void WidgetOpenTimer::Reset(Widget* widget) {
DCHECK(!open_timer_.has_value());
DCHECK(!observed_widget_.IsObservingSource(widget));
observed_widget_.Observe(widget);
open_timer_ = base::ElapsedTimer();
}
gfx::NativeWindow GetRootWindow(const Widget* widget) {
gfx::NativeWindow window = widget->GetNativeWindow();
#if defined(USE_AURA)
window = window->GetRootWindow();
#endif
return window;
}
} // namespace views
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/widget_utils.cc | C++ | unknown | 1,138 |
// 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_WIDGET_WIDGET_UTILS_H_
#define UI_VIEWS_WIDGET_WIDGET_UTILS_H_
#include "base/functional/callback.h"
#include "base/scoped_observation.h"
#include "base/time/time.h"
#include "base/timer/elapsed_timer.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/views_export.h"
#include "ui/views/widget/widget.h"
#include "ui/views/widget/widget_observer.h"
namespace views {
class Widget;
class VIEWS_EXPORT WidgetOpenTimer : public WidgetObserver {
public:
using Callback = base::RepeatingCallback<void(base::TimeDelta)>;
explicit WidgetOpenTimer(Callback callback);
WidgetOpenTimer(const WidgetOpenTimer&) = delete;
const WidgetOpenTimer& operator=(const WidgetOpenTimer&) = delete;
~WidgetOpenTimer() override;
// WidgetObserver:
void OnWidgetDestroying(Widget* widget) override;
// Called to start the |open_timer_|.
void Reset(Widget* widget);
private:
// Callback run when the passed in Widget is destroyed.
Callback callback_;
// Time the bubble has been open. Used for UMA metrics collection.
absl::optional<base::ElapsedTimer> open_timer_;
base::ScopedObservation<Widget, WidgetObserver> observed_widget_{this};
};
// Returns the root window for |widget|. On non-Aura, this is equivalent to
// widget->GetNativeWindow().
VIEWS_EXPORT gfx::NativeWindow GetRootWindow(const Widget* widget);
} // namespace views
#endif // UI_VIEWS_WIDGET_WIDGET_UTILS_H_
| Zhao-PengFei35/chromium_src_4 | ui/views/widget/widget_utils.h | C++ | unknown | 1,570 |